mirror of
https://github.com/bitbaum/loki.git
synced 2026-12-04 09:20:03 +01:00
feat(home): wire bridge.cancel end-to-end — POST /api/cancel + worker Ctrl+C + UI button
bridge.cancel was schema-only: declared in events.ts, projected by
state.ts (clears currentRun on runId match), but no producer and no
consumer. A running agent in a zellij tab could not be interrupted from
the home/ UI — user had to switch tabs and Ctrl+C manually, leaving the
brain blind to the cancellation until the next stop-hook fired.
Wired the three missing pieces:
• home/server.ts: POST /api/cancel { project, runId?, reason? }. When
runId is omitted, falls back to the live currentRun.runId. Emits a
bridge.cancel event into the log. 404 with a hint when nothing is
running. Validation matches the other endpoints.
• home/worker.ts: applyEvent now returns { dispatch?, cancel? }. A
live bridge.cancel triggers sendRawKey(project, 3) — same Ctrl+C
pattern src/app/api/control/switch-agent/route.ts uses for stuck
agents. Replay-phase cancels are historical (already happened) so
they update state but do NOT re-send Ctrl+C. A cancel also clears
the runId from pendingDispatches so crash-recovery on next boot
doesn't re-fire a dispatch the user already killed.
• home/server.ts (UI): running cards now render a Cancel button next
to the running pill; idle cards keep the Propose + Dispatch pair.
Single delegated click listener handles both via data-action attrs.
The stop-hook still emits worker.finished with whatever outcome
infer_outcome_v1 derives from session.md at shutdown time (typically
"partial" when the agent was mid-task) — we don't forge a finish event
ourselves, the natural flow catches up.
home/worker.ts self-tests: 12/12 (was 8/8) — added live-cancel-emits,
replay-cancel-no-emit, cancel-drops-pending, dispatch-after-cancel-skips.
home/state.ts: 11/11 still green. tsc clean.
This commit is contained in:
2 files changed
+161
-8
No files matched your search
+87
-5
@@ -109,6 +109,8 @@ const INDEX_HTML = `<!doctype html>
|
||||
.actions button:disabled { opacity: 0.4; cursor: not-allowed; }
|
||||
.actions button.primary { border-color: #16a34a55; color: #4ade80; }
|
||||
.actions button.primary:hover:not(:disabled) { background: #16a34a22; }
|
||||
.actions button.danger { border-color: #dc262655; color: #f87171; }
|
||||
.actions button.danger:hover:not(:disabled) { background: #dc262622; }
|
||||
.proposal { font-size: 11px; color: #a3a3a3; margin-top: 0.5rem; padding: 0.4rem 0.6rem; border-left: 2px solid #525252; background: #0f0f0f; line-height: 1.5; word-break: break-word; }
|
||||
.proposal .label { color: #71717a; text-transform: uppercase; letter-spacing: 0.05em; font-size: 10px; margin-right: 0.4rem; }
|
||||
pre { color: #525252; font-size: 11px; background: #050505; padding: 1rem; border-radius: 4px; margin-top: 2rem; overflow-x: auto; }
|
||||
@@ -175,10 +177,36 @@ async function dispatch(project, autonomy, btn) {
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
async function cancelRun(project, btn) {
|
||||
const buttons = btn.parentElement.querySelectorAll('button');
|
||||
buttons.forEach(b => b.disabled = true);
|
||||
try {
|
||||
const r = await fetch('/api/cancel', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ project, reason: 'cancelled from /control' }),
|
||||
});
|
||||
const j = await r.json();
|
||||
if (!r.ok) {
|
||||
proposals.set(project, { dispatched: false, decision: { action: { kind: 'error', intent: '', reason: j.error || ('HTTP ' + r.status) }, confidence: 0 } });
|
||||
} else {
|
||||
proposals.set(project, { dispatched: false, decision: { action: { kind: 'cancelled', intent: '', reason: 'Ctrl+C sent · runId ' + (j.runId || '').slice(0, 8) }, confidence: 0 } });
|
||||
}
|
||||
} catch (e) {
|
||||
proposals.set(project, { dispatched: false, decision: { action: { kind: 'error', intent: '', reason: String(e) }, confidence: 0 } });
|
||||
} finally {
|
||||
buttons.forEach(b => b.disabled = false);
|
||||
refresh();
|
||||
}
|
||||
}
|
||||
document.addEventListener('click', (e) => {
|
||||
const btn = e.target.closest('button[data-project][data-autonomy]');
|
||||
const btn = e.target.closest('button[data-action]');
|
||||
if (!btn) return;
|
||||
dispatch(btn.dataset.project, btn.dataset.autonomy, btn);
|
||||
if (btn.dataset.action === 'dispatch') {
|
||||
dispatch(btn.dataset.project, btn.dataset.autonomy, btn);
|
||||
} else if (btn.dataset.action === 'cancel') {
|
||||
cancelRun(btn.dataset.project, btn);
|
||||
}
|
||||
});
|
||||
async function refresh() {
|
||||
try {
|
||||
@@ -205,10 +233,12 @@ async function refresh() {
|
||||
: '';
|
||||
const projAttr = escapeHtml(p.project);
|
||||
const actions = cr
|
||||
? ''
|
||||
? '<div class="actions">' +
|
||||
'<button class="danger" data-action="cancel" data-project="' + projAttr + '">Cancel</button>' +
|
||||
'</div>'
|
||||
: '<div class="actions">' +
|
||||
'<button data-project="' + projAttr + '" data-autonomy="confirm">Propose</button>' +
|
||||
'<button class="primary" data-project="' + projAttr + '" data-autonomy="auto">Dispatch</button>' +
|
||||
'<button data-action="dispatch" data-project="' + projAttr + '" data-autonomy="confirm">Propose</button>' +
|
||||
'<button class="primary" data-action="dispatch" data-project="' + projAttr + '" data-autonomy="auto">Dispatch</button>' +
|
||||
'</div>';
|
||||
return \`
|
||||
<div class="project\${cr ? ' running' : ''}">
|
||||
@@ -309,6 +339,58 @@ const server = http.createServer((req, res) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// Cancel an in-flight run. Emits a bridge.cancel event that:
|
||||
// 1) the worker tails and turns into a Ctrl+C sent to the project's tab
|
||||
// 2) state.ts projects into "currentRun = undefined" once the runId matches
|
||||
// 3) the worker treats as a terminator so a never-started dispatch sitting
|
||||
// in pendingDispatches doesn't fire on next worker restart
|
||||
//
|
||||
// Body: { project: string, runId?: string, reason?: string }
|
||||
// If runId is omitted, the live currentRun.runId is used. 404 if there's
|
||||
// no active run for the project.
|
||||
if (url === "/api/cancel" && req.method === "POST") {
|
||||
let body = "";
|
||||
req.on("data", (chunk) => { body += String(chunk); });
|
||||
req.on("end", () => {
|
||||
try {
|
||||
const parsed = body.trim() ? JSON.parse(body) : {};
|
||||
const projectName: string | undefined = parsed.project;
|
||||
if (typeof projectName !== "string" || !projectName) {
|
||||
res.statusCode = 400;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ error: "missing 'project' string in body" }));
|
||||
return;
|
||||
}
|
||||
const liveState = state.get(projectName);
|
||||
const runId: string | undefined =
|
||||
(typeof parsed.runId === "string" && parsed.runId) || liveState?.currentRun?.runId;
|
||||
if (!runId) {
|
||||
res.statusCode = 404;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({
|
||||
error: `no active run for project: ${projectName}`,
|
||||
hint: "POST body can include a runId to cancel a specific run; otherwise the project must have a currentRun.",
|
||||
}));
|
||||
return;
|
||||
}
|
||||
const reason = (typeof parsed.reason === "string" && parsed.reason.slice(0, 200)) || "user cancel";
|
||||
appendEvent({
|
||||
kind: "bridge.cancel",
|
||||
project: projectName,
|
||||
runId,
|
||||
reason,
|
||||
});
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ ok: true, runId, reason }));
|
||||
} catch (e) {
|
||||
res.statusCode = 400;
|
||||
res.setHeader("Content-Type", "application/json");
|
||||
res.end(JSON.stringify({ error: String(e) }));
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// M6 — dispatch. Run decide() against the current state for a project and
|
||||
// either emit a bridge.dispatch event (when autonomy + confidence say "go")
|
||||
// or return the proposed action for a confirm-mode UI to render.
|
||||
|
||||
+74
-3
@@ -28,10 +28,13 @@
|
||||
|
||||
import { tailLog, type EventPhase } from "./log";
|
||||
import { appendEvent, LOG_PATH } from "./emit";
|
||||
import { injectIntoTab } from "@/lib/zellij";
|
||||
import { injectIntoTab, sendRawKey } from "@/lib/zellij";
|
||||
import { APP_NAME, APP_SLUG } from "@/config/brand";
|
||||
import type { Event } from "@/lib/events";
|
||||
|
||||
/** Linux Ctrl+C raw key code. Same value used by switch-agent for hard interrupt. */
|
||||
const CTRL_C = 3;
|
||||
|
||||
// ── State held by the worker process ────────────────────────────────────────
|
||||
|
||||
export type WorkerState = {
|
||||
@@ -55,7 +58,7 @@ export function applyEvent(
|
||||
state: WorkerState,
|
||||
event: Event,
|
||||
phase: EventPhase,
|
||||
): { dispatch?: Event } {
|
||||
): { dispatch?: Event; cancel?: Event } {
|
||||
// worker.started AND worker.crashed both terminate a runId from the
|
||||
// worker's POV — one succeeded, the other failed permanently. Either
|
||||
// way, don't re-inject. Without crashed-as-terminator, a failed
|
||||
@@ -66,6 +69,14 @@ export function applyEvent(
|
||||
state.pendingDispatches.delete(event.runId);
|
||||
return {};
|
||||
}
|
||||
// bridge.cancel ALSO terminates a runId: drop it from pendingDispatches so
|
||||
// crash-recovery on next boot doesn't re-fire a dispatch the user already
|
||||
// killed. Live cancels also signal the caller to send Ctrl+C to the tab.
|
||||
if (event.kind === "bridge.cancel") {
|
||||
state.startedRunIds.add(event.runId);
|
||||
state.pendingDispatches.delete(event.runId);
|
||||
return phase === "live" ? { cancel: event } : {};
|
||||
}
|
||||
if (event.kind !== "bridge.dispatch") return {};
|
||||
if (state.startedRunIds.has(event.runId)) return {}; // already handled
|
||||
|
||||
@@ -84,6 +95,26 @@ export function applyEvent(
|
||||
|
||||
// ── Side-effect: actually inject + emit worker.started ──────────────────────
|
||||
|
||||
/**
|
||||
* Side-effect: send Ctrl+C to the project's tab. Symmetric to executeDispatch —
|
||||
* worker is the only process that touches zellij, regardless of intent.
|
||||
*
|
||||
* The stop hook that runs when the agent shuts down will still emit a
|
||||
* worker.finished event with whatever outcome infer_outcome_v1 derives from
|
||||
* the session.md at that moment (typically "partial" when done is empty),
|
||||
* so the brain's state catches up naturally without us forging a finish here.
|
||||
*/
|
||||
function executeCancel(event: Event) {
|
||||
if (event.kind !== "bridge.cancel") return;
|
||||
try {
|
||||
sendRawKey(event.project, CTRL_C);
|
||||
console.log(`[worker] sent Ctrl+C to project=${event.project} runId=${event.runId} reason=${event.reason}`);
|
||||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : String(e);
|
||||
console.error(`[worker] cancel failed runId=${event.runId}: ${msg}`);
|
||||
}
|
||||
}
|
||||
|
||||
function executeDispatch(state: WorkerState, event: Event) {
|
||||
if (event.kind !== "bridge.dispatch") return;
|
||||
try {
|
||||
@@ -119,8 +150,9 @@ function start() {
|
||||
const handle = tailLog(
|
||||
LOG_PATH,
|
||||
(event, phase) => {
|
||||
const { dispatch } = applyEvent(state, event, phase);
|
||||
const { dispatch, cancel } = applyEvent(state, event, phase);
|
||||
if (dispatch) executeDispatch(state, dispatch);
|
||||
if (cancel) executeCancel(cancel);
|
||||
},
|
||||
(err) => console.error("[worker]", err.message),
|
||||
);
|
||||
@@ -168,6 +200,10 @@ function selfTest() {
|
||||
kind: "worker.crashed", project: "Test", runId,
|
||||
error: "inject failed: tab not found",
|
||||
});
|
||||
const cancelEvent = (runId: string): Event => ({
|
||||
v: 1, id: `cancel-${runId}`, ts: "2026-01-01T00:02:00Z",
|
||||
kind: "bridge.cancel", project: "Test", runId, reason: "user clicked Cancel",
|
||||
});
|
||||
|
||||
type Case = { name: string; run: () => boolean };
|
||||
const cases: Case[] = [
|
||||
@@ -236,6 +272,41 @@ function selfTest() {
|
||||
return r.dispatch === undefined;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "live bridge.cancel returns the event so caller sends Ctrl+C",
|
||||
run: () => {
|
||||
const s = fresh();
|
||||
applyEvent(s, startedEvent("a"), "live");
|
||||
const r = applyEvent(s, cancelEvent("a"), "live");
|
||||
return r.cancel?.kind === "bridge.cancel" && r.cancel.runId === "a";
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "replay bridge.cancel does NOT emit a Ctrl+C (history, not now)",
|
||||
run: () => {
|
||||
const s = fresh();
|
||||
const r = applyEvent(s, cancelEvent("a"), "replay");
|
||||
return r.cancel === undefined && s.startedRunIds.has("a");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "bridge.cancel during replay drops a pending dispatch (don't crash-recover a cancelled run)",
|
||||
run: () => {
|
||||
const s = fresh();
|
||||
applyEvent(s, dispatchEvent("a"), "replay");
|
||||
applyEvent(s, cancelEvent("a"), "replay");
|
||||
return s.pendingDispatches.size === 0 && s.startedRunIds.has("a");
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "live dispatch is skipped when a prior cancel already terminated the runId",
|
||||
run: () => {
|
||||
const s = fresh();
|
||||
applyEvent(s, cancelEvent("a"), "live");
|
||||
const r = applyEvent(s, dispatchEvent("a"), "live");
|
||||
return r.dispatch === undefined;
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unrelated event types are no-ops on state",
|
||||
run: () => {
|
||||
|
||||
Reference in new issue
Block a user