Skip to content

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

Python

Redirect every queued bootstrap caller to its replacement

Rach Pradhane73450f771c4
diff --git a/apps/native/app/api/acp/route.ts b/apps/native/app/api/acp/route.ts
index 3bd5a1ab..c51784e2 100644
--- a/apps/native/app/api/acp/route.ts
+++ b/apps/native/app/api/acp/route.ts
@@ -81,10 +81,11 @@ 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>>; __graffAcpBootstrapReplacements?: WeakMap<Promise<Slot>, Promise<Slot>>; __graffAcpRetirements?: Map<string, Promise<void>>; __graffAcpShuttingDown?: boolean };
+type BootstrapGeneration = { replacement?: Promise<Slot> };
+const g = globalThis as typeof globalThis & { __graffAcpSlots?: Map<string, Slot>; __graffAcpBootstraps?: Map<string, Promise<Slot>>; __graffAcpBootstrapGenerations?: WeakMap<Promise<Slot>, BootstrapGeneration>; __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 bootstrapReplacements = (g.__graffAcpBootstrapReplacements ??= new WeakMap<Promise<Slot>, Promise<Slot>>());
+const bootstrapGenerations = (g.__graffAcpBootstrapGenerations ??= new WeakMap<Promise<Slot>, BootstrapGeneration>());
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.
@@ -260,16 +261,21 @@ function bootstrap(chat: string, opts: BootstrapOpts): Promise<Slot> {
// Explicit changes can replace a stalled handshake. Ordinary concurrent
// requests must wait instead of killing the worker they are about to use.
const replacing = opts.reset || (live !== undefined && !matchesBootstrap(live, opts));
- const previous = replacing ? bootstraps.get(chat) : undefined;
+ const previous = bootstraps.get(chat);
+ const previousGeneration = previous ? bootstrapGenerations.get(previous) : undefined;
+ // Every caller queued behind a handshake belongs to that same generation.
+ // Replacing its tail must redirect the original caller as well as the queue.
+ const generation: BootstrapGeneration = !replacing && previousGeneration ? previousGeneration : {};
if (replacing) bootstraps.delete(chat);
const serialized = serializeBootstrap(bootstraps, chat, () => bootstrapNow(chat, opts));
- const generation = bootstraps.get(chat);
+ const pending = bootstraps.get(chat);
+ if (pending) bootstrapGenerations.set(pending, generation);
const result = serialized.catch(error => {
- const replacement = generation ? bootstrapReplacements.get(generation) : undefined;
+ const replacement = generation.replacement;
if (replacement) return replacement;
throw error;
});
- if (previous) bootstrapReplacements.set(previous, result);
+ if (replacing && previousGeneration) previousGeneration.replacement = result;
return result;
}
diff --git a/apps/native/lib/acp-route-adoption.test.ts b/apps/native/lib/acp-route-adoption.test.ts
new file mode 100644
index 00000000..0fa3e5a3
--- /dev/null
+++ b/apps/native/lib/acp-route-adoption.test.ts
@@ -0,0 +1,86 @@
+import { expect, test } from "bun:test";
+import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { NextRequest } from "next/server";
+import { POST } from "../app/api/acp/route";
+
+async function until(ready: () => boolean) {
+ const end = Date.now() + 3500;
+ while (!ready()) {
+ if (Date.now() > end) throw new Error("Bootstrap fixture readiness timed out");
+ await new Promise(resolve => setTimeout(resolve, 10));
+ }
+}
+
+for (const outcome of ["replacement", "failure", "dispose"] as const) {
+ test(`queued bootstrap callers share the final ${outcome} outcome`, async () => {
+ const temp = mkdtempSync(path.join(os.tmpdir(), "graff-acp-adoption-"));
+ const binary = path.join(temp, "agent.cjs");
+ const oldBin = process.env.GRAFF_BIN;
+ writeFileSync(binary, `#!/usr/bin/env node
+const fs = require('node:fs');
+const stalled = process.argv.includes('stalled');
+const failed = process.argv.includes('failure');
+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') {
+ if (stalled) fs.writeFileSync('stalled', String(process.pid));
+ else if (failed) send({id:req.id,error:{code:-32603,message:'final bootstrap failure'}});
+ else send({id:req.id,result:{protocolVersion:1}});
+ }
+ if (req.method === 'session/new') {
+ send({id:req.id,result:{sessionId:'replacement'}});
+ send({method:'session/update',params:{update:{sessionUpdate:'available_commands_update',availableCommands:[]}}});
+ }
+}).on('close', () => process.exit(0));
+`, { mode: 0o700 });
+ const chat = `adoption-${path.basename(temp)}`;
+ const pending = (globalThis as typeof globalThis & { __graffAcpBootstraps: Map<string, Promise<unknown>> }).__graffAcpBootstraps;
+ const call = (method: string, params = {}) => POST(new NextRequest("http://localhost/api/acp", {
+ method: "POST", body: JSON.stringify({ chat, method, params }),
+ }));
+ const starts = () => readFileSync(path.join(temp, "starts"), "utf8").trim().split("\n").map(Number);
+ try {
+ process.env.GRAFF_BIN = binary;
+ const original = call("bootstrap", { cwd: temp, model: "stalled", mcp: true });
+ await until(() => { try { return !!readFileSync(path.join(temp, "stalled")); } catch { return false; } });
+ const first = pending.get(chat);
+ const queued = call("bootstrap");
+ await until(() => pending.get(chat) !== first);
+ const last = outcome === "dispose"
+ ? call("dispose")
+ : call("bootstrap", { cwd: temp, model: outcome, mcp: true });
+ const [a, a2, b] = await Promise.all([original, queued, last]);
+ if (outcome === "replacement") {
+ for (const response of [a, a2, b]) {
+ expect(response.status).toBe(200);
+ expect((await response.json()).sessionId).toBe("replacement");
+ }
+ expect(starts().length).toBe(2);
+ expect(() => process.kill(starts()[0], 0)).toThrow();
+ expect(() => process.kill(starts()[1], 0)).not.toThrow();
+ expect((await call("bootstrap", { cwd: temp, model: "replacement", mcp: true })).status).toBe(200);
+ expect(starts().length).toBe(2);
+ } else {
+ for (const response of outcome === "failure" ? [a, a2, b] : [a, a2]) {
+ expect(response.status).toBe(502);
+ const error = (await response.json()).error as string;
+ expect(error).toContain(outcome === "failure" ? "final bootstrap failure" : "worker retired");
+ if (outcome === "failure") expect(error).not.toContain("worker retired");
+ }
+ if (outcome === "dispose") expect(b.status).toBe(200);
+ for (const pid of starts()) expect(() => process.kill(pid, 0)).toThrow();
+ expect((await call("bootstrap", { cwd: temp, model: "replacement", mcp: true })).status).toBe(200);
+ }
+ expect(pending.has(chat)).toBe(false);
+ } finally {
+ await call("dispose");
+ if (oldBin === undefined) delete process.env.GRAFF_BIN; else process.env.GRAFF_BIN = oldBin;
+ for (const pid of starts()) expect(() => process.kill(pid, 0)).toThrow();
+ rmSync(temp, { recursive: true, force: true });
+ }
+ }, 10000);
+}