Skip to content

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

Python

Expose sub-agent activity through ACP and the desktop

Rach640e649c205c
diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml
index 41eab4a7..1916e94f 100644
--- a/.github/workflows/desktop.yml
+++ b/.github/workflows/desktop.yml
@@ -24,4 +24,5 @@ jobs:
- run: bun run build
- run: bun run test:projects
- run: bun run test:stress
+ - run: bun run test:agents
- run: bun build electron/updater-runtime.cjs --target=node --format=cjs --external electron --outfile /tmp/updater-runtime.cjs
diff --git a/apps/native/README.md b/apps/native/README.md
index 6657dfaa..409b0511 100644
--- a/apps/native/README.md
+++ b/apps/native/README.md
@@ -185,6 +185,31 @@ Click the workspace name to search by name **or folder path**. The current
workspace is first; full paths distinguish folders with the same name. Arrow keys
browse results, Enter selects, and Escape returns to the previous control.
+## Sub-agent activity
+
+Open **Agents**, select a connected Graff, then select one of its **Sub-agents**.
+The view shows emitted progress, tool calls and results, and completion or failure.
+Tool details stay collapsed until opened. **Message this Graff** opens the parent
+message composer separately; inspecting a child sends no instructions.
+
+Both the GUI and Graff binary must support this feed. Activity belongs to a live
+parent session and is not restored after that process exits. Large output and
+older events are bounded and marked as shortened. Resource measurements remain
+for the shared parent process. Activity text is excluded from profiler feedback.
+
+The existing `graff/agents` ACP extension accepts two read-only actions:
+
+| Action | Parameters | Result |
+|---|---|---|
+| `children` | `target`, `startId`, `scope` | Recent child metadata, availability and truncation |
+| `activity` | Same fields plus `child` | Child metadata, ACP `session/update` envelopes and final response |
+
+Use the parent identity returned by `list`; `scope` defaults to the workspace.
+The observer revalidates identity and scope, and each update carries the child
+identifier as `sessionId`. Responses are complete recent snapshots, not incremental
+patches: replace the inspected snapshot on refresh. This does not add independent
+child prompting, cancellation or session restoration.
+
## GUI regression checks
Run these from this package with Bun:
@@ -210,6 +235,8 @@ Projects, and mouse resizing in both directions. `bun run test:stress`
covers long transcripts and tool output without changing macOS
Spaces. The full `test:visual` suite additionally checks native fullscreen
transitions; the stress results explicitly report fullscreen as not run.
+`bun run test:agents` covers live, completed and failed children, tool disclosure,
+late replies after selection changes, and inspection without sending messages.
For a separate, opt-in real coding trial, run `electron/gui-coding-smoke.cjs` with
the package's Electron executable. It uses configured credentials in a disposable
diff --git a/apps/native/app/api/agents/route.ts b/apps/native/app/api/agents/route.ts
index c4f9b31f..cf51728c 100644
--- a/apps/native/app/api/agents/route.ts
+++ b/apps/native/app/api/agents/route.ts
@@ -13,11 +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'].includes(body.action)) return Response.json({ error: 'Unknown agents action' }, { status: 400 });
+ if (!['list', 'send', 'children', 'activity'].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 === '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 b21d8006..71214940 100644
--- a/apps/native/app/visual-tests/agents/fixture.tsx
+++ b/apps/native/app/visual-tests/agents/fixture.tsx
@@ -8,6 +8,23 @@ export default function Fixture() {
const request = useCallback(async (_root: string | undefined, params: Record<string, unknown>) => {
if (scenario === 'error') throw new Error('Observer unavailable');
if (params.action === 'send') { setSent(JSON.stringify(params)); return { delivery: 'queued' }; }
+ 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},
+ {id:'child-failed', label:'Interrupted worker', task:'Check failure recovery', status:'failed', updatedAt:3, truncated:false},
+ ]};
+ if (params.action === 'activity') {
+ const id = String(params.child), working = id === 'child-working', failed = id === 'child-failed';
+ // A deliberately late reply must never replace the newly selected child.
+ if (working) await new Promise(resolve => setTimeout(resolve, 350));
+ const update = (value: object) => ({jsonrpc:'2.0', method:'session/update', params:{sessionId:id, update:value}});
+ return {agent:{id, label:working ? 'Inspect navigation' : failed ? 'Interrupted worker' : 'Review complete', task:'Check the changes', status:working ? 'working' : failed ? 'failed' : 'completed', updatedAt:Date.now(), truncated:!working && !failed},
+ updates:[
+ update({sessionUpdate:'agent_thought_chunk', content:{type:'text', text:'Checking the focus boundary.'}}),
+ update({sessionUpdate:'tool_call', toolCallId:'read-1', kind:'read', title:'Read navigation.ts', rawInput:{path:'navigation.ts'}, status:'in_progress'}),
+ ...(!working ? [update({sessionUpdate:'tool_call_update', toolCallId:'read-1', status:failed ? 'failed' : 'completed', content:[{type:'content', content:{type:'text', text:'navigation result\n'.repeat(100)}}]})] : []),
+ ], response:working ? '' : failed ? 'Worker could not finish.' : 'The focus order is correct.'};
+ }
return { agents: scenario === 'empty' ? [] : [
{ session: 'peer-a', title: 'Implement navigation', startId: '11', pid: 1, task: 'Refine keyboard navigation', workspace: '/demo/workspace', status: 'working', resources: { rssMiB: 20, cpuPercent: 1.2 } },
...(params.scope === 'device' ? [{ session: 'peer-b', title: 'Review accessibility', startId: '12', pid: 2, task: 'Check focus order', workspace: '/demo/second', status: 'waiting', resources: null }] : []),
diff --git a/apps/native/components/site/AgentsPane.tsx b/apps/native/components/site/AgentsPane.tsx
index 2316f345..58de83af 100644
--- a/apps/native/components/site/AgentsPane.tsx
+++ b/apps/native/components/site/AgentsPane.tsx
@@ -2,6 +2,7 @@
import { useEffect, useRef, useState } from 'react';
import { agentKey, agentName, agentRequest, type AgentSnapshot, type LocalAgent } from '@/lib/agents';
import ResizableReviewPane from './ResizableReviewPane';
+import SubagentActivity from './SubagentActivity';
export default function AgentsPane({ root, onClose, request = agentRequest }: { root?: string; onClose(): void; request?: typeof agentRequest }) {
const [scope, setScope] = useState('workspace');
@@ -13,6 +14,8 @@ export default function AgentsPane({ root, onClose, request = agentRequest }: {
const [sending, setSending] = useState(false);
const [notice, setNotice] = useState('');
const [refresh, setRefresh] = useState(0);
+ const [composing, setComposing] = useState(false);
+ const content = useRef<HTMLDivElement>(null);
const input = useRef<HTMLTextAreaElement>(null);
useEffect(() => { setRecipient(null); setNotice(''); setText(''); }, [root]);
useEffect(() => {
@@ -34,13 +37,13 @@ export default function AgentsPane({ root, onClose, request = agentRequest }: {
const agents = snapshot?.agents ?? [];
const selected = agents.find(a => recipient && agentKey(a) === agentKey(recipient));
const name = (session: string) => agents.find(a => a.session === session)?.title || session || 'Workspace';
- const choose = (agent: LocalAgent) => { setRecipient(agent); setNotice(''); input.current?.focus(); };
+ const choose = (agent: LocalAgent) => { setRecipient(agent); setNotice(''); setComposing(false); content.current?.scrollTo({top:0}); };
const submit = async () => {
if (!selected || !text.trim() || sending) return;
setSending(true); setNotice('');
try {
await request(root, { action: 'send', target: selected.session, startId: selected.startId, text, kind });
- setText(''); setNotice('Queued · Graff will read this at its next step.'); setRefresh(n => n + 1);
+ setText(''); setNotice('Queued · Graff will read this at its next step.');
} catch (e) { setNotice(e instanceof Error ? e.message : 'Message could not be queued'); }
finally { setSending(false); }
};
@@ -50,29 +53,31 @@ export default function AgentsPane({ root, onClose, request = agentRequest }: {
<div className="flex gap-1 border-b border-line p-3" role="group" aria-label="Agent scope">
{['workspace', 'device'].map(value => <button key={value} aria-pressed={scope === value} onClick={() => { setScope(value); setRecipient(null); }} className={`rounded-lg px-3 py-2 text-xs ${scope === value ? 'bg-hover-2 text-ink' : 'text-ink-2 hover:bg-hover'}`}>{value === 'workspace' ? 'This workspace' : 'All local Graffs'}</button>)}
</div>
- <div className="min-h-0 flex-1 overflow-y-auto p-3 space-y-4">
+ <div ref={content} className="min-h-0 flex-1 overflow-y-auto p-3 space-y-4">
{error && <p role="alert" className="text-sm text-ink-2">{error} <button className="underline" onClick={() => setRefresh(n => n + 1)}>Retry</button></p>}
{!snapshot && !error && <p role="status" className="text-sm text-ink-3">Finding local Graffs…</p>}
{snapshot && !agents.length && <p className="text-sm text-ink-3">No connected Graffs {scope === 'workspace' ? 'in this workspace' : 'on this laptop'}. Start a Graff session to coordinate.</p>}
- <ul className="space-y-2">{agents.map(agent => <li key={agentKey(agent)}><button onClick={() => choose(agent)} aria-pressed={!!recipient && agentKey(recipient) === agentKey(agent)} className={`w-full rounded-xl border p-3 text-left hover:bg-hover ${recipient && agentKey(recipient) === agentKey(agent) ? 'border-accent bg-hover' : 'border-line'}`}>
+ {!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>
{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>
- {!!snapshot?.messages.length && <section aria-label="Peer messages" className="space-y-3"><h3 className="text-xs font-medium text-ink-3">Recent coordination</h3>{snapshot.messages.map((message, i) => <article key={`${message.ts_ms}:${i}`} className="rounded-xl border border-line p-3">
+ </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 && <section aria-label="Peer messages" className="space-y-3"><h3 className="text-xs font-medium text-ink-3">Recent coordination</h3>{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>)}</section>}
</div>
- <form className="space-y-2 border-t border-line p-3" onSubmit={e => { e.preventDefault(); void submit(); }}>
+ {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(); }}>
<label className="block text-xs text-ink-2">To<select aria-label="Message recipient" value={selected ? agentKey(selected) : ''} onChange={e => { setRecipient(agents.find(a => agentKey(a) === e.target.value) ?? null); setNotice(''); }} className="ml-2 max-w-[85%] rounded-lg bg-hover px-2 py-1 text-ink"><option value="">Select a Graff</option>{agents.map(a => <option key={agentKey(a)} value={agentKey(a)}>{agentName(a)}</option>)}</select></label>
{recipient && !selected && <p className="text-xs text-ink-3">Recipient is unavailable in this view. Select a connected Graff.</p>}
<textarea ref={input} aria-label="Message to Graff" value={text} onChange={e => setText(e.target.value)} maxLength={8192} rows={2} placeholder="Ask a peer, share context, or request a handoff…" className="w-full resize-y rounded-xl border border-line bg-surface p-3 text-sm outline-none focus:border-accent" />
<div className="flex items-center gap-2"><select aria-label="Coordination type" value={kind} onChange={e => setKind(e.target.value)} className="rounded-lg bg-hover p-2 text-xs"><option value="message">Message</option><option value="handoff">Handoff request</option></select><button type="submit" disabled={!selected || !text.trim() || sending || !!error} className="ml-auto rounded-lg bg-hover-2 px-3 py-2 text-sm disabled:opacity-40">{sending ? 'Queuing…' : 'Send to Graff'}</button></div>
{notice && <p role="status" className="text-xs text-ink-2">{notice}</p>}
<p title="A handoff requests coordination, without transferring ownership. Profiler exports exclude message content and peer identities." className="text-[10px] text-ink-3">Messages arrive at the recipient’s next step.</p>
- </form>
+ </form>}
</aside>
</ResizableReviewPane>;
}
diff --git a/apps/native/components/site/ChatBubbles.tsx b/apps/native/components/site/ChatBubbles.tsx
index 521ea306..bbb2102d 100644
--- a/apps/native/components/site/ChatBubbles.tsx
+++ b/apps/native/components/site/ChatBubbles.tsx
@@ -71,12 +71,14 @@ export const AssistantBody = memo(function AssistantBody({
onReview,
scroller,
following,
+ reasoningLabel,
}: {
turn: AssistantTurn;
onOpenPath?: (path: string) => void;
onReview?: () => void;
scroller?: RefObject<HTMLDivElement | null>;
following: boolean;
+ reasoningLabel?: string;
}) {
const thinking = turn.status === "thinking";
const live = thinking || turn.status === "streaming";
@@ -131,8 +133,8 @@ export const AssistantBody = memo(function AssistantBody({
<ThinkingState
variant="Reasoning"
rows={reasoningRows.length ? reasoningRows : [{ primary: "Waiting on the model…", shimmer: true }]}
- activeLabel={turn.model ? `Thinking · ${turn.model}` : "Thinking"}
- doneLabel={thoughtSecs ? `Thought for ${thoughtSecs}s` : "Thought"}
+ activeLabel={reasoningLabel ?? (turn.model ? `Thinking · ${turn.model}` : "Thinking")}
+ doneLabel={reasoningLabel ?? (thoughtSecs ? `Thought for ${thoughtSecs}s` : "Thought")}
working={thinking}
/>
)}
diff --git a/apps/native/components/site/SubagentActivity.tsx b/apps/native/components/site/SubagentActivity.tsx
new file mode 100644
index 00000000..8c3d7d0c
--- /dev/null
+++ b/apps/native/components/site/SubagentActivity.tsx
@@ -0,0 +1,84 @@
+'use client';
+import { useEffect, useMemo, useState } from 'react';
+import { agentRequest, agentKey, type LocalAgent, type ChildAgent, type ChildActivity } from '@/lib/agents';
+import { applyAcpUpdate, emptyTurn, finishAcpTurn } from '@/lib/acp';
+import { AssistantBody } from './ChatBubbles';
+
+export default function SubagentActivity({root, parent, scope, request}: {root?: string; parent: LocalAgent; scope: string; request: typeof agentRequest}) {
+ const [children, setChildren] = useState<ChildAgent[]>([]);
+ const [selected, setSelected] = useState<string | null>(null);
+ const [activity, setActivity] = useState<ChildActivity | null>(null);
+ const [error, setError] = useState('');
+ const [loaded, setLoaded] = useState(false);
+ const [refresh, setRefresh] = useState(0);
+ const [limited, setLimited] = useState(false);
+ const key = agentKey(parent);
+ useEffect(() => {
+ let disposed = false, timer: ReturnType<typeof setTimeout>;
+ const controller = new AbortController();
+ setChildren([]); setLoaded(false); setLimited(false); setError(''); setSelected(null); setActivity(null);
+ const poll = async () => {
+ try {
+ if (document.visibilityState !== 'hidden') {
+ const result = await request(root, {action:'children', scope, target:parent.session, startId:parent.startId}, controller.signal);
+ if (!disposed) { setChildren(result.children ?? []); setLimited(!!result.truncated); setLoaded(true); setError(''); }
+ }
+ } catch (e) { if (!disposed) setError(e instanceof Error ? e.message : 'Sub-agents unavailable'); }
+ finally { if (!disposed) timer = setTimeout(poll, 3000); }
+ };
+ void poll();
+ return () => { disposed = true; controller.abort(); clearTimeout(timer); };
+ }, [root, key, parent.session, parent.startId, scope, request, refresh]);
+ const [detailError, setDetailError] = useState('');
+ const [retry, setRetry] = useState(0);
+ useEffect(() => {
+ setActivity(null); setDetailError('');
+ if (!selected) return;
+ let disposed = false, timer: ReturnType<typeof setTimeout>;
+ const controller = new AbortController();
+ const poll = async () => {
+ let done = false;
+ try {
+ if (document.visibilityState !== 'hidden') {
+ const result: ChildActivity = await request(root, {action:'activity', scope, target:parent.session, startId:parent.startId, child:selected}, controller.signal);
+ if (result.agent.id !== selected) throw new Error('Sub-agent selection changed. Select it again.');
+ if (!disposed) { setActivity(result); setDetailError(''); done = result.agent.status !== 'working'; }
+ }
+ } catch (e) { if (!disposed) setDetailError(e instanceof Error ? e.message : 'Activity unavailable'); }
+ finally { if (!disposed && !done) timer = setTimeout(poll, 1000); }
+ };
+ void poll();
+ return () => { disposed = true; controller.abort(); clearTimeout(timer); };
+ }, [root, key, parent.session, parent.startId, scope, selected, request, retry]);
+ const turn = useMemo(() => {
+ if (!activity || activity.agent.id !== selected) return null;
+ let value = emptyTurn();
+ for (const line of activity.updates) if ('method' in line && line.method === 'session/update' && line.params.sessionId === activity.agent.id) value = applyAcpUpdate(value, line.params.update);
+ if (activity.agent.status !== 'working') {
+ if (activity.response && !value.text.endsWith(activity.response)) value = applyAcpUpdate(value, {sessionUpdate:'agent_message_chunk', content:{type:'text', text:`${value.text ? '\n\n' : ''}${activity.response}`}});
+ value = finishAcpTurn(value);
+ if (activity.agent.status === 'failed') value = {...value, status:'error', error:activity.response || 'Sub-agent failed.'};
+ }
+ // Snapshot replay time is not the child's execution time.
+ return {...value, tools:value.tools.map(tool => ({...tool, startedAt:undefined, elapsedMs:undefined}))};
+ }, [activity, selected]);
+ 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>
+ {error ? <p role="alert" className="text-xs text-ink-2">{error} <button className="underline" onClick={() => setRefresh(n => n + 1)}>Retry</button></p>
+ : !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)}>{!children.some(child => child.id === selected) && <option value={selected}>Selected sub-agent</option>}{children.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">{children.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">
+ <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>}
+ {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>
+ {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>
+ <p className="mt-3 text-[10px] text-ink-3">Reported progress and tool activity. Opening this view does not send instructions.</p>
+ </section>}
+ </section>;
+}
diff --git a/apps/native/electron/agents-visual.cjs b/apps/native/electron/agents-visual.cjs
index da97f67a..20cb3880 100644
--- a/apps/native/electron/agents-visual.cjs
+++ b/apps/native/electron/agents-visual.cjs
@@ -3,6 +3,7 @@ const fs = require('node:fs');
const path = require('node:path');
async function runAgentVisuals({ win, origin, output }) {
const js = source => win.webContents.executeJavaScript(source);
+ const selectChild = id => js(`(()=>{const id=${JSON.stringify(id)}, button=document.querySelector('[data-child-agent="'+id+'"]');if(button){button.click();return;}const select=document.querySelector('[aria-label="Select sub-agent"]');Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,'value').set.call(select,id);select.dispatchEvent(new Event('change',{bubbles:true}));})()`);
const wait = async source => { for (let i = 0; i < 100; i++) { if (await js(source)) return; await new Promise(r => setTimeout(r, 40)); } console.error(await js('document.body.innerText')); fs.writeFileSync(path.join(output, 'agents-failed.png'), (await win.webContents.capturePage()).toPNG()); throw Error(`Agent visual timeout: ${source}`); };
win.webContents.on('console-message', (_e, level, message) => { if (level >= 2) console.error('Agent fixture:', message); });
win.show(); win.focus();
@@ -19,7 +20,36 @@ async function runAgentVisuals({ win, origin, output }) {
await js(`document.querySelectorAll('[aria-label="Agent scope"] button')[1].click()`);
await wait(`document.body.textContent.includes('Review accessibility')`);
await js(`document.querySelectorAll('li button')[1].click()`);
- assert.equal(await js(`document.activeElement.getAttribute('aria-label')`), 'Message to Graff');
+ await wait(`document.querySelector('[data-child-agent="child-working"]')`);
+ assert.notEqual(await js(`document.activeElement.getAttribute('aria-label')`), 'Message to Graff', 'Inspection should not move focus into the send form');
+ await selectChild('child-working');
+ await wait(`document.querySelector('[aria-label="Sub-agent activity"]')?.textContent.includes('Live')`);
+ 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.')`);
+ 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()`);
+ await wait(`document.querySelector('[aria-label="Sub-agent activity"]')?.textContent.includes('navigation result')`);
+ assert.equal(await js(`document.querySelector('[data-agent-sent]').textContent`), '', 'Reading activity must not send messages');
+ assert.equal(await js(`document.querySelector('[aria-label="Sub-agent activity"]').textContent.includes('Recent activity only')`), true);
+ await js(`document.querySelector('[data-tool-row]').click()`);
+ await js(`Promise.all(document.getAnimations().filter(a=>a.effect?.getTiming().iterations!==Infinity).map(a=>a.finished.catch(()=>{}))).then(()=>true)`);
+ assert.equal(await js(`getComputedStyle(document.querySelector('[aria-label="Sub-agent activity"] article')).opacity`), '1');
+ for (const theme of ['light', 'dark', 'codegraff']) {
+ await js(`document.querySelector('[data-agent-theme="${theme}"]').click()`);
+ await js('new Promise(resolve=>requestAnimationFrame(()=>requestAnimationFrame(()=>resolve(true))))');
+ fs.writeFileSync(path.join(output, `agents-child-${theme}.png`), (await win.webContents.capturePage()).toPNG());
+ }
+ // Switch before the deliberately late working-child response arrives.
+ await selectChild('child-working');
+ await selectChild('child-failed');
+ await wait(`document.querySelector('[aria-label="Sub-agent activity"]')?.textContent.includes('Worker could not finish.')`);
+ await new Promise(resolve => setTimeout(resolve, 500));
+ assert.equal(await js(`document.querySelector('[aria-label="Sub-agent activity"] strong').textContent`), 'Interrupted worker');
+ await js(`document.querySelector('[aria-label="Close sub-agent activity"]').click()`);
+ await wait(`!document.querySelector('[aria-label="Sub-agent activity"]')`);
+ await js(`Array.from(document.querySelectorAll('button')).find(b => b.textContent === 'Message this Graff…').click()`);
await js(`(()=>{const t=document.querySelector('textarea');Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(t,'Please review this update.');t.dispatchEvent(new Event('input',{bubbles:true}));})()`);
await wait(`!document.querySelector('button[type="submit"]').disabled`);
await js(`document.querySelector('button[type="submit"]').click()`);
@@ -31,6 +61,6 @@ async function runAgentVisuals({ win, origin, output }) {
assert.equal(await js(`document.querySelector('button[type="submit"]').disabled`), true);
await js(`document.querySelector('[data-agent-case="error"]').click()`);
await wait(`document.querySelector('[role="alert"]')?.textContent.includes('Observer unavailable')`);
- console.log('Agents visual checks passed: themes, bounds, scope, targeting, queued send, disconnected recipient, error.');
+ console.log('Agents visual checks passed: themes, scope, live/completed/failed children, tool disclosure, selection races, read-only inspection, explicit send, disconnection and errors.');
}
module.exports = { runAgentVisuals };
diff --git a/apps/native/electron/visual-tests.cjs b/apps/native/electron/visual-tests.cjs
index 4ea28a00..754cef69 100644
--- a/apps/native/electron/visual-tests.cjs
+++ b/apps/native/electron/visual-tests.cjs
@@ -51,6 +51,11 @@ app.whenReady().then(async () => {
assert.deepEqual(apiRequests, [], 'Stress fixtures never call engine or model APIs');
return;
}
+ if (process.env.GRAFF_VISUAL_SUITE === 'agents') {
+ await require('./agents-visual.cjs').runAgentVisuals({ win, origin, output });
+ assert.deepEqual(apiRequests, [], 'Agent fixtures never call engine or model APIs');
+ return;
+ }
await win.loadURL(`${origin}/visual-tests`);
const js = source => win.webContents.executeJavaScript(source);
const wait = async source => { for (let i = 0; i < 100; i++) { if (await js(source)) return; await sleep(50); } throw Error(`Visual check timed out: ${source}`); };
diff --git a/apps/native/lib/acp.test.ts b/apps/native/lib/acp.test.ts
index 4be40609..fae4c058 100644
--- a/apps/native/lib/acp.test.ts
+++ b/apps/native/lib/acp.test.ts
@@ -18,6 +18,13 @@ describe("parseRpcLine", () => {
});
describe("applyAcpUpdate", () => {
+ it("keeps the file chip when a completion update omits its title and input", () => {
+ let turn = applyAcpUpdate(emptyTurn(), {sessionUpdate:'tool_call', toolCallId:'read-one', title:'read_file', kind:'read', rawInput:{path:'navigation.ts'}, status:'in_progress'});
+ turn = applyAcpUpdate(turn, {sessionUpdate:'tool_call_update', toolCallId:'read-one', status:'completed'});
+ assert.equal(turn.tools[0].name, 'Read file');
+ assert.equal(turn.tools[0].chip, 'navigation.ts');
+ assert.equal(turn.tools[0].path, 'navigation.ts');
+ });
it("streams thought then text onto a live turn", () => {
let turn = emptyTurn();
turn = applyAcpUpdate(turn, { sessionUpdate: "agent_thought_chunk", content: { type: "text", text: "look around" } });
diff --git a/apps/native/lib/acp.ts b/apps/native/lib/acp.ts
index ab07db0a..7794bf9f 100644
--- a/apps/native/lib/acp.ts
+++ b/apps/native/lib/acp.ts
@@ -181,7 +181,7 @@ function upsertTool(turn: AssistantTurn, update: Extract<AcpUpdate, { toolCallId
? fromInput
: (prev?.detail ?? []);
const mcp = mcpParts(title);
- const label = labelForKind(kind, title);
+ const label = prev && !kind ? prev.name : labelForKind(kind, title);
const command = typeof rawInput.command === "string" ? firstLine(rawInput.command) : undefined;
// A raw MCP name as chip repeated the label; show the server instead, and
// no chip at all when it would just echo the label. codedb's query lives
diff --git a/apps/native/lib/agents.ts b/apps/native/lib/agents.ts
index a86b9a85..6a42c8f1 100644
--- a/apps/native/lib/agents.ts
+++ b/apps/native/lib/agents.ts
@@ -10,3 +10,6 @@ export async function agentRequest(root: string | undefined, params: Record<stri
if (!res.ok) throw new Error(body.error || 'Agents unavailable');
return body;
}
+
+export type ChildAgent = { id: string; label: string; task: string; status: 'working' | 'completed' | 'failed'; updatedAt: number; truncated: boolean };
+export type ChildActivity = { agent: ChildAgent; updates: import('./acp').JsonRpcLine[]; response: string };
diff --git a/apps/native/package.json b/apps/native/package.json
index 46312451..20aae720 100644
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@ -19,6 +19,7 @@
"test:projects": "GRAFF_VISUAL_SUITE=projects bun scripts/test-visual.mjs",
"test:splits": "GRAFF_VISUAL_SUITE=splits bun scripts/test-visual.mjs",
"test:stress": "GRAFF_VISUAL_SUITE=stress bun scripts/test-visual.mjs",
+ "test:agents": "GRAFF_VISUAL_SUITE=agents bun scripts/test-visual.mjs",
"test:performance": "GRAFF_PERFORMANCE_TESTS=1 bun scripts/test-visual.mjs"
},
"dependencies": {
diff --git a/docs/adr/0082-subagent-activity-through-acp.md b/docs/adr/0082-subagent-activity-through-acp.md
new file mode 100644
index 00000000..5843e5eb
--- /dev/null
+++ b/docs/adr/0082-subagent-activity-through-acp.md
@@ -0,0 +1,42 @@
+# 0082. Sub-agent inspection uses a separate ACP activity feed
+
+Status: accepted
+
+## Context
+
+Sub-agents run as worker threads. Their streamed progress previously had no
+frontend sink, so opening the Agents panel could show peer sessions but not the
+work happening inside them. Sharing the parent's output writer would mix child
+text into its transcript and tie background activity to one prompt's lifetime.
+
+## Decision
+
+Each child gets an independent engine event sink. It records emitted reasoning
+text, response text, tool calls and results, followed by completion or failure.
+It never reserves parent transcript sequence numbers. Stream delivery checks
+for an injected sink independently of an output writer.
+
+The local presence registry holds atomic snapshots under the parent's PID and
+process-start identity. Unix uses owner-only permissions; Windows inherits the
+home directory's ACL, matching the other local stores. The read-only `graff/agents` actions
+`children` and `activity` revalidate the parent and workspace scope on every
+request. Activity returns standard ACP session-update envelopes keyed to the
+child identifier. Inspection neither consumes inboxes nor sends instructions.
+
+The GUI opens a focused child selector after selecting a parent Graff. It reuses
+the existing transcript and collapsed tool disclosures. Late responses from a
+previous selection are discarded. Polling pauses when the window is hidden and
+stops for completed children. Messaging remains an explicit separate action.
+
+## Consequences
+
+This is recent activity for a live parent, not a durable child session API.
+Snapshots retain at most 96 events, each with at most 2 KiB of text, and a 32 KiB
+final response. Delta publication is throttled; tool transitions and completion
+publish immediately. Only the newest 64 completed children are retained alongside
+working children. Parent retirement or dead-presence cleanup removes its feed.
+Truncation is shown explicitly. Older binaries report no available feed.
+
+Activity stays local and is excluded from profiler feedback. Worker threads
+share their parent's resource measurements; per-child RSS is not claimed.
+The view displays only progress the agent emitted, not hidden reasoning.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 11404220..21bf98e9 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -92,6 +92,7 @@ record only when you need the evidence or the edge cases.
| [0079](0079-desktop-updates-are-signed-and-user-restarted.md) | Signed desktop updates download in the background and install only on explicit restart; one process owns each profile. |
| [0080](0080-desktop-projects-are-folders.md) | Desktop projects are folders; preferences survive local UI origin changes, and new chats inherit the focused project's folder. |
| [0081](0081-desktop-split-focus-and-layout.md) | Split positions remain stable as focus changes; shared controls and draggable separators keep navigation usable. |
+| [0082](0082-subagent-activity-through-acp.md) | Sub-agents publish bounded, independent activity snapshots for read-only ACP inspection without mixing parent transcripts. |
## When to write one
diff --git a/evals/harness_behavior.jsonl b/evals/harness_behavior.jsonl
index 8ca873cc..2f1f32e8 100644
--- a/evals/harness_behavior.jsonl
+++ b/evals/harness_behavior.jsonl
@@ -69,3 +69,4 @@
{"id": "model-loop-fenced-data", "prompt": "Return the requested literal data block.", "args": ["--no-lean"], "script": [{"text": "```text\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\n```"}], "assert": [{"final_text_contains": "```text\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\nI will wait for your reply.\n```"}], "why": "#743: Legitimate fenced repetition remains intact"}
{"id": "native-read-image-same-turn", "why": "Native image reads must deliver pixels on the next model request without waiting for a second user prompt.", "prompt": "Read image.png with read_file and confirm that the image arrived.", "script": [{"tool": "bash", "arguments": {"command": "python3 -c \"import base64; open('image.png','wb').write(base64.b64decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII='))\""}}, {"tool": "read_file", "arguments": {"path": "image.png"}}, {"text": "Image received."}], "assert": [{"event": {"type": "tool_result", "name": "read_file", "is_error": false}}, {"request_contains": {"index": -1, "text": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII="}}, {"final_text_contains": "Image received."}], "controls_before_prompt": [{"type": "set_model", "provider": "lmstudio", "model": "mock-vision"}]}
{"id": "meta-tool-completion-status", "why": "A metadata tool must finish its announced GUI row even when its result body uses a separate presentation path.", "prompt": "Create one pending todo, then finish your response.", "script": [{"tool": "todo_write", "arguments": {"todos": [{"content": "Review fixture", "status": "pending"}]}}, {"text": "The pending item is ready."}], "assert": [{"event": {"type": "tool_call", "name": "todo_write", "id": "call_1"}}, {"event": {"type": "tool_call_finished", "name": "todo_write", "id": "call_1", "is_error": false}}]}
+{"id": "subagent-activity-isolated-sink", "why": "Frontendless workers must publish their streamed progress, tool identity and final report to a separate bounded activity feed without emitting child prose as parent text.", "workspace_seed": {"example.txt": "fixture content\n", "check_activity.py": "import json, pathlib\nsnapshots = [json.loads(p.read_text()) for p in pathlib.Path('.graff/live').glob('activity-*/*.json')]\nassert len(snapshots) == 1, len(snapshots)\ns = snapshots[0]\nassert s['agent']['status'] == 'completed', s['agent']\nassert s['response'] == 'Child review complete.', s['response']\nassert any(e['type'] == 'text' and 'Child is inspecting.' in e['text'] for e in s['events']), s['events']\nassert any(e['type'] == 'tool_call' and e['name'] == 'read_file' and e['text'] == 'example.txt' and e['input_key'] == 'path' for e in s['events']), s['events']\nassert any(e['type'] == 'tool_result' and 'fixture content' in e['text'] for e in s['events']), s['events']\nassert not any('Parent has finished.' in e['text'] for e in s['events'])\nprint('child-activity-verified')\n"}, "prompt": "Use one subagent to inspect example.txt, then verify its activity feed with check_activity.py.", "script": [{"tool": "subagent", "arguments": {"description": "Inspect example", "prompt": "Read example.txt and report your findings."}}, {"text": "Child is inspecting.", "tool": "read_file", "arguments": {"path": "example.txt"}}, {"text": "Child review complete."}, {"tool": "bash", "arguments": {"command": "python3 check_activity.py"}}, {"text": "Parent has finished."}], "assert": [{"event": {"type": "tool_result", "name": "bash", "text": "child-activity-verified\n"}}, {"events_at_most": {"match": {"type": "text", "text": "Child is inspecting."}, "count": 0}}, {"final_text_contains": "Parent has finished."}]}
diff --git a/src/acp_agent_activity.zig b/src/acp_agent_activity.zig
new file mode 100644
index 00000000..e3631b70
--- /dev/null
+++ b/src/acp_agent_activity.zig
@@ -0,0 +1,145 @@
+//! Read-only child inspection through graff/agents, with standard ACP updates.
+const std = @import("std");
+const Io = std.Io;
+const A = std.mem.Allocator;
+const activity = @import("subagent_activity.zig");
+const proto = @import("acp_protocol.zig");
+const stream = @import("acp_stream.zig");
+
+pub fn list(a: A, io: Io, dir: Io.Dir) ![]activity.Meta {
+ var rows: std.ArrayList(activity.Meta) = .empty;
+ var scan = dir.iterate();
+ var count: usize = 0;
+ while (try scan.next(io)) |entry| {
+ if (entry.kind != .file or !std.mem.endsWith(u8, entry.name, ".meta")) continue;
+ count += 1;
+ if (count > 256) break;
+ const bytes = dir.readFileAlloc(io, entry.name, a, .limited(16384)) catch continue;
+ const row = std.json.parseFromSliceLeaky(activity.Meta, a, bytes, .{ .ignore_unknown_fields = true }) catch continue;
+ if (activity.validId(row.id)) try rows.append(a, row);
+ }
+ std.mem.sort(activity.Meta, rows.items, {}, struct {
+ fn less(_: void, x: activity.Meta, y: activity.Meta) bool {
+ return x.updatedAt > y.updatedAt;
+ }
+ }.less);
+ return rows.items;
+}
+
+pub fn updates(a: A, snapshot: activity.Snapshot) ![]std.json.Value {
+ var rows: std.ArrayList(std.json.Value) = .empty;
+ for (snapshot.events) |event| {
+ var out: Io.Writer.Allocating = .init(a);
+ defer out.deinit();
+ const w = &out.writer;
+ if (std.mem.eql(u8, event.type, "reasoning")) {
+ try stream.writeThought(w, snapshot.agent.id, event.text);
+ } else if (std.mem.eql(u8, event.type, "text")) {
+ try stream.writeMessage(w, snapshot.agent.id, event.text);
+ } else if (std.mem.eql(u8, event.type, "tool_call")) {
+ var input: std.json.ObjectMap = .empty;
+ try input.put(a, @tagName(event.input_key), .{ .string = event.text });
+ try stream.writeToolCall(w, snapshot.agent.id, event.id, event.name, .{ .object = input });
+ } else if (std.mem.eql(u8, event.type, "tool_result")) {
+ try stream.writeToolDone(w, snapshot.agent.id, event.id, event.is_error, event.text);
+ } else continue;
+ try rows.append(a, try std.json.parseFromSliceLeaky(std.json.Value, a, w.buffered(), .{}));
+ }
+ return rows.items;
+}
+
+/// Parent identity and workspace scope have already been verified by acp_agents.
+pub fn handle(a: A, io: Io, registry: Io.Dir, out: *Io.Writer, req: proto.Request, pid: i32, start: u64, child: []const u8) !void {
+ var buf: [80]u8 = undefined;
+ var dir = registry.openDir(io, try activity.directory(&buf, pid, start), .{ .iterate = true }) catch {
+ if (child.len == 0) try proto.writeResult(out, req.id, .{ .children = &.{}, .available = false }) else try proto.writeError(out, req.id, -32001, "Sub-agent activity is unavailable; this session may use an older binary");
+ return;
+ };
+ defer dir.close(io);
+ if (child.len == 0) {
+ const children = try list(a, io, dir);
+ try proto.writeResult(out, req.id, .{ .children = children[0..@min(children.len, 128)], .available = true, .truncated = children.len > 128 });
+ return;
+ }
+ if (!activity.validId(child)) {
+ try proto.writeError(out, req.id, -32602, "Invalid sub-agent identifier");
+ 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");
+ return;
+ };
+ const snapshot = std.json.parseFromSliceLeaky(activity.Snapshot, a, bytes, .{ .ignore_unknown_fields = true }) catch {
+ try proto.writeError(out, req.id, -32001, "Sub-agent activity could not be read");
+ return;
+ };
+ if (!std.mem.eql(u8, snapshot.agent.id, child) or snapshot.events.len > activity.max_events) {
+ try proto.writeError(out, req.id, -32602, "Sub-agent snapshot does not match the selected child");
+ return;
+ }
+ try proto.writeResult(out, req.id, .{ .agent = snapshot.agent, .updates = try updates(a, snapshot), .response = snapshot.response });
+}
+
+test "child updates retain identity and reuse ACP thought tool and response shapes" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const snapshot: activity.Snapshot = .{ .agent = .{ .id = "child-a", .label = "Review", .task = "Review" }, .response = "Done", .events = &.{
+ .{ .type = "reasoning", .text = "Checking the boundary" },
+ .{ .type = "tool_call", .id = "call-1", .name = "read_file", .text = "example.ts", .input_key = .path },
+ .{ .type = "tool_result", .id = "call-1", .text = "file body" },
+ .{ .type = "text", .text = "Done" },
+ } };
+ const result = try updates(a, snapshot);
+ try std.testing.expectEqual(@as(usize, 4), result.len);
+ for (result) |row| try std.testing.expectEqualStrings("child-a", row.object.get("params").?.object.get("sessionId").?.string);
+ const update = result[1].object.get("params").?.object.get("update").?;
+ try std.testing.expectEqualStrings("call-1", update.object.get("toolCallId").?.string);
+ try std.testing.expectEqualStrings("read", update.object.get("kind").?.string);
+ try std.testing.expectEqualStrings("example.ts", update.object.get("rawInput").?.object.get("path").?.string);
+}
+
+test "child inspection verifies parent identity scope and child without consuming messages" {
+ const presence = @import("presence.zig");
+ const peers = @import("acp_agents.zig");
+ const io = std.testing.io;
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.createDirPath(io, presence.registry_subdir);
+ var live = try tmp.dir.openDir(io, presence.registry_subdir, .{});
+ defer live.close(io);
+ const self = @import("proc_identity.zig").selfRecord(io);
+ if (self.start_id == 0) return error.SkipZigTest;
+ try live.writeFile(io, .{ .sub_path = "peer.json", .data = try presence.formatRecord(a, .{ .pid = self.pid, .start_id = self.start_id, .session_id = "parent", .identity = "different-workspace" }) });
+ const home = try tmp.dir.realPathFileAlloc(io, ".", a);
+ const registry = try live.realPathFileAlloc(io, ".", a);
+ var first = try activity.Recorder.init(std.testing.allocator, io, registry, "child-a", "First child", "Inspect");
+ defer first.deinit();
+ var second = try activity.Recorder.init(std.testing.allocator, io, registry, "child-b", "Second child", "Review");
+ defer second.deinit();
+ first.finish(true, "First child result");
+ second.finish(false, "Second child failed");
+ const cases = .{
+ .{ "children", "device", self.start_id, "", "First child", "Second child" },
+ .{ "activity", "device", self.start_id, "child-a", "First child result", "!Second child failed" },
+ .{ "activity", "device", self.start_id, "child-b", "Second child failed", "!First child result" },
+ .{ "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" },
+ };
+ 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] } }, .{});
+ var out: Io.Writer.Allocating = .init(a);
+ defer out.deinit();
+ try std.testing.expect(try peers.handle(a, io, home, &out.writer, proto.parseRequest(a, line).?));
+ try std.testing.expect(std.mem.indexOf(u8, out.writer.buffered(), case[4]) != null);
+ if (case[5][0] == '!') {
+ try std.testing.expect(std.mem.indexOf(u8, out.writer.buffered(), case[5][1..]) == null);
+ } else try std.testing.expect(std.mem.indexOf(u8, out.writer.buffered(), case[5]) != null);
+ }
+ try std.testing.expectEqual(@as(usize, 0), (try peers.tail(a, io, live, presence.device_room)).len);
+}
diff --git a/src/acp_agents.zig b/src/acp_agents.zig
index c2ee6372..69199508 100644
--- a/src/acp_agents.zig
+++ b/src/acp_agents.zig
@@ -48,7 +48,7 @@ pub fn handle(a: A, io: Io, home: []const u8, out: *Io.Writer, req: proto.Reques
const root = lease.currentIdentity(a, io, a).id;
const dir_path = try std.fmt.allocPrint(a, "{s}/{s}", .{ home, presence.registry_subdir });
var dir = Io.Dir.cwd().openDir(io, dir_path, .{ .iterate = true }) catch {
- if (std.mem.eql(u8, field(req.params, "action"), "send"))
+ if (field(req.params, "action").len != 0 and !std.mem.eql(u8, field(req.params, "action"), "list"))
try proto.writeError(out, req.id, -32001, "Peer registry unavailable; start a Graff session first")
else
try proto.writeResult(out, req.id, .{ .agents = &.{}, .messages = &.{}, .delivery = "No connected Graffs" });
@@ -57,6 +57,21 @@ 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")) {
+ 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;
+ try @import("acp_agent_activity.zig").handle(a, io, dir, out, req, owner.pid, owner.start_id, child);
+ return true;
+ }
+ try proto.writeError(out, req.id, -32602, "Parent session changed or is unavailable; refresh and select it again");
+ return true;
+ }
if (std.mem.eql(u8, action, "send")) {
const target = field(req.params, "target");
const text = std.mem.trim(u8, field(req.params, "text"), " \r\n\t");
diff --git a/src/agent_stream.zig b/src/agent_stream.zig
index db2fbd96..f0ebf40e 100644
--- a/src/agent_stream.zig
+++ b/src/agent_stream.zig
@@ -438,7 +438,7 @@ pub fn stallGiveUpMessage(self: *Agent, retries: usize) ?[]const u8 {
/// typed events through the sink. Best-effort: parse failures are ignored
/// (the buffered body is parsed afterwards).
pub fn printDelta(self: *Agent, raw_line: []const u8) void {
- const no_ui = self.out == null;
+ const no_ui = self.out == null and self.sink == null;
if (no_ui and !rlm_spec.available and !(main_mod.unattended and !main_mod.json_mode)) return;
const payload = ssePayload(raw_line) orelse return;
const parsed = std.json.parseFromSlice(Value, self.gpa, payload, .{}) catch return;
diff --git a/src/agent_tools.zig b/src/agent_tools.zig
index 98ab0568..d9654d5c 100644
--- a/src/agent_tools.zig
+++ b/src/agent_tools.zig
@@ -427,7 +427,7 @@ pub fn sayToolUse(self: *Agent, call: ToolCall) !void {
/// close the announced row without duplicating the result body.
pub fn sayToolResult(self: *Agent, call: ToolCall, r: ExecResult) void {
const name = call.name;
- if (self.out == null) return; // no frontend attached: nothing to tell, as ever
+ if (self.out == null and self.sink == null) return;
const ev: engine_events.ToolOutcome = .{
.id = call.id,
.name = name,
diff --git a/src/http_client_tests.zig b/src/http_client_tests.zig
index 2fd652a1..1f3bf638 100644
--- a/src/http_client_tests.zig
+++ b/src/http_client_tests.zig
@@ -5,6 +5,11 @@ const http_client = @import("http_client.zig");
const Recovery = http_client.Recovery;
const RecoveryOutcome = http_client.RecoveryOutcome;
+test "HTTP client integration coverage" {
+ _ = @import("http_client_integration_tests.zig");
+ _ = @import("http_client_trajectory_tests.zig");
+}
+
fn recoverTask(recovery: *Recovery, client: *std.http.Client) RecoveryOutcome {
return recovery.recoverConstructionTls(client);
}
diff --git a/src/main.zig b/src/main.zig
index 2214a49c..8c385d7b 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -570,8 +570,6 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("main_test.zig");
_ = @import("http_client.zig");
_ = @import("http_client_tests.zig");
- _ = @import("http_client_integration_tests.zig");
- _ = @import("http_client_trajectory_tests.zig");
_ = @import("prompt_astra.zig");
_ = @import("agent_empty_completion.zig"); // #745: plain-final reconciliation
_ = @import("agent_model_loop.zig");
@@ -595,5 +593,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("goal_pacing.zig");
_ = @import("presence_record.zig");
_ = @import("acp_agents.zig");
+ _ = @import("subagent_activity.zig");
+ _ = @import("acp_agent_activity.zig");
_ = @import("read_image.zig");
}
diff --git a/src/presence.zig b/src/presence.zig
index 12c09b41..f2efc464 100644
--- a/src/presence.zig
+++ b/src/presence.zig
@@ -62,6 +62,7 @@ pub fn listPeersBounded(io: Io, arena: Allocator, dir: Io.Dir, limit: usize) Pee
if (live == .gone) {
// Provably dead (#413): reap on read so the registry self-cleans
// even when the owner crashed without retire().
+ @import("subagent_activity.zig").cleanup(io, d, rec.pid, rec.start_id);
d.deleteFile(io, entry.name) catch {};
continue;
}
@@ -236,6 +237,7 @@ pub fn retire(io: Io) void {
const name = g_own_name orelse return;
var dir = Io.Dir.cwd().openDir(io, dir_path, .{}) catch return;
defer dir.close(io);
+ @import("subagent_activity.zig").cleanup(io, dir, g_self.pid, g_self.start_id);
dir.deleteFile(io, name) catch {};
// The shared channel is NOT ours to delete: co-resident sessions may still be mid-drain, and its bytes are the room's history.
}
@@ -384,6 +386,10 @@ pub fn drainChannel(io: Io, arena: Allocator) []const Message {
return out.items;
}
+pub fn registryPath() ?[]const u8 {
+ return g_dir;
+}
+
pub fn ownSession() []const u8 {
return g_session;
}
diff --git a/src/subagent_activity.zig b/src/subagent_activity.zig
new file mode 100644
index 00000000..7dfffd57
--- /dev/null
+++ b/src/subagent_activity.zig
@@ -0,0 +1,267 @@
+//! Bounded child activity, independent of the parent's prompt/stdout lifetime.
+const std = @import("std");
+const Io = std.Io;
+const A = std.mem.Allocator;
+const sink = @import("engine_sink.zig");
+const util = @import("util.zig");
+const proc = @import("proc_identity.zig");
+const private_file: Io.File.Permissions = if (@import("builtin").os.tag == .windows) .default_file else .fromMode(0o600);
+const private_dir: Io.File.Permissions = if (@import("builtin").os.tag == .windows) .default_dir else .fromMode(0o700);
+pub const max_events = 96;
+pub const max_text = 2048;
+pub const file_limit = 2 * 1024 * 1024;
+pub const Meta = struct {
+ id: []const u8,
+ label: []const u8,
+ task: []const u8,
+ status: []const u8 = "working",
+ updatedAt: i64 = 0,
+ truncated: bool = false,
+};
+pub const InputKey = enum { path, file, command, url, description };
+pub const Event = struct { type: []const u8, id: []const u8 = "", name: []const u8 = "", text: []const u8 = "", is_error: bool = false, input_key: InputKey = .description };
+pub const Snapshot = struct { agent: Meta, events: []const Event, response: []const u8 };
+pub fn directory(buf: []u8, pid: i32, start_id: u64) ![]const u8 {
+ return std.fmt.bufPrint(buf, "activity-{d}-{x}", .{ pid, start_id });
+}
+pub fn validId(id: []const u8) bool {
+ if (id.len == 0 or id.len > 64) return false;
+ for (id) |c| if (!std.ascii.isAlphanumeric(c) and c != '-') 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 {};
+}
+fn writeAtomic(io: Io, a: A, dir: Io.Dir, name: []const u8, value: anytype) !void {
+ const bytes = try std.json.Stringify.valueAlloc(a, value, .{});
+ defer a.free(bytes);
+ var f = try dir.createFileAtomic(io, name, .{ .permissions = private_file, .replace = true });
+ defer f.deinit(io);
+ try f.file.writeStreamingAll(io, bytes);
+ try f.replace(io);
+}
+
+pub const Recorder = struct {
+ a: A,
+ io: Io,
+ dir: Io.Dir,
+ meta: Meta,
+ events: std.ArrayList(Event) = .empty,
+ mu: Io.Mutex = .init,
+ last_write: i64 = 0,
+ response: []const u8 = "",
+ pub fn init(a: A, io: Io, registry_path: []const u8, id: []const u8, label: []const u8, task: []const u8) !Recorder {
+ if (!validId(id)) return error.InvalidChildId;
+ var registry = try Io.Dir.cwd().openDir(io, registry_path, .{});
+ defer registry.close(io);
+ const self = proc.selfRecord(io);
+ var buf: [80]u8 = undefined;
+ const name = try directory(&buf, self.pid, self.start_id);
+ registry.createDir(io, name, private_dir) catch |err| if (err != error.PathAlreadyExists) return err;
+ const dir = try registry.openDir(io, name, .{ .iterate = true });
+ var result: Recorder = .{ .a = a, .io = io, .dir = dir, .meta = .{ .id = id, .label = util.utf8Prefix(label, 256), .task = util.utf8Prefix(task, 2048) } };
+ result.publish(true);
+ return result;
+ }
+ pub fn deinit(self: *Recorder) void {
+ if (std.mem.eql(u8, self.meta.status, "working")) self.finish(false, "Sub-agent ended before producing a report.");
+ for (self.events.items) |event| self.freeEvent(event);
+ self.events.deinit(self.a);
+ self.dir.close(self.io);
+ }
+ pub fn engineSink(self: *Recorder) sink.EngineSink {
+ return .{ .ctx = self, .vt = &vtable };
+ }
+ const vtable: sink.VTable = .{ .emit = emit, .durable = false };
+ fn emit(ctx: *anyopaque, stamped: sink.Stamped) void {
+ const self: *Recorder = @ptrCast(@alignCast(ctx));
+ self.mu.lockUncancelable(self.io);
+ defer self.mu.unlock(self.io);
+ const ev: Event = switch (stamped.event) {
+ .reasoning_delta => |v| .{ .type = "reasoning", .text = v.text },
+ .text_delta => |v| .{ .type = "text", .text = v.text },
+ .tool_call_announced => |v| .{ .type = "tool_call", .id = v.id, .name = v.name, .text = inputTitle(v.input), .input_key = inputKey(v.input) },
+ .tool_result => |v| .{ .type = "tool_result", .id = v.id, .name = v.name, .text = v.text, .is_error = v.is_error or v.cancelled },
+ .tool_rejected => |v| .{ .type = "tool_result", .id = v.id, .name = v.name, .text = v.message, .is_error = true },
+ else => return,
+ };
+ self.append(ev) catch return;
+ self.publish(std.mem.eql(u8, ev.type, "tool_call") or std.mem.eql(u8, ev.type, "tool_result"));
+ }
+ fn inputTitle(input: std.json.Value) []const u8 {
+ if (input != .object) return "";
+ return util.strFieldObj(input.object, @tagName(inputKey(input))) orelse "";
+ }
+ fn inputKey(input: std.json.Value) InputKey {
+ if (input != .object) return .description;
+ inline for (std.meta.tags(InputKey)) |key| {
+ if (util.strFieldObj(input.object, @tagName(key)) != null) return key;
+ }
+ return .description;
+ }
+ fn freeEvent(self: *Recorder, event: Event) void {
+ self.a.free(event.id);
+ self.a.free(event.name);
+ self.a.free(event.text);
+ }
+ pub fn append(self: *Recorder, ev: Event) !void {
+ const text = util.utf8Prefix(ev.text, max_text);
+ if (text.len < ev.text.len) self.meta.truncated = true;
+ if ((std.mem.eql(u8, ev.type, "text") or std.mem.eql(u8, ev.type, "reasoning")) and self.events.items.len > 0) {
+ const last = &self.events.items[self.events.items.len - 1];
+ if (std.mem.eql(u8, last.type, ev.type) and last.text.len + text.len <= max_text) {
+ const combined = try std.mem.concat(self.a, u8, &.{ last.text, text });
+ self.a.free(last.text);
+ last.text = combined;
+ return;
+ }
+ }
+ const id = try self.a.dupe(u8, util.utf8Prefix(ev.id, 128));
+ errdefer self.a.free(id);
+ const name = try self.a.dupe(u8, util.utf8Prefix(ev.name, 128));
+ errdefer self.a.free(name);
+ const owned = try self.a.dupe(u8, text);
+ errdefer self.a.free(owned);
+ if (self.events.items.len == max_events) {
+ self.freeEvent(self.events.orderedRemove(0));
+ self.meta.truncated = true;
+ }
+ try self.events.append(self.a, .{ .type = ev.type, .id = id, .name = name, .text = owned, .is_error = ev.is_error, .input_key = ev.input_key });
+ }
+ 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);
+ if (self.response.len != report.len) self.meta.truncated = true;
+ self.publish(true);
+ self.prune();
+ self.response = ""; // report belongs to the worker's arena
+ }
+ fn prune(self: *Recorder) void {
+ var arena = std.heap.ArenaAllocator.init(self.a);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var completed: std.ArrayList(Meta) = .empty;
+ var it = self.dir.iterate();
+ while (it.next(self.io) catch null) |entry| {
+ if (entry.kind != .file or !std.mem.endsWith(u8, entry.name, ".meta")) continue;
+ const bytes = self.dir.readFileAlloc(self.io, entry.name, a, .limited(16384)) catch continue;
+ const meta = std.json.parseFromSliceLeaky(Meta, a, bytes, .{}) catch continue;
+ if (!validId(meta.id) or std.mem.eql(u8, meta.status, "working")) continue;
+ completed.append(a, meta) catch return;
+ }
+ std.mem.sort(Meta, completed.items, {}, struct {
+ fn less(_: void, x: Meta, y: Meta) bool {
+ return x.updatedAt > y.updatedAt;
+ }
+ }.less);
+ for (completed.items[@min(64, completed.items.len)..]) |meta| {
+ var buf: [100]u8 = undefined;
+ self.dir.deleteFile(self.io, std.fmt.bufPrint(&buf, "{s}.meta", .{meta.id}) catch continue) catch {};
+ self.dir.deleteFile(self.io, std.fmt.bufPrint(&buf, "{s}.json", .{meta.id}) catch continue) catch {};
+ }
+ }
+ fn publish(self: *Recorder, force: bool) void {
+ const now = util.unixMs(self.io);
+ if (!force and now - self.last_write < 500) return;
+ self.meta.updatedAt = now;
+ var buf: [100]u8 = undefined;
+ const data_name = std.fmt.bufPrint(&buf, "{s}.json", .{self.meta.id}) catch return;
+ writeAtomic(self.io, self.a, self.dir, data_name, Snapshot{ .agent = self.meta, .events = self.events.items, .response = self.response }) catch return;
+ const meta_name = std.fmt.bufPrint(&buf, "{s}.meta", .{self.meta.id}) catch return;
+ writeAtomic(self.io, self.a, self.dir, meta_name, self.meta) catch return;
+ self.last_write = now;
+ }
+};
+
+/// Disabled when the parent has no local presence (including lean eval runs).
+pub fn start(a: A, io: Io, id: []const u8, label: []const u8, task: []const u8) ?Recorder {
+ const dir = @import("presence.zig").registryPath() orelse return null;
+ return Recorder.init(a, io, dir, id, label, task) catch null;
+}
+
+test "child activity coalesces deltas and bounds retained events and text" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var r: Recorder = .{ .a = std.testing.allocator, .io = std.testing.io, .dir = try tmp.dir.openDir(std.testing.io, ".", .{}), .meta = .{ .id = "child", .label = "test", .task = "test", .status = "completed" } };
+ defer r.deinit();
+ try r.append(.{ .type = "text", .text = "one" });
+ try r.append(.{ .type = "text", .text = "two" });
+ try std.testing.expectEqualStrings("onetwo", r.events.items[0].text);
+ for (0..200) |_| try r.append(.{ .type = "tool_call", .id = "call", .name = "read_file" });
+ try std.testing.expectEqual(max_events, r.events.items.len);
+ try std.testing.expect(r.meta.truncated);
+ try std.testing.expect(!validId("../elsewhere"));
+ try std.testing.expect(validId("sa-001-abc"));
+}
+
+test "frontendless child SSE reaches its own activity sink and final snapshot" {
+ const a = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const root = try tmp.dir.realPathFileAlloc(io, ".", a);
+ defer a.free(root);
+ var recorder = try Recorder.init(a, io, root, "child-one", "Review", "Check the boundary");
+ defer recorder.deinit();
+ var arena = std.heap.ArenaAllocator.init(a);
+ defer arena.deinit();
+ var agent: @import("agent.zig").Agent = .{
+ .gpa = a,
+ .arena = arena.allocator(),
+ .io = io,
+ .client = undefined,
+ .out = null,
+ .provider = .{ .id = "test", .kind = .openai, .auth = .bearer, .url = "", .api_key = "", .model = "test", .context = 0 },
+ .messages = std.json.Array.init(arena.allocator()),
+ .sub = true,
+ .label = "Review",
+ .sink = recorder.engineSink(),
+ };
+ @import("agent_stream.zig").printDelta(&agent, "data: {\"choices\":[{\"delta\":{\"reasoning_content\":\"Checking the input\",\"content\":\"I found the boundary\"}}]}");
+ try std.testing.expectEqual(@as(usize, 2), recorder.events.items.len);
+ try std.testing.expectEqualStrings("reasoning", recorder.events.items[0].type);
+ try std.testing.expectEqualStrings("text", recorder.events.items[1].type);
+ const call: @import("tools.zig").ToolCall = .{ .id = "call-one", .name = "read_file", .input = .null };
+ try @import("agent_tools.zig").sayToolUse(&agent, call);
+ @import("agent_tools.zig").sayToolResult(&agent, call, .{ .text = "contents", .is_error = false });
+ recorder.finish(true, "Review finished");
+ const bytes = try recorder.dir.readFileAlloc(io, "child-one.json", a, .limited(file_limit));
+ defer a.free(bytes);
+ const parsed = try std.json.parseFromSlice(Snapshot, a, bytes, .{});
+ defer parsed.deinit();
+ try std.testing.expectEqualStrings("completed", parsed.value.agent.status);
+ try std.testing.expectEqualStrings("Review finished", parsed.value.response);
+ try std.testing.expectEqual(@as(usize, 4), parsed.value.events.len);
+}
+
+test "child retention preserves working children and removes oldest completed snapshots" {
+ const a = std.testing.allocator;
+ const io = std.testing.io;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var r: Recorder = .{ .a = a, .io = io, .dir = try tmp.dir.openDir(io, ".", .{ .iterate = true }), .meta = .{ .id = "working", .label = "Working", .task = "Review" } };
+ defer r.deinit();
+ r.publish(true);
+ for (0..70) |i| {
+ var id_buf: [64]u8 = undefined;
+ const id = try std.fmt.bufPrint(&id_buf, "completed-{d}", .{i});
+ var file_buf: [80]u8 = undefined;
+ try writeAtomic(io, a, r.dir, try std.fmt.bufPrint(&file_buf, "{s}.meta", .{id}), Meta{ .id = id, .label = "Done", .task = "Review", .status = "completed", .updatedAt = @intCast(i) });
+ try r.dir.writeFile(io, .{ .sub_path = try std.fmt.bufPrint(&file_buf, "{s}.json", .{id}), .data = "{}" });
+ }
+ r.prune();
+ try std.testing.expectError(error.FileNotFound, r.dir.openFile(io, "completed-0.json", .{}));
+ const kept = try r.dir.openFile(io, "completed-69.json", .{});
+ kept.close(io);
+ const working = try r.dir.openFile(io, "working.json", .{});
+ working.close(io);
+ var count: usize = 0;
+ var it = r.dir.iterate();
+ while (try it.next(io)) |entry| if (std.mem.endsWith(u8, entry.name, ".meta")) {
+ count += 1;
+ };
+ try std.testing.expectEqual(@as(usize, 65), count);
+}
diff --git a/src/subagent_run.zig b/src/subagent_run.zig
index 60ba8976..1ba26834 100644
--- a/src/subagent_run.zig
+++ b/src/subagent_run.zig
@@ -316,6 +316,9 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
const sub_id = cards.subagentId(&id_buf, ordinal, label, prompt);
const sprite = cards.subagentSprite(ordinal);
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();
var wt: ?jobs.AgentWorktree = null;
var isolation_note: []const u8 = "";
@@ -355,14 +358,7 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
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);
- // Bounded in-worker re-ask. The ROOT has failover (runTurnWithFallback);
- // a worker had one shot, so a single flaky response cost a whole report
- // while its siblings on the same credential finished. subagent_retry owns
- // the ceiling and the class filter — this loop only spends them, on the
- // SAME provider (no worker cross-provider failover: see that module).
- // Resuming runTurn re-issues a request against the history as it stands,
- // so nothing already executed is replayed; a wire failure lands before any
- // assistant message is appended, which is what keeps that true.
+ // Retry transient failures against the same child history.
var attempts: u8 = 0;
const report: anyerror![]const u8 = ask: {
while (true) {
@@ -380,6 +376,7 @@ pub fn runSub(ctx: ToolCtx, kind: []const u8, label: []const u8, prompt: []const
};
const run_ms: i64 = @intCast(@max(0, sub_start.untilNow(ctx.io, .awake).toMilliseconds()));
const run_ok = if (report) |r| r.len > 0 else |_| false;
+ if (activity) |*recorder| recorder.finish(run_ok, if (report) |r| r else |_| (agent.last_api_error orelse "Sub-agent failed"));
if (wf_task) {
// The sa- id (shared with agent_usage) pairs parallel workflow rows;
// without it a consumer can only match tool_call/tool_result by order.