@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 03:37 UTC

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