graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
feat(gui): workspace agents, opt-in tasks, and cancel-safe follow-ups
Rach Pradhan71a680d76b4c
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsindex 6f2ab04e..ab3bd295 100644--- a/apps/native/app/api/acp/route.ts+++ b/apps/native/app/api/acp/route.ts@@ -30,10 +30,16 @@ type Slot = {/** What the agent said it services, from `available_commands_update`. */commands: AcpCommand[];spawnError: Error | null;+ /** The in-flight session/prompt, kept so a cancel can end the turn gate. */+ pendingPrompt: Promise<unknown> | null;};const HANDSHAKE_MS = 120_000;const RPC_MS = 30_000;+/** How long a cancel waits for the interrupted turn to wind down on its own+ * before the streaming gate is forced open. Without this, a turn that never+ * sends a terminal reply (agent error, lost stream) 409s every follow-up. */+const CANCEL_GRACE_MS = 8_000;type SpawnOpts = { model?: string; resume?: string; cwd: string; yolo: boolean; mcp: boolean };type BootstrapOpts = { model?: string; reset?: boolean; resume?: string; cwd?: string; yolo?: boolean; mcp?: boolean };@@ -117,10 +123,14 @@ function spawnAgent(chat: string, opts: SpawnOpts): Slot {if (opts.yolo) args.push("--yolo");if (opts.model) args.push("--model", opts.model);if (opts.resume) args.push("--resume", opts.resume);+ // Next's bundled server configuration is runtime-only. Leaking it into+ // agent shells makes unrelated Next projects skip their own configuration.+ const env = { ...process.env };+ delete env.__NEXT_PRIVATE_STANDALONE_CONFIG;const child = spawn(graffBin(), args, {stdio: ["pipe", "pipe", "inherit"],cwd: opts.cwd,- env: { ...process.env, GRAFF_DESKTOP_CHAT: chat, ...(!opts.mcp ? { GRAFF_MCP_CONFIG: mcpOffPath() } : {}) },+ env: { ...env, GRAFF_DESKTOP_CHAT: chat, ...(!opts.mcp ? { GRAFF_MCP_CONFIG: mcpOffPath() } : {}) },});const slot: Slot = {child,@@ -134,6 +144,7 @@ function spawnAgent(chat: string, opts: SpawnOpts): Slot {mcp: opts.mcp,commands: [],spawnError: null,+ pendingPrompt: null,};slot.transport = new AcpTransport(child, message => noteCommands(slot, message));child.on("error", (err) => {@@ -167,6 +178,22 @@ function rpc(slot: Slot, method: string, params?: unknown, timeoutMs = RPC_MS):return slot.transport.request(method, params, timeoutMs);}+/** End a turn after the client cancelled it: give the interrupted+ * session/prompt a short grace to wind down on its own, then force the gate+ * open so follow-ups don't 409 forever on a turn that never replied. */+async function endTurn(slot: Slot): Promise<void> {+ const pending = slot.pendingPrompt;+ if (pending) {+ const grace = new Promise<void>(resolve => {+ const timer = setTimeout(resolve, CANCEL_GRACE_MS);+ timer.unref();+ });+ await Promise.race([pending.catch(() => {}), grace]);+ }+ slot.pendingPrompt = null;+ slot.streaming = false;+}+/** The tab's live agent when it still matches what was asked for (model,* session file, workspace, approval mode); otherwise a fresh spawn. A* request that leaves a field out accepts whatever the live agent has. */@@ -256,7 +283,12 @@ export async function POST(req: NextRequest) {}const slot = await bootstrap(chat, { model });if (method === "session/cancel") {- slot.transport.notify("session/cancel", body.params);+ try {+ slot.transport.notify("session/cancel", body.params);+ } catch {+ // a dead transport means the turn is over regardless+ }+ await endTurn(slot);return Response.json({ ok: true });}if (method === "session/prompt") {@@ -268,16 +300,19 @@ export async function POST(req: NextRequest) {let cancelled = false;const stream = new ReadableStream({start(controller) {- void slot.transport.request("session/prompt", { ...promptParams, sessionId: slot.sessionId }, 24 * 60 * 60 * 1000,- line => { if (!cancelled) controller.enqueue(encoder.encode(`${line}\n`)); })+ const pending = slot.transport.request("session/prompt", { ...promptParams, sessionId: slot.sessionId }, 24 * 60 * 60 * 1000,+ line => { if (!cancelled) controller.enqueue(encoder.encode(`${line}\n`)); });+ slot.pendingPrompt = pending;+ void pending.then(() => { if (!cancelled) { cancelled = true; controller.close(); } }).catch(error => { if (!cancelled) { cancelled = true; controller.error(error); } })- .finally(() => { slot.streaming = false; });+ .finally(() => { slot.pendingPrompt = null; slot.streaming = false; });},cancel() {if (cancelled) return; // Completed streams must not cancel a later turn.cancelled = true;try { slot.transport.notify("session/cancel", { sessionId: slot.sessionId }); } catch {}+ void endTurn(slot);},});return new Response(stream, { headers: { "content-type": "application/x-ndjson", "cache-control": "no-store" } });diff --git a/apps/native/app/visual-tests/agents/fixture.tsx b/apps/native/app/visual-tests/agents/fixture.tsxindex f6c12e37..f63b7b68 100644--- a/apps/native/app/visual-tests/agents/fixture.tsx+++ b/apps/native/app/visual-tests/agents/fixture.tsx@@ -5,14 +5,13 @@ 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 [fullWidth, setFullWidth] = useState(true);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},@@ -36,7 +35,7 @@ export default function Fixture() {], messages: [{ from_session: 'peer-a', to: 'peer-b', ts_ms: 1000, text: 'The navigation update is ready for review.', kind: 'handoff' }], delivery: 'Queued' };}, []);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><output data-agent-cancelled className="break-all">{cancelled}</output></div><AgentsPane root="/demo/workspace" onClose={() => {}} request={request} /></div>+ <nav className="flex flex-wrap gap-3 p-3"><button data-agent-layout onClick={() => setFullWidth(value => !value)}>{fullWidth ? 'Use side panel' : 'Use workspace view'}</button>{['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>+ <output data-agent-sent className="sr-only">{sent}</output><div className="flex min-h-0 flex-1 gap-3 p-3">{!fullWidth && <div className="flex-1 min-w-0 p-5"><h1>Workspace conversation</h1></div>}<AgentsPane fullWidth={fullWidth} root="/demo/workspace" onClose={() => {}} request={request} /></div></main>;}diff --git a/apps/native/components/site/AgentCard.tsx b/apps/native/components/site/AgentCard.tsxnew file mode 100644index 00000000..b5affe91--- /dev/null+++ b/apps/native/components/site/AgentCard.tsx@@ -0,0 +1,15 @@+'use client';+import { agentName, type LocalAgent } from '@/lib/agents';++export function AgentStatus({ status }: { status: string }) {+ return <span className="inline-flex shrink-0 items-center gap-1.5 text-xs text-ink-3"><span aria-hidden="true" className={`h-1.5 w-1.5 rounded-full ${status === 'working' ? 'bg-accent' : 'bg-ink-3'}`} />{status === 'working' ? 'Working' : status === 'waiting' ? 'Waiting' : 'Connected'}</span>;+}++export default function AgentCard({ agent, showWorkspace, onSelect }: { agent: LocalAgent; showWorkspace: boolean; onSelect(): void }) {+ return <li className="min-w-0"><button onClick={onSelect} aria-pressed={false} className="flex h-full w-full flex-col gap-3 rounded-xl border border-line bg-surface p-4 text-left transition-colors hover:bg-hover focus-visible:outline focus-visible:outline-accent">+ <span className="flex w-full min-w-0 flex-wrap items-center gap-2"><span className="min-w-0 flex-1 truncate text-sm font-medium">{agentName(agent)}</span><AgentStatus status={agent.status} /></span>+ <span className="line-clamp-3 break-words text-sm text-ink-2">{agent.task || 'No task published'}</span>+ {showWorkspace && <span title={agent.workspace} className="block w-full truncate text-xs text-ink-3">{agent.workspace}</span>}+ <span className="mt-auto pt-1 text-xs text-ink-3">Inspect & coordinate →</span>+ </button></li>;+}diff --git a/apps/native/components/site/AgentsPane.tsx b/apps/native/components/site/AgentsPane.tsxindex 9558a866..f3240f7a 100644--- a/apps/native/components/site/AgentsPane.tsx+++ b/apps/native/components/site/AgentsPane.tsx@@ -1,35 +1,29 @@'use client';import { useEffect, useRef, useState } from 'react';-import { agentKey, agentName, agentRequest, workingAgentCount, type AgentSnapshot, type LocalAgent, type PeerMessage } from '@/lib/agents';+import { agentKey, agentName, agentRequest, type AgentSnapshot, type LocalAgent } from '@/lib/agents';import ResizableReviewPane from './ResizableReviewPane';import SubagentActivity from './SubagentActivity';+import AgentCard, { AgentStatus } from './AgentCard';+type Draft = { text: string; kind: string; notice: string; failed: boolean; sending: boolean };+const emptyDraft: Draft = { text: '', kind: 'message', notice: '', failed: false, sending: false };-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, onOccupancy }: { root?: string; onClose(): void; request?: typeof agentRequest; onOccupancy?(count: number): void }) {+export default function AgentsPane({ root, onClose, request = agentRequest, fullWidth = false }: { root?: string; onClose(): void; request?: typeof agentRequest; fullWidth?: boolean }) {const [scope, setScope] = useState('workspace');const [showIdle, setShowIdle] = useState(false);const [snapshot, setSnapshot] = useState<AgentSnapshot | null>(null);const [error, setError] = useState('');const [recipient, setRecipient] = useState<LocalAgent | null>(null);- const [text, setText] = useState('');- const [kind, setKind] = useState('message');- const [sending, setSending] = useState(false);- const [notice, setNotice] = useState('');+ const [drafts, setDrafts] = useState<Record<string, Draft>>({});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]);+ const pending = useRef(new Set<string>());+ useEffect(() => { setRecipient(null); setComposing(false); }, [root]);useEffect(() => {if (!snapshot || !recipient || snapshot.agents.some(agent => agentKey(agent) === agentKey(recipient))) return;- setRecipient(null); setNotice(''); setText(''); setComposing(false);+ setRecipient(null); setComposing(false);}, [snapshot, recipient]);useEffect(() => {let disposed = false, timer: ReturnType<typeof setTimeout>;@@ -39,7 +33,7 @@ export default function AgentsPane({ root, onClose, request = agentRequest, onOctry {if (document.visibilityState !== 'hidden') {const data = await request(root, { action: 'list', scope }, controller.signal);- if (!disposed) { setSnapshot(data); setError(''); onOccupancy?.(workingAgentCount(data.agents)); }+ if (!disposed) { setSnapshot(data); setError(''); }}} catch (e) { if (!disposed) setError(e instanceof Error ? e.message : 'Agents unavailable'); }finally { if (!disposed) timer = setTimeout(poll, 5000); }@@ -47,53 +41,63 @@ export default function AgentsPane({ root, onClose, request = agentRequest, onOcvoid poll();return () => { disposed = true; controller.abort(); clearTimeout(timer); };}, [root, scope, refresh, request]);+ useEffect(() => { if (composing) input.current?.focus(); }, [composing]);const connected = snapshot?.agents ?? [];const agents = connected.filter(agent => showIdle || agent.status === 'working');const selected = connected.find(a => recipient && agentKey(a) === agentKey(recipient));+ const draftKey = JSON.stringify([root ?? '', recipient ? agentKey(recipient) : '']);+ const draft = drafts[draftKey] ?? emptyDraft;+ const updateDraft = (key: string, patch: Partial<Draft>) => setDrafts(current => ({ ...current, [key]: { ...(current[key] ?? emptyDraft), ...patch } }));const name = (session: string) => connected.find(a => a.session === session)?.title || session || 'Workspace';- const choose = (agent: LocalAgent) => { setRecipient(agent); setNotice(''); setComposing(false); content.current?.scrollTo({top:0}); };+ const choose = (agent: LocalAgent) => { setRecipient(agent); setComposing(false); content.current?.scrollTo({ top: 0 }); };+ const compose = (kind: string) => { updateDraft(draftKey, { kind }); setComposing(true); input.current?.focus(); };const submit = async () => {- if (!selected || !text.trim() || sending) return;- setSending(true); setNotice('');+ if (!selected || !draft.text.trim() || pending.current.has(draftKey)) return;+ const key = draftKey;+ pending.current.add(key);+ updateDraft(key, { sending: true, notice: '', failed: false });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.');- } catch (e) { setNotice(e instanceof Error ? e.message : 'Message could not be queued'); }- finally { setSending(false); }+ await request(root, { action: 'send', target: selected.session, startId: selected.startId, text: draft.text, kind: draft.kind });+ updateDraft(key, { text: '', notice: 'Queued · Graff will read this at its next step.', failed: false });+ } catch (e) { updateDraft(key, { notice: e instanceof Error ? e.message : 'Message could not be queued', failed: true }); }+ finally { pending.current.delete(key); updateDraft(key, { sending: false }); }};- return <ResizableReviewPane label="agents" defaultWidth={440}>- <aside aria-label="Agents panel" className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page text-ink">- <header className="flex items-center gap-2 border-b border-line p-4"><strong className="flex-1">Agents <span className="text-ink-3 font-normal">{snapshot ? agents.length : ''}</span></strong><button onClick={onClose} aria-label="Close agents" className="rounded px-2 hover:bg-hover">×</button></header>- <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>- <label className="flex items-center gap-2 border-b border-line px-3 py-2 text-xs text-ink-3"><input type="checkbox" checked={showIdle} onChange={e => setShowIdle(e.target.checked)} />Show idle agents</label>- <div ref={content} className="min-h-0 flex-1 overflow-y-auto p-3 space-y-4">+ const messages = snapshot?.messages.filter(message => !selected || message.to === selected.session || message.from_session === selected.session) ?? [];+ const pane = <aside aria-label="Agents panel" className="flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden rounded-[14px] border border-line bg-page text-ink">+ <header className="flex items-center gap-3 border-b border-line p-4"><div className="min-w-0 flex-1"><strong>Agents <span className="font-normal text-ink-3">{snapshot ? agents.length : ''}</span></strong><p className="mt-1 text-xs text-ink-3">Inspect work, share context, and request handoffs.</p></div><button onClick={onClose} aria-label="Close agents" className="rounded px-2 py-1 hover:bg-hover">×</button></header>+ <div className="flex flex-wrap items-center gap-3 border-b border-line p-3">+ <div className="flex gap-1" role="group" aria-label="Agent scope">{['workspace', 'device'].map(value => <button key={value} aria-pressed={scope === value} onClick={() => { setScope(value); setRecipient(null); setComposing(false); }} 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>+ <label className="flex items-center gap-2 text-xs text-ink-3"><input type="checkbox" checked={showIdle} onChange={e => setShowIdle(e.target.checked)} />Show idle agents</label>+ </div>+ <div ref={content} className="min-h-0 flex-1 overflow-y-auto p-4">+ <div className="mx-auto w-full max-w-6xl 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 && !selected && !agents.length && <p className="text-sm text-ink-3">No {showIdle ? 'connected' : 'active'} Graffs {scope === 'workspace' ? 'in this workspace' : 'on this laptop'}.{!showIdle && connected.length > 0 ? ' Show idle agents to see connected sessions waiting for input.' : ' Start a Graff session to coordinate.'}</p>}- {!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>}-- </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>- {!!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>}+ {snapshot && !selected && !agents.length && <div className="rounded-xl border border-dashed border-line p-6"><p className="text-sm text-ink-2">No {showIdle ? 'connected' : 'working'} Graffs {scope === 'workspace' ? 'in this workspace' : 'on this device'}.</p><p className="mt-2 text-xs text-ink-3">{!showIdle && connected.length > 0 ? 'Connected sessions are waiting for input. Show idle agents to inspect or message them.' : 'Start a Graff session to coordinate.'}</p></div>}+ {!selected && <ul className="grid gap-3" style={{ gridTemplateColumns: fullWidth ? 'repeat(auto-fit, minmax(min(100%, 280px), 1fr))' : 'minmax(0, 1fr)' }}>{agents.map(agent => <AgentCard key={agentKey(agent)} agent={agent} showWorkspace={scope === 'device'} onSelect={() => choose(agent)} />)}</ul>}+ {selected && <>+ <button aria-label="Back to all agents" className="rounded-lg px-2 py-1 text-xs hover:bg-hover" onClick={() => { setRecipient(null); setComposing(false); }}>← Agents</button>+ <section aria-label="Selected agent" className="space-y-3 rounded-xl border border-line bg-surface p-4">+ <div className="flex flex-wrap items-center gap-3"><h2 className="min-w-0 flex-1 break-words text-base font-medium">{agentName(selected)}</h2><AgentStatus status={selected.status} /></div>+ <p className="whitespace-pre-wrap break-words text-sm text-ink-2">{selected.task || 'No task published'}</p>+ <div className="flex flex-wrap gap-2"><button onClick={() => compose('message')} aria-expanded={composing && draft.kind === 'message'} className="rounded-lg bg-hover-2 px-3 py-2 text-xs">Message this Graff…</button><button onClick={() => compose('handoff')} aria-expanded={composing && draft.kind === 'handoff'} className="rounded-lg border border-line px-3 py-2 text-xs hover:bg-hover">Request handoff</button></div>+ <details className="text-xs text-ink-3"><summary className="cursor-pointer">Session details</summary><p className="mt-2 break-words">{selected.workspace}</p><p className="mt-2 tabular-nums">{selected.resources ? `${selected.resources.rssMiB.toFixed(1)} MiB · ${selected.resources.cpuPercent === null ? 'CPU sampling…' : `${selected.resources.cpuPercent.toFixed(1)}% CPU`}` : 'Resource measurements unavailable'}</p><p className="mt-1">Graff process only; shared workers and GPU are not attributed.</p></details>+ </section>+ {composing && <form className="space-y-3 rounded-xl border border-line p-4" onSubmit={e => { e.preventDefault(); void submit(); }}>+ <div className="flex items-center gap-2"><label className="min-w-0 flex-1 truncate text-xs text-ink-2">To {agentName(selected)}</label><button type="button" onClick={() => setComposing(false)} className="rounded px-2 py-1 text-xs hover:bg-hover">Hide composer</button></div>+ <textarea ref={input} aria-label="Message to Graff" value={draft.text} disabled={draft.sending} onChange={e => updateDraft(draftKey, { text: e.target.value })} maxLength={8192} rows={3} placeholder={draft.kind === 'handoff' ? 'Describe the work, relevant context, and what you need from this agent…' : 'Ask a peer or share context…'} className="w-full resize-y rounded-xl border border-line bg-surface p-3 text-sm outline-none focus:border-accent" />+ <div className="flex flex-wrap items-center gap-2"><select aria-label="Coordination type" disabled={draft.sending} value={draft.kind} onChange={e => updateDraft(draftKey, { kind: 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={!draft.text.trim() || draft.sending || !!error} className="ml-auto rounded-lg bg-hover-2 px-3 py-2 text-sm disabled:opacity-40">{draft.sending ? 'Queuing…' : 'Send to Graff'}</button></div>+ <p className="text-xs text-ink-3">Messages arrive at the recipient’s next step.{draft.kind === 'handoff' ? ' A handoff is a request, not a transfer of ownership or confirmation of acceptance.' : ''}</p>+ </form>}+ {draft.notice && <p role={draft.failed ? 'alert' : 'status'} className="rounded-lg border border-line p-3 text-xs text-ink-2">{draft.notice}</p>}+ <SubagentActivity key={agentKey(selected)} root={root} parent={selected} scope={scope} request={request} />+ </>}+ {!!messages.length && <details aria-label="Peer messages" className="space-y-3"><summary className="cursor-pointer text-xs font-medium text-ink-3">Coordination history{selected ? ' with this Graff' : ''} · {messages.length}</summary>{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>}</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(); }}>- <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>{selected && !agents.some(a => agentKey(a) === agentKey(selected)) && <option value={agentKey(selected)}>{agentName(selected)}</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 another Graff or show idle agents.</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>}- </aside>- </ResizableReviewPane>;+ </div>+ </aside>;+ return fullWidth ? pane : <ResizableReviewPane label="agents" defaultWidth={440}>{pane}</ResizableReviewPane>;}diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex b66ce529..61f7e23f 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -22,7 +22,8 @@ import FilesPane from "@/components/site/FilesPane";import BrowserPane from "@/components/site/DesktopBrowserPane";import { annotationsBlock, type BrowserPin } from "@/lib/browser/annotations";import { browserClose, browserHandle, browserNav } from "@/lib/browser-client";-import TaskRows from "@/components/primitives/TaskRows";+import TasksPane, { taskItems } from "./TasksPane";+import { useTasksVisibility } from "./useTasksVisibility";import ChatTranscript from "./ChatTranscript";import { useDesktopShortcuts } from "./useDesktopShortcuts";import EmptyState from "@/components/site/ChatEmpty";@@ -87,6 +88,7 @@ export default function GraffHarness() {const [models, setModels] = useState<PromptModel[]>([{ key: "", name: "Loading graff models…" }]);const [model, setModelKey] = useState<string | null>(process.env.NEXT_PUBLIC_GRAFF_MODEL || null);const [agentsOpen, setAgentsOpen] = useState(false);+ const [tasksOpen, setTasksOpen] = useTasksVisibility();const [filesOpen, setFilesOpen] = useState(false);const [fileRequest, setFileRequest] = useState<{ path: string; n: number; changes?: boolean } | null>(null);const fileReqRef = useRef(0);@@ -139,8 +141,6 @@ export default function GraffHarness() {panesRef.current = panes;const [following, setFollowing] = useState(true);const { queuesRef, queues, queueIdRef, setQueue, steerer, steerStatus, remove: removeQueued } = usePromptQueue();- const [workingAgents, setWorkingAgents] = useState(0);- const [cancelError, setCancelError] = useState<Record<number, string>>({});const runningRef = useRef(new Set<number>());// Closed tabs, oldest first, for the reopen shortcut.const closedRef = useRef<{ session: string | null; cwd?: string; resumable: boolean }[]>([]);@@ -156,6 +156,7 @@ export default function GraffHarness() {const busy = busyIds.has(chatThread.id);const chatModel = chatThread.model ?? model ?? undefined;const sessionId = sessionIds[chatThread.id] ?? null;+ const queued = queues[chatThread.id] ?? [];const handleOf = (chatId: number) => chatHandle(pageRef.current, chatId);const setBusyFor = (chatId: number, on: boolean) =>setBusyIds((current) => {@@ -349,6 +350,7 @@ export default function GraffHarness() {const runPrompt = async (chatId: number, trimmed: string) => {runningRef.current.add(chatId);+ steerer.begin(chatId);setFollowing(true);const thread = chatsRef.current.find((c) => c.id === chatId);const spawnModel = thread?.model ?? model ?? undefined;@@ -373,13 +375,6 @@ export default function GraffHarness() {),);setBusyFor(chatId, true);- setCancelError((current) => {- if (!current[chatId]) return current;- const next = { ...current };- delete next[chatId];- return next;- });- steerer.begin(chatId);setHistory((current) => {const next = pushHistory(current, trimmed);saveHistory(window.localStorage, next);@@ -403,6 +398,7 @@ export default function GraffHarness() {turn = { ...turn, connected: true, lastUpdateAt: Date.now() };painter.update(turn);for await (const update of prompt(handleOf(chatId), id, wire)) {+ // An update proves the prompt reached the agent; don't cancel during session startup.if (update.sessionUpdate === "gui_turn_end") steerer.finish(chatId);else steerer.ready(chatId);turn = applyAcpUpdate(turn, update);@@ -453,7 +449,7 @@ export default function GraffHarness() {};const openChat = (id: number) => {- setProjectsOpen(false);+ setProjectsOpen(false); setAgentsOpen(false);const session = newSessionName();sessionNamesRef.current.set(id, session);const cwd = activePathRef.current ?? undefined;@@ -492,7 +488,7 @@ export default function GraffHarness() {/** Focus a visible chat in place, or replace only the focused split. */const focusChat = (id: number) => {- setProjectsOpen(false);+ setProjectsOpen(false); setAgentsOpen(false);setConversationsOpen(false);const folder = chatsRef.current.find(chat => chat.id === id)?.cwd;if (folder && folder !== activePathRef.current) activateWorkspace(folder);@@ -532,6 +528,7 @@ export default function GraffHarness() {sessionsRef.current.delete(id);sessionNamesRef.current.delete(id);runningRef.current.delete(id);+ steerer.finish(id);setQueue(id, []);setSessionIds((current) => {const { [id]: _gone, ...rest } = current;@@ -672,7 +669,6 @@ export default function GraffHarness() {</div>)}<PromptQueue items={threadQueued} busy={threadBusy} status={steerStatus[thread.id]}- error={cancelError[thread.id]}onRemove={item => removeQueued(thread.id, item)}onSteer={item => steerer.steer(thread.id, item, () => {const session = sessionsRef.current.get(thread.id);@@ -693,13 +689,7 @@ export default function GraffHarness() {busy={threadBusy}onStop={() => {const live = sessionsRef.current.get(thread.id);- if (!live) {- setCancelError(current => ({ ...current, [thread.id]: "Nothing to interrupt yet." }));- return;- }- void cancel(handleOf(thread.id), live).catch(err => {- setCancelError(current => ({ ...current, [thread.id]: err instanceof Error ? err.message : "Could not interrupt the current turn" }));- });+ if (live) void cancel(handleOf(thread.id), live).catch(() => {});}}/></div>@@ -782,7 +772,7 @@ export default function GraffHarness() {chatCwd={chatCwd} workspaceName={workspaceName} onFolder={() => setDialog({ mode: "new" })} openChanges={openChanges}browserOpen={browserOpen} onBrowser={() => { setAgentsOpen(false); setProjectsOpen(false); setConversationsOpen(false); setFilesOpen(false); setBrowserOpen(open => !open); }} pinCount={pinCount}terminalVisible={terminalVisible} toggleTerminal={toggleTerminal} agentsOpen={agentsOpen}- workingAgents={workingAgents}+ tasksOpen={tasksOpen} taskCount={paneTodos.length} onTasks={() => { setAgentsOpen(false); setTasksOpen(!tasksOpen); }}onAgents={() => { setProjectsOpen(false); setAgentsOpen(!agentsOpen); setFilesOpen(false); setBrowserOpen(false); setConversationsOpen(false); }} /><ConversationOpenNotice request={savedConversation.request} onCancel={savedConversation.cancel} onRetry={savedConversation.retry} /><div className="flex min-h-0 flex-1 gap-2.5">@@ -804,13 +794,13 @@ export default function GraffHarness() {/></section>) : null}- <div className="min-h-0 min-w-0 flex-1" style={{ display: projectsOpen || conversationsOpen ? "none" : "flex" }}>+ <div className="min-h-0 min-w-0 flex-1" style={{ display: projectsOpen || conversationsOpen || agentsOpen ? "none" : "flex" }}><ChatSplitLayout threads={columns} liveChatIds={chats.map(chat => chat.id)} activeId={activeId} direction={splitDirection} weights={paneWeights} setWeights={setPaneWeights}onFocus={focusChat} onClose={closeChat} folder={thread => ({name: workspaceNameOf(thread), path: cwdOf(thread)})}body={columnBody} split={columnIds.length > 1} /></div>- {agentsOpen && !projectsOpen && !filesOpen && !browserOpen && !conversationsOpen && <AgentsPane key={chatCwd} root={chatCwd} onClose={() => setAgentsOpen(false)} onOccupancy={setWorkingAgents} />}+ {agentsOpen && !projectsOpen && !filesOpen && !browserOpen && !conversationsOpen && <AgentsPane key={chatCwd} root={chatCwd} fullWidth onClose={() => setAgentsOpen(false)} />}{filesOpen && !projectsOpen && !conversationsOpen && (fileRequest?.changes ? <ChangesPane root={chatThread.cwd} onClose={() => setFilesOpen(false)} /> : <FilesPane root={chatThread.cwd} requested={fileRequest} onClose={() => setFilesOpen(false)} />)}{browserOpen && !projectsOpen && !conversationsOpen && (@@ -825,25 +815,8 @@ export default function GraffHarness() {/>)}- {!projectsOpen && !filesOpen && !browserOpen && !conversationsOpen && active && paneTodos.length > 0 && (- <aside- className="hidden w-[360px] shrink-0 flex-col overflow-hidden rounded-[14px] border border-line bg-page lg:flex"- style={{ animation: "fade-in 300ms ease both" }}- >- <div className="flex h-11 shrink-0 items-center border-b border-line px-4">- <span className="text-[13px] font-semibold text-ink">Tasks</span>- </div>- <div className="min-h-0 flex-1 overflow-y-auto p-4">- <TaskRows- variant="List"- items={paneTodos.map((todo) => ({- key: todo.id,- label: todo.content,- status: todo.status === "in_progress" ? "in_progress" : todo.status === "completed" ? "completed" : "pending",- }))}- />- </div>- </aside>+ {tasksOpen && !agentsOpen && !projectsOpen && !filesOpen && !browserOpen && !conversationsOpen && active && paneTodos.length > 0 && (+ <TasksPane items={taskItems(paneTodos)} onClose={() => setTasksOpen(false)} />)}</div>{terminalUsed && chatCwd && <TerminalPane key={chatCwd} cwd={chatCwd} visible={terminalVisible} onHide={() => setTerminalVisible(false)} />}diff --git a/apps/native/components/site/HarnessChrome.tsx b/apps/native/components/site/HarnessChrome.tsxindex 70288698..46ce47aa 100644--- a/apps/native/components/site/HarnessChrome.tsx+++ b/apps/native/components/site/HarnessChrome.tsx@@ -9,24 +9,28 @@ type Props = {conversationsOpen: boolean; openConversations(): void; split: boolean; toggleSplit(): void;filesOpen: boolean; onFiles(): void; chatCwd?: string; workspaceName: string; onFolder(): void;openChanges(): void; browserOpen: boolean; onBrowser(): void; pinCount: number;- terminalVisible: boolean; toggleTerminal(): void; agentsOpen: boolean; onAgents(): void; workingAgents?: number;+ terminalVisible: boolean; toggleTerminal(): void; agentsOpen: boolean; onAgents(): void;+ tasksOpen?: boolean; taskCount?: number; onTasks?(): void;};export default function HarnessChrome({chats, activeId, busyIds, focusChat, closeChat, newChat,conversationsOpen, openConversations, split, toggleSplit, filesOpen, onFiles, chatCwd,workspaceName, onFolder, openChanges, browserOpen, onBrowser, pinCount, terminalVisible,- toggleTerminal, agentsOpen, onAgents, workingAgents = 0}: Props) {+ toggleTerminal, agentsOpen, onAgents, tasksOpen, taskCount = 0, onTasks}: Props) {const frame = useRef<HTMLDivElement>(null);useEffect(() => { frame.current?.querySelector(`[data-tab-id="${activeId}"]`)?.scrollIntoView({block: "nearest", inline: "nearest"}); }, [activeId]);return (<div ref={frame} data-workspace-toolbar className={`${reviewStyles.chatbar} flex shrink-0 flex-col overflow-hidden rounded-[14px] border border-line bg-page`}>- {/* Tabs scroll independently; toolbar labels collapse in narrow panes. */}+ {/* One workspace-level tab strip above every split; never owned by a pane. */}<div className="flex h-10 min-w-0 shrink-0 items-center gap-1 overflow-x-auto px-2 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden">+ <button type="button" aria-label="Show agents" aria-pressed={agentsOpen} onClick={onAgents}+ className={`h-7 shrink-0 rounded-[7px] px-3 text-[12.5px] font-medium ${agentsOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover"}`}>Agents</button>+ <span aria-hidden="true" className="mx-1 h-4 w-px shrink-0 bg-line" />{chats.map((c) => (<divdata-tab-id={c.id}key={c.id}className={`group/tab flex h-7 w-36 shrink-0 items-center gap-0.5 rounded-[7px] pl-2.5 pr-1 text-[12.5px] font-medium transition-colors duration-100 ${- c.id === activeId ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"+ c.id === activeId && !agentsOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover hover:text-ink"}`}>{busyIds.has(c.id) && (@@ -38,7 +42,7 @@ export default function HarnessChrome({chats, activeId, busyIds, focusChat, clos)}<buttontype="button"- aria-pressed={c.id === activeId}+ aria-pressed={c.id === activeId && !agentsOpen}onClick={() => {focusChat(c.id);}}@@ -139,7 +143,8 @@ export default function HarnessChrome({chats, activeId, busyIds, focusChat, clos)}</button><button aria-label="Toggle terminal" aria-pressed={terminalVisible} title="Terminal (⌘J)" onClick={toggleTerminal} className="rounded-lg px-2 py-1 text-xs text-ink-2 hover:bg-hover"><svg aria-hidden="true" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><rect x="3" y="4" width="18" height="16" rx="3"/><path d="m7 9 3 3-3 3m6 0h4"/></svg></button>- <button aria-label="Show agents" aria-pressed={agentsOpen} onClick={onAgents} className="flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs text-ink-2 hover:bg-hover"><svg aria-hidden="true" width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7"><circle cx="9" cy="7" r="3"/><path d="M3 20v-3a6 6 0 0 1 12 0v3M16 4a3 3 0 0 1 0 6M18 14a5 5 0 0 1 3 4v2"/></svg><span data-toolbar-label>Agents{workingAgents > 0 ? ` (${workingAgents})` : ""}</span>{workingAgents > 0 && <span className="size-1.5 shrink-0 animate-pulse rounded-full" style={{ background: "var(--accent)" }} aria-hidden />}</button>+ {onTasks && <button type="button" aria-label="Show tasks" aria-pressed={tasksOpen} onClick={onTasks}+ className={`shrink-0 rounded-lg px-2 py-1 text-xs ${tasksOpen ? "bg-hover-2 text-ink" : "text-ink-2 hover:bg-hover"}`}>Tasks{taskCount > 0 ? ` (${taskCount})` : ""}</button>}<ThemeToggle /></div></div>diff --git a/apps/native/components/site/TasksPane.tsx b/apps/native/components/site/TasksPane.tsxnew file mode 100644index 00000000..f9cf262c--- /dev/null+++ b/apps/native/components/site/TasksPane.tsx@@ -0,0 +1,25 @@+"use client";++import TaskRows, { type TaskItem } from "@/components/primitives/TaskRows";++export function taskItems(todos: { id: string; content: string; status: string }[]): TaskItem[] {+ return todos.map(todo => ({ key: todo.id, label: todo.content,+ status: todo.status === "in_progress" ? "in_progress" : todo.status === "completed" ? "completed" : "pending" }));+}++/** Dismiss presentation only; the agent's checklist remains intact. */+export default function TasksPane({ items, onClose }: { items: TaskItem[]; onClose(): void }) {+ return (+ <aside aria-label="Tasks" className="hidden w-[360px] shrink-0 flex-col overflow-hidden rounded-[14px] border border-line bg-page lg:flex"+ style={{ animation: "fade-in 300ms ease both" }}>+ <div className="flex h-11 shrink-0 items-center justify-between border-b border-line px-4">+ <span className="text-[13px] font-semibold text-ink">Tasks</span>+ <button type="button" onClick={onClose} aria-label="Hide tasks" title="Hide tasks"+ className="flex h-7 w-7 items-center justify-center rounded-md text-ink-2 hover:bg-hover">×</button>+ </div>+ <div className="min-h-0 flex-1 overflow-y-auto p-4">+ <TaskRows variant="List" items={items} />+ </div>+ </aside>+ );+}diff --git a/apps/native/components/site/useTasksVisibility.ts b/apps/native/components/site/useTasksVisibility.tsnew file mode 100644index 00000000..8c63b11b--- /dev/null+++ b/apps/native/components/site/useTasksVisibility.ts@@ -0,0 +1,18 @@+"use client";++import { useEffect, useState } from "react";++const KEY = "graff.tasks.visible";++/** A view preference, not checklist state; survives panel and chat switches. */+export function useTasksVisibility() {+ const [open, setOpen] = useState(false);+ useEffect(() => {+ try { setOpen(localStorage.getItem(KEY) === "true"); } catch { /* optional storage */ }+ }, []);+ const change = (value: boolean) => {+ setOpen(value);+ try { localStorage.setItem(KEY, String(value)); } catch { /* optional storage */ }+ };+ return [open, change] as const;+}diff --git a/apps/native/electron/agents-visual.cjs b/apps/native/electron/agents-visual.cjsindex 7f717a0d..02eaeff8 100644--- a/apps/native/electron/agents-visual.cjs+++ b/apps/native/electron/agents-visual.cjs@@ -9,40 +9,39 @@ async function runAgentVisuals({ win, origin, output }) {win.show(); win.focus();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.')`));+ assert.equal(await js(`document.querySelector('li').textContent.includes('MiB')`), false, 'Cards omit resource diagnostics');+ await js(`document.querySelector('[data-agent-layout]').click()`);+ assert.ok(await js(`document.querySelector('aside').getBoundingClientRect().width < innerWidth - 100`), 'Default side panel remains compatible');+ await js(`document.querySelector('[data-agent-layout]').click()`);+ assert.ok(await js(`document.querySelector('aside').getBoundingClientRect().width > innerWidth - 50`), 'Workspace view fills available width');+ assert.equal(await js(`document.querySelector('textarea')`), null, 'Composer is contextual, not permanently visible');for (const theme of ['light', 'dark', 'codegraff']) {await js(`document.querySelector('[data-agent-theme="${theme}"]').click()`);await js('document.fonts.ready.then(()=>true)');- const bounds = await js(`(()=>{const a=document.querySelector('aside').getBoundingClientRect(),b=document.querySelector('textarea').getBoundingClientRect();return {right:a.right,bottom:b.bottom,height:innerHeight,width:innerWidth}})()`);+ const bounds = await js(`(()=>{const a=document.querySelector('aside').getBoundingClientRect();return {right:a.right,bottom:a.bottom,height:innerHeight,width:innerWidth}})()`);assert.ok(bounds.right <= bounds.width && bounds.bottom < bounds.height, JSON.stringify(bounds));fs.writeFileSync(path.join(output, `agents-${theme}.png`), (await win.webContents.capturePage()).toPNG());}await js(`document.querySelector('[data-agent-case="idle"]').click()`);- await wait(`document.body.textContent.includes('No active Graffs')`);+ await wait(`document.body.textContent.includes('No working Graffs')`);assert.equal(await js(`document.querySelectorAll('li button').length`), 0, 'A peer disappears when it stops working');await js(`document.querySelector('[data-agent-case="connected"]').click()`);await wait(`document.querySelectorAll('li button').length === 1`);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');await js(`Array.from(document.querySelectorAll('button')).find(b => b.textContent === 'Message this Graff…').click()`);- assert.equal(await js(`document.querySelector('[aria-label="Message recipient"] option:checked')?.textContent`), 'Implement navigation', 'Idle selection remains an explicit recipient');+ assert.equal(await js(`document.querySelector('form label')?.textContent`), 'To Implement navigation', 'Idle selection remains an explicit recipient');await js(`document.querySelector('[aria-label="Back to all agents"]').click()`);- await wait(`document.body.textContent.includes('No active Graffs')`);+ await wait(`document.body.textContent.includes('No working Graffs')`);await js(`document.querySelector('[data-agent-case="connected"]').click()`);await wait(`document.querySelectorAll('li button').length === 1`);await js(`document.querySelectorAll('[aria-label="Agent scope"] button')[1].click()`);await wait(`document.querySelectorAll('li button').length === 1`);- assert.equal(await js(`document.querySelector('[aria-label="Message recipient"]').textContent.includes('Review accessibility')`), false, 'Idle peers are excluded from active recipients');+ assert.equal(await js(`document.querySelector('textarea')`), null, 'Overview does not show a recipient-less composer');assert.equal(await js(`document.querySelector('[aria-label="Peer messages"]').open`), false, 'Old coordination stays collapsed');await js(`Array.from(document.querySelectorAll('label')).find(l => l.textContent.includes('Show idle agents')).querySelector('input').click()`);await wait(`document.querySelectorAll('li button').length === 2`);@@ -57,7 +56,6 @@ 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()`);@@ -83,6 +81,14 @@ async function runAgentVisuals({ win, origin, output }) {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('[aria-label="Back to all agents"]').click()`);+ await js(`document.querySelectorAll('li button')[0].click()`);+ await js(`Array.from(document.querySelectorAll('button')).find(b => b.textContent === 'Message this Graff…').click()`);+ assert.equal(await js(`document.querySelector('textarea').value`), '', 'Drafts do not leak to another recipient');+ await js(`document.querySelector('[aria-label="Back to all agents"]').click()`);+ await js(`document.querySelectorAll('li button')[1].click()`);+ await js(`Array.from(document.querySelectorAll('button')).find(b => b.textContent === 'Message this Graff…').click()`);+ assert.equal(await js(`document.querySelector('textarea').value`), 'Please review this update.', 'Returning to a recipient restores its draft');await js(`document.querySelector('button[type="submit"]').click()`);await wait(`document.body.textContent.includes('Queued · Graff')`);const sent = JSON.parse(await js(`document.querySelector('[data-agent-sent]').textContent`));@@ -90,7 +96,7 @@ async function runAgentVisuals({ win, origin, output }) {await js(`document.querySelector('[data-agent-case="empty"]').click()`);await wait(`document.body.textContent.includes('No connected Graffs')`);await wait(`!document.body.textContent.includes('Recipient is unavailable')`);- assert.equal(await js(`document.querySelector('button[type="submit"]').disabled`), true);+ assert.equal(await js(`document.querySelector('textarea')`), null, 'Composer is contextual, not permanently visible');await js(`document.querySelector('[data-agent-case="connected"]').click()`);await wait(`document.querySelectorAll('li button').length === 2`);assert.equal(await js(`document.querySelector('[aria-label="Sub-agent activity"]')`), null, 'A disconnected selection does not return when the peer reconnects');diff --git a/apps/native/electron/updates.cjs b/apps/native/electron/updates.cjsindex c8647db7..3547af30 100644--- a/apps/native/electron/updates.cjs+++ b/apps/native/electron/updates.cjs@@ -1,10 +1,21 @@const fs = require('node:fs');const path = require('node:path');-const FIRST_CHECK_MS = 30_000;-const POLL_MS = 6 * 60 * 60 * 1000;--function createUpdates({ updater, version, available = true, automatic = true, notify, save = () => {}, onReady }) {+// Electron's macOS isPackaged is basename(exe) != "electron", and the+// distribution bundle keeps the executable named Electron — so it is always+// false in signed releases. The signed feed config is the availability+// signal instead: only distribute.sh writes app-update.yml, before signing.+function updateAvailability({ platform, env, execPath, feedPath }) {+ return platform === 'darwin' && !env.GRAFF_ELECTRON_SMOKE &&+ !execPath.startsWith('/Volumes/') && fs.existsSync(feedPath);+}+function createUpdates({ updater, version, available = true, automatic = true, notify, save = () => {}, feedPath }) {+ if (available && updater && feedPath && updater.isUpdaterActive && !updater.isUpdaterActive()) {+ // Electron reports an unpackaged app even for signed releases (see+ // updateAvailability). Point electron-updater at the signed feed config+ // explicitly so check/download/install still run against it.+ try { updater.forceDevUpdateConfig = true; updater.updateConfigPath = feedPath; } catch {}+ }let state = { status: available ? 'idle' : 'unavailable', currentVersion: version, automatic, interactive: false };let checking = false;const emit = patch => { state = { ...state, ...patch }; notify({ ...state }); };@@ -22,13 +33,7 @@ function createUpdates({ updater, version, available = true, automatic = true, nif (percent !== state.percent) emit({ status: 'downloading', percent });});updater.on('update-not-available', () => emit({ status: 'current', version: undefined, percent: undefined }));- updater.on('update-downloaded', info => {- emit({ status: 'ready', version: info.version, percent: 100 });- if (onReady && info.version && info.version !== state.prompted) {- state.prompted = info.version; // once per version: dismiss means Later, never a loop- onReady(info.version);- }- });+ updater.on('update-downloaded', info => emit({ status: 'ready', version: info.version, percent: 100 }));updater.on('error', () => emit({ status: 'error', message: 'Could not update. Check your connection and try again.' }));}return {@@ -61,52 +66,31 @@ function createUpdates({ updater, version, available = true, automatic = true, n}function installUpdates({ app, win, ipcMain, trusted, resources }) {- const { dialog } = require('electron');const prefs = path.join(app.getPath('userData'), 'updates.json');let automatic = true;try { automatic = JSON.parse(fs.readFileSync(prefs, 'utf8')).automatic !== false; } catch {}- const available = app.isPackaged && process.platform === 'darwin' && !process.env.GRAFF_ELECTRON_SMOKE &&- !process.execPath.startsWith('/Volumes/') && fs.existsSync(path.join(resources, 'app-update.yml'));- let autoItem;+ const feedPath = path.join(resources, 'app-update.yml');+ const available = updateAvailability({ platform: process.platform, env: process.env, execPath: process.execPath, feedPath });const controller = createUpdates({ version: app.getVersion(), automatic, available,- updater: available ? require('./updater-runtime.cjs') : null,+ updater: available ? require('./updater-runtime.cjs') : null, feedPath,save: value => { fs.mkdirSync(path.dirname(prefs), { recursive: true }); fs.writeFileSync(prefs, JSON.stringify({ automatic: value })); },- notify: state => {- if (autoItem) autoItem.checked = state.automatic;- if (!win.isDestroyed()) { win.webContents.send('update-state', state); win.setProgressBar(state.status === 'downloading' ? (state.percent ?? 0) / 100 : -1); }- },- onReady: readyVersion => {- // The standard update modal (Sparkle/electron-updater style): pops once- // per downloaded version, after the download — never mid-conversation.- if (win.isDestroyed()) return;- void dialog.showMessageBox(win, {- type: 'info',- title: 'Update Available',- message: `Codegraff ${readyVersion} is ready to install.`,- detail: 'Restart to apply the update now, or keep working — Codegraff offers the restart again at next launch.',- buttons: ['Restart to update', 'Later'], defaultId: 0, cancelId: 1,- }).then(({ response }) => {- if (response === 0 && !win.isDestroyed()) { try { controller.restart(); } catch {} }- }).catch(() => {});- },+ notify: state => { if (!win.isDestroyed()) { win.webContents.send('update-state', state); win.setProgressBar(state.status === 'downloading' ? (state.percent ?? 0) / 100 : -1); } },});- autoItem = { label: 'Automatically Download Updates', type: 'checkbox', checked: automatic,- click: item => controller.setAutomatic(item.checked) };- ipcMain.handle('updates', async (event, action, value) => {+ ipcMain.handle('updates', async (event, action) => {trusted(event);if (action === 'check') await controller.check(true);else if (action === 'restart') controller.restart();- else if (action === 'automatic') controller.setAutomatic(!!value);else if (action !== 'state') throw Error('Unknown update action');return controller.state();});const check = () => { if (controller.state().automatic) void controller.check(); };- const first = setTimeout(check, FIRST_CHECK_MS), repeat = setInterval(check, POLL_MS);+ const first = setTimeout(check, 30000), repeat = setInterval(check, 6 * 60 * 60 * 1000);first.unref(); repeat.unref();app.once('before-quit', () => { clearTimeout(first); clearInterval(repeat); });return [{ label: 'Check for Updates…', click: () => void controller.check(true) },- autoItem,+ { label: 'Automatically Download Updates', type: 'checkbox', checked: automatic,+ click: item => controller.setAutomatic(item.checked) },];}-module.exports = { createUpdates, installUpdates, FIRST_CHECK_MS, POLL_MS };+module.exports = { createUpdates, installUpdates, updateAvailability };diff --git a/apps/native/electron/updates.test.cjs b/apps/native/electron/updates.test.cjsindex 69c8739f..de4ad5a7 100644--- a/apps/native/electron/updates.test.cjs+++ b/apps/native/electron/updates.test.cjs@@ -1,14 +1,16 @@const { test, expect } = require('bun:test');const { EventEmitter } = require('node:events');-const { createUpdates } = require('./updates.cjs');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const { createUpdates, updateAvailability } = require('./updates.cjs');function fixture(options = {}) {const updater = new EventEmitter(), events = [], saved = [];let checks = 0, installs = 0;- const ready = [];updater.checkForUpdates = async () => { checks++; updater.emit('checking-for-update'); return null; };updater.quitAndInstall = () => { installs++; };- const updates = createUpdates({ updater, version: '1.0.0', notify: state => events.push(state), save: value => saved.push(value), onReady: v => ready.push(v), ...options });- return { updater, updates, events, saved, ready, checks: () => checks, installs: () => installs };+ const updates = createUpdates({ updater, version: '1.0.0', notify: state => events.push(state), save: value => saved.push(value), ...options });+ return { updater, updates, events, saved, checks: () => checks, installs: () => installs };}test('downloads in the background but never interrupts a running task automatically', async () => {const f = fixture();@@ -64,30 +66,31 @@ test('concurrent checks are coalesced and automatic-download preference persistsexpect(f.saved).toEqual([false]);expect(f.updates.state().automatic).toBe(false);});--test('the ready modal pops once per version, never in a dismiss loop', async () => {- const f = fixture();- await f.updates.check();- f.updater.emit('update-available', { version: '1.0.1' });- f.updater.emit('update-downloaded', { version: '1.0.1' });- f.updater.emit('update-downloaded', { version: '1.0.1' }); // duplicate event after a redownload- expect(f.ready).toEqual(['1.0.1']);- await f.updates.check(); // checks while ready do not re-prompt- expect(f.ready).toEqual(['1.0.1']);- f.updater.emit('update-downloaded', { version: '1.0.2' });- expect(f.ready).toEqual(['1.0.1', '1.0.2']);-});--test('automatic checks wait 30s after launch then every six hours', () => {- const { FIRST_CHECK_MS, POLL_MS } = require('./updates.cjs');- expect(FIRST_CHECK_MS).toBe(30_000);- expect(POLL_MS).toBe(6 * 60 * 60 * 1000);-});--test('in-app settings expose check and the six-hour automatic poll', () => {- const src = require('node:fs').readFileSync(require('node:path').join(__dirname, '../components/site/DesktopUpdates.tsx'), 'utf8');- expect(src).toContain('data-desktop-update-settings');- expect(src).toContain('Check for Updates');- expect(src).toContain('every six hours');- expect(src).toContain('data-desktop-update-automatic');+test('a signed release whose executable is still named Electron can check', async () => {+ // Regression: macOS isPackaged is basename(exe) != "electron", and the+ // distribution bundle keeps the executable named Electron — so the flag is+ // false in signed releases. The signed feed config is the signal instead.+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-update-gate-'));+ try {+ const feedPath = path.join(dir, 'app-update.yml');+ fs.writeFileSync(feedPath, JSON.stringify({ provider: 'generic', url: 'https://example.com/' }));+ const gate = { platform: 'darwin', env: {}, execPath: '/Applications/Codegraff.app/Contents/MacOS/Electron', feedPath };+ expect(updateAvailability(gate)).toBe(true);+ expect(updateAvailability({ ...gate, platform: 'linux' })).toBe(false);+ expect(updateAvailability({ ...gate, env: { GRAFF_ELECTRON_SMOKE: '1' } })).toBe(false);+ expect(updateAvailability({ ...gate, execPath: '/Volumes/Codegraff/Codegraff.app/Contents/MacOS/Electron' })).toBe(false);+ expect(updateAvailability({ ...gate, feedPath: path.join(dir, 'missing.yml') })).toBe(false);+ // electron-updater also gates on isPackaged internally; a signed bundle+ // reporting false must be pointed at the signed feed explicitly.+ const configured = fixture({ feedPath });+ const seen = [];+ configured.updater.isUpdaterActive = () => seen.length > 0;+ Object.defineProperty(configured.updater, 'updateConfigPath', { set: value => seen.push(value) });+ createUpdates({ updater: configured.updater, version: '1.0.0', feedPath,+ notify: () => {}, save: () => {} });+ expect(seen).toEqual([feedPath]);+ expect(configured.updater.forceDevUpdateConfig).toBe(true);+ } finally {+ fs.rmSync(dir, { recursive: true, force: true });+ }});diff --git a/apps/native/electron/workspace-layout-visual.cjs b/apps/native/electron/workspace-layout-visual.cjsnew file mode 100644index 00000000..f3116c64--- /dev/null+++ b/apps/native/electron/workspace-layout-visual.cjs@@ -0,0 +1,115 @@+// Headless, synthetic checks against the production GUI. No agent/provider calls.+const { app, BrowserWindow } = require('electron');+const { spawn } = require('node:child_process');+const { installGalleryFixture } = require('./gallery-fixture.cjs');+const fs = require('node:fs');+const path = require('node:path');+const os = require('node:os');+const net = require('node:net');+const assert = require('node:assert/strict');+const root = path.resolve(__dirname, '..');+const output = path.resolve(root, '../../zig-out/visual-tests/workspace');+const temporary = fs.mkdtempSync(path.join(os.tmpdir(), 'graff-workspace-visual-'));+app.setPath('userData', path.join(temporary, 'profile'));+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));+let server, win;+const deadline = setTimeout(() => finish(1), 120000);+app.whenReady().then(async () => {+ fs.mkdirSync(output, { recursive: true });+ const socket = net.createServer();+ await new Promise(resolve => socket.listen(0, '127.0.0.1', resolve));+ const port = socket.address().port;+ await new Promise(resolve => socket.close(resolve));+ const origin = `http://127.0.0.1:${port}`;+ const env = { ...process.env, GRAFF_VISUAL_TESTS: '1', GRAFF_DESKTOP_TOKEN: '', NEXT_TELEMETRY_DISABLED: '1' };+ delete env.__NEXT_PRIVATE_STANDALONE_CONFIG;+ const log = fs.openSync(path.join(output, 'server.log'), 'w');+ server = spawn(process.env.GRAFF_TEST_BUN || 'bun', ['node_modules/next/dist/bin/next', 'start', '--port', String(port), '--hostname', '127.0.0.1'],+ { cwd: root, env, detached: true, stdio: ['ignore', log, log] });+ fs.closeSync(log);+ for (let i = 0; ; i++) {+ try { if ((await fetch(origin)).ok) break; } catch {}+ if (i === 100) throw Error('Production GUI did not start');+ await sleep(100);+ }+ win = new BrowserWindow({ width: 1440, height: 920, show: false, webPreferences: {+ sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false, offscreen: true,+ } });+ const wc = win.webContents;+ const unexpected = [];+ wc.session.webRequest.onBeforeRequest((details, callback) => {+ const url = new URL(details.url);+ if (url.origin === origin && url.pathname.startsWith('/api/')) unexpected.push(url.pathname);+ callback({ cancel: url.origin === origin ? url.pathname.startsWith('/api/') : !details.url.startsWith('data:') });+ });+ wc.debugger.attach('1.3');+ await wc.debugger.sendCommand('Page.enable');+ await wc.debugger.sendCommand('Page.addScriptToEvaluateOnNewDocument', { source: `(${installGalleryFixture.toString()})();+ const fixtureFetch=window.fetch;+ window.fetch=async(input,options)=>{+ if(String(input).includes('/api/acp') && options?.body && JSON.parse(options.body).method==='session/prompt') {+ const updates=[{sessionUpdate:'tool_call',toolCallId:'todo',title:'todo_write',kind:'think',status:'completed',rawInput:{todos:[{id:'a',content:'Review the layout',status:'in_progress'}]}},+ {sessionUpdate:'agent_message_chunk',content:{type:'text',text:'The layout is ready to inspect.'}}];+ const lines=updates.map(update=>({jsonrpc:'2.0',method:'session/update',params:{sessionId:'demo',update}}));+ lines.push({jsonrpc:'2.0',id:1,result:{stopReason:'end_turn'}});+ return new Response(lines.map(line=>JSON.stringify(line)).join('\\n')+'\\n');+ }+ return fixtureFetch(input,options);+ };` });+ const js = source => wc.executeJavaScript(source);+ const wait = async source => {+ for (let i = 0; i < 150; i++) { if (await js(source)) return; await sleep(40); }+ throw Error(`Workspace check timed out: ${source}`);+ };+ const click = async selector => { await js(`document.querySelector(${JSON.stringify(selector)}).click()`); await sleep(100); };+ const key = async (key, extra = {}) => {+ await js(`document.activeElement.dispatchEvent(new KeyboardEvent('keydown',${JSON.stringify({key,bubbles:true,cancelable:true,...extra})}))`);+ await sleep(100);+ };+ await wc.loadURL(origin);+ await wait(`!!document.querySelector('textarea[aria-label="Prompt"]')`);+ await js(`(()=>{const e=document.querySelector('textarea[aria-label="Prompt"]');Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype,'value').set.call(e,'Check the layout');e.dispatchEvent(new Event('input',{bubbles:true}));})()`);+ await wait(`!document.querySelector('[aria-label="Send"]').disabled`);+ await click('[aria-label="Send"]');+ await wait(`document.querySelector('[aria-label="Show tasks"]').textContent.includes('(1)')`);+ assert.equal(await js(`!!document.querySelector('aside[aria-label="Tasks"]')`), false, 'Tasks does not open itself');+ await click('[aria-label="Show tasks"]');+ await wait(`!!document.querySelector('[aria-label="Hide tasks"]')`);+ await click('[aria-label="Hide tasks"]');+ await click('[aria-label="Show agents"]');+ await wait(`!!document.querySelector('[aria-label="Agents panel"]')`);+ assert.equal(await js(`document.querySelector('[data-chat-layout]').parentElement.style.display`), 'none');+ const geometry = await js(`(()=>{const t=document.querySelector('[data-workspace-toolbar]').getBoundingClientRect(),a=document.querySelector('[aria-label="Agents panel"]').getBoundingClientRect();return {toolbar:t.width,agents:a.width,below:a.top>=t.bottom}})()`);+ assert.ok(geometry.below && Math.abs(geometry.toolbar - geometry.agents) < 4, JSON.stringify(geometry));+ await click('[aria-label="Close agents"]');+ assert.equal(await js(`!!document.querySelector('aside[aria-label="Tasks"]')`), false, 'Tasks remains dismissed after navigation');+ await key('d', { metaKey: true });+ await wait(`document.querySelectorAll('[data-chat]').length===2`);+ const checkToolbar = async () => {+ const bounds = await js(`(()=>{const bars=[...document.querySelectorAll('[data-workspace-toolbar]')],t=bars[0].getBoundingClientRect();return {count:bars.length,inside:!!bars[0].closest('[data-chat]'),panes:[...document.querySelectorAll('[data-chat]')].map(p=>{const r=p.getBoundingClientRect();return {below:r.top>=t.bottom,left:r.left>=t.left-1,right:r.right<=t.right+1}})}})()`);+ assert.equal(bounds.count, 1); assert.equal(bounds.inside, false);+ assert.ok(bounds.panes.every(p => p.below && p.left && p.right), JSON.stringify(bounds));+ };+ await checkToolbar();+ await js(`document.querySelectorAll('[data-chat]')[1].querySelector('textarea').focus()`);+ await checkToolbar();+ await js('document.fonts.ready.then(()=>true)');+ fs.writeFileSync(path.join(output, 'shared-toolbar-splits.png'), (await wc.capturePage()).toPNG());+ await key('d', { metaKey: true, shiftKey: true });+ await checkToolbar();+ await click('[aria-label="Show agents"]');+ await wait(`!!document.querySelector('[aria-label="Agents panel"]')`);+ fs.writeFileSync(path.join(output, 'agents-workspace.png'), (await wc.capturePage()).toPNG());+ await wc.reload();+ await wait(`!!document.querySelector('[aria-label="Show tasks"]')`);+ assert.equal(await js(`document.querySelector('[aria-label="Show tasks"]').getAttribute('aria-pressed')`), 'false');+ assert.deepEqual(unexpected, [], 'Synthetic checks must never reach real agent APIs');+ console.log('PASS: shared toolbar above horizontal/vertical splits; full-width Agents; Tasks close persists across navigation/reload. No engine calls.');+}).then(() => finish(0)).catch(error => { console.error(error); finish(1); });+function finish(code) {+ clearTimeout(deadline);+ if (win && !win.isDestroyed()) win.destroy();+ if (server?.pid) try { process.kill(-server.pid, 'SIGTERM'); } catch {}+ fs.rmSync(temporary, { recursive: true, force: true });+ app.exit(code);+}diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.tsindex ac5b24d2..7cdc67e4 100644--- a/apps/native/lib/acp-client.ts+++ b/apps/native/lib/acp-client.ts@@ -127,11 +127,12 @@ export async function* prompt(}export async function cancel(chat: ChatHandle, sessionId: string): Promise<void> {- await fetch(BASE, {+ const response = await fetch(BASE, {method: "POST",headers: { "content-type": "application/json" },body: JSON.stringify({ chat, method: "session/cancel", params: { sessionId } }),- }).catch(() => {});+ });+ if (!response.ok) throw new Error("Could not interrupt the current turn");}/** Kill a closed tab's agent. `keepalive` so a close-then-navigate still lands. */diff --git a/apps/native/package.json b/apps/native/package.jsonindex acc5043e..c5155ebf 100644--- a/apps/native/package.json+++ b/apps/native/package.json@@ -10,7 +10,7 @@"start": "NEXT_TELEMETRY_DISABLED=1 next start --port 3000","mock-serve": "node scripts/mock-serve.mjs","lint": "next lint",- "test": "node --experimental-strip-types --test lib/cite-markup.test.ts lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-queue-steer.test.ts lib/agents.test.ts lib/mermaid-plugin.test.ts lib/prompt-history.test.ts lib/attachments.test.ts lib/workspaces.test.ts lib/fuzzy.test.ts lib/folder-picker.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts",+ "test": "node --experimental-strip-types --test lib/cite-markup.test.ts lib/graff-events.test.ts lib/acp.test.ts lib/sessions.test.ts lib/session-store.test.ts lib/follow-scroll.test.ts lib/prompt-queue.test.ts lib/prompt-queue-steer.test.ts lib/agents.test.ts lib/mcp-apps.test.ts lib/mermaid-plugin.test.ts lib/prompt-history.test.ts lib/attachments.test.ts lib/workspaces.test.ts lib/fuzzy.test.ts lib/folder-picker.test.ts lib/browser/annotations.test.ts lib/browser/url.test.ts","electron:build": "bash electron/build.sh","test:electron": "bun test electron/policy.test.cjs","test:desktop": "bun test lib ./electron/*.test.cjs",diff --git a/scripts/test-acp-steer.py b/scripts/test-acp-steer.pynew file mode 100644index 00000000..157ed1ba--- /dev/null+++ b/scripts/test-acp-steer.py@@ -0,0 +1,117 @@+#!/usr/bin/env python3+"""Offline ACP force-steer regression: cancel a live stream, then reuse the session."""+import http.server+import json+import os+from pathlib import Path+import queue+import subprocess+import sys+import tempfile+import threading+import time+++class Model(http.server.BaseHTTPRequestHandler):+ def log_message(self, *_args):+ pass++ def do_GET(self):+ body = json.dumps({"data": [{"id": "mock"}]}).encode()+ self.send_response(200)+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)++ def do_POST(self):+ self.rfile.read(int(self.headers["Content-Length"]))+ self.send_response(200)+ self.send_header("Content-Type", "text/event-stream")+ self.send_header("Connection", "close")+ self.end_headers()+ try:+ for _ in range(100):+ data = {"id": "mock", "choices": [{"index": 0,+ "delta": {"content": "working "}, "finish_reason": None}]}+ self.wfile.write(("data: " + json.dumps(data) + "\n\n").encode())+ self.wfile.flush()+ time.sleep(0.1)+ self.wfile.write(b"data: [DONE]\n\n")+ self.wfile.flush()+ except (BrokenPipeError, ConnectionResetError):+ pass+++def main():+ binary = str(Path(sys.argv[1] if len(sys.argv) > 1 else "zig-out/bin/graff").resolve())+ # LM Studio's built-in local endpoint; fail rather than reuse an occupied port.+ server = http.server.ThreadingHTTPServer(("127.0.0.1", 1234), Model)+ threading.Thread(target=server.serve_forever, daemon=True).start()+ try:+ with tempfile.TemporaryDirectory(prefix="graff-acp-steer-") as temp:+ env = {k: v for k, v in os.environ.items() if not k.endswith("_API_KEY")}+ config = Path(temp) / "mcp.json"+ config.write_text('{"mcpServers":{}}')+ env.update(HOME=temp, LMSTUDIO_API_KEY="local", GRAFF_NO_TELEMETRY="1",+ GRAFF_FLEET="off", GRAFF_NO_SMOLIFY="1",+ GRAFF_MCP_CONFIG=str(config), NO_COLOR="1")+ proc = subprocess.Popen([binary, "acp", "--model", "lmstudio", "--yolo"],+ cwd=temp, env=env, stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)+ events = queue.Queue()++ def read():+ for line in proc.stdout:+ try:+ events.put(json.loads(line))+ except ValueError:+ pass++ threading.Thread(target=read, daemon=True).start()++ def send(method, params, request_id=None):+ value = {"jsonrpc": "2.0", "method": method, "params": params}+ if request_id is not None:+ value["id"] = request_id+ proc.stdin.write(json.dumps(value) + "\n")+ proc.stdin.flush()++ def until(predicate, timeout=30):+ end = time.monotonic() + timeout+ while True:+ value = events.get(timeout=max(0.01, end - time.monotonic()))+ if predicate(value):+ return value+ if time.monotonic() >= end:+ raise AssertionError("ACP response deadline exceeded")++ try:+ send("initialize", {"protocolVersion": 1}, 1)+ until(lambda v: v.get("id") == 1)+ send("session/new", {"cwd": temp}, 2)+ sid = until(lambda v: v.get("id") == 2)["result"]["sessionId"]+ for request_id in (3, 4):+ send("session/prompt", {"sessionId": sid, "prompt": [+ {"type": "text", "text": f"Say hello {request_id}"}]}, request_id)+ until(lambda v: v.get("params", {}).get("update", {}).get(+ "sessionUpdate") == "agent_message_chunk")+ started = time.monotonic()+ send("session/cancel", {"sessionId": sid})+ result = until(lambda v: v.get("id") == request_id, timeout=5)+ assert result.get("result", {}).get("stopReason") == "cancelled", result+ print(f"PASS: live turn interrupted in {time.monotonic() - started:.2f}s")+ print("PASS: next turn streams in the same session after force-steer")+ finally:+ proc.stdin.close()+ try:+ proc.wait(timeout=5)+ except subprocess.TimeoutExpired:+ proc.terminate()+ proc.wait(timeout=5)+ finally:+ server.shutdown()+ server.server_close()+++if __name__ == "__main__":+ main()diff --git a/src/acp.zig b/src/acp.zigindex 1b0a62bd..0b18030a 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -93,6 +93,14 @@ fn liveBind(ctx: *anyopaque, session_id: []const u8) void {live.session_id = session_id;}+/// Per-turn context meter: the live occupancy estimate against the model's+/// wall, so the client can render remaining context without reading history.+fn liveMeter(ctx: *anyopaque) engine.Meter {+ const live: *LiveTurn = @ptrCast(@alignCast(ctx));+ const root = live.root;+ return .{ .used = root.effectiveContextTokens(), .window = root.provider.context };+}+/// The ACP user message: GUI `@[image]` attachments become native vision/// blocks — the same promotion mainloop and the REPL do — instead of the/// pixels never leaving the client and the model reading literal marker text.@@ -243,6 +251,7 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_.slash = liveSlash,.after_user = liveAfter,.bind_session = liveBind,+ .meter = liveMeter,.extra = liveModels,};while (true) {@@ -497,7 +506,7 @@ test "handleLine: turn failures map to a stopReason or a -32603" {w = .fixed(&buf);var failing: Dispatch = .{ .turn = failTurn, .ctx = undefined };try handleLine(&failing, a, &w, prompt);- try testing.expectEqualStrings("{\"jsonrpc\":\"2.0\",\"id\":1,\"error\":{\"code\":-32603,\"message\":\"ApiError\"}}\n", w.buffered());+ try testing.expectEqualStrings("{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"stopReason\":\"failed\"}}\n", w.buffered());}test "isAcpSubcommand claims only `acp`, and arms the stdout discipline" {diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex 445061bd..1baf1990 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -32,6 +32,11 @@ pub const TurnFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const upub const SlashFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror!?[]const u8;pub const AfterUserFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u8) void;pub const BindSessionFn = *const fn (ctx: *anyopaque, session_id: []const u8) void;+/// Optional per-turn context meter: used and window tokens for the+/// `gui_context_meter` update the client renders as a remaining-context ring.+/// Null when the embed has no live agent (pure in-process loop, tests).+pub const Meter = struct { used: u64, window: u64 };+pub const MeterFn = *const fn (ctx: *anyopaque) Meter;/// Vendor-method escape hatch: gets every request the core loop does not/// claim; returns true when it answered (false falls through to -32601).pub const ExtraFn = *const fn (ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Request) anyerror!bool;@@ -45,6 +50,7 @@ pub const Dispatch = struct {slash: ?SlashFn = null,after_user: ?AfterUserFn = null,bind_session: ?BindSessionFn = null,+ meter: ?MeterFn = null,extra: ?ExtraFn = null,};@@ -94,9 +100,24 @@ fn promptTurn(d: *Dispatch, arena: Allocator, w: *Io.Writer, req: proto.Request)return respond(w, req, .{ .stopReason = "cancelled" });if (err == error.RunBudgetExhausted)return respond(w, req, .{ .stopReason = "max_turn_requests" });+ if (err == error.ApiError)+ return respond(w, req, .{ .stopReason = "failed" });return respondError(w, req, err_internal, @errorName(err));};if (final.len > 0) try writeSessionUpdate(w, sid, final);+ if (d.meter) |meter| {+ // The context ring reads this, not the model catalog: used is the+ // live occupancy estimate, window the model's wall. No text, no PII.+ const m = meter(d.ctx);+ if (m.window > 0) try proto.writeNotification(w, "session/update", .{+ .sessionId = sid,+ .update = .{+ .sessionUpdate = "gui_context_meter",+ .used = m.used,+ .window = m.window,+ },+ });+ }const extra = if (extra_cancelled) |f| f() else false;const stop: []const u8 = if (cancel_flag.load(.acquire) or extra) "cancelled" else "end_turn";try respond(w, req, .{ .stopReason = stop });