Files
fusion/packages/dashboard/app/utils/dataFreshness.ts
gsxdsm f26cbedf4f fix(dashboard): close the code-review findings on the mobile tab-discard work
An 11-reviewer pass over f157bf7460..f5163d8351 found defects in the mobile
tab-discard change set itself. This fixes them.

Silent data loss (the recurring defect class):
- AgentDetailView reconnect refetched limit:100 and replaced wholesale, so 380
  displayed lines vanished with no "Load older" and no indicator; it now
  reconciles through the shared logStreamReconcile helper.
- useActivityLog.loadMore past the cap discarded the page it had just fetched
  while advancing the cursor and leaving hasMore true, so the feed silently
  stopped paginating behind a live-looking button.
- useAgentLogs: loadMore and resyncFromServer had no mutual exclusion, a
  no-overlap resync discarded explicitly paged-back history, a resync outliving
  the reconnect delay left an unmarked gap, and the live-tail trim could evict
  the gap marker itself.
- useLiveTranscript's resync overwrote live entries that raced the refetch.

The premise itself was not fully delivered:
- useProjects, useNodes, and useMeshState never called clearInterval, so they
  polled the whole time the tab was hidden. useProjects is mounted for the
  entire session, so the page never went idle -- the primary mechanism this
  work depends on. All three now use the shared visibility gate.
- sse-bus fired onReconnect twice per reconnect cycle and fanned out ~28
  subscribers in one tick, against a ~6-connection-per-origin cap on a waking
  radio. The successful open is now the single authority, and the fan-out uses
  the same exported stagger primitive as the polling path rather than a second
  copy of the slot formula.
- A channel first subscribed during the hidden window opened a live EventSource
  and keepalive; suspension is now a module-level condition openChannel
  consults, and a channel opened inside the grace window re-arms it.

Credentials and correctness:
- The service worker persisted every GET /api/* to durable Cache Storage,
  including /api/settings with daemonToken, githubAuthToken, gitlabAuthToken
  and ntfyAccessToken in plaintext, with no exclusion and no purge path --
  "Clear all cached data" only walked localStorage. Now gated, bounded, and
  genuinely purgeable.
- useTasks cleared its own snapshot when the mount revalidation failed on a
  waking radio, so the board blanked and the next restore was empty too.
  Suspension-class failures no longer destroy the cache.
- A single-row SSE update reset lastFetchTimeMs to now while an hours-old
  hydrated snapshot was on screen, re-marking every in-progress card stuck.
- ListView's "Select all visible tasks" acted on the full filtered set while
  only 50 rows rendered, so a bulk delete reached rows the operator could not
  see. Column's search window reset keyed on a boolean, so refining a query
  kept the expanded window.

Tests that could not fail:
- App.test.tsx mocked TerminalModal as isOpen ? <div/> : null, making the
  unmount-on-close invariant unobservable; MockEventSource kept its listeners
  after close(), so cases passed with their onReconnect handlers deleted.
- The SSE resync ratchet scanned only hooks/, exempting ~13 component call
  sites -- the exact regression it exists to prevent.
- MissionControlPanel's bespoke poll and the xterm scrollback constants and
  WebGL disposal had no coverage at all.

Verified: tsc -p tsconfig.app.json clean, pnpm lint clean, pnpm
check:changesets clean, 877 tests passing across 36 scoped files.
Known unrelated red: MailboxView.test.tsx's FN-8407 CSS guard fails at HEAD
too -- this diff adds no @media rule and no .mailbox-view--mobile selector,
the only two things that assertion inspects. Left alone deliberately.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 11:17:52 -07:00

50 lines
2.5 KiB
TypeScript

/*
FNXC:MobileTabDiscard 2026-07-26-10:16:
Single source of the `dataAsOfMs` contract. Any "is this thing stale / stuck / unresponsive" verdict
computed in the client must measure a server timestamp against the AGE OF THE DATA IT CAME WITH, not
against wall-clock now.
Why this module exists rather than an inline `dataAsOfMs ?? Date.now()` at each call site: raising the
SWR hydration TTL means a mobile tab discard can restore a board from a snapshot that is hours old.
Every such verdict computed against `Date.now()` then reads uniformly overdue — every in-progress task
"stuck" (fixed in taskStuck.ts), every agent "Unresponsive" (fixed in agentHealth.tsx). That is one
defect class, found on three surfaces, because the clock choice was re-decided at each call site and
was silently omissible.
The ratchet: `dataAsOfMs` is a REQUIRED positional parameter here, typed `number | undefined`. A caller
may still pass `undefined` (no snapshot hydrated -> now really is the data's age), but it cannot forget
to decide — TypeScript rejects the two-argument call. Keep it required; the omissibility was the bug.
*/
/**
* Milliseconds elapsed between `timestampMs` and the moment the containing data was last confirmed
* fresh by the server.
*
* @param timestampMs - Server-provided instant being aged (epoch ms). `NaN` propagates so callers can
* detect an unparseable timestamp instead of receiving a plausible-looking `0`.
* @param dataAsOfMs - When the record carrying `timestampMs` was last confirmed fresh. Pass the SWR
* envelope's `savedAt` for hydrated snapshots, the fetch time for live data, and `undefined` only
* when the data provably came from the current wall-clock moment (falls back to `Date.now()`).
*
* Clamped at zero: a timestamp newer than its own snapshot is clock skew or an optimistic local write,
* never negative age.
*/
export function elapsedSinceMs(timestampMs: number, dataAsOfMs: number | undefined): number {
return Math.max(0, (dataAsOfMs ?? Date.now()) - timestampMs);
}
/**
* True when `timestampMs` is older than `thresholdMs` relative to the age of the data it arrived with.
*
* Returns false for an unparseable (`NaN`) `timestampMs` — absence of proof of staleness is not proof
* of staleness. Surfaces that must treat an invalid timestamp as a failure (agentHealth does) should
* check `Number.isFinite` themselves before calling.
*/
export function isOverdue(
timestampMs: number,
thresholdMs: number,
dataAsOfMs: number | undefined,
): boolean {
return elapsedSinceMs(timestampMs, dataAsOfMs) > thresholdMs;
}