Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat(gui): show peer talk and Stop on working sub-agents

Rach Pradhan89dbb9975927
diff --git a/apps/native/app/api/agents/route.ts b/apps/native/app/api/agents/route.ts
index cf51728c..a615980b 100644
--- a/apps/native/app/api/agents/route.ts
+++ b/apps/native/app/api/agents/route.ts
@@ -13,12 +13,12 @@ export async function POST(req: Request) {
const body = await req.json();
const resolved = resolveRoot(typeof body.root === 'string' ? body.root : undefined);
if ('error' in resolved) return Response.json({ error: resolved.error }, { status: resolved.status });
- if (!['list', 'send', 'children', 'activity'].includes(body.action)) return Response.json({ error: 'Unknown agents action' }, { status: 400 });
+ if (!['list', 'send', 'children', 'activity', 'cancel'].includes(body.action)) return Response.json({ error: 'Unknown agents action' }, { status: 400 });
if (body.action === 'send' && (typeof body.text !== 'string' || body.text.length > 8192)) return Response.json({ error: 'Message too large' }, { status: 400 });
const built = path.resolve(process.cwd(), '../../zig-out/bin/graff');
const binary = process.env.GRAFF_BIN || (existsSync(built) ? built : 'graff');
const result = await observeAgents(binary, resolved.root, { action: body.action, scope: body.scope === 'device' ? 'device' : 'workspace',
- ...(body.action === 'children' || body.action === 'activity' ? { target: body.target, startId: body.startId, child: body.child } : {}),
+ ...(body.action === 'children' || body.action === 'activity' || body.action === 'cancel' ? { target: body.target, startId: body.startId, child: body.child } : {}),
...(body.action === 'send' ? { target: body.target, startId: body.startId, text: body.text, kind: body.kind } : {}) });
if (body.action === 'list') (result as AgentSnapshot).agents = await sample(result.agents);
return Response.json(result, { headers: { 'cache-control': 'no-store' } });
diff --git a/apps/native/app/visual-tests/agents/fixture.tsx b/apps/native/app/visual-tests/agents/fixture.tsx
index 36ff9937..f6c12e37 100644
--- a/apps/native/app/visual-tests/agents/fixture.tsx
+++ b/apps/native/app/visual-tests/agents/fixture.tsx
@@ -5,12 +5,14 @@ import { applyAppearance, type Appearance } from '@/lib/appearance';
export default function Fixture() {
const [scenario, setScenario] = useState('connected');
const [sent, setSent] = useState('');
+ const [cancelled, setCancelled] = useState('');
const scenarioRef = useRef(scenario);
scenarioRef.current = scenario;
const request = useCallback(async (_root: string | undefined, params: Record<string, unknown>) => {
const scenario = scenarioRef.current;
if (scenario === 'error') throw new Error('Observer unavailable');
if (params.action === 'send') { setSent(JSON.stringify(params)); return { delivery: 'queued' }; }
+ if (params.action === 'cancel') { setCancelled(JSON.stringify(params)); return { status: 'interrupted' }; }
if (params.action === 'children') return {children: [
{id:'child-working', label:'Inspect navigation', task:'Check keyboard focus', status:'working', updatedAt:1, truncated:false},
{id:'child-completed', label:'Review complete', task:'Review the changes', status:'completed', updatedAt:2, truncated:true},
@@ -35,6 +37,6 @@ export default function Fixture() {
}, []);
return <main className="flex h-screen flex-col bg-page text-ink">
<nav className="flex gap-3 p-3">{['connected', 'idle', 'empty', 'error'].map(value => <button key={value} data-agent-case={value} onClick={() => setScenario(value)}>{value}</button>)}{['light', 'dark', 'codegraff'].map(theme => <button key={theme} data-agent-theme={theme} onClick={() => applyAppearance(theme as Appearance)}>{theme}</button>)}</nav>
- <div className="flex min-h-0 flex-1 gap-3 p-3"><div className="flex-1 min-w-0 p-5"><h1>Workspace conversation</h1><p>The agent panel keeps coordination alongside your work.</p><output data-agent-sent className="break-all">{sent}</output></div><AgentsPane root="/demo/workspace" onClose={() => {}} request={request} /></div>
+ <div className="flex min-h-0 flex-1 gap-3 p-3"><div className="flex-1 min-w-0 p-5"><h1>Workspace conversation</h1><p>The agent panel keeps coordination alongside your work.</p><output data-agent-sent className="break-all">{sent}</output><output data-agent-cancelled className="break-all">{cancelled}</output></div><AgentsPane root="/demo/workspace" onClose={() => {}} request={request} /></div>
</main>;
}
diff --git a/apps/native/components/site/AgentsPane.tsx b/apps/native/components/site/AgentsPane.tsx
index 8d996fa8..c8bc2f88 100644
--- a/apps/native/components/site/AgentsPane.tsx
+++ b/apps/native/components/site/AgentsPane.tsx
@@ -1,9 +1,17 @@
'use client';
import { useEffect, useRef, useState } from 'react';
-import { agentKey, agentName, agentRequest, type AgentSnapshot, type LocalAgent } from '@/lib/agents';
+import { agentKey, agentName, agentRequest, type AgentSnapshot, type LocalAgent, type PeerMessage } from '@/lib/agents';
import ResizableReviewPane from './ResizableReviewPane';
import SubagentActivity from './SubagentActivity';
+
+function talkLine(message: PeerMessage, name: (session: string) => string) {
+ return <article className="rounded-xl border border-line p-3">
+ <div className="flex items-center gap-2 text-[11px] text-ink-3"><span className="min-w-0 flex-1 truncate">{message.from_user ? 'You' : name(message.from_session)} → {name(message.to)}</span><time>{new Date(message.ts_ms).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</time></div>
+ {message.kind === 'handoff' && <span className="text-xs text-accent">Handoff request</span>}<p className="mt-2 whitespace-pre-wrap break-words text-sm">{message.text}</p>
+ </article>;
+}
+
export default function AgentsPane({ root, onClose, request = agentRequest }: { root?: string; onClose(): void; request?: typeof agentRequest }) {
const [scope, setScope] = useState('workspace');
const [showIdle, setShowIdle] = useState(false);
@@ -67,14 +75,15 @@ export default function AgentsPane({ root, onClose, request = agentRequest }: {
{!selected && <ul className="space-y-2">{agents.map(agent => <li key={agentKey(agent)}><button onClick={() => choose(agent)} aria-pressed={false} className="w-full rounded-xl border border-line p-3 text-left hover:bg-hover">
<span className="flex items-center gap-2"><span className="min-w-0 flex-1 truncate text-sm font-medium">{agentName(agent)}</span><span className="text-xs text-ink-3">{agent.status === 'working' ? 'Working' : agent.status === 'waiting' ? 'Waiting' : 'Connected'}</span></span>
<span className="mt-1 block text-xs text-ink-2 break-words">{agent.task || 'No task published'}</span>
+ {snapshot?.messages.filter(m => m.to === agent.session || m.from_session === agent.session).slice(-1).map(m => <span key={m.ts_ms} className="mt-2 block truncate text-xs text-ink-3">{m.from_user ? 'You' : name(m.from_session)} → {name(m.to)}: {m.text}</span>)}
{scope === 'device' && <span title={agent.workspace} className="mt-1 block truncate text-xs text-ink-3">{agent.workspace}</span>}
<span title="Graff process only; shared workers and GPU are not attributed" className="mt-2 block text-[11px] text-ink-3 tabular-nums">{agent.resources ? `${agent.resources.rssMiB.toFixed(1)} MiB · ${agent.resources.cpuPercent === null ? 'CPU sampling…' : `${agent.resources.cpuPercent.toFixed(1)}% CPU`}` : 'Resource measurements unavailable'}</span>
</button></li>)}</ul>}
- {selected && <><div className="flex min-w-0 items-center gap-3 text-xs"><button aria-label="Back to all agents" className="shrink-0 rounded-lg px-2 py-1 hover:bg-hover" onClick={() => setRecipient(null)}>← Agents</button><strong className="truncate">{agentName(selected)}</strong></div><SubagentActivity key={agentKey(selected)} root={root} parent={selected} scope={scope} request={request} /></>}
- {!selected && !!snapshot?.messages.length && <details aria-label="Peer messages" className="space-y-3"><summary className="cursor-pointer text-xs font-medium text-ink-3">Coordination history</summary>{snapshot.messages.map((message, i) => <article key={`${message.ts_ms}:${i}`} className="rounded-xl border border-line p-3">
- <div className="flex items-center gap-2 text-[11px] text-ink-3"><span className="min-w-0 flex-1 truncate">{message.from_user ? 'You' : name(message.from_session)} → {name(message.to)}</span><time>{new Date(message.ts_ms).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}</time></div>
- {message.kind === 'handoff' && <span className="text-xs text-accent">Handoff request</span>}<p className="mt-2 whitespace-pre-wrap break-words text-sm">{message.text}</p>
- </article>)}</details>}
+ {selected && <><div className="flex min-w-0 items-center gap-3 text-xs"><button aria-label="Back to all agents" className="shrink-0 rounded-lg px-2 py-1 hover:bg-hover" onClick={() => setRecipient(null)}>← Agents</button><strong className="truncate">{agentName(selected)}</strong></div>
+ {!!snapshot?.messages.filter(m => m.to === selected.session || m.from_session === selected.session).length && <section aria-label="Recent coordination" className="space-y-2"><h3 className="text-xs font-medium text-ink-2">How they talk</h3>{snapshot.messages.filter(m => m.to === selected.session || m.from_session === selected.session).slice(-8).map((message, i) => <div key={`${message.ts_ms}:${i}`}>{talkLine(message, name)}</div>)}</section>}
+ <SubagentActivity key={agentKey(selected)} root={root} parent={selected} scope={scope} request={request} /></>}
+ {!selected && !!snapshot?.messages.length && <section aria-label="Recent coordination" className="space-y-2"><h3 className="text-xs font-medium text-ink-2">How they talk</h3>{snapshot.messages.slice(-8).map((message, i) => <div key={`${message.ts_ms}:${i}`}>{talkLine(message, name)}</div>)}</section>}
+ {!selected && !!snapshot?.messages.length && <details aria-label="Peer messages" className="space-y-3"><summary className="cursor-pointer text-xs font-medium text-ink-3">Coordination history</summary>{snapshot.messages.map((message, i) => <div key={`${message.ts_ms}:${i}`}>{talkLine(message, name)}</div>)}</details>}
</div>
{selected && <button className="shrink-0 border-t border-line px-4 py-3 text-left text-xs hover:bg-hover" aria-expanded={composing} onClick={() => setComposing(value => !value)}>{composing ? 'Hide message composer' : 'Message this Graff…'}</button>}
{(!selected || composing) && <form className="space-y-2 border-t border-line p-3" onSubmit={e => { e.preventDefault(); void submit(); }}>
diff --git a/apps/native/components/site/SubagentActivity.tsx b/apps/native/components/site/SubagentActivity.tsx
index 508e8349..469d5c16 100644
--- a/apps/native/components/site/SubagentActivity.tsx
+++ b/apps/native/components/site/SubagentActivity.tsx
@@ -13,6 +13,7 @@ export default function SubagentActivity({root, parent, scope, request}: {root?:
const [loaded, setLoaded] = useState(false);
const [refresh, setRefresh] = useState(0);
const [limited, setLimited] = useState(false);
+ const [stopping, setStopping] = useState(false);
const key = agentKey(parent);
useEffect(() => {
let disposed = false, timer: ReturnType<typeof setTimeout>;
@@ -64,6 +65,16 @@ export default function SubagentActivity({root, parent, scope, request}: {root?:
return {...value, tools:value.tools.map(tool => ({...tool, startedAt:undefined, elapsedMs:undefined}))};
}, [activity, selected]);
const visibleChildren = children.filter(child => showFinished || child.status !== 'completed');
+ const stop = async (id: string) => {
+ if (!id || stopping) return;
+ setStopping(true);
+ try {
+ await request(root, {action:'cancel', scope, target:parent.session, startId:parent.startId, child:id});
+ setSelected(id);
+ setRetry(n => n + 1);
+ } catch (e) { setDetailError(e instanceof Error ? e.message : 'Could not interrupt this sub-agent'); }
+ finally { setStopping(false); }
+ };
return <section aria-label="Sub-agents" className="space-y-3 rounded-xl border border-line p-3">
<h3 className="text-sm font-medium">Sub-agents</h3>
<label className="flex items-center gap-2 text-xs text-ink-3"><input type="checkbox" checked={showFinished} onChange={e => setShowFinished(e.target.checked)} />Show completed sub-agents</label>
@@ -72,13 +83,16 @@ export default function SubagentActivity({root, parent, scope, request}: {root?:
: !loaded ? <p role="status" className="text-xs text-ink-3">Finding sub-agents…</p>
: !children.length ? <p className="text-xs text-ink-3">No sub-agent activity published by this session yet. Older Graff binaries do not publish this feed.</p> : null}
{selected ? <select aria-label="Select sub-agent" className="w-full min-w-0 rounded-lg bg-hover p-2 text-xs text-ink" value={selected} onChange={e => setSelected(e.target.value)}>{!visibleChildren.some(child => child.id === selected) && <option value={selected}>{children.find(child => child.id === selected)?.label || 'Selected sub-agent'}</option>}{visibleChildren.map(child => <option key={child.id} value={child.id}>{child.label || 'Sub-agent'} · {child.status}</option>)}</select>
- : <div className="max-h-48 space-y-1 overflow-y-auto">{visibleChildren.map(child => <button key={child.id} data-child-agent={child.id} onClick={() => setSelected(child.id)} className="w-full rounded-lg p-2 text-left text-xs hover:bg-hover">
+ : <div className="max-h-48 space-y-1 overflow-y-auto">{visibleChildren.map(child => <div key={child.id} className="flex items-start gap-1">
+ <button data-child-agent={child.id} onClick={() => setSelected(child.id)} className="min-w-0 flex-1 rounded-lg p-2 text-left text-xs hover:bg-hover">
<span className="flex items-center gap-2"><span className="min-w-0 flex-1 truncate font-medium">{child.label || 'Sub-agent'}</span><span className="text-ink-3">{child.status === 'working' ? 'Working' : child.status === 'completed' ? 'Completed' : 'Failed'}</span></span>
<span className="mt-1 block truncate text-ink-3" title={child.task}>{child.task}</span>
- </button>)}</div>}
+ </button>
+ {child.status === 'working' && <button type="button" aria-label="Stop sub-agent" disabled={stopping} onClick={() => void stop(child.id)} className="mt-1 shrink-0 rounded-lg px-2 py-1 text-xs text-ink-2 hover:bg-hover disabled:opacity-40">Stop</button>}
+ </div>)}</div>}
{limited && <p className="text-xs text-ink-3">Showing the most recent sub-agents.</p>}
{selected && <section aria-label="Sub-agent activity" className="border-t border-line pt-3">
- <div className="mb-3 flex items-center gap-2 text-xs"><strong className="min-w-0 flex-1 truncate">{activity?.agent.label || children.find(c => c.id === selected)?.label || 'Activity'}</strong><span role="status" className="text-ink-3">{detailError ? 'Updates unavailable' : activity?.agent.status === 'working' ? 'Live' : activity ? activity.agent.status === 'completed' ? 'Completed' : 'Failed' : 'Loading…'}</span><button aria-label="Close sub-agent activity" onClick={() => setSelected(null)}>×</button></div>
+ <div className="mb-3 flex items-center gap-2 text-xs"><strong className="min-w-0 flex-1 truncate">{activity?.agent.label || children.find(c => c.id === selected)?.label || 'Activity'}</strong><span role="status" className="text-ink-3">{detailError ? 'Updates unavailable' : activity?.agent.status === 'working' ? 'Live' : activity ? activity.agent.status === 'completed' ? 'Completed' : 'Failed' : 'Loading…'}</span>{activity?.agent.status === 'working' && <button type="button" aria-label="Stop sub-agent" disabled={stopping} onClick={() => void stop(selected)} className="rounded-lg px-2 py-1 text-ink-2 hover:bg-hover disabled:opacity-40">{stopping ? 'Stopping…' : 'Stop'}</button>}<button aria-label="Close sub-agent activity" onClick={() => setSelected(null)}>×</button></div>
{detailError && <p role="alert" className="mb-3 text-xs text-ink-2">{detailError} <button className="underline" onClick={() => setRetry(n => n + 1)}>Retry</button></p>}
{activity?.agent.truncated && <p className="mb-3 text-xs text-ink-3">Recent activity only. Older events or large outputs were shortened.</p>}
<div className="max-h-[50vh] overflow-y-auto overscroll-contain [overflow-wrap:anywhere]">{turn && <AssistantBody key={selected} turn={turn} following={false} reasoningLabel="Reported reasoning" />}</div>
diff --git a/apps/native/electron/agents-visual.cjs b/apps/native/electron/agents-visual.cjs
index 3512787c..7f717a0d 100644
--- a/apps/native/electron/agents-visual.cjs
+++ b/apps/native/electron/agents-visual.cjs
@@ -10,6 +10,8 @@ async function runAgentVisuals({ win, origin, output }) {
await win.loadURL(`${origin}/visual-tests/agents`);
await wait(`document.body.textContent.includes('Implement navigation')`);
assert.equal(await js(`document.querySelector('button[type="submit"]').disabled`), true);
+ assert.equal(await js(`document.querySelector('[aria-label="Recent coordination"] h3')?.textContent`), 'How they talk');
+ assert.ok(await js(`document.querySelector('[aria-label="Recent coordination"]').textContent.includes('The navigation update is ready for review.')`));
for (const theme of ['light', 'dark', 'codegraff']) {
await js(`document.querySelector('[data-agent-theme="${theme}"]').click()`);
await js('document.fonts.ready.then(()=>true)');
@@ -25,6 +27,10 @@ async function runAgentVisuals({ win, origin, output }) {
await js(`document.querySelector('li button').click()`);
await selectChild('child-working');
await wait(`document.querySelector('[aria-label="Sub-agent activity"]')?.textContent.includes('Live')`);
+ assert.equal(await js(`document.querySelector('[aria-label="Stop sub-agent"]')?.textContent`), 'Stop');
+ await js(`document.querySelector('[aria-label="Stop sub-agent"]').click()`);
+ await wait(`document.querySelector('[data-agent-cancelled]')?.textContent.includes('child-working')`);
+ assert.equal(await js(`document.querySelector('[data-agent-sent]').textContent`), '', 'Stop must interrupt, not send a peer message');
await js(`document.querySelector('[data-agent-case="idle"]').click()`);
await new Promise(resolve => setTimeout(resolve, 5500));
assert.equal(await js(`document.querySelector('[aria-label="Sub-agent activity"] strong')?.textContent`), 'Inspect navigation', 'Inspection survives the parent becoming idle');
@@ -51,6 +57,7 @@ async function runAgentVisuals({ win, origin, output }) {
assert.equal(await js(`document.querySelector('[data-tool-summary]')?.getAttribute('aria-expanded')`), 'false');
await selectChild('child-completed');
await wait(`document.querySelector('[aria-label="Sub-agent activity"]')?.textContent.includes('The focus order is correct.')`);
+ assert.equal(await js(`document.querySelector('[aria-label="Stop sub-agent"]')`), null, 'Completed children cannot be interrupted');
await js(`document.querySelector('[data-tool-summary]').click()`);
await wait(`document.querySelector('[aria-label="Sub-agent activity"]')?.textContent.includes('navigation.ts')`);
await js(`document.querySelector('[data-tool-row]').click()`);
diff --git a/docs/adr/0094-subagent-interrupt-is-a-cancel-file.md b/docs/adr/0094-subagent-interrupt-is-a-cancel-file.md
new file mode 100644
index 00000000..dd9e7eae
--- /dev/null
+++ b/docs/adr/0094-subagent-interrupt-is-a-cancel-file.md
@@ -0,0 +1,24 @@
+# 0094. Sub-agent interrupt is a cancel file, not session/cancel
+
+Status: accepted
+
+## Context
+
+The GUI inspects children through a dedicated observer process (ADR 0082).
+That observer cannot set the live `Agent.esc_cancel` flag, and `session/cancel`
+would stop the parent turn. There is still no cheap mid-request abort of an
+in-flight child (see `agentJobsReap`).
+
+## Decision
+
+`graff/agents` action `cancel` writes `{id}.cancel` in the parent's activity
+directory after the same parent/workspace checks as `activity`. The child
+honors the file at start, on the next activity emit, and at `finish` — even
+if the model later returns a report, the snapshot is failed/`Interrupted.`.
+
+The GUI Stop control uses this action. It does not send a peer message.
+
+## Consequences
+
+Stop is cross-process and parent-safe. An in-flight HTTP body may finish
+before the next emit; the published status is still interrupted.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index b1772cbc..d08b5ce8 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -104,6 +104,7 @@ record only when you need the evidence or the edge cases.
| [0091](0091-persistent-jobs-honor-wait-ms.md) | Persistent `run_in_background` jobs honor `wait_ms` as a timeout; finite jobs still wait until exit (ADR 0010). |
| [0092](0092-codedb-context-is-local-first.md) | Bare `codedb context` is `--local`; `--hybrid` / `--semantic` are opt-in remote rerank (and still refused under ADR 0084 policy). |
| [0093](0093-project-layout-breadth-and-directory-hints.md) | Project layout favors breadth under its caps; missing directories offer bounded sibling hints without changing confinement or ADR 0090 constraint policy. |
+| [0094](0094-subagent-interrupt-is-a-cancel-file.md) | GUI Stop writes `{id}.cancel` in the activity dir; the child finishes failed even if the model returns. Not `session/cancel`. |
## When to write one
diff --git a/src/acp_agent_activity.zig b/src/acp_agent_activity.zig
index e3631b70..39a32562 100644
--- a/src/acp_agent_activity.zig
+++ b/src/acp_agent_activity.zig
@@ -65,6 +65,20 @@ pub fn handle(a: A, io: Io, registry: Io.Dir, out: *Io.Writer, req: proto.Reques
try proto.writeError(out, req.id, -32602, "Invalid sub-agent identifier");
return;
}
+ const action = blk: {
+ const p = req.params orelse break :blk "";
+ if (p != .object) break :blk "";
+ const v = p.object.get("action") orelse break :blk "";
+ break :blk if (v == .string) v.string else "";
+ };
+ if (std.mem.eql(u8, action, "cancel")) {
+ activity.requestInterrupt(io, dir, child) catch {
+ try proto.writeError(out, req.id, -32001, "Sub-agent could not be interrupted");
+ return;
+ };
+ try proto.writeResult(out, req.id, .{ .status = "interrupted" });
+ return;
+ }
const name = try std.fmt.allocPrint(a, "{s}.json", .{child});
const bytes = dir.readFileAlloc(io, name, a, .limited(activity.file_limit)) catch {
try proto.writeError(out, req.id, -32001, "Sub-agent activity is no longer available");
@@ -130,6 +144,8 @@ test "child inspection verifies parent identity scope and child without consumin
.{ "activity", "workspace", self.start_id, "child-a", "Parent session changed", "!First child result" },
.{ "activity", "device", @as(u64, 0), "child-a", "Parent session changed", "!First child result" },
.{ "activity", "device", self.start_id, "../child-a", "Invalid sub-agent", "!First child result" },
+ .{ "cancel", "device", self.start_id, "child-a", "interrupted", "!Parent session changed" },
+ .{ "cancel", "workspace", self.start_id, "child-a", "Parent session changed", "!interrupted" },
};
inline for (cases) |case| {
const line = try std.json.Stringify.valueAlloc(a, .{ .id = 1, .method = "graff/agents", .params = .{ .action = case[0], .scope = case[1], .target = "parent", .startId = try std.fmt.allocPrint(a, "{d}", .{case[2]}), .child = case[3] } }, .{});
diff --git a/src/acp_agents.zig b/src/acp_agents.zig
index 69199508..4c773a61 100644
--- a/src/acp_agents.zig
+++ b/src/acp_agents.zig
@@ -57,15 +57,15 @@ pub fn handle(a: A, io: Io, home: []const u8, out: *Io.Writer, req: proto.Reques
defer dir.close(io);
const all = presence.listPeersBounded(io, a, dir, 128);
const action = field(req.params, "action");
- if (std.mem.eql(u8, action, "children") or std.mem.eql(u8, action, "activity")) {
+ if (std.mem.eql(u8, action, "children") or std.mem.eql(u8, action, "activity") or std.mem.eql(u8, action, "cancel")) {
const target = field(req.params, "target");
const start = std.fmt.parseInt(u64, field(req.params, "startId"), 10) catch 0;
const device = std.mem.eql(u8, field(req.params, "scope"), "device");
for (all.records, all.probes) |owner, probe| {
if (!verified(owner, probe) or owner.start_id != start or !std.mem.eql(u8, target, owner.session_id)) continue;
if (!device and !std.mem.eql(u8, root, owner.identity)) continue;
- const child = if (std.mem.eql(u8, action, "activity")) field(req.params, "child") else "";
- if (std.mem.eql(u8, action, "activity") and child.len == 0) break;
+ const child = if (std.mem.eql(u8, action, "activity") or std.mem.eql(u8, action, "cancel")) field(req.params, "child") else "";
+ if ((std.mem.eql(u8, action, "activity") or std.mem.eql(u8, action, "cancel")) and child.len == 0) break;
try @import("acp_agent_activity.zig").handle(a, io, dir, out, req, owner.pid, owner.start_id, child);
return true;
}
diff --git a/src/subagent_activity.zig b/src/subagent_activity.zig
index 7dfffd57..756bfb7a 100644
--- a/src/subagent_activity.zig
+++ b/src/subagent_activity.zig
@@ -29,6 +29,21 @@ pub fn validId(id: []const u8) bool {
for (id) |c| if (!std.ascii.isAlphanumeric(c) and c != '-') return false;
return true;
}
+
+pub fn requestInterrupt(io: Io, dir: Io.Dir, id: []const u8) !void {
+ if (!validId(id)) return error.InvalidChildId;
+ var buf: [80]u8 = undefined;
+ const name = try std.fmt.bufPrint(&buf, "{s}.cancel", .{id});
+ var f = try dir.createFile(io, name, .{});
+ f.close(io);
+}
+
+pub fn interruptRequested(io: Io, dir: Io.Dir, id: []const u8) bool {
+ var buf: [80]u8 = undefined;
+ const name = std.fmt.bufPrint(&buf, "{s}.cancel", .{id}) catch return false;
+ _ = dir.statFile(io, name, .{}) catch return false;
+ return true;
+}
pub fn cleanup(io: Io, registry: Io.Dir, pid: i32, start_id: u64) void {
var buf: [80]u8 = undefined;
registry.deleteTree(io, directory(&buf, pid, start_id) catch return) catch {};
@@ -78,6 +93,12 @@ pub const Recorder = struct {
const self: *Recorder = @ptrCast(@alignCast(ctx));
self.mu.lockUncancelable(self.io);
defer self.mu.unlock(self.io);
+ if (interruptRequested(self.io, self.dir, self.meta.id) and std.mem.eql(u8, self.meta.status, "working")) {
+ self.meta.status = "failed";
+ self.response = "Interrupted.";
+ self.publish(true);
+ return;
+ }
const ev: Event = switch (stamped.event) {
.reasoning_delta => |v| .{ .type = "reasoning", .text = v.text },
.text_delta => |v| .{ .type = "text", .text = v.text },
@@ -132,8 +153,9 @@ pub const Recorder = struct {
pub fn finish(self: *Recorder, ok: bool, report: []const u8) void {
self.mu.lockUncancelable(self.io);
defer self.mu.unlock(self.io);
- self.meta.status = if (ok) "completed" else "failed";
- self.response = util.utf8Prefix(report, 32768);
+ const interrupted = interruptRequested(self.io, self.dir, self.meta.id);
+ self.meta.status = if (interrupted or !ok) "failed" else "completed";
+ self.response = util.utf8Prefix(if (interrupted) "Interrupted." else report, 32768);
if (self.response.len != report.len) self.meta.truncated = true;
self.publish(true);
self.prune();
@@ -182,6 +204,18 @@ pub fn start(a: A, io: Io, id: []const u8, label: []const u8, task: []const u8)
return Recorder.init(a, io, dir, id, label, task) catch null;
}
+test "cancel file marks a working child interrupted even if it later finishes" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const io = std.testing.io;
+ var r: Recorder = .{ .a = std.testing.allocator, .io = io, .dir = try tmp.dir.openDir(io, ".", .{}), .meta = .{ .id = "child", .label = "test", .task = "test" } };
+ defer r.deinit();
+ try requestInterrupt(io, r.dir, "child");
+ try std.testing.expect(interruptRequested(io, r.dir, "child"));
+ r.finish(true, "I still wrote a report.");
+ try std.testing.expectEqualStrings("failed", r.meta.status);
+}
+
test "child activity coalesces deltas and bounds retained events and text" {
var tmp = std.testing.tmpDir(.{});
defer tmp.cleanup();
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index 84743b73..f64559a7 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -318,7 +318,13 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
cards.subagentLaunchCard(arena, sub_id, sprite, label, kind, prompt);
var activity = @import("subagent_activity.zig").start(gpa, ctx.io, sub_id, label, prompt);
defer if (activity) |*recorder| recorder.deinit();
- if (activity) |*recorder| agent.sink = recorder.engineSink();
+ if (activity) |*recorder| {
+ if (@import("subagent_activity.zig").interruptRequested(ctx.io, recorder.dir, sub_id)) {
+ recorder.finish(false, "Interrupted.");
+ return .{ .output = .{ .text = try gpa.dupe(u8, "Interrupted."), .is_error = true }, .usage = .{} };
+ }
+ agent.sink = recorder.engineSink();
+ }
var wt: ?jobs.AgentWorktree = null;
var isolation_note: []const u8 = "";
@@ -344,17 +350,8 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
const wf_task = std.mem.eql(u8, kind, "workflow_task");
if (wf_task) guiEmit(ctx.io, .{ .type = "tool_call", .name = "subagent", .input = .{ .description = label }, .id = sub_id });
- // A /loop deadline on the parent reaches the child as guidance on its own
- // task prompt (goal_pacing.childTaskPrompt): same absolute deadline, minus
- // the margin the parent needs to integrate the result. No-op without one.
- //
- // #381/#383: playbook.rideBrief then prepends the live constraint +
- // learned block. THIS is the one injection point for every spawn path
- // there is — the `subagent` tool (sync and background), workflow phase
- // tasks, workflow retries, pipeline stages and the judge all funnel
- // through runSub — and it reads .graff/playbook.jsonl at assembly time,
- // never a copy held in the parent's conversation, which is exactly why a
- // compacted (or brand-new) session still carries the user's "no"s.
+ // Loop deadline + playbook.rideBrief: every spawn path (subagent, workflow,
+ // retry, judge) injects live constraints here from .graff/playbook.jsonl.
const task_prompt = playbook.rideBrief(ctx.io, arena, try goal_pacing.childTaskPrompt(arena, prompt, ctx.loop_deadline_ms, util.unixMs(ctx.io)));
try agent.messages.append(try textMessage(arena, "user", task_prompt));
defer agent.tools_used.deinit(gpa);