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