diff --git a/docs/guides/remote-instances.md b/docs/guides/remote-instances.md index 1e4d5fb81..8882a1daa 100644 --- a/docs/guides/remote-instances.md +++ b/docs/guides/remote-instances.md @@ -31,6 +31,22 @@ It is separate from remote execution/worker deployment. ## Quick pairing: copy a command, follow a link back +Repeated pairing to the same verified destination appears as one server in the +directory and host switcher. The confirmation says **This nanobot is already +saved**; **Save and open** keeps the new authorization as well as the old ones, +preserves the saved name, and reuses a healthy open connection. When reconnecting, +the directory prefers a non-expired authorization unless another is already selected. +Use **Connection details** in that server's menu to choose or forget one specific +connection. Forgetting one does not delete the others or revoke its server-side key. +Disconnect an open connection before choosing a different authorization. The +20-connection limit counts retained authorizations, not just visible server rows. + +Grouping is read-only: it requires matching encrypted-receipt evidence for the +SSH endpoint, pinned host key, account, resolved nanobot configuration, WebUI port +and credential. Names/IPs alone and restart-scoped gateway IDs are insufficient. +Different instances remain separate, as do unverified manual SSH entries or +changed addresses/credentials. No old authorization files are silently deleted. + For a Linux server with this version of nanobot installed, you do not need to prepare a local SSH key or know the service account/config path: diff --git a/nanobot/webui/remote_instances.py b/nanobot/webui/remote_instances.py index 134b54ed5..bec2d45c0 100644 --- a/nanobot/webui/remote_instances.py +++ b/nanobot/webui/remote_instances.py @@ -125,6 +125,7 @@ class RemoteInstances: def snapshot(self) -> dict[str, Any]: profiles: list[dict[str, Any]] = [] + instances: dict[tuple[str, str, int, str, str, int, str, str], str] = {} for key, profile in self._read().items(): connection = self.connections.get(key) error = (connection.error or ("" if connection.tunnel.active else "ssh_unreachable")) if connection else "disconnected" @@ -140,6 +141,11 @@ class RemoteInstances: expiry = self.pairing.authorization_until(profile.pair_id) if expiry is not None: item["authorized_until"] = expiry + receipt = self.pairing.saved_receipt(profile.pair_id) + if receipt is not None: + # Group only authenticated local receipt evidence, never + # display names, addresses alone, or transient gateway IDs. + item["instance_id"] = instances.setdefault(receipt.destination(), key) profiles.append(item) return {"available": True, "machine_name": socket.gethostname(), "profiles": profiles} @@ -226,23 +232,53 @@ class RemoteInstances: code = payload.get("code", "") if not isinstance(code, str): raise RemoteError("pair_invalid") + receipt = self.pairing.saved_receipt(profiles[key].pair_id) if action == "pair_finish" and key in profiles and profiles[key].pair_id else None + if receipt is None: + receipt = self.pairing.review(key, code) + matches = [saved_key for saved_key, saved in profiles.items() + if saved.pair_id and (previous := self.pairing.saved_receipt(saved.pair_id)) + and previous.destination() == receipt.destination()] + # Prefer an already-open connection; never disconnect it merely + # because the user paired this same instance again. + live_key = next((saved_key for saved_key in matches + if (live := self.connections.get(saved_key)) + and live.tunnel.active and not live.error), "") + if action == "pair_finish" and live_key: + await self._check(self.connections[live_key]) + if self.connections[live_key].error: + live_key = "" if action == "pair_preview": - return self.pairing.preview(key, code) + preview = receipt.preview() + if matches: + preview["existing_connection"] = {"id": live_key or matches[0], + "name": profiles[matches[0]].name, + "connected": bool(live_key)} + return preview if len(profiles) >= 20 and key not in profiles: raise RemoteError("profile_limit") # Completion is idempotent. No browser-provided host/path/key is # trusted as a substitute for the encrypted server receipt. if key in profiles: - return {"id": key, **self.snapshot()} + return {"id": live_key or key, **self.snapshot()} receipt = self.pairing.finish(key, code) profile = self.pairing.profile(receipt) + if matches: + profile.name = profiles[matches[0]].name + # A saved route belongs to this exact verified destination. + # Keep it when re-pairing; do not fall back to a broken VPN route. + source = profiles[live_key or matches[-1]] + if source.ssh_config: + route = self.pairing.path(key) / "ssh_route" + _write_text_atomic(route, Path(source.ssh_config).read_text()) + route.chmod(0o600) + profile.ssh_config = str(route) known = self._known_hosts(key) known.parent.mkdir(parents=True, exist_ok=True) _write_text_atomic(known, "nanobot-remote " + receipt.host_key + "\n") known.chmod(0o600) profiles[key] = _SavedProfile(**profile.model_dump(), pair_id=key) self._write(profiles) - return {"id": key, **self.snapshot()} + return {"id": live_key or key, **self.snapshot()} if action == "save": profile = RemoteProfile.model_validate(payload.get("profile")) if key and key not in profiles: diff --git a/nanobot/webui/remote_pairing.py b/nanobot/webui/remote_pairing.py index 87888248c..62f1c244b 100644 --- a/nanobot/webui/remote_pairing.py +++ b/nanobot/webui/remote_pairing.py @@ -169,6 +169,17 @@ class PairReceipt(BaseModel): "authorized_until": self.authorized_until, "revoke_command": f"nanobot remote revoke {self.id} --ssh-user {self.user}"} + def destination(self) -> tuple[str, str, int, str, str, int, str, str]: + """Conservative same-instance evidence, confined to the local manager. + + A name/IP or the restart-scoped gateway ID is not enough. Require the + same pinned SSH server, account, resolved config and WebUI capability. + Keep changed credentials/addresses separate rather than guessing. Never + send this tuple (or a credential-derived hash) to the browser. + """ + return (self.host, self.user, self.ssh_port, self.host_key, self.config_path, + self.port, self.secret, self.token_issue_path) + def _derive(shared: bytes, request_id: str) -> bytes: return HKDF(algorithm=hashes.SHA256(), length=32, salt=request_id.encode(), info=_CONTEXT).derive(shared) @@ -267,6 +278,17 @@ class PairStore: def preview(self, key: str, code: str) -> dict[str, Any]: return self._decrypt(key, code, pending=True).preview() + def review(self, key: str, code: str) -> PairReceipt: + return self._decrypt(key, code, pending=True) + + def saved_receipt(self, key: str) -> PairReceipt | None: + """Read grouping evidence, even for expired grants, without granting access.""" + try: + code = (self.path(key) / "receipt").read_text() + return self._decrypt(key, code, pending=False, require_active=False) + except (OSError, RemoteError): + return None + def finish(self, key: str, code: str) -> PairReceipt: receipt = self._decrypt(key, code, pending=True) path = self.path(key) / "receipt" diff --git a/tests/webui/test_remote_pairing.py b/tests/webui/test_remote_pairing.py index 4f3b27b35..5b2f34279 100644 --- a/tests/webui/test_remote_pairing.py +++ b/tests/webui/test_remote_pairing.py @@ -228,6 +228,113 @@ async def test_api_pair_finalization_pins_host_and_hides_credentials(tmp_path): assert manager.snapshot()["profiles"] == [] +async def test_repeated_pairing_groups_one_instance_without_deleting_authorizations(tmp_path): + manager = RemoteInstances(tmp_path) + first = read_request((await manager.action("pair_start", {}))["command"].split()[-1]) + original = receipt(first) + await manager.action("pair_finish", {"id": first.id, "code": seal(first, original)}) + profiles = manager._read() + profiles[first.id].name = "My team" + manager._write(profiles) + before = manager.pairing.path(first.id).joinpath("identity").read_bytes() + second = read_request((await manager.action("pair_start", {}))["command"].split()[-1]) + renewed = original.model_copy(update={"id": second.id, "ssh_key": second.ssh_key}) + code = seal(second, renewed) + preview = await manager.action("pair_preview", {"id": second.id, "code": code}) + assert preview["existing_connection"] == {"id": first.id, "name": "My team", "connected": False} + assert len(manager.snapshot()["profiles"]) == 1 # Preview never saves or deletes. + result = await manager.action("pair_finish", {"id": second.id, "code": code}) + assert result["id"] == second.id + assert len(result["profiles"]) == 2 # Grants remain separately manageable. + assert {item["instance_id"] for item in result["profiles"]} == {first.id} + assert {item["name"] for item in result["profiles"]} == {"My team"} + assert manager.pairing.path(first.id).joinpath("identity").read_bytes() == before + assert manager.pairing.connection(second.id)["secret"] == original.secret + assert original.secret not in json.dumps(result) + assert original.host_key not in json.dumps(result) + assert (await manager.action("pair_finish", {"id": second.id, "code": code}))["id"] == second.id + assert len({item["instance_id"] for item in RemoteInstances(tmp_path).snapshot()["profiles"]}) == 1 + await manager.action("remove", {"id": second.id}) + assert manager.pairing.path(first.id).joinpath("identity").read_bytes() == before + assert len(manager.snapshot()["profiles"]) == 1 + + +@pytest.mark.parametrize("change", [ + {"host": "203.0.113.2"}, {"user": "other"}, {"ssh_port": 2222}, + {"config_path": "/srv/other/config.json"}, {"port": 9876}, + {"secret": "another-private-credential"}, {"token_issue_path": "/different-issuer"}, + {"host_key": ssh_public()}, +]) +async def test_same_name_or_ip_never_groups_different_pairing_destinations(tmp_path, change): + manager = RemoteInstances(tmp_path) + first = read_request((await manager.action("pair_start", {}))["command"].split()[-1]) + original = receipt(first) + await manager.action("pair_finish", {"id": first.id, "code": seal(first, original)}) + second = read_request((await manager.action("pair_start", {}))["command"].split()[-1]) + other = original.model_copy(update={"id": second.id, "ssh_key": second.ssh_key, **change}) + code = seal(second, other) + preview = await manager.action("pair_preview", {"id": second.id, "code": code}) + assert "existing_connection" not in preview + result = await manager.action("pair_finish", {"id": second.id, "code": code}) + assert len({item["instance_id"] for item in result["profiles"]}) == 2 + + +@pytest.mark.parametrize("healthy", [True, False]) +async def test_repair_retains_route_and_reuses_only_a_healthy_existing_connection(tmp_path, monkeypatch, healthy): + manager = RemoteInstances(tmp_path) + first = read_request((await manager.action("pair_start", {}))["command"].split()[-1]) + original = receipt(first) + await manager.action("pair_finish", {"id": first.id, "code": seal(first, original)}) + route = manager.pairing.path(first.id) / "ssh_route" + route.write_text("Host *\n ProxyCommand /usr/bin/nc -b en0 %h %p\n") + profiles = manager._read() + profiles[first.id].ssh_config = str(route) + profiles[first.id].local_port = 23456 + manager._write(profiles) + live = SimpleNamespace(tunnel=SimpleNamespace(active=True), error="", gateway_id="live-session", + proxy=SimpleNamespace(pause=AsyncMock())) + manager.connections[first.id] = live + + async def check(connection): + connection.error = "" if healthy else "remote_auth_failed" + + monkeypatch.setattr(manager, "_check", check) + second = read_request((await manager.action("pair_start", {}))["command"].split()[-1]) + renewed = original.model_copy(update={"id": second.id, "ssh_key": second.ssh_key}) + code = seal(second, renewed) + result = await manager.action("pair_finish", {"id": second.id, "code": code}) + assert result["id"] == (first.id if healthy else second.id) + assert manager.connections[first.id] is live + live.proxy.pause.assert_not_awaited() + assert manager._read()[first.id].local_port == 23456 + new_route = manager.pairing.path(second.id) / "ssh_route" + assert new_route.read_text() == route.read_text() + if os.name != "nt": + assert new_route.stat().st_mode & 0o777 == 0o600 + assert manager._read()[second.id].ssh_config == str(new_route) + + +async def test_grouping_old_receipts_is_read_only_and_tolerates_expired_or_missing_grants(tmp_path, monkeypatch): + manager = RemoteInstances(tmp_path) + first = read_request((await manager.action("pair_start", {}))["command"].split()[-1]) + original = receipt(first) + await manager.action("pair_finish", {"id": first.id, "code": seal(first, original)}) + second = read_request((await manager.action("pair_start", {}))["command"].split()[-1]) + other = original.model_copy(update={"id": second.id, "ssh_key": second.ssh_key}) + await manager.action("pair_finish", {"id": second.id, "code": seal(second, other)}) + saved = manager.path.read_bytes() + monkeypatch.setattr(time, "time", lambda: original.authorized_until + 10) + assert len({item["instance_id"] for item in manager.snapshot()["profiles"]}) == 1 + assert manager.path.read_bytes() == saved + with pytest.raises(RemoteError, match="pair_authorization_expired"): + manager.pairing.connection(first.id) + manager.pairing.path(second.id).joinpath("receipt").unlink() + result = manager.snapshot()["profiles"] + assert len(result) == 2 + assert "instance_id" not in result[1] + assert manager.path.read_bytes() == saved + + @pytest.mark.parametrize("with_route", [False, True]) async def test_paired_profile_follows_moved_data_root(tmp_path, monkeypatch, with_route): original = tmp_path / "original" diff --git a/webui/src/components/remote/QuickPairSetup.tsx b/webui/src/components/remote/QuickPairSetup.tsx index 048569708..3e734f105 100644 --- a/webui/src/components/remote/QuickPairSetup.tsx +++ b/webui/src/components/remote/QuickPairSetup.tsx @@ -15,7 +15,8 @@ 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 }; +type Preview = { id: string; host: string; hostname: string; fingerprint: string; authorized_until: number; revoke_command: string; + existing_connection?: { id: string; name: string; connected: boolean } }; /** Public invitation → encrypted receipt → explicit confirmation. No private key inputs. */ export function QuickPairSetup({ returned, onSSH, onClose }: { returned?: PairReturn | null; onSSH: () => void; onClose: () => void }) { @@ -128,14 +129,14 @@ export function QuickPairSetup({ returned, onSSH, onClose }: { returned?: PairRe const invalidReturn = ["pair_invalid", "pair_expired", "pair_used"].some((code) => error === `remote.errors.${code}`); const restartAvailable = !saved && (expired || (!!error && !request?.command && !preview && (!returned || invalidReturn))); const reviewingReturn = !!returned && !request?.command && !preview && !manual && !restartAvailable; - const title = preview ? "remote.pair.confirmTitle" : reviewingReturn ? "remote.pair.review" : restartAvailable ? "remote.add" + const title = preview ? preview.existing_connection ? "remote.sameInstance.title" : "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 showIllustration = !preview && !manual && !reviewingReturn && !restartAvailable; const showBusy = pending && busyVisible; - const actionLabel = restartAvailable ? "remote.pair.restart" : reviewingReturn ? error ? "remote.retry" : "remote.pair.review" : preview ? saved ? "remote.retry" : "remote.connect" + const actionLabel = restartAvailable ? "remote.pair.restart" : reviewingReturn ? error ? "remote.retry" : "remote.pair.review" : preview ? saved ? "remote.retry" : preview.existing_connection ? "remote.sameInstance.saveAndOpen" : "remote.connect" : manual ? "remote.pair.review" : copied ? "remote.pair.copyAgain" : "remote.pair.copy"; const busyLabel = waitingForLocal ? "remote.pair.waitingForLocal" : preview ? "remote.connecting" : !restartAvailable && (manual || returned) ? "remote.pair.checkingLink" : "remote.pair.preparing"; @@ -154,9 +155,10 @@ export function QuickPairSetup({ returned, onSSH, onClose }: { returned?: PairRe {preview ?
-

