Open History to see the last commit
1import type { ThreadStructure, ThreadStructureRuntime } from "@t3tools/client-runtime/state/shell";
2import { msg } from "gt-react";
3import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
4import {
5 type AssetResource,
6 type OrchestrationV2Checkpoint,
7 type OrchestrationV2ThreadProjection,
8 type OrchestrationV2ExecutionNode,
9 type OrchestrationV2PlanArtifact,
10 type OrchestrationV2ProjectedTurnItem,
11 type OrchestrationV2RunAttempt,
12 type OrchestrationV2TurnItem,
13 type RunId,
14 type ToolActivitySurface,
15 type ToolActivityIcon,
16 type ToolActivitySource,
17 type ThreadId,
18 type TurnItemId,
19} from "@t3tools/contracts";
20import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";
21import { classifyToolActivity, collectToolFilePaths } from "@t3tools/shared/toolActivity";
22import { formatReadToolLabel, formatSearchToolLabel } from "@t3tools/shared/toolActivityCopy";
23import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
24import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
25import type { McpAppReference } from "@t3tools/shared/mcpApp";
26import {
27 htmlRenderFromToolItem,
28 mcpAppFromToolItem,
29 sentMessageFromToolItem,
30} from "@t3tools/shared/toolOutput";
31import {
32 contextCompactionLabel,
33 workEntryIndicatesToolFailure,
34} from "@t3tools/client-runtime/work-log/presentation";
35import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
36import { repositoryCheckpointScopeIds } from "@t3tools/client-runtime/state/thread-repositories";
37import type {
38 ThreadPendingApproval,
39 ThreadPendingUserInput,
40} from "@t3tools/client-runtime/state/thread-requests";
41import type { ThreadRunSummary, ThreadRuntimeSummary } from "@t3tools/client-runtime/state/shell";
42import { threadRuntimeHasInterruptibleRun } from "@t3tools/client-runtime/state/thread-execution";
43import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation";
44
45import {
46 isImageAttachment,
47 type ChatAttachment,
48 type ChatMessage,
49 type ProposedPlan,
50 type SessionPhase,
51 type TurnDiffSummary,
52} from "./types";
53import { m, type MessageResolver } from "./i18n/messages";
54import * as DateTime from "effect/DateTime";
55import * as Equal from "effect/Equal";
56import { shallow } from "zustand/vanilla/shallow";
57
58export {
59 workEntryDisplayIndicatesToolFailure,
60 workEntryIndicatesToolFailure,
61} from "@t3tools/client-runtime/work-log/presentation";
62
63export type WorkLogToolLifecycleStatus =
64 | "idle"
65 | "inProgress"
66 | "completed"
67 | "failed"
68 | "declined"
69 | "stopped";
70
71export interface WorkLogEntry {
72 readonly questionAnswer?: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
73 readonly id: string;
74 readonly createdAt: string;
75 readonly runId?: RunId | null;
76 readonly label: string;
77 readonly detail?: string;
78 readonly command?: string;
79 readonly rawCommand?: string;
80 readonly changedFiles?: ReadonlyArray<string>;
81 readonly tone: "thinking" | "tool" | "info" | "error";
82 readonly toolTitle?: string;
83 readonly toolCallId?: string;
84 readonly viewedImagePath?: string;
85 readonly toolSurface?: ToolActivitySurface;
86 readonly toolIcon?: ToolActivityIcon;
87 readonly toolSource?: ToolActivitySource;
88 readonly sourceActivityKind?: string;
89 readonly taskId?: string;
90 readonly agentRole?: string;
91 readonly toolData?: unknown;
92 readonly requestKind?: string;
93 readonly itemType?: OrchestrationV2TurnItem["type"];
94 readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus;
95 readonly structuredPayload?: OrchestrationV2TurnItem;
96 readonly sourceItemType?: OrchestrationV2TurnItem["type"];
97 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
98}
99
100export type PendingApproval = ThreadPendingApproval;
101export type PendingUserInput = ThreadPendingUserInput;
102
103export type TimelineAttempt = Pick<
104 OrchestrationV2RunAttempt,
105 "id" | "runId" | "attemptOrdinal" | "rootNodeId" | "status" | "completedAt"
106>;
107
108export type TimelineEntry = (
109 | {
110 readonly id: string;
111 readonly kind: "message";
112 readonly createdAt: string;
113 readonly message: ChatMessage;
114 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
115 }
116 | {
117 readonly id: string;
118 readonly kind: "proposed-plan";
119 readonly createdAt: string;
120 readonly proposedPlan: ProposedPlan;
121 }
122 | {
123 readonly id: string;
124 readonly kind: "html-render";
125 readonly createdAt: string;
126 readonly runId: RunId | null;
127 readonly htmlRender: HtmlRenderReference;
128 }
129 | {
130 readonly id: string;
131 readonly kind: "sent-message";
132 readonly createdAt: string;
133 readonly runId: RunId | null;
134 readonly text: string;
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
242export type TaskListPlan = Extract<OrchestrationV2PlanArtifact, { readonly kind: "todo_list" }>;
243
244// Snapshots do not load plans in run order, so the run ordinal decides which list is newest.
245export function findLatestTaskList(projection: ThreadStructure | null): TaskListPlan | null {
246 if (projection === null) return null;
247 const runOrdinals = new Map<RunId | null, number>(
248 projection.runs.map((run) => [run.id, run.ordinal]),
249 );
250 let latest: TaskListPlan | null = null;
251 for (const plan of projection.plans) {
252 if (plan.kind !== "todo_list" || plan.status === "superseded") continue;
253 if (
254 latest === null ||
255 (runOrdinals.get(plan.runId) ?? -1) >= (runOrdinals.get(latest.runId) ?? -1)
256 ) {
257 latest = plan;
258 }
259 }
260 return latest === null || latest.steps.length === 0 ? null : latest;
261}
262
263const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"]["type"]>([
264 "fork",
265 "handoff",
266 "run_interrupt_request",
267 "run_interrupt_result",
268 "secret_request",
269 "feedback_request",
270 "handoff_request",
271 "link_request",
272 "subagent",
273]);
274
275const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
276 "fork",
277 "thread_created",
278 // Still answerable after a steer supersedes the attempt that asked.
279 "secret_request",
280 "feedback_request",
281 "handoff_request",
282 "link_request",
283]);
284
285export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean {
286 return (
287 entry.kind === "event" && PERSISTENT_RESOURCE_V2_ITEM_TYPES.has(entry.projectedItem.item.type)
288 );
289}
290
291function projectedItemCreatedAt(row: OrchestrationV2ProjectedTurnItem): string {
292 return DateTime.formatIso(row.item.startedAt ?? row.item.updatedAt);
293}
294
295function projectedWorkEntryStatus(
296 item: OrchestrationV2TurnItem,
297): NonNullable<WorkLogEntry["toolLifecycleStatus"]> {
298 switch (item.status) {
299 case "pending":
300 case "running":
301 case "waiting":
302 return "inProgress";
303 case "completed":
304 return "completed";
305 case "idle":
306 return "idle";
307 case "failed":
308 return "failed";
309 case "cancelled":
310 case "interrupted":
311 return item.toolNonExecutionKind === "declined" ? "declined" : "stopped";
312 }
313}
314
315function projectedWorkEntryTone(item: OrchestrationV2TurnItem): WorkLogEntry["tone"] {
316 if (item.type === "error") return "info";
317 if (item.type === "reasoning") return "thinking";
318 switch (item.type) {
319 case "command_execution":
320 case "file_change":
321 case "file_search":
322 case "web_search":
323 case "dynamic_tool":
324 case "subagent":
325 case "thread_created":
326 case "user_input_request":
327 case "approval_request":
328 return "tool";
329 default:
330 return "info";
331 }
332}
333
334export function providerErrorPresentation(
335 item: Extract<OrchestrationV2TurnItem, { readonly type: "error" }>,
336 resolve: MessageResolver = m,
337): { readonly label: string; readonly detail: string } {
338 if (item.retry === undefined) {
339 return {
340 label:
341 item.failure.class === "usage_limit"
342 ? resolve(msg("Usage limit reached"))
343 : item.title?.trim() || resolve(msg("Provider error")),
344 detail: item.failure.message,
345 };
346 }
347 const progress =
348 item.retry.maxAttempts === null
349 ? `${item.retry.attempt}`
350 : `${item.retry.attempt}/${item.retry.maxAttempts}`;
351 const counts = { progress, attempt: item.retry.attempt };
352 const label =
353 item.status === "running"
354 ? resolve(msg("Retrying provider ({progress})", { progress }))
355 : item.status === "completed"
356 ? resolve(
357 msg(
358 "{attempt, plural, one {Provider recovered ({progress} retries)} other {Provider recovered ({progress} retries)}}",
359 ),
360 counts,
361 )
362 : item.status === "failed"
363 ? item.failure.class === "usage_limit"
364 ? resolve(
365 msg(
366 "{attempt, plural, one {Usage limit reached after {progress} retries} other {Usage limit reached after {progress} retries}}",
367 ),
368 counts,
369 )
370 : resolve(
371 msg(
372 "{attempt, plural, one {Provider error after {progress} retries} other {Provider error after {progress} retries}}",
373 ),
374 counts,
375 )
376 : resolve(msg("Provider retry stopped ({progress})", { progress }));
377 const retryDelay =
378 item.status === "running" && item.retry.retryDelayMs !== null && item.retry.retryDelayMs > 0
379 ? item.retry.retryDelayMs < 1_000
380 ? ` ${resolve(msg("Retrying in {delay}ms.", { delay: item.retry.retryDelayMs }))}`
381 : ` ${resolve(
382 msg("Retrying in {delay}s.", {
383 delay: (item.retry.retryDelayMs / 1_000).toFixed(1).replace(/\.0$/u, ""),
384 }),
385 )}`
386 : "";
387 return {
388 label,
389 detail: `${item.failure.message}${retryDelay}`,
390 };
391}
392
393function projectedWorkEntry(
394 row: OrchestrationV2ProjectedTurnItem,
395 resolve: MessageResolver,
396): WorkLogEntry {
397 const { item } = row;
398 const title = item.title?.trim() || null;
399 const common = {
400 id: item.id,
401 createdAt: projectedItemCreatedAt(row),
402 runId: item.runId,
403 tone: projectedWorkEntryTone(item),
404 itemType: item.type,
405 toolLifecycleStatus: projectedWorkEntryStatus(item),
406 structuredPayload: item,
407 projectedItem: row,
408 ...extractToolActivityPresentation(item),
409 } as const;
410
411 switch (item.type) {
412 case "thread_created":
413 return {
414 ...common,
415 label: resolve(msg("Created thread")),
416 };
417 case "compaction":
418 return {
419 ...common,
420 label: contextCompactionLabel(item, resolve),
421 sourceActivityKind: "context-compaction",
422 ...(item.summary ? { detail: item.summary } : {}),
423 };
424 case "reasoning":
425 return {
426 ...common,
427 label: title ?? resolve(msg("Thinking", { $context: "status of an agent reasoning" })),
428 ...(item.text ? { detail: item.text } : {}),
429 };
430 case "command_execution":
431 return {
432 ...common,
433 label: title ?? resolve(msg("Ran command")),
434 command: item.input,
435 rawCommand: item.input,
436 toolTitle: title ?? resolve(msg("Command", { $context: "noun, a shell command tool" })),
437 toolData: item,
438 };
439 case "file_change": {
440 return {
441 ...common,
442 label:
443 title ??
444 (item.changes !== undefined && item.changes.length > 1
445 ? resolve(
446 msg("{count, plural, one {Changed {count} file} other {Changed {count} files}}"),
447 { count: item.changes.length },
448 )
449 : resolve(msg("Changed {fileName}", { fileName: item.fileName }))),
450 changedFiles: item.changes?.length
451 ? item.changes.map((change) => change.path)
452 : [item.fileName],
453 toolTitle: title ?? resolve(msg("File change", { $context: "noun, a tool title" })),
454 toolData: item,
455 };
456 }
457 case "file_search":
458 return {
459 ...common,
460 label: title ?? formatSearchToolLabel(item, resolve) ?? resolve(msg("Searched files")),
461 ...(item.pattern ? { detail: item.pattern } : {}),
462 toolTitle: title ?? resolve(msg("File search", { $context: "noun, a tool title" })),
463 toolData: item,
464 };
465 case "web_search":
466 return {
467 ...common,
468 label: title ?? resolve(msg("Searched the web")),
469 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
470 toolTitle: title ?? resolve(msg("Web search", { $context: "noun, a tool title" })),
471 toolData: item,
472 };
473 case "checkpoint":
474 return {
475 ...common,
476 label: title ?? resolve(msg("Checkpoint captured")),
477 changedFiles: item.files.map((file) => file.path),
478 toolData: item,
479 };
480 case "system_notice":
481 return {
482 ...common,
483 label: item.message,
484 ...(item.level === "info" ? {} : { sourceActivityKind: "runtime.warning" }),
485 };
486 case "error": {
487 const presentation = providerErrorPresentation(item, resolve);
488 return {
489 ...common,
490 ...presentation,
491 ...(item.failure.class === "usage_limit" && item.status !== "completed"
492 ? { sourceActivityKind: "runtime.warning" }
493 : item.retry === undefined
494 ? { sourceActivityKind: "runtime.error" }
495 : {}),
496 toolData: item,
497 };
498 }
499 case "dynamic_tool": {
500 const classified = classifyToolActivity({
501 itemType: "dynamic_tool_call",
502 data: { toolName: item.toolName ?? undefined, input: item.input },
503 });
504 const [readPath] = collectToolFilePaths({ input: item.input });
505 return {
506 ...common,
507 label:
508 title ??
509 (classified === "read"
510 ? formatReadToolLabel(readPath ?? "", 0, resolve)
511 : classified === "search"
512 ? (formatSearchToolLabel({ input: item.input }, resolve) ??
513 item.toolName ??
514 resolve(msg("Tool call", { $context: "noun" })))
515 : (item.toolName ?? resolve(msg("Tool call", { $context: "noun" })))),
516 toolTitle:
517 title ?? item.toolName ?? resolve(msg("Tool", { $context: "noun, a tool title" })),
518 toolData: { input: item.input, output: item.output },
519 };
520 }
521 case "todo_list": {
522 // Each todo update is a quiet row where the agent wrote it; it opens to every step.
523 const done = item.steps.filter((step) => step.status === "completed").length;
524 const current =
525 item.steps.find((step) => step.status === "running") ??
526 item.steps.find((step) => step.status === "pending");
527 return {
528 ...common,
529 label: current
530 ? resolve(msg("Tasks {done}/{total} · {current}"), {
531 done,
532 total: item.steps.length,
533 current: current.text,
534 })
535 : resolve(msg("Tasks {done}/{total}"), { done, total: item.steps.length }),
536 };
537 }
538 case "approval_request":
539 return {
540 ...common,
541 label: title ?? resolve(msg("Approval requested")),
542 detail: item.prompt ?? item.requestKind,
543 toolData: item,
544 };
545 case "user_input_request":
546 return {
547 ...common,
548 label:
549 title ??
550 (item.questionAnswer
551 ? resolve(msg("Answered questions"))
552 : resolve(msg("Input requested"))),
553 ...(item.questionAnswer ? { questionAnswer: item.questionAnswer } : {}),
554 toolData: item,
555 };
556 default:
557 return {
558 ...common,
559 label: title ?? item.type.replaceAll("_", " "),
560 toolData: item,
561 };
562 }
563}
564
565/** Preserve visibleTurnItems' committed order; interleave client messages by timestamp. */
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 readonly resolve?: MessageResolver;
575}
576
577export interface TimelineEntriesProjection {
578 readonly input: TimelineEntriesInput;
579 readonly entries: TimelineEntry[];
580}
581
582export function deriveTimelineEntriesFromVisibleTurnItems(
583 input: TimelineEntriesInput,
584): TimelineEntry[] {
585 const committedMessageIds = new Set<string>();
586 const entries: TimelineEntry[] = [];
587 const attemptByRootNodeId = new Map(
588 (input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
589 );
590 const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const));
591 const planById = new Map((input.plans ?? []).map((plan) => [plan.id, plan] as const));
592
593 const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => {
594 if (item.nodeId === null || item.runId === null) return undefined;
595 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
596 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
597 while (nodeId !== null && !visited.has(nodeId)) {
598 visited.add(nodeId);
599 const directAttempt = attemptByRootNodeId.get(nodeId);
600 if (directAttempt?.runId === item.runId) return directAttempt;
601 const node = nodeById.get(nodeId);
602 if (node === undefined) return undefined;
603 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
604 if (rootAttempt?.runId === item.runId) return rootAttempt;
605 nodeId = node.parentNodeId;
606 }
607 return undefined;
608 };
609
610 // An answer that started a later run stays a normal message at that run's position.
611 const foldedAnswerRunIdByMessageId = new Map<string, OrchestrationV2TurnItem["runId"]>(
612 input.visibleTurnItems.flatMap(({ item }) =>
613 item.type === "user_input_request" && item.questionAnswer
614 ? [[`async-answer:${item.questionAnswer.requestId}`, item.runId] as const]
615 : [],
616 ),
617 );
618 for (const row of input.visibleTurnItems) {
619 const { item } = row;
620 if (turnItemIsWorkspacePreparation(item) && !item.deferredWork) continue;
621 if (item.type === "checkpoint") continue;
622 if (
623 item.type === "user_message" &&
624 item.inputIntent === "queued_turn" &&
625 item.status === "pending"
626 )
627 continue;
628 if (
629 item.type === "user_message" &&
630 foldedAnswerRunIdByMessageId.get(item.messageId) === item.runId
631 )
632 continue;
633 const createdAt = projectedItemCreatedAt(row);
634 const attempt = resolveAttempt(item);
635 const attemptMetadata = attempt === undefined ? {} : { attempt };
636 if (item.type === "notification") {
637 entries.push({
638 id: item.id,
639 kind: "work",
640 createdAt,
641 entry: {
642 id: item.id,
643 createdAt,
644 runId: item.runId,
645 label: item.summary,
646 tone: "info",
647 itemType: item.type,
648 structuredPayload: item,
649 projectedItem: row,
650 },
651 ...attemptMetadata,
652 });
653 continue;
654 }
655 if (item.type === "user_message" || item.type === "assistant_message") {
656 const message: ChatMessage = {
657 id: item.messageId,
658 role: item.type === "user_message" ? "user" : "assistant",
659 text: item.text,
660 ...(item.type === "user_message" && item.context ? { context: item.context } : {}),
661 ...((item.attachments?.length ?? 0) > 0
662 ? {
663 attachments: (item.attachments ?? []).map((attachment) => {
664 const previewUrl = input.attachmentUrlById?.get(attachment.id);
665 return previewUrl ? { ...attachment, previewUrl } : attachment;
666 }),
667 }
668 : {}),
669 runId: item.runId,
670 streaming: item.type === "assistant_message" && item.streaming,
671 ...(item.type === "user_message"
672 ? {
673 createdBy: item.createdBy,
674 creationSource: item.creationSource,
675 ...(item.senderThreadId !== undefined ? { senderThreadId: item.senderThreadId } : {}),
676 ...(item.linkedSender !== undefined ? { linkedSender: item.linkedSender } : {}),
677 ...(item.idleCompaction !== undefined ? { idleCompaction: item.idleCompaction } : {}),
678 ...(item.scheduledTaskId !== undefined
679 ? { scheduledTaskId: item.scheduledTaskId }
680 : {}),
681 }
682 : {}),
683 createdAt,
684 updatedAt: DateTime.formatIso(item.updatedAt),
685 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
686 };
687 committedMessageIds.add(message.id);
688 entries.push({
689 id: message.id,
690 kind: "message",
691 createdAt,
692 message,
693 projectedItem: row,
694 ...attemptMetadata,
695 });
696 continue;
697 }
698
699 if (item.type === "proposed_plan") {
700 const plan = planById.get(item.planId);
701 const proposedPlan = {
702 id: item.planId,
703 runId: item.runId,
704 planMarkdown: item.markdown,
705 status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
706 createdAt,
707 updatedAt: DateTime.formatIso(item.updatedAt),
708 };
709 entries.push({
710 id: item.id,
711 kind: "proposed-plan",
712 createdAt,
713 proposedPlan,
714 ...attemptMetadata,
715 });
716 continue;
717 }
718
719 const htmlRender =
720 item.type === "dynamic_tool" && item.status === "completed"
721 ? htmlRenderFromToolItem(item)
722 : undefined;
723 if (htmlRender !== undefined) {
724 entries.push({
725 id: item.id,
726 kind: "html-render",
727 createdAt,
728 runId: item.runId,
729 htmlRender,
730 ...attemptMetadata,
731 });
732 continue;
733 }
734
735 const sentMessage =
736 item.type === "dynamic_tool" && item.status === "completed"
737 ? sentMessageFromToolItem(item)
738 : undefined;
739 if (sentMessage !== undefined) {
740 entries.push({
741 id: item.id,
742 kind: "sent-message",
743 createdAt,
744 runId: item.runId,
745 text: sentMessage,
746 ...attemptMetadata,
747 });
748 continue;
749 }
750
751 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
752 entries.push({
753 id: item.id,
754 kind: "event",
755 createdAt,
756 projectedItem: row,
757 ...attemptMetadata,
758 });
759 continue;
760 }
761
762 entries.push({
763 id: item.id,
764 kind: "work",
765 createdAt,
766 entry: projectedWorkEntry(row, input.resolve ?? m),
767 ...attemptMetadata,
768 });
769
770 const mcpApp = item.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined;
771 if (mcpApp !== undefined) {
772 entries.push({
773 id: `mcp-app:${item.id}`,
774 kind: "mcp-app",
775 createdAt,
776 runId: item.runId,
777 sourceThreadId: row.sourceThreadId,
778 itemId: row.sourceItemId,
779 revision: turnItemDetailRevision(item),
780 mcpApp,
781 ...attemptMetadata,
782 });
783 }
784 }
785
786 const retainedMessageIds = new Set([
787 ...committedMessageIds,
788 ...foldedAnswerRunIdByMessageId.keys(),
789 ]);
790 for (const message of input.anchoredMessages ?? []) {
791 if (retainedMessageIds.has(message.id)) continue;
792 retainedMessageIds.add(message.id);
793 const entry: TimelineEntry = {
794 id: message.id,
795 kind: "message",
796 createdAt: message.createdAt,
797 message,
798 };
799 const insertionIndex = entries.findIndex(
800 (candidate) => candidate.createdAt > message.createdAt,
801 );
802 if (insertionIndex === -1) {
803 entries.push(entry);
804 } else {
805 entries.splice(insertionIndex, 0, entry);
806 }
807 }
808
809 for (const message of input.optimisticMessages) {
810 if (message.inputIntent !== "queued_turn" && !retainedMessageIds.has(message.id)) {
811 retainedMessageIds.add(message.id);
812 entries.push({
813 id: message.id,
814 kind: "message",
815 createdAt: message.createdAt,
816 message,
817 });
818 }
819 }
820
821 return entries;
822}
823
824type AttachmentResource = Extract<AssetResource, { readonly _tag: "attachment" }>;
825const EMPTY_IMAGE_RESOURCES = Object.freeze<ReadonlyArray<AttachmentResource>>([]);
826
827export function selectMessageImageResources(
828 attachments: ChatMessage["attachments"],
829): ReadonlyArray<AttachmentResource> {
830 const attachmentIds = new Set<string>();
831 for (const attachment of attachments ?? []) {
832 if (!isImageAttachment(attachment)) continue;
833 const previewUrl = attachment.previewUrl;
834 if (previewUrl?.startsWith("blob:") || previewUrl?.startsWith("data:")) continue;
835 attachmentIds.add(attachment.id);
836 }
837 return attachmentIds.size === 0
838 ? EMPTY_IMAGE_RESOURCES
839 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
840}
841
842export function selectHandoffImageResources(
843 messages: ReadonlyArray<Pick<ChatMessage, "id" | "role" | "attachments">> | undefined,
844 handoffs: Readonly<Record<string, ReadonlyArray<string>>>,
845): ReadonlyArray<AttachmentResource> {
846 if (Object.keys(handoffs).length === 0) return EMPTY_IMAGE_RESOURCES;
847 const attachmentIds = new Set<string>();
848 for (const message of messages ?? []) {
849 if (message.role !== "user" || !handoffs[message.id]?.length) continue;
850 for (const attachment of message.attachments ?? []) {
851 if (isImageAttachment(attachment)) attachmentIds.add(attachment.id);
852 }
853 }
854 return attachmentIds.size === 0
855 ? EMPTY_IMAGE_RESOURCES
856 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
857}
858
859export function createMessageAttachmentPreviewProjector() {
860 const attachmentsBySource = new WeakMap<
861 ReadonlyArray<ChatAttachment>,
862 ReadonlyArray<ChatAttachment>
863 >();
864 const messagesBySource = new WeakMap<ChatMessage, ChatMessage>();
865 return (
866 message: ChatMessage,
867 previewUrlFor: (attachment: ChatAttachment) => string | undefined,
868 ): ChatMessage => {
869 const source = message.attachments;
870 if (!source || source.length === 0) return message;
871 const previous = attachmentsBySource.get(source) ?? source;
872 let changed: ChatAttachment[] | undefined;
873 let hasOverrides = false;
874 for (const [index, attachment] of source.entries()) {
875 const previewUrl = previewUrlFor(attachment);
876 const sourceUrl = "previewUrl" in attachment ? attachment.previewUrl : undefined;
877 const previousAttachment = previous[index]!;
878 const previousUrl =
879 "previewUrl" in previousAttachment ? previousAttachment.previewUrl : undefined;
880 const next =
881 !previewUrl || previewUrl === sourceUrl
882 ? attachment
883 : previewUrl === previousUrl
884 ? previousAttachment
885 : { ...attachment, previewUrl };
886 hasOverrides ||= next !== attachment;
887 if (next !== previousAttachment) {
888 changed ??= previous.slice();
889 changed[index] = next;
890 }
891 }
892 const attachments = hasOverrides ? (changed ?? previous) : source;
893 attachmentsBySource.set(source, attachments);
894 if (attachments === source) {
895 messagesBySource.delete(message);
896 return message;
897 }
898 const previousMessage = messagesBySource.get(message);
899 if (previousMessage?.attachments === attachments) return previousMessage;
900 const result = { ...message, attachments };
901 messagesBySource.set(message, result);
902 return result;
903 };
904}
905
906export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
907 if (
908 previous.role !== "assistant" ||
909 next.role !== "assistant" ||
910 !previous.streaming ||
911 !next.streaming
912 ) {
913 return false;
914 }
915 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previous;
916 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = next;
917 return shallow(previousMetadata, nextMetadata);
918}
919
920function streamedTextMetadata(item: OrchestrationV2TurnItem) {
921 if (item.type === "proposed_plan" && item.streaming) {
922 const { markdown: _markdown, updatedAt: _updatedAt, ...metadata } = item;
923 return metadata;
924 }
925 if ((item.type === "assistant_message" || item.type === "reasoning") && item.streaming) {
926 const { text: _text, updatedAt: _updatedAt, ...metadata } = item;
927 return metadata;
928 }
929 return null;
930}
931
932export function isStreamingTurnItemTextUpdate(
933 previous: OrchestrationV2ProjectedTurnItem,
934 next: OrchestrationV2ProjectedTurnItem,
935): boolean {
936 const { item: previousItem, ...previousSource } = previous;
937 const { item: nextItem, ...nextSource } = next;
938 const previousMetadata = streamedTextMetadata(previousItem);
939 const nextMetadata = streamedTextMetadata(nextItem);
940 if (
941 previousMetadata === null ||
942 nextMetadata === null ||
943 !shallow(previousSource, nextSource) ||
944 projectedItemCreatedAt(previous) !== projectedItemCreatedAt(next)
945 ) {
946 return false;
947 }
948 // Wire decoding recreates timestamps and attachments; compare only the changed item's metadata.
949 return Equal.equals(previousMetadata, nextMetadata);
950}
951
952/**
953 * A changed tool or work item maps to exactly one entry with the item's id.
954 * Messages and question answers take part in cross-entry dedupe, and anchored
955 * messages are placed by createdAt, so those changes rebuild.
956 */
957function canRederiveInPlace(
958 input: TimelineEntriesInput,
959 previousItem: OrchestrationV2ProjectedTurnItem,
960 item: OrchestrationV2ProjectedTurnItem,
961): boolean {
962 return (
963 item.item.id === previousItem.item.id &&
964 item.item.type === previousItem.item.type &&
965 item.item.type !== "user_message" &&
966 item.item.type !== "assistant_message" &&
967 item.item.type !== "user_input_request" &&
968 // An app call projects two entries; in-place reuse replaces one.
969 (previousItem.item.type !== "dynamic_tool" ||
970 mcpAppFromToolItem(previousItem.item) === undefined) &&
971 ((input.anchoredMessages?.length ?? 0) === 0 ||
972 projectedItemCreatedAt(item) === projectedItemCreatedAt(previousItem))
973 );
974}
975
976/** Entries read only each plan's status; streaming plans rebuild artifacts with every delta. */
977function samePlanStatuses(
978 next: TimelineEntriesInput["plans"],
979 previous: TimelineEntriesInput["plans"],
980): boolean {
981 if (next === previous) return true;
982 if (next === undefined || previous === undefined || next.length !== previous.length) return false;
983 return next.every((plan, index) => {
984 const before = previous[index]!;
985 return plan.id === before.id && plan.kind === before.kind && plan.status === before.status;
986 });
987}
988
989function reuseTimelineEntries(
990 input: TimelineEntriesInput,
991 previous: TimelineEntriesProjection,
992): TimelineEntry[] | null {
993 const before = previous.input;
994 if (
995 input.visibleTurnItems.length < before.visibleTurnItems.length ||
996 !shallow(input.optimisticMessages, before.optimisticMessages) ||
997 !shallow(input.anchoredMessages, before.anchoredMessages) ||
998 !shallow(input.attachmentUrlById, before.attachmentUrlById) ||
999 !shallow(input.attempts, before.attempts) ||
1000 !shallow(input.nodes, before.nodes) ||
1001 !samePlanStatuses(input.plans, before.plans) ||
1002 input.resolve !== before.resolve
1003 ) {
1004 return null;
1005 }
1006 const appended = input.visibleTurnItems.length > before.visibleTurnItems.length;
1007 // Keep full projection until committed items interleave and deduplicate anchored/optimistic messages.
1008 if (
1009 appended &&
1010 (input.optimisticMessages.length > 0 || (input.anchoredMessages?.length ?? 0) > 0)
1011 ) {
1012 return null;
1013 }
1014 // Answer rows can replace a message already present in the retained prefix.
1015 if (
1016 appended &&
1017 input.visibleTurnItems
1018 .slice(before.visibleTurnItems.length)
1019 .some(
1020 ({ item }) =>
1021 (item.type === "user_input_request" && item.questionAnswer !== undefined) ||
1022 (item.type === "user_message" && item.messageId.startsWith("async-answer:")),
1023 )
1024 )
1025 return null;
1026 const replacements = new Map<
1027 OrchestrationV2ProjectedTurnItem,
1028 OrchestrationV2ProjectedTurnItem
1029 >();
1030 const changedItems: OrchestrationV2ProjectedTurnItem[] = [];
1031 for (let index = 0; index < before.visibleTurnItems.length; index += 1) {
1032 const previousItem = before.visibleTurnItems[index]!;
1033 const item = input.visibleTurnItems[index]!;
1034 if (item === previousItem) continue;
1035 // Reasoning and plan text re-derive below; only assistant text patches the message.
1036 if (
1037 item.item.type === "assistant_message" &&
1038 isStreamingTurnItemTextUpdate(previousItem, item)
1039 ) {
1040 replacements.set(previousItem, item);
1041 continue;
1042 }
1043 if (!canRederiveInPlace(input, previousItem, item)) return null;
1044 changedItems.push(item);
1045 }
1046 // One batch keeps the attempt/node/plan lookups to a single build.
1047 const rederived =
1048 changedItems.length === 0
1049 ? []
1050 : deriveTimelineEntriesFromVisibleTurnItems({
1051 ...input,
1052 visibleTurnItems: changedItems,
1053 optimisticMessages: [],
1054 anchoredMessages: [],
1055 });
1056 if (
1057 rederived.length !== changedItems.length ||
1058 rederived.some((entry, index) => entry.id !== changedItems[index]!.item.id)
1059 ) {
1060 return null;
1061 }
1062 const rederivedEntries = new Map(rederived.map((entry) => [entry.id, entry]));
1063 if (replacements.size === 0 && rederivedEntries.size === 0 && !appended) {
1064 return previous.entries;
1065 }
1066 let rederivedCount = 0;
1067 const entries = previous.entries.map((entry): TimelineEntry => {
1068 const rederivedEntry = rederivedEntries.get(entry.id);
1069 if (rederivedEntry !== undefined) {
1070 rederivedCount += 1;
1071 return rederivedEntry;
1072 }
1073 const row =
1074 entry.kind === "message" && entry.projectedItem !== undefined
1075 ? replacements.get(entry.projectedItem)
1076 : undefined;
1077 if (entry.kind !== "message" || row?.item.type !== "assistant_message") return entry;
1078 return {
1079 ...entry,
1080 projectedItem: row,
1081 message: {
1082 ...entry.message,
1083 text: row.item.text,
1084 updatedAt: DateTime.formatIso(row.item.updatedAt),
1085 },
1086 };
1087 });
1088 if (rederivedCount !== rederivedEntries.size) return null;
1089 if (appended) {
1090 entries.push(
1091 ...deriveTimelineEntriesFromVisibleTurnItems({
1092 ...input,
1093 visibleTurnItems: input.visibleTurnItems.slice(before.visibleTurnItems.length),
1094 }),
1095 );
1096 }
1097 return entries;
1098}
1099
1100export function deriveTimelineEntriesFromVisibleTurnItemsWithState(
1101 input: TimelineEntriesInput,
1102 previous: TimelineEntriesProjection | null = null,
1103): TimelineEntriesProjection {
1104 const reused = previous === null ? null : reuseTimelineEntries(input, previous);
1105 if (reused !== null) return { input, entries: reused };
1106 const entries = deriveTimelineEntriesFromVisibleTurnItems(input);
1107 if (previous === null || !shallow(input.attachmentUrlById, previous.input.attachmentUrlById)) {
1108 return { input, entries };
1109 }
1110 const previousMessages = new Map(
1111 previous.entries.flatMap((entry) =>
1112 entry.kind === "message" ? [[entry.id, entry] as const] : [],
1113 ),
1114 );
1115 return {
1116 input,
1117 entries: entries.map((entry) => {
1118 if (entry.kind !== "message" || entry.projectedItem === undefined) return entry;
1119 const before = previousMessages.get(entry.id);
1120 if (before?.projectedItem !== entry.projectedItem) return entry;
1121 return before.attempt === entry.attempt ? before : { ...entry, message: before.message };
1122 }),
1123 };
1124}
1125
1126// Run ordinals keep increasing after a rewind; only visible local runs define predecessors.
1127export function deriveRevertTurnCountByUserMessageId(input: {
1128 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
1129 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
1130 readonly threadStartCheckpointAvailable: boolean;
1131 readonly availableRevertTurnCounts?: ReadonlySet<number> | undefined;
1132 readonly unsettledRunId?: RunId | null;
1133}): Map<ChatMessage["id"], number> {
1134 const turnCountByRunId = new Map<RunId, number>();
1135 for (const checkpoint of input.checkpoints) {
1136 if (isRewindableCheckpoint(checkpoint)) {
1137 turnCountByRunId.set(checkpoint.runId, checkpoint.checkpointTurnCount);
1138 }
1139 }
1140 const targetByRunId = new Map<RunId, number | undefined>();
1141 const byUserMessageId = new Map<ChatMessage["id"], number>();
1142 let previousRunId: RunId | null = null;
1143 for (const entry of input.timelineEntries) {
1144 // Inherited history belongs to the source thread, not our checkpoint scope.
1145 if (entry.kind !== "message" && entry.kind !== "work") continue;
1146 const projectedItem =
1147 entry.kind === "message" ? entry.projectedItem : entry.entry.projectedItem;
1148 if (projectedItem?.visibility === "inherited") continue;
1149 const runId =
1150 entry.kind === "message"
1151 ? entry.message.runId
1152 : entry.entry.itemType === "notification"
1153 ? entry.entry.runId
1154 : null;
1155 if (runId == null) continue;
1156 if (!targetByRunId.has(runId)) {
1157 targetByRunId.set(
1158 runId,
1159 previousRunId === null
1160 ? input.threadStartCheckpointAvailable
1161 ? 0
1162 : undefined
1163 : turnCountByRunId.get(previousRunId),
1164 );
1165 previousRunId = runId;
1166 }
1167 if (entry.kind !== "message") continue;
1168 const { message } = entry;
1169 if (message.role !== "user" || message.runId === input.unsettledRunId) continue;
1170 if (message.inputIntent !== "turn_start" && message.inputIntent !== "queued_turn") continue;
1171 const target = targetByRunId.get(runId);
1172 if (
1173 target !== undefined &&
1174 (input.availableRevertTurnCounts === undefined || input.availableRevertTurnCounts.has(target))
1175 )
1176 byUserMessageId.set(message.id, target);
1177 }
1178 return byUserMessageId;
1179}
1180
1181// A missing or failed snapshot (no git, a side chat, a capture error) still pins a
1182// conversation position; only restoring files needs a ready one.
1183function isRewindableCheckpoint(checkpoint: Pick<OrchestrationV2Checkpoint, "status">) {
1184 return checkpoint.status !== "stale";
1185}
1186
1187export function findRevertCheckpoint(
1188 projection:
1189 | Pick<OrchestrationV2ThreadProjection, "checkpoints" | "checkpointScopes">
1190 | null
1191 | undefined,
1192 turnCount: number,
1193): OrchestrationV2Checkpoint | undefined {
1194 if (projection == null) return undefined;
1195 // A tracked repository's baseline also sits at ordinal zero; it is never a rewind target.
1196 const repositoryScopeIds = repositoryCheckpointScopeIds(projection.checkpointScopes);
1197 return projection.checkpoints.findLast(
1198 (checkpoint) =>
1199 !repositoryScopeIds.has(checkpoint.scopeId) &&
1200 isRewindableCheckpoint(checkpoint) &&
1201 (turnCount === 0
1202 ? checkpoint.ordinalWithinScope === 0 && checkpoint.appRunOrdinal === null
1203 : checkpoint.appRunOrdinal === turnCount),
1204 );
1205}
1206
1207export function derivePhase(runtime: ThreadStructureRuntime | null): SessionPhase {
1208 if (runtime === null) return "disconnected";
1209 if (
1210 runtime.status === "preparing" ||
1211 runtime.status === "starting" ||
1212 runtime.status === "queued"
1213 )
1214 return "connecting";
1215 if (runtime.status === "running" || runtime.status === "waiting") return "running";
1216 return "ready";
1217}
1218
1219/** Preparing and starting runs can be interrupted; Stop need not wait for running. */
1220export function deriveCanInterruptRunningThread(
1221 hasActiveThread: boolean,
1222 runtime: ThreadStructureRuntime | null,
1223): boolean {
1224 return (
1225 hasActiveThread &&
1226 (derivePhase(runtime) === "running" || threadRuntimeHasInterruptibleRun(runtime))
1227 );
1228}
1229
1230export type { TurnDiffSummary };