feat(webui): complete remote pairing and connection recovery

This commit is contained in:
Xubin Ren committed 2026-10-02 11:36:34 +08:00
1 parent 11889c018e
commit 192ca6e49e
52 files changed
+7313 -675

No files matched your search

+74 -10
View File
@@ -1,6 +1,7 @@
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type { Window as HappyWindow } from "happy-dom";
import i18n from "@/i18n";
import type {
@@ -11,6 +12,8 @@ import type {
WorkspaceScopePayload,
} from "@/lib/types";
(window as unknown as HappyWindow).happyDOM.settings.disableIframePageLoading = true;
const connectSpy = vi.fn();
const refreshSpy = vi.fn();
const createChatSpy = vi.fn().mockResolvedValue("chat-1");
@@ -318,6 +321,7 @@ describe("App layout", () => {
sessionUpdateHandlers.clear();
sidebarStateUpdateHandlers.clear();
window.history.replaceState(null, "", "/");
sessionStorage.removeItem("nanobot.remote-instance");
Reflect.deleteProperty(window, "nanobotHost");
setNavigatorPlatform("Linux x86_64");
localStorage.removeItem("nanobot-webui.sidebar");
@@ -688,16 +692,19 @@ describe("App layout", () => {
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
const remote = await within(sidebar).findByRole("button", { name: "Remote connections" });
fireEvent.click(remote);
fireEvent.click(await screen.findByRole("button", { name: "Connect to remote nanobot…" }));
const host = await screen.findByRole("textbox", { name: "SSH address" });
expect(screen.getByRole("main")).toContainElement(host);
expect(within(sidebar).queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();
fireEvent.pointerDown(await within(sidebar).findByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });
fireEvent.click(await screen.findByRole("menuitem", { name: "Manage connections…" }));
expect(await screen.findByRole("heading", { name: "Remote connections" })).toBeVisible();
expect(sidebar).toBeVisible();
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(remote).toHaveAttribute("aria-current", "page");
fireEvent.click(await screen.findByRole("button", { name: "Add server" }));
fireEvent.pointerDown(screen.getByRole("button", { name: "Other ways" }), { button: 0, ctrlKey: false });
fireEvent.click(screen.getByRole("menuitem", { name: "Use existing SSH settings" }));
const host = await screen.findByRole("textbox", { name: "SSH address" });
expect(screen.getByRole("dialog", { name: "Connect to a server" })).toContainElement(host);
expect(window.location.hash).toBe("#/remote");
expect(document.title).toBe("Remote connections · nanobot");
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
fireEvent.click(within(sidebar).getByRole("button", { name: "New topic" }));
expect(window.location.hash).toBe("#/new");
expect(screen.queryByRole("textbox", { name: "SSH address" })).not.toBeInTheDocument();
@@ -705,8 +712,64 @@ describe("App layout", () => {
window.history.replaceState(null, "", "#/remote");
window.dispatchEvent(new PopStateEvent("popstate"));
});
expect(await screen.findByRole("region", { name: "From your SSH config" })).toBeVisible();
expect(remote).toHaveAttribute("aria-current", "page");
expect(await screen.findByRole("button", { name: "Add server" })).toBeVisible();
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(within(sidebar).queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();
});
it("closes the mobile sidebar when managing connections from its host menu", async () => {
const user = userEvent.setup();
requestMutationSpy.mockResolvedValue({ hosts: [], files: [], incomplete: false });
vi.stubGlobal("matchMedia", vi.fn().mockImplementation((query: string) => ({
matches: !query.includes("1024px"), media: query, onchange: null,
addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(),
removeEventListener: vi.fn(), dispatchEvent: vi.fn(),
})));
mockFetchRoutes({
"/api/settings": baseSettingsPayload(),
"/api/remote-instances": { available: true, profiles: [] },
});
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
await user.click(await screen.findByRole("button", { name: "Toggle sidebar" }));
const sheet = await screen.findByRole("dialog");
fireEvent.pointerDown(await within(sheet).findByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });
fireEvent.click(await screen.findByRole("menuitem", { name: "Manage connections…" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(await screen.findByRole("heading", { name: "Remote connections" })).toBeVisible();
expect(window.location.hash).toBe("#/remote");
expect(screen.queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();
await waitFor(() => expect(document.body.style.pointerEvents).not.toBe("none"));
await user.click(screen.getByRole("button", { name: "Add server" }));
expect(await screen.findByRole("dialog", { name: "Add server" })).toBeVisible();
});
it("releases the mobile sidebar modal when switching to a server", async () => {
const user = userEvent.setup();
vi.stubGlobal("matchMedia", vi.fn().mockImplementation((query: string) => ({
matches: !query.includes("1024px"), media: query, onchange: null,
addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(),
removeEventListener: vi.fn(), dispatchEvent: vi.fn(),
})));
const profile = { id: "3b968d52-081d-4898-9970-ff0a1fc93817", name: "Team server",
host: "team", port: null, ssh_config: "", identity_file: "",
config_path: "~/.nanobot/config.json", runtime_user: "", connected: false };
requestMutationSpy.mockResolvedValue({ ...profile, hostname: "team-host", gateway_id: "remote-gateway",
url: "http://127.0.0.1:23456/#/?bootstrapSecret=test-only" });
mockFetchRoutes({
"/api/settings": baseSettingsPayload(),
"/api/remote-instances": { available: true, profiles: [profile] },
});
render(<App />);
await user.click(await screen.findByRole("button", { name: "Toggle sidebar" }));
const sheet = await screen.findByRole("dialog");
await user.click(await within(sheet).findByRole("button", { name: "Switch host" }));
await user.click(await screen.findByRole("menuitem", { name: "Team server team" }));
const frame = await screen.findByTitle("nanobot on Team server");
fireEvent.load(frame);
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
await waitFor(() => expect(document.body.style.pointerEvents).not.toBe("none"));
expect(frame).toBeVisible();
});
it("opens a remote setup deep link after reloading without opening Settings", async () => {
@@ -717,7 +780,8 @@ describe("App layout", () => {
"/api/remote-instances": { available: true, profiles: [] },
});
render(<App />);
expect(await screen.findByRole("region", { name: "From your SSH config" })).toBeVisible();
expect(await screen.findByRole("button", { name: "Add server" })).toBeVisible();
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(screen.getByRole("navigation", { name: "Sidebar navigation" })).toBeVisible();
expect(screen.queryByRole("navigation", { name: "Settings sections" })).not.toBeInTheDocument();
expect(window.location.hash).toBe("#/remote");
+73 -1
View File
@@ -40,6 +40,75 @@ beforeEach(() => {
afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });
describe("host session lifecycle", () => {
it("clears a failed reconnect only after that host's loaded view recovers", async () => {
const { result } = renderHook(useHostSessions);
await ready(result, 0);
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) => ({ ...p, connected: false })) });
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
mocks.request.mockRejectedValueOnce(new Error("ssh_unreachable"));
await act(async () => { await expect(result.current.connect(ids[0])).rejects.toThrow("ssh_unreachable"); });
expect(result.current.error).toBe("ssh_unreachable");
mocks.read.mockResolvedValue(directory);
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
expect(result.current.frames[0].offline).toBe(false);
expect(result.current.error).toBe("");
});
it("does not clear a failed destination because the active host is healthy", async () => {
const { result } = renderHook(useHostSessions);
await ready(result, 0);
mocks.request.mockRejectedValueOnce(new Error("ssh_unreachable"));
await act(async () => { await expect(result.current.connect(ids[1])).rejects.toThrow("ssh_unreachable"); });
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
expect(result.current.error).toBe("ssh_unreachable");
expect(result.current.selected?.id).toBe(ids[0]);
});
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: [] });
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
const stale = deferred<typeof directory>();
mocks.read.mockReturnValueOnce(stale.promise);
await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });
mocks.read.mockResolvedValue(directory);
await act(async () => { await result.current.connect(ids[0]); });
await act(async () => { stale.resolve({ ...directory, profiles: [] }); });
expect(result.current.frames[0].failures).toBe(0);
expect(result.current.directory?.profiles).toHaveLength(4);
});
it("keeps an old gateway view offline when another tab connects a new gateway", async () => {
const { result } = renderHook(useHostSessions);
await ready(result, 0);
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) =>
p.id === ids[0] ? { ...p, gateway_id: "restarted-gateway" } : p) });
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
expect(result.current.frames[0].offline).toBe(true);
expect(result.current.selected?.id).toBe(ids[0]);
});
it("does not revive an old proxy view after the local gateway restarts", async () => {
const { result } = renderHook(useHostSessions);
await ready(result, 0);
mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) =>
p.id === ids[0] ? { ...p, view_id: "new-local-proxy-session" } : p) });
await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });
expect(result.current.frames[0].offline).toBe(true);
expect(result.current.frames[0].error).toBe("instance_changed");
});
it("does not report a successful disconnect as failed when refreshing the list fails", async () => {
const { result } = renderHook(useHostSessions);
await ready(result, 0);
mocks.read.mockRejectedValue(new Error("directory_unavailable"));
await act(async () => { await expect(result.current.disconnect(ids[0])).resolves.toBeUndefined(); });
expect(result.current.selected).toBeNull();
expect(result.current.frames).toHaveLength(0);
expect(result.current.directoryError).toBe(true);
});
it("keeps the current host until the destination view loads, then switches warm without RPC", async () => {
const { result } = renderHook(useHostSessions);
await ready(result, 0);
@@ -115,7 +184,10 @@ describe("host session lifecycle", () => {
await ready(result, 0);
const { completion } = await start(result, 1);
const rejected = expect(completion).rejects.toThrow("view_load_failed");
await act(async () => { await vi.advanceTimersByTimeAsync(25_000); await rejected; });
await act(async () => { await vi.advanceTimersByTimeAsync(59_999); });
expect(result.current.pending?.id).toBe(ids[1]);
expect(result.current.selected?.id).toBe(ids[0]);
await act(async () => { await vi.advanceTimersByTimeAsync(1); await rejected; });
expect(result.current.selected?.id).toBe(ids[0]);
expect(result.current.frames).toHaveLength(1);
await ready(result, 1);
+253
View File
@@ -0,0 +1,253 @@
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { HostNavigationContext, HostSwitcher, RemoteHostMenu, type HostPicker } from "@/components/remote/HostSwitcher";
import { readRecentRemotes, rememberRecentRemote } from "@/lib/remote-instances";
vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: {
status: "open", onStatus: () => () => {},
} }) }));
function picker(count: number): HostPicker {
return {
kind: "shell", name: "Local", hostname: "My-Mac", localName: "My-Mac",
currentId: null, recentIds: [], pending: null, error: "", offline: false,
profiles: Array.from({ length: count }, (_, index) => ({
id: `00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`,
name: index === 1 ? "研发服务器" : `Server ${index + 1}`,
host: `ubuntu@host-${index + 1}.test`, ready: false,
})),
select: vi.fn(), manage: vi.fn(), cancel: vi.fn(), clearError: vi.fn(), restoreFocus: vi.fn(),
};
}
async function openMenu(value: HostPicker) {
const view = render(<HostNavigationContext.Provider value={value}><HostSwitcher /></HostNavigationContext.Provider>);
await userEvent.click(screen.getByRole("button", { name: "Switch host" }));
await screen.findByRole("menu");
return view;
}
beforeEach(() => window.localStorage.clear());
afterEach(() => { cleanup(); vi.restoreAllMocks(); });
describe("host switcher", () => {
it("keeps the current host identity visible until a pending switch is ready", async () => {
const value = picker(2);
value.pending = value.profiles[0];
render(<HostNavigationContext.Provider value={value}><HostSwitcher /></HostNavigationContext.Provider>);
const trigger = screen.getByRole("button", { name: "Switch host" });
expect(within(trigger).getByText("Local", { exact: true })).toBeVisible();
expect(trigger).toHaveAttribute("title", expect.stringContaining("Connecting to Server 1"));
expect(within(trigger).getByRole("status")).toHaveTextContent("Local · My-Mac · Connected · Connecting to Server 1");
await userEvent.click(trigger);
expect(screen.getByRole("menuitem", { name: "Local nanobot My-Mac" })).toHaveAttribute("aria-current", "true");
expect(screen.getByRole("menuitem", { name: "Server 1 ubuntu@host-1.test" })).not.toHaveAttribute("aria-current");
});
it("does not label a healthy host offline when switching to another host fails", async () => {
const value = { ...picker(2), error: "Destination SSH is unreachable" };
render(<HostNavigationContext.Provider value={value}><HostSwitcher /></HostNavigationContext.Provider>);
const trigger = screen.getByRole("button", { name: "Switch host" });
expect(within(trigger).getByRole("status")).toHaveTextContent("Local · My-Mac · Connected");
expect(trigger).toHaveAttribute("title", expect.stringContaining(value.error));
expect(trigger).not.toHaveTextContent("Offline");
await userEvent.click(trigger);
expect(screen.getByRole("alert")).toHaveTextContent(value.error);
});
it("keeps a truly disconnected host offline independently of switch errors", () => {
const value = { ...picker(2), offline: true, name: "Team server", hostname: "team-host" };
render(<HostNavigationContext.Provider value={value}><HostSwitcher /></HostNavigationContext.Provider>);
expect(screen.getByRole("status")).toHaveTextContent("Team server · team-host · Server connection lost");
});
it("keeps remote sidebar identity and connection status separate from pending or failed switches", () => {
const value = { kind: "embedded" as const, name: "Team server", hostname: "team-host", pendingName: "Another server", open: vi.fn() };
const view = render(<HostNavigationContext.Provider value={value}><HostSwitcher /></HostNavigationContext.Provider>);
const trigger = screen.getByRole("button", { name: "Switch host" });
expect(within(trigger).getByText("Team server", { exact: true })).toBeVisible();
expect(within(trigger).getByRole("status")).toHaveTextContent("Team server · team-host · Connected · Connecting to Another server");
view.rerender(<HostNavigationContext.Provider value={{ ...value, pendingName: undefined, error: "Destination SSH is unreachable" }}><HostSwitcher /></HostNavigationContext.Provider>);
expect(within(trigger).getByRole("status")).toHaveTextContent("Team server · team-host · Connected");
expect(trigger).toHaveAttribute("title", expect.stringContaining("Destination SSH is unreachable"));
});
it.each([0, 1, 5])("keeps %i saved hosts simple without search", async (count) => {
await openMenu(picker(count));
expect(screen.queryByRole("textbox")).not.toBeInTheDocument();
expect(screen.getAllByRole("menuitem")).toHaveLength(count + 2);
});
it.each([6, 10, 20])("searches %i saved hosts, with management outside the scroll area", async (count) => {
await openMenu(picker(count));
const input = screen.getByRole("textbox", { name: "Search hosts…" });
await waitFor(() => expect(input).toHaveFocus());
const group = screen.getByRole("group", { name: "Switch host" });
expect(within(group).getAllByRole("menuitem")).toHaveLength(count + 1);
expect(group).toHaveClass("overflow-y-auto", "min-h-0");
expect(group).not.toContainElement(screen.getByRole("menuitem", { name: "Manage connections…" }));
await userEvent.type(input, "HOST-6.TEST");
expect(within(group).getAllByRole("menuitem")).toHaveLength(1);
expect(within(group).getByText("Server 6")).toBeVisible();
expect(input).toHaveFocus();
});
it("finds names with spaces, non-Latin names and the local machine", async () => {
await openMenu(picker(20));
const input = screen.getByRole("textbox");
await userEvent.type(input, "Server 20");
expect(screen.getByRole("menuitem", { name: "Server 20 ubuntu@host-20.test" })).toBeVisible();
fireEvent.change(input, { target: { value: "研发" } });
expect(screen.getByRole("menuitem", { name: "研发服务器 ubuntu@host-2.test" })).toBeVisible();
fireEvent.change(input, { target: { value: "My-Mac" } });
expect(screen.getByRole("menuitem", { name: "Local nanobot My-Mac" })).toBeVisible();
expect(screen.queryByText("Server 20")).not.toBeInTheDocument();
});
it("keeps search focused while the pointer crosses results", async () => {
await openMenu(picker(10));
const input = screen.getByRole("textbox");
await waitFor(() => expect(input).toHaveFocus());
const row = screen.getByRole("menuitem", { name: "Server 1 ubuntu@host-1.test" });
fireEvent.pointerMove(row, { pointerType: "mouse", clientX: 25 });
fireEvent.pointerOut(row, { pointerType: "mouse" });
expect(input).toHaveFocus();
await userEvent.type(input, "Server 10");
expect(screen.getByRole("menuitem", { name: "Server 10 ubuntu@host-10.test" })).toBeVisible();
});
it("supports arrow navigation back to search, then Enter selection", async () => {
const value = picker(10);
await openMenu(value);
const input = screen.getByRole("textbox");
await userEvent.type(input, "host-10");
await userEvent.keyboard("{ArrowDown}");
expect(screen.getByRole("menuitem", { name: "Server 10 ubuntu@host-10.test" })).toHaveFocus();
await userEvent.keyboard("{ArrowUp}");
expect(input).toHaveFocus();
await userEvent.keyboard("{Enter}");
expect(value.select).toHaveBeenCalledWith(value.profiles[9].id);
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
});
it("does not connect or close when confirming IME input", async () => {
const value = picker(10);
await openMenu(value);
const input = screen.getByRole("textbox");
fireEvent.compositionStart(input);
fireEvent.change(input, { target: { value: "研发" } });
fireEvent.keyDown(input, { key: "Enter", isComposing: true });
fireEvent.keyDown(input, { key: "Escape", isComposing: true });
expect(value.select).not.toHaveBeenCalled();
expect(screen.getByRole("menu")).toBeVisible();
fireEvent.compositionEnd(input);
fireEvent.keyDown(input, { key: "Enter" });
expect(value.select).toHaveBeenCalledWith(value.profiles[1].id);
});
it("does not select a host on empty search Enter", async () => {
const value = picker(10);
await openMenu(value);
await waitFor(() => expect(screen.getByRole("textbox")).toHaveFocus());
await userEvent.keyboard("{Enter}");
expect(value.select).not.toHaveBeenCalled();
});
it("shows an empty result without hiding management or selecting it on Enter", async () => {
const value = picker(10);
await openMenu(value);
await userEvent.type(screen.getByRole("textbox"), "missing");
expect(screen.getByRole("status", { name: "" })).toHaveTextContent("No matching hosts");
await userEvent.keyboard("{Enter}");
expect(value.select).not.toHaveBeenCalled();
expect(value.manage).not.toHaveBeenCalled();
await userEvent.keyboard("{ArrowDown}{Enter}");
expect(value.manage).toHaveBeenCalledOnce();
});
it("clears search on reopen and restores focus on Escape", async () => {
const value = picker(10);
await openMenu(value);
await userEvent.type(screen.getByRole("textbox"), "Server 10");
await userEvent.keyboard("{Escape}");
await waitFor(() => expect(value.restoreFocus).toHaveBeenCalled());
await userEvent.click(screen.getByRole("button", { name: "Switch host" }));
expect(await screen.findByRole("textbox")).toHaveValue("");
expect(screen.getAllByRole("menuitem")).toHaveLength(12);
});
it("pins local, then current and recent hosts, without live reordering or duplicates", async () => {
const value = picker(20);
value.currentId = value.profiles[19].id;
value.recentIds = [value.profiles[8].id, value.currentId, "deleted-id"];
const rendered = await openMenu(value);
const names = () => within(screen.getByRole("group")).getAllByRole("menuitem").map((item) => item.textContent);
expect(names().slice(0, 4)).toEqual(["Local nanobotMy-Mac", "Server 20ubuntu@host-20.test", "Server 9ubuntu@host-9.test", "Server 1ubuntu@host-1.test"]);
const before = names();
rendered.rerender(<HostNavigationContext.Provider value={{ ...value, recentIds: [value.profiles[5].id] }}><HostSwitcher /></HostNavigationContext.Provider>);
expect(names()).toEqual(before);
});
it("uses the same searchable menu for the parent-owned remote sidebar", async () => {
const value = picker(20);
render(<RemoteHostMenu picker={value} anchor={{ left: 48, top: 540, width: 160, height: 32 }} onClose={vi.fn()} />);
const input = await screen.findByRole("textbox");
await userEvent.type(input, "host-20");
await userEvent.click(screen.getByRole("menuitem", { name: "Server 20 ubuntu@host-20.test" }));
expect(value.select).toHaveBeenCalledWith(value.profiles[19].id);
});
it("keeps search available if the directory shrinks while filtering", async () => {
const value = picker(10);
const rendered = await openMenu(value);
await userEvent.type(screen.getByRole("textbox"), "host-10");
rendered.rerender(<HostNavigationContext.Provider value={{ ...value, profiles: value.profiles.slice(0, 5) }}><HostSwitcher /></HostNavigationContext.Provider>);
const input = screen.getByRole("textbox");
expect(input).toHaveValue("host-10");
await userEvent.clear(input);
expect(within(screen.getByRole("group")).getAllByRole("menuitem")).toHaveLength(6);
});
it("does not autofocus search and summon the keyboard on touch devices", async () => {
const original = window.matchMedia.bind(window);
vi.spyOn(window, "matchMedia").mockImplementation((query) => ({ ...original(query), matches: query === "(pointer: coarse)" }));
await openMenu(picker(20));
expect(screen.getByRole("menu")).toHaveFocus();
expect(screen.getByRole("textbox")).not.toHaveFocus();
await userEvent.click(screen.getByRole("menuitem", { name: "Server 20 ubuntu@host-20.test" }));
await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());
});
it("keeps cancel and errors accessible even when no hosts match", async () => {
const value = picker(20);
value.pending = value.profiles[3]; value.error = "Try again";
await openMenu(value);
await userEvent.type(screen.getByRole("textbox"), "missing");
expect(screen.getByRole("alert")).toHaveTextContent("Try again");
await userEvent.click(screen.getByRole("button", { name: "Close" }));
expect(value.clearError).toHaveBeenCalledOnce();
await userEvent.click(screen.getByRole("menuitem", { name: "Cancel switch" }));
expect(value.cancel).toHaveBeenCalledOnce();
});
});
describe("recent host preferences", () => {
it("keeps only bounded, unique profile IDs and ignores malformed storage", () => {
window.localStorage.setItem("nanobot.recent-remote-instances", "not json");
expect(readRecentRemotes()).toEqual([]);
const ids = picker(25).profiles.map(({ id }) => id);
window.localStorage.setItem("nanobot.recent-remote-instances", JSON.stringify([null, "http://secret", ids[0], ...ids]));
expect(readRecentRemotes()).toEqual(ids.slice(0, 20));
const next = rememberRecentRemote(ids[5], readRecentRemotes());
expect(next).toHaveLength(20);
expect(next[0]).toBe(ids[5]);
expect(readRecentRemotes()).toEqual(next);
});
it("keeps switching available when browser storage is disabled", () => {
vi.spyOn(window.localStorage, "getItem").mockImplementation(() => { throw new Error("disabled"); });
vi.spyOn(window.localStorage, "setItem").mockImplementation(() => { throw new Error("disabled"); });
expect(readRecentRemotes()).toEqual([]);
expect(rememberRecentRemote(picker(1).profiles[0].id, [])).toEqual([picker(1).profiles[0].id]);
});
});
+78
View File
@@ -0,0 +1,78 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { PairRouteSettings } from "@/components/remote/PairRouteSettings";
import i18n from "@/i18n";
const mocks = vi.hoisted(() => ({ action: vi.fn(), refresh: vi.fn(), config: "" }));
vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: { requestMutation: mocks.action } }) }));
vi.mock("@/components/remote/RemoteInstances", () => ({ useRemoteConnections: () => ({ refresh: mocks.refresh, directory: { profiles: [{ id: "paired", paired: true, ssh_config: mocks.config }, { id: "ssh", name: "Team SSH", paired: false }] } }) }));
beforeEach(async () => { await i18n.changeLanguage("en"); mocks.action.mockReset().mockResolvedValue({}); mocks.refresh.mockReset().mockResolvedValue(undefined); mocks.config = ""; });
afterEach(cleanup);
async function chooseSSH() {
await userEvent.click(screen.getByRole("combobox"));
await userEvent.click(screen.getByRole("option", { name: "Team SSH" }));
}
describe("paired network route", () => {
it("does not mislabel a saved custom route as a direct connection", () => {
mocks.config = "/private/paired/ssh_route";
render(<PairRouteSettings id="paired" />);
expect(screen.getByRole("combobox")).toHaveTextContent("Saved network route");
expect(screen.getByRole("button", { name: "Save changes" })).toBeDisabled();
expect(mocks.action).not.toHaveBeenCalled();
});
it("shows direct only when no saved route is configured", () => {
render(<PairRouteSettings id="paired" />);
expect(screen.getByRole("combobox")).toHaveTextContent("Direct connection");
expect(screen.getByRole("button", { name: "Save changes" })).toBeDisabled();
});
it("shows saving, then confirms the saved route without connecting", async () => {
let finish!: (value: unknown) => void;
mocks.action.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
render(<PairRouteSettings id="paired" />);
await chooseSSH();
fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
expect(screen.getByRole("button", { name: "Saving…" })).toBeDisabled();
expect(screen.getByRole("combobox")).toBeDisabled();
await act(async () => finish({}));
expect(screen.getByRole("status")).toHaveTextContent("Saved");
expect(screen.getByRole("button", { name: "Save changes" })).toBeDisabled();
expect(mocks.action).toHaveBeenCalledOnce();
expect(mocks.action).toHaveBeenCalledWith("remote.pair_route", { id: "paired", route_id: "ssh" }, 65000);
});
it("preserves the chosen route after a failed save and allows retry", async () => {
mocks.action.mockRejectedValueOnce(new Error("pair_route_mismatch"));
render(<PairRouteSettings id="paired" />);
await chooseSSH();
fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
expect(await screen.findByRole("alert")).toHaveTextContent("same server");
expect(screen.getByRole("combobox")).toHaveTextContent("Team SSH");
fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
await waitFor(() => expect(screen.queryByRole("alert")).toBeNull());
expect(screen.getByRole("status")).toHaveTextContent("Saved");
});
it("distinguishes a saved route from a subsequent failed directory refresh", async () => {
mocks.refresh.mockRejectedValue(new Error("offline"));
render(<PairRouteSettings id="paired" />);
await chooseSSH();
fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't read your saved servers");
expect(screen.getByRole("status")).toHaveTextContent("Saved");
expect(screen.getByRole("button", { name: "Save changes" })).toBeDisabled();
expect(mocks.action).toHaveBeenCalledOnce();
});
it("does not dismiss a different screen when a closed editor finishes saving", async () => {
let finish!: (value: unknown) => void;
mocks.action.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
const saved = vi.fn();
const view = render(<PairRouteSettings id="paired" onSaved={saved} />);
await chooseSSH();
fireEvent.click(screen.getByRole("button", { name: "Save changes" }));
view.unmount();
await act(async () => finish({}));
expect(saved).not.toHaveBeenCalled();
});
});
+263
View File
@@ -0,0 +1,263 @@
import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { QuickPairSetup } from "@/components/remote/QuickPairSetup";
import { Dialog, DialogContent } from "@/components/ui/dialog";
import i18n from "@/i18n";
const mocks = vi.hoisted(() => {
const action = vi.fn();
return { action, client: { requestMutation: action }, connect: vi.fn(), refresh: vi.fn(), cancel: vi.fn(), copy: vi.fn() };
});
vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: mocks.client }) }));
vi.mock("@/components/remote/RemoteInstances", () => ({ useRemoteConnections: () => ({ connect: mocks.connect, refresh: mocks.refresh, cancel: mocks.cancel, directory: { profiles: [] } }) }));
vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: mocks.copy }));
const request = () => ({ id: "request-1", command: "nanobot remote pair nbpr1.public", expires: Date.now() / 1000 + 600 });
const preview = { id: "request-1", host: "ubuntu@server", hostname: "team", fingerprint: "SHA256:trusted-server", authorized_until: Date.now() / 1000 + 86400, revoke_command: "nanobot remote revoke request-1" };
beforeEach(async () => {
await i18n.changeLanguage("en");
mocks.action.mockReset().mockImplementation(async (action: string) => {
if (action === "remote.pair_start") return request();
if (action === "remote.pair_preview") return preview;
if (action === "remote.pair_finish") return { id: "paired-server" };
return {};
});
mocks.copy.mockReset().mockResolvedValue(true);
mocks.connect.mockReset().mockResolvedValue(undefined);
mocks.refresh.mockReset().mockResolvedValue(undefined);
});
afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });
const view = (onSSH = vi.fn(), onClose = vi.fn()) => render(<Dialog open><DialogContent><QuickPairSetup onSSH={onSSH} onClose={onClose} /></DialogContent></Dialog>);
function chooseOtherWay(name: string) {
fireEvent.pointerDown(screen.getByRole("button", { name: "Other ways" }), { button: 0, ctrlKey: false });
fireEvent.click(screen.getByRole("menuitem", { name }));
}
async function reviewed() {
await screen.findByRole("button", { name: "Copy command" });
chooseOtherWay("Use a connection code instead");
fireEvent.change(await screen.findByRole("textbox", { name: "Connection code" }), { target: { value: "nbpc1.encrypted" } });
fireEvent.click(screen.getByRole("button", { name: "Review connection" }));
await screen.findByRole("heading", { name: "Open this nanobot?" });
}
describe("quick pairing", () => {
it("never asks a returning user to copy another command while validating their link", async () => {
mocks.action.mockImplementation(() => new Promise(() => {}));
render(<Dialog open><DialogContent><QuickPairSetup returned={{ id: "request-1", code: "nbpc1.encrypted" }} onSSH={vi.fn()} onClose={vi.fn()} /></DialogContent></Dialog>);
expect(screen.getByRole("heading", { name: "Review connection" })).toBeVisible();
expect(screen.queryByRole("button", { name: "Copy command" })).toBeNull();
expect(screen.queryByText("Run one command in your server terminal to connect.")).toBeNull();
expect(screen.getByRole("button", { name: "Review connection" })).toBeDisabled();
expect(mocks.connect).not.toHaveBeenCalled();
});
it("shows only the next action and reveals requirements on demand", async () => {
view();
await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());
expect(screen.getByText(/For Linux servers/).closest(".inline-disclosure")).toHaveAttribute("aria-hidden", "true");
expect(screen.queryByRole("menuitem")).toBeNull();
expect(screen.getByText(/After authorizing/)).toHaveAttribute("aria-hidden", "true");
chooseOtherWay("Requirements & help");
expect(screen.getByText(/For Linux servers/)).toBeVisible();
expect(screen.getByText(/Commands expire after 10 minutes/)).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "View command" }));
expect(screen.getByText(request().command)).toBeVisible();
expect(screen.getByText(/For Linux servers/).closest(".inline-disclosure")).toHaveAttribute("aria-hidden", "true");
});
it("keeps closed command details mounted but inert for reversible transitions", async () => {
view();
const toggle = await screen.findByRole("button", { name: "View command" });
const panel = document.getElementById(toggle.getAttribute("aria-controls")!);
expect(panel).toHaveAttribute("data-state", "closed");
expect(panel).toHaveAttribute("inert");
fireEvent.click(toggle);
expect(panel).toHaveAttribute("data-state", "open");
expect(panel).not.toHaveAttribute("inert");
expect(toggle).toHaveAttribute("aria-expanded", "true");
fireEvent.click(toggle);
expect(document.getElementById(toggle.getAttribute("aria-controls")!)).toBe(panel);
expect(panel).toHaveAttribute("aria-hidden", "true");
expect(panel).toHaveAttribute("inert");
});
it("keeps preparation in the button, and delays its indicator without delaying readiness", async () => {
vi.useFakeTimers();
let finish!: (value: ReturnType<typeof request>) => void;
mocks.action.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
view();
const button = screen.getByRole("button", { name: "Copy command" });
expect(button).toBeDisabled();
expect(button).toHaveAttribute("aria-busy", "true");
expect(screen.queryByText("Preparing your connection…")).toBeNull();
act(() => { vi.advanceTimersByTime(199); });
expect(button).toHaveTextContent("Copy command");
act(() => { vi.advanceTimersByTime(1); });
expect(button).toHaveTextContent("Preparing your connection…");
expect(screen.getByRole("status").closest("button")).toBe(button);
await act(async () => finish(request()));
expect(button).toHaveTextContent("Copy command");
expect(button).toBeEnabled();
expect(button).toHaveAttribute("aria-busy", "false");
});
it("does not flash a delayed status after fast preparation finishes", async () => {
vi.useFakeTimers();
view();
await act(async () => {});
act(() => { vi.advanceTimersByTime(250); });
expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled();
expect(screen.queryByText("Preparing your connection…")).toBeNull();
});
it("preserves the pasted code and SSH fallback during a slow review", async () => {
const ssh = vi.fn();
view(ssh);
await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());
chooseOtherWay("Use a connection code instead");
fireEvent.change(screen.getByRole("textbox", { name: "Connection code" }), { target: { value: "nbpc1.unfinished" } });
mocks.action.mockImplementation(() => new Promise(() => {}));
vi.useFakeTimers();
fireEvent.click(screen.getByRole("button", { name: "Review connection" }));
act(() => { vi.advanceTimersByTime(200); });
expect(screen.getByRole("textbox", { name: "Connection code" })).toHaveValue("nbpc1.unfinished");
expect(screen.getByRole("button", { name: "Checking the connection link…" })).toBeDisabled();
chooseOtherWay("Use existing SSH settings");
expect(ssh).toHaveBeenCalledOnce();
});
it("advances only after copying succeeds and never implies a server connection", async () => {
let finish!: (success: boolean) => void;
mocks.copy.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
view();
await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());
fireEvent.click(screen.getByRole("button", { name: "Copy command" }));
expect(screen.getByRole("heading", { name: "Add server" })).toBeVisible();
await act(async () => finish(true));
expect(screen.getByRole("heading", { name: "Command copied" })).toBeVisible();
expect(screen.getByText(/Paste it into your server terminal/)).toBeVisible();
expect(screen.getByRole("button", { name: "Copy again" })).toBeEnabled();
expect(screen.getByRole("button", { name: "Copy again" })).toHaveClass("border", "border-input");
expect(screen.getByRole("dialog")).toHaveAccessibleDescription(i18n.t("remote.pair.afterCopyHint"));
expect(mocks.connect).not.toHaveBeenCalled();
expect(mocks.action.mock.calls.map(([action]) => action)).toEqual(["remote.pair_start"]);
});
it("exposes the command when the clipboard fails without claiming it was copied", async () => {
mocks.copy.mockResolvedValue(false);
view();
await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());
fireEvent.click(screen.getByRole("button", { name: "Copy command" }));
await screen.findByRole("alert");
expect(screen.getByText(request().command)).toBeVisible();
expect(screen.getByRole("heading", { name: "Add server" })).toBeVisible();
expect(screen.queryByRole("button", { name: "Copy again" })).toBeNull();
});
it("keeps a manual code when returning to the simpler command screen", async () => {
view();
await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());
chooseOtherWay("Use a connection code instead");
await waitFor(() => expect(screen.getByRole("textbox", { name: "Connection code" })).toHaveFocus());
fireEvent.change(screen.getByRole("textbox", { name: "Connection code" }), { target: { value: "nbpc1.unfinished" } });
fireEvent.click(screen.getByRole("button", { name: "Back" }));
expect(screen.queryByRole("textbox")).toBeNull();
chooseOtherWay("Use a connection code instead");
expect(screen.getByRole("textbox", { name: "Connection code" })).toHaveValue("nbpc1.unfinished");
});
it("replaces copied guidance with recovery when the invitation expires", async () => {
const timer = vi.spyOn(window, "setTimeout");
view();
await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());
fireEvent.click(screen.getByRole("button", { name: "Copy command" }));
await screen.findByRole("heading", { name: "Command copied" });
const expiry = timer.mock.calls.find(([, delay]) => typeof delay === "number" && delay > 599_000)?.[0];
expect(typeof expiry).toBe("function");
act(() => { if (typeof expiry === "function") expiry(); });
expect(screen.queryByRole("heading", { name: "Command copied" })).toBeNull();
expect(screen.getByText(/This request has expired/)).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Get a new command" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());
expect(screen.queryByText(/This request has expired/)).toBeNull();
});
it("can revisit the receipt from return-link confirmation without a disabled copy dead end", async () => {
render(<Dialog open><DialogContent><QuickPairSetup returned={{ id: "request-1", code: "nbpc1.encrypted" }} onSSH={vi.fn()} onClose={vi.fn()} /></DialogContent></Dialog>);
await screen.findByRole("heading", { name: "Open this nanobot?" });
fireEvent.click(screen.getByRole("button", { name: "Back" }));
expect(screen.getByRole("textbox", { name: "Connection code" })).toHaveValue("nbpc1.encrypted");
expect(screen.getByRole("button", { name: "Review connection" })).toBeEnabled();
expect(screen.queryByRole("button", { name: "Copy command" })).toBeNull();
expect(mocks.connect).not.toHaveBeenCalled();
});
it("prepares one command when Add server opens and keeps the SSH entry", async () => {
const ssh = vi.fn(); view(ssh);
await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());
expect(mocks.action.mock.calls.filter(([action]) => action === "remote.pair_start")).toHaveLength(1);
expect(screen.queryByRole("textbox", { name: /Private key/ })).toBeNull();
expect(screen.queryByRole("textbox", { name: "Connection code" })).toBeNull();
chooseOtherWay("Use existing SSH settings");
expect(ssh).toHaveBeenCalledOnce();
});
it("reviews public details before storing and opening the connection", async () => {
const close = vi.fn(); view(vi.fn(), close); await reviewed();
expect(mocks.action).not.toHaveBeenCalledWith("remote.pair_finish", expect.anything(), expect.anything());
expect(screen.getByText(/full access/)).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await waitFor(() => expect(close).toHaveBeenCalledOnce());
expect(mocks.connect).toHaveBeenCalledWith("paired-server", expect.any(Function));
});
it("keeps the receipt and saved profile after a network failure, retries without re-authorizing", async () => {
mocks.connect.mockRejectedValueOnce(new Error("ssh_connection_closed"));
view(); await reviewed(); fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await screen.findByRole("alert");
expect(screen.getByText(/Pairing is saved/)).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Retry" }));
await waitFor(() => expect(mocks.connect).toHaveBeenCalledTimes(2));
expect(mocks.action.mock.calls.filter(([action]) => action === "remote.pair_finish")).toHaveLength(1);
});
it("shows an actionable invalid-code error without losing the pasted value", async () => {
mocks.action.mockImplementation(async (action: string) => {
if (action === "remote.pair_start") return request();
if (action === "remote.pair_preview") throw new Error("pair_invalid");
return {};
});
view(); await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());
chooseOtherWay("Use a connection code instead");
fireEvent.change(await screen.findByRole("textbox", { name: "Connection code" }), { target: { value: "bad-code" } });
fireEvent.click(screen.getByRole("button", { name: "Review connection" }));
expect(await screen.findByRole("alert")).toHaveTextContent(/invalid/);
expect(screen.getByRole("textbox", { name: "Connection code" })).toHaveValue("bad-code");
});
it("cleans up an invitation returned after closing the dialog", async () => {
let resolve!: (value: ReturnType<typeof request>) => void;
mocks.action.mockImplementation((action: string) => action === "remote.pair_start" ? new Promise((done) => { resolve = done; }) : Promise.resolve({}));
const result = view();
result.unmount(); await act(async () => resolve(request()));
expect(mocks.action).toHaveBeenCalledWith("remote.pair_cancel", { id: "request-1" }, 65000);
});
it("keeps a displayed invitation when navigating away so the return link survives", async () => {
const result = view();
await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());
result.unmount();
expect(mocks.action.mock.calls.some(([action]) => action === "remote.pair_cancel")).toBe(false);
});
it("reviews a returned receipt without generating another key or connecting automatically", async () => {
render(<Dialog open><DialogContent><QuickPairSetup returned={{ id: "request-1", code: "nbpc1.encrypted" }} onSSH={vi.fn()} onClose={vi.fn()} /></DialogContent></Dialog>);
await screen.findByRole("heading", { name: "Open this nanobot?" });
expect(mocks.action).toHaveBeenCalledWith("remote.pair_preview", { id: "request-1", code: "nbpc1.encrypted" }, 65000);
expect(mocks.action.mock.calls.some(([action]) => action === "remote.pair_start" || action === "remote.pair_finish")).toBe(false);
expect(mocks.connect).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await waitFor(() => expect(mocks.connect).toHaveBeenCalledOnce());
});
it("offers a fresh command when a returned link is invalid", async () => {
mocks.action.mockRejectedValue(new Error("pair_invalid"));
render(<Dialog open><DialogContent><QuickPairSetup returned={{ id: "", code: "" }} onSSH={vi.fn()} onClose={vi.fn()} /></DialogContent></Dialog>);
expect(await screen.findByRole("alert")).toHaveTextContent(/invalid/);
expect(screen.getByRole("button", { name: "Get a new command" })).toBeEnabled();
expect(screen.queryByRole("button", { name: "Copy command" })).toBeNull();
expect(mocks.connect).not.toHaveBeenCalled();
});
it("recovers from preparation failure without showing a stuck preparing state", async () => {
mocks.action.mockRejectedValueOnce(new Error("local_io_error"));
view();
await screen.findByRole("alert");
expect(screen.queryByText("Preparing your connection…")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: "Get a new command" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());
expect(screen.queryByRole("alert")).toBeNull();
});
});
+603 -58
View File
@@ -1,12 +1,13 @@
import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { useState } from "react";
import { useEffect, useState } from "react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { RemoteInstances } from "@/components/remote/RemoteInstances";
import { RemoteConnectionsPage } from "@/components/remote/RemoteConnectionsPage";
import { Sidebar } from "@/components/Sidebar";
import { HOST_BRIDGE } from "@/components/remote/host-bridge";
import { readSelectedRemote, rememberSelectedRemote, validateRemoteConnection, type RemoteConnection } from "@/lib/remote-instances";
import { readSelectedRemote, readRecentRemotes, rememberSelectedRemote, validateRemoteConnection, type RemoteConnection } from "@/lib/remote-instances";
import i18n from "@/i18n";
import { clearPairReturn, initializePairReturn } from "@/lib/remote-pair-return";
import type { Window as HappyWindow } from "happy-dom";
(window as unknown as HappyWindow).happyDOM.settings.disableIframePageLoading = true;
@@ -15,7 +16,14 @@ const mocks = vi.hoisted(() => {
const request = vi.fn();
const discover = vi.fn();
const onStatus = vi.fn();
return { read: vi.fn(), request, discover, onStatus, client: { status: "open", requestMutation: (action: string, payload: unknown, timeout: number) => action === "remote.discover" ? discover(payload) : request(action, payload, timeout), onStatus }, token: () => "local-token" };
const inspect = vi.fn();
return { read: vi.fn(), request, discover, inspect, onStatus, client: { status: "open", requestMutation: (action: string, payload: unknown, timeout: number) => {
// Quick pairing prepares a local-only invitation when Add server opens;
// these tests track SSH/config mutations separately from that lifecycle.
if (action === "remote.pair_start") return Promise.resolve({ id: "pending-pair", command: "nanobot remote pair nbpr1.public", expires: Date.now() / 1000 + 600 });
if (action === "remote.pair_cancel") return Promise.resolve({ cancelled: true });
return action === "remote.discover" ? discover(payload) : action === "remote.inspect" ? inspect(payload) : request(action, payload, timeout);
}, onStatus }, token: () => "local-token" };
});
vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: mocks.client, getToken: mocks.token }) }));
vi.mock("@/lib/remote-instances", async (original) => ({
@@ -27,13 +35,17 @@ const connection: RemoteConnection = { ...profile, hostname: "team-host", gatewa
const noop = () => {};
function LocalShell({ collapsed = false, initialRemote = false }) {
const [remotePage, setRemotePage] = useState(initialRemote);
useEffect(() => {
const route = () => setRemotePage(window.location.hash === "#/remote");
window.addEventListener("hashchange", route);
return () => window.removeEventListener("hashchange", route);
}, []);
return <>
<Sidebar collapsed={collapsed} sessions={[]} activeKey={null} loading={false} newChatActive={false}
onNewChat={() => setRemotePage(false)} onSelect={noop} onRequestDelete={noop} onTogglePin={noop}
onNewChat={() => { window.location.hash = "/new"; setRemotePage(false); }} onSelect={noop} onRequestDelete={noop} onTogglePin={noop}
onRequestRename={noop} onToggleArchive={noop} onToggleGroup={noop}
onRequestRenameProject={noop} onNewChatInProject={noop} onOpenSettings={noop}
onOpenApps={noop} onOpenSkills={noop} onOpenAutomations={noop} onOpenChannels={noop}
onOpenRemoteConnections={() => setRemotePage(true)} activeUtility={remotePage ? "remote" : null}
onOpenSearch={noop} onToggleArchived={noop} />
<main>{remotePage ? <RemoteConnectionsPage onBackToChat={() => setRemotePage(false)} /> : <><p>Local conversations</p><textarea aria-label="Local draft" /></>}</main>
</>;
@@ -43,16 +55,18 @@ const view = (collapsed = false, initialRemote = false) => render(<RemoteInstanc
beforeEach(async () => {
await i18n.changeLanguage("en");
window.sessionStorage.clear(); window.localStorage.clear();
window.history.replaceState(null, "", "#/new");
mocks.onStatus.mockReset().mockImplementation((handler) => { handler("open"); return () => {}; });
mocks.read.mockReset().mockResolvedValue({ available: true, machine_name: "Xubin-Mac", profiles: [profile] });
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.save") return { id: profile.id };
return {};
});
});
afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
afterEach(() => { cleanup(); clearPairReturn(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
async function readyRemote() {
const frame = await screen.findByTitle("nanobot on Team server");
@@ -61,44 +75,298 @@ async function readyRemote() {
return frame;
}
async function chooseHost(name: string) {
fireEvent.pointerDown(screen.getByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });
fireEvent.pointerDown(await screen.findByRole("button", { name: i18n.t("remote.switchHost") }), { button: 0, ctrlKey: false });
fireEvent.click(await screen.findByRole("menuitem", { name }));
}
async function openDirectory() {
fireEvent.click(await screen.findByRole("button", { name: "Remote connections" }));
await chooseHost(i18n.t("remote.manageConnections"));
await screen.findByRole("heading", { name: i18n.t("remote.title") });
}
function chooseExistingSSH() {
fireEvent.pointerDown(screen.getByRole("button", { name: i18n.t("remote.pair.otherWays") }), { button: 0, ctrlKey: false });
fireEvent.click(screen.getByRole("menuitem", { name: i18n.t("remote.pair.useSSH") }));
}
describe("remote instance UX", () => {
it("places remote connections after Channels with the existing sidebar button style", async () => {
it("lets directory users cancel a cold connection before it takes over", async () => {
let finish!: (value: RemoteConnection) => void;
mocks.request.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
view(false, true);
fireEvent.click(await screen.findByRole("button", { name: "Team server ubuntu@example.test" }));
expect(await screen.findByText("Connecting to Team server…")).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Cancel switch" }));
expect(screen.getByRole("button", { name: "Add server" })).toBeEnabled();
await act(async () => finish(connection));
expect(readSelectedRemote()).toBeNull();
expect(screen.queryByTitle("nanobot on Team server")).toBeNull();
});
it("keeps SSH progress in the action and preserves a cancelable form", async () => {
mocks.inspect.mockImplementation(() => new Promise(() => {}));
await addAndInspect();
const action = await screen.findByRole("button", { name: "Signing in and looking for nanobot…" });
expect(action).toBeDisabled();
expect(within(screen.getByRole("dialog")).getByRole("status").closest("button")).toBe(action);
expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue(profile.host);
expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled();
});
it("keeps editing compact and only suggests SSH hosts after changing the destination", async () => {
view(false, true);
fireEvent.pointerDown(await screen.findByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false });
fireEvent.click(await screen.findByRole("menuitem", { name: "Edit connection" }));
const address = screen.getByRole("textbox", { name: "SSH address" });
expect(address).toHaveValue(profile.host);
expect(mocks.discover).not.toHaveBeenCalled();
expect(screen.queryByText("From your SSH config")).toBeNull();
fireEvent.change(address, { target: { value: "ubuntu@other.test" } });
await waitFor(() => expect(mocks.discover).toHaveBeenCalledOnce());
expect(mocks.request).not.toHaveBeenCalled();
});
it("warns about live views before forgetting but cancellation does not disconnect", async () => {
mocks.read.mockResolvedValue({ available: true, machine_name: "Xubin-Mac", profiles: [{ ...profile, connected: true }] });
view(false, true);
fireEvent.pointerDown(await screen.findByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false });
fireEvent.click(await screen.findByRole("menuitem", { name: "Forget server" }));
const dialog = await screen.findByRole("dialog", { name: "Forget Team server?" });
expect(within(dialog).getByRole("note")).toHaveTextContent("Unsaved work may be lost");
expect(within(dialog).getByRole("note")).toHaveTextContent("tabs using this connection");
fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));
expect(mocks.request).not.toHaveBeenCalled();
});
const pairId = "c6f4f0b0-99d2-4b90-883e-903353a4a0dc";
const pairCode = `nbpc1.${btoa(JSON.stringify({ id: pairId, data: "encrypted" })).replace(/=+$/, "")}`;
function prepareReturn() {
mocks.request.mockImplementation(async (action: string) => action === "remote.pair_preview" ? {
id: pairId, hostname: "New server", host: "ubuntu@new.example", fingerprint: "SHA256:verified",
authorized_until: Date.now() / 1000 + 86400, revoke_command: "nanobot remote revoke device",
} : connection);
window.history.replaceState(null, "", `http://localhost:3000/#/remote?pairing=${pairCode}`);
initializePairReturn();
}
it("opens a returned link locally instead of restoring another selected server", async () => {
rememberSelectedRemote(connection);
prepareReturn();
view(false, true);
expect(await screen.findByRole("heading", { name: "Open this nanobot?" })).toBeVisible();
expect(screen.getByText("New server")).toBeVisible();
expect(window.location.hash).toBe("#/remote");
expect(mocks.request.mock.calls.some(([action]) => action === "remote.connect" || action === "remote.pair_finish")).toBe(false);
});
it("brings a same-tab return link out of a remote view without closing its tunnel", async () => {
view(false, true);
fireEvent.click(await screen.findByRole("button", { name: "Team server ubuntu@example.test" }));
await readyRemote();
mocks.request.mockClear();
await act(async () => { prepareReturn(); });
expect(await screen.findByRole("heading", { name: "Open this nanobot?" })).toBeVisible();
expect(readSelectedRemote()).toBeNull();
expect(mocks.request.mock.calls.some(([action]) => action === "remote.disconnect" || action === "remote.connect" || action === "remote.pair_finish")).toBe(false);
});
it("chooses a local SSH config file and discovers its hosts without uploading contents", async () => {
mocks.request.mockResolvedValue({ path: "/local/team/ssh_config" });
mocks.discover.mockImplementation(async ({ ssh_config }) => ({ files: [], incomplete: false,
hosts: ssh_config ? [{ host: "cloud-team", source: ssh_config, ssh_config }] : [],
}));
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: "ubuntu@203.0.113.1" } });
fireEvent.click(screen.getByRole("button", { name: "Connection options" }));
fireEvent.click(screen.getByRole("button", { name: "Choose file: SSH config file (optional)" }));
await waitFor(() => expect(screen.getByRole("textbox", { name: "SSH config file (optional)" })).toHaveValue("/local/team/ssh_config"));
expect(mocks.request).toHaveBeenCalledWith("remote.pick_file", {}, 310_000);
expect(await screen.findByRole("button", { name: "Use cloud-team" })).toBeVisible();
expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue("ubuntu@203.0.113.1");
fireEvent.click(screen.getByRole("button", { name: "Use cloud-team" }));
expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue("cloud-team");
});
it("keeps an existing private key path when file selection is cancelled", async () => {
mocks.request.mockResolvedValue({ path: null });
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
fireEvent.click(screen.getByRole("button", { name: "Connection options" }));
fireEvent.change(screen.getByRole("textbox", { name: "Private key path (optional)" }), { target: { value: "/local/ssh-key" } });
fireEvent.click(screen.getByRole("button", { name: "Choose file: Private key path (optional)" }));
await waitFor(() => expect(screen.getByRole("button", { name: "Choose file: Private key path (optional)" })).toBeEnabled());
expect(screen.getByRole("textbox", { name: "Private key path (optional)" })).toHaveValue("/local/ssh-key");
});
it("does not apply a late file choice to a new editor", async () => {
let finish!: (value: unknown) => void;
mocks.request.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
fireEvent.click(screen.getByRole("button", { name: "Connection options" }));
fireEvent.click(screen.getByRole("button", { name: "Choose file: Private key path (optional)" }));
expect(screen.getByRole("button", { name: "Connect" })).toBeDisabled();
expect(screen.getByText("Choose a file in the system dialog…")).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
fireEvent.click(screen.getByRole("button", { name: "Connection options" }));
await act(async () => finish({ path: "/old/choice" }));
expect(screen.getByRole("textbox", { name: "Private key path (optional)" })).toHaveValue("");
});
async function addAndInspect() {
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: profile.host } });
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
}
it("offers a discovered service account without connecting until confirmed", async () => {
mocks.inspect.mockResolvedValue({ hostname: "team-host", incomplete: false, candidates: [{
config_path: "/var/lib/nanobot/.nanobot/config.json", runtime_user: "nanobot", service: "nanobot-team.service",
}] });
await addAndInspect();
expect(await screen.findByText("SSH connected")).toBeVisible();
expect(screen.getByRole("radio")).toBeChecked();
expect(screen.getByText(/Runs as nanobot/)).toBeVisible();
expect(screen.queryByRole("textbox", { name: "SSH address" })).not.toBeInTheDocument();
expect(mocks.request.mock.calls.some(([action]) => action === "remote.connect")).toBe(false);
fireEvent.click(screen.getByRole("button", { name: "Open nanobot" }));
await readyRemote();
expect(mocks.request).toHaveBeenCalledWith("remote.save", { id: profile.id, profile: expect.objectContaining({
config_path: "/var/lib/nanobot/.nanobot/config.json", runtime_user: "nanobot",
}) }, 65_000);
expect(mocks.inspect).toHaveBeenCalledTimes(1);
});
it("switches when the verified app is ready without waiting for every iframe resource", async () => {
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Team server ubuntu@example.test" }));
const frame = await screen.findByTitle("nanobot on Team server");
const source = { postMessage: vi.fn() };
Object.defineProperty(frame, "contentWindow", { value: source });
const origin = new URL(connection.url).origin;
await act(async () => window.dispatchEvent(new MessageEvent("message", {
data: { channel: HOST_BRIDGE, type: "hello" }, source: source as unknown as Window, origin,
})));
const nonce = source.postMessage.mock.calls[0][0].nonce;
await act(async () => window.dispatchEvent(new MessageEvent("message", {
data: { channel: HOST_BRIDGE, type: "ready", nonce: "wrong" }, source: source as unknown as Window, origin,
})));
expect(readSelectedRemote()).toBeNull();
await act(async () => window.dispatchEvent(new MessageEvent("message", {
data: { channel: HOST_BRIDGE, type: "ready", nonce }, source: source as unknown as Window, origin,
})));
await waitFor(() => expect(readSelectedRemote()?.id).toBe(profile.id));
});
it("gives a cold page time to load and keeps its failed setup retryable", async () => {
const timer = vi.spyOn(window, "setTimeout");
await addAndInspect();
await screen.findByTitle("nanobot on Team server");
const deadline = timer.mock.calls.find(([, delay]) => delay === 60_000);
expect(deadline).toBeDefined();
await act(async () => { (deadline![0] as () => void)(); });
expect(await screen.findByRole("alert")).toHaveTextContent(i18n.t("remote.errors.view_load_failed"));
expect(screen.queryByRole("button", { name: "SSH login settings" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Open nanobot" }));
await readyRemote();
});
it("requires an explicit choice between multiple discovered nanobots", async () => {
mocks.inspect.mockResolvedValue({ hostname: "team-host", incomplete: false, candidates: [
{ config_path: "/srv/one/config.json", runtime_user: "", service: "" },
{ config_path: "/srv/two/config.json", runtime_user: "nanobot", service: "nanobot-two.service" },
] });
await addAndInspect();
await screen.findByText("SSH connected");
expect(screen.getByRole("button", { name: "Open nanobot" })).toBeDisabled();
fireEvent.click(screen.getByRole("radio", { name: /nanobot-two.service/ }));
expect(screen.getByRole("button", { name: "Open nanobot" })).toBeEnabled();
fireEvent.click(screen.getByRole("button", { name: "Open nanobot" }));
await readyRemote();
expect(mocks.request).toHaveBeenCalledWith("remote.save", { id: profile.id, profile: expect.objectContaining({ config_path: "/srv/two/config.json" }) }, 65_000);
});
it("asks for the server location only after SSH succeeds but discovery finds nothing", async () => {
mocks.inspect.mockResolvedValue({ hostname: "team-host", candidates: [], incomplete: true });
await addAndInspect();
expect(await screen.findByText("No nanobot configuration found")).toBeVisible();
expect(screen.getByText("SSH connected")).toBeVisible();
fireEvent.change(screen.getByRole("textbox", { name: "Server's nanobot config path" }), { target: { value: "/srv/bot/config.json" } });
fireEvent.click(screen.getByRole("button", { name: "Open nanobot" }));
await readyRemote();
expect(mocks.inspect).toHaveBeenCalledTimes(1);
});
it("recovers a handshake failure through SSH settings without blaming nanobot or a missing key", async () => {
mocks.inspect.mockRejectedValue(new Error("ssh_connection_closed"));
await addAndInspect();
expect(await screen.findByRole("alert")).toHaveTextContent("does not confirm a key problem");
expect(screen.queryByText("SSH connected")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "SSH login settings" }));
expect(screen.getByRole("textbox", { name: "Private key path (optional)" })).toBeVisible();
expect(screen.queryByRole("textbox", { name: "Server's nanobot config path" })).not.toBeInTheDocument();
expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue(profile.host);
});
it("does not resume inspection or auto-connect after cancelling the dialog", async () => {
let resolve!: (value: unknown) => void;
mocks.inspect.mockReturnValue(new Promise((done) => { resolve = done; }));
await addAndInspect();
await waitFor(() => expect(mocks.inspect).toHaveBeenCalledTimes(1));
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
await act(async () => resolve({ hostname: "server", candidates: [{ config_path: "/srv/bot/config.json", runtime_user: "", service: "" }], incomplete: false }));
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(mocks.request.mock.calls.some(([action]) => action === "remote.connect")).toBe(false);
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.save")).toHaveLength(1);
});
it("verifies a first-contact host before resuming discovery instead of connecting blindly", async () => {
mocks.inspect.mockRejectedValueOnce(new Error("host_key_unknown")).mockResolvedValue({
hostname: "team-host", candidates: [], incomplete: false,
});
mocks.request.mockImplementation(async (action: string) => action === "remote.save" ? { id: profile.id }
: action === "remote.fingerprint" ? { fingerprint: "SHA256:verified-test", challenge: "nonce" } : {});
await addAndInspect();
await screen.findByText("SHA256:verified-test");
fireEvent.click(screen.getByRole("button", { name: "Fingerprint matches · Connect" }));
expect(await screen.findByText("No nanobot configuration found")).toBeVisible();
expect(mocks.inspect).toHaveBeenCalledTimes(2);
expect(mocks.request.mock.calls.some(([action]) => action === "remote.connect")).toBe(false);
});
it("changing the server requires discovery again and preserves typed SSH settings", async () => {
mocks.inspect.mockResolvedValue({ hostname: "team-host", candidates: [], incomplete: false });
await addAndInspect();
await screen.findByText("SSH connected");
fireEvent.click(screen.getByRole("button", { name: "Change" }));
expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue(profile.host);
fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: "ubuntu@second.test" } });
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await screen.findByText("SSH connected");
expect(mocks.inspect).toHaveBeenCalledTimes(2);
});
it("uses only the footer host menu to reach connection management", async () => {
view();
const entry = await screen.findByRole("button", { name: "Remote connections" });
const channels = screen.getByRole("button", { name: "Channels" });
expect(channels.nextElementSibling).toBe(entry);
expect(entry).toHaveClass("h-8", "rounded-xl", "text-[13px]");
expect(entry).not.toHaveAttribute("aria-haspopup");
expect(entry).not.toHaveAttribute("aria-current");
await screen.findByRole("button", { name: "Switch host" });
expect(screen.queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();
expect(screen.queryByText("This machine")).not.toBeInTheDocument();
fireEvent.click(entry);
await screen.findByRole("heading", { name: "Remote connections" });
await openDirectory();
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(screen.getByRole("main")).toContainElement(screen.getByText("Team server"));
expect(entry).toHaveAttribute("aria-current", "page");
expect(screen.getByRole("navigation", { name: "Sidebar navigation" })).toBeVisible();
expect(screen.getByText("Local nanobot")).toBeInTheDocument();
expect(screen.getByText("Currently using")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Connect to remote nanobot…" })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Add server" })).toBeInTheDocument();
});
it("keeps the connection action accessible when the sidebar is collapsed", async () => {
view(true);
const entry = await screen.findByRole("button", { name: "Remote connections" });
expect(entry).toHaveClass("w-8", "justify-center");
expect(entry.textContent).toBe("");
const switcher = screen.getByRole("button", { name: "Switch host" });
const switcher = await screen.findByRole("button", { name: "Switch host" });
expect(screen.queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();
expect(switcher).toHaveClass("w-8", "h-8");
expect(switcher).toHaveAttribute("title", expect.stringContaining("Xubin-Mac"));
fireEvent.click(entry);
await screen.findByRole("heading", { name: "Remote connections" });
await openDirectory();
});
it("moves the remote picker into a verified sidebar and can return local through its parent-owned menu", async () => {
@@ -129,12 +397,13 @@ describe("remote instance UX", () => {
it("uses clear Chinese navigation and returns from the connection form without saving", async () => {
await i18n.changeLanguage("zh-CN");
view();
fireEvent.click(await screen.findByRole("button", { name: "远程连接" }));
await openDirectory();
expect(screen.getByText("本地 nanobot")).toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "连接远程 nanobot…" }));
expect(screen.getByRole("heading", { name: "连接远程 nanobot" })).toBeInTheDocument();
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "返回" }));
fireEvent.click(screen.getByRole("button", { name: "添加服务器" }));
chooseExistingSSH();
expect(screen.getByRole("heading", { name: "连接服务器" })).toBeInTheDocument();
expect(screen.getByRole("dialog", { name: "连接服务器" })).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "取消" }));
expect(screen.getByRole("heading", { name: "远程连接" })).toBeInTheDocument();
expect(screen.queryByRole("textbox", { name: "SSH 地址" })).not.toBeInTheDocument();
expect(mocks.request).not.toHaveBeenCalled();
@@ -150,6 +419,7 @@ describe("remote instance UX", () => {
expect(screen.getByRole("button", { name: "Switch host" })).toHaveAttribute("title", expect.stringContaining("Team server · team-host"));
expect(mocks.request).toHaveBeenCalledWith("remote.connect", { id: profile.id }, 65_000);
expect(window.sessionStorage.getItem("nanobot.remote-instance")).not.toContain("secret");
expect(readRecentRemotes()).toEqual([profile.id]);
const storedValues = Array.from({ length: window.localStorage.length }, (_, index) =>
window.localStorage.getItem(window.localStorage.key(index) || ""));
expect(JSON.stringify(storedValues)).not.toContain("private-secret");
@@ -164,6 +434,7 @@ describe("remote instance UX", () => {
expect(screen.getByRole("heading", { name: "Remote connections" })).toBeVisible();
expect(mocks.request.mock.calls.some(([action]) => action === "remote.disconnect")).toBe(false);
expect(readSelectedRemote()).toBeNull();
expect(readRecentRemotes()).toEqual([profile.id]);
expect(mocks.request.mock.calls.some(([action]) => String(action).includes("stop"))).toBe(false);
});
@@ -254,17 +525,176 @@ describe("remote instance UX", () => {
});
it("saves once and preserves entered fields when SSH authentication fails", async () => {
mocks.inspect.mockRejectedValue(new Error("ssh_auth_failed"));
mocks.request.mockImplementation(async (action: string) => {
if (action === "remote.save") return { id: profile.id };
throw new Error("ssh_auth_failed");
});
view(); await openDirectory(); fireEvent.click(screen.getByRole("button", { name: "Connect to remote nanobot…" }));
view(); await openDirectory(); fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: "ubuntu@example.test" } });
fireEvent.click(screen.getByRole("button", { name: "Save & connect" }));
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await screen.findByRole("alert");
expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue("ubuntu@example.test");
expect(screen.getByRole("button", { name: "Save & connect" })).toBeEnabled();
expect(screen.getByRole("button", { name: "Connect" })).toBeEnabled();
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.save")).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await waitFor(() => expect(mocks.request.mock.calls.filter(([action]) => action === "remote.save")).toHaveLength(2));
expect(mocks.inspect).toHaveBeenCalledWith({ id: profile.id });
expect(mocks.request.mock.calls.some(([action]) => action === "remote.connect")).toBe(false);
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.save")[1][1]).toMatchObject({ id: profile.id });
});
it("edits in the same dialog but only saves, without connecting or switching", async () => {
view(); await openDirectory();
fireEvent.pointerDown(screen.getByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false });
fireEvent.click(await screen.findByRole("menuitem", { name: "Edit connection" }));
const dialog = await screen.findByRole("dialog", { name: "Edit connection" });
expect(within(dialog).getByRole("textbox", { name: "SSH address" })).toHaveValue(profile.host);
fireEvent.click(within(dialog).getByRole("button", { name: "Connection options" }));
fireEvent.change(within(dialog).getByRole("textbox", { name: "Name (optional)" }), { target: { value: "Renamed server" } });
fireEvent.click(within(dialog).getByRole("button", { name: "Save changes" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(mocks.request).toHaveBeenCalledTimes(1);
expect(mocks.request).toHaveBeenCalledWith("remote.save", {
id: profile.id, profile: expect.objectContaining({ host: profile.host, name: "Renamed server" }),
}, 65_000);
expect(readSelectedRemote()).toBeNull();
expect(screen.getByRole("heading", { name: "Remote connections" })).toBeVisible();
});
it.each(["en", "zh-CN"])("keeps server login separate from nanobot location (%s)", async (language) => {
await i18n.changeLanguage(language);
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: i18n.t("remote.add") }));
chooseExistingSSH();
fireEvent.click(screen.getByRole("button", { name: i18n.t("remote.connectionOptions") }));
const port = screen.getByRole("spinbutton", { name: i18n.t("remote.sshPort") });
const key = screen.getByRole("textbox", { name: i18n.t("remote.identity_file") });
expect(screen.queryByRole("textbox", { name: i18n.t("remote.runtime_user") })).not.toBeInTheDocument();
expect(screen.queryByRole("textbox", { name: i18n.t("remote.config_path") })).not.toBeInTheDocument();
expect(port).toHaveClass("h-10");
expect(key).toHaveClass("h-10");
});
it("imports a pasted SSH command into the existing connection options", async () => {
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
const address = screen.getByRole("textbox", { name: "SSH address" });
fireEvent.change(address, { target: { value: 'ssh -p2222 -i "~/.ssh/team key" -l ubuntu example.test' } });
fireEvent.blur(address);
expect(address).toHaveValue("ubuntu@example.test");
expect(screen.getByRole("status")).toHaveTextContent(i18n.t("remote.commandImported"));
expect(mocks.request).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Connection options" }));
expect(screen.getByRole("spinbutton", { name: "SSH port" })).toHaveValue(2222);
expect(screen.getByRole("textbox", { name: "Private key path (optional)" })).toHaveValue("~/.ssh/team key");
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await readyRemote();
expect(mocks.request).toHaveBeenCalledWith("remote.save", {
id: "", profile: expect.objectContaining({ host: "ubuntu@example.test", name: "ubuntu@example.test", port: 2222, identity_file: "~/.ssh/team key" }),
}, 65_000);
});
it("parses Enter submission without requiring a blur and preserves fields after failure", async () => {
mocks.request.mockImplementation(async (action: string) => {
if (action === "remote.save") return { id: profile.id };
throw new Error("ssh_agent_refused");
});
view(); await openDirectory(); fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
const address = screen.getByRole("textbox", { name: "SSH address" });
fireEvent.change(address, { target: { value: "ssh -p 2222 ubuntu@example.test" } });
fireEvent.submit(address.closest("form")!);
const alert = await screen.findByRole("alert");
expect(alert).toHaveTextContent(i18n.t("remote.errors.ssh_agent_refused"));
expect(alert.closest(".overflow-y-auto")).toBeNull();
expect(address).toHaveValue("ubuntu@example.test");
fireEvent.click(screen.getByRole("button", { name: "Connection options" }));
expect(screen.getByRole("spinbutton", { name: "SSH port" })).toHaveValue(2222);
expect(screen.getByRole("button", { name: "Connect" })).toBeEnabled();
});
it("doesn't save or execute a command with unsupported flags", async () => {
view(); await openDirectory(); fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
const address = screen.getByRole("textbox", { name: "SSH address" });
fireEvent.change(address, { target: { value: "ssh -o ProxyCommand=unsafe team" } });
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
expect(await screen.findByRole("alert")).toHaveTextContent(i18n.t("remote.errors.invalid_ssh_command"));
expect(address).toHaveValue("ssh -o ProxyCommand=unsafe team");
expect(mocks.request).not.toHaveBeenCalled();
});
it("closes a successful add dialog so returning local shows the directory", async () => {
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: profile.host } });
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await readyRemote();
await chooseHost("Local nanobot Xubin-Mac");
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(screen.getByRole("heading", { name: "Remote connections" })).toBeVisible();
});
it("cancels a dialog's pending connection without a late jump or error", async () => {
let finish: ((result: RemoteConnection) => void) | undefined;
mocks.request.mockImplementation(async (action: string) => action === "remote.save" ? { id: profile.id }
: new Promise<RemoteConnection>((resolve) => { finish = resolve; }));
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: profile.host } });
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await waitFor(() => expect(finish).toBeDefined());
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
await act(async () => { finish?.(connection); });
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(screen.queryByTitle("nanobot on Team server")).not.toBeInTheDocument();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(readSelectedRemote()).toBeNull();
});
it("keeps verification in one dialog and Back preserves setup without trusting", async () => {
mocks.request.mockImplementation(async (action: string) => {
if (action === "remote.save") return { id: profile.id };
if (action === "remote.connect") throw new Error("host_key_unknown");
if (action === "remote.fingerprint") return { fingerprint: "SHA256:example", challenge: "one-use" };
return {};
});
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: profile.host } });
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await screen.findByText("SHA256:example");
expect(screen.getAllByRole("dialog")).toHaveLength(1);
fireEvent.click(screen.getByRole("button", { name: "Back" }));
expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue(profile.host);
expect(screen.getAllByRole("dialog")).toHaveLength(1);
expect(mocks.request.mock.calls.some(([action]) => action === "remote.trust")).toBe(false);
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
});
it("does not reopen verification after cancelling a pending fingerprint read", async () => {
let finish: ((value: { fingerprint: string; challenge: string }) => void) | undefined;
mocks.request.mockImplementation(async (action: string) => {
if (action === "remote.save") return { id: profile.id };
if (action === "remote.connect") throw new Error("host_key_unknown");
return new Promise<{ fingerprint: string; challenge: string }>((resolve) => { finish = resolve; });
});
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: profile.host } });
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await waitFor(() => expect(finish).toBeDefined());
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
await act(async () => { finish?.({ fingerprint: "SHA256:example", challenge: "one-use" }); });
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(screen.queryByText("SHA256:example")).not.toBeInTheDocument();
});
it("doesn't create privileged controls on an unsupported remote gateway", async () => {
@@ -280,20 +710,26 @@ describe("remote instance UX", () => {
expect(mocks.read).not.toHaveBeenCalled();
expect(mocks.discover).not.toHaveBeenCalled();
expect(screen.queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Connect to remote nanobot…" })).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Add server" })).not.toBeInTheDocument();
});
it("offers existing SSH hosts or manual inline setup for the first server", async () => {
it("keeps the directory quiet and offers one focused add-server dialog", async () => {
mocks.read.mockResolvedValue({ available: true, profiles: [] });
view(); await openDirectory();
await screen.findByText("No named hosts found. You can enter an SSH address below.");
fireEvent.click(screen.getByRole("button", { name: "Connect to remote nanobot…" }));
expect(mocks.discover).not.toHaveBeenCalled();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
const host = screen.getByRole("textbox", { name: "SSH address" });
expect(host.closest(".settings-row")).not.toBeNull();
expect(screen.getByRole("main")).toContainElement(host);
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(screen.queryByRole("button", { name: "Connect to remote nanobot…" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Save & connect" })).toBeDisabled();
const dialog = screen.getByRole("dialog", { name: "Connect to a server" });
expect(dialog).toContainElement(host);
expect(host).toHaveFocus();
expect(within(dialog).getAllByRole("textbox")).toHaveLength(1);
expect(screen.getByRole("button", { name: "Add server", hidden: true })).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Connect" })).toBeDisabled();
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "Add server" })).toHaveFocus();
expect(screen.getByRole("heading", { name: "Remote connections" })).toBeVisible();
});
it("does not navigate to a remote instance after leaving a pending connection", async () => {
@@ -313,9 +749,11 @@ describe("remote instance UX", () => {
mocks.read.mockResolvedValue({ available: true, profiles: [] });
mocks.request.mockImplementation(() => new Promise<{ id: string }>((resolve) => { finish = resolve; }));
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Connect to remote nanobot…" }));
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: "ubuntu@example.test" } });
fireEvent.click(screen.getByRole("button", { name: "Save & connect" }));
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
fireEvent.click(screen.getByRole("button", { name: "New topic" }));
await act(async () => { finish?.({ id: profile.id }); });
expect(mocks.request).toHaveBeenCalledTimes(1);
@@ -324,7 +762,7 @@ describe("remote instance UX", () => {
it("keeps cached servers visible during refresh and lets users retry failed reads", async () => {
view();
await screen.findByRole("button", { name: "Remote connections" });
await screen.findByRole("button", { name: "Switch host" });
mocks.read.mockRejectedValue(new Error("directory_unavailable"));
await openDirectory();
await screen.findByRole("alert");
@@ -361,53 +799,82 @@ describe("remote instance UX", () => {
{ host: "staging", source: "/home/test/.ssh/hosts", ssh_config: "" },
], files: ["/home/test/.ssh/config"], incomplete: false });
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
await screen.findByRole("button", { name: "Use team-sg" });
expect(mocks.request).not.toHaveBeenCalled();
fireEvent.change(screen.getByRole("textbox", { name: "Search SSH hosts" }), { target: { value: "team" } });
const address = screen.getByRole("textbox", { name: "SSH address" });
fireEvent.keyDown(address, { key: "ArrowDown" });
expect(screen.getByRole("button", { name: "Use team-sg" })).toHaveFocus();
fireEvent.keyDown(document.activeElement!, { key: "ArrowDown" });
expect(screen.getByRole("button", { name: "Use staging" })).toHaveFocus();
fireEvent.keyDown(document.activeElement!, { key: "ArrowUp" });
fireEvent.keyDown(document.activeElement!, { key: "ArrowUp" });
expect(address).toHaveFocus();
fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: "team" } });
expect(screen.queryByRole("button", { name: "Use staging" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Use team-sg" }));
expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue("team-sg");
fireEvent.click(screen.getByRole("button", { name: "Save & connect" }));
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await readyRemote();
expect(mocks.request).toHaveBeenCalledWith("remote.save", expect.objectContaining({ profile: expect.objectContaining({ host: "team-sg", ssh_config: "", port: null }) }), 65_000);
});
it("reads a custom SSH config and carries that path to the selected profile", async () => {
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Use another SSH config file" }));
fireEvent.change(screen.getByRole("textbox", { name: "SSH config file to read" }), { target: { value: "/team/ssh_config" } });
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
fireEvent.click(screen.getByRole("button", { name: "Connection options" }));
mocks.discover.mockResolvedValue({ hosts: [{ host: "team", source: "/team/ssh_config", ssh_config: "/team/ssh_config" }], files: ["/team/ssh_config"], incomplete: false });
fireEvent.click(screen.getByRole("button", { name: "Read hosts" }));
fireEvent.change(screen.getByRole("textbox", { name: "SSH config file (optional)" }), { target: { value: "/team/ssh_config" } });
fireEvent.click(await screen.findByRole("button", { name: "Use team" }));
fireEvent.click(screen.getByRole("button", { name: "Advanced options" }));
expect(screen.getByRole("textbox", { name: "SSH config file (optional)" })).toHaveValue("/team/ssh_config");
expect(screen.getByRole("spinbutton", { name: "SSH port" })).toHaveValue(null);
expect(mocks.discover).toHaveBeenCalledWith({ ssh_config: "/team/ssh_config" });
const reads = mocks.discover.mock.calls.length;
fireEvent.click(screen.getByRole("button", { name: "Back" }));
expect(screen.getByRole("button", { name: "Use team" })).toBeVisible();
expect(screen.getByRole("textbox", { name: "SSH config file to read" })).toHaveValue("/team/ssh_config");
expect(mocks.discover).toHaveBeenCalledTimes(reads);
expect(screen.queryByRole("button", { name: "Read hosts" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
await readyRemote();
expect(mocks.request).toHaveBeenCalledWith("remote.save", expect.objectContaining({ profile: expect.objectContaining({ host: "team", ssh_config: "/team/ssh_config" }) }), 65_000);
});
it("keeps manual entry available for an invalid discovery response", async () => {
mocks.discover.mockResolvedValue({ hosts: [{}], files: [], incomplete: false });
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
await screen.findByRole("alert");
fireEvent.click(screen.getByRole("button", { name: "Connect to remote nanobot…" }));
expect(screen.getByRole("textbox", { name: "SSH address" })).toBeVisible();
expect(mocks.request).not.toHaveBeenCalled();
});
it("ignores late SSH suggestions after changing the config file", async () => {
let finishOld: ((value: unknown) => void) | undefined;
mocks.discover.mockImplementation(({ ssh_config }: { ssh_config: string }) => ssh_config
? Promise.resolve({ hosts: [{ host: "custom-team", source: ssh_config, ssh_config }], files: [ssh_config], incomplete: false })
: new Promise((resolve) => { finishOld = resolve; }));
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
await waitFor(() => expect(finishOld).toBeDefined());
fireEvent.click(screen.getByRole("button", { name: "Connection options" }));
fireEvent.change(screen.getByRole("textbox", { name: "SSH config file (optional)" }), { target: { value: "/team/config" } });
await screen.findByRole("button", { name: "Use custom-team" });
await act(async () => { finishOld?.({ hosts: [{ host: "stale-host", source: "/default", ssh_config: "" }], files: ["/default"], incomplete: false }); });
expect(screen.queryByRole("button", { name: "Use stale-host" })).not.toBeInTheDocument();
expect(screen.getByRole("button", { name: "Use custom-team" })).toBeVisible();
expect(mocks.request).not.toHaveBeenCalled();
});
it("keeps manual setup available when discovery fails and does not clear cached hosts", async () => {
mocks.discover.mockResolvedValue({ hosts: [{ host: "team", source: "/config", ssh_config: "/config" }], files: ["/config"], incomplete: false });
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Add server" }));
chooseExistingSSH();
await screen.findByRole("button", { name: "Use team" });
mocks.discover.mockRejectedValue(new Error("ssh_config_unreadable"));
fireEvent.click(screen.getByRole("button", { name: "Refresh SSH hosts" }));
await screen.findByRole("alert");
expect(screen.getByRole("button", { name: "Use team" })).toBeVisible();
fireEvent.click(screen.getByRole("button", { name: "Connect to remote nanobot…" }));
expect(screen.getByRole("textbox", { name: "SSH address" })).toBeVisible();
});
@@ -447,6 +914,84 @@ describe("remote instance UX", () => {
expect(screen.getByTitle("nanobot on Team server")).toBe(frame);
expect(frame.parentElement).not.toHaveAttribute("inert");
});
it("rechecks on wake and network recovery without reloading or switching hosts", async () => {
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
const rendered = view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Team server ubuntu@example.test" }));
const frame = await readyRemote();
mocks.read.mockClear();
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);
await screen.findByText("Server connection lost");
mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, connected: true }] });
await act(async () => { window.dispatchEvent(new Event("pageshow")); });
expect(mocks.read).toHaveBeenCalledTimes(3);
expect(screen.queryByText("Server connection lost")).not.toBeInTheDocument();
expect(screen.getByTitle("nanobot on Team server")).toBe(frame);
expect(readSelectedRemote()?.id).toBe(profile.id);
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.connect")).toHaveLength(1);
rendered.unmount();
mocks.read.mockClear();
window.dispatchEvent(new Event("online"));
document.dispatchEvent(new Event("visibilitychange"));
expect(mocks.read).not.toHaveBeenCalled();
});
it("coalesces wake signals while a health check is in flight", async () => {
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Team server ubuntu@example.test" }));
await readyRemote();
let finish: ((result: unknown) => void) | undefined;
mocks.read.mockClear().mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
await act(async () => {
window.dispatchEvent(new Event("online"));
window.dispatchEvent(new Event("pageshow"));
document.dispatchEvent(new Event("visibilitychange"));
});
expect(mocks.read).toHaveBeenCalledTimes(1);
await act(async () => { finish?.({ available: true, profiles: [{ ...profile, connected: true }] }); });
expect(readSelectedRemote()?.id).toBe(profile.id);
});
it.each(["pair_authorization_rejected", "remote_auth_failed", "host_key_changed", "incompatible_gateway"])("offers setup rather than endless reconnect for %s", async (code) => {
vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Team server ubuntu@example.test" }));
await readyRemote();
mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, connected: false, connection_error: code }] });
await act(async () => { window.dispatchEvent(new Event("online")); });
await act(async () => { window.dispatchEvent(new Event("pageshow")); });
expect(screen.getByText(i18n.t(`remote.errors.${code}`))).toBeVisible();
expect(screen.queryByRole("button", { name: "Reconnect" })).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "Manage connections…" }));
expect(readSelectedRemote()).toBeNull();
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.disconnect")).toHaveLength(0);
});
it("dismissing a restore error does not leave an endless opening screen", async () => {
rememberSelectedRemote(connection);
mocks.request.mockRejectedValue(new Error("ssh_unreachable"));
view();
await screen.findByText("Server connection lost");
fireEvent.pointerDown(screen.getByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });
fireEvent.click(await screen.findByRole("button", { name: "Close" }));
fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });
expect(screen.getByText("Server connection lost")).toBeVisible();
expect(screen.getByRole("button", { name: "Reconnect" })).toBeVisible();
expect(screen.queryByText("Opening your server…")).not.toBeInTheDocument();
});
it.each([[-1, true], [3, true], [30, false]])("shows only relevant device expiry hints at %i days", async (days, visible) => {
mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, paired: true,
authorized_until: Math.floor(Date.now() / 1000) + days * 86400 }] });
view(false, true);
await screen.findByRole("button", { name: /Team server ubuntu@example.test/ });
expect(!!screen.queryByText(days < 0 ? /Authorization expired/ : /Authorization expires/)).toBe(visible);
});
});
it.each(["https://evil.example/", "http://user@127.0.0.1:23456/", "javascript:alert(1)", "http://127.0.0.1:23456/wrong"])("rejects unsafe navigation %s", (url) => {
@@ -0,0 +1,37 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { clearPairReturn, initializePairReturn, parsePairReturn, readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";
const id = "c6f4f0b0-99d2-4b90-883e-903353a4a0dc";
const code = `nbpc1.${btoa(JSON.stringify({ id, data: "encrypted" })).replace(/=+$/, "")}`;
afterEach(() => { clearPairReturn(); vi.unstubAllGlobals(); });
describe("pairing return link", () => {
it("parses only a bounded return receipt, never a hostname or executable action", () => {
expect(parsePairReturn(`#/remote?pairing=${code}`)).toEqual({ id, code });
expect(parsePairReturn(`#/new?pairing=${code}`)).toBeNull();
expect(parsePairReturn("#/remote")).toBeNull();
for (const invalid of ["bad", "nbpc1." + "A".repeat(32769), "nbpc1.e30", code + "&pairing=" + code]) {
expect(parsePairReturn(`#/remote?pairing=${invalid}`)).toEqual({ id: "", code: "" });
}
});
it("removes fragment data before notifying the UI, without persisting it", () => {
const replaceState = vi.fn();
const win = { top: null as unknown, location: { hash: `#/remote?pairing=${code}`, hostname: "127.0.0.1", protocol: "http:", pathname: "/", search: "" }, history: { replaceState } };
win.top = win;
vi.stubGlobal("window", win);
const listener = vi.fn(() => expect(replaceState).toHaveBeenCalledWith(null, "", "/#/remote"));
const unsubscribe = subscribePairReturn(listener);
initializePairReturn();
expect(readPairReturn()).toEqual({ id, code });
expect(listener).toHaveBeenCalledOnce();
unsubscribe();
});
it.each([true, false])("rejects a non-local controller (embedded=%s)", (embedded) => {
const win = { top: null as unknown, location: { hash: `#/remote?pairing=${code}`, hostname: embedded ? "localhost" : "example.com", protocol: "http:", pathname: "/", search: "" }, history: { replaceState: vi.fn() } };
win.top = embedded ? {} : win;
vi.stubGlobal("window", win);
initializePairReturn();
expect(win.history.replaceState).toHaveBeenCalled();
expect(readPairReturn()).toBeNull();
});
});
+30
View File
@@ -0,0 +1,30 @@
import { describe, expect, it } from "vitest";
import { parseSSHAddress } from "@/lib/ssh-address";
describe("SSH address import", () => {
it.each(["team", "ubuntu@example.test", "user@2001:db8::1"])("keeps the address %s", (host) => {
expect(parseSSHAddress(` ${host} `)).toEqual({ host });
});
it("imports quoted paths, a login user and port without running a command", () => {
expect(parseSSHAddress('ssh -p 2222 -l ubuntu -i "~/.ssh/team key" -F ~/.ssh/work team')).toEqual({
host: "ubuntu@team", port: 2222, identity_file: "~/.ssh/team key", ssh_config: "~/.ssh/work",
});
});
it("supports attached option values and preserves Windows path separators", () => {
expect(parseSSHAddress('ssh -p2222 -i "C:\\Users\\User Name\\.ssh\\id_ed25519" team')).toEqual({
host: "team", port: 2222, identity_file: "C:\\Users\\User Name\\.ssh\\id_ed25519",
});
expect(() => parseSSHAddress("ssh -F'bad' host")).toThrow("invalid_ssh_command");
expect(parseSSHAddress("ssh -i '/tmp/my key' team")).toEqual({ host: "team", identity_file: "/tmp/my key" });
});
it.each([
"", "ssh -p", "ssh -p 0 team", "ssh -p 65536 team", "ssh -p 2.5 team",
"ssh -p 22 -p 23 team", "ssh -i", 'ssh -i "unterminated team',
"ssh -l root ubuntu@team", "ssh -l root", "ssh one two", "ssh team -p 22",
"ssh -o StrictHostKeyChecking=no team", "ssh -J jump team", "ssh -A team",
"ssh team whoami", "ssh team; whoami", "ssh team && whoami", "ssh team\nwhoami",
"ssh -i $(touch) team", "ssh -i $HOME/key team", "https://team", "user@host;evil",
])("rejects ambiguous or unsupported input without silently discarding it: %s", (text) => {
expect(() => parseSSHAddress(text)).toThrow("invalid_ssh_command");
});
});