Skip to content

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

Python

Merge release GUI workspace and cancellation fixes

Rach Pradhane284bd3ecad0
diff --cc .github/workflows/desktop.yml
index d24cdf96,1916e94f..b0eeefba
--- a/.github/workflows/desktop.yml
+++ b/.github/workflows/desktop.yml
@@@ -23,48 -22,7 +23,49 @@@ jobs
- run: bun install --frozen-lockfile
- run: bun run test:desktop
- run: bun run build
+ - run: bun run test:overflow
+ - run: bun run test:tasks
- run: bun run test:projects
++ - run: bun run test:workspace
- run: bun run test:stress
- run: bun run test:agents
+ - run: bun run test:sessions
- run: bun build electron/updater-runtime.cjs --target=node --format=cjs --external electron --outfile /tmp/updater-runtime.cjs
+ native:
+ name: native macOS GUI
+ runs-on: macos-26
+ timeout-minutes: 20
+ defaults:
+ run:
+ working-directory: apps/native
+ steps:
+ - uses: actions/checkout@v7
+ - uses: oven-sh/setup-bun@v2
+ with:
+ bun-version: '1.4.2'
+ - run: bun install --frozen-lockfile
+ - name: Native graphical session, Activity sheet and OS capabilities
+ run: bun run test:native
+ env:
+ GRAFF_ELECTRON_FOREGROUND: '1'
+ - run: bun run build
+ - name: Foreground GUI suite including native fullscreen
+ run: bun run test:visual
+ env:
+ GRAFF_ELECTRON_FOREGROUND: '1'
+ - name: Require native fullscreen coverage
+ run: bun scripts/check-native-ci.mjs
+ - name: Native coverage report
+ if: always()
+ run: bun scripts/check-native-ci.mjs --summary
+ - uses: actions/upload-artifact@v7
+ if: always()
+ with:
+ name: native-gui-results
+ path: |
+ zig-out/native-tests/native-results.json
+ zig-out/visual-tests/test-run.json
+ zig-out/visual-tests/stress-results.json
+ zig-out/visual-tests/stress-fullscreen.png
+ if-no-files-found: warn
+ retention-days: 7
diff --cc apps/native/app/api/acp/route.ts
index 6f2ab04e,ab3bd295..3202e49d
--- a/apps/native/app/api/acp/route.ts
+++ b/apps/native/app/api/acp/route.ts
@@@ -9,6 -9,6 +9,9 @@@ import { AcpTransport } from "@/lib/acp
import { defaultRoot, resolveRoot } from "@/lib/server-root";
import { prepareGuiPrompt } from "@/lib/gui-skill-context";
++import { retireWorker } from "@/lib/acp-retire";
++import { finishCancelledPrompt } from "@/lib/acp-cancel";
++
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
@@@ -30,6 -30,8 +33,10 @@@ 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;
++ restart: boolean;
++ restartReady: Promise<void> | null;
};
const HANDSHAKE_MS = 120_000;
@@@ -134,13 -144,14 +149,16 @@@ function spawnAgent(chat: string, opts
mcp: opts.mcp,
commands: [],
spawnError: null,
+ pendingPrompt: null,
++ restart: false,
++ restartReady: null,
};
slot.transport = new AcpTransport(child, message => noteCommands(slot, message));
child.on("error", (err) => {
slot.spawnError = err;
});
child.on("exit", () => {
-- if (slots.get(chat) === slot) slots.delete(chat);
++ if (slots.get(chat) === slot && !slot.restart) slots.delete(chat);
});
slots.set(chat, slot);
return slot;
@@@ -167,6 -178,22 +185,16 @@@ function rpc(slot: Slot, method: string
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. */
++/** Retire an unresponsive worker; bootstrap restores its saved session. */
+ 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;
++ await finishCancelledPrompt(slot, async () => {
++ slot.restart = true;
++ slot.restartReady = retireWorker(slot.child);
++ slot.transport.abort(new Error("The interrupted worker stopped responding; the next turn will reload its saved session."));
++ await slot.restartReady;
++ }, CANCEL_GRACE_MS);
+ }
+
/** 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. */
@@@ -181,12 -208,12 +209,17 @@@ async function bootstrap(chat: string,
(opts.yolo === undefined || live.yolo === opts.yolo) &&
(opts.mcp === undefined || live.mcp === opts.mcp);
if (!opts.reset && same) return live;
++ const recovering = live?.restart ? live : undefined;
++ if (recovering?.restartReady) {
++ await recovering.restartReady;
++ if (slots.get(chat) !== live) return bootstrap(chat, opts);
++ }
const slot = spawnAgent(chat, {
-- model: opts.model,
-- resume: opts.resume,
-- cwd: opts.cwd ?? defaultRoot(),
-- yolo: opts.yolo ?? defaultYolo(),
-- mcp: opts.mcp ?? true,
++ model: opts.model ?? recovering?.model ?? undefined,
++ resume: opts.resume ?? recovering?.resume ?? recovering?.sessionId ?? undefined,
++ cwd: opts.cwd ?? recovering?.cwd ?? defaultRoot(),
++ yolo: opts.yolo ?? recovering?.yolo ?? defaultYolo(),
++ mcp: opts.mcp ?? recovering?.mcp ?? true,
});
await rpc(slot, "initialize", { protocolVersion: 1, clientCapabilities: { fs: {} } }, HANDSHAKE_MS);
const created = (await rpc(slot, "session/new", { cwd: slot.cwd }, HANDSHAKE_MS)) as {
@@@ -268,11 -300,13 +306,13 @@@ export async function POST(req: NextReq
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; });
++ .finally(() => { if (slot.pendingPrompt === pending) { slot.pendingPrompt = null; slot.streaming = false; } });
},
cancel() {
if (cancelled) return; // Completed streams must not cancel a later turn.
diff --cc apps/native/components/site/AgentsPane.tsx
index 9558a866,f3240f7a..7f852961
--- a/apps/native/components/site/AgentsPane.tsx
+++ b/apps/native/components/site/AgentsPane.tsx
@@@ -1,18 -1,14 +1,14 @@@
'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 { agentKey, agentName, workingAgentCount, 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 }) {
++export default function AgentsPane({ root, onClose, request = agentRequest, fullWidth = false, onOccupancy }: { root?: string; onClose(): void; request?: typeof agentRequest; fullWidth?: boolean; onOccupancy?(count: number): void }) {
const [scope, setScope] = useState('workspace');
const [showIdle, setShowIdle] = useState(false);
const [snapshot, setSnapshot] = useState<AgentSnapshot | null>(null);
diff --cc apps/native/components/site/GraffHarness.tsx
index 401ef284,61f7e23f..8c234458
--- a/apps/native/components/site/GraffHarness.tsx
+++ b/apps/native/components/site/GraffHarness.tsx
@@@ -1,10 -1,10 +1,10 @@@
"use client";
++import { useHarnessSessions } from "./useHarnessSessions";
++import { createPromptRunner } from "./harness-prompt-runner";
import { workspaceActions } from "./harness-workspace-actions";
import ProjectsPane from "./ProjectsPane";
import { useSavedConversation, ConversationOpenNotice } from "./useSavedConversation";
--import { restoreProjects, persistProjects } from "@/lib/project-preferences";
--import { createTurnPainter } from "@/lib/turn-painter";
import { useQuietSettings } from "./useQuietSettings";
import HarnessChrome from "./HarnessChrome";
import ChatSplitLayout from "./ChatSplitLayout";
@@@ -14,51 -14,55 +14,42 @@@ 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";
-import PromptBar, { type PromptModel } from "@/components/primitives/PromptBar";
++import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { type PromptModel } from "@/components/primitives/PromptBar";
import SidebarNav from "@/components/primitives/SidebarNav";
import ConversationsPane from "@/components/site/ConversationsPane";
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 TasksPane, { taskItems } from "./TasksPane";
++import { type BrowserPin } from "@/lib/browser/annotations";
++import { browserClose } from "@/lib/browser-client";
+import ChatColumn from "./ChatColumn";
+import TasksSidebar from "./TasksSidebar";
+ import { useTasksVisibility } from "./useTasksVisibility";
-import ChatTranscript from "./ChatTranscript";
+import { MAX_COLUMNS, SPLIT_LIMIT_MESSAGE, splitLimitReached } from "./harness-split";
import { useDesktopShortcuts } from "./useDesktopShortcuts";
--import EmptyState from "@/components/site/ChatEmpty";
import {
cancel,
chatHandle,
-- checkHealth,
-- disposePage,
disposeSession,
-- ensureSession,
-- fetchModels,
-- prompt,
type Health,
} from "@/lib/acp-client";
--import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AcpCommand, type AssistantTurn } from "@/lib/acp";
++import { type AcpCommand } from "@/lib/acp";
import { useChatScroll } from "./useChatScroll";
--import { enqueuePrompt, shiftQueuedPrompt } from "@/lib/prompt-queue";
-import PromptQueue from "./PromptQueue";
++import { enqueuePrompt } from "@/lib/prompt-queue";
import { usePromptQueue } from "./usePromptQueue";
--import { dateGroup, listSessionsPage, relativeTime, removeSession, type StoredSession } from "@/lib/sessions";
--import { loadHistory, mergeHistory, pushHistory, saveHistory } from "@/lib/prompt-history";
++import { removeSession, type StoredSession } from "@/lib/sessions";
++import { loadHistory } from "@/lib/prompt-history";
import WorkspaceDialog from "@/components/site/WorkspaceDialog";
import {
basename,
findWorkspace,
shellQuote,
-- upsertWorkspace,
type Workspace,
} from "@/lib/workspaces";
/** Whether the sidecar browser pane was open, restored after a reload. */
const BROWSER_OPEN_KEY = "graff.native.browser.open";
-/** Columns the split view will show at once, the active chat included. */
-const MAX_COLUMNS = 4;
-
--/** Rows the sidebar previews; the library pages the rest. */
--const SIDEBAR_PAGE = 12;
--
export default function GraffHarness() {
const [chats, setChats] = useState<Chat[]>([{ id: 1, title: null, messages: [] }]);
const [activeId, setActiveId] = useState(1);
@@@ -84,6 -88,7 +75,8 @@@
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 [workingAgents, setWorkingAgents] = useState(0);
+ 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);
@@@ -113,8 -118,6 +106,7 @@@
// the whole chat area, so opening it leaves the other side panes.
const [projectsOpen, setProjectsOpen] = useState(false);
const [conversationsOpen, setConversationsOpen] = useState(false);
- const [tasksOpen, setTasksOpen] = useState(false);
+ const [splitNotice, setSplitNotice] = useState<string | null>(null);
const openConversations = () => {
setProjectsOpen(false);
setAgentsOpen(false);
@@@ -136,10 -139,8 +128,9 @@@
chatsRef.current = chats;
const panesRef = useRef<number[]>([]);
panesRef.current = panes;
-- const [following, setFollowing] = useState(true);
++ const [, 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 }[]>([]);
@@@ -164,146 -169,145 +155,14 @@@
const setChatModel = (chatId: number, key: string) =>
setChats((current) => current.map((c) => (c.id === chatId ? { ...c, model: key } : c)));
const lastAssistant = [...chatThread.messages].reverse().find((m): m is Extract<Msg, { role: "assistant" }> => m.role === "assistant");
-- // A resumed session's prompts came from its file, not this browser; fold
-- // them in so ArrowUp walks the conversation on screen first.
-- const composerHistory = useMemo(
-- () => mergeHistory(history, chatThread.messages.flatMap((m) => (m.role === "user" ? [m.text] : []))),
-- [history, chatThread.messages],
-- );
const setPins = (chatId: number, list: BrowserPin[]) => {
pinsRef.current = { ...pinsRef.current, [chatId]: list };
setPinsByChat(pinsRef.current);
};
-- const adoptCatalog = async (chatId: number) => {
-- // Use the provider and model actually resolved by graff.
-- try {
-- const { models: live, current, commands: available } = await fetchModels(sessionsRef.current.has(chatId) ? handleOf(chatId) : undefined, activePathRef.current ?? undefined);
-- if (live.length > 0) setModels(live);
-- if (available?.length) { setCatalogCommands(available); setCommands(old => ({ ...old, [chatId]: available })); }
-- if (current) {
-- setChatModel(chatId, current);
-- setModelKey((fallback) => fallback ?? current);
-- }
-- } catch {
-- // Do not invent a selected model when the catalog is unavailable.
-- }
-- };
--
-- // Refresh the catalog on focus. If its agent was
-- // not up yet, or the page outlived a restart — would show the fallback
-- // for good, so ask again whenever the window comes back to the front.
-- const catalogRef = useRef({ adopt: (_: number) => {}, activeId: 1 });
-- useEffect(() => {
-- const again = () => {
-- if (document.visibilityState === "hidden") return;
-- catalogRef.current.adopt(catalogRef.current.activeId);
-- };
-- window.addEventListener("focus", again);
-- document.addEventListener("visibilitychange", again);
-- return () => {
-- window.removeEventListener("focus", again);
-- document.removeEventListener("visibilitychange", again);
-- };
-- }, []);
--
-- const requireSession = async (chatId: number, reset = false, key?: string): Promise<string> => {
- if (chatsRef.current.find(c => c.id === chatId)?.snapshot) throw new Error("Continue here before resuming this saved snapshot.");
-- const live = sessionsRef.current.get(chatId);
-- if (!reset && live) return live;
-- const chat = chatsRef.current.find((c) => c.id === chatId);
-- // A tab spawns where it was opened; the first tab, opened before the
-- // workspace list loaded, takes the active workspace.
-- const cwd = chat?.cwd ?? activePathRef.current ?? undefined;
-- const ws = findWorkspace(workspacesRef.current, cwd);
-- const spawnModel = key ?? chat?.model ?? ws?.model ?? model ?? undefined;
-- const { sessionId: id, commands } = await ensureSession(handleOf(chatId), {
-- model: spawnModel,
-- reset,
-- resume: sessionNamesRef.current.get(chatId),
-- cwd,
-- yolo: ws?.yolo,
-- mcp: ws?.mcp,
-- });
-- sessionsRef.current.set(chatId, id);
-- setSessionIds((current) => ({ ...current, [chatId]: id }));
-- // Populate the command menu from this agent's advertisement.
-- if (commands.length > 0) setCommands((current) => ({ ...current, [chatId]: commands }));
-- setHealth({ ok: true });
-- await adoptCatalog(chatId);
-- return id;
-- };
--
-- useEffect(() => {
-- let cancelled = false;
-- (async () => {
-- const h = await checkHealth();
-- if (cancelled) return;
-- setHealth(h);
-- if (!h.ok) return;
-- // The server's default workspace is always a row; the remembered pick
-- // wins when it is still listed, else the default is active.
-- const root = h.cwd ?? "";
-- const savedProjects = await restoreProjects(window.localStorage);
-- if (cancelled) return;
-- let list = savedProjects.list;
-- if (root && !findWorkspace(list, root)) list = upsertWorkspace(list, { path: root, name: basename(root) });
-- const remembered = savedProjects.active;
-- const active = findWorkspace(list, remembered)?.path ?? findWorkspace(list, root)?.path ?? list[0]?.path ?? null;
-- workspacesRef.current = list;
-- activePathRef.current = active;
-- setWorkspaces(list);
-- setActivePath(active);
-- persistProjects(window.localStorage, list, active);
-- if (active) setChats((current) => current.map((c) => (c.id === 1 && !c.cwd ? { ...c, cwd: active } : c)));
-- void refreshStored();
-- try {
-- const session = newSessionName();
-- sessionNamesRef.current.set(1, session);
-- setChats((current) => current.map((c) => (c.id === 1 ? { ...c, session } : c)));
-- if (window.graffDesktop) { await adoptCatalog(1); return; } // No coding session needed.
-- await requireSession(1);
-- if (cancelled) return;
-- await adoptCatalog(1);
-- } catch (err) {
-- if (!cancelled) {
-- setHealth({ ok: false, detail: err instanceof Error ? err.message : String(err) });
-- }
-- }
-- })();
-- void refreshStored();
-- // Reap this page's agents when it goes away — without this every reload
-- // leaves a `graff acp` (and its MCP children) running under the dev server.
-- const page = pageRef.current;
-- const reap = () => disposePage(page);
-- window.addEventListener("pagehide", reap);
-- return () => {
-- cancelled = true;
-- window.removeEventListener("pagehide", reap);
-- };
-- // The first tab's agent is spawned once per mount; later tabs spawn their
-- // own on creation, and a model change respawns only the active tab's.
-- // eslint-disable-next-line react-hooks/exhaustive-deps
-- }, []);
--
-- /** Re-read the active workspace's session directory; tabs adopt the
-- * titles graff saved. */
-- const refreshStored = async () => {
-- try {
-- const page = await listSessionsPage({ root: activePathRef.current ?? undefined, limit: SIDEBAR_PAGE });
-- setStored(page.sessions);
-- setStoredTotal(page.total);
-- setChats((current) =>
-- current.map((c) => {
-- if (c.titledByModel) return c;
-- const saved = c.session ? page.sessions.find((s) => s.name === c.session) : undefined;
-- return saved?.title && saved.title !== c.title ? { ...c, title: saved.title } : c;
-- }),
-- );
-- } catch {
-- // the sidebar keeps its last list
-- }
-- };
++ const { adoptCatalog, requireSession, refreshStored } = useHarnessSessions({
++ sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal
++ });
const openPath = useCallback((path: string) => {
setProjectsOpen(false); setAgentsOpen(false); setBrowserOpen(false);
@@@ -331,111 -335,105 +190,9 @@@
.catch(() => undefined);
};
-- const patchAssistant = (chatId: number, msgId: number, next: AssistantTurn) => {
-- setChats((current) =>
-- current.map((c) =>
-- c.id !== chatId
-- ? c
-- : {
-- ...c,
-- messages: c.messages.map((m) => (m.role === "assistant" && m.id === msgId ? { ...m, turn: next } : m)),
-- },
-- ),
-- );
-- };
--
-- 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;
-- const userId = (msgIdRef.current += 1);
-- const asstId = (msgIdRef.current += 1);
-- const title = thread?.title ?? (trimmed.length > 30 ? `${trimmed.slice(0, 30).trimEnd()}…` : trimmed);
-- // The first prompt of a tab names it, in the model's words.
-- if (!thread?.title) nameChat(chatId, trimmed, thread?.cwd);
-- setChats((current) =>
-- current.map((c) =>
-- c.id !== chatId
-- ? c
-- : {
-- ...c,
-- title,
- snapshot: undefined,
-- messages: [
-- ...c.messages,
-- { id: userId, role: "user", text: trimmed },
-- { id: asstId, role: "assistant", turn: { ...emptyTurn(), model: spawnModel, startedAt: Date.now() } },
-- ],
-- },
-- ),
-- );
-- 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);
-- return next;
-- });
-- // Pins from the sidecar ride behind the prompt, with the tab's handle
-- // so the agent can drive the same page; they are spent on send. Behind,
-- // not ahead: graff titles the session from the message's first line.
-- let wire = trimmed;
-- const pins = /^\/(effort|reasoning|fast)(?:\s|$)/.test(trimmed) ? [] : pinsRef.current[chatId] ?? [];
-- if (pins.length > 0) {
-- const handle = await browserHandle(handleOf(chatId)).catch(() => null);
-- wire = `${trimmed}\n\n${annotationsBlock(pins, handle)}`;
-- setPins(chatId, []);
-- }
-- let turn: AssistantTurn = { ...emptyTurn(), model: spawnModel, startedAt: Date.now() };
-- const painter = createTurnPainter<AssistantTurn>(next => patchAssistant(chatId, asstId, next));
-- const startedAt = Date.now();
-- try {
-- const id = await requireSession(chatId);
-- 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);
-- if (turn.thoughtMs === undefined && turn.status !== "thinking") turn = { ...turn, thoughtMs: Date.now() - startedAt };
-- painter.update(turn);
-- }
-- // The turn carried pins, so the agent most likely changed the page:
-- // reload the chat's tab so the pane shows the result without a click.
-- if (pins.length > 0) void browserNav(handleOf(chatId), "reload").catch(() => undefined);
-- if (/^\/(effort|reasoning|fast)(?:\s|$)/.test(trimmed)) void adoptCatalog(chatId);
-- turn = finishAcpTurn(turn);
-- painter.finish(turn);
-- } catch (err) {
-- turn = finishAcpTurn({ ...turn, error: err instanceof Error ? err.message : String(err), status: "error" });
-- painter.finish(turn);
-- } finally {
-- painter.dispose();
-- steerer.finish(chatId);
-- runningRef.current.delete(chatId);
-- setBusyFor(chatId, false);
-- void refreshStored();
-- setTimeout(() => void refreshStored(), 2500);
-- const { next, rest } = shiftQueuedPrompt(queuesRef.current[chatId] ?? []);
-- setQueue(chatId, rest);
-- if (next) void runPrompt(chatId, next.text);
-- }
-- };
--
-- const nameChat = (chatId: number, prompt: string, cwd: string | undefined) => {
-- void fetch("/api/title", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ prompt, cwd }) })
-- .then(res => res.ok ? res.json() : null).then(body => {
-- const title = body?.title?.trim();
-- if (title) setChats(current => current.map(c => c.id === chatId ? { ...c, title, titledByModel: true } : c));
-- }).catch(() => undefined);
-- };
++ const runPrompt = createPromptRunner({
++ runningRef, steerer, setFollowing, chatsRef, model, msgIdRef, setChats, setBusyFor, setHistory, pinsRef, handleOf, setPins, requireSession, adoptCatalog, refreshStored, queuesRef, setQueue, setCancelError
++ });
const settings = useQuietSettings({ requireSession, handleOf, running: runningRef.current, apply: (catalog) => setModels(catalog.models) });
const send = async (text: string, forChat?: number) => {
@@@ -666,7 -724,7 +424,6 @@@
toggleTerminal, equalize: () => setPaneWeights({}), openWorkspace: () => setDialog({ mode: "new" }),
});
-- catalogRef.current = { adopt: (id: number) => { if (!runningRef.current.has(id)) void adoptCatalog(id).catch(() => undefined); }, activeId };
const paneTodos = lastAssistant?.turn.todos ?? [];
// Zoom only changes visibility; the split order is retained.
@@@ -714,9 -772,7 +471,9 @@@
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={() => setTasksOpen(open => !open)}
+ tasksOpen={tasksOpen} taskCount={paneTodos.length} onTasks={() => { setAgentsOpen(false); setTasksOpen(!tasksOpen); }}
+ splitNotice={splitNotice}
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">
@@@ -744,7 -800,7 +501,7 @@@
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)} />}
++ {agentsOpen && !projectsOpen && !filesOpen && !browserOpen && !conversationsOpen && <AgentsPane key={chatCwd} root={chatCwd} fullWidth onOccupancy={setWorkingAgents} 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 && (
@@@ -759,8 -815,8 +516,8 @@@
/>
)}
- {!projectsOpen && !filesOpen && !browserOpen && !conversationsOpen && tasksOpen && (
- {tasksOpen && !agentsOpen && !projectsOpen && !filesOpen && !browserOpen && !conversationsOpen && active && paneTodos.length > 0 && (
- <TasksPane items={taskItems(paneTodos)} onClose={() => setTasksOpen(false)} />
++ {!agentsOpen && !projectsOpen && !filesOpen && !browserOpen && !conversationsOpen && tasksOpen && (
+ <TasksSidebar items={paneTodos} onClose={() => setTasksOpen(false)} />
)}
</div>
{terminalUsed && chatCwd && <TerminalPane key={chatCwd} cwd={chatCwd} visible={terminalVisible} onHide={() => setTerminalVisible(false)} />}
diff --cc apps/native/components/site/HarnessChrome.tsx
index 5bfadc48,46ce47aa..30960729
--- a/apps/native/components/site/HarnessChrome.tsx
+++ b/apps/native/components/site/HarnessChrome.tsx
@@@ -21,8 -20,11 +21,11 @@@ export default function HarnessChrome({
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>
++ 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{workingAgents > 0 ? ` (${workingAgents})` : ""}</button>
+ <span aria-hidden="true" className="mx-1 h-4 w-px shrink-0 bg-line" />
{chats.map((c) => (
<div
data-tab-id={c.id}
@@@ -141,17 -143,10 +144,16 @@@
)}
</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>}
+ {onTasks && (
+ <button type="button" aria-pressed={tasksOpen} aria-label="Show tasks" title="Tasks — open on demand, not when a chat has a list" disabled={taskCount === 0 && !tasksOpen} onClick={onTasks}
+ className={`flex items-center gap-1.5 rounded-lg px-2 py-1 text-xs hover:bg-hover disabled:opacity-40 ${tasksOpen ? "bg-hover-2 text-ink" : "text-ink-2"}`}>
+ <span data-toolbar-label>Tasks{taskCount > 0 ? ` (${taskCount})` : ""}</span>
+ </button>
+ )}
<ThemeToggle />
+ <DesktopSettings />
</div>
+ {splitNotice && <p role="status" data-split-limit className="border-t border-line px-3 py-1.5 text-[12px] text-ink-2">{splitNotice}</p>}
</div>
);
diff --cc apps/native/components/site/harness-prompt-runner.ts
index 00000000,00000000..ba76650d
new file mode 100644
--- /dev/null
+++ b/apps/native/components/site/harness-prompt-runner.ts
@@@ -1,0 -1,0 +1,126 @@@
++import type { MutableRefObject, Dispatch, SetStateAction } from "react";
++import { createTurnPainter } from "@/lib/turn-painter";
++import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AssistantTurn } from "@/lib/acp";
++import { prompt } from "@/lib/acp-client";
++import { annotationsBlock, type BrowserPin } from "@/lib/browser/annotations";
++import { browserHandle, browserNav } from "@/lib/browser-client";
++import { pushHistory, saveHistory } from "@/lib/prompt-history";
++import { shiftQueuedPrompt, type QueuedPrompt } from "@/lib/prompt-queue";
++import type { createQueueSteerer } from "@/lib/prompt-queue-steer";
++import type { Chat } from "./harness-types";
++type Ref<T> = MutableRefObject<T>;
++type Setter<T> = Dispatch<SetStateAction<T>>;
++type Props = {
++ runningRef: Ref<Set<number>>; steerer: ReturnType<typeof createQueueSteerer>; setFollowing: Setter<boolean>;
++ chatsRef: Ref<Chat[]>; model: string | null; msgIdRef: Ref<number>; setChats: Setter<Chat[]>;
++ setCancelError: Setter<Record<number, string>>;
++ setBusyFor(id: number, on: boolean): void; setHistory: Setter<string[]>;
++ pinsRef: Ref<Record<number, BrowserPin[]>>; handleOf(id: number): string;
++ setPins(id: number, pins: BrowserPin[]): void; requireSession(id: number): Promise<string>;
++ adoptCatalog(id: number): Promise<void>; refreshStored(): Promise<void>;
++ queuesRef: Ref<Record<number, QueuedPrompt[]>>; setQueue(id: number, queue: QueuedPrompt[]): void;
++};
++export function createPromptRunner({runningRef, steerer, setFollowing, chatsRef, model, msgIdRef, setChats, setBusyFor, setHistory, pinsRef, handleOf, setPins, requireSession, adoptCatalog, refreshStored, queuesRef, setQueue, setCancelError}: Props) {
++ const patchAssistant = (chatId: number, msgId: number, next: AssistantTurn) => {
++ setChats((current) =>
++ current.map((c) =>
++ c.id !== chatId
++ ? c
++ : {
++ ...c,
++ messages: c.messages.map((m) => (m.role === "assistant" && m.id === msgId ? { ...m, turn: next } : m)),
++ },
++ ),
++ );
++ };
++
++ const runPrompt = async (chatId: number, trimmed: string) => {
++ setCancelError(current => { const next = { ...current }; delete next[chatId]; return next; });
++ runningRef.current.add(chatId);
++ steerer.begin(chatId);
++ setFollowing(true);
++ const thread = chatsRef.current.find((c) => c.id === chatId);
++ const spawnModel = thread?.model ?? model ?? undefined;
++ const userId = (msgIdRef.current += 1);
++ const asstId = (msgIdRef.current += 1);
++ const title = thread?.title ?? (trimmed.length > 30 ? `${trimmed.slice(0, 30).trimEnd()}…` : trimmed);
++ // The first prompt of a tab names it, in the model's words.
++ if (!thread?.title) nameChat(chatId, trimmed, thread?.cwd);
++ setChats((current) =>
++ current.map((c) =>
++ c.id !== chatId
++ ? c
++ : {
++ ...c,
++ title,
++ snapshot: undefined,
++ messages: [
++ ...c.messages,
++ { id: userId, role: "user", text: trimmed },
++ { id: asstId, role: "assistant", turn: { ...emptyTurn(), model: spawnModel, startedAt: Date.now() } },
++ ],
++ },
++ ),
++ );
++ setBusyFor(chatId, true);
++ setHistory((current) => {
++ const next = pushHistory(current, trimmed);
++ saveHistory(window.localStorage, next);
++ return next;
++ });
++ // Pins from the sidecar ride behind the prompt, with the tab's handle
++ // so the agent can drive the same page; they are spent on send. Behind,
++ // not ahead: graff titles the session from the message's first line.
++ let wire = trimmed;
++ const pins = /^\/(effort|reasoning|fast)(?:\s|$)/.test(trimmed) ? [] : pinsRef.current[chatId] ?? [];
++ if (pins.length > 0) {
++ const handle = await browserHandle(handleOf(chatId)).catch(() => null);
++ wire = `${trimmed}\n\n${annotationsBlock(pins, handle)}`;
++ setPins(chatId, []);
++ }
++ let turn: AssistantTurn = { ...emptyTurn(), model: spawnModel, startedAt: Date.now() };
++ const painter = createTurnPainter<AssistantTurn>(next => patchAssistant(chatId, asstId, next));
++ const startedAt = Date.now();
++ try {
++ const id = await requireSession(chatId);
++ 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);
++ if (turn.thoughtMs === undefined && turn.status !== "thinking") turn = { ...turn, thoughtMs: Date.now() - startedAt };
++ painter.update(turn);
++ }
++ // The turn carried pins, so the agent most likely changed the page:
++ // reload the chat's tab so the pane shows the result without a click.
++ if (pins.length > 0) void browserNav(handleOf(chatId), "reload").catch(() => undefined);
++ if (/^\/(effort|reasoning|fast)(?:\s|$)/.test(trimmed)) void adoptCatalog(chatId);
++ turn = finishAcpTurn(turn);
++ painter.finish(turn);
++ } catch (err) {
++ turn = finishAcpTurn({ ...turn, error: err instanceof Error ? err.message : String(err), status: "error" });
++ painter.finish(turn);
++ } finally {
++ painter.dispose();
++ steerer.finish(chatId);
++ runningRef.current.delete(chatId);
++ setBusyFor(chatId, false);
++ void refreshStored();
++ setTimeout(() => void refreshStored(), 2500);
++ const { next, rest } = shiftQueuedPrompt(queuesRef.current[chatId] ?? []);
++ setQueue(chatId, rest);
++ if (next) void runPrompt(chatId, next.text);
++ }
++ };
++
++ const nameChat = (chatId: number, prompt: string, cwd: string | undefined) => {
++ void fetch("/api/title", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ prompt, cwd }) })
++ .then(res => res.ok ? res.json() : null).then(body => {
++ const title = body?.title?.trim();
++ if (title) setChats(current => current.map(c => c.id === chatId ? { ...c, title, titledByModel: true } : c));
++ }).catch(() => undefined);
++ };
++ return runPrompt;
++}
diff --cc apps/native/components/site/useHarnessSessions.ts
index 00000000,00000000..cf2ec36f
new file mode 100644
--- /dev/null
+++ b/apps/native/components/site/useHarnessSessions.ts
@@@ -1,0 -1,0 +1,156 @@@
++import { useEffect, useRef, type MutableRefObject, type Dispatch, type SetStateAction } from "react";
++import { checkHealth, disposePage, ensureSession, fetchModels, type Health } from "@/lib/acp-client";
++import type { AcpCommand } from "@/lib/acp";
++import type { PromptModel } from "@/components/primitives/PromptBar";
++import { listSessionsPage, type StoredSession } from "@/lib/sessions";
++import { restoreProjects, persistProjects } from "@/lib/project-preferences";
++import { basename, findWorkspace, upsertWorkspace, type Workspace } from "@/lib/workspaces";
++import { newSessionName, type Chat } from "./harness-types";
++type Ref<T> = MutableRefObject<T>;
++type Setter<T> = Dispatch<SetStateAction<T>>;
++type Props = {
++ sessionsRef: Ref<Map<number, string>>; sessionNamesRef: Ref<Map<number, string>>;
++ chatsRef: Ref<Chat[]>; workspacesRef: Ref<Workspace[]>; activePathRef: Ref<string | null>;
++ pageRef: Ref<string>; runningRef: Ref<Set<number>>; model: string | null; activeId: number;
++ handleOf(id: number): string; setModels: Setter<PromptModel[]>;
++ setCommands: Setter<Record<number, AcpCommand[]>>; setCatalogCommands: Setter<AcpCommand[]>;
++ setChatModel(id: number, key: string): void; setModelKey: Setter<string | null>;
++ setSessionIds: Setter<Record<number, string>>; setHealth: Setter<Health | null>;
++ setWorkspaces: Setter<Workspace[]>; setActivePath: Setter<string | null>;
++ setChats: Setter<Chat[]>; setStored: Setter<StoredSession[]>; setStoredTotal: Setter<number>;
++};
++const SIDEBAR_PAGE = 12;
++export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal}: Props) {
++ const adoptCatalog = async (chatId: number) => {
++ // Use the provider and model actually resolved by graff.
++ try {
++ const { models: live, current, commands: available } = await fetchModels(sessionsRef.current.has(chatId) ? handleOf(chatId) : undefined, activePathRef.current ?? undefined);
++ if (live.length > 0) setModels(live);
++ if (available?.length) { setCatalogCommands(available); setCommands(old => ({ ...old, [chatId]: available })); }
++ if (current) {
++ setChatModel(chatId, current);
++ setModelKey((fallback) => fallback ?? current);
++ }
++ } catch {
++ // Do not invent a selected model when the catalog is unavailable.
++ }
++ };
++
++ // Refresh the catalog on focus. If its agent was
++ // not up yet, or the page outlived a restart — would show the fallback
++ // for good, so ask again whenever the window comes back to the front.
++ const catalogRef = useRef({ adopt: (_: number) => {}, activeId: 1 });
++ useEffect(() => {
++ const again = () => {
++ if (document.visibilityState === "hidden") return;
++ catalogRef.current.adopt(catalogRef.current.activeId);
++ };
++ window.addEventListener("focus", again);
++ document.addEventListener("visibilitychange", again);
++ return () => {
++ window.removeEventListener("focus", again);
++ document.removeEventListener("visibilitychange", again);
++ };
++ }, []);
++
++ const requireSession = async (chatId: number, reset = false, key?: string): Promise<string> => {
++ if (chatsRef.current.find(c => c.id === chatId)?.snapshot) throw new Error("Continue here before resuming this saved snapshot.");
++ const live = sessionsRef.current.get(chatId);
++ if (!reset && live) return live;
++ const chat = chatsRef.current.find((c) => c.id === chatId);
++ // A tab spawns where it was opened; the first tab, opened before the
++ // workspace list loaded, takes the active workspace.
++ const cwd = chat?.cwd ?? activePathRef.current ?? undefined;
++ const ws = findWorkspace(workspacesRef.current, cwd);
++ const spawnModel = key ?? chat?.model ?? ws?.model ?? model ?? undefined;
++ const { sessionId: id, commands } = await ensureSession(handleOf(chatId), {
++ model: spawnModel,
++ reset,
++ resume: sessionNamesRef.current.get(chatId),
++ cwd,
++ yolo: ws?.yolo,
++ mcp: ws?.mcp,
++ });
++ sessionsRef.current.set(chatId, id);
++ setSessionIds((current) => ({ ...current, [chatId]: id }));
++ // Populate the command menu from this agent's advertisement.
++ if (commands.length > 0) setCommands((current) => ({ ...current, [chatId]: commands }));
++ setHealth({ ok: true });
++ await adoptCatalog(chatId);
++ return id;
++ };
++
++ useEffect(() => {
++ let cancelled = false;
++ (async () => {
++ const h = await checkHealth();
++ if (cancelled) return;
++ setHealth(h);
++ if (!h.ok) return;
++ // The server's default workspace is always a row; the remembered pick
++ // wins when it is still listed, else the default is active.
++ const root = h.cwd ?? "";
++ const savedProjects = await restoreProjects(window.localStorage);
++ if (cancelled) return;
++ let list = savedProjects.list;
++ if (root && !findWorkspace(list, root)) list = upsertWorkspace(list, { path: root, name: basename(root) });
++ const remembered = savedProjects.active;
++ const active = findWorkspace(list, remembered)?.path ?? findWorkspace(list, root)?.path ?? list[0]?.path ?? null;
++ workspacesRef.current = list;
++ activePathRef.current = active;
++ setWorkspaces(list);
++ setActivePath(active);
++ persistProjects(window.localStorage, list, active);
++ if (active) setChats((current) => current.map((c) => (c.id === 1 && !c.cwd ? { ...c, cwd: active } : c)));
++ void refreshStored();
++ try {
++ const session = newSessionName();
++ sessionNamesRef.current.set(1, session);
++ setChats((current) => current.map((c) => (c.id === 1 ? { ...c, session } : c)));
++ if (window.graffDesktop) { await adoptCatalog(1); return; } // No coding session needed.
++ await requireSession(1);
++ if (cancelled) return;
++ await adoptCatalog(1);
++ } catch (err) {
++ if (!cancelled) {
++ setHealth({ ok: false, detail: err instanceof Error ? err.message : String(err) });
++ }
++ }
++ })();
++ void refreshStored();
++ // Reap this page's agents when it goes away — without this every reload
++ // leaves a `graff acp` (and its MCP children) running under the dev server.
++ const page = pageRef.current;
++ const reap = () => disposePage(page);
++ window.addEventListener("pagehide", reap);
++ return () => {
++ cancelled = true;
++ window.removeEventListener("pagehide", reap);
++ };
++ // The first tab's agent is spawned once per mount; later tabs spawn their
++ // own on creation, and a model change respawns only the active tab's.
++ // eslint-disable-next-line react-hooks/exhaustive-deps
++ }, []);
++
++ /** Re-read the active workspace's session directory; tabs adopt the
++ * titles graff saved. */
++ const refreshStored = async () => {
++ try {
++ const page = await listSessionsPage({ root: activePathRef.current ?? undefined, limit: SIDEBAR_PAGE });
++ setStored(page.sessions);
++ setStoredTotal(page.total);
++ setChats((current) =>
++ current.map((c) => {
++ if (c.titledByModel) return c;
++ const saved = c.session ? page.sessions.find((s) => s.name === c.session) : undefined;
++ return saved?.title && saved.title !== c.title ? { ...c, title: saved.title } : c;
++ }),
++ );
++ } catch {
++ // the sidebar keeps its last list
++ }
++ };
++
++ catalogRef.current = { adopt: (id: number) => { if (!runningRef.current.has(id)) void adoptCatalog(id).catch(() => undefined); }, activeId };
++ return { adoptCatalog, requireSession, refreshStored };
++}
diff --cc apps/native/electron/agents-visual.cjs
index 622745fe,02eaeff8..c3c846e4
--- a/apps/native/electron/agents-visual.cjs
+++ b/apps/native/electron/agents-visual.cjs
@@@ -7,12 -6,15 +7,15 @@@ async function runAgentVisuals({ win, o
const selectChild = id => js(`(()=>{const id=${JSON.stringify(id)}, button=document.querySelector('[data-child-agent="'+id+'"]');if(button){button.click();return;}const select=document.querySelector('[aria-label="Select sub-agent"]');Object.getOwnPropertyDescriptor(HTMLSelectElement.prototype,'value').set.call(select,id);select.dispatchEvent(new Event('change',{bubbles:true}));})()`);
const wait = async source => { for (let i = 0; i < 200; 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();
+ testDesktop.present(win);
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)');
diff --cc apps/native/electron/workspace-layout-visual.cjs
index 00000000,f3116c64..7bbb337f
mode 000000,100644..100644
--- a/apps/native/electron/workspace-layout-visual.cjs
+++ b/apps/native/electron/workspace-layout-visual.cjs
@@@ -1,0 -1,115 +1,122 @@@
+ // Headless, synthetic checks against the production GUI. No agent/provider calls.
-const { app, BrowserWindow } = require('electron');
++const testDesktop = require('./test-desktop.cjs');
++const { app } = 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);
++let stage = "startup";
++const deadline = setTimeout(() => { console.error(`Workspace deadline during ${stage}`); 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,
++ stage = "create hidden window";
++ win = testDesktop.createWindow({ width: 1440, height: 920, show: false, webPreferences: {
++ sandbox: true, contextIsolation: true, nodeIntegration: false, backgroundThrottling: false,
+ } });
+ 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');
++ testDesktop.attachTestDebugger(wc);
++ stage = 'enable page debugger';
+ await wc.debugger.sendCommand('Page.enable');
++ stage = 'install fixture';
+ 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 js = source => { stage = source; return 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);
+ };
++ stage = "load production GUI";
+ 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');
++ assert.equal(await js(`!!document.querySelector('[data-tasks-sidebar]')`), 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 wait(`!!document.querySelector('[aria-label="Close tasks"]')`);
++ await click('[aria-label="Close 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');
++ assert.equal(await js(`!!document.querySelector('[data-tasks-sidebar]')`), 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();
++ try { testDesktop.assertSafe(); } catch (error) { console.error(error); code = 1; }
++ testDesktop.cleanup();
+ if (server?.pid) try { process.kill(-server.pid, 'SIGTERM'); } catch {}
+ fs.rmSync(temporary, { recursive: true, force: true });
+ app.exit(code);
+ }
diff --cc apps/native/lib/acp-cancel.test.ts
index 00000000,00000000..0edabea3
new file mode 100644
--- /dev/null
+++ b/apps/native/lib/acp-cancel.test.ts
@@@ -1,0 -1,0 +1,35 @@@
++import { test, expect } from 'bun:test';
++import { finishCancelledPrompt } from './acp-cancel';
++const deferred = () => { let resolve!: () => void; const promise = new Promise<void>(r => { resolve = r; }); return { promise, resolve }; };
++test('cancel waits for the current prompt and preserves its reusable worker', async () => {
++ const pending = deferred(); const slot = { pendingPrompt: pending.promise as Promise<unknown> | null, streaming: true };
++ let expired = false;
++ const cancel = finishCancelledPrompt(slot, () => { expired = true; }, 1000);
++ expect(slot.streaming).toBe(true); pending.resolve(); await cancel;
++ expect(slot.streaming).toBe(false); expect(slot.pendingPrompt).toBeNull(); expect(expired).toBe(false);
++});
++test('cancel retires a hung worker before releasing the prompt gate', async () => {
++ const slot = { pendingPrompt: deferred().promise as Promise<unknown> | null, streaming: true };
++ let expired = false;
++ await finishCancelledPrompt(slot, () => { expect(slot.streaming).toBe(true); expired = true; }, 1);
++ expect(expired).toBe(true); expect(slot.streaming).toBe(false);
++});
++test('a late cancellation does not clear the next prompt or retire its worker', async () => {
++ const first = deferred(), second = deferred();
++ const slot = { pendingPrompt: first.promise as Promise<unknown> | null, streaming: true };
++ const cancel = finishCancelledPrompt(slot, () => { throw Error('wrong worker'); }, 1000);
++ slot.pendingPrompt = second.promise; first.resolve(); await cancel;
++ expect(slot.streaming).toBe(true); expect(slot.pendingPrompt).toBe(second.promise);
++});
++test('a rejected prompt releases the cancellation gate without waiting for the grace', async () => {
++ const slot = { pendingPrompt: Promise.reject(Error('failed')) as Promise<unknown> | null, streaming: true };
++ await finishCancelledPrompt(slot, () => { throw Error('already ended'); }, 1000);
++ expect(slot.streaming).toBe(false);
++});
++test('a timeout keeps the gate closed until worker retirement completes', async () => {
++ const stopped = deferred(), retiring = deferred();
++ const slot = { pendingPrompt: deferred().promise as Promise<unknown> | null, streaming: true };
++ const cancel = finishCancelledPrompt(slot, async () => { retiring.resolve(); await stopped.promise; }, 1);
++ await retiring.promise; expect(slot.streaming).toBe(true);
++ stopped.resolve(); await cancel; expect(slot.streaming).toBe(false);
++});
diff --cc apps/native/lib/acp-cancel.ts
index 00000000,00000000..a46ec121
new file mode 100644
--- /dev/null
+++ b/apps/native/lib/acp-cancel.ts
@@@ -1,0 -1,0 +1,17 @@@
++type TurnSlot = { pendingPrompt: Promise<unknown> | null; streaming: boolean };
++
++/** A cancellation owns one prompt. Its late completion must not release another. */
++export async function finishCancelledPrompt(slot: TurnSlot, expire: () => void | Promise<void>, graceMs: number) {
++ const pending = slot.pendingPrompt;
++ if (!pending) return;
++ let timer: ReturnType<typeof setTimeout> | undefined;
++ const settled = await Promise.race([
++ pending.then(() => true, () => true),
++ new Promise<false>(resolve => { timer = setTimeout(() => resolve(false), graceMs); }),
++ ]).finally(() => clearTimeout(timer));
++ if (slot.pendingPrompt !== pending) return;
++ // A stuck worker cannot safely accept another prompt or keep broadcasting
++ // updates into its successor. Retire its transport before reopening the gate.
++ if (!settled) await expire();
++ if (slot.pendingPrompt === pending) { slot.pendingPrompt = null; slot.streaming = false; }
++}
diff --cc apps/native/lib/acp-retire.test.ts
index 00000000,00000000..87b24199
new file mode 100644
--- /dev/null
+++ b/apps/native/lib/acp-retire.test.ts
@@@ -1,0 -1,0 +1,14 @@@
++import { test, expect } from "bun:test";
++import { spawn } from "node:child_process";
++import { once } from "node:events";
++import { retireWorker } from "./acp-retire";
++
++test("recovery waits for an unresponsive worker to exit, escalating when it ignores termination", async () => {
++ const child = spawn(process.execPath, ["-e", 'process.on("SIGTERM", () => {}); console.log("ready"); setInterval(() => {}, 1000)'], { stdio: ["ignore", "pipe", "ignore"] });
++ try {
++ await once(child.stdout!, "data");
++ await retireWorker(child, 20);
++ expect(child.signalCode).toBe("SIGKILL");
++ await retireWorker(child, 20); // Already exited workers need no second wait.
++ } finally { child.kill("SIGKILL"); }
++});
diff --cc apps/native/lib/acp-retire.ts
index 00000000,00000000..f2bea7c4
new file mode 100644
--- /dev/null
+++ b/apps/native/lib/acp-retire.ts
@@@ -1,0 -1,0 +1,15 @@@
++import type { ChildProcess } from "node:child_process";
++
++/** A replacement must not load a session while its old writer is still alive. */
++export function retireWorker(child: ChildProcess, graceMs = 1000): Promise<void> {
++ if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();
++ return new Promise((resolve, reject) => {
++ const timer = setTimeout(() => child.kill("SIGKILL"), graceMs);
++ const cleanup = () => { clearTimeout(timer); child.off("exit", exited); child.off("error", failed); };
++ const exited = () => { cleanup(); resolve(); };
++ const failed = (error: Error) => { cleanup(); reject(error); };
++ child.once("exit", exited);
++ child.once("error", failed);
++ child.kill("SIGTERM");
++ });
++}
diff --cc apps/native/lib/acp-route.test.ts
index 00000000,00000000..30a8b3f0
new file mode 100644
--- /dev/null
+++ b/apps/native/lib/acp-route.test.ts
@@@ -1,0 -1,0 +1,70 @@@
++import { test, expect } from "bun:test";
++import { mkdtempSync, writeFileSync, readFileSync, rmSync } from "node:fs";
++import os from "node:os";
++import path from "node:path";
++import { NextRequest } from "next/server";
++import { POST } from "../app/api/acp/route";
++
++test("a stuck cancelled ACP worker is replaced from its saved session before follow-up", async () => {
++ const temp = mkdtempSync(path.join(os.tmpdir(), "graff-acp-route-"));
++ const binary = path.join(temp, "agent.cjs");
++ const oldBin = process.env.GRAFF_BIN;
++ const oldConfig = process.env.__NEXT_PRIVATE_STANDALONE_CONFIG;
++ // This executable speaks ACP only; no model, network, or real session files.
++ writeFileSync(binary, `#!/usr/bin/env node
++const fs = require('node:fs');
++const path = require('node:path');
++const readline = require('node:readline');
++if (process.env.__NEXT_PRIVATE_STANDALONE_CONFIG) process.exit(2);
++const previous = path.join(process.cwd(), 'pid');
++if (fs.existsSync(previous)) {
++ try { process.kill(Number(fs.readFileSync(previous)), 0); process.exit(3); } catch {}
++}
++fs.writeFileSync(previous, String(process.pid));
++const resumed = process.argv.includes('--resume');
++fs.appendFileSync('starts', JSON.stringify(process.argv.slice(2))+'\\n');
++process.on('SIGTERM', () => {});
++const send = value => console.log(JSON.stringify(value));
++readline.createInterface({input:process.stdin}).on('line', line => {
++ const req=JSON.parse(line);
++ if(req.method==='initialize') send({id:req.id,result:{}});
++ if(req.method==='session/new') {
++ send({id:req.id,result:{sessionId:'saved-conversation'}});
++ send({method:'session/update',params:{update:{sessionUpdate:'available_commands_update',availableCommands:[{name:'help'}]}}});
++ }
++ if(req.method==='session/prompt') {
++ send({method:'session/update',params:{update:{sessionUpdate:'agent_message_chunk',content:{type:'text',text:resumed?'recovered':'started'}}}});
++ if(resumed) send({id:req.id,result:{stopReason:'end_turn'}});
++ }
++}).on('close',()=>process.exit(0));
++`, { mode: 0o700 });
++ const chat = `route-test-${path.basename(temp)}`;
++ const call = (method: string, params = {}) => POST(new NextRequest("http://localhost/api/acp", {
++ method: "POST", body: JSON.stringify({ chat, method, params }),
++ }));
++ try {
++ process.env.GRAFF_BIN = binary;
++ process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = "fixture";
++ const initial = await call("bootstrap", { cwd: temp, model: "fixture", yolo: false, mcp: true });
++ expect(initial.status).toBe(200);
++ const first = await call("session/prompt", { prompt: [{ type: "text", text: "start" }] });
++ const reader = first.body!.getReader();
++ expect(new TextDecoder().decode((await reader.read()).value)).toContain("started");
++ const ended = reader.read().then(() => false, () => true);
++ const cancelled = await call("session/cancel", { sessionId: "saved-conversation" });
++ expect(cancelled.status).toBe(200);
++ expect(await ended).toBe(true);
++ const next = await call("session/prompt", { prompt: [{ type: "text", text: "follow up" }] });
++ expect(next.status).toBe(200);
++ const text = await next.text();
++ expect(text).toContain("recovered");
++ expect(text).toContain('"stopReason":"end_turn"');
++ const starts = readFileSync(path.join(temp, "starts"), "utf8").trim().split("\n").map(line => JSON.parse(line));
++ expect(starts).toEqual([["acp", "--model", "fixture"], ["acp", "--model", "fixture", "--resume", "saved-conversation"]]);
++ } finally {
++ await call("dispose");
++ if (oldBin === undefined) delete process.env.GRAFF_BIN; else process.env.GRAFF_BIN = oldBin;
++ if (oldConfig === undefined) delete process.env.__NEXT_PRIVATE_STANDALONE_CONFIG; else process.env.__NEXT_PRIVATE_STANDALONE_CONFIG = oldConfig;
++ rmSync(temp, { recursive: true, force: true });
++ }
++}, 20000);
diff --cc apps/native/lib/acp-transport.test.ts
index cda3b3b6,cda3b3b6..1dade309
--- a/apps/native/lib/acp-transport.test.ts
+++ b/apps/native/lib/acp-transport.test.ts
@@@ -46,3 -46,3 +46,13 @@@ test("an oversized protocol line marks
await assert.rejects(pending, /exceeds limit/); assert.equal(transport.usable, false);
await assert.rejects(transport.request("session/prompt"), /exceeds limit/);
});
++
++test("retiring a stuck transport rejects the old prompt and discards late updates", async () => {
++ const { child, transport } = fixture(); const lines: string[] = [];
++ const pending = transport.request("session/prompt", {}, 1000, line => lines.push(line));
++ transport.abort(new Error("worker retired"));
++ await assert.rejects(pending, /worker retired/);
++ child.stdout.write(JSON.stringify({ method: "session/update", params: { text: "late" } }) + "\n");
++ assert.deepEqual(lines, []);
++ await assert.rejects(transport.request("session/prompt"), /worker retired/);
++});
diff --cc apps/native/lib/acp-transport.ts
index ab76a3c0,ab76a3c0..a281ee51
--- a/apps/native/lib/acp-transport.ts
+++ b/apps/native/lib/acp-transport.ts
@@@ -49,6 -49,6 +49,7 @@@ export class AcpTransport
for (const pending of this.pending.values()) { clearTimeout(pending.timer); pending.reject(error); }
this.pending.clear(); this.listeners.clear();
}
++ abort(error: Error) { this.fail(error); }
get usable(): boolean { return this.failure === null; }
notify(method: string, params?: unknown) {
if (this.failure) throw this.failure;
diff --cc apps/native/package.json
index 7001a256,c5155ebf..bf171ed5
--- a/apps/native/package.json
+++ b/apps/native/package.json
@@@ -22,18 -21,10 +22,19 @@@
"test:splits": "GRAFF_VISUAL_SUITE=splits bun scripts/test-visual.mjs",
"test:stress": "GRAFF_VISUAL_SUITE=stress bun scripts/test-visual.mjs",
"test:code": "GRAFF_VISUAL_SUITE=code bun scripts/test-visual.mjs",
+ "test:overflow": "GRAFF_VISUAL_SUITE=overflow node scripts/test-visual.mjs",
"test:agents": "GRAFF_VISUAL_SUITE=agents bun scripts/test-visual.mjs",
+ "test:tasks": "GRAFF_VISUAL_SUITE=tasks node scripts/test-visual.mjs",
+ "test:sessions": "GRAFF_VISUAL_SUITE=sessions bun scripts/test-visual.mjs",
+ "test:background": "bun scripts/test-background.mjs",
+ "test:native": "bun scripts/test-native.mjs",
"test:performance": "GRAFF_PERFORMANCE_TESTS=1 bun scripts/test-visual.mjs",
"benchmark:desktop": "bun scripts/benchmark-desktop.mjs",
- "test:mcp-apps": "bun test lib/mcp-apps.test.ts && playwright test -c playwright.mcp.config.ts"
+ "test:mcp-apps": "bun test lib/mcp-apps.test.ts && playwright test -c playwright.mcp.config.ts",
+ "test:focus": "bun scripts/test-desktop-focus.mjs",
+ "test:tagged": "GRAFF_VISUAL_SUITE=tagged bun scripts/test-visual.mjs",
- "test:browser": "GRAFF_VISUAL_SUITE=browser bun scripts/test-visual.mjs"
++ "test:browser": "GRAFF_VISUAL_SUITE=browser bun scripts/test-visual.mjs",
++ "test:workspace": "bun scripts/test-workspace.mjs"
},
"dependencies": {
"@streamdown/code": "^1.1.1",
diff --cc apps/native/scripts/test-workspace.mjs
index 00000000,00000000..7424e5f5
new file mode 100644
--- /dev/null
+++ b/apps/native/scripts/test-workspace.mjs
@@@ -1,0 -1,0 +1,2 @@@
++import { runElectron } from './test-electron.mjs';
++await runElectron('electron/workspace-layout-visual.cjs');
diff --cc docs/adr/0102-workspace-agents-and-cancel-recovery.md
index 00000000,00000000..95ec46f5
new file mode 100644
--- /dev/null
+++ b/docs/adr/0102-workspace-agents-and-cancel-recovery.md
@@@ -1,0 -1,0 +1,32 @@@
++# 0102. Workspace agents, explicit Tasks, and bounded cancel recovery
++
++Status: accepted 2026-09-11
++
++## Context
++
++Agent inspection needs enough room for messages without narrowing every chat.
++Task updates must respect a user's decision to dismiss the sidebar. A cancelled
++ACP prompt can fail to send its terminal reply, leaving every follow-up blocked.
++Simply clearing the streaming flag lets late replies interfere with a new turn.
++
++## Decision
++
++Agents occupies the workspace beneath a shared tab strip. Chat splits stay
++mounted while hidden so switching views preserves composer drafts. Each agent
++recipient has its own draft and sending requires an explicit action. Tasks
++visibility changes only through user controls and persists in browser storage.
++
++Cancellation waits up to eight seconds for the same pending prompt. A prompt
++that finishes remains reusable. On timeout, retire its transport, terminate the
++worker, and await process exit before a replacement loads the saved session.
++A worker ignoring termination is killed after a further second. Late replies
++cannot clear a successor's streaming gate or deliver updates into it. Recovery
++retains the workspace, session name and agent settings. Cancellation failures
++remain visible to the user.
++
++## Consequences
++
++Recovery preserves the last saved conversation; unsaved output from a stuck
++worker may be lost. The timed-out worker is not reused. Local GUI verification
++uses hidden windows under ADR 0101, including the workspace layout regression;
++native foreground coverage remains a separate GitHub Actions job.
diff --cc docs/adr/README.md
index ea523672,725315f5..01dd2ce9
--- a/docs/adr/README.md
+++ b/docs/adr/README.md
@@@ -106,13 -106,7 +106,14 @@@ record only when you need the evidence
| [0093](0093-project-layout-breadth-and-directory-hints.md) | Project layout favors breadth under its caps; missing directories offer bounded sibling hints without changing confinement or ADR 0090 constraint policy. |
| [0094](0094-subagent-interrupt-is-a-cancel-file.md) | GUI Stop writes `{id}.cancel` in the activity dir; the child finishes failed even if the model returns. Not `session/cancel`. |
| [0095](0095-mcp-apps-are-isolated-result-views.md) | MCP Apps are private saved result views in isolated GUI/browser sandboxes; app tool calls require a future approval path. |
-| [0097](0097-explicit-bash-timeout-cannot-extend-the-foreground-wait.md) | An explicit `timeout` may only shorten root foreground bash's wait, never extend it past the auto-background bound (#850). |
+| [0096](0096-desktop-link-destination.md) | Persist the desktop link destination outside origin-scoped storage; validate once and reveal the focused chat's Browser without navigating the app. |
+| [0097](0097-isolate-probe-clipboards.md) | Offline PTY probes get private clipboard commands per process; direct probe runs retain OS clipboard integration. |
+| [0098](0098-orphan-listeners-are-not-stop-authority.md) | Legacy listener discovery is read-only; stop authority requires verified ownership, port preflight checks both families, and unknown browser visibility protects listening jobs. |
+| [0099](0099-gui-saved-sessions-are-snapshots.md) | A saved-session GET is a snapshot with unknown live status; the GUI must not infer the REPL finished. |
+| [0100](0100-publication-claims-and-verified-completion.md) | Non-draft PRs fail closed on CI/Verification/helper-only claims; artifact presence ACK is not ownership; recipe success is verified task success. |
+
+| [0101](0101-gui-tests-preserve-desktop-focus.md) | GUI tests stay hidden by default; visible opt-in can overlap other apps, and native foreground checks require separate opt-in. |
++| [0102](0102-workspace-agents-and-cancel-recovery.md) | Agents uses the workspace area, Tasks visibility is explicit and persisted, and timed-out cancellation retires the worker before session recovery. |
## When to write one
diff --cc src/acp.zig
index 1b0a62bd,0b18030a..708bb603
--- a/src/acp.zig
+++ b/src/acp.zig
@@@ -525,3 -534,3 +534,24 @@@ test "ACP advertises the complete REPL
try std.testing.expectEqualStrings(command.name[1..], exposed.name);
}
}
++
++test "handleLine: live context occupancy precedes the terminal prompt reply" {
++ var state = std.heap.ArenaAllocator.init(testing.allocator);
++ defer state.deinit();
++ const a = state.allocator();
++ var buf: [16384]u8 = undefined;
++ var w: Io.Writer = .fixed(&buf);
++ const meter = struct {
++ fn read(_: *anyopaque) engine.Meter {
++ return .{ .used = 123, .window = 1000 };
++ }
++ }.read;
++ var d: Dispatch = .{ .turn = echoTurn, .ctx = undefined, .meter = meter };
++ try handleLine(&d, a, &w, "{\"id\":1,\"method\":\"session/new\"}");
++ w = .fixed(&buf);
++ try handleLine(&d, a, &w, "{\"id\":2,\"method\":\"session/prompt\",\"params\":{\"prompt\":[{\"type\":\"text\",\"text\":\"hi\"}]}}");
++ const output = w.buffered();
++ const occupancy = std.mem.indexOf(u8, output, "\"gui_context_meter\",\"used\":123,\"window\":1000") orelse return error.MissingMeter;
++ const terminal = std.mem.indexOf(u8, output, "\"stopReason\":\"end_turn\"") orelse return error.MissingTerminalReply;
++ try testing.expect(occupancy < terminal);
++}
diff --cc src/exec_bash.zig
index c76e2797,30fe29b7..db2a9be1
--- a/src/exec_bash.zig
+++ b/src/exec_bash.zig
@@@ -1,12 -1,12 +1,13 @@@
//! Root and subagent `bash` dispatch. Split out of exec.zig so the grok-build
//! auto-background path (#620) has room without growing exec.zig.
//!
-//! Root foreground: spawn a job, wait up to 120s (or `timeout` ms), then
-//! promote rather than kill — the process keeps running and the model gets a
-//! job id. Subagents stay on the #93 kill-at-120s path (no TTY, no /jobs UI).
+//! Root foreground: spawn a job, wait up to 120s (a shorter `timeout` may
+//! promote earlier; a larger one cannot extend the wait), then promote
+//! rather than kill — the process keeps running and the model gets a job
+//! id. Subagents stay on the #93 kill-at-120s path (no TTY, no /jobs UI).
const std = @import("std");
+ const builtin = @import("builtin");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const Value = std.json.Value;
@@@ -114,39 -118,81 +115,67 @@@ test "rootWaitMs: omitted/zero use 120s
try std.testing.expectEqual(@as(u64, 5_000), rootWaitMs(custom.value));
}
-// #850: `timeout` used to replace the promotion delay wholesale (capped only by
-// the 10h `wait_cap_ms`), so `{"timeout": 3600000}` parked the turn for an hour
-// — #620's failure mode, reachable through the parameter instead of a missing
-// deadline. It is a ceiling now, and the ceiling is the effective default.
-test "#850: a large explicit timeout cannot extend the foreground wait" {
- const main_mod = @import("main.zig");
- const nlt = @import("no_local_tools.zig");
- const saved_u = main_mod.unattended;
- const saved_l = nlt.lean;
- defer {
- main_mod.unattended = saved_u;
- nlt.lean = saved_l;
- }
- main_mod.unattended = false;
- const hour = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":3600000}", .{});
- defer hour.deinit();
- try std.testing.expectEqual(root_wait_ms, rootWaitMs(hour.value));
- const absurd = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":999999999}", .{});
- defer absurd.deinit();
- try std.testing.expectEqual(root_wait_ms, rootWaitMs(absurd.value));
-}
-
-test "rootWaitMs: lean unattended oneshot defaults to 15s; timeout still wins" {
- const main_mod = @import("main.zig");
- const nlt = @import("no_local_tools.zig");
- const saved_u = main_mod.unattended;
- const saved_l = nlt.lean;
- defer {
- main_mod.unattended = saved_u;
- nlt.lean = saved_l;
- }
- main_mod.unattended = true;
- nlt.lean = true;
- const empty = try std.json.parseFromSlice(Value, std.testing.allocator, "{}", .{});
- defer empty.deinit();
- try std.testing.expectEqual(lean_oneshot_wait_ms, rootWaitMs(empty.value));
- const custom = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":5000}", .{});
- defer custom.deinit();
- try std.testing.expectEqual(@as(u64, 5_000), rootWaitMs(custom.value));
- // #850: 15s is the ceiling on lean too — a longer ask still promotes at 15s.
- const long = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":60000}", .{});
- defer long.deinit();
- try std.testing.expectEqual(lean_oneshot_wait_ms, rootWaitMs(long.value));
- main_mod.unattended = false;
- try std.testing.expectEqual(root_wait_ms, rootWaitMs(empty.value));
+test "#850: a large explicit timeout cannot extend the foreground bound" {
+ const huge = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":999999999}", .{});
+ defer huge.deinit();
+ try std.testing.expectEqual(root_wait_ms, rootWaitMs(huge.value));
+ try std.testing.expect(rootWaitMs(huge.value) < job_wait.wait_cap_ms);
+ const schema = @embedFile("schema.zig");
+ try std.testing.expect(std.mem.indexOf(u8, schema, "max 36000000") == null);
}
+ // The behavior half of #850: a wait bounded at the default promotes rather than
+ // parking the turn, the child is NOT killed, and it stays reachable through the
+ // same bash_output/bash_kill the auto-background result points the model at.
-// The 120s bound itself is the constant asserted above; 200ms stands in for the
-// expiry so the test does not sleep for the real one.
++// The bound itself is the pure-function assertion above; 200ms stands in for
++// the expiry so the test does not sleep for the real one.
+ test "#850: promotion at the bound leaves the child alive and reachable" {
+ if (builtin.os.tag == .windows or builtin.os.tag == .wasi) return error.SkipZigTest;
+ jobs.g_jobs = .{};
+ const gpa = std.testing.allocator;
+ const io = std.testing.io;
+ const id = (try jobs.spawnJob(gpa, io, "sleep 5; printf never")).id;
+ defer jobs.jobsReap(gpa, io);
+ const waited = try jobs.waitForeground(gpa, io, id, 200);
+ defer switch (waited) {
+ .running => |r| gpa.free(r.output),
+ .done => |d| gpa.free(d.output),
+ .cancelled => |c| gpa.free(c.output),
+ };
+ try std.testing.expect(waited == .running);
+ try std.testing.expectEqual(id, waited.running.id);
+ const snap = try jobs.jobOutput(gpa, io, id, 0);
+ defer gpa.free(snap.text);
+ try std.testing.expect(std.mem.indexOf(u8, snap.text, "running") != null);
+ const killed = try jobs.jobKill(gpa, io, id);
+ defer gpa.free(killed.text);
+ try std.testing.expect(std.mem.indexOf(u8, killed.text, "killed") != null);
+ }
+
+test "rootWaitMs: lean unattended oneshot defaults to 15s; shorter timeout still wins" {
+ const main_mod = @import("main.zig");
+ const nlt = @import("no_local_tools.zig");
+ const saved_u = main_mod.unattended;
+ const saved_l = nlt.lean;
+ defer {
+ main_mod.unattended = saved_u;
+ nlt.lean = saved_l;
+ }
+ main_mod.unattended = true;
+ nlt.lean = true;
+ const empty = try std.json.parseFromSlice(Value, std.testing.allocator, "{}", .{});
+ defer empty.deinit();
+ try std.testing.expectEqual(lean_oneshot_wait_ms, rootWaitMs(empty.value));
+ const custom = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":5000}", .{});
+ defer custom.deinit();
+ try std.testing.expectEqual(@as(u64, 5_000), rootWaitMs(custom.value));
+ const huge = try std.json.parseFromSlice(Value, std.testing.allocator, "{\"timeout\":60000}", .{});
+ defer huge.deinit();
+ try std.testing.expectEqual(lean_oneshot_wait_ms, rootWaitMs(huge.value));
+ main_mod.unattended = false;
+ try std.testing.expectEqual(root_wait_ms, rootWaitMs(empty.value));
+}
+
fn formatJobDone(gpa: Allocator, cmd: []const u8, wait: jobs.FgDone) !ToolOutput {
defer gpa.free(wait.output);
var aw: Io.Writer.Allocating = .init(gpa);
diff --cc src/schema.zig
index 61e77589,85a87a79..b7e43ace
--- a/src/schema.zig
+++ b/src/schema.zig
@@@ -53,9 -53,9 +53,9 @@@ const empty_schema
pub const base_specs = [_]ToolSpec{
.{
.name = "bash",
- .desc = "Run a shell command via /bin/sh -c in the current working directory. Returns stdout, stderr, and the exit code. A user-cancelled command reports cancelled (its whole local process group is killed; a remote process started over ssh may survive on the remote host). Foreground commands that are still running after 120s (or a shorter `timeout` ms) are moved to the background and return a job id — the process keeps running. For long-running commands set run_in_background true to skip the wait. You are notified on completion — do not poll. bash_output(wait_ms>0) blocks until exit (up to 10h); omit wait_ms for a snapshot. Stop it with bash_kill. A background job that writes nothing and is read by nobody for 2 hours is stopped for inactivity and you are told; rerun it only if it is still needed (the user pins a long-lived server with /jobs keep).",
+ .desc = "Run a shell command via /bin/sh -c in the current working directory. Returns stdout, stderr, and the exit code. A user-cancelled command reports cancelled (its whole local process group is killed; a remote process started over ssh may survive on the remote host). Foreground commands that are still running after 120s (or a shorter timeout ms) are moved to the background and return a job id — the process keeps running. For long-running commands set run_in_background true to skip the wait. You are notified on completion — do not poll. bash_output(wait_ms>0) blocks until exit (up to 10h); omit wait_ms for a snapshot. Stop it with bash_kill. A background job that writes nothing and is read by nobody for 2 hours is stopped for inactivity and you are told; rerun it only if it is still needed (the user pins a long-lived server with /jobs keep).",
.schema =
- \\{"type": "object", "properties": {"command": {"type": "string", "description": "Shell command to execute"}, "timeout": {"type": "integer", "description": "Optional foreground wait in milliseconds before auto-background. A shorter value promotes earlier; a larger value cannot extend past the 120s (lean -p: 15s) bound. 0 uses the default. Ignored when run_in_background is true."}, "run_in_background": {"type": "boolean", "description": "Start as a background job and return its id immediately instead of waiting (default false)"}}, "required": ["command"]}
- \\{"type": "object", "properties": {"command": {"type": "string", "description": "Shell command to execute"}, "timeout": {"type": "integer", "description": "Optional foreground wait in milliseconds before auto-background; it may only SHORTEN the 120000 ms default — a larger value is clamped to it, never allowed to extend the wait. To wait for a genuinely long command, set run_in_background true and use bash_output(wait_ms>0), which blocks until exit (10h cap). 0 uses the default. Ignored when run_in_background is true."}, "run_in_background": {"type": "boolean", "description": "Start as a background job and return its id immediately instead of waiting (default false)"}}, "required": ["command"]}
++ \\{"type": "object", "properties": {"command": {"type": "string", "description": "Shell command to execute"}, "timeout": {"type": "integer", "description": "Optional foreground wait in milliseconds before auto-background. A shorter value promotes earlier; a larger value cannot extend past the 120s (lean -p: 15s) bound — to wait for a genuinely long command, set run_in_background true and use bash_output(wait_ms>0), which blocks until exit (10h cap). 0 uses the default. Ignored when run_in_background is true."}, "run_in_background": {"type": "boolean", "description": "Start as a background job and return its id immediately instead of waiting (default false)"}}, "required": ["command"]}
,
},
.{