Skip to content

Commit 2171c50

Browse files
perf(web): relative "checked" labels re-render only when their text changes (pingdotgg#20819)
Co-authored-by: Claude Opus 5.5 <[email protected]>
1 parent 2fbd431 commit 2171c50

6 files changed

Lines changed: 112 additions & 47 deletions

File tree

‎apps/web/src/components/settings/DiagnosticsSettings.tsx‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,8 @@ import * as Option from "effect/Option";
2323
import { cn } from "../../lib/utils";
2424
import { ensureLocalApi } from "../../localApi";
2525
import { useOpenInPreferredEditor } from "../../editorPreferences";
26-
import { formatRelativeTimeLabel, getRelativeTimeState } from "../../timestampFormat";
26+
import { formatRelativeTimeLabel } from "../../timestampFormat";
27+
import { useRelativeTimeState } from "../../hooks/useRelativeTimeState";
2728
import { useEnvironmentQuery } from "../../state/query";
2829
import { serverEnvironment } from "../../state/server";
2930
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
@@ -35,7 +36,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
3536
import { toastManager } from "../ui/toast";
3637
import { ExpandableText } from "./ExpandableText";
3738
import { ResourceTelemetryDiagnostics } from "./ResourceTelemetryDiagnostics";
38-
import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";
39+
import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
3940
import { useAtomCommand } from "../../state/use-atom-command";
4041
import { useSettingsScope } from "./SettingsScopeContext";
4142
import { TelemetryExportSettings } from "./TelemetryExportSettings";
@@ -664,8 +665,7 @@ function ProcessResourceHistoryTable({
664665
}
665666

666667
function DiagnosticsLastChecked({ checkedAt }: { checkedAt: DateTime.Utc | null }) {
667-
useRelativeTimeTick();
668-
const relative = getRelativeTimeState(checkedAt ? DateTime.formatIso(checkedAt) : null);
668+
const relative = useRelativeTimeState(checkedAt ? DateTime.formatIso(checkedAt) : null);
669669

670670
if (relative.status === "missing") {
671671
return <span className="text-2xs text-muted-foreground/50">Checking</span>;

‎apps/web/src/components/settings/ProviderSettingsPanel.tsx‎

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
5757
import { useEnvironmentSessionState } from "../../state/session";
5858
import { useProjects, useServerConfigs } from "../../state/entities";
5959
import { useAtomCommand } from "../../state/use-atom-command";
60-
import { getRelativeTimeState } from "../../timestampFormat";
60+
import { useRelativeTimeState } from "../../hooks/useRelativeTimeState";
6161
import {
6262
ConnectionStatusDot,
6363
connectionPhaseDotClassName,
@@ -112,7 +112,6 @@ import {
112112
SettingsPageContainer,
113113
SettingsRow,
114114
SettingsSection,
115-
useRelativeTimeTick,
116115
useSettingsSearchTargetId,
117116
} from "./settingsLayout";
118117
import {
@@ -151,8 +150,7 @@ function configuredBinaryPath(config: unknown): string {
151150
}
152151

153152
function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {
154-
useRelativeTimeTick();
155-
const lastCheckedRelative = getRelativeTimeState(lastCheckedAt);
153+
const lastCheckedRelative = useRelativeTimeState(lastCheckedAt);
156154

157155
if (lastCheckedRelative.status === "missing") {
158156
return null;

‎apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx‎

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ import { ensureLocalApi } from "../../localApi";
4444
import { serverEnvironment } from "../../state/server";
4545
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
4646
import { useAtomCommand } from "../../state/use-atom-command";
47-
import { formatRelativeTime } from "../../timestampFormat";
47+
import { useRelativeTimeState } from "../../hooks/useRelativeTimeState";
4848
import { Button } from "../ui/button";
4949
import { MorphIcon } from "~/components/MorphIcon";
5050
import { ScrollArea } from "../ui/scroll-area";
@@ -57,7 +57,7 @@ import {
5757
shouldShowResourceMonitorRetry,
5858
visibleResourceTelemetryProcesses,
5959
} from "./ResourceTelemetryDiagnostics.logic";
60-
import { SettingsSection, useRelativeTimeTick } from "./settingsLayout";
60+
import { SettingsSection } from "./settingsLayout";
6161

6262
const HISTORY_WINDOWS = [
6363
{ label: "5m", windowMs: 5 * 60_000, bucketMs: 15_000 },
@@ -207,12 +207,8 @@ function SourceStatusBadge({
207207
}
208208

209209
function LastSampleLabel({ sampledAt }: { sampledAt: DateTime.Utc | null }) {
210-
useRelativeTimeTick();
211-
if (!sampledAt) {
212-
return <span className="text-2xs text-muted-foreground/55">Waiting for sample</span>;
213-
}
214-
const relative = formatRelativeTime(DateTime.formatIso(sampledAt));
215-
if (!relative) {
210+
const relative = useRelativeTimeState(sampledAt ? DateTime.formatIso(sampledAt) : null);
211+
if (relative.status !== "relative") {
216212
return <span className="text-2xs text-muted-foreground/55">Waiting for sample</span>;
217213
}
218214
return (
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { useSyncExternalStore } from "react";
2+
3+
import {
4+
formatRelativeElapsed,
5+
msUntilRelativeTimeChange,
6+
relativeTimeElapsedMs,
7+
type RelativeTimeState,
8+
} from "../timestampFormat";
9+
10+
/**
11+
* A "5m ago" label that re-renders only when its text changes: the snapshot is
12+
* the elapsed time floored to the label's precision, and one timer fires at the
13+
* next boundary instead of polling every second.
14+
*/
15+
export function useRelativeTimeState(isoDate: string | null): RelativeTimeState {
16+
const subscribe = (onChange: () => void) => {
17+
if (isoDate === null) return () => {};
18+
let timer: ReturnType<typeof setTimeout> | undefined;
19+
const schedule = () => {
20+
const delayMs = msUntilRelativeTimeChange(isoDate);
21+
if (delayMs === null) return;
22+
timer = setTimeout(() => {
23+
onChange();
24+
schedule();
25+
}, delayMs);
26+
};
27+
schedule();
28+
return () => clearTimeout(timer);
29+
};
30+
const getSnapshot = () => (isoDate === null ? null : relativeTimeElapsedMs(isoDate));
31+
const elapsedMs = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
32+
33+
if (isoDate === null) return { status: "missing" };
34+
if (elapsedMs === null) return { status: "invalid" };
35+
return { status: "relative", ...formatRelativeElapsed(elapsedMs) };
36+
}

‎apps/web/src/timestampFormat.test.ts‎

Lines changed: 26 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@ import {
1111
formatShortTimestamp,
1212
formatTimestamp,
1313
formatUpcomingTimestamp,
14-
getRelativeTimeState,
14+
msUntilRelativeTimeChange,
15+
relativeTimeElapsedMs,
1516
resolveTimestampLocale,
1617
} from "./timestampFormat";
1718

@@ -253,9 +254,9 @@ describe("invalid timestamp inputs", () => {
253254
expect(formatRelativeTimeLabel("not-a-date")).toBe("");
254255
});
255256

256-
it("distinguishes missing and invalid relative time state", () => {
257-
expect(getRelativeTimeState(null)).toEqual({ status: "missing" });
258-
expect(getRelativeTimeState("not-a-date")).toEqual({ status: "invalid" });
257+
it("has no relative time boundary for an invalid timestamp", () => {
258+
expect(relativeTimeElapsedMs("not-a-date")).toBeNull();
259+
expect(msUntilRelativeTimeChange("not-a-date")).toBeNull();
259260
});
260261

261262
it("returns an empty elapsed duration instead of a NaN label", () => {
@@ -272,22 +273,27 @@ describe("invalid timestamp inputs", () => {
272273
});
273274
});
274275

275-
describe("getRelativeTimeState", () => {
276-
beforeEach(() => {
277-
vi.useFakeTimers();
278-
vi.setSystemTime(new Date("2026-04-07T12:00:00.000Z"));
279-
});
280-
281-
afterEach(() => {
282-
vi.useRealTimers();
283-
});
284-
285-
it("returns relative parts for valid timestamps", () => {
286-
expect(getRelativeTimeState("2026-04-07T11:45:00.000Z")).toEqual({
287-
status: "relative",
288-
value: "15m",
289-
suffix: "ago",
290-
});
276+
describe("relative time boundaries", () => {
277+
const nowMs = Date.parse("2026-04-07T12:00:00.000Z");
278+
279+
it("waits for the label to change instead of the next second", () => {
280+
// "just now" turns into "1m ago" at the one-minute mark.
281+
expect(msUntilRelativeTimeChange("2026-04-07T11:59:40.000Z", nowMs)).toBe(40_000);
282+
// "2m ago" turns into "3m ago" a minute after the 2m mark.
283+
expect(msUntilRelativeTimeChange("2026-04-07T11:57:30.000Z", nowMs)).toBe(30_000);
284+
// "3h ago" holds until the 4h mark.
285+
expect(msUntilRelativeTimeChange("2026-04-07T08:30:00.000Z", nowMs)).toBe(30 * 60_000);
286+
// "2d ago" holds until the 3d mark.
287+
expect(msUntilRelativeTimeChange("2026-04-05T00:00:00.000Z", nowMs)).toBe(12 * 3_600_000);
288+
// A future timestamp reads "just now" until a minute after it.
289+
expect(msUntilRelativeTimeChange("2026-04-07T12:00:10.000Z", nowMs)).toBe(70_000);
290+
});
291+
292+
it("keeps the elapsed snapshot stable while the label is unchanged", () => {
293+
const at = "2026-04-07T11:57:30.000Z";
294+
expect(relativeTimeElapsedMs(at, nowMs)).toBe(2 * 60_000);
295+
expect(relativeTimeElapsedMs(at, nowMs + 29_999)).toBe(2 * 60_000);
296+
expect(relativeTimeElapsedMs(at, nowMs + 30_000)).toBe(3 * 60_000);
291297
});
292298
});
293299

‎apps/web/src/timestampFormat.ts‎

Lines changed: 40 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -203,12 +203,43 @@ export type RelativeTimeState =
203203
| { status: "invalid" }
204204
| { status: "relative"; value: string; suffix: string | null };
205205

206-
export function formatRelativeTime(isoDate: string): RelativeTimeParts | null {
206+
const MINUTE_MS = 60_000;
207+
const HOUR_MS = 3_600_000;
208+
const DAY_MS = 86_400_000;
209+
210+
function relativeTimeUnitMs(elapsedMs: number): number {
211+
if (elapsedMs < HOUR_MS) return MINUTE_MS;
212+
if (elapsedMs < DAY_MS) return HOUR_MS;
213+
return DAY_MS;
214+
}
215+
216+
/**
217+
* Elapsed time floored to the precision `formatRelativeTime` shows, so two
218+
* instants with the same label return the same number.
219+
*/
220+
export function relativeTimeElapsedMs(isoDate: string, nowMs: number = Date.now()): number | null {
207221
const date = parseTimestampDate(isoDate);
208222
if (!date) return null;
209-
const diffMs = Date.now() - date.getTime();
210-
if (diffMs < 0) return { value: "just now", suffix: null };
211-
const seconds = Math.floor(diffMs / 1000);
223+
const elapsedMs = Math.max(0, nowMs - date.getTime());
224+
const unitMs = relativeTimeUnitMs(elapsedMs);
225+
return Math.floor(elapsedMs / unitMs) * unitMs;
226+
}
227+
228+
/** Milliseconds until the `formatRelativeTime` label for `isoDate` next changes. */
229+
export function msUntilRelativeTimeChange(
230+
isoDate: string,
231+
nowMs: number = Date.now(),
232+
): number | null {
233+
const date = parseTimestampDate(isoDate);
234+
if (!date) return null;
235+
const elapsedMs = Math.max(0, nowMs - date.getTime());
236+
const unitMs = relativeTimeUnitMs(elapsedMs);
237+
const nextChangeMs = date.getTime() + (Math.floor(elapsedMs / unitMs) + 1) * unitMs;
238+
return nextChangeMs - nowMs;
239+
}
240+
241+
export function formatRelativeElapsed(elapsedMs: number): RelativeTimeParts {
242+
const seconds = Math.floor(elapsedMs / 1000);
212243
if (seconds < 60) return { value: "just now", suffix: null };
213244
const minutes = Math.floor(seconds / 60);
214245
if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
@@ -218,19 +249,17 @@ export function formatRelativeTime(isoDate: string): RelativeTimeParts | null {
218249
return { value: `${days}d`, suffix: "ago" };
219250
}
220251

252+
export function formatRelativeTime(isoDate: string): RelativeTimeParts | null {
253+
const elapsedMs = relativeTimeElapsedMs(isoDate);
254+
return elapsedMs === null ? null : formatRelativeElapsed(elapsedMs);
255+
}
256+
221257
export function formatRelativeTimeLabel(isoDate: string) {
222258
const relative = formatRelativeTime(isoDate);
223259
if (!relative) return "";
224260
return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
225261
}
226262

227-
export function getRelativeTimeState(isoDate: string | null): RelativeTimeState {
228-
if (!isoDate) return { status: "missing" };
229-
const relative = formatRelativeTime(isoDate);
230-
if (!relative) return { status: "invalid" };
231-
return { status: "relative", ...relative };
232-
}
233-
234263
export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
235264
const date = parseTimestampDate(isoDate);
236265
if (!date) return "";

0 commit comments

Comments
 (0)