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

orchestrationTiming.ts

61 lines2.0 KB

1type LatestRunTiming = {
2 readonly runId: string | null;
3 readonly startedAt: string | null;
4 readonly completedAt: string | null;
5};
6​
7type RuntimeActivityState = {
8 readonly orchestrationStatus: string;
9 readonly activeRunId?: string | null;
10};
11​
12export function formatDuration(durationMs: number): string {
13 if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
14 if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
15 if (durationMs < 10_000) {
16 const tenths = Math.round(durationMs / 100) / 10;
17 return tenths >= 10 ? "10s" : `${tenths.toFixed(1)}s`;
18 }
19 if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
20 const totalSeconds = Math.round(durationMs / 1_000);
21 const hours = Math.floor(totalSeconds / 3_600);
22 const minutes = Math.floor((totalSeconds % 3_600) / 60);
23 const seconds = totalSeconds % 60;
24 const parts: string[] = [];
25 if (hours > 0) parts.push(`${hours}h`);
26 if (minutes > 0) parts.push(`${minutes}m`);
27 if (seconds > 0) parts.push(`${seconds}s`);
28 return parts.join(" ");
30​
31export function formatElapsed(startIso: string, endIso: string | undefined): string | null {
32 if (!endIso) return null;
33 const startedAt = Date.parse(startIso);
34 const endedAt = Date.parse(endIso);
35 if (Number.isNaN(startedAt) || Number.isNaN(endedAt) || endedAt < startedAt) {
36 return null;
37 }
38 return formatDuration(endedAt - startedAt);
40​
41export function isLatestRunSettled(
42 latestRun: LatestRunTiming | null,
43 runtime: RuntimeActivityState | null,
44): boolean {
45 if (!latestRun?.startedAt) return false;
46 if (!latestRun.completedAt) return false;
47 if (!runtime) return true;
48 if (runtime.orchestrationStatus === "running") return false;
49 return true;
51​
52export function deriveActiveWorkStartedAt(
53 latestRun: LatestRunTiming | null,
54 runtime: RuntimeActivityState | null,
55 sendStartedAt: string | null,
56): string | null {
57 if (!isLatestRunSettled(latestRun, runtime)) {
58 return latestRun?.startedAt ?? sendStartedAt;
59 }
60 return sendStartedAt;