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

session-logic.ts

1,228 lines41.7 KB

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