TypeScript
fix(server): show why Codex hooks stopped a turn (#27399)
Lakshmi Tanmay9b7208832eed
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.tsindex 90ee44f3d5b..8e73db37843 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts@@ -2366,6 +2366,116 @@ describe("CodexAdapterV2 post-settle continuation", () => {),);+ it.effect.each([+ { hook: "stopped", status: "interrupted", expected: true },+ { hook: "completed", status: "interrupted", expected: false },+ { hook: "warning", status: "interrupted", expected: false },+ { hook: "empty", status: "interrupted", expected: false },+ { hook: "wrong-turn", status: "interrupted", expected: false },+ { hook: "wrong-thread", status: "interrupted", expected: false },+ { hook: "unscoped", status: "interrupted", expected: false },+ { hook: "stopped", status: "completed", expected: false },+ { hook: "stopped", status: "failed", expected: false },+ ] as const)(+ "correlates $hook hook output with a $status turn only",+ ({ hook, status, expected }) =>+ Effect.gen(function* () {+ const nativeThreadId = "hook-thread";+ const stopReason = "Save a current task checkpoint before compaction.";+ const hookCompleted = (turnId: string | null) => ({+ type: "emit_inbound" as const,+ label: "hook/completed",+ frame: {+ method: "hook/completed",+ params: {+ threadId: hook === "wrong-thread" ? "other-thread" : nativeThreadId,+ turnId: hook === "unscoped" ? null : hook === "wrong-turn" ? "other-turn" : turnId,+ run: {+ id: "checkpoint-hook",+ eventName: "preCompact",+ source: "project",+ sourcePath: "/workspace/.codex/hooks.json",+ scope: "turn",+ executionMode: "sync",+ handlerType: "command",+ displayOrder: 1,+ startedAt: 1782622440,+ status: hook === "completed" ? "completed" : "stopped",+ entries: [+ { kind: "warning", text: "Unrelated hook diagnostic" },+ {+ kind: hook === "warning" ? "warning" : "stop",+ text: hook === "empty" ? " " : stopReason,+ },+ ],+ },+ },+ },+ });+ const transcript = makeCodexReplayTranscript({+ scenario: `hook-stop-${hook}-${status}`,+ entries: [+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "hook-turn", prompt: "work" }),+ hookCompleted("hook-turn"),+ {+ type: "emit_inbound",+ label: "turn/completed",+ frame: {+ method: "turn/completed",+ params: {+ threadId: nativeThreadId,+ turn: makeCodexReplayTurn({ id: "hook-turn", status }),+ },+ },+ },+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId: "next-turn", prompt: "work" })+ .slice(-3)+ .map((entry, index) => (index < 2 ? withReplayRequestId(entry, 4) : entry)),+ hookCompleted("hook-turn"),+ {+ type: "emit_inbound",+ label: "turn/completed/next",+ frame: {+ method: "turn/completed",+ params: {+ threadId: nativeThreadId,+ turn: makeCodexReplayTurn({ id: "next-turn", status: "interrupted" }),+ },+ },+ },+ ],+ });+ const harness = yield* makeCodexReplayHarness(transcript);+ for (const turn of ["hook-turn", "next-turn"]) {+ yield* harness.runtime.startTurn(+ makeCodexTestTurnInput({+ threadId: harness.threadId,+ providerThread: harness.providerThread,+ now: yield* DateTime.now,+ attemptId: RunAttemptId.make(turn),+ text: "work",+ }),+ );+ yield* harness.awaitTerminal(turn === "hook-turn" ? 1 : 2);+ }+ assert.deepEqual(+ harness.terminalEvents().map((event) => ({+ status: event.status,+ reason: event.status === "failed" ? undefined : event.reason,+ })),+ [+ { status, reason: expected ? `preCompact hook (project): ${stopReason}` : undefined },+ { status: "interrupted", reason: undefined },+ ],+ );+ }).pipe(+ Effect.scoped,+ Effect.provide(+ Layer.mergeAll(IdAllocator.layer, McpProviderSessions.layer, NodeServices.layer),+ ),+ ),+ );+it.effect("resumes a provider thread without requesting or decoding its history", () =>Effect.scoped(Effect.gen(function* () {diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.tsindex 821cf051c32..1003ea48b12 100644--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts@@ -1120,6 +1120,7 @@ function withCodexManagedFailure(}interface ActiveCodexTurnContext {+ hookStopReason?: string;capacityRetryAttempt?: number;capacityRetryPending?: Deferred.Deferred<ActiveCodexTurnContext | undefined>;closedCommandItemIds?: ReadonlySet<string>;@@ -4479,6 +4480,22 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (updateSubagentSelection(payload.threadId, payload.toModel),);+ yield* client.handleServerNotification("hook/completed", (payload) =>+ Effect.gen(function* () {+ if (payload.turnId == null || payload.run.status !== "stopped") return;+ const context = (yield* Ref.get(activeTurns)).get(payload.turnId);+ if (context?.providerThread.nativeThreadRef?.nativeId !== payload.threadId) return;+ const reason = payload.run.entries+ .filter((entry) => entry.kind === "stop")+ .map((entry) => entry.text.trim())+ .filter(Boolean)+ .join("\n");+ if (!reason) return;+ const source = payload.run.source === undefined ? "" : ` (${payload.run.source})`;+ context.hookStopReason = `${payload.run.eventName} hook${source}: ${reason}`;+ }),+ );+yield* client.handleServerNotification("turn/started", (payload) =>Effect.gen(function* () {const context = (yield* Ref.get(activeTurns)).get(payload.turn.id);@@ -5746,6 +5763,9 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (runOrdinal: input.context.input.runOrdinal,status: terminalStatus,failure: null,+ ...(terminalStatus === "interrupted" && input.context.hookStopReason !== undefined+ ? { reason: input.context.hookStopReason }+ : {}),threadDisposition: "reusable",};},diff --git a/apps/server/src/orchestration-v2/RunExecutionService.test.ts b/apps/server/src/orchestration-v2/RunExecutionService.test.tsindex dee246855b8..1cbd164b9e6 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.test.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.test.ts@@ -2561,22 +2561,43 @@ it.effect("does not overwrite Stop when ownership changes after the finalization}),);-it.effect("emits run_interrupt_result when hard-stop finalizes the active attempt", () =>- Effect.gen(function* () {- const { written, observed, committedEffects } = yield* captureRootRunTermination({- key: "hard-stop",- shouldFinalizeRun: () => Effect.succeed(true),- });- assert.deepEqual(- written.map((item) => item.type),- ["run_interrupt_result"],- );- assert.deepEqual(observed, ["run:interrupted", "pull-requests-refreshed"]);- assert.deepEqual(- committedEffects.map((effect) => effect.request.type),- ["checkpoint.capture"],- );- }),+it.effect.each([+ { providerReason: undefined, requestReason: undefined, expected: "Stopped by the provider" },+ {+ providerReason: "preCompact hook (project): Save a checkpoint.",+ requestReason: undefined,+ expected: "preCompact hook (project): Save a checkpoint.",+ },+ {+ providerReason: "preCompact hook (project): Save a checkpoint.",+ requestReason: "Stopped by the user",+ expected: "Stopped by the user",+ },+])(+ "emits run_interrupt_result with $expected when finalizing the active attempt",+ ({ providerReason, requestReason, expected }) =>+ Effect.gen(function* () {+ const { written, observed, committedEffects } = yield* captureRootRunTermination({+ key: "hard-stop",+ shouldFinalizeRun: () => Effect.succeed(true),+ loadRunInterruptReason: () => Effect.succeed(requestReason),+ events: (ids) =>+ Stream.make({ ...rootTerminalEvent(ids, "interrupted"), reason: providerReason }),+ });+ assert.deepEqual(+ written.map((item) => item.type),+ ["run_interrupt_result"],+ );+ assert.deepEqual(observed, ["run:interrupted", "pull-requests-refreshed"]);+ assert.equal(+ written[0]?.type === "run_interrupt_result" ? written[0].message : undefined,+ expected,+ );+ assert.deepEqual(+ committedEffects.map((effect) => effect.request.type),+ ["checkpoint.capture"],+ );+ }),);it.effect("records a finished run as failed when its ownership check cannot be read", () =>@@ -3054,6 +3075,7 @@ function captureRootRunTermination(input: {readonly shouldFinalizeRun: () => Effect.Effect<boolean, ProjectionStore.ProjectionStoreV2Error>;readonly rejectTerminalWrite?: boolean;readonly hasUnpairedRunInterruptRequest?: () => Effect.Effect<boolean, never>;+ readonly loadRunInterruptReason?: () => Effect.Effect<string | undefined, never>;readonly hasPendingBackgroundWorkForThread?: ProviderAdapter.ProviderAdapterV2SessionRuntime["hasPendingBackgroundWorkForThread"];readonly seedOpenSubagent?: boolean;readonly events?: (@@ -3238,6 +3260,9 @@ function captureRootRunTermination(input: {attemptId: ids.attemptId,providerTurnOrdinal: 1,shouldFinalizeRun: input.shouldFinalizeRun,+ ...(input.loadRunInterruptReason === undefined+ ? {}+ : { loadRunInterruptReason: input.loadRunInterruptReason }),...(input.shouldStartProviderTurn === undefined? {}: { shouldStartProviderTurn: input.shouldStartProviderTurn }),diff --git a/apps/server/src/orchestration-v2/RunExecutionService.ts b/apps/server/src/orchestration-v2/RunExecutionService.tsindex b9b2b09bd22..780ee76437f 100644--- a/apps/server/src/orchestration-v2/RunExecutionService.ts+++ b/apps/server/src/orchestration-v2/RunExecutionService.ts@@ -686,8 +686,10 @@ export const layer: Layer.Layer<}const allocateEventId = () => idAllocator.allocate.event({ threadId: input.run.threadId });const reason =- input.terminal.status === "interrupted" && input.loadRunInterruptReason !== undefined- ? yield* input.loadRunInterruptReason()+ input.terminal.status === "interrupted"+ ? ((input.loadRunInterruptReason === undefined+ ? undefined+ : yield* input.loadRunInterruptReason()) ?? input.terminal.reason): undefined;const open = input.openRunOwnedSubagents ?? emptyOpenRunOwnedSubagentProjection();const hasOpenSubagentProjection =@@ -1775,7 +1777,6 @@ export function makeInterruptResultTurnItem(input: {readonly run: OrchestrationV2Run;readonly rootNode: OrchestrationV2ExecutionNode;readonly providerThread: OrchestrationV2ProviderThread;- /** The Stop's own reason, from its run_interrupt_request item. */readonly reason: string | undefined;readonly completedAt: DateTime.Utc;}): OrchestrationV2TurnItem {diff --git a/apps/web/src/components/chat/TimelineSystemDivider.tsx b/apps/web/src/components/chat/TimelineSystemDivider.tsxindex 85724d862e8..825b2f79edd 100644--- a/apps/web/src/components/chat/TimelineSystemDivider.tsx+++ b/apps/web/src/components/chat/TimelineSystemDivider.tsx@@ -10,6 +10,7 @@ export function TimelineSystemDivider(props: {readonly tone?: "neutral" | "danger";readonly icon?: LucideIcon;readonly showDetailSeparator?: boolean;+ readonly wrapDetail?: boolean;readonly actionLabel?: string;readonly onAction?: () => void;}) {@@ -22,7 +23,8 @@ export function TimelineSystemDivider(props: {<spanclassName={cn("inline-flex min-w-0 items-center opacity-70",- typeof props.detail === "string" && "max-w-80 truncate",+ typeof props.detail === "string" &&+ (props.wrapDetail ? "max-w-80 whitespace-pre-wrap" : "max-w-80 truncate"),)}>{props.showDetailSeparator === false ? null : "·\u00a0"}diff --git a/apps/web/src/components/chat/V2LifecycleRow.tsx b/apps/web/src/components/chat/V2LifecycleRow.tsxindex d9320d71488..446585e5fd8 100644--- a/apps/web/src/components/chat/V2LifecycleRow.tsx+++ b/apps/web/src/components/chat/V2LifecycleRow.tsx@@ -73,7 +73,12 @@ export function V2LifecycleRow(props: {const { item } = props;if (item.type === "run_interrupt_result") {return (- <TimelineSystemDivider label="Run interrupted" detail={item.message} icon={CircleStopIcon} />+ <TimelineSystemDivider+ label="Run interrupted"+ detail={item.message}+ icon={CircleStopIcon}+ wrapDetail+ />);}if (item.type === "handoff") {diff --git a/packages/provider-core/src/server/ProviderAdapter.ts b/packages/provider-core/src/server/ProviderAdapter.tsindex a3332fe0319..a92256d7dd7 100644--- a/packages/provider-core/src/server/ProviderAdapter.ts+++ b/packages/provider-core/src/server/ProviderAdapter.ts@@ -159,6 +159,7 @@ export const ProviderAdapterV2Event = Schema.Union([runOrdinal: PositiveInt,status: Schema.Literals(["completed", "interrupted", "cancelled"]),failure: Schema.Null,+ reason: Schema.optional(Schema.String),threadDisposition: Schema.Literals(["reusable", "broken"]),}),Schema.Struct({