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

+6 -8
View File
@@ -1154,6 +1154,10 @@ function Shell({
const [sidebarWidth, setSidebarWidth] = useState(readSidebarWidth);
const [sidebarDragging, setSidebarDragging] = useState(false);
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]);
const mobileSidebarRef = useRef<HTMLDivElement>(null);
const [sessionSearchOpen, setSessionSearchOpen] = useState(false);
const mobileWorkbench = useMediaQuery("(max-width: 767px)");
@@ -1287,6 +1291,7 @@ function Shell({
useEffect(() => {
const applyRoute = () => {
const route = readShellRoute();
if (route.view === "remote") setMobileSidebarOpen(false);
if (currentShellRouteRef.current.view === "settings" && route.view !== "settings" && settingsExitGuardRef.current) {
writeShellRoute(currentShellRouteRef.current, true);
settingsExitGuardRef.current(() => {
@@ -2131,12 +2136,6 @@ function Shell({
setMobileSidebarOpen(false);
}, [activeKey, navigate]);
const onOpenRemoteConnections = useCallback(() => {
setSessionSearchOpen(false);
navigate({ view: "remote", activeKey, settingsSection: "overview" });
setMobileSidebarOpen(false);
}, [activeKey, navigate]);
const onOpenSkills = useCallback(() => {
setSessionSearchOpen(false);
navigate({ view: "skills", activeKey, settingsSection: "skills" });
@@ -2733,11 +2732,10 @@ function Shell({
onOpenApps,
onOpenAutomations,
onOpenChannels,
onOpenRemoteConnections,
onOpenSkills,
onSettingsIntent,
onOpenSearch: onOpenSessionSearch,
activeUtility: view === "apps" || view === "automations" || view === "skills" || view === "channels" || view === "remote" ? view : null,
activeUtility: view === "apps" || view === "automations" || view === "skills" || view === "channels" ? view : null,
onToggleArchived,
pinnedKeys: sidebarPinnedTabKeys,
archivedKeys: sidebarArchivedTabKeys,
+1 -15
View File
@@ -9,7 +9,6 @@ import {
Brain,
CalendarClock,
MessageCircle,
MonitorUp,
PanelLeftClose,
Search,
Settings,
@@ -24,7 +23,6 @@ import {
type SidebarPaneGroup,
} from "@/components/ChatList";
import { HostSwitcher } from "@/components/remote/HostSwitcher";
import { useRemoteConnections } from "@/components/remote/RemoteInstances";
import {
SIDEBAR_SELECTION_ACTION_ITEM_CLASS,
SidebarSelectionHighlight,
@@ -70,10 +68,9 @@ interface SidebarProps {
onOpenSkills: () => void;
onOpenAutomations: () => void;
onOpenChannels: () => void;
onOpenRemoteConnections?: () => void;
onSettingsIntent?: () => void;
onOpenSearch: () => void;
activeUtility?: "apps" | "skills" | "automations" | "channels" | "remote" | null;
activeUtility?: "apps" | "skills" | "automations" | "channels" | null;
onToggleArchived: () => void;
onCollapse?: () => void;
onExpand?: () => void;
@@ -111,7 +108,6 @@ function isApplePlatform(): boolean {
export function Sidebar(props: SidebarProps) {
const { t } = useTranslation();
const remoteConnections = useRemoteConnections();
const [menuPortalContainer, setMenuPortalContainer] =
useState<HTMLElement | null>(null);
const collapsed = Boolean(props.collapsed);
@@ -257,16 +253,6 @@ export function Sidebar(props: SidebarProps) {
selectionRef={activeActionRef}
icon={<MessageCircle className="h-4 w-4" />}
/>
{remoteConnections?.available && props.onOpenRemoteConnections && (
<SidebarActionButton
collapsed={collapsed}
label={t("remote.title")}
onClick={props.onOpenRemoteConnections}
active={props.activeUtility === "remote"}
selectionRef={activeActionRef}
icon={<MonitorUp className="h-4 w-4" />}
/>
)}
{props.archivedCount ? (
<SidebarActionButton
collapsed={collapsed}
+86 -20
View File
@@ -1,5 +1,5 @@
import { createContext, useContext, useEffect, useRef, useState } from "react";
import { Check, ChevronUp, CircleAlert, Laptop, Loader2, Server, Settings2, X } from "lucide-react";
import { Check, ChevronUp, CircleAlert, Laptop, Loader2, Search, Server, Settings2, X } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { ConnectionBadge } from "@/components/ConnectionBadge";
@@ -16,6 +16,7 @@ export interface HostPicker {
localName: string;
currentId: string | null;
profiles: { id: string; name: string; host: string; ready: boolean }[];
recentIds: string[];
pending: { id: string; name: string } | null;
error: string;
offline: boolean;
@@ -32,30 +33,90 @@ interface EmbeddedPicker extends EmbeddedHost {
export const HostNavigationContext = createContext<HostPicker | EmbeddedPicker | null>(null);
function HostMenuContent({ picker, portalContainer }: { picker: HostPicker; portalContainer?: HTMLElement | null }) {
const { t } = useTranslation();
return <DropdownMenuContent side="top" align="end" sideOffset={8} collisionPadding={12}
portalContainer={portalContainer} className="w-64 max-w-[calc(100vw-1.5rem)]"
portalContainer={portalContainer} className="flex w-64 max-w-[calc(100vw-1.5rem)] flex-col overflow-hidden"
onEscapeKeyDown={(event) => { if (event.isComposing) event.preventDefault(); }}
onCloseAutoFocus={(event) => { event.preventDefault(); picker.restoreFocus(); }}>
<DropdownMenuLabel>{t("remote.switchHost")}</DropdownMenuLabel>
<DropdownMenuItem onSelect={() => picker.select(null)} className="gap-2.5">
<HostMenuItems picker={picker} />
</DropdownMenuContent>;
}
/** Mounted with the menu so every opening starts with a fresh, stable list. */
function HostMenuItems({ picker }: { picker: HostPicker }) {
const { t } = useTranslation();
const [searchable] = useState(() => picker.profiles.length > 5);
const [query, setQuery] = useState("");
const [order] = useState(() => [picker.currentId, ...picker.recentIds]);
const search = useRef<HTMLInputElement>(null);
const list = useRef<HTMLDivElement>(null);
const needle = query.trim().toLocaleLowerCase();
const matches = (...values: string[]) => values.some((value) => value.toLocaleLowerCase().includes(needle));
const showLocal = matches(t("remote.local"), picker.localName);
const profiles = picker.profiles.filter(({ name, host }) => matches(name, host));
if (searchable) {
const rank = (id: string) => { const index = order.indexOf(id); return index < 0 ? order.length : index; };
profiles.sort((a, b) => rank(a.id) - rank(b.id));
}
useEffect(() => {
// Don't summon the software keyboard when opening the picker on a touch device.
if (!searchable || window.matchMedia("(pointer: coarse)").matches) return;
const frame = requestAnimationFrame(() => search.current?.focus({ preventScroll: true }));
return () => cancelAnimationFrame(frame);
}, [searchable]);
return <div className="flex min-h-0 flex-col"
onPointerMoveCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }}
onPointerOutCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }}
onKeyDownCapture={(event) => {
if (!searchable) return;
if (event.nativeEvent.isComposing) { event.stopPropagation(); return; }
const items = Array.from(event.currentTarget.querySelectorAll<HTMLElement>('[role="menuitem"]'));
if (event.target === search.current) {
// Keep spaces and IME input out of Radix's menu typeahead.
if (event.key !== "Escape") event.stopPropagation();
if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Tab") {
event.preventDefault();
(event.key === "ArrowUp" || event.shiftKey ? items.at(-1) : items[0])?.focus();
} else if (event.key === "Enter") {
event.preventDefault();
if (needle) list.current?.querySelector<HTMLElement>('[role="menuitem"]')?.click();
}
} else if (event.key === "Tab" || (event.key === "ArrowUp" && event.target === items[0])) {
event.preventDefault(); event.stopPropagation(); search.current?.focus();
}
}}>
{searchable ? <div className="flex shrink-0 items-center gap-2 px-2.5 pb-2 pt-1.5">
<Search aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />
<input ref={search} aria-label={t("remote.searchHosts")} placeholder={t("remote.searchHosts")}
value={query} onChange={(event) => setQuery(event.target.value)} autoComplete="off" spellCheck={false}
className="h-7 min-w-0 flex-1 bg-transparent text-[13px] outline-none placeholder:text-muted-foreground" />
</div> : <DropdownMenuLabel className="shrink-0">{t("remote.switchHost")}</DropdownMenuLabel>}
<div ref={list} role="group" aria-label={t("remote.switchHost")}
className="min-h-0 overflow-y-auto overscroll-contain scrollbar-thin scrollbar-track-transparent">
{showLocal && <DropdownMenuItem onSelect={() => picker.select(null)} className="gap-2.5" aria-current={!picker.currentId || undefined}>
<Laptop className="h-4 w-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1"><span className="block">{t("remote.local")}</span><span className="block truncate text-xs text-muted-foreground">{picker.localName}</span></span>
{!picker.currentId && <Check className="h-4 w-4" />}
</DropdownMenuItem>
{!!picker.profiles.length && <DropdownMenuSeparator />}
{picker.profiles.map((profile) => <DropdownMenuItem key={profile.id} onSelect={() => picker.select(profile.id)} className="gap-2.5">
</DropdownMenuItem>}
{showLocal && !!profiles.length && <DropdownMenuSeparator />}
{profiles.map((profile) => <DropdownMenuItem key={profile.id} onSelect={() => picker.select(profile.id)} className="gap-2.5"
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 animate-spin" /> : picker.currentId === profile.id ? <Check className="h-4 w-4" />
: profile.ready ? <span className="text-[11px] text-muted-foreground">{t("remote.ready")}</span> : null}
{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}
</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>
<div className="shrink-0">
{picker.pending && <><DropdownMenuSeparator /><DropdownMenuItem onSelect={picker.cancel} className="gap-2.5"><X className="h-4 w-4" />{t("remote.cancelSwitch")}</DropdownMenuItem></>}
{picker.error && <div role="alert" className="px-2.5 py-2 text-xs leading-5 text-destructive">
{picker.error}<button className="ml-2 underline underline-offset-2" onClick={picker.clearError}>{t("common.close")}</button>
{picker.error && <div role="alert" className="flex items-start gap-2 px-2.5 py-2 text-xs leading-5 text-foreground">
<CircleAlert aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{picker.error}<button className="ml-2 underline underline-offset-2" onClick={picker.clearError}>{t("common.close")}</button></span>
</div>}
<DropdownMenuSeparator />
<DropdownMenuItem className="gap-2.5" onSelect={picker.manage}><Settings2 className="h-4 w-4 text-muted-foreground" />{t("remote.manageConnections")}</DropdownMenuItem>
</DropdownMenuContent>;
</div>
</div>;
}
/** Shared sidebar control. Remote frames can only open the trusted shell's menu. */
@@ -70,11 +131,15 @@ export function HostSwitcher({ collapsed = false, portalContainer }: { collapsed
const shell = picker.kind === "shell" ? picker : null;
const remote = picker.kind === "embedded" || !!shell?.currentId;
const pendingName = picker.kind === "shell" ? picker.pending?.name : picker.pendingName;
const failed = !!picker.error || !!shell?.offline || status === "error" || status === "closed";
// A failed switch describes the destination, not the still-active connection.
const failed = !!shell?.offline || status === "error" || status === "closed";
const waiting = !!pendingName || status === "connecting" || status === "reconnecting";
const label = pendingName ? t("remote.connecting") : picker.name;
const detail = pendingName ? t("remote.preparing", { name: pendingName }) : `${picker.name} · ${picker.hostname}`;
const title = picker.error || `${detail} — ${t(failed ? "remote.offline" : `connection.${status}`)}`;
// The old host stays interactive until the new one is ready. Keep its identity
// visible; progress belongs to the target's row and the accessible status.
const label = picker.name;
const current = `${picker.name} · ${picker.hostname} · ${t(failed ? "remote.offline" : `connection.${status}`)}`;
const detail = pendingName ? `${current} · ${t("remote.preparing", { name: pendingName })}` : current;
const title = picker.error ? `${detail} — ${picker.error}` : detail;
const button = <Button ref={buttonRef} variant="ghost" size="sm" aria-label={t("remote.switchHost")} title={title}
data-host-switcher className={cn("host-no-drag h-8 min-w-0 gap-2 rounded-xl px-2 text-xs font-normal text-sidebar-content/75 hover:bg-sidebar-accent/65 hover:text-sidebar-content",
collapsed ? "w-8 justify-center px-0" : "max-w-full flex-1 justify-start")}
@@ -83,15 +148,16 @@ export function HostSwitcher({ collapsed = false, portalContainer }: { collapsed
if (rect) picker.open({ left: rect.left, top: rect.top, width: rect.width, height: rect.height });
} : undefined}>
<span className="relative flex shrink-0 items-center justify-center">
{waiting ? <Loader2 className="h-4 w-4 animate-spin" /> : failed ? <CircleAlert className="h-4 w-4 text-destructive" />
{waiting ? <Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" /> : failed ? <CircleAlert className="h-4 w-4" />
: remote ? <Server className="h-4 w-4" /> : <Laptop className="h-4 w-4" />}
{!waiting && !failed && <span aria-hidden className={cn("absolute -bottom-0.5 -right-0.5 h-1.5 w-1.5 rounded-full ring-2 ring-sidebar", status === "open" ? "bg-emerald-500" : "bg-muted-foreground")} />}
</span>
{!collapsed && <><span className="truncate">{label}</span><ChevronUp className="ml-auto h-3 w-3 shrink-0 opacity-60" /></>}
<span className="sr-only" role="status">{detail} · {t(failed ? "remote.offline" : `connection.${status}`)}</span>
<span className="sr-only" role="status">{detail}</span>
</Button>;
if (!shell) return button;
return <DropdownMenu><DropdownMenuTrigger asChild>{button}</DropdownMenuTrigger><HostMenuContent picker={shell} portalContainer={portalContainer} /></DropdownMenu>;
// The mobile sidebar already owns the modal lock; a nested lock can outlive it on navigation.
return <DropdownMenu modal={!portalContainer}><DropdownMenuTrigger asChild>{button}</DropdownMenuTrigger><HostMenuContent picker={shell} portalContainer={portalContainer} /></DropdownMenu>;
}
/** Parent-owned menu anchored to the active remote sidebar, never inside its DOM. */
@@ -0,0 +1,58 @@
import { useEffect, useRef, useState } from "react";
import { AlertCircle, Check, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { useClient } from "@/providers/ClientProvider";
import { remoteAction } from "@/lib/remote-instances";
import { useRemoteConnections } from "./RemoteInstances";
/** An explicit escape hatch for a VPN/bound-interface route, not a new SSH form. */
export function PairRouteSettings({ id, onSaved }: { id: string; onSaved?: () => void }) {
const { t } = useTranslation();
const { client } = useClient();
const connections = useRemoteConnections();
const hasSavedRoute = !!connections?.directory?.profiles.find((profile) => profile.id === id)?.ssh_config;
const [route, setRoute] = useState(hasSavedRoute ? "saved" : "direct");
const [original, setOriginal] = useState(route);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [saved, setSaved] = useState(false);
const alive = useRef(true);
useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);
const save = async () => {
setBusy(true); setError(""); setSaved(false);
try {
await remoteAction(client, "pair_route", { id, route_id: route === "direct" ? "" : route });
if (!alive.current) return;
// Saving and refreshing are different outcomes. Never invite a second save
// merely because the directory refresh failed after the write succeeded.
setOriginal(route); setSaved(true);
try { await connections?.refresh(); }
catch {
if (alive.current) setError(t("remote.errors.directory_unavailable"));
return;
}
if (alive.current) onSaved?.();
} catch (reason) {
if (alive.current) setError(t(`remote.errors.${reason instanceof Error ? reason.message : "unknown"}`, { defaultValue: t("remote.errors.unknown") }));
} finally { if (alive.current) setBusy(false); }
};
return <div className="space-y-3">
<p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.routeHint")}</p>
<Select value={route} onValueChange={(value) => { setRoute(value); setError(""); setSaved(false); }} disabled={busy}><SelectTrigger aria-label={t("remote.pair.route")}><SelectValue /></SelectTrigger>
<SelectContent>
{hasSavedRoute && <SelectItem value="saved">{t("remote.pair.savedRoute")}</SelectItem>}
<SelectItem value="direct">{t("remote.pair.direct")}</SelectItem>
{connections?.directory?.profiles.filter((profile) => !profile.paired).map((profile) => <SelectItem key={profile.id} value={profile.id}>{profile.name}</SelectItem>)}
</SelectContent>
</Select>
{error && <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{error}</p>}
<div className="flex items-center justify-end gap-3">
{saved && <p role="status" className="mr-auto flex items-center gap-1.5 text-xs text-muted-foreground"><Check aria-hidden className="h-3.5 w-3.5" />{t("remote.saved")}</p>}
<Button size="sm" disabled={busy || route === original || route === "saved"} aria-busy={busy} onClick={() => { void save(); }}>
{busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" />}{t(busy ? "remote.saving" : "remote.save")}
</Button>
</div>
</div>;
}
@@ -0,0 +1,210 @@
import { useEffect, useId, useRef, useState } from "react";
import { AlertCircle, ArrowLeft, Check, ChevronDown, Copy, Loader2 } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import { DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { Disclosure, DisclosureContent } from "@/components/ui/disclosure";
import { Textarea } from "@/components/ui/textarea";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useClient } from "@/providers/ClientProvider";
import { copyTextToClipboard } from "@/lib/clipboard";
import { remoteAction } from "@/lib/remote-instances";
import { pairingReturnOrigin, type PairReturn } from "@/lib/remote-pair-return";
import { useRemoteConnections } from "./RemoteInstances";
import { PairRouteSettings } from "./PairRouteSettings";
type Request = { id: string; command: string; expires: number };
type Preview = { id: string; host: string; hostname: string; fingerprint: string; authorized_until: number; revoke_command: string };
/** Public invitation → encrypted receipt → explicit confirmation. No private key inputs. */
export function QuickPairSetup({ returned, onSSH, onClose }: { returned?: PairReturn | null; onSSH: () => void; onClose: () => void }) {
const { t } = useTranslation();
const { client } = useClient();
const connections = useRemoteConnections();
const [request, setRequest] = useState<Request | null>(returned ? { id: returned.id, command: "", expires: 0 } : null);
const [preview, setPreview] = useState<Preview | null>(null);
const [code, setCode] = useState(returned?.code || "");
const [saved, setSaved] = useState("");
const [busy, setBusy] = useState(false);
const [busyVisible, setBusyVisible] = useState(false);
const [error, setError] = useState("");
const [copied, setCopied] = useState(false);
const [expired, setExpired] = useState(false);
const [manual, setManual] = useState(false);
const [panel, setPanel] = useState<"command" | "help" | null>(null);
const alive = useRef(true);
const initialized = useRef(false);
const requestId = useRef(returned?.id || "");
const manualInput = useRef<HTMLTextAreaElement>(null);
const focusManual = useRef(false);
const codeId = useId();
const panelId = useId();
useEffect(() => {
if (!busy) { setBusyVisible(false); return; }
// Fast local preparation should not flash a loading label or move the dialog.
const timer = window.setTimeout(() => setBusyVisible(true), 200);
return () => window.clearTimeout(timer);
}, [busy]);
useEffect(() => {
alive.current = true;
return () => {
alive.current = false;
// A link opens in a new tab. Closing/reloading the originating page must
// not destroy its key before the new page can validate the receipt.
// Pending invitations are bounded and expire in PairStore.
};
}, [client]);
useEffect(() => {
if (!request?.expires || saved) return;
const timer = window.setTimeout(() => setExpired(true), Math.max(0, request.expires * 1000 - Date.now()));
return () => window.clearTimeout(timer);
}, [request, saved]);
const run = async (action: () => Promise<void>) => {
setBusy(true); setError("");
try { await action(); }
catch (reason) {
if (alive.current) setError(t(`remote.errors.${reason instanceof Error ? reason.message : "unknown"}`, { defaultValue: t("remote.errors.unknown") }));
} finally { if (alive.current) setBusy(false); }
};
const start = () => run(async () => {
if (requestId.current) await remoteAction(client, "pair_cancel", { id: requestId.current });
const result = await remoteAction<Request>(client, "pair_start", { return_origin: pairingReturnOrigin() });
if (!alive.current) { await remoteAction(client, "pair_cancel", { id: result.id }); return; }
requestId.current = result.id;
setRequest(result); setPreview(null); setCode(""); setCopied(false); setExpired(false); setManual(false); setPanel(null);
});
const review = () => run(async () => {
if (!request) return;
const result = await remoteAction<Preview>(client, "pair_preview", { id: request.id, code });
if (alive.current) setPreview(result);
});
const connect = () => run(async () => {
if (!request || !preview || !connections) return;
let id = saved;
if (!id) {
const result = await remoteAction<{ id: string }>(client, "pair_finish", { id: request.id, code });
id = result.id;
if (!alive.current) return;
setSaved(id);
}
await connections.refresh();
if (!alive.current) return;
await connections.connect(id, () => alive.current);
if (alive.current) onClose();
});
useEffect(() => {
if (initialized.current) return;
initialized.current = true;
if (returned) void review();
else void start();
// One invitation per mounted dialog, never one per re-render. The returned
// receipt is reviewed only; saving/connecting still requires a user click.
}, []);
const copyCommand = () => {
if (!request) return;
void copyTextToClipboard(request.command).then((ok) => {
if (!alive.current || requestId.current !== request.id || Date.now() >= request.expires * 1000) return;
if (ok) { setCopied(true); setError(""); setPanel(null); }
else { setPanel("command"); setError(t("remote.pair.copyFailed")); }
});
};
const restartAvailable = !saved && (expired || (!!error && !request?.command && !preview));
const reviewingReturn = !!returned && !request?.command && !preview && !manual && !restartAvailable;
const title = preview ? "remote.pair.confirmTitle" : reviewingReturn ? "remote.pair.review" : restartAvailable ? "remote.add"
: manual ? "remote.pair.code" : copied ? "remote.pair.copiedTitle" : "remote.add";
const description = preview || reviewingReturn ? "remote.pair.confirmLinkDescription" : restartAvailable ? "remote.pair.introHint"
: manual ? "remote.pair.codeHint" : copied ? "remote.pair.afterCopyHint" : "remote.pair.introHint";
const showCopied = copied && !manual && !preview && !restartAvailable;
const showBusy = busy && busyVisible;
const actionLabel = restartAvailable ? "remote.pair.restart" : reviewingReturn ? "remote.pair.review" : preview ? saved ? "remote.retry" : "remote.connect"
: manual ? "remote.pair.review" : copied ? "remote.pair.copyAgain" : "remote.pair.copy";
const busyLabel = preview ? "remote.connecting" : !restartAvailable && (manual || returned)
? "remote.pair.checkingLink" : "remote.pair.preparing";
return <>
<DialogHeader className="shrink-0 pr-5 text-left">
<div aria-live="polite" aria-atomic="true" className="space-y-1.5">
<DialogTitle className="flex min-h-5 items-center gap-2">
{showCopied && <Check aria-hidden="true" className="h-5 w-5 shrink-0 motion-safe:animate-in motion-safe:fade-in duration-150" />}
{t(title)}
</DialogTitle>
<div className="grid">
<DialogDescription className="col-start-1 row-start-1">{t(description)}</DialogDescription>
{/* Reserve the longer instruction in either state, including translated text.
It is only a layout spacer, never a second screen-reader announcement. */}
{!preview && !manual && !reviewingReturn && <p aria-hidden="true" className="invisible pointer-events-none col-start-1 row-start-1 select-none text-sm">
{t(showCopied ? "remote.pair.introHint" : "remote.pair.afterCopyHint")}
</p>}
</div>
</div>
</DialogHeader>
<div className="-mx-1 min-h-0 space-y-4 overflow-y-auto overscroll-contain px-1">
{preview ? <div className="space-y-4">
<div className="rounded-2xl bg-muted/50 p-4">
<p className="font-medium">{preview.hostname}</p>
<p className="mt-1 break-all text-xs text-muted-foreground">{preview.host}</p>
</div>
<p className="text-[13px] leading-5">{t("remote.pair.access")}</p>
<p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.expiry", { date: new Date(preview.authorized_until * 1000).toLocaleDateString() })}</p>
<Disclosure className="text-xs text-muted-foreground" summaryClassName="flex min-h-9 items-center gap-2 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
summary={<><ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />{t("remote.pair.security")}</>}>
<p className="my-2 leading-5">{t("remote.pair.fingerprint")}</p><code className="block break-all">{preview.fingerprint}</code>
<p className="mb-2 mt-4 leading-5">{t("remote.pair.revoke")}</p><code className="block break-all">{preview.revoke_command}</code>
</Disclosure>
{saved && error && <div className="space-y-2"><p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.retryHint")}</p>
<Disclosure summaryClassName="flex min-h-9 items-center gap-2 rounded-xl text-xs text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" contentClassName="pt-2"
summary={<><ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />{t("remote.pair.route")}</>}><PairRouteSettings id={saved} /></Disclosure>
</div>}
</div> : restartAvailable ? null : <>
{manual && <div className="space-y-2"><label htmlFor={codeId} className="sr-only">{t("remote.pair.code")}</label>
<Textarea ref={manualInput} id={codeId} value={code} onChange={(event) => { setCode(event.target.value); setError(""); }} placeholder="nbpc1.…" autoComplete="off" spellCheck={false} disabled={busy || expired} className="min-h-20 resize-none break-all font-mono text-xs" />
</div>}
<div>
<DisclosureContent id={panelId} open={panel === "command" && !!request?.command}>
<div className="rounded-2xl bg-muted/50 p-3">
<code className="block max-h-32 select-text overflow-y-auto break-all text-[11px] leading-5" aria-label={t("remote.pair.command")}>{request?.command}</code>
</div>
</DisclosureContent>
<DisclosureContent open={panel === "help"}>
<div className="space-y-2 rounded-2xl bg-muted/50 p-3 text-xs leading-5 text-muted-foreground">
<p className="font-medium text-foreground">{t("remote.pair.helpTitle")}</p>
<p>{t("remote.pair.requirements")}</p>
<p>{t("remote.pair.runHint")}</p>
<p>{t("remote.pair.validityHint")}</p>
</div>
</DisclosureContent>
</div>
</>}
{expired && !saved && <p role="status" className="text-xs leading-5 text-muted-foreground">{t("remote.pair.expired")}</p>}
{error && <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{error}</p>}
</div>
<div className={preview ? "flex shrink-0 flex-col-reverse gap-2 pt-1 sm:flex-row sm:items-center sm:justify-between" : "flex shrink-0 flex-col gap-2 pt-1"}>
{preview && (!saved ? <Button variant="ghost" disabled={busy} onClick={() => { setPreview(null); setError(""); if (!request?.command) setManual(true); }}><ArrowLeft className="mr-1 h-4 w-4" />{t("remote.back")}</Button>
: <Button variant="ghost" onClick={() => { connections?.cancel(); onClose(); }}>{t("common.cancel")}</Button>
)}
<Button variant={showCopied ? "outline" : "default"} className={showCopied ? "bg-transparent" : undefined} aria-label={t(showBusy ? busyLabel : actionLabel)} aria-busy={busy} disabled={busy || (!restartAvailable && (!request || (!preview && (manual ? !code.trim() : !request.command))))} onClick={() => { if (restartAvailable) void start(); else if (preview) void connect(); else if (manual) void review(); else copyCommand(); }}>
{showBusy ? <Loader2 aria-hidden="true" className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" /> : !restartAvailable && !preview && !manual && !reviewingReturn ? <Copy aria-hidden="true" className="mr-2 h-4 w-4 shrink-0" /> : null}
<span role="status" className="min-w-0 truncate">{t(showBusy ? busyLabel : actionLabel)}</span>
</Button>
{!preview && <div className="-mx-3 flex items-center justify-between gap-1">
{request?.command ? manual ? <Button variant="ghost" size="sm" disabled={busy} onClick={() => { setManual(false); setPanel(null); setError(""); }}>{t("remote.back")}</Button>
: <Button variant="ghost" size="sm" className="text-xs text-muted-foreground" disabled={expired} aria-expanded={panel === "command"} aria-controls={panelId} onClick={() => setPanel(panel === "command" ? null : "command")}>{t("remote.pair.showCommand")}</Button> : <span />}
<DropdownMenu>
<DropdownMenuTrigger asChild><Button variant="ghost" size="sm" className="text-xs text-muted-foreground">{t("remote.pair.otherWays")}<ChevronDown aria-hidden="true" className="ml-1 h-3.5 w-3.5" /></Button></DropdownMenuTrigger>
<DropdownMenuContent align="end" onCloseAutoFocus={(event) => {
if (focusManual.current) { event.preventDefault(); focusManual.current = false; manualInput.current?.focus(); }
}}>
<DropdownMenuItem disabled={!request || busy || expired || restartAvailable} onSelect={() => { focusManual.current = true; setManual(true); setPanel(null); setError(""); }}>{t("remote.pair.pasteInstead")}</DropdownMenuItem>
<DropdownMenuItem onSelect={onSSH}>{t("remote.pair.useSSH")}</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuItem disabled={restartAvailable} onSelect={() => setPanel(panel === "help" ? null : "help")}>{t("remote.pair.helpTitle")}</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>}
</div>
</>;
}
@@ -1,25 +1,28 @@
import { useEffect, useId, useRef, useState } from "react";
import { ArrowLeft, ArrowUpRight, Check, ChevronLeft, Laptop, Loader2, MoreHorizontal, Plus, Server, ShieldCheck } from "lucide-react";
import { useEffect, useId, useRef, useState, useSyncExternalStore, type ReactNode } from "react";
import { AlertCircle, ArrowUpRight, Check, ChevronDown, ChevronLeft, FolderOpen, Laptop, Loader2, MoreHorizontal, Plus, Server } from "lucide-react";
import { useTranslation } from "react-i18next";
import { SettingsGroup, SettingsRow, SettingsSectionTitle } from "@/components/settings/shared/SettingsControls";
import { SettingsAdvancedOptions } from "@/components/settings/shared/SettingsFeature";
import { SettingsGroup } from "@/components/settings/shared/SettingsControls";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { DisclosureContent } from "@/components/ui/disclosure";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { useClient } from "@/providers/ClientProvider";
import { remoteAction, type RemoteProfile } from "@/lib/remote-instances";
import { remoteAction, type RemoteInspection, type RemoteProfile } from "@/lib/remote-instances";
import { cn } from "@/lib/utils";
import { parseSSHAddress } from "@/lib/ssh-address";
import { clearPairReturn, readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";
import { useRemoteConnections } from "./RemoteInstances";
import { SSHHostPicker } from "./SSHHostPicker";
import { QuickPairSetup } from "./QuickPairSetup";
import { PairRouteSettings } from "./PairRouteSettings";
const emptyProfile = (): Omit<RemoteProfile, "id" | "connected"> => ({
name: "", host: "", port: null, ssh_config: "", identity_file: "",
config_path: "~/.nanobot/config.json", runtime_user: "",
});
/** A shell destination, not a dialog. Only verification and removal need confirmation. */
/** The page is a server directory. Add/edit/first-use verification share one dialog. */
export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChromeInset = false, onBackToChat }: {
mainNavigationExpanded?: boolean;
hostChromeInset?: boolean;
@@ -30,74 +33,182 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
const connections = useRemoteConnections();
const [form, setForm] = useState(emptyProfile);
const [editorOpen, setEditorOpen] = useState(false);
const [editingId, setEditingId] = useState("");
const returnedPair = useSyncExternalStore(subscribePairReturn, readPairReturn);
const [quickOpen, setQuickOpen] = useState(!!returnedPair);
const [pairRoute, setPairRoute] = useState("");
const [editing, setEditing] = useState(false);
const [savedId, setSavedId] = useState("");
const [busy, setBusy] = useState("");
const [error, setError] = useState("");
const [errorCode, setErrorCode] = useState("");
const [sshOptions, setSSHOptions] = useState(false);
const [manualLocation, setManualLocation] = useState(false);
const [inspection, setInspection] = useState<RemoteInspection | null>(null);
const [inspectBeforeConnect, setInspectBeforeConnect] = useState(true);
const [commandImported, setCommandImported] = useState(false);
const [removing, setRemoving] = useState<RemoteProfile | null>(null);
const [disconnecting, setDisconnecting] = useState<RemoteProfile | null>(null);
const [fingerprint, setFingerprint] = useState<{ id: string; fingerprint: string; challenge: string } | null>(null);
const lastRemoval = useRef<RemoteProfile | null>(null);
const lastDisconnect = useRef<RemoteProfile | null>(null);
const [fingerprint, setFingerprint] = useState<{ id: string; fingerprint: string; challenge: string; inspect: boolean } | null>(null);
const hostInput = useRef<HTMLInputElement>(null);
const editorTrigger = useRef<HTMLButtonElement | null>(null);
const mounted = useRef(true);
const operation = useRef(0);
const optionsId = useId();
const refresh = connections?.refresh;
// Keep confirmation content intact during Radix's exit animation.
useEffect(() => { if (removing) lastRemoval.current = removing; }, [removing]);
useEffect(() => { if (disconnecting) lastDisconnect.current = disconnecting; }, [disconnecting]);
useEffect(() => { if (returnedPair) setQuickOpen(true); }, [returnedPair]);
useEffect(() => {
mounted.current = true;
// Keep cached rows visible while refreshing in the background.
void refresh?.().catch(() => {});
return () => { mounted.current = false; };
return () => { mounted.current = false; operation.current += 1; };
}, [refresh]);
if (!connections) return null;
const { directory, directoryError, connect: connectHost, disconnect: disconnectHost } = connections;
const showForm = editorOpen;
const pageError = error || (directoryError ? t("remote.errors.directory_unavailable") : "");
const wanted = (attempt: number) => mounted.current && attempt === operation.current;
const showError = (reason: unknown) => {
if (!mounted.current) return;
const code = reason instanceof Error ? reason.message : "unknown";
if (/^(ssh_|host_key_|local_file_not_found)/.test(code)) {
setInspection(null); setManualLocation(false); setInspectBeforeConnect(true);
}
setErrorCode(code);
setError(t(`remote.errors.${code}`, { defaultValue: t("remote.errors.unknown") }));
};
const closeEditor = () => {
operation.current += 1;
if (busy) connections.cancel();
setBusy(""); setEditorOpen(false); setFingerprint(null); setError(""); setErrorCode("");
};
const beginEditor = (profile?: RemoteProfile) => {
operation.current += 1;
setEditing(!!profile); setSavedId(profile?.id || "");
setSSHOptions(false); setManualLocation(false); setInspection(null);
setInspectBeforeConnect(!profile); setErrorCode("");
setForm(profile ? { name: profile.name, host: profile.host, port: profile.port,
ssh_config: profile.ssh_config, identity_file: profile.identity_file,
config_path: profile.config_path, runtime_user: profile.runtime_user } : emptyProfile());
setError(""); setCommandImported(false); setEditorOpen(true); setFingerprint(null);
};
const connect = async (id: string) => {
setBusy(id); setError("");
const importCommand = () => {
if (!/^ssh\s/.test(form.host.trim())) return;
try {
await connectHost(id, () => mounted.current);
setForm({ ...form, ...parseSSHAddress(form.host) });
setCommandImported(true); setError("");
} catch (reason) { showError(reason); }
};
const pickFile = async (field: "ssh_config" | "identity_file") => {
const attempt = ++operation.current;
setBusy(`pick-${field}`); setError(""); setErrorCode("");
try {
const result = await remoteAction<{ path: string | null }>(client, "pick_file", {});
if (wanted(attempt) && typeof result.path === "string" && result.path) {
setForm((previous) => ({ ...previous, [field]: result.path }));
}
} catch (reason) { if (wanted(attempt)) showError(reason); }
finally { if (wanted(attempt)) setBusy(""); }
};
const filePicker = (field: "ssh_config" | "identity_file") => <Button type="button" variant="ghost" size="icon" className="shrink-0"
disabled={!!busy} title={t("remote.setup.chooseFile", { field: t(`remote.${field}`) })}
aria-label={t("remote.setup.chooseFile", { field: t(`remote.${field}`) })} onClick={() => { void pickFile(field); }}>
{busy === `pick-${field}` ? <Loader2 className="h-4 w-4 animate-spin" /> : <FolderOpen className="h-4 w-4" />}
</Button>;
const connect = async (id: string, attempt = ++operation.current, inspect = false) => {
setBusy(inspect ? "inspect" : id); setError(""); setErrorCode("");
try {
if (inspect) {
const result = await remoteAction<RemoteInspection>(client, "inspect", { id });
if (!wanted(attempt)) return;
if (!result || !Array.isArray(result.candidates) || typeof result.hostname !== "string") throw new Error("probe_failed");
setInspection(result);
setInspectBeforeConnect(false);
const single = result.candidates.length === 1 ? result.candidates[0] : null;
if (single) setForm((previous) => ({ ...previous, config_path: single.config_path, runtime_user: single.runtime_user }));
else if (result.candidates.length) setForm((previous) => ({ ...previous, config_path: "", runtime_user: "" }));
// Only the unambiguous login-user default is automatic. Service accounts
// always require an explicit choice before attempting existing sudo access.
if (!single || single.runtime_user) {
setManualLocation(!result.candidates.length);
return;
}
// Keep the submitted profile (including a newly imported SSH command).
const address = parseSSHAddress(form.host);
const profile = { ...form, ...address,
name: form.name.trim() || address.host,
config_path: single.config_path, runtime_user: single.runtime_user };
if (profile.config_path !== form.config_path || profile.runtime_user !== form.runtime_user) {
await remoteAction(client, "save", { id, profile });
}
if (!wanted(attempt)) return;
await refresh?.();
if (!wanted(attempt)) return;
setBusy(id);
}
await connectHost(id, () => wanted(attempt));
if (wanted(attempt)) { setEditorOpen(false); setFingerprint(null); }
} catch (reason) {
if (!mounted.current) return;
if (!wanted(attempt)) return;
if (reason instanceof Error && reason.message === "host_key_unknown") {
try {
const result = await remoteAction<{ fingerprint: string; challenge: string }>(client, "fingerprint", { id });
if (mounted.current) setFingerprint({ id, ...result });
} catch (scanError) { showError(scanError); }
} else { showError(reason); }
} finally {
if (mounted.current) setBusy("");
}
if (wanted(attempt)) setFingerprint({ id, ...result, inspect });
} catch (scanError) { if (wanted(attempt)) showError(scanError); }
} else {
if (!editorOpen) {
const profile = directory?.profiles.find((item) => item.id === id);
if (profile && !profile.paired) {
setForm({ name: profile.name, host: profile.host, port: profile.port,
ssh_config: profile.ssh_config, identity_file: profile.identity_file,
config_path: profile.config_path, runtime_user: profile.runtime_user });
setSavedId(id); setEditing(false); setEditorOpen(true); setInspectBeforeConnect(true);
setInspection(null); setManualLocation(false); setSSHOptions(false);
}
}
showError(reason);
}
} finally { if (wanted(attempt)) setBusy(""); }
};
const trustHost = async () => {
if (!fingerprint) return;
const attempt = ++operation.current;
const id = fingerprint.id;
setBusy("trust"); setError("");
try {
await remoteAction(client, "trust", { id: fingerprint.id, challenge: fingerprint.challenge });
if (!mounted.current) return;
const id = fingerprint.id;
setFingerprint(null);
await connect(id);
} catch (reason) { showError(reason); }
finally { if (mounted.current) setBusy(""); }
await remoteAction(client, "trust", { id, challenge: fingerprint.challenge });
if (wanted(attempt)) { setFingerprint(null); await connect(id, attempt, fingerprint.inspect); }
} catch (reason) { if (wanted(attempt)) showError(reason); }
finally { if (wanted(attempt)) setBusy(""); }
};
const save = async () => {
setEditorOpen(true); setBusy("save"); setError("");
const attempt = ++operation.current;
setBusy("save"); setError(""); setErrorCode("");
try {
// Also parse here for Enter submission, which doesn't blur the address.
const address = parseSSHAddress(form.host);
const normalized = { ...form, ...address, name: form.name.trim() || address.host };
setForm({ ...form, ...address });
const result = await remoteAction<{ id: string }>(client, "save", {
id: editingId, profile: { ...form, name: form.name.trim() || form.host.trim() },
id: savedId, profile: normalized,
});
if (!mounted.current) return;
setEditingId(result.id);
// Retain the saved id on failures so retry never creates duplicate profiles.
if (wanted(attempt)) setSavedId(result.id);
await refresh?.();
if (mounted.current) await connect(result.id);
} catch (reason) { showError(reason); }
finally { if (mounted.current) setBusy(""); }
if (!wanted(attempt)) return;
if (editing) setEditorOpen(false);
else await connect(result.id, attempt, inspectBeforeConnect && !manualLocation);
} catch (reason) { if (wanted(attempt)) showError(reason); }
finally { if (wanted(attempt)) setBusy(""); }
};
const remove = async () => {
@@ -107,20 +218,30 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
await disconnectHost(removing.id);
await remoteAction(client, "remove", { id: removing.id });
if (mounted.current) setRemoving(null);
await refresh?.();
} catch (reason) { showError(reason); }
await refresh?.().catch(() => {});
} catch (reason) { if (mounted.current) showError(reason); }
finally { if (mounted.current) setBusy(""); }
};
const disconnect = async (id: string) => {
setBusy(id); setError("");
try { await disconnectHost(id); if (mounted.current) setDisconnecting(null); }
catch (reason) { showError(reason); }
catch (reason) { if (mounted.current) showError(reason); }
finally { if (mounted.current) setBusy(""); }
};
const closeEditor = () => {
setEditorOpen(false); setEditingId(""); setForm(emptyProfile()); setError("");
const pageError = error || (directoryError ? t("remote.errors.directory_unavailable") : "");
const nanobotError = /^(config_|runtime_user_|webui_|remote_auth_|remote_unreachable|incompatible_gateway|public_ws_|python_|probe_failed)/.test(errorCode);
const locationStep = !!inspection || manualLocation || nanobotError;
const openingProfile = !editorOpen && !fingerprint && !removing && !disconnecting
? directory?.profiles.find((profile) => profile.id === busy) : null;
const editorAction = editing ? "remote.save" : locationStep ? "remote.setup.openNanobot" : "remote.connect";
const editorLabel = !busy || busy.startsWith("pick-") ? editorAction : busy === "save" ? "remote.saving"
: busy === "inspect" ? "remote.setup.checking" : "remote.setup.opening";
const editingProfile = editing ? directory?.profiles.find((profile) => profile.id === savedId) : null;
const removalProfile = removing || lastRemoval.current;
const disconnectProfile = disconnecting || lastDisconnect.current;
const editSSH = () => {
setInspection(null); setManualLocation(false); setInspectBeforeConnect(true);
setError(""); setErrorCode(""); setSSHOptions(true);
};
return <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-settings-canvas">
@@ -135,7 +256,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
<h1 className="text-[24px] font-normal leading-tight tracking-normal text-foreground sm:text-[28px]">{t("remote.title")}</h1>
</div>
<div className="settings-stack">
<p className="settings-list-inset text-[13px] leading-6 text-muted-foreground">{t(showForm ? "remote.addDescription" : "remote.description")}</p>
<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">
@@ -145,101 +266,186 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
<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>
</SettingsGroup>
{showForm ? <form onSubmit={(event) => { event.preventDefault(); void save(); }} className="settings-stack">
<div className="settings-section-heading">
<SettingsSectionTitle>{t(editingId ? "remote.edit" : "remote.addTitle")}</SettingsSectionTitle>
<Button type="button" variant="ghost" size="sm" className="gap-1.5" disabled={!!busy} onClick={closeEditor}>
<ArrowLeft className="h-3.5 w-3.5" />{t("remote.back")}
</Button>
</div>
<SettingsGroup>
<RemoteField label={t("remote.host")} value={form.host} placeholder="ubuntu@192.0.2.10" required disabled={!!busy}
onChange={(host) => setForm({ ...form, host })} />
<RemoteField label={t("remote.name")} value={form.name} placeholder={t("remote.namePlaceholder")} disabled={!!busy}
onChange={(name) => setForm({ ...form, name })} />
</SettingsGroup>
<SettingsAdvancedOptions>
<SettingsGroup>
<RemoteField label={t("remote.sshPort")} value={form.port == null ? "" : String(form.port)} placeholder={t("remote.portPlaceholder")} type="number" min={1} max={65535} disabled={!!busy}
onChange={(port) => setForm({ ...form, port: port === "" ? null : Number(port) })} />
{(["ssh_config", "identity_file", "config_path", "runtime_user"] as const).map((key) =>
<RemoteField key={key} label={t(`remote.${key}`)} value={form[key]} disabled={!!busy}
onChange={(value) => setForm({ ...form, [key]: value })} />)}
</SettingsGroup>
</SettingsAdvancedOptions>
<div className="settings-list-inset flex flex-wrap items-start justify-between gap-4">
<p className="flex max-w-sm flex-1 items-start gap-2 text-xs leading-5 text-muted-foreground"><ShieldCheck className="mt-0.5 h-3.5 w-3.5 shrink-0" />{t("remote.keyHint")}</p>
<Button type="submit" disabled={!!busy || !form.host.trim()}>{busy && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}{t(busy ? "remote.connecting" : "remote.saveConnect")}</Button>
</div>
</form> : null}
<div hidden={showForm} className={cn("settings-stack", showForm && "hidden")}>
{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={() => { 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>
<ArrowUpRight className="h-4 w-4 text-muted-foreground" />
</button>
<DropdownMenu><DropdownMenuTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8 shrink-0" disabled={!!busy} aria-label={t("remote.manage", { name: profile.name })}><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
<DropdownMenuContent align="end">
{(profile.connected || connections.openHostIds.includes(profile.id)) && <DropdownMenuItem onSelect={() => setDisconnecting(profile)}>{t("remote.disconnect")}</DropdownMenuItem>}
<DropdownMenuItem disabled={profile.connected || connections.openHostIds.includes(profile.id)} onSelect={() => {
const { name, host, port, ssh_config, identity_file, config_path, runtime_user } = profile;
setEditingId(profile.id); setForm({ name, host, port, ssh_config, identity_file, config_path, runtime_user }); setEditorOpen(true); setError("");
}}>{t("remote.edit")}</DropdownMenuItem>
<DropdownMenuItem onSelect={() => setRemoving(profile)}>{t("remote.forget")}</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>)}
</SettingsGroup>}
<SSHHostPicker disabled={!!busy} onSelect={({ host, ssh_config }) => {
setEditingId(""); setForm({ ...emptyProfile(), name: host, host, ssh_config }); setEditorOpen(true); setError("");
}} />
<div className="settings-list-inset"><Button variant="ghost" className="gap-2" disabled={!!busy} onClick={() => { setEditingId(""); setForm(emptyProfile()); setEditorOpen(true); setError(""); }}>
<Plus className="h-4 w-4" />{t("remote.add")}
</Button></div>
</div>
{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) => {
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>
{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", {
date: new Date(profile.authorized_until * 1000).toLocaleDateString(),
})}
</span>}
</span>
<ArrowUpRight className="h-4 w-4 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; }}
onKeyDown={(event) => { editorTrigger.current = event.currentTarget; }}
aria-label={t("remote.manage", { name: profile.name })}><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
<DropdownMenuContent align="end">
{!profile.paired && <DropdownMenuItem disabled={profile.connected || connections.openHostIds.includes(profile.id)} onSelect={() => beginEditor(profile)}>{t("remote.edit")}</DropdownMenuItem>}
{profile.paired && <DropdownMenuItem disabled={profile.connected || connections.openHostIds.includes(profile.id)} onSelect={() => setPairRoute(profile.id)}>{t("remote.pair.route")}</DropdownMenuItem>}
{(profile.connected || connections.openHostIds.includes(profile.id)) && <DropdownMenuItem onSelect={() => { setError(""); setDisconnecting(profile); }}>{t("remote.disconnect")}</DropdownMenuItem>}
<DropdownMenuItem tone="destructive" onSelect={() => { setError(""); setRemoving(profile); }}>{t("remote.forget")}</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>)}
</SettingsGroup>}
{openingProfile && <div className="settings-list-inset flex items-center justify-between gap-3">
<p role="status" className="min-w-0 truncate text-xs text-muted-foreground">{t("remote.preparing", { name: openingProfile.name })}</p>
<Button variant="ghost" size="sm" className="shrink-0" onClick={closeEditor}>{t("remote.cancelSwitch")}</Button>
</div>}
<div className="settings-list-inset"><Button variant="ghost" className="gap-2" disabled={!!busy} onClick={(event) => {
editorTrigger.current = event.currentTarget; setQuickOpen(true);
}}><Plus className="h-4 w-4" />{t("remote.add")}</Button></div>
</>}
{!directory && !directoryError && <div role="status" className="settings-list-inset flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" />{t("remote.loading")}</div>}
{directory && !directory.available && <p className="settings-list-inset text-sm text-muted-foreground">{t("remote.unavailable")}</p>}
{pageError && !fingerprint && <div className="settings-list-inset space-y-2">
<p role="alert" className="text-[13px] leading-5 text-destructive">{pageError}</p>
{pageError && !editorOpen && !fingerprint && !removing && !disconnecting && <div className="settings-list-inset space-y-2">
<p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{pageError}</p>
{directoryError && <Button variant="ghost" size="sm" disabled={!!busy} onClick={() => {
setBusy("refresh"); setError(""); void refresh?.().catch(showError).finally(() => { if (mounted.current) setBusy(""); });
setBusy("refresh"); setError(""); void refresh?.().catch((reason: unknown) => { if (mounted.current) showError(reason); }).finally(() => { if (mounted.current) setBusy(""); });
}}>{t("remote.retry")}</Button>}
</div>}
</div>
</div>
</div>
<Dialog open={quickOpen} onOpenChange={(open) => { setQuickOpen(open); if (!open) clearPairReturn(); }}>
<DialogContent className="flex max-h-[85dvh] max-w-md flex-col overflow-hidden">
{quickOpen && <QuickPairSetup key={returnedPair?.code || "new"} returned={returnedPair} onSSH={() => { clearPairReturn(); setQuickOpen(false); beginEditor(); }} onClose={() => { clearPairReturn(); setQuickOpen(false); }} />}
</DialogContent>
</Dialog>
<Dialog open={!!pairRoute} onOpenChange={(open) => { if (!open) setPairRoute(""); }}>
<DialogContent className="max-w-md"><DialogHeader><DialogTitle>{t("remote.pair.route")}</DialogTitle><DialogDescription>{t("remote.pair.routeDescription")}</DialogDescription></DialogHeader>
{pairRoute && <PairRouteSettings id={pairRoute} onSaved={() => setPairRoute("")} />}
</DialogContent>
</Dialog>
<Dialog open={editorOpen || !!fingerprint} onOpenChange={(open) => { if (!open) closeEditor(); }}>
<DialogContent className="flex max-h-[85dvh] max-w-md flex-col overflow-hidden" onOpenAutoFocus={(event) => {
if (!fingerprint) { event.preventDefault(); hostInput.current?.focus(); }
}} onCloseAutoFocus={(event) => {
event.preventDefault();
if (!editorTrigger.current?.closest("[inert]")) editorTrigger.current?.focus({ preventScroll: true });
}}>
<DialogHeader className="shrink-0 pr-5 text-left">
<DialogTitle>{t(fingerprint ? "remote.verifyTitle" : editing ? "remote.edit" : "remote.addTitle")}</DialogTitle>
<DialogDescription>{t(fingerprint ? "remote.verifyDescription" : editing ? "remote.editDescription" : "remote.addDescription")}</DialogDescription>
</DialogHeader>
{fingerprint ? <>
<div className="space-y-2 rounded-2xl bg-muted/40 p-3">
<p className="break-all text-[13px] font-medium">{directory?.profiles.find((profile) => profile.id === fingerprint.id)?.host || form.host}</p>
<code className="block select-text break-all text-xs text-muted-foreground">{fingerprint.fingerprint}</code>
</div>
<p className="text-xs leading-5 text-muted-foreground">{t("remote.verifyHint")}</p>
{error && <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{error}</p>}
<div className="grid grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:items-center sm:justify-end">
{editorOpen && <Button variant="ghost" disabled={!!busy} className="mr-auto gap-1" onClick={() => { setFingerprint(null); setError(""); setErrorCode(""); setInspection(null); setInspectBeforeConnect(true); }}><ChevronLeft className="h-4 w-4" />{t("remote.back")}</Button>}
<Button variant="ghost" onClick={closeEditor}>{t("common.cancel")}</Button>
<Button className="col-span-2 h-auto min-h-10 whitespace-normal" disabled={!!busy} aria-busy={!!busy} onClick={() => { void trustHost(); }}>{busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" />}{t("remote.verifyConnect")}</Button>
</div>
</> : <form onSubmit={(event) => { event.preventDefault(); if (!busy && form.host.trim() && (!locationStep || form.config_path.trim())) void save(); }} className="flex min-h-0 flex-col gap-4">
<div className="-mx-1 min-h-0 space-y-4 overflow-y-auto overscroll-contain px-1">
{!editing && <ol aria-label={t("remote.setup.progress")} className="flex items-center gap-3 text-xs text-muted-foreground">
<li aria-current={!locationStep ? "step" : undefined} className={cn("flex items-center gap-1.5", !locationStep && "text-foreground")}>
{locationStep ? <Check className="h-3.5 w-3.5" /> : <span>1</span>}{t("remote.setup.server")}</li>
<li aria-hidden="true" className="h-px w-5 bg-border" />
<li aria-current={locationStep ? "step" : undefined} className={cn("flex items-center gap-1.5", locationStep && "text-foreground")}><span>2</span>{t("remote.setup.nanobot")}</li>
</ol>}
{locationStep && !editing ? <div className="space-y-4">
<div className="flex items-center justify-between gap-3 rounded-2xl bg-muted/40 px-3 py-2.5">
<span className="min-w-0 text-[13px]"><span className="block font-medium">{t("remote.setup.signedIn")}</span><span className="block truncate text-xs text-muted-foreground">{form.host}</span></span>
<Button type="button" size="sm" variant="ghost" disabled={!!busy} onClick={editSSH}>{t("remote.setup.changeServer")}</Button>
</div>
{!!inspection?.candidates.length && <fieldset className="space-y-2">
<legend className="mb-2 text-[13px] font-medium">{t("remote.setup.chooseNanobot")}</legend>
{inspection.candidates.map((candidate) => <label key={candidate.config_path + candidate.runtime_user} className={cn("flex cursor-pointer items-start gap-3 rounded-2xl border p-3 transition-colors", !manualLocation && form.config_path === candidate.config_path && form.runtime_user === candidate.runtime_user ? "border-foreground/30 bg-muted/40" : "border-border hover:bg-muted/30")}>
<input type="radio" name="nanobot-location" className="mt-1 accent-foreground" disabled={!!busy}
checked={!manualLocation && form.config_path === candidate.config_path && form.runtime_user === candidate.runtime_user}
onChange={() => { setManualLocation(false); setForm({ ...form, config_path: candidate.config_path, runtime_user: candidate.runtime_user }); setError(""); setErrorCode(""); }} />
<span className="min-w-0 text-[13px]"><span className="block font-medium">{candidate.service || t("remote.setup.yourNanobot")}</span>
<span className="block break-all text-xs leading-5 text-muted-foreground">{candidate.config_path}</span>
{candidate.runtime_user && <span className="mt-1 block text-xs leading-5 text-muted-foreground">{t("remote.setup.serviceAccount", { user: candidate.runtime_user })}</span>}
</span>
</label>)}
</fieldset>}
{inspection && !inspection.candidates.length && <div className="space-y-1">
<p className="text-[13px] font-medium">{t("remote.setup.notFound")}</p>
<p className="text-xs leading-5 text-muted-foreground">{t("remote.setup.notFoundHint")}</p>
</div>}
{inspection?.incomplete && <p className="text-xs leading-5 text-muted-foreground">{t("remote.setup.limitedSearch")}</p>}
{!manualLocation && <Button type="button" variant="ghost" size="sm" disabled={!!busy} onClick={() => setManualLocation(true)}>{t("remote.setup.manualLocation")}</Button>}
</div> : <>
<SSHHostPicker inputRef={hostInput} disabled={!!busy} value={form.host} configFile={form.ssh_config} imported={commandImported}
suggestions={!editingProfile || form.host !== editingProfile.host || form.ssh_config !== editingProfile.ssh_config}
onChange={(host) => { setForm({ ...form, host }); setCommandImported(false); setError(""); setErrorCode(""); }} onBlur={importCommand} />
<div>
<button type="button" disabled={!!busy} aria-expanded={sshOptions} aria-controls={optionsId}
className="flex min-h-9 items-center gap-2 rounded-xl text-[13px] text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
onClick={() => setSSHOptions(!sshOptions)}>
<ChevronDown className={cn("h-3.5 w-3.5 transition-transform", sshOptions && "rotate-180")} />{t("remote.connectionOptions")}
</button>
<DisclosureContent id={optionsId} open={sshOptions} className="space-y-3 pb-1 pt-3">
<RemoteField label={t("remote.ssh_config")} value={form.ssh_config} placeholder="~/.ssh/config" disabled={!!busy} onChange={(ssh_config) => setForm({ ...form, ssh_config })} action={filePicker("ssh_config")} />
<RemoteField label={t("remote.identity_file")} value={form.identity_file} disabled={!!busy} onChange={(identity_file) => setForm({ ...form, identity_file })} action={filePicker("identity_file")} />
<p className="text-xs leading-5 text-muted-foreground">{t("remote.setup.keyHint")}</p>
<RemoteField label={t("remote.sshPort")} value={form.port == null ? "" : String(form.port)} placeholder={t("remote.portPlaceholder")} type="number" min={1} max={65535} disabled={!!busy}
onChange={(port) => setForm({ ...form, port: port === "" ? null : Number(port) })} />
<RemoteField label={t("remote.name")} value={form.name} placeholder={form.host || t("remote.namePlaceholder")} disabled={!!busy} onChange={(name) => setForm({ ...form, name })} />
</DisclosureContent>
</div>
</>}
{(editing || manualLocation || nanobotError) && <div className="space-y-3">
<RemoteField label={t("remote.config_path")} value={form.config_path} disabled={!!busy} onChange={(config_path) => setForm({ ...form, config_path })} />
<RemoteField label={t("remote.runtime_user")} value={form.runtime_user} disabled={!!busy} onChange={(runtime_user) => setForm({ ...form, runtime_user })} />
<p className="text-xs leading-5 text-muted-foreground">{t("remote.setup.locationHint")}</p>
</div>}
</div>
<div className="shrink-0 space-y-3 pt-1">
{error && <div className="space-y-1">
<p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{error}</p>
{!sshOptions && /^(ssh_|local_file_not_found)/.test(errorCode) && <Button type="button" variant="ghost" size="sm" disabled={!!busy} onClick={editSSH}>{t("remote.setup.sshSettings")}</Button>}
</div>}
{busy.startsWith("pick-") && <p role="status" className="text-xs text-muted-foreground">{t("remote.setup.pickingFile")}</p>}
<div className="grid grid-cols-[auto_minmax(0,1fr)] items-center gap-2">
<Button type="button" variant="ghost" onClick={closeEditor}>{t("common.cancel")}</Button>
<Button type="submit" className="min-w-0" title={t(editorLabel)} aria-label={t(editorLabel)} aria-busy={!!busy} disabled={!!busy || !form.host.trim() || (locationStep && !form.config_path.trim())}>
{busy && !busy.startsWith("pick-") && <Loader2 aria-hidden className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" />}
<span role={busy && !busy.startsWith("pick-") ? "status" : undefined} className="truncate">{t(editorLabel)}</span>
</Button>
</div>
</div>
</form>}
</DialogContent>
</Dialog>
<Dialog open={!!disconnecting} onOpenChange={(value) => { if (!value && !busy) setDisconnecting(null); }}>
<DialogContent className="max-w-sm"><DialogHeader><DialogTitle>{t("remote.disconnectTitle", { name: disconnecting?.name })}</DialogTitle><DialogDescription>{t("remote.disconnectDescription")}</DialogDescription></DialogHeader>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<div className="flex justify-end gap-2"><Button variant="ghost" disabled={!!busy} onClick={() => setDisconnecting(null)}>{t("common.cancel")}</Button><Button variant="destructive" disabled={!!busy} onClick={() => { if (disconnecting) void disconnect(disconnecting.id); }}>{t("remote.disconnect")}</Button></div>
<DialogContent className="max-h-[85dvh] max-w-sm overflow-y-auto"><DialogHeader className="pr-5 text-left"><DialogTitle className="break-words leading-snug">{t("remote.disconnectTitle", { name: disconnectProfile?.name })}</DialogTitle><DialogDescription>{t("remote.disconnectDescription")}</DialogDescription></DialogHeader>
{error && <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{error}</p>}
<div className="grid grid-cols-2 gap-2"><Button variant="ghost" disabled={!!busy} onClick={() => setDisconnecting(null)}>{t("common.cancel")}</Button><Button variant="outline" className="min-w-0" disabled={!!busy} aria-busy={!!busy} onClick={() => { if (disconnecting) void disconnect(disconnecting.id); }}>{busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" />}<span className="truncate">{t("remote.disconnect")}</span></Button></div>
</DialogContent>
</Dialog>
<Dialog open={!!removing} onOpenChange={(value) => { if (!value && !busy) setRemoving(null); }}>
<DialogContent className="max-w-sm"><DialogHeader><DialogTitle>{t("remote.forgetTitle", { name: removing?.name })}</DialogTitle><DialogDescription>{t("remote.forgetDescription")}</DialogDescription></DialogHeader>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<div className="flex justify-end gap-2"><Button variant="ghost" disabled={!!busy} onClick={() => setRemoving(null)}>{t("common.cancel")}</Button><Button variant="destructive" disabled={!!busy} onClick={() => { void remove(); }}>{t("remote.forget")}</Button></div>
</DialogContent>
</Dialog>
<Dialog open={!!fingerprint} onOpenChange={(value) => { if (!value && !busy) setFingerprint(null); }}>
<DialogContent className="max-w-md"><DialogHeader><DialogTitle>{t("remote.verifyTitle")}</DialogTitle><DialogDescription>{t("remote.verifyDescription")}</DialogDescription></DialogHeader>
<code className="break-all rounded-xl bg-muted p-3 text-xs">{fingerprint?.fingerprint}</code>
<p className="text-xs leading-relaxed text-muted-foreground">{t("remote.verifyHint")}</p>
{error && <p role="alert" className="text-sm text-destructive">{error}</p>}
<div className="flex justify-end gap-2"><Button variant="ghost" disabled={!!busy} onClick={() => setFingerprint(null)}>{t("common.cancel")}</Button><Button disabled={!!busy} onClick={() => { void trustHost(); }}>{t("remote.verifyConnect")}</Button></div>
<DialogContent className="max-h-[85dvh] max-w-sm overflow-y-auto"><DialogHeader className="pr-5 text-left"><DialogTitle className="break-words leading-snug">{t("remote.forgetTitle", { name: removalProfile?.name })}</DialogTitle><DialogDescription>{t("remote.forgetDescription")}</DialogDescription></DialogHeader>
{removalProfile && (removalProfile.connected || connections.openHostIds.includes(removalProfile.id)) && <p role="note" className="rounded-xl bg-muted/40 p-3 text-xs leading-5">{t("remote.activeForgetWarning")}</p>}
{removalProfile?.paired && <div className="space-y-2 text-xs text-muted-foreground"><p>{t("remote.pair.forgetHint")}</p><code className="block break-all">{removalProfile.revoke_command}</code></div>}
{error && <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{error}</p>}
<div className="grid grid-cols-2 gap-2"><Button variant="ghost" disabled={!!busy} onClick={() => setRemoving(null)}>{t("common.cancel")}</Button><Button variant="destructive" className="min-w-0" disabled={!!busy} aria-busy={!!busy} onClick={() => { void remove(); }}>{busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" />}<span className="truncate">{t("remote.forget")}</span></Button></div>
</DialogContent>
</Dialog>
</div>;
}
function RemoteField({ label, onChange, ...props }: {
function RemoteField({ label, onChange, action, ...props }: {
label: string; value: string; onChange: (value: string) => void;
placeholder?: string; required?: boolean; disabled?: boolean; type?: string; min?: number; max?: number;
action?: ReactNode;
placeholder?: string; disabled?: boolean; type?: string; min?: number; max?: number;
}) {
const id = useId();
return <SettingsRow title={<label htmlFor={id}>{label}</label>}>
<Input id={id} {...props} onChange={(event) => onChange(event.target.value)} autoComplete="off" spellCheck={false} />
</SettingsRow>;
return <div className="space-y-1.5"><label htmlFor={id} className="block text-xs text-muted-foreground">{label}</label>
<div className="flex items-center gap-1"><Input id={id} {...props} className="min-w-0" onChange={(event) => onChange(event.target.value)} autoComplete="off" spellCheck={false} />{action}</div>
</div>;
}
+29 -12
View File
@@ -1,11 +1,12 @@
import { createContext, useContext, useEffect, useLayoutEffect, useRef, type ReactNode } from "react";
import { createContext, useContext, useEffect, useLayoutEffect, useRef, useSyncExternalStore, type ReactNode } from "react";
import { Loader2, PlugZap } from "lucide-react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import type { RemoteDirectory } from "@/lib/remote-instances";
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";
const RemoteContext = createContext<{
available: boolean;
@@ -16,6 +17,7 @@ const RemoteContext = createContext<{
refresh: () => Promise<RemoteDirectory>;
connect: (id: string, stillWanted?: () => boolean) => Promise<void>;
disconnect: (id: string) => Promise<void>;
cancel: () => void;
} | null>(null);
export function useRemoteConnections() { return useContext(RemoteContext); }
@@ -23,6 +25,9 @@ export function useRemoteConnections() { return useContext(RemoteContext); }
export function RemoteInstances({ children }: { children: ReactNode }) {
const { t } = useTranslation();
const hosts = useHostSessions();
const returnedPair = useSyncExternalStore(subscribePairReturn, readPairReturn);
const returnLocal = hosts.local;
useEffect(() => { if (returnedPair) returnLocal(); }, [returnedPair, returnLocal]);
const { selected, pending, frames, directory, error } = hosts;
const localPanel = useRef<HTMLDivElement>(null);
const lastLocalFocus = useRef<HTMLElement | null>(null);
@@ -34,24 +39,33 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
};
const message = error ? t(`remote.errors.${error}`, { defaultValue: t("remote.errors.unknown") }) : "";
const bridge = useSidebarHostBridge(frames, selected?.id, frameNodes, restoreLocalFocus, { pendingName: pending?.name, error: message });
useEffect(() => {
// A verified remote app can be interactive before optional images/fonts
// finish loading. Older bundles still use the iframe load fallback.
for (const id of bridge.readyIds) hosts.loaded(id);
}, [bridge.readyIds, hosts.loaded]);
const restoreFocus = () => {
if (activeHostId.current) bridge.focus(activeHostId.current);
else restoreLocalFocus();
};
const available = directory?.available === true || hosts.directoryError;
const activeFrame = frames.find((frame) => frame.connection.id === selected?.id);
const offline = !!selected && (activeFrame?.offline || (!activeFrame && !pending && !!error));
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 switchHost = (id: string) => {
void hosts.connect(id).catch((reason: unknown) => hosts.setError(reason instanceof Error ? reason.message : "unknown"));
// The session module owns attempt-scoped errors, including cancelled work.
void hosts.connect(id).catch(() => {});
};
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,
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) })),
pending, error: message, offline: !!offline, select: (id) => { if (id) switchHost(id); else hosts.local(); },
manage: () => { hosts.local(); window.location.hash = "/remote"; },
cancel: hosts.cancel, clearError: () => hosts.setError(""), restoreFocus,
manage,
cancel: hosts.cancel, clearError: hosts.clearError, restoreFocus,
};
useEffect(() => { if (selected) document.title = `${selected.name} · nanobot`; }, [selected]);
useEffect(() => {
@@ -76,7 +90,7 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
return <RemoteContext.Provider value={{ available, localActive: !selected, directory,
openHostIds: frames.map((frame) => frame.connection.id),
directoryError: hosts.directoryError, refresh: hosts.refresh, connect: hosts.connect, disconnect: hosts.disconnect }}>
directoryError: hosts.directoryError, refresh: hosts.refresh, connect: hosts.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">
@@ -87,7 +101,7 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
</div>
{frames.map((frame) => {
const active = selected?.id === frame.connection.id;
return <div key={`${frame.connection.id}:${frame.connection.gateway_id}`} data-host-view={frame.connection.id} aria-hidden={!active || offline}
return <div key={`${frame.connection.id}:${frame.connection.gateway_id}:${frame.connection.view_id || ""}`} data-host-view={frame.connection.id} aria-hidden={!active || offline}
{...(!active || offline ? { inert: "" } : {})} style={{ visibility: active ? "visible" : "hidden" }}
className={`absolute inset-0 transition-opacity duration-150 motion-reduce:transition-none ${active ? "visible opacity-100" : "invisible pointer-events-none opacity-0"}`}>
<iframe ref={(node) => { if (node) frameNodes.current.set(frame.connection.id, node); else frameNodes.current.delete(frame.connection.id); }}
@@ -99,10 +113,13 @@ export function RemoteInstances({ children }: { children: ReactNode }) {
})}
{selected && (offline || !activeFrame?.loaded) && <div className="absolute inset-0 flex flex-col items-center justify-center gap-3 bg-background px-6 text-center">
{offline ? <PlugZap className="h-7 w-7 text-muted-foreground" /> : <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />}
<p className="max-w-full break-words text-xs text-muted-foreground">{selected.name} · {selected.hostname}</p>
<p className="font-medium">{t(offline ? "remote.offline" : "remote.opening")}</p>
<p className="max-w-sm text-sm text-muted-foreground">{message || t("remote.noFallback")}</p>
<div className="flex items-center gap-2">
{offline && <Button disabled={!!pending} onClick={() => switchHost(selected.id)}>{t("remote.reconnect")}</Button>}
<p className="max-w-sm text-sm text-muted-foreground">{recoveryMessage}</p>
<div className="flex flex-wrap items-center justify-center gap-2">
{offline && (needsRemoteSetup(recoveryCode) ? <Button onClick={manage}>{t("remote.manageConnections")}</Button> : <Button disabled={!!pending} aria-busy={!!pending} onClick={() => switchHost(selected.id)}>
{pending && <Loader2 aria-hidden className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" />}{t(pending ? "remote.connecting" : "remote.reconnect")}
</Button>)}
<Button variant="ghost" onClick={hosts.local}>{t("remote.returnLocal")}</Button>
</div>
</div>}
+75 -59
View File
@@ -1,97 +1,113 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { ArrowRight, FileText, Loader2, RefreshCw, Search, Server } from "lucide-react";
import { useCallback, useEffect, useId, useRef, useState, type RefObject } from "react";
import { Check, RefreshCw, Server } from "lucide-react";
import { useTranslation } from "react-i18next";
import { SettingsGroup, SettingsSectionTitle } from "@/components/settings/shared/SettingsControls";
import { Button } from "@/components/ui/button";
import { Disclosure } from "@/components/ui/disclosure";
import { Input } from "@/components/ui/input";
import { useClient } from "@/providers/ClientProvider";
import { remoteAction, type SSHDiscovery } from "@/lib/remote-instances";
export function SSHHostPicker({ disabled, onSelect }: {
/** One address field for both manual entry and existing SSH aliases. */
export function SSHHostPicker({ disabled, value, configFile, imported, suggestions = true, onChange, onBlur, inputRef }: {
disabled: boolean;
onSelect: (host: SSHDiscovery["hosts"][number]) => void;
value: string;
configFile: string;
imported: boolean;
suggestions?: boolean;
onChange: (host: string) => void;
onBlur: () => void;
inputRef: RefObject<HTMLInputElement>;
}) {
const { t } = useTranslation();
const { client } = useClient();
const [result, setResult] = useState<SSHDiscovery | null>(null);
const id = useId();
const [result, setResult] = useState<{ file: string; data: SSHDiscovery } | null>(null);
const [busy, setBusy] = useState(false);
const [error, setError] = useState("");
const [configFile, setConfigFile] = useState("");
const [loadedFile, setLoadedFile] = useState("");
const [query, setQuery] = useState("");
const requestId = useRef(0);
const mounted = useRef(true);
const load = useCallback(async (file: string) => {
const id = ++requestId.current;
const list = useRef<HTMLDivElement>(null);
const file = configFile.trim();
const load = useCallback(async (path: string) => {
const request = ++requestId.current;
setBusy(true); setError("");
try {
const next = await remoteAction<SSHDiscovery>(client, "discover", { ssh_config: file.trim() });
const next = await remoteAction<SSHDiscovery>(client, "discover", { ssh_config: path });
if (!next || !Array.isArray(next.hosts) || !Array.isArray(next.files)
|| typeof next.incomplete !== "boolean" || next.hosts.some((host) => !host
|| typeof host.host !== "string" || typeof host.source !== "string" || typeof host.ssh_config !== "string")) {
throw new Error("discovery_failed");
}
if (mounted.current && id === requestId.current) {
setResult(next); setLoadedFile(file.trim()); setQuery("");
}
if (mounted.current && request === requestId.current) setResult({ file: path, data: next });
} catch (reason) {
if (mounted.current && id === requestId.current) {
if (mounted.current && request === requestId.current) {
const code = reason instanceof Error ? reason.message : "unknown";
setError(t(`remote.errors.${code}`, { defaultValue: t("remote.discoveryError") }));
}
} finally {
if (mounted.current && id === requestId.current) setBusy(false);
if (mounted.current && request === requestId.current) setBusy(false);
}
}, [client, t]);
useEffect(() => {
mounted.current = true;
if (!suggestions) return;
let started = false;
let timer: ReturnType<typeof setTimeout> | undefined;
const unsubscribe = client.onStatus((status) => {
if (status === "open" && !started) { started = true; void load(""); }
if (status === "open" && !started) {
started = true;
// Custom paths update quietly after typing; no separate "read config" flow.
timer = setTimeout(() => { void load(file); }, file ? 300 : 0);
}
});
return () => { mounted.current = false; requestId.current += 1; unsubscribe(); };
}, [client, load]);
return () => { mounted.current = false; requestId.current += 1; clearTimeout(timer); unsubscribe(); };
}, [client, file, load, suggestions]);
const hosts = (result?.hosts ?? []).filter(({ host }) => host.toLowerCase().includes(query.trim().toLowerCase()));
return <section className="settings-stack" aria-label={t("remote.sshHosts")}>
<div className="settings-section-heading">
<SettingsSectionTitle>{t("remote.sshHosts")}</SettingsSectionTitle>
<Button variant="ghost" size="icon" className="h-8 w-8" aria-label={t("remote.refreshHosts")} disabled={busy || disabled} onClick={() => { void load(loadedFile); }}>
<RefreshCw className={`h-4 w-4 ${busy ? "animate-spin" : ""}`} />
</Button>
</div>
<p className="settings-list-inset text-xs leading-5 text-muted-foreground">{t("remote.sshHostsHint")}</p>
{!!result?.hosts.length && <div className="settings-list-inset relative">
<div className="relative"><Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<Input className="pl-9" aria-label={t("remote.searchHosts")} placeholder={t("remote.searchHosts")} value={query} onChange={(event) => setQuery(event.target.value)} />
// Never select cached suggestions belonging to a different config file.
const data = suggestions && result?.file === file ? result.data : null;
const matched = (data?.hosts ?? []).filter(({ host }) => host.toLowerCase().includes(value.trim().toLowerCase()));
// A user recovering from a failed user@IP connection may select a custom
// config containing an alias. Keep that alias discoverable without asking
// them to know it already or silently replacing the address they entered.
const hosts = matched.length || !file ? matched : (data?.hosts ?? []);
return <div className="space-y-2.5">
<label htmlFor={id} className="block text-[13px] font-medium">{t("remote.host")}</label>
<Input ref={inputRef} id={id} value={value} required disabled={disabled} autoComplete="off" spellCheck={false}
placeholder={t("remote.hostPlaceholder")} aria-describedby={`${id}-hint`}
onChange={(event) => onChange(event.target.value)}
onBlur={onBlur}
onKeyDown={(event) => {
if (event.key === "ArrowDown" && hosts.length && !busy) {
event.preventDefault(); list.current?.querySelector<HTMLButtonElement>("button")?.focus();
}
}} />
<p id={`${id}-hint`} role={imported ? "status" : undefined} className="text-xs leading-5 text-muted-foreground">{t(imported ? "remote.commandImported" : suggestions ? "remote.commandHint" : "remote.addressHint")}</p>
{suggestions && (!!hosts.length || !!error) && <div className="rounded-2xl bg-muted/40 p-1.5">
<div className="flex h-8 items-center justify-between gap-2 px-2">
<span className="text-xs text-muted-foreground">{t("remote.sshHosts")}</span>
<Button type="button" variant="ghost" size="icon" className="h-7 w-7" aria-label={t("remote.refreshHosts")}
disabled={busy || disabled} onClick={() => { void load(file); }}>
<RefreshCw className={`h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} />
</Button>
</div>
</div>}
{hosts.length > 0 && <SettingsGroup>
<div className="max-h-64 overflow-y-auto">
{hosts.map((host) => <button key={host.host} type="button" disabled={disabled || busy}
aria-label={t("remote.useHost", { host: host.host })}
className="settings-list-row settings-hover flex w-full items-center gap-3 py-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50"
onClick={() => onSelect(host)}>
<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">{host.host}</span>
<span title={host.source} className="mt-0.5 block truncate text-xs text-muted-foreground">{host.source}</span></span>
<ArrowRight className="h-4 w-4 shrink-0 text-muted-foreground" />
<div ref={list} className="max-h-36 overflow-y-auto" aria-label={t("remote.sshHosts")}>
{hosts.map((host, index) => <button key={host.host} type="button" disabled={disabled || busy}
title={host.source} aria-label={t("remote.useHost", { host: host.host })}
className="flex min-h-9 w-full items-center gap-2.5 rounded-xl px-2 text-left text-[13px] transition-colors hover:bg-foreground/5 focus-visible:bg-foreground/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50"
onKeyDown={(event) => {
if (event.key === "ArrowDown" || event.key === "ArrowUp") {
event.preventDefault();
const next = index + (event.key === "ArrowDown" ? 1 : -1);
if (next < 0) inputRef.current?.focus();
else list.current?.querySelectorAll<HTMLButtonElement>("button")[next]?.focus();
}
}}
onClick={() => { onChange(host.host); inputRef.current?.focus(); }}>
<Server className="h-4 w-4 shrink-0 text-muted-foreground" /><span className="flex-1 truncate">{host.host}</span>
{value === host.host && <Check className="h-3.5 w-3.5 text-muted-foreground" />}
</button>)}
</div>
</SettingsGroup>}
{!result && busy && <p role="status" className="settings-list-inset flex items-center gap-2 text-xs text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" />{t("remote.loadingHosts")}</p>}
{result && !hosts.length && <p className="settings-list-inset text-[13px] leading-5 text-muted-foreground">{t(query ? "remote.noMatchingHosts" : "remote.noHosts")}</p>}
{result?.incomplete && <p className="settings-list-inset text-xs text-muted-foreground">{t("remote.partialHosts")}</p>}
<Disclosure summaryClassName="settings-list-inset flex min-h-10 items-center gap-2 rounded-xl text-xs text-muted-foreground settings-hover"
summary={<><FileText className="h-3.5 w-3.5" />{t("remote.otherConfig")}</>}>
<form className="settings-list-inset flex flex-wrap items-center gap-2 py-3" onSubmit={(event) => { event.preventDefault(); void load(configFile); }}>
<Input className="min-w-40 flex-1" aria-label={t("remote.configToRead")} placeholder="~/.ssh/config" value={configFile} disabled={busy || disabled} onChange={(event) => setConfigFile(event.target.value)} />
<Button type="submit" variant="outline" disabled={busy || disabled}>{t("remote.readConfig")}</Button>
</form>
</Disclosure>
{error && <p role="alert" className="settings-list-inset text-[13px] leading-5 text-destructive">{error}</p>}
</section>;
{error && <p role="alert" className="px-2 py-1 text-xs leading-5 text-muted-foreground">{error}</p>}
</div>}
{data?.incomplete && <p className="text-xs leading-5 text-muted-foreground">{t("remote.partialHosts")}</p>}
</div>;
}
+78 -28
View File
@@ -1,6 +1,7 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { useClient } from "@/providers/ClientProvider";
import { readRemoteInstances, readSelectedRemote, rememberSelectedRemote, remoteAction, validateRemoteConnection, type RemoteConnection, type RemoteDirectory, type SelectedRemote } from "@/lib/remote-instances";
import { readPairReturn } from "@/lib/remote-pair-return";
import { readRemoteInstances, readSelectedRemote, readRecentRemotes, rememberSelectedRemote, rememberRecentRemote, remoteAction, validateRemoteConnection, type RemoteConnection, type RemoteDirectory, type SelectedRemote } from "@/lib/remote-instances";
// Never silently evict a view containing drafts or unfinished attachments.
// Tunnels are shared across browser tabs, so only explicit disconnect closes one.
@@ -10,21 +11,27 @@ export interface HostFrame {
loaded: boolean;
offline: boolean;
failures: number;
error?: string;
}
interface PendingSwitch { id: string; name: string }
interface SwitchFailure { id: string; code: string }
export function useHostSessions() {
const { client, getToken } = useClient();
const [directory, setDirectory] = useState<RemoteDirectory | null>(null);
const [directoryError, setDirectoryError] = useState(false);
const [selected, setSelected] = useState<SelectedRemote | null>(readSelectedRemote);
const [selected, setSelected] = useState<SelectedRemote | null>(() => readPairReturn() ? null : readSelectedRemote());
const [recentIds, setRecentIds] = useState(readRecentRemotes);
const recentIdsRef = useRef(recentIds);
const selectedRef = useRef(selected);
const initial = useRef(selected);
const cache = useRef(new Map<string, HostFrame>());
const [frames, setFrames] = useState<HostFrame[]>([]);
const [pending, setPending] = useState<PendingSwitch | null>(null);
const pendingRef = useRef<PendingSwitch | null>(null);
const [error, setError] = useState("");
const [pending, setPending] = useState<PendingSwitch | null>(() => selected ? { id: selected.id, name: selected.name } : null);
const pendingRef = useRef<PendingSwitch | null>(pending);
const [failure, setFailure] = useState<SwitchFailure | null>(null);
const clearError = useCallback(() => setFailure(null), []);
const directoryGeneration = useRef(0);
const mounted = useRef(true);
const epoch = useRef(0);
const waiter = useRef<{ id: string; finish: (ready: boolean) => void } | null>(null);
@@ -43,17 +50,22 @@ export function useHostSessions() {
selectedRef.current = value;
setSelected(value);
rememberSelectedRemote(value);
setError("");
if (value) {
recentIdsRef.current = rememberRecentRemote(value.id, recentIdsRef.current);
setRecentIds(recentIdsRef.current);
}
setFailure(null);
publish();
}, [publish]);
const local = useCallback(() => { cancel(); select(null); }, [cancel, select]);
const refresh = useCallback(async () => {
const generation = ++directoryGeneration.current;
try {
const next = window.top === window ? await readRemoteInstances(getToken()) : { available: false, profiles: [] };
if (mounted.current) { setDirectory(next); setDirectoryError(false); }
if (mounted.current && generation === directoryGeneration.current) { setDirectory(next); setDirectoryError(false); }
return next;
} catch (reason) {
if (mounted.current) setDirectoryError(true);
if (mounted.current && generation === directoryGeneration.current) setDirectoryError(true);
throw reason;
}
}, [getToken]);
@@ -67,10 +79,15 @@ export function useHostSessions() {
if (wanted()) select(warm.connection);
return;
}
if (!warm && cache.current.size >= MAX_HOST_VIEWS) throw new Error("view_limit");
if (!warm && cache.current.size >= MAX_HOST_VIEWS) {
setFailure({ id, code: "view_limit" });
throw new Error("view_limit");
}
// A health response started before this mutation describes the old tunnel.
directoryGeneration.current += 1;
const name = directory?.profiles.find((item) => item.id === id)?.name || initial.current?.name || id;
setPendingSwitch({ id, name });
setError("");
setFailure(null);
let openingFrame = warm?.loaded ? undefined : warm;
try {
const connection = validateRemoteConnection(await remoteAction<RemoteConnection>(client, "connect", { id }));
@@ -80,12 +97,13 @@ export function useHostSessions() {
return;
}
let frame = cache.current.get(id);
if (!frame || frame.connection.url !== connection.url || frame.connection.gateway_id !== connection.gateway_id) {
if (!frame || frame.connection.url !== connection.url || frame.connection.gateway_id !== connection.gateway_id
|| frame.connection.view_id !== connection.view_id) {
frame = { connection, loaded: false, offline: false, failures: 0 };
cache.current.set(id, frame);
} else {
frame.connection = connection;
frame.offline = false; frame.failures = 0;
frame.offline = false; frame.failures = 0; frame.error = "";
}
if (!frame.loaded) openingFrame = frame;
publish();
@@ -95,14 +113,20 @@ export function useHostSessions() {
const timer = window.setTimeout(() => {
waiter.current = null;
reject(new Error("view_load_failed"));
}, 25_000);
// Cold remote bundles can take several SSH round trips. Keep the
// current host usable and cancellable while giving them time to load.
}, 60_000);
waiter.current = { id, finish: (ready) => { window.clearTimeout(timer); resolve(ready); } };
});
if (!ready) return;
}
if (wanted()) select(connection);
} catch (reason) {
if (wanted()) throw reason;
if (wanted()) {
setFailure({ id, code: reason instanceof Error ? reason.message : "unknown" });
void refresh().catch(() => {});
throw reason;
}
} finally {
// Cancelled/failed cold pages contain no user work. Don't let them use up
// the view budget; a newer attempt for this host owns its transport now.
@@ -122,12 +146,15 @@ export function useHostSessions() {
if (waiter.current?.id === id) { waiter.current.finish(true); waiter.current = null; }
}, [publish]);
const disconnect = useCallback(async (id: string) => {
directoryGeneration.current += 1;
if (pendingRef.current?.id === id) cancel();
await remoteAction(client, "disconnect", { id });
if (selectedRef.current?.id === id) local();
cache.current.delete(id);
publish();
await refresh();
// The mutation succeeded. A failed follow-up read must not ask the user to
// repeat a destructive action; refresh has its own retryable list error.
await refresh().catch(() => {});
}, [cancel, client, local, publish, refresh]);
useEffect(() => {
@@ -138,41 +165,52 @@ export function useHostSessions() {
useEffect(() => {
const saved = initial.current;
if (!saved || window.top !== window) return;
const restoration = epoch.current;
let started = false;
const timer = window.setTimeout(() => {
started = true;
if (selectedRef.current?.id === saved.id) setError("ssh_unreachable");
if (selectedRef.current?.id === saved.id && epoch.current === restoration) {
setPendingSwitch(null);
setFailure({ id: saved.id, code: "ssh_unreachable" });
}
}, 15_000);
const unsubscribe = client.onStatus((status) => {
if (status !== "open" || started) return;
started = true;
window.clearTimeout(timer);
if (selectedRef.current?.id !== saved.id) return;
void connectRef.current(saved.id).catch((reason: unknown) => {
if (mounted.current && selectedRef.current?.id === saved.id) setError(reason instanceof Error ? reason.message : "unknown");
});
if (selectedRef.current?.id !== saved.id || epoch.current !== restoration) return;
void connectRef.current(saved.id).catch(() => {});
});
return () => { window.clearTimeout(timer); unsubscribe(); };
}, [client]);
}, [client, setPendingSwitch]);
useEffect(() => {
let checking = false;
let cancelled = false;
const tick = async () => {
if (checking || !cache.current.size) return;
checking = true;
const generation = ++directoryGeneration.current;
try {
const next = await readRemoteInstances(getToken());
if (cancelled) return;
if (cancelled || generation !== directoryGeneration.current) return;
setDirectory(next); setDirectoryError(false);
for (const [id, frame] of cache.current) {
if (id === pendingRef.current?.id) continue;
const connected = next.profiles.some((profile) => profile.id === id && profile.connected);
const profile = next.profiles.find((profile) => profile.id === id);
const changed = (!!profile?.gateway_id && profile.gateway_id !== frame.connection.gateway_id)
|| (!!profile?.view_id && profile.view_id !== frame.connection.view_id);
const connected = !!profile?.connected && !changed;
frame.failures = connected ? 0 : frame.failures + 1;
if (connected || frame.failures >= 2) frame.offline = !connected;
if (connected || frame.failures >= 2) {
frame.offline = !connected;
frame.error = connected ? "" : changed ? "instance_changed" : profile?.connection_error || (!profile ? "profile_not_found" : "");
}
if (connected && frame.loaded) setFailure((current) => current?.id === id ? null : current);
}
} catch {
if (!cancelled) for (const frame of cache.current.values()) {
if (++frame.failures >= 2) frame.offline = true;
if (!cancelled && generation === directoryGeneration.current) for (const [id, frame] of cache.current) {
if (id === pendingRef.current?.id) continue;
if (++frame.failures >= 2) { frame.offline = true; frame.error = "directory_unavailable"; }
}
} finally {
checking = false;
@@ -180,7 +218,19 @@ export function useHostSessions() {
}
};
const timer = window.setInterval(() => { void tick(); }, 5_000);
return () => { cancelled = true; window.clearInterval(timer); };
// Background tabs throttle timers. Recheck promptly after waking or a
// network change, without reloading a frame or changing the selected host.
const wake = () => { if (document.visibilityState === "visible") void tick(); };
window.addEventListener("online", wake);
window.addEventListener("pageshow", wake);
document.addEventListener("visibilitychange", wake);
return () => {
cancelled = true; window.clearInterval(timer);
window.removeEventListener("online", wake);
window.removeEventListener("pageshow", wake);
document.removeEventListener("visibilitychange", wake);
};
}, [client, getToken, publish]);
return { directory, directoryError, refresh, selected, frames, pending, error, setError, connect, cancel, local, disconnect, loaded };
return { directory, directoryError, refresh, selected, recentIds, frames, pending,
error: failure?.code || "", errorId: failure?.id, clearError, connect, cancel, local, disconnect, loaded };
}
+121 -18
View File
@@ -1,5 +1,96 @@
{
"remote": {
"activeForgetWarning": "All tabs using this connection will disconnect. Unsaved work may be lost.",
"saved": "Saved",
"pair": {
"expiringDevice": "Authorization expires {{date}}.",
"expiredDevice": "Authorization expired. Pair this server again before reconnecting.",
"introHint": "Run one command in your server terminal to connect.",
"copiedTitle": "Command copied",
"afterCopyHint": "Paste it into your server terminal. After authorizing, open the returned link on this computer.",
"copyAgain": "Copy again",
"otherWays": "Other ways",
"helpTitle": "Requirements & help",
"validityHint": "Commands expire after 10 minutes. Review access before authorizing.",
"linkDescription": "Run a command on your server, then follow its link back here.",
"preparing": "Preparing your connection…",
"linkRunHint": "Paste the command into your cloud terminal and authorize this computer. It is valid for 10 minutes.",
"showCommand": "View command",
"checkingLink": "Checking the connection link…",
"returnTitle": "2. Return to nanobot",
"returnHint": "After authorizing, open the terminal’s link on this computer. We’ll fill in the connection details.",
"pasteInstead": "Use a connection code instead",
"confirmLinkDescription": "Continue only if this link or code came from your own trusted server terminal.",
"route": "Network route…",
"direct": "Direct connection",
"savedRoute": "Saved network route",
"routeDescription": "For an existing VPN or special SSH network route.",
"routeHint": "Optionally reuse the network route of a saved SSH connection to this same server. Its login key and credentials are not copied.",
"title": "Connect without an SSH setup",
"description": "Run one command in your server console, then bring the connection code back here.",
"steps": {
"run": "Copy a pairing command to your server terminal.",
"paste": "Paste the code the server gives you.",
"connect": "Confirm the server and open nanobot."
},
"requirements": "For Linux servers with nanobot installed. SSH must still be reachable; no relay or public WebUI is needed.",
"useSSH": "Use existing SSH settings",
"start": "Get pairing command",
"runTitle": "1. Run on your server",
"runHint": "Open the terminal in your cloud console. Paste this command and follow the prompts. The server also needs this version of nanobot.",
"command": "Pairing command",
"copy": "Copy command",
"copied": "Copied",
"copyFailed": "Could not copy. Select and copy the command above.",
"code": "Connection code",
"codeHint": "Use the code starting with nbpc1. from that terminal. It only works with this local pairing request.",
"expired": "This request has expired. Generate a new command. If you already authorized it on the server, use the revoke command printed there.",
"restart": "Get a new command",
"review": "Review connection",
"confirmTitle": "Open this nanobot?",
"confirmDescription": "Only continue with a code copied from your own trusted server terminal.",
"access": "This computer will have full access to this nanobot's chats, settings and enabled tools.",
"expiry": "Device authorization expires on {{date}}. Your server's SSH and nanobot ports stay private as configured.",
"security": "Connection details & revocation",
"fingerprint": "The SSH server must match this fingerprint from the server console:",
"revoke": "To revoke new connections, run this on the server and close any open remote sessions:",
"retryHint": "Pairing is saved. You can retry without running the server command again. If SSH is blocked by your network or VPN, pairing cannot bypass it.",
"forgetHint": "Forgetting removes this connection from the list, not its server authorization. To revoke the device, run this on the server:"
},
"setup": {
"progress": "Connection setup",
"server": "Server",
"nanobot": "nanobot",
"signedIn": "SSH connected",
"changeServer": "Change",
"chooseNanobot": "Which nanobot would you like to open?",
"yourNanobot": "Your nanobot",
"serviceAccount": "Runs as {{user}}. Opening uses this account’s existing sudo permissions.",
"notFound": "No nanobot configuration found",
"notFoundHint": "Check that nanobot is installed and running. For Docker or a custom installation, ask the person who deployed it for the config path and service account.",
"limitedSearch": "Checked your config and named nanobot system services. Other installations may need a path below.",
"manualLocation": "Specify a different location",
"keyHint": "Use the path to your SSH private key on this computer, not its contents or a model API key. Password-only SSH login is not supported yet.",
"locationHint": "These are paths and accounts on the server. No installation or permission changes will be made.",
"sshSettings": "SSH login settings",
"checking": "Signing in and looking for nanobot…",
"opening": "Opening the existing nanobot…",
"openNanobot": "Open nanobot",
"chooseFile": "Choose file: {{field}}",
"pickingFile": "Choose a file in the system dialog…"
},
"searchHosts": "Search hosts…",
"noMatchingHosts": "No matching hosts",
"commandHint": "Enter user@server or choose a saved SSH host. We’ll sign in using your existing SSH settings, then look for nanobot.",
"commandImported": "SSH options filled in. You can review them in Connection options.",
"hostPlaceholder": "Host alias or user@server",
"addressHint": "Your existing SSH username, key and port are used automatically.",
"manualAddress": "No matching alias. You can connect with the address above.",
"connectionOptions": "Connection options",
"editDescription": "Save your changes here, then connect when you’re ready.",
"save": "Save changes",
"saving": "Saving…",
"connect": "Connect",
"localShort": "Local",
"disconnectTitle": "Disconnect from {{name}}?",
"disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
@@ -11,19 +102,11 @@
"cancelSwitch": "Cancel switch",
"localEnvironment": "Local · {{name}}",
"sshHosts": "From your SSH config",
"sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
"refreshHosts": "Refresh SSH hosts",
"searchHosts": "Search SSH hosts",
"useHost": "Use {{host}}",
"loadingHosts": "Reading SSH config…",
"noHosts": "No named hosts found. You can enter an SSH address below.",
"noMatchingHosts": "No matching hosts.",
"partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
"otherConfig": "Use another SSH config file",
"configToRead": "SSH config file to read",
"readConfig": "Read hosts",
"discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
"portPlaceholder": "Use SSH config (normally 22)",
"portPlaceholder": "From SSH config",
"loading": "Loading connections…",
"retry": "Retry",
"unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
@@ -39,20 +122,17 @@
"current": "Currently using",
"remote": "Remote",
"returnLocal": "Back to local nanobot",
"add": "Connect to remote nanobot…",
"addTitle": "Connect to remote nanobot",
"addDescription": "Connect to a nanobot that's already running on your server.",
"add": "Add server",
"addTitle": "Connect to a server",
"addDescription": "Connect to an existing nanobot. Chats and settings stay on the server.",
"host": "SSH address",
"name": "Name (optional)",
"namePlaceholder": "Team server",
"keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
"advanced": "Advanced",
"sshPort": "SSH port",
"ssh_config": "SSH config file (optional)",
"identity_file": "Private key path (optional)",
"config_path": "Server's nanobot config path",
"runtime_user": "nanobot service account (optional)",
"saveConnect": "Save & connect",
"connecting": "Connecting…",
"opening": "Opening your server…",
"frameTitle": "nanobot on {{name}}",
@@ -65,6 +145,28 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
"disconnected": "This shared connection was closed. Reconnect when you’re ready.",
"instance_changed": "This server connection changed. Reconnecting will reload its view; unsent drafts may be lost.",
"pair_authorization_rejected": "The server no longer accepts this device key. Its authorization may have been revoked or expired. Pair again from your server console.",
"pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",
"pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",
"pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",
"pair_expired": "This pairing request expired. Generate a new command.",
"pair_authorization_expired": "This device authorization expired. Pair the server again.",
"pair_used": "This request was already used. Generate a new one.",
"pair_limit": "Close unused pairing windows and try again.",
"pair_managed": "Pair again to change the server or credentials.",
"ssh_connection_closed": "The SSH connection closed during setup. This does not confirm a key problem. Check your VPN/proxy or use the SSH settings that work in your terminal.",
"ssh_refused": "The server refused the SSH connection. Check its SSH port and whether the SSH service is running.",
"ssh_host_not_found": "This server name could not be resolved. Check the address or choose a host from your SSH config.",
"ssh_too_many_keys": "SSH tried too many keys. Specify the correct key using an SSH config with IdentitiesOnly yes.",
"duplicate_instance": "This nanobot is already connected through another SSH address. Use its existing entry in Switch host.",
"ssh_agent_refused": "Your SSH agent declined to use the key. Unlock or approve it in your key manager, then retry. If SSH works only in a terminal, restart nanobot from that terminal.",
"ssh_key_permissions": "SSH rejected the private key file permissions. Restrict access to your user account, then retry.",
"ssh_config_invalid": "OpenSSH could not read these connection settings. Check the selected SSH config in your terminal.",
"ssh_forwarding_denied": "SSH signed in, but the server blocked port forwarding. Ask the administrator to allow forwarding to nanobot's loopback port.",
"probe_failed": "SSH signed in, but could not run the nanobot check. Check that this account can run non-interactive Python commands.",
"invalid_ssh_command": "Use a host alias, user@server, or ssh with -p, -i, -F and -l. Quote paths containing spaces. Put other options in SSH config; remote commands aren't supported.",
"view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
"view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
"same_instance": "This is the nanobot you are already using. No remote connection is needed.",
@@ -79,10 +181,11 @@
"host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
"host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "The file chooser couldn't open. You can paste a local file path instead.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
@@ -92,7 +195,7 @@
"webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
"remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
"profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
"invalid_profile": "Check the address, port and Advanced fields.",
"invalid_profile": "Check the address, port and Connection options fields.",
"profile_not_found": "This saved server no longer exists. Refresh the list.",
"profile_limit": "You can save up to 20 servers.",
"connection_limit": "Disconnect an existing server before opening another connection.",
+121 -18
View File
@@ -1,5 +1,96 @@
{
"remote": {
"activeForgetWarning": "Se desconectarán todas las pestañas que usen esta conexión. El trabajo sin guardar puede perderse.",
"saved": "Guardado",
"pair": {
"expiringDevice": "La autorización vence el {{date}}.",
"expiredDevice": "La autorización ha vencido. Vuelve a emparejar este servidor antes de reconectar.",
"introHint": "Ejecuta un comando en la terminal de tu servidor para conectarte.",
"copiedTitle": "Comando copiado",
"afterCopyHint": "Pégalo en la terminal de tu servidor. Tras autorizar, abre el enlace que aparece en este ordenador.",
"copyAgain": "Copiar de nuevo",
"otherWays": "Otras formas",
"helpTitle": "Requisitos y ayuda",
"validityHint": "Los comandos caducan en 10 minutos. Revisa los permisos antes de autorizar.",
"linkDescription": "Ejecuta un comando en el servidor y vuelve mediante el enlace del terminal.",
"preparing": "Preparando la conexión…",
"linkRunHint": "Pega el comando en el terminal de la nube y autoriza este equipo. Es válido durante 10 minutos.",
"showCommand": "Ver comando",
"checkingLink": "Comprobando el enlace…",
"returnTitle": "2. Volver a nanobot",
"returnHint": "Tras autorizar, abre el enlace del terminal en este equipo. Completaremos los datos de conexión.",
"pasteInstead": "Usar un código de conexión",
"confirmLinkDescription": "Continúa solo si el enlace o código procede del terminal de tu propio servidor de confianza.",
"route": "Ruta de red…",
"direct": "Conexión directa",
"savedRoute": "Ruta de red guardada",
"routeDescription": "Para una VPN o una ruta SSH especial existente.",
"routeHint": "Reutiliza la ruta de red de una conexión SSH guardada al mismo servidor, sin copiar sus claves ni credenciales.",
"title": "Conectar sin configurar SSH",
"description": "Ejecuta un comando en la consola del servidor y pega aquí el código de conexión.",
"steps": {
"run": "Copia el comando de emparejamiento en el terminal del servidor.",
"paste": "Pega el código que genera el servidor.",
"connect": "Confirma el servidor y abre nanobot."
},
"requirements": "Para servidores Linux con nanobot instalado. SSH debe ser accesible; no hace falta un intermediario ni una WebUI pública.",
"useSSH": "Usar ajustes SSH existentes",
"start": "Obtener comando",
"runTitle": "1. Ejecutar en el servidor",
"runHint": "Abre el terminal de tu consola en la nube, pega el comando y sigue las indicaciones. El servidor también necesita esta versión de nanobot.",
"command": "Comando de emparejamiento",
"copy": "Copiar comando",
"copied": "Copiado",
"copyFailed": "No se pudo copiar. Selecciona y copia el comando de arriba.",
"code": "Código de conexión",
"codeHint": "Usa el código que empieza por nbpc1. Solo funciona con esta solicitud local.",
"expired": "La solicitud ha caducado. Genera un comando nuevo. Si ya la autorizaste, usa el comando de revocación mostrado en el servidor.",
"restart": "Generar otro comando",
"review": "Revisar conexión",
"confirmTitle": "¿Abrir este nanobot?",
"confirmDescription": "Continúa solo con un código copiado de tu propio terminal de servidor de confianza.",
"access": "Este ordenador tendrá acceso completo a los chats, ajustes y herramientas habilitadas de este nanobot.",
"expiry": "La autorización caduca el {{date}}. No cambia la exposición configurada de los puertos SSH y nanobot.",
"security": "Detalles y revocación",
"fingerprint": "El servidor SSH debe coincidir con esta huella de la consola:",
"revoke": "Para revocar conexiones nuevas, ejecuta esto en el servidor y cierra las sesiones remotas abiertas:",
"retryHint": "El emparejamiento está guardado. Puedes reintentar sin ejecutar el comando otra vez. No evita bloqueos de SSH por la red o VPN.",
"forgetHint": "Olvidar elimina la conexión de la lista, no la autorización del servidor. Para revocarla, ejecuta:"
},
"setup": {
"progress": "Configuración de conexión",
"server": "Servidor",
"nanobot": "nanobot",
"signedIn": "SSH conectado",
"changeServer": "Cambiar",
"chooseNanobot": "¿Qué nanobot quieres abrir?",
"yourNanobot": "Tu nanobot",
"serviceAccount": "Se ejecuta como {{user}}. Se usarán los permisos sudo existentes de esta cuenta.",
"notFound": "No se encontró la configuración de nanobot",
"notFoundHint": "Comprueba que nanobot esté instalado y en ejecución. Para Docker o instalaciones personalizadas, pide al administrador la ruta y la cuenta del servicio.",
"limitedSearch": "Se revisaron tu configuración y los servicios nanobot del sistema. Otras instalaciones pueden requerir una ruta.",
"manualLocation": "Especificar otra ubicación",
"keyHint": "Ruta de la clave SSH privada en este equipo, no su contenido ni una clave de API. El acceso SSH solo con contraseña aún no es compatible.",
"locationHint": "Ruta y cuenta del servidor. No se instalará nada ni se cambiarán permisos.",
"sshSettings": "Ajustes de acceso SSH",
"checking": "Iniciando sesión y buscando nanobot…",
"opening": "Abriendo el nanobot existente…",
"openNanobot": "Abrir nanobot",
"chooseFile": "Elegir archivo: {{field}}",
"pickingFile": "Elige un archivo en el diálogo del sistema…"
},
"searchHosts": "Buscar servidores…",
"noMatchingHosts": "No hay servidores coincidentes",
"commandHint": "Escribe usuario@servidor o elige un host SSH. Iniciaremos sesión con tus ajustes existentes y buscaremos nanobot.",
"commandImported": "Opciones SSH completadas. Puedes revisarlas en Opciones de conexión.",
"hostPlaceholder": "Host alias or user@server",
"addressHint": "Your existing SSH username, key and port are used automatically.",
"manualAddress": "No matching alias. You can connect with the address above.",
"connectionOptions": "Connection options",
"editDescription": "Save your changes here, then connect when you’re ready.",
"save": "Save changes",
"saving": "Saving…",
"connect": "Connect",
"localShort": "Local",
"disconnectTitle": "Disconnect from {{name}}?",
"disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
@@ -11,19 +102,11 @@
"cancelSwitch": "Cancel switch",
"localEnvironment": "Local · {{name}}",
"sshHosts": "From your SSH config",
"sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
"refreshHosts": "Refresh SSH hosts",
"searchHosts": "Search SSH hosts",
"useHost": "Use {{host}}",
"loadingHosts": "Reading SSH config…",
"noHosts": "No named hosts found. You can enter an SSH address below.",
"noMatchingHosts": "No matching hosts.",
"partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
"otherConfig": "Use another SSH config file",
"configToRead": "SSH config file to read",
"readConfig": "Read hosts",
"discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
"portPlaceholder": "Use SSH config (normally 22)",
"portPlaceholder": "From SSH config",
"loading": "Loading connections…",
"retry": "Retry",
"unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
@@ -39,20 +122,17 @@
"current": "Currently using",
"remote": "Remote",
"returnLocal": "Back to local nanobot",
"add": "Connect to remote nanobot…",
"addTitle": "Connect to remote nanobot",
"addDescription": "Connect to a nanobot that's already running on your server.",
"add": "Add server",
"addTitle": "Connect to a server",
"addDescription": "Connect to an existing nanobot. Chats and settings stay on the server.",
"host": "SSH address",
"name": "Name (optional)",
"namePlaceholder": "Team server",
"keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
"advanced": "Advanced",
"sshPort": "SSH port",
"ssh_config": "SSH config file (optional)",
"identity_file": "Private key path (optional)",
"config_path": "Server's nanobot config path",
"runtime_user": "nanobot service account (optional)",
"saveConnect": "Save & connect",
"connecting": "Connecting…",
"opening": "Opening your server…",
"frameTitle": "nanobot on {{name}}",
@@ -65,6 +145,28 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
"disconnected": "Esta conexión compartida se cerró. Reconecta cuando quieras.",
"instance_changed": "La conexión a este servidor cambió. Al reconectar se recargará la vista; los borradores sin enviar podrían perderse.",
"pair_authorization_rejected": "El servidor ya no acepta la clave de este dispositivo. La autorización puede haberse revocado o caducado. Vuelve a emparejar desde la consola del servidor.",
"pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",
"pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",
"pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",
"pair_expired": "This pairing request expired. Generate a new command.",
"pair_authorization_expired": "This device authorization expired. Pair the server again.",
"pair_used": "This request was already used. Generate a new one.",
"pair_limit": "Close unused pairing windows and try again.",
"pair_managed": "Pair again to change the server or credentials.",
"ssh_connection_closed": "La conexión SSH se cerró durante la configuración. No confirma un problema de clave. Revisa la VPN o el proxy, o usa los ajustes SSH que funcionan en tu terminal.",
"ssh_refused": "El servidor rechazó SSH. Revisa el puerto y que el servicio SSH esté activo.",
"ssh_host_not_found": "No se pudo resolver el nombre. Revisa la dirección o elige un host de tu configuración SSH.",
"ssh_too_many_keys": "SSH intentó demasiadas claves. Especifica la clave correcta con IdentitiesOnly yes en la configuración SSH.",
"duplicate_instance": "Este nanobot ya está conectado mediante otra dirección SSH. Usa la conexión existente en Cambiar servidor.",
"ssh_agent_refused": "El agente SSH rechazó el uso de la clave. Desbloquéala o autorízala en tu gestor de claves y reintenta. Si solo funciona en un terminal, reinicia nanobot desde ese terminal.",
"ssh_key_permissions": "SSH rechazó los permisos del archivo de clave privada. Restringe el acceso a tu cuenta y reintenta.",
"ssh_config_invalid": "OpenSSH no pudo leer la configuración de conexión. Revisa la configuración SSH seleccionada en tu terminal.",
"ssh_forwarding_denied": "SSH inició sesión, pero el servidor bloqueó el reenvío de puertos. Pide al administrador que permita reenviar al puerto de bucle local de nanobot.",
"probe_failed": "SSH inició sesión, pero no pudo comprobar nanobot. Verifica que esta cuenta pueda ejecutar comandos Python no interactivos.",
"invalid_ssh_command": "Usa un alias, usuario@servidor o ssh con -p, -i, -F y -l. Pon entre comillas las rutas con espacios. Guarda otras opciones en la configuración SSH; no se admiten comandos remotos.",
"view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
"view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
"same_instance": "This is the nanobot you are already using. No remote connection is needed.",
@@ -79,10 +181,11 @@
"host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
"host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "No se pudo abrir el selector. Puedes pegar la ruta de un archivo local.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
@@ -92,7 +195,7 @@
"webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
"remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
"profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
"invalid_profile": "Check the address, port and Advanced fields.",
"invalid_profile": "Check the address, port and Connection options fields.",
"profile_not_found": "This saved server no longer exists. Refresh the list.",
"profile_limit": "You can save up to 20 servers.",
"connection_limit": "Disconnect an existing server before opening another connection.",
+121 -18
View File
@@ -1,5 +1,96 @@
{
"remote": {
"activeForgetWarning": "Tous les onglets utilisant cette connexion seront déconnectés. Le travail non enregistré peut être perdu.",
"saved": "Enregistré",
"pair": {
"expiringDevice": "L’autorisation expire le {{date}}.",
"expiredDevice": "L’autorisation a expiré. Associez à nouveau ce serveur avant de vous reconnecter.",
"introHint": "Exécutez une commande dans le terminal du serveur pour vous connecter.",
"copiedTitle": "Commande copiée",
"afterCopyHint": "Collez-la dans le terminal du serveur. Après autorisation, ouvrez le lien affiché sur cet ordinateur.",
"copyAgain": "Copier à nouveau",
"otherWays": "Autres méthodes",
"helpTitle": "Prérequis et aide",
"validityHint": "Les commandes expirent après 10 minutes. Vérifiez les accès avant d’autoriser.",
"linkDescription": "Exécutez une commande sur le serveur, puis revenez via le lien du terminal.",
"preparing": "Préparation de la connexion…",
"linkRunHint": "Collez la commande dans le terminal cloud et autorisez cet ordinateur. Elle est valable 10 minutes.",
"showCommand": "Voir la commande",
"checkingLink": "Vérification du lien…",
"returnTitle": "2. Revenir à nanobot",
"returnHint": "Après autorisation, ouvrez le lien du terminal sur cet ordinateur. Les informations de connexion seront remplies automatiquement.",
"pasteInstead": "Utiliser un code de connexion",
"confirmLinkDescription": "Continuez uniquement si ce lien ou ce code provient du terminal de votre propre serveur de confiance.",
"route": "Chemin réseau…",
"direct": "Connexion directe",
"savedRoute": "Chemin réseau enregistré",
"routeDescription": "Pour un VPN ou un chemin SSH particulier existant.",
"routeHint": "Réutilisez le chemin réseau d’une connexion SSH enregistrée vers le même serveur, sans copier ses clés ni ses identifiants.",
"title": "Se connecter sans configurer SSH",
"description": "Exécutez une commande dans la console du serveur, puis collez le code de connexion ici.",
"steps": {
"run": "Copiez la commande d’association dans le terminal du serveur.",
"paste": "Collez le code fourni par le serveur.",
"connect": "Confirmez le serveur et ouvrez nanobot."
},
"requirements": "Pour les serveurs Linux où nanobot est installé. SSH doit rester accessible ; aucun relais ni WebUI publique requis.",
"useSSH": "Utiliser les réglages SSH",
"start": "Obtenir la commande",
"runTitle": "1. Exécuter sur le serveur",
"runHint": "Ouvrez le terminal de votre console cloud, collez la commande et suivez les indications. Le serveur doit aussi utiliser cette version de nanobot.",
"command": "Commande d’association",
"copy": "Copier la commande",
"copied": "Copié",
"copyFailed": "Copie impossible. Sélectionnez et copiez la commande ci-dessus.",
"code": "Code de connexion",
"codeHint": "Utilisez le code commençant par nbpc1. Il fonctionne uniquement avec cette demande locale.",
"expired": "Cette demande a expiré. Générez une nouvelle commande. Si elle a déjà été autorisée, utilisez la commande de révocation affichée sur le serveur.",
"restart": "Nouvelle commande",
"review": "Vérifier la connexion",
"confirmTitle": "Ouvrir ce nanobot ?",
"confirmDescription": "Continuez uniquement avec un code copié depuis votre propre terminal de serveur de confiance.",
"access": "Cet ordinateur aura un accès complet aux conversations, réglages et outils activés de ce nanobot.",
"expiry": "L’autorisation expire le {{date}}. L’exposition configurée des ports SSH et nanobot reste inchangée.",
"security": "Détails et révocation",
"fingerprint": "Le serveur SSH doit correspondre à cette empreinte affichée dans sa console :",
"revoke": "Pour révoquer les nouvelles connexions, exécutez ceci sur le serveur et fermez les sessions distantes ouvertes :",
"retryHint": "L’association est enregistrée. Réessayez sans relancer la commande serveur. Elle ne contourne pas un blocage SSH par le réseau ou le VPN.",
"forgetHint": "Oublier retire la connexion de la liste, mais pas l’autorisation du serveur. Pour la révoquer, exécutez :"
},
"setup": {
"progress": "Configuration de la connexion",
"server": "Serveur",
"nanobot": "nanobot",
"signedIn": "SSH connecté",
"changeServer": "Modifier",
"chooseNanobot": "Quel nanobot souhaitez-vous ouvrir ?",
"yourNanobot": "Votre nanobot",
"serviceAccount": "Exécuté sous {{user}}. Les permissions sudo existantes de ce compte seront utilisées.",
"notFound": "Configuration nanobot introuvable",
"notFoundHint": "Vérifiez que nanobot est installé et actif. Pour Docker ou une installation personnalisée, demandez le chemin et le compte de service à l’administrateur.",
"limitedSearch": "Votre configuration et les services système nanobot ont été vérifiés. Les autres installations peuvent nécessiter un chemin.",
"manualLocation": "Indiquer un autre emplacement",
"keyHint": "Chemin de la clé SSH privée sur cet ordinateur, pas son contenu ni une clé API. La connexion SSH par mot de passe seul n’est pas encore prise en charge.",
"locationHint": "Chemin et compte sur le serveur. Aucune installation ni modification des permissions.",
"sshSettings": "Paramètres de connexion SSH",
"checking": "Connexion et recherche de nanobot…",
"opening": "Ouverture du nanobot existant…",
"openNanobot": "Ouvrir nanobot",
"chooseFile": "Choisir un fichier : {{field}}",
"pickingFile": "Choisissez un fichier dans la fenêtre système…"
},
"searchHosts": "Rechercher un hôte…",
"noMatchingHosts": "Aucun hôte correspondant",
"commandHint": "Saisissez utilisateur@serveur ou choisissez un hôte SSH. Nous utiliserons vos réglages existants, puis chercherons nanobot.",
"commandImported": "Options SSH renseignées. Vous pouvez les vérifier dans les options de connexion.",
"hostPlaceholder": "Host alias or user@server",
"addressHint": "Your existing SSH username, key and port are used automatically.",
"manualAddress": "No matching alias. You can connect with the address above.",
"connectionOptions": "Connection options",
"editDescription": "Save your changes here, then connect when you’re ready.",
"save": "Save changes",
"saving": "Saving…",
"connect": "Connect",
"localShort": "Local",
"disconnectTitle": "Disconnect from {{name}}?",
"disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
@@ -11,19 +102,11 @@
"cancelSwitch": "Cancel switch",
"localEnvironment": "Local · {{name}}",
"sshHosts": "From your SSH config",
"sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
"refreshHosts": "Refresh SSH hosts",
"searchHosts": "Search SSH hosts",
"useHost": "Use {{host}}",
"loadingHosts": "Reading SSH config…",
"noHosts": "No named hosts found. You can enter an SSH address below.",
"noMatchingHosts": "No matching hosts.",
"partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
"otherConfig": "Use another SSH config file",
"configToRead": "SSH config file to read",
"readConfig": "Read hosts",
"discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
"portPlaceholder": "Use SSH config (normally 22)",
"portPlaceholder": "From SSH config",
"loading": "Loading connections…",
"retry": "Retry",
"unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
@@ -39,20 +122,17 @@
"current": "Currently using",
"remote": "Remote",
"returnLocal": "Back to local nanobot",
"add": "Connect to remote nanobot…",
"addTitle": "Connect to remote nanobot",
"addDescription": "Connect to a nanobot that's already running on your server.",
"add": "Add server",
"addTitle": "Connect to a server",
"addDescription": "Connect to an existing nanobot. Chats and settings stay on the server.",
"host": "SSH address",
"name": "Name (optional)",
"namePlaceholder": "Team server",
"keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
"advanced": "Advanced",
"sshPort": "SSH port",
"ssh_config": "SSH config file (optional)",
"identity_file": "Private key path (optional)",
"config_path": "Server's nanobot config path",
"runtime_user": "nanobot service account (optional)",
"saveConnect": "Save & connect",
"connecting": "Connecting…",
"opening": "Opening your server…",
"frameTitle": "nanobot on {{name}}",
@@ -65,6 +145,28 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
"disconnected": "Cette connexion partagée a été fermée. Reconnectez-vous quand vous le souhaitez.",
"instance_changed": "La connexion à ce serveur a changé. La reconnexion rechargera la vue ; les brouillons non envoyés risquent d’être perdus.",
"pair_authorization_rejected": "Le serveur n’accepte plus la clé de cet appareil. L’autorisation a peut-être été révoquée ou a expiré. Relancez l’association depuis la console du serveur.",
"pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",
"pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",
"pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",
"pair_expired": "This pairing request expired. Generate a new command.",
"pair_authorization_expired": "This device authorization expired. Pair the server again.",
"pair_used": "This request was already used. Generate a new one.",
"pair_limit": "Close unused pairing windows and try again.",
"pair_managed": "Pair again to change the server or credentials.",
"ssh_connection_closed": "La connexion SSH a été interrompue. Cela ne confirme pas un problème de clé. Vérifiez le VPN ou le proxy, ou utilisez les paramètres SSH fonctionnant dans votre terminal.",
"ssh_refused": "Le serveur a refusé SSH. Vérifiez le port et le service SSH.",
"ssh_host_not_found": "Impossible de résoudre ce nom. Vérifiez l’adresse ou choisissez un hôte dans votre configuration SSH.",
"ssh_too_many_keys": "SSH a essayé trop de clés. Indiquez la bonne clé avec IdentitiesOnly yes dans la configuration SSH.",
"duplicate_instance": "Ce nanobot est déjà connecté via une autre adresse SSH. Utilisez sa connexion existante dans le sélecteur d’hôte.",
"ssh_agent_refused": "L’agent SSH a refusé d’utiliser la clé. Déverrouillez-la ou autorisez-la dans votre gestionnaire de clés, puis réessayez. Si seul le terminal fonctionne, relancez nanobot depuis ce terminal.",
"ssh_key_permissions": "SSH a refusé les permissions du fichier de clé privée. Limitez son accès à votre compte, puis réessayez.",
"ssh_config_invalid": "OpenSSH n’a pas pu lire ces réglages de connexion. Vérifiez la configuration SSH sélectionnée dans votre terminal.",
"ssh_forwarding_denied": "SSH est connecté, mais le serveur bloque le transfert de ports. Demandez à l’administrateur d’autoriser le transfert vers le port de boucle locale de nanobot.",
"probe_failed": "SSH est connecté, mais la vérification de nanobot a échoué. Vérifiez que ce compte peut exécuter des commandes Python non interactives.",
"invalid_ssh_command": "Utilisez un alias, utilisateur@serveur ou ssh avec -p, -i, -F et -l. Mettez entre guillemets les chemins contenant des espaces. Placez les autres options dans la configuration SSH ; les commandes distantes ne sont pas prises en charge.",
"view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
"view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
"same_instance": "This is the nanobot you are already using. No remote connection is needed.",
@@ -79,10 +181,11 @@
"host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
"host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "Impossible d’ouvrir le sélecteur. Vous pouvez saisir le chemin d’un fichier local.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
@@ -92,7 +195,7 @@
"webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
"remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
"profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
"invalid_profile": "Check the address, port and Advanced fields.",
"invalid_profile": "Check the address, port and Connection options fields.",
"profile_not_found": "This saved server no longer exists. Refresh the list.",
"profile_limit": "You can save up to 20 servers.",
"connection_limit": "Disconnect an existing server before opening another connection.",
+121 -18
View File
@@ -1,5 +1,96 @@
{
"remote": {
"activeForgetWarning": "Semua tab yang memakai koneksi ini akan terputus. Pekerjaan yang belum disimpan dapat hilang.",
"saved": "Tersimpan",
"pair": {
"expiringDevice": "Otorisasi berakhir pada {{date}}.",
"expiredDevice": "Otorisasi telah berakhir. Pasangkan ulang server ini sebelum menyambungkan kembali.",
"introHint": "Jalankan satu perintah di terminal server untuk terhubung.",
"copiedTitle": "Perintah disalin",
"afterCopyHint": "Tempel dan jalankan di terminal server. Setelah memberi izin, buka tautan yang muncul di komputer ini.",
"copyAgain": "Salin lagi",
"otherWays": "Cara lain",
"helpTitle": "Syarat & bantuan",
"validityHint": "Perintah berlaku selama 10 menit. Periksa akses sebelum memberi izin.",
"linkDescription": "Jalankan perintah di server, lalu kembali melalui tautan di terminal.",
"preparing": "Menyiapkan koneksi…",
"linkRunHint": "Tempel perintah di terminal cloud dan izinkan komputer ini. Perintah berlaku selama 10 menit.",
"showCommand": "Lihat perintah",
"checkingLink": "Memeriksa tautan koneksi…",
"returnTitle": "2. Kembali ke nanobot",
"returnHint": "Setelah mengizinkan, buka tautan terminal di komputer ini. Detail koneksi akan diisi otomatis.",
"pasteInstead": "Gunakan kode koneksi",
"confirmLinkDescription": "Lanjutkan hanya jika tautan atau kode berasal dari terminal server tepercaya milik Anda.",
"route": "Rute jaringan…",
"direct": "Koneksi langsung",
"savedRoute": "Rute jaringan tersimpan",
"routeDescription": "Untuk VPN atau rute SSH khusus yang sudah ada.",
"routeHint": "Gunakan rute jaringan koneksi SSH tersimpan ke server yang sama, tanpa menyalin kunci atau kredensialnya.",
"title": "Hubungkan tanpa menyiapkan SSH",
"description": "Jalankan satu perintah di konsol server, lalu tempelkan kode koneksi di sini.",
"steps": {
"run": "Salin perintah pemasangan ke terminal server.",
"paste": "Tempel kode yang diberikan server.",
"connect": "Konfirmasi server dan buka nanobot."
},
"requirements": "Untuk server Linux dengan nanobot terpasang. SSH harus bisa dijangkau; tidak perlu relai atau WebUI publik.",
"useSSH": "Gunakan pengaturan SSH",
"start": "Dapatkan perintah",
"runTitle": "1. Jalankan di server",
"runHint": "Buka terminal konsol cloud, tempel perintah, lalu ikuti petunjuknya. Server juga memerlukan versi nanobot yang mendukung fitur ini.",
"command": "Perintah pemasangan",
"copy": "Salin perintah",
"copied": "Disalin",
"copyFailed": "Gagal menyalin. Pilih dan salin perintah di atas.",
"code": "Kode koneksi",
"codeHint": "Gunakan kode berawalan nbpc1. dari terminal. Kode hanya berlaku untuk permintaan lokal ini.",
"expired": "Permintaan kedaluwarsa. Buat perintah baru. Jika sudah diizinkan di server, gunakan perintah pencabutan yang ditampilkan di sana.",
"restart": "Buat perintah baru",
"review": "Tinjau koneksi",
"confirmTitle": "Buka nanobot ini?",
"confirmDescription": "Lanjutkan hanya dengan kode dari terminal server Anda sendiri yang tepercaya.",
"access": "Komputer ini akan memiliki akses penuh ke obrolan, pengaturan, dan alat aktif nanobot ini.",
"expiry": "Izin perangkat berakhir pada {{date}}. Pengaturan keterbukaan port SSH dan nanobot tidak berubah.",
"security": "Detail dan pencabutan izin",
"fingerprint": "Server SSH harus cocok dengan sidik jari dari konsol server ini:",
"revoke": "Untuk mencabut koneksi baru, jalankan ini di server dan tutup sesi jarak jauh yang terbuka:",
"retryHint": "Pemasangan tersimpan. Coba lagi tanpa menjalankan ulang perintah server. Pemasangan tidak dapat melewati pemblokiran SSH oleh jaringan atau VPN.",
"forgetHint": "Melupakan hanya menghapus koneksi dari daftar, bukan izin server. Untuk mencabutnya, jalankan di server:"
},
"setup": {
"progress": "Pengaturan koneksi",
"server": "Server",
"nanobot": "nanobot",
"signedIn": "SSH terhubung",
"changeServer": "Ubah",
"chooseNanobot": "nanobot mana yang ingin dibuka?",
"yourNanobot": "nanobot Anda",
"serviceAccount": "Berjalan sebagai {{user}}. Menggunakan izin sudo yang sudah ada untuk akun ini.",
"notFound": "Konfigurasi nanobot tidak ditemukan",
"notFoundHint": "Pastikan nanobot terpasang dan berjalan. Untuk Docker atau instalasi khusus, minta jalur konfigurasi dan akun layanan kepada pengelola.",
"limitedSearch": "Konfigurasi Anda dan layanan sistem nanobot telah diperiksa. Instalasi lain mungkin memerlukan jalur.",
"manualLocation": "Tentukan lokasi lain",
"keyHint": "Jalur berkas kunci privat SSH di komputer ini, bukan isinya atau kunci API. Login SSH hanya dengan kata sandi belum didukung.",
"locationHint": "Jalur dan akun pada server. Tidak ada instalasi atau perubahan izin.",
"sshSettings": "Pengaturan login SSH",
"checking": "Masuk dan mencari nanobot…",
"opening": "Membuka nanobot yang ada…",
"openNanobot": "Buka nanobot",
"chooseFile": "Pilih file: {{field}}",
"pickingFile": "Pilih file di dialog sistem…"
},
"searchHosts": "Cari host…",
"noMatchingHosts": "Tidak ada host yang cocok",
"commandHint": "Masukkan pengguna@server atau pilih host SSH. Kami akan masuk dengan pengaturan yang ada, lalu mencari nanobot.",
"commandImported": "Opsi SSH telah diisi. Periksa di Opsi koneksi.",
"hostPlaceholder": "Host alias or user@server",
"addressHint": "Your existing SSH username, key and port are used automatically.",
"manualAddress": "No matching alias. You can connect with the address above.",
"connectionOptions": "Connection options",
"editDescription": "Save your changes here, then connect when you’re ready.",
"save": "Save changes",
"saving": "Saving…",
"connect": "Connect",
"localShort": "Local",
"disconnectTitle": "Disconnect from {{name}}?",
"disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
@@ -11,19 +102,11 @@
"cancelSwitch": "Cancel switch",
"localEnvironment": "Local · {{name}}",
"sshHosts": "From your SSH config",
"sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
"refreshHosts": "Refresh SSH hosts",
"searchHosts": "Search SSH hosts",
"useHost": "Use {{host}}",
"loadingHosts": "Reading SSH config…",
"noHosts": "No named hosts found. You can enter an SSH address below.",
"noMatchingHosts": "No matching hosts.",
"partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
"otherConfig": "Use another SSH config file",
"configToRead": "SSH config file to read",
"readConfig": "Read hosts",
"discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
"portPlaceholder": "Use SSH config (normally 22)",
"portPlaceholder": "From SSH config",
"loading": "Loading connections…",
"retry": "Retry",
"unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
@@ -39,20 +122,17 @@
"current": "Currently using",
"remote": "Remote",
"returnLocal": "Back to local nanobot",
"add": "Connect to remote nanobot…",
"addTitle": "Connect to remote nanobot",
"addDescription": "Connect to a nanobot that's already running on your server.",
"add": "Add server",
"addTitle": "Connect to a server",
"addDescription": "Connect to an existing nanobot. Chats and settings stay on the server.",
"host": "SSH address",
"name": "Name (optional)",
"namePlaceholder": "Team server",
"keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
"advanced": "Advanced",
"sshPort": "SSH port",
"ssh_config": "SSH config file (optional)",
"identity_file": "Private key path (optional)",
"config_path": "Server's nanobot config path",
"runtime_user": "nanobot service account (optional)",
"saveConnect": "Save & connect",
"connecting": "Connecting…",
"opening": "Opening your server…",
"frameTitle": "nanobot on {{name}}",
@@ -65,6 +145,28 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
"disconnected": "Koneksi bersama ini telah ditutup. Sambungkan kembali saat Anda siap.",
"instance_changed": "Koneksi server ini berubah. Menyambungkan kembali akan memuat ulang tampilan; draf yang belum dikirim dapat hilang.",
"pair_authorization_rejected": "Server tidak lagi menerima kunci perangkat ini. Otorisasinya mungkin dicabut atau kedaluwarsa. Pasangkan kembali melalui konsol server.",
"pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",
"pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",
"pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",
"pair_expired": "This pairing request expired. Generate a new command.",
"pair_authorization_expired": "This device authorization expired. Pair the server again.",
"pair_used": "This request was already used. Generate a new one.",
"pair_limit": "Close unused pairing windows and try again.",
"pair_managed": "Pair again to change the server or credentials.",
"ssh_connection_closed": "Koneksi SSH ditutup saat penyiapan. Ini belum membuktikan masalah kunci. Periksa VPN/proksi atau gunakan pengaturan SSH yang berfungsi di terminal.",
"ssh_refused": "Server menolak SSH. Periksa port dan layanan SSH.",
"ssh_host_not_found": "Nama server tidak dapat ditemukan. Periksa alamat atau pilih host dari konfigurasi SSH.",
"ssh_too_many_keys": "SSH mencoba terlalu banyak kunci. Tentukan kunci yang benar dengan IdentitiesOnly yes pada konfigurasi SSH.",
"duplicate_instance": "Nanobot ini sudah terhubung melalui alamat SSH lain. Gunakan koneksi yang ada di menu Ganti host.",
"ssh_agent_refused": "Agen SSH menolak penggunaan kunci. Buka kunci atau setujui di pengelola kunci, lalu coba lagi. Jika hanya terminal yang bisa terhubung, mulai ulang nanobot dari terminal tersebut.",
"ssh_key_permissions": "SSH menolak izin berkas kunci privat. Batasi akses hanya untuk akun Anda, lalu coba lagi.",
"ssh_config_invalid": "OpenSSH tidak dapat membaca pengaturan koneksi ini. Periksa konfigurasi SSH yang dipilih di terminal.",
"ssh_forwarding_denied": "SSH berhasil masuk, tetapi server memblokir penerusan port. Minta administrator mengizinkan penerusan ke port loopback nanobot.",
"probe_failed": "SSH berhasil masuk, tetapi pemeriksaan nanobot tidak dapat dijalankan. Pastikan akun ini dapat menjalankan perintah Python noninteraktif.",
"invalid_ssh_command": "Gunakan alias host, pengguna@server, atau ssh dengan -p, -i, -F, dan -l. Apit jalur yang berisi spasi dengan tanda kutip. Masukkan opsi lain ke konfigurasi SSH; perintah jarak jauh tidak didukung.",
"view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
"view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
"same_instance": "This is the nanobot you are already using. No remote connection is needed.",
@@ -79,10 +181,11 @@
"host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
"host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "Pemilih file tidak dapat dibuka. Tempel jalur file lokal sebagai gantinya.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
@@ -92,7 +195,7 @@
"webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
"remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
"profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
"invalid_profile": "Check the address, port and Advanced fields.",
"invalid_profile": "Check the address, port and Connection options fields.",
"profile_not_found": "This saved server no longer exists. Refresh the list.",
"profile_limit": "You can save up to 20 servers.",
"connection_limit": "Disconnect an existing server before opening another connection.",
+121 -18
View File
@@ -1,5 +1,96 @@
{
"remote": {
"activeForgetWarning": "この接続を使用しているすべてのタブが切断されます。未保存の内容が失われる可能性があります。",
"saved": "保存済み",
"pair": {
"expiringDevice": "認証は {{date}} に期限切れになります。",
"expiredDevice": "認証の期限が切れました。再接続する前にペアリングし直してください。",
"introHint": "サーバーのターミナルでコマンドを実行して接続します。",
"copiedTitle": "コマンドをコピーしました",
"afterCopyHint": "サーバーのターミナルに貼り付けて実行します。承認後、表示されたリンクをこのパソコンで開いてください。",
"copyAgain": "もう一度コピー",
"otherWays": "ほかの接続方法",
"helpTitle": "利用条件とヘルプ",
"validityHint": "コマンドは10分間有効です。承認前にアクセス権限を確認してください。",
"linkDescription": "サーバーでコマンドを実行し、端末のリンクからここに戻ります。",
"preparing": "接続を準備しています…",
"linkRunHint": "クラウド端末にコマンドを貼り付け、このコンピューターを承認してください。有効期限は10分です。",
"showCommand": "コマンドを表示",
"checkingLink": "接続リンクを確認しています…",
"returnTitle": "2. nanobot に戻る",
"returnHint": "承認後、このコンピューターで端末のリンクを開くと、接続情報が自動入力されます。",
"pasteInstead": "代わりに接続コードを使う",
"confirmLinkDescription": "自分の信頼できるサーバー端末から取得したリンクまたはコードであることを確認してください。",
"route": "ネットワーク経路…",
"direct": "直接接続",
"savedRoute": "保存済みのネットワーク経路",
"routeDescription": "VPN や既存の特殊な SSH 経路向けの設定です。",
"routeHint": "同じサーバーへの保存済み SSH 接続の経路だけを利用します。認証鍵や認証情報はコピーしません。",
"title": "SSH の設定なしで接続",
"description": "サーバーのコンソールでコマンドを実行し、接続コードをここに貼り付けます。",
"steps": {
"run": "ペアリングコマンドをサーバーの端末で実行します。",
"paste": "サーバーが返したコードを貼り付けます。",
"connect": "サーバーを確認し、nanobot を開きます。"
},
"requirements": "nanobot をインストールした Linux サーバー向けです。SSH 接続は必要ですが、中継サービスや WebUI の公開は不要です。",
"useSSH": "既存の SSH 設定を使用",
"start": "コマンドを取得",
"runTitle": "1. サーバーで実行",
"runHint": "クラウド管理画面の端末にコマンドを貼り付け、案内に従ってください。サーバーにもこの機能に対応した nanobot が必要です。",
"command": "ペアリングコマンド",
"copy": "コマンドをコピー",
"copied": "コピーしました",
"copyFailed": "コピーできませんでした。上のコマンドを選択してコピーしてください。",
"code": "接続コード",
"codeHint": "端末に表示された nbpc1. で始まるコードを使用します。このローカル要求でのみ有効です。",
"expired": "要求が期限切れです。新しいコマンドを取得してください。サーバーで認可済みなら、端末に表示された取消コマンドを実行してください。",
"restart": "新しいコマンドを取得",
"review": "接続情報を確認",
"confirmTitle": "この nanobot を開きますか?",
"confirmDescription": "ご自身の信頼できるサーバー端末からコピーしたコードでのみ続行してください。",
"access": "このコンピューターは、この nanobot のチャット、設定、有効なツールへ完全にアクセスできます。",
"expiry": "認可の有効期限は {{date}} です。SSH と nanobot の既存のポート公開設定は変更しません。",
"security": "接続の詳細と認可の取消",
"fingerprint": "接続先の SSH サーバーは、サーバー端末のこの指紋と一致する必要があります:",
"revoke": "新規接続の認可を取り消すには、サーバーで次を実行し、開いているリモートセッションも閉じてください:",
"retryHint": "ペアリングは保存済みです。サーバーのコマンドを再実行せずに再試行できます。ネットワークや VPN による SSH の遮断は回避できません。",
"forgetHint": "削除するのはローカル一覧の接続だけで、サーバーの認可は残ります。取消にはサーバーで次を実行してください:"
},
"setup": {
"progress": "接続設定",
"server": "サーバー",
"nanobot": "nanobot",
"signedIn": "SSH 接続済み",
"changeServer": "変更",
"chooseNanobot": "どの nanobot を開きますか?",
"yourNanobot": "あなたの nanobot",
"serviceAccount": "実行アカウントは {{user}} です。このアカウントの既存の sudo 権限を使用します。",
"notFound": "nanobot の設定が見つかりません",
"notFoundHint": "nanobot がインストール済みで稼働中か確認してください。Docker や独自構成の場合は、管理者に設定パスとサービスアカウントを確認してください。",
"limitedSearch": "自分の設定と nanobot システムサービスを確認しました。他の構成ではパスの指定が必要です。",
"manualLocation": "別の場所を指定",
"keyHint": "このコンピューター上の SSH 秘密鍵ファイルのパスです。鍵の内容や API キーではありません。パスワードのみの SSH ログインは未対応です。",
"locationHint": "サーバー上のパスとアカウントです。インストールや権限変更は行いません。",
"sshSettings": "SSH ログイン設定",
"checking": "ログインして nanobot を検索中…",
"opening": "既存の nanobot を開いています…",
"openNanobot": "nanobot を開く",
"chooseFile": "ファイルを選択:{{field}}",
"pickingFile": "システムダイアログでファイルを選択してください…"
},
"searchHosts": "ホストを検索…",
"noMatchingHosts": "一致するホストがありません",
"commandHint": "ユーザー名@サーバーを入力するか SSH ホストを選択してください。既存の設定でログインし、nanobot を探します。",
"commandImported": "SSH 設定を入力しました。「接続オプション」で確認できます。",
"hostPlaceholder": "Host alias or user@server",
"addressHint": "Your existing SSH username, key and port are used automatically.",
"manualAddress": "No matching alias. You can connect with the address above.",
"connectionOptions": "Connection options",
"editDescription": "Save your changes here, then connect when you’re ready.",
"save": "Save changes",
"saving": "Saving…",
"connect": "Connect",
"localShort": "Local",
"disconnectTitle": "Disconnect from {{name}}?",
"disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
@@ -11,19 +102,11 @@
"cancelSwitch": "Cancel switch",
"localEnvironment": "Local · {{name}}",
"sshHosts": "From your SSH config",
"sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
"refreshHosts": "Refresh SSH hosts",
"searchHosts": "Search SSH hosts",
"useHost": "Use {{host}}",
"loadingHosts": "Reading SSH config…",
"noHosts": "No named hosts found. You can enter an SSH address below.",
"noMatchingHosts": "No matching hosts.",
"partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
"otherConfig": "Use another SSH config file",
"configToRead": "SSH config file to read",
"readConfig": "Read hosts",
"discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
"portPlaceholder": "Use SSH config (normally 22)",
"portPlaceholder": "From SSH config",
"loading": "Loading connections…",
"retry": "Retry",
"unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
@@ -39,20 +122,17 @@
"current": "Currently using",
"remote": "Remote",
"returnLocal": "Back to local nanobot",
"add": "Connect to remote nanobot…",
"addTitle": "Connect to remote nanobot",
"addDescription": "Connect to a nanobot that's already running on your server.",
"add": "Add server",
"addTitle": "Connect to a server",
"addDescription": "Connect to an existing nanobot. Chats and settings stay on the server.",
"host": "SSH address",
"name": "Name (optional)",
"namePlaceholder": "Team server",
"keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
"advanced": "Advanced",
"sshPort": "SSH port",
"ssh_config": "SSH config file (optional)",
"identity_file": "Private key path (optional)",
"config_path": "Server's nanobot config path",
"runtime_user": "nanobot service account (optional)",
"saveConnect": "Save & connect",
"connecting": "Connecting…",
"opening": "Opening your server…",
"frameTitle": "nanobot on {{name}}",
@@ -65,6 +145,28 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
"disconnected": "この共有接続は閉じられました。必要なときに再接続できます。",
"instance_changed": "このサーバーへの接続が変わりました。再接続すると画面が再読み込みされ、未送信の下書きが失われる場合があります。",
"pair_authorization_rejected": "サーバーがこのデバイスの鍵を受け付けなくなりました。認可が取り消されたか期限切れの可能性があります。サーバーのコンソールから再度ペアリングしてください。",
"pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",
"pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",
"pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",
"pair_expired": "This pairing request expired. Generate a new command.",
"pair_authorization_expired": "This device authorization expired. Pair the server again.",
"pair_used": "This request was already used. Generate a new one.",
"pair_limit": "Close unused pairing windows and try again.",
"pair_managed": "Pair again to change the server or credentials.",
"ssh_connection_closed": "接続の確立中に SSH が切断されました。鍵の問題とは限りません。VPN・プロキシを確認するか、端末で接続できる SSH 設定を使用してください。",
"ssh_refused": "サーバーが SSH 接続を拒否しました。ポートと SSH サービスを確認してください。",
"ssh_host_not_found": "サーバー名を解決できません。アドレスを確認するか、SSH 設定からホストを選んでください。",
"ssh_too_many_keys": "SSH が試した鍵が多すぎます。SSH 設定で正しい鍵と IdentitiesOnly yes を指定してください。",
"duplicate_instance": "この nanobot は別の SSH アドレスで接続済みです。ホスト切り替えから既存の接続を選んでください。",
"ssh_agent_refused": "SSH エージェントが鍵の使用を拒否しました。鍵管理アプリで解除・承認して再試行してください。ターミナルでのみ接続できる場合は、そのターミナルから nanobot を再起動してください。",
"ssh_key_permissions": "SSH が秘密鍵ファイルの権限を拒否しました。自分のアカウントだけがアクセスできるようにして再試行してください。",
"ssh_config_invalid": "OpenSSH が接続設定を読み取れませんでした。選択した SSH 設定をターミナルで確認してください。",
"ssh_forwarding_denied": "SSH ログインは成功しましたが、サーバーがポート転送を拒否しました。nanobot のループバックポートへの転送を管理者に許可してもらってください。",
"probe_failed": "SSH ログインは成功しましたが、nanobot の確認を実行できませんでした。このアカウントで非対話型の Python コマンドを実行できるか確認してください。",
"invalid_ssh_command": "ホスト別名、ユーザー@サーバー、または -p、-i、-F、-l を含む ssh コマンドを入力してください。空白を含むパスは引用符で囲んでください。他のオプションは SSH 設定に記述し、リモートコマンドは含めないでください。",
"view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
"view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
"same_instance": "This is the nanobot you are already using. No remote connection is needed.",
@@ -79,10 +181,11 @@
"host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
"host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "ファイル選択画面を開けませんでした。ローカルファイルのパスを入力してください。",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
@@ -92,7 +195,7 @@
"webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
"remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
"profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
"invalid_profile": "Check the address, port and Advanced fields.",
"invalid_profile": "Check the address, port and Connection options fields.",
"profile_not_found": "This saved server no longer exists. Refresh the list.",
"profile_limit": "You can save up to 20 servers.",
"connection_limit": "Disconnect an existing server before opening another connection.",
+121 -18
View File
@@ -1,5 +1,96 @@
{
"remote": {
"activeForgetWarning": "이 연결을 사용하는 모든 탭의 연결이 끊어집니다. 저장하지 않은 내용이 손실될 수 있습니다.",
"saved": "저장됨",
"pair": {
"expiringDevice": "인증이 {{date}}에 만료됩니다.",
"expiredDevice": "인증이 만료되었습니다. 다시 연결하기 전에 서버를 다시 페어링하세요.",
"introHint": "서버 터미널에서 명령어를 실행해 연결하세요.",
"copiedTitle": "명령어 복사 완료",
"afterCopyHint": "서버 터미널에 붙여넣어 실행하세요. 승인 후 표시된 링크를 이 컴퓨터에서 여세요.",
"copyAgain": "다시 복사",
"otherWays": "다른 연결 방법",
"helpTitle": "사용 조건 및 도움말",
"validityHint": "명령어는 10분 동안 유효합니다. 승인 전에 접근 권한을 확인하세요.",
"linkDescription": "서버에서 명령을 실행한 후 터미널의 링크로 돌아오세요.",
"preparing": "연결 준비 중…",
"linkRunHint": "클라우드 터미널에 명령을 붙여넣고 이 컴퓨터를 승인하세요. 명령은 10분간 유효합니다.",
"showCommand": "명령 보기",
"checkingLink": "연결 링크 확인 중…",
"returnTitle": "2. nanobot으로 돌아가기",
"returnHint": "승인 후 이 컴퓨터에서 터미널의 링크를 열면 연결 정보가 자동으로 입력됩니다.",
"pasteInstead": "대신 연결 코드 사용",
"confirmLinkDescription": "본인의 신뢰할 수 있는 서버 터미널에서 받은 링크나 코드인지 확인하세요.",
"route": "네트워크 경로…",
"direct": "직접 연결",
"savedRoute": "저장된 네트워크 경로",
"routeDescription": "VPN 또는 기존의 특수 SSH 경로 설정입니다.",
"routeHint": "같은 서버의 저장된 SSH 연결에서 네트워크 경로만 재사용합니다. 로그인 키나 자격 증명은 복사하지 않습니다.",
"title": "SSH 설정 없이 연결",
"description": "서버 콘솔에서 명령 하나를 실행한 뒤 연결 코드를 여기에 붙여넣으세요.",
"steps": {
"run": "페어링 명령을 서버 터미널에 복사해 실행하세요.",
"paste": "서버가 생성한 코드를 붙여넣으세요.",
"connect": "서버를 확인하고 nanobot을 여세요."
},
"requirements": "nanobot이 설치된 Linux 서버용입니다. SSH 연결은 가능해야 하며 중계 서버나 공개 WebUI는 필요하지 않습니다.",
"useSSH": "기존 SSH 설정 사용",
"start": "페어링 명령 받기",
"runTitle": "1. 서버에서 실행",
"runHint": "클라우드 콘솔의 터미널에 명령을 붙여넣고 안내를 따르세요. 서버에도 이 기능을 지원하는 nanobot 버전이 필요합니다.",
"command": "페어링 명령",
"copy": "명령 복사",
"copied": "복사됨",
"copyFailed": "복사하지 못했습니다. 위 명령을 선택해 직접 복사하세요.",
"code": "연결 코드",
"codeHint": "터미널의 nbpc1.로 시작하는 코드를 사용하세요. 이 로컬 페어링 요청에만 유효합니다.",
"expired": "요청이 만료되었습니다. 새 명령을 받으세요. 서버에서 이미 승인했다면 터미널에 표시된 취소 명령을 사용하세요.",
"restart": "새 명령 받기",
"review": "연결 정보 확인",
"confirmTitle": "이 nanobot을 열까요?",
"confirmDescription": "본인의 신뢰할 수 있는 서버 터미널에서 복사한 코드로만 진행하세요.",
"access": "이 컴퓨터는 이 nanobot의 채팅, 설정, 활성화된 도구에 완전히 접근할 수 있습니다.",
"expiry": "기기 승인 만료일은 {{date}}입니다. 기존 SSH 및 nanobot 포트 공개 설정은 변경하지 않습니다.",
"security": "연결 정보 및 승인 취소",
"fingerprint": "SSH 서버는 서버 콘솔의 다음 지문과 일치해야 합니다:",
"revoke": "새 연결의 승인을 취소하려면 서버에서 다음 명령을 실행하고 열린 원격 세션도 닫으세요:",
"retryHint": "페어링이 저장되었습니다. 서버 명령을 다시 실행하지 않고 재시도할 수 있습니다. 네트워크나 VPN의 SSH 차단은 우회할 수 없습니다.",
"forgetHint": "잊기는 로컬 목록에서 연결만 제거하며 서버 승인은 남습니다. 취소하려면 서버에서 실행하세요:"
},
"setup": {
"progress": "연결 설정",
"server": "서버",
"nanobot": "nanobot",
"signedIn": "SSH 연결됨",
"changeServer": "변경",
"chooseNanobot": "어떤 nanobot을 열까요?",
"yourNanobot": "내 nanobot",
"serviceAccount": "{{user}} 계정으로 실행됩니다. 이 계정의 기존 sudo 권한을 사용합니다.",
"notFound": "nanobot 설정을 찾지 못했습니다",
"notFoundHint": "nanobot이 설치되어 실행 중인지 확인하세요. Docker 또는 사용자 지정 설치는 관리자에게 설정 경로와 서비스 계정을 문의하세요.",
"limitedSearch": "내 설정과 nanobot 시스템 서비스를 확인했습니다. 다른 설치는 경로 지정이 필요할 수 있습니다.",
"manualLocation": "다른 위치 지정",
"keyHint": "이 컴퓨터에 있는 SSH 개인 키 파일의 경로입니다. 키 내용이나 API 키가 아닙니다. 비밀번호만 사용하는 SSH 로그인은 아직 지원하지 않습니다.",
"locationHint": "서버의 경로와 계정입니다. 설치하거나 권한을 변경하지 않습니다.",
"sshSettings": "SSH 로그인 설정",
"checking": "로그인하고 nanobot을 찾는 중…",
"opening": "기존 nanobot을 여는 중…",
"openNanobot": "nanobot 열기",
"chooseFile": "파일 선택: {{field}}",
"pickingFile": "시스템 창에서 파일을 선택하세요…"
},
"searchHosts": "호스트 검색…",
"noMatchingHosts": "일치하는 호스트가 없습니다",
"commandHint": "사용자@서버를 입력하거나 SSH 호스트를 선택하세요. 기존 설정으로 로그인한 뒤 nanobot을 찾습니다.",
"commandImported": "SSH 설정을 입력했습니다. 연결 옵션에서 확인할 수 있습니다.",
"hostPlaceholder": "Host alias or user@server",
"addressHint": "Your existing SSH username, key and port are used automatically.",
"manualAddress": "No matching alias. You can connect with the address above.",
"connectionOptions": "Connection options",
"editDescription": "Save your changes here, then connect when you’re ready.",
"save": "Save changes",
"saving": "Saving…",
"connect": "Connect",
"localShort": "Local",
"disconnectTitle": "Disconnect from {{name}}?",
"disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
@@ -11,19 +102,11 @@
"cancelSwitch": "Cancel switch",
"localEnvironment": "Local · {{name}}",
"sshHosts": "From your SSH config",
"sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
"refreshHosts": "Refresh SSH hosts",
"searchHosts": "Search SSH hosts",
"useHost": "Use {{host}}",
"loadingHosts": "Reading SSH config…",
"noHosts": "No named hosts found. You can enter an SSH address below.",
"noMatchingHosts": "No matching hosts.",
"partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
"otherConfig": "Use another SSH config file",
"configToRead": "SSH config file to read",
"readConfig": "Read hosts",
"discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
"portPlaceholder": "Use SSH config (normally 22)",
"portPlaceholder": "From SSH config",
"loading": "Loading connections…",
"retry": "Retry",
"unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
@@ -39,20 +122,17 @@
"current": "Currently using",
"remote": "Remote",
"returnLocal": "Back to local nanobot",
"add": "Connect to remote nanobot…",
"addTitle": "Connect to remote nanobot",
"addDescription": "Connect to a nanobot that's already running on your server.",
"add": "Add server",
"addTitle": "Connect to a server",
"addDescription": "Connect to an existing nanobot. Chats and settings stay on the server.",
"host": "SSH address",
"name": "Name (optional)",
"namePlaceholder": "Team server",
"keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
"advanced": "Advanced",
"sshPort": "SSH port",
"ssh_config": "SSH config file (optional)",
"identity_file": "Private key path (optional)",
"config_path": "Server's nanobot config path",
"runtime_user": "nanobot service account (optional)",
"saveConnect": "Save & connect",
"connecting": "Connecting…",
"opening": "Opening your server…",
"frameTitle": "nanobot on {{name}}",
@@ -65,6 +145,28 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
"disconnected": "공유 연결이 종료되었습니다. 준비되면 다시 연결하세요.",
"instance_changed": "이 서버 연결이 변경되었습니다. 다시 연결하면 화면이 새로고침되어 보내지 않은 초안이 사라질 수 있습니다.",
"pair_authorization_rejected": "서버가 이 기기의 키를 더 이상 허용하지 않습니다. 권한이 취소되었거나 만료되었을 수 있습니다. 서버 콘솔에서 다시 페어링하세요.",
"pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",
"pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",
"pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",
"pair_expired": "This pairing request expired. Generate a new command.",
"pair_authorization_expired": "This device authorization expired. Pair the server again.",
"pair_used": "This request was already used. Generate a new one.",
"pair_limit": "Close unused pairing windows and try again.",
"pair_managed": "Pair again to change the server or credentials.",
"ssh_connection_closed": "설정 중 SSH 연결이 종료되었습니다. 키 문제로 단정할 수 없습니다. VPN·프록시를 확인하거나 터미널에서 작동하는 SSH 설정을 사용하세요.",
"ssh_refused": "서버가 SSH를 거부했습니다. 포트와 SSH 서비스가 실행 중인지 확인하세요.",
"ssh_host_not_found": "서버 이름을 확인할 수 없습니다. 주소를 확인하거나 SSH 설정의 호스트를 선택하세요.",
"ssh_too_many_keys": "SSH가 너무 많은 키를 시도했습니다. SSH 설정에 올바른 키와 IdentitiesOnly yes를 지정하세요.",
"duplicate_instance": "이 nanobot은 다른 SSH 주소로 이미 연결되어 있습니다. 호스트 전환에서 기존 연결을 사용하세요.",
"ssh_agent_refused": "SSH 에이전트가 키 사용을 거부했습니다. 키 관리자에서 잠금을 해제하거나 승인한 후 다시 시도하세요. 터미널에서만 연결된다면 해당 터미널에서 nanobot을 다시 시작하세요.",
"ssh_key_permissions": "SSH가 개인 키 파일 권한을 거부했습니다. 본인 계정만 파일에 접근하도록 제한한 후 다시 시도하세요.",
"ssh_config_invalid": "OpenSSH가 연결 설정을 읽지 못했습니다. 터미널에서 선택한 SSH 설정을 확인하세요.",
"ssh_forwarding_denied": "SSH 로그인은 성공했지만 서버가 포트 전달을 차단했습니다. 관리자에게 nanobot의 루프백 포트 전달을 허용해 달라고 요청하세요.",
"probe_failed": "SSH 로그인은 성공했지만 nanobot 확인을 실행하지 못했습니다. 이 계정에서 비대화형 Python 명령을 실행할 수 있는지 확인하세요.",
"invalid_ssh_command": "호스트 별칭, 사용자@서버 또는 -p, -i, -F, -l 옵션이 있는 ssh 명령을 입력하세요. 공백이 있는 경로는 따옴표로 감싸세요. 다른 옵션은 SSH 설정에 넣으세요. 원격 명령은 지원하지 않습니다.",
"view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
"view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
"same_instance": "This is the nanobot you are already using. No remote connection is needed.",
@@ -79,10 +181,11 @@
"host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
"host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "파일 선택 창을 열 수 없습니다. 로컬 파일 경로를 직접 입력할 수 있습니다.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
@@ -92,7 +195,7 @@
"webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
"remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
"profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
"invalid_profile": "Check the address, port and Advanced fields.",
"invalid_profile": "Check the address, port and Connection options fields.",
"profile_not_found": "This saved server no longer exists. Refresh the list.",
"profile_limit": "You can save up to 20 servers.",
"connection_limit": "Disconnect an existing server before opening another connection.",
+121 -18
View File
@@ -1,5 +1,96 @@
{
"remote": {
"activeForgetWarning": "Todas as abas que usam esta conexão serão desconectadas. O trabalho não salvo pode ser perdido.",
"saved": "Salvo",
"pair": {
"expiringDevice": "A autorização expira em {{date}}.",
"expiredDevice": "A autorização expirou. Pareie este servidor novamente antes de reconectar.",
"introHint": "Execute um comando no terminal do servidor para conectar.",
"copiedTitle": "Comando copiado",
"afterCopyHint": "Cole no terminal do servidor. Após autorizar, abra o link exibido neste computador.",
"copyAgain": "Copiar novamente",
"otherWays": "Outras formas",
"helpTitle": "Requisitos e ajuda",
"validityHint": "Os comandos expiram em 10 minutos. Revise as permissões antes de autorizar.",
"linkDescription": "Execute um comando no servidor e volte pelo link do terminal.",
"preparing": "Preparando a conexão…",
"linkRunHint": "Cole o comando no terminal da nuvem e autorize este computador. Ele é válido por 10 minutos.",
"showCommand": "Ver comando",
"checkingLink": "Verificando o link…",
"returnTitle": "2. Voltar ao nanobot",
"returnHint": "Após autorizar, abra o link do terminal neste computador. Os dados da conexão serão preenchidos automaticamente.",
"pasteInstead": "Usar um código de conexão",
"confirmLinkDescription": "Continue apenas se o link ou código veio do terminal do seu próprio servidor confiável.",
"route": "Rota de rede…",
"direct": "Conexão direta",
"savedRoute": "Rota de rede salva",
"routeDescription": "Para uma VPN ou rota SSH especial existente.",
"routeHint": "Reutilize a rota de rede de uma conexão SSH salva com o mesmo servidor, sem copiar suas chaves ou credenciais.",
"title": "Conectar sem configurar SSH",
"description": "Execute um comando no console do servidor e cole o código de conexão aqui.",
"steps": {
"run": "Copie o comando de pareamento para o terminal do servidor.",
"paste": "Cole o código fornecido pelo servidor.",
"connect": "Confirme o servidor e abra o nanobot."
},
"requirements": "Para servidores Linux com nanobot instalado. O SSH deve estar acessível; não é necessário um intermediário nem uma WebUI pública.",
"useSSH": "Usar configurações SSH",
"start": "Obter comando",
"runTitle": "1. Executar no servidor",
"runHint": "Abra o terminal do console de nuvem, cole o comando e siga as instruções. O servidor também precisa desta versão do nanobot.",
"command": "Comando de pareamento",
"copy": "Copiar comando",
"copied": "Copiado",
"copyFailed": "Não foi possível copiar. Selecione e copie o comando acima.",
"code": "Código de conexão",
"codeHint": "Use o código que começa com nbpc1. Ele só funciona com esta solicitação local.",
"expired": "A solicitação expirou. Gere um novo comando. Se já a autorizou no servidor, use o comando de revogação exibido lá.",
"restart": "Gerar novo comando",
"review": "Revisar conexão",
"confirmTitle": "Abrir este nanobot?",
"confirmDescription": "Continue apenas com um código copiado do seu próprio terminal de servidor confiável.",
"access": "Este computador terá acesso completo às conversas, configurações e ferramentas habilitadas deste nanobot.",
"expiry": "A autorização expira em {{date}}. A exposição configurada das portas SSH e nanobot não muda.",
"security": "Detalhes e revogação",
"fingerprint": "O servidor SSH deve corresponder a esta impressão digital do console:",
"revoke": "Para revogar novas conexões, execute isto no servidor e feche as sessões remotas abertas:",
"retryHint": "O pareamento foi salvo. Tente novamente sem executar o comando outra vez. Ele não contorna bloqueios de SSH pela rede ou VPN.",
"forgetHint": "Esquecer remove a conexão da lista, não a autorização do servidor. Para revogar, execute no servidor:"
},
"setup": {
"progress": "Configuração da conexão",
"server": "Servidor",
"nanobot": "nanobot",
"signedIn": "SSH conectado",
"changeServer": "Alterar",
"chooseNanobot": "Qual nanobot deseja abrir?",
"yourNanobot": "Seu nanobot",
"serviceAccount": "Executado como {{user}}. Serão usadas as permissões sudo existentes dessa conta.",
"notFound": "Configuração do nanobot não encontrada",
"notFoundHint": "Verifique se o nanobot está instalado e em execução. Para Docker ou instalações personalizadas, peça ao administrador o caminho e a conta do serviço.",
"limitedSearch": "Sua configuração e os serviços nanobot do sistema foram verificados. Outras instalações podem exigir um caminho.",
"manualLocation": "Especificar outro local",
"keyHint": "Caminho da chave SSH privada neste computador, não seu conteúdo nem uma chave de API. Login SSH apenas com senha ainda não é suportado.",
"locationHint": "Caminho e conta no servidor. Nada será instalado e nenhuma permissão será alterada.",
"sshSettings": "Configurações de login SSH",
"checking": "Entrando e procurando nanobot…",
"opening": "Abrindo o nanobot existente…",
"openNanobot": "Abrir nanobot",
"chooseFile": "Escolher arquivo: {{field}}",
"pickingFile": "Escolha um arquivo na janela do sistema…"
},
"searchHosts": "Buscar hosts…",
"noMatchingHosts": "Nenhum host encontrado",
"commandHint": "Digite usuário@servidor ou escolha um host SSH. Entraremos com suas configurações existentes e procuraremos nanobot.",
"commandImported": "Opções SSH preenchidas. Você pode revisá-las nas opções de conexão.",
"hostPlaceholder": "Host alias or user@server",
"addressHint": "Your existing SSH username, key and port are used automatically.",
"manualAddress": "No matching alias. You can connect with the address above.",
"connectionOptions": "Connection options",
"editDescription": "Save your changes here, then connect when you’re ready.",
"save": "Save changes",
"saving": "Saving…",
"connect": "Connect",
"localShort": "Local",
"disconnectTitle": "Disconnect from {{name}}?",
"disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
@@ -11,19 +102,11 @@
"cancelSwitch": "Cancel switch",
"localEnvironment": "Local · {{name}}",
"sshHosts": "From your SSH config",
"sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
"refreshHosts": "Refresh SSH hosts",
"searchHosts": "Search SSH hosts",
"useHost": "Use {{host}}",
"loadingHosts": "Reading SSH config…",
"noHosts": "No named hosts found. You can enter an SSH address below.",
"noMatchingHosts": "No matching hosts.",
"partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
"otherConfig": "Use another SSH config file",
"configToRead": "SSH config file to read",
"readConfig": "Read hosts",
"discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
"portPlaceholder": "Use SSH config (normally 22)",
"portPlaceholder": "From SSH config",
"loading": "Loading connections…",
"retry": "Retry",
"unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
@@ -39,20 +122,17 @@
"current": "Currently using",
"remote": "Remote",
"returnLocal": "Back to local nanobot",
"add": "Connect to remote nanobot…",
"addTitle": "Connect to remote nanobot",
"addDescription": "Connect to a nanobot that's already running on your server.",
"add": "Add server",
"addTitle": "Connect to a server",
"addDescription": "Connect to an existing nanobot. Chats and settings stay on the server.",
"host": "SSH address",
"name": "Name (optional)",
"namePlaceholder": "Team server",
"keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
"advanced": "Advanced",
"sshPort": "SSH port",
"ssh_config": "SSH config file (optional)",
"identity_file": "Private key path (optional)",
"config_path": "Server's nanobot config path",
"runtime_user": "nanobot service account (optional)",
"saveConnect": "Save & connect",
"connecting": "Connecting…",
"opening": "Opening your server…",
"frameTitle": "nanobot on {{name}}",
@@ -65,6 +145,28 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
"disconnected": "Esta conexão compartilhada foi fechada. Reconecte quando quiser.",
"instance_changed": "A conexão com este servidor mudou. A reconexão recarregará a tela; rascunhos não enviados poderão ser perdidos.",
"pair_authorization_rejected": "O servidor não aceita mais a chave deste dispositivo. A autorização pode ter sido revogada ou expirado. Faça o pareamento novamente no console do servidor.",
"pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",
"pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",
"pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",
"pair_expired": "This pairing request expired. Generate a new command.",
"pair_authorization_expired": "This device authorization expired. Pair the server again.",
"pair_used": "This request was already used. Generate a new one.",
"pair_limit": "Close unused pairing windows and try again.",
"pair_managed": "Pair again to change the server or credentials.",
"ssh_connection_closed": "A conexão SSH foi encerrada durante a configuração. Isso não confirma um problema de chave. Verifique a VPN/proxy ou use os ajustes SSH que funcionam no terminal.",
"ssh_refused": "O servidor recusou SSH. Verifique a porta e se o serviço SSH está ativo.",
"ssh_host_not_found": "Não foi possível resolver o nome. Verifique o endereço ou escolha um host da configuração SSH.",
"ssh_too_many_keys": "SSH tentou chaves demais. Especifique a chave correta com IdentitiesOnly yes na configuração SSH.",
"duplicate_instance": "Este nanobot já está conectado por outro endereço SSH. Use a conexão existente em Alternar host.",
"ssh_agent_refused": "O agente SSH recusou o uso da chave. Desbloqueie ou autorize a chave no gerenciador e tente novamente. Se funcionar apenas no terminal, reinicie o nanobot por esse terminal.",
"ssh_key_permissions": "O SSH rejeitou as permissões do arquivo de chave privada. Restrinja o acesso à sua conta e tente novamente.",
"ssh_config_invalid": "O OpenSSH não conseguiu ler as configurações de conexão. Verifique a configuração SSH selecionada no terminal.",
"ssh_forwarding_denied": "O SSH conectou, mas o servidor bloqueou o encaminhamento de portas. Peça ao administrador que permita o encaminhamento para a porta de loopback do nanobot.",
"probe_failed": "O SSH conectou, mas não conseguiu verificar o nanobot. Confirme se esta conta pode executar comandos Python não interativos.",
"invalid_ssh_command": "Use um alias, usuário@servidor ou ssh com -p, -i, -F e -l. Coloque caminhos com espaços entre aspas. Adicione outras opções à configuração SSH; comandos remotos não são compatíveis.",
"view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
"view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
"same_instance": "This is the nanobot you are already using. No remote connection is needed.",
@@ -79,10 +181,11 @@
"host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
"host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "Não foi possível abrir o seletor. Você pode colar o caminho de um arquivo local.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
@@ -92,7 +195,7 @@
"webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
"remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
"profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
"invalid_profile": "Check the address, port and Advanced fields.",
"invalid_profile": "Check the address, port and Connection options fields.",
"profile_not_found": "This saved server no longer exists. Refresh the list.",
"profile_limit": "You can save up to 20 servers.",
"connection_limit": "Disconnect an existing server before opening another connection.",
+121 -18
View File
@@ -1,5 +1,96 @@
{
"remote": {
"activeForgetWarning": "Tất cả thẻ đang dùng kết nối này sẽ bị ngắt. Nội dung chưa lưu có thể bị mất.",
"saved": "Đã lưu",
"pair": {
"expiringDevice": "Quyền truy cập hết hạn vào {{date}}.",
"expiredDevice": "Quyền truy cập đã hết hạn. Hãy ghép nối lại máy chủ trước khi kết nối lại.",
"introHint": "Chạy một lệnh trong terminal máy chủ để kết nối.",
"copiedTitle": "Đã sao chép lệnh",
"afterCopyHint": "Dán và chạy trong terminal máy chủ. Sau khi cấp quyền, mở liên kết được trả về trên máy tính này.",
"copyAgain": "Sao chép lại",
"otherWays": "Cách khác",
"helpTitle": "Yêu cầu và trợ giúp",
"validityHint": "Lệnh hết hạn sau 10 phút. Kiểm tra quyền truy cập trước khi cấp quyền.",
"linkDescription": "Chạy lệnh trên máy chủ, rồi quay lại bằng liên kết trong terminal.",
"preparing": "Đang chuẩn bị kết nối…",
"linkRunHint": "Dán lệnh vào terminal đám mây và cấp quyền cho máy tính này. Lệnh có hiệu lực trong 10 phút.",
"showCommand": "Xem lệnh",
"checkingLink": "Đang kiểm tra liên kết…",
"returnTitle": "2. Quay lại nanobot",
"returnHint": "Sau khi cấp quyền, mở liên kết trong terminal trên máy tính này. Thông tin kết nối sẽ được điền tự động.",
"pasteInstead": "Dùng mã kết nối",
"confirmLinkDescription": "Chỉ tiếp tục nếu liên kết hoặc mã đến từ terminal máy chủ đáng tin cậy của chính bạn.",
"route": "Đường truyền mạng…",
"direct": "Kết nối trực tiếp",
"savedRoute": "Đường truyền đã lưu",
"routeDescription": "Dành cho VPN hoặc tuyến SSH đặc biệt đã có.",
"routeHint": "Dùng lại đường truyền của kết nối SSH đã lưu tới cùng máy chủ, không sao chép khóa hay thông tin đăng nhập.",
"title": "Kết nối không cần cấu hình SSH",
"description": "Chạy một lệnh trong bảng điều khiển máy chủ, rồi dán mã kết nối vào đây.",
"steps": {
"run": "Sao chép lệnh ghép nối vào terminal máy chủ.",
"paste": "Dán mã do máy chủ cung cấp.",
"connect": "Xác nhận máy chủ và mở nanobot."
},
"requirements": "Dành cho máy chủ Linux đã cài nanobot. SSH vẫn phải truy cập được; không cần máy chủ trung gian hay WebUI công khai.",
"useSSH": "Dùng cấu hình SSH có sẵn",
"start": "Lấy lệnh ghép nối",
"runTitle": "1. Chạy trên máy chủ",
"runHint": "Mở terminal của bảng điều khiển đám mây, dán lệnh và làm theo hướng dẫn. Máy chủ cũng cần phiên bản nanobot hỗ trợ tính năng này.",
"command": "Lệnh ghép nối",
"copy": "Sao chép lệnh",
"copied": "Đã sao chép",
"copyFailed": "Không thể sao chép. Hãy chọn và sao chép lệnh ở trên.",
"code": "Mã kết nối",
"codeHint": "Dùng mã bắt đầu bằng nbpc1. trong terminal. Mã chỉ dùng được với yêu cầu cục bộ này.",
"expired": "Yêu cầu đã hết hạn. Hãy tạo lệnh mới. Nếu đã cấp quyền trên máy chủ, hãy dùng lệnh thu hồi được hiển thị ở đó.",
"restart": "Lấy lệnh mới",
"review": "Kiểm tra kết nối",
"confirmTitle": "Mở nanobot này?",
"confirmDescription": "Chỉ tiếp tục với mã được sao chép từ terminal máy chủ đáng tin cậy của chính bạn.",
"access": "Máy tính này sẽ có toàn quyền truy cập trò chuyện, cài đặt và công cụ đã bật của nanobot này.",
"expiry": "Quyền thiết bị hết hạn vào {{date}}. Phạm vi mở cổng SSH và nanobot hiện có không thay đổi.",
"security": "Chi tiết và thu hồi quyền",
"fingerprint": "Máy chủ SSH phải khớp với dấu vân tay từ bảng điều khiển này:",
"revoke": "Để thu hồi kết nối mới, chạy lệnh này trên máy chủ và đóng các phiên từ xa đang mở:",
"retryHint": "Đã lưu ghép nối. Bạn có thể thử lại mà không chạy lại lệnh trên máy chủ. Ghép nối không vượt qua việc chặn SSH của mạng hoặc VPN.",
"forgetHint": "Quên chỉ xóa kết nối khỏi danh sách, không thu hồi quyền trên máy chủ. Để thu hồi, chạy trên máy chủ:"
},
"setup": {
"progress": "Thiết lập kết nối",
"server": "Máy chủ",
"nanobot": "nanobot",
"signedIn": "Đã kết nối SSH",
"changeServer": "Đổi",
"chooseNanobot": "Bạn muốn mở nanobot nào?",
"yourNanobot": "nanobot của bạn",
"serviceAccount": "Chạy bằng tài khoản {{user}}. Sử dụng quyền sudo hiện có của tài khoản này.",
"notFound": "Không tìm thấy cấu hình nanobot",
"notFoundHint": "Kiểm tra nanobot đã được cài và đang chạy. Với Docker hoặc cài đặt tùy chỉnh, hãy hỏi người triển khai về đường dẫn và tài khoản dịch vụ.",
"limitedSearch": "Đã kiểm tra cấu hình của bạn và các dịch vụ hệ thống nanobot. Cài đặt khác có thể cần chỉ định đường dẫn.",
"manualLocation": "Chỉ định vị trí khác",
"keyHint": "Đường dẫn tệp khóa SSH riêng trên máy này, không phải nội dung khóa hay khóa API. Chưa hỗ trợ đăng nhập SSH chỉ bằng mật khẩu.",
"locationHint": "Đường dẫn và tài khoản trên máy chủ. Không cài đặt hay thay đổi quyền.",
"sshSettings": "Thiết lập đăng nhập SSH",
"checking": "Đang đăng nhập và tìm nanobot…",
"opening": "Đang mở nanobot hiện có…",
"openNanobot": "Mở nanobot",
"chooseFile": "Chọn tệp: {{field}}",
"pickingFile": "Chọn tệp trong hộp thoại hệ thống…"
},
"searchHosts": "Tìm máy chủ…",
"noMatchingHosts": "Không có máy chủ phù hợp",
"commandHint": "Nhập người_dùng@máy_chủ hoặc chọn máy SSH. Chúng tôi sẽ dùng thiết lập hiện có để đăng nhập, rồi tìm nanobot.",
"commandImported": "Đã điền các tùy chọn SSH. Bạn có thể xem lại trong Tùy chọn kết nối.",
"hostPlaceholder": "Host alias or user@server",
"addressHint": "Your existing SSH username, key and port are used automatically.",
"manualAddress": "No matching alias. You can connect with the address above.",
"connectionOptions": "Connection options",
"editDescription": "Save your changes here, then connect when you’re ready.",
"save": "Save changes",
"saving": "Saving…",
"connect": "Connect",
"localShort": "Local",
"disconnectTitle": "Disconnect from {{name}}?",
"disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
@@ -11,19 +102,11 @@
"cancelSwitch": "Cancel switch",
"localEnvironment": "Local · {{name}}",
"sshHosts": "From your SSH config",
"sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
"refreshHosts": "Refresh SSH hosts",
"searchHosts": "Search SSH hosts",
"useHost": "Use {{host}}",
"loadingHosts": "Reading SSH config…",
"noHosts": "No named hosts found. You can enter an SSH address below.",
"noMatchingHosts": "No matching hosts.",
"partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
"otherConfig": "Use another SSH config file",
"configToRead": "SSH config file to read",
"readConfig": "Read hosts",
"discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
"portPlaceholder": "Use SSH config (normally 22)",
"portPlaceholder": "From SSH config",
"loading": "Loading connections…",
"retry": "Retry",
"unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
@@ -39,20 +122,17 @@
"current": "Currently using",
"remote": "Remote",
"returnLocal": "Back to local nanobot",
"add": "Connect to remote nanobot…",
"addTitle": "Connect to remote nanobot",
"addDescription": "Connect to a nanobot that's already running on your server.",
"add": "Add server",
"addTitle": "Connect to a server",
"addDescription": "Connect to an existing nanobot. Chats and settings stay on the server.",
"host": "SSH address",
"name": "Name (optional)",
"namePlaceholder": "Team server",
"keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
"advanced": "Advanced",
"sshPort": "SSH port",
"ssh_config": "SSH config file (optional)",
"identity_file": "Private key path (optional)",
"config_path": "Server's nanobot config path",
"runtime_user": "nanobot service account (optional)",
"saveConnect": "Save & connect",
"connecting": "Connecting…",
"opening": "Opening your server…",
"frameTitle": "nanobot on {{name}}",
@@ -65,6 +145,28 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
"disconnected": "Kết nối dùng chung này đã đóng. Bạn có thể kết nối lại khi sẵn sàng.",
"instance_changed": "Kết nối đến máy chủ này đã thay đổi. Kết nối lại sẽ tải lại giao diện; bản nháp chưa gửi có thể bị mất.",
"pair_authorization_rejected": "Máy chủ không còn chấp nhận khóa của thiết bị này. Quyền truy cập có thể đã bị thu hồi hoặc hết hạn. Hãy ghép nối lại từ bảng điều khiển máy chủ.",
"pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",
"pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",
"pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",
"pair_expired": "This pairing request expired. Generate a new command.",
"pair_authorization_expired": "This device authorization expired. Pair the server again.",
"pair_used": "This request was already used. Generate a new one.",
"pair_limit": "Close unused pairing windows and try again.",
"pair_managed": "Pair again to change the server or credentials.",
"ssh_connection_closed": "Kết nối SSH đóng trong khi thiết lập. Chưa thể kết luận là lỗi khóa. Kiểm tra VPN/proxy hoặc dùng thiết lập SSH hoạt động trong terminal.",
"ssh_refused": "Máy chủ từ chối SSH. Kiểm tra cổng và dịch vụ SSH.",
"ssh_host_not_found": "Không phân giải được tên máy chủ. Kiểm tra địa chỉ hoặc chọn máy từ cấu hình SSH.",
"ssh_too_many_keys": "SSH thử quá nhiều khóa. Chỉ định khóa đúng và IdentitiesOnly yes trong cấu hình SSH.",
"duplicate_instance": "Nanobot này đã được kết nối qua một địa chỉ SSH khác. Hãy dùng kết nối hiện có trong menu Chuyển máy chủ.",
"ssh_agent_refused": "SSH agent từ chối sử dụng khóa. Hãy mở khóa hoặc chấp thuận trong trình quản lý khóa rồi thử lại. Nếu chỉ kết nối được từ terminal, hãy khởi động lại nanobot từ terminal đó.",
"ssh_key_permissions": "SSH từ chối quyền của tệp khóa riêng. Hãy giới hạn quyền truy cập cho tài khoản của bạn rồi thử lại.",
"ssh_config_invalid": "OpenSSH không đọc được thiết lập kết nối. Hãy kiểm tra cấu hình SSH đã chọn trong terminal.",
"ssh_forwarding_denied": "Đã đăng nhập SSH nhưng máy chủ chặn chuyển tiếp cổng. Hãy nhờ quản trị viên cho phép chuyển tiếp đến cổng loopback của nanobot.",
"probe_failed": "Đã đăng nhập SSH nhưng không chạy được bước kiểm tra nanobot. Hãy xác nhận tài khoản này chạy được lệnh Python không tương tác.",
"invalid_ssh_command": "Dùng bí danh, người_dùng@máy_chủ hoặc ssh với -p, -i, -F và -l. Đặt đường dẫn có dấu cách trong dấu nháy. Các tùy chọn khác cần đặt trong cấu hình SSH; không hỗ trợ lệnh từ xa.",
"view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
"view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
"same_instance": "This is the nanobot you are already using. No remote connection is needed.",
@@ -79,10 +181,11 @@
"host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
"host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "Không thể mở hộp thoại chọn tệp. Bạn có thể dán đường dẫn tệp cục bộ.",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
@@ -92,7 +195,7 @@
"webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
"remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
"profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
"invalid_profile": "Check the address, port and Advanced fields.",
"invalid_profile": "Check the address, port and Connection options fields.",
"profile_not_found": "This saved server no longer exists. Refresh the list.",
"profile_limit": "You can save up to 20 servers.",
"connection_limit": "Disconnect an existing server before opening another connection.",
+121 -18
View File
@@ -1,5 +1,96 @@
{
"remote": {
"activeForgetWarning": "也会断开正在使用此连接的标签页,未保存的内容可能丢失。",
"saved": "已保存",
"pair": {
"expiringDevice": "授权将于 {{date}} 到期。",
"expiredDevice": "授权已到期,重新连接前请再次配对。",
"introHint": "在服务器终端运行一条命令,即可开始连接。",
"copiedTitle": "命令已复制",
"afterCopyHint": "去服务器终端粘贴运行。确认授权后,点击返回链接回到这里。",
"copyAgain": "再次复制",
"otherWays": "其他连接方式",
"helpTitle": "使用条件与帮助",
"validityHint": "命令 10 分钟内有效。授权前,请确认访问权限。",
"linkDescription": "在服务器运行命令,再点击终端里的链接回到这里。",
"preparing": "正在准备连接…",
"linkRunHint": "将命令粘贴到云服务器终端,按提示授权这台电脑。命令有效期为 10 分钟。",
"showCommand": "查看命令",
"checkingLink": "正在核对连接链接…",
"returnTitle": "2. 返回 nanobot",
"returnHint": "授权后,在这台电脑上打开终端给出的链接,连接信息会自动填好。",
"pasteInstead": "改用连接码",
"confirmLinkDescription": "请确认链接或连接码来自你自己的可信服务器终端。",
"route": "网络连接方式…",
"direct": "直接连接",
"savedRoute": "已保存的网络路径",
"routeDescription": "适用于 VPN 或已有特殊 SSH 网络路径。",
"routeHint": "可以借用同一服务器已有 SSH 连接的网络路径。不会复制其登录密钥或凭据。",
"title": "无需配置 SSH,连接服务器",
"description": "在云服务器终端运行一条命令,再把连接码贴回来。",
"steps": {
"run": "把配对命令复制到服务器终端运行。",
"paste": "贴回服务器生成的连接码。",
"connect": "确认服务器,打开 nanobot。"
},
"requirements": "适用于已安装 nanobot 的 Linux 服务器。仍需 SSH 网络可达;不需要中继,也不用公开 WebUI。",
"useSSH": "使用已有 SSH 配置",
"start": "获取配对命令",
"runTitle": "1. 在服务器上运行",
"runHint": "打开云控制台的终端,粘贴命令并按提示操作。服务器也需要安装支持此功能的 nanobot 版本。",
"command": "配对命令",
"copy": "复制命令",
"copied": "已复制",
"copyFailed": "复制失败,请选中上面的命令手动复制。",
"code": "连接码",
"codeHint": "粘贴终端里以 nbpc1. 开头的连接码,只能用于本次本地配对。",
"expired": "配对请求已过期,请重新生成命令。如果已在服务器授权,请用终端显示的撤销命令清理旧授权。",
"restart": "重新获取命令",
"review": "确认连接信息",
"confirmTitle": "打开这个 nanobot?",
"confirmDescription": "请确认连接码来自你自己的可信服务器终端。",
"access": "这台电脑将能访问此 nanobot 的聊天、设置,以及已启用的工具。",
"expiry": "设备授权有效期至 {{date}}。不会更改服务器现有的 SSH 和 nanobot 端口开放范围。",
"security": "连接详情与撤销授权",
"fingerprint": "连接时会核对服务器终端提供的 SSH 指纹:",
"revoke": "如需撤销新连接,在服务器运行以下命令,并关闭已打开的远程会话:",
"retryHint": "配对已保存,无需重复运行服务器命令。若网络或 VPN 阻断 SSH,配对无法绕过该限制。",
"forgetHint": "忘记连接只会从本地列表移除,不会撤销服务器授权。撤销设备请在服务器运行:"
},
"setup": {
"progress": "连接设置",
"server": "服务器",
"nanobot": "nanobot",
"signedIn": "SSH 已连接",
"changeServer": "更改",
"chooseNanobot": "打开哪一个 nanobot?",
"yourNanobot": "你的 nanobot",
"serviceAccount": "运行账户为 {{user}}。打开时将使用已有的 sudo 权限。",
"notFound": "没有找到 nanobot 配置",
"notFoundHint": "请确认服务器已安装并运行 nanobot。Docker 或自定义部署需要向部署者获取配置路径和服务账户。",
"limitedSearch": "已检查你的配置和 nanobot 系统服务。其他部署方式可能需要在下方指定路径。",
"manualLocation": "指定其他位置",
"keyHint": "填写这台电脑上的 SSH 私钥文件路径,不是密钥内容或模型 API Key。暂不支持仅用 SSH 密码登录。",
"locationHint": "这里填写服务器上的路径和账户。不会安装程序或修改权限。",
"sshSettings": "SSH 登录设置",
"checking": "正在登录并寻找 nanobot…",
"opening": "正在打开已有的 nanobot…",
"openNanobot": "打开 nanobot",
"chooseFile": "选择文件:{{field}}",
"pickingFile": "请在系统窗口中选择文件…"
},
"searchHosts": "搜索主机…",
"noMatchingHosts": "没有匹配的主机",
"commandHint": "填写 用户名@服务器,或选择已有 SSH 主机。我们会先登录服务器,再寻找 nanobot。",
"commandImported": "已填入 SSH 设置,可在「连接选项」中查看。",
"hostPlaceholder": "主机别名或 用户名@服务器",
"addressHint": "自动沿用已有 SSH 配置中的用户名、密钥和端口。",
"manualAddress": "没有匹配的别名,也可以直接连接上面输入的地址。",
"connectionOptions": "连接选项",
"editDescription": "保存连接设置,不会立即切换到服务器。",
"save": "保存修改",
"saving": "正在保存…",
"connect": "连接",
"localShort": "本地",
"disconnectTitle": "断开与 {{name}} 的连接?",
"disconnectDescription": "将关闭此服务器页面及共享的 SSH 连接,可能丢失未保存的内容,并影响其他正在使用此连接的标签页。服务器上的 nanobot 会继续运行。",
@@ -11,19 +102,11 @@
"cancelSwitch": "取消切换",
"localEnvironment": "本地 · {{name}}",
"sshHosts": "来自 SSH 配置",
"sshHostsHint": "选择已有主机,用户名、密钥和端口会沿用 SSH 配置。点击连接前不会访问服务器。",
"refreshHosts": "刷新 SSH 主机",
"searchHosts": "搜索 SSH 主机",
"useHost": "使用 {{host}}",
"loadingHosts": "正在读取 SSH 配置…",
"noHosts": "没有找到已命名的主机,也可以在下面手动输入 SSH 地址。",
"noMatchingHosts": "没有匹配的主机。",
"partialHosts": "部分配置未能列出,你仍可手动输入主机别名或地址。",
"otherConfig": "使用其他 SSH 配置文件",
"configToRead": "要读取的 SSH 配置文件",
"readConfig": "读取主机",
"discoveryError": "无法读取 SSH 主机,请重试或手动输入地址。",
"portPlaceholder": "沿用 SSH 配置(通常为 22)",
"portPlaceholder": "沿用 SSH 配置",
"loading": "正在读取连接…",
"retry": "重试",
"unavailable": "请从本地运行的 nanobot 打开此页面,才能通过 SSH 连接服务器。",
@@ -39,20 +122,17 @@
"current": "正在使用",
"remote": "远程",
"returnLocal": "切回本地 nanobot",
"add": "连接远程 nanobot…",
"addTitle": "连接远程 nanobot",
"addDescription": "连接服务器上已经运行的 nanobot。",
"add": "添加服务器",
"addTitle": "连接服务器",
"addDescription": "连接已运行的 nanobot,聊天和设置留在服务器。",
"host": "SSH 地址",
"name": "名称(可选)",
"namePlaceholder": "团队服务器",
"keyHint": "使用系统 SSH 密钥。模型 Key 和会话留在服务器上。",
"advanced": "高级",
"sshPort": "SSH 端口",
"ssh_config": "SSH 配置文件(可选)",
"identity_file": "私钥路径(可选)",
"config_path": "服务器上的 nanobot 配置路径",
"runtime_user": "nanobot 运行账号(可选)",
"saveConnect": "保存并连接",
"connecting": "正在连接…",
"opening": "正在打开服务器…",
"frameTitle": "{{name}} 上的 nanobot",
@@ -65,6 +145,28 @@
"forgetTitle": "忘记 {{name}}?",
"forgetDescription": "只移除本机保存的连接。服务器上的 nanobot、密钥和会话都不会被删除。",
"errors": {
"disconnected": "此共享连接已断开,需要时可重新连接。",
"instance_changed": "此服务器的连接已发生变化。重新连接会重新打开页面,未发送的草稿可能丢失。",
"pair_authorization_rejected": "服务器不再接受这台设备的密钥,授权可能已撤销或过期。请从服务器终端重新配对。",
"pair_route_mismatch": "请选择指向同一台服务器的 SSH 连接。",
"pair_route_unsupported": "此连接使用了跳板机,请使用原有 SSH 连接入口。",
"pair_invalid": "连接码无效,或不属于本次配对,请从服务器终端重新复制。",
"pair_expired": "配对请求已过期,请重新获取命令。",
"pair_authorization_expired": "设备授权已过期,请重新配对。",
"pair_used": "此请求已使用,请重新获取命令。",
"pair_limit": "请关闭其他配对窗口后重试。",
"pair_managed": "更换服务器或凭据请重新配对。",
"ssh_connection_closed": "SSH 连接在建立过程中断开,还不能判断是密钥问题。请检查 VPN/代理,或使用终端中能登录的 SSH 配置。",
"ssh_refused": "服务器拒绝了 SSH 连接。请检查 SSH 端口及服务是否运行。",
"ssh_host_not_found": "无法解析服务器名称。请检查地址,或从 SSH 配置中选择主机。",
"ssh_too_many_keys": "SSH 尝试了过多密钥。请在 SSH 配置中指定正确密钥,并设置 IdentitiesOnly yes。",
"duplicate_instance": "这个 nanobot 已通过另一个 SSH 地址连接,请在「切换主机」中使用已有连接。",
"ssh_agent_refused": "SSH 密钥代理未同意使用密钥。请在密钥管理器中解锁或确认后重试。如果只有终端能连接,请从那个终端重新启动 nanobot。",
"ssh_key_permissions": "SSH 拒绝使用权限过宽的私钥文件。请将文件访问权限限制为你的账号后重试。",
"ssh_config_invalid": "OpenSSH 无法读取这些连接设置,请在终端检查所选 SSH 配置。",
"ssh_forwarding_denied": "SSH 已登录,但服务器禁止端口转发。请让管理员允许转发到 nanobot 的回环端口。",
"probe_failed": "SSH 已登录,但未能运行 nanobot 检查。请确认该账号能执行非交互式 Python 命令。",
"invalid_ssh_command": "可输入主机别名、用户名@服务器,或含 -p、-i、-F、-l 的 ssh 命令。含空格的路径请加引号;其他选项请写入 SSH 配置,不支持附带远程命令。",
"view_limit": "已保留 3 个服务器界面。请在管理连接中断开其中一个,再打开新服务器。",
"view_load_failed": "服务器界面加载较慢,请重试。当前界面保持不变。",
"same_instance": "这是你当前正在使用的 nanobot,无需再次连接。",
@@ -79,10 +181,11 @@
"host_key_unknown": "本机还没有验证过这台服务器。请先与服务器管理员核对 SSH 指纹后再连接。",
"host_key_changed": "服务器的 SSH 身份发生了变化,已阻止连接。请先与管理员确认,不要跳过这个警告。",
"local_file_not_found": "本机找不到指定的 SSH 配置文件或私钥。",
"file_picker_unavailable": "无法打开文件选择窗口,也可以直接填写本机文件路径。",
"runtime_user_denied": "SSH 已登录,但不能免密切换到这个运行账号,请与服务器管理员确认。",
"python_unavailable": "服务器需要 python3 来读取已有的 nanobot 配置。",
"config_not_found": "找不到 nanobot 配置,请在「高级」中填写它在服务器上的路径。",
"config_permission": "SSH 账号无权读取 nanobot 配置,请在「高级」中填写 nanobot 的运行账号。",
"config_not_found": "找不到 nanobot 配置,请在「连接选项」中填写它在服务器上的路径。",
"config_permission": "SSH 账号无权读取 nanobot 配置,请在「连接选项」中填写 nanobot 的运行账号。",
"config_invalid": "无法读取服务器上的 nanobot 配置。",
"webui_disabled": "服务器的 WebUI 尚未启用,请先在服务器上开启。",
"webui_auth_required": "服务器需要在配置中设置 WebUI 登录密钥。这里不需要模型 Key。",
@@ -92,7 +195,7 @@
"webui_unavailable": "Gateway 在运行,但没有安装 WebUI。",
"remote_unreachable": "SSH 已连接,但 nanobot WebUI 没有响应,请确认它正在运行。",
"profile_store_invalid": "无法读取已保存的连接,原文件未被覆盖。",
"invalid_profile": "请检查服务器地址、端口和高级选项。",
"invalid_profile": "请检查服务器地址、端口和连接选项。",
"profile_not_found": "这个连接已不存在,请刷新列表。",
"profile_limit": "最多可以保存 20 台服务器。",
"connection_limit": "请先断开一台服务器,再建立新连接。",
+121 -18
View File
@@ -1,5 +1,96 @@
{
"remote": {
"activeForgetWarning": "也會中斷正在使用此連線的分頁,未儲存的內容可能遺失。",
"saved": "已儲存",
"pair": {
"expiringDevice": "授權將於 {{date}} 到期。",
"expiredDevice": "授權已到期,重新連線前請再次配對。",
"introHint": "在伺服器終端執行一條指令,即可開始連線。",
"copiedTitle": "指令已複製",
"afterCopyHint": "到伺服器終端貼上執行。確認授權後,點擊返回連結回到這裡。",
"copyAgain": "再次複製",
"otherWays": "其他連線方式",
"helpTitle": "使用條件與說明",
"validityHint": "指令 10 分鐘內有效。授權前,請確認存取權限。",
"linkDescription": "在伺服器執行命令,再點擊終端裡的連結回到這裡。",
"preparing": "正在準備連線…",
"linkRunHint": "將命令貼到雲端伺服器終端,依提示授權這台電腦。命令有效期為 10 分鐘。",
"showCommand": "檢視命令",
"checkingLink": "正在核對連線連結…",
"returnTitle": "2. 返回 nanobot",
"returnHint": "授權後,在這台電腦上開啟終端提供的連結,連線資訊會自動填入。",
"pasteInstead": "改用連線碼",
"confirmLinkDescription": "請確認連結或連線碼來自你自己的可信伺服器終端。",
"route": "網路連線方式…",
"direct": "直接連線",
"savedRoute": "已儲存的網路路徑",
"routeDescription": "適用於 VPN 或既有的特殊 SSH 網路路徑。",
"routeHint": "可沿用同一伺服器既有 SSH 連線的網路路徑,不會複製登入金鑰或憑證。",
"title": "無需設定 SSH,連線伺服器",
"description": "在雲端伺服器終端執行一條指令,再把連線碼貼回來。",
"steps": {
"run": "複製配對指令,在伺服器終端執行。",
"paste": "貼回伺服器產生的連線碼。",
"connect": "確認伺服器並開啟 nanobot。"
},
"requirements": "適用於已安裝 nanobot 的 Linux 伺服器。仍需能透過 SSH 連線;不需要中繼,也不用公開 WebUI。",
"useSSH": "使用既有 SSH 設定",
"start": "取得配對指令",
"runTitle": "1. 在伺服器上執行",
"runHint": "開啟雲端控制台終端,貼上指令並依提示操作。伺服器也需要支援此功能的 nanobot 版本。",
"command": "配對指令",
"copy": "複製指令",
"copied": "已複製",
"copyFailed": "複製失敗,請選取上方指令手動複製。",
"code": "連線碼",
"codeHint": "貼上終端中以 nbpc1. 開頭的連線碼,只能用於本次本機配對。",
"expired": "配對請求已過期,請重新產生指令。若已在伺服器授權,請使用終端顯示的撤銷指令清除舊授權。",
"restart": "重新取得指令",
"review": "確認連線資訊",
"confirmTitle": "開啟這個 nanobot?",
"confirmDescription": "請確認連線碼來自你自己的可信伺服器終端。",
"access": "這台電腦將能存取此 nanobot 的聊天、設定與已啟用工具。",
"expiry": "裝置授權有效至 {{date}}。不會變更伺服器現有的 SSH 和 nanobot 連接埠開放範圍。",
"security": "連線詳情與撤銷授權",
"fingerprint": "連線時會核對伺服器終端提供的 SSH 指紋:",
"revoke": "若要撤銷新連線,請在伺服器執行以下指令,並關閉已開啟的遠端工作階段:",
"retryHint": "配對已儲存,無需重複執行伺服器指令。若網路或 VPN 阻擋 SSH,配對無法繞過該限制。",
"forgetHint": "忘記連線只會移除本機列表項目,不會撤銷伺服器授權。撤銷裝置請在伺服器執行:"
},
"setup": {
"progress": "連線設定",
"server": "伺服器",
"nanobot": "nanobot",
"signedIn": "SSH 已連線",
"changeServer": "變更",
"chooseNanobot": "開啟哪一個 nanobot?",
"yourNanobot": "你的 nanobot",
"serviceAccount": "執行帳戶為 {{user}}。開啟時將使用既有的 sudo 權限。",
"notFound": "找不到 nanobot 設定",
"notFoundHint": "請確認伺服器已安裝並執行 nanobot。Docker 或自訂部署需要向部署者取得設定路徑和服務帳戶。",
"limitedSearch": "已檢查你的設定和 nanobot 系統服務。其他部署方式可能需要在下方指定路徑。",
"manualLocation": "指定其他位置",
"keyHint": "填寫這台電腦上的 SSH 私密金鑰檔案路徑,不是金鑰內容或模型 API Key。暫不支援僅用 SSH 密碼登入。",
"locationHint": "這裡填寫伺服器上的路徑和帳戶。不會安裝程式或修改權限。",
"sshSettings": "SSH 登入設定",
"checking": "正在登入並尋找 nanobot…",
"opening": "正在開啟既有的 nanobot…",
"openNanobot": "開啟 nanobot",
"chooseFile": "選擇檔案:{{field}}",
"pickingFile": "請在系統視窗中選擇檔案…"
},
"searchHosts": "搜尋主機…",
"noMatchingHosts": "沒有符合的主機",
"commandHint": "填寫 使用者名稱@伺服器,或選擇既有 SSH 主機。我們會先登入伺服器,再尋找 nanobot。",
"commandImported": "已填入 SSH 設定,可在「連線選項」中查看。",
"hostPlaceholder": "主機別名或 使用者名稱@伺服器",
"addressHint": "自動沿用既有 SSH 設定中的使用者名稱、金鑰和連接埠。",
"manualAddress": "沒有符合的別名,也可以直接連線到上方輸入的位址。",
"connectionOptions": "連線選項",
"editDescription": "儲存連線設定,不會立即切換到伺服器。",
"save": "儲存變更",
"saving": "正在儲存…",
"connect": "連線",
"localShort": "本地",
"disconnectTitle": "中斷與 {{name}} 的連線?",
"disconnectDescription": "將關閉此伺服器頁面及共用的 SSH 連線,可能遺失未儲存的內容,並影響其他正在使用此連線的分頁。伺服器上的 nanobot 會繼續執行。",
@@ -11,19 +102,11 @@
"cancelSwitch": "取消切换",
"localEnvironment": "Local · {{name}}",
"sshHosts": "From your SSH config",
"sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
"refreshHosts": "Refresh SSH hosts",
"searchHosts": "Search SSH hosts",
"useHost": "Use {{host}}",
"loadingHosts": "Reading SSH config…",
"noHosts": "No named hosts found. You can enter an SSH address below.",
"noMatchingHosts": "No matching hosts.",
"partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
"otherConfig": "Use another SSH config file",
"configToRead": "SSH config file to read",
"readConfig": "Read hosts",
"discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
"portPlaceholder": "Use SSH config (normally 22)",
"portPlaceholder": "沿用 SSH 設定",
"loading": "正在讀取連線…",
"retry": "重試",
"unavailable": "請從本機執行的 nanobot 開啟此頁面,才能透過 SSH 連線伺服器。",
@@ -39,20 +122,17 @@
"current": "Currently using",
"remote": "Remote",
"returnLocal": "Back to local nanobot",
"add": "Connect to remote nanobot…",
"addTitle": "Connect to remote nanobot",
"addDescription": "Connect to a nanobot that's already running on your server.",
"add": "新增伺服器",
"addTitle": "連線伺服器",
"addDescription": "連線至已執行的 nanobot,聊天和設定留在伺服器。",
"host": "SSH address",
"name": "Name (optional)",
"namePlaceholder": "Team server",
"keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
"advanced": "Advanced",
"sshPort": "SSH port",
"ssh_config": "SSH config file (optional)",
"identity_file": "Private key path (optional)",
"config_path": "Server's nanobot config path",
"runtime_user": "nanobot service account (optional)",
"saveConnect": "Save & connect",
"connecting": "Connecting…",
"opening": "Opening your server…",
"frameTitle": "nanobot on {{name}}",
@@ -65,6 +145,28 @@
"forgetTitle": "Forget {{name}}?",
"forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
"errors": {
"disconnected": "此共用連線已中斷,需要時可重新連線。",
"instance_changed": "此伺服器的連線已發生變化。重新連線會重新開啟頁面,未傳送的草稿可能遺失。",
"pair_authorization_rejected": "伺服器不再接受這台裝置的金鑰,授權可能已撤銷或過期。請從伺服器終端重新配對。",
"pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",
"pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",
"pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",
"pair_expired": "This pairing request expired. Generate a new command.",
"pair_authorization_expired": "This device authorization expired. Pair the server again.",
"pair_used": "This request was already used. Generate a new one.",
"pair_limit": "Close unused pairing windows and try again.",
"pair_managed": "Pair again to change the server or credentials.",
"ssh_connection_closed": "SSH 連線在建立過程中中斷,尚無法判斷是否為金鑰問題。請檢查 VPN/代理,或使用終端機中能登入的 SSH 設定。",
"ssh_refused": "伺服器拒絕了 SSH 連線。請檢查 SSH 連接埠及服務是否執行。",
"ssh_host_not_found": "無法解析伺服器名稱。請檢查位址,或從 SSH 設定中選擇主機。",
"ssh_too_many_keys": "SSH 嘗試了過多金鑰。請在 SSH 設定中指定正確金鑰,並設定 IdentitiesOnly yes。",
"duplicate_instance": "這個 nanobot 已透過另一個 SSH 位址連線,請在「切換主機」中使用現有連線。",
"ssh_agent_refused": "SSH 金鑰代理未同意使用金鑰。請在金鑰管理器中解鎖或確認後重試。如果只有終端機能連線,請從該終端機重新啟動 nanobot。",
"ssh_key_permissions": "SSH 拒絕使用權限過寬的私鑰檔案。請將檔案存取權限限制為你的帳號後重試。",
"ssh_config_invalid": "OpenSSH 無法讀取這些連線設定,請在終端機檢查所選 SSH 設定。",
"ssh_forwarding_denied": "SSH 已登入,但伺服器禁止連接埠轉送。請讓管理員允許轉送至 nanobot 的回環連接埠。",
"probe_failed": "SSH 已登入,但未能執行 nanobot 檢查。請確認該帳號能執行非互動式 Python 指令。",
"invalid_ssh_command": "可輸入主機別名、使用者@伺服器,或含 -p、-i、-F、-l 的 ssh 指令。含空格的路徑請加引號;其他選項請寫入 SSH 設定,不支援附帶遠端指令。",
"view_limit": "已保留 3 个服务器界面。请在管理连接中断开其中一个,再打开新服务器。",
"view_load_failed": "服务器界面加载较慢,请重试。当前界面保持不变。",
"same_instance": "This is the nanobot you are already using. No remote connection is needed.",
@@ -79,10 +181,11 @@
"host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
"host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
"local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
"file_picker_unavailable": "無法開啟檔案選擇視窗,也可以直接填寫本機檔案路徑。",
"runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
"python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
"config_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",
"config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.",
"config_invalid": "Couldn't read the server's nanobot configuration.",
"webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
"webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
@@ -92,7 +195,7 @@
"webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
"remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
"profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
"invalid_profile": "Check the address, port and Advanced fields.",
"invalid_profile": "Check the address, port and Connection options fields.",
"profile_not_found": "This saved server no longer exists. Refresh the list.",
"profile_limit": "You can save up to 20 servers.",
"connection_limit": "Disconnect an existing server before opening another connection.",
+42 -1
View File
@@ -11,6 +11,17 @@ export interface RemoteProfile {
config_path: string;
runtime_user: string;
connected: boolean;
gateway_id?: string;
view_id?: string;
connection_error?: string;
paired?: boolean;
revoke_command?: string;
authorized_until?: number;
}
/** Persistent setup problems need a repair path, not an endless Retry button. */
export function needsRemoteSetup(code: string): boolean {
return /^(pair_|host_key_|ssh_auth_failed$|ssh_agent_refused$|ssh_key_permissions$|ssh_config_|local_file_not_found$|remote_auth_failed$|incompatible_gateway$|webui_disabled$|profile_not_found$)/.test(code);
}
export interface RemoteDirectory {
@@ -32,9 +43,22 @@ export interface RemoteConnection {
hostname: string;
config_path: string;
gateway_id: string;
view_id?: string;
url: string;
}
export interface RemoteLocation {
config_path: string;
runtime_user: string;
service: string;
}
export interface RemoteInspection {
hostname: string;
candidates: RemoteLocation[];
incomplete: boolean;
}
export async function readRemoteInstances(token: string): Promise<RemoteDirectory> {
const response = await fetchWithTimeout("/api/remote-instances", {
headers: { Authorization: `Bearer ${token}` },
@@ -47,7 +71,7 @@ export async function readRemoteInstances(token: string): Promise<RemoteDirector
export function remoteAction<T>(
client: WebUIMutationTransport, action: string, payload: Record<string, unknown>,
): Promise<T> {
return client.requestMutation<T>(`remote.${action}`, payload, 65_000);
return client.requestMutation<T>(`remote.${action}`, payload, action === "pick_file" ? 310_000 : 65_000);
}
/** Never let a server response navigate the shell to an arbitrary origin. */
@@ -62,6 +86,23 @@ export function validateRemoteConnection(connection: RemoteConnection): RemoteCo
export type SelectedRemote = Pick<RemoteConnection, "id" | "name" | "hostname">;
const SELECTED_REMOTE = "nanobot.remote-instance";
const RECENT_REMOTES = "nanobot.recent-remote-instances";
/** Only profile IDs are persisted, never connection URLs or credentials. */
export function readRecentRemotes(): string[] {
try {
const value: unknown = JSON.parse(window.localStorage.getItem(RECENT_REMOTES) || "[]");
return Array.isArray(value) ? [...new Set(value.filter((id): id is string =>
typeof id === "string" && /^[a-f0-9-]{36}$/.test(id)))].slice(0, 20) : [];
} catch { return []; }
}
export function rememberRecentRemote(id: string, previous: string[]): string[] {
const next = [id, ...previous.filter((item) => item !== id)].slice(0, 20);
try { window.localStorage.setItem(RECENT_REMOTES, JSON.stringify(next)); }
catch { /* Switching still works when browser storage is disabled. */ }
return next;
}
export function readSelectedRemote(): SelectedRemote | null {
try {
+51
View File
@@ -0,0 +1,51 @@
/** One-shot handoff from a trusted server console, held in memory, never storage. */
export interface PairReturn { id: string; code: string }
let pending: PairReturn | null = null;
const listeners = new Set<() => void>();
export function parsePairReturn(hash: string): PairReturn | null {
const [path, query = ""] = hash.split("?", 2);
if (path !== "#/remote") return null;
const params = new URLSearchParams(query);
if (!params.has("pairing")) return null;
const invalid = { id: "", code: "" };
const code = params.get("pairing") || "";
if (params.getAll("pairing").length !== 1 || code.length > 32768 || !/^nbpc1\.[A-Za-z0-9_-]+$/.test(code)) return invalid;
try {
const encoded = code.slice(6).replace(/-/g, "+").replace(/_/g, "/");
const envelope: unknown = JSON.parse(atob(encoded.padEnd(Math.ceil(encoded.length / 4) * 4, "=")));
if (!envelope || typeof envelope !== "object" || !("id" in envelope)
|| typeof envelope.id !== "string" || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(envelope.id)) return invalid;
// The backend must decrypt and validate this. A parsed ID grants no access.
return { id: envelope.id, code };
} catch { return invalid; }
}
export function initializePairReturn(): void {
const returned = parsePairReturn(window.location.hash);
if (!returned) return;
window.history.replaceState(null, "", `${window.location.pathname}${window.location.search}#/remote`);
// A remote iframe must never become a local connection controller.
if (window.top === window && window.location.protocol === "http:"
&& ["127.0.0.1", "localhost", "[::1]"].includes(window.location.hostname)) {
pending = returned;
listeners.forEach((listener) => listener());
}
}
export function readPairReturn(): PairReturn | null { return pending; }
export function subscribePairReturn(listener: () => void): () => void {
listeners.add(listener);
return () => { listeners.delete(listener); };
}
export function clearPairReturn(): void {
pending = null;
listeners.forEach((listener) => listener());
}
export function pairingReturnOrigin(): string {
return window.top === window && window.location.protocol === "http:"
&& ["127.0.0.1", "localhost", "[::1]"].includes(window.location.hostname)
? window.location.origin : "";
}
+60
View File
@@ -0,0 +1,60 @@
/** Import connection fields, never execute a pasted command or shell syntax. */
export interface SSHAddress {
host: string;
port?: number;
identity_file?: string;
ssh_config?: string;
}
export function parseSSHAddress(input: string): SSHAddress {
const text = input.trim();
const invalid = () => new Error("invalid_ssh_command");
const validHost = (host: string) => /^[a-zA-Z0-9][a-zA-Z0-9._:@-]{0,252}$/.test(host);
if (!/^ssh\s/.test(text)) {
if (!validHost(text)) throw invalid();
return { host: text };
}
// A deliberately small grammar: quoted paths (including Windows paths),
// a destination and -p/-i/-F/-l. No expansions, remote commands or flags
// that change trust, forwarding, or execute a local ProxyCommand.
if (/[;$`|&<>]/.test(text) || [...text].some((char) => char.charCodeAt(0) < 32 && char !== "\t")) throw invalid();
const token = /\s*(?:"([^"]*)"|'([^']*)'|([^\s"']+))(?:\s+|$)/gy;
const words: string[] = [];
while (token.lastIndex < text.length) {
const match = token.exec(text);
if (!match) throw invalid();
words.push(match[1] ?? match[2] ?? match[3]);
}
words.shift(); // ssh
const result: SSHAddress = { host: "" };
const seen = new Set<string>();
let user = "";
for (let index = 0; index < words.length; index++) {
const word = words[index];
if (!word.startsWith("-")) {
if (result.host || !validHost(word)) throw invalid();
result.host = word;
continue;
}
// Options after the destination are a remote command in ssh, not options.
if (result.host) throw invalid();
const flag = word.slice(0, 2);
if (!["-p", "-i", "-F", "-l"].includes(flag) || seen.has(flag)) throw invalid();
seen.add(flag);
const value = word.length > 2 ? word.slice(2) : words[++index];
if (!value || value.startsWith("-") || value.length > 2048) throw invalid();
if (flag === "-p") {
if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 65535) throw invalid();
result.port = Number(value);
} else if (flag === "-i") result.identity_file = value;
else if (flag === "-F") result.ssh_config = value;
else {
if (!/^[a-zA-Z0-9_][a-zA-Z0-9._-]*$/.test(value)) throw invalid();
user = value;
}
}
if (!result.host || (user && result.host.includes("@"))) throw invalid();
if (user) result.host = `${user}@${result.host}`;
if (!validHost(result.host)) throw invalid();
return result;
}
+3
View File
@@ -4,6 +4,7 @@ import App from "./App";
import "./globals.css";
import { initializeI18n } from "./i18n";
import { initializeLoopbackRuntimeHost } from "./lib/runtime";
import { initializePairReturn } from "./lib/remote-pair-return";
// `crypto.randomUUID` is only defined in secure contexts (HTTPS or localhost).
// LAN access over plain HTTP leaves it undefined, which crashes components that
@@ -24,6 +25,8 @@ if (typeof globalThis.crypto !== "undefined" && !("randomUUID" in globalThis.cry
const root = document.getElementById("root");
if (!root) throw new Error("root element missing");
initializePairReturn();
window.addEventListener("hashchange", initializePairReturn);
initializeLoopbackRuntimeHost();
async function renderWebui(container: HTMLElement) {
+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");
});
});