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

session-logic.ts

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