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