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

session-logic.ts

1,153 lines38.2 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?.map((change) => change.path) ?? [item.fileName],
398 toolTitle: title ?? "File change",
399 toolData: item,
400 };
401 }
402 case "file_search":
403 return {
404 ...common,
405 label: title ?? formatSearchToolLabel(item) ?? "Searched files",
406 ...(item.pattern ? { detail: item.pattern } : {}),
407 toolTitle: title ?? "File search",
408 toolData: item,
409 };
410 case "web_search":
411 return {
412 ...common,
413 label: title ?? "Searched the web",
414 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
415 toolTitle: title ?? "Web search",
416 toolData: item,
417 };
418 case "checkpoint":
419 return {
420 ...common,
421 label: title ?? "Checkpoint captured",
422 changedFiles: item.files.map((file) => file.path),
423 toolData: item,
424 };
425 case "system_notice":
426 return {
427 ...common,
428 label: item.message,
429 sourceActivityKind: "runtime.warning",
430 };
431 case "error": {
432 const presentation = providerErrorPresentation(item);
433 return {
434 ...common,
435 ...presentation,
436 ...(item.failure.class === "usage_limit" && item.status !== "completed"
437 ? { sourceActivityKind: "runtime.warning" }
438 : item.retry === undefined
439 ? { sourceActivityKind: "runtime.error" }
440 : {}),
441 toolData: item,
442 };
443 }
444 case "dynamic_tool": {
445 const classified = classifyToolActivity({
446 itemType: "dynamic_tool_call",
447 data: { toolName: item.toolName ?? undefined, input: item.input },
448 });
449 const [readPath] = collectToolFilePaths({ input: item.input });
450 return {
451 ...common,
452 label:
453 title ??
454 (classified === "read"
455 ? formatReadToolLabel(readPath ?? "")
456 : classified === "search"
457 ? (formatSearchToolLabel({ input: item.input }) ?? item.toolName ?? "Tool call")
458 : (item.toolName ?? "Tool call")),
459 toolTitle: title ?? item.toolName ?? "Tool",
460 toolData: { input: item.input, output: item.output },
461 };
462 }
463 case "todo_list": {
464 // Each todo update is a quiet row where the agent wrote it; it opens to every step.
465 const done = item.steps.filter((step) => step.status === "completed").length;
466 const current =
467 item.steps.find((step) => step.status === "running") ??
468 item.steps.find((step) => step.status === "pending");
469 return {
470 ...common,
471 label: `Tasks ${done}/${item.steps.length}${current ? ` · ${current.text}` : ""}`,
472 };
473 }
474 case "approval_request":
475 return {
476 ...common,
477 label: title ?? "Approval requested",
478 detail: item.prompt ?? item.requestKind,
479 toolData: item,
480 };
481 case "user_input_request":
482 return {
483 ...common,
484 label: title ?? (item.questionAnswer ? "Answered questions" : "Input requested"),
485 ...(item.questionAnswer ? { questionAnswer: item.questionAnswer } : {}),
486 toolData: item,
487 };
488 default:
489 return {
490 ...common,
491 label: title ?? item.type.replaceAll("_", " "),
492 toolData: item,
493 };
494 }
496​
497/** Preserve visibleTurnItems' committed order; interleave client messages by timestamp. */
498export interface TimelineEntriesInput {
499 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
500 readonly optimisticMessages: ReadonlyArray<ChatMessage>;
501 readonly anchoredMessages?: ReadonlyArray<ChatMessage>;
502 readonly attachmentUrlById?: ReadonlyMap<string, string>;
503 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
504 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
505 readonly plans?: ReadonlyArray<OrchestrationV2PlanArtifact>;
507​
508export interface TimelineEntriesProjection {
509 readonly input: TimelineEntriesInput;
510 readonly entries: TimelineEntry[];
512​
513export function deriveTimelineEntriesFromVisibleTurnItems(
514 input: TimelineEntriesInput,
515): TimelineEntry[] {
516 const committedMessageIds = new Set<string>();
517 const entries: TimelineEntry[] = [];
518 const attemptByRootNodeId = new Map(
519 (input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
520 );
521 const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const));
522 const planById = new Map((input.plans ?? []).map((plan) => [plan.id, plan] as const));
523​
524 const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => {
525 if (item.nodeId === null || item.runId === null) return undefined;
526 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
527 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
528 while (nodeId !== null && !visited.has(nodeId)) {
529 visited.add(nodeId);
530 const directAttempt = attemptByRootNodeId.get(nodeId);
531 if (directAttempt?.runId === item.runId) return directAttempt;
532 const node = nodeById.get(nodeId);
533 if (node === undefined) return undefined;
534 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
535 if (rootAttempt?.runId === item.runId) return rootAttempt;
536 nodeId = node.parentNodeId;
537 }
538 return undefined;
539 };
540​
541 // An answer that started a later run stays a normal message at that run's position.
542 const foldedAnswerRunIdByMessageId = new Map<string, OrchestrationV2TurnItem["runId"]>(
543 input.visibleTurnItems.flatMap(({ item }) =>
544 item.type === "user_input_request" && item.questionAnswer
545 ? [[`async-answer:${item.questionAnswer.requestId}`, item.runId] as const]
546 : [],
547 ),
548 );
549 for (const row of input.visibleTurnItems) {
550 const { item } = row;
551 if (turnItemIsWorkspacePreparation(item) && !item.deferredWork) continue;
552 if (item.type === "checkpoint") continue;
553 if (
554 item.type === "user_message" &&
555 item.inputIntent === "queued_turn" &&
556 item.status === "pending"
557 )
558 continue;
559 if (
560 item.type === "user_message" &&
561 foldedAnswerRunIdByMessageId.get(item.messageId) === item.runId
562 )
563 continue;
564 const createdAt = projectedItemCreatedAt(row);
565 const attempt = resolveAttempt(item);
566 const attemptMetadata = attempt === undefined ? {} : { attempt };
567 if (item.type === "notification") {
568 entries.push({
569 id: item.id,
570 kind: "work",
571 createdAt,
572 entry: {
573 id: item.id,
574 createdAt,
575 runId: item.runId,
576 label: item.summary,
577 tone: "info",
578 itemType: item.type,
579 structuredPayload: item,
580 projectedItem: row,
581 },
582 ...attemptMetadata,
583 });
584 continue;
585 }
586 if (item.type === "user_message" || item.type === "assistant_message") {
587 const message: ChatMessage = {
588 id: item.messageId,
589 role: item.type === "user_message" ? "user" : "assistant",
590 text: item.text,
591 ...(item.type === "user_message" && item.context ? { context: item.context } : {}),
592 ...((item.attachments?.length ?? 0) > 0
593 ? {
594 attachments: (item.attachments ?? []).map((attachment) => {
595 const previewUrl = input.attachmentUrlById?.get(attachment.id);
596 return previewUrl ? { ...attachment, previewUrl } : attachment;
597 }),
598 }
599 : {}),
600 runId: item.runId,
601 streaming: item.type === "assistant_message" && item.streaming,
602 ...(item.type === "user_message"
603 ? {
604 createdBy: item.createdBy,
605 creationSource: item.creationSource,
606 ...(item.senderThreadId !== undefined ? { senderThreadId: item.senderThreadId } : {}),
607 ...(item.linkedSender !== undefined ? { linkedSender: item.linkedSender } : {}),
608 ...(item.idleCompaction !== undefined ? { idleCompaction: item.idleCompaction } : {}),
609 ...(item.scheduledTaskId !== undefined
610 ? { scheduledTaskId: item.scheduledTaskId }
611 : {}),
612 }
613 : {}),
614 createdAt,
615 updatedAt: DateTime.formatIso(item.updatedAt),
616 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
617 };
618 committedMessageIds.add(message.id);
619 entries.push({
620 id: message.id,
621 kind: "message",
622 createdAt,
623 message,
624 projectedItem: row,
625 ...attemptMetadata,
626 });
627 continue;
628 }
629​
630 if (item.type === "proposed_plan") {
631 const plan = planById.get(item.planId);
632 const proposedPlan = {
633 id: item.planId,
634 runId: item.runId,
635 planMarkdown: item.markdown,
636 status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
637 createdAt,
638 updatedAt: DateTime.formatIso(item.updatedAt),
639 };
640 entries.push({
641 id: item.id,
642 kind: "proposed-plan",
643 createdAt,
644 proposedPlan,
645 ...attemptMetadata,
646 });
647 continue;
648 }
649​
650 const htmlRender =
651 item.type === "dynamic_tool" && item.status === "completed"
652 ? htmlRenderFromToolItem(item)
653 : undefined;
654 if (htmlRender !== undefined) {
655 entries.push({
656 id: item.id,
657 kind: "html-render",
658 createdAt,
659 runId: item.runId,
660 htmlRender,
661 ...attemptMetadata,
662 });
663 continue;
664 }
665​
666 const sentMessage =
667 item.type === "dynamic_tool" && item.status === "completed"
668 ? sentMessageFromToolItem(item)
669 : undefined;
670 if (sentMessage !== undefined) {
671 entries.push({
672 id: item.id,
673 kind: "sent-message",
674 createdAt,
675 runId: item.runId,
676 text: sentMessage,
677 ...attemptMetadata,
678 });
679 continue;
680 }
681​
682 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
683 entries.push({
684 id: item.id,
685 kind: "event",
686 createdAt,
687 projectedItem: row,
688 ...attemptMetadata,
689 });
690 continue;
691 }
692​
693 entries.push({
694 id: item.id,
695 kind: "work",
696 createdAt,
697 entry: projectedWorkEntry(row),
698 ...attemptMetadata,
699 });
700​
701 const mcpApp = item.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined;
702 if (mcpApp !== undefined) {
703 entries.push({
704 id: `mcp-app:${item.id}`,
705 kind: "mcp-app",
706 createdAt,
707 runId: item.runId,
708 sourceThreadId: row.sourceThreadId,
709 itemId: row.sourceItemId,
710 revision: turnItemDetailRevision(item),
711 mcpApp,
712 ...attemptMetadata,
713 });
714 }
715 }
716​
717 const retainedMessageIds = new Set([
718 ...committedMessageIds,
719 ...foldedAnswerRunIdByMessageId.keys(),
720 ]);
721 for (const message of input.anchoredMessages ?? []) {
722 if (retainedMessageIds.has(message.id)) continue;
723 retainedMessageIds.add(message.id);
724 const entry: TimelineEntry = {
725 id: message.id,
726 kind: "message",
727 createdAt: message.createdAt,
728 message,
729 };
730 const insertionIndex = entries.findIndex(
731 (candidate) => candidate.createdAt > message.createdAt,
732 );
733 if (insertionIndex === -1) {
734 entries.push(entry);
735 } else {
736 entries.splice(insertionIndex, 0, entry);
737 }
738 }
739​
740 for (const message of input.optimisticMessages) {
741 if (message.inputIntent !== "queued_turn" && !retainedMessageIds.has(message.id)) {
742 retainedMessageIds.add(message.id);
743 entries.push({
744 id: message.id,
745 kind: "message",
746 createdAt: message.createdAt,
747 message,
748 });
749 }
750 }
751​
752 return entries;
754​
755type AttachmentResource = Extract<AssetResource, { readonly _tag: "attachment" }>;
756const EMPTY_IMAGE_RESOURCES = Object.freeze<ReadonlyArray<AttachmentResource>>([]);
757​
758export function selectMessageImageResources(
759 attachments: ChatMessage["attachments"],
760): ReadonlyArray<AttachmentResource> {
761 const attachmentIds = new Set<string>();
762 for (const attachment of attachments ?? []) {
763 if (!isImageAttachment(attachment)) continue;
764 const previewUrl = attachment.previewUrl;
765 if (previewUrl?.startsWith("blob:") || previewUrl?.startsWith("data:")) continue;
766 attachmentIds.add(attachment.id);
767 }
768 return attachmentIds.size === 0
769 ? EMPTY_IMAGE_RESOURCES
770 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
772​
773export function selectHandoffImageResources(
774 messages: ReadonlyArray<Pick<ChatMessage, "id" | "role" | "attachments">> | undefined,
775 handoffs: Readonly<Record<string, ReadonlyArray<string>>>,
776): ReadonlyArray<AttachmentResource> {
777 if (Object.keys(handoffs).length === 0) return EMPTY_IMAGE_RESOURCES;
778 const attachmentIds = new Set<string>();
779 for (const message of messages ?? []) {
780 if (message.role !== "user" || !handoffs[message.id]?.length) continue;
781 for (const attachment of message.attachments ?? []) {
782 if (isImageAttachment(attachment)) attachmentIds.add(attachment.id);
783 }
784 }
785 return attachmentIds.size === 0
786 ? EMPTY_IMAGE_RESOURCES
787 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
789​
790export function createMessageAttachmentPreviewProjector() {
791 const attachmentsBySource = new WeakMap<
792 ReadonlyArray<ChatAttachment>,
793 ReadonlyArray<ChatAttachment>
794 >();
795 const messagesBySource = new WeakMap<ChatMessage, ChatMessage>();
796 return (
797 message: ChatMessage,
798 previewUrlFor: (attachment: ChatAttachment) => string | undefined,
799 ): ChatMessage => {
800 const source = message.attachments;
801 if (!source || source.length === 0) return message;
802 const previous = attachmentsBySource.get(source) ?? source;
803 let changed: ChatAttachment[] | undefined;
804 let hasOverrides = false;
805 for (const [index, attachment] of source.entries()) {
806 const previewUrl = previewUrlFor(attachment);
807 const sourceUrl = "previewUrl" in attachment ? attachment.previewUrl : undefined;
808 const previousAttachment = previous[index]!;
809 const previousUrl =
810 "previewUrl" in previousAttachment ? previousAttachment.previewUrl : undefined;
811 const next =
812 !previewUrl || previewUrl === sourceUrl
813 ? attachment
814 : previewUrl === previousUrl
815 ? previousAttachment
816 : { ...attachment, previewUrl };
817 hasOverrides ||= next !== attachment;
818 if (next !== previousAttachment) {
819 changed ??= previous.slice();
820 changed[index] = next;
821 }
822 }
823 const attachments = hasOverrides ? (changed ?? previous) : source;
824 attachmentsBySource.set(source, attachments);
825 if (attachments === source) {
826 messagesBySource.delete(message);
827 return message;
828 }
829 const previousMessage = messagesBySource.get(message);
830 if (previousMessage?.attachments === attachments) return previousMessage;
831 const result = { ...message, attachments };
832 messagesBySource.set(message, result);
833 return result;
834 };
836​
837export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
838 if (
839 previous.role !== "assistant" ||
840 next.role !== "assistant" ||
841 !previous.streaming ||
842 !next.streaming
843 ) {
844 return false;
845 }
846 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previous;
847 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = next;
848 return shallow(previousMetadata, nextMetadata);
850​
851function streamedTextMetadata(item: OrchestrationV2TurnItem) {
852 if (item.type === "proposed_plan" && item.streaming) {
853 const { markdown: _markdown, updatedAt: _updatedAt, ...metadata } = item;
854 return metadata;
855 }
856 if ((item.type === "assistant_message" || item.type === "reasoning") && item.streaming) {
857 const { text: _text, updatedAt: _updatedAt, ...metadata } = item;
858 return metadata;
859 }
860 return null;
862​
863export function isStreamingTurnItemTextUpdate(
864 previous: OrchestrationV2ProjectedTurnItem,
865 next: OrchestrationV2ProjectedTurnItem,
866): boolean {
867 const { item: previousItem, ...previousSource } = previous;
868 const { item: nextItem, ...nextSource } = next;
869 const previousMetadata = streamedTextMetadata(previousItem);
870 const nextMetadata = streamedTextMetadata(nextItem);
871 if (
872 previousMetadata === null ||
873 nextMetadata === null ||
874 !shallow(previousSource, nextSource) ||
875 projectedItemCreatedAt(previous) !== projectedItemCreatedAt(next)
876 ) {
877 return false;
878 }
879 // Wire decoding recreates timestamps and attachments; compare only the changed item's metadata.
880 return Equal.equals(previousMetadata, nextMetadata);
882​
883/**
884 * A changed tool or work item maps to exactly one entry with the item's id.
885 * Messages and question answers take part in cross-entry dedupe, and anchored
886 * messages are placed by createdAt, so those changes rebuild.
887 */
888function canRederiveInPlace(
889 input: TimelineEntriesInput,
890 previousItem: OrchestrationV2ProjectedTurnItem,
891 item: OrchestrationV2ProjectedTurnItem,
892): boolean {
893 return (
894 item.item.id === previousItem.item.id &&
895 item.item.type === previousItem.item.type &&
896 item.item.type !== "user_message" &&
897 item.item.type !== "assistant_message" &&
898 item.item.type !== "user_input_request" &&
899 // An app call projects two entries; in-place reuse replaces one.
900 (previousItem.item.type !== "dynamic_tool" ||
901 mcpAppFromToolItem(previousItem.item) === undefined) &&
902 ((input.anchoredMessages?.length ?? 0) === 0 ||
903 projectedItemCreatedAt(item) === projectedItemCreatedAt(previousItem))
904 );
906​
907/** Entries read only each plan's status; streaming plans rebuild artifacts with every delta. */
908function samePlanStatuses(
909 next: TimelineEntriesInput["plans"],
910 previous: TimelineEntriesInput["plans"],
911): boolean {
912 if (next === previous) return true;
913 if (next === undefined || previous === undefined || next.length !== previous.length) return false;
914 return next.every((plan, index) => {
915 const before = previous[index]!;
916 return plan.id === before.id && plan.kind === before.kind && plan.status === before.status;
917 });
919​
920function reuseTimelineEntries(
921 input: TimelineEntriesInput,
922 previous: TimelineEntriesProjection,
923): TimelineEntry[] | null {
924 const before = previous.input;
925 if (
926 input.visibleTurnItems.length < before.visibleTurnItems.length ||
927 !shallow(input.optimisticMessages, before.optimisticMessages) ||
928 !shallow(input.anchoredMessages, before.anchoredMessages) ||
929 !shallow(input.attachmentUrlById, before.attachmentUrlById) ||
930 !shallow(input.attempts, before.attempts) ||
931 !shallow(input.nodes, before.nodes) ||
932 !samePlanStatuses(input.plans, before.plans)
933 ) {
934 return null;
935 }
936 const appended = input.visibleTurnItems.length > before.visibleTurnItems.length;
937 // Keep full projection until committed items interleave and deduplicate anchored/optimistic messages.
938 if (
939 appended &&
940 (input.optimisticMessages.length > 0 || (input.anchoredMessages?.length ?? 0) > 0)
941 ) {
942 return null;
943 }
944 // Answer rows can replace a message already present in the retained prefix.
945 if (
946 appended &&
947 input.visibleTurnItems
948 .slice(before.visibleTurnItems.length)
949 .some(
950 ({ item }) =>
951 (item.type === "user_input_request" && item.questionAnswer !== undefined) ||
952 (item.type === "user_message" && item.messageId.startsWith("async-answer:")),
953 )
954 )
955 return null;
956 const replacements = new Map<
957 OrchestrationV2ProjectedTurnItem,
958 OrchestrationV2ProjectedTurnItem
959 >();
960 const changedItems: OrchestrationV2ProjectedTurnItem[] = [];
961 for (let index = 0; index < before.visibleTurnItems.length; index += 1) {
962 const previousItem = before.visibleTurnItems[index]!;
963 const item = input.visibleTurnItems[index]!;
964 if (item === previousItem) continue;
965 // Reasoning and plan text re-derive below; only assistant text patches the message.
966 if (
967 item.item.type === "assistant_message" &&
968 isStreamingTurnItemTextUpdate(previousItem, item)
969 ) {
970 replacements.set(previousItem, item);
971 continue;
972 }
973 if (!canRederiveInPlace(input, previousItem, item)) return null;
974 changedItems.push(item);
975 }
976 // One batch keeps the attempt/node/plan lookups to a single build.
977 const rederived =
978 changedItems.length === 0
979 ? []
980 : deriveTimelineEntriesFromVisibleTurnItems({
981 ...input,
982 visibleTurnItems: changedItems,
983 optimisticMessages: [],
984 anchoredMessages: [],
985 });
986 if (
987 rederived.length !== changedItems.length ||
988 rederived.some((entry, index) => entry.id !== changedItems[index]!.item.id)
989 ) {
990 return null;
991 }
992 const rederivedEntries = new Map(rederived.map((entry) => [entry.id, entry]));
993 if (replacements.size === 0 && rederivedEntries.size === 0 && !appended) {
994 return previous.entries;
995 }
996 let rederivedCount = 0;
997 const entries = previous.entries.map((entry): TimelineEntry => {
998 const rederivedEntry = rederivedEntries.get(entry.id);
999 if (rederivedEntry !== undefined) {
1000 rederivedCount += 1;
1001 return rederivedEntry;
1003 const row =
1004 entry.kind === "message" && entry.projectedItem !== undefined
1005 ? replacements.get(entry.projectedItem)
1006 : undefined;
1007 if (entry.kind !== "message" || row?.item.type !== "assistant_message") return entry;
1008 return {
1009 ...entry,
1010 projectedItem: row,
1011 message: {
1012 ...entry.message,
1013 text: row.item.text,
1014 updatedAt: DateTime.formatIso(row.item.updatedAt),
1015 },
1016 };
1017 });
1018 if (rederivedCount !== rederivedEntries.size) return null;
1019 if (appended) {
1020 entries.push(
1021 ...deriveTimelineEntriesFromVisibleTurnItems({
1022 ...input,
1023 visibleTurnItems: input.visibleTurnItems.slice(before.visibleTurnItems.length),
1024 }),
1025 );
1027 return entries;
1029​
1030export function deriveTimelineEntriesFromVisibleTurnItemsWithState(
1031 input: TimelineEntriesInput,
1032 previous: TimelineEntriesProjection | null = null,
1033): TimelineEntriesProjection {
1034 const reused = previous === null ? null : reuseTimelineEntries(input, previous);
1035 if (reused !== null) return { input, entries: reused };
1036 const entries = deriveTimelineEntriesFromVisibleTurnItems(input);
1037 if (previous === null || !shallow(input.attachmentUrlById, previous.input.attachmentUrlById)) {
1038 return { input, entries };
1040 const previousMessages = new Map(
1041 previous.entries.flatMap((entry) =>
1042 entry.kind === "message" ? [[entry.id, entry] as const] : [],
1043 ),
1044 );
1045 return {
1046 input,
1047 entries: entries.map((entry) => {
1048 if (entry.kind !== "message" || entry.projectedItem === undefined) return entry;
1049 const before = previousMessages.get(entry.id);
1050 if (before?.projectedItem !== entry.projectedItem) return entry;
1051 return before.attempt === entry.attempt ? before : { ...entry, message: before.message };
1052 }),
1053 };
1055​
1056// Run ordinals keep increasing after a rewind; only visible local runs define predecessors.
1057export function deriveRevertTurnCountByUserMessageId(input: {
1058 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
1059 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
1060 readonly threadStartCheckpointAvailable: boolean;
1061 readonly availableRevertTurnCounts?: ReadonlySet<number> | undefined;
1062 readonly unsettledRunId?: RunId | null;
1063}): Map<ChatMessage["id"], number> {
1064 const turnCountByRunId = new Map<RunId, number>();
1065 for (const checkpoint of input.checkpoints) {
1066 if (isRewindableCheckpoint(checkpoint)) {
1067 turnCountByRunId.set(checkpoint.runId, checkpoint.checkpointTurnCount);
1070 const targetByRunId = new Map<RunId, number | undefined>();
1071 const byUserMessageId = new Map<ChatMessage["id"], number>();
1072 let previousRunId: RunId | null = null;
1073 for (const entry of input.timelineEntries) {
1074 // Inherited history belongs to the source thread, not our checkpoint scope.
1075 if (entry.kind !== "message" && entry.kind !== "work") continue;
1076 const projectedItem =
1077 entry.kind === "message" ? entry.projectedItem : entry.entry.projectedItem;
1078 if (projectedItem?.visibility === "inherited") continue;
1079 const runId =
1080 entry.kind === "message"
1081 ? entry.message.runId
1082 : entry.entry.itemType === "notification"
1083 ? entry.entry.runId
1084 : null;
1085 if (runId == null) continue;
1086 if (!targetByRunId.has(runId)) {
1087 targetByRunId.set(
1088 runId,
1089 previousRunId === null
1090 ? input.threadStartCheckpointAvailable
1091 ? 0
1092 : undefined
1093 : turnCountByRunId.get(previousRunId),
1094 );
1095 previousRunId = runId;
1097 if (entry.kind !== "message") continue;
1098 const { message } = entry;
1099 if (message.role !== "user" || message.runId === input.unsettledRunId) continue;
1100 if (message.inputIntent !== "turn_start" && message.inputIntent !== "queued_turn") continue;
1101 const target = targetByRunId.get(runId);
1102 if (
1103 target !== undefined &&
1104 (input.availableRevertTurnCounts === undefined || input.availableRevertTurnCounts.has(target))
1106 byUserMessageId.set(message.id, target);
1108 return byUserMessageId;
1110​
1111// A missing snapshot (no git, or a side chat) still pins a conversation position; only
1112// restoring files needs a ready one.
1113function isRewindableCheckpoint(checkpoint: Pick<OrchestrationV2Checkpoint, "status">) {
1114 return checkpoint.status === "ready" || checkpoint.status === "missing";
1116​
1117export function findRevertCheckpoint(
1118 checkpoints: ReadonlyArray<OrchestrationV2Checkpoint>,
1119 turnCount: number,
1120): OrchestrationV2Checkpoint | undefined {
1121 return checkpoints.findLast(
1122 (checkpoint) =>
1123 isRewindableCheckpoint(checkpoint) &&
1124 (turnCount === 0
1125 ? checkpoint.ordinalWithinScope === 0 && checkpoint.appRunOrdinal === null
1126 : checkpoint.appRunOrdinal === turnCount),
1127 );
1129​
1130export function derivePhase(runtime: ThreadStructureRuntime | null): SessionPhase {
1131 if (runtime === null) return "disconnected";
1132 if (
1133 runtime.status === "preparing" ||
1134 runtime.status === "starting" ||
1135 runtime.status === "queued"
1137 return "connecting";
1138 if (runtime.status === "running" || runtime.status === "waiting") return "running";
1139 return "ready";
1141​
1142/** Preparing and starting runs can be interrupted; Stop need not wait for running. */
1143export function deriveCanInterruptRunningThread(
1144 hasActiveThread: boolean,
1145 runtime: ThreadStructureRuntime | null,
1146): boolean {
1147 return (
1148 hasActiveThread &&
1149 (derivePhase(runtime) === "running" || threadRuntimeHasInterruptibleRun(runtime))
1150 );
1152​
1153export type { TurnDiffSummary };