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>
241 lines
8.2 KiB
TypeScript
241 lines
8.2 KiB
TypeScript
import { useState, useEffect, useCallback, useRef } from "react";
|
|
import { useTranslation } from "react-i18next";
|
|
import type { DockerNodeConfigInfo, NodeCreateInput, NodeInfo, NodeOnboardingInput, NodeUpdateInput, RemoteNodeProjectDiscoveryResult } from "../api";
|
|
import {
|
|
fetchDockerConfigDiff,
|
|
fetchDockerNodeConfig,
|
|
fetchNodes,
|
|
registerNode,
|
|
updateDockerNodeConfig,
|
|
updateNode,
|
|
unregisterNode,
|
|
checkNodeHealth,
|
|
discoverRemoteNodeProjects,
|
|
} from "../api";
|
|
import { persistNodeProjectPathMappings } from "../api-node";
|
|
import { recordResumeEvent } from "../utils/resumeInstrumentation";
|
|
import { isVisibilityResumeError, useTabVisibilitySuspension, useVisibilityAwarePoll } from "./visibilitySuspension";
|
|
|
|
export interface UseNodesResult {
|
|
nodes: NodeInfo[];
|
|
loading: boolean;
|
|
error: string | null;
|
|
refresh: () => Promise<void>;
|
|
register: (input: NodeOnboardingInput) => Promise<NodeInfo>;
|
|
update: (id: string, updates: NodeUpdateInput) => Promise<NodeInfo>;
|
|
unregister: (id: string) => Promise<void>;
|
|
healthCheck: (id: string) => Promise<void>;
|
|
fetchDockerConfig: (nodeId: string) => Promise<DockerNodeConfigInfo | null>;
|
|
patchDockerConfig: (nodeId: string, config: Partial<DockerNodeConfigInfo>) => Promise<DockerNodeConfigInfo>;
|
|
fetchDockerDiff: (nodeId: string) => Promise<{ persistedVersion: number; deployedVersion: number | null; needsRecreate: boolean }>;
|
|
discoverRemoteProjects: (input: { url: string; apiKey?: string }) => Promise<RemoteNodeProjectDiscoveryResult>;
|
|
}
|
|
|
|
const POLL_INTERVAL_MS = 10000; // 10 seconds
|
|
const VISIBILITY_REFRESH_DEBOUNCE_MS = 1000;
|
|
|
|
/**
|
|
* Hook for fetching and managing node registry state.
|
|
* Automatically polls for updates every 10 seconds.
|
|
* Refetches when the tab becomes visible again.
|
|
*/
|
|
export function useNodes(): UseNodesResult {
|
|
const { t } = useTranslation("app");
|
|
const [nodes, setNodes] = useState<NodeInfo[]>([]);
|
|
const [loading, setLoading] = useState(true);
|
|
const [error, setError] = useState<string | null>(null);
|
|
const lastVisibilityRefreshRef = useRef<number>(0);
|
|
const nodesRef = useRef(nodes);
|
|
const visibilitySuspension = useTabVisibilitySuspension();
|
|
|
|
useEffect(() => {
|
|
nodesRef.current = nodes;
|
|
}, [nodes]);
|
|
|
|
const shouldSuppressVisibilityResumeError = useCallback((errorMessage: string): boolean => {
|
|
return nodesRef.current.length > 0 && isVisibilityResumeError(errorMessage, visibilitySuspension.wasRecentlyHidden());
|
|
}, [visibilitySuspension]);
|
|
|
|
const refresh = useCallback(async () => {
|
|
try {
|
|
setError(null);
|
|
const data = await fetchNodes();
|
|
setNodes(data);
|
|
} catch (err) {
|
|
const errorMessage = err instanceof Error ? err.message : t("nodes.errorFetching", "Failed to fetch nodes");
|
|
if (!shouldSuppressVisibilityResumeError(errorMessage)) {
|
|
setError(errorMessage);
|
|
}
|
|
// Keep stale data visible if polling refresh fails
|
|
}
|
|
}, [shouldSuppressVisibilityResumeError, t]);
|
|
|
|
useEffect(() => {
|
|
let cancelled = false;
|
|
|
|
async function load() {
|
|
setLoading(true);
|
|
try {
|
|
const data = await fetchNodes();
|
|
if (!cancelled) {
|
|
setNodes(data);
|
|
setError(null);
|
|
}
|
|
} catch (err) {
|
|
const errorMessage = err instanceof Error ? err.message : t("nodes.errorFetching", "Failed to fetch nodes");
|
|
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: "useNodes",
|
|
trigger: "visibility",
|
|
projectId: undefined,
|
|
replayAttempted: false,
|
|
reason: "debounce-skipped",
|
|
detail: { timeSinceLastRefreshMs: timeSinceLastRefresh },
|
|
});
|
|
return;
|
|
}
|
|
|
|
lastVisibilityRefreshRef.current = now;
|
|
recordResumeEvent({
|
|
view: "useNodes",
|
|
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 node-registry 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 the node
|
|
list 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 });
|
|
|
|
const register = useCallback(async (input: NodeOnboardingInput): Promise<NodeInfo> => {
|
|
const { projectMappings, ...nodeInput } = input;
|
|
const node = await registerNode(nodeInput as NodeCreateInput);
|
|
|
|
if (projectMappings.length > 0) {
|
|
try {
|
|
await persistNodeProjectPathMappings(node.id, projectMappings);
|
|
} catch (error) {
|
|
const mappingError = error instanceof Error ? error.message : t("nodes.errorPersistMappings", "Failed to persist project mappings");
|
|
let cleanupErrorMessage = "";
|
|
try {
|
|
await unregisterNode(node.id);
|
|
} catch (cleanupError) {
|
|
cleanupErrorMessage = cleanupError instanceof Error
|
|
? cleanupError.message
|
|
: t("nodes.errorUnregisterAfterMappingFailure", "Failed to unregister node after mapping failure");
|
|
}
|
|
|
|
await refresh();
|
|
|
|
if (cleanupErrorMessage) {
|
|
throw new Error(`${mappingError}. Cleanup also failed: ${cleanupErrorMessage}`);
|
|
}
|
|
throw new Error(mappingError);
|
|
}
|
|
}
|
|
|
|
await refresh();
|
|
return node;
|
|
}, [refresh, t]);
|
|
|
|
const update = useCallback(async (id: string, updates: NodeUpdateInput): Promise<NodeInfo> => {
|
|
const node = await updateNode(id, updates);
|
|
setNodes((prev) => prev.map((existing) => (existing.id === id ? node : existing)));
|
|
return node;
|
|
}, []);
|
|
|
|
const unregister = useCallback(async (id: string): Promise<void> => {
|
|
await unregisterNode(id);
|
|
setNodes((prev) => prev.filter((node) => node.id !== id));
|
|
}, []);
|
|
|
|
const healthCheck = useCallback(async (id: string): Promise<void> => {
|
|
const result = await checkNodeHealth(id);
|
|
setNodes((prev) => prev.map((node) => (
|
|
node.id === id
|
|
? {
|
|
...node,
|
|
status: result.status,
|
|
updatedAt: result.checkedAt,
|
|
}
|
|
: node
|
|
)));
|
|
}, []);
|
|
|
|
const fetchDockerConfig = useCallback((nodeId: string) => fetchDockerNodeConfig(nodeId), []);
|
|
|
|
const patchDockerConfig = useCallback(async (nodeId: string, config: Partial<DockerNodeConfigInfo>) => {
|
|
const updatedConfig = await updateDockerNodeConfig(nodeId, config);
|
|
setNodes((prev) => prev.map((node) => (
|
|
node.id === nodeId
|
|
? { ...node, dockerConfig: updatedConfig }
|
|
: node
|
|
)));
|
|
return updatedConfig;
|
|
}, []);
|
|
|
|
const fetchDockerDiff = useCallback(async (nodeId: string) => {
|
|
const diff = await fetchDockerConfigDiff(nodeId);
|
|
if ("persistedVersion" in diff) {
|
|
return diff;
|
|
}
|
|
return { persistedVersion: 0, deployedVersion: null, needsRecreate: false };
|
|
}, []);
|
|
|
|
const discoverRemoteProjects = useCallback(async (input: { url: string; apiKey?: string }) => {
|
|
return discoverRemoteNodeProjects(input);
|
|
}, []);
|
|
|
|
return {
|
|
nodes,
|
|
loading,
|
|
error,
|
|
refresh,
|
|
register,
|
|
update,
|
|
unregister,
|
|
healthCheck,
|
|
fetchDockerConfig,
|
|
patchDockerConfig,
|
|
fetchDockerDiff,
|
|
discoverRemoteProjects,
|
|
};
|
|
}
|