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

session-logic.ts

1,207 lines40.8 KB

1import type { 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​
242const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"]["type"]>([
243 "fork",
244 "handoff",
245 "run_interrupt_request",
246 "run_interrupt_result",
247 "secret_request",
248 "feedback_request",
249 "link_request",
250 "subagent",
251]);
252​
253const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
254 "fork",
255 "thread_created",
256 // Still answerable after a steer supersedes the attempt that asked.
257 "secret_request",
258 "feedback_request",
259 "link_request",
260]);
261​
262export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean {
263 return (
264 entry.kind === "event" && PERSISTENT_RESOURCE_V2_ITEM_TYPES.has(entry.projectedItem.item.type)
265 );
267​
268function projectedItemCreatedAt(row: OrchestrationV2ProjectedTurnItem): string {
269 return DateTime.formatIso(row.item.startedAt ?? row.item.updatedAt);
271​
272function projectedWorkEntryStatus(
273 item: OrchestrationV2TurnItem,
274): NonNullable<WorkLogEntry["toolLifecycleStatus"]> {
275 switch (item.status) {
276 case "pending":
277 case "running":
278 case "waiting":
279 return "inProgress";
280 case "completed":
281 return "completed";
282 case "idle":
283 return "idle";
284 case "failed":
285 return "failed";
286 case "cancelled":
287 case "interrupted":
288 return "stopped";
289 }
291​
292function projectedWorkEntryTone(item: OrchestrationV2TurnItem): WorkLogEntry["tone"] {
293 if (item.type === "error") return "info";
294 if (item.type === "reasoning") return "thinking";
295 switch (item.type) {
296 case "command_execution":
297 case "file_change":
298 case "file_search":
299 case "web_search":
300 case "dynamic_tool":
301 case "subagent":
302 case "thread_created":
303 case "user_input_request":
304 case "approval_request":
305 return "tool";
306 default:
307 return "info";
308 }
310​
311export function providerErrorPresentation(
312 item: Extract<OrchestrationV2TurnItem, { readonly type: "error" }>,
313 resolve: MessageResolver = m,
314): { readonly label: string; readonly detail: string } {
315 if (item.retry === undefined) {
316 return {
317 label:
318 item.failure.class === "usage_limit"
319 ? resolve(msg("Usage limit reached"))
320 : item.title?.trim() || resolve(msg("Provider error")),
321 detail: item.failure.message,
322 };
323 }
324 const progress =
325 item.retry.maxAttempts === null
326 ? `${item.retry.attempt}`
327 : `${item.retry.attempt}/${item.retry.maxAttempts}`;
328 const counts = { progress, attempt: item.retry.attempt };
329 const label =
330 item.status === "running"
331 ? resolve(msg("Retrying provider ({progress})", { progress }))
332 : item.status === "completed"
333 ? resolve(
334 msg(
335 "{attempt, plural, one {Provider recovered ({progress} retries)} other {Provider recovered ({progress} retries)}}",
336 ),
337 counts,
338 )
339 : item.status === "failed"
340 ? item.failure.class === "usage_limit"
341 ? resolve(
342 msg(
343 "{attempt, plural, one {Usage limit reached after {progress} retries} other {Usage limit reached after {progress} retries}}",
344 ),
345 counts,
346 )
347 : resolve(
348 msg(
349 "{attempt, plural, one {Provider error after {progress} retries} other {Provider error after {progress} retries}}",
350 ),
351 counts,
352 )
353 : resolve(msg("Provider retry stopped ({progress})", { progress }));
354 const retryDelay =
355 item.status === "running" && item.retry.retryDelayMs !== null && item.retry.retryDelayMs > 0
356 ? item.retry.retryDelayMs < 1_000
357 ? ` ${resolve(msg("Retrying in {delay}ms.", { delay: item.retry.retryDelayMs }))}`
358 : ` ${resolve(
359 msg("Retrying in {delay}s.", {
360 delay: (item.retry.retryDelayMs / 1_000).toFixed(1).replace(/\.0$/u, ""),
361 }),
362 )}`
363 : "";
364 return {
365 label,
366 detail: `${item.failure.message}${retryDelay}`,
367 };
369​
370function projectedWorkEntry(
371 row: OrchestrationV2ProjectedTurnItem,
372 resolve: MessageResolver,
373): WorkLogEntry {
374 const { item } = row;
375 const title = item.title?.trim() || null;
376 const common = {
377 id: item.id,
378 createdAt: projectedItemCreatedAt(row),
379 runId: item.runId,
380 tone: projectedWorkEntryTone(item),
381 itemType: item.type,
382 toolLifecycleStatus: projectedWorkEntryStatus(item),
383 structuredPayload: item,
384 projectedItem: row,
385 ...extractToolActivityPresentation(item),
386 } as const;
387​
388 switch (item.type) {
389 case "thread_created":
390 return {
391 ...common,
392 label: resolve(msg("Created thread")),
393 };
394 case "compaction":
395 return {
396 ...common,
397 label: contextCompactionLabel(item, resolve),
398 sourceActivityKind: "context-compaction",
399 ...(item.summary ? { detail: item.summary } : {}),
400 };
401 case "reasoning":
402 return {
403 ...common,
404 label: title ?? resolve(msg("Thinking", { $context: "status of an agent reasoning" })),
405 ...(item.text ? { detail: item.text } : {}),
406 };
407 case "command_execution":
408 return {
409 ...common,
410 label: title ?? resolve(msg("Ran command")),
411 command: item.input,
412 rawCommand: item.input,
413 toolTitle: title ?? resolve(msg("Command", { $context: "noun, a shell command tool" })),
414 toolData: item,
415 };
416 case "file_change": {
417 return {
418 ...common,
419 label:
420 title ??
421 (item.changes !== undefined && item.changes.length > 1
422 ? resolve(
423 msg("{count, plural, one {Changed {count} file} other {Changed {count} files}}"),
424 { count: item.changes.length },
425 )
426 : resolve(msg("Changed {fileName}", { fileName: item.fileName }))),
427 changedFiles: item.changes?.length
428 ? item.changes.map((change) => change.path)
429 : [item.fileName],
430 toolTitle: title ?? resolve(msg("File change", { $context: "noun, a tool title" })),
431 toolData: item,
432 };
433 }
434 case "file_search":
435 return {
436 ...common,
437 label: title ?? formatSearchToolLabel(item, resolve) ?? resolve(msg("Searched files")),
438 ...(item.pattern ? { detail: item.pattern } : {}),
439 toolTitle: title ?? resolve(msg("File search", { $context: "noun, a tool title" })),
440 toolData: item,
441 };
442 case "web_search":
443 return {
444 ...common,
445 label: title ?? resolve(msg("Searched the web")),
446 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
447 toolTitle: title ?? resolve(msg("Web search", { $context: "noun, a tool title" })),
448 toolData: item,
449 };
450 case "checkpoint":
451 return {
452 ...common,
453 label: title ?? resolve(msg("Checkpoint captured")),
454 changedFiles: item.files.map((file) => file.path),
455 toolData: item,
456 };
457 case "system_notice":
458 return {
459 ...common,
460 label: item.message,
461 ...(item.level === "info" ? {} : { sourceActivityKind: "runtime.warning" }),
462 };
463 case "error": {
464 const presentation = providerErrorPresentation(item, resolve);
465 return {
466 ...common,
467 ...presentation,
468 ...(item.failure.class === "usage_limit" && item.status !== "completed"
469 ? { sourceActivityKind: "runtime.warning" }
470 : item.retry === undefined
471 ? { sourceActivityKind: "runtime.error" }
472 : {}),
473 toolData: item,
474 };
475 }
476 case "dynamic_tool": {
477 const classified = classifyToolActivity({
478 itemType: "dynamic_tool_call",
479 data: { toolName: item.toolName ?? undefined, input: item.input },
480 });
481 const [readPath] = collectToolFilePaths({ input: item.input });
482 return {
483 ...common,
484 label:
485 title ??
486 (classified === "read"
487 ? formatReadToolLabel(readPath ?? "", 0, resolve)
488 : classified === "search"
489 ? (formatSearchToolLabel({ input: item.input }, resolve) ??
490 item.toolName ??
491 resolve(msg("Tool call", { $context: "noun" })))
492 : (item.toolName ?? resolve(msg("Tool call", { $context: "noun" })))),
493 toolTitle:
494 title ?? item.toolName ?? resolve(msg("Tool", { $context: "noun, a tool title" })),
495 toolData: { input: item.input, output: item.output },
496 };
497 }
498 case "todo_list": {
499 // Each todo update is a quiet row where the agent wrote it; it opens to every step.
500 const done = item.steps.filter((step) => step.status === "completed").length;
501 const current =
502 item.steps.find((step) => step.status === "running") ??
503 item.steps.find((step) => step.status === "pending");
504 return {
505 ...common,
506 label: current
507 ? resolve(msg("Tasks {done}/{total} · {current}"), {
508 done,
509 total: item.steps.length,
510 current: current.text,
511 })
512 : resolve(msg("Tasks {done}/{total}"), { done, total: item.steps.length }),
513 };
514 }
515 case "approval_request":
516 return {
517 ...common,
518 label: title ?? resolve(msg("Approval requested")),
519 detail: item.prompt ?? item.requestKind,
520 toolData: item,
521 };
522 case "user_input_request":
523 return {
524 ...common,
525 label:
526 title ??
527 (item.questionAnswer
528 ? resolve(msg("Answered questions"))
529 : resolve(msg("Input requested"))),
530 ...(item.questionAnswer ? { questionAnswer: item.questionAnswer } : {}),
531 toolData: item,
532 };
533 default:
534 return {
535 ...common,
536 label: title ?? item.type.replaceAll("_", " "),
537 toolData: item,
538 };
539 }
541​
542/** Preserve visibleTurnItems' committed order; interleave client messages by timestamp. */
543export interface TimelineEntriesInput {
544 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
545 readonly optimisticMessages: ReadonlyArray<ChatMessage>;
546 readonly anchoredMessages?: ReadonlyArray<ChatMessage>;
547 readonly attachmentUrlById?: ReadonlyMap<string, string>;
548 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
549 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
550 readonly plans?: ReadonlyArray<OrchestrationV2PlanArtifact>;
551 readonly resolve?: MessageResolver;
553​
554export interface TimelineEntriesProjection {
555 readonly input: TimelineEntriesInput;
556 readonly entries: TimelineEntry[];
558​
559export function deriveTimelineEntriesFromVisibleTurnItems(
560 input: TimelineEntriesInput,
561): TimelineEntry[] {
562 const committedMessageIds = new Set<string>();
563 const entries: TimelineEntry[] = [];
564 const attemptByRootNodeId = new Map(
565 (input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
566 );
567 const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const));
568 const planById = new Map((input.plans ?? []).map((plan) => [plan.id, plan] as const));
569​
570 const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => {
571 if (item.nodeId === null || item.runId === null) return undefined;
572 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
573 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
574 while (nodeId !== null && !visited.has(nodeId)) {
575 visited.add(nodeId);
576 const directAttempt = attemptByRootNodeId.get(nodeId);
577 if (directAttempt?.runId === item.runId) return directAttempt;
578 const node = nodeById.get(nodeId);
579 if (node === undefined) return undefined;
580 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
581 if (rootAttempt?.runId === item.runId) return rootAttempt;
582 nodeId = node.parentNodeId;
583 }
584 return undefined;
585 };
586​
587 // An answer that started a later run stays a normal message at that run's position.
588 const foldedAnswerRunIdByMessageId = new Map<string, OrchestrationV2TurnItem["runId"]>(
589 input.visibleTurnItems.flatMap(({ item }) =>
590 item.type === "user_input_request" && item.questionAnswer
591 ? [[`async-answer:${item.questionAnswer.requestId}`, item.runId] as const]
592 : [],
593 ),
594 );
595 for (const row of input.visibleTurnItems) {
596 const { item } = row;
597 if (turnItemIsWorkspacePreparation(item) && !item.deferredWork) continue;
598 if (item.type === "checkpoint") continue;
599 if (
600 item.type === "user_message" &&
601 item.inputIntent === "queued_turn" &&
602 item.status === "pending"
603 )
604 continue;
605 if (
606 item.type === "user_message" &&
607 foldedAnswerRunIdByMessageId.get(item.messageId) === item.runId
608 )
609 continue;
610 const createdAt = projectedItemCreatedAt(row);
611 const attempt = resolveAttempt(item);
612 const attemptMetadata = attempt === undefined ? {} : { attempt };
613 if (item.type === "notification") {
614 entries.push({
615 id: item.id,
616 kind: "work",
617 createdAt,
618 entry: {
619 id: item.id,
620 createdAt,
621 runId: item.runId,
622 label: item.summary,
623 tone: "info",
624 itemType: item.type,
625 structuredPayload: item,
626 projectedItem: row,
627 },
628 ...attemptMetadata,
629 });
630 continue;
631 }
632 if (item.type === "user_message" || item.type === "assistant_message") {
633 const message: ChatMessage = {
634 id: item.messageId,
635 role: item.type === "user_message" ? "user" : "assistant",
636 text: item.text,
637 ...(item.type === "user_message" && item.context ? { context: item.context } : {}),
638 ...((item.attachments?.length ?? 0) > 0
639 ? {
640 attachments: (item.attachments ?? []).map((attachment) => {
641 const previewUrl = input.attachmentUrlById?.get(attachment.id);
642 return previewUrl ? { ...attachment, previewUrl } : attachment;
643 }),
644 }
645 : {}),
646 runId: item.runId,
647 streaming: item.type === "assistant_message" && item.streaming,
648 ...(item.type === "user_message"
649 ? {
650 createdBy: item.createdBy,
651 creationSource: item.creationSource,
652 ...(item.senderThreadId !== undefined ? { senderThreadId: item.senderThreadId } : {}),
653 ...(item.linkedSender !== undefined ? { linkedSender: item.linkedSender } : {}),
654 ...(item.idleCompaction !== undefined ? { idleCompaction: item.idleCompaction } : {}),
655 ...(item.scheduledTaskId !== undefined
656 ? { scheduledTaskId: item.scheduledTaskId }
657 : {}),
658 }
659 : {}),
660 createdAt,
661 updatedAt: DateTime.formatIso(item.updatedAt),
662 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
663 };
664 committedMessageIds.add(message.id);
665 entries.push({
666 id: message.id,
667 kind: "message",
668 createdAt,
669 message,
670 projectedItem: row,
671 ...attemptMetadata,
672 });
673 continue;
674 }
675​
676 if (item.type === "proposed_plan") {
677 const plan = planById.get(item.planId);
678 const proposedPlan = {
679 id: item.planId,
680 runId: item.runId,
681 planMarkdown: item.markdown,
682 status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
683 createdAt,
684 updatedAt: DateTime.formatIso(item.updatedAt),
685 };
686 entries.push({
687 id: item.id,
688 kind: "proposed-plan",
689 createdAt,
690 proposedPlan,
691 ...attemptMetadata,
692 });
693 continue;
694 }
695​
696 const htmlRender =
697 item.type === "dynamic_tool" && item.status === "completed"
698 ? htmlRenderFromToolItem(item)
699 : undefined;
700 if (htmlRender !== undefined) {
701 entries.push({
702 id: item.id,
703 kind: "html-render",
704 createdAt,
705 runId: item.runId,
706 htmlRender,
707 ...attemptMetadata,
708 });
709 continue;
710 }
711​
712 const sentMessage =
713 item.type === "dynamic_tool" && item.status === "completed"
714 ? sentMessageFromToolItem(item)
715 : undefined;
716 if (sentMessage !== undefined) {
717 entries.push({
718 id: item.id,
719 kind: "sent-message",
720 createdAt,
721 runId: item.runId,
722 text: sentMessage,
723 ...attemptMetadata,
724 });
725 continue;
726 }
727​
728 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
729 entries.push({
730 id: item.id,
731 kind: "event",
732 createdAt,
733 projectedItem: row,
734 ...attemptMetadata,
735 });
736 continue;
737 }
738​
739 entries.push({
740 id: item.id,
741 kind: "work",
742 createdAt,
743 entry: projectedWorkEntry(row, input.resolve ?? m),
744 ...attemptMetadata,
745 });
746​
747 const mcpApp = item.type === "dynamic_tool" ? mcpAppFromToolItem(item) : undefined;
748 if (mcpApp !== undefined) {
749 entries.push({
750 id: `mcp-app:${item.id}`,
751 kind: "mcp-app",
752 createdAt,
753 runId: item.runId,
754 sourceThreadId: row.sourceThreadId,
755 itemId: row.sourceItemId,
756 revision: turnItemDetailRevision(item),
757 mcpApp,
758 ...attemptMetadata,
759 });
760 }
761 }
762​
763 const retainedMessageIds = new Set([
764 ...committedMessageIds,
765 ...foldedAnswerRunIdByMessageId.keys(),
766 ]);
767 for (const message of input.anchoredMessages ?? []) {
768 if (retainedMessageIds.has(message.id)) continue;
769 retainedMessageIds.add(message.id);
770 const entry: TimelineEntry = {
771 id: message.id,
772 kind: "message",
773 createdAt: message.createdAt,
774 message,
775 };
776 const insertionIndex = entries.findIndex(
777 (candidate) => candidate.createdAt > message.createdAt,
778 );
779 if (insertionIndex === -1) {
780 entries.push(entry);
781 } else {
782 entries.splice(insertionIndex, 0, entry);
783 }
784 }
785​
786 for (const message of input.optimisticMessages) {
787 if (message.inputIntent !== "queued_turn" && !retainedMessageIds.has(message.id)) {
788 retainedMessageIds.add(message.id);
789 entries.push({
790 id: message.id,
791 kind: "message",
792 createdAt: message.createdAt,
793 message,
794 });
795 }
796 }
797​
798 return entries;
800​
801type AttachmentResource = Extract<AssetResource, { readonly _tag: "attachment" }>;
802const EMPTY_IMAGE_RESOURCES = Object.freeze<ReadonlyArray<AttachmentResource>>([]);
803​
804export function selectMessageImageResources(
805 attachments: ChatMessage["attachments"],
806): ReadonlyArray<AttachmentResource> {
807 const attachmentIds = new Set<string>();
808 for (const attachment of attachments ?? []) {
809 if (!isImageAttachment(attachment)) continue;
810 const previewUrl = attachment.previewUrl;
811 if (previewUrl?.startsWith("blob:") || previewUrl?.startsWith("data:")) continue;
812 attachmentIds.add(attachment.id);
813 }
814 return attachmentIds.size === 0
815 ? EMPTY_IMAGE_RESOURCES
816 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
818​
819export function selectHandoffImageResources(
820 messages: ReadonlyArray<Pick<ChatMessage, "id" | "role" | "attachments">> | undefined,
821 handoffs: Readonly<Record<string, ReadonlyArray<string>>>,
822): ReadonlyArray<AttachmentResource> {
823 if (Object.keys(handoffs).length === 0) return EMPTY_IMAGE_RESOURCES;
824 const attachmentIds = new Set<string>();
825 for (const message of messages ?? []) {
826 if (message.role !== "user" || !handoffs[message.id]?.length) continue;
827 for (const attachment of message.attachments ?? []) {
828 if (isImageAttachment(attachment)) attachmentIds.add(attachment.id);
829 }
830 }
831 return attachmentIds.size === 0
832 ? EMPTY_IMAGE_RESOURCES
833 : Array.from(attachmentIds, (attachmentId) => ({ _tag: "attachment", attachmentId }));
835​
836export function createMessageAttachmentPreviewProjector() {
837 const attachmentsBySource = new WeakMap<
838 ReadonlyArray<ChatAttachment>,
839 ReadonlyArray<ChatAttachment>
840 >();
841 const messagesBySource = new WeakMap<ChatMessage, ChatMessage>();
842 return (
843 message: ChatMessage,
844 previewUrlFor: (attachment: ChatAttachment) => string | undefined,
845 ): ChatMessage => {
846 const source = message.attachments;
847 if (!source || source.length === 0) return message;
848 const previous = attachmentsBySource.get(source) ?? source;
849 let changed: ChatAttachment[] | undefined;
850 let hasOverrides = false;
851 for (const [index, attachment] of source.entries()) {
852 const previewUrl = previewUrlFor(attachment);
853 const sourceUrl = "previewUrl" in attachment ? attachment.previewUrl : undefined;
854 const previousAttachment = previous[index]!;
855 const previousUrl =
856 "previewUrl" in previousAttachment ? previousAttachment.previewUrl : undefined;
857 const next =
858 !previewUrl || previewUrl === sourceUrl
859 ? attachment
860 : previewUrl === previousUrl
861 ? previousAttachment
862 : { ...attachment, previewUrl };
863 hasOverrides ||= next !== attachment;
864 if (next !== previousAttachment) {
865 changed ??= previous.slice();
866 changed[index] = next;
867 }
868 }
869 const attachments = hasOverrides ? (changed ?? previous) : source;
870 attachmentsBySource.set(source, attachments);
871 if (attachments === source) {
872 messagesBySource.delete(message);
873 return message;
874 }
875 const previousMessage = messagesBySource.get(message);
876 if (previousMessage?.attachments === attachments) return previousMessage;
877 const result = { ...message, attachments };
878 messagesBySource.set(message, result);
879 return result;
880 };
882​
883export function isStreamingMessageTextUpdate(previous: ChatMessage, next: ChatMessage): boolean {
884 if (
885 previous.role !== "assistant" ||
886 next.role !== "assistant" ||
887 !previous.streaming ||
888 !next.streaming
889 ) {
890 return false;
891 }
892 const { text: _previousText, updatedAt: _previousUpdatedAt, ...previousMetadata } = previous;
893 const { text: _nextText, updatedAt: _nextUpdatedAt, ...nextMetadata } = next;
894 return shallow(previousMetadata, nextMetadata);
896​
897function streamedTextMetadata(item: OrchestrationV2TurnItem) {
898 if (item.type === "proposed_plan" && item.streaming) {
899 const { markdown: _markdown, updatedAt: _updatedAt, ...metadata } = item;
900 return metadata;
901 }
902 if ((item.type === "assistant_message" || item.type === "reasoning") && item.streaming) {
903 const { text: _text, updatedAt: _updatedAt, ...metadata } = item;
904 return metadata;
905 }
906 return null;
908​
909export function isStreamingTurnItemTextUpdate(
910 previous: OrchestrationV2ProjectedTurnItem,
911 next: OrchestrationV2ProjectedTurnItem,
912): boolean {
913 const { item: previousItem, ...previousSource } = previous;
914 const { item: nextItem, ...nextSource } = next;
915 const previousMetadata = streamedTextMetadata(previousItem);
916 const nextMetadata = streamedTextMetadata(nextItem);
917 if (
918 previousMetadata === null ||
919 nextMetadata === null ||
920 !shallow(previousSource, nextSource) ||
921 projectedItemCreatedAt(previous) !== projectedItemCreatedAt(next)
922 ) {
923 return false;
924 }
925 // Wire decoding recreates timestamps and attachments; compare only the changed item's metadata.
926 return Equal.equals(previousMetadata, nextMetadata);
928​
929/**
930 * A changed tool or work item maps to exactly one entry with the item's id.
931 * Messages and question answers take part in cross-entry dedupe, and anchored
932 * messages are placed by createdAt, so those changes rebuild.
933 */
934function canRederiveInPlace(
935 input: TimelineEntriesInput,
936 previousItem: OrchestrationV2ProjectedTurnItem,
937 item: OrchestrationV2ProjectedTurnItem,
938): boolean {
939 return (
940 item.item.id === previousItem.item.id &&
941 item.item.type === previousItem.item.type &&
942 item.item.type !== "user_message" &&
943 item.item.type !== "assistant_message" &&
944 item.item.type !== "user_input_request" &&
945 // An app call projects two entries; in-place reuse replaces one.
946 (previousItem.item.type !== "dynamic_tool" ||
947 mcpAppFromToolItem(previousItem.item) === undefined) &&
948 ((input.anchoredMessages?.length ?? 0) === 0 ||
949 projectedItemCreatedAt(item) === projectedItemCreatedAt(previousItem))
950 );
952​
953/** Entries read only each plan's status; streaming plans rebuild artifacts with every delta. */
954function samePlanStatuses(
955 next: TimelineEntriesInput["plans"],
956 previous: TimelineEntriesInput["plans"],
957): boolean {
958 if (next === previous) return true;
959 if (next === undefined || previous === undefined || next.length !== previous.length) return false;
960 return next.every((plan, index) => {
961 const before = previous[index]!;
962 return plan.id === before.id && plan.kind === before.kind && plan.status === before.status;
963 });
965​
966function reuseTimelineEntries(
967 input: TimelineEntriesInput,
968 previous: TimelineEntriesProjection,
969): TimelineEntry[] | null {
970 const before = previous.input;
971 if (
972 input.visibleTurnItems.length < before.visibleTurnItems.length ||
973 !shallow(input.optimisticMessages, before.optimisticMessages) ||
974 !shallow(input.anchoredMessages, before.anchoredMessages) ||
975 !shallow(input.attachmentUrlById, before.attachmentUrlById) ||
976 !shallow(input.attempts, before.attempts) ||
977 !shallow(input.nodes, before.nodes) ||
978 !samePlanStatuses(input.plans, before.plans) ||
979 input.resolve !== before.resolve
980 ) {
981 return null;
982 }
983 const appended = input.visibleTurnItems.length > before.visibleTurnItems.length;
984 // Keep full projection until committed items interleave and deduplicate anchored/optimistic messages.
985 if (
986 appended &&
987 (input.optimisticMessages.length > 0 || (input.anchoredMessages?.length ?? 0) > 0)
988 ) {
989 return null;
990 }
991 // Answer rows can replace a message already present in the retained prefix.
992 if (
993 appended &&
994 input.visibleTurnItems
995 .slice(before.visibleTurnItems.length)
996 .some(
997 ({ item }) =>
998 (item.type === "user_input_request" && item.questionAnswer !== undefined) ||
999 (item.type === "user_message" && item.messageId.startsWith("async-answer:")),
1002 return null;
1003 const replacements = new Map<
1004 OrchestrationV2ProjectedTurnItem,
1005 OrchestrationV2ProjectedTurnItem
1006 >();
1007 const changedItems: OrchestrationV2ProjectedTurnItem[] = [];
1008 for (let index = 0; index < before.visibleTurnItems.length; index += 1) {
1009 const previousItem = before.visibleTurnItems[index]!;
1010 const item = input.visibleTurnItems[index]!;
1011 if (item === previousItem) continue;
1012 // Reasoning and plan text re-derive below; only assistant text patches the message.
1013 if (
1014 item.item.type === "assistant_message" &&
1015 isStreamingTurnItemTextUpdate(previousItem, item)
1016 ) {
1017 replacements.set(previousItem, item);
1018 continue;
1020 if (!canRederiveInPlace(input, previousItem, item)) return null;
1021 changedItems.push(item);
1023 // One batch keeps the attempt/node/plan lookups to a single build.
1024 const rederived =
1025 changedItems.length === 0
1026 ? []
1027 : deriveTimelineEntriesFromVisibleTurnItems({
1028 ...input,
1029 visibleTurnItems: changedItems,
1030 optimisticMessages: [],
1031 anchoredMessages: [],
1032 });
1033 if (
1034 rederived.length !== changedItems.length ||
1035 rederived.some((entry, index) => entry.id !== changedItems[index]!.item.id)
1036 ) {
1037 return null;
1039 const rederivedEntries = new Map(rederived.map((entry) => [entry.id, entry]));
1040 if (replacements.size === 0 && rederivedEntries.size === 0 && !appended) {
1041 return previous.entries;
1043 let rederivedCount = 0;
1044 const entries = previous.entries.map((entry): TimelineEntry => {
1045 const rederivedEntry = rederivedEntries.get(entry.id);
1046 if (rederivedEntry !== undefined) {
1047 rederivedCount += 1;
1048 return rederivedEntry;
1050 const row =
1051 entry.kind === "message" && entry.projectedItem !== undefined
1052 ? replacements.get(entry.projectedItem)
1053 : undefined;
1054 if (entry.kind !== "message" || row?.item.type !== "assistant_message") return entry;
1055 return {
1056 ...entry,
1057 projectedItem: row,
1058 message: {
1059 ...entry.message,
1060 text: row.item.text,
1061 updatedAt: DateTime.formatIso(row.item.updatedAt),
1062 },
1063 };
1064 });
1065 if (rederivedCount !== rederivedEntries.size) return null;
1066 if (appended) {
1067 entries.push(
1068 ...deriveTimelineEntriesFromVisibleTurnItems({
1069 ...input,
1070 visibleTurnItems: input.visibleTurnItems.slice(before.visibleTurnItems.length),
1071 }),
1072 );
1074 return entries;
1076​
1077export function deriveTimelineEntriesFromVisibleTurnItemsWithState(
1078 input: TimelineEntriesInput,
1079 previous: TimelineEntriesProjection | null = null,
1080): TimelineEntriesProjection {
1081 const reused = previous === null ? null : reuseTimelineEntries(input, previous);
1082 if (reused !== null) return { input, entries: reused };
1083 const entries = deriveTimelineEntriesFromVisibleTurnItems(input);
1084 if (previous === null || !shallow(input.attachmentUrlById, previous.input.attachmentUrlById)) {
1085 return { input, entries };
1087 const previousMessages = new Map(
1088 previous.entries.flatMap((entry) =>
1089 entry.kind === "message" ? [[entry.id, entry] as const] : [],
1090 ),
1091 );
1092 return {
1093 input,
1094 entries: entries.map((entry) => {
1095 if (entry.kind !== "message" || entry.projectedItem === undefined) return entry;
1096 const before = previousMessages.get(entry.id);
1097 if (before?.projectedItem !== entry.projectedItem) return entry;
1098 return before.attempt === entry.attempt ? before : { ...entry, message: before.message };
1099 }),
1100 };
1102​
1103// Run ordinals keep increasing after a rewind; only visible local runs define predecessors.
1104export function deriveRevertTurnCountByUserMessageId(input: {
1105 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
1106 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
1107 readonly threadStartCheckpointAvailable: boolean;
1108 readonly availableRevertTurnCounts?: ReadonlySet<number> | undefined;
1109 readonly unsettledRunId?: RunId | null;
1110}): Map<ChatMessage["id"], number> {
1111 const turnCountByRunId = new Map<RunId, number>();
1112 for (const checkpoint of input.checkpoints) {
1113 if (isRewindableCheckpoint(checkpoint)) {
1114 turnCountByRunId.set(checkpoint.runId, checkpoint.checkpointTurnCount);
1117 const targetByRunId = new Map<RunId, number | undefined>();
1118 const byUserMessageId = new Map<ChatMessage["id"], number>();
1119 let previousRunId: RunId | null = null;
1120 for (const entry of input.timelineEntries) {
1121 // Inherited history belongs to the source thread, not our checkpoint scope.
1122 if (entry.kind !== "message" && entry.kind !== "work") continue;
1123 const projectedItem =
1124 entry.kind === "message" ? entry.projectedItem : entry.entry.projectedItem;
1125 if (projectedItem?.visibility === "inherited") continue;
1126 const runId =
1127 entry.kind === "message"
1128 ? entry.message.runId
1129 : entry.entry.itemType === "notification"
1130 ? entry.entry.runId
1131 : null;
1132 if (runId == null) continue;
1133 if (!targetByRunId.has(runId)) {
1134 targetByRunId.set(
1135 runId,
1136 previousRunId === null
1137 ? input.threadStartCheckpointAvailable
1138 ? 0
1139 : undefined
1140 : turnCountByRunId.get(previousRunId),
1141 );
1142 previousRunId = runId;
1144 if (entry.kind !== "message") continue;
1145 const { message } = entry;
1146 if (message.role !== "user" || message.runId === input.unsettledRunId) continue;
1147 if (message.inputIntent !== "turn_start" && message.inputIntent !== "queued_turn") continue;
1148 const target = targetByRunId.get(runId);
1149 if (
1150 target !== undefined &&
1151 (input.availableRevertTurnCounts === undefined || input.availableRevertTurnCounts.has(target))
1153 byUserMessageId.set(message.id, target);
1155 return byUserMessageId;
1157​
1158// A missing or failed snapshot (no git, a side chat, a capture error) still pins a
1159// conversation position; only restoring files needs a ready one.
1160function isRewindableCheckpoint(checkpoint: Pick<OrchestrationV2Checkpoint, "status">) {
1161 return checkpoint.status !== "stale";
1163​
1164export function findRevertCheckpoint(
1165 projection:
1166 | Pick<OrchestrationV2ThreadProjection, "checkpoints" | "checkpointScopes">
1167 | null
1168 | undefined,
1169 turnCount: number,
1170): OrchestrationV2Checkpoint | undefined {
1171 if (projection == null) return undefined;
1172 // A tracked repository's baseline also sits at ordinal zero; it is never a rewind target.
1173 const repositoryScopeIds = repositoryCheckpointScopeIds(projection.checkpointScopes);
1174 return projection.checkpoints.findLast(
1175 (checkpoint) =>
1176 !repositoryScopeIds.has(checkpoint.scopeId) &&
1177 isRewindableCheckpoint(checkpoint) &&
1178 (turnCount === 0
1179 ? checkpoint.ordinalWithinScope === 0 && checkpoint.appRunOrdinal === null
1180 : checkpoint.appRunOrdinal === turnCount),
1181 );
1183​
1184export function derivePhase(runtime: ThreadStructureRuntime | null): SessionPhase {
1185 if (runtime === null) return "disconnected";
1186 if (
1187 runtime.status === "preparing" ||
1188 runtime.status === "starting" ||
1189 runtime.status === "queued"
1191 return "connecting";
1192 if (runtime.status === "running" || runtime.status === "waiting") return "running";
1193 return "ready";
1195​
1196/** Preparing and starting runs can be interrupted; Stop need not wait for running. */
1197export function deriveCanInterruptRunningThread(
1198 hasActiveThread: boolean,
1199 runtime: ThreadStructureRuntime | null,
1200): boolean {
1201 return (
1202 hasActiveThread &&
1203 (derivePhase(runtime) === "running" || threadRuntimeHasInterruptibleRun(runtime))
1204 );
1206​
1207export type { TurnDiffSummary };