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 { CodeBlock } from "@/components/CodeBlock"; 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 { groupRemoteProfiles, isCompatibilityError, 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 "./remote-context"; import { SSHHostPicker } from "./SSHHostPicker"; import { QuickPairSetup } from "./QuickPairSetup"; import { PairRouteSettings } from "./PairRouteSettings"; import { HostConnectionStatus } from "./HostConnectionStatus"; import { HostCompatibilityDialog } from "./HostCompatibilityDialog"; import "./remote-layout.css"; 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 [quickReturn, setQuickReturn] = useState(returnedPair); const [pairRoute, setPairRoute] = useState(""); const [details, setDetails] = useState(""); const [detailsOpen, setDetailsOpen] = useState(false); const [routeOpen, setRouteOpen] = useState(false); const [versionId, setVersionId] = useState(""); const [renaming, setRenaming] = useState(null); const [name, setName] = useState(""); const [renameError, setRenameError] = useState(""); const [editing, setEditing] = useState(false); const [savedId, setSavedId] = useState(""); const [busy, setBusy] = useState(""); const [errorCode, setErrorCode] = useState(""); const error = errorCode ? t(`remote.errors.${errorCode}`, { defaultValue: t("remote.errors.unknown") }) : ""; 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 nameId = useId(); const nameInput = useRef(null); 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) { setQuickReturn(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); }; const closeEditor = () => { operation.current += 1; if (busy) connections.cancel(); setBusy(""); setEditorOpen(false); setFingerprint(null); 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()); setCommandImported(false); setEditorOpen(true); setFingerprint(null); }; const importCommand = () => { if (!/^ssh\s/.test(form.host.trim())) return; try { setForm({ ...form, ...parseSSHAddress(form.host) }); setCommandImported(true); setErrorCode(""); } catch (reason) { showError(reason); } }; const pickFile = async (field: "ssh_config" | "identity_file") => { const attempt = ++operation.current; setBusy(`pick-${field}`); 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); 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 === "local_webui_unavailable") { showError(reason); return; } if (reason instanceof Error && isCompatibilityError(reason.message)) { await refresh?.().catch(() => {}); if (wanted(attempt)) { setEditorOpen(false); setVersionId(id); showError(reason); } 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"); setErrorCode(""); 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"); 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"); setErrorCode(""); try { await connections.remove(removing.id); if (mounted.current) setRemoving(null); } catch (reason) { if (mounted.current) showError(reason); } finally { if (mounted.current) setBusy(""); } }; const rename = async () => { if (!renaming || busy || !name.trim() || name.trim() === renaming.name) return; setBusy("rename"); setRenameError(""); try { await connections.rename(renaming.id, name.trim()); if (mounted.current) setRenaming(null); } catch (reason) { if (mounted.current) setRenameError(t(`remote.errors.${reason instanceof Error ? reason.message : "unknown"}`, { defaultValue: t("remote.errors.unknown") })); } finally { if (mounted.current) setBusy(""); } }; const disconnect = async (id: string) => { setBusy(id); setErrorCode(""); 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); setErrorCode(""); setSSHOptions(true); }; const groups = groupRemoteProfiles(directory?.profiles || [], connections.activeHostId); const detailGroup = groups.find((group) => group.id === details); const detailConnection = detailGroup?.connections.find((profile) => profile.connected || connections.openHostIds.includes(profile.id)); const removalIsShared = groups.some((group) => group.connections.length > 1 && group.connections.some((profile) => profile.id === removalProfile?.id)); const connectionActions = (profile: RemoteProfile, grouped = false) => <> {!profile.paired && { setDetailsOpen(false); beginEditor(profile); }}>{t("remote.edit")}} {profile.paired && { setDetailsOpen(false); setPairRoute(profile.id); setRouteOpen(true); }}>{t("remote.pair.route")}} {(profile.connected || connections.openHostIds.includes(profile.id)) && { setDetailsOpen(false); setErrorCode(""); setDisconnecting(profile); }}>{t("remote.disconnect")}} { setDetailsOpen(false); setErrorCode(""); setRemoving(profile); }}>{t(grouped ? "remote.sameInstance.forgetConnection" : "remote.forget")} ; return

{t("remote.title")}

{t("remote.description")}

{directory?.available && <> {directory.profiles.length > 0 && {groups.map(({ id: groupId, profile, connections: entries }) =>
{ setRenaming(profile); setName(profile.name); setRenameError(""); }}>{t("remote.rename.action")} setVersionId(profile.id)}>{t("remote.compatibility.title")} {entries.length > 1 ? { setDetails(groupId); setDetailsOpen(true); }}>{t("remote.sameInstance.details")} : connectionActions(profile)}
)}
} {openingProfile &&

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

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

{t("remote.unavailable")}

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

{directoryError && }
}
profile.id === versionId)} clientVersion={directory?.client_version} onClose={() => setVersionId("")} /> { if (!open && !busy) setRenaming(null); }}> { event.preventDefault(); nameInput.current?.focus(); nameInput.current?.select(); }} onCloseAutoFocus={(event) => { event.preventDefault(); editorTrigger.current?.focus({ preventScroll: true }); }}> {t("remote.rename.title")} {t("remote.rename.hint")}
{ event.preventDefault(); void rename(); }}> { setName(event.target.value); setRenameError(""); }} /> {renameError && }
{ if (!open) setDetailsOpen(false); }}> {t("remote.sameInstance.details")}{t("remote.sameInstance.detailsHint")}
{detailGroup?.connections.map((profile, index) =>
{connectionActions(profile, true)}
)}
{detailConnection &&

{t("remote.sameInstance.switchHint")}

}
{ setQuickOpen(open); if (!open) clearPairReturn(); }}> { clearPairReturn(); setQuickOpen(false); beginEditor(); }} onClose={() => { clearPairReturn(); setQuickOpen(false); }} /> {t("remote.pair.route")}{t("remote.pair.routeHint")} {pairRoute && setRouteOpen(false)} />} { 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); 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(removalIsShared ? "remote.sameInstance.forgetTitle" : "remote.forgetTitle", { name: removalProfile?.name })}{t(removalIsShared ? "remote.sameInstance.forgetHint" : "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}
; }