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

session-logic.ts

652 lines20.7 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";
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;
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 }>;
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"];
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 );
142​
143export function workEntryIndicatesToolFailure(entry: WorkLogEntry): boolean {
144 return (
145 entry.tone === "error" ||
146 entry.toolLifecycleStatus === "failed" ||
147 entry.toolLifecycleStatus === "declined"
148 );
150​
151export function workEntryIndicatesToolSuccess(entry: WorkLogEntry): boolean {
152 return workLogEntryIsToolLike(entry) && entry.toolLifecycleStatus === "completed";
154​
155export function workEntryIndicatesToolNeutralStatus(entry: WorkLogEntry): boolean {
156 return (
157 workLogEntryIsToolLike(entry) &&
158 !workEntryIndicatesToolFailure(entry) &&
159 !workEntryIndicatesToolSuccess(entry)
160 );
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`;
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);
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 === "starting" ||
194 latestRun.status === "running" ||
195 latestRun.status === "waiting"
196 )
197 return false;
198 return runtime?.activeRunId !== latestRun.runId;
200​
201export function deriveActiveWorkStartedAt(
202 latestRun: Pick<ThreadRunSummary, "runId" | "startedAt" | "completedAt" | "status"> | null,
203 runtime: Pick<ThreadRuntimeSummary, "status" | "activeRunId"> | null,
204 sendStartedAt: string | null,
205): string | null {
206 if (runtime?.activeRunId !== null && runtime?.activeRunId !== undefined) {
207 return latestRun?.runId === runtime.activeRunId
208 ? (latestRun.startedAt ?? sendStartedAt)
209 : sendStartedAt;
210 }
211 return isLatestRunSettled(latestRun, runtime)
212 ? sendStartedAt
213 : (latestRun?.startedAt ?? sendStartedAt);
215​
216export function derivePendingApprovals(
217 approvals: ReadonlyArray<ThreadPendingApproval>,
218): ThreadPendingApproval[] {
219 return [...approvals].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
221​
222export function derivePendingUserInputs(
223 inputs: ReadonlyArray<ThreadPendingUserInput>,
224): ThreadPendingUserInput[] {
225 return [...inputs].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
227​
228export function deriveActivePlanState(
229 projection: OrchestrationV2ThreadProjection | null,
230 latestRunId: RunId | undefined,
231): ActivePlanState | null {
232 if (projection === null) return null;
233 const plans = projection.plans.filter((plan) => plan.kind === "todo_list");
234 const plan =
235 [...plans].toReversed().find((candidate) => candidate.runId === latestRunId) ??
236 plans.at(-1) ??
237 null;
238 if (plan === null || plan.steps.length === 0) return null;
239 return {
240 createdAt: planItemTime(projection, plan.id),
241 runId: plan.runId,
242 explanation: plan.explanation ?? null,
243 steps: plan.steps.map(({ text, status }) => ({
244 step: text,
245 status: status === "running" ? "inProgress" : status,
246 })),
247 };
249​
250function planItemTime(projection: OrchestrationV2ThreadProjection, planId: PlanId): string {
251 const item = projection.turnItems.findLast(
252 (candidate) =>
253 (candidate.type === "proposed_plan" || candidate.type === "todo_list") &&
254 candidate.planId === planId,
255 );
256 return DateTime.formatIso(item?.updatedAt ?? projection.updatedAt);
258​
259function toLatestProposedPlanState(
260 projection: OrchestrationV2ThreadProjection,
261 plan: Extract<OrchestrationV2PlanArtifact, { readonly kind: "proposed_plan" }>,
262): LatestProposedPlanState {
263 const updatedAt = planItemTime(projection, plan.id);
264 return {
265 id: plan.id,
266 createdAt: updatedAt,
267 updatedAt,
268 runId: plan.runId,
269 planMarkdown: plan.markdown,
270 status: plan.status,
271 };
273​
274export function findLatestProposedPlan(
275 projection: OrchestrationV2ThreadProjection | null,
276 latestRunId: RunId | string | null | undefined,
277): LatestProposedPlanState | null {
278 if (projection === null) return null;
279 const plans = projection.plans.filter((plan) => plan.kind === "proposed_plan");
280 const candidates = latestRunId ? plans.filter((plan) => plan.runId === latestRunId) : plans;
281 const plan = [...(candidates.length > 0 ? candidates : plans)]
282 .toSorted(
283 (left, right) =>
284 planItemTime(projection, left.id).localeCompare(planItemTime(projection, right.id)) ||
285 left.id.localeCompare(right.id),
286 )
287 .at(-1);
288 return plan === undefined ? null : toLatestProposedPlanState(projection, plan);
290​
291export function findSidebarProposedPlan(input: {
292 readonly threads: ReadonlyArray<{
293 readonly id: ThreadId;
294 readonly projection: OrchestrationV2ThreadProjection;
295 }>;
296 readonly latestRun: Pick<ThreadRunSummary, "runId" | "sourcePlanRef"> | null;
297 readonly latestRunSettled: boolean;
298 readonly threadId: ThreadId | string | null | undefined;
299}): LatestProposedPlanState | null {
300 if (!input.latestRunSettled && input.latestRun?.sourcePlanRef !== undefined) {
301 const source = input.latestRun.sourcePlanRef;
302 const sourceProjection = input.threads.find(
303 (thread) => thread.id === source.threadId,
304 )?.projection;
305 const plan = sourceProjection?.plans.find(
306 (candidate) => candidate.kind === "proposed_plan" && candidate.id === source.planId,
307 );
308 if (sourceProjection !== undefined && plan?.kind === "proposed_plan") {
309 return toLatestProposedPlanState(sourceProjection, plan);
310 }
311 }
312 const activeProjection = input.threads.find((thread) => thread.id === input.threadId)?.projection;
313 return findLatestProposedPlan(activeProjection ?? null, input.latestRun?.runId);
315​
316export function hasActionableProposedPlan(plan: LatestProposedPlanState | null): boolean {
317 return plan?.status === "active";
319​
320const STANDALONE_V2_ITEM_TYPES = new Set<OrchestrationV2ProjectedTurnItem["item"]["type"]>([
321 "approval_request",
322 "compaction",
323 "error",
324 "fork",
325 "handoff",
326 "run_interrupt_request",
327 "run_interrupt_result",
328 "subagent",
329 "thread_created",
330 "user_input_request",
331]);
332​
333const PERSISTENT_RESOURCE_V2_ITEM_TYPES = new Set<OrchestrationV2TurnItem["type"]>([
334 "fork",
335 "subagent",
336 "thread_created",
337]);
338​
339export function timelineEntryIsPersistentResourceCard(entry: TimelineEntry): boolean {
340 return (
341 entry.kind === "event" && PERSISTENT_RESOURCE_V2_ITEM_TYPES.has(entry.projectedItem.item.type)
342 );
344​
345function projectedItemCreatedAt(row: OrchestrationV2ProjectedTurnItem): string {
346 return DateTime.formatIso(row.item.startedAt ?? row.item.updatedAt);
348​
349function projectedWorkEntryStatus(
350 item: OrchestrationV2TurnItem,
351): NonNullable<WorkLogEntry["toolLifecycleStatus"]> {
352 switch (item.status) {
353 case "pending":
354 case "running":
355 case "waiting":
356 return "inProgress";
357 case "completed":
358 return "completed";
359 case "failed":
360 return "failed";
361 case "cancelled":
362 case "interrupted":
363 return "stopped";
364 }
366​
367function projectedWorkEntryTone(item: OrchestrationV2TurnItem): WorkLogEntry["tone"] {
368 if (item.status === "failed") return "error";
369 if (item.type === "reasoning") return "thinking";
370 switch (item.type) {
371 case "command_execution":
372 case "file_change":
373 case "file_search":
374 case "web_search":
375 case "dynamic_tool":
376 case "subagent":
377 return "tool";
378 default:
379 return "info";
380 }
382​
383function projectedWorkEntry(row: OrchestrationV2ProjectedTurnItem): WorkLogEntry {
384 const { item } = row;
385 const title = item.title?.trim() || null;
386 const common = {
387 id: item.id,
388 createdAt: projectedItemCreatedAt(row),
389 runId: item.runId,
390 tone: projectedWorkEntryTone(item),
391 itemType: item.type,
392 toolLifecycleStatus: projectedWorkEntryStatus(item),
393 structuredPayload: item,
394 projectedItem: row,
395 } as const;
396​
397 switch (item.type) {
398 case "reasoning":
399 return {
400 ...common,
401 label: title ?? "Thinking",
402 ...(item.text ? { detail: item.text } : {}),
403 };
404 case "command_execution":
405 return {
406 ...common,
407 label: title ?? "Ran command",
408 command: item.input,
409 rawCommand: item.input,
410 ...(item.output ? { detail: item.output } : {}),
411 toolTitle: title ?? "Command",
412 toolData: item,
413 };
414 case "file_change":
415 return {
416 ...common,
417 label: title ?? `Changed ${item.fileName}`,
418 changedFiles: [item.fileName],
419 ...(item.diffStr ? { detail: item.diffStr } : {}),
420 toolTitle: title ?? "File change",
421 toolData: item,
422 };
423 case "file_search":
424 return {
425 ...common,
426 label: title ?? "Searched files",
427 ...(item.pattern ? { detail: item.pattern } : {}),
428 toolTitle: title ?? "File search",
429 toolData: item,
430 };
431 case "web_search":
432 return {
433 ...common,
434 label: title ?? "Searched the web",
435 ...(item.patterns?.length ? { detail: item.patterns.join(", ") } : {}),
436 toolTitle: title ?? "Web search",
437 toolData: item,
438 };
439 case "checkpoint":
440 return {
441 ...common,
442 label: title ?? "Checkpoint captured",
443 changedFiles: item.files.map((file) => file.path),
444 toolData: item,
445 };
446 case "error":
447 return {
448 ...common,
449 label: title ?? "Provider error",
450 detail: item.failure.message,
451 toolData: item,
452 };
453 case "todo_list": {
454 const completed = item.steps.filter((step) => step.status === "completed").length;
455 return {
456 ...common,
457 label: title ?? "Updated tasks",
458 detail: `${completed}/${item.steps.length} completed`,
459 toolData: item,
460 };
461 }
462 case "dynamic_tool":
463 return {
464 ...common,
465 label: title ?? item.toolName ?? "Tool call",
466 toolTitle: title ?? item.toolName ?? "Tool",
467 toolData: { input: item.input, output: item.output },
468 };
469 default:
470 return {
471 ...common,
472 label: title ?? item.type.replaceAll("_", " "),
473 toolData: item,
474 };
475 }
477​
478/**
479 * Builds the web timeline in the exact order committed by `visibleTurnItems`.
480 * Committed rows are presented directly from their projected item. Optimistic
481 * messages are the only client-owned entries appended to that sequence.
482 */
483export function deriveTimelineEntriesFromVisibleTurnItems(input: {
484 readonly visibleTurnItems: ReadonlyArray<OrchestrationV2ProjectedTurnItem>;
485 readonly optimisticMessages: ReadonlyArray<ChatMessage>;
486 readonly attachmentUrlById?: ReadonlyMap<string, string>;
487 readonly attempts?: ReadonlyArray<OrchestrationV2RunAttempt>;
488 readonly nodes?: ReadonlyArray<OrchestrationV2ExecutionNode>;
489}): TimelineEntry[] {
490 const committedMessageIds = new Set<string>();
491 const entries: TimelineEntry[] = [];
492 const attemptByRootNodeId = new Map(
493 (input.attempts ?? []).map((attempt) => [attempt.rootNodeId, attempt] as const),
494 );
495 const nodeById = new Map((input.nodes ?? []).map((node) => [node.id, node] as const));
496​
497 const resolveAttempt = (item: OrchestrationV2TurnItem): TimelineAttempt | undefined => {
498 if (item.nodeId === null || item.runId === null) return undefined;
499 let nodeId: OrchestrationV2ExecutionNode["id"] | null = item.nodeId;
500 const visited = new Set<OrchestrationV2ExecutionNode["id"]>();
501 while (nodeId !== null && !visited.has(nodeId)) {
502 visited.add(nodeId);
503 const directAttempt = attemptByRootNodeId.get(nodeId);
504 if (directAttempt?.runId === item.runId) return directAttempt;
505 const node = nodeById.get(nodeId);
506 if (node === undefined) return undefined;
507 const rootAttempt = attemptByRootNodeId.get(node.rootNodeId);
508 if (rootAttempt?.runId === item.runId) return rootAttempt;
509 nodeId = node.parentNodeId;
510 }
511 return undefined;
512 };
513​
514 for (const row of input.visibleTurnItems) {
515 const { item } = row;
516 const createdAt = projectedItemCreatedAt(row);
517 const attempt = resolveAttempt(item);
518 const attemptMetadata = attempt === undefined ? {} : { attempt };
519 if (item.type === "user_message" || item.type === "assistant_message") {
520 const message: ChatMessage = {
521 id: item.messageId,
522 role: item.type === "user_message" ? "user" : "assistant",
523 text: item.text,
524 ...(item.type === "user_message" && item.attachments.length > 0
525 ? {
526 attachments: item.attachments.map((attachment) => {
527 const previewUrl = input.attachmentUrlById?.get(attachment.id);
528 return previewUrl ? { ...attachment, previewUrl } : attachment;
529 }),
530 }
531 : {}),
532 runId: item.runId,
533 streaming: item.type === "assistant_message" && item.streaming,
534 ...(item.type === "user_message"
535 ? { createdBy: item.createdBy, creationSource: item.creationSource }
536 : {}),
537 createdAt,
538 updatedAt: DateTime.formatIso(item.updatedAt),
539 ...(item.type === "user_message" ? { inputIntent: item.inputIntent } : {}),
540 };
541 committedMessageIds.add(message.id);
542 entries.push({
543 id: message.id,
544 kind: "message",
545 createdAt,
546 message,
547 projectedItem: row,
548 ...attemptMetadata,
549 });
550 continue;
551 }
552​
553 if (item.type === "proposed_plan") {
554 const proposedPlan = {
555 id: item.planId,
556 runId: item.runId,
557 planMarkdown: item.markdown,
558 status: "active" as const,
559 createdAt,
560 updatedAt: DateTime.formatIso(item.updatedAt),
561 };
562 entries.push({
563 id: item.id,
564 kind: "proposed-plan",
565 createdAt,
566 proposedPlan,
567 ...attemptMetadata,
568 });
569 continue;
570 }
571​
572 if (STANDALONE_V2_ITEM_TYPES.has(item.type)) {
573 entries.push({
574 id: item.id,
575 kind: "event",
576 createdAt,
577 projectedItem: row,
578 ...attemptMetadata,
579 });
580 continue;
581 }
582​
583 entries.push({
584 id: item.id,
585 kind: "work",
586 createdAt,
587 entry: projectedWorkEntry(row),
588 ...attemptMetadata,
589 });
590 }
591​
592 for (const message of input.optimisticMessages) {
593 if (!committedMessageIds.has(message.id)) {
594 entries.push({
595 id: message.id,
596 kind: "message",
597 createdAt: message.createdAt,
598 message,
599 });
600 }
601 }
602​
603 return entries;
605​
606export function inferCheckpointTurnCountByRunId(
607 summaries: ReadonlyArray<ThreadCheckpointSummary>,
608): Record<string, number> {
609 return Object.fromEntries(
610 summaries.flatMap((summary) =>
611 summary.runId === null ? [] : [[summary.runId, summary.checkpointTurnCount] as const],
612 ),
613 );
615​
616export function deriveRevertTurnCountByUserMessageId(input: {
617 readonly timelineEntries: ReadonlyArray<TimelineEntry>;
618 readonly checkpoints: ReadonlyArray<ThreadCheckpointSummary>;
619}): Map<ChatMessage["id"], number> {
620 const readyCheckpointByRunId = new Map<RunId, ThreadCheckpointSummary>();
621 for (const checkpoint of input.checkpoints) {
622 if (checkpoint.status === "ready") {
623 readyCheckpointByRunId.set(checkpoint.runId, checkpoint);
624 }
625 }
626 const byUserMessageId = new Map<ChatMessage["id"], number>();
627 for (const entry of input.timelineEntries) {
628 if (entry.kind !== "message" || entry.message.role !== "user") continue;
629 if (entry.message.inputIntent !== "turn_start" && entry.message.inputIntent !== "queued_turn") {
630 continue;
631 }
632 if (entry.message.runId === null) continue;
633 const checkpoint = readyCheckpointByRunId.get(entry.message.runId);
634 if (checkpoint === undefined) continue;
635 byUserMessageId.set(entry.message.id, Math.max(0, checkpoint.checkpointTurnCount - 1));
636 }
637 return byUserMessageId;
639​
640export function derivePhase(runtime: ThreadRuntimeSummary | null): SessionPhase {
641 if (runtime === null) return "disconnected";
642 if (
643 runtime.status === "preparing" ||
644 runtime.status === "starting" ||
645 runtime.status === "queued"
646 )
647 return "connecting";
648 if (runtime.status === "running" || runtime.status === "waiting") return "running";
649 return "ready";
651​
652export type { TurnDiffSummary };