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:
1 parent
918e4155dd
commit
4124948442
73 files changed
+3971
-1271
No files matched your search
@@ -73,6 +73,7 @@ const SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: NOW,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
],
|
||||
@@ -108,6 +109,7 @@ const THREAD_SNAPSHOT: OrchestrationV2ThreadDetailSnapshot = {
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: NOW,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
runs: [],
|
||||
|
||||
@@ -25,6 +25,8 @@ import type { StatusTone } from "../../components/StatusPill";
|
||||
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
|
||||
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
|
||||
import { scopedThreadKey } from "../../lib/scopedEntities";
|
||||
import { threadEnvironment } from "../../state/threads";
|
||||
import { useAtomCommand } from "../../state/use-atom-command";
|
||||
import type {
|
||||
PendingApproval,
|
||||
PendingUserInput,
|
||||
@@ -240,6 +242,39 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
|
||||
selectedThreadKeyRef.current = selectedThreadKey;
|
||||
}, [selectedThreadKey]);
|
||||
|
||||
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
|
||||
const lastDispatchedVisitRef = useRef<string | null>(null);
|
||||
const selectedThreadId = props.selectedThread.id;
|
||||
const selectedThreadUpdatedAt = props.selectedThread.updatedAt;
|
||||
const selectedThreadLastVisitedAt = props.selectedThread.lastVisitedAt;
|
||||
useEffect(() => {
|
||||
// Records the server-side visited watermark while the thread is on
|
||||
// screen (mirror of web ChatView), so the "Done" marker clears on every
|
||||
// device. Field absent → the server predates visited tracking.
|
||||
if (selectedThreadLastVisitedAt === undefined) return;
|
||||
const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
|
||||
if (Number.isNaN(threadUpdatedAtMs)) return;
|
||||
const lastVisitedAtMs = selectedThreadLastVisitedAt
|
||||
? Date.parse(selectedThreadLastVisitedAt)
|
||||
: NaN;
|
||||
if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
|
||||
// Dedupe per watermark — the effect re-runs before the command echo lands.
|
||||
const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
|
||||
if (lastDispatchedVisitRef.current === dispatchKey) return;
|
||||
lastDispatchedVisitRef.current = dispatchKey;
|
||||
void visitThread({
|
||||
environmentId: props.environmentId,
|
||||
input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
|
||||
});
|
||||
}, [
|
||||
props.environmentId,
|
||||
selectedThreadId,
|
||||
selectedThreadKey,
|
||||
selectedThreadLastVisitedAt,
|
||||
selectedThreadUpdatedAt,
|
||||
visitThread,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
setAnchorMessageId(null);
|
||||
lastScrolledAnchorMessageIdRef.current = null;
|
||||
|
||||
@@ -29,13 +29,10 @@ import { useThreadPr } from "../../state/use-thread-pr";
|
||||
import { ThreadSwipeable } from "../home/thread-swipe-actions";
|
||||
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
|
||||
import {
|
||||
resolveThreadListV2SnoozeMenuSelection,
|
||||
resolveThreadListV2SnoozeGateExpiryMs,
|
||||
resolveThreadListV2Status,
|
||||
resolveThreadListV2SwipeActions,
|
||||
threadHasUnseenCompletion,
|
||||
type ThreadListV2Status,
|
||||
} from "./threadListV2";
|
||||
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
|
||||
|
||||
/**
|
||||
* Thread List v2 renders one flat native list: rich edge-to-edge rows for
|
||||
@@ -418,7 +415,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
|
||||
const selected = props.selected === true;
|
||||
|
||||
const status = resolveThreadListV2Status(thread);
|
||||
const statusLabel = STATUS_LABEL_BY_STATUS[status];
|
||||
// "Done" marks a completion the user has not opened yet — same emerald
|
||||
// label as the web sidebar, sourced from the server-side visited watermark
|
||||
// so checking a thread on any device clears it everywhere.
|
||||
const isUnread = status === "ready" && threadHasUnseenCompletion(thread);
|
||||
const statusLabel =
|
||||
STATUS_LABEL_BY_STATUS[status] ??
|
||||
(isUnread ? { label: "Done", className: "text-emerald-700 dark:text-emerald-300" } : undefined);
|
||||
const timeLabel = threadTimeLabel(thread);
|
||||
|
||||
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
|
||||
|
||||
@@ -122,6 +122,27 @@ export function resolveThreadListV2Enabled(input: {
|
||||
return input.legacyPreference !== true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Completed-but-not-yet-seen, mirroring the web sidebar's
|
||||
* hasUnseenCompletion. The visited watermark is server state
|
||||
* (thread.lastVisitedAt), so the marker agrees across web and mobile.
|
||||
* Never-visited threads count as read — a fresh environment must not light
|
||||
* up its whole history — and pre-tracking servers (field absent) never
|
||||
* report unread.
|
||||
*/
|
||||
export function threadHasUnseenCompletion(
|
||||
thread: Pick<EnvironmentThreadShell, "latestRun" | "lastVisitedAt">,
|
||||
): boolean {
|
||||
const completedAt = thread.latestRun?.completedAt;
|
||||
if (!completedAt) return false;
|
||||
const completedAtMs = Date.parse(completedAt);
|
||||
if (Number.isNaN(completedAtMs)) return false;
|
||||
if (!thread.lastVisitedAt) return false;
|
||||
const lastVisitedAtMs = Date.parse(thread.lastVisitedAt);
|
||||
if (Number.isNaN(lastVisitedAtMs)) return true;
|
||||
return completedAtMs > lastVisitedAtMs;
|
||||
}
|
||||
|
||||
export function resolveThreadListV2Status(
|
||||
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
|
||||
): ThreadListV2Status {
|
||||
|
||||
@@ -108,6 +108,29 @@ describe("buildThreadFeed", () => {
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it("adds queued input only after dispatch creates its turn item", () => {
|
||||
const dispatchedRunId = RunId.make("run-dispatched-queued");
|
||||
const dispatchedMessageId = MessageId.make("message-dispatched-queued");
|
||||
expect(buildThreadFeed([])).toEqual([]);
|
||||
|
||||
const promotedEntries = buildThreadFeed([
|
||||
projected(
|
||||
{
|
||||
...userMessage(),
|
||||
id: TurnItemId.make("item-dispatched-queued"),
|
||||
runId: dispatchedRunId,
|
||||
messageId: dispatchedMessageId,
|
||||
inputIntent: "turn_start",
|
||||
},
|
||||
0,
|
||||
),
|
||||
]);
|
||||
expect(promotedEntries.map((entry) => entry.id)).toEqual([dispatchedMessageId]);
|
||||
expect(
|
||||
promotedEntries[0]?.type === "message" ? promotedEntries[0].message.inputIntent : undefined,
|
||||
).toBe("turn_start");
|
||||
});
|
||||
|
||||
it("preserves authoritative V2 order instead of sorting reconstructed collections", () => {
|
||||
const rows = [
|
||||
projected(userMessage("2026-06-20T00:00:03.000Z"), 0),
|
||||
|
||||
@@ -951,12 +951,13 @@ export function buildPendingUserInputAnswers(
|
||||
export function buildThreadFeed(
|
||||
visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
|
||||
): ThreadFeedEntry[] {
|
||||
const entries = visibleTurnItems.map((row): RawThreadFeedEntry => {
|
||||
const entries: RawThreadFeedEntry[] = [];
|
||||
for (const row of visibleTurnItems) {
|
||||
const item = row.item;
|
||||
const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
|
||||
if (item.type === "user_message" || item.type === "assistant_message") {
|
||||
const updatedAt = DateTime.formatIso(item.updatedAt);
|
||||
return {
|
||||
entries.push({
|
||||
type: "message",
|
||||
id: item.messageId,
|
||||
createdAt,
|
||||
@@ -980,16 +981,17 @@ export function buildThreadFeed(
|
||||
updatedAt,
|
||||
projectedItem: row,
|
||||
},
|
||||
};
|
||||
});
|
||||
continue;
|
||||
}
|
||||
const activity = toFeedActivity(row);
|
||||
return {
|
||||
entries.push({
|
||||
type: "activity",
|
||||
id: activity.id,
|
||||
createdAt,
|
||||
runId: item.runId,
|
||||
activity,
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
return groupAdjacentActivities(entries);
|
||||
}
|
||||
@@ -152,6 +152,7 @@ export const make = Effect.gen(function* () {
|
||||
threadPinning: true,
|
||||
threadPinReorder: true,
|
||||
threadTitleRegeneration: true,
|
||||
threadVisitedTracking: true,
|
||||
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
|
||||
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
|
||||
},
|
||||
|
||||
@@ -603,6 +603,9 @@ function makeTurnInput(input: {
|
||||
createdAt: input.now,
|
||||
updatedAt: input.now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
threadId: input.threadId,
|
||||
|
||||
@@ -107,6 +107,9 @@ function makeClaudeTestAppThread(input: {
|
||||
createdAt: input.now,
|
||||
updatedAt: input.now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
};
|
||||
}
|
||||
@@ -979,6 +982,9 @@ describe("ClaudeAdapterV2 native fork", () => {
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
},
|
||||
threadId: targetThreadId,
|
||||
@@ -1153,6 +1159,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
|
||||
readonly subtype?: string;
|
||||
readonly isError?: boolean;
|
||||
readonly errors?: ReadonlyArray<string>;
|
||||
readonly apiErrorStatus?: number;
|
||||
}) =>
|
||||
claudeSdkFrame({
|
||||
type: "result",
|
||||
@@ -1176,6 +1183,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
...(input.origin === undefined ? {} : { origin: input.origin }),
|
||||
...(input.errors === undefined ? {} : { errors: input.errors }),
|
||||
...(input.apiErrorStatus === undefined ? {} : { api_error_status: input.apiErrorStatus }),
|
||||
});
|
||||
const turnOneResult = makeResultFrame({
|
||||
uuid: "00000000-0000-4000-8000-000000000102",
|
||||
@@ -1303,6 +1311,125 @@ describe("ClaudeAdapterV2 background wake turns", () => {
|
||||
});
|
||||
const makeWakeHarness = makeWakeHarnessWithOptions();
|
||||
|
||||
it.effect("projects API retries and resolves the same item after recovery", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeWakeHarness;
|
||||
const now = yield* DateTime.now;
|
||||
yield* harness.runtime.startTurn(
|
||||
makeClaudeTestTurnInput({
|
||||
threadId: harness.threadId,
|
||||
providerThread: harness.providerThread,
|
||||
now,
|
||||
attemptId: RunAttemptId.make("attempt-claude-api-retry"),
|
||||
text: "Open github.com.",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
|
||||
yield* Queue.offer(
|
||||
harness.sdkMessages,
|
||||
claudeSdkFrame({
|
||||
type: "system",
|
||||
subtype: "api_retry",
|
||||
attempt: 2,
|
||||
max_retries: 10,
|
||||
retry_delay_ms: 1_500,
|
||||
error_status: 529,
|
||||
error: "overloaded",
|
||||
uuid: "00000000-0000-4000-8000-000000000201",
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
}),
|
||||
);
|
||||
const retryItems = () =>
|
||||
harness.events.flatMap((event) =>
|
||||
event.type === "turn_item.updated" &&
|
||||
event.turnItem.type === "error" &&
|
||||
event.turnItem.retry !== undefined
|
||||
? [event.turnItem]
|
||||
: [],
|
||||
);
|
||||
yield* awaitUntil(() => retryItems().length === 1, "Claude retry item");
|
||||
const runningRetry = retryItems()[0];
|
||||
assert.equal(runningRetry?.status, "running");
|
||||
assert.equal(runningRetry?.failure.code, "api_error_529");
|
||||
assert.deepEqual(runningRetry?.retry, {
|
||||
attempt: 2,
|
||||
maxAttempts: 10,
|
||||
retryDelayMs: 1_500,
|
||||
});
|
||||
|
||||
yield* Queue.offer(
|
||||
harness.sdkMessages,
|
||||
makeResultFrame({
|
||||
uuid: "00000000-0000-4000-8000-000000000202",
|
||||
result: "Opened GitHub.",
|
||||
}),
|
||||
);
|
||||
yield* awaitUntil(() => harness.terminalEvents().length === 1, "recovered Claude turn");
|
||||
yield* awaitUntil(() => retryItems().length === 2, "resolved Claude retry item");
|
||||
const recoveredRetry = retryItems()[1];
|
||||
assert.equal(recoveredRetry?.id, runningRetry?.id);
|
||||
assert.equal(recoveredRetry?.status, "completed");
|
||||
assert.equal(recoveredRetry?.title, "Provider recovered");
|
||||
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("carries exhausted retry progress into the terminal provider error", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const harness = yield* makeWakeHarness;
|
||||
const now = yield* DateTime.now;
|
||||
yield* harness.runtime.startTurn(
|
||||
makeClaudeTestTurnInput({
|
||||
threadId: harness.threadId,
|
||||
providerThread: harness.providerThread,
|
||||
now,
|
||||
attemptId: RunAttemptId.make("attempt-claude-api-retry-exhausted"),
|
||||
text: "Open github.com.",
|
||||
attachments: [],
|
||||
}),
|
||||
);
|
||||
yield* Queue.offer(
|
||||
harness.sdkMessages,
|
||||
claudeSdkFrame({
|
||||
type: "system",
|
||||
subtype: "api_retry",
|
||||
attempt: 10,
|
||||
max_retries: 10,
|
||||
retry_delay_ms: 38_010,
|
||||
error_status: 529,
|
||||
error: "overloaded",
|
||||
uuid: "00000000-0000-4000-8000-000000000203",
|
||||
session_id: WAKE_NATIVE_SESSION,
|
||||
}),
|
||||
);
|
||||
yield* Queue.offer(
|
||||
harness.sdkMessages,
|
||||
makeResultFrame({
|
||||
uuid: "00000000-0000-4000-8000-000000000204",
|
||||
result: "Claude is temporarily overloaded.",
|
||||
isError: true,
|
||||
apiErrorStatus: 529,
|
||||
}),
|
||||
);
|
||||
yield* awaitUntil(() => harness.terminalEvents().length === 1, "failed Claude turn");
|
||||
|
||||
const terminal = harness.terminalEvents()[0];
|
||||
assert.equal(terminal?.status, "failed");
|
||||
if (terminal?.status !== "failed") return;
|
||||
assert.deepEqual(terminal.retry, {
|
||||
attempt: 10,
|
||||
maxAttempts: 10,
|
||||
retryDelayMs: 38_010,
|
||||
});
|
||||
assert.isDefined(terminal.retryStartedAt);
|
||||
assert.equal(terminal.failure.code, "api_error_529");
|
||||
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
|
||||
),
|
||||
);
|
||||
|
||||
it.effect("buffers wake output and requests a single continuation run", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
|
||||
@@ -10,6 +10,7 @@ import {
|
||||
type Query as ClaudeQuery,
|
||||
type Settings as ClaudeSdkSettings,
|
||||
type SDKAssistantMessage,
|
||||
type SDKAPIRetryMessage,
|
||||
type SDKMessage,
|
||||
type SDKResultMessage,
|
||||
type SDKUserMessage,
|
||||
@@ -27,6 +28,7 @@ import {
|
||||
type OrchestrationV2ExecutionNode,
|
||||
type OrchestrationV2ProviderCapabilities,
|
||||
type OrchestrationV2ProviderFailure,
|
||||
type OrchestrationV2ProviderRetry,
|
||||
type OrchestrationV2ProviderSession,
|
||||
type OrchestrationV2ProviderThread,
|
||||
type OrchestrationV2ProviderTurn,
|
||||
@@ -70,7 +72,7 @@ import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanc
|
||||
import { T3_CODE_ORCHESTRATION_INSTRUCTIONS } from "../../provider/T3OrchestrationInstructions.ts";
|
||||
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
|
||||
import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts";
|
||||
import { makeProviderFailure } from "../ProviderFailure.ts";
|
||||
import { makeProviderFailure, makeProviderRetryTurnItem } from "../ProviderFailure.ts";
|
||||
import { turnScopedSelectionTransition } from "../ProviderSelectionTransition.ts";
|
||||
import {
|
||||
ProviderAdapterEnsureThreadError,
|
||||
@@ -1802,6 +1804,19 @@ function providerFailureFromResult(
|
||||
});
|
||||
}
|
||||
|
||||
function providerFailureFromApiRetry(message: SDKAPIRetryMessage): OrchestrationV2ProviderFailure {
|
||||
const errorName = message.error.replaceAll("_", " ");
|
||||
return makeProviderFailure({
|
||||
message: `Claude API ${errorName}.`,
|
||||
code:
|
||||
message.error_status === null
|
||||
? message.error
|
||||
: `api_error_${Math.trunc(message.error_status)}`,
|
||||
class: message.error_status === null ? "transport_error" : "provider_error",
|
||||
retryable: true,
|
||||
});
|
||||
}
|
||||
|
||||
function buildAssistantArtifacts(input: {
|
||||
readonly idAllocator: IdAllocatorV2Shape;
|
||||
readonly turnInput: ProviderAdapterV2TurnInput;
|
||||
@@ -1908,6 +1923,13 @@ interface ActiveClaudeTurnContext {
|
||||
readonly subagentNodesByTaskId: Map<string, OrchestrationV2ExecutionNode["id"]>;
|
||||
}
|
||||
|
||||
interface ActiveClaudeProviderRetry {
|
||||
readonly retry: OrchestrationV2ProviderRetry;
|
||||
readonly failure: OrchestrationV2ProviderFailure;
|
||||
readonly startedAt: DateTime.Utc;
|
||||
readonly itemOrdinal: number;
|
||||
}
|
||||
|
||||
interface ActiveClaudeSubagent {
|
||||
task: OrchestrationV2Subagent;
|
||||
readonly childThreadId: ThreadId;
|
||||
@@ -1993,6 +2015,9 @@ export function makeClaudeAdapterV2(
|
||||
const openedNativeThreads = yield* Ref.make(new Set<string>());
|
||||
const itemOrdinals = yield* Ref.make(new Map<string, number>());
|
||||
const nextItemOrdinalsByTurn = yield* Ref.make(new Map<string, number>());
|
||||
const providerRetries = yield* Ref.make(
|
||||
new Map<OrchestrationV2ProviderTurn["id"], ActiveClaudeProviderRetry>(),
|
||||
);
|
||||
const pendingRuntimeRequests = yield* Ref.make(
|
||||
new Map<string, PendingClaudeRuntimeRequest>(),
|
||||
);
|
||||
@@ -2840,6 +2865,37 @@ export function makeClaudeAdapterV2(
|
||||
);
|
||||
}
|
||||
|
||||
const providerRetry = yield* Ref.modify(providerRetries, (current) => {
|
||||
const retry = current.get(input.context.providerTurnId);
|
||||
if (retry === undefined) {
|
||||
return [undefined, current] as const;
|
||||
}
|
||||
const updated = new Map(current);
|
||||
updated.delete(input.context.providerTurnId);
|
||||
return [retry, updated] as const;
|
||||
});
|
||||
if (providerRetry !== undefined && input.status !== "failed") {
|
||||
yield* emitProviderEvent({
|
||||
type: "turn_item.updated",
|
||||
driver: CLAUDE_PROVIDER,
|
||||
turnItem: makeProviderRetryTurnItem({
|
||||
idAllocator,
|
||||
driver: CLAUDE_PROVIDER,
|
||||
threadId: input.context.input.threadId,
|
||||
runId: input.context.input.runId,
|
||||
nodeId: input.context.input.rootNodeId,
|
||||
providerThreadId: input.context.input.providerThread.id,
|
||||
providerTurnId: input.context.providerTurnId,
|
||||
itemOrdinal: providerRetry.itemOrdinal,
|
||||
failure: providerRetry.failure,
|
||||
retry: providerRetry.retry,
|
||||
status: input.status,
|
||||
startedAt: providerRetry.startedAt,
|
||||
updatedAt: input.completedAt,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
const threadDisposition = input.threadDisposition ?? "reusable";
|
||||
const terminalEvent: ProviderAdapterV2Event =
|
||||
input.status === "failed"
|
||||
@@ -2855,6 +2911,12 @@ export function makeClaudeAdapterV2(
|
||||
),
|
||||
status: input.status,
|
||||
failure: input.failure ?? makeProviderFailure({ class: "provider_error" }),
|
||||
...(providerRetry === undefined
|
||||
? {}
|
||||
: {
|
||||
retry: providerRetry.retry,
|
||||
retryStartedAt: providerRetry.startedAt,
|
||||
}),
|
||||
threadDisposition,
|
||||
}
|
||||
: {
|
||||
@@ -3144,6 +3206,51 @@ export function makeClaudeAdapterV2(
|
||||
context.nativeMessageCursor = message.uuid;
|
||||
}
|
||||
|
||||
if (message.type === "system" && message.subtype === "api_retry") {
|
||||
const updatedAt = yield* DateTime.now;
|
||||
const previous = (yield* Ref.get(providerRetries)).get(context.providerTurnId);
|
||||
const retry: OrchestrationV2ProviderRetry = {
|
||||
attempt: Math.max(1, Math.trunc(message.attempt)),
|
||||
maxAttempts: Math.max(1, Math.trunc(message.max_retries)),
|
||||
retryDelayMs: Math.max(0, Math.trunc(message.retry_delay_ms)),
|
||||
};
|
||||
const failure = providerFailureFromApiRetry(message);
|
||||
const itemOrdinal =
|
||||
previous?.itemOrdinal ??
|
||||
(yield* resolveItemOrdinal(context, `terminal-failure:${context.providerTurnId}`));
|
||||
const state: ActiveClaudeProviderRetry = {
|
||||
retry,
|
||||
failure,
|
||||
startedAt: previous?.startedAt ?? updatedAt,
|
||||
itemOrdinal,
|
||||
};
|
||||
yield* Ref.update(providerRetries, (current) => {
|
||||
const updated = new Map(current);
|
||||
updated.set(context.providerTurnId, state);
|
||||
return updated;
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "turn_item.updated",
|
||||
driver: CLAUDE_PROVIDER,
|
||||
turnItem: makeProviderRetryTurnItem({
|
||||
idAllocator,
|
||||
driver: CLAUDE_PROVIDER,
|
||||
threadId: context.input.threadId,
|
||||
runId: context.input.runId,
|
||||
nodeId: context.input.rootNodeId,
|
||||
providerThreadId: context.input.providerThread.id,
|
||||
providerTurnId: context.providerTurnId,
|
||||
itemOrdinal,
|
||||
failure,
|
||||
retry,
|
||||
status: "running",
|
||||
startedAt: state.startedAt,
|
||||
updatedAt,
|
||||
}),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.type === "system" && message.subtype === "task_started") {
|
||||
if (isClaudeNonSubagentTask(message)) {
|
||||
context.ignoredTaskIds.add(message.task_id);
|
||||
|
||||
@@ -835,6 +835,9 @@ function makeCodexTestAppThread(input: {
|
||||
createdAt: input.now,
|
||||
updatedAt: input.now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
};
|
||||
}
|
||||
@@ -1112,6 +1115,87 @@ describe("CodexAdapterV2 post-settle continuation", () => {
|
||||
event.type === "message.updated" && event.message.role === "assistant",
|
||||
);
|
||||
|
||||
it.effect("projects retryable app-server errors and resolves the same item after recovery", () =>
|
||||
Effect.scoped(
|
||||
Effect.gen(function* () {
|
||||
const scenario = "codex-provider-api-retry";
|
||||
const nativeThreadId = `native-${scenario}-thread`;
|
||||
const nativeTurnId = `native-${scenario}-turn`;
|
||||
const transcript = makeCodexReplayTranscript({
|
||||
scenario,
|
||||
entries: [
|
||||
...codexReplayPreamble({
|
||||
nativeThreadId,
|
||||
nativeTurnId,
|
||||
prompt: "Open github.com.",
|
||||
}),
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "error/retry",
|
||||
frame: {
|
||||
method: "error",
|
||||
params: {
|
||||
threadId: nativeThreadId,
|
||||
turnId: nativeTurnId,
|
||||
willRetry: true,
|
||||
error: {
|
||||
message: "Reconnecting... 2/5",
|
||||
additionalDetails: "The response stream disconnected.",
|
||||
codexErrorInfo: {
|
||||
responseStreamDisconnected: { httpStatusCode: 529 },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "emit_inbound",
|
||||
label: "turn/completed",
|
||||
frame: {
|
||||
method: "turn/completed",
|
||||
params: {
|
||||
threadId: nativeThreadId,
|
||||
turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
const harness = yield* makeCodexReplayHarness(transcript);
|
||||
const now = yield* DateTime.now;
|
||||
yield* harness.runtime.startTurn(
|
||||
makeCodexTestTurnInput({
|
||||
threadId: harness.threadId,
|
||||
providerThread: harness.providerThread,
|
||||
now,
|
||||
attemptId: RunAttemptId.make("attempt-codex-provider-api-retry"),
|
||||
text: "Open github.com.",
|
||||
}),
|
||||
);
|
||||
yield* awaitUntil(() => harness.terminalEvents().length === 1, "Codex retry recovery");
|
||||
|
||||
const retryItems = harness.events.flatMap((event) =>
|
||||
event.type === "turn_item.updated" &&
|
||||
event.turnItem.type === "error" &&
|
||||
event.turnItem.retry !== undefined
|
||||
? [event.turnItem]
|
||||
: [],
|
||||
);
|
||||
assert.lengthOf(retryItems, 2);
|
||||
assert.equal(retryItems[0]?.status, "running");
|
||||
assert.equal(retryItems[0]?.failure.code, "responseStreamDisconnected");
|
||||
assert.deepEqual(retryItems[0]?.retry, {
|
||||
attempt: 2,
|
||||
maxAttempts: 5,
|
||||
retryDelayMs: null,
|
||||
});
|
||||
assert.equal(retryItems[1]?.id, retryItems[0]?.id);
|
||||
assert.equal(retryItems[1]?.status, "completed");
|
||||
assert.equal(retryItems[1]?.title, "Provider recovered");
|
||||
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
|
||||
),
|
||||
);
|
||||
|
||||
const finalAnswerTranscript = (
|
||||
scenario: string,
|
||||
answers: ReadonlyArray<{
|
||||
|
||||
@@ -10,6 +10,8 @@ import type {
|
||||
ModelSelection,
|
||||
OrchestrationV2PlanArtifact,
|
||||
OrchestrationV2ProviderCapabilities,
|
||||
OrchestrationV2ProviderFailure,
|
||||
OrchestrationV2ProviderRetry,
|
||||
OrchestrationV2ProviderSession,
|
||||
OrchestrationV2ProviderThread,
|
||||
OrchestrationV2ProviderTurn,
|
||||
@@ -71,7 +73,7 @@ import {
|
||||
type ProviderContinuationRequest,
|
||||
ProviderContinuationRequests,
|
||||
} from "../ProviderContinuationRequests.ts";
|
||||
import { makeProviderFailure } from "../ProviderFailure.ts";
|
||||
import { makeProviderFailure, makeProviderRetryTurnItem } from "../ProviderFailure.ts";
|
||||
import { turnScopedSelectionTransition } from "../ProviderSelectionTransition.ts";
|
||||
import {
|
||||
ProviderAdapterEnsureThreadError,
|
||||
@@ -771,6 +773,31 @@ export const resolveCodexRollbackTurnCount = Effect.fn("CodexAdapterV2.resolveRo
|
||||
},
|
||||
);
|
||||
|
||||
export function parseCodexRetryProgress(
|
||||
message: string,
|
||||
): Pick<OrchestrationV2ProviderRetry, "attempt" | "maxAttempts"> | null {
|
||||
const match = /\b(\d+)\s*\/\s*(\d+)\b/u.exec(message);
|
||||
if (match?.[1] === undefined || match[2] === undefined) {
|
||||
return null;
|
||||
}
|
||||
const attempt = Number.parseInt(match[1], 10);
|
||||
const maxAttempts = Number.parseInt(match[2], 10);
|
||||
if (attempt < 1 || maxAttempts < 1) {
|
||||
return null;
|
||||
}
|
||||
return { attempt, maxAttempts };
|
||||
}
|
||||
|
||||
function codexErrorInfoCode(value: unknown): string | null {
|
||||
if (typeof value === "string") {
|
||||
return value;
|
||||
}
|
||||
if (typeof value !== "object" || value === null) {
|
||||
return null;
|
||||
}
|
||||
return Object.keys(value)[0] ?? null;
|
||||
}
|
||||
|
||||
interface ActiveCodexTurnContext {
|
||||
readonly input: ProviderAdapterV2TurnInput;
|
||||
readonly projectionAppThread: OrchestrationV2AppThread;
|
||||
@@ -788,6 +815,13 @@ interface ActiveCodexTurnContext {
|
||||
readonly startedAt: DateTime.Utc;
|
||||
}
|
||||
|
||||
interface ActiveCodexProviderRetry {
|
||||
readonly retry: OrchestrationV2ProviderRetry;
|
||||
readonly failure: OrchestrationV2ProviderFailure;
|
||||
readonly startedAt: DateTime.Utc;
|
||||
readonly itemOrdinal: number;
|
||||
}
|
||||
|
||||
/** Snapshot of a still-running commandExecution item for interrupt/fail terminalization. */
|
||||
interface TrackedRunningCommandItem {
|
||||
readonly id: string;
|
||||
@@ -1418,6 +1452,9 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
const nextProviderTurnOrdinals = yield* Ref.make(new Map<string, number>());
|
||||
const itemOrdinals = yield* Ref.make(new Map<string, number>());
|
||||
const nextItemOrdinalsByTurn = yield* Ref.make(new Map<string, number>());
|
||||
const providerRetries = yield* Ref.make(
|
||||
new Map<ProviderTurnId, ActiveCodexProviderRetry>(),
|
||||
);
|
||||
const planDeltas = yield* Ref.make(new Map<string, string>());
|
||||
const planIds = yield* Ref.make(new Map<string, OrchestrationV2PlanArtifact["id"]>());
|
||||
const pendingRuntimeRequests = yield* Ref.make(
|
||||
@@ -3745,6 +3782,73 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
}).pipe(Effect.orDie, turnTerminalizationPermit.withPermits(1)),
|
||||
);
|
||||
|
||||
yield* client.handleServerNotification("error", (payload) =>
|
||||
Effect.gen(function* () {
|
||||
if (!payload.willRetry) {
|
||||
return;
|
||||
}
|
||||
const context = yield* awaitActiveTurn(payload.turnId);
|
||||
if (context === undefined) {
|
||||
return;
|
||||
}
|
||||
const updatedAt = yield* DateTime.now;
|
||||
const previous = (yield* Ref.get(providerRetries)).get(context.providerTurnId);
|
||||
const progress = parseCodexRetryProgress(payload.error.message);
|
||||
const retry: OrchestrationV2ProviderRetry = {
|
||||
attempt: progress?.attempt ?? (previous?.retry.attempt ?? 0) + 1,
|
||||
maxAttempts: progress?.maxAttempts ?? previous?.retry.maxAttempts ?? null,
|
||||
retryDelayMs: null,
|
||||
};
|
||||
const code = codexErrorInfoCode(payload.error.codexErrorInfo);
|
||||
const additionalDetails = payload.error.additionalDetails?.trim();
|
||||
const failure = makeProviderFailure({
|
||||
message:
|
||||
additionalDetails === undefined || additionalDetails.length === 0
|
||||
? payload.error.message
|
||||
: additionalDetails,
|
||||
code,
|
||||
class:
|
||||
code?.startsWith("http") === true || code?.startsWith("responseStream") === true
|
||||
? "transport_error"
|
||||
: "provider_error",
|
||||
retryable: true,
|
||||
});
|
||||
const itemOrdinal =
|
||||
previous?.itemOrdinal ??
|
||||
(yield* resolveItemOrdinal(context, `terminal-failure:${context.providerTurnId}`));
|
||||
const state: ActiveCodexProviderRetry = {
|
||||
retry,
|
||||
failure,
|
||||
startedAt: previous?.startedAt ?? updatedAt,
|
||||
itemOrdinal,
|
||||
};
|
||||
yield* Ref.update(providerRetries, (current) => {
|
||||
const updated = new Map(current);
|
||||
updated.set(context.providerTurnId, state);
|
||||
return updated;
|
||||
});
|
||||
yield* emitProviderEvent({
|
||||
type: "turn_item.updated",
|
||||
driver: CODEX_PROVIDER,
|
||||
turnItem: makeProviderRetryTurnItem({
|
||||
idAllocator,
|
||||
driver: CODEX_PROVIDER,
|
||||
threadId: context.projectionThreadId,
|
||||
runId: context.projectionRunId,
|
||||
nodeId: context.providerNodeId,
|
||||
providerThreadId: context.providerThread.id,
|
||||
providerTurnId: context.providerTurnId,
|
||||
itemOrdinal,
|
||||
failure,
|
||||
retry,
|
||||
status: "running",
|
||||
startedAt: state.startedAt,
|
||||
updatedAt,
|
||||
}),
|
||||
});
|
||||
}).pipe(Effect.orDie),
|
||||
);
|
||||
|
||||
yield* client.handleServerNotification("item/started", (payload) =>
|
||||
Effect.gen(function* () {
|
||||
const context = yield* awaitActiveTurn(payload.turnId);
|
||||
@@ -4469,6 +4573,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
readonly context: ActiveCodexTurnContext;
|
||||
readonly status: OrchestrationV2ProviderTurn["status"];
|
||||
readonly failureMessage?: string;
|
||||
readonly providerRetry?: ActiveCodexProviderRetry;
|
||||
}): Effect.fn.Return<CodexRootTerminalEvent> {
|
||||
const terminalStatus = providerTurnStatusToTerminal(input.status);
|
||||
if (terminalStatus === "failed") {
|
||||
@@ -4483,10 +4588,19 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
`terminal-failure:${input.context.providerTurnId}`,
|
||||
),
|
||||
status: terminalStatus,
|
||||
failure: makeProviderFailure({
|
||||
message: input.failureMessage,
|
||||
class: "provider_error",
|
||||
}),
|
||||
failure:
|
||||
input.failureMessage === undefined && input.providerRetry !== undefined
|
||||
? input.providerRetry.failure
|
||||
: makeProviderFailure({
|
||||
message: input.failureMessage,
|
||||
class: "provider_error",
|
||||
}),
|
||||
...(input.providerRetry === undefined
|
||||
? {}
|
||||
: {
|
||||
retry: input.providerRetry.retry,
|
||||
retryStartedAt: input.providerRetry.startedAt,
|
||||
}),
|
||||
threadDisposition: "reusable",
|
||||
};
|
||||
}
|
||||
@@ -4509,6 +4623,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
readonly nativeTurnId: string;
|
||||
readonly status: OrchestrationV2ProviderTurn["status"];
|
||||
readonly failureMessage?: string;
|
||||
readonly providerRetry?: ActiveCodexProviderRetry;
|
||||
}) {
|
||||
const event = yield* makeRootTerminalEvent(input);
|
||||
const hasActiveDescendants = Array.from((yield* Ref.get(activeTurns)).values()).some(
|
||||
@@ -4563,6 +4678,39 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
if (current !== input.context) {
|
||||
return false;
|
||||
}
|
||||
const providerRetry = yield* Ref.modify(providerRetries, (current) => {
|
||||
const retry = current.get(input.context.providerTurnId);
|
||||
if (retry === undefined) {
|
||||
return [undefined, current] as const;
|
||||
}
|
||||
const updated = new Map(current);
|
||||
updated.delete(input.context.providerTurnId);
|
||||
return [retry, updated] as const;
|
||||
});
|
||||
if (
|
||||
providerRetry !== undefined &&
|
||||
(input.status !== "failed" || input.context.subagent !== null)
|
||||
) {
|
||||
yield* emitProviderEvent({
|
||||
type: "turn_item.updated",
|
||||
driver: CODEX_PROVIDER,
|
||||
turnItem: makeProviderRetryTurnItem({
|
||||
idAllocator,
|
||||
driver: CODEX_PROVIDER,
|
||||
threadId: input.context.projectionThreadId,
|
||||
runId: input.context.projectionRunId,
|
||||
nodeId: input.context.providerNodeId,
|
||||
providerThreadId: input.context.providerThread.id,
|
||||
providerTurnId: input.context.providerTurnId,
|
||||
itemOrdinal: providerRetry.itemOrdinal,
|
||||
failure: providerRetry.failure,
|
||||
retry: providerRetry.retry,
|
||||
status: providerTurnStatusToTerminal(input.status),
|
||||
startedAt: providerRetry.startedAt,
|
||||
updatedAt: input.completedAt,
|
||||
}),
|
||||
});
|
||||
}
|
||||
if (input.status !== "completed") {
|
||||
yield* Ref.update(terminalizedNonCompletedNativeTurns, (current) => {
|
||||
const updated = new Set(current);
|
||||
@@ -4659,7 +4807,10 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
|
||||
);
|
||||
}
|
||||
if (input.context.subagent === null) {
|
||||
yield* emitOrDeferRootTerminal(input);
|
||||
yield* emitOrDeferRootTerminal({
|
||||
...input,
|
||||
...(providerRetry === undefined ? {} : { providerRetry }),
|
||||
});
|
||||
}
|
||||
const waiter = (yield* Ref.get(turnWaiters)).get(input.nativeTurnId);
|
||||
if (waiter !== undefined) {
|
||||
|
||||
@@ -104,6 +104,9 @@ function makeThread(threadId: ThreadId, now: DateTime.Utc): OrchestrationV2AppTh
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -178,6 +178,7 @@ function importedThread(row: LegacyThreadRow): OrchestrationV2AppThread {
|
||||
archivedAt: nullableDateTime(row.archived_at),
|
||||
settledOverride: settledOverrideFor(row.settled_override),
|
||||
settledAt: nullableDateTime(row.settled_at),
|
||||
lastVisitedAt: null,
|
||||
deletedAt: nullableDateTime(row.deleted_at),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -185,6 +185,12 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId {
|
||||
case "thread.archive":
|
||||
case "thread.unarchive":
|
||||
case "thread.delete":
|
||||
case "thread.settle":
|
||||
case "thread.unsettle":
|
||||
case "thread.snooze":
|
||||
case "thread.unsnooze":
|
||||
case "thread.visit":
|
||||
case "thread.mark-unread":
|
||||
case "thread.metadata.update":
|
||||
case "thread.runtime-mode.set":
|
||||
case "thread.interaction-mode.set":
|
||||
@@ -197,6 +203,8 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId {
|
||||
case "run.interrupt":
|
||||
case "queued-message.promote-to-steer":
|
||||
case "queued-run.reorder":
|
||||
case "queued-run.cancel":
|
||||
case "queued-run.edit":
|
||||
case "runtime-request.respond":
|
||||
case "checkpoint.rollback":
|
||||
case "provider.switch":
|
||||
@@ -651,6 +659,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
|
||||
const rootNode = projection.nodes.find((candidate) => candidate.id === rootNodeId);
|
||||
const attempt = projection.attempts.find((candidate) => candidate.id === attemptId);
|
||||
const queuedMessage = projection.messages.find(
|
||||
(candidate) => candidate.id === queuedRun.userMessageId,
|
||||
);
|
||||
const legacyQueuedTurnItem = projection.turnItems.find(
|
||||
(
|
||||
candidate,
|
||||
): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
|
||||
candidate.type === "user_message" &&
|
||||
candidate.runId === queuedRun.id &&
|
||||
candidate.messageId === queuedRun.userMessageId,
|
||||
);
|
||||
const queuedProviderThread = projection.providerThreads.find(
|
||||
(candidate) => candidate.id === providerThreadId,
|
||||
);
|
||||
@@ -660,6 +679,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
if (
|
||||
rootNode === undefined ||
|
||||
attempt === undefined ||
|
||||
queuedMessage === undefined ||
|
||||
queuedProviderThread === undefined ||
|
||||
(rootNode.checkpointScopeId !== null && storedCheckpointScope === undefined)
|
||||
) {
|
||||
@@ -729,6 +749,31 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
queuePosition: null,
|
||||
startedAt: null,
|
||||
};
|
||||
const userTurnItem: OrchestrationV2TurnItem = {
|
||||
...(legacyQueuedTurnItem ?? {
|
||||
id: idAllocator.derive.userTurnItem({ messageId: queuedMessage.id }),
|
||||
threadId,
|
||||
runId: queuedRun.id,
|
||||
nodeId: rootNodeId,
|
||||
providerThreadId: queuedProviderThread.id,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: queuedRun.ordinal * 100,
|
||||
status: "completed",
|
||||
title: null,
|
||||
type: "user_message",
|
||||
messageId: queuedMessage.id,
|
||||
text: queuedMessage.text,
|
||||
attachments: queuedMessage.attachments,
|
||||
createdBy: queuedMessage.createdBy,
|
||||
creationSource: queuedMessage.creationSource,
|
||||
}),
|
||||
inputIntent: "turn_start",
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
const checkpointEvents: ReadonlyArray<Omit<OrchestrationV2DomainEvent, "id">> =
|
||||
storedCheckpointScope === undefined
|
||||
? [
|
||||
@@ -762,6 +807,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
occurredAt: now,
|
||||
payload: providerThread,
|
||||
},
|
||||
{
|
||||
type: "turn-item.updated",
|
||||
threadId,
|
||||
runId: queuedRun.id,
|
||||
nodeId: rootNodeId,
|
||||
providerInstanceId: queuedRun.providerInstanceId,
|
||||
occurredAt: now,
|
||||
payload: userTurnItem,
|
||||
},
|
||||
{
|
||||
type: "run.updated",
|
||||
threadId,
|
||||
@@ -853,6 +907,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
archivedAt: null,
|
||||
settledOverride: null,
|
||||
settledAt: null,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
lastVisitedAt: null,
|
||||
deletedAt: null,
|
||||
};
|
||||
|
||||
@@ -873,6 +932,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
| "thread.archive"
|
||||
| "thread.unarchive"
|
||||
| "thread.delete"
|
||||
| "thread.settle"
|
||||
| "thread.unsettle"
|
||||
| "thread.snooze"
|
||||
| "thread.unsnooze"
|
||||
| "thread.visit"
|
||||
| "thread.mark-unread"
|
||||
| "thread.metadata.update"
|
||||
| "thread.runtime-mode.set"
|
||||
| "thread.interaction-mode.set"
|
||||
@@ -949,6 +1014,59 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
: null;
|
||||
|
||||
const now = yield* DateTime.now;
|
||||
let snoozedUntil: DateTime.Utc | null = null;
|
||||
if (command.type === "thread.snooze") {
|
||||
const parsedSnoozedUntil = DateTime.make(command.snoozedUntil);
|
||||
if (
|
||||
Option.isNone(parsedSnoozedUntil) ||
|
||||
DateTime.toEpochMillis(parsedSnoozedUntil.value) <= DateTime.toEpochMillis(now)
|
||||
) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future.`,
|
||||
});
|
||||
}
|
||||
if (projection.runtimeRequests.some((request) => request.status === "pending")) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed.`,
|
||||
});
|
||||
}
|
||||
if (projection.runs.some((run) => run.status === "queued")) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Thread ${command.threadId} has a queued run and cannot be snoozed.`,
|
||||
});
|
||||
}
|
||||
snoozedUntil = parsedSnoozedUntil.value;
|
||||
}
|
||||
let visitedAt: DateTime.Utc | null = null;
|
||||
if (command.type === "thread.visit") {
|
||||
const parsedVisitedAt = DateTime.make(command.visitedAt);
|
||||
if (Option.isNone(parsedVisitedAt)) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Thread ${command.threadId} visit time ${command.visitedAt} is not a valid timestamp.`,
|
||||
});
|
||||
}
|
||||
visitedAt = parsedVisitedAt.value;
|
||||
}
|
||||
let markUnreadVisitedAt: DateTime.Utc | null = null;
|
||||
if (command.type === "thread.mark-unread") {
|
||||
const latestRunCompletedAt = projection.runs.at(-1)?.completedAt ?? null;
|
||||
if (latestRunCompletedAt === null) {
|
||||
return yield* new OrchestratorDispatchError({
|
||||
commandId: command.commandId,
|
||||
commandType: command.type,
|
||||
cause: `Thread ${command.threadId} has no completed run to mark unread.`,
|
||||
});
|
||||
}
|
||||
markUnreadVisitedAt = DateTime.subtract(latestRunCompletedAt, { milliseconds: 1 });
|
||||
}
|
||||
const updatedThread: OrchestrationV2AppThread = (() => {
|
||||
switch (command.type) {
|
||||
case "thread.archive":
|
||||
@@ -957,6 +1075,59 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
return { ...thread, archivedAt: null, updatedAt: now };
|
||||
case "thread.delete":
|
||||
return { ...thread, deletedAt: thread.deletedAt ?? now, updatedAt: now };
|
||||
case "thread.settle": {
|
||||
const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
|
||||
return {
|
||||
...thread,
|
||||
settledOverride: "settled",
|
||||
settledAt: alreadySettled ? thread.settledAt : now,
|
||||
updatedAt: alreadySettled ? thread.updatedAt : now,
|
||||
};
|
||||
}
|
||||
case "thread.unsettle": {
|
||||
const alreadyPinnedActive = thread.settledOverride === "active";
|
||||
return {
|
||||
...thread,
|
||||
settledOverride: "active",
|
||||
settledAt: null,
|
||||
updatedAt: alreadyPinnedActive ? thread.updatedAt : now,
|
||||
};
|
||||
}
|
||||
case "thread.snooze": {
|
||||
const sameWakeTime =
|
||||
thread.snoozedUntil != null &&
|
||||
snoozedUntil !== null &&
|
||||
DateTime.toEpochMillis(thread.snoozedUntil) === DateTime.toEpochMillis(snoozedUntil);
|
||||
const existingSnoozedAt = sameWakeTime ? (thread.snoozedAt ?? null) : null;
|
||||
return {
|
||||
...thread,
|
||||
snoozedUntil,
|
||||
snoozedAt: existingSnoozedAt ?? now,
|
||||
updatedAt: existingSnoozedAt === null ? now : thread.updatedAt,
|
||||
};
|
||||
}
|
||||
case "thread.unsnooze": {
|
||||
const alreadyAwake = thread.snoozedUntil == null;
|
||||
return {
|
||||
...thread,
|
||||
snoozedUntil: null,
|
||||
snoozedAt: null,
|
||||
updatedAt: alreadyAwake ? thread.updatedAt : now,
|
||||
};
|
||||
}
|
||||
// Visited tracking records read state only; it must not bump updatedAt,
|
||||
// otherwise viewing a thread would count as activity (and re-trigger the
|
||||
// clients that dispatch thread.visit whenever updatedAt advances).
|
||||
case "thread.visit": {
|
||||
const previousVisitedAt = thread.lastVisitedAt;
|
||||
const movesForward =
|
||||
visitedAt !== null &&
|
||||
(previousVisitedAt === null ||
|
||||
DateTime.toEpochMillis(visitedAt) > DateTime.toEpochMillis(previousVisitedAt));
|
||||
return movesForward ? { ...thread, lastVisitedAt: visitedAt } : thread;
|
||||
}
|
||||
case "thread.mark-unread":
|
||||
return { ...thread, lastVisitedAt: markUnreadVisitedAt };
|
||||
case "thread.metadata.update":
|
||||
return {
|
||||
...thread,
|
||||
@@ -987,6 +1158,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
return "thread.unarchived" as const;
|
||||
case "thread.delete":
|
||||
return "thread.deleted" as const;
|
||||
case "thread.settle":
|
||||
return "thread.settled" as const;
|
||||
case "thread.unsettle":
|
||||
return "thread.unsettled" as const;
|
||||
case "thread.snooze":
|
||||
return "thread.snoozed" as const;
|
||||
case "thread.unsnooze":
|
||||
return "thread.unsnoozed" as const;
|
||||
case "thread.visit":
|
||||
return "thread.visited" as const;
|
||||
case "thread.mark-unread":
|
||||
return "thread.marked-unread" as const;
|
||||
case "thread.metadata.update":
|
||||
return "thread.metadata-updated" as const;
|
||||
case "thread.runtime-mode.set":
|
||||
@@ -2307,29 +2490,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
const turnItem: OrchestrationV2TurnItem = {
|
||||
createdBy: command.createdBy,
|
||||
creationSource: command.creationSource,
|
||||
id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
providerThreadId: queueProviderThread.id,
|
||||
providerTurnId: null,
|
||||
nativeItemRef: null,
|
||||
parentItemId: null,
|
||||
ordinal: ordinal * 100,
|
||||
status: "completed",
|
||||
title: null,
|
||||
startedAt: now,
|
||||
completedAt: now,
|
||||
updatedAt: now,
|
||||
type: "user_message",
|
||||
messageId: command.messageId,
|
||||
inputIntent: "queued_turn",
|
||||
text: command.text,
|
||||
attachments: command.attachments,
|
||||
};
|
||||
const emitEvent = emit(events, command);
|
||||
yield* emitEvent({
|
||||
type: "run.created",
|
||||
@@ -2388,15 +2548,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
occurredAt: now,
|
||||
payload: message,
|
||||
});
|
||||
yield* emitEvent({
|
||||
type: "turn-item.updated",
|
||||
threadId: command.threadId,
|
||||
runId,
|
||||
nodeId: rootNodeId,
|
||||
providerInstanceId: modelSelection.instanceId,
|
||||
occurredAt: now,
|
||||
payload: turnItem,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const pendingForkTransfer = pendingForkTransferForThread(projection);
|
||||
@@ -3273,6 +3424,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
|
||||
attachments: command.attachments,
|
||||
};
|
||||
const activeHandoff = portableForkHandoff ?? mergeBackHandoff ?? providerSwitchHandoff;
|
||||
const handoffSourceRuns =
|
||||
portableForkHandoff !== null
|
||||
? sourceRun === null
|
||||
? []
|
||||
: [sourceRun]
|
||||
: providerSwitchHandoff === null
|
||||
? mergeBackSourceRun === null
|
||||
? []
|
||||
: [mergeBackSourceRun]
|
||||
: providerSwitchCoveredRuns;
|
||||
const handoffFromModelSelections = Array.from(
|
||||
new Map(
|
||||
handoffSourceRuns.map((run) => [
|
||||
`${run.modelSelection.instanceId} | ||||