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 "subagent",
304]);
305
306const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
307 "fork",
308 "thread_created",
309 // Still answerable after a steer supersedes the attempt that asked.
310 "secret_request",
311]);
312
313export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean {
314 return (
315 entry.kind === "event" && PERSISTENT_RESOURCE_V2_ITEM_TYPES.has(entry.projectedItem.item.type)
316 );
317}
318
319function projectedItemCreatedAt(row: OrchestrationV2ProjectedTurnItem): string {
320 return DateTime.formatIso(row.item.startedAt ?? row.item.updatedAt);
321}
322
323function projectedWorkEntryStatus(
324 item: OrchestrationV2TurnItem,
325): NonNullable<WorkLogEntry["toolLifecycleStatus"]> {
326 switch (item.status) {
327 case "pending":
328 case "running":
329 case "waiting":
330 return "inProgress";
331 case "completed":
332 return "completed";
333 case "idle":
334 return "idle";
335 case "failed":
336 return "failed";
337 case "cancelled":
338 case "interrupted":
339 return "stopped";
340 }
341}
342
343function projectedWorkEntryTone(item: OrchestrationV2TurnItem): WorkLogEntry["tone"] {
344 if (item.type === "error") return "info";
345 if (item.type === "reasoning") return "thinking";
346 switch (item.type) {
347 case "command_execution":
348 case "file_change":
349 case "file_search":
350 case "web_search":
351 case "dynamic_tool":
352 case "subagent":
353 case "thread_created":
354 case "user_input_request":
355 case "approval_request":
356 return "tool";
357 default:
358 return "info";
359 }
360}
361
362export function providerErrorPresentation(
363 item: Extract<OrchestrationV2TurnItem, { readonly type: "error" }>,
364): { readonly label: string; readonly detail: string } {
365 if (item.retry === undefined) {
366 return {
367 label:
368 item.failure.class === "usage_limit"
369 ? "Usage limit reached"
370 : item.title?.trim() || "Provider error",
371 detail: item.failure.message,
372 };
373 }
374 const progress =
375 item.retry.maxAttempts === null
376 ? `${item.retry.attempt}`
377 : `${item.retry.attempt}/${item.retry.maxAttempts}`;
378 const label =
379 item.status === "running"
380 ? `Retrying provider (${progress})`
381 : item.status === "completed"
382 ? `Provider recovered (${progress} retries)`
383 : item.status === "failed"
384 ? `${item.failure.class === "usage_limit" ? "Usage limit reached" : "Provider error"} after ${progress} retries`
385 : `Provider retry stopped (${progress})`;
386 const retryDelay =
387 item.status === "running" && item.retry.retryDelayMs !== null && item.retry.retryDelayMs > 0
388 ? item.retry.retryDelayMs < 1_000
389 ? ` Retrying in ${item.retry.retryDelayMs}ms.`
390 : ` Retrying in ${(item.retry.retryDelayMs / 1_000).toFixed(1).replace(/\.0$/u, "")}s.`
391 : "";
392 return {
393 label,
394 detail: `${item.failure.message}${retryDelay}`,
395 };
396}
397
398function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry {
399 const { item } = row;
400 const title = item.title?.trim() || null;
401 const common = {
402 id: item.id,
403 createdAt: projectedItemCreatedAt(row),
404 runId: item.runId,
405 tone: projectedWorkEntryTone(item),
406 itemType: item.type,
407 toolLifecycleStatus: projectedWorkEntryStatus(item),
408 structuredPayload: item,
409 projectedItem: row,
410 ...extractToolActivityPresentation(item),
411 } as const;
412
413 switch (item.type) {
414 case "thread_created":
415 return {
416 ...common,
417 label: "Created thread",
418 };
419 case "compaction":
420 return {
421 ...common,
422 label: contextCompactionLabel(item),
423 sourceActivityKind: "context-compaction",
424 ...(item.summary ? { detail: item.summary } : {}),
425 };
426 case "reasoning":
427 return {
428 ...common,
429 label: title ?? "Thinking",
430 ...(item.text ? { detail: item.text } : {}),
431 };
432 case "command_execution":
433 return {
434 ...common,
435 label: title ?? "Ran command",
436 command: item.input,
437 rawCommand: item.input,
438 toolTitle: title ?? "Command",
439 toolData: item,
440 };
441 case "file_change": {
442 return {
443 ...common,
444 label:
445 title ??
446 (item.changes !== undefined && item.changes.length > 1
447 ? `Changed ${item.changes.length} files`
448 : `Changed ${item.fileName}`),
449 changedFiles: item.changes?.map((change) => change.path) ?? [item.fileName],
450 toolTitle: title ?? "File change",
451 toolData: item,
452 };
453 }
454 case "file_search":
455 return {
456 ...common,
457 label: title ?? formatSearchToolLabel(item) ?? "Searched files",
458 ...(item.pattern ? { detail: item.pattern } : {}),
459 toolTitle: title ?? "File search",
460 toolData: item,
461 };
462 case "web_search":
463 return {
464 ...common,
465 label: title ?? "Searched the web",
466 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
467 toolTitle: title ?? "Web search",
468 toolData: item,
469 };
470 case "checkpoint":
471 return {
472 ...common,
473 label: title ?? "Checkpoint captured",
474 changedFiles: item.files.map((file) => file.path),
475 toolData: item,
476 };
477 case "system_notice":
478 return {
479 ...common,
480 label: item.message,
481 sourceActivityKind: "runtime.warning",
482 };
483 case "error": {
484 const presentation = providerErrorPresentation(item);
485 return {
486 ...common,
487 ...presentation,
488 ...(item.failure.class === "usage_limit" && item.status !== "completed"
489 ? { sourceActivityKind: "runtime.warning" }
490 : item.retry === undefined
491 ? { sourceActivityKind: "runtime.error" }
492 : {}),
493 toolData: item,
494 };
495 }
496 case "dynamic_tool": {
497 const classified = classifyToolActivity({
498 itemType: "dynamic_tool_call",
499 data: { toolName: item.toolName ?? undefined, input: item.input },
500 });
501 const [readPath] = collectToolFilePaths({ input: item.input });
502 return {
503 ...common,
504 label:
505 title ??
506 (classified === "read"
507 ? formatReadToolLabel(readPath ?? "")
508 : classified === "search"
509 ? (formatSearchToolLabel({ input: item.input }) ?? item.toolName ?? "Tool call")
510 : (item.toolName ?? "Tool call")),
511 toolTitle: title ?? item.toolName ?? "Tool",
512 toolData: { input: item.input, output: item.output },
513 };
514 }
515 case "todo_list": {
516 // Each todo update is a quiet row where the agent wrote it; it opens to every step.
517 const done = item.steps.filter((step) => step.status === "completed").length;
518 const current =
519 item.steps.find((step) => step.status === "running") ??
520 item.steps.find((step) => step.status === "pending");
521 return {
522 ...common,
523 label: `Tasks ${done}/${item.steps.length}${current ? ` · ${current.text}` : ""}`,
524 };
525 }
526 case "approval_request":
527 return {
528 ...common,
529 label: title ?? "Approval requested",
530 detail: item.prompt ?? item.requestKind,
531 toolData: item,
532 };
533 case "user_input_request":
534 return {
535 ...common,
536 label: title ?? (item.questionAnswer ? "Answered questions" : "Input requested"),
537 ...(item.questionAnswer ? { questionAnswer: item.questionAnswer } : {}),
538 toolData: item,
539 };
540 default:
541 return {
542 ...common,
543 label: title ?? item.type.replaceAll("_", " "),
544 toolData: item,
545 };
546 }
547}
548
549/** Preserve visibleTurnItems' committed order; interleave client messages by timestamp. */
550export interface TimelineEntriesInput {
551 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
552 readonly optimisticMessages: ReadonlyArray<ChatMessage>;
553 readonly anchoredMessages?: ReadonlyArray<ChatMessage>;
554 readonly attachmentUrlById?: ReadonlyMap<string, string>;
555 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
556 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
557 readonly plans?: ReadonlyArray<OrchestrationV2PlanArtifact>;
558}
559
560export interface TimelineEntriesProjection {
561 readonly input: TimelineEntriesInput;
562 readonly entries: TimelineEntry[];
563}
564
565export function deriveTimelineEntriesFromVisibleTurnItems(
566 input: TimelineEntriesInput,
567): TimelineEntry[] {
568 const committedMessageIds = new Set<string>();
569 const entries: TimelineEntry[] = [];
570 const attemptByRootNodeId = new Map(
571 (input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
572 );
573 const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const));
574 const planById = new Map((input.plans ?? []).map((plan) => [plan.id, plan] as const));
575
576 const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => {
577 if (item.nodeId === null || item.runId === null) return undefined;
578 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
579 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
580 while (nodeId !== null && !visited.has(nodeId)) {
581 visited.add(nodeId);
582 const directAttempt = attemptByRootNodeId.get(nodeId);
583 if (directAttempt?.runId === item.runId) return directAttempt;
584 const node = nodeById.get(nodeId);
585 if (node === undefined) return undefined;
586 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
587 if (rootAttempt?.runId === item.runId) return rootAttempt;
588 nodeId = node.parentNodeId;
589 }
590 return undefined;
591 };
592
593 const foldedAnswerMessageIds = new Set(
594 input.visibleTurnItems.flatMap(({ item }) =>
595 item.type === "user_input_request" && item.questionAnswer
596 ? [`async-answer:${item.questionAnswer.requestId}`]
597 : [],
598 ),
599 );
600 for (const row of input.visibleTurnItems) {
601 const { item } = row;
602 if (turnItemIsWorkspacePreparation(item)) continue;
603 if (item.type === "checkpoint") continue;
604 if (item.type === "user_message" && foldedAnswerMessageIds.has(item.messageId)) continue;
605 const createdAt = projectedItemCreatedAt(row);
606 const attempt = resolveAttempt(item);
607 const attemptMetadata = attempt === undefined ? {} : { attempt };
608 if (item.type === "notification") {
609 entries.push({
610 id: item.id,
611 kind: "work",
612 createdAt,
613 entry: {
614 id: item.id,
615 createdAt,
616 runId: item.runId,
617 label: item.summary,
618 tone: "info",
619 itemType: item.type,
620 structuredPayload: item,
621 projectedItem: row,
622 },
623 ...attemptMetadata,
624 });
625 continue;
626 }
627 if (item.type === "user_message" || item.type === "assistant_message") {
628 const message: ChatMessage = {
629 id: item.messageId,
630 role: item.type === "user_message" ? "user" : "assistant",
631 text: item.text,
632 ...(item.type === "user_message" && item.context ? { context: item.context } : {}),
633 ...((item.attachments?.length ?? 0) > 0
634 ? {
635 attachments: (item.attachments ?? []).map((attachment) => {
636 const previewUrl = input.attachmentUrlById?.get(attachment.id);
637 return previewUrl ? { ...attachment, previewUrl } : attachment;
638 }),
639 }
640 : {}),
641 runId: item.runId,
642 streaming: item.type === "assistant_message" && item.streaming,
643 ...(item.type === "user_message"
644 ? {
645 createdBy: item.createdBy,
646 creationSource: item.creationSource,
647 ...(item.senderThreadId !== undefined ? { senderThreadId: item.senderThreadId } : {}),
648 ...(item.idleCompaction !== undefined ? { idleCompaction: item.idleCompaction } : {}),
649 ...(item.scheduledTaskId !== undefined
650 ? { scheduledTaskId: item.scheduledTaskId }
651 : {}),
652 }
653 : {}),
654 createdAt,
655 updatedAt: DateTime.formatIso(item.updatedAt),
656 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
657 };
658 committedMessageIds.add(message.id);
659 entries.push({
660 id: message.id,
661 kind: "message",
662 createdAt,
663 message,
664 projectedItem: row,
665 ...attemptMetadata,
666 });
667 continue;
668 }
669
670 if (item.type === "proposed_plan") {
671 const plan = planById.get(item.planId);
672 const proposedPlan = {
673 id: item.planId,
674 runId: item.runId,
675 planMarkdown: item.markdown,
676 status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
677 createdAt,
678 updatedAt: DateTime.formatIso(item.updatedAt),
679 };
680 entries.push({
681 id: item.id,
682 kind: "proposed-plan",
683 createdAt,
684 proposedPlan,
685 ...attemptMetadata,
686 });
687 continue;
688 }
689
690 const htmlRender =
691 item.type === "dynamic_tool" && item.status === "completed"
692 ? htmlRenderFromToolItem(item)
693 : undefined;
694 if (htmlRender !== undefined) {
695 entries.push({
696 id: item.id,
697 kind: "html-render",
698 createdAt,
699 runId: item.runId,
700 htmlRender,
701 ...attemptMetadata,
702 });
703 continue;
704 }
705
706 const mcpApp =
707 item.type === "dynamic_tool" && item.status === "completed"
708 ? mcpAppFromToolItem(item)
709 : undefined;
710 if (mcpApp !== undefined) {
711 entries.push({
712 id: item.id,
713 kind: "mcp-app",
714 createdAt,
715 runId: item.runId,
716 sourceThreadId: row.sourceThreadId,
717 itemId: row.sourceItemId,
718 revision: turnItemDetailRevision(item),
719 mcpApp,
720 ...attemptMetadata,
721 });
722 continue;
723 }
724
725 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
726 entries.push({
727 id: item.id,
728 kind: "event",
729 createdAt,
730 projectedItem: row,
731 ...attemptMetadata,
732 });
733 continue;
734 }
735
736 entries.push({
737 id: item.id,
738 kind: "work",
739 createdAt,
740 entry: projectedWorkEntry(row),
741 ...attemptMetadata,
742 });
743 }
744
745 const retainedMessageIds = new Set([...committedMessageIds, ...foldedAnswerMessageIds]);
746 for (const message of input.anchoredMessages ?? []) {
747 if (retainedMessageIds.has(message.id)) continue;
748 retainedMessageIds.add(message.id);
749 const entry: TimelineEntry = {
750 id: message.id,
751 kind: "message",
752 createdAt: message.createdAt,
753 message,
754 };
755 const insertionIndex = entries.findIndex(
756 (candidate) => candidate.createdAt > message.createdAt,
757 );
758 if (insertionIndex === -1) {
759 entries.push(entry);
760 } else {
761 entries.splice(insertionIndex, 0, entry);
762 }
763 }
764
765 for (const message of input.optimisticMessages) {
766 if (message.inputIntent !== "queued_turn" && !retainedMessageIds.has(message.id)) {
767 retainedMessageIds.add(message.id);
768 entries.push({
769 id: message.id,
770 kind: "message",
771 createdAt: message.createdAt,
772 message,
773 });
774 }
775 }
776
777 return entries;
778}
779
780type AttachmentResource = Extract<AssetResource, { readonly _tag: "attachment" }>;
781const EMPTY_IMAGE_RESOURCES = Object.freeze<ReadonlyArray<AttachmentResource>>([]);
782
783export function selectMessageImageResources(
784 attachments: ChatMessage["attachments"],
785): ReadonlyArray<AttachmentResource> {
786 const attachmentIds = new Set<string>();
787 for (const attachment of attachments ?? []) {
788 if (!isImageAttachment(attachment)) continue;
789 const previewUrl = attachment.previewUrl;
790 if (previewUrl?.startsWith("blob:") || previewUrl?.startsWith("data:")) continue;
791 attachmentIds.add(attachment.id);
792 }
793 return attachmentIds.size === 0
794 ? EMPTY_IMAGE_RESOURCES
795 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
796}
797
798export function selectHandoffImageResources(
799 messages: ReadonlyArray<Pick<ChatMessage, "id" | "role" | "attachments">> | undefined,
800 handoffs: Readonly<Record<string, ReadonlyArray<string>>>,
801): ReadonlyArray<AttachmentResource> {
802 if (Object.keys(handoffs).length === 0) return EMPTY_IMAGE_RESOURCES;
803 const attachmentIds = new Set<string>();
804 for (const message of messages ?? []) {
805 if (message.role !== "user" || !handoffs[message.id]?.length) continue;
806 for (const attachment of message.attachments ?? []) {
807 if (isImageAttachment(attachment)) attachmentIds.add(attachment.id);
808 }
809 }
810 return attachmentIds.size === 0
811 ? EMPTY_IMAGE_RESOURCES
812 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
813}
814
815export function createMessageAttachmentPreviewProjector() {
816 const attachmentsBySource = new WeakMap<
817 ReadonlyArray<ChatAttachment>,
818 ReadonlyArray<ChatAttachment>
819 >();
820 const messagesBySource = new WeakMap<ChatMessage, ChatMessage>();
821 return (
822 message: ChatMessage,
823 previewUrlFor: (attachment: ChatAttachment) => string | undefined,
824 ): ChatMessage => {
825 const source = message.attachments;
826 if (!source || source.length === 0) return message;
827 const previous = attachmentsBySource.get(source) ?? source;
828 let changed: ChatAttachment[] | undefined;
829 let hasOverrides = false;
830 for (const [index, attachment] of source.entries()) {
831 const previewUrl = previewUrlFor(attachment);
832 const sourceUrl = "previewUrl" in attachment ? attachment.previewUrl : undefined;
833 const previousAttachment = previous[index]!;
834 const previousUrl =
835 "previewUrl" in previousAttachment ? previousAttachment.previewUrl : undefined;
836 const next =
837 !previewUrl || previewUrl === sourceUrl
838 ? attachment
839 : previewUrl === previousUrl
840 ? previousAttachment
841 : { ...attachment, previewUrl };
842 hasOverrides ||= next !== attachment;
843 if (next !== previousAttachment) {
844 changed ??= previous.slice();
845 changed[index] = next;
846 }
847 }
848 const attachments = hasOverrides ? (changed ?? previous) : source;
849 attachmentsBySource.set(source, attachments);
850 if (attachments === source) {
851 messagesBySource.delete(message);
852 return message;
853 }
854 const previousMessage = messagesBySource.get(message);
855 if (previousMessage?.attachments === attachments) return previousMessage;
856 const result = { ...message, attachments };
857 messagesBySource.set(message, result);
858 return result;
859 };
860}
861
862export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
863 if (
864 previous.role !== "assistant" ||
865 next.role !== "assistant" ||
866 !previous.streaming ||
867 !next.streaming
868 ) {
869 return false;
870 }
871 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previous;
872 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = next;
873 return shallow(previousMetadata, nextMetadata);
874}
875
876export function isStreamingTurnItemTextUpdate(
877 previous: OrchestrationV2ProjectedTurnItem,
878 next: OrchestrationV2ProjectedTurnItem,
879): boolean {
880 const { item: previousItem, ...previousSource } = previous;
881 const { item: nextItem, ...nextSource } = next;
882 if (
883 previousItem.type !== "assistant_message" ||
884 nextItem.type !== "assistant_message" ||
885 !previousItem.streaming ||
886 !nextItem.streaming ||
887 !shallow(previousSource, nextSource) ||
888 projectedItemCreatedAt(previous) !== projectedItemCreatedAt(next)
889 ) {
890 return false;
891 }
892 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previousItem;
893 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = nextItem;
894 // Wire decoding recreates timestamps and attachments; compare only the changed item's metadata.
895 return Equal.equals(previousMetadata, nextMetadata);
896}
897
898function reuseTimelineEntries(
899 input: TimelineEntriesInput,
900 previous: TimelineEntriesProjection,
901): TimelineEntry[] | null {
902 const before = previous.input;
903 if (
904 input.visibleTurnItems.length < before.visibleTurnItems.length ||
905 !shallow(input.optimisticMessages, before.optimisticMessages) ||
906 !shallow(input.anchoredMessages, before.anchoredMessages) ||
907 !shallow(input.attachmentUrlById, before.attachmentUrlById) ||
908 !shallow(input.attempts, before.attempts) ||
909 !shallow(input.nodes, before.nodes) ||
910 !shallow(input.plans, before.plans)
911 ) {
912 return null;
913 }
914 const appended = input.visibleTurnItems.length > before.visibleTurnItems.length;
915 // Keep full projection until committed items interleave and deduplicate anchored/optimistic messages.
916 if (
917 appended &&
918 (input.optimisticMessages.length > 0 || (input.anchoredMessages?.length ?? 0) > 0)
919 ) {
920 return null;
921 }
922 // Answer rows can replace a message already present in the retained prefix.
923 if (
924 appended &&
925 input.visibleTurnItems
926 .slice(before.visibleTurnItems.length)
927 .some(
928 ({ item }) =>
929 (item.type === "user_input_request" && item.questionAnswer !== undefined) ||
930 (item.type === "user_message" && item.messageId.startsWith("async-answer:")),
931 )
932 )
933 return null;
934 const replacements = new Map<
935 OrchestrationV2ProjectedTurnItem,
936 OrchestrationV2ProjectedTurnItem
937 >();
938 for (let index = 0; index < before.visibleTurnItems.length; index += 1) {
939 const previousItem = before.visibleTurnItems[index]!;
940 const item = input.visibleTurnItems[index]!;
941 if (item === previousItem) continue;
942 if (!isStreamingTurnItemTextUpdate(previousItem, item)) return null;
943 replacements.set(previousItem, item);
944 }
945 if (replacements.size === 0 && !appended) return previous.entries;
946 const entries = previous.entries.map((entry): TimelineEntry => {
947 const row =
948 entry.kind === "message" && entry.projectedItem !== undefined
949 ? replacements.get(entry.projectedItem)
950 : undefined;
951 if (entry.kind !== "message" || row?.item.type !== "assistant_message") return entry;
952 return {
953 ...entry,
954 projectedItem: row,
955 message: {
956 ...entry.message,
957 text: row.item.text,
958 updatedAt: DateTime.formatIso(row.item.updatedAt),
959 },
960 };
961 });
962 if (appended) {
963 entries.push(
964 ...deriveTimelineEntriesFromVisibleTurnItems({
965 ...input,
966 visibleTurnItems: input.visibleTurnItems.slice(before.visibleTurnItems.length),
967 }),
968 );
969 }
970 return entries;
971}
972
973export function deriveTimelineEntriesFromVisibleTurnItemsWithState(
974 input: TimelineEntriesInput,
975 previous: TimelineEntriesProjection | null = null,
976): TimelineEntriesProjection {
977 const reused = previous === null ? null : reuseTimelineEntries(input, previous);
978 if (reused !== null) return { input, entries: reused };
979 const entries = deriveTimelineEntriesFromVisibleTurnItems(input);
980 if (previous === null || !shallow(input.attachmentUrlById, previous.input.attachmentUrlById)) {
981 return { input, entries };
982 }
983 const previousMessages = new Map(
984 previous.entries.flatMap((entry) =>
985 entry.kind === "message" ? [[entry.id, entry] as const] : [],
986 ),
987 );
988 return {
989 input,
990 entries: entries.map((entry) => {
991 if (entry.kind !== "message" || entry.projectedItem === undefined) return entry;
992 const before = previousMessages.get(entry.id);
993 if (before?.projectedItem !== entry.projectedItem) return entry;
994 return before.attempt === entry.attempt ? before : { ...entry, message: before.message };
995 }),
996 };
997}
998
999// Run ordinals keep increasing after a rewind; only visible local runs define predecessors.
1000export function deriveRevertTurnCountByUserMessageId(input: {
1001 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
1002 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
1003 readonly threadStartCheckpointReady: boolean;
1004 readonly availableRevertTurnCounts?: ReadonlySet<number> | undefined;
1005 readonly unsettledRunId?: RunId | null;
1006}): Map<ChatMessage["id"], number> {
1007 const readyTurnCountByRunId = new Map<RunId, number>();
1008 for (const checkpoint of input.checkpoints) {
1009 if (checkpoint.status === "ready") {
1010 readyTurnCountByRunId.set(checkpoint.runId, checkpoint.checkpointTurnCount);
1011 }
1012 }
1013 const targetByRunId = new Map<RunId, number | undefined>();
1014 const byUserMessageId = new Map<ChatMessage["id"], number>();
1015 let previousRunId: RunId | null = null;
1016 for (const entry of input.timelineEntries) {
1017 // Inherited history belongs to the source thread, not our checkpoint scope.
1018 if (entry.kind !== "message" && entry.kind !== "work") continue;
1019 const projectedItem =
1020 entry.kind === "message" ? entry.projectedItem : entry.entry.projectedItem;
1021 if (projectedItem?.visibility === "inherited") continue;
1022 const runId =
1023 entry.kind === "message"
1024 ? entry.message.runId
1025 : entry.entry.itemType === "notification"
1026 ? entry.entry.runId
1027 : null;
1028 if (runId == null) continue;
1029 if (!targetByRunId.has(runId)) {
1030 targetByRunId.set(
1031 runId,
1032 previousRunId === null
1033 ? input.threadStartCheckpointReady
1034 ? 0
1035 : undefined
1036 : readyTurnCountByRunId.get(previousRunId),
1037 );
1038 previousRunId = runId;
1039 }
1040 if (entry.kind !== "message") continue;
1041 const { message } = entry;
1042 if (message.role !== "user" || message.runId === input.unsettledRunId) continue;
1043 if (message.inputIntent !== "turn_start" && message.inputIntent !== "queued_turn") continue;
1044 const target = targetByRunId.get(runId);
1045 if (
1046 target !== undefined &&
1047 (input.availableRevertTurnCounts === undefined || input.availableRevertTurnCounts.has(target))
1048 )
1049 byUserMessageId.set(message.id, target);
1050 }
1051 return byUserMessageId;
1052}
1053
1054export function findRevertCheckpoint(
1055 checkpoints: ReadonlyArray<OrchestrationV2Checkpoint>,
1056 turnCount: number,
1057): OrchestrationV2Checkpoint | undefined {
1058 return checkpoints.findLast(
1059 (checkpoint) =>
1060 checkpoint.status === "ready" &&
1061 (turnCount === 0
1062 ? checkpoint.ordinalWithinScope === 0 && checkpoint.appRunOrdinal === null
1063 : checkpoint.appRunOrdinal === turnCount),
1064 );
1065}
1066
1067export function derivePhase(runtime: ThreadStructureRuntime | null): SessionPhase {
1068 if (runtime === null) return "disconnected";
1069 if (
1070 runtime.status === "preparing" ||
1071 runtime.status === "starting" ||
1072 runtime.status === "queued"
1073 )
1074 return "connecting";
1075 if (runtime.status === "running" || runtime.status === "waiting") return "running";
1076 return "ready";
1077}
1078
1079/** Preparing and starting runs can be interrupted; Stop need not wait for running. */
1080export function deriveCanInterruptRunningThread(
1081 hasActiveThread: boolean,
1082 runtime: ThreadStructureRuntime | null,
1083): boolean {
1084 return (
1085 hasActiveThread &&
1086 (derivePhase(runtime) === "running" || threadRuntimeHasInterruptibleRun(runtime))
1087 );
1088}
1089
1090export type { TurnDiffSummary };