Skip to content
TypeScript

fix(codex): settle compaction items when turns end (#17265)

lukeccae51a814df
diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
index c1622f04869..49c3e53375a 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts
@@ -3322,6 +3322,143 @@ describe("CodexAdapterV2 post-settle continuation", () => {
),
);
+ it.effect.each(["failed", "interrupted", "Stop"] as const)(
+ "settles unfinished compaction on %s without changing completed compaction",
+ (outcome) =>
+ Effect.scoped(
+ Effect.gen(function* () {
+ const nativeThreadId = "compact-thread";
+ const nativeTurnId = "compact-turn";
+ const error = {
+ message: "Remote compaction stream disconnected",
+ codexErrorInfo: "other",
+ additionalDetails: null,
+ };
+ const transcript = makeCodexReplayTranscript({
+ scenario: `automatic-compaction-${outcome}`,
+ entries: [
+ ...codexReplayPreamble({ nativeThreadId, nativeTurnId, prompt: "Continue." }),
+ ...(
+ [
+ { method: "item/started", id: "completed-item", startedAtMs: 1782622441000 },
+ { method: "item/completed", id: "completed-item", completedAtMs: 1782622442000 },
+ { method: "item/started", id: "unfinished-item", startedAtMs: 1782622443000 },
+ ] as const
+ ).map(({ method, id, ...timestamps }) => ({
+ type: "emit_inbound" as const,
+ label: `${method}/${id}`,
+ frame: {
+ method,
+ params: {
+ threadId: nativeThreadId,
+ turnId: nativeTurnId,
+ item: { type: "contextCompaction", id },
+ ...timestamps,
+ },
+ },
+ })),
+ ...(outcome === "Stop"
+ ? [
+ {
+ type: "expect_outbound" as const,
+ label: "turn/interrupt",
+ frame: {
+ id: 4,
+ method: "turn/interrupt",
+ params: { threadId: nativeThreadId, turnId: nativeTurnId },
+ },
+ },
+ {
+ type: "emit_inbound" as const,
+ label: "turn/interrupt/failed",
+ frame: { id: 4, error: { code: -32_000, message: "Interrupt failed" } },
+ },
+ ]
+ : [
+ {
+ type: "emit_inbound" as const,
+ label: "turn/completed",
+ frame: {
+ method: "turn/completed",
+ params: {
+ threadId: nativeThreadId,
+ turn: {
+ ...makeCodexReplayTurn({ id: nativeTurnId, status: outcome }),
+ error: outcome === "failed" ? error : null,
+ },
+ },
+ },
+ },
+ ]),
+ ],
+ });
+ const compactionStarted = yield* Deferred.make<ProviderTurnId>();
+ const harness = yield* makeCodexReplayHarness(transcript, (event) =>
+ event.type === "turn_item.updated" &&
+ event.turnItem.nativeItemRef?.nativeId === "unfinished-item" &&
+ event.turnItem.status === "running" &&
+ event.turnItem.providerTurnId !== null
+ ? Deferred.succeed(compactionStarted, event.turnItem.providerTurnId)
+ : Effect.void,
+ );
+ yield* TestClock.setTime(1782622445000);
+ yield* harness.runtime.startTurn(
+ makeCodexTestTurnInput({
+ threadId: harness.threadId,
+ providerThread: harness.providerThread,
+ now: yield* DateTime.now,
+ attemptId: RunAttemptId.make(`compact-${outcome}-attempt`),
+ text: "Continue.",
+ }),
+ );
+ if (outcome === "Stop") {
+ const providerTurnId = yield* Deferred.await(compactionStarted);
+ const interrupt = yield* harness.runtime
+ .interruptTurn({ providerThread: harness.providerThread, providerTurnId })
+ .pipe(Effect.exit);
+ assert.equal(interrupt._tag, "Failure");
+ }
+ yield* harness.firstTerminal;
+ const items = harness.events.flatMap((event) =>
+ event.type === "turn_item.updated" && event.turnItem.type === "compaction"
+ ? [event.turnItem]
+ : [],
+ );
+ const completed = items.filter(
+ (item) => item.nativeItemRef?.nativeId === "completed-item",
+ );
+ const unfinished = items.filter(
+ (item) => item.nativeItemRef?.nativeId === "unfinished-item",
+ );
+ const status = outcome === "failed" ? "failed" : "interrupted";
+ assert.deepEqual(
+ unfinished.map((item) => item.status),
+ ["running", status],
+ );
+ assert.equal(unfinished[0]?.id, unfinished[1]?.id);
+ assert.deepEqual(unfinished[1]?.startedAt, DateTime.makeUnsafe(1782622443000));
+ assert.deepEqual(
+ unfinished[1]?.completedAt,
+ DateTime.makeUnsafe(outcome === "Stop" ? 1782622445000 : 1782622450000),
+ );
+ assert.deepEqual(
+ completed.map((item) => item.status),
+ ["running", "completed"],
+ );
+ assert.deepEqual(completed[1]?.startedAt, DateTime.makeUnsafe(1782622441000));
+ assert.deepEqual(completed[1]?.completedAt, DateTime.makeUnsafe(1782622442000));
+ assert.equal(harness.terminalEvents()[0]?.status, status);
+ if (outcome === "failed") {
+ assert.equal(harness.terminalEvents()[0]?.failure?.message, error.message);
+ }
+ }).pipe(
+ 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.ts
index a971e77fced..5664fdb230d 100644
--- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
+++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts
@@ -1157,6 +1157,7 @@ interface ActiveCodexTurnContext {
readonly rootNodeId: OrchestrationV2ExecutionNode["id"];
readonly subagent: CodexSubagentThreadContext | null;
readonly startedAt: DateTime.Utc;
+ readonly runningCompactionItemIds: Set<string>;
// Modern approval requests omit paths; keep the kinds without retaining patch bodies.
readonly fileChangeKindsByItem: Map<string, CodexFileChangeKinds>;
readonly itemPositions: Map<
@@ -2037,6 +2038,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
startedAt: input.startedAt,
itemPositions: new Map(),
fileChangeKindsByItem: new Map(),
+ runningCompactionItemIds: new Set(),
};
yield* Ref.update(limitedTurnItems, (current) => {
const next = new Map(current);
@@ -2618,6 +2620,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
startedAt: turn.startedAt,
itemPositions: new Map(),
fileChangeKindsByItem: new Map(),
+ runningCompactionItemIds: new Set(),
};
beginTurnTokenUsage(activeContext);
endSessionApprovalsOnModeChange(activeContext);
@@ -4627,15 +4630,16 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
const emitCompactionItem = Effect.fn("CodexAdapterV2.emitCompactionItem")(function* (
context: ActiveCodexTurnContext,
nativeItemId: string,
- status: "running" | "completed",
- nativeStartedAt?: DateTime.Utc,
+ status: "running" | "completed" | "failed" | "interrupted" | "cancelled",
+ updatedAt: DateTime.Utc,
) {
- const now = yield* DateTime.now;
const { ordinal, startedAt } = yield* resolveItemPosition(
context,
nativeItemId,
- nativeStartedAt,
+ updatedAt,
);
+ if (status === "running") context.runningCompactionItemIds.add(nativeItemId);
+ else context.runningCompactionItemIds.delete(nativeItemId);
yield* emitProviderEvent({
type: "turn_item.updated",
driver: CODEX_PROVIDER,
@@ -4655,10 +4659,17 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
type: "compaction",
driver: CODEX_PROVIDER,
status,
- title: status === "completed" ? "Context compacted" : "Compacting context",
+ title:
+ status === "running"
+ ? "Compacting context"
+ : status === "completed"
+ ? "Context compacted"
+ : status === "failed"
+ ? "Context compaction failed"
+ : "Context compaction stopped",
startedAt,
- completedAt: status === "completed" ? now : null,
- updatedAt: now,
+ completedAt: status === "running" ? null : updatedAt,
+ updatedAt,
},
});
});
@@ -4831,7 +4842,12 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
}
if (payload.item.type === "contextCompaction") {
- yield* emitCompactionItem(context, payload.item.id, "completed");
+ yield* emitCompactionItem(
+ context,
+ payload.item.id,
+ "completed",
+ DateTime.makeUnsafe(payload.completedAtMs),
+ );
return;
}
@@ -5866,6 +5882,15 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
for (const [key, part] of reasoningParts) {
if (part.turnId === input.nativeTurnId) reasoningParts.delete(key);
}
+ // Failed compaction can end the turn without item/completed.
+ for (const nativeItemId of input.context.runningCompactionItemIds) {
+ yield* emitCompactionItem(
+ input.context,
+ nativeItemId,
+ providerTurnStatusToTerminal(input.status),
+ input.completedAt,
+ );
+ }
const nativeThreadId = input.context.providerThread.nativeThreadRef?.nativeId;
const activation =
nativeThreadId == null ? undefined : goalActivations.get(nativeThreadId);
@@ -6118,6 +6143,7 @@ export const makeCodexAdapterV2 = Effect.fn("makeCodexAdapterV2")(function* (
startedAt: now,
itemPositions: new Map(),
fileChangeKindsByItem: new Map(),
+ runningCompactionItemIds: new Set(),
};
const providerTurn = {
id: context.providerTurnId,
diff --git a/packages/client-runtime/src/work-log/presentation.ts b/packages/client-runtime/src/work-log/presentation.ts
index de0fd994084..f16b0722abe 100644
--- a/packages/client-runtime/src/work-log/presentation.ts
+++ b/packages/client-runtime/src/work-log/presentation.ts
@@ -1,4 +1,5 @@
import {
+ isOrchestrationV2WorkActive,
isToolLifecycleItemType,
type AssetResource,
type RuntimeItemStatus,
@@ -70,7 +71,7 @@ export function contextCompactionLabel(item: CompactionLabelItem): string {
if (item.status === "failed") return "Context compaction failed";
if (item.status === "cancelled" || item.status === "interrupted")
return "Context compaction stopped";
- if (item.status === "running") return "Compacting context";
+ if (isOrchestrationV2WorkActive(item.status)) return "Compacting context";
const tokens = contextCompactionTokenCounts(item);
return tokens
? `Context compacted ${tokens.before} → ${tokens.after} tokens`