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