feat(webui): connect to existing remote nanobot instances (NAN-157)
This commit is contained in:
1 parent
6ecb74aea9
commit
11889c018e
34 files changed
+4074
-14
No files matched your search
@@ -9,6 +9,7 @@ import {
|
||||
Brain,
|
||||
CalendarClock,
|
||||
MessageCircle,
|
||||
MonitorUp,
|
||||
PanelLeftClose,
|
||||
Search,
|
||||
Settings,
|
||||
@@ -22,7 +23,8 @@ import {
|
||||
type SidebarDeleteItem,
|
||||
type SidebarPaneGroup,
|
||||
} from "@/components/ChatList";
|
||||
import { ConnectionBadge } from "@/components/ConnectionBadge";
|
||||
import { HostSwitcher } from "@/components/remote/HostSwitcher";
|
||||
import { useRemoteConnections } from "@/components/remote/RemoteInstances";
|
||||
import {
|
||||
SIDEBAR_SELECTION_ACTION_ITEM_CLASS,
|
||||
SidebarSelectionHighlight,
|
||||
@@ -68,9 +70,10 @@ interface SidebarProps {
|
||||
onOpenSkills: () => void;
|
||||
onOpenAutomations: () => void;
|
||||
onOpenChannels: () => void;
|
||||
onOpenRemoteConnections?: () => void;
|
||||
onSettingsIntent?: () => void;
|
||||
onOpenSearch: () => void;
|
||||
activeUtility?: "apps" | "skills" | "automations" | "channels" | null;
|
||||
activeUtility?: "apps" | "skills" | "automations" | "channels" | "remote" | null;
|
||||
onToggleArchived: () => void;
|
||||
onCollapse?: () => void;
|
||||
onExpand?: () => void;
|
||||
@@ -108,6 +111,7 @@ 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);
|
||||
@@ -253,6 +257,16 @@ 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}
|
||||
@@ -332,7 +346,7 @@ export function Sidebar(props: SidebarProps) {
|
||||
className="w-9"
|
||||
icon={<Settings className="h-4 w-4" />}
|
||||
/>
|
||||
<ConnectionBadge />
|
||||
<HostSwitcher collapsed={collapsed} portalContainer={props.containActionMenus ? menuPortalContainer : undefined} />
|
||||
</div>
|
||||
</nav>
|
||||
</TooltipProvider>
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
import { createContext, useContext, useEffect, useRef, useState } from "react";
|
||||
import { Check, ChevronUp, CircleAlert, Laptop, Loader2, Server, Settings2, X } from "lucide-react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { ConnectionBadge } from "@/components/ConnectionBadge";
|
||||
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
|
||||
import { useClient } from "@/providers/ClientProvider";
|
||||
import { cn } from "@/lib/utils";
|
||||
import type { ConnectionStatus } from "@/lib/types";
|
||||
import type { HostAnchor, EmbeddedHost } from "./host-bridge";
|
||||
|
||||
export interface HostPicker {
|
||||
kind: "shell";
|
||||
name: string;
|
||||
hostname: string;
|
||||
localName: string;
|
||||
currentId: string | null;
|
||||
profiles: { id: string; name: string; host: string; ready: boolean }[];
|
||||
pending: { id: string; name: string } | null;
|
||||
error: string;
|
||||
offline: boolean;
|
||||
select: (id: string | null) => void;
|
||||
manage: () => void;
|
||||
cancel: () => void;
|
||||
clearError: () => void;
|
||||
restoreFocus: () => void;
|
||||
}
|
||||
interface EmbeddedPicker extends EmbeddedHost {
|
||||
kind: "embedded";
|
||||
open: (anchor: HostAnchor) => void;
|
||||
}
|
||||
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)]"
|
||||
onCloseAutoFocus={(event) => { event.preventDefault(); picker.restoreFocus(); }}>
|
||||
<DropdownMenuLabel>{t("remote.switchHost")}</DropdownMenuLabel>
|
||||
<DropdownMenuItem onSelect={() => picker.select(null)} className="gap-2.5">
|
||||
<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">
|
||||
<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}
|
||||
</DropdownMenuItem>)}
|
||||
{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>
|
||||
</div>}
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuItem className="gap-2.5" onSelect={picker.manage}><Settings2 className="h-4 w-4 text-muted-foreground" />{t("remote.manageConnections")}</DropdownMenuItem>
|
||||
</DropdownMenuContent>;
|
||||
}
|
||||
|
||||
/** Shared sidebar control. Remote frames can only open the trusted shell's menu. */
|
||||
export function HostSwitcher({ collapsed = false, portalContainer }: { collapsed?: boolean; portalContainer?: HTMLElement | null }) {
|
||||
const picker = useContext(HostNavigationContext);
|
||||
const { client } = useClient();
|
||||
const { t } = useTranslation();
|
||||
const [status, setStatus] = useState<ConnectionStatus>(client.status);
|
||||
useEffect(() => client.onStatus(setStatus), [client]);
|
||||
const buttonRef = useRef<HTMLButtonElement>(null);
|
||||
if (!picker) return <ConnectionBadge />;
|
||||
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";
|
||||
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}`)}`;
|
||||
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")}
|
||||
onClick={picker.kind === "embedded" ? () => {
|
||||
const rect = buttonRef.current?.getBoundingClientRect();
|
||||
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" />
|
||||
: 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>
|
||||
</Button>;
|
||||
if (!shell) return button;
|
||||
return <DropdownMenu><DropdownMenuTrigger asChild>{button}</DropdownMenuTrigger><HostMenuContent picker={shell} portalContainer={portalContainer} /></DropdownMenu>;
|
||||
}
|
||||
|
||||
/** Parent-owned menu anchored to the active remote sidebar, never inside its DOM. */
|
||||
export function RemoteHostMenu({ picker, anchor, onClose }: { picker: HostPicker; anchor: HostAnchor | null; onClose: () => void }) {
|
||||
return <DropdownMenu open={!!anchor} onOpenChange={(open) => { if (!open) onClose(); }}>
|
||||
<DropdownMenuTrigger asChild><button tabIndex={-1} aria-hidden className="pointer-events-none fixed opacity-0" style={anchor ? {
|
||||
left: Math.max(0, Math.min(anchor.left, window.innerWidth - 32)), top: Math.max(0, Math.min(anchor.top, window.innerHeight - 32)),
|
||||
width: Math.min(anchor.width, window.innerWidth), height: Math.min(anchor.height, 64),
|
||||
} : { width: 0, height: 0 }} /></DropdownMenuTrigger>
|
||||
<HostMenuContent picker={picker} />
|
||||
</DropdownMenu>;
|
||||
}
|
||||
@@ -0,0 +1,245 @@
|
||||
import { useEffect, useId, useRef, useState } from "react";
|
||||
import { ArrowLeft, ArrowUpRight, Check, ChevronLeft, Laptop, Loader2, MoreHorizontal, Plus, Server, ShieldCheck } 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 { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
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 { cn } from "@/lib/utils";
|
||||
import { useRemoteConnections } from "./RemoteInstances";
|
||||
import { SSHHostPicker } from "./SSHHostPicker";
|
||||
|
||||
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. */
|
||||
export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChromeInset = false, onBackToChat }: {
|
||||
mainNavigationExpanded?: boolean;
|
||||
hostChromeInset?: boolean;
|
||||
onBackToChat: () => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { client } = useClient();
|
||||
const connections = useRemoteConnections();
|
||||
const [form, setForm] = useState(emptyProfile);
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const [editingId, setEditingId] = useState("");
|
||||
const [busy, setBusy] = useState("");
|
||||
const [error, setError] = useState("");
|
||||
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 mounted = useRef(true);
|
||||
const refresh = connections?.refresh;
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
// Keep cached rows visible while refreshing in the background.
|
||||
void refresh?.().catch(() => {});
|
||||
return () => { mounted.current = false; };
|
||||
}, [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 showError = (reason: unknown) => {
|
||||
if (!mounted.current) return;
|
||||
const code = reason instanceof Error ? reason.message : "unknown";
|
||||
setError(t(`remote.errors.${code}`, { defaultValue: t("remote.errors.unknown") }));
|
||||
};
|
||||
|
||||
const connect = async (id: string) => {
|
||||
setBusy(id); setError("");
|
||||
try {
|
||||
await connectHost(id, () => mounted.current);
|
||||
} catch (reason) {
|
||||
if (!mounted.current) 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("");
|
||||
}
|
||||
};
|
||||
|
||||
const trustHost = async () => {
|
||||
if (!fingerprint) return;
|
||||
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(""); }
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
setEditorOpen(true); setBusy("save"); setError("");
|
||||
try {
|
||||
const result = await remoteAction<{ id: string }>(client, "save", {
|
||||
id: editingId, profile: { ...form, name: form.name.trim() || form.host.trim() },
|
||||
});
|
||||
if (!mounted.current) return;
|
||||
setEditingId(result.id);
|
||||
await refresh?.();
|
||||
if (mounted.current) await connect(result.id);
|
||||
} catch (reason) { showError(reason); }
|
||||
finally { if (mounted.current) setBusy(""); }
|
||||
};
|
||||
|
||||
const remove = async () => {
|
||||
if (!removing) return;
|
||||
setBusy("remove"); setError("");
|
||||
try {
|
||||
await disconnectHost(removing.id);
|
||||
await remoteAction(client, "remove", { id: removing.id });
|
||||
if (mounted.current) setRemoving(null);
|
||||
await refresh?.();
|
||||
} catch (reason) { 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); }
|
||||
finally { if (mounted.current) setBusy(""); }
|
||||
};
|
||||
|
||||
const closeEditor = () => {
|
||||
setEditorOpen(false); setEditingId(""); setForm(emptyProfile()); setError("");
|
||||
};
|
||||
|
||||
return <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-settings-canvas">
|
||||
<div className="min-w-0 flex-1 overflow-y-auto [scrollbar-gutter:stable]">
|
||||
<div data-settings-section="remote" data-main-navigation-expanded={mainNavigationExpanded}
|
||||
className={cn("settings-grid settings-feature-page mx-auto w-full animate-in fade-in-0 slide-in-from-bottom-1 py-6 duration-200 ease-out motion-reduce:animate-none sm:py-8 lg:py-12",
|
||||
hostChromeInset && "pt-[4.25rem] sm:pt-[4.25rem] lg:pt-[4.75rem]")}>
|
||||
<div className="settings-feature-header mb-7">
|
||||
<Button variant="ghost" size="sm" className="touch-target mb-4 gap-1 lg:hidden" onClick={onBackToChat}>
|
||||
<ChevronLeft className="h-4 w-4" />{t("settings.backToChat")}
|
||||
</Button>
|
||||
<h1 className="text-[24px] font-normal leading-tight tracking-normal text-foreground sm:text-[28px]">{t("remote.title")}</h1>
|
||||
</div>
|
||||
<div className="settings-stack">
|
||||
<p className="settings-list-inset text-[13px] leading-6 text-muted-foreground">{t(showForm ? "remote.addDescription" : "remote.description")}</p>
|
||||
{directory?.available && <>
|
||||
<SettingsGroup>
|
||||
<div className="settings-list-row flex items-center gap-3 py-3">
|
||||
<Laptop className="h-[18px] w-[18px] shrink-0 text-muted-foreground" />
|
||||
<span className="min-w-0 flex-1"><span className="block text-[14px] font-medium">{t("remote.local")}</span>
|
||||
{directory.machine_name && <span className="mt-0.5 block truncate text-xs text-muted-foreground">{directory.machine_name}</span>}</span>
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground"><Check className="h-3.5 w-3.5" />{t("remote.current")}</span>
|
||||
</div>
|
||||
</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 && !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>
|
||||
{directoryError && <Button variant="ghost" size="sm" disabled={!!busy} onClick={() => {
|
||||
setBusy("refresh"); setError(""); void refresh?.().catch(showError).finally(() => { if (mounted.current) setBusy(""); });
|
||||
}}>{t("remote.retry")}</Button>}
|
||||
</div>}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<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>
|
||||
</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>
|
||||
</Dialog>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function RemoteField({ label, onChange, ...props }: {
|
||||
label: string; value: string; onChange: (value: string) => void;
|
||||
placeholder?: string; required?: boolean; 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>;
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import { createContext, useContext, useEffect, useLayoutEffect, useRef, 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 { useHostSessions } from "./useHostSessions";
|
||||
import { HostNavigationContext, HostSwitcher, RemoteHostMenu, type HostPicker } from "./HostSwitcher";
|
||||
import { useSidebarHostBridge } from "./useSidebarHostBridge";
|
||||
|
||||
const RemoteContext = createContext<{
|
||||
available: boolean;
|
||||
localActive: boolean;
|
||||
openHostIds: string[];
|
||||
directory: RemoteDirectory | null;
|
||||
directoryError: boolean;
|
||||
refresh: () => Promise<RemoteDirectory>;
|
||||
connect: (id: string, stillWanted?: () => boolean) => Promise<void>;
|
||||
disconnect: (id: string) => Promise<void>;
|
||||
} | null>(null);
|
||||
export function useRemoteConnections() { return useContext(RemoteContext); }
|
||||
|
||||
/** Keep host views alive; navigation belongs in each view's sidebar, not a second header. */
|
||||
export function RemoteInstances({ children }: { children: ReactNode }) {
|
||||
const { t } = useTranslation();
|
||||
const hosts = useHostSessions();
|
||||
const { selected, pending, frames, directory, error } = hosts;
|
||||
const localPanel = useRef<HTMLDivElement>(null);
|
||||
const lastLocalFocus = useRef<HTMLElement | null>(null);
|
||||
const frameNodes = useRef(new Map<string, HTMLIFrameElement>());
|
||||
const activeHostId = useRef(selected?.id);
|
||||
activeHostId.current = selected?.id;
|
||||
const restoreLocalFocus = () => {
|
||||
if (lastLocalFocus.current?.isConnected) lastLocalFocus.current.focus({ preventScroll: true });
|
||||
};
|
||||
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 });
|
||||
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 switchHost = (id: string) => {
|
||||
void hosts.connect(id).catch((reason: unknown) => hosts.setError(reason instanceof Error ? reason.message : "unknown"));
|
||||
};
|
||||
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,
|
||||
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,
|
||||
};
|
||||
useEffect(() => { if (selected) document.title = `${selected.name} · nanobot`; }, [selected]);
|
||||
useEffect(() => {
|
||||
const rememberFocus = (event: FocusEvent) => {
|
||||
if (event.target instanceof HTMLElement && localPanel.current?.contains(event.target)
|
||||
&& !event.target.closest("[data-host-switcher]")) lastLocalFocus.current = event.target;
|
||||
};
|
||||
document.addEventListener("focusin", rememberFocus);
|
||||
return () => document.removeEventListener("focusin", rememberFocus);
|
||||
}, []);
|
||||
useLayoutEffect(() => {
|
||||
if (selected) frameNodes.current.get(selected.id)?.focus({ preventScroll: true });
|
||||
else restoreLocalFocus();
|
||||
}, [selected]);
|
||||
useEffect(() => {
|
||||
if (!selected) return;
|
||||
const stop = (event: KeyboardEvent) => event.stopPropagation();
|
||||
document.addEventListener("keydown", stop);
|
||||
document.addEventListener("keyup", stop);
|
||||
return () => { document.removeEventListener("keydown", stop); document.removeEventListener("keyup", stop); };
|
||||
}, [selected]);
|
||||
|
||||
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 }}>
|
||||
<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">
|
||||
<div ref={localPanel} data-host-view="local" aria-hidden={!!selected} {...(selected ? { inert: "" } : {})}
|
||||
style={{ visibility: selected ? "hidden" : "visible" }}
|
||||
className={`absolute inset-0 transition-opacity duration-150 motion-reduce:transition-none ${selected ? "invisible pointer-events-none opacity-0" : "visible opacity-100"}`}>
|
||||
{children}
|
||||
</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}
|
||||
{...(!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); }}
|
||||
src={frame.connection.url} title={t("remote.frameTitle", { name: frame.connection.name })}
|
||||
className="h-full w-full border-0" referrerPolicy="no-referrer"
|
||||
sandbox="allow-scripts allow-same-origin allow-forms allow-downloads allow-popups allow-popups-to-escape-sandbox"
|
||||
onLoad={() => { bridge.initialize(frame.connection.id); hosts.loaded(frame.connection.id); }} />
|
||||
</div>;
|
||||
})}
|
||||
{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="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>}
|
||||
<Button variant="ghost" onClick={hosts.local}>{t("remote.returnLocal")}</Button>
|
||||
</div>
|
||||
</div>}
|
||||
</div>
|
||||
{/* Older remote bundles cannot host the control. Keep an explicit exit
|
||||
in a compact bottom strip, never cover their sidebar controls. */}
|
||||
{selected && (!bridge.readyIds.includes(selected.id) || offline) && <div data-testid="legacy-host-footer" className="flex shrink-0 items-center border-t border-border/50 bg-sidebar px-2.5 py-1">
|
||||
<div className="flex w-52 min-w-0"><HostSwitcher /></div>
|
||||
</div>}
|
||||
<RemoteHostMenu picker={picker} anchor={bridge.anchor} onClose={bridge.close} />
|
||||
</div>
|
||||
</HostNavigationContext.Provider>
|
||||
</RemoteContext.Provider>;
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { useCallback, useEffect, useRef, useState } from "react";
|
||||
import { ArrowRight, FileText, Loader2, RefreshCw, Search, 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 }: {
|
||||
disabled: boolean;
|
||||
onSelect: (host: SSHDiscovery["hosts"][number]) => void;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const { client } = useClient();
|
||||
const [result, setResult] = useState<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;
|
||||
setBusy(true); setError("");
|
||||
try {
|
||||
const next = await remoteAction<SSHDiscovery>(client, "discover", { ssh_config: file.trim() });
|
||||
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("");
|
||||
}
|
||||
} catch (reason) {
|
||||
if (mounted.current && id === 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);
|
||||
}
|
||||
}, [client, t]);
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
let started = false;
|
||||
const unsubscribe = client.onStatus((status) => {
|
||||
if (status === "open" && !started) { started = true; void load(""); }
|
||||
});
|
||||
return () => { mounted.current = false; requestId.current += 1; unsubscribe(); };
|
||||
}, [client, load]);
|
||||
|
||||
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)} />
|
||||
</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" />
|
||||
</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>;
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
// The embedded UI may ask to open the host menu, never execute SSH actions.
|
||||
// Host lists, paths and credentials remain exclusively in the local shell.
|
||||
export const HOST_BRIDGE = "nanobot.host-navigation.v1";
|
||||
export interface HostAnchor { left: number; top: number; width: number; height: number }
|
||||
export interface EmbeddedHost { name: string; hostname: string; pendingName?: string; error?: string }
|
||||
|
||||
export function isLocalShellOrigin(origin: string): boolean {
|
||||
try {
|
||||
const url = new URL(origin);
|
||||
return url.origin === origin && ["http:", "https:"].includes(url.protocol)
|
||||
&& ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
|
||||
} catch { return false; }
|
||||
}
|
||||
|
||||
export function bridgeMessage(value: unknown): Record<string, unknown> | null {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
||||
const message = value as Record<string, unknown>;
|
||||
return message.channel === HOST_BRIDGE && typeof message.type === "string" ? message : null;
|
||||
}
|
||||
|
||||
export function readEmbeddedHost(message: Record<string, unknown>): EmbeddedHost | null {
|
||||
return typeof message.name === "string" && message.name.length > 0 && message.name.length <= 120
|
||||
&& typeof message.hostname === "string" && message.hostname.length <= 255
|
||||
&& (message.pendingName === undefined || typeof message.pendingName === "string" && message.pendingName.length <= 120)
|
||||
&& (message.error === undefined || typeof message.error === "string" && message.error.length <= 1024)
|
||||
? { name: message.name, hostname: message.hostname, pendingName: message.pendingName as string | undefined, error: message.error as string | undefined } : null;
|
||||
}
|
||||
|
||||
export function readHostAnchor(value: unknown): HostAnchor | null {
|
||||
if (!value || typeof value !== "object") return null;
|
||||
const rect = value as Record<string, unknown>;
|
||||
return ["left", "top", "width", "height"].every((key) => typeof rect[key] === "number"
|
||||
&& Number.isFinite(rect[key]) && Math.abs(rect[key] as number) <= 100_000)
|
||||
&& (rect.width as number) > 0 && (rect.height as number) > 0
|
||||
? { left: rect.left as number, top: rect.top as number, width: rect.width as number, height: rect.height as number } : null;
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
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";
|
||||
|
||||
// Never silently evict a view containing drafts or unfinished attachments.
|
||||
// Tunnels are shared across browser tabs, so only explicit disconnect closes one.
|
||||
export const MAX_HOST_VIEWS = 3;
|
||||
export interface HostFrame {
|
||||
connection: RemoteConnection;
|
||||
loaded: boolean;
|
||||
offline: boolean;
|
||||
failures: number;
|
||||
}
|
||||
interface PendingSwitch { id: string; name: 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 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 mounted = useRef(true);
|
||||
const epoch = useRef(0);
|
||||
const waiter = useRef<{ id: string; finish: (ready: boolean) => void } | null>(null);
|
||||
const publish = useCallback(() => { if (mounted.current) setFrames([...cache.current.values()]); }, []);
|
||||
const setPendingSwitch = useCallback((value: PendingSwitch | null) => {
|
||||
pendingRef.current = value;
|
||||
if (mounted.current) setPending(value);
|
||||
}, []);
|
||||
const cancel = useCallback(() => {
|
||||
epoch.current += 1;
|
||||
waiter.current?.finish(false);
|
||||
waiter.current = null;
|
||||
setPendingSwitch(null);
|
||||
}, [setPendingSwitch]);
|
||||
const select = useCallback((value: SelectedRemote | null) => {
|
||||
selectedRef.current = value;
|
||||
setSelected(value);
|
||||
rememberSelectedRemote(value);
|
||||
setError("");
|
||||
publish();
|
||||
}, [publish]);
|
||||
const local = useCallback(() => { cancel(); select(null); }, [cancel, select]);
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const next = window.top === window ? await readRemoteInstances(getToken()) : { available: false, profiles: [] };
|
||||
if (mounted.current) { setDirectory(next); setDirectoryError(false); }
|
||||
return next;
|
||||
} catch (reason) {
|
||||
if (mounted.current) setDirectoryError(true);
|
||||
throw reason;
|
||||
}
|
||||
}, [getToken]);
|
||||
|
||||
const connect = useCallback(async (id: string, stillWanted: () => boolean = () => true) => {
|
||||
cancel();
|
||||
const attempt = epoch.current;
|
||||
const wanted = () => mounted.current && attempt === epoch.current && stillWanted();
|
||||
const warm = cache.current.get(id);
|
||||
if (warm?.loaded && !warm.offline) {
|
||||
if (wanted()) select(warm.connection);
|
||||
return;
|
||||
}
|
||||
if (!warm && cache.current.size >= MAX_HOST_VIEWS) throw new Error("view_limit");
|
||||
const name = directory?.profiles.find((item) => item.id === id)?.name || initial.current?.name || id;
|
||||
setPendingSwitch({ id, name });
|
||||
setError("");
|
||||
let openingFrame = warm?.loaded ? undefined : warm;
|
||||
try {
|
||||
const connection = validateRemoteConnection(await remoteAction<RemoteConnection>(client, "connect", { id }));
|
||||
if (!wanted()) {
|
||||
// A cancelled SSH request can finish later. Never switch away from the
|
||||
// latest choice or close its tunnel, which another tab may already use.
|
||||
return;
|
||||
}
|
||||
let frame = cache.current.get(id);
|
||||
if (!frame || frame.connection.url !== connection.url || frame.connection.gateway_id !== connection.gateway_id) {
|
||||
frame = { connection, loaded: false, offline: false, failures: 0 };
|
||||
cache.current.set(id, frame);
|
||||
} else {
|
||||
frame.connection = connection;
|
||||
frame.offline = false; frame.failures = 0;
|
||||
}
|
||||
if (!frame.loaded) openingFrame = frame;
|
||||
publish();
|
||||
void refresh().catch(() => {});
|
||||
if (!frame.loaded) {
|
||||
const ready = await new Promise<boolean>((resolve, reject) => {
|
||||
const timer = window.setTimeout(() => {
|
||||
waiter.current = null;
|
||||
reject(new Error("view_load_failed"));
|
||||
}, 25_000);
|
||||
waiter.current = { id, finish: (ready) => { window.clearTimeout(timer); resolve(ready); } };
|
||||
});
|
||||
if (!ready) return;
|
||||
}
|
||||
if (wanted()) select(connection);
|
||||
} catch (reason) {
|
||||
if (wanted()) 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.
|
||||
if (openingFrame && !openingFrame.loaded && cache.current.get(id) === openingFrame
|
||||
&& (attempt === epoch.current || pendingRef.current?.id !== id)) {
|
||||
cache.current.delete(id);
|
||||
publish();
|
||||
}
|
||||
if (attempt === epoch.current) setPendingSwitch(null);
|
||||
}
|
||||
}, [cancel, client, directory, publish, refresh, select, setPendingSwitch]);
|
||||
const connectRef = useRef(connect);
|
||||
connectRef.current = connect;
|
||||
const loaded = useCallback((id: string) => {
|
||||
const frame = cache.current.get(id);
|
||||
if (frame) { frame.loaded = true; publish(); }
|
||||
if (waiter.current?.id === id) { waiter.current.finish(true); waiter.current = null; }
|
||||
}, [publish]);
|
||||
const disconnect = useCallback(async (id: string) => {
|
||||
if (pendingRef.current?.id === id) cancel();
|
||||
await remoteAction(client, "disconnect", { id });
|
||||
if (selectedRef.current?.id === id) local();
|
||||
cache.current.delete(id);
|
||||
publish();
|
||||
await refresh();
|
||||
}, [cancel, client, local, publish, refresh]);
|
||||
|
||||
useEffect(() => {
|
||||
mounted.current = true;
|
||||
void refresh().catch(() => {});
|
||||
return () => { mounted.current = false; cancel(); };
|
||||
}, [cancel, refresh]);
|
||||
useEffect(() => {
|
||||
const saved = initial.current;
|
||||
if (!saved || window.top !== window) return;
|
||||
let started = false;
|
||||
const timer = window.setTimeout(() => {
|
||||
started = true;
|
||||
if (selectedRef.current?.id === saved.id) setError("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");
|
||||
});
|
||||
});
|
||||
return () => { window.clearTimeout(timer); unsubscribe(); };
|
||||
}, [client]);
|
||||
useEffect(() => {
|
||||
let checking = false;
|
||||
let cancelled = false;
|
||||
const tick = async () => {
|
||||
if (checking || !cache.current.size) return;
|
||||
checking = true;
|
||||
try {
|
||||
const next = await readRemoteInstances(getToken());
|
||||
if (cancelled) 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);
|
||||
frame.failures = connected ? 0 : frame.failures + 1;
|
||||
if (connected || frame.failures >= 2) frame.offline = !connected;
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) for (const frame of cache.current.values()) {
|
||||
if (++frame.failures >= 2) frame.offline = true;
|
||||
}
|
||||
} finally {
|
||||
checking = false;
|
||||
if (!cancelled) publish();
|
||||
}
|
||||
};
|
||||
const timer = window.setInterval(() => { void tick(); }, 5_000);
|
||||
return () => { cancelled = true; window.clearInterval(timer); };
|
||||
}, [client, getToken, publish]);
|
||||
return { directory, directoryError, refresh, selected, frames, pending, error, setError, connect, cancel, local, disconnect, loaded };
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
|
||||
import { HOST_BRIDGE, bridgeMessage, isLocalShellOrigin, readEmbeddedHost, readHostAnchor, type EmbeddedHost, type HostAnchor } from "./host-bridge";
|
||||
import type { HostFrame } from "./useHostSessions";
|
||||
|
||||
interface Peer { source: Window; origin: string; nonce: string }
|
||||
export function useSidebarHostBridge(frames: HostFrame[], selectedId: string | undefined,
|
||||
nodes: RefObject<Map<string, HTMLIFrameElement>>, restoreLocalFocus: () => void,
|
||||
activity: { pendingName?: string; error?: string }) {
|
||||
const [embedded, setEmbedded] = useState<EmbeddedHost | null>(null);
|
||||
const [readyIds, setReadyIds] = useState<string[]>([]);
|
||||
const [anchor, setAnchor] = useState<HostAnchor | null>(null);
|
||||
const parent = useRef<Peer | null>(null);
|
||||
const peers = useRef(new Map<string, Peer>());
|
||||
const latest = useRef({ frames, selectedId, restoreLocalFocus, activity });
|
||||
latest.current = { frames, selectedId, restoreLocalFocus, activity };
|
||||
const initialize = useCallback((id: string) => {
|
||||
const frame = latest.current.frames.find((item) => item.connection.id === id);
|
||||
const source = nodes.current?.get(id)?.contentWindow;
|
||||
if (!frame || !source) return;
|
||||
const origin = new URL(frame.connection.url).origin;
|
||||
let peer = peers.current.get(id);
|
||||
if (!peer || peer.source !== source || peer.origin !== origin) {
|
||||
peer = { source, origin, nonce: crypto.randomUUID() };
|
||||
peers.current.set(id, peer);
|
||||
setReadyIds((ids) => ids.filter((value) => value !== id));
|
||||
}
|
||||
// Deliberately only public display identity, never SSH metadata or secrets.
|
||||
source.postMessage({ channel: HOST_BRIDGE, type: "init", nonce: peer.nonce,
|
||||
name: frame.connection.name, hostname: frame.connection.hostname,
|
||||
...(latest.current.selectedId === id ? latest.current.activity : {}) }, origin);
|
||||
}, [nodes]);
|
||||
useEffect(() => {
|
||||
const receive = (event: MessageEvent<unknown>) => {
|
||||
const message = bridgeMessage(event.data);
|
||||
if (!message) return;
|
||||
if (window.parent !== window) {
|
||||
if (event.source !== window.parent || !isLocalShellOrigin(event.origin)) return;
|
||||
const current = parent.current;
|
||||
if (current && (current.origin !== event.origin || current.nonce !== message.nonce)) return;
|
||||
if (message.type === "init") {
|
||||
const host = readEmbeddedHost(message);
|
||||
if (!host || typeof message.nonce !== "string" || !/^[a-f0-9-]{36}$/.test(message.nonce)) return;
|
||||
parent.current = { source: window.parent, origin: event.origin, nonce: message.nonce };
|
||||
setEmbedded(host);
|
||||
window.parent.postMessage({ channel: HOST_BRIDGE, type: "ready", nonce: message.nonce }, event.origin);
|
||||
} else if (message.type === "focus" && current) latest.current.restoreLocalFocus();
|
||||
return;
|
||||
}
|
||||
// Both source and origin must match a frame this shell actually owns.
|
||||
const frame = latest.current.frames.find((item) => nodes.current?.get(item.connection.id)?.contentWindow === event.source
|
||||
&& new URL(item.connection.url).origin === event.origin);
|
||||
if (!frame) return;
|
||||
const id = frame.connection.id;
|
||||
if (message.type === "hello") { initialize(id); return; }
|
||||
const peer = peers.current.get(id);
|
||||
if (!peer || message.nonce !== peer.nonce) return;
|
||||
if (message.type === "ready") {
|
||||
setReadyIds((ids) => ids.includes(id) ? ids : [...ids, id]);
|
||||
} else if (message.type === "open" && latest.current.selectedId === id && !frame.offline) {
|
||||
const rect = readHostAnchor(message.anchor);
|
||||
const outer = nodes.current?.get(id)?.getBoundingClientRect();
|
||||
if (rect && outer) setAnchor({ ...rect, left: outer.left + rect.left, top: outer.top + rect.top });
|
||||
}
|
||||
// No select/connect/disconnect action is accepted from an embedded page.
|
||||
};
|
||||
window.addEventListener("message", receive);
|
||||
// A public capability probe carries no identity, settings or credentials.
|
||||
if (window.parent !== window) window.parent.postMessage({ channel: HOST_BRIDGE, type: "hello" }, "*");
|
||||
return () => window.removeEventListener("message", receive);
|
||||
}, [initialize, nodes]);
|
||||
useEffect(() => { setAnchor(null); }, [selectedId]);
|
||||
useEffect(() => {
|
||||
if (selectedId && peers.current.has(selectedId)) initialize(selectedId);
|
||||
}, [initialize, selectedId, activity.pendingName, activity.error]);
|
||||
useEffect(() => {
|
||||
for (const id of peers.current.keys()) if (!frames.some((frame) => frame.connection.id === id)) peers.current.delete(id);
|
||||
}, [frames]);
|
||||
const focus = (id: string) => {
|
||||
const peer = peers.current.get(id);
|
||||
if (peer && readyIds.includes(id)) peer.source.postMessage({ channel: HOST_BRIDGE, type: "focus", nonce: peer.nonce }, peer.origin);
|
||||
else nodes.current?.get(id)?.focus({ preventScroll: true });
|
||||
};
|
||||
return { anchor, close: () => setAnchor(null), readyIds, initialize, focus,
|
||||
embedded: embedded ? { ...embedded, kind: "embedded" as const, open: (position: HostAnchor) => {
|
||||
const peer = parent.current;
|
||||
peer?.source.postMessage({ channel: HOST_BRIDGE, type: "open", nonce: peer.nonce, anchor: position }, peer.origin);
|
||||
} } : null };
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { useRef, useState } from "react";
|
||||
import { useContext, useRef, useState } from "react";
|
||||
import { HostNavigationContext, HostSwitcher } from "@/components/remote/HostSwitcher";
|
||||
import {
|
||||
Activity,
|
||||
Info,
|
||||
@@ -76,6 +77,7 @@ export function SettingsSidebar(props: SettingsSidebarProps) {
|
||||
isNativeHost,
|
||||
} = props;
|
||||
const { t } = useTranslation();
|
||||
const hostNavigation = useContext(HostNavigationContext);
|
||||
const mobile = useMediaQuery("(max-width: 1023px)");
|
||||
const restartLabel = isRestarting
|
||||
? t(isNativeHost ? "app.system.restartingEngine" : "app.system.restarting")
|
||||
@@ -185,6 +187,7 @@ export function SettingsSidebar(props: SettingsSidebarProps) {
|
||||
<span>{t("app.account.logout")}</span>
|
||||
</Button>
|
||||
) : null}
|
||||
{hostNavigation && <div className="mt-2 flex min-w-0"><HostSwitcher /></div>}
|
||||
</div>
|
||||
</aside>
|
||||
);
|
||||
@@ -207,6 +210,7 @@ function MobileSettingsNavigation({
|
||||
restartLabel: string;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const hostNavigation = useContext(HostNavigationContext);
|
||||
const [open, setOpen] = useState(false);
|
||||
const restart = () => { setOpen(false); onRestart?.(); };
|
||||
const restartTone = restartPending && !isRestarting
|
||||
@@ -274,6 +278,7 @@ function MobileSettingsNavigation({
|
||||
</> : null}
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
{hostNavigation && <HostSwitcher collapsed />}
|
||||
</div>
|
||||
{onRestart && (restartPending || isRestarting) ? (
|
||||
<div className="flex min-h-11 items-center justify-between gap-2 px-4 pb-1">
|
||||
|
||||
Reference in new issue
Block a user