Database governance built for humans and agents — controlling changes and access across every major database.
Go cicddata-governancedata-maskingdata-securitydatabase-accessdatabase-governancedevopsdevsecopsflywaygitopsliquibasemongodbmysqloraclepostgresqlschema-migrationssecuritysql-clientsqlservertidb
refactor(frontend): make time-varying displays correct by construction
zchpeter99e1834ff2e0
diff --git a/docs/design/timestamp-display.md b/docs/design/timestamp-display.mdindex cd53c93c7d..7057fdf700 100644--- a/docs/design/timestamp-display.md+++ b/docs/design/timestamp-display.md@@ -270,23 +270,35 @@ no seconds per D5. Relative age may accompany it in the tooltip.`relative-time` element, which schedules updates at the next boundary, is the referencebehavior. The contract that makes this hold:- **Every time-varying reading comes as a pair** — the function that renders it and the- function returning the first instant its output will differ (`Infinity` if never). The pair- lives together and is tested together: sampled across ages, the reading is constant up to- that instant and differs at it, followed across several successive boundaries so a reading- that leaves a value and later returns to it cannot hide a skipped span. The samples include- sub-millisecond timestamps, starts off the whole minute, and a turn of the year, where a- boundary a fraction early, one computed from a rounded clock, or a seasonal change otherwise- hides. A boundary- borrowed from a different reading, or re-derived by hand beside one, is the defect this rules- out — the two drift silently, and a test of the boundary alone cannot see it.- - **A boundary is evaluated no later than its reading.** Evaluated after, it can see a change- the reading just missed, name the change after that, and leave the stale reading on screen.+ function returning the first instant its output will differ (`Infinity` if never), defined+ together as one reading object and tested together: sampled across ages, the reading is+ constant up to that instant and differs at it, followed across several successive boundaries+ so a reading that leaves a value and later returns to it cannot hide a skipped span. The+ samples include sub-millisecond timestamps, starts off the whole minute, and a turn of the+ year, where a boundary a fraction early, one computed from a rounded clock, or a seasonal+ change otherwise hides.+ - **A display gets a reading only through `useTimeReading`**, which takes the reading object,+ evaluates its boundary before its value, and subscribes to the shared clock. Pairing,+ subscription and evaluation order therefore hold by construction rather than by convention at+ each call site: a boundary borrowed from a different reading or re-derived beside one, a+ display that forgot to subscribe, and a boundary evaluated after its value — which can see a+ change the value just missed and schedule the one after — are each impossible to write+ without leaving the hook.- **The shared clock accepts any instant.** Deadlines are wall-clock instants but timers skiptime the machine sleeps, so the clock re-checks at least once a minute: a display is at most- a minute behind after sleep or a clock adjustment. It wakes only the subscribers that are due,- re-checks a woken display that names the same instant again after a resync interval rather- than on every other display's wake, and leaves a short gap after each wake so a boundary that- keeps naming a past instant cannot spin it.+ a minute behind after sleep or a clock adjustment. A boundary is only valid on a clock at+ least as late as the one it was computed on, so a clock stepped backward wakes every+ subscribed display at the next check. A reading that has settled for good holds no+ subscription, so a clock stepped back past its last change leaves it as it was until something+ else renders it — the price of settled displays costing nothing. The clock wakes only the+ subscribers that are due, re-checks a+ woken display that names the same instant again after a resync interval rather than on every+ other display's wake, and leaves a short gap after each wake so a boundary that keeps naming+ a past instant cannot spin it.+ - **An absent timestamp has no reading.** The conversion yields nothing rather than a+ substitute — the current time and the epoch are both plausible-looking lies — and the+ container picks the empty form: "-" in a table cell, or the label dropped along with its+ separator in an inline line.- Guarded by fake-timer tests and a sweep of render-time `Date.now()` over the touched surfacesat implementation time — a review pass, not a lint: telling render scope from handlers andeffects statically would flag most legitimate uses.@@ -344,10 +356,11 @@ points where the implementation had to choose:examples above show it trailing. That is ICU's pattern for the locale; the strings come from`Intl` rather than being assembled, so the locale's own order wins.-The staleness rule holds through `useNow` and the reading pairs described under Implementation-shape. The clock replaced the ad-hoc interval behind the plan-detail created time, and the pairs-cover the displays that had no clock at all: the SQL-editor grant countdown, the masking-exemption-expiry label, the sample-instance expiry alert, and the access-grant expired badge.+The staleness rule holds through `useTimeReading` and the reading objects described under+Implementation shape. The clock replaced the ad-hoc interval behind the plan-detail created time,+and the readings cover the displays that had no clock at all: the SQL-editor grant countdown, the+masking-exemption expiry label, the sample-instance expiry alert, and the access-grant expired+badge.The rule governs displays of time. Two kinds of clock read stay outside it: **query membership** —the masking-exemption status filter, the role-expiry reminder's "within two days" list — which,diff --git a/frontend/src/components/AuditLogTable.test.tsx b/frontend/src/components/AuditLogTable.test.tsxindex bcf595957e..b9049b46ee 100644--- a/frontend/src/components/AuditLogTable.test.tsx+++ b/frontend/src/components/AuditLogTable.test.tsx@@ -123,13 +123,12 @@ vi.mock("@/api/methods", () => ({}));vi.mock("@/utils", () => ({- formatAbsoluteDateTime: () => "2026-04-27 00:00:00",getDefaultPagination: () => 1000,humanizeDurationV1: () => "0ms",}));vi.mock("@/types", () => ({- getDateForPbTimestampProtoEs: () => new Date("2026-04-27T00:00:00Z"),+ getTimeForPbTimestampProtoEs: () => new Date("2026-04-27T00:00:00Z").getTime(),}));globalThis.ResizeObserver = class ResizeObserver {diff --git a/frontend/src/components/HumanizeTs.test.tsx b/frontend/src/components/HumanizeTs.test.tsxindex 947c66adf5..a43fb9e88e 100644--- a/frontend/src/components/HumanizeTs.test.tsx+++ b/frontend/src/components/HumanizeTs.test.tsx@@ -6,19 +6,26 @@ vi.mock("react-i18next", () => ({useTranslation: () => ({ t: (k: string) => k, i18n: { language: "en" } }),}));-const formatters = vi.hoisted(() => ({- // Age-based so a label that never re-renders is visibly distinguishable from- // one that keeps up with the clock.- formatQueueTime: (ms: number) => `queue:${Date.now() - ms}`,- formatRelativeTime: (ms: number) => `relative:${Date.now() - ms}`,- formatCompactDateTime: (ms: number) => `compact:${ms}`,- formatOperationalDateTime: (ms: number) => `operational:${ms}`,- formatAbsoluteDateTime: vi.fn((ms: number) => `absolute:${ms}`),- // Distinct offsets, so a reading scheduled on the other reading's boundary- // wakes at the wrong time and shows it.- nextQueueTimeChangeAt: (ms: number) => ms + 60_000,- nextRelativeTimeChangeAt: (ms: number) => ms + 45_000,-}));+const formatters = vi.hoisted(() => {+ // A reading whose label is its age, so a display that was not re-rendered+ // shows a stale age, and whose boundary is a fixed offset after the timestamp.+ // The two offsets differ, so a label scheduled on the other reading's+ // boundary re-renders at the wrong second and shows it.+ const ageReading = (prefix: string, boundaryOffsetMs: number) => ({+ read: (ms: number) => `${prefix}:${Date.now() - ms}`,+ nextChangeAt: (ms: number) =>+ Date.now() < ms + boundaryOffsetMs+ ? ms + boundaryOffsetMs+ : Number.POSITIVE_INFINITY,+ });+ return {+ queueTimeReading: ageReading("queue", 60_000),+ relativeTimeReading: ageReading("relative", 45_000),+ formatCompactDateTime: (ms: number) => `compact:${ms}`,+ formatOperationalDateTime: (ms: number) => `operational:${ms}`,+ formatAbsoluteDateTime: vi.fn((ms: number) => `absolute:${ms}`),+ };+});vi.mock("@/utils/datetime", () => formatters);@@ -48,6 +55,16 @@ const openTooltip = async (el: Element | null) => {const overlayText = () =>document.getElementById("bb-react-layer-overlay")?.textContent ?? "";+// One act per second, as a browser commits between timer turns; a single long+// act would commit only once, at its end, and hide when the render happened.+const advanceSeconds = (seconds: number) => {+ for (let second = 0; second < seconds; second++) {+ act(() => {+ vi.advanceTimersByTime(1_000);+ });+ }+};+const secondsAgo = (seconds: number) =>Math.floor(Date.now() / 1000) - seconds;@@ -110,10 +127,11 @@ describe("HumanizeTs", () => {// The tooltip opens 100ms after focus, which the age already reflects.expect(overlayText()).toContain("relative:30100");- // The relative reading's own boundary is 45s after the timestamp.- act(() => {- vi.advanceTimersByTime(15_000);- });+ // The relative reading's boundary is 45s after the timestamp: the age holds+ // until then and moves on at it.+ advanceSeconds(14);+ expect(overlayText()).toContain("relative:30100");+ advanceSeconds(1);expect(overlayText()).toContain("relative:45100");});@@ -131,10 +149,10 @@ describe("HumanizeTs", () => {act(() => root.render(<HumanizeTs ts={secondsAgo(30)} tooltip={false} />));expect(container.textContent).toBe("queue:30000");- // The work-queue reading's own boundary is 60s after the timestamp.- act(() => {- vi.advanceTimersByTime(30_000);- });+ // The work-queue reading's boundary is 60s after the timestamp.+ advanceSeconds(29);+ expect(container.textContent).toBe("queue:30000");+ advanceSeconds(1);expect(container.textContent).toBe("queue:60000");});diff --git a/frontend/src/components/HumanizeTs.tsx b/frontend/src/components/HumanizeTs.tsxindex 266a21f0c3..9d4dc3c559 100644--- a/frontend/src/components/HumanizeTs.tsx+++ b/frontend/src/components/HumanizeTs.tsx@@ -1,15 +1,14 @@import type { ComponentType } from "react";import { useTranslation } from "react-i18next";import { Tooltip } from "@/components/ui/tooltip";-import { useNow } from "@/hooks/useNow";+import { useTimeReading } from "@/hooks/useTimeReading";import {formatAbsoluteDateTime,formatCompactDateTime,formatOperationalDateTime,- formatQueueTime,- formatRelativeTime,- nextQueueTimeChangeAt,- nextRelativeTimeChangeAt,+ queueTimeReading,+ relativeTimeReading,+ type TimeReading,} from "@/utils/datetime";/**@@ -46,29 +45,32 @@ function FullDateTime({ tsMs }: { tsMs: number }) {}function RelativeAge({ tsMs }: { tsMs: number }) {- useNow(nextRelativeTimeChangeAt(tsMs));- return <>{formatRelativeTime(tsMs)}</>;+ return <>{useTimeReading(relativeTimeReading, tsMs)}</>;}-// Each mode's label, the boundary that keeps it current if it changes with-// time, and the reading its tooltip restores: the full date-time for every-// reduced form, the age for the full one.+const fixed = (+ format: (tsMs: number) => string+): TimeReading<number, string> => ({+ read: format,+ nextChangeAt: () => Number.POSITIVE_INFINITY,+});++// Each mode's label reading, and the reading its tooltip restores: the full+// date-time for every reduced form, the age for the full one.const MODES: Record<TimeDisplayMode,{- format: (tsMs: number) => string;- nextChangeAt?: (tsMs: number) => number;+ label: TimeReading<number, string>;Hidden: ComponentType<{ tsMs: number }>;}> = {- queue: {- format: formatQueueTime,- nextChangeAt: nextQueueTimeChangeAt,+ queue: { label: queueTimeReading, Hidden: FullDateTime },+ compact: { label: fixed(formatCompactDateTime), Hidden: FullDateTime },+ operational: {+ label: fixed(formatOperationalDateTime),Hidden: FullDateTime,},- compact: { format: formatCompactDateTime, Hidden: FullDateTime },- operational: { format: formatOperationalDateTime, Hidden: FullDateTime },- datetime: { format: formatAbsoluteDateTime, Hidden: RelativeAge },+ datetime: { label: fixed(formatAbsoluteDateTime), Hidden: RelativeAge },};/**@@ -85,9 +87,8 @@ export function HumanizeTs({// Subscribe to locale changes so the rendered strings update on a language switch.useTranslation();const tsMs = ts * 1000;- const { format, nextChangeAt, Hidden } = MODES[mode];- useNow(nextChangeAt?.(tsMs));- const label = format(tsMs);+ const { label: labelReading, Hidden } = MODES[mode];+ const label = useTimeReading(labelReading, tsMs);if (!tooltip) {return <span className={className}>{label}</span>;}diff --git a/frontend/src/components/SampleExpirationAlert.tsx b/frontend/src/components/SampleExpirationAlert.tsxindex af7f281e56..f09f32f9f2 100644--- a/frontend/src/components/SampleExpirationAlert.tsx+++ b/frontend/src/components/SampleExpirationAlert.tsx@@ -1,14 +1,10 @@import { useTranslation } from "react-i18next";import { Alert } from "@/components/ui/alert";-import { useNow } from "@/hooks/useNow";+import { useTimeReading } from "@/hooks/useTimeReading";import { normalizeInstanceName } from "@/lib/resourceName";import { useAppStore } from "@/stores/app";import { getTimeForPbTimestampProtoEs } from "@/types";-import {- formatAbsoluteDateTime,- nextDaysLeftChangeAt,- readDaysLeft,-} from "@/utils/datetime";+import { daysLeftReading, formatAbsoluteDateTime } from "@/utils/datetime";type SampleExpirationAlertProps = Readonly<{instanceName: string;@@ -24,19 +20,14 @@ export function SampleExpirationAlert({({ instance }) => instance === canonicalInstanceName)?.expireTime;- const expireTimeMs = expireTime- ? getTimeForPbTimestampProtoEs(expireTime)- : undefined;- useNow(- expireTimeMs === undefined ? undefined : nextDaysLeftChangeAt(expireTimeMs)- );+ const expireTimeMs = getTimeForPbTimestampProtoEs(expireTime);+ const daysLeft = useTimeReading(daysLeftReading, expireTimeMs);- if (expireTimeMs === undefined) {+ if (expireTimeMs === undefined || daysLeft === undefined) {return null;}const formattedExpireTime = formatAbsoluteDateTime(expireTimeMs);- const daysLeft = readDaysLeft(expireTimeMs);const description =daysLeft.kind === "passed"? t("instance.sample-expiration-expired", {diff --git a/frontend/src/components/release/ReleaseInfoCard.tsx b/frontend/src/components/release/ReleaseInfoCard.tsxindex 5fe4455ba3..f93df9e081 100644--- a/frontend/src/components/release/ReleaseInfoCard.tsx+++ b/frontend/src/components/release/ReleaseInfoCard.tsx@@ -96,9 +96,7 @@ function NotFoundBlock() {function ReleaseBlock({ release }: Readonly<{ release: Release }>) {const { t } = useTranslation();const displayedFiles = release.files.slice(0, MAX_DISPLAYED_RELEASE_FILES);- const createdTimeMs = release.createTime- ? getTimeForPbTimestampProtoEs(release.createTime)- : undefined;+ const createdTimeMs = getTimeForPbTimestampProtoEs(release.createTime);return (<div className="rounded-sm border border-control-border bg-control-bg/50 px-4 py-3">diff --git a/frontend/src/components/revision/RevisionDetailPanel.tsx b/frontend/src/components/revision/RevisionDetailPanel.tsxindex 75f1de19d6..faa59737c2 100644--- a/frontend/src/components/revision/RevisionDetailPanel.tsx+++ b/frontend/src/components/revision/RevisionDetailPanel.tsx@@ -113,10 +113,7 @@ export function RevisionDetailPanel({const taskFullLink = revision?.taskRun? extractTaskLink(revision.taskRun): "";- // A revision without a create time shows none, rather than the time now.- const createTimeMs = revision?.createTime- ? getTimeForPbTimestampProtoEs(revision.createTime)- : undefined;+ const createTimeMs = getTimeForPbTimestampProtoEs(revision?.createTime);const formattedStatementSize = statement? bytesToString(new TextEncoder().encode(statement).length): "";diff --git a/frontend/src/hooks/useNow.test.tsx b/frontend/src/hooks/useTimeReading.test.tsxsimilarity index 58%rename from frontend/src/hooks/useNow.test.tsxrename to frontend/src/hooks/useTimeReading.test.tsxindex 4b473c8b32..7a851ce153 100644--- a/frontend/src/hooks/useNow.test.tsx+++ b/frontend/src/hooks/useTimeReading.test.tsx@@ -1,7 +1,7 @@import { act } from "react";import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";-import { useNow } from "./useNow";+import { useTimeReading } from "./useTimeReading";(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }@@ -9,15 +9,24 @@ import { useNow } from "./useNow";const DAY_MS = 86_400_000;+type ProbeSpec = {+ changesAtMs: () => number;+ // An absent input has no reading.+ input?: number;+};+function Probe({- changesAtMs,+ spec,onRender,}: {- changesAtMs: () => number | undefined;- onRender: () => void;+ spec: ProbeSpec;+ onRender: (value: string | undefined) => void;}) {- useNow(changesAtMs());- onRender();+ const value = useTimeReading(+ { read: (input: number) => `read:${input}`, nextChangeAt: spec.changesAtMs },+ "input" in spec ? spec.input : 0+ );+ onRender(value);return null;}@@ -25,31 +34,33 @@ function Probe({// the module-level clock for the next test.const roots: ReturnType<typeof createRoot>[] = [];-const mount = (probes: { changesAtMs: () => number | undefined }[]) => {+const mount = (probes: ProbeSpec[]) => {const container = document.createElement("div");const root = createRoot(container);roots.push(root);const renders = probes.map(() => 0);+ const values: (string | undefined)[] = probes.map(() => undefined);act(() =>root.render(<>- {probes.map((probe, index) => (+ {probes.map((spec, index) => (<Probe- changesAtMs={probe.changesAtMs}// biome-ignore lint/suspicious/noArrayIndexKey: fixed probe listkey={index}- onRender={() => {+ spec={spec}+ onRender={(value) => {renders[index] += 1;+ values[index] = value;}}/>))}</>));- return { root, renders };+ return { root, renders, values };};-describe("useNow", () => {+describe("useTimeReading", () => {beforeEach(() => {vi.useFakeTimers();vi.setSystemTime(new Date("2026-03-02T12:00:00Z"));@@ -143,16 +154,17 @@ describe("useNow", () => {test("re-checks a woken subscriber whose boundary did not advance", () => {// A wall clock stepped back between the wake and its render, or a boundary// held stale by a memo, names the instant that just passed a second time.- let stepBackMs = 0;const deadlineMs = Date.now() + 1_000;const { renders } = mount([- { changesAtMs: () => (Date.now() - stepBackMs < deadlineMs ? deadlineMs : deadlineMs + 60_000) },+ {+ changesAtMs: () =>+ Date.now() < deadlineMs ? deadlineMs : deadlineMs + 60_000,+ },]);act(() => {vi.advanceTimersByTime(1_000);- stepBackMs = 2;- vi.setSystemTime(Date.now() - stepBackMs);+ vi.setSystemTime(Date.now() - 2);});expect(renders).toEqual([2]);@@ -188,8 +200,100 @@ describe("useNow", () => {expect(vi.getTimerCount()).toBe(0);});- test("holds nothing for a display that does not vary with time", () => {- mount([{ changesAtMs: () => undefined }]);+ test("holds nothing for an absent input, and reads nothing", () => {+ const { values } = mount([+ { changesAtMs: () => Date.now() + 1_000, input: undefined },+ ]);+ expect(values).toEqual([undefined]);expect(vi.getTimerCount()).toBe(0);});++ test("evaluates the boundary before the value it schedules", () => {+ const calls: string[] = [];+ function OrderProbe() {+ useTimeReading(+ {+ read: () => calls.push("read"),+ nextChangeAt: () => {+ calls.push("boundary");+ return Number.POSITIVE_INFINITY;+ },+ },+ 0+ );+ return null;+ }+ const root = createRoot(document.createElement("div"));+ roots.push(root);+ act(() => root.render(<OrderProbe />));+ expect(calls).toEqual(["boundary", "read"]);+ });++ test("returns the reading's current value, and keeps it current", () => {+ let value = "before";+ const deadlineMs = Date.now() + 1_000;+ const { values } = mount([+ {+ changesAtMs: () => {+ value = Date.now() < deadlineMs ? "before" : "after";+ return Date.now() < deadlineMs ? deadlineMs : Number.POSITIVE_INFINITY;+ },+ },+ ]);+ expect(values).toEqual(["read:0"]);+ expect(value).toBe("before");++ act(() => {+ vi.advanceTimersByTime(1_000);+ });+ expect(value).toBe("after");+ });++ test("wakes every display when the wall clock steps backward", () => {+ // Each boundary was computed on the later clock; on the earlier one it can+ // be far off in either direction.+ const deadlineMs = Date.now() + 5 * 60_000;+ const { renders } = mount([{ changesAtMs: () => deadlineMs }]);++ vi.setSystemTime(Date.now() - 10 * 60_000);+ act(() => {+ vi.advanceTimersByTime(60_000);+ });+ expect(renders[0]).toBe(2);+ });++ test("never stretches the wake gap past its bound after a clock step", () => {+ const firstMs = Date.now() + 1_000;+ mount([{ changesAtMs: () => (Date.now() < firstMs ? firstMs : Number.POSITIVE_INFINITY) }]);+ act(() => {+ vi.advanceTimersByTime(1_000);+ });++ vi.setSystemTime(Date.now() - 3_600_000);+ const secondMs = Date.now() + 100;+ const { renders } = mount([+ { changesAtMs: () => (Date.now() < secondMs ? secondMs : Number.POSITIVE_INFINITY) },+ ]);+ act(() => {+ vi.advanceTimersByTime(350);+ });+ expect(renders).toEqual([2]);+ });++ test("starts no wake gap from a re-check that woke nobody", () => {+ const farMs = Date.now() + 2 * 60_000;+ mount([{ changesAtMs: () => farMs }]);+ act(() => {+ vi.advanceTimersByTime(60_000);+ });++ const soonMs = Date.now() + 10;+ const { renders } = mount([+ { changesAtMs: () => (Date.now() < soonMs ? soonMs : Number.POSITIVE_INFINITY) },+ ]);+ act(() => {+ vi.advanceTimersByTime(20);+ });+ expect(renders).toEqual([2]);+ });});diff --git a/frontend/src/hooks/useNow.ts b/frontend/src/hooks/useTimeReading.tssimilarity index 61%rename from frontend/src/hooks/useNow.tsrename to frontend/src/hooks/useTimeReading.tsindex d84c54339a..1cdfb2c1a3 100644--- a/frontend/src/hooks/useNow.ts+++ b/frontend/src/hooks/useTimeReading.ts@@ -1,4 +1,5 @@import { useEffect, useReducer } from "react";+import type { TimeReading } from "@/utils/datetime";/*** A single clock shared by every time-varying display.@@ -6,9 +7,9 @@ import { useEffect, useReducer } from "react";* Each subscriber declares the instant its rendering next changes, so the clock* holds one timeout, set for the earliest of those, and wakes only the* subscribers that are due. A woken subscriber normally re-renders and declares- * its next instant; one that names the same instant again -- a wall clock- * stepped back before the render, or a boundary held stale -- is re-checked- * after a resync interval rather than on every neighbour's tick.+ * its next instant; one that names the same instant again -- a boundary held+ * stale, say -- is re-checked after a resync interval rather than on every+ * neighbour's wake.*/type Subscriber = {changesAtMs: number;@@ -18,7 +19,8 @@ type Subscriber = {const subscribers = new Set<Subscriber>();let timer: ReturnType<typeof setTimeout> | undefined;let armedForMs = Number.POSITIVE_INFINITY;-let lastTickMs = Number.NEGATIVE_INFINITY;+let armedAtMs = Number.NEGATIVE_INFINITY;+let lastWakeMs = Number.NEGATIVE_INFINITY;// Deadlines are wall-clock instants, but timers do not count time the machine// sleeps and the wall clock can be adjusted, so the clock re-checks at least@@ -42,11 +44,12 @@ function arm(changesAtMs: number): void {if (!Number.isFinite(changesAtMs)) {return;}- armedForMs = changesAtMs;const nowMs = Date.now();+ armedForMs = changesAtMs;+ armedAtMs = nowMs;// Bounded above too, so a clock stepped backward cannot stretch the gap.const gapMs = Math.min(- Math.max(lastTickMs + MIN_WAKE_GAP_MS - nowMs, 0),+ Math.max(lastWakeMs + MIN_WAKE_GAP_MS - nowMs, 0),MIN_WAKE_GAP_MS);const delayMs = Math.min(Math.max(changesAtMs - nowMs, gapMs), RESYNC_MS);@@ -55,27 +58,23 @@ function arm(changesAtMs: number): void {function tick(): void {const nowMs = Date.now();- lastTickMs = nowMs;+ // A timer cannot fire before it was armed, so a wall clock reading earlier+ // than the arm means the clock stepped backward, and every boundary computed+ // on the later clock may now be wrong in either direction.+ const clockSteppedBack = nowMs < armedAtMs;let nextMs = Number.POSITIVE_INFINITY;for (const subscriber of subscribers) {- if (subscriber.changesAtMs <= nowMs) {+ if (clockSteppedBack || subscriber.changesAtMs <= nowMs) {subscriber.changesAtMs = nowMs + RESYNC_MS;subscriber.wake();+ lastWakeMs = nowMs;}nextMs = Math.min(nextMs, subscriber.changesAtMs);}arm(nextMs);}-/**- * Re-renders the caller once `changesAtMs` arrives; `undefined` or `Infinity`- * holds no subscription.- *- * Compute `changesAtMs` before the reading it schedules. Computed after, it can- * see a change the reading just missed, name the change after that, and leave- * the stale reading on screen.- */-export function useNow(changesAtMs: number | undefined): void {+function useNow(changesAtMs: number | undefined): void {// A counter rather than the time: setting a timestamp can bail out when two// wakes land in the same millisecond, and a missed render is a frozen label.const [, wake] = useReducer((count: number) => count + 1, 0);@@ -99,3 +98,29 @@ export function useNow(changesAtMs: number | undefined): void {};}, [changesAtMs]);}++/**+ * The current value of a time-varying reading, kept current: the caller+ * re-renders when the value next changes. An absent input has no value and+ * holds no subscription.+ *+ * This is the only way a display gets such a value, so the value always comes+ * with its own boundary and a subscription. The boundary is evaluated first:+ * evaluated after the value, it can see a change the value just missed, name+ * the change after that, and leave the stale value on screen.+ */+export function useTimeReading<Input, Value>(+ reading: TimeReading<Input, Value>,+ input: Input+): Value;+export function useTimeReading<Input, Value>(+ reading: TimeReading<Input, Value>,+ input: Input | undefined+): Value | undefined;+export function useTimeReading<Input, Value>(+ reading: TimeReading<Input, Value>,+ input: Input | undefined+): Value | undefined {+ useNow(input === undefined ? undefined : reading.nextChangeAt(input));+ return input === undefined ? undefined : reading.read(input);+}diff --git a/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx b/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsxindex 9f3044d4a3..540dde4707 100644--- a/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx+++ b/frontend/src/modules/sql-editor/components/AccessGrantItem.test.tsx@@ -1,5 +1,6 @@import type { ReactElement } from "react";import { act } from "react";+import { timestampFromMs } from "@bufbuild/protobuf/wkt";import { createRoot } from "react-dom/client";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";@@ -9,10 +10,9 @@ import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";const mocks = vi.hoisted(() => ({useTranslation: vi.fn(() => ({ t: (key: string) => key })),- getAccessGrantDisplayStatus: vi.fn(),+ readStatus: vi.fn(),+ actualReadStatus: undefined as unknown as (input: never) => unknown,getAccessGrantDisplayStatusText: vi.fn(),- getActiveAccessGrantDeadlineMs: vi.fn(),- nextAccessGrantDisplayStatusChangeAt: vi.fn(),getAccessGrantStatusTagType: vi.fn(),}));@@ -34,14 +34,21 @@ vi.mock("react-i18next", () => ({useTranslation: mocks.useTranslation,}));-vi.mock("@/utils/accessGrant", () => ({- getAccessGrantDisplayStatus: mocks.getAccessGrantDisplayStatus,- getAccessGrantDisplayStatusText: mocks.getAccessGrantDisplayStatusText,- getActiveAccessGrantDeadlineMs: mocks.getActiveAccessGrantDeadlineMs,- nextAccessGrantDisplayStatusChangeAt:- mocks.nextAccessGrantDisplayStatusChangeAt,- getAccessGrantStatusTagType: mocks.getAccessGrantStatusTagType,-}));+// The real module, with the status value and its labels stubbed per test; the+// status boundary and the deadline stay real, so the clock wiring is exercised.+vi.mock("@/utils/accessGrant", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@/utils/accessGrant")>();+ mocks.actualReadStatus = actual.accessGrantStatusReading.read as never;+ return {+ ...actual,+ accessGrantStatusReading: {+ read: mocks.readStatus,+ nextChangeAt: actual.accessGrantStatusReading.nextChangeAt,+ },+ getAccessGrantDisplayStatusText: mocks.getAccessGrantDisplayStatusText,+ getAccessGrantStatusTagType: mocks.getAccessGrantStatusTagType,+ };+});// Stub Badge and Tooltip as simple pass-throughvi.mock("@/components/ui/badge", () => ({@@ -143,18 +150,15 @@ const renderIntoContainer = (element: ReactElement) => {beforeEach(async () => {vi.clearAllMocks();mocks.useTranslation.mockReturnValue({ t: (key: string) => key });- mocks.getAccessGrantDisplayStatus.mockReturnValue("ACTIVE");+ mocks.readStatus.mockReturnValue("ACTIVE");mocks.getAccessGrantDisplayStatusText.mockReturnValue("Active");- mocks.getActiveAccessGrantDeadlineMs.mockReturnValue(undefined);- mocks.nextAccessGrantDisplayStatusChangeAt.mockReturnValue(- Number.POSITIVE_INFINITY- );mocks.getAccessGrantStatusTagType.mockReturnValue("success");({ AccessGrantItem } = await import("./AccessGrantItem"));});afterEach(() => {+ vi.useRealTimers();document.body.innerHTML = "";});@@ -197,7 +201,7 @@ describe("AccessGrantItem", () => {});test("renders status badge with correct label for ACTIVE status", () => {- mocks.getAccessGrantDisplayStatus.mockReturnValue("ACTIVE");+ mocks.readStatus.mockReturnValue("ACTIVE");mocks.getAccessGrantDisplayStatusText.mockReturnValue("Active");mocks.getAccessGrantStatusTagType.mockReturnValue("success");@@ -241,7 +245,7 @@ describe("AccessGrantItem", () => {});test("Run button shows only for ACTIVE status", () => {- mocks.getAccessGrantDisplayStatus.mockReturnValue("ACTIVE");+ mocks.readStatus.mockReturnValue("ACTIVE");const grant = makeGrant();const onRun = vi.fn();const onRequest = vi.fn();@@ -261,7 +265,7 @@ describe("AccessGrantItem", () => {});test("Run button is absent for non-ACTIVE status", () => {- mocks.getAccessGrantDisplayStatus.mockReturnValue("PENDING");+ mocks.readStatus.mockReturnValue("PENDING");const grant = makeGrant();const onRun = vi.fn();const onRequest = vi.fn();@@ -281,7 +285,7 @@ describe("AccessGrantItem", () => {});test("Re-request button shows for REJECTED status", () => {- mocks.getAccessGrantDisplayStatus.mockReturnValue("REJECTED");+ mocks.readStatus.mockReturnValue("REJECTED");mocks.getAccessGrantDisplayStatusText.mockReturnValue("Rejected");mocks.getAccessGrantStatusTagType.mockReturnValue("error");@@ -304,7 +308,7 @@ describe("AccessGrantItem", () => {});test("Click Run → onRun(grant) called with the grant", async () => {- mocks.getAccessGrantDisplayStatus.mockReturnValue("ACTIVE");+ mocks.readStatus.mockReturnValue("ACTIVE");const grant = makeGrant();const onRun = vi.fn();const onRequest = vi.fn();@@ -329,4 +333,49 @@ describe("AccessGrantItem", () => {expect(onRun).toHaveBeenCalledWith(grant);unmount();});++ test("counts down while mounted, then turns expired at the deadline", () => {+ vi.useFakeTimers();+ vi.setSystemTime(new Date("2026-03-02T12:00:00Z"));+ mocks.readStatus.mockImplementation(mocks.actualReadStatus);+ mocks.useTranslation.mockReturnValue({+ t: (key: string, options?: { time?: string }) =>+ options?.time && key === "sql-editor.expire-in"+ ? `${key}:${options.time}`+ : key,+ });+ const deadlineMs = Date.now() + 3 * 60_000;+ const grant = makeGrant({+ expiration: {+ case: "expireTime",+ value: timestampFromMs(deadlineMs),+ } as never,+ });++ const { container, render, unmount } = renderIntoContainer(+ <AccessGrantItem grant={grant as never} onRun={vi.fn()} onRequest={vi.fn()} />+ );+ render();+ const advanceSeconds = (seconds: number) => {+ for (let second = 0; second < seconds; second++) {+ act(() => {+ vi.advanceTimersByTime(1_000);+ });+ }+ };++ expect(container.textContent).toContain("sql-editor.expire-in:3m");+ advanceSeconds(1);+ expect(container.textContent).toContain("sql-editor.expire-in:2m");+ advanceSeconds(60);+ expect(container.textContent).toContain("sql-editor.expire-in:1m");+ advanceSeconds(60);+ expect(container.textContent).toContain("sql-editor.expire-in:0m");+ expect(container.querySelector("[data-run-btn]")).not.toBeNull();++ advanceSeconds(60);+ expect(container.textContent).toContain("issue.access-grant.expired-at");+ expect(container.querySelector("[data-run-btn]")).toBeNull();+ unmount();+ });});diff --git a/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx b/frontend/src/modules/sql-editor/components/AccessGrantItem.tsxindex 11da7c2216..ee2e355669 100644--- a/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx+++ b/frontend/src/modules/sql-editor/components/AccessGrantItem.tsx@@ -4,22 +4,17 @@ import { RouterLink } from "@/components/RouterLink";import { Badge } from "@/components/ui/badge";import { Button } from "@/components/ui/button";import { Tooltip } from "@/components/ui/tooltip";-import { useNow } from "@/hooks/useNow";+import { useTimeReading } from "@/hooks/useTimeReading";import { cn } from "@/lib/utils";import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";import type { Issue } from "@/types/proto-es/v1/issue_service_pb";import {- getAccessGrantDisplayStatus,+ accessGrantStatusReading,getAccessGrantDisplayStatusText,getAccessGrantStatusTagType,getActiveAccessGrantDeadlineMs,- nextAccessGrantDisplayStatusChangeAt,} from "@/utils/accessGrant";-import {- formatAbsoluteDateTime,- nextCountdownChangeAt,- readCountdown,-} from "@/utils/datetime";+import { countdownReading, formatAbsoluteDateTime } from "@/utils/datetime";function mapTagTypeToBadgeVariant(tagType: "success" | "warning" | "error" | "default"@@ -48,21 +43,16 @@ export function AccessGrantItem({const { t } = useTranslation();const deadlineMs = getActiveAccessGrantDeadlineMs(grant);- useNow(- Math.min(- nextAccessGrantDisplayStatusChangeAt(grant),- deadlineMs === undefined- ? Number.POSITIVE_INFINITY- : nextCountdownChangeAt(deadlineMs)- )- );-- const displayStatus = getAccessGrantDisplayStatus(grant, issue);+ const countdown = useTimeReading(countdownReading, deadlineMs);+ const displayStatus = useTimeReading(accessGrantStatusReading, {+ grant,+ issue,+ });const isActive = displayStatus === "ACTIVE";const isExpired = displayStatus === "EXPIRED";const isRejectedOrCanceled =displayStatus !== "ACTIVE" && displayStatus !== "PENDING";- const statusLabel = getAccessGrantDisplayStatusText(grant, issue);+ const statusLabel = getAccessGrantDisplayStatusText(displayStatus);const statusTagType = getAccessGrantStatusTagType(displayStatus);const badgeVariant = mapTagTypeToBadgeVariant(statusTagType);@@ -71,8 +61,7 @@ export function AccessGrantItem({// it in a tooltip; the other two are interpolated sentences and state the// deadline in full themselves.const expiration = (() => {- if (deadlineMs === undefined) return undefined;- const countdown = readCountdown(deadlineMs);+ if (deadlineMs === undefined || countdown === undefined) return undefined;const deadline = formatAbsoluteDateTime(deadlineMs);switch (countdown.kind) {case "passed":diff --git a/frontend/src/modules/sql-editor/components/HistoryPane.test.tsx b/frontend/src/modules/sql-editor/components/HistoryPane.test.tsxindex 5145d56679..9eb16917bb 100644--- a/frontend/src/modules/sql-editor/components/HistoryPane.test.tsx+++ b/frontend/src/modules/sql-editor/components/HistoryPane.test.tsx@@ -148,9 +148,7 @@ vi.mock("./HistorySearchInput", () => ({vi.mock("@/types", () => ({DEBOUNCE_SEARCH_DELAY: 300,- getTimeForPbTimestampProtoEs: vi.fn((ts: unknown, defaultValue = 0) =>- ts ? new Date("2024-01-15T10:30:00Z").getTime() : defaultValue- ),+ getTimeForPbTimestampProtoEs: () => new Date("2024-01-15T10:30:00Z").getTime(),}));vi.mock("@/utils", () => ({diff --git a/frontend/src/routes/project/DatabaseChangelogDetailPage.tsx b/frontend/src/routes/project/DatabaseChangelogDetailPage.tsxindex 6795550517..9292e493d0 100644--- a/frontend/src/routes/project/DatabaseChangelogDetailPage.tsx+++ b/frontend/src/routes/project/DatabaseChangelogDetailPage.tsx@@ -303,9 +303,9 @@ export function DatabaseChangelogDetailPage({const databaseDisplayName =extractDatabaseResourceName(detail.database?.name ?? "").databaseName ||databaseName;- const createTimeMs = resolvedChangelog?.createTime- ? getTimeForPbTimestampProtoEs(resolvedChangelog.createTime)- : undefined;+ const createTimeMs = getTimeForPbTimestampProtoEs(+ resolvedChangelog?.createTime+ );const formattedSchemaSize = useMemo(() => {if (!resolvedChangelog?.schemaSize) {return "";diff --git a/frontend/src/routes/project/ProjectAccessGrantsPage.tsx b/frontend/src/routes/project/ProjectAccessGrantsPage.tsxindex 56064cfc4e..c4d3309fc4 100644--- a/frontend/src/routes/project/ProjectAccessGrantsPage.tsx+++ b/frontend/src/routes/project/ProjectAccessGrantsPage.tsx@@ -37,9 +37,9 @@ import {distributeColumnWidths,useColumnWidths,} from "@/hooks/useColumnWidths";-import { useNow } from "@/hooks/useNow";import { PagedTableFooter, usePagedData } from "@/hooks/usePagedData";import { useProjectByName } from "@/hooks/useProjectByName";+import { useTimeReading } from "@/hooks/useTimeReading";import { pushNotification } from "@/stores";import { useAppStore } from "@/stores/app";import type { AccessGrantFilter as AccessFilter } from "@/stores/app/types";@@ -55,13 +55,12 @@ import type { Issue } from "@/types/proto-es/v1/issue_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import {type AccessGrantDisplayStatus,- getAccessGrantDisplayStatus,+ accessGrantStatusReading,getAccessGrantDisplayStatusText,getAccessGrantExpireTimeMs,getAccessGrantStatusTagType,getDefaultPagination,hasProjectPermissionV2,- nextAccessGrantDisplayStatusChangeAt,} from "@/utils";import { extractDatabaseResourceName } from "@/utils/v1/database";@@ -747,19 +746,15 @@ function AccessGrantRow({onRevoke: () => void;}) {const { t } = useTranslation();- useNow(nextAccessGrantDisplayStatusChangeAt(grant));- const status = getAccessGrantDisplayStatus(grant, issue);-- const createdTimeMs = grant.createTime- ? getTimeForPbTimestampProtoEs(grant.createTime)- : undefined;+ const status = useTimeReading(accessGrantStatusReading, { grant, issue });+ const createdTimeMs = getTimeForPbTimestampProtoEs(grant.createTime);const expireTimeMs = getAccessGrantExpireTimeMs(grant);return (<TableRow><TableCell><Badge variant={statusTagVariant(status)}>- {getAccessGrantDisplayStatusText(grant, issue)}+ {getAccessGrantDisplayStatusText(status)}</Badge></TableCell><TableCell>diff --git a/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx b/frontend/src/routes/project/ProjectMaskingExemptionPage.tsxindex 1e6181c044..c019fcb33f 100644--- a/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx+++ b/frontend/src/routes/project/ProjectMaskingExemptionPage.tsx@@ -30,8 +30,8 @@ import {} from "@/components/ui/table";import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";import { useCurrentUser } from "@/hooks/useAppState";-import { useNow } from "@/hooks/useNow";import { useProjectByName } from "@/hooks/useProjectByName";+import { useTimeReading } from "@/hooks/useTimeReading";import {buildMemberSummary,generateGrantTitle,@@ -65,7 +65,7 @@ import {import { Setting_SettingName } from "@/types/proto-es/v1/setting_service_pb";import { PlanFeature } from "@/types/proto-es/v1/subscription_service_pb";import { getDefaultPagination, hasProjectPermissionV2 } from "@/utils";-import { nextDaysLeftChangeAt, readDaysLeft } from "@/utils/datetime";+import { daysLeftReading } from "@/utils/datetime";import {batchConvertFromCELString,type ConditionExpression,@@ -1087,14 +1087,10 @@ function ExemptionGrantSection({const title = useMemo(() => generateGrantTitle(grant), [grant]);- useNow(- grant.expirationTimestamp- ? nextDaysLeftChangeAt(grant.expirationTimestamp)- : undefined+ const daysLeft = useTimeReading(+ daysLeftReading,+ grant.expirationTimestamp || undefined);- const daysLeft = grant.expirationTimestamp- ? readDaysLeft(grant.expirationTimestamp)- : undefined;return (<div>diff --git a/frontend/src/routes/project/ProjectPlanDashboardPage.tsx b/frontend/src/routes/project/ProjectPlanDashboardPage.tsxindex 0c36962d2c..df77426cd8 100644--- a/frontend/src/routes/project/ProjectPlanDashboardPage.tsx+++ b/frontend/src/routes/project/ProjectPlanDashboardPage.tsx@@ -511,7 +511,7 @@ function PlanTable({resizable: true,render: (_plan, ctx) =>ctx.updateTimeTs === undefined ? (- "-"+ <span className="text-control-light">-</span>) : (<HumanizeTsts={ctx.updateTimeTs}diff --git a/frontend/src/routes/project/database-detail/changelog/DatabaseChangelogTable.test.tsx b/frontend/src/routes/project/database-detail/changelog/DatabaseChangelogTable.test.tsxindex e4ea61b67a..e9db222c5a 100644--- a/frontend/src/routes/project/database-detail/changelog/DatabaseChangelogTable.test.tsx+++ b/frontend/src/routes/project/database-detail/changelog/DatabaseChangelogTable.test.tsx@@ -27,7 +27,7 @@ vi.mock("@/utils/v1/changelog", () => ({}));vi.mock("@/types", () => ({- getDateForPbTimestampProtoEs: () => new Date("2026-04-15T00:00:00Z"),+ getTimeForPbTimestampProtoEs: () => new Date("2026-04-15T00:00:00Z").getTime(),}));vi.mock("@/components/HumanizeTs", () => ({diff --git a/frontend/src/routes/project/database-detail/panels/DatabaseOverviewPanel.test.tsx b/frontend/src/routes/project/database-detail/panels/DatabaseOverviewPanel.test.tsxindex 2e0c13d0e7..4eff7433d5 100644--- a/frontend/src/routes/project/database-detail/panels/DatabaseOverviewPanel.test.tsx+++ b/frontend/src/routes/project/database-detail/panels/DatabaseOverviewPanel.test.tsx@@ -144,13 +144,17 @@ vi.mock("@/stores/app/databaseCatalog", () => ({}));vi.mock("@/utils/datetime", () => ({- formatQueueTime: mocks.formatRelativeTime,+ queueTimeReading: {+ read: mocks.formatRelativeTime,+ nextChangeAt: () => Number.POSITIVE_INFINITY,+ },+ relativeTimeReading: {+ read: mocks.formatRelativeTime,+ nextChangeAt: () => Number.POSITIVE_INFINITY,+ },formatCompactDateTime: mocks.formatAbsoluteDateTime,formatOperationalDateTime: mocks.formatAbsoluteDateTime,formatAbsoluteDateTime: mocks.formatAbsoluteDateTime,- formatRelativeTime: mocks.formatRelativeTime,- nextQueueTimeChangeAt: () => Number.POSITIVE_INFINITY,- nextRelativeTimeChangeAt: () => Number.POSITIVE_INFINITY,}));vi.mock("@/utils", () => ({diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.test.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.test.tsxindex 4a62efa154..2fc3425c91 100644--- a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.test.tsx+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.test.tsx@@ -71,7 +71,6 @@ vi.mock("@/utils", () => ({vi.mock("@/utils/accessGrant", () => ({getAccessGrantExpirationText: () => ({ type: "never" }),- getAccessGrantExpireTimeMs: () => undefined,}));vi.mock("../context/IssueDetailContext", () => ({diff --git a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsxindex 5e271c762a..4a7c64ce9b 100644--- a/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx+++ b/frontend/src/routes/project/issue-detail/components/IssueDetailAccessGrantDetails.tsx@@ -9,10 +9,7 @@ import { projectNamePrefix } from "@/stores/modules/v1/common";import { isValidDatabaseName } from "@/types";import type { AccessGrant } from "@/types/proto-es/v1/access_grant_service_pb";import { extractProjectResourceName, hasProjectPermissionV2 } from "@/utils";-import {- getAccessGrantExpirationText,- getAccessGrantExpireTimeMs,-} from "@/utils/accessGrant";+import { getAccessGrantExpirationText } from "@/utils/accessGrant";import { useIssueDetailContext } from "../context/IssueDetailContext";export function IssueDetailAccessGrantDetails() {@@ -83,9 +80,6 @@ export function IssueDetailAccessGrantDetails() {const expirationInfo = accessGrant? getAccessGrantExpirationText(accessGrant): { type: "never" as const };- const expireTimeMs = accessGrant- ? getAccessGrantExpireTimeMs(accessGrant)- : undefined;return (<div className="flex flex-col gap-y-4">@@ -168,22 +162,18 @@ export function IssueDetailAccessGrantDetails() {{t("common.expiration")}</span><div className="text-base">- {expirationInfo.type === "never"- ? t("project.members.never-expires")- : expirationInfo.type === "duration"- ? // Pending grant — TTL is still on the proto, safe- // to surface as "{{duration}} after issue approved".- t("issue.access-grant.duration-after-approval", {- duration: expirationInfo.value,- })- : // Active grant — show the absolute expire datetime- // only. The original requested duration is gone- // post-activation (input-only proto field); we- // can't recover it without double-counting the- // approval wait. Bot review #3370767734.- expireTimeMs !== undefined && (- <HumanizeTs mode="operational" ts={expireTimeMs / 1000} />- )}+ {expirationInfo.type === "never" ? (+ t("project.members.never-expires")+ ) : expirationInfo.type === "duration" ? (+ t("issue.access-grant.duration-after-approval", {+ duration: expirationInfo.value,+ })+ ) : (+ <HumanizeTs+ mode="operational"+ ts={expirationInfo.expireTimeMs / 1000}+ />+ )}</div></div></div>diff --git a/frontend/src/types/timestamp.test.ts b/frontend/src/types/timestamp.test.tsindex 8c99a3310e..0757dbc9fe 100644--- a/frontend/src/types/timestamp.test.ts+++ b/frontend/src/types/timestamp.test.ts@@ -14,12 +14,11 @@ describe("getTimeForPbTimestampProtoEs", () => {expect(getTimeForPbTimestampProtoEs(undefined, 0)).toBe(0);});- test("refuses to invent a time when a caller bypasses the types", () => {- // Substituting the current time would show "now" as when something- // happened; the overloads make this unreachable from typed code.- const untyped = getTimeForPbTimestampProtoEs as unknown as (- timestamp?: undefined- ) => number;- expect(() => untyped(undefined)).toThrow();+ test("has no reading for an absent timestamp without a fallback", () => {+ // The current time or the epoch would each show a plausible-looking time.+ const absent:+ | Parameters<typeof getTimeForPbTimestampProtoEs>[0]+ | undefined = undefined;+ expect(getTimeForPbTimestampProtoEs(absent)).toBeUndefined();});});diff --git a/frontend/src/types/timestamp.ts b/frontend/src/types/timestamp.tsindex 1be6c9729a..7854fefb6e 100644--- a/frontend/src/types/timestamp.ts+++ b/frontend/src/types/timestamp.ts@@ -3,9 +3,10 @@ import type { Timestamp as TimestampProtoEs } from "@bufbuild/protobuf/wkt";// Helper functions for proto-es timestamps (which use bigint for seconds)/**- * Milliseconds since the epoch. A timestamp that may be absent needs an explicit- * fallback: substituting the current time silently would show "now" as when- * something happened.+ * Milliseconds since the epoch. An absent timestamp has no reading: without a+ * fallback the result is `undefined`, which the type makes the caller handle.+ * Substituting a time instead -- the current one, or the epoch -- would show a+ * plausible-looking moment that never happened.*/export function getTimeForPbTimestampProtoEs(timestamp: TimestampProtoEs@@ -14,14 +15,14 @@ export function getTimeForPbTimestampProtoEs(timestamp: TimestampProtoEs | undefined,defaultValue: number): number;+export function getTimeForPbTimestampProtoEs(+ timestamp: TimestampProtoEs | undefined+): number | undefined;export function getTimeForPbTimestampProtoEs(timestamp?: TimestampProtoEs,defaultValue?: number-): number {+): number | undefined {if (!timestamp) {- if (defaultValue === undefined) {- throw new Error("An absent timestamp needs an explicit fallback");- }return defaultValue;}return Number(timestamp.seconds) * 1000 + timestamp.nanos / 1000000;diff --git a/frontend/src/utils/accessGrant.test.ts b/frontend/src/utils/accessGrant.test.tsindex 8aa80148b8..1155909161 100644--- a/frontend/src/utils/accessGrant.test.ts+++ b/frontend/src/utils/accessGrant.test.ts@@ -12,19 +12,28 @@ vi.mock("@/lib/i18n", () => ({}));import {- getAccessGrantDisplayStatus,+ accessGrantStatusReading,getAccessGrantExpireTimeMs,- nextAccessGrantDisplayStatusChangeAt,} from "./accessGrant";const HOUR_MS = 3_600_000;const DAY_MS = 86_400_000;-const grantWithDeadline = (status: AccessGrant_Status, deadlineMs: number) =>- create(AccessGrantSchema, {+const grantWithDeadline = (status: AccessGrant_Status, deadlineMs: number) => {+ // Proto timestamps carry sub-millisecond nanos, where a boundary written by+ // hand a fraction late would otherwise hide.+ const expireTime = timestampFromMs(Math.floor(deadlineMs));+ expireTime.nanos += Math.round((deadlineMs % 1) * 1_000_000);+ return create(AccessGrantSchema, {status,- expiration: { case: "expireTime", value: timestampFromMs(deadlineMs) },+ expiration: { case: "expireTime", value: expireTime },});+};++const statusOf = (grant: ReturnType<typeof grantWithDeadline>) =>+ accessGrantStatusReading.read({ grant });+const statusChangesAt = (grant: ReturnType<typeof grantWithDeadline>) =>+ accessGrantStatusReading.nextChangeAt({ grant });describe("access grant status over time", () => {const baseMs = new Date("2026-03-02T12:00:00Z").getTime();@@ -38,20 +47,23 @@ describe("access grant status over time", () => {vi.useRealTimers();});- test("an activated grant reads expired from the instant after its deadline", () => {- const deadlineMs = baseMs + HOUR_MS;- const grant = grantWithDeadline(AccessGrant_Status.ACTIVE, deadlineMs);+ test.each([0, 0.5])(+ "an activated grant reads expired from the instant after its deadline (+%s ms)",+ (fractionMs) => {+ const deadlineMs = baseMs + HOUR_MS + fractionMs;+ const grant = grantWithDeadline(AccessGrant_Status.ACTIVE, deadlineMs);- const changesAtMs = nextAccessGrantDisplayStatusChangeAt(grant);- expect(changesAtMs).toBe(deadlineMs + 1);+ const changesAtMs = statusChangesAt(grant);+ expect(changesAtMs).toBe(baseMs + HOUR_MS + 1);- vi.setSystemTime(changesAtMs - 1);- expect(getAccessGrantDisplayStatus(grant)).toBe("ACTIVE");- expect(nextAccessGrantDisplayStatusChangeAt(grant)).toBe(changesAtMs);+ vi.setSystemTime(changesAtMs - 1);+ expect(statusOf(grant)).toBe("ACTIVE");+ expect(statusChangesAt(grant)).toBe(changesAtMs);- vi.setSystemTime(changesAtMs);- expect(getAccessGrantDisplayStatus(grant)).toBe("EXPIRED");- });+ vi.setSystemTime(changesAtMs);+ expect(statusOf(grant)).toBe("EXPIRED");+ }+ );test.each([["an expired", AccessGrant_Status.ACTIVE, baseMs - HOUR_MS],@@ -61,13 +73,11 @@ describe("access grant status over time", () => {"%s grant's status has nothing left to change",(_, status, deadlineMs) => {const grant = grantWithDeadline(status, deadlineMs);- const status0 = getAccessGrantDisplayStatus(grant);+ const status0 = statusOf(grant);- expect(nextAccessGrantDisplayStatusChangeAt(grant)).toBe(- Number.POSITIVE_INFINITY- );+ expect(statusChangesAt(grant)).toBe(Number.POSITIVE_INFINITY);vi.setSystemTime(baseMs + 400 * DAY_MS);- expect(getAccessGrantDisplayStatus(grant)).toBe(status0);+ expect(statusOf(grant)).toBe(status0);});@@ -82,7 +92,7 @@ describe("access grant status over time", () => {});expect(getAccessGrantExpireTimeMs(grant)).toBeUndefined();- expect(nextAccessGrantDisplayStatusChangeAt(grant)).toBe(+ expect(accessGrantStatusReading.nextChangeAt({ grant })).toBe(Number.POSITIVE_INFINITY);});diff --git a/frontend/src/utils/accessGrant.ts b/frontend/src/utils/accessGrant.tsindex 005332483e..bb2b009a2e 100644--- a/frontend/src/utils/accessGrant.ts+++ b/frontend/src/utils/accessGrant.ts@@ -7,7 +7,7 @@ import {} from "@/types/proto-es/v1/access_grant_service_pb";import { ApprovalStatus, IssueStatus } from "@/types/proto-es/v1/common_pb";import type { Issue } from "@/types/proto-es/v1/issue_service_pb";-import { hasPassed, nextPassedAt } from "@/utils/datetime";+import { passedReading, type TimeReading } from "@/utils/datetime";export type AccessGrantFilterStatus =| "ACTIVE"@@ -35,7 +35,7 @@ export const getAccessGrantExpireTimeMs = (export const getAccessGrantExpirationText = (grant: AccessGrant):- | { type: "datetime" }+ | { type: "datetime"; expireTimeMs: number }| { type: "duration"; value: string }| { type: "never" } => {if (grant.expiration.case === "expireTime") {@@ -48,7 +48,10 @@ export const getAccessGrantExpirationText = (// later would render as "1d4h", which misleads reviewers about// the actual granted window. Show the absolute expire datetime// alone instead. Bot review #3370767734.- return { type: "datetime" };+ return {+ type: "datetime",+ expireTimeMs: getTimeForPbTimestampProtoEs(grant.expiration.value),+ };}if (grant.expiration.case === "ttl") {// Pending grants still carry the requested TTL — safe to format.@@ -74,12 +77,12 @@ export const getActiveAccessGrantDeadlineMs = (? getAccessGrantExpireTimeMs(grant): undefined;-export const getAccessGrantDisplayStatus = (+const getAccessGrantDisplayStatus = (grant: AccessGrant,issue?: Issue): AccessGrantDisplayStatus => {const deadlineMs = getActiveAccessGrantDeadlineMs(grant);- if (deadlineMs !== undefined && hasPassed(deadlineMs)) {+ if (deadlineMs !== undefined && passedReading.read(deadlineMs)) {return "EXPIRED";}switch (grant.status) {@@ -102,21 +105,26 @@ export const getAccessGrantDisplayStatus = (}};-/** The first instant `getAccessGrantDisplayStatus` reads this grant differently. */-export const nextAccessGrantDisplayStatusChangeAt = (- grant: AccessGrant-): number => {- const deadlineMs = getActiveAccessGrantDeadlineMs(grant);- return deadlineMs === undefined- ? Number.POSITIVE_INFINITY- : nextPassedAt(deadlineMs);+/**+ * A grant's status as displayed. Only an activated grant's status changes with+ * time, turning expired when its deadline passes.+ */+export const accessGrantStatusReading: TimeReading<+ { grant: AccessGrant; issue?: Issue },+ AccessGrantDisplayStatus+> = {+ read: ({ grant, issue }) => getAccessGrantDisplayStatus(grant, issue),+ nextChangeAt: ({ grant }) => {+ const deadlineMs = getActiveAccessGrantDeadlineMs(grant);+ return deadlineMs === undefined+ ? Number.POSITIVE_INFINITY+ : passedReading.nextChangeAt(deadlineMs);+ },};export const getAccessGrantDisplayStatusText = (- grant: AccessGrant,- issue?: Issue+ displayStatus: AccessGrantDisplayStatus) => {- const displayStatus = getAccessGrantDisplayStatus(grant, issue);switch (displayStatus) {case "ACTIVE":return i18n.t("common.active");diff --git a/frontend/src/utils/datetime.test.ts b/frontend/src/utils/datetime.test.tsindex ff4a7e25cf..d32d31ccd3 100644--- a/frontend/src/utils/datetime.test.ts+++ b/frontend/src/utils/datetime.test.ts@@ -20,21 +20,19 @@ const withLocale = (language: string, run: () => void) => {};import {+ countdownReading,+ daysLeftReading,formatAbsoluteDate,formatAbsoluteDateTime,formatCompactDateTime,formatOperationalDateTime,formatQueueTime,formatRelativeTime,- hasPassed,- nextCountdownChangeAt,- nextDaysLeftChangeAt,- nextPassedAt,- nextQueueTimeChangeAt,- nextRelativeTimeChangeAt,+ passedReading,+ queueTimeReading,RELATIVE_THRESHOLD_MS,- readCountdown,- readDaysLeft,+ relativeTimeReading,+ type TimeReading,} from "./datetime";const SECOND_MS = 1_000;@@ -249,11 +247,12 @@ const FINAL_PROBES_MS = [400 * DAY_MS,];-const expectBoundaryMatchesReading = (- read: (tsMs: number) => string,- nextChangeAt: (tsMs: number) => number,+const expectBoundaryMatchesReading = <Value>(+ reading: TimeReading<number, Value>,tsMs: number) => {+ const read = (input: number) => JSON.stringify(reading.read(input));+ const { nextChangeAt } = reading;for (let link = 0; link < CHAIN_LINKS; link++) {const startMs = Date.now();const reading = read(tsMs);@@ -322,8 +321,7 @@ describe("reading boundaries", () => {({ start, offset, fractionMs }) => {const startMs = startAt(start);expectBoundaryMatchesReading(- formatQueueTime,- nextQueueTimeChangeAt,+ queueTimeReading,startMs - offset + fractionMs);}@@ -334,8 +332,7 @@ describe("reading boundaries", () => {({ start, offset, fractionMs }) => {const startMs = startAt(start);expectBoundaryMatchesReading(- formatRelativeTime,- nextRelativeTimeChangeAt,+ relativeTimeReading,startMs - offset + fractionMs);}@@ -379,28 +376,19 @@ describe("deadline readings", () => {vi.useRealTimers();});- const pairs = [- [- "countdown",- (targetMs: number) => JSON.stringify(readCountdown(targetMs)),- nextCountdownChangeAt,- ],- [- "days-left",- (targetMs: number) => JSON.stringify(readDaysLeft(targetMs)),- nextDaysLeftChangeAt,- ],- ["passed", (targetMs: number) => String(hasPassed(targetMs)), nextPassedAt],+ const readings = [+ ["countdown", countdownReading],+ ["days-left", daysLeftReading],+ ["passed", passedReading],] as const;- describe.each(pairs)("%s", (_name, read, nextChangeAt) => {+ describe.each(readings)("%s", (_name, reading) => {test.each(boundaryCases(SAMPLED_REMAINING_MS))("names the instant the reading changes ($offset ms left from $start, +$fractionMs ms)",({ start, offset, fractionMs }) => {const startMs = startAt(start);expectBoundaryMatchesReading(- read,- nextChangeAt,+ reading as TimeReading<number, unknown>,startMs + offset + fractionMs);}@@ -409,24 +397,31 @@ describe("deadline readings", () => {test("counts down in hours and minutes within the last day", () => {expect(- readCountdown(baseMs + 3 * HOUR_MS + 20 * MINUTE_MS + 59_999)+ countdownReading.read(baseMs + 3 * HOUR_MS + 20 * MINUTE_MS + 59_999)).toEqual({ kind: "within", hours: 3, minutes: 20 });- expect(readCountdown(baseMs + DAY_MS)).toEqual({ kind: "beyondDay" });- expect(readCountdown(baseMs)).toEqual({+ expect(countdownReading.read(baseMs + DAY_MS)).toEqual({+ kind: "beyondDay",+ });+ expect(countdownReading.read(baseMs)).toEqual({kind: "within",hours: 0,minutes: 0,});- expect(readCountdown(baseMs - 1)).toEqual({ kind: "passed" });+ expect(countdownReading.read(baseMs - 1)).toEqual({ kind: "passed" });});test("rounds whole days up, and treats the deadline itself as passed", () => {- expect(readDaysLeft(baseMs + DAY_MS + 1)).toEqual({+ expect(daysLeftReading.read(baseMs + DAY_MS + 1)).toEqual({kind: "days",days: 2,});- expect(readDaysLeft(baseMs + DAY_MS)).toEqual({ kind: "days", days: 1 });- expect(readDaysLeft(baseMs + DAY_MS - 1)).toEqual({ kind: "today" });- expect(readDaysLeft(baseMs)).toEqual({ kind: "passed" });+ expect(daysLeftReading.read(baseMs + DAY_MS)).toEqual({+ kind: "days",+ days: 1,+ });+ expect(daysLeftReading.read(baseMs + DAY_MS - 1)).toEqual({+ kind: "today",+ });+ expect(daysLeftReading.read(baseMs)).toEqual({ kind: "passed" });});});diff --git a/frontend/src/utils/datetime.ts b/frontend/src/utils/datetime.tsindex 5f23c1ed9a..f6ce81cb0a 100644--- a/frontend/src/utils/datetime.ts+++ b/frontend/src/utils/datetime.ts@@ -54,6 +54,16 @@ const dateTimeFormatter = (): Intl.DateTimeFormat =>cachedFormatter(name, (locale) => new Intl.DateTimeFormat(locale, options));+/**+ * A value that changes with time, paired with the first instant it changes+ * (`Infinity` if never). Displays read one only through `useTimeReading`,+ * which keeps the two together and schedules the display on the shared clock.+ */+export type TimeReading<Input, Value> = {+ read: (input: Input) => Value;+ nextChangeAt: (input: Input) => number;+};+export function formatRelativeTime(timestampMs: number): string {const diffMs = Date.now() - timestampMs;const ageMs = Math.abs(diffMs);@@ -158,16 +168,17 @@ function absoluteDateChangeAt(timestampMs: number, nowMs: number): number {);}-/** The first instant `formatRelativeTime` renders this timestamp differently. */-export function nextRelativeTimeChangeAt(timestampMs: number): number {+function nextRelativeTimeChangeAt(timestampMs: number): number {return relativeTimeChangeAt(timestampMs, Date.now());}-/**- * The first instant `formatQueueTime` renders this timestamp differently, or- * `Infinity` once it has settled on a date for good.- */-export function nextQueueTimeChangeAt(timestampMs: number): number {+/** A timestamp's age, as "5 minutes ago" or "in 2 days". */+export const relativeTimeReading: TimeReading<number, string> = {+ read: formatRelativeTime,+ nextChangeAt: nextRelativeTimeChangeAt,+};++function nextQueueTimeChangeAt(timestampMs: number): number {const nowMs = Date.now();const diffMs = nowMs - timestampMs;if (Math.abs(diffMs) < RELATIVE_THRESHOLD_MS) {@@ -186,20 +197,33 @@ export function nextQueueTimeChangeAt(timestampMs: number): number {return Math.min(reentersAtMs, absoluteDateChangeAt(timestampMs, nowMs));}-// Readings of a deadline. Each is paired with the first instant it changes, so-// a display showing one stays current on the shared clock.+/**+ * A work-queue timestamp: its age within 30 days, a date beyond. Settles for+ * good once it reads as a date from another year.+ */+export const queueTimeReading: TimeReading<number, string> = {+ read: formatQueueTime,+ nextChangeAt: nextQueueTimeChangeAt,+};++// Readings of a deadline.-/** Whether a deadline is behind us; the deadline instant itself is not. */-export function hasPassed(targetMs: number): boolean {+function hasPassed(targetMs: number): boolean {return targetMs < Date.now();}-export function nextPassedAt(targetMs: number): number {+function nextPassedAt(targetMs: number): number {return hasPassed(targetMs)? Number.POSITIVE_INFINITY: Math.floor(targetMs) + 1;}+/** Whether a deadline is behind us; the deadline instant itself is not. */+export const passedReading: TimeReading<number, boolean> = {+ read: hasPassed,+ nextChangeAt: nextPassedAt,+};+/*** Time left before a deadline as a countdown: hours and whole minutes within* the last day, and no count beyond it.@@ -209,7 +233,7 @@ export type Countdown =| { kind: "beyondDay" }| { kind: "within"; hours: number; minutes: number };-export function readCountdown(targetMs: number): Countdown {+function readCountdown(targetMs: number): Countdown {const remainingMs = targetMs - Date.now();if (remainingMs < 0) {return { kind: "passed" };@@ -224,7 +248,7 @@ export function readCountdown(targetMs: number): Countdown {};}-export function nextCountdownChangeAt(targetMs: number): number {+function nextCountdownChangeAt(targetMs: number): number {const remainingMs = targetMs - Date.now();if (remainingMs < 0) {return Number.POSITIVE_INFINITY;@@ -238,6 +262,11 @@ export function nextCountdownChangeAt(targetMs: number): number {return Math.floor(targetMs - thresholdMs) + 1;}+export const countdownReading: TimeReading<number, Countdown> = {+ read: readCountdown,+ nextChangeAt: nextCountdownChangeAt,+};+/*** Time left before a deadline in whole days, rounded up; "today" within the* last day. Unlike `hasPassed`, the deadline instant itself counts as passed.@@ -247,7 +276,7 @@ export type DaysLeft =| { kind: "today" }| { kind: "days"; days: number };-export function readDaysLeft(targetMs: number): DaysLeft {+function readDaysLeft(targetMs: number): DaysLeft {const remainingMs = targetMs - Date.now();if (remainingMs <= 0) {return { kind: "passed" };@@ -258,7 +287,7 @@ export function readDaysLeft(targetMs: number): DaysLeft {return { kind: "days", days: Math.ceil(remainingMs / DAY_MS) };}-export function nextDaysLeftChangeAt(targetMs: number): number {+function nextDaysLeftChangeAt(targetMs: number): number {const remainingMs = targetMs - Date.now();if (remainingMs <= 0) {return Number.POSITIVE_INFINITY;@@ -274,3 +303,8 @@ export function nextDaysLeftChangeAt(targetMs: number): number {? Math.floor(targetMs - DAY_MS) + 1: Math.ceil(targetMs - (days - 1) * DAY_MS);}++export const daysLeftReading: TimeReading<number, DaysLeft> = {+ read: readDaysLeft,+ nextChangeAt: nextDaysLeftChangeAt,+};