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

session-logic.ts

1,064 lines34.9 KB

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