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

session-logic.ts

1,164 lines38.8 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.idleCompaction !== undefined ? { idleCompaction: item.idleCompaction } : {}),
718 ...(item.scheduledTaskId !== undefined
719 ? { scheduledTaskId: item.scheduledTaskId }
720 : {}),
721 }
722 : {}),
723 createdAt,
724 updatedAt: DateTime.formatIso(item.updatedAt),
725 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
726 };
727 committedMessageIds.add(message.id);
728 entries.push({
729 id: message.id,
730 kind: "message",
731 createdAt,
732 message,
733 projectedItem: row,
734 ...attemptMetadata,
735 });
736 continue;
737 }
738​
739 if (item.type === "proposed_plan") {
740 const plan = planById.get(item.planId);
741 const proposedPlan = {
742 id: item.planId,
743 runId: item.runId,
744 planMarkdown: item.markdown,
745 status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
746 createdAt,
747 updatedAt: DateTime.formatIso(item.updatedAt),
748 };
749 entries.push({
750 id: item.id,
751 kind: "proposed-plan",
752 createdAt,
753 proposedPlan,
754 ...attemptMetadata,
755 });
756 continue;
757 }
758​
759 const htmlRender =
760 item.type === "dynamic_tool" && item.status === "completed"
761 ? htmlRenderFromToolItem(item)
762 : undefined;
763 if (htmlRender !== undefined) {
764 entries.push({
765 id: item.id,
766 kind: "html-render",
767 createdAt,
768 runId: item.runId,
769 htmlRender,
770 ...attemptMetadata,
771 });
772 continue;
773 }
774​
775 const mcpApp =
776 item.type === "dynamic_tool" && item.status === "completed"
777 ? mcpAppFromToolItem(item)
778 : undefined;
779 if (mcpApp !== undefined) {
780 entries.push({
781 id: item.id,
782 kind: "mcp-app",
783 createdAt,
784 runId: item.runId,
785 sourceThreadId: row.sourceThreadId,
786 itemId: row.sourceItemId,
787 revision: turnItemDetailRevision(item),
788 mcpApp,
789 ...attemptMetadata,
790 });
791 continue;
792 }
793​
794 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
795 entries.push({
796 id: item.id,
797 kind: "event",
798 createdAt,
799 projectedItem: row,
800 ...attemptMetadata,
801 });
802 continue;
803 }
804​
805 entries.push({
806 id: item.id,
807 kind: "work",
808 createdAt,
809 entry: projectedWorkEntry(row),
810 ...attemptMetadata,
811 });
812 }
813​
814 const retainedMessageIds = new Set([...committedMessageIds, ...foldedAnswerMessageIds]);
815 for (const message of input.anchoredMessages ?? []) {
816 if (retainedMessageIds.has(message.id)) continue;
817 retainedMessageIds.add(message.id);
818 const entry: TimelineEntry = {
819 id: message.id,
820 kind: "message",
821 createdAt: message.createdAt,
822 message,
823 };
824 const insertionIndex = entries.findIndex(
825 (candidate) => candidate.createdAt > message.createdAt,
826 );
827 if (insertionIndex === -1) {
828 entries.push(entry);
829 } else {
830 entries.splice(insertionIndex, 0, entry);
831 }
832 }
833​
834 for (const message of input.optimisticMessages) {
835 if (message.inputIntent !== "queued_turn" && !retainedMessageIds.has(message.id)) {
836 retainedMessageIds.add(message.id);
837 entries.push({
838 id: message.id,
839 kind: "message",
840 createdAt: message.createdAt,
841 message,
842 });
843 }
844 }
845​
846 return entries;
848​
849type AttachmentResource = Extract<AssetResource, { readonly _tag: "attachment" }>;
850const EMPTY_IMAGE_RESOURCES = Object.freeze<ReadonlyArray<AttachmentResource>>([]);
851​
852export function selectMessageImageResources(
853 attachments: ChatMessage["attachments"],
854): ReadonlyArray<AttachmentResource> {
855 const attachmentIds = new Set<string>();
856 for (const attachment of attachments ?? []) {
857 if (!isImageAttachment(attachment)) continue;
858 const previewUrl = attachment.previewUrl;
859 if (previewUrl?.startsWith("blob:") || previewUrl?.startsWith("data:")) continue;
860 attachmentIds.add(attachment.id);
861 }
862 return attachmentIds.size === 0
863 ? EMPTY_IMAGE_RESOURCES
864 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
866​
867export function selectHandoffImageResources(
868 messages: ReadonlyArray<Pick<ChatMessage, "id" | "role" | "attachments">> | undefined,
869 handoffs: Readonly<Record<string, ReadonlyArray<string>>>,
870): ReadonlyArray<AttachmentResource> {
871 if (Object.keys(handoffs).length === 0) return EMPTY_IMAGE_RESOURCES;
872 const attachmentIds = new Set<string>();
873 for (const message of messages ?? []) {
874 if (message.role !== "user" || !handoffs[message.id]?.length) continue;
875 for (const attachment of message.attachments ?? []) {
876 if (isImageAttachment(attachment)) attachmentIds.add(attachment.id);
877 }
878 }
879 return attachmentIds.size === 0
880 ? EMPTY_IMAGE_RESOURCES
881 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
883​
884export function createMessageAttachmentPreviewProjector() {
885 const attachmentsBySource = new WeakMap<
886 ReadonlyArray<ChatAttachment>,
887 ReadonlyArray<ChatAttachment>
888 >();
889 const messagesBySource = new WeakMap<ChatMessage, ChatMessage>();
890 return (
891 message: ChatMessage,
892 previewUrlFor: (attachment: ChatAttachment) => string | undefined,
893 ): ChatMessage => {
894 const source = message.attachments;
895 if (!source || source.length === 0) return message;
896 const previous = attachmentsBySource.get(source) ?? source;
897 let changed: ChatAttachment[] | undefined;
898 let hasOverrides = false;
899 for (const [index, attachment] of source.entries()) {
900 const previewUrl = previewUrlFor(attachment);
901 const sourceUrl = "previewUrl" in attachment ? attachment.previewUrl : undefined;
902 const previousAttachment = previous[index]!;
903 const previousUrl =
904 "previewUrl" in previousAttachment ? previousAttachment.previewUrl : undefined;
905 const next =
906 !previewUrl || previewUrl === sourceUrl
907 ? attachment
908 : previewUrl === previousUrl
909 ? previousAttachment
910 : { ...attachment, previewUrl };
911 hasOverrides ||= next !== attachment;
912 if (next !== previousAttachment) {
913 changed ??= previous.slice();
914 changed[index] = next;
915 }
916 }
917 const attachments = hasOverrides ? (changed ?? previous) : source;
918 attachmentsBySource.set(source, attachments);
919 if (attachments === source) {
920 messagesBySource.delete(message);
921 return message;
922 }
923 const previousMessage = messagesBySource.get(message);
924 if (previousMessage?.attachments === attachments) return previousMessage;
925 const result = { ...message, attachments };
926 messagesBySource.set(message, result);
927 return result;
928 };
930​
931export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
932 if (
933 previous.role !== "assistant" ||
934 next.role !== "assistant" ||
935 !previous.streaming ||
936 !next.streaming
937 ) {
938 return false;
939 }
940 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previous;
941 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = next;
942 return shallow(previousMetadata, nextMetadata);
944​
945export function isStreamingTurnItemTextUpdate(
946 previous: OrchestrationV2ProjectedTurnItem,
947 next: OrchestrationV2ProjectedTurnItem,
948): boolean {
949 const { item: previousItem, ...previousSource } = previous;
950 const { item: nextItem, ...nextSource } = next;
951 if (
952 previousItem.type !== "assistant_message" ||
953 nextItem.type !== "assistant_message" ||
954 !previousItem.streaming ||
955 !nextItem.streaming ||
956 !shallow(previousSource, nextSource) ||
957 projectedItemCreatedAt(previous) !== projectedItemCreatedAt(next)
958 ) {
959 return false;
960 }
961 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previousItem;
962 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = nextItem;
963 // Wire decoding can recreate timestamps and attachments on each update.
964 // Compare only the changed item's metadata, never the entire transcript.
965 return Equal.equals(previousMetadata, nextMetadata);
967​
968function reuseTimelineEntries(
969 input: TimelineEntriesInput,
970 previous: TimelineEntriesProjection,
971): TimelineEntry[] | null {
972 const before = previous.input;
973 if (
974 input.visibleTurnItems.length < before.visibleTurnItems.length ||
975 !shallow(input.optimisticMessages, before.optimisticMessages) ||
976 !shallow(input.anchoredMessages, before.anchoredMessages) ||
977 !shallow(input.attachmentUrlById, before.attachmentUrlById) ||
978 !shallow(input.attempts, before.attempts) ||
979 !shallow(input.nodes, before.nodes) ||
980 !shallow(input.plans, before.plans)
981 ) {
982 return null;
983 }
984 const appended = input.visibleTurnItems.length > before.visibleTurnItems.length;
985 // Anchored and optimistic messages need to be interleaved/deduplicated when
986 // committed items arrive. Keep the full projection for that transition.
987 if (
988 appended &&
989 (input.optimisticMessages.length > 0 || (input.anchoredMessages?.length ?? 0) > 0)
990 ) {
991 return null;
992 }
993 // Answer rows can replace a message already present in the retained prefix.
994 if (
995 appended &&
996 input.visibleTurnItems
997 .slice(before.visibleTurnItems.length)
998 .some(
999 ({ item }) =>
1000 (item.type === "user_input_request" && item.questionAnswer !== undefined) ||
1001 (item.type === "user_message" && item.messageId.startsWith("async-answer:")),
1004 return null;
1005 const replacements = new Map<
1006 OrchestrationV2ProjectedTurnItem,
1007 OrchestrationV2ProjectedTurnItem
1008 >();
1009 for (let index = 0; index < before.visibleTurnItems.length; index += 1) {
1010 const previousItem = before.visibleTurnItems[index]!;
1011 const item = input.visibleTurnItems[index]!;
1012 if (item === previousItem) continue;
1013 if (!isStreamingTurnItemTextUpdate(previousItem, item)) return null;
1014 replacements.set(previousItem, item);
1016 if (replacements.size === 0 && !appended) return previous.entries;
1017 const entries = previous.entries.map((entry): TimelineEntry => {
1018 const row =
1019 entry.kind === "message" && entry.projectedItem !== undefined
1020 ? replacements.get(entry.projectedItem)
1021 : undefined;
1022 if (entry.kind !== "message" || row?.item.type !== "assistant_message") return entry;
1023 return {
1024 ...entry,
1025 projectedItem: row,
1026 message: {
1027 ...entry.message,
1028 text: row.item.text,
1029 updatedAt: DateTime.formatIso(row.item.updatedAt),
1030 },
1031 };
1032 });
1033 if (appended) {
1034 entries.push(
1035 ...deriveTimelineEntriesFromVisibleTurnItems({
1036 ...input,
1037 visibleTurnItems: input.visibleTurnItems.slice(before.visibleTurnItems.length),
1038 }),
1039 );
1041 return entries;
1043​
1044export function deriveTimelineEntriesFromVisibleTurnItemsWithState(
1045 input: TimelineEntriesInput,
1046 previous: TimelineEntriesProjection | null = null,
1047): TimelineEntriesProjection {
1048 const reused = previous === null ? null : reuseTimelineEntries(input, previous);
1049 if (reused !== null) return { input, entries: reused };
1050 const entries = deriveTimelineEntriesFromVisibleTurnItems(input);
1051 if (previous === null || !shallow(input.attachmentUrlById, previous.input.attachmentUrlById)) {
1052 return { input, entries };
1054 const previousMessages = new Map(
1055 previous.entries.flatMap((entry) =>
1056 entry.kind === "message" ? [[entry.id, entry] as const] : [],
1057 ),
1058 );
1059 return {
1060 input,
1061 entries: entries.map((entry) => {
1062 if (entry.kind !== "message" || entry.projectedItem === undefined) return entry;
1063 const before = previousMessages.get(entry.id);
1064 if (before?.projectedItem !== entry.projectedItem) return entry;
1065 return before.attempt === entry.attempt ? before : { ...entry, message: before.message };
1066 }),
1067 };
1069​
1070// Run ordinals keep increasing after a rewind; only visible local runs define predecessors.
1071export function deriveRevertTurnCountByUserMessageId(input: {
1072 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
1073 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
1074 readonly threadStartCheckpointReady: boolean;
1075 readonly availableRevertTurnCounts?: ReadonlySet<number> | undefined;
1076 readonly unsettledRunId?: RunId | null;
1077}): Map<ChatMessage["id"], number> {
1078 const readyTurnCountByRunId = new Map<RunId, number>();
1079 for (const checkpoint of input.checkpoints) {
1080 if (checkpoint.status === "ready") {
1081 readyTurnCountByRunId.set(checkpoint.runId, checkpoint.checkpointTurnCount);
1084 const targetByRunId = new Map<RunId, number | undefined>();
1085 const byUserMessageId = new Map<ChatMessage["id"], number>();
1086 let previousRunId: RunId | null = null;
1087 for (const entry of input.timelineEntries) {
1088 // Inherited history belongs to the source thread, not our checkpoint scope.
1089 if (entry.kind !== "message" && entry.kind !== "work") continue;
1090 const projectedItem =
1091 entry.kind === "message" ? entry.projectedItem : entry.entry.projectedItem;
1092 if (projectedItem?.visibility === "inherited") continue;
1093 const runId =
1094 entry.kind === "message"
1095 ? entry.message.runId
1096 : entry.entry.itemType === "notification"
1097 ? entry.entry.runId
1098 : null;
1099 if (runId == null) continue;
1100 if (!targetByRunId.has(runId)) {
1101 targetByRunId.set(
1102 runId,
1103 previousRunId === null
1104 ? input.threadStartCheckpointReady
1105 ? 0
1106 : undefined
1107 : readyTurnCountByRunId.get(previousRunId),
1108 );
1109 previousRunId = runId;
1111 if (entry.kind !== "message") continue;
1112 const { message } = entry;
1113 if (message.role !== "user" || message.runId === input.unsettledRunId) continue;
1114 if (message.inputIntent !== "turn_start" && message.inputIntent !== "queued_turn") continue;
1115 const target = targetByRunId.get(runId);
1116 if (
1117 target !== undefined &&
1118 (input.availableRevertTurnCounts === undefined || input.availableRevertTurnCounts.has(target))
1120 byUserMessageId.set(message.id, target);
1122 return byUserMessageId;
1124​
1125export function findRevertCheckpoint(
1126 checkpoints: ReadonlyArray<OrchestrationV2Checkpoint>,
1127 turnCount: number,
1128): OrchestrationV2Checkpoint | undefined {
1129 return checkpoints.findLast(
1130 (checkpoint) =>
1131 checkpoint.status === "ready" &&
1132 (turnCount === 0
1133 ? checkpoint.ordinalWithinScope === 0 && checkpoint.appRunOrdinal === null
1134 : checkpoint.appRunOrdinal === turnCount),
1135 );
1137​
1138export function derivePhase(runtime: ThreadStructureRuntime | null): SessionPhase {
1139 if (runtime === null) return "disconnected";
1140 if (
1141 runtime.status === "preparing" ||
1142 runtime.status === "starting" ||
1143 runtime.status === "queued"
1145 return "connecting";
1146 if (runtime.status === "running" || runtime.status === "waiting") return "running";
1147 return "ready";
1149​
1150/**
1151 * The server settles a preparing or starting run on `run.interrupt`
1152 * (Orchestrator.dispatchRunInterrupt), so Stop must not wait for the phase to reach "running".
1153 */
1154export function deriveCanInterruptRunningThread(
1155 hasActiveThread: boolean,
1156 runtime: ThreadStructureRuntime | null,
1157): boolean {
1158 return (
1159 hasActiveThread &&
1160 (derivePhase(runtime) === "running" || threadRuntimeHasInterruptibleRun(runtime))
1161 );
1163​
1164export type { TurnDiffSummary };