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

orchestrationTiming.ts

66 lines2.4 KB

1type LatestRunTiming = {
2 readonly runId: string | null;
3 /** Set when the turn is created; `startedAt` waits for the provider. */
4 readonly requestedAt?: string | null;
5 readonly startedAt: string | null;
6 readonly completedAt: string | null;
7};
8​
9type RuntimeActivityState = {
10 readonly orchestrationStatus: string;
11 readonly activeRunId?: string | null;
12};
13​
14export function formatDuration(durationMs: number): string {
15 if (!Number.isFinite(durationMs) || durationMs < 0) return "0ms";
16 if (durationMs < 1_000) return `${Math.max(1, Math.round(durationMs))}ms`;
17 if (durationMs < 10_000) {
18 const tenths = Math.round(durationMs / 100) / 10;
19 return tenths >= 10 ? "10s" : `${tenths.toFixed(1)}s`;
20 }
21 if (durationMs < 60_000) return `${Math.round(durationMs / 1_000)}s`;
22 const totalSeconds = Math.round(durationMs / 1_000);
23 const hours = Math.floor(totalSeconds / 3_600);
24 const minutes = Math.floor((totalSeconds % 3_600) / 60);
25 const seconds = totalSeconds % 60;
26 const parts: string[] = [];
27 if (hours > 0) parts.push(`${hours}h`);
28 if (minutes > 0) parts.push(`${minutes}m`);
29 if (seconds > 0) parts.push(`${seconds}s`);
30 return parts.join(" ");
32​
33function isLatestRunSettled(
34 latestRun: LatestRunTiming | null,
35 runtime: RuntimeActivityState | null,
36): boolean {
37 if (!latestRun) return false;
38 if (!latestRun.completedAt) return false;
39 if (!runtime) return true;
40 if (runtime.orchestrationStatus === "running") return false;
41 return true;
43​
44/**
45 * When the working indicator should be counting, and from when.
46 *
47 * `requestedAt` is the floor for an unsettled turn. The projector only stamps
48 * `startedAt` in the same update that moves the session to "running", so while
49 * the provider spins up (session "starting") a requested turn has no
50 * `startedAt` at all — and returning null there blinks the indicator out for
51 * the whole spin-up. A settled turn still falls through to `sendStartedAt`, so
52 * this cannot leave the indicator counting after the work is done.
53 */
54export function deriveActiveWorkStartedAt(
55 latestRun: LatestRunTiming | null,
56 runtime: RuntimeActivityState | null,
57 sendStartedAt: string | null,
58): string | null {
59 if (runtime?.activeRunId && runtime.activeRunId !== latestRun?.runId) {
60 return sendStartedAt;
61 }
62 if (!isLatestRunSettled(latestRun, runtime)) {
63 return latestRun?.startedAt ?? latestRun?.requestedAt ?? sendStartedAt;
64 }
65 return sendStartedAt;