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

session-logic.ts

579 lines15.2 KB

1import type { ProviderEvent, ProviderKind, ProviderSession } from "@acme/contracts";
2import type { ChatMessage, SessionPhase } from "./types";
3​
4export const PROVIDER_OPTIONS: Array<{
5 value: ProviderKind;
6 label: string;
7 available: boolean;
8}> = [
9 { value: "codex", label: "Codex", available: true },
10 { value: "claudeCode", label: "Claude Code (soon)", available: false },
11];
12​
13export function readNativeApi() {
14 if (typeof window === "undefined") return undefined;
15 return window.nativeApi;
17​
18export function asObject(value: unknown): Record<string, unknown> | undefined {
19 if (!value || typeof value !== "object") return undefined;
20 return value as Record<string, unknown>;
22​
23export function asString(value: unknown): string | undefined {
24 return typeof value === "string" ? value : undefined;
26​
27export function formatTimestamp(isoDate: string): string {
28 return new Intl.DateTimeFormat(undefined, {
29 hour: "numeric",
30 minute: "2-digit",
31 second: "2-digit",
32 }).format(new Date(isoDate));
34​
35export function formatDuration(durationMs: number): string {
36 if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
37 if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
38 if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
39 if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
40​
41 const minutes = Math.floor(durationMs / 60_000);
42 const seconds = Math.round((durationMs % 60_000) / 1_000);
43 if (seconds === 0) return `${minutes}m`;
44 if (seconds === 60) return `${minutes + 1}m`;
45 return `${minutes}m ${seconds}s`;
47​
48export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
49 if (!endIso) return null;
50​
51 const startedAt = Date.parse(startIso);
52 const endedAt = Date.parse(endIso);
53 if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
54 return null;
55 }
56​
57 return formatDuration(endedAt - startedAt);
59​
60export interface WorkLogEntry {
61 id: string;
62 createdAt: string;
63 label: string;
64 detail?: string;
65 tone: "thinking" | "tool" | "info" | "error";
67​
68export type TimelineEntry =
69 | {
70 id: string;
71 kind: "message";
72 createdAt: string;
73 message: ChatMessage;
74 }
75 | {
76 id: string;
77 kind: "work";
78 createdAt: string;
79 entry: WorkLogEntry;
80 };
81​
82function normalizeDetail(value: string | undefined): string | undefined {
83 if (!value) return undefined;
84 const trimmed = value.trim();
85 return trimmed.length > 0 ? trimmed : undefined;
87​
88function normalizeItemType(raw: string | undefined): string {
89 if (!raw) return "item";
90 return raw
91 .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
92 .replace(/[._/-]/g, " ")
93 .replace(/\s+/g, " ")
94 .trim()
95 .toLowerCase();
97​
98function shouldDropItemType(type: string): boolean {
99 if (
100 type.includes("preamble") ||
101 type.includes("reasoning") ||
102 type.includes("thought")
103 ) {
104 return true;
105 }
106​
107 return type === "work" || type.startsWith("work ");
109​
110function shouldShowItemLifecycle(type: string): boolean {
111 return (
112 type.includes("tool") ||
113 type.includes("command") ||
114 type.includes("file change")
115 );
117​
118function shouldDropMethod(method: string): boolean {
119 return /(^|\/)(preamble|work|reasoning|thought)(\/|$)/i.test(method);
121​
122function itemTypeMeta(type: string): {
123 label: string;
124 tone: WorkLogEntry["tone"];
125} {
126 if (type.includes("command")) {
127 return { label: "Command run", tone: "tool" };
128 }
129 if (type.includes("file change")) {
130 return { label: "File change", tone: "tool" };
131 }
132 if (type.includes("tool")) {
133 return { label: "Tool call", tone: "tool" };
134 }
135 return { label: "Work item", tone: "info" };
137​
138function extractDetail(
139 payload: Record<string, unknown> | undefined,
140 item: Record<string, unknown> | undefined,
141): string | undefined {
142 const candidates = [
143 asString(item?.title),
144 asString(item?.summary),
145 asString(item?.text),
146 asString(item?.command),
147 asString(payload?.message),
148 asString(payload?.prompt),
149 asString(payload?.command),
150 ];
151​
152 for (const candidate of candidates) {
153 const detail = normalizeDetail(candidate);
154 if (detail) return detail;
155 }
156 return undefined;
158​
159function entryFromItemLifecycle(event: ProviderEvent): WorkLogEntry | null {
160 const payload = asObject(event.payload);
161 const item = asObject(payload?.item);
162 const normalizedType = normalizeItemType(asString(item?.type));
163 if (shouldDropItemType(normalizedType) || shouldDropMethod(event.method)) {
164 return null;
165 }
166 if (!shouldShowItemLifecycle(normalizedType)) {
167 return null;
168 }
169​
170 const meta = itemTypeMeta(normalizedType);
171 const isStarted = event.method === "item/started";
172 const isCompleted = event.method === "item/completed";
173 if (!isStarted && !isCompleted) {
174 return null;
175 }
176​
177 const label = isCompleted ? `${meta.label} complete` : meta.label;
178 const detail = extractDetail(payload, item);
179 return {
180 id: event.id,
181 createdAt: event.createdAt,
182 label,
183 ...(detail ? { detail } : {}),
184 tone: meta.tone,
185 };
187​
188function entryFromRequest(event: ProviderEvent): WorkLogEntry | null {
189 if (event.kind !== "request") return null;
190 if (shouldDropMethod(event.method)) return null;
191​
192 if (event.method.includes("commandExecution")) {
193 return {
194 id: event.id,
195 createdAt: event.createdAt,
196 label: "Command approval requested",
197 tone: "tool",
198 };
199 }
200​
201 if (event.method.includes("fileChange")) {
202 return {
203 id: event.id,
204 createdAt: event.createdAt,
205 label: "File-change approval requested",
206 tone: "tool",
207 };
208 }
209​
210 if (event.method.includes("requestUserInput")) {
211 return {
212 id: event.id,
213 createdAt: event.createdAt,
214 label: "Tool requested user input",
215 tone: "tool",
216 };
217 }
218​
219 return {
220 id: event.id,
221 createdAt: event.createdAt,
222 label: `Request: ${event.method}`,
223 tone: "info",
224 };
226​
227function entryFromNotification(
228 event: ProviderEvent,
229 turnStartedAt: number,
230): WorkLogEntry | null {
231 if (event.kind !== "notification") return null;
232 if (shouldDropMethod(event.method)) return null;
233 if (event.method === "item/agentMessage/delta") return null;
234 if (event.method === "turn/started") {
235 return null;
236 }
237 if (event.method === "thread/started") return null;
238​
239 if (event.method === "turn/completed") {
240 const payload = asObject(event.payload);
241 const turn = asObject(payload?.turn);
242 const status = asString(turn?.status);
243 const turnError = asObject(turn?.error);
244 const turnErrorMessage = asString(turnError?.message);
245 const turnErrorDetail = normalizeDetail(turnErrorMessage);
246 const eventAt = Date.parse(event.createdAt);
247 const durationMs =
248 Number.isNaN(turnStartedAt) ||
249 Number.isNaN(eventAt) ||
250 eventAt < turnStartedAt
251 ? undefined
252 : eventAt - turnStartedAt;
253​
254 return {
255 id: event.id,
256 createdAt: event.createdAt,
257 label:
258 status === "failed"
259 ? "Turn failed"
260 : durationMs !== undefined
261 ? `Turn complete in ${formatDuration(durationMs)}`
262 : "Turn complete",
263 ...(turnErrorDetail ? { detail: turnErrorDetail } : {}),
264 tone: status === "failed" ? "error" : "info",
265 };
266 }
267​
268 const lifecycleEntry = entryFromItemLifecycle(event);
269 if (lifecycleEntry) return lifecycleEntry;
270​
271 if (event.method.startsWith("item/")) return null;
272​
273 return null;
275​
276function entryFromError(event: ProviderEvent): WorkLogEntry | null {
277 if (event.kind !== "error") return null;
278 if (shouldDropMethod(event.method)) return null;
279 const detail = normalizeDetail(event.message);
280​
281 return {
282 id: event.id,
283 createdAt: event.createdAt,
284 label: "Runtime error",
285 ...(detail ? { detail } : {}),
286 tone: "error",
287 };
289​
290function eventTurnId(event: ProviderEvent): string | undefined {
291 const payload = asObject(event.payload);
292 const turn = asObject(payload?.turn);
293 return event.turnId ?? asString(turn?.id);
295​
296export function deriveWorkLogEntries(
297 events: ProviderEvent[],
298 turnId: string | undefined,
299): WorkLogEntry[] {
300 const ordered = [...events].toReversed();
301 const entries: WorkLogEntry[] = [];
302 const turnStartedAtIso = turnId
303 ? ordered.find((event) => {
304 if (event.method !== "turn/started") return false;
305 return eventTurnId(event) === turnId;
306 })?.createdAt
307 : undefined;
308 const turnStartedAt = turnStartedAtIso ? Date.parse(turnStartedAtIso) : Number.NaN;
309​
310 for (const event of ordered) {
311 if (turnId) {
312 const scopedTurnId = eventTurnId(event);
313 if (scopedTurnId && scopedTurnId !== turnId) {
314 continue;
315 }
316​
317 if (!scopedTurnId && !Number.isNaN(turnStartedAt)) {
318 const eventAt = Date.parse(event.createdAt);
319 if (!Number.isNaN(eventAt) && eventAt < turnStartedAt) {
320 continue;
321 }
322 }
323 }
324​
325 const fromRequest = entryFromRequest(event);
326 if (fromRequest) {
327 entries.push(fromRequest);
328 continue;
329 }
330​
331 const fromNotification = entryFromNotification(event, turnStartedAt);
332 if (fromNotification) {
333 entries.push(fromNotification);
334 continue;
335 }
336​
337 const fromError = entryFromError(event);
338 if (fromError) {
339 entries.push(fromError);
340 }
341 }
342​
343 return entries;
345​
346function toTimestamp(isoDate: string): number {
347 const parsed = Date.parse(isoDate);
348 return Number.isNaN(parsed) ? Number.POSITIVE_INFINITY : parsed;
350​
351export function deriveTimelineEntries(
352 messages: ChatMessage[],
353 workEntries: WorkLogEntry[],
354): TimelineEntry[] {
355 const timeline: TimelineEntry[] = [];
356 let messageIndex = 0;
357 let workIndex = 0;
358​
359 while (messageIndex < messages.length || workIndex < workEntries.length) {
360 const message = messages[messageIndex];
361 const workEntry = workEntries[workIndex];
362​
363 if (!message && workEntry) {
364 timeline.push({
365 id: `work:${workEntry.id}`,
366 kind: "work",
367 createdAt: workEntry.createdAt,
368 entry: workEntry,
369 });
370 workIndex += 1;
371 continue;
372 }
373​
374 if (!workEntry && message) {
375 timeline.push({
376 id: `message:${message.id}`,
377 kind: "message",
378 createdAt: message.createdAt,
379 message,
380 });
381 messageIndex += 1;
382 continue;
383 }
384​
385 if (!message || !workEntry) {
386 break;
387 }
388​
389 const messageAt = toTimestamp(message.createdAt);
390 const workAt = toTimestamp(workEntry.createdAt);
391​
392 if (workAt <= messageAt) {
393 timeline.push({
394 id: `work:${workEntry.id}`,
395 kind: "work",
396 createdAt: workEntry.createdAt,
397 entry: workEntry,
398 });
399 workIndex += 1;
400 continue;
401 }
402​
403 timeline.push({
404 id: `message:${message.id}`,
405 kind: "message",
406 createdAt: message.createdAt,
407 message,
408 });
409 messageIndex += 1;
410 }
411​
412 return timeline;
414​
415export function derivePhase(session: ProviderSession | null): SessionPhase {
416 if (!session || session.status === "closed") return "disconnected";
417 if (session.status === "connecting") return "connecting";
418 if (session.status === "running") return "running";
419 return "ready";
421​
422export function evolveSession(previous: ProviderSession, event: ProviderEvent): ProviderSession {
423 const payload = asObject(event.payload);
424​
425 if (event.method === "thread/started") {
426 const thread = asObject(payload?.thread);
427 return {
428 ...previous,
429 threadId: asString(thread?.id) ?? event.threadId ?? previous.threadId,
430 updatedAt: event.createdAt,
431 };
432 }
433​
434 if (event.method === "turn/started") {
435 const turn = asObject(payload?.turn);
436 return {
437 ...previous,
438 status: "running",
439 activeTurnId: asString(turn?.id) ?? event.turnId ?? previous.activeTurnId,
440 updatedAt: event.createdAt,
441 };
442 }
443​
444 if (event.method === "turn/completed") {
445 const turn = asObject(payload?.turn);
446 const status = asString(turn?.status);
447 const turnError = asObject(turn?.error);
448 return {
449 ...previous,
450 status: status === "failed" ? "error" : "ready",
451 activeTurnId: undefined,
452 lastError: asString(turnError?.message) ?? previous.lastError,
453 updatedAt: event.createdAt,
454 };
455 }
456​
457 if (event.kind === "error") {
458 return {
459 ...previous,
460 status: "error",
461 lastError: event.message ?? previous.lastError,
462 updatedAt: event.createdAt,
463 };
464 }
465​
466 if (event.method === "session/closed" || event.method === "session/exited") {
467 return {
468 ...previous,
469 status: "closed",
470 activeTurnId: undefined,
471 lastError: event.message ?? previous.lastError,
472 updatedAt: event.createdAt,
473 };
474 }
475​
476 return { ...previous, updatedAt: event.createdAt };
478​
479export function applyEventToMessages(
480 previous: ChatMessage[],
481 event: ProviderEvent,
482 activeAssistantItemRef: { current: string | null },
483): ChatMessage[] {
484 const payload = asObject(event.payload);
485​
486 if (event.method === "item/started") {
487 const item = asObject(payload?.item);
488 if (asString(item?.type) !== "agentMessage") return previous;
489 const itemId = asString(item?.id);
490 if (!itemId) return previous;
491​
492 activeAssistantItemRef.current = itemId;
493 const seedText = asString(item?.text) ?? "";
494 const filtered = previous.filter((entry) => entry.id !== itemId);
495 return [
496 ...filtered,
497 {
498 id: itemId,
499 role: "assistant",
500 text: seedText,
501 createdAt: event.createdAt,
502 streaming: true,
503 },
504 ];
505 }
506​
507 if (event.method === "item/agentMessage/delta") {
508 const itemId = event.itemId ?? asString(payload?.itemId);
509 const delta = event.textDelta ?? asString(payload?.delta) ?? "";
510 if (!itemId || !delta) return previous;
511​
512 const existingIndex = previous.findIndex((entry) => entry.id === itemId);
513 if (existingIndex === -1) {
514 activeAssistantItemRef.current = itemId;
515 return [
516 ...previous,
517 {
518 id: itemId,
519 role: "assistant",
520 text: delta,
521 createdAt: event.createdAt,
522 streaming: true,
523 },
524 ];
525 }
526​
527 const updated = [...previous];
528 const existing = updated[existingIndex];
529 if (!existing) return previous;
530 updated[existingIndex] = {
531 ...existing,
532 text: `${existing.text}${delta}`,
533 streaming: true,
534 };
535 return updated;
536 }
537​
538 if (event.method === "item/completed") {
539 const item = asObject(payload?.item);
540 if (asString(item?.type) !== "agentMessage") return previous;
541 const itemId = asString(item?.id);
542 if (!itemId) return previous;
543​
544 const fullText = asString(item?.text);
545 const existingIndex = previous.findIndex((entry) => entry.id === itemId);
546 if (existingIndex === -1) {
547 return [
548 ...previous,
549 {
550 id: itemId,
551 role: "assistant",
552 text: fullText ?? "",
553 createdAt: event.createdAt,
554 streaming: false,
555 },
556 ];
557 }
558​
559 const updated = [...previous];
560 const existing = updated[existingIndex];
561 if (!existing) return previous;
562 updated[existingIndex] = {
563 ...existing,
564 text: fullText ?? existing.text,
565 streaming: false,
566 };
567​
568 if (activeAssistantItemRef.current === itemId) {
569 activeAssistantItemRef.current = null;
570 }
571 return updated;
572 }
573​
574 if (event.method === "turn/completed") {
575 return previous.map((entry) => ({ ...entry, streaming: false }));
576 }
577​
578 return previous;