fix(webui): scope remote health checks to visible demand (#6657)
* fix(webui): scope remote health checks to visible demand * fix(webui): simplify demand-driven health polling
This commit is contained in:
1 parent
ce3f36983d
commit
5e9810c1ad
15 files changed
+661
-95
No files matched your search
@@ -23,6 +23,7 @@ function HostMenuContent({ picker, portalContainer }: { picker: HostPicker; port
|
||||
/** Mounted with the menu so every opening starts with a fresh, stable list. */
|
||||
function HostMenuItems({ picker }: { picker: HostPicker }) {
|
||||
const { t } = useTranslation();
|
||||
useEffect(() => picker.watchDirectory?.(), [picker.watchDirectory]);
|
||||
const [searchable] = useState(() => picker.profiles.length > 5);
|
||||
const [query, setQuery] = useState("");
|
||||
const [order] = useState(() => [picker.currentId, ...picker.recentIds]);
|
||||
|
||||
@@ -71,6 +71,9 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
|
||||
const nameId = useId();
|
||||
const nameInput = useRef<HTMLInputElement>(null);
|
||||
const refresh = connections?.refresh;
|
||||
const watchDirectory = connections?.watchDirectory;
|
||||
const visible = connections?.localActive || connections?.managing;
|
||||
useEffect(() => { if (visible) return watchDirectory?.(); }, [visible, watchDirectory]);
|
||||
const page = useRef<HTMLDivElement>(null);
|
||||
useEffect(() => { if (connections?.managing) page.current?.focus({ preventScroll: true }); }, [connections?.managing]);
|
||||
|
||||
|
||||
@@ -118,7 +118,7 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
|
||||
else if (managing) void connect(id).catch(() => {});
|
||||
else switchHost(id);
|
||||
},
|
||||
manage,
|
||||
manage, watchDirectory: hosts.watchDirectory,
|
||||
cancel: hosts.cancel, clearError: hosts.clearError, restoreFocus: () => { if (!managing) restoreFocus(); },
|
||||
};
|
||||
useEffect(() => { if (selected) document.title = selected.name; }, [selected]);
|
||||
@@ -149,7 +149,7 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
|
||||
embeddedManagement: !!bridge.embedded, reportManagementSurface: bridge.embedded ? bridge.reportSurface : undefined,
|
||||
closeManagement: bridge.embedded ? bridge.leaveManagement : () => changeManagement(false), selectLocal,
|
||||
openHostIds: frames.map((frame) => frame.connection.id),
|
||||
directoryError: hosts.directoryError, refresh: hosts.refresh, rename: hosts.rename, connect, disconnect: hosts.disconnect, remove: hosts.remove, cancel: hosts.cancel }}>
|
||||
directoryError: hosts.directoryError, refresh: hosts.refresh, watchDirectory: hosts.watchDirectory, rename: hosts.rename, connect, disconnect: hosts.disconnect, remove: hosts.remove, cancel: hosts.cancel }}>
|
||||
<HostNavigationContext.Provider value={bridge.embedded || (available || selected ? picker : null)}>
|
||||
<div className="flex h-full min-h-0 flex-col bg-background">
|
||||
<div className="relative min-h-0 flex-1 overflow-hidden">
|
||||
|
||||
@@ -20,6 +20,7 @@ export interface HostPicker {
|
||||
cancel: () => void;
|
||||
clearError: () => void;
|
||||
restoreFocus: () => void;
|
||||
watchDirectory?: () => () => void;
|
||||
}
|
||||
export interface EmbeddedPicker extends EmbeddedHost {
|
||||
kind: "embedded";
|
||||
|
||||
@@ -19,6 +19,7 @@ export const RemoteContext = createContext<{
|
||||
directory: RemoteDirectory | null;
|
||||
directoryError: boolean;
|
||||
refresh: () => Promise<RemoteDirectory>;
|
||||
watchDirectory: () => () => void;
|
||||
rename: (id: string, name: string) => Promise<void>;
|
||||
connect: (id: string, stillWanted?: () => boolean) => Promise<void>;
|
||||
disconnect: (id: string) => Promise<void>;
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
import { usePageVisibility } from "@/hooks/usePageVisibility";
|
||||
import { readPairReturn } from "@/lib/remote-pair-return";
|
||||
import { readRemoteInstances, readSelectedRemote, readRecentRemotes, rememberSelectedRemote, rememberRecentRemote, remoteAction, validateRemoteConnection, type RemoteConnection, type RemoteDirectory, type SelectedRemote } from "@/lib/remote-instances";
|
||||
import { needsRemoteSetup, readRemoteInstances, readSelectedRemote, readRecentRemotes, rememberSelectedRemote, rememberRecentRemote, remoteAction, validateRemoteConnection, type RemoteConnection, type RemoteDirectory, type SelectedRemote } from "@/lib/remote-instances";
|
||||
|
||||
// Never silently evict a view containing drafts or unfinished attachments.
|
||||
// Tunnels are shared across browser tabs, so only explicit disconnect closes one.
|
||||
@@ -11,6 +12,7 @@ export interface HostFrame {
|
||||
loaded: boolean;
|
||||
offline: boolean;
|
||||
failures: number;
|
||||
healthCheck?: number;
|
||||
error?: string;
|
||||
}
|
||||
interface PendingSwitch { id: string; name: string }
|
||||
@@ -18,7 +20,17 @@ interface SwitchFailure { id: string; code: string }
|
||||
|
||||
export function useHostSessions() {
|
||||
const { client, getToken } = useClient();
|
||||
const pageVisible = usePageVisibility();
|
||||
const [directory, setDirectory] = useState<RemoteDirectory | null>(null);
|
||||
const directoryRef = useRef(directory);
|
||||
const directoryRead = useRef<{ generation: number; ids: string[]; promise: Promise<RemoteDirectory> } | null>(null);
|
||||
const observers = useRef(0);
|
||||
const [observing, setObserving] = useState(false);
|
||||
const watchDirectory = useCallback(() => {
|
||||
observers.current += 1;
|
||||
setObserving(true);
|
||||
return () => { observers.current -= 1; setObserving(observers.current > 0); };
|
||||
}, []);
|
||||
const [directoryError, setDirectoryError] = useState(false);
|
||||
const [selected, setSelected] = useState<SelectedRemote | null>(() => readPairReturn() ? null : readSelectedRemote());
|
||||
const [recentIds, setRecentIds] = useState(readRecentRemotes);
|
||||
@@ -66,6 +78,7 @@ export function useHostSessions() {
|
||||
return true;
|
||||
}, [cancel, select]);
|
||||
const applyDirectory = useCallback((next: RemoteDirectory) => {
|
||||
directoryRef.current = next;
|
||||
setDirectory(next); setDirectoryError(false);
|
||||
// Names are metadata, not a new host session. Keep iframe URLs, drafts,
|
||||
// selection and connection state intact when this or another tab renames.
|
||||
@@ -92,39 +105,106 @@ export function useHostSessions() {
|
||||
directoryGeneration.current += 1;
|
||||
if (mounted.current) applyDirectory(next);
|
||||
}, [applyDirectory, client]);
|
||||
const refresh = useCallback(async () => {
|
||||
const generation = ++directoryGeneration.current;
|
||||
try {
|
||||
const next = window.top === window ? await readRemoteInstances(getToken()) : { available: false, profiles: [] };
|
||||
if (mounted.current && generation === directoryGeneration.current) applyDirectory(next);
|
||||
return next;
|
||||
} catch (reason) {
|
||||
if (mounted.current && generation === directoryGeneration.current) setDirectoryError(true);
|
||||
throw reason;
|
||||
const readDirectory = useCallback(function read(ids: string[] = [], wanted: () => boolean = () => true): Promise<RemoteDirectory> {
|
||||
if (!mounted.current || !wanted()) return Promise.resolve(directoryRef.current || { available: false, profiles: [] });
|
||||
if (window.top !== window) {
|
||||
const next = { available: false, profiles: [] };
|
||||
if (mounted.current) applyDirectory(next);
|
||||
return Promise.resolve(next);
|
||||
}
|
||||
}, [applyDirectory, getToken]);
|
||||
// Visibility affects observation, never the shared transport's lifetime.
|
||||
if (document.visibilityState === "hidden") ids = [];
|
||||
const generation = directoryGeneration.current;
|
||||
const pendingRead = directoryRead.current;
|
||||
if (pendingRead?.generation === generation) {
|
||||
if (ids.every((id) => pendingRead.ids.includes(id))) return pendingRead.promise;
|
||||
return pendingRead.promise.catch(() => {}).then(() => read(ids, wanted));
|
||||
}
|
||||
const promise = readRemoteInstances(getToken(), ids).then((next) => {
|
||||
if (!mounted.current || generation !== directoryGeneration.current) return next;
|
||||
applyDirectory(next);
|
||||
for (const [id, frame] of cache.current) {
|
||||
if (id === pendingRef.current?.id) continue;
|
||||
const profile = next.profiles.find((item) => item.id === id);
|
||||
const changed = (!!profile?.gateway_id && profile.gateway_id !== frame.connection.gateway_id)
|
||||
|| (!!profile?.view_id && profile.view_id !== frame.connection.view_id);
|
||||
const connected = !!profile?.connected && !changed;
|
||||
// Missing connections and changed identities are authoritative, not a
|
||||
// transient probe failure. A cached probe must not count twice.
|
||||
if (connected) frame.failures = 0;
|
||||
else if (!profile?.gateway_id || changed || needsRemoteSetup(profile.connection_error || "")) frame.failures = 2;
|
||||
else if (profile.health_check !== frame.healthCheck) frame.failures += 1;
|
||||
frame.healthCheck = profile?.health_check;
|
||||
if (connected || frame.failures >= 2) {
|
||||
frame.offline = !connected;
|
||||
frame.error = connected ? "" : changed ? "instance_changed" : profile?.connection_error || (!profile ? "profile_not_found" : "");
|
||||
}
|
||||
if (connected && frame.loaded) setFailure((current) => current?.id === id ? null : current);
|
||||
}
|
||||
if (cache.current.size) publish();
|
||||
return next;
|
||||
}).catch((reason: unknown) => {
|
||||
if (mounted.current && generation === directoryGeneration.current) {
|
||||
setDirectoryError(true);
|
||||
for (const id of ids) {
|
||||
const frame = cache.current.get(id);
|
||||
if (frame && id !== pendingRef.current?.id && ++frame.failures >= 2) {
|
||||
frame.offline = true; frame.error = "directory_unavailable";
|
||||
}
|
||||
}
|
||||
if (ids.length) publish();
|
||||
}
|
||||
throw reason;
|
||||
});
|
||||
directoryRead.current = { generation, ids, promise };
|
||||
const finish = () => { if (directoryRead.current?.promise === promise) directoryRead.current = null; };
|
||||
void promise.then(finish, finish);
|
||||
return promise;
|
||||
}, [applyDirectory, getToken, publish]);
|
||||
const healthTargets = useCallback(() => {
|
||||
const profiles = directoryRef.current?.profiles ?? [];
|
||||
const ids = observers.current ? profiles.filter((profile) => profile.gateway_id).map((profile) => profile.id) : [];
|
||||
if (selectedRef.current && cache.current.has(selectedRef.current.id)) ids.push(selectedRef.current.id);
|
||||
return [...new Set(ids)].filter((id) => id !== pendingRef.current?.id);
|
||||
}, []);
|
||||
const refresh = useCallback(async () => {
|
||||
const next = await readDirectory();
|
||||
const ids = healthTargets();
|
||||
return mounted.current && document.visibilityState !== "hidden" && ids.length ? readDirectory(ids) : next;
|
||||
}, [healthTargets, readDirectory]);
|
||||
|
||||
const connect = useCallback(async (id: string, stillWanted: () => boolean = () => true) => {
|
||||
cancel();
|
||||
const attempt = epoch.current;
|
||||
const wanted = () => mounted.current && attempt === epoch.current && stillWanted();
|
||||
const warm = cache.current.get(id);
|
||||
if (warm?.loaded && !warm.offline) {
|
||||
if (wanted()) select(warm.connection);
|
||||
return;
|
||||
}
|
||||
if (!warm && cache.current.size >= MAX_HOST_VIEWS) {
|
||||
setFailure({ id, code: "view_limit" });
|
||||
throw new Error("view_limit");
|
||||
}
|
||||
// A health response started before this mutation describes the old tunnel.
|
||||
directoryGeneration.current += 1;
|
||||
const name = directory?.profiles.find((item) => item.id === id)?.name || initial.current?.name || id;
|
||||
setPendingSwitch({ id, name });
|
||||
setFailure(null);
|
||||
let openingFrame = warm?.loaded ? undefined : warm;
|
||||
try {
|
||||
if (warm?.loaded && !warm.offline) {
|
||||
// A retained view may have spent hours unobserved. Check its identity
|
||||
// before reusing it, without reloading the iframe or reconnecting SSH.
|
||||
const next = await readDirectory([id], wanted);
|
||||
if (!wanted()) return;
|
||||
const profile = next.profiles.find((item) => item.id === id);
|
||||
if (profile?.connected && profile.gateway_id === warm.connection.gateway_id
|
||||
&& profile.view_id === warm.connection.view_id) {
|
||||
select(warm.connection);
|
||||
return;
|
||||
}
|
||||
warm.offline = true;
|
||||
publish();
|
||||
}
|
||||
const connection = validateRemoteConnection(await remoteAction<RemoteConnection>(client, "connect", { id }));
|
||||
// Reads started before or during this mutation describe the old tunnel.
|
||||
directoryGeneration.current += 1;
|
||||
if (!wanted()) {
|
||||
// A cancelled SSH request can finish later. Never switch away from the
|
||||
// latest choice or close its tunnel, which another tab may already use.
|
||||
@@ -141,7 +221,7 @@ export function useHostSessions() {
|
||||
}
|
||||
if (!frame.loaded) openingFrame = frame;
|
||||
publish();
|
||||
void refresh().catch(() => {});
|
||||
void readDirectory().catch(() => {});
|
||||
if (!frame.loaded) {
|
||||
const ready = await new Promise<boolean>((resolve, reject) => {
|
||||
const timer = window.setTimeout(() => {
|
||||
@@ -171,7 +251,7 @@ export function useHostSessions() {
|
||||
}
|
||||
if (attempt === epoch.current) setPendingSwitch(null);
|
||||
}
|
||||
}, [cancel, client, directory, publish, refresh, select, setPendingSwitch]);
|
||||
}, [cancel, client, directory, publish, readDirectory, refresh, select, setPendingSwitch]);
|
||||
const connectRef = useRef(connect);
|
||||
connectRef.current = connect;
|
||||
const loaded = useCallback((id: string) => {
|
||||
@@ -197,9 +277,9 @@ export function useHostSessions() {
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
void refresh().catch(() => {});
|
||||
return () => { mounted.current = false; cancel(); };
|
||||
}, [cancel, refresh]);
|
||||
void readDirectory().catch(() => {});
|
||||
return () => { mounted.current = false; directoryGeneration.current += 1; cancel(); };
|
||||
}, [cancel, readDirectory]);
|
||||
useEffect(() => {
|
||||
const saved = initial.current;
|
||||
if (!saved || window.top !== window) return;
|
||||
@@ -222,53 +302,43 @@ export function useHostSessions() {
|
||||
return () => { window.clearTimeout(timer); unsubscribe(); };
|
||||
}, [client, setPendingSwitch]);
|
||||
useEffect(() => {
|
||||
let checking = false;
|
||||
let cancelled = false;
|
||||
const tick = async () => {
|
||||
if (checking || !cache.current.size) return;
|
||||
checking = true;
|
||||
const generation = ++directoryGeneration.current;
|
||||
if (window.top !== window || !pageVisible || (!selected?.id && !observing)) return;
|
||||
let disposed = false;
|
||||
let running = false;
|
||||
let refreshPending = false;
|
||||
let timer: number | undefined;
|
||||
const hidden = () => document.visibilityState === "hidden";
|
||||
const poll = async (readList = false) => {
|
||||
if (disposed || hidden()) return;
|
||||
if (running) { refreshPending = true; return; }
|
||||
running = true;
|
||||
window.clearTimeout(timer);
|
||||
try {
|
||||
const next = await readRemoteInstances(getToken());
|
||||
if (cancelled || generation !== directoryGeneration.current) return;
|
||||
applyDirectory(next);
|
||||
for (const [id, frame] of cache.current) {
|
||||
if (id === pendingRef.current?.id) continue;
|
||||
const profile = next.profiles.find((profile) => profile.id === id);
|
||||
const changed = (!!profile?.gateway_id && profile.gateway_id !== frame.connection.gateway_id)
|
||||
|| (!!profile?.view_id && profile.view_id !== frame.connection.view_id);
|
||||
const connected = !!profile?.connected && !changed;
|
||||
frame.failures = connected ? 0 : frame.failures + 1;
|
||||
if (connected || frame.failures >= 2) {
|
||||
frame.offline = !connected;
|
||||
frame.error = connected ? "" : changed ? "instance_changed" : profile?.connection_error || (!profile ? "profile_not_found" : "");
|
||||
}
|
||||
if (connected && frame.loaded) setFailure((current) => current?.id === id ? null : current);
|
||||
}
|
||||
do {
|
||||
refreshPending = false;
|
||||
if (readList || (observing && !healthTargets().length)) await readDirectory([], () => !disposed && !hidden());
|
||||
if (disposed || hidden()) break;
|
||||
const ids = healthTargets();
|
||||
if (ids.length) await readDirectory(ids, () => !disposed && !hidden());
|
||||
} while (refreshPending && !disposed);
|
||||
} catch {
|
||||
if (!cancelled && generation === directoryGeneration.current) for (const [id, frame] of cache.current) {
|
||||
if (id === pendingRef.current?.id) continue;
|
||||
if (++frame.failures >= 2) { frame.offline = true; frame.error = "directory_unavailable"; }
|
||||
}
|
||||
// Keep the retained page; readDirectory owns health/error projection.
|
||||
} finally {
|
||||
checking = false;
|
||||
if (!cancelled) publish();
|
||||
running = false;
|
||||
if (refreshPending && !disposed && !hidden()) void poll(true);
|
||||
else if (!disposed && (healthTargets().length || observing)) timer = window.setTimeout(() => void poll(), 5_000);
|
||||
}
|
||||
};
|
||||
const timer = window.setInterval(() => { void tick(); }, 5_000);
|
||||
// Background tabs throttle timers. Recheck promptly after waking or a
|
||||
// network change, without reloading a frame or changing the selected host.
|
||||
const wake = () => { if (document.visibilityState === "visible") void tick(); };
|
||||
const wake = () => { void poll(true); };
|
||||
window.addEventListener("online", wake);
|
||||
window.addEventListener("pageshow", wake);
|
||||
document.addEventListener("visibilitychange", wake);
|
||||
void poll(true);
|
||||
return () => {
|
||||
cancelled = true; window.clearInterval(timer);
|
||||
disposed = true; window.clearTimeout(timer);
|
||||
window.removeEventListener("online", wake);
|
||||
window.removeEventListener("pageshow", wake);
|
||||
document.removeEventListener("visibilitychange", wake);
|
||||
};
|
||||
}, [applyDirectory, client, getToken, publish]);
|
||||
return { directory, directoryError, refresh, rename, selected, recentIds, frames, pending,
|
||||
}, [healthTargets, observing, pageVisible, pending?.id, readDirectory, selected?.id]);
|
||||
return { directory, directoryError, refresh, watchDirectory, rename, selected, recentIds, frames, pending,
|
||||
error: failure?.code || "", errorId: failure?.id, clearError, connect, cancel, local, reveal, disconnect, remove, loaded };
|
||||
}
|
||||
@@ -24,6 +24,7 @@ export interface RemoteProfile {
|
||||
gateway_id?: string;
|
||||
view_id?: string;
|
||||
connection_error?: string;
|
||||
health_check?: number;
|
||||
paired?: boolean;
|
||||
/** Opaque grouping ID supplied only after the local backend verifies receipts. */
|
||||
instance_id?: string;
|
||||
@@ -97,8 +98,9 @@ export interface RemoteInspection {
|
||||
incomplete: boolean;
|
||||
}
|
||||
|
||||
export async function readRemoteInstances(token: string): Promise<RemoteDirectory> {
|
||||
const response = await fetchWithTimeout("/api/remote-instances", {
|
||||
export async function readRemoteInstances(token: string, check: string[] = []): Promise<RemoteDirectory> {
|
||||
const query = new URLSearchParams(check.map((id) => ["check", id]));
|
||||
const response = await fetchWithTimeout(`/api/remote-instances${query.size ? `?${query}` : ""}`, {
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
if (response.status === 403 || response.status === 404) return { available: false, profiles: [] };
|
||||
|
||||
@@ -31,6 +31,7 @@ async function ready(result: { current: Session }, index: number) {
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(document, "visibilityState", { configurable: true, get: () => "visible" });
|
||||
vi.useFakeTimers();
|
||||
window.sessionStorage.clear();
|
||||
mocks.read.mockReset().mockResolvedValue(directory);
|
||||
@@ -43,6 +44,170 @@ beforeEach(() => {
|
||||
afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });
|
||||
|
||||
describe("host session lifecycle", () => {
|
||||
it("does not probe retained remote views while local or hidden, and rechecks on return", async () => {
|
||||
let visibility: DocumentVisibilityState = "visible";
|
||||
vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility);
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
act(() => result.current.local());
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
await act(async () => { await result.current.connect(ids[0]); });
|
||||
expect(mocks.read.mock.calls.some(([, targets]) => targets?.includes(ids[0]))).toBe(true);
|
||||
act(() => { visibility = "hidden"; document.dispatchEvent(new Event("visibilitychange")); });
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
await act(async () => { visibility = "visible"; document.dispatchEvent(new Event("visibilitychange")); });
|
||||
expect(mocks.read.mock.calls.some(([, targets]) => targets?.includes(ids[0]))).toBe(true);
|
||||
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.connect")).toHaveLength(1);
|
||||
expect(result.current.frames).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("only probes the selected host, not every retained view", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
await ready(result, 1);
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(mocks.read).toHaveBeenCalledWith("token", [ids[1]]);
|
||||
expect(mocks.read.mock.calls.every(([, targets]) => !targets?.includes(ids[0]))).toBe(true);
|
||||
});
|
||||
it("checks existing connections only while the local directory is observed", async () => {
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: [
|
||||
directory.profiles[0], { ...directory.profiles[1], connected: false, connection_error: "remote_unreachable" },
|
||||
{ ...directory.profiles[2], connected: false, connection_error: "pair_authorization_rejected" },
|
||||
{ ...directory.profiles[3], connected: false, gateway_id: undefined },
|
||||
] });
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await act(async () => {});
|
||||
let stop!: () => void;
|
||||
await act(async () => { stop = result.current.watchDirectory(); });
|
||||
expect(mocks.read).toHaveBeenCalledWith("token", ids.slice(0, 3));
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(mocks.read.mock.calls).toEqual([["token", ids.slice(0, 3)]]);
|
||||
act(stop);
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(30_000); });
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
expect(mocks.request).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("discovers connections and then updates the directory through targeted polls", async () => {
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: [] });
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await act(async () => {});
|
||||
await act(async () => { result.current.watchDirectory(); });
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: [directory.profiles[0]] });
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(mocks.read.mock.calls).toEqual([["token", []], ["token", [ids[0]]]]);
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.slice(0, 2) });
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(mocks.read.mock.calls).toEqual([["token", [ids[0]]]]);
|
||||
expect(result.current.directory?.profiles).toHaveLength(2);
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(mocks.read.mock.calls).toEqual([["token", ids.slice(0, 2)]]);
|
||||
});
|
||||
|
||||
it("keeps checking an observed host after a setup error and notices its recovery", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) =>
|
||||
p.id === ids[0] ? { ...p, connected: false, connection_error: "remote_auth_failed", health_check: 1 } : p) });
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(result.current.frames[0].offline).toBe(true);
|
||||
mocks.read.mockResolvedValue(directory);
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(mocks.read.mock.calls).toEqual([["token", [ids[0]]]]);
|
||||
expect(result.current.frames[0].offline).toBe(false);
|
||||
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.connect")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("counts distinct failed probes rather than repeated reads of a cached failure", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
let revision = 41;
|
||||
let connected = false;
|
||||
mocks.read.mockImplementation(async () => ({ ...directory, profiles: directory.profiles.map((p) =>
|
||||
p.id === ids[0] ? { ...p, connected, health_check: revision, connection_error: connected ? "" : "remote_unreachable" } : p) }));
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(result.current.frames[0].failures).toBe(1);
|
||||
await act(async () => { await result.current.refresh(); await result.current.refresh(); });
|
||||
expect(result.current.frames[0].failures).toBe(1);
|
||||
expect(result.current.frames[0].offline).toBe(false);
|
||||
revision += 1;
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(result.current.frames[0].offline).toBe(true);
|
||||
connected = true; revision += 1;
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
expect(result.current.frames[0].offline).toBe(false);
|
||||
expect(result.current.selected?.id).toBe(ids[0]);
|
||||
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.connect")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not start a queued probe after its observer leaves", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
const slow = deferred<typeof directory>();
|
||||
mocks.read.mockReturnValueOnce(slow.promise);
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
let stop!: () => void;
|
||||
await act(async () => { stop = result.current.watchDirectory(); });
|
||||
act(() => { stop(); result.current.local(); });
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { slow.resolve(directory); await vi.advanceTimersByTimeAsync(30_000); });
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
expect(result.current.frames).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("rechecks a queued wake immediately even when the old request fails", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
const slow = deferred<typeof directory>();
|
||||
mocks.read.mockReturnValueOnce(slow.promise);
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
act(() => { window.dispatchEvent(new Event("online")); window.dispatchEvent(new Event("pageshow")); });
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { slow.reject(new Error("directory_unavailable")); });
|
||||
expect(mocks.read.mock.calls.filter(([, targets]) => targets?.length)).toEqual([["token", [ids[0]]]]);
|
||||
expect(result.current.selected?.id).toBe(ids[0]);
|
||||
expect(result.current.frames[0].offline).toBe(false);
|
||||
});
|
||||
|
||||
it("can cancel a warm view's revalidation without activating it", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
act(() => result.current.local());
|
||||
const slow = deferred<typeof directory>();
|
||||
mocks.read.mockReturnValueOnce(slow.promise);
|
||||
const { completion } = await start(result, 0);
|
||||
expect(result.current.pending?.id).toBe(ids[0]);
|
||||
act(() => result.current.cancel());
|
||||
await act(async () => { slow.resolve(directory); await completion; });
|
||||
expect(result.current.selected).toBeNull();
|
||||
expect(result.current.frames).toHaveLength(1);
|
||||
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.connect")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("does not reuse a retained view when revalidation finds a different gateway", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
act(() => result.current.local());
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) =>
|
||||
p.id === ids[0] ? { ...p, gateway_id: "another-gateway" } : p) });
|
||||
mocks.request.mockRejectedValueOnce(new Error("instance_changed"));
|
||||
await act(async () => { await expect(result.current.connect(ids[0])).rejects.toThrow("instance_changed"); });
|
||||
expect(result.current.selected).toBeNull();
|
||||
expect(result.current.frames[0].offline).toBe(true);
|
||||
expect(result.current.frames[0].connection.gateway_id).toBe("gateway-0");
|
||||
});
|
||||
|
||||
it("reveals only a loaded live view for notifications, without connecting", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
@@ -51,9 +216,10 @@ describe("host session lifecycle", () => {
|
||||
act(() => { expect(result.current.reveal(ids[0])).toBe(true); });
|
||||
expect(result.current.selected?.id).toBe(ids[0]);
|
||||
act(() => { expect(result.current.reveal(ids[3])).toBe(false); });
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) => ({ ...p, connected: false })) });
|
||||
let check = 0;
|
||||
mocks.read.mockImplementation(async () => ({ ...directory, profiles: directory.profiles.map((p) => ({ ...p, connected: false, health_check: ++check })) }));
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
|
||||
act(() => { expect(result.current.reveal(ids[1])).toBe(false); });
|
||||
act(() => { expect(result.current.reveal(ids[0])).toBe(false); });
|
||||
expect(mocks.request).not.toHaveBeenCalled();
|
||||
});
|
||||
it("clears a failed reconnect only after that host's loaded view recovers", async () => {
|
||||
@@ -83,8 +249,11 @@ describe("host session lifecycle", () => {
|
||||
it("ignores a stale health failure that arrives after reconnect succeeds", async () => {
|
||||
const { result } = renderHook(useHostSessions);
|
||||
await ready(result, 0);
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: [] });
|
||||
let revision = 0;
|
||||
mocks.read.mockImplementation(async () => ({ ...directory, profiles: directory.profiles.map((p) =>
|
||||
({ ...p, connected: false, connection_error: "remote_unreachable", health_check: ++revision })) }));
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
|
||||
expect(result.current.frames[0].offline).toBe(true);
|
||||
const stale = deferred<typeof directory>();
|
||||
mocks.read.mockReturnValueOnce(stale.promise);
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
|
||||
@@ -100,7 +269,9 @@ describe("host session lifecycle", () => {
|
||||
await ready(result, 0);
|
||||
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) =>
|
||||
p.id === ids[0] ? { ...p, gateway_id: "restarted-gateway" } : p) });
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
|
||||
expect(mocks.read.mock.calls).toEqual([["token", [ids[0]]], ["token", [ids[0]]]]);
|
||||
expect(result.current.frames[0].offline).toBe(true);
|
||||
expect(result.current.selected?.id).toBe(ids[0]);
|
||||
});
|
||||
@@ -195,7 +366,9 @@ describe("host session lifecycle", () => {
|
||||
act(() => result.current.loaded(ids[0]));
|
||||
expect(result.current.selected).toBeNull();
|
||||
expect(result.current.frames).toHaveLength(0);
|
||||
expect(vi.getTimerCount()).toBe(1);
|
||||
mocks.read.mockClear();
|
||||
await act(async () => { await vi.advanceTimersByTimeAsync(60_000); });
|
||||
expect(mocks.read).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("a timed-out cold page leaves the old host intact and can be retried", async () => {
|
||||
|
||||
@@ -25,6 +25,7 @@ const connection = {
|
||||
|
||||
class TestSocket {
|
||||
static current: TestSocket;
|
||||
static connected = false;
|
||||
readyState = 0;
|
||||
sent: Outbound[] = [];
|
||||
onopen: (() => void) | null = null;
|
||||
@@ -41,6 +42,7 @@ class TestSocket {
|
||||
const frame = JSON.parse(data) as Outbound;
|
||||
this.sent.push(frame);
|
||||
if (frame.type !== "webui_request") return;
|
||||
if (frame.action === "remote.connect") TestSocket.connected = true;
|
||||
const result = frame.action === "remote.connect" ? connection
|
||||
: frame.action === "remote.pair_start" ? { id: "test-pair", command: "nanobot remote pair nbpr1.test", expires: Date.now() / 1000 + 600 }
|
||||
: frame.action === "remote.discover" ? { hosts: [], files: [], incomplete: false } : {};
|
||||
@@ -101,10 +103,12 @@ beforeEach(() => {
|
||||
localStorage.clear();
|
||||
sessionStorage.clear();
|
||||
window.history.replaceState(null, "", "/#/new");
|
||||
TestSocket.connected = false;
|
||||
vi.stubGlobal("WebSocket", TestSocket);
|
||||
vi.stubGlobal("fetch", vi.fn(async (input: RequestInfo | URL) => {
|
||||
const path = String(input);
|
||||
if (path === "/api/remote-instances") return Response.json({ available: true, machine_name: "Local machine", profiles: [profile] });
|
||||
const path = String(input).split("?")[0];
|
||||
if (path === "/api/remote-instances") return Response.json({ available: true, machine_name: "Local machine",
|
||||
profiles: [TestSocket.connected ? { ...connection, connected: true, health_check: 1 } : profile] });
|
||||
if (path === "/api/sessions") return Response.json({ sessions: [] });
|
||||
if (path === "/api/webui/sidebar-state") return Response.json({});
|
||||
return new Response(null, { status: 404 });
|
||||
|
||||
@@ -58,6 +58,7 @@ function LocalShell({ collapsed = false, initialRemote = false }) {
|
||||
const view = (collapsed = false, initialRemote = false) => render(<RemoteInstances><LocalShell collapsed={collapsed} initialRemote={initialRemote} /></RemoteInstances>);
|
||||
|
||||
beforeEach(async () => {
|
||||
Object.defineProperty(document, "visibilityState", { configurable: true, get: () => "visible" });
|
||||
await i18n.changeLanguage("en");
|
||||
window.sessionStorage.clear(); window.localStorage.clear();
|
||||
window.history.replaceState(null, "", "#/new");
|
||||
@@ -66,7 +67,12 @@ beforeEach(async () => {
|
||||
mocks.discover.mockReset().mockResolvedValue({ hosts: [], files: [], incomplete: false });
|
||||
mocks.inspect.mockReset().mockResolvedValue({ hostname: "team-host", candidates: [{ config_path: "~/.nanobot/config.json", runtime_user: "", service: "" }], incomplete: false });
|
||||
mocks.request.mockReset().mockImplementation(async (action: string) => {
|
||||
if (action === "remote.connect") return connection;
|
||||
if (action === "remote.connect") {
|
||||
const current = await mocks.read.getMockImplementation()?.("local-token", []);
|
||||
mocks.read.mockResolvedValue({ ...current, profiles: current.profiles.map((item: typeof profile) => item.id === profile.id
|
||||
? { ...item, connected: true, gateway_id: connection.gateway_id, health_check: 1 } : item) });
|
||||
return connection;
|
||||
}
|
||||
if (action === "remote.save") return { id: profile.id };
|
||||
if (action === "remote.disconnect") return { available: true, profiles: [profile] };
|
||||
return {};
|
||||
@@ -1312,17 +1318,18 @@ describe("remote instance UX", () => {
|
||||
|
||||
it("tolerates transient health failures and covers, rather than reloads, the remote frame", async () => {
|
||||
let tick: (() => void) | undefined;
|
||||
const setInterval = globalThis.setInterval;
|
||||
vi.spyOn(window, "setInterval").mockImplementation((callback, delay) => {
|
||||
if (delay === 5_000) tick = callback;
|
||||
const timer = setInterval(callback, delay);
|
||||
globalThis.clearInterval(timer);
|
||||
const setTimeout = globalThis.setTimeout;
|
||||
vi.spyOn(window, "setTimeout").mockImplementation((callback, delay) => {
|
||||
const timer = setTimeout(callback, delay);
|
||||
if (delay === 5_000) { tick = callback; globalThis.clearTimeout(timer); }
|
||||
return timer;
|
||||
});
|
||||
view(); await openDirectory();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Team server ubuntu@example.test" }));
|
||||
const frame = await readyRemote();
|
||||
fireEvent.load(frame);
|
||||
let check = 1;
|
||||
mocks.read.mockImplementation(async () => ({ available: true, profiles: [{ ...profile, gateway_id: connection.gateway_id, health_check: ++check }] }));
|
||||
await act(async () => { tick?.(); });
|
||||
expect(screen.queryByRole("region", { name: "Server connection lost" })).not.toBeInTheDocument();
|
||||
await act(async () => { tick?.(); });
|
||||
@@ -1338,19 +1345,26 @@ describe("remote instance UX", () => {
|
||||
});
|
||||
|
||||
it("rechecks on wake and network recovery without reloading or switching hosts", async () => {
|
||||
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
|
||||
let visibility: DocumentVisibilityState = "visible";
|
||||
vi.spyOn(document, "visibilityState", "get").mockImplementation(() => visibility);
|
||||
const rendered = view(); await openDirectory();
|
||||
fireEvent.click(screen.getByRole("button", { name: "Team server ubuntu@example.test" }));
|
||||
const frame = await readyRemote();
|
||||
mocks.read.mockClear();
|
||||
let check = 1;
|
||||
mocks.read.mockClear().mockImplementation(async (_token, ids: string[]) => {
|
||||
if (ids.length) check++;
|
||||
return { available: true, profiles: [{ ...profile, gateway_id: connection.gateway_id, health_check: check }] };
|
||||
});
|
||||
const probes = () => mocks.read.mock.calls.filter(([, ids]) => ids?.length);
|
||||
await act(async () => { window.dispatchEvent(new Event("online")); });
|
||||
expect(mocks.read).toHaveBeenCalledTimes(1);
|
||||
await act(async () => { document.dispatchEvent(new Event("visibilitychange")); });
|
||||
expect(mocks.read).toHaveBeenCalledTimes(2);
|
||||
expect(probes()).toHaveLength(1);
|
||||
act(() => { visibility = "hidden"; document.dispatchEvent(new Event("visibilitychange")); });
|
||||
await act(async () => { visibility = "visible"; document.dispatchEvent(new Event("visibilitychange")); });
|
||||
expect(probes()).toHaveLength(2);
|
||||
await screen.findByRole("region", { name: "Server connection lost" });
|
||||
mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, connected: true }] });
|
||||
mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, connected: true, gateway_id: connection.gateway_id, health_check: ++check }] });
|
||||
await act(async () => { window.dispatchEvent(new Event("pageshow")); });
|
||||
expect(mocks.read).toHaveBeenCalledTimes(3);
|
||||
expect(probes()).toHaveLength(3);
|
||||
expect(screen.queryByRole("region", { name: "Server connection lost" })).not.toBeInTheDocument();
|
||||
expect(screen.getByTitle("nanobot on Team server")).toBe(frame);
|
||||
expect(readSelectedRemote()?.id).toBe(profile.id);
|
||||
|
||||
Reference in new issue
Block a user