Skip to content
TypeScript

fix(server): capture turn checkpoints after all edits finish (#9841)

Julius Marminge7a089b2b2449
diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts
index 2f2c4b30525..390e61138f0 100644
--- a/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts
+++ b/apps/server/src/orchestration/Layers/CheckpointReactor.test.ts
@@ -12,6 +12,7 @@ import {
} from "@t3tools/contracts";
import {
CommandId,
+ CheckpointRef,
DEFAULT_PROVIDER_INTERACTION_MODE,
EventId,
MessageId,
@@ -667,6 +668,167 @@ describe("CheckpointReactor", () => {
}),
);
+ effectIt.effect.each(["turn.completed", "turn.aborted"] as const)(
+ "captures every edit after a mid-turn diff update on %s",
+ (terminalEventType) =>
+ Effect.gen(function* () {
+ const harness = yield* Effect.promise(() =>
+ createHarness({ seedFilesystemCheckpoints: false }),
+ );
+ const threadId = ThreadId.make("thread-1");
+ const turnId = asTurnId("turn-1");
+ const assistantMessageId = MessageId.make("assistant:mid-turn");
+ const createdAt = "2026-01-01T00:00:00.000Z";
+ yield* harness.engine.dispatch({
+ type: "thread.session.set",
+ commandId: CommandId.make("cmd-mid-turn-running"),
+ threadId,
+ session: {
+ threadId,
+ status: "running",
+ providerName: "codex",
+ runtimeMode: "approval-required",
+ activeTurnId: turnId,
+ lastError: null,
+ updatedAt: createdAt,
+ },
+ createdAt,
+ });
+ harness.provider.emit({
+ type: "turn.started",
+ eventId: EventId.make("evt-mid-turn-start"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt,
+ threadId,
+ turnId,
+ });
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.baseline.captured",
+ });
+
+ NodeFS.writeFileSync(NodePath.join(harness.cwd, "early.ts"), "export const early = 1;\n");
+ yield* harness.engine.dispatch({
+ type: "thread.turn.diff.complete",
+ commandId: CommandId.make("cmd-mid-turn-diff"),
+ threadId,
+ turnId,
+ completedAt: createdAt,
+ checkpointRef: CheckpointRef.make("provider-diff:mid-turn"),
+ assistantMessageId,
+ status: "missing",
+ files: [],
+ checkpointTurnCount: 1,
+ createdAt,
+ });
+ yield* Effect.promise(harness.drain);
+
+ NodeFS.writeFileSync(NodePath.join(harness.cwd, "late.ts"), "export const late = 2;\n");
+ yield* harness.engine.dispatch({
+ type: "thread.session.set",
+ commandId: CommandId.make("cmd-mid-turn-settled"),
+ threadId,
+ session: {
+ threadId,
+ status: terminalEventType === "turn.aborted" ? "interrupted" : "ready",
+ providerName: "codex",
+ runtimeMode: "approval-required",
+ activeTurnId: null,
+ lastError: null,
+ updatedAt: createdAt,
+ },
+ createdAt,
+ });
+ harness.provider.emit({
+ eventId: EventId.make("evt-mid-turn-complete"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt,
+ threadId,
+ turnId,
+ ...(terminalEventType === "turn.completed"
+ ? { type: "turn.completed", payload: { state: "completed" } }
+ : { type: "turn.aborted", payload: { reason: "Interrupted by user." } }),
+ });
+ yield* Effect.promise(harness.drain);
+ expect(gitRefExists(harness.cwd, checkpointRefForThreadTurn(threadId, 1))).toBe(true);
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.diff.finalized",
+ turnId,
+ checkpointTurnCount: 1,
+ });
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "turn.processing.quiesced",
+ turnId,
+ });
+ yield* Effect.promise(harness.drain);
+ const thread = (yield* Effect.promise(harness.readModel)).threads.find(
+ (entry) => entry.id === threadId,
+ );
+ expect(thread?.checkpoints).toHaveLength(1);
+ expect(thread?.checkpoints[0]?.status).toBe("ready");
+ expect(thread?.latestTurn?.state).toBe(
+ terminalEventType === "turn.aborted" ? "interrupted" : "completed",
+ );
+ expect(thread?.checkpoints[0]?.assistantMessageId).toBe(assistantMessageId);
+ expect(thread?.checkpoints[0]?.files.map((file) => file.path)).toEqual([
+ "early.ts",
+ "late.ts",
+ ]);
+ expect(
+ gitShowFileAtRef(harness.cwd, checkpointRefForThreadTurn(threadId, 1), "late.ts"),
+ ).toBe("export const late = 2;\n");
+
+ const followUpTurnId = asTurnId("turn-2");
+ harness.provider.emit({
+ type: "turn.started",
+ eventId: EventId.make("evt-follow-up-start"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt,
+ threadId,
+ turnId: followUpTurnId,
+ });
+ harness.provider.emit({
+ type: "turn.completed",
+ eventId: EventId.make("evt-follow-up-complete"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt,
+ threadId,
+ turnId: followUpTurnId,
+ payload: { state: "completed" },
+ });
+ expect(yield* harness.nextReceipt).toMatchObject({
+ type: "checkpoint.diff.finalized",
+ turnId: followUpTurnId,
+ checkpointTurnCount: 2,
+ });
+ const followUp = (yield* Effect.promise(harness.readModel)).threads.find(
+ (entry) => entry.id === threadId,
+ );
+ expect(
+ followUp?.checkpoints.find((checkpoint) => checkpoint.turnId === followUpTurnId),
+ ).toMatchObject({ checkpointTurnCount: 2, files: [] });
+ }),
+ );
+
+ it("does not capture an aborted turn without a matching start or active session", async () => {
+ const harness = await createHarness({ seedFilesystemCheckpoints: false });
+ harness.provider.emit({
+ type: "turn.aborted",
+ eventId: EventId.make("evt-untracked-abort"),
+ provider: ProviderDriverKind.make("codex"),
+ createdAt: "2026-01-01T00:00:00.000Z",
+ threadId: ThreadId.make("thread-1"),
+ turnId: asTurnId("turn-untracked"),
+ payload: { reason: "Interrupted before the turn started." },
+ });
+ await harness.drain();
+
+ const thread = (await harness.readModel()).threads.find((entry) => entry.id === "thread-1");
+ expect(thread?.checkpoints).toEqual([]);
+ expect(
+ gitRefExists(harness.cwd, checkpointRefForThreadTurn(ThreadId.make("thread-1"), 1)),
+ ).toBe(false);
+ });
+
it("refreshes local git status state on turn completion using the session cwd", async () => {
const gitStatusRefreshCalls: string[] = [];
const harness = await createHarness({
diff --git a/apps/server/src/orchestration/Layers/CheckpointReactor.ts b/apps/server/src/orchestration/Layers/CheckpointReactor.ts
index 108abd5d06b..f155a6ae365 100644
--- a/apps/server/src/orchestration/Layers/CheckpointReactor.ts
+++ b/apps/server/src/orchestration/Layers/CheckpointReactor.ts
@@ -216,9 +216,7 @@ const make = Effect.gen(function* () {
return cwd;
});
- // Shared tail for both capture paths: creates the git checkpoint ref, diffs
- // it against the previous turn, then dispatches the domain events to update
- // the orchestration read model.
+ // Capture the completed turn's files, then publish its summary and receipts.
const captureAndDispatchCheckpoint = Effect.fn("captureAndDispatchCheckpoint")(function* (input: {
readonly threadId: ThreadId;
readonly turnId: TurnId;
@@ -353,9 +351,9 @@ const make = Effect.gen(function* () {
});
});
- // Captures a real git checkpoint when a turn completes via a runtime event.
+ // Capture the files left by a completed or interrupted turn.
const captureCheckpointFromTurnCompletion = Effect.fn("captureCheckpointFromTurnCompletion")(
- function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" }>) {
+ function* (event: Extract<ProviderRuntimeEvent, { type: "turn.completed" | "turn.aborted" }>) {
const turnId = toTurnId(event.turnId);
if (!turnId) {
return;
@@ -412,75 +410,16 @@ const make = Effect.gen(function* () {
thread,
cwd: checkpointCwd,
turnCount: nextTurnCount,
- status: checkpointStatusFromRuntime(event.payload.state),
- assistantMessageId: undefined,
+ status:
+ event.type === "turn.aborted"
+ ? "ready"
+ : checkpointStatusFromRuntime(event.payload.state),
+ assistantMessageId: existingPlaceholder?.assistantMessageId ?? undefined,
createdAt: event.createdAt,
});
},
);
- // Captures a real git checkpoint when a placeholder checkpoint (status "missing")
- // is detected via a domain event. This replaces the placeholder with a real
- // git-ref-based checkpoint.
- //
- // ProviderRuntimeIngestion creates placeholder checkpoints on turn.diff.updated
- // events from the Codex runtime. This handler fires when the corresponding
- // domain event arrives, allowing the reactor to capture the actual filesystem
- // state into a git ref and dispatch a replacement checkpoint.
- const captureCheckpointFromPlaceholder = Effect.fn("captureCheckpointFromPlaceholder")(function* (
- event: Extract<OrchestrationEvent, { type: "thread.turn-diff-completed" }>,
- ) {
- const { threadId, turnId, checkpointTurnCount, status } = event.payload;
-
- // Only replace placeholders; skip events from our own real captures.
- if (status !== "missing") {
- return;
- }
-
- const thread = yield* resolveThreadDetail(threadId);
- if (!thread) {
- yield* Effect.logWarning("checkpoint capture from placeholder skipped: thread not found", {
- threadId,
- });
- return;
- }
-
- // If a real checkpoint already exists for this turn, skip.
- if (
- thread.checkpoints.some(
- (checkpoint) => checkpoint.turnId === turnId && checkpoint.status !== "missing",
- )
- ) {
- yield* Effect.logDebug(
- "checkpoint capture from placeholder skipped: real checkpoint already exists",
- { threadId, turnId },
- );
- return;
- }
-
- const projects = yield* resolveThreadProjects(thread.projectId);
- const checkpointCwd = yield* resolveCheckpointCwd({
- threadId,
- thread,
- projects,
- preferSessionRuntime: true,
- });
- if (!checkpointCwd) {
- return;
- }
-
- yield* captureAndDispatchCheckpoint({
- threadId,
- turnId,
- thread,
- cwd: checkpointCwd,
- turnCount: checkpointTurnCount,
- status: "ready",
- assistantMessageId: event.payload.assistantMessageId ?? undefined,
- createdAt: event.payload.completedAt,
- });
- });
-
const ensurePreTurnBaselineFromTurnStart = Effect.fn("ensurePreTurnBaselineFromTurnStart")(
function* (event: Extract<ProviderRuntimeEvent, { type: "turn.started" }>) {
const turnId = toTurnId(event.turnId);
@@ -876,25 +815,6 @@ const make = Effect.gen(function* () {
);
return;
}
-
- // When ProviderRuntimeIngestion creates a placeholder checkpoint (status "missing")
- // from a turn.diff.updated runtime event, capture the real git checkpoint to
- // replace it. ProviderService broadcasts runtime events to each subscriber.
- // This domain-event path also captures checkpoints from turn diff updates.
- if (event.type === "thread.turn-diff-completed") {
- yield* captureCheckpointFromPlaceholder(event).pipe(
- Effect.catch((error) =>
- Effect.flatMap(nowIso, (createdAt) =>
- appendCaptureFailureActivity({
- threadId: event.payload.threadId,
- turnId: event.payload.turnId,
- detail: error.message,
- createdAt,
- }).pipe(Effect.catch(() => Effect.void)),
- ),
- ),
- );
- }
});
const processRuntimeEvent = Effect.fn("processRuntimeEvent")(function* (
@@ -939,7 +859,13 @@ const make = Effect.gen(function* () {
pending.delete(event.threadId);
yield* pullRequests.refreshAfterTurn;
}
- if (event.type === "turn.aborted") return;
+ if (
+ event.type === "turn.aborted" &&
+ !isTrackedTurn &&
+ !sameId(thread?.session?.activeTurnId, turnId)
+ ) {
+ return;
+ }
yield* captureCheckpointFromTurnCompletion(event).pipe(
Effect.catch((error) =>
Effect.flatMap(nowIso, (createdAt) =>
@@ -987,8 +913,7 @@ const make = Effect.gen(function* () {
if (
event.type !== "thread.turn-start-requested" &&
event.type !== "thread.message-sent" &&
- event.type !== "thread.checkpoint-revert-requested" &&
- event.type !== "thread.turn-diff-completed"
+ event.type !== "thread.checkpoint-revert-requested"
) {
return Effect.void;
}
diff --git a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
index 77dfb5e3b88..cd028d50223 100644
--- a/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
+++ b/apps/server/src/orchestration/Layers/ProjectionPipeline.ts
@@ -1573,7 +1573,10 @@ const makeOrchestrationProjectionPipeline = Effect.fn("makeOrchestrationProjecti
yield* projectionTurnRepository.upsertByTurnId({
...existingTurn.value,
assistantMessageId: event.payload.assistantMessageId,
- state: turnStillRunning ? existingTurn.value.state : nextState,
+ state:
+ turnStillRunning || existingTurn.value.state === "interrupted"
+ ? existingTurn.value.state
+ : nextState,
checkpointTurnCount: event.payload.checkpointTurnCount,
checkpointRef: event.payload.checkpointRef,
checkpointStatus: event.payload.status,
diff --git a/apps/server/src/orchestration/projector.test.ts b/apps/server/src/orchestration/projector.test.ts
index dad3d07370f..4b37137936f 100644
--- a/apps/server/src/orchestration/projector.test.ts
+++ b/apps/server/src/orchestration/projector.test.ts
@@ -7,6 +7,7 @@ import {
type OrchestrationEvent,
} from "@t3tools/contracts";
import * as Effect from "effect/Effect";
+import { it as effectIt } from "@effect/vitest";
import { describe, expect, it } from "vite-plus/test";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
@@ -239,110 +240,234 @@ describe("orchestration projector", () => {
expect(next.threads).toEqual([]);
});
- it("tracks latest turn id from session lifecycle events", async () => {
- const createdAt = "2026-02-23T08:00:00.000Z";
- const startedAt = "2026-02-23T08:00:05.000Z";
- const model = createEmptyReadModel(createdAt);
-
- const afterCreate = await Effect.runPromise(
- projectEvent(
- model,
- makeEvent({
- sequence: 1,
- type: "thread.created",
- aggregateKind: "thread",
- aggregateId: "thread-1",
- occurredAt: createdAt,
- commandId: "cmd-create",
- payload: {
- threadId: "thread-1",
- projectId: "project-1",
- title: "demo",
- modelSelection: {
- provider: ProviderDriverKind.make("codex"),
- model: "gpt-5.3-codex",
- },
- runtimeMode: "full-access",
- branch: null,
- worktreePath: null,
- createdAt,
- updatedAt: createdAt,
- },
- }),
- ),
- );
+ effectIt.effect.each([
+ ["ready", "completed"],
+ ["interrupted", "interrupted"],
+ ] as const)(
+ "preserves the turn state after a %s session captures its checkpoint",
+ ([status, state]) =>
+ Effect.gen(function* () {
+ const createdAt = "2026-02-23T08:00:00.000Z";
+ const startedAt = "2026-02-23T08:00:05.000Z";
+ const model = createEmptyReadModel(createdAt);
- const settledAt = "2026-02-23T08:01:00.000Z";
- const [afterRunning, afterReady] = await Effect.runPromise(
- Effect.flatMap(
- projectEvent(
- afterCreate,
+ const afterCreate = yield* projectEvent(
+ model,
makeEvent({
- sequence: 2,
- type: "thread.session-set",
+ sequence: 1,
+ type: "thread.created",
aggregateKind: "thread",
aggregateId: "thread-1",
- occurredAt: startedAt,
- commandId: "cmd-running",
+ occurredAt: createdAt,
+ commandId: "cmd-create",
payload: {
threadId: "thread-1",
- session: {
- threadId: "thread-1",
- status: "running",
- providerName: "codex",
- providerSessionId: "session-1",
- providerThreadId: "provider-thread-1",
- runtimeMode: "approval-required",
- activeTurnId: "turn-1",
- lastError: null,
- updatedAt: startedAt,
+ projectId: "project-1",
+ title: "demo",
+ modelSelection: {
+ provider: ProviderDriverKind.make("codex"),
+ model: "gpt-5.3-codex",
},
+ runtimeMode: "full-access",
+ branch: null,
+ worktreePath: null,
+ createdAt,
+ updatedAt: createdAt,
},
}),
- ),
- (running) =>
- Effect.map(
- projectEvent(
- running,
- makeEvent({
- sequence: 3,
- type: "thread.session-set",
- aggregateKind: "thread",
- aggregateId: "thread-1",
- occurredAt: settledAt,
- commandId: "cmd-ready",
- payload: {
+ );
+
+ const settledAt = "2026-02-23T08:01:00.000Z";
+ const [afterRunning, afterReady] = yield* Effect.flatMap(
+ projectEvent(
+ afterCreate,
+ makeEvent({
+ sequence: 2,
+ type: "thread.session-set",
+ aggregateKind: "thread",
+ aggregateId: "thread-1",
+ occurredAt: startedAt,
+ commandId: "cmd-running",
+ payload: {
+ threadId: "thread-1",
+ session: {
threadId: "thread-1",
- session: {
+ status: "running",
+ providerName: "codex",
+ providerSessionId: "session-1",
+ providerThreadId: "provider-thread-1",
+ runtimeMode: "approval-required",
+ activeTurnId: "turn-1",
+ lastError: null,
+ updatedAt: startedAt,
+ },
+ },
+ }),
+ ),
+ (running) =>
+ Effect.map(
+ projectEvent(
+ running,
+ makeEvent({
+ sequence: 3,
+ type: "thread.session-set",
+ aggregateKind: "thread",
+ aggregateId: "thread-1",
+ occurredAt: settledAt,
+ commandId: "cmd-ready",
+ payload: {
threadId: "thread-1",
- status: "ready",
- providerName: "codex",
- providerSessionId: "session-1",
- providerThreadId: "provider-thread-1",
- runtimeMode: "approval-required",
- activeTurnId: null,
- lastError: null,
- updatedAt: settledAt,
+ session: {
+ threadId: "thread-1",
+ status,
+ providerName: "codex",
+ providerSessionId: "session-1",
+ providerThreadId: "provider-thread-1",
+ runtimeMode: "approval-required",
+ activeTurnId: null,
+ lastError: null,
+ updatedAt: settledAt,
+ },
},
- },
- }),
+ }),
+ ),
+ (ready) => [running, ready] as const,
),
- (ready) => [running, ready] as const,
- ),
- ),
- );
+ );
- const thread = afterRunning.threads[0];
- expect(thread?.latestTurn?.turnId).toBe("turn-1");
- expect(thread?.session?.status).toBe("running");
-
- // Leaving the "running" session status settles the running turn with the
- // session timestamp as the turn end.
- const settledThread = afterReady.threads[0];
- expect(settledThread?.latestTurn?.turnId).toBe("turn-1");
- expect(settledThread?.latestTurn?.state).toBe("completed");
- expect(settledThread?.latestTurn?.completedAt).toBe(settledAt);
- });
+ const thread = afterRunning.threads[0];
+ expect(thread?.latestTurn?.turnId).toBe("turn-1");
+ expect(thread?.session?.status).toBe("running");
+
+ // Leaving the "running" session status settles the running turn with the
+ // session timestamp as the turn end.
+ const settledThread = afterReady.threads[0];
+ expect(settledThread?.latestTurn?.turnId).toBe("turn-1");
+ expect(settledThread?.latestTurn?.state).toBe(state);
+ expect(settledThread?.latestTurn?.completedAt).toBe(settledAt);
+
+ const captured = yield* projectEvent(
+ afterReady,
+ makeEvent({
+ sequence: 4,
+ type: "thread.turn-diff-completed",
+ aggregateKind: "thread",
+ aggregateId: "thread-1",
+ occurredAt: settledAt,
+ commandId: "cmd-final-checkpoint",
+ payload: {
+ threadId: "thread-1",
+ turnId: "turn-1",
+ checkpointTurnCount: 1,
+ checkpointRef: "refs/t3/checkpoints/thread-1/turn/1",
+ status: "ready",
+ files: [],
+ assistantMessageId: "assistant:turn-1",
+ completedAt: settledAt,
+ },
+ }),
+ );
+ expect(captured.threads[0]?.latestTurn?.state).toBe(state);
+ expect(captured.threads[0]?.checkpoints[0]?.status).toBe("ready");
+ }),
+ );
+
+ effectIt.effect.each([null, "ready", "interrupted", "stopped"] as const)(
+ "replaces a missing checkpoint without inventing interruption for a %s session",
+ (sessionStatus) =>
+ Effect.gen(function* () {
+ const now = "2026-09-04T23:00:00.000Z";
+ const threadId = "thread-placeholder";
+ const event = (sequence: number, type: OrchestrationEvent["type"], payload: unknown) =>
+ makeEvent({
+ sequence,
+ type,
+ payload,
+ aggregateKind: "thread",
+ aggregateId: threadId,
+ occurredAt: now,
+ commandId: `placeholder-${sequence}`,
+ });
+ let model = yield* projectEvent(
+ createEmptyReadModel(now),
+ event(1, "thread.created", {
+ threadId,
+ projectId: "project-1",
+ title: "Placeholder",
+ modelSelection: { instanceId: "codex", model: "test" },
+ runtimeMode: "full-access",
+ interactionMode: "default",
+ branch: null,
+ worktreePath: null,
+ createdAt: now,
+ updatedAt: now,
+ }),
+ );
+ const checkpoint = {
+ threadId,
+ turnId: "turn-placeholder",
+ checkpointTurnCount: 1,
+ checkpointRef: "provider-diff:placeholder",
+ files: [],
+ assistantMessageId: "assistant:placeholder",
+ completedAt: now,
+ };
+ if (sessionStatus === "interrupted" || sessionStatus === "stopped") {
+ model = yield* projectEvent(
+ model,
+ event(2, "thread.session-set", {
+ threadId,
+ session: {
+ threadId,
+ status: "running",
+ providerName: "codex",
+ runtimeMode: "full-access",
+ activeTurnId: "turn-placeholder",
+ lastError: null,
+ updatedAt: now,
+ },
+ }),
+ );
+ }
+ model = yield* projectEvent(
+ model,
+ event(3, "thread.turn-diff-completed", {
+ ...checkpoint,
+ status: "missing",
+ }),
+ );
+ if (sessionStatus !== null) {
+ model = yield* projectEvent(
+ model,
+ event(4, "thread.session-set", {
+ threadId,
+ session: {
+ threadId,
+ status: sessionStatus,
+ providerName: "codex",
+ runtimeMode: "full-access",
+ activeTurnId: null,
+ lastError: null,
+ updatedAt: now,
+ },
+ }),
+ );
+ }
+ model = yield* projectEvent(
+ model,
+ event(5, "thread.turn-diff-completed", {
+ ...checkpoint,
+ status: "ready",
+ checkpointRef: "refs/t3/checkpoints/thread-placeholder/turn/1",
+ }),
+ );
+ expect(model.threads[0]?.latestTurn?.state).toBe(
+ sessionStatus === "interrupted" || sessionStatus === "stopped"
+ ? "interrupted"
+ : "completed",
+ );
+ }),
+ );
it("updates canonical thread runtime mode from thread.runtime-mode-set", async () => {
const createdAt = "2026-02-23T08:00:00.000Z";
diff --git a/apps/server/src/orchestration/projector.ts b/apps/server/src/orchestration/projector.ts
index 3cea194bbb4..a558e0ad7af 100644
--- a/apps/server/src/orchestration/projector.ts
+++ b/apps/server/src/orchestration/projector.ts
@@ -64,7 +64,7 @@ function retainThreadActivities(activities: OrchestrationThread["activities"]) {
function checkpointStatusToLatestTurnState(status: "ready" | "missing" | "error") {
if (status === "error") return "error" as const;
- if (status === "missing") return "interrupted" as const;
+ // Match SQL and client projections: a missing git ref is not an interruption.
return "completed" as const;
}
@@ -746,7 +746,11 @@ export function projectEvent(
? thread.latestTurn
: {
turnId: payload.turnId,
- state: checkpointStatusToLatestTurnState(payload.status),
+ state:
+ thread.latestTurn?.turnId === payload.turnId &&
+ thread.latestTurn.state === "interrupted"
+ ? "interrupted"
+ : checkpointStatusToLatestTurnState(payload.status),
requestedAt:
thread.latestTurn?.turnId === payload.turnId
? thread.latestTurn.requestedAt
diff --git a/packages/client-runtime/src/state/threadReducer.test.ts b/packages/client-runtime/src/state/threadReducer.test.ts
index 40198099766..9a9be9b4da0 100644
--- a/packages/client-runtime/src/state/threadReducer.test.ts
+++ b/packages/client-runtime/src/state/threadReducer.test.ts
@@ -1129,33 +1129,52 @@ describe("applyThreadDetailEvent", () => {
});
describe("thread.turn-diff-completed", () => {
- it("adds a checkpoint and updates latestTurn", () => {
- const result = applyThreadDetailEvent(baseThread, {
- ...baseEventFields,
- sequence: 13,
- occurredAt: "2026-04-01T12:00:00.000Z",
- aggregateKind: "thread",
- aggregateId: ThreadId.make("thread-1"),
- type: "thread.turn-diff-completed",
- payload: {
- threadId: ThreadId.make("thread-1"),
- turnId: TurnId.make("turn-1"),
- checkpointTurnCount: 1,
- checkpointRef: CheckpointRef.make("ref-1"),
- status: "ready",
- files: [],
- assistantMessageId: MessageId.make("msg-3"),
- completedAt: "2026-04-01T12:00:00.000Z",
- },
- });
-
- expect(result.kind).toBe("updated");
- if (result.kind === "updated") {
- expect(result.thread.checkpoints).toHaveLength(1);
- expect(result.thread.latestTurn?.turnId).toBe("turn-1");
- expect(result.thread.latestTurn?.state).toBe("completed");
- }
- });
+ it.each([null, "interrupted"] as const)(
+ "adds a checkpoint without replacing a %s turn outcome",
+ (previousState) => {
+ const result = applyThreadDetailEvent(
+ {
+ ...baseThread,
+ latestTurn:
+ previousState === null
+ ? null
+ : {
+ turnId: TurnId.make("turn-1"),
+ state: previousState,
+ requestedAt: "2026-04-01T11:00:00.000Z",
+ startedAt: "2026-04-01T11:00:00.000Z",
+ completedAt: "2026-04-01T12:00:00.000Z",
+ assistantMessageId: null,
+ },
+ },
+ {
+ ...baseEventFields,
+ sequence: 13,
+ occurredAt: "2026-04-01T12:00:00.000Z",
+ aggregateKind: "thread",
+ aggregateId: ThreadId.make("thread-1"),
+ type: "thread.turn-diff-completed",
+ payload: {
+ threadId: ThreadId.make("thread-1"),
+ turnId: TurnId.make("turn-1"),
+ checkpointTurnCount: 1,
+ checkpointRef: CheckpointRef.make("ref-1"),
+ status: "ready",
+ files: [],
+ assistantMessageId: MessageId.make("msg-3"),
+ completedAt: "2026-04-01T12:00:00.000Z",
+ },
+ },
+ );
+
+ expect(result.kind).toBe("updated");
+ if (result.kind === "updated") {
+ expect(result.thread.checkpoints).toHaveLength(1);
+ expect(result.thread.latestTurn?.turnId).toBe("turn-1");
+ expect(result.thread.latestTurn?.state).toBe(previousState ?? "completed");
+ }
+ },
+ );
});
describe("thread.reverted", () => {
diff --git a/packages/client-runtime/src/state/threadReducer.ts b/packages/client-runtime/src/state/threadReducer.ts
index 690c74bdea0..1de0b654c06 100644
--- a/packages/client-runtime/src/state/threadReducer.ts
+++ b/packages/client-runtime/src/state/threadReducer.ts
@@ -521,7 +521,10 @@ export function applyThreadDetailEvent(
(thread.latestTurn === null || thread.latestTurn.turnId === event.payload.turnId)
? {
turnId: event.payload.turnId,
- state: checkpointStatusToTurnState(event.payload.status),
+ state:
+ thread.latestTurn?.state === "interrupted"
+ ? "interrupted"
+ : checkpointStatusToTurnState(event.payload.status),
requestedAt: thread.latestTurn?.requestedAt ?? event.payload.completedAt,
startedAt: thread.latestTurn?.startedAt ?? event.payload.completedAt,
completedAt: event.payload.completedAt,