feat(orchestration): track provider retries and thread visits

- Project retry progress and recovery for Codex and Claude turns
- Sync thread completion markers through server-side visit timestamps
This commit is contained in:
Julius Marminge committed 2026-08-14 11:23:30 +02:00
1 parent 918e4155dd
commit 4124948442
73 files changed
+3971 -1271

No files matched your search

@@ -73,6 +73,7 @@ const SHELL_SNAPSHOT: OrchestrationV2ShellSnapshot = {
archivedAt: null,
settledOverride: null,
settledAt: NOW,
lastVisitedAt: null,
deletedAt: null,
},
],
@@ -108,6 +109,7 @@ const THREAD_SNAPSHOT: OrchestrationV2ThreadDetailSnapshot = {
archivedAt: null,
settledOverride: null,
settledAt: NOW,
lastVisitedAt: null,
deletedAt: null,
},
runs: [],
@@ -25,6 +25,8 @@ import type { StatusTone } from "../../components/StatusPill";
import type { DraftComposerImageAttachment } from "../../lib/composerImages";
import { CHAT_CONTENT_MAX_WIDTH, type LayoutVariant } from "../../lib/layout";
import { scopedThreadKey } from "../../lib/scopedEntities";
import { threadEnvironment } from "../../state/threads";
import { useAtomCommand } from "../../state/use-atom-command";
import type {
PendingApproval,
PendingUserInput,
@@ -240,6 +242,39 @@ export const ThreadDetailScreen = memo(function ThreadDetailScreen(props: Thread
selectedThreadKeyRef.current = selectedThreadKey;
}, [selectedThreadKey]);
const visitThread = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
const lastDispatchedVisitRef = useRef<string | null>(null);
const selectedThreadId = props.selectedThread.id;
const selectedThreadUpdatedAt = props.selectedThread.updatedAt;
const selectedThreadLastVisitedAt = props.selectedThread.lastVisitedAt;
useEffect(() => {
// Records the server-side visited watermark while the thread is on
// screen (mirror of web ChatView), so the "Done" marker clears on every
// device. Field absent → the server predates visited tracking.
if (selectedThreadLastVisitedAt === undefined) return;
const threadUpdatedAtMs = Date.parse(selectedThreadUpdatedAt);
if (Number.isNaN(threadUpdatedAtMs)) return;
const lastVisitedAtMs = selectedThreadLastVisitedAt
? Date.parse(selectedThreadLastVisitedAt)
: NaN;
if (!Number.isNaN(lastVisitedAtMs) && lastVisitedAtMs >= threadUpdatedAtMs) return;
// Dedupe per watermark — the effect re-runs before the command echo lands.
const dispatchKey = `${selectedThreadKey}:${selectedThreadUpdatedAt}`;
if (lastDispatchedVisitRef.current === dispatchKey) return;
lastDispatchedVisitRef.current = dispatchKey;
void visitThread({
environmentId: props.environmentId,
input: { threadId: selectedThreadId, visitedAt: selectedThreadUpdatedAt },
});
}, [
props.environmentId,
selectedThreadId,
selectedThreadKey,
selectedThreadLastVisitedAt,
selectedThreadUpdatedAt,
visitThread,
]);
useEffect(() => {
setAnchorMessageId(null);
lastScrolledAnchorMessageIdRef.current = null;
@@ -29,13 +29,10 @@ import { useThreadPr } from "../../state/use-thread-pr";
import { ThreadSwipeable } from "../home/thread-swipe-actions";
import { buildThreadTitleRegenerationMenuItems } from "./thread-title-regeneration-menu";
import {
resolveThreadListV2SnoozeMenuSelection,
resolveThreadListV2SnoozeGateExpiryMs,
resolveThreadListV2Status,
resolveThreadListV2SwipeActions,
threadHasUnseenCompletion,
type ThreadListV2Status,
} from "./threadListV2";
import { ThreadSearchMatchExcerpt } from "./thread-search-match";
/**
* Thread List v2 renders one flat native list: rich edge-to-edge rows for
@@ -418,7 +415,13 @@ export const ThreadListV2Row = memo(function ThreadListV2Row(props: {
const selected = props.selected === true;
const status = resolveThreadListV2Status(thread);
const statusLabel = STATUS_LABEL_BY_STATUS[status];
// "Done" marks a completion the user has not opened yet — same emerald
// label as the web sidebar, sourced from the server-side visited watermark
// so checking a thread on any device clears it everywhere.
const isUnread = status === "ready" && threadHasUnseenCompletion(thread);
const statusLabel =
STATUS_LABEL_BY_STATUS[status] ??
(isUnread ? { label: "Done", className: "text-emerald-700 dark:text-emerald-300" } : undefined);
const timeLabel = threadTimeLabel(thread);
const handleDelete = useCallback(() => onDeleteThread(thread), [onDeleteThread, thread]);
@@ -122,6 +122,27 @@ export function resolveThreadListV2Enabled(input: {
return input.legacyPreference !== true;
}
/**
* Completed-but-not-yet-seen, mirroring the web sidebar's
* hasUnseenCompletion. The visited watermark is server state
* (thread.lastVisitedAt), so the marker agrees across web and mobile.
* Never-visited threads count as read — a fresh environment must not light
* up its whole history — and pre-tracking servers (field absent) never
* report unread.
*/
export function threadHasUnseenCompletion(
thread: Pick<EnvironmentThreadShell, "latestRun" | "lastVisitedAt">,
): boolean {
const completedAt = thread.latestRun?.completedAt;
if (!completedAt) return false;
const completedAtMs = Date.parse(completedAt);
if (Number.isNaN(completedAtMs)) return false;
if (!thread.lastVisitedAt) return false;
const lastVisitedAtMs = Date.parse(thread.lastVisitedAt);
if (Number.isNaN(lastVisitedAtMs)) return true;
return completedAtMs > lastVisitedAtMs;
}
export function resolveThreadListV2Status(
thread: Pick<EnvironmentThreadShell, "hasPendingApprovals" | "hasPendingUserInput" | "session">,
): ThreadListV2Status {
@@ -108,6 +108,29 @@ describe("buildThreadFeed", () => {
).toBe(true);
});
it("adds queued input only after dispatch creates its turn item", () => {
const dispatchedRunId = RunId.make("run-dispatched-queued");
const dispatchedMessageId = MessageId.make("message-dispatched-queued");
expect(buildThreadFeed([])).toEqual([]);
const promotedEntries = buildThreadFeed([
projected(
{
...userMessage(),
id: TurnItemId.make("item-dispatched-queued"),
runId: dispatchedRunId,
messageId: dispatchedMessageId,
inputIntent: "turn_start",
},
0,
),
]);
expect(promotedEntries.map((entry) => entry.id)).toEqual([dispatchedMessageId]);
expect(
promotedEntries[0]?.type === "message" ? promotedEntries[0].message.inputIntent : undefined,
).toBe("turn_start");
});
it("preserves authoritative V2 order instead of sorting reconstructed collections", () => {
const rows = [
projected(userMessage("2026-06-20T00:00:03.000Z"), 0),
+8 -6
View File
@@ -951,12 +951,13 @@ export function buildPendingUserInputAnswers(
export function buildThreadFeed(
visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>,
): ThreadFeedEntry[] {
const entries = visibleTurnItems.map((row): RawThreadFeedEntry => {
const entries: RawThreadFeedEntry[] = [];
for (const row of visibleTurnItems) {
const item = row.item;
const createdAt = DateTime.formatIso(item.startedAt ?? item.updatedAt);
if (item.type === "user_message" || item.type === "assistant_message") {
const updatedAt = DateTime.formatIso(item.updatedAt);
return {
entries.push({
type: "message",
id: item.messageId,
createdAt,
@@ -980,16 +981,17 @@ export function buildThreadFeed(
updatedAt,
projectedItem: row,
},
};
});
continue;
}
const activity = toFeedActivity(row);
return {
entries.push({
type: "activity",
id: activity.id,
createdAt,
runId: item.runId,
activity,
};
});
});
}
return groupAdjacentActivities(entries);
}
@@ -152,6 +152,7 @@ export const make = Effect.gen(function* () {
threadPinning: true,
threadPinReorder: true,
threadTitleRegeneration: true,
threadVisitedTracking: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverSelfUpdate === "boot-service" ? { serverSelfUpdateProgress: true } : {}),
},
@@ -603,6 +603,9 @@ function makeTurnInput(input: {
createdAt: input.now,
updatedAt: input.now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
},
threadId: input.threadId,
@@ -107,6 +107,9 @@ function makeClaudeTestAppThread(input: {
createdAt: input.now,
updatedAt: input.now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
};
}
@@ -979,6 +982,9 @@ describe("ClaudeAdapterV2 native fork", () => {
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
},
threadId: targetThreadId,
@@ -1153,6 +1159,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
readonly subtype?: string;
readonly isError?: boolean;
readonly errors?: ReadonlyArray<string>;
readonly apiErrorStatus?: number;
}) =>
claudeSdkFrame({
type: "result",
@@ -1176,6 +1183,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
session_id: WAKE_NATIVE_SESSION,
...(input.origin === undefined ? {} : { origin: input.origin }),
...(input.errors === undefined ? {} : { errors: input.errors }),
...(input.apiErrorStatus === undefined ? {} : { api_error_status: input.apiErrorStatus }),
});
const turnOneResult = makeResultFrame({
uuid: "00000000-0000-4000-8000-000000000102",
@@ -1303,6 +1311,125 @@ describe("ClaudeAdapterV2 background wake turns", () => {
});
const makeWakeHarness = makeWakeHarnessWithOptions();
it.effect("projects API retries and resolves the same item after recovery", () =>
Effect.scoped(
Effect.gen(function* () {
const harness = yield* makeWakeHarness;
const now = yield* DateTime.now;
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-api-retry"),
text: "Open github.com.",
attachments: [],
}),
);
yield* Queue.offer(
harness.sdkMessages,
claudeSdkFrame({
type: "system",
subtype: "api_retry",
attempt: 2,
max_retries: 10,
retry_delay_ms: 1_500,
error_status: 529,
error: "overloaded",
uuid: "00000000-0000-4000-8000-000000000201",
session_id: WAKE_NATIVE_SESSION,
}),
);
const retryItems = () =>
harness.events.flatMap((event) =>
event.type === "turn_item.updated" &&
event.turnItem.type === "error" &&
event.turnItem.retry !== undefined
? [event.turnItem]
: [],
);
yield* awaitUntil(() => retryItems().length === 1, "Claude retry item");
const runningRetry = retryItems()[0];
assert.equal(runningRetry?.status, "running");
assert.equal(runningRetry?.failure.code, "api_error_529");
assert.deepEqual(runningRetry?.retry, {
attempt: 2,
maxAttempts: 10,
retryDelayMs: 1_500,
});
yield* Queue.offer(
harness.sdkMessages,
makeResultFrame({
uuid: "00000000-0000-4000-8000-000000000202",
result: "Opened GitHub.",
}),
);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "recovered Claude turn");
yield* awaitUntil(() => retryItems().length === 2, "resolved Claude retry item");
const recoveredRetry = retryItems()[1];
assert.equal(recoveredRetry?.id, runningRetry?.id);
assert.equal(recoveredRetry?.status, "completed");
assert.equal(recoveredRetry?.title, "Provider recovered");
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
),
);
it.effect("carries exhausted retry progress into the terminal provider error", () =>
Effect.scoped(
Effect.gen(function* () {
const harness = yield* makeWakeHarness;
const now = yield* DateTime.now;
yield* harness.runtime.startTurn(
makeClaudeTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-claude-api-retry-exhausted"),
text: "Open github.com.",
attachments: [],
}),
);
yield* Queue.offer(
harness.sdkMessages,
claudeSdkFrame({
type: "system",
subtype: "api_retry",
attempt: 10,
max_retries: 10,
retry_delay_ms: 38_010,
error_status: 529,
error: "overloaded",
uuid: "00000000-0000-4000-8000-000000000203",
session_id: WAKE_NATIVE_SESSION,
}),
);
yield* Queue.offer(
harness.sdkMessages,
makeResultFrame({
uuid: "00000000-0000-4000-8000-000000000204",
result: "Claude is temporarily overloaded.",
isError: true,
apiErrorStatus: 529,
}),
);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "failed Claude turn");
const terminal = harness.terminalEvents()[0];
assert.equal(terminal?.status, "failed");
if (terminal?.status !== "failed") return;
assert.deepEqual(terminal.retry, {
attempt: 10,
maxAttempts: 10,
retryDelayMs: 38_010,
});
assert.isDefined(terminal.retryStartedAt);
assert.equal(terminal.failure.code, "api_error_529");
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
),
);
it.effect("buffers wake output and requests a single continuation run", () =>
Effect.scoped(
Effect.gen(function* () {
@@ -10,6 +10,7 @@ import {
type Query as ClaudeQuery,
type Settings as ClaudeSdkSettings,
type SDKAssistantMessage,
type SDKAPIRetryMessage,
type SDKMessage,
type SDKResultMessage,
type SDKUserMessage,
@@ -27,6 +28,7 @@ import {
type OrchestrationV2ExecutionNode,
type OrchestrationV2ProviderCapabilities,
type OrchestrationV2ProviderFailure,
type OrchestrationV2ProviderRetry,
type OrchestrationV2ProviderSession,
type OrchestrationV2ProviderThread,
type OrchestrationV2ProviderTurn,
@@ -70,7 +72,7 @@ import { mergeProviderInstanceEnvironment } from "../../provider/ProviderInstanc
import { T3_CODE_ORCHESTRATION_INSTRUCTIONS } from "../../provider/T3OrchestrationInstructions.ts";
import * as McpProviderSession from "../../mcp/McpProviderSession.ts";
import { IdAllocatorV2, type IdAllocatorV2Shape } from "../IdAllocator.ts";
import { makeProviderFailure } from "../ProviderFailure.ts";
import { makeProviderFailure, makeProviderRetryTurnItem } from "../ProviderFailure.ts";
import { turnScopedSelectionTransition } from "../ProviderSelectionTransition.ts";
import {
ProviderAdapterEnsureThreadError,
@@ -1802,6 +1804,19 @@ function providerFailureFromResult(
});
}
function providerFailureFromApiRetry(message: SDKAPIRetryMessage): OrchestrationV2ProviderFailure {
const errorName = message.error.replaceAll("_", " ");
return makeProviderFailure({
message: `Claude API ${errorName}.`,
code:
message.error_status === null
? message.error
: `api_error_${Math.trunc(message.error_status)}`,
class: message.error_status === null ? "transport_error" : "provider_error",
retryable: true,
});
}
function buildAssistantArtifacts(input: {
readonly idAllocator: IdAllocatorV2Shape;
readonly turnInput: ProviderAdapterV2TurnInput;
@@ -1908,6 +1923,13 @@ interface ActiveClaudeTurnContext {
readonly subagentNodesByTaskId: Map<string, OrchestrationV2ExecutionNode["id"]>;
}
interface ActiveClaudeProviderRetry {
readonly retry: OrchestrationV2ProviderRetry;
readonly failure: OrchestrationV2ProviderFailure;
readonly startedAt: DateTime.Utc;
readonly itemOrdinal: number;
}
interface ActiveClaudeSubagent {
task: OrchestrationV2Subagent;
readonly childThreadId: ThreadId;
@@ -1993,6 +2015,9 @@ export function makeClaudeAdapterV2(
const openedNativeThreads = yield* Ref.make(new Set<string>());
const itemOrdinals = yield* Ref.make(new Map<string, number>());
const nextItemOrdinalsByTurn = yield* Ref.make(new Map<string, number>());
const providerRetries = yield* Ref.make(
new Map<OrchestrationV2ProviderTurn["id"], ActiveClaudeProviderRetry>(),
);
const pendingRuntimeRequests = yield* Ref.make(
new Map<string, PendingClaudeRuntimeRequest>(),
);
@@ -2840,6 +2865,37 @@ export function makeClaudeAdapterV2(
);
}
const providerRetry = yield* Ref.modify(providerRetries, (current) => {
const retry = current.get(input.context.providerTurnId);
if (retry === undefined) {
return [undefined, current] as const;
}
const updated = new Map(current);
updated.delete(input.context.providerTurnId);
return [retry, updated] as const;
});
if (providerRetry !== undefined && input.status !== "failed") {
yield* emitProviderEvent({
type: "turn_item.updated",
driver: CLAUDE_PROVIDER,
turnItem: makeProviderRetryTurnItem({
idAllocator,
driver: CLAUDE_PROVIDER,
threadId: input.context.input.threadId,
runId: input.context.input.runId,
nodeId: input.context.input.rootNodeId,
providerThreadId: input.context.input.providerThread.id,
providerTurnId: input.context.providerTurnId,
itemOrdinal: providerRetry.itemOrdinal,
failure: providerRetry.failure,
retry: providerRetry.retry,
status: input.status,
startedAt: providerRetry.startedAt,
updatedAt: input.completedAt,
}),
});
}
const threadDisposition = input.threadDisposition ?? "reusable";
const terminalEvent: ProviderAdapterV2Event =
input.status === "failed"
@@ -2855,6 +2911,12 @@ export function makeClaudeAdapterV2(
),
status: input.status,
failure: input.failure ?? makeProviderFailure({ class: "provider_error" }),
...(providerRetry === undefined
? {}
: {
retry: providerRetry.retry,
retryStartedAt: providerRetry.startedAt,
}),
threadDisposition,
}
: {
@@ -3144,6 +3206,51 @@ export function makeClaudeAdapterV2(
context.nativeMessageCursor = message.uuid;
}
if (message.type === "system" && message.subtype === "api_retry") {
const updatedAt = yield* DateTime.now;
const previous = (yield* Ref.get(providerRetries)).get(context.providerTurnId);
const retry: OrchestrationV2ProviderRetry = {
attempt: Math.max(1, Math.trunc(message.attempt)),
maxAttempts: Math.max(1, Math.trunc(message.max_retries)),
retryDelayMs: Math.max(0, Math.trunc(message.retry_delay_ms)),
};
const failure = providerFailureFromApiRetry(message);
const itemOrdinal =
previous?.itemOrdinal ??
(yield* resolveItemOrdinal(context, `terminal-failure:${context.providerTurnId}`));
const state: ActiveClaudeProviderRetry = {
retry,
failure,
startedAt: previous?.startedAt ?? updatedAt,
itemOrdinal,
};
yield* Ref.update(providerRetries, (current) => {
const updated = new Map(current);
updated.set(context.providerTurnId, state);
return updated;
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: CLAUDE_PROVIDER,
turnItem: makeProviderRetryTurnItem({
idAllocator,
driver: CLAUDE_PROVIDER,
threadId: context.input.threadId,
runId: context.input.runId,
nodeId: context.input.rootNodeId,
providerThreadId: context.input.providerThread.id,
providerTurnId: context.providerTurnId,
itemOrdinal,
failure,
retry,
status: "running",
startedAt: state.startedAt,
updatedAt,
}),
});
return;
}
if (message.type === "system" && message.subtype === "task_started") {
if (isClaudeNonSubagentTask(message)) {
context.ignoredTaskIds.add(message.task_id);
@@ -835,6 +835,9 @@ function makeCodexTestAppThread(input: {
createdAt: input.now,
updatedAt: input.now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
};
}
@@ -1112,6 +1115,87 @@ describe("CodexAdapterV2 post-settle continuation", () => {
event.type === "message.updated" && event.message.role === "assistant",
);
it.effect("projects retryable app-server errors and resolves the same item after recovery", () =>
Effect.scoped(
Effect.gen(function* () {
const scenario = "codex-provider-api-retry";
const nativeThreadId = `native-${scenario}-thread`;
const nativeTurnId = `native-${scenario}-turn`;
const transcript = makeCodexReplayTranscript({
scenario,
entries: [
...codexReplayPreamble({
nativeThreadId,
nativeTurnId,
prompt: "Open github.com.",
}),
{
type: "emit_inbound",
label: "error/retry",
frame: {
method: "error",
params: {
threadId: nativeThreadId,
turnId: nativeTurnId,
willRetry: true,
error: {
message: "Reconnecting... 2/5",
additionalDetails: "The response stream disconnected.",
codexErrorInfo: {
responseStreamDisconnected: { httpStatusCode: 529 },
},
},
},
},
},
{
type: "emit_inbound",
label: "turn/completed",
frame: {
method: "turn/completed",
params: {
threadId: nativeThreadId,
turn: makeCodexReplayTurn({ id: nativeTurnId, status: "completed" }),
},
},
},
],
});
const harness = yield* makeCodexReplayHarness(transcript);
const now = yield* DateTime.now;
yield* harness.runtime.startTurn(
makeCodexTestTurnInput({
threadId: harness.threadId,
providerThread: harness.providerThread,
now,
attemptId: RunAttemptId.make("attempt-codex-provider-api-retry"),
text: "Open github.com.",
}),
);
yield* awaitUntil(() => harness.terminalEvents().length === 1, "Codex retry recovery");
const retryItems = harness.events.flatMap((event) =>
event.type === "turn_item.updated" &&
event.turnItem.type === "error" &&
event.turnItem.retry !== undefined
? [event.turnItem]
: [],
);
assert.lengthOf(retryItems, 2);
assert.equal(retryItems[0]?.status, "running");
assert.equal(retryItems[0]?.failure.code, "responseStreamDisconnected");
assert.deepEqual(retryItems[0]?.retry, {
attempt: 2,
maxAttempts: 5,
retryDelayMs: null,
});
assert.equal(retryItems[1]?.id, retryItems[0]?.id);
assert.equal(retryItems[1]?.status, "completed");
assert.equal(retryItems[1]?.title, "Provider recovered");
}).pipe(Effect.provide(Layer.merge(idAllocatorLayer, NodeServices.layer))),
),
);
const finalAnswerTranscript = (
scenario: string,
answers: ReadonlyArray<{
@@ -10,6 +10,8 @@ import type {
ModelSelection,
OrchestrationV2PlanArtifact,
OrchestrationV2ProviderCapabilities,
OrchestrationV2ProviderFailure,
OrchestrationV2ProviderRetry,
OrchestrationV2ProviderSession,
OrchestrationV2ProviderThread,
OrchestrationV2ProviderTurn,
@@ -71,7 +73,7 @@ import {
type ProviderContinuationRequest,
ProviderContinuationRequests,
} from "../ProviderContinuationRequests.ts";
import { makeProviderFailure } from "../ProviderFailure.ts";
import { makeProviderFailure, makeProviderRetryTurnItem } from "../ProviderFailure.ts";
import { turnScopedSelectionTransition } from "../ProviderSelectionTransition.ts";
import {
ProviderAdapterEnsureThreadError,
@@ -771,6 +773,31 @@ export const resolveCodexRollbackTurnCount = Effect.fn("CodexAdapterV2.resolveRo
},
);
export function parseCodexRetryProgress(
message: string,
): Pick<OrchestrationV2ProviderRetry, "attempt" | "maxAttempts"> | null {
const match = /\b(\d+)\s*\/\s*(\d+)\b/u.exec(message);
if (match?.[1] === undefined || match[2] === undefined) {
return null;
}
const attempt = Number.parseInt(match[1], 10);
const maxAttempts = Number.parseInt(match[2], 10);
if (attempt < 1 || maxAttempts < 1) {
return null;
}
return { attempt, maxAttempts };
}
function codexErrorInfoCode(value: unknown): string | null {
if (typeof value === "string") {
return value;
}
if (typeof value !== "object" || value === null) {
return null;
}
return Object.keys(value)[0] ?? null;
}
interface ActiveCodexTurnContext {
readonly input: ProviderAdapterV2TurnInput;
readonly projectionAppThread: OrchestrationV2AppThread;
@@ -788,6 +815,13 @@ interface ActiveCodexTurnContext {
readonly startedAt: DateTime.Utc;
}
interface ActiveCodexProviderRetry {
readonly retry: OrchestrationV2ProviderRetry;
readonly failure: OrchestrationV2ProviderFailure;
readonly startedAt: DateTime.Utc;
readonly itemOrdinal: number;
}
/** Snapshot of a still-running commandExecution item for interrupt/fail terminalization. */
interface TrackedRunningCommandItem {
readonly id: string;
@@ -1418,6 +1452,9 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
const nextProviderTurnOrdinals = yield* Ref.make(new Map<string, number>());
const itemOrdinals = yield* Ref.make(new Map<string, number>());
const nextItemOrdinalsByTurn = yield* Ref.make(new Map<string, number>());
const providerRetries = yield* Ref.make(
new Map<ProviderTurnId, ActiveCodexProviderRetry>(),
);
const planDeltas = yield* Ref.make(new Map<string, string>());
const planIds = yield* Ref.make(new Map<string, OrchestrationV2PlanArtifact["id"]>());
const pendingRuntimeRequests = yield* Ref.make(
@@ -3745,6 +3782,73 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
}).pipe(Effect.orDie, turnTerminalizationPermit.withPermits(1)),
);
yield* client.handleServerNotification("error", (payload) =>
Effect.gen(function* () {
if (!payload.willRetry) {
return;
}
const context = yield* awaitActiveTurn(payload.turnId);
if (context === undefined) {
return;
}
const updatedAt = yield* DateTime.now;
const previous = (yield* Ref.get(providerRetries)).get(context.providerTurnId);
const progress = parseCodexRetryProgress(payload.error.message);
const retry: OrchestrationV2ProviderRetry = {
attempt: progress?.attempt ?? (previous?.retry.attempt ?? 0) + 1,
maxAttempts: progress?.maxAttempts ?? previous?.retry.maxAttempts ?? null,
retryDelayMs: null,
};
const code = codexErrorInfoCode(payload.error.codexErrorInfo);
const additionalDetails = payload.error.additionalDetails?.trim();
const failure = makeProviderFailure({
message:
additionalDetails === undefined || additionalDetails.length === 0
? payload.error.message
: additionalDetails,
code,
class:
code?.startsWith("http") === true || code?.startsWith("responseStream") === true
? "transport_error"
: "provider_error",
retryable: true,
});
const itemOrdinal =
previous?.itemOrdinal ??
(yield* resolveItemOrdinal(context, `terminal-failure:${context.providerTurnId}`));
const state: ActiveCodexProviderRetry = {
retry,
failure,
startedAt: previous?.startedAt ?? updatedAt,
itemOrdinal,
};
yield* Ref.update(providerRetries, (current) => {
const updated = new Map(current);
updated.set(context.providerTurnId, state);
return updated;
});
yield* emitProviderEvent({
type: "turn_item.updated",
driver: CODEX_PROVIDER,
turnItem: makeProviderRetryTurnItem({
idAllocator,
driver: CODEX_PROVIDER,
threadId: context.projectionThreadId,
runId: context.projectionRunId,
nodeId: context.providerNodeId,
providerThreadId: context.providerThread.id,
providerTurnId: context.providerTurnId,
itemOrdinal,
failure,
retry,
status: "running",
startedAt: state.startedAt,
updatedAt,
}),
});
}).pipe(Effect.orDie),
);
yield* client.handleServerNotification("item/started", (payload) =>
Effect.gen(function* () {
const context = yield* awaitActiveTurn(payload.turnId);
@@ -4469,6 +4573,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
readonly context: ActiveCodexTurnContext;
readonly status: OrchestrationV2ProviderTurn["status"];
readonly failureMessage?: string;
readonly providerRetry?: ActiveCodexProviderRetry;
}): Effect.fn.Return<CodexRootTerminalEvent> {
const terminalStatus = providerTurnStatusToTerminal(input.status);
if (terminalStatus === "failed") {
@@ -4483,10 +4588,19 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
`terminal-failure:${input.context.providerTurnId}`,
),
status: terminalStatus,
failure: makeProviderFailure({
message: input.failureMessage,
class: "provider_error",
}),
failure:
input.failureMessage === undefined && input.providerRetry !== undefined
? input.providerRetry.failure
: makeProviderFailure({
message: input.failureMessage,
class: "provider_error",
}),
...(input.providerRetry === undefined
? {}
: {
retry: input.providerRetry.retry,
retryStartedAt: input.providerRetry.startedAt,
}),
threadDisposition: "reusable",
};
}
@@ -4509,6 +4623,7 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
readonly nativeTurnId: string;
readonly status: OrchestrationV2ProviderTurn["status"];
readonly failureMessage?: string;
readonly providerRetry?: ActiveCodexProviderRetry;
}) {
const event = yield* makeRootTerminalEvent(input);
const hasActiveDescendants = Array.from((yield* Ref.get(activeTurns)).values()).some(
@@ -4563,6 +4678,39 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
if (current !== input.context) {
return false;
}
const providerRetry = yield* Ref.modify(providerRetries, (current) => {
const retry = current.get(input.context.providerTurnId);
if (retry === undefined) {
return [undefined, current] as const;
}
const updated = new Map(current);
updated.delete(input.context.providerTurnId);
return [retry, updated] as const;
});
if (
providerRetry !== undefined &&
(input.status !== "failed" || input.context.subagent !== null)
) {
yield* emitProviderEvent({
type: "turn_item.updated",
driver: CODEX_PROVIDER,
turnItem: makeProviderRetryTurnItem({
idAllocator,
driver: CODEX_PROVIDER,
threadId: input.context.projectionThreadId,
runId: input.context.projectionRunId,
nodeId: input.context.providerNodeId,
providerThreadId: input.context.providerThread.id,
providerTurnId: input.context.providerTurnId,
itemOrdinal: providerRetry.itemOrdinal,
failure: providerRetry.failure,
retry: providerRetry.retry,
status: providerTurnStatusToTerminal(input.status),
startedAt: providerRetry.startedAt,
updatedAt: input.completedAt,
}),
});
}
if (input.status !== "completed") {
yield* Ref.update(terminalizedNonCompletedNativeTurns, (current) => {
const updated = new Set(current);
@@ -4659,7 +4807,10 @@ export function makeCodexAdapterV2(adapterOptions: CodexAdapterV2Options): Provi
);
}
if (input.context.subagent === null) {
yield* emitOrDeferRootTerminal(input);
yield* emitOrDeferRootTerminal({
...input,
...(providerRetry === undefined ? {} : { providerRetry }),
});
}
const waiter = (yield* Ref.get(turnWaiters)).get(input.nativeTurnId);
if (waiter !== undefined) {
@@ -104,6 +104,9 @@ function makeThread(threadId: ThreadId, now: DateTime.Utc): OrchestrationV2AppTh
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
};
}
@@ -178,6 +178,7 @@ function importedThread(row: LegacyThreadRow): OrchestrationV2AppThread {
archivedAt: nullableDateTime(row.archived_at),
settledOverride: settledOverrideFor(row.settled_override),
settledAt: nullableDateTime(row.settled_at),
lastVisitedAt: null,
deletedAt: nullableDateTime(row.deleted_at),
};
}
+446 -61
View File
@@ -185,6 +185,12 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId {
case "thread.archive":
case "thread.unarchive":
case "thread.delete":
case "thread.settle":
case "thread.unsettle":
case "thread.snooze":
case "thread.unsnooze":
case "thread.visit":
case "thread.mark-unread":
case "thread.metadata.update":
case "thread.runtime-mode.set":
case "thread.interaction-mode.set":
@@ -197,6 +203,8 @@ function commandThreadId(command: OrchestrationV2Command): ThreadId {
case "run.interrupt":
case "queued-message.promote-to-steer":
case "queued-run.reorder":
case "queued-run.cancel":
case "queued-run.edit":
case "runtime-request.respond":
case "checkpoint.rollback":
case "provider.switch":
@@ -651,6 +659,17 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
const rootNode = projection.nodes.find((candidate) => candidate.id === rootNodeId);
const attempt = projection.attempts.find((candidate) => candidate.id === attemptId);
const queuedMessage = projection.messages.find(
(candidate) => candidate.id === queuedRun.userMessageId,
);
const legacyQueuedTurnItem = projection.turnItems.find(
(
candidate,
): candidate is Extract<OrchestrationV2TurnItem, { readonly type: "user_message" }> =>
candidate.type === "user_message" &&
candidate.runId === queuedRun.id &&
candidate.messageId === queuedRun.userMessageId,
);
const queuedProviderThread = projection.providerThreads.find(
(candidate) => candidate.id === providerThreadId,
);
@@ -660,6 +679,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
if (
rootNode === undefined ||
attempt === undefined ||
queuedMessage === undefined ||
queuedProviderThread === undefined ||
(rootNode.checkpointScopeId !== null && storedCheckpointScope === undefined)
) {
@@ -729,6 +749,31 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
queuePosition: null,
startedAt: null,
};
const userTurnItem: OrchestrationV2TurnItem = {
...(legacyQueuedTurnItem ?? {
id: idAllocator.derive.userTurnItem({ messageId: queuedMessage.id }),
threadId,
runId: queuedRun.id,
nodeId: rootNodeId,
providerThreadId: queuedProviderThread.id,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: queuedRun.ordinal * 100,
status: "completed",
title: null,
type: "user_message",
messageId: queuedMessage.id,
text: queuedMessage.text,
attachments: queuedMessage.attachments,
createdBy: queuedMessage.createdBy,
creationSource: queuedMessage.creationSource,
}),
inputIntent: "turn_start",
startedAt: now,
completedAt: now,
updatedAt: now,
};
const checkpointEvents: ReadonlyArray<Omit<OrchestrationV2DomainEvent, "id">> =
storedCheckpointScope === undefined
? [
@@ -762,6 +807,15 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
occurredAt: now,
payload: providerThread,
},
{
type: "turn-item.updated",
threadId,
runId: queuedRun.id,
nodeId: rootNodeId,
providerInstanceId: queuedRun.providerInstanceId,
occurredAt: now,
payload: userTurnItem,
},
{
type: "run.updated",
threadId,
@@ -853,6 +907,11 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
lastVisitedAt: null,
deletedAt: null,
};
@@ -873,6 +932,12 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
| "thread.archive"
| "thread.unarchive"
| "thread.delete"
| "thread.settle"
| "thread.unsettle"
| "thread.snooze"
| "thread.unsnooze"
| "thread.visit"
| "thread.mark-unread"
| "thread.metadata.update"
| "thread.runtime-mode.set"
| "thread.interaction-mode.set"
@@ -949,6 +1014,59 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
: null;
const now = yield* DateTime.now;
let snoozedUntil: DateTime.Utc | null = null;
if (command.type === "thread.snooze") {
const parsedSnoozedUntil = DateTime.make(command.snoozedUntil);
if (
Option.isNone(parsedSnoozedUntil) ||
DateTime.toEpochMillis(parsedSnoozedUntil.value) <= DateTime.toEpochMillis(now)
) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Thread ${command.threadId} snooze wake time ${command.snoozedUntil} is not in the future.`,
});
}
if (projection.runtimeRequests.some((request) => request.status === "pending")) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Thread ${command.threadId} has a pending approval or user-input request and cannot be snoozed.`,
});
}
if (projection.runs.some((run) => run.status === "queued")) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Thread ${command.threadId} has a queued run and cannot be snoozed.`,
});
}
snoozedUntil = parsedSnoozedUntil.value;
}
let visitedAt: DateTime.Utc | null = null;
if (command.type === "thread.visit") {
const parsedVisitedAt = DateTime.make(command.visitedAt);
if (Option.isNone(parsedVisitedAt)) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Thread ${command.threadId} visit time ${command.visitedAt} is not a valid timestamp.`,
});
}
visitedAt = parsedVisitedAt.value;
}
let markUnreadVisitedAt: DateTime.Utc | null = null;
if (command.type === "thread.mark-unread") {
const latestRunCompletedAt = projection.runs.at(-1)?.completedAt ?? null;
if (latestRunCompletedAt === null) {
return yield* new OrchestratorDispatchError({
commandId: command.commandId,
commandType: command.type,
cause: `Thread ${command.threadId} has no completed run to mark unread.`,
});
}
markUnreadVisitedAt = DateTime.subtract(latestRunCompletedAt, { milliseconds: 1 });
}
const updatedThread: OrchestrationV2AppThread = (() => {
switch (command.type) {
case "thread.archive":
@@ -957,6 +1075,59 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return { ...thread, archivedAt: null, updatedAt: now };
case "thread.delete":
return { ...thread, deletedAt: thread.deletedAt ?? now, updatedAt: now };
case "thread.settle": {
const alreadySettled = thread.settledOverride === "settled" && thread.settledAt !== null;
return {
...thread,
settledOverride: "settled",
settledAt: alreadySettled ? thread.settledAt : now,
updatedAt: alreadySettled ? thread.updatedAt : now,
};
}
case "thread.unsettle": {
const alreadyPinnedActive = thread.settledOverride === "active";
return {
...thread,
settledOverride: "active",
settledAt: null,
updatedAt: alreadyPinnedActive ? thread.updatedAt : now,
};
}
case "thread.snooze": {
const sameWakeTime =
thread.snoozedUntil != null &&
snoozedUntil !== null &&
DateTime.toEpochMillis(thread.snoozedUntil) === DateTime.toEpochMillis(snoozedUntil);
const existingSnoozedAt = sameWakeTime ? (thread.snoozedAt ?? null) : null;
return {
...thread,
snoozedUntil,
snoozedAt: existingSnoozedAt ?? now,
updatedAt: existingSnoozedAt === null ? now : thread.updatedAt,
};
}
case "thread.unsnooze": {
const alreadyAwake = thread.snoozedUntil == null;
return {
...thread,
snoozedUntil: null,
snoozedAt: null,
updatedAt: alreadyAwake ? thread.updatedAt : now,
};
}
// Visited tracking records read state only; it must not bump updatedAt,
// otherwise viewing a thread would count as activity (and re-trigger the
// clients that dispatch thread.visit whenever updatedAt advances).
case "thread.visit": {
const previousVisitedAt = thread.lastVisitedAt;
const movesForward =
visitedAt !== null &&
(previousVisitedAt === null ||
DateTime.toEpochMillis(visitedAt) > DateTime.toEpochMillis(previousVisitedAt));
return movesForward ? { ...thread, lastVisitedAt: visitedAt } : thread;
}
case "thread.mark-unread":
return { ...thread, lastVisitedAt: markUnreadVisitedAt };
case "thread.metadata.update":
return {
...thread,
@@ -987,6 +1158,18 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
return "thread.unarchived" as const;
case "thread.delete":
return "thread.deleted" as const;
case "thread.settle":
return "thread.settled" as const;
case "thread.unsettle":
return "thread.unsettled" as const;
case "thread.snooze":
return "thread.snoozed" as const;
case "thread.unsnooze":
return "thread.unsnoozed" as const;
case "thread.visit":
return "thread.visited" as const;
case "thread.mark-unread":
return "thread.marked-unread" as const;
case "thread.metadata.update":
return "thread.metadata-updated" as const;
case "thread.runtime-mode.set":
@@ -2307,29 +2490,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
createdAt: now,
updatedAt: now,
};
const turnItem: OrchestrationV2TurnItem = {
createdBy: command.createdBy,
creationSource: command.creationSource,
id: idAllocator.derive.userTurnItem({ messageId: command.messageId }),
threadId: command.threadId,
runId,
nodeId: rootNodeId,
providerThreadId: queueProviderThread.id,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: ordinal * 100,
status: "completed",
title: null,
startedAt: now,
completedAt: now,
updatedAt: now,
type: "user_message",
messageId: command.messageId,
inputIntent: "queued_turn",
text: command.text,
attachments: command.attachments,
};
const emitEvent = emit(events, command);
yield* emitEvent({
type: "run.created",
@@ -2388,15 +2548,6 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
occurredAt: now,
payload: message,
});
yield* emitEvent({
type: "turn-item.updated",
threadId: command.threadId,
runId,
nodeId: rootNodeId,
providerInstanceId: modelSelection.instanceId,
occurredAt: now,
payload: turnItem,
});
return;
}
const pendingForkTransfer = pendingForkTransferForThread(projection);
@@ -3273,6 +3424,24 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
attachments: command.attachments,
};
const activeHandoff = portableForkHandoff ?? mergeBackHandoff ?? providerSwitchHandoff;
const handoffSourceRuns =
portableForkHandoff !== null
? sourceRun === null
? []
: [sourceRun]
: providerSwitchHandoff === null
? mergeBackSourceRun === null
? []
: [mergeBackSourceRun]
: providerSwitchCoveredRuns;
const handoffFromModelSelections = Array.from(
new Map(
handoffSourceRuns.map((run) => [
`${run.modelSelection.instanceId}${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<OrchestrationV2Command, { readonly type: "queued-run.cancel" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
) =>
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<OrchestrationV2Command, { readonly type: "queued-run.edit" }>,
events: Ref.Ref<Array<OrchestrationV2DomainEvent>>,
) =>
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,
@@ -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,
},
});
@@ -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<ProjectionStoreV2, never, SqlClient.SqlClient> =
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<ProjectionStoreV2, never, SqlClient.SqlClient> =
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<ProjectionStoreV2, never, SqlClient.SqlClient> =
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,
@@ -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"]),
}),
]);
@@ -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);
}),
@@ -248,6 +248,10 @@ export const layer: Layer.Layer<ProviderEventIngestorV2, never, EventSinkV2 | Id
providerTurnId: input.event.providerTurnId,
itemOrdinal: input.event.failureItemOrdinal,
failure: input.event.failure,
...(input.event.retry === undefined ? {} : { retry: input.event.retry }),
...(input.event.retryStartedAt === undefined
? {}
: { retryStartedAt: input.event.retryStartedAt }),
occurredAt,
}),
}),
@@ -2,6 +2,7 @@ import type {
NodeId,
OrchestrationV2ProviderFailure,
OrchestrationV2ProviderFailureClass,
OrchestrationV2ProviderRetry,
OrchestrationV2TurnItem,
ProviderDriverKind,
ProviderThreadId,
@@ -121,6 +122,8 @@ export function makeProviderFailureTurnItem(input: {
readonly providerTurnId: ProviderTurnId;
readonly itemOrdinal: number;
readonly failure: OrchestrationV2ProviderFailure;
readonly retry?: OrchestrationV2ProviderRetry;
readonly retryStartedAt?: DateTime.Utc;
readonly occurredAt: DateTime.Utc;
}): Extract<OrchestrationV2TurnItem, { readonly type: "error" }> {
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<OrchestrationV2TurnItem, { readonly type: "error" }> {
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,
};
}
@@ -168,6 +168,9 @@ function makeThreadCreatedEvent(input: {
createdAt: input.now,
updatedAt: input.now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
};
return {
@@ -70,6 +70,9 @@ function makeProjection(input: {
createdAt: input.now,
updatedAt: input.now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
},
runs: [],
@@ -48,6 +48,9 @@ function makeThread(input: {
createdAt: input.now,
updatedAt: input.now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
};
}
@@ -54,6 +54,7 @@ function makeParentThread(): OrchestrationV2AppThread {
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
snoozedUntil,
snoozedAt,
deletedAt: null,
@@ -75,6 +75,7 @@ export function makeSubagentChildThread(input: {
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
lastVisitedAt: null,
deletedAt: null,
};
}
@@ -55,6 +55,7 @@ function makeSourceThread(): OrchestrationV2AppThread {
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
snoozedUntil,
snoozedAt,
deletedAt: null,
@@ -86,6 +86,7 @@ export const layer: Layer.Layer<ThreadForkServiceV2> = Layer.succeed(
settledAt: null,
snoozedUntil: null,
snoozedAt: null,
lastVisitedAt: null,
deletedAt: null,
};
const transfer: OrchestrationV2ContextTransfer = {
@@ -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<RunId>();
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* () {
@@ -101,6 +101,12 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
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":
@@ -113,6 +119,8 @@ function commandThreadIds(command: OrchestrationV2Command): ReadonlyArray<Thread
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":
@@ -183,6 +183,9 @@ layer("OrchestrationEventStore", (it) => {
createdAt: occurredAt,
updatedAt: occurredAt,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
},
},
@@ -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);
File diff suppressed because it is too large. Load diff
+16 -1
View File
@@ -122,7 +122,7 @@ type ThreadStatusInput = Pick<
| "runtime"
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
> & {
lastVisitedAt?: string | undefined;
lastVisitedAt?: string | null | undefined;
};
export interface ThreadJumpHintVisibilityController {
@@ -217,6 +217,21 @@ export function useThreadJumpHintVisibility(): {
};
}
/**
* Effective visited watermark for a thread. Servers with visited tracking
* project `lastVisitedAt` on the shell and are authoritative — that value is
* shared across every device connected to the environment. Pre-tracking
* servers omit the field, and the browser's locally persisted watermark keeps
* working as before.
*/
export function resolveThreadLastVisitedAt(
serverLastVisitedAt: string | null | undefined,
localLastVisitedAt: string | undefined,
): string | undefined {
if (serverLastVisitedAt === undefined) return localLastVisitedAt;
return serverLastVisitedAt ?? undefined;
}
export function hasUnseenCompletion(thread: ThreadStatusInput): boolean {
if (!thread.latestRun?.completedAt) return false;
const completedAt = Date.parse(thread.latestRun.completedAt);
+57 -8
View File
@@ -133,6 +133,14 @@ import { useNowMinute } from "../hooks/useNowMinute";
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import { useProjects, useThreadShells } from "../state/entities";
import { environmentServerConfigsAtom, primaryServerKeybindingsAtom } from "../state/server";
import { useComposerDraftStore } from "../composerDraftStore";
import { useNewThreadHandler } from "../hooks/useHandleNewThread";
import { useDesktopUpdateState } from "../state/desktopUpdate";
import { useMarkThreadUnread, useThreadActions } from "../hooks/useThreadActions";
import { projectEnvironment } from "../state/projects";
import { useEnvironmentQuery } from "../state/query";
import { threadEnvironment, useEnvironmentThread } from "../state/threads";
import { vcsEnvironment } from "../state/vcs";
import { threadEnvironment } from "../state/threads";
import { useEnvironmentQuery } from "../state/query";
@@ -199,6 +207,7 @@ import {
isContextMenuPointerDown,
isTrailingDoubleClick,
resolveProjectStatusIndicator,
resolveThreadLastVisitedAt,
resolveThreadRowClassName,
resolveThreadStatusPill,
orderItemsByPreferredIds,
@@ -837,7 +846,8 @@ const SidebarThreadRow = memo(function SidebarThreadRow(props: {
);
const threadKey = scopedThreadKey(threadRef);
const forkParentThreadId = getSidebarForkParentThreadId(thread);
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
const openPrLink = useOpenPrLink();
const runningTerminalIds = useThreadRunningTerminalIds({
@@ -1785,6 +1795,43 @@ export default function Sidebar() {
});
const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{ path: string }>({
onCopy: ({ path }) => {
const updateSettings = useUpdateClientSettings();
const sidebarThreadPreviewCount = useClientSettings<SidebarThreadPreviewCount>(
(settings) => settings.sidebarThreadPreviewCount,
);
const router = useRouter();
const { isMobile, setOpenMobile } = useSidebar();
const markThreadUnread = useMarkThreadUnread();
const setProjectExpanded = useUiStateStore((state) => state.setProjectExpanded);
const toggleThreadSelection = useThreadSelectionStore((state) => state.toggleThread);
const rangeSelectTo = useThreadSelectionStore((state) => state.rangeSelectTo);
const clearSelection = useThreadSelectionStore((state) => state.clearSelection);
const removeFromSelection = useThreadSelectionStore((state) => state.removeFromSelection);
const setSelectionAnchor = useThreadSelectionStore((state) => state.setAnchor);
const { copyToClipboard: copyThreadIdToClipboard } = useCopyToClipboard<{
threadId: ThreadId;
}>({
onCopy: (ctx) => {
toastManager.add({
type: "success",
title: "Thread ID copied",
description: ctx.threadId,
});
},
onError: (error) => {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to copy thread ID",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
},
});
const { copyToClipboard: copyPathToClipboard } = useCopyToClipboard<{
path: string;
}>({
onCopy: (ctx) => {
toastManager.add({
type: "success",
title: "Path copied",
@@ -2299,9 +2346,12 @@ export default function Sidebar() {
useShallow((state) =>
projectThreads.map(
(thread) =>
state.threadLastVisitedAtById[
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))
] ?? null,
resolveThreadLastVisitedAt(
thread.lastVisitedAt,
state.threadLastVisitedAtById[
scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id))
],
) ?? null,
),
),
);
@@ -2539,9 +2589,8 @@ export default function Sidebar() {
);
if (clicked === "mark-unread") {
for (const threadKey of threadKeys) {
const thread = sidebarThreadByKeyRef.current.get(threadKey);
markThreadUnread(threadKey, thread?.latestRun?.completedAt);
for (const { threadRef } of selectedThreadEntries) {
markThreadUnread(threadRef);
}
})();
},
@@ -3116,7 +3165,7 @@ export default function Sidebar() {
}
if (clicked === "mark-unread") {
markThreadUnread(threadKey, thread.latestRun?.completedAt);
markThreadUnread(scopeThreadRef(thread.environmentId, thread.id));
return;
}
if (clicked === "copy-path") {
+211 -380
View File
@@ -13,7 +13,6 @@ import {
scopedThreadKey,
} from "@t3tools/client-runtime/environment";
import type { ScopedThreadRef, SidebarProjectGroupingMode } from "@t3tools/contracts";
import type { TimestampFormat } from "@t3tools/contracts/settings";
import {
AlarmClockIcon,
AlarmClockOffIcon,
@@ -85,7 +84,7 @@ import {
} from "../sidebarProjectGrouping";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
import { useThreadSelectionStore } from "../threadSelectionStore";
import { useThreadActions } from "../hooks/useThreadActions";
import { useMarkThreadUnread, useThreadActions } from "../hooks/useThreadActions";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { openCommandPalette } from "../commandPaletteBus";
import { startNewThreadFromContext } from "../lib/chatThreadActions";
@@ -108,7 +107,6 @@ import {
import { formatRelativeTimeLabel, parseTimestampDate } from "../timestampFormat";
import type { SidebarThreadSummary } from "../types";
import { cn } from "~/lib/utils";
import { buildThreadActionMenuItems } from "./threadActionMenu.logic";
import {
buildBulkTitleRegenerationContextMenuItem,
formatWorkingDurationLabel,
@@ -120,7 +118,7 @@ import {
resolveAdjacentThreadId,
resolveSettledTimestamp,
resolveSidebarV2Status,
searchSidebarThreadsByTitle,
resolveThreadLastVisitedAt,
resolveWorkingStartedAt,
shouldNavigateAfterProjectRemoval,
sortSidebarV2ProjectGroups,
@@ -344,15 +342,11 @@ function SnoozePopoverButton(props: {
open: boolean;
onOpenChange: (open: boolean) => void;
onSnooze: (preset: SnoozePreset) => void;
timestampFormat: TimestampFormat;
}) {
const { open, onOpenChange, onSnooze, timestampFormat } = props;
const { open, onOpenChange, onSnooze } = props;
// Presets resolve at open time so "In 1 hour" is relative to the click,
// not to when the row mounted.
const presets = useMemo(
() => (open ? resolveSnoozePresets(new Date(), timestampFormat) : []),
[open, timestampFormat],
);
const presets = useMemo(() => (open ? resolveSnoozePresets(new Date()) : []), [open]);
return (
<Popover open={open} onOpenChange={onOpenChange}>
<PopoverTrigger
@@ -404,12 +398,8 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
snoozeSupported: boolean;
// Renders the pin glyph. Pinned cards keep the full settle/snooze quick
// actions: settling clears the pin server-side, and snoozing hides the
// card until wake with the pin intact underneath. The glyph is also the
// in-row pin state cue (the pinned block has no header), so it always
// shows while pinned; it only becomes a clickable unpin quick-action once
// the pinning capability is confirmed, and stays a passive marker while
// the descriptor is not loaded. Pinning itself lives in the context menu.
pinningSupported: boolean;
// card until wake with the pin intact underneath. Pin/unpin themselves
// live in the context menu only.
isPinned: boolean;
// Compact wake countdown ("2h") for rows in the snoozed shelf.
snoozeWakeLabelText: string | null;
@@ -423,7 +413,6 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
projectCwd: string | null;
projectTitle: string | null;
providerEntryByInstanceId: ReadonlyMap<string, ProviderInstanceEntry>;
timestampFormat: TimestampFormat;
onThreadClick: (event: ReactMouseEvent, threadRef: ScopedThreadRef) => void;
onThreadActivate: (threadRef: ScopedThreadRef) => void;
onStartRename: (threadRef: ScopedThreadRef, title: string) => void;
@@ -437,8 +426,6 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
onUnsettle: (threadRef: ScopedThreadRef) => void;
onSnooze: (threadRef: ScopedThreadRef, preset: SnoozePreset) => void;
onUnsnooze: (threadRef: ScopedThreadRef) => void;
onUnpin: (threadRef: ScopedThreadRef) => void;
onAcknowledgeWoke: (threadRef: ScopedThreadRef, visitedAt: string) => void;
onChangeRequestState: (threadKey: string, state: "open" | "closed" | "merged" | null) => void;
}) {
const {
@@ -447,7 +434,6 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
onCancelRename,
onCommitRename,
onContextMenu,
onAcknowledgeWoke,
onRenameTitleChange,
onSettle,
onSnooze,
@@ -456,7 +442,6 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
onThreadClick,
onUnsettle,
onUnsnooze,
onUnpin,
renamingTitle,
thread,
variant,
@@ -467,8 +452,8 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
[thread.environmentId, thread.id],
);
const threadKey = scopedThreadKey(threadRef);
const isRegeneratingTitle = thread.titleRegeneration != null;
const lastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
const localLastVisitedAt = useUiStateStore((state) => state.threadLastVisitedAtById[threadKey]);
const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
const isSelected = useThreadSelectionStore((state) => state.selectedThreadKeys.has(threadKey));
const openPrLink = useOpenPrLink();
const runningTerminalIds = useThreadRunningTerminalIds({
@@ -478,40 +463,19 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
const terminalStatus = terminalStatusFromRunningIds(runningTerminalIds);
const terminalProcessCount = runningTerminalIds.length;
const gitCwd = thread.worktreePath ?? props.projectCwd;
const gitStatus = useEnvironmentQuery(
(thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
? vcsEnvironment.status({
environmentId: thread.environmentId,
input: { cwd: gitCwd },
})
: null,
);
const pr = resolveThreadPr({
threadBranch: thread.branch,
gitStatus: gitStatus.data,
});
const prState = pr?.state ?? null;
// Same semantics as v1 (never-visited counts as read): flipping the beta
// flag must not light up every historical thread as unread.
const isUnread = hasUnseenCompletion({ ...thread, lastVisitedAt });
const status = resolveSidebarV2Status(thread);
// A woken thread reappears at its original position (the sort is
// deliberately static), so the pill has to carry the weight. Snoozing is
// an explicit act, so the pill clears only when the user re-engages:
// reading a completion-triggered wake, clicking the pill, sending a
// message, settling, archiving — or finishing the work outright (merged
// or closed PR). Timer wakes survive a mere visit. An unparseable visit
// timestamp counts as never-visited — corrupt local data must not eat
// the wake signal.
// an explicit act, so unlike Done, a never-visited woke thread still
// shows the pill; visiting clears it. An unparseable visit timestamp
// counts as never-visited — corrupt local data must not eat the wake
// signal.
const lastVisitedDate = lastVisitedAt === undefined ? null : parseTimestampDate(lastVisitedAt);
const wokeAtDate = props.wokeAt === null ? null : parseTimestampDate(props.wokeAt);
const isWoke =
wokeAtDate !== null &&
(lastVisitedDate === null || lastVisitedDate < wokeAtDate) &&
prState !== "merged" &&
prState !== "closed";
const isWoke = wokeAtDate !== null && (lastVisitedDate === null || lastVisitedDate < wokeAtDate);
// In-flight rows (working, or waiting on approval/input) fade as a whole:
// there is nothing for the user to do yet, so prominence is reserved for
// rows that need a human — done (unread), read-but-unsettled, failed, and
@@ -519,8 +483,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
// findable. In-flight rows recede the same as read-ready ones (inbox-zero:
// working threads aren't your problem yet) — only the colored status label
// stands out.
const isInFlight =
status === "working" || status === "monitoring" || status === "approval" || status === "input";
const isInFlight = status === "working" || status === "approval" || status === "input";
const shouldRecede =
(status === "ready" || isInFlight) && !isUnread && !isWoke && !props.isActive && !isSelected;
// Status hues follow the system-wide convention set by sidebar v1 and the
@@ -531,64 +494,65 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
? {
label: "Working",
icon: "working" as const,
// No shimmer: a label that animates forever is noise in a sidebar
// full of them (and repaints every vsync on high-refresh displays).
// Working is a background state, so it rests at the dim end of what
// the old pulse cycled through; only the thread you have open gets
// the label at full strength.
className: cn("text-sky-600 dark:text-sky-400", !props.isActive && "opacity-75"),
className:
"animate-sidebar-working-text text-sky-600 motion-reduce:animate-none dark:text-sky-400",
}
: status === "monitoring"
: status === "approval"
? {
// Monitoring is calm background presence, not active progress
// (monitoring-pill D6), so it keeps the label at full strength.
label: "Monitoring",
label: "Approval",
icon: null,
className: "text-sky-600 dark:text-sky-400",
className: "text-amber-700 dark:text-amber-300",
}
: status === "approval"
: status === "input"
? {
label: "Approval",
label: "Input",
icon: null,
className: "text-amber-700 dark:text-amber-300",
className: "text-indigo-600 dark:text-indigo-300",
}
: status === "input"
: status === "failed"
? {
label: "Input",
label: "Failed",
icon: null,
className: "text-indigo-600 dark:text-indigo-300",
className: "text-red-700 dark:text-red-300",
}
: status === "failed"
: isWoke
? {
label: "Failed",
icon: null,
className: "text-red-700 dark:text-red-300",
label: "Woke",
icon: "woke" as const,
className: "text-amber-700 dark:text-amber-300",
}
: isWoke
: isUnread
? {
label: "Woke",
icon: "woke" as const,
className: "text-amber-700 dark:text-amber-300",
label: "Done",
icon: "done" as const,
className: "text-emerald-700 dark:text-emerald-300",
}
: isUnread
? {
label: "Done",
icon: "done" as const,
className: "text-emerald-700 dark:text-emerald-300",
}
: null;
const isWokeStatus = topStatus?.icon === "woke";
: null;
const gitCwd = thread.worktreePath ?? props.projectCwd;
const gitStatus = useEnvironmentQuery(
(thread.branch != null || thread.worktreePath !== null) && gitCwd !== null
? vcsEnvironment.status({
environmentId: thread.environmentId,
input: { cwd: gitCwd },
})
: null,
);
const branchMismatch = resolveLocalCheckoutBranchMismatch({
effectiveEnvMode: thread.worktreePath === null ? "local" : "worktree",
activeWorktreePath: thread.worktreePath,
activeThreadBranch: thread.branch,
currentGitBranch: gitStatus.data?.refName ?? null,
});
const pr = resolveThreadPr({
threadBranch: thread.branch,
gitStatus: gitStatus.data,
});
const prStatus = prStatusIndicator(pr, gitStatus.data?.sourceControlProvider);
const settledPrHoverClass = pr ? settledPrHoverColorClass(pr.state) : undefined;
// Report the PR state up: the parent partitions rows with effectiveSettled,
// and a merged/closed PR auto-settles a thread — data only rows have.
const prState = pr?.state ?? null;
useEffect(() => {
onChangeRequestState(threadKey, prState);
}, [onChangeRequestState, prState, threadKey]);
@@ -627,15 +591,6 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
},
[onThreadClick, threadRef],
);
const handleAcknowledgeWokeClick = useCallback(
(event: ReactMouseEvent) => {
event.preventDefault();
event.stopPropagation();
if (props.wokeAt === null) return;
onAcknowledgeWoke(threadRef, props.wokeAt);
},
[onAcknowledgeWoke, props.wokeAt, threadRef],
);
const handleContextMenu = useCallback(
(event: ReactMouseEvent) => {
event.preventDefault();
@@ -711,14 +666,6 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
},
[onUnsnooze, threadRef],
);
const handleUnpinClick = useCallback(
(event: ReactMouseEvent) => {
event.preventDefault();
event.stopPropagation();
onUnpin(threadRef);
},
[onUnpin, threadRef],
);
const handleSnoozePreset = useCallback(
(preset: SnoozePreset) => {
onSnooze(threadRef, preset);
@@ -791,7 +738,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
isUnread || isWoke
? "text-foreground"
: shouldRecede
? "text-secondary-label"
? "text-muted-foreground/80"
: status === "failed"
? "text-foreground/95"
: "text-foreground/90",
@@ -802,7 +749,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
? "text-foreground"
: isUnread
? "text-muted-foreground"
: "text-secondary-label/70",
: "text-muted-foreground/70",
),
isRegeneratingTitle && "opacity-[0.55]",
)}
@@ -822,8 +769,8 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
"shrink-0 text-xs tabular-nums hover:underline",
variant === "slim" && variantAction === "unsettle"
? props.isActive
? "text-secondary-label"
: cn("text-secondary-label transition-colors", settledPrHoverClass)
? "text-muted-foreground/70"
: cn("text-muted-foreground/35 transition-colors", settledPrHoverClass)
: prStatus.colorClass,
)}
aria-label={prStatus.tooltip}
@@ -892,12 +839,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
the time/jump label yields to the settle affordance. */}
{prBadge}
<span className="relative ml-auto flex h-6 min-w-8 shrink-0 items-center justify-end">
<span
className={cn(
"inline-flex justify-end tabular-nums text-secondary-label transition-opacity",
!isWoke && "group-hover/v2-row:opacity-0",
)}
>
<span className="inline-flex justify-end tabular-nums text-muted-foreground/55 transition-opacity group-hover/v2-row:opacity-0">
{variantAction === "unsnooze" && props.snoozeWakeLabelText !== null ? (
// Snoozed rows show when they come BACK, not when they were
// last touched — the return ticket is the row's whole story.
@@ -907,16 +849,14 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
) : isWoke ? (
// A wake can land straight in the settled tail (e.g. PR
// merged while snoozed); the signal must survive the trip.
<button
type="button"
aria-label="Dismiss Woke notification"
title="Dismiss Woke notification"
onClick={handleAcknowledgeWokeClick}
className="inline-flex cursor-pointer items-center gap-1 rounded-sm text-xs font-medium text-amber-700 outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring dark:text-amber-300"
<span
role="status"
aria-label="Woke from snooze"
className="inline-flex items-center gap-1 text-xs font-medium text-amber-700 dark:text-amber-300"
>
<AlarmClockIcon aria-hidden className="size-3" />
<span role="status">Woke</span>
</button>
Woke
</span>
) : (
<span className="text-xs">
{variantAction === "unsettle"
@@ -931,10 +871,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
type="button"
aria-label="Wake thread now"
onClick={handleUnsnoozeClick}
className={cn(
"pointer-events-none absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/v2-row:pointer-events-auto group-hover/v2-row:opacity-100",
isWoke && "group-hover/v2-row:static",
)}
className="absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover/v2-row:opacity-100"
>
<AlarmClockOffIcon className="size-3" />
</button>
@@ -944,10 +881,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
type="button"
aria-label="Un-settle thread"
onClick={handleUnsettleClick}
className={cn(
"pointer-events-none absolute inset-y-0 right-0 -mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/v2-row:pointer-events-auto group-hover/v2-row:opacity-100",
isWoke && "group-hover/v2-row:static",
)}
className="absolute inset-y-0 right-0 -mr-1 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-1.5 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover/v2-row:opacity-100"
>
<Undo2Icon className="mb-px size-3.5" />
</button>
@@ -956,10 +890,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
type="button"
aria-label="Settle thread"
onClick={handleSettleClick}
className={cn(
"pointer-events-none absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:pointer-events-auto focus-visible:opacity-100 group-hover/v2-row:pointer-events-auto group-hover/v2-row:opacity-100",
isWoke && "group-hover/v2-row:static",
)}
className="absolute inset-y-0 right-0 inline-flex cursor-pointer items-center gap-1 rounded-md bg-transparent px-2 text-xs text-muted-foreground opacity-0 transition-opacity hover:text-foreground focus-visible:opacity-100 group-hover/v2-row:opacity-100"
>
<CheckIcon className="size-3" />
</button>
@@ -1006,7 +937,7 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
{props.projectTitle ? (
<span
className={cn(
"min-w-0 flex-1 truncate text-secondary-label text-xs",
"min-w-0 flex-1 truncate text-xs text-muted-foreground/85",
shouldRecede ? "font-normal" : "font-medium",
)}
>
@@ -1016,79 +947,50 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
<span className="flex-1" />
)}
{props.isPinned ? (
props.pinningSupported ? (
<button
type="button"
aria-label="Unpin thread"
title="Unpin thread"
onClick={handleUnpinClick}
className="inline-flex cursor-pointer items-center rounded-sm text-muted-foreground/65 outline-none transition-colors hover:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
>
<PinIcon aria-hidden className="size-3 shrink-0" />
</button>
) : (
<PinIcon
aria-label="Pinned"
role="img"
className="size-3 shrink-0 text-muted-foreground/65"
/>
)
<PinIcon
aria-label="Pinned"
role="img"
className="size-3 shrink-0 text-muted-foreground/65"
/>
) : null}
{/* The visible state owns this slot's width: status at rest,
actions on hover/keyboard focus or while the popover is open. Keeping
the hidden state out of flow lets the project label reclaim
space without either state overlapping it. */}
<span className="group/v2-status-slot relative ml-auto flex h-5 min-w-8 shrink-0 items-stretch justify-end text-xs">
{/* Read-only status labels yield to the hover actions. Woke is
itself an action, so it stays pointer-enabled and visible
while the other controls appear beside it. */}
{/* pointer-events-none: while hovered this label is absolute
+ opacity-0, which paints it ABOVE the in-flow settle/snooze
buttons; without it the invisible label eats their clicks. */}
<span
className={cn(
isWokeStatus
? "pointer-events-auto"
: "pointer-events-none group-has-[:focus-visible]/v2-status-slot:absolute group-has-[:focus-visible]/v2-status-slot:right-0 group-has-[:focus-visible]/v2-status-slot:opacity-0 group-hover/v2-row:absolute group-hover/v2-row:right-0 group-hover/v2-row:opacity-0",
"self-center justify-self-end tabular-nums text-secondary-label transition-opacity",
snoozeMenuOpen && "pointer-events-none absolute right-0 opacity-0",
"pointer-events-none self-center justify-self-end tabular-nums text-muted-foreground/65 transition-opacity group-has-[:focus-visible]/v2-status-slot:absolute group-has-[:focus-visible]/v2-status-slot:right-0 group-has-[:focus-visible]/v2-status-slot:opacity-0 group-hover/v2-row:absolute group-hover/v2-row:right-0 group-hover/v2-row:opacity-0",
snoozeMenuOpen && "absolute right-0 opacity-0",
)}
>
{topStatus ? (
isWokeStatus ? (
<button
type="button"
aria-label="Dismiss Woke notification"
title="Dismiss Woke notification"
onClick={handleAcknowledgeWokeClick}
className={cn(
"inline-flex cursor-pointer items-center gap-1 rounded-sm font-medium outline-none hover:underline focus-visible:ring-2 focus-visible:ring-ring",
topStatus.className,
)}
>
<span
className={cn(
"inline-flex items-center gap-1 font-medium",
topStatus.className,
)}
>
{topStatus.icon === "working" ? (
<CircleDashedIcon aria-hidden className="size-4 shrink-0" />
) : topStatus.icon === "done" ? (
<CircleCheckIcon aria-hidden className="size-4 shrink-0" />
) : topStatus.icon === "woke" ? (
<AlarmClockIcon aria-hidden className="size-4 shrink-0" />
<span role="status">{topStatus.label}</span>
</button>
) : (
<span
className={cn(
"inline-flex items-center gap-1 font-medium",
topStatus.className,
)}
>
{topStatus.icon === "working" ? (
<CircleDashedIcon aria-hidden className="size-4 shrink-0" />
) : topStatus.icon === "done" ? (
<CircleCheckIcon aria-hidden className="size-4 shrink-0" />
) : null}
{/* The label alone is the live region: a role="status"
wrapper around the ticking duration would make
screen readers announce every second. */}
<span role="status">{topStatus.label}</span>
{status === "working" ? (
<span aria-hidden>
<WorkingDuration startedAt={resolveWorkingStartedAt(thread)} />
</span>
) : null}
</span>
)
) : null}
{/* The label alone is the live region: a role="status"
wrapper around the ticking duration would make
screen readers announce every second. */}
<span role="status">{topStatus.label}</span>
{status === "working" ? (
<span aria-hidden>
<WorkingDuration startedAt={resolveWorkingStartedAt(thread)} />
</span>
) : null}
</span>
) : (
threadTimeLabel(thread)
)}
@@ -1101,8 +1003,8 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
// would keep the controls pinned over the status label
// once the pointer moves away (e.g. after a failed
// settle) instead of cross-fading back.
"pointer-events-none absolute inset-y-0 right-0 flex items-stretch opacity-0 transition-opacity has-[:focus-visible]:pointer-events-auto has-[:focus-visible]:static has-[:focus-visible]:opacity-100 group-hover/v2-row:pointer-events-auto group-hover/v2-row:static group-hover/v2-row:opacity-100",
snoozeMenuOpen && "pointer-events-auto static opacity-100",
"absolute inset-y-0 right-0 flex items-stretch opacity-0 transition-opacity has-[:focus-visible]:static has-[:focus-visible]:opacity-100 group-hover/v2-row:static group-hover/v2-row:opacity-100",
snoozeMenuOpen && "static opacity-100",
)}
>
{showSnoozeButton ? (
@@ -1110,7 +1012,6 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
open={snoozeMenuOpen}
onOpenChange={setSnoozeMenuOpen}
onSnooze={handleSnoozePreset}
timestampFormat={props.timestampFormat}
/>
) : null}
{props.settlementSupported ? (
@@ -1136,19 +1037,8 @@ const SidebarV2Row = memo(function SidebarV2Row(props: {
</span>
) : null}
</div>
<div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-secondary-label text-xs">
{/* While working, the current plan step outranks the branch:
it's the one line that says what the thread is doing. */}
{status === "working" && thread.planProgress ? (
<span className="min-w-0 flex-1 truncate whitespace-nowrap">
{thread.planProgress.step}
{/* Completed count, matching the transcript chip's n/m. */}
<span className="text-icon-muted tabular-nums">
{" "}
{thread.planProgress.completedSteps}/{thread.planProgress.totalSteps}
</span>
</span>
) : thread.branch ? (
<div className="mt-0.5 flex min-w-0 items-center gap-1.5 text-xs text-muted-foreground/75">
{thread.branch ? (
<span className="min-w-0 flex-1 truncate whitespace-nowrap">{thread.branch}</span>
) : (
<span className="flex-1" />
@@ -1309,7 +1199,6 @@ export default function SidebarV2() {
const autoSettleAfterDays = useClientSettings((s) => s.sidebarAutoSettleAfterDays);
const confirmThreadDelete = useClientSettings((s) => s.confirmThreadDelete);
const sidebarProjectSortOrder = useClientSettings((s) => s.sidebarProjectSortOrder);
const timestampFormat = useClientSettings((s) => s.timestampFormat);
const projectGroupingSettings = useClientSettings(selectProjectGroupingSettings);
const {
settleThread,
@@ -1320,6 +1209,7 @@ export default function SidebarV2() {
unpinThread,
deleteThread,
} = useThreadActions();
const markThreadUnread = useMarkThreadUnread();
const updateThreadMetadata = useAtomCommand(threadEnvironment.updateMetadata, {
reportFailure: false,
});
@@ -1382,14 +1272,6 @@ export default function SidebarV2() {
const setSelectionAnchor = useThreadSelectionStore((s) => s.setAnchor);
const toggleThreadSelection = useThreadSelectionStore((s) => s.toggleThread);
const rangeSelectTo = useThreadSelectionStore((s) => s.rangeSelectTo);
const markThreadUnread = useUiStateStore((s) => s.markThreadUnread);
const markThreadVisited = useUiStateStore((s) => s.markThreadVisited);
const acknowledgeWoke = useCallback(
(threadRef: ScopedThreadRef, visitedAt: string) => {
markThreadVisited(scopedThreadKey(threadRef), visitedAt);
},
[markThreadVisited],
);
const routeTarget = useParams({
strict: false,
select: (params) => resolveThreadRouteTarget(params),
@@ -2227,40 +2109,6 @@ export default function SidebarV2() {
);
// One snooze per thread at a time — same double-dispatch guard as settle.
const snoozingThreadKeysRef = useRef(new Set<string>());
const performSnooze = useCallback(
async (
threadRef: ScopedThreadRef,
preset: SnoozePreset,
opts: { coSnoozingKeys?: ReadonlySet<string> } = {},
) => {
const threadKey = scopedThreadKey(threadRef);
if (snoozingThreadKeysRef.current.has(threadKey)) {
return { status: "skipped" } as const;
}
snoozingThreadKeysRef.current.add(threadKey);
try {
// Snoozing the open thread moves you forward, same as settle —
// both park the thread you're done with for now.
const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys);
const result = await snoozeThread(threadRef, preset.snoozedUntil);
if (result._tag === "Failure") {
// Never navigate away from a thread that did not snooze.
return isAtomCommandInterrupted(result)
? ({ status: "interrupted" } as const)
: ({ status: "failure", error: squashAtomCommandFailure(result) } as const);
}
// Only move forward if the user is still on the snoozed thread —
// a navigation made during the await wins over ours.
if (routeThreadKeyRef.current === threadKey) {
navigateAfterSnooze?.();
}
return { status: "success" } as const;
} finally {
snoozingThreadKeysRef.current.delete(threadKey);
}
},
[planForwardNavigation, snoozeThread],
);
const attemptSnooze = useCallback(
(
threadRef: ScopedThreadRef,
@@ -2268,35 +2116,52 @@ export default function SidebarV2() {
opts: { coSnoozingKeys?: ReadonlySet<string> } = {},
) => {
void (async () => {
const outcome = await performSnooze(threadRef, preset, opts);
if (outcome.status === "failure") {
const threadKey = scopedThreadKey(threadRef);
if (snoozingThreadKeysRef.current.has(threadKey)) return;
snoozingThreadKeysRef.current.add(threadKey);
try {
// Snoozing the open thread moves you forward, same as settle —
// both park the thread you're done with for now.
const navigateAfterSnooze = planForwardNavigation(threadKey, opts.coSnoozingKeys);
const result = await snoozeThread(threadRef, preset.snoozedUntil);
if (result._tag === "Failure") {
// Never navigate away from a thread that did not snooze.
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to snooze thread",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
return;
}
// Snooze hides the row, so the toast is the only confirmation —
// and the Undo is the escape hatch for a mis-click.
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to snooze thread",
description:
outcome.error instanceof Error ? outcome.error.message : "An error occurred.",
type: "success",
title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date())}`,
timeout: 5_000,
actionProps: {
children: "Undo",
onClick: () => attemptUnsnooze(threadRef),
},
}),
);
return;
// Only move forward if the user is still on the snoozed thread —
// a navigation made during the await wins over ours.
if (routeThreadKeyRef.current === threadKey) {
navigateAfterSnooze?.();
}
} finally {
snoozingThreadKeysRef.current.delete(threadKey);
}
if (outcome.status !== "success") return;
// Snooze hides the row, so the toast is the only confirmation —
// and the Undo is the escape hatch for a mis-click.
toastManager.add(
stackedThreadToast({
type: "success",
title: `Snoozed until ${snoozeWakeDescription(preset.snoozedUntil, new Date(), timestampFormat)}`,
timeout: 5_000,
actionProps: {
children: "Undo",
onClick: () => attemptUnsnooze(threadRef),
},
}),
);
})();
},
[attemptUnsnooze, performSnooze, timestampFormat],
[attemptUnsnooze, planForwardNavigation, snoozeThread],
);
const removeFromSelection = useThreadSelectionStore((s) => s.removeFromSelection);
@@ -2337,7 +2202,7 @@ export default function SidebarV2() {
supportedCount: titleRegenerationThreads.length,
actionableCount: regeneratableTitleThreads.length,
});
const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat);
const snoozePresets = resolveSnoozePresets(new Date());
const clicked = await settlePromise(() =>
api.contextMenu.show(
[
@@ -2370,55 +2235,12 @@ export default function SidebarV2() {
// Post-snooze navigation must skip threads snoozing in this same
// batch — they are all leaving the card block together.
const coSnoozingKeys = new Set(threadKeys);
clearSelection();
const outcomes = await Promise.all(
selectedThreads.map(async (thread) => {
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
const outcome = await performSnooze(threadRef, preset, { coSnoozingKeys });
return { outcome, threadRef };
}),
);
const snoozedThreadRefs = outcomes.flatMap(({ outcome, threadRef }) =>
outcome.status === "success" ? [threadRef] : [],
);
const failures = outcomes.flatMap(({ outcome }) =>
outcome.status === "failure" ? [outcome.error] : [],
);
if (snoozedThreadRefs.length > 0) {
const snoozedCount = snoozedThreadRefs.length;
const failedCount = failures.length;
toastManager.add(
stackedThreadToast({
type: failedCount > 0 ? "warning" : "success",
title:
failedCount > 0
? `Snoozed ${snoozedCount} of ${selectedThreads.length} threads`
: `Snoozed ${snoozedCount} thread${snoozedCount === 1 ? "" : "s"}`,
description:
failedCount > 0
? `${failedCount} thread${failedCount === 1 ? "" : "s"} couldn't be snoozed.`
: undefined,
timeout: 5_000,
actionProps: {
children: "Undo",
onClick: () => {
for (const threadRef of snoozedThreadRefs) attemptUnsnooze(threadRef);
},
},
}),
);
} else if (failures.length > 0) {
const firstError = failures[0];
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to snooze threads",
description:
firstError instanceof Error ? firstError.message : "An error occurred.",
}),
);
for (const thread of selectedThreads) {
attemptSnooze(scopeThreadRef(thread.environmentId, thread.id), preset, {
coSnoozingKeys,
});
}
clearSelection();
}
return;
}
@@ -2462,7 +2284,8 @@ export default function SidebarV2() {
if (clicked.value === "mark-unread") {
for (const threadKey of threadKeys) {
const thread = threadByKeyRef.current.get(threadKey);
markThreadUnread(threadKey, thread?.latestTurn?.completedAt);
if (!thread) continue;
markThreadUnread(scopeThreadRef(thread.environmentId, thread.id));
}
clearSelection();
return;
@@ -2514,12 +2337,9 @@ export default function SidebarV2() {
confirmThreadDelete,
deleteThread,
markThreadUnread,
performSnooze,
removeFromSelection,
serverConfigs,
attemptUnsnooze,
updateThreadMetadata,
timestampFormat,
],
);
@@ -2559,24 +2379,65 @@ export default function SidebarV2() {
const isSnoozed = snoozedThreadKeysRef.current.has(threadKey);
const isPinned = thread.pinnedAt != null;
// Presets resolve at menu-open time (same as the popover).
const snoozePresets = resolveSnoozePresets(new Date(), timestampFormat);
const snoozePresets = resolveSnoozePresets(new Date());
const clicked = await settlePromise(() =>
api.contextMenu.show(
buildThreadActionMenuItems({
branch: thread.branch ?? null,
isPinned,
isSettled,
isSnoozed,
canSnoozeNow: canSnooze(thread, { now: new Date().toISOString() }),
isRegeneratingTitle,
supports: {
settlement: supportsSettlement,
snooze: supportsSnooze,
pinning: supportsPinning,
titleRegeneration: supportsTitleRegeneration,
},
snoozePresets,
}),
[
...(thread.branch
? [
{
id: "new-thread-on-branch",
label: `New thread on ${thread.branch}`,
},
]
: []),
...(supportsPinning
? [
isPinned
? { id: "unpin", label: "Unpin thread" }
: { id: "pin", label: "Pin thread" },
]
: []),
// Both lifecycle actions stay available on pinned threads:
// settling clears the pin ("done" beats "keep on top"), and
// snoozing hides the card until wake with the pin intact.
...(supportsSettlement
? [
isSettled
? { id: "unsettle", label: "Un-settle thread" }
: { id: "settle", label: "Settle thread" },
]
: []),
...(supportsSnooze
? [
isSnoozed
? { id: "unsnooze", label: "Wake thread" }
: {
id: "snooze",
label: "Snooze",
disabled: !canSnooze(thread, { now: new Date().toISOString() }),
children: snoozePresets.map((preset) => ({
id: `snooze:${preset.id}`,
label: `${preset.label} (${preset.whenLabel})`,
})),
},
]
: []),
{ id: "rename", label: "Rename thread" },
...(supportsTitleRegeneration
? [
{
id: "regenerate-title",
label: isRegeneratingTitle ? "Regenerating…" : "Regenerate title",
disabled: isRegeneratingTitle,
},
]
: []),
{ id: "mark-unread", label: "Mark unread" },
{ id: "copy-path", label: "Copy path", icon: "copy" },
...(thread.branch ? [{ id: "copy-branch", label: "Copy branch", icon: "copy" }] : []),
{ id: "delete", label: "Delete", destructive: true, icon: "trash" },
],
position,
),
);
@@ -2649,25 +2510,7 @@ export default function SidebarV2() {
return;
}
case "mark-unread":
markThreadUnread(threadKey, thread.latestTurn?.completedAt);
return;
case "copy-path":
if (!threadWorkspacePath) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Path unavailable",
description: "This thread does not have a workspace path to copy.",
}),
);
return;
}
copyPathToClipboard(threadWorkspacePath, { path: threadWorkspacePath });
return;
case "copy-branch":
if (thread.branch) {
copyBranchToClipboard(thread.branch, { branch: thread.branch });
}
markThreadUnread(threadRef);
return;
case "delete": {
if (confirmThreadDelete) {
@@ -2717,7 +2560,6 @@ export default function SidebarV2() {
serverConfigs,
startThreadRename,
updateThreadMetadata,
timestampFormat,
],
);
@@ -2812,22 +2654,18 @@ export default function SidebarV2() {
openCommandPalette({ open: "new-thread-in" });
}, [isMobile, newThreadContext, projectGroups.length, setOpenMobile]);
// The button mirrors chat.new: in multi-project setups both route through
// the command palette's "New thread in..." picker, and in single-project
// setups both create immediately. chat.newLocal always creates directly, so
// it is only a correct label when chat.new is unbound.
// Same resolution as v1: prefer the local-thread binding, fall back to
// chat.new, no platform gating — web users have working shortcuts too.
const newThreadShortcutLabel =
shortcutLabelForCommand(keybindings, "chat.new") ??
shortcutLabelForCommand(keybindings, "chat.newLocal");
shortcutLabelForCommand(keybindings, "chat.newLocal") ??
shortcutLabelForCommand(keybindings, "chat.new");
return (
<>
<SidebarChromeHeader isElectron={isElectron} />
<SidebarContent
className="gap-0"
fixedHeader={
// Lifted above the stage backdrop, whose fade bleeds below the
// header and would otherwise paint across the search row's outline.
<SidebarGroup className="relative z-[1] gap-1 p-[var(--sidebar-content-inset)]">
<SidebarGroup className="gap-1 p-[var(--sidebar-content-inset)]">
<div className="flex items-center gap-1">
<div className="flex h-8 min-w-0 flex-1 items-center gap-2 rounded-md px-2 py-1.5 text-sm font-medium text-sidebar-muted-foreground hover:bg-sidebar-row-hover hover:text-sidebar-foreground">
<SearchIcon className="size-4 shrink-0 text-sidebar-muted-foreground/80" />
@@ -2962,7 +2800,7 @@ export default function SidebarV2() {
type="button"
aria-label={`Project actions for ${project.displayName}`}
title={`Project actions for ${project.displayName}`}
className="ml-auto inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-icon-muted outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
className="ml-auto inline-flex size-6 shrink-0 cursor-pointer items-center justify-center rounded-md text-muted-foreground/55 outline-none transition-colors hover:bg-accent hover:text-foreground focus-visible:bg-accent focus-visible:text-foreground focus-visible:ring-2 focus-visible:ring-ring"
onPointerDown={(event) => event.stopPropagation()}
onClick={(event) => {
void handleProjectActions(event, project);
@@ -3104,10 +2942,6 @@ export default function SidebarV2() {
serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadSnooze === true
}
pinningSupported={
serverConfigs.get(thread.environmentId)?.environment.capabilities
.threadPinning === true
}
isPinned={section === "pinned"}
snoozeWakeLabelText={
section === "snoozed" && thread.snoozedUntil != null
@@ -3134,7 +2968,6 @@ export default function SidebarV2() {
) ?? null
}
providerEntryByInstanceId={providerEntryByInstanceId}
timestampFormat={timestampFormat}
onThreadClick={handleThreadClick}
onThreadActivate={navigateToThread}
onStartRename={startThreadRename}
@@ -3148,8 +2981,6 @@ export default function SidebarV2() {
onUnsettle={attemptUnsettle}
onSnooze={attemptSnooze}
onUnsnooze={attemptUnsnooze}
onUnpin={attemptUnpin}
onAcknowledgeWoke={acknowledgeWoke}
onChangeRequestState={handleChangeRequestState}
/>
);
@@ -13,7 +13,11 @@ import { useThreadRunningTerminalIds } from "../state/terminalSessions";
import { vcsEnvironment } from "../state/vcs";
import { useUiStateStore } from "../uiStateStore";
import { resolveChangeRequestPresentation } from "../sourceControlPresentation";
import { resolveThreadStatusPill, type ThreadStatusPill } from "./Sidebar.logic";
import {
resolveThreadLastVisitedAt,
resolveThreadStatusPill,
type ThreadStatusPill,
} from "./Sidebar.logic";
import type { SidebarThreadSummary } from "../types";
import { formatWorktreePathForDisplay } from "../worktreeCleanup";
import { Tooltip, TooltipPopup, TooltipTrigger } from "./ui/tooltip";
@@ -231,9 +235,10 @@ export function ThreadStatusLabel({
*/
export function ThreadRowLeadingStatus({ thread }: { thread: SidebarThreadSummary }) {
const threadRef = scopeThreadRef(thread.environmentId, thread.id);
const lastVisitedAt = useUiStateStore(
const localLastVisitedAt = useUiStateStore(
(state) => state.threadLastVisitedAtById[scopedThreadKey(threadRef)],
);
const lastVisitedAt = resolveThreadLastVisitedAt(thread.lastVisitedAt, localLastVisitedAt);
const threadProject = useProject(
useMemo(
() => scopeProjectRef(thread.environmentId, thread.projectId),
+120 -57
View File
@@ -10,11 +10,8 @@ import type {
ScopedThreadRef,
ServerProvider,
ThreadId,
<<<<<<< HEAD
=======
RunId,
RuntimeRequestId,
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
} from "@t3tools/contracts";
import {
ProviderDriverKind,
@@ -199,6 +196,8 @@ import { toastManager } from "../ui/toast";
import {
BotIcon,
CircleAlertIcon,
ListTodoIcon,
LoaderCircleIcon,
PencilRulerIcon,
type LucideIcon,
LockIcon,
@@ -214,6 +213,7 @@ import {
deriveProviderInstanceEntries,
NO_PROVIDER_MODEL_SELECTION,
resolveProviderDriverKindForInstanceSelection,
resolveProviderCatalogAvailability,
resolveSelectableProviderInstanceEntry,
sortProviderInstanceEntries,
type ProviderInstanceEntry,
@@ -253,7 +253,7 @@ const runtimeModeConfig: Record<
},
auto: {
label: "Auto",
description: "Supported providers approve routine actions; others still ask.",
description: "An AI reviewer approves routine actions; risky ones still ask.",
icon: SparklesIcon,
},
"full-access": {
@@ -308,8 +308,12 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
showInteractionModeToggle: boolean;
interactionMode: ProviderInteractionMode;
runtimeMode: RuntimeMode;
showPlanToggle: boolean;
planSidebarLabel: string;
planSidebarOpen: boolean;
onToggleInteractionMode: () => void;
onRuntimeModeChange: (mode: RuntimeMode) => void;
onTogglePlanSidebar: () => void;
}) {
const runtimeModeOption = runtimeModeConfig[props.runtimeMode];
const RuntimeModeIcon = runtimeModeOption.icon;
@@ -317,6 +321,9 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
props.interactionMode === "plan"
? "Plan mode — click to return to normal build mode"
: "Default mode — click to enter plan mode";
const planSidebarTooltip = props.planSidebarOpen
? `Hide ${props.planSidebarLabel.toLowerCase()} sidebar`
: `Show ${props.planSidebarLabel.toLowerCase()} sidebar`;
const interactionModeToggle = props.showInteractionModeToggle ? (
<>
@@ -328,8 +335,8 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
className={cn(
"shrink-0 whitespace-nowrap",
props.interactionMode === "plan"
? "bg-accent text-accent-foreground hover:bg-accent/80"
: "text-secondary-label hover:text-foreground",
? "bg-blue-500/10 text-blue-400 hover:bg-blue-500/15 hover:text-blue-300"
: "text-muted-foreground/70 hover:text-foreground/80",
)}
type="button"
onClick={props.onToggleInteractionMode}
@@ -392,6 +399,36 @@ const ComposerFooterModeControls = memo(function ComposerFooterModeControls(prop
</Tooltip>
{interactionModeToggle}
{props.showPlanToggle ? (
<>
<Separator orientation="vertical" className="mx-0.5 hidden h-4 sm:block" />
<Tooltip>
<TooltipTrigger
render={
<ComposerControl
className={cn(
"shrink-0 whitespace-nowrap",
props.planSidebarOpen
? "bg-blue-500/10 text-blue-400 hover:bg-blue-500/15 hover:text-blue-300"
: "text-muted-foreground/70 hover:text-foreground/80",
)}
type="button"
onClick={props.onTogglePlanSidebar}
aria-label={planSidebarTooltip}
/>
}
>
<ComposerControlIcon
icon={ListTodoIcon}
className={props.planSidebarOpen ? "text-current opacity-100" : undefined}
/>
<span className="sr-only sm:not-sr-only">{props.planSidebarLabel}</span>
</TooltipTrigger>
<TooltipPopup side="top">{planSidebarTooltip}</TooltipPopup>
</Tooltip>
</>
) : null}
</>
);
});
@@ -431,7 +468,7 @@ const ComposerFooterPrimaryActions = memo(function ComposerFooterPrimaryActions(
/>
) : null}
{props.isPreparingWorktree ? (
<span className="text-secondary-label text-xs">Preparing worktree...</span>
<span className="text-muted-foreground/70 text-xs">Preparing worktree...</span>
) : null}
{props.isRunning && props.hasSendableContent ? (
<span className="hidden text-[11px] text-muted-foreground/70 sm:inline">
@@ -552,18 +589,11 @@ export interface ChatComposerProps {
// Plan
showPlanFollowUpPrompt: boolean;
<<<<<<< HEAD
activeProposedPlan: Thread["proposedPlans"][number] | null;
<<<<<<< HEAD
=======
=======
activeProposedPlan: LatestProposedPlanState | null;
>>>>>>> d454b3880e (Retire V1 client orchestration parity)
activePlan: { runId?: RunId | null } | null;
sidebarProposedPlan: { runId?: RunId | null } | null;
planSidebarLabel: string;
planSidebarOpen: boolean;
>>>>>>> 79c36e6204 (Complete orchestration V2 frontend cutover)
// Mode
runtimeMode: RuntimeMode;
@@ -571,6 +601,7 @@ export interface ChatComposerProps {
// Provider / model
lockedProvider: ProviderDriverKind | null;
providerCatalogLoaded: boolean;
providerStatuses: ServerProvider[];
activeProjectDefaultModelSelection: ModelSelection | null | undefined;
activeThreadModelSelection: ModelSelection | null | undefined;
@@ -620,6 +651,7 @@ export interface ChatComposerProps {
toggleInteractionMode: () => void;
handleRuntimeModeChange: (mode: RuntimeMode) => void;
handleInteractionModeChange: (mode: ProviderInteractionMode) => void;
togglePlanSidebar: () => void;
focusComposer: () => void;
scheduleComposerFocus: () => void;
@@ -662,9 +694,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
respondingRequestIds,
showPlanFollowUpPrompt,
activeProposedPlan,
activePlan,
sidebarProposedPlan,
planSidebarLabel,
planSidebarOpen,
runtimeMode,
interactionMode,
lockedProvider,
providerCatalogLoaded,
providerStatuses,
activeProjectDefaultModelSelection,
activeThreadModelSelection,
@@ -694,6 +731,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
toggleInteractionMode,
handleRuntimeModeChange,
handleInteractionModeChange,
togglePlanSidebar,
focusComposer,
scheduleComposerFocus,
setThreadError,
@@ -858,7 +896,27 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
() => providerInstanceEntries.find((entry) => entry.instanceId === selectedInstanceId),
[providerInstanceEntries, selectedInstanceId],
);
const noProviderAvailable = selectedProviderEntry === undefined;
const providerCatalogAvailability = resolveProviderCatalogAvailability({
catalogLoaded: providerCatalogLoaded,
entries: providerInstanceEntries,
selectedEntry: selectedProviderEntry,
});
const noProviderAvailable = providerCatalogAvailability !== "ready";
const providerAvailabilityCopy =
providerCatalogAvailability === "loading"
? {
label: "Loading providers…",
placeholder: "Providers are still loading",
}
: providerCatalogAvailability === "unconfigured"
? {
label: "No providers configured",
placeholder: "Enable a provider in Settings to send a message",
}
: {
label: "Providers unavailable",
placeholder: "No configured provider is currently available",
};
// The driver kind follows the instance that will actually run the turn,
// which can differ from the persisted selection when that selection is
// disabled.
@@ -908,16 +966,14 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
const selectedPromptEffort = composerProviderState.promptEffort;
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
// Plan mode is a legacy feature behind Settings → Beta. With the flag off,
// ChatView forces the effective mode to "default", so hiding the toggle
// can't trap anyone in plan mode.
const planModeUiEnabled = settings.planModeEnabled;
const composerProviderControls = useMemo(
() => ({
showInteractionModeToggle:
planModeUiEnabled && getProviderInteractionModeToggle(providerStatuses, selectedProvider),
showInteractionModeToggle: getProviderInteractionModeToggle(
providerStatuses,
selectedProvider,
),
}),
[planModeUiEnabled, providerStatuses, selectedProvider],
[providerStatuses, selectedProvider],
);
const selectedModelSelection = useMemo<ModelSelection>(
() => createModelSelection(selectedInstanceId, selectedModel, selectedModelOptionsForDispatch),
@@ -1079,24 +1135,20 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
label: "/model",
description: "Switch response model for this thread",
},
...(planModeUiEnabled
? ([
{
id: "slash:plan",
type: "slash-command",
command: "plan",
label: "/plan",
description: "Switch this thread into plan mode",
},
{
id: "slash:default",
type: "slash-command",
command: "default",
label: "/default",
description: "Switch this thread back to normal build mode",
},
] as const)
: []),
{
id: "slash:plan",
type: "slash-command",
command: "plan",
label: "/plan",
description: "Switch this thread into plan mode",
},
{
id: "slash:default",
type: "slash-command",
command: "default",
label: "/default",
description: "Switch this thread back to normal build mode",
},
] satisfies ReadonlyArray<Extract<ComposerCommandItem, { type: "slash-command" }>>;
const providerSlashCommandItems = (selectedProviderStatus?.slashCommands ?? []).map(
(command) => ({
@@ -1131,13 +1183,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
);
}
return [];
}, [
composerTrigger,
planModeUiEnabled,
selectedProvider,
selectedProviderStatus,
workspaceEntries.entries,
]);
}, [composerTrigger, selectedProvider, selectedProviderStatus, workspaceEntries.entries]);
const composerMenuOpen = Boolean(composerTrigger);
const composerMenuSearchKey = composerTrigger
@@ -1177,6 +1223,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
isComposerCollapsedMobile && !isComposerApprovalState && pendingUserInputs.length === 0;
const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null;
const showPlanSidebarToggle = Boolean(activePlan || sidebarProposedPlan || planSidebarOpen);
const composerFooterActionLayoutKey = useMemo(() => {
if (activePendingProgress) {
return `pending:${activePendingProgress.questionIndex}:${activePendingProgress.isLastQuestion}:${activePendingIsResponding}`;
@@ -1894,7 +1941,6 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
event: KeyboardEvent,
) => {
if (key === "Tab" && event.shiftKey) {
if (!planModeUiEnabled) return false;
toggleInteractionMode();
return true;
}
@@ -2796,7 +2842,9 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
type="button"
className={cn(
"min-w-0 flex-1 truncate bg-transparent py-1.5 text-left text-sm",
activePendingProgress?.customAnswer ? "text-foreground" : "text-placeholder",
activePendingProgress?.customAnswer
? "text-foreground"
: "text-muted-foreground/60",
!activePendingProgress?.activeQuestion?.multiSelect && "px-3 py-2",
)}
onPointerDown={(event) => event.preventDefault()}
@@ -2841,7 +2889,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
"min-w-0 flex-1 truncate bg-transparent p-0 text-left text-[14px] focus:outline-none",
(activePendingProgress ? activePendingProgress.customAnswer : prompt.trim())
? "text-foreground"
: "text-placeholder",
: "text-muted-foreground/35",
)}
onPointerDown={(event) => event.preventDefault()}
onClick={expandMobileComposer}
@@ -2851,11 +2899,13 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
? activePendingProgress.customAnswer ||
"Type your own answer, or leave this blank to use the selected option"
: prompt.trim() ||
(noProviderAvailable ? "Enable a provider in Settings" : "Ask anything...")}
(noProviderAvailable
? providerAvailabilityCopy.placeholder
: "Ask anything...")}
</button>
<button
type="button"
className="flex size-8 shrink-0 items-center justify-center rounded-full bg-message-action text-message-action-foreground hover:bg-message-action-hover disabled:opacity-30"
className="flex size-8 shrink-0 items-center justify-center rounded-full bg-primary/90 text-primary-foreground disabled:opacity-30"
disabled={collapsedComposerPrimaryActionDisabled}
aria-label={collapsedComposerPrimaryActionLabel}
onPointerDown={(event) => event.preventDefault()}
@@ -3005,7 +3055,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
/>
</button>
) : (
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-secondary-label">
<div className="flex h-full w-full items-center justify-center px-1 text-center text-[10px] text-muted-foreground/70">
{image.name}
</div>
)}
@@ -3077,7 +3127,7 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
: projectSelectionRequired
? "Choose a project above to start a thread"
: noProviderAvailable
? "Enable a provider in Settings to send a message"
? providerAvailabilityCopy.placeholder
: phase === "disconnected"
? "Ask for follow-up changes or attach images"
: "Ask anything, @tag files/folders, $use skills, or / for commands"
@@ -3144,10 +3194,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
variant="ghost"
disabled
data-chat-provider-unavailable="true"
className="shrink-0 gap-2 px-2 text-secondary-label sm:px-3"
data-chat-provider-availability={providerCatalogAvailability}
className="shrink-0 gap-2 px-2 text-muted-foreground/70 sm:px-3"
>
<CircleAlertIcon className="size-4" />
No provider available
{providerCatalogAvailability === "loading" ? (
<LoaderCircleIcon className="size-4" />
) : (
<CircleAlertIcon className="size-4" />
)}
{providerAvailabilityCopy.label}
</Button>
) : (
<ProviderModelPicker
@@ -3178,11 +3233,15 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
{isComposerFooterCompact ? (
<CompactComposerControlsMenu
activePlan={showPlanSidebarToggle}
interactionMode={interactionMode}
planSidebarLabel={planSidebarLabel}
planSidebarOpen={planSidebarOpen}
runtimeMode={runtimeMode}
showInteractionModeToggle={composerProviderControls.showInteractionModeToggle}
traitsMenuContent={providerTraitsMenuContent}
onToggleInteractionMode={toggleInteractionMode}
onTogglePlanSidebar={togglePlanSidebar}
onRuntimeModeChange={handleRuntimeModeChange}
/>
) : (
@@ -3197,8 +3256,12 @@ export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps)
showInteractionModeToggle={composerProviderControls.showInteractionModeToggle}
interactionMode={interactionMode}
runtimeMode={runtimeMode}
showPlanToggle={showPlanSidebarToggle}
planSidebarLabel={planSidebarLabel}
planSidebarOpen={planSidebarOpen}
onToggleInteractionMode={toggleInteractionMode}
onRuntimeModeChange={handleRuntimeModeChange}
onTogglePlanSidebar={togglePlanSidebar}
/>
</>
)}
@@ -783,6 +783,147 @@ describe("MessagesTimeline", () => {
expect(markup).not.toContain("Structured details");
});
it("renders context handoffs as from → to model endpoints instead of the summary", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const providerStatuses = [
{
instanceId: "codex_personal",
driver: "codex",
enabled: true,
installed: true,
version: null,
status: "ready",
auth: {},
checkedAt: MESSAGE_CREATED_AT,
models: [{ slug: "gpt-5.6-sol", name: "GPT 5.6 Sol", isCustom: false, capabilities: null }],
slashCommands: [],
skills: [],
},
{
instanceId: "claudeAgent",
driver: "claudeAgent",
enabled: true,
installed: true,
version: null,
status: "ready",
auth: {},
checkedAt: MESSAGE_CREATED_AT,
models: [
{ slug: "claude-fable-5", name: "Claude Fable 5", isCustom: false, capabilities: null },
],
slashCommands: [],
skills: [],
},
] as never;
const buildHandoffEntry = (item: Record<string, unknown>) => ({
id: "handoff-1",
kind: "event" as const,
createdAt: MESSAGE_CREATED_AT,
projectedItem: {
position: 0,
visibility: "local",
sourceThreadId: "thread-1",
sourceItemId: "handoff-1",
item: {
id: "handoff-1",
threadId: "thread-1",
runId: "run-2",
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 0,
status: "completed",
title: "Provider handoff",
startedAt: null,
completedAt: null,
updatedAt: {},
type: "handoff",
contextHandoffId: "handoff-1",
fromProviderThreadIds: ["provider-thread-1"],
toProviderThreadId: "provider-thread-2",
strategy: "full_thread_summary",
summary: "Full conversation context for provider handoff.",
...item,
},
} as never,
});
const markup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
providerStatuses={providerStatuses}
timelineEntries={[
buildHandoffEntry({
fromProviderInstanceIds: ["codex_personal"],
toProviderInstanceId: "claudeAgent",
fromModelSelections: [{ instanceId: "codex_personal", model: "gpt-5.6-sol" }],
toModel: "claude-fable-5",
}),
]}
/>,
);
expect(markup).toContain("Context handoff");
expect(markup).toContain("GPT 5.6 Sol");
expect(markup).toContain("Claude Fable 5");
expect(markup).not.toContain("Full conversation context");
// Items persisted before models were stamped recover them from the
// projection runs: the handoff's run is the target, the newest earlier
// run per source instance is the origin.
const legacyRuns = [
{
id: "run-1",
ordinal: 1,
providerInstanceId: "codex_personal",
modelSelection: { instanceId: "codex_personal", model: "gpt-5.6-sol" },
},
{
id: "run-2",
ordinal: 2,
providerInstanceId: "claudeAgent",
modelSelection: { instanceId: "claudeAgent", model: "claude-fable-5" },
},
] as never;
const legacyMarkup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
providerStatuses={providerStatuses}
runs={legacyRuns}
timelineEntries={[
buildHandoffEntry({
fromProviderInstanceIds: ["codex_personal"],
toProviderInstanceId: "claudeAgent",
}),
]}
/>,
);
expect(legacyMarkup).toContain("GPT 5.6 Sol");
expect(legacyMarkup).toContain("Claude Fable 5");
expect(legacyMarkup).not.toContain("Full conversation context");
// Without run data either (e.g. cross-thread items) it falls back to
// provider names.
const bareMarkup = renderToStaticMarkup(
<MessagesTimeline
{...buildProps()}
providerStatuses={providerStatuses}
timelineEntries={[
buildHandoffEntry({
fromProviderInstanceIds: ["codex_personal"],
toProviderInstanceId: "claudeAgent",
}),
]}
/>,
);
expect(bareMarkup).toContain("Codex Personal");
expect(bareMarkup).not.toContain("Full conversation context");
});
it("renders created threads as linked cards outside the work log", async () => {
const { MessagesTimeline } = await import("./MessagesTimeline");
const markup = renderToStaticMarkup(
+103 -243
View File
@@ -1,9 +1,11 @@
import {
type EnvironmentId,
type MessageId,
type OrchestrationV2Run,
type OrchestrationV2TurnItem,
type RunAttemptId,
type ScopedThreadRef,
type ServerProvider,
type ServerProviderSkill,
type RunId,
type ThreadId,
@@ -25,10 +27,12 @@ import {
type MouseEvent,
type ReactNode,
} from "react";
import { flushSync } from "react-dom";
import { LegendList, type LegendListRef } from "@legendapp/list/react";
import { FileDiff } from "@pierre/diffs/react";
import {
type TimelineEntry,
providerErrorPresentation,
workEntryIndicatesToolFailure,
workEntryIndicatesToolNeutralStatus,
workEntryIndicatesToolSuccess,
@@ -137,6 +141,10 @@ interface TimelineRowSharedState {
resolvedTheme: "light" | "dark";
workspaceRoot: string | undefined;
skills: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
/** Provider snapshots for resolving handoff endpoints to icons + model names. */
providerStatuses: ReadonlyArray<ServerProvider>;
/** Projection runs, for recovering handoff models on legacy items. */
runs: ReadonlyArray<OrchestrationV2Run>;
activeThreadEnvironmentId: EnvironmentId;
onRevertUserMessage: (messageId: MessageId) => void;
onImageExpand: (preview: ExpandedImagePreview) => void;
@@ -159,61 +167,23 @@ interface TimelineRowActivityState {
isRevertingCheckpoint: boolean;
activeTurnInProgress: boolean;
latestTurnId: TurnId | null;
/** Current plan step label for the working row, when the turn has a plan. */
workingStepLabel: string | null;
}
const TimelineRowCtx = createContext<TimelineRowSharedState>(null!);
const TimelineRowActivityCtx = createContext<TimelineRowActivityState>(null!);
const TIMELINE_LIST_HEADER = <div className="h-3 sm:h-4" />;
const TIMELINE_LIST_FADE_HEADER = <div className="h-10 sm:h-12" />;
// Header row shown when older turns exist beyond the loaded window. Plain
// button, no spinner animation; the label change is the loading indicator.
function TimelineLoadEarlierHeader({
loading,
onLoadEarlier,
fade,
}: {
loading: boolean;
onLoadEarlier: () => void;
fade: boolean;
}) {
return (
<div className={fade ? "pt-10 sm:pt-12" : "pt-3 sm:pt-4"}>
<div className="mx-auto w-full max-w-3xl pb-2">
<button
type="button"
onClick={onLoadEarlier}
disabled={loading}
className="w-full py-1.5 text-xs text-muted-foreground/60 hover:text-foreground disabled:cursor-default"
>
{loading ? "Loading earlier turns…" : "Load earlier turns"}
</button>
</div>
</div>
);
}
const TIMELINE_LIST_FOOTER = <div className="h-3 sm:h-4" />;
const EMPTY_TIMELINE_SKILLS: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">> = [];
const TIMELINE_MAINTAIN_SCROLL_AT_END = {
animated: false,
on: {
dataChange: true,
itemLayout: true,
layout: true,
},
} as const;
const EMPTY_TIMELINE_PROVIDERS: ReadonlyArray<ServerProvider> = [];
const EMPTY_TIMELINE_RUNS: ReadonlyArray<OrchestrationV2Run> = [];
// ---------------------------------------------------------------------------
// Props (public API)
// ---------------------------------------------------------------------------
interface MessagesTimelineProps {
agentPanelModel?: AgentPanelModel;
onOpenAgents?: () => void;
isWorking: boolean;
workingStepLabel?: string | null;
activeTurnInProgress: boolean;
activeTurnStartedAt: string | null;
listRef: React.RefObject<LegendListRef | null>;
@@ -245,22 +215,16 @@ interface MessagesTimelineProps {
timestampFormat: TimestampFormat;
workspaceRoot: string | undefined;
skills?: ReadonlyArray<Pick<ServerProviderSkill, "name" | "displayName">>;
providerStatuses?: ReadonlyArray<ServerProvider>;
runs?: ReadonlyArray<OrchestrationV2Run>;
anchorMessageId: MessageId | null;
onAnchorReady: (messageId: MessageId, anchorIndex: number) => void;
onAnchorSizeChanged: (messageId: MessageId, size: number) => void;
contentInsetEndAdjustment: number;
/**
* Whether the timeline should keep pinning to the live edge as content
* grows. Off while the user is reading history; LegendList's own
* maintainScrollAtEnd would otherwise re-pin regardless of ChatView's
* scroll-mode refs whenever the user drifts near the bottom.
*/
liveFollowEnabled: boolean;
onIsAtEndChange: (isAtEnd: boolean) => void;
onManualNavigation: () => void;
hideEmptyPlaceholder?: boolean;
topFadeEnabled?: boolean;
/** Non-null when older turns exist beyond the loaded window. */
loadEarlier?: { readonly loading: boolean; readonly onLoadEarlier: () => void } | null;
}
// ---------------------------------------------------------------------------
@@ -269,11 +233,8 @@ interface MessagesTimelineProps {
export const MessagesTimeline = memo(function MessagesTimeline({
isWorking,
workingStepLabel = null,
activeTurnInProgress,
activeTurnStartedAt,
agentPanelModel = EMPTY_AGENT_PANEL_MODEL,
onOpenAgents = NOOP_OPEN_AGENTS,
listRef,
timelineEntries,
latestRun,
@@ -294,15 +255,16 @@ export const MessagesTimeline = memo(function MessagesTimeline({
timestampFormat,
workspaceRoot,
skills = EMPTY_TIMELINE_SKILLS,
providerStatuses = EMPTY_TIMELINE_PROVIDERS,
runs = EMPTY_TIMELINE_RUNS,
anchorMessageId,
onAnchorReady,
onAnchorSizeChanged,
contentInsetEndAdjustment,
liveFollowEnabled,
onIsAtEndChange,
onManualNavigation,
hideEmptyPlaceholder = false,
topFadeEnabled = false,
loadEarlier = null,
}: MessagesTimelineProps) {
const [expandedRunIds, setExpandedRunIds] = useState<ReadonlySet<RunId>>(new Set());
const [expandedAttemptIds, setExpandedAttemptIds] = useState<ReadonlySet<RunAttemptId>>(
@@ -325,28 +287,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
} else {
next.add(runId);
}
if (disclosureSettleSecondFrameRef.current !== null) {
cancelAnimationFrame(disclosureSettleSecondFrameRef.current);
}
};
}, []);
const suspendEndScrollMaintenanceForDisclosure = useCallback((anchorKey: string) => {
disclosureAnchorKeyRef.current = anchorKey;
setDisclosureToggleSettling(true);
if (disclosureSettleFrameRef.current !== null) {
cancelAnimationFrame(disclosureSettleFrameRef.current);
}
if (disclosureSettleSecondFrameRef.current !== null) {
cancelAnimationFrame(disclosureSettleSecondFrameRef.current);
}
disclosureSettleFrameRef.current = requestAnimationFrame(() => {
disclosureSettleSecondFrameRef.current = requestAnimationFrame(() => {
disclosureAnchorKeyRef.current = null;
setDisclosureToggleSettling(false);
disclosureSettleFrameRef.current = null;
disclosureSettleSecondFrameRef.current = null;
});
return next;
});
}, []);
const onToggleAttemptFold = useCallback((attemptId: RunAttemptId) => {
@@ -370,23 +311,23 @@ export const MessagesTimeline = memo(function MessagesTimeline({
secondFrameId = window.requestAnimationFrame(() => {
setFoldToggleSettling(false);
});
if (anchorBottomBeforeToggle === null || !anchorElement) {
return;
}
const delta = anchorElement.getBoundingClientRect().bottom - anchorBottomBeforeToggle;
if (Math.abs(delta) < 0.5) {
return;
}
const list = listRef.current;
const currentScroll = list?.getState?.().scroll;
if (list && typeof currentScroll === "number") {
list.scrollToOffset({ offset: currentScroll + delta, animated: false });
}
},
[suspendEndScrollMaintenanceForDisclosure],
);
const onToggleWorkGroup = useCallback(
(groupId: string, anchorKey: string) => {
suspendEndScrollMaintenanceForDisclosure(anchorKey);
setExpandedWorkGroupIds((existing) => {
const next = new Set(existing);
if (next.has(groupId)) {
next.delete(groupId);
} else {
next.add(groupId);
}
return next;
});
},
[suspendEndScrollMaintenanceForDisclosure],
[listRef],
);
// An in-session interrupt leaves its turn expanded so the user keeps their
@@ -456,16 +397,26 @@ export const MessagesTimeline = memo(function MessagesTimeline({
},
[anchorMessageId, onAnchorReady],
);
const handleAnchorSizeChanged = useCallback(
(size: number) => {
if (anchorMessageId !== null) {
onAnchorSizeChanged(anchorMessageId, size);
}
},
[anchorMessageId, onAnchorSizeChanged],
);
const anchoredEndSpace = useMemo(() => {
const config = resolveChatListAnchoredEndSpace(rows, anchorMessageId, (row) =>
row.kind === "message" ? row.message.id : null,
);
return config ? { ...config, onReady: handleAnchorReady } : undefined;
}, [anchorMessageId, handleAnchorReady, rows]);
return config
? { ...config, onReady: handleAnchorReady, onSizeChanged: handleAnchorSizeChanged }
: undefined;
}, [anchorMessageId, handleAnchorReady, handleAnchorSizeChanged, rows]);
const handleScroll = useCallback(() => {
const state = listRef.current?.getState?.();
const isAtEnd = resolveTimelineIsAtEnd(state, contentInsetEndAdjustment);
const isAtEnd = resolveTimelineIsAtEnd(state);
if (isAtEnd !== undefined) {
onIsAtEndChange(isAtEnd);
}
@@ -491,7 +442,7 @@ export const MessagesTimeline = memo(function MessagesTimeline({
strip.dataset.inView = inView ? "true" : "false";
}
}, [contentInsetEndAdjustment, listRef, minimapItems, minimapStripMap, onIsAtEndChange]);
}, [listRef, minimapItems, minimapStripMap, onIsAtEndChange]);
useEffect(() => {
const frame = requestAnimationFrame(handleScroll);
@@ -532,6 +483,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
resolvedTheme,
workspaceRoot,
skills,
providerStatuses,
runs,
activeThreadEnvironmentId,
onRevertUserMessage,
onImageExpand,
@@ -549,6 +502,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
resolvedTheme,
workspaceRoot,
skills,
providerStatuses,
runs,
activeThreadEnvironmentId,
onRevertUserMessage,
onImageExpand,
@@ -566,9 +521,8 @@ export const MessagesTimeline = memo(function MessagesTimeline({
isRevertingCheckpoint,
activeTurnInProgress,
latestTurnId: latestTurn?.turnId ?? null,
workingStepLabel,
}),
[activeTurnInProgress, isRevertingCheckpoint, isWorking, latestTurn?.turnId, workingStepLabel],
[activeTurnInProgress, isRevertingCheckpoint, isWorking, latestTurn?.turnId],
);
const listHeader = useMemo(
() =>
@@ -606,7 +560,9 @@ export const MessagesTimeline = memo(function MessagesTimeline({
if (rows.length === 0 && !isWorking && parentThreadLink === null) {
return (
<div className="flex h-full items-center justify-center">
<p className="text-placeholder text-sm">Send a message to start the conversation.</p>
<p className="text-sm text-muted-foreground/30">
Send a message to start the conversation.
</p>
</div>
);
}
@@ -1050,7 +1006,7 @@ function UserTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "message"
/>
</button>
) : (
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-secondary-label text-[11px]">
<div className="flex min-h-[72px] items-center justify-center px-2 py-3 text-center text-[11px] text-muted-foreground/70">
{image.name}
</div>
)}
@@ -1360,13 +1316,19 @@ function v2EventPresentation(item: OrchestrationV2TurnItem): {
readonly icon: LucideIcon;
} {
switch (item.type) {
case "error":
case "error": {
const presentation = providerErrorPresentation(item);
return {
label: item.title?.trim() || "Provider error",
detail: item.failure.message,
tone: "danger",
...presentation,
tone:
item.status === "completed"
? "success"
: item.status === "running"
? "warning"
: "danger",
icon: CircleAlertIcon,
};
}
case "run_interrupt_request":
return {
label: "Interrupt requested",
@@ -1451,6 +1413,8 @@ function V2EventTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "event"
item={item}
createdAt={row.createdAt}
timestampFormat={ctx.timestampFormat}
providerStatuses={ctx.providerStatuses}
runs={ctx.runs}
onOpenThread={ctx.onOpenThread}
/>
);
@@ -1534,16 +1498,15 @@ function V2EventTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "event"
}
function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "working" }> }) {
const { workingStepLabel } = use(TimelineRowActivityCtx);
return (
<div className="py-0.5 pl-1.5">
<div className="flex min-w-0 items-center gap-2 pt-1 text-secondary-label text-[11px] tabular-nums">
<div className="flex items-center gap-2 pt-1 text-[11px] text-muted-foreground/70 tabular-nums">
<span className="inline-flex items-center gap-[3px]">
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-status-pulse" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-status-pulse [animation-delay:200ms]" />
<span className="h-1 w-1 rounded-full bg-muted-foreground/30 animate-status-pulse [animation-delay:400ms]" />
</span>
<span className="shrink-0">
<span>
{row.createdAt ? (
<>
Working for <WorkingTimer createdAt={row.createdAt} />
@@ -1552,9 +1515,6 @@ function WorkingTimelineRow({ row }: { row: Extract<TimelineRow, { kind: "workin
"Working..."
)}
</span>
{workingStepLabel ? (
<span className="min-w-0 truncate text-muted-foreground/55">· {workingStepLabel}</span>
) : null}
</div>
</div>
);
@@ -1616,7 +1576,9 @@ const WorkGroupSection = memo(function WorkGroupSection({
return (
<section className="-mx-1 space-y-0.5 px-1 py-0.5" aria-label={groupLabel}>
{!onlyToolEntries && (
<p className="px-0.5 pb-0.5 font-medium text-secondary-label text-[11px]">{groupLabel}</p>
<p className="px-0.5 pb-0.5 font-medium text-[11px] text-muted-foreground/65">
{groupLabel}
</p>
)}
<div className="space-y-px">
{nonEmptyEntries.map((workEntry) => (
@@ -1650,9 +1612,13 @@ function WorkGroupToggleTimelineRow({
type="button"
className="flex w-full cursor-pointer items-center gap-1.5 rounded-md px-0.5 py-0.5 text-left text-[12px] leading-5 transition-colors duration-150 hover:bg-accent/20 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring/70"
aria-expanded={row.expanded}
onClick={() => ctx.onToggleWorkGroup(row.groupId, row.id)}
onClick={(event) => {
const anchorElement =
event.currentTarget.closest<HTMLElement>("[data-timeline-row-id]") ?? event.currentTarget;
ctx.onToggleWorkGroup(row.groupId, anchorElement);
}}
>
<span className="flex size-5 shrink-0 items-center justify-center text-icon-muted">
<span className="flex size-5 shrink-0 items-center justify-center text-muted-foreground/65">
<ChevronDownIcon
className={cn(
"size-3.5 shrink-0 opacity-70 transition-transform duration-200",
@@ -1661,11 +1627,11 @@ function WorkGroupToggleTimelineRow({
/>
</span>
{row.expanded ? (
<span className="font-medium text-foreground">
<span className="font-medium text-foreground/82">
Show fewer {row.onlyToolEntries ? "tool calls" : "log entries"}
</span>
) : (
<span className="font-medium text-foreground">
<span className="font-medium text-foreground/82">
+{row.hiddenCount} previous {labelNoun}
</span>
)}
@@ -1795,7 +1761,7 @@ const UserMessageElementContextChip = memo(function UserMessageElementContextChi
<Tooltip>
<TooltipTrigger
render={
<span className="inline-flex max-w-full items-center gap-1 rounded-md border border-border/70 bg-background/70 px-1.5 py-0.5 text-foreground/85 text-xs">
<span className="inline-flex max-w-full items-center gap-1 rounded-md border border-border/70 bg-background/70 px-1.5 py-0.5 text-xs text-foreground/85">
<MousePointerClickIcon className="size-3 shrink-0" />
<span className="truncate">{props.context.header}</span>
</span>
@@ -1835,13 +1801,13 @@ function UserMessagePreviewAnnotationCard(props: {
) : null}
<div className="min-w-0 px-2.5 py-2">
{props.annotation.comment ? (
<div className="max-w-80 truncate text-foreground text-xs font-medium">
<div className="max-w-80 truncate text-xs font-medium text-foreground/90">
{props.annotation.comment}
</div>
) : null}
<div
className={cn(
"flex items-center gap-2 text-secondary-label text-[10px]",
"flex items-center gap-2 text-[10px] text-muted-foreground",
props.annotation.comment && "mt-1",
)}
>
@@ -1930,7 +1896,7 @@ const CollapsibleUserMessageBody = memo(function CollapsibleUserMessageBody(prop
aria-expanded={expanded}
data-scroll-anchor-ignore
onClick={() => setExpanded((value) => !value)}
className="-ml-1 h-6 rounded-md px-1.5 text-secondary-label text-xs hover:bg-muted/55 hover:text-message-foreground"
className="-ml-1 h-6 rounded-md px-1.5 text-xs text-muted-foreground/72 hover:bg-muted/55 hover:text-foreground/85"
>
{expanded ? "Show less" : "Show full message"}
</Button>
@@ -1969,7 +1935,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
cwd={props.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
skills={props.skills}
className="text-message-foreground"
className="text-foreground"
lineBreaks
/>
) : null}
@@ -1981,7 +1947,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
const reviewCommentSegments = parseReviewCommentMessageSegments(props.text);
if (reviewCommentSegments.some((segment) => segment.kind === "review-comment")) {
return (
<div className="space-y-3 text-message-foreground text-sm leading-relaxed">
<div className="space-y-3 text-sm leading-relaxed text-foreground">
{reviewCommentSegments.map((segment) =>
segment.kind === "text" ? (
segment.text.trim().length > 0 ? (
@@ -1991,7 +1957,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
cwd={props.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
skills={props.skills}
className="text-message-foreground"
className="text-foreground"
lineBreaks
/>
</div>
@@ -2050,7 +2016,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
}
return (
<div className="whitespace-pre-wrap wrap-break-word text-message-foreground text-sm leading-relaxed">
<div className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground">
{inlineNodes}
</div>
);
@@ -2079,7 +2045,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
cwd={props.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
skills={props.skills}
className="text-message-foreground"
className="text-foreground"
lineBreaks
/>,
);
@@ -2088,7 +2054,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
}
return (
<div className="whitespace-pre-wrap wrap-break-word text-message-foreground text-sm leading-relaxed">
<div className="whitespace-pre-wrap wrap-break-word text-sm leading-relaxed text-foreground">
{inlineNodes}
</div>
);
@@ -2104,7 +2070,7 @@ const UserMessageBody = memo(function UserMessageBody(props: {
cwd={props.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
skills={props.skills}
className="text-message-foreground"
className="text-foreground"
lineBreaks
/>
);
@@ -2121,10 +2087,10 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
return (
<div className="space-y-2 rounded-lg border border-border/70 bg-background/70 p-3">
<div className="space-y-1">
<div className="text-message-foreground text-xs font-medium">
<div className="text-xs font-medium text-foreground">
{formatWorkspaceRelativePath(comment.filePath, ctx.workspaceRoot)}
</div>
<div className="text-secondary-label text-[11px]">
<div className="text-[11px] text-muted-foreground">
{comment.sectionTitle} · {comment.rangeLabel}
</div>
</div>
@@ -2139,7 +2105,7 @@ function UserMessageReviewCommentCard({ comment }: { comment: ReviewCommentConte
cwd={ctx.markdownCwd}
threadRef={ctx.threadRef ?? undefined}
skills={ctx.skills}
className="text-message-foreground"
className="text-foreground"
/>
)}
{renderablePatch?.kind === "files" &&
@@ -2276,24 +2242,24 @@ function workToneIcon(tone: TimelineWorkEntry["tone"]): {
if (tone === "error") {
return {
iconName: "circle-alert",
className: "text-foreground",
className: "text-foreground/92",
};
}
if (tone === "thinking") {
return {
iconName: "bot",
className: "text-foreground",
className: "text-foreground/92",
};
}
if (tone === "info") {
return {
iconName: "check",
className: "text-icon-muted",
className: "text-muted-foreground",
};
}
return {
iconName: "zap",
className: "text-foreground",
className: "text-foreground/92",
};
}
@@ -2419,115 +2385,9 @@ function toolWorkEntryHeading(workEntry: TimelineWorkEntry): string {
const stopRowToggle = (e: { stopPropagation: () => void }) => e.stopPropagation();
/**
* A1 spawn CTA: one anchored row per workflow run (or per-turn direct-spawn
* batch). Live status is derived from the shared agent panel model at render
* time — the row itself never re-renders a roster; the Agents panel is the
* only roster. Freezes to past tense when every member settles. Static dot,
* no animation.
*/
const AgentSpawnCtaRow = memo(function AgentSpawnCtaRow(props: { workEntry: TimelineWorkEntry }) {
const { workEntry } = props;
const { agentPanelModel, onOpenAgents } = use(TimelineRowCtx);
const spawn = workEntry.agentSpawn;
if (!spawn) {
return null;
}
const memberIds = new Set(spawn.agentTaskIds);
const workflowGroup = spawn.workflowId
? agentPanelModel.workflows.find((group) => group.workflow.id === spawn.workflowId)
: undefined;
const agents = workflowGroup
? [...workflowGroup.phases.flatMap((phase) => phase.members), ...workflowGroup.unphasedMembers]
: agentPanelModel.directAgents.filter((agent) => memberIds.has(agent.id));
const agentCount = Math.max(
agents.length,
Math.max(memberIds.size - (spawn.workflowId ? 1 : 0), 0),
);
const running = agents.filter(
(agent) => agent.status === "running" || agent.status === "pending",
).length;
const waiting = agents.filter((agent) => agent.status === "waiting").length;
const failed = agents.filter((agent) => agent.status === "failed").length;
// The coordinator's own status is authoritative for workflows: dynamic
// spawns mean the member list can be momentarily all-settled while the
// run is still mid-flight (the "completed" lie from live testing). A
// workflow is live until the coordinator itself reaches a terminal state.
const coordinatorStatus = workflowGroup?.workflow.status;
const coordinatorSettled =
coordinatorStatus === "completed" ||
coordinatorStatus === "failed" ||
coordinatorStatus === "cancelled" ||
coordinatorStatus === "interrupted";
const live = workflowGroup !== undefined ? !coordinatorSettled : running + waiting > 0;
// Same rule as the panel footer: providers may aggregate member usage into
// the coordinator, so count the coordinator only when no members exist.
const totalTokens = agents.reduce(
(sum, agent) => sum + (agent.usage?.totalTokens ?? 0),
spawn.workflowId && agents.length === 0 ? (workflowGroup?.workflow.usage?.totalTokens ?? 0) : 0,
);
const livePhase = workflowGroup?.phases.find((phase) => phase.state === "running");
const workflowName =
workflowGroup?.workflow.workflowName ?? workflowGroup?.workflow.title ?? null;
// One steady in-flight presentation (monitoring-pill rule): waiting and
// stalled agents read as working; only settled states differentiate.
const working = running + waiting;
const dotClass = live ? "bg-info" : failed > 0 ? "bg-destructive" : "bg-success";
const lead = live
? `Kicked off ${agentCount} subagent${agentCount === 1 ? "" : "s"}`
: `Ran ${agentCount} subagent${agentCount === 1 ? "" : "s"}`;
const status = live
? livePhase
? `${livePhase.title} · ${livePhase.activeCount} working`
: working > 0
? `${working} working`
: "working"
: failed > 0
? `${failed} failed`
: "✓ completed";
return (
<button
type="button"
onClick={onOpenAgents}
className="-mx-1 flex w-full items-center gap-2 rounded-md border border-border/60 bg-card/50 px-2.5 py-1.5 text-left text-[13px] transition hover:bg-accent/50"
>
<span aria-hidden className={cn("size-1.5 shrink-0 rounded-full", dotClass)} />
<WorkEntryIconSvg name="bot" className="size-3.5 shrink-0 text-muted-foreground" />
<span className="min-w-0 truncate">
<span className="font-medium">{lead}</span>
{workflowName ? <span className="text-muted-foreground"> · {workflowName}</span> : null}
</span>
<span className="ml-auto flex shrink-0 items-center gap-2 font-mono text-[.7rem] text-muted-foreground">
<span>{status}</span>
{totalTokens > 0 ? (
<span className="tabular-nums">Σ {formatSubagentTokenCount(totalTokens)}</span>
) : null}
<span className="text-info-foreground">{live ? "Open Agents ▸" : "View ▸"}</span>
</span>
</button>
);
});
const SimpleWorkEntryRow = memo(function SimpleWorkEntryRow(props: {
workEntry: TimelineWorkEntry;
workspaceRoot: string | undefined;
}) {
const { workEntry, workspaceRoot } = props;
// Before any hooks: spawn CTA rows render their own component.
if (workEntry.agentSpawn) {
return <AgentSpawnCtaRow workEntry={workEntry} />;
}
return <PlainWorkEntryRow workEntry={workEntry} workspaceRoot={workspaceRoot} />;
});
const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
workEntry: TimelineWorkEntry;
workspaceRoot: string | undefined;
}) {
const { workEntry, workspaceRoot } = props;
const activity = use(TimelineRowActivityCtx);
@@ -2557,14 +2417,14 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
: showDestructiveRowStyle
? "text-destructive"
: workEntry.tone === "tool" || showFailedIndicator
? "text-icon-muted"
? "text-muted-foreground/65"
: iconConfig.className,
);
const headingClass = showWarningIndicator
? "font-medium text-warning"
: showDestructiveRowStyle
? "font-medium text-destructive"
: "font-medium text-foreground";
: "font-medium text-foreground/82";
const turnSettled = !activity.activeTurnInProgress;
const showNeutralIndicator = !turnSettled && workEntryIndicatesToolNeutralStatus(workEntry);
const showSuccessIndicator =
@@ -2619,11 +2479,11 @@ const PlainWorkEntryRow = memo(function PlainWorkEntryRow(props: {
</span>
) : null}
{preview && (
<span className="min-w-0 flex-1 truncate text-secondary-label">{preview}</span>
<span className="min-w-0 flex-1 truncate text-muted-foreground/55">{preview}</span>
)}
</p>
</div>
<div className="flex shrink-0 items-center gap-px text-icon-muted">
<div className="flex shrink-0 items-center gap-px text-muted-foreground/55">
<span
className="flex size-4 shrink-0 items-center justify-center"
aria-hidden={!canExpand}
@@ -1,96 +1,296 @@
import { scopeThreadRef } from "@t3tools/client-runtime/environment";
import { deriveThreadQueueWorkflowState } from "@t3tools/client-runtime/state/thread-workflows";
import type { EnvironmentId, RunId, ThreadId } from "@t3tools/contracts";
import { ArrowDownIcon, ArrowUpIcon, CornerUpRightIcon, ListOrderedIcon } from "lucide-react";
import {
ArrowDownIcon,
ArrowUpIcon,
CheckIcon,
Clock3Icon,
CornerUpRightIcon,
ListOrderedIcon,
PencilIcon,
XIcon,
} from "lucide-react";
import { useMemo, useState } from "react";
import { threadEnvironment } from "../../state/threads";
import { useThreadProjection } from "../../state/entities";
import { useAtomCommand } from "../../state/use-atom-command";
import type { ChatMessage } from "../../types";
import { Button } from "../ui/button";
export function QueuedRunsControl(props: {
readonly environmentId: EnvironmentId;
readonly threadId: ThreadId;
readonly optimisticMessages: ReadonlyArray<Pick<ChatMessage, "id" | "inputIntent" | "text">>;
}) {
const projection = useThreadProjection(
scopeThreadRef(props.environmentId, props.threadId),
)?.projection;
const reorder = useAtomCommand(threadEnvironment.reorderQueuedRun);
const promote = useAtomCommand(threadEnvironment.promoteQueuedRun);
const cancel = useAtomCommand(threadEnvironment.cancelQueuedRun);
const edit = useAtomCommand(threadEnvironment.editQueuedRun);
const [busyRunId, setBusyRunId] = useState<RunId | null>(null);
const [editing, setEditing] = useState<{ runId: RunId; draft: string } | null>(null);
const workflow = useMemo(
() => (projection ? deriveThreadQueueWorkflowState(projection) : null),
[projection],
);
const queued = workflow?.queuedRuns ?? [];
const activeRun = workflow?.activeRun ?? null;
const committedQueuedMessageIds = new Set(queued.map(({ run }) => run.userMessageId));
const optimisticQueued = props.optimisticMessages.filter(
(message) =>
message.inputIntent === "queued_turn" && !committedQueuedMessageIds.has(message.id),
);
const items = [
...queued.map(({ run, text }, serverIndex) => ({
key: run.id,
runId: run.id,
serverIndex,
text,
pending: false,
})),
...optimisticQueued.map((message) => ({
key: message.id,
runId: null,
serverIndex: null,
text: message.text,
pending: true,
})),
];
if (queued.length === 0) return null;
if (items.length === 0) return null;
const move = async (runId: RunId, beforeRunId: RunId | null) => {
setBusyRunId(runId);
await reorder({
environmentId: props.environmentId,
input: { threadId: props.threadId, runId, beforeRunId },
});
setBusyRunId(null);
try {
await reorder({
environmentId: props.environmentId,
input: { threadId: props.threadId, runId, beforeRunId },
});
} finally {
setBusyRunId(null);
}
};
const steer = async (queuedRunId: RunId) => {
if (activeRun === null) return;
setBusyRunId(queuedRunId);
await promote({
environmentId: props.environmentId,
input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id },
});
setBusyRunId(null);
try {
await promote({
environmentId: props.environmentId,
input: { threadId: props.threadId, queuedRunId, targetRunId: activeRun.id },
});
} finally {
setBusyRunId(null);
}
};
const remove = async (runId: RunId) => {
setBusyRunId(runId);
try {
await cancel({
environmentId: props.environmentId,
input: { threadId: props.threadId, runId },
});
} finally {
setBusyRunId(null);
}
};
const saveEdit = async (runId: RunId, originalText: string) => {
if (editing === null || editing.runId !== runId) return;
const text = editing.draft.trim();
if (text.length === 0) return;
if (text === originalText) {
setEditing(null);
return;
}
setBusyRunId(runId);
try {
await edit({
environmentId: props.environmentId,
input: { threadId: props.threadId, runId, text },
});
setEditing(null);
} finally {
setBusyRunId(null);
}
};
return (
<section className="mx-auto mb-2 max-w-208 rounded-xl border border-border bg-background/96 shadow-xs">
<header className="flex items-center gap-2 border-b border-border px-3 py-2 text-xs font-medium">
<ListOrderedIcon className="size-3.5 text-muted-foreground" />
Queue
<span className="ml-auto tabular-nums text-muted-foreground">{queued.length}</span>
<section
aria-label={`${items.length} queued message${items.length === 1 ? "" : "s"}`}
aria-live="polite"
className="chat-composer-queue-strip relative z-0 -mb-4 mx-auto w-[calc(100%-2.75rem)] max-w-[calc(48rem-2.75rem)] px-2 pt-1.5 pb-5"
>
<header className="flex h-6 items-center gap-1.5 px-1.5 text-[11px] font-medium text-muted-foreground">
<ListOrderedIcon className="size-3.5" />
<span>Queued</span>
<span className="rounded-full bg-muted/70 px-1.5 text-[10px] tabular-nums">
{items.length}
</span>
</header>
<ol className="max-h-40 overflow-y-auto p-1.5">
{queued.map(({ run, text }, index) => (
<li key={run.id} className="flex min-w-0 items-center gap-2 rounded-lg px-2 py-1.5">
<span className="w-5 shrink-0 text-right text-[10px] tabular-nums text-muted-foreground">
{index + 1}
</span>
<span className="min-w-0 flex-1 truncate text-xs">{text}</span>
<Button
size="icon-xs"
variant="ghost"
aria-label="Move queued message up"
disabled={busyRunId !== null || !workflow?.canReorder || index === 0}
onClick={() => void move(run.id, queued[index - 1]?.run.id ?? null)}
<ol className="max-h-32 overflow-y-auto px-1">
{items.map((item, index) => {
const rowEditing =
item.runId !== null && editing !== null && editing.runId === item.runId
? editing
: null;
return (
<li
key={item.key}
className="flex min-w-0 items-center gap-1 border-border/45 border-t py-1 first:border-t-0"
>
<ArrowUpIcon className="size-3" />
</Button>
<Button
size="icon-xs"
variant="ghost"
aria-label="Move queued message down"
disabled={busyRunId !== null || !workflow?.canReorder || index === queued.length - 1}
onClick={() => void move(run.id, queued[index + 2]?.run.id ?? null)}
>
<ArrowDownIcon className="size-3" />
</Button>
<Button
size="xs"
variant="outline"
disabled={busyRunId !== null || !workflow?.canPromoteToSteer}
title={activeRun === null ? "There is no active run to steer" : "Promote to steer"}
onClick={() => void steer(run.id)}
>
<CornerUpRightIcon className="size-3" />
Steer
</Button>
</li>
))}
<span className="w-4 shrink-0 text-center text-[10px] tabular-nums text-muted-foreground/65">
{index + 1}
</span>
{item.pending ? (
<Clock3Icon
aria-label="Saving queued message"
className="size-3 shrink-0 text-muted-foreground/60"
/>
) : null}
{rowEditing !== null ? (
<>
<input
aria-label="Edit queued message"
autoFocus
className="min-w-0 flex-1 rounded-sm border border-border/60 bg-transparent px-1.5 py-0.5 text-xs outline-none focus:border-border"
value={rowEditing.draft}
onChange={(event) =>
setEditing((current) =>
current === null ? current : { ...current, draft: event.target.value },
)
}
onKeyDown={(event) => {
if (event.key === "Enter") {
event.preventDefault();
if (item.runId !== null) void saveEdit(item.runId, item.text);
}
if (event.key === "Escape") {
event.preventDefault();
setEditing(null);
}
}}
/>
<Button
size="icon-xs"
variant="ghost"
aria-label="Save queued message"
className="size-6 text-muted-foreground"
disabled={busyRunId !== null || rowEditing.draft.trim().length === 0}
onClick={() => {
if (item.runId !== null) void saveEdit(item.runId, item.text);
}}
>
<CheckIcon className="size-3" />
</Button>
<Button
size="icon-xs"
variant="ghost"
aria-label="Cancel editing queued message"
className="size-6 text-muted-foreground"
disabled={busyRunId !== null}
onClick={() => setEditing(null)}
>
<XIcon className="size-3" />
</Button>
</>
) : (
<>
<span className="min-w-0 flex-1 truncate text-xs" title={item.text}>
{item.text}
</span>
<Button
size="icon-xs"
variant="ghost"
aria-label="Edit queued message"
className="size-6 text-muted-foreground"
disabled={item.runId === null || busyRunId !== null}
onClick={() => {
if (item.runId !== null) setEditing({ runId: item.runId, draft: item.text });
}}
>
<PencilIcon className="size-3" />
</Button>
<Button
size="icon-xs"
variant="ghost"
aria-label="Move queued message up"
className="size-6 text-muted-foreground"
disabled={
item.runId === null ||
item.serverIndex === null ||
busyRunId !== null ||
!workflow?.canReorder ||
item.serverIndex === 0
}
onClick={() => {
if (item.runId === null || item.serverIndex === null) return;
void move(item.runId, queued[item.serverIndex - 1]?.run.id ?? null);
}}
>
<ArrowUpIcon className="size-3" />
</Button>
<Button
size="icon-xs"
variant="ghost"
aria-label="Move queued message down"
className="size-6 text-muted-foreground"
disabled={
item.runId === null ||
item.serverIndex === null ||
busyRunId !== null ||
!workflow?.canReorder ||
item.serverIndex === queued.length - 1
}
onClick={() => {
if (item.runId === null || item.serverIndex === null) return;
void move(item.runId, queued[item.serverIndex + 2]?.run.id ?? null);
}}
>
<ArrowDownIcon className="size-3" />
</Button>
<Button
size="xs"
variant="ghost"
className="h-6 gap-1 px-1.5 text-[11px] text-muted-foreground"
disabled={
item.runId === null || busyRunId !== null || !workflow?.canPromoteToSteer
}
title={
activeRun === null
? "There is no active run to steer"
: "Send as a steer instead"
}
onClick={() => {
if (item.runId !== null) void steer(item.runId);
}}
>
<CornerUpRightIcon className="size-3" />
Steer
</Button>
<Button
size="icon-xs"
variant="ghost"
aria-label="Remove queued message"
className="size-6 text-muted-foreground"
disabled={item.runId === null || busyRunId !== null}
title="Remove from queue"
onClick={() => {
if (item.runId !== null) void remove(item.runId);
}}
>
<XIcon className="size-3" />
</Button>
</>
)}
</li>
);
})}
</ol>
</section>
);
@@ -109,7 +109,7 @@ export function ThreadDetailsPanel(props: ThreadDetailsPanelProps) {
<div
className={cn(
"panel-glass overflow-hidden rounded-[20px]",
props.mode === "popover" && "panel-glass-opaque",
props.mode === "popover" && "panel-glass-elevated",
props.mode === "inline" ? "max-h-full" : "max-h-[calc(100dvh-6.5rem)]",
)}
data-thread-details-card
@@ -1,10 +1,11 @@
import type { ReactNode } from "react";
import type { LucideIcon } from "lucide-react";
import { cn } from "~/lib/utils";
export function TimelineSystemDivider(props: {
readonly label: string;
readonly detail?: string | null;
readonly detail?: ReactNode | null;
readonly tone?: "neutral" | "danger";
readonly icon?: LucideIcon;
readonly actionLabel?: string;
+110 -3
View File
@@ -1,6 +1,14 @@
import type { OrchestrationV2TurnItem, ThreadId } from "@t3tools/contracts";
import { Fragment } from "react";
import type {
OrchestrationV2Run,
OrchestrationV2TurnItem,
ProviderInstanceId,
ServerProvider,
ThreadId,
} from "@t3tools/contracts";
import type { TimestampFormat } from "@t3tools/contracts/settings";
import {
ArrowRightIcon,
BotIcon,
ChevronDownIcon,
ExternalLinkIcon,
@@ -12,7 +20,9 @@ import {
ZapIcon,
} from "lucide-react";
import { getProviderInstanceEntry } from "../../providerInstances";
import { formatShortTimestamp } from "../../timestampFormat";
import { PROVIDER_ICON_BY_PROVIDER, getTriggerDisplayModelName } from "./providerIconUtils";
import { TimelineSystemDivider } from "./TimelineSystemDivider";
const LIFECYCLE_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
@@ -49,6 +59,8 @@ export function V2LifecycleRow(props: {
readonly item: OrchestrationV2TurnItem;
readonly createdAt: string;
readonly timestampFormat: TimestampFormat;
readonly providerStatuses: ReadonlyArray<ServerProvider>;
readonly runs: ReadonlyArray<OrchestrationV2Run>;
readonly onOpenThread: (threadId: ThreadId) => void;
}) {
const { item } = props;
@@ -95,14 +107,58 @@ export function V2LifecycleRow(props: {
);
}
if (item.type === "handoff") {
// Items persisted before models were stamped only carry instance ids;
// recover the models from the thread's runs (the handoff's own run is
// the target, the newest earlier run per source instance is the origin).
// HandoffEndpoint falls back to the provider display name when neither
// source has a model.
const handoffRun =
item.runId === null ? undefined : props.runs.find((run) => run.id === item.runId);
const toModel =
item.toModel ??
(handoffRun !== undefined && handoffRun.providerInstanceId === item.toProviderInstanceId
? handoffRun.modelSelection.model
: undefined);
const fromEndpoints: ReadonlyArray<{
readonly instanceId: ProviderInstanceId;
readonly model?: string | undefined;
}> =
item.fromModelSelections !== undefined && item.fromModelSelections.length > 0
? item.fromModelSelections
: item.fromProviderInstanceIds.map((instanceId) => ({
instanceId,
model: latestRunModelBefore(props.runs, instanceId, handoffRun?.ordinal),
}));
return (
<TimelineSystemDivider
label="Context handoff"
icon={ZapIcon}
tone={item.status === "failed" ? "danger" : "neutral"}
detail={
item.summary ??
`${item.fromProviderInstanceIds.join(", ")} → ${item.toProviderInstanceId}`
<span className="inline-flex min-w-0 items-center gap-1.5">
{fromEndpoints.map((endpoint, index) => (
<Fragment key={`${endpoint.instanceId}:${endpoint.model ?? ""}`}>
{index > 0 ? (
<span aria-hidden="true" className="-ml-1">
,
</span>
) : null}
<HandoffEndpoint
providers={props.providerStatuses}
instanceId={endpoint.instanceId}
model={endpoint.model}
/>
</Fragment>
))}
{fromEndpoints.length > 0 ? (
<ArrowRightIcon aria-hidden="true" className="size-3 shrink-0" />
) : null}
<HandoffEndpoint
providers={props.providerStatuses}
instanceId={item.toProviderInstanceId}
model={toModel}
/>
</span>
}
/>
);
@@ -238,3 +294,54 @@ function RelatedThreadCard(props: {
function subagentDisplayTitle(title: string): string {
return title.replace(/^Subagent:\s*/i, "");
}
/**
* Model of the newest run for `instanceId` that started before the handoff's
* own run. Legacy handoff items don't record their source models, but the
* covered runs are still in the projection.
*/
function latestRunModelBefore(
runs: ReadonlyArray<OrchestrationV2Run>,
instanceId: ProviderInstanceId,
beforeOrdinal: number | undefined,
): string | undefined {
let latest: OrchestrationV2Run | undefined;
for (const run of runs) {
if (run.providerInstanceId !== instanceId) continue;
if (beforeOrdinal !== undefined && run.ordinal >= beforeOrdinal) continue;
if (latest === undefined || run.ordinal > latest.ordinal) latest = run;
}
return latest?.modelSelection.model;
}
/**
* One side of a context handoff: the provider's brand icon plus the model's
* display name. Falls back to the raw model slug when the instance no longer
* lists it, and to the instance display name (or id) when no model was
* recorded on the item.
*/
function HandoffEndpoint(props: {
readonly providers: ReadonlyArray<ServerProvider>;
readonly instanceId: ProviderInstanceId;
readonly model?: string | undefined;
}) {
const entry = getProviderInstanceEntry(props.providers, props.instanceId);
const Icon = entry === undefined ? null : (PROVIDER_ICON_BY_PROVIDER[entry.driverKind] ?? null);
const model = props.model?.trim();
const providerModel =
model === undefined || model.length === 0
? undefined
: entry?.models.find((candidate) => candidate.slug === model);
const label =
providerModel !== undefined
? getTriggerDisplayModelName(providerModel)
: model !== undefined && model.length > 0
? model
: (entry?.displayName ?? props.instanceId);
return (
<span className="inline-flex min-w-0 items-center gap-1">
{Icon === null ? null : <Icon aria-hidden="true" className="size-3 shrink-0" />}
<span className="max-w-40 truncate">{label}</span>
</span>
);
}
@@ -16,9 +16,30 @@ import { previewBridge } from "./previewBridge";
import {
clampPreviewMiniPlayerPosition,
clampPreviewMiniPlayerSize,
defaultPreviewMiniPlayerPosition,
PREVIEW_MINI_PLAYER_DEFAULT_SIZE,
} from "./previewMiniPlayerLayout";
/**
* Where a freshly opened player should land: under the inline thread-details
* card when that panel is open (it owns the top-right corner), otherwise the
* top-right CSS placement the element already has.
*/
function initialPreviewMiniPlayerPosition(root: HTMLElement, parent: HTMLElement) {
const fallback = { x: root.offsetLeft, y: root.offsetTop };
const card = root
.closest('[data-thread-details-inline-reserved="true"]')
?.querySelector('[data-thread-details-panel="inline"] [data-thread-details-card]');
if (!(card instanceof HTMLElement)) return fallback;
const cardRect = card.getBoundingClientRect();
return defaultPreviewMiniPlayerPosition({
fallback,
parentRect: parent.getBoundingClientRect(),
playerWidth: root.offsetWidth,
detailsCardRect: { right: cardRect.right, bottom: cardRect.bottom },
});
}
interface DragState {
readonly pointerId: number;
readonly pointerX: number;
@@ -92,7 +113,7 @@ export function ThreadPreviewMiniPlayer({ threadRef, tabId, bottomInset }: Props
);
usePreviewMiniPlayerStore.getState().resize(threadRef, tabId, nextSize);
const next = clampPreviewMiniPlayerPosition(
position ?? { x: root.offsetLeft, y: root.offsetTop },
position ?? initialPreviewMiniPlayerPosition(root, parent),
{ width: parent.clientWidth, height: parent.clientHeight },
nextSize,
bottomInset,
@@ -3,9 +3,37 @@ import { describe, expect, it } from "vite-plus/test";
import {
clampPreviewMiniPlayerPosition,
clampPreviewMiniPlayerSize,
defaultPreviewMiniPlayerPosition,
PREVIEW_MINI_PLAYER_EDGE_GAP,
} from "./previewMiniPlayerLayout";
describe("defaultPreviewMiniPlayerPosition", () => {
it("keeps the top-right fallback when the inline details panel is closed", () => {
expect(
defaultPreviewMiniPlayerPosition({
fallback: { x: 664, y: 16 },
parentRect: { left: 300, top: 60 },
playerWidth: 320,
detailsCardRect: null,
}),
).toEqual({ x: 664, y: 16 });
});
it("slides under the inline details card with right edges aligned", () => {
expect(
defaultPreviewMiniPlayerPosition({
fallback: { x: 664, y: 16 },
parentRect: { left: 300, top: 60 },
playerWidth: 320,
detailsCardRect: { right: 1280, bottom: 320 },
}),
).toEqual({
x: 1280 - 300 - 320,
y: 320 - 60 + PREVIEW_MINI_PLAYER_EDGE_GAP,
});
});
});
describe("clampPreviewMiniPlayerPosition", () => {
it("keeps a dragged player within the chat viewport", () => {
expect(
@@ -24,6 +24,27 @@ export function clampPreviewMiniPlayerSize(
};
}
/**
* Default spot for a freshly opened mini player. Normally the top-right CSS
* placement stands (`fallback`), but when the inline thread-details panel is
* open its card occupies that corner — slide the player underneath the card,
* right edges aligned, so neither surface covers the other. The result still
* goes through `clampPreviewMiniPlayerPosition`, which pulls the player back
* up when a tall card would push it into the composer.
*/
export function defaultPreviewMiniPlayerPosition(input: {
readonly fallback: PreviewMiniPlayerPosition;
readonly parentRect: { readonly left: number; readonly top: number };
readonly playerWidth: number;
readonly detailsCardRect: { readonly right: number; readonly bottom: number } | null;
}): PreviewMiniPlayerPosition {
if (input.detailsCardRect === null) return input.fallback;
return {
x: input.detailsCardRect.right - input.parentRect.left - input.playerWidth,
y: input.detailsCardRect.bottom - input.parentRect.top + PREVIEW_MINI_PLAYER_EDGE_GAP,
};
}
export function clampPreviewMiniPlayerPosition(
position: PreviewMiniPlayerPosition,
container: PreviewMiniPlayerSize,
+31
View File
@@ -26,11 +26,13 @@ import {
readEnvironmentSupportsPinReorder,
readEnvironmentSupportsSettlement,
readEnvironmentSupportsSnooze,
readEnvironmentSupportsVisitedTracking,
readEnvironmentThreadRefs,
readProject,
readThreadShell,
readThreadShells,
} from "../state/entities";
import { useUiStateStore } from "../uiStateStore";
import { useTerminalUiStateStore } from "../terminalUiStateStore";
import { useUiStateStore } from "../uiStateStore";
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
@@ -135,6 +137,32 @@ export class ThreadPinReorderUnsupportedError extends Schema.TaggedErrorClass<Th
}
}
/**
* Marks a thread unread. Servers with visited tracking own the unread marker
* (thread.mark-unread rewinds the server-side visited watermark, syncing the
* marker to every device); older servers keep the browser-local marker.
*/
export function useMarkThreadUnread() {
const markThreadUnreadMutation = useAtomCommand(threadEnvironment.markUnread, {
reportFailure: false,
});
const markThreadUnreadLocal = useUiStateStore((state) => state.markThreadUnread);
return useCallback(
(target: ScopedThreadRef) => {
if (readEnvironmentSupportsVisitedTracking(target.environmentId)) {
void markThreadUnreadMutation({
environmentId: target.environmentId,
input: { threadId: target.threadId },
});
return;
}
const thread = readThreadShell(target);
markThreadUnreadLocal(scopedThreadKey(target), thread?.latestRun?.completedAt);
},
[markThreadUnreadLocal, markThreadUnreadMutation],
);
}
export function useThreadActions() {
const closeTerminal = useAtomCommand(terminalEnvironment.close);
const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
@@ -167,6 +195,7 @@ export function useThreadActions() {
const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
reportFailure: false,
});
const markThreadUnread = useMarkThreadUnread();
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
reportFailure: false,
@@ -708,11 +737,13 @@ export function useThreadActions() {
pinThread,
unpinThread,
reorderPinnedThread,
markThreadUnread,
}),
[
archiveThread,
confirmAndDeleteThread,
deleteThread,
markThreadUnread,
pinThread,
reorderPinnedThread,
settleThread,
@@ -0,0 +1,45 @@
import { scopeThreadRef, scopedThreadKey } from "@t3tools/client-runtime/environment";
import { useEffect } from "react";
import { useThreadShells } from "../state/entities";
import { threadEnvironment } from "../state/threads";
import { useAtomCommand } from "../state/use-atom-command";
import { useUiStateStore } from "../uiStateStore";
// Module-level so each thread is considered once per page load. The visit
// command is idempotent server-side (the server keeps max(stored, supplied)),
// so repeats across page loads are harmless — this only avoids re-dispatching
// within a session.
const migratedThreadKeys = new Set<string>();
/**
* One-way migration of the browser-local visited watermarks into servers with
* visited tracking. Before tracking existed, "Done" lived in this browser's
* localStorage; pushing those watermarks up seeds the server value so other
* devices see the same read state. The server never rewinds a newer visit, so
* this cannot clobber progress made elsewhere.
*/
export function useThreadVisitedMigration(): void {
const threads = useThreadShells();
const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
useEffect(() => {
for (const thread of threads) {
// Field absent → the environment's server has no visited tracking; keep
// the local value in play and reconsider if the server upgrades.
if (thread.lastVisitedAt === undefined) continue;
const threadKey = scopedThreadKey(scopeThreadRef(thread.environmentId, thread.id));
if (migratedThreadKeys.has(threadKey)) continue;
migratedThreadKeys.add(threadKey);
const local = useUiStateStore.getState().threadLastVisitedAtById[threadKey];
if (!local) continue;
const localMs = Date.parse(local);
if (!Number.isFinite(localMs)) continue;
const serverMs = thread.lastVisitedAt === null ? null : Date.parse(thread.lastVisitedAt);
if (serverMs !== null && Number.isFinite(serverMs) && serverMs >= localMs) continue;
void visitThreadMutation({
environmentId: thread.environmentId,
input: { threadId: thread.id, visitedAt: local },
});
}
}, [threads, visitThreadMutation]);
}
+42 -2
View File
@@ -769,6 +769,31 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
isolation: isolate;
}
.chat-composer-queue-strip {
--chat-composer-queue-outline: rgb(0 0 0 / 8%);
--chat-composer-queue-surface: var(--card);
isolation: isolate;
}
.chat-composer-queue-strip::before {
pointer-events: none;
position: absolute;
z-index: -1;
inset: 0;
border: 1px solid var(--chat-composer-queue-outline);
border-radius: 16px 16px 0 0;
background: color-mix(
in srgb,
var(--chat-composer-queue-surface) var(--glass-opacity),
transparent
);
-webkit-backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
box-shadow: 0 -10px 28px -24px rgb(0 0 0 / 45%);
content: "";
}
.chat-composer-context-strip::before {
position: absolute;
z-index: -1;
@@ -787,6 +812,17 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
--chat-composer-highlight: rgb(255 255 255 / 3%);
}
.dark .chat-composer-queue-strip {
--chat-composer-queue-outline: rgb(255 255 255 / 7%);
--chat-composer-queue-surface: color-mix(in srgb, var(--background) 96%, var(--color-white));
}
.dark .chat-composer-queue-strip::before {
box-shadow:
inset 0 1px rgb(255 255 255 / 3%),
0 -12px 28px -24px rgb(0 0 0 / 80%);
}
.dark .chat-composer-glass-host {
box-shadow: none;
}
@@ -904,8 +940,12 @@ html[data-mobile-composer-route-transition="true"]::view-transition-old(t3-mobil
backdrop-filter: blur(var(--glass-blur)) saturate(var(--glass-saturation));
}
.panel-glass-opaque::before {
background: var(--popover);
.panel-glass-elevated::before {
background: color-mix(
in srgb,
var(--popover) 50%,
color-mix(in srgb, var(--background) var(--glass-opacity), transparent)
);
}
.dialog-glass {
+41
View File
@@ -7,6 +7,7 @@ import {
isProviderInstancePickerReady,
isProviderInstancePickerVisible,
resolveDefaultProviderModelSelection,
resolveProviderCatalogAvailability,
resolveSelectableProviderInstance,
resolveProviderDriverKindForInstanceSelection,
} from "./providerInstances";
@@ -68,6 +69,46 @@ describe("isProviderInstancePickerReady", () => {
});
});
describe("resolveProviderCatalogAvailability", () => {
const [entry] = deriveProviderInstanceEntries([
provider({ provider: ProviderDriverKind.make("codex"), instanceId: "codex" }),
]);
it("keeps the initial reactive config state distinct from an empty catalogue", () => {
expect(
resolveProviderCatalogAvailability({
catalogLoaded: false,
entries: [],
selectedEntry: undefined,
}),
).toBe("loading");
expect(
resolveProviderCatalogAvailability({
catalogLoaded: true,
entries: [],
selectedEntry: undefined,
}),
).toBe("unconfigured");
});
it("distinguishes a selected provider from configured but unusable providers", () => {
expect(
resolveProviderCatalogAvailability({
catalogLoaded: true,
entries: entry ? [entry] : [],
selectedEntry: entry,
}),
).toBe("ready");
expect(
resolveProviderCatalogAvailability({
catalogLoaded: true,
entries: entry ? [entry] : [],
selectedEntry: undefined,
}),
).toBe("unavailable");
});
});
describe("isProviderInstancePickerVisible", () => {
it("keeps enabled instances in the rail and removes disabled instances", () => {
const [enabledEntry, disabledEntry] = deriveProviderInstanceEntries([
+18
View File
@@ -64,6 +64,24 @@ export interface ProviderInstanceEntry {
readonly models: ReadonlyArray<ServerProviderModel>;
}
export type ProviderCatalogAvailability = "loading" | "ready" | "unavailable" | "unconfigured";
/**
* Keep a provider catalogue that has not arrived yet distinct from a loaded
* catalogue with no usable entries. Environment config streams are reactive:
* treating their initial `null` as a final empty list strands otherwise
* recoverable threads behind a misleading "no providers" state.
*/
export function resolveProviderCatalogAvailability(input: {
readonly catalogLoaded: boolean;
readonly entries: ReadonlyArray<ProviderInstanceEntry>;
readonly selectedEntry: ProviderInstanceEntry | undefined;
}): ProviderCatalogAvailability {
if (!input.catalogLoaded) return "loading";
if (input.selectedEntry !== undefined) return "ready";
return input.entries.length === 0 ? "unconfigured" : "unavailable";
}
/**
* Whether an instance can currently contribute models to an interactive picker.
*
+124
View File
@@ -21,6 +21,7 @@ import {
deriveRevertTurnCountByUserMessageId,
findLatestProposedPlan,
isLatestRunSettled,
providerErrorPresentation,
type TimelineEntry,
} from "./session-logic";
import { makeThreadProjectionFixture } from "./test-fixtures";
@@ -46,6 +47,64 @@ describe("V2 session presentation", () => {
{ status: "running", activeRunId: runId },
),
).toBe(false);
expect(
isLatestRunSettled(
{ runId, status: "queued", startedAt: null, completedAt: null },
{ status: "running", activeRunId: RunId.make("run-active") },
),
).toBe(false);
});
it("labels provider retry progress, delay, recovery, and exhaustion", () => {
const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
const retryItem = {
id: TurnItemId.make("item-provider-retry"),
threadId: ThreadId.make("thread-provider-retry"),
runId: RunId.make("run-provider-retry"),
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 1,
status: "running" as const,
title: "Provider retry",
startedAt: now,
completedAt: null,
updatedAt: now,
type: "error" as const,
failure: {
class: "provider_error" as const,
message: "Claude API overloaded.",
code: "api_error_529",
retryable: true,
},
retry: {
attempt: 2,
maxAttempts: 10,
retryDelayMs: 1_500,
},
} satisfies Extract<OrchestrationV2TurnItem, { readonly type: "error" }>;
expect(providerErrorPresentation(retryItem)).toEqual({
label: "Retrying provider (2/10)",
detail: "Claude API overloaded. Retrying in 1.5s.",
});
expect(
providerErrorPresentation({
...retryItem,
status: "completed",
completedAt: now,
}),
).toMatchObject({ label: "Provider recovered (2/10 retries)" });
expect(
providerErrorPresentation({
...retryItem,
status: "failed",
retry: { ...retryItem.retry, attempt: 10 },
completedAt: now,
}),
).toMatchObject({ label: "Provider error after 10/10 retries" });
});
it("selects the latest proposed plan for a run", () => {
@@ -304,6 +363,71 @@ describe("V2 session presentation", () => {
}
});
it("waits for a dispatched turn item before adding queued input to the timeline", () => {
const projection = makeThreadProjectionFixture();
const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
const runId = RunId.make("run-dispatched-queued");
const messageId = MessageId.make("message-dispatched-queued");
const optimisticMessage = {
id: messageId,
role: "user" as const,
text: "Queued input",
runId: null,
inputIntent: "queued_turn" as const,
streaming: false,
createdAt: DateTime.formatIso(now),
updatedAt: DateTime.formatIso(now),
};
expect(
deriveTimelineEntriesFromVisibleTurnItems({
visibleTurnItems: [],
optimisticMessages: [optimisticMessage],
}),
).toEqual([]);
const dispatchedItem = {
id: TurnItemId.make("item-dispatched-queued"),
threadId: projection.thread.id,
runId,
nodeId: null,
providerThreadId: null,
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 200,
status: "completed" as const,
title: null,
startedAt: now,
completedAt: now,
updatedAt: now,
type: "user_message" as const,
messageId,
inputIntent: "turn_start" as const,
text: "Queued input",
attachments: [],
createdBy: "user" as const,
creationSource: "web" as const,
} satisfies OrchestrationV2TurnItem;
const promotedEntries = deriveTimelineEntriesFromVisibleTurnItems({
visibleTurnItems: [
{
position: 0,
visibility: "local",
sourceThreadId: projection.thread.id,
sourceItemId: dispatchedItem.id,
item: dispatchedItem,
},
],
optimisticMessages: [optimisticMessage],
});
expect(promotedEntries.map((entry) => entry.id)).toEqual([messageId]);
expect(promotedEntries[0]?.kind).toBe("message");
if (promotedEntries[0]?.kind === "message") {
expect(promotedEntries[0].message.inputIntent).toBe("turn_start");
}
});
it("uses projected plan status and file contents in timeline entries", () => {
const now = DateTime.makeUnsafe("2026-06-20T00:00:00.000Z");
const threadId = ThreadId.make("thread-timeline-artifacts");
+42 -6
View File
@@ -190,6 +190,7 @@ export function isLatestRunSettled(
if (latestRun === null) return false;
if (
latestRun.status === "preparing" ||
latestRun.status === "queued" ||
latestRun.status === "starting" ||
latestRun.status === "running" ||
latestRun.status === "waiting"
@@ -446,6 +447,39 @@ function projectedWorkEntryTone(item: OrchestrationV2TurnItem): WorkLogEntry["to
}
}
export function providerErrorPresentation(
item: Extract<OrchestrationV2TurnItem, { readonly type: "error" }>,
): { readonly label: string; readonly detail: string } {
if (item.retry === undefined) {
return {
label: item.title?.trim() || "Provider error",
detail: item.failure.message,
};
}
const progress =
item.retry.maxAttempts === null
? `${item.retry.attempt}`
: `${item.retry.attempt}/${item.retry.maxAttempts}`;
const label =
item.status === "running"
? `Retrying provider (${progress})`
: item.status === "completed"
? `Provider recovered (${progress} retries)`
: item.status === "failed"
? `Provider error after ${progress} retries`
: `Provider retry stopped (${progress})`;
const retryDelay =
item.status === "running" && item.retry.retryDelayMs !== null && item.retry.retryDelayMs > 0
? item.retry.retryDelayMs < 1_000
? ` Retrying in ${item.retry.retryDelayMs}ms.`
: ` Retrying in ${(item.retry.retryDelayMs / 1_000).toFixed(1).replace(/\.0$/u, "")}s.`
: "";
return {
label,
detail: `${item.failure.message}${retryDelay}`,
};
}
function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry {
const { item } = row;
const title = item.title?.trim() || null;
@@ -511,13 +545,14 @@ function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry
changedFiles: item.files.map((file) => file.path),
toolData: item,
};
case "error":
case "error": {
const presentation = providerErrorPresentation(item);
return {
...common,
label: title ?? "Provider error",
detail: item.failure.message,
...presentation,
toolData: item,
};
}
case "todo_list": {
const completed = item.steps.filter((step) => step.status === "completed").length;
return {
@@ -545,8 +580,9 @@ function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry
/**
* Builds the web timeline in the exact order committed by `visibleTurnItems`.
* Committed rows are presented directly from their projected item. Optimistic
* messages are the only client-owned entries appended to that sequence.
* Committed rows are presented directly from their projected item. Queued
* input is absent by construction until dispatch creates its user turn item.
* Optimistic messages are the only client-owned entries appended afterward.
*/
export function deriveTimelineEntriesFromVisibleTurnItems(input: {
readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
@@ -661,7 +697,7 @@ export function deriveTimelineEntriesFromVisibleTurnItems(input: {
}
for (const message of input.optimisticMessages) {
if (!committedMessageIds.has(message.id)) {
if (message.inputIntent !== "queued_turn" && !committedMessageIds.has(message.id)) {
entries.push({
id: message.id,
kind: "message",
+30
View File
@@ -183,6 +183,36 @@ export function readThreadProjection(ref: ScopedThreadRef): EnvironmentThread |
>>>>>>> d849d1caf9 (Retire V1 client orchestration parity)
}
/** Whether the environment's server understands thread.settle/unsettle.
False for pre-settlement servers (capability defaults false on decode),
so clients under version skew fall back instead of erroring. */
export function readEnvironmentSupportsSettlement(environmentId: EnvironmentId): boolean {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadSettlement === true
);
}
/** Whether the environment's server understands thread.snooze/unsnooze.
Same version-skew contract as settlement. */
export function readEnvironmentSupportsSnooze(environmentId: EnvironmentId): boolean {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadSnooze === true
);
}
/** Whether the environment's server understands thread.visit/mark-unread and
projects lastVisitedAt on thread shells. Same version-skew contract as
settlement: against older servers, clients keep the browser-local visited
state instead. */
export function readEnvironmentSupportsVisitedTracking(environmentId: EnvironmentId): boolean {
return (
appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment.capabilities
.threadVisitedTracking === true
);
}
export function readEnvironmentThreadRefs(
environmentId: EnvironmentId,
): ReadonlyArray<ScopedThreadRef> {
+3
View File
@@ -42,6 +42,9 @@ export function makeThreadProjectionFixture(): OrchestrationV2ThreadProjection {
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
},
runs: [],
@@ -40,6 +40,8 @@ import {
createProject,
forkThreadFromRun,
mergeThreadBack,
cancelQueuedRun,
editQueuedRun,
promoteQueuedRun,
reorderQueuedRun,
revertThreadCheckpoint,
@@ -419,6 +421,17 @@ describe("V2 environment commands", () => {
queuedRunId: RunId.make("run-3"),
targetRunId: RunId.make("run-active"),
}).pipe(provide);
yield* cancelQueuedRun({
commandId: CommandId.make("cancel"),
threadId: v2ThreadId,
runId: RunId.make("run-3"),
}).pipe(provide);
yield* editQueuedRun({
commandId: CommandId.make("edit"),
threadId: v2ThreadId,
runId: RunId.make("run-3"),
text: "updated queued text",
}).pipe(provide);
expect(commands).toMatchObject([
{ type: "thread.fork", sourcePoint: { type: "run", runId: "run-1" } },
@@ -429,6 +442,8 @@ describe("V2 environment commands", () => {
queuedRunId: "run-3",
targetRunId: "run-active",
},
{ type: "queued-run.cancel", runId: "run-3" },
{ type: "queued-run.edit", runId: "run-3", text: "updated queued text" },
]);
}).pipe(Effect.provide(TEST_CRYPTO_LAYER)),
);
@@ -72,6 +72,13 @@ export type DeleteThreadInput = ThreadCommandInput;
export type ArchiveThreadInput = ThreadCommandInput;
export type UnarchiveThreadInput = ThreadCommandInput;
export interface VisitThreadInput extends ThreadCommandInput {
/** Watermark of the thread state the viewer has seen (ISO timestamp). */
readonly visitedAt: string;
}
export type MarkThreadUnreadInput = ThreadCommandInput;
export interface UpdateThreadMetadataInput extends ThreadCommandInput {
readonly title?: string;
readonly modelSelection?: ModelSelection;
@@ -170,6 +177,15 @@ export interface PromoteQueuedRunInput extends ThreadCommandInput {
readonly targetRunId: RunId;
}
export interface CancelQueuedRunInput extends ThreadCommandInput {
readonly runId: RunId;
}
export interface EditQueuedRunInput extends ThreadCommandInput {
readonly runId: RunId;
readonly text: string;
}
const allocateCommandId = Effect.fn("EnvironmentCommands.allocateCommandId")(function* (
input: CommandMetadata,
) {
@@ -335,6 +351,66 @@ export const unarchiveThread = Effect.fn("EnvironmentCommands.unarchiveThread")(
return yield* simpleThreadCommand("thread.unarchive", input);
});
export const settleThread = Effect.fn("EnvironmentCommands.settleThread")(function* (
input: SettleThreadInput,
) {
return yield* simpleThreadCommand("thread.settle", input);
});
export const unsettleThread = Effect.fn("EnvironmentCommands.unsettleThread")(function* (
input: UnsettleThreadInput,
) {
return yield* dispatch({
type: "thread.unsettle",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
reason: input.reason,
});
});
export const snoozeThread = Effect.fn("EnvironmentCommands.snoozeThread")(function* (
input: SnoozeThreadInput,
) {
return yield* dispatch({
type: "thread.snooze",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
snoozedUntil: input.snoozedUntil,
});
});
export const unsnoozeThread = Effect.fn("EnvironmentCommands.unsnoozeThread")(function* (
input: UnsnoozeThreadInput,
) {
return yield* dispatch({
type: "thread.unsnooze",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
reason: input.reason,
});
});
export const visitThread = Effect.fn("EnvironmentCommands.visitThread")(function* (
input: VisitThreadInput,
) {
return yield* dispatch({
type: "thread.visit",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
visitedAt: input.visitedAt,
});
});
export const markThreadUnread = Effect.fn("EnvironmentCommands.markThreadUnread")(function* (
input: MarkThreadUnreadInput,
) {
return yield* dispatch({
type: "thread.mark-unread",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
});
});
export const updateThreadMetadata = Effect.fn("EnvironmentCommands.updateThreadMetadata")(
function* (input: UpdateThreadMetadataInput) {
const commandId = yield* allocateCommandId(input);
@@ -649,3 +725,26 @@ export const promoteQueuedRun = Effect.fn("EnvironmentCommands.promoteQueuedRun"
targetRunId: input.targetRunId,
});
});
export const cancelQueuedRun = Effect.fn("EnvironmentCommands.cancelQueuedRun")(function* (
input: CancelQueuedRunInput,
) {
return yield* dispatch({
type: "queued-run.cancel",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
runId: input.runId,
});
});
export const editQueuedRun = Effect.fn("EnvironmentCommands.editQueuedRun")(function* (
input: EditQueuedRunInput,
) {
return yield* dispatch({
type: "queued-run.edit",
commandId: yield* allocateCommandId(input),
threadId: input.threadId,
runId: input.runId,
text: input.text,
});
});
@@ -40,6 +40,30 @@ describe("V2 client presentation", () => {
});
});
it("preserves shell run timestamps for sidebar activity clocks", () => {
const runId = RunId.make("run-working-clock");
const requestedAt = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
const startedAt = DateTime.makeUnsafe("2026-06-20T01:00:02.000Z");
const shell = presentThreadShell(environmentId, {
...v2ThreadShell,
latestRunId: runId,
latestRunRequestedAt: requestedAt,
latestRunStartedAt: startedAt,
latestRunCompletedAt: null,
activeRunId: runId,
status: "running",
updatedAt: DateTime.makeUnsafe("2026-06-20T01:04:45.000Z"),
});
expect(shell.latestRun).toMatchObject({
runId,
status: "running",
requestedAt: "2026-06-20T01:00:00.000Z",
startedAt: "2026-06-20T01:00:02.000Z",
completedAt: null,
});
});
it("derives execution summaries without wrapping or copying the projection", () => {
const runId = RunId.make("run-1");
const now = DateTime.makeUnsafe("2026-06-20T01:00:00.000Z");
+24 -3
View File
@@ -91,6 +91,16 @@ export interface EnvironmentThreadShell {
readonly createdAt: string;
readonly updatedAt: string;
readonly archivedAt: string | null;
readonly settledOverride: "settled" | "active" | null;
readonly settledAt: string | null;
readonly snoozedUntil: string | null;
readonly snoozedAt: string | null;
/**
* Server-tracked visited watermark. `undefined` means the environment's
* server predates visited tracking and clients should fall back to any
* local visited state they keep.
*/
readonly lastVisitedAt?: string | null;
readonly deletedAt: string | null;
readonly source: OrchestrationV2ThreadShell;
}
@@ -143,10 +153,14 @@ export function presentThreadShell(
: ({
runId: thread.latestRunId,
status: thread.status === "idle" ? "completed" : thread.status,
requestedAt: null,
startedAt: null,
requestedAt: nullableIso(thread.latestRunRequestedAt ?? null),
startedAt: nullableIso(thread.latestRunStartedAt ?? null),
completedAt:
thread.status === "idle" || terminalRunStatus(thread.status) ? updatedAt : null,
thread.latestRunCompletedAt === undefined
? thread.status === "idle" || terminalRunStatus(thread.status)
? updatedAt
: null
: nullableIso(thread.latestRunCompletedAt),
assistantMessageId: null,
} satisfies ThreadRunSummary);
return {
@@ -177,6 +191,13 @@ export function presentThreadShell(
createdAt: iso(thread.createdAt),
updatedAt,
archivedAt: nullableIso(thread.archivedAt),
settledOverride: thread.settledOverride,
settledAt: nullableIso(thread.settledAt),
snoozedUntil: nullableIso(thread.snoozedUntil ?? null),
snoozedAt: nullableIso(thread.snoozedAt ?? null),
...(thread.lastVisitedAt === undefined
? {}
: { lastVisitedAt: nullableIso(thread.lastVisitedAt) }),
deletedAt: nullableIso(thread.deletedAt),
source: thread,
};
@@ -36,7 +36,7 @@ const run = {
contextHandoffId: null,
} satisfies OrchestrationV2Run;
function commandItem(id: string, output = "done"): OrchestrationV2TurnItem {
function commandItem(id: string, output = "done", ordinal = 1): OrchestrationV2TurnItem {
return {
id: TurnItemId.make(id),
threadId,
@@ -46,7 +46,7 @@ function commandItem(id: string, output = "done"): OrchestrationV2TurnItem {
providerTurnId: null,
nativeItemRef: null,
parentItemId: null,
ordinal: 1,
ordinal,
status: "completed",
title: null,
startedAt: now,
@@ -77,6 +77,9 @@ const emptyProjection = {
createdAt: now,
updatedAt: now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
},
runs: [],
@@ -197,6 +200,39 @@ describe("applyOrchestrationV2ProjectionEvent", () => {
expect(next?.visibleTurnItems[1]).toBe(secondRow);
});
it("inserts live turn items by authoritative ordinal", () => {
const queuedFuture = commandItem("item-queued-future", "queued", 300);
const activeAssistant = commandItem("item-active-assistant", "done", 201);
const queuedRow = {
position: 0,
visibility: "local" as const,
sourceThreadId: threadId,
sourceItemId: queuedFuture.id,
item: queuedFuture,
};
const projection = {
...emptyProjection,
runs: [run],
turnItems: [queuedFuture],
visibleTurnItems: [queuedRow],
};
const event = {
id: "event-active-assistant",
type: "turn-item.updated",
threadId,
runId,
occurredAt: now,
payload: activeAssistant,
} as OrchestrationV2DomainEvent;
const next = applyOrchestrationV2ProjectionEvent(projection, event);
expect(next?.visibleTurnItems.map((row) => row.item.id)).toEqual([
activeAssistant.id,
queuedFuture.id,
]);
expect(next?.visibleTurnItems.map((row) => row.position)).toEqual([0, 1]);
});
it("removes only hidden local items while preserving inherited rows", () => {
const inherited = commandItem("item-inherited");
const local = commandItem("item-local");
@@ -67,15 +67,15 @@ function upsertVisibleTurnItem(
const rows = projection.visibleTurnItems;
const index = rows.findIndex((row) => row.sourceItemId === item.id);
const next = {
position: index === -1 ? rows.length : rows[index]!.position,
position: 0,
visibility: "local" as const,
sourceThreadId: item.threadId,
sourceItemId: item.id,
item,
};
if (index === -1) return [...rows, next];
const previous = rows[index]!;
const previous = index === -1 ? undefined : rows[index]!;
if (
previous !== undefined &&
previous.visibility === next.visibility &&
previous.sourceThreadId === next.sourceThreadId &&
previous.sourceItemId === next.sourceItemId &&
@@ -83,9 +83,16 @@ function upsertVisibleTurnItem(
) {
return rows;
}
const updated = [...rows];
updated[index] = next;
return updated;
const updated = index === -1 ? [...rows] : [...rows.slice(0, index), ...rows.slice(index + 1)];
const insertionIndex = updated.findIndex(
(row) =>
row.visibility === "local" &&
(row.item.ordinal > item.ordinal ||
(row.item.ordinal === item.ordinal &&
String(row.item.id).localeCompare(String(item.id)) > 0)),
);
updated.splice(insertionIndex === -1 ? updated.length : insertionIndex, 0, next);
return renumberVisibleItems(updated);
}
/** Applies one committed event to a matching thread projection. */
@@ -107,6 +114,10 @@ export function applyOrchestrationV2ProjectionEvent(
case "thread.model-selection-updated":
case "thread.provider-switched":
return { ...base, thread: event.payload };
// Visited tracking is read state, not activity: skip the updatedAt bump.
case "thread.visited":
case "thread.marked-unread":
return { ...projection, thread: event.payload };
case "run.created":
case "run.updated": {
const next = { ...base, runs: upsertEntity(base.runs, event.payload) };
@@ -52,6 +52,9 @@ export const v2ThreadShell: OrchestrationV2ThreadShell = {
createdAt: v2Now,
updatedAt: v2Now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
};
@@ -74,6 +77,9 @@ export const v2Projection: OrchestrationV2ThreadProjection = {
createdAt: v2Now,
updatedAt: v2Now,
archivedAt: null,
settledOverride: null,
settledAt: null,
lastVisitedAt: null,
deletedAt: null,
},
runs: [],
@@ -4,9 +4,12 @@ import { Atom } from "effect/unstable/reactivity";
import { createAtomCommandScheduler, createEnvironmentCommand } from "./runtime.ts";
import {
type ArchiveThreadInput,
type CancelQueuedRunInput,
type CreateThreadInput,
type DeleteThreadInput,
type EditQueuedRunInput,
type InterruptThreadTurnInput,
type MarkThreadUnreadInput,
type ForkThreadFromRunInput,
type MergeThreadBackInput,
type PromoteQueuedRunInput,
@@ -27,11 +30,15 @@ import {
type UnsettleThreadInput,
type UnsnoozeThreadInput,
type UpdateThreadMetadataInput,
type VisitThreadInput,
archiveThread,
cancelQueuedRun,
createThread,
deleteThread,
editQueuedRun,
interruptThreadTurn,
forkThreadFromRun,
markThreadUnread,
mergeThreadBack,
promoteQueuedRun,
reorderQueuedRun,
@@ -51,14 +58,18 @@ import {
unsettleThread,
unsnoozeThread,
updateThreadMetadata,
visitThread,
} from "../operations/commands.ts";
import type { EnvironmentRegistry } from "../connection/registry.ts";
export type {
ArchiveThreadInput,
CancelQueuedRunInput,
CreateThreadInput,
DeleteThreadInput,
EditQueuedRunInput,
InterruptThreadTurnInput,
MarkThreadUnreadInput,
ForkThreadFromRunInput,
MergeThreadBackInput,
PromoteQueuedRunInput,
@@ -80,6 +91,7 @@ export type {
UnsettleThreadInput,
UnsnoozeThreadInput,
UpdateThreadMetadataInput,
VisitThreadInput,
} from "../operations/commands.ts";
export function createThreadEnvironmentAtoms<R, E>(
@@ -158,6 +170,18 @@ export function createThreadEnvironmentAtoms<R, E>(
scheduler,
concurrency,
}),
visit: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:visit",
execute: (input: VisitThreadInput) => visitThread(input),
scheduler,
concurrency,
}),
markUnread: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:mark-unread",
execute: (input: MarkThreadUnreadInput) => markThreadUnread(input),
scheduler,
concurrency,
}),
updateMetadata: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:update-metadata",
execute: (input: UpdateThreadMetadataInput) => updateThreadMetadata(input),
@@ -243,5 +267,17 @@ export function createThreadEnvironmentAtoms<R, E>(
scheduler,
concurrency,
}),
cancelQueuedRun: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:cancel-queued-run",
execute: (input: CancelQueuedRunInput) => cancelQueuedRun(input),
scheduler,
concurrency,
}),
editQueuedRun: createEnvironmentCommand(runtime, {
label: "environment-data:commands:thread:edit-queued-run",
execute: (input: EditQueuedRunInput) => editQueuedRun(input),
scheduler,
concurrency,
}),
};
}
@@ -46,7 +46,7 @@ describe("thread execution presentation", () => {
const runtime = deriveThreadRuntime(projection);
expect(runtime).toMatchObject({
status: "queued",
status: "running",
activeRunId: runningRun.id,
});
expect(threadRuntimeHasInterruptibleRun(runtime)).toBe(true);
@@ -62,6 +62,7 @@ export function deriveThreadRuntime(
projection: OrchestrationV2ThreadProjection,
): ThreadRuntimeSummary | null {
const latestRun = deriveLatestThreadRun(projection);
const activityRun = deriveThreadActivityRun(projection);
const providerSession = projection.providerSessions.findLast(
(session) => session.providerInstanceId === projection.thread.providerInstanceId,
);
@@ -69,7 +70,10 @@ export function deriveThreadRuntime(
const activeRunId =
latestMatchingRun(projection, (run) => INTERRUPTIBLE_RUN_STATUSES.has(run.status))?.id ?? null;
return {
status: latestRun?.status ?? "idle",
// Queueing creates a newer run, but does not replace the provider work
// already in flight. Present the executing run's status until it reaches
// a terminal state so clients do not flash from "running" to "queued".
status: activityRun?.status ?? "idle",
activeRunId,
providerInstanceId: projection.thread.providerInstanceId,
providerName: providerSession?.driver ?? null,
@@ -85,6 +85,42 @@ describe("thread workflows", () => {
expect(state.canPromoteToSteer).toBe(true);
});
it("removes only the promoted head from the visible queue", () => {
const state = deriveThreadQueueWorkflowState({
thread: { id: "thread", activeProviderThreadId: "provider-thread" },
runs: [
{
id: "promoted",
status: "starting",
userMessageId: "message-promoted",
providerThreadId: "provider-thread",
ordinal: 2,
queuePosition: null,
},
{
id: "still-queued",
status: "queued",
userMessageId: "message-still-queued",
providerThreadId: "provider-thread",
ordinal: 3,
queuePosition: 2,
},
],
messages: [
{ id: "message-promoted", text: "Run now" },
{ id: "message-still-queued", text: "Wait longer" },
],
providerTurns: [],
providerThreads: [],
providerSessions: [],
} as never);
expect(state.activeRun?.id).toBe("promoted");
expect(state.queuedRuns.map(({ run, text }) => [run.id, text])).toEqual([
["still-queued", "Wait longer"],
]);
});
it.each(["preparing", "starting", "waiting"] as const)(
"does not promote queued work into a %s run",
(status) => {
+5
View File
@@ -67,6 +67,11 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
/** Server understands regenerateTitle on thread.meta.update. Absent on
older servers, so clients hide the action instead of sending it. */
threadTitleRegeneration: Schema.optionalKey(Schema.Boolean),
/** Server understands thread.visit / thread.mark-unread commands and
projects lastVisitedAt on thread shells. Same version-skew contract as
threadSettlement: clients keep their local visited state against
servers that lack this. */
threadVisitedTracking: Schema.optionalKey(Schema.Boolean),
/** The update path clients should offer for this server. Absent on
servers that must be relaunched manually (dev checkouts, Windows
foreground runs, pre-update servers). */
+122
View File
@@ -315,6 +315,17 @@ export const OrchestrationV2AppThread = Schema.Struct({
createdAt: Schema.DateTimeUtc,
updatedAt: Schema.DateTimeUtc,
archivedAt: Schema.NullOr(Schema.DateTimeUtc),
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])).pipe(
Schema.withDecodingDefault(Effect.succeed(null)),
),
settledAt: Schema.NullOr(Schema.DateTimeUtc).pipe(
Schema.withDecodingDefault(Effect.succeed(null)),
),
snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
lastVisitedAt: Schema.NullOr(Schema.DateTimeUtc).pipe(
Schema.withDecodingDefault(Effect.succeed(null)),
),
deletedAt: Schema.NullOr(Schema.DateTimeUtc),
});
export type OrchestrationV2AppThread = typeof OrchestrationV2AppThread.Type;
@@ -728,6 +739,18 @@ export const OrchestrationV2ProviderFailure = Schema.Struct({
});
export type OrchestrationV2ProviderFailure = typeof OrchestrationV2ProviderFailure.Type;
/**
* Provider-reported retry progress. Some providers expose all fields (Claude),
* while others only expose `willRetry` and encode counters in display text
* (Codex), so the protocol-specific values remain nullable.
*/
export const OrchestrationV2ProviderRetry = Schema.Struct({
attempt: PositiveInt,
maxAttempts: Schema.NullOr(PositiveInt),
retryDelayMs: Schema.NullOr(NonNegativeInt),
});
export type OrchestrationV2ProviderRetry = typeof OrchestrationV2ProviderRetry.Type;
export const OrchestrationV2ProviderThreadDisposition = Schema.Literals(["reusable", "broken"]);
export type OrchestrationV2ProviderThreadDisposition =
typeof OrchestrationV2ProviderThreadDisposition.Type;
@@ -873,6 +896,7 @@ export const OrchestrationV2TurnItem = Schema.Union([
...OrchestrationV2TurnItemBaseFields,
type: Schema.Literal("error"),
failure: OrchestrationV2ProviderFailure,
retry: Schema.optional(OrchestrationV2ProviderRetry),
}),
Schema.Struct({
...OrchestrationV2TurnItemBaseFields,
@@ -890,6 +914,11 @@ export const OrchestrationV2TurnItem = Schema.Union([
toProviderThreadId: ProviderThreadId,
fromProviderInstanceIds: Schema.Array(ProviderInstanceId),
toProviderInstanceId: ProviderInstanceId,
// Model selections active on the covered source runs and the target
// model, so timelines can label the handoff by model rather than by
// provider instance id. Absent on items persisted before these fields.
fromModelSelections: Schema.optional(Schema.Array(ModelSelection)),
toModel: Schema.optional(Schema.String),
strategy: Schema.Literals([
"delta_since_target_last_seen",
"fork_delta_summary",
@@ -991,6 +1020,12 @@ export const OrchestrationV2DomainEvent = Schema.Union([
"thread.archived",
"thread.unarchived",
"thread.deleted",
"thread.settled",
"thread.unsettled",
"thread.snoozed",
"thread.unsnoozed",
"thread.visited",
"thread.marked-unread",
"thread.metadata-updated",
"thread.runtime-mode-updated",
"thread.interaction-mode-updated",
@@ -1163,6 +1198,9 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
activeProviderThreadId: Schema.NullOr(ProviderThreadId),
historyOrigin: Schema.optional(OrchestrationV2ThreadHistoryOrigin),
latestRunId: Schema.NullOr(RunId),
latestRunRequestedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
latestRunCompletedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
activeRunId: Schema.NullOr(RunId),
status: OrchestrationV2ShellThreadStatus,
lastError: Schema.optional(Schema.NullOr(Schema.String)),
@@ -1175,6 +1213,15 @@ export const OrchestrationV2ThreadShell = Schema.Struct({
createdAt: Schema.DateTimeUtc,
updatedAt: Schema.DateTimeUtc,
archivedAt: Schema.NullOr(Schema.DateTimeUtc),
settledOverride: Schema.NullOr(Schema.Literals(["settled", "active"])),
settledAt: Schema.NullOr(Schema.DateTimeUtc),
snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
/**
* Omitted by servers that predate server-side visited tracking; clients fall
* back to their local visited state when the field is absent.
*/
lastVisitedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtc)),
deletedAt: Schema.NullOr(Schema.DateTimeUtc),
});
export type OrchestrationV2ThreadShell = typeof OrchestrationV2ThreadShell.Type;
@@ -1241,6 +1288,14 @@ export const OrchestrationV2AppThreadJson = OrchestrationV2AppThread.mapFields((
createdAt: Schema.DateTimeUtcFromString,
updatedAt: Schema.DateTimeUtcFromString,
archivedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
settledAt: Schema.NullOr(Schema.DateTimeUtcFromString).pipe(
Schema.withDecodingDefault(Effect.succeed(null)),
),
snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
lastVisitedAt: Schema.NullOr(Schema.DateTimeUtcFromString).pipe(
Schema.withDecodingDefault(Effect.succeed(null)),
),
deletedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
}));
export type OrchestrationV2AppThreadJson = typeof OrchestrationV2AppThreadJson.Type;
@@ -1475,6 +1530,7 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
...OrchestrationV2TurnItemJsonBaseFields,
type: Schema.Literal("error"),
failure: OrchestrationV2ProviderFailure,
retry: Schema.optional(OrchestrationV2ProviderRetry),
}),
Schema.Struct({
...OrchestrationV2TurnItemJsonBaseFields,
@@ -1492,6 +1548,8 @@ export const OrchestrationV2TurnItemJson = Schema.Union([
toProviderThreadId: ProviderThreadId,
fromProviderInstanceIds: Schema.Array(ProviderInstanceId),
toProviderInstanceId: ProviderInstanceId,
fromModelSelections: Schema.optional(Schema.Array(ModelSelection)),
toModel: Schema.optional(Schema.String),
strategy: Schema.Literals([
"delta_since_target_last_seen",
"fork_delta_summary",
@@ -1597,6 +1655,9 @@ export type OrchestrationV2LatestVisibleMessageSummaryJson =
export const OrchestrationV2ThreadShellJson = OrchestrationV2ThreadShell.mapFields((fields) => ({
...fields,
latestRunRequestedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
latestRunStartedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
latestRunCompletedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
pendingRuntimeRequest: Schema.NullOr(OrchestrationV2PendingRuntimeRequestSummaryJson),
latestVisibleMessage: Schema.NullOr(OrchestrationV2LatestVisibleMessageSummaryJson),
latestUserMessageAt: Schema.NullOr(Schema.DateTimeUtcFromString),
@@ -1604,6 +1665,9 @@ export const OrchestrationV2ThreadShellJson = OrchestrationV2ThreadShell.mapFiel
updatedAt: Schema.DateTimeUtcFromString,
archivedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
settledAt: Schema.NullOr(Schema.DateTimeUtcFromString),
snoozedUntil: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
snoozedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
lastVisitedAt: Schema.optional(Schema.NullOr(Schema.DateTimeUtcFromString)),
deletedAt: Schema.NullOr(Schema.DateTimeUtcFromString),
}));
export type OrchestrationV2ThreadShellJson = typeof OrchestrationV2ThreadShellJson.Type;
@@ -1642,6 +1706,12 @@ export const OrchestrationV2DomainEventJson = Schema.Union([
"thread.archived",
"thread.unarchived",
"thread.deleted",
"thread.settled",
"thread.unsettled",
"thread.snoozed",
"thread.unsnoozed",
"thread.visited",
"thread.marked-unread",
"thread.metadata-updated",
"thread.runtime-mode-updated",
"thread.interaction-mode-updated",
@@ -1789,6 +1859,45 @@ export const OrchestrationV2Command = Schema.Union([
commandId: CommandId,
threadId: ThreadId,
}),
Schema.Struct({
type: Schema.Literal("thread.settle"),
commandId: CommandId,
threadId: ThreadId,
}),
Schema.Struct({
type: Schema.Literal("thread.unsettle"),
commandId: CommandId,
threadId: ThreadId,
reason: Schema.Literal("user"),
}),
Schema.Struct({
type: Schema.Literal("thread.snooze"),
commandId: CommandId,
threadId: ThreadId,
snoozedUntil: IsoDateTime,
}),
Schema.Struct({
type: Schema.Literal("thread.unsnooze"),
commandId: CommandId,
threadId: ThreadId,
reason: Schema.Literal("user"),
}),
Schema.Struct({
type: Schema.Literal("thread.visit"),
commandId: CommandId,
threadId: ThreadId,
/**
* Watermark of the thread state the viewer has seen (typically the shell's
* updatedAt). The server keeps the maximum of the stored and supplied
* values, so replays and out-of-order deliveries cannot move it backwards.
*/
visitedAt: IsoDateTime,
}),
Schema.Struct({
type: Schema.Literal("thread.mark-unread"),
commandId: CommandId,
threadId: ThreadId,
}),
Schema.Struct({
type: Schema.Literal("thread.metadata.update"),
commandId: CommandId,
@@ -1882,6 +1991,19 @@ export const OrchestrationV2Command = Schema.Union([
runId: RunId,
beforeRunId: Schema.NullOr(RunId),
}),
Schema.Struct({
type: Schema.Literal("queued-run.cancel"),
commandId: CommandId,
threadId: ThreadId,
runId: RunId,
}),
Schema.Struct({
type: Schema.Literal("queued-run.edit"),
commandId: CommandId,
threadId: ThreadId,
runId: RunId,
text: Schema.String,
}),
Schema.Struct({
type: Schema.Literal("runtime-request.respond"),
commandId: CommandId,
@@ -57,6 +57,39 @@ describe("isOrchestrationV2TurnItemVisible", () => {
).toBe(true);
});
it("hides queued user messages once their run is cancelled", () => {
expect(
isOrchestrationV2TurnItemVisible({
item: { type: "user_message", inputIntent: "queued_turn", runId, nodeId },
runs: [{ id: runId, status: "cancelled" }],
attempts: [],
items: [{ type: "user_message", inputIntent: "queued_turn", runId, nodeId }],
}),
).toBe(false);
});
it("keeps queued user messages while their run is queued", () => {
expect(
isOrchestrationV2TurnItemVisible({
item: { type: "user_message", inputIntent: "queued_turn", runId, nodeId },
runs: [{ id: runId, status: "queued" }],
attempts: [],
items: [{ type: "user_message", inputIntent: "queued_turn", runId, nodeId }],
}),
).toBe(true);
});
it("keeps non-queued user messages on cancelled runs", () => {
expect(
isOrchestrationV2TurnItemVisible({
item: { type: "user_message", inputIntent: "turn_start", runId, nodeId },
runs: [{ id: runId, status: "cancelled" }],
attempts: [],
items: [{ type: "user_message", inputIntent: "turn_start", runId, nodeId }],
}),
).toBe(true);
});
it("does not hide an interruption because another attempt was superseded", () => {
expect(
isOrchestrationV2TurnItemVisible({
+16 -1
View File
@@ -2,11 +2,14 @@ import type {
OrchestrationV2Run,
OrchestrationV2RunAttempt,
OrchestrationV2TurnItem,
OrchestrationV2UserMessageInputIntent,
} from "@t3tools/contracts";
type TimelineRun = Pick<OrchestrationV2Run, "id" | "status">;
type TimelineRunAttempt = Pick<OrchestrationV2RunAttempt, "runId" | "rootNodeId" | "status">;
type TimelineTurnItem = Pick<OrchestrationV2TurnItem, "type" | "runId" | "nodeId">;
type TimelineTurnItem = Pick<OrchestrationV2TurnItem, "type" | "runId" | "nodeId"> & {
readonly inputIntent?: OrchestrationV2UserMessageInputIntent;
};
export function isOrchestrationV2SupersededInterrupt(input: {
readonly item: TimelineTurnItem;
@@ -50,6 +53,18 @@ export function isOrchestrationV2TurnItemVisible(input: {
return false;
}
// A queued message is composer state, not conversation history. When its run
// is cancelled the input never reached the provider, so it must not surface
// as a transcript row.
if (
item.type === "user_message" &&
item.inputIntent === "queued_turn" &&
item.runId !== null &&
input.runs.some((run) => run.id === item.runId && run.status === "cancelled")
) {
return false;
}
return !isOrchestrationV2SupersededInterrupt({
item,
attempts: input.attempts,
@@ -35,6 +35,17 @@ describe("resolveT3McpToolPresentation", () => {
});
});
it("pretty prints preview T3 MCP tool names", () => {
expect(resolveT3McpToolPresentation("T3-code.preview_open")).toEqual({
displayName: "Open a page in the preview browser",
logo: "t3-code",
});
expect(resolveT3McpToolPresentation("mcp__t3-code__preview_status")).toEqual({
displayName: "Get preview browser status",
logo: "t3-code",
});
});
it("keeps unknown MCP tools on the generic renderer path", () => {
expect(resolveT3McpToolPresentation("mcp__github__search_issues")).toBeNull();
});
+18 -2
View File
@@ -25,6 +25,20 @@ const T3_MCP_TOOL_DISPLAY_NAMES: Record<string, string> = {
t3_thread_interrupt: "Interrupt a T3 thread",
t3_worktree_handoff: "Hand off thread to a git worktree",
t3_worktree_status: "Get thread worktree status",
preview_status: "Get preview browser status",
preview_open: "Open a page in the preview browser",
preview_navigate: "Navigate the preview browser",
preview_snapshot: "Snapshot the preview page",
preview_click: "Click in the preview browser",
preview_press: "Press a key in the preview browser",
preview_type: "Type in the preview browser",
preview_scroll: "Scroll the preview browser",
preview_resize: "Resize the preview browser",
preview_evaluate: "Evaluate script in the preview browser",
preview_wait_for: "Wait for the preview page",
preview_set_appearance: "Set preview browser appearance",
preview_recording_start: "Start recording the preview browser",
preview_recording_stop: "Stop recording the preview browser",
};
function normalizeT3McpToolLabel(value: string): string {
@@ -36,12 +50,14 @@ function resolveT3McpToolName(value: string): string | null {
const mcpMatch = /^mcp__(?<server>.+?)__(?<tool>.+)$/.exec(label);
if (mcpMatch?.groups) {
const { server, tool } = mcpMatch.groups;
return server !== undefined && tool !== undefined && T3_MCP_SERVER_ALIASES.has(server)
return server !== undefined &&
tool !== undefined &&
T3_MCP_SERVER_ALIASES.has(server.toLowerCase())
? tool
: null;
}
const namespaceMatch = /^(?<server>t3-code|t3_code|t3code)[.:/](?<tool>.+)$/.exec(label);
const namespaceMatch = /^(?<server>t3-code|t3_code|t3code)[.:/](?<tool>.+)$/i.exec(label);
if (namespaceMatch?.groups) {
return namespaceMatch.groups.tool ?? null;
}