Skip to content

Your lightweight open-source personal agent.

feat(webui): connect to existing remote nanobot instances (NAN-157)

Xubin Ren11889c018e89
diff --git a/docs/guides/remote-instances.md b/docs/guides/remote-instances.md
new file mode 100644
index 000000000..9c4b8d6a3
--- /dev/null
+++ b/docs/guides/remote-instances.md
@@ -0,0 +1,151 @@
+# Connect to an existing remote nanobot
+
+Open your local **nanobot WebUI** and choose **Remote connections** in the sidebar
+(below Channels). Setup opens in the main content area, with the sidebar still
+available. Choose a host from **From your SSH config**, or enter an SSH address
+such as `ubuntu@your-server` using **Connect to remote nanobot…**.
+Give it a recognizable name, then choose **Save & connect**. Next time, select
+the saved server. No port-forwarding command or `.command` launcher is needed.
+
+To add another server, choose **Connect to remote nanobot…** below your saved
+connections. Use a server's menu to edit or forget it. The page supports browser
+back/forward and the `#/remote` route. Leaving setup while SSH is connecting won't
+switch you away from the page you chose when that connection finishes.
+
+This connects to the nanobot **already running on the server**. It does not
+install a worker, clone a workspace, move conversations, or start a second bot.
+It is separate from remote execution/worker deployment.
+
+## Find a server you already use
+
+nanobot lists named hosts from `~/.ssh/config` and the system SSH config, including
+ordinary `Include` files. Search by alias, then select a host to review its setup.
+If your configuration lives elsewhere, expand **Use another SSH config file**
+and enter its local path. Returning from setup keeps the previous list and search.
+
+Discovery is passive: it reads host names and source paths, not private keys,
+and does not contact servers or execute SSH hooks. Wildcard and negated patterns
+aren't destinations. Conditional includes may suggest hosts; only connecting
+checks reachability. Large or dynamic configurations show a partial-list notice;
+you can still enter an alias manually. Discovery is capped at 200 hosts, 64 files,
+256 KiB per file, and approximately 1 MiB in total.
+
+At connection time, the system SSH client resolves your existing `User`, `Port`,
+`IdentityFile`, jump hosts and other connection settings. An empty port field
+inherits SSH configuration instead of overriding it with 22. Listing a host
+does not mean nanobot is installed there. Enter an alias or address, not a full
+shell command.
+
+## Prerequisites
+
+- Run the local WebUI on a loopback address, using the system OpenSSH client.
+- Your SSH key must already have access to the server. Encrypted keys should
+ be unlocked in the system SSH agent. Interactive SSH passwords are not
+ collected by this UI.
+- The remote server needs `python3` and an already running nanobot WebUI with
+ a configured `tokenIssueSecret` (or `token`) in its configuration file.
+- The remote gateway must support the authenticated `/webui/terminal`
+ identity probe, protocol version 1, and have the WebUI bundle installed.
+ The initial transport supports HTTP on the server's loopback address; SSH
+ encrypts the connection. A configured public WebSocket URL is not supported.
+
+If this machine has never connected to the server, nanobot displays its SSH
+fingerprint. Compare it with the server console or your administrator before
+confirming. The public key is pinned for this connection, without changing
+your system `known_hosts`. A **changed** host key is blocked, not automatically
+accepted. Jump-host-only or non-Ed25519 hosts can use a previously verified
+system SSH configuration instead of the in-app first-contact verifier.
+
+## Advanced options
+
+Most setups only need the SSH address. Expand **Advanced** when necessary:
+
+| Option | Meaning |
+| --- | --- |
+| SSH port | Optional override; empty inherits SSH config (normally 22) |
+| SSH config file | Existing local config, including aliases or jump hosts |
+| Private key path | Path to an existing local key; key contents aren't uploaded |
+| nanobot config path | Server-side config, default `~/.nanobot/config.json` |
+| nanobot service account | Optional account owning the remote config; requires existing passwordless `sudo -u` permission |
+
+For a service installation, the SSH login and nanobot owner may differ. For
+example, you might sign in as `ubuntu`, with nanobot running as `nanobot` and
+its config in `/var/lib/nanobot/.nanobot/config.json`. Enter those last two
+values in Advanced. The connection does not grant new sudo privileges.
+
+## Using the remote instance
+
+The remote instance's **own complete WebUI** fills the main window. Its UI
+version follows the server, independently of the local
+installation. Model settings, channels, tools and conversations belong to that
+server. The isolated remote view cannot navigate the local application's
+top-level window. The first version has been exercised in macOS Chrome; native
+desktop-host packaging and other platforms still need their own acceptance.
+
+The host switcher lives beside **Settings at the bottom of the sidebar**, showing
+**Local** or your saved server name. It is also available in Settings. Its menu
+opens upward and shows the computer name, recent hosts, and **Manage connections…**.
+With the sidebar collapsed, the icon still opens the same menu. Recent, loaded
+hosts show **Ready**. Remote
+connection setup is hidden inside the embedded remote view, and connecting back
+to the same gateway is rejected rather than creating a nested local session.
+
+Updated remote WebUIs put the switcher in the same sidebar location. A narrowly
+scoped, origin- and frame-checked bridge sends only the current host's display
+identity and allows its button to open the local shell's menu. The remote page
+does not receive your host directory, SSH configuration, or connection commands.
+Older remote WebUIs retain a compact bottom-strip switcher so you can always
+return local without covering their controls.
+
+Refreshing restores the selected remote instance. A failed connection stays
+on a remote error screen; it never silently redirects work to your local agent.
+The selected server ID is stored per browser tab, without credentials.
+
+- **Switching hosts**, including returning local, keeps both pages mounted and
+ keeps SSH connected. Each host retains its own chat, unsent draft, scroll
+ position and UI state; nothing is copied between hosts. Up to three remote
+ views are kept per tab. At the limit, explicitly disconnect one rather than
+ silently discarding its work. Reloading the browser still follows each
+ instance's normal draft persistence; unfinished uploads aren't guaranteed.
+- A first connection prepares a hidden server page while the current page stays
+ usable. It switches after the page loads; **Cancel switch** keeps you where
+ you are. The most recent choice wins even if an earlier SSH request finishes
+ later. Cancelling navigation does not stop an in-flight server connection.
+ Older server WebUIs can still show their own sign-in/startup indicator after
+ the initial page load; returning to an already loaded view avoids that startup.
+- **Disconnect** in a server's menu confirms before closing its view and shared
+ SSH tunnel. Unsaved view-only work can be lost; the remote bot keeps running.
+ Idle views do not automatically close a tunnel another tab might be using.
+- **Forget server** removes its local connection metadata and pinned public key.
+ It does not delete remote conversations, keys, files, or the installation.
+- Closing the local gateway cleans up its SSH processes. The independently
+ running remote gateway, Linear integration, and scheduled tasks keep running.
+- Connections to the same saved server share one tunnel; explicitly disconnecting
+ it also disconnects other local tabs using that tunnel. Reloading a tab reuses
+ a healthy connection. Up to four servers can be connected concurrently.
+
+## Security and troubleshooting
+
+The local connection directory is stored beside the local config under
+`webui/remote-instances.json`. It contains connection metadata, not private-key
+contents or model/channel credentials. A stable loopback port per saved server
+keeps browser preferences scoped to that server. Port conflicts fail explicitly;
+nanobot does not attach to an unrelated listener.
+
+SSH authenticates the server. A read-only, fixed Python probe retrieves only
+WebUI login information from its config. The gateway's protocol and runtime ID
+are verified before navigation. The WebUI credential is held by the live
+connection and passed in the remote view's URL fragment, not an HTTP query or
+local model configuration. The remote WebUI uses its existing browser login
+storage. Nothing opens a public administration port or forwards your SSH agent.
+
+Remote-connection actions require an authenticated local WebUI connection, a
+loopback-bound gateway, and local request origin. They are unavailable from a
+public/reverse-proxied administration page. Connecting requires server admin
+access; permission to mention nanobot in Linear is **not** that permission.
+
+Common errors explain whether SSH authentication, a missing config, a service
+account, WebUI authentication, protocol compatibility or networking failed.
+Configurations whose WebUI secret is supplied only by a service environment,
+interactive SSH passwords, and remote WebUIs with a public WebSocket URL need
+additional setup; this flow does not silently weaken their authentication.
diff --git a/nanobot/channels/websocket/runtime.py b/nanobot/channels/websocket/runtime.py
index 05df43843..927e7986a 100644
--- a/nanobot/channels/websocket/runtime.py
+++ b/nanobot/channels/websocket/runtime.py
@@ -676,6 +676,7 @@ class WebSocketChannel(BaseChannel):
)
async def start(self) -> None:
+ self.gateway.http.remote_instances.resume()
from nanobot.utils.logging_bridge import redirect_lib_logging
redirect_lib_logging("websockets", level="WARNING")
@@ -880,6 +881,7 @@ class WebSocketChannel(BaseChannel):
# -- Outbound WebSocket events -----------------------------------------
async def stop(self) -> None:
+ await self.gateway.http.remote_instances.close()
server_task = self._server_task
if (
not self._running
diff --git a/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py b/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py
index feee6e51f..64f719538 100644
--- a/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py
+++ b/nanobot/channels/websocket/tests/test_websocket_runtime_lifecycle.py
@@ -45,6 +45,7 @@ def _channel() -> WebSocketChannel:
gateway = MagicMock()
gateway.session_manager = None
gateway.http.settings_routes.close = AsyncMock()
+ gateway.http.remote_instances.close = AsyncMock()
return WebSocketChannel(
{"enabled": True, "allowFrom": ["*"]},
MessageBus(),
diff --git a/nanobot/webui/remote_instances.py b/nanobot/webui/remote_instances.py
new file mode 100644
index 000000000..35aeea115
--- /dev/null
+++ b/nanobot/webui/remote_instances.py
@@ -0,0 +1,251 @@
+"""Local connection directory. Owns SSH tunnels, never remote gateway lifetimes."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import secrets
+import socket
+import time
+import uuid
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, cast
+from urllib.parse import quote
+
+import httpx
+from pydantic import Field
+
+from nanobot.utils.helpers import _write_text_atomic # pyright: ignore[reportPrivateUsage]
+from nanobot.webui import remote_ssh
+from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, Tunnel
+
+
+class _SavedProfile(RemoteProfile):
+ # Retain an origin per server so browser preferences/caches cannot drift
+ # between servers on every reconnect. Not an editable API field.
+ local_port: int = Field(default=0, ge=0, le=65535)
+
+
+@dataclass
+class Connection:
+ tunnel: Tunnel
+ secret: str
+ hostname: str
+ config_path: str
+ gateway_id: str
+ error: str = ""
+
+
+class RemoteInstances:
+ """List/save/connect/disconnect with credentials confined to live connections."""
+
+ def __init__(self, directory: Path, *, local_gateway_id: str = "") -> None:
+ self.path = directory / "remote-instances.json"
+ self.local_gateway_id = local_gateway_id
+ self.connections: dict[str, Connection] = {}
+ self._lock = asyncio.Lock()
+ self._unverified: dict[str, tuple[str, str, float]] = {}
+ self._unknown_hosts: set[str] = set()
+ self._closed = False
+
+ def _known_hosts(self, key: str) -> Path:
+ return self.path.parent / "remote-hosts" / key
+
+ def resume(self) -> None:
+ """Allow a reused local channel to start again after its stop completed."""
+ self._closed = False
+
+ def _read(self) -> dict[str, _SavedProfile]:
+ if not self.path.exists():
+ return {}
+ try:
+ raw = json.loads(self.path.read_text(encoding="utf-8"))
+ if not isinstance(raw, dict):
+ raise ValueError
+ return {str(uuid.UUID(key)): _SavedProfile.model_validate(value)
+ for key, value in cast(dict[str, Any], raw).items()}
+ except (ValueError, TypeError, OSError):
+ raise RemoteError("profile_store_invalid") from None
+
+ def _write(self, profiles: dict[str, _SavedProfile]) -> None:
+ self.path.parent.mkdir(parents=True, exist_ok=True)
+ _write_text_atomic(self.path, json.dumps(
+ {key: profile.model_dump() for key, profile in profiles.items()}, ensure_ascii=False,
+ ))
+ self.path.chmod(0o600)
+
+ def snapshot(self) -> dict[str, Any]:
+ return {"available": True, "machine_name": socket.gethostname(), "profiles": [
+ {"id": key, **profile.model_dump(exclude={"local_port"}),
+ "connected": key in self.connections
+ and self.connections[key].tunnel.process.returncode is None
+ and not self.connections[key].error}
+ for key, profile in self._read().items()
+ ]}
+
+ async def health(self) -> dict[str, Any]:
+ async def check(connection: Connection) -> None:
+ if connection.tunnel.process.returncode is not None:
+ connection.error = "ssh_unreachable"
+ return
+ try:
+ async with httpx.AsyncClient(timeout=8, trust_env=False) as client:
+ response = await client.get(
+ f"http://127.0.0.1:{connection.tunnel.port}/webui/terminal",
+ headers={"X-Nanobot-Auth": connection.secret},
+ )
+ if response.status_code != 200:
+ connection.error = "remote_unreachable"
+ elif response.json().get("gatewayId") != connection.gateway_id:
+ connection.error = "instance_changed"
+ else:
+ connection.error = ""
+ except (httpx.HTTPError, ValueError, AttributeError):
+ connection.error = "remote_unreachable"
+
+ await asyncio.gather(*(check(item) for item in tuple(self.connections.values())))
+ return self.snapshot()
+
+ async def action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:
+ if action == "discover":
+ from nanobot.webui.ssh_config import discover_hosts
+
+ config_file = payload.get("ssh_config", "")
+ if not isinstance(config_file, str):
+ raise RemoteError("invalid_profile")
+ discovery = await asyncio.to_thread(discover_hosts, config_file)
+ return dict(discovery)
+ async with self._lock:
+ if self._closed:
+ raise RemoteError("local_io_error")
+ profiles = self._read()
+ key = str(payload.get("id", ""))
+ if action == "save":
+ profile = RemoteProfile.model_validate(payload.get("profile"))
+ if key and key not in profiles:
+ raise RemoteError("profile_not_found")
+ if not key and len(profiles) >= 20:
+ raise RemoteError("profile_limit")
+ key = key or str(uuid.uuid4())
+ if key in self.connections:
+ raise RemoteError("disconnect_before_edit")
+ target_changed = key in profiles and any(
+ getattr(profiles[key], field) != getattr(profile, field)
+ for field in ("host", "port", "ssh_config")
+ )
+ if target_changed:
+ self._known_hosts(key).unlink(missing_ok=True)
+ self._unverified.pop(key, None)
+ self._unknown_hosts.discard(key)
+ local_port = profiles[key].local_port if key in profiles and not target_changed else 0
+ profiles[key] = _SavedProfile(**profile.model_dump(), local_port=local_port)
+ self._write(profiles)
+ return {"id": key, **self.snapshot()}
+ if key not in profiles:
+ raise RemoteError("profile_not_found")
+ if action == "connect":
+ try:
+ return await self._connect(key, profiles[key])
+ except RemoteError as exc:
+ if str(exc) == "host_key_unknown":
+ self._unknown_hosts.add(key)
+ else:
+ self._unknown_hosts.discard(key)
+ raise
+ if action == "fingerprint":
+ if key not in self._unknown_hosts or self._known_hosts(key).exists():
+ raise RemoteError("host_key_changed")
+ known_host, fingerprint = await remote_ssh.scan_host_key(profiles[key])
+ challenge = secrets.token_urlsafe(24)
+ self._unverified[key] = (challenge, known_host, time.monotonic() + 300)
+ return {"fingerprint": fingerprint, "challenge": challenge}
+ if action == "trust":
+ pending = self._unverified.pop(key, None)
+ if (not pending or pending[2] < time.monotonic()
+ or not secrets.compare_digest(pending[0], str(payload.get("challenge", "")))
+ or key not in self._unknown_hosts or self._known_hosts(key).exists()):
+ raise RemoteError("host_key_changed")
+ path = self._known_hosts(key)
+ path.parent.mkdir(parents=True, exist_ok=True)
+ _write_text_atomic(path, pending[1])
+ path.chmod(0o600)
+ self._unknown_hosts.discard(key)
+ return {"trusted": True}
+ if action in {"disconnect", "remove"}:
+ connection = self.connections.pop(key, None)
+ if connection:
+ await connection.tunnel.close()
+ if action == "remove":
+ del profiles[key]
+ self._write(profiles)
+ self._known_hosts(key).unlink(missing_ok=True)
+ self._unknown_hosts.discard(key)
+ self._unverified.pop(key, None)
+ return self.snapshot()
+ raise RemoteError("unknown_action")
+
+ def _launch(self, key: str, profile: RemoteProfile, connection: Connection) -> dict[str, Any]:
+ return {"id": key, "name": profile.name, "host": profile.host,
+ "hostname": connection.hostname, "config_path": connection.config_path,
+ "url": f"http://127.0.0.1:{connection.tunnel.port}/#/?bootstrapSecret={quote(connection.secret, safe='')}",
+ "gateway_id": connection.gateway_id}
+
+ async def _connect(self, key: str, profile: _SavedProfile) -> dict[str, Any]:
+ existing = self.connections.get(key)
+ if existing:
+ await self.health()
+ if not existing.error:
+ return self._launch(key, profile, existing)
+ await existing.tunnel.close()
+ del self.connections[key]
+ if len(self.connections) >= 4:
+ raise RemoteError("connection_limit")
+ known_hosts = self._known_hosts(key)
+ data = await remote_ssh.probe(profile, known_hosts)
+ tunnel = await remote_ssh.open_tunnel(profile, data["port"], known_hosts, profile.local_port)
+ base = f"http://127.0.0.1:{tunnel.port}"
+ try:
+ async with httpx.AsyncClient(timeout=8, trust_env=False, follow_redirects=False) as client:
+ response = await client.get(
+ f"{base}/webui/terminal", headers={"X-Nanobot-Auth": data["secret"]},
+ )
+ if response.status_code in {401, 403}:
+ raise RemoteError("remote_auth_failed")
+ if response.status_code != 200:
+ raise RemoteError("incompatible_gateway")
+ raw_identity = response.json()
+ if not isinstance(raw_identity, dict):
+ raise RemoteError("incompatible_gateway")
+ identity = cast(dict[str, Any], raw_identity)
+ if (identity.get("protocolVersion") != 1
+ or not isinstance(identity.get("gatewayId"), str)):
+ raise RemoteError("incompatible_gateway")
+ if identity["gatewayId"] == self.local_gateway_id:
+ raise RemoteError("same_instance")
+ # Require the installed WebUI too, not just a port answering HTTP.
+ page = await client.get(base + "/")
+ if page.status_code != 200 or "text/html" not in page.headers.get("content-type", ""):
+ raise RemoteError("webui_unavailable")
+ connection = Connection(
+ tunnel, data["secret"], str(data.get("hostname", profile.host)),
+ str(data.get("config_path", profile.config_path)), identity["gatewayId"],
+ )
+ profiles = self._read()
+ profiles[key].local_port = tunnel.port
+ self._write(profiles)
+ self.connections[key] = connection
+ return self._launch(key, profile, connection)
+ except BaseException as exc:
+ await tunnel.close()
+ if isinstance(exc, httpx.HTTPError):
+ raise RemoteError("remote_unreachable") from None
+ if isinstance(exc, ValueError):
+ raise RemoteError("incompatible_gateway") from None
+ raise
+
+ async def close(self) -> None:
+ self._closed = True
+ async with self._lock:
+ connections, self.connections = self.connections, {}
+ await asyncio.gather(*(item.tunnel.close() for item in connections.values()))
diff --git a/nanobot/webui/remote_ssh.py b/nanobot/webui/remote_ssh.py
new file mode 100644
index 000000000..7f7817308
--- /dev/null
+++ b/nanobot/webui/remote_ssh.py
@@ -0,0 +1,262 @@
+"""SSH-only access to an existing nanobot. Never installs or starts a remote process.
+
+The system SSH client owns key/agent authentication and host verification. Probe
+output is private: only the WebUI credential is read, never provider credentials.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import base64
+import hashlib
+import json
+import shlex
+import shutil
+import socket
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any, cast
+
+from pydantic import BaseModel, ConfigDict, Field, field_validator
+
+
+class RemoteError(Exception):
+ """A stable, non-secret error code for the connection UI."""
+
+
+class RemoteProfile(BaseModel):
+ model_config = ConfigDict(extra="forbid", str_strip_whitespace=True)
+
+ name: str = Field(min_length=1, max_length=64)
+ host: str = Field(min_length=1, max_length=253, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9._:@-]*$")
+ port: int | None = Field(default=None, ge=1, le=65535)
+ ssh_config: str = Field(default="", max_length=2048)
+ identity_file: str = Field(default="", max_length=2048)
+ config_path: str = Field(default="~/.nanobot/config.json", min_length=1, max_length=2048)
+ runtime_user: str = Field(default="", max_length=64, pattern=r"^([a-zA-Z_][a-zA-Z0-9_-]*)?$")
+
+ @field_validator("ssh_config", "identity_file", "config_path")
+ @classmethod
+ def safe_path(cls, value: str) -> str:
+ if any(ord(char) < 32 for char in value):
+ raise ValueError("control characters are not allowed")
+ return value
+
+
+# Fixed program, quoted as one shell argument. No user-supplied shell commands.
+_PROBE = r'''
+import json, os, pathlib, socket, sys
+try:
+ path = pathlib.Path(sys.argv[1]).expanduser()
+ data = json.loads(path.read_text())
+ ws = data.get("channels", {}).get("websocket", {})
+ secret = ws.get("tokenIssueSecret") or ws.get("token_issue_secret") or ws.get("token")
+ if not ws.get("enabled"):
+ raise ValueError("webui_disabled")
+ if not isinstance(secret, str) or not secret.strip() or "${" in secret:
+ raise ValueError("webui_auth_required")
+ if ws.get("publicWsUrl") or ws.get("public_ws_url"):
+ raise ValueError("public_ws_unsupported")
+ print(json.dumps({"port": ws.get("port", 8765), "secret": secret,
+ "hostname": socket.gethostname(), "config_path": str(path)}))
+except FileNotFoundError:
+ print(json.dumps({"error": "config_not_found"}))
+except PermissionError:
+ print(json.dumps({"error": "config_permission"}))
+except ValueError as e:
+ code = str(e)
+ print(json.dumps({"error": code if code in {"webui_disabled", "webui_auth_required", "public_ws_unsupported"} else "config_invalid"}))
+'''
+
+
+def ssh_arguments(profile: RemoteProfile, known_hosts: Path | None = None) -> list[str]:
+ executable = shutil.which("ssh")
+ if not executable:
+ raise RemoteError("ssh_unavailable")
+ args = [executable]
+ for flag, value in [("-F", profile.ssh_config), ("-i", profile.identity_file)]:
+ if value:
+ path = Path(value).expanduser()
+ if not path.is_file():
+ raise RemoteError("local_file_not_found")
+ args.extend([flag, str(path)])
+ # CLI options override config. Never forward the agent or reuse an unrelated
+ # multiplexed session (whose identity/forwarding policy could be different).
+ args.extend([
+ "-o", "BatchMode=yes", "-o", "StrictHostKeyChecking=yes",
+ "-o", "ForwardAgent=no", "-o", "ForwardX11=no", "-o", "PermitLocalCommand=no",
+ "-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=10",
+ "-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=2",
+ "-o", "ExitOnForwardFailure=yes", "-o", "RequestTTY=no",
+ ])
+ if profile.port is not None:
+ args.extend(["-p", str(profile.port)])
+ if known_hosts and known_hosts.is_file():
+ args.extend(["-o", f"UserKnownHostsFile={known_hosts}", "-o", "GlobalKnownHostsFile=none",
+ "-o", "HostKeyAlias=nanobot-remote", "-o", "HostKeyAlgorithms=ssh-ed25519",
+ "-o", "UpdateHostKeys=no"])
+ return args
+
+
+def ssh_error(stderr: bytes) -> str:
+ text = stderr.decode("utf-8", errors="replace").lower()
+ if "host identification has changed" in text:
+ return "host_key_changed"
+ if "host key verification failed" in text or "no ed25519 host key is known" in text:
+ return "host_key_unknown"
+ if "permission denied" in text:
+ return "ssh_auth_failed"
+ if "sudo:" in text:
+ return "runtime_user_denied"
+ if "python3" in text and "not found" in text:
+ return "python_unavailable"
+ return "ssh_unreachable"
+
+
+async def stop_process(process: asyncio.subprocess.Process) -> None:
+ if process.returncode is None:
+ try:
+ process.terminate()
+ except ProcessLookupError:
+ pass
+ try:
+ await asyncio.wait_for(process.wait(), 3)
+ except TimeoutError:
+ try:
+ process.kill()
+ except ProcessLookupError:
+ pass
+ await process.wait()
+
+
+async def probe(profile: RemoteProfile, known_hosts: Path | None = None) -> dict[str, Any]:
+ remote = ["python3", "-c", _PROBE, profile.config_path]
+ if profile.runtime_user:
+ remote = ["sudo", "-n", "-H", "-u", profile.runtime_user, "--", *remote]
+ process = await asyncio.create_subprocess_exec(
+ *ssh_arguments(profile, known_hosts), profile.host, shlex.join(remote),
+ stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.PIPE,
+ )
+ try:
+ stdout, stderr = await asyncio.wait_for(process.communicate(), 20)
+ if process.returncode:
+ raise RemoteError(ssh_error(stderr))
+ try:
+ raw = json.loads(stdout)
+ if not isinstance(raw, dict):
+ raise ValueError
+ data = cast(dict[str, Any], raw)
+ if data.get("error"):
+ raise RemoteError(str(data["error"]))
+ if not isinstance(data.get("secret"), str) or not data["secret"]:
+ raise ValueError
+ if type(data.get("port")) is not int or not 1 <= data["port"] <= 65535:
+ raise ValueError
+ return data
+ except (ValueError, TypeError):
+ raise RemoteError("config_invalid") from None
+ except TimeoutError:
+ raise RemoteError("ssh_unreachable") from None
+ finally:
+ await stop_process(process)
+
+
+@dataclass
+class Tunnel:
+ process: asyncio.subprocess.Process
+ port: int
+
+ async def close(self) -> None:
+ await stop_process(self.process)
+
+
+async def open_tunnel(
+ profile: RemoteProfile, remote_port: int, known_hosts: Path | None = None,
+ local_port: int = 0,
+) -> Tunnel:
+ # Reserve a loopback candidate. SSH remains responsible for binding and
+ # ExitOnForwardFailure ensures a collision cannot connect us to another app.
+ with socket.socket() as candidate:
+ try:
+ # Match OpenSSH's listener policy: a just-closed tunnel can leave
+ # TIME_WAIT connections without another program owning the port.
+ candidate.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ candidate.bind(("127.0.0.1", local_port))
+ candidate.listen(1)
+ except OSError:
+ raise RemoteError("local_port_in_use") from None
+ port = int(candidate.getsockname()[1])
+ process = await asyncio.create_subprocess_exec(
+ *ssh_arguments(profile, known_hosts), "-N", "-L", f"127.0.0.1:{port}:127.0.0.1:{remote_port}",
+ profile.host, stdin=asyncio.subprocess.DEVNULL,
+ stdout=asyncio.subprocess.DEVNULL, stderr=asyncio.subprocess.PIPE,
+ )
+ tunnel = Tunnel(process, port)
+ try:
+ for _ in range(100):
+ if process.returncode is not None:
+ stderr = await process.stderr.read() if process.stderr else b""
+ raise RemoteError(ssh_error(stderr))
+ try:
+ reader, writer = await asyncio.wait_for(
+ asyncio.open_connection("127.0.0.1", port), 0.2,
+ )
+ del reader
+ writer.close()
+ await writer.wait_closed()
+ return tunnel
+ except (OSError, TimeoutError):
+ await asyncio.sleep(0.1)
+ raise RemoteError("ssh_unreachable")
+ except BaseException:
+ await tunnel.close()
+ raise
+
+
+async def scan_host_key(profile: RemoteProfile) -> tuple[str, str]:
+ """Return an UNVERIFIED key and fingerprint, never silently trust it.
+
+ Resolve SSH aliases with the user's own config. Scanning is deliberately
+ direct; jump-host-only setups should verify via their existing SSH config.
+ """
+ keyscan = shutil.which("ssh-keyscan")
+ if not keyscan:
+ raise RemoteError("ssh_unavailable")
+ process = await asyncio.create_subprocess_exec(
+ *ssh_arguments(profile), "-G", profile.host,
+ stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.DEVNULL,
+ )
+ try:
+ output, _ = await asyncio.wait_for(process.communicate(), 10)
+ if process.returncode:
+ raise RemoteError("ssh_unreachable")
+ finally:
+ await stop_process(process)
+ settings = dict(line.split(" ", 1) for line in output.decode().splitlines() if " " in line)
+ hostname, port = settings.get("hostname", ""), settings.get("port", "22")
+ if not hostname or hostname.startswith("-") or not port.isdigit():
+ raise RemoteError("invalid_profile")
+ scan = await asyncio.create_subprocess_exec(
+ keyscan, "-T", "5", "-p", port, "-t", "ed25519", hostname,
+ stdin=asyncio.subprocess.DEVNULL, stdout=asyncio.subprocess.PIPE,
+ stderr=asyncio.subprocess.DEVNULL,
+ )
+ try:
+ output, _ = await asyncio.wait_for(scan.communicate(), 8)
+ for line in output.decode().splitlines():
+ fields = line.split()
+ if len(fields) != 3 or fields[1] != "ssh-ed25519":
+ continue
+ try:
+ binary = base64.b64decode(fields[2], validate=True)
+ except ValueError:
+ continue
+ fingerprint = "SHA256:" + base64.b64encode(hashlib.sha256(binary).digest()).decode().rstrip("=")
+ return f"nanobot-remote ssh-ed25519 {fields[2]}\n", fingerprint
+ raise RemoteError("host_key_scan_failed")
+ except TimeoutError:
+ raise RemoteError("host_key_scan_failed") from None
+ finally:
+ await stop_process(scan)
diff --git a/nanobot/webui/ssh_config.py b/nanobot/webui/ssh_config.py
new file mode 100644
index 000000000..057e4692d
--- /dev/null
+++ b/nanobot/webui/ssh_config.py
@@ -0,0 +1,126 @@
+"""Discover named SSH targets without running SSH, shell hooks, or contacting hosts.
+
+This is a bounded name index, not an SSH configuration evaluator. OpenSSH still
+resolves User, Port, IdentityFile, ProxyJump and Match at connection time.
+"""
+
+from __future__ import annotations
+
+import glob
+import os
+import re
+import shlex
+import stat
+from pathlib import Path
+from typing import TypedDict
+
+from nanobot.webui.remote_ssh import RemoteError
+
+
+class SSHHost(TypedDict):
+ host: str
+ source: str
+ ssh_config: str
+
+
+class SSHDiscovery(TypedDict):
+ hosts: list[SSHHost]
+ files: list[str]
+ incomplete: bool
+
+
+def discover_hosts(config_file: str = "") -> SSHDiscovery:
+ """Read literal Host names, including Include files, with no side effects.
+
+ Wildcard/negated Host patterns are not destinations. Conditional includes
+ may contribute suggestions; those are not claims that a host is reachable.
+ Only names and source paths are returned, never arbitrary config contents.
+ """
+ if len(config_file) > 2048 or any(ord(char) < 32 for char in config_file):
+ raise RemoteError("invalid_profile")
+ home = Path.home()
+ user_ssh = home / ".ssh"
+ system_ssh = (Path(os.environ.get("PROGRAMDATA", "C:/ProgramData")) / "ssh"
+ if os.name == "nt" else Path("/etc/ssh"))
+ roots = [(Path(config_file).expanduser(), user_ssh)] if config_file else [
+ (user_ssh / "config", user_ssh), (system_ssh / "ssh_config", system_ssh),
+ ]
+ result: SSHDiscovery = {"hosts": [], "files": [], "incomplete": False}
+ visited: set[Path] = set()
+ names: set[str] = set()
+ bytes_read = 0
+
+ def visit(path: Path, base: Path, *, required: bool = False) -> None:
+ nonlocal bytes_read
+ try:
+ path = path.resolve()
+ if path in visited:
+ return
+ if len(visited) >= 64 or bytes_read >= 1_048_576:
+ result["incomplete"] = True
+ return
+ visited.add(path)
+ info = path.stat()
+ if not stat.S_ISREG(info.st_mode) or info.st_size > 262_144:
+ raise ValueError
+ # Bound reads too, even if the file grows after stat().
+ with path.open("rb") as stream:
+ content = stream.read(min(262_145, 1_048_577 - bytes_read))
+ bytes_read += len(content)
+ if len(content) > 262_144 or bytes_read > 1_048_576:
+ raise ValueError
+ lines = content.decode("utf-8").splitlines()
+ except FileNotFoundError:
+ if required:
+ raise RemoteError("local_file_not_found") from None
+ return
+ except (OSError, ValueError, RuntimeError):
+ if required:
+ raise RemoteError("ssh_config_unreadable") from None
+ result["incomplete"] = True
+ return
+ result["files"].append(str(path))
+ for line in lines:
+ match = re.match(r"^\s*(Host|Include)(?:\s*=\s*|\s+)(.*)$", line, re.I)
+ if not match:
+ continue
+ try:
+ values = shlex.split(match[2], comments=True)
+ except ValueError:
+ result["incomplete"] = True
+ continue
+ if match[1].lower() == "host":
+ for name in values:
+ if (len(name) > 253 or not re.fullmatch(r"[a-zA-Z0-9][a-zA-Z0-9._:@-]*", name)
+ or name.casefold() in names):
+ continue
+ if len(result["hosts"]) >= 200:
+ result["incomplete"] = True
+ return
+ names.add(name.casefold())
+ result["hosts"].append({"host": name, "source": str(path),
+ "ssh_config": str(roots[0][0].expanduser()) if config_file else ""})
+ else:
+ for pattern in values:
+ # Tokens/environment-dependent paths cannot be resolved without
+ # a target. Leave them to SSH; never invoke `ssh -G` on page load
+ # because Match exec can execute arbitrary local commands.
+ if "$" in pattern or "%" in pattern:
+ result["incomplete"] = True
+ continue
+ expanded = Path(pattern).expanduser()
+ if not expanded.is_absolute():
+ expanded = base / expanded
+ matches = glob.iglob(str(expanded))
+ paths: list[str] = []
+ for candidate in matches:
+ if len(paths) >= 64:
+ result["incomplete"] = True
+ break
+ paths.append(candidate)
+ for candidate in sorted(paths):
+ visit(Path(candidate), base)
+
+ for root, base in roots:
+ visit(root, base, required=bool(config_file))
+ return result
diff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.py
index 33b222258..620e3b5db 100644
--- a/nanobot/webui/ws_http.py
+++ b/nanobot/webui/ws_http.py
@@ -164,6 +164,13 @@ class _WebUIThreadDiagnostics:
event_loop_lag_ms: float = 0.0
_WEBUI_MUTATION_PATHS = {
+ "remote.discover": "/api/remote-instances/discover",
+ "remote.save": "/api/remote-instances/save",
+ "remote.connect": "/api/remote-instances/connect",
+ "remote.disconnect": "/api/remote-instances/disconnect",
+ "remote.remove": "/api/remote-instances/remove",
+ "remote.fingerprint": "/api/remote-instances/fingerprint",
+ "remote.trust": "/api/remote-instances/trust",
"automation.enable": "/api/webui/automations/enable",
"automation.disable": "/api/webui/automations/disable",
"automation.delete": "/api/webui/automations/delete",
@@ -372,6 +379,11 @@ class GatewayHTTPHandler:
self.ingress = ingress
self.workspaces = workspaces
self.settings = settings
+ from nanobot.webui.remote_instances import RemoteInstances
+
+ self.remote_instances = RemoteInstances(
+ settings.config.path.parent / "webui", local_gateway_id=tokens.instance_id,
+ )
self.skills_workspace_path = skills_workspace_path
self.disabled_skills: set[str] = (
disabled_skills if disabled_skills is not None else set()
@@ -512,6 +524,8 @@ class GatewayHTTPHandler:
return _http_error(404, "WebUI mutation action not found")
def _is_webui_mutation_path(self, path: str) -> bool:
+ if path.startswith("/api/remote-instances/"):
+ return True
if self.settings_routes.is_mutation_path(path):
return True
if re.match(r"^/api/sessions/[^/]+/delete$", path):
@@ -560,6 +574,8 @@ class GatewayHTTPHandler:
request: WsRequest,
got: str,
) -> Any | None:
+ if got == "/api/remote-instances" or got.startswith("/api/remote-instances/"):
+ return await self._dispatch_remote_instances(connection, request, got)
# Token issue endpoint
if self.config.token_issue_path:
issue_expected = _normalize_config_path(self.config.token_issue_path)
@@ -617,6 +633,38 @@ class GatewayHTTPHandler:
return connection.respond(404, "Not Found")
+ async def _dispatch_remote_instances(
+ self, connection: Any, request: WsRequest, path: str,
+ ) -> Response:
+ from pydantic import ValidationError
+
+ from nanobot.webui.remote_ssh import RemoteError
+
+ if not self.check_api_token(request):
+ return _http_error(401, "Unauthorized")
+ # A public/reverse-proxied WebUI must never gain access to this machine's
+ # SSH agent, private keys or network. Same checks as local folder picking.
+ if not (_is_loopback_host(self.config.host)
+ and _is_local_browser_request(connection, request.headers)):
+ return _http_error(403, "remote_connections_local_only")
+ origin = request.headers.get("Origin", "")
+ if origin and not _is_loopback_host(urlsplit(origin).hostname or ""):
+ return _http_error(403, "remote_connections_local_only")
+ try:
+ if path == "/api/remote-instances":
+ return _http_json_response(await self.remote_instances.health(), extra_headers=_NO_STORE_HEADERS)
+ if not getattr(request, _WEBUI_MUTATION_REQUEST_ATTR, False):
+ return _http_error(405, "WebSocket required")
+ payload = getattr(request, _WEBUI_MUTATION_PAYLOAD_ATTR, {})
+ result = await self.remote_instances.action(path.rsplit("/", 1)[-1], payload)
+ return _http_json_response(result, extra_headers=_NO_STORE_HEADERS)
+ except RemoteError as exc:
+ return _http_error(400, str(exc))
+ except ValidationError:
+ return _http_error(400, "invalid_profile")
+ except OSError:
+ return _http_error(500, "local_io_error")
+
def _log_slow_http(self, path: str, response: Any | None, started: float) -> None:
elapsed_ms = int((time.perf_counter() - started) * 1000)
if elapsed_ms < _SLOW_WEBUI_HTTP_LOG_MS:
diff --git a/tests/webui/test_remote_instances.py b/tests/webui/test_remote_instances.py
new file mode 100644
index 000000000..3a26e4f19
--- /dev/null
+++ b/tests/webui/test_remote_instances.py
@@ -0,0 +1,286 @@
+"""Connection boundaries: no deployment, copied model keys or remote shutdown."""
+
+import asyncio
+import json
+import socket
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import httpx
+import pytest
+from pydantic import ValidationError
+from websockets.datastructures import Headers
+from websockets.http11 import Request
+
+from nanobot.channels.websocket.runtime import WebSocketConfig
+from nanobot.webui import remote_ssh
+from nanobot.webui.gateway_services import build_gateway_services
+from nanobot.webui.remote_instances import RemoteInstances
+from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, ssh_arguments, ssh_error
+
+
+def manager(tmp_path):
+ return RemoteInstances(tmp_path)
+
+
+async def save(manager, **values):
+ result = await manager.action("save", {"profile": {"name": "Team", "host": "[email protected]", **values}})
+ return result["id"]
+
+
+def ssh(monkeypatch):
+ process = SimpleNamespace(returncode=None)
+ tunnel = SimpleNamespace(process=process, port=23456, close=AsyncMock())
+ probe = AsyncMock(return_value={"port": 8765, "secret": "private-webui-secret", "hostname": "team-host"})
+ monkeypatch.setattr(remote_ssh, "probe", probe)
+ monkeypatch.setattr(remote_ssh, "open_tunnel", AsyncMock(return_value=tunnel))
+ state = {"status": 200, "identity": {"protocolVersion": 1, "gatewayId": "remote-one"}}
+
+ def respond(request):
+ if request.url.path == "/webui/terminal":
+ assert request.headers["X-Nanobot-Auth"] == "private-webui-secret"
+ return httpx.Response(state["status"], json=state["identity"])
+ return httpx.Response(200, text="<!doctype html><title>nanobot</title>", headers={"content-type": "text/html"})
+
+ real_client = httpx.AsyncClient
+ monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: real_client(transport=httpx.MockTransport(respond), **kwargs))
+ return SimpleNamespace(tunnel=tunnel, probe=probe, state=state)
+
+
+async def test_save_survives_restart_without_credentials(manager):
+ key = await save(manager)
+ assert RemoteInstances(manager.path.parent).snapshot()["profiles"][0]["id"] == key
+ assert "secret" not in manager.path.read_text()
+ with pytest.raises(ValidationError):
+ await save(manager, private_key="must-never-save")
+
+
[email protected]("host", ["-oProxyCommand=evil", "user@host;whoami", "a\nb", "$(id)", "host name"])
+def test_hosts_cannot_be_shell_or_ssh_options(host):
+ with pytest.raises(ValidationError):
+ RemoteProfile(name="Team", host=host)
+
+
+def test_strict_ssh_without_agent_forwarding(monkeypatch):
+ monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "/usr/bin/ssh")
+ args = ssh_arguments(RemoteProfile(name="Team", host="my-alias"))
+ for option in ["StrictHostKeyChecking=yes", "BatchMode=yes", "ForwardAgent=no", "ControlPath=none", "PermitLocalCommand=no", "ExitOnForwardFailure=yes"]:
+ assert option in args
+ assert "StrictHostKeyChecking=no" not in args
+
+
+async def test_connect_checks_protocol_and_only_disconnects_tunnel(manager, ssh):
+ key = await save(manager)
+ connection = await manager.action("connect", {"id": key})
+ assert connection["hostname"] == "team-host"
+ assert connection["gateway_id"] == "remote-one"
+ assert connection["url"].startswith("http://127.0.0.1:23456/#/?bootstrapSecret=")
+ assert "private-webui-secret" not in json.dumps(manager.snapshot())
+ assert "private-webui-secret" not in manager.path.read_text()
+ await manager.action("disconnect", {"id": key})
+ ssh.tunnel.close.assert_awaited_once()
+ assert not manager.snapshot()["profiles"][0]["connected"]
+ assert len(manager.snapshot()["profiles"]) == 1
+
+
[email protected](("status", "identity", "error"), [
+ (401, {}, "remote_auth_failed"), (404, {}, "incompatible_gateway"),
+ (200, {"protocolVersion": 2, "gatewayId": "other"}, "incompatible_gateway"),
+ (200, {"protocolVersion": 1}, "incompatible_gateway"),
+])
+async def test_bad_target_closes_tunnel_and_never_returns_launch_url(manager, ssh, status, identity, error):
+ key = await save(manager)
+ ssh.state.update(status=status, identity=identity)
+ with pytest.raises(RemoteError, match=error):
+ await manager.action("connect", {"id": key})
+ ssh.tunnel.close.assert_awaited_once()
+ assert not manager.connections
+
+
+async def test_server_restart_requires_reconnect_not_local_fallback(manager, ssh):
+ key = await save(manager)
+ await manager.action("connect", {"id": key})
+ ssh.state["identity"]["gatewayId"] = "restarted"
+ assert not (await manager.health())["profiles"][0]["connected"]
+ assert key in manager.connections
+ ssh.tunnel.close.assert_not_awaited()
+
+
+async def test_connect_to_own_gateway_is_rejected_without_nesting(manager, ssh):
+ manager.local_gateway_id = "remote-one"
+ key = await save(manager)
+ with pytest.raises(RemoteError, match="same_instance"):
+ await manager.action("connect", {"id": key})
+ ssh.tunnel.close.assert_awaited_once()
+ assert not manager.connections
+
+
+async def test_forget_only_removes_saved_profile(manager, ssh):
+ key = await save(manager)
+ await manager.action("connect", {"id": key})
+ await manager.action("remove", {"id": key})
+ assert manager.snapshot()["profiles"] == []
+ ssh.tunnel.close.assert_awaited_once()
+
+
+async def test_closing_local_manager_reaps_ssh(manager, ssh):
+ key = await save(manager)
+ await manager.action("connect", {"id": key})
+ await manager.close()
+ ssh.tunnel.close.assert_awaited_once()
+ assert len(manager.snapshot()["profiles"]) == 1
+
+
+async def test_refresh_reuses_a_healthy_tunnel(manager, ssh):
+ key = await save(manager)
+ first = await manager.action("connect", {"id": key})
+ second = await manager.action("connect", {"id": key})
+ assert first["url"] == second["url"]
+ ssh.probe.assert_awaited_once()
+ ssh.tunnel.close.assert_not_awaited()
+
+
+async def test_reconnect_keeps_origin_and_changing_target_does_not(manager, ssh):
+ key = await save(manager)
+ await manager.action("connect", {"id": key})
+ assert json.loads(manager.path.read_text())[key]["local_port"] == 23456
+ await 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
+ await manager.action("save", {"id": key, "profile": {"name": "Other", "host": "other.example.test"}})
+ assert json.loads(manager.path.read_text())[key]["local_port"] == 0
+
+
+async def test_corrupt_store_not_overwritten(manager):
+ manager.path.write_text("corrupt")
+ with pytest.raises(RemoteError, match="profile_store_invalid"):
+ await save(manager)
+ assert manager.path.read_text() == "corrupt"
+
+
+async def test_new_host_trust_is_explicit_scoped_and_one_use(manager, ssh, monkeypatch):
+ key = await save(manager)
+ ssh.probe.side_effect = RemoteError("host_key_unknown")
+ with pytest.raises(RemoteError):
+ await manager.action("connect", {"id": key})
+ monkeypatch.setattr(remote_ssh, "scan_host_key", AsyncMock(return_value=("nanobot-remote ssh-ed25519 test-key\n", "SHA256:test")))
+ result = await manager.action("fingerprint", {"id": key})
+ assert result["fingerprint"] == "SHA256:test"
+ assert not list(manager.path.parent.glob("remote-hosts/*"))
+ await manager.action("trust", {"id": key, "challenge": result["challenge"]})
+ assert (manager.path.parent / "remote-hosts" / key).read_text() == "nanobot-remote ssh-ed25519 test-key\n"
+ with pytest.raises(RemoteError, match="host_key_changed"):
+ await manager.action("trust", {"id": key, "challenge": result["challenge"]})
+ with pytest.raises(RemoteError, match="host_key_changed"):
+ await manager.action("fingerprint", {"id": key})
+
+
+async def test_changed_known_host_cannot_be_overridden_in_ui(manager, ssh):
+ key = await save(manager)
+ ssh.probe.side_effect = RemoteError("host_key_changed")
+ with pytest.raises(RemoteError, match="host_key_changed"):
+ await manager.action("connect", {"id": key})
+ with pytest.raises(RemoteError, match="host_key_changed"):
+ await manager.action("fingerprint", {"id": key})
+
+
+async def test_shutdown_prevents_new_tunnels(manager, ssh):
+ key = await save(manager)
+ await manager.close()
+ with pytest.raises(RemoteError, match="local_io_error"):
+ await manager.action("connect", {"id": key})
+ ssh.probe.assert_not_awaited()
+
+
[email protected](("stderr", "code"), [
+ (b"WARNING: REMOTE HOST IDENTIFICATION HAS CHANGED", "host_key_changed"),
+ (b"Host key verification failed", "host_key_unknown"),
+ (b"Permission denied (publickey). secret-information", "ssh_auth_failed"),
+ (b"timed out with private address", "ssh_unreachable"),
+])
+def test_errors_never_echo_raw_ssh_output(stderr, code):
+ assert ssh_error(stderr) == code
+
+
+def gateway(tmp_path):
+ return build_gateway_services(
+ config=WebSocketConfig(host="127.0.0.1"), bus=MagicMock(), session_manager=None,
+ static_dist_path=None, workspace_path=tmp_path, config_path=tmp_path / "config.json",
+ default_restrict_to_workspace=False, runtime_model_name=None,
+ runtime_surface="browser", runtime_capabilities_overrides=None,
+ )
+
+
[email protected]("action", ["save", "discover", "connect", "remove", "trust"])
+async def test_http_mutations_are_not_gettable_even_with_token(gateway, action):
+ request = Request(f"/api/remote-instances/{action}", Headers())
+ connection = SimpleNamespace(remote_address=("127.0.0.1", 10000))
+ result = await gateway.http.dispatch(connection, request)
+ assert result.status_code == 405
+
+
[email protected](("peer", "host", "origin", "status"), [
+ ("127.0.0.1", "127.0.0.1:8765", "http://127.0.0.1:8765", 200),
+ ("203.0.113.1", "127.0.0.1:8765", "http://127.0.0.1:8765", 403),
+ ("127.0.0.1", "bot.example.com", "https://bot.example.com", 403),
+ ("127.0.0.1", "127.0.0.1:8765", "https://evil.example", 403),
+])
+async def test_ssh_access_is_local_and_authenticated(gateway, peer, host, origin, status):
+ token = gateway.tokens.issue_api_token(60)
+ connection = SimpleNamespace(remote_address=(peer, 10000))
+ request = Request("/api/remote-instances", Headers({"Host": host, "Origin": origin, "Authorization": f"Bearer {token}"}))
+ result = await gateway.http.dispatch(connection, request)
+ assert result.status_code == status
+ request = Request("/api/remote-instances", Headers({"Host": host}))
+ assert (await gateway.http.dispatch(connection, request)).status_code == 401
+
+
+async def test_cancellation_reaps_inflight_probe(monkeypatch):
+ process = MagicMock(returncode=None)
+ process.communicate = AsyncMock(side_effect=asyncio.CancelledError)
+ process.wait = AsyncMock(return_value=0)
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process))
+ with pytest.raises(asyncio.CancelledError):
+ await remote_ssh.probe(RemoteProfile(name="Test", host="example.test"))
+ process.terminate.assert_called_once()
+
+
+async def test_tunnel_refuses_an_existing_listener(monkeypatch):
+ spawn = AsyncMock()
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)
+ with socket.socket() as listener:
+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(1)
+ with pytest.raises(RemoteError, match="local_port_in_use"):
+ await remote_ssh.open_tunnel(
+ RemoteProfile(name="Test", host="example.test"), 8765,
+ local_port=listener.getsockname()[1],
+ )
+ spawn.assert_not_awaited()
+
+
+async def test_tunnel_reuses_closed_port_with_time_wait(monkeypatch):
+ with socket.socket() as listener:
+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
+ listener.bind(("127.0.0.1", 0))
+ listener.listen(1)
+ port = listener.getsockname()[1]
+ with socket.create_connection(("127.0.0.1", port), timeout=1) as peer:
+ accepted, _ = listener.accept()
+ accepted.close() # Server-side active close leaves TIME_WAIT after peer closes.
+ assert peer.recv(1) == b""
+ process = MagicMock(returncode=None)
+ process.wait = AsyncMock(return_value=0)
+ writer = MagicMock()
+ writer.wait_closed = AsyncMock()
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process))
+ monkeypatch.setattr(asyncio, "open_connection", AsyncMock(return_value=(None, writer)))
+ tunnel = await remote_ssh.open_tunnel(
+ RemoteProfile(name="Test", host="example.test"), 8765, local_port=port,
+ )
+ assert tunnel.port == port
+ await tunnel.close()
diff --git a/tests/webui/test_ssh_config.py b/tests/webui/test_ssh_config.py
new file mode 100644
index 000000000..785d36e9b
--- /dev/null
+++ b/tests/webui/test_ssh_config.py
@@ -0,0 +1,137 @@
+"""Name discovery is passive; OpenSSH, not our index, interprets connection options."""
+
+import asyncio
+import json
+import subprocess
+
+import pytest
+
+from nanobot.webui.remote_instances import RemoteInstances
+from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, ssh_arguments
+from nanobot.webui.ssh_config import discover_hosts
+
+
+def ssh_home(tmp_path, monkeypatch):
+ monkeypatch.setattr("pathlib.Path.home", lambda: tmp_path)
+ folder = tmp_path / ".ssh"
+ folder.mkdir()
+ return folder
+
+
+def test_discover_host_names_quotes_equals_multiple_aliases_and_patterns(ssh_home):
+ config = ssh_home / "config"
+ config.write_text('''# Host ignored
+Host=one two "three" # comment
+ HostName not-returned.example
+ IdentityFile private-key-not-returned
+Host * !excluded jump? [ab]bad -unsafe one
+Host TWO
+Host ipv6:alias
+''')
+ result = discover_hosts(str(config))
+ assert [host["host"] for host in result["hosts"]] == ["one", "two", "three", "ipv6:alias"]
+ assert {host["ssh_config"] for host in result["hosts"]} == {str(config)}
+ assert "private-key-not-returned" not in json.dumps(result)
+ assert "not-returned.example" not in json.dumps(result)
+
+
+def test_recursive_includes_are_sorted_relative_to_ssh_root_and_deduplicated(ssh_home):
+ (ssh_home / "hosts").mkdir()
+ (ssh_home / "config").write_text('Include "hosts/*.conf"\nHost final\n')
+ (ssh_home / "hosts" / "b.conf").write_text("Host second\nInclude config\n")
+ (ssh_home / "hosts" / "a.conf").write_text("Host first\nInclude hosts/b.conf\n")
+ result = discover_hosts(str(ssh_home / "config"))
+ assert [host["host"] for host in result["hosts"]] == ["first", "second", "final"]
+ assert len(result["files"]) == 3
+ assert not result["incomplete"]
+
+
+def test_default_config_is_found_without_pinning_a_custom_file(ssh_home):
+ (ssh_home / "config").write_text("Host default-test\n Port 2222\n")
+ result = discover_hosts()
+ host = next(host for host in result["hosts"] if host["host"] == "default-test")
+ assert host["ssh_config"] == ""
+ assert host["source"] == str(ssh_home / "config")
+
+
+def test_discovery_never_runs_ssh_match_exec_or_proxy_commands(ssh_home, monkeypatch):
+ def forbidden(*args, **kwargs):
+ pytest.fail("Discovery must not execute anything")
+
+ monkeypatch.setattr(subprocess, "run", forbidden)
+ monkeypatch.setattr(subprocess, "Popen", forbidden)
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", forbidden)
+ config = ssh_home / "config"
+ config.write_text('Host safe\n Match exec "touch dangerous"\nProxyCommand command-not-returned\n')
+ assert [host["host"] for host in discover_hosts(str(config))["hosts"]] == ["safe"]
+
+
+def test_unresolvable_includes_and_invalid_lines_do_not_hide_other_hosts(ssh_home):
+ config = ssh_home / "config"
+ config.write_text('Host ok\nInclude ${UNSET}/config %h.conf\nHost "unterminated\nHost good\n')
+ result = discover_hosts(str(config))
+ assert [host["host"] for host in result["hosts"]] == ["ok", "good"]
+ assert result["incomplete"]
+
+
[email protected]("contents", [b"\xff", b"x" * 262145])
+def test_unreadable_or_oversized_custom_config_is_an_explicit_error(ssh_home, contents):
+ path = ssh_home / "config"
+ path.write_bytes(contents)
+ with pytest.raises(RemoteError, match="ssh_config_unreadable"):
+ discover_hosts(str(path))
+
+
+def test_missing_explicit_config_is_not_silently_treated_as_empty(ssh_home):
+ with pytest.raises(RemoteError, match="local_file_not_found"):
+ discover_hosts(str(ssh_home / "missing"))
+
+
+def test_host_limit_is_bounded_and_reported(ssh_home):
+ config = ssh_home / "config"
+ config.write_text("\n".join(f"Host host-{n}" for n in range(250)))
+ result = discover_hosts(str(config))
+ assert len(result["hosts"]) == 200
+ assert result["incomplete"]
+
+
+def test_include_read_budget_is_bounded_and_reported(ssh_home):
+ config = ssh_home / "config"
+ config.write_text("Include large-*\nHost final\n")
+ for index in range(6):
+ (ssh_home / f"large-{index}").write_text(f"Host host-{index}\n#" + "x" * 250000)
+ result = discover_hosts(str(config))
+ assert result["incomplete"]
+ assert len(result["files"]) == 5 # Root plus four complete included files.
+ assert result["hosts"][-1]["host"] == "final"
+
+
[email protected]("path", ["\nsecret", "\x00bad", "x" * 2049])
+def test_invalid_paths_rejected_before_reading(path):
+ with pytest.raises(RemoteError, match="invalid_profile"):
+ discover_hosts(path)
+
+
[email protected](("override", "expected"), [(None, "2222"), (2200, "2200")])
+def test_system_ssh_inherits_config_port_user_and_identity(ssh_home, override, expected):
+ config = ssh_home / "config"
+ config.write_text("Host example-test\n HostName 192.0.2.10\n User tester\n Port 2222\n IdentityFile /tmp/test-key\n")
+ profile = RemoteProfile(name="Test", host="example-test", ssh_config=str(config), port=override)
+ # This controlled fixture has no Match exec; -G makes no network connections.
+ result = subprocess.run([*ssh_arguments(profile), "-G", profile.host],
+ capture_output=True, text=True, check=True)
+ settings = dict(line.split(" ", 1) for line in result.stdout.splitlines() if " " in line)
+ assert settings["port"] == expected
+ assert settings["user"] == "tester"
+ assert settings["identityfile"] == "/tmp/test-key"
+
+
+async def test_manager_discovery_does_not_save_profiles_or_connect(ssh_home):
+ config = ssh_home / "config"
+ config.write_text("Host one\n")
+ manager = RemoteInstances(ssh_home / "webui")
+ result = await manager.action("discover", {"ssh_config": str(config)})
+ assert result["hosts"][0]["host"] == "one"
+ assert not manager.path.exists()
+ assert not manager.connections
diff --git a/webui/src/App.tsx b/webui/src/App.tsx
index b7951a9ba..3b7ffd18f 100644
--- a/webui/src/App.tsx
+++ b/webui/src/App.tsx
@@ -13,6 +13,8 @@ import { Trans, useTranslation } from "react-i18next";
import { channelUiPresentation } from "@/channel-plugins/registry";
import { StarPrompt } from "@/components/StarPrompt";
import { Sidebar } from "@/components/Sidebar";
+import { RemoteInstances, useRemoteConnections } from "@/components/remote/RemoteInstances";
+import { RemoteConnectionsPage } from "@/components/remote/RemoteConnectionsPage";
import { LanguageSwitcher } from "@/components/LanguageSwitcher";
import { SidebarResizeHandle, SIDEBAR_MIN_WIDTH, SIDEBAR_MAX_WIDTH } from "@/components/SidebarResizeHandle";
import { matchSidebarShortcut } from "@/lib/sidebar-shortcuts";
@@ -130,7 +132,7 @@ const TOKEN_REFRESH_MIN_DELAY_MS = 5_000;
const PAIRING_POLL_INTERVAL_MS = 5_000;
const PAIRING_IDLE_POLL_INTERVAL_MS = 15_000;
const PAIRING_DISMISS_SNOOZE_MS = 30_000;
-type ShellView = "chat" | "settings" | "apps" | "automations" | "skills" | "channels";
+type ShellView = "chat" | "settings" | "apps" | "automations" | "skills" | "channels" | "remote";
type ShellRoute = {
view: ShellView;
activeKey: string | null;
@@ -280,6 +282,9 @@ function readShellRoute(): ShellRoute {
if (path === "/channels") {
return { view: "channels", activeKey, temporary, settingsSection: "channels" };
}
+ if (path === "/remote") {
+ return { view: "remote", activeKey, temporary, settingsSection: "overview" };
+ }
if (path === "/skills") {
return { view: "skills", activeKey, temporary, settingsSection: "skills" };
}
@@ -1084,12 +1089,12 @@ export default function App() {
modelName={state.modelName}
ingressLimits={state.ingressLimits}
>
- <Shell
+ <RemoteInstances><Shell
runtimeSurface={state.runtimeSurface}
onModelNameChange={handleModelNameChange}
onLogout={handleLogout}
onNativeEngineRestart={handleNativeEngineRestart}
- />
+ /></RemoteInstances>
</ClientProvider>
);
}
@@ -1106,6 +1111,7 @@ function Shell({
onNativeEngineRestart: () => Promise<string>;
}) {
const { t, i18n } = useTranslation();
+ const localActive = useRemoteConnections()?.localActive !== false;
const { client, getToken } = useClient();
const { theme, toggle } = useTheme();
const {
@@ -2125,6 +2131,12 @@ function Shell({
setMobileSidebarOpen(false);
}, [activeKey, navigate]);
+ const onOpenRemoteConnections = useCallback(() => {
+ setSessionSearchOpen(false);
+ navigate({ view: "remote", activeKey, settingsSection: "overview" });
+ setMobileSidebarOpen(false);
+ }, [activeKey, navigate]);
+
const onOpenSkills = useCallback(() => {
setSessionSearchOpen(false);
navigate({ view: "skills", activeKey, settingsSection: "skills" });
@@ -2135,6 +2147,7 @@ function Shell({
const actions = { newChat: onNewChat, search: onOpenSessionSearch, apps: onOpenApps,
skills: onOpenSkills, automations: onOpenAutomations, channels: onOpenChannels, settings: () => onOpenSettings() };
const handleKeyDown = (event: globalThis.KeyboardEvent) => {
+ if (!localActive) return;
const action = matchSidebarShortcut(event);
if (!action) return;
event.preventDefault();
@@ -2142,7 +2155,7 @@ function Shell({
};
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
- }, [onNewChat, onOpenSessionSearch, onOpenApps, onOpenSkills, onOpenAutomations, onOpenChannels, onOpenSettings]);
+ }, [localActive, onNewChat, onOpenSessionSearch, onOpenApps, onOpenSkills, onOpenAutomations, onOpenChannels, onOpenSettings]);
const onSettingsSectionChange = useCallback(
(section: SettingsSectionKey) => {
@@ -2632,6 +2645,7 @@ function Shell({
}, [updateWorkbenchState]);
useEffect(() => {
+ if (!localActive) return;
if (view === "settings") {
document.title = t("app.documentTitle.chat", {
title: t("settings.sidebar.title"),
@@ -2654,6 +2668,10 @@ function Shell({
document.title = t("app.documentTitle.chat", { title: t("settings.nav.channels") });
return;
}
+ if (view === "remote") {
+ document.title = t("app.documentTitle.chat", { title: t("remote.title") });
+ return;
+ }
if (view === "skills") {
document.title = t("app.documentTitle.chat", {
title: t("settings.nav.skills", { defaultValue: "Skills" }),
@@ -2663,7 +2681,7 @@ function Shell({
document.title = activeSession
? t("app.documentTitle.chat", { title: headerTitle })
: t("app.documentTitle.base");
- }, [activeSession, headerTitle, i18n.resolvedLanguage, t, view]);
+ }, [localActive, activeSession, headerTitle, i18n.resolvedLanguage, t, view]);
const pinnedPaneKeys = useMemo(
() => new Set(sidebarState.pinned_keys),
@@ -2715,10 +2733,11 @@ function Shell({
onOpenApps,
onOpenAutomations,
onOpenChannels,
+ onOpenRemoteConnections,
onOpenSkills,
onSettingsIntent,
onOpenSearch: onOpenSessionSearch,
- activeUtility: view === "apps" || view === "automations" || view === "skills" || view === "channels" ? view : null,
+ activeUtility: view === "apps" || view === "automations" || view === "skills" || view === "channels" || view === "remote" ? view : null,
onToggleArchived,
pinnedKeys: sidebarPinnedTabKeys,
archivedKeys: sidebarArchivedTabKeys,
@@ -2747,7 +2766,7 @@ function Shell({
return (
<ThemeProvider theme={theme}>
- <StarPrompt ready={!loading && !sidebarStateLoading} />
+ <StarPrompt ready={localActive && !loading && !sidebarStateLoading} />
<div
className={cn(
"relative h-full w-full overflow-hidden",
@@ -2874,7 +2893,7 @@ function Shell({
view !== "chat" && "hidden",
)}
>
- <ThreadVisibilityContext.Provider value={view === "chat"}>
+ <ThreadVisibilityContext.Provider value={localActive && view === "chat"}>
<Suspense fallback={<StartupShell embedded />}>
<PaneWorkbench
panes={renderedWorkbenchPanes}
@@ -3021,7 +3040,11 @@ function Shell({
</div>}
{view !== "chat" && (
<div className="absolute inset-0 flex flex-col">
- <Suspense fallback={<SurfaceLoadingFallback />}>
+ {view === "remote" ? <RemoteConnectionsPage
+ mainNavigationExpanded={showMainSidebar && hostSidebarOpen}
+ hostChromeInset={showHostChrome}
+ onBackToChat={onBackToChat}
+ /> : <Suspense fallback={<SurfaceLoadingFallback />}>
<SettingsView
registerExitGuard={registerSettingsExitGuard}
theme={theme}
@@ -3043,7 +3066,7 @@ function Shell({
isRestarting={isRestarting}
hostChromeInset={showHostChrome}
/>
- </Suspense>
+ </Suspense>}
</div>
)}
</main>
diff --git a/webui/src/components/Sidebar.tsx b/webui/src/components/Sidebar.tsx
index be368c413..3f4752811 100644
--- a/webui/src/components/Sidebar.tsx
+++ b/webui/src/components/Sidebar.tsx
@@ -9,6 +9,7 @@ import {
Brain,
CalendarClock,
MessageCircle,
+ MonitorUp,
PanelLeftClose,
Search,
Settings,
@@ -22,7 +23,8 @@ import {
type SidebarDeleteItem,
type SidebarPaneGroup,
} from "@/components/ChatList";
-import { ConnectionBadge } from "@/components/ConnectionBadge";
+import { HostSwitcher } from "@/components/remote/HostSwitcher";
+import { useRemoteConnections } from "@/components/remote/RemoteInstances";
import {
SIDEBAR_SELECTION_ACTION_ITEM_CLASS,
SidebarSelectionHighlight,
@@ -68,9 +70,10 @@ interface SidebarProps {
onOpenSkills: () => void;
onOpenAutomations: () => void;
onOpenChannels: () => void;
+ onOpenRemoteConnections?: () => void;
onSettingsIntent?: () => void;
onOpenSearch: () => void;
- activeUtility?: "apps" | "skills" | "automations" | "channels" | null;
+ activeUtility?: "apps" | "skills" | "automations" | "channels" | "remote" | null;
onToggleArchived: () => void;
onCollapse?: () => void;
onExpand?: () => void;
@@ -108,6 +111,7 @@ function isApplePlatform(): boolean {
export function Sidebar(props: SidebarProps) {
const { t } = useTranslation();
+ const remoteConnections = useRemoteConnections();
const [menuPortalContainer, setMenuPortalContainer] =
useState<HTMLElement | null>(null);
const collapsed = Boolean(props.collapsed);
@@ -253,6 +257,16 @@ export function Sidebar(props: SidebarProps) {
selectionRef={activeActionRef}
icon={<MessageCircle className="h-4 w-4" />}
/>
+ {remoteConnections?.available && props.onOpenRemoteConnections && (
+ <SidebarActionButton
+ collapsed={collapsed}
+ label={t("remote.title")}
+ onClick={props.onOpenRemoteConnections}
+ active={props.activeUtility === "remote"}
+ selectionRef={activeActionRef}
+ icon={<MonitorUp className="h-4 w-4" />}
+ />
+ )}
{props.archivedCount ? (
<SidebarActionButton
collapsed={collapsed}
@@ -332,7 +346,7 @@ export function Sidebar(props: SidebarProps) {
className="w-9"
icon={<Settings className="h-4 w-4" />}
/>
- <ConnectionBadge />
+ <HostSwitcher collapsed={collapsed} portalContainer={props.containActionMenus ? menuPortalContainer : undefined} />
</div>
</nav>
</TooltipProvider>
diff --git a/webui/src/components/remote/HostSwitcher.tsx b/webui/src/components/remote/HostSwitcher.tsx
new file mode 100644
index 000000000..47066d235
--- /dev/null
+++ b/webui/src/components/remote/HostSwitcher.tsx
@@ -0,0 +1,106 @@
+import { createContext, useContext, useEffect, useRef, useState } from "react";
+import { Check, ChevronUp, CircleAlert, Laptop, Loader2, Server, Settings2, X } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/components/ui/button";
+import { ConnectionBadge } from "@/components/ConnectionBadge";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { useClient } from "@/providers/ClientProvider";
+import { cn } from "@/lib/utils";
+import type { ConnectionStatus } from "@/lib/types";
+import type { HostAnchor, EmbeddedHost } from "./host-bridge";
+
+export interface HostPicker {
+ kind: "shell";
+ name: string;
+ hostname: string;
+ localName: string;
+ currentId: string | null;
+ profiles: { id: string; name: string; host: string; ready: boolean }[];
+ pending: { id: string; name: string } | null;
+ error: string;
+ offline: boolean;
+ select: (id: string | null) => void;
+ manage: () => void;
+ cancel: () => void;
+ clearError: () => void;
+ restoreFocus: () => void;
+}
+interface EmbeddedPicker extends EmbeddedHost {
+ kind: "embedded";
+ open: (anchor: HostAnchor) => void;
+}
+export const HostNavigationContext = createContext<HostPicker | EmbeddedPicker | null>(null);
+
+function HostMenuContent({ picker, portalContainer }: { picker: HostPicker; portalContainer?: HTMLElement | null }) {
+ const { t } = useTranslation();
+ return <DropdownMenuContent side="top" align="end" sideOffset={8} collisionPadding={12}
+ portalContainer={portalContainer} className="w-64 max-w-[calc(100vw-1.5rem)]"
+ onCloseAutoFocus={(event) => { event.preventDefault(); picker.restoreFocus(); }}>
+ <DropdownMenuLabel>{t("remote.switchHost")}</DropdownMenuLabel>
+ <DropdownMenuItem onSelect={() => picker.select(null)} className="gap-2.5">
+ <Laptop className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1"><span className="block">{t("remote.local")}</span><span className="block truncate text-xs text-muted-foreground">{picker.localName}</span></span>
+ {!picker.currentId && <Check className="h-4 w-4" />}
+ </DropdownMenuItem>
+ {!!picker.profiles.length && <DropdownMenuSeparator />}
+ {picker.profiles.map((profile) => <DropdownMenuItem key={profile.id} onSelect={() => picker.select(profile.id)} className="gap-2.5">
+ <Server className="h-4 w-4 shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1"><span className="block truncate">{profile.name}</span><span className="block truncate text-xs text-muted-foreground">{profile.host}</span></span>
+ {picker.pending?.id === profile.id ? <Loader2 className="h-4 w-4 animate-spin" /> : picker.currentId === profile.id ? <Check className="h-4 w-4" />
+ : profile.ready ? <span className="text-[11px] text-muted-foreground">{t("remote.ready")}</span> : null}
+ </DropdownMenuItem>)}
+ {picker.pending && <><DropdownMenuSeparator /><DropdownMenuItem onSelect={picker.cancel} className="gap-2.5"><X className="h-4 w-4" />{t("remote.cancelSwitch")}</DropdownMenuItem></>}
+ {picker.error && <div role="alert" className="px-2.5 py-2 text-xs leading-5 text-destructive">
+ {picker.error}<button className="ml-2 underline underline-offset-2" onClick={picker.clearError}>{t("common.close")}</button>
+ </div>}
+ <DropdownMenuSeparator />
+ <DropdownMenuItem className="gap-2.5" onSelect={picker.manage}><Settings2 className="h-4 w-4 text-muted-foreground" />{t("remote.manageConnections")}</DropdownMenuItem>
+ </DropdownMenuContent>;
+}
+
+/** Shared sidebar control. Remote frames can only open the trusted shell's menu. */
+export function HostSwitcher({ collapsed = false, portalContainer }: { collapsed?: boolean; portalContainer?: HTMLElement | null }) {
+ const picker = useContext(HostNavigationContext);
+ const { client } = useClient();
+ const { t } = useTranslation();
+ const [status, setStatus] = useState<ConnectionStatus>(client.status);
+ useEffect(() => client.onStatus(setStatus), [client]);
+ const buttonRef = useRef<HTMLButtonElement>(null);
+ if (!picker) return <ConnectionBadge />;
+ const shell = picker.kind === "shell" ? picker : null;
+ const remote = picker.kind === "embedded" || !!shell?.currentId;
+ const pendingName = picker.kind === "shell" ? picker.pending?.name : picker.pendingName;
+ const failed = !!picker.error || !!shell?.offline || status === "error" || status === "closed";
+ const waiting = !!pendingName || status === "connecting" || status === "reconnecting";
+ const label = pendingName ? t("remote.connecting") : picker.name;
+ const detail = pendingName ? t("remote.preparing", { name: pendingName }) : `${picker.name} · ${picker.hostname}`;
+ const title = picker.error || `${detail} — ${t(failed ? "remote.offline" : `connection.${status}`)}`;
+ const button = <Button ref={buttonRef} variant="ghost" size="sm" aria-label={t("remote.switchHost")} title={title}
+ data-host-switcher className={cn("host-no-drag h-8 min-w-0 gap-2 rounded-xl px-2 text-xs font-normal text-sidebar-content/75 hover:bg-sidebar-accent/65 hover:text-sidebar-content",
+ collapsed ? "w-8 justify-center px-0" : "max-w-full flex-1 justify-start")}
+ onClick={picker.kind === "embedded" ? () => {
+ const rect = buttonRef.current?.getBoundingClientRect();
+ if (rect) picker.open({ left: rect.left, top: rect.top, width: rect.width, height: rect.height });
+ } : undefined}>
+ <span className="relative flex shrink-0 items-center justify-center">
+ {waiting ? <Loader2 className="h-4 w-4 animate-spin" /> : failed ? <CircleAlert className="h-4 w-4 text-destructive" />
+ : remote ? <Server className="h-4 w-4" /> : <Laptop className="h-4 w-4" />}
+ {!waiting && !failed && <span aria-hidden className={cn("absolute -bottom-0.5 -right-0.5 h-1.5 w-1.5 rounded-full ring-2 ring-sidebar", status === "open" ? "bg-emerald-500" : "bg-muted-foreground")} />}
+ </span>
+ {!collapsed && <><span className="truncate">{label}</span><ChevronUp className="ml-auto h-3 w-3 shrink-0 opacity-60" /></>}
+ <span className="sr-only" role="status">{detail} · {t(failed ? "remote.offline" : `connection.${status}`)}</span>
+ </Button>;
+ if (!shell) return button;
+ return <DropdownMenu><DropdownMenuTrigger asChild>{button}</DropdownMenuTrigger><HostMenuContent picker={shell} portalContainer={portalContainer} /></DropdownMenu>;
+}
+
+/** Parent-owned menu anchored to the active remote sidebar, never inside its DOM. */
+export function RemoteHostMenu({ picker, anchor, onClose }: { picker: HostPicker; anchor: HostAnchor | null; onClose: () => void }) {
+ return <DropdownMenu open={!!anchor} onOpenChange={(open) => { if (!open) onClose(); }}>
+ <DropdownMenuTrigger asChild><button tabIndex={-1} aria-hidden className="pointer-events-none fixed opacity-0" style={anchor ? {
+ left: Math.max(0, Math.min(anchor.left, window.innerWidth - 32)), top: Math.max(0, Math.min(anchor.top, window.innerHeight - 32)),
+ width: Math.min(anchor.width, window.innerWidth), height: Math.min(anchor.height, 64),
+ } : { width: 0, height: 0 }} /></DropdownMenuTrigger>
+ <HostMenuContent picker={picker} />
+ </DropdownMenu>;
+}
diff --git a/webui/src/components/remote/RemoteConnectionsPage.tsx b/webui/src/components/remote/RemoteConnectionsPage.tsx
new file mode 100644
index 000000000..0ea5d3c3f
--- /dev/null
+++ b/webui/src/components/remote/RemoteConnectionsPage.tsx
@@ -0,0 +1,245 @@
+import { useEffect, useId, useRef, useState } from "react";
+import { ArrowLeft, ArrowUpRight, Check, ChevronLeft, Laptop, Loader2, MoreHorizontal, Plus, Server, ShieldCheck } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { SettingsGroup, SettingsRow, SettingsSectionTitle } from "@/components/settings/shared/SettingsControls";
+import { SettingsAdvancedOptions } from "@/components/settings/shared/SettingsFeature";
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";
+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
+import { useClient } from "@/providers/ClientProvider";
+import { remoteAction, type RemoteProfile } from "@/lib/remote-instances";
+import { cn } from "@/lib/utils";
+import { useRemoteConnections } from "./RemoteInstances";
+import { SSHHostPicker } from "./SSHHostPicker";
+
+const emptyProfile = (): Omit<RemoteProfile, "id" | "connected"> => ({
+ name: "", host: "", port: null, ssh_config: "", identity_file: "",
+ config_path: "~/.nanobot/config.json", runtime_user: "",
+});
+
+/** A shell destination, not a dialog. Only verification and removal need confirmation. */
+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 [editingId, setEditingId] = useState("");
+ const [busy, setBusy] = useState("");
+ const [error, setError] = useState("");
+ const [removing, setRemoving] = useState<RemoteProfile | null>(null);
+ const [disconnecting, setDisconnecting] = useState<RemoteProfile | null>(null);
+ const [fingerprint, setFingerprint] = useState<{ id: string; fingerprint: string; challenge: string } | null>(null);
+ const mounted = useRef(true);
+ const refresh = connections?.refresh;
+
+ useEffect(() => {
+ mounted.current = true;
+ // Keep cached rows visible while refreshing in the background.
+ void refresh?.().catch(() => {});
+ return () => { mounted.current = false; };
+ }, [refresh]);
+
+ if (!connections) return null;
+ const { directory, directoryError, connect: connectHost, disconnect: disconnectHost } = connections;
+ const showForm = editorOpen;
+ const pageError = error || (directoryError ? t("remote.errors.directory_unavailable") : "");
+ const showError = (reason: unknown) => {
+ if (!mounted.current) return;
+ const code = reason instanceof Error ? reason.message : "unknown";
+ setError(t(`remote.errors.${code}`, { defaultValue: t("remote.errors.unknown") }));
+ };
+
+ const connect = async (id: string) => {
+ setBusy(id); setError("");
+ try {
+ await connectHost(id, () => mounted.current);
+ } catch (reason) {
+ if (!mounted.current) return;
+ if (reason instanceof Error && reason.message === "host_key_unknown") {
+ try {
+ const result = await remoteAction<{ fingerprint: string; challenge: string }>(client, "fingerprint", { id });
+ if (mounted.current) setFingerprint({ id, ...result });
+ } catch (scanError) { showError(scanError); }
+ } else { showError(reason); }
+ } finally {
+ if (mounted.current) setBusy("");
+ }
+ };
+
+ const trustHost = async () => {
+ if (!fingerprint) return;
+ setBusy("trust"); setError("");
+ try {
+ await remoteAction(client, "trust", { id: fingerprint.id, challenge: fingerprint.challenge });
+ if (!mounted.current) return;
+ const id = fingerprint.id;
+ setFingerprint(null);
+ await connect(id);
+ } catch (reason) { showError(reason); }
+ finally { if (mounted.current) setBusy(""); }
+ };
+
+ const save = async () => {
+ setEditorOpen(true); setBusy("save"); setError("");
+ try {
+ const result = await remoteAction<{ id: string }>(client, "save", {
+ id: editingId, profile: { ...form, name: form.name.trim() || form.host.trim() },
+ });
+ if (!mounted.current) return;
+ setEditingId(result.id);
+ await refresh?.();
+ if (mounted.current) await connect(result.id);
+ } catch (reason) { showError(reason); }
+ finally { if (mounted.current) 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 (reason) { showError(reason); }
+ finally { if (mounted.current) setBusy(""); }
+ };
+
+ const disconnect = async (id: string) => {
+ setBusy(id); setError("");
+ try { await disconnectHost(id); if (mounted.current) setDisconnecting(null); }
+ catch (reason) { showError(reason); }
+ finally { if (mounted.current) setBusy(""); }
+ };
+
+ const closeEditor = () => {
+ setEditorOpen(false); setEditingId(""); setForm(emptyProfile()); setError("");
+ };
+
+ return <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-settings-canvas">
+ <div className="min-w-0 flex-1 overflow-y-auto [scrollbar-gutter:stable]">
+ <div data-settings-section="remote" data-main-navigation-expanded={mainNavigationExpanded}
+ className={cn("settings-grid settings-feature-page mx-auto w-full animate-in fade-in-0 slide-in-from-bottom-1 py-6 duration-200 ease-out motion-reduce:animate-none sm:py-8 lg:py-12",
+ hostChromeInset && "pt-[4.25rem] sm:pt-[4.25rem] lg:pt-[4.75rem]")}>
+ <div className="settings-feature-header mb-7">
+ <Button variant="ghost" size="sm" className="touch-target mb-4 gap-1 lg:hidden" onClick={onBackToChat}>
+ <ChevronLeft className="h-4 w-4" />{t("settings.backToChat")}
+ </Button>
+ <h1 className="text-[24px] font-normal leading-tight tracking-normal text-foreground sm:text-[28px]">{t("remote.title")}</h1>
+ </div>
+ <div className="settings-stack">
+ <p className="settings-list-inset text-[13px] leading-6 text-muted-foreground">{t(showForm ? "remote.addDescription" : "remote.description")}</p>
+ {directory?.available && <>
+ <SettingsGroup>
+ <div className="settings-list-row flex items-center gap-3 py-3">
+ <Laptop className="h-[18px] w-[18px] shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1"><span className="block text-[14px] font-medium">{t("remote.local")}</span>
+ {directory.machine_name && <span className="mt-0.5 block truncate text-xs text-muted-foreground">{directory.machine_name}</span>}</span>
+ <span className="flex items-center gap-1.5 text-xs text-muted-foreground"><Check className="h-3.5 w-3.5" />{t("remote.current")}</span>
+ </div>
+ </SettingsGroup>
+ {showForm ? <form onSubmit={(event) => { event.preventDefault(); void save(); }} className="settings-stack">
+ <div className="settings-section-heading">
+ <SettingsSectionTitle>{t(editingId ? "remote.edit" : "remote.addTitle")}</SettingsSectionTitle>
+ <Button type="button" variant="ghost" size="sm" className="gap-1.5" disabled={!!busy} onClick={closeEditor}>
+ <ArrowLeft className="h-3.5 w-3.5" />{t("remote.back")}
+ </Button>
+ </div>
+ <SettingsGroup>
+ <RemoteField label={t("remote.host")} value={form.host} placeholder="[email protected]" required disabled={!!busy}
+ onChange={(host) => setForm({ ...form, host })} />
+ <RemoteField label={t("remote.name")} value={form.name} placeholder={t("remote.namePlaceholder")} disabled={!!busy}
+ onChange={(name) => setForm({ ...form, name })} />
+ </SettingsGroup>
+ <SettingsAdvancedOptions>
+ <SettingsGroup>
+ <RemoteField label={t("remote.sshPort")} value={form.port == null ? "" : String(form.port)} placeholder={t("remote.portPlaceholder")} type="number" min={1} max={65535} disabled={!!busy}
+ onChange={(port) => setForm({ ...form, port: port === "" ? null : Number(port) })} />
+ {(["ssh_config", "identity_file", "config_path", "runtime_user"] as const).map((key) =>
+ <RemoteField key={key} label={t(`remote.${key}`)} value={form[key]} disabled={!!busy}
+ onChange={(value) => setForm({ ...form, [key]: value })} />)}
+ </SettingsGroup>
+ </SettingsAdvancedOptions>
+ <div className="settings-list-inset flex flex-wrap items-start justify-between gap-4">
+ <p className="flex max-w-sm flex-1 items-start gap-2 text-xs leading-5 text-muted-foreground"><ShieldCheck className="mt-0.5 h-3.5 w-3.5 shrink-0" />{t("remote.keyHint")}</p>
+ <Button type="submit" disabled={!!busy || !form.host.trim()}>{busy && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}{t(busy ? "remote.connecting" : "remote.saveConnect")}</Button>
+ </div>
+ </form> : null}
+ <div hidden={showForm} className={cn("settings-stack", showForm && "hidden")}>
+ {directory.profiles.length > 0 && <SettingsGroup>
+ {directory.profiles.map((profile) => <div key={profile.id} className="settings-list-row settings-hover flex items-center gap-2 transition-colors">
+ <button type="button" className="flex min-h-[60px] min-w-0 flex-1 items-center gap-3 rounded-xl py-3 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" disabled={!!busy} onClick={() => { void connect(profile.id); }}>
+ {busy === profile.id ? <Loader2 className="h-[18px] w-[18px] shrink-0 animate-spin text-muted-foreground" /> : <Server className="h-[18px] w-[18px] shrink-0 text-muted-foreground" />}
+ <span className="min-w-0 flex-1"><span className="block truncate text-[14px] font-medium">{profile.name}</span><span className="mt-0.5 block truncate text-xs text-muted-foreground">{profile.host}</span></span>
+ <ArrowUpRight className="h-4 w-4 text-muted-foreground" />
+ </button>
+ <DropdownMenu><DropdownMenuTrigger asChild><Button variant="ghost" size="icon" className="h-8 w-8 shrink-0" disabled={!!busy} aria-label={t("remote.manage", { name: profile.name })}><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>
+ <DropdownMenuContent align="end">
+ {(profile.connected || connections.openHostIds.includes(profile.id)) && <DropdownMenuItem onSelect={() => setDisconnecting(profile)}>{t("remote.disconnect")}</DropdownMenuItem>}
+ <DropdownMenuItem disabled={profile.connected || connections.openHostIds.includes(profile.id)} onSelect={() => {
+ const { name, host, port, ssh_config, identity_file, config_path, runtime_user } = profile;
+ setEditingId(profile.id); setForm({ name, host, port, ssh_config, identity_file, config_path, runtime_user }); setEditorOpen(true); setError("");
+ }}>{t("remote.edit")}</DropdownMenuItem>
+ <DropdownMenuItem onSelect={() => setRemoving(profile)}>{t("remote.forget")}</DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </div>)}
+ </SettingsGroup>}
+ <SSHHostPicker disabled={!!busy} onSelect={({ host, ssh_config }) => {
+ setEditingId(""); setForm({ ...emptyProfile(), name: host, host, ssh_config }); setEditorOpen(true); setError("");
+ }} />
+ <div className="settings-list-inset"><Button variant="ghost" className="gap-2" disabled={!!busy} onClick={() => { setEditingId(""); setForm(emptyProfile()); setEditorOpen(true); setError(""); }}>
+ <Plus className="h-4 w-4" />{t("remote.add")}
+ </Button></div>
+ </div>
+ </>}
+ {!directory && !directoryError && <div role="status" className="settings-list-inset flex items-center gap-2 text-sm text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" />{t("remote.loading")}</div>}
+ {directory && !directory.available && <p className="settings-list-inset text-sm text-muted-foreground">{t("remote.unavailable")}</p>}
+ {pageError && !fingerprint && <div className="settings-list-inset space-y-2">
+ <p role="alert" className="text-[13px] leading-5 text-destructive">{pageError}</p>
+ {directoryError && <Button variant="ghost" size="sm" disabled={!!busy} onClick={() => {
+ setBusy("refresh"); setError(""); void refresh?.().catch(showError).finally(() => { if (mounted.current) setBusy(""); });
+ }}>{t("remote.retry")}</Button>}
+ </div>}
+ </div>
+ </div>
+ </div>
+ <Dialog open={!!disconnecting} onOpenChange={(value) => { if (!value && !busy) setDisconnecting(null); }}>
+ <DialogContent className="max-w-sm"><DialogHeader><DialogTitle>{t("remote.disconnectTitle", { name: disconnecting?.name })}</DialogTitle><DialogDescription>{t("remote.disconnectDescription")}</DialogDescription></DialogHeader>
+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
+ <div className="flex justify-end gap-2"><Button variant="ghost" disabled={!!busy} onClick={() => setDisconnecting(null)}>{t("common.cancel")}</Button><Button variant="destructive" disabled={!!busy} onClick={() => { if (disconnecting) void disconnect(disconnecting.id); }}>{t("remote.disconnect")}</Button></div>
+ </DialogContent>
+ </Dialog>
+ <Dialog open={!!removing} onOpenChange={(value) => { if (!value && !busy) setRemoving(null); }}>
+ <DialogContent className="max-w-sm"><DialogHeader><DialogTitle>{t("remote.forgetTitle", { name: removing?.name })}</DialogTitle><DialogDescription>{t("remote.forgetDescription")}</DialogDescription></DialogHeader>
+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
+ <div className="flex justify-end gap-2"><Button variant="ghost" disabled={!!busy} onClick={() => setRemoving(null)}>{t("common.cancel")}</Button><Button variant="destructive" disabled={!!busy} onClick={() => { void remove(); }}>{t("remote.forget")}</Button></div>
+ </DialogContent>
+ </Dialog>
+ <Dialog open={!!fingerprint} onOpenChange={(value) => { if (!value && !busy) setFingerprint(null); }}>
+ <DialogContent className="max-w-md"><DialogHeader><DialogTitle>{t("remote.verifyTitle")}</DialogTitle><DialogDescription>{t("remote.verifyDescription")}</DialogDescription></DialogHeader>
+ <code className="break-all rounded-xl bg-muted p-3 text-xs">{fingerprint?.fingerprint}</code>
+ <p className="text-xs leading-relaxed text-muted-foreground">{t("remote.verifyHint")}</p>
+ {error && <p role="alert" className="text-sm text-destructive">{error}</p>}
+ <div className="flex justify-end gap-2"><Button variant="ghost" disabled={!!busy} onClick={() => setFingerprint(null)}>{t("common.cancel")}</Button><Button disabled={!!busy} onClick={() => { void trustHost(); }}>{t("remote.verifyConnect")}</Button></div>
+ </DialogContent>
+ </Dialog>
+ </div>;
+}
+
+function RemoteField({ label, onChange, ...props }: {
+ label: string; value: string; onChange: (value: string) => void;
+ placeholder?: string; required?: boolean; disabled?: boolean; type?: string; min?: number; max?: number;
+}) {
+ const id = useId();
+ return <SettingsRow title={<label htmlFor={id}>{label}</label>}>
+ <Input id={id} {...props} onChange={(event) => onChange(event.target.value)} autoComplete="off" spellCheck={false} />
+ </SettingsRow>;
+}
diff --git a/webui/src/components/remote/RemoteInstances.tsx b/webui/src/components/remote/RemoteInstances.tsx
new file mode 100644
index 000000000..4dc954547
--- /dev/null
+++ b/webui/src/components/remote/RemoteInstances.tsx
@@ -0,0 +1,119 @@
+import { createContext, useContext, useEffect, useLayoutEffect, useRef, type ReactNode } from "react";
+import { Loader2, PlugZap } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import { Button } from "@/components/ui/button";
+import type { RemoteDirectory } from "@/lib/remote-instances";
+import { useHostSessions } from "./useHostSessions";
+import { HostNavigationContext, HostSwitcher, RemoteHostMenu, type HostPicker } from "./HostSwitcher";
+import { useSidebarHostBridge } from "./useSidebarHostBridge";
+
+const RemoteContext = createContext<{
+ available: boolean;
+ localActive: boolean;
+ openHostIds: string[];
+ directory: RemoteDirectory | null;
+ directoryError: boolean;
+ refresh: () => Promise<RemoteDirectory>;
+ connect: (id: string, stillWanted?: () => boolean) => Promise<void>;
+ disconnect: (id: string) => Promise<void>;
+} | null>(null);
+export function useRemoteConnections() { return useContext(RemoteContext); }
+
+/** Keep host views alive; navigation belongs in each view's sidebar, not a second header. */
+export function RemoteInstances({ children }: { children: ReactNode }) {
+ const { t } = useTranslation();
+ const hosts = useHostSessions();
+ const { selected, pending, frames, directory, error } = hosts;
+ const localPanel = useRef<HTMLDivElement>(null);
+ const lastLocalFocus = useRef<HTMLElement | null>(null);
+ const frameNodes = useRef(new Map<string, HTMLIFrameElement>());
+ const activeHostId = useRef(selected?.id);
+ activeHostId.current = selected?.id;
+ const restoreLocalFocus = () => {
+ if (lastLocalFocus.current?.isConnected) lastLocalFocus.current.focus({ preventScroll: true });
+ };
+ const message = error ? t(`remote.errors.${error}`, { defaultValue: t("remote.errors.unknown") }) : "";
+ const bridge = useSidebarHostBridge(frames, selected?.id, frameNodes, restoreLocalFocus, { pendingName: pending?.name, error: message });
+ const restoreFocus = () => {
+ if (activeHostId.current) bridge.focus(activeHostId.current);
+ else restoreLocalFocus();
+ };
+ const available = directory?.available === true || hosts.directoryError;
+ const activeFrame = frames.find((frame) => frame.connection.id === selected?.id);
+ const offline = !!selected && (activeFrame?.offline || (!activeFrame && !pending && !!error));
+ const switchHost = (id: string) => {
+ void hosts.connect(id).catch((reason: unknown) => hosts.setError(reason instanceof Error ? reason.message : "unknown"));
+ };
+ 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,
+ profiles: (directory?.profiles || []).map(({ id, name, host }) => ({ id, name, host,
+ ready: frames.some((frame) => frame.connection.id === id && !frame.offline && frame.loaded) })),
+ pending, error: message, offline: !!offline, select: (id) => { if (id) switchHost(id); else hosts.local(); },
+ manage: () => { hosts.local(); window.location.hash = "/remote"; },
+ cancel: hosts.cancel, clearError: () => hosts.setError(""), restoreFocus,
+ };
+ useEffect(() => { if (selected) document.title = `${selected.name} · nanobot`; }, [selected]);
+ useEffect(() => {
+ const rememberFocus = (event: FocusEvent) => {
+ if (event.target instanceof HTMLElement && localPanel.current?.contains(event.target)
+ && !event.target.closest("[data-host-switcher]")) lastLocalFocus.current = event.target;
+ };
+ document.addEventListener("focusin", rememberFocus);
+ return () => document.removeEventListener("focusin", rememberFocus);
+ }, []);
+ useLayoutEffect(() => {
+ if (selected) frameNodes.current.get(selected.id)?.focus({ preventScroll: true });
+ else restoreLocalFocus();
+ }, [selected]);
+ useEffect(() => {
+ if (!selected) return;
+ const stop = (event: KeyboardEvent) => event.stopPropagation();
+ document.addEventListener("keydown", stop);
+ document.addEventListener("keyup", stop);
+ return () => { document.removeEventListener("keydown", stop); document.removeEventListener("keyup", stop); };
+ }, [selected]);
+
+ return <RemoteContext.Provider value={{ available, localActive: !selected, directory,
+ openHostIds: frames.map((frame) => frame.connection.id),
+ directoryError: hosts.directoryError, refresh: hosts.refresh, connect: hosts.connect, disconnect: hosts.disconnect }}>
+ <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">
+ <div ref={localPanel} data-host-view="local" aria-hidden={!!selected} {...(selected ? { inert: "" } : {})}
+ style={{ visibility: selected ? "hidden" : "visible" }}
+ className={`absolute inset-0 transition-opacity duration-150 motion-reduce:transition-none ${selected ? "invisible pointer-events-none opacity-0" : "visible opacity-100"}`}>
+ {children}
+ </div>
+ {frames.map((frame) => {
+ const active = selected?.id === frame.connection.id;
+ return <div key={`${frame.connection.id}:${frame.connection.gateway_id}`} data-host-view={frame.connection.id} aria-hidden={!active || offline}
+ {...(!active || offline ? { inert: "" } : {})} style={{ visibility: active ? "visible" : "hidden" }}
+ className={`absolute inset-0 transition-opacity duration-150 motion-reduce:transition-none ${active ? "visible opacity-100" : "invisible pointer-events-none opacity-0"}`}>
+ <iframe ref={(node) => { if (node) frameNodes.current.set(frame.connection.id, node); else frameNodes.current.delete(frame.connection.id); }}
+ src={frame.connection.url} title={t("remote.frameTitle", { name: frame.connection.name })}
+ className="h-full w-full border-0" referrerPolicy="no-referrer"
+ sandbox="allow-scripts allow-same-origin allow-forms allow-downloads allow-popups allow-popups-to-escape-sandbox"
+ onLoad={() => { bridge.initialize(frame.connection.id); hosts.loaded(frame.connection.id); }} />
+ </div>;
+ })}
+ {selected && (offline || !activeFrame?.loaded) && <div className="absolute inset-0 flex flex-col items-center justify-center gap-3 bg-background px-6 text-center">
+ {offline ? <PlugZap className="h-7 w-7 text-muted-foreground" /> : <Loader2 className="h-6 w-6 animate-spin text-muted-foreground" />}
+ <p className="font-medium">{t(offline ? "remote.offline" : "remote.opening")}</p>
+ <p className="max-w-sm text-sm text-muted-foreground">{message || t("remote.noFallback")}</p>
+ <div className="flex items-center gap-2">
+ {offline && <Button disabled={!!pending} onClick={() => switchHost(selected.id)}>{t("remote.reconnect")}</Button>}
+ <Button variant="ghost" onClick={hosts.local}>{t("remote.returnLocal")}</Button>
+ </div>
+ </div>}
+ </div>
+ {/* Older remote bundles cannot host the control. Keep an explicit exit
+ in a compact bottom strip, never cover their sidebar controls. */}
+ {selected && (!bridge.readyIds.includes(selected.id) || offline) && <div data-testid="legacy-host-footer" className="flex shrink-0 items-center border-t border-border/50 bg-sidebar px-2.5 py-1">
+ <div className="flex w-52 min-w-0"><HostSwitcher /></div>
+ </div>}
+ <RemoteHostMenu picker={picker} anchor={bridge.anchor} onClose={bridge.close} />
+ </div>
+ </HostNavigationContext.Provider>
+ </RemoteContext.Provider>;
+}
diff --git a/webui/src/components/remote/SSHHostPicker.tsx b/webui/src/components/remote/SSHHostPicker.tsx
new file mode 100644
index 000000000..3df22e31e
--- /dev/null
+++ b/webui/src/components/remote/SSHHostPicker.tsx
@@ -0,0 +1,97 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { ArrowRight, FileText, Loader2, RefreshCw, Search, Server } from "lucide-react";
+import { useTranslation } from "react-i18next";
+
+import { SettingsGroup, SettingsSectionTitle } from "@/components/settings/shared/SettingsControls";
+import { Button } from "@/components/ui/button";
+import { Disclosure } from "@/components/ui/disclosure";
+import { Input } from "@/components/ui/input";
+import { useClient } from "@/providers/ClientProvider";
+import { remoteAction, type SSHDiscovery } from "@/lib/remote-instances";
+
+export function SSHHostPicker({ disabled, onSelect }: {
+ disabled: boolean;
+ onSelect: (host: SSHDiscovery["hosts"][number]) => void;
+}) {
+ const { t } = useTranslation();
+ const { client } = useClient();
+ const [result, setResult] = useState<SSHDiscovery | null>(null);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const [configFile, setConfigFile] = useState("");
+ const [loadedFile, setLoadedFile] = useState("");
+ const [query, setQuery] = useState("");
+ const requestId = useRef(0);
+ const mounted = useRef(true);
+ const load = useCallback(async (file: string) => {
+ const id = ++requestId.current;
+ setBusy(true); setError("");
+ try {
+ const next = await remoteAction<SSHDiscovery>(client, "discover", { ssh_config: file.trim() });
+ if (!next || !Array.isArray(next.hosts) || !Array.isArray(next.files)
+ || typeof next.incomplete !== "boolean" || next.hosts.some((host) => !host
+ || typeof host.host !== "string" || typeof host.source !== "string" || typeof host.ssh_config !== "string")) {
+ throw new Error("discovery_failed");
+ }
+ if (mounted.current && id === requestId.current) {
+ setResult(next); setLoadedFile(file.trim()); setQuery("");
+ }
+ } catch (reason) {
+ if (mounted.current && id === requestId.current) {
+ const code = reason instanceof Error ? reason.message : "unknown";
+ setError(t(`remote.errors.${code}`, { defaultValue: t("remote.discoveryError") }));
+ }
+ } finally {
+ if (mounted.current && id === requestId.current) setBusy(false);
+ }
+ }, [client, t]);
+
+ useEffect(() => {
+ mounted.current = true;
+ let started = false;
+ const unsubscribe = client.onStatus((status) => {
+ if (status === "open" && !started) { started = true; void load(""); }
+ });
+ return () => { mounted.current = false; requestId.current += 1; unsubscribe(); };
+ }, [client, load]);
+
+ const hosts = (result?.hosts ?? []).filter(({ host }) => host.toLowerCase().includes(query.trim().toLowerCase()));
+ return <section className="settings-stack" aria-label={t("remote.sshHosts")}>
+ <div className="settings-section-heading">
+ <SettingsSectionTitle>{t("remote.sshHosts")}</SettingsSectionTitle>
+ <Button variant="ghost" size="icon" className="h-8 w-8" aria-label={t("remote.refreshHosts")} disabled={busy || disabled} onClick={() => { void load(loadedFile); }}>
+ <RefreshCw className={`h-4 w-4 ${busy ? "animate-spin" : ""}`} />
+ </Button>
+ </div>
+ <p className="settings-list-inset text-xs leading-5 text-muted-foreground">{t("remote.sshHostsHint")}</p>
+ {!!result?.hosts.length && <div className="settings-list-inset relative">
+ <div className="relative"><Search className="pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
+ <Input className="pl-9" aria-label={t("remote.searchHosts")} placeholder={t("remote.searchHosts")} value={query} onChange={(event) => setQuery(event.target.value)} />
+ </div>
+ </div>}
+ {hosts.length > 0 && <SettingsGroup>
+ <div className="max-h-64 overflow-y-auto">
+ {hosts.map((host) => <button key={host.host} type="button" disabled={disabled || busy}
+ aria-label={t("remote.useHost", { host: host.host })}
+ className="settings-list-row settings-hover flex w-full items-center gap-3 py-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50"
+ onClick={() => onSelect(host)}>
+ <Server className="h-[18px] w-[18px] shrink-0 text-muted-foreground" />
+ <span className="min-w-0 flex-1"><span className="block truncate text-[14px] font-medium">{host.host}</span>
+ <span title={host.source} className="mt-0.5 block truncate text-xs text-muted-foreground">{host.source}</span></span>
+ <ArrowRight className="h-4 w-4 shrink-0 text-muted-foreground" />
+ </button>)}
+ </div>
+ </SettingsGroup>}
+ {!result && busy && <p role="status" className="settings-list-inset flex items-center gap-2 text-xs text-muted-foreground"><Loader2 className="h-4 w-4 animate-spin" />{t("remote.loadingHosts")}</p>}
+ {result && !hosts.length && <p className="settings-list-inset text-[13px] leading-5 text-muted-foreground">{t(query ? "remote.noMatchingHosts" : "remote.noHosts")}</p>}
+ {result?.incomplete && <p className="settings-list-inset text-xs text-muted-foreground">{t("remote.partialHosts")}</p>}
+ <Disclosure summaryClassName="settings-list-inset flex min-h-10 items-center gap-2 rounded-xl text-xs text-muted-foreground settings-hover"
+ summary={<><FileText className="h-3.5 w-3.5" />{t("remote.otherConfig")}</>}>
+ <form className="settings-list-inset flex flex-wrap items-center gap-2 py-3" onSubmit={(event) => { event.preventDefault(); void load(configFile); }}>
+ <Input className="min-w-40 flex-1" aria-label={t("remote.configToRead")} placeholder="~/.ssh/config" value={configFile} disabled={busy || disabled} onChange={(event) => setConfigFile(event.target.value)} />
+ <Button type="submit" variant="outline" disabled={busy || disabled}>{t("remote.readConfig")}</Button>
+ </form>
+ </Disclosure>
+ {error && <p role="alert" className="settings-list-inset text-[13px] leading-5 text-destructive">{error}</p>}
+ </section>;
+}
diff --git a/webui/src/components/remote/host-bridge.ts b/webui/src/components/remote/host-bridge.ts
new file mode 100644
index 000000000..5fafee46a
--- /dev/null
+++ b/webui/src/components/remote/host-bridge.ts
@@ -0,0 +1,36 @@
+// The embedded UI may ask to open the host menu, never execute SSH actions.
+// Host lists, paths and credentials remain exclusively in the local shell.
+export const HOST_BRIDGE = "nanobot.host-navigation.v1";
+export interface HostAnchor { left: number; top: number; width: number; height: number }
+export interface EmbeddedHost { name: string; hostname: string; pendingName?: string; error?: string }
+
+export function isLocalShellOrigin(origin: string): boolean {
+ try {
+ const url = new URL(origin);
+ return url.origin === origin && ["http:", "https:"].includes(url.protocol)
+ && ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname);
+ } catch { return false; }
+}
+
+export function bridgeMessage(value: unknown): Record<string, unknown> | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const message = value as Record<string, unknown>;
+ return message.channel === HOST_BRIDGE && typeof message.type === "string" ? message : null;
+}
+
+export function readEmbeddedHost(message: Record<string, unknown>): EmbeddedHost | null {
+ return typeof message.name === "string" && message.name.length > 0 && message.name.length <= 120
+ && typeof message.hostname === "string" && message.hostname.length <= 255
+ && (message.pendingName === undefined || typeof message.pendingName === "string" && message.pendingName.length <= 120)
+ && (message.error === undefined || typeof message.error === "string" && message.error.length <= 1024)
+ ? { name: message.name, hostname: message.hostname, pendingName: message.pendingName as string | undefined, error: message.error as string | undefined } : null;
+}
+
+export function readHostAnchor(value: unknown): HostAnchor | null {
+ if (!value || typeof value !== "object") return null;
+ const rect = value as Record<string, unknown>;
+ return ["left", "top", "width", "height"].every((key) => typeof rect[key] === "number"
+ && Number.isFinite(rect[key]) && Math.abs(rect[key] as number) <= 100_000)
+ && (rect.width as number) > 0 && (rect.height as number) > 0
+ ? { left: rect.left as number, top: rect.top as number, width: rect.width as number, height: rect.height as number } : null;
+}
diff --git a/webui/src/components/remote/useHostSessions.ts b/webui/src/components/remote/useHostSessions.ts
new file mode 100644
index 000000000..2b520c222
--- /dev/null
+++ b/webui/src/components/remote/useHostSessions.ts
@@ -0,0 +1,186 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useClient } from "@/providers/ClientProvider";
+import { readRemoteInstances, readSelectedRemote, rememberSelectedRemote, remoteAction, validateRemoteConnection, type RemoteConnection, type RemoteDirectory, type SelectedRemote } from "@/lib/remote-instances";
+
+// Never silently evict a view containing drafts or unfinished attachments.
+// Tunnels are shared across browser tabs, so only explicit disconnect closes one.
+export const MAX_HOST_VIEWS = 3;
+export interface HostFrame {
+ connection: RemoteConnection;
+ loaded: boolean;
+ offline: boolean;
+ failures: number;
+}
+interface PendingSwitch { id: string; name: string }
+
+export function useHostSessions() {
+ const { client, getToken } = useClient();
+ const [directory, setDirectory] = useState<RemoteDirectory | null>(null);
+ const [directoryError, setDirectoryError] = useState(false);
+ const [selected, setSelected] = useState<SelectedRemote | null>(readSelectedRemote);
+ const selectedRef = useRef(selected);
+ const initial = useRef(selected);
+ const cache = useRef(new Map<string, HostFrame>());
+ const [frames, setFrames] = useState<HostFrame[]>([]);
+ const [pending, setPending] = useState<PendingSwitch | null>(null);
+ const pendingRef = useRef<PendingSwitch | null>(null);
+ const [error, setError] = useState("");
+ const mounted = useRef(true);
+ const epoch = useRef(0);
+ const waiter = useRef<{ id: string; finish: (ready: boolean) => void } | null>(null);
+ const publish = useCallback(() => { if (mounted.current) setFrames([...cache.current.values()]); }, []);
+ const setPendingSwitch = useCallback((value: PendingSwitch | null) => {
+ pendingRef.current = value;
+ if (mounted.current) setPending(value);
+ }, []);
+ const cancel = useCallback(() => {
+ epoch.current += 1;
+ waiter.current?.finish(false);
+ waiter.current = null;
+ setPendingSwitch(null);
+ }, [setPendingSwitch]);
+ const select = useCallback((value: SelectedRemote | null) => {
+ selectedRef.current = value;
+ setSelected(value);
+ rememberSelectedRemote(value);
+ setError("");
+ publish();
+ }, [publish]);
+ const local = useCallback(() => { cancel(); select(null); }, [cancel, select]);
+ const refresh = useCallback(async () => {
+ try {
+ const next = window.top === window ? await readRemoteInstances(getToken()) : { available: false, profiles: [] };
+ if (mounted.current) { setDirectory(next); setDirectoryError(false); }
+ return next;
+ } catch (reason) {
+ if (mounted.current) setDirectoryError(true);
+ throw reason;
+ }
+ }, [getToken]);
+
+ const connect = useCallback(async (id: string, stillWanted: () => boolean = () => true) => {
+ cancel();
+ const attempt = epoch.current;
+ const wanted = () => mounted.current && attempt === epoch.current && stillWanted();
+ const warm = cache.current.get(id);
+ if (warm?.loaded && !warm.offline) {
+ if (wanted()) select(warm.connection);
+ return;
+ }
+ if (!warm && cache.current.size >= MAX_HOST_VIEWS) throw new Error("view_limit");
+ const name = directory?.profiles.find((item) => item.id === id)?.name || initial.current?.name || id;
+ setPendingSwitch({ id, name });
+ setError("");
+ let openingFrame = warm?.loaded ? undefined : warm;
+ try {
+ const connection = validateRemoteConnection(await remoteAction<RemoteConnection>(client, "connect", { id }));
+ if (!wanted()) {
+ // A cancelled SSH request can finish later. Never switch away from the
+ // latest choice or close its tunnel, which another tab may already use.
+ return;
+ }
+ let frame = cache.current.get(id);
+ if (!frame || frame.connection.url !== connection.url || frame.connection.gateway_id !== connection.gateway_id) {
+ frame = { connection, loaded: false, offline: false, failures: 0 };
+ cache.current.set(id, frame);
+ } else {
+ frame.connection = connection;
+ frame.offline = false; frame.failures = 0;
+ }
+ if (!frame.loaded) openingFrame = frame;
+ publish();
+ void refresh().catch(() => {});
+ if (!frame.loaded) {
+ const ready = await new Promise<boolean>((resolve, reject) => {
+ const timer = window.setTimeout(() => {
+ waiter.current = null;
+ reject(new Error("view_load_failed"));
+ }, 25_000);
+ waiter.current = { id, finish: (ready) => { window.clearTimeout(timer); resolve(ready); } };
+ });
+ if (!ready) return;
+ }
+ if (wanted()) select(connection);
+ } catch (reason) {
+ if (wanted()) throw reason;
+ } finally {
+ // Cancelled/failed cold pages contain no user work. Don't let them use up
+ // the view budget; a newer attempt for this host owns its transport now.
+ if (openingFrame && !openingFrame.loaded && cache.current.get(id) === openingFrame
+ && (attempt === epoch.current || pendingRef.current?.id !== id)) {
+ cache.current.delete(id);
+ publish();
+ }
+ if (attempt === epoch.current) setPendingSwitch(null);
+ }
+ }, [cancel, client, directory, publish, refresh, select, setPendingSwitch]);
+ const connectRef = useRef(connect);
+ connectRef.current = connect;
+ const loaded = useCallback((id: string) => {
+ const frame = cache.current.get(id);
+ 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) => {
+ if (pendingRef.current?.id === id) cancel();
+ await remoteAction(client, "disconnect", { id });
+ if (selectedRef.current?.id === id) local();
+ cache.current.delete(id);
+ publish();
+ await refresh();
+ }, [cancel, client, local, publish, refresh]);
+
+ useEffect(() => {
+ mounted.current = true;
+ void refresh().catch(() => {});
+ return () => { mounted.current = false; cancel(); };
+ }, [cancel, refresh]);
+ useEffect(() => {
+ const saved = initial.current;
+ if (!saved || window.top !== window) return;
+ let started = false;
+ const timer = window.setTimeout(() => {
+ started = true;
+ if (selectedRef.current?.id === saved.id) setError("ssh_unreachable");
+ }, 15_000);
+ const unsubscribe = client.onStatus((status) => {
+ if (status !== "open" || started) return;
+ started = true;
+ window.clearTimeout(timer);
+ if (selectedRef.current?.id !== saved.id) return;
+ void connectRef.current(saved.id).catch((reason: unknown) => {
+ if (mounted.current && selectedRef.current?.id === saved.id) setError(reason instanceof Error ? reason.message : "unknown");
+ });
+ });
+ return () => { window.clearTimeout(timer); unsubscribe(); };
+ }, [client]);
+ useEffect(() => {
+ let checking = false;
+ let cancelled = false;
+ const tick = async () => {
+ if (checking || !cache.current.size) return;
+ checking = true;
+ try {
+ const next = await readRemoteInstances(getToken());
+ if (cancelled) return;
+ setDirectory(next); setDirectoryError(false);
+ for (const [id, frame] of cache.current) {
+ if (id === pendingRef.current?.id) continue;
+ const connected = next.profiles.some((profile) => profile.id === id && profile.connected);
+ frame.failures = connected ? 0 : frame.failures + 1;
+ if (connected || frame.failures >= 2) frame.offline = !connected;
+ }
+ } catch {
+ if (!cancelled) for (const frame of cache.current.values()) {
+ if (++frame.failures >= 2) frame.offline = true;
+ }
+ } finally {
+ checking = false;
+ if (!cancelled) publish();
+ }
+ };
+ const timer = window.setInterval(() => { void tick(); }, 5_000);
+ return () => { cancelled = true; window.clearInterval(timer); };
+ }, [client, getToken, publish]);
+ return { directory, directoryError, refresh, selected, frames, pending, error, setError, connect, cancel, local, disconnect, loaded };
+}
diff --git a/webui/src/components/remote/useSidebarHostBridge.ts b/webui/src/components/remote/useSidebarHostBridge.ts
new file mode 100644
index 000000000..81055b8ee
--- /dev/null
+++ b/webui/src/components/remote/useSidebarHostBridge.ts
@@ -0,0 +1,88 @@
+import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
+import { HOST_BRIDGE, bridgeMessage, isLocalShellOrigin, readEmbeddedHost, readHostAnchor, type EmbeddedHost, type HostAnchor } from "./host-bridge";
+import type { HostFrame } from "./useHostSessions";
+
+interface Peer { source: Window; origin: string; nonce: string }
+export function useSidebarHostBridge(frames: HostFrame[], selectedId: string | undefined,
+ nodes: RefObject<Map<string, HTMLIFrameElement>>, restoreLocalFocus: () => void,
+ activity: { pendingName?: string; error?: string }) {
+ const [embedded, setEmbedded] = useState<EmbeddedHost | null>(null);
+ const [readyIds, setReadyIds] = useState<string[]>([]);
+ const [anchor, setAnchor] = useState<HostAnchor | null>(null);
+ const parent = useRef<Peer | null>(null);
+ const peers = useRef(new Map<string, Peer>());
+ const latest = useRef({ frames, selectedId, restoreLocalFocus, activity });
+ latest.current = { frames, selectedId, restoreLocalFocus, activity };
+ const initialize = useCallback((id: string) => {
+ const frame = latest.current.frames.find((item) => item.connection.id === id);
+ const source = nodes.current?.get(id)?.contentWindow;
+ if (!frame || !source) return;
+ const origin = new URL(frame.connection.url).origin;
+ let peer = peers.current.get(id);
+ if (!peer || peer.source !== source || peer.origin !== origin) {
+ peer = { source, origin, nonce: crypto.randomUUID() };
+ peers.current.set(id, peer);
+ setReadyIds((ids) => ids.filter((value) => value !== id));
+ }
+ // Deliberately only public display identity, never SSH metadata or secrets.
+ source.postMessage({ channel: HOST_BRIDGE, type: "init", nonce: peer.nonce,
+ name: frame.connection.name, hostname: frame.connection.hostname,
+ ...(latest.current.selectedId === id ? latest.current.activity : {}) }, origin);
+ }, [nodes]);
+ useEffect(() => {
+ const receive = (event: MessageEvent<unknown>) => {
+ const message = bridgeMessage(event.data);
+ if (!message) return;
+ if (window.parent !== window) {
+ if (event.source !== window.parent || !isLocalShellOrigin(event.origin)) return;
+ const current = parent.current;
+ if (current && (current.origin !== event.origin || current.nonce !== message.nonce)) return;
+ if (message.type === "init") {
+ const host = readEmbeddedHost(message);
+ if (!host || typeof message.nonce !== "string" || !/^[a-f0-9-]{36}$/.test(message.nonce)) return;
+ parent.current = { source: window.parent, origin: event.origin, nonce: message.nonce };
+ setEmbedded(host);
+ window.parent.postMessage({ channel: HOST_BRIDGE, type: "ready", nonce: message.nonce }, event.origin);
+ } else if (message.type === "focus" && current) latest.current.restoreLocalFocus();
+ return;
+ }
+ // Both source and origin must match a frame this shell actually owns.
+ const frame = latest.current.frames.find((item) => nodes.current?.get(item.connection.id)?.contentWindow === event.source
+ && new URL(item.connection.url).origin === event.origin);
+ if (!frame) return;
+ const id = frame.connection.id;
+ if (message.type === "hello") { initialize(id); return; }
+ const peer = peers.current.get(id);
+ if (!peer || message.nonce !== peer.nonce) return;
+ if (message.type === "ready") {
+ setReadyIds((ids) => ids.includes(id) ? ids : [...ids, id]);
+ } else if (message.type === "open" && latest.current.selectedId === id && !frame.offline) {
+ const rect = readHostAnchor(message.anchor);
+ const outer = nodes.current?.get(id)?.getBoundingClientRect();
+ if (rect && outer) setAnchor({ ...rect, left: outer.left + rect.left, top: outer.top + rect.top });
+ }
+ // No select/connect/disconnect action is accepted from an embedded page.
+ };
+ window.addEventListener("message", receive);
+ // A public capability probe carries no identity, settings or credentials.
+ if (window.parent !== window) window.parent.postMessage({ channel: HOST_BRIDGE, type: "hello" }, "*");
+ return () => window.removeEventListener("message", receive);
+ }, [initialize, nodes]);
+ useEffect(() => { setAnchor(null); }, [selectedId]);
+ useEffect(() => {
+ if (selectedId && peers.current.has(selectedId)) initialize(selectedId);
+ }, [initialize, selectedId, activity.pendingName, activity.error]);
+ useEffect(() => {
+ for (const id of peers.current.keys()) if (!frames.some((frame) => frame.connection.id === id)) peers.current.delete(id);
+ }, [frames]);
+ const focus = (id: string) => {
+ const peer = peers.current.get(id);
+ if (peer && readyIds.includes(id)) peer.source.postMessage({ channel: HOST_BRIDGE, type: "focus", nonce: peer.nonce }, peer.origin);
+ else nodes.current?.get(id)?.focus({ preventScroll: true });
+ };
+ return { anchor, close: () => setAnchor(null), readyIds, initialize, focus,
+ embedded: embedded ? { ...embedded, kind: "embedded" as const, open: (position: HostAnchor) => {
+ const peer = parent.current;
+ peer?.source.postMessage({ channel: HOST_BRIDGE, type: "open", nonce: peer.nonce, anchor: position }, peer.origin);
+ } } : null };
+}
diff --git a/webui/src/components/settings/SettingsSidebar.tsx b/webui/src/components/settings/SettingsSidebar.tsx
index c54cb2b37..de2157bc6 100644
--- a/webui/src/components/settings/SettingsSidebar.tsx
+++ b/webui/src/components/settings/SettingsSidebar.tsx
@@ -1,4 +1,5 @@
-import { useRef, useState } from "react";
+import { useContext, useRef, useState } from "react";
+import { HostNavigationContext, HostSwitcher } from "@/components/remote/HostSwitcher";
import {
Activity,
Info,
@@ -76,6 +77,7 @@ export function SettingsSidebar(props: SettingsSidebarProps) {
isNativeHost,
} = props;
const { t } = useTranslation();
+ const hostNavigation = useContext(HostNavigationContext);
const mobile = useMediaQuery("(max-width: 1023px)");
const restartLabel = isRestarting
? t(isNativeHost ? "app.system.restartingEngine" : "app.system.restarting")
@@ -185,6 +187,7 @@ export function SettingsSidebar(props: SettingsSidebarProps) {
<span>{t("app.account.logout")}</span>
</Button>
) : null}
+ {hostNavigation && <div className="mt-2 flex min-w-0"><HostSwitcher /></div>}
</div>
</aside>
);
@@ -207,6 +210,7 @@ function MobileSettingsNavigation({
restartLabel: string;
}) {
const { t } = useTranslation();
+ const hostNavigation = useContext(HostNavigationContext);
const [open, setOpen] = useState(false);
const restart = () => { setOpen(false); onRestart?.(); };
const restartTone = restartPending && !isRestarting
@@ -274,6 +278,7 @@ function MobileSettingsNavigation({
</> : null}
</DropdownMenuContent>
</DropdownMenu>
+ {hostNavigation && <HostSwitcher collapsed />}
</div>
{onRestart && (restartPending || isRestarting) ? (
<div className="flex min-h-11 items-center justify-between gap-2 px-4 pb-1">
diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.json
index f5fd7bf8b..a9cb7948e 100644
--- a/webui/src/i18n/locales/en/common.json
+++ b/webui/src/i18n/locales/en/common.json
@@ -1,4 +1,106 @@
{
+ "remote": {
+ "localShort": "Local",
+ "disconnectTitle": "Disconnect from {{name}}?",
+ "disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
+ "hostBar": "Current connection",
+ "switchHost": "Switch host",
+ "manageConnections": "Manage connections…",
+ "ready": "Ready",
+ "preparing": "Connecting to {{name}}…",
+ "cancelSwitch": "Cancel switch",
+ "localEnvironment": "Local · {{name}}",
+ "sshHosts": "From your SSH config",
+ "sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
+ "refreshHosts": "Refresh SSH hosts",
+ "searchHosts": "Search SSH hosts",
+ "useHost": "Use {{host}}",
+ "loadingHosts": "Reading SSH config…",
+ "noHosts": "No named hosts found. You can enter an SSH address below.",
+ "noMatchingHosts": "No matching hosts.",
+ "partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
+ "otherConfig": "Use another SSH config file",
+ "configToRead": "SSH config file to read",
+ "readConfig": "Read hosts",
+ "discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
+ "portPlaceholder": "Use SSH config (normally 22)",
+ "loading": "Loading connections…",
+ "retry": "Retry",
+ "unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
+ "back": "Back",
+ "disconnect": "Disconnect",
+ "verifyTitle": "Verify this server",
+ "verifyDescription": "Before connecting for the first time, compare this SSH fingerprint with your server console or administrator.",
+ "verifyHint": "Continue only if it matches. Only this server's public key is saved; your system SSH config is unchanged.",
+ "verifyConnect": "Fingerprint matches · Connect",
+ "title": "Remote connections",
+ "description": "Connect to nanobot on a server. Chats and settings stay there.",
+ "local": "Local nanobot",
+ "current": "Currently using",
+ "remote": "Remote",
+ "returnLocal": "Back to local nanobot",
+ "add": "Connect to remote nanobot…",
+ "addTitle": "Connect to remote nanobot",
+ "addDescription": "Connect to a nanobot that's already running on your server.",
+ "host": "SSH address",
+ "name": "Name (optional)",
+ "namePlaceholder": "Team server",
+ "keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
+ "advanced": "Advanced",
+ "sshPort": "SSH port",
+ "ssh_config": "SSH config file (optional)",
+ "identity_file": "Private key path (optional)",
+ "config_path": "Server's nanobot config path",
+ "runtime_user": "nanobot service account (optional)",
+ "saveConnect": "Save & connect",
+ "connecting": "Connecting…",
+ "opening": "Opening your server…",
+ "frameTitle": "nanobot on {{name}}",
+ "offline": "Server connection lost",
+ "noFallback": "You're still using remote nanobot. Nothing is sent to local nanobot.",
+ "reconnect": "Reconnect",
+ "manage": "Manage {{name}}",
+ "edit": "Edit connection",
+ "forget": "Forget server",
+ "forgetTitle": "Forget {{name}}?",
+ "forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
+ "errors": {
+ "view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
+ "view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
+ "same_instance": "This is the nanobot you are already using. No remote connection is needed.",
+ "ssh_config_unreadable": "This SSH config could not be read. Check its path, permissions and format.",
+ "local_port_in_use": "This connection's local port is in use. Close the conflicting application, or forget and add this server again.",
+ "host_key_scan_failed": "Couldn't retrieve this server's fingerprint. For jump hosts, verify it through your existing SSH configuration.",
+ "unknown": "Couldn't connect. Check the server and try again.",
+ "directory_unavailable": "Couldn't read your saved servers. Please try again.",
+ "ssh_unavailable": "Install the OpenSSH client on this machine to connect.",
+ "ssh_auth_failed": "SSH couldn't sign in. Check the username and key, and unlock your key in the system SSH agent if needed.",
+ "ssh_unreachable": "Can't reach SSH on this server. Check the address, port and network.",
+ "host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
+ "host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
+ "local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
+ "runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
+ "python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
+ "config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
+ "config_invalid": "Couldn't read the server's nanobot configuration.",
+ "webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
+ "webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
+ "public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+ "remote_auth_failed": "The server rejected its saved WebUI credential. Check its running configuration.",
+ "incompatible_gateway": "This endpoint isn't a compatible nanobot gateway. Update the server or check its configuration.",
+ "webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
+ "remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
+ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
+ "invalid_profile": "Check the address, port and Advanced fields.",
+ "profile_not_found": "This saved server no longer exists. Refresh the list.",
+ "profile_limit": "You can save up to 20 servers.",
+ "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.",
+ "invalid_remote_url": "The connection returned an unexpected address. It was blocked."
+ }
+ },
"previewTabs": {
"title": "Preview",
"closeTab": "Close {{name}}",
diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.json
index 6e434a3bb..2b3ba95e5 100644
--- a/webui/src/i18n/locales/es/common.json
+++ b/webui/src/i18n/locales/es/common.json
@@ -1,4 +1,106 @@
{
+ "remote": {
+ "localShort": "Local",
+ "disconnectTitle": "Disconnect from {{name}}?",
+ "disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
+ "hostBar": "Current connection",
+ "switchHost": "Switch host",
+ "manageConnections": "Manage connections…",
+ "ready": "Ready",
+ "preparing": "Connecting to {{name}}…",
+ "cancelSwitch": "Cancel switch",
+ "localEnvironment": "Local · {{name}}",
+ "sshHosts": "From your SSH config",
+ "sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
+ "refreshHosts": "Refresh SSH hosts",
+ "searchHosts": "Search SSH hosts",
+ "useHost": "Use {{host}}",
+ "loadingHosts": "Reading SSH config…",
+ "noHosts": "No named hosts found. You can enter an SSH address below.",
+ "noMatchingHosts": "No matching hosts.",
+ "partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
+ "otherConfig": "Use another SSH config file",
+ "configToRead": "SSH config file to read",
+ "readConfig": "Read hosts",
+ "discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
+ "portPlaceholder": "Use SSH config (normally 22)",
+ "loading": "Loading connections…",
+ "retry": "Retry",
+ "unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
+ "back": "Back",
+ "disconnect": "Disconnect",
+ "verifyTitle": "Verify this server",
+ "verifyDescription": "Before connecting for the first time, compare this SSH fingerprint with your server console or administrator.",
+ "verifyHint": "Continue only if it matches. Only this server's public key is saved; your system SSH config is unchanged.",
+ "verifyConnect": "Fingerprint matches · Connect",
+ "title": "Remote connections",
+ "description": "Connect to nanobot on a server. Chats and settings stay there.",
+ "local": "Local nanobot",
+ "current": "Currently using",
+ "remote": "Remote",
+ "returnLocal": "Back to local nanobot",
+ "add": "Connect to remote nanobot…",
+ "addTitle": "Connect to remote nanobot",
+ "addDescription": "Connect to a nanobot that's already running on your server.",
+ "host": "SSH address",
+ "name": "Name (optional)",
+ "namePlaceholder": "Team server",
+ "keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
+ "advanced": "Advanced",
+ "sshPort": "SSH port",
+ "ssh_config": "SSH config file (optional)",
+ "identity_file": "Private key path (optional)",
+ "config_path": "Server's nanobot config path",
+ "runtime_user": "nanobot service account (optional)",
+ "saveConnect": "Save & connect",
+ "connecting": "Connecting…",
+ "opening": "Opening your server…",
+ "frameTitle": "nanobot on {{name}}",
+ "offline": "Server connection lost",
+ "noFallback": "You're still using remote nanobot. Nothing is sent to local nanobot.",
+ "reconnect": "Reconnect",
+ "manage": "Manage {{name}}",
+ "edit": "Edit connection",
+ "forget": "Forget server",
+ "forgetTitle": "Forget {{name}}?",
+ "forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
+ "errors": {
+ "view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
+ "view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
+ "same_instance": "This is the nanobot you are already using. No remote connection is needed.",
+ "ssh_config_unreadable": "This SSH config could not be read. Check its path, permissions and format.",
+ "local_port_in_use": "This connection's local port is in use. Close the conflicting application, or forget and add this server again.",
+ "host_key_scan_failed": "Couldn't retrieve this server's fingerprint. For jump hosts, verify it through your existing SSH configuration.",
+ "unknown": "Couldn't connect. Check the server and try again.",
+ "directory_unavailable": "Couldn't read your saved servers. Please try again.",
+ "ssh_unavailable": "Install the OpenSSH client on this machine to connect.",
+ "ssh_auth_failed": "SSH couldn't sign in. Check the username and key, and unlock your key in the system SSH agent if needed.",
+ "ssh_unreachable": "Can't reach SSH on this server. Check the address, port and network.",
+ "host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
+ "host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
+ "local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
+ "runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
+ "python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
+ "config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
+ "config_invalid": "Couldn't read the server's nanobot configuration.",
+ "webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
+ "webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
+ "public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+ "remote_auth_failed": "The server rejected its saved WebUI credential. Check its running configuration.",
+ "incompatible_gateway": "This endpoint isn't a compatible nanobot gateway. Update the server or check its configuration.",
+ "webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
+ "remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
+ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
+ "invalid_profile": "Check the address, port and Advanced fields.",
+ "profile_not_found": "This saved server no longer exists. Refresh the list.",
+ "profile_limit": "You can save up to 20 servers.",
+ "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.",
+ "invalid_remote_url": "The connection returned an unexpected address. It was blocked."
+ }
+ },
"previewTabs": {
"title": "Vista previa",
"closeTab": "Cerrar {{name}}",
diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.json
index fa5e4b25c..d1da50c23 100644
--- a/webui/src/i18n/locales/fr/common.json
+++ b/webui/src/i18n/locales/fr/common.json
@@ -1,4 +1,106 @@
{
+ "remote": {
+ "localShort": "Local",
+ "disconnectTitle": "Disconnect from {{name}}?",
+ "disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
+ "hostBar": "Current connection",
+ "switchHost": "Switch host",
+ "manageConnections": "Manage connections…",
+ "ready": "Ready",
+ "preparing": "Connecting to {{name}}…",
+ "cancelSwitch": "Cancel switch",
+ "localEnvironment": "Local · {{name}}",
+ "sshHosts": "From your SSH config",
+ "sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
+ "refreshHosts": "Refresh SSH hosts",
+ "searchHosts": "Search SSH hosts",
+ "useHost": "Use {{host}}",
+ "loadingHosts": "Reading SSH config…",
+ "noHosts": "No named hosts found. You can enter an SSH address below.",
+ "noMatchingHosts": "No matching hosts.",
+ "partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
+ "otherConfig": "Use another SSH config file",
+ "configToRead": "SSH config file to read",
+ "readConfig": "Read hosts",
+ "discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
+ "portPlaceholder": "Use SSH config (normally 22)",
+ "loading": "Loading connections…",
+ "retry": "Retry",
+ "unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
+ "back": "Back",
+ "disconnect": "Disconnect",
+ "verifyTitle": "Verify this server",
+ "verifyDescription": "Before connecting for the first time, compare this SSH fingerprint with your server console or administrator.",
+ "verifyHint": "Continue only if it matches. Only this server's public key is saved; your system SSH config is unchanged.",
+ "verifyConnect": "Fingerprint matches · Connect",
+ "title": "Remote connections",
+ "description": "Connect to nanobot on a server. Chats and settings stay there.",
+ "local": "Local nanobot",
+ "current": "Currently using",
+ "remote": "Remote",
+ "returnLocal": "Back to local nanobot",
+ "add": "Connect to remote nanobot…",
+ "addTitle": "Connect to remote nanobot",
+ "addDescription": "Connect to a nanobot that's already running on your server.",
+ "host": "SSH address",
+ "name": "Name (optional)",
+ "namePlaceholder": "Team server",
+ "keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
+ "advanced": "Advanced",
+ "sshPort": "SSH port",
+ "ssh_config": "SSH config file (optional)",
+ "identity_file": "Private key path (optional)",
+ "config_path": "Server's nanobot config path",
+ "runtime_user": "nanobot service account (optional)",
+ "saveConnect": "Save & connect",
+ "connecting": "Connecting…",
+ "opening": "Opening your server…",
+ "frameTitle": "nanobot on {{name}}",
+ "offline": "Server connection lost",
+ "noFallback": "You're still using remote nanobot. Nothing is sent to local nanobot.",
+ "reconnect": "Reconnect",
+ "manage": "Manage {{name}}",
+ "edit": "Edit connection",
+ "forget": "Forget server",
+ "forgetTitle": "Forget {{name}}?",
+ "forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
+ "errors": {
+ "view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
+ "view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
+ "same_instance": "This is the nanobot you are already using. No remote connection is needed.",
+ "ssh_config_unreadable": "This SSH config could not be read. Check its path, permissions and format.",
+ "local_port_in_use": "This connection's local port is in use. Close the conflicting application, or forget and add this server again.",
+ "host_key_scan_failed": "Couldn't retrieve this server's fingerprint. For jump hosts, verify it through your existing SSH configuration.",
+ "unknown": "Couldn't connect. Check the server and try again.",
+ "directory_unavailable": "Couldn't read your saved servers. Please try again.",
+ "ssh_unavailable": "Install the OpenSSH client on this machine to connect.",
+ "ssh_auth_failed": "SSH couldn't sign in. Check the username and key, and unlock your key in the system SSH agent if needed.",
+ "ssh_unreachable": "Can't reach SSH on this server. Check the address, port and network.",
+ "host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
+ "host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
+ "local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
+ "runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
+ "python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
+ "config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
+ "config_invalid": "Couldn't read the server's nanobot configuration.",
+ "webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
+ "webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
+ "public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+ "remote_auth_failed": "The server rejected its saved WebUI credential. Check its running configuration.",
+ "incompatible_gateway": "This endpoint isn't a compatible nanobot gateway. Update the server or check its configuration.",
+ "webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
+ "remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
+ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
+ "invalid_profile": "Check the address, port and Advanced fields.",
+ "profile_not_found": "This saved server no longer exists. Refresh the list.",
+ "profile_limit": "You can save up to 20 servers.",
+ "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.",
+ "invalid_remote_url": "The connection returned an unexpected address. It was blocked."
+ }
+ },
"previewTabs": {
"title": "Aperçu",
"closeTab": "Fermer {{name}}",
diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.json
index 4bfaa1374..256204d25 100644
--- a/webui/src/i18n/locales/id/common.json
+++ b/webui/src/i18n/locales/id/common.json
@@ -1,4 +1,106 @@
{
+ "remote": {
+ "localShort": "Local",
+ "disconnectTitle": "Disconnect from {{name}}?",
+ "disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
+ "hostBar": "Current connection",
+ "switchHost": "Switch host",
+ "manageConnections": "Manage connections…",
+ "ready": "Ready",
+ "preparing": "Connecting to {{name}}…",
+ "cancelSwitch": "Cancel switch",
+ "localEnvironment": "Local · {{name}}",
+ "sshHosts": "From your SSH config",
+ "sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
+ "refreshHosts": "Refresh SSH hosts",
+ "searchHosts": "Search SSH hosts",
+ "useHost": "Use {{host}}",
+ "loadingHosts": "Reading SSH config…",
+ "noHosts": "No named hosts found. You can enter an SSH address below.",
+ "noMatchingHosts": "No matching hosts.",
+ "partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
+ "otherConfig": "Use another SSH config file",
+ "configToRead": "SSH config file to read",
+ "readConfig": "Read hosts",
+ "discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
+ "portPlaceholder": "Use SSH config (normally 22)",
+ "loading": "Loading connections…",
+ "retry": "Retry",
+ "unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
+ "back": "Back",
+ "disconnect": "Disconnect",
+ "verifyTitle": "Verify this server",
+ "verifyDescription": "Before connecting for the first time, compare this SSH fingerprint with your server console or administrator.",
+ "verifyHint": "Continue only if it matches. Only this server's public key is saved; your system SSH config is unchanged.",
+ "verifyConnect": "Fingerprint matches · Connect",
+ "title": "Remote connections",
+ "description": "Connect to nanobot on a server. Chats and settings stay there.",
+ "local": "Local nanobot",
+ "current": "Currently using",
+ "remote": "Remote",
+ "returnLocal": "Back to local nanobot",
+ "add": "Connect to remote nanobot…",
+ "addTitle": "Connect to remote nanobot",
+ "addDescription": "Connect to a nanobot that's already running on your server.",
+ "host": "SSH address",
+ "name": "Name (optional)",
+ "namePlaceholder": "Team server",
+ "keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
+ "advanced": "Advanced",
+ "sshPort": "SSH port",
+ "ssh_config": "SSH config file (optional)",
+ "identity_file": "Private key path (optional)",
+ "config_path": "Server's nanobot config path",
+ "runtime_user": "nanobot service account (optional)",
+ "saveConnect": "Save & connect",
+ "connecting": "Connecting…",
+ "opening": "Opening your server…",
+ "frameTitle": "nanobot on {{name}}",
+ "offline": "Server connection lost",
+ "noFallback": "You're still using remote nanobot. Nothing is sent to local nanobot.",
+ "reconnect": "Reconnect",
+ "manage": "Manage {{name}}",
+ "edit": "Edit connection",
+ "forget": "Forget server",
+ "forgetTitle": "Forget {{name}}?",
+ "forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
+ "errors": {
+ "view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
+ "view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
+ "same_instance": "This is the nanobot you are already using. No remote connection is needed.",
+ "ssh_config_unreadable": "This SSH config could not be read. Check its path, permissions and format.",
+ "local_port_in_use": "This connection's local port is in use. Close the conflicting application, or forget and add this server again.",
+ "host_key_scan_failed": "Couldn't retrieve this server's fingerprint. For jump hosts, verify it through your existing SSH configuration.",
+ "unknown": "Couldn't connect. Check the server and try again.",
+ "directory_unavailable": "Couldn't read your saved servers. Please try again.",
+ "ssh_unavailable": "Install the OpenSSH client on this machine to connect.",
+ "ssh_auth_failed": "SSH couldn't sign in. Check the username and key, and unlock your key in the system SSH agent if needed.",
+ "ssh_unreachable": "Can't reach SSH on this server. Check the address, port and network.",
+ "host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
+ "host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
+ "local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
+ "runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
+ "python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
+ "config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
+ "config_invalid": "Couldn't read the server's nanobot configuration.",
+ "webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
+ "webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
+ "public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+ "remote_auth_failed": "The server rejected its saved WebUI credential. Check its running configuration.",
+ "incompatible_gateway": "This endpoint isn't a compatible nanobot gateway. Update the server or check its configuration.",
+ "webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
+ "remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
+ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
+ "invalid_profile": "Check the address, port and Advanced fields.",
+ "profile_not_found": "This saved server no longer exists. Refresh the list.",
+ "profile_limit": "You can save up to 20 servers.",
+ "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.",
+ "invalid_remote_url": "The connection returned an unexpected address. It was blocked."
+ }
+ },
"previewTabs": {
"title": "Pratinjau",
"closeTab": "Tutup {{name}}",
diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.json
index 72d74490c..d32b9f583 100644
--- a/webui/src/i18n/locales/ja/common.json
+++ b/webui/src/i18n/locales/ja/common.json
@@ -1,4 +1,106 @@
{
+ "remote": {
+ "localShort": "Local",
+ "disconnectTitle": "Disconnect from {{name}}?",
+ "disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
+ "hostBar": "Current connection",
+ "switchHost": "Switch host",
+ "manageConnections": "Manage connections…",
+ "ready": "Ready",
+ "preparing": "Connecting to {{name}}…",
+ "cancelSwitch": "Cancel switch",
+ "localEnvironment": "Local · {{name}}",
+ "sshHosts": "From your SSH config",
+ "sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
+ "refreshHosts": "Refresh SSH hosts",
+ "searchHosts": "Search SSH hosts",
+ "useHost": "Use {{host}}",
+ "loadingHosts": "Reading SSH config…",
+ "noHosts": "No named hosts found. You can enter an SSH address below.",
+ "noMatchingHosts": "No matching hosts.",
+ "partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
+ "otherConfig": "Use another SSH config file",
+ "configToRead": "SSH config file to read",
+ "readConfig": "Read hosts",
+ "discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
+ "portPlaceholder": "Use SSH config (normally 22)",
+ "loading": "Loading connections…",
+ "retry": "Retry",
+ "unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
+ "back": "Back",
+ "disconnect": "Disconnect",
+ "verifyTitle": "Verify this server",
+ "verifyDescription": "Before connecting for the first time, compare this SSH fingerprint with your server console or administrator.",
+ "verifyHint": "Continue only if it matches. Only this server's public key is saved; your system SSH config is unchanged.",
+ "verifyConnect": "Fingerprint matches · Connect",
+ "title": "Remote connections",
+ "description": "Connect to nanobot on a server. Chats and settings stay there.",
+ "local": "Local nanobot",
+ "current": "Currently using",
+ "remote": "Remote",
+ "returnLocal": "Back to local nanobot",
+ "add": "Connect to remote nanobot…",
+ "addTitle": "Connect to remote nanobot",
+ "addDescription": "Connect to a nanobot that's already running on your server.",
+ "host": "SSH address",
+ "name": "Name (optional)",
+ "namePlaceholder": "Team server",
+ "keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
+ "advanced": "Advanced",
+ "sshPort": "SSH port",
+ "ssh_config": "SSH config file (optional)",
+ "identity_file": "Private key path (optional)",
+ "config_path": "Server's nanobot config path",
+ "runtime_user": "nanobot service account (optional)",
+ "saveConnect": "Save & connect",
+ "connecting": "Connecting…",
+ "opening": "Opening your server…",
+ "frameTitle": "nanobot on {{name}}",
+ "offline": "Server connection lost",
+ "noFallback": "You're still using remote nanobot. Nothing is sent to local nanobot.",
+ "reconnect": "Reconnect",
+ "manage": "Manage {{name}}",
+ "edit": "Edit connection",
+ "forget": "Forget server",
+ "forgetTitle": "Forget {{name}}?",
+ "forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
+ "errors": {
+ "view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
+ "view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
+ "same_instance": "This is the nanobot you are already using. No remote connection is needed.",
+ "ssh_config_unreadable": "This SSH config could not be read. Check its path, permissions and format.",
+ "local_port_in_use": "This connection's local port is in use. Close the conflicting application, or forget and add this server again.",
+ "host_key_scan_failed": "Couldn't retrieve this server's fingerprint. For jump hosts, verify it through your existing SSH configuration.",
+ "unknown": "Couldn't connect. Check the server and try again.",
+ "directory_unavailable": "Couldn't read your saved servers. Please try again.",
+ "ssh_unavailable": "Install the OpenSSH client on this machine to connect.",
+ "ssh_auth_failed": "SSH couldn't sign in. Check the username and key, and unlock your key in the system SSH agent if needed.",
+ "ssh_unreachable": "Can't reach SSH on this server. Check the address, port and network.",
+ "host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
+ "host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
+ "local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
+ "runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
+ "python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
+ "config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
+ "config_invalid": "Couldn't read the server's nanobot configuration.",
+ "webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
+ "webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
+ "public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+ "remote_auth_failed": "The server rejected its saved WebUI credential. Check its running configuration.",
+ "incompatible_gateway": "This endpoint isn't a compatible nanobot gateway. Update the server or check its configuration.",
+ "webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
+ "remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
+ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
+ "invalid_profile": "Check the address, port and Advanced fields.",
+ "profile_not_found": "This saved server no longer exists. Refresh the list.",
+ "profile_limit": "You can save up to 20 servers.",
+ "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.",
+ "invalid_remote_url": "The connection returned an unexpected address. It was blocked."
+ }
+ },
"previewTabs": {
"title": "プレビュー",
"closeTab": "{{name}} を閉じる",
diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.json
index 855c8a0b0..a4c43a05d 100644
--- a/webui/src/i18n/locales/ko/common.json
+++ b/webui/src/i18n/locales/ko/common.json
@@ -1,4 +1,106 @@
{
+ "remote": {
+ "localShort": "Local",
+ "disconnectTitle": "Disconnect from {{name}}?",
+ "disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
+ "hostBar": "Current connection",
+ "switchHost": "Switch host",
+ "manageConnections": "Manage connections…",
+ "ready": "Ready",
+ "preparing": "Connecting to {{name}}…",
+ "cancelSwitch": "Cancel switch",
+ "localEnvironment": "Local · {{name}}",
+ "sshHosts": "From your SSH config",
+ "sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
+ "refreshHosts": "Refresh SSH hosts",
+ "searchHosts": "Search SSH hosts",
+ "useHost": "Use {{host}}",
+ "loadingHosts": "Reading SSH config…",
+ "noHosts": "No named hosts found. You can enter an SSH address below.",
+ "noMatchingHosts": "No matching hosts.",
+ "partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
+ "otherConfig": "Use another SSH config file",
+ "configToRead": "SSH config file to read",
+ "readConfig": "Read hosts",
+ "discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
+ "portPlaceholder": "Use SSH config (normally 22)",
+ "loading": "Loading connections…",
+ "retry": "Retry",
+ "unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
+ "back": "Back",
+ "disconnect": "Disconnect",
+ "verifyTitle": "Verify this server",
+ "verifyDescription": "Before connecting for the first time, compare this SSH fingerprint with your server console or administrator.",
+ "verifyHint": "Continue only if it matches. Only this server's public key is saved; your system SSH config is unchanged.",
+ "verifyConnect": "Fingerprint matches · Connect",
+ "title": "Remote connections",
+ "description": "Connect to nanobot on a server. Chats and settings stay there.",
+ "local": "Local nanobot",
+ "current": "Currently using",
+ "remote": "Remote",
+ "returnLocal": "Back to local nanobot",
+ "add": "Connect to remote nanobot…",
+ "addTitle": "Connect to remote nanobot",
+ "addDescription": "Connect to a nanobot that's already running on your server.",
+ "host": "SSH address",
+ "name": "Name (optional)",
+ "namePlaceholder": "Team server",
+ "keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
+ "advanced": "Advanced",
+ "sshPort": "SSH port",
+ "ssh_config": "SSH config file (optional)",
+ "identity_file": "Private key path (optional)",
+ "config_path": "Server's nanobot config path",
+ "runtime_user": "nanobot service account (optional)",
+ "saveConnect": "Save & connect",
+ "connecting": "Connecting…",
+ "opening": "Opening your server…",
+ "frameTitle": "nanobot on {{name}}",
+ "offline": "Server connection lost",
+ "noFallback": "You're still using remote nanobot. Nothing is sent to local nanobot.",
+ "reconnect": "Reconnect",
+ "manage": "Manage {{name}}",
+ "edit": "Edit connection",
+ "forget": "Forget server",
+ "forgetTitle": "Forget {{name}}?",
+ "forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
+ "errors": {
+ "view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
+ "view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
+ "same_instance": "This is the nanobot you are already using. No remote connection is needed.",
+ "ssh_config_unreadable": "This SSH config could not be read. Check its path, permissions and format.",
+ "local_port_in_use": "This connection's local port is in use. Close the conflicting application, or forget and add this server again.",
+ "host_key_scan_failed": "Couldn't retrieve this server's fingerprint. For jump hosts, verify it through your existing SSH configuration.",
+ "unknown": "Couldn't connect. Check the server and try again.",
+ "directory_unavailable": "Couldn't read your saved servers. Please try again.",
+ "ssh_unavailable": "Install the OpenSSH client on this machine to connect.",
+ "ssh_auth_failed": "SSH couldn't sign in. Check the username and key, and unlock your key in the system SSH agent if needed.",
+ "ssh_unreachable": "Can't reach SSH on this server. Check the address, port and network.",
+ "host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
+ "host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
+ "local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
+ "runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
+ "python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
+ "config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
+ "config_invalid": "Couldn't read the server's nanobot configuration.",
+ "webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
+ "webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
+ "public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+ "remote_auth_failed": "The server rejected its saved WebUI credential. Check its running configuration.",
+ "incompatible_gateway": "This endpoint isn't a compatible nanobot gateway. Update the server or check its configuration.",
+ "webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
+ "remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
+ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
+ "invalid_profile": "Check the address, port and Advanced fields.",
+ "profile_not_found": "This saved server no longer exists. Refresh the list.",
+ "profile_limit": "You can save up to 20 servers.",
+ "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.",
+ "invalid_remote_url": "The connection returned an unexpected address. It was blocked."
+ }
+ },
"previewTabs": {
"title": "미리보기",
"closeTab": "{{name}} 닫기",
diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.json
index 78ba410f3..80cd07bd3 100644
--- a/webui/src/i18n/locales/pt-BR/common.json
+++ b/webui/src/i18n/locales/pt-BR/common.json
@@ -1,4 +1,106 @@
{
+ "remote": {
+ "localShort": "Local",
+ "disconnectTitle": "Disconnect from {{name}}?",
+ "disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
+ "hostBar": "Current connection",
+ "switchHost": "Switch host",
+ "manageConnections": "Manage connections…",
+ "ready": "Ready",
+ "preparing": "Connecting to {{name}}…",
+ "cancelSwitch": "Cancel switch",
+ "localEnvironment": "Local · {{name}}",
+ "sshHosts": "From your SSH config",
+ "sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
+ "refreshHosts": "Refresh SSH hosts",
+ "searchHosts": "Search SSH hosts",
+ "useHost": "Use {{host}}",
+ "loadingHosts": "Reading SSH config…",
+ "noHosts": "No named hosts found. You can enter an SSH address below.",
+ "noMatchingHosts": "No matching hosts.",
+ "partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
+ "otherConfig": "Use another SSH config file",
+ "configToRead": "SSH config file to read",
+ "readConfig": "Read hosts",
+ "discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
+ "portPlaceholder": "Use SSH config (normally 22)",
+ "loading": "Loading connections…",
+ "retry": "Retry",
+ "unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
+ "back": "Back",
+ "disconnect": "Disconnect",
+ "verifyTitle": "Verify this server",
+ "verifyDescription": "Before connecting for the first time, compare this SSH fingerprint with your server console or administrator.",
+ "verifyHint": "Continue only if it matches. Only this server's public key is saved; your system SSH config is unchanged.",
+ "verifyConnect": "Fingerprint matches · Connect",
+ "title": "Remote connections",
+ "description": "Connect to nanobot on a server. Chats and settings stay there.",
+ "local": "Local nanobot",
+ "current": "Currently using",
+ "remote": "Remote",
+ "returnLocal": "Back to local nanobot",
+ "add": "Connect to remote nanobot…",
+ "addTitle": "Connect to remote nanobot",
+ "addDescription": "Connect to a nanobot that's already running on your server.",
+ "host": "SSH address",
+ "name": "Name (optional)",
+ "namePlaceholder": "Team server",
+ "keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
+ "advanced": "Advanced",
+ "sshPort": "SSH port",
+ "ssh_config": "SSH config file (optional)",
+ "identity_file": "Private key path (optional)",
+ "config_path": "Server's nanobot config path",
+ "runtime_user": "nanobot service account (optional)",
+ "saveConnect": "Save & connect",
+ "connecting": "Connecting…",
+ "opening": "Opening your server…",
+ "frameTitle": "nanobot on {{name}}",
+ "offline": "Server connection lost",
+ "noFallback": "You're still using remote nanobot. Nothing is sent to local nanobot.",
+ "reconnect": "Reconnect",
+ "manage": "Manage {{name}}",
+ "edit": "Edit connection",
+ "forget": "Forget server",
+ "forgetTitle": "Forget {{name}}?",
+ "forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
+ "errors": {
+ "view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
+ "view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
+ "same_instance": "This is the nanobot you are already using. No remote connection is needed.",
+ "ssh_config_unreadable": "This SSH config could not be read. Check its path, permissions and format.",
+ "local_port_in_use": "This connection's local port is in use. Close the conflicting application, or forget and add this server again.",
+ "host_key_scan_failed": "Couldn't retrieve this server's fingerprint. For jump hosts, verify it through your existing SSH configuration.",
+ "unknown": "Couldn't connect. Check the server and try again.",
+ "directory_unavailable": "Couldn't read your saved servers. Please try again.",
+ "ssh_unavailable": "Install the OpenSSH client on this machine to connect.",
+ "ssh_auth_failed": "SSH couldn't sign in. Check the username and key, and unlock your key in the system SSH agent if needed.",
+ "ssh_unreachable": "Can't reach SSH on this server. Check the address, port and network.",
+ "host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
+ "host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
+ "local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
+ "runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
+ "python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
+ "config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
+ "config_invalid": "Couldn't read the server's nanobot configuration.",
+ "webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
+ "webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
+ "public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+ "remote_auth_failed": "The server rejected its saved WebUI credential. Check its running configuration.",
+ "incompatible_gateway": "This endpoint isn't a compatible nanobot gateway. Update the server or check its configuration.",
+ "webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
+ "remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
+ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
+ "invalid_profile": "Check the address, port and Advanced fields.",
+ "profile_not_found": "This saved server no longer exists. Refresh the list.",
+ "profile_limit": "You can save up to 20 servers.",
+ "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.",
+ "invalid_remote_url": "The connection returned an unexpected address. It was blocked."
+ }
+ },
"previewTabs": {
"title": "Prévia",
"closeTab": "Fechar {{name}}",
diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.json
index e8b28263e..a7c309f9e 100644
--- a/webui/src/i18n/locales/vi/common.json
+++ b/webui/src/i18n/locales/vi/common.json
@@ -1,4 +1,106 @@
{
+ "remote": {
+ "localShort": "Local",
+ "disconnectTitle": "Disconnect from {{name}}?",
+ "disconnectDescription": "This closes the server view and shared SSH connection. Unsaved work may be lost, and other tabs using this connection will disconnect. nanobot keeps running on the server.",
+ "hostBar": "Current connection",
+ "switchHost": "Switch host",
+ "manageConnections": "Manage connections…",
+ "ready": "Ready",
+ "preparing": "Connecting to {{name}}…",
+ "cancelSwitch": "Cancel switch",
+ "localEnvironment": "Local · {{name}}",
+ "sshHosts": "From your SSH config",
+ "sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
+ "refreshHosts": "Refresh SSH hosts",
+ "searchHosts": "Search SSH hosts",
+ "useHost": "Use {{host}}",
+ "loadingHosts": "Reading SSH config…",
+ "noHosts": "No named hosts found. You can enter an SSH address below.",
+ "noMatchingHosts": "No matching hosts.",
+ "partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
+ "otherConfig": "Use another SSH config file",
+ "configToRead": "SSH config file to read",
+ "readConfig": "Read hosts",
+ "discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
+ "portPlaceholder": "Use SSH config (normally 22)",
+ "loading": "Loading connections…",
+ "retry": "Retry",
+ "unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",
+ "back": "Back",
+ "disconnect": "Disconnect",
+ "verifyTitle": "Verify this server",
+ "verifyDescription": "Before connecting for the first time, compare this SSH fingerprint with your server console or administrator.",
+ "verifyHint": "Continue only if it matches. Only this server's public key is saved; your system SSH config is unchanged.",
+ "verifyConnect": "Fingerprint matches · Connect",
+ "title": "Remote connections",
+ "description": "Connect to nanobot on a server. Chats and settings stay there.",
+ "local": "Local nanobot",
+ "current": "Currently using",
+ "remote": "Remote",
+ "returnLocal": "Back to local nanobot",
+ "add": "Connect to remote nanobot…",
+ "addTitle": "Connect to remote nanobot",
+ "addDescription": "Connect to a nanobot that's already running on your server.",
+ "host": "SSH address",
+ "name": "Name (optional)",
+ "namePlaceholder": "Team server",
+ "keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
+ "advanced": "Advanced",
+ "sshPort": "SSH port",
+ "ssh_config": "SSH config file (optional)",
+ "identity_file": "Private key path (optional)",
+ "config_path": "Server's nanobot config path",
+ "runtime_user": "nanobot service account (optional)",
+ "saveConnect": "Save & connect",
+ "connecting": "Connecting…",
+ "opening": "Opening your server…",
+ "frameTitle": "nanobot on {{name}}",
+ "offline": "Server connection lost",
+ "noFallback": "You're still using remote nanobot. Nothing is sent to local nanobot.",
+ "reconnect": "Reconnect",
+ "manage": "Manage {{name}}",
+ "edit": "Edit connection",
+ "forget": "Forget server",
+ "forgetTitle": "Forget {{name}}?",
+ "forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
+ "errors": {
+ "view_limit": "Three server views are already kept open. Disconnect one in Manage connections before opening another.",
+ "view_load_failed": "The server view is taking too long to load. Retry; your current view is unchanged.",
+ "same_instance": "This is the nanobot you are already using. No remote connection is needed.",
+ "ssh_config_unreadable": "This SSH config could not be read. Check its path, permissions and format.",
+ "local_port_in_use": "This connection's local port is in use. Close the conflicting application, or forget and add this server again.",
+ "host_key_scan_failed": "Couldn't retrieve this server's fingerprint. For jump hosts, verify it through your existing SSH configuration.",
+ "unknown": "Couldn't connect. Check the server and try again.",
+ "directory_unavailable": "Couldn't read your saved servers. Please try again.",
+ "ssh_unavailable": "Install the OpenSSH client on this machine to connect.",
+ "ssh_auth_failed": "SSH couldn't sign in. Check the username and key, and unlock your key in the system SSH agent if needed.",
+ "ssh_unreachable": "Can't reach SSH on this server. Check the address, port and network.",
+ "host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
+ "host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
+ "local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
+ "runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
+ "python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
+ "config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
+ "config_invalid": "Couldn't read the server's nanobot configuration.",
+ "webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
+ "webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
+ "public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+ "remote_auth_failed": "The server rejected its saved WebUI credential. Check its running configuration.",
+ "incompatible_gateway": "This endpoint isn't a compatible nanobot gateway. Update the server or check its configuration.",
+ "webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
+ "remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
+ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
+ "invalid_profile": "Check the address, port and Advanced fields.",
+ "profile_not_found": "This saved server no longer exists. Refresh the list.",
+ "profile_limit": "You can save up to 20 servers.",
+ "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.",
+ "invalid_remote_url": "The connection returned an unexpected address. It was blocked."
+ }
+ },
"previewTabs": {
"title": "Xem trước",
"closeTab": "Đóng {{name}}",
diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.json
index a708a6756..bf11a02c3 100644
--- a/webui/src/i18n/locales/zh-CN/common.json
+++ b/webui/src/i18n/locales/zh-CN/common.json
@@ -1,4 +1,106 @@
{
+ "remote": {
+ "localShort": "本地",
+ "disconnectTitle": "断开与 {{name}} 的连接?",
+ "disconnectDescription": "将关闭此服务器页面及共享的 SSH 连接,可能丢失未保存的内容,并影响其他正在使用此连接的标签页。服务器上的 nanobot 会继续运行。",
+ "hostBar": "当前连接",
+ "switchHost": "切换主机",
+ "manageConnections": "管理连接…",
+ "ready": "已就绪",
+ "preparing": "正在连接 {{name}}…",
+ "cancelSwitch": "取消切换",
+ "localEnvironment": "本地 · {{name}}",
+ "sshHosts": "来自 SSH 配置",
+ "sshHostsHint": "选择已有主机,用户名、密钥和端口会沿用 SSH 配置。点击连接前不会访问服务器。",
+ "refreshHosts": "刷新 SSH 主机",
+ "searchHosts": "搜索 SSH 主机",
+ "useHost": "使用 {{host}}",
+ "loadingHosts": "正在读取 SSH 配置…",
+ "noHosts": "没有找到已命名的主机,也可以在下面手动输入 SSH 地址。",
+ "noMatchingHosts": "没有匹配的主机。",
+ "partialHosts": "部分配置未能列出,你仍可手动输入主机别名或地址。",
+ "otherConfig": "使用其他 SSH 配置文件",
+ "configToRead": "要读取的 SSH 配置文件",
+ "readConfig": "读取主机",
+ "discoveryError": "无法读取 SSH 主机,请重试或手动输入地址。",
+ "portPlaceholder": "沿用 SSH 配置(通常为 22)",
+ "loading": "正在读取连接…",
+ "retry": "重试",
+ "unavailable": "请从本地运行的 nanobot 打开此页面,才能通过 SSH 连接服务器。",
+ "back": "返回",
+ "disconnect": "断开连接",
+ "verifyTitle": "验证服务器身份",
+ "verifyDescription": "第一次连接前,请与服务器控制台或管理员核对下面的 SSH 指纹。",
+ "verifyHint": "指纹一致再继续。只保存这台服务器的公钥,不修改系统 SSH 配置。",
+ "verifyConnect": "指纹一致,继续连接",
+ "title": "远程连接",
+ "description": "连接服务器上的 nanobot,聊天和设置保留在服务器。",
+ "local": "本地 nanobot",
+ "current": "正在使用",
+ "remote": "远程",
+ "returnLocal": "切回本地 nanobot",
+ "add": "连接远程 nanobot…",
+ "addTitle": "连接远程 nanobot",
+ "addDescription": "连接服务器上已经运行的 nanobot。",
+ "host": "SSH 地址",
+ "name": "名称(可选)",
+ "namePlaceholder": "团队服务器",
+ "keyHint": "使用系统 SSH 密钥。模型 Key 和会话留在服务器上。",
+ "advanced": "高级",
+ "sshPort": "SSH 端口",
+ "ssh_config": "SSH 配置文件(可选)",
+ "identity_file": "私钥路径(可选)",
+ "config_path": "服务器上的 nanobot 配置路径",
+ "runtime_user": "nanobot 运行账号(可选)",
+ "saveConnect": "保存并连接",
+ "connecting": "正在连接…",
+ "opening": "正在打开服务器…",
+ "frameTitle": "{{name}} 上的 nanobot",
+ "offline": "与服务器的连接已断开",
+ "noFallback": "当前仍在使用远程 nanobot,不会将操作转到本地 nanobot。",
+ "reconnect": "重新连接",
+ "manage": "管理 {{name}}",
+ "edit": "编辑连接",
+ "forget": "忘记服务器",
+ "forgetTitle": "忘记 {{name}}?",
+ "forgetDescription": "只移除本机保存的连接。服务器上的 nanobot、密钥和会话都不会被删除。",
+ "errors": {
+ "view_limit": "已保留 3 个服务器界面。请在管理连接中断开其中一个,再打开新服务器。",
+ "view_load_failed": "服务器界面加载较慢,请重试。当前界面保持不变。",
+ "same_instance": "这是你当前正在使用的 nanobot,无需再次连接。",
+ "ssh_config_unreadable": "无法读取此 SSH 配置,请检查文件路径、权限和格式。",
+ "local_port_in_use": "这个连接的本机端口正被其他程序占用。请关闭占用程序后重试,或忘记并重新添加连接。",
+ "host_key_scan_failed": "暂时无法获取服务器指纹。如果使用跳板机,请通过已有 SSH 配置验证身份。",
+ "unknown": "连接未成功,请检查服务器后重试。",
+ "directory_unavailable": "暂时无法读取已保存的服务器,请重试。",
+ "ssh_unavailable": "本机需要安装 OpenSSH 客户端才能连接。",
+ "ssh_auth_failed": "SSH 登录失败。请检查用户名和密钥;加密的密钥需要先在系统 SSH agent 中解锁。",
+ "ssh_unreachable": "无法连接服务器的 SSH,请检查地址、端口和网络。",
+ "host_key_unknown": "本机还没有验证过这台服务器。请先与服务器管理员核对 SSH 指纹后再连接。",
+ "host_key_changed": "服务器的 SSH 身份发生了变化,已阻止连接。请先与管理员确认,不要跳过这个警告。",
+ "local_file_not_found": "本机找不到指定的 SSH 配置文件或私钥。",
+ "runtime_user_denied": "SSH 已登录,但不能免密切换到这个运行账号,请与服务器管理员确认。",
+ "python_unavailable": "服务器需要 python3 来读取已有的 nanobot 配置。",
+ "config_not_found": "找不到 nanobot 配置,请在「高级」中填写它在服务器上的路径。",
+ "config_permission": "SSH 账号无权读取 nanobot 配置,请在「高级」中填写 nanobot 的运行账号。",
+ "config_invalid": "无法读取服务器上的 nanobot 配置。",
+ "webui_disabled": "服务器的 WebUI 尚未启用,请先在服务器上开启。",
+ "webui_auth_required": "服务器需要在配置中设置 WebUI 登录密钥。这里不需要模型 Key。",
+ "public_ws_unsupported": "这台服务器设置了公网 WebSocket 地址。首版支持通过 SSH 连接回环地址上的 WebUI。",
+ "remote_auth_failed": "服务器拒绝了 WebUI 登录凭据,请检查它实际运行的配置。",
+ "incompatible_gateway": "该地址不是兼容的 nanobot gateway,请检查配置或更新服务器版本。",
+ "webui_unavailable": "Gateway 在运行,但没有安装 WebUI。",
+ "remote_unreachable": "SSH 已连接,但 nanobot WebUI 没有响应,请确认它正在运行。",
+ "profile_store_invalid": "无法读取已保存的连接,原文件未被覆盖。",
+ "invalid_profile": "请检查服务器地址、端口和高级选项。",
+ "profile_not_found": "这个连接已不存在,请刷新列表。",
+ "profile_limit": "最多可以保存 20 台服务器。",
+ "connection_limit": "请先断开一台服务器,再建立新连接。",
+ "disconnect_before_edit": "请先断开这个服务器,再编辑连接信息。",
+ "local_io_error": "无法保存或打开连接,请检查本机文件权限。",
+ "invalid_remote_url": "连接返回了异常地址,已阻止打开。"
+ }
+ },
"previewTabs": {
"title": "预览",
"closeTab": "关闭 {{name}}",
diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.json
index e797dfe2b..09d6fb16b 100644
--- a/webui/src/i18n/locales/zh-TW/common.json
+++ b/webui/src/i18n/locales/zh-TW/common.json
@@ -1,4 +1,106 @@
{
+ "remote": {
+ "localShort": "本地",
+ "disconnectTitle": "中斷與 {{name}} 的連線?",
+ "disconnectDescription": "將關閉此伺服器頁面及共用的 SSH 連線,可能遺失未儲存的內容,並影響其他正在使用此連線的分頁。伺服器上的 nanobot 會繼續執行。",
+ "hostBar": "当前连接",
+ "switchHost": "切换主机",
+ "manageConnections": "管理连接…",
+ "ready": "已就绪",
+ "preparing": "正在连接 {{name}}…",
+ "cancelSwitch": "取消切换",
+ "localEnvironment": "Local · {{name}}",
+ "sshHosts": "From your SSH config",
+ "sshHostsHint": "Choose a saved SSH host. Its username, key and port are inherited; no servers are contacted until you connect.",
+ "refreshHosts": "Refresh SSH hosts",
+ "searchHosts": "Search SSH hosts",
+ "useHost": "Use {{host}}",
+ "loadingHosts": "Reading SSH config…",
+ "noHosts": "No named hosts found. You can enter an SSH address below.",
+ "noMatchingHosts": "No matching hosts.",
+ "partialHosts": "Some entries couldn't be listed. You can still enter an alias or address manually.",
+ "otherConfig": "Use another SSH config file",
+ "configToRead": "SSH config file to read",
+ "readConfig": "Read hosts",
+ "discoveryError": "Couldn't read SSH hosts. Retry or enter an address manually.",
+ "portPlaceholder": "Use SSH config (normally 22)",
+ "loading": "正在讀取連線…",
+ "retry": "重試",
+ "unavailable": "請從本機執行的 nanobot 開啟此頁面,才能透過 SSH 連線伺服器。",
+ "back": "Back",
+ "disconnect": "Disconnect",
+ "verifyTitle": "Verify this server",
+ "verifyDescription": "Before connecting for the first time, compare this SSH fingerprint with your server console or administrator.",
+ "verifyHint": "Continue only if it matches. Only this server's public key is saved; your system SSH config is unchanged.",
+ "verifyConnect": "Fingerprint matches · Connect",
+ "title": "Remote connections",
+ "description": "Connect to nanobot on a server. Chats and settings stay there.",
+ "local": "Local nanobot",
+ "current": "Currently using",
+ "remote": "Remote",
+ "returnLocal": "Back to local nanobot",
+ "add": "Connect to remote nanobot…",
+ "addTitle": "Connect to remote nanobot",
+ "addDescription": "Connect to a nanobot that's already running on your server.",
+ "host": "SSH address",
+ "name": "Name (optional)",
+ "namePlaceholder": "Team server",
+ "keyHint": "Uses your system's SSH keys. Model keys and conversations stay on the server.",
+ "advanced": "Advanced",
+ "sshPort": "SSH port",
+ "ssh_config": "SSH config file (optional)",
+ "identity_file": "Private key path (optional)",
+ "config_path": "Server's nanobot config path",
+ "runtime_user": "nanobot service account (optional)",
+ "saveConnect": "Save & connect",
+ "connecting": "Connecting…",
+ "opening": "Opening your server…",
+ "frameTitle": "nanobot on {{name}}",
+ "offline": "Server connection lost",
+ "noFallback": "You're still using remote nanobot. Nothing is sent to local nanobot.",
+ "reconnect": "Reconnect",
+ "manage": "Manage {{name}}",
+ "edit": "Edit connection",
+ "forget": "Forget server",
+ "forgetTitle": "Forget {{name}}?",
+ "forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.",
+ "errors": {
+ "view_limit": "已保留 3 个服务器界面。请在管理连接中断开其中一个,再打开新服务器。",
+ "view_load_failed": "服务器界面加载较慢,请重试。当前界面保持不变。",
+ "same_instance": "This is the nanobot you are already using. No remote connection is needed.",
+ "ssh_config_unreadable": "This SSH config could not be read. Check its path, permissions and format.",
+ "local_port_in_use": "This connection's local port is in use. Close the conflicting application, or forget and add this server again.",
+ "host_key_scan_failed": "Couldn't retrieve this server's fingerprint. For jump hosts, verify it through your existing SSH configuration.",
+ "unknown": "Couldn't connect. Check the server and try again.",
+ "directory_unavailable": "Couldn't read your saved servers. Please try again.",
+ "ssh_unavailable": "Install the OpenSSH client on this machine to connect.",
+ "ssh_auth_failed": "SSH couldn't sign in. Check the username and key, and unlock your key in the system SSH agent if needed.",
+ "ssh_unreachable": "Can't reach SSH on this server. Check the address, port and network.",
+ "host_key_unknown": "This server hasn't been verified by SSH on this machine yet. Verify its host fingerprint with your administrator before connecting.",
+ "host_key_changed": "The server's SSH identity has changed. Connection blocked. Confirm this change with your administrator; don't bypass the warning.",
+ "local_file_not_found": "The SSH config or private key file couldn't be found on this machine.",
+ "runtime_user_denied": "SSH signed in, but cannot read as that service account without a password. Check the account with your server administrator.",
+ "python_unavailable": "The server needs python3 to locate its existing nanobot configuration.",
+ "config_not_found": "nanobot's config wasn't found. Set its server-side path in Advanced.",
+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Advanced.",
+ "config_invalid": "Couldn't read the server's nanobot configuration.",
+ "webui_disabled": "The server's WebUI is disabled. Enable it on the server first.",
+ "webui_auth_required": "The server needs a WebUI login secret in its config. No model key is needed here.",
+ "public_ws_unsupported": "This server uses a public WebSocket URL. This first version supports a loopback WebUI over SSH.",
+ "remote_auth_failed": "The server rejected its saved WebUI credential. Check its running configuration.",
+ "incompatible_gateway": "This endpoint isn't a compatible nanobot gateway. Update the server or check its configuration.",
+ "webui_unavailable": "The gateway is running, but its WebUI isn't installed.",
+ "remote_unreachable": "SSH connected, but the nanobot WebUI isn't responding. Check that it's running.",
+ "profile_store_invalid": "Saved connections couldn't be read. They haven't been overwritten.",
+ "invalid_profile": "Check the address, port and Advanced fields.",
+ "profile_not_found": "This saved server no longer exists. Refresh the list.",
+ "profile_limit": "You can save up to 20 servers.",
+ "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.",
+ "invalid_remote_url": "The connection returned an unexpected address. It was blocked."
+ }
+ },
"previewTabs": {
"title": "預覽",
"closeTab": "關閉 {{name}}",
diff --git a/webui/src/lib/remote-instances.ts b/webui/src/lib/remote-instances.ts
new file mode 100644
index 000000000..6f792d66d
--- /dev/null
+++ b/webui/src/lib/remote-instances.ts
@@ -0,0 +1,81 @@
+import type { WebUIMutationTransport } from "./api";
+import { fetchWithTimeout } from "./http";
+
+export interface RemoteProfile {
+ id: string;
+ name: string;
+ host: string;
+ port: number | null;
+ ssh_config: string;
+ identity_file: string;
+ config_path: string;
+ runtime_user: string;
+ connected: boolean;
+}
+
+export interface RemoteDirectory {
+ available: boolean;
+ machine_name?: string;
+ profiles: RemoteProfile[];
+}
+
+export interface SSHDiscovery {
+ hosts: { host: string; source: string; ssh_config: string }[];
+ files: string[];
+ incomplete: boolean;
+}
+
+export interface RemoteConnection {
+ id: string;
+ name: string;
+ host: string;
+ hostname: string;
+ config_path: string;
+ gateway_id: string;
+ url: string;
+}
+
+export async function readRemoteInstances(token: string): Promise<RemoteDirectory> {
+ const response = await fetchWithTimeout("/api/remote-instances", {
+ headers: { Authorization: `Bearer ${token}` },
+ });
+ if (response.status === 403 || response.status === 404) return { available: false, profiles: [] };
+ if (!response.ok) throw new Error("directory_unavailable");
+ return response.json() as Promise<RemoteDirectory>;
+}
+
+export function remoteAction<T>(
+ client: WebUIMutationTransport, action: string, payload: Record<string, unknown>,
+): Promise<T> {
+ return client.requestMutation<T>(`remote.${action}`, payload, 65_000);
+}
+
+/** Never let a server response navigate the shell to an arbitrary origin. */
+export function validateRemoteConnection(connection: RemoteConnection): RemoteConnection {
+ const url = new URL(connection.url);
+ if (url.protocol !== "http:" || url.hostname !== "127.0.0.1" || !url.port
+ || url.username || url.password || url.pathname !== "/") {
+ throw new Error("invalid_remote_url");
+ }
+ return connection;
+}
+
+export type SelectedRemote = Pick<RemoteConnection, "id" | "name" | "hostname">;
+const SELECTED_REMOTE = "nanobot.remote-instance";
+
+export function readSelectedRemote(): SelectedRemote | null {
+ try {
+ // A remote WebUI embedded by another nanobot must not inherit a local host's selector.
+ if (window.top !== window) return null;
+ const value = JSON.parse(window.sessionStorage.getItem(SELECTED_REMOTE) || "null") as SelectedRemote | null;
+ return value && /^[a-f0-9-]{36}$/.test(value.id) && typeof value.name === "string"
+ && typeof value.hostname === "string" ? value : null;
+ } catch { return null; }
+}
+
+export function rememberSelectedRemote(value: SelectedRemote | null): void {
+ try {
+ if (value) window.sessionStorage.setItem(SELECTED_REMOTE, JSON.stringify({ id: value.id, name: value.name, hostname: value.hostname }));
+ else window.sessionStorage.removeItem(SELECTED_REMOTE);
+ } catch { /* Storage can be disabled; the live connection still works. */ }
+}
diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsx
index 27be13240..b3a71cc10 100644
--- a/webui/src/tests/app-layout.test.tsx
+++ b/webui/src/tests/app-layout.test.tsx
@@ -679,6 +679,50 @@ describe("App layout", () => {
expect(window.location.hash).toBe("#/channels");
});
+ it("opens Remote connections in the main shell and restores it through browser history", async () => {
+ requestMutationSpy.mockResolvedValue({ hosts: [], files: [], incomplete: false });
+ mockFetchRoutes({
+ "/api/settings": baseSettingsPayload(),
+ "/api/remote-instances": { available: true, profiles: [] },
+ });
+ render(<App />);
+ await waitFor(() => expect(connectSpy).toHaveBeenCalled());
+ const sidebar = screen.getByRole("navigation", { name: "Sidebar navigation" });
+ const remote = await within(sidebar).findByRole("button", { name: "Remote connections" });
+ fireEvent.click(remote);
+ fireEvent.click(await screen.findByRole("button", { name: "Connect to remote nanobot…" }));
+ const host = await screen.findByRole("textbox", { name: "SSH address" });
+ expect(screen.getByRole("main")).toContainElement(host);
+ expect(sidebar).toBeVisible();
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(remote).toHaveAttribute("aria-current", "page");
+ expect(window.location.hash).toBe("#/remote");
+ expect(document.title).toBe("Remote connections · nanobot");
+ fireEvent.click(within(sidebar).getByRole("button", { name: "New topic" }));
+ expect(window.location.hash).toBe("#/new");
+ expect(screen.queryByRole("textbox", { name: "SSH address" })).not.toBeInTheDocument();
+ act(() => {
+ window.history.replaceState(null, "", "#/remote");
+ window.dispatchEvent(new PopStateEvent("popstate"));
+ });
+ expect(await screen.findByRole("region", { name: "From your SSH config" })).toBeVisible();
+ expect(remote).toHaveAttribute("aria-current", "page");
+ });
+
+ it("opens a remote setup deep link after reloading without opening Settings", async () => {
+ requestMutationSpy.mockResolvedValue({ hosts: [], files: [], incomplete: false });
+ window.history.replaceState(null, "", "#/remote");
+ mockFetchRoutes({
+ "/api/settings": baseSettingsPayload(),
+ "/api/remote-instances": { available: true, profiles: [] },
+ });
+ render(<App />);
+ expect(await screen.findByRole("region", { name: "From your SSH config" })).toBeVisible();
+ expect(screen.getByRole("navigation", { name: "Sidebar navigation" })).toBeVisible();
+ expect(screen.queryByRole("navigation", { name: "Settings sections" })).not.toBeInTheDocument();
+ expect(window.location.hash).toBe("#/remote");
+ });
+
it("highlights the blank new-topic destination immediately", async () => {
render(<App />);
diff --git a/webui/src/tests/host-bridge.test.tsx b/webui/src/tests/host-bridge.test.tsx
new file mode 100644
index 000000000..9f450a3a9
--- /dev/null
+++ b/webui/src/tests/host-bridge.test.tsx
@@ -0,0 +1,110 @@
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { HOST_BRIDGE, isLocalShellOrigin, readHostAnchor } from "@/components/remote/host-bridge";
+import { useSidebarHostBridge } from "@/components/remote/useSidebarHostBridge";
+import type { HostFrame } from "@/components/remote/useHostSessions";
+const origin = "http://127.0.0.1:23456";
+const makeFrame = (id = "host-a"): HostFrame => ({
+ connection: { id, name: "Team server", host: "private-ssh-alias", hostname: "team-host", config_path: "/private/config.json", gateway_id: "gateway-1", url: `${origin}/#/?bootstrapSecret=never-share-this` },
+ loaded: true, offline: false, failures: 0,
+});
+const rect = { left: 60, top: 600, width: 120, height: 32 };
+function addFrame() {
+ const node = document.createElement("iframe");
+ // A detached frame avoids loading a page in the unit-test environment.
+ Object.defineProperty(node, "contentWindow", { value: { postMessage: vi.fn() } });
+ vi.spyOn(node, "getBoundingClientRect").mockReturnValue(new DOMRect(10, 20, 800, 800));
+ return node;
+}
+function send(source: Window, data: Record<string, unknown>, from = origin) {
+ act(() => { window.dispatchEvent(new MessageEvent("message", { source, origin: from, data: { channel: HOST_BRIDGE, ...data } })); });
+}
+function parentView() {
+ const node = addFrame();
+ const source = node.contentWindow!;
+ const post = vi.spyOn(source, "postMessage").mockImplementation(() => {});
+ const nodes = { current: new Map([["host-a", node]]) };
+ const restore = vi.fn();
+ const hook = renderHook(({ selectedId }) => useSidebarHostBridge([makeFrame()], selectedId, nodes, restore, {}), {
+ initialProps: { selectedId: "host-a" as string | undefined },
+ });
+ send(source, { type: "hello" });
+ const init = post.mock.calls[0][0] as Record<string, unknown>;
+ return { ...hook, node, source, post, init, restore };
+}
+afterEach(() => { cleanup(); document.querySelectorAll("iframe").forEach((node) => node.remove()); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
+
+describe("sidebar host bridge", () => {
+ it("sends only current display identity, never secrets, profiles or filesystem paths", () => {
+ const { post, init } = parentView();
+ expect(post).toHaveBeenCalledWith(expect.objectContaining({ type: "init", name: "Team server", hostname: "team-host" }), origin);
+ const json = JSON.stringify(init);
+ expect(json).not.toContain("never-share-this");
+ expect(json).not.toContain("config.json");
+ expect(json).not.toContain("private-ssh-alias");
+ expect(init).not.toHaveProperty("profiles");
+ });
+
+ it("requires matching source, origin and nonce before enabling the sidebar or opening its menu", () => {
+ const { source, init, result } = parentView();
+ send(source, { type: "ready", nonce: "wrong" });
+ send(source, { type: "ready", nonce: init.nonce }, "https://attacker.example");
+ send(window, { type: "ready", nonce: init.nonce });
+ expect(result.current.readyIds).toEqual([]);
+ send(source, { type: "ready", nonce: init.nonce });
+ expect(result.current.readyIds).toEqual(["host-a"]);
+ send(source, { type: "open", nonce: init.nonce, anchor: rect });
+ expect(result.current.anchor).toEqual({ ...rect, left: 70, top: 620 });
+ });
+
+ it("ignores inactive frames and does not accept commands to connect, disconnect or navigate", () => {
+ const { source, init, result, rerender } = parentView();
+ for (const type of ["connect", "disconnect", "select", "navigate"]) send(source, { type, nonce: init.nonce, id: "another-host", url: "https://attacker.example" });
+ expect(result.current.anchor).toBeNull();
+ rerender({ selectedId: undefined });
+ send(source, { type: "open", nonce: init.nonce, anchor: rect });
+ expect(result.current.anchor).toBeNull();
+ });
+
+ it("rejects invalid anchor values without opening a menu", () => {
+ const { source, init, result } = parentView();
+ send(source, { type: "open", nonce: init.nonce, anchor: { ...rect, top: NaN } });
+ expect(result.current.anchor).toBeNull();
+ expect(readHostAnchor({ ...rect, width: -1 })).toBeNull();
+ expect(readHostAnchor({ ...rect, left: "0" })).toBeNull();
+ });
+
+ it("restores remote focus only through a verified sidebar bridge", () => {
+ const { source, init, result, post } = parentView();
+ send(source, { type: "ready", nonce: init.nonce });
+ act(() => result.current.focus("host-a"));
+ expect(post).toHaveBeenLastCalledWith({ channel: HOST_BRIDGE, type: "focus", nonce: init.nonce }, origin);
+ });
+
+ it("embedded mode trusts only its loopback parent and pins the handshake", () => {
+ const parent = addFrame().contentWindow!;
+ const post = vi.spyOn(parent, "postMessage").mockImplementation(() => {});
+ vi.stubGlobal("parent", parent);
+ const restore = vi.fn();
+ const nodes = { current: new Map<string, HTMLIFrameElement>() };
+ const { result } = renderHook(() => useSidebarHostBridge([], undefined, nodes, restore, {}));
+ expect(post).toHaveBeenCalledWith({ channel: HOST_BRIDGE, type: "hello" }, "*");
+ const nonce = crypto.randomUUID();
+ const init = { type: "init", nonce, name: "Team server", hostname: "team-host" };
+ send(parent, init, "https://attacker.example");
+ send(window, init, "http://127.0.0.1:8870");
+ expect(result.current.embedded).toBeNull();
+ send(parent, init, "http://127.0.0.1:8870");
+ expect(result.current.embedded?.name).toBe("Team server");
+ act(() => result.current.embedded?.open(rect));
+ expect(post).toHaveBeenLastCalledWith({ channel: HOST_BRIDGE, type: "open", nonce, anchor: rect }, "http://127.0.0.1:8870");
+ send(parent, { ...init, name: "Spoofed", nonce: crypto.randomUUID() }, "http://127.0.0.1:8870");
+ expect(result.current.embedded?.name).toBe("Team server");
+ send(parent, { type: "focus", nonce }, "http://127.0.0.1:8870");
+ expect(restore).toHaveBeenCalledOnce();
+ });
+
+ it.each(["null", "https://example.com", "http://127.0.0.1.evil.test", "file:///tmp/page", "http://127.0.0.1:8870/path"])("rejects non-shell origin %s", (value) => {
+ expect(isLocalShellOrigin(value)).toBe(false);
+ });
+});
diff --git a/webui/src/tests/host-sessions.test.tsx b/webui/src/tests/host-sessions.test.tsx
new file mode 100644
index 000000000..a827e97ea
--- /dev/null
+++ b/webui/src/tests/host-sessions.test.tsx
@@ -0,0 +1,168 @@
+import { act, cleanup, renderHook } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { useHostSessions, MAX_HOST_VIEWS } from "@/components/remote/useHostSessions";
+import type { RemoteConnection } from "@/lib/remote-instances";
+
+const mocks = vi.hoisted(() => ({ read: vi.fn(), request: vi.fn(), token: () => "token",
+ client: { requestMutation: (...args: unknown[]) => mocks.request(...args), onStatus: () => () => {} } }));
+vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: mocks.client, getToken: mocks.token }) }));
+vi.mock("@/lib/remote-instances", async (original) => ({
+ ...await original<typeof import("@/lib/remote-instances")>(), readRemoteInstances: mocks.read,
+}));
+const ids = Array.from({ length: 4 }, (_, i) => `3b968d52-081d-4898-9970-ff0a1fc9381${i}`);
+const connections: RemoteConnection[] = ids.map((id, i) => ({ id, name: `Server ${i}`, hostname: `host-${i}`,
+ gateway_id: `gateway-${i}`, url: `http://127.0.0.1:${24000 + i}/#/?bootstrapSecret=secret` }));
+const directory = { available: true, profiles: connections.map((item) => ({ ...item, connected: true })) };
+const deferred = <T,>() => {
+ let resolve!: (value: T) => void;
+ let reject!: (reason: Error) => void;
+ const promise = new Promise<T>((yes, no) => { resolve = yes; reject = no; });
+ return { promise, resolve, reject };
+};
+type Session = ReturnType<typeof useHostSessions>;
+async function start(result: { current: Session }, index: number) {
+ let completion!: Promise<void>;
+ await act(async () => { completion = result.current.connect(ids[index]); });
+ return { completion };
+}
+async function ready(result: { current: Session }, index: number) {
+ const { completion } = await start(result, index);
+ await act(async () => { result.current.loaded(ids[index]); await completion; });
+}
+
+beforeEach(() => {
+ vi.useFakeTimers();
+ 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) : {});
+});
+afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });
+
+describe("host session lifecycle", () => {
+ it("keeps the current host until the destination view loads, then switches warm without RPC", async () => {
+ const { result } = renderHook(useHostSessions);
+ await ready(result, 0);
+ const { completion } = await start(result, 1);
+ expect(result.current.selected?.id).toBe(ids[0]);
+ expect(result.current.pending?.id).toBe(ids[1]);
+ await act(async () => { result.current.loaded(ids[1]); await completion; });
+ expect(result.current.selected?.id).toBe(ids[1]);
+ await act(async () => { await result.current.connect(ids[0]); });
+ expect(result.current.selected?.id).toBe(ids[0]);
+ expect(mocks.request.mock.calls.filter(([action]) => action === "remote.connect")).toHaveLength(2);
+ });
+
+ it("retains views and shared tunnels when switching local, including after a long idle", async () => {
+ const { result } = renderHook(useHostSessions);
+ await ready(result, 0);
+ const frame = result.current.frames[0];
+ act(() => result.current.local());
+ await act(async () => { await vi.advanceTimersByTimeAsync(15 * 60_000); });
+ expect(result.current.selected).toBeNull();
+ expect(result.current.frames[0]).toBe(frame);
+ expect(mocks.request.mock.calls.some(([action]) => action === "remote.disconnect")).toBe(false);
+ await act(async () => { await result.current.connect(ids[0]); });
+ expect(result.current.selected?.id).toBe(ids[0]);
+ });
+
+ it("a failed destination leaves the active host usable", async () => {
+ const { result } = renderHook(useHostSessions);
+ await ready(result, 0);
+ mocks.request.mockRejectedValueOnce(new Error("ssh_unreachable"));
+ await act(async () => { await expect(result.current.connect(ids[1])).rejects.toThrow("ssh_unreachable"); });
+ expect(result.current.selected?.id).toBe(ids[0]);
+ expect(result.current.frames[0].offline).toBe(false);
+ expect(result.current.pending).toBeNull();
+ });
+
+ it("the latest choice wins even when an earlier SSH request finishes later", async () => {
+ const { result } = renderHook(useHostSessions);
+ const slow = deferred<RemoteConnection>();
+ mocks.request.mockReturnValueOnce(slow.promise);
+ const first = await start(result, 0);
+ await ready(result, 1);
+ await act(async () => { slow.resolve(connections[0]); await first.completion; });
+ expect(result.current.selected?.id).toBe(ids[1]);
+ expect(result.current.frames).toHaveLength(1);
+ expect(mocks.request.mock.calls.some(([action]) => action === "remote.disconnect")).toBe(false);
+ });
+
+ it("cancelling SSH suppresses late errors and never activates a host", async () => {
+ const { result } = renderHook(useHostSessions);
+ const slow = deferred<RemoteConnection>();
+ mocks.request.mockReturnValueOnce(slow.promise);
+ const first = await start(result, 0);
+ act(() => result.current.cancel());
+ await act(async () => { slow.reject(new Error("ssh_unreachable")); await first.completion; });
+ expect(result.current.selected).toBeNull();
+ expect(result.current.pending).toBeNull();
+ expect(result.current.error).toBe("");
+ });
+
+ it("cancelling page load releases an unused view slot and ignores a late load event", async () => {
+ const { result } = renderHook(useHostSessions);
+ const first = await start(result, 0);
+ await act(async () => { result.current.cancel(); await first.completion; });
+ act(() => result.current.loaded(ids[0]));
+ expect(result.current.selected).toBeNull();
+ expect(result.current.frames).toHaveLength(0);
+ expect(vi.getTimerCount()).toBe(1); // health interval only
+ });
+
+ it("a timed-out cold page leaves the old host intact and can be retried", async () => {
+ const { result } = renderHook(useHostSessions);
+ await ready(result, 0);
+ const { completion } = await start(result, 1);
+ const rejected = expect(completion).rejects.toThrow("view_load_failed");
+ await act(async () => { await vi.advanceTimersByTimeAsync(25_000); await rejected; });
+ expect(result.current.selected?.id).toBe(ids[0]);
+ expect(result.current.frames).toHaveLength(1);
+ await ready(result, 1);
+ expect(result.current.selected?.id).toBe(ids[1]);
+ });
+
+ it("a newer request for the same host is not removed by the previous cancelled load", async () => {
+ const { result } = renderHook(useHostSessions);
+ const first = await start(result, 0);
+ const second = await start(result, 0);
+ await act(async () => { result.current.loaded(ids[0]); await Promise.all([first.completion, second.completion]); });
+ expect(result.current.selected?.id).toBe(ids[0]);
+ expect(result.current.frames).toHaveLength(1);
+ });
+
+ it("bounds view memory without silently discarding user drafts", async () => {
+ const { result } = renderHook(useHostSessions);
+ for (let i = 0; i < MAX_HOST_VIEWS; i++) await ready(result, i);
+ await act(async () => { await expect(result.current.connect(ids[3])).rejects.toThrow("view_limit"); });
+ expect(result.current.frames.map((item) => item.connection.id)).toEqual(ids.slice(0, 3));
+ expect(result.current.selected?.id).toBe(ids[2]);
+ await act(async () => { await result.current.disconnect(ids[0]); });
+ expect(result.current.frames).toHaveLength(2);
+ await ready(result, 3);
+ expect(result.current.selected?.id).toBe(ids[3]);
+ });
+
+ it("releases an unfinished view when a same-host retry fails", async () => {
+ const { result } = renderHook(useHostSessions);
+ const first = await start(result, 0);
+ mocks.request.mockRejectedValueOnce(new Error("ssh_unreachable"));
+ await act(async () => {
+ await expect(result.current.connect(ids[0])).rejects.toThrow("ssh_unreachable");
+ await first.completion;
+ });
+ expect(result.current.frames).toHaveLength(0);
+ expect(result.current.selected).toBeNull();
+ });
+
+ it("explicit disconnect closes that view, but never stops the remote bot", async () => {
+ const { result } = renderHook(useHostSessions);
+ await ready(result, 0);
+ await ready(result, 1);
+ await act(async () => { await result.current.disconnect(ids[1]); });
+ expect(result.current.selected).toBeNull();
+ expect(result.current.frames.map((item) => item.connection.id)).toEqual([ids[0]]);
+ expect(mocks.request).toHaveBeenCalledWith("remote.disconnect", { id: ids[1] }, 65_000);
+ expect(mocks.request.mock.calls.some(([action]) => action.includes("stop"))).toBe(false);
+ });
+});
diff --git a/webui/src/tests/remote-instances.test.tsx b/webui/src/tests/remote-instances.test.tsx
new file mode 100644
index 000000000..c1d072b55
--- /dev/null
+++ b/webui/src/tests/remote-instances.test.tsx
@@ -0,0 +1,454 @@
+import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
+import { useState } from "react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { RemoteInstances } from "@/components/remote/RemoteInstances";
+import { RemoteConnectionsPage } from "@/components/remote/RemoteConnectionsPage";
+import { Sidebar } from "@/components/Sidebar";
+import { HOST_BRIDGE } from "@/components/remote/host-bridge";
+import { readSelectedRemote, rememberSelectedRemote, validateRemoteConnection, type RemoteConnection } from "@/lib/remote-instances";
+import i18n from "@/i18n";
+import type { Window as HappyWindow } from "happy-dom";
+
+(window as unknown as HappyWindow).happyDOM.settings.disableIframePageLoading = true;
+
+const mocks = vi.hoisted(() => {
+ const request = vi.fn();
+ const discover = vi.fn();
+ const onStatus = vi.fn();
+ return { read: vi.fn(), request, discover, onStatus, client: { status: "open", requestMutation: (action: string, payload: unknown, timeout: number) => action === "remote.discover" ? discover(payload) : request(action, payload, timeout), onStatus }, token: () => "local-token" };
+});
+vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: mocks.client, getToken: mocks.token }) }));
+vi.mock("@/lib/remote-instances", async (original) => ({
+ ...await original<typeof import("@/lib/remote-instances")>(), readRemoteInstances: mocks.read,
+}));
+
+const profile = { id: "3b968d52-081d-4898-9970-ff0a1fc93817", name: "Team server", host: "[email protected]", port: 22, config_path: "~/.nanobot/config.json", ssh_config: "", identity_file: "", runtime_user: "", connected: false };
+const connection: RemoteConnection = { ...profile, hostname: "team-host", gateway_id: "gateway-1", url: "http://127.0.0.1:23456/#/?bootstrapSecret=private-secret" };
+const noop = () => {};
+function LocalShell({ collapsed = false, initialRemote = false }) {
+ const [remotePage, setRemotePage] = useState(initialRemote);
+ return <>
+ <Sidebar collapsed={collapsed} sessions={[]} activeKey={null} loading={false} newChatActive={false}
+ onNewChat={() => setRemotePage(false)} onSelect={noop} onRequestDelete={noop} onTogglePin={noop}
+ onRequestRename={noop} onToggleArchive={noop} onToggleGroup={noop}
+ onRequestRenameProject={noop} onNewChatInProject={noop} onOpenSettings={noop}
+ onOpenApps={noop} onOpenSkills={noop} onOpenAutomations={noop} onOpenChannels={noop}
+ onOpenRemoteConnections={() => setRemotePage(true)} activeUtility={remotePage ? "remote" : null}
+ onOpenSearch={noop} onToggleArchived={noop} />
+ <main>{remotePage ? <RemoteConnectionsPage onBackToChat={() => setRemotePage(false)} /> : <><p>Local conversations</p><textarea aria-label="Local draft" /></>}</main>
+ </>;
+}
+const view = (collapsed = false, initialRemote = false) => render(<RemoteInstances><LocalShell collapsed={collapsed} initialRemote={initialRemote} /></RemoteInstances>);
+
+beforeEach(async () => {
+ await i18n.changeLanguage("en");
+ window.sessionStorage.clear(); window.localStorage.clear();
+ mocks.onStatus.mockReset().mockImplementation((handler) => { handler("open"); return () => {}; });
+ mocks.read.mockReset().mockResolvedValue({ available: true, machine_name: "Xubin-Mac", profiles: [profile] });
+ mocks.discover.mockReset().mockResolvedValue({ hosts: [], files: [], incomplete: false });
+ mocks.request.mockReset().mockImplementation(async (action: string) => {
+ if (action === "remote.connect") return connection;
+ if (action === "remote.save") return { id: profile.id };
+ return {};
+ });
+});
+afterEach(() => { cleanup(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });
+
+async function readyRemote() {
+ const frame = await screen.findByTitle("nanobot on Team server");
+ await act(async () => { fireEvent.load(frame); });
+ await waitFor(() => expect(readSelectedRemote()?.id).toBe(profile.id));
+ return frame;
+}
+async function chooseHost(name: string) {
+ fireEvent.pointerDown(screen.getByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });
+ fireEvent.click(await screen.findByRole("menuitem", { name }));
+}
+async function openDirectory() {
+ fireEvent.click(await screen.findByRole("button", { name: "Remote connections" }));
+}
+
+describe("remote instance UX", () => {
+ it("places remote connections after Channels with the existing sidebar button style", async () => {
+ view();
+ const entry = await screen.findByRole("button", { name: "Remote connections" });
+ const channels = screen.getByRole("button", { name: "Channels" });
+ expect(channels.nextElementSibling).toBe(entry);
+ expect(entry).toHaveClass("h-8", "rounded-xl", "text-[13px]");
+ expect(entry).not.toHaveAttribute("aria-haspopup");
+ expect(entry).not.toHaveAttribute("aria-current");
+ expect(screen.queryByText("This machine")).not.toBeInTheDocument();
+ fireEvent.click(entry);
+ await screen.findByRole("heading", { name: "Remote connections" });
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(screen.getByRole("main")).toContainElement(screen.getByText("Team server"));
+ expect(entry).toHaveAttribute("aria-current", "page");
+ expect(screen.getByRole("navigation", { name: "Sidebar navigation" })).toBeVisible();
+ expect(screen.getByText("Local nanobot")).toBeInTheDocument();
+ expect(screen.getByText("Currently using")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Connect to remote nanobot…" })).toBeInTheDocument();
+ });
+
+ it("keeps the connection action accessible when the sidebar is collapsed", async () => {
+ view(true);
+ const entry = await screen.findByRole("button", { name: "Remote connections" });
+ expect(entry).toHaveClass("w-8", "justify-center");
+ expect(entry.textContent).toBe("");
+ const switcher = screen.getByRole("button", { name: "Switch host" });
+ expect(switcher).toHaveClass("w-8", "h-8");
+ expect(switcher).toHaveAttribute("title", expect.stringContaining("Xubin-Mac"));
+ fireEvent.click(entry);
+ await screen.findByRole("heading", { name: "Remote connections" });
+ });
+
+ it("moves the remote picker into a verified sidebar and can return local through its parent-owned menu", async () => {
+ view();
+ await screen.findByText("Local");
+ await chooseHost("Team server [email protected]");
+ const frame = await screen.findByTitle("nanobot on Team server");
+ const source = { postMessage: vi.fn() };
+ Object.defineProperty(frame, "contentWindow", { value: source });
+ await act(async () => { fireEvent.load(frame); });
+ await waitFor(() => expect(readSelectedRemote()?.id).toBe(profile.id));
+ expect(screen.getByTestId("legacy-host-footer")).toBeVisible();
+ const nonce = source.postMessage.mock.calls[0][0].nonce;
+ const message = (data: Record<string, unknown>) => act(() => {
+ window.dispatchEvent(new MessageEvent("message", { source: source as unknown as Window,
+ origin: "http://127.0.0.1:23456", data: { channel: HOST_BRIDGE, nonce, ...data } }));
+ });
+ message({ type: "ready" });
+ expect(screen.queryByTestId("legacy-host-footer")).not.toBeInTheDocument();
+ message({ type: "open", anchor: { left: 40, top: 500, width: 150, height: 32 } });
+ expect(await screen.findByRole("menu")).toHaveAttribute("data-side", "top");
+ fireEvent.click(screen.getByRole("menuitem", { name: "Local nanobot Xubin-Mac" }));
+ await waitFor(() => expect(screen.getByText("Local conversations")).toBeVisible());
+ expect(frame).toBeInTheDocument();
+ expect(mocks.request.mock.calls.some(([action]) => action === "remote.disconnect")).toBe(false);
+ });
+
+ it("uses clear Chinese navigation and returns from the connection form without saving", async () => {
+ await i18n.changeLanguage("zh-CN");
+ view();
+ fireEvent.click(await screen.findByRole("button", { name: "远程连接" }));
+ expect(screen.getByText("本地 nanobot")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "连接远程 nanobot…" }));
+ expect(screen.getByRole("heading", { name: "连接远程 nanobot" })).toBeInTheDocument();
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "返回" }));
+ expect(screen.getByRole("heading", { name: "远程连接" })).toBeInTheDocument();
+ expect(screen.queryByRole("textbox", { name: "SSH 地址" })).not.toBeInTheDocument();
+ expect(mocks.request).not.toHaveBeenCalled();
+ });
+
+ it("opens a saved server without asking for keys or configuration again", async () => {
+ view(); await openDirectory();
+ fireEvent.click(screen.getByRole("button", { name: "Team server [email protected]" }));
+ const frame = await readyRemote();
+ expect(frame).toHaveAttribute("src", connection.url);
+ expect(frame).toHaveAttribute("sandbox", expect.not.stringContaining("allow-top-navigation"));
+ expect(document.querySelector('[data-host-view="local"]')).toHaveAttribute("inert");
+ expect(screen.getByRole("button", { name: "Switch host" })).toHaveAttribute("title", expect.stringContaining("Team server · team-host"));
+ expect(mocks.request).toHaveBeenCalledWith("remote.connect", { id: profile.id }, 65_000);
+ expect(window.sessionStorage.getItem("nanobot.remote-instance")).not.toContain("secret");
+ const storedValues = Array.from({ length: window.localStorage.length }, (_, index) =>
+ window.localStorage.getItem(window.localStorage.key(index) || ""));
+ expect(JSON.stringify(storedValues)).not.toContain("private-secret");
+ expect(JSON.stringify(storedValues)).not.toContain(connection.url);
+ });
+
+ it("returning local keeps the saved server view and SSH warm", async () => {
+ view(); await openDirectory();
+ fireEvent.click(screen.getByRole("button", { name: "Team server [email protected]" }));
+ await readyRemote();
+ await chooseHost("Local nanobot Xubin-Mac");
+ expect(screen.getByRole("heading", { name: "Remote connections" })).toBeVisible();
+ expect(mocks.request.mock.calls.some(([action]) => action === "remote.disconnect")).toBe(false);
+ expect(readSelectedRemote()).toBeNull();
+ expect(mocks.request.mock.calls.some(([action]) => String(action).includes("stop"))).toBe(false);
+ });
+
+ it("keeps local drafts, view identity and keyboard focus across warm round trips", async () => {
+ view();
+ const draft = screen.getByRole("textbox", { name: "Local draft" });
+ draft.focus();
+ fireEvent.change(draft, { target: { value: "Unsent local draft" } });
+ await screen.findByText("Local");
+ await chooseHost("Team server [email protected]");
+ const frame = await readyRemote();
+ expect(draft).not.toBeVisible();
+ const shortcut = vi.fn();
+ window.addEventListener("keydown", shortcut);
+ fireEvent.keyDown(screen.getByRole("button", { name: "Switch host" }), { key: "b", metaKey: true });
+ expect(shortcut).not.toHaveBeenCalled();
+ window.removeEventListener("keydown", shortcut);
+ await chooseHost("Local nanobot Xubin-Mac");
+ await waitFor(() => expect(draft).toHaveFocus());
+ expect(screen.getByRole("textbox", { name: "Local draft" })).toBe(draft);
+ expect(draft).toHaveValue("Unsent local draft");
+ await chooseHost("Team server [email protected] Ready");
+ expect(screen.getByTitle("nanobot on Team server")).toBe(frame);
+ expect(mocks.request.mock.calls.filter(([action]) => action === "remote.connect")).toHaveLength(1);
+ });
+
+ it("can close an offline cached view, but confirms before discarding its state", async () => {
+ view(); await openDirectory();
+ fireEvent.click(screen.getByRole("button", { name: "Team server [email protected]" }));
+ await readyRemote();
+ await chooseHost("Local nanobot Xubin-Mac");
+ fireEvent.pointerDown(screen.getByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false });
+ fireEvent.click(await screen.findByRole("menuitem", { name: "Disconnect" }));
+ const dialog = await screen.findByRole("dialog", { name: "Disconnect from Team server?" });
+ expect(mocks.request.mock.calls.some(([action]) => action === "remote.disconnect")).toBe(false);
+ fireEvent.click(within(dialog).getByRole("button", { name: "Disconnect" }));
+ await waitFor(() => expect(screen.queryByTitle("nanobot on Team server")).not.toBeInTheDocument());
+ expect(mocks.request).toHaveBeenCalledWith("remote.disconnect", { id: profile.id }, 65_000);
+ });
+
+ it("refresh restores the selected remote, keeping the local shell hidden", async () => {
+ rememberSelectedRemote(connection);
+ view();
+ expect(screen.queryByText("Local conversations")).not.toBeVisible();
+ await readyRemote();
+ expect(mocks.request).toHaveBeenCalledWith("remote.connect", { id: profile.id }, 65_000);
+ });
+
+ it("failed restore stays remote and offers reconnect and an explicit return", async () => {
+ rememberSelectedRemote(connection);
+ mocks.request.mockRejectedValue(new Error("ssh_unreachable"));
+ view();
+ await screen.findByText("Server connection lost");
+ expect(screen.queryByText("Local conversations")).not.toBeVisible();
+ expect(screen.getByRole("button", { name: "Reconnect" })).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Back to local nanobot" }));
+ await screen.findByText("Local conversations");
+ });
+
+ it("waits for the local socket before restoring and restores only once", async () => {
+ let status: ((value: string) => void) | undefined;
+ const unsubscribe = vi.fn();
+ mocks.onStatus.mockImplementation((handler) => { status = handler; handler("connecting"); return unsubscribe; });
+ rememberSelectedRemote(connection);
+ const rendered = view();
+ expect(mocks.request).not.toHaveBeenCalled();
+ expect(screen.queryByText("Local conversations")).not.toBeVisible();
+ await act(async () => { status?.("open"); });
+ await readyRemote();
+ await act(async () => { status?.("reconnecting"); status?.("open"); });
+ expect(mocks.request).toHaveBeenCalledTimes(1);
+ rendered.unmount();
+ expect(unsubscribe).toHaveBeenCalled();
+ });
+
+ it("clears errors from an earlier connection when opening a server from the page", async () => {
+ rememberSelectedRemote(connection);
+ mocks.request.mockRejectedValue(new Error("ssh_unreachable"));
+ view();
+ await screen.findByText("Server connection lost");
+ fireEvent.click(screen.getByRole("button", { name: "Back to local nanobot" }));
+ await screen.findByText("Local conversations");
+ mocks.request.mockResolvedValue(connection);
+ await openDirectory();
+ fireEvent.click(screen.getByRole("button", { name: "Team server [email protected]" }));
+ await readyRemote();
+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();
+ });
+
+ it("saves once and preserves entered fields when SSH authentication fails", async () => {
+ mocks.request.mockImplementation(async (action: string) => {
+ if (action === "remote.save") return { id: profile.id };
+ throw new Error("ssh_auth_failed");
+ });
+ view(); await openDirectory(); fireEvent.click(screen.getByRole("button", { name: "Connect to remote nanobot…" }));
+ fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: "[email protected]" } });
+ fireEvent.click(screen.getByRole("button", { name: "Save & connect" }));
+ await screen.findByRole("alert");
+ expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue("[email protected]");
+ expect(screen.getByRole("button", { name: "Save & connect" })).toBeEnabled();
+ expect(mocks.request.mock.calls.filter(([action]) => action === "remote.save")).toHaveLength(1);
+ });
+
+ it("doesn't create privileged controls on an unsupported remote gateway", async () => {
+ mocks.read.mockResolvedValue({ available: false, profiles: [] });
+ view(); await waitFor(() => expect(mocks.read).toHaveBeenCalled());
+ expect(screen.queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();
+ });
+
+ it("does not discover SSH hosts or expose nested connections inside a remote frame", async () => {
+ vi.stubGlobal("top", {});
+ view(false, true);
+ await screen.findByText(i18n.t("remote.unavailable"));
+ expect(mocks.read).not.toHaveBeenCalled();
+ expect(mocks.discover).not.toHaveBeenCalled();
+ expect(screen.queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Connect to remote nanobot…" })).not.toBeInTheDocument();
+ });
+
+ it("offers existing SSH hosts or manual inline setup for the first server", async () => {
+ mocks.read.mockResolvedValue({ available: true, profiles: [] });
+ view(); await openDirectory();
+ await screen.findByText("No named hosts found. You can enter an SSH address below.");
+ fireEvent.click(screen.getByRole("button", { name: "Connect to remote nanobot…" }));
+ const host = screen.getByRole("textbox", { name: "SSH address" });
+ expect(host.closest(".settings-row")).not.toBeNull();
+ expect(screen.getByRole("main")).toContainElement(host);
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(screen.queryByRole("button", { name: "Connect to remote nanobot…" })).not.toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Save & connect" })).toBeDisabled();
+ });
+
+ it("does not navigate to a remote instance after leaving a pending connection", async () => {
+ let finish: ((result: RemoteConnection) => void) | undefined;
+ mocks.request.mockImplementation(() => new Promise<RemoteConnection>((resolve) => { finish = resolve; }));
+ view(); await openDirectory();
+ fireEvent.click(screen.getByRole("button", { name: "Team server [email protected]" }));
+ fireEvent.click(screen.getByRole("button", { name: "New topic" }));
+ await act(async () => { finish?.(connection); });
+ expect(screen.getByText("Local conversations")).toBeVisible();
+ expect(screen.queryByTitle("nanobot on Team server")).not.toBeInTheDocument();
+ expect(readSelectedRemote()).toBeNull();
+ });
+
+ it("does not start SSH if the user leaves while a profile is saving", async () => {
+ let finish: ((result: { id: string }) => void) | undefined;
+ mocks.read.mockResolvedValue({ available: true, profiles: [] });
+ mocks.request.mockImplementation(() => new Promise<{ id: string }>((resolve) => { finish = resolve; }));
+ view(); await openDirectory();
+ fireEvent.click(screen.getByRole("button", { name: "Connect to remote nanobot…" }));
+ fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: "[email protected]" } });
+ fireEvent.click(screen.getByRole("button", { name: "Save & connect" }));
+ fireEvent.click(screen.getByRole("button", { name: "New topic" }));
+ await act(async () => { finish?.({ id: profile.id }); });
+ expect(mocks.request).toHaveBeenCalledTimes(1);
+ expect(screen.getByText("Local conversations")).toBeVisible();
+ });
+
+ it("keeps cached servers visible during refresh and lets users retry failed reads", async () => {
+ view();
+ await screen.findByRole("button", { name: "Remote connections" });
+ mocks.read.mockRejectedValue(new Error("directory_unavailable"));
+ await openDirectory();
+ await screen.findByRole("alert");
+ expect(screen.getByText("Team server")).toBeVisible();
+ mocks.read.mockResolvedValue({ available: true, profiles: [profile] });
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ await waitFor(() => expect(screen.queryByRole("alert")).not.toBeInTheDocument());
+ expect(screen.getByText("Team server")).toBeVisible();
+ });
+
+ it("explains unavailable direct routes without displaying SSH controls", async () => {
+ mocks.read.mockResolvedValue({ available: false, profiles: [] });
+ view(false, true);
+ await screen.findByText("Open this page from a locally running nanobot to connect to servers over SSH.");
+ expect(screen.queryByRole("textbox", { name: "SSH address" })).not.toBeInTheDocument();
+ expect(mocks.request).not.toHaveBeenCalled();
+ });
+
+ it("identifies the host in the existing sidebar footer without a top bar", async () => {
+ view();
+ const identity = await screen.findByRole("button", { name: "Switch host" });
+ expect(identity).toHaveTextContent("Local");
+ expect(identity).toHaveAttribute("title", expect.stringContaining("Xubin-Mac"));
+ expect(screen.getByRole("navigation", { name: "Sidebar navigation" })).toContainElement(identity);
+ expect(document.querySelector("header")).toBeNull();
+ fireEvent.pointerDown(identity, { button: 0, ctrlKey: false });
+ expect(await screen.findByRole("menuitem", { name: "Local nanobot Xubin-Mac" })).toBeVisible();
+ expect(screen.getByRole("menuitem", { name: "Manage connections…" })).toBeVisible();
+ });
+
+ it("discovers and filters SSH aliases without connecting, then inherits the selected config", async () => {
+ mocks.discover.mockResolvedValue({ hosts: [
+ { host: "team-sg", source: "/home/test/.ssh/config", ssh_config: "" },
+ { host: "staging", source: "/home/test/.ssh/hosts", ssh_config: "" },
+ ], files: ["/home/test/.ssh/config"], incomplete: false });
+ view(); await openDirectory();
+ await screen.findByRole("button", { name: "Use team-sg" });
+ expect(mocks.request).not.toHaveBeenCalled();
+ fireEvent.change(screen.getByRole("textbox", { name: "Search SSH hosts" }), { target: { value: "team" } });
+ expect(screen.queryByRole("button", { name: "Use staging" })).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: "Use team-sg" }));
+ expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue("team-sg");
+ fireEvent.click(screen.getByRole("button", { name: "Save & connect" }));
+ await readyRemote();
+ expect(mocks.request).toHaveBeenCalledWith("remote.save", expect.objectContaining({ profile: expect.objectContaining({ host: "team-sg", ssh_config: "", port: null }) }), 65_000);
+ });
+
+ it("reads a custom SSH config and carries that path to the selected profile", async () => {
+ view(); await openDirectory();
+ fireEvent.click(screen.getByRole("button", { name: "Use another SSH config file" }));
+ fireEvent.change(screen.getByRole("textbox", { name: "SSH config file to read" }), { target: { value: "/team/ssh_config" } });
+ mocks.discover.mockResolvedValue({ hosts: [{ host: "team", source: "/team/ssh_config", ssh_config: "/team/ssh_config" }], files: ["/team/ssh_config"], incomplete: false });
+ fireEvent.click(screen.getByRole("button", { name: "Read hosts" }));
+ fireEvent.click(await screen.findByRole("button", { name: "Use team" }));
+ fireEvent.click(screen.getByRole("button", { name: "Advanced options" }));
+ expect(screen.getByRole("textbox", { name: "SSH config file (optional)" })).toHaveValue("/team/ssh_config");
+ expect(screen.getByRole("spinbutton", { name: "SSH port" })).toHaveValue(null);
+ expect(mocks.discover).toHaveBeenCalledWith({ ssh_config: "/team/ssh_config" });
+ const reads = mocks.discover.mock.calls.length;
+ fireEvent.click(screen.getByRole("button", { name: "Back" }));
+ expect(screen.getByRole("button", { name: "Use team" })).toBeVisible();
+ expect(screen.getByRole("textbox", { name: "SSH config file to read" })).toHaveValue("/team/ssh_config");
+ expect(mocks.discover).toHaveBeenCalledTimes(reads);
+ });
+
+ it("keeps manual entry available for an invalid discovery response", async () => {
+ mocks.discover.mockResolvedValue({ hosts: [{}], files: [], incomplete: false });
+ view(); await openDirectory();
+ await screen.findByRole("alert");
+ fireEvent.click(screen.getByRole("button", { name: "Connect to remote nanobot…" }));
+ expect(screen.getByRole("textbox", { name: "SSH address" })).toBeVisible();
+ expect(mocks.request).not.toHaveBeenCalled();
+ });
+
+ it("keeps manual setup available when discovery fails and does not clear cached hosts", async () => {
+ mocks.discover.mockResolvedValue({ hosts: [{ host: "team", source: "/config", ssh_config: "/config" }], files: ["/config"], incomplete: false });
+ view(); await openDirectory();
+ await screen.findByRole("button", { name: "Use team" });
+ mocks.discover.mockRejectedValue(new Error("ssh_config_unreadable"));
+ fireEvent.click(screen.getByRole("button", { name: "Refresh SSH hosts" }));
+ await screen.findByRole("alert");
+ expect(screen.getByRole("button", { name: "Use team" })).toBeVisible();
+ fireEvent.click(screen.getByRole("button", { name: "Connect to remote nanobot…" }));
+ expect(screen.getByRole("textbox", { name: "SSH address" })).toBeVisible();
+ });
+
+ it("requires an explicit fingerprint confirmation and never trusts a changed host", async () => {
+ mocks.request.mockImplementation(async (action: string) => {
+ if (action === "remote.connect") throw new Error("host_key_unknown");
+ if (action === "remote.fingerprint") return { fingerprint: "SHA256:example", challenge: "one-use" };
+ return {};
+ });
+ view(); await openDirectory();
+ fireEvent.click(screen.getByRole("button", { name: "Team server [email protected]" }));
+ await screen.findByText("SHA256:example");
+ expect(mocks.request.mock.calls.some(([action]) => action === "remote.trust")).toBe(false);
+ mocks.request.mockImplementation(async (action: string) => action === "remote.connect" ? connection : {});
+ fireEvent.click(screen.getByRole("button", { name: "Fingerprint matches · Connect" }));
+ await readyRemote();
+ expect(mocks.request).toHaveBeenCalledWith("remote.trust", { id: profile.id, challenge: "one-use" }, 65_000);
+ });
+
+ it("tolerates transient health failures and covers, rather than reloads, the remote frame", async () => {
+ let tick: (() => void) | undefined;
+ vi.spyOn(window, "setInterval").mockImplementation((callback, delay) => { if (delay === 5_000) tick = callback as () => void; return 1; });
+ view(); await openDirectory();
+ fireEvent.click(screen.getByRole("button", { name: "Team server [email protected]" }));
+ const frame = await readyRemote();
+ fireEvent.load(frame);
+ await act(async () => { tick?.(); });
+ expect(screen.queryByText("Server connection lost")).not.toBeInTheDocument();
+ await act(async () => { tick?.(); });
+ await screen.findByText("Server connection lost");
+ expect(screen.getByTitle("nanobot on Team server")).toBeInTheDocument();
+ expect(frame.parentElement).toHaveAttribute("inert");
+ expect(document.querySelector('[data-host-view="local"]')).toHaveAttribute("inert");
+ fireEvent.click(screen.getByRole("button", { name: "Reconnect" }));
+ await waitFor(() => expect(screen.queryByText("Server connection lost")).not.toBeInTheDocument());
+ expect(screen.queryByText("Opening your server…")).not.toBeInTheDocument();
+ expect(screen.getByTitle("nanobot on Team server")).toBe(frame);
+ expect(frame.parentElement).not.toHaveAttribute("inert");
+ });
+});
+
+it.each(["https://evil.example/", "http://[email protected]:23456/", "javascript:alert(1)", "http://127.0.0.1:23456/wrong"])("rejects unsafe navigation %s", (url) => {
+ expect(() => validateRemoteConnection({ ...connection, url })).toThrow();
+});