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

session-logic.ts

841 lines26.8 KB

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;
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 }>;
88​
89export interface TurnPlanEntry {
90 /** Stable per-plan row id (plans rewrite in place; the row must not churn). */
91 readonly id: string;
92 readonly createdAt: string;
93 readonly runId: RunId | null;
94 readonly plan: ActivePlanState;
96​
97export interface LatestProposedPlanState {
98 readonly id: PlanId;
99 readonly createdAt: string;
100 readonly updatedAt: string;
101 readonly runId: RunId | null;
102 readonly planMarkdown: string;
103 readonly status: OrchestrationV2PlanArtifact["status"];
105​
106export type TimelineAttempt = Pick<
107 OrchestrationV2RunAttempt,
108 "id" | "runId" | "attemptOrdinal" | "rootNodeId" | "status"
109>;
110​
111export type TimelineEntry = (
112 | {
113 readonly id: string;
114 readonly kind: "message";
115 readonly createdAt: string;
116 readonly message: ChatMessage;
117 readonly projectedItem?: OrchestrationV2ProjectedTurnItem;
118 }
119 | {
120 readonly id: string;
121 readonly kind: "proposed-plan";
122 readonly createdAt: string;
123 readonly proposedPlan: ProposedPlan;
124 }
125 | {
126 readonly id: string;
127 readonly kind: "work";
128 readonly createdAt: string;
129 readonly entry: WorkLogEntry;
130 }
131 | {
132 readonly id: string;
133 readonly kind: "event";
134 readonly createdAt: string;
135 readonly projectedItem: OrchestrationV2ProjectedTurnItem;
136 }
137 | {
138 readonly id: string;
139 readonly kind: "turn-plan";
140 readonly createdAt: string;
141 readonly turnPlan: TurnPlanEntry;
142 }
143) & {
144 /** V2 identity resolved from the item's execution node, when locally available. */
145 readonly attempt?: TimelineAttempt;
146};
147​
148export function workLogEntryIsToolLike(entry: WorkLogEntry): boolean {
149 return (
150 entry.tone === "tool" ||
151 entry.tone === "thinking" ||
152 entry.tone === "error" ||
153 entry.command !== undefined ||
154 entry.requestKind !== undefined
155 );
157​
158/** Heuristic: providers often emit successful item status while error text lives in `detail` / `command`. */
159function toolDetailTextLooksLikeFailure(text: string): boolean {
160 const t = text.toLowerCase();
161 if (t.includes("file not found")) {
162 return true;
163 }
164 if (t.includes("no files found")) {
165 return true;
166 }
167 if (
168 t.includes("enoent") ||
169 t.includes("no such file or directory") ||
170 t.includes("no such file")
171 ) {
172 return true;
173 }
174 if (t.includes("cannot find path") && t.includes("because it does not exist")) {
175 return true;
176 }
177 if (t.includes("commandnotfoundexception")) {
178 return true;
179 }
180 if (t.includes("is not recognized as the name of a cmdlet")) {
181 return true;
182 }
183 if (t.includes("is not recognized") && t.includes("the term '")) {
184 return true;
185 }
186 if (t.includes("a parameter cannot be found that matches parameter name")) {
187 return true;
188 }
189 if (t.includes("command not found")) {
190 return true;
191 }
192 if (/<exited with exit code\s+[1-9]\d*\s*>/i.test(text)) {
193 return true;
194 }
195 if (/exit(?:ed)? with exit code\s+[1-9]\d*/i.test(text)) {
196 return true;
197 }
198 if (/exit code\s*[:\s]\s*[1-9]\d*\b/i.test(text)) {
199 return true;
200 }
201 return false;
203​
204function workEntryIndicatesToolFailureFromOutput(
205 entry: WorkLogEntry,
206 includeCommand: boolean,
207): boolean {
208 if (entry.tone === "error") {
209 return true;
210 }
211 const ls = entry.toolLifecycleStatus;
212 if (ls === "failed" || ls === "declined") {
213 return true;
214 }
215 if (!workLogEntryIsToolLike(entry)) {
216 return false;
217 }
218 const parts: string[] = [];
219 if (entry.detail) {
220 parts.push(entry.detail);
221 }
222 if (includeCommand && entry.command) {
223 parts.push(entry.command);
224 }
225 const blob = parts.join("\n");
226 if (blob.length === 0) {
227 return false;
228 }
229 return toolDetailTextLooksLikeFailure(blob);
231​
232/** True when a tool failed, including providers that put error output in `command`. */
233export function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean {
234 return workEntryIndicatesToolFailureFromOutput(entry, true);
236​
237/** True when the rendered result indicates failure. The command itself is user intent, not output. */
238export function workEntryDisplayIndicatesToolFailure(entry: WorkLogEntry): boolean {
239 return workEntryIndicatesToolFailureFromOutput(entry, false);
241​
242/** Severe failures keep the red treatment ordinary tool failures lost: provider
243 * runtime errors mean the turn or a core side effect broke, not that a
244 * command exited nonzero. */
245export function workEntrySignalsSevereFailure(entry: WorkLogEntry): boolean {
246 return entry.itemType === "error";
248​
249export function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean {
250 return (
251 workLogEntryIsToolLike(entry) &&
252 !workEntryIndicatesToolFailure(entry) &&
253 entry.toolLifecycleStatus === "completed"
254 );
256​
257export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolean {
258 return (
259 workLogEntryIsToolLike(entry) &&
260 !workEntryIndicatesToolFailure(entry) &&
261 !workEntryIndicatesToolSuccess(entry)
262 );
264​
265export function formatDuration(durationMs: number): string {
266 if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
267 if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
268 if (durationMs < 10_000) {
269 const tenths = Math.round(durationMs / 100) / 10;
270 return tenths >= 10 ? "10s" : `${tenths.toFixed(1)}s`;
271 }
272 if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
273 const minutes = Math.floor(durationMs / 60_000);
274 const seconds = Math.round((durationMs % 60_000) / 1_000);
275 if (seconds === 0) return `${minutes}m`;
276 if (seconds === 60) return `${minutes + 1}m`;
277 return `${minutes}m ${seconds}s`;
279​
280export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
281 if (!endIso) return null;
282 const startedAt = Date.parse(startIso);
283 const endedAt = Date.parse(endIso);
284 if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) return null;
285 return formatDuration(endedAt - startedAt);
287​
288export function isLatestRunSettled(
289 latestRun: Pick<ThreadRunSummary, "runId" | "startedAt" | "completedAt" | "status"> | null,
290 runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId"> | null,
291): boolean {
292 if (latestRun === null) return false;
293 if (
294 latestRun.status === "preparing" ||
295 latestRun.status === "queued" ||
296 latestRun.status === "starting" ||
297 latestRun.status === "running" ||
298 latestRun.status === "waiting"
299 )
300 return false;
301 return runtime?.activeRunId !== latestRun.runId;
303​
304export function deriveActiveWorkStartedAt(
305 latestRun: Pick<ThreadRunSummary, "runId" | "startedAt" | "completedAt" | "status"> | null,
306 runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId"> | null,
307 sendStartedAt: string | null,
308): string | null {
309 if (runtime?.activeRunId !== null && runtime?.activeRunId !== undefined) {
310 return latestRun?.runId === runtime.activeRunId
311 ? (latestRun.startedAt ?? sendStartedAt)
312 : sendStartedAt;
313 }
314 return isLatestRunSettled(latestRun, runtime)
315 ? sendStartedAt
316 : (latestRun?.startedAt ?? sendStartedAt);
318​
319export function derivePendingApprovals(
320 approvals: ReadonlyArray<ThreadPendingApproval>,
321): ThreadPendingApproval[] {
322 return [...approvals].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
324​
325export function derivePendingUserInputs(
326 inputs: ReadonlyArray<ThreadPendingUserInput>,
327): ThreadPendingUserInput[] {
328 return [...inputs].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
330​
331export function deriveActivePlanState(
332 projection: OrchestrationV2ThreadProjection | null,
333 latestRunId: RunId | undefined,
334): ActivePlanState | null {
335 if (projection === null) return null;
336 const plans = projection.plans.filter((plan) => plan.kind === "todo_list");
337 const plan =
338 [...plans].toReversed().find((candidate) => candidate.runId === latestRunId) ??
339 plans.at(-1) ??
340 null;
341 if (plan === null || plan.steps.length === 0) return null;
342 return {
343 createdAt: planItemTime(projection, plan.id),
344 runId: plan.runId,
345 explanation: plan.explanation ?? null,
346 steps: plan.steps.map(({ text, status }) => ({
347 step: text,
348 status: status === "running" ? "inProgress" : status,
349 })),
350 };
352​
353function planItemTime(projection: OrchestrationV2ThreadProjection, planId: PlanId): string {
354 const item = projection.turnItems.findLast(
355 (candidate) =>
356 (candidate.type === "proposed_plan" || candidate.type === "todo_list") &&
357 candidate.planId === planId,
358 );
359 return DateTime.formatIso(item?.updatedAt ?? projection.updatedAt);
361​
362function toLatestProposedPlanState(
363 projection: OrchestrationV2ThreadProjection,
364 plan: Extract<OrchestrationV2PlanArtifact, { readonly kind: "proposed_plan" }>,
365): LatestProposedPlanState {
366 const updatedAt = planItemTime(projection, plan.id);
367 return {
368 id: plan.id,
369 createdAt: updatedAt,
370 updatedAt,
371 runId: plan.runId,
372 planMarkdown: plan.markdown,
373 status: plan.status,
374 };
376​
377export function findLatestProposedPlan(
378 projection: OrchestrationV2ThreadProjection | null,
379 latestRunId: RunId | string | null | undefined,
380): LatestProposedPlanState | null {
381 if (projection === null) return null;
382 const plans = projection.plans.filter((plan) => plan.kind === "proposed_plan");
383 const candidates = latestRunId ? plans.filter((plan) => plan.runId === latestRunId) : plans;
384 const plan = [...(candidates.length > 0 ? candidates : plans)]
385 .toSorted(
386 (left, right) =>
387 planItemTime(projection, left.id).localeCompare(planItemTime(projection, right.id)) ||
388 left.id.localeCompare(right.id),
389 )
390 .at(-1);
391 return plan === undefined ? null : toLatestProposedPlanState(projection, plan);
393​
394export function findSidebarProposedPlan(input: {
395 readonly threads: ReadonlyArray<{
396 readonly id: ThreadId;
397 readonly projection: OrchestrationV2ThreadProjection;
398 }>;
399 readonly latestRun: Pick<ThreadRunSummary, "runId" | "sourcePlanRef"> | null;
400 readonly latestRunSettled: boolean;
401 readonly threadId: ThreadId | string | null | undefined;
402}): LatestProposedPlanState | null {
403 if (!input.latestRunSettled && input.latestRun?.sourcePlanRef !== undefined) {
404 const source = input.latestRun.sourcePlanRef;
405 const sourceProjection = input.threads.find(
406 (thread) => thread.id === source.threadId,
407 )?.projection;
408 const plan = sourceProjection?.plans.find(
409 (candidate) => candidate.kind === "proposed_plan" && candidate.id === source.planId,
410 );
411 if (sourceProjection !== undefined && plan?.kind === "proposed_plan") {
412 return toLatestProposedPlanState(sourceProjection, plan);
413 }
414 }
415 const activeProjection = input.threads.find((thread) => thread.id === input.threadId)?.projection;
416 return findLatestProposedPlan(activeProjection ?? null, input.latestRun?.runId);
418​
419export function hasActionableProposedPlan(plan: LatestProposedPlanState | null): boolean {
420 return plan?.status === "active";
422​
423const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"]["type"]>([
424 "approval_request",
425 "compaction",
426 "fork",
427 "handoff",
428 "run_interrupt_request",
429 "run_interrupt_result",
430 "subagent",
431 "thread_created",
432 "user_input_request",
433]);
434​
435const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
436 "fork",
437 "subagent",
438 "thread_created",
439]);
440​
441export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean {
442 return (
443 entry.kind === "event" && PERSISTENT_RESOURCE_V2_ITEM_TYPES.has(entry.projectedItem.item.type)
444 );
446​
447function projectedItemCreatedAt(row: OrchestrationV2ProjectedTurnItem): string {
448 return DateTime.formatIso(row.item.startedAt ?? row.item.updatedAt);
450​
451function projectedWorkEntryStatus(
452 item: OrchestrationV2TurnItem,
453): NonNullable<WorkLogEntry["toolLifecycleStatus"]> {
454 switch (item.status) {
455 case "pending":
456 case "running":
457 case "waiting":
458 return "inProgress";
459 case "completed":
460 return "completed";
461 case "failed":
462 return "failed";
463 case "cancelled":
464 case "interrupted":
465 return "stopped";
466 }
468​
469function projectedWorkEntryTone(item: OrchestrationV2TurnItem): WorkLogEntry["tone"] {
470 if (item.type === "error") return "info";
471 if (item.type === "reasoning") return "thinking";
472 switch (item.type) {
473 case "command_execution":
474 case "file_change":
475 case "file_search":
476 case "web_search":
477 case "dynamic_tool":
478 case "subagent":
479 return "tool";
480 default:
481 return "info";
482 }
484​
485export function providerErrorPresentation(
486 item: Extract<OrchestrationV2TurnItem, { readonly type: "error" }>,
487): { readonly label: string; readonly detail: string } {
488 if (item.retry === undefined) {
489 return {
490 label: item.title?.trim() || "Provider error",
491 detail: item.failure.message,
492 };
493 }
494 const progress =
495 item.retry.maxAttempts === null
496 ? `${item.retry.attempt}`
497 : `${item.retry.attempt}/${item.retry.maxAttempts}`;
498 const label =
499 item.status === "running"
500 ? `Retrying provider (${progress})`
501 : item.status === "completed"
502 ? `Provider recovered (${progress} retries)`
503 : item.status === "failed"
504 ? `Provider error after ${progress} retries`
505 : `Provider retry stopped (${progress})`;
506 const retryDelay =
507 item.status === "running" && item.retry.retryDelayMs !== null && item.retry.retryDelayMs > 0
508 ? item.retry.retryDelayMs < 1_000
509 ? ` Retrying in ${item.retry.retryDelayMs}ms.`
510 : ` Retrying in ${(item.retry.retryDelayMs / 1_000).toFixed(1).replace(/\.0$/u, "")}s.`
511 : "";
512 return {
513 label,
514 detail: `${item.failure.message}${retryDelay}`,
515 };
517​
518function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry {
519 const { item } = row;
520 const title = item.title?.trim() || null;
521 const common = {
522 id: item.id,
523 createdAt: projectedItemCreatedAt(row),
524 runId: item.runId,
525 tone: projectedWorkEntryTone(item),
526 itemType: item.type,
527 toolLifecycleStatus: projectedWorkEntryStatus(item),
528 structuredPayload: item,
529 projectedItem: row,
530 } as const;
531​
532 switch (item.type) {
533 case "reasoning":
534 return {
535 ...common,
536 label: title ?? "Thinking",
537 ...(item.text ? { detail: item.text } : {}),
538 };
539 case "command_execution":
540 return {
541 ...common,
542 label: title ?? "Ran command",
543 command: item.input,
544 rawCommand: item.input,
545 ...(item.output ? { detail: item.output } : {}),
546 toolTitle: title ?? "Command",
547 toolData: item,
548 };
549 case "file_change": {
550 const detail = item.diffStr ?? item.newStr;
551 return {
552 ...common,
553 label: title ?? `Changed ${item.fileName}`,
554 changedFiles: [item.fileName],
555 ...(detail ? { detail } : {}),
556 toolTitle: title ?? "File change",
557 toolData: item,
558 };
559 }
560 case "file_search":
561 return {
562 ...common,
563 label: title ?? "Searched files",
564 ...(item.pattern ? { detail: item.pattern } : {}),
565 toolTitle: title ?? "File search",
566 toolData: item,
567 };
568 case "web_search":
569 return {
570 ...common,
571 label: title ?? "Searched the web",
572 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
573 toolTitle: title ?? "Web search",
574 toolData: item,
575 };
576 case "checkpoint":
577 return {
578 ...common,
579 label: title ?? "Checkpoint captured",
580 changedFiles: item.files.map((file) => file.path),
581 toolData: item,
582 };
583 case "error": {
584 const presentation = providerErrorPresentation(item);
585 return {
586 ...common,
587 ...presentation,
588 toolData: item,
589 };
590 }
591 case "dynamic_tool":
592 return {
593 ...common,
594 label: title ?? item.toolName ?? "Tool call",
595 toolTitle: title ?? item.toolName ?? "Tool",
596 toolData: { input: item.input, output: item.output },
597 };
598 default:
599 return {
600 ...common,
601 label: title ?? item.type.replaceAll("_", " "),
602 toolData: item,
603 };
604 }
606​
607/**
608 * Builds the web timeline in the exact order committed by `visibleTurnItems`.
609 * Committed rows are presented directly from their projected item. Queued
610 * input is absent by construction until dispatch creates its user turn item.
611 * Persistent client-owned messages are inserted by timestamp without sorting
612 * the canonical sequence. True optimistic sends remain appended afterward.
613 */
614export function deriveTimelineEntriesFromVisibleTurnItems(input: {
615 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
616 readonly optimisticMessages: ReadonlyArray<ChatMessage>;
617 readonly anchoredMessages?: ReadonlyArray<ChatMessage>;
618 readonly attachmentUrlById?: ReadonlyMap<string, string>;
619 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
620 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
621 readonly plans?: ReadonlyArray<OrchestrationV2PlanArtifact>;
622}): TimelineEntry[] {
623 const committedMessageIds = new Set<string>();
624 const entries: TimelineEntry[] = [];
625 const attemptByRootNodeId = new Map(
626 (input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
627 );
628 const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const));
629 const planById = new Map((input.plans ?? []).map((plan) => [plan.id, plan] as const));
630​
631 const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => {
632 if (item.nodeId === null || item.runId === null) return undefined;
633 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
634 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
635 while (nodeId !== null && !visited.has(nodeId)) {
636 visited.add(nodeId);
637 const directAttempt = attemptByRootNodeId.get(nodeId);
638 if (directAttempt?.runId === item.runId) return directAttempt;
639 const node = nodeById.get(nodeId);
640 if (node === undefined) return undefined;
641 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
642 if (rootAttempt?.runId === item.runId) return rootAttempt;
643 nodeId = node.parentNodeId;
644 }
645 return undefined;
646 };
647​
648 for (const row of input.visibleTurnItems) {
649 const { item } = row;
650 if (turnItemIsWorkspacePreparation(item)) continue;
651 const createdAt = projectedItemCreatedAt(row);
652 const attempt = resolveAttempt(item);
653 const attemptMetadata = attempt === undefined ? {} : { attempt };
654 if (item.type === "user_message" || item.type === "assistant_message") {
655 const message: ChatMessage = {
656 id: item.messageId,
657 role: item.type === "user_message" ? "user" : "assistant",
658 text: item.text,
659 ...(item.type === "user_message" && item.attachments.length > 0
660 ? {
661 attachments: item.attachments.map((attachment) => {
662 const previewUrl = input.attachmentUrlById?.get(attachment.id);
663 return previewUrl ? { ...attachment, previewUrl } : attachment;
664 }),
665 }
666 : {}),
667 runId: item.runId,
668 streaming: item.type === "assistant_message" && item.streaming,
669 ...(item.type === "user_message"
670 ? { createdBy: item.createdBy, creationSource: item.creationSource }
671 : {}),
672 createdAt,
673 updatedAt: DateTime.formatIso(item.updatedAt),
674 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
675 };
676 committedMessageIds.add(message.id);
677 entries.push({
678 id: message.id,
679 kind: "message",
680 createdAt,
681 message,
682 projectedItem: row,
683 ...attemptMetadata,
684 });
685 continue;
686 }
687​
688 if (item.type === "proposed_plan") {
689 const plan = planById.get(item.planId);
690 const proposedPlan = {
691 id: item.planId,
692 runId: item.runId,
693 planMarkdown: item.markdown,
694 status: plan?.kind === "proposed_plan" ? plan.status : ("active" as const),
695 createdAt,
696 updatedAt: DateTime.formatIso(item.updatedAt),
697 };
698 entries.push({
699 id: item.id,
700 kind: "proposed-plan",
701 createdAt,
702 proposedPlan,
703 ...attemptMetadata,
704 });
705 continue;
706 }
707​
708 if (item.type === "todo_list") {
709 // One inline plan chip per todo list; the item rewrites in place as
710 // steps progress, so the chip stays anchored where planning began. A
711 // snapshot with no steps means the plan was withdrawn — no chip.
712 const artifact = planById.get(item.planId);
713 const steps = artifact?.kind === "todo_list" ? artifact.steps : item.steps;
714 const explanation =
715 (artifact?.kind === "todo_list" ? artifact.explanation : undefined) ?? item.explanation;
716 if (steps.length === 0) continue;
717 entries.push({
718 id: item.id,
719 kind: "turn-plan",
720 createdAt,
721 turnPlan: {
722 id: `turn-plan:${item.planId}`,
723 createdAt,
724 runId: item.runId,
725 plan: {
726 createdAt,
727 runId: item.runId,
728 explanation: explanation ?? null,
729 steps: steps.map(({ text, status }) => ({
730 step: text,
731 status: status === "running" ? "inProgress" : status,
732 })),
733 },
734 },
735 ...attemptMetadata,
736 });
737 continue;
738 }
739​
740 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
741 entries.push({
742 id: item.id,
743 kind: "event",
744 createdAt,
745 projectedItem: row,
746 ...attemptMetadata,
747 });
748 continue;
749 }
750​
751 entries.push({
752 id: item.id,
753 kind: "work",
754 createdAt,
755 entry: projectedWorkEntry(row),
756 ...attemptMetadata,
757 });
758 }
759​
760 const retainedMessageIds = new Set(committedMessageIds);
761 for (const message of input.anchoredMessages ?? []) {
762 if (retainedMessageIds.has(message.id)) continue;
763 retainedMessageIds.add(message.id);
764 const entry: TimelineEntry = {
765 id: message.id,
766 kind: "message",
767 createdAt: message.createdAt,
768 message,
769 };
770 const insertionIndex = entries.findIndex(
771 (candidate) => candidate.createdAt > message.createdAt,
772 );
773 if (insertionIndex === -1) {
774 entries.push(entry);
775 } else {
776 entries.splice(insertionIndex, 0, entry);
777 }
778 }
779​
780 for (const message of input.optimisticMessages) {
781 if (message.inputIntent !== "queued_turn" && !retainedMessageIds.has(message.id)) {
782 retainedMessageIds.add(message.id);
783 entries.push({
784 id: message.id,
785 kind: "message",
786 createdAt: message.createdAt,
787 message,
788 });
789 }
790 }
791​
792 return entries;
794​
795export function inferCheckpointTurnCountByRunId(
796 summaries: ReadonlyArray<ThreadCheckpointSummary>,
797): Record<string, number> {
798 return Object.fromEntries(
799 summaries.flatMap((summary) =>
800 summary.runId === null ? [] : [[summary.runId, summary.checkpointTurnCount] as const],
801 ),
802 );
804​
805export function deriveRevertTurnCountByUserMessageId(input: {
806 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
807 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
808}): Map<ChatMessage["id"], number> {
809 const readyCheckpointByRunId = new Map<RunId, ThreadCheckpointSummary>();
810 for (const checkpoint of input.checkpoints) {
811 if (checkpoint.status === "ready") {
812 readyCheckpointByRunId.set(checkpoint.runId, checkpoint);
813 }
814 }
815 const byUserMessageId = new Map<ChatMessage["id"], number>();
816 for (const entry of input.timelineEntries) {
817 if (entry.kind !== "message" || entry.message.role !== "user") continue;
818 if (entry.message.inputIntent !== "turn_start" && entry.message.inputIntent !== "queued_turn") {
819 continue;
820 }
821 if (entry.message.runId === null) continue;
822 const checkpoint = readyCheckpointByRunId.get(entry.message.runId);
823 if (checkpoint === undefined) continue;
824 byUserMessageId.set(entry.message.id, Math.max(0, checkpoint.checkpointTurnCount - 1));
825 }
826 return byUserMessageId;
828​
829export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase {
830 if (runtime === null) return "disconnected";
831 if (
832 runtime.status === "preparing" ||
833 runtime.status === "starting" ||
834 runtime.status === "queued"
835 )
836 return "connecting";
837 if (runtime.status === "running" || runtime.status === "waiting") return "running";
838 return "ready";
840​
841export type { TurnDiffSummary };