ui(remote): manage connections without switching hosts

This commit is contained in:
Xubin Ren committed 2026-10-02 11:36:34 +08:00
1 parent f4e45c98d7
commit 715bdf45c8
9 files changed
+241 -50

No files matched your search

+10 -3
View File
@@ -2,7 +2,7 @@
Open your local **nanobot WebUI**, click the current host (initially **Local**)
at the bottom of the sidebar, and choose **Manage connections…**. This is the
single entry point for switching and managing hosts. The page lists this computer
single entry point for switching and managing hosts. The panel lists this computer
and your saved servers. Choose
**Connect to remote nanobot** to copy a prepared pairing command, or choose **Other ways → Use existing SSH settings**
to enter an SSH address such as
@@ -252,8 +252,15 @@ desktop-host packaging and other platforms still need their own acceptance.
The host switcher lives beside **Settings at the bottom of the sidebar**, showing
**Local** or your saved server name. It is also available in Settings. Its menu
opens upward and shows the computer name, recent hosts, and **Manage connections…**.
With the sidebar collapsed, the icon still opens the same menu. Recent, loaded
hosts show **Ready**. Remote
With the sidebar collapsed, the icon still opens the same menu. A check marks
the host you are viewing; a separate green dot marks an established connection.
Saved but disconnected hosts stay gray, and connecting or failed hosts have
distinct progress/error indicators. **Manage connections…** opens a side panel
without switching to Local, changing the route, or disconnecting the server.
Closing it returns to the same view and draft. The panel uses the same connection
states with text labels, so color is never the only way to distinguish them.
Selecting a host in the panel switches only after its view is ready; a failed
attempt leaves the original host selected. Remote
connection setup is hidden inside the embedded remote view, and connecting back
to the same gateway is rejected rather than creating a nested local session.
+5 -3
View File
@@ -1111,7 +1111,9 @@ function Shell({
onNativeEngineRestart: () => Promise<string>;
}) {
const { t, i18n } = useTranslation();
const localActive = useRemoteConnections()?.localActive !== false;
const remoteConnections = useRemoteConnections();
const localActive = remoteConnections?.localActive !== false;
const managingConnections = remoteConnections?.managing === true;
const { client, getToken } = useClient();
const { theme, toggle } = useTheme();
const {
@@ -1156,8 +1158,8 @@ function Shell({
const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);
useEffect(() => {
// The drawer portals outside the local host panel; don't leave it over a remote view.
if (!localActive) setMobileSidebarOpen(false);
}, [localActive]);
if (!localActive || managingConnections) setMobileSidebarOpen(false);
}, [localActive, managingConnections]);
const mobileSidebarRef = useRef<HTMLDivElement>(null);
const [sessionSearchOpen, setSessionSearchOpen] = useState(false);
const mobileWorkbench = useMediaQuery("(max-width: 767px)");
@@ -0,0 +1,20 @@
import { CircleAlert, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { cn } from "@/lib/utils";
export type HostConnectionState = "open" | "closed" | "connecting" | "error";
/** Connectivity is independent of which host the user is currently viewing. */
export function HostConnectionStatus({ state, compact = false }: {
state: HostConnectionState;
compact?: boolean;
}) {
const { t } = useTranslation();
const label = t(`connection.${state}`);
return <span role="status" title={label} className="inline-flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">
{state === "connecting" ? <Loader2 aria-hidden className="h-3.5 w-3.5 animate-spin motion-reduce:animate-none" />
: state === "error" ? <CircleAlert aria-hidden className="h-3.5 w-3.5 text-amber-600 dark:text-amber-400" />
: <span aria-hidden className={cn("h-1.5 w-1.5 rounded-full", state === "open" ? "bg-emerald-500" : "bg-muted-foreground/40")} />}
<span className={compact ? "sr-only" : undefined}>{label}</span>
</span>;
}
+5 -3
View File
@@ -8,6 +8,7 @@ import { useClient } from "@/providers/ClientProvider";
import { cn } from "@/lib/utils";
import type { ConnectionStatus } from "@/lib/types";
import type { HostAnchor, EmbeddedHost } from "./host-bridge";
import { HostConnectionStatus, type HostConnectionState } from "./HostConnectionStatus";
export interface HostPicker {
kind: "shell";
@@ -15,7 +16,7 @@ export interface HostPicker {
hostname: string;
localName: string;
currentId: string | null;
profiles: { id: string; name: string; host: string; ready: boolean }[];
profiles: { id: string; name: string; host: string; state: HostConnectionState }[];
recentIds: string[];
pending: { id: string; name: string } | null;
error: string;
@@ -100,11 +101,12 @@ function HostMenuItems({ picker }: { picker: HostPicker }) {
</DropdownMenuItem>}
{showLocal && !!profiles.length && <DropdownMenuSeparator />}
{profiles.map((profile) => <DropdownMenuItem key={profile.id} onSelect={() => picker.select(profile.id)} className="gap-2.5"
aria-label={`${profile.name} ${profile.host}`} aria-describedby={`host-state-${profile.id}`}
title={`${profile.name} · ${profile.host}`} aria-current={picker.currentId === profile.id || undefined}>
<Server className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1"><span className="block truncate">{profile.name}</span><span className="block truncate text-xs text-muted-foreground">{profile.host}</span></span>
{picker.pending?.id === profile.id ? <Loader2 className="h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" /> : picker.currentId === profile.id ? <Check className="h-4 w-4 shrink-0" />
: profile.ready ? <span className="shrink-0 text-[11px] text-muted-foreground">{t("remote.ready")}</span> : null}
<span id={`host-state-${profile.id}`}><HostConnectionStatus state={profile.state} compact /></span>
{picker.currentId === profile.id && <Check aria-label={t("remote.current")} className="h-4 w-4 shrink-0" />}
</DropdownMenuItem>)}
{!showLocal && !profiles.length && <p role="status" className="px-2.5 py-6 text-center text-xs text-muted-foreground">{t("remote.noMatchingHosts")}</p>}
</div>
@@ -16,6 +16,7 @@ import { useRemoteConnections } from "./RemoteInstances";
import { SSHHostPicker } from "./SSHHostPicker";
import { QuickPairSetup } from "./QuickPairSetup";
import { PairRouteSettings } from "./PairRouteSettings";
import { HostConnectionStatus } from "./HostConnectionStatus";
const emptyProfile = (): Omit<RemoteProfile, "id" | "connected"> => ({
name: "", host: "", port: null, ssh_config: "", identity_file: "",
@@ -23,9 +24,10 @@ const emptyProfile = (): Omit<RemoteProfile, "id" | "connected"> => ({
});
/** The page is a server directory. Add/edit/first-use verification share one dialog. */
export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChromeInset = false, onBackToChat }: {
export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChromeInset = false, inPanel = false, onBackToChat }: {
mainNavigationExpanded?: boolean;
hostChromeInset?: boolean;
inPanel?: boolean;
onBackToChat: () => void;
}) {
const { t } = useTranslation();
@@ -56,6 +58,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
const mounted = useRef(true);
const operation = useRef(0);
const optionsId = useId();
const statusId = useId();
const refresh = connections?.refresh;
// Keep confirmation content intact during Radix's exit animation.
@@ -248,31 +251,36 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
<div className="min-w-0 flex-1 overflow-y-auto [scrollbar-gutter:stable]">
<div data-settings-section="remote" data-main-navigation-expanded={mainNavigationExpanded}
className={cn("settings-grid settings-feature-page mx-auto w-full animate-in fade-in-0 slide-in-from-bottom-1 py-6 duration-200 ease-out motion-reduce:animate-none sm:py-8 lg:py-12",
hostChromeInset && "pt-[4.25rem] sm:pt-[4.25rem] lg:pt-[4.75rem]")}>
<div className="settings-feature-header mb-7">
hostChromeInset && "pt-[4.25rem] sm:pt-[4.25rem] lg:pt-[4.75rem]",
inPanel && "px-6 py-4 sm:py-4 lg:py-4 [--settings-margin:0px] [--settings-inset:16px]")}>
{!inPanel && <div className="settings-feature-header mb-7">
<Button variant="ghost" size="sm" className="touch-target mb-4 gap-1 lg:hidden" onClick={onBackToChat}>
<ChevronLeft className="h-4 w-4" />{t("settings.backToChat")}
</Button>
<h1 className="text-[24px] font-normal leading-tight tracking-normal text-foreground sm:text-[28px]">{t("remote.title")}</h1>
</div>
</div>}
<div className="settings-stack">
<p className="settings-list-inset text-[13px] leading-6 text-muted-foreground">{t("remote.description")}</p>
{directory?.available && <>
<SettingsGroup>
<div className="settings-list-row flex items-center gap-3 py-3">
<button type="button" className="settings-list-row settings-hover flex w-full items-center gap-3 py-3 text-left"
aria-current={connections.localActive || undefined} onClick={connections.selectLocal}>
<Laptop className="h-[18px] w-[18px] shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1"><span className="block text-[14px] font-medium">{t("remote.local")}</span>
{directory.machine_name && <span className="mt-0.5 block truncate text-xs text-muted-foreground">{directory.machine_name}</span>}</span>
<span className="flex items-center gap-1.5 text-xs text-muted-foreground"><Check className="h-3.5 w-3.5" />{t("remote.current")}</span>
</div>
{connections.localActive && <span className="flex items-center gap-1.5 text-xs text-muted-foreground"><Check className="h-3.5 w-3.5" />{t("remote.current")}</span>}
</button>
</SettingsGroup>
{directory.profiles.length > 0 && <SettingsGroup>
{directory.profiles.map((profile) => <div key={profile.id} className="settings-list-row settings-hover flex items-center gap-2 transition-colors">
<button type="button" className="flex min-h-[60px] min-w-0 flex-1 items-center gap-3 rounded-xl py-3 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" disabled={!!busy} onClick={(event) => {
<button type="button" aria-label={`${profile.name} ${profile.host}`} aria-describedby={`${statusId}-${profile.id}`}
aria-current={connections.activeHostId === profile.id || undefined}
className="flex min-h-[60px] min-w-0 flex-1 items-center gap-3 rounded-xl py-3 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" disabled={!!busy} onClick={(event) => {
editorTrigger.current = event.currentTarget; void connect(profile.id);
}}>
{busy === profile.id ? <Loader2 className="h-[18px] w-[18px] shrink-0 animate-spin text-muted-foreground" /> : <Server className="h-[18px] w-[18px] shrink-0 text-muted-foreground" />}
<span className="min-w-0 flex-1"><span className="block truncate text-[14px] font-medium">{profile.name}</span><span className="mt-0.5 block truncate text-xs text-muted-foreground">{profile.host}</span>
<span id={`${statusId}-${profile.id}`} className="mt-1 block"><HostConnectionStatus state={connections.hostStates[profile.id] || "closed"} /></span>
{profile.paired && typeof profile.authorized_until === "number" && Number.isFinite(profile.authorized_until)
&& profile.authorized_until * 1000 <= Date.now() + 7 * 86_400_000 && <span className="mt-1 block text-xs leading-5 text-muted-foreground">
{t(profile.authorized_until * 1000 <= Date.now() ? "remote.pair.expiredDevice" : "remote.pair.expiringDevice", {
@@ -280,7 +288,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
})}
</span>}
</span>
<ArrowUpRight className="h-4 w-4 text-muted-foreground" />
{connections.activeHostId === profile.id ? <Check aria-label={t("remote.current")} className="h-4 w-4 shrink-0 text-muted-foreground" /> : <ArrowUpRight aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />}
</button>
<DropdownMenu><DropdownMenuTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8 shrink-0" disabled={!!busy}
onPointerDown={(event) => { editorTrigger.current = event.currentTarget; }}
@@ -1,16 +1,23 @@
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useSyncExternalStore, type ReactNode } from "react";
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
import { Loader2, PlugZap } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Sheet, SheetContent, SheetTitle } from "@/components/ui/sheet";
import { needsRemoteSetup, type RemoteDirectory } from "@/lib/remote-instances";
import { useHostSessions } from "./useHostSessions";
import { HostNavigationContext, HostSwitcher, RemoteHostMenu, type HostPicker } from "./HostSwitcher";
import { useSidebarHostBridge } from "./useSidebarHostBridge";
import { readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";
import { RemoteConnectionsPage } from "./RemoteConnectionsPage";
import type { HostConnectionState } from "./HostConnectionStatus";
const RemoteContext = createContext<{
available: boolean;
localActive: boolean;
activeHostId: string | null;
hostStates: Record<string, HostConnectionState>;
managing: boolean;
selectLocal: () => void;
openHostIds: string[];
directory: RemoteDirectory | null;
directoryError: boolean;
@@ -25,6 +32,11 @@ export function useRemoteConnections() { return useContext(RemoteContext); }
export function RemoteInstances({ children }: { children: ReactNode }) {
const { t } = useTranslation();
const hosts = useHostSessions();
const [managing, setManaging] = useState(false);
const managementOpen = useRef(false);
const managementConnect = useRef(false);
const managementPanel = useRef<HTMLDivElement>(null);
const legacyFooter = useRef<HTMLDivElement>(null);
const returnedPair = useSyncExternalStore(subscribePairReturn, readPairReturn);
const returnLocal = hosts.local;
useEffect(() => { if (returnedPair) returnLocal(); }, [returnedPair, returnLocal]);
@@ -45,7 +57,9 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
for (const id of bridge.readyIds) hosts.loaded(id);
}, [bridge.readyIds, hosts.loaded]);
const restoreFocus = () => {
if (activeHostId.current) bridge.focus(activeHostId.current);
const fallback = legacyFooter.current?.querySelector<HTMLElement>("[data-host-switcher]");
if (activeHostId.current && fallback) fallback.focus({ preventScroll: true });
else if (activeHostId.current) bridge.focus(activeHostId.current);
else restoreLocalFocus();
};
const available = directory?.available === true || hosts.directoryError;
@@ -53,7 +67,32 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
const offline = !!selected && (activeFrame?.offline || (!activeFrame && pending?.id !== selected.id));
const recoveryCode = (hosts.errorId === selected?.id ? error : "") || activeFrame?.error || "";
const recoveryMessage = recoveryCode ? t(`remote.errors.${recoveryCode}`, { defaultValue: t("remote.errors.unknown") }) : t("remote.noFallback");
const manage = () => { hosts.local(); window.location.hash = "/remote"; };
const changeManagement = (open: boolean) => {
managementOpen.current = open;
// Dismissing management cancels only work started there, not an existing
// switch or session restoration that happens to be running behind it.
if (!open && managementConnect.current) hosts.cancel();
setManaging(open);
};
const manage = () => { bridge.close(); changeManagement(true); };
const selectLocal = () => { hosts.local(); changeManagement(false); };
const connect = async (id: string, stillWanted: () => boolean = () => true) => {
const wanted = () => stillWanted() && (!managing || managementOpen.current);
if (!wanted()) return;
managementConnect.current = managing;
try {
await hosts.connect(id, wanted);
managementConnect.current = false;
if (wanted()) changeManagement(false);
} finally { managementConnect.current = false; }
};
const hostStates: Record<string, HostConnectionState> = {};
for (const profile of directory?.profiles || []) {
const frame = frames.find((item) => item.connection.id === profile.id);
hostStates[profile.id] = pending?.id === profile.id ? "connecting"
: hosts.directoryError || frame?.offline || hosts.errorId === profile.id || (profile.connection_error && profile.connection_error !== "disconnected") ? "error"
: profile.connected || (frame?.loaded && !frame.offline) ? "open" : "closed";
}
const switchHost = (id: string) => {
// The session module owns attempt-scoped errors, including cancelled work.
void hosts.connect(id).catch(() => {});
@@ -61,11 +100,10 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
const picker: HostPicker = {
kind: "shell", name: selected?.name || t("remote.localShort"), hostname: selected?.hostname || directory?.machine_name || "nanobot",
localName: directory?.machine_name || "nanobot", currentId: selected?.id || null, recentIds: hosts.recentIds,
profiles: (directory?.profiles || []).map(({ id, name, host }) => ({ id, name, host,
ready: frames.some((frame) => frame.connection.id === id && !frame.offline && frame.loaded) })),
profiles: (directory?.profiles || []).map(({ id, name, host }) => ({ id, name, host, state: hostStates[id] })),
pending, error: message, offline: !!offline, select: (id) => { if (id) switchHost(id); else hosts.local(); },
manage,
cancel: hosts.cancel, clearError: hosts.clearError, restoreFocus,
cancel: hosts.cancel, clearError: hosts.clearError, restoreFocus: () => { if (!managing) restoreFocus(); },
};
useEffect(() => { if (selected) document.title = `${selected.name} · nanobot`; }, [selected]);
useEffect(() => {
@@ -89,8 +127,9 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
}, [selected]);
return <RemoteContext.Provider value={{ available, localActive: !selected, directory,
activeHostId: selected?.id || null, hostStates, managing, selectLocal,
openHostIds: frames.map((frame) => frame.connection.id),
directoryError: hosts.directoryError, refresh: hosts.refresh, connect: hosts.connect, disconnect: hosts.disconnect, cancel: hosts.cancel }}>
directoryError: hosts.directoryError, refresh: hosts.refresh, connect, disconnect: hosts.disconnect, cancel: hosts.cancel }}>
<HostNavigationContext.Provider value={bridge.embedded || (available || selected ? picker : null)}>
<div className="flex h-full min-h-0 flex-col bg-background">
<div className="relative min-h-0 flex-1 overflow-hidden">
@@ -126,10 +165,18 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
</div>
{/* Older remote bundles cannot host the control. Keep an explicit exit
in a compact bottom strip, never cover their sidebar controls. */}
{selected && (!bridge.readyIds.includes(selected.id) || offline) && <div data-testid="legacy-host-footer" className="flex shrink-0 items-center border-t border-border/50 bg-sidebar px-2.5 py-1">
{selected && (!bridge.readyIds.includes(selected.id) || offline) && <div ref={legacyFooter} data-testid="legacy-host-footer" className="flex shrink-0 items-center border-t border-border/50 bg-sidebar px-2.5 py-1">
<div className="flex w-52 min-w-0"><HostSwitcher /></div>
</div>}
<RemoteHostMenu picker={picker} anchor={bridge.anchor} onClose={bridge.close} />
<Sheet open={managing} onOpenChange={changeManagement}>
<SheetContent ref={managementPanel} aria-describedby={undefined} className="w-full gap-0 overflow-hidden bg-settings-canvas outline-none sm:max-w-xl"
onOpenAutoFocus={(event) => { event.preventDefault(); managementPanel.current?.focus(); }}
onCloseAutoFocus={(event) => { event.preventDefault(); restoreFocus(); }}>
<div className="shrink-0 px-6 pb-2 pt-7 pr-12"><SheetTitle className="text-xl font-medium">{t("remote.title")}</SheetTitle></div>
<RemoteConnectionsPage inPanel onBackToChat={() => changeManagement(false)} />
</SheetContent>
</Sheet>
</div>
</HostNavigationContext.Provider>
</RemoteContext.Provider>;
+9 -6
View File
@@ -683,7 +683,7 @@ describe("App layout", () => {
expect(window.location.hash).toBe("#/channels");
});
it("opens Remote connections in the main shell and restores it through browser history", async () => {
it("opens management over the current view while keeping the standalone deep link", async () => {
requestMutationSpy.mockResolvedValue({ hosts: [], files: [], incomplete: false });
mockFetchRoutes({
"/api/settings": baseSettingsPayload(),
@@ -692,6 +692,8 @@ describe("App layout", () => {
render(<App />);
await waitFor(() => expect(connectSpy).toHaveBeenCalled());
const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
const originalHash = window.location.hash;
const originalTitle = document.title;
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…" }));
@@ -702,9 +704,10 @@ describe("App layout", () => {
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");
expect(window.location.hash).toBe(originalHash);
expect(document.title).toBe(originalTitle);
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
fireEvent.click(within(screen.getByRole("dialog", { name: "Remote connections" })).getByRole("button", { name: "Close" }));
fireEvent.click(within(sidebar).getByRole("button", { name: "New topic" }));
expect(window.location.hash).toBe("#/new");
expect(screen.queryByRole("textbox", { name: "SSH address" })).not.toBeInTheDocument();
@@ -735,11 +738,11 @@ describe("App layout", () => {
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());
await waitFor(() => expect(sheet).not.toBeInTheDocument());
expect(screen.getByRole("dialog", { name: "Remote connections" })).toBeVisible();
expect(await screen.findByRole("heading", { name: "Remote connections" })).toBeVisible();
expect(window.location.hash).toBe("#/remote");
expect(window.location.hash).not.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: "Connect to remote nanobot" }));
expect(await screen.findByRole("dialog", { name: "Connect to remote nanobot" })).toBeVisible();
});
+3 -3
View File
@@ -15,7 +15,7 @@ function picker(count: number): HostPicker {
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,
host: `ubuntu@host-${index + 1}.test`, state: "closed",
})),
select: vi.fn(), manage: vi.fn(), cancel: vi.fn(), clearError: vi.fn(), restoreFocus: vi.fn(),
};
@@ -181,8 +181,8 @@ describe("host switcher", () => {
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 names = () => within(screen.getByRole("group")).getAllByRole("menuitem").map((item) => item.getAttribute("aria-label") || item.textContent);
expect(names().slice(0, 4)).toEqual(["Local nanobotMy-Mac", "Server 20 ubuntu@host-20.test", "Server 9 ubuntu@host-9.test", "Server 1 ubuntu@host-1.test"]);
const before = names();
rendered.rerender(<HostNavigationContext.Provider value={{ ...value, recentIds: [value.profiles[5].id] }}><HostSwitcher /></HostNavigationContext.Provider>);
expect(names()).toEqual(before);
+117 -15
View File
@@ -88,6 +88,106 @@ function chooseExistingSSH() {
}
describe("remote instance UX", () => {
it("manages connections without changing the remote host, route, frame or authorization", async () => {
view();
await chooseHost("Team server ubuntu@example.test");
const frame = await readyRemote();
const originalTitle = document.title;
const originalHash = window.location.hash;
mocks.request.mockClear();
await openDirectory();
const panel = screen.getByRole("dialog", { name: "Remote connections" });
const current = within(panel).getByRole("button", { name: "Team server ubuntu@example.test" });
expect(current).toHaveAttribute("aria-current", "true");
expect(within(current).getByRole("status")).toHaveTextContent("Connected");
expect(within(current).getByRole("status").querySelector(".bg-emerald-500")).not.toBeNull();
expect(within(panel).getByRole("button", { name: "Local nanobot Xubin-Mac" })).not.toHaveAttribute("aria-current");
expect(readSelectedRemote()?.id).toBe(profile.id);
expect(window.location.hash).toBe(originalHash);
expect(document.title).toBe(originalTitle);
fireEvent.click(within(panel).getByRole("button", { name: "Close" }));
await waitFor(() => expect(panel).not.toBeInTheDocument());
expect(screen.getByTitle("nanobot on Team server")).toBe(frame);
expect(frame).toBeVisible();
expect(readSelectedRemote()?.id).toBe(profile.id);
expect(screen.getByRole("button", { name: "Switch host" })).toHaveFocus();
expect(mocks.request).not.toHaveBeenCalled();
});
it("retains a local draft when management is opened and dismissed with Escape", async () => {
view();
const draft = screen.getByRole("textbox", { name: "Local draft" });
draft.focus();
fireEvent.change(draft, { target: { value: "Keep this unsent draft" } });
await openDirectory();
fireEvent.keyDown(screen.getByRole("dialog"), { key: "Escape" });
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(screen.getByRole("textbox", { name: "Local draft" })).toBe(draft);
expect(draft).toHaveValue("Keep this unsent draft");
expect(draft).toHaveFocus();
expect(mocks.request).not.toHaveBeenCalled();
});
it("does not cancel an earlier host switch just because management was opened and closed", async () => {
let finish!: (value: RemoteConnection) => void;
mocks.request.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));
view();
await chooseHost("Team server ubuntu@example.test");
await openDirectory();
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Close" }));
await act(async () => finish(connection));
const frame = await readyRemote();
expect(frame).toBeVisible();
expect(readSelectedRemote()?.id).toBe(profile.id);
});
it("only returns local when the user explicitly selects it in management", async () => {
view();
await chooseHost("Team server ubuntu@example.test");
const frame = await readyRemote();
await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Local nanobot Xubin-Mac" }));
await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
expect(readSelectedRemote()).toBeNull();
expect(screen.getByText("Local conversations")).toBeVisible();
expect(frame).toBeInTheDocument();
expect(mocks.request.mock.calls.some(([action]) => action === "remote.disconnect")).toBe(false);
});
it.each([
{ connected: false, connection_error: "disconnected", label: "Disconnected" },
{ connected: true, connection_error: "", label: "Connected" },
{ connected: false, connection_error: "ssh_auth_failed", label: "Connection error" },
])("shows $label independently of the current view in both management and the menu", async ({ label, ...health }) => {
mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, ...health }] });
view();
await openDirectory();
const row = screen.getByRole("button", { name: "Team server ubuntu@example.test" });
expect(row).not.toHaveAttribute("aria-current");
expect(within(row).getByRole("status")).toHaveTextContent(label);
fireEvent.click(within(screen.getByRole("dialog")).getByRole("button", { name: "Close" }));
fireEvent.pointerDown(screen.getByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });
const item = await screen.findByRole("menuitem", { name: "Team server ubuntu@example.test" });
expect(within(item).getByRole("status")).toHaveTextContent(label);
expect(item).toHaveAccessibleDescription(label);
});
it("leaves management open on a failed switch without moving off the current server", async () => {
const other = { ...profile, id: "f1b18099-61d5-41d7-9c1d-6f647f7000e5", name: "Other server" };
mocks.read.mockResolvedValue({ available: true, profiles: [profile, other] });
view();
await chooseHost("Team server ubuntu@example.test");
await readyRemote();
await openDirectory();
mocks.request.mockRejectedValue(new Error("ssh_unreachable"));
fireEvent.click(screen.getByRole("button", { name: "Other server ubuntu@example.test" }));
expect(await screen.findByRole("alert")).toHaveTextContent(i18n.t("remote.errors.ssh_unreachable"));
expect(readSelectedRemote()?.id).toBe(profile.id);
fireEvent.click(within(screen.getByRole("dialog", { name: "Connect to a server" })).getByRole("button", { name: "Cancel" }));
expect(within(screen.getByRole("button", { name: "Other server ubuntu@example.test" })).getByRole("status")).toHaveTextContent("Connection error");
expect(screen.getByRole("dialog", { name: "Remote connections" })).toBeVisible();
});
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; }));
@@ -315,7 +415,7 @@ describe("remote instance UX", () => {
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(screen.queryByRole("dialog", { name: "Connect to a server" })).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);
});
@@ -352,9 +452,9 @@ describe("remote instance UX", () => {
expect(screen.queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();
expect(screen.queryByText("This machine")).not.toBeInTheDocument();
await openDirectory();
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(screen.getByRole("main")).toContainElement(screen.getByText("Team server"));
expect(screen.getByRole("navigation", { name: "Sidebar navigation" })).toBeVisible();
expect(screen.getByRole("dialog", { name: "Remote connections" })).toContainElement(screen.getByText("Team server"));
expect(document.querySelector('nav')).toBeVisible();
expect(window.location.hash).toBe("#/new");
expect(screen.getByText("Local nanobot")).toBeInTheDocument();
expect(screen.getByText("Currently using")).toBeInTheDocument();
expect(screen.getByRole("button", { name: "Connect to remote nanobot" })).toBeInTheDocument();
@@ -431,7 +531,7 @@ describe("remote instance UX", () => {
fireEvent.click(screen.getByRole("button", { name: "Team server ubuntu@example.test" }));
await readyRemote();
await chooseHost("Local nanobot Xubin-Mac");
expect(screen.getByRole("heading", { name: "Remote connections" })).toBeVisible();
expect(screen.getByText("Local conversations")).toBeVisible();
expect(mocks.request.mock.calls.some(([action]) => action === "remote.disconnect")).toBe(false);
expect(readSelectedRemote()).toBeNull();
expect(readRecentRemotes()).toEqual([profile.id]);
@@ -456,7 +556,7 @@ describe("remote instance UX", () => {
await waitFor(() => expect(draft).toHaveFocus());
expect(screen.getByRole("textbox", { name: "Local draft" })).toBe(draft);
expect(draft).toHaveValue("Unsent local draft");
await chooseHost("Team server ubuntu@example.test Ready");
await chooseHost("Team server ubuntu@example.test");
expect(screen.getByTitle("nanobot on Team server")).toBe(frame);
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.connect")).toHaveLength(1);
});
@@ -466,6 +566,7 @@ describe("remote instance UX", () => {
fireEvent.click(screen.getByRole("button", { name: "Team server ubuntu@example.test" }));
await readyRemote();
await chooseHost("Local nanobot Xubin-Mac");
await openDirectory();
fireEvent.pointerDown(screen.getByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false });
fireEvent.click(await screen.findByRole("menuitem", { name: "Disconnect" }));
const dialog = await screen.findByRole("dialog", { name: "Disconnect from Team server?" });
@@ -554,7 +655,7 @@ describe("remote instance UX", () => {
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());
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Edit connection" })).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" }),
@@ -627,7 +728,7 @@ describe("remote instance UX", () => {
expect(mocks.request).not.toHaveBeenCalled();
});
it("closes a successful add dialog so returning local shows the directory", async () => {
it("closes successful setup and restores the original local view on return", async () => {
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Connect to remote nanobot" }));
chooseExistingSSH();
@@ -636,7 +737,7 @@ describe("remote instance UX", () => {
await readyRemote();
await chooseHost("Local nanobot Xubin-Mac");
expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
expect(screen.getByRole("heading", { name: "Remote connections" })).toBeVisible();
expect(screen.getByText("Local conversations")).toBeVisible();
});
it("cancels a dialog's pending connection without a late jump or error", async () => {
@@ -651,7 +752,7 @@ describe("remote instance UX", () => {
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.queryByRole("dialog", { name: "Connect to a server" })).not.toBeInTheDocument();
expect(screen.queryByTitle("nanobot on Team server")).not.toBeInTheDocument();
expect(screen.queryByRole("alert")).not.toBeInTheDocument();
expect(readSelectedRemote()).toBeNull();
@@ -693,7 +794,7 @@ describe("remote instance UX", () => {
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.queryByRole("dialog", { name: "Connect to a server" })).not.toBeInTheDocument();
expect(screen.queryByText("SHA256:example")).not.toBeInTheDocument();
});
@@ -727,7 +828,7 @@ describe("remote instance UX", () => {
expect(screen.getByRole("button", { name: "Connect to remote nanobot", 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());
await waitFor(() => expect(screen.queryByRole("dialog", { name: "Connect to a server" })).not.toBeInTheDocument());
expect(screen.getByRole("button", { name: "Connect to remote nanobot" })).toHaveFocus();
expect(screen.getByRole("heading", { name: "Remote connections" })).toBeVisible();
});
@@ -737,7 +838,7 @@ describe("remote instance UX", () => {
mocks.request.mockImplementation(() => new Promise<RemoteConnection>((resolve) => { finish = resolve; }));
view(); await openDirectory();
fireEvent.click(screen.getByRole("button", { name: "Team server ubuntu@example.test" }));
fireEvent.click(screen.getByRole("button", { name: "New topic" }));
fireEvent.click(within(screen.getByRole("dialog", { name: "Remote connections" })).getByRole("button", { name: "Close" }));
await act(async () => { finish?.(connection); });
expect(screen.getByText("Local conversations")).toBeVisible();
expect(screen.queryByTitle("nanobot on Team server")).not.toBeInTheDocument();
@@ -754,7 +855,7 @@ describe("remote instance UX", () => {
fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: "ubuntu@example.test" } });
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
fireEvent.click(screen.getByRole("button", { name: "Cancel" }));
fireEvent.click(screen.getByRole("button", { name: "New topic" }));
fireEvent.click(within(screen.getByRole("dialog", { name: "Remote connections" })).getByRole("button", { name: "Close" }));
await act(async () => { finish?.({ id: profile.id }); });
expect(mocks.request).toHaveBeenCalledTimes(1);
expect(screen.getByText("Local conversations")).toBeVisible();
@@ -968,7 +1069,8 @@ describe("remote instance UX", () => {
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(readSelectedRemote()?.id).toBe(profile.id);
expect(screen.getByRole("dialog", { name: "Remote connections" })).toBeVisible();
expect(mocks.request.mock.calls.filter(([action]) => action === "remote.disconnect")).toHaveLength(0);
});