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

session-logic.ts

1,262 lines42.9 KB

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