Open History to see the last commit
1import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
2import {
3 type AssetResource,
4 type OrchestrationV2Checkpoint,
5 type OrchestrationV2ExecutionNode,
6 type OrchestrationV2PlanArtifact,
7 type OrchestrationV2ProjectedTurnItem,
8 type OrchestrationV2RunAttempt,
9 type OrchestrationV2ThreadProjection,
10 type OrchestrationV2TurnItem,
11 type PlanId,
12 type RunId,
13 type ToolActivitySurface,
14 type ToolActivityIcon,
15 type ToolActivitySource,
16 type ThreadId,
17 type TurnItemId,
18} from "@t3tools/contracts";
19import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";
20import {
21 classifyToolActivity,
22 collectToolFilePaths,
23 formatReadToolLabel,
24 formatSearchToolLabel,
25} from "@t3tools/shared/toolActivity";
26import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
27import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
28import type { McpAppReference } from "@t3tools/shared/mcpApp";
29import { htmlRenderFromToolItem, mcpAppFromToolItem } from "@t3tools/shared/toolOutput";
30import {
31 contextCompactionLabel,
32 workEntryIndicatesToolFailure,
33} from "@t3tools/client-runtime/work-log/presentation";
34import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
35import type {
36 ThreadPendingApproval,
37 ThreadPendingUserInput,
38} from "@t3tools/client-runtime/state/thread-requests";
39import type { ThreadRunSummary, ThreadRuntimeSummary } from "@t3tools/client-runtime/state/shell";
40import { threadRuntimeHasInterruptibleRun } from "@t3tools/client-runtime/state/thread-execution";
41import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation";
42
43import {
44 isImageAttachment,
45 type ChatAttachment,
46 type ChatMessage,
47 type ProposedPlan,
48 type SessionPhase,
49 type TurnDiffSummary,
50} from "./types";
51import * as DateTime from "effect/DateTime";
52import * as Equal from "effect/Equal";
53import { shallow } from "zustand/vanilla/shallow";
54
55export { formatDuration } from "@t3tools/shared/orchestrationTiming";
56export {
57 workEntryDisplayIndicatesToolFailure,
58 workEntryIndicatesToolFailure,
59} from "@t3tools/client-runtime/work-log/presentation";
60
61export type WorkLogToolLifecycleStatus =
62 | "idle"
63 | "inProgress"
64 | "completed"
65 | "failed"
66 | "declined"
67 | "stopped";
68
69export interface WorkLogEntry {
70 readonly questionAnswer?: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
71 readonly id: string;
72 readonly createdAt: string;
73 readonly runId?: RunId | null;
74 readonly label: string;
75 readonly detail?: string;
76 readonly command?: string;
77 readonly rawCommand?: string;
78 readonly changedFiles?: ReadonlyArray<string>;
79 readonly tone: "thinking" | "tool" | "info" | "error";
80 readonly toolTitle?: string;
81 readonly toolCallId?: string;
82 readonly viewedImagePath?: string;
83 readonly toolSurface?: ToolActivitySurface;
84 readonly toolIcon?: ToolActivityIcon;
85 readonly toolSource?: ToolActivitySource;
86 readonly sourceActivityKind?: string;
87 readonly taskId?: string;
88 readonly agentRole?: string;
89 readonly toolData?: unknown;
90 readonly requestKind?: string;
91 readonly itemType?: OrchestrationV2TurnItem["type"];
92 readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus;
93 readonly structuredPayload?: OrchestrationV2TurnItem;
94 readonly sourceItemType?: OrchestrationV2TurnItem["type"];
95 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
96}
97
98export type PendingApproval = ThreadPendingApproval;
99export type PendingUserInput = ThreadPendingUserInput;
100
101export interface ActivePlanState {
102 readonly createdAt: string;
103 readonly runId: RunId | null;
104 readonly explanation?: string | null;
105 readonly steps: Array<{
106 readonly step: string;
107 readonly status: "pending" | "inProgress" | "completed";
108 readonly durationMs?: number;
109 }>;
110}
111
112export interface LatestProposedPlanState {
113 readonly id: PlanId;
114 readonly createdAt: string;
115 readonly updatedAt: string;
116 readonly runId: RunId | null;
117 readonly planMarkdown: string;
118 readonly status: OrchestrationV2PlanArtifact["status"];
119}
120
121export type TimelineAttempt = Pick<
122 OrchestrationV2RunAttempt,
123 "id" | "runId" | "attemptOrdinal" | "rootNodeId" | "status" | "completedAt"
124>;
125
126export type TimelineEntry = (
127 | {
128 readonly id: string;
129 readonly kind: "message";
130 readonly createdAt: string;
131 readonly message: ChatMessage;
132 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
133 }
134 | {
135 readonly id: string;
136 readonly kind: "proposed-plan";
137 readonly createdAt: string;
138 readonly proposedPlan: ProposedPlan;
139 }
140 | {
141 readonly id: string;
142 readonly kind: "html-render";
143 readonly createdAt: string;
144 readonly runId: RunId | null;
145 readonly htmlRender: HtmlRenderReference;
146 }
147 | {
148 readonly id: string;
149 readonly kind: "mcp-app";
150 readonly createdAt: string;
151 readonly runId: RunId | null;
152 readonly sourceThreadId: ThreadId;
153 readonly itemId: TurnItemId;
154 readonly revision: string;
155 readonly mcpApp: McpAppReference;
156 }
157 | {
158 readonly id: string;
159 readonly kind: "work";
160 readonly createdAt: string;
161 readonly entry: WorkLogEntry;
162 }
163 | {
164 readonly id: string;
165 readonly kind: "event";
166 readonly createdAt: string;
167 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
168 }
169) & {
170 readonly attempt?: TimelineAttempt;
171};
172
173export function workLogEntryIsToolLike(entry: WorkLogEntry): boolean {
174 return (
175 entry.tone === "tool" ||
176 entry.tone === "thinking" ||
177 entry.tone === "error" ||
178 entry.command !== undefined ||
179 entry.requestKind !== undefined
180 );
181}
182
183export function workEntrySignalsSevereFailure(entry: WorkLogEntry): boolean {
184 return entry.itemType === "error";
185}
186
187export function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean {
188 if (
189 !workLogEntryIsToolLike(entry) ||
190 workEntryIndicatesToolFailure(entry) ||
191 (entry.tone === "thinking" && entry.itemType !== "reasoning")
192 ) {
193 return false;
194 }
195 const status = entry.toolLifecycleStatus;
196 return (
197 status !== "failed" &&
198 status !== "declined" &&
199 status !== "inProgress" &&
200 status !== "stopped" &&
201 status !== "idle"
202 );
203}
204
205export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolean {
206 return (
207 workLogEntryIsToolLike(entry) &&
208 !workEntryIndicatesToolFailure(entry) &&
209 !workEntryIndicatesToolSuccess(entry)
210 );
211}
212
213export function isLatestRunSettled(
214 latestRun: Pick<ThreadRunSummary, "runId" | "startedAt" | "completedAt" | "status"> | null,
215 runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId"> | null,
216): boolean {
217 if (latestRun === null) return false;
218 if (
219 latestRun.status === "preparing" ||
220 latestRun.status === "queued" ||
221 latestRun.status === "starting" ||
222 latestRun.status === "running" ||
223 latestRun.status === "waiting"
224 )
225 return false;
226 return runtime?.activeRunId !== latestRun.runId;
227}
228
229export function deriveActiveWorkStartedAt(
230 latestRun: Pick<
231 ThreadRunSummary,
232 "runId" | "startedAt" | "requestedAt" | "completedAt" | "status"
233 > | null,
234 runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId" | "activityStartedAt"> | null,
235 sendStartedAt: string | null,
236): string | null {
237 const startedAt = resolveThreadWorkingStartedAt({ latestRun, runtime });
238 return startedAt ?? (runtime?.activeRunId == null ? sendStartedAt : null);
239}
240
241export function derivePendingApprovals(
242 approvals: ReadonlyArray<ThreadPendingApproval>,
243): ThreadPendingApproval[] {
244 return [...approvals].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
245}
246
247export function derivePendingUserInputs(
248 inputs: ReadonlyArray<ThreadPendingUserInput>,
249): ThreadPendingUserInput[] {
250 return [...inputs].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
251}
252
253export function deriveActivePlanState(
254 projection: OrchestrationV2ThreadProjection | null,
255 latestRunId: RunId | undefined,
256): ActivePlanState | null {
257 if (projection === null) return null;
258 const plans = projection.plans
259 .filter((plan) => plan.kind === "todo_list")
260 .filter((plan) => plan.status !== "superseded");
261 const runOrdinals = new Map<RunId | null, number>(
262 projection.runs.map((run) => [run.id, run.ordinal]),
263 );
264 const plan =
265 plans.findLast((candidate) => candidate.runId === latestRunId) ??
266 plans.reduce<(typeof plans)[number] | null>(
267 (latest, candidate) =>
268 latest === null ||
269 (runOrdinals.get(candidate.runId) ?? -1) >= (runOrdinals.get(latest.runId) ?? -1)
270 ? candidate
271 : latest,
272 null,
273 );
274 if (plan === null || plan.steps.length === 0) return null;
275 return {
276 createdAt: planItemTime(projection, plan.id),
277 runId: plan.runId,
278 explanation: plan.explanation ?? null,
279 steps: plan.steps.map(({ text, status, durationMs }) => ({
280 step: text,
281 status: status === "running" ? "inProgress" : status,
282 ...(durationMs === undefined ? {} : { durationMs }),
283 })),
284 };
285}
286
287// Claude's unfinished tasks belong to the provider session, not just the turn.
288export function selectComposerTasksPlan(
289 projection: OrchestrationV2ThreadProjection | null,
290 plan: ActivePlanState | null,
291 activeRunId: RunId | null,
292 activeRunSettled: boolean,
293): ActivePlanState | null {
294 if (projection === null || plan === null) return null;
295 if (activeRunId !== null && !activeRunSettled && plan.runId === activeRunId) return plan;
296 if (plan.steps.every((step) => step.status === "completed")) return null;
297 const planProviderThreadId = projection.runs.find(
298 (run) => run.id === plan.runId,
299 )?.providerThreadId;
300 if (planProviderThreadId === undefined || planProviderThreadId === null) return null;
301 const planDriver = projection.providerThreads.find(
302 (providerThread) => providerThread.id === planProviderThreadId,
303 )?.driver;
304 if (planDriver !== "claudeAgent") return null;
305 let latestStartedRun: OrchestrationV2ThreadProjection["runs"][number] | null = null;
306 for (const run of projection.runs) {
307 if (
308 run.startedAt !== null &&
309 run.providerThreadId !== null &&
310 (latestStartedRun === null || run.ordinal > latestStartedRun.ordinal)
311 ) {
312 latestStartedRun = run;
313 }
314 }
315 return latestStartedRun?.providerThreadId === planProviderThreadId ? plan : null;
316}
317
318function planItemTime(projection: OrchestrationV2ThreadProjection, planId: PlanId): string {
319 const item = projection.turnItems.findLast(
320 (candidate) =>
321 (candidate.type === "proposed_plan" || candidate.type === "todo_list") &&
322 candidate.planId === planId,
323 );
324 return DateTime.formatIso(item?.updatedAt ?? projection.updatedAt);
325}
326
327function toLatestProposedPlanState(
328 projection: OrchestrationV2ThreadProjection,
329 plan: Extract<OrchestrationV2PlanArtifact, { readonly kind: "proposed_plan" }>,
330): LatestProposedPlanState {
331 const updatedAt = planItemTime(projection, plan.id);
332 return {
333 id: plan.id,
334 createdAt: updatedAt,
335 updatedAt,
336 runId: plan.runId,
337 planMarkdown: plan.markdown,
338 status: plan.status,
339 };
340}
341
342export function findLatestProposedPlan(
343 projection: OrchestrationV2ThreadProjection | null,
344 latestRunId: RunId | string | null | undefined,
345): LatestProposedPlanState | null {
346 if (projection === null) return null;
347 const plans = projection.plans.filter((plan) => plan.kind === "proposed_plan");
348 const candidates = latestRunId ? plans.filter((plan) => plan.runId === latestRunId) : plans;
349 const plan = [...(candidates.length > 0 ? candidates : plans)]
350 .toSorted(
351 (left, right) =>
352 planItemTime(projection, left.id).localeCompare(planItemTime(projection, right.id)) ||
353 left.id.localeCompare(right.id),
354 )
355 .at(-1);
356 return plan === undefined ? null : toLatestProposedPlanState(projection, plan);
357}
358
359export function hasActionableProposedPlan(plan: LatestProposedPlanState | null): boolean {
360 return plan?.status === "active";
361}
362
363const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"]["type"]>([
364 "fork",
365 "handoff",
366 "run_interrupt_request",
367 "run_interrupt_result",
368 "secret_request",
369 "subagent",
370]);
371
372const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
373 "fork",
374 "thread_created",
375 // Still answerable after a steer supersedes the attempt that asked.
376 "secret_request",
377]);
378
379export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean {
380 return (
381 entry.kind === "event" && PERSISTENT_RESOURCE_V2_ITEM_TYPES.has(entry.projectedItem.item.type)
382 );
383}
384
385function projectedItemCreatedAt(row: OrchestrationV2ProjectedTurnItem): string {
386 return DateTime.formatIso(row.item.startedAt ?? row.item.updatedAt);
387}
388
389function projectedWorkEntryStatus(
390 item: OrchestrationV2TurnItem,
391): NonNullable<WorkLogEntry["toolLifecycleStatus"]> {
392 switch (item.status) {
393 case "pending":
394 case "running":
395 case "waiting":
396 return "inProgress";
397 case "completed":
398 return "completed";
399 case "idle":
400 return "idle";
401 case "failed":
402 return "failed";
403 case "cancelled":
404 case "interrupted":
405 return "stopped";
406 }
407}
408
409function projectedWorkEntryTone(item: OrchestrationV2TurnItem): WorkLogEntry["tone"] {
410 if (item.type === "error") return "info";
411 if (item.type === "reasoning") return "thinking";
412 switch (item.type) {
413 case "command_execution":
414 case "file_change":
415 case "file_search":
416 case "web_search":
417 case "dynamic_tool":
418 case "subagent":
419 case "thread_created":
420 case "user_input_request":
421 case "approval_request":
422 return "tool";
423 default:
424 return "info";
425 }
426}
427
428export function providerErrorPresentation(
429 item: Extract<OrchestrationV2TurnItem, { readonly type: "error" }>,
430): { readonly label: string; readonly detail: string } {
431 if (item.retry === undefined) {
432 return {
433 label:
434 item.failure.class === "usage_limit"
435 ? "Usage limit reached"
436 : item.title?.trim() || "Provider error",
437 detail: item.failure.message,
438 };
439 }
440 const progress =
441 item.retry.maxAttempts === null
442 ? `${item.retry.attempt}`
443 : `${item.retry.attempt}/${item.retry.maxAttempts}`;
444 const label =
445 item.status === "running"
446 ? `Retrying provider (${progress})`
447 : item.status === "completed"
448 ? `Provider recovered (${progress} retries)`
449 : item.status === "failed"
450 ? `${item.failure.class === "usage_limit" ? "Usage limit reached" : "Provider error"} after ${progress} retries`
451 : `Provider retry stopped (${progress})`;
452 const retryDelay =
453 item.status === "running" && item.retry.retryDelayMs !== null && item.retry.retryDelayMs > 0
454 ? item.retry.retryDelayMs < 1_000
455 ? ` Retrying in ${item.retry.retryDelayMs}ms.`
456 : ` Retrying in ${(item.retry.retryDelayMs / 1_000).toFixed(1).replace(/\.0$/u, "")}s.`
457 : "";
458 return {
459 label,
460 detail: `${item.failure.message}${retryDelay}`,
461 };
462}
463
464function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry {
465 const { item } = row;
466 const title = item.title?.trim() || null;
467 const common = {
468 id: item.id,
469 createdAt: projectedItemCreatedAt(row),
470 runId: item.runId,
471 tone: projectedWorkEntryTone(item),
472 itemType: item.type,
473 toolLifecycleStatus: projectedWorkEntryStatus(item),
474 structuredPayload: item,
475 projectedItem: row,
476 ...extractToolActivityPresentation(item),
477 } as const;
478
479 switch (item.type) {
480 case "thread_created":
481 return {
482 ...common,
483 label: "Created thread",
484 };
485 case "compaction":
486 return {
487 ...common,
488 label: contextCompactionLabel(item),
489 sourceActivityKind: "context-compaction",
490 ...(item.summary ? { detail: item.summary } : {}),
491 };
492 case "reasoning":
493 return {
494 ...common,
495 label: title ?? "Thinking",
496 ...(item.text ? { detail: item.text } : {}),
497 };
498 case "command_execution":
499 return {
500 ...common,
501 label: title ?? "Ran command",
502 command: item.input,
503 rawCommand: item.input,
504 toolTitle: title ?? "Command",
505 toolData: item,
506 };
507 case "file_change": {
508 return {
509 ...common,
510 label:
511 title ??
512 (item.changes !== undefined && item.changes.length > 1
513 ? `Changed ${item.changes.length} files`
514 : `Changed ${item.fileName}`),
515 changedFiles: item.changes?.map((change) => change.path) ?? [item.fileName],
516 toolTitle: title ?? "File change",
517 toolData: item,
518 };
519 }
520 case "file_search":
521 return {
522 ...common,
523 label: title ?? formatSearchToolLabel(item) ?? "Searched files",
524 ...(item.pattern ? { detail: item.pattern } : {}),
525 toolTitle: title ?? "File search",
526 toolData: item,
527 };
528 case "web_search":
529 return {
530 ...common,
531 label: title ?? "Searched the web",
532 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
533 toolTitle: title ?? "Web search",
534 toolData: item,
535 };
536 case "checkpoint":
537 return {
538 ...common,
539 label: title ?? "Checkpoint captured",
540 changedFiles: item.files.map((file) => file.path),
541 toolData: item,
542 };
543 case "system_notice":
544 return {
545 ...common,
546 label: item.message,
547 sourceActivityKind: "runtime.warning",
548 };
549 case "error": {
550 const presentation = providerErrorPresentation(item);
551 return {
552 ...common,
553 ...presentation,
554 ...(item.failure.class === "usage_limit" && item.status !== "completed"
555 ? { sourceActivityKind: "runtime.warning" }
556 : item.retry === undefined
557 ? { sourceActivityKind: "runtime.error" }
558 : {}),
559 toolData: item,
560 };
561 }
562 case "dynamic_tool": {
563 const classified = classifyToolActivity({
564 itemType: "dynamic_tool_call",
565 data: { toolName: item.toolName ?? undefined, input: item.input },
566 });
567 const [readPath] = collectToolFilePaths({ input: item.input });
568 return {
569 ...common,
570 label:
571 title ??
572 (classified === "read"
573 ? formatReadToolLabel(readPath ?? "")
574 : classified === "search"
575 ? (formatSearchToolLabel({ input: item.input }) ?? item.toolName ?? "Tool call")
576 : (item.toolName ?? "Tool call")),
577 toolTitle: title ?? item.toolName ?? "Tool",
578 toolData: { input: item.input, output: item.output },
579 };
580 }
581 case "approval_request":
582 return {
583 ...common,
584 label: title ?? "Approval requested",
585 detail: item.prompt ?? item.requestKind,
586 toolData: item,
587 };
588 case "user_input_request":
589 return {
590 ...common,
591 label: title ?? (item.questionAnswer ? "Answered questions" : "Input requested"),
592 ...(item.questionAnswer ? { questionAnswer: item.questionAnswer } : {}),
593 toolData: item,
594 };
595 default:
596 return {
597 ...common,
598 label: title ?? item.type.replaceAll("_", " "),
599 toolData: item,
600 };
601 }
602}
603
604/**
605 * Builds the web timeline in the exact order committed by `visibleTurnItems`. Persistent
606 * client-owned messages are inserted by timestamp without sorting the canonical sequence.
607 */
608export interface TimelineEntriesInput {
609 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
610 readonly optimisticMessages: ReadonlyArray<ChatMessage>;
611 readonly anchoredMessages?: ReadonlyArray<ChatMessage>;
612 readonly attachmentUrlById?: ReadonlyMap<string, string>;
613 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
614 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
615 readonly plans?: ReadonlyArray<OrchestrationV2PlanArtifact>;
616}
617
618export interface TimelineEntriesProjection {
619 readonly input: TimelineEntriesInput;
620 readonly entries: TimelineEntry[];
621}
622
623export function deriveTimelineEntriesFromVisibleTurnItems(
624 input: TimelineEntriesInput,
625): TimelineEntry[] {
626 const committedMessageIds = new Set<string>();
627 const entries: TimelineEntry[] = [];
628 const attemptByRootNodeId = new Map(
629 (input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
630 );
631 const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const));
632 const planById = new Map((input.plans ?? []).map((plan) => [plan.id, plan] as const));
633
634 const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => {
635 if (item.nodeId === null || item.runId === null) return undefined;
636 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
637 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
638 while (nodeId !== null && !visited.has(nodeId)) {
639 visited.add(nodeId);
640 const directAttempt = attemptByRootNodeId.get(nodeId);
641 if (directAttempt?.runId === item.runId) return directAttempt;
642 const node = nodeById.get(nodeId);
643 if (node === undefined) return undefined;
644 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
645 if (rootAttempt?.runId === item.runId) return rootAttempt;
646 nodeId = node.parentNodeId;
647 }
648 return undefined;
649 };
650
651 const foldedAnswerMessageIds = new Set(
652 input.visibleTurnItems.flatMap(({ item }) =>
653 item.type === "user_input_request" && item.questionAnswer
654 ? [`async-answer:${item.questionAnswer.requestId}`]
655 : [],
656 ),
657 );
658 for (const row of input.visibleTurnItems) {
659 const { item } = row;
660 if (turnItemIsWorkspacePreparation(item)) continue;
661 if (item.type === "todo_list" || item.type === "checkpoint") continue;
662 if (item.type === "user_message" && foldedAnswerMessageIds.has(item.messageId)) continue;
663 const createdAt = projectedItemCreatedAt(row);
664 const attempt = resolveAttempt(item);
665 const attemptMetadata = attempt === undefined ? {} : { attempt };
666 if (item.type === "notification") {
667 entries.push({
668 id: item.id,
669 kind: "work",
670 createdAt,
671 entry: {
672 id: item.id,
673 createdAt,
674 runId: item.runId,
675 label: item.summary,
676 tone: "info",
677 itemType: item.type,
678 structuredPayload: item,
679 projectedItem: row,
680 },
681 ...attemptMetadata,
682 });
683 continue;
684 }
685 if (item.type === "user_message" || item.type === "assistant_message") {
686 const message: ChatMessage = {
687 id: item.messageId,
688 role: item.type === "user_message" ? "user" : "assistant",
689 text: item.text,
690 ...(item.type === "user_message" && item.context ? { context: item.context } : {}),
691 ...((item.attachments?.length ?? 0) > 0
692 ? {
693 attachments: (item.attachments ?? []).map((attachment) => {
694 const previewUrl = input.attachmentUrlById?.get(attachment.id);
695 return previewUrl ? { ...attachment, previewUrl } : attachment;
696 }),
697 }
698 : {}),
699 runId: item.runId,
700 streaming: item.type === "assistant_message" && item.streaming,
701 ...(item.type === "user_message"
702 ? {
703 createdBy: item.createdBy,
704 creationSource: item.creationSource,
705 ...(item.senderThreadId !== undefined ? { senderThreadId: item.senderThreadId } : {}),
706 ...(item.scheduledTaskId !== undefined
707 ? { scheduledTaskId: item.scheduledTaskId }
708 : {}),
709 }
710 : {}),
711 createdAt,
712 updatedAt: DateTime.formatIso(item.updatedAt),
713 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
714 };
715 committedMessageIds.add(message.id);
716 entries.push({
717 id: message.id,
718 kind: "message",
719 createdAt,
720 message,
721 projectedItem: row,
722 ...attemptMetadata,
723 });
724 continue;
725 }
726
727 if (item.type === "proposed_plan") {
728 const plan = planById.get(item.planId);
729 const proposedPlan = {
730 id: item.planId,
731 runId: item.runId,
732 planMarkdown: item.markdown,
733 status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
734 createdAt,
735 updatedAt: DateTime.formatIso(item.updatedAt),
736 };
737 entries.push({
738 id: item.id,
739 kind: "proposed-plan",
740 createdAt,
741 proposedPlan,
742 ...attemptMetadata,
743 });
744 continue;
745 }
746
747 const htmlRender =
748 item.type === "dynamic_tool" && item.status === "completed"
749 ? htmlRenderFromToolItem(item)
750 : undefined;
751 if (htmlRender !== undefined) {
752 entries.push({
753 id: item.id,
754 kind: "html-render",
755 createdAt,
756 runId: item.runId,
757 htmlRender,
758 ...attemptMetadata,
759 });
760 continue;
761 }
762
763 const mcpApp =
764 item.type === "dynamic_tool" && item.status === "completed"
765 ? mcpAppFromToolItem(item)
766 : undefined;
767 if (mcpApp !== undefined) {
768 entries.push({
769 id: item.id,
770 kind: "mcp-app",
771 createdAt,
772 runId: item.runId,
773 sourceThreadId: row.sourceThreadId,
774 itemId: row.sourceItemId,
775 revision: turnItemDetailRevision(item),
776 mcpApp,
777 ...attemptMetadata,
778 });
779 continue;
780 }
781
782 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
783 entries.push({
784 id: item.id,
785 kind: "event",
786 createdAt,
787 projectedItem: row,
788 ...attemptMetadata,
789 });
790 continue;
791 }
792
793 entries.push({
794 id: item.id,
795 kind: "work",
796 createdAt,
797 entry: projectedWorkEntry(row),
798 ...attemptMetadata,
799 });
800 }
801
802 const retainedMessageIds = new Set([...committedMessageIds, ...foldedAnswerMessageIds]);
803 for (const message of input.anchoredMessages ?? []) {
804 if (retainedMessageIds.has(message.id)) continue;
805 retainedMessageIds.add(message.id);
806 const entry: TimelineEntry = {
807 id: message.id,
808 kind: "message",
809 createdAt: message.createdAt,
810 message,
811 };
812 const insertionIndex = entries.findIndex(
813 (candidate) => candidate.createdAt > message.createdAt,
814 );
815 if (insertionIndex === -1) {
816 entries.push(entry);
817 } else {
818 entries.splice(insertionIndex, 0, entry);
819 }
820 }
821
822 for (const message of input.optimisticMessages) {
823 if (message.inputIntent !== "queued_turn" && !retainedMessageIds.has(message.id)) {
824 retainedMessageIds.add(message.id);
825 entries.push({
826 id: message.id,
827 kind: "message",
828 createdAt: message.createdAt,
829 message,
830 });
831 }
832 }
833
834 return entries;
835}
836
837type AttachmentResource = Extract<AssetResource, { readonly _tag: "attachment" }>;
838const EMPTY_IMAGE_RESOURCES = Object.freeze<ReadonlyArray<AttachmentResource>>([]);
839
840export function selectMessageImageResources(
841 attachments: ChatMessage["attachments"],
842): ReadonlyArray<AttachmentResource> {
843 const attachmentIds = new Set<string>();
844 for (const attachment of attachments ?? []) {
845 if (!isImageAttachment(attachment)) continue;
846 const previewUrl = attachment.previewUrl;
847 if (previewUrl?.startsWith("blob:") || previewUrl?.startsWith("data:")) continue;
848 attachmentIds.add(attachment.id);
849 }
850 return attachmentIds.size === 0
851 ? EMPTY_IMAGE_RESOURCES
852 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
853}
854
855export function selectHandoffImageResources(
856 messages: ReadonlyArray<Pick<ChatMessage, "id" | "role" | "attachments">> | undefined,
857 handoffs: Readonly<Record<string, ReadonlyArray<string>>>,
858): ReadonlyArray<AttachmentResource> {
859 if (Object.keys(handoffs).length === 0) return EMPTY_IMAGE_RESOURCES;
860 const attachmentIds = new Set<string>();
861 for (const message of messages ?? []) {
862 if (message.role !== "user" || !handoffs[message.id]?.length) continue;
863 for (const attachment of message.attachments ?? []) {
864 if (isImageAttachment(attachment)) attachmentIds.add(attachment.id);
865 }
866 }
867 return attachmentIds.size === 0
868 ? EMPTY_IMAGE_RESOURCES
869 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
870}
871
872export function createMessageAttachmentPreviewProjector() {
873 const attachmentsBySource = new WeakMap<
874 ReadonlyArray<ChatAttachment>,
875 ReadonlyArray<ChatAttachment>
876 >();
877 const messagesBySource = new WeakMap<ChatMessage, ChatMessage>();
878 return (
879 message: ChatMessage,
880 previewUrlFor: (attachment: ChatAttachment) => string | undefined,
881 ): ChatMessage => {
882 const source = message.attachments;
883 if (!source || source.length === 0) return message;
884 const previous = attachmentsBySource.get(source) ?? source;
885 let changed: ChatAttachment[] | undefined;
886 let hasOverrides = false;
887 for (const [index, attachment] of source.entries()) {
888 const previewUrl = previewUrlFor(attachment);
889 const sourceUrl = "previewUrl" in attachment ? attachment.previewUrl : undefined;
890 const previousAttachment = previous[index]!;
891 const previousUrl =
892 "previewUrl" in previousAttachment ? previousAttachment.previewUrl : undefined;
893 const next =
894 !previewUrl || previewUrl === sourceUrl
895 ? attachment
896 : previewUrl === previousUrl
897 ? previousAttachment
898 : { ...attachment, previewUrl };
899 hasOverrides ||= next !== attachment;
900 if (next !== previousAttachment) {
901 changed ??= previous.slice();
902 changed[index] = next;
903 }
904 }
905 const attachments = hasOverrides ? (changed ?? previous) : source;
906 attachmentsBySource.set(source, attachments);
907 if (attachments === source) {
908 messagesBySource.delete(message);
909 return message;
910 }
911 const previousMessage = messagesBySource.get(message);
912 if (previousMessage?.attachments === attachments) return previousMessage;
913 const result = { ...message, attachments };
914 messagesBySource.set(message, result);
915 return result;
916 };
917}
918
919export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
920 if (
921 previous.role !== "assistant" ||
922 next.role !== "assistant" ||
923 !previous.streaming ||
924 !next.streaming
925 ) {
926 return false;
927 }
928 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previous;
929 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = next;
930 return shallow(previousMetadata, nextMetadata);
931}
932
933export function isStreamingTurnItemTextUpdate(
934 previous: OrchestrationV2ProjectedTurnItem,
935 next: OrchestrationV2ProjectedTurnItem,
936): boolean {
937 const { item: previousItem, ...previousSource } = previous;
938 const { item: nextItem, ...nextSource } = next;
939 if (
940 previousItem.type !== "assistant_message" ||
941 nextItem.type !== "assistant_message" ||
942 !previousItem.streaming ||
943 !nextItem.streaming ||
944 !shallow(previousSource, nextSource) ||
945 projectedItemCreatedAt(previous) !== projectedItemCreatedAt(next)
946 ) {
947 return false;
948 }
949 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previousItem;
950 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = nextItem;
951 // Wire decoding can recreate timestamps and attachments on each update.
952 // Compare only the changed item's metadata, never the entire transcript.
953 return Equal.equals(previousMetadata, nextMetadata);
954}
955
956function reuseTimelineEntries(
957 input: TimelineEntriesInput,
958 previous: TimelineEntriesProjection,
959): TimelineEntry[] | null {
960 const before = previous.input;
961 if (
962 input.visibleTurnItems.length < before.visibleTurnItems.length ||
963 !shallow(input.optimisticMessages, before.optimisticMessages) ||
964 !shallow(input.anchoredMessages, before.anchoredMessages) ||
965 !shallow(input.attachmentUrlById, before.attachmentUrlById) ||
966 !shallow(input.attempts, before.attempts) ||
967 !shallow(input.nodes, before.nodes) ||
968 !shallow(input.plans, before.plans)
969 ) {
970 return null;
971 }
972 const appended = input.visibleTurnItems.length > before.visibleTurnItems.length;
973 // Anchored and optimistic messages need to be interleaved/deduplicated when
974 // committed items arrive. Keep the full projection for that transition.
975 if (
976 appended &&
977 (input.optimisticMessages.length > 0 || (input.anchoredMessages?.length ?? 0) > 0)
978 ) {
979 return null;
980 }
981 // Answer rows can replace a message already present in the retained prefix.
982 if (
983 appended &&
984 input.visibleTurnItems
985 .slice(before.visibleTurnItems.length)
986 .some(
987 ({ item }) =>
988 (item.type === "user_input_request" && item.questionAnswer !== undefined) ||
989 (item.type === "user_message" && item.messageId.startsWith("async-answer:")),
990 )
991 )
992 return null;
993 const replacements = new Map<
994 OrchestrationV2ProjectedTurnItem,
995 OrchestrationV2ProjectedTurnItem
996 >();
997 for (const [index, previousItem] of before.visibleTurnItems.entries()) {
998 const item = input.visibleTurnItems[index]!;
999 if (item === previousItem) continue;
1000 if (!isStreamingTurnItemTextUpdate(previousItem, item)) return null;
1001 replacements.set(previousItem, item);
1002 }
1003 if (replacements.size === 0 && !appended) return previous.entries;
1004 const entries = previous.entries.map((entry): TimelineEntry => {
1005 const row =
1006 entry.kind === "message" && entry.projectedItem !== undefined
1007 ? replacements.get(entry.projectedItem)
1008 : undefined;
1009 if (entry.kind !== "message" || row?.item.type !== "assistant_message") return entry;
1010 return {
1011 ...entry,
1012 projectedItem: row,
1013 message: {
1014 ...entry.message,
1015 text: row.item.text,
1016 updatedAt: DateTime.formatIso(row.item.updatedAt),
1017 },
1018 };
1019 });
1020 if (appended) {
1021 entries.push(
1022 ...deriveTimelineEntriesFromVisibleTurnItems({
1023 ...input,
1024 visibleTurnItems: input.visibleTurnItems.slice(before.visibleTurnItems.length),
1025 }),
1026 );
1027 }
1028 return entries;
1029}
1030
1031export function deriveTimelineEntriesFromVisibleTurnItemsWithState(
1032 input: TimelineEntriesInput,
1033 previous: TimelineEntriesProjection | null = null,
1034): TimelineEntriesProjection {
1035 const reused = previous === null ? null : reuseTimelineEntries(input, previous);
1036 if (reused !== null) return { input, entries: reused };
1037 const entries = deriveTimelineEntriesFromVisibleTurnItems(input);
1038 if (previous === null || !shallow(input.attachmentUrlById, previous.input.attachmentUrlById)) {
1039 return { input, entries };
1040 }
1041 const previousMessages = new Map(
1042 previous.entries.flatMap((entry) =>
1043 entry.kind === "message" ? [[entry.id, entry] as const] : [],
1044 ),
1045 );
1046 return {
1047 input,
1048 entries: entries.map((entry) => {
1049 if (entry.kind !== "message" || entry.projectedItem === undefined) return entry;
1050 const before = previousMessages.get(entry.id);
1051 if (before?.projectedItem !== entry.projectedItem) return entry;
1052 return before.attempt === entry.attempt ? before : { ...entry, message: before.message };
1053 }),
1054 };
1055}
1056
1057// Run ordinals keep increasing after a rewind; only visible local runs define predecessors.
1058export function deriveRevertTurnCountByUserMessageId(input: {
1059 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
1060 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
1061 readonly threadStartCheckpointReady: boolean;
1062 readonly availableRevertTurnCounts?: ReadonlySet<number> | undefined;
1063 readonly unsettledRunId?: RunId | null;
1064}): Map<ChatMessage["id"], number> {
1065 const readyTurnCountByRunId = new Map<RunId, number>();
1066 for (const checkpoint of input.checkpoints) {
1067 if (checkpoint.status === "ready") {
1068 readyTurnCountByRunId.set(checkpoint.runId, checkpoint.checkpointTurnCount);
1069 }
1070 }
1071 const targetByRunId = new Map<RunId, number | undefined>();
1072 const byUserMessageId = new Map<ChatMessage["id"], number>();
1073 let previousRunId: RunId | null = null;
1074 for (const entry of input.timelineEntries) {
1075 // Inherited history belongs to the source thread, not our checkpoint scope.
1076 if (entry.kind !== "message" && entry.kind !== "work") continue;
1077 const projectedItem =
1078 entry.kind === "message" ? entry.projectedItem : entry.entry.projectedItem;
1079 if (projectedItem?.visibility === "inherited") continue;
1080 const runId =
1081 entry.kind === "message"
1082 ? entry.message.runId
1083 : entry.entry.itemType === "notification"
1084 ? entry.entry.runId
1085 : null;
1086 if (runId == null) continue;
1087 if (!targetByRunId.has(runId)) {
1088 targetByRunId.set(
1089 runId,
1090 previousRunId === null
1091 ? input.threadStartCheckpointReady
1092 ? 0
1093 : undefined
1094 : readyTurnCountByRunId.get(previousRunId),
1095 );
1096 previousRunId = runId;
1097 }
1098 if (entry.kind !== "message") continue;
1099 const { message } = entry;
1100 if (message.role !== "user" || message.runId === input.unsettledRunId) continue;
1101 if (message.inputIntent !== "turn_start" && message.inputIntent !== "queued_turn") continue;
1102 const target = targetByRunId.get(runId);
1103 if (
1104 target !== undefined &&
1105 (input.availableRevertTurnCounts === undefined || input.availableRevertTurnCounts.has(target))
1106 )
1107 byUserMessageId.set(message.id, target);
1108 }
1109 return byUserMessageId;
1110}
1111
1112export function findRevertCheckpoint(
1113 checkpoints: ReadonlyArray<OrchestrationV2Checkpoint>,
1114 turnCount: number,
1115): OrchestrationV2Checkpoint | undefined {
1116 return checkpoints.findLast(
1117 (checkpoint) =>
1118 checkpoint.status === "ready" &&
1119 (turnCount === 0
1120 ? checkpoint.ordinalWithinScope === 0 && checkpoint.appRunOrdinal === null
1121 : checkpoint.appRunOrdinal === turnCount),
1122 );
1123}
1124
1125export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase {
1126 if (runtime === null) return "disconnected";
1127 if (
1128 runtime.status === "preparing" ||
1129 runtime.status === "starting" ||
1130 runtime.status === "queued"
1131 )
1132 return "connecting";
1133 if (runtime.status === "running" || runtime.status === "waiting") return "running";
1134 return "ready";
1135}
1136
1137/**
1138 * The server settles a preparing or starting run on `run.interrupt`
1139 * (Orchestrator.dispatchRunInterrupt), so Stop must not wait for the phase to reach "running".
1140 */
1141export function deriveCanInterruptRunningThread(
1142 hasActiveThread: boolean,
1143 runtime: ThreadRuntimeSummary | null,
1144): boolean {
1145 return (
1146 hasActiveThread &&
1147 (derivePhase(runtime) === "running" || threadRuntimeHasInterruptibleRun(runtime))
1148 );
1149}
1150
1151export type { TurnDiffSummary };