Files
fusion/packages/dashboard/app/hooks/useProjects.ts
gsxdsm b6243d68fe FN-6197: suppress tab-resume fetch errors in dashboard
Keep cached dashboard data visible while reconnecting after transient tab-resume fetch failures.

- detect likely tab suspension and visibility-resume fetch errors across dashboard data hooks
- suppress transient "Failed to fetch" errors when cached project and node data already exist
- show a "Connecting…" executor status state instead of surfacing raw resume-time fetch errors
- add dashboard tests covering visibility suspension handling and executor reconnect rendering
- add a patch changeset for the published CLI package

Files changed:
 .changeset/tame-tab-resume-fetch.md                |   5 +
 packages/dashboard/app/App.tsx                     |  16 ++-
 .../dashboard/app/components/ExecutorStatusBar.css |  19 ++-
 .../dashboard/app/components/ExecutorStatusBar.tsx |  12 ++
 .../__tests__/ExecutorStatusBar.test.tsx           |  20 ++-
 .../dashboard/app/hooks/__tests__/useNodes.test.ts | 149 ++++++++++++++++++++-
 .../app/hooks/__tests__/useProjects.test.ts        |  72 +++++++++-
 .../hooks/__tests__/visibilitySuspension.test.ts   |  13 ++
 packages/dashboard/app/hooks/useExecutorStats.ts   |  15 ++-
 .../dashboard/app/hooks/useManagedDockerNodes.ts   |  25 +++-
 packages/dashboard/app/hooks/useMeshState.ts       |  25 +++-
 packages/dashboard/app/hooks/useNodes.ts           |  25 +++-
 packages/dashboard/app/hooks/useProjectHealth.ts   |  18 ++-
 packages/dashboard/app/hooks/useProjects.ts        |  27 +++-
 packages/dashboard/app/hooks/useUsageData.ts       |  24 +++-
 .../dashboard/app/hooks/visibilitySuspension.ts    |   4 +
 16 files changed, 435 insertions(+), 34 deletions(-)

Fusion-Task-Id: FN-6197

Fusion-Task-Lineage: 834f56d8-8391-414f-8cbd-7e626c5724d0
2026-06-10 09:21:48 -07:00

249 lines
8.0 KiB
TypeScript

