Skip to content

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

Python

Preserve the initializing worker for concurrent chat requests

justrach3fb2589b8684
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.ts
index 6983025d..eeb97c9f 100644
--- a/apps/native/app/api/acp/route.ts
+++ b/apps/native/app/api/acp/route.ts
@@ -13,7 +13,7 @@ import { prepareGuiPrompt } from "@/lib/gui-skill-context";
import { attachmentStore } from "@/lib/attachment-store";
import { retireWorker } from "@/lib/acp-retire";
-import { initializeWorker } from "@/lib/acp-bootstrap";
+import { initializeWorker, serializeBootstrap } from "@/lib/acp-bootstrap";
import { finishCancelledPrompt } from "@/lib/acp-cancel";
export const runtime = "nodejs";
@@ -73,8 +73,9 @@ 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> };
+const g = globalThis as typeof globalThis & { __graffAcpSlots?: Map<string, Slot>; __graffAcpBootstraps?: Map<string, Promise<Slot>> };
const slots = (g.__graffAcpSlots ??= new Map<string, Slot>());
+const bootstraps = (g.__graffAcpBootstraps ??= new Map<string, Promise<Slot>>());
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._-]*$/;
@@ -188,21 +189,31 @@ async function endTurn(slot: Slot): Promise<void> {
/** The tab's live agent when it still matches what was asked for (model,
* session file, workspace, approval mode); otherwise a fresh spawn. A
* request that leaves a field out accepts whatever the live agent has. */
-async function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {
- const live = slots.get(chat);
- const same =
- live !== undefined &&
- live.sessionId !== null && live.transport.usable &&
- (!opts.model || live.model === opts.model) &&
+function matchesBootstrap(live: Slot, opts: BootstrapOpts): boolean {
+ return (!opts.model || live.model === opts.model) &&
(!opts.resume || live.resume === opts.resume) &&
(!opts.cwd || live.cwd === opts.cwd) &&
(opts.yolo === undefined || live.yolo === opts.yolo) &&
(opts.mcp === undefined || live.mcp === opts.mcp);
+}
+
+function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {
+ 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.
+ if (opts.reset || (live && !matchesBootstrap(live, opts))) bootstraps.delete(chat);
+ return serializeBootstrap(bootstraps, chat, () => bootstrapNow(chat, opts));
+}
+
+async function bootstrapNow(chat: string, opts: BootstrapOpts): Promise<Slot> {
+ const live = slots.get(chat);
+ const same = live !== undefined && live.sessionId !== null &&
+ live.transport.usable && matchesBootstrap(live, opts);
if (!opts.reset && same) return live;
const recovering = live?.restart ? live : undefined;
if (recovering?.restartReady) {
await recovering.restartReady;
- if (slots.get(chat) !== live) return bootstrap(chat, opts);
+ if (slots.get(chat) !== live) return bootstrapNow(chat, opts);
}
const slot = spawnAgent(chat, {
model: opts.model ?? recovering?.model ?? undefined,
@@ -221,6 +232,7 @@ async function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {
if (slots.get(chat) === slot) slots.delete(chat);
});
await drainCommands(slot);
+ if (slots.get(chat) !== slot) throw new Error("ACP startup was disposed. Retry to start a new worker.");
return slot;
}
diff --git a/apps/native/lib/acp-bootstrap.test.ts b/apps/native/lib/acp-bootstrap.test.ts
index 068a926c..1ffdd3f0 100644
--- a/apps/native/lib/acp-bootstrap.test.ts
+++ b/apps/native/lib/acp-bootstrap.test.ts
@@ -2,7 +2,7 @@ import { test, expect } from "bun:test";
import { spawn } from "node:child_process";
import { once } from "node:events";
import { AcpTransport } from "./acp-transport";
-import { initializeWorker } from "./acp-bootstrap";
+import { initializeWorker, serializeBootstrap } from "./acp-bootstrap";
import { retireWorker } from "./acp-retire";
async function worker(mode: string) {
@@ -43,3 +43,59 @@ for (const mode of ["initialize", "session/new", "invalid"]) {
} finally { await retireWorker(fresh.child, 50); }
});
}
+
+
+test("overlapping startup and first prompt share a completed worker", async () => {
+ const pending = new Map<string, Promise<string>>();
+ let live: Awaited<ReturnType<typeof worker>> | undefined;
+ let session: string | undefined;
+ let starts = 0;
+ const start = async () => {
+ if (session) return session;
+ starts++;
+ live = await worker("okay");
+ session = await initializeWorker(live.transport, process.cwd(), async () => {
+ await retireWorker(live!.child, 50);
+ }, 1000);
+ return session;
+ };
+ try {
+ expect(await Promise.all([
+ serializeBootstrap(pending, "chat", start),
+ serializeBootstrap(pending, "chat", start),
+ serializeBootstrap(pending, "chat", start),
+ ])).toEqual(["ready", "ready", "ready"]);
+ expect(starts).toBe(1);
+ expect(live?.transport.usable).toBe(true);
+ expect(pending.size).toBe(0);
+ } finally { if (live) await retireWorker(live.child, 50); }
+});
+
+test("a failed startup rejects queued callers without resurrecting it", async () => {
+ const pending = new Map<string, Promise<string>>();
+ let fail!: (error: Error) => void;
+ let queuedStarts = 0;
+ const first = serializeBootstrap(pending, "chat", () => new Promise<string>((_, reject) => { fail = reject; }));
+ const second = serializeBootstrap(pending, "chat", async () => { queuedStarts++; return "unexpected"; });
+ const results = Promise.allSettled([first, second]);
+ await Promise.resolve();
+ fail(new Error("startup disposed"));
+ expect((await results).map(result => result.status)).toEqual(["rejected", "rejected"]);
+ expect(queuedStarts).toBe(0);
+ expect(pending.size).toBe(0);
+ expect(await serializeBootstrap(pending, "chat", async () => "retry")).toBe("retry");
+});
+
+test("queued option changes wait while other chats stay independent", async () => {
+ const pending = new Map<string, Promise<string>>();
+ let ready!: (value: string) => void;
+ let current = "first workspace";
+ const first = serializeBootstrap(pending, "chat", () => new Promise<string>(resolve => { ready = resolve; }));
+ const moved = serializeBootstrap(pending, "chat", async () => { current = "second workspace"; return current; });
+ expect(await serializeBootstrap(pending, "other", async () => "independent")).toBe("independent");
+ expect(current).toBe("first workspace");
+ ready(current);
+ expect(await first).toBe("first workspace");
+ expect(await moved).toBe("second workspace");
+ expect(pending.size).toBe(0);
+});
diff --git a/apps/native/lib/acp-bootstrap.ts b/apps/native/lib/acp-bootstrap.ts
index 4d5158fb..807244f2 100644
--- a/apps/native/lib/acp-bootstrap.ts
+++ b/apps/native/lib/acp-bootstrap.ts
@@ -23,3 +23,16 @@ export async function initializeWorker(
throw error;
}
}
+
+/** Serialize a chat's handshakes, then re-evaluate its live slot/options.
+ * A failed or disposed startup rejects its already queued callers too; only
+ * a later explicit request retries. Different chats remain independent. */
+export async function serializeBootstrap<T>(
+ pending: Map<string, Promise<T>>, chat: string, start: () => Promise<T>,
+): Promise<T> {
+ const previous = pending.get(chat);
+ const next = previous ? previous.then(start) : Promise.resolve().then(start);
+ pending.set(chat, next);
+ try { return await next; }
+ finally { if (pending.get(chat) === next) pending.delete(chat); }
+}
diff --git a/apps/native/lib/acp-route.test.ts b/apps/native/lib/acp-route.test.ts
index 3d933cf0..51d0f491 100644
--- a/apps/native/lib/acp-route.test.ts
+++ b/apps/native/lib/acp-route.test.ts
@@ -185,3 +185,52 @@ require('node:readline').createInterface({input:process.stdin}).on('line',line=>
rmSync(temp,{recursive:true,force:true});
}
},10000);
+
+
+test("concurrent matching bootstraps finish one delayed worker handshake", async () => {
+ const temp = mkdtempSync(path.join(os.tmpdir(), "graff-acp-concurrent-"));
+ const binary = path.join(temp, "agent.cjs");
+ const oldBin = process.env.GRAFF_BIN;
+ writeFileSync(binary, `#!/usr/bin/env node
+const fs = require('node:fs');
+fs.appendFileSync('starts',String(process.pid)+'\\n');
+const send=value=>console.log(JSON.stringify(value));
+require('node:readline').createInterface({input:process.stdin}).on('line',line=>{
+ const req=JSON.parse(line);
+ if(req.method==='initialize') send({id:req.id,result:{}});
+ if(req.method==='session/new') {
+ fs.writeFileSync('initializing','yes');
+ setTimeout(()=>{
+ send({id:req.id,result:{sessionId:'shared'}});
+ send({method:'session/update',params:{update:{sessionUpdate:'available_commands_update',availableCommands:[{name:'help'}]}}});
+ },200);
+ }
+}).on('close',()=>process.exit(0));
+`, {mode:0o700});
+ const chat = `concurrent-test-${path.basename(temp)}`;
+ const call = (method: string, params = {}) => deadline(POST(new NextRequest("http://localhost/api/acp", {
+ method:"POST",body:JSON.stringify({chat,method,params}),
+ })), method);
+ try {
+ process.env.GRAFF_BIN = binary;
+ const options = {cwd:temp,model:"fixture",mcp:true};
+ const startup = call("bootstrap", {...options, reset:true});
+ await deadline((async()=>{
+ for(;;) {
+ try { readFileSync(path.join(temp,"initializing")); return; } catch {}
+ await new Promise(resolve=>setTimeout(resolve,10));
+ }
+ })(),"worker initializing");
+ const responses = await Promise.all([startup, call("bootstrap",options), call("bootstrap",options)]);
+ for (const response of responses) {
+ expect(response.status).toBe(200);
+ expect((await response.json()).sessionId).toBe("shared");
+ }
+ expect(readFileSync(path.join(temp,"starts"),"utf8").trim().split("\n")).toHaveLength(1);
+ expect((await call("initialize")).status).toBe(200);
+ } finally {
+ await call("dispose");
+ if(oldBin===undefined)delete process.env.GRAFF_BIN;else process.env.GRAFF_BIN=oldBin;
+ rmSync(temp,{recursive:true,force:true});
+ }
+},10000);