Skip to content

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

Python

feat: add desktop agent coordination and refresh UI documentation

Rach Pradhanab71cadcf2aa
diff --git a/README.md b/README.md
index 2788025b..3036207b 100644
--- a/README.md
+++ b/README.md
@@ -33,6 +33,12 @@ curl -fsSL https://github.com/justrach/codegraff/releases/latest/download/instal
<p align="center"><sub>Prefer a window? Grab the <a href="#the-desktop-app">desktop app</a>. Then run <code>graff</code> and tell it what you need.</sub></p>
+**Evaluated on FrontierHarness tasks.** Graff includes a reproducible
+[FrontierHarness evaluation runner](graff-evals/frontier-harness/README.md),
+with recorded outcomes and explicit protocol differences. See
+[how we measure it](#how-we-measure-it) for the public task suite, grading,
+and the limits of comparisons with the published board.
+
## The desktop app
The current desktop preview uses Electron and embedded Chromium, with native
@@ -47,6 +53,16 @@ activity, and explicit working/finished/interrupted states keep the conversation
readable. Appearance includes White, Black, Website and the official CodeGraff
palette. Mention `$gui-theme` or `@gui-theme` in the GUI to create a custom theme.
+![CodeGraff Agents panel with local peers and a handoff request](docs/images/desktop-agents-codegraff.png)
+
+**Agents** brings Graff-to-Graff coordination into the GUI. See sessions in the
+current workspace or across the laptop, their published tasks and activity,
+and recent messages. Select a peer in the panel's composer to send a message
+or handoff request. Delivery is queued to the recipient's next step; browsing
+history does not consume their inbox. The optional profiler records anonymous
+per-agent resource measurements, with identities and message contents excluded
+from feedback exports. See the [Agents guide](docs/agents-panel.md).
+
![CodeGraff palette with a resizable Changes panel beside the conversation](docs/images/desktop-review-codegraff.png)
**Changes** shows local staged, unstaged and untracked edits, diffs, worktrees
@@ -271,7 +287,7 @@ deterministic task set. What it does not prove: anything about the live repo —
the `inhouse` fixtures are distilled shapes, not the codebase.
**Layer 2 — `frontier-harness/`.** It runs the same 30 tasks as
-[runta-dev/frontier-harness-eval](https://github.com/runta-dev/frontier-harness-eval)
+[FrontierHarness Eval](https://github.com/frontier-harness-eval/eval)
— 21 from Terminal-Bench 2.1 and 9 from DeepSWE — in Docker, under a protocol
that is deliberately not the same bench seat (see "What these runs are not"
below, and `PROTOCOL.md`). The board side is a pinned snapshot of the published
diff --git a/apps/native/app/api/agents/route.ts b/apps/native/app/api/agents/route.ts
new file mode 100644
index 00000000..c4f9b31f
--- /dev/null
+++ b/apps/native/app/api/agents/route.ts
@@ -0,0 +1,25 @@
+import path from 'node:path';
+import { existsSync } from 'node:fs';
+import { resolveRoot } from '@/lib/server-root';
+import type { AgentSnapshot } from '@/lib/agents';
+// Shared with Electron's opt-in profiler; all peer discovery stays in Graff.
+import { observeAgents, agentSampler } from '../../../electron/agent-observer.cjs';
+export const runtime = 'nodejs';
+export const dynamic = 'force-dynamic';
+const sample = agentSampler();
+export async function POST(req: Request) {
+ try {
+ if (Number(req.headers.get('content-length')) > 16384) return Response.json({ error: 'Message too large' }, { status: 413 });
+ 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 (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 === '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' } });
+ } catch (error) { return Response.json({ error: error instanceof Error ? error.message : 'Agents unavailable' }, { status: 502 }); }
+}
diff --git a/apps/native/app/visual-tests/agents/fixture.tsx b/apps/native/app/visual-tests/agents/fixture.tsx
new file mode 100644
index 00000000..b21d8006
--- /dev/null
+++ b/apps/native/app/visual-tests/agents/fixture.tsx
@@ -0,0 +1,20 @@
+'use client';
+import { useCallback, useState } from 'react';
+import AgentsPane from '@/components/site/AgentsPane';
+import { applyAppearance, type Appearance } from '@/lib/appearance';
+export default function Fixture() {
+ const [scenario, setScenario] = useState('connected');
+ const [sent, setSent] = useState('');
+ 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' }; }
+ 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 }] : []),
+ ], messages: [{ from_session: 'peer-a', to: 'peer-b', ts_ms: 1000, text: 'The navigation update is ready for review.', kind: 'handoff' }], delivery: 'Queued' };
+ }, [scenario]);
+ return <main className="flex h-screen flex-col bg-page text-ink">
+ <nav className="flex gap-3 p-3">{['connected', 'empty', 'error'].map(value => <button key={value} data-agent-case={value} onClick={() => setScenario(value)}>{value}</button>)}{['light', 'dark', 'codegraff'].map(theme => <button key={theme} data-agent-theme={theme} onClick={() => applyAppearance(theme as Appearance)}>{theme}</button>)}</nav>
+ <div className="flex min-h-0 flex-1 gap-3 p-3"><div className="flex-1 min-w-0 p-5"><h1>Workspace conversation</h1><p>The agent panel keeps coordination alongside your work.</p><output data-agent-sent className="break-all">{sent}</output></div><AgentsPane root="/demo/workspace" onClose={() => {}} request={request} /></div>
+ </main>;
+}
diff --git a/apps/native/app/visual-tests/agents/page.tsx b/apps/native/app/visual-tests/agents/page.tsx
new file mode 100644
index 00000000..fbbe2dbf
--- /dev/null
+++ b/apps/native/app/visual-tests/agents/page.tsx
@@ -0,0 +1,7 @@
+import { notFound } from 'next/navigation';
+import Fixture from './fixture';
+export const dynamic = 'force-dynamic';
+export default function Page() {
+ if (process.env.GRAFF_VISUAL_TESTS !== '1') notFound();
+ return <Fixture />;
+}
diff --git a/apps/native/components/primitives/CodeGraffMark.tsx b/apps/native/components/primitives/CodeGraffMark.tsx
new file mode 100644
index 00000000..cb4d1749
--- /dev/null
+++ b/apps/native/components/primitives/CodeGraffMark.tsx
@@ -0,0 +1,6 @@
+/** The compact ink-circle/code mark inherits the active theme's ink color. */
+export default function CodeGraffMark({ size = 20 }: { size?: number }) {
+ return <svg data-codegraff-mark aria-hidden="true" width={size} height={size} viewBox="0 0 32 32" fill="none">
+ <use href="/codegraff-mark.svg#mark" />
+ </svg>;
+}
diff --git a/apps/native/components/primitives/SidebarNav.tsx b/apps/native/components/primitives/SidebarNav.tsx
index b948aa13..78ea6731 100644
--- a/apps/native/components/primitives/SidebarNav.tsx
+++ b/apps/native/components/primitives/SidebarNav.tsx
@@ -13,11 +13,11 @@ import {
IconMagnifyingGlass,
IconChat,
IconPlusMedium,
- IconPopsicle2,
IconSettingsGear1,
IconSidebarLeftArrow,
IconSidebarLeftOpen,
} from "@/lib/icons";
+import CodeGraffMark from "./CodeGraffMark";
import GlideMenu from "@/components/primitives/GlideMenu";
import { monogram } from "@/lib/workspaces";
@@ -342,7 +342,7 @@ export default function SidebarNav({
className="sidebar-workspace-control absolute left-2 top-1 flex h-8 w-[188px] items-center rounded-[8px] px-2 text-left transition-[background-color,transform] duration-100 hover:bg-hover-2 active:scale-[0.99]"
>
<span className="sidebar-logo flex size-5 shrink-0 items-center justify-center text-ink">
- <IconPopsicle2 size={18} />
+ <CodeGraffMark size={20} />
</span>
<span className="sidebar-copy ml-1.5 min-w-0 flex-1 truncate text-[14px] font-medium text-ink-2" title={workspace?.path}>
{workspace?.name ?? WORKSPACE.name}
diff --git a/apps/native/components/site/AgentsPane.tsx b/apps/native/components/site/AgentsPane.tsx
new file mode 100644
index 00000000..2316f345
--- /dev/null
+++ b/apps/native/components/site/AgentsPane.tsx
@@ -0,0 +1,78 @@
+'use client';
+import { useEffect, useRef, useState } from 'react';
+import { agentKey, agentName, agentRequest, type AgentSnapshot, type LocalAgent } from '@/lib/agents';
+import ResizableReviewPane from './ResizableReviewPane';
+
+export default function AgentsPane({ root, onClose, request = agentRequest }: { root?: string; onClose(): void; request?: typeof agentRequest }) {
+ const [scope, setScope] = useState('workspace');
+ 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 [refresh, setRefresh] = useState(0);
+ const input = useRef<HTMLTextAreaElement>(null);
+ useEffect(() => { setRecipient(null); setNotice(''); setText(''); }, [root]);
+ useEffect(() => {
+ let disposed = false, timer: ReturnType<typeof setTimeout>;
+ const controller = new AbortController();
+ setSnapshot(null); setError('');
+ const poll = async () => {
+ try {
+ if (document.visibilityState !== 'hidden') {
+ const data = await request(root, { action: 'list', scope }, controller.signal);
+ if (!disposed) { setSnapshot(data); setError(''); }
+ }
+ } catch (e) { if (!disposed) setError(e instanceof Error ? e.message : 'Agents unavailable'); }
+ finally { if (!disposed) timer = setTimeout(poll, 5000); }
+ };
+ void poll();
+ return () => { disposed = true; controller.abort(); clearTimeout(timer); };
+ }, [root, scope, refresh, request]);
+ 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 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);
+ } catch (e) { setNotice(e instanceof Error ? e.message : 'Message could not be queued'); }
+ finally { setSending(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>
+ <div 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'}`}>
+ <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">
+ <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(); }}>
+ <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>
+ </aside>
+ </ResizableReviewPane>;
+}
diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsx
index 7fc4e5fd..41c4da6b 100644
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@ -3,6 +3,8 @@
import { createTurnPainter } from "@/lib/turn-painter";
import { useQuietSettings } from "./useQuietSettings";
import reviewStyles from "./ChangesPane.module.css";
+import AgentsPane from "./AgentsPane";
+import { newPageToken, newSessionName, type Chat, type Msg } from "./harness-types";
import ChangesPane from "./ChangesPane";
import { useBrowserVisibility } from "./useBrowserVisibility";
import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
@@ -57,29 +59,6 @@ const MAX_COLUMNS = 4;
/** Rows the sidebar previews; the library pages the rest. */
const SIDEBAR_PAGE = 12;
-type Msg =
- | { id: number; role: "user"; text: string }
- | { id: number; role: "assistant"; turn: AssistantTurn };
-
-/** `model` is what this tab's own agent was spawned with; the harness-level
- * model is only the default a new tab inherits. `cwd` is the workspace the
- * tab's agent runs in — fixed at spawn, like the model. */
-type Chat = { id: number; title: string | null; messages: Msg[]; model?: string; session?: string; cwd?: string;
- /** The model named this tab from its first prompt: the session poller,
- * which reads graff's own saved title, must leave it alone. */
- titledByModel?: boolean };
-
-function newPageToken(): string {
- return Math.random().toString(36).slice(2, 10);
-}
-
-/** A fresh tab's graff session name. Not `session-…`: that prefix is what the
- * REPL's auto-title renames, and a tab needs a name that stays put so the
- * sidebar row and the running agent keep pointing at the same file. */
-function newSessionName(): string {
- return `native-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
-}
-
export default function GraffHarness() {
const [chats, setChats] = useState<Chat[]>([{ id: 1, title: null, messages: [] }]);
const [activeId, setActiveId] = useState(1);
@@ -100,6 +79,7 @@ export default function GraffHarness() {
// resolution decides, and `current` from that call re-points the picker.
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 [filesOpen, setFilesOpen] = useState(false);
const [fileRequest, setFileRequest] = useState<{ path: string; n: number; changes?: boolean } | null>(null);
const fileReqRef = useRef(0);
@@ -333,6 +313,7 @@ export default function GraffHarness() {
}, []);
const openChanges = useCallback(() => {
+ setAgentsOpen(false);
setBrowserOpen(false); setConversationsOpen(false);
setFilesOpen(true);
setFileRequest({ path: "", n: (fileReqRef.current += 1), changes: true });
@@ -1010,6 +991,7 @@ export default function GraffHarness() {
<span className="rounded-full bg-accent px-1.5 text-[10px] font-semibold text-white tabular-nums">{pinCount}</span>
)}
</button>
+ <button aria-label="Show agents" aria-pressed={agentsOpen} onClick={() => { setAgentsOpen(!agentsOpen); setFilesOpen(false); setBrowserOpen(false); setConversationsOpen(false); }} 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</span></button>
<ThemeToggle />
</div>
</div>
@@ -1170,6 +1152,7 @@ export default function GraffHarness() {
</>
)}
+ {agentsOpen && !filesOpen && !browserOpen && !conversationsOpen && <AgentsPane key={chatCwd} root={chatCwd} onClose={() => setAgentsOpen(false)} />}
{filesOpen && !conversationsOpen && (fileRequest?.changes ? <ChangesPane root={chatThread.cwd} onClose={() => setFilesOpen(false)} /> : <FilesPane root={chatThread.cwd} requested={fileRequest} onClose={() => setFilesOpen(false)} />)}
{browserOpen && !conversationsOpen && (
diff --git a/apps/native/components/site/ResizableReviewPane.tsx b/apps/native/components/site/ResizableReviewPane.tsx
index 02705bc7..07ee1552 100644
--- a/apps/native/components/site/ResizableReviewPane.tsx
+++ b/apps/native/components/site/ResizableReviewPane.tsx
@@ -2,9 +2,8 @@
import { useLayoutEffect, useRef, useState, type ReactNode } from "react";
import styles from "./ChangesPane.module.css";
-const storageKey = "graff.changes.width";
-const defaultWidth = 650;
-export default function ResizableReviewPane({ children }: { children: ReactNode }) {
+export default function ResizableReviewPane({ children, label = "changes", defaultWidth = 650 }: { children: ReactNode; label?: string; defaultWidth?: number }) {
+ const storageKey = `graff.${label}.width`;
const frame = useRef<HTMLDivElement>(null);
const drag = useRef<{ x: number; width: number } | null>(null);
const [preferred, setPreferred] = useState(defaultWidth);
@@ -35,7 +34,7 @@ export default function ResizableReviewPane({ children }: { children: ReactNode
return () => { document.body.style.cursor = cursor; document.body.style.userSelect = userSelect; };
}, [dragging]);
return <div ref={frame} className="relative flex min-h-0 min-w-0 shrink-0" style={{ width }}>
- <div role="separator" aria-label="Resize changes panel" aria-orientation="vertical" tabIndex={0}
+ <div role="separator" aria-label={`Resize ${label} panel`} aria-orientation="vertical" tabIndex={0}
aria-valuemin={Math.round(minimum)} aria-valuemax={Math.round(maximum)} aria-valuenow={Math.round(width)}
title="Drag to resize · Double-click to reset" className={styles.resize} data-dragging={dragging || undefined}
onPointerDown={event => {
diff --git a/apps/native/components/site/harness-types.ts b/apps/native/components/site/harness-types.ts
new file mode 100644
index 00000000..e59f8934
--- /dev/null
+++ b/apps/native/components/site/harness-types.ts
@@ -0,0 +1,24 @@
+import type { AssistantTurn } from "@/lib/acp";
+export type Msg =
+ | { id: number; role: "user"; text: string }
+ | { id: number; role: "assistant"; turn: AssistantTurn };
+
+/** `model` is what this tab's own agent was spawned with; the harness-level
+ * model is only the default a new tab inherits. `cwd` is the workspace the
+ * tab's agent runs in — fixed at spawn, like the model. */
+export type Chat = { id: number; title: string | null; messages: Msg[]; model?: string; session?: string; cwd?: string;
+ /** The model named this tab from its first prompt: the session poller,
+ * which reads graff's own saved title, must leave it alone. */
+ titledByModel?: boolean };
+
+export function newPageToken(): string {
+ return Math.random().toString(36).slice(2, 10);
+}
+
+/** A fresh tab's graff session name. Not `session-…`: that prefix is what the
+ * REPL's auto-title renames, and a tab needs a name that stays put so the
+ * sidebar row and the running agent keep pointing at the same file. */
+export function newSessionName(): string {
+ return `native-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 6)}`;
+}
+
diff --git a/apps/native/electron/agent-observer.cjs b/apps/native/electron/agent-observer.cjs
new file mode 100644
index 00000000..4237625c
--- /dev/null
+++ b/apps/native/electron/agent-observer.cjs
@@ -0,0 +1,54 @@
+const { spawn, execFile } = require('node:child_process');
+const { promisify } = require('node:util');
+const { performance } = require('node:perf_hooks');
+const { cpuMilliseconds } = require('./process-metrics.cjs');
+
+// The observer exits on stdin EOF. It never starts a model, MCP or a session.
+function observeAgents(binary, root, params = {}) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(binary, [], { cwd: root, env: { ...process.env, GRAFF_AGENT_OBSERVER: '1' }, stdio: ['pipe', 'pipe', 'ignore'] });
+ let data = '', settled = false;
+ const done = (error, value) => { if (settled) return; settled = true; clearTimeout(timer); if (error) child.kill(); error ? reject(error) : resolve(value); };
+ const timer = setTimeout(() => done(new Error('Agent observer timed out')), 8000);
+ child.on('error', () => done(new Error('Agent observer could not start')));
+ child.stdin.on('error', () => done(new Error('Agent observer disconnected')));
+ child.stdout.on('data', chunk => {
+ data += chunk;
+ if (data.length > 2 * 1024 * 1024) done(new Error('Agent snapshot exceeds limit'));
+ });
+ child.on('close', () => {
+ if (settled) return;
+ try {
+ const reply = JSON.parse(data.trim());
+ if (reply.error) done(new Error(reply.error.message));
+ else if (!reply.result) done(new Error('Invalid agent snapshot'));
+ else done(null, reply.result);
+ } catch { done(new Error('Agent snapshot unavailable; rebuild the Graff binary')); }
+ });
+ child.stdin.end(JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'graff/agents', params }) + '\n');
+ });
+}
+
+function agentSampler() {
+ let previous = new Map();
+ return async agents => {
+ if (!agents.length || process.platform !== 'darwin') { previous.clear(); return agents.map(a => ({ ...a, resources: null })); }
+ // Root-process measurements: shared workers/GPU cannot be attributed safely.
+ const { stdout } = await promisify(execFile)('ps', ['-axo', 'pid=,rss=,time=,lstart='], { timeout: 3000, maxBuffer: 2 * 1024 * 1024, env: { ...process.env, LC_ALL: 'C' } });
+ const rows = new Map(stdout.trim().split('\n').map(line => {
+ const [pid, rss, time, ...start] = line.trim().split(/\s+/);
+ return [Number(pid), { rss: Number(rss), time: cpuMilliseconds(time || '0'), start: Date.parse(start.join(' ')) }];
+ }));
+ const at = performance.now(), next = new Map();
+ const result = agents.map(agent => {
+ const row = rows.get(agent.pid), key = `${agent.pid}:${agent.startId}`;
+ // OS start second must still match the microsecond identity verified by Graff.
+ if (!row || Math.floor(Number(agent.startId) / 1000000) !== Math.floor(row.start / 1000)) return { ...agent, resources: null };
+ const last = previous.get(key);
+ next.set(key, { time: row.time, at });
+ return { ...agent, resources: { rssMiB: row.rss / 1024, cpuPercent: last && at > last.at ? Math.max(0, row.time - last.time) / (at - last.at) * 100 : null } };
+ });
+ previous = next; return result;
+ };
+}
+module.exports = { observeAgents, agentSampler };
diff --git a/apps/native/electron/agents-visual.cjs b/apps/native/electron/agents-visual.cjs
new file mode 100644
index 00000000..da97f67a
--- /dev/null
+++ b/apps/native/electron/agents-visual.cjs
@@ -0,0 +1,36 @@
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+async function runAgentVisuals({ win, origin, output }) {
+ const js = source => win.webContents.executeJavaScript(source);
+ 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();
+ 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);
+ 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}})()`);
+ 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.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 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()`);
+ await wait(`document.body.textContent.includes('Queued · Graff')`);
+ const sent = JSON.parse(await js(`document.querySelector('[data-agent-sent]').textContent`));
+ assert.equal(sent.target, 'peer-b'); assert.equal(sent.startId, '12'); assert.equal(sent.kind, 'message');
+ await js(`document.querySelector('[data-agent-case="empty"]').click()`);
+ await wait(`document.body.textContent.includes('No connected Graffs')`);
+ 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.');
+}
+module.exports = { runAgentVisuals };
diff --git a/apps/native/electron/gallery-fixture.cjs b/apps/native/electron/gallery-fixture.cjs
index 1d8c11da..6662c40a 100644
--- a/apps/native/electron/gallery-fixture.cjs
+++ b/apps/native/electron/gallery-fixture.cjs
@@ -9,6 +9,10 @@ function installGalleryFixture() {
window.fetch = async (input, options) => {
const url = new URL(typeof input === 'string' ? input : input.url, location.origin);
if (!url.pathname.startsWith('/api/')) return original(input, options);
+ if (url.pathname === '/api/agents') return json({ agents: [
+ { session: 'navigation', startId: '1', pid: 1, title: 'Refine navigation', task: 'Improve focus order and keyboard shortcuts', workspace: root, status: 'working', resources: null },
+ { session: 'review', startId: '2', pid: 2, title: 'Review accessibility', task: 'Check the updated sidebar', workspace: root, status: 'waiting', resources: null }
+ ], messages: [{ from_session: 'navigation', to: 'review', text: 'The sidebar update is ready. Please check keyboard navigation.', kind: 'handoff', ts_ms: 1788652800000 }], delivery: 'Queued' });
if (url.pathname === '/api/models') return json(catalog);
if (url.pathname === '/api/sessions') return json({ cwd: root, sessions: [], total: 0, nextCursor: null });
if (url.pathname === '/api/themes') return json({ themes: [], issues: [] });
diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjs
index 3859fde2..5a0d1596 100644
--- a/apps/native/electron/main.cjs
+++ b/apps/native/electron/main.cjs
@@ -11,6 +11,7 @@ const { desktopConfig } = require('./desktop-config.cjs');
const { browserAction } = require('./browser-actions.cjs');
const { Profiler } = require('./profiler.cjs');
const { rendererSample } = require('./renderer-profile.cjs');
+const { observeAgents, agentSampler } = require('./agent-observer.cjs');
const { chromiumSample } = require('./hardware-profile.cjs');
const fs = require('node:fs/promises');
@@ -61,9 +62,11 @@ app.whenReady().then(async () => {
});
computer = new ComputerUse(resources, win);
const sampleTree = intervalSampler(process.pid, () => browser.liveCount);
+ const sampleAgents = agentSampler();
profiler = new Profiler(async () => {
- const [tree, renderer] = await Promise.all([sampleTree(), rendererSample(win.webContents).catch(() => ({}))]);
- return { ...tree, ...renderer, ...chromiumSample(app.getAppMetrics()) };
+ const [tree, renderer, agents] = await Promise.all([sampleTree(), rendererSample(win.webContents).catch(() => ({})),
+ observeAgents(path.join(resources, "graff"), root, { scope: "device", history: "off" }).then(data => sampleAgents(data.agents)).catch(() => [])]);
+ return { ...tree, ...renderer, agents, ...chromiumSample(app.getAppMetrics()) };
}, enabled => {
if (!enabled) void rendererSample(win.webContents, false).catch(() => {});
if (win.isDestroyed()) return;
diff --git a/apps/native/electron/performance-scenarios.cjs b/apps/native/electron/performance-scenarios.cjs
index b2f9818c..e262f63a 100644
--- a/apps/native/electron/performance-scenarios.cjs
+++ b/apps/native/electron/performance-scenarios.cjs
@@ -1,4 +1,5 @@
const fs = require('node:fs');
+const assert = require('node:assert/strict');
const path = require('node:path');
const { app, BrowserWindow, ipcMain } = require('electron');
const { Profiler } = require('./profiler.cjs');
@@ -64,7 +65,11 @@ async function runPerformance({ win: fixtureWindow, origin, output }) {
await js(`document.querySelector('[aria-label="Review workspace changes"]').click()`);
await wait(`document.querySelector('[aria-label="File diff"]')?.getAttribute('aria-busy')==='false'`);
await capture('desktop-review-codegraff.png');
- await js(`document.querySelector('[aria-label="Close changes"]').click(); window.galleryBenchmark=true`);
+ await js(`document.querySelector('[aria-label="Close changes"]').click(); document.querySelector('[aria-label="Show agents"]').click()`);
+ await wait(`document.querySelector('[aria-label="Agents panel"]')?.textContent.includes('Refine navigation')`);
+ assert.ok(await js(`!!document.querySelector('.sidebar-logo [data-codegraff-mark] use')`));
+ await capture('desktop-agents-codegraff.png');
+ await js(`document.querySelector('[aria-label="Close agents"]').click(); window.galleryBenchmark=true`);
console.log('Performance: stream');
profiler.mark('candidate');
await send('Stream the demonstration transcript.');
diff --git a/apps/native/electron/profiler.cjs b/apps/native/electron/profiler.cjs
index 6daea5d9..70265af8 100644
--- a/apps/native/electron/profiler.cjs
+++ b/apps/native/electron/profiler.cjs
@@ -4,9 +4,9 @@ const OPTIONAL = ['lcpMs', 'fcpMs', 'interactionMaxMs', 'layoutShift', 'renderer
const EVENTS = new Set(['ui-ready', 'page-navigation', 'page-loaded', 'renderer-crash', 'browser-action', 'computer-action', 'action-failed', 'renderer-long-task']);
const finite = value => Number.isFinite(value) ? Math.round(value * 100) / 100 : 0;
class Profiler {
- constructor(sample, notify = () => {}, hardware = () => ({})) { this.sample = sample; this.hardware = hardware; this.notify = notify; this.timer = null; this.samples = []; this.events = []; this.phase = 'baseline'; this.started = 0; this.busy = false; this.generation = 0; }
+ constructor(sample, notify = () => {}, hardware = () => ({})) { this.sample = sample; this.hardware = hardware; this.notify = notify; this.timer = null; this.samples = []; this.events = []; this.phase = 'baseline'; this.started = 0; this.busy = false; this.generation = 0; this.agentSlots = new Map(); }
async start() {
- this.stop(); this.samples = []; this.events = []; this.started = performance.now(); this.phase = 'baseline';
+ this.stop(); this.agentSlots.clear(); this.samples = []; this.events = []; this.started = performance.now(); this.phase = 'baseline';
this.active = true; this.notify(true); this.expected = performance.now() + 2000;
this.timer = setInterval(() => {
const lag = Math.max(0, performance.now() - this.expected); this.expected = performance.now() + 2000;
@@ -23,7 +23,17 @@ class Profiler {
const raw = await this.sample();
if (!this.active || generation !== this.generation) return;
// Construct every field explicitly. Never serialize process names, URLs or raw metrics objects.
- this.samples.push({ elapsedMs: finite(performance.now() - this.started), phase,
+ const agents = (Array.isArray(raw.agents) ? raw.agents : []).slice(0, 16).flatMap(agent => {
+ if (!agent || !agent.resources) return [];
+ const key = `${agent.pid}:${agent.startId}`;
+ if (!this.agentSlots.has(key)) {
+ if (this.agentSlots.size >= 128) return [];
+ this.agentSlots.set(key, this.agentSlots.size + 1);
+ }
+ return [{ slot: this.agentSlots.get(key), rssMiB: Number.isFinite(agent.resources.rssMiB) ? Math.max(0, finite(agent.resources.rssMiB)) : null,
+ cpuPercent: Number.isFinite(agent.resources.cpuPercent) ? Math.max(0, finite(agent.resources.cpuPercent)) : null }];
+ });
+ this.samples.push({ agents, elapsedMs: finite(performance.now() - this.started), phase,
rssMiB: finite(raw.rssMiB), cpuPercent: finite(raw.cpuPercent), processes: finite(raw.processes),
browsers: finite(raw.browsers), mainLoopLagMs: finite(lag),
...Object.fromEntries(OPTIONAL.map(key => [key, Number.isFinite(raw[key]) ? Math.max(0, finite(raw[key])) : null])) });
@@ -45,7 +55,7 @@ class Profiler {
};
const baseline = summary('baseline'), candidate = summary('candidate');
return { schema: 'codegraff-performance-v2', acceleration: accelerationStatus(this.hardware()), gpuUtilizationPercent: null, privacy: 'Measurements only; no content, paths, URLs, identifiers, screenshots or free-form text.',
- measurement: 'RSS sums the app process tree and may count shared pages twice. CPU is interval process-tree CPU time; short-lived exited children can be missed and the first sample is zero. Main loop lag is timer delay; renderer long tasks are durations only. Paint timings are document-relative (reload during recording for a fresh LCP); interactionMaxMs is the slowest observed interaction, not INP. Layout shift sums recording entries, not session-window CLS. GPU process CPU/RSS are host resources, not GPU utilization or VRAM; shared Apple Silicon memory overlaps RSS. Missing measurements are null.',
+ measurement: 'RSS sums the app process tree and may count shared pages twice. CPU is interval process-tree CPU time; short-lived exited children can be missed and the first sample is zero. Main loop lag is timer delay; renderer long tasks are durations only. Paint timings are document-relative (reload during recording for a fresh LCP); interactionMaxMs is the slowest observed interaction, not INP. Layout shift sums recording entries, not session-window CLS. GPU process CPU/RSS are host resources, not GPU utilization or VRAM; shared Apple Silicon memory overlaps RSS. Per-agent slots are anonymous within one recording and measure only the Graff root process; shared children and GPU are not attributed. Missing measurements are null.',
status: this.status(), baseline, candidate,
comparison: baseline.samples && candidate.samples ? { meanRssMiBDelta: finite(candidate.meanRssMiB - baseline.meanRssMiB), meanCpuPercentDelta: finite(candidate.meanCpuPercent - baseline.meanCpuPercent) } : null,
samples: this.samples.map(row => ({ ...row })), events: this.events.map(row => ({ ...row })) };
diff --git a/apps/native/electron/profiler.test.cjs b/apps/native/electron/profiler.test.cjs
index 95c22165..5c971580 100644
--- a/apps/native/electron/profiler.test.cjs
+++ b/apps/native/electron/profiler.test.cjs
@@ -66,3 +66,12 @@ test('renderer observers stay off until recording and disconnect on stop', () =>
collectRendererMetrics(false); assert.ok(observers.every(observer => observer.disconnected));
} finally { collectRendererMetrics(false); globalThis.PerformanceObserver = originalObserver; globalThis.document = originalDocument; }
});
+test('agent resources use recording-local slots and exclude messages and identities', async () => {
+ let startId = 'secret-start';
+ const p = new Profiler(async () => ({ agents: [{ pid: 92741, startId, session: 'SECRET', title: 'PRIVATE', workspace: '/Users/private', messages: ['PRIVATE'], resources: { rssMiB: 12, cpuPercent: null, text: 'SECRET' } }] }));
+ await p.start(); await p.capture(0);
+ startId = 'reused-pid'; await p.capture(0); p.stop();
+ assert.deepEqual(p.report().samples.map(s => s.agents[0]), [{ slot: 1, rssMiB: 12, cpuPercent: null }, { slot: 1, rssMiB: 12, cpuPercent: null }, { slot: 2, rssMiB: 12, cpuPercent: null }]);
+ assert.doesNotMatch(JSON.stringify(p.report()), /SECRET|PRIVATE|92741|secret-start|reused-pid|\/Users/);
+ await p.start(); p.stop(); assert.equal(p.report().samples[0].agents[0].slot, 1);
+});
diff --git a/apps/native/electron/smoke.cjs b/apps/native/electron/smoke.cjs
index 69ecc0a0..baa51e42 100644
--- a/apps/native/electron/smoke.cjs
+++ b/apps/native/electron/smoke.cjs
@@ -86,6 +86,13 @@ async function run({ win, browser, automation, backend, metrics, activity, compu
assert.match(review.result.status, /review.txt/);
const diff = await win.webContents.executeJavaScript(`fetch('/api/acp',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({chat:'electron-smoke',method:'graff/changes',params:{action:'diff',path:'review.txt'}})}).then(r=>r.json())`);
assert.match(diff.result.diff, /Shared review fixture/);
+ const agents = await win.webContents.executeJavaScript(`fetch('/api/agents',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({root:${JSON.stringify(cwd)},action:'list',scope:'workspace'})}).then(async r=>({status:r.status,body:await r.json()}))`);
+ assert.equal(agents.status, 200, JSON.stringify(agents.body));
+ assert.ok(Array.isArray(agents.body.agents));
+ assert.ok(agents.body.agents.length > 0, 'Observer sees the temporary ACP session');
+ const extension = await win.webContents.executeJavaScript(`fetch('/api/acp',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({chat:'electron-smoke',method:'graff/agents',params:{action:'list',history:'off'}})}).then(r=>r.json())`);
+ assert.ok(Array.isArray(extension.result.agents));
+ report.agents = 'packaged observer and live ACP expose peer discovery; no messages sent';
report.review = 'real ACP shared status and untracked diff';
report.settings = 'real ACP effort and fast commands updated harness state';
diff --git a/apps/native/electron/visual-tests.cjs b/apps/native/electron/visual-tests.cjs
index e7637a33..7d470563 100644
--- a/apps/native/electron/visual-tests.cjs
+++ b/apps/native/electron/visual-tests.cjs
@@ -55,6 +55,7 @@ app.whenReady().then(async () => {
results.push(`${theme}/${name}`);
}
}
+ await require('./agents-visual.cjs').runAgentVisuals({ win, origin, output });
if (process.env.GRAFF_PERFORMANCE_TESTS) await require('./performance-scenarios.cjs').runPerformance({ win, origin, output });
assert.deepEqual(apiRequests, [], 'Visual fixtures must not call the engine or model APIs');
fs.writeFileSync(path.join(output, 'results.json'), JSON.stringify({ passed: results, apiRequests }, null, 2));
diff --git a/apps/native/lib/agents.ts b/apps/native/lib/agents.ts
new file mode 100644
index 00000000..a86b9a85
--- /dev/null
+++ b/apps/native/lib/agents.ts
@@ -0,0 +1,12 @@
+export type LocalAgent = { session: string; startId: string; pid: number; title: string; task: string; workspace: string; status: string;
+ resources?: { rssMiB: number; cpuPercent: number | null } | null };
+export type PeerMessage = { from_session: string; to: string; text: string; ts_ms: number; from_user: boolean; kind?: string };
+export type AgentSnapshot = { agents: LocalAgent[]; messages: PeerMessage[]; delivery: string };
+export const agentKey = (agent: LocalAgent) => `${agent.pid}:${agent.startId}`;
+export const agentName = (agent: LocalAgent) => agent.title || agent.session || 'Untitled Graff';
+export async function agentRequest(root: string | undefined, params: Record<string, unknown>, signal?: AbortSignal) {
+ const res = await fetch('/api/agents', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ root, ...params }), signal });
+ const body = await res.json();
+ if (!res.ok) throw new Error(body.error || 'Agents unavailable');
+ return body;
+}
diff --git a/apps/native/public/codegraff-mark.svg b/apps/native/public/codegraff-mark.svg
new file mode 100644
index 00000000..c87d8986
--- /dev/null
+++ b/apps/native/public/codegraff-mark.svg
@@ -0,0 +1,9 @@
+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" fill="none">
+ <title>CodeGraff</title>
+ <g id="mark">
+ <!-- An open ink circle around code brackets, simplified for small sizes. -->
+ <path fill="currentColor" d="M27.2 8.5C23.9 3.4 17.4 1.9 11.9 4.1 5.8 6.5 2.9 13.3 4.7 19.5 6.5 25.5 12.9 29.1 19 27.6c4.2-1 7.2-3.7 8.7-7.3-1 5.5-5.2 9.8-10.9 10.2C9.1 31.2 2.1 25.6 1.6 18 1 10.1 6.1 3.1 13.7 1.8c5.7-1 11.3 1.6 13.5 6.7Z"/>
+ <path stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" d="m12 12-4 4 4 4m9-8 4 4-4 4m-3-10-3 12"/>
+ <path fill="currentColor" d="M28 16h2v2h-2zm1-5h2v2h-2zm-3-1h1.5v1.5H26z"/>
+ </g>
+</svg>
diff --git a/docs/adr/0076-local-agent-panel.md b/docs/adr/0076-local-agent-panel.md
new file mode 100644
index 00000000..c1b66754
--- /dev/null
+++ b/docs/adr/0076-local-agent-panel.md
@@ -0,0 +1,27 @@
+# 0076. Local agent coordination stays in Graff
+
+Status: accepted
+
+## Decision
+
+The GUI defaults to peers in the current worktree, with an explicit device-wide
+view. The `graff/agents` ACP extension exposes verified live peers, bounded recent
+room history, and explicit addressed human messages. Discovery compares process
+start identities, not PID alone. Old peers without a verifiable identity are
+excluded. Legacy activity is shown as connected, never inferred from CPU usage.
+
+A lightweight observer entry point bypasses provider, MCP and session startup.
+It serves the same extension independently of a busy model turn. It creates no
+presence entry and does not read or advance a session's inbox cursor. Inspection
+is bounded to recent complete log records. Message submission revalidates the
+selected recipient's start identity; it never silently retargets a stale choice.
+
+Delivery is queued to the recipient's next step boundary. A handoff is an explicit
+coordination request, not a claim that task ownership transferred or a peer read
+or accepted the message. No automatic messages are sent by opening the panel.
+
+Per-peer resource sampling measures the Graff process only. Shared workers and
+GPU usage cannot be reliably attributed. Feedback exports use anonymous slots
+scoped to a single bounded recording and numeric resources only, never peer
+names, tasks, paths, PIDs, process identities or message content. Recording and
+export remain opt-in, with no automatic upload.
diff --git a/docs/adr/README.md b/docs/adr/README.md
index 2528c99c..8144b3b0 100644
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@ -86,6 +86,7 @@ record only when you need the evidence or the edge cases.
| [0073](0073-acp-stream-and-shared-review.md) | One ACP stdout reader routes responses; shared review reads Git working trees without inferring edit authorship. |
| [0074](0074-gui-skills-and-portable-themes.md) | Explicit desktop skills and validated themes live in the GUI; selected instructions travel over ACP. |
| [0075](0075-acp-adapter-and-desktop-measurements.md) | ACP presentation decoding is separate from session lifecycle; desktop performance uses bounded workload measurements and default Chromium acceleration. |
+| [0076](0076-local-agent-panel.md) | Verified local peer discovery, non-consuming history, explicit queued DMs and anonymous profiler slots. |
## When to write one
diff --git a/docs/agents-panel.md b/docs/agents-panel.md
new file mode 100644
index 00000000..488db761
--- /dev/null
+++ b/docs/agents-panel.md
@@ -0,0 +1,43 @@
+# Agents panel
+
+Open **Agents** in the desktop toolbar. The panel starts with **This workspace**;
+choose **All local Graffs** to include sessions in other workspaces on the same
+computer. Drag the divider to resize it.
+
+Select a Graff to address the panel's composer, then choose **Message** or
+**Handoff request** and press **Send to Graff**. Sending queues a message for the
+recipient's next step. It does not start a model turn, wake an idle session,
+confirm that a message was read, or automatically transfer task ownership.
+Closing the panel stops its refreshes. Opening it never sends messages.
+
+Activity is published by current Graff builds. Older builds show **Connected**.
+Task descriptions appear when a peer has published a goal. Recent messages are
+read independently of inbox delivery, so inspecting them does not consume them.
+
+On macOS, each peer shows its Graff process RSS and interval CPU measurement.
+Shared child processes and GPU resources are not attributed to individual peers.
+The optional Performance recording includes anonymous per-peer numeric samples.
+Feedback reports exclude names, tasks, process identities and messages; exporting
+writes a local report and does not upload it.
+
+## ACP
+
+`graff/agents` supports:
+
+- `{ "action": "list", "scope": "workspace" }` for peers and recent messages.
+- `{ "action": "list", "scope": "device", "history": "off" }` for local peers only.
+- `{ "action": "send", "target": "<session>", "startId": "<startId>", "kind": "message", "text": "..." }` for an explicit human message. `kind` can also be `handoff`.
+
+Use the session and start identity from a fresh list response. Changed or
+ambiguous recipients fail instead of silently targeting another process.
+
+The desktop's short-lived observer runs the same vendor extension before model,
+credential, MCP and session startup. It remains available during another Graff's
+active turn. It accepts only local peer requests and creates no session.
+
+## Offline verification
+
+`bun run test:visual` in the desktop package exercises theme rendering, panel
+bounds, scope switching, recipient selection, queued sends, disconnection and
+errors using synthetic peers. The packaged smoke check verifies real read-only
+ACP discovery. Unit tests send only to isolated temporary mailboxes.
diff --git a/docs/images/desktop-agents-codegraff.png b/docs/images/desktop-agents-codegraff.png
new file mode 100644
index 00000000..dc297f36
Binary files /dev/null and b/docs/images/desktop-agents-codegraff.png differ
diff --git a/docs/images/desktop-chat-dark.png b/docs/images/desktop-chat-dark.png
index c9e41a1e..a7df4a19 100644
Binary files a/docs/images/desktop-chat-dark.png and b/docs/images/desktop-chat-dark.png differ
diff --git a/docs/images/desktop-review-codegraff.png b/docs/images/desktop-review-codegraff.png
index eaf3c9bf..7601f865 100644
Binary files a/docs/images/desktop-review-codegraff.png and b/docs/images/desktop-review-codegraff.png differ
diff --git a/src/acp.zig b/src/acp.zig
index 7d7723ca..5d5920f2 100644
--- a/src/acp.zig
+++ b/src/acp.zig
@@ -107,6 +107,7 @@ fn userMessage(arena: Allocator, root: *agent_mod.Agent, text: []const u8) !Valu
/// Rows come back in election order (plan, then local, credits, api).
fn liveModels(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Request) anyerror!bool {
const live: *LiveTurn = @ptrCast(@alignCast(ctx));
+ if (try @import("acp_agents.zig").handle(arena, live.root.io, live.root.home, w, req)) return true;
if (try @import("acp_changes.zig").handle(arena, live.root.io, w, req)) return true;
if (!std.mem.eql(u8, req.method, "graff/models")) return false;
if (req.id == null) return true;
diff --git a/src/acp_agents.zig b/src/acp_agents.zig
new file mode 100644
index 00000000..c2ee6372
--- /dev/null
+++ b/src/acp_agents.zig
@@ -0,0 +1,218 @@
+//! Local peer inspection and explicit human DMs. Reading never drains an inbox.
+const std = @import("std");
+const Io = std.Io;
+const A = std.mem.Allocator;
+const proto = @import("acp_protocol.zig");
+const presence = @import("presence.zig");
+const chan = @import("presence_chan.zig");
+const proc = @import("proc_identity.zig");
+const lease = @import("worktree_lease.zig");
+
+fn field(params: ?std.json.Value, key: []const u8) []const u8 {
+ const p = params orelse return "";
+ if (p != .object) return "";
+ const v = p.object.get(key) orelse return "";
+ return if (v == .string) v.string else "";
+}
+
+pub fn verified(owner: lease.Owner, probe: proc.Probe) bool {
+ return owner.start_id != 0 and switch (probe) {
+ .id => |id| id == owner.start_id,
+ else => false,
+ };
+}
+
+/// Bounded tail, including logs larger than the ordinary inbox read limit.
+pub fn tail(a: A, io: Io, dir: Io.Dir, name: []const u8) ![]const chan.Message {
+ const f = dir.openFile(io, name, .{}) catch return &.{};
+ defer f.close(io);
+ const size = (try f.stat(io)).size;
+ const start = size -| (64 * 1024);
+ const bytes = try a.alloc(u8, @intCast(size - start));
+ const n = try f.readPositionalAll(io, bytes, start);
+ var pos: usize = if (start == 0) 0 else (std.mem.indexOfScalar(u8, bytes[0..n], '\n') orelse return &.{}) + 1;
+ var messages: std.ArrayList(chan.Message) = .empty;
+ while (std.mem.indexOfScalarPos(u8, bytes[0..n], pos, '\n')) |end| {
+ const line = bytes[pos..end];
+ pos = end + 1;
+ const m = std.json.parseFromSliceLeaky(chan.Message, a, line, .{ .ignore_unknown_fields = true }) catch continue;
+ if (m.text.len > 8192 or m.text.len == 0) continue;
+ try messages.append(a, m);
+ }
+ return messages.items[messages.items.len -| 100..];
+}
+
+pub fn handle(a: A, io: Io, home: []const u8, out: *Io.Writer, req: proto.Request) !bool {
+ if (!std.mem.eql(u8, req.method, "graff/agents")) return false;
+ if (req.id == null) return true;
+ 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"))
+ 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" });
+ return true;
+ };
+ defer dir.close(io);
+ const all = presence.listPeersBounded(io, a, dir, 128);
+ const action = field(req.params, "action");
+ 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");
+ const kind = field(req.params, "kind");
+ const start = field(req.params, "startId");
+ for (all.records, all.probes) |owner, probe| {
+ if (!verified(owner, probe) or !std.mem.eql(u8, target, owner.session_id)) continue;
+ const expected = std.fmt.parseInt(u64, start, 10) catch 0;
+ if (expected != owner.start_id or text.len == 0 or text.len > 8192 or (!std.mem.eql(u8, kind, "message") and !std.mem.eql(u8, kind, "handoff"))) break;
+ // Legacy receivers match session-name substrings. Refuse a name
+ // that could reach another live peer instead of guessing.
+ for (all.records, all.probes) |other, other_probe| {
+ if (other.pid != owner.pid and verified(other, other_probe) and @import("peer_target.zig").addressedTo(target, other.session_id)) {
+ try proto.writeError(out, req.id, -32602, "Recipient names overlap; rename a session before sending");
+ return true;
+ }
+ }
+ const self = proc.selfRecord(io);
+ const ok = chan.postMessage(io, a, dir, presence.device_room, .{
+ .from_pid = self.pid,
+ .from_start = self.start_id,
+ .from_session = "GUI",
+ .from_user = true,
+ .to = owner.session_id,
+ .text = if (std.mem.eql(u8, kind, "handoff")) try std.fmt.allocPrint(a, "Handoff request: {s}", .{text}) else text,
+ .kind = kind,
+ .ts_ms = @import("util.zig").unixMs(io),
+ });
+ if (ok) try proto.writeResult(out, req.id, .{ .delivery = "queued" }) else try proto.writeError(out, req.id, -32001, "Message could not be queued");
+ return true;
+ }
+ try proto.writeError(out, req.id, -32602, "Recipient changed or message invalid; refresh and select the recipient again");
+ return true;
+ }
+ if (action.len != 0 and !std.mem.eql(u8, action, "list")) {
+ try proto.writeError(out, req.id, -32602, "Unknown agents action");
+ return true;
+ }
+ const device = std.mem.eql(u8, field(req.params, "scope"), "device");
+ const Row = struct { session: []const u8, startId: []const u8, pid: i32, title: []const u8, task: []const u8, workspace: []const u8, status: []const u8 };
+ var rows: std.ArrayList(Row) = .empty;
+ var identities: std.StringHashMap(void) = .init(a);
+ try identities.put(root, {});
+ for (all.records, all.probes) |owner, probe| {
+ if (!verified(owner, probe) or (!device and !std.mem.eql(u8, root, owner.identity))) continue;
+ try rows.append(a, .{ .session = owner.session_id, .startId = try std.fmt.allocPrint(a, "{d}", .{owner.start_id}), .pid = owner.pid, .title = owner.title, .task = owner.goal, .workspace = owner.identity, .status = owner.activity });
+ try identities.put(owner.identity, {});
+ }
+ if (std.mem.eql(u8, field(req.params, "history"), "off")) {
+ try proto.writeResult(out, req.id, .{ .agents = rows.items });
+ return true;
+ }
+ var messages: std.ArrayList(chan.Message) = .empty;
+ var it = identities.keyIterator();
+ while (it.next()) |identity| {
+ var buf: [chan.chan_name_max]u8 = undefined;
+ try messages.appendSlice(a, try tail(a, io, dir, chan.chanName(&buf, identity.*)));
+ }
+ for (try tail(a, io, dir, presence.device_room)) |m| {
+ const relevant = device or blk: {
+ for (rows.items) |row| if (std.mem.eql(u8, row.session, m.to) or std.mem.eql(u8, row.session, m.from_session)) break :blk true;
+ break :blk false;
+ };
+ if (relevant) try messages.append(a, m);
+ }
+ std.mem.sort(chan.Message, messages.items, {}, struct {
+ fn less(_: void, x: chan.Message, y: chan.Message) bool {
+ return x.ts_ms < y.ts_ms;
+ }
+ }.less);
+ try proto.writeResult(out, req.id, .{ .agents = rows.items, .messages = messages.items[messages.items.len -| 100..], .delivery = "Queued messages are read at a peer's next step boundary. Handoffs are coordination requests, not ownership transfers." });
+ return true;
+}
+
+/// Dedicated observer: no model, credentials, MCP, session files or presence entry.
+pub fn run(init: std.process.Init) !void {
+ var input_buf: [65536]u8 = undefined;
+ var output_buf: [4096]u8 = undefined;
+ var input = Io.File.stdin().reader(init.io, &input_buf);
+ var output = Io.File.stdout().writer(init.io, &output_buf);
+ var arena = std.heap.ArenaAllocator.init(init.gpa);
+ defer arena.deinit();
+ while (try input.interface.takeDelimiter('\n')) |line| {
+ defer _ = arena.reset(.retain_capacity);
+ const req = proto.parseRequest(arena.allocator(), line);
+ if (req) |r| {
+ if (!try handle(arena.allocator(), init.io, init.environ_map.get("HOME") orelse "", &output.interface, r))
+ try proto.writeError(&output.interface, r.id, -32601, "Observer supports graff/agents only");
+ }
+ try output.interface.flush();
+ }
+}
+
+test "agent inspection rejects recycled and unverifiable processes" {
+ try std.testing.expect(verified(.{ .start_id = 4 }, .{ .id = 4 }));
+ try std.testing.expect(!verified(.{ .start_id = 4 }, .{ .id = 5 }));
+ try std.testing.expect(!verified(.{ .start_id = 4 }, .unknown));
+ try std.testing.expect(!verified(.{}, .{ .id = 4 }));
+}
+
+test "agent history does not consume inbox cursors or torn records" {
+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
+ defer arena.deinit();
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const io = std.testing.io;
+ try tmp.dir.writeFile(io, .{ .sub_path = "room", .data = "{\"text\":\"hello\"}\n{\"text\":\"torn" });
+ try std.testing.expectEqual(@as(usize, 1), (try tail(arena.allocator(), io, tmp.dir, "room")).len);
+ try std.testing.expectEqual(@as(usize, 1), (try tail(arena.allocator(), io, tmp.dir, "room")).len);
+}
+
+test "explicit GUI messages revalidate recipient and queue only to a temporary room" {
+ 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 = proc.selfRecord(io);
+ if (self.start_id == 0) return error.SkipZigTest;
+ const record = try presence.formatRecord(a, .{ .pid = self.pid, .start_id = self.start_id, .session_id = "test-peer" });
+ try live.writeFile(io, .{ .sub_path = "peer.json", .data = record });
+ const home = try tmp.dir.realPathFileAlloc(io, ".", a);
+ var storage: [4096]u8 = undefined;
+ var writer: Io.Writer = .fixed(&storage);
+ const stale = proto.parseRequest(a, "{\"id\":1,\"method\":\"graff/agents\",\"params\":{\"action\":\"send\",\"target\":\"test-peer\",\"startId\":\"0\",\"text\":\"review please\",\"kind\":\"handoff\"}}\n").?;
+ try std.testing.expect(try handle(a, io, home, &writer, stale));
+ try std.testing.expect(std.mem.indexOf(u8, writer.buffered(), "Recipient changed") != null);
+ try std.testing.expectEqual(@as(usize, 0), (try tail(a, io, live, presence.device_room)).len);
+ writer = .fixed(&storage);
+ const valid = proto.parseRequest(a, try std.fmt.allocPrint(a, "{{\"id\":2,\"method\":\"graff/agents\",\"params\":{{\"action\":\"send\",\"target\":\"test-peer\",\"startId\":\"{d}\",\"text\":\"review please\",\"kind\":\"handoff\"}}}}", .{self.start_id})).?;
+ try std.testing.expect(try handle(a, io, home, &writer, valid));
+ try std.testing.expect(std.mem.indexOf(u8, writer.buffered(), "queued") != null);
+ const posted = try tail(a, io, live, presence.device_room);
+ try std.testing.expectEqual(@as(usize, 1), posted.len);
+ try std.testing.expectEqualStrings("test-peer", posted[0].to);
+ try std.testing.expectEqualStrings("handoff", posted[0].kind);
+ try std.testing.expect(posted[0].from_user);
+}
+
+test "agent history reads recent bounded records even after a large old log" {
+ 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();
+ const old = try a.alloc(u8, 300 * 1024);
+ @memset(old, ' ');
+ try tmp.dir.writeFile(io, .{ .sub_path = "room", .data = old });
+ try std.testing.expect(chan.postMessage(io, a, tmp.dir, "room", .{ .text = "old partial line" }));
+ try std.testing.expect(chan.postMessage(io, a, tmp.dir, "room", .{ .text = "recent complete line" }));
+ const messages = try tail(a, io, tmp.dir, "room");
+ try std.testing.expectEqual(@as(usize, 1), messages.len);
+ try std.testing.expectEqualStrings("recent complete line", messages[0].text);
+}
diff --git a/src/main.zig b/src/main.zig
index 98429fa6..1eabebf7 100644
--- a/src/main.zig
+++ b/src/main.zig
@@ -239,14 +239,13 @@ const startup_timing = @import("startup_timing.zig"); // .shutdown_trace re-expo
const session_start = @import("session_start.zig");
const session_run = @import("session_run.zig");
pub fn main(init: std.process.Init) !void {
+ if (init.environ_map.get("GRAFF_AGENT_OBSERVER") != null) return @import("acp_agents.zig").run(init);
var boot = startup_timing.Tracker.init(startup_timing.shutdown_trace.arm(init.io, init.environ_map), init.environ_map.get("GRAFF_BOOT_DEBUG") != null); // #364: arm() passes io through, so the teardown below stamps phases without a line of its own
const gpa = init.gpa;
const io = init.io;
const arena = init.arena.allocator();
// #122: raise the open-file soft limit to the OS hard cap (Darwin defaults
- // to 256) so parallel tool/subagent/MCP fan-out in one turn doesn't blow up
- // shell tools with ProcessFdQuotaExceeded. Best-effort, no-op where rlimits
- // don't exist.
+ // to 256). Raising it avoids ProcessFdQuotaExceeded during parallel tools.
std.process.raiseFileDescriptorLimit();
// #124: a per-turn scratch arena for the root agent's transient parse garbage,
// reset each request() so a long REPL/--json/serve session's RSS stays flat.
@@ -597,4 +596,5 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu
_ = @import("goal_todo.zig");
_ = @import("goal_pacing.zig");
_ = @import("presence_record.zig");
+ _ = @import("acp_agents.zig");
}
diff --git a/src/presence.zig b/src/presence.zig
index 94f70418..12c09b41 100644
--- a/src/presence.zig
+++ b/src/presence.zig
@@ -44,6 +44,10 @@ pub const Peers = struct {
/// return the survivors. Best-effort throughout: an unreadable registry means
/// "no peers", never an error propagated into a tool call.
pub fn listPeers(io: Io, arena: Allocator, dir: Io.Dir) Peers {
+ return listPeersBounded(io, arena, dir, max_peers);
+}
+
+pub fn listPeersBounded(io: Io, arena: Allocator, dir: Io.Dir, limit: usize) Peers {
var records: std.ArrayList(Owner) = .empty;
var probes: std.ArrayList(proc_identity.Probe) = .empty;
var d = dir;
@@ -51,7 +55,7 @@ pub fn listPeers(io: Io, arena: Allocator, dir: Io.Dir) Peers {
while (it.next(io) catch null) |entry| {
if (entry.kind != .file) continue;
if (!std.mem.endsWith(u8, entry.name, ".json")) continue;
- if (records.items.len >= max_peers) break;
+ if (records.items.len >= @min(limit, 128)) break;
const text = d.readFileAlloc(io, entry.name, arena, .limited(record_max)) catch continue;
const rec = parseRecord(arena, text) orelse continue;
const live = proc_identity.probe(io, rec.pid);
@@ -119,11 +123,18 @@ var g_tail_seeked: bool = false; // one-shots fast-forward both rooms exactly on
var g_acked: [max_peers]u64 = undefined;
var g_acked_len: usize = 0;
+var g_activity: []const u8 = "waiting";
+pub fn noteActivity(io: Io, arena: Allocator, working: bool) void {
+ g_activity = if (working) "working" else "waiting";
+ writeOwn(io, arena);
+}
+
fn writeOwn(io: Io, arena: Allocator) void {
const dir_path = g_dir orelse return;
const name = g_own_name orelse return;
var owner = worktree_lease.selfOwner(io, g_identity, g_session, unixMs(io));
owner.goal = g_goal;
+ owner.activity = g_activity;
owner.title = g_title;
owner.session_base = g_session_base;
const text = formatRecord(arena, owner) catch return;
diff --git a/src/presence_chan.zig b/src/presence_chan.zig
index c66975f3..609e81c8 100644
--- a/src/presence_chan.zig
+++ b/src/presence_chan.zig
@@ -36,6 +36,7 @@ pub const Message = struct {
ts_ms: i64 = 0,
text: []const u8 = "",
from_user: bool = false,
+ kind: []const u8 = "message",
};
/// The channel file for a worktree identity: content-hash, so it is stable
diff --git a/src/presence_record.zig b/src/presence_record.zig
index 4606d02d..b37165cb 100644
--- a/src/presence_record.zig
+++ b/src/presence_record.zig
@@ -17,6 +17,7 @@ const RecordJson = struct {
identity: []const u8 = "",
goal: []const u8 = "",
last_seen_ms: i64 = 0,
+ activity: []const u8 = "connected",
title: []const u8 = "",
session_base: []const u8 = "",
};
@@ -31,6 +32,7 @@ pub fn formatRecord(arena: Allocator, owner: Owner) ![]const u8 {
.identity = owner.identity,
.goal = owner.goal,
.last_seen_ms = owner.last_seen_ms,
+ .activity = owner.activity,
.title = owner.title,
.session_base = owner.session_base,
});
@@ -47,6 +49,7 @@ pub fn parseRecord(arena: Allocator, text: []const u8) ?Owner {
.identity = rec.identity,
.goal = rec.goal,
.last_seen_ms = rec.last_seen_ms,
+ .activity = rec.activity,
.title = rec.title,
.session_base = rec.session_base,
};
diff --git a/src/providers.zig b/src/providers.zig
index f6e89c15..a986d924 100644
--- a/src/providers.zig
+++ b/src/providers.zig
@@ -1,9 +1,7 @@
//! Provider-switch core: resolve a /model or set_model request to a
//! Provider, apply it to the running Agent (translating or clearing history
//! across a wire-format change), and announce the switch. Split
-//! out of main.zig (600-line goal). The interactive pickers + ultracode
-//! steering + login-auth flow that build on top of this live in
-//! pickers.zig, which back-imports switchProvider from here. Back-imports
+//! out of main.zig. Interactive pickers live in pickers.zig. Back-imports
//! main (as main_mod, since several params are named `root`) for Agent,
//! Keys, Provider, provider_specs, and extractText.
@@ -221,6 +219,8 @@ pub fn failoverEligible(provider_id: []const u8, detail: []const u8) bool {
/// fallback becomes active for this session but does not replace the saved
/// model preference.
pub fn runTurnWithFallback(root: *Agent, keys: *Keys, arena: Allocator, out: ?*Io.Writer) anyerror![]const u8 {
+ if (!root.sub) @import("presence.zig").noteActivity(root.io, arena, true);
+ defer if (!root.sub) @import("presence.zig").noteActivity(root.io, arena, false);
const behavior_turn = trace.beginRootTurn(root.tracer);
defer trace.endRootTurn(root.tracer, behavior_turn);
if (root.fallback_blocked) return error.FallbackConsentRequired;
diff --git a/src/worktree_lease.zig b/src/worktree_lease.zig
index 371e8eb2..aedec970 100644
--- a/src/worktree_lease.zig
+++ b/src/worktree_lease.zig
@@ -71,6 +71,7 @@ pub const Owner = struct {
/// peer reads to decide whether its work overlaps. Empty when unknown.
goal: []const u8 = "",
last_seen_ms: i64 = 0,
+ activity: []const u8 = "connected",
/// #700: the human title from `.session.json`. Empty on older records.
title: []const u8 = "",
/// #700: durable saved-session file base (slug). Empty on older records.