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:
chengyongru authored and GitHub committed 2026-11-14 00:32:10 +08:00
1 parent ce3f36983d
commit 5e9810c1ad
15 files changed
+661 -95

No files matched your search

+177 -4
View File
@@ -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 });
+27 -13
View File
@@ -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);