Skip to content

Claude Code. Any Model. The most powerful AI coding agent now speaks every language.

fix(openai-codex): end a replayed script at the user's interrupt

Jack Rudenko819c52c22bc5
diff --git a/ai-docs/architecture/code-mode.md b/ai-docs/architecture/code-mode.md
index a4a73840..8d979212 100644
--- a/ai-docs/architecture/code-mode.md
+++ b/ai-docs/architecture/code-mode.md
@@ -183,7 +183,7 @@ for the same script.
| Situation (the last user message answers nested ids) | Behaviour |
|---|---|
| suspended, owned by this session, expected batch | results resolve or reject by seq (`is_error` rejects with a plain string, as Codex); missing → "no tool_result returned"; blocked again → **synthetic reply**; done → output stored, the upstream turn continues and the input builder renders it |
-| `[Request interrupted by user` beside the results | terminated: output so far, the results, "interrupted by the user"; continue |
+| `[Request interrupted by user` beside the results | terminated: output so far, the results, "interrupted by the user"; continue. A LOST record is replayed only up to the answered round and terminated there (never fed its results), so Esc yields no further tool call |
| consumed batch, same `batchHash` (a duplicate request) | the memoised step: the same synthetic reply, or the stored completion |
| consumed batch, different `batchHash` (a rewind that re-ran tools) | lost path, tombstone under the new completion key |
| suspended, owned by ANOTHER session (a fork) | untouched; the fork gets `Script failed` "this script belongs to the session this one was forked from; claudish cannot run it twice"; the owner's later run output wins every lookup |
diff --git a/packages/cli/src/code-mode/replay.ts b/packages/cli/src/code-mode/replay.ts
index 4bfd00f9..3c515659 100644
--- a/packages/cli/src/code-mode/replay.ts
+++ b/packages/cli/src/code-mode/replay.ts
@@ -20,12 +20,14 @@ import { log } from "../logger.js";
import { type ClaudeToolLike, renderExecTool } from "./exec-tool.js";
import { type BatchResultEntry, batchHash, canonicalJson, completionKey } from "./hashes.js";
import { decodeNestedId, encodeNestedId } from "./ids.js";
+import type { ExecOutput } from "./output.js";
import { nestedBlocksFor, settleDone, suspendBlocked } from "./relay.js";
import { type QuickJSModuleLease, currentQuickJSModule } from "./sandbox/quickjs-loader.js";
import {
type NestedCall,
type NestedResult,
type ScriptRuntime,
+ type ScriptStep,
createScriptRuntime,
} from "./sandbox/script-runtime.js";
import type { ExecRecord, ExecState, ScriptStore } from "./script-store.js";
@@ -49,6 +51,12 @@ export interface ReplayInput {
/** Claude Code's tools in this request (the identifiers the script calls). */
tools: readonly ClaudeToolLike[];
sessionKey: string;
+ /**
+ * The user interrupted (Esc) beside the last round's results: the script is
+ * re-run up to that round and ENDED there, never fed its results, so it can
+ * emit no further tool call — as the live path terminates on the same marker.
+ */
+ interrupted?: boolean;
/** Test seam; default the loaded module, if any. */
module?: QuickJSModuleLease;
}
@@ -56,6 +64,12 @@ export interface ReplayInput {
export type ReplayResult =
| { kind: "reply"; blocks: [NestedToolUse, ...NestedToolUse[]] }
| { kind: "done" }
+ /**
+ * Interrupted at the last round: `output` is what the script produced before
+ * it (the runtime is disposed, the record still `lost`); `key` is the
+ * completion key through that round. The caller adds the results and stores it.
+ */
+ | { kind: "interrupted"; output: ExecOutput; key: string }
| undefined;
function entriesOf(
@@ -100,13 +114,45 @@ function resultsFor(
return out;
}
+/**
+ * Feed history's rounds to a freshly started script, checking each batch it
+ * blocks on against the round. `stopped` is a divergence (undefined) or an
+ * interrupt at the last round; otherwise the step after the last round.
+ */
+function runRounds(
+ runtime: ScriptRuntime,
+ input: ReplayInput
+): { kind: "ran"; step: ScriptStep; hashes: string[] } | { kind: "stopped"; result: ReplayResult } {
+ const { record, rounds, results } = input;
+ let step = runtime.start(record.source);
+ const hashes: string[] = [];
+ for (const [k, round] of rounds.entries()) {
+ if (step.kind !== "blocked" || !matchesRound(record.execCallId, step.calls, round)) {
+ log(`[CodeMode] exec ${record.originalCallId}: replay diverged from history; script lost`);
+ runtime.dispose();
+ return { kind: "stopped", result: undefined };
+ }
+ hashes.push(batchHash(entriesOf(round.ids, results)));
+ if (input.interrupted && k === rounds.length - 1) {
+ const output = runtime.terminate("");
+ log(`[CodeMode] exec ${record.originalCallId}: replayed to the interrupt; terminated`);
+ return {
+ kind: "stopped",
+ result: { kind: "interrupted", output, key: completionKey(hashes) },
+ };
+ }
+ step = runtime.resume(resultsFor(round, results));
+ }
+ return { kind: "ran", step, hashes };
+}
+
/**
* Re-run `record`'s script against history. A blocked step past the last
* round is the script's next batch (reply); a finished one is stored. Undefined
* when the script is not replayable or diverged: the record stays lost.
*/
export function replayLostScript(input: ReplayInput): ReplayResult {
- const { record, rounds, results, scripts } = input;
+ const { record, rounds, scripts } = input;
if (record.state !== "lost" || record.batches.length === 0 || !record.source) return undefined;
if (rounds.length === 0) return undefined;
const lease = input.module ?? currentQuickJSModule();
@@ -121,17 +167,9 @@ export function replayLostScript(input: ReplayInput): ReplayResult {
module: lease,
onEvicted: () => scripts.loseIfRuntimeGone(record),
});
- let step = runtime.start(record.source);
- const hashes: string[] = [];
- for (const round of rounds) {
- if (step.kind !== "blocked" || !matchesRound(record.execCallId, step.calls, round)) {
- log(`[CodeMode] exec ${record.originalCallId}: replay diverged from history; script lost`);
- runtime.dispose();
- return undefined;
- }
- hashes.push(batchHash(entriesOf(round.ids, results)));
- step = runtime.resume(resultsFor(round, results));
- }
+ const ran = runRounds(runtime, input);
+ if (ran.kind !== "ran") return ran.result;
+ const { step, hashes } = ran;
scripts.transition(record, "replay");
scripts.attachRuntime(record, runtime);
record.batches = rounds.map((round, k) => ({ ids: round.ids, batchHash: hashes[k] }));
diff --git a/packages/cli/src/code-mode/resume.ts b/packages/cli/src/code-mode/resume.ts
index 5f870c36..16205478 100644
--- a/packages/cli/src/code-mode/resume.ts
+++ b/packages/cli/src/code-mode/resume.ts
@@ -258,9 +258,10 @@ class Resume {
interrupted: boolean
): ResumeOutcome {
const record = this.scripts.get(this.view.accountKey, execKey);
- // An evicted runtime whose source is kept: re-run it against history first.
+ // An evicted runtime whose source is kept: re-run it against history first
+ // (on an interrupt, only up to the answered round, then ended there).
if (record?.state === "lost" && record.sessionKey === this.view.sessionKey) {
- const replayed = this.replay(execKey, record, results);
+ const replayed = this.replay(execKey, record, results, interrupted);
if (replayed) return replayed;
}
// Restart, another account's record, eviction or a poisoned module: the
@@ -398,7 +399,8 @@ class Resume {
private replay(
execKey: string,
record: ExecRecord,
- lastResults: ReadonlyMap<string, ClaudeContentBlock>
+ lastResults: ReadonlyMap<string, ClaudeContentBlock>,
+ interrupted: boolean
): ResumeOutcome | undefined {
const rounds = this.historyRounds(execKey);
const answered = this.answeredRound(rounds, lastResults);
@@ -410,8 +412,24 @@ class Resume {
results: this.view.results,
tools: this.view.tools,
sessionKey: this.view.sessionKey,
+ interrupted,
});
if (!replayed) return undefined;
+ if (replayed.kind === "interrupted") {
+ // The live path's terminated output: what ran before the interrupt, the
+ // results it was waiting for, the note. No further tool call is emitted.
+ try {
+ const { output } = replayed;
+ output.parts.push(...resultParts(rounds[answered].ids, lastResults, this.view.toolUses));
+ output.parts.push({ type: "text", text: INTERRUPTED_NOTE });
+ this.scripts.storeOutput(record, replayed.key, output, "run", this.view.sessionKey);
+ this.scripts.transition(record, "terminate");
+ return { kind: "continue" };
+ } catch (err) {
+ log(`[CodeMode] exec ${record.originalCallId}: storing the interrupt failed: ${err}`);
+ return undefined;
+ }
+ }
return replayed.kind === "reply" ? replayed : { kind: "continue" };
}
diff --git a/packages/cli/src/code-mode/script-store.ts b/packages/cli/src/code-mode/script-store.ts
index 72e1a4d2..1903d8a5 100644
--- a/packages/cli/src/code-mode/script-store.ts
+++ b/packages/cli/src/code-mode/script-store.ts
@@ -17,7 +17,8 @@
* running: block → suspended, finish → completed, fail → failed
* suspended: resume → running, terminate → terminated, abandon → terminated,
* evict → lost, expire → lost
- * lost: answer → failed (tombstone stored), replay → running
+ * lost: answer → failed (tombstone stored), replay → running,
+ * terminate → terminated (replayed up to a user interrupt)
* completed / failed / terminated: answer → same state
*
* The catalog's table throws on an illegal transition. Here it is logged and
@@ -65,7 +66,7 @@ const TRANSITIONS: Record<ExecState, Partial<Record<ExecEvent, ExecState>>> = {
evict: "lost",
expire: "lost",
},
- lost: { answer: "failed", replay: "running" },
+ lost: { answer: "failed", replay: "running", terminate: "terminated" },
completed: { answer: "completed" },
failed: { answer: "failed" },
terminated: { answer: "terminated" },