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