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

session-logic.ts

970 lines32.4 KB

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