feat(orchestration): track provider retries and thread visits

- Project retry progress and recovery for Codex and Claude turns
- Sync thread completion markers through server-side visit timestamps
This commit is contained in:
Julius Marminge committed 2026-08-07 13:27:21 +02:00
1 parent a04e807333
commit 844dad005a
73 files changed
+3918 -1273

No files matched your search

@@ -40,6 +40,8 @@ import {
createProject,
forkThreadFromRun,
mergeThreadBack,
cancelQueuedRun,
editQueuedRun,
promoteQueuedRun,
reorderQueuedRun,
revertThreadCheckpoint,
@@ -419,6 +421,17 @@ describe("V2 environment commands", () => {
queuedRunId: RunId.make("run-3"),
targetRunId: RunId.make("run-active"),
}).pipe(provide);
yield* cancelQueuedRun({
commandId: CommandId.make("cancel"),
threadId: v2ThreadId,
runId: RunId.make("run-3"),
}).pipe(provide);
yield* editQueuedRun({
commandId: CommandId.make("edit"),
threadId: v2ThreadId,
runId: RunId.make("run-3"),
text: "updated queued text",
}).pipe(provide);
expect(commands).toMatchObject([
{ type: "thread.fork", sourcePoint: { type: "run", runId: "run-1" } },
@@ -429,6 +442,8 @@ describe("V2 environment commands", () => {
queuedRunId: "run-3",
targetRunId: "run-active",
},
{ type: "queued-run.cancel", runId: "run-3" },
{ type: "queued-run.edit", runId: "run-3", text: "updated queued text" },
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
@@ -72,6 +72,13 @@ export type DeleteThreadInput = ThreadCommandInput;
export type ArchiveThreadInput = ThreadCommandInput;
export type UnarchiveThreadInput = ThreadCommandInput;
export interface VisitThreadInput extends ThreadCommandInput {
/** Watermark of the thread state the viewer has seen (ISO timestamp). */
readonly visitedAt: string;
}
export type MarkThreadUnreadInput = ThreadCommandInput;
export interface UpdateThreadMetadataInput extends ThreadCommandInput {
readonly title?: string;
readonly modelSelection?: ModelSelection;
@@ -170,6 +177,15 @@ export interface PromoteQueuedRunInput extends ThreadCommandInput {
readonly targetRunId: RunId;
}
export interface CancelQueuedRunInput extends ThreadCommandInput {
readonly runId: RunId;
}
export interface EditQueuedRunInput extends ThreadCommandInput {
readonly runId: RunId;
readonly text: string;
}
const allocateCommandId = Effect.fn("EnvironmentCommands.allocateCommandId")(function* (
input: CommandMetadata,
) {
@@ -335,6 +351,66 @@ export const unarchiveThread = Effect.fn("EnvironmentCommands.unarchiveThread")(
return yield* simpleThreadCommand("thread.unarchive", input);
});
export const settleThread = Effect.fn("EnvironmentCommands.settleThread")(function* (
input: SettleThreadInput,
) {
return yield* simpleThreadCommand("thread.settle", input);
});
export const unsettleThread = Effect.fn("EnvironmentCommands.unsettleThread")(function* (
input: UnsettleThreadInput,
) {
return yield* dispatch({
type: "thread.unsettle",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
reason: input.reason,
});
});
export const snoozeThread = Effect.fn("EnvironmentCommands.snoozeThread")(function* (
input: SnoozeThreadInput,
) {
return yield* dispatch({
type: "thread.snooze",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
snoozedUntil: input.snoozedUntil,
});
});
export const unsnoozeThread = Effect.fn("EnvironmentCommands.unsnoozeThread")(function* (
input: UnsnoozeThreadInput,
) {
return yield* dispatch({
type: "thread.unsnooze",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
reason: input.reason,
});
});
export const visitThread = Effect.fn("EnvironmentCommands.visitThread")(function* (
input: VisitThreadInput,
) {
return yield* dispatch({
type: "thread.visit",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
visitedAt: input.visitedAt,
});
});
export const markThreadUnread = Effect.fn("EnvironmentCommands.markThreadUnread")(function* (
input: MarkThreadUnreadInput,
) {
return yield* dispatch({
type: "thread.mark-unread",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
});
});
export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadMetadata")(
function* (input: UpdateThreadMetadataInput) {
const commandId = yield* allocateCommandId(input);
@@ -649,3 +725,26 @@ export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun"
targetRunId: input.targetRunId,
});
});
export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* (
input: CancelQueuedRunInput,
) {
return yield* dispatch({
type: "queued-run.cancel",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
runId: input.runId,
});
});
export const editQueuedRun = Effect.fn("EnvironmentCommands.editQueuedRun")(function* (
input: EditQueuedRunInput,
) {
return yield* dispatch({
type: "queued-run.edit",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
runId: input.runId,
text: input.text,
});
});
@@ -40,6 +40,30 @@ describe("V2 client presentation", () => {
});
});
it("preserves shell run timestamps for sidebar activity clocks", () => {
const runId = RunId.make("run-working-clock");
const requestedAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
const startedAt = DateTime.makeUnsafe("2026-06-20T01:00:02.000Z");
const shell = presentThreadShell(environmentId, {
...v2ThreadShell,
latestRunId: runId,
latestRunRequestedAt: requestedAt,
latestRunStartedAt: startedAt,
latestRunCompletedAt: null,
activeRunId: runId,
status: "running",
updatedAt: DateTime.makeUnsafe("2026-06-20T01:04:45.000Z"),
});
expect(shell.latestRun).toMatchObject({
runId,
status: "running",
requestedAt: "2026-06-20T01:00:00.000Z",
startedAt: "2026-06-20T01:00:02.000Z",
completedAt: null,
});
});
it("derives execution summaries without wrapping or copying the projection", () => {
const runId = RunId.make("run-1");
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
+24 -3
View File
@@ -91,6 +91,16 @@ export interface EnvironmentThreadShell {
readonly createdAt: string;
readonly updatedAt: string;
readonly archivedAt: string | null;
readonly settledOverride: "settled" | "active" | null;
readonly settledAt: string | null;
readonly snoozedUntil: string | null;
readonly snoozedAt: string | null;
/**
* Server-tracked visited watermark. `undefined` means the environment's
* server predates visited tracking and clients should fall back to any
* local visited state they keep.
*/
readonly lastVisitedAt?: string | null;
readonly deletedAt: string | null;
readonly source: OrchestrationV2ThreadShell;
}
@@ -143,10 +153,14 @@ export function presentThreadShell(
: ({
runId: thread.latestRunId,
status: thread.status === "idle" ? "completed" : thread.status,
requestedAt: null,
startedAt: null,
requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
startedAt: nullableIso(thread.latestRunStartedAt ?? null),
completedAt:
thread.status === "idle" || terminalRunStatus(thread.status) ? updatedAt : null,
thread.latestRunCompletedAt === undefined
? thread.status === "idle" || terminalRunStatus(thread.status)
? updatedAt
: null
: nullableIso(thread.latestRunCompletedAt),
assistantMessageId: null,
} satisfies ThreadRunSummary);
return {
@@ -177,6 +191,13 @@ export function presentThreadShell(
createdAt: iso(thread.createdAt),
updatedAt,
archivedAt: nullableIso(thread.archivedAt),
settledOverride: thread.settledOverride,
settledAt: nullableIso(thread.settledAt),
snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
snoozedAt: nullableIso(thread.snoozedAt ?? null),
...(thread.lastVisitedAt === undefined
? {}
: { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
deletedAt: nullableIso(thread.deletedAt),
source: thread,
};
@@ -36,7 +36,7 @@ const run = {
contextHandoffId: null,
} satisfies OrchestrationV2Run;
function commandItem(id: string, output = "done"): OrchestrationV2TurnItem {
function commandItem(id: string, output = "done", ordinal = 1): OrchestrationV2TurnItem {
return {
id: TurnItemId.make(id),
threadId,
@@ -46,7 +46,7 @@ function commandItem(id: string, output = "done"): OrchestrationV2TurnItem {
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 1,
ordinal,
status: "completed",
title: null,
startedAt: now,
@@ -77,6 +77,9 @@ const emptyProjection = {
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
},
runs: [],
@@ -197,6 +200,39 @@ describe("applyOrchestrationV2ProjectionEvent", () => {
expect(next?.visibleTurnItems[1]).toBe(secondRow);
});
it("inserts live turn items by authoritative ordinal", () => {
const queuedFuture = commandItem("item-queued-future", "queued", 300);
const activeAssistant = commandItem("item-active-assistant", "done", 201);
const queuedRow = {
position: 0,
visibility: "local" as const,
sourceThreadId: threadId,
sourceItemId: queuedFuture.id,
item: queuedFuture,
};
const projection = {
...emptyProjection,
runs: [run],
turnItems: [queuedFuture],
visibleTurnItems: [queuedRow],
};
const event = {
id: "event-active-assistant",
type: "turn-item.updated",
threadId,
runId,
occurredAt: now,
payload: activeAssistant,
} as OrchestrationV2DomainEvent;
const next = applyOrchestrationV2ProjectionEvent(projection, event);
expect(next?.visibleTurnItems.map((row) => row.item.id)).toEqual([
activeAssistant.id,
queuedFuture.id,
]);
expect(next?.visibleTurnItems.map((row) => row.position)).toEqual([0, 1]);
});
it("removes only hidden local items while preserving inherited rows", () => {
const inherited = commandItem("item-inherited");
const local = commandItem("item-local");
@@ -67,15 +67,15 @@ function upsertVisibleTurnItem(
const rows = projection.visibleTurnItems;
const index = rows.findIndex((row) => row.sourceItemId === item.id);
const next = {
position: index === -1 ? rows.length : rows[index]!.position,
position: 0,
visibility: "local" as const,
sourceThreadId: item.threadId,
sourceItemId: item.id,
item,
};
if (index === -1) return [...rows, next];
const previous = rows[index]!;
const previous = index === -1 ? undefined : rows[index]!;
if (
previous !== undefined &&
previous.visibility === next.visibility &&
previous.sourceThreadId === next.sourceThreadId &&
previous.sourceItemId === next.sourceItemId &&
@@ -83,9 +83,16 @@ function upsertVisibleTurnItem(
) {
return rows;
}
const updated = [...rows];
updated[index] = next;
return updated;
const updated = index === -1 ? [...rows] : [...rows.slice(0, index), ...rows.slice(index + 1)];
const insertionIndex = updated.findIndex(
(row) =>
row.visibility === "local" &&
(row.item.ordinal > item.ordinal ||
(row.item.ordinal === item.ordinal &&
String(row.item.id).localeCompare(String(item.id)) > 0)),
);
updated.splice(insertionIndex === -1 ? updated.length : insertionIndex, 0, next);
return renumberVisibleItems(updated);
}
/** Applies one committed event to a matching thread projection. */
@@ -107,6 +114,10 @@ export function applyOrchestrationV2ProjectionEvent(
case "thread.model-selection-updated":
case "thread.provider-switched":
return { ...base, thread: event.payload };
// Visited tracking is read state, not activity: skip the updatedAt bump.
case "thread.visited":
case "thread.marked-unread":
return { ...projection, thread: event.payload };
case "run.created":
case "run.updated": {
const next = { ...base, runs: upsertEntity(base.runs, event.payload) };
@@ -52,6 +52,9 @@ export const v2ThreadShell: OrchestrationV2ThreadShell = {
createdAt: v2Now,
updatedAt: v2Now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
};
@@ -74,6 +77,9 @@ export const v2Projection: OrchestrationV2ThreadProjection = {
createdAt: v2Now,
updatedAt: v2Now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
},
runs: [],
@@ -4,9 +4,12 @@ import { Atom } from "effect/unstable/reactivity";
import { createAtomCommandScheduler, createEnvironmentCommand } from "./runtime.ts";
import {
type ArchiveThreadInput,
type CancelQueuedRunInput,
type CreateThreadInput,
type DeleteThreadInput,
type EditQueuedRunInput,
type InterruptThreadTurnInput,
type MarkThreadUnreadInput,
type ForkThreadFromRunInput,
type MergeThreadBackInput,
type PromoteQueuedRunInput,
@@ -26,11 +29,15 @@ import {
type UnsettleThreadInput,
type UnsnoozeThreadInput,
type UpdateThreadMetadataInput,
type VisitThreadInput,
archiveThread,
cancelQueuedRun,
createThread,
deleteThread,
editQueuedRun,
interruptThreadTurn,
forkThreadFromRun,
markThreadUnread,
mergeThreadBack,
promoteQueuedRun,
reorderQueuedRun,
@@ -49,14 +56,18 @@ import {
unsettleThread,
unsnoozeThread,
updateThreadMetadata,
visitThread,
} from "../operations/commands.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
export type {
ArchiveThreadInput,
CancelQueuedRunInput,
CreateThreadInput,
DeleteThreadInput,
EditQueuedRunInput,
InterruptThreadTurnInput,
MarkThreadUnreadInput,
ForkThreadFromRunInput,
MergeThreadBackInput,
PromoteQueuedRunInput,
@@ -77,6 +88,7 @@ export type {
UnsettleThreadInput,
UnsnoozeThreadInput,
UpdateThreadMetadataInput,
VisitThreadInput,
} from "../operations/commands.ts";
export function createThreadEnvironmentAtoms<R, E>(
@@ -149,6 +161,18 @@ export function createThreadEnvironmentAtoms<R, E>(
scheduler,
concurrency,
}),
visit: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:visit",
execute: (input: VisitThreadInput) => visitThread(input),
scheduler,
concurrency,
}),
markUnread: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:mark-unread",
execute: (input: MarkThreadUnreadInput) => markThreadUnread(input),
scheduler,
concurrency,
}),
updateMetadata: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:update-metadata",
execute: (input: UpdateThreadMetadataInput) => updateThreadMetadata(input),
@@ -234,5 +258,17 @@ export function createThreadEnvironmentAtoms<R, E>(
scheduler,
concurrency,
}),
cancelQueuedRun: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:cancel-queued-run",
execute: (input: CancelQueuedRunInput) => cancelQueuedRun(input),
scheduler,
concurrency,
}),
editQueuedRun: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:edit-queued-run",
execute: (input: EditQueuedRunInput) => editQueuedRun(input),
scheduler,
concurrency,
}),
};
}
@@ -46,7 +46,7 @@ describe("thread execution presentation", () => {
const runtime = deriveThreadRuntime(projection);
expect(runtime).toMatchObject({
status: "queued",
status: "running",
activeRunId: runningRun.id,
});
expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
@@ -62,6 +62,7 @@ export function deriveThreadRuntime(
projection: OrchestrationV2ThreadProjection,
): ThreadRuntimeSummary | null {
const latestRun = deriveLatestThreadRun(projection);
const activityRun = deriveThreadActivityRun(projection);
const providerSession = projection.providerSessions.findLast(
(session) => session.providerInstanceId === projection.thread.providerInstanceId,
);
@@ -69,7 +70,10 @@ export function deriveThreadRuntime(
const activeRunId =
latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
return {
status: latestRun?.status ?? "idle",
// Queueing creates a newer run, but does not replace the provider work
// already in flight. Present the executing run's status until it reaches
// a terminal state so clients do not flash from "running" to "queued".
status: activityRun?.status ?? "idle",
activeRunId,
providerInstanceId: projection.thread.providerInstanceId,
providerName: providerSession?.driver ?? null,
@@ -85,6 +85,42 @@ describe("thread workflows", () => {
expect(state.canPromoteToSteer).toBe(true);
});
it("removes only the promoted head from the visible queue", () => {
const state = deriveThreadQueueWorkflowState({
thread: { id: "thread", activeProviderThreadId: "provider-thread" },
runs: [
{
id: "promoted",
status: "starting",
userMessageId: "message-promoted",
providerThreadId: "provider-thread",
ordinal: 2,
queuePosition: null,
},
{
id: "still-queued",
status: "queued",
userMessageId: "message-still-queued",
providerThreadId: "provider-thread",
ordinal: 3,
queuePosition: 2,
},
],
messages: [
{ id: "message-promoted", text: "Run now" },
{ id: "message-still-queued", text: "Wait longer" },
],
providerTurns: [],
providerThreads: [],
providerSessions: [],
} as never);
expect(state.activeRun?.id).toBe("promoted");
expect(state.queuedRuns.map(({ run, text }) => [run.id, text])).toEqual([
["still-queued", "Wait longer"],
]);
});
it.each(["preparing", "starting", "waiting"] as const)(
"does not promote queued work into a %s run",
(status) => {