{preview.hostname}

+

{preview.existing_connection?.name || preview.hostname}

{preview.host}

+ {preview.existing_connection &&

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

}

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

{t("remote.pair.expiry", { date: new Date(preview.authorized_until * 1000).toLocaleDateString() })}

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 && { setDetails(""); beginEditor(profile); }}>{t("remote.edit")}} + {profile.paired && { setDetails(""); setPairRoute(profile.id); }}>{t("remote.pair.route")}} + {(profile.connected || connections.openHostIds.includes(profile.id)) && { setDetails(""); setError(""); setDisconnecting(profile); }}>{t("remote.disconnect")}} + { setDetails(""); setError(""); setRemoving(profile); }}>{t(grouped ? "remote.sameInstance.forgetConnection" : "remote.forget")} + ; return
@@ -272,7 +283,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro {directory.profiles.length > 0 && - {directory.profiles.map((profile) =>
+ {groups.map(({ id: groupId, profile, connections: entries }) =>
- {!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")} + {entries.length > 1 ? setDetails(groupId)}>{t("remote.sameInstance.details")} : connectionActions(profile)}
)} @@ -323,6 +332,28 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro
+ { if (!open) setDetails(""); }}> + + {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(); }}> {quickOpen && { clearPairReturn(); setQuickOpen(false); beginEditor(); }} onClose={() => { clearPairReturn(); setQuickOpen(false); }} />} @@ -437,11 +468,11 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro { if (!value && !busy) setRemoving(null); }}> - {t("remote.forgetTitle", { name: removalProfile?.name })}{t("remote.forgetDescription")} + {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 &&

} -
+
; diff --git a/webui/src/components/remote/RemoteInstances.tsx b/webui/src/components/remote/RemoteInstances.tsx index 26bac669f..914029c30 100644 --- a/webui/src/components/remote/RemoteInstances.tsx +++ b/webui/src/components/remote/RemoteInstances.tsx @@ -2,7 +2,7 @@ import { createContext, useContext, useEffect, useLayoutEffect, useRef, useState import { Loader2, PlugZap } from "lucide-react"; import { useTranslation } from "react-i18next"; import { Button } from "@/components/ui/button"; -import { needsRemoteSetup, type RemoteDirectory } from "@/lib/remote-instances"; +import { groupRemoteProfiles, needsRemoteSetup, type RemoteDirectory } from "@/lib/remote-instances"; import { useHostSessions } from "./useHostSessions"; import { HostNavigationContext, HostSwitcher, RemoteHostMenu, type HostPicker } from "./HostSwitcher"; import { useSidebarHostBridge } from "./useSidebarHostBridge"; @@ -101,7 +101,8 @@ export function RemoteInstances({ children }: { children: ReactNode }) { 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, recentIds: hosts.recentIds, - profiles: (directory?.profiles || []).map(({ id, name, host }) => ({ id, name, host, state: hostStates[id] })), + profiles: groupRemoteProfiles(directory?.profiles || [], selected?.id || null) + .map(({ profile: { id, name, host } }) => ({ id, name, host, state: hostStates[id] })), pending, error: message, offline: !!offline, select: (id) => { if (!id) selectLocal(); diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json index 2361f5cc8..2284d22f9 100644 --- a/webui/src/i18n/locales/en/common.json +++ b/webui/src/i18n/locales/en/common.json @@ -1,5 +1,19 @@ { "remote": { + "sameInstance": { + "forgetAction": "Forget", + "switchHint": "To use another authorization, disconnect the open connection first.", + "title": "This nanobot is already saved", + "saveAndOpen": "Save and open", + "pairHint": "Keep one server entry. This authorization will be saved too; existing connections are kept.", + "details": "Connection details", + "detailsHint": "These connections open the same nanobot. Choose one to use, or manage its authorization.", + "connection": "Connection {{count}}", + "manageConnection": "Manage connection {{count}}", + "forgetConnection": "Forget connection", + "forgetTitle": "Forget this connection?", + "forgetHint": "Only this saved connection will be removed. Other connections and data on the server will stay." + }, "activeForgetWarning": "All tabs using this connection will disconnect. Unsaved work may be lost.", "saved": "Saved", "pair": { @@ -199,7 +213,7 @@ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.", "invalid_profile": "Check the address, port and Connection options fields.", "profile_not_found": "This saved server no longer exists. Refresh the list.", - "profile_limit": "You can save up to 20 servers.", + "profile_limit": "You can save up to 20 connections. Remove an unused authorization in Connection details, or forget an unused server.", "connection_limit": "Disconnect an existing server before opening another connection.", "disconnect_before_edit": "Disconnect this server before editing it.", "local_io_error": "Couldn't save or open the connection. Check local file permissions.", diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json index 6f3e274cc..4fd1bdc70 100644 --- a/webui/src/i18n/locales/es/common.json +++ b/webui/src/i18n/locales/es/common.json @@ -1,5 +1,19 @@ { "remote": { + "sameInstance": { + "forgetAction": "Forget", + "switchHint": "To use another authorization, disconnect the open connection first.", + "title": "This nanobot is already saved", + "saveAndOpen": "Save and open", + "pairHint": "Keep one server entry. This authorization will be saved too; existing connections are kept.", + "details": "Connection details", + "detailsHint": "These connections open the same nanobot. Choose one to use, or manage its authorization.", + "connection": "Connection {{count}}", + "manageConnection": "Manage connection {{count}}", + "forgetConnection": "Forget connection", + "forgetTitle": "Forget this connection?", + "forgetHint": "Only this saved connection will be removed. Other connections and data on the server will stay." + }, "activeForgetWarning": "Se desconectarán todas las pestañas que usen esta conexión. El trabajo sin guardar puede perderse.", "saved": "Guardado", "pair": { @@ -199,7 +213,7 @@ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.", "invalid_profile": "Check the address, port and Connection options fields.", "profile_not_found": "This saved server no longer exists. Refresh the list.", - "profile_limit": "You can save up to 20 servers.", + "profile_limit": "You can save up to 20 connections. Remove an unused authorization in Connection details, or forget an unused server.", "connection_limit": "Disconnect an existing server before opening another connection.", "disconnect_before_edit": "Disconnect this server before editing it.", "local_io_error": "Couldn't save or open the connection. Check local file permissions.", diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json index cd6aee42a..234792e87 100644 --- a/webui/src/i18n/locales/fr/common.json +++ b/webui/src/i18n/locales/fr/common.json @@ -1,5 +1,19 @@ { "remote": { + "sameInstance": { + "forgetAction": "Forget", + "switchHint": "To use another authorization, disconnect the open connection first.", + "title": "This nanobot is already saved", + "saveAndOpen": "Save and open", + "pairHint": "Keep one server entry. This authorization will be saved too; existing connections are kept.", + "details": "Connection details", + "detailsHint": "These connections open the same nanobot. Choose one to use, or manage its authorization.", + "connection": "Connection {{count}}", + "manageConnection": "Manage connection {{count}}", + "forgetConnection": "Forget connection", + "forgetTitle": "Forget this connection?", + "forgetHint": "Only this saved connection will be removed. Other connections and data on the server will stay." + }, "activeForgetWarning": "Tous les onglets utilisant cette connexion seront déconnectés. Le travail non enregistré peut être perdu.", "saved": "Enregistré", "pair": { @@ -199,7 +213,7 @@ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.", "invalid_profile": "Check the address, port and Connection options fields.", "profile_not_found": "This saved server no longer exists. Refresh the list.", - "profile_limit": "You can save up to 20 servers.", + "profile_limit": "You can save up to 20 connections. Remove an unused authorization in Connection details, or forget an unused server.", "connection_limit": "Disconnect an existing server before opening another connection.", "disconnect_before_edit": "Disconnect this server before editing it.", "local_io_error": "Couldn't save or open the connection. Check local file permissions.", diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json index a2bce9c50..ea30ae7f3 100644 --- a/webui/src/i18n/locales/id/common.json +++ b/webui/src/i18n/locales/id/common.json @@ -1,5 +1,19 @@ { "remote": { + "sameInstance": { + "forgetAction": "Forget", + "switchHint": "To use another authorization, disconnect the open connection first.", + "title": "This nanobot is already saved", + "saveAndOpen": "Save and open", + "pairHint": "Keep one server entry. This authorization will be saved too; existing connections are kept.", + "details": "Connection details", + "detailsHint": "These connections open the same nanobot. Choose one to use, or manage its authorization.", + "connection": "Connection {{count}}", + "manageConnection": "Manage connection {{count}}", + "forgetConnection": "Forget connection", + "forgetTitle": "Forget this connection?", + "forgetHint": "Only this saved connection will be removed. Other connections and data on the server will stay." + }, "activeForgetWarning": "Semua tab yang memakai koneksi ini akan terputus. Pekerjaan yang belum disimpan dapat hilang.", "saved": "Tersimpan", "pair": { @@ -199,7 +213,7 @@ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.", "invalid_profile": "Check the address, port and Connection options fields.", "profile_not_found": "This saved server no longer exists. Refresh the list.", - "profile_limit": "You can save up to 20 servers.", + "profile_limit": "You can save up to 20 connections. Remove an unused authorization in Connection details, or forget an unused server.", "connection_limit": "Disconnect an existing server before opening another connection.", "disconnect_before_edit": "Disconnect this server before editing it.", "local_io_error": "Couldn't save or open the connection. Check local file permissions.", diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json index 6e39159ee..ab303e86e 100644 --- a/webui/src/i18n/locales/ja/common.json +++ b/webui/src/i18n/locales/ja/common.json @@ -1,5 +1,19 @@ { "remote": { + "sameInstance": { + "forgetAction": "Forget", + "switchHint": "To use another authorization, disconnect the open connection first.", + "title": "This nanobot is already saved", + "saveAndOpen": "Save and open", + "pairHint": "Keep one server entry. This authorization will be saved too; existing connections are kept.", + "details": "Connection details", + "detailsHint": "These connections open the same nanobot. Choose one to use, or manage its authorization.", + "connection": "Connection {{count}}", + "manageConnection": "Manage connection {{count}}", + "forgetConnection": "Forget connection", + "forgetTitle": "Forget this connection?", + "forgetHint": "Only this saved connection will be removed. Other connections and data on the server will stay." + }, "activeForgetWarning": "この接続を使用しているすべてのタブが切断されます。未保存の内容が失われる可能性があります。", "saved": "保存済み", "pair": { @@ -199,7 +213,7 @@ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.", "invalid_profile": "Check the address, port and Connection options fields.", "profile_not_found": "This saved server no longer exists. Refresh the list.", - "profile_limit": "You can save up to 20 servers.", + "profile_limit": "You can save up to 20 connections. Remove an unused authorization in Connection details, or forget an unused server.", "connection_limit": "Disconnect an existing server before opening another connection.", "disconnect_before_edit": "Disconnect this server before editing it.", "local_io_error": "Couldn't save or open the connection. Check local file permissions.", diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json index 2c1701434..4eb5e9bb5 100644 --- a/webui/src/i18n/locales/ko/common.json +++ b/webui/src/i18n/locales/ko/common.json @@ -1,5 +1,19 @@ { "remote": { + "sameInstance": { + "forgetAction": "Forget", + "switchHint": "To use another authorization, disconnect the open connection first.", + "title": "This nanobot is already saved", + "saveAndOpen": "Save and open", + "pairHint": "Keep one server entry. This authorization will be saved too; existing connections are kept.", + "details": "Connection details", + "detailsHint": "These connections open the same nanobot. Choose one to use, or manage its authorization.", + "connection": "Connection {{count}}", + "manageConnection": "Manage connection {{count}}", + "forgetConnection": "Forget connection", + "forgetTitle": "Forget this connection?", + "forgetHint": "Only this saved connection will be removed. Other connections and data on the server will stay." + }, "activeForgetWarning": "이 연결을 사용하는 모든 탭의 연결이 끊어집니다. 저장하지 않은 내용이 손실될 수 있습니다.", "saved": "저장됨", "pair": { @@ -199,7 +213,7 @@ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.", "invalid_profile": "Check the address, port and Connection options fields.", "profile_not_found": "This saved server no longer exists. Refresh the list.", - "profile_limit": "You can save up to 20 servers.", + "profile_limit": "You can save up to 20 connections. Remove an unused authorization in Connection details, or forget an unused server.", "connection_limit": "Disconnect an existing server before opening another connection.", "disconnect_before_edit": "Disconnect this server before editing it.", "local_io_error": "Couldn't save or open the connection. Check local file permissions.", diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json index 605fc5ad9..4294ec87e 100644 --- a/webui/src/i18n/locales/pt-BR/common.json +++ b/webui/src/i18n/locales/pt-BR/common.json @@ -1,5 +1,19 @@ { "remote": { + "sameInstance": { + "forgetAction": "Forget", + "switchHint": "To use another authorization, disconnect the open connection first.", + "title": "This nanobot is already saved", + "saveAndOpen": "Save and open", + "pairHint": "Keep one server entry. This authorization will be saved too; existing connections are kept.", + "details": "Connection details", + "detailsHint": "These connections open the same nanobot. Choose one to use, or manage its authorization.", + "connection": "Connection {{count}}", + "manageConnection": "Manage connection {{count}}", + "forgetConnection": "Forget connection", + "forgetTitle": "Forget this connection?", + "forgetHint": "Only this saved connection will be removed. Other connections and data on the server will stay." + }, "activeForgetWarning": "Todas as abas que usam esta conexão serão desconectadas. O trabalho não salvo pode ser perdido.", "saved": "Salvo", "pair": { @@ -199,7 +213,7 @@ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.", "invalid_profile": "Check the address, port and Connection options fields.", "profile_not_found": "This saved server no longer exists. Refresh the list.", - "profile_limit": "You can save up to 20 servers.", + "profile_limit": "You can save up to 20 connections. Remove an unused authorization in Connection details, or forget an unused server.", "connection_limit": "Disconnect an existing server before opening another connection.", "disconnect_before_edit": "Disconnect this server before editing it.", "local_io_error": "Couldn't save or open the connection. Check local file permissions.", diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json index 2927be7f8..a72a557fb 100644 --- a/webui/src/i18n/locales/vi/common.json +++ b/webui/src/i18n/locales/vi/common.json @@ -1,5 +1,19 @@ { "remote": { + "sameInstance": { + "forgetAction": "Forget", + "switchHint": "To use another authorization, disconnect the open connection first.", + "title": "This nanobot is already saved", + "saveAndOpen": "Save and open", + "pairHint": "Keep one server entry. This authorization will be saved too; existing connections are kept.", + "details": "Connection details", + "detailsHint": "These connections open the same nanobot. Choose one to use, or manage its authorization.", + "connection": "Connection {{count}}", + "manageConnection": "Manage connection {{count}}", + "forgetConnection": "Forget connection", + "forgetTitle": "Forget this connection?", + "forgetHint": "Only this saved connection will be removed. Other connections and data on the server will stay." + }, "activeForgetWarning": "Tất cả thẻ đang dùng kết nối này sẽ bị ngắt. Nội dung chưa lưu có thể bị mất.", "saved": "Đã lưu", "pair": { @@ -199,7 +213,7 @@ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.", "invalid_profile": "Check the address, port and Connection options fields.", "profile_not_found": "This saved server no longer exists. Refresh the list.", - "profile_limit": "You can save up to 20 servers.", + "profile_limit": "You can save up to 20 connections. Remove an unused authorization in Connection details, or forget an unused server.", "connection_limit": "Disconnect an existing server before opening another connection.", "disconnect_before_edit": "Disconnect this server before editing it.", "local_io_error": "Couldn't save or open the connection. Check local file permissions.", diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json index ae22ecb02..0e6e11ffd 100644 --- a/webui/src/i18n/locales/zh-CN/common.json +++ b/webui/src/i18n/locales/zh-CN/common.json @@ -1,5 +1,19 @@ { "remote": { + "sameInstance": { + "forgetAction": "忘记", + "switchHint": "要使用另一份授权,请先断开当前连接。", + "title": "这个 nanobot 已连接过", + "saveAndOpen": "保存并打开", + "pairHint": "服务器列表只保留一条。这次授权也会保存,已有连接不会被删除。", + "details": "连接详情", + "detailsHint": "这些连接指向同一个 nanobot。选择一个使用,或管理它的授权。", + "connection": "连接 {{count}}", + "manageConnection": "管理连接 {{count}}", + "forgetConnection": "忘记此连接", + "forgetTitle": "忘记此连接?", + "forgetHint": "只移除此电脑上的这条连接,其他连接和服务器上的数据会保留。" + }, "activeForgetWarning": "也会断开正在使用此连接的标签页,未保存的内容可能丢失。", "saved": "已保存", "pair": { @@ -199,7 +213,7 @@ "profile_store_invalid": "无法读取已保存的连接,原文件未被覆盖。", "invalid_profile": "请检查服务器地址、端口和连接选项。", "profile_not_found": "这个连接已不存在,请刷新列表。", - "profile_limit": "最多可以保存 20 台服务器。", + "profile_limit": "最多保存 20 条连接。请先在连接详情中移除不再使用的授权,或忘记不再使用的服务器。", "connection_limit": "请先断开一台服务器,再建立新连接。", "disconnect_before_edit": "请先断开这个服务器,再编辑连接信息。", "local_io_error": "无法保存或打开连接,请检查本机文件权限。", diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json index 5750073c4..9a0bbd132 100644 --- a/webui/src/i18n/locales/zh-TW/common.json +++ b/webui/src/i18n/locales/zh-TW/common.json @@ -1,5 +1,19 @@ { "remote": { + "sameInstance": { + "forgetAction": "忘記", + "switchHint": "若要使用另一份授權,請先中斷目前連線。", + "title": "這個 nanobot 已連線過", + "saveAndOpen": "儲存並開啟", + "pairHint": "伺服器清單只保留一筆。這次授權也會儲存,已有連線不會被刪除。", + "details": "連線詳情", + "detailsHint": "這些連線指向同一個 nanobot。選擇一個使用,或管理它的授權。", + "connection": "連線 {{count}}", + "manageConnection": "管理連線 {{count}}", + "forgetConnection": "忘記此連線", + "forgetTitle": "忘記此連線?", + "forgetHint": "只移除此電腦上的這筆連線,其他連線與伺服器上的資料會保留。" + }, "activeForgetWarning": "也會中斷正在使用此連線的分頁,未儲存的內容可能遺失。", "saved": "已儲存", "pair": { @@ -199,7 +213,7 @@ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.", "invalid_profile": "Check the address, port and Connection options fields.", "profile_not_found": "This saved server no longer exists. Refresh the list.", - "profile_limit": "You can save up to 20 servers.", + "profile_limit": "最多儲存 20 筆連線。請先在連線詳情中移除不再使用的授權,或忘記不再使用的伺服器。", "connection_limit": "Disconnect an existing server before opening another connection.", "disconnect_before_edit": "Disconnect this server before editing it.", "local_io_error": "Couldn't save or open the connection. Check local file permissions.", diff --git a/webui/src/lib/remote-instances.ts b/webui/src/lib/remote-instances.ts index 330a121b9..4ad4097ff 100644 --- a/webui/src/lib/remote-instances.ts +++ b/webui/src/lib/remote-instances.ts @@ -15,10 +15,36 @@ export interface RemoteProfile { view_id?: string; connection_error?: string; paired?: boolean; + /** Opaque grouping ID supplied only after the local backend verifies receipts. */ + instance_id?: string; revoke_command?: string; authorized_until?: number; } +export interface RemoteProfileGroup { + id: string; + profile: RemoteProfile; + connections: RemoteProfile[]; +} + +/** One visible instance; keep every underlying grant available in details. */ +export function groupRemoteProfiles(profiles: RemoteProfile[], currentId: string | null): RemoteProfileGroup[] { + const groups = new Map(); + for (const profile of profiles) { + const id = profile.instance_id || profile.id; + const group = groups.get(id) || []; + group.push(profile); + groups.set(id, group); + } + return [...groups].map(([id, connections]) => { + const preferred = connections.find((item) => item.id === currentId) + || connections.find((item) => item.connected) + || [...connections].reverse().find((item) => item.authorized_until != null && item.authorized_until * 1000 > Date.now()) + || connections[0]; + return { id, profile: { ...preferred, name: connections[0].name }, connections }; + }); +} + /** Persistent setup problems need a repair path, not an endless Retry button. */ export function needsRemoteSetup(code: string): boolean { return /^(pair_|host_key_|ssh_auth_failed$|ssh_agent_refused$|ssh_key_permissions$|ssh_config_|local_file_not_found$|remote_auth_failed$|incompatible_gateway$|webui_disabled$|profile_not_found$)/.test(code); diff --git a/webui/src/tests/quick-pair.test.tsx b/webui/src/tests/quick-pair.test.tsx index a499d0af9..b437f9acc 100644 --- a/webui/src/tests/quick-pair.test.tsx +++ b/webui/src/tests/quick-pair.test.tsx @@ -65,6 +65,22 @@ async function reviewed() { } describe("quick pairing", () => { + it("explains an existing instance and saves its additional authorization only on confirmation", async () => { + mocks.action.mockImplementation(async (action: string) => { + if (action === "remote.pair_preview") return { ...preview, existing_connection: { id: "saved-server", name: "My team", connected: true } }; + if (action === "remote.pair_finish") return { id: "saved-server" }; + return {}; + }); + returnedView(); + await screen.findByRole("heading", { name: "This nanobot is already saved" }); + expect(screen.getByText("My team")).toBeVisible(); + expect(screen.getByText(i18n.t("remote.sameInstance.pairHint"))).toBeVisible(); + expect(mocks.action.mock.calls.some(([action]) => action === "remote.pair_finish")).toBe(false); + expect(mocks.connect).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Save and open" })); + await waitFor(() => expect(mocks.connect).toHaveBeenCalledWith("saved-server", expect.any(Function))); + expect(mocks.action).toHaveBeenCalledWith("remote.pair_finish", { id: "request-1", code: "nbpc1.encrypted" }, 65000); + }); it("introduces remote access with the original logo and no duplicate instruction spacer", async () => { view(); await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled()); diff --git a/webui/src/tests/remote-instances.test.tsx b/webui/src/tests/remote-instances.test.tsx index 5a00c734c..00f079755 100644 --- a/webui/src/tests/remote-instances.test.tsx +++ b/webui/src/tests/remote-instances.test.tsx @@ -91,6 +91,51 @@ function chooseExistingSSH() { } describe("remote instance UX", () => { + it("shows one verified instance in management and the switcher while retaining both grants in details", async () => { + const second = { ...profile, id: "f1b18099-61d5-41d7-9c1d-6f647f7000e5", paired: true, instance_id: profile.id }; + mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, paired: true, instance_id: profile.id }, second] }); + view(); + await openDirectory(); + expect(screen.getAllByRole("button", { name: "Team server ubuntu@example.test" })).toHaveLength(1); + fireEvent.pointerDown(screen.getByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false }); + fireEvent.click(screen.getByRole("menuitem", { name: "Connection details" })); + const details = await screen.findByRole("dialog", { name: "Connection details" }); + expect(within(details).getByRole("button", { name: /^Connection 1 / })).toBeVisible(); + expect(within(details).getByRole("button", { name: /^Connection 2 / })).toBeVisible(); + fireEvent.pointerDown(within(details).getByRole("button", { name: "Manage connection 1" }), { button: 0, ctrlKey: false }); + fireEvent.click(screen.getByRole("menuitem", { name: "Forget connection" })); + expect(await screen.findByRole("dialog", { name: "Forget this connection?" })).toHaveTextContent(i18n.t("remote.sameInstance.forgetHint")); + expect(screen.getByRole("button", { name: "Forget", exact: true })).toBeVisible(); + expect(screen.getByRole("button", { name: "Forget", exact: true }).firstElementChild).not.toHaveClass("truncate"); + expect(screen.queryByRole("button", { name: "Forget server", exact: true })).not.toBeInTheDocument(); + fireEvent.click(screen.getByRole("button", { name: "Cancel", exact: true })); + expect(mocks.request).not.toHaveBeenCalled(); + fireEvent.click(screen.getByRole("button", { name: "Back", exact: true })); + fireEvent.pointerDown(screen.getByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false }); + expect(await screen.findAllByRole("menuitem", { name: "Team server ubuntu@example.test" })).toHaveLength(1); + }); + + it("keeps same-address unverified instances separate and shows their config paths", async () => { + mocks.read.mockResolvedValue({ available: true, profiles: [profile, { ...profile, id: "another", config_path: "/srv/other/config.json" }] }); + view(); await openDirectory(); + expect(screen.getAllByRole("button", { name: "Team server ubuntu@example.test" })).toHaveLength(2); + expect(screen.getByTitle("/srv/other/config.json")).toBeVisible(); + expect(screen.getByTitle(profile.config_path)).toBeVisible(); + }); + + it("requires disconnecting before opening another authorization of an already-connected instance", async () => { + const second = { ...profile, id: "second-grant", connected: true, paired: true, instance_id: profile.id }; + mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, paired: true, instance_id: profile.id }, second] }); + view(); await openDirectory(); + fireEvent.pointerDown(screen.getByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false }); + fireEvent.click(screen.getByRole("menuitem", { name: "Connection details" })); + const details = await screen.findByRole("dialog", { name: "Connection details" }); + expect(within(details).getByRole("button", { name: /^Connection 1 / })).toBeDisabled(); + expect(within(details).getByRole("button", { name: /^Connection 2 / })).toBeEnabled(); + expect(within(details).getByText(i18n.t("remote.sameInstance.switchHint"))).toBeVisible(); + expect(within(details).getByRole("button", { name: "Manage connection 1" })).toBeEnabled(); + expect(mocks.request).not.toHaveBeenCalled(); + }); it("manages connections without changing the remote host, route, frame or authorization", async () => { view(); await chooseHost("Team server ubuntu@example.test"); diff --git a/webui/src/tests/remote-profile-groups.test.ts b/webui/src/tests/remote-profile-groups.test.ts new file mode 100644 index 000000000..f54ab82b7 --- /dev/null +++ b/webui/src/tests/remote-profile-groups.test.ts @@ -0,0 +1,27 @@ +import { describe, expect, it } from "vitest"; +import { groupRemoteProfiles, type RemoteProfile } from "@/lib/remote-instances"; + +const profile: RemoteProfile = { id: "one", name: "Team", host: "ubuntu@server", port: 22, + ssh_config: "", identity_file: "", config_path: "/srv/bot/config.json", runtime_user: "", connected: false }; + +describe("remote instance grouping", () => { + it("does not guess from names, addresses, or restart-scoped gateway IDs", () => { + expect(groupRemoteProfiles([profile, { ...profile, id: "two" }], null)).toHaveLength(2); + expect(groupRemoteProfiles([{ ...profile, gateway_id: "same" }, { ...profile, id: "two", gateway_id: "same" }], null)).toHaveLength(2); + }); + it("keeps all grants but selects the current view before a connected or newer grant", () => { + const old = { ...profile, instance_id: "instance" }; + const renewed = { ...old, id: "two", name: "auto-generated", connected: true }; + const groups = groupRemoteProfiles([old, renewed], "one"); + expect(groups).toHaveLength(1); + expect(groups[0].connections).toEqual([old, renewed]); + expect(groups[0].profile.id).toBe("one"); + expect(groupRemoteProfiles([old, renewed], null)[0].profile).toMatchObject({ id: "two", name: "Team" }); + }); + it("prefers a usable grant when none is selected and does not mutate the directory", () => { + const items = [Object.freeze({ ...profile, instance_id: "same", authorized_until: 1 }), + Object.freeze({ ...profile, id: "two", instance_id: "same", authorized_until: Date.now() / 1000 + 1000 })]; + expect(groupRemoteProfiles(items, null)[0].profile.id).toBe("two"); + expect(items[0].id).toBe("one"); + }); +});