Open History to see the last commit
1import {
2 ProviderDriverKind,
3 type OrchestrationV2ExecutionNode,
4 type OrchestrationV2PlanArtifact,
5 type OrchestrationV2ProjectedTurnItem,
6 type OrchestrationV2RunAttempt,
7 type OrchestrationV2ThreadProjection,
8 type OrchestrationV2TurnItem,
9 type PlanId,
10 type RunId,
11 type ThreadId,
12} from "@t3tools/contracts";
13import type { ThreadCheckpointSummary } from "@t3tools/client-runtime/state/thread-checkpoints";
14import type {
15 ThreadPendingApproval,
16 ThreadPendingUserInput,
17} from "@t3tools/client-runtime/state/thread-requests";
18import type { ThreadRunSummary, ThreadRuntimeSummary } from "@t3tools/client-runtime/state/shell";
19import { turnItemIsWorkspacePreparation } from "@t3tools/client-runtime/state/turn-item-presentation";
20
21import type { ChatMessage, ProposedPlan, SessionPhase, TurnDiffSummary } from "./types";
22import * as DateTime from "effect/DateTime";
23
24export type ProviderPickerKind = ProviderDriverKind;
25
26export const PROVIDER_OPTIONS: Array<{
27 value: ProviderPickerKind;
28 label: string;
29 available: boolean;
30 pickerSidebarBadge?: "new" | "soon";
31}> = [
32 { value: ProviderDriverKind.make("codex"), label: "Codex", available: true },
33 { value: ProviderDriverKind.make("claudeAgent"), label: "Claude", available: true },
34 {
35 value: ProviderDriverKind.make("opencode"),
36 label: "OpenCode",
37 available: true,
38 pickerSidebarBadge: "new",
39 },
40 {
41 value: ProviderDriverKind.make("cursor"),
42 label: "Cursor",
43 available: true,
44 pickerSidebarBadge: "new",
45 },
46 { value: ProviderDriverKind.make("grok"), label: "Grok", available: true },
47];
48
49export type WorkLogToolLifecycleStatus =
50 | "inProgress"
51 | "completed"
52 | "failed"
53 | "declined"
54 | "stopped";
55
56export interface WorkLogEntry {
57 readonly id: string;
58 readonly createdAt: string;
59 readonly runId?: RunId | null;
60 readonly label: string;
61 readonly detail?: string;
62 readonly command?: string;
63 readonly rawCommand?: string;
64 readonly changedFiles?: ReadonlyArray<string>;
65 readonly tone: "thinking" | "tool" | "info" | "error";
66 readonly toolTitle?: string;
67 readonly toolData?: unknown;
68 readonly requestKind?: string;
69 readonly itemType?: OrchestrationV2TurnItem["type"];
70 readonly toolLifecycleStatus?: WorkLogToolLifecycleStatus;
71 readonly structuredPayload?: OrchestrationV2TurnItem;
72 readonly sourceItemType?: OrchestrationV2TurnItem["type"];
73 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
74}
75
76export type PendingApproval = ThreadPendingApproval;
77export type PendingUserInput = ThreadPendingUserInput;
78
79export interface ActivePlanState {
80 readonly createdAt: string;
81 readonly runId: RunId | null;
82 readonly explanation?: string | null;
83 readonly steps: Array<{
84 readonly step: string;
85 readonly status: "pending" | "inProgress" | "completed";
86 }>;
87}
88
89export interface LatestProposedPlanState {
90 readonly id: PlanId;
91 readonly createdAt: string;
92 readonly updatedAt: string;
93 readonly runId: RunId | null;
94 readonly planMarkdown: string;
95 readonly status: OrchestrationV2PlanArtifact["status"];
96}
97
98export type TimelineAttempt = Pick<
99 OrchestrationV2RunAttempt,
100 "id" | "runId" | "attemptOrdinal" | "rootNodeId" | "status"
101>;
102
103export type TimelineEntry = (
104 | {
105 readonly id: string;
106 readonly kind: "message";
107 readonly createdAt: string;
108 readonly message: ChatMessage;
109 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
110 }
111 | {
112 readonly id: string;
113 readonly kind: "proposed-plan";
114 readonly createdAt: string;
115 readonly proposedPlan: ProposedPlan;
116 }
117 | {
118 readonly id: string;
119 readonly kind: "work";
120 readonly createdAt: string;
121 readonly entry: WorkLogEntry;
122 }
123 | {
124 readonly id: string;
125 readonly kind: "event";
126 readonly createdAt: string;
127 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
128 }
129) & {
130 /** V2 identity resolved from the item's execution node, when locally available. */
131 readonly attempt?: TimelineAttempt;
132};
133
134export function workLogEntryIsToolLike(entry: WorkLogEntry): boolean {
135 return (
136 entry.tone === "tool" ||
137 entry.tone === "thinking" ||
138 entry.tone === "error" ||
139 entry.command !== undefined ||
140 entry.requestKind !== undefined
141 );
142}
143
144export function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean {
145 return (
146 entry.tone === "error" ||
147 entry.toolLifecycleStatus === "failed" ||
148 entry.toolLifecycleStatus === "declined"
149 );
150}
151
152export function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean {
153 return workLogEntryIsToolLike(entry) && entry.toolLifecycleStatus === "completed";
154}
155
156export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolean {
157 return (
158 workLogEntryIsToolLike(entry) &&
159 !workEntryIndicatesToolFailure(entry) &&
160 !workEntryIndicatesToolSuccess(entry)
161 );
162}
163
164export function formatDuration(durationMs: number): string {
165 if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
166 if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
167 if (durationMs < 10_000) {
168 const tenths = Math.round(durationMs / 100) / 10;
169 return tenths >= 10 ? "10s" : `${tenths.toFixed(1)}s`;
170 }
171 if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
172 const minutes = Math.floor(durationMs / 60_000);
173 const seconds = Math.round((durationMs % 60_000) / 1_000);
174 if (seconds === 0) return `${minutes}m`;
175 if (seconds === 60) return `${minutes + 1}m`;
176 return `${minutes}m ${seconds}s`;
177}
178
179export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
180 if (!endIso) return null;
181 const startedAt = Date.parse(startIso);
182 const endedAt = Date.parse(endIso);
183 if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) return null;
184 return formatDuration(endedAt - startedAt);
185}
186
187export function isLatestRunSettled(
188 latestRun: Pick<ThreadRunSummary, "runId" | "startedAt" | "completedAt" | "status"> | null,
189 runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId"> | null,
190): boolean {
191 if (latestRun === null) return false;
192 if (
193 latestRun.status === "preparing" ||
194 latestRun.status === "queued" ||
195 latestRun.status === "starting" ||
196 latestRun.status === "running" ||
197 latestRun.status === "waiting"
198 )
199 return false;
200 return runtime?.activeRunId !== latestRun.runId;
201}
202
203export function deriveActiveWorkStartedAt(
204 latestRun: Pick<ThreadRunSummary, "runId" | "startedAt" | "completedAt" | "status"> | null,
205 runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId"> | null,
206 sendStartedAt: string | null,
207): string | null {
208 if (runtime?.activeRunId !== null && runtime?.activeRunId !== undefined) {
209 return latestRun?.runId === runtime.activeRunId
210 ? (latestRun.startedAt ?? sendStartedAt)
211 : sendStartedAt;
212 }
213 return isLatestRunSettled(latestRun, runtime)
214 ? sendStartedAt
215 : (latestRun?.startedAt ?? sendStartedAt);
216}
217
218export function derivePendingApprovals(
219 approvals: ReadonlyArray<ThreadPendingApproval>,
220): ThreadPendingApproval[] {
221 return [...approvals].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
222}
223
224export function derivePendingUserInputs(
225 inputs: ReadonlyArray<ThreadPendingUserInput>,
226): ThreadPendingUserInput[] {
227 return [...inputs].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
228}
229
230export function deriveActivePlanState(
231 projection: OrchestrationV2ThreadProjection | null,
232 latestRunId: RunId | undefined,
233): ActivePlanState | null {
234 if (projection === null) return null;
235 const plans = projection.plans.filter((plan) => plan.kind === "todo_list");
236 const plan =
237 [...plans].toReversed().find((candidate) => candidate.runId === latestRunId) ??
238 plans.at(-1) ??
239 null;
240 if (plan === null || plan.steps.length === 0) return null;
241 return {
242 createdAt: planItemTime(projection, plan.id),
243 runId: plan.runId,
244 explanation: plan.explanation ?? null,
245 steps: plan.steps.map(({ text, status }) => ({
246 step: text,
247 status: status === "running" ? "inProgress" : status,
248 })),
249 };
250}
251
252function planItemTime(projection: OrchestrationV2ThreadProjection, planId: PlanId): string {
253 const item = projection.turnItems.findLast(
254 (candidate) =>
255 (candidate.type === "proposed_plan" || candidate.type === "todo_list") &&
256 candidate.planId === planId,
257 );
258 return DateTime.formatIso(item?.updatedAt ?? projection.updatedAt);
259}
260
261function toLatestProposedPlanState(
262 projection: OrchestrationV2ThreadProjection,
263 plan: Extract<OrchestrationV2PlanArtifact, { readonly kind: "proposed_plan" }>,
264): LatestProposedPlanState {
265 const updatedAt = planItemTime(projection, plan.id);
266 return {
267 id: plan.id,
268 createdAt: updatedAt,
269 updatedAt,
270 runId: plan.runId,
271 planMarkdown: plan.markdown,
272 status: plan.status,
273 };
274}
275
276export function findLatestProposedPlan(
277 projection: OrchestrationV2ThreadProjection | null,
278 latestRunId: RunId | string | null | undefined,
279): LatestProposedPlanState | null {
280 if (projection === null) return null;
281 const plans = projection.plans.filter((plan) => plan.kind === "proposed_plan");
282 const candidates = latestRunId ? plans.filter((plan) => plan.runId === latestRunId) : plans;
283 const plan = [...(candidates.length > 0 ? candidates : plans)]
284 .toSorted(
285 (left, right) =>
286 planItemTime(projection, left.id).localeCompare(planItemTime(projection, right.id)) ||
287 left.id.localeCompare(right.id),
288 )
289 .at(-1);
290 return plan === undefined ? null : toLatestProposedPlanState(projection, plan);
291}
292
293export function findSidebarProposedPlan(input: {
294 readonly threads: ReadonlyArray<{
295 readonly id: ThreadId;
296 readonly projection: OrchestrationV2ThreadProjection;
297 }>;
298 readonly latestRun: Pick<ThreadRunSummary, "runId" | "sourcePlanRef"> | null;
299 readonly latestRunSettled: boolean;
300 readonly threadId: ThreadId | string | null | undefined;
301}): LatestProposedPlanState | null {
302 if (!input.latestRunSettled && input.latestRun?.sourcePlanRef !== undefined) {
303 const source = input.latestRun.sourcePlanRef;
304 const sourceProjection = input.threads.find(
305 (thread) => thread.id === source.threadId,
306 )?.projection;
307 const plan = sourceProjection?.plans.find(
308 (candidate) => candidate.kind === "proposed_plan" && candidate.id === source.planId,
309 );
310 if (sourceProjection !== undefined && plan?.kind === "proposed_plan") {
311 return toLatestProposedPlanState(sourceProjection, plan);
312 }
313 }
314 const activeProjection = input.threads.find((thread) => thread.id === input.threadId)?.projection;
315 return findLatestProposedPlan(activeProjection ?? null, input.latestRun?.runId);
316}
317
318export function hasActionableProposedPlan(plan: LatestProposedPlanState | null): boolean {
319 return plan?.status === "active";
320}
321
322const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"]["type"]>([
323 "approval_request",
324 "compaction",
325 "error",
326 "fork",
327 "handoff",
328 "run_interrupt_request",
329 "run_interrupt_result",
330 "subagent",
331 "thread_created",
332 "user_input_request",
333]);
334
335const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
336 "fork",
337 "subagent",
338 "thread_created",
339]);
340
341export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean {
342 return (
343 entry.kind === "event" && PERSISTENT_RESOURCE_V2_ITEM_TYPES.has(entry.projectedItem.item.type)
344 );
345}
346
347function projectedItemCreatedAt(row: OrchestrationV2ProjectedTurnItem): string {
348 return DateTime.formatIso(row.item.startedAt ?? row.item.updatedAt);
349}
350
351function projectedWorkEntryStatus(
352 item: OrchestrationV2TurnItem,
353): NonNullable<WorkLogEntry["toolLifecycleStatus"]> {
354 switch (item.status) {
355 case "pending":
356 case "running":
357 case "waiting":
358 return "inProgress";
359 case "completed":
360 return "completed";
361 case "failed":
362 return "failed";
363 case "cancelled":
364 case "interrupted":
365 return "stopped";
366 }
367}
368
369function projectedWorkEntryTone(item: OrchestrationV2TurnItem): WorkLogEntry["tone"] {
370 if (item.status === "failed") return "error";
371 if (item.type === "reasoning") return "thinking";
372 switch (item.type) {
373 case "command_execution":
374 case "file_change":
375 case "file_search":
376 case "web_search":
377 case "dynamic_tool":
378 case "subagent":
379 return "tool";
380 default:
381 return "info";
382 }
383}
384
385export function providerErrorPresentation(
386 item: Extract<OrchestrationV2TurnItem, { readonly type: "error" }>,
387): { readonly label: string; readonly detail: string } {
388 if (item.retry === undefined) {
389 return {
390 label: item.title?.trim() || "Provider error",
391 detail: item.failure.message,
392 };
393 }
394 const progress =
395 item.retry.maxAttempts === null
396 ? `${item.retry.attempt}`
397 : `${item.retry.attempt}/${item.retry.maxAttempts}`;
398 const label =
399 item.status === "running"
400 ? `Retrying provider (${progress})`
401 : item.status === "completed"
402 ? `Provider recovered (${progress} retries)`
403 : item.status === "failed"
404 ? `Provider error after ${progress} retries`
405 : `Provider retry stopped (${progress})`;
406 const retryDelay =
407 item.status === "running" && item.retry.retryDelayMs !== null && item.retry.retryDelayMs > 0
408 ? item.retry.retryDelayMs < 1_000
409 ? ` Retrying in ${item.retry.retryDelayMs}ms.`
410 : ` Retrying in ${(item.retry.retryDelayMs / 1_000).toFixed(1).replace(/\.0$/u, "")}s.`
411 : "";
412 return {
413 label,
414 detail: `${item.failure.message}${retryDelay}`,
415 };
416}
417
418function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry {
419 const { item } = row;
420 const title = item.title?.trim() || null;
421 const common = {
422 id: item.id,
423 createdAt: projectedItemCreatedAt(row),
424 runId: item.runId,
425 tone: projectedWorkEntryTone(item),
426 itemType: item.type,
427 toolLifecycleStatus: projectedWorkEntryStatus(item),
428 structuredPayload: item,
429 projectedItem: row,
430 } as const;
431
432 switch (item.type) {
433 case "reasoning":
434 return {
435 ...common,
436 label: title ?? "Thinking",
437 ...(item.text ? { detail: item.text } : {}),
438 };
439 case "command_execution":
440 return {
441 ...common,
442 label: title ?? "Ran command",
443 command: item.input,
444 rawCommand: item.input,
445 ...(item.output ? { detail: item.output } : {}),
446 toolTitle: title ?? "Command",
447 toolData: item,
448 };
449 case "file_change": {
450 const detail = item.diffStr ?? item.newStr;
451 return {
452 ...common,
453 label: title ?? `Changed ${item.fileName}`,
454 changedFiles: [item.fileName],
455 ...(detail ? { detail } : {}),
456 toolTitle: title ?? "File change",
457 toolData: item,
458 };
459 }
460 case "file_search":
461 return {
462 ...common,
463 label: title ?? "Searched files",
464 ...(item.pattern ? { detail: item.pattern } : {}),
465 toolTitle: title ?? "File search",
466 toolData: item,
467 };
468 case "web_search":
469 return {
470 ...common,
471 label: title ?? "Searched the web",
472 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
473 toolTitle: title ?? "Web search",
474 toolData: item,
475 };
476 case "checkpoint":
477 return {
478 ...common,
479 label: title ?? "Checkpoint captured",
480 changedFiles: item.files.map((file) => file.path),
481 toolData: item,
482 };
483 case "error": {
484 const presentation = providerErrorPresentation(item);
485 return {
486 ...common,
487 ...presentation,
488 toolData: item,
489 };
490 }
491 case "todo_list": {
492 const completed = item.steps.filter((step) => step.status === "completed").length;
493 return {
494 ...common,
495 label: title ?? "Updated tasks",
496 detail: `${completed}/${item.steps.length} completed`,
497 toolData: item,
498 };
499 }
500 case "dynamic_tool":
501 return {
502 ...common,
503 label: title ?? item.toolName ?? "Tool call",
504 toolTitle: title ?? item.toolName ?? "Tool",
505 toolData: { input: item.input, output: item.output },
506 };
507 default:
508 return {
509 ...common,
510 label: title ?? item.type.replaceAll("_", " "),
511 toolData: item,
512 };
513 }
514}
515
516/**
517 * Builds the web timeline in the exact order committed by `visibleTurnItems`.
518 * Committed rows are presented directly from their projected item. Queued
519 * input is absent by construction until dispatch creates its user turn item.
520 * Optimistic messages are the only client-owned entries appended afterward.
521 */
522export function deriveTimelineEntriesFromVisibleTurnItems(input: {
523 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
524 readonly optimisticMessages: ReadonlyArray<ChatMessage>;
525 readonly attachmentUrlById?: ReadonlyMap<string, string>;
526 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
527 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
528 readonly plans?: ReadonlyArray<OrchestrationV2PlanArtifact>;
529}): TimelineEntry[] {
530 const committedMessageIds = new Set<string>();
531 const entries: TimelineEntry[] = [];
532 const attemptByRootNodeId = new Map(
533 (input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
534 );
535 const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const));
536 const planById = new Map((input.plans ?? []).map((plan) => [plan.id, plan] as const));
537
538 const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => {
539 if (item.nodeId === null || item.runId === null) return undefined;
540 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
541 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
542 while (nodeId !== null && !visited.has(nodeId)) {
543 visited.add(nodeId);
544 const directAttempt = attemptByRootNodeId.get(nodeId);
545 if (directAttempt?.runId === item.runId) return directAttempt;
546 const node = nodeById.get(nodeId);
547 if (node === undefined) return undefined;
548 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
549 if (rootAttempt?.runId === item.runId) return rootAttempt;
550 nodeId = node.parentNodeId;
551 }
552 return undefined;
553 };
554
555 for (const row of input.visibleTurnItems) {
556 const { item } = row;
557 if (turnItemIsWorkspacePreparation(item)) continue;
558 const createdAt = projectedItemCreatedAt(row);
559 const attempt = resolveAttempt(item);
560 const attemptMetadata = attempt === undefined ? {} : { attempt };
561 if (item.type === "user_message" || item.type === "assistant_message") {
562 const message: ChatMessage = {
563 id: item.messageId,
564 role: item.type === "user_message" ? "user" : "assistant",
565 text: item.text,
566 ...(item.type === "user_message" && item.attachments.length > 0
567 ? {
568 attachments: item.attachments.map((attachment) => {
569 const previewUrl = input.attachmentUrlById?.get(attachment.id);
570 return previewUrl ? { ...attachment, previewUrl } : attachment;
571 }),
572 }
573 : {}),
574 runId: item.runId,
575 streaming: item.type === "assistant_message" && item.streaming,
576 ...(item.type === "user_message"
577 ? { createdBy: item.createdBy, creationSource: item.creationSource }
578 : {}),
579 createdAt,
580 updatedAt: DateTime.formatIso(item.updatedAt),
581 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
582 };
583 committedMessageIds.add(message.id);
584 entries.push({
585 id: message.id,
586 kind: "message",
587 createdAt,
588 message,
589 projectedItem: row,
590 ...attemptMetadata,
591 });
592 continue;
593 }
594
595 if (item.type === "proposed_plan") {
596 const plan = planById.get(item.planId);
597 const proposedPlan = {
598 id: item.planId,
599 runId: item.runId,
600 planMarkdown: item.markdown,
601 status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
602 createdAt,
603 updatedAt: DateTime.formatIso(item.updatedAt),
604 };
605 entries.push({
606 id: item.id,
607 kind: "proposed-plan",
608 createdAt,
609 proposedPlan,
610 ...attemptMetadata,
611 });
612 continue;
613 }
614
615 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
616 entries.push({
617 id: item.id,
618 kind: "event",
619 createdAt,
620 projectedItem: row,
621 ...attemptMetadata,
622 });
623 continue;
624 }
625
626 entries.push({
627 id: item.id,
628 kind: "work",
629 createdAt,
630 entry: projectedWorkEntry(row),
631 ...attemptMetadata,
632 });
633 }
634
635 for (const message of input.optimisticMessages) {
636 if (message.inputIntent !== "queued_turn" && !committedMessageIds.has(message.id)) {
637 entries.push({
638 id: message.id,
639 kind: "message",
640 createdAt: message.createdAt,
641 message,
642 });
643 }
644 }
645
646 return entries;
647}
648
649export function inferCheckpointTurnCountByRunId(
650 summaries: ReadonlyArray<ThreadCheckpointSummary>,
651): Record<string, number> {
652 return Object.fromEntries(
653 summaries.flatMap((summary) =>
654 summary.runId === null ? [] : [[summary.runId, summary.checkpointTurnCount] as const],
655 ),
656 );
657}
658
659export function deriveRevertTurnCountByUserMessageId(input: {
660 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
661 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
662}): Map<ChatMessage["id"], number> {
663 const readyCheckpointByRunId = new Map<RunId, ThreadCheckpointSummary>();
664 for (const checkpoint of input.checkpoints) {
665 if (checkpoint.status === "ready") {
666 readyCheckpointByRunId.set(checkpoint.runId, checkpoint);
667 }
668 }
669 const byUserMessageId = new Map<ChatMessage["id"], number>();
670 for (const entry of input.timelineEntries) {
671 if (entry.kind !== "message" || entry.message.role !== "user") continue;
672 if (entry.message.inputIntent !== "turn_start" && entry.message.inputIntent !== "queued_turn") {
673 continue;
674 }
675 if (entry.message.runId === null) continue;
676 const checkpoint = readyCheckpointByRunId.get(entry.message.runId);
677 if (checkpoint === undefined) continue;
678 byUserMessageId.set(entry.message.id, Math.max(0, checkpoint.checkpointTurnCount - 1));
679 }
680 return byUserMessageId;
681}
682
683export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase {
684 if (runtime === null) return "disconnected";
685 if (
686 runtime.status === "preparing" ||
687 runtime.status === "starting" ||
688 runtime.status === "queued"
689 )
690 return "connecting";
691 if (runtime.status === "running" || runtime.status === "waiting") return "running";
692 return "ready";
693}
694
695export type { TurnDiffSummary };