graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Wait for worker retirement before replacing GUI sessions
justrachc29b2ad06cad
diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.ymlindex 631a7ad3..69b54a09 100644--- a/.github/workflows/desktop.yml+++ b/.github/workflows/desktop.yml@@ -2,10 +2,10 @@ name: desktopon:workflow_dispatch:pull_request:- paths: ['apps/native/**', 'src/**', 'scripts/eval/frontend_model.py', 'scripts/eval/mock_model.py', 'scripts/eval/test_mock_model.py', 'scripts/*zig-ci.py', '.github/actions/setup-codegraff-zig/**', '.github/workflows/desktop.yml']+ paths: ['apps/native/**', 'src/**', 'scripts/test-server-retention.py', 'scripts/eval/frontend_model.py', 'scripts/eval/mock_model.py', 'scripts/eval/test_mock_model.py', 'scripts/*zig-ci.py', '.github/actions/setup-codegraff-zig/**', '.github/workflows/desktop.yml']push:branches: [main, 'release/**']- paths: ['apps/native/**', 'src/**', 'scripts/eval/frontend_model.py', 'scripts/eval/mock_model.py', 'scripts/eval/test_mock_model.py', 'scripts/*zig-ci.py', '.github/actions/setup-codegraff-zig/**', '.github/workflows/desktop.yml']+ paths: ['apps/native/**', 'src/**', 'scripts/test-server-retention.py', 'scripts/eval/frontend_model.py', 'scripts/eval/mock_model.py', 'scripts/eval/test_mock_model.py', 'scripts/*zig-ci.py', '.github/actions/setup-codegraff-zig/**', '.github/workflows/desktop.yml']permissions:contents: readjobs:@@ -89,6 +89,10 @@ jobs:if: ${{ !cancelled() && steps.zig.conclusion == 'success' }}run: zig buildworking-directory: .+ - name: Worker replacement and retained listener lifecycle+ if: ${{ !cancelled() && steps.worker.conclusion == 'success' }}+ run: python3 scripts/test-server-retention.py --gui --evidence "$RUNNER_TEMP/server-retention-gui"+ working-directory: .- name: Production front-end failure and recovery with native input when permittedif: ${{ !cancelled() && steps.worker.conclusion == 'success' }}run: bun run test:frontenddiff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.tsindex e6f58876..2791c794 100644--- a/apps/native/app/api/acp/route.ts+++ b/apps/native/app/api/acp/route.ts@@ -71,9 +71,10 @@ function mcpOffPath(): string {// child's history; `dispose`/`dispose-page` reap children on tab close and// page unload. Kept on globalThis so dev-server module reloads don't orphan// running agents.-const g = globalThis as typeof globalThis & { __graffAcpSlots?: Map<string, Slot>; __graffAcpBootstraps?: Map<string, Promise<Slot>> };+const g = globalThis as typeof globalThis & { __graffAcpSlots?: Map<string, Slot>; __graffAcpBootstraps?: Map<string, Promise<Slot>>; __graffAcpRetirements?: Map<string, Promise<void>> };const slots = (g.__graffAcpSlots ??= new Map<string, Slot>());const bootstraps = (g.__graffAcpBootstraps ??= new Map<string, Promise<Slot>>());+const retirements = (g.__graffAcpRetirements ??= new Map<string, Promise<void>>());const DEFAULT_CHAT = "default";// Session names become a CLI argument and a filename under .graff/sessions.const SESSION_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;@@ -98,35 +99,23 @@ function defaultYolo(): boolean {// would skip. The signal is the fallback for an agent that does not wind down.const EXIT_GRACE_MS = 5_000;-function killSlot(chat: string) {+function killSlot(chat: string): Promise<void> {const slot = slots.get(chat);- if (!slot) return;+ if (!slot) return retirements.get(chat) ?? Promise.resolve();slots.delete(chat);- try {- slot.child.stdin.end();- } catch {- // already closed- }- const timer = setTimeout(() => {- try {- slot.child.kill("SIGTERM");- } catch {- // already gone- }- }, EXIT_GRACE_MS);- timer.unref();- slot.child.once("exit", () => clearTimeout(timer));+ const pending = retireWorker(slot.child, EXIT_GRACE_MS, "eof");+ retirements.set(chat, pending);+ const forget = () => { if (retirements.get(chat) === pending) retirements.delete(chat); };+ void pending.then(forget, forget);+ return pending;}-function killPage(page: string) {+async function killPage(page: string) {const prefix = `${page}:`;- for (const chat of [...slots.keys()]) {- if (chat.startsWith(prefix)) killSlot(chat);- }+ await Promise.all([...new Set([...slots.keys(), ...retirements.keys()])].filter(chat => chat.startsWith(prefix)).map(killSlot));}function spawnAgent(chat: string, opts: SpawnOpts): Slot {- killSlot(chat);const args = ["acp"];if (opts.yolo) args.push("--yolo");if (opts.model) args.push("--model", opts.model);@@ -218,6 +207,7 @@ function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {}async function bootstrapNow(chat: string, opts: BootstrapOpts): Promise<Slot> {+ await retirements.get(chat);const live = slots.get(chat);const same = live !== undefined && live.sessionId !== null &&live.transport.usable && matchesBootstrap(live, opts);@@ -227,6 +217,8 @@ async function bootstrapNow(chat: string, opts: BootstrapOpts): Promise<Slot> {await recovering.restartReady;if (slots.get(chat) !== live) return bootstrapNow(chat, opts);}+ await killSlot(chat);+ if (slots.has(chat)) return bootstrapNow(chat, opts);const slot = spawnAgent(chat, {model: opts.model ?? recovering?.model ?? undefined,resume: opts.resume ?? recovering?.resume ?? recovering?.sessionId ?? undefined,@@ -276,11 +268,11 @@ export async function POST(req: NextRequest) {const model = typeof body.params?.model === "string" ? body.params.model : undefined;try {if (method === "dispose") {- killSlot(chat);+ await killSlot(chat);return Response.json({ ok: true });}if (method === "dispose-page") {- if (typeof body.params?.page === "string" && body.params.page) killPage(body.params.page);+ if (typeof body.params?.page === "string" && body.params.page) await killPage(body.params.page);return Response.json({ ok: true });}if (method === "bootstrap") {diff --git a/apps/native/lib/acp-retire.test.ts b/apps/native/lib/acp-retire.test.tsindex 87b24199..6b6c727c 100644--- a/apps/native/lib/acp-retire.test.ts+++ b/apps/native/lib/acp-retire.test.ts@@ -12,3 +12,24 @@ test("recovery waits for an unresponsive worker to exit, escalating when it ignoawait retireWorker(child, 20); // Already exited workers need no second wait.} finally { child.kill("SIGKILL"); }});+++test("normal retirement lets EOF finish the worker's exit save", async () => {+ const child = spawn(process.execPath, ["-e", 'process.stdin.resume(); process.stdin.on("end", () => setTimeout(() => process.exit(0), 40)); console.log("ready")'], { stdio: ["pipe", "pipe", "ignore"] });+ try {+ await once(child.stdout!, "data");+ await retireWorker(child, 1000, "eof");+ expect(child.exitCode).toBe(0);+ expect(child.signalCode).toBeNull();+ } finally { child.kill("SIGKILL"); }+});+++test("EOF retirement escalates when the worker ignores EOF and termination", async () => {+ const child = spawn(process.execPath, ["-e", 'process.stdin.resume(); process.on("SIGTERM", () => {}); console.log("ready"); setInterval(() => {}, 1000)'], { stdio: ["pipe", "pipe", "ignore"] });+ try {+ await once(child.stdout!, "data");+ await retireWorker(child, 20, "eof");+ expect(child.signalCode).toBe("SIGKILL");+ } finally { child.kill("SIGKILL"); }+});diff --git a/apps/native/lib/acp-retire.ts b/apps/native/lib/acp-retire.tsindex f2bea7c4..626fa887 100644--- a/apps/native/lib/acp-retire.ts+++ b/apps/native/lib/acp-retire.ts@@ -1,15 +1,22 @@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> {+export function retireWorker(child: ChildProcess, graceMs = 1000, request: "signal" | "eof" = "signal"): Promise<void> {if (child.exitCode !== null || child.signalCode !== null) return Promise.resolve();return new Promise((resolve, reject) => {- const timer = setTimeout(() => child.kill("SIGKILL"), graceMs);+ let timer = setTimeout(() => {+ if (request === "eof") {+ child.kill("SIGTERM");+ timer = setTimeout(() => child.kill("SIGKILL"), 1000);+ } else 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");+ if (request === "eof") {+ try { child.stdin?.end(); } catch { child.kill("SIGTERM"); }+ } else child.kill("SIGTERM");});}diff --git a/apps/native/scripts/test-server-retention-route.ts b/apps/native/scripts/test-server-retention-route.tsnew file mode 100644index 00000000..c7512546--- /dev/null+++ b/apps/native/scripts/test-server-retention-route.ts@@ -0,0 +1,57 @@+import { strict as assert } from "node:assert";+import { writeFileSync } from "node:fs";+import { NextRequest } from "next/server";+import { POST } from "../app/api/acp/route";++const cwd = process.env.GRAFF_RETENTION_WORKSPACE!;+const evidence = process.env.GRAFF_RETENTION_EVIDENCE!;+const chat = "retention-fixture:chat";+const slots = (globalThis as any).__graffAcpSlots as Map<string, any>;+async function request(method: string, params: object = {}) {+ const response = await POST(new NextRequest("http://localhost/api/acp", {+ method: "POST", body: JSON.stringify({ chat, method, params }),+ }));+ const text = await response.text();+ assert.equal(response.status, 200, text);+ return text;+}+async function prompt(name: string, text: string) {+ const stream = await request("session/prompt", { prompt: [{ type: "text", text }] });+ writeFileSync(`${evidence}/${name}.jsonl`, stream);+ const events = stream.trim().split("\n").map(line => JSON.parse(line));+ assert(!events.some(event => event.error), stream);+ assert(events.some(event => event.result?.stopReason === "end_turn"), stream);+ assert(events.some(event => event.params?.update?.status === "completed" &&+ (JSON.stringify(event.params.update.content) ?? "").includes("listener ready")), stream);+}+async function waitExit(child: any) {+ const deadline = Date.now() + 10_000;+ while (child.exitCode === null && child.signalCode === null) {+ assert(Date.now() < deadline, "worker failed to retire");+ await new Promise(resolve => setTimeout(resolve, 20));+ }+}+let first: any;+let second: any;+try {+ await request("bootstrap", { cwd, model: "lmstudio", mcp: false });+ first = slots.get(chat).child;+ await prompt("first-prompt", "Start the isolated listener and verify readiness.");+ await request("bootstrap", { cwd, model: "lmstudio", reset: true, mcp: false });+ second = slots.get(chat).child;+ const replacement = { oldPid: first.pid, newPid: second.pid, oldExit: first.exitCode, oldSignal: first.signalCode };+ writeFileSync(`${evidence}/replacement.json`, JSON.stringify(replacement, null, 2));+ assert(first.exitCode !== null || first.signalCode !== null, "replacement was ready while old worker was still alive");+ await prompt("second-prompt", "Verify the existing listener is still reachable.");+ await request("dispose");+ await waitExit(second);+ assert.equal(first.exitCode, 0, "old worker did not exit gracefully");+ assert.equal(second.exitCode, 0, "disposed worker did not exit gracefully");+ console.log("PASS GUI API: old worker exits before replacement is ready; listener remains reachable");+} finally {+ await request("dispose");+ for (const child of [first, second].filter(Boolean)) {+ try { child.stdin.end(); await waitExit(child); }+ catch { child.kill("SIGKILL"); }+ }+}diff --git a/docs/adr/0098-orphan-listeners-are-not-stop-authority.md b/docs/adr/0098-orphan-listeners-are-not-stop-authority.mdindex 1b43185d..8f42eb1c 100644--- a/docs/adr/0098-orphan-listeners-are-not-stop-authority.md+++ b/docs/adr/0098-orphan-listeners-are-not-stop-authority.md@@ -53,3 +53,10 @@ paths, so the flag cannot establish historical user intent. This changesobservability, not the conservative cleanup rule above. The productionretention regression verifies a surviving listener after owner exit, itsrecord and CLI explanation, and an explicit verified stop.++GUI worker replacement and disposal await confirmed process exit. Graceful+EOF allows session saving and retention bookkeeping; bounded termination+and kill fallbacks handle unresponsive workers. A per-chat retirement promise+prevents a concurrent bootstrap from passing a worker still shutting down.+The GUI API regression uses the real worker and listener to verify replacement+ordering, continued listener access, and explicit cleanup.diff --git a/scripts/test-server-retention.py b/scripts/test-server-retention.pyindex 50271523..cdab67f6 100644--- a/scripts/test-server-retention.py+++ b/scripts/test-server-retention.py@@ -5,6 +5,7 @@ root = Path(__file__).resolve().parents[1]parser = argparse.ArgumentParser(description=__doc__)parser.add_argument('--graff', type=Path, default=root / 'zig-out/bin/graff')parser.add_argument('--evidence', type=Path, required=True)+parser.add_argument('--gui', action='store_true', help='Also exercise the GUI API replacement path; requires Bun and native app dependencies')args = parser.parse_args()out = args.evidence.resolve()out.mkdir(parents=True, exist_ok=True)@@ -24,12 +25,17 @@ def run_case(mode):env = {k: v for (k, v) in os.environ.items() if not k.endswith('_API_KEY')}env.update(HOME=temp, LMSTUDIO_API_KEY='local', GRAFF_NO_TELEMETRY='1', GRAFF_FLEET='off', GRAFF_NO_SMOLIFY='1', GRAFF_NO_CODEDB_GUARD='1', NO_COLOR='1', GRAFF_JOB_IDLE_WARN_MINS='0', GRAFF_JOB_IDLE_STOP_MINS='1', GRAFF_MCP_CONFIG=str(work / 'mcp.json'))model = reg.ScriptedModel([{'tool': 'bash', 'arguments': {'command': shlex.quote(sys.executable) + ' listener.py', 'run_in_background': True}}, reg.tool(shlex.quote(sys.executable) + ' ready.py'), {'text': 'The isolated listener is ready.'}])+ if mode == 'gui':+ model.script.extend([reg.tool(shlex.quote(sys.executable) + ' ready.py'), {'text': 'Still reachable.'}])model.start(1234)pid = Nonetry:command = [str(graff), '--json', '--yolo', '--old', '--model', 'lmstudio']prompt = json.dumps({'type': 'user', 'text': 'Start the isolated listener and verify readiness.'}) + '\n'- if mode == 'normal':+ if mode == 'gui':+ env.update(GRAFF_BIN=str(graff), GRAFF_CWD=str(work), GRAFF_RETENTION_WORKSPACE=str(work), GRAFF_RETENTION_EVIDENCE=str(out))+ command = ['bun', str(root / 'apps/native/scripts/test-server-retention-route.ts')]+ if mode != 'crash':done = reg.bounded_run(command, cwd=work, env=env, text=True, capture_output=True, timeout=110, input=prompt)else:with (out / 'owner-stdout.log').open('w+') as stdout, (out / 'owner-stderr.log').open('w+') as stderr:@@ -69,13 +75,13 @@ def run_case(mode):assert len(recs) == 1, recsrecord = json.loads(recs[0].read_text())assert not record['pinned'], record- assert record['retained'] == (mode == 'normal'), record- assert record.get('retention_reason') == ('unverified_consumers' if mode == 'normal' else None), record+ assert record['retained'] == (mode != 'crash'), record+ assert record.get('retention_reason') == ('unverified_consumers' if mode != 'crash' else None), record(out / 'retained-record.json').write_text(json.dumps(record, indent=2))listing = reg.bounded_run([str(graff), 'servers', 'list'], cwd=work, env=env, text=True, capture_output=True, timeout=30)(out / 'retained-list.log').write_text(listing.stdout)assert str(record['pid']) in listing.stdout, listing.stdout- if mode == 'normal':+ if mode != 'crash':assert 'consumer visibility unknown' in listing.stdout, listing.stdoutelse:row = next(line for line in listing.stdout.splitlines() if line.split() and line.split()[0].lstrip('+') == str(record['pid']))@@ -97,5 +103,5 @@ def run_case(mode):except ProcessLookupError:pass-for mode in ('normal', 'crash'):+for mode in (('normal', 'crash', 'gui') if args.gui else ('normal', 'crash')):run_case(mode)