Files
fusion/packages/dashboard/app/hooks/useMeshState.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

120 lines
4.3 KiB
TypeScript

import { useCallback, useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import type { NodeMeshState } from "@fusion/core";
import { fetchMeshState } from "../api";
import { recordResumeEvent } from "../utils/resumeInstrumentation";
import { isVisibilityResumeError, useTabVisibilitySuspension, useVisibilityAwarePoll } from "./visibilitySuspension";
const POLL_INTERVAL_MS = 10000;
const VISIBILITY_REFRESH_DEBOUNCE_MS = 1000;
export interface UseMeshStateResult {
meshState: NodeMeshState[];
loading: boolean;
error: string | null;
refresh: () => Promise<void>;
}
export function useMeshState(): UseMeshStateResult {
const { t } = useTranslation("app");
const [meshState, setMeshState] = useState<NodeMeshState[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const lastVisibilityRefreshRef = useRef<number>(0);
const meshStateRef = useRef(meshState);
const visibilitySuspension = useTabVisibilitySuspension();
useEffect(() => {
meshStateRef.current = meshState;
}, [meshState]);
const shouldSuppressVisibilityResumeError = useCallback((errorMessage: string): boolean => {
return meshStateRef.current.length > 0 && isVisibilityResumeError(errorMessage, visibilitySuspension.wasRecentlyHidden());
}, [visibilitySuspension]);
const refresh = useCallback(async () => {
try {
setError(null);
const data = await fetchMeshState();
setMeshState(data.nodes);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : t("mesh.failedToFetchMeshState", "Failed to fetch mesh state");
if (!shouldSuppressVisibilityResumeError(errorMessage)) {
setError(errorMessage);
}
}
}, [shouldSuppressVisibilityResumeError, t]);
useEffect(() => {
let cancelled = false;
async function load() {
setLoading(true);
try {
const data = await fetchMeshState();
if (!cancelled) {
setMeshState(data.nodes);
setError(null);
}
} catch (err) {
const errorMessage = err instanceof Error ? err.message : t("mesh.failedToFetchMeshState", "Failed to fetch mesh state");
if (!cancelled && !shouldSuppressVisibilityResumeError(errorMessage)) {
setError(errorMessage);
}
} finally {
if (!cancelled) {
setLoading(false);
}
}
}
void load();
const handleVisibilityChange = () => {
if (document.visibilityState !== "visible") return;
const now = Date.now();
const timeSinceLastRefresh = now - lastVisibilityRefreshRef.current;
if (timeSinceLastRefresh < VISIBILITY_REFRESH_DEBOUNCE_MS) {
recordResumeEvent({
view: "useMeshState",
trigger: "visibility",
projectId: undefined,
replayAttempted: false,
reason: "debounce-skipped",
detail: { timeSinceLastRefreshMs: timeSinceLastRefresh },
});
return;
}
lastVisibilityRefreshRef.current = now;
recordResumeEvent({
view: "useMeshState",
trigger: "visibility",
projectId: undefined,
replayAttempted: false,
reason: "debounced-refresh",
});
void refresh();
};
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
cancelled = true;
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
}, [refresh, shouldSuppressVisibilityResumeError, t]);
/*
FNXC:MobileTabRetention 2026-07-26-16:05:
This 10s mesh-state poll was NOT visibility-gated: the `visibilitychange` listener above only ADDS a refresh
on the visible edge and never cleared the interval, so a backgrounded tab kept fetching mesh state every 10
seconds. Background network work is the primary signal iOS Safari / iOS PWA / Chrome Android use to discard
a tab, producing the white-splash reload on return.
`refreshOnVisible: false` because the debounced, instrumented listener above already owns the visible-edge
refresh; letting the helper refresh too would fetch twice on one edge.
*/
useVisibilityAwarePoll(refresh, POLL_INTERVAL_MS, { enabled: !loading, refreshOnVisible: false });
return { meshState, loading, error, refresh };
}