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

session-logic.ts

187 lines5.8 KB

1import {
2 ApprovalRequestId,
3 type OrchestrationThreadActivity,
4 type ProviderKind,
5 type TurnId,
6} from "@t3tools/contracts";
7​
8import type { ChatMessage, SessionPhase, ThreadSession, TurnDiffSummary } from "./types";
9​
10export const PROVIDER_OPTIONS: Array<{
11 value: ProviderKind;
12 label: string;
13 available: boolean;
14}> = [
15 { value: "codex", label: "Codex", available: true },
16 { value: "claudeCode", label: "Claude Code (soon)", available: false },
17];
18​
19export interface WorkLogEntry {
20 id: string;
21 createdAt: string;
22 label: string;
23 detail?: string;
24 tone: "thinking" | "tool" | "info" | "error";
26​
27export interface PendingApproval {
28 requestId: ApprovalRequestId;
29 requestKind: "command" | "file-change";
30 createdAt: string;
31 detail?: string;
33​
34export type TimelineEntry =
35 | {
36 id: string;
37 kind: "message";
38 createdAt: string;
39 message: ChatMessage;
40 }
41 | {
42 id: string;
43 kind: "work";
44 createdAt: string;
45 entry: WorkLogEntry;
46 };
47​
48export function formatTimestamp(isoDate: string): string {
49 return new Intl.DateTimeFormat(undefined, {
50 hour: "numeric",
51 minute: "2-digit",
52 second: "2-digit",
53 }).format(new Date(isoDate));
55​
56export function formatDuration(durationMs: number): string {
57 if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
58 if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
59 if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
60 if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
61 const minutes = Math.floor(durationMs / 60_000);
62 const seconds = Math.round((durationMs % 60_000) / 1_000);
63 if (seconds === 0) return `${minutes}m`;
64 if (seconds === 60) return `${minutes + 1}m`;
65 return `${minutes}m ${seconds}s`;
67​
68export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
69 if (!endIso) return null;
70 const startedAt = Date.parse(startIso);
71 const endedAt = Date.parse(endIso);
72 if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
73 return null;
74 }
75 return formatDuration(endedAt - startedAt);
77​
78export function derivePendingApprovals(
79 activities: ReadonlyArray<OrchestrationThreadActivity>,
80): PendingApproval[] {
81 const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
82 const ordered = [...activities].toSorted((left, right) =>
83 left.createdAt.localeCompare(right.createdAt),
84 );
85​
86 for (const activity of ordered) {
87 const payload =
88 activity.payload && typeof activity.payload === "object"
89 ? (activity.payload as Record<string, unknown>)
90 : null;
91 const requestId =
92 payload && typeof payload.requestId === "string"
93 ? ApprovalRequestId.makeUnsafe(payload.requestId)
94 : null;
95 const requestKind =
96 payload && (payload.requestKind === "command" || payload.requestKind === "file-change")
97 ? payload.requestKind
98 : null;
99 const detail = payload && typeof payload.detail === "string" ? payload.detail : undefined;
100​
101 if (activity.kind === "approval.requested" && requestId && requestKind) {
102 openByRequestId.set(requestId, {
103 requestId,
104 requestKind,
105 createdAt: activity.createdAt,
106 ...(detail ? { detail } : {}),
107 });
108 continue;
109 }
110​
111 if (activity.kind === "approval.resolved" && requestId) {
112 openByRequestId.delete(requestId);
113 }
114 }
115​
116 return [...openByRequestId.values()].toSorted((left, right) =>
117 left.createdAt.localeCompare(right.createdAt),
118 );
120​
121export function deriveWorkLogEntries(
122 activities: ReadonlyArray<OrchestrationThreadActivity>,
123 latestTurnId: TurnId | undefined,
124): WorkLogEntry[] {
125 const ordered = [...activities].toSorted((left, right) =>
126 left.createdAt.localeCompare(right.createdAt),
127 );
128 return ordered
129 .filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true))
130 .filter((activity) => activity.kind !== "tool.started")
131 .filter((activity) => activity.summary !== "Checkpoint captured")
132 .map((activity) => {
133 const payload =
134 activity.payload && typeof activity.payload === "object"
135 ? (activity.payload as Record<string, unknown>)
136 : null;
137 const entry: WorkLogEntry = {
138 id: activity.id,
139 createdAt: activity.createdAt,
140 label: activity.summary,
141 tone: activity.tone === "approval" ? "info" : activity.tone,
142 };
143 if (payload && typeof payload.detail === "string" && payload.detail.length > 0) {
144 entry.detail = payload.detail;
145 }
146 return entry;
147 });
149​
150export function deriveTimelineEntries(
151 messages: ChatMessage[],
152 workEntries: WorkLogEntry[],
153): TimelineEntry[] {
154 const messageRows: TimelineEntry[] = messages.map((message) => ({
155 id: message.id,
156 kind: "message",
157 createdAt: message.createdAt,
158 message,
159 }));
160 const workRows: TimelineEntry[] = workEntries.map((entry) => ({
161 id: entry.id,
162 kind: "work",
163 createdAt: entry.createdAt,
164 entry,
165 }));
166 return [...messageRows, ...workRows].toSorted((a, b) => a.createdAt.localeCompare(b.createdAt));
168​
169export function inferCheckpointTurnCountByTurnId(
170 summaries: TurnDiffSummary[],
171): Record<TurnId, number> {
172 const sorted = [...summaries].toSorted((a, b) => a.completedAt.localeCompare(b.completedAt));
173 const result: Record<TurnId, number> = {};
174 for (let index = 0; index < sorted.length; index += 1) {
175 const summary = sorted[index];
176 if (!summary) continue;
177 result[summary.turnId] = index + 1;
178 }
179 return result;
181​
182export function derivePhase(session: ThreadSession | null): SessionPhase {
183 if (!session || session.status === "closed") return "disconnected";
184 if (session.status === "connecting") return "connecting";
185 if (session.status === "running") return "running";
186 return "ready";