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

session-logic.ts

997 lines33.5 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:
364 item.failure.class === "usage_limit"
365 ? "Usage limit reached"
366 : item.title?.trim() || "Provider error",
367 detail: item.failure.message,
368 };
369 }
370 const progress =
371 item.retry.maxAttempts === null
372 ? `${item.retry.attempt}`
373 : `${item.retry.attempt}/${item.retry.maxAttempts}`;
374 const label =
375 item.status === "running"
376 ? `Retrying provider (${progress})`
377 : item.status === "completed"
378 ? `Provider recovered (${progress} retries)`
379 : item.status === "failed"
380 ? `${item.failure.class === "usage_limit" ? "Usage limit reached" : "Provider error"} after ${progress} retries`
381 : `Provider retry stopped (${progress})`;
382 const retryDelay =
383 item.status === "running" && item.retry.retryDelayMs !== null && item.retry.retryDelayMs > 0
384 ? item.retry.retryDelayMs < 1_000
385 ? ` Retrying in ${item.retry.retryDelayMs}ms.`
386 : ` Retrying in ${(item.retry.retryDelayMs / 1_000).toFixed(1).replace(/\.0$/u, "")}s.`
387 : "";
388 return {
389 label,
390 detail: `${item.failure.message}${retryDelay}`,
391 };
393​
394function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry {
395 const { item } = row;
396 const title = item.title?.trim() || null;
397 const common = {
398 id: item.id,
399 createdAt: projectedItemCreatedAt(row),
400 runId: item.runId,
401 tone: projectedWorkEntryTone(item),
402 itemType: item.type,
403 toolLifecycleStatus: projectedWorkEntryStatus(item),
404 structuredPayload: item,
405 projectedItem: row,
406 ...extractToolActivityPresentation(item),
407 } as const;
408​
409 switch (item.type) {
410 case "thread_created":
411 return {
412 ...common,
413 label: "Created thread",
414 };
415 case "compaction":
416 return {
417 ...common,
418 label: contextCompactionLabel(item),
419 sourceActivityKind: "context-compaction",
420 ...(item.summary ? { detail: item.summary } : {}),
421 };
422 case "reasoning":
423 return {
424 ...common,
425 label: title ?? "Thinking",
426 ...(item.text ? { detail: item.text } : {}),
427 };
428 case "command_execution":
429 return {
430 ...common,
431 label: title ?? "Ran command",
432 command: item.input,
433 rawCommand: item.input,
434 toolTitle: title ?? "Command",
435 toolData: item,
436 };
437 case "file_change": {
438 return {
439 ...common,
440 label:
441 title ??
442 (item.changes !== undefined && item.changes.length > 1
443 ? `Changed ${item.changes.length} files`
444 : `Changed ${item.fileName}`),
445 changedFiles: item.changes?.map((change) => change.path) ?? [item.fileName],
446 toolTitle: title ?? "File change",
447 toolData: item,
448 };
449 }
450 case "file_search":
451 return {
452 ...common,
453 label: title ?? "Searched files",
454 ...(item.pattern ? { detail: item.pattern } : {}),
455 toolTitle: title ?? "File search",
456 toolData: item,
457 };
458 case "web_search":
459 return {
460 ...common,
461 label: title ?? "Searched the web",
462 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
463 toolTitle: title ?? "Web search",
464 toolData: item,
465 };
466 case "checkpoint":
467 return {
468 ...common,
469 label: title ?? "Checkpoint captured",
470 changedFiles: item.files.map((file) => file.path),
471 toolData: item,
472 };
473 case "system_notice":
474 return {
475 ...common,
476 label: item.message,
477 sourceActivityKind: "runtime.warning",
478 };
479 case "error": {
480 const presentation = providerErrorPresentation(item);
481 return {
482 ...common,
483 ...presentation,
484 ...(item.failure.class === "usage_limit" && item.status !== "completed"
485 ? { sourceActivityKind: "runtime.warning" }
486 : item.retry === undefined
487 ? { sourceActivityKind: "runtime.error" }
488 : {}),
489 toolData: item,
490 };
491 }
492 case "dynamic_tool":
493 return {
494 ...common,
495 label: title ?? item.toolName ?? "Tool call",
496 toolTitle: title ?? item.toolName ?? "Tool",
497 toolData: { input: item.input, output: item.output },
498 };
499 case "approval_request":
500 return {
501 ...common,
502 label: title ?? "Approval requested",
503 detail: item.prompt ?? item.requestKind,
504 toolData: item,
505 };
506 case "user_input_request":
507 return {
508 ...common,
509 label: title ?? (item.questionAnswer ? "Answered questions" : "Input requested"),
510 ...(item.questionAnswer ? { questionAnswer: item.questionAnswer } : {}),
511 toolData: item,
512 };
513 default:
514 return {
515 ...common,
516 label: title ?? item.type.replaceAll("_", " "),
517 toolData: item,
518 };
519 }
521​
522/**
523 * Builds the web timeline in the exact order committed by `visibleTurnItems`.
524 * Committed rows are presented directly from their projected item. Queued
525 * input is absent by construction until dispatch creates its user turn item.
526 * Persistent client-owned messages are inserted by timestamp without sorting
527 * the canonical sequence. True optimistic sends remain appended afterward.
528 */
529export interface TimelineEntriesInput {
530 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
531 readonly optimisticMessages: ReadonlyArray<ChatMessage>;
532 readonly anchoredMessages?: ReadonlyArray<ChatMessage>;
533 readonly attachmentUrlById?: ReadonlyMap<string, string>;
534 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
535 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
536 readonly plans?: ReadonlyArray<OrchestrationV2PlanArtifact>;
538​
539export interface TimelineEntriesProjection {
540 readonly input: TimelineEntriesInput;
541 readonly entries: TimelineEntry[];
543​
544export function deriveTimelineEntriesFromVisibleTurnItems(
545 input: TimelineEntriesInput,
546): TimelineEntry[] {
547 const committedMessageIds = new Set<string>();
548 const entries: TimelineEntry[] = [];
549 const attemptByRootNodeId = new Map(
550 (input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
551 );
552 const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const));
553 const planById = new Map((input.plans ?? []).map((plan) => [plan.id, plan] as const));
554​
555 const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => {
556 if (item.nodeId === null || item.runId === null) return undefined;
557 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
558 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
559 while (nodeId !== null && !visited.has(nodeId)) {
560 visited.add(nodeId);
561 const directAttempt = attemptByRootNodeId.get(nodeId);
562 if (directAttempt?.runId === item.runId) return directAttempt;
563 const node = nodeById.get(nodeId);
564 if (node === undefined) return undefined;
565 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
566 if (rootAttempt?.runId === item.runId) return rootAttempt;
567 nodeId = node.parentNodeId;
568 }
569 return undefined;
570 };
571​
572 const foldedAnswerMessageIds = new Set(
573 input.visibleTurnItems.flatMap(({ item }) =>
574 item.type === "user_input_request" && item.questionAnswer
575 ? [`async-answer:${item.questionAnswer.requestId}`]
576 : [],
577 ),
578 );
579 for (const row of input.visibleTurnItems) {
580 const { item } = row;
581 if (turnItemIsWorkspacePreparation(item)) continue;
582 // Task progress belongs in the composer, not between conversation entries.
583 if (item.type === "todo_list" || item.type === "checkpoint") continue;
584 if (item.type === "user_message" && foldedAnswerMessageIds.has(item.messageId)) continue;
585 const createdAt = projectedItemCreatedAt(row);
586 const attempt = resolveAttempt(item);
587 const attemptMetadata = attempt === undefined ? {} : { attempt };
588 if (item.type === "notification") {
589 entries.push({
590 id: item.id,
591 kind: "work",
592 createdAt,
593 entry: {
594 id: item.id,
595 createdAt,
596 runId: item.runId,
597 label: item.summary,
598 tone: "info",
599 itemType: item.type,
600 structuredPayload: item,
601 projectedItem: row,
602 },
603 ...attemptMetadata,
604 });
605 continue;
606 }
607 if (item.type === "user_message" || item.type === "assistant_message") {
608 const message: ChatMessage = {
609 id: item.messageId,
610 role: item.type === "user_message" ? "user" : "assistant",
611 text: item.text,
612 ...(item.type === "user_message" && item.context ? { context: item.context } : {}),
613 ...((item.attachments?.length ?? 0) > 0
614 ? {
615 attachments: (item.attachments ?? []).map((attachment) => {
616 const previewUrl = input.attachmentUrlById?.get(attachment.id);
617 return previewUrl ? { ...attachment, previewUrl } : attachment;
618 }),
619 }
620 : {}),
621 runId: item.runId,
622 streaming: item.type === "assistant_message" && item.streaming,
623 ...(item.type === "user_message"
624 ? {
625 createdBy: item.createdBy,
626 creationSource: item.creationSource,
627 ...(item.scheduledTaskId !== undefined
628 ? { scheduledTaskId: item.scheduledTaskId }
629 : {}),
630 }
631 : {}),
632 createdAt,
633 updatedAt: DateTime.formatIso(item.updatedAt),
634 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
635 };
636 committedMessageIds.add(message.id);
637 entries.push({
638 id: message.id,
639 kind: "message",
640 createdAt,
641 message,
642 projectedItem: row,
643 ...attemptMetadata,
644 });
645 continue;
646 }
647​
648 if (item.type === "proposed_plan") {
649 const plan = planById.get(item.planId);
650 const proposedPlan = {
651 id: item.planId,
652 runId: item.runId,
653 planMarkdown: item.markdown,
654 status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
655 createdAt,
656 updatedAt: DateTime.formatIso(item.updatedAt),
657 };
658 entries.push({
659 id: item.id,
660 kind: "proposed-plan",
661 createdAt,
662 proposedPlan,
663 ...attemptMetadata,
664 });
665 continue;
666 }
667​
668 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
669 entries.push({
670 id: item.id,
671 kind: "event",
672 createdAt,
673 projectedItem: row,
674 ...attemptMetadata,
675 });
676 continue;
677 }
678​
679 entries.push({
680 id: item.id,
681 kind: "work",
682 createdAt,
683 entry: projectedWorkEntry(row),
684 ...attemptMetadata,
685 });
686 }
687​
688 const retainedMessageIds = new Set([...committedMessageIds, ...foldedAnswerMessageIds]);
689 for (const message of input.anchoredMessages ?? []) {
690 if (retainedMessageIds.has(message.id)) continue;
691 retainedMessageIds.add(message.id);
692 const entry: TimelineEntry = {
693 id: message.id,
694 kind: "message",
695 createdAt: message.createdAt,
696 message,
697 };
698 const insertionIndex = entries.findIndex(
699 (candidate) => candidate.createdAt > message.createdAt,
700 );
701 if (insertionIndex === -1) {
702 entries.push(entry);
703 } else {
704 entries.splice(insertionIndex, 0, entry);
705 }
706 }
707​
708 for (const message of input.optimisticMessages) {
709 if (message.inputIntent !== "queued_turn" && !retainedMessageIds.has(message.id)) {
710 retainedMessageIds.add(message.id);
711 entries.push({
712 id: message.id,
713 kind: "message",
714 createdAt: message.createdAt,
715 message,
716 });
717 }
718 }
719​
720 return entries;
722​
723type AttachmentResource = Extract<AssetResource, { readonly _tag: "attachment" }>;
724const EMPTY_IMAGE_RESOURCES = Object.freeze<ReadonlyArray<AttachmentResource>>([]);
725​
726/** A mounted row requests its stored images. Local previews keep their existing URLs. */
727export function selectMessageImageResources(
728 attachments: ChatMessage["attachments"],
729): ReadonlyArray<AttachmentResource> {
730 const attachmentIds = new Set<string>();
731 for (const attachment of attachments ?? []) {
732 if (!isImageAttachment(attachment)) continue;
733 const previewUrl = attachment.previewUrl;
734 if (previewUrl?.startsWith("blob:") || previewUrl?.startsWith("data:")) continue;
735 attachmentIds.add(attachment.id);
736 }
737 return attachmentIds.size === 0
738 ? EMPTY_IMAGE_RESOURCES
739 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
741​
742/** Handoffs need server URLs even while their message rows are unmounted. */
743export function selectHandoffImageResources(
744 messages: ReadonlyArray<Pick<ChatMessage, "id" | "role" | "attachments">> | undefined,
745 handoffs: Readonly<Record<string, ReadonlyArray<string>>>,
746): ReadonlyArray<AttachmentResource> {
747 if (Object.keys(handoffs).length === 0) return EMPTY_IMAGE_RESOURCES;
748 const attachmentIds = new Set<string>();
749 for (const message of messages ?? []) {
750 if (message.role !== "user" || !handoffs[message.id]?.length) continue;
751 for (const attachment of message.attachments ?? []) {
752 if (isImageAttachment(attachment)) attachmentIds.add(attachment.id);
753 }
754 }
755 return attachmentIds.size === 0
756 ? EMPTY_IMAGE_RESOURCES
757 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
759​
760/** Own one mapper per preview stage. Immutable messages retain unchanged preview objects. */
761export function createMessageAttachmentPreviewProjector() {
762 const attachmentsBySource = new WeakMap<
763 ReadonlyArray<ChatAttachment>,
764 ReadonlyArray<ChatAttachment>
765 >();
766 const messagesBySource = new WeakMap<ChatMessage, ChatMessage>();
767 return (
768 message: ChatMessage,
769 previewUrlFor: (attachment: ChatAttachment) => string | undefined,
770 ): ChatMessage => {
771 const source = message.attachments;
772 if (!source || source.length === 0) return message;
773 const previous = attachmentsBySource.get(source) ?? source;
774 let changed: ChatAttachment[] | undefined;
775 let hasOverrides = false;
776 for (const [index, attachment] of source.entries()) {
777 const previewUrl = previewUrlFor(attachment);
778 const sourceUrl = "previewUrl" in attachment ? attachment.previewUrl : undefined;
779 const previousAttachment = previous[index]!;
780 const previousUrl =
781 "previewUrl" in previousAttachment ? previousAttachment.previewUrl : undefined;
782 const next =
783 !previewUrl || previewUrl === sourceUrl
784 ? attachment
785 : previewUrl === previousUrl
786 ? previousAttachment
787 : { ...attachment, previewUrl };
788 hasOverrides ||= next !== attachment;
789 if (next !== previousAttachment) {
790 changed ??= previous.slice();
791 changed[index] = next;
792 }
793 }
794 const attachments = hasOverrides ? (changed ?? previous) : source;
795 attachmentsBySource.set(source, attachments);
796 if (attachments === source) {
797 messagesBySource.delete(message);
798 return message;
799 }
800 const previousMessage = messagesBySource.get(message);
801 if (previousMessage?.attachments === attachments) return previousMessage;
802 const result = { ...message, attachments };
803 messagesBySource.set(message, result);
804 return result;
805 };
807​
808/** Text and update time do not change a streaming assistant message's row structure. */
809export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
810 if (
811 previous.role !== "assistant" ||
812 next.role !== "assistant" ||
813 !previous.streaming ||
814 !next.streaming
815 ) {
816 return false;
817 }
818 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previous;
819 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = next;
820 return shallow(previousMetadata, nextMetadata);
822​
823/** Keep provenance and execution metadata in the rebuild boundary, including inspector data. */
824export function isStreamingTurnItemTextUpdate(
825 previous: OrchestrationV2ProjectedTurnItem,
826 next: OrchestrationV2ProjectedTurnItem,
827): boolean {
828 const { item: previousItem, ...previousSource } = previous;
829 const { item: nextItem, ...nextSource } = next;
830 if (
831 previousItem.type !== "assistant_message" ||
832 nextItem.type !== "assistant_message" ||
833 !previousItem.streaming ||
834 !nextItem.streaming ||
835 !shallow(previousSource, nextSource) ||
836 projectedItemCreatedAt(previous) !== projectedItemCreatedAt(next)
837 ) {
838 return false;
839 }
840 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previousItem;
841 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = nextItem;
842 // Wire decoding can recreate timestamps and attachments on each update.
843 // Compare only the changed item's metadata, never the entire transcript.
844 return Equal.equals(previousMetadata, nextMetadata);
846​
847function reuseTimelineEntries(
848 input: TimelineEntriesInput,
849 previous: TimelineEntriesProjection,
850): TimelineEntry[] | null {
851 const before = previous.input;
852 if (
853 input.visibleTurnItems.length < before.visibleTurnItems.length ||
854 !shallow(input.optimisticMessages, before.optimisticMessages) ||
855 !shallow(input.anchoredMessages, before.anchoredMessages) ||
856 !shallow(input.attachmentUrlById, before.attachmentUrlById) ||
857 !shallow(input.attempts, before.attempts) ||
858 !shallow(input.nodes, before.nodes) ||
859 !shallow(input.plans, before.plans)
860 ) {
861 return null;
862 }
863 const appended = input.visibleTurnItems.length > before.visibleTurnItems.length;
864 // Anchored and optimistic messages need to be interleaved/deduplicated when
865 // committed items arrive. Keep the full projection for that transition.
866 if (
867 appended &&
868 (input.optimisticMessages.length > 0 || (input.anchoredMessages?.length ?? 0) > 0)
869 ) {
870 return null;
871 }
872 // Answer rows can replace a message already present in the retained prefix.
873 if (
874 appended &&
875 input.visibleTurnItems
876 .slice(before.visibleTurnItems.length)
877 .some(
878 ({ item }) =>
879 (item.type === "user_input_request" && item.questionAnswer !== undefined) ||
880 (item.type === "user_message" && item.messageId.startsWith("async-answer:")),
881 )
882 )
883 return null;
884 const replacements = new Map<
885 OrchestrationV2ProjectedTurnItem,
886 OrchestrationV2ProjectedTurnItem
887 >();
888 for (const [index, previousItem] of before.visibleTurnItems.entries()) {
889 const item = input.visibleTurnItems[index]!;
890 if (item === previousItem) continue;
891 if (!isStreamingTurnItemTextUpdate(previousItem, item)) return null;
892 replacements.set(previousItem, item);
893 }
894 if (replacements.size === 0 && !appended) return previous.entries;
895 const entries = previous.entries.map((entry): TimelineEntry => {
896 const row =
897 entry.kind === "message" && entry.projectedItem !== undefined
898 ? replacements.get(entry.projectedItem)
899 : undefined;
900 if (entry.kind !== "message" || row?.item.type !== "assistant_message") return entry;
901 return {
902 ...entry,
903 projectedItem: row,
904 message: {
905 ...entry.message,
906 text: row.item.text,
907 updatedAt: DateTime.formatIso(row.item.updatedAt),
908 },
909 };
910 });
911 if (appended) {
912 entries.push(
913 ...deriveTimelineEntriesFromVisibleTurnItems({
914 ...input,
915 visibleTurnItems: input.visibleTurnItems.slice(before.visibleTurnItems.length),
916 }),
917 );
918 }
919 return entries;
921​
922/** Reuse immutable entries during streaming without reordering the canonical v2 sequence. */
923export function deriveTimelineEntriesFromVisibleTurnItemsWithState(
924 input: TimelineEntriesInput,
925 previous: TimelineEntriesProjection | null = null,
926): TimelineEntriesProjection {
927 const reused = previous === null ? null : reuseTimelineEntries(input, previous);
928 if (reused !== null) return { input, entries: reused };
929 const entries = deriveTimelineEntriesFromVisibleTurnItems(input);
930 if (previous === null || !shallow(input.attachmentUrlById, previous.input.attachmentUrlById)) {
931 return { input, entries };
932 }
933 // Tool output and lifecycle changes rebuild grouping, but unchanged message
934 // objects and previews still let memoized history rows stay mounted.
935 const previousMessages = new Map(
936 previous.entries.flatMap((entry) =>
937 entry.kind === "message" ? [[entry.id, entry] as const] : [],
938 ),
939 );
940 return {
941 input,
942 entries: entries.map((entry) => {
943 if (entry.kind !== "message" || entry.projectedItem === undefined) return entry;
944 const before = previousMessages.get(entry.id);
945 if (before?.projectedItem !== entry.projectedItem) return entry;
946 return before.attempt === entry.attempt ? before : { ...entry, message: before.message };
947 }),
948 };
950​
951export function inferCheckpointTurnCountByRunId(
952 summaries: ReadonlyArray<ThreadCheckpointSummary>,
953): Record<string, number> {
954 return Object.fromEntries(
955 summaries.flatMap((summary) =>
956 summary.runId === null ? [] : [[summary.runId, summary.checkpointTurnCount] as const],
957 ),
958 );
960​
961export function deriveRevertTurnCountByUserMessageId(input: {
962 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
963 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
964}): Map<ChatMessage["id"], number> {
965 const readyCheckpointByRunId = new Map<RunId, ThreadCheckpointSummary>();
966 for (const checkpoint of input.checkpoints) {
967 if (checkpoint.status === "ready") {
968 readyCheckpointByRunId.set(checkpoint.runId, checkpoint);
969 }
970 }
971 const byUserMessageId = new Map<ChatMessage["id"], number>();
972 for (const entry of input.timelineEntries) {
973 if (entry.kind !== "message" || entry.message.role !== "user") continue;
974 if (entry.message.inputIntent !== "turn_start" && entry.message.inputIntent !== "queued_turn") {
975 continue;
976 }
977 if (entry.message.runId === null) continue;
978 const checkpoint = readyCheckpointByRunId.get(entry.message.runId);
979 if (checkpoint === undefined) continue;
980 byUserMessageId.set(entry.message.id, Math.max(0, checkpoint.checkpointTurnCount - 1));
981 }
982 return byUserMessageId;
984​
985export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase {
986 if (runtime === null) return "disconnected";
987 if (
988 runtime.status === "preparing" ||
989 runtime.status === "starting" ||
990 runtime.status === "queued"
991 )
992 return "connecting";
993 if (runtime.status === "running" || runtime.status === "waiting") return "running";
994 return "ready";
996​
997export type { TurnDiffSummary };