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

session-logic.ts

1,156 lines38.5 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/** Preserve visibleTurnItems' committed order; interleave client messages by timestamp. */
616export interface TimelineEntriesInput {
617 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
618 readonly optimisticMessages: ReadonlyArray<ChatMessage>;
619 readonly anchoredMessages?: ReadonlyArray<ChatMessage>;
620 readonly attachmentUrlById?: ReadonlyMap<string, string>;
621 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
622 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
623 readonly plans?: ReadonlyArray<OrchestrationV2PlanArtifact>;
625​
626export interface TimelineEntriesProjection {
627 readonly input: TimelineEntriesInput;
628 readonly entries: TimelineEntry[];
630​
631export function deriveTimelineEntriesFromVisibleTurnItems(
632 input: TimelineEntriesInput,
633): TimelineEntry[] {
634 const committedMessageIds = new Set<string>();
635 const entries: TimelineEntry[] = [];
636 const attemptByRootNodeId = new Map(
637 (input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
638 );
639 const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const));
640 const planById = new Map((input.plans ?? []).map((plan) => [plan.id, plan] as const));
641​
642 const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => {
643 if (item.nodeId === null || item.runId === null) return undefined;
644 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
645 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
646 while (nodeId !== null && !visited.has(nodeId)) {
647 visited.add(nodeId);
648 const directAttempt = attemptByRootNodeId.get(nodeId);
649 if (directAttempt?.runId === item.runId) return directAttempt;
650 const node = nodeById.get(nodeId);
651 if (node === undefined) return undefined;
652 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
653 if (rootAttempt?.runId === item.runId) return rootAttempt;
654 nodeId = node.parentNodeId;
655 }
656 return undefined;
657 };
658​
659 const foldedAnswerMessageIds = new Set(
660 input.visibleTurnItems.flatMap(({ item }) =>
661 item.type === "user_input_request" && item.questionAnswer
662 ? [`async-answer:${item.questionAnswer.requestId}`]
663 : [],
664 ),
665 );
666 for (const row of input.visibleTurnItems) {
667 const { item } = row;
668 if (turnItemIsWorkspacePreparation(item)) continue;
669 if (item.type === "todo_list" || item.type === "checkpoint") continue;
670 if (item.type === "user_message" && foldedAnswerMessageIds.has(item.messageId)) continue;
671 const createdAt = projectedItemCreatedAt(row);
672 const attempt = resolveAttempt(item);
673 const attemptMetadata = attempt === undefined ? {} : { attempt };
674 if (item.type === "notification") {
675 entries.push({
676 id: item.id,
677 kind: "work",
678 createdAt,
679 entry: {
680 id: item.id,
681 createdAt,
682 runId: item.runId,
683 label: item.summary,
684 tone: "info",
685 itemType: item.type,
686 structuredPayload: item,
687 projectedItem: row,
688 },
689 ...attemptMetadata,
690 });
691 continue;
692 }
693 if (item.type === "user_message" || item.type === "assistant_message") {
694 const message: ChatMessage = {
695 id: item.messageId,
696 role: item.type === "user_message" ? "user" : "assistant",
697 text: item.text,
698 ...(item.type === "user_message" && item.context ? { context: item.context } : {}),
699 ...((item.attachments?.length ?? 0) > 0
700 ? {
701 attachments: (item.attachments ?? []).map((attachment) => {
702 const previewUrl = input.attachmentUrlById?.get(attachment.id);
703 return previewUrl ? { ...attachment, previewUrl } : attachment;
704 }),
705 }
706 : {}),
707 runId: item.runId,
708 streaming: item.type === "assistant_message" && item.streaming,
709 ...(item.type === "user_message"
710 ? {
711 createdBy: item.createdBy,
712 creationSource: item.creationSource,
713 ...(item.senderThreadId !== undefined ? { senderThreadId: item.senderThreadId } : {}),
714 ...(item.idleCompaction !== undefined ? { idleCompaction: item.idleCompaction } : {}),
715 ...(item.scheduledTaskId !== undefined
716 ? { scheduledTaskId: item.scheduledTaskId }
717 : {}),
718 }
719 : {}),
720 createdAt,
721 updatedAt: DateTime.formatIso(item.updatedAt),
722 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
723 };
724 committedMessageIds.add(message.id);
725 entries.push({
726 id: message.id,
727 kind: "message",
728 createdAt,
729 message,
730 projectedItem: row,
731 ...attemptMetadata,
732 });
733 continue;
734 }
735​
736 if (item.type === "proposed_plan") {
737 const plan = planById.get(item.planId);
738 const proposedPlan = {
739 id: item.planId,
740 runId: item.runId,
741 planMarkdown: item.markdown,
742 status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
743 createdAt,
744 updatedAt: DateTime.formatIso(item.updatedAt),
745 };
746 entries.push({
747 id: item.id,
748 kind: "proposed-plan",
749 createdAt,
750 proposedPlan,
751 ...attemptMetadata,
752 });
753 continue;
754 }
755​
756 const htmlRender =
757 item.type === "dynamic_tool" && item.status === "completed"
758 ? htmlRenderFromToolItem(item)
759 : undefined;
760 if (htmlRender !== undefined) {
761 entries.push({
762 id: item.id,
763 kind: "html-render",
764 createdAt,
765 runId: item.runId,
766 htmlRender,
767 ...attemptMetadata,
768 });
769 continue;
770 }
771​
772 const mcpApp =
773 item.type === "dynamic_tool" && item.status === "completed"
774 ? mcpAppFromToolItem(item)
775 : undefined;
776 if (mcpApp !== undefined) {
777 entries.push({
778 id: item.id,
779 kind: "mcp-app",
780 createdAt,
781 runId: item.runId,
782 sourceThreadId: row.sourceThreadId,
783 itemId: row.sourceItemId,
784 revision: turnItemDetailRevision(item),
785 mcpApp,
786 ...attemptMetadata,
787 });
788 continue;
789 }
790​
791 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
792 entries.push({
793 id: item.id,
794 kind: "event",
795 createdAt,
796 projectedItem: row,
797 ...attemptMetadata,
798 });
799 continue;
800 }
801​
802 entries.push({
803 id: item.id,
804 kind: "work",
805 createdAt,
806 entry: projectedWorkEntry(row),
807 ...attemptMetadata,
808 });
809 }
810​
811 const retainedMessageIds = new Set([...committedMessageIds, ...foldedAnswerMessageIds]);
812 for (const message of input.anchoredMessages ?? []) {
813 if (retainedMessageIds.has(message.id)) continue;
814 retainedMessageIds.add(message.id);
815 const entry: TimelineEntry = {
816 id: message.id,
817 kind: "message",
818 createdAt: message.createdAt,
819 message,
820 };
821 const insertionIndex = entries.findIndex(
822 (candidate) => candidate.createdAt > message.createdAt,
823 );
824 if (insertionIndex === -1) {
825 entries.push(entry);
826 } else {
827 entries.splice(insertionIndex, 0, entry);
828 }
829 }
830​
831 for (const message of input.optimisticMessages) {
832 if (message.inputIntent !== "queued_turn" && !retainedMessageIds.has(message.id)) {
833 retainedMessageIds.add(message.id);
834 entries.push({
835 id: message.id,
836 kind: "message",
837 createdAt: message.createdAt,
838 message,
839 });
840 }
841 }
842​
843 return entries;
845​
846type AttachmentResource = Extract<AssetResource, { readonly _tag: "attachment" }>;
847const EMPTY_IMAGE_RESOURCES = Object.freeze<ReadonlyArray<AttachmentResource>>([]);
848​
849export function selectMessageImageResources(
850 attachments: ChatMessage["attachments"],
851): ReadonlyArray<AttachmentResource> {
852 const attachmentIds = new Set<string>();
853 for (const attachment of attachments ?? []) {
854 if (!isImageAttachment(attachment)) continue;
855 const previewUrl = attachment.previewUrl;
856 if (previewUrl?.startsWith("blob:") || previewUrl?.startsWith("data:")) continue;
857 attachmentIds.add(attachment.id);
858 }
859 return attachmentIds.size === 0
860 ? EMPTY_IMAGE_RESOURCES
861 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
863​
864export function selectHandoffImageResources(
865 messages: ReadonlyArray<Pick<ChatMessage, "id" | "role" | "attachments">> | undefined,
866 handoffs: Readonly<Record<string, ReadonlyArray<string>>>,
867): ReadonlyArray<AttachmentResource> {
868 if (Object.keys(handoffs).length === 0) return EMPTY_IMAGE_RESOURCES;
869 const attachmentIds = new Set<string>();
870 for (const message of messages ?? []) {
871 if (message.role !== "user" || !handoffs[message.id]?.length) continue;
872 for (const attachment of message.attachments ?? []) {
873 if (isImageAttachment(attachment)) attachmentIds.add(attachment.id);
874 }
875 }
876 return attachmentIds.size === 0
877 ? EMPTY_IMAGE_RESOURCES
878 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
880​
881export function createMessageAttachmentPreviewProjector() {
882 const attachmentsBySource = new WeakMap<
883 ReadonlyArray<ChatAttachment>,
884 ReadonlyArray<ChatAttachment>
885 >();
886 const messagesBySource = new WeakMap<ChatMessage, ChatMessage>();
887 return (
888 message: ChatMessage,
889 previewUrlFor: (attachment: ChatAttachment) => string | undefined,
890 ): ChatMessage => {
891 const source = message.attachments;
892 if (!source || source.length === 0) return message;
893 const previous = attachmentsBySource.get(source) ?? source;
894 let changed: ChatAttachment[] | undefined;
895 let hasOverrides = false;
896 for (const [index, attachment] of source.entries()) {
897 const previewUrl = previewUrlFor(attachment);
898 const sourceUrl = "previewUrl" in attachment ? attachment.previewUrl : undefined;
899 const previousAttachment = previous[index]!;
900 const previousUrl =
901 "previewUrl" in previousAttachment ? previousAttachment.previewUrl : undefined;
902 const next =
903 !previewUrl || previewUrl === sourceUrl
904 ? attachment
905 : previewUrl === previousUrl
906 ? previousAttachment
907 : { ...attachment, previewUrl };
908 hasOverrides ||= next !== attachment;
909 if (next !== previousAttachment) {
910 changed ??= previous.slice();
911 changed[index] = next;
912 }
913 }
914 const attachments = hasOverrides ? (changed ?? previous) : source;
915 attachmentsBySource.set(source, attachments);
916 if (attachments === source) {
917 messagesBySource.delete(message);
918 return message;
919 }
920 const previousMessage = messagesBySource.get(message);
921 if (previousMessage?.attachments === attachments) return previousMessage;
922 const result = { ...message, attachments };
923 messagesBySource.set(message, result);
924 return result;
925 };
927​
928export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
929 if (
930 previous.role !== "assistant" ||
931 next.role !== "assistant" ||
932 !previous.streaming ||
933 !next.streaming
934 ) {
935 return false;
936 }
937 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previous;
938 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = next;
939 return shallow(previousMetadata, nextMetadata);
941​
942export function isStreamingTurnItemTextUpdate(
943 previous: OrchestrationV2ProjectedTurnItem,
944 next: OrchestrationV2ProjectedTurnItem,
945): boolean {
946 const { item: previousItem, ...previousSource } = previous;
947 const { item: nextItem, ...nextSource } = next;
948 if (
949 previousItem.type !== "assistant_message" ||
950 nextItem.type !== "assistant_message" ||
951 !previousItem.streaming ||
952 !nextItem.streaming ||
953 !shallow(previousSource, nextSource) ||
954 projectedItemCreatedAt(previous) !== projectedItemCreatedAt(next)
955 ) {
956 return false;
957 }
958 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previousItem;
959 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = nextItem;
960 // Wire decoding recreates timestamps and attachments; compare only the changed item's metadata.
961 return Equal.equals(previousMetadata, nextMetadata);
963​
964function reuseTimelineEntries(
965 input: TimelineEntriesInput,
966 previous: TimelineEntriesProjection,
967): TimelineEntry[] | null {
968 const before = previous.input;
969 if (
970 input.visibleTurnItems.length < before.visibleTurnItems.length ||
971 !shallow(input.optimisticMessages, before.optimisticMessages) ||
972 !shallow(input.anchoredMessages, before.anchoredMessages) ||
973 !shallow(input.attachmentUrlById, before.attachmentUrlById) ||
974 !shallow(input.attempts, before.attempts) ||
975 !shallow(input.nodes, before.nodes) ||
976 !shallow(input.plans, before.plans)
977 ) {
978 return null;
979 }
980 const appended = input.visibleTurnItems.length > before.visibleTurnItems.length;
981 // Keep full projection until committed items interleave and deduplicate anchored/optimistic messages.
982 if (
983 appended &&
984 (input.optimisticMessages.length > 0 || (input.anchoredMessages?.length ?? 0) > 0)
985 ) {
986 return null;
987 }
988 // Answer rows can replace a message already present in the retained prefix.
989 if (
990 appended &&
991 input.visibleTurnItems
992 .slice(before.visibleTurnItems.length)
993 .some(
994 ({ item }) =>
995 (item.type === "user_input_request" && item.questionAnswer !== undefined) ||
996 (item.type === "user_message" && item.messageId.startsWith("async-answer:")),
997 )
998 )
999 return null;
1000 const replacements = new Map<
1001 OrchestrationV2ProjectedTurnItem,
1002 OrchestrationV2ProjectedTurnItem
1003 >();
1004 for (let index = 0; index < before.visibleTurnItems.length; index += 1) {
1005 const previousItem = before.visibleTurnItems[index]!;
1006 const item = input.visibleTurnItems[index]!;
1007 if (item === previousItem) continue;
1008 if (!isStreamingTurnItemTextUpdate(previousItem, item)) return null;
1009 replacements.set(previousItem, item);
1011 if (replacements.size === 0 && !appended) return previous.entries;
1012 const entries = previous.entries.map((entry): TimelineEntry => {
1013 const row =
1014 entry.kind === "message" && entry.projectedItem !== undefined
1015 ? replacements.get(entry.projectedItem)
1016 : undefined;
1017 if (entry.kind !== "message" || row?.item.type !== "assistant_message") return entry;
1018 return {
1019 ...entry,
1020 projectedItem: row,
1021 message: {
1022 ...entry.message,
1023 text: row.item.text,
1024 updatedAt: DateTime.formatIso(row.item.updatedAt),
1025 },
1026 };
1027 });
1028 if (appended) {
1029 entries.push(
1030 ...deriveTimelineEntriesFromVisibleTurnItems({
1031 ...input,
1032 visibleTurnItems: input.visibleTurnItems.slice(before.visibleTurnItems.length),
1033 }),
1034 );
1036 return entries;
1038​
1039export function deriveTimelineEntriesFromVisibleTurnItemsWithState(
1040 input: TimelineEntriesInput,
1041 previous: TimelineEntriesProjection | null = null,
1042): TimelineEntriesProjection {
1043 const reused = previous === null ? null : reuseTimelineEntries(input, previous);
1044 if (reused !== null) return { input, entries: reused };
1045 const entries = deriveTimelineEntriesFromVisibleTurnItems(input);
1046 if (previous === null || !shallow(input.attachmentUrlById, previous.input.attachmentUrlById)) {
1047 return { input, entries };
1049 const previousMessages = new Map(
1050 previous.entries.flatMap((entry) =>
1051 entry.kind === "message" ? [[entry.id, entry] as const] : [],
1052 ),
1053 );
1054 return {
1055 input,
1056 entries: entries.map((entry) => {
1057 if (entry.kind !== "message" || entry.projectedItem === undefined) return entry;
1058 const before = previousMessages.get(entry.id);
1059 if (before?.projectedItem !== entry.projectedItem) return entry;
1060 return before.attempt === entry.attempt ? before : { ...entry, message: before.message };
1061 }),
1062 };
1064​
1065// Run ordinals keep increasing after a rewind; only visible local runs define predecessors.
1066export function deriveRevertTurnCountByUserMessageId(input: {
1067 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
1068 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
1069 readonly threadStartCheckpointReady: boolean;
1070 readonly availableRevertTurnCounts?: ReadonlySet<number> | undefined;
1071 readonly unsettledRunId?: RunId | null;
1072}): Map<ChatMessage["id"], number> {
1073 const readyTurnCountByRunId = new Map<RunId, number>();
1074 for (const checkpoint of input.checkpoints) {
1075 if (checkpoint.status === "ready") {
1076 readyTurnCountByRunId.set(checkpoint.runId, checkpoint.checkpointTurnCount);
1079 const targetByRunId = new Map<RunId, number | undefined>();
1080 const byUserMessageId = new Map<ChatMessage["id"], number>();
1081 let previousRunId: RunId | null = null;
1082 for (const entry of input.timelineEntries) {
1083 // Inherited history belongs to the source thread, not our checkpoint scope.
1084 if (entry.kind !== "message" && entry.kind !== "work") continue;
1085 const projectedItem =
1086 entry.kind === "message" ? entry.projectedItem : entry.entry.projectedItem;
1087 if (projectedItem?.visibility === "inherited") continue;
1088 const runId =
1089 entry.kind === "message"
1090 ? entry.message.runId
1091 : entry.entry.itemType === "notification"
1092 ? entry.entry.runId
1093 : null;
1094 if (runId == null) continue;
1095 if (!targetByRunId.has(runId)) {
1096 targetByRunId.set(
1097 runId,
1098 previousRunId === null
1099 ? input.threadStartCheckpointReady
1100 ? 0
1101 : undefined
1102 : readyTurnCountByRunId.get(previousRunId),
1103 );
1104 previousRunId = runId;
1106 if (entry.kind !== "message") continue;
1107 const { message } = entry;
1108 if (message.role !== "user" || message.runId === input.unsettledRunId) continue;
1109 if (message.inputIntent !== "turn_start" && message.inputIntent !== "queued_turn") continue;
1110 const target = targetByRunId.get(runId);
1111 if (
1112 target !== undefined &&
1113 (input.availableRevertTurnCounts === undefined || input.availableRevertTurnCounts.has(target))
1115 byUserMessageId.set(message.id, target);
1117 return byUserMessageId;
1119​
1120export function findRevertCheckpoint(
1121 checkpoints: ReadonlyArray<OrchestrationV2Checkpoint>,
1122 turnCount: number,
1123): OrchestrationV2Checkpoint | undefined {
1124 return checkpoints.findLast(
1125 (checkpoint) =>
1126 checkpoint.status === "ready" &&
1127 (turnCount === 0
1128 ? checkpoint.ordinalWithinScope === 0 && checkpoint.appRunOrdinal === null
1129 : checkpoint.appRunOrdinal === turnCount),
1130 );
1132​
1133export function derivePhase(runtime: ThreadStructureRuntime | null): SessionPhase {
1134 if (runtime === null) return "disconnected";
1135 if (
1136 runtime.status === "preparing" ||
1137 runtime.status === "starting" ||
1138 runtime.status === "queued"
1140 return "connecting";
1141 if (runtime.status === "running" || runtime.status === "waiting") return "running";
1142 return "ready";
1144​
1145/** Preparing and starting runs can be interrupted; Stop need not wait for running. */
1146export function deriveCanInterruptRunningThread(
1147 hasActiveThread: boolean,
1148 runtime: ThreadStructureRuntime | null,
1149): boolean {
1150 return (
1151 hasActiveThread &&
1152 (derivePhase(runtime) === "running" || threadRuntimeHasInterruptibleRun(runtime))
1153 );
1155​
1156export type { TurnDiffSummary };