Skip to content

Commit 9c33f86

Browse files
authored
fix: fence turn interrupt retries to the original prompt (#723)
## Summary Continues the original SDK 2.2 audit at specification baseline `d5e9949c3e6a9cd072adebaa44e6f63289590c17`. No later specification changes are included. The missing cancellation-crossing-next-prompt test exposed a real bug: an old `turn/interrupt` could return `no active turn to interrupt` after a newer prompt started. Retry eligibility checked only whether *any* prompt was active, then recomputed the turn ID from the newer prompt's state. The old cancellation could therefore interrupt work received after it. - Bind interrupt retries to the original active-prompt identity and its registered turn, rather than to the presence of any active prompt. - Recheck ownership after retry waits and while awaiting child interruption/pending turn starts. - Do not remap an explicit late turn ID through a newer prompt's registered state. - Keep legitimate same-prompt registration retries, including the existing shared v1 cancellation behavior. - Add a v2 wire regression matrix for acknowledgement-before-completion, completion-before-acknowledgement, and a delayed no-active-turn error. Earlier queued prompts are cancelled; later prompts run normally and are never targeted by the old interrupt. ## Validation - `npm run typecheck`: passed - `npm run build`: passed - `npm test`: 2,368 passed, 39 skipped - `npm run test:integration`: all 19 passed - `git diff --check`: passed The late-error regression failed before the implementation fix by observing an extra interrupt against `turn-2`. Existing v1 cancellation and retry tests pass unchanged. The real-Codex integration matrix covers normal cancellation and child ownership; the exact delayed-error race is injected through the native mock for deterministic wire coverage. Opt-in E2E tests were not run. This PR is independently based on main and does not include #720, #721, or #722. No review Markdown file is included.
1 parent 3720341 commit 9c33f86

2 files changed

Lines changed: 64 additions & 4 deletions

File tree

‎src/CodexAcpServer.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4374,12 +4374,14 @@ export class CodexAcpServer {
43744374
turn: { threadId: string, turnId: string },
43754375
requestName: "Cancel" | "Close",
43764376
): Promise<void> {
4377+
const activePrompt = this.activePrompts.get(sessionState.sessionId);
43774378
this.codexAcpClient.markTurnStale({
43784379
threadId: turn.threadId,
43794380
turnId: turn.turnId,
43804381
});
43814382
try {
43824383
await this.interruptStandardChildren(sessionState);
4384+
if (this.activePrompts.get(sessionState.sessionId) !== activePrompt) return;
43834385
await this.requestTurnInterrupt(sessionState, turn.threadId, turn.turnId, requestName);
43844386
} finally {
43854387
this.codexAcpClient.resolveTurnInterrupted({
@@ -4395,6 +4397,7 @@ export class CodexAcpServer {
43954397
* interrupt", and once it registers a later turn under a different id, "expected active turn
43964398
* id <completionTurnId> but found <Y>". Both are retried, with the id recomputed on every
43974399
* attempt so a `turn/started` that arrives between retries is picked up.
4400+
* Retries belong to that prompt, not to a newer prompt that starts while a reply is pending.
43984401
*/
43994402
private async requestTurnInterrupt(
44004403
sessionState: SessionState,
@@ -4407,7 +4410,12 @@ export class CodexAcpServer {
44074410
logger.log(`${requestName} - turnInterrupt skipped: the app-server of the turn is gone`, {sessionId: threadId});
44084411
return;
44094412
}
4410-
let turnId = codexRunningTurnId(sessionState, completionTurnId);
4413+
const activePrompt = this.activePrompts.get(sessionState.sessionId);
4414+
const ownsRegisteredTurn = activePrompt?.currentTurn?.threadId === threadId
4415+
&& activePrompt.currentTurn.turnId === completionTurnId;
4416+
const stillOwnsPrompt = () => ownsRegisteredTurn && activePrompt !== undefined
4417+
&& this.activePrompts.get(sessionState.sessionId) === activePrompt;
4418+
let turnId = ownsRegisteredTurn ? codexRunningTurnId(sessionState, completionTurnId) : completionTurnId;
44114419
for (let attempt = 0; ; attempt++) {
44124420
try {
44134421
await this.runWithProcessCheck(() => this.codexAcpClient.turnInterrupt({
@@ -4420,12 +4428,11 @@ export class CodexAcpServer {
44204428
});
44214429
return;
44224430
} catch (err) {
4423-
const promptStillActive = this.activePrompts.has(threadId);
44244431
const mismatch = parseExpectedActiveTurnMismatch(err);
44254432
const isMismatch = mismatch !== null
44264433
&& mismatch.expected === sessionState.currentTurnId
44274434
&& mismatch.found !== "";
4428-
const retryable = promptStillActive
4435+
const retryable = stillOwnsPrompt()
44294436
&& (isNoActiveTurnError(err) || isMismatch)
44304437
&& attempt < NO_ACTIVE_TURN_RETRY_DELAYS_MS.length;
44314438
if (!retryable) {
@@ -4438,6 +4445,7 @@ export class CodexAcpServer {
44384445
// to completion and answer `end_turn`, which ACP forbids after a
44394446
// `session/cancel`.
44404447
await new Promise(resolve => setTimeout(resolve, NO_ACTIVE_TURN_RETRY_DELAYS_MS[attempt]!));
4448+
if (!stillOwnsPrompt()) return;
44414449
// Recompute after the wait: a `turn/started` may have landed in the meantime, and
44424450
// `interruptTurnId` always wins once it is set. Otherwise fall back to the id Codex
44434451
// just reported as active, or to the id we started with.
@@ -4470,9 +4478,11 @@ export class CodexAcpServer {
44704478
requestName: "Cancel" | "Close",
44714479
resolveInterruptedTurn: boolean,
44724480
): Promise<void> {
4481+
const activePrompt = this.activePrompts.get(sessionState.sessionId);
44734482
await this.interruptStandardChildren(sessionState);
4483+
if (this.activePrompts.get(sessionState.sessionId) !== activePrompt) return;
44744484
const turnId = await this.getInterruptibleTurnId(sessionState, requestName);
4475-
if (!turnId) {
4485+
if (!turnId || this.activePrompts.get(sessionState.sessionId) !== activePrompt) {
44764486
return;
44774487
}
44784488

‎src/__tests__/CodexACPAgent/cancel-v2.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,6 +136,56 @@ describe('session/cancel and session/close over ACP v2', () => {
136136
]);
137137
});
138138

139+
it.each(["ack-before-end", "end-before-ack", "late-no-active"] as const)(
140+
"does not cancel a later prompt while an older interrupt is pending (%s)", async ordering => {
141+
const client = await connectSession();
142+
closeClient = () => client.connection.close();
143+
const interrupting = deferred<void>();
144+
const release = deferred<void>();
145+
const cancel = vi.spyOn(client.agent, "cancel");
146+
let interrupts = 0;
147+
client.setCodexResponse("turn/interrupt", async () => {
148+
if (++interrupts === 1) {
149+
interrupting.resolve();
150+
await release.promise;
151+
if (ordering === "late-no-active") throw new Error("no active turn to interrupt");
152+
}
153+
return {};
154+
});
155+
try {
156+
const first = client.sendPrompt([{type: "text", text: "First"}]);
157+
await vi.waitFor(() => expect(client.turnStartParams).toHaveLength(1));
158+
client.emit(turnStarted());
159+
client.emit(itemCompleted(userMessageItem(client.turnStartParams[0]!["clientUserMessageId"] as string)));
160+
await first;
161+
const beforeCancel = client.sendPrompt([{type: "text", text: "Before cancellation"}]);
162+
await settle();
163+
await client.cancel();
164+
await interrupting.promise;
165+
await expect(beforeCancel).rejects.toMatchObject({code: -32800});
166+
const afterCancel = client.sendPrompt([{type: "text", text: "After cancellation"}]);
167+
await settle();
168+
expect(client.turnStartParams).toHaveLength(1);
169+
if (ordering === "ack-before-end") release.resolve();
170+
client.emit(turnFinished("interrupted"));
171+
await vi.waitFor(() => expect(client.turnStartParams).toHaveLength(2));
172+
client.emit(turnStarted("turn-2"));
173+
const messageId = client.turnStartParams[1]!["clientUserMessageId"] as string;
174+
client.emit(itemCompleted(userMessageItem(messageId, "After cancellation"), "turn-2"));
175+
await expect(afterCancel).resolves.toEqual(expect.objectContaining({messageId}));
176+
release.resolve();
177+
await cancel.mock.results[0]!.value;
178+
expect(client.turnInterruptCalls()).toEqual([{threadId: sessionId, turnId}]);
179+
client.emit(turnCompleted("turn-2"));
180+
await client.promptRunFinished(1);
181+
await settle();
182+
expect(stateUpdates(client.transcript).at(-1)).toEqual({state: "idle", stopReason: "end_turn"});
183+
} finally {
184+
release.resolve();
185+
}
186+
},
187+
);
188+
139189
it('drops a queued prompt with -32800 on session/close', async () => {
140190
const client = await connectSession();
141191
closeClient = null; // closeSession below already tears the session down.

0 commit comments

Comments
 (0)