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