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

session-logic.ts

990 lines33.2 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" && entry.itemType !== "reasoning")
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 const foldedAnswerMessageIds = new Set(
566 input.visibleTurnItems.flatMap(({ item }) =>
567 item.type === "user_input_request" && item.questionAnswer
568 ? [`async-answer:${item.questionAnswer.requestId}`]
569 : [],
570 ),
571 );
572 for (const row of input.visibleTurnItems) {
573 const { item } = row;
574 if (turnItemIsWorkspacePreparation(item)) continue;
575 // Task progress belongs in the composer, not between conversation entries.
576 if (item.type === "todo_list" || item.type === "checkpoint") continue;
577 if (item.type === "user_message" && foldedAnswerMessageIds.has(item.messageId)) continue;
578 const createdAt = projectedItemCreatedAt(row);
579 const attempt = resolveAttempt(item);
580 const attemptMetadata = attempt === undefined ? {} : { attempt };
581 if (item.type === "notification") {
582 entries.push({
583 id: item.id,
584 kind: "work",
585 createdAt,
586 entry: {
587 id: item.id,
588 createdAt,
589 runId: item.runId,
590 label: item.summary,
591 tone: "info",
592 itemType: item.type,
593 structuredPayload: item,
594 projectedItem: row,
595 },
596 ...attemptMetadata,
597 });
598 continue;
599 }
600 if (item.type === "user_message" || item.type === "assistant_message") {
601 const message: ChatMessage = {
602 id: item.messageId,
603 role: item.type === "user_message" ? "user" : "assistant",
604 text: item.text,
605 ...(item.type === "user_message" && item.context ? { context: item.context } : {}),
606 ...((item.attachments?.length ?? 0) > 0
607 ? {
608 attachments: (item.attachments ?? []).map((attachment) => {
609 const previewUrl = input.attachmentUrlById?.get(attachment.id);
610 return previewUrl ? { ...attachment, previewUrl } : attachment;
611 }),
612 }
613 : {}),
614 runId: item.runId,
615 streaming: item.type === "assistant_message" && item.streaming,
616 ...(item.type === "user_message"
617 ? {
618 createdBy: item.createdBy,
619 creationSource: item.creationSource,
620 ...(item.scheduledTaskId !== undefined
621 ? { scheduledTaskId: item.scheduledTaskId }
622 : {}),
623 }
624 : {}),
625 createdAt,
626 updatedAt: DateTime.formatIso(item.updatedAt),
627 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
628 };
629 committedMessageIds.add(message.id);
630 entries.push({
631 id: message.id,
632 kind: "message",
633 createdAt,
634 message,
635 projectedItem: row,
636 ...attemptMetadata,
637 });
638 continue;
639 }
640​
641 if (item.type === "proposed_plan") {
642 const plan = planById.get(item.planId);
643 const proposedPlan = {
644 id: item.planId,
645 runId: item.runId,
646 planMarkdown: item.markdown,
647 status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
648 createdAt,
649 updatedAt: DateTime.formatIso(item.updatedAt),
650 };
651 entries.push({
652 id: item.id,
653 kind: "proposed-plan",
654 createdAt,
655 proposedPlan,
656 ...attemptMetadata,
657 });
658 continue;
659 }
660​
661 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
662 entries.push({
663 id: item.id,
664 kind: "event",
665 createdAt,
666 projectedItem: row,
667 ...attemptMetadata,
668 });
669 continue;
670 }
671​
672 entries.push({
673 id: item.id,
674 kind: "work",
675 createdAt,
676 entry: projectedWorkEntry(row),
677 ...attemptMetadata,
678 });
679 }
680​
681 const retainedMessageIds = new Set([...committedMessageIds, ...foldedAnswerMessageIds]);
682 for (const message of input.anchoredMessages ?? []) {
683 if (retainedMessageIds.has(message.id)) continue;
684 retainedMessageIds.add(message.id);
685 const entry: TimelineEntry = {
686 id: message.id,
687 kind: "message",
688 createdAt: message.createdAt,
689 message,
690 };
691 const insertionIndex = entries.findIndex(
692 (candidate) => candidate.createdAt > message.createdAt,
693 );
694 if (insertionIndex === -1) {
695 entries.push(entry);
696 } else {
697 entries.splice(insertionIndex, 0, entry);
698 }
699 }
700​
701 for (const message of input.optimisticMessages) {
702 if (message.inputIntent !== "queued_turn" && !retainedMessageIds.has(message.id)) {
703 retainedMessageIds.add(message.id);
704 entries.push({
705 id: message.id,
706 kind: "message",
707 createdAt: message.createdAt,
708 message,
709 });
710 }
711 }
712​
713 return entries;
715​
716type AttachmentResource = Extract<AssetResource, { readonly _tag: "attachment" }>;
717const EMPTY_IMAGE_RESOURCES = Object.freeze<ReadonlyArray<AttachmentResource>>([]);
718​
719/** A mounted row requests its stored images. Local previews keep their existing URLs. */
720export function selectMessageImageResources(
721 attachments: ChatMessage["attachments"],
722): ReadonlyArray<AttachmentResource> {
723 const attachmentIds = new Set<string>();
724 for (const attachment of attachments ?? []) {
725 if (!isImageAttachment(attachment)) continue;
726 const previewUrl = attachment.previewUrl;
727 if (previewUrl?.startsWith("blob:") || previewUrl?.startsWith("data:")) continue;
728 attachmentIds.add(attachment.id);
729 }
730 return attachmentIds.size === 0
731 ? EMPTY_IMAGE_RESOURCES
732 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
734​
735/** Handoffs need server URLs even while their message rows are unmounted. */
736export function selectHandoffImageResources(
737 messages: ReadonlyArray<Pick<ChatMessage, "id" | "role" | "attachments">> | undefined,
738 handoffs: Readonly<Record<string, ReadonlyArray<string>>>,
739): ReadonlyArray<AttachmentResource> {
740 if (Object.keys(handoffs).length === 0) return EMPTY_IMAGE_RESOURCES;
741 const attachmentIds = new Set<string>();
742 for (const message of messages ?? []) {
743 if (message.role !== "user" || !handoffs[message.id]?.length) continue;
744 for (const attachment of message.attachments ?? []) {
745 if (isImageAttachment(attachment)) attachmentIds.add(attachment.id);
746 }
747 }
748 return attachmentIds.size === 0
749 ? EMPTY_IMAGE_RESOURCES
750 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
752​
753/** Own one mapper per preview stage. Immutable messages retain unchanged preview objects. */
754export function createMessageAttachmentPreviewProjector() {
755 const attachmentsBySource = new WeakMap<
756 ReadonlyArray<ChatAttachment>,
757 ReadonlyArray<ChatAttachment>
758 >();
759 const messagesBySource = new WeakMap<ChatMessage, ChatMessage>();
760 return (
761 message: ChatMessage,
762 previewUrlFor: (attachment: ChatAttachment) => string | undefined,
763 ): ChatMessage => {
764 const source = message.attachments;
765 if (!source || source.length === 0) return message;
766 const previous = attachmentsBySource.get(source) ?? source;
767 let changed: ChatAttachment[] | undefined;
768 let hasOverrides = false;
769 for (const [index, attachment] of source.entries()) {
770 const previewUrl = previewUrlFor(attachment);
771 const sourceUrl = "previewUrl" in attachment ? attachment.previewUrl : undefined;
772 const previousAttachment = previous[index]!;
773 const previousUrl =
774 "previewUrl" in previousAttachment ? previousAttachment.previewUrl : undefined;
775 const next =
776 !previewUrl || previewUrl === sourceUrl
777 ? attachment
778 : previewUrl === previousUrl
779 ? previousAttachment
780 : { ...attachment, previewUrl };
781 hasOverrides ||= next !== attachment;
782 if (next !== previousAttachment) {
783 changed ??= previous.slice();
784 changed[index] = next;
785 }
786 }
787 const attachments = hasOverrides ? (changed ?? previous) : source;
788 attachmentsBySource.set(source, attachments);
789 if (attachments === source) {
790 messagesBySource.delete(message);
791 return message;
792 }
793 const previousMessage = messagesBySource.get(message);
794 if (previousMessage?.attachments === attachments) return previousMessage;
795 const result = { ...message, attachments };
796 messagesBySource.set(message, result);
797 return result;
798 };
800​
801/** Text and update time do not change a streaming assistant message's row structure. */
802export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
803 if (
804 previous.role !== "assistant" ||
805 next.role !== "assistant" ||
806 !previous.streaming ||
807 !next.streaming
808 ) {
809 return false;
810 }
811 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previous;
812 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = next;
813 return shallow(previousMetadata, nextMetadata);
815​
816/** Keep provenance and execution metadata in the rebuild boundary, including inspector data. */
817export function isStreamingTurnItemTextUpdate(
818 previous: OrchestrationV2ProjectedTurnItem,
819 next: OrchestrationV2ProjectedTurnItem,
820): boolean {
821 const { item: previousItem, ...previousSource } = previous;
822 const { item: nextItem, ...nextSource } = next;
823 if (
824 previousItem.type !== "assistant_message" ||
825 nextItem.type !== "assistant_message" ||
826 !previousItem.streaming ||
827 !nextItem.streaming ||
828 !shallow(previousSource, nextSource) ||
829 projectedItemCreatedAt(previous) !== projectedItemCreatedAt(next)
830 ) {
831 return false;
832 }
833 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previousItem;
834 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = nextItem;
835 // Wire decoding can recreate timestamps and attachments on each update.
836 // Compare only the changed item's metadata, never the entire transcript.
837 return Equal.equals(previousMetadata, nextMetadata);
839​
840function reuseTimelineEntries(
841 input: TimelineEntriesInput,
842 previous: TimelineEntriesProjection,
843): TimelineEntry[] | null {
844 const before = previous.input;
845 if (
846 input.visibleTurnItems.length < before.visibleTurnItems.length ||
847 !shallow(input.optimisticMessages, before.optimisticMessages) ||
848 !shallow(input.anchoredMessages, before.anchoredMessages) ||
849 !shallow(input.attachmentUrlById, before.attachmentUrlById) ||
850 !shallow(input.attempts, before.attempts) ||
851 !shallow(input.nodes, before.nodes) ||
852 !shallow(input.plans, before.plans)
853 ) {
854 return null;
855 }
856 const appended = input.visibleTurnItems.length > before.visibleTurnItems.length;
857 // Anchored and optimistic messages need to be interleaved/deduplicated when
858 // committed items arrive. Keep the full projection for that transition.
859 if (
860 appended &&
861 (input.optimisticMessages.length > 0 || (input.anchoredMessages?.length ?? 0) > 0)
862 ) {
863 return null;
864 }
865 // Answer rows can replace a message already present in the retained prefix.
866 if (
867 appended &&
868 input.visibleTurnItems
869 .slice(before.visibleTurnItems.length)
870 .some(
871 ({ item }) =>
872 (item.type === "user_input_request" && item.questionAnswer !== undefined) ||
873 (item.type === "user_message" && item.messageId.startsWith("async-answer:")),
874 )
875 )
876 return null;
877 const replacements = new Map<
878 OrchestrationV2ProjectedTurnItem,
879 OrchestrationV2ProjectedTurnItem
880 >();
881 for (const [index, previousItem] of before.visibleTurnItems.entries()) {
882 const item = input.visibleTurnItems[index]!;
883 if (item === previousItem) continue;
884 if (!isStreamingTurnItemTextUpdate(previousItem, item)) return null;
885 replacements.set(previousItem, item);
886 }
887 if (replacements.size === 0 && !appended) return previous.entries;
888 const entries = previous.entries.map((entry): TimelineEntry => {
889 const row =
890 entry.kind === "message" && entry.projectedItem !== undefined
891 ? replacements.get(entry.projectedItem)
892 : undefined;
893 if (entry.kind !== "message" || row?.item.type !== "assistant_message") return entry;
894 return {
895 ...entry,
896 projectedItem: row,
897 message: {
898 ...entry.message,
899 text: row.item.text,
900 updatedAt: DateTime.formatIso(row.item.updatedAt),
901 },
902 };
903 });
904 if (appended) {
905 entries.push(
906 ...deriveTimelineEntriesFromVisibleTurnItems({
907 ...input,
908 visibleTurnItems: input.visibleTurnItems.slice(before.visibleTurnItems.length),
909 }),
910 );
911 }
912 return entries;
914​
915/** Reuse immutable entries during streaming without reordering the canonical v2 sequence. */
916export function deriveTimelineEntriesFromVisibleTurnItemsWithState(
917 input: TimelineEntriesInput,
918 previous: TimelineEntriesProjection | null = null,
919): TimelineEntriesProjection {
920 const reused = previous === null ? null : reuseTimelineEntries(input, previous);
921 if (reused !== null) return { input, entries: reused };
922 const entries = deriveTimelineEntriesFromVisibleTurnItems(input);
923 if (previous === null || !shallow(input.attachmentUrlById, previous.input.attachmentUrlById)) {
924 return { input, entries };
925 }
926 // Tool output and lifecycle changes rebuild grouping, but unchanged message
927 // objects and previews still let memoized history rows stay mounted.
928 const previousMessages = new Map(
929 previous.entries.flatMap((entry) =>
930 entry.kind === "message" ? [[entry.id, entry] as const] : [],
931 ),
932 );
933 return {
934 input,
935 entries: entries.map((entry) => {
936 if (entry.kind !== "message" || entry.projectedItem === undefined) return entry;
937 const before = previousMessages.get(entry.id);
938 if (before?.projectedItem !== entry.projectedItem) return entry;
939 return before.attempt === entry.attempt ? before : { ...entry, message: before.message };
940 }),
941 };
943​
944export function inferCheckpointTurnCountByRunId(
945 summaries: ReadonlyArray<ThreadCheckpointSummary>,
946): Record<string, number> {
947 return Object.fromEntries(
948 summaries.flatMap((summary) =>
949 summary.runId === null ? [] : [[summary.runId, summary.checkpointTurnCount] as const],
950 ),
951 );
953​
954export function deriveRevertTurnCountByUserMessageId(input: {
955 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
956 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
957}): Map<ChatMessage["id"], number> {
958 const readyCheckpointByRunId = new Map<RunId, ThreadCheckpointSummary>();
959 for (const checkpoint of input.checkpoints) {
960 if (checkpoint.status === "ready") {
961 readyCheckpointByRunId.set(checkpoint.runId, checkpoint);
962 }
963 }
964 const byUserMessageId = new Map<ChatMessage["id"], number>();
965 for (const entry of input.timelineEntries) {
966 if (entry.kind !== "message" || entry.message.role !== "user") continue;
967 if (entry.message.inputIntent !== "turn_start" && entry.message.inputIntent !== "queued_turn") {
968 continue;
969 }
970 if (entry.message.runId === null) continue;
971 const checkpoint = readyCheckpointByRunId.get(entry.message.runId);
972 if (checkpoint === undefined) continue;
973 byUserMessageId.set(entry.message.id, Math.max(0, checkpoint.checkpointTurnCount - 1));
974 }
975 return byUserMessageId;
977​
978export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase {
979 if (runtime === null) return "disconnected";
980 if (
981 runtime.status === "preparing" ||
982 runtime.status === "starting" ||
983 runtime.status === "queued"
984 )
985 return "connecting";
986 if (runtime.status === "running" || runtime.status === "waiting") return "running";
987 return "ready";
989​
990export type { TurnDiffSummary };