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