Skip to content

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

Python

Drain desktop workers before stopping the backend

justrach6e3dbd7655a6
diff --git a/.github/workflows/desktop.yml b/.github/workflows/desktop.yml
index 69b54a09..39bca696 100644
--- a/.github/workflows/desktop.yml
+++ b/.github/workflows/desktop.yml
@@ -115,12 +115,16 @@ jobs:
env:
GRAFF_FRONTEND_OUTPUT: ../../zig-out/cli-test
- name: Packaged conversation title creation and recovery
+ id: packaged
if: ${{ !cancelled() && steps.worker.conclusion == 'success' }}
run: |
GRAFF_REUSE_ENGINE=1 bun run electron:build
bun run test:packaged-titles
env:
GRAFF_PACKAGED_OUTPUT: ../../zig-out/packaged-titles
+ - name: Production desktop shutdown preserves retained servers
+ if: ${{ !cancelled() && steps.packaged.conclusion == 'success' }}
+ run: bun scripts/test-server-desktop.mjs
- name: Bounded mixed split and memory stress
if: ${{ !cancelled() && steps.worker.conclusion == 'success' }}
run: bun run test:split-stress
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.ts
index 2791c794..1ae25bdb 100644
--- a/apps/native/app/api/acp/route.ts
+++ b/apps/native/app/api/acp/route.ts
@@ -71,7 +71,7 @@ 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>>; __graffAcpRetirements?: Map<string, Promise<void>> };
+const g = globalThis as typeof globalThis & { __graffAcpSlots?: Map<string, Slot>; __graffAcpBootstraps?: Map<string, Promise<Slot>>; __graffAcpRetirements?: Map<string, Promise<void>>; __graffAcpShuttingDown?: boolean };
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>>());
@@ -199,6 +199,7 @@ function matchesBootstrap(live: Slot, opts: BootstrapOpts): boolean {
}
function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {
+ if (g.__graffAcpShuttingDown) return Promise.reject(new Error("Desktop is shutting down"));
const live = slots.get(chat);
// Explicit changes can replace a stalled handshake. Ordinary concurrent
// requests must wait instead of killing the worker they are about to use.
@@ -208,6 +209,7 @@ function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {
async function bootstrapNow(chat: string, opts: BootstrapOpts): Promise<Slot> {
await retirements.get(chat);
+ if (g.__graffAcpShuttingDown) throw new Error("Desktop is shutting down");
const live = slots.get(chat);
const same = live !== undefined && live.sessionId !== null &&
live.transport.usable && matchesBootstrap(live, opts);
@@ -218,6 +220,7 @@ async function bootstrapNow(chat: string, opts: BootstrapOpts): Promise<Slot> {
if (slots.get(chat) !== live) return bootstrapNow(chat, opts);
}
await killSlot(chat);
+ if (g.__graffAcpShuttingDown) throw new Error("Desktop is shutting down");
if (slots.has(chat)) return bootstrapNow(chat, opts);
const slot = spawnAgent(chat, {
model: opts.model ?? recovering?.model ?? undefined,
@@ -267,6 +270,11 @@ export async function POST(req: NextRequest) {
const chat = typeof body.chat === "string" && body.chat ? body.chat : DEFAULT_CHAT;
const model = typeof body.params?.model === "string" ? body.params.model : undefined;
try {
+ if (method === "shutdown") {
+ g.__graffAcpShuttingDown = true;
+ await Promise.all([...new Set([...slots.keys(), ...retirements.keys()])].map(killSlot));
+ return Response.json({ ok: true });
+ }
if (method === "dispose") {
await killSlot(chat);
return Response.json({ ok: true });
diff --git a/apps/native/electron/VISUAL-TESTS.md b/apps/native/electron/VISUAL-TESTS.md
index 8cf56f3c..677c4ce9 100644
--- a/apps/native/electron/VISUAL-TESTS.md
+++ b/apps/native/electron/VISUAL-TESTS.md
@@ -295,3 +295,16 @@ macOS window occlusion or presented frames.
Compare resource use with the same production benchmark described above; motion
checks verify behavior and cleanup, not an overall desktop memory budget.
+
+## Retained servers at desktop shutdown
+
+After building the GUI, worker, and Electron bundle, run
+`bun scripts/test-server-desktop.mjs`. The production Electron main and backend
+run with isolated profiles and hidden windows. Trusted Chromium input starts a
+real HTTP server through the worker, then optionally pins it. The test observes
+backend and worker exit before the external watchdog can clean up, requests a
+logged HTTP response after quit, and verifies fresh CLI discovery and stop.
+An unrelated listener must survive. Model replies are scripted locally; this
+is not a live-provider or native OS keyboard test. Logs, trajectories and
+screenshots stay in `zig-out/server-desktop` (or `GRAFF_SHUTDOWN_OUTPUT`).
+`GRAFF_SHUTDOWN_NATIVE` can select an already built native resources directory.
diff --git a/apps/native/electron/main.cjs b/apps/native/electron/main.cjs
index b879c00a..7ca2b579 100644
--- a/apps/native/electron/main.cjs
+++ b/apps/native/electron/main.cjs
@@ -26,7 +26,6 @@ app.setPath('userData', process.env.GRAFF_ELECTRON_SMOKE ? (process.env.GRAFF_SM
if (process.env.GRAFF_ELECTRON_SMOKE) process.env.GRAFF_THEMES_DIR = path.join(app.getPath('userData'), 'themes');
let win, browser, backend, automation, computer, profiler;
let terminals;
-let quitting = false;
const workspaceRequests = require('./workspace-open.cjs').workspaceOpen(target => {
if (win && !win.isDestroyed()) win.webContents.send('workspace-open', target);
});
@@ -52,16 +51,24 @@ function trusted(event) {
if (event.sender !== win?.webContents || event.senderFrame !== win.webContents.mainFrame ||
new URL(event.senderFrame.url).origin !== backend.origin) throw new Error('Untrusted IPC sender');
}
+let stopPromise;
function stop() {
- if (quitting) return; quitting = true;
- let unsafe = false;
- try { testDesktop?.assertSafe(); } catch (error) { console.error(error); unsafe = true; }
- terminals?.closeAll();
- profiler?.stop(); browser?.closeAll(); automation?.server.close(); backend?.stop();
- testDesktop?.cleanup();
- if (unsafe) app.exit(1);
+ if (stopPromise) return stopPromise;
+ return stopPromise = (async () => {
+ let unsafe = false;
+ try { testDesktop?.assertSafe(); } catch (error) { console.error(error); unsafe = true; }
+ terminals?.closeAll();
+ profiler?.stop(); browser?.closeAll(); automation?.server.close(); await backend?.stop();
+ testDesktop?.cleanup();
+ if (unsafe) app.exit(1);
+ })();
}
-app.on('before-quit', stop);
+let stopped = false;
+app.on('before-quit', event => {
+ if (stopped) return;
+ event.preventDefault();
+ void stop().finally(() => { stopped = true; app.quit(); });
+});
app.on('window-all-closed', () => app.quit());
process.on('SIGTERM', () => app.quit());
process.on('SIGINT', () => app.quit());
@@ -188,5 +195,5 @@ app.whenReady().then(async () => {
await win.loadURL(backend.origin); win.setWindowButtonVisibility(true);
if (testDesktop) testDesktop.present(win); else win.show();
profiler.record('ui-ready');
- if (process.env.GRAFF_ELECTRON_SMOKE) require(process.env.GRAFF_SMOKE_LAUNCH_ONLY ? './smoke-launch.cjs' : './smoke.cjs').run({ win, browser, automation, backend, metrics, activity, computer, profiler, token }).then(() => app.quit()).catch(error => { console.error(error); stop(); app.exit(1); });
-}).catch(error => { console.error(error); stop(); app.exit(1); });
+ if (process.env.GRAFF_ELECTRON_SMOKE) require(process.env.GRAFF_SMOKE_SERVER_LIFECYCLE ? './smoke-server-lifecycle.cjs' : process.env.GRAFF_SMOKE_LAUNCH_ONLY ? './smoke-launch.cjs' : './smoke.cjs').run({ win, browser, automation, backend, metrics, activity, computer, profiler, token }).then(() => app.quit()).catch(async error => { console.error(error); await stop(); app.exit(1); });
+}).catch(async error => { console.error(error); await stop(); app.exit(1); });
diff --git a/apps/native/electron/server-lifecycle-entry.cjs b/apps/native/electron/server-lifecycle-entry.cjs
new file mode 100644
index 00000000..868f2aab
--- /dev/null
+++ b/apps/native/electron/server-lifecycle-entry.cjs
@@ -0,0 +1,6 @@
+// Exercise the production detached backend group; the launcher owns cleanup.
+delete process.env.GRAFF_TEST_MANAGED_GROUP;
+const logs = require('node:path').join(process.env.GRAFF_SHUTDOWN_OUTPUT, 'logs');
+require('node:fs').mkdirSync(logs, {recursive:true});
+require('electron').app.setPath('logs', logs);
+require('./main.cjs');
diff --git a/apps/native/electron/server-shutdown.test.cjs b/apps/native/electron/server-shutdown.test.cjs
new file mode 100644
index 00000000..3526a11b
--- /dev/null
+++ b/apps/native/electron/server-shutdown.test.cjs
@@ -0,0 +1,36 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { once } = require('node:events');
+const { startServer } = require('./server.cjs');
+
+test('desktop shutdown is bounded when the backend ignores its drain request', {timeout:20000}, async () => {
+ const temp = fs.mkdtempSync(path.join(os.tmpdir(),'graff-shutdown-timeout-'));
+ fs.mkdirSync(path.join(temp,'ui'));
+ fs.symlinkSync(process.execPath,path.join(temp,'bun'));
+ fs.writeFileSync(path.join(temp,'ui/server.js'), `
+ const http=require('node:http'),fs=require('node:fs');
+ http.createServer((req,res)=>{
+ if(req.method==='GET'){res.end('ready');return;}
+ let body='';req.on('data',chunk=>body+=chunk);
+ req.on('end',()=>fs.writeFileSync('request.json',JSON.stringify({body:JSON.parse(body),token:req.headers['x-graff-desktop']})));
+ }).listen(Number(process.env.PORT),process.env.HOSTNAME);
+ `);
+ let backend;
+ try {
+ backend = await startServer(temp,temp,'fixture-token',path.join(temp,'logs'));
+ const started = Date.now();
+ const first = backend.stop();
+ assert.equal(backend.stop(),first,'concurrent quits should share shutdown');
+ await first;
+ assert(Date.now()-started<15000,'backend drain exceeded its bound');
+ if(backend.child.exitCode===null&&backend.child.signalCode===null)await once(backend.child,'exit');
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(temp,'ui/request.json'),'utf8')),{body:{method:'shutdown'},token:'fixture-token'});
+ await assert.rejects(fetch(backend.origin,{signal:AbortSignal.timeout(1000)}));
+ } finally {
+ if(backend&&backend.child.exitCode===null&&backend.child.signalCode===null){backend.child.kill('SIGKILL');await once(backend.child,'exit');}
+ fs.rmSync(temp,{recursive:true,force:true});
+ }
+});
diff --git a/apps/native/electron/server.cjs b/apps/native/electron/server.cjs
index f9a0d569..5bce8e62 100644
--- a/apps/native/electron/server.cjs
+++ b/apps/native/electron/server.cjs
@@ -25,7 +25,20 @@ async function startServer(resources, root, token, logDirectory, desktopEnv = {}
fs.closeSync(log);
let spawnError; child.on('error', error => { spawnError = error; });
const origin = `http://127.0.0.1:${port}`;
- const stop = () => { if (child.pid) { try { managed ? child.kill('SIGTERM') : process.kill(-child.pid, 'SIGTERM'); } catch {} } };
+ let stopping;
+ const stop = () => stopping ??= (async () => {
+ // Let workers save sessions and hand retained server pipes to drainers.
+ if (child.exitCode === null && child.signalCode === null) {
+ try {
+ const response = await fetch(`${origin}/api/acp`, {
+ method: 'POST', headers: { 'content-type': 'application/json', 'x-graff-desktop': token },
+ body: JSON.stringify({ method: 'shutdown' }), signal: AbortSignal.timeout(7500),
+ });
+ if (!response.ok) console.warn('Worker shutdown was not acknowledged; stopping backend');
+ } catch { console.warn('Worker shutdown unavailable; stopping backend'); }
+ }
+ if (child.pid) { try { managed ? child.kill('SIGTERM') : process.kill(-child.pid, 'SIGTERM'); } catch {} }
+ })();
try {
for (let attempt = 0; attempt < 120; attempt++) {
if (spawnError) throw spawnError;
@@ -34,6 +47,6 @@ async function startServer(resources, root, token, logDirectory, desktopEnv = {}
await new Promise(resolve => setTimeout(resolve, 250));
}
throw new Error('UI server did not start');
- } catch (error) { stop(); throw error; }
+ } catch (error) { await stop(); throw error; }
}
module.exports = { startServer };
diff --git a/apps/native/electron/smoke-server-lifecycle.cjs b/apps/native/electron/smoke-server-lifecycle.cjs
new file mode 100644
index 00000000..b8155814
--- /dev/null
+++ b/apps/native/electron/smoke-server-lifecycle.cjs
@@ -0,0 +1,53 @@
+const assert = require('node:assert/strict');
+const fs = require('node:fs'), path = require('node:path');
+const desktop = require('./test-desktop.cjs');
+const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
+exports.run = async ({win, backend}) => {
+ const output = process.env.GRAFF_SHUTDOWN_OUTPUT;
+ const js = source => win.webContents.executeJavaScript(source);
+ const until = async (condition, label) => {
+ const end = Date.now() + 30000;
+ while (Date.now() < end) { if (await condition()) return; await sleep(50); }
+ throw Error(`Shutdown fixture timed out: ${label}`);
+ };
+ await until(() => js(`!!document.querySelector('[data-workspace-ready="true"] textarea[aria-label="Prompt"]')`), 'composer');
+ async function submit(text) {
+ const box = await js(`(() => { const e=document.querySelector('textarea[aria-label="Prompt"]');e.scrollIntoView({block:'center'});const r=e.getBoundingClientRect();return {x:r.x+r.width/2,y:r.y+r.height/2}; })()`);
+ await desktop.testInput(win.webContents, {type:'mouseDown',button:'left',clickCount:1,...box});
+ await desktop.testInput(win.webContents, {type:'mouseUp',button:'left',clickCount:1,...box});
+ for (const keyCode of text) await desktop.testInput(win.webContents, {type:'char',keyCode});
+ await desktop.testInput(win.webContents, {type:'keyDown',keyCode:'Return'});
+ await desktop.testInput(win.webContents, {type:'keyUp',keyCode:'Return'});
+ }
+ await submit('Start the isolated listener, check its socket, and report readiness.');
+ await until(() => js(`document.body.innerText.includes('Listener ready for shutdown.')`), 'agent completion');
+ if (process.env.GRAFF_SHUTDOWN_PIN === '1') {
+ await submit('/jobs keep 1');
+ await until(() => js(`document.body.innerText.includes('job 1 pinned')`), 'explicit user pin');
+ }
+ const workspace = process.env.GRAFF_CWD;
+ const listener = JSON.parse(fs.readFileSync(path.join(workspace,'listener.json'),'utf8'));
+ const records = fs.readdirSync(path.join(process.env.HOME,'.codegraff/jobs')).map(name => JSON.parse(fs.readFileSync(path.join(process.env.HOME,'.codegraff/jobs',name),'utf8')));
+ assert.equal(records.length, 1);
+ assert.equal(records[0].pinned, process.env.GRAFF_SHUTDOWN_PIN === '1');
+ fs.writeFileSync(path.join(output,'before-quit.json'),JSON.stringify({app:process.pid,backend:backend.child.pid,listener,record:records[0]},null,2));
+ fs.writeFileSync(path.join(output,'gui-text.txt'),await js('document.body.innerText'));
+ fs.writeFileSync(path.join(output,'before-quit.png'),(await win.webContents.capturePage()).toPNG());
+ desktop.assertSafe();
+ // Observe shutdown before the external watchdog can reap Electron's group.
+ const alive = pid => {
+ try { return !require('node:child_process').execFileSync('ps',['-p',String(pid),'-o','stat='],{encoding:'utf8'}).trim().startsWith('Z'); }
+ catch { return false; }
+ };
+ let observingQuit = false;
+ require('electron').app.on('before-quit', event => {
+ event.preventDefault();
+ if (observingQuit) return;
+ observingQuit = true;
+ until(() => !alive(backend.child.pid) && !alive(records[0].owner_pid), 'production backend and worker shutdown')
+ .then(() => {
+ fs.writeFileSync(path.join(output,'quit-observed.json'),JSON.stringify({backendGone:true,workerGone:true}));
+ require('electron').app.exit(0);
+ }).catch(error => { console.error(error); require('electron').app.exit(1); });
+ });
+};
diff --git a/apps/native/scripts/test-server-desktop.mjs b/apps/native/scripts/test-server-desktop.mjs
new file mode 100644
index 00000000..49608818
--- /dev/null
+++ b/apps/native/scripts/test-server-desktop.mjs
@@ -0,0 +1,66 @@
+import {spawn,execFileSync} from 'node:child_process';
+import {createRequire} from 'node:module';
+import fs from 'node:fs';
+import net from 'node:net';
+import os from 'node:os';
+import path from 'node:path';
+import assert from 'node:assert/strict';
+import {fileURLToPath} from 'node:url';
+import {runDesktopProcess} from './test-electron.mjs';
+const require=createRequire(import.meta.url),ui=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..'),repo=path.resolve(ui,'../..');
+const binary=process.env.GRAFF_FRONTEND_BIN||path.join(repo,'zig-out/bin/graff');
+const native=process.env.GRAFF_SHUTDOWN_NATIVE||path.join(repo,'zig-out/electron/Codegraff.app/Contents/Resources/native');
+const output=path.resolve(process.env.GRAFF_SHUTDOWN_OUTPUT||path.join(repo,'zig-out/server-desktop'));
+const sleep=ms=>new Promise(r=>setTimeout(r,ms));
+const connects=port=>new Promise(resolve=>{const s=net.connect({host:'127.0.0.1',port});s.setTimeout(500);s.once('connect',()=>{s.destroy();resolve(true)});s.once('error',()=>resolve(false));s.once('timeout',()=>{s.destroy();resolve(false)});});
+for(const pinned of [false,true]) {
+ const temp=fs.mkdtempSync(path.join(os.tmpdir(),'graff-desktop-shutdown-')),out=path.join(output,pinned?'pinned':'automatic'),workspace=path.join(temp,'workspace'),resources=path.join(temp,'resources');
+ for(const dir of [out,workspace,resources])fs.mkdirSync(dir,{recursive:true});
+ fs.cpSync(path.join(ui,'.next/standalone'),path.join(resources,'ui'),{recursive:true});
+ fs.cpSync(path.join(ui,'electron'),path.join(resources,'app'),{recursive:true});
+ fs.cpSync(path.join(ui,'.next/static'),path.join(resources,'ui/.next/static'),{recursive:true});
+ const backendFile=path.join(resources,'ui/server.js');
+ fs.writeFileSync(backendFile,`import {writeFileSync as recordBackendPid} from 'node:fs';recordBackendPid(${JSON.stringify(path.join(out,'backend-pid.txt'))},String(process.pid));\n`+fs.readFileSync(backendFile,'utf8'));
+ fs.symlinkSync(native,path.join(resources,'native'));fs.symlinkSync(process.execPath,path.join(resources,'bun'));
+ fs.writeFileSync(path.join(resources,'graff'),'#!/usr/bin/env python3\nimport os,sys\nbinary='+JSON.stringify(binary)+'\nargs=sys.argv[1:]\nif args and args[0]=="acp":args += ["--model","lmstudio","--old","--yolo"]\nos.execv(binary,[binary]+args)\n',{mode:0o755});
+ fs.writeFileSync(path.join(workspace,'listener.py'),"import os,json\nfrom pathlib import Path\nfrom http.server import HTTPServer,BaseHTTPRequestHandler\nclass Handler(BaseHTTPRequestHandler):\n def do_GET(self):\n print('request served',flush=True)\n self.send_response(200);self.end_headers();self.wfile.write(b'ready')\ns=HTTPServer(('127.0.0.1',0),Handler)\nPath('listener.json').write_text(json.dumps({'pid':os.getpid(),'port':s.server_port}))\ns.serve_forever()\n");
+ fs.writeFileSync(path.join(workspace,'ready.py'),"import json,time,urllib.request\nfrom pathlib import Path\nfor _ in range(100):\n if Path('listener.json').exists():break\n time.sleep(.05)\nr=json.loads(Path('listener.json').read_text());body=urllib.request.urlopen('http://127.0.0.1:'+str(r['port']),timeout=2).read();assert body==b'ready',body;print('HTTP response verified: ready')\n");
+ const script=path.join(temp,'script.json'),mcp=path.join(temp,'mcp.json');fs.writeFileSync(mcp,'{"mcpServers":{}}');fs.writeFileSync(script,JSON.stringify([{tool:'bash',arguments:{command:'python3 listener.py',run_in_background:true}},{tool:'bash',arguments:{command:'python3 ready.py'}},{text:'Listener ready for shutdown.'}]));
+ const env={...process.env,HOME:temp,LMSTUDIO_API_KEY:'local',GRAFF_CWD:workspace,GRAFF_ELECTRON_RESOURCES:resources,GRAFF_ELECTRON_SMOKE:path.join(out,'smoke.json'),GRAFF_SMOKE_SERVER_LIFECYCLE:'1',GRAFF_SHUTDOWN_OUTPUT:out,GRAFF_SHUTDOWN_PIN:pinned?'1':'0',GRAFF_SMOKE_PROFILE:path.join(temp,'profile'),GRAFF_MCP_CONFIG:mcp,GRAFF_NO_TELEMETRY:'1',GRAFF_FLEET:'off',GRAFF_NO_SMOLIFY:'1',GRAFF_NO_CODEDB_GUARD:'1'};
+ for(const key of Object.keys(env))if(key.endsWith('_API_KEY')&&key!=='LMSTUDIO_API_KEY')delete env[key];
+ const fd=fs.openSync(path.join(out,'model.log'),'w'),model=spawn('python3',[path.join(repo,'scripts/eval/frontend_model.py'),'--script',script,'--requests',path.join(out,'requests.json')],{env,stdio:['ignore',fd,fd]});fs.closeSync(fd);
+ const unrelated=net.createServer(s=>s.end());await new Promise(r=>unrelated.listen(0,'127.0.0.1',r));
+ try {
+ const end=Date.now()+10000;while(!fs.readFileSync(path.join(out,'model.log'),'utf8').includes('scripted model on')){assert(model.exitCode===null&&Date.now()<end,'fixture unavailable');await sleep(50)}
+ process.env.GRAFF_TEST_TIMEOUT_MS='120000';
+ assert.equal(await runDesktopProcess(require('electron'),[path.join(ui,'electron/server-lifecycle-entry.cjs')],env),0,'Electron fixture failed');
+ const before=JSON.parse(fs.readFileSync(path.join(out,'before-quit.json'),'utf8'));
+ assert.deepEqual(JSON.parse(fs.readFileSync(path.join(out,'quit-observed.json'),'utf8')),{backendGone:true,workerGone:true});
+ assert(await connects(before.listener.port),'listener lost during quit');
+ const response=await fetch(`http://127.0.0.1:${before.listener.port}`,{signal:AbortSignal.timeout(2000)});
+ const responseText=await response.text();assert.equal(response.status,200);assert.equal(responseText,'ready');
+ fs.writeFileSync(path.join(out,'after-response.txt'),responseText);
+ const rec=JSON.parse(fs.readFileSync(path.join(temp,'.codegraff/jobs',`${before.record.pid}.json`),'utf8'));assert.equal(rec.pinned,pinned);assert.equal(rec.retained,true);assert.equal(rec.retention_reason,pinned?'user_pin':'unverified_consumers');
+ const listing=execFileSync(binary,['servers','list'],{env,cwd:workspace,encoding:'utf8',timeout:30000});fs.writeFileSync(path.join(out,'after-list.txt'),listing);
+ const row=listing.split('\n').find(l=>l.trim().split(/\s+/)[0].replace(/^\+/,'')===String(before.record.pid));assert(row?.includes('gone'),listing);
+ fs.writeFileSync(path.join(out,'stop.txt'),execFileSync(binary,['servers','stop',String(before.record.pid)],{env,cwd:workspace,encoding:'utf8',timeout:30000}));
+ assert(!await connects(before.listener.port),'verified stop left listener open');assert(await connects(unrelated.address().port),'unrelated listener lost');
+ fs.writeFileSync(path.join(out,'results.json'),JSON.stringify({status:'passed',pinned,desktopQuitObserved:true,listenerSurvived:true,verifiedStopClosed:true,unrelatedSurvived:true},null,2));console.log(`PASS desktop quit: pinned=${pinned}`);
+ } finally {
+ const registry=path.join(temp,'.codegraff/jobs');
+ if(fs.existsSync(registry))for(const file of fs.readdirSync(registry)){
+ try {const record=JSON.parse(fs.readFileSync(path.join(registry,file),'utf8'));execFileSync(binary,['servers','stop',String(record.pid)],{env,cwd:workspace,timeout:10000,stdio:'ignore'});}catch{}
+ }
+ const backendPidFile=path.join(out,'backend-pid.txt');
+ if(fs.existsSync(backendPidFile)){
+ const pid=Number(fs.readFileSync(backendPidFile,'utf8'));
+ try {
+ const snapshot=execFileSync('ps',['-p',String(pid),'-o','pgid=,command='],{encoding:'utf8'}).trim();
+ if(snapshot.split(/\s+/)[0]===String(pid)&&snapshot.includes(path.join(resources,'ui/server.js')))process.kill(-pid,'SIGTERM');
+ } catch {}
+ }
+ if(fs.existsSync(path.join(workspace,'.graff')))fs.cpSync(path.join(workspace,'.graff'),path.join(out,'graff'),{recursive:true});
+ const logs=path.join(temp,'profile/logs');if(fs.existsSync(logs))fs.cpSync(logs,path.join(out,'logs'),{recursive:true});
+ model.kill('SIGTERM');unrelated.close();fs.rmSync(temp,{recursive:true,force:true});
+ }
+}
diff --git a/apps/native/scripts/test-server-retention-route.ts b/apps/native/scripts/test-server-retention-route.ts
index c7512546..e865f11a 100644
--- a/apps/native/scripts/test-server-retention-route.ts
+++ b/apps/native/scripts/test-server-retention-route.ts
@@ -47,6 +47,13 @@ try {
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");
+ await request("shutdown");
+ const refused = await POST(new NextRequest("http://localhost/api/acp", {
+ method: "POST", body: JSON.stringify({chat, method:"bootstrap", params:{cwd, model:"lmstudio", mcp:false}}),
+ }));
+ assert.equal(refused.status, 502);
+ assert((await refused.text()).includes("shutting down"));
+ assert.equal(slots.size, 0, "shutdown allowed a replacement worker");
console.log("PASS GUI API: old worker exits before replacement is ready; listener remains reachable");
} finally {
await request("dispose");
diff --git a/docs/adr/0098-orphan-listeners-are-not-stop-authority.md b/docs/adr/0098-orphan-listeners-are-not-stop-authority.md
index 8f42eb1c..3a264053 100644
--- a/docs/adr/0098-orphan-listeners-are-not-stop-authority.md
+++ b/docs/adr/0098-orphan-listeners-are-not-stop-authority.md
@@ -60,3 +60,11 @@ 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.
+
+Desktop quit drains all ACP workers through the authenticated local backend
+before terminating its process group. The backend refuses new bootstraps once
+shutdown begins. EOF permits output-pipe handoff, so a retained server can
+still log and serve HTTP after quit; a socket alone is insufficient evidence.
+The app waits for this bounded shutdown, including repeated quit requests.
+The Electron regression checks an HTTP response after quit for both automatic
+retention and an explicit pin, then verifies discovery and stop from a new CLI.