Open History to see the last commit
1import { isOrchestrationV2WorkActive, type OrchestrationV2Subagent } from "@t3tools/contracts";
2
3export function deriveSubagentElapsedMs(
4 agent: {
5 readonly status: OrchestrationV2Subagent["status"];
6 readonly startedAt: string | null;
7 readonly completedAt: string | null;
8 },
9 nowMs: number,
10): number | null {
11 if (agent.startedAt === null) return null;
12 const end = isOrchestrationV2WorkActive(agent.status)
13 ? nowMs
14 : agent.completedAt === null
15 ? null
16 : Date.parse(agent.completedAt);
17 if (end === null) return null;
18 const start = Date.parse(agent.startedAt);
19 return Number.isFinite(start) && Number.isFinite(end) ? Math.max(0, end - start) : null;
20}
21
22type LatestRunTiming = {
23 readonly runId: string | null;
24 readonly requestedAt?: string | null;
25 readonly startedAt: string | null;
26 readonly completedAt: string | null;
27};
28
29type RuntimeActivityState = {
30 readonly orchestrationStatus: string;
31 readonly activeRunId?: string | null;
32};
33
34export function formatDuration(durationMs: number): string {
35 if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
36 if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
37 if (durationMs < 10_000) {
38 const tenths = Math.round(durationMs / 100) / 10;
39 return tenths >= 10 ? "10s" : `${tenths.toFixed(1)}s`;
40 }
41 if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
42 const totalSeconds = Math.round(durationMs / 1_000);
43 const hours = Math.floor(totalSeconds / 3_600);
44 const minutes = Math.floor((totalSeconds % 3_600) / 60);
45 const seconds = totalSeconds % 60;
46 const parts: string[] = [];
47 if (hours > 0) parts.push(`${hours}h`);
48 if (minutes > 0) parts.push(`${minutes}m`);
49 if (seconds > 0) parts.push(`${seconds}s`);
50 return parts.join(" ");
51}
52
53function isLatestRunSettled(
54 latestRun: LatestRunTiming | null,
55 runtime: RuntimeActivityState | null,
56): boolean {
57 if (!latestRun) return false;
58 if (!latestRun.completedAt) return false;
59 if (!runtime) return true;
60 if (runtime.orchestrationStatus === "running") return false;
61 return true;
62}
63
64/**
65 * The projector only stamps `startedAt` in the same update that moves the
66 * session to "running", so while the provider spins up (session "starting") a
67 * requested turn has no `startedAt` at all — and returning null there blinks
68 * the indicator out for the whole spin-up.
69 */
70export function deriveActiveWorkStartedAt(
71 latestRun: LatestRunTiming | null,
72 runtime: RuntimeActivityState | null,
73 sendStartedAt: string | null,
74): string | null {
75 if (runtime?.activeRunId && runtime.activeRunId !== latestRun?.runId) {
76 return sendStartedAt;
77 }
78 if (!isLatestRunSettled(latestRun, runtime)) {
79 return latestRun?.startedAt ?? latestRun?.requestedAt ?? sendStartedAt;
80 }
81 return sendStartedAt;
82}