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

session-logic.ts

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