The best way to control Claude Code, Codex and more from any computer or phone
fix(server): show why Codex hooks stopped a turn (#27399)
Co-authored-by: maria-rcks <maria@kuuro.net>
Lakshmi Tanmay committed
Nov 2, 2026 at 03:14 UTC
9b7208832eedaf9d3a8ab9002bbe3adcb313a921
7 files changed
+185
-21
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+110
@@ -2366,6 +2366,116 @@ describe("CodexAdapterV2 post-settle continuation", () => {
2366
),
2367
);
2368
2369
+ it.effect.each([
2370
+ { hook: "stopped", status: "interrupted", expected: true },
2371
+ { hook: "completed", status: "interrupted", expected: false },
2372
+ { hook: "warning", status: "interrupted", expected: false },
2373
+ { hook: "empty", status: "interrupted", expected: false },
2374
+ { hook: "wrong-turn", status: "interrupted", expected: false },
2375
+ { hook: "wrong-thread", status: "interrupted", expected: false },
2376
+ { hook: "unscoped", status: "interrupted", expected: false },
2377
+ { hook: "stopped", status: "completed", expected: false },
2378
+ { hook: "stopped", status: "failed", expected: false },
2379
+ ] as const)(
2380
+ "correlates $hook hook output with a $status turn only",
2381
+ ({ hook, status, expected }) =>
2382
+ Effect.gen(function* () {
2383
+ const nativeThreadId = "hook-thread";
2384
+ const stopReason = "Save a current task checkpoint before compaction.";
2385
+ const hookCompleted = (turnId: string | null) => ({
2386
+ type: "emit_inbound" as const,
2387
+ label: "hook/completed",
2388
+ frame: {
2389
+ method: "hook/completed",
2390
+ params: {
2391
+ threadId: hook === "wrong-thread" ? "other-thread" : nativeThreadId,
2392
+ turnId: hook === "unscoped" ? null : hook === "wrong-turn" ? "other-turn" : turnId,
2393
+ run: {
2394
+ id: "checkpoint-hook",
2395
+ eventName: "preCompact",
2396
+ source: "project",
2397
+ sourcePath: "/workspace/.codex/hooks.json",
2398
+ scope: "turn",
2399
+ executionMode: "sync",
2400
+ handlerType: "command",
2401
+ displayOrder: 1,
2402
+ startedAt: 1782622440,
2403
+ status: hook === "completed" ? "completed" : "stopped",
2404
+ entries: [
2405
+ { kind: "warning", text: "Unrelated hook diagnostic" },
2406
+ {
2407
+ kind: hook === "warning" ? "warning" : "stop",
2408
+ text: hook === "empty" ? " " : stopReason,
2409
+ },
2410
+ ],
2411
+ },
2412
+ },
2413
+ },
2414
+ });
2415
+ const transcript = makeCodexReplayTranscript({
2416
+ scenario: `hook-stop-${hook}-${status}`,
2417
+ entries: [
2418
+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "hook-turn", prompt: "work" }),
2419
+ hookCompleted("hook-turn"),
2420
+ {
2421
+ type: "emit_inbound",
2422
+ label: "turn/completed",
2423
+ frame: {
2424
+ method: "turn/completed",
2425
+ params: {
2426
+ threadId: nativeThreadId,
2427
+ turn: makeCodexReplayTurn({ id: "hook-turn", status }),
2428
+ },
2429
+ },
2430
+ },
2431
+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "next-turn", prompt: "work" })
2432
+ .slice(-3)
2433
+ .map((entry, index) => (index < 2 ? withReplayRequestId(entry, 4) : entry)),
2434
+ hookCompleted("hook-turn"),
2435
+ {
2436
+ type: "emit_inbound",
2437
+ label: "turn/completed/next",
2438
+ frame: {
2439
+ method: "turn/completed",
2440
+ params: {
2441
+ threadId: nativeThreadId,
2442
+ turn: makeCodexReplayTurn({ id: "next-turn", status: "interrupted" }),
2443
+ },
2444
+ },
2445
+ },
2446
+ ],
2447
+ });
2448
+ const harness = yield* makeCodexReplayHarness(transcript);
2449
+ for (const turn of ["hook-turn", "next-turn"]) {
2450
+ yield* harness.runtime.startTurn(
2451
+ makeCodexTestTurnInput({
2452
+ threadId: harness.threadId,
2453
+ providerThread: harness.providerThread,
2454
+ now: yield* DateTime.now,
2455
+ attemptId: RunAttemptId.make(turn),
2456
+ text: "work",
2457
+ }),
2458
+ );
2459
+ yield* harness.awaitTerminal(turn === "hook-turn" ? 1 : 2);
2460
+ }
2461
+ assert.deepEqual(
2462
+ harness.terminalEvents().map((event) => ({
2463
+ status: event.status,
2464
+ reason: event.status === "failed" ? undefined : event.reason,
2465
+ })),
2466
+ [
2467
+ { status, reason: expected ? `preCompact hook (project): ${stopReason}` : undefined },
2468
+ { status: "interrupted", reason: undefined },
2469
+ ],
2470
+ );
2471
+ }).pipe(
2472
+ Effect.scoped,
2473
+ Effect.provide(
2474
+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),
2475
+ ),
2476
+ ),
2477
+ );
2478
+
2479
it.effect("resumes a provider thread without requesting or decoding its history", () =>
2480
Effect.scoped(
2481
Effect.gen(function* () {
apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+20
@@ -1120,6 +1120,7 @@ function withCodexManagedFailure(
1120
}
1121
1122
interface ActiveCodexTurnContext {
1123
+ hookStopReason?: string;
1124
capacityRetryAttempt?: number;
1125
capacityRetryPending?: Deferred.Deferred<ActiveCodexTurnContext | undefined>;
1126
closedCommandItemIds?: ReadonlySet<string>;
@@ -4479,6 +4480,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
4480
updateSubagentSelection(payload.threadId, payload.toModel),
4481
);
4482
4483
+ yield* client.handleServerNotification("hook/completed", (payload) =>
4484
+ Effect.gen(function* () {
4485
+ if (payload.turnId == null || payload.run.status !== "stopped") return;
4486
+ const context = (yield* Ref.get(activeTurns)).get(payload.turnId);
4487
+ if (context?.providerThread.nativeThreadRef?.nativeId !== payload.threadId) return;
4488
+ const reason = payload.run.entries
4489
+ .filter((entry) => entry.kind === "stop")
4490
+ .map((entry) => entry.text.trim())
4491
+ .filter(Boolean)
4492
+ .join("\n");
4493
+ if (!reason) return;
4494
+ const source = payload.run.source === undefined ? "" : ` (${payload.run.source})`;
4495
+ context.hookStopReason = `${payload.run.eventName} hook${source}: ${reason}`;
4496
+ }),
4497
+ );
4498
+
4499
yield* client.handleServerNotification("turn/started", (payload) =>
4500
Effect.gen(function* () {
4501
const context = (yield* Ref.get(activeTurns)).get(payload.turn.id);
@@ -5746,6 +5763,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
5763
runOrdinal: input.context.input.runOrdinal,
5764
status: terminalStatus,
5765
failure: null,
5766
+ ...(terminalStatus === "interrupted" && input.context.hookStopReason !== undefined
5767
+ ? { reason: input.context.hookStopReason }
5768
+ : {}),
5769
threadDisposition: "reusable",
5770
};
5771
},
apps/server/src/orchestration-v2/RunExecutionService.test.ts
+41
-16
@@ -2561,22 +2561,43 @@ it.effect("does not overwrite Stop when ownership changes after the finalization
2561
}),
2562
);
2563
2564
-it.effect("emits run_interrupt_result when hard-stop finalizes the active attempt", () =>
2565
- Effect.gen(function* () {
2566
- const { written, observed, committedEffects } = yield* captureRootRunTermination({
2567
- key: "hard-stop",
2568
- shouldFinalizeRun: () => Effect.succeed(true),
2569
- });
2570
- assert.deepEqual(
2571
- written.map((item) => item.type),
2572
- ["run_interrupt_result"],
2573
- );
2574
- assert.deepEqual(observed, ["run:interrupted", "pull-requests-refreshed"]);
2575
- assert.deepEqual(
2576
- committedEffects.map((effect) => effect.request.type),
2577
- ["checkpoint.capture"],
2578
- );
2579
- }),
2564
+it.effect.each([
2565
+ { providerReason: undefined, requestReason: undefined, expected: "Stopped by the provider" },
2566
+ {
2567
+ providerReason: "preCompact hook (project): Save a checkpoint.",
2568
+ requestReason: undefined,
2569
+ expected: "preCompact hook (project): Save a checkpoint.",
2570
+ },
2571
+ {
2572
+ providerReason: "preCompact hook (project): Save a checkpoint.",
2573
+ requestReason: "Stopped by the user",
2574
+ expected: "Stopped by the user",
2575
+ },
2576
+])(
2577
+ "emits run_interrupt_result with $expected when finalizing the active attempt",
2578
+ ({ providerReason, requestReason, expected }) =>
2579
+ Effect.gen(function* () {
2580
+ const { written, observed, committedEffects } = yield* captureRootRunTermination({
2581
+ key: "hard-stop",
2582
+ shouldFinalizeRun: () => Effect.succeed(true),
2583
+ loadRunInterruptReason: () => Effect.succeed(requestReason),
2584
+ events: (ids) =>
2585
+ Stream.make({ ...rootTerminalEvent(ids, "interrupted"), reason: providerReason }),
2586
+ });
2587
+ assert.deepEqual(
2588
+ written.map((item) => item.type),
2589
+ ["run_interrupt_result"],
2590
+ );
2591
+ assert.deepEqual(observed, ["run:interrupted", "pull-requests-refreshed"]);
2592
+ assert.equal(
2593
+ written[0]?.type === "run_interrupt_result" ? written[0].message : undefined,
2594
+ expected,
2595
+ );
2596
+ assert.deepEqual(
2597
+ committedEffects.map((effect) => effect.request.type),
2598
+ ["checkpoint.capture"],
2599
+ );
2600
+ }),
2601
);
2602
2603
it.effect("records a finished run as failed when its ownership check cannot be read", () =>
@@ -3054,6 +3075,7 @@ function captureRootRunTermination(input: {
3075
readonly shouldFinalizeRun: () => Effect.Effect<boolean, ProjectionStore.ProjectionStoreV2Error>;
3076
readonly rejectTerminalWrite?: boolean;
3077
readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;
3078
+ readonly loadRunInterruptReason?: () => Effect.Effect<string | undefined, never>;
3079
readonly hasPendingBackgroundWorkForThread?: ProviderAdapter.ProviderAdapterV2SessionRuntime["hasPendingBackgroundWorkForThread"];
3080
readonly seedOpenSubagent?: boolean;
3081
readonly events?: (
@@ -3238,6 +3260,9 @@ function captureRootRunTermination(input: {
3260
attemptId: ids.attemptId,
3261
providerTurnOrdinal: 1,
3262
shouldFinalizeRun: input.shouldFinalizeRun,
3263
+ ...(input.loadRunInterruptReason === undefined
3264
+ ? {}
3265
+ : { loadRunInterruptReason: input.loadRunInterruptReason }),
3266
...(input.shouldStartProviderTurn === undefined
3267
? {}
3268
: { shouldStartProviderTurn: input.shouldStartProviderTurn }),
apps/server/src/orchestration-v2/RunExecutionService.ts
+4
-3
@@ -686,8 +686,10 @@ export const layer: Layer.Layer<
686
}
687
const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId });
688
const reason =
689
- input.terminal.status === "interrupted" && input.loadRunInterruptReason !== undefined
690
- ? yield* input.loadRunInterruptReason()
689
+ input.terminal.status === "interrupted"
690
+ ? ((input.loadRunInterruptReason === undefined
691
+ ? undefined
692
+ : yield* input.loadRunInterruptReason()) ?? input.terminal.reason)
693
: undefined;
694
const open = input.openRunOwnedSubagents ?? emptyOpenRunOwnedSubagentProjection();
695
const hasOpenSubagentProjection =
@@ -1775,7 +1777,6 @@ export function makeInterruptResultTurnItem(input: {
1777
readonly run: OrchestrationV2Run;
1778
readonly rootNode: OrchestrationV2ExecutionNode;
1779
readonly providerThread: OrchestrationV2ProviderThread;
1778
- /** The Stop's own reason, from its run_interrupt_request item. */
1780
readonly reason: string | undefined;
1781
readonly completedAt: DateTime.Utc;
1782
}): OrchestrationV2TurnItem {
apps/web/src/components/chat/TimelineSystemDivider.tsx
+3
-1
@@ -10,6 +10,7 @@ export function TimelineSystemDivider(props: {
10
readonly tone?: "neutral" | "danger";
11
readonly icon?: LucideIcon;
12
readonly showDetailSeparator?: boolean;
13
+ readonly wrapDetail?: boolean;
14
readonly actionLabel?: string;
15
readonly onAction?: () => void;
16
}) {
@@ -22,7 +23,8 @@ export function TimelineSystemDivider(props: {
23
<span
24
className={cn(
25
"inline-flex min-w-0 items-center opacity-70",
25
- typeof props.detail === "string" && "max-w-80 truncate",
26
+ typeof props.detail === "string" &&
27
+ (props.wrapDetail ? "max-w-80 whitespace-pre-wrap" : "max-w-80 truncate"),
28
)}
29
>
30
{props.showDetailSeparator === false ? null : "·\u00a0"}
apps/web/src/components/chat/V2LifecycleRow.tsx
+6
-1
@@ -73,7 +73,12 @@ export function V2LifecycleRow(props: {
73
const { item } = props;
74
if (item.type === "run_interrupt_result") {
75
return (
76
- <TimelineSystemDivider label="Run interrupted" detail={item.message} icon={CircleStopIcon} />
76
+ <TimelineSystemDivider
77
+ label="Run interrupted"
78
+ detail={item.message}
79
+ icon={CircleStopIcon}
80
+ wrapDetail
81
+ />
82
);
83
}
84
if (item.type === "handoff") {
packages/provider-core/src/server/ProviderAdapter.ts
+1
@@ -159,6 +159,7 @@ export const ProviderAdapterV2Event = Schema.Union([
159
runOrdinal: PositiveInt,
160
status: Schema.Literals(["completed", "interrupted", "cancelled"]),
161
failure: Schema.Null,
162
+ reason: Schema.optional(Schema.String),
163
threadDisposition: Schema.Literals(["reusable", "broken"]),
164
}),
165
Schema.Struct({