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

session-logic.ts

1,155 lines38.3 KB

1import type { ThreadStructureRuntime } from "@t3tools/client-runtime/state/shell";
2import { resolveThreadWorkingStartedAt } from "@t3tools/client-runtime/state/models";
3import {
4 type AssetResource,
5 type OrchestrationV2Checkpoint,
6 type OrchestrationV2ExecutionNode,
7 type OrchestrationV2PlanArtifact,
8 type OrchestrationV2ProjectedTurnItem,
9 type OrchestrationV2RunAttempt,
10 type OrchestrationV2TurnItem,
11 type RunId,
12 type ToolActivitySurface,
13 type ToolActivityIcon,
14 type ToolActivitySource,
15 type ThreadId,
16 type TurnItemId,
17} from "@t3tools/contracts";
18import { extractToolActivityPresentation } from "@t3tools/client-runtime/work-log/tool-presentation";
19import {
20 classifyToolActivity,
21 collectToolFilePaths,
22 formatReadToolLabel,
23 formatSearchToolLabel,
24} from "@t3tools/shared/toolActivity";
25import type { HtmlRenderReference } from "@t3tools/shared/htmlRender";
26import { turnItemDetailRevision } from "@t3tools/client-runtime/work-log/item-detail";
27import type { McpAppReference } from "@t3tools/shared/mcpApp";
28import {
29 htmlRenderFromToolItem,
30 mcpAppFromToolItem,
31 sentMessageFromToolItem,
32} from "@t3tools/shared/toolOutput";
33import {
34 contextCompactionLabel,
35 workEntryIndicatesToolFailure,
36} from "@t3tools/client-runtime/work-log/presentation";
37import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
38import type {
39 ThreadPendingApproval,
40 ThreadPendingUserInput,
41} from "@t3tools/client-runtime/state/thread-requests";
42import type { ThreadRunSummary, ThreadRuntimeSummary } from "@t3tools/client-runtime/state/shell";
43import { threadRuntimeHasInterruptibleRun } from "@t3tools/client-runtime/state/thread-execution";
44import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation";
45​
46import {
47 isImageAttachment,
48 type ChatAttachment,
49 type ChatMessage,
50 type ProposedPlan,
51 type SessionPhase,
52 type TurnDiffSummary,
53} from "./types";
54import * as DateTime from "effect/DateTime";
55import * as Equal from "effect/Equal";
56import { shallow } from "zustand/vanilla/shallow";
57​
58export { formatDuration } from "@t3tools/shared/orchestrationTiming";
59export {
60 workEntryDisplayIndicatesToolFailure,
61 workEntryIndicatesToolFailure,
62} from "@t3tools/client-runtime/work-log/presentation";
63​
64export type WorkLogToolLifecycleStatus =
65 | "idle"
66 | "inProgress"
67 | "completed"
68 | "failed"
69 | "declined"
70 | "stopped";
71​
72export interface WorkLogEntry {
73 readonly questionAnswer?: import("@t3tools/contracts").UserInputAttachmentAnswerPayload;
74 readonly id: string;
75 readonly createdAt: string;
76 readonly runId?: RunId | null;
77 readonly label: string;
78 readonly detail?: string;
79 readonly command?: string;
80 readonly rawCommand?: string;
81 readonly changedFiles?: ReadonlyArray<string>;
82 readonly tone: "thinking" | "tool" | "info" | "error";
83 readonly toolTitle?: string;
84 readonly toolCallId?: string;
85 readonly viewedImagePath?: string;
86 readonly toolSurface?: ToolActivitySurface;
87 readonly toolIcon?: ToolActivityIcon;
88 readonly toolSource?: ToolActivitySource;
89 readonly sourceActivityKind?: string;
90 readonly taskId?: string;
91 readonly agentRole?: string;
92 readonly toolData?: unknown;
93 readonly requestKind?: string;
94 readonly itemType?: OrchestrationV2TurnItem["type"];
95 readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus;
96 readonly structuredPayload?: OrchestrationV2TurnItem;
97 readonly sourceItemType?: OrchestrationV2TurnItem["type"];
98 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
100​
101export type PendingApproval = ThreadPendingApproval;
102export type PendingUserInput = ThreadPendingUserInput;
103​
104export type TimelineAttempt = Pick<
105 OrchestrationV2RunAttempt,
106 "id" | "runId" | "attemptOrdinal" | "rootNodeId" | "status" | "completedAt"
107>;
108​
109export type TimelineEntry = (
110 | {
111 readonly id: string;
112 readonly kind: "message";
113 readonly createdAt: string;
114 readonly message: ChatMessage;
115 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
116 }
117 | {
118 readonly id: string;
119 readonly kind: "proposed-plan";
120 readonly createdAt: string;
121 readonly proposedPlan: ProposedPlan;
122 }
123 | {
124 readonly id: string;
125 readonly kind: "html-render";
126 readonly createdAt: string;
127 readonly runId: RunId | null;
128 readonly htmlRender: HtmlRenderReference;
129 }
130 | {
131 readonly id: string;
132 readonly kind: "sent-message";
133 readonly createdAt: string;
134 readonly runId: RunId | null;
135 readonly text: string;
136 }
137 | {
138 readonly id: string;
139 readonly kind: "mcp-app";
140 readonly createdAt: string;
141 readonly runId: RunId | null;
142 readonly sourceThreadId: ThreadId;
143 readonly itemId: TurnItemId;
144 readonly revision: string;
145 readonly mcpApp: McpAppReference;
146 }
147 | {
148 readonly id: string;
149 readonly kind: "work";
150 readonly createdAt: string;
151 readonly entry: WorkLogEntry;
152 }
153 | {
154 readonly id: string;
155 readonly kind: "event";
156 readonly createdAt: string;
157 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
158 }
159) & {
160 readonly attempt?: TimelineAttempt;
161};
162​
163export function workLogEntryIsToolLike(entry: WorkLogEntry): boolean {
164 return (
165 entry.tone === "tool" ||
166 entry.tone === "thinking" ||
167 entry.tone === "error" ||
168 entry.command !== undefined ||
169 entry.requestKind !== undefined
170 );
172​
173export function workEntrySignalsSevereFailure(entry: WorkLogEntry): boolean {
174 return entry.itemType === "error";
176​
177export function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean {
178 if (
179 !workLogEntryIsToolLike(entry) ||
180 workEntryIndicatesToolFailure(entry) ||
181 (entry.tone === "thinking" && entry.itemType !== "reasoning")
182 ) {
183 return false;
184 }
185 const status = entry.toolLifecycleStatus;
186 return (
187 status !== "failed" &&
188 status !== "declined" &&
189 status !== "inProgress" &&
190 status !== "stopped" &&
191 status !== "idle"
192 );
194​
195export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolean {
196 return (
197 workLogEntryIsToolLike(entry) &&
198 !workEntryIndicatesToolFailure(entry) &&
199 !workEntryIndicatesToolSuccess(entry)
200 );
202​
203export function isLatestRunSettled(
204 latestRun: Pick<ThreadRunSummary, "runId" | "startedAt" | "completedAt" | "status"> | null,
205 runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId"> | null,
206): boolean {
207 if (latestRun === null) return false;
208 if (
209 latestRun.status === "preparing" ||
210 latestRun.status === "queued" ||
211 latestRun.status === "starting" ||
212 latestRun.status === "running" ||
213 latestRun.status === "waiting"
214 )
215 return false;
216 return runtime?.activeRunId !== latestRun.runId;
218​
219export function deriveActiveWorkStartedAt(
220 latestRun: Pick<
221 ThreadRunSummary,
222 "runId" | "startedAt" | "requestedAt" | "completedAt" | "status"
223 > | null,
224 runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId" | "activityStartedAt"> | null,
225 sendStartedAt: string | null,
226): string | null {
227 const startedAt = resolveThreadWorkingStartedAt({ latestRun, runtime });
228 return startedAt ?? (runtime?.activeRunId == null ? sendStartedAt : null);
230​
231export function derivePendingApprovals(
232 approvals: ReadonlyArray<ThreadPendingApproval>,
233): ThreadPendingApproval[] {
234 return [...approvals].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
236​
237export function derivePendingUserInputs(
238 inputs: ReadonlyArray<ThreadPendingUserInput>,
239): ThreadPendingUserInput[] {
240 return [...inputs].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
242​
243const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"]["type"]>([
244 "fork",
245 "handoff",
246 "run_interrupt_request",
247 "run_interrupt_result",
248 "secret_request",
249 "link_request",
250 "subagent",
251]);
252​
253const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
254 "fork",
255 "thread_created",
256 // Still answerable after a steer supersedes the attempt that asked.
257 "secret_request",
258 "link_request",
259]);
260​
261export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean {
262 return (
263 entry.kind === "event" && PERSISTENT_RESOURCE_V2_ITEM_TYPES.has(entry.projectedItem.item.type)
264 );
266​
267function projectedItemCreatedAt(row: OrchestrationV2ProjectedTurnItem): string {
268 return DateTime.formatIso(row.item.startedAt ?? row.item.updatedAt);
270​
271function projectedWorkEntryStatus(
272 item: OrchestrationV2TurnItem,
273): NonNullable<WorkLogEntry["toolLifecycleStatus"]> {
274 switch (item.status) {
275 case "pending":
276 case "running":
277 case "waiting":
278 return "inProgress";
279 case "completed":
280 return "completed";
281 case "idle":
282 return "idle";
283 case "failed":
284 return "failed";
285 case "cancelled":
286 case "interrupted":
287 return "stopped";
288 }
290​
291function projectedWorkEntryTone(item: OrchestrationV2TurnItem): WorkLogEntry["tone"] {
292 if (item.type === "error") return "info";
293 if (item.type === "reasoning") return "thinking";
294 switch (item.type) {
295 case "command_execution":
296 case "file_change":
297 case "file_search":
298 case "web_search":
299 case "dynamic_tool":
300 case "subagent":
301 case "thread_created":
302 case "user_input_request":
303 case "approval_request":
304 return "tool";
305 default:
306 return "info";
307 }
309​
310export function providerErrorPresentation(
311 item: Extract<OrchestrationV2TurnItem, { readonly type: "error" }>,
312): { readonly label: string; readonly detail: string } {
313 if (item.retry === undefined) {
314 return {
315 label:
316 item.failure.class === "usage_limit"
317 ? "Usage limit reached"
318 : item.title?.trim() || "Provider error",
319 detail: item.failure.message,
320 };
321 }
322 const progress =
323 item.retry.maxAttempts === null
324 ? `${item.retry.attempt}`
325 : `${item.retry.attempt}/${item.retry.maxAttempts}`;
326 const label =
327 item.status === "running"
328 ? `Retrying provider (${progress})`
329 : item.status === "completed"
330 ? `Provider recovered (${progress} retries)`
331 : item.status === "failed"
332 ? `${item.failure.class === "usage_limit" ? "Usage limit reached" : "Provider error"} after ${progress} retries`
333 : `Provider retry stopped (${progress})`;
334 const retryDelay =
335 item.status === "running" && item.retry.retryDelayMs !== null && item.retry.retryDelayMs > 0
336 ? item.retry.retryDelayMs < 1_000
337 ? ` Retrying in ${item.retry.retryDelayMs}ms.`
338 : ` Retrying in ${(item.retry.retryDelayMs / 1_000).toFixed(1).replace(/\.0$/u, "")}s.`
339 : "";
340 return {
341 label,
342 detail: `${item.failure.message}${retryDelay}`,
343 };
345​
346function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry {
347 const { item } = row;
348 const title = item.title?.trim() || null;
349 const common = {
350 id: item.id,
351 createdAt: projectedItemCreatedAt(row),
352 runId: item.runId,
353 tone: projectedWorkEntryTone(item),
354 itemType: item.type,
355 toolLifecycleStatus: projectedWorkEntryStatus(item),
356 structuredPayload: item,
357 projectedItem: row,
358 ...extractToolActivityPresentation(item),
359 } as const;
360​
361 switch (item.type) {
362 case "thread_created":
363 return {
364 ...common,
365 label: "Created thread",
366 };
367 case "compaction":
368 return {
369 ...common,
370 label: contextCompactionLabel(item),
371 sourceActivityKind: "context-compaction",
372 ...(item.summary ? { detail: item.summary } : {}),
373 };
374 case "reasoning":
375 return {
376 ...common,
377 label: title ?? "Thinking",
378 ...(item.text ? { detail: item.text } : {}),
379 };
380 case "command_execution":
381 return {
382 ...common,
383 label: title ?? "Ran command",
384 command: item.input,
385 rawCommand: item.input,
386 toolTitle: title ?? "Command",
387 toolData: item,
388 };
389 case "file_change": {
390 return {
391 ...common,
392 label:
393 title ??
394 (item.changes !== undefined && item.changes.length > 1
395 ? `Changed ${item.changes.length} files`
396 : `Changed ${item.fileName}`),
397 changedFiles: item.changes?.length
398 ? item.changes.map((change) => change.path)
399 : [item.fileName],
400 toolTitle: title ?? "File change",
401 toolData: item,
402 };
403 }
404 case "file_search":
405 return {
406 ...common,
407 label: title ?? formatSearchToolLabel(item) ?? "Searched files",
408 ...(item.pattern ? { detail: item.pattern } : {}),
409 toolTitle: title ?? "File search",
410 toolData: item,
411 };
412 case "web_search":
413 return {
414 ...common,
415 label: title ?? "Searched the web",
416 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
417 toolTitle: title ?? "Web search",
418 toolData: item,
419 };
420 case "checkpoint":
421 return {
422 ...common,
423 label: title ?? "Checkpoint captured",
424 changedFiles: item.files.map((file) => file.path),
425 toolData: item,
426 };
427 case "system_notice":
428 return {
429 ...common,
430 label: item.message,
431 ...(item.level === "info" ? {} : { sourceActivityKind: "runtime.warning" }),
432 };
433 case "error": {
434 const presentation = providerErrorPresentation(item);
435 return {
436 ...common,
437 ...presentation,
438 ...(item.failure.class === "usage_limit" && item.status !== "completed"
439 ? { sourceActivityKind: "runtime.warning" }
440 : item.retry === undefined
441 ? { sourceActivityKind: "runtime.error" }
442 : {}),
443 toolData: item,
444 };
445 }
446 case "dynamic_tool": {
447 const classified = classifyToolActivity({
448 itemType: "dynamic_tool_call",
449 data: { toolName: item.toolName ?? undefined, input: item.input },
450 });
451 const [readPath] = collectToolFilePaths({ input: item.input });
452 return {
453 ...common,
454 label:
455 title ??
456 (classified === "read"
457 ? formatReadToolLabel(readPath ?? "")
458 : classified === "search"
459 ? (formatSearchToolLabel({ input: item.input }) ?? item.toolName ?? "Tool call")
460 : (item.toolName ?? "Tool call")),
461 toolTitle: title ?? item.toolName ?? "Tool",
462 toolData: { input: item.input, output: item.output },
463 };
464 }
465 case "todo_list": {
466 // Each todo update is a quiet row where the agent wrote it; it opens to every step.
467 const done = item.steps.filter((step) => step.status === "completed").length;
468 const current =
469 item.steps.find((step) => step.status === "running") ??
470 item.steps.find((step) => step.status === "pending");
471 return {
472 ...common,
473 label: `Tasks ${done}/${item.steps.length}${current ? ` · ${current.text}` : ""}`,
474 };
475 }
476 case "approval_request":
477 return {
478 ...common,
479 label: title ?? "Approval requested",
480 detail: item.prompt ?? item.requestKind,
481 toolData: item,
482 };
483 case "user_input_request":
484 return {
485 ...common,
486 label: title ?? (item.questionAnswer ? "Answered questions" : "Input requested"),
487 ...(item.questionAnswer ? { questionAnswer: item.questionAnswer } : {}),
488 toolData: item,
489 };
490 default:
491 return {
492 ...common,
493 label: title ?? item.type.replaceAll("_", " "),
494 toolData: item,
495 };
496 }
498​
499/** Preserve visibleTurnItems' committed order; interleave client messages by timestamp. */
500export interface TimelineEntriesInput {
501 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
502 readonly optimisticMessages: ReadonlyArray<ChatMessage>;
503 readonly anchoredMessages?: ReadonlyArray<ChatMessage>;
504 readonly attachmentUrlById?: ReadonlyMap<string, string>;
505 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
506 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
507 readonly plans?: ReadonlyArray<OrchestrationV2PlanArtifact>;
509​
510export interface TimelineEntriesProjection {
511 readonly input: TimelineEntriesInput;
512 readonly entries: TimelineEntry[];
514​
515export function deriveTimelineEntriesFromVisibleTurnItems(
516 input: TimelineEntriesInput,
517): TimelineEntry[] {
518 const committedMessageIds = new Set<string>();
519 const entries: TimelineEntry[] = [];
520 const attemptByRootNodeId = new Map(
521 (input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
522 );
523 const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const));
524 const planById = new Map((input.plans ?? []).map((plan) => [plan.id, plan] as const));
525​
526 const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => {
527 if (item.nodeId === null || item.runId === null) return undefined;
528 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
529 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
530 while (nodeId !== null && !visited.has(nodeId)) {
531 visited.add(nodeId);
532 const directAttempt = attemptByRootNodeId.get(nodeId);
533 if (directAttempt?.runId === item.runId) return directAttempt;
534 const node = nodeById.get(nodeId);
535 if (node === undefined) return undefined;
536 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
537 if (rootAttempt?.runId === item.runId) return rootAttempt;
538 nodeId = node.parentNodeId;
539 }
540 return undefined;
541 };
542​
543 // An answer that started a later run stays a normal message at that run's position.
544 const foldedAnswerRunIdByMessageId = new Map<string, OrchestrationV2TurnItem["runId"]>(
545 input.visibleTurnItems.flatMap(({ item }) =>
546 item.type === "user_input_request" && item.questionAnswer
547 ? [[`async-answer:${item.questionAnswer.requestId}`, item.runId] as const]
548 : [],
549 ),
550 );
551 for (const row of input.visibleTurnItems) {
552 const { item } = row;
553 if (turnItemIsWorkspacePreparation(item) && !item.deferredWork) continue;
554 if (item.type === "checkpoint") continue;
555 if (
556 item.type === "user_message" &&
557 item.inputIntent === "queued_turn" &&
558 item.status === "pending"
559 )
560 continue;
561 if (
562 item.type === "user_message" &&
563 foldedAnswerRunIdByMessageId.get(item.messageId) === item.runId
564 )
565 continue;
566 const createdAt = projectedItemCreatedAt(row);
567 const attempt = resolveAttempt(item);
568 const attemptMetadata = attempt === undefined ? {} : { attempt };
569 if (item.type === "notification") {
570 entries.push({
571 id: item.id,
572 kind: "work",
573 createdAt,
574 entry: {
575 id: item.id,
576 createdAt,
577 runId: item.runId,
578 label: item.summary,
579 tone: "info",
580 itemType: item.type,
581 structuredPayload: item,
582 projectedItem: row,
583 },
584 ...attemptMetadata,
585 });
586 continue;
587 }
588 if (item.type === "user_message" || item.type === "assistant_message") {
589 const message: ChatMessage = {
590 id: item.messageId,
591 role: item.type === "user_message" ? "user" : "assistant",
592 text: item.text,
593 ...(item.type === "user_message" && item.context ? { context: item.context } : {}),
594 ...((item.attachments?.length ?? 0) > 0
595 ? {
596 attachments: (item.attachments ?? []).map((attachment) => {
597 const previewUrl = input.attachmentUrlById?.get(attachment.id);
598 return previewUrl ? { ...attachment, previewUrl } : attachment;
599 }),
600 }
601 : {}),
602 runId: item.runId,
603 streaming: item.type === "assistant_message" && item.streaming,
604 ...(item.type === "user_message"
605 ? {
606 createdBy: item.createdBy,
607 creationSource: item.creationSource,
608 ...(item.senderThreadId !== undefined ? { senderThreadId: item.senderThreadId } : {}),
609 ...(item.linkedSender !== undefined ? { linkedSender: item.linkedSender } : {}),
610 ...(item.idleCompaction !== undefined ? { idleCompaction: item.idleCompaction } : {}),
611 ...(item.scheduledTaskId !== undefined
612 ? { scheduledTaskId: item.scheduledTaskId }
613 : {}),
614 }
615 : {}),
616 createdAt,
617 updatedAt: DateTime.formatIso(item.updatedAt),
618 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
619 };
620 committedMessageIds.add(message.id);
621 entries.push({
622 id: message.id,
623 kind: "message",
624 createdAt,
625 message,
626 projectedItem: row,
627 ...attemptMetadata,
628 });
629 continue;
630 }
631​
632 if (item.type === "proposed_plan") {
633 const plan = planById.get(item.planId);
634 const proposedPlan = {
635 id: item.planId,
636 runId: item.runId,
637 planMarkdown: item.markdown,
638 status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
639 createdAt,
640 updatedAt: DateTime.formatIso(item.updatedAt),
641 };
642 entries.push({
643 id: item.id,
644 kind: "proposed-plan",
645 createdAt,
646 proposedPlan,
647 ...attemptMetadata,
648 });
649 continue;
650 }
651​
652 const htmlRender =
653 item.type === "dynamic_tool" && item.status === "completed"
654 ? htmlRenderFromToolItem(item)
655 : undefined;
656 if (htmlRender !== undefined) {
657 entries.push({
658 id: item.id,
659 kind: "html-render",
660 createdAt,
661 runId: item.runId,
662 htmlRender,
663 ...attemptMetadata,
664 });
665 continue;
666 }
667​
668 const sentMessage =
669 item.type === "dynamic_tool" && item.status === "completed"
670 ? sentMessageFromToolItem(item)
671 : undefined;
672 if (sentMessage !== undefined) {
673 entries.push({
674 id: item.id,
675 kind: "sent-message",
676 createdAt,
677 runId: item.runId,
678 text: sentMessage,
679 ...attemptMetadata,
680 });
681 continue;
682 }
683​
684 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
685 entries.push({
686 id: item.id,
687 kind: "event",
688 createdAt,
689 projectedItem: row,
690 ...attemptMetadata,
691 });
692 continue;
693 }
694​
695 entries.push({
696 id: item.id,
697 kind: "work",
698 createdAt,
699 entry: projectedWorkEntry(row),
700 ...attemptMetadata,
701 });
702​
703 const mcpApp = item.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined;
704 if (mcpApp !== undefined) {
705 entries.push({
706 id: `mcp-app:${item.id}`,
707 kind: "mcp-app",
708 createdAt,
709 runId: item.runId,
710 sourceThreadId: row.sourceThreadId,
711 itemId: row.sourceItemId,
712 revision: turnItemDetailRevision(item),
713 mcpApp,
714 ...attemptMetadata,
715 });
716 }
717 }
718​
719 const retainedMessageIds = new Set([
720 ...committedMessageIds,
721 ...foldedAnswerRunIdByMessageId.keys(),
722 ]);
723 for (const message of input.anchoredMessages ?? []) {
724 if (retainedMessageIds.has(message.id)) continue;
725 retainedMessageIds.add(message.id);
726 const entry: TimelineEntry = {
727 id: message.id,
728 kind: "message",
729 createdAt: message.createdAt,
730 message,
731 };
732 const insertionIndex = entries.findIndex(
733 (candidate) => candidate.createdAt > message.createdAt,
734 );
735 if (insertionIndex === -1) {
736 entries.push(entry);
737 } else {
738 entries.splice(insertionIndex, 0, entry);
739 }
740 }
741​
742 for (const message of input.optimisticMessages) {
743 if (message.inputIntent !== "queued_turn" && !retainedMessageIds.has(message.id)) {
744 retainedMessageIds.add(message.id);
745 entries.push({
746 id: message.id,
747 kind: "message",
748 createdAt: message.createdAt,
749 message,
750 });
751 }
752 }
753​
754 return entries;
756​
757type AttachmentResource = Extract<AssetResource, { readonly _tag: "attachment" }>;
758const EMPTY_IMAGE_RESOURCES = Object.freeze<ReadonlyArray<AttachmentResource>>([]);
759​
760export function selectMessageImageResources(
761 attachments: ChatMessage["attachments"],
762): ReadonlyArray<AttachmentResource> {
763 const attachmentIds = new Set<string>();
764 for (const attachment of attachments ?? []) {
765 if (!isImageAttachment(attachment)) continue;
766 const previewUrl = attachment.previewUrl;
767 if (previewUrl?.startsWith("blob:") || previewUrl?.startsWith("data:")) continue;
768 attachmentIds.add(attachment.id);
769 }
770 return attachmentIds.size === 0
771 ? EMPTY_IMAGE_RESOURCES
772 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
774​
775export function selectHandoffImageResources(
776 messages: ReadonlyArray<Pick<ChatMessage, "id" | "role" | "attachments">> | undefined,
777 handoffs: Readonly<Record<string, ReadonlyArray<string>>>,
778): ReadonlyArray<AttachmentResource> {
779 if (Object.keys(handoffs).length === 0) return EMPTY_IMAGE_RESOURCES;
780 const attachmentIds = new Set<string>();
781 for (const message of messages ?? []) {
782 if (message.role !== "user" || !handoffs[message.id]?.length) continue;
783 for (const attachment of message.attachments ?? []) {
784 if (isImageAttachment(attachment)) attachmentIds.add(attachment.id);
785 }
786 }
787 return attachmentIds.size === 0
788 ? EMPTY_IMAGE_RESOURCES
789 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
791​
792export function createMessageAttachmentPreviewProjector() {
793 const attachmentsBySource = new WeakMap<
794 ReadonlyArray<ChatAttachment>,
795 ReadonlyArray<ChatAttachment>
796 >();
797 const messagesBySource = new WeakMap<ChatMessage, ChatMessage>();
798 return (
799 message: ChatMessage,
800 previewUrlFor: (attachment: ChatAttachment) => string | undefined,
801 ): ChatMessage => {
802 const source = message.attachments;
803 if (!source || source.length === 0) return message;
804 const previous = attachmentsBySource.get(source) ?? source;
805 let changed: ChatAttachment[] | undefined;
806 let hasOverrides = false;
807 for (const [index, attachment] of source.entries()) {
808 const previewUrl = previewUrlFor(attachment);
809 const sourceUrl = "previewUrl" in attachment ? attachment.previewUrl : undefined;
810 const previousAttachment = previous[index]!;
811 const previousUrl =
812 "previewUrl" in previousAttachment ? previousAttachment.previewUrl : undefined;
813 const next =
814 !previewUrl || previewUrl === sourceUrl
815 ? attachment
816 : previewUrl === previousUrl
817 ? previousAttachment
818 : { ...attachment, previewUrl };
819 hasOverrides ||= next !== attachment;
820 if (next !== previousAttachment) {
821 changed ??= previous.slice();
822 changed[index] = next;
823 }
824 }
825 const attachments = hasOverrides ? (changed ?? previous) : source;
826 attachmentsBySource.set(source, attachments);
827 if (attachments === source) {
828 messagesBySource.delete(message);
829 return message;
830 }
831 const previousMessage = messagesBySource.get(message);
832 if (previousMessage?.attachments === attachments) return previousMessage;
833 const result = { ...message, attachments };
834 messagesBySource.set(message, result);
835 return result;
836 };
838​
839export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
840 if (
841 previous.role !== "assistant" ||
842 next.role !== "assistant" ||
843 !previous.streaming ||
844 !next.streaming
845 ) {
846 return false;
847 }
848 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previous;
849 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = next;
850 return shallow(previousMetadata, nextMetadata);
852​
853function streamedTextMetadata(item: OrchestrationV2TurnItem) {
854 if (item.type === "proposed_plan" && item.streaming) {
855 const { markdown: _markdown, updatedAt: _updatedAt, ...metadata } = item;
856 return metadata;
857 }
858 if ((item.type === "assistant_message" || item.type === "reasoning") && item.streaming) {
859 const { text: _text, updatedAt: _updatedAt, ...metadata } = item;
860 return metadata;
861 }
862 return null;
864​
865export function isStreamingTurnItemTextUpdate(
866 previous: OrchestrationV2ProjectedTurnItem,
867 next: OrchestrationV2ProjectedTurnItem,
868): boolean {
869 const { item: previousItem, ...previousSource } = previous;
870 const { item: nextItem, ...nextSource } = next;
871 const previousMetadata = streamedTextMetadata(previousItem);
872 const nextMetadata = streamedTextMetadata(nextItem);
873 if (
874 previousMetadata === null ||
875 nextMetadata === null ||
876 !shallow(previousSource, nextSource) ||
877 projectedItemCreatedAt(previous) !== projectedItemCreatedAt(next)
878 ) {
879 return false;
880 }
881 // Wire decoding recreates timestamps and attachments; compare only the changed item's metadata.
882 return Equal.equals(previousMetadata, nextMetadata);
884​
885/**
886 * A changed tool or work item maps to exactly one entry with the item's id.
887 * Messages and question answers take part in cross-entry dedupe, and anchored
888 * messages are placed by createdAt, so those changes rebuild.
889 */
890function canRederiveInPlace(
891 input: TimelineEntriesInput,
892 previousItem: OrchestrationV2ProjectedTurnItem,
893 item: OrchestrationV2ProjectedTurnItem,
894): boolean {
895 return (
896 item.item.id === previousItem.item.id &&
897 item.item.type === previousItem.item.type &&
898 item.item.type !== "user_message" &&
899 item.item.type !== "assistant_message" &&
900 item.item.type !== "user_input_request" &&
901 // An app call projects two entries; in-place reuse replaces one.
902 (previousItem.item.type !== "dynamic_tool" ||
903 mcpAppFromToolItem(previousItem.item) === undefined) &&
904 ((input.anchoredMessages?.length ?? 0) === 0 ||
905 projectedItemCreatedAt(item) === projectedItemCreatedAt(previousItem))
906 );
908​
909/** Entries read only each plan's status; streaming plans rebuild artifacts with every delta. */
910function samePlanStatuses(
911 next: TimelineEntriesInput["plans"],
912 previous: TimelineEntriesInput["plans"],
913): boolean {
914 if (next === previous) return true;
915 if (next === undefined || previous === undefined || next.length !== previous.length) return false;
916 return next.every((plan, index) => {
917 const before = previous[index]!;
918 return plan.id === before.id && plan.kind === before.kind && plan.status === before.status;
919 });
921​
922function reuseTimelineEntries(
923 input: TimelineEntriesInput,
924 previous: TimelineEntriesProjection,
925): TimelineEntry[] | null {
926 const before = previous.input;
927 if (
928 input.visibleTurnItems.length < before.visibleTurnItems.length ||
929 !shallow(input.optimisticMessages, before.optimisticMessages) ||
930 !shallow(input.anchoredMessages, before.anchoredMessages) ||
931 !shallow(input.attachmentUrlById, before.attachmentUrlById) ||
932 !shallow(input.attempts, before.attempts) ||
933 !shallow(input.nodes, before.nodes) ||
934 !samePlanStatuses(input.plans, before.plans)
935 ) {
936 return null;
937 }
938 const appended = input.visibleTurnItems.length > before.visibleTurnItems.length;
939 // Keep full projection until committed items interleave and deduplicate anchored/optimistic messages.
940 if (
941 appended &&
942 (input.optimisticMessages.length > 0 || (input.anchoredMessages?.length ?? 0) > 0)
943 ) {
944 return null;
945 }
946 // Answer rows can replace a message already present in the retained prefix.
947 if (
948 appended &&
949 input.visibleTurnItems
950 .slice(before.visibleTurnItems.length)
951 .some(
952 ({ item }) =>
953 (item.type === "user_input_request" && item.questionAnswer !== undefined) ||
954 (item.type === "user_message" && item.messageId.startsWith("async-answer:")),
955 )
956 )
957 return null;
958 const replacements = new Map<
959 OrchestrationV2ProjectedTurnItem,
960 OrchestrationV2ProjectedTurnItem
961 >();
962 const changedItems: OrchestrationV2ProjectedTurnItem[] = [];
963 for (let index = 0; index < before.visibleTurnItems.length; index += 1) {
964 const previousItem = before.visibleTurnItems[index]!;
965 const item = input.visibleTurnItems[index]!;
966 if (item === previousItem) continue;
967 // Reasoning and plan text re-derive below; only assistant text patches the message.
968 if (
969 item.item.type === "assistant_message" &&
970 isStreamingTurnItemTextUpdate(previousItem, item)
971 ) {
972 replacements.set(previousItem, item);
973 continue;
974 }
975 if (!canRederiveInPlace(input, previousItem, item)) return null;
976 changedItems.push(item);
977 }
978 // One batch keeps the attempt/node/plan lookups to a single build.
979 const rederived =
980 changedItems.length === 0
981 ? []
982 : deriveTimelineEntriesFromVisibleTurnItems({
983 ...input,
984 visibleTurnItems: changedItems,
985 optimisticMessages: [],
986 anchoredMessages: [],
987 });
988 if (
989 rederived.length !== changedItems.length ||
990 rederived.some((entry, index) => entry.id !== changedItems[index]!.item.id)
991 ) {
992 return null;
993 }
994 const rederivedEntries = new Map(rederived.map((entry) => [entry.id, entry]));
995 if (replacements.size === 0 && rederivedEntries.size === 0 && !appended) {
996 return previous.entries;
997 }
998 let rederivedCount = 0;
999 const entries = previous.entries.map((entry): TimelineEntry => {
1000 const rederivedEntry = rederivedEntries.get(entry.id);
1001 if (rederivedEntry !== undefined) {
1002 rederivedCount += 1;
1003 return rederivedEntry;
1005 const row =
1006 entry.kind === "message" && entry.projectedItem !== undefined
1007 ? replacements.get(entry.projectedItem)
1008 : undefined;
1009 if (entry.kind !== "message" || row?.item.type !== "assistant_message") return entry;
1010 return {
1011 ...entry,
1012 projectedItem: row,
1013 message: {
1014 ...entry.message,
1015 text: row.item.text,
1016 updatedAt: DateTime.formatIso(row.item.updatedAt),
1017 },
1018 };
1019 });
1020 if (rederivedCount !== rederivedEntries.size) return null;
1021 if (appended) {
1022 entries.push(
1023 ...deriveTimelineEntriesFromVisibleTurnItems({
1024 ...input,
1025 visibleTurnItems: input.visibleTurnItems.slice(before.visibleTurnItems.length),
1026 }),
1027 );
1029 return entries;
1031​
1032export function deriveTimelineEntriesFromVisibleTurnItemsWithState(
1033 input: TimelineEntriesInput,
1034 previous: TimelineEntriesProjection | null = null,
1035): TimelineEntriesProjection {
1036 const reused = previous === null ? null : reuseTimelineEntries(input, previous);
1037 if (reused !== null) return { input, entries: reused };
1038 const entries = deriveTimelineEntriesFromVisibleTurnItems(input);
1039 if (previous === null || !shallow(input.attachmentUrlById, previous.input.attachmentUrlById)) {
1040 return { input, entries };
1042 const previousMessages = new Map(
1043 previous.entries.flatMap((entry) =>
1044 entry.kind === "message" ? [[entry.id, entry] as const] : [],
1045 ),
1046 );
1047 return {
1048 input,
1049 entries: entries.map((entry) => {
1050 if (entry.kind !== "message" || entry.projectedItem === undefined) return entry;
1051 const before = previousMessages.get(entry.id);
1052 if (before?.projectedItem !== entry.projectedItem) return entry;
1053 return before.attempt === entry.attempt ? before : { ...entry, message: before.message };
1054 }),
1055 };
1057​
1058// Run ordinals keep increasing after a rewind; only visible local runs define predecessors.
1059export function deriveRevertTurnCountByUserMessageId(input: {
1060 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
1061 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
1062 readonly threadStartCheckpointAvailable: boolean;
1063 readonly availableRevertTurnCounts?: ReadonlySet<number> | undefined;
1064 readonly unsettledRunId?: RunId | null;
1065}): Map<ChatMessage["id"], number> {
1066 const turnCountByRunId = new Map<RunId, number>();
1067 for (const checkpoint of input.checkpoints) {
1068 if (isRewindableCheckpoint(checkpoint)) {
1069 turnCountByRunId.set(checkpoint.runId, checkpoint.checkpointTurnCount);
1072 const targetByRunId = new Map<RunId, number | undefined>();
1073 const byUserMessageId = new Map<ChatMessage["id"], number>();
1074 let previousRunId: RunId | null = null;
1075 for (const entry of input.timelineEntries) {
1076 // Inherited history belongs to the source thread, not our checkpoint scope.
1077 if (entry.kind !== "message" && entry.kind !== "work") continue;
1078 const projectedItem =
1079 entry.kind === "message" ? entry.projectedItem : entry.entry.projectedItem;
1080 if (projectedItem?.visibility === "inherited") continue;
1081 const runId =
1082 entry.kind === "message"
1083 ? entry.message.runId
1084 : entry.entry.itemType === "notification"
1085 ? entry.entry.runId
1086 : null;
1087 if (runId == null) continue;
1088 if (!targetByRunId.has(runId)) {
1089 targetByRunId.set(
1090 runId,
1091 previousRunId === null
1092 ? input.threadStartCheckpointAvailable
1093 ? 0
1094 : undefined
1095 : turnCountByRunId.get(previousRunId),
1096 );
1097 previousRunId = runId;
1099 if (entry.kind !== "message") continue;
1100 const { message } = entry;
1101 if (message.role !== "user" || message.runId === input.unsettledRunId) continue;
1102 if (message.inputIntent !== "turn_start" && message.inputIntent !== "queued_turn") continue;
1103 const target = targetByRunId.get(runId);
1104 if (
1105 target !== undefined &&
1106 (input.availableRevertTurnCounts === undefined || input.availableRevertTurnCounts.has(target))
1108 byUserMessageId.set(message.id, target);
1110 return byUserMessageId;
1112​
1113// A missing snapshot (no git, or a side chat) still pins a conversation position; only
1114// restoring files needs a ready one.
1115function isRewindableCheckpoint(checkpoint: Pick<OrchestrationV2Checkpoint, "status">) {
1116 return checkpoint.status === "ready" || checkpoint.status === "missing";
1118​
1119export function findRevertCheckpoint(
1120 checkpoints: ReadonlyArray<OrchestrationV2Checkpoint>,
1121 turnCount: number,
1122): OrchestrationV2Checkpoint | undefined {
1123 return checkpoints.findLast(
1124 (checkpoint) =>
1125 isRewindableCheckpoint(checkpoint) &&
1126 (turnCount === 0
1127 ? checkpoint.ordinalWithinScope === 0 && checkpoint.appRunOrdinal === null
1128 : checkpoint.appRunOrdinal === turnCount),
1129 );
1131​
1132export function derivePhase(runtime: ThreadStructureRuntime | null): SessionPhase {
1133 if (runtime === null) return "disconnected";
1134 if (
1135 runtime.status === "preparing" ||
1136 runtime.status === "starting" ||
1137 runtime.status === "queued"
1139 return "connecting";
1140 if (runtime.status === "running" || runtime.status === "waiting") return "running";
1141 return "ready";
1143​
1144/** Preparing and starting runs can be interrupted; Stop need not wait for running. */
1145export function deriveCanInterruptRunningThread(
1146 hasActiveThread: boolean,
1147 runtime: ThreadStructureRuntime | null,
1148): boolean {
1149 return (
1150 hasActiveThread &&
1151 (derivePhase(runtime) === "running" || threadRuntimeHasInterruptibleRun(runtime))
1152 );
1154​
1155export type { TurnDiffSummary };