Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

session-logic.ts

1,056 lines34.8 KB

1import {
2 type AssetResource,
3 ProviderDriverKind,
4 type OrchestrationV2ExecutionNode,
5 type OrchestrationV2PlanArtifact,
6 type OrchestrationV2ProjectedTurnItem,
7 type OrchestrationV2RunAttempt,
8 type OrchestrationV2ThreadProjection,
9 type OrchestrationV2TurnItem,
10 type PlanId,
11 type RunId,
12 type ThreadId,
13 type ToolActivitySurface,
14 type ToolActivityIcon,
15 type ToolActivitySource,
16} from "@t3tools/contracts";
17import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";
18import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
19import type {
20 ThreadPendingApproval,
21 ThreadPendingUserInput,
22} from "@t3tools/client-runtime/state/thread-requests";
23import type { ThreadRunSummary, ThreadRuntimeSummary } from "@t3tools/client-runtime/state/shell";
24import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation";
25​
26import {
27 isImageAttachment,
28 type ChatAttachment,
29 type ChatMessage,
30 type ProposedPlan,
31 type SessionPhase,
32 type TurnDiffSummary,
33} from "./types";
34import * as DateTime from "effect/DateTime";
35import * as Equal from "effect/Equal";
36import { shallow } from "zustand/vanilla/shallow";
37​
38export { formatDuration, formatElapsed } from "@t3tools/shared/orchestrationTiming";
39​
40export type ProviderPickerKind = ProviderDriverKind;
41​
42export const PROVIDER_OPTIONS: Array<{
43 value: ProviderPickerKind;
44 label: string;
45 available: boolean;
46 pickerSidebarBadge?: "new" | "soon";
47}> = [
48 { value: ProviderDriverKind.make("codex"), label: "Codex", available: true },
49 { value: ProviderDriverKind.make("claudeAgent"), label: "Claude", available: true },
50 {
51 value: ProviderDriverKind.make("opencode"),
52 label: "OpenCode",
53 available: true,
54 pickerSidebarBadge: "new",
55 },
56 {
57 value: ProviderDriverKind.make("cursor"),
58 label: "Cursor",
59 available: true,
60 pickerSidebarBadge: "new",
61 },
62 { value: ProviderDriverKind.make("grok"), label: "Grok", available: true },
63 {
64 value: ProviderDriverKind.make("antigravity"),
65 label: "Antigravity",
66 available: true,
67 pickerSidebarBadge: "new",
68 },
69];
70​
71export type WorkLogToolLifecycleStatus =
72 | "idle"
73 | "inProgress"
74 | "completed"
75 | "failed"
76 | "declined"
77 | "stopped";
78​
79export interface WorkLogEntry {
80 readonly id: string;
81 readonly createdAt: string;
82 readonly runId?: RunId | null;
83 readonly label: string;
84 readonly detail?: string;
85 readonly command?: string;
86 readonly rawCommand?: string;
87 readonly changedFiles?: ReadonlyArray<string>;
88 readonly tone: "thinking" | "tool" | "info" | "error";
89 readonly toolTitle?: string;
90 readonly toolCallId?: string;
91 readonly viewedImagePath?: string;
92 readonly toolSurface?: ToolActivitySurface;
93 readonly toolIcon?: ToolActivityIcon;
94 readonly toolSource?: ToolActivitySource;
95 readonly sourceActivityKind?: string;
96 readonly taskId?: string;
97 readonly agentRole?: string;
98 readonly toolData?: unknown;
99 readonly requestKind?: string;
100 readonly itemType?: OrchestrationV2TurnItem["type"];
101 readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus;
102 readonly structuredPayload?: OrchestrationV2TurnItem;
103 readonly sourceItemType?: OrchestrationV2TurnItem["type"];
104 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
106​
107export type PendingApproval = ThreadPendingApproval;
108export type PendingUserInput = ThreadPendingUserInput;
109​
110export interface ActivePlanState {
111 readonly createdAt: string;
112 readonly runId: RunId | null;
113 readonly explanation?: string | null;
114 readonly steps: Array<{
115 readonly step: string;
116 readonly status: "pending" | "inProgress" | "completed";
117 }>;
119​
120export interface LatestProposedPlanState {
121 readonly id: PlanId;
122 readonly createdAt: string;
123 readonly updatedAt: string;
124 readonly runId: RunId | null;
125 readonly planMarkdown: string;
126 readonly status: OrchestrationV2PlanArtifact["status"];
128​
129export type TimelineAttempt = Pick<
130 OrchestrationV2RunAttempt,
131 "id" | "runId" | "attemptOrdinal" | "rootNodeId" | "status"
132>;
133​
134export type TimelineEntry = (
135 | {
136 readonly id: string;
137 readonly kind: "message";
138 readonly createdAt: string;
139 readonly message: ChatMessage;
140 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
141 }
142 | {
143 readonly id: string;
144 readonly kind: "proposed-plan";
145 readonly createdAt: string;
146 readonly proposedPlan: ProposedPlan;
147 }
148 | {
149 readonly id: string;
150 readonly kind: "work";
151 readonly createdAt: string;
152 readonly entry: WorkLogEntry;
153 }
154 | {
155 readonly id: string;
156 readonly kind: "event";
157 readonly createdAt: string;
158 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
159 }
160) & {
161 /** V2 identity resolved from the item's execution node, when locally available. */
162 readonly attempt?: TimelineAttempt;
163};
164​
165export function workLogEntryIsToolLike(entry: WorkLogEntry): boolean {
166 return (
167 entry.tone === "tool" ||
168 entry.tone === "thinking" ||
169 entry.tone === "error" ||
170 entry.command !== undefined ||
171 entry.requestKind !== undefined
172 );
174​
175/** Heuristic: providers often emit successful item status while error text lives in `detail` / `command`. */
176function toolDetailTextLooksLikeFailure(text: string): boolean {
177 const t = text.toLowerCase();
178 if (t.includes("file not found")) {
179 return true;
180 }
181 if (t.includes("no files found")) {
182 return true;
183 }
184 if (
185 t.includes("enoent") ||
186 t.includes("no such file or directory") ||
187 t.includes("no such file")
188 ) {
189 return true;
190 }
191 if (t.includes("cannot find path") && t.includes("because it does not exist")) {
192 return true;
193 }
194 if (t.includes("commandnotfoundexception")) {
195 return true;
196 }
197 if (t.includes("is not recognized as the name of a cmdlet")) {
198 return true;
199 }
200 if (t.includes("is not recognized") && t.includes("the term '")) {
201 return true;
202 }
203 if (t.includes("a parameter cannot be found that matches parameter name")) {
204 return true;
205 }
206 if (t.includes("command not found")) {
207 return true;
208 }
209 if (/<exited with exit code\s+[1-9]\d*\s*>/i.test(text)) {
210 return true;
211 }
212 if (/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text)) {
213 return true;
214 }
215 if (/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)) {
216 return true;
217 }
218 return false;
220​
221function workEntryIndicatesToolFailureFromOutput(
222 entry: WorkLogEntry,
223 includeCommand: boolean,
224): boolean {
225 if (entry.tone === "error") {
226 return true;
227 }
228 const ls = entry.toolLifecycleStatus;
229 if (ls === "failed" || ls === "declined") {
230 return true;
231 }
232 if (!workLogEntryIsToolLike(entry)) {
233 return false;
234 }
235 const parts: string[] = [];
236 if (entry.detail) {
237 parts.push(entry.detail);
238 }
239 if (includeCommand && entry.command) {
240 parts.push(entry.command);
241 }
242 const blob = parts.join("\n");
243 if (blob.length === 0) {
244 return false;
245 }
246 return toolDetailTextLooksLikeFailure(blob);
248​
249/** True when a tool failed, including providers that put error output in `command`. */
250export function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean {
251 return workEntryIndicatesToolFailureFromOutput(entry, true);
253​
254/** True when the rendered result indicates failure. The command itself is user intent, not output. */
255export function workEntryDisplayIndicatesToolFailure(entry: WorkLogEntry): boolean {
256 return workEntryIndicatesToolFailureFromOutput(entry, false);
258​
259/** Severe failures keep the red treatment ordinary tool failures lost: provider
260 * runtime errors mean the turn or a core side effect broke, not that a
261 * command exited nonzero. */
262export function workEntrySignalsSevereFailure(entry: WorkLogEntry): boolean {
263 return entry.itemType === "error";
265​
266export function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean {
267 if (
268 !workLogEntryIsToolLike(entry) ||
269 workEntryIndicatesToolFailure(entry) ||
270 entry.tone === "thinking"
271 ) {
272 return false;
273 }
274 const status = entry.toolLifecycleStatus;
275 return (
276 status !== "failed" &&
277 status !== "declined" &&
278 status !== "inProgress" &&
279 status !== "stopped" &&
280 status !== "idle"
281 );
283​
284export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolean {
285 return (
286 workLogEntryIsToolLike(entry) &&
287 !workEntryIndicatesToolFailure(entry) &&
288 !workEntryIndicatesToolSuccess(entry)
289 );
291​
292export function isLatestRunSettled(
293 latestRun: Pick<ThreadRunSummary, "runId" | "startedAt" | "completedAt" | "status"> | null,
294 runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId"> | null,
295): boolean {
296 if (latestRun === null) return false;
297 if (
298 latestRun.status === "preparing" ||
299 latestRun.status === "queued" ||
300 latestRun.status === "starting" ||
301 latestRun.status === "running" ||
302 latestRun.status === "waiting"
303 )
304 return false;
305 return runtime?.activeRunId !== latestRun.runId;
307​
308export function deriveActiveWorkStartedAt(
309 latestRun: Pick<ThreadRunSummary, "runId" | "startedAt" | "completedAt" | "status"> | null,
310 runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId"> | null,
311 sendStartedAt: string | null,
312): string | null {
313 if (runtime?.activeRunId !== null && runtime?.activeRunId !== undefined) {
314 return latestRun?.runId === runtime.activeRunId
315 ? (latestRun.startedAt ?? sendStartedAt)
316 : sendStartedAt;
317 }
318 return isLatestRunSettled(latestRun, runtime)
319 ? sendStartedAt
320 : (latestRun?.startedAt ?? sendStartedAt);
322​
323export function derivePendingApprovals(
324 approvals: ReadonlyArray<ThreadPendingApproval>,
325): ThreadPendingApproval[] {
326 return [...approvals].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
328​
329export function derivePendingUserInputs(
330 inputs: ReadonlyArray<ThreadPendingUserInput>,
331): ThreadPendingUserInput[] {
332 return [...inputs].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
334​
335export function deriveActivePlanState(
336 projection: OrchestrationV2ThreadProjection | null,
337 latestRunId: RunId | undefined,
338): ActivePlanState | null {
339 if (projection === null) return null;
340 const plans = projection.plans.filter((plan) => plan.kind === "todo_list");
341 const plan =
342 [...plans].toReversed().find((candidate) => candidate.runId === latestRunId) ??
343 plans.at(-1) ??
344 null;
345 if (plan === null || plan.steps.length === 0) return null;
346 return {
347 createdAt: planItemTime(projection, plan.id),
348 runId: plan.runId,
349 explanation: plan.explanation ?? null,
350 steps: plan.steps.map(({ text, status }) => ({
351 step: text,
352 status: status === "running" ? "inProgress" : status,
353 })),
354 };
356​
357function planItemTime(projection: OrchestrationV2ThreadProjection, planId: PlanId): string {
358 const item = projection.turnItems.findLast(
359 (candidate) =>
360 (candidate.type === "proposed_plan" || candidate.type === "todo_list") &&
361 candidate.planId === planId,
362 );
363 return DateTime.formatIso(item?.updatedAt ?? projection.updatedAt);
365​
366function toLatestProposedPlanState(
367 projection: OrchestrationV2ThreadProjection,
368 plan: Extract<OrchestrationV2PlanArtifact, { readonly kind: "proposed_plan" }>,
369): LatestProposedPlanState {
370 const updatedAt = planItemTime(projection, plan.id);
371 return {
372 id: plan.id,
373 createdAt: updatedAt,
374 updatedAt,
375 runId: plan.runId,
376 planMarkdown: plan.markdown,
377 status: plan.status,
378 };
380​
381export function findLatestProposedPlan(
382 projection: OrchestrationV2ThreadProjection | null,
383 latestRunId: RunId | string | null | undefined,
384): LatestProposedPlanState | null {
385 if (projection === null) return null;
386 const plans = projection.plans.filter((plan) => plan.kind === "proposed_plan");
387 const candidates = latestRunId ? plans.filter((plan) => plan.runId === latestRunId) : plans;
388 const plan = [...(candidates.length > 0 ? candidates : plans)]
389 .toSorted(
390 (left, right) =>
391 planItemTime(projection, left.id).localeCompare(planItemTime(projection, right.id)) ||
392 left.id.localeCompare(right.id),
393 )
394 .at(-1);
395 return plan === undefined ? null : toLatestProposedPlanState(projection, plan);
397​
398export function findSidebarProposedPlan(input: {
399 readonly threads: ReadonlyArray<{
400 readonly id: ThreadId;
401 readonly projection: OrchestrationV2ThreadProjection;
402 }>;
403 readonly latestRun: Pick<ThreadRunSummary, "runId" | "sourcePlanRef"> | null;
404 readonly latestRunSettled: boolean;
405 readonly threadId: ThreadId | string | null | undefined;
406}): LatestProposedPlanState | null {
407 if (!input.latestRunSettled && input.latestRun?.sourcePlanRef !== undefined) {
408 const source = input.latestRun.sourcePlanRef;
409 const sourceProjection = input.threads.find(
410 (thread) => thread.id === source.threadId,
411 )?.projection;
412 const plan = sourceProjection?.plans.find(
413 (candidate) => candidate.kind === "proposed_plan" && candidate.id === source.planId,
414 );
415 if (sourceProjection !== undefined && plan?.kind === "proposed_plan") {
416 return toLatestProposedPlanState(sourceProjection, plan);
417 }
418 }
419 const activeProjection = input.threads.find((thread) => thread.id === input.threadId)?.projection;
420 return findLatestProposedPlan(activeProjection ?? null, input.latestRun?.runId);
422​
423export function hasActionableProposedPlan(plan: LatestProposedPlanState | null): boolean {
424 return plan?.status === "active";
426​
427const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"]["type"]>([
428 "approval_request",
429 "fork",
430 "handoff",
431 "run_interrupt_request",
432 "run_interrupt_result",
433 "subagent",
434 "thread_created",
435 "user_input_request",
436]);
437​
438const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
439 "fork",
440 "subagent",
441 "thread_created",
442]);
443​
444export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean {
445 return (
446 entry.kind === "event" && PERSISTENT_RESOURCE_V2_ITEM_TYPES.has(entry.projectedItem.item.type)
447 );
449​
450function projectedItemCreatedAt(row: OrchestrationV2ProjectedTurnItem): string {
451 return DateTime.formatIso(row.item.startedAt ?? row.item.updatedAt);
453​
454function projectedWorkEntryStatus(
455 item: OrchestrationV2TurnItem,
456): NonNullable<WorkLogEntry["toolLifecycleStatus"]> {
457 switch (item.status) {
458 case "pending":
459 case "running":
460 case "waiting":
461 return "inProgress";
462 case "completed":
463 return "completed";
464 case "idle":
465 return "idle";
466 case "failed":
467 return "failed";
468 case "cancelled":
469 case "interrupted":
470 return "stopped";
471 }
473​
474function projectedWorkEntryTone(item: OrchestrationV2TurnItem): WorkLogEntry["tone"] {
475 if (item.type === "error") return "info";
476 if (item.type === "reasoning") return "thinking";
477 switch (item.type) {
478 case "command_execution":
479 case "file_change":
480 case "file_search":
481 case "web_search":
482 case "dynamic_tool":
483 case "subagent":
484 return "tool";
485 default:
486 return "info";
487 }
489​
490export function providerErrorPresentation(
491 item: Extract<OrchestrationV2TurnItem, { readonly type: "error" }>,
492): { readonly label: string; readonly detail: string } {
493 if (item.retry === undefined) {
494 return {
495 label: item.title?.trim() || "Provider error",
496 detail: item.failure.message,
497 };
498 }
499 const progress =
500 item.retry.maxAttempts === null
501 ? `${item.retry.attempt}`
502 : `${item.retry.attempt}/${item.retry.maxAttempts}`;
503 const label =
504 item.status === "running"
505 ? `Retrying provider (${progress})`
506 : item.status === "completed"
507 ? `Provider recovered (${progress} retries)`
508 : item.status === "failed"
509 ? `Provider error after ${progress} retries`
510 : `Provider retry stopped (${progress})`;
511 const retryDelay =
512 item.status === "running" && item.retry.retryDelayMs !== null && item.retry.retryDelayMs > 0
513 ? item.retry.retryDelayMs < 1_000
514 ? ` Retrying in ${item.retry.retryDelayMs}ms.`
515 : ` Retrying in ${(item.retry.retryDelayMs / 1_000).toFixed(1).replace(/\.0$/u, "")}s.`
516 : "";
517 return {
518 label,
519 detail: `${item.failure.message}${retryDelay}`,
520 };
522​
523function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry {
524 const { item } = row;
525 const title = item.title?.trim() || null;
526 const common = {
527 id: item.id,
528 createdAt: projectedItemCreatedAt(row),
529 runId: item.runId,
530 tone: projectedWorkEntryTone(item),
531 itemType: item.type,
532 toolLifecycleStatus: projectedWorkEntryStatus(item),
533 structuredPayload: item,
534 projectedItem: row,
535 ...extractToolActivityPresentation(item),
536 } as const;
537​
538 switch (item.type) {
539 case "compaction":
540 return {
541 ...common,
542 label: item.status === "running" ? "Compacting context" : "Context compacted",
543 sourceActivityKind: "context-compaction",
544 ...(item.summary ? { detail: item.summary } : {}),
545 };
546 case "reasoning":
547 return {
548 ...common,
549 label: title ?? "Thinking",
550 ...(item.text ? { detail: item.text } : {}),
551 };
552 case "command_execution":
553 return {
554 ...common,
555 label: title ?? "Ran command",
556 command: item.input,
557 rawCommand: item.input,
558 ...(item.output ? { detail: item.output } : {}),
559 toolTitle: title ?? "Command",
560 toolData: item,
561 };
562 case "file_change": {
563 const detail = item.diffStr ?? item.newStr;
564 return {
565 ...common,
566 label: title ?? `Changed ${item.fileName}`,
567 changedFiles: [item.fileName],
568 ...(detail ? { detail } : {}),
569 toolTitle: title ?? "File change",
570 toolData: item,
571 };
572 }
573 case "file_search":
574 return {
575 ...common,
576 label: title ?? "Searched files",
577 ...(item.pattern ? { detail: item.pattern } : {}),
578 toolTitle: title ?? "File search",
579 toolData: item,
580 };
581 case "web_search":
582 return {
583 ...common,
584 label: title ?? "Searched the web",
585 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
586 toolTitle: title ?? "Web search",
587 toolData: item,
588 };
589 case "checkpoint":
590 return {
591 ...common,
592 label: title ?? "Checkpoint captured",
593 changedFiles: item.files.map((file) => file.path),
594 toolData: item,
595 };
596 case "system_notice":
597 return {
598 ...common,
599 label: item.message,
600 sourceActivityKind: "runtime.warning",
601 };
602 case "error": {
603 const presentation = providerErrorPresentation(item);
604 return {
605 ...common,
606 ...presentation,
607 ...(item.retry === undefined ? { sourceActivityKind: "runtime.error" } : {}),
608 toolData: item,
609 };
610 }
611 case "dynamic_tool":
612 return {
613 ...common,
614 label: title ?? item.toolName ?? "Tool call",
615 toolTitle: title ?? item.toolName ?? "Tool",
616 toolData: { input: item.input, output: item.output },
617 };
618 default:
619 return {
620 ...common,
621 label: title ?? item.type.replaceAll("_", " "),
622 toolData: item,
623 };
624 }
626​
627/**
628 * Builds the web timeline in the exact order committed by `visibleTurnItems`.
629 * Committed rows are presented directly from their projected item. Queued
630 * input is absent by construction until dispatch creates its user turn item.
631 * Persistent client-owned messages are inserted by timestamp without sorting
632 * the canonical sequence. True optimistic sends remain appended afterward.
633 */
634export interface TimelineEntriesInput {
635 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
636 readonly optimisticMessages: ReadonlyArray<ChatMessage>;
637 readonly anchoredMessages?: ReadonlyArray<ChatMessage>;
638 readonly attachmentUrlById?: ReadonlyMap<string, string>;
639 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
640 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
641 readonly plans?: ReadonlyArray<OrchestrationV2PlanArtifact>;
643​
644export interface TimelineEntriesProjection {
645 readonly input: TimelineEntriesInput;
646 readonly entries: TimelineEntry[];
648​
649export function deriveTimelineEntriesFromVisibleTurnItems(
650 input: TimelineEntriesInput,
651): TimelineEntry[] {
652 const committedMessageIds = new Set<string>();
653 const entries: TimelineEntry[] = [];
654 const attemptByRootNodeId = new Map(
655 (input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
656 );
657 const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const));
658 const planById = new Map((input.plans ?? []).map((plan) => [plan.id, plan] as const));
659​
660 const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => {
661 if (item.nodeId === null || item.runId === null) return undefined;
662 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
663 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
664 while (nodeId !== null && !visited.has(nodeId)) {
665 visited.add(nodeId);
666 const directAttempt = attemptByRootNodeId.get(nodeId);
667 if (directAttempt?.runId === item.runId) return directAttempt;
668 const node = nodeById.get(nodeId);
669 if (node === undefined) return undefined;
670 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
671 if (rootAttempt?.runId === item.runId) return rootAttempt;
672 nodeId = node.parentNodeId;
673 }
674 return undefined;
675 };
676​
677 for (const row of input.visibleTurnItems) {
678 const { item } = row;
679 if (turnItemIsWorkspacePreparation(item)) continue;
680 // Task progress belongs in the composer, not between conversation entries.
681 if (item.type === "todo_list") continue;
682 const createdAt = projectedItemCreatedAt(row);
683 const attempt = resolveAttempt(item);
684 const attemptMetadata = attempt === undefined ? {} : { attempt };
685 if (item.type === "user_message" || item.type === "assistant_message") {
686 const message: ChatMessage = {
687 id: item.messageId,
688 role: item.type === "user_message" ? "user" : "assistant",
689 text: item.text,
690 ...((item.attachments?.length ?? 0) > 0
691 ? {
692 attachments: (item.attachments ?? []).map((attachment) => {
693 const previewUrl = input.attachmentUrlById?.get(attachment.id);
694 return previewUrl ? { ...attachment, previewUrl } : attachment;
695 }),
696 }
697 : {}),
698 runId: item.runId,
699 streaming: item.type === "assistant_message" && item.streaming,
700 ...(item.type === "user_message"
701 ? { createdBy: item.createdBy, creationSource: item.creationSource }
702 : {}),
703 createdAt,
704 updatedAt: DateTime.formatIso(item.updatedAt),
705 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
706 };
707 committedMessageIds.add(message.id);
708 entries.push({
709 id: message.id,
710 kind: "message",
711 createdAt,
712 message,
713 projectedItem: row,
714 ...attemptMetadata,
715 });
716 continue;
717 }
718​
719 if (item.type === "proposed_plan") {
720 const plan = planById.get(item.planId);
721 const proposedPlan = {
722 id: item.planId,
723 runId: item.runId,
724 planMarkdown: item.markdown,
725 status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
726 createdAt,
727 updatedAt: DateTime.formatIso(item.updatedAt),
728 };
729 entries.push({
730 id: item.id,
731 kind: "proposed-plan",
732 createdAt,
733 proposedPlan,
734 ...attemptMetadata,
735 });
736 continue;
737 }
738​
739 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
740 entries.push({
741 id: item.id,
742 kind: "event",
743 createdAt,
744 projectedItem: row,
745 ...attemptMetadata,
746 });
747 continue;
748 }
749​
750 entries.push({
751 id: item.id,
752 kind: "work",
753 createdAt,
754 entry: projectedWorkEntry(row),
755 ...attemptMetadata,
756 });
757 }
758​
759 const retainedMessageIds = new Set(committedMessageIds);
760 for (const message of input.anchoredMessages ?? []) {
761 if (retainedMessageIds.has(message.id)) continue;
762 retainedMessageIds.add(message.id);
763 const entry: TimelineEntry = {
764 id: message.id,
765 kind: "message",
766 createdAt: message.createdAt,
767 message,
768 };
769 const insertionIndex = entries.findIndex(
770 (candidate) => candidate.createdAt > message.createdAt,
771 );
772 if (insertionIndex === -1) {
773 entries.push(entry);
774 } else {
775 entries.splice(insertionIndex, 0, entry);
776 }
777 }
778​
779 for (const message of input.optimisticMessages) {
780 if (message.inputIntent !== "queued_turn" && !retainedMessageIds.has(message.id)) {
781 retainedMessageIds.add(message.id);
782 entries.push({
783 id: message.id,
784 kind: "message",
785 createdAt: message.createdAt,
786 message,
787 });
788 }
789 }
790​
791 return entries;
793​
794type AttachmentResource = Extract<AssetResource, { readonly _tag: "attachment" }>;
795const EMPTY_IMAGE_RESOURCES = Object.freeze<ReadonlyArray<AttachmentResource>>([]);
796​
797/** A mounted row requests its stored images. Local previews keep their existing URLs. */
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 }));
812​
813/** Handoffs need server URLs even while their message rows are unmounted. */
814export function selectHandoffImageResources(
815 messages: ReadonlyArray<Pick<ChatMessage, "id" | "role" | "attachments">> | undefined,
816 handoffs: Readonly<Record<string, ReadonlyArray<string>>>,
817): ReadonlyArray<AttachmentResource> {
818 if (Object.keys(handoffs).length === 0) return EMPTY_IMAGE_RESOURCES;
819 const attachmentIds = new Set<string>();
820 for (const message of messages ?? []) {
821 if (message.role !== "user" || !handoffs[message.id]?.length) continue;
822 for (const attachment of message.attachments ?? []) {
823 if (isImageAttachment(attachment)) attachmentIds.add(attachment.id);
824 }
825 }
826 return attachmentIds.size === 0
827 ? EMPTY_IMAGE_RESOURCES
828 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
830​
831/** Own one mapper per preview stage. Immutable messages retain unchanged preview objects. */
832export 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 };
878​
879/** Text and update time do not change a streaming assistant message's row structure. */
880export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
881 if (
882 previous.role !== "assistant" ||
883 next.role !== "assistant" ||
884 !previous.streaming ||
885 !next.streaming
886 ) {
887 return false;
888 }
889 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previous;
890 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = next;
891 return shallow(previousMetadata, nextMetadata);
893​
894/** Keep provenance and execution metadata in the rebuild boundary, including inspector data. */
895export function isStreamingTurnItemTextUpdate(
896 previous: OrchestrationV2ProjectedTurnItem,
897 next: OrchestrationV2ProjectedTurnItem,
898): boolean {
899 const { item: previousItem, ...previousSource } = previous;
900 const { item: nextItem, ...nextSource } = next;
901 if (
902 previousItem.type !== "assistant_message" ||
903 nextItem.type !== "assistant_message" ||
904 !previousItem.streaming ||
905 !nextItem.streaming ||
906 !shallow(previousSource, nextSource) ||
907 projectedItemCreatedAt(previous) !== projectedItemCreatedAt(next)
908 ) {
909 return false;
910 }
911 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previousItem;
912 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = nextItem;
913 // Wire decoding can recreate timestamps and attachments on each update.
914 // Compare only the changed item's metadata, never the entire transcript.
915 return Equal.equals(previousMetadata, nextMetadata);
917​
918function reuseTimelineEntries(
919 input: TimelineEntriesInput,
920 previous: TimelineEntriesProjection,
921): TimelineEntry[] | null {
922 const before = previous.input;
923 if (
924 input.visibleTurnItems.length < before.visibleTurnItems.length ||
925 !shallow(input.optimisticMessages, before.optimisticMessages) ||
926 !shallow(input.anchoredMessages, before.anchoredMessages) ||
927 !shallow(input.attachmentUrlById, before.attachmentUrlById) ||
928 !shallow(input.attempts, before.attempts) ||
929 !shallow(input.nodes, before.nodes) ||
930 !shallow(input.plans, before.plans)
931 ) {
932 return null;
933 }
934 const appended = input.visibleTurnItems.length > before.visibleTurnItems.length;
935 // Anchored and optimistic messages need to be interleaved/deduplicated when
936 // committed items arrive. Keep the full projection for that transition.
937 if (
938 appended &&
939 (input.optimisticMessages.length > 0 || (input.anchoredMessages?.length ?? 0) > 0)
940 ) {
941 return null;
942 }
943 const replacements = new Map<
944 OrchestrationV2ProjectedTurnItem,
945 OrchestrationV2ProjectedTurnItem
946 >();
947 for (const [index, previousItem] of before.visibleTurnItems.entries()) {
948 const item = input.visibleTurnItems[index]!;
949 if (item === previousItem) continue;
950 if (!isStreamingTurnItemTextUpdate(previousItem, item)) return null;
951 replacements.set(previousItem, item);
952 }
953 if (replacements.size === 0 && !appended) return previous.entries;
954 const entries = previous.entries.map((entry): TimelineEntry => {
955 const row =
956 entry.kind === "message" && entry.projectedItem !== undefined
957 ? replacements.get(entry.projectedItem)
958 : undefined;
959 if (entry.kind !== "message" || row?.item.type !== "assistant_message") return entry;
960 return {
961 ...entry,
962 projectedItem: row,
963 message: {
964 ...entry.message,
965 text: row.item.text,
966 updatedAt: DateTime.formatIso(row.item.updatedAt),
967 },
968 };
969 });
970 if (appended) {
971 entries.push(
972 ...deriveTimelineEntriesFromVisibleTurnItems({
973 ...input,
974 visibleTurnItems: input.visibleTurnItems.slice(before.visibleTurnItems.length),
975 }),
976 );
977 }
978 return entries;
980​
981/** Reuse immutable entries during streaming without reordering the canonical v2 sequence. */
982export function deriveTimelineEntriesFromVisibleTurnItemsWithState(
983 input: TimelineEntriesInput,
984 previous: TimelineEntriesProjection | null = null,
985): TimelineEntriesProjection {
986 const reused = previous === null ? null : reuseTimelineEntries(input, previous);
987 if (reused !== null) return { input, entries: reused };
988 const entries = deriveTimelineEntriesFromVisibleTurnItems(input);
989 if (previous === null || !shallow(input.attachmentUrlById, previous.input.attachmentUrlById)) {
990 return { input, entries };
991 }
992 // Tool output and lifecycle changes rebuild grouping, but unchanged message
993 // objects and previews still let memoized history rows stay mounted.
994 const previousMessages = new Map(
995 previous.entries.flatMap((entry) =>
996 entry.kind === "message" ? [[entry.id, entry] as const] : [],
997 ),
998 );
999 return {
1000 input,
1001 entries: entries.map((entry) => {
1002 if (entry.kind !== "message" || entry.projectedItem === undefined) return entry;
1003 const before = previousMessages.get(entry.id);
1004 if (before?.projectedItem !== entry.projectedItem) return entry;
1005 return before.attempt === entry.attempt ? before : { ...entry, message: before.message };
1006 }),
1007 };
1009​
1010export function inferCheckpointTurnCountByRunId(
1011 summaries: ReadonlyArray<ThreadCheckpointSummary>,
1012): Record<string, number> {
1013 return Object.fromEntries(
1014 summaries.flatMap((summary) =>
1015 summary.runId === null ? [] : [[summary.runId, summary.checkpointTurnCount] as const],
1016 ),
1017 );
1019​
1020export function deriveRevertTurnCountByUserMessageId(input: {
1021 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
1022 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
1023}): Map<ChatMessage["id"], number> {
1024 const readyCheckpointByRunId = new Map<RunId, ThreadCheckpointSummary>();
1025 for (const checkpoint of input.checkpoints) {
1026 if (checkpoint.status === "ready") {
1027 readyCheckpointByRunId.set(checkpoint.runId, checkpoint);
1030 const byUserMessageId = new Map<ChatMessage["id"], number>();
1031 for (const entry of input.timelineEntries) {
1032 if (entry.kind !== "message" || entry.message.role !== "user") continue;
1033 if (entry.message.inputIntent !== "turn_start" && entry.message.inputIntent !== "queued_turn") {
1034 continue;
1036 if (entry.message.runId === null) continue;
1037 const checkpoint = readyCheckpointByRunId.get(entry.message.runId);
1038 if (checkpoint === undefined) continue;
1039 byUserMessageId.set(entry.message.id, Math.max(0, checkpoint.checkpointTurnCount - 1));
1041 return byUserMessageId;
1043​
1044export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase {
1045 if (runtime === null) return "disconnected";
1046 if (
1047 runtime.status === "preparing" ||
1048 runtime.status === "starting" ||
1049 runtime.status === "queued"
1051 return "connecting";
1052 if (runtime.status === "running" || runtime.status === "waiting") return "running";
1053 return "ready";
1055​
1056export type { TurnDiffSummary };