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

session-logic.ts

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