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

+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 };
}