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

session-logic.ts

674 lines17.9 KB

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