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 } 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 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"; import { HostConnectionStatus } from "./HostConnectionStatus"; const emptyProfile = (): Omit => ({ name: "", host: "", port: null, ssh_config: "", identity_file: "", config_path: "~/.nanobot/config.json", runtime_user: "", }); /** 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; onBackToChat: () => void; }) { const { t } = useTranslation(); const { client } = useClient(); const connections = useRemoteConnections(); const [form, setForm] = useState(emptyProfile); const [editorOpen, setEditorOpen] = useState(false); 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(null); const [inspectBeforeConnect, setInspectBeforeConnect] = useState(true); const [commandImported, setCommandImported] = useState(false); const [removing, setRemoving] = useState(null); const [disconnecting, setDisconnecting] = useState(null); const lastRemoval = useRef(null); const lastDisconnect = useRef(null); const [fingerprint, setFingerprint] = useState<{ id: string; fingerprint: string; challenge: string; inspect: boolean } | null>(null); const hostInput = useRef(null); const editorTrigger = useRef(null); const mounted = useRef(true); const operation = useRef(0); const optionsId = useId(); const statusId = useId(); const refresh = connections?.refresh; const page = useRef(null); useEffect(() => { if (connections?.managing) page.current?.focus({ preventScroll: true }); }, [connections?.managing]); // 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; void refresh?.().catch(() => {}); return () => { mounted.current = false; operation.current += 1; }; }, [refresh]); if (!connections) return null; const { directory, directoryError, connect: connectHost, disconnect: disconnectHost } = connections; const wanted = (attempt: number) => mounted.current && attempt === operation.current; const showError = (reason: unknown) => { 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 importCommand = () => { if (!/^ssh\s/.test(form.host.trim())) return; try { 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") => ; const connect = async (id: string, attempt = ++operation.current, inspect = false) => { setBusy(inspect ? "inspect" : id); setError(""); setErrorCode(""); try { if (inspect) { const result = await remoteAction(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 (!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 (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, 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 () => { 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: savedId, profile: normalized, }); // Retain the saved id on failures so retry never creates duplicate profiles. if (wanted(attempt)) setSavedId(result.id); await refresh?.(); 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 () => { if (!removing) return; setBusy("remove"); setError(""); try { await disconnectHost(removing.id); await remoteAction(client, "remove", { id: removing.id }); if (mounted.current) setRemoving(null); await refresh?.().catch(() => {}); } 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) { if (mounted.current) showError(reason); } finally { if (mounted.current) setBusy(""); } }; 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

{t("remote.title")}

{t("remote.description")}

{directory?.available && <> {directory.profiles.length > 0 && {directory.profiles.map((profile) =>
{!profile.paired && beginEditor(profile)}>{t("remote.edit")}} {profile.paired && setPairRoute(profile.id)}>{t("remote.pair.route")}} {(profile.connected || connections.openHostIds.includes(profile.id)) && { setError(""); setDisconnecting(profile); }}>{t("remote.disconnect")}} { setError(""); setRemoving(profile); }}>{t("remote.forget")}
)}
} {openingProfile &&

{t("remote.preparing", { name: openingProfile.name })}

}
} {!directory && !directoryError &&
{t("remote.loading")}
} {directory && !directory.available &&

{t("remote.unavailable")}

} {pageError && !editorOpen && !fingerprint && !removing && !disconnecting &&

{directoryError && }
}
{ setQuickOpen(open); if (!open) clearPairReturn(); }}> {quickOpen && { clearPairReturn(); setQuickOpen(false); beginEditor(); }} onClose={() => { clearPairReturn(); setQuickOpen(false); }} />} { if (!open) setPairRoute(""); }}> {t("remote.pair.route")}{t("remote.pair.routeDescription")} {pairRoute && setPairRoute("")} />} { if (!open) closeEditor(); }}> { if (!fingerprint) { event.preventDefault(); hostInput.current?.focus(); } }} onCloseAutoFocus={(event) => { event.preventDefault(); if (!editorTrigger.current?.closest("[inert]")) editorTrigger.current?.focus({ preventScroll: true }); }}> {t(fingerprint ? "remote.verifyTitle" : editing ? "remote.edit" : "remote.addTitle")} {t(fingerprint ? "remote.verifyDescription" : editing ? "remote.editDescription" : "remote.addDescription")} {fingerprint ? <>

{directory?.profiles.find((profile) => profile.id === fingerprint.id)?.host || form.host}

{fingerprint.fingerprint}

{t("remote.verifyHint")}

{error &&

}
{editorOpen && }
:
{ event.preventDefault(); if (!busy && form.host.trim() && (!locationStep || form.config_path.trim())) void save(); }} className="flex min-h-0 flex-col gap-4">
{!editing &&
  1. {locationStep ? : 1}{t("remote.setup.server")}
  2. 2{t("remote.setup.nanobot")}
} {locationStep && !editing ?
{t("remote.setup.signedIn")}{form.host}
{!!inspection?.candidates.length &&
{t("remote.setup.chooseNanobot")} {inspection.candidates.map((candidate) => )}
} {inspection && !inspection.candidates.length &&

{t("remote.setup.notFound")}

{t("remote.setup.notFoundHint")}

} {inspection?.incomplete &&

{t("remote.setup.limitedSearch")}

} {!manualLocation && }
: <> { setForm({ ...form, host }); setCommandImported(false); setError(""); setErrorCode(""); }} onBlur={importCommand} />
setForm({ ...form, ssh_config })} action={filePicker("ssh_config")} /> setForm({ ...form, identity_file })} action={filePicker("identity_file")} />

{t("remote.setup.keyHint")}

setForm({ ...form, port: port === "" ? null : Number(port) })} /> setForm({ ...form, name })} />
} {(editing || manualLocation || nanobotError) &&
setForm({ ...form, config_path })} /> setForm({ ...form, runtime_user })} />

{t("remote.setup.locationHint")}

}
{error &&

{!sshOptions && /^(ssh_|local_file_not_found)/.test(errorCode) && }
} {busy.startsWith("pick-") &&

{t("remote.setup.pickingFile")}

}
}
{ if (!value && !busy) setDisconnecting(null); }}> {t("remote.disconnectTitle", { name: disconnectProfile?.name })}{t("remote.disconnectDescription")} {error &&

}
{ if (!value && !busy) setRemoving(null); }}> {t("remote.forgetTitle", { name: removalProfile?.name })}{t("remote.forgetDescription")} {removalProfile && (removalProfile.connected || connections.openHostIds.includes(removalProfile.id)) &&

{t("remote.activeForgetWarning")}

} {removalProfile?.paired &&

{t("remote.pair.forgetHint")}

{removalProfile.revoke_command}
} {error &&

}
; } function RemoteField({ label, onChange, action, ...props }: { label: string; value: string; onChange: (value: string) => void; action?: ReactNode; placeholder?: string; disabled?: boolean; type?: string; min?: number; max?: number; }) { const id = useId(); return
onChange(event.target.value)} autoComplete="off" spellCheck={false} />{action}
; }