agent-console 1.3.4: Stop ends the turn at once on ACP, Claude and Codex (#768)

Stop now ends the turn at once, and a resend right after it is safe, on
all three paths:
- ACP (Devin, Cursor, Copilot, OpenCode, Pi, dsh): session/cancel goes as
  a notification, the local turn ends at once, and a resend waits for the
  cancel and the previous prompt to settle.
- Claude: the result FIFO (turnGen, awaitingResult, skipResultGens) lives
  on each CLI process, and a replaced CLI's leftover stdout is ignored.
  After a crash the queue stays open, so the next send resumes with
  --resume.
- Codex: a turn whose turn/start response arrives after Stop is
  interrupted by its own response id.

Run at 0cf12a96 on mote with HOME=$(mktemp -d):
- root bun test: 6171 pass, 0 fail;
- bun scripts/check.mjs agent-console: ok;
- in packages/agent-console: npm ci, npm run check (tsc) and npm run
  build are ok, daemon/dist is byte-identical to the committed one, and
  verify:build is OK;
- npx vitest run: 68 files, 507 passed, 17 skipped.

Broken by hand, then acp-interrupt, claude-cli and codex-interrupt were
run again. Each mutant was red:
- codex: wasCancelled forced false: 1 fail;
- codex: interrupt() no longer ends the local turn: 5 fail;
- acp: pendingCancelSettle not awaited: 1 fail;
- acp: the late prompt settle ends the turn without the activeTurnId
  guard: 1 fail;
- claude: a replaced CLI's stdout no longer ignored: 1 fail;
- claude: interrupt no longer marks its gen in skipResultGens: 2 fail;
- claude: a crash closes the queue instead of setting needsRestart: 2 fail.

Not tried: a real Claude or Codex CLI. The PR says Devin 3000.11.3 was
tried live.
Not blocking: a Codex turn/start response that arrives after
turn/completed sends an extra turn/interrupt and leaves one
staleCodexTurns entry.
This commit is contained in:
qingnian108
2026-11-06 13:49:42 +08:00
committed by GitHub
parent beb6343586
commit 39f5427420
16 changed files with 1311 additions and 122 deletions
+185 -48
View File
@@ -2439,6 +2439,12 @@ var init_cli = __esm({
exited;
/** The answer to initialize (commands, models, account …), null when it failed */
initialized;
/** Monotonic turn gen for THIS process (dies with the CLI). */
turnGen = 0;
/** Turn gens still waiting for a `result` from THIS process (dies with the CLI). */
awaitingResult = [];
/** Gens already ended locally on interrupt; their late `result` must be dropped. */
skipResultGens = /* @__PURE__ */ new Set();
child;
buf = "";
seq = 0;
@@ -2648,7 +2654,14 @@ var init_session = __esm({
}
async pump(cli) {
for await (const m of cli.messages) {
for (const ev of mapSdkMessage(m, this.st, this.o.cwd)) this.emit(ev);
if (this.cli !== cli) continue;
for (const ev of mapSdkMessage(m, this.st, this.o.cwd)) {
if (ev.type === "turn_ended") {
const g = cli.awaitingResult.shift();
if (g != null && cli.skipResultGens.delete(g)) continue;
}
this.emit(ev);
}
}
const exit = await cli.exited;
if (this.closed || this.stopping.has(cli)) return;
@@ -2659,7 +2672,6 @@ var init_session = __esm({
this.turnId = null;
if (this.cli === cli) {
this.needsRestart = true;
this.q.close();
}
}
emit(ev) {
@@ -2673,6 +2685,8 @@ var init_session = __esm({
if (this.needsRestart) await this.restart();
const cli = this.ensureCli();
this.turnNum++;
const gen = ++cli.turnGen;
cli.awaitingResult.push(gen);
this.turnId = "u_" + Date.now().toString(36) + "_" + this.turnNum;
this.st.sawInterrupt = false;
this.emit({
@@ -2826,7 +2840,17 @@ var init_session = __esm({
}
this.pending.clear();
const cli = this.cli;
if (!cli || !cli.alive) return;
const endLocal = () => {
if (this.turnId) {
const gen = cli?.awaitingResult.at(-1);
if (gen != null) cli.skipResultGens.add(gen);
this.emit({ type: "turn_ended", turnId: this.turnId, status: "interrupted" });
}
};
if (!cli || !cli.alive) {
endLocal();
return;
}
try {
await cli.interrupt();
} catch (e) {
@@ -2834,8 +2858,12 @@ var init_session = __esm({
this.stopping.add(cli);
this.needsRestart = true;
void cli.close(500);
if (this.turnId) this.emit({ type: "turn_ended", turnId: this.turnId, status: "interrupted" });
if (this.turnId) {
this.emit({ type: "turn_ended", turnId: this.turnId, status: "interrupted" });
}
return;
}
endLocal();
}
async setModel(model) {
this.o.model = model;
@@ -3853,18 +3881,32 @@ var init_session2 = __esm({
pending = /* @__PURE__ */ new Map();
closed = false;
started = null;
interruptWanted = false;
ourTurnId = null;
// The current turn's turnId in the timeline (generated on send)
/** Codex turn ids whose late started/completed/deltas must be ignored. */
staleCodexTurns = /* @__PURE__ */ new Set();
codexSlash = null;
emit(ev) {
if (ev.type === "turn_ended") {
if (ev.turnId && this.staleCodexTurns.delete(ev.turnId)) return;
if (this.ourTurnId) ev.turnId = this.ourTurnId;
this.ourTurnId = null;
this.st.currentTurnId = null;
this.interruptWanted = false;
if (ev.turnId && this.staleCodexTurns.delete(ev.turnId)) {
if (this.st.currentTurnId === ev.turnId) this.st.currentTurnId = null;
return;
}
if (this.ourTurnId) {
if (!ev.turnId || ev.turnId === this.st.currentTurnId || ev.turnId === this.ourTurnId) {
ev.turnId = this.ourTurnId;
} else {
return;
}
this.ourTurnId = null;
this.st.currentTurnId = null;
} else {
if (ev.turnId) {
this.staleCodexTurns.delete(ev.turnId);
if (this.st.currentTurnId === ev.turnId) this.st.currentTurnId = null;
}
return;
}
}
this.q.push(ev);
}
@@ -3880,8 +3922,18 @@ var init_session2 = __esm({
);
this.rpc = rpc;
rpc.onNotification = (m, p) => {
const turnFromParams = () => {
const turn = p?.turn;
if (typeof turn?.id === "string") return turn.id;
if (typeof p.turnId === "string") return p.turnId;
return null;
};
const tid = turnFromParams();
if (tid && this.staleCodexTurns.has(tid)) {
if (m === "turn/completed") this.staleCodexTurns.delete(tid);
return;
}
for (const ev of mapNotification(m, p, this.st)) this.emit(ev);
if (this.interruptWanted && this.st.currentTurnId) void this.interrupt();
};
rpc.onServerRequest = (m, p) => this.onServerRequest(m, p);
rpc.onExit = () => {
@@ -3945,7 +3997,6 @@ var init_session2 = __esm({
this.codexSlash = entries;
const wireText = expandCodexSlash(input.text, entries);
const { items, warnings } = await buildCodexInput(wireText, input.images ?? []);
this.interruptWanted = false;
const turnId = "u_" + Date.now().toString(36) + "_" + rid3();
if (this.ourTurnId && this.st.currentTurnId) this.staleCodexTurns.add(this.st.currentTurnId);
this.ourTurnId = turnId;
@@ -3959,7 +4010,7 @@ var init_session2 = __esm({
});
for (const w of warnings) this.emit({ type: "notice", level: "warn", message: tr("notice.attachmentIssue", { detail: w }) });
try {
await rpc.request("turn/start", {
const res = await rpc.request("turn/start", {
threadId: this.sessionThreadId ?? void 0,
input: items,
model: this.o.model,
@@ -3967,7 +4018,26 @@ var init_session2 = __esm({
approvalPolicy: preset.approvalPolicy,
sandboxPolicy: preset.sandboxPolicy
});
const codexTurnId = typeof res?.turn?.id === "string" ? res.turn.id : null;
if (!codexTurnId) return;
const wasCancelled = this.ourTurnId !== turnId;
if (wasCancelled) {
this.staleCodexTurns.add(codexTurnId);
try {
await rpc.request(
"turn/interrupt",
{ threadId: this.threadId(), turnId: codexTurnId },
5e3
);
} catch (e) {
const msg = String(e?.message ?? e);
if (!/idle|not running|no.*turn/i.test(msg)) log("warn", "codex interrupt \u5931\u8D25", { err: msg });
}
return;
}
this.st.currentTurnId = codexTurnId;
} catch (e) {
if (this.ourTurnId !== turnId) return;
this.emit({
type: "turn_ended",
turnId,
@@ -3993,24 +4063,30 @@ var init_session2 = __esm({
async interrupt() {
for (const [, p] of this.pending) p.resolve({ cancelled: true });
this.pending.clear();
if (!this.rpc) return;
if (!this.st.currentTurnId) {
this.interruptWanted = true;
const localTurn = this.ourTurnId;
const codexTurn = this.st.currentTurnId;
if (!this.rpc) {
if (localTurn) this.emit({ type: "turn_ended", turnId: localTurn, status: "interrupted" });
return;
}
this.interruptWanted = false;
try {
await this.rpc.request(
"turn/interrupt",
{ threadId: this.threadId(), turnId: this.st.currentTurnId },
5e3
);
} catch (e) {
const msg = String(e?.message ?? e);
if (!/idle|not running|no.*turn/i.test(msg)) {
log("warn", "codex interrupt \u5931\u8D25", { err: msg });
if (codexTurn) {
this.staleCodexTurns.add(codexTurn);
try {
await this.rpc.request(
"turn/interrupt",
{ threadId: this.threadId(), turnId: codexTurn },
5e3
);
} catch (e) {
const msg = String(e?.message ?? e);
if (!/idle|not running|no.*turn/i.test(msg)) {
log("warn", "codex interrupt \u5931\u8D25", { err: msg });
}
}
}
if (localTurn && this.ourTurnId === localTurn) {
this.emit({ type: "turn_ended", turnId: localTurn, status: "interrupted" });
}
}
threadId() {
return this.sessionThreadId ?? void 0;
@@ -4777,6 +4853,11 @@ var init_session3 = __esm({
turnId = null;
turnNum = 0;
running = false;
/** Current wire session/prompt settle (never rejects) — interrupt waits for it before the next prompt. */
inFlightPrompt = null;
/** After Stop: notify(cancel) + previous prompt settle + one macrotask, so pumpUpdates drains before next prompt(). */
pendingCancelSettle = null;
closeWaiters = [];
permPending = /* @__PURE__ */ new Map();
mapCtx = newMapCtx();
modelConfigId = null;
@@ -5058,12 +5139,12 @@ var init_session3 = __esm({
await this.ready();
if (this.running) throw new Error("\u5F53\u524D\u8F6E\u6B21\u5C1A\u672A\u7ED3\u675F");
this.turnNum++;
this.turnId = "u_" + Date.now().toString(36) + "_" + this.turnNum;
this.mapCtx = newMapCtx();
const turnId = "u_" + Date.now().toString(36) + "_" + this.turnNum;
this.turnId = turnId;
this.running = true;
this.q.push({
type: "turn_started",
turnId: this.turnId,
turnId,
model: this.o.model,
mode: this.o.mode,
effort: this.o.effort
@@ -5072,10 +5153,11 @@ var init_session3 = __esm({
const attachments = input.images ?? [];
if (!text && !attachments.length) {
this.running = false;
this.q.push({ type: "turn_ended", turnId: this.turnId, status: "completed" });
this.q.push({ type: "turn_ended", turnId, status: "completed" });
return;
}
const built = await buildAcpPrompt(text, attachments, this.promptCaps, input.mentions ?? []);
if (this.closed || !this.running || this.turnId !== turnId) return;
const agent = this.o.providerName ?? this.o.binName;
if (built.imagesByPath.length && !this.promptCaps.image) {
const switched = this.o.imagesFollowStartModel && this.initCaps.image && this.o.model !== this.startModel;
@@ -5083,19 +5165,65 @@ var init_session3 = __esm({
}
for (const w of built.warnings) this.q.push({ type: "notice", level: "warn", message: tr("notice.attachmentIssue", { detail: w }) });
if (!built.blocks.length) {
this.running = false;
this.q.push({ type: "turn_ended", turnId: this.turnId, status: "completed" });
if (this.turnId === turnId && this.running) {
this.running = false;
this.q.push({ type: "turn_ended", turnId, status: "completed" });
}
return;
}
void this.runTurn(built.blocks);
void this.runTurn(turnId, built.blocks);
}
// Send this turn's prompt; reading updates is the job of the persistent pumpUpdates() (following Paseo: session/update is handled at session level)
async runTurn(prompt) {
this.activeTurnId = this.turnId;
waitCloseOrTimeout(ms) {
if (this.closed) return Promise.resolve();
return new Promise((resolve4) => {
const t = setTimeout(() => {
this.closeWaiters = this.closeWaiters.filter((w) => w !== done);
resolve4();
}, ms);
const done = () => {
clearTimeout(t);
resolve4();
};
this.closeWaiters.push(done);
});
}
// Send this turn's prompt; session/update still flows through pumpUpdates, but ending the turn is tied
// to this prompt() promise so a JSON-RPC error on a cancelled prompt cannot leave a leftover counter.
// After Stop, wait for pendingCancelSettle before activating Turn N+1 on the wire (Devin cancels an
// overlapping session/prompt that arrives while the previous one is still unwinding).
async runTurn(turnId, prompt) {
const pending = this.pendingCancelSettle;
if (pending) {
await Promise.race([pending, this.waitCloseOrTimeout(2e3)]);
if (this.pendingCancelSettle === pending) this.pendingCancelSettle = null;
if (this.closed || !this.running || this.turnId !== turnId) return;
}
this.mapCtx = newMapCtx();
this.activeTurnId = turnId;
this.wakePump?.();
this.wakePump = null;
this.active.prompt(prompt).catch(() => {
const req = this.active.prompt(prompt);
const settle = req.then(() => {
}, () => {
});
this.inFlightPrompt = settle;
try {
const res = await req;
if (this.activeTurnId === turnId) {
this.endTurn(stopToTurnEnd(res.stopReason, turnId));
}
} catch (e) {
if (this.activeTurnId === turnId) {
this.endTurn({
type: "turn_ended",
turnId,
status: "failed",
error: String(e?.message ?? e)
});
}
} finally {
if (this.inFlightPrompt === settle) this.inFlightPrompt = null;
}
}
endTurn(ev) {
for (const id2 of [...this.permPending.keys()]) this.cancelPerm(id2);
@@ -5117,10 +5245,6 @@ var init_session3 = __esm({
msg = await session.nextUpdate();
} catch (e) {
if (this.closed) return;
const turnId = this.activeTurnId;
if (turnId) {
this.endTurn({ type: "turn_ended", turnId, status: "failed", error: String(e?.message ?? e) });
}
await new Promise((r) => this.wakePump = r);
continue;
}
@@ -5132,19 +5256,30 @@ var init_session3 = __esm({
}
if (!this.activeTurnId) continue;
for (const ev of mapSessionUpdate(u, this.mapCtx)) this.q.push(ev);
} else if (this.activeTurnId) {
this.endTurn(stopToTurnEnd(msg.stopReason, this.activeTurnId));
} else {
continue;
}
}
}
async interrupt() {
await this.ready();
if (!this.ctx || !this.active) return;
try {
await this.ctx.request(methods2.agent.session.cancel, { sessionId: this.active.sessionId });
} catch (e) {
const notifyP = this.ctx.notify(methods2.agent.session.cancel, { sessionId: this.active.sessionId }).catch((e) => {
log("info", `ACP cancel: ${String(e)}`);
});
const prevSettle = this.inFlightPrompt ?? Promise.resolve();
this.pendingCancelSettle = Promise.all([notifyP, prevSettle]).then(
() => new Promise((r) => setTimeout(r, 0))
);
if (this.running) {
const turnId = this.activeTurnId ?? this.turnId;
if (turnId) {
this.endTurn({ type: "turn_ended", turnId, status: "interrupted" });
} else {
this.running = false;
}
}
await notifyP;
}
async setModel(model) {
this.o.model = model;
@@ -5177,6 +5312,7 @@ var init_session3 = __esm({
}
async close() {
this.closed = true;
for (const w of this.closeWaiters.splice(0)) w();
this.wakePump?.();
this.settleCommands();
for (const r of this.permPending.values()) r({ cancelled: true });
@@ -9066,7 +9202,8 @@ var AgentManager = class {
await this.setStatus(threadId, "running");
try {
const images = await this.resolveAttachments(attachmentRefs);
await rt.session.send({ text: withMentions(text, mentions), images, mentions });
const payload = { text: withMentions(text, mentions), images, mentions };
await rt.session.send(payload);
} catch (e) {
const msg = String(e?.message ?? e);
await this.appendRaw(threadId, { type: "notice", level: "error", message: tr("notice.sendFailed", { detail: msg }) });
File diff suppressed because one or more lines are too long
@@ -347,7 +347,10 @@ export class AgentManager {
await this.setStatus(threadId, "running");
try {
const images = await this.resolveAttachments(attachmentRefs);
await rt.session!.send({ text: withMentions(text, mentions), images, mentions });
const payload = { text: withMentions(text, mentions), images, mentions };
// No string-matching retry for 当前轮次尚未结束: ACP/Claude/Codex now clear the in-flight turn on
// interrupt (and ACP ties discard to each prompt() promise), so the guard should not fire after Stop.
await rt.session!.send(payload);
} catch (e) {
// A failed send must not leave the conversation running
const msg = String((e as Error)?.message ?? e);
@@ -63,6 +63,11 @@ export class AcpSession implements ProviderSession {
private turnId: string | null = null;
private turnNum = 0;
private running = false;
/** Current wire session/prompt settle (never rejects) — interrupt waits for it before the next prompt. */
private inFlightPrompt: Promise<void> | null = null;
/** After Stop: notify(cancel) + previous prompt settle + one macrotask, so pumpUpdates drains before next prompt(). */
private pendingCancelSettle: Promise<void> | null = null;
private closeWaiters: Array<() => void> = [];
private permPending = new Map<string, (a: RespondAnswer) => void>();
private mapCtx: MapCtx = newMapCtx();
private modelConfigId: string | null = null;
@@ -392,12 +397,12 @@ export class AcpSession implements ProviderSession {
await this.ready();
if (this.running) throw new Error("当前轮次尚未结束");
this.turnNum++;
this.turnId = "u_" + Date.now().toString(36) + "_" + this.turnNum;
this.mapCtx = newMapCtx();
const turnId = "u_" + Date.now().toString(36) + "_" + this.turnNum;
this.turnId = turnId;
this.running = true;
this.q.push({
type: "turn_started",
turnId: this.turnId,
turnId,
model: this.o.model,
mode: this.o.mode,
effort: this.o.effort,
@@ -406,11 +411,13 @@ export class AcpSession implements ProviderSession {
const attachments = input.images ?? [];
if (!text && !attachments.length) {
this.running = false;
this.q.push({ type: "turn_ended", turnId: this.turnId, status: "completed" });
this.q.push({ type: "turn_ended", turnId, status: "completed" });
return;
}
// An image-only message is still a prompt: images go as image blocks when the Agent takes them, else by file path
const built = await buildAcpPrompt(text, attachments, this.promptCaps, input.mentions ?? []);
// Interrupt during buildAcpPrompt: that turn already ended locally — do not start a wire prompt for it
if (this.closed || !this.running || this.turnId !== turnId) return;
const agent = this.o.providerName ?? this.o.binName;
if (built.imagesByPath.length && !this.promptCaps.image) {
const switched = this.o.imagesFollowStartModel && this.initCaps.image && this.o.model !== this.startModel;
@@ -419,21 +426,69 @@ export class AcpSession implements ProviderSession {
for (const w of built.warnings) this.q.push({ type: "notice", level: "warn", message: tr("notice.attachmentIssue", { detail: w }) });
if (!built.blocks.length) {
// Every attachment failed to resolve and there was no text: nothing to send
this.running = false;
this.q.push({ type: "turn_ended", turnId: this.turnId, status: "completed" });
if (this.turnId === turnId && this.running) {
this.running = false;
this.q.push({ type: "turn_ended", turnId, status: "completed" });
}
return;
}
void this.runTurn(built.blocks);
void this.runTurn(turnId, built.blocks);
}
// Send this turn's prompt; reading updates is the job of the persistent pumpUpdates() (following Paseo: session/update is handled at session level)
private async runTurn(prompt: Parameters<ActiveSession["prompt"]>[0]): Promise<void> {
this.activeTurnId = this.turnId;
private waitCloseOrTimeout(ms: number): Promise<void> {
if (this.closed) return Promise.resolve();
return new Promise((resolve) => {
const t = setTimeout(() => {
this.closeWaiters = this.closeWaiters.filter((w) => w !== done);
resolve();
}, ms);
const done = () => {
clearTimeout(t);
resolve();
};
this.closeWaiters.push(done);
});
}
// Send this turn's prompt; session/update still flows through pumpUpdates, but ending the turn is tied
// to this prompt() promise so a JSON-RPC error on a cancelled prompt cannot leave a leftover counter.
// After Stop, wait for pendingCancelSettle before activating Turn N+1 on the wire (Devin cancels an
// overlapping session/prompt that arrives while the previous one is still unwinding).
private async runTurn(turnId: string, prompt: Parameters<ActiveSession["prompt"]>[0]): Promise<void> {
const pending = this.pendingCancelSettle;
if (pending) {
await Promise.race([pending, this.waitCloseOrTimeout(2000)]);
if (this.pendingCancelSettle === pending) this.pendingCancelSettle = null;
if (this.closed || !this.running || this.turnId !== turnId) return;
}
this.mapCtx = newMapCtx();
this.activeTurnId = turnId;
this.wakePump?.();
this.wakePump = null;
this.active!.prompt(prompt).catch(() => {
/* failures surface through nextUpdate() and pumpUpdates ends the turn */
});
const req = this.active!.prompt(prompt);
// Never-reject settle so interrupt can await the wire round-trip without try/catch
const settle = req.then(() => {}, () => {});
this.inFlightPrompt = settle;
try {
const res = await req;
// prompt() also enqueues a stop for nextUpdate(); pumpUpdates drains it without ending.
// interrupt() already called endTurn (clears activeTurnId), so a late settle is a no-op.
// activeTurnId === turnId alone is enough (running is cleared together with activeTurnId).
if (this.activeTurnId === turnId) {
this.endTurn(stopToTurnEnd(res.stopReason, turnId));
}
} catch (e) {
if (this.activeTurnId === turnId) {
this.endTurn({
type: "turn_ended",
turnId,
status: "failed",
error: String((e as Error)?.message ?? e),
});
}
} finally {
if (this.inFlightPrompt === settle) this.inFlightPrompt = null;
}
}
private endTurn(ev: ProviderEvent): void {
@@ -460,11 +515,8 @@ export class AcpSession implements ProviderSession {
msg = await session.nextUpdate();
} catch (e) {
if (this.closed) return;
const turnId = this.activeTurnId;
if (turnId) {
this.endTurn({ type: "turn_ended", turnId, status: "failed", error: String((e as Error)?.message ?? e) });
}
// After an error the queue keeps throwing the same error until the next prompt clears it: wait for the next turn before reading again
// Prompt JSON-RPC errors reject the update queue; runTurn's catch ends/discards that turn.
// clearErrors() runs on the next prompt(); wait until then before reading again.
await new Promise<void>((r) => (this.wakePump = r));
continue;
}
@@ -476,8 +528,9 @@ export class AcpSession implements ProviderSession {
}
if (!this.activeTurnId) continue; // Other updates outside a turn (e.g. mode change echoes) don't go to the timeline
for (const ev of mapSessionUpdate(u, this.mapCtx)) this.q.push(ev);
} else if (this.activeTurnId) {
this.endTurn(stopToTurnEnd(msg.stopReason, this.activeTurnId));
} else {
// kind === "stop": turn ending is owned by runTurn's prompt() promise. Drain only.
continue;
}
}
}
@@ -485,11 +538,30 @@ export class AcpSession implements ProviderSession {
async interrupt(): Promise<void> {
await this.ready();
if (!this.ctx || !this.active) return;
try {
await this.ctx.request(methods.agent.session.cancel, { sessionId: this.active.sessionId });
} catch (e) {
log("info", `ACP cancel: ${String(e)}`);
// Queue session/cancel on the wire FIRST so a consumer that reacts to turn_ended (0ms resend) cannot
// beat cancel onto the wire. ACP cancel is a CancelNotification (Devin only registers that form).
const notifyP = this.ctx
.notify(methods.agent.session.cancel, { sessionId: this.active.sessionId })
.catch((e) => {
log("info", `ACP cancel: ${String(e)}`);
});
const prevSettle = this.inFlightPrompt ?? Promise.resolve();
// After cancel + previous prompt settle, one macrotask lets pumpUpdates drain stop / park on wakePump
// before the next active.prompt() calls updates.clearErrors().
this.pendingCancelSettle = Promise.all([notifyP, prevSettle]).then(
() => new Promise<void>((r) => setTimeout(r, 0)),
);
// End the local turn so `running` clears immediately (UI idle; send() must not throw 当前轮次尚未结束).
// Clearing activeTurnId/running is enough for runTurn's late settle to no-op (no cancelledPromptGens set).
if (this.running) {
const turnId = this.activeTurnId ?? this.turnId;
if (turnId) {
this.endTurn({ type: "turn_ended", turnId, status: "interrupted" });
} else {
this.running = false;
}
}
await notifyP;
}
async setModel(model: string | null): Promise<void> {
@@ -529,6 +601,7 @@ export class AcpSession implements ProviderSession {
async close(): Promise<void> {
this.closed = true;
for (const w of this.closeWaiters.splice(0)) w();
this.wakePump?.();
this.settleCommands();
for (const r of this.permPending.values()) r({ cancelled: true });
@@ -73,6 +73,12 @@ export class ClaudeCli {
readonly exited: Promise<{ code: number | null; signal: NodeJS.Signals | null }>;
/** The answer to initialize (commands, models, account …), null when it failed */
readonly initialized: Promise<Json | null>;
/** Monotonic turn gen for THIS process (dies with the CLI). */
turnGen = 0;
/** Turn gens still waiting for a `result` from THIS process (dies with the CLI). */
awaitingResult: number[] = [];
/** Gens already ended locally on interrupt; their late `result` must be dropped. */
skipResultGens = new Set<number>();
private child: ChildProcess;
private buf = "";
private seq = 0;
@@ -61,6 +61,7 @@ export class ClaudeSession implements ProviderSession {
// The CLI is only started before the first send (or a command list request)
private ensureCli(): ClaudeCli {
if (this.cli && !this.needsRestart) return this.cli;
// New ClaudeCli carries its own empty turnGen / awaitingResult / skipResultGens
this.st = newMapState();
const effort = this.o.effort && EFFORTS.includes(this.o.effort) ? this.o.effort : null;
const cli = new ClaudeCli(
@@ -85,7 +86,17 @@ export class ClaudeSession implements ProviderSession {
private async pump(cli: ClaudeCli): Promise<void> {
for await (const m of cli.messages) {
for (const ev of mapSdkMessage(m, this.st, this.o.cwd)) this.emit(ev);
// Replaced CLI: ignore leftover stdout so it cannot emit into this session or shift a newer CLI's FIFO
if (this.cli !== cli) continue;
for (const ev of mapSdkMessage(m, this.st, this.o.cwd)) {
if (ev.type === "turn_ended") {
// Drop by this CLI's FIFO of results owed — not by interrupt status (send() resets sawInterrupt,
// and the real Claude CLI ends cancelled turns with subtype error_during_execution → failed).
const g = cli.awaitingResult.shift();
if (g != null && cli.skipResultGens.delete(g)) continue;
}
this.emit(ev);
}
}
const exit = await cli.exited;
// A CLI this session stopped on purpose (restart / close) is not a crash
@@ -97,10 +108,10 @@ export class ClaudeSession implements ProviderSession {
this.emit({ type: "notice", level: "error", message: tail ? `${detail} — stderr: ${tail}` : detail });
if (this.turnId) this.emit({ type: "turn_ended", turnId: this.turnId, status: "failed", error: detail });
this.turnId = null;
// The event stream ended: an old CLI that restart() replaced must not close the event queue
// Keep the event queue open on crash so the next send can restart with --resume (FIFO lived on this dead CLI).
// Intentionally not this.q.close(): closing would end manager.pumpEvents and mark the thread closed.
if (this.cli === cli) {
this.needsRestart = true; // Rebuild with --resume on the next send
this.q.close();
this.needsRestart = true;
}
}
@@ -116,6 +127,8 @@ export class ClaudeSession implements ProviderSession {
if (this.needsRestart) await this.restart();
const cli = this.ensureCli();
this.turnNum++;
const gen = ++cli.turnGen;
cli.awaitingResult.push(gen);
this.turnId = "u_" + Date.now().toString(36) + "_" + this.turnNum;
this.st.sawInterrupt = false; // A new turn clears the old interrupt flag
this.emit({
@@ -279,17 +292,36 @@ export class ClaudeSession implements ProviderSession {
}
this.pending.clear();
const cli = this.cli;
if (!cli || !cli.alive) return;
const endLocal = () => {
// End immediately so manager/UI clear running even if the CLI is slow to emit result
// (same class of bug as ACP: idle UI while provider.turn still open → next send races).
if (this.turnId) {
// Mark the latest owed gen on this CLI so its late result is dropped (FIFO order).
// Do not look at status/sawInterrupt (send() clears the flag).
const gen = cli?.awaitingResult.at(-1);
if (gen != null) cli!.skipResultGens.add(gen);
this.emit({ type: "turn_ended", turnId: this.turnId, status: "interrupted" });
}
};
if (!cli || !cli.alive) {
endLocal();
return;
}
try {
await cli.interrupt();
} catch (e) {
// No answer: stop this CLI; the next send starts it again with --resume
// No answer: stop this CLI; the next send starts it again with --resume.
// FIFO lived on this CLI — abandoning it is enough; do not touch a newer CLI's gens.
log("warn", "claude interrupt failed", { err: String(e) });
this.stopping.add(cli);
this.needsRestart = true;
void cli.close(500);
if (this.turnId) this.emit({ type: "turn_ended", turnId: this.turnId, status: "interrupted" });
if (this.turnId) {
this.emit({ type: "turn_ended", turnId: this.turnId, status: "interrupted" });
}
return;
}
endLocal();
}
async setModel(model: string | null): Promise<void> {
@@ -43,8 +43,8 @@ export class CodexSession implements ProviderSession {
private pending = new Map<string, PendingReq>();
private closed = false;
private started: Promise<void> | null = null;
private interruptWanted = false;
private ourTurnId: string | null = null; // The current turn's turnId in the timeline (generated on send)
/** Codex turn ids whose late started/completed/deltas must be ignored. */
private staleCodexTurns = new Set<string>();
private codexSlash: CodexSlashEntry[] | null = null;
@@ -69,14 +69,31 @@ export class CodexSession implements ProviderSession {
private emit(ev: ProviderEvent): void {
if (ev.type === "turn_ended") {
// A late completion for the previous turn (already ended by the interrupt fallback): drop it so it doesn't end the new turn
if (ev.turnId && this.staleCodexTurns.delete(ev.turnId)) return;
// turn_started uses our own turnId, so the end must use the same one,
// otherwise the manager's per-turn dedupe breaks (interrupt fallback + late completion would end the next turn)
if (this.ourTurnId) ev.turnId = this.ourTurnId;
this.ourTurnId = null;
this.st.currentTurnId = null;
this.interruptWanted = false;
// Late completion for a turn we already interrupted (or superseded): drop it
if (ev.turnId && this.staleCodexTurns.delete(ev.turnId)) {
if (this.st.currentTurnId === ev.turnId) this.st.currentTurnId = null;
return;
}
// Remap Codex turn id → our timeline turnId only when it is the active turn.
// If ourTurnId was already cleared (interrupted) or belongs to another turn, do not emit a
// stray turn_ended under the raw codex-turn-* id (yetone's probe: turn_ended codex-turn-2).
if (this.ourTurnId) {
if (!ev.turnId || ev.turnId === this.st.currentTurnId || ev.turnId === this.ourTurnId) {
ev.turnId = this.ourTurnId;
} else {
// Completion for some other Codex turn while we have an active local turn — ignore
return;
}
this.ourTurnId = null;
this.st.currentTurnId = null;
} else {
// No active local turn — drop provider completions (already ended locally or spurious)
if (ev.turnId) {
this.staleCodexTurns.delete(ev.turnId);
if (this.st.currentTurnId === ev.turnId) this.st.currentTurnId = null;
}
return;
}
}
this.q.push(ev);
}
@@ -93,8 +110,19 @@ export class CodexSession implements ProviderSession {
);
this.rpc = rpc;
rpc.onNotification = (m, p) => {
const turnFromParams = (): string | null => {
const turn = (p as { turn?: { id?: string } })?.turn;
if (typeof turn?.id === "string") return turn.id;
if (typeof (p as { turnId?: string }).turnId === "string") return (p as { turnId: string }).turnId;
return null;
};
const tid = turnFromParams();
// Any notification for a stale Codex turn (started / completed / deltas if tagged) is ignored
if (tid && this.staleCodexTurns.has(tid)) {
if (m === "turn/completed") this.staleCodexTurns.delete(tid);
return;
}
for (const ev of mapNotification(m, p, this.st)) this.emit(ev);
if (this.interruptWanted && this.st.currentTurnId) void this.interrupt();
};
rpc.onServerRequest = (m, p) => this.onServerRequest(m, p);
rpc.onExit = () => {
@@ -158,12 +186,11 @@ export class CodexSession implements ProviderSession {
this.codexSlash = entries;
const wireText = expandCodexSlash(input.text, entries);
const { items, warnings } = await buildCodexInput(wireText, input.images ?? []);
this.interruptWanted = false;
const turnId = "u_" + Date.now().toString(36) + "_" + rid();
// A new turn started before the previous one completed (interrupt fallback) → remember its Codex turnId
// A new turn started before the previous one completed → mark previous Codex id stale
if (this.ourTurnId && this.st.currentTurnId) this.staleCodexTurns.add(this.st.currentTurnId);
this.ourTurnId = turnId;
this.st.currentTurnId = null; // Filled in by this turn's turn/started, so we never interrupt/steer with the previous turn's id
this.st.currentTurnId = null; // Filled from THIS turn's turn/start response only
this.emit({
type: "turn_started",
turnId,
@@ -173,15 +200,38 @@ export class CodexSession implements ProviderSession {
});
for (const w of warnings) this.emit({ type: "notice", level: "warn", message: tr("notice.attachmentIssue", { detail: w }) });
try {
await rpc.request("turn/start", {
const res = (await rpc.request("turn/start", {
threadId: this.sessionThreadId ?? undefined,
input: items,
model: this.o.model,
effort: this.o.effort,
approvalPolicy: preset.approvalPolicy,
sandboxPolicy: preset.sandboxPolicy,
});
})) as { turn?: { id?: string } };
const codexTurnId = typeof res?.turn?.id === "string" ? res.turn.id : null;
if (!codexTurnId) return;
// If Stop ran while turn/start was in flight, interrupt() already ended locally and cleared
// ourTurnId (or a newer send replaced it). Either way ourTurnId !== turnId — no separate
// cancelled-turns set is needed (each half of the old OR was redundant with the other).
const wasCancelled = this.ourTurnId !== turnId;
if (wasCancelled) {
this.staleCodexTurns.add(codexTurnId);
try {
await rpc.request(
"turn/interrupt",
{ threadId: this.threadId(), turnId: codexTurnId },
5000,
);
} catch (e) {
const msg = String((e as Error)?.message ?? e);
if (!/idle|not running|no.*turn/i.test(msg)) log("warn", "codex interrupt 失败", { err: msg });
}
return;
}
this.st.currentTurnId = codexTurnId;
} catch (e) {
// turn/start failed after a local interrupt/supersede: do not emit a second turn_ended
if (this.ourTurnId !== turnId) return;
this.emit({
type: "turn_ended",
turnId,
@@ -210,26 +260,35 @@ export class CodexSession implements ProviderSession {
async interrupt(): Promise<void> {
for (const [, p] of this.pending) p.resolve({ cancelled: true });
this.pending.clear();
if (!this.rpc) return;
if (!this.st.currentTurnId) {
// turn/started hasn't arrived yet: remember it and send the interrupt as soon as the turnId is known
this.interruptWanted = true;
const localTurn = this.ourTurnId;
const codexTurn = this.st.currentTurnId;
if (!this.rpc) {
if (localTurn) this.emit({ type: "turn_ended", turnId: localTurn, status: "interrupted" });
return;
}
this.interruptWanted = false;
try {
await this.rpc.request(
"turn/interrupt",
{ threadId: this.threadId(), turnId: this.st.currentTurnId },
5000,
);
} catch (e) {
// "Already idle"-type errors count as success
const msg = String((e as Error)?.message ?? e);
if (!/idle|not running|no.*turn/i.test(msg)) {
log("warn", "codex interrupt 失败", { err: msg });
// No codexTurn yet (turn/start still in flight): end locally below so ourTurnId clears;
// the in-flight turn/start response handler then sees ourTurnId !== turnId and interrupts.
if (codexTurn) {
this.staleCodexTurns.add(codexTurn);
try {
await this.rpc.request(
"turn/interrupt",
{ threadId: this.threadId(), turnId: codexTurn },
5000,
);
} catch (e) {
// "Already idle"-type errors count as success
const msg = String((e as Error)?.message ?? e);
if (!/idle|not running|no.*turn/i.test(msg)) {
log("warn", "codex interrupt 失败", { err: msg });
}
}
}
// End the local turn immediately (Devin/ACP-class): manager 1s fallback alone left UI idle while
// ourTurnId stayed set, so a quick next send raced a late turn/completed onto the new turn.
if (localTurn && this.ourTurnId === localTurn) {
this.emit({ type: "turn_ended", turnId: localTurn, status: "interrupted" });
}
}
private threadId(): string | undefined {
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "@magpie-community/page-agent-console",
"version": "1.3.3",
"version": "1.3.4",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@magpie-community/page-agent-console",
"version": "1.3.3",
"version": "1.3.4",
"license": "MIT",
"dependencies": {
"@agentclientprotocol/sdk": "2.1.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/page-agent-console",
"version": "1.3.3",
"version": "1.3.4",
"description": "在 magpie 窗口里加一个「Agent 控制台」页面:用常驻本地服务驱动本机的 Agent CLI(Claude Code、Codex、Cursor 等),带结构化时间线。A Magpie page that drives local Agent CLIs (Claude Code, Codex, Cursor, and others) with a persistent local daemon and a structured timeline.",
"author": "qingnian108 (https://github.com/qingnian108)",
"homepage": "https://github.com/qingnian108/magpie-agent-console",
@@ -0,0 +1,180 @@
// ACP session/cancel must be a notification. Devin CLI only registers CancelNotification; a request got
// -32601 Method not found, running stayed true, and the next send failed with 当前轮次尚未结束 after Stop.
import { afterAll, afterEach, beforeAll, describe, expect, it } from "vitest";
import { existsSync, mkdtempSync, readFileSync, rmSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { createAcpProvider } from "../../daemon/src/providers/acp/provider.js";
import type { ProviderSession } from "../../daemon/src/providers/types.js";
import type { ProviderEvent } from "../../daemon/src/timeline/types.js";
const fixture = resolve(__dirname, "fixtures", "fake-acp-agent.mjs");
const launch = { cmd: process.execPath, prefixArgs: [fixture] };
let dir: string;
beforeAll(() => {
dir = mkdtempSync(join(tmpdir(), "acp-interrupt-"));
});
afterAll(() => rmSync(dir, { recursive: true, force: true }));
afterEach(() => {
delete process.env.FAKE_ACP_CANCEL_LOG;
delete process.env.FAKE_ACP_SLOW_MS;
delete process.env.FAKE_ACP_IGNORE_CANCEL;
delete process.env.FAKE_ACP_CANCEL_AS_ERROR;
delete process.env.FAKE_ACP_CANCEL_SETTLE_MS;
});
type Run = { session: ProviderSession; events: ProviderEvent[]; clog: string; done: Promise<void> };
async function open(opts: { slowMs?: number; ignoreCancel?: boolean; cancelAsError?: boolean; cancelSettleMs?: number } = {}): Promise<Run> {
const clog = join(dir, `c-${Math.random().toString(36).slice(2)}.jsonl`);
process.env.FAKE_ACP_CANCEL_LOG = clog;
if (opts.slowMs != null) process.env.FAKE_ACP_SLOW_MS = String(opts.slowMs);
else delete process.env.FAKE_ACP_SLOW_MS;
if (opts.ignoreCancel) process.env.FAKE_ACP_IGNORE_CANCEL = "1";
else delete process.env.FAKE_ACP_IGNORE_CANCEL;
if (opts.cancelAsError) process.env.FAKE_ACP_CANCEL_AS_ERROR = "1";
else delete process.env.FAKE_ACP_CANCEL_AS_ERROR;
if (opts.cancelSettleMs != null) process.env.FAKE_ACP_CANCEL_SETTLE_MS = String(opts.cancelSettleMs);
else delete process.env.FAKE_ACP_CANCEL_SETTLE_MS;
const provider = createAcpProvider({ id: "fake-interrupt", name: "Fake ACP", binName: "fake-acp", acpArgs: [], installHint: "" });
const session = await provider.createSession({
threadId: "t1", cwd: dir, model: null, mode: "default", effort: null, resumeId: null, launch,
});
const events: ProviderEvent[] = [];
const done = (async () => {
for await (const ev of session.events) events.push(ev);
})();
return { session, events, clog, done };
}
async function until(check: () => boolean, ms = 10000) {
const end = Date.now() + ms;
while (!check()) {
if (Date.now() > end) throw new Error("timed out");
await new Promise((r) => setTimeout(r, 20));
}
}
const cancels = (clog: string) =>
existsSync(clog) ? readFileSync(clog, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)) : [];
describe("ACP interrupt / session/cancel", () => {
it("interrupt sends session/cancel as a notification (no JSON-RPC id), not a request", async () => {
const r = await open({ slowMs: 5000 });
try {
await r.session.send({ text: "slow", images: [] });
await until(() => r.events.some((e) => e.type === "turn_started"));
await r.session.interrupt();
await until(() => cancels(r.clog).length >= 1);
expect(cancels(r.clog)[0]).toMatchObject({ notification: true, hasId: false });
await until(() => r.events.some((e) => e.type === "turn_ended"));
const end = r.events.find((e) => e.type === "turn_ended") as { status?: string };
expect(end.status).toBe("interrupted");
} finally {
await r.session.close();
await r.done;
}
}, 20000);
it("after interrupt, send() is allowed again even when the agent ignores cancel (running cleared)", async () => {
const r = await open({ slowMs: 8000, ignoreCancel: true });
try {
await r.session.send({ text: "first", images: [] });
await until(() => r.events.some((e) => e.type === "turn_started"));
await r.session.interrupt();
await until(() => r.events.some((e) => e.type === "turn_ended" && (e as { status?: string }).status === "interrupted"));
// Must not throw 当前轮次尚未结束 — the local running flag was cleared on interrupt
await expect(r.session.send({ text: "second", images: [] })).resolves.toBeUndefined();
await until(() => r.events.filter((e) => e.type === "turn_started").length >= 2);
expect(r.events.filter((e) => e.type === "turn_started")).toHaveLength(2);
// No failed turn claiming 当前轮次尚未结束
const failed = r.events.filter((e) => e.type === "turn_ended" && (e as { status?: string }).status === "failed");
expect(failed.map((e) => (e as { error?: string }).error ?? "")).not.toEqual(
expect.arrayContaining([expect.stringContaining("当前轮次尚未结束")]),
);
} finally {
await r.session.close();
await r.done;
}
}, 20000);
it("a late stopReason from the cancelled prompt does not end the next turn", async () => {
// Agent will eventually end the ignored-cancel prompt; that stop must be discarded
const r = await open({ slowMs: 300, ignoreCancel: true });
try {
await r.session.send({ text: "first", images: [] });
await until(() => r.events.some((e) => e.type === "turn_started"));
await r.session.interrupt();
await until(() => r.events.some((e) => e.type === "turn_ended"));
await r.session.send({ text: "second", images: [] });
await until(() => r.events.filter((e) => e.type === "turn_started").length >= 2);
// Wait past the first prompt's slow timeout so its stopReason arrives
await new Promise((r) => setTimeout(r, 500));
// Second turn should still be running (or complete on its own later) — not closed by the stale stop
const ends = r.events.filter((e) => e.type === "turn_ended") as { status?: string; turnId?: string }[];
// Only the interrupt end so far (second turn's prompt still open until its own 300ms, which may have fired)
// Accept either: second still open, or second completed with end_turn — never a spurious double-interrupt.
expect(ends[0]?.status).toBe("interrupted");
expect(ends.filter((e) => e.status === "interrupted")).toHaveLength(1);
} finally {
await r.session.close();
await r.done;
}
}, 20000);
it("cancel answered with JSON-RPC error (-32603) must not swallow the next turn's stop", async () => {
// pendingCancelStops only decremented on stop; a -32603 on the cancelled prompt left the counter at 1
// and the next turn's stop was discarded so that turn never ended.
const r = await open({ slowMs: 250, cancelAsError: true });
try {
await r.session.send({ text: "first", images: [] });
await until(() => r.events.some((e) => e.type === "turn_started"));
await r.session.interrupt();
await until(() => r.events.some((e) => e.type === "turn_ended" && (e as { status?: string }).status === "interrupted"));
await expect(r.session.send({ text: "second", images: [] })).resolves.toBeUndefined();
await until(() => r.events.filter((e) => e.type === "turn_started").length >= 2);
// Second turn must be able to end normally when its own stop arrives (not swallowed by a leftover counter)
await until(() => r.events.filter((e) => e.type === "turn_ended").length >= 2, 10000);
const ends = r.events.filter((e) => e.type === "turn_ended") as { status?: string }[];
expect(ends[0]?.status).toBe("interrupted");
expect(ends[ends.length - 1]?.status).toBe("completed");
} finally {
await r.session.close();
await r.done;
}
}, 20000);
it("0ms resend after interrupt: Devin-like cancel settle must not cancel Turn 2", async () => {
// Real Devin cancels an overlapping session/prompt that arrives while prompt1 is still unwinding.
// Without pendingCancelSettle, ends are [interrupted, interrupted]; with the fix [interrupted, completed].
const r = await open({ slowMs: 5000, cancelSettleMs: 60 });
try {
await r.session.send({ text: "first", images: [] });
await until(() => r.events.some((e) => e.type === "turn_started"));
await r.session.interrupt();
await until(() => r.events.some((e) => e.type === "turn_ended" && (e as { status?: string }).status === "interrupted"));
// Immediate 0ms resend (AgentManager queue / instant UI send)
await expect(r.session.send({ text: "second", images: [] })).resolves.toBeUndefined();
await until(() => r.events.filter((e) => e.type === "turn_started").length >= 2);
await until(() => r.events.filter((e) => e.type === "turn_ended").length >= 2, 10000);
const ends = r.events.filter((e) => e.type === "turn_ended") as { status?: string }[];
expect(ends.map((e) => e.status)).toEqual(["interrupted", "completed"]);
const afterT2 = r.events.filter((e) => e.type === "turn_started").length >= 2;
const t2StartIdx = r.events.findIndex((e, i) => e.type === "turn_started" && r.events.slice(0, i + 1).filter((x) => x.type === "turn_started").length === 2);
const afterStart = r.events.slice(t2StartIdx + 1);
const stale = afterStart.filter((e) => e.type === "assistant_delta" && (e as { text?: string }).text === "STALE_FROM_TURN_1");
expect(stale).toHaveLength(0);
const t2Text = afterStart
.filter((e) => e.type === "assistant_delta" || e.type === "assistant_message")
.map((e) => (e as { text?: string }).text || "")
.join("");
expect(t2Text.length).toBeGreaterThan(0);
expect(t2Text).not.toContain("STALE_FROM_TURN_1");
void afterT2;
} finally {
await r.session.close();
await r.done;
}
}, 20000);
});
@@ -2,14 +2,23 @@
// (fixtures/fake-claude.mjs) that speaks the same protocol: streaming text / thinking / tools, permission approve and
// deny, the CLI withdrawing an ask, interrupt, model / mode switches, resume, images, slash commands, and a claude
// that is missing or dies.
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { ClaudeSession } from "../../daemon/src/providers/claude/session.js";
import { createClaudeProvider } from "../../daemon/src/providers/claude/provider.js";
import { setAppLocale } from "../../daemon/src/util/i18n.js";
import type { ProviderEvent } from "../../daemon/src/timeline/types.js";
import { AgentManager } from "../../daemon/src/agents/manager.js";
import { ThreadsStore } from "../../daemon/src/store/threads.js";
import { ProjectsStore } from "../../daemon/src/store/projects.js";
import { SettingsStore } from "../../daemon/src/store/settings.js";
import { AttachmentStore } from "../../daemon/src/store/attachments.js";
import { Gateway } from "../../daemon/src/ws/gateway.js";
import { initProviders, registerProvider, getProvider } from "../../daemon/src/providers/registry.js";
import { clearProviderCache } from "../../daemon/src/providers/infoCache.js";
import type { Config } from "../../daemon/src/config.js";
const fixture = resolve(__dirname, "fixtures", "fake-claude.mjs");
const bin = { ok: true as const, cmd: process.execPath, prefixArgs: [fixture], display: fixture, via: "shim-js" };
@@ -140,6 +149,130 @@ describe("claude over stream-json", () => {
}
});
it("after interrupt, send() works again even when the CLI result is late", async () => {
// Hold the late interrupt result until release: interrupted + send(second) must both happen first
// (order, not wall clock — red on main which waits for the late result before send(second)).
const hold = join(dir, `hold-late-${++n}`);
writeFileSync(hold, "");
const { s, events, until, log } = open({}, { FAKE_CLAUDE_HOLD_FILE: hold });
try {
await s.send({ text: "SLOW", images: [] });
await until((e) => e.type === "assistant_delta");
await s.interrupt();
expect(await until(ended)).toMatchObject({ status: "interrupted" });
await expect(s.send({ text: "second", images: [] })).resolves.toBeUndefined();
await until((e) => e.type === "turn_started" && events.filter((x) => x.type === "turn_started").length >= 2);
const secondOnWire = () => log().some((l) => l.in?.type === "user" && JSON.stringify(l.in).includes("second"));
const wireDeadline = Date.now() + 2000;
while (Date.now() < wireDeadline && !secondOnWire()) await new Promise((r) => setTimeout(r, 15));
expect(secondOnWire()).toBe(true);
expect(existsSync(hold)).toBe(true);
unlinkSync(hold);
await until((e) => e.type === "turn_ended" && events.filter((x) => x.type === "turn_ended").length >= 2);
const ends = events.filter((e) => e.type === "turn_ended") as { status?: string }[];
expect(ends[0]?.status).toBe("interrupted");
expect(ends.filter((e) => e.status === "interrupted")).toHaveLength(1);
expect(ends[ends.length - 1]?.status).toBe("completed");
expect(log().filter((l) => l.in?.type === "user").length).toBeGreaterThanOrEqual(2);
} finally {
try { unlinkSync(hold); } catch { /* gone */ }
await s.close();
}
});
it("late error_during_execution after next send must not end the new turn as failed", async () => {
// Real Claude Code CLI ends an interrupted turn with subtype error_during_execution (not error_interrupted).
// send() resets sawInterrupt, so that result maps to failed; dropping by this CLI's FIFO of results owed
// (not status) is required so the late result cannot kill the next turn.
// Hold the late result: second user must be on the wire before release (red on main).
const hold = join(dir, `hold-fifo-${++n}`);
writeFileSync(hold, "");
const { s, events, until, log } = open({}, { FAKE_CLAUDE_HOLD_FILE: hold });
try {
await s.send({ text: "SLOW", images: [] });
await until((e) => e.type === "assistant_delta");
await s.interrupt();
expect(await until(ended)).toMatchObject({ status: "interrupted" });
await s.send({ text: "second", images: [] });
await until((e) => e.type === "turn_started" && events.filter((x) => x.type === "turn_started").length >= 2);
const secondOnWire = () => log().some((l) => l.in?.type === "user" && JSON.stringify(l.in).includes("second"));
const wireDeadline = Date.now() + 2000;
while (Date.now() < wireDeadline && !secondOnWire()) await new Promise((r) => setTimeout(r, 15));
expect(secondOnWire()).toBe(true);
expect(existsSync(hold)).toBe(true);
const endsBeforeRelease = events.filter((e) => e.type === "turn_ended") as { status?: string }[];
expect(endsBeforeRelease).toHaveLength(1);
expect(endsBeforeRelease[0]?.status).toBe("interrupted");
unlinkSync(hold);
await until((e) => e.type === "turn_ended" && events.filter((x) => x.type === "turn_ended").length >= 2);
const ends = events.filter((e) => e.type === "turn_ended") as { status?: string }[];
expect(ends.filter((e) => e.status === "interrupted")).toHaveLength(1);
expect(ends.some((e) => e.status === "failed")).toBe(false);
expect(ends[ends.length - 1]?.status).toBe("completed");
} finally {
try { unlinkSync(hold); } catch { /* gone */ }
await s.close();
}
});
it("interrupt control_response error restarts CLI; next turn still completes", async () => {
// On 45a67b2 the failed-interrupt gen stayed in awaitingResult/skipResultGens; the restarted CLI's
// first result shifted that stale gen and was dropped, so the next turn never ended.
// FIFO now lives on ClaudeCli, so abandoning the failed CLI is enough (no session-level reset).
const { s, events, until } = open({}, { FAKE_CLAUDE_INTERRUPT_FAIL: "1" });
try {
await s.send({ text: "SLOW", images: [] });
await until((e) => e.type === "assistant_delta");
await s.interrupt();
expect(await until(ended)).toMatchObject({ status: "interrupted" });
await expect(s.send({ text: "second", images: [] })).resolves.toBeUndefined();
await until((e) => e.type === "turn_started" && events.filter((x) => x.type === "turn_started").length >= 2);
await until((e) => e.type === "turn_ended" && events.filter((x) => x.type === "turn_ended").length >= 2, 10000);
const ends = events.filter((e) => e.type === "turn_ended") as { status?: string }[];
expect(ends[0]?.status).toBe("interrupted");
expect(ends[ends.length - 1]?.status).toBe("completed");
} finally {
await s.close();
}
});
it("replaced CLI leftover stdout is ignored (this.cli !== cli)", async () => {
// Interrupt fails; old CLI lingers and emits a poison result while restart replaces it.
// Without `if (this.cli !== cli) continue` that poison would emit a spurious turn_ended.
const { s, events, until } = open({}, { FAKE_CLAUDE_INTERRUPT_FAIL: "1", FAKE_CLAUDE_FAIL_LINGER_RESULT_MS: "120" });
try {
await s.send({ text: "SLOW", images: [] });
await until((e) => e.type === "assistant_delta");
await s.interrupt();
expect(await until(ended)).toMatchObject({ status: "interrupted" });
await expect(s.send({ text: "second", images: [] })).resolves.toBeUndefined();
await until((e) => e.type === "turn_ended" && events.filter((x) => x.type === "turn_ended").length >= 2, 10000);
await new Promise((r) => setTimeout(r, 250)); // past linger window
const ends = events.filter((e) => e.type === "turn_ended") as { status?: string; error?: string }[];
expect(ends.map((e) => e.status)).toEqual(["interrupted", "completed"]);
expect(ends.some((e) => (e.error ?? "").includes("POISON_FROM_OLD_CLI"))).toBe(false);
expect(events.filter((e) => e.type === "turn_ended")).toHaveLength(2);
} finally {
await s.close();
}
});
it("CLI crash mid-turn: next turn on a fresh CLI still completes", async () => {
// A turn whose CLI died must not leave its gen in awaitingResult for the next CLI's first result.
const { s, events, until } = open({}, { FAKE_CLAUDE_CRASH_AFTER_DELTA: "1" });
try {
await s.send({ text: "SLOW", images: [] });
expect(await until(ended)).toMatchObject({ status: "failed" });
await expect(s.send({ text: "after-crash", images: [] })).resolves.toBeUndefined();
await until((e) => e.type === "turn_ended" && events.filter((x) => x.type === "turn_ended").length >= 2, 10000);
const ends = events.filter((e) => e.type === "turn_ended") as { status?: string }[];
expect(ends[0]?.status).toBe("failed");
expect(ends[ends.length - 1]?.status).toBe("completed");
} finally {
await s.close();
}
});
it("model and mode switch in place; bypassPermissions and effort relaunch with --resume", async () => {
const { s, events, until, log } = open();
try {
@@ -250,3 +383,92 @@ describe("claude over stream-json", () => {
.rejects.toThrow(/^claude was not found .*Claude Code is not bundled with this plugin; install it first: npm i -g @anthropic-ai\/claude-code/);
});
});
describe("AgentManager + Claude crash keeps thread open (resume)", () => {
// Point 7 / yetone review 3: crash path intentionally does NOT close the event queue, so the
// manager does not mark the thread closed; the next send restarts Claude with --resume.
const cfg: Config = { port: 0, dataDir: "", token: "t", version: "0.0.0", idleExitMinutes: 60, buildStamp: "0" };
let mdir: string;
let threads: ThreadsStore;
let projects: ProjectsStore;
let settings: SettingsStore;
let gw: Gateway;
let manager: AgentManager;
let threadId: string;
let logFile: string;
beforeEach(async () => {
mdir = mkdtempSync(join(tmpdir(), "claude-mgr-"));
logFile = join(mdir, "claude.jsonl");
process.env.AGENT_CONSOLE_MOCK = "1";
process.env.FAKE_CLAUDE_LOG = logFile;
delete process.env.FAKE_CLAUDE_CRASH_AFTER_DELTA;
delete process.env.FAKE_CLAUDE_EXIT;
delete process.env.FAKE_CLAUDE_INTERRUPT_FAIL;
delete process.env.FAKE_CLAUDE_HOLD_FILE;
delete process.env.FAKE_CLAUDE_FAIL_LINGER_RESULT_MS;
initProviders();
registerProvider(
createClaudeProvider({
resolve: async () => ({ ok: true as const, cmd: process.execPath, prefixArgs: [fixture], display: fixture, via: "shim-js" }),
}),
);
const claude = getProvider("claude")!;
claude.detect = async () => ({ available: true, bin: fixture, version: "fake-0" });
clearProviderCache("claude");
threads = new ThreadsStore(mdir);
projects = new ProjectsStore(mdir);
settings = new SettingsStore(mdir);
gw = new Gateway(cfg);
manager = new AgentManager(gw, threads, projects, settings, new AttachmentStore(join(mdir, "attachments")));
const proj = await projects.create(mdir);
threadId = (await threads.create({ projectId: proj.id, provider: "claude" })).id;
});
afterEach(() => {
manager.shutdown();
delete process.env.FAKE_CLAUDE_CRASH_AFTER_DELTA;
delete process.env.FAKE_CLAUDE_LOG;
rmSync(mdir, { recursive: true, force: true });
});
const waitFor = async (fn: () => boolean | Promise<boolean>, ms = 15000) => {
const t0 = Date.now();
while (Date.now() - t0 < ms) {
if (await fn()) return;
await new Promise((r) => setTimeout(r, 40));
}
throw new Error("waitFor timed out");
};
it("mid-turn CLI crash: thread stays idle (not closed); next send resumes with --resume", async () => {
process.env.FAKE_CLAUDE_CRASH_AFTER_DELTA = "1";
await manager.send(threadId, { text: "SLOW" });
await waitFor(async () => (await threads.get(threadId))?.status === "idle");
const meta1 = await threads.get(threadId);
expect(meta1?.status).toBe("idle");
expect(meta1?.status).not.toBe("closed");
expect(meta1?.lastTurnStatus).toBe("failed");
expect(meta1?.providerSessionId).toBeTruthy();
const sid = meta1!.providerSessionId!;
delete process.env.FAKE_CLAUDE_CRASH_AFTER_DELTA;
await manager.send(threadId, { text: "after-crash" });
await waitFor(async () => (await threads.get(threadId))?.lastTurnStatus === "completed");
const meta2 = await threads.get(threadId);
expect(meta2?.status).toBe("idle");
expect(meta2?.status).not.toBe("closed");
const argvs = readFileSync(logFile, "utf8")
.trim()
.split("\n")
.map((l) => JSON.parse(l))
.filter((l) => l.argv)
.map((l) => l.argv as string[]);
expect(argvs.length).toBeGreaterThanOrEqual(2);
expect(argvs[1]).toEqual(expect.arrayContaining(["--resume", sid]));
const ends = (await threads.readEvents(threadId, 0, 50000)).filter((e) => e.type === "turn_ended") as { status?: string }[];
expect(ends[0]?.status).toBe("failed");
expect(ends[ends.length - 1]?.status).toBe("completed");
}, 30000);
});
@@ -0,0 +1,213 @@
// Codex interrupt: turn/interrupt is a JSON-RPC *request* (has a response). After interrupt the local turn
// must end so a late turn/completed cannot bind onto the next send (same class of bug as ACP/Devin).
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, unlinkSync } from "node:fs";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { CodexSession } from "../../daemon/src/providers/codex/session.js";
import type { ProviderEvent } from "../../daemon/src/timeline/types.js";
const fixture = resolve(__dirname, "fixtures", "fake-codex-app-server.mjs");
let dir: string;
beforeAll(() => {
dir = mkdtempSync(join(tmpdir(), "codex-interrupt-"));
});
afterAll(() => rmSync(dir, { recursive: true, force: true }));
type Run = { session: CodexSession; events: ProviderEvent[]; logFile: string; done: Promise<void> };
function open(env: Record<string, string> = {}): Run {
const logFile = join(dir, `c-${Math.random().toString(36).slice(2)}.jsonl`);
const session = new CodexSession({
threadId: "t1",
cwd: dir,
model: null,
mode: "default",
effort: null,
resumeId: null,
binCmd: process.execPath,
binPrefixArgs: [],
version: "test",
launch: { cmd: process.execPath, prefixArgs: [fixture] },
});
// Inject env for the child via process.env (CodexRpc inherits process.env)
for (const [k, v] of Object.entries({ FAKE_CODEX_LOG: logFile, ...env })) process.env[k] = v;
const events: ProviderEvent[] = [];
const done = (async () => {
for await (const ev of session.events) events.push(ev);
})();
return { session, events, logFile, done };
}
async function until(check: () => boolean, ms = 10000) {
const end = Date.now() + ms;
while (!check()) {
if (Date.now() > end) throw new Error("timed out");
await new Promise((r) => setTimeout(r, 20));
}
}
const lines = (f: string) =>
existsSync(f) ? readFileSync(f, "utf8").trim().split("\n").filter(Boolean).map((l) => JSON.parse(l)) : [];
describe("Codex interrupt", () => {
it("interrupt sends turn/interrupt as a JSON-RPC request (with id), not a notification", async () => {
const r = open({ FAKE_CODEX_SLOW_MS: "5000" });
try {
await r.session.send({ text: "slow", images: [] });
await until(() => r.events.some((e) => e.type === "turn_started"));
// Wait until fake has emitted turn/started (Codex turn id known)
await until(() => lines(r.logFile).some((l) => l.in?.method === "turn/start"));
await until(() => r.events.some((e) => e.type === "assistant_delta") || lines(r.logFile).length > 3);
await new Promise((x) => setTimeout(x, 80)); // allow turn/started notification to arrive
await r.session.interrupt();
await until(() => lines(r.logFile).some((l) => l.in?.method === "turn/interrupt"));
const hit = lines(r.logFile).find((l) => l.in?.method === "turn/interrupt");
expect(hit.in.id).toEqual(expect.any(Number));
await until(() => r.events.some((e) => e.type === "turn_ended"));
expect((r.events.find((e) => e.type === "turn_ended") as { status?: string }).status).toBe("interrupted");
} finally {
await r.session.close();
await r.done;
delete process.env.FAKE_CODEX_SLOW_MS;
delete process.env.FAKE_CODEX_LOG;
delete process.env.FAKE_CODEX_IGNORE_INTERRUPT;
delete process.env.FAKE_CODEX_START_DELAY_MS;
delete process.env.FAKE_CODEX_STARTED_DELAY_MS;
delete process.env.FAKE_CODEX_RESPONSE_HOLD_FILE;
delete process.env.FAKE_CODEX_STARTED_HOLD_FILE;
}
}, 20000);
it("after interrupt, send() works again; late turn/completed does not end the new turn", async () => {
const r = open({ FAKE_CODEX_SLOW_MS: "600", FAKE_CODEX_IGNORE_INTERRUPT: "1" });
try {
await r.session.send({ text: "first", images: [] });
await until(() => r.events.some((e) => e.type === "turn_started"));
await new Promise((x) => setTimeout(x, 80));
await r.session.interrupt();
await until(() => r.events.some((e) => e.type === "turn_ended" && (e as { status?: string }).status === "interrupted"));
await expect(r.session.send({ text: "second", images: [] })).resolves.toBeUndefined();
await until(() => r.events.filter((e) => e.type === "turn_started").length >= 2);
await new Promise((x) => setTimeout(x, 800)); // past first turn's slow timeout
const ends = r.events.filter((e) => e.type === "turn_ended") as { status?: string }[];
expect(ends[0]?.status).toBe("interrupted");
expect(ends.filter((e) => e.status === "interrupted")).toHaveLength(1);
} finally {
await r.session.close();
await r.done;
delete process.env.FAKE_CODEX_SLOW_MS;
delete process.env.FAKE_CODEX_LOG;
delete process.env.FAKE_CODEX_IGNORE_INTERRUPT;
delete process.env.FAKE_CODEX_START_DELAY_MS;
delete process.env.FAKE_CODEX_STARTED_DELAY_MS;
delete process.env.FAKE_CODEX_RESPONSE_HOLD_FILE;
delete process.env.FAKE_CODEX_STARTED_HOLD_FILE;
}
}, 20000);
it("interrupt before turn/started still ends locally and does not poison the next send", async () => {
const r = open({ FAKE_CODEX_SLOW_MS: "400" });
try {
const sendP = r.session.send({ text: "first", images: [] });
await until(() => r.events.some((e) => e.type === "turn_started"));
// Interrupt immediately — may race before fake's delayed turn/started
await r.session.interrupt();
await sendP.catch(() => {});
await until(() => r.events.some((e) => e.type === "turn_ended"));
await expect(r.session.send({ text: "second", images: [] })).resolves.toBeUndefined();
await until(() => r.events.filter((e) => e.type === "turn_started").length >= 2);
await until(() => r.events.filter((e) => e.type === "turn_ended").length >= 2, 10000);
const ends = r.events.filter((e) => e.type === "turn_ended") as { status?: string }[];
expect(ends.some((e) => e.status === "interrupted")).toBe(true);
} finally {
await r.session.close();
await r.done;
delete process.env.FAKE_CODEX_SLOW_MS;
delete process.env.FAKE_CODEX_LOG;
delete process.env.FAKE_CODEX_IGNORE_INTERRUPT;
delete process.env.FAKE_CODEX_START_DELAY_MS;
delete process.env.FAKE_CODEX_STARTED_DELAY_MS;
delete process.env.FAKE_CODEX_RESPONSE_HOLD_FILE;
delete process.env.FAKE_CODEX_STARTED_HOLD_FILE;
}
}, 20000);
it("Stop after turn/start response, before turn/started, then immediate resend", async () => {
// Hold turn/started until release: interrupted + send(second) must both happen while hold exists
// (order, not wall clock — red on main which waited for turn/started / completion).
const hold = join(dir, `hold-started-${Math.random().toString(36).slice(2)}`);
writeFileSync(hold, "");
const r = open({ FAKE_CODEX_SLOW_MS: "1500", FAKE_CODEX_STARTED_DELAY_MS: "0", FAKE_CODEX_STARTED_HOLD_FILE: hold });
try {
await r.session.send({ text: "first", images: [] });
await until(() => r.events.some((e) => e.type === "turn_started"));
// Response is not held — wait until send() returns (currentTurnId set) then Stop before started
await r.session.interrupt();
await until(() => r.events.some((e) => e.type === "turn_ended" && (e as { status?: string }).status === "interrupted"));
await expect(r.session.send({ text: "second", images: [] })).resolves.toBeUndefined();
await until(() => r.events.filter((e) => e.type === "turn_started").length >= 2);
expect(existsSync(hold)).toBe(true); // fake has not emitted turn/started for turn 1 yet
unlinkSync(hold);
await until(() => lines(r.logFile).some((l) => l.in?.method === "turn/interrupt"), 5000);
expect(lines(r.logFile).find((l) => l.in?.method === "turn/interrupt").in.params.turnId).toBe("codex-turn-1");
await until(() => r.events.filter((e) => e.type === "turn_ended").length >= 2, 10000);
const ends = r.events.filter((e) => e.type === "turn_ended") as { status?: string; turnId?: string }[];
expect(ends.map((e) => e.status)).toEqual(["interrupted", "completed"]);
expect(ends[1]?.turnId?.startsWith("u_")).toBe(true);
} finally {
try { unlinkSync(hold); } catch { /* already gone */ }
await r.session.close();
await r.done;
delete process.env.FAKE_CODEX_SLOW_MS;
delete process.env.FAKE_CODEX_LOG;
delete process.env.FAKE_CODEX_IGNORE_INTERRUPT;
delete process.env.FAKE_CODEX_START_DELAY_MS;
delete process.env.FAKE_CODEX_STARTED_DELAY_MS;
delete process.env.FAKE_CODEX_RESPONSE_HOLD_FILE;
delete process.env.FAKE_CODEX_STARTED_HOLD_FILE;
}
}, 20000);
it("Stop while turn/start is in flight, then immediate resend interrupts codex-turn-1", async () => {
// Hold the first turn/start response: interrupt + send(second) must both happen while hold exists.
// ourTurnId !== turnId alone covers this (cancelledLocalTurns removed as redundant). Red on main.
const hold = join(dir, `hold-response-${Math.random().toString(36).slice(2)}`);
writeFileSync(hold, "");
const r = open({ FAKE_CODEX_SLOW_MS: "1500", FAKE_CODEX_RESPONSE_HOLD_FILE: hold });
try {
const send1 = r.session.send({ text: "first", images: [] });
await until(() => r.events.some((e) => e.type === "turn_started"));
await r.session.interrupt();
await until(() => r.events.some((e) => e.type === "turn_ended" && (e as { status?: string }).status === "interrupted"));
// Do not await send(second) until the hold is released — its turn/start response is also gated.
const send2 = r.session.send({ text: "second", images: [] });
await until(() => r.events.filter((e) => e.type === "turn_started").length >= 2);
expect(existsSync(hold)).toBe(true); // turn/start response for turn 1 still held
unlinkSync(hold);
await send1.catch(() => {});
await send2;
await until(() => lines(r.logFile).some((l) => l.in?.method === "turn/interrupt"), 5000);
const interrupts = lines(r.logFile).filter((l) => l.in?.method === "turn/interrupt").map((l) => l.in.params.turnId);
expect(interrupts).toContain("codex-turn-1");
await until(() => r.events.filter((e) => e.type === "turn_ended").length >= 2, 10000);
await new Promise((x) => setTimeout(x, 300));
const ends = r.events.filter((e) => e.type === "turn_ended") as { status?: string; turnId?: string }[];
expect(ends).toHaveLength(2);
expect(ends.map((e) => e.status)).toEqual(["interrupted", "completed"]);
expect(ends.every((e) => e.turnId && e.turnId.startsWith("u_"))).toBe(true);
} finally {
try { unlinkSync(hold); } catch { /* already gone */ }
await r.session.close();
await r.done;
delete process.env.FAKE_CODEX_SLOW_MS;
delete process.env.FAKE_CODEX_LOG;
delete process.env.FAKE_CODEX_IGNORE_INTERRUPT;
delete process.env.FAKE_CODEX_START_DELAY_MS;
delete process.env.FAKE_CODEX_STARTED_DELAY_MS;
delete process.env.FAKE_CODEX_RESPONSE_HOLD_FILE;
delete process.env.FAKE_CODEX_STARTED_HOLD_FILE;
}
}, 20000);
});
@@ -9,6 +9,17 @@
// "withdraw": asks, then sends $/cancel_request for it and ends the turn once the client answers
// "answer": asks and ends the turn once the client answers (the normal path)
// FAKE_ACP_PERM_LOG file each answer to session/request_permission is appended to, one JSON line
// FAKE_ACP_CANCEL_LOG file each session/cancel is appended to, one JSON line { notification, hasId, sessionId }
// FAKE_ACP_SLOW_MS hold each session/prompt open this many ms (or until session/cancel); cancel ends with
// stopReason cancelled. Used to test interrupt while a turn is in flight.
// FAKE_ACP_IGNORE_CANCEL when set with FAKE_ACP_SLOW_MS: cancel is logged but does not end the prompt (Devin-like
// "cancel was a no-op / never acknowledged" — the client must clear its own running flag)
// FAKE_ACP_CANCEL_AS_ERROR when set with FAKE_ACP_SLOW_MS: cancel answers the in-flight session/prompt with
// JSON-RPC error -32603 (no stopReason) — leftover pendingCancelStops counters used to
// swallow the next turn's stop after this.
// FAKE_ACP_CANCEL_SETTLE_MS Devin-like: after session/cancel, wait this many ms (emit STALE_FROM_TURN_1 chunk)
// before settling cancelled. A new session/prompt that arrives while cancelling is
// itself answered stopReason cancelled (0ms-resend race).
// Every prompt is answered with one agent_message_chunk ("ok: <n> blocks") and stopReason end_turn.
import { appendFileSync } from "node:fs";
import { createInterface } from "node:readline";
@@ -17,10 +28,17 @@ const caps = process.env.FAKE_ACP_PROMPT_CAPS ? JSON.parse(process.env.FAKE_ACP_
const session = process.env.FAKE_ACP_SESSION ? JSON.parse(process.env.FAKE_ACP_SESSION) : {};
const logFile = process.env.FAKE_ACP_LOG;
const sessionLog = process.env.FAKE_ACP_SESSION_LOG;
const cancelLog = process.env.FAKE_ACP_CANCEL_LOG;
const permMode = process.env.FAKE_ACP_PERM;
const permLog = process.env.FAKE_ACP_PERM_LOG;
const slowMs = process.env.FAKE_ACP_SLOW_MS ? Number(process.env.FAKE_ACP_SLOW_MS) : 0;
const ignoreCancel = !!process.env.FAKE_ACP_IGNORE_CANCEL;
const cancelAsError = !!process.env.FAKE_ACP_CANCEL_AS_ERROR;
const cancelSettleMs = process.env.FAKE_ACP_CANCEL_SETTLE_MS ? Number(process.env.FAKE_ACP_CANCEL_SETTLE_MS) : 0;
let nextOwnId = 9000;
const waiting = new Map(); // our request id -> callback(response)
/** @type {Map<string, { timer: NodeJS.Timeout | null, finish: (reason: string) => void, fail: (code: number, message: string) => void, cancelling?: boolean }>} */
const openPrompts = new Map(); // sessionId -> in-flight slow prompt
const out = (msg) => process.stdout.write(JSON.stringify({ jsonrpc: "2.0", ...msg }) + "\n");
const answer = (id, result) => out({ id, result });
const logSession = (method, sessionId) => {
@@ -117,10 +135,66 @@ createInterface({ input: process.stdin }).on("line", (line) => {
}
return;
}
if (slowMs > 0) {
const prior = openPrompts.get(p.sessionId);
// Devin race: a new prompt while the previous is still cancelling → cancel the new one too
if (prior?.cancelling) {
return answer(m.id, { stopReason: "cancelled" });
}
if (prior) prior.finish("cancelled");
const finish = (reason) => {
const open = openPrompts.get(p.sessionId);
if (!open || open.finish !== finish) return;
if (open.timer) clearTimeout(open.timer);
openPrompts.delete(p.sessionId);
answer(m.id, { stopReason: reason });
};
const fail = (code, message) => {
const open = openPrompts.get(p.sessionId);
if (!open || open.fail !== fail) return;
if (open.timer) clearTimeout(open.timer);
openPrompts.delete(p.sessionId);
out({ id: m.id, error: { code, message } });
};
const timer = setTimeout(() => finish("end_turn"), slowMs);
openPrompts.set(p.sessionId, { timer, finish, fail, cancelling: false });
return;
}
return answer(m.id, { stopReason: "end_turn" });
}
case "session/cancel":
case "session/cancel": {
// ACP cancel is a notification (no JSON-RPC id). If a client wrongly sends it as a request, answer
// Method not found like Devin CLI (which only registers the notification handler).
if (cancelLog) {
appendFileSync(
cancelLog,
JSON.stringify({ notification: m.id === undefined, hasId: m.id !== undefined, sessionId: p.sessionId }) + "\n",
);
}
if (m.id !== undefined) {
return out({ id: m.id, error: { code: -32601, message: "Method not found" } });
}
const open = openPrompts.get(p.sessionId);
if (open && !ignoreCancel) {
if (cancelAsError) open.fail(-32603, "Internal error");
else if (cancelSettleMs > 0) {
// Devin-like delayed cancel settle + trailing stale chunk
open.cancelling = true;
if (open.timer) clearTimeout(open.timer);
open.timer = setTimeout(() => {
out({
method: "session/update",
params: {
sessionId: p.sessionId,
update: { sessionUpdate: "agent_message_chunk", content: { type: "text", text: "STALE_FROM_TURN_1" } },
},
});
open.finish("cancelled");
}, cancelSettleMs);
} else open.finish("cancelled");
}
return;
}
default:
if (m.id !== undefined) out({ id: m.id, error: { code: -32601, message: `method not found: ${m.method}` } });
}
@@ -5,13 +5,25 @@
// user tool_result and result messages. Every argv and stdin line is appended to $FAKE_CLAUDE_LOG.
// The user text picks the scenario: TOOL (ask to run Bash), CANCEL (ask, then withdraw the ask), SLOW (stream and wait
// for an interrupt); anything else is echoed with a description of the image blocks it got.
import { appendFileSync } from "node:fs";
// FAKE_CLAUDE_INTERRUPT_RESULT_MS delay (ms) between interrupt ack and ending the SLOW turn (late-result races).
// FAKE_CLAUDE_HOLD_FILE when set, wait until this path is deleted before emitting the delayed interrupt result.
// FAKE_CLAUDE_INTERRUPT_FAIL when set, interrupt control_response is an error (busy) — CLI must restart.
// FAKE_CLAUDE_FAIL_LINGER_RESULT_MS with INTERRUPT_FAIL: emit a poison `result` after N ms, and delay stdin-close exit
// so a replaced CLI's pump can see leftover stdout (tests this.cli !== cli guard).
// FAKE_CLAUDE_CRASH_AFTER_DELTA when set with SLOW: after first text delta, exit(1) mid-turn.
import { appendFileSync, existsSync } from "node:fs";
import { createInterface } from "node:readline";
const args = process.argv.slice(2);
const logFile = process.env.FAKE_CLAUDE_LOG;
const log = (o) => logFile && appendFileSync(logFile, JSON.stringify(o) + "\n");
log({ argv: args });
/** Poll until FAKE_CLAUDE_HOLD_FILE is gone (or unset). Deterministic release gate for tests. */
async function waitHold() {
const f = process.env.FAKE_CLAUDE_HOLD_FILE;
if (!f) return;
while (existsSync(f)) await new Promise((r) => setTimeout(r, 15));
}
if (process.env.FAKE_CLAUDE_EXIT) {
process.stderr.write("fake claude: boom\n");
process.exit(Number(process.env.FAKE_CLAUDE_EXIT));
@@ -65,6 +77,10 @@ async function turn(content) {
}
if (text.includes("SLOW")) {
say("working");
if (process.env.FAKE_CLAUDE_CRASH_AFTER_DELTA) {
process.stderr.write("fake claude: crash after delta\n");
process.exit(1);
}
await new Promise((resolve) => (interruptTurn = resolve));
return done({ subtype: "error_during_execution", is_error: true, result: "" });
}
@@ -74,6 +90,20 @@ async function turn(content) {
done();
}
// Real Claude CLI handles user turns in order: one result per user message, FIFO.
// Queue user messages so a late interrupted result cannot arrive after a newer turn's result.
const userQueue = [];
let turning = false;
async function pumpUsers() {
if (turning) return;
turning = true;
while (userQueue.length) {
const content = userQueue.shift();
try { await turn(content); } catch (e) { console.error("fake-claude turn error", e); }
}
turning = false;
}
const rl = createInterface({ input: process.stdin });
rl.on("line", (line) => {
if (!line.trim()) return;
@@ -85,7 +115,35 @@ rl.on("line", (line) => {
if (r.subtype === "initialize") return ok({ commands: [{ name: "review", description: "Review the diff", argumentHint: "[path]" }, { name: "compact", description: "Compact", argumentHint: "" }], models: [{ value: "sonnet" }] });
if (r.subtype === "set_model") { model = r.model ?? "default"; return ok(); }
if (r.subtype === "set_permission_mode") { mode = r.mode; return ok(); }
if (r.subtype === "interrupt") { ok(); interruptTurn?.(); interruptTurn = null; return; }
if (r.subtype === "interrupt") {
if (process.env.FAKE_CLAUDE_INTERRUPT_FAIL) {
out({ type: "control_response", response: { subtype: "error", request_id: m.request_id, error: "busy" } });
const linger = Number(process.env.FAKE_CLAUDE_FAIL_LINGER_RESULT_MS || 0);
if (linger > 0) {
setTimeout(() => {
// Poison result for a replaced CLI's pump (must be ignored via this.cli !== cli)
out({
type: "result", subtype: "error_during_execution", is_error: true, result: "POISON_FROM_OLD_CLI",
duration_ms: 1, num_turns: 1, session_id: sid, total_cost_usd: 0,
usage: { input_tokens: 0, output_tokens: 0, cache_read_input_tokens: 0 },
});
}, linger);
}
return;
}
ok();
const resume = interruptTurn;
interruptTurn = null;
// Optional delay / hold-file gate before ending the turn so interrupt→resend races can be tested
const delay = Number(process.env.FAKE_CLAUDE_INTERRUPT_RESULT_MS || 0);
const release = async () => {
if (delay > 0) await new Promise((r) => setTimeout(r, delay));
await waitHold();
resume?.();
};
void release();
return;
}
return out({ type: "control_response", response: { subtype: "error", request_id: m.request_id, error: "unknown" } });
}
if (m.type === "control_response") {
@@ -93,6 +151,13 @@ rl.on("line", (line) => {
waiting.delete(m.response.request_id);
return w?.(m.response.response);
}
if (m.type === "user") void turn(m.message.content);
if (m.type === "user") {
userQueue.push(m.message.content);
void pumpUsers();
}
});
rl.on("close", () => {
const linger = Number(process.env.FAKE_CLAUDE_FAIL_LINGER_RESULT_MS || 0);
if (linger > 0) setTimeout(() => process.exit(0), linger + 80);
else process.exit(0);
});
rl.on("close", () => process.exit(0));
@@ -0,0 +1,101 @@
#!/usr/bin/env node
// Minimal `codex app-server` stand-in for interrupt tests. No network, no model.
// Env:
// FAKE_CODEX_LOG append every client JSON-RPC line
// FAKE_CODEX_SLOW_MS delay before turn/started + turn/completed (default 0)
// FAKE_CODEX_IGNORE_INTERRUPT when set, turn/interrupt is answered but turn is not ended
// FAKE_CODEX_START_DELAY_MS delay only the first turn/start *response* (in-flight Stop race)
// FAKE_CODEX_STARTED_DELAY_MS delay before turn/started after the response (default derived from SLOW_MS)
// FAKE_CODEX_RESPONSE_HOLD_FILE wait until deleted before emitting a turn/start *response*
// FAKE_CODEX_STARTED_HOLD_FILE wait until deleted before emitting turn/started
import { appendFileSync, existsSync } from "node:fs";
import { createInterface } from "node:readline";
const logFile = process.env.FAKE_CODEX_LOG;
const slowMs = Number(process.env.FAKE_CODEX_SLOW_MS || 0);
const ignoreInterrupt = !!process.env.FAKE_CODEX_IGNORE_INTERRUPT;
const startDelayMs = Number(process.env.FAKE_CODEX_START_DELAY_MS || 0);
const startedDelayMs = process.env.FAKE_CODEX_STARTED_DELAY_MS != null
? Number(process.env.FAKE_CODEX_STARTED_DELAY_MS)
: null;
let startCount = 0;
const out = (msg) => process.stdout.write(JSON.stringify(msg) + "\n");
const log = (o) => logFile && appendFileSync(logFile, JSON.stringify(o) + "\n");
async function waitHold(envKey) {
const f = process.env[envKey];
if (!f) return;
while (existsSync(f)) await new Promise((r) => setTimeout(r, 15));
}
let threadId = "thread-1";
let turnSeq = 0;
/** @type {Map<string, { timer?: NodeJS.Timeout, finish: (status: string) => void }>} */
const openTurns = new Map();
createInterface({ input: process.stdin }).on("line", (line) => {
if (!line.trim()) return;
let m;
try { m = JSON.parse(line); } catch { return; }
log({ in: m });
if (!m.method) return;
const id = m.id;
const p = m.params ?? {};
switch (m.method) {
case "initialize":
return out({ id, result: { userAgent: "fake-codex" } });
case "initialized":
return;
case "thread/start":
case "thread/resume":
threadId = p.threadId || threadId;
return out({ id, result: { thread: { id: threadId } } });
case "turn/start": {
const turnId = `codex-turn-${++turnSeq}`;
const n = ++startCount;
const finish = (status) => {
const open = openTurns.get(turnId);
if (!open || open.finish !== finish) return;
if (open.timer) clearTimeout(open.timer);
openTurns.delete(turnId);
out({ method: "turn/completed", params: { turn: { id: turnId, status } } });
};
const start = async () => {
await waitHold("FAKE_CODEX_STARTED_HOLD_FILE");
out({ method: "turn/started", params: { turn: { id: turnId } } });
out({ method: "item/agentMessage/delta", params: { itemId: "m1", delta: "hi" } });
if (slowMs > 0) {
const timer = setTimeout(() => finish("completed"), slowMs);
openTurns.set(turnId, { timer, finish });
} else {
finish("completed");
}
};
const respond = async () => {
await waitHold("FAKE_CODEX_RESPONSE_HOLD_FILE");
out({ id, result: { turn: { id: turnId } } });
// Delay turn/started so tests can interrupt after turn/start's response but before the event
const startedWait = startedDelayMs != null
? startedDelayMs
: (slowMs > 0 ? Math.min(200, Math.max(80, Math.floor(slowMs / 4))) : 0);
if (startedWait > 0) setTimeout(() => { void start(); }, startedWait);
else void start();
};
// First turn/start only: delay the JSON-RPC *response* so Stop can race while in flight
const delay = n === 1 && startDelayMs > 0 ? startDelayMs : 0;
if (delay > 0) setTimeout(() => { void respond(); }, delay);
else void respond();
return;
}
case "turn/interrupt": {
const turnId = p.turnId;
out({ id, result: {} });
const open = openTurns.get(turnId);
if (open && !ignoreInterrupt) open.finish("interrupted");
return;
}
case "turn/steer":
return out({ id, result: {} });
default:
if (id !== undefined) out({ id, result: {} });
}
});
@@ -0,0 +1,24 @@
// Transport matrix: which of the 8 catalog agents share ACP session/cancel vs a custom interrupt path.
import { describe, expect, it } from "vitest";
import { PROVIDER_CATALOG } from "../../daemon/src/providers/catalog.js";
import { isAcpCatalogId, acpConfigForEntry } from "../../daemon/src/providers/acp/specs.js";
describe("interrupt transport audit", () => {
it("catalog has the 8 supported agents", () => {
expect(PROVIDER_CATALOG.map((e) => e.id)).toEqual([
"claude", "codex", "cursor", "copilot", "opencode", "pi", "devin", "dsh",
]);
});
it("Claude and Codex are custom; the other six share ACP AcpSession", () => {
const byId = Object.fromEntries(PROVIDER_CATALOG.map((e) => [e.id, e]));
expect(isAcpCatalogId("claude")).toBe(false);
expect(isAcpCatalogId("codex")).toBe(false);
for (const id of ["cursor", "copilot", "opencode", "pi", "devin", "dsh"]) {
expect(isAcpCatalogId(id)).toBe(true);
expect(acpConfigForEntry(byId[id], "test")).not.toBeNull();
}
expect(acpConfigForEntry(byId.claude, "test")).toBeNull();
expect(acpConfigForEntry(byId.codex, "test")).toBeNull();
});
});