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