Skip to content

Commit 287c5b7

Browse files
committed
Join held Claude startup through graceful adapter shutdown
1 parent c0edd1b commit 287c5b7

3 files changed

Lines changed: 221 additions & 22 deletions

File tree

‎packages/acp/tests/adapter-protocol.test.ts‎

Lines changed: 83 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ interface Adapter {
4949
/** The adapter process, so a case can say what the resource still observes. */
5050
readonly child: ChildProcess;
5151
readonly log: string;
52+
readonly closed: Operation<{ code: number | null; signal: NodeJS.Signals | null }>;
53+
readonly replies: Array<Record<string, unknown>>;
5254
request(method: string, params: unknown): Operation<Record<string, unknown>>;
5355
/**
5456
* Every `session/update` notification the adapter sent, in arrival order.
@@ -75,15 +77,28 @@ function useAdapter(provider: string, environment: Record<string, string>): Oper
7577
const entry = adapters.executablePath(provider);
7678

7779
let child: ChildProcess | undefined;
78-
const closed = withResolvers<void>();
79-
const onClose = (): void => closed.resolve();
80+
const closed = withResolvers<{ code: number | null; signal: NodeJS.Signals | null }>();
81+
let outcome: { code: number | null; signal: NodeJS.Signals | null } | undefined;
82+
let onStdout: ((chunk: Buffer) => void) | undefined;
83+
const onClose = (code: number | null, signal: NodeJS.Signals | null): void => {
84+
outcome = { code, signal };
85+
closed.resolve(outcome);
86+
};
8087
yield* ensure(function* () {
8188
if (child !== undefined) {
8289
try {
83-
child.stdin?.end();
84-
child.kill();
90+
if (outcome === undefined) {
91+
child.stdin?.end();
92+
// Claude disposes pending Queries on EOF; SIGTERM can preempt that shutdown.
93+
if (provider !== "claude") {
94+
child.kill();
95+
}
96+
}
8597
yield* closed.operation;
8698
} finally {
99+
if (onStdout !== undefined) {
100+
child.stdout?.off("data", onStdout);
101+
}
87102
child.off("close", onClose);
88103
}
89104
}
@@ -99,10 +114,11 @@ function useAdapter(provider: string, environment: Record<string, string>): Oper
99114

100115
const pending = new Map<number, (message: Record<string, unknown>) => void>();
101116
const updates: Array<Record<string, unknown>> = [];
117+
const replies: Array<Record<string, unknown>> = [];
102118
let next = 1;
103119
let buffer = "";
104120

105-
const onStdout = (chunk: Buffer): void => {
121+
onStdout = (chunk: Buffer): void => {
106122
buffer += chunk.toString("utf8");
107123
let index = buffer.indexOf("\n");
108124
while (index >= 0) {
@@ -119,6 +135,9 @@ function useAdapter(provider: string, environment: Record<string, string>): Oper
119135
continue;
120136
}
121137
const id = message["id"];
138+
if (typeof id === "number" && message["method"] === undefined) {
139+
replies.push(message);
140+
}
122141
if (typeof id === "number" && pending.has(id)) {
123142
pending.get(id)?.(message);
124143
pending.delete(id);
@@ -139,19 +158,13 @@ function useAdapter(provider: string, environment: Record<string, string>): Oper
139158
}
140159
};
141160

142-
// Detached before the kill above, because destructors unwind in reverse:
143-
// the adapter stops being read before the process it is reading is ended.
144-
// Established before the subscription, because `yield* ensure(...)` is
145-
// itself a suspension an owner can be halted at.
146-
yield* ensure(() => {
147-
processChild.stdout?.off("data", onStdout);
148-
});
149-
150-
processChild.stdout?.on("data", onStdout);
161+
child.stdout?.on("data", onStdout);
151162

152163
yield* provide({
153164
child: processChild,
154165
log,
166+
closed: closed.operation,
167+
replies,
155168
updates,
156169
*request(method: string, params: unknown): Operation<Record<string, unknown>> {
157170
const id = next++;
@@ -512,23 +525,23 @@ describe("Tier EA — the embedded adapters' prompt-response metadata", () => {
512525
}
513526

514527
it("HC Claude cancellation joins the held startup Query with no late response", function* () {
515-
let child: ChildProcess | undefined;
528+
let adapter: Adapter | undefined;
516529
let answered = false;
517530
yield* scoped(function* () {
518-
const adapter = yield* useAdapter("claude", {
531+
const live = yield* useAdapter("claude", {
519532
...CLAUDE_ENV,
520533
FAKE_CLAUDE_CONFIRMATION: "held",
521534
});
522-
child = adapter.child;
523-
yield* initialize(adapter);
535+
adapter = live;
536+
yield* initialize(live);
524537
const opening = yield* effectionSpawn(function* () {
525-
yield* openSession(adapter);
538+
yield* openSession(live);
526539
answered = true;
527540
});
528541
let started = false;
529542
while (!started) {
530543
try {
531-
started = (yield* readTextFile(adapter.log)).includes('"control_request"');
544+
started = (yield* readTextFile(live.log)).includes('"control_request"');
532545
} catch {
533546
/* The CLI has not created its log yet. */
534547
}
@@ -537,12 +550,60 @@ describe("Tier EA — the embedded adapters' prompt-response metadata", () => {
537550
}
538551
}
539552
yield* opening.halt();
540-
expect(acceptances(adapter)).toEqual([]);
553+
expect(acceptances(live)).toEqual([]);
541554
});
542-
expect(child?.exitCode).toBe(0);
555+
if (adapter === undefined) {
556+
throw new Error("the adapter never started");
557+
}
558+
expect(yield* adapter.closed).toEqual({ code: 0, signal: null });
559+
expect(acceptances(adapter)).toEqual([]);
560+
expect(
561+
adapter.replies.some((reply) => {
562+
const result = reply["result"];
563+
return (
564+
typeof result === "object" &&
565+
result !== null &&
566+
typeof Reflect.get(result, "sessionId") === "string"
567+
);
568+
}),
569+
).toBe(false);
543570
expect(answered).toBe(false);
544571
});
545572

