Skip to content
TypeScript

perf(web): relative "checked" labels re-render only when their text changes (#20819)

Julius Marminge2171c50726d8
diff --git a/apps/web/src/components/settings/DiagnosticsSettings.tsx b/apps/web/src/components/settings/DiagnosticsSettings.tsx
index 277fc731f76..fbac3df05fd 100644
--- a/apps/web/src/components/settings/DiagnosticsSettings.tsx
+++ b/apps/web/src/components/settings/DiagnosticsSettings.tsx
@@ -23,7 +23,8 @@ import * as Option from "effect/Option";
import { cn } from "../../lib/utils";
import { ensureLocalApi } from "../../localApi";
import { useOpenInPreferredEditor } from "../../editorPreferences";
-import { formatRelativeTimeLabel, getRelativeTimeState } from "../../timestampFormat";
+import { formatRelativeTimeLabel } from "../../timestampFormat";
+import { useRelativeTimeState } from "../../hooks/useRelativeTimeState";
import { useEnvironmentQuery } from "../../state/query";
import { serverEnvironment } from "../../state/server";
import { useCopyToClipboard } from "../../hooks/useCopyToClipboard";
@@ -35,7 +36,7 @@ import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
import { toastManager } from "../ui/toast";
import { ExpandableText } from "./ExpandableText";
import { ResourceTelemetryDiagnostics } from "./ResourceTelemetryDiagnostics";
-import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";
+import { SettingsPageContainer, SettingsSection } from "./settingsLayout";
import { useAtomCommand } from "../../state/use-atom-command";
import { useSettingsScope } from "./SettingsScopeContext";
import { TelemetryExportSettings } from "./TelemetryExportSettings";
@@ -664,8 +665,7 @@ function ProcessResourceHistoryTable({
}
function DiagnosticsLastChecked({ checkedAt }: { checkedAt: DateTime.Utc | null }) {
- useRelativeTimeTick();
- const relative = getRelativeTimeState(checkedAt ? DateTime.formatIso(checkedAt) : null);
+ const relative = useRelativeTimeState(checkedAt ? DateTime.formatIso(checkedAt) : null);
if (relative.status === "missing") {
return <span className="text-2xs text-muted-foreground/50">Checking</span>;
diff --git a/apps/web/src/components/settings/ProviderSettingsPanel.tsx b/apps/web/src/components/settings/ProviderSettingsPanel.tsx
index 6c0064a08fb..3cfe42d1991 100644
--- a/apps/web/src/components/settings/ProviderSettingsPanel.tsx
+++ b/apps/web/src/components/settings/ProviderSettingsPanel.tsx
@@ -57,7 +57,7 @@ import { EMPTY_SERVER_PROVIDERS, serverEnvironment } from "../../state/server";
import { useEnvironmentSessionState } from "../../state/session";
import { useProjects, useServerConfigs } from "../../state/entities";
import { useAtomCommand } from "../../state/use-atom-command";
-import { getRelativeTimeState } from "../../timestampFormat";
+import { useRelativeTimeState } from "../../hooks/useRelativeTimeState";
import {
ConnectionStatusDot,
connectionPhaseDotClassName,
@@ -112,7 +112,6 @@ import {
SettingsPageContainer,
SettingsRow,
SettingsSection,
- useRelativeTimeTick,
useSettingsSearchTargetId,
} from "./settingsLayout";
import {
@@ -151,8 +150,7 @@ function configuredBinaryPath(config: unknown): string {
}
function ProviderLastChecked({ lastCheckedAt }: { lastCheckedAt: string | null }) {
- useRelativeTimeTick();
- const lastCheckedRelative = getRelativeTimeState(lastCheckedAt);
+ const lastCheckedRelative = useRelativeTimeState(lastCheckedAt);
if (lastCheckedRelative.status === "missing") {
return null;
diff --git a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx
index 327b32ba39b..0a02bb2ba90 100644
--- a/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx
+++ b/apps/web/src/components/settings/ResourceTelemetryDiagnostics.tsx
@@ -44,7 +44,7 @@ import { ensureLocalApi } from "../../localApi";
import { serverEnvironment } from "../../state/server";
import { readEnvironmentScope, useEnvironmentScope } from "../../state/session";
import { useAtomCommand } from "../../state/use-atom-command";
-import { formatRelativeTime } from "../../timestampFormat";
+import { useRelativeTimeState } from "../../hooks/useRelativeTimeState";
import { Button } from "../ui/button";
import { MorphIcon } from "~/components/MorphIcon";
import { ScrollArea } from "../ui/scroll-area";
@@ -57,7 +57,7 @@ import {
shouldShowResourceMonitorRetry,
visibleResourceTelemetryProcesses,
} from "./ResourceTelemetryDiagnostics.logic";
-import { SettingsSection, useRelativeTimeTick } from "./settingsLayout";
+import { SettingsSection } from "./settingsLayout";
const HISTORY_WINDOWS = [
{ label: "5m", windowMs: 5 * 60_000, bucketMs: 15_000 },
@@ -207,12 +207,8 @@ function SourceStatusBadge({
}
function LastSampleLabel({ sampledAt }: { sampledAt: DateTime.Utc | null }) {
- useRelativeTimeTick();
- if (!sampledAt) {
- return <span className="text-2xs text-muted-foreground/55">Waiting for sample</span>;
- }
- const relative = formatRelativeTime(DateTime.formatIso(sampledAt));
- if (!relative) {
+ const relative = useRelativeTimeState(sampledAt ? DateTime.formatIso(sampledAt) : null);
+ if (relative.status !== "relative") {
return <span className="text-2xs text-muted-foreground/55">Waiting for sample</span>;
}
return (
diff --git a/apps/web/src/hooks/useRelativeTimeState.ts b/apps/web/src/hooks/useRelativeTimeState.ts
new file mode 100644
index 00000000000..9d7847d8fd1
--- /dev/null
+++ b/apps/web/src/hooks/useRelativeTimeState.ts
@@ -0,0 +1,36 @@
+import { useSyncExternalStore } from "react";
+
+import {
+ formatRelativeElapsed,
+ msUntilRelativeTimeChange,
+ relativeTimeElapsedMs,
+ type RelativeTimeState,
+} from "../timestampFormat";
+
+/**
+ * A "5m ago" label that re-renders only when its text changes: the snapshot is
+ * the elapsed time floored to the label's precision, and one timer fires at the
+ * next boundary instead of polling every second.
+ */
+export function useRelativeTimeState(isoDate: string | null): RelativeTimeState {
+ const subscribe = (onChange: () => void) => {
+ if (isoDate === null) return () => {};
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const schedule = () => {
+ const delayMs = msUntilRelativeTimeChange(isoDate);
+ if (delayMs === null) return;
+ timer = setTimeout(() => {
+ onChange();
+ schedule();
+ }, delayMs);
+ };
+ schedule();
+ return () => clearTimeout(timer);
+ };
+ const getSnapshot = () => (isoDate === null ? null : relativeTimeElapsedMs(isoDate));
+ const elapsedMs = useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
+
+ if (isoDate === null) return { status: "missing" };
+ if (elapsedMs === null) return { status: "invalid" };
+ return { status: "relative", ...formatRelativeElapsed(elapsedMs) };
+}
diff --git a/apps/web/src/timestampFormat.test.ts b/apps/web/src/timestampFormat.test.ts
index 985eaf230f7..d033bc6d362 100644
--- a/apps/web/src/timestampFormat.test.ts
+++ b/apps/web/src/timestampFormat.test.ts
@@ -11,7 +11,8 @@ import {
formatShortTimestamp,
formatTimestamp,
formatUpcomingTimestamp,
- getRelativeTimeState,
+ msUntilRelativeTimeChange,
+ relativeTimeElapsedMs,
resolveTimestampLocale,
} from "./timestampFormat";
@@ -253,9 +254,9 @@ describe("invalid timestamp inputs", () => {
expect(formatRelativeTimeLabel("not-a-date")).toBe("");
});
- it("distinguishes missing and invalid relative time state", () => {
- expect(getRelativeTimeState(null)).toEqual({ status: "missing" });
- expect(getRelativeTimeState("not-a-date")).toEqual({ status: "invalid" });
+ it("has no relative time boundary for an invalid timestamp", () => {
+ expect(relativeTimeElapsedMs("not-a-date")).toBeNull();
+ expect(msUntilRelativeTimeChange("not-a-date")).toBeNull();
});
it("returns an empty elapsed duration instead of a NaN label", () => {
@@ -272,22 +273,27 @@ describe("invalid timestamp inputs", () => {
});
});
-describe("getRelativeTimeState", () => {
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-04-07T12:00:00.000Z"));
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it("returns relative parts for valid timestamps", () => {
- expect(getRelativeTimeState("2026-04-07T11:45:00.000Z")).toEqual({
- status: "relative",
- value: "15m",
- suffix: "ago",
- });
+describe("relative time boundaries", () => {
+ const nowMs = Date.parse("2026-04-07T12:00:00.000Z");
+
+ it("waits for the label to change instead of the next second", () => {
+ // "just now" turns into "1m ago" at the one-minute mark.
+ expect(msUntilRelativeTimeChange("2026-04-07T11:59:40.000Z", nowMs)).toBe(40_000);
+ // "2m ago" turns into "3m ago" a minute after the 2m mark.
+ expect(msUntilRelativeTimeChange("2026-04-07T11:57:30.000Z", nowMs)).toBe(30_000);
+ // "3h ago" holds until the 4h mark.
+ expect(msUntilRelativeTimeChange("2026-04-07T08:30:00.000Z", nowMs)).toBe(30 * 60_000);
+ // "2d ago" holds until the 3d mark.
+ expect(msUntilRelativeTimeChange("2026-04-05T00:00:00.000Z", nowMs)).toBe(12 * 3_600_000);
+ // A future timestamp reads "just now" until a minute after it.
+ expect(msUntilRelativeTimeChange("2026-04-07T12:00:10.000Z", nowMs)).toBe(70_000);
+ });
+
+ it("keeps the elapsed snapshot stable while the label is unchanged", () => {
+ const at = "2026-04-07T11:57:30.000Z";
+ expect(relativeTimeElapsedMs(at, nowMs)).toBe(2 * 60_000);
+ expect(relativeTimeElapsedMs(at, nowMs + 29_999)).toBe(2 * 60_000);
+ expect(relativeTimeElapsedMs(at, nowMs + 30_000)).toBe(3 * 60_000);
});
});
diff --git a/apps/web/src/timestampFormat.ts b/apps/web/src/timestampFormat.ts
index 8250cced447..2d80bdfeaf1 100644
--- a/apps/web/src/timestampFormat.ts
+++ b/apps/web/src/timestampFormat.ts
@@ -203,12 +203,43 @@ export type RelativeTimeState =
| { status: "invalid" }
| { status: "relative"; value: string; suffix: string | null };
-export function formatRelativeTime(isoDate: string): RelativeTimeParts | null {
+const MINUTE_MS = 60_000;
+const HOUR_MS = 3_600_000;
+const DAY_MS = 86_400_000;
+
+function relativeTimeUnitMs(elapsedMs: number): number {
+ if (elapsedMs < HOUR_MS) return MINUTE_MS;
+ if (elapsedMs < DAY_MS) return HOUR_MS;
+ return DAY_MS;
+}
+
+/**
+ * Elapsed time floored to the precision `formatRelativeTime` shows, so two
+ * instants with the same label return the same number.
+ */
+export function relativeTimeElapsedMs(isoDate: string, nowMs: number = Date.now()): number | null {
const date = parseTimestampDate(isoDate);
if (!date) return null;
- const diffMs = Date.now() - date.getTime();
- if (diffMs < 0) return { value: "just now", suffix: null };
- const seconds = Math.floor(diffMs / 1000);
+ const elapsedMs = Math.max(0, nowMs - date.getTime());
+ const unitMs = relativeTimeUnitMs(elapsedMs);
+ return Math.floor(elapsedMs / unitMs) * unitMs;
+}
+
+/** Milliseconds until the `formatRelativeTime` label for `isoDate` next changes. */
+export function msUntilRelativeTimeChange(
+ isoDate: string,
+ nowMs: number = Date.now(),
+): number | null {
+ const date = parseTimestampDate(isoDate);
+ if (!date) return null;
+ const elapsedMs = Math.max(0, nowMs - date.getTime());
+ const unitMs = relativeTimeUnitMs(elapsedMs);
+ const nextChangeMs = date.getTime() + (Math.floor(elapsedMs / unitMs) + 1) * unitMs;
+ return nextChangeMs - nowMs;
+}
+
+export function formatRelativeElapsed(elapsedMs: number): RelativeTimeParts {
+ const seconds = Math.floor(elapsedMs / 1000);
if (seconds < 60) return { value: "just now", suffix: null };
const minutes = Math.floor(seconds / 60);
if (minutes < 60) return { value: `${minutes}m`, suffix: "ago" };
@@ -218,19 +249,17 @@ export function formatRelativeTime(isoDate: string): RelativeTimeParts | null {
return { value: `${days}d`, suffix: "ago" };
}
+export function formatRelativeTime(isoDate: string): RelativeTimeParts | null {
+ const elapsedMs = relativeTimeElapsedMs(isoDate);
+ return elapsedMs === null ? null : formatRelativeElapsed(elapsedMs);
+}
+
export function formatRelativeTimeLabel(isoDate: string) {
const relative = formatRelativeTime(isoDate);
if (!relative) return "";
return relative.suffix ? `${relative.value} ${relative.suffix}` : relative.value;
}
-export function getRelativeTimeState(isoDate: string | null): RelativeTimeState {
- if (!isoDate) return { status: "missing" };
- const relative = formatRelativeTime(isoDate);
- if (!relative) return { status: "invalid" };
- return { status: "relative", ...relative };
-}
-
export function formatElapsedDurationLabel(isoDate: string, nowMs: number = Date.now()): string {
const date = parseTimestampDate(isoDate);
if (!date) return "";