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