Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
fix(remote): simplify connection mutations and preserve host state
Xubin Ren2330bfc5a54b
diff --git a/nanobot/webui/remote_instances.py b/nanobot/webui/remote_instances.pyindex b846c43c4..006eb6ec3 100644--- a/nanobot/webui/remote_instances.py+++ b/nanobot/webui/remote_instances.py@@ -333,11 +333,14 @@ class RemoteInstances:))if instance_changed:self._remember_origins(profiles)- local_port = profiles[key].local_port if key in profiles and not instance_changed else 0- proxy_origin = bool(local_port and profiles[key].proxy_origin)- profiles[key] = _SavedProfile(**profile.model_dump(), local_port=local_port,- proxy_origin=proxy_origin)+ # Update editable fields without reconstructing (and losing)+ # managed origin metadata for an unchanged destination.+ profiles[key] = (profiles[key].model_copy(update=profile.model_dump())+ if key in profiles and not instance_changed+ else _SavedProfile(**profile.model_dump()))self._write(profiles)+ if instance_changed:+ self._compatibility.pop(key, None)if target_changed:self._known_hosts(key).unlink(missing_ok=True)self._unverified.pop(key, None)diff --git a/tests/webui/test_remote_instances.py b/tests/webui/test_remote_instances.pyindex 4edda4f54..b2ce57bbc 100644--- a/tests/webui/test_remote_instances.py+++ b/tests/webui/test_remote_instances.py@@ -481,13 +481,33 @@ async def test_health_budget_includes_waiting_for_connection_lock(manager, ssh,async def test_reconnect_keeps_origin_and_changing_target_does_not(manager, ssh):key = await save(manager)- await manager.action("connect", {"id": key})+ first = await manager.action("connect", {"id": key})assert json.loads(manager.path.read_text())[key]["local_port"] == 23456await manager.action("disconnect", {"id": key})await manager.action("save", {"id": key, "profile": {"name": "Renamed", "host": "[email protected]"}})assert json.loads(manager.path.read_text())[key]["local_port"] == 23456+ # Editing display metadata must preserve the local-client origin marker,+ # not just its port: otherwise reconnect silently retires that origin.+ assert json.loads(manager.path.read_text())[key]["local_client_origin"] is True+ second = await manager.action("connect", {"id": key})+ assert second["url"] == first["url"]+ RemoteProxy.open.assert_awaited_once()+ await manager.action("disconnect", {"id": key})await manager.action("save", {"id": key, "profile": {"name": "Other", "host": "other.example.test"}})assert json.loads(manager.path.read_text())[key]["local_port"] == 0+ assert "compatibility" not in manager.snapshot()["profiles"][0]+++async def test_editing_failed_target_clears_its_compatibility_diagnosis(manager, ssh):+ key = await save(manager)+ ssh.state["identity"].pop("webui")+ with pytest.raises(RemoteError, match="webui_compatibility_unknown"):+ await manager.action("connect", {"id": key})+ result = await manager.action("save", {"id": key, "profile": {+ "name": "Other", "host": "other.example.test",+ }})+ assert result["profiles"][0]["connection_error"] == "disconnected"+ assert "compatibility" not in result["profiles"][0]async def test_corrupt_store_not_overwritten(manager):diff --git a/webui/src/components/remote/RemoteConnectionsPage.tsx b/webui/src/components/remote/RemoteConnectionsPage.tsxindex 05126b8d2..44ed7e239 100644--- a/webui/src/components/remote/RemoteConnectionsPage.tsx+++ b/webui/src/components/remote/RemoteConnectionsPage.tsx@@ -51,8 +51,8 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChroconst [editing, setEditing] = useState(false);const [savedId, setSavedId] = useState("");const [busy, setBusy] = useState("");- const [error, setError] = 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<RemoteInspection | null>(null);@@ -96,12 +96,11 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChrosetInspection(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("");+ setBusy(""); setEditorOpen(false); setFingerprint(null); setErrorCode("");};const beginEditor = (profile?: RemoteProfile) => {operation.current += 1;@@ -111,20 +110,20 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChrosetForm(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);+ 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("");+ setCommandImported(true); setErrorCode("");} catch (reason) { showError(reason); }};const pickFile = async (field: "ssh_config" | "identity_file") => {const attempt = ++operation.current;- setBusy(`pick-${field}`); setError(""); setErrorCode("");+ setBusy(`pick-${field}`); setErrorCode("");try {const result = await remoteAction<{ path: string | null }>(client, "pick_file", {});if (wanted(attempt) && typeof result.path === "string" && result.path) {@@ -140,7 +139,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro</Button>;const connect = async (id: string, attempt = ++operation.current, inspect = false) => {- setBusy(inspect ? "inspect" : id); setError(""); setErrorCode("");+ setBusy(inspect ? "inspect" : id); setErrorCode("");try {if (inspect) {const result = await remoteAction<RemoteInspection>(client, "inspect", { id });@@ -208,7 +207,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChroif (!fingerprint) return;const attempt = ++operation.current;const id = fingerprint.id;- setBusy("trust"); setError("");+ setBusy("trust"); setErrorCode("");try {await remoteAction(client, "trust", { id, challenge: fingerprint.challenge });if (wanted(attempt)) { setFingerprint(null); await connect(id, attempt, fingerprint.inspect); }@@ -218,7 +217,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChroconst save = async () => {const attempt = ++operation.current;- setBusy("save"); setError(""); setErrorCode("");+ setBusy("save"); setErrorCode("");try {// Also parse here for Enter submission, which doesn't blur the address.const address = parseSSHAddress(form.host);@@ -239,12 +238,10 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChroconst remove = async () => {if (!removing) return;- setBusy("remove"); setError("");+ setBusy("remove"); setErrorCode("");try {- await disconnectHost(removing.id);- await remoteAction(client, "remove", { id: removing.id });+ await connections.remove(removing.id);if (mounted.current) setRemoving(null);- await refresh?.().catch(() => {});} catch (reason) { if (mounted.current) showError(reason); }finally { if (mounted.current) setBusy(""); }};@@ -259,7 +256,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro} finally { if (mounted.current) setBusy(""); }};const disconnect = async (id: string) => {- setBusy(id); setError("");+ setBusy(id); setErrorCode("");try { await disconnectHost(id); if (mounted.current) setDisconnecting(null); }catch (reason) { if (mounted.current) showError(reason); }finally { if (mounted.current) setBusy(""); }@@ -277,7 +274,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChroconst disconnectProfile = disconnecting || lastDisconnect.current;const editSSH = () => {setInspection(null); setManualLocation(false); setInspectBeforeConnect(true);- setError(""); setErrorCode(""); setSSHOptions(true);+ setErrorCode(""); setSSHOptions(true);};const groups = groupRemoteProfiles(directory?.profiles || [], connections.activeHostId);const detailGroup = groups.find((group) => group.id === details);@@ -286,8 +283,8 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChroconst connectionActions = (profile: RemoteProfile, grouped = false) => <>{!profile.paired && <DropdownMenuItem disabled={profile.connected || connections.openHostIds.includes(profile.id)} onSelect={() => { setDetailsOpen(false); beginEditor(profile); }}>{t("remote.edit")}</DropdownMenuItem>}{profile.paired && <DropdownMenuItem disabled={profile.connected || connections.openHostIds.includes(profile.id)} onSelect={() => { setDetailsOpen(false); setPairRoute(profile.id); setRouteOpen(true); }}>{t("remote.pair.route")}</DropdownMenuItem>}- {(profile.connected || connections.openHostIds.includes(profile.id)) && <DropdownMenuItem onSelect={() => { setDetailsOpen(false); setError(""); setDisconnecting(profile); }}>{t("remote.disconnect")}</DropdownMenuItem>}- <DropdownMenuItem tone="destructive" onSelect={() => { setDetailsOpen(false); setError(""); setRemoving(profile); }}>{t(grouped ? "remote.sameInstance.forgetConnection" : "remote.forget")}</DropdownMenuItem>+ {(profile.connected || connections.openHostIds.includes(profile.id)) && <DropdownMenuItem onSelect={() => { setDetailsOpen(false); setErrorCode(""); setDisconnecting(profile); }}>{t("remote.disconnect")}</DropdownMenuItem>}+ <DropdownMenuItem tone="destructive" onSelect={() => { setDetailsOpen(false); setErrorCode(""); setRemoving(profile); }}>{t(grouped ? "remote.sameInstance.forgetConnection" : "remote.forget")}</DropdownMenuItem></>;return <div ref={page} tabIndex={-1} role="region" aria-label={t("remote.title")} className="flex min-h-0 flex-1 flex-col overflow-hidden bg-settings-canvas outline-none">@@ -361,7 +358,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro{pageError && !editorOpen && !fingerprint && !removing && !disconnecting && <div className="settings-list-inset space-y-2"><p role="alert" className="remote-alert 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((reason: unknown) => { if (mounted.current) showError(reason); }).finally(() => { if (mounted.current) setBusy(""); });+ setBusy("refresh"); setErrorCode(""); void refresh?.().catch((reason: unknown) => { if (mounted.current) showError(reason); }).finally(() => { if (mounted.current) setBusy(""); });}}>{t("remote.retry")}</Button>}</div>}</div>@@ -444,7 +441,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro<p className="text-xs leading-5 text-muted-foreground">{t("remote.verifyHint")}</p>{error && <p role="alert" className="remote-alert 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" /><span>{error}</span></p>}<div className="remote-dialog-actions">- {editorOpen && <Button variant="ghost" disabled={!!busy} className="gap-1" onClick={() => { setFingerprint(null); setError(""); setErrorCode(""); setInspection(null); setInspectBeforeConnect(true); }}><ChevronLeft className="h-4 w-4" />{t("remote.back")}</Button>}+ {editorOpen && <Button variant="ghost" disabled={!!busy} className="gap-1" onClick={() => { setFingerprint(null); 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>@@ -466,7 +463,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro{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(""); }} />+ onChange={() => { setManualLocation(false); setForm({ ...form, config_path: candidate.config_path, runtime_user: candidate.runtime_user }); setErrorCode(""); }} /><span className="min-w-0 text-[13px]"><span className="block font-medium [overflow-wrap:anywhere]">{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>}@@ -482,7 +479,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro</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} />+ onChange={(host) => { setForm({ ...form, host }); setCommandImported(false); 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"diff --git a/webui/src/components/remote/RemoteInstances.tsx b/webui/src/components/remote/RemoteInstances.tsxindex 4e4525b90..748130aab 100644--- a/webui/src/components/remote/RemoteInstances.tsx+++ b/webui/src/components/remote/RemoteInstances.tsx@@ -30,6 +30,7 @@ const RemoteContext = createContext<{rename: (id: string, name: string) => Promise<void>;connect: (id: string, stillWanted?: () => boolean) => Promise<void>;disconnect: (id: string) => Promise<void>;+ remove: (id: string) => Promise<void>;cancel: () => void;} | null>(null);export function useRemoteConnections() { return useContext(RemoteContext); }@@ -161,7 +162,7 @@ export function RemoteInstances({ children }: { children: ReactNode }) {embeddedManagement: !!bridge.embedded, reportManagementSurface: bridge.embedded ? bridge.reportSurface : undefined,closeManagement: bridge.embedded ? bridge.leaveManagement : () => changeManagement(false), selectLocal,openHostIds: frames.map((frame) => frame.connection.id),- directoryError: hosts.directoryError, refresh: hosts.refresh, rename: hosts.rename, connect, disconnect: hosts.disconnect, cancel: hosts.cancel }}>+ directoryError: hosts.directoryError, refresh: hosts.refresh, rename: hosts.rename, connect, disconnect: hosts.disconnect, remove: hosts.remove, 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">diff --git a/webui/src/components/remote/useHostSessions.ts b/webui/src/components/remote/useHostSessions.tsindex 192b10881..5af6eb3bd 100644--- a/webui/src/components/remote/useHostSessions.ts+++ b/webui/src/components/remote/useHostSessions.ts@@ -172,17 +172,21 @@ export function useHostSessions() {if (frame) { frame.loaded = true; publish(); }if (waiter.current?.id === id) { waiter.current.finish(true); waiter.current = null; }}, [publish]);- const disconnect = useCallback(async (id: string) => {+ const closeConnection = useCallback(async (id: string, action: "disconnect" | "remove") => {directoryGeneration.current += 1;if (pendingRef.current?.id === id) cancel();- await remoteAction(client, "disconnect", { id });+ // The backend owns the transaction. In particular, a failed Forget must+ // leave the connection and its browser view intact for a safe retry.+ const next = await remoteAction<RemoteDirectory>(client, action, { id });+ directoryGeneration.current += 1;+ if (!mounted.current) return;if (selectedRef.current?.id === id) local();cache.current.delete(id);+ applyDirectory(next);publish();- // 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]);+ }, [applyDirectory, cancel, client, local, publish]);+ const disconnect = useCallback((id: string) => closeConnection(id, "disconnect"), [closeConnection]);+ const remove = useCallback((id: string) => closeConnection(id, "remove"), [closeConnection]);useEffect(() => {mounted.current = true;@@ -259,5 +263,5 @@ export function useHostSessions() {};}, [applyDirectory, client, getToken, publish]);return { directory, directoryError, refresh, rename, selected, recentIds, frames, pending,- error: failure?.code || "", errorId: failure?.id, clearError, connect, cancel, local, disconnect, loaded };+ error: failure?.code || "", errorId: failure?.id, clearError, connect, cancel, local, disconnect, remove, loaded };}diff --git a/webui/src/tests/host-sessions.test.tsx b/webui/src/tests/host-sessions.test.tsxindex 94b9fca6f..0e4b6a23f 100644--- a/webui/src/tests/host-sessions.test.tsx+++ b/webui/src/tests/host-sessions.test.tsx@@ -35,7 +35,10 @@ beforeEach(() => {window.sessionStorage.clear();mocks.read.mockReset().mockResolvedValue(directory);mocks.request.mockReset().mockImplementation(async (action: string, payload: { id: string }) =>- action === "remote.connect" ? connections.find((item) => item.id === payload.id) : {});+ action === "remote.connect" ? connections.find((item) => item.id === payload.id) : {+ ...directory, profiles: directory.profiles.map((profile) =>+ profile.id === payload.id ? { ...profile, connected: false } : profile),+ });});afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });@@ -99,14 +102,17 @@ describe("host session lifecycle", () => {expect(result.current.frames[0].error).toBe("instance_changed");});- it("does not report a successful disconnect as failed when refreshing the list fails", async () => {+ it("uses the disconnect result without a second directory read", async () => {const { result } = renderHook(useHostSessions);await ready(result, 0);+ const reads = mocks.read.mock.calls.length;mocks.read.mockRejectedValue(new Error("directory_unavailable"));await act(async () => { await expect(result.current.disconnect(ids[0])).resolves.toBeUndefined(); });expect(result.current.selected).toBeNull();expect(result.current.frames).toHaveLength(0);- expect(result.current.directoryError).toBe(true);+ expect(result.current.directory?.profiles.find((profile) => profile.id === ids[0])?.connected).toBe(false);+ expect(mocks.read).toHaveBeenCalledTimes(reads);+ expect(result.current.directoryError).toBe(false);});it("keeps the current host until the destination view loads, then switches warm without RPC", async () => {diff --git a/webui/src/tests/remote-instances.test.tsx b/webui/src/tests/remote-instances.test.tsxindex 350583781..75e0fd9be 100644--- a/webui/src/tests/remote-instances.test.tsx+++ b/webui/src/tests/remote-instances.test.tsx@@ -67,6 +67,7 @@ beforeEach(async () => {mocks.request.mockReset().mockImplementation(async (action: string) => {if (action === "remote.connect") return connection;if (action === "remote.save") return { id: profile.id };+ if (action === "remote.disconnect") return { available: true, profiles: [profile] };return {};});});@@ -860,6 +861,33 @@ describe("remote instance UX", () => {expect(mocks.request).toHaveBeenCalledWith("remote.disconnect", { id: profile.id }, 65_000);});+ it("keeps the current view when forgetting fails and closes it only after a successful retry", async () => {+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Team server [email protected]" }));+ const frame = await readyRemote();+ await openDirectory();+ fireEvent.pointerDown(screen.getByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Forget server" }));+ const dialog = await screen.findByRole("dialog", { name: "Forget Team server?" });+ mocks.request.mockImplementation(async (action: string) => {+ if (action === "remote.remove") throw new Error("local_io_error");+ return {};+ });+ fireEvent.click(within(dialog).getByRole("button", { name: "Forget server" }));+ await within(dialog).findByRole("alert");+ expect(readSelectedRemote()?.id).toBe(profile.id);+ expect(frame).toBeInTheDocument();+ expect(mocks.request.mock.calls.map(([action]) => action)).toEqual(["remote.connect", "remote.remove"]);++ mocks.request.mockResolvedValue({ available: true, profiles: [] });+ mocks.read.mockRejectedValue(new Error("directory_unavailable"));+ fireEvent.click(within(dialog).getByRole("button", { name: "Forget server" }));+ await waitFor(() => expect(frame).not.toBeInTheDocument());+ expect(readSelectedRemote()).toBeNull();+ expect(screen.queryByRole("button", { name: "Manage Team server" })).not.toBeInTheDocument();+ expect(mocks.request.mock.calls.map(([action]) => action)).toEqual(["remote.connect", "remote.remove", "remote.remove"]);+ });+it("refresh restores the selected remote, keeping the local shell hidden", async () => {rememberSelectedRemote(connection);view();