import { useState, useEffect, useCallback, useRef } from "react";
import type { ProjectInfo } from "../api";
import {
fetchProjectsAcrossNodes,
hasNodeMappingsSupport,
registerProject,
unregisterProject,
updateProject,
type ProjectCreateInput,
type ProjectInfoWithSource,
type ProjectNodeAvailability,
} from "../api";
import { SWR_CACHE_KEYS, SWR_DEFAULT_MAX_AGE_MS, clearCache, readCache, writeCache } from "../utils/swrCache";
import { recordResumeEvent } from "../utils/resumeInstrumentation";
import { isVisibilityResumeError, useTabVisibilitySuspension } from "./visibilitySuspension";
export interface UseProjectsResult {
/** List of all registered projects (local + remote) */
projects: ProjectInfoWithSource[];
/** Loading state for initial fetch */
loading: boolean;
/** Error message if fetch failed */
error: string | null;
/** Manually refresh projects list */
refresh: () => Promise<void>;
/** Register a new project */
register: (input: ProjectCreateInput) => Promise<ProjectInfo>;
/** Update an existing project */
update: (id: string, updates: Partial<ProjectInfo>) => Promise<ProjectInfo>;
/** Unregister a project */
unregister: (id: string) => Promise<void>;
}
const POLL_INTERVAL_MS = 5000; // 5 seconds
const VISIBILITY_REFRESH_DEBOUNCE_MS = 1000;
function normalizeNodeMappings(project: ProjectInfoWithSource): ProjectNodeAvailability[] {
const mappingSource = hasNodeMappingsSupport(project)
? (project.nodeMappings ?? project.projectNodeMappings ?? project.pathMappings ?? [])
: [];
const normalizedMappings = mappingSource
.filter((mapping) => Boolean(mapping?.nodeId) && Boolean(mapping?.path))
.map((mapping) => ({
nodeId: mapping.nodeId,
nodeName: mapping.nodeName,
path: mapping.path,
available: mapping.available !== false,
}));
if (normalizedMappings.length > 0) {
return normalizedMappings;
}
if (project.nodeId && project.path) {
return [{
nodeId: project.nodeId,
nodeName: project._sourceNodeName,
path: project.path,
available: true,
}];
}
return [];
}
function normalizeProjects(projects: ProjectInfoWithSource[]): ProjectInfoWithSource[] {
return projects.map((project) => ({
...project,
nodeMappings: normalizeNodeMappings(project),
}));
}
/**
* Hook for fetching and managing projects.
* Automatically polls for updates every 5 seconds.
* Refetches when the tab becomes visible again.
* Provides optimistic updates for UI responsiveness.
*/
export function useProjects(): UseProjectsResult {
const [projects, setProjects] = useState<ProjectInfoWithSource[]>(() => {
const cached = readCache<ProjectInfoWithSource[]>(SWR_CACHE_KEYS.PROJECTS, { maxAgeMs: SWR_DEFAULT_MAX_AGE_MS });
if (!Array.isArray(cached)) {
return [];
}
if (cached.length > 0) {
console.info("[swr-cache] hit projects=", cached.length);
}
return normalizeProjects(cached);
});
const [loading, setLoading] = useState(() => projects.length === 0);
const [error, setError] = useState<string | null>(null);
const intervalRef = useRef<NodeJS.Timeout | null>(null);
const lastVisibilityRefreshRef = useRef<number>(0);
const projectsRef = useRef(projects);
const visibilitySuspension = useTabVisibilitySuspension();
useEffect(() => {
projectsRef.current = projects;
}, [projects]);
const shouldSuppressVisibilityResumeError = useCallback((errorMessage: string): boolean => {
return projectsRef.current.length > 0 && isVisibilityResumeError(errorMessage, visibilitySuspension.wasRecentlyHidden());
}, [visibilitySuspension]);
const refresh = useCallback(async () => {
try {
setError(null);
const data = await fetchProjectsAcrossNodes();
const normalizedData = normalizeProjects(data);
setProjects(normalizedData);
writeCache(SWR_CACHE_KEYS.PROJECTS, normalizedData);
} catch (err) {
const errorMessage = err instanceof Error ? err.message : "Failed to fetch projects";
if (!shouldSuppressVisibilityResumeError(errorMessage)) {
setError(errorMessage);
}
// Don't clear existing projects on error - keep showing stale data
}
}, [shouldSuppressVisibilityResumeError]);
// Initial fetch and visibility change handler
useEffect(() => {
let cancelled = false;
async function load() {
const hadCachedProjects = projects.length > 0;
if (!hadCachedProjects) {
setLoading(true);
}
const t0 = performance.now();
try {
const data = await fetchProjectsAcrossNodes();
const normalizedData = normalizeProjects(data);
const elapsed = Math.round(performance.now() - t0);
console.log(`[useProjects] initial fetchProjectsAcrossNodes took ${elapsed}ms (${normalizedData.length} projects)`);
if (!cancelled) {
setProjects(normalizedData);
setError(null);
writeCache(SWR_CACHE_KEYS.PROJECTS, normalizedData);
}
} catch (err) {
const elapsed = Math.round(performance.now() - t0);
const errorMessage = err instanceof Error ? err.message : "Failed to fetch projects";
console.warn(`[useProjects] initial fetch failed after ${elapsed}ms: ${errorMessage}`);
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: "useProjects",
trigger: "visibility",
projectId: undefined,
replayAttempted: false,
reason: "debounce-skipped",
detail: { timeSinceLastRefreshMs: timeSinceLastRefresh },
});
return;
}
lastVisibilityRefreshRef.current = now;
recordResumeEvent({
view: "useProjects",
trigger: "visibility",
projectId: undefined,
replayAttempted: false,
reason: "debounced-refresh",
});
void refresh();
};
document.addEventListener("visibilitychange", handleVisibilityChange);
return () => {
cancelled = true;
document.removeEventListener("visibilitychange", handleVisibilityChange);
};
}, [projects.length, refresh, shouldSuppressVisibilityResumeError]);
// Polling for updates
useEffect(() => {
// Only start polling after initial load completes
if (loading) return;
intervalRef.current = setInterval(() => {
refresh();
}, POLL_INTERVAL_MS);
return () => {
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
};
}, [loading, refresh]);
const register = useCallback(async (input: ProjectCreateInput): Promise<ProjectInfo> => {
const project = await registerProject(input);
// Optimistically add to list
setProjects((prev) => [...prev, project]);
return project;
}, []);
const update = useCallback(async (id: string, updates: Partial<ProjectInfo>): Promise<ProjectInfo> => {
const project = await updateProject(id, updates);
// Optimistically update in list
setProjects((prev) =>
prev.map((p) => (p.id === id ? project : p))
);
return project;
}, []);
const unregister = useCallback(async (id: string): Promise<void> => {
await unregisterProject(id);
// Optimistically remove from list
setProjects((prev) => {
const nextProjects = prev.filter((p) => p.id !== id);
writeCache(SWR_CACHE_KEYS.PROJECTS, nextProjects);
return nextProjects;
});
clearCache(`${SWR_CACHE_KEYS.TASKS_PREFIX}${id}`);
}, []);
return {
projects,
loading,
error,
refresh,
register,
update,
unregister,
};
}