Open History to see the last commit
1import {
2 ApprovalRequestId,
3 type OrchestrationLatestTurn,
4 type OrchestrationThreadActivity,
5 type OrchestrationProposedPlanId,
6 type ProviderKind,
7 type UserInputQuestion,
8 type TurnId,
9} from "@t3tools/contracts";
10
11import type {
12 ChatMessage,
13 ProposedPlan,
14 SessionPhase,
15 ThreadSession,
16 TurnDiffSummary,
17} from "./types";
18
19export type ProviderPickerKind = ProviderKind | "claudeCode" | "cursor";
20
21export const PROVIDER_OPTIONS: Array<{
22 value: ProviderPickerKind;
23 label: string;
24 available: boolean;
25}> = [
26 { value: "codex", label: "Codex", available: true },
27 { value: "claudeCode", label: "Claude Code", available: false },
28 { value: "cursor", label: "Cursor", available: false },
29];
30
31export interface WorkLogEntry {
32 id: string;
33 createdAt: string;
34 label: string;
35 detail?: string;
36 command?: string;
37 changedFiles?: ReadonlyArray<string>;
38 tone: "thinking" | "tool" | "info" | "error";
39}
40
41export interface PendingApproval {
42 requestId: ApprovalRequestId;
43 requestKind: "command" | "file-read" | "file-change";
44 createdAt: string;
45 detail?: string;
46}
47
48export interface PendingUserInput {
49 requestId: ApprovalRequestId;
50 createdAt: string;
51 questions: ReadonlyArray<UserInputQuestion>;
52}
53
54export interface ActivePlanState {
55 createdAt: string;
56 turnId: TurnId | null;
57 explanation?: string | null;
58 steps: Array<{
59 step: string;
60 status: "pending" | "inProgress" | "completed";
61 }>;
62}
63
64export interface LatestProposedPlanState {
65 id: OrchestrationProposedPlanId;
66 createdAt: string;
67 updatedAt: string;
68 turnId: TurnId | null;
69 planMarkdown: string;
70}
71
72export type TimelineEntry =
73 | {
74 id: string;
75 kind: "message";
76 createdAt: string;
77 message: ChatMessage;
78 }
79 | {
80 id: string;
81 kind: "proposed-plan";
82 createdAt: string;
83 proposedPlan: ProposedPlan;
84 }
85 | {
86 id: string;
87 kind: "work";
88 createdAt: string;
89 entry: WorkLogEntry;
90 };
91
92export function formatTimestamp(isoDate: string): string {
93 return new Intl.DateTimeFormat(undefined, {
94 hour: "numeric",
95 minute: "2-digit",
96 second: "2-digit",
97 }).format(new Date(isoDate));
98}
99
100export function formatDuration(durationMs: number): string {
101 if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
102 if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
103 if (durationMs < 10_000) return `${(durationMs / 1_000).toFixed(1)}s`;
104 if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
105 const minutes = Math.floor(durationMs / 60_000);
106 const seconds = Math.round((durationMs % 60_000) / 1_000);
107 if (seconds === 0) return `${minutes}m`;
108 if (seconds === 60) return `${minutes + 1}m`;
109 return `${minutes}m ${seconds}s`;
110}
111
112export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
113 if (!endIso) return null;
114 const startedAt = Date.parse(startIso);
115 const endedAt = Date.parse(endIso);
116 if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
117 return null;
118 }
119 return formatDuration(endedAt - startedAt);
120}
121
122type LatestTurnTiming = Pick<OrchestrationLatestTurn, "turnId" | "startedAt" | "completedAt">;
123type SessionActivityState = Pick<ThreadSession, "orchestrationStatus" | "activeTurnId">;
124
125export function isLatestTurnSettled(
126 latestTurn: LatestTurnTiming | null,
127 session: SessionActivityState | null,
128): boolean {
129 if (!latestTurn?.startedAt) return false;
130 if (!latestTurn.completedAt) return false;
131 if (!session) return true;
132 if (session.orchestrationStatus === "running") return false;
133 return true;
134}
135
136export function deriveActiveWorkStartedAt(
137 latestTurn: LatestTurnTiming | null,
138 session: SessionActivityState | null,
139 sendStartedAt: string | null,
140): string | null {
141 if (!isLatestTurnSettled(latestTurn, session)) {
142 return latestTurn?.startedAt ?? sendStartedAt;
143 }
144 return sendStartedAt;
145}
146
147function requestKindFromRequestType(requestType: unknown): PendingApproval["requestKind"] | null {
148 switch (requestType) {
149 case "command_execution_approval":
150 case "exec_command_approval":
151 return "command";
152 case "file_read_approval":
153 return "file-read";
154 case "file_change_approval":
155 case "apply_patch_approval":
156 return "file-change";
157 default:
158 return null;
159 }
160}
161
162export function derivePendingApprovals(
163 activities: ReadonlyArray<OrchestrationThreadActivity>,
164): PendingApproval[] {
165 const openByRequestId = new Map<ApprovalRequestId, PendingApproval>();
166 const ordered = [...activities].toSorted(compareActivitiesByOrder);
167
168 for (const activity of ordered) {
169 const payload =
170 activity.payload && typeof activity.payload === "object"
171 ? (activity.payload as Record<string, unknown>)
172 : null;
173 const requestId =
174 payload && typeof payload.requestId === "string"
175 ? ApprovalRequestId.makeUnsafe(payload.requestId)
176 : null;
177 const requestKind =
178 payload &&
179 (payload.requestKind === "command" ||
180 payload.requestKind === "file-read" ||
181 payload.requestKind === "file-change")
182 ? payload.requestKind
183 : payload
184 ? requestKindFromRequestType(payload.requestType)
185 : null;
186 const detail = payload && typeof payload.detail === "string" ? payload.detail : undefined;
187
188 if (activity.kind === "approval.requested" && requestId && requestKind) {
189 openByRequestId.set(requestId, {
190 requestId,
191 requestKind,
192 createdAt: activity.createdAt,
193 ...(detail ? { detail } : {}),
194 });
195 continue;
196 }
197
198 if (activity.kind === "approval.resolved" && requestId) {
199 openByRequestId.delete(requestId);
200 continue;
201 }
202
203 if (
204 activity.kind === "provider.approval.respond.failed" &&
205 requestId &&
206 detail?.includes("Unknown pending permission request")
207 ) {
208 openByRequestId.delete(requestId);
209 continue;
210 }
211 }
212
213 return [...openByRequestId.values()].toSorted((left, right) =>
214 left.createdAt.localeCompare(right.createdAt),
215 );
216}
217
218function parseUserInputQuestions(
219 payload: Record<string, unknown> | null,
220): ReadonlyArray<UserInputQuestion> | null {
221 const questions = payload?.questions;
222 if (!Array.isArray(questions)) {
223 return null;
224 }
225 const parsed = questions
226 .map<UserInputQuestion | null>((entry) => {
227 if (!entry || typeof entry !== "object") return null;
228 const question = entry as Record<string, unknown>;
229 if (
230 typeof question.id !== "string" ||
231 typeof question.header !== "string" ||
232 typeof question.question !== "string" ||
233 !Array.isArray(question.options)
234 ) {
235 return null;
236 }
237 const options = question.options
238 .map<UserInputQuestion["options"][number] | null>((option) => {
239 if (!option || typeof option !== "object") return null;
240 const optionRecord = option as Record<string, unknown>;
241 if (
242 typeof optionRecord.label !== "string" ||
243 typeof optionRecord.description !== "string"
244 ) {
245 return null;
246 }
247 return {
248 label: optionRecord.label,
249 description: optionRecord.description,
250 };
251 })
252 .filter((option): option is UserInputQuestion["options"][number] => option !== null);
253 if (options.length === 0) {
254 return null;
255 }
256 return {
257 id: question.id,
258 header: question.header,
259 question: question.question,
260 options,
261 };
262 })
263 .filter((question): question is UserInputQuestion => question !== null);
264 return parsed.length > 0 ? parsed : null;
265}
266
267export function derivePendingUserInputs(
268 activities: ReadonlyArray<OrchestrationThreadActivity>,
269): PendingUserInput[] {
270 const openByRequestId = new Map<ApprovalRequestId, PendingUserInput>();
271 const ordered = [...activities].toSorted(compareActivitiesByOrder);
272
273 for (const activity of ordered) {
274 const payload =
275 activity.payload && typeof activity.payload === "object"
276 ? (activity.payload as Record<string, unknown>)
277 : null;
278 const requestId =
279 payload && typeof payload.requestId === "string"
280 ? ApprovalRequestId.makeUnsafe(payload.requestId)
281 : null;
282
283 if (activity.kind === "user-input.requested" && requestId) {
284 const questions = parseUserInputQuestions(payload);
285 if (!questions) {
286 continue;
287 }
288 openByRequestId.set(requestId, {
289 requestId,
290 createdAt: activity.createdAt,
291 questions,
292 });
293 continue;
294 }
295
296 if (activity.kind === "user-input.resolved" && requestId) {
297 openByRequestId.delete(requestId);
298 }
299 }
300
301 return [...openByRequestId.values()].toSorted((left, right) =>
302 left.createdAt.localeCompare(right.createdAt),
303 );
304}
305
306export function deriveActivePlanState(
307 activities: ReadonlyArray<OrchestrationThreadActivity>,
308 latestTurnId: TurnId | undefined,
309): ActivePlanState | null {
310 const ordered = [...activities].toSorted(compareActivitiesByOrder);
311 const candidates = ordered.filter((activity) => {
312 if (activity.kind !== "turn.plan.updated") {
313 return false;
314 }
315 if (!latestTurnId) {
316 return true;
317 }
318 return activity.turnId === latestTurnId;
319 });
320 const latest = candidates.at(-1);
321 if (!latest) {
322 return null;
323 }
324 const payload =
325 latest.payload && typeof latest.payload === "object"
326 ? (latest.payload as Record<string, unknown>)
327 : null;
328 const rawPlan = payload?.plan;
329 if (!Array.isArray(rawPlan)) {
330 return null;
331 }
332 const steps = rawPlan
333 .map((entry) => {
334 if (!entry || typeof entry !== "object") return null;
335 const record = entry as Record<string, unknown>;
336 if (typeof record.step !== "string") {
337 return null;
338 }
339 const status =
340 record.status === "completed" || record.status === "inProgress" ? record.status : "pending";
341 return {
342 step: record.step,
343 status,
344 };
345 })
346 .filter(
347 (
348 step,
349 ): step is {
350 step: string;
351 status: "pending" | "inProgress" | "completed";
352 } => step !== null,
353 );
354 if (steps.length === 0) {
355 return null;
356 }
357 return {
358 createdAt: latest.createdAt,
359 turnId: latest.turnId,
360 ...(payload && "explanation" in payload
361 ? { explanation: payload.explanation as string | null }
362 : {}),
363 steps,
364 };
365}
366
367export function findLatestProposedPlan(
368 proposedPlans: ReadonlyArray<ProposedPlan>,
369 latestTurnId: TurnId | string | null | undefined,
370): LatestProposedPlanState | null {
371 if (latestTurnId) {
372 const matchingTurnPlan = [...proposedPlans]
373 .filter((proposedPlan) => proposedPlan.turnId === latestTurnId)
374 .toSorted(
375 (left, right) =>
376 left.updatedAt.localeCompare(right.updatedAt) || left.id.localeCompare(right.id),
377 )
378 .at(-1);
379 if (matchingTurnPlan) {
380 return {
381 id: matchingTurnPlan.id,
382 createdAt: matchingTurnPlan.createdAt,
383 updatedAt: matchingTurnPlan.updatedAt,
384 turnId: matchingTurnPlan.turnId,
385 planMarkdown: matchingTurnPlan.planMarkdown,
386 };
387 }
388 }
389
390 const latestPlan = [...proposedPlans]
391 .toSorted(
392 (left, right) =>
393 left.updatedAt.localeCompare(right.updatedAt) || left.id.localeCompare(right.id),
394 )
395 .at(-1);
396 if (!latestPlan) {
397 return null;
398 }
399
400 return {
401 id: latestPlan.id,
402 createdAt: latestPlan.createdAt,
403 updatedAt: latestPlan.updatedAt,
404 turnId: latestPlan.turnId,
405 planMarkdown: latestPlan.planMarkdown,
406 };
407}
408
409export function deriveWorkLogEntries(
410 activities: ReadonlyArray<OrchestrationThreadActivity>,
411 latestTurnId: TurnId | undefined,
412): WorkLogEntry[] {
413 const ordered = [...activities].toSorted(compareActivitiesByOrder);
414 return ordered
415 .filter((activity) => (latestTurnId ? activity.turnId === latestTurnId : true))
416 .filter((activity) => activity.kind !== "tool.started")
417 .filter((activity) => activity.kind !== "task.started" && activity.kind !== "task.completed")
418 .filter((activity) => activity.summary !== "Checkpoint captured")
419 .map((activity) => {
420 const payload =
421 activity.payload && typeof activity.payload === "object"
422 ? (activity.payload as Record<string, unknown>)
423 : null;
424 const command = extractToolCommand(payload);
425 const changedFiles = extractChangedFiles(payload);
426 const entry: WorkLogEntry = {
427 id: activity.id,
428 createdAt: activity.createdAt,
429 label: activity.summary,
430 tone: activity.tone === "approval" ? "info" : activity.tone,
431 };
432 if (payload && typeof payload.detail === "string" && payload.detail.length > 0) {
433 entry.detail = payload.detail;
434 }
435 if (command) {
436 entry.command = command;
437 }
438 if (changedFiles.length > 0) {
439 entry.changedFiles = changedFiles;
440 }
441 return entry;
442 });
443}
444
445function asRecord(value: unknown): Record<string, unknown> | null {
446 return value && typeof value === "object" ? (value as Record<string, unknown>) : null;
447}
448
449function asTrimmedString(value: unknown): string | null {
450 if (typeof value !== "string") {
451 return null;
452 }
453 const trimmed = value.trim();
454 return trimmed.length > 0 ? trimmed : null;
455}
456
457function normalizeCommandValue(value: unknown): string | null {
458 const direct = asTrimmedString(value);
459 if (direct) {
460 return direct;
461 }
462 if (!Array.isArray(value)) {
463 return null;
464 }
465 const parts = value
466 .map((entry) => asTrimmedString(entry))
467 .filter((entry): entry is string => entry !== null);
468 return parts.length > 0 ? parts.join(" ") : null;
469}
470
471function extractToolCommand(payload: Record<string, unknown> | null): string | null {
472 const data = asRecord(payload?.data);
473 const item = asRecord(data?.item);
474 const itemResult = asRecord(item?.result);
475 const itemInput = asRecord(item?.input);
476 const candidates = [
477 normalizeCommandValue(item?.command),
478 normalizeCommandValue(itemInput?.command),
479 normalizeCommandValue(itemResult?.command),
480 normalizeCommandValue(data?.command),
481 ];
482 return candidates.find((candidate) => candidate !== null) ?? null;
483}
484
485function pushChangedFile(target: string[], seen: Set<string>, value: unknown) {
486 const normalized = asTrimmedString(value);
487 if (!normalized || seen.has(normalized)) {
488 return;
489 }
490 seen.add(normalized);
491 target.push(normalized);
492}
493
494function collectChangedFiles(value: unknown, target: string[], seen: Set<string>, depth: number) {
495 if (depth > 4 || target.length >= 12) {
496 return;
497 }
498 if (Array.isArray(value)) {
499 for (const entry of value) {
500 collectChangedFiles(entry, target, seen, depth + 1);
501 if (target.length >= 12) {
502 return;
503 }
504 }
505 return;
506 }
507
508 const record = asRecord(value);
509 if (!record) {
510 return;
511 }
512
513 pushChangedFile(target, seen, record.path);
514 pushChangedFile(target, seen, record.filePath);
515 pushChangedFile(target, seen, record.relativePath);
516 pushChangedFile(target, seen, record.filename);
517 pushChangedFile(target, seen, record.newPath);
518 pushChangedFile(target, seen, record.oldPath);
519
520 for (const nestedKey of [
521 "item",
522 "result",
523 "input",
524 "data",
525 "changes",
526 "files",
527 "edits",
528 "patch",
529 "patches",
530 "operations",
531 ]) {
532 if (!(nestedKey in record)) {
533 continue;
534 }
535 collectChangedFiles(record[nestedKey], target, seen, depth + 1);
536 if (target.length >= 12) {
537 return;
538 }
539 }
540}
541
542function extractChangedFiles(payload: Record<string, unknown> | null): string[] {
543 const data = asRecord(payload?.data);
544 const changedFiles: string[] = [];
545 collectChangedFiles(data, changedFiles, new Set<string>(), 0);
546 return changedFiles;
547}
548
549function compareActivitiesByOrder(
550 left: OrchestrationThreadActivity,
551 right: OrchestrationThreadActivity,
552): number {
553 if (left.sequence !== undefined && right.sequence !== undefined) {
554 if (left.sequence !== right.sequence) {
555 return left.sequence - right.sequence;
556 }
557 } else if (left.sequence !== undefined) {
558 return 1;
559 } else if (right.sequence !== undefined) {
560 return -1;
561 }
562
563 return left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id);
564}
565
566export function hasToolActivityForTurn(
567 activities: ReadonlyArray<OrchestrationThreadActivity>,
568 turnId: TurnId | null | undefined,
569): boolean {
570 if (!turnId) return false;
571 return activities.some((activity) => activity.turnId === turnId && activity.tone === "tool");
572}
573
574export function deriveTimelineEntries(
575 messages: ChatMessage[],
576 proposedPlans: ProposedPlan[],
577 workEntries: WorkLogEntry[],
578): TimelineEntry[] {
579 const messageRows: TimelineEntry[] = messages.map((message) => ({
580 id: message.id,
581 kind: "message",
582 createdAt: message.createdAt,
583 message,
584 }));
585 const proposedPlanRows: TimelineEntry[] = proposedPlans.map((proposedPlan) => ({
586 id: proposedPlan.id,
587 kind: "proposed-plan",
588 createdAt: proposedPlan.createdAt,
589 proposedPlan,
590 }));
591 const workRows: TimelineEntry[] = workEntries.map((entry) => ({
592 id: entry.id,
593 kind: "work",
594 createdAt: entry.createdAt,
595 entry,
596 }));
597 return [...messageRows, ...proposedPlanRows, ...workRows].toSorted((a, b) =>
598 a.createdAt.localeCompare(b.createdAt),
599 );
600}
601
602export function inferCheckpointTurnCountByTurnId(
603 summaries: TurnDiffSummary[],
604): Record<TurnId, number> {
605 const sorted = [...summaries].toSorted((a, b) => a.completedAt.localeCompare(b.completedAt));
606 const result: Record<TurnId, number> = {};
607 for (let index = 0; index < sorted.length; index += 1) {
608 const summary = sorted[index];
609 if (!summary) continue;
610 result[summary.turnId] = index + 1;
611 }
612 return result;
613}
614
615export function derivePhase(session: ThreadSession | null): SessionPhase {
616 if (!session || session.status === "closed") return "disconnected";
617 if (session.status === "connecting") return "connecting";
618 if (session.status === "running") return "running";
619 return "ready";
620}