graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Restore saved protocol sessions and route tool approvals to clients
Rach Pradhan361be87c3af5
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsindex c51784e2..ffec679c 100644--- a/apps/native/app/api/acp/route.ts+++ b/apps/native/app/api/acp/route.ts@@ -380,6 +380,13 @@ export async function POST(req: NextRequest) {});return Response.json({ sessionId: slot.sessionId, cwd: slot.cwd, commands: slot.commands });}+ if (method === "session/permission") {+ const current = slots.get(chat);+ const { requestId, sessionId, optionId } = body.params ?? {};+ if (!current || typeof sessionId !== "string" || current.sessionId !== sessionId || typeof requestId !== "string" || !(optionId === null || typeof optionId === "string") || !current.transport.respondPermission(requestId, sessionId, optionId))+ return Response.json({ error: "Permission request is no longer active or response is invalid" }, { status: 409 });+ return Response.json({ ok: true });+ }const slot = await bootstrap(chat, { model });if (method === "session/cancel") {try {@@ -442,7 +449,7 @@ export async function POST(req: NextRequest) {slot.pendingPrompt = pending;// Both rejection and success settle the gate without changing the wire outcome.const settled = () => {- if (slot.pendingPrompt === pending) { slot.pendingPrompt = null; slot.streaming = false; }+ if (slot.pendingPrompt === pending) { slot.transport.clearPermissions(); slot.pendingPrompt = null; slot.streaming = false; }if (slots.get(chat) === slot) watchIdle(chat, slot);};void pending.then(settled, settled);diff --git a/apps/native/components/site/GraffHarness.tsx b/apps/native/components/site/GraffHarness.tsxindex 155aedee..07d6650d 100644--- a/apps/native/components/site/GraffHarness.tsx+++ b/apps/native/components/site/GraffHarness.tsx@@ -1,4 +1,5 @@"use client";+import { useAcpPermissions } from "./useAcpPermissions";import SessionTabs from "./SessionTabs";import { useResponsiveNavigation } from "./useResponsiveNavigation";import { useNavigationPromptFocus } from "./useNavigationPromptFocus";@@ -169,6 +170,7 @@ export default function GraffHarness() {const { paneRef, tailing } = useChatScroll(chats, columnKey);const sessionId = sessionIds[chatThread.id] ?? null;const handleOf = (chatId: number) => chatHandle(pageRef.current, chatId);+ const permissions = useAcpPermissions(handleOf);const setBusyFor = (chatId: number, on: boolean) =>setBusyIds((current) => {if (current.has(chatId) === on) return current;@@ -185,7 +187,7 @@ export default function GraffHarness() {setPinsByChat(pinsRef.current);};- const { adoptCatalog, requireSession, refreshStored, projectsReady, unwatchIdle, chatCatalogs, catalogStatus, applyCatalog } = useHarnessSessions({+ const { adoptCatalog, requireSession, refreshStored, projectsReady, unwatchIdle, chatCatalogs, catalogStatus, applyCatalog } = useHarnessSessions({ onPermission: permissions.update,sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal,pendingPick: () => pendingPickRef.current ?? pendingModel,});@@ -219,11 +221,10 @@ export default function GraffHarness() {});const modelLabel = (key: string | null | undefined) => modelDisplayName(models, key);- const runPrompt = createPromptRunner({ onStarted: started, onCompleted: completed,+ const runPrompt = createPromptRunner({ onPermission: permissions.update, onStarted: started, onCompleted: completed,runningRef, steerer, setFollowing, chatsRef, model, msgIdRef, setChats, setBusyFor, setHistory, pinsRef, handleOf, setPins, requireSession, prepareModel, adoptCatalog, refreshStored, takeQueuedPrompt, setCancelError});const settings = useQuietSettings({ requireSession, handleOf, running: runningRef.current, apply: applyCatalog });-const send = async (text: string, forChat?: number) => {const trimmed = text.trim();const chatId = forChat ?? chatThread.id;@@ -452,14 +453,13 @@ export default function GraffHarness() {resizePane: delta => groups.resize(delta/4),toggleTerminal, equalize: groups.balance, openWorkspace: () => setDialog({ mode: "new" }),});-const paneTodos = lastAssistant?.turn.todos ?? [];// Zoom only changes visibility; the split order is retained.const columns = (zoomedPane !== null ? [zoomedPane] : columnIds).map((id) => chats.find((c) => c.id === id)).filter((c): c is Chat => c !== undefined);-return (<main ref={promptFocusRoot} data-graff-main data-workspace-ready={projectsReady} className="flex h-[100dvh] gap-0 bg-canvas p-2.5 text-ink lg:pl-0">+ {permissions.dialog}<div {...navigation.panelProps}><SidebarNavonCloseNavigation={navigation.close} onCollapsedChange={navigation.onCollapsedChange}openSessions={navigation.sidebarVisible && <div className="mb-4">diff --git a/apps/native/components/site/harness-prompt-runner.ts b/apps/native/components/site/harness-prompt-runner.tsindex 810df190..da48d1c4 100644--- a/apps/native/components/site/harness-prompt-runner.ts+++ b/apps/native/components/site/harness-prompt-runner.ts@@ -1,3 +1,4 @@+import type { PermissionRequest } from "@/lib/acp-permission";import type { MutableRefObject, Dispatch, SetStateAction } from "react";import { createTurnPainter } from "@/lib/turn-painter";import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AssistantTurn } from "@/lib/acp";@@ -13,6 +14,7 @@ import { playUiSound } from "@/lib/ui-sounds";type Ref<T> = MutableRefObject<T>;type Setter<T> = Dispatch<SetStateAction<T>>;type Props = {+ onPermission?(chatId: number, request: PermissionRequest | null): void;onStarted(id: number): void;onCompleted(id: number): void;runningRef: Ref<Set<number>>; steerer: ReturnType<typeof createQueueSteerer>; setFollowing: Setter<boolean>;@@ -25,7 +27,7 @@ type Props = {adoptCatalog(id: number): Promise<void>; refreshStored(): Promise<void>;takeQueuedPrompt(id: number): QueuedPrompt | undefined;};-export function createPromptRunner({onStarted, onCompleted, runningRef, steerer, setFollowing, chatsRef, model, msgIdRef, setChats, setBusyFor, setHistory, pinsRef, handleOf, setPins, requireSession, prepareModel, adoptCatalog, refreshStored, takeQueuedPrompt, setCancelError}: Props) {+export function createPromptRunner({onPermission, onStarted, onCompleted, runningRef, steerer, setFollowing, chatsRef, model, msgIdRef, setChats, setBusyFor, setHistory, pinsRef, handleOf, setPins, requireSession, prepareModel, adoptCatalog, refreshStored, takeQueuedPrompt, setCancelError}: Props) {const patchAssistant = (chatId: number, msgId: number, next: AssistantTurn) => {setChats((current) =>current.map((c) =>@@ -104,6 +106,7 @@ export function createPromptRunner({onStarted, onCompleted, runningRef, steerer,turn = { ...turn, connected: true, lastUpdateAt: Date.now() };painter.update(turn);for await (const update of prompt(handleOf(chatId), id, wire)) {+ if (update.sessionUpdate === "gui_permission") { onPermission?.(chatId, update.permission as PermissionRequest); continue; }// The bridge acknowledges prompt dispatch before model output, so// queued steering can cancel even during a slow first response.if (update.sessionUpdate === "gui_turn_end") steerer.finish(chatId);@@ -127,6 +130,7 @@ export function createPromptRunner({onStarted, onCompleted, runningRef, steerer,painter.finish(turn);playUiSound("error");} finally {+ onPermission?.(chatId, null);painter.dispose();steerer.finish(chatId);runningRef.current.delete(chatId);diff --git a/apps/native/components/site/idle-peer-turns.ts b/apps/native/components/site/idle-peer-turns.tsindex 1b8bc4f1..4f235d36 100644--- a/apps/native/components/site/idle-peer-turns.ts+++ b/apps/native/components/site/idle-peer-turns.ts@@ -1,3 +1,4 @@+import type { PermissionRequest } from "@/lib/acp-permission";import { applyAcpUpdate, emptyTurn, finishAcpTurn, type AssistantTurn } from "@/lib/acp";import { idleUpdates, type ChatHandle } from "@/lib/acp-client";import { holdIdleUntilAbort } from "@/lib/idle-http";@@ -9,6 +10,7 @@ import { playUiSound } from "@/lib/ui-sounds";* or other POST during one chat's turn can use the origin's connection slots* no matter how many background tabs hold streams (#1068). */export async function pumpIdlePeerTurns(opts: {+ onPermission?(chat: number, request: PermissionRequest | null): void;chatId: number;handle: ChatHandle;sessionId: string;@@ -19,6 +21,8 @@ export async function pumpIdlePeerTurns(opts: {let asstId: number | undefined;const paint = (update: Parameters<typeof applyAcpUpdate>[1]) => {if (opts.running() || opts.signal.aborted) return;+ if (update.sessionUpdate === "gui_permission") { opts.onPermission?.(opts.chatId, update.permission as PermissionRequest); return; }+ if (update.sessionUpdate === "gui_turn_end") opts.onPermission?.(opts.chatId, null);let cue: "error" | "ready" | null = null;opts.setChats(current => current.map(chat => {if (chat.id !== opts.chatId) return chat;diff --git a/apps/native/components/site/useAcpPermissions.tsx b/apps/native/components/site/useAcpPermissions.tsxnew file mode 100644index 00000000..3ffe2665--- /dev/null+++ b/apps/native/components/site/useAcpPermissions.tsx@@ -0,0 +1,30 @@+"use client";+import { useState } from "react";+import { answerPermission, type PermissionRequest } from "@/lib/acp-permission";+export function useAcpPermissions(handleOf: (id: number) => string) {+ const [requests, setRequests] = useState<Record<number, PermissionRequest>>({});+ const [busy, setBusy] = useState<string | null>(null);+ const [error, setError] = useState("");+ const update = (chat: number, request: PermissionRequest | null) => setRequests(current => {+ const next = { ...current }; if (request) next[chat] = request; else delete next[chat]; return next;+ });+ const entry = Object.entries(requests)[0];+ const respond = async (chat: number, request: PermissionRequest, option: string | null) => {+ setBusy(request.requestId); setError("");+ try {+ await answerPermission(handleOf(chat), request, option);+ setRequests(current => { if (current[chat]?.requestId !== request.requestId) return current; const next = { ...current }; delete next[chat]; return next; });+ } catch (e) { setError(e instanceof Error ? e.message : String(e)); }+ finally { setBusy(null); }+ };+ const dialog = entry ? <div role="dialog" aria-modal="true" aria-label="Tool permission" className="fixed inset-0 z-50 grid place-items-center bg-black/40">+ <section className="max-w-lg rounded-xl bg-background p-6 shadow-xl">+ <h2 className="font-semibold">Allow this tool in chat {entry[0]}?</h2>+ <p className="my-4 whitespace-pre-wrap break-words">{entry[1].toolCall.title ?? entry[1].toolCall.toolCallId}</p>+ <div className="flex flex-wrap gap-2">{entry[1].options.map(option => <button className="rounded border px-3 py-2" disabled={busy === entry[1].requestId} key={option.optionId} onClick={() => void respond(Number(entry[0]), entry[1], option.optionId)}>{option.name}</button>)}+ <button className="rounded border px-3 py-2" disabled={busy === entry[1].requestId} onClick={() => void respond(Number(entry[0]), entry[1], null)}>Cancel request</button>+ </div>{error && <p role="alert" className="mt-3 text-red">{error}</p>}+ </section>+ </div> : null;+ return { update, dialog };+}diff --git a/apps/native/components/site/useHarnessSessions.ts b/apps/native/components/site/useHarnessSessions.tsindex 72227695..11569e13 100644--- a/apps/native/components/site/useHarnessSessions.ts+++ b/apps/native/components/site/useHarnessSessions.ts@@ -1,3 +1,4 @@+import type { PermissionRequest } from "@/lib/acp-permission";import { useEffect, useRef, useState, type MutableRefObject, type Dispatch, type SetStateAction } from "react";import { bindMcpAppChat, checkHealth, disposePage, ensureSession, fetchModels, type Health } from "@/lib/acp-client";import { shouldReapPage } from "@/lib/acp-terminate";@@ -12,6 +13,7 @@ import { newSessionName, type Chat } from "./harness-types";type Ref<T> = MutableRefObject<T>;type Setter<T> = Dispatch<SetStateAction<T>>;type Props = {+ onPermission?(chat: number, request: PermissionRequest | null): void;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;@@ -24,7 +26,7 @@ type Props = {pendingPick(): { key: string; chatId: number } | null;};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, pendingPick}: Props) {+export function useHarnessSessions({onPermission, sessionsRef, sessionNamesRef, chatsRef, workspacesRef, activePathRef, pageRef, runningRef, model, activeId, handleOf, setModels, setCommands, setCatalogCommands, setChatModel, setModelKey, setSessionIds, setHealth, setWorkspaces, setActivePath, setChats, setStored, setStoredTotal, pendingPick}: Props) {const [projectsReady, setProjectsReady] = useState(false);const [chatCatalogs, setChatCatalogs] = useState<Record<number, PromptModel[]>>({});const [catalogStatus, setCatalogStatus] = useState<Record<number, { loading: boolean; error?: string }>>({});@@ -44,7 +46,7 @@ export function useHarnessSessions({sessionsRef, sessionNamesRef, chatsRef, workconst ac = new AbortController();idleCtl.current.set(chatId, ac);void pumpIdlePeerTurns({- chatId, handle: handleOf(chatId), sessionId, signal: ac.signal,+ onPermission, chatId, handle: handleOf(chatId), sessionId, signal: ac.signal,// Every pump pauses while ANY turn runs: the six-slot HTTP/1.1 pool is// per origin, so one chat's turn frees the idle streams of all the// others or a mid-turn attach never starts.diff --git a/apps/native/lib/acp-client.ts b/apps/native/lib/acp-client.tsindex dc939700..510c42d6 100644--- a/apps/native/lib/acp-client.ts+++ b/apps/native/lib/acp-client.ts@@ -1,3 +1,4 @@+import { permissionRequest } from "./acp-permission";import { parseRpcLine, type AcpCommand, type AcpUpdate, type JsonRpcLine } from "./acp";import { liveAppearanceTokens } from "./appearance-note";import { readAnswerResponse, validateAnswer } from "./ask-answer";@@ -117,6 +118,8 @@ export async function* prompt(}, true);let terminal = false;for await (const line of ndjson(res)) {+ const permission = permissionRequest(line);+ if (permission) { yield { sessionUpdate: "gui_permission", permission }; continue; }if ("method" in line && line.method === "session/update") {yield line.params.update;continue;@@ -151,6 +154,8 @@ export async function* idleUpdates(throw new Error(`ACP session/idle → ${res.status}: ${detail.slice(0, 240)}`);}for await (const line of ndjson(res)) {+ const permission = permissionRequest(line);+ if (permission) { yield { sessionUpdate: "gui_permission", permission }; continue; }if ("method" in line && line.method === "session/update") yield line.params.update;}}diff --git a/apps/native/lib/acp-permission.test.ts b/apps/native/lib/acp-permission.test.tsnew file mode 100644index 00000000..f855a102--- /dev/null+++ b/apps/native/lib/acp-permission.test.ts@@ -0,0 +1,36 @@+import { test, expect } from "bun:test";+import { EventEmitter } from "node:events";+import { PassThrough } from "node:stream";+import { AcpTransport } from "./acp-transport";+import { permissionRequest } from "./acp-permission";+function fixture() {+ const child = Object.assign(new EventEmitter(), {stdout:new PassThrough(),stdin:new PassThrough()});+ const lines:string[]=[]; const writes:string[]=[];+ child.stdin.on("data",chunk=>writes.push(chunk.toString()));+ const transport = new AcpTransport(child as never); transport.subscribe(line=>lines.push(line));+ return {child,transport,lines,writes};+}+const request={jsonrpc:"2.0",id:"graff-permission-1",method:"session/request_permission",params:{sessionId:"s",toolCall:{toolCallId:"call1",title:"run command"},options:[{optionId:"once",name:"Allow once",kind:"allow_once"},{optionId:"always",name:"Always allow command",kind:"allow_always"},{optionId:"reject",name:"Reject",kind:"reject_once"}]}};+test("permission replies bind process, session, original ID and offered option exactly once",()=>{+ const f=fixture(); f.child.stdout.write(JSON.stringify(request)+"\n");+ const r=permissionRequest(JSON.parse(f.lines[0]))!;+ expect(r.requestId).not.toBe(request.id);+ expect(f.transport.respondPermission(r.requestId,"other","once")).toBe(false);+ expect(f.transport.respondPermission(r.requestId,"s","invented")).toBe(false);+ expect(f.transport.respondPermission(r.requestId,"s","always")).toBe(true);+ expect(f.transport.respondPermission(r.requestId,"s","once")).toBe(false);+ expect(JSON.parse(f.writes[0])).toEqual({jsonrpc:"2.0",id:request.id,result:{outcome:{outcome:"selected",optionId:"always"}}});+ const replacement=fixture(); replacement.child.stdout.write(JSON.stringify(request)+"\n");+ expect(replacement.transport.respondPermission(r.requestId,"s","once")).toBe(false);+});+test("cancel, prompt finish and child exit invalidate pending permissions",()=>{+ for(const finish of ["cancel","finish","exit"]){+ const f=fixture();f.child.stdout.write(JSON.stringify(request)+"\n");const r=permissionRequest(JSON.parse(f.lines[0]))!;+ if(finish==="cancel") f.transport.notify("session/cancel",{sessionId:"s"});+ else if(finish==="finish") f.transport.clearPermissions(); else f.child.emit("close",1,null);+ expect(f.transport.respondPermission(r.requestId,"s","once")).toBe(false);+ }+ const f=fixture();f.child.stdout.write(JSON.stringify(request)+"\n");const r=permissionRequest(JSON.parse(f.lines[0]))!;+ expect(f.transport.respondPermission(r.requestId,"s",null)).toBe(true);+ expect(JSON.parse(f.writes[0]).result.outcome).toEqual({outcome:"cancelled"});+});diff --git a/apps/native/lib/acp-permission.ts b/apps/native/lib/acp-permission.tsnew file mode 100644index 00000000..964123d7--- /dev/null+++ b/apps/native/lib/acp-permission.ts@@ -0,0 +1,18 @@+export type PermissionRequest = {+ requestId: string;+ sessionId: string;+ toolCall: { toolCallId: string; title?: string };+ options: { optionId: string; name: string; kind: string }[];+};+export function permissionRequest(message: unknown): PermissionRequest | null {+ const m = message as { id?: unknown; method?: unknown; params?: Partial<PermissionRequest> };+ const p = m?.params;+ if (m?.method !== "session/request_permission" || typeof m.id !== "string" || typeof p?.sessionId !== "string" || typeof p.toolCall?.toolCallId !== "string" || !Array.isArray(p.options)) return null;+ const options = p.options.filter(o => typeof o?.optionId === "string" && typeof o.name === "string" && ["allow_once", "allow_always", "reject_once", "reject_always"].includes(o.kind));+ if (!options.length || options.length !== p.options.length) return null;+ return { requestId: m.id, sessionId: p.sessionId, toolCall: p.toolCall, options };+}+export async function answerPermission(chat: string, request: PermissionRequest, optionId: string | null): Promise<void> {+ const response = await fetch("/api/acp", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ chat, method: "session/permission", params: { requestId: request.requestId, sessionId: request.sessionId, optionId } }) });+ if (!response.ok) throw new Error((await response.json()).error ?? "Permission response was not delivered");+}diff --git a/apps/native/lib/acp-transport.ts b/apps/native/lib/acp-transport.tsindex deb333f2..d6eec3c4 100644--- a/apps/native/lib/acp-transport.ts+++ b/apps/native/lib/acp-transport.ts@@ -1,12 +1,24 @@+import { randomUUID } from "node:crypto";+import { permissionRequest } from "./acp-permission";import type { ChildProcessByStdio } from "node:child_process";import type { Readable, Writable } from "node:stream";import { StringDecoder } from "node:string_decoder";type Child = ChildProcessByStdio<Writable, Readable, null>;-type Message = { id?: number; method?: string; params?: unknown; result?: unknown; error?: { message?: string } };+type Message = { id?: number | string; method?: string; params?: unknown; result?: unknown; error?: { message?: string } };type Pending = { resolve(value: unknown): void; reject(error: Error): void; timer: ReturnType<typeof setTimeout>; onLine?: (line: string) => void };/** Exactly one stdout reader. RPCs never consume another request's notifications. */export class AcpTransport {+ private permissions = new Map<string, { id: number | string; session: string; options: Set<string> }>();+ clearPermissions() { this.permissions.clear(); }+ respondPermission(token: string, session: string, optionId: string | null): boolean {+ const request = this.permissions.get(token);+ if (!request || request.session !== session || (optionId !== null && !request.options.has(optionId)) || this.failure) return false;+ this.permissions.delete(token);+ const outcome = optionId === null ? { outcome: "cancelled" } : { outcome: "selected", optionId };+ this.child.stdin.write(JSON.stringify({ jsonrpc: "2.0", id: request.id, result: { outcome } }) + "\n");+ return true;+ }private nextId = 1;private buffer = "";private decoder = new StringDecoder("utf8");@@ -26,9 +38,22 @@ export class AcpTransport {let newline;while ((newline = this.buffer.indexOf("\n")) >= 0) {if (newline > 8 * 1024 * 1024) { this.fail(new Error("ACP line exceeds limit")); return; }- const line = this.buffer.slice(0, newline); this.buffer = this.buffer.slice(newline + 1);+ let line = this.buffer.slice(0, newline); this.buffer = this.buffer.slice(newline + 1);let message: Message;try { message = JSON.parse(line); } catch { continue; }+ if (message.method === "session/request_permission" && (typeof message.id === "string" || typeof message.id === "number")) {+ const permission = permissionRequest({ ...message, id: String(message.id) });+ if (permission) {+ const token = randomUUID();+ this.permissions.set(token, { id: message.id, session: permission.sessionId, options: new Set(permission.options.map(o => o.optionId)) });+ message = { ...message, id: token };+ line = JSON.stringify(message);+ }+ }+ if (message.method === "session/update") {+ const params = message.params as { update?: { sessionUpdate?: string } };+ if (params?.update?.sessionUpdate === "gui_turn_end") this.clearPermissions();+ }if (message.method) {this.notification(message);for (const listener of this.listeners) listener(line);@@ -45,6 +70,7 @@ export class AcpTransport {private fail(error: Error) {if (this.failure) return;this.failure = error;+ this.clearPermissions();this.buffer = "";for (const pending of this.pending.values()) { clearTimeout(pending.timer); pending.reject(error); }this.pending.clear(); this.listeners.clear();@@ -56,6 +82,7 @@ export class AcpTransport {return () => { this.listeners.delete(fn); };}notify(method: string, params?: unknown) {+ if (method === "session/cancel") this.clearPermissions();if (this.failure) throw this.failure;this.child.stdin.write(JSON.stringify({ jsonrpc: "2.0", method, params }) + "\n");}diff --git a/apps/native/scripts/test-acp-permission-ui.mjs b/apps/native/scripts/test-acp-permission-ui.mjsnew file mode 100644index 00000000..832c487e--- /dev/null+++ b/apps/native/scripts/test-acp-permission-ui.mjs@@ -0,0 +1,47 @@+/** Real browser -> desktop route -> real ACP -> offline model permission proof. */+import { mkdtempSync, writeFileSync, existsSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { NextRequest } from "next/server";+import { chromium } from "playwright";+import { POST } from "../app/api/acp/route";+const temp = mkdtempSync(path.join(tmpdir(), "acp-permission-ui-"));+const binary = path.resolve(process.argv[2]);+const native = path.resolve(import.meta.dir, "..");+const repo = path.resolve(native, "../..");+const script = path.join(temp, "model.json");+writeFileSync(script, JSON.stringify([{tool:"bash",arguments:{command:"python3 -c \"open('approved.txt','w').write('approved')\""}},{text:"Approved command completed."}]));+const model = Bun.spawn(["python3",path.join(repo,"scripts/eval/mock_model.py"),"--script",script,"--port","0"],{stdout:"pipe",stderr:"inherit"});+const reader = model.stdout.getReader();+let startup = "";+while (!startup.includes("\n")) { const chunk = await reader.read(); if (chunk.done) break; startup += new TextDecoder().decode(chunk.value); }+reader.releaseLock();+const port = startup.match(/127\.0\.0\.1:(\d+)/)?.[1];+if (!port) { model.kill(); throw new Error("Mock provider did not report its port"); }+const oldEnv = {...process.env};+for(const key of Object.keys(process.env)) if(key.endsWith("_API_KEY")) delete process.env[key];+Object.assign(process.env,{HOME:temp,GRAFF_BIN:binary,AI_GATEWAY_API_KEY:"local",GRAFF_VERCEL_URL:`http://127.0.0.1:${port}/v1/chat/completions`,GRAFF_NO_TELEMETRY:"1",GRAFF_FLEET:"off",GRAFF_NO_SMOLIFY:"1",GRAFF_NO_CODEDB_GUARD:"1"});+const entry = path.join(native,".permission-ui-fixture.tsx");+writeFileSync(entry, `import React,{useEffect,useState} from 'react';import{createRoot}from'react-dom/client';import{useAcpPermissions}from'./components/site/useAcpPermissions';import{prompt}from'./lib/acp-client';function App(){const permissions=useAcpPermissions(()=>"permission-ui");const[done,setDone]=useState(false);useEffect(()=>{(async()=>{const r=await fetch('/api/acp',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({chat:'permission-ui',method:'bootstrap',params:{cwd:${JSON.stringify(temp)},model:'vercel',yolo:false,mcp:false}})});const s=await r.json();for await(const u of prompt('permission-ui',s.sessionId,'Execute the fixture command.')){if(u.sessionUpdate==='gui_permission')permissions.update(1,u.permission as any);}setDone(true);})().catch(e=>document.body.dataset.error=String(e));},[]);return <>{permissions.dialog}<p>{done?'Completed':'Running'}</p></>}createRoot(document.getElementById('root')!).render(<App/>);`);+let server;+let browser;+try {+ const build=await Bun.build({entrypoints:[entry],target:"browser",define:{"process.env.NODE_ENV":JSON.stringify("production")}});+ if(!build.success)throw new Error(String(build.logs));+ const javascript=await build.outputs[0].text();+ server=Bun.serve({port:0,fetch:async request=>new URL(request.url).pathname==='/api/acp'?POST(new NextRequest(request)):new Response(new URL(request.url).pathname==='/app.js'?javascript:'<div id="root"></div><script src="/app.js"></script>',{headers:{'content-type':new URL(request.url).pathname==='/app.js'?'text/javascript':'text/html'}})});+ browser=await chromium.launch({headless:true});const page=await browser.newPage();await page.goto(server.url.toString());+ await page.getByRole('dialog',{name:'Tool permission'}).waitFor({timeout:30000});+ if(existsSync(path.join(temp,'approved.txt')))throw new Error('Command ran before browser approval');+ await page.getByRole('button',{name:'Allow once',exact:true}).click();+ await page.getByText('Completed',{exact:true}).waitFor({timeout:30000});+ if(readFileSync(path.join(temp,'approved.txt'),'utf8')!=='approved')throw new Error('Approved command missing');+ if(await page.getByRole('dialog').count())throw new Error('Permission remained after acknowledgement');+ console.log('PASS browser permission: explicit click -> HTTP route -> ACP reply -> command execution');+} finally {+ await browser?.close();+ await POST(new NextRequest('http://localhost/api/acp',{method:'POST',body:JSON.stringify({chat:'permission-ui',method:'dispose'})}));+ server?.stop(true);model.kill();await model.exited;+ rmSync(entry,{force:true});rmSync(temp,{recursive:true,force:true});+ for(const key of Object.keys(process.env))if(!(key in oldEnv))delete process.env[key];Object.assign(process.env,oldEnv);+}diff --git a/docs/acp-client-parity.md b/docs/acp-client-parity.mdnew file mode 100644index 00000000..320667d2--- /dev/null+++ b/docs/acp-client-parity.md@@ -0,0 +1,11 @@+# ACP client behavior and limits++The live `graff acp` process speaks [ACP v1](https://agentclientprotocol.com/protocol/v1/overview). The desktop is its client: it sends prompts and renders `session/update` notifications. A streamed tool row is identified by `toolCallId`; updates change that row, and a new `content` array replaces its prior content. The turn ends when the original `session/prompt` request responds with a `stopReason`, including `cancelled` after cancellation. [Tool calls](https://agentclientprotocol.com/protocol/v1/tool-calls) and [prompt turns](https://agentclientprotocol.com/protocol/v1/prompt-turn) define those wire rules.++The desktop restores its own saved chat view and starts a replacement agent with `--resume <name>`. Separately, a v1 client may use `session/load` when the live agent advertises `loadSession`: the session ID is a saved conversation name in the selected workspace, and the agent replays retained user messages, assistant messages, and tool results before responding. Replay is display history; it does not rerun tools or revive shell jobs. The in-process embed has no durable store and does not advertise `loadSession`. [ACP session setup](https://agentclientprotocol.com/protocol/v1/session-setup) specifies the capability and replay order.++The desktop defaults to `--yolo`; setting `GRAFF_YOLO=0` opts into client permission decisions. Pending permission requests must receive a response, including a `cancelled` outcome if the turn is cancelled. [ACP permission flow](https://agentclientprotocol.com/protocol/v1/tool-calls#requesting-permission) defines the request and outcomes. A transport event alone does not establish that the visible desktop control was exercised, so permission UI needs end-to-end verification.++The agent's shell tool uses its own job handles. These are separate from ACP's optional **client-owned** `terminal/create`, `terminal/output`, `terminal/kill`, and `terminal/release` surface, which this desktop does not advertise. After a shell host restart, an old job handle must fail closed; restoring a conversation cannot make it live again. [ACP terminals](https://agentclientprotocol.com/protocol/v1/terminals) describes the separate terminal capability.++Process reliability remains a distinct limit: [issue #1193](https://github.com/justrach/codegraff/issues/1193) tracks an unverified ACP process exit during concurrent network activity. A client should report that interruption and keep completed, saved work visible; ACP protocol support alone does not prove the desktop can finish every active turn.diff --git a/docs/acp-registry.md b/docs/acp-registry.mdindex ceb182d2..1a25f931 100644--- a/docs/acp-registry.md+++ b/docs/acp-registry.md@@ -20,7 +20,8 @@ and the host recipe stays [embedding.md](embedding.md). Replace those with| Provider login | `graff login` / keychain / env keys. Not ACP `authenticate`. || `initialize.authMethods` | **Shipped.** `graff-login` / `type: "terminal"` / `args: ["login"]`. `authenticate` stays unused — the client re-spawns `graff login`. || Credential-free startup | **Shipped.** A clean `graff acp` initializes, then returns ACP `auth_required` until login and respawn. |-| `session/load`, `session/request_permission` | Not implemented. Unattended + `--yolo` is the host path. |+| `session/load` | Live CLI restores saved conversations in the selected workspace and replays retained history. |+| `session/request_permission` | Interactive clients answer tool approval requests; unattended `--yolo` remains available. See [client behavior](acp-client-parity.md). |A stale comment on #613 said #612 was still open. It is not: streaming is onthe tagged v0.0.279 cut. The final in-repo registry prerequisite was startupdiff --git a/docs/adr/0180-acp-permissions-belong-to-the-client.md b/docs/adr/0180-acp-permissions-belong-to-the-client.mdnew file mode 100644index 00000000..9e1bca02--- /dev/null+++ b/docs/adr/0180-acp-permissions-belong-to-the-client.md@@ -0,0 +1,21 @@+# 0180: ACP permissions belong to the client++Status: accepted++## Context++The engine already knows which operations require approval, but ACP previously had no frontend input bridge. Non-auto-approved desktop and editor sessions could only receive an unattended denial.++## Decision++This supersedes the permission-input limitation in ADR0032. Bind the existing engine permission handler to a standard server-initiated `session/request_permission` RPC during live ACP turns. Advertise explicit once, reject and, where the engine has a persistent approval key, always options. Always uses the existing scoped approval key and persistence mechanism; it does not widen plan mode or introduce blanket approval. Plan read requests offer once/reject only.++Match each response to one pending server request, accept only an offered option, and resolve cancellation, transport EOF or invalid responses as denial. Cancel and prompt completion retire pending input before another turn can request it. Explicit auto-approval continues to bypass requests.++The desktop owns the controls and delivery acknowledgement. It maps server IDs to unpredictable tokens scoped to the exact live transport, validates chat/session and offered options, and consumes a token once. A response from a replaced worker cannot approve the next worker even if its server IDs and restored session name repeat. Both prompt and idle-peer streams carry permission requests. Failed delivery stays visible.++## Consequences++The existing workspace auto-approval preference and default are preserved; this adds an interactive path when auto-approval is disabled. Persistent approvals retain existing scope (for example, an executable key), which is named in the Always option. No client decision bypasses unconditional engine policy checks. The bridge provides root permission input; detached worker approval policy is unchanged.++Offline coverage includes real ACP once/always/reject/cancel behavior and explicit auto-approval, transport stale/duplicate/wrong-session/unknown-option rejection, and a headless browser click through the production desktop route to actual tool execution.diff --git a/docs/adr/0181-acp-load-replays-saved-conversation.md b/docs/adr/0181-acp-load-replays-saved-conversation.mdnew file mode 100644index 00000000..9604d3eb--- /dev/null+++ b/docs/adr/0181-acp-load-replays-saved-conversation.md@@ -0,0 +1,33 @@+# 0181. ACP load replays a saved conversation in its workspace++Status: accepted 2026-09-23++## Context++The live ACP process returned a temporary protocol session ID while saving+under a different conversation name. A new client process could not use the+standard v1 `session/load` request to recover that conversation. The desktop+already has a startup `--resume` path, but an external ACP client needs a+stable ID and a protocol replay.++## Decision++The live ACP `session/new` ID is the saved conversation basename. Only the+live CLI advertises `loadSession`; the in-process embed has no durable store+and continues to advertise false. `session/load` accepts a validated basename+from the selected workspace, restores provider-native history, and replays+human messages, assistant messages, and saved tool calls/results from the+retained append-only transcript as ACP v1+updates before responding. An invocation with no saved result replays as a+failed historical call. Loading never reruns a tool or reconnects a shell job.++Malformed, missing, and workspace-mismatched IDs receive JSON-RPC errors.+The request cannot use a filesystem path as its session ID or discover a+same-named save in another workspace.++## Consequences++Clients can reload a conversation in a new ACP process and then prompt using+the restored provider context. GUI startup `--resume` remains a separate path.+The offline two-process fixture in `scripts/test-acp-session-load.py` checks+replay, follow-up context, and rejection of stale shell handles.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex c66ea32b..1073fc63 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -205,6 +205,9 @@ record only when you need the evidence or the edge cases.| [0179](0179-durable-shell-handles.md) | Reserve durable JS-exact shell handles before spawning; stale handles never target new jobs. |+| [0180](0180-acp-permissions-belong-to-the-client.md) | ACP permission decisions belong to the active client and request; cancellation never grants approval. |+| [0181](0181-acp-load-replays-saved-conversation.md) | Live ACP loads saved conversations in their selected workspace and replays history without rerunning tools. |+## When to write oneWrite an ADR when a decision is load-bearing and non-obvious: it was reacheddiff --git a/docs/embedding.md b/docs/embedding.mdindex b102854e..478ded49 100644--- a/docs/embedding.md+++ b/docs/embedding.md@@ -15,9 +15,10 @@ chips (ADR [0032](adr/0032-acp-streams-mid-turn.md)). `graff serve` is notrequired.Methods and shapes below are what `src/acp.zig` / `src/acp_protocol.zig`-actually implement. `session/load` and `session/request_permission` are not-implemented; unattended + `--yolo` is how a host that wants tools from the-first call runs the agent.+actually implement. Live agents support `session/load` for saved conversations+and send `session/request_permission` when tool approval is required. Unattended+hosts may use `--yolo`; interactive hosts must answer permission requests.+See [client behavior and limits](acp-client-parity.md).## `graff acp`@@ -33,7 +34,8 @@ session/prompt → session/update* then { stopReason }`initialize` params: `{ protocolVersion: 1, clientCapabilities: { fs: {} } }`.Negotiated version is `min(client, 1)`. Capabilities today:-`loadSession: false`, `promptCapabilities: { image: false, audio: false,+`loadSession: true` for the authenticated live CLI (`false` for the in-process+embed and pre-auth startup), `promptCapabilities: { image: false, audio: false,embeddedContext: true }`.`session/new` params may include `cwd`. After the result, the agent advertisesdiff --git a/scripts/eval-tier1.sh b/scripts/eval-tier1.shindex 7b35ffa4..c21b7eb9 100755--- a/scripts/eval-tier1.sh+++ b/scripts/eval-tier1.sh@@ -186,7 +186,9 @@ if wanted shell; thenpython3 scripts/eval/process_guard.py --timeout 180 zig build-exe src/shell_identity_probe.zig -lc -femit-bin="$probe_dir/identity" &&python3 scripts/eval/process_guard.py --timeout 60 python3 scripts/test-shell-identity.py "$probe_dir/identity" &&python3 scripts/eval/process_guard.py --timeout 90 python3 scripts/test-shell-restart.py zig-out/bin/graff &&- python3 scripts/eval/process_guard.py --timeout 90 python3 scripts/test-acp-released-fixes.py zig-out/bin/graff+ python3 scripts/eval/process_guard.py --timeout 90 python3 scripts/test-acp-released-fixes.py zig-out/bin/graff &&+ python3 scripts/eval/process_guard.py --timeout 120 python3 scripts/test-acp-permissions.py zig-out/bin/graff &&+ python3 scripts/eval/process_guard.py --timeout 90 python3 scripts/test-acp-session-load.py zig-out/bin/graff); then :; elserecord_fail shellfidiff --git a/scripts/test-acp-permissions.py b/scripts/test-acp-permissions.pynew file mode 100644index 00000000..3c645982--- /dev/null+++ b/scripts/test-acp-permissions.py@@ -0,0 +1,59 @@+#!/usr/bin/env python3+"""Offline real ACP permission decisions, persistence and cancellation."""+import json, os, queue, signal, subprocess, sys, tempfile, threading, time+from pathlib import Path+sys.path.insert(0,str(Path(__file__).resolve().parent/'eval'))+from mock_model import ScriptedModel++def run(binary,decision):+ command="python3 -c \"open('approved.txt','a').write('yes')\""+ script=[{'tool':'bash','arguments':{'command':command}}, {'tool':'bash','arguments':{'command':command}}, {'text':'Done.'}]+ model=ScriptedModel(script)+ with tempfile.TemporaryDirectory(prefix='acp-permissions-') as temp:+ env={k:v for k,v in os.environ.items() if not k.endswith('_API_KEY')}+ config=Path(temp)/'mcp.json';config.write_text('{"mcpServers":{}}')+ env.update(HOME=temp,AI_GATEWAY_API_KEY='local',GRAFF_MCP_CONFIG=str(config),GRAFF_NO_TELEMETRY='1',GRAFF_FLEET='off',GRAFF_NO_SMOLIFY='1',GRAFF_NO_CODEDB_GUARD='1')+ port = model.start(0)+ env['GRAFF_VERCEL_URL'] = f'http://127.0.0.1:{port}/v1/chat/completions'+ proc=subprocess.Popen([binary,'acp','--model','vercel','--old','--no-lean'] + (['--yolo'] if decision=='yolo' else []),cwd=temp,env=env,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.DEVNULL,text=True,start_new_session=True)+ messages=queue.Queue()+ def read():+ for line in proc.stdout:+ try:messages.put(json.loads(line))+ except ValueError:pass+ messages.put(None)+ threading.Thread(target=read,daemon=True).start()+ def send(obj):proc.stdin.write(json.dumps({'jsonrpc':'2.0',**obj})+'\n');proc.stdin.flush()+ def wait(id,respond=False):+ requests=[]; deadline=time.monotonic()+30+ while True:+ m=messages.get(timeout=max(.01,deadline-time.monotonic()));assert m is not None,'worker exited'+ if m.get('id')==id:return m,requests+ if m.get('method')=='session/request_permission':+ assert respond,m+ assert not (Path(temp)/'approved.txt').exists() or requests, 'tool executed before approval'+ requests.append(m)+ if decision=='cancel':send({'method':'session/cancel','params':{'sessionId':sid}});continue+ # Stale ID cannot grant the active request.+ send({'id':'graff-permission-0','result':{'outcome':{'outcome':'selected','optionId':'allow_always'}}})+ outcome={'outcome':'cancelled'} if decision=='dismiss' else {'outcome':'selected','optionId':decision}+ send({'id':m['id'],'result':{'outcome':outcome}})+ try:+ send({'id':1,'method':'initialize','params':{'protocolVersion':1}});wait(1)+ send({'id':2,'method':'session/new','params':{'cwd':temp,'mcpServers':[]}});result,_=wait(2);sid=result['result']['sessionId']+ send({'id':3,'method':'session/prompt','params':{'sessionId':sid,'prompt':[{'type':'text','text':'Run the scripted fixture.'}]}})+ result,requests=wait(3,True)+ assert bool(requests) == (decision != 'yolo'), 'unexpected permission count'+ content=(Path(temp)/'approved.txt').read_text() if (Path(temp)/'approved.txt').exists() else ''+ if decision=='yolo':assert not requests and content=='yesyes',(requests,content)+ elif decision=='allow_always':assert len(requests)==1 and content=='yesyes',(requests,content)+ elif decision=='allow_once':assert len(requests)==2 and content=='yesyes',(requests,content)+ else:assert content=='',content+ if decision=='cancel':assert result.get('result',{}).get('stopReason')=='cancelled',result+ print('PASS ACP permission',decision,'requests',len(requests),flush=True)+ finally:+ os.killpg(proc.pid,signal.SIGKILL);proc.wait(timeout=3);model.stop()++if __name__=='__main__':+ binary=str(Path(sys.argv[1]).resolve())+ for decision in ['allow_once','allow_always','reject_once','dismiss','cancel','yolo']:run(binary,decision)diff --git a/scripts/test-acp-session-load.py b/scripts/test-acp-session-load.pynew file mode 100644index 00000000..5953d2c4--- /dev/null+++ b/scripts/test-acp-session-load.py@@ -0,0 +1,194 @@+#!/usr/bin/env python3+"""Offline two-process ACP v1 load: replay, context, and stale shell handles."""+import json+import os+import re+import selectors+import signal+import subprocess+import sys+import tempfile+import time+from pathlib import Path++REPO = Path(__file__).resolve().parents[1]+sys.path.insert(0, str(REPO / "scripts/eval"))+from mock_model import ScriptedModel+++class Acp:+ def __init__(self, binary, cwd, home, port):+ env = {k: v for k, v in os.environ.items() if not k.endswith("_API_KEY") and not k.startswith(("GRAFF_", "HARNESS_"))}+ env.update(HOME=str(home), AI_GATEWAY_API_KEY="local", GRAFF_FLEET="off",+ GRAFF_VERCEL_URL=f"http://127.0.0.1:{port}/v1/chat/completions",+ GRAFF_NO_TELEMETRY="1", GRAFF_NO_SMOLIFY="1",+ GRAFF_BEHAVIOR_UPLOAD="off", NO_COLOR="1")+ self.err = open(cwd / f"acp-{time.time_ns()}.stderr", "w")+ self.proc = subprocess.Popen([str(binary), "acp", "--yolo", "--old", "--model", "vercel"],+ cwd=cwd, env=env, stdin=subprocess.PIPE, stdout=subprocess.PIPE,+ stderr=self.err, start_new_session=True)+ self.selector = selectors.DefaultSelector()+ self.selector.register(self.proc.stdout, selectors.EVENT_READ)+ self.pending = b""+ self.next_id = 0+ self.events = []++ def request(self, method, params=None, timeout=25):+ self.next_id += 1+ target = self.next_id+ self.proc.stdin.write((json.dumps({"jsonrpc": "2.0", "id": target, "method": method,+ "params": params or {}}) + "\n").encode())+ self.proc.stdin.flush()+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ if b"\n" not in self.pending:+ if not self.selector.select(.1):+ continue+ chunk = os.read(self.proc.stdout.fileno(), 65536)+ if not chunk:+ raise AssertionError(f"ACP exited during {method}")+ self.pending += chunk+ while b"\n" in self.pending:+ line, self.pending = self.pending.split(b"\n", 1)+ item = json.loads(line)+ self.events.append(item)+ if item.get("id") == target:+ return item+ raise AssertionError(f"ACP {method} timed out")++ def close(self):+ self.selector.close()+ if self.proc.poll() is None:+ self.proc.stdin.close()+ try:+ self.proc.wait(timeout=3)+ except subprocess.TimeoutExpired:+ os.killpg(self.proc.pid, signal.SIGTERM)+ try:+ self.proc.wait(timeout=3)+ except subprocess.TimeoutExpired:+ pass+ if self.proc.poll() is None:+ os.killpg(self.proc.pid, signal.SIGKILL)+ self.proc.wait(timeout=3)+ self.err.close()+++def tool_text(body):+ return [m.get("content", "") for m in body.get("messages", []) if m.get("role") == "tool"]+++class FollowingModel(ScriptedModel):+ def __init__(self, old_handle):+ super().__init__([])+ self.old_handle = old_handle+ self.new_handle = None+ self.stale_output = ""+ self.stale_kill = ""+ self.new_output = ""++ def next_reply(self, body):+ with self._lock:+ self.requests.append(body)+ n = len(self.requests)+ if n == 1:+ return {"tool": "shell", "arguments": {"action": "run", "command": "sleep 5", "run_in_background": True}}+ if n == 2:+ found = re.search(r"\[job (\d+) started:", tool_text(body)[-1])+ assert found, "new background job handle missing"+ self.new_handle = int(found.group(1))+ return {"tool": "bash_output", "arguments": {"id": self.old_handle, "wait_ms": 0}}+ if n == 3:+ self.stale_output = tool_text(body)[-1]+ return {"tool": "bash_kill", "arguments": {"id": self.old_handle}}+ if n == 4:+ self.stale_kill = tool_text(body)[-1]+ return {"tool": "bash_output", "arguments": {"id": self.new_handle, "wait_ms": 0}}+ if n == 5:+ self.new_output = tool_text(body)[-1]+ return {"text": "Loaded context remains available."}+ return {"text": "done"}+++def run(binary):+ with tempfile.TemporaryDirectory(prefix="graff-acp-load-") as temporary:+ cwd = Path(temporary)+ home = cwd / "home"+ home.mkdir()+ first_model = ScriptedModel([+ {"tool": "shell", "arguments": {"action": "run", "command": "sleep 5", "run_in_background": True}},+ {"text": "Original assistant answer."},+ ])+ first_port = first_model.start(0)+ a = Acp(binary, cwd, home, first_port)+ try:+ init = a.request("initialize", {"protocolVersion": 1})+ assert init["result"]["agentCapabilities"]["loadSession"] is True+ sid = a.request("session/new", {"cwd": str(cwd), "mcpServers": []})["result"]["sessionId"]+ assert "/" not in sid and "\\" not in sid+ turn = a.request("session/prompt", {"sessionId": sid, "prompt": [{"type": "text", "text": "Original human request."}]}, 35)+ assert turn["result"]["stopReason"] == "end_turn"+ old_result = tool_text(first_model.requests[1])[-1]+ old = int(re.search(r"\[job (\d+) started:", old_result).group(1))+ saved = cwd / ".graff" / "sessions" / f"{sid}.session.json"+ end = time.monotonic() + 5+ while not saved.exists() and time.monotonic() < end:+ time.sleep(.05)+ assert saved.exists(), "ACP session ID is not the durable save basename"+ finally:+ a.close()+ first_model.stop()++ # Simulate a compacted provider window: the transcript still retains+ # an older user turn that no longer appears in the model snapshot.+ transcript = cwd / ".graff" / "sessions" / f"{sid}.transcript.jsonl"+ assert transcript.exists()+ transcript.write_text(json.dumps({"role": "user", "content": "Older retained request."}) + "\n" + transcript.read_text())++ next_model = FollowingModel(old)+ second_port = next_model.start(0)+ b = Acp(binary, cwd, home, second_port)+ try:+ b.request("initialize", {"protocolVersion": 1})+ created = b.request("session/new", {"cwd": str(cwd), "mcpServers": []})["result"]+ fresh = created["sessionId"]+ assert fresh != sid+ bad = b.request("session/load", {"sessionId": "../escape", "cwd": str(cwd), "mcpServers": []})+ assert bad["error"]["code"] == -32602+ missing = b.request("session/load", {"sessionId": "missing", "cwd": str(cwd), "mcpServers": []})+ assert missing["error"]["code"] == -32602+ corrupt = cwd / ".graff" / "sessions" / "corrupt.session.json"+ corrupt.write_text('{"provider":42,"model":"mock","messages":[]}')+ invalid = b.request("session/load", {"sessionId": "corrupt", "cwd": str(cwd), "mcpServers": []})+ assert invalid["error"]["code"] == -32602+ wrong = b.request("session/load", {"sessionId": sid, "cwd": str(home), "mcpServers": []})+ assert wrong["error"]["code"] == -32602+ before = len(b.events)+ loaded = b.request("session/load", {"sessionId": sid, "cwd": str(cwd), "mcpServers": []})+ assert loaded.get("result") == {}, (created, loaded)+ replay = b.events[before:]+ updates = [event["params"]["update"] for event in replay if event.get("method") == "session/update"]+ assert any(u.get("sessionUpdate") == "user_message_chunk" and u["content"].get("text") == "Original human request." for u in updates)+ assert any(u.get("sessionUpdate") == "user_message_chunk" and u["content"].get("text") == "Older retained request." for u in updates)+ assert any(u.get("sessionUpdate") == "agent_message_chunk" and u["content"].get("text") == "Original assistant answer." for u in updates)+ assert any(u.get("sessionUpdate") == "tool_call" for u in updates)+ assert any(u.get("sessionUpdate") == "tool_call_update" and u.get("status") == "completed" for u in updates)+ stale_session = b.request("session/prompt", {"sessionId": fresh, "prompt": [{"type": "text", "text": "Wrong session."}]})+ assert stale_session["error"]["code"] == -32602+ continued = b.request("session/prompt", {"sessionId": sid, "prompt": [{"type": "text", "text": "Continue with original context."}]}, 35)+ assert continued["result"]["stopReason"] == "end_turn"+ assert next_model.new_handle != old+ assert "Original human request." in json.dumps(next_model.requests[0])+ assert "Original assistant answer." in json.dumps(next_model.requests[0])+ assert re.search(r"unknown|stale|no background job|interrupted", next_model.stale_output, re.I)+ assert re.search(r"unknown|stale|no background job|interrupted", next_model.stale_kill, re.I)+ assert str(next_model.new_handle) not in next_model.stale_output+ assert not re.search(r"unknown|stale|no background job|interrupted", next_model.new_output, re.I)+ finally:+ b.close()+ next_model.stop()+ print("ACP session/load replay and stale shell isolation: ok")+++if __name__ == "__main__":+ run(Path(sys.argv[1] if len(sys.argv) > 1 else REPO / "zig-out/bin/graff").resolve())diff --git a/src/acp.zig b/src/acp.zigindex 4249c096..54d69de1 100644--- a/src/acp.zig+++ b/src/acp.zig@@ -210,7 +210,11 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_engine.implementation_version = main_mod.harness_version;engine.cancel_flag.store(false, .release);engine.on_cancel = syncEscCancel;- var inbox: @import("acp_inbox.zig").Inbox = .{ .gpa = gpa, .io = io, .reader = in };+ var permission_bridge: @import("acp_permission.zig").Bridge = .{ .io = io, .out = out };+ const previous_permission = root.permission;+ root.permission = permission_bridge.handler();+ defer root.permission = previous_permission;+ var inbox: @import("acp_inbox.zig").Inbox = .{ .gpa = gpa, .io = io, .reader = in, .permission = &permission_bridge };try inbox.start();defer inbox.deinit();acp_inbox_nudge = &inbox;@@ -235,6 +239,7 @@ pub fn runAcpCommand(gpa: Allocator, io: Io, environ_map: anytype, root: *agent_.extra = liveModels,.cwd = if (std.fs.path.isAbsolute(main_mod.g_cwd_display)) main_mod.g_cwd_display else "",};+ @import("acp_session_load.zig").configure(&d, &live);while (true) {const event = (inbox.wait(arena) catch break) orelse break;switch (event) {diff --git a/src/acp_engine.zig b/src/acp_engine.zigindex 367962aa..4c61c53b 100644--- a/src/acp_engine.zig+++ b/src/acp_engine.zig@@ -32,6 +32,7 @@ pub const TurnFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const upub const SlashFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u8) anyerror!?[]const u8;pub const AfterUserFn = *const fn (ctx: *anyopaque, arena: Allocator, text: []const u8) void;pub const BindSessionFn = *const fn (ctx: *anyopaque, session_id: []const u8) void;+pub const LoadSessionFn = *const fn (ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Request) anyerror!void;/// Optional per-turn context meter: used and window tokens for the/// `gui_context_meter` update available to clients./// Null when the embed has no live agent (pure in-process loop, tests).@@ -50,6 +51,9 @@ pub const Dispatch = struct {slash: ?SlashFn = null,after_user: ?AfterUserFn = null,bind_session: ?BindSessionFn = null,+ load_session: ?LoadSessionFn = null,+ /// Live CLI saves under this stable name; embeds retain generated IDs.+ durable_session_id: ?[]const u8 = null,meter: ?MeterFn = null,extra: ?ExtraFn = null,error_message: ?*const fn (ctx: *anyopaque, err: anyerror) []const u8 = null,@@ -152,11 +156,11 @@ test "slash commands refresh occupancy before their terminal response" {try std.testing.expect(meter_pos < end_pos);}-fn respondInitialize(w: *Io.Writer, req: proto.Request) !void {+fn respondInitialize(w: *Io.Writer, req: proto.Request, can_load: bool) !void {return respond(w, req, .{.protocolVersion = negotiateVersion(req.params),.agentCapabilities = .{- .loadSession = false,+ .loadSession = can_load,.promptCapabilities = proto.PromptCapabilities{},},.agentInfo = proto.AgentImplementation{ .version = implementation_version },@@ -169,18 +173,18 @@ fn respondInitialize(w: *Io.Writer, req: proto.Request) !void {/// engine response; every request that needs a live Agent is auth-gated.pub fn handlePreAuthLine(arena: Allocator, w: *Io.Writer, line: []const u8) !void {const req = parseRequest(arena, line) orelse return;- if (std.mem.eql(u8, req.method, "initialize")) return respondInitialize(w, req);+ if (std.mem.eql(u8, req.method, "initialize")) return respondInitialize(w, req, false);return respondError(w, req, err_auth_required, acp_auth.required_message);}pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const u8) !void {const req = parseRequest(arena, line) orelse return;- if (std.mem.eql(u8, req.method, "initialize")) return respondInitialize(w, req);+ if (std.mem.eql(u8, req.method, "initialize")) return respondInitialize(w, req, d.load_session != null);if (std.mem.eql(u8, req.method, "authenticate"))return respondError(w, req, err_method_not_found, "terminal auth is out of band: re-spawn graff login");if (std.mem.eql(u8, req.method, "session/new")) {d.created += 1;- d.session_id = try std.fmt.allocPrint(arena, "acp-{x}-{d}", .{ d.seed, d.created });+ d.session_id = d.durable_session_id orelse try std.fmt.allocPrint(arena, "acp-{x}-{d}", .{ d.seed, d.created });if (d.cwd.len > 0)try respond(w, req, .{ .sessionId = d.session_id.?, .cwd = d.cwd })else@@ -188,12 +192,22 @@ pub fn handleLine(d: *Dispatch, arena: Allocator, w: *Io.Writer, line: []const utry proto.writeAvailableCommands(w, d.session_id.?, proto.slashCommands());return;}+ if (d.load_session != null and (std.mem.eql(u8, req.method, "session/prompt") or std.mem.eql(u8, req.method, "session/cancel"))) {+ const params = req.params orelse return respondError(w, req, -32602, "Invalid session ID");+ if (params != .object) return respondError(w, req, -32602, "Invalid session ID");+ const sid = util.strFieldObj(params.object, "sessionId") orelse return respondError(w, req, -32602, "Invalid session ID");+ if (d.session_id == null or !std.mem.eql(u8, sid, d.session_id.?))+ return respondError(w, req, -32602, "Unknown session ID");+ }if (std.mem.eql(u8, req.method, "session/cancel")) {cancel_flag.store(true, .release);if (on_cancel) |hook| hook();if (req.id != null) return respond(w, req, .{});return;}+ if (std.mem.eql(u8, req.method, "session/load")) {+ if (d.load_session) |load| return load(d.ctx, arena, w, req);+ }if (std.mem.eql(u8, req.method, "session/prompt")) return promptTurn(d, arena, w, req);if (d.extra) |extra| if (try extra(d.ctx, arena, w, req)) return;if (req.id == null) return;diff --git a/src/acp_inbox.zig b/src/acp_inbox.zigindex cb8bcbb6..c6453230 100644--- a/src/acp_inbox.zig+++ b/src/acp_inbox.zig@@ -7,6 +7,7 @@ const cancel_source = @import("cancel_source.zig");const acp_ask = @import("acp_ask.zig");pub const Inbox = struct {+ permission: ?*@import("acp_permission.zig").Bridge = null,gpa: std.mem.Allocator,io: Io,reader: *Io.Reader,@@ -101,6 +102,10 @@ pub const Inbox = struct {fn accept(self: *Inbox, line: []const u8) !void {var arena = std.heap.ArenaAllocator.init(self.gpa);defer arena.deinit();+ if (self.permission) |bridge| {+ const value = std.json.parseFromSliceLeaky(std.json.Value, arena.allocator(), line, .{}) catch .null;+ if (bridge.accept(value)) return;+ }const req = proto.parseRequest(arena.allocator(), line);self.mutex.lockUncancelable(self.io);defer self.mutex.unlock(self.io);@@ -117,6 +122,7 @@ pub const Inbox = struct {self.cancelled = true;if (self.active) cancel_source.cancel(.acp_cancel);acp_ask.cancelIfWaiting();+ if (self.permission) |bridge| bridge.cancel();}}return;@@ -150,6 +156,7 @@ pub const Inbox = struct {}self.mutex.lockUncancelable(self.io);self.eof = true;+ if (self.permission) |bridge| bridge.cancel();self.ready.broadcast(self.io);self.mutex.unlock(self.io);}diff --git a/src/acp_live_turn.zig b/src/acp_live_turn.zigindex 9010791b..bed55165 100644--- a/src/acp_live_turn.zig+++ b/src/acp_live_turn.zig@@ -25,6 +25,7 @@ pub const LiveTurn = struct {prev_turn_id: u64 = 0,prev_prompt_fp: [16]u8 = @splat(0),inbox: ?*@import("acp_inbox.zig").Inbox = null,+ dispatch: ?*@import("acp_engine.zig").Dispatch = null,pub fn errorMessage(ctx: *anyopaque, err: anyerror) []const u8 {const self: *LiveTurn = @ptrCast(@alignCast(ctx));@@ -38,8 +39,14 @@ pub const LiveTurn = struct {// upstream (client dispatch / bootstrap / transport), not in the turn.if (self.root.tracer) |tr| tr.note("acp_prompt", self.session_id);agent_mod.Agent.prepareRootTurn(); // #753: a prior stream cancel must not steal the continuation- if (self.inbox) |inbox| inbox.begin();- defer if (self.inbox) |inbox| inbox.end();+ if (self.inbox) |inbox| {+ if (inbox.permission) |bridge| bridge.begin(self.session_id);+ inbox.begin();+ }+ defer if (self.inbox) |inbox| {+ if (inbox.permission) |bridge| bridge.cancel();+ inbox.end();+ };const review_prompt = review.promptFromLine(text);const parent_override = self.root.sys_override;const parent_review_mode = self.root.review_mode;diff --git a/src/acp_permission.zig b/src/acp_permission.zignew file mode 100644index 00000000..9edd099a--- /dev/null+++ b/src/acp_permission.zig@@ -0,0 +1,153 @@+//! ACP server-initiated permission RPC, scoped to one live process and turn.+const std = @import("std");+const Io = std.Io;+const permission = @import("engine_permission.zig");+const util = @import("util.zig");+pub const Bridge = struct {+ io: Io,+ out: *Io.Writer,+ session: []const u8 = "",+ mutex: Io.Mutex = .init,+ ready: Io.Condition = .init,+ sequence: u64 = 0,+ pending: ?u64 = null,+ decision: ?permission.Decision = null,+ allow_always: bool = false,+ closed: bool = false,++ pub fn handler(self: *Bridge) permission.Handler {+ return .{ .ctx = self, .request = ask };+ }+ pub fn cancel(self: *Bridge) void {+ self.mutex.lockUncancelable(self.io);+ defer self.mutex.unlock(self.io);+ self.closed = true;+ self.decision = .deny;+ self.ready.broadcast(self.io);+ }+ pub fn begin(self: *Bridge, session: []const u8) void {+ self.mutex.lockUncancelable(self.io);+ defer self.mutex.unlock(self.io);+ self.session = session;+ self.closed = false;+ }+ fn ask(ctx: *anyopaque, io: Io, req: permission.Request) permission.Decision {+ const self: *Bridge = @ptrCast(@alignCast(ctx));+ self.mutex.lockUncancelable(io);+ defer self.mutex.unlock(io);+ if (self.closed or self.pending != null) return .deny;+ self.sequence += 1;+ self.pending = self.sequence;+ self.decision = null;+ self.allow_always = req.allow_always;+ defer {+ self.pending = null;+ self.decision = null;+ }+ var idbuf: [64]u8 = undefined;+ const id = std.fmt.bufPrint(&idbuf, "graff-permission-{d}", .{self.sequence}) catch return .deny;+ const Option = struct { optionId: []const u8, name: []const u8, kind: []const u8 };+ const options = [_]Option{+ .{ .optionId = "allow_once", .name = "Allow once", .kind = "allow_once" },+ .{ .optionId = "reject_once", .name = "Reject", .kind = "reject_once" },+ .{ .optionId = "allow_always", .name = req.always_label, .kind = "allow_always" },+ };+ {+ // Same order as tool dispatch: bridge state -> shared output.+ // Inbox responses/cancel never acquire the output lock. Release it+ // before waiting so background events remain visible during consent.+ const main = @import("main.zig");+ main.g_gui_mu.lockUncancelable(io);+ defer main.g_gui_mu.unlock(io);+ std.json.Stringify.value(.{ .jsonrpc = "2.0", .id = id, .method = "session/request_permission", .params = .{+ .sessionId = self.session,+ .toolCall = .{ .toolCallId = req.call_id, .title = req.description, .status = "pending" },+ .options = options[0..if (req.allow_always) @as(usize, 3) else 2],+ } }, .{}, self.out) catch return .deny;+ self.out.writeByte('\n') catch return .deny;+ self.out.flush() catch return .deny;+ }+ while (self.decision == null and !self.closed) self.ready.waitUncancelable(io, &self.mutex);+ return self.decision orelse .deny;+ }+ /// Responses have no method. Only the currently pending server ID can resolve.+ pub fn accept(self: *Bridge, value: std.json.Value) bool {+ if (value != .object or value.object.contains("method")) return false;+ const id = util.strFieldObj(value.object, "id") orelse return false;+ if (!std.mem.startsWith(u8, id, "graff-permission-")) return false;+ self.mutex.lockUncancelable(self.io);+ defer self.mutex.unlock(self.io);+ const seq = std.fmt.parseInt(u64, id[17..], 10) catch return true;+ if (self.closed or self.pending != seq or self.decision != null) return true;+ const result = value.object.get("result") orelse {+ self.decision = .deny;+ self.ready.broadcast(self.io);+ return true;+ };+ const outcome = if (result == .object) result.object.get("outcome") orelse .null else .null;+ var decision: permission.Decision = .deny;+ if (outcome == .object and std.mem.eql(u8, util.strFieldObj(outcome.object, "outcome") orelse "", "selected")) {+ const option = util.strFieldObj(outcome.object, "optionId") orelse "";+ if (std.mem.eql(u8, option, "allow_once")) decision = .allow_once;+ if (self.allow_always and std.mem.eql(u8, option, "allow_always")) decision = .allow_always;+ }+ self.decision = decision;+ self.ready.broadcast(self.io);+ return true;+ }+};++test "ACP permission replies reject stale duplicate and unoffered choices" {+ var out: Io.Writer.Allocating = .init(std.testing.allocator);+ defer out.deinit();+ var bridge: Bridge = .{ .io = std.testing.io, .out = &out.writer, .pending = 2 };+ for ([_][]const u8{+ "{\"id\":\"graff-permission-1\",\"result\":{\"outcome\":{\"outcome\":\"selected\",\"optionId\":\"allow_once\"}}}",+ "{\"id\":\"graff-permission-2\",\"result\":{\"outcome\":{\"outcome\":\"selected\",\"optionId\":\"allow_always\"}}}",+ }, 0..) |text, index| {+ var parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, text, .{});+ defer parsed.deinit();+ try std.testing.expect(bridge.accept(parsed.value));+ if (index == 0) try std.testing.expect(bridge.decision == null) else try std.testing.expectEqual(permission.Decision.deny, bridge.decision.?);+ }+ bridge.cancel();+ try std.testing.expect(bridge.closed);+}++test "ACP permission waits for shared output lock before any JSON bytes" {+ const Probe = struct {+ writer: Io.Writer = .{ .vtable = &.{ .drain = drain }, .buffer = &.{}, .end = 0 },+ touched: std.atomic.Value(bool) = .init(false),+ started: std.atomic.Value(bool) = .init(false),+ fn drain(w: *Io.Writer, _: []const []const u8, _: usize) Io.Writer.Error!usize {+ const self: *@This() = @alignCast(@fieldParentPtr("writer", w));+ self.touched.store(true, .release);+ return error.WriteFailed;+ }+ fn run(self: *@This(), bridge: *Bridge) void {+ self.started.store(true, .release);+ _ = bridge.handler().ask(std.testing.io, .{ .call_id = "call", .tool = "bash", .description = "request" });+ }+ };+ const io = std.testing.io;+ var probe: Probe = .{};+ var bridge: Bridge = .{ .io = io, .out = &probe.writer };+ const main = @import("main.zig");+ main.g_gui_mu.lockUncancelable(io);+ var locked = true;+ defer if (locked) main.g_gui_mu.unlock(io);+ var worker = try io.concurrent(Probe.run, .{ &probe, &bridge });+ while (!probe.started.load(.acquire)) try io.sleep(.fromMilliseconds(1), .awake);+ try io.sleep(.fromMilliseconds(25), .awake);+ const wrote_while_locked = probe.touched.load(.acquire);+ main.g_gui_mu.unlock(io);+ locked = false;+ worker.await(io);+ try std.testing.expect(!wrote_while_locked);+ try std.testing.expect(probe.touched.load(.acquire));+ // A failed frame also releases both locks and retires its pending request.+ main.g_gui_mu.lockUncancelable(io);+ main.g_gui_mu.unlock(io);+ bridge.cancel();+ try std.testing.expect(bridge.pending == null);+}diff --git a/src/acp_replay.zig b/src/acp_replay.zignew file mode 100644index 00000000..63babd82--- /dev/null+++ b/src/acp_replay.zig@@ -0,0 +1,197 @@+//! Project saved provider history onto ACP v1's user-visible replay stream.+//! This never invokes a tool: orphaned calls become failed historical rows.+const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const Value = std.json.Value;+const proto = @import("acp_protocol.zig");+const util = @import("util.zig");+const session_peer = @import("session_peer.zig");++const Call = struct { id: []const u8, finished: bool = false };++fn field(obj: std.json.ObjectMap, key: []const u8) ?[]const u8 {+ return util.strFieldObj(obj, key);+}++fn visibleText(arena: Allocator, value: Value) ![]const u8 {+ if (value == .string) return value.string;+ if (value == .object) {+ const o = value.object;+ if (field(o, "text")) |text| return text;+ if (o.get("content")) |content| return visibleText(arena, content);+ return "";+ }+ if (value != .array) return "";+ var result: std.ArrayList(u8) = .empty;+ for (value.array.items) |part| {+ const text = try visibleText(arena, part);+ if (text.len == 0) continue;+ if (result.items.len > 0) try result.append(arena, '\n');+ try result.appendSlice(arena, text);+ }+ return result.items;+}++fn message(w: *Io.Writer, sid: []const u8, role: []const u8, text: []const u8) !void {+ if (text.len == 0) return;+ try proto.writeNotification(w, "session/update", .{+ .sessionId = sid,+ .update = .{+ .sessionUpdate = if (std.mem.eql(u8, role, "user")) "user_message_chunk" else "agent_message_chunk",+ .content = .{ .type = "text", .text = text },+ },+ });+}++fn beginCall(arena: Allocator, w: *Io.Writer, sid: []const u8, calls: *std.ArrayList(Call), id: []const u8, name: []const u8) !void {+ for (calls.items) |c| if (std.mem.eql(u8, c.id, id)) return;+ try calls.append(arena, .{ .id = id });+ try proto.writeNotification(w, "session/update", .{+ .sessionId = sid,+ .update = .{+ .sessionUpdate = "tool_call",+ .toolCallId = id,+ .title = name,+ .kind = "other",+ .status = "in_progress",+ },+ });+}++fn finishCall(arena: Allocator, w: *Io.Writer, sid: []const u8, calls: *std.ArrayList(Call), id: []const u8, output: Value, failed: bool) !void {+ try beginCall(arena, w, sid, calls, id, "Tool result");+ for (calls.items) |*c| if (std.mem.eql(u8, c.id, id)) {+ c.finished = true;+ break;+ };+ const text = try visibleText(arena, output);+ if (text.len > 0) {+ try proto.writeNotification(w, "session/update", .{+ .sessionId = sid,+ .update = .{+ .sessionUpdate = "tool_call_update",+ .toolCallId = id,+ .status = if (failed) "failed" else "completed",+ .content = .{.{ .type = "content", .content = .{ .type = "text", .text = text } }},+ },+ });+ } else {+ try proto.writeNotification(w, "session/update", .{+ .sessionId = sid,+ .update = .{ .sessionUpdate = "tool_call_update", .toolCallId = id, .status = if (failed) "failed" else "completed" },+ });+ }+}++fn isError(obj: std.json.ObjectMap) bool {+ const v = obj.get("is_error") orelse obj.get("isError") orelse return false;+ return v == .bool and v.bool;+}++fn resultFailed(obj: std.json.ObjectMap, output: Value) bool {+ if (isError(obj)) return true;+ // OpenAI Chat has no error bit; the harness persists failed tool results+ // with this exact prefix. Responses output has no lossless status field.+ return output == .string and std.mem.startsWith(u8, output.string, "[error] ");+}++fn replayPart(arena: Allocator, w: *Io.Writer, sid: []const u8, calls: *std.ArrayList(Call), role: []const u8, part: Value) !void {+ if (part != .object) {+ if (part == .string) try message(w, sid, role, part.string);+ return;+ }+ const obj = part.object;+ const typ = field(obj, "type") orelse "";+ if (std.mem.eql(u8, typ, "tool_use") or std.mem.eql(u8, typ, "function_call")) {+ const id = field(obj, "id") orelse field(obj, "call_id") orelse return;+ try beginCall(arena, w, sid, calls, id, field(obj, "name") orelse "Tool call");+ return;+ }+ if (std.mem.eql(u8, typ, "tool_result") or std.mem.eql(u8, typ, "function_call_output")) {+ const id = field(obj, "tool_use_id") orelse field(obj, "call_id") orelse return;+ const output = obj.get("content") orelse obj.get("output") orelse .null;+ try finishCall(arena, w, sid, calls, id, output, resultFailed(obj, output));+ return;+ }+ if (std.mem.eql(u8, typ, "text") or std.mem.eql(u8, typ, "input_text") or std.mem.eql(u8, typ, "output_text")) {+ if (field(obj, "text")) |text| try message(w, sid, role, text);+ }+}++/// Replay the persisted conversation in order, preserving human/assistant+/// roles and completed/failed tool evidence across Anthropic, OpenAI Chat,+/// and Responses histories. Opaque reasoning and provider metadata stay out.+pub fn replay(arena: Allocator, w: *Io.Writer, sid: []const u8, messages: []const Value) !void {+ var calls: std.ArrayList(Call) = .empty;+ for (messages) |item| {+ if (item != .object) continue;+ const obj = item.object;+ const typ = field(obj, "type") orelse "";+ if (std.mem.eql(u8, typ, "function_call") or std.mem.eql(u8, typ, "function_call_output")) {+ try replayPart(arena, w, sid, &calls, "assistant", item);+ continue;+ }+ const role = field(obj, "role") orelse continue;+ if (std.mem.eql(u8, role, "user") and !session_peer.isHumanUserTurn(item)) continue;+ if (std.mem.eql(u8, role, "tool")) {+ const id = field(obj, "tool_call_id") orelse continue;+ const output = obj.get("content") orelse .null;+ try finishCall(arena, w, sid, &calls, id, output, resultFailed(obj, output));+ continue;+ }+ if (!std.mem.eql(u8, role, "user") and !std.mem.eql(u8, role, "assistant")) continue;+ if (obj.get("content")) |content| {+ if (content == .array) {+ for (content.array.items) |part| try replayPart(arena, w, sid, &calls, role, part);+ } else try replayPart(arena, w, sid, &calls, role, content);+ }+ if (obj.get("tool_calls")) |tool_calls| if (tool_calls == .array) {+ for (tool_calls.array.items) |call| {+ if (call != .object) continue;+ const id = field(call.object, "id") orelse continue;+ const function = call.object.get("function") orelse .null;+ const name = if (function == .object) field(function.object, "name") orelse "Tool call" else "Tool call";+ try beginCall(arena, w, sid, &calls, id, name);+ }+ };+ }+ // A saved tool invocation without a result is historical unfinished work.+ // It must never appear newly running or as a successful recovered job.+ for (calls.items) |call| if (!call.finished) {+ try proto.writeNotification(w, "session/update", .{+ .sessionId = sid,+ .update = .{+ .sessionUpdate = "tool_call_update",+ .toolCallId = call.id,+ .status = "failed",+ .content = .{.{ .type = "content", .content = .{ .type = "text", .text = "Interrupted before a saved result was available." } }},+ },+ });+ };+}++test "ACP load replay keeps roles, tool results, failures, and orphan state" {+ var state = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer state.deinit();+ const arena = state.allocator();+ const saved = try std.json.parseFromSliceLeaky(Value, arena,+ \\[{"role":"user","content":"Please check"},+ \\ {"role":"assistant","content":[{"type":"text","text":"Running"},{"type":"tool_use","id":"ok","name":"shell"}]},+ \\ {"role":"user","content":[{"type":"tool_result","tool_use_id":"ok","content":"done"}]},+ \\ {"role":"assistant","tool_calls":[{"id":"bad","function":{"name":"edit_file"}}]},+ \\ {"role":"tool","tool_call_id":"bad","content":"[error] permission denied"},+ \\ {"type":"function_call","call_id":"orphan","name":"shell"},+ \\ {"role":"assistant","content":"Report"}]+ , .{});+ var out: Io.Writer.Allocating = .init(arena);+ try replay(arena, &out.writer, "saved", saved.array.items);+ const bytes = out.writer.buffered();+ try std.testing.expect(std.mem.indexOf(u8, bytes, "\"sessionUpdate\":\"user_message_chunk\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "\"text\":\"Please check\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "\"text\":\"Report\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "\"toolCallId\":\"ok\",\"status\":\"completed\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "\"toolCallId\":\"bad\",\"status\":\"failed\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "\"toolCallId\":\"orphan\",\"status\":\"failed\"") != null);+ try std.testing.expect(std.mem.indexOf(u8, bytes, "\"toolCallId\":\"orphan\",\"status\":\"completed\"") == null);+}diff --git a/src/acp_session_load.zig b/src/acp_session_load.zignew file mode 100644index 00000000..91211472--- /dev/null+++ b/src/acp_session_load.zig@@ -0,0 +1,95 @@+//! ACP v1 session/load for the live CLI Agent. Only a saved session in the+//! selected workspace can be loaded; session IDs are plain save basenames.+const std = @import("std");+const Io = std.Io;+const Allocator = std.mem.Allocator;+const proto = @import("acp_protocol.zig");+const engine = @import("acp_engine.zig");+const session = @import("session.zig");+const session_index = @import("session_index.zig");+const replay = @import("acp_replay.zig");+const transcript = @import("session_transcript.zig");+const LiveTurn = @import("acp_live_turn.zig").LiveTurn;+const util = @import("util.zig");++const invalid_params: i32 = -32602;++pub fn configure(d: *engine.Dispatch, live: *LiveTurn) void {+ d.load_session = load;+ d.durable_session_id = if (session.validSessionName(live.root.session_name)) live.root.session_name else null;+ live.dispatch = d;+}++fn reject(w: *Io.Writer, req: proto.Request, message: []const u8) !void {+ if (req.id != null) try proto.writeError(w, req.id, invalid_params, message);+}++fn replayHistory(arena: Allocator, root: *@import("agent.zig").Agent, w: *Io.Writer, sid: []const u8) !void {+ // The provider context can be compacted. The append-only transcript keeps+ // earlier visible turns; a legacy save without one uses current history.+ var retained: std.ArrayList(std.json.Value) = .empty;+ for ([_][]const u8{+ try transcript.rotatedPath(arena, sid),+ try transcript.transcriptPath(arena, sid),+ }) |path| {+ const bytes = Io.Dir.cwd().readFileAlloc(root.io, path, arena, .limited(transcript.cap_bytes + 1024)) catch continue;+ var lines = std.mem.splitScalar(u8, bytes, '\n');+ while (lines.next()) |line| {+ if (line.len == 0) continue;+ const value = std.json.parseFromSliceLeaky(std.json.Value, arena, line, .{ .allocate = .alloc_always }) catch continue;+ try retained.append(arena, value);+ }+ }+ try replay.replay(arena, w, sid, if (retained.items.len > 0) retained.items else root.messages.items);+}++pub fn load(ctx: *anyopaque, arena: Allocator, w: *Io.Writer, req: proto.Request) anyerror!void {+ const live: *LiveTurn = @ptrCast(@alignCast(ctx));+ const d = live.dispatch orelse return reject(w, req, "Session loading is unavailable");+ const params = req.params orelse return reject(w, req, "Invalid session/load parameters");+ if (params != .object) return reject(w, req, "Invalid session/load parameters");+ const sid = util.strFieldObj(params.object, "sessionId") orelse return reject(w, req, "Invalid session ID");+ const cwd = util.strFieldObj(params.object, "cwd") orelse return reject(w, req, "Invalid session workspace");+ if (!session.validSessionName(sid)) return reject(w, req, "Invalid session ID");+ if (!std.fs.path.isAbsolute(cwd))+ return reject(w, req, "Session workspace does not match the selected workspace");+ const canonical_cwd = Io.Dir.cwd().realPathFileAlloc(live.root.io, cwd, arena) catch cwd;+ const canonical_active = Io.Dir.cwd().realPathFileAlloc(live.root.io, d.cwd, arena) catch d.cwd;+ if (!session_index.sameWorkspace(canonical_cwd, canonical_active))+ return reject(w, req, "Session workspace does not match the selected workspace");+ // No discovery fallback to the user's home or a sibling checkout. A save+ // with this basename in another workspace is a different conversation.+ const path = try session.sessionPath(arena, sid);+ const stat = Io.Dir.cwd().statFile(live.root.io, path, .{}) catch+ return reject(w, req, "Unknown session ID in the selected workspace");+ if (stat.kind != .file) return reject(w, req, "Unknown session ID in the selected workspace");+ const bytes = Io.Dir.cwd().readFileAlloc(live.root.io, path, arena, .limited(8 * 1024 * 1024)) catch+ return reject(w, req, "Saved session could not be loaded");+ const parsed = std.json.parseFromSliceLeaky(std.json.Value, arena, bytes, .{ .allocate = .alloc_always }) catch+ return reject(w, req, "Saved session could not be loaded");+ if (parsed != .object) return reject(w, req, "Saved session could not be loaded");+ const provider = parsed.object.get("provider") orelse return reject(w, req, "Saved session could not be loaded");+ const model = parsed.object.get("model") orelse return reject(w, req, "Saved session could not be loaded");+ const messages = parsed.object.get("messages") orelse return reject(w, req, "Saved session could not be loaded");+ if (provider != .string or model != .string or messages != .array)+ return reject(w, req, "Saved session could not be loaded");+ if (util.strFieldObj(parsed.object, "workspace")) |saved_workspace| {+ const canonical_saved = Io.Dir.cwd().realPathFileAlloc(live.root.io, saved_workspace, arena) catch saved_workspace;+ if (!session_index.sameWorkspace(canonical_saved, canonical_active))+ return reject(w, req, "Saved session belongs to another workspace");+ }+ // Flush the outgoing conversation before replacing provider-native state.+ session.saveSession(live.root, arena, live.root.session_name) catch |err| {+ return proto.writeError(w, req.id, engine.err_internal, @errorName(err));+ };+ session.loadSession(live.root, live.keys, arena, sid) catch |err| {+ return proto.writeError(w, req.id, invalid_params, if (err == error.FileNotFound) "Unknown session ID in the selected workspace" else "Saved session could not be loaded");+ };+ live.root.session_name = try arena.dupe(u8, sid);+ live.session_id = live.root.session_name;+ d.session_id = live.session_id;+ d.durable_session_id = live.session_id;+ try replayHistory(arena, live.root, w, live.session_id);+ try proto.writeResult(w, req.id, struct {}{});+ try proto.writeAvailableCommands(w, live.session_id, proto.slashCommands());+}diff --git a/src/agent_tool_gate.zig b/src/agent_tool_gate.zigindex 3ec047d5..86ea21d9 100644--- a/src/agent_tool_gate.zig+++ b/src/agent_tool_gate.zig@@ -305,7 +305,14 @@ pub fn gateTool(self: *Agent, call: ToolCall) !?ExecResult {} else return null;if (self.permission) |handler| {- if (handler.ask(self.io, .{ .call_id = call.id, .tool = call.name, .description = prompt_line }) == .allow_once) return null;+ switch (handler.ask(self.io, .{ .call_id = call.id, .tool = call.name, .description = prompt_line, .allow_always = true, .always_label = try std.fmt.allocPrint(self.arena, "Always allow {s}", .{key}) })) {+ .allow_once => return null,+ .allow_always => {+ try approvals.approve(self.io, self.gpa, key);+ return null;+ },+ .deny => {},+ }return .{ .text = try self.arena.dupe(u8, "user declined this tool call; do not retry it or a reworded equivalent. Continue with approved work or report the blocker."), .is_error = true };}diff --git a/src/engine_permission.zig b/src/engine_permission.zigindex 86f83c51..5bce8a62 100644--- a/src/engine_permission.zig+++ b/src/engine_permission.zig@@ -1,7 +1,7 @@//! Frontend-owned permission input; the engine owns which calls need consent.const std = @import("std");-pub const Decision = enum { allow_once, deny };-pub const Request = struct { call_id: []const u8, tool: []const u8, description: []const u8 };+pub const Decision = enum { allow_once, allow_always, deny };+pub const Request = struct { call_id: []const u8, tool: []const u8, description: []const u8, allow_always: bool = false, always_label: []const u8 = "Always allow this permission" };pub const Handler = struct {ctx: *anyopaque,request: *const fn (*anyopaque, std.Io, Request) Decision,diff --git a/src/main.zig b/src/main.zigindex 88fa96d7..44d4f8a3 100644--- a/src/main.zig+++ b/src/main.zig@@ -558,7 +558,7 @@ const agentJobsReap = subagent.agentJobsReap; // #276 P0-3: background subagentsconst workflow = @import("workflow_test.zig"); // the engine's tests live here (workflow.zig hit the 600-line cap)const exec = @import("exec.zig");test { // ── Unit tests (`zig build test`): pull in tests from imported modules (mcp.zig)- _ = .{ @import("mcp_apps.zig"), @import("html_view.zig"), @import("providers_confirmation_tests.zig"), @import("repl_model_confirmation_tests.zig"), @import("repl_model_pick_tests.zig"), @import("engine_sink_citation_tests.zig"), @import("cite_markup_stream_tests.zig"), @import("oneshot_citation_tests.zig"), @import("tui_acp.zig") };+ _ = .{ @import("mcp_apps.zig"), @import("html_view.zig"), @import("providers_confirmation_tests.zig"), @import("repl_model_confirmation_tests.zig"), @import("repl_model_pick_tests.zig"), @import("engine_sink_citation_tests.zig"), @import("cite_markup_stream_tests.zig"), @import("oneshot_citation_tests.zig"), @import("tui_acp.zig"), @import("acp_permission.zig") };_ = .{ @import("mcp_server_tests.zig"), @import("main_test.zig"), @import("artifact_claim_command.zig"), @import("cli_path_hint.zig"), @import("run_budget.zig"), @import("pr_review_input.zig"), @import("pr_claim_review.zig"), @import("tui_paste_transfer.zig") };_ = .{ @import("session_catalog.zig"), @import("session_prompt.zig"), @import("session_discovery.zig") };_ = .{ @import("prompt_astra.zig"), @import("prompt_guidance.zig") }; // per-model guidance (Astra, GPT-5.6)@@ -593,6 +593,7 @@ test { // ── Unit tests (`zig build test`): pull in tests from imported modu_ = @import("acp_agents.zig");_ = .{ @import("subagent_activity.zig"), @import("subagent_interactive.zig"), @import("subagent_recovery.zig"), @import("subagent_retained.zig"), @import("subagent_run_tests.zig") };_ = @import("acp_agent_activity.zig");+ _ = @import("acp_replay.zig");_ = @import("read_image.zig");_ = .{ @import("pr_local_checks.zig"), @import("mcp_names.zig"), @import("workspace_history.zig"), @import("file_worktree.zig"), @import("mcp_turn_context.zig"), @import("review_deadline.zig"), @import("issue_cmd.zig"), @import("shell_tool.zig"), @import("acp_ask.zig"), @import("side_steer.zig"), @import("task_workspace_tests.zig"), @import("workspace_prepare_tests.zig"), @import("worktree_reap.zig") };}