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

session-logic.ts

1,150 lines38.1 KB

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