573+
it("HC Claude startup disposal joins the backend and its held helper before returning", function* () {
574+
const root = yield* until(mkdtemp(join(tmpdir(), "xmd disposal ")));
575+
yield* ensure(() => rm(root, { recursive: true, force: true }));
576+
const adapters = createEmbeddedAdapters(join(root, "adapters"));
577+
yield* adapters.materialize("claude");
578+
const done = withResolvers<{ error: string | undefined; stdout: string; stderr: string }>();
579+
let observer: ChildProcess | undefined;
580+
yield* ensure(function* () {
581+
if (observer) {
582+
observer.kill();
583+
yield* done.operation;
584+
}
585+
});
586+
observer = execFile(
587+
"node",
588+
[join(FIXTURES, "claude-startup-disposal.mjs"), adapters.executablePath("claude"), root],
589+
{
590+
env: { ...process.env, CLAUDE_CODE_EXECUTABLE: FAKE_CLAUDE },
591+
},
592+
(error, stdout, stderr) => done.resolve({ error: error?.message, stdout, stderr }),
593+
);
594+
const result = yield* done.operation;
595+
expect(result.error).toBeUndefined();
596+
const observation = JSON.parse(result.stdout);
597+
expect(observation.events).toEqual(["dispose-start", "backend-close", "dispose-return"]);
598+
expect(observation.closedWhenDisposeReturned).toBe(true);
599+
expect(observation.outcome).toEqual({ code: 0, signal: null });
600+
expect(observation.helperClosed).toBe(true);
601+
expect(observation.result.status).toBe("refused");
602+
expect(observation.updates).toEqual([]);
603+
expect(observation.userMessages).toBe(0);
604+
expect(observation.remainingSessions).toBe(0);
605+
});
606+
546607
it("HC Claude preserves settings and runs only a fixed internal hook with its Node", function* () {
547608
const adapter = yield* useAdapter("claude", CLAUDE_ENV);
548609
yield* initialize(adapter);
Lines changed: 124 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,124 @@
1+
import { main, ensure, until, sleep, withResolvers } from "effection";
2+
import childProcess from "node:child_process";
3+
import { syncBuiltinESMExports } from "node:module";
4+
import { readTextFile } from "@effectionx/fs";
5+
import { dirname, join } from "node:path";
6+
import { pathToFileURL } from "node:url";
7+
import process from "node:process";
8+
9+
const [entry, root] = process.argv.slice(2);
10+
const log = join(root, "backend.log");
11+
12+
main(function* () {
13+
const updates = [];
14+
const events = [];
15+
let agent;
16+
const nativeSpawn = childProcess.spawn;
17+
const client = {
18+
sessionUpdate(update) {
19+
updates.push(update);
20+
return Promise.resolve();
21+
},
22+
};
23+
const closed = withResolvers();
24+
let child;
25+
let outcome;
26+
const onClose = (code, signal) => {
27+
outcome = { code, signal };
28+
events.push("backend-close");
29+
closed.resolve();
30+
};
31+
yield* ensure(function* () {
32+
try {
33+
if (agent) {
34+
yield* until(agent.dispose());
35+
}
36+
if (child) {
37+
if (outcome === undefined) {
38+
child.kill();
39+
}
40+
yield* closed.operation;
41+
}
42+
} finally {
43+
child?.off("close", onClose);
44+
childProcess.spawn = nativeSpawn;
45+
syncBuiltinESMExports();
46+
}
47+
});
48+
// The SDK custom-spawn seam delivers raw exit events; observe its default launcher unchanged.
49+
childProcess.spawn = (command, args, options) => {
50+
const spawned = nativeSpawn(command, args, options);
51+
if (
52+
command === process.env.CLAUDE_CODE_EXECUTABLE ||
53+
args?.includes(process.env.CLAUDE_CODE_EXECUTABLE)
54+
) {
55+
child = spawned;
56+
child.on("close", onClose);
57+
}
58+
return spawned;
59+
};
60+
syncBuiltinESMExports();
61+
const { ClaudeAcpAgent } = yield* until(
62+
import(pathToFileURL(join(dirname(entry), "lib.js")).href),
63+
);
64+
agent = new ClaudeAcpAgent(client, { log() {}, error() {} });
65+
yield* until(agent.initialize({ protocolVersion: 1, clientCapabilities: {} }));
66+
const opening = agent
67+
.newSession({
68+
cwd: root,
69+
mcpServers: [],
70+
_meta: {
71+
claudeCode: {
72+
options: {
73+
env: {
74+
FAKE_CLAUDE_LOG: log,
75+
FAKE_CLAUDE_CONFIRMATION: "held",
76+
FAKE_CLAUDE_HELD_HELPER: "1",
77+
},
78+
},
79+
},
80+
},
81+
})
82+
.then(
83+
() => ({ status: "returned" }),
84+
(error) => ({ status: "refused", message: error.message }),
85+
);
86+
let ready = false;
87+
while (!ready) {
88+
try {
89+
ready = (yield* readTextFile(log)).includes('"control_request"');
90+
} catch {
91+
// Startup has not created the backend log yet.
92+
}
93+
if (!ready) {
94+
yield* sleep(10);
95+
}
96+
}
97+
events.push("dispose-start");
98+
yield* until(agent.dispose());
99+
events.push("dispose-return");
100+
const closedWhenDisposeReturned = outcome !== undefined;
101+
const result = yield* until(opening);
102+
if (child === undefined) {
103+
throw new Error("the SDK backend spawn was not observed");
104+
}
105+
yield* closed.operation;
106+
const entries = (yield* readTextFile(log))
107+
.trim()
108+
.split("\n")
109+
.map((line) => JSON.parse(line));
110+
console.log(
111+
JSON.stringify({
112+
events,
113+
outcome,
114+
closedWhenDisposeReturned,
115+
result,
116+
updates,
117+
helperClosed: entries.some(
118+
(record) => record.event === "helper-close" && record.code === 0 && record.signal === null,
119+
),
120+
userMessages: entries.filter((record) => record.raw?.type === "user").length,
121+
remainingSessions: Object.keys(agent.sessions).length,
122+
}),
123+
);
124+
});

‎packages/acp/tests/fixtures/fake-claude-cli.cjs‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
*/
1515
const fs = require("node:fs");
1616
const crypto = require("node:crypto");
17+
const { spawn } = require("node:child_process");
1718

1819
const LOG = process.env.FAKE_CLAUDE_LOG;
1920

@@ -57,6 +58,19 @@ emit({
5758
});
5859

5960
const confirmation = process.env.FAKE_CLAUDE_CONFIRMATION ?? "success";
61+
if (confirmation === "held" && process.env.FAKE_CLAUDE_HELD_HELPER === "1") {
62+
let helper;
63+
const onEnd = () => helper.stdin.end();
64+
const onHelperClose = (code, signal) => {
65+
log({ event: "helper-close", code, signal });
66+
helper.off("close", onHelperClose);
67+
process.stdin.off("end", onEnd);
68+
process.exit(0);
69+
};
70+
process.stdin.on("end", onEnd);
71+
helper = spawn(process.execPath, ["-e", "process.stdin.resume()"], { stdio: "pipe" });
72+
helper.on("close", onHelperClose);
73+
}
6074
function confirm() {
6175
if (confirmation === "absent" || confirmation === "held") {
6276
return;

0 commit comments

Comments
 (0)