diff --git a/apps/mobile/src/connection/environment-cache-store.test.ts b/apps/mobile/src/connection/environment-cache-store.test.ts index a3e7686c7e..1488038c98 100644 --- a/apps/mobile/src/connection/environment-cache-store.test.ts +++ b/apps/mobile/src/connection/environment-cache-store.test.ts @@ -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: [], diff --git a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx index 8d8d516e14..eaf19745bd 100644 --- a/apps/mobile/src/features/threads/ThreadDetailScreen.tsx +++ b/apps/mobile/src/features/threads/ThreadDetailScreen.tsx @@ -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(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; diff --git a/apps/mobile/src/features/threads/thread-list-v2-items.tsx b/apps/mobile/src/features/threads/thread-list-v2-items.tsx index 1c25f949ed..08da0f02a4 100644 --- a/apps/mobile/src/features/threads/thread-list-v2-items.tsx +++ b/apps/mobile/src/features/threads/thread-list-v2-items.tsx @@ -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]); diff --git a/apps/mobile/src/features/threads/threadListV2.ts b/apps/mobile/src/features/threads/threadListV2.ts index c65f25b0d8..9715dd7839 100644 --- a/apps/mobile/src/features/threads/threadListV2.ts +++ b/apps/mobile/src/features/threads/threadListV2.ts @@ -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, +): 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, ): ThreadListV2Status { diff --git a/apps/mobile/src/lib/threadActivity.test.ts b/apps/mobile/src/lib/threadActivity.test.ts index 766d498607..bc88064969 100644 --- a/apps/mobile/src/lib/threadActivity.test.ts +++ b/apps/mobile/src/lib/threadActivity.test.ts @@ -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), diff --git a/apps/mobile/src/lib/threadActivity.ts b/apps/mobile/src/lib/threadActivity.ts index 3cad2b206b..4465d10a94 100644 --- a/apps/mobile/src/lib/threadActivity.ts +++ b/apps/mobile/src/lib/threadActivity.ts @@ -951,12 +951,13 @@ export function buildPendingUserInputAnswers( export function buildThreadFeed( visibleTurnItems: ReadonlyArray, ): 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); } diff --git a/apps/server/src/environment/ServerEnvironment.ts b/apps/server/src/environment/ServerEnvironment.ts index 45dc0ee9cf..f2037df7b8 100644 --- a/apps/server/src/environment/ServerEnvironment.ts +++ b/apps/server/src/environment/ServerEnvironment.ts @@ -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 } : {}), }, diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts index 3cd7e87c91..220c064895 100644 --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.test.ts @@ -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, diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts index 48f20b17fb..00965d58e4 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts @@ -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; + 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* () { diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 381a83340c..0c43abe823 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -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; } +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()); const itemOrdinals = yield* Ref.make(new Map()); const nextItemOrdinalsByTurn = yield* Ref.make(new Map()); + const providerRetries = yield* Ref.make( + new Map(), + ); const pendingRuntimeRequests = yield* Ref.make( new Map(), ); @@ -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); diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts index 2a40c51830..28af984fba 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.test.ts @@ -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<{ diff --git a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts index 7273f8b3b7..a356ce54e1 100644 --- a/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts @@ -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 | 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()); const itemOrdinals = yield* Ref.make(new Map()); const nextItemOrdinalsByTurn = yield* Ref.make(new Map()); + const providerRetries = yield* Ref.make( + new Map(), + ); const planDeltas = yield* Ref.make(new Map()); const planIds = yield* Ref.make(new Map()); 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 { 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) { diff --git a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts index 75d5bedffe..ab9fb93e8d 100644 --- a/apps/server/src/orchestration-v2/FoundationPersistence.test.ts +++ b/apps/server/src/orchestration-v2/FoundationPersistence.test.ts @@ -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, }; } diff --git a/apps/server/src/orchestration-v2/LegacyV1ThreadImporter.ts b/apps/server/src/orchestration-v2/LegacyV1ThreadImporter.ts index 946d8c3561..229df8373d 100644 --- a/apps/server/src/orchestration-v2/LegacyV1ThreadImporter.ts +++ b/apps/server/src/orchestration-v2/LegacyV1ThreadImporter.ts @@ -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), }; } diff --git a/apps/server/src/orchestration-v2/Orchestrator.ts b/apps/server/src/orchestration-v2/Orchestrator.ts index 4761ff9876..050ffa5d37 100644 --- a/apps/server/src/orchestration-v2/Orchestrator.ts +++ b/apps/server/src/orchestration-v2/Orchestrator.ts @@ -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 => + 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> = 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}${run.modelSelection.model}`, + run.modelSelection, + ]), + ).values(), + ); const handoffTurnItem: OrchestrationV2TurnItem | null = activeHandoff === null ? null @@ -3303,19 +3472,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio contextHandoffId: activeHandoff.id, fromProviderThreadIds: activeHandoff.fromProviderThreadIds, toProviderThreadId: activeHandoff.toProviderThreadId, - fromProviderInstanceIds: - portableForkHandoff !== null - ? sourceRun === null - ? [] - : [sourceRun.providerInstanceId] - : providerSwitchHandoff === null - ? mergeBackSourceRun === null - ? [] - : [mergeBackSourceRun.providerInstanceId] - : Array.from( - new Set(providerSwitchCoveredRuns.map((run) => run.providerInstanceId)), - ), + fromProviderInstanceIds: Array.from( + new Set(handoffSourceRuns.map((run) => run.providerInstanceId)), + ), toProviderInstanceId: modelSelection.instanceId, + fromModelSelections: handoffFromModelSelections, + toModel: modelSelection.model, strategy: activeHandoff.strategy, summary: activeHandoff.summaryText, }; @@ -4366,6 +4528,153 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio ); }); + const dispatchQueuedRunCancel = ( + command: Extract, + events: Ref.Ref>, + ) => + Effect.gen(function* () { + const projection = yield* projectionStore + .getThreadProjection(command.threadId) + .pipe( + Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })), + ); + const queuedRun = projection.runs.find((candidate) => candidate.id === command.runId); + if (queuedRun === undefined || queuedRun.status !== "queued") { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Run ${command.runId} is not queued.`, + }); + } + const queuedRootNode = + queuedRun.rootNodeId === null + ? undefined + : projection.nodes.find((candidate) => candidate.id === queuedRun.rootNodeId); + const queuedAttempt = + queuedRun.activeAttemptId === null + ? undefined + : projection.attempts.find((candidate) => candidate.id === queuedRun.activeAttemptId); + + const now = yield* DateTime.now; + const emitEvent = emit(events, command); + yield* emitEvent({ + type: "run.updated", + threadId: command.threadId, + runId: queuedRun.id, + ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }), + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: { + ...queuedRun, + status: "cancelled", + queuePosition: null, + completedAt: now, + }, + }); + if (queuedAttempt !== undefined && queuedRootNode !== undefined) { + yield* emitEvent({ + type: "run-attempt.updated", + threadId: command.threadId, + runId: queuedRun.id, + nodeId: queuedRootNode.id, + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: { + ...queuedAttempt, + status: "cancelled", + completedAt: now, + }, + }); + } + if (queuedRootNode !== undefined) { + yield* emitEvent({ + type: "node.updated", + threadId: command.threadId, + runId: queuedRun.id, + nodeId: queuedRootNode.id, + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: { + ...queuedRootNode, + status: "cancelled", + completedAt: now, + }, + }); + } + }); + + const dispatchQueuedRunEdit = ( + command: Extract, + events: Ref.Ref>, + ) => + Effect.gen(function* () { + if (command.text.trim().length === 0) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Queued run ${command.runId} cannot be edited to an empty message.`, + }); + } + const projection = yield* projectionStore + .getThreadProjection(command.threadId) + .pipe( + Effect.mapError(() => new OrchestratorProjectionError({ threadId: command.threadId })), + ); + const queuedRun = projection.runs.find((candidate) => candidate.id === command.runId); + if (queuedRun === undefined || queuedRun.status !== "queued") { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Run ${command.runId} is not queued.`, + }); + } + const queuedMessage = projection.messages.find( + (candidate) => candidate.id === queuedRun.userMessageId, + ); + if (queuedMessage === undefined) { + return yield* new OrchestratorDispatchError({ + commandId: command.commandId, + commandType: command.type, + cause: `Queued run ${queuedRun.id} has no user message.`, + }); + } + const queuedTurnItem = projection.turnItems.find( + (candidate) => + candidate.type === "user_message" && candidate.messageId === queuedMessage.id, + ); + + const now = yield* DateTime.now; + const emitEvent = emit(events, command); + yield* emitEvent({ + type: "message.updated", + threadId: command.threadId, + runId: queuedRun.id, + ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }), + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: { + ...queuedMessage, + text: command.text, + updatedAt: now, + }, + }); + if (queuedTurnItem !== undefined && queuedTurnItem.type === "user_message") { + yield* emitEvent({ + type: "turn-item.updated", + threadId: command.threadId, + runId: queuedRun.id, + ...(queuedRun.rootNodeId === null ? {} : { nodeId: queuedRun.rootNodeId }), + providerInstanceId: queuedRun.providerInstanceId, + occurredAt: now, + payload: { + ...queuedTurnItem, + text: command.text, + updatedAt: now, + }, + }); + } + }); + const loadProjectionForCommand = (command: OrchestrationV2Command) => projectionStore .getThreadProjection(commandThreadId(command)) @@ -5309,6 +5618,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio 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": @@ -5343,6 +5658,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio case "queued-run.reorder": yield* dispatchQueuedRunReorder(command, events); break; + case "queued-run.cancel": + yield* dispatchQueuedRunCancel(command, events); + break; + case "queued-run.edit": + yield* dispatchQueuedRunEdit(command, events); + break; case "checkpoint.rollback": yield* dispatchCheckpointRollback(command, events, effects); break; @@ -5497,7 +5818,35 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio const dispatchWithReceipt = (command: OrchestrationV2Command) => threadDispatch.withLock(commandThreadId(command), dispatchWithReceiptEffect(command)); - yield* eventSink.stream().pipe( + const handleTerminalRun = (stored: OrchestrationV2StoredEvent) => + Effect.gen(function* () { + const threadId = stored.event.threadId; + // finalize writes the parent thread and startNextQueuedRun writes this + // thread, so each takes its own thread's lock, sequentially and never + // nested: dispatchDelegatedTaskRequest already writes child events + // while holding the parent lock, so nesting the parent lock inside the + // child lock here would invert that order, and the keyed executor's + // semaphores are neither reentrant nor deadlock-aware. + const parentThreadId = yield* appOwnedSubagentParentThreadId(threadId); + if (parentThreadId !== undefined) { + yield* threadDispatch.withLock(parentThreadId, finalizeAppOwnedSubagent(threadId)); + } + yield* threadDispatch.withLock(threadId, startNextQueuedRun(threadId)); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to react to terminal V2 run", { + threadId: stored.event.threadId, + sequence: stored.sequence, + cause, + }), + ), + ); + + // Historical terminal events are already represented by the projections + // below. Replaying the full event table on every server start delays live + // queue promotion in proportion to the lifetime size of the database. + const terminalEventsAfterSequence = yield* eventSink.latestSequence().pipe(Effect.orDie); + yield* eventSink.stream({ afterSequence: terminalEventsAfterSequence }).pipe( Stream.filter( (stored) => stored.event.type === "run.updated" && @@ -5508,25 +5857,61 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio stored.event.payload.status === "cancelled" || stored.event.payload.status === "rolled_back"), ), - Stream.runForEach((stored) => - Effect.gen(function* () { - const threadId = stored.event.threadId; - // finalize writes the parent thread and startNextQueuedRun writes this - // thread, so each takes its own thread's lock, sequentially and never - // nested: dispatchDelegatedTaskRequest already writes child events - // while holding the parent lock, so nesting the parent lock inside the - // child lock here would invert that order, and the keyed executor's - // semaphores are neither reentrant nor deadlock-aware. - const parentThreadId = yield* appOwnedSubagentParentThreadId(threadId); - if (parentThreadId !== undefined) { - yield* threadDispatch.withLock(parentThreadId, finalizeAppOwnedSubagent(threadId)); - } - yield* threadDispatch.withLock(threadId, startNextQueuedRun(threadId)); - }).pipe(Effect.catchCause(() => Effect.void)), - ), + Stream.runForEach(handleTerminalRun), Effect.forkDetach, ); + // The high-water subscription deliberately skips history, so recover the + // two terminal side effects from current projections instead: one queued + // run per idle thread, plus any app-owned child result not yet transferred. + yield* resumeQueuedRuns.pipe( + Effect.tap((resumed) => + resumed === 0 + ? Effect.void + : Effect.logInfo("Resumed queued V2 runs after recovery", { resumed }), + ), + Effect.catchCause((cause) => + Effect.logWarning("Failed to recover queued V2 runs", { + cause, + }), + ), + ); + yield* projectionStore.getShellSnapshot().pipe( + Effect.flatMap((shell) => + Effect.forEach( + [...shell.threads, ...shell.archivedThreads].filter( + (thread) => + thread.lineage.relationshipToParent === "subagent" && + thread.lineage.parentThreadId !== null && + thread.forkedFrom?.type === "node" && + (thread.status === "completed" || + thread.status === "interrupted" || + thread.status === "failed" || + thread.status === "cancelled" || + thread.status === "rolled_back"), + ), + (thread) => + threadDispatch + .withLock(thread.lineage.parentThreadId!, finalizeAppOwnedSubagent(thread.id)) + .pipe( + Effect.catchCause((cause) => + Effect.logWarning("Failed to recover terminal app-owned subagent", { + childThreadId: thread.id, + parentThreadId: thread.lineage.parentThreadId, + cause, + }), + ), + ), + { concurrency: 8, discard: true }, + ), + ), + Effect.catchCause((cause) => + Effect.logWarning("Failed to inspect app-owned subagents during recovery", { + cause, + }), + ), + ); + return OrchestratorV2.of({ resumeQueuedRuns, dispatch: dispatchWithReceipt, diff --git a/apps/server/src/orchestration-v2/ProjectionStore.test.ts b/apps/server/src/orchestration-v2/ProjectionStore.test.ts index 64469f54ce..a34f8db902 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.test.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.test.ts @@ -139,6 +139,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { archivedAt: null, settledOverride: null, settledAt: null, + lastVisitedAt: null, deletedAt: null, }, }); @@ -158,6 +159,15 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { ); assert.equal(shell?.status, "running"); assert.equal(shell?.activeRunId, runId); + assert.equal( + shell?.latestRunRequestedAt && DateTime.toEpochMillis(shell.latestRunRequestedAt), + DateTime.toEpochMillis(now), + ); + assert.equal( + shell?.latestRunStartedAt && DateTime.toEpochMillis(shell.latestRunStartedAt), + DateTime.toEpochMillis(now), + ); + assert.isNull(shell?.latestRunCompletedAt); yield* projectionStore.apply({ id: EventId.make("event:projection-shell-interruptible:waiting"), @@ -210,6 +220,9 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { createdAt: now, updatedAt: now, archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, deletedAt: null, }); const session = { @@ -336,6 +349,9 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { createdAt: now, updatedAt: now, archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, deletedAt: null, }, }); @@ -455,6 +471,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { archivedAt: null, settledOverride: null, settledAt: null, + lastVisitedAt: null, deletedAt: null, }, }); @@ -491,6 +508,7 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { archivedAt: null, settledOverride: null, settledAt: null, + lastVisitedAt: null, deletedAt: null, }, }); @@ -609,6 +627,9 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { createdAt: now, updatedAt: now, archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, deletedAt: null, }, }); @@ -981,6 +1002,9 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { createdAt: now, updatedAt: now, archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, deletedAt: null, }, }); @@ -1015,6 +1039,9 @@ it.layer(TestLayer)("ProjectionStoreV2", (it) => { createdAt: now, updatedAt: now, archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, deletedAt: null, }, }); diff --git a/apps/server/src/orchestration-v2/ProjectionStore.ts b/apps/server/src/orchestration-v2/ProjectionStore.ts index 0e0bd5ff73..2eb4d412e8 100644 --- a/apps/server/src/orchestration-v2/ProjectionStore.ts +++ b/apps/server/src/orchestration-v2/ProjectionStore.ts @@ -186,6 +186,14 @@ export function applyToProjection( ...base, thread: event.payload, }; + // Visited tracking is read state, not activity: skip the updatedAt bump so + // viewing a thread does not surface it as recently active. + case "thread.visited": + case "thread.marked-unread": + return { + ...projection, + thread: event.payload, + }; case "run.created": case "run.updated": return withLocalVisibleTurnItems({ @@ -385,6 +393,9 @@ type ShellThreadRow = { readonly payload_json: string; readonly latest_run_id: string | null; readonly latest_run_status: string | null; + readonly latest_run_requested_at: string | null; + readonly latest_run_started_at: string | null; + readonly latest_run_completed_at: string | null; readonly active_run_id: string | null; readonly last_error: string | null; readonly pending_request_payload_json: string | null; @@ -791,6 +802,9 @@ export function threadShellFromProjection( ? {} : { historyOrigin: projection.thread.historyOrigin }), latestRunId: latestRun?.id ?? null, + latestRunRequestedAt: latestRun?.requestedAt ?? null, + latestRunStartedAt: latestRun?.startedAt ?? null, + latestRunCompletedAt: latestRun?.completedAt ?? null, activeRunId: activeRun?.id ?? null, status: latestRun?.status ?? "idle", lastError: providerSession?.lastError ?? null, @@ -820,6 +834,11 @@ export function threadShellFromProjection( createdAt: projection.thread.createdAt, updatedAt: projection.updatedAt, archivedAt: projection.thread.archivedAt, + settledOverride: projection.thread.settledOverride, + settledAt: projection.thread.settledAt, + snoozedUntil: projection.thread.snoozedUntil ?? null, + snoozedAt: projection.thread.snoozedAt ?? null, + lastVisitedAt: projection.thread.lastVisitedAt, deletedAt: projection.thread.deletedAt, }; } @@ -832,6 +851,9 @@ type ShellThreadState = { readonly thread: OrchestrationV2ThreadProjection["thread"]; readonly latestRunId: RunId | null; readonly latestRunStatus: OrchestrationV2ShellThreadStatus; + readonly latestRunRequestedAt: DateTime.Utc | null; + readonly latestRunStartedAt: DateTime.Utc | null; + readonly latestRunCompletedAt: DateTime.Utc | null; readonly activeRunId: RunId | null; readonly lastError: string | null; readonly pendingRuntimeRequest: OrchestrationV2ThreadProjection["runtimeRequests"][number] | null; @@ -950,6 +972,9 @@ function shellFromState(input: { ? {} : { historyOrigin: input.state.thread.historyOrigin }), latestRunId: input.state.latestRunId, + latestRunRequestedAt: input.state.latestRunRequestedAt, + latestRunStartedAt: input.state.latestRunStartedAt, + latestRunCompletedAt: input.state.latestRunCompletedAt, activeRunId: input.state.activeRunId, status: input.state.latestRunStatus, lastError: input.state.lastError, @@ -977,6 +1002,11 @@ function shellFromState(input: { createdAt: input.state.thread.createdAt, updatedAt: input.state.updatedAt, archivedAt: input.state.thread.archivedAt, + settledOverride: input.state.thread.settledOverride, + settledAt: input.state.thread.settledAt, + snoozedUntil: input.state.thread.snoozedUntil ?? null, + snoozedAt: input.state.thread.snoozedAt ?? null, + lastVisitedAt: input.state.thread.lastVisitedAt, deletedAt: input.state.thread.deletedAt, }; } @@ -993,6 +1023,12 @@ export const layer: Layer.Layer = case "thread.archived": case "thread.unarchived": case "thread.deleted": + case "thread.settled": + case "thread.unsettled": + case "thread.snoozed": + case "thread.unsnoozed": + case "thread.visited": + case "thread.marked-unread": case "thread.metadata-updated": case "thread.runtime-mode-updated": case "thread.interaction-mode-updated": @@ -2079,6 +2115,27 @@ export const layer: Layer.Layer = ORDER BY r.ordinal DESC, r.run_id DESC LIMIT 1 ) AS latest_run_status, + ( + SELECT r.requested_at + FROM orchestration_v2_projection_runs r + WHERE r.thread_id = t.thread_id + ORDER BY r.ordinal DESC, r.run_id DESC + LIMIT 1 + ) AS latest_run_requested_at, + ( + SELECT json_extract(r.payload_json, '$.startedAt') + FROM orchestration_v2_projection_runs r + WHERE r.thread_id = t.thread_id + ORDER BY r.ordinal DESC, r.run_id DESC + LIMIT 1 + ) AS latest_run_started_at, + ( + SELECT r.completed_at + FROM orchestration_v2_projection_runs r + WHERE r.thread_id = t.thread_id + ORDER BY r.ordinal DESC, r.run_id DESC + LIMIT 1 + ) AS latest_run_completed_at, ( SELECT r.run_id FROM orchestration_v2_projection_runs r @@ -2196,6 +2253,18 @@ export const layer: Layer.Layer = thread, latestRunId: row.latest_run_id === null ? null : RunId.make(row.latest_run_id), latestRunStatus: shellStatusFromStoredRunStatus(row.latest_run_status), + latestRunRequestedAt: + row.latest_run_requested_at === null + ? null + : DateTime.makeUnsafe(row.latest_run_requested_at), + latestRunStartedAt: + row.latest_run_started_at === null + ? null + : DateTime.makeUnsafe(row.latest_run_started_at), + latestRunCompletedAt: + row.latest_run_completed_at === null + ? null + : DateTime.makeUnsafe(row.latest_run_completed_at), activeRunId: row.active_run_id === null ? null : RunId.make(row.active_run_id), lastError: row.last_error, pendingRuntimeRequest, diff --git a/apps/server/src/orchestration-v2/ProviderAdapter.ts b/apps/server/src/orchestration-v2/ProviderAdapter.ts index d8f3595bcf..a86fb0b48f 100644 --- a/apps/server/src/orchestration-v2/ProviderAdapter.ts +++ b/apps/server/src/orchestration-v2/ProviderAdapter.ts @@ -11,6 +11,7 @@ import { OrchestrationV2PlanArtifact, OrchestrationV2ProviderCapabilities, OrchestrationV2ProviderFailure, + OrchestrationV2ProviderRetry, OrchestrationV2ProviderThread, OrchestrationV2ProviderTurn, OrchestrationV2RuntimeRequest, @@ -143,6 +144,8 @@ export const ProviderAdapterV2Event = Schema.Union([ failureItemOrdinal: PositiveInt, status: Schema.Literal("failed"), failure: OrchestrationV2ProviderFailure, + retry: Schema.optional(OrchestrationV2ProviderRetry), + retryStartedAt: Schema.optional(Schema.DateTimeUtc), threadDisposition: Schema.Literals(["reusable", "broken"]), }), ]); diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts index 3f360dd14e..86a2c16ae3 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.test.ts @@ -90,6 +90,9 @@ function threadCreatedEvent( createdAt: now, updatedAt: now, archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, deletedAt: null, }; @@ -233,6 +236,7 @@ layer("ProviderEventIngestorV2", (it) => { it.effect("persists a failed provider terminal as one expected error item", () => Effect.gen(function* () { const now = yield* DateTime.now; + const retryStartedAt = DateTime.makeUnsafe(DateTime.toEpochMillis(now) - 5_000); const eventSink = yield* EventSinkV2; const projectionStore = yield* ProjectionStoreV2; const ingestor = yield* ProviderEventIngestorV2; @@ -269,6 +273,12 @@ layer("ProviderEventIngestorV2", (it) => { code: "invalid_request", class: "validation_error", }), + retry: { + attempt: 3, + maxAttempts: 3, + retryDelayMs: 2_000, + }, + retryStartedAt, threadDisposition: "reusable", }, }); @@ -286,6 +296,15 @@ layer("ProviderEventIngestorV2", (it) => { if (errorItem?.type !== "error") return; assert.equal(errorItem.failure.message, "Invalid reasoning effort."); assert.equal(errorItem.failure.code, "invalid_request"); + assert.deepEqual(errorItem.retry, { + attempt: 3, + maxAttempts: 3, + retryDelayMs: 2_000, + }); + assert.equal( + DateTime.toEpochMillis(errorItem.startedAt), + DateTime.toEpochMillis(retryStartedAt), + ); assert.equal(errorItem.providerThreadId, providerThreadId); assert.equal(errorItem.providerTurnId, providerTurnId); }), diff --git a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts index 91e4a97439..233db488e8 100644 --- a/apps/server/src/orchestration-v2/ProviderEventIngestor.ts +++ b/apps/server/src/orchestration-v2/ProviderEventIngestor.ts @@ -248,6 +248,10 @@ export const layer: Layer.Layer { return { @@ -138,10 +141,62 @@ export function makeProviderFailureTurnItem(input: { ordinal: input.itemOrdinal, status: "failed", title: "Provider error", - startedAt: input.occurredAt, + startedAt: input.retryStartedAt ?? input.occurredAt, completedAt: input.occurredAt, updatedAt: input.occurredAt, type: "error", failure: input.failure, + ...(input.retry === undefined ? {} : { retry: input.retry }), + }; +} + +export function makeProviderRetryTurnItem(input: { + readonly idAllocator: IdAllocatorV2Shape; + readonly driver: ProviderDriverKind; + readonly threadId: ThreadId; + readonly runId: RunId | null; + readonly nodeId: NodeId | null; + readonly providerThreadId: ProviderThreadId; + readonly providerTurnId: ProviderTurnId; + readonly itemOrdinal: number; + readonly failure: OrchestrationV2ProviderFailure; + readonly retry: OrchestrationV2ProviderRetry; + readonly status: Extract< + OrchestrationV2TurnItem["status"], + "running" | "completed" | "failed" | "interrupted" | "cancelled" + >; + readonly startedAt: DateTime.Utc; + readonly updatedAt: DateTime.Utc; +}): Extract { + const completed = input.status !== "running"; + let title = "Provider retry"; + if (input.status === "completed") { + title = "Provider recovered"; + } else if (input.status === "failed") { + title = "Provider error"; + } else if (input.status === "interrupted" || input.status === "cancelled") { + title = "Provider retry stopped"; + } + return { + id: input.idAllocator.derive.turnItemFromProviderItem({ + driver: input.driver, + nativeItemId: `terminal-failure:${input.providerTurnId}`, + }), + threadId: input.threadId, + runId: input.runId, + nodeId: input.nodeId, + providerThreadId: input.providerThreadId, + providerTurnId: input.providerTurnId, + nativeItemRef: null, + parentItemId: null, + ordinal: input.itemOrdinal, + status: input.status, + title, + startedAt: input.startedAt, + completedAt: completed ? input.updatedAt : null, + updatedAt: input.updatedAt, + type: "error", + failure: input.failure, + retry: input.retry, }; } diff --git a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts index 579e620235..bb1c8733d7 100644 --- a/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts +++ b/apps/server/src/orchestration-v2/ProviderSessionManager.test.ts @@ -168,6 +168,9 @@ function makeThreadCreatedEvent(input: { createdAt: input.now, updatedAt: input.now, archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, deletedAt: null, }; return { diff --git a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts index dc5e7232c9..489fed13e1 100644 --- a/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts +++ b/apps/server/src/orchestration-v2/ProviderTurnControlService.test.ts @@ -70,6 +70,9 @@ function makeProjection(input: { createdAt: input.now, updatedAt: input.now, archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, deletedAt: null, }, runs: [], diff --git a/apps/server/src/orchestration-v2/RuntimePolicy.test.ts b/apps/server/src/orchestration-v2/RuntimePolicy.test.ts index 76a8c2a63d..5e10c592f7 100644 --- a/apps/server/src/orchestration-v2/RuntimePolicy.test.ts +++ b/apps/server/src/orchestration-v2/RuntimePolicy.test.ts @@ -48,6 +48,9 @@ function makeThread(input: { createdAt: input.now, updatedAt: input.now, archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, deletedAt: null, }; } diff --git a/apps/server/src/orchestration-v2/SubagentProjection.test.ts b/apps/server/src/orchestration-v2/SubagentProjection.test.ts index c40c296b16..a1ff328d5e 100644 --- a/apps/server/src/orchestration-v2/SubagentProjection.test.ts +++ b/apps/server/src/orchestration-v2/SubagentProjection.test.ts @@ -54,6 +54,7 @@ function makeParentThread(): OrchestrationV2AppThread { archivedAt: null, settledOverride: null, settledAt: null, + lastVisitedAt: null, snoozedUntil, snoozedAt, deletedAt: null, diff --git a/apps/server/src/orchestration-v2/SubagentProjection.ts b/apps/server/src/orchestration-v2/SubagentProjection.ts index defbc277c9..79c0881d59 100644 --- a/apps/server/src/orchestration-v2/SubagentProjection.ts +++ b/apps/server/src/orchestration-v2/SubagentProjection.ts @@ -75,6 +75,7 @@ export function makeSubagentChildThread(input: { settledAt: null, snoozedUntil: null, snoozedAt: null, + lastVisitedAt: null, deletedAt: null, }; } diff --git a/apps/server/src/orchestration-v2/ThreadForkService.test.ts b/apps/server/src/orchestration-v2/ThreadForkService.test.ts index 410ec53b57..9315783c85 100644 --- a/apps/server/src/orchestration-v2/ThreadForkService.test.ts +++ b/apps/server/src/orchestration-v2/ThreadForkService.test.ts @@ -55,6 +55,7 @@ function makeSourceThread(): OrchestrationV2AppThread { archivedAt: null, settledOverride: null, settledAt: null, + lastVisitedAt: null, snoozedUntil, snoozedAt, deletedAt: null, diff --git a/apps/server/src/orchestration-v2/ThreadForkService.ts b/apps/server/src/orchestration-v2/ThreadForkService.ts index f15b79f76f..f712516b1a 100644 --- a/apps/server/src/orchestration-v2/ThreadForkService.ts +++ b/apps/server/src/orchestration-v2/ThreadForkService.ts @@ -86,6 +86,7 @@ export const layer: Layer.Layer = Layer.succeed( settledAt: null, snoozedUntil: null, snoozedAt: null, + lastVisitedAt: null, deletedAt: null, }; const transfer: OrchestrationV2ContextTransfer = { diff --git a/apps/server/src/orchestration-v2/runtimeLayer.test.ts b/apps/server/src/orchestration-v2/runtimeLayer.test.ts index b889c7e98a..548d97a66b 100644 --- a/apps/server/src/orchestration-v2/runtimeLayer.test.ts +++ b/apps/server/src/orchestration-v2/runtimeLayer.test.ts @@ -831,6 +831,288 @@ it.layer(TestLayer)("OrchestrationV2LayerLive lifecycle", (it) => { assert.equal(afterPromotion.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled"); }), ); + + it.effect("promotes only one queued run after each terminal run", () => + Effect.gen(function* () { + const orchestrator = yield* OrchestratorV2; + const eventSink = yield* EventSinkV2; + const threadId = ThreadId.make("runtime-layer-serialized-queue-thread"); + + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-serialized-queue-create"), + threadId, + projectId: ProjectId.make("runtime-layer-serialized-queue-project"), + title: "Serialized queue", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: process.cwd(), + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-serialized-queue-active"), + threadId, + messageId: MessageId.make("runtime-layer-serialized-queue-active"), + text: "Active", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-serialized-queue-first"), + threadId, + messageId: MessageId.make("runtime-layer-serialized-queue-first"), + text: "First queued", + attachments: [], + modelSelection, + dispatchMode: { type: "queue_after_active" }, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-serialized-queue-second"), + threadId, + messageId: MessageId.make("runtime-layer-serialized-queue-second"), + text: "Second queued", + attachments: [], + modelSelection, + dispatchMode: { type: "queue_after_active" }, + }); + + const before = yield* orchestrator.getThreadProjection(threadId); + const activeRun = before.runs.find((run) => run.status === "starting"); + const queuedRuns = before.runs + .filter((run) => run.status === "queued") + .toSorted((left, right) => left.ordinal - right.ordinal); + const firstQueuedRun = queuedRuns[0]; + const secondQueuedRun = queuedRuns[1]; + assert.isDefined(activeRun); + assert.isDefined(firstQueuedRun); + assert.isDefined(secondQueuedRun); + assert.isFalse( + before.turnItems.some( + (item) => + item.type === "user_message" && + (item.messageId === firstQueuedRun.userMessageId || + item.messageId === secondQueuedRun.userMessageId), + ), + "queued messages must not exist as turn items before dispatch", + ); + + const promotedRunIds = yield* Queue.unbounded(); + const afterSequence = yield* orchestrator.getThreadEventSequence(threadId); + yield* eventSink.stream({ threadId, afterSequence }).pipe( + Stream.runForEach((stored) => + stored.event.type === "run.updated" && stored.event.payload.status === "starting" + ? Queue.offer(promotedRunIds, stored.event.payload.id) + : Effect.void, + ), + Effect.forkScoped, + ); + yield* Effect.yieldNow; + + const activeCompletedAt = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make("runtime-layer-serialized-queue-active-completed"), + type: "run.updated", + threadId, + runId: activeRun.id, + ...(activeRun.rootNodeId === null ? {} : { nodeId: activeRun.rootNodeId }), + providerInstanceId: activeRun.providerInstanceId, + occurredAt: activeCompletedAt, + payload: { + ...activeRun, + status: "completed", + completedAt: activeCompletedAt, + }, + }, + ], + }); + + assert.equal(yield* Queue.take(promotedRunIds), firstQueuedRun.id); + const afterFirstPromotion = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + afterFirstPromotion.runs.find((run) => run.id === firstQueuedRun.id)?.status, + "starting", + ); + assert.equal( + afterFirstPromotion.runs.find((run) => run.id === secondQueuedRun.id)?.status, + "queued", + ); + const promotedMessageItem = afterFirstPromotion.turnItems.find( + (item) => item.type === "user_message" && item.messageId === firstQueuedRun.userMessageId, + ); + assert.isDefined(promotedMessageItem); + if (promotedMessageItem.type !== "user_message") { + assert.fail("promoted queue item must be a user message"); + } + assert.equal(promotedMessageItem.inputIntent, "turn_start"); + assert.isTrue( + promotedMessageItem.startedAt !== null && + DateTime.toEpochMillis(promotedMessageItem.startedAt) >= + DateTime.toEpochMillis(activeCompletedAt), + ); + + const promotedFirst = afterFirstPromotion.runs.find((run) => run.id === firstQueuedRun.id); + assert.isDefined(promotedFirst); + const firstCompletedAt = yield* DateTime.now; + yield* eventSink.write({ + events: [ + { + id: EventId.make("runtime-layer-serialized-queue-first-completed"), + type: "run.updated", + threadId, + runId: promotedFirst.id, + ...(promotedFirst.rootNodeId === null ? {} : { nodeId: promotedFirst.rootNodeId }), + providerInstanceId: promotedFirst.providerInstanceId, + occurredAt: firstCompletedAt, + payload: { + ...promotedFirst, + status: "completed", + completedAt: firstCompletedAt, + }, + }, + ], + }); + + assert.equal(yield* Queue.take(promotedRunIds), secondQueuedRun.id); + const afterSecondPromotion = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + afterSecondPromotion.runs.find((run) => run.id === firstQueuedRun.id)?.status, + "completed", + ); + assert.equal( + afterSecondPromotion.runs.find((run) => run.id === secondQueuedRun.id)?.status, + "starting", + ); + }), + ); + + it.effect("edits and removes queued runs", () => + Effect.gen(function* () { + const orchestrator = yield* OrchestratorV2; + const threadId = ThreadId.make("runtime-layer-queued-edit-thread"); + + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-queued-edit-create"), + threadId, + projectId: ProjectId.make("runtime-layer-queued-edit-project"), + title: "Edit queued work", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: "/tmp/runtime-layer-queued-edit", + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-queued-edit-active-message"), + threadId, + messageId: MessageId.make("runtime-layer-queued-edit-active-message"), + text: "Keep the provider occupied.", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-queued-edit-queued-message"), + threadId, + messageId: MessageId.make("runtime-layer-queued-edit-queued-message"), + text: "Original queued text.", + attachments: [], + modelSelection, + dispatchMode: { type: "queue_after_active" }, + }); + + const before = yield* orchestrator.getThreadProjection(threadId); + const queuedRun = before.runs.find((run) => run.status === "queued"); + assert.isDefined(queuedRun); + + yield* orchestrator.dispatch({ + type: "queued-run.edit", + commandId: CommandId.make("runtime-layer-queued-edit-edit"), + threadId, + runId: queuedRun.id, + text: "Updated queued text.", + }); + + const afterEdit = yield* orchestrator.getThreadProjection(threadId); + assert.equal( + afterEdit.messages.find((message) => message.id === queuedRun.userMessageId)?.text, + "Updated queued text.", + ); + const editedItem = afterEdit.turnItems.find( + (item) => item.type === "user_message" && item.messageId === queuedRun.userMessageId, + ); + assert.isUndefined(editedItem, "editing queue state must not create a timeline turn item"); + + const emptyEditError = yield* orchestrator + .dispatch({ + type: "queued-run.edit", + commandId: CommandId.make("runtime-layer-queued-edit-empty"), + threadId, + runId: queuedRun.id, + text: " ", + }) + .pipe(Effect.flip); + assert.equal(emptyEditError._tag, "OrchestratorDispatchError"); + + yield* orchestrator.dispatch({ + type: "queued-run.cancel", + commandId: CommandId.make("runtime-layer-queued-edit-cancel"), + threadId, + runId: queuedRun.id, + }); + + const afterCancel = yield* orchestrator.getThreadProjection(threadId); + assert.equal(afterCancel.runs.find((run) => run.id === queuedRun.id)?.status, "cancelled"); + assert.equal( + afterCancel.attempts.find((attempt) => attempt.runId === queuedRun.id)?.status, + "cancelled", + ); + assert.equal( + afterCancel.nodes.find((node) => node.runId === queuedRun.id)?.status, + "cancelled", + ); + assert.isFalse( + afterCancel.visibleTurnItems.some( + (row) => row.item.type === "user_message" && row.item.runId === queuedRun.id, + ), + "removed queued message must not surface as a transcript row", + ); + assert.equal(yield* orchestrator.resumeQueuedRuns, 0); + + const cancelAgainError = yield* orchestrator + .dispatch({ + type: "queued-run.cancel", + commandId: CommandId.make("runtime-layer-queued-edit-cancel-again"), + threadId, + runId: queuedRun.id, + }) + .pipe(Effect.flip); + assert.equal(cancelAgainError._tag, "OrchestratorDispatchError"); + }), + ); }); it.layer(SharedApplicationDataPlaneTestLayer)("pending provider interruption", (it) => { @@ -911,6 +1193,164 @@ it.layer(SharedApplicationDataPlaneTestLayer)("pending provider interruption", ( ); }); +it.layer(SharedApplicationDataPlaneTestLayer)("snooze projection", (it) => { + it.effect("carries snooze state through the V2 shell projection", () => + Effect.gen(function* () { + const applicationEngine = yield* OrchestrationEngineService; + const orchestrator = yield* OrchestratorV2; + const projectId = ProjectId.make("runtime-layer-snoozed-project"); + const threadId = ThreadId.make("runtime-layer-snoozed-thread"); + const snoozedUntil = "2099-07-25T09:00:00.000Z"; + + yield* applicationEngine.dispatch({ + type: "project.create", + commandId: CommandId.make("runtime-layer-snoozed-project-create"), + projectId, + title: "Snoozed shell projection", + workspaceRoot: "/tmp/runtime-layer-snoozed-project", + defaultModelSelection: modelSelection, + scripts: [], + createdAt: "2026-07-24T00:00:00.000Z", + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-snoozed-thread-create"), + threadId, + projectId, + title: "Snoozed thread", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + yield* orchestrator.dispatch({ + type: "thread.snooze", + commandId: CommandId.make("runtime-layer-snoozed-thread-snooze"), + threadId, + snoozedUntil, + }); + + const firstProjection = yield* orchestrator.getThreadProjection(threadId); + const firstSnoozedAt = firstProjection.thread.snoozedAt; + const firstUpdatedAt = firstProjection.thread.updatedAt; + assert.isNotNull(firstSnoozedAt); + + yield* orchestrator.dispatch({ + type: "thread.snooze", + commandId: CommandId.make("runtime-layer-snoozed-thread-snooze-again"), + threadId, + snoozedUntil, + }); + + const shell = yield* orchestrator.getShellSnapshot(); + const thread = shell.threads.find((candidate) => candidate.id === threadId); + assert.isDefined(thread); + assert.equal(DateTime.formatIso(thread.snoozedUntil!), snoozedUntil); + assert.deepEqual(thread.snoozedAt, firstSnoozedAt); + assert.deepEqual(thread.updatedAt, firstUpdatedAt); + + yield* orchestrator.dispatch({ + type: "message.dispatch", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-snoozed-message"), + threadId, + messageId: MessageId.make("runtime-layer-snoozed-message"), + text: "Wake this thread.", + attachments: [], + modelSelection, + dispatchMode: { type: "start_immediately" }, + }); + + const awakened = yield* orchestrator.getThreadProjection(threadId); + assert.isNull(awakened.thread.snoozedUntil); + assert.isNull(awakened.thread.snoozedAt); + }), + ); +}); + +it.layer(SharedApplicationDataPlaneTestLayer)("visited projection", (it) => { + it.effect("carries the visited watermark through the V2 shell projection", () => + Effect.gen(function* () { + const applicationEngine = yield* OrchestrationEngineService; + const orchestrator = yield* OrchestratorV2; + const projectId = ProjectId.make("runtime-layer-visited-project"); + const threadId = ThreadId.make("runtime-layer-visited-thread"); + const visitedAt = "2026-07-24T01:00:00.000Z"; + + yield* applicationEngine.dispatch({ + type: "project.create", + commandId: CommandId.make("runtime-layer-visited-project-create"), + projectId, + title: "Visited shell projection", + workspaceRoot: "/tmp/runtime-layer-visited-project", + defaultModelSelection: modelSelection, + scripts: [], + createdAt: "2026-07-24T00:00:00.000Z", + }); + yield* orchestrator.dispatch({ + type: "thread.create", + createdBy: "user", + creationSource: "web", + commandId: CommandId.make("runtime-layer-visited-thread-create"), + threadId, + projectId, + title: "Visited thread", + modelSelection, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + }); + const created = yield* orchestrator.getThreadProjection(threadId); + assert.isNull(created.thread.lastVisitedAt); + const createdUpdatedAt = created.thread.updatedAt; + + yield* orchestrator.dispatch({ + type: "thread.visit", + commandId: CommandId.make("runtime-layer-visited-thread-visit"), + threadId, + visitedAt, + }); + const visited = yield* orchestrator.getThreadProjection(threadId); + assert.isNotNull(visited.thread.lastVisitedAt); + assert.equal(DateTime.formatIso(visited.thread.lastVisitedAt!), visitedAt); + // Visiting records read state, not activity: updatedAt must not move. + assert.deepEqual(visited.thread.updatedAt, createdUpdatedAt); + + // Monotonic: an older watermark (a replay or a stale device) cannot + // rewind the marker. + yield* orchestrator.dispatch({ + type: "thread.visit", + commandId: CommandId.make("runtime-layer-visited-thread-visit-stale"), + threadId, + visitedAt: "2026-07-24T00:30:00.000Z", + }); + const afterStaleVisit = yield* orchestrator.getThreadProjection(threadId); + assert.equal(DateTime.formatIso(afterStaleVisit.thread.lastVisitedAt!), visitedAt); + + const shell = yield* orchestrator.getShellSnapshot(); + const thread = shell.threads.find((candidate) => candidate.id === threadId); + assert.isDefined(thread); + assert.equal(DateTime.formatIso(thread!.lastVisitedAt!), visitedAt); + assert.deepEqual(thread!.updatedAt, createdUpdatedAt); + + // No completed run yet → nothing to mark unread against. + const markUnread = yield* orchestrator + .dispatch({ + type: "thread.mark-unread", + commandId: CommandId.make("runtime-layer-visited-thread-mark-unread"), + threadId, + }) + .pipe(Effect.flip); + assert.instanceOf(markUnread, OrchestratorDispatchError); + }), + ); +}); + it.layer(SharedApplicationDataPlaneTestLayer)("shared application data plane", (it) => { it.effect("orders retained project transactions and V2 thread transactions in one source", () => Effect.gen(function* () { diff --git a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts index db47771130..8b1cc07667 100644 --- a/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts +++ b/apps/server/src/orchestration-v2/testkit/OrchestratorScenario.ts @@ -101,6 +101,12 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray { createdAt: occurredAt, updatedAt: occurredAt, archivedAt: null, + settledOverride: null, + settledAt: null, + lastVisitedAt: null, deletedAt: null, }, }, diff --git a/apps/web/src/components/AppSidebarLayout.tsx b/apps/web/src/components/AppSidebarLayout.tsx index a3ba766796..2677551675 100644 --- a/apps/web/src/components/AppSidebarLayout.tsx +++ b/apps/web/src/components/AppSidebarLayout.tsx @@ -14,8 +14,13 @@ import { getLocalStorageItem, removeLocalStorageItem } from "../hooks/useLocalSt import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"; import { cn, isMacPlatform } from "../lib/utils"; import { primaryServerKeybindingsAtom } from "../state/server"; +<<<<<<< HEAD import { useEnvironmentIdentificationMode, useLegacySidebarEnabled } from "../hooks/useSettings"; import LegacyThreadSidebar from "./LegacySidebar"; +======= +import { useEnvironmentIdentificationMode, useSidebarV2Enabled } from "../hooks/useSettings"; +import { useThreadVisitedMigration } from "../hooks/useThreadVisitedMigration"; +>>>>>>> 844dad005a (feat(orchestration): track provider retries and thread visits) import ThreadSidebar from "./Sidebar"; import { SettingsSidebarNav } from "./settings/SettingsSidebarNav"; import { SidebarChromeHeader } from "./sidebar/SidebarChrome"; @@ -138,9 +143,18 @@ function ProjectProjectionRetention() { export function AppSidebarLayout({ children }: { children: ReactNode }) { const navigate = useNavigate(); +<<<<<<< HEAD const legacySidebarEnabled = useLegacySidebarEnabled(); // Settings routes show the settings nav in place of whichever thread // sidebar is active. +======= + const sidebarV2Enabled = useSidebarV2Enabled(); + // Seeds server-side visited tracking from this browser's localStorage the + // first time each thread shell loads (no-op on already-seeded servers). + useThreadVisitedMigration(); + // Settings routes render the settings nav, which lives in the v1 component + // and is identical for both sidebars — so v1 stays mounted there. +>>>>>>> 844dad005a (feat(orchestration): track provider retries and thread visits) const pathname = useLocation({ select: (location) => location.pathname }); const isOnSettings = pathname === "/settings" || pathname.startsWith("/settings/"); const isMacosDesktop = isElectron && isMacPlatform(navigator.platform); diff --git a/apps/web/src/components/ChatView.tsx b/apps/web/src/components/ChatView.tsx index 18c44a61bb..23fa1b6138 100644 --- a/apps/web/src/components/ChatView.tsx +++ b/apps/web/src/components/ChatView.tsx @@ -24,10 +24,12 @@ import { } from "@t3tools/contracts"; import { type EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; import { + deriveThreadActivityRun, deriveLatestThreadRun, deriveThreadRuntime, } from "@t3tools/client-runtime/state/thread-execution"; import { resolveThreadProviderSession } from "@t3tools/client-runtime/state/thread-workflows"; +import { resolveThreadLastVisitedAt } from "./Sidebar.logic"; import { derivePendingThreadRequests } from "@t3tools/client-runtime/state/thread-requests"; import { parseScopedThreadKey, @@ -84,7 +86,7 @@ import { deriveRevertTurnCountByUserMessageId, deriveActiveWorkStartedAt, deriveActivePlanState, - deriveTurnPlans, + findSidebarProposedPlan, findLatestProposedPlan, hasActionableProposedPlan, isLatestRunSettled, @@ -148,13 +150,9 @@ import { usePreviewMiniPlayerStore, } from "../previewMiniPlayerStore"; import { RightPanelTabs } from "./RightPanelTabs"; -import { AgentsPanel } from "./AgentsPanel"; -import { - deriveAgentPanelModel, - foldSubagentActivities, -} from "@t3tools/client-runtime/state/subagentRuntime"; import { DiffWorkerPoolProvider } from "./DiffWorkerPoolProvider"; import { resolveShortcutCommand, shortcutLabelForCommand } from "../keybindings"; +import PlanSidebar from "./PlanSidebar"; import ThreadTerminalDrawer from "./ThreadTerminalDrawer"; import { ChevronDownIcon } from "lucide-react"; import { cn, randomHex } from "~/lib/utils"; @@ -214,11 +212,7 @@ import { serverEnvironment, } from "../state/server"; import { terminalEnvironment } from "../state/terminal"; -import { threadEnvironment, useEnvironmentThread } from "../state/threads"; -import { - requestOlderThreadTurns, - threadHasOlderTurns, -} from "@t3tools/client-runtime/state/threads"; +import { threadEnvironment } from "../state/threads"; import { vcsEnvironment } from "../state/vcs"; import { useEnvironments, usePrimaryEnvironment } from "../state/environments"; import { @@ -236,7 +230,6 @@ import { DraftHeroHeadline } from "./chat/DraftHeroHeadline"; import { ExpandedImageDialog } from "./chat/ExpandedImageDialog"; import { PullRequestThreadDialog } from "./PullRequestThreadDialog"; import { MessagesTimeline } from "./chat/MessagesTimeline"; -import { resolveTimelineIsAtEnd } from "./chat/MessagesTimeline.logic"; import { ChatHeader } from "./chat/ChatHeader"; import { shouldShowOpenInPicker } from "./chat/OpenInPicker.logic"; import { useOpenFavoriteEditorShortcut } from "./chat/OpenInPickerShortcut"; @@ -248,12 +241,7 @@ import { import { type ExpandedImagePreview } from "./chat/ExpandedImagePreview"; import { ThreadDetailsPanel, type ThreadDetailsPanelProps } from "./chat/ThreadDetailsPanel"; import { NoActiveThreadState } from "./NoActiveThreadState"; -import { - resolveEffectiveEnvMode, - resolveLocalCheckoutBranchMismatch, - shouldShowComposerContextStrip, - shouldShowEnvironmentIndicator, -} from "./BranchToolbar.logic"; +import { resolveEffectiveEnvMode, resolveLocalCheckoutBranchMismatch } from "./BranchToolbar.logic"; import { getProviderStatusBannerKey, ProviderStatusBanner, @@ -333,6 +321,7 @@ const IMAGE_ONLY_BOOTSTRAP_PROMPT = "[User attached one or more images without additional text. Respond using the conversation context and the attached image(s).]"; const EMPTY_PROVIDERS: ServerProvider[] = []; const EMPTY_PROVIDER_SKILLS: ServerProvider["skills"] = []; +const EMPTY_PROJECTION_RUNS: OrchestrationV2ThreadProjection["runs"] = []; const EMPTY_ATTACHMENT_IDS: string[] = []; const EMPTY_PENDING_USER_INPUT_ANSWERS: Record = {}; function useDraftHeroLayoutTransition(isDraftHeroState: boolean) { @@ -1244,21 +1233,11 @@ function ChatViewContent(props: ChatViewProps) { [serverVisibleTurnItems], ); const markThreadVisited = useUiStateStore((store) => store.markThreadVisited); - const activeThreadLastVisitedAt = useUiStateStore( + const activeThreadLocalLastVisitedAt = useUiStateStore( (store) => store.threadLastVisitedAtById[routeThreadKey], ); - const loadEarlierTurns = useMemo(() => { - if (routeKind !== "server" || !threadHasOlderTurns(routeThreadState)) { - return null; - } - return { - loading: routeThreadState.page._tag === "Some" && routeThreadState.page.value.loadingOlder, - onLoadEarlier: () => { - requestOlderThreadTurns(routeThreadRef.environmentId, routeThreadRef.threadId); - }, - }; - }, [routeKind, routeThreadRef, routeThreadState]); - const markThreadVisited = useUiStateStore((store) => store.markThreadVisited); + const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false }); + const lastDispatchedVisitRef = useRef(null); const settings = useEnvironmentSettings(environmentId); // New-thread defaults live in the primary environment's settings.json (the // settings UI never writes to remote environments), so read them from the @@ -1268,6 +1247,7 @@ function ChatViewContent(props: ChatViewProps) { (store) => store.setStickyModelSelection, ); const timestampFormat = settings.timestampFormat; + const autoOpenPlanSidebar = settings.autoOpenPlanSidebar; const navigate = useNavigate(); const { resolvedTheme } = useTheme(); // Granular store selectors — avoid subscribing to prompt changes. @@ -1492,6 +1472,10 @@ function ChatViewContent(props: ChatViewProps) { () => (serverProjection === null ? null : deriveLatestThreadRun(serverProjection)), [serverProjection], ); + const serverActivityRun = useMemo( + () => (serverProjection === null ? null : deriveThreadActivityRun(serverProjection)), + [serverProjection], + ); const serverRuntime = useMemo( () => (serverProjection === null ? null : deriveThreadRuntime(serverProjection)), [serverProjection], @@ -1503,6 +1487,7 @@ function ChatViewContent(props: ChatViewProps) { const supportsProviderSwitchingViaHandoff = activeProviderSession?.capabilities.sessions.supportsProviderSwitchingViaHandoff === true; const activeLatestRun = isServerThread ? serverLatestRun : (activeThread?.latestRun ?? null); + const activeActivityRun = isServerThread ? serverActivityRun : (activeThread?.latestRun ?? null); const activeRuntime = isServerThread ? serverRuntime : (activeThread?.runtime ?? null); const parentSubagentThreadId = activeThread?.lineage.relationshipToParent === "subagent" @@ -1548,13 +1533,8 @@ function ChatViewContent(props: ChatViewProps) { // the branch mismatch banner. const [, setThreadErrorBannerDismissTick] = useState(0); const runtimeMode = composerRuntimeMode ?? activeThread?.runtimeMode ?? DEFAULT_RUNTIME_MODE; - // Plan mode is legacy (Settings → Beta). With the flag off the effective - // mode is forced to "default" — even for threads with a stored plan mode — - // so nobody is trapped in plan mode while its toggle is hidden. The next - // send persists "default" back to the thread. - const interactionMode = settings.planModeEnabled - ? (composerInteractionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE) - : DEFAULT_INTERACTION_MODE; + const interactionMode = + composerInteractionMode ?? activeThread?.interactionMode ?? DEFAULT_INTERACTION_MODE; const isLocalDraftThread = !isServerThread && localDraftThread !== undefined; const canCheckoutPullRequestIntoThread = isLocalDraftThread; const activeThreadId = activeThread?.id ?? null; @@ -1641,7 +1621,7 @@ function ChatViewContent(props: ChatViewProps) { ); const previewPanelOpen = activeRightPanelKind === "preview" && isPreviewSupportedInRuntime(); const rightPanelOpen = rightPanelState.isOpen; - const canMaximizeRightPanel = rightPanelOpen && !shouldUseRightPanelSheet; + const canMaximizeRightPanel = rightPanelOpen && !shouldUsePlanSidebarSheet; const rightPanelMaximized = canMaximizeRightPanel && maximizedRightPanelThreadKey === routeThreadKey; const inlineRightPanelOwnsTitleBar = rightPanelOpen && !shouldUsePlanSidebarSheet; @@ -1684,6 +1664,8 @@ function ChatViewContent(props: ChatViewProps) { previewPanelOpen, ]); + const planSidebarOpen = activeRightPanelKind === "plan"; + const existingOpenTerminalThreadKeys = useMemo(() => { const existingThreadKeys = new Set([...serverThreadKeys, ...draftThreadKeys]); return openTerminalThreadKeys.filter((nextThreadKey) => existingThreadKeys.has(nextThreadKey)); @@ -1950,6 +1932,46 @@ function ChatViewContent(props: ChatViewProps) { [openOrReuseProjectDraftThread], ); + useEffect(() => { + if (!serverThread?.id) return; + const threadUpdatedAt = Date.parse(serverThread.updatedAt); + if (Number.isNaN(threadUpdatedAt)) return; + const effectiveLastVisitedAt = resolveThreadLastVisitedAt( + serverThread.lastVisitedAt, + activeThreadLocalLastVisitedAt, + ); + const lastVisitedAt = effectiveLastVisitedAt ? Date.parse(effectiveLastVisitedAt) : NaN; + if (!Number.isNaN(lastVisitedAt) && lastVisitedAt >= threadUpdatedAt) return; + + if (serverThread.lastVisitedAt !== undefined) { + // Server-tracked visited state: record the watermark server-side so it + // syncs across every device connected to the environment. Dedupe per + // watermark — the effect re-runs before the command's echo lands. + const dispatchKey = `${routeThreadKey}:${serverThread.updatedAt}`; + if (lastDispatchedVisitRef.current === dispatchKey) return; + lastDispatchedVisitRef.current = dispatchKey; + void visitThreadMutation({ + environmentId: serverThread.environmentId, + input: { threadId: serverThread.id, visitedAt: serverThread.updatedAt }, + }); + return; + } + + markThreadVisited( + scopedThreadKey(scopeThreadRef(serverThread.environmentId, serverThread.id)), + serverThread.updatedAt, + ); + }, [ + activeThreadLocalLastVisitedAt, + markThreadVisited, + routeThreadKey, + serverThread?.environmentId, + serverThread?.id, + serverThread?.lastVisitedAt, + serverThread?.updatedAt, + visitThreadMutation, + ]); + const selectedProviderByThreadId = composerActiveProvider ?? null; const threadProvider = activeThread?.modelSelection.instanceId ?? @@ -2073,21 +2095,7 @@ function ChatViewContent(props: ChatViewProps) { () => deriveActivePlanState(serverProjection, activeLatestRun?.runId ?? undefined), [activeLatestRun?.runId, serverProjection], ); - // Current step for the in-chat working row: only for the running turn's own - // plan (deriveActivePlanState falls back to older turns' plans, which must - // not label fresh work). Falls back to the first pending step so an - // all-pending freshly written plan labels the row, matching the chip and - // the server's planProgress. - const workingStepLabel = useMemo(() => { - if (!activePlan || activePlan.turnId !== (activeLatestTurn?.turnId ?? null)) { - return null; - } - return ( - activePlan.steps.find((step) => step.status === "inProgress")?.step ?? - activePlan.steps.find((step) => step.status === "pending")?.step ?? - null - ); - }, [activeLatestTurn?.turnId, activePlan]); + const planSidebarLabel = sidebarProposedPlan || interactionMode === "plan" ? "Plan" : "Tasks"; const showPlanFollowUpPrompt = pendingUserInputs.length === 0 && interactionMode === "plan" && @@ -2110,7 +2118,7 @@ function ChatViewContent(props: ChatViewProps) { }); const isWorking = phase === "running" || isSendBusy || isConnecting || isRevertingCheckpoint; const activeWorkStartedAt = deriveActiveWorkStartedAt( - activeLatestRun, + activeActivityRun, activeRuntime, localDispatchStartedAt, ); @@ -3049,6 +3057,9 @@ function ChatViewContent(props: ChatViewProps) { }, [activeThreadRef, openPreview]); const addDiffSurface = useCallback(() => { if (!activeThreadRef || !isServerThread || !isGitRepo) return; + if (planSidebarOpen) { + dismissPlanSidebarForCurrentTurn(); + } useRightPanelStore.getState().open(activeThreadRef, "diff"); onDiffPanelOpen?.(); }, [activeThreadRef, isGitRepo, isServerThread, onDiffPanelOpen]); @@ -3059,10 +3070,6 @@ function ChatViewContent(props: ChatViewProps) { if (!activeThreadRef || !activeProject) return; useRightPanelStore.getState().open(activeThreadRef, "files"); }, [activeProject, activeThreadRef]); - const addAgentsSurface = useCallback(() => { - if (!activeThreadRef) return; - useRightPanelStore.getState().open(activeThreadRef, "agents"); - }, [activeThreadRef]); const openFileSurface = useCallback( (relativePath: string) => { if (!activeThreadRef || !activeProject) return; @@ -3190,6 +3197,11 @@ function ChatViewContent(props: ChatViewProps) { const activateRightPanelSurface = useCallback( (surface: RightPanelSurface) => { if (!activeThreadRef) return; + if (surface.kind === "plan") { + planSidebarDismissedForTurnRef.current = null; + } else if (planSidebarOpen) { + dismissPlanSidebarForCurrentTurn(); + } useRightPanelStore.getState().activateSurface(activeThreadRef, surface.id); if (surface.kind === "preview" && surface.resourceId) { setActivePreviewTab(activeThreadRef, surface.resourceId); @@ -3201,12 +3213,16 @@ function ChatViewContent(props: ChatViewProps) { onDiffPanelOpen?.(); } }, - [activeThreadRef, diffOpen, onDiffPanelOpen], + [activeThreadRef, diffOpen, dismissPlanSidebarForCurrentTurn, onDiffPanelOpen, planSidebarOpen], ); const toggleRightPanel = useCallback(() => { if (!activeThreadRef) return; if (rightPanelOpen) { - closePreviewPanel(); + if (planSidebarOpen) { + closePlanSidebar(); + } else { + closePreviewPanel(); + } return; } useRightPanelStore.getState().toggleVisibility(activeThreadRef); @@ -3228,6 +3244,10 @@ function ChatViewContent(props: ChatViewProps) { const cleanupRightPanelSurfaces = useCallback( (surfaces: readonly RightPanelSurface[]) => { if (!activeThreadRef) return; + if (surfaces.some((surface) => surface.kind === "plan")) { + dismissPlanSidebarForCurrentTurn(); + } + for (const surface of surfaces) { if (surface.kind === "preview" && surface.resourceId) { void closePreviewSession({ @@ -3253,6 +3273,7 @@ function ChatViewContent(props: ChatViewProps) { activePreviewState.sessions, closePreview, closeTerminalMutation, + dismissPlanSidebarForCurrentTurn, storeCloseTerminal, ], ); @@ -3434,27 +3455,38 @@ function ChatViewContent(props: ChatViewProps) { new Debouncer(() => setShowScrollToBottom(true), { wait: 150 }), ); const timelineScrollModeRef = useRef("following-end"); - // State mirror of the follow mode refs. LegendList's maintainScrollAtEnd - // re-pins on its own (independent of the refs), so the timeline needs a - // render-visible flag to switch it off once the user scrolls away. - const [timelineLiveFollowEnabled, setTimelineLiveFollowEnabled] = useState(true); const pendingTimelineAnchorRef = useRef(null); const positionedTimelineAnchorRef = useRef(null); const settledTimelineAnchorRef = useRef(null); const activeTimelineAnchorIndexRef = useRef(null); + const observedTimelineActivityRef = useRef<{ + readonly threadKey: string | null; + readonly runId: RunId | null; + }>({ + threadKey: activeThreadKey, + runId: activeActivityRun?.runId ?? null, + }); const anchorUserScrollGenerationRef = useRef(0); const liveFollowUserScrollGenerationRef = useRef(0); - // Manual navigation stops live-follow without removing anchored end space. - // Collapsing that space during a gesture clamps the viewport back to the end. + const pendingAnchorScrollRestoreRef = useRef<{ + readonly messageId: MessageId; + readonly offset: number; + readonly userScrollGeneration: number; + } | null>(null); + const anchorScrollRestoreFrameRef = useRef(null); const cancelTimelineLiveFollowForUserNavigation = useCallback(() => { anchorUserScrollGenerationRef.current += 1; timelineScrollModeRef.current = "free-scrolling"; liveFollowUserScrollGenerationRef.current = null; - setTimelineLiveFollowEnabled(false); pendingTimelineAnchorRef.current = null; positionedTimelineAnchorRef.current = null; settledTimelineAnchorRef.current = null; activeTimelineAnchorIndexRef.current = null; + pendingAnchorScrollRestoreRef.current = null; + if (anchorScrollRestoreFrameRef.current !== null) { + cancelAnimationFrame(anchorScrollRestoreFrameRef.current); + anchorScrollRestoreFrameRef.current = null; + } }, []); const cancelTimelineLiveFollowForUserNavigationRef = useRef( cancelTimelineLiveFollowForUserNavigation, @@ -3463,6 +3495,49 @@ function ChatViewContent(props: ChatViewProps) { cancelTimelineLiveFollowForUserNavigationRef.current = cancelTimelineLiveFollowForUserNavigation; }, [cancelTimelineLiveFollowForUserNavigation]); + useEffect(() => { + const observed = observedTimelineActivityRef.current; + if (observed.threadKey !== activeThreadKey) { + observedTimelineActivityRef.current = { + threadKey: activeThreadKey, + runId: activeActivityRun?.runId ?? null, + }; + return; + } + if ( + activeActivityRun === null || + activeActivityRun.status === "queued" || + observed.runId === activeActivityRun.runId + ) { + return; + } + const dispatchedUserItem = serverProjection?.visibleTurnItems.find( + (row) => row.item.type === "user_message" && row.item.runId === activeActivityRun.runId, + ); + if (dispatchedUserItem?.item.type !== "user_message") { + return; + } + observedTimelineActivityRef.current = { + threadKey: activeThreadKey, + runId: activeActivityRun.runId, + }; + if ( + pendingTimelineAnchorRef.current !== null || + timelineScrollModeRef.current === "free-scrolling" + ) { + return; + } + + const messageId = dispatchedUserItem.item.messageId; + isAtEndRef.current = true; + timelineScrollModeRef.current = "anchoring-new-turn"; + liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current; + pendingTimelineAnchorRef.current = messageId; + activeTimelineAnchorIndexRef.current = null; + showScrollDebouncer.current.cancel(); + setShowScrollToBottom(false); + setTimelineAnchor({ threadKey: activeThreadKey, messageId }); + }, [activeActivityRun, activeThreadKey, serverProjection]); const getActiveTimelineTurnMetrics = useCallback( (list?: LegendListRef | null) => { const resolvedList = list ?? legendListRef.current; @@ -3510,140 +3585,52 @@ function ChatViewContent(props: ChatViewProps) { }, [composerOverlayHeight], ); + // Live-follow stays active after send/thread-open until an actual list scroll // gesture opts out. const scrollToEnd = useCallback((animated = false) => { isAtEndRef.current = true; timelineScrollModeRef.current = "following-end"; liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current; - setTimelineLiveFollowEnabled(true); pendingTimelineAnchorRef.current = null; activeTimelineAnchorIndexRef.current = null; showScrollDebouncer.current.cancel(); setShowScrollToBottom(false); - setTimelineAnchor((current) => - current.messageId === null ? current : { ...current, messageId: null }, - ); - requestAnimationFrame(() => { - void legendListRef.current?.scrollToEnd?.({ animated }); - }); + void legendListRef.current?.scrollToEnd?.({ animated }); }, []); useEffect(() => { let removeListeners: (() => void) | null = null; - let frame: number | null = null; - const attach = (remainingAttempts: number) => { - frame = requestAnimationFrame(() => { - frame = null; - const scrollNode = legendListRef.current?.getScrollableNode(); - if (!scrollNode) { - // The list may not have mounted on the first frame after a thread - // switch — without a retry the opt-out listeners never attach and - // live-follow becomes impossible to escape for the whole thread. - if (remainingAttempts > 0) { - attach(remainingAttempts - 1); - } - return; - } - const handleManualNavigation = () => { - cancelTimelineLiveFollowForUserNavigationRef.current(); - }; - // The gestures below must only break follow when they can actually - // move the viewport away from the live edge. Follow now gates - // LegendList's maintainScrollAtEnd, so a spurious break while pinned - // at the end produces no scroll event, never re-arms, and streaming - // silently stops following. Underflowing content can't scroll at all, - // so nothing there should break follow. - const contentScrollsUp = () => timelineRealContentOverflowsViewport(); - // The follow re-arm band, not the strict flag: streaming growth makes - // isAtEnd flicker false for a frame before the follow scroll catches - // up, and a gesture landing in that window while still pinned would - // otherwise break follow with no scroll event left to re-arm it. - const viewportIsAwayFromEnd = () => - resolveTimelineIsAtEnd(legendListRef.current?.getState(), composerOverlayHeight) === - false; - // Only an upward wheel is a navigation intent; wheeling down while - // following either does nothing (at the end) or moves toward it. - const handleWheel = (event: WheelEvent) => { - if (event.deltaY < 0 && contentScrollsUp()) { - handleManualNavigation(); - } - }; - // Touch direction isn't observable here (touchmove fires on any - // finger motion, scrolling or not), so break only once the drag has - // actually carried the viewport out of the end band — an upward flick - // gets there within its first few events and later touchmoves break. - const handleTouchMove = () => { - if (viewportIsAwayFromEnd()) { - handleManualNavigation(); - } - }; - // Scrollbar drags produce no wheel/touch events; they are the only - // pointerdowns whose target is the scroll node itself rather than a - // message row. Content clicks break follow only away from the end - // (reading or selecting up there must hold position); clicking near - // the live edge keeps following. - const handlePointerDown = (event: PointerEvent) => { - if (event.target === scrollNode) { - if (contentScrollsUp()) { - handleManualNavigation(); - } - return; - } - if (viewportIsAwayFromEnd()) { - handleManualNavigation(); - } - }; - // Keyboard scrolling (PageUp/Home/ArrowUp) bypasses wheel and - // pointer events entirely; without this the timeline yanks back to - // the end on the next stream chunk. - const handleKeyDown = (event: KeyboardEvent) => { - switch (event.key) { - case "PageUp": - case "Home": - case "ArrowUp": - if (contentScrollsUp()) { - handleManualNavigation(); - } - break; - default: - break; - } - }; - scrollNode.addEventListener("wheel", handleWheel, { - passive: true, - }); - scrollNode.addEventListener("touchmove", handleTouchMove, { - passive: true, - }); - scrollNode.addEventListener("pointerdown", handlePointerDown, { - passive: true, - }); - scrollNode.addEventListener("keydown", handleKeyDown); - removeListeners = () => { - scrollNode.removeEventListener("wheel", handleWheel); - scrollNode.removeEventListener("touchmove", handleTouchMove); - scrollNode.removeEventListener("pointerdown", handlePointerDown); - scrollNode.removeEventListener("keydown", handleKeyDown); - }; + const frame = requestAnimationFrame(() => { + const scrollNode = legendListRef.current?.getScrollableNode(); + if (!scrollNode) { + return; + } + const handleManualNavigation = () => { + cancelTimelineLiveFollowForUserNavigationRef.current(); + }; + scrollNode.addEventListener("wheel", handleManualNavigation, { + passive: true, }); - }; - attach(12); + scrollNode.addEventListener("touchmove", handleManualNavigation, { + passive: true, + }); + scrollNode.addEventListener("pointerdown", handleManualNavigation, { + passive: true, + }); + removeListeners = () => { + scrollNode.removeEventListener("wheel", handleManualNavigation); + scrollNode.removeEventListener("touchmove", handleManualNavigation); + scrollNode.removeEventListener("pointerdown", handleManualNavigation); + }; + }); return () => { - if (frame !== null) { - cancelAnimationFrame(frame); - } + cancelAnimationFrame(frame); removeListeners?.(); }; - }, [activeThread?.id, composerOverlayHeight, timelineRealContentOverflowsViewport]); + }, [activeThread?.id]); const onTimelineAnchorReady = useCallback((messageId: MessageId, anchorIndex: number) => { - // Anchored-end space can be remeasured when the turn completes. Once the - // user has scrolled away (or returned to ordinary end-following), that - // remeasurement must not restart the send-time anchor positioning. - if (timelineScrollModeRef.current !== "anchoring-new-turn") { - return; - } if (pendingTimelineAnchorRef.current === messageId) { pendingTimelineAnchorRef.current = null; } @@ -3665,23 +3652,75 @@ function ChatViewContent(props: ChatViewProps) { } return; } - void list - .scrollToIndex({ - index: anchorIndex, - animated: true, - viewPosition: 0, - viewOffset: CHAT_LIST_ANCHOR_OFFSET, - }) - .then(() => { - if (positionedTimelineAnchorRef.current !== messageId) { - return; - } - settledTimelineAnchorRef.current = messageId; - }); + const scrollNode = list.getScrollableNode(); + let finished = false; + const finishAnimatedPositioning = () => { + if (finished) { + return; + } + finished = true; + window.clearTimeout(fallbackTimer); + scrollNode.removeEventListener("scrollend", finishAnimatedPositioning); + if (positionedTimelineAnchorRef.current !== messageId) { + return; + } + const scrollOffset = list.getState().scroll; + void list.scrollToOffset({ offset: scrollOffset, animated: false }); + settledTimelineAnchorRef.current = messageId; + }; + const fallbackTimer = window.setTimeout(finishAnimatedPositioning, 750); + scrollNode.addEventListener("scrollend", finishAnimatedPositioning, { once: true }); + void list.scrollToIndex({ + index: anchorIndex, + animated: true, + viewPosition: 0, + viewOffset: CHAT_LIST_ANCHOR_OFFSET, + }); }); }; requestAnimationFrame(() => positionAnchor(12)); }, []); + const onTimelineAnchorSizeChanged = useCallback((messageId: MessageId) => { + if (settledTimelineAnchorRef.current !== messageId) { + return; + } + if (liveFollowUserScrollGenerationRef.current === anchorUserScrollGenerationRef.current) { + return; + } + const scrollOffset = legendListRef.current?.getState().scroll; + if (scrollOffset === undefined) { + return; + } + if (pendingAnchorScrollRestoreRef.current === null) { + pendingAnchorScrollRestoreRef.current = { + messageId, + offset: scrollOffset, + userScrollGeneration: anchorUserScrollGenerationRef.current, + }; + } + if (anchorScrollRestoreFrameRef.current !== null) { + return; + } + anchorScrollRestoreFrameRef.current = requestAnimationFrame(() => { + anchorScrollRestoreFrameRef.current = null; + const pending = pendingAnchorScrollRestoreRef.current; + pendingAnchorScrollRestoreRef.current = null; + if ( + pending && + settledTimelineAnchorRef.current === pending.messageId && + pending.userScrollGeneration === anchorUserScrollGenerationRef.current + ) { + const list = legendListRef.current; + const currentScrollOffset = list?.getState().scroll; + if ( + typeof currentScrollOffset === "number" && + Math.abs(currentScrollOffset - pending.offset) <= 2 + ) { + void list?.scrollToOffset({ offset: pending.offset, animated: false }); + } + } + }); + }, []); const onIsAtEndChange = useCallback((isAtEnd: boolean) => { if ( @@ -3697,7 +3736,6 @@ function ChatViewContent(props: ChatViewProps) { if (isAtEnd) { timelineScrollModeRef.current = "following-end"; liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current; - setTimelineLiveFollowEnabled(true); showScrollDebouncer.current.cancel(); setShowScrollToBottom(false); } else { @@ -3707,9 +3745,6 @@ function ChatViewContent(props: ChatViewProps) { } }, []); - // Anchored end space intentionally disables LegendList's normal end-follow so - // the sent message can stay near the top. T3 only owns streaming adjustments - // during that mode; LegendList owns ordinary end-follow everywhere else. useEffect(() => { if (!activeThread?.id) { return; @@ -3717,9 +3752,6 @@ function ChatViewContent(props: ChatViewProps) { if (liveFollowUserScrollGenerationRef.current !== anchorUserScrollGenerationRef.current) { return; } - if (timelineScrollModeRef.current !== "anchoring-new-turn") { - return; - } let secondFrame: number | null = null; const frame = requestAnimationFrame(() => { @@ -3741,13 +3773,28 @@ function ChatViewContent(props: ChatViewProps) { return; } - const metrics = getActiveTimelineTurnMetrics(list); - if (!metrics || metrics.scrollDeltaToRevealEnd <= 1) { + if (timelineScrollModeRef.current === "anchoring-new-turn") { + const metrics = getActiveTimelineTurnMetrics(list); + if (!metrics) { + return; + } + if (metrics.scrollDeltaToRevealEnd <= 1) { + return; + } + + const nextOffset = list.getState().scroll + metrics.scrollDeltaToRevealEnd; + void list.scrollToOffset({ offset: nextOffset, animated: false }); return; } - const nextOffset = list.getState().scroll + metrics.scrollDeltaToRevealEnd; - void list.scrollToOffset({ offset: nextOffset, animated: false }); + if (timelineScrollModeRef.current !== "following-end") { + return; + } + if (!timelineRealContentOverflowsViewport(list)) { + return; + } + + void list.scrollToEnd?.({ animated: false }); }); }); @@ -3757,20 +3804,31 @@ function ChatViewContent(props: ChatViewProps) { cancelAnimationFrame(secondFrame); } }; - }, [activeThread?.id, timelineEntries, getActiveTimelineTurnMetrics]); + }, [ + activeThread?.id, + timelineEntries, + getActiveTimelineTurnMetrics, + timelineRealContentOverflowsViewport, + ]); useEffect(() => { setPullRequestDialogState(null); isAtEndRef.current = true; timelineScrollModeRef.current = "following-end"; liveFollowUserScrollGenerationRef.current = anchorUserScrollGenerationRef.current; - setTimelineLiveFollowEnabled(true); pendingTimelineAnchorRef.current = null; positionedTimelineAnchorRef.current = null; settledTimelineAnchorRef.current = null; activeTimelineAnchorIndexRef.current = null; showScrollDebouncer.current.cancel(); setShowScrollToBottom(false); + if (planSidebarOpenOnNextThreadRef.current) { + planSidebarOpenOnNextThreadRef.current = false; + if (activeThreadRef) { + useRightPanelStore.getState().open(activeThreadRef, "plan"); + } + } + planSidebarDismissedForTurnRef.current = null; // activeThreadRef resets transitively with the active thread. }, [activeThread?.id]); @@ -3914,18 +3972,13 @@ function ChatViewContent(props: ChatViewProps) { const supportsSettlement = serverConfig?.environment.capabilities.threadSettlement === true; const supportsSnooze = serverConfig?.environment.capabilities.threadSnooze === true; const nowMinute = useNowMinute(); - const snoozeNow = new Date().toISOString(); const activeThreadSnoozed = activeThreadShell !== null && supportsSnooze && - effectiveSnoozed(activeThreadShell, { now: snoozeNow }); + effectiveSnoozed(activeThreadShell, { now: new Date().toISOString() }); const [snoozeWakeTick, bumpSnoozeWakeTick] = useState(0); - void snoozeWakeTick; - const activeThreadWokeAt = - activeThreadShell !== null && supportsSnooze - ? threadWokeAt(activeThreadShell, { now: snoozeNow }) - : null; useEffect(() => { + void snoozeWakeTick; if (!activeThreadSnoozed) return; const wakeAtMs = Date.parse(activeThreadShell?.snoozedUntil ?? ""); if (!Number.isFinite(wakeAtMs)) return; @@ -3935,41 +3988,6 @@ function ChatViewContent(props: ChatViewProps) { ); return () => window.clearTimeout(id); }, [activeThreadShell?.snoozedUntil, activeThreadSnoozed, snoozeWakeTick]); - const acknowledgeActiveThreadWoke = useCallback(() => { - if (activeThreadRef === null || activeThreadWokeAt === null) return; - markThreadVisited(scopedThreadKey(activeThreadRef), activeThreadWokeAt); - }, [activeThreadRef, activeThreadWokeAt, markThreadVisited]); - // Mirror of the sidebar's Woke pill for the open thread: same visit - // comparison, same merged/closed-PR suppression (finished work needs no - // wake-up call). Drives the dismissible composer banner below. - const activeThreadLastVisitedAt = useUiStateStore((store) => - activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey], - ); - const activeThreadWokeVisible = useMemo(() => { - if (activeThreadWokeAt === null) return false; - if (activeThreadPr?.state === "merged" || activeThreadPr?.state === "closed") return false; - const wokeAtMs = Date.parse(activeThreadWokeAt); - if (Number.isNaN(wokeAtMs)) return false; - // Having the thread open counts as a visit at completedAt (the effect - // above stamps it); folding that floor in here keeps a completion- - // triggered wake from flashing a banner for one frame before the stamp - // lands. An unparseable stored visit counts as never-visited: corrupt - // local data must not eat the wake signal. - const storedVisitMs = activeThreadLastVisitedAt ? Date.parse(activeThreadLastVisitedAt) : NaN; - const completedAtMs = activeLatestTurn?.completedAt - ? Date.parse(activeLatestTurn.completedAt) - : NaN; - const lastVisitedMs = Math.max( - Number.isNaN(storedVisitMs) ? -Infinity : storedVisitMs, - Number.isNaN(completedAtMs) ? -Infinity : completedAtMs, - ); - return lastVisitedMs < wokeAtMs; - }, [ - activeLatestTurn?.completedAt, - activeThreadLastVisitedAt, - activeThreadPr?.state, - activeThreadWokeAt, - ]); const activeThreadSettled = useMemo(() => { if (activeThreadShell === null || !supportsSettlement) return false; return effectiveSettled(activeThreadShell, { @@ -4150,109 +4168,9 @@ function ChatViewContent(props: ChatViewProps) { switchGitRef, updateThreadMetadata, ]); - // Background work (subagent fleets, workflow runs, watch loops) can outlive - // the turn; once it settles, the composer stop button is gone, so this - // banner is the only visible stop affordance. Stop routes through the - // stop-everything interrupt: it kills every live background task before - // interrupting, and works by session, so no active turn is needed. - const activeBackgroundLiveness = - !isWorking && activeThread ? (activeThreadShell?.backgroundLiveness ?? null) : null; - const [isStoppingBackgroundWork, setIsStoppingBackgroundWork] = useState(false); - useEffect(() => { - // "Stopping..." holds until the liveness clears; the interrupt command - // returning only means the request was accepted. - if (activeBackgroundLiveness === null) { - setIsStoppingBackgroundWork(false); - } - }, [activeBackgroundLiveness]); - useEffect(() => { - // Per-thread state: switching threads while A's stop is pending must not - // disable B's Stop button (review finding). - setIsStoppingBackgroundWork(false); - }, [activeThreadId]); - const handleStopBackgroundWork = useCallback(async () => { - if (!activeThread) return; - setIsStoppingBackgroundWork(true); - const result = await interruptThreadTurn({ - environmentId, - input: buildThreadTurnInterruptInput(activeThread), - }); - if (result._tag === "Failure") { - // Every failure clears the pending state — an interrupted command - // never reached the server, so liveness would hold "Stopping..." - // forever. Only real failures toast. - setIsStoppingBackgroundWork(false); - if (!isAtomCommandInterrupted(result)) { - const error = squashAtomCommandFailure(result); - setThreadError( - activeThread.id, - error instanceof Error ? error.message : "Failed to stop background work.", - ); - } - } - }, [activeThread, environmentId, interruptThreadTurn, setThreadError]); - const backgroundLivenessBannerItem = useMemo(() => { - if (activeBackgroundLiveness === null || !activeThread) { - return null; - } - const working = activeBackgroundLiveness === "working"; - const liveCount = agentPanelModel.liveCount; - return { - id: `background-liveness:${activeThread.id}`, - variant: "default", - icon: ( -