Your lightweight open-source personal agent.
Python agent-frameworkai-agentai-agentschatbotchatopsdiscord-botllm-agentsllmslocal-llmmcpmodel-context-protocolmulti-agentopenai-compatibleopenclawpersonal-ai-assistantpythonself-hostedtelegram-bot-ai-assistantwebuiworkflow-automation
feat(webui): complete remote pairing and connection recovery
Xubin Ren192ca6e49e91
diff --git a/docs/guides/remote-instances.md b/docs/guides/remote-instances.mdindex 9c4b8d6a3..03ca065b8 100644--- a/docs/guides/remote-instances.md+++ b/docs/guides/remote-instances.md@@ -1,27 +1,160 @@# 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.+Open your local **nanobot WebUI**, click the current host (initially **Local**)+at the bottom of the sidebar, and choose **Manage connections…**. This is the+single entry point for switching and managing hosts. The page lists this computer+and your saved servers. Choose+**Add server** to copy a prepared pairing command, or choose **Other ways → Use existing SSH settings**+to enter an SSH address such as+`ubuntu@your-server` or pick a suggested host from your SSH config. Choose+**Connect**. Next time, select the saved server directly. No port-forwarding+command or `.command` launcher is needed.++With more than five saved servers, the host menu includes search by name or SSH+address. The current server and recently used servers appear first; the local+computer stays at the top. Only the host list scrolls, so **Manage connections…**+stays visible. Use the arrow keys to choose a result, Enter to connect, and Escape+to close. Recent choices are remembered in this browser, not synced to servers.++To add another server, choose **Add server** below your saved connections. Use a+server's menu to edit or forget it. Editing opens the same dialog; **Save changes**+saves without connecting or switching hosts. Disconnect an open server before+editing its connection settings. The page supports browser back/forward and the+`#/remote` route. Cancelling setup while saving or connecting prevents a later+automatic switch. A profile or SSH tunnel already created is not rolled back;+you can manage it from the directory. Adding the same connection settings again+reuses that entry, without renaming it or disconnecting an open view.This connects to the nanobot **already running on the server**. It does notinstall a worker, clone a workspace, move conversations, or start a second bot.It is separate from remote execution/worker deployment.+## Quick pairing: copy a command, follow a link back++For a Linux server with this version of nanobot installed, you do not need to+prepare a local SSH key or know the service account/config path:++1. In your **local** WebUI choose **Add server → Copy command**. The command is+ prepared when setup opens; **View command** lets you inspect it before running.+ After a successful copy, the dialog shows what to do in your server terminal.+ This is a clipboard confirmation, not a claim that the server is connected.+ **Other ways → Requirements & help** contains prerequisites and expiry details.+2. Open your cloud provider's server terminal. Run the command in the environment+ where nanobot is installed (activate its virtual environment for source installs).+ The command discovers the default config and named nanobot systemd services;+ choose a configuration if there is more than one. Provide the server's reachable+ IP/hostname and an existing non-root SSH login account when prompted.+ A single existing login account (including the original account under sudo)+ is selected automatically and shown in the authorization summary. A global+ server address reported by the SSH session can also be selected automatically;+ private/NAT addresses are never guessed. Use `--ssh-user` or `--host` to override.+3. Review the **full nanobot access** authorization on the server and confirm it.+ If nanobot runs as another service account, the server administrator must run+ this step. Pairing does not install sudo rules or weaken config permissions.+4. Open the terminal's **Return to nanobot** link on the same computer and in the+ same browser profile that started pairing. The local WebUI opens the server+ confirmation directly; review its identity and access, then choose **Connect**.+ The link does not authorize or connect automatically. If the terminal cannot+ open links, choose **Other ways → Use a connection code instead** and paste the returned+ `nbpc1.…` code, then **Review connection**. Both paths use the same verification.++The return link targets only an HTTP loopback origin (`127.0.0.1`, `localhost`,+or `[::1]`). Its fragment contains an encrypted receipt, not a plaintext admin+secret, and is scrubbed before the WebUI signs in. A new tab can continue the+request even if the original setup tab was closed. Pending keys remain on the+local backend for the ten-minute invitation lifetime; abandoned requests are+cleaned when a new request is prepared. A link opened on another machine, an+expired request, or a modified code fails closed. Native/non-loopback origins+continue to use the code fallback. Existing local authentication is still required.++No relay, public WebUI, uploaded private key, QR scan or new firewall rule is+involved. The public invitation expires after ten minutes. The returned code is+encrypted for that local instance; another computer/request cannot import it.+The server host key is pinned from the code copied through your trusted terminal.+Do not accept a connection code supplied by someone you do not trust.++The dedicated device SSH key expires after 90 days. OpenSSH `restrict` disables+shell-adjacent features and all SSH forwarding; a forced, fixed Python stdio+bridge connects only to the selected loopback nanobot port. It cannot execute+the client's SSH command. No extra daemon is installed or started. The server+requires OpenSSH with `restrict` and `expiry-time` support, `/usr/bin/python3`,+an Ed25519 host key, and the conventional `~/.ssh/authorized_keys` layout.+Custom SSH policies/layouts may reject the grant; use existing SSH settings in+that case. Windows servers and containers are not supported by quick pairing.++This is still **full access to nanobot**, not read-only access. Its configured+tools may themselves run commands or modify files. The WebUI credential stays+in the local backend, encrypted at rest alongside a private local decryption key+and dedicated SSH identity (directories `0700`, files `0600`). This protects+against other OS users, not compromise of your logged-in account. Provider keys+are not exported by the pairing protocol. Changes to the remote WebUI secret or+port require pairing again; they are not silently refreshed through sudo.++SSH network reachability is still required. Pairing cannot fix a blocked port or+VPN route. A failed connection keeps the paired profile for retry. **Network+route…** can explicitly reuse a saved connection's proxy/bound-interface route+to the same host, without copying its identity settings. Jump-host routes should+continue to use the ordinary SSH connection flow.++If the server rejects a paired device key, the UI asks you to pair again rather+than unlock an unrelated SSH agent. This can happen after revocation or expiry.++**Disconnect** closes local streams. **Forget** removes the local directory entry,+including that device's local pairing keys, but does not revoke server authorization.+To revoke, run the command displayed+in the connection details on the server:++```bash+nanobot remote revoke DEVICE_ID --ssh-user LOGIN_ACCOUNT+```++Only that device's exact managed key entry is removed; existing login keys stay+unchanged. Close any already-open remote sessions too: removing an authorized+key prevents new SSH authentication, not existing sessions. If setup is cancelled+after server authorization, use the revoke command printed in that terminal.+Re-pairing after expiry uses a new independent key, not an extension of an old grant.++## Existing SSH setup: server, then nanobot++The setup dialog separates **Server** (SSH login) from **nanobot** (which+installation to open). Start with an address or an existing SSH host. You do+not need to know nanobot's config path in advance.++After SSH signs in, a read-only check looks for the selected account's config+and up to eight named `nanobot*.service` systemd units. It reads service metadata+and checks config-file locations; it does not read their contents, scan other+users' home directories, run sudo, install software or change permissions.+One configuration belonging to the login account opens automatically. Multiple+configurations are shown as choices. A service owned by another account always+requires an explicit **Open nanobot** choice, showing that account and path;+opening still requires existing passwordless sudo permission.++If nothing is found, the dialog confirms **SSH connected** and asks for the+server's config path and optional service account. Docker, custom service names,+user services and non-systemd deployments may need this manual step. Failure to+find a config is not proof that nanobot is absent. Finding a config is also not+proof that its WebUI is running: the normal authenticated gateway check still+happens before opening.++SSH failures keep the entered address and offer **SSH login settings** for the+local key path, SSH config and port. Connection refusal, name resolution,+connection closure and authentication rejection have distinct messages. The+application does not infer a missing key from a closed connection, nor change+VPN, proxy or network-interface settings automatically. A custom SSH config+outside standard locations must still be explicitly supplied by its owner.+## 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.+The add/edit dialog suggests named hosts from `~/.ssh/config` and the system SSH+config, including ordinary `Include` files. Typing in **SSH address** filters+these suggestions without a separate search field. Selecting a host fills the+address; it does not connect until you choose **Connect**. Arrow keys navigate+the suggestions. If your configuration lives elsewhere, expand **Connection+options** and select the file beside **SSH config file**, or enter its local path.+Suggestions update automatically; no separate file-reading step is needed.+The private key field also has a native file chooser. Selecting a file returns+only its path: it does not upload, copy or read the private key. Cancelling leaves+the existing path unchanged. Headless hosts can use the manual path fields.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@@ -33,13 +166,22 @@ you can still enter an alias manually. Discovery is capped at 200 hosts, 64 fileAt connection time, the system SSH client resolves your existing `User`, `Port`,`IdentityFile`, jump hosts and other connection settings. An empty port fieldinherits 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.+does not mean nanobot is installed there.++You can also paste a simple command, for example+`ssh -p 2222 -i "~/.ssh/team key" ubuntu@your-server`. The address field imports+`-p` (port), `-i` (key path), `-F` (config path) and `-l` (login user) into the+existing Connection options. Review these before connecting. Quoted paths can+contain spaces, including Windows paths. This is an importer, not a terminal:+remote commands, shell expansions, repeated options and other flags are rejected,+not executed or silently discarded. Keep advanced options such as `ProxyJump`+in your SSH config and enter the alias. An interactive alias's `RemoteCommand`+and forced TTY are disabled for the fixed nanobot probe.## 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+- For **existing SSH settings**, your key must already have access to the server. Encrypted keys shouldbe unlocked in the system SSH agent. Interactive SSH passwords are notcollected by this UI.- The remote server needs `python3` and an already running nanobot WebUI with@@ -47,18 +189,22 @@ shell command.- 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.+ encrypts the connection. A configured public WebSocket URL or trusted-proxy+ authentication is not supported by this SSH connection mode.If this machine has never connected to the server, nanobot displays its SSHfingerprint. Compare it with the server console or your administrator before-confirming. The public key is pinned for this connection, without changing+confirming in the same dialog. **Back** returns to the filled-in form when adding+a server. The public key is pinned for this connection, without changingyour system `known_hosts`. A **changed** host key is blocked, not automaticallyaccepted. Jump-host-only or non-Ed25519 hosts can use a previously verifiedsystem SSH configuration instead of the in-app first-contact verifier.-## Advanced options+## Connection options-Most setups only need the SSH address. Expand **Advanced** when necessary:+Most setups only need the SSH address. Expand **Connection options** when necessary.+You can also give the server a recognizable name here; otherwise its address is+used as the name.| Option | Meaning || --- | --- |@@ -70,8 +216,10 @@ Most setups only need the SSH address. Expand **Advanced** when necessary:For a service installation, the SSH login and nanobot owner may differ. Forexample, 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.+its config in `/var/lib/nanobot/.nanobot/config.json`. The discovery step offers+these values when it finds the service; otherwise use **Specify a different+location** in the nanobot step. Editing a saved connection also exposes these+fields. The connection does not grant new sudo privileges.## Using the remote instance@@ -100,6 +248,12 @@ return local without covering their controls.Refreshing restores the selected remote instance. A failed connection stayson a remote error screen; it never silently redirects work to your local agent.The selected server ID is stored per browser tab, without credentials.+When the page becomes visible again or the browser reports network recovery,+nanobot immediately rechecks existing connections. It does not reload the remote+view, switch hosts, or resend messages. If the connection remains unavailable,+use **Reconnect**. Different aliases resolving to the same already-connected+gateway are rejected; choose its existing entry in the host switcher. Separate+nanobot instances on one server can still use separate profiles and config paths.- **Switching hosts**, including returning local, keeps both pages mounted andkeeps SSH connected. Each host retains its own chat, unsent draft, scroll@@ -129,15 +283,47 @@ The selected server ID is stored per browser tab, without credentials.The local connection directory is stored beside the local config under`webui/remote-instances.json`. It contains connection metadata, not private-keycontents 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.+keeps browser preferences scoped to that server. Changing the SSH target, config+path, service account or identity file assigns a fresh browser origin, rather+than loading the previous instance's drafts. The adjacent+`remote-origin-ports.json` records previously used ports, without credentials;+these ports are not assigned to new targets, even after forgetting a profile.+Keep that file alongside the connection directory when moving local settings.+Port conflicts fail explicitly; nanobot does not attach to an unrelated listener.++The local gateway owns a browser-facing proxy and a separate, private SSH+transport. Browser login, API, WebSocket and media credentials are local+capabilities: they cannot authenticate to the remote gateway. The remote+credentials stay in backend memory. System SSH's private stdin/stdout pipes,+SSH configuration and host-key verification still secure the upstream transport.+Disconnecting or forgetting closes active requests but retains disabled+listeners until local gateway shutdown. Reconnecting the same saved instance+reuses its browser origin. An offline profile can be edited without first+disconnecting it in another tab.++Closing the local gateway drains proxy requests before releasing its private+transport. If an old tab retries the browser address after shutdown, it sends+only local capabilities from the stopped proxy, not a remote login credential.+Close old tabs anyway: after shutdown another local process can serve content+at that address. This does not isolate nanobot from malware running as you.+On Windows, exclusive socket ownership may delay reusing a port after shutdown;+retry later if it remains occupied. Nanobot does not weaken socket ownership+to force a reconnect.SSH authenticates the server. A read-only, fixed Python probe retrieves onlyWebUI 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.+are verified before navigation. Only a local proxy credential is passed in the+remote view's URL fragment and stored by its existing login UI. Local gateway+restart replaces that credential and invalidates local token/media mappings;+reopening the saved connection handles this without an extra login step.+Nothing opens a public administration port or forwards your SSH agent.++**Upgrading the earlier remote-connection prototype:** it passed the remote+WebUI login secret to browser storage. This version retires those old browser+origins, but cannot revoke a secret already saved in an old tab. Close those+tabs, clear their browser site data, and rotate the remote WebUI login secret+to invalidate the old credential. This migration does not rotate credentials+or restart your server automatically.Remote-connection actions require an authenticated local WebUI connection, aloopback-bound gateway, and local request origin. They are unavailable from a@@ -146,6 +332,12 @@ access; permission to mention nanobot in Linear is **not** that permission.Common errors explain whether SSH authentication, a missing config, a serviceaccount, WebUI authentication, protocol compatibility or networking failed.+Key-agent refusal, unsafe key-file permissions, invalid SSH configuration and+server-side port-forwarding denial have separate recovery hints. Login banners+are ignored when reading the framed probe result. A failed probe is distinct+from an invalid nanobot configuration; raw SSH output and credentials aren't+displayed in error messages. If SSH works in a terminal but not in nanobot,+check that nanobot was started with access to the same system SSH agent.Configurations whose WebUI secret is supplied only by a service environment,interactive SSH passwords, and remote WebUIs with a public WebSocket URL needadditional setup; this flow does not silently weaken their authentication.diff --git a/nanobot/cli/commands.py b/nanobot/cli/commands.pyindex 3a20e1319..83c2cc795 100644--- a/nanobot/cli/commands.py+++ b/nanobot/cli/commands.py@@ -97,6 +97,11 @@ app = typer.Typer(console = Console()+# Server-console pairing stays outside the agent/gateway lifecycle.+from nanobot.cli.remote import app as remote_app # noqa: E402++app.add_typer(remote_app, name="remote")+def version_callback(value: bool):if value:console.print(f"{__logo__} nanobot v{__version__}")diff --git a/nanobot/cli/remote.py b/nanobot/cli/remote.pynew file mode 100644index 000000000..9cac4b949--- /dev/null+++ b/nanobot/cli/remote.py@@ -0,0 +1,139 @@+"""Server-console commands for explicit remote WebUI device authorization."""++from __future__ import annotations++import ipaddress+import os+import subprocess+import sys+import time+from pathlib import Path++import typer+from click import IntRange++app = typer.Typer(help="Pair this server with a local nanobot. No public WebUI or relay.")+++def _default_host() -> str:+ """Use only a globally reachable address reported by this SSH session.++ A cloud's outbound address or a NAT/private address is not evidence of the+ inbound SSH destination. Do not contact an external IP lookup service.+ """+ fields = os.environ.get("SSH_CONNECTION", "").split()+ try:+ address = ipaddress.ip_address(fields[2]) if len(fields) == 4 else None+ return str(address) if address and address.is_global else ""+ except ValueError:+ return ""+++def _default_ssh_user() -> str | None:+ """Suggest the existing login account, including when invoked through sudo."""+ import pwd++ current = pwd.getpwuid(os.getuid())+ if current.pw_uid:+ return current.pw_name+ users = [u.pw_name for u in pwd.getpwall() if 1000 <= u.pw_uid < 65534 and u.pw_shell.endswith(("/bash", "/sh", "/zsh"))]+ sudo_user = os.environ.get("SUDO_USER")+ if sudo_user in users:+ return sudo_user+ return users[0] if len(users) == 1 else None+++def pair(+ request: str = typer.Argument(help="Public pairing request copied from your local WebUI"),+ host: str = typer.Option("", help="Server IP or hostname reachable from your computer"),+ ssh_user: str = typer.Option("", help="Existing non-root SSH login account"),+ port: int = typer.Option(22, min=1, max=65535, help="Existing SSH port; not changed"),+ config: Path | None = typer.Option(None, help="Existing nanobot config; discovered if omitted"),+) -> None:+ """Run in your server terminal, then open the returned link on your computer."""+ from nanobot.webui.remote_pairing import fingerprint, read_request, return_link+ from nanobot.webui.remote_ssh import RemoteError++ try:+ if sys.platform != "linux":+ raise RemoteError("pair_linux_required")+ from nanobot.webui.remote_pair_server import authorize, metadata++ invitation = read_request(request)+ host_key = " ".join(Path("/etc/ssh/ssh_host_ed25519_key.pub").read_text().split()[:2])+ if config is None:+ from nanobot.webui.remote_discovery import (+ _LOCATE, # pyright: ignore[reportPrivateUsage]+ RemoteInspection,+ )++ result = subprocess.run([sys.executable, "-c", _LOCATE, str(Path.home() / ".nanobot/config.json")], capture_output=True, text=True, timeout=8)+ records = [line.partition("NANOBOT_REMOTE:")[2] for line in result.stdout.splitlines() if "NANOBOT_REMOTE:" in line]+ candidates = RemoteInspection.model_validate_json(records[-1]).candidates if records else []+ if len(candidates) == 1:+ config = Path(candidates[0].config_path)+ elif candidates:+ for index, item in enumerate(candidates, 1):+ typer.echo(f'{index}. {item.service or "nanobot"} — {item.config_path}')+ choice = int(typer.prompt("Which nanobot?", type=IntRange(1, len(candidates))))+ config = Path(candidates[choice - 1].config_path)+ else:+ config = Path(typer.prompt("Path to your nanobot config"))+ config = config.expanduser().resolve()+ details = metadata(config)+ if not ssh_user:+ ssh_user = _default_ssh_user() or typer.prompt("SSH login account")+ if not host:+ host = _default_host() or typer.prompt("Server public IP or hostname (shown in your cloud console)")+ typer.echo(f"\nAuthorize {invitation.label} to use nanobot on {ssh_user}@{host}?\nConfig: {config}\nServer fingerprint: {fingerprint(host_key)}")+ typer.echo("This grants full nanobot WebUI access, including configured tools and settings.\nA dedicated SSH key can only reach this nanobot port; no shell or other forwarding.\nAuthorization lasts 90 days. No existing keys, firewall rules or model settings change.")+ typer.confirm("Authorize this computer?", abort=True, default=False)+ # Check the service is running before granting access; no credential is sent.+ import socket++ with socket.create_connection(("127.0.0.1", details["port"]), timeout=5):+ pass+ code = authorize(invitation, host=host, user=ssh_user, ssh_port=port, config=config,+ host_key=host_key, until=int(time.time()) + 90 * 86400)+ link = return_link(invitation, code)+ if link:+ typer.echo("\nReturn to nanobot on your computer to finish connecting:")+ typer.echo("Open this link in the same computer/browser that started pairing.\n")+ typer.echo(link)+ typer.echo("\nIf your terminal cannot open links, paste this connection code into nanobot:\n")+ else:+ typer.echo("\nPaste this connection code into the same local nanobot window:\n")+ typer.echo(code)+ typer.echo(f"\nTo revoke new connections: nanobot remote revoke {invitation.id} --ssh-user {ssh_user}")+ typer.echo("Close any already-open remote sessions as well. Re-pair after changing the WebUI secret or port.")+ except (OSError, ValueError, KeyError, subprocess.SubprocessError, RemoteError) as exc:+ typer.echo(f"Pairing not completed: {str(exc) if isinstance(exc, RemoteError) else 'check server config, login account and SSH installation'}. Existing settings were not reset.", err=True)+ if str(exc) == "config_permission":+ typer.echo("The nanobot config belongs to another account. Run this command in its installation environment as the server administrator, or ask that administrator to pair it. Do not make the config publicly readable.", err=True)+ raise typer.Exit(1) from None+++def revoke(device: str, ssh_user: str = typer.Option("", help="SSH account used when pairing")) -> None:+ """Remove only this device's managed SSH authorization, preserving other keys."""+ import getpass++ from nanobot.webui.remote_ssh import RemoteError++ try:+ if sys.platform != "linux":+ raise RemoteError("pair_linux_required")+ from nanobot.webui.remote_pair_server import as_account++ user = ssh_user or getpass.getuser()+ typer.confirm(f"Revoke device {device} for SSH account {user}?", abort=True, default=False)+ as_account(user, "revoke", {"id": device})+ typer.echo("Authorization removed. Already-open SSH sessions must also be closed.")+ except (OSError, KeyError, RemoteError, subprocess.SubprocessError):+ typer.echo("Could not revoke. Check the device ID and run as the SSH account or server administrator.", err=True)+ raise typer.Exit(1) from None+++if __name__ == "__main__":+ app()diff --git a/nanobot/webui/native_folder_picker.py b/nanobot/webui/native_folder_picker.pyindex 37a91dbcc..e97df8ec3 100644--- a/nanobot/webui/native_folder_picker.py+++ b/nanobot/webui/native_folder_picker.py@@ -1,4 +1,4 @@-"""Native directory picker used by a locally hosted WebUI."""+"""Native path pickers used by a locally hosted WebUI; never read file contents."""from __future__ import annotations@@ -9,6 +9,7 @@ import sysfrom contextlib import suppressfrom dataclasses import dataclassfrom pathlib import Path+from typing import Literal_PICKER_TIMEOUT_SECONDS = 300_COMMON_ENV_KEYS = (@@ -66,7 +67,8 @@ class _PickerCommand:cancel_markers: tuple[str, ...] = ()-def _picker_command() -> _PickerCommand | None:+def _picker_command(kind: Literal["folder", "file"] = "folder") -> _PickerCommand | None:+ title = "Select Workspace Directory" if kind == "folder" else "Select SSH key or configuration file"if sys.platform == "darwin":executable = shutil.which("osascript")if executable is None:@@ -75,9 +77,9 @@ def _picker_command() -> _PickerCommand | None:argv=(executable,"-e",- 'set selectedFolder to choose folder with prompt "Select Workspace Directory"',+ f'set selectedPath to choose {kind} with prompt "{title}"',"-e",- "POSIX path of selectedFolder",+ "POSIX path of selectedPath",),cancel_codes=frozenset({1}),cancel_markers=("user canceled", "(-128)"),@@ -87,14 +89,22 @@ def _picker_command() -> _PickerCommand | None:executable = shutil.which("powershell.exe") or shutil.which("powershell")if executable is None:return None- script = (- "Add-Type -AssemblyName System.Windows.Forms;"+ dialog = ("$dialog=New-Object System.Windows.Forms.FolderBrowserDialog;"- "$dialog.Description='Select Workspace Directory';"+ f"$dialog.Description='{title}';""$dialog.ShowNewFolderButton=$true;"+ ) if kind == "folder" else (+ "$dialog=New-Object System.Windows.Forms.OpenFileDialog;"+ f"$dialog.Title='{title}';"+ "$dialog.CheckFileExists=$true;$dialog.Multiselect=$false;"+ )+ selected = "SelectedPath" if kind == "folder" else "FileName"+ script = (+ "Add-Type -AssemblyName System.Windows.Forms;"+ + dialog +"if($dialog.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK){""[Console]::OutputEncoding=[System.Text.UTF8Encoding]::new();"- "[Console]::Out.Write($dialog.SelectedPath)}"+ f"[Console]::Out.Write($dialog.{selected})}}")return _PickerCommand(argv=(@@ -117,15 +127,15 @@ def _picker_command() -> _PickerCommand | None:argv=(zenity,"--file-selection",- "--directory",- "--title=Select Workspace Directory",+ *(("--directory",) if kind == "folder" else ()),+ f"--title={title}",),cancel_codes=frozenset({1}),)kdialog = shutil.which("kdialog")if kdialog is not None:return _PickerCommand(- argv=(kdialog, "--getexistingdirectory", str(Path.home())),+ argv=(kdialog, "--getexistingdirectory" if kind == "folder" else "--getopenfilename", str(Path.home())),cancel_codes=frozenset({1}),)return None@@ -167,7 +177,15 @@ async def _stop_process(process: asyncio.subprocess.Process) -> None:async def pick_native_folder() -> str | None:"""Open the platform directory picker and return an existing absolute path."""- command = _picker_command()+ return await _pick_native_path(_picker_command(), "directory")+++async def pick_native_file() -> str | None:+ """Choose an existing local file without opening, uploading or copying it."""+ return await _pick_native_path(_picker_command("file"), "file")+++async def _pick_native_path(command: _PickerCommand | None, kind: str) -> str | None:if command is None:raise NativeFolderPickerError("native folder picker is unavailable on this host")@@ -206,6 +224,6 @@ async def pick_native_folder() -> str | None:if not selected:return Nonepath = Path(selected).expanduser()- if not path.is_absolute() or not path.is_dir():- raise NativeFolderPickerError("native folder picker returned an invalid directory")+ if not path.is_absolute() or not (path.is_dir() if kind == "directory" else path.is_file()):+ raise NativeFolderPickerError(f"native path picker returned an invalid {kind}")return str(path)diff --git a/nanobot/webui/remote_discovery.py b/nanobot/webui/remote_discovery.pynew file mode 100644index 000000000..ccb38732b--- /dev/null+++ b/nanobot/webui/remote_discovery.py@@ -0,0 +1,133 @@+"""Locate remote nanobot configurations without reading credentials or using sudo.++Only the selected account's config and named nanobot systemd units are inspected.+An alternate service account is returned as a choice, never silently impersonated.+"""++from __future__ import annotations++from pathlib import Path+from typing import Any++from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator++from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, run_check++_LOCATE = r'''+import getpass, json, os, pathlib, re, shlex, socket, stat, subprocess, sys+try:+ import pwd+except ImportError:+ pwd = None++candidates = []+incomplete = False+current_user = pwd.getpwuid(os.getuid()).pw_name if pwd else getpass.getuser()++def add(path, user="", service=""):+ global incomplete+ if len(candidates) >= 8:+ incomplete = True+ return+ try:+ path = pathlib.Path(path).expanduser()+ if not path.is_absolute():+ return+ exists = stat.S_ISREG(path.stat().st_mode)+ except PermissionError:+ # A declared service config can be offered even when the SSH account+ # cannot stat it. The later explicit choice still needs sudo permission.+ exists = bool(service)+ except (OSError, ValueError):+ return+ user = "" if user == current_user else user+ item = {"config_path": str(path), "runtime_user": user, "service": service}+ if exists and not any(x["config_path"] == item["config_path"] and x["runtime_user"] == user for x in candidates):+ candidates.append(item)++add(sys.argv[1])++def systemctl(*args):+ result = subprocess.run(["systemctl", *args, "--no-pager"],+ capture_output=True, text=True, timeout=2)+ if result.returncode:+ raise OSError("systemctl unavailable")+ return result.stdout++try:+ units = [line.split()[0] for line in systemctl("list-units", "--all", "--plain", "--no-legend", "nanobot*.service").splitlines() if line.split()]+ units = [name for name in units if re.fullmatch(r"nanobot[a-zA-Z0-9_.@-]*\.service", name)]+ incomplete = len(units) > 8+ if units and pwd:+ records = systemctl("show", *units[:8], "--property=Id,User,ExecStart,WorkingDirectory")+ for block in records.strip().split("\n\n"):+ fields = dict(line.split("=", 1) for line in block.splitlines() if "=" in line)+ service = fields.get("Id", "")+ if service not in units[:8]:+ continue+ user = fields.get("User") or "root"+ if not re.fullmatch(r"[a-zA-Z_][a-zA-Z0-9_-]*", user):+ continue+ try:+ home = pathlib.Path(pwd.getpwnam(user).pw_dir)+ tokens = shlex.split(fields.get("ExecStart", ""))+ except (KeyError, ValueError):+ incomplete = True+ continue+ config = None+ for index, token in enumerate(tokens):+ if token.startswith("--config="):+ config = token.split("=", 1)[1]+ break+ if token in {"--config", "-c"} and index + 1 < len(tokens):+ config = tokens[index + 1]+ break+ if config and ("$" in config or "%" in config):+ incomplete = True+ continue+ if config:+ if config.startswith("~/"):+ path = home / config[2:]+ elif pathlib.Path(config).is_absolute():+ path = pathlib.Path(config)+ else:+ path = pathlib.Path(fields.get("WorkingDirectory") or str(home)) / config+ else:+ path = home / ".nanobot/config.json"+ add(path, user, service)+except (OSError, subprocess.TimeoutExpired):+ incomplete = True++print("\n\x1eNANOBOT_REMOTE:" + json.dumps({"hostname": socket.gethostname(), "candidates": candidates, "incomplete": incomplete}))+'''+++class RemoteLocation(BaseModel):+ model_config = ConfigDict(extra="ignore", strict=True)++ config_path: str = Field(min_length=1, max_length=2048)+ runtime_user: str = Field(default="", max_length=64, pattern=r"^([a-zA-Z_][a-zA-Z0-9_-]*)?$")+ service: str = Field(default="", max_length=256, pattern=r"^([a-zA-Z0-9_.@-]+\.service)?$")++ @field_validator("config_path")+ @classmethod+ def safe_path(cls, value: str) -> str:+ return RemoteProfile.safe_path(value)+++class RemoteInspection(BaseModel):+ model_config = ConfigDict(extra="ignore", strict=True)++ hostname: str = Field(min_length=1, max_length=253)+ candidates: list[RemoteLocation] = Field(max_length=8)+ incomplete: bool+++async def inspect(profile: RemoteProfile, known_hosts: Path | None = None) -> dict[str, Any]:+ # Inspection is always performed as the SSH login, even when an old profile+ # has a service account. Discovery must not implicitly escalate privileges.+ result = await run_check(profile.model_copy(update={"runtime_user": ""}), _LOCATE, known_hosts)+ try:+ return RemoteInspection.model_validate(result).model_dump()+ except ValidationError:+ raise RemoteError("probe_failed") from Nonediff --git a/nanobot/webui/remote_instances.py b/nanobot/webui/remote_instances.pyindex 35aeea115..fd1ad34b1 100644--- a/nanobot/webui/remote_instances.py+++ b/nanobot/webui/remote_instances.py@@ -18,13 +18,18 @@ from pydantic import Fieldfrom nanobot.utils.helpers import _write_text_atomic # pyright: ignore[reportPrivateUsage]from nanobot.webui import remote_ssh+from nanobot.webui.remote_proxy import RemoteProxyfrom nanobot.webui.remote_ssh import RemoteError, RemoteProfile, Tunnel+_HEALTH_TIMEOUT_SECONDS = 12+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)+ proxy_origin: bool = False+ pair_id: str = ""@dataclass@@ -34,7 +39,9 @@ class Connection:hostname: strconfig_path: strgateway_id: str+ proxy: RemoteProxyerror: str = ""+ paired: bool = Falseclass RemoteInstances:@@ -43,11 +50,19 @@ class RemoteInstances:def __init__(self, directory: Path, *, local_gateway_id: str = "") -> None:self.path = directory / "remote-instances.json"self.local_gateway_id = local_gateway_id+ # Public identity, not an authentication capability. A new local manager+ # cannot renew a cached iframe's old proxy credentials after restart.+ self._view_session = uuid.uuid4().hexself.connections: dict[str, Connection] = {}+ self._proxies: dict[int, RemoteProxy] = {}self._lock = asyncio.Lock()+ self._picker_lock = asyncio.Lock()self._unverified: dict[str, tuple[str, str, float]] = {}self._unknown_hosts: set[str] = set()self._closed = False+ from nanobot.webui.remote_pairing import PairStore++ self.pairing = PairStore(directory)def _known_hosts(self, key: str) -> Path:return self.path.parent / "remote-hosts" / key@@ -75,39 +90,108 @@ class RemoteInstances:))self.path.chmod(0o600)+ def _remember_origins(self, profiles: dict[str, _SavedProfile], port: int = 0) -> set[int]:+ # Browser storage outlives edits, Forget and gateway restarts. Keep a+ # small append-only port ledger, including pre-ledger saved profiles,+ # so a new target never inherits a retired target's browser origin.+ path = self.path.with_name("remote-origin-ports.json")+ try:+ raw: object = json.loads(path.read_text()) if path.exists() else []+ if not isinstance(raw, list):+ raise ValueError+ ports: set[int] = set()+ for value in cast(list[object], raw):+ if type(value) is not int or not 1 <= value <= 65535:+ raise ValueError+ ports.add(value)+ except (ValueError, TypeError, OSError):+ raise RemoteError("profile_store_invalid") from None+ ports.update(profile.local_port for profile in profiles.values() if profile.local_port)+ if port:+ ports.add(port)+ path.parent.mkdir(parents=True, exist_ok=True)+ _write_text_atomic(path, json.dumps(sorted(ports)))+ path.chmod(0o600)+ return ports+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()- ]}+ profiles: list[dict[str, Any]] = []+ for key, profile in self._read().items():+ connection = self.connections.get(key)+ error = (connection.error or ("" if connection.tunnel.active else "ssh_unreachable")) if connection else "disconnected"+ item = {"id": key, **profile.model_dump(exclude={"local_port", "proxy_origin", "pair_id"}),+ "connected": connection is not None and not error,+ "connection_error": error}+ if connection:+ item["gateway_id"] = connection.gateway_id+ item["view_id"] = self._view_session+ if profile.pair_id:+ item.update(paired=True, revoke_command=+ f"nanobot remote revoke {profile.pair_id} --ssh-user {profile.host.split('@')[0]}")+ expiry = self.pairing.authorization_until(profile.pair_id)+ if expiry is not None:+ item["authorized_until"] = expiry+ profiles.append(item)+ return {"available": True, "machine_name": socket.gethostname(), "profiles": profiles}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:+ # Hold a lifetime lease through every credential-bearing request. Final+ # shutdown cannot release the listeners halfway through a health check.+ try:+ # Includes lock contention and all response reads, not just each+ # socket read. Return the directory before the browser's 20s budget.+ async with asyncio.timeout(_HEALTH_TIMEOUT_SECONDS):+ async with self._lock:+ await asyncio.gather(*(self._check(item) for item in self.connections.values()))+ except TimeoutError:+ pass+ return self.snapshot()++ async def _check(self, connection: Connection) -> None:+ if not connection.tunnel.active:+ connection.error = "ssh_unreachable"+ return+ try:+ async with httpx.AsyncClient(timeout=20, 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 in {401, 403}:+ connection.error = "remote_auth_failed"+ elif response.status_code != 200:+ connection.error = "remote_unreachable"+ else:+ raw_identity = response.json()+ identity = cast(dict[str, Any], raw_identity) if isinstance(raw_identity, dict) else {}+ if (type(identity.get("protocolVersion")) is not int+ or identity.get("protocolVersion") != 1 or not isinstance(identity.get("gatewayId"), str)):+ connection.error = "incompatible_gateway"+ elif identity["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()+ except (httpx.HTTPError, ValueError, AttributeError):+ connection.error = connection.tunnel.error or "remote_unreachable"+ if connection.paired and connection.error == "ssh_auth_failed":+ connection.error = "pair_authorization_rejected"+ except asyncio.CancelledError:+ connection.error = "remote_unreachable"+ raiseasync def action(self, action: str, payload: dict[str, Any]) -> dict[str, Any]:+ if action == "pick_file":+ from nanobot.webui.native_folder_picker import NativeFolderPickerError, pick_native_file++ if self._closed or self._picker_lock.locked():+ raise RemoteError("file_picker_unavailable")+ # The route is authenticated and loopback-only. No caller-provided+ # command, file content or initial directory enters the OS dialog.+ async with self._picker_lock:+ try:+ return {"path": await pick_native_file()}+ except NativeFolderPickerError:+ raise RemoteError("file_picker_unavailable") from Noneif action == "discover":from nanobot.webui.ssh_config import discover_hosts@@ -121,31 +205,114 @@ class RemoteInstances:raise RemoteError("local_io_error")profiles = self._read()key = str(payload.get("id", ""))+ if action == "pair_start":+ return_origin = payload.get("return_origin", "")+ if not isinstance(return_origin, str):+ raise RemoteError("pair_invalid")+ return self.pairing.start(return_origin)+ if action == "pair_cancel":+ self.pairing.cancel(key)+ return {"cancelled": True}+ if action in {"pair_preview", "pair_finish"}:+ code = payload.get("code", "")+ if not isinstance(code, str):+ raise RemoteError("pair_invalid")+ if action == "pair_preview":+ return self.pairing.preview(key, code)+ if len(profiles) >= 20 and key not in profiles:+ raise RemoteError("profile_limit")+ # Completion is idempotent. No browser-provided host/path/key is+ # trusted as a substitute for the encrypted server receipt.+ if key in profiles:+ return {"id": key, **self.snapshot()}+ receipt = self.pairing.finish(key, code)+ profile = self.pairing.profile(receipt)+ known = self._known_hosts(key)+ known.parent.mkdir(parents=True, exist_ok=True)+ _write_text_atomic(known, "nanobot-remote " + receipt.host_key + "\n")+ known.chmod(0o600)+ profiles[key] = _SavedProfile(**profile.model_dump(), pair_id=key)+ self._write(profiles)+ return {"id": key, **self.snapshot()}if action == "save":profile = RemoteProfile.model_validate(payload.get("profile"))if key and key not in profiles:raise RemoteError("profile_not_found")+ if key and profiles[key].pair_id:+ raise RemoteError("pair_managed")+ if key and profiles[key].model_dump(include=set(RemoteProfile.model_fields)) == profile.model_dump():+ # Retrying a slow browser load must not count as editing a+ # live SSH connection. Real changes still require disconnect.+ return {"id": key, **self.snapshot()}+ if not key:+ destination = profile.model_dump(exclude={"name"})+ for saved_key, saved in profiles.items():+ if saved.model_dump(include=set(destination)) == destination:+ # Reopening Add after a failed attempt should reuse+ # its entry, without renaming it or closing live views.+ return {"id": saved_key, **self.snapshot()}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")+ connection = self.connections.get(key)+ if connection:+ if connection.tunnel.active and not connection.error:+ raise RemoteError("disconnect_before_edit")+ # A fresh tab offers Edit for an offline profile. Release its+ # failed tunnel here instead of demanding a hidden Disconnect.+ await connection.proxy.pause()+ del self.connections[key]target_changed = key in profiles and any(getattr(profiles[key], field) != getattr(profile, field)for field in ("host", "port", "ssh_config"))+ instance_changed = target_changed or (key in profiles and any(+ getattr(profiles[key], field) != getattr(profile, field)+ for field in ("config_path", "runtime_user", "identity_file")+ ))+ if instance_changed:+ self._remember_origins(profiles)+ local_port = profiles[key].local_port if key in profiles and not instance_changed else 0+ proxy_origin = bool(local_port and profiles[key].proxy_origin)+ profiles[key] = _SavedProfile(**profile.model_dump(), local_port=local_port,+ proxy_origin=proxy_origin)+ self._write(profiles)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":+ if action == "pair_route":+ profile = profiles[key]+ if not profile.pair_id:+ raise RemoteError("pair_invalid")+ existing = self.connections.get(key)+ if existing and existing.tunnel.active and not existing.error:+ raise RemoteError("disconnect_before_edit")+ route_id = str(payload.get("route_id", ""))+ if route_id:+ source = profiles.get(route_id)+ if source is None or source.pair_id:+ raise RemoteError("profile_not_found")+ config = await remote_ssh.pairing_route(source, profile.host.split("@")[-1])+ path = self.pairing.path(profile.pair_id) / "ssh_route"+ _write_text_atomic(path, config)+ path.chmod(0o600)+ profile.ssh_config = str(path)+ else:+ profile.ssh_config = ""+ self._write(profiles)+ return self.snapshot()+ if action in {"connect", "inspect"}:try:+ if action == "inspect":+ if profiles[key].pair_id:+ raise RemoteError("pair_managed")+ from nanobot.webui.remote_discovery import inspect++ return await inspect(profiles[key], self._known_hosts(key))return await self._connect(key, profiles[key])except RemoteError as exc:if str(exc) == "host_key_unknown":@@ -175,8 +342,11 @@ class RemoteInstances:if action in {"disconnect", "remove"}:connection = self.connections.pop(key, None)if connection:- await connection.tunnel.close()+ await connection.proxy.pause()if action == "remove":+ self._remember_origins(profiles)+ if profiles[key].pair_id:+ self.pairing.forget(profiles[key].pair_id)del profiles[key]self._write(profiles)self._known_hosts(key).unlink(missing_ok=True)@@ -188,25 +358,41 @@ class RemoteInstances: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}+ "url": f"{connection.proxy.origin}/#/?bootstrapSecret={quote(connection.proxy.secret, safe='')}",+ "gateway_id": connection.gateway_id, "view_id": self._view_session}async def _connect(self, key: str, profile: _SavedProfile) -> dict[str, Any]:existing = self.connections.get(key)if existing:- await self.health()+ await self._check(existing)if not existing.error:return self._launch(key, profile, existing)- await existing.tunnel.close()+ await existing.proxy.pause()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)+ transport: RemoteProfile = profile+ if profile.pair_id:+ data = self.pairing.connection(profile.pair_id)+ transport = remote_ssh.PairedSSHProfile(**profile.model_dump(include=set(RemoteProfile.model_fields)))+ else:+ data = await remote_ssh.probe(profile, known_hosts)+ used_ports = self._remember_origins(self._read())+ # Retire browser origins from the earlier transparent tunnel. Those+ # origins may still contain remote secrets in old tabs/localStorage.+ local_port = profile.local_port if profile.proxy_origin else 0+ proxy = self._proxies.get(local_port)+ if proxy is not None:+ tunnel = proxy.tunnel+ tunnel.resume(transport, data["port"], known_hosts)+ else:+ tunnel = await remote_ssh.open_tunnel(+ transport, data["port"], known_hosts, excluded_ports=used_ports,+ )base = f"http://127.0.0.1:{tunnel.port}"try:- async with httpx.AsyncClient(timeout=8, trust_env=False, follow_redirects=False) as client:+ async with httpx.AsyncClient(timeout=20, trust_env=False, follow_redirects=False) as client:response = await client.get(f"{base}/webui/terminal", headers={"X-Nanobot-Auth": data["secret"]},)@@ -218,28 +404,58 @@ class RemoteInstances:if not isinstance(raw_identity, dict):raise RemoteError("incompatible_gateway")identity = cast(dict[str, Any], raw_identity)- if (identity.get("protocolVersion") != 1+ if (type(identity.get("protocolVersion")) is not int or identity.get("protocolVersion") != 1or not isinstance(identity.get("gatewayId"), str)):raise RemoteError("incompatible_gateway")if identity["gatewayId"] == self.local_gateway_id:raise RemoteError("same_instance")+ # SSH aliases identify routes, not nanobot instances. Don't open+ # two independent browser views of the same live gateway.+ if any(item.gateway_id == identity["gatewayId"]+ for item in self.connections.values()):+ raise RemoteError("duplicate_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")+ issue_path = data.get("token_issue_path", "")+ if not isinstance(issue_path, str):+ raise RemoteError("incompatible_gateway")+ if proxy is None:+ proxy = await RemoteProxy.open(+ tunnel, data["secret"], identity["gatewayId"], issue_path,+ local_port=local_port, excluded_ports=used_ports,+ )+ else:+ proxy.resume(data["secret"], identity["gatewayId"], issue_path)connection = Connection(tunnel, data["secret"], str(data.get("hostname", profile.host)),- str(data.get("config_path", profile.config_path)), identity["gatewayId"],+ str(data.get("config_path", profile.config_path)), identity["gatewayId"], proxy,+ paired=bool(profile.pair_id),)profiles = self._read()- profiles[key].local_port = tunnel.port+ self._remember_origins(profiles, proxy.port)+ profiles[key].local_port = proxy.port+ profiles[key].proxy_origin = Trueself._write(profiles)+ self._proxies[proxy.port] = proxyself.connections[key] = connectionreturn self._launch(key, profile, connection)except BaseException as exc:- await tunnel.close()+ if proxy is not None and proxy.port in self._proxies:+ await proxy.pause()+ else:+ # No launch URL has been returned for this new origin. All+ # internal HTTP requests have finished; retaining it would leak+ # a listener on every failed attempt with local_port still zero.+ if proxy is not None:+ await proxy.close()+ else:+ await tunnel.close()if isinstance(exc, httpx.HTTPError):- raise RemoteError("remote_unreachable") from None+ if profile.pair_id and tunnel.error == "ssh_auth_failed":+ raise RemoteError("pair_authorization_rejected") from None+ raise RemoteError(tunnel.error or "remote_unreachable") from Noneif isinstance(exc, ValueError):raise RemoteError("incompatible_gateway") from Noneraise@@ -247,5 +463,6 @@ class RemoteInstances:async def close(self) -> None:self._closed = Trueasync with self._lock:- connections, self.connections = self.connections, {}- await asyncio.gather(*(item.tunnel.close() for item in connections.values()))+ proxies, self._proxies = self._proxies, {}+ self.connections.clear()+ await asyncio.gather(*(proxy.close() for proxy in proxies.values()))diff --git a/nanobot/webui/remote_pair_server.py b/nanobot/webui/remote_pair_server.pynew file mode 100644index 000000000..ec8193b1f--- /dev/null+++ b/nanobot/webui/remote_pair_server.py@@ -0,0 +1,213 @@+"""Explicit server-side authorization for relay-free remote WebUI pairing.++Only an already-authorized server operator runs this module. No daemon, sudoers+rule, listener or SSH policy is installed. The dedicated key executes one fixed+stdio bridge, with all OpenSSH forwarding and interactive features disabled.+"""++from __future__ import annotations++import datetime+import fcntl+import json+import os+import shlex+import socket+import stat+import subprocess+import sys+import tempfile+from pathlib import Path+from typing import Any++from nanobot.webui.remote_pairing import PairReceipt, PairRequest, private_write, public_key, seal+from nanobot.webui.remote_ssh import RemoteError++# No dynamic command, destination or environment input is accepted by the bridge.+# SSH_ORIGINAL_COMMAND is deliberately ignored. Each invocation is one TCP stream.+_BRIDGE = '''import os, socket, threading+s = socket.create_connection(("127.0.0.1", PORT), timeout=10)+s.settimeout(None)+def send():+ try:+ while True:+ data = os.read(0, 65536)+ if not data:+ break+ s.sendall(data)+ s.shutdown(socket.SHUT_WR)+ except OSError:+ s.close()+threading.Thread(target=send, daemon=True).start()+try:+ while True:+ data = s.recv(65536)+ if not data:+ break+ while data:+ data = data[os.write(1, data):]+finally:+ s.close()+'''+++def metadata(config: Path) -> dict[str, Any]:+ """Read only the WebUI credential out of the operator-selected config."""+ try:+ raw = json.loads(config.read_text())+ ws = raw.get("channels", {}).get("websocket", {})+ secret = ws.get("tokenIssueSecret") or ws.get("token_issue_secret") or ws.get("token")+ if not ws.get("enabled") or not isinstance(secret, str) or not secret.strip() or "${" in secret:+ raise RemoteError("webui_auth_required")+ if ws.get("publicWsUrl") or ws.get("public_ws_url") or ws.get("trustedProxyAuth") or ws.get("trusted_proxy_auth"):+ raise RemoteError("incompatible_gateway")+ port = ws.get("port", 8765)+ if type(port) is not int or not 1 <= port <= 65535:+ raise ValueError+ return {"port": port, "secret": secret, "hostname": socket.gethostname(),+ "config_path": str(config.resolve()),+ "token_issue_path": ws.get("tokenIssuePath") or ws.get("token_issue_path") or ""}+ except PermissionError:+ raise RemoteError("config_permission") from None+ except (OSError, ValueError, TypeError, AttributeError):+ raise RemoteError("config_invalid") from None+++def _directory(path: Path) -> None:+ if path.is_symlink():+ raise RemoteError("pair_ssh_layout")+ path.mkdir(mode=0o700, exist_ok=True)+ info = path.stat()+ if info.st_uid != os.getuid() or info.st_mode & 0o022:+ raise RemoteError("pair_ssh_layout")+++def write_authorization(home: Path, request: PairRequest, port: int, until: int) -> None:+ """Runs as the SSH account, never with root privileges over another home."""+ request.check_expiry()+ ssh = home / ".ssh"+ _directory(ssh)+ root = ssh / "nanobot-remote"+ _directory(root)+ target = root / request.id+ # Only our lock file; do not change permissions/content of unrelated keys.+ lock = os.open(root / "lock", os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)+ with os.fdopen(lock, "r+") as guard:+ fcntl.flock(guard, fcntl.LOCK_EX)+ if target.exists():+ raise RemoteError("pair_used")+ target.mkdir(mode=0o700)+ try:+ bridge = target / "bridge.py"+ private_write(bridge, _BRIDGE.replace("PORT", str(port)).encode())+ command = shlex.join(["/usr/bin/python3", "-I", "-S", str(bridge)]).replace("\\", "\\\\").replace('"', '\\"')+ expiry = datetime.datetime.fromtimestamp(until, datetime.UTC).strftime("%Y%m%d%H%M%SZ")+ line = f'restrict,expiry-time="{expiry}",command="{command}" {request.ssh_key} nanobot-remote:{request.id}\n'+ private_write(target / "authorization", line.encode())+ _update_keys(ssh / "authorized_keys", add=line)+ except BaseException:+ # Never remove an existing directory or unrelated key on rollback.+ for name in ("bridge.py", "authorization"):+ (target / name).unlink(missing_ok=True)+ target.rmdir()+ raise+++def _update_keys(path: Path, *, add: str = "", remove: str = "") -> None:+ fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)+ with os.fdopen(fd, "r+") as handle:+ info = os.fstat(handle.fileno())+ if not stat.S_ISREG(info.st_mode) or info.st_uid != os.getuid() or info.st_nlink != 1 or info.st_mode & 0o022:+ raise RemoteError("pair_ssh_layout")+ fcntl.flock(handle, fcntl.LOCK_EX)+ original = handle.read(1024 * 1024 + 1)+ if len(original) > 1024 * 1024:+ raise RemoteError("pair_ssh_layout")+ if add:+ handle.seek(0, 2)+ handle.write(("\n" if original and not original.endswith("\n") else "") + add)+ else:+ # Exact managed line, not a substring/comment match.+ replacement = "".join(line for line in original.splitlines(keepends=True) if line != remove)+ if replacement == original:+ return+ temporary_fd, temporary_name = tempfile.mkstemp(prefix=".nanobot-revoke-", dir=path.parent)+ try:+ with os.fdopen(temporary_fd, "w") as output:+ output.write(replacement)+ output.flush()+ os.fsync(output.fileno())+ os.fchmod(output.fileno(), stat.S_IMODE(info.st_mode))+ os.replace(temporary_name, path)+ finally:+ Path(temporary_name).unlink(missing_ok=True)+ handle.flush()+ os.fsync(handle.fileno())+++def remove_authorization(home: Path, key: str) -> None:+ from nanobot.webui.remote_pairing import PairStore++ # Validate before joining any path, even for a manually typed revoke command.+ PairStore(home).path(key)+ root = home / ".ssh" / "nanobot-remote"+ _directory(home / ".ssh")+ _directory(root)+ target = root / key+ if target.is_symlink() or not target.is_dir():+ raise RemoteError("pair_invalid")+ lock = os.open(root / "lock", os.O_RDWR | os.O_NOFOLLOW)+ with os.fdopen(lock, "r+") as guard:+ fcntl.flock(guard, fcntl.LOCK_EX)+ line = (target / "authorization").read_text()+ if not line.endswith(f" nanobot-remote:{key}\n") or "\n" in line[:-1]:+ raise RemoteError("pair_invalid")+ _update_keys(home / ".ssh/authorized_keys", remove=line)+ # Keep the non-secret receipt/bridge for an auditable, retryable revoke.+++def as_account(user: str, operation: str, data: dict[str, Any]) -> None:+ import pwd++ account = pwd.getpwnam(user)+ if account.pw_uid == 0 or account.pw_shell.endswith(("/nologin", "/false")):+ raise RemoteError("pair_login_user")+ if os.getuid() not in (0, account.pw_uid):+ raise RemoteError("config_permission")+ child = dict(data, home=account.pw_dir, operation=operation)+ # Drop all supplementary groups *before* any write in a user-owned home.+ options: dict[str, Any] = {}+ if os.getuid() == 0:+ options = {"user": account.pw_uid, "group": account.pw_gid, "extra_groups": []}+ result = subprocess.run(+ [sys.executable, "-m", "nanobot.webui.remote_pair_server"],+ input=json.dumps(child), text=True, capture_output=True, timeout=20, **options,+ )+ if result.returncode:+ code = result.stdout.strip()+ raise RemoteError(code if code in {"pair_used", "pair_expired", "pair_ssh_layout", "pair_invalid"} else "pair_install_failed")+++def authorize(request: PairRequest, *, host: str, user: str, ssh_port: int,+ config: Path, host_key: str, until: int) -> str:+ request.check_expiry()+ receipt = PairReceipt(id=request.id, ssh_key=request.ssh_key, host=host, user=user,+ ssh_port=ssh_port, host_key=public_key(host_key), authorized_until=until,+ **metadata(config))+ encrypted = seal(request, receipt) # Fail crypto/validation before authorizing anything.+ as_account(user, "install", {"request": request.model_dump(), "port": receipt.port, "until": until})+ return encrypted+++if __name__ == "__main__":+ try:+ data = json.loads(sys.stdin.read(32768))+ if data["operation"] == "install":+ write_authorization(Path(data["home"]), PairRequest.model_validate(data["request"]), data["port"], data["until"])+ elif data["operation"] == "revoke":+ remove_authorization(Path(data["home"]), data["id"])+ else:+ raise RemoteError("pair_invalid")+ except Exception as exc:+ print(str(exc) if isinstance(exc, RemoteError) else "pair_install_failed")+ sys.exit(1)diff --git a/nanobot/webui/remote_pairing.py b/nanobot/webui/remote_pairing.pynew file mode 100644index 000000000..87888248c--- /dev/null+++ b/nanobot/webui/remote_pairing.py@@ -0,0 +1,322 @@+"""Copy/paste pairing protocol. Private material never enters the WebUI response.++The request is public. A receipt is encrypted for the requesting local instance;+its provenance is the user's trusted server terminal, not a public relay. SSH's+host key is pinned from that receipt before any credential-bearing connection.+"""++from __future__ import annotations++import base64+import hashlib+import json+import os+import re+import secrets+import socket+import time+import uuid+from pathlib import Path+from typing import Any, cast++from cryptography.exceptions import InvalidTag, UnsupportedAlgorithm+from cryptography.hazmat.primitives import hashes, serialization+from cryptography.hazmat.primitives.asymmetric import ed25519, x25519+from cryptography.hazmat.primitives.ciphers.aead import AESGCM+from cryptography.hazmat.primitives.kdf.hkdf import HKDF+from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator++from nanobot.webui.remote_ssh import RemoteError, RemoteProfile++_TTL = 600+_CONTEXT = b"nanobot-remote-pair-v1"+++def local_return_origin(value: str) -> str:+ """Only the local top-level WebUI can receive a pairing link. No redirects."""+ if value == "":+ return value+ match = re.fullmatch(r"http://(127\.0\.0\.1|localhost|\[::1\])(?::([0-9]{1,5}))?", value)+ if not match or (match[2] is not None and not 1 <= int(match[2]) <= 65535):+ raise ValueError("local return address required")+ return value+++def return_link(request: PairRequest, code: str) -> str:+ # Fragment data is never sent in the HTTP request or Referer. The frontend+ # scrubs it before authentication and still requires a confirmation.+ if not request.return_origin:+ return ""+ if not re.fullmatch(r"nbpc1\.[A-Za-z0-9_-]{1,32762}", code):+ raise RemoteError("pair_invalid")+ return f"{local_return_origin(request.return_origin)}/#/remote?pairing={code}"+++def encode(value: bytes) -> str:+ return base64.urlsafe_b64encode(value).decode().rstrip("=")+++def decode(value: str) -> bytes:+ return base64.b64decode(value + "=" * (-len(value) % 4), altchars=b"-_", validate=True)+++def pack(prefix: str, data: dict[str, Any]) -> str:+ return prefix + encode(json.dumps(data, separators=(",", ":")).encode())+++def unpack(prefix: str, value: str) -> dict[str, Any]:+ if len(value) > 32768:+ raise RemoteError("pair_invalid")+ value = "".join(value.split())+ try:+ if not value.startswith(prefix):+ raise ValueError+ raw = json.loads(decode(value[len(prefix):]))+ if not isinstance(raw, dict):+ raise ValueError+ return cast(dict[str, Any], raw)+ except (ValueError, TypeError, UnicodeError):+ raise RemoteError("pair_invalid") from None+++def public_key(value: str) -> str:+ """Accept exactly one Ed25519 key, without options, comments or newlines."""+ try:+ key = serialization.load_ssh_public_key(value.encode())+ except UnsupportedAlgorithm:+ raise ValueError("Ed25519 required") from None+ if not isinstance(key, ed25519.Ed25519PublicKey):+ raise ValueError("Ed25519 required")+ canonical = key.public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH).decode()+ if canonical != value:+ raise ValueError("non-canonical key")+ return value+++def fingerprint(key: str) -> str:+ return "SHA256:" + base64.b64encode(hashlib.sha256(base64.b64decode(key.split()[1])).digest()).decode().rstrip("=")+++class PairRequest(BaseModel):+ model_config = ConfigDict(extra="forbid", strict=True)+ id: str+ expires: int+ label: str = Field(min_length=1, max_length=64, pattern=r"^[\w .@-]+$")+ ssh_key: str = Field(max_length=256)+ exchange_key: str = Field(min_length=43, max_length=43)+ return_origin: str = Field(default="", max_length=64)++ @field_validator("return_origin")+ @classmethod+ def valid_return_origin(cls, value: str) -> str:+ return local_return_origin(value)++ @field_validator("id")+ @classmethod+ def valid_id(cls, value: str) -> str:+ if str(uuid.UUID(value)) != value:+ raise ValueError("invalid id")+ return value++ @field_validator("ssh_key")+ @classmethod+ def valid_key(cls, value: str) -> str:+ return public_key(value)++ @field_validator("exchange_key")+ @classmethod+ def valid_exchange(cls, value: str) -> str:+ x25519.X25519PublicKey.from_public_bytes(decode(value))+ return value++ def check_expiry(self) -> None:+ if not time.time() < self.expires <= time.time() + _TTL + 60:+ raise RemoteError("pair_expired")+++def read_request(value: str) -> PairRequest:+ try:+ request = PairRequest.model_validate(unpack("nbpr1.", value))+ request.check_expiry()+ return request+ except (ValidationError, ValueError):+ raise RemoteError("pair_invalid") from None+++class PairReceipt(BaseModel):+ model_config = ConfigDict(extra="forbid", strict=True)+ id: str+ ssh_key: str+ host: str = Field(min_length=1, max_length=253, pattern=r"^[a-zA-Z0-9][a-zA-Z0-9.:-]*$")+ user: str = Field(min_length=1, max_length=64, pattern=r"^[a-zA-Z_][a-zA-Z0-9_-]*$")+ ssh_port: int = Field(ge=1, le=65535)+ host_key: str+ hostname: str = Field(min_length=1, max_length=253)+ config_path: str = Field(min_length=1, max_length=2048)+ port: int = Field(ge=1, le=65535)+ secret: str = Field(min_length=1, max_length=4096, repr=False)+ token_issue_path: str = Field(default="", max_length=2048)+ authorized_until: int++ @field_validator("host_key", "ssh_key")+ @classmethod+ def valid_key(cls, value: str) -> str:+ return public_key(value)++ def preview(self) -> dict[str, Any]:+ return {"id": self.id, "host": f"{self.user}@{self.host}", "port": self.ssh_port,+ "hostname": self.hostname, "fingerprint": fingerprint(self.host_key),+ "authorized_until": self.authorized_until,+ "revoke_command": f"nanobot remote revoke {self.id} --ssh-user {self.user}"}+++def _derive(shared: bytes, request_id: str) -> bytes:+ return HKDF(algorithm=hashes.SHA256(), length=32, salt=request_id.encode(), info=_CONTEXT).derive(shared)+++def seal(request: PairRequest, receipt: PairReceipt) -> str:+ private = x25519.X25519PrivateKey.generate()+ peer = x25519.X25519PublicKey.from_public_bytes(decode(request.exchange_key))+ nonce = secrets.token_bytes(12)+ encrypted = AESGCM(_derive(private.exchange(peer), request.id)).encrypt(+ nonce, receipt.model_dump_json().encode(), _CONTEXT + request.id.encode(),+ )+ return pack("nbpc1.", {"id": request.id, "key": encode(private.public_key().public_bytes_raw()),+ "nonce": encode(nonce), "data": encode(encrypted)})+++def private_write(path: Path, content: bytes) -> None:+ # Callers own the private parent directory. Never overwrite or follow links.+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ with os.fdopen(fd, "wb") as handle:+ handle.write(content)+ handle.flush()+ os.fsync(handle.fileno())+++class PairStore:+ def __init__(self, directory: Path) -> None:+ self.root = directory / "remote-pairing"++ def path(self, key: str) -> Path:+ try:+ if str(uuid.UUID(key)) != key:+ raise ValueError+ except (ValueError, AttributeError):+ raise RemoteError("pair_invalid") from None+ return self.root / key++ def start(self, return_origin: str = "") -> dict[str, Any]:+ try:+ return_origin = local_return_origin(return_origin)+ except (ValueError, TypeError):+ raise RemoteError("pair_invalid") from None+ self.root.mkdir(mode=0o700, parents=True, exist_ok=True)+ if self.root.is_symlink():+ raise RemoteError("local_io_error")+ self.root.chmod(0o700)+ # Bound abandoned requests without deleting completed device identities.+ pending = 0+ for path in self.root.iterdir():+ if path.is_dir() and not (path / "receipt").exists():+ if path.stat().st_mtime < time.time() - _TTL:+ self.cancel(path.name)+ else:+ pending += 1+ if pending >= 8:+ raise RemoteError("pair_limit")+ key = str(uuid.uuid4())+ path = self.path(key)+ path.mkdir(mode=0o700)+ ssh = ed25519.Ed25519PrivateKey.generate()+ exchange = x25519.X25519PrivateKey.generate()+ request = PairRequest(id=key, expires=int(time.time()) + _TTL,+ label="".join(c for c in socket.gethostname() if c.isalnum() or c in ".-_")[:64] or "Computer",+ ssh_key=ssh.public_key().public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH).decode(),+ exchange_key=encode(exchange.public_key().public_bytes_raw()),+ return_origin=return_origin)+ private_write(path / "identity", ssh.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.OpenSSH, serialization.NoEncryption()))+ private_write(path / "exchange", exchange.private_bytes_raw())+ private_write(path / "request", request.model_dump_json().encode())+ return {"id": key, "expires": request.expires,+ "command": "nanobot remote pair " + pack("nbpr1.", request.model_dump(exclude_defaults=True))}++ def _decrypt(self, key: str, code: str, *, pending: bool, require_active: bool = True) -> PairReceipt:+ path = self.path(key)+ try:+ request = PairRequest.model_validate_json((path / "request").read_bytes())+ if pending:+ request.check_expiry()+ envelope = unpack("nbpc1.", code)+ if envelope.get("id") != key:+ raise ValueError+ private = x25519.X25519PrivateKey.from_private_bytes((path / "exchange").read_bytes())+ peer = x25519.X25519PublicKey.from_public_bytes(decode(envelope["key"]))+ clear = AESGCM(_derive(private.exchange(peer), key)).decrypt(+ decode(envelope["nonce"]), decode(envelope["data"]), _CONTEXT + key.encode(),+ )+ receipt = PairReceipt.model_validate_json(clear)+ if receipt.id != key or receipt.ssh_key != request.ssh_key:+ raise ValueError+ if require_active and receipt.authorized_until <= time.time():+ raise RemoteError("pair_authorization_expired")+ return receipt+ except (OSError, ValueError, TypeError, KeyError, InvalidTag):+ raise RemoteError("pair_invalid") from None++ def preview(self, key: str, code: str) -> dict[str, Any]:+ return self._decrypt(key, code, pending=True).preview()++ def finish(self, key: str, code: str) -> PairReceipt:+ receipt = self._decrypt(key, code, pending=True)+ path = self.path(key) / "receipt"+ if path.exists():+ if path.read_text() != code:+ raise RemoteError("pair_used")+ else:+ private_write(path, code.encode())+ return receipt++ def connection(self, key: str) -> dict[str, Any]:+ try:+ code = (self.path(key) / "receipt").read_text()+ except OSError:+ raise RemoteError("pair_invalid") from None+ return self._decrypt(key, code, pending=False).model_dump()++ def authorization_until(self, key: str) -> int | None:+ """Expose only the expiry for display, including already-expired grants.++ Connecting still goes through connection(), which rejects expired grants.+ A missing/unreadable receipt must not hide every other saved server.+ """+ try:+ code = (self.path(key) / "receipt").read_text()+ return self._decrypt(key, code, pending=False, require_active=False).authorized_until+ except (OSError, RemoteError):+ return None++ def cancel(self, key: str) -> None:+ path = self.path(key)+ if path.is_symlink() or (path / "receipt").exists():+ return+ for name in ("identity", "exchange", "request"):+ (path / name).unlink(missing_ok=True)+ if path.exists():+ path.rmdir()++ def forget(self, key: str) -> None:+ """Destroy only this managed local identity; server revocation is separate."""+ path = self.path(key)+ if path.is_symlink():+ raise RemoteError("local_io_error")+ for name in ("identity", "exchange", "request", "receipt", "ssh_route"):+ (path / name).unlink(missing_ok=True)+ if path.exists():+ path.rmdir()++ def profile(self, receipt: PairReceipt, ssh_config: str = "") -> RemoteProfile:+ return RemoteProfile(name=receipt.hostname[:64], host=f"{receipt.user}@{receipt.host}",+ port=receipt.ssh_port, config_path=receipt.config_path,+ identity_file=str(self.path(receipt.id) / "identity"),+ ssh_config=ssh_config)diff --git a/nanobot/webui/remote_proxy.py b/nanobot/webui/remote_proxy.pynew file mode 100644index 000000000..fec3cc997--- /dev/null+++ b/nanobot/webui/remote_proxy.py@@ -0,0 +1,368 @@+"""A browser origin with local capabilities, not reusable remote credentials.++The private SSH listener is never published. This proxy drains its requests+before releasing that listener; a process reclaiming the public browser port+after shutdown can receive only capabilities from an already-dead proxy.+"""++from __future__ import annotations++import asyncio+import contextlib+import json+import math+import re+import secrets+import socket+import time+from collections import OrderedDict+from dataclasses import dataclass+from typing import Any, cast++import httpx+from aiohttp import WSMsgType, web+from cryptography.fernet import Fernet, InvalidToken+from websockets.asyncio.client import connect+from websockets.exceptions import WebSocketException+from websockets.typing import Origin+from yarl import URL++from nanobot.webui.remote_ssh import Tunnel, _listen # pyright: ignore[reportPrivateUsage]++_MAX_BYTES = 64 * 1024 * 1024+_MAX_CAPABILITIES = 10000+_MEDIA_PATH = r"/api/media/[A-Za-z0-9_-]{22}/[A-Za-z0-9_-]+"+# Consume absolute URLs unchanged before matching gateway-relative media paths.+# An external site's similarly named route is not this proxy's capability.+_MEDIA = re.compile(r"(?:[A-Za-z][A-Za-z0-9+.-]*:)?//[^\s<>\"'`()]+|"+ rf"(?<![A-Za-z0-9_/%:.~-])(?P<media>{_MEDIA_PATH})")+_REQUEST_HEADERS = {"accept", "accept-language", "content-type", "range", "if-range"}+_RESPONSE_HEADERS = {+ "content-type", "content-range", "accept-ranges", "content-disposition",+ "content-security-policy", "x-content-type-options", "last-modified",+}+++@dataclass(frozen=True)+class _Grant:+ remote: str+ expires: float+ path: str = ""+++class RemoteProxy:+ """Owns the public listener, local credentials and a private SSH transport."""++ def __init__(self, tunnel: Tunnel, secret: str, gateway_id: str, issue_path: str) -> None:+ self.tunnel = tunnel+ self.secret = secrets.token_urlsafe(32)+ self.port = 0+ self._remote_secret = secret+ self._gateway_id = gateway_id+ self._issue_path = issue_path.rstrip("/") or ""+ # Reload caches are scoped to WS pathname. A fresh process must not+ # reuse cached transcripts containing a previous proxy's media grants.+ self._ws_path = "/remote-session/" + secrets.token_urlsafe(18)+ self._api: dict[str, _Grant] = {}+ self._ws: dict[str, _Grant] = {}+ self._media_cipher = Fernet(Fernet.generate_key())+ self._media_cache: OrderedDict[str, str] = OrderedDict()+ self._tasks: set[asyncio.Task[Any]] = set()+ self._bootstrap_lock = asyncio.Lock()+ self._enabled = True+ self._runner: web.AppRunner | None = None++ @classmethod+ async def open(+ cls, tunnel: Tunnel, secret: str, gateway_id: str, issue_path: str = "",+ *, local_port: int = 0, excluded_ports: set[int] | None = None,+ ) -> RemoteProxy:+ self = cls(tunnel, secret, gateway_id, issue_path)+ listener = _listen(local_port, excluded_ports or set())+ self.port = int(listener.getsockname()[1])+ app = web.Application(client_max_size=_MAX_BYTES)+ app.router.add_route("*", "/{path:.*}", self._handle)+ self._runner = web.AppRunner(app, access_log=None, handler_cancellation=True)+ try:+ await self._runner.setup()+ await web.SockSite(self._runner, listener).start()+ return self+ except BaseException:+ listener.close()+ await self._runner.cleanup()+ raise++ @property+ def active(self) -> bool:+ return self._enabled and self.tunnel.active++ @property+ def origin(self) -> str:+ return f"http://127.0.0.1:{self.port}"++ def resume(self, secret: str, gateway_id: str, issue_path: str = "") -> None:+ if gateway_id != self._gateway_id:+ self._ws_path = "/remote-session/" + secrets.token_urlsafe(18)+ self._api.clear()+ self._ws.clear()+ self._media_cipher = Fernet(Fernet.generate_key())+ self._media_cache.clear()+ self._remote_secret = secret+ self._gateway_id = gateway_id+ self._issue_path = issue_path.rstrip("/") or ""+ self._enabled = True++ async def pause(self) -> None:+ self._enabled = False+ tasks = list(self._tasks)+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ self._api.clear()+ self._ws.clear()+ await self.tunnel.pause()++ async def close(self) -> None:+ await self.pause()+ if self._runner is not None:+ await self._runner.cleanup()+ self._runner = None+ self._remote_secret = ""+ self._media_cipher = Fernet(Fernet.generate_key())+ self._media_cache.clear()+ await self.tunnel.close()++ def _credential(self, request: web.Request, *, bootstrap: bool = False) -> str:+ # Decode query names once. Reject duplicates and mixed aliases rather+ # than allowing the client and upstream to disagree about precedence.+ auth = request.headers.getall("Authorization", [])+ issue = request.headers.getall("X-Nanobot-Auth", [])+ query = request.rel_url.query.getall("token", [])+ if len(auth) + len(issue) + len(query) > 1:+ raise web.HTTPUnauthorized()+ if auth:+ scheme, _, value = auth[0].partition(" ")+ if scheme.lower() != "bearer" or not value:+ raise web.HTTPUnauthorized()+ return value+ if bootstrap and issue:+ return issue[0]+ if not bootstrap and query:+ return query[0]+ return ""++ def _grant(self, token: str, grants: dict[str, _Grant], *, consume: bool = False) -> _Grant:+ grant = grants.pop(token, None) if consume else grants.get(token)+ if grant is None or grant.expires <= time.monotonic():+ raise web.HTTPUnauthorized()+ return grant++ async def _handle(self, request: web.Request) -> web.StreamResponse:+ if (request.headers.getall("Host", []) != [f"127.0.0.1:{self.port}"]+ or request.headers.getall("Origin", []) not in ([], [self.origin])):+ raise web.HTTPForbidden()+ if not self.active:+ raise web.HTTPServiceUnavailable()+ task = asyncio.current_task()+ assert task is not None+ self._tasks.add(task)+ try:+ # The upstream gateway uses the raw path (not unquoted path) for+ # routing. Keep it intact and do not normalize escaped separators.+ path = request.rel_url.raw_path.rstrip("/") or "/"+ if path == self._issue_path:+ raise web.HTTPForbidden()+ if request.headers.get("Upgrade", "").lower() == "websocket":+ if path != self._ws_path:+ raise web.HTTPNotFound()+ grant = self._grant(self._credential(request), self._ws, consume=True)+ return await self._websocket(request, grant)+ if path == "/webui/bootstrap":+ if request.method != "GET":+ raise web.HTTPMethodNotAllowed(request.method, ["GET"])+ supplied = self._credential(request, bootstrap=True)+ if not secrets.compare_digest(supplied.encode(), self.secret.encode()):+ raise web.HTTPUnauthorized()+ async with self._bootstrap_lock:+ return await self._bootstrap()+ if path == "/webui/terminal":+ raise web.HTTPForbidden()+ return await self._http(request, path)+ except (httpx.HTTPError, WebSocketException, OSError, ValueError):+ # Never reflect upstream URLs, credentials or raw exception text.+ raise web.HTTPBadGateway(text="Remote connection unavailable") from None+ finally:+ self._tasks.discard(task)++ def _headers(self, request: web.Request) -> dict[str, str]:+ headers = {key: value for key, value in request.headers.items()+ if key.lower() in _REQUEST_HEADERS}+ headers["Host"] = f"127.0.0.1:{self.port}"+ headers["Origin"] = self.origin+ return headers++ def _upstream(self, path: str) -> str:+ return f"http://127.0.0.1:{self.tunnel.port}{path}"++ async def _bootstrap(self) -> web.Response:+ now = time.monotonic()+ for grants in (self._api, self._ws):+ for key in [key for key, value in grants.items() if value.expires <= now]:+ del grants[key]+ if len(grants) >= _MAX_CAPABILITIES:+ raise web.HTTPTooManyRequests()+ async with httpx.AsyncClient(trust_env=False, timeout=20) as client:+ response = await client.get(self._upstream("/webui/bootstrap"), headers={+ "X-Nanobot-Auth": self._remote_secret, "Host": f"127.0.0.1:{self.port}",+ })+ if response.status_code != 200:+ raise web.HTTPBadGateway(text="Remote authentication unavailable")+ payload: object = response.json()+ if not isinstance(payload, dict):+ raise ValueError("invalid bootstrap")+ data = cast(dict[str, Any], payload)+ terminal = data.get("terminal")+ if not isinstance(terminal, dict):+ raise ValueError("invalid terminal")+ terminal = cast(dict[str, Any], terminal)+ ttl, ws_path = data.get("expires_in"), data.get("ws_path")+ if (terminal.get("gatewayId") != self._gateway_id+ or terminal.get("protocolVersion") != 1+ or not isinstance(ttl, (float, int)) or not math.isfinite(ttl) or not 0 < ttl <= 86400+ or not isinstance(ws_path, str) or not ws_path.startswith("/")+ or ws_path.startswith("//") or "?" in ws_path or "#" in ws_path+ or any(ord(c) < 33 for c in ws_path)+ or not isinstance(data.get("token"), str) or not data["token"]+ or not isinstance(data.get("api_token"), str) or not data["api_token"]):+ raise ValueError("incompatible bootstrap")+ token, api_token = secrets.token_urlsafe(32), secrets.token_urlsafe(32)+ # Count elapsed upstream time against the remote token's TTL.+ self._ws[token] = _Grant(data["token"], now + ttl, ws_path)+ self._api[api_token] = _Grant(data["api_token"], now + ttl)+ result = {key: data[key] for key in (+ "limits", "model_name", "runtime_surface", "runtime_capabilities",+ ) if key in data}+ result.update(token=token, api_token=api_token, expires_in=ttl,+ terminal={"protocolVersion": 1, "gatewayId": self._gateway_id},+ ws_path=self._ws_path, ws_url=f"ws://127.0.0.1:{self.port}{self._ws_path}")+ return web.json_response(result, headers={"Cache-Control": "no-store"})++ def _local_media(self, match: re.Match[str]) -> str:+ remote = match.group("media")+ if remote is None:+ return match.group()+ existing = self._media_cache.get(remote)+ if existing:+ self._media_cache.move_to_end(remote)+ return existing+ # Authenticated encryption hides the remote bearer URL without retaining+ # an unbounded mapping. Eviction only changes future URL spelling: every+ # previously issued URL still works for this proxy's lifetime.+ local = "/api/media/local/" + self._media_cipher.encrypt(remote.encode()).decode()+ if len(self._media_cache) >= _MAX_CAPABILITIES:+ self._media_cache.popitem(last=False)+ self._media_cache[remote] = local+ return local++ def _remote_media(self, path: str) -> str:+ prefix = "/api/media/local/"+ if not path.startswith(prefix):+ raise web.HTTPUnauthorized()+ try:+ remote = self._media_cipher.decrypt(path[len(prefix):].encode()).decode()+ except (InvalidToken, UnicodeError, ValueError):+ raise web.HTTPUnauthorized() from None+ if not re.fullmatch(_MEDIA_PATH, remote):+ raise web.HTTPUnauthorized()+ return remote++ def _rewrite(self, value: Any) -> Any:+ if isinstance(value, str):+ return _MEDIA.sub(self._local_media, value)+ if isinstance(value, list):+ return [self._rewrite(item) for item in cast(list[Any], value)]+ if isinstance(value, dict):+ return {key: self._rewrite(item) for key, item in cast(dict[str, Any], value).items()}+ return value++ async def _http(self, request: web.Request, path: str) -> web.StreamResponse:+ url = request.rel_url.with_query([+ (key, value) for key, value in request.rel_url.query.items() if key != "token"+ ])+ headers = self._headers(request)+ if path.startswith("/api/media/"):+ remote = self._remote_media(path)+ url = URL(remote).with_query(url.query)+ elif path.startswith("/api/"):+ grant = self._grant(self._credential(request), self._api)+ headers["Authorization"] = "Bearer " + grant.remote+ # HTTP API and static responses are read-only. WebUI writes travel over+ # its authenticated multiplex WebSocket, not an arbitrary HTTP relay.+ if request.method not in {"GET", "HEAD"}:+ raise web.HTTPMethodNotAllowed(request.method, ["GET", "HEAD"])+ async with httpx.AsyncClient(trust_env=False, timeout=30) as client:+ async with client.stream(request.method, self._upstream(str(url)), headers=headers) as upstream:+ if upstream.is_redirect:+ raise web.HTTPBadGateway(text="Unexpected remote redirect")+ outgoing = {key: value for key, value in upstream.headers.items()+ if key.lower() in _RESPONSE_HEADERS}+ outgoing["Cache-Control"] = "no-store"+ if "application/json" in upstream.headers.get("content-type", ""):+ body = bytearray()+ async for chunk in upstream.aiter_bytes():+ body.extend(chunk)+ if len(body) > _MAX_BYTES:+ raise ValueError("response too large")+ if request.method == "HEAD":+ return web.Response(status=upstream.status_code, headers=outgoing)+ return web.Response(body=json.dumps(self._rewrite(json.loads(body))).encode(),+ status=upstream.status_code, headers=outgoing)+ result = web.StreamResponse(status=upstream.status_code, headers=outgoing)+ await result.prepare(request)+ async for chunk in upstream.aiter_bytes():+ await result.write(chunk)+ await result.write_eof()+ return result++ async def _websocket(self, request: web.Request, grant: _Grant) -> web.WebSocketResponse:+ # An already-connected socket fixes the upstream and disables all WS+ # redirects. Its HTTP authority still matches the browser's origin.+ upstream_socket = socket.socket()+ upstream_socket.setblocking(False)+ try:+ await asyncio.wait_for(asyncio.get_running_loop().sock_connect(+ upstream_socket, ("127.0.0.1", self.tunnel.port),+ ), 20)+ query = [(key, value) for key, value in request.rel_url.query.items() if key != "token"]+ query.append(("token", grant.remote))+ url = URL(f"ws://127.0.0.1:{self.port}").with_path(grant.path, encoded=True).with_query(query)+ async with connect(str(url), sock=upstream_socket, proxy=None, origin=Origin(self.origin),+ max_size=_MAX_BYTES, open_timeout=20, close_timeout=2) as upstream:+ browser = web.WebSocketResponse(max_msg_size=_MAX_BYTES, heartbeat=30)+ await browser.prepare(request)++ async def receive() -> None:+ try:+ async for message in upstream:+ if isinstance(message, bytes):+ await browser.send_bytes(message)+ else:+ await browser.send_str(json.dumps(self._rewrite(json.loads(message))))+ finally:+ await browser.close()++ reader = asyncio.create_task(receive())+ try:+ async for message in browser:+ if message.type in {WSMsgType.TEXT, WSMsgType.BINARY}:+ await upstream.send(message.data)+ finally:+ reader.cancel()+ await asyncio.gather(reader, return_exceptions=True)+ await browser.close()+ return browser+ finally:+ # connect owns the socket after handoff; close is also safe if+ # cancellation occurred before the protocol took ownership.+ with contextlib.suppress(OSError):+ upstream_socket.close()diff --git a/nanobot/webui/remote_ssh.py b/nanobot/webui/remote_ssh.pyindex 7f7817308..207e92ec9 100644--- a/nanobot/webui/remote_ssh.py+++ b/nanobot/webui/remote_ssh.py@@ -8,12 +8,13 @@ from __future__ import annotationsimport asyncioimport base64+import contextlibimport hashlibimport json+import osimport shleximport shutilimport socket-from dataclasses import dataclassfrom pathlib import Pathfrom typing import Any, cast@@ -43,9 +44,27 @@ class RemoteProfile(BaseModel):return value+class PairedSSHProfile(RemoteProfile):+ """Internal transport marker. Not accepted by the editable profile API."""+++def transport_arguments(profile: RemoteProfile, remote_port: int, known_hosts: Path | None) -> list[str]:+ args = ssh_arguments(profile, known_hosts)+ if isinstance(profile, PairedSSHProfile):+ # The server key's forced command owns the fixed destination. Do not+ # request forwarding or execute the ordinary credential probe.+ return [*args, profile.host, "nanobot-remote-bridge"]+ return [*args, "-W", f"127.0.0.1:{remote_port}", profile.host]+++# Frame the result so login banners don't get mistaken for invalid config JSON.+_PROBE_PREFIX = b"\x1eNANOBOT_REMOTE:"+# Fixed program, quoted as one shell argument. No user-supplied shell commands._PROBE = r'''import json, os, pathlib, socket, sys+def emit(value):+ print("\n\x1eNANOBOT_REMOTE:" + json.dumps(value))try:path = pathlib.Path(sys.argv[1]).expanduser()data = json.loads(path.read_text())@@ -57,15 +76,20 @@ try: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)}))+ if ws.get("trustedProxyAuth") or ws.get("trusted_proxy_auth"):+ raise ValueError("incompatible_gateway")+ emit({"port": ws.get("port", 8765), "secret": secret,+ "token_issue_path": ws.get("tokenIssuePath") or ws.get("token_issue_path") or "",+ "hostname": socket.gethostname(), "config_path": str(path)})except FileNotFoundError:- print(json.dumps({"error": "config_not_found"}))+ emit({"error": "config_not_found"})except PermissionError:- print(json.dumps({"error": "config_permission"}))+ emit({"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"}))+ emit({"error": code if code in {"webui_disabled", "webui_auth_required", "public_ws_unsupported", "incompatible_gateway"} else "config_invalid"})+except (AttributeError, TypeError):+ emit({"error": "config_invalid"})'''@@ -74,6 +98,8 @@ def ssh_arguments(profile: RemoteProfile, known_hosts: Path | None = None) -> liif not executable:raise RemoteError("ssh_unavailable")args = [executable]+ if isinstance(profile, PairedSSHProfile) and not profile.ssh_config:+ args.extend(["-F", os.devnull])for flag, value in [("-F", profile.ssh_config), ("-i", profile.identity_file)]:if value:path = Path(value).expanduser()@@ -88,9 +114,19 @@ def ssh_arguments(profile: RemoteProfile, known_hosts: Path | None = None) -> li"-o", "ControlMaster=no", "-o", "ControlPath=none", "-o", "ConnectTimeout=10","-o", "ServerAliveInterval=10", "-o", "ServerAliveCountMax=2","-o", "ExitOnForwardFailure=yes", "-o", "RequestTTY=no",+ # Interactive aliases may start tmux or another shell automatically.+ # This connection runs only our fixed probe and forwarding transport.+ # Older clients lack these settings and the corresponding behavior.+ "-o", "IgnoreUnknown=StdinNull,ForkAfterAuthentication,RemoteCommand",+ "-o", "RemoteCommand=none",+ "-o", "ClearAllForwardings=yes", "-o", "StdinNull=no",+ "-o", "ForkAfterAuthentication=no",])if profile.port is not None:args.extend(["-p", str(profile.port)])+ if isinstance(profile, PairedSSHProfile):+ # Never fall back to a user's unrelated identity or agent for this grant.+ args.extend(["-o", "IdentitiesOnly=yes", "-o", "IdentityAgent=none"])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",@@ -104,10 +140,28 @@ def ssh_error(stderr: bytes) -> str: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 "unprotected private key file" in text or "bad permissions" in text:+ return "ssh_key_permissions"+ if "agent refused operation" in text or "signing failed" in text:+ return "ssh_agent_refused"+ if "bad configuration option" in text or "terminating, 1 bad configuration" in text:+ return "ssh_config_invalid"+ if "administratively prohibited" in text:+ return "ssh_forwarding_denied"+ if "open failed: connect failed" in text:+ return "remote_unreachable"+ if "too many authentication failures" in text:+ return "ssh_too_many_keys"+ if "permission denied" in text:+ return "ssh_auth_failed"+ if "connection refused" in text:+ return "ssh_refused"+ if "could not resolve hostname" in text:+ return "ssh_host_not_found"+ if "connection closed" in text or "connection reset" in text:+ return "ssh_connection_closed"if "python3" in text and "not found" in text:return "python_unavailable"return "ssh_unreachable"@@ -129,8 +183,11 @@ async def stop_process(process: asyncio.subprocess.Process) -> None:await process.wait()-async def probe(profile: RemoteProfile, known_hosts: Path | None = None) -> dict[str, Any]:- remote = ["python3", "-c", _PROBE, profile.config_path]+async def run_check(+ profile: RemoteProfile, program: str, known_hosts: Path | None = None,+) -> dict[str, Any]:+ """Run a fixed read-only program with SSH's existing identity and trust policy."""+ remote = ["python3", "-c", program, profile.config_path]if profile.runtime_user:remote = ["sudo", "-n", "-H", "-u", profile.runtime_user, "--", *remote]process = await asyncio.create_subprocess_exec(@@ -143,73 +200,213 @@ async def probe(profile: RemoteProfile, known_hosts: Path | None = None) -> dictif process.returncode:raise RemoteError(ssh_error(stderr))try:- raw = json.loads(stdout)+ records = [line[len(_PROBE_PREFIX):] for line in stdout.split(b"\n")+ if line.startswith(_PROBE_PREFIX)]+ if len(records) != 1:+ raise ValueError+ raw = json.loads(records[0])if not isinstance(raw, dict):raise ValueErrordata = 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 ValueErrorreturn dataexcept (ValueError, TypeError):- raise RemoteError("config_invalid") from None+ raise RemoteError("probe_failed") from None+ except TimeoutError:+ raise RemoteError("ssh_unreachable") from None+ finally:+ await stop_process(process)+++async def probe(profile: RemoteProfile, known_hosts: Path | None = None) -> dict[str, Any]:+ data = await run_check(profile, _PROBE, known_hosts)+ if (not isinstance(data.get("secret"), str) or not data["secret"]+ or type(data.get("port")) is not int or not 1 <= data["port"] <= 65535):+ raise RemoteError("probe_failed")+ return data+++async def pairing_route(source: RemoteProfile, target_host: str) -> str:+ """Explicitly reuse a saved route, never its identities or target settings."""+ process = await asyncio.create_subprocess_exec(+ *ssh_arguments(source), "-G", source.host,+ stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL,+ stdin=asyncio.subprocess.DEVNULL,+ )+ try:+ output, _ = await asyncio.wait_for(process.communicate(), 10)+ if process.returncode:+ raise RemoteError("ssh_config_invalid")+ values = dict(line.split(" ", 1) for line in output.decode().splitlines() if " " in line)+ if values.get("hostname", "").lower() != target_host.lower():+ raise RemoteError("pair_route_mismatch")+ if values.get("proxyjump", "none") != "none":+ raise RemoteError("pair_route_unsupported")+ lines = ["Host *"]+ for option in ("proxycommand", "bindaddress", "bindinterface"):+ value = values.get(option, "none")+ if value != "none":+ lines.append(f" {option} {value}")+ return "\n".join(lines) + "\n"except TimeoutError:raise RemoteError("ssh_unreachable") from Nonefinally:await stop_process(process)-@dataclassclass Tunnel:- process: asyncio.subprocess.Process- port: int+ """Own a private loopback transport; upstream bytes only use SSH pipes.++ Pausing closes streams, not the listener: other browser tabs may still retry+ that origin. Only final owner shutdown relinquishes the listening socket.+ """++ def __init__(self, args: list[str], port: int) -> None:+ self.args = args+ self.port = port+ self.server: asyncio.Server | None = None+ self.enabled = True+ self.error = ""+ self._streams: set[asyncio.Task[None]] = set()++ @property+ def active(self) -> bool:+ return self.enabled and self.server is not None and self.server.is_serving()++ def resume(self, profile: RemoteProfile, remote_port: int, known_hosts: Path) -> None:+ self.args = transport_arguments(profile, remote_port, known_hosts)+ self.error = ""+ self.enabled = True++ def accept(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:+ if not self.active or len(self._streams) >= 32:+ writer.close()+ return+ task = asyncio.create_task(self._relay(reader, writer))+ self._streams.add(task)++ def finished(task: asyncio.Task[None]) -> None:+ self._streams.discard(task)+ # Cancellation can happen before _relay enters its try/finally.+ writer.close()++ task.add_done_callback(finished)++ async def _relay(self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:+ process: asyncio.subprocess.Process | None = None+ pumps: list[asyncio.Task[None]] = []+ stderr = bytearray()++ async def copy(source: asyncio.StreamReader, destination: asyncio.StreamWriter) -> None:+ while data := await source.read(65536):+ destination.write(data)+ await destination.drain()+ if destination.can_write_eof():+ destination.write_eof()++ async def drain_errors(source: asyncio.StreamReader) -> None:+ while data := await source.read(4096):+ stderr.extend(data[:max(0, 8192 - len(stderr))])++ try:+ # Shield process creation so cancellation cannot lose a spawned child+ # before we have its handle and can reap it.+ spawn = asyncio.create_task(asyncio.create_subprocess_exec(+ *self.args, stdin=asyncio.subprocess.PIPE,+ stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE,+ ))+ try:+ process = await asyncio.shield(spawn)+ except asyncio.CancelledError:+ process = await spawn+ raise+ assert process is not None+ assert process.stdin is not None and process.stdout is not None and process.stderr is not None+ pumps = [asyncio.create_task(copy(reader, process.stdin)),+ asyncio.create_task(copy(process.stdout, writer)),+ asyncio.create_task(drain_errors(process.stderr))]+ done, _ = await asyncio.wait(pumps[:2], return_when=asyncio.FIRST_COMPLETED)+ for task in done:+ await task+ # Preserve a client's half-close while draining the final response.+ # Conversely, EOF from SSH must wake an idle keepalive client.+ await pumps[1]+ pumps[0].cancel()+ process.stdin.close()+ await asyncio.wait_for(process.wait(), 3)+ await pumps[2]+ if process.returncode:+ self.error = ssh_error(bytes(stderr))+ except (OSError, ConnectionError):+ self.error = "ssh_unreachable"+ finally:+ for task in pumps:+ task.cancel()+ await asyncio.gather(*pumps, return_exceptions=True)+ if process is not None:+ await stop_process(process)+ writer.close()+ with contextlib.suppress(OSError):+ await writer.wait_closed()++ async def pause(self) -> None:+ self.enabled = False+ streams = list(self._streams)+ for task in streams:+ task.cancel()+ await asyncio.gather(*streams, return_exceptions=True)async def close(self) -> None:- await stop_process(self.process)+ await self.pause()+ if self.server is not None:+ self.server.close()+ await self.server.wait_closed()+++def _listen(local_port: int, excluded_ports: set[int]) -> socket.socket:+ # Never release the chosen socket between validation and use. Windows reuse+ # has different semantics; exclusive binding rejects existing listeners.+ rejected: list[socket.socket] = []+ try:+ for _ in range(128):+ listener = socket.socket()+ try:+ if hasattr(socket, "SO_EXCLUSIVEADDRUSE"):+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_EXCLUSIVEADDRUSE, 1)+ else:+ listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ listener.bind(("127.0.0.1", local_port))+ listener.listen()+ if not local_port and listener.getsockname()[1] in excluded_ports:+ rejected.append(listener)+ continue+ listener.setblocking(False)+ return listener+ except BaseException:+ listener.close()+ raise+ raise RemoteError("local_port_in_use")+ except OSError:+ raise RemoteError("local_port_in_use") from None+ finally:+ for listener in rejected:+ listener.close()async def open_tunnel(profile: RemoteProfile, remote_port: int, known_hosts: Path | None = None,local_port: int = 0,+ *, excluded_ports: set[int] | None = None,) -> 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)+ args = transport_arguments(profile, remote_port, known_hosts)+ listener = _listen(local_port, excluded_ports or set())+ tunnel = Tunnel(args, int(listener.getsockname()[1]))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")+ tunnel.server = await asyncio.start_server(tunnel.accept, sock=listener)+ return tunnelexcept BaseException:+ listener.close()await tunnel.close()raisediff --git a/nanobot/webui/ws_http.py b/nanobot/webui/ws_http.pyindex 620e3b5db..12e4acbce 100644--- a/nanobot/webui/ws_http.py+++ b/nanobot/webui/ws_http.py@@ -165,6 +165,13 @@ class _WebUIThreadDiagnostics:_WEBUI_MUTATION_PATHS = {"remote.discover": "/api/remote-instances/discover",+ "remote.pair_start": "/api/remote-instances/pair_start",+ "remote.pair_preview": "/api/remote-instances/pair_preview",+ "remote.pair_finish": "/api/remote-instances/pair_finish",+ "remote.pair_cancel": "/api/remote-instances/pair_cancel",+ "remote.pair_route": "/api/remote-instances/pair_route",+ "remote.inspect": "/api/remote-instances/inspect",+ "remote.pick_file": "/api/remote-instances/pick_file","remote.save": "/api/remote-instances/save","remote.connect": "/api/remote-instances/connect","remote.disconnect": "/api/remote-instances/disconnect",diff --git a/pyproject.toml b/pyproject.tomlindex 2734c2452..b510ad68f 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -30,6 +30,8 @@ dependencies = [# Feishu's lark-oapi currently requires websockets<16; core supports 15 and 16."websockets>=15.0,<17.0","httpx[socks]>=0.28.0,<1.0.0",+ "aiohttp>=3.14.3,<4.0.0",+ "cryptography>=46.0.0","ddgs>=9.5.5,<10.0.0","oauth-cli-kit>=0.1.6,<1.0.0","loguru>=0.7.3,<1.0.0",diff --git a/tests/cli/test_remote_pair_defaults.py b/tests/cli/test_remote_pair_defaults.pynew file mode 100644index 000000000..458f2d7f8--- /dev/null+++ b/tests/cli/test_remote_pair_defaults.py@@ -0,0 +1,35 @@+"""Server pairing suggests a real login account, never blindly trusts SUDO_USER."""++from types import SimpleNamespace++import pytest++from nanobot.cli import remote+++ ("uid", "sudo_user", "expected"),+ [(1001, "other", "ubuntu"), (0, "ubuntu", "ubuntu"),+ (0, "missing", None), (0, "nanobot", None), (0, "root", None)],+)+def test_pair_suggests_existing_login_account(monkeypatch, uid, sudo_user, expected):+ pwd = pytest.importorskip("pwd")+ users = [SimpleNamespace(pw_name=name, pw_uid=user_uid, pw_shell=shell) for name, user_uid, shell in+ [("root", 0, "/bin/bash"), ("ubuntu", 1001, "/bin/bash"),+ ("other", 1002, "/bin/bash"), ("nanobot", 1003, "/usr/sbin/nologin")]]+ monkeypatch.setattr(remote.os, "getuid", lambda: uid)+ monkeypatch.setattr(pwd, "getpwuid", lambda _: users[1] if uid else users[0])+ monkeypatch.setattr(pwd, "getpwall", lambda: users)+ monkeypatch.setenv("SUDO_USER", sudo_user)+ assert remote._default_ssh_user() == expected++[email protected](("connection", "expected"), [+ ("1.1.1.1 50000 8.8.8.8 22", "8.8.8.8"),+ ("1.1.1.1 50000 10.0.0.8 22", ""),+ ("1.1.1.1 50000 127.0.0.1 22", ""),+ ("1.1.1.1 50000 not-an-ip 22", ""), ("", ""),+])+def test_only_global_ssh_server_address_can_be_suggested(monkeypatch, connection, expected):+ monkeypatch.setenv("SSH_CONNECTION", connection)+ assert remote._default_host() == expecteddiff --git a/tests/utils/test_native_folder_picker.py b/tests/utils/test_native_folder_picker.pyindex feb5a26de..6b5d8e19a 100644--- a/tests/utils/test_native_folder_picker.py+++ b/tests/utils/test_native_folder_picker.py@@ -110,3 +110,51 @@ async def test_pick_native_folder_wraps_process_start_failure(tmp_path, monkeypawith pytest.raises(picker.NativeFolderPickerError, match="failed to start"):await picker.pick_native_folder()++[email protected]("result", ["file", "directory", "cancel"])+async def test_pick_native_file_returns_only_existing_file_path(tmp_path, monkeypatch, result):+ selected = tmp_path / "ssh-config"+ selected.write_text("must-not-be-read-or-returned")+ output = str(selected if result == "file" else tmp_path)+ command = _picker_command(tmp_path, "raise SystemExit(1)" if result == "cancel" else f"print({output!r})")+ monkeypatch.setattr(picker, "_picker_command", lambda kind: command)+ if result == "directory":+ with pytest.raises(picker.NativeFolderPickerError, match="invalid file"):+ await picker.pick_native_file()+ else:+ assert await picker.pick_native_file() == (str(selected) if result == "file" else None)++[email protected]("platform,marker", [+ ("darwin", "choose file"), ("win32", "OpenFileDialog"), ("linux", "--file-selection"),+])+def test_file_picker_uses_platform_file_dialog(monkeypatch, platform, marker):+ monkeypatch.setattr(picker.sys, "platform", platform)+ monkeypatch.setattr(picker.shutil, "which", lambda executable: executable)+ monkeypatch.setenv("DISPLAY", ":test")+ command = picker._picker_command("file")+ assert command is not None+ assert marker in " ".join(command.argv)+ assert "--directory" not in command.argv+++def test_file_picker_is_unavailable_on_headless_linux(monkeypatch):+ monkeypatch.setattr(picker.sys, "platform", "linux")+ monkeypatch.delenv("DISPLAY", raising=False)+ monkeypatch.delenv("WAYLAND_DISPLAY", raising=False)+ assert picker._picker_command("file") is None+++async def test_file_picker_cancellation_reaps_process(monkeypatch):+ import asyncio+ from unittest.mock import AsyncMock, MagicMock++ process = MagicMock(returncode=None)+ process.communicate = AsyncMock(side_effect=asyncio.CancelledError)+ process.wait = AsyncMock(return_value=0)+ monkeypatch.setattr(picker, "_picker_command", lambda kind: picker._PickerCommand(("picker",), frozenset()))+ monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process))+ with pytest.raises(asyncio.CancelledError):+ await picker.pick_native_file()+ process.terminate.assert_called_once()diff --git a/tests/webui/test_gateway_webui_smoke.py b/tests/webui/test_gateway_webui_smoke.pyindex 93331a30b..008e96c92 100644--- a/tests/webui/test_gateway_webui_smoke.py+++ b/tests/webui/test_gateway_webui_smoke.py@@ -9,18 +9,72 @@ import subprocessimport sysimport timefrom pathlib import Path+from unittest.mock import AsyncMock, MagicMockfrom urllib.parse import quoteimport httpximport pytestimport websockets+from nanobot.config.loader import load_configfrom nanobot.session.manager import SessionManagerfrom nanobot.session.recovery import PENDING_USER_TURN_KEY, RUNTIME_CHECKPOINT_KEY+from nanobot.webui.remote_proxy import RemoteProxy+from nanobot.webui.remote_ssh import Tunnel_BOOTSTRAP_SECRET = "smoke-secret"+async def test_remote_proxy_with_real_gateway_chat_settings_and_renewal(tmp_path: Path) -> None:+ """The auth proxy must preserve the actual gateway's WebUI mutation audience."""+ ws_port, gateway_port = _free_port(), _free_port()+ workspace = tmp_path / "workspace"+ workspace.mkdir()+ config_path, log_path = tmp_path / "config.json", tmp_path / "gateway.log"+ _write_smoke_config(config_path, workspace=workspace, ws_port=ws_port, gateway_port=gateway_port)+ process = _start_gateway(config_path, log_path)+ proxy = None+ try:+ upstream = _wait_for_bootstrap(f"http://127.0.0.1:{ws_port}", process, log_path)+ # The real gateway already owns this private listener. SSH pipe ownership+ # and shutdown are exercised separately by test_remote_proxy/remote_tunnel.+ transport = MagicMock(spec=Tunnel, port=ws_port, active=True,+ pause=AsyncMock(), close=AsyncMock())+ proxy = await RemoteProxy.open(transport, _BOOTSTRAP_SECRET, upstream["terminal"]["gatewayId"])+ async with httpx.AsyncClient(trust_env=False) as client:+ first = (await client.get(proxy.origin + "/webui/bootstrap", headers={+ "X-Nanobot-Auth": proxy.secret,+ })).json()+ assert _BOOTSTRAP_SECRET not in json.dumps(first)+ async with websockets.connect(first["ws_url"] + "?token=" + first["token"] + "&client_id=proxy-smoke") as ws:+ assert (await _recv_until(ws, "ready"))["client_id"] == "proxy-smoke"+ await ws.send(json.dumps({"type": "new_chat"}))+ chat_id = (await _recv_until(ws, "attached"))["chat_id"]+ await _recv_until(ws, "session_updated")+ await ws.send(json.dumps({"type": "message", "chat_id": chat_id,+ "content": "/model", "webui": True, "turn_id": "proxy-turn"}))+ assert "custom/smoke-model" in (await _recv_until(ws, "message"))["text"]+ await _recv_until(ws, "turn_end")+ await ws.send(json.dumps({"type": "webui_request", "request_id": "proxy-settings",+ "action": "settings.runtime_config.update",+ "payload": {"values": {"agents.defaults.max_tool_iterations": 2}}}))+ mutation = await _recv_until(ws, "webui_response")+ assert mutation["ok"] is True, mutation+ assert load_config(config_path).agents.defaults.max_tool_iterations == 2+ renewed = (await client.get(proxy.origin + "/webui/bootstrap", headers={+ "X-Nanobot-Auth": proxy.secret,+ })).json()+ assert renewed["token"] != first["token"]+ response = await client.get(proxy.origin + "/api/sessions", headers={+ "Authorization": "Bearer " + renewed["api_token"],+ })+ assert f"websocket:{chat_id}" in {row["key"] for row in response.json()["sessions"]}+ finally:+ if proxy is not None:+ await proxy.close()+ _stop_gateway(process)++def _free_port() -> int:with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:sock.bind(("127.0.0.1", 0))diff --git a/tests/webui/test_remote_discovery.py b/tests/webui/test_remote_discovery.pynew file mode 100644index 000000000..253008aa3--- /dev/null+++ b/tests/webui/test_remote_discovery.py@@ -0,0 +1,144 @@+"""Remote setup discovers metadata, not secrets, and never invents sudo access."""++import asyncio+import json+import os+import subprocess+import sys+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock, MagicMock++import pytest++from nanobot.webui import remote_discovery, remote_ssh+from nanobot.webui.remote_instances import RemoteInstances+from nanobot.webui.remote_ssh import RemoteError, RemoteProfile++if sys.platform != "win32":+ import pwd+++def locate(monkeypatch, capsys, path, units="", properties=""):+ calls = []++ def systemctl(args, **kwargs):+ calls.append(args)+ assert args[0] == "systemctl" and "sudo" not in args+ assert kwargs["timeout"] == 2+ return SimpleNamespace(returncode=0, stdout=units if "list-units" in args else properties)++ monkeypatch.setattr(sys, "argv", ["locate", str(path)])+ monkeypatch.setattr(subprocess, "run", systemctl)+ exec(remote_discovery._LOCATE, {})+ result = json.loads(capsys.readouterr().out.split("NANOBOT_REMOTE:")[1])+ assert "model-secret" not in json.dumps(result)+ return result, calls+++def test_default_config_found_without_reading_contents(tmp_path, monkeypatch, capsys):+ path = tmp_path / "config.json"+ path.write_text("model-secret") # Even invalid config content isn't read by discovery.+ result, calls = locate(monkeypatch, capsys, path)+ assert result["candidates"] == [{"config_path": str(path), "runtime_user": "", "service": ""}]+ assert len(calls) == 1++[email protected](sys.platform == "win32", reason="systemd account discovery targets Unix servers")+def test_service_account_and_private_path_are_offered_without_sudo(tmp_path, monkeypatch, capsys):+ path = tmp_path / ".nanobot/config.json"+ original_stat = Path.stat++ def stat(self, *args, **kwargs):+ if self == path:+ raise PermissionError+ return original_stat(self, *args, **kwargs)++ monkeypatch.setattr(Path, "stat", stat)+ monkeypatch.setattr(pwd, "getpwnam", lambda name: SimpleNamespace(pw_dir=str(tmp_path)))+ result, calls = locate(monkeypatch, capsys, tmp_path / "missing.json",+ "nanobot-team.service loaded active running\n",+ "Id=nanobot-team.service\nUser=nanobot\nWorkingDirectory=/opt/nanobot\nExecStart=/opt/nanobot/bin/nanobot gateway\n")+ assert result["candidates"] == [{"config_path": str(path), "runtime_user": "nanobot", "service": "nanobot-team.service"}]+ assert len(calls) == 2++[email protected](sys.platform == "win32", reason="systemd account discovery targets Unix servers")+def test_multiple_configs_and_custom_service_path(tmp_path, monkeypatch, capsys):+ default = tmp_path / "default.json"+ custom = tmp_path / "custom config.json"+ default.touch()+ custom.touch()+ user = pwd.getpwuid(os.getuid()).pw_name+ result, _ = locate(monkeypatch, capsys, default, "nanobot.service loaded active running\n",+ f'Id=nanobot.service\nUser={user}\nWorkingDirectory={tmp_path}\nExecStart=nanobot gateway --config "custom config.json"\n')+ assert [item["config_path"] for item in result["candidates"]] == [str(default), str(custom)]+ assert all(not item["runtime_user"] for item in result["candidates"])+++def test_unavailable_systemctl_keeps_default_result(tmp_path, monkeypatch, capsys):+ monkeypatch.setattr(sys, "argv", ["locate", str(tmp_path / "absent")])+ monkeypatch.setattr(subprocess, "run", MagicMock(side_effect=FileNotFoundError))+ exec(remote_discovery._LOCATE, {})+ result = json.loads(capsys.readouterr().out.split("NANOBOT_REMOTE:")[1])+ assert result["candidates"] == []+ assert result["incomplete"] is True+++async def test_inspection_uses_login_user_and_strips_unexpected_data(monkeypatch):+ check = AsyncMock(return_value={"hostname": "server", "candidates": [{+ "config_path": "/srv/bot/config.json", "runtime_user": "nanobot", "service": "nanobot.service", "secret": "model-secret",+ }], "incomplete": False, "secret": "model-secret"})+ monkeypatch.setattr(remote_discovery, "run_check", check)+ result = await remote_discovery.inspect(RemoteProfile(name="Test", host="server", runtime_user="root"))+ assert check.call_args.args[0].runtime_user == ""+ assert "model-secret" not in json.dumps(result)++[email protected]("result", [+ {"hostname": "server", "candidates": [{"config_path": "/tmp/x\n", "runtime_user": ""}], "incomplete": False},+ {"hostname": "server", "candidates": [{"config_path": "/tmp/x", "runtime_user": "-root"}], "incomplete": False},+ {"hostname": "server", "candidates": [{}] * 9, "incomplete": False},+ {"hostname": "server", "candidates": "bad", "incomplete": False},+])+async def test_malformed_inspection_is_rejected(monkeypatch, result):+ monkeypatch.setattr(remote_discovery, "run_check", AsyncMock(return_value=result))+ with pytest.raises(RemoteError, match="probe_failed"):+ await remote_discovery.inspect(RemoteProfile(name="Test", host="server"))+++async def test_inspection_reuses_host_verification_without_opening_tunnel(tmp_path, monkeypatch):+ manager = RemoteInstances(tmp_path)+ key = (await manager.action("save", {"profile": {"name": "Test", "host": "server"}}))["id"]+ check = AsyncMock(side_effect=RemoteError("host_key_unknown"))+ monkeypatch.setattr(remote_discovery, "inspect", check)+ with pytest.raises(RemoteError, match="host_key_unknown"):+ await manager.action("inspect", {"id": key})+ assert key in manager._unknown_hosts+ assert not manager.connections+ check.side_effect = None+ check.return_value = {"hostname": "server", "candidates": [], "incomplete": False}+ before = manager.path.read_bytes()+ assert (await manager.action("inspect", {"id": key}))["candidates"] == []+ assert manager.path.read_bytes() == before+++async def test_cancelled_inspection_reaps_remote_process(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_discovery.inspect(RemoteProfile(name="Test", host="server"))+ process.terminate.assert_called_once()++[email protected](("message", "code"), [+ (b"kex_exchange_identification: Connection closed by remote host", "ssh_connection_closed"),+ (b"Connection reset by peer", "ssh_connection_closed"),+ (b"connect to host server port 22: Connection refused", "ssh_refused"),+ (b"Could not resolve hostname server", "ssh_host_not_found"),+ (b"Too many authentication failures", "ssh_too_many_keys"),+])+def test_setup_errors_are_actionable_without_leaking_server_output(message, code):+ assert remote_ssh.ssh_error(message) == codediff --git a/tests/webui/test_remote_instances.py b/tests/webui/test_remote_instances.pyindex 3a26e4f19..4e80314ae 100644--- a/tests/webui/test_remote_instances.py+++ b/tests/webui/test_remote_instances.py@@ -3,6 +3,8 @@import asyncioimport jsonimport socket+import subprocess+import sysfrom types import SimpleNamespacefrom unittest.mock import AsyncMock, MagicMock@@ -13,10 +15,17 @@ from websockets.datastructures import Headersfrom websockets.http11 import Requestfrom nanobot.channels.websocket.runtime import WebSocketConfig-from nanobot.webui import remote_ssh+from nanobot.webui import remote_instances, remote_sshfrom nanobot.webui.gateway_services import build_gateway_servicesfrom nanobot.webui.remote_instances import RemoteInstances-from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, ssh_arguments, ssh_error+from nanobot.webui.remote_proxy import RemoteProxy+from nanobot.webui.remote_ssh import (+ RemoteError,+ RemoteProfile,+ open_tunnel,+ ssh_arguments,+ ssh_error,+)@pytest.fixture@@ -31,8 +40,11 @@ async def save(manager, **values):@pytest.fixturedef ssh(monkeypatch):- process = SimpleNamespace(returncode=None)- tunnel = SimpleNamespace(process=process, port=23456, close=AsyncMock())+ tunnel = SimpleNamespace(active=True, error="", port=23455, pause=AsyncMock(), close=AsyncMock(), resume=MagicMock())+ proxy = SimpleNamespace(tunnel=tunnel, port=23456, origin="http://127.0.0.1:23456",+ secret="local-capability", pause=tunnel.pause, close=tunnel.close,+ resume=MagicMock())+ monkeypatch.setattr(RemoteProxy, "open", AsyncMock(return_value=proxy))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))@@ -46,7 +58,7 @@ def ssh(monkeypatch):real_client = httpx.AsyncClientmonkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: real_client(transport=httpx.MockTransport(respond), **kwargs))- return SimpleNamespace(tunnel=tunnel, probe=probe, state=state)+ return SimpleNamespace(tunnel=tunnel, proxy=proxy, probe=probe, state=state, client=real_client)async def test_save_survives_restart_without_credentials(manager):@@ -57,6 +69,58 @@ async def test_save_survives_restart_without_credentials(manager):await save(manager, private_key="must-never-save")+async def test_new_local_manager_has_new_view_identity_for_same_remote(manager, ssh):+ key = await save(manager)+ first = await manager.action("connect", {"id": key})+ await manager.action("disconnect", {"id": key})+ resumed = await manager.action("connect", {"id": key})+ assert resumed["view_id"] == first["view_id"]+ restarted = RemoteInstances(manager.path.parent)+ second = await restarted.action("connect", {"id": key})+ assert second["gateway_id"] == first["gateway_id"]+ assert second["view_id"] != first["view_id"]+ assert restarted.snapshot()["profiles"][0]["view_id"] == second["view_id"]+ assert "view_id" not in manager.path.read_text()+++async def test_unchanged_save_allows_retry_after_browser_load_failure(manager, ssh):+ key = await save(manager)+ await manager.action("connect", {"id": key})+ before = manager.path.read_bytes()+ result = await manager.action("save", {"id": key, "profile": {+ "name": "Team", "host": "[email protected]",+ }})+ assert result["id"] == key+ assert manager.path.read_bytes() == before+ ssh.tunnel.pause.assert_not_awaited()+++async def test_readding_exact_destination_reuses_entry_without_renaming_or_disconnect(manager, ssh):+ key = await save(manager)+ before = manager.path.read_bytes()+ assert await save(manager, name="Another name") == key+ assert manager.path.read_bytes() == before+ await manager.action("connect", {"id": key})+ before = manager.path.read_bytes()+ live = manager.connections[key]+ assert await save(manager, name="Still the same instance") == key+ assert manager.path.read_bytes() == before+ assert manager.connections[key] is live+ ssh.tunnel.pause.assert_not_awaited()+ ssh.tunnel.close.assert_not_awaited()++[email protected]("change", [+ {"host": "another-alias"}, {"port": 2222}, {"identity_file": "/other/key"},+ {"runtime_user": "nanobot"}, {"ssh_config": "/other/config"},+ {"config_path": "/srv/another-bot/config.json"},+])+async def test_different_destinations_are_not_collapsed_before_connecting(manager, change):+ first = await save(manager)+ assert await save(manager, **change) != first+ assert len(manager.snapshot()["profiles"]) == 2++@pytest.mark.parametrize("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):@@ -66,7 +130,7 @@ def test_hosts_cannot_be_shell_or_ssh_options(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"]:+ for option in ["StrictHostKeyChecking=yes", "BatchMode=yes", "ForwardAgent=no", "ControlPath=none", "PermitLocalCommand=no", "ExitOnForwardFailure=yes", "RemoteCommand=none"]:assert option in argsassert "StrictHostKeyChecking=no" not in args@@ -77,10 +141,12 @@ async def test_connect_checks_protocol_and_only_disconnects_tunnel(manager, ssh)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(connection)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()+ ssh.tunnel.pause.assert_awaited_once()+ ssh.tunnel.close.assert_not_awaited()assert not manager.snapshot()["profiles"][0]["connected"]assert len(manager.snapshot()["profiles"]) == 1@@ -99,15 +165,91 @@ async def test_bad_target_closes_tunnel_and_never_returns_launch_url(manager, ssassert not manager.connections+async def test_failed_initial_retries_do_not_accumulate_listeners(manager, ssh, monkeypatch):+ monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "fixture-ssh")+ monkeypatch.setattr(remote_ssh, "open_tunnel", AsyncMock(wraps=open_tunnel))+ key = await save(manager)+ ssh.state["status"] = 404+ for _ in range(8):+ with pytest.raises(RemoteError, match="incompatible_gateway"):+ await manager.action("connect", {"id": key})+ assert not manager._proxies+ assert json.loads(manager.path.read_text())[key]["local_port"] == 0+++async def test_failed_reconnect_retains_published_origin(manager, ssh):+ key = await save(manager)+ await manager.action("connect", {"id": key})+ await manager.action("disconnect", {"id": key})+ ssh.state["status"] = 404+ with pytest.raises(RemoteError, match="incompatible_gateway"):+ await manager.action("connect", {"id": key})+ assert manager._proxies == {23456: ssh.proxy}+ ssh.tunnel.close.assert_not_awaited()++[email protected]("paired", [False, True])+async def test_rejected_pair_key_explains_repair_not_ssh_agent(manager, ssh, monkeypatch, paired):+ key = await save(manager)+ if paired:+ profiles = manager._read()+ profiles[key].pair_id = key+ manager._write(profiles)+ monkeypatch.setattr(manager.pairing, "connection", lambda _: ssh.probe.return_value)+ ssh.tunnel.error = "ssh_auth_failed"++ def reject(_):+ raise httpx.ReadError("SSH authentication rejected")++ monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: ssh.client(+ transport=httpx.MockTransport(reject), **kwargs,+ ))+ with pytest.raises(RemoteError, match="pair_authorization_rejected" if paired else "ssh_auth_failed"):+ await manager.action("connect", {"id": key})+ assert not manager.connections+ ssh.tunnel.close.assert_awaited_once()++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"]+ profile = (await manager.health())["profiles"][0]+ assert not profile["connected"]+ assert profile["connection_error"] == "instance_changed"+ assert profile["gateway_id"] == "remote-one"assert key in manager.connectionsssh.tunnel.close.assert_not_awaited()[email protected](("status", "identity", "error"), [+ (401, {}, "remote_auth_failed"),+ (403, {}, "remote_auth_failed"),+ (200, {"protocolVersion": 2, "gatewayId": "remote-one"}, "incompatible_gateway"),+ (200, {"protocolVersion": True, "gatewayId": "remote-one"}, "incompatible_gateway"),+ (200, [], "incompatible_gateway"),+])+async def test_health_reports_actionable_safe_errors(manager, ssh, status, identity, error):+ key = await save(manager)+ await manager.action("connect", {"id": key})+ ssh.state.update(status=status, identity=identity)+ profile = (await manager.health())["profiles"][0]+ assert profile["connection_error"] == error+ assert not profile["connected"]+ assert "private-webui-secret" not in json.dumps(profile)+++async def test_explicit_disconnect_is_not_a_network_failure(manager, ssh):+ key = await save(manager)+ await manager.action("connect", {"id": key})+ await manager.action("disconnect", {"id": key})+ assert (await manager.health())["profiles"][0]["connection_error"] == "disconnected"+ await manager.action("connect", {"id": key})+ profile = (await manager.health())["profiles"][0]+ assert profile["connected"]+ assert not profile.get("connection_error")++async def test_connect_to_own_gateway_is_rejected_without_nesting(manager, ssh):manager.local_gateway_id = "remote-one"key = await save(manager)@@ -117,12 +259,39 @@ async def test_connect_to_own_gateway_is_rejected_without_nesting(manager, ssh):assert not manager.connections[email protected]("gateway_id", ["remote-one", "another-instance"])+async def test_aliases_cannot_open_duplicate_views_but_distinct_instances_can(manager, ssh, monkeypatch, gateway_id):+ first = await save(manager)+ await manager.action("connect", {"id": first})+ first_connection = manager.connections[first]+ alias = await save(manager, host="another-alias", config_path="/srv/bot/config.json")+ # A genuinely separate tunnel/proxy, rather than the shared fixture handle.+ second_tunnel = SimpleNamespace(active=True, error="", port=23457, close=AsyncMock())+ second_proxy = SimpleNamespace(port=23458, origin="http://127.0.0.1:23458", secret="local-two")+ monkeypatch.setattr(remote_ssh, "open_tunnel", AsyncMock(return_value=second_tunnel))+ monkeypatch.setattr(RemoteProxy, "open", AsyncMock(return_value=second_proxy))+ ssh.state["identity"]["gatewayId"] = gateway_id+ if gateway_id == "remote-one":+ with pytest.raises(RemoteError, match="duplicate_instance"):+ await manager.action("connect", {"id": alias})+ second_tunnel.close.assert_awaited_once()+ RemoteProxy.open.assert_not_awaited()+ assert alias not in manager.connections+ else:+ assert (await manager.action("connect", {"id": alias}))["gateway_id"] == gateway_id+ second_tunnel.close.assert_not_awaited()+ assert manager.connections[first] is first_connection+ ssh.tunnel.pause.assert_not_awaited()+ ssh.tunnel.close.assert_not_awaited()++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()+ ssh.tunnel.pause.assert_awaited_once()+ ssh.tunnel.close.assert_not_awaited()async def test_closing_local_manager_reaps_ssh(manager, ssh):@@ -142,6 +311,78 @@ async def test_refresh_reuses_a_healthy_tunnel(manager, ssh):ssh.tunnel.close.assert_not_awaited()+async def test_reconnect_resumes_reserved_listener(manager, ssh):+ key = await save(manager)+ first = await manager.action("connect", {"id": key})+ await manager.action("disconnect", {"id": key})+ second = await manager.action("connect", {"id": key})+ assert first["url"] == second["url"]+ remote_ssh.open_tunnel.assert_awaited_once()+ ssh.tunnel.resume.assert_called_once()+ ssh.tunnel.close.assert_not_awaited()+++async def test_shutdown_does_not_release_origin_during_health_request(manager, ssh, monkeypatch):+ key = await save(manager)+ await manager.action("connect", {"id": key})+ entered, release = asyncio.Event(), asyncio.Event()++ async def respond(request):+ entered.set()+ await release.wait()+ ssh.tunnel.close.assert_not_awaited()+ assert request.headers["X-Nanobot-Auth"] == "private-webui-secret"+ return httpx.Response(200, json=ssh.state["identity"])++ monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: ssh.client(+ transport=httpx.MockTransport(respond), **kwargs,+ ))+ health = asyncio.create_task(manager.health())+ await asyncio.wait_for(entered.wait(), 2)+ shutdown = asyncio.create_task(manager.close())+ try:+ await asyncio.sleep(0)+ assert not shutdown.done()+ ssh.tunnel.close.assert_not_awaited()+ finally:+ release.set()+ await asyncio.gather(health, shutdown)+ ssh.tunnel.close.assert_awaited_once()+++async def test_health_deadline_returns_editable_offline_directory(manager, ssh, monkeypatch):+ key = await save(manager)+ await manager.action("connect", {"id": key})+ cancelled = asyncio.Event()++ async def respond(request):+ try:+ await asyncio.Event().wait()+ finally:+ cancelled.set()++ monkeypatch.setattr(remote_instances, "_HEALTH_TIMEOUT_SECONDS", 0.02)+ monkeypatch.setattr(httpx, "AsyncClient", lambda **kwargs: ssh.client(+ transport=httpx.MockTransport(respond), **kwargs,+ ))+ directory = await asyncio.wait_for(manager.health(), 1)+ assert not directory["profiles"][0]["connected"]+ assert cancelled.is_set()+ await manager.action("save", {"id": key, "profile": {+ "name": "Repaired", "host": "[email protected]",+ }})+ assert manager.snapshot()["profiles"][0]["name"] == "Repaired"+++async def test_health_budget_includes_waiting_for_connection_lock(manager, ssh, monkeypatch):+ key = await save(manager)+ await manager.action("connect", {"id": key})+ monkeypatch.setattr(remote_instances, "_HEALTH_TIMEOUT_SECONDS", 0.02)+ async with manager._lock:+ directory = await asyncio.wait_for(manager.health(), 1)+ assert directory["profiles"][0]["id"] == key++async def test_reconnect_keeps_origin_and_changing_target_does_not(manager, ssh):key = await save(manager)await manager.action("connect", {"id": key})@@ -160,6 +401,110 @@ async def test_corrupt_store_not_overwritten(manager):assert manager.path.read_text() == "corrupt"[email protected]("change", [+ {"config_path": "/srv/other-bot/config.json"},+ {"runtime_user": "other-bot"},+ {"identity_file": "/tmp/other-identity"},+])+async def test_changing_instance_drops_origin_but_keeps_server_trust(manager, ssh, change):+ key = await save(manager)+ await manager.action("connect", {"id": key})+ await manager.action("disconnect", {"id": key})+ known_hosts = manager.path.parent / "remote-hosts" / key+ known_hosts.parent.mkdir()+ known_hosts.write_text("nanobot-remote ssh-ed25519 fixture\n")+ await manager.action("save", {"id": key, "profile": {+ "name": "Another bot", "host": "[email protected]", **change,+ }})+ assert json.loads(manager.path.read_text())[key]["local_port"] == 0+ assert known_hosts.read_text() == "nanobot-remote ssh-ed25519 fixture\n"++[email protected]("failure", ["process-exit", "health-error"])+async def test_offline_profile_can_be_edited_without_hidden_disconnect(manager, ssh, failure):+ key = await save(manager)+ await manager.action("connect", {"id": key})+ if failure == "process-exit":+ ssh.tunnel.active = False+ else:+ ssh.state["status"] = 503+ assert not (await manager.health())["profiles"][0]["connected"]+ await manager.action("save", {"id": key, "profile": {"name": "Fixed", "host": "fixed.example.test"}})+ ssh.tunnel.pause.assert_awaited_once()+ assert key not in manager.connections+ assert manager.snapshot()["profiles"][0]["host"] == "fixed.example.test"+++async def test_live_profile_still_requires_explicit_disconnect_before_edit(manager, ssh):+ key = await save(manager)+ await manager.action("connect", {"id": key})+ with pytest.raises(RemoteError, match="disconnect_before_edit"):+ await manager.action("save", {"id": key, "profile": {"name": "Changed", "host": "other.test"}})+ ssh.tunnel.close.assert_not_awaited()+++async def test_retired_origins_survive_edit_forget_and_restart(manager, ssh, monkeypatch):+ key = await save(manager)+ await manager.action("connect", {"id": key})+ await manager.action("disconnect", {"id": key})+ await manager.action("save", {"id": key, "profile": {+ "name": "Other instance", "host": "[email protected]", "config_path": "/srv/b/config.json",+ }})+ restarted = RemoteInstances(manager.path.parent)++ async def different_origin(*args, local_port, excluded_ports):+ assert local_port == 0+ assert 23456 in excluded_ports+ ssh.proxy.port = 23457+ return ssh.proxy++ monkeypatch.setattr(RemoteProxy, "open", different_origin)+ await restarted.action("connect", {"id": key})+ await restarted.action("remove", {"id": key})+ assert restarted.snapshot()["profiles"] == []+ restarted_again = RemoteInstances(manager.path.parent)+ assert restarted_again._remember_origins({}) == {23456, 23457}+ assert "private-webui-secret" not in (manager.path.parent / "remote-origin-ports.json").read_text()+++async def test_old_profile_origin_is_remembered_before_first_edit(manager, ssh):+ key = await save(manager)+ old = json.loads(manager.path.read_text())+ old[key]["local_port"] = 23456+ manager.path.write_text(json.dumps(old)) # Pre-ledger profile created by the previous build.+ await manager.action("save", {"id": key, "profile": {+ "name": "Other", "host": "[email protected]", "runtime_user": "other-user",+ }})+ assert RemoteInstances(manager.path.parent)._remember_origins({}) == {23456}+++async def test_legacy_transparent_origin_is_not_reused(manager, ssh):+ key = await save(manager)+ old = json.loads(manager.path.read_text())+ old[key]["local_port"] = 12345+ manager.path.write_text(json.dumps(old))+ await manager.action("connect", {"id": key})+ kwargs = RemoteProxy.open.call_args.kwargs+ assert kwargs["local_port"] == 0+ assert 12345 in kwargs["excluded_ports"]+ assert json.loads(manager.path.read_text())[key]["proxy_origin"] is True+ assert "proxy_origin" not in manager.snapshot()["profiles"][0]+++async def test_invalid_origin_ledger_blocks_target_change_without_losing_profile_or_pin(manager):+ key = await save(manager)+ before = manager.path.read_bytes()+ ledger = manager.path.parent / "remote-origin-ports.json"+ ledger.write_text('{"corrupt": true}')+ known_hosts = manager.path.parent / "remote-hosts" / key+ known_hosts.parent.mkdir()+ known_hosts.write_text("trusted-key")+ with pytest.raises(RemoteError, match="profile_store_invalid"):+ await manager.action("save", {"id": key, "profile": {"name": "Other", "host": "other.example.test"}})+ assert manager.path.read_bytes() == before+ assert known_hosts.read_text() == "trusted-key"++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")@@ -199,6 +544,12 @@ async def test_shutdown_prevents_new_tunnels(manager, ssh):(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"),+ (b"sudo: permission denied for private-user", "runtime_user_denied"),+ (b"WARNING: UNPROTECTED PRIVATE KEY FILE! Permission denied", "ssh_key_permissions"),+ (b"sign_and_send_pubkey: signing failed for /private/path: agent refused operation\nPermission denied", "ssh_agent_refused"),+ (b"/private/config: Bad configuration option: typo", "ssh_config_invalid"),+ (b"channel 0: open failed: administratively prohibited: open failed", "ssh_forwarding_denied"),+ (b"channel 0: open failed: connect failed: Connection refused", "remote_unreachable"),])def test_errors_never_echo_raw_ssh_output(stderr, code):assert ssh_error(stderr) == code@@ -214,7 +565,7 @@ def gateway(tmp_path):)[email protected]("action", ["save", "discover", "connect", "remove", "trust"])[email protected]("action", ["save", "discover", "inspect", "pick_file", "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))@@ -222,6 +573,56 @@ async def test_http_mutations_are_not_gettable_even_with_token(gateway, action):assert result.status_code == 405[email protected]("path", ["/local/ssh-config", None])+async def test_file_picker_returns_path_without_saving_profile(manager, monkeypatch, path):+ from nanobot.webui import native_folder_picker++ choose = AsyncMock(return_value=path)+ monkeypatch.setattr(native_folder_picker, "pick_native_file", choose)+ assert await manager.action("pick_file", {}) == {"path": path}+ assert not manager.path.exists()+ choose.assert_awaited_once_with()+++async def test_file_picker_failure_does_not_expose_native_error(manager, monkeypatch):+ from nanobot.webui import native_folder_picker++ monkeypatch.setattr(native_folder_picker, "pick_native_file", AsyncMock(+ side_effect=native_folder_picker.NativeFolderPickerError("private diagnostic"),+ ))+ with pytest.raises(RemoteError, match="^file_picker_unavailable$"):+ await manager.action("pick_file", {})+++async def test_file_picker_does_not_open_multiple_system_dialogs(manager, monkeypatch):+ from nanobot.webui import native_folder_picker++ choose = AsyncMock()+ monkeypatch.setattr(native_folder_picker, "pick_native_file", choose)+ async with manager._picker_lock:+ with pytest.raises(RemoteError, match="file_picker_unavailable"):+ await manager.action("pick_file", {})+ choose.assert_not_awaited()++[email protected]("peer,host,origin", [+ ("203.0.113.1", "127.0.0.1:8765", "http://127.0.0.1:8765"),+ ("127.0.0.1", "bot.example.com", "https://bot.example.com"),+ ("127.0.0.1", "127.0.0.1:8765", "https://evil.example"),+])+async def test_remote_clients_cannot_open_local_file_picker(gateway, monkeypatch, peer, host, origin):+ from nanobot.webui import native_folder_picker++ choose = AsyncMock()+ monkeypatch.setattr(native_folder_picker, "pick_native_file", choose)+ connection = SimpleNamespace(remote_address=(peer, 10000), request=SimpleNamespace(+ headers=Headers({"Host": host, "Origin": origin}),+ ))+ result = await gateway.http.dispatch_webui_mutation(connection, "remote.pick_file", {})+ assert result.status_code == 403+ choose.assert_not_awaited()++@pytest.mark.parametrize(("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),@@ -248,6 +649,51 @@ async def test_cancellation_reaps_inflight_probe(monkeypatch):process.terminate.assert_called_once()[email protected]("field", ["trustedProxyAuth", "trusted_proxy_auth"])+def test_ssh_probe_rejects_trusted_assertion_bypass(tmp_path, field):+ path = tmp_path / "config.json"+ path.write_text(json.dumps({"channels": {"websocket": {+ "enabled": True, "tokenIssueSecret": "synthetic-root",+ field: {"assertionHeader": "Host", "trustedPeers": ["127.0.0.0/8"]},+ }}}))+ result = subprocess.run([sys.executable, "-c", remote_ssh._PROBE, str(path)],+ capture_output=True, text=True, check=True)+ assert json.loads(result.stdout.split("NANOBOT_REMOTE:")[1]) == {"error": "incompatible_gateway"}++[email protected]("banner", [b"", b"Welcome to the server\n", b"{\"port\": 1}\nWelcome without newline"])+async def test_probe_ignores_shell_banners_without_exposing_them(monkeypatch, banner):+ data = {"port": 8765, "secret": "synthetic-root"}+ process = MagicMock(returncode=0)+ process.communicate = AsyncMock(return_value=(+ banner + b"\n" + remote_ssh._PROBE_PREFIX + json.dumps(data).encode() + b"\nGoodbye\n", b"",+ ))+ monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process))+ assert await remote_ssh.probe(RemoteProfile(name="Test", host="example.test")) == data++[email protected]("output", [+ b"Welcome. Password required for private-user.",+ b'\x1eNANOBOT_REMOTE:{"port": 8765, "secret": "s"}\n\x1eNANOBOT_REMOTE:{}',+ b"\x1eNANOBOT_REMOTE:not-json-with-private-data",+])+async def test_invalid_probe_protocol_is_not_reported_as_bad_config(monkeypatch, output):+ process = MagicMock(returncode=0)+ process.communicate = AsyncMock(return_value=(output, b""))+ monkeypatch.setattr(asyncio, "create_subprocess_exec", AsyncMock(return_value=process))+ with pytest.raises(RemoteError, match="^probe_failed$"):+ await remote_ssh.probe(RemoteProfile(name="Test", host="example.test"))++[email protected]("config", ["invalid JSON", "[]", '{"channels": null}', '{"channels": {"websocket": []}}'])+def test_probe_reports_malformed_config_as_config_error(tmp_path, config):+ path = tmp_path / "config.json"+ path.write_text(config)+ result = subprocess.run([sys.executable, "-c", remote_ssh._PROBE, str(path)],+ capture_output=True, text=True, check=True)+ assert json.loads(result.stdout.split("NANOBOT_REMOTE:")[1]) == {"error": "config_invalid"}++async def test_tunnel_refuses_an_existing_listener(monkeypatch):spawn = AsyncMock()monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)@@ -263,7 +709,8 @@ async def test_tunnel_refuses_an_existing_listener(monkeypatch):spawn.assert_not_awaited()-async def test_tunnel_reuses_closed_port_with_time_wait(monkeypatch):[email protected](hasattr(socket, "SO_EXCLUSIVEADDRUSE"), reason="Unix TIME_WAIT reuse; Windows requires exclusive ownership")+async def test_tunnel_reuses_closed_port_with_time_wait():with socket.socket() as listener:listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)listener.bind(("127.0.0.1", 0))@@ -273,12 +720,6 @@ async def test_tunnel_reuses_closed_port_with_time_wait(monkeypatch):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,)diff --git a/tests/webui/test_remote_pairing.py b/tests/webui/test_remote_pairing.pynew file mode 100644index 000000000..3f999afe7--- /dev/null+++ b/tests/webui/test_remote_pairing.py@@ -0,0 +1,297 @@+"""Pairing protocol, restricted authorization and local API regression tests."""++import json+import os+import socket+import subprocess+import sys+import threading+import time+from types import SimpleNamespace+from unittest.mock import AsyncMock++import pytest+from cryptography.hazmat.primitives import serialization+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey++from nanobot.webui import remote_pair_server, remote_pairing, remote_ssh+from nanobot.webui.remote_instances import RemoteInstances+from nanobot.webui.remote_pairing import PairReceipt, PairStore, read_request, seal+from nanobot.webui.remote_ssh import (+ PairedSSHProfile,+ RemoteError,+ ssh_arguments,+ transport_arguments,+)+++def ssh_public():+ return Ed25519PrivateKey.generate().public_key().public_bytes(serialization.Encoding.OpenSSH, serialization.PublicFormat.OpenSSH).decode()+++def receipt(request, **updates):+ return PairReceipt(**dict(id=request.id, ssh_key=request.ssh_key, host="203.0.113.1", user="ubuntu",+ ssh_port=22, host_key=ssh_public(), hostname="team", config_path="/srv/nanobot/config.json",+ port=8765, secret="private-webui-credential", authorized_until=int(time.time()) + 86400,+ **updates))+++def pair(tmp_path):+ store = PairStore(tmp_path)+ start = store.start()+ request = read_request(start["command"].split()[-1])+ value = receipt(request)+ return store, start, request, value, seal(request, value)+++def test_round_trip_only_preview_public_fields_and_restart(pair):+ store, start, request, value, code = pair+ assert "secret" not in json.dumps(start)+ assert "private-webui-credential" not in code+ preview = store.preview(request.id, code)+ assert preview["host"] == "[email protected]"+ assert "secret" not in json.dumps(preview)+ store.finish(request.id, code)+ assert PairStore(store.root.parent).connection(request.id)["secret"] == value.secret+ assert store.finish(request.id, code) == value+ for path in store.path(request.id).iterdir():+ assert path.stat().st_mode & 0o777 == 0o600+ assert store.path(request.id).stat().st_mode & 0o777 == 0o700+ assert value.secret not in (store.path(request.id) / "receipt").read_text()+++def test_expiry_and_reconnect_have_distinct_lifetimes(pair, monkeypatch):+ store, _, request, _, code = pair+ store.finish(request.id, code)+ monkeypatch.setattr(remote_pairing.time, "time", lambda: request.expires + 1)+ with pytest.raises(RemoteError, match="pair_expired"):+ store.preview(request.id, code)+ assert store.connection(request.id)["secret"]+++def test_wrong_request_and_tampering_fail_closed(pair):+ store, _, request, _, code = pair+ another = store.start()+ for invalid in [code[:-20] + "AAAAAAAAAAAAAAAAAAAA", "garbage", "nbpc1." + "A" * 32769]:+ with pytest.raises(RemoteError, match="pair_invalid"):+ store.preview(request.id, invalid)+ with pytest.raises(RemoteError, match="pair_invalid"):+ store.preview(another["id"], code)+ assert not (store.path(request.id) / "receipt").exists()+++def test_wrapped_console_code_is_accepted(pair):+ store, _, request, _, code = pair+ wrapped = "\n".join(code[i:i + 80] for i in range(0, len(code), 80))+ assert store.preview(request.id, wrapped)["id"] == request.id++[email protected]("origin", ["http://127.0.0.1:8870", "http://localhost:5173", "http://[::1]:8765"])+def test_return_link_is_loopback_fragment_only_and_survives_new_store(tmp_path, origin):+ from urllib.parse import urlsplit++ store = PairStore(tmp_path)+ started = store.start(origin)+ request = read_request(started["command"].split()[-1])+ value = receipt(request)+ code = seal(request, value)+ link = remote_pairing.return_link(request, code)+ assert link == origin + "/#/remote?pairing=" + code+ assert not urlsplit(link).query+ assert "private-webui-credential" not in link+ assert PairStore(tmp_path).preview(request.id, code)["host"] == "[email protected]"++[email protected]("origin", ["https://example.com", "http://127.0.0.1.evil.test", "http://[email protected]", "http://127.0.0.1:0", "http://127.0.0.1:65536", "http://127.0.0.1/path", "http://127.0.0.1?redirect=bad", "http://127.0.0.1#bad", "http://127.0.0.1\n", "http://2130706433", "file:///tmp"])+def test_return_link_rejects_external_or_ambiguous_targets_before_creating_key(tmp_path, origin):+ store = PairStore(tmp_path)+ with pytest.raises(RemoteError, match="pair_invalid"):+ store.start(origin)+ assert not store.root.exists()+++def test_legacy_request_still_has_copy_code_fallback(pair):+ _, _, request, _, code = pair+ assert remote_pairing.return_link(request, code) == ""+++def test_cancel_only_deletes_pending_pair_files(pair):+ store, _, request, _, code = pair+ pending = store.start()+ store.cancel(pending["id"])+ assert not store.path(pending["id"]).exists()+ store.finish(request.id, code)+ store.cancel(request.id)+ assert store.connection(request.id)["secret"]+ with pytest.raises(RemoteError):+ store.cancel("../../outside")+++def test_server_appends_restricted_key_and_revoke_preserves_existing(pair, tmp_path):+ _, _, request, _, _ = pair+ home = tmp_path / "server-home"+ home.mkdir()+ (home / ".ssh").mkdir(mode=0o700)+ original = ssh_public() + " existing-admin\n"+ keys = home / ".ssh/authorized_keys"+ keys.write_text(original)+ remote_pair_server.write_authorization(home, request, 8765, int(time.time()) + 86400)+ lines = keys.read_text().splitlines()+ assert lines[0] + "\n" == original+ assert lines[1].startswith('restrict,expiry-time="')+ assert "port-forwarding" not in lines[1]+ assert request.ssh_key in lines[1]+ assert "private-webui" not in (home / ".ssh/nanobot-remote" / request.id / "bridge.py").read_text()+ with pytest.raises(RemoteError, match="pair_used"):+ remote_pair_server.write_authorization(home, request, 8765, int(time.time()) + 86400)+ remote_pair_server.remove_authorization(home, request.id)+ assert keys.read_text() == original+ remote_pair_server.remove_authorization(home, request.id)+ assert keys.read_text() == original+++def test_server_refuses_symlink_authorized_keys_without_touching_target(pair, tmp_path):+ _, _, request, _, _ = pair+ home = tmp_path / "server"+ (home / ".ssh").mkdir(parents=True, mode=0o700)+ outside = tmp_path / "important"+ outside.write_text("untouched")+ (home / ".ssh/authorized_keys").symlink_to(outside)+ with pytest.raises(OSError):+ remote_pair_server.write_authorization(home, request, 8765, int(time.time()) + 86400)+ assert outside.read_text() == "untouched"+++def test_paired_transport_cannot_fall_back_to_generic_probe_or_forwarding(pair, monkeypatch):+ store, _, request, value, _ = pair+ monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "/usr/bin/ssh")+ profile = PairedSSHProfile(**store.profile(value).model_dump())+ args = ssh_arguments(profile)+ assert "IdentityAgent=none" in args and "IdentitiesOnly=yes" in args+ assert args[1:3] == ["-F", os.devnull]+ transport = transport_arguments(profile, value.port, store.path(request.id) / "known_hosts")+ assert "-W" not in transport+ assert transport[-1] == "nanobot-remote-bridge"+ assert "sudo" not in " ".join(transport)+++def test_fixed_bridge_streams_only_to_baked_in_loopback_port():+ # Real bidirectional bytes, no SSH_ORIGINAL_COMMAND interpolation.+ listener = socket.socket()+ listener.bind(("127.0.0.1", 0))+ listener.listen(1)+ port = listener.getsockname()[1]+ def serve():+ with listener:+ connection, _ = listener.accept()+ with connection:+ data = bytearray()+ while chunk := connection.recv(8192):+ data.extend(chunk)+ connection.sendall(b"received:" + data)+ worker = threading.Thread(target=serve, daemon=True)+ worker.start()+ result = subprocess.run([sys.executable, "-I", "-S", "-c", remote_pair_server._BRIDGE.replace("PORT", str(port))],+ input=b"hello-webui", capture_output=True, timeout=5,+ env={**os.environ, "SSH_ORIGINAL_COMMAND": "echo MUST-NOT-EXECUTE"})+ worker.join(2)+ assert result.returncode == 0+ assert result.stdout == b"received:hello-webui"+++async def test_api_pair_finalization_pins_host_and_hides_credentials(tmp_path):+ manager = RemoteInstances(tmp_path)+ started = await manager.action("pair_start", {})+ request = read_request(started["command"].split()[-1])+ value = receipt(request)+ code = seal(request, value)+ preview = await manager.action("pair_preview", {"id": request.id, "code": code})+ assert "secret" not in preview+ result = await manager.action("pair_finish", {"id": request.id, "code": code})+ assert result["profiles"][0]["paired"] is True+ assert "private-webui" not in json.dumps(result)+ assert "private-webui" not in manager.path.read_text()+ assert manager._known_hosts(request.id).read_text() == "nanobot-remote " + value.host_key + "\n"+ again = await manager.action("pair_finish", {"id": request.id, "code": code})+ assert again["id"] == request.id and len(again["profiles"]) == 1+ with pytest.raises(RemoteError, match="pair_managed"):+ await manager.action("save", {"id": request.id, "profile": manager.pairing.profile(value).model_dump()})+ await manager.action("pair_cancel", {"id": request.id})+ assert manager.pairing.connection(request.id)["secret"]+ await manager.action("remove", {"id": request.id})+ assert not manager.pairing.path(request.id).exists()+ assert manager.snapshot()["profiles"] == []+++def test_model_keys_never_enter_pairing_metadata(tmp_path):+ path = tmp_path / "config.json"+ path.write_text(json.dumps({"providers": {"deepseek": {"apiKey": "not-exported"}},+ "channels": {"websocket": {"enabled": True, "tokenIssueSecret": "webui-only"}}}))+ assert "not-exported" not in json.dumps(remote_pair_server.metadata(path))+++async def test_route_import_only_copies_network_options(monkeypatch, tmp_path):+ config = tmp_path / "config"+ config.write_text("")+ process = SimpleNamespace(returncode=0, communicate=AsyncMock(return_value=(+ b"hostname 203.0.113.1\nuser ubuntu\nport 22\nidentityfile /private/admin-key\nproxycommand nc -b en0 %h %p\nbindaddress none\nbindinterface none\nproxyjump none\n", b"")))+ monkeypatch.setattr(remote_ssh.asyncio, "create_subprocess_exec", AsyncMock(return_value=process))+ monkeypatch.setattr(remote_ssh, "stop_process", AsyncMock())+ profile = remote_ssh.RemoteProfile(name="existing", host="alias", ssh_config=str(config))+ route = await remote_ssh.pairing_route(profile, "203.0.113.1")+ assert route == "Host *\n proxycommand nc -b en0 %h %p\n"+ assert "identity" not in route and "admin" not in route+ with pytest.raises(RemoteError, match="pair_route_mismatch"):+ await remote_ssh.pairing_route(profile, "different.example")+++def test_request_cannot_inject_authorized_keys_options(pair):+ _, start, _, _, _ = pair+ raw = remote_pairing.unpack("nbpr1.", start["command"].split()[-1])+ raw["ssh_key"] = 'command="sh" ' + raw["ssh_key"]+ with pytest.raises(RemoteError, match="pair_invalid"):+ read_request(remote_pairing.pack("nbpr1.", raw))+++def test_expired_device_cannot_connect(pair, monkeypatch):+ store, _, request, value, code = pair+ store.finish(request.id, code)+ monkeypatch.setattr(remote_pairing.time, "time", lambda: value.authorized_until + 1)+ with pytest.raises(RemoteError, match="pair_authorization_expired"):+ store.connection(request.id)+ # The UI can explain expiry without opening a path around connection().+ assert store.authorization_until(request.id) == value.authorized_until+++def test_authorization_expiry_does_not_hide_other_profiles_on_corrupt_receipt(pair):+ store, _, request, _, code = pair+ store.finish(request.id, code)+ (store.path(request.id) / "receipt").write_text("invalid")+ assert store.authorization_until(request.id) is None+ with pytest.raises(RemoteError, match="pair_invalid"):+ store.connection(request.id)+++async def test_saved_pair_exposes_only_expiry_and_public_metadata(pair, monkeypatch):+ store, _, request, value, code = pair+ manager = RemoteInstances(store.root.parent)+ await manager.action("pair_finish", {"id": request.id, "code": code})+ monkeypatch.setattr(remote_pairing.time, "time", lambda: value.authorized_until + 1)+ profile = manager.snapshot()["profiles"][0]+ assert profile["authorized_until"] == value.authorized_until+ assert value.secret not in json.dumps(profile)+ assert "receipt" not in profile and "exchange_key" not in profile+ with pytest.raises(RemoteError, match="pair_authorization_expired"):+ await manager.action("connect", {"id": request.id})+++def test_failure_before_authorizing_does_not_write_keys(pair, monkeypatch, tmp_path):+ _, _, request, value, _ = pair+ install = AsyncMock()+ monkeypatch.setattr(remote_pair_server, "as_account", install)+ with pytest.raises(RemoteError):+ remote_pair_server.authorize(request, host=value.host, user=value.user, ssh_port=22,+ config=tmp_path / "missing", host_key=value.host_key,+ until=value.authorized_until)+ install.assert_not_called()diff --git a/tests/webui/test_remote_proxy.py b/tests/webui/test_remote_proxy.pynew file mode 100644index 000000000..38ee56401--- /dev/null+++ b/tests/webui/test_remote_proxy.py@@ -0,0 +1,387 @@+"""Real browser-side HTTP/WS, real gateway auth, and an owned SSH-pipe fixture."""++import asyncio+import base64+import json+import socket+import sys+import time+from dataclasses import replace+from types import SimpleNamespace+from unittest.mock import MagicMock+from urllib.parse import parse_qs, urlsplit++import httpx+import pytest+from websockets.asyncio.client import connect+from websockets.asyncio.server import serve+from websockets.datastructures import Headers+from websockets.exceptions import InvalidStatus+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_proxy import RemoteProxy+from nanobot.webui.remote_ssh import RemoteProfile, open_tunnel++ROOT = "synthetic-remote-root"+MEDIA = "/api/media/AAAAAAAAAAAAAAAAAAAAAA/remoteFilePayload"+++async def remote(tmp_path, monkeypatch):+ config = WebSocketConfig(host="127.0.0.1", token_issue_secret=ROOT, path="/custom/ws")+ services = build_gateway_services(+ config=config, 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,+ )+ seen, children = [], []+ state = SimpleNamespace(block=asyncio.Event(), entered=asyncio.Event(), ws_redirect=False)++ async def process(connection, request):+ seen.append(request)+ path = urlsplit(request.path).path+ if path == "/redirect" or (state.ws_redirect and path == config.path):+ response = connection.respond(302, "redirect")+ response.headers["Location"] = "http://127.0.0.1:1/?token=" + ROOT+ response.headers["Set-Cookie"] = "credential=" + ROOT+ return response+ if path == "/api/fixture" or path == "/api/block":+ if not services.tokens.check_api_token(request):+ return connection.respond(401, "Unauthorized")+ if path == "/api/block":+ state.entered.set()+ await state.block.wait()+ response = connection.respond(200, json.dumps({"text": f""}))+ response.headers["Content-Type"] = "application/json"+ response.headers["Set-Cookie"] = "credential=" + ROOT+ return response+ if path == MEDIA:+ assert request.headers.get("Authorization") is None+ response = connection.respond(206, "bytes")+ response.headers["Content-Type"] = "image/png"+ response.headers["Content-Range"] = "bytes 0-4/10"+ return response+ return await services.endpoint.process_request(connection, request, is_allowed=lambda _: True)++ async def messages(ws):+ assert ws in services.endpoint.webui_connections+ assert ws.request.headers.get("X-Nanobot-Auth") is None+ await ws.send(json.dumps({"ready": True, "media": MEDIA,+ "query": parse_qs(urlsplit(ws.request.path).query).get("client_id")}))+ async for message in ws:+ await ws.send(message)++ real_spawn = asyncio.create_subprocess_exec+ monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "fixture-ssh")+ async with serve(messages, "127.0.0.1", 0, process_request=process, max_size=64 * 1024 * 1024) as server:+ port = server.sockets[0].getsockname()[1]+ pipe = f"""+import os, socket, threading+upstream = socket.create_connection(('127.0.0.1', {port}))+def upload():+ while data := os.read(0, 65536):+ upstream.sendall(data)+ upstream.shutdown(socket.SHUT_WR)+threading.Thread(target=upload, daemon=True).start()+while data := upstream.recv(65536):+ os.write(1, data)+"""++ async def spawn(*args, **kwargs):+ child = await real_spawn(sys.executable, "-u", "-c", pipe, **kwargs)+ children.append(child)+ return child++ monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)+ profile = RemoteProfile(name="Test", host="fixture.test")+ tunnel = await open_tunnel(profile, port)+ proxy = await RemoteProxy.open(tunnel, ROOT, services.tokens.instance_id)+ try:+ async with httpx.AsyncClient(trust_env=False) as client:+ yield SimpleNamespace(proxy=proxy, tunnel=tunnel, client=client, services=services,+ seen=seen, state=state, profile=profile, port=port)+ finally:+ state.block.set()+ await proxy.close()+ assert all(child.returncode is not None for child in children)+++async def bootstrap(remote, headers=None):+ response = await remote.client.get(remote.proxy.origin + "/webui/bootstrap", headers=(+ headers or {"X-Nanobot-Auth": remote.proxy.secret}+ ))+ assert response.status_code == 200, response.text+ return response.json()+++async def test_remote_credentials_never_leave_the_backend(remote):+ first, second = await asyncio.gather(bootstrap(remote), bootstrap(remote))+ assert first["token"] != second["token"]+ for issued in (first, second):+ assert ROOT not in json.dumps(issued)+ assert issued["token"] not in remote.services.tokens.issued_tokens+ assert issued["api_token"] not in remote.services.tokens.api_tokens+ assert issued["ws_url"].startswith(f"ws://127.0.0.1:{remote.proxy.port}/remote-session/")+ response = await remote.client.get(remote.proxy.origin + "/api/fixture", headers={+ "Authorization": "Bearer " + issued["api_token"], "Cookie": "injected=1",+ "X-Forwarded-User": "admin", "X-Forwarded-Host": "evil.test",+ })+ assert response.status_code == 200+ assert MEDIA not in response.text and ROOT not in response.text+ assert "set-cookie" not in response.headers+ request = remote.seen[-1]+ assert request.headers.get("Cookie") is None+ assert request.headers.get("X-Forwarded-User") is None+ assert request.headers.get("X-Forwarded-Host") is None+ assert request.headers["Authorization"] != "Bearer " + issued["api_token"]++[email protected]("query", ["?token={token}&token=evil", "?%74oken={token}&token=evil"])+async def test_ambiguous_auth_aliases_are_rejected(remote, query):+ issued = await bootstrap(remote)+ response = await remote.client.get(remote.proxy.origin + "/api/fixture" + query.format(token=issued["api_token"]))+ assert response.status_code == 401+++async def test_encoded_query_auth_and_case_insensitive_bearer(remote):+ issued = await bootstrap(remote, {"authorization": "bearer " + remote.proxy.secret})+ response = await remote.client.get(remote.proxy.origin + "/api/fixture?%74oken=" + issued["api_token"])+ assert response.status_code == 200+ assert "token=" not in remote.seen[-1].path+ response = await remote.client.get(remote.proxy.origin + "/api/fixture?token=" + issued["api_token"],+ headers={"Authorization": "Bearer " + issued["api_token"]})+ assert response.status_code == 401++[email protected]("headers", [+ {"Host": "evil.test"}, {"Origin": "https://evil.test"}, {"Origin": "null"},+])+async def test_foreign_browser_origin_rejected_even_with_local_secret(remote, headers):+ response = await remote.client.get(remote.proxy.origin + "/webui/bootstrap", headers={+ "X-Nanobot-Auth": remote.proxy.secret, **headers,+ })+ assert response.status_code == 403+ assert remote.seen == []+++async def test_custom_ws_path_multiple_tabs_and_binary_upload(remote):+ issued = await bootstrap(remote)+ url = issued["ws_url"] + "?token=" + issued["token"] + "&client_id=original-tab"+ async with connect(url, proxy=None, origin=remote.proxy.origin, max_size=64 * 1024 * 1024) as ws:+ ready = json.loads(await ws.recv())+ assert ready["query"] == ["original-tab"]+ assert ready["media"].startswith("/api/media/local/")+ binary = bytes(range(256)) * 8192+ await ws.send(binary)+ assert await ws.recv() == binary+ await ws.send(json.dumps({"text": "normal message", "nested": [1, 2]}))+ assert json.loads(await ws.recv())["text"] == "normal message"+ with pytest.raises(InvalidStatus) as rejected:+ async with connect(url, proxy=None):+ pass+ assert rejected.value.response.status_code == 401+ second = await bootstrap(remote)+ async with connect(second["ws_url"] + "?token=" + second["token"], proxy=None) as other:+ assert json.loads(await other.recv())["ready"] is True+++async def test_signed_media_wrapped_over_http_and_websocket_and_range_preserved(remote):+ issued = await bootstrap(remote)+ response = await remote.client.get(remote.proxy.origin + "/api/fixture", headers={+ "Authorization": "Bearer " + issued["api_token"],+ })+ local = response.json()["text"].split("(")[1][:-1]+ async with connect(issued["ws_url"] + "?token=" + issued["token"], proxy=None) as ws:+ assert json.loads(await ws.recv())["media"] == local+ response = await remote.client.get(remote.proxy.origin + local, headers={"Range": "bytes=0-4"})+ assert response.status_code == 206 and response.content == b"bytes"+ assert response.headers["content-range"] == "bytes 0-4/10"+ assert remote.seen[-1].headers["Range"] == "bytes=0-4"+ assert (await remote.client.get(remote.proxy.origin + MEDIA)).status_code == 401+++async def test_http_and_websocket_redirects_cannot_disclose_credentials(remote):+ response = await remote.client.get(remote.proxy.origin + "/redirect")+ assert response.status_code == 502+ assert ROOT not in response.text and "location" not in response.headers+ assert "set-cookie" not in response.headers+ remote.state.ws_redirect = True+ issued = await bootstrap(remote)+ with pytest.raises(InvalidStatus) as rejected:+ async with connect(issued["ws_url"] + "?token=" + issued["token"], proxy=None):+ pass+ assert rejected.value.response.status_code == 502+++async def test_pause_keeps_origin_and_revokes_grants_but_allows_renewal(remote):+ issued = await bootstrap(remote)+ await remote.proxy.pause()+ with socket.socket() as competitor:+ competitor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ with pytest.raises(OSError):+ competitor.bind(("127.0.0.1", remote.proxy.port))+ competitor.listen()+ assert (await remote.client.get(remote.proxy.origin + "/")).status_code == 503+ remote.tunnel.resume(remote.profile, remote.port, None)+ remote.proxy.resume(ROOT, remote.services.tokens.instance_id)+ assert (await remote.client.get(remote.proxy.origin + "/api/fixture", headers={+ "Authorization": "Bearer " + issued["api_token"],+ })).status_code == 401+ assert (await bootstrap(remote))["ws_url"] == issued["ws_url"]++[email protected](hasattr(socket, "SO_EXCLUSIVEADDRUSE"), reason="Unix immediate port takeover; Windows keeps exclusive ownership until release")+async def test_shutdown_replay_contains_only_dead_local_capabilities(remote):+ issued = await bootstrap(remote)+ origin, secret = remote.proxy.origin, remote.proxy.secret+ await remote.proxy.close()+ received = []++ async def replacement(reader, writer):+ received.append(await reader.readuntil(b"\r\n\r\n"))+ writer.write(b"HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\nConnection: close\r\n\r\n")+ await writer.drain()+ writer.close()+ await writer.wait_closed()++ # The same browser retries after the local gateway exits. The new process+ # receives credentials that the actual remote gateway cannot authenticate.+ async with await asyncio.start_server(replacement, "127.0.0.1", remote.proxy.port):+ await remote.client.get(origin + "/webui/bootstrap", headers={"X-Nanobot-Auth": secret})+ await remote.client.get(origin + "/api/fixture", headers={"Authorization": "Bearer " + issued["api_token"]})+ wire = b"".join(received).decode()+ assert ROOT not in wire+ assert not any(token in wire for token in remote.services.tokens.api_tokens)+ assert not any(token in wire for token in remote.services.tokens.issued_tokens)+ assert not remote.services.tokens.check_api_token(Request("/api/fixture", Headers({+ "Authorization": "Bearer " + issued["api_token"],+ })))+++async def test_shutdown_cancels_inflight_proxy_requests_before_closing_private_origin(remote):+ issued = await bootstrap(remote)+ pending = asyncio.create_task(remote.client.get(remote.proxy.origin + "/api/block", headers={+ "Authorization": "Bearer " + issued["api_token"],+ }))+ await asyncio.wait_for(remote.state.entered.wait(), 3)+ close = remote.tunnel.close++ async def guarded_close():+ assert not remote.proxy._tasks+ await close()++ remote.tunnel.close = guarded_close+ await asyncio.wait_for(remote.proxy.close(), 5)+ await asyncio.gather(pending, return_exceptions=True)+++async def test_configured_token_issuer_cannot_be_used_through_proxy(remote):+ remote.services.http.config.token_issue_path = "/assets/token"+ remote.proxy.resume(ROOT, remote.services.tokens.instance_id, "/assets/token")+ issued = await bootstrap(remote)+ for path in ("/assets/token", "/assets/token/", "/assets/token?token=" + issued["api_token"]):+ response = await remote.client.get(remote.proxy.origin + path, headers={"X-Nanobot-Auth": remote.proxy.secret})+ assert response.status_code == 403+ remote.services.http.config.token_issue_path = "/webui/bootstrap"+ assert (await remote.client.get(remote.proxy.origin + "/webui/bootstrap", headers={+ "X-Nanobot-Auth": remote.proxy.secret,+ })).status_code == 502+++async def test_expired_local_tokens_fail_and_renewal_recovers(remote):+ issued = await bootstrap(remote)+ for grants, token in ((remote.proxy._api, issued["api_token"]), (remote.proxy._ws, issued["token"])):+ grants[token] = replace(grants[token], expires=time.monotonic() - 1)+ assert (await remote.client.get(remote.proxy.origin + "/api/fixture", headers={+ "Authorization": "Bearer " + issued["api_token"],+ })).status_code == 401+ with pytest.raises(InvalidStatus) as rejected:+ async with connect(issued["ws_url"] + "?token=" + issued["token"], proxy=None):+ pass+ assert rejected.value.response.status_code == 401+ renewed = await bootstrap(remote)+ assert (await remote.client.get(remote.proxy.origin + "/api/fixture", headers={+ "Authorization": "Bearer " + renewed["api_token"],+ })).status_code == 200+++async def test_local_restart_rejects_all_old_credentials_and_changes_cache_scope(remote):+ issued = await bootstrap(remote)+ secret, port = remote.proxy.secret, remote.proxy.port+ await remote.proxy.close()+ tunnel = await open_tunnel(remote.profile, remote.port)+ # A new origin also works on Windows while its old exclusive socket lingers.+ remote.proxy = await RemoteProxy.open(tunnel, ROOT, remote.services.tokens.instance_id,+ excluded_ports={port})+ try:+ assert (await remote.client.get(remote.proxy.origin + "/webui/bootstrap", headers={+ "X-Nanobot-Auth": secret,+ })).status_code == 401+ assert (await remote.client.get(remote.proxy.origin + "/api/fixture", headers={+ "Authorization": "Bearer " + issued["api_token"],+ })).status_code == 401+ renewed = await bootstrap(remote)+ assert urlsplit(renewed["ws_url"]).path != urlsplit(issued["ws_url"]).path+ finally:+ await remote.proxy.close()+++async def test_remote_restart_invalidates_media_and_cache_scope(remote):+ issued = await bootstrap(remote)+ await remote.client.get(remote.proxy.origin + "/api/fixture", headers={+ "Authorization": "Bearer " + issued["api_token"],+ })+ assert remote.proxy._media_cache+ remote.proxy.resume(ROOT, "new-instance")+ assert not remote.proxy._media_cache+ assert remote.proxy._ws_path != issued["ws_path"]++[email protected]("path", ["/", "/custom/%61pi"])+async def test_custom_websocket_literal_paths_are_preserved(remote, path):+ remote.services.http.config.path = path+ issued = await bootstrap(remote)+ async with connect(issued["ws_url"] + "?token=" + issued["token"], proxy=None) as ws:+ assert json.loads(await ws.recv())["ready"] is True+ assert any(urlsplit(request.path).path == path for request in remote.seen)++[email protected]("prefix", ["https://images.example", "//cdn.example", "file:///tmp"])+async def test_external_media_like_urls_remain_unchanged(remote, prefix):+ external = prefix + MEDIA+ text = f" and "+ rewritten = remote.proxy._rewrite(text)+ assert external in rewritten+ assert rewritten.count("/api/media/local/") == 1+ assert len(remote.proxy._media_cache) == 1+++async def test_media_cache_eviction_preserves_old_links_and_new_media(remote):+ first = remote.proxy._rewrite(MEDIA)+ for index in range(10001):+ remote.proxy._rewrite(f"/api/media/BBBBBBBBBBBBBBBBBBBBBB/{index}")+ assert len(remote.proxy._media_cache) == 10000+ assert MEDIA not in remote.proxy._media_cache+ assert (await remote.client.get(remote.proxy.origin + first)).status_code == 206+ latest = remote.proxy._rewrite(MEDIA)+ assert (await remote.client.get(remote.proxy.origin + latest)).status_code == 206+ assert MEDIA.encode() not in base64.urlsafe_b64decode(first.rsplit("/", 1)[1])+ await remote.proxy.pause()+ remote.tunnel.resume(remote.profile, remote.port, None)+ remote.proxy.resume(ROOT, remote.services.tokens.instance_id)+ assert (await remote.client.get(remote.proxy.origin + first)).status_code == 206+++async def test_media_capabilities_reject_tampering_and_other_proxy_keys(remote):+ local = remote.proxy._rewrite(MEDIA)+ prefix, token = local.rsplit("/", 1)+ ciphertext = bytearray(base64.urlsafe_b64decode(token))+ ciphertext[40] ^= 1+ tampered = prefix + "/" + base64.urlsafe_b64encode(ciphertext).decode()+ assert (await remote.client.get(remote.proxy.origin + tampered)).status_code == 401+ remote.proxy.resume(ROOT, "replacement-gateway")+ assert (await remote.client.get(remote.proxy.origin + local)).status_code == 401diff --git a/tests/webui/test_remote_tunnel.py b/tests/webui/test_remote_tunnel.pynew file mode 100644index 000000000..85d97c69c--- /dev/null+++ b/tests/webui/test_remote_tunnel.py@@ -0,0 +1,283 @@+"""Real loopback sockets and subprocess pipes; no external host or credentials."""++import asyncio+import contextlib+import socket+import sys+from unittest.mock import MagicMock++import pytest+from websockets.asyncio.client import connect+from websockets.asyncio.server import serve++from nanobot.webui import remote_ssh+from nanobot.webui.remote_ssh import RemoteError, RemoteProfile, open_tunnel++PROFILE = RemoteProfile(name="Fixture", host="fixture.test")+ECHO = "import os\nwhile data := os.read(0, 65536):\n os.write(1, data)\n"+++def assert_owned(port):+ with socket.socket() as competitor:+ competitor.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ with pytest.raises(OSError):+ competitor.bind(("127.0.0.1", port))+ competitor.listen()+++def ssh_child(monkeypatch):+ real_spawn = asyncio.create_subprocess_exec+ children = []+ state = {"script": ECHO, "port": 0, "gate": None, "started": asyncio.Event()}+ monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "fixture-ssh")++ async def spawn(*args, **kwargs):+ assert args[-3:] == ("-W", "127.0.0.1:8765", "fixture.test")+ assert "-L" not in args+ assert_owned(state["port"])+ child = await real_spawn(sys.executable, "-u", "-c", state["script"], **kwargs)+ children.append(child)+ state["started"].set()+ if state["gate"] is not None:+ await state["gate"].wait()+ return child++ monkeypatch.setattr(asyncio, "create_subprocess_exec", spawn)+ return state, children+++async def test_large_binary_stream_and_half_close(ssh_child):+ state, children = ssh_child+ tunnel = await open_tunnel(PROFILE, 8765)+ state["port"] = tunnel.port+ reader, writer = await asyncio.open_connection("127.0.0.1", tunnel.port)+ payload = bytes(range(256)) * 4096++ async def upload():+ writer.write(payload)+ await writer.drain()+ writer.write_eof()++ try:+ _, response = await asyncio.wait_for(asyncio.gather(upload(), reader.read()), 10)+ assert response == payload+ assert_owned(tunnel.port)+ finally:+ writer.close()+ await writer.wait_closed()+ await tunnel.close()+ assert children and all(child.returncode is not None for child in children)+++async def test_http_keepalive_and_chunked_upload(ssh_child):+ import httpx++ state, _ = ssh_child+ state["script"] = """+import sys+stream = sys.stdin.buffer+while stream.readline():+ headers = {}+ while (line := stream.readline()) not in (b'\\r\\n', b''):+ key, value = line.decode().split(':', 1)+ headers[key.lower()] = value.strip()+ if headers.get('transfer-encoding') == 'chunked':+ body = b''+ while size := int(stream.readline(), 16):+ body += stream.read(size)+ stream.read(2)+ stream.read(2)+ else:+ body = stream.read(int(headers.get('content-length', '0')))+ sys.stdout.buffer.write(b'HTTP/1.1 200 OK\\r\\nContent-Length: ' + str(len(body)).encode() + b'\\r\\n\\r\\n' + body)+ sys.stdout.buffer.flush()+"""+ tunnel = await open_tunnel(PROFILE, 8765)+ state["port"] = tunnel.port++ async def chunks():+ for _ in range(4):+ yield b"chunk" * 10000++ try:+ async with httpx.AsyncClient(trust_env=False) as client:+ base = f"http://127.0.0.1:{tunnel.port}"+ response = await client.post(base, content=chunks())+ assert response.content == b"chunk" * 40000+ response = await client.post(base, content=b"keepalive")+ assert response.content == b"keepalive"+ finally:+ await tunnel.close()+++async def test_websocket_upgrade_and_bidirectional_messages(ssh_child):+ state, _ = ssh_child++ async def echo(websocket):+ async for message in websocket:+ await websocket.send(message)++ async with serve(echo, "127.0.0.1", 0) as server:+ port = server.sockets[0].getsockname()[1]+ state["script"] = f"""+import os, socket, threading+upstream = socket.create_connection(('127.0.0.1', {port}))+def upload():+ while data := os.read(0, 65536):+ upstream.sendall(data)+ upstream.shutdown(socket.SHUT_WR)+threading.Thread(target=upload, daemon=True).start()+while data := upstream.recv(65536):+ os.write(1, data)+"""+ tunnel = await open_tunnel(PROFILE, 8765)+ state["port"] = tunnel.port+ try:+ async with connect(f"ws://127.0.0.1:{tunnel.port}", proxy=None) as websocket:+ for message in ["hello", bytes(range(256)) * 1000, "still connected"]:+ await websocket.send(message)+ assert await asyncio.wait_for(websocket.recv(), 5) == message+ finally:+ await tunnel.close()+++async def test_pause_keeps_origin_reserved_and_resume_reuses_it(ssh_child, tmp_path):+ state, children = ssh_child+ tunnel = await open_tunnel(PROFILE, 8765)+ state["port"] = tunnel.port+ reader, writer = await asyncio.open_connection("127.0.0.1", tunnel.port)+ try:+ writer.write(b"first")+ await writer.drain()+ assert await asyncio.wait_for(reader.readexactly(5), 5) == b"first"+ await tunnel.pause()+ assert not tunnel.active+ assert_owned(tunnel.port)+ assert all(child.returncode is not None for child in children)+ assert await reader.read() == b""+ blocked_reader, blocked_writer = await asyncio.open_connection("127.0.0.1", tunnel.port)+ try:+ assert await asyncio.wait_for(blocked_reader.read(), 2) == b""+ assert len(children) == 1+ finally:+ blocked_writer.close()+ await blocked_writer.wait_closed()+ tunnel.resume(PROFILE, 8765, tmp_path / "missing-known-hosts")+ resumed_reader, resumed_writer = await asyncio.open_connection("127.0.0.1", tunnel.port)+ try:+ resumed_writer.write(b"second")+ await resumed_writer.drain()+ assert await asyncio.wait_for(resumed_reader.readexactly(6), 5) == b"second"+ finally:+ resumed_writer.close()+ await resumed_writer.wait_closed()+ finally:+ writer.close()+ await writer.wait_closed()+ await tunnel.close()+ assert all(child.returncode is not None for child in children)+++async def test_failed_ssh_never_releases_origin_or_forwards_to_competitor(ssh_child):+ state, children = ssh_child+ state["script"] = "import sys\nsys.stderr.write('Permission denied\\n' + 'x' * 100000)\nsys.exit(255)"+ tunnel = await open_tunnel(PROFILE, 8765)+ state["port"] = tunnel.port+ reader, writer = await asyncio.open_connection("127.0.0.1", tunnel.port)+ try:+ assert await asyncio.wait_for(reader.read(), 5) == b""+ await asyncio.gather(*tunnel._streams)+ assert tunnel.error == "ssh_auth_failed"+ assert_owned(tunnel.port)+ await tunnel.pause()+ assert_owned(tunnel.port)+ finally:+ writer.close()+ await writer.wait_closed()+ await tunnel.close()+ assert children[0].returncode == 255+++async def test_cancellation_during_subprocess_creation_reaps_child(ssh_child):+ state, children = ssh_child+ state["gate"] = asyncio.Event()+ tunnel = await open_tunnel(PROFILE, 8765)+ state["port"] = tunnel.port+ reader, writer = await asyncio.open_connection("127.0.0.1", tunnel.port)+ try:+ await asyncio.wait_for(state["started"].wait(), 5)+ paused = asyncio.create_task(tunnel.pause())+ await asyncio.sleep(0)+ assert not paused.done()+ assert_owned(tunnel.port)+ state["gate"].set()+ await asyncio.wait_for(paused, 5)+ assert children[0].returncode is not None+ assert await reader.read() == b""+ finally:+ state["gate"].set()+ writer.close()+ await writer.wait_closed()+ await tunnel.close()+++async def test_cancellation_before_relay_starts_closes_client():+ tunnel = remote_ssh.Tunnel([], 0)+ tunnel.server = MagicMock(is_serving=lambda: True)+ writer = MagicMock()+ tunnel.accept(asyncio.StreamReader(), writer)+ await tunnel.pause()+ writer.close.assert_called()+ assert not tunnel._streams+++async def test_occupied_port_is_rejected_even_with_reuseaddr(monkeypatch):+ monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "fixture-ssh")+ with socket.socket() as owner:+ owner.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)+ owner.bind(("127.0.0.1", 0))+ owner.listen()+ with pytest.raises(RemoteError, match="local_port_in_use"):+ await open_tunnel(PROFILE, 8765, local_port=owner.getsockname()[1])+++def test_windows_listener_uses_exclusive_bind(monkeypatch):+ listener = MagicMock()+ listener.getsockname.return_value = ("127.0.0.1", 24000)+ monkeypatch.setattr(remote_ssh.socket, "socket", lambda: listener)+ monkeypatch.setattr(remote_ssh.socket, "SO_EXCLUSIVEADDRUSE", 123456, raising=False)+ assert remote_ssh._listen(24000, set()) is listener+ listener.setsockopt.assert_called_once_with(socket.SOL_SOCKET, 123456, 1)+ listener.bind.assert_called_once_with(("127.0.0.1", 24000))+++def test_new_origin_skips_retired_ports_without_releasing_them_early(monkeypatch):+ retired, fresh = MagicMock(), MagicMock()+ retired.getsockname.return_value = ("127.0.0.1", 24000)+ fresh.getsockname.return_value = ("127.0.0.1", 24001)++ def sockets():+ yield retired+ retired.close.assert_not_called()+ yield fresh++ candidates = sockets()+ monkeypatch.setattr(remote_ssh.socket, "socket", lambda: next(candidates))+ assert remote_ssh._listen(0, {24000}) is fresh+ retired.close.assert_called_once()+ fresh.close.assert_not_called()+++async def test_listener_is_released_only_on_final_close(monkeypatch):+ monkeypatch.setattr(remote_ssh.shutil, "which", lambda _: "fixture-ssh")+ tunnel = await open_tunnel(PROFILE, 8765)+ try:+ assert_owned(tunnel.port)+ await tunnel.pause()+ assert_owned(tunnel.port)+ finally:+ await tunnel.close()+ with contextlib.closing(socket.socket()) as replacement:+ replacement.bind(("127.0.0.1", tunnel.port))+ replacement.listen()diff --git a/tests/webui/test_ssh_config.py b/tests/webui/test_ssh_config.pyindex 785d36e9b..ae2c9ff73 100644--- a/tests/webui/test_ssh_config.py+++ b/tests/webui/test_ssh_config.py@@ -75,7 +75,7 @@ def test_unresolvable_includes_and_invalid_lines_do_not_hide_other_hosts(ssh_homassert result["incomplete"][email protected]("contents", [b"\xff", b"x" * 262145])[email protected]("contents", [b"\xff", b"x" * 262145], ids=["invalid-utf8", "oversized"])def test_unreadable_or_oversized_custom_config_is_an_explicit_error(ssh_home, contents):path = ssh_home / "config"path.write_bytes(contents)@@ -116,7 +116,7 @@ def test_invalid_paths_rejected_before_reading(path):@pytest.mark.parametrize(("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")+ config.write_text("Host example-test\n HostName 192.0.2.10\n User tester\n Port 2222\n IdentityFile /tmp/test-key\n RemoteCommand tmux attach\n RequestTTY force\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],@@ -125,6 +125,8 @@ def test_system_ssh_inherits_config_port_user_and_identity(ssh_home, override, eassert settings["port"] == expectedassert settings["user"] == "tester"assert settings["identityfile"] == "/tmp/test-key"+ assert settings.get("remotecommand", "none") == "none"+ assert settings["requesttty"] == "false"async def test_manager_discovery_does_not_save_profiles_or_connect(ssh_home):diff --git a/webui/src/App.tsx b/webui/src/App.tsxindex 3b7ffd18f..d356d8d77 100644--- a/webui/src/App.tsx+++ b/webui/src/App.tsx@@ -1154,6 +1154,10 @@ function Shell({const [sidebarWidth, setSidebarWidth] = useState(readSidebarWidth);const [sidebarDragging, setSidebarDragging] = useState(false);const [mobileSidebarOpen, setMobileSidebarOpen] = useState(false);+ useEffect(() => {+ // The drawer portals outside the local host panel; don't leave it over a remote view.+ if (!localActive) setMobileSidebarOpen(false);+ }, [localActive]);const mobileSidebarRef = useRef<HTMLDivElement>(null);const [sessionSearchOpen, setSessionSearchOpen] = useState(false);const mobileWorkbench = useMediaQuery("(max-width: 767px)");@@ -1287,6 +1291,7 @@ function Shell({useEffect(() => {const applyRoute = () => {const route = readShellRoute();+ if (route.view === "remote") setMobileSidebarOpen(false);if (currentShellRouteRef.current.view === "settings" && route.view !== "settings" && settingsExitGuardRef.current) {writeShellRoute(currentShellRouteRef.current, true);settingsExitGuardRef.current(() => {@@ -2131,12 +2136,6 @@ 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" });@@ -2733,11 +2732,10 @@ function Shell({onOpenApps,onOpenAutomations,onOpenChannels,- onOpenRemoteConnections,onOpenSkills,onSettingsIntent,onOpenSearch: onOpenSessionSearch,- activeUtility: view === "apps" || view === "automations" || view === "skills" || view === "channels" || view === "remote" ? view : null,+ activeUtility: view === "apps" || view === "automations" || view === "skills" || view === "channels" ? view : null,onToggleArchived,pinnedKeys: sidebarPinnedTabKeys,archivedKeys: sidebarArchivedTabKeys,diff --git a/webui/src/components/Sidebar.tsx b/webui/src/components/Sidebar.tsxindex 3f4752811..de8cbb452 100644--- a/webui/src/components/Sidebar.tsx+++ b/webui/src/components/Sidebar.tsx@@ -9,7 +9,6 @@ import {Brain,CalendarClock,MessageCircle,- MonitorUp,PanelLeftClose,Search,Settings,@@ -24,7 +23,6 @@ import {type SidebarPaneGroup,} from "@/components/ChatList";import { HostSwitcher } from "@/components/remote/HostSwitcher";-import { useRemoteConnections } from "@/components/remote/RemoteInstances";import {SIDEBAR_SELECTION_ACTION_ITEM_CLASS,SidebarSelectionHighlight,@@ -70,10 +68,9 @@ interface SidebarProps {onOpenSkills: () => void;onOpenAutomations: () => void;onOpenChannels: () => void;- onOpenRemoteConnections?: () => void;onSettingsIntent?: () => void;onOpenSearch: () => void;- activeUtility?: "apps" | "skills" | "automations" | "channels" | "remote" | null;+ activeUtility?: "apps" | "skills" | "automations" | "channels" | null;onToggleArchived: () => void;onCollapse?: () => void;onExpand?: () => void;@@ -111,7 +108,6 @@ 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);@@ -257,16 +253,6 @@ 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 ? (<SidebarActionButtoncollapsed={collapsed}diff --git a/webui/src/components/remote/HostSwitcher.tsx b/webui/src/components/remote/HostSwitcher.tsxindex 47066d235..1aeb113c3 100644--- a/webui/src/components/remote/HostSwitcher.tsx+++ b/webui/src/components/remote/HostSwitcher.tsx@@ -1,5 +1,5 @@import { createContext, useContext, useEffect, useRef, useState } from "react";-import { Check, ChevronUp, CircleAlert, Laptop, Loader2, Server, Settings2, X } from "lucide-react";+import { Check, ChevronUp, CircleAlert, Laptop, Loader2, Search, Server, Settings2, X } from "lucide-react";import { useTranslation } from "react-i18next";import { Button } from "@/components/ui/button";import { ConnectionBadge } from "@/components/ConnectionBadge";@@ -16,6 +16,7 @@ export interface HostPicker {localName: string;currentId: string | null;profiles: { id: string; name: string; host: string; ready: boolean }[];+ recentIds: string[];pending: { id: string; name: string } | null;error: string;offline: boolean;@@ -32,30 +33,90 @@ interface EmbeddedPicker extends EmbeddedHost {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)]"+ portalContainer={portalContainer} className="flex w-64 max-w-[calc(100vw-1.5rem)] flex-col overflow-hidden"+ onEscapeKeyDown={(event) => { if (event.isComposing) event.preventDefault(); }}onCloseAutoFocus={(event) => { event.preventDefault(); picker.restoreFocus(); }}>- <DropdownMenuLabel>{t("remote.switchHost")}</DropdownMenuLabel>- <DropdownMenuItem onSelect={() => picker.select(null)} className="gap-2.5">+ <HostMenuItems picker={picker} />+ </DropdownMenuContent>;+}++/** Mounted with the menu so every opening starts with a fresh, stable list. */+function HostMenuItems({ picker }: { picker: HostPicker }) {+ const { t } = useTranslation();+ const [searchable] = useState(() => picker.profiles.length > 5);+ const [query, setQuery] = useState("");+ const [order] = useState(() => [picker.currentId, ...picker.recentIds]);+ const search = useRef<HTMLInputElement>(null);+ const list = useRef<HTMLDivElement>(null);+ const needle = query.trim().toLocaleLowerCase();+ const matches = (...values: string[]) => values.some((value) => value.toLocaleLowerCase().includes(needle));+ const showLocal = matches(t("remote.local"), picker.localName);+ const profiles = picker.profiles.filter(({ name, host }) => matches(name, host));+ if (searchable) {+ const rank = (id: string) => { const index = order.indexOf(id); return index < 0 ? order.length : index; };+ profiles.sort((a, b) => rank(a.id) - rank(b.id));+ }+ useEffect(() => {+ // Don't summon the software keyboard when opening the picker on a touch device.+ if (!searchable || window.matchMedia("(pointer: coarse)").matches) return;+ const frame = requestAnimationFrame(() => search.current?.focus({ preventScroll: true }));+ return () => cancelAnimationFrame(frame);+ }, [searchable]);++ return <div className="flex min-h-0 flex-col"+ onPointerMoveCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }}+ onPointerOutCapture={(event) => { if (document.activeElement === search.current) event.preventDefault(); }}+ onKeyDownCapture={(event) => {+ if (!searchable) return;+ if (event.nativeEvent.isComposing) { event.stopPropagation(); return; }+ const items = Array.from(event.currentTarget.querySelectorAll<HTMLElement>('[role="menuitem"]'));+ if (event.target === search.current) {+ // Keep spaces and IME input out of Radix's menu typeahead.+ if (event.key !== "Escape") event.stopPropagation();+ if (event.key === "ArrowDown" || event.key === "ArrowUp" || event.key === "Tab") {+ event.preventDefault();+ (event.key === "ArrowUp" || event.shiftKey ? items.at(-1) : items[0])?.focus();+ } else if (event.key === "Enter") {+ event.preventDefault();+ if (needle) list.current?.querySelector<HTMLElement>('[role="menuitem"]')?.click();+ }+ } else if (event.key === "Tab" || (event.key === "ArrowUp" && event.target === items[0])) {+ event.preventDefault(); event.stopPropagation(); search.current?.focus();+ }+ }}>+ {searchable ? <div className="flex shrink-0 items-center gap-2 px-2.5 pb-2 pt-1.5">+ <Search aria-hidden className="h-4 w-4 shrink-0 text-muted-foreground" />+ <input ref={search} aria-label={t("remote.searchHosts")} placeholder={t("remote.searchHosts")}+ value={query} onChange={(event) => setQuery(event.target.value)} autoComplete="off" spellCheck={false}+ className="h-7 min-w-0 flex-1 bg-transparent text-[13px] outline-none placeholder:text-muted-foreground" />+ </div> : <DropdownMenuLabel className="shrink-0">{t("remote.switchHost")}</DropdownMenuLabel>}+ <div ref={list} role="group" aria-label={t("remote.switchHost")}+ className="min-h-0 overflow-y-auto overscroll-contain scrollbar-thin scrollbar-track-transparent">+ {showLocal && <DropdownMenuItem onSelect={() => picker.select(null)} className="gap-2.5" aria-current={!picker.currentId || undefined}><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">+ </DropdownMenuItem>}+ {showLocal && !!profiles.length && <DropdownMenuSeparator />}+ {profiles.map((profile) => <DropdownMenuItem key={profile.id} onSelect={() => picker.select(profile.id)} className="gap-2.5"+ title={`${profile.name} · ${profile.host}`} aria-current={picker.currentId === profile.id || undefined}><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}+ {picker.pending?.id === profile.id ? <Loader2 className="h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" /> : picker.currentId === profile.id ? <Check className="h-4 w-4 shrink-0" />+ : profile.ready ? <span className="shrink-0 text-[11px] text-muted-foreground">{t("remote.ready")}</span> : null}</DropdownMenuItem>)}+ {!showLocal && !profiles.length && <p role="status" className="px-2.5 py-6 text-center text-xs text-muted-foreground">{t("remote.noMatchingHosts")}</p>}+ </div>+ <div className="shrink-0">{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>+ {picker.error && <div role="alert" className="flex items-start gap-2 px-2.5 py-2 text-xs leading-5 text-foreground">+ <CircleAlert aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" /><span>{picker.error}<button className="ml-2 underline underline-offset-2" onClick={picker.clearError}>{t("common.close")}</button></span></div>}<DropdownMenuSeparator /><DropdownMenuItem className="gap-2.5" onSelect={picker.manage}><Settings2 className="h-4 w-4 text-muted-foreground" />{t("remote.manageConnections")}</DropdownMenuItem>- </DropdownMenuContent>;+ </div>+ </div>;}/** Shared sidebar control. Remote frames can only open the trusted shell's menu. */@@ -70,11 +131,15 @@ export function HostSwitcher({ collapsed = false, portalContainer }: { collapsedconst 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";+ // A failed switch describes the destination, not the still-active connection.+ const failed = !!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}`)}`;+ // The old host stays interactive until the new one is ready. Keep its identity+ // visible; progress belongs to the target's row and the accessible status.+ const label = picker.name;+ const current = `${picker.name} · ${picker.hostname} · ${t(failed ? "remote.offline" : `connection.${status}`)}`;+ const detail = pendingName ? `${current} · ${t("remote.preparing", { name: pendingName })}` : current;+ const title = picker.error ? `${detail} — ${picker.error}` : detail;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")}@@ -83,15 +148,16 @@ export function HostSwitcher({ collapsed = false, portalContainer }: { collapsedif (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" />+ {waiting ? <Loader2 className="h-4 w-4 animate-spin motion-reduce:animate-none" /> : failed ? <CircleAlert className="h-4 w-4" />: 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>+ <span className="sr-only" role="status">{detail}</span></Button>;if (!shell) return button;- return <DropdownMenu><DropdownMenuTrigger asChild>{button}</DropdownMenuTrigger><HostMenuContent picker={shell} portalContainer={portalContainer} /></DropdownMenu>;+ // The mobile sidebar already owns the modal lock; a nested lock can outlive it on navigation.+ return <DropdownMenu modal={!portalContainer}><DropdownMenuTrigger asChild>{button}</DropdownMenuTrigger><HostMenuContent picker={shell} portalContainer={portalContainer} /></DropdownMenu>;}/** Parent-owned menu anchored to the active remote sidebar, never inside its DOM. */diff --git a/webui/src/components/remote/PairRouteSettings.tsx b/webui/src/components/remote/PairRouteSettings.tsxnew file mode 100644index 000000000..758a500dc--- /dev/null+++ b/webui/src/components/remote/PairRouteSettings.tsx@@ -0,0 +1,58 @@+import { useEffect, useRef, useState } from "react";+import { AlertCircle, Check, Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { useClient } from "@/providers/ClientProvider";+import { remoteAction } from "@/lib/remote-instances";+import { useRemoteConnections } from "./RemoteInstances";++/** An explicit escape hatch for a VPN/bound-interface route, not a new SSH form. */+export function PairRouteSettings({ id, onSaved }: { id: string; onSaved?: () => void }) {+ const { t } = useTranslation();+ const { client } = useClient();+ const connections = useRemoteConnections();+ const hasSavedRoute = !!connections?.directory?.profiles.find((profile) => profile.id === id)?.ssh_config;+ const [route, setRoute] = useState(hasSavedRoute ? "saved" : "direct");+ const [original, setOriginal] = useState(route);+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");+ const [saved, setSaved] = useState(false);+ const alive = useRef(true);+ useEffect(() => { alive.current = true; return () => { alive.current = false; }; }, []);+ const save = async () => {+ setBusy(true); setError(""); setSaved(false);+ try {+ await remoteAction(client, "pair_route", { id, route_id: route === "direct" ? "" : route });+ if (!alive.current) return;+ // Saving and refreshing are different outcomes. Never invite a second save+ // merely because the directory refresh failed after the write succeeded.+ setOriginal(route); setSaved(true);+ try { await connections?.refresh(); }+ catch {+ if (alive.current) setError(t("remote.errors.directory_unavailable"));+ return;+ }+ if (alive.current) onSaved?.();+ } catch (reason) {+ if (alive.current) setError(t(`remote.errors.${reason instanceof Error ? reason.message : "unknown"}`, { defaultValue: t("remote.errors.unknown") }));+ } finally { if (alive.current) setBusy(false); }+ };+ return <div className="space-y-3">+ <p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.routeHint")}</p>+ <Select value={route} onValueChange={(value) => { setRoute(value); setError(""); setSaved(false); }} disabled={busy}><SelectTrigger aria-label={t("remote.pair.route")}><SelectValue /></SelectTrigger>+ <SelectContent>+ {hasSavedRoute && <SelectItem value="saved">{t("remote.pair.savedRoute")}</SelectItem>}+ <SelectItem value="direct">{t("remote.pair.direct")}</SelectItem>+ {connections?.directory?.profiles.filter((profile) => !profile.paired).map((profile) => <SelectItem key={profile.id} value={profile.id}>{profile.name}</SelectItem>)}+ </SelectContent>+ </Select>+ {error && <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{error}</p>}+ <div className="flex items-center justify-end gap-3">+ {saved && <p role="status" className="mr-auto flex items-center gap-1.5 text-xs text-muted-foreground"><Check aria-hidden className="h-3.5 w-3.5" />{t("remote.saved")}</p>}+ <Button size="sm" disabled={busy || route === original || route === "saved"} aria-busy={busy} onClick={() => { void save(); }}>+ {busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" />}{t(busy ? "remote.saving" : "remote.save")}+ </Button>+ </div>+ </div>;+}diff --git a/webui/src/components/remote/QuickPairSetup.tsx b/webui/src/components/remote/QuickPairSetup.tsxnew file mode 100644index 000000000..8ffa004e7--- /dev/null+++ b/webui/src/components/remote/QuickPairSetup.tsx@@ -0,0 +1,210 @@+import { useEffect, useId, useRef, useState } from "react";+import { AlertCircle, ArrowLeft, Check, ChevronDown, Copy, Loader2 } from "lucide-react";+import { useTranslation } from "react-i18next";+import { Button } from "@/components/ui/button";+import { DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { Disclosure, DisclosureContent } from "@/components/ui/disclosure";+import { Textarea } from "@/components/ui/textarea";+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";+import { useClient } from "@/providers/ClientProvider";+import { copyTextToClipboard } from "@/lib/clipboard";+import { remoteAction } from "@/lib/remote-instances";+import { pairingReturnOrigin, type PairReturn } from "@/lib/remote-pair-return";+import { useRemoteConnections } from "./RemoteInstances";+import { PairRouteSettings } from "./PairRouteSettings";++type Request = { id: string; command: string; expires: number };+type Preview = { id: string; host: string; hostname: string; fingerprint: string; authorized_until: number; revoke_command: string };++/** Public invitation → encrypted receipt → explicit confirmation. No private key inputs. */+export function QuickPairSetup({ returned, onSSH, onClose }: { returned?: PairReturn | null; onSSH: () => void; onClose: () => void }) {+ const { t } = useTranslation();+ const { client } = useClient();+ const connections = useRemoteConnections();+ const [request, setRequest] = useState<Request | null>(returned ? { id: returned.id, command: "", expires: 0 } : null);+ const [preview, setPreview] = useState<Preview | null>(null);+ const [code, setCode] = useState(returned?.code || "");+ const [saved, setSaved] = useState("");+ const [busy, setBusy] = useState(false);+ const [busyVisible, setBusyVisible] = useState(false);+ const [error, setError] = useState("");+ const [copied, setCopied] = useState(false);+ const [expired, setExpired] = useState(false);+ const [manual, setManual] = useState(false);+ const [panel, setPanel] = useState<"command" | "help" | null>(null);+ const alive = useRef(true);+ const initialized = useRef(false);+ const requestId = useRef(returned?.id || "");+ const manualInput = useRef<HTMLTextAreaElement>(null);+ const focusManual = useRef(false);+ const codeId = useId();+ const panelId = useId();++ useEffect(() => {+ if (!busy) { setBusyVisible(false); return; }+ // Fast local preparation should not flash a loading label or move the dialog.+ const timer = window.setTimeout(() => setBusyVisible(true), 200);+ return () => window.clearTimeout(timer);+ }, [busy]);++ useEffect(() => {+ alive.current = true;+ return () => {+ alive.current = false;+ // A link opens in a new tab. Closing/reloading the originating page must+ // not destroy its key before the new page can validate the receipt.+ // Pending invitations are bounded and expire in PairStore.+ };+ }, [client]);+ useEffect(() => {+ if (!request?.expires || saved) return;+ const timer = window.setTimeout(() => setExpired(true), Math.max(0, request.expires * 1000 - Date.now()));+ return () => window.clearTimeout(timer);+ }, [request, saved]);++ const run = async (action: () => Promise<void>) => {+ setBusy(true); setError("");+ try { await action(); }+ catch (reason) {+ if (alive.current) setError(t(`remote.errors.${reason instanceof Error ? reason.message : "unknown"}`, { defaultValue: t("remote.errors.unknown") }));+ } finally { if (alive.current) setBusy(false); }+ };+ const start = () => run(async () => {+ if (requestId.current) await remoteAction(client, "pair_cancel", { id: requestId.current });+ const result = await remoteAction<Request>(client, "pair_start", { return_origin: pairingReturnOrigin() });+ if (!alive.current) { await remoteAction(client, "pair_cancel", { id: result.id }); return; }+ requestId.current = result.id;+ setRequest(result); setPreview(null); setCode(""); setCopied(false); setExpired(false); setManual(false); setPanel(null);+ });+ const review = () => run(async () => {+ if (!request) return;+ const result = await remoteAction<Preview>(client, "pair_preview", { id: request.id, code });+ if (alive.current) setPreview(result);+ });+ const connect = () => run(async () => {+ if (!request || !preview || !connections) return;+ let id = saved;+ if (!id) {+ const result = await remoteAction<{ id: string }>(client, "pair_finish", { id: request.id, code });+ id = result.id;+ if (!alive.current) return;+ setSaved(id);+ }+ await connections.refresh();+ if (!alive.current) return;+ await connections.connect(id, () => alive.current);+ if (alive.current) onClose();+ });++ useEffect(() => {+ if (initialized.current) return;+ initialized.current = true;+ if (returned) void review();+ else void start();+ // One invitation per mounted dialog, never one per re-render. The returned+ // receipt is reviewed only; saving/connecting still requires a user click.+ }, []);+ const copyCommand = () => {+ if (!request) return;+ void copyTextToClipboard(request.command).then((ok) => {+ if (!alive.current || requestId.current !== request.id || Date.now() >= request.expires * 1000) return;+ if (ok) { setCopied(true); setError(""); setPanel(null); }+ else { setPanel("command"); setError(t("remote.pair.copyFailed")); }+ });+ };+ const restartAvailable = !saved && (expired || (!!error && !request?.command && !preview));+ const reviewingReturn = !!returned && !request?.command && !preview && !manual && !restartAvailable;+ const title = preview ? "remote.pair.confirmTitle" : reviewingReturn ? "remote.pair.review" : restartAvailable ? "remote.add"+ : manual ? "remote.pair.code" : copied ? "remote.pair.copiedTitle" : "remote.add";+ const description = preview || reviewingReturn ? "remote.pair.confirmLinkDescription" : restartAvailable ? "remote.pair.introHint"+ : manual ? "remote.pair.codeHint" : copied ? "remote.pair.afterCopyHint" : "remote.pair.introHint";+ const showCopied = copied && !manual && !preview && !restartAvailable;+ const showBusy = busy && busyVisible;+ const actionLabel = restartAvailable ? "remote.pair.restart" : reviewingReturn ? "remote.pair.review" : preview ? saved ? "remote.retry" : "remote.connect"+ : manual ? "remote.pair.review" : copied ? "remote.pair.copyAgain" : "remote.pair.copy";+ const busyLabel = preview ? "remote.connecting" : !restartAvailable && (manual || returned)+ ? "remote.pair.checkingLink" : "remote.pair.preparing";++ return <>+ <DialogHeader className="shrink-0 pr-5 text-left">+ <div aria-live="polite" aria-atomic="true" className="space-y-1.5">+ <DialogTitle className="flex min-h-5 items-center gap-2">+ {showCopied && <Check aria-hidden="true" className="h-5 w-5 shrink-0 motion-safe:animate-in motion-safe:fade-in duration-150" />}+ {t(title)}+ </DialogTitle>+ <div className="grid">+ <DialogDescription className="col-start-1 row-start-1">{t(description)}</DialogDescription>+ {/* Reserve the longer instruction in either state, including translated text.+ It is only a layout spacer, never a second screen-reader announcement. */}+ {!preview && !manual && !reviewingReturn && <p aria-hidden="true" className="invisible pointer-events-none col-start-1 row-start-1 select-none text-sm">+ {t(showCopied ? "remote.pair.introHint" : "remote.pair.afterCopyHint")}+ </p>}+ </div>+ </div>+ </DialogHeader>+ <div className="-mx-1 min-h-0 space-y-4 overflow-y-auto overscroll-contain px-1">+ {preview ? <div className="space-y-4">+ <div className="rounded-2xl bg-muted/50 p-4">+ <p className="font-medium">{preview.hostname}</p>+ <p className="mt-1 break-all text-xs text-muted-foreground">{preview.host}</p>+ </div>+ <p className="text-[13px] leading-5">{t("remote.pair.access")}</p>+ <p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.expiry", { date: new Date(preview.authorized_until * 1000).toLocaleDateString() })}</p>+ <Disclosure className="text-xs text-muted-foreground" summaryClassName="flex min-h-9 items-center gap-2 rounded-xl focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ summary={<><ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />{t("remote.pair.security")}</>}>+ <p className="my-2 leading-5">{t("remote.pair.fingerprint")}</p><code className="block break-all">{preview.fingerprint}</code>+ <p className="mb-2 mt-4 leading-5">{t("remote.pair.revoke")}</p><code className="block break-all">{preview.revoke_command}</code>+ </Disclosure>+ {saved && error && <div className="space-y-2"><p className="text-xs leading-5 text-muted-foreground">{t("remote.pair.retryHint")}</p>+ <Disclosure summaryClassName="flex min-h-9 items-center gap-2 rounded-xl text-xs text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring" contentClassName="pt-2"+ summary={<><ChevronDown aria-hidden className="h-3.5 w-3.5 shrink-0 transition-transform group-data-[state=open]/disclosure:rotate-180 motion-reduce:transition-none" />{t("remote.pair.route")}</>}><PairRouteSettings id={saved} /></Disclosure>+ </div>}+ </div> : restartAvailable ? null : <>+ {manual && <div className="space-y-2"><label htmlFor={codeId} className="sr-only">{t("remote.pair.code")}</label>+ <Textarea ref={manualInput} id={codeId} value={code} onChange={(event) => { setCode(event.target.value); setError(""); }} placeholder="nbpc1.…" autoComplete="off" spellCheck={false} disabled={busy || expired} className="min-h-20 resize-none break-all font-mono text-xs" />+ </div>}+ <div>+ <DisclosureContent id={panelId} open={panel === "command" && !!request?.command}>+ <div className="rounded-2xl bg-muted/50 p-3">+ <code className="block max-h-32 select-text overflow-y-auto break-all text-[11px] leading-5" aria-label={t("remote.pair.command")}>{request?.command}</code>+ </div>+ </DisclosureContent>+ <DisclosureContent open={panel === "help"}>+ <div className="space-y-2 rounded-2xl bg-muted/50 p-3 text-xs leading-5 text-muted-foreground">+ <p className="font-medium text-foreground">{t("remote.pair.helpTitle")}</p>+ <p>{t("remote.pair.requirements")}</p>+ <p>{t("remote.pair.runHint")}</p>+ <p>{t("remote.pair.validityHint")}</p>+ </div>+ </DisclosureContent>+ </div>+ </>}+ {expired && !saved && <p role="status" className="text-xs leading-5 text-muted-foreground">{t("remote.pair.expired")}</p>}+ {error && <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{error}</p>}+ </div>+ <div className={preview ? "flex shrink-0 flex-col-reverse gap-2 pt-1 sm:flex-row sm:items-center sm:justify-between" : "flex shrink-0 flex-col gap-2 pt-1"}>+ {preview && (!saved ? <Button variant="ghost" disabled={busy} onClick={() => { setPreview(null); setError(""); if (!request?.command) setManual(true); }}><ArrowLeft className="mr-1 h-4 w-4" />{t("remote.back")}</Button>+ : <Button variant="ghost" onClick={() => { connections?.cancel(); onClose(); }}>{t("common.cancel")}</Button>+ )}+ <Button variant={showCopied ? "outline" : "default"} className={showCopied ? "bg-transparent" : undefined} aria-label={t(showBusy ? busyLabel : actionLabel)} aria-busy={busy} disabled={busy || (!restartAvailable && (!request || (!preview && (manual ? !code.trim() : !request.command))))} onClick={() => { if (restartAvailable) void start(); else if (preview) void connect(); else if (manual) void review(); else copyCommand(); }}>+ {showBusy ? <Loader2 aria-hidden="true" className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" /> : !restartAvailable && !preview && !manual && !reviewingReturn ? <Copy aria-hidden="true" className="mr-2 h-4 w-4 shrink-0" /> : null}+ <span role="status" className="min-w-0 truncate">{t(showBusy ? busyLabel : actionLabel)}</span>+ </Button>+ {!preview && <div className="-mx-3 flex items-center justify-between gap-1">+ {request?.command ? manual ? <Button variant="ghost" size="sm" disabled={busy} onClick={() => { setManual(false); setPanel(null); setError(""); }}>{t("remote.back")}</Button>+ : <Button variant="ghost" size="sm" className="text-xs text-muted-foreground" disabled={expired} aria-expanded={panel === "command"} aria-controls={panelId} onClick={() => setPanel(panel === "command" ? null : "command")}>{t("remote.pair.showCommand")}</Button> : <span />}+ <DropdownMenu>+ <DropdownMenuTrigger asChild><Button variant="ghost" size="sm" className="text-xs text-muted-foreground">{t("remote.pair.otherWays")}<ChevronDown aria-hidden="true" className="ml-1 h-3.5 w-3.5" /></Button></DropdownMenuTrigger>+ <DropdownMenuContent align="end" onCloseAutoFocus={(event) => {+ if (focusManual.current) { event.preventDefault(); focusManual.current = false; manualInput.current?.focus(); }+ }}>+ <DropdownMenuItem disabled={!request || busy || expired || restartAvailable} onSelect={() => { focusManual.current = true; setManual(true); setPanel(null); setError(""); }}>{t("remote.pair.pasteInstead")}</DropdownMenuItem>+ <DropdownMenuItem onSelect={onSSH}>{t("remote.pair.useSSH")}</DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem disabled={restartAvailable} onSelect={() => setPanel(panel === "help" ? null : "help")}>{t("remote.pair.helpTitle")}</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>}+ </div>+ </>;+}diff --git a/webui/src/components/remote/RemoteConnectionsPage.tsx b/webui/src/components/remote/RemoteConnectionsPage.tsxindex 0ea5d3c3f..3c71a849b 100644--- a/webui/src/components/remote/RemoteConnectionsPage.tsx+++ b/webui/src/components/remote/RemoteConnectionsPage.tsx@@ -1,25 +1,28 @@-import { useEffect, useId, useRef, useState } from "react";-import { ArrowLeft, ArrowUpRight, Check, ChevronLeft, Laptop, Loader2, MoreHorizontal, Plus, Server, ShieldCheck } from "lucide-react";+import { useEffect, useId, useRef, useState, useSyncExternalStore, type ReactNode } from "react";+import { AlertCircle, ArrowUpRight, Check, ChevronDown, ChevronLeft, FolderOpen, Laptop, Loader2, MoreHorizontal, Plus, Server } from "lucide-react";import { useTranslation } from "react-i18next";--import { SettingsGroup, SettingsRow, SettingsSectionTitle } from "@/components/settings/shared/SettingsControls";-import { SettingsAdvancedOptions } from "@/components/settings/shared/SettingsFeature";+import { SettingsGroup } from "@/components/settings/shared/SettingsControls";import { Button } from "@/components/ui/button";import { Input } from "@/components/ui/input";+import { DisclosureContent } from "@/components/ui/disclosure";import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/components/ui/dialog";import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";import { useClient } from "@/providers/ClientProvider";-import { remoteAction, type RemoteProfile } from "@/lib/remote-instances";+import { remoteAction, type RemoteInspection, type RemoteProfile } from "@/lib/remote-instances";import { cn } from "@/lib/utils";+import { parseSSHAddress } from "@/lib/ssh-address";+import { clearPairReturn, readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";import { useRemoteConnections } from "./RemoteInstances";import { SSHHostPicker } from "./SSHHostPicker";+import { QuickPairSetup } from "./QuickPairSetup";+import { PairRouteSettings } from "./PairRouteSettings";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. */+/** The page is a server directory. Add/edit/first-use verification share one dialog. */export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChromeInset = false, onBackToChat }: {mainNavigationExpanded?: boolean;hostChromeInset?: boolean;@@ -30,74 +33,182 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChroconst connections = useRemoteConnections();const [form, setForm] = useState(emptyProfile);const [editorOpen, setEditorOpen] = useState(false);- const [editingId, setEditingId] = useState("");+ const returnedPair = useSyncExternalStore(subscribePairReturn, readPairReturn);+ const [quickOpen, setQuickOpen] = useState(!!returnedPair);+ const [pairRoute, setPairRoute] = useState("");+ const [editing, setEditing] = useState(false);+ const [savedId, setSavedId] = useState("");const [busy, setBusy] = useState("");const [error, setError] = useState("");+ const [errorCode, setErrorCode] = useState("");+ const [sshOptions, setSSHOptions] = useState(false);+ const [manualLocation, setManualLocation] = useState(false);+ const [inspection, setInspection] = useState<RemoteInspection | null>(null);+ const [inspectBeforeConnect, setInspectBeforeConnect] = useState(true);+ const [commandImported, setCommandImported] = useState(false);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 lastRemoval = useRef<RemoteProfile | null>(null);+ const lastDisconnect = useRef<RemoteProfile | null>(null);+ const [fingerprint, setFingerprint] = useState<{ id: string; fingerprint: string; challenge: string; inspect: boolean } | null>(null);+ const hostInput = useRef<HTMLInputElement>(null);+ const editorTrigger = useRef<HTMLButtonElement | null>(null);const mounted = useRef(true);+ const operation = useRef(0);+ const optionsId = useId();const refresh = connections?.refresh;+ // Keep confirmation content intact during Radix's exit animation.+ useEffect(() => { if (removing) lastRemoval.current = removing; }, [removing]);+ useEffect(() => { if (disconnecting) lastDisconnect.current = disconnecting; }, [disconnecting]);++ useEffect(() => { if (returnedPair) setQuickOpen(true); }, [returnedPair]);+useEffect(() => {mounted.current = true;- // Keep cached rows visible while refreshing in the background.void refresh?.().catch(() => {});- return () => { mounted.current = false; };+ return () => { mounted.current = false; operation.current += 1; };}, [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 wanted = (attempt: number) => mounted.current && attempt === operation.current;const showError = (reason: unknown) => {- if (!mounted.current) return;const code = reason instanceof Error ? reason.message : "unknown";+ if (/^(ssh_|host_key_|local_file_not_found)/.test(code)) {+ setInspection(null); setManualLocation(false); setInspectBeforeConnect(true);+ }+ setErrorCode(code);setError(t(`remote.errors.${code}`, { defaultValue: t("remote.errors.unknown") }));};+ const closeEditor = () => {+ operation.current += 1;+ if (busy) connections.cancel();+ setBusy(""); setEditorOpen(false); setFingerprint(null); setError(""); setErrorCode("");+ };+ const beginEditor = (profile?: RemoteProfile) => {+ operation.current += 1;+ setEditing(!!profile); setSavedId(profile?.id || "");+ setSSHOptions(false); setManualLocation(false); setInspection(null);+ setInspectBeforeConnect(!profile); setErrorCode("");+ setForm(profile ? { name: profile.name, host: profile.host, port: profile.port,+ ssh_config: profile.ssh_config, identity_file: profile.identity_file,+ config_path: profile.config_path, runtime_user: profile.runtime_user } : emptyProfile());+ setError(""); setCommandImported(false); setEditorOpen(true); setFingerprint(null);+ };- const connect = async (id: string) => {- setBusy(id); setError("");+ const importCommand = () => {+ if (!/^ssh\s/.test(form.host.trim())) return;try {- await connectHost(id, () => mounted.current);+ setForm({ ...form, ...parseSSHAddress(form.host) });+ setCommandImported(true); setError("");+ } catch (reason) { showError(reason); }+ };++ const pickFile = async (field: "ssh_config" | "identity_file") => {+ const attempt = ++operation.current;+ setBusy(`pick-${field}`); setError(""); setErrorCode("");+ try {+ const result = await remoteAction<{ path: string | null }>(client, "pick_file", {});+ if (wanted(attempt) && typeof result.path === "string" && result.path) {+ setForm((previous) => ({ ...previous, [field]: result.path }));+ }+ } catch (reason) { if (wanted(attempt)) showError(reason); }+ finally { if (wanted(attempt)) setBusy(""); }+ };+ const filePicker = (field: "ssh_config" | "identity_file") => <Button type="button" variant="ghost" size="icon" className="shrink-0"+ disabled={!!busy} title={t("remote.setup.chooseFile", { field: t(`remote.${field}`) })}+ aria-label={t("remote.setup.chooseFile", { field: t(`remote.${field}`) })} onClick={() => { void pickFile(field); }}>+ {busy === `pick-${field}` ? <Loader2 className="h-4 w-4 animate-spin" /> : <FolderOpen className="h-4 w-4" />}+ </Button>;++ const connect = async (id: string, attempt = ++operation.current, inspect = false) => {+ setBusy(inspect ? "inspect" : id); setError(""); setErrorCode("");+ try {+ if (inspect) {+ const result = await remoteAction<RemoteInspection>(client, "inspect", { id });+ if (!wanted(attempt)) return;+ if (!result || !Array.isArray(result.candidates) || typeof result.hostname !== "string") throw new Error("probe_failed");+ setInspection(result);+ setInspectBeforeConnect(false);+ const single = result.candidates.length === 1 ? result.candidates[0] : null;+ if (single) setForm((previous) => ({ ...previous, config_path: single.config_path, runtime_user: single.runtime_user }));+ else if (result.candidates.length) setForm((previous) => ({ ...previous, config_path: "", runtime_user: "" }));+ // Only the unambiguous login-user default is automatic. Service accounts+ // always require an explicit choice before attempting existing sudo access.+ if (!single || single.runtime_user) {+ setManualLocation(!result.candidates.length);+ return;+ }+ // Keep the submitted profile (including a newly imported SSH command).+ const address = parseSSHAddress(form.host);+ const profile = { ...form, ...address,+ name: form.name.trim() || address.host,+ config_path: single.config_path, runtime_user: single.runtime_user };+ if (profile.config_path !== form.config_path || profile.runtime_user !== form.runtime_user) {+ await remoteAction(client, "save", { id, profile });+ }+ if (!wanted(attempt)) return;+ await refresh?.();+ if (!wanted(attempt)) return;+ setBusy(id);+ }+ await connectHost(id, () => wanted(attempt));+ if (wanted(attempt)) { setEditorOpen(false); setFingerprint(null); }} catch (reason) {- if (!mounted.current) return;+ if (!wanted(attempt)) return;if (reason instanceof Error && reason.message === "host_key_unknown") {try {const result = await remoteAction<{ fingerprint: string; challenge: string }>(client, "fingerprint", { id });- if (mounted.current) setFingerprint({ id, ...result });- } catch (scanError) { showError(scanError); }- } else { showError(reason); }- } finally {- if (mounted.current) setBusy("");- }+ if (wanted(attempt)) setFingerprint({ id, ...result, inspect });+ } catch (scanError) { if (wanted(attempt)) showError(scanError); }+ } else {+ if (!editorOpen) {+ const profile = directory?.profiles.find((item) => item.id === id);+ if (profile && !profile.paired) {+ setForm({ name: profile.name, host: profile.host, port: profile.port,+ ssh_config: profile.ssh_config, identity_file: profile.identity_file,+ config_path: profile.config_path, runtime_user: profile.runtime_user });+ setSavedId(id); setEditing(false); setEditorOpen(true); setInspectBeforeConnect(true);+ setInspection(null); setManualLocation(false); setSSHOptions(false);+ }+ }+ showError(reason);+ }+ } finally { if (wanted(attempt)) setBusy(""); }};const trustHost = async () => {if (!fingerprint) return;+ const attempt = ++operation.current;+ const id = fingerprint.id;setBusy("trust"); setError("");try {- await remoteAction(client, "trust", { id: 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(""); }+ await remoteAction(client, "trust", { id, challenge: fingerprint.challenge });+ if (wanted(attempt)) { setFingerprint(null); await connect(id, attempt, fingerprint.inspect); }+ } catch (reason) { if (wanted(attempt)) showError(reason); }+ finally { if (wanted(attempt)) setBusy(""); }};const save = async () => {- setEditorOpen(true); setBusy("save"); setError("");+ const attempt = ++operation.current;+ setBusy("save"); setError(""); setErrorCode("");try {+ // Also parse here for Enter submission, which doesn't blur the address.+ const address = parseSSHAddress(form.host);+ const normalized = { ...form, ...address, name: form.name.trim() || address.host };+ setForm({ ...form, ...address });const result = await remoteAction<{ id: string }>(client, "save", {- id: editingId, profile: { ...form, name: form.name.trim() || form.host.trim() },+ id: savedId, profile: normalized,});- if (!mounted.current) return;- setEditingId(result.id);+ // Retain the saved id on failures so retry never creates duplicate profiles.+ if (wanted(attempt)) setSavedId(result.id);await refresh?.();- if (mounted.current) await connect(result.id);- } catch (reason) { showError(reason); }- finally { if (mounted.current) setBusy(""); }+ if (!wanted(attempt)) return;+ if (editing) setEditorOpen(false);+ else await connect(result.id, attempt, inspectBeforeConnect && !manualLocation);+ } catch (reason) { if (wanted(attempt)) showError(reason); }+ finally { if (wanted(attempt)) setBusy(""); }};const remove = async () => {@@ -107,20 +218,30 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChroawait disconnectHost(removing.id);await remoteAction(client, "remove", { id: removing.id });if (mounted.current) setRemoving(null);- await refresh?.();- } catch (reason) { showError(reason); }+ await refresh?.().catch(() => {});+ } catch (reason) { if (mounted.current) showError(reason); }finally { if (mounted.current) setBusy(""); }};-const disconnect = async (id: string) => {setBusy(id); setError("");try { await disconnectHost(id); if (mounted.current) setDisconnecting(null); }- catch (reason) { showError(reason); }+ catch (reason) { if (mounted.current) showError(reason); }finally { if (mounted.current) setBusy(""); }};-- const closeEditor = () => {- setEditorOpen(false); setEditingId(""); setForm(emptyProfile()); setError("");+ const pageError = error || (directoryError ? t("remote.errors.directory_unavailable") : "");+ const nanobotError = /^(config_|runtime_user_|webui_|remote_auth_|remote_unreachable|incompatible_gateway|public_ws_|python_|probe_failed)/.test(errorCode);+ const locationStep = !!inspection || manualLocation || nanobotError;+ const openingProfile = !editorOpen && !fingerprint && !removing && !disconnecting+ ? directory?.profiles.find((profile) => profile.id === busy) : null;+ const editorAction = editing ? "remote.save" : locationStep ? "remote.setup.openNanobot" : "remote.connect";+ const editorLabel = !busy || busy.startsWith("pick-") ? editorAction : busy === "save" ? "remote.saving"+ : busy === "inspect" ? "remote.setup.checking" : "remote.setup.opening";+ const editingProfile = editing ? directory?.profiles.find((profile) => profile.id === savedId) : null;+ const removalProfile = removing || lastRemoval.current;+ const disconnectProfile = disconnecting || lastDisconnect.current;+ const editSSH = () => {+ setInspection(null); setManualLocation(false); setInspectBeforeConnect(true);+ setError(""); setErrorCode(""); setSSHOptions(true);};return <div className="flex min-h-0 flex-1 flex-col overflow-hidden bg-settings-canvas">@@ -135,7 +256,7 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro<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>+ <p className="settings-list-inset text-[13px] leading-6 text-muted-foreground">{t("remote.description")}</p>{directory?.available && <><SettingsGroup><div className="settings-list-row flex items-center gap-3 py-3">@@ -145,101 +266,186 @@ export function RemoteConnectionsPage({ mainNavigationExpanded = false, hostChro<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.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={(event) => {+ editorTrigger.current = event.currentTarget; 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>+ {profile.paired && typeof profile.authorized_until === "number" && Number.isFinite(profile.authorized_until)+ && profile.authorized_until * 1000 <= Date.now() + 7 * 86_400_000 && <span className="mt-1 block text-xs leading-5 text-muted-foreground">+ {t(profile.authorized_until * 1000 <= Date.now() ? "remote.pair.expiredDevice" : "remote.pair.expiringDevice", {+ date: new Date(profile.authorized_until * 1000).toLocaleDateString(),+ })}+ </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}+ onPointerDown={(event) => { editorTrigger.current = event.currentTarget; }}+ onKeyDown={(event) => { editorTrigger.current = event.currentTarget; }}+ aria-label={t("remote.manage", { name: profile.name })}><MoreHorizontal className="h-4 w-4" /></Button></DropdownMenuTrigger>+ <DropdownMenuContent align="end">+ {!profile.paired && <DropdownMenuItem disabled={profile.connected || connections.openHostIds.includes(profile.id)} onSelect={() => beginEditor(profile)}>{t("remote.edit")}</DropdownMenuItem>}+ {profile.paired && <DropdownMenuItem disabled={profile.connected || connections.openHostIds.includes(profile.id)} onSelect={() => setPairRoute(profile.id)}>{t("remote.pair.route")}</DropdownMenuItem>}+ {(profile.connected || connections.openHostIds.includes(profile.id)) && <DropdownMenuItem onSelect={() => { setError(""); setDisconnecting(profile); }}>{t("remote.disconnect")}</DropdownMenuItem>}+ <DropdownMenuItem tone="destructive" onSelect={() => { setError(""); setRemoving(profile); }}>{t("remote.forget")}</DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </div>)}+ </SettingsGroup>}+ {openingProfile && <div className="settings-list-inset flex items-center justify-between gap-3">+ <p role="status" className="min-w-0 truncate text-xs text-muted-foreground">{t("remote.preparing", { name: openingProfile.name })}</p>+ <Button variant="ghost" size="sm" className="shrink-0" onClick={closeEditor}>{t("remote.cancelSwitch")}</Button>+ </div>}+ <div className="settings-list-inset"><Button variant="ghost" className="gap-2" disabled={!!busy} onClick={(event) => {+ editorTrigger.current = event.currentTarget; setQuickOpen(true);+ }}><Plus className="h-4 w-4" />{t("remote.add")}</Button></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>+ {pageError && !editorOpen && !fingerprint && !removing && !disconnecting && <div className="settings-list-inset space-y-2">+ <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{pageError}</p>{directoryError && <Button variant="ghost" size="sm" disabled={!!busy} onClick={() => {- setBusy("refresh"); setError(""); void refresh?.().catch(showError).finally(() => { if (mounted.current) setBusy(""); });+ setBusy("refresh"); setError(""); void refresh?.().catch((reason: unknown) => { if (mounted.current) showError(reason); }).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>++ <Dialog open={quickOpen} onOpenChange={(open) => { setQuickOpen(open); if (!open) clearPairReturn(); }}>+ <DialogContent className="flex max-h-[85dvh] max-w-md flex-col overflow-hidden">+ {quickOpen && <QuickPairSetup key={returnedPair?.code || "new"} returned={returnedPair} onSSH={() => { clearPairReturn(); setQuickOpen(false); beginEditor(); }} onClose={() => { clearPairReturn(); setQuickOpen(false); }} />}</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>+ <Dialog open={!!pairRoute} onOpenChange={(open) => { if (!open) setPairRoute(""); }}>+ <DialogContent className="max-w-md"><DialogHeader><DialogTitle>{t("remote.pair.route")}</DialogTitle><DialogDescription>{t("remote.pair.routeDescription")}</DialogDescription></DialogHeader>+ {pairRoute && <PairRouteSettings id={pairRoute} onSaved={() => setPairRoute("")} />}+ </DialogContent>+ </Dialog>+ <Dialog open={editorOpen || !!fingerprint} onOpenChange={(open) => { if (!open) closeEditor(); }}>+ <DialogContent className="flex max-h-[85dvh] max-w-md flex-col overflow-hidden" onOpenAutoFocus={(event) => {+ if (!fingerprint) { event.preventDefault(); hostInput.current?.focus(); }+ }} onCloseAutoFocus={(event) => {+ event.preventDefault();+ if (!editorTrigger.current?.closest("[inert]")) editorTrigger.current?.focus({ preventScroll: true });+ }}>+ <DialogHeader className="shrink-0 pr-5 text-left">+ <DialogTitle>{t(fingerprint ? "remote.verifyTitle" : editing ? "remote.edit" : "remote.addTitle")}</DialogTitle>+ <DialogDescription>{t(fingerprint ? "remote.verifyDescription" : editing ? "remote.editDescription" : "remote.addDescription")}</DialogDescription>+ </DialogHeader>+ {fingerprint ? <>+ <div className="space-y-2 rounded-2xl bg-muted/40 p-3">+ <p className="break-all text-[13px] font-medium">{directory?.profiles.find((profile) => profile.id === fingerprint.id)?.host || form.host}</p>+ <code className="block select-text break-all text-xs text-muted-foreground">{fingerprint.fingerprint}</code>+ </div>+ <p className="text-xs leading-5 text-muted-foreground">{t("remote.verifyHint")}</p>+ {error && <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{error}</p>}+ <div className="grid grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:items-center sm:justify-end">+ {editorOpen && <Button variant="ghost" disabled={!!busy} className="mr-auto gap-1" onClick={() => { setFingerprint(null); setError(""); setErrorCode(""); setInspection(null); setInspectBeforeConnect(true); }}><ChevronLeft className="h-4 w-4" />{t("remote.back")}</Button>}+ <Button variant="ghost" onClick={closeEditor}>{t("common.cancel")}</Button>+ <Button className="col-span-2 h-auto min-h-10 whitespace-normal" disabled={!!busy} aria-busy={!!busy} onClick={() => { void trustHost(); }}>{busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" />}{t("remote.verifyConnect")}</Button>+ </div>+ </> : <form onSubmit={(event) => { event.preventDefault(); if (!busy && form.host.trim() && (!locationStep || form.config_path.trim())) void save(); }} className="flex min-h-0 flex-col gap-4">+ <div className="-mx-1 min-h-0 space-y-4 overflow-y-auto overscroll-contain px-1">+ {!editing && <ol aria-label={t("remote.setup.progress")} className="flex items-center gap-3 text-xs text-muted-foreground">+ <li aria-current={!locationStep ? "step" : undefined} className={cn("flex items-center gap-1.5", !locationStep && "text-foreground")}>+ {locationStep ? <Check className="h-3.5 w-3.5" /> : <span>1</span>}{t("remote.setup.server")}</li>+ <li aria-hidden="true" className="h-px w-5 bg-border" />+ <li aria-current={locationStep ? "step" : undefined} className={cn("flex items-center gap-1.5", locationStep && "text-foreground")}><span>2</span>{t("remote.setup.nanobot")}</li>+ </ol>}+ {locationStep && !editing ? <div className="space-y-4">+ <div className="flex items-center justify-between gap-3 rounded-2xl bg-muted/40 px-3 py-2.5">+ <span className="min-w-0 text-[13px]"><span className="block font-medium">{t("remote.setup.signedIn")}</span><span className="block truncate text-xs text-muted-foreground">{form.host}</span></span>+ <Button type="button" size="sm" variant="ghost" disabled={!!busy} onClick={editSSH}>{t("remote.setup.changeServer")}</Button>+ </div>+ {!!inspection?.candidates.length && <fieldset className="space-y-2">+ <legend className="mb-2 text-[13px] font-medium">{t("remote.setup.chooseNanobot")}</legend>+ {inspection.candidates.map((candidate) => <label key={candidate.config_path + candidate.runtime_user} className={cn("flex cursor-pointer items-start gap-3 rounded-2xl border p-3 transition-colors", !manualLocation && form.config_path === candidate.config_path && form.runtime_user === candidate.runtime_user ? "border-foreground/30 bg-muted/40" : "border-border hover:bg-muted/30")}>+ <input type="radio" name="nanobot-location" className="mt-1 accent-foreground" disabled={!!busy}+ checked={!manualLocation && form.config_path === candidate.config_path && form.runtime_user === candidate.runtime_user}+ onChange={() => { setManualLocation(false); setForm({ ...form, config_path: candidate.config_path, runtime_user: candidate.runtime_user }); setError(""); setErrorCode(""); }} />+ <span className="min-w-0 text-[13px]"><span className="block font-medium">{candidate.service || t("remote.setup.yourNanobot")}</span>+ <span className="block break-all text-xs leading-5 text-muted-foreground">{candidate.config_path}</span>+ {candidate.runtime_user && <span className="mt-1 block text-xs leading-5 text-muted-foreground">{t("remote.setup.serviceAccount", { user: candidate.runtime_user })}</span>}+ </span>+ </label>)}+ </fieldset>}+ {inspection && !inspection.candidates.length && <div className="space-y-1">+ <p className="text-[13px] font-medium">{t("remote.setup.notFound")}</p>+ <p className="text-xs leading-5 text-muted-foreground">{t("remote.setup.notFoundHint")}</p>+ </div>}+ {inspection?.incomplete && <p className="text-xs leading-5 text-muted-foreground">{t("remote.setup.limitedSearch")}</p>}+ {!manualLocation && <Button type="button" variant="ghost" size="sm" disabled={!!busy} onClick={() => setManualLocation(true)}>{t("remote.setup.manualLocation")}</Button>}+ </div> : <>+ <SSHHostPicker inputRef={hostInput} disabled={!!busy} value={form.host} configFile={form.ssh_config} imported={commandImported}+ suggestions={!editingProfile || form.host !== editingProfile.host || form.ssh_config !== editingProfile.ssh_config}+ onChange={(host) => { setForm({ ...form, host }); setCommandImported(false); setError(""); setErrorCode(""); }} onBlur={importCommand} />+ <div>+ <button type="button" disabled={!!busy} aria-expanded={sshOptions} aria-controls={optionsId}+ className="flex min-h-9 items-center gap-2 rounded-xl text-[13px] text-muted-foreground hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"+ onClick={() => setSSHOptions(!sshOptions)}>+ <ChevronDown className={cn("h-3.5 w-3.5 transition-transform", sshOptions && "rotate-180")} />{t("remote.connectionOptions")}+ </button>+ <DisclosureContent id={optionsId} open={sshOptions} className="space-y-3 pb-1 pt-3">+ <RemoteField label={t("remote.ssh_config")} value={form.ssh_config} placeholder="~/.ssh/config" disabled={!!busy} onChange={(ssh_config) => setForm({ ...form, ssh_config })} action={filePicker("ssh_config")} />+ <RemoteField label={t("remote.identity_file")} value={form.identity_file} disabled={!!busy} onChange={(identity_file) => setForm({ ...form, identity_file })} action={filePicker("identity_file")} />+ <p className="text-xs leading-5 text-muted-foreground">{t("remote.setup.keyHint")}</p>+ <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) })} />+ <RemoteField label={t("remote.name")} value={form.name} placeholder={form.host || t("remote.namePlaceholder")} disabled={!!busy} onChange={(name) => setForm({ ...form, name })} />+ </DisclosureContent>+ </div>+ </>}+ {(editing || manualLocation || nanobotError) && <div className="space-y-3">+ <RemoteField label={t("remote.config_path")} value={form.config_path} disabled={!!busy} onChange={(config_path) => setForm({ ...form, config_path })} />+ <RemoteField label={t("remote.runtime_user")} value={form.runtime_user} disabled={!!busy} onChange={(runtime_user) => setForm({ ...form, runtime_user })} />+ <p className="text-xs leading-5 text-muted-foreground">{t("remote.setup.locationHint")}</p>+ </div>}+ </div>+ <div className="shrink-0 space-y-3 pt-1">+ {error && <div className="space-y-1">+ <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{error}</p>+ {!sshOptions && /^(ssh_|local_file_not_found)/.test(errorCode) && <Button type="button" variant="ghost" size="sm" disabled={!!busy} onClick={editSSH}>{t("remote.setup.sshSettings")}</Button>}+ </div>}+ {busy.startsWith("pick-") && <p role="status" className="text-xs text-muted-foreground">{t("remote.setup.pickingFile")}</p>}+ <div className="grid grid-cols-[auto_minmax(0,1fr)] items-center gap-2">+ <Button type="button" variant="ghost" onClick={closeEditor}>{t("common.cancel")}</Button>+ <Button type="submit" className="min-w-0" title={t(editorLabel)} aria-label={t(editorLabel)} aria-busy={!!busy} disabled={!!busy || !form.host.trim() || (locationStep && !form.config_path.trim())}>+ {busy && !busy.startsWith("pick-") && <Loader2 aria-hidden className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" />}+ <span role={busy && !busy.startsWith("pick-") ? "status" : undefined} className="truncate">{t(editorLabel)}</span>+ </Button>+ </div>+ </div>+ </form>}</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>+ <Dialog open={!!disconnecting} onOpenChange={(value) => { if (!value && !busy) setDisconnecting(null); }}>+ <DialogContent className="max-h-[85dvh] max-w-sm overflow-y-auto"><DialogHeader className="pr-5 text-left"><DialogTitle className="break-words leading-snug">{t("remote.disconnectTitle", { name: disconnectProfile?.name })}</DialogTitle><DialogDescription>{t("remote.disconnectDescription")}</DialogDescription></DialogHeader>+ {error && <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{error}</p>}+ <div className="grid grid-cols-2 gap-2"><Button variant="ghost" disabled={!!busy} onClick={() => setDisconnecting(null)}>{t("common.cancel")}</Button><Button variant="outline" className="min-w-0" disabled={!!busy} aria-busy={!!busy} onClick={() => { if (disconnecting) void disconnect(disconnecting.id); }}>{busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" />}<span className="truncate">{t("remote.disconnect")}</span></Button></div>+ </DialogContent>+ </Dialog>+ <Dialog open={!!removing} onOpenChange={(value) => { if (!value && !busy) setRemoving(null); }}>+ <DialogContent className="max-h-[85dvh] max-w-sm overflow-y-auto"><DialogHeader className="pr-5 text-left"><DialogTitle className="break-words leading-snug">{t("remote.forgetTitle", { name: removalProfile?.name })}</DialogTitle><DialogDescription>{t("remote.forgetDescription")}</DialogDescription></DialogHeader>+ {removalProfile && (removalProfile.connected || connections.openHostIds.includes(removalProfile.id)) && <p role="note" className="rounded-xl bg-muted/40 p-3 text-xs leading-5">{t("remote.activeForgetWarning")}</p>}+ {removalProfile?.paired && <div className="space-y-2 text-xs text-muted-foreground"><p>{t("remote.pair.forgetHint")}</p><code className="block break-all">{removalProfile.revoke_command}</code></div>}+ {error && <p role="alert" className="flex items-start gap-2 text-[13px] leading-5 text-foreground"><AlertCircle aria-hidden="true" className="mt-0.5 h-4 w-4 shrink-0 text-muted-foreground" />{error}</p>}+ <div className="grid grid-cols-2 gap-2"><Button variant="ghost" disabled={!!busy} onClick={() => setRemoving(null)}>{t("common.cancel")}</Button><Button variant="destructive" className="min-w-0" disabled={!!busy} aria-busy={!!busy} onClick={() => { void remove(); }}>{busy && <Loader2 aria-hidden className="mr-2 h-4 w-4 shrink-0 animate-spin motion-reduce:animate-none" />}<span className="truncate">{t("remote.forget")}</span></Button></div></DialogContent></Dialog></div>;}-function RemoteField({ label, onChange, ...props }: {+function RemoteField({ label, onChange, action, ...props }: {label: string; value: string; onChange: (value: string) => void;- placeholder?: string; required?: boolean; disabled?: boolean; type?: string; min?: number; max?: number;+ action?: ReactNode;+ placeholder?: string; 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>;+ return <div className="space-y-1.5"><label htmlFor={id} className="block text-xs text-muted-foreground">{label}</label>+ <div className="flex items-center gap-1"><Input id={id} {...props} className="min-w-0" onChange={(event) => onChange(event.target.value)} autoComplete="off" spellCheck={false} />{action}</div>+ </div>;}diff --git a/webui/src/components/remote/RemoteInstances.tsx b/webui/src/components/remote/RemoteInstances.tsxindex 4dc954547..87b2e41f4 100644--- a/webui/src/components/remote/RemoteInstances.tsx+++ b/webui/src/components/remote/RemoteInstances.tsx@@ -1,11 +1,12 @@-import { createContext, useContext, useEffect, useLayoutEffect, useRef, type ReactNode } from "react";+import { createContext, useContext, useEffect, useLayoutEffect, useRef, useSyncExternalStore, 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 { needsRemoteSetup, type RemoteDirectory } from "@/lib/remote-instances";import { useHostSessions } from "./useHostSessions";import { HostNavigationContext, HostSwitcher, RemoteHostMenu, type HostPicker } from "./HostSwitcher";import { useSidebarHostBridge } from "./useSidebarHostBridge";+import { readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";const RemoteContext = createContext<{available: boolean;@@ -16,6 +17,7 @@ const RemoteContext = createContext<{refresh: () => Promise<RemoteDirectory>;connect: (id: string, stillWanted?: () => boolean) => Promise<void>;disconnect: (id: string) => Promise<void>;+ cancel: () => void;} | null>(null);export function useRemoteConnections() { return useContext(RemoteContext); }@@ -23,6 +25,9 @@ export function useRemoteConnections() { return useContext(RemoteContext); }export function RemoteInstances({ children }: { children: ReactNode }) {const { t } = useTranslation();const hosts = useHostSessions();+ const returnedPair = useSyncExternalStore(subscribePairReturn, readPairReturn);+ const returnLocal = hosts.local;+ useEffect(() => { if (returnedPair) returnLocal(); }, [returnedPair, returnLocal]);const { selected, pending, frames, directory, error } = hosts;const localPanel = useRef<HTMLDivElement>(null);const lastLocalFocus = useRef<HTMLElement | null>(null);@@ -34,24 +39,33 @@ export function RemoteInstances({ children }: { children: ReactNode }) {};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 });+ useEffect(() => {+ // A verified remote app can be interactive before optional images/fonts+ // finish loading. Older bundles still use the iframe load fallback.+ for (const id of bridge.readyIds) hosts.loaded(id);+ }, [bridge.readyIds, hosts.loaded]);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 offline = !!selected && (activeFrame?.offline || (!activeFrame && pending?.id !== selected.id));+ const recoveryCode = (hosts.errorId === selected?.id ? error : "") || activeFrame?.error || "";+ const recoveryMessage = recoveryCode ? t(`remote.errors.${recoveryCode}`, { defaultValue: t("remote.errors.unknown") }) : t("remote.noFallback");+ const manage = () => { hosts.local(); window.location.hash = "/remote"; };const switchHost = (id: string) => {- void hosts.connect(id).catch((reason: unknown) => hosts.setError(reason instanceof Error ? reason.message : "unknown"));+ // The session module owns attempt-scoped errors, including cancelled work.+ void hosts.connect(id).catch(() => {});};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,+ localName: directory?.machine_name || "nanobot", currentId: selected?.id || null, recentIds: hosts.recentIds,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,+ manage,+ cancel: hosts.cancel, clearError: hosts.clearError, restoreFocus,};useEffect(() => { if (selected) document.title = `${selected.name} · nanobot`; }, [selected]);useEffect(() => {@@ -76,7 +90,7 @@ export function RemoteInstances({ children }: { children: ReactNode }) {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 }}>+ directoryError: hosts.directoryError, refresh: hosts.refresh, connect: hosts.connect, disconnect: hosts.disconnect, cancel: hosts.cancel }}><HostNavigationContext.Provider value={bridge.embedded || (available || selected ? picker : null)}><div className="flex h-full min-h-0 flex-col bg-background"><div className="relative min-h-0 flex-1 overflow-hidden">@@ -87,7 +101,7 @@ export function RemoteInstances({ children }: { children: ReactNode }) {</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}+ return <div key={`${frame.connection.id}:${frame.connection.gateway_id}:${frame.connection.view_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); }}@@ -99,10 +113,13 @@ export function RemoteInstances({ children }: { children: ReactNode }) {})}{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="max-w-full break-words text-xs text-muted-foreground">{selected.name} · {selected.hostname}</p><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>}+ <p className="max-w-sm text-sm text-muted-foreground">{recoveryMessage}</p>+ <div className="flex flex-wrap items-center justify-center gap-2">+ {offline && (needsRemoteSetup(recoveryCode) ? <Button onClick={manage}>{t("remote.manageConnections")}</Button> : <Button disabled={!!pending} aria-busy={!!pending} onClick={() => switchHost(selected.id)}>+ {pending && <Loader2 aria-hidden className="mr-2 h-4 w-4 animate-spin motion-reduce:animate-none" />}{t(pending ? "remote.connecting" : "remote.reconnect")}+ </Button>)}<Button variant="ghost" onClick={hosts.local}>{t("remote.returnLocal")}</Button></div></div>}diff --git a/webui/src/components/remote/SSHHostPicker.tsx b/webui/src/components/remote/SSHHostPicker.tsxindex 3df22e31e..58e55fcac 100644--- a/webui/src/components/remote/SSHHostPicker.tsx+++ b/webui/src/components/remote/SSHHostPicker.tsx@@ -1,97 +1,113 @@-import { useCallback, useEffect, useRef, useState } from "react";-import { ArrowRight, FileText, Loader2, RefreshCw, Search, Server } from "lucide-react";+import { useCallback, useEffect, useId, useRef, useState, type RefObject } from "react";+import { Check, RefreshCw, 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 }: {+/** One address field for both manual entry and existing SSH aliases. */+export function SSHHostPicker({ disabled, value, configFile, imported, suggestions = true, onChange, onBlur, inputRef }: {disabled: boolean;- onSelect: (host: SSHDiscovery["hosts"][number]) => void;+ value: string;+ configFile: string;+ imported: boolean;+ suggestions?: boolean;+ onChange: (host: string) => void;+ onBlur: () => void;+ inputRef: RefObject<HTMLInputElement>;}) {const { t } = useTranslation();const { client } = useClient();- const [result, setResult] = useState<SSHDiscovery | null>(null);+ const id = useId();+ const [result, setResult] = useState<{ file: string; data: 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;+ const list = useRef<HTMLDivElement>(null);+ const file = configFile.trim();+ const load = useCallback(async (path: string) => {+ const request = ++requestId.current;setBusy(true); setError("");try {- const next = await remoteAction<SSHDiscovery>(client, "discover", { ssh_config: file.trim() });+ const next = await remoteAction<SSHDiscovery>(client, "discover", { ssh_config: path });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("");- }+ if (mounted.current && request === requestId.current) setResult({ file: path, data: next });} catch (reason) {- if (mounted.current && id === requestId.current) {+ if (mounted.current && request === 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);+ if (mounted.current && request === requestId.current) setBusy(false);}}, [client, t]);-useEffect(() => {mounted.current = true;+ if (!suggestions) return;let started = false;+ let timer: ReturnType<typeof setTimeout> | undefined;const unsubscribe = client.onStatus((status) => {- if (status === "open" && !started) { started = true; void load(""); }+ if (status === "open" && !started) {+ started = true;+ // Custom paths update quietly after typing; no separate "read config" flow.+ timer = setTimeout(() => { void load(file); }, file ? 300 : 0);+ }});- return () => { mounted.current = false; requestId.current += 1; unsubscribe(); };- }, [client, load]);+ return () => { mounted.current = false; requestId.current += 1; clearTimeout(timer); unsubscribe(); };+ }, [client, file, load, suggestions]);- 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)} />+ // Never select cached suggestions belonging to a different config file.+ const data = suggestions && result?.file === file ? result.data : null;+ const matched = (data?.hosts ?? []).filter(({ host }) => host.toLowerCase().includes(value.trim().toLowerCase()));+ // A user recovering from a failed user@IP connection may select a custom+ // config containing an alias. Keep that alias discoverable without asking+ // them to know it already or silently replacing the address they entered.+ const hosts = matched.length || !file ? matched : (data?.hosts ?? []);+ return <div className="space-y-2.5">+ <label htmlFor={id} className="block text-[13px] font-medium">{t("remote.host")}</label>+ <Input ref={inputRef} id={id} value={value} required disabled={disabled} autoComplete="off" spellCheck={false}+ placeholder={t("remote.hostPlaceholder")} aria-describedby={`${id}-hint`}+ onChange={(event) => onChange(event.target.value)}+ onBlur={onBlur}+ onKeyDown={(event) => {+ if (event.key === "ArrowDown" && hosts.length && !busy) {+ event.preventDefault(); list.current?.querySelector<HTMLButtonElement>("button")?.focus();+ }+ }} />+ <p id={`${id}-hint`} role={imported ? "status" : undefined} className="text-xs leading-5 text-muted-foreground">{t(imported ? "remote.commandImported" : suggestions ? "remote.commandHint" : "remote.addressHint")}</p>+ {suggestions && (!!hosts.length || !!error) && <div className="rounded-2xl bg-muted/40 p-1.5">+ <div className="flex h-8 items-center justify-between gap-2 px-2">+ <span className="text-xs text-muted-foreground">{t("remote.sshHosts")}</span>+ <Button type="button" variant="ghost" size="icon" className="h-7 w-7" aria-label={t("remote.refreshHosts")}+ disabled={busy || disabled} onClick={() => { void load(file); }}>+ <RefreshCw className={`h-3.5 w-3.5 ${busy ? "animate-spin" : ""}`} />+ </Button></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" />+ <div ref={list} className="max-h-36 overflow-y-auto" aria-label={t("remote.sshHosts")}>+ {hosts.map((host, index) => <button key={host.host} type="button" disabled={disabled || busy}+ title={host.source} aria-label={t("remote.useHost", { host: host.host })}+ className="flex min-h-9 w-full items-center gap-2.5 rounded-xl px-2 text-left text-[13px] transition-colors hover:bg-foreground/5 focus-visible:bg-foreground/5 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring disabled:opacity-50"+ onKeyDown={(event) => {+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {+ event.preventDefault();+ const next = index + (event.key === "ArrowDown" ? 1 : -1);+ if (next < 0) inputRef.current?.focus();+ else list.current?.querySelectorAll<HTMLButtonElement>("button")[next]?.focus();+ }+ }}+ onClick={() => { onChange(host.host); inputRef.current?.focus(); }}>+ <Server className="h-4 w-4 shrink-0 text-muted-foreground" /><span className="flex-1 truncate">{host.host}</span>+ {value === host.host && <Check className="h-3.5 w-3.5 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>;+ {error && <p role="alert" className="px-2 py-1 text-xs leading-5 text-muted-foreground">{error}</p>}+ </div>}+ {data?.incomplete && <p className="text-xs leading-5 text-muted-foreground">{t("remote.partialHosts")}</p>}+ </div>;}diff --git a/webui/src/components/remote/useHostSessions.ts b/webui/src/components/remote/useHostSessions.tsindex 2b520c222..ef388f12c 100644--- a/webui/src/components/remote/useHostSessions.ts+++ b/webui/src/components/remote/useHostSessions.ts@@ -1,6 +1,7 @@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";+import { readPairReturn } from "@/lib/remote-pair-return";+import { readRemoteInstances, readSelectedRemote, readRecentRemotes, rememberSelectedRemote, rememberRecentRemote, 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.@@ -10,21 +11,27 @@ export interface HostFrame {loaded: boolean;offline: boolean;failures: number;+ error?: string;}interface PendingSwitch { id: string; name: string }+interface SwitchFailure { id: string; code: 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 [selected, setSelected] = useState<SelectedRemote | null>(() => readPairReturn() ? null : readSelectedRemote());+ const [recentIds, setRecentIds] = useState(readRecentRemotes);+ const recentIdsRef = useRef(recentIds);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 [pending, setPending] = useState<PendingSwitch | null>(() => selected ? { id: selected.id, name: selected.name } : null);+ const pendingRef = useRef<PendingSwitch | null>(pending);+ const [failure, setFailure] = useState<SwitchFailure | null>(null);+ const clearError = useCallback(() => setFailure(null), []);+ const directoryGeneration = useRef(0);const mounted = useRef(true);const epoch = useRef(0);const waiter = useRef<{ id: string; finish: (ready: boolean) => void } | null>(null);@@ -43,17 +50,22 @@ export function useHostSessions() {selectedRef.current = value;setSelected(value);rememberSelectedRemote(value);- setError("");+ if (value) {+ recentIdsRef.current = rememberRecentRemote(value.id, recentIdsRef.current);+ setRecentIds(recentIdsRef.current);+ }+ setFailure(null);publish();}, [publish]);const local = useCallback(() => { cancel(); select(null); }, [cancel, select]);const refresh = useCallback(async () => {+ const generation = ++directoryGeneration.current;try {const next = window.top === window ? await readRemoteInstances(getToken()) : { available: false, profiles: [] };- if (mounted.current) { setDirectory(next); setDirectoryError(false); }+ if (mounted.current && generation === directoryGeneration.current) { setDirectory(next); setDirectoryError(false); }return next;} catch (reason) {- if (mounted.current) setDirectoryError(true);+ if (mounted.current && generation === directoryGeneration.current) setDirectoryError(true);throw reason;}}, [getToken]);@@ -67,10 +79,15 @@ export function useHostSessions() {if (wanted()) select(warm.connection);return;}- if (!warm && cache.current.size >= MAX_HOST_VIEWS) throw new Error("view_limit");+ if (!warm && cache.current.size >= MAX_HOST_VIEWS) {+ setFailure({ id, code: "view_limit" });+ throw new Error("view_limit");+ }+ // A health response started before this mutation describes the old tunnel.+ directoryGeneration.current += 1;const name = directory?.profiles.find((item) => item.id === id)?.name || initial.current?.name || id;setPendingSwitch({ id, name });- setError("");+ setFailure(null);let openingFrame = warm?.loaded ? undefined : warm;try {const connection = validateRemoteConnection(await remoteAction<RemoteConnection>(client, "connect", { id }));@@ -80,12 +97,13 @@ export function useHostSessions() {return;}let frame = cache.current.get(id);- if (!frame || frame.connection.url !== connection.url || frame.connection.gateway_id !== connection.gateway_id) {+ if (!frame || frame.connection.url !== connection.url || frame.connection.gateway_id !== connection.gateway_id+ || frame.connection.view_id !== connection.view_id) {frame = { connection, loaded: false, offline: false, failures: 0 };cache.current.set(id, frame);} else {frame.connection = connection;- frame.offline = false; frame.failures = 0;+ frame.offline = false; frame.failures = 0; frame.error = "";}if (!frame.loaded) openingFrame = frame;publish();@@ -95,14 +113,20 @@ export function useHostSessions() {const timer = window.setTimeout(() => {waiter.current = null;reject(new Error("view_load_failed"));- }, 25_000);+ // Cold remote bundles can take several SSH round trips. Keep the+ // current host usable and cancellable while giving them time to load.+ }, 60_000);waiter.current = { id, finish: (ready) => { window.clearTimeout(timer); resolve(ready); } };});if (!ready) return;}if (wanted()) select(connection);} catch (reason) {- if (wanted()) throw reason;+ if (wanted()) {+ setFailure({ id, code: reason instanceof Error ? reason.message : "unknown" });+ void refresh().catch(() => {});+ 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.@@ -122,12 +146,15 @@ export function useHostSessions() {if (waiter.current?.id === id) { waiter.current.finish(true); waiter.current = null; }}, [publish]);const disconnect = useCallback(async (id: string) => {+ directoryGeneration.current += 1;if (pendingRef.current?.id === id) cancel();await remoteAction(client, "disconnect", { id });if (selectedRef.current?.id === id) local();cache.current.delete(id);publish();- await refresh();+ // The mutation succeeded. A failed follow-up read must not ask the user to+ // repeat a destructive action; refresh has its own retryable list error.+ await refresh().catch(() => {});}, [cancel, client, local, publish, refresh]);useEffect(() => {@@ -138,41 +165,52 @@ export function useHostSessions() {useEffect(() => {const saved = initial.current;if (!saved || window.top !== window) return;+ const restoration = epoch.current;let started = false;const timer = window.setTimeout(() => {started = true;- if (selectedRef.current?.id === saved.id) setError("ssh_unreachable");+ if (selectedRef.current?.id === saved.id && epoch.current === restoration) {+ setPendingSwitch(null);+ setFailure({ id: saved.id, code: "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");- });+ if (selectedRef.current?.id !== saved.id || epoch.current !== restoration) return;+ void connectRef.current(saved.id).catch(() => {});});return () => { window.clearTimeout(timer); unsubscribe(); };- }, [client]);+ }, [client, setPendingSwitch]);useEffect(() => {let checking = false;let cancelled = false;const tick = async () => {if (checking || !cache.current.size) return;checking = true;+ const generation = ++directoryGeneration.current;try {const next = await readRemoteInstances(getToken());- if (cancelled) return;+ if (cancelled || generation !== directoryGeneration.current) 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);+ const profile = next.profiles.find((profile) => profile.id === id);+ const changed = (!!profile?.gateway_id && profile.gateway_id !== frame.connection.gateway_id)+ || (!!profile?.view_id && profile.view_id !== frame.connection.view_id);+ const connected = !!profile?.connected && !changed;frame.failures = connected ? 0 : frame.failures + 1;- if (connected || frame.failures >= 2) frame.offline = !connected;+ if (connected || frame.failures >= 2) {+ frame.offline = !connected;+ frame.error = connected ? "" : changed ? "instance_changed" : profile?.connection_error || (!profile ? "profile_not_found" : "");+ }+ if (connected && frame.loaded) setFailure((current) => current?.id === id ? null : current);}} catch {- if (!cancelled) for (const frame of cache.current.values()) {- if (++frame.failures >= 2) frame.offline = true;+ if (!cancelled && generation === directoryGeneration.current) for (const [id, frame] of cache.current) {+ if (id === pendingRef.current?.id) continue;+ if (++frame.failures >= 2) { frame.offline = true; frame.error = "directory_unavailable"; }}} finally {checking = false;@@ -180,7 +218,19 @@ export function useHostSessions() {}};const timer = window.setInterval(() => { void tick(); }, 5_000);- return () => { cancelled = true; window.clearInterval(timer); };+ // Background tabs throttle timers. Recheck promptly after waking or a+ // network change, without reloading a frame or changing the selected host.+ const wake = () => { if (document.visibilityState === "visible") void tick(); };+ window.addEventListener("online", wake);+ window.addEventListener("pageshow", wake);+ document.addEventListener("visibilitychange", wake);+ return () => {+ cancelled = true; window.clearInterval(timer);+ window.removeEventListener("online", wake);+ window.removeEventListener("pageshow", wake);+ document.removeEventListener("visibilitychange", wake);+ };}, [client, getToken, publish]);- return { directory, directoryError, refresh, selected, frames, pending, error, setError, connect, cancel, local, disconnect, loaded };+ return { directory, directoryError, refresh, selected, recentIds, frames, pending,+ error: failure?.code || "", errorId: failure?.id, clearError, connect, cancel, local, disconnect, loaded };}diff --git a/webui/src/i18n/locales/en/common.json b/webui/src/i18n/locales/en/common.jsonindex a9cb7948e..d23b68569 100644--- a/webui/src/i18n/locales/en/common.json+++ b/webui/src/i18n/locales/en/common.json@@ -1,5 +1,96 @@{"remote": {+ "activeForgetWarning": "All tabs using this connection will disconnect. Unsaved work may be lost.",+ "saved": "Saved",+ "pair": {+ "expiringDevice": "Authorization expires {{date}}.",+ "expiredDevice": "Authorization expired. Pair this server again before reconnecting.",+ "introHint": "Run one command in your server terminal to connect.",+ "copiedTitle": "Command copied",+ "afterCopyHint": "Paste it into your server terminal. After authorizing, open the returned link on this computer.",+ "copyAgain": "Copy again",+ "otherWays": "Other ways",+ "helpTitle": "Requirements & help",+ "validityHint": "Commands expire after 10 minutes. Review access before authorizing.",+ "linkDescription": "Run a command on your server, then follow its link back here.",+ "preparing": "Preparing your connection…",+ "linkRunHint": "Paste the command into your cloud terminal and authorize this computer. It is valid for 10 minutes.",+ "showCommand": "View command",+ "checkingLink": "Checking the connection link…",+ "returnTitle": "2. Return to nanobot",+ "returnHint": "After authorizing, open the terminal’s link on this computer. We’ll fill in the connection details.",+ "pasteInstead": "Use a connection code instead",+ "confirmLinkDescription": "Continue only if this link or code came from your own trusted server terminal.",+ "route": "Network route…",+ "direct": "Direct connection",+ "savedRoute": "Saved network route",+ "routeDescription": "For an existing VPN or special SSH network route.",+ "routeHint": "Optionally reuse the network route of a saved SSH connection to this same server. Its login key and credentials are not copied.",+ "title": "Connect without an SSH setup",+ "description": "Run one command in your server console, then bring the connection code back here.",+ "steps": {+ "run": "Copy a pairing command to your server terminal.",+ "paste": "Paste the code the server gives you.",+ "connect": "Confirm the server and open nanobot."+ },+ "requirements": "For Linux servers with nanobot installed. SSH must still be reachable; no relay or public WebUI is needed.",+ "useSSH": "Use existing SSH settings",+ "start": "Get pairing command",+ "runTitle": "1. Run on your server",+ "runHint": "Open the terminal in your cloud console. Paste this command and follow the prompts. The server also needs this version of nanobot.",+ "command": "Pairing command",+ "copy": "Copy command",+ "copied": "Copied",+ "copyFailed": "Could not copy. Select and copy the command above.",+ "code": "Connection code",+ "codeHint": "Use the code starting with nbpc1. from that terminal. It only works with this local pairing request.",+ "expired": "This request has expired. Generate a new command. If you already authorized it on the server, use the revoke command printed there.",+ "restart": "Get a new command",+ "review": "Review connection",+ "confirmTitle": "Open this nanobot?",+ "confirmDescription": "Only continue with a code copied from your own trusted server terminal.",+ "access": "This computer will have full access to this nanobot's chats, settings and enabled tools.",+ "expiry": "Device authorization expires on {{date}}. Your server's SSH and nanobot ports stay private as configured.",+ "security": "Connection details & revocation",+ "fingerprint": "The SSH server must match this fingerprint from the server console:",+ "revoke": "To revoke new connections, run this on the server and close any open remote sessions:",+ "retryHint": "Pairing is saved. You can retry without running the server command again. If SSH is blocked by your network or VPN, pairing cannot bypass it.",+ "forgetHint": "Forgetting removes this connection from the list, not its server authorization. To revoke the device, run this on the server:"+ },+ "setup": {+ "progress": "Connection setup",+ "server": "Server",+ "nanobot": "nanobot",+ "signedIn": "SSH connected",+ "changeServer": "Change",+ "chooseNanobot": "Which nanobot would you like to open?",+ "yourNanobot": "Your nanobot",+ "serviceAccount": "Runs as {{user}}. Opening uses this account’s existing sudo permissions.",+ "notFound": "No nanobot configuration found",+ "notFoundHint": "Check that nanobot is installed and running. For Docker or a custom installation, ask the person who deployed it for the config path and service account.",+ "limitedSearch": "Checked your config and named nanobot system services. Other installations may need a path below.",+ "manualLocation": "Specify a different location",+ "keyHint": "Use the path to your SSH private key on this computer, not its contents or a model API key. Password-only SSH login is not supported yet.",+ "locationHint": "These are paths and accounts on the server. No installation or permission changes will be made.",+ "sshSettings": "SSH login settings",+ "checking": "Signing in and looking for nanobot…",+ "opening": "Opening the existing nanobot…",+ "openNanobot": "Open nanobot",+ "chooseFile": "Choose file: {{field}}",+ "pickingFile": "Choose a file in the system dialog…"+ },+ "searchHosts": "Search hosts…",+ "noMatchingHosts": "No matching hosts",+ "commandHint": "Enter user@server or choose a saved SSH host. We’ll sign in using your existing SSH settings, then look for nanobot.",+ "commandImported": "SSH options filled in. You can review them in Connection options.",+ "hostPlaceholder": "Host alias or user@server",+ "addressHint": "Your existing SSH username, key and port are used automatically.",+ "manualAddress": "No matching alias. You can connect with the address above.",+ "connectionOptions": "Connection options",+ "editDescription": "Save your changes here, then connect when you’re ready.",+ "save": "Save changes",+ "saving": "Saving…",+ "connect": "Connect","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.",@@ -11,19 +102,11 @@"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)",+ "portPlaceholder": "From SSH config","loading": "Loading connections…","retry": "Retry","unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",@@ -39,20 +122,17 @@"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.",+ "add": "Add server",+ "addTitle": "Connect to a server",+ "addDescription": "Connect to an existing nanobot. Chats and settings stay on the 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}}",@@ -65,6 +145,28 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "disconnected": "This shared connection was closed. Reconnect when you’re ready.",+ "instance_changed": "This server connection changed. Reconnecting will reload its view; unsent drafts may be lost.",+ "pair_authorization_rejected": "The server no longer accepts this device key. Its authorization may have been revoked or expired. Pair again from your server console.",+ "pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",+ "pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",+ "pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",+ "pair_expired": "This pairing request expired. Generate a new command.",+ "pair_authorization_expired": "This device authorization expired. Pair the server again.",+ "pair_used": "This request was already used. Generate a new one.",+ "pair_limit": "Close unused pairing windows and try again.",+ "pair_managed": "Pair again to change the server or credentials.",+ "ssh_connection_closed": "The SSH connection closed during setup. This does not confirm a key problem. Check your VPN/proxy or use the SSH settings that work in your terminal.",+ "ssh_refused": "The server refused the SSH connection. Check its SSH port and whether the SSH service is running.",+ "ssh_host_not_found": "This server name could not be resolved. Check the address or choose a host from your SSH config.",+ "ssh_too_many_keys": "SSH tried too many keys. Specify the correct key using an SSH config with IdentitiesOnly yes.",+ "duplicate_instance": "This nanobot is already connected through another SSH address. Use its existing entry in Switch host.",+ "ssh_agent_refused": "Your SSH agent declined to use the key. Unlock or approve it in your key manager, then retry. If SSH works only in a terminal, restart nanobot from that terminal.",+ "ssh_key_permissions": "SSH rejected the private key file permissions. Restrict access to your user account, then retry.",+ "ssh_config_invalid": "OpenSSH could not read these connection settings. Check the selected SSH config in your terminal.",+ "ssh_forwarding_denied": "SSH signed in, but the server blocked port forwarding. Ask the administrator to allow forwarding to nanobot's loopback port.",+ "probe_failed": "SSH signed in, but could not run the nanobot check. Check that this account can run non-interactive Python commands.",+ "invalid_ssh_command": "Use a host alias, user@server, or ssh with -p, -i, -F and -l. Quote paths containing spaces. Put other options in SSH config; remote commands aren't supported.","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.",@@ -79,10 +181,11 @@"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.",+ "file_picker_unavailable": "The file chooser couldn't open. You can paste a local file path instead.","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_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.","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.",@@ -92,7 +195,7 @@"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.",+ "invalid_profile": "Check the address, port and Connection options fields.","profile_not_found": "This saved server no longer exists. Refresh the list.","profile_limit": "You can save up to 20 servers.","connection_limit": "Disconnect an existing server before opening another connection.",diff --git a/webui/src/i18n/locales/es/common.json b/webui/src/i18n/locales/es/common.jsonindex 2b3ba95e5..074a19f5a 100644--- a/webui/src/i18n/locales/es/common.json+++ b/webui/src/i18n/locales/es/common.json@@ -1,5 +1,96 @@{"remote": {+ "activeForgetWarning": "Se desconectarán todas las pestañas que usen esta conexión. El trabajo sin guardar puede perderse.",+ "saved": "Guardado",+ "pair": {+ "expiringDevice": "La autorización vence el {{date}}.",+ "expiredDevice": "La autorización ha vencido. Vuelve a emparejar este servidor antes de reconectar.",+ "introHint": "Ejecuta un comando en la terminal de tu servidor para conectarte.",+ "copiedTitle": "Comando copiado",+ "afterCopyHint": "Pégalo en la terminal de tu servidor. Tras autorizar, abre el enlace que aparece en este ordenador.",+ "copyAgain": "Copiar de nuevo",+ "otherWays": "Otras formas",+ "helpTitle": "Requisitos y ayuda",+ "validityHint": "Los comandos caducan en 10 minutos. Revisa los permisos antes de autorizar.",+ "linkDescription": "Ejecuta un comando en el servidor y vuelve mediante el enlace del terminal.",+ "preparing": "Preparando la conexión…",+ "linkRunHint": "Pega el comando en el terminal de la nube y autoriza este equipo. Es válido durante 10 minutos.",+ "showCommand": "Ver comando",+ "checkingLink": "Comprobando el enlace…",+ "returnTitle": "2. Volver a nanobot",+ "returnHint": "Tras autorizar, abre el enlace del terminal en este equipo. Completaremos los datos de conexión.",+ "pasteInstead": "Usar un código de conexión",+ "confirmLinkDescription": "Continúa solo si el enlace o código procede del terminal de tu propio servidor de confianza.",+ "route": "Ruta de red…",+ "direct": "Conexión directa",+ "savedRoute": "Ruta de red guardada",+ "routeDescription": "Para una VPN o una ruta SSH especial existente.",+ "routeHint": "Reutiliza la ruta de red de una conexión SSH guardada al mismo servidor, sin copiar sus claves ni credenciales.",+ "title": "Conectar sin configurar SSH",+ "description": "Ejecuta un comando en la consola del servidor y pega aquí el código de conexión.",+ "steps": {+ "run": "Copia el comando de emparejamiento en el terminal del servidor.",+ "paste": "Pega el código que genera el servidor.",+ "connect": "Confirma el servidor y abre nanobot."+ },+ "requirements": "Para servidores Linux con nanobot instalado. SSH debe ser accesible; no hace falta un intermediario ni una WebUI pública.",+ "useSSH": "Usar ajustes SSH existentes",+ "start": "Obtener comando",+ "runTitle": "1. Ejecutar en el servidor",+ "runHint": "Abre el terminal de tu consola en la nube, pega el comando y sigue las indicaciones. El servidor también necesita esta versión de nanobot.",+ "command": "Comando de emparejamiento",+ "copy": "Copiar comando",+ "copied": "Copiado",+ "copyFailed": "No se pudo copiar. Selecciona y copia el comando de arriba.",+ "code": "Código de conexión",+ "codeHint": "Usa el código que empieza por nbpc1. Solo funciona con esta solicitud local.",+ "expired": "La solicitud ha caducado. Genera un comando nuevo. Si ya la autorizaste, usa el comando de revocación mostrado en el servidor.",+ "restart": "Generar otro comando",+ "review": "Revisar conexión",+ "confirmTitle": "¿Abrir este nanobot?",+ "confirmDescription": "Continúa solo con un código copiado de tu propio terminal de servidor de confianza.",+ "access": "Este ordenador tendrá acceso completo a los chats, ajustes y herramientas habilitadas de este nanobot.",+ "expiry": "La autorización caduca el {{date}}. No cambia la exposición configurada de los puertos SSH y nanobot.",+ "security": "Detalles y revocación",+ "fingerprint": "El servidor SSH debe coincidir con esta huella de la consola:",+ "revoke": "Para revocar conexiones nuevas, ejecuta esto en el servidor y cierra las sesiones remotas abiertas:",+ "retryHint": "El emparejamiento está guardado. Puedes reintentar sin ejecutar el comando otra vez. No evita bloqueos de SSH por la red o VPN.",+ "forgetHint": "Olvidar elimina la conexión de la lista, no la autorización del servidor. Para revocarla, ejecuta:"+ },+ "setup": {+ "progress": "Configuración de conexión",+ "server": "Servidor",+ "nanobot": "nanobot",+ "signedIn": "SSH conectado",+ "changeServer": "Cambiar",+ "chooseNanobot": "¿Qué nanobot quieres abrir?",+ "yourNanobot": "Tu nanobot",+ "serviceAccount": "Se ejecuta como {{user}}. Se usarán los permisos sudo existentes de esta cuenta.",+ "notFound": "No se encontró la configuración de nanobot",+ "notFoundHint": "Comprueba que nanobot esté instalado y en ejecución. Para Docker o instalaciones personalizadas, pide al administrador la ruta y la cuenta del servicio.",+ "limitedSearch": "Se revisaron tu configuración y los servicios nanobot del sistema. Otras instalaciones pueden requerir una ruta.",+ "manualLocation": "Especificar otra ubicación",+ "keyHint": "Ruta de la clave SSH privada en este equipo, no su contenido ni una clave de API. El acceso SSH solo con contraseña aún no es compatible.",+ "locationHint": "Ruta y cuenta del servidor. No se instalará nada ni se cambiarán permisos.",+ "sshSettings": "Ajustes de acceso SSH",+ "checking": "Iniciando sesión y buscando nanobot…",+ "opening": "Abriendo el nanobot existente…",+ "openNanobot": "Abrir nanobot",+ "chooseFile": "Elegir archivo: {{field}}",+ "pickingFile": "Elige un archivo en el diálogo del sistema…"+ },+ "searchHosts": "Buscar servidores…",+ "noMatchingHosts": "No hay servidores coincidentes",+ "commandHint": "Escribe usuario@servidor o elige un host SSH. Iniciaremos sesión con tus ajustes existentes y buscaremos nanobot.",+ "commandImported": "Opciones SSH completadas. Puedes revisarlas en Opciones de conexión.",+ "hostPlaceholder": "Host alias or user@server",+ "addressHint": "Your existing SSH username, key and port are used automatically.",+ "manualAddress": "No matching alias. You can connect with the address above.",+ "connectionOptions": "Connection options",+ "editDescription": "Save your changes here, then connect when you’re ready.",+ "save": "Save changes",+ "saving": "Saving…",+ "connect": "Connect","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.",@@ -11,19 +102,11 @@"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)",+ "portPlaceholder": "From SSH config","loading": "Loading connections…","retry": "Retry","unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",@@ -39,20 +122,17 @@"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.",+ "add": "Add server",+ "addTitle": "Connect to a server",+ "addDescription": "Connect to an existing nanobot. Chats and settings stay on the 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}}",@@ -65,6 +145,28 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "disconnected": "Esta conexión compartida se cerró. Reconecta cuando quieras.",+ "instance_changed": "La conexión a este servidor cambió. Al reconectar se recargará la vista; los borradores sin enviar podrían perderse.",+ "pair_authorization_rejected": "El servidor ya no acepta la clave de este dispositivo. La autorización puede haberse revocado o caducado. Vuelve a emparejar desde la consola del servidor.",+ "pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",+ "pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",+ "pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",+ "pair_expired": "This pairing request expired. Generate a new command.",+ "pair_authorization_expired": "This device authorization expired. Pair the server again.",+ "pair_used": "This request was already used. Generate a new one.",+ "pair_limit": "Close unused pairing windows and try again.",+ "pair_managed": "Pair again to change the server or credentials.",+ "ssh_connection_closed": "La conexión SSH se cerró durante la configuración. No confirma un problema de clave. Revisa la VPN o el proxy, o usa los ajustes SSH que funcionan en tu terminal.",+ "ssh_refused": "El servidor rechazó SSH. Revisa el puerto y que el servicio SSH esté activo.",+ "ssh_host_not_found": "No se pudo resolver el nombre. Revisa la dirección o elige un host de tu configuración SSH.",+ "ssh_too_many_keys": "SSH intentó demasiadas claves. Especifica la clave correcta con IdentitiesOnly yes en la configuración SSH.",+ "duplicate_instance": "Este nanobot ya está conectado mediante otra dirección SSH. Usa la conexión existente en Cambiar servidor.",+ "ssh_agent_refused": "El agente SSH rechazó el uso de la clave. Desbloquéala o autorízala en tu gestor de claves y reintenta. Si solo funciona en un terminal, reinicia nanobot desde ese terminal.",+ "ssh_key_permissions": "SSH rechazó los permisos del archivo de clave privada. Restringe el acceso a tu cuenta y reintenta.",+ "ssh_config_invalid": "OpenSSH no pudo leer la configuración de conexión. Revisa la configuración SSH seleccionada en tu terminal.",+ "ssh_forwarding_denied": "SSH inició sesión, pero el servidor bloqueó el reenvío de puertos. Pide al administrador que permita reenviar al puerto de bucle local de nanobot.",+ "probe_failed": "SSH inició sesión, pero no pudo comprobar nanobot. Verifica que esta cuenta pueda ejecutar comandos Python no interactivos.",+ "invalid_ssh_command": "Usa un alias, usuario@servidor o ssh con -p, -i, -F y -l. Pon entre comillas las rutas con espacios. Guarda otras opciones en la configuración SSH; no se admiten comandos remotos.","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.",@@ -79,10 +181,11 @@"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.",+ "file_picker_unavailable": "No se pudo abrir el selector. Puedes pegar la ruta de un archivo local.","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_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.","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.",@@ -92,7 +195,7 @@"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.",+ "invalid_profile": "Check the address, port and Connection options fields.","profile_not_found": "This saved server no longer exists. Refresh the list.","profile_limit": "You can save up to 20 servers.","connection_limit": "Disconnect an existing server before opening another connection.",diff --git a/webui/src/i18n/locales/fr/common.json b/webui/src/i18n/locales/fr/common.jsonindex d1da50c23..975d1afba 100644--- a/webui/src/i18n/locales/fr/common.json+++ b/webui/src/i18n/locales/fr/common.json@@ -1,5 +1,96 @@{"remote": {+ "activeForgetWarning": "Tous les onglets utilisant cette connexion seront déconnectés. Le travail non enregistré peut être perdu.",+ "saved": "Enregistré",+ "pair": {+ "expiringDevice": "L’autorisation expire le {{date}}.",+ "expiredDevice": "L’autorisation a expiré. Associez à nouveau ce serveur avant de vous reconnecter.",+ "introHint": "Exécutez une commande dans le terminal du serveur pour vous connecter.",+ "copiedTitle": "Commande copiée",+ "afterCopyHint": "Collez-la dans le terminal du serveur. Après autorisation, ouvrez le lien affiché sur cet ordinateur.",+ "copyAgain": "Copier à nouveau",+ "otherWays": "Autres méthodes",+ "helpTitle": "Prérequis et aide",+ "validityHint": "Les commandes expirent après 10 minutes. Vérifiez les accès avant d’autoriser.",+ "linkDescription": "Exécutez une commande sur le serveur, puis revenez via le lien du terminal.",+ "preparing": "Préparation de la connexion…",+ "linkRunHint": "Collez la commande dans le terminal cloud et autorisez cet ordinateur. Elle est valable 10 minutes.",+ "showCommand": "Voir la commande",+ "checkingLink": "Vérification du lien…",+ "returnTitle": "2. Revenir à nanobot",+ "returnHint": "Après autorisation, ouvrez le lien du terminal sur cet ordinateur. Les informations de connexion seront remplies automatiquement.",+ "pasteInstead": "Utiliser un code de connexion",+ "confirmLinkDescription": "Continuez uniquement si ce lien ou ce code provient du terminal de votre propre serveur de confiance.",+ "route": "Chemin réseau…",+ "direct": "Connexion directe",+ "savedRoute": "Chemin réseau enregistré",+ "routeDescription": "Pour un VPN ou un chemin SSH particulier existant.",+ "routeHint": "Réutilisez le chemin réseau d’une connexion SSH enregistrée vers le même serveur, sans copier ses clés ni ses identifiants.",+ "title": "Se connecter sans configurer SSH",+ "description": "Exécutez une commande dans la console du serveur, puis collez le code de connexion ici.",+ "steps": {+ "run": "Copiez la commande d’association dans le terminal du serveur.",+ "paste": "Collez le code fourni par le serveur.",+ "connect": "Confirmez le serveur et ouvrez nanobot."+ },+ "requirements": "Pour les serveurs Linux où nanobot est installé. SSH doit rester accessible ; aucun relais ni WebUI publique requis.",+ "useSSH": "Utiliser les réglages SSH",+ "start": "Obtenir la commande",+ "runTitle": "1. Exécuter sur le serveur",+ "runHint": "Ouvrez le terminal de votre console cloud, collez la commande et suivez les indications. Le serveur doit aussi utiliser cette version de nanobot.",+ "command": "Commande d’association",+ "copy": "Copier la commande",+ "copied": "Copié",+ "copyFailed": "Copie impossible. Sélectionnez et copiez la commande ci-dessus.",+ "code": "Code de connexion",+ "codeHint": "Utilisez le code commençant par nbpc1. Il fonctionne uniquement avec cette demande locale.",+ "expired": "Cette demande a expiré. Générez une nouvelle commande. Si elle a déjà été autorisée, utilisez la commande de révocation affichée sur le serveur.",+ "restart": "Nouvelle commande",+ "review": "Vérifier la connexion",+ "confirmTitle": "Ouvrir ce nanobot ?",+ "confirmDescription": "Continuez uniquement avec un code copié depuis votre propre terminal de serveur de confiance.",+ "access": "Cet ordinateur aura un accès complet aux conversations, réglages et outils activés de ce nanobot.",+ "expiry": "L’autorisation expire le {{date}}. L’exposition configurée des ports SSH et nanobot reste inchangée.",+ "security": "Détails et révocation",+ "fingerprint": "Le serveur SSH doit correspondre à cette empreinte affichée dans sa console :",+ "revoke": "Pour révoquer les nouvelles connexions, exécutez ceci sur le serveur et fermez les sessions distantes ouvertes :",+ "retryHint": "L’association est enregistrée. Réessayez sans relancer la commande serveur. Elle ne contourne pas un blocage SSH par le réseau ou le VPN.",+ "forgetHint": "Oublier retire la connexion de la liste, mais pas l’autorisation du serveur. Pour la révoquer, exécutez :"+ },+ "setup": {+ "progress": "Configuration de la connexion",+ "server": "Serveur",+ "nanobot": "nanobot",+ "signedIn": "SSH connecté",+ "changeServer": "Modifier",+ "chooseNanobot": "Quel nanobot souhaitez-vous ouvrir ?",+ "yourNanobot": "Votre nanobot",+ "serviceAccount": "Exécuté sous {{user}}. Les permissions sudo existantes de ce compte seront utilisées.",+ "notFound": "Configuration nanobot introuvable",+ "notFoundHint": "Vérifiez que nanobot est installé et actif. Pour Docker ou une installation personnalisée, demandez le chemin et le compte de service à l’administrateur.",+ "limitedSearch": "Votre configuration et les services système nanobot ont été vérifiés. Les autres installations peuvent nécessiter un chemin.",+ "manualLocation": "Indiquer un autre emplacement",+ "keyHint": "Chemin de la clé SSH privée sur cet ordinateur, pas son contenu ni une clé API. La connexion SSH par mot de passe seul n’est pas encore prise en charge.",+ "locationHint": "Chemin et compte sur le serveur. Aucune installation ni modification des permissions.",+ "sshSettings": "Paramètres de connexion SSH",+ "checking": "Connexion et recherche de nanobot…",+ "opening": "Ouverture du nanobot existant…",+ "openNanobot": "Ouvrir nanobot",+ "chooseFile": "Choisir un fichier : {{field}}",+ "pickingFile": "Choisissez un fichier dans la fenêtre système…"+ },+ "searchHosts": "Rechercher un hôte…",+ "noMatchingHosts": "Aucun hôte correspondant",+ "commandHint": "Saisissez utilisateur@serveur ou choisissez un hôte SSH. Nous utiliserons vos réglages existants, puis chercherons nanobot.",+ "commandImported": "Options SSH renseignées. Vous pouvez les vérifier dans les options de connexion.",+ "hostPlaceholder": "Host alias or user@server",+ "addressHint": "Your existing SSH username, key and port are used automatically.",+ "manualAddress": "No matching alias. You can connect with the address above.",+ "connectionOptions": "Connection options",+ "editDescription": "Save your changes here, then connect when you’re ready.",+ "save": "Save changes",+ "saving": "Saving…",+ "connect": "Connect","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.",@@ -11,19 +102,11 @@"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)",+ "portPlaceholder": "From SSH config","loading": "Loading connections…","retry": "Retry","unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",@@ -39,20 +122,17 @@"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.",+ "add": "Add server",+ "addTitle": "Connect to a server",+ "addDescription": "Connect to an existing nanobot. Chats and settings stay on the 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}}",@@ -65,6 +145,28 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "disconnected": "Cette connexion partagée a été fermée. Reconnectez-vous quand vous le souhaitez.",+ "instance_changed": "La connexion à ce serveur a changé. La reconnexion rechargera la vue ; les brouillons non envoyés risquent d’être perdus.",+ "pair_authorization_rejected": "Le serveur n’accepte plus la clé de cet appareil. L’autorisation a peut-être été révoquée ou a expiré. Relancez l’association depuis la console du serveur.",+ "pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",+ "pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",+ "pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",+ "pair_expired": "This pairing request expired. Generate a new command.",+ "pair_authorization_expired": "This device authorization expired. Pair the server again.",+ "pair_used": "This request was already used. Generate a new one.",+ "pair_limit": "Close unused pairing windows and try again.",+ "pair_managed": "Pair again to change the server or credentials.",+ "ssh_connection_closed": "La connexion SSH a été interrompue. Cela ne confirme pas un problème de clé. Vérifiez le VPN ou le proxy, ou utilisez les paramètres SSH fonctionnant dans votre terminal.",+ "ssh_refused": "Le serveur a refusé SSH. Vérifiez le port et le service SSH.",+ "ssh_host_not_found": "Impossible de résoudre ce nom. Vérifiez l’adresse ou choisissez un hôte dans votre configuration SSH.",+ "ssh_too_many_keys": "SSH a essayé trop de clés. Indiquez la bonne clé avec IdentitiesOnly yes dans la configuration SSH.",+ "duplicate_instance": "Ce nanobot est déjà connecté via une autre adresse SSH. Utilisez sa connexion existante dans le sélecteur d’hôte.",+ "ssh_agent_refused": "L’agent SSH a refusé d’utiliser la clé. Déverrouillez-la ou autorisez-la dans votre gestionnaire de clés, puis réessayez. Si seul le terminal fonctionne, relancez nanobot depuis ce terminal.",+ "ssh_key_permissions": "SSH a refusé les permissions du fichier de clé privée. Limitez son accès à votre compte, puis réessayez.",+ "ssh_config_invalid": "OpenSSH n’a pas pu lire ces réglages de connexion. Vérifiez la configuration SSH sélectionnée dans votre terminal.",+ "ssh_forwarding_denied": "SSH est connecté, mais le serveur bloque le transfert de ports. Demandez à l’administrateur d’autoriser le transfert vers le port de boucle locale de nanobot.",+ "probe_failed": "SSH est connecté, mais la vérification de nanobot a échoué. Vérifiez que ce compte peut exécuter des commandes Python non interactives.",+ "invalid_ssh_command": "Utilisez un alias, utilisateur@serveur ou ssh avec -p, -i, -F et -l. Mettez entre guillemets les chemins contenant des espaces. Placez les autres options dans la configuration SSH ; les commandes distantes ne sont pas prises en charge.","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.",@@ -79,10 +181,11 @@"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.",+ "file_picker_unavailable": "Impossible d’ouvrir le sélecteur. Vous pouvez saisir le chemin d’un fichier local.","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_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.","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.",@@ -92,7 +195,7 @@"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.",+ "invalid_profile": "Check the address, port and Connection options fields.","profile_not_found": "This saved server no longer exists. Refresh the list.","profile_limit": "You can save up to 20 servers.","connection_limit": "Disconnect an existing server before opening another connection.",diff --git a/webui/src/i18n/locales/id/common.json b/webui/src/i18n/locales/id/common.jsonindex 256204d25..9db394b04 100644--- a/webui/src/i18n/locales/id/common.json+++ b/webui/src/i18n/locales/id/common.json@@ -1,5 +1,96 @@{"remote": {+ "activeForgetWarning": "Semua tab yang memakai koneksi ini akan terputus. Pekerjaan yang belum disimpan dapat hilang.",+ "saved": "Tersimpan",+ "pair": {+ "expiringDevice": "Otorisasi berakhir pada {{date}}.",+ "expiredDevice": "Otorisasi telah berakhir. Pasangkan ulang server ini sebelum menyambungkan kembali.",+ "introHint": "Jalankan satu perintah di terminal server untuk terhubung.",+ "copiedTitle": "Perintah disalin",+ "afterCopyHint": "Tempel dan jalankan di terminal server. Setelah memberi izin, buka tautan yang muncul di komputer ini.",+ "copyAgain": "Salin lagi",+ "otherWays": "Cara lain",+ "helpTitle": "Syarat & bantuan",+ "validityHint": "Perintah berlaku selama 10 menit. Periksa akses sebelum memberi izin.",+ "linkDescription": "Jalankan perintah di server, lalu kembali melalui tautan di terminal.",+ "preparing": "Menyiapkan koneksi…",+ "linkRunHint": "Tempel perintah di terminal cloud dan izinkan komputer ini. Perintah berlaku selama 10 menit.",+ "showCommand": "Lihat perintah",+ "checkingLink": "Memeriksa tautan koneksi…",+ "returnTitle": "2. Kembali ke nanobot",+ "returnHint": "Setelah mengizinkan, buka tautan terminal di komputer ini. Detail koneksi akan diisi otomatis.",+ "pasteInstead": "Gunakan kode koneksi",+ "confirmLinkDescription": "Lanjutkan hanya jika tautan atau kode berasal dari terminal server tepercaya milik Anda.",+ "route": "Rute jaringan…",+ "direct": "Koneksi langsung",+ "savedRoute": "Rute jaringan tersimpan",+ "routeDescription": "Untuk VPN atau rute SSH khusus yang sudah ada.",+ "routeHint": "Gunakan rute jaringan koneksi SSH tersimpan ke server yang sama, tanpa menyalin kunci atau kredensialnya.",+ "title": "Hubungkan tanpa menyiapkan SSH",+ "description": "Jalankan satu perintah di konsol server, lalu tempelkan kode koneksi di sini.",+ "steps": {+ "run": "Salin perintah pemasangan ke terminal server.",+ "paste": "Tempel kode yang diberikan server.",+ "connect": "Konfirmasi server dan buka nanobot."+ },+ "requirements": "Untuk server Linux dengan nanobot terpasang. SSH harus bisa dijangkau; tidak perlu relai atau WebUI publik.",+ "useSSH": "Gunakan pengaturan SSH",+ "start": "Dapatkan perintah",+ "runTitle": "1. Jalankan di server",+ "runHint": "Buka terminal konsol cloud, tempel perintah, lalu ikuti petunjuknya. Server juga memerlukan versi nanobot yang mendukung fitur ini.",+ "command": "Perintah pemasangan",+ "copy": "Salin perintah",+ "copied": "Disalin",+ "copyFailed": "Gagal menyalin. Pilih dan salin perintah di atas.",+ "code": "Kode koneksi",+ "codeHint": "Gunakan kode berawalan nbpc1. dari terminal. Kode hanya berlaku untuk permintaan lokal ini.",+ "expired": "Permintaan kedaluwarsa. Buat perintah baru. Jika sudah diizinkan di server, gunakan perintah pencabutan yang ditampilkan di sana.",+ "restart": "Buat perintah baru",+ "review": "Tinjau koneksi",+ "confirmTitle": "Buka nanobot ini?",+ "confirmDescription": "Lanjutkan hanya dengan kode dari terminal server Anda sendiri yang tepercaya.",+ "access": "Komputer ini akan memiliki akses penuh ke obrolan, pengaturan, dan alat aktif nanobot ini.",+ "expiry": "Izin perangkat berakhir pada {{date}}. Pengaturan keterbukaan port SSH dan nanobot tidak berubah.",+ "security": "Detail dan pencabutan izin",+ "fingerprint": "Server SSH harus cocok dengan sidik jari dari konsol server ini:",+ "revoke": "Untuk mencabut koneksi baru, jalankan ini di server dan tutup sesi jarak jauh yang terbuka:",+ "retryHint": "Pemasangan tersimpan. Coba lagi tanpa menjalankan ulang perintah server. Pemasangan tidak dapat melewati pemblokiran SSH oleh jaringan atau VPN.",+ "forgetHint": "Melupakan hanya menghapus koneksi dari daftar, bukan izin server. Untuk mencabutnya, jalankan di server:"+ },+ "setup": {+ "progress": "Pengaturan koneksi",+ "server": "Server",+ "nanobot": "nanobot",+ "signedIn": "SSH terhubung",+ "changeServer": "Ubah",+ "chooseNanobot": "nanobot mana yang ingin dibuka?",+ "yourNanobot": "nanobot Anda",+ "serviceAccount": "Berjalan sebagai {{user}}. Menggunakan izin sudo yang sudah ada untuk akun ini.",+ "notFound": "Konfigurasi nanobot tidak ditemukan",+ "notFoundHint": "Pastikan nanobot terpasang dan berjalan. Untuk Docker atau instalasi khusus, minta jalur konfigurasi dan akun layanan kepada pengelola.",+ "limitedSearch": "Konfigurasi Anda dan layanan sistem nanobot telah diperiksa. Instalasi lain mungkin memerlukan jalur.",+ "manualLocation": "Tentukan lokasi lain",+ "keyHint": "Jalur berkas kunci privat SSH di komputer ini, bukan isinya atau kunci API. Login SSH hanya dengan kata sandi belum didukung.",+ "locationHint": "Jalur dan akun pada server. Tidak ada instalasi atau perubahan izin.",+ "sshSettings": "Pengaturan login SSH",+ "checking": "Masuk dan mencari nanobot…",+ "opening": "Membuka nanobot yang ada…",+ "openNanobot": "Buka nanobot",+ "chooseFile": "Pilih file: {{field}}",+ "pickingFile": "Pilih file di dialog sistem…"+ },+ "searchHosts": "Cari host…",+ "noMatchingHosts": "Tidak ada host yang cocok",+ "commandHint": "Masukkan pengguna@server atau pilih host SSH. Kami akan masuk dengan pengaturan yang ada, lalu mencari nanobot.",+ "commandImported": "Opsi SSH telah diisi. Periksa di Opsi koneksi.",+ "hostPlaceholder": "Host alias or user@server",+ "addressHint": "Your existing SSH username, key and port are used automatically.",+ "manualAddress": "No matching alias. You can connect with the address above.",+ "connectionOptions": "Connection options",+ "editDescription": "Save your changes here, then connect when you’re ready.",+ "save": "Save changes",+ "saving": "Saving…",+ "connect": "Connect","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.",@@ -11,19 +102,11 @@"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)",+ "portPlaceholder": "From SSH config","loading": "Loading connections…","retry": "Retry","unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",@@ -39,20 +122,17 @@"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.",+ "add": "Add server",+ "addTitle": "Connect to a server",+ "addDescription": "Connect to an existing nanobot. Chats and settings stay on the 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}}",@@ -65,6 +145,28 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "disconnected": "Koneksi bersama ini telah ditutup. Sambungkan kembali saat Anda siap.",+ "instance_changed": "Koneksi server ini berubah. Menyambungkan kembali akan memuat ulang tampilan; draf yang belum dikirim dapat hilang.",+ "pair_authorization_rejected": "Server tidak lagi menerima kunci perangkat ini. Otorisasinya mungkin dicabut atau kedaluwarsa. Pasangkan kembali melalui konsol server.",+ "pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",+ "pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",+ "pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",+ "pair_expired": "This pairing request expired. Generate a new command.",+ "pair_authorization_expired": "This device authorization expired. Pair the server again.",+ "pair_used": "This request was already used. Generate a new one.",+ "pair_limit": "Close unused pairing windows and try again.",+ "pair_managed": "Pair again to change the server or credentials.",+ "ssh_connection_closed": "Koneksi SSH ditutup saat penyiapan. Ini belum membuktikan masalah kunci. Periksa VPN/proksi atau gunakan pengaturan SSH yang berfungsi di terminal.",+ "ssh_refused": "Server menolak SSH. Periksa port dan layanan SSH.",+ "ssh_host_not_found": "Nama server tidak dapat ditemukan. Periksa alamat atau pilih host dari konfigurasi SSH.",+ "ssh_too_many_keys": "SSH mencoba terlalu banyak kunci. Tentukan kunci yang benar dengan IdentitiesOnly yes pada konfigurasi SSH.",+ "duplicate_instance": "Nanobot ini sudah terhubung melalui alamat SSH lain. Gunakan koneksi yang ada di menu Ganti host.",+ "ssh_agent_refused": "Agen SSH menolak penggunaan kunci. Buka kunci atau setujui di pengelola kunci, lalu coba lagi. Jika hanya terminal yang bisa terhubung, mulai ulang nanobot dari terminal tersebut.",+ "ssh_key_permissions": "SSH menolak izin berkas kunci privat. Batasi akses hanya untuk akun Anda, lalu coba lagi.",+ "ssh_config_invalid": "OpenSSH tidak dapat membaca pengaturan koneksi ini. Periksa konfigurasi SSH yang dipilih di terminal.",+ "ssh_forwarding_denied": "SSH berhasil masuk, tetapi server memblokir penerusan port. Minta administrator mengizinkan penerusan ke port loopback nanobot.",+ "probe_failed": "SSH berhasil masuk, tetapi pemeriksaan nanobot tidak dapat dijalankan. Pastikan akun ini dapat menjalankan perintah Python noninteraktif.",+ "invalid_ssh_command": "Gunakan alias host, pengguna@server, atau ssh dengan -p, -i, -F, dan -l. Apit jalur yang berisi spasi dengan tanda kutip. Masukkan opsi lain ke konfigurasi SSH; perintah jarak jauh tidak didukung.","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.",@@ -79,10 +181,11 @@"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.",+ "file_picker_unavailable": "Pemilih file tidak dapat dibuka. Tempel jalur file lokal sebagai gantinya.","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_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.","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.",@@ -92,7 +195,7 @@"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.",+ "invalid_profile": "Check the address, port and Connection options fields.","profile_not_found": "This saved server no longer exists. Refresh the list.","profile_limit": "You can save up to 20 servers.","connection_limit": "Disconnect an existing server before opening another connection.",diff --git a/webui/src/i18n/locales/ja/common.json b/webui/src/i18n/locales/ja/common.jsonindex d32b9f583..beb259bfe 100644--- a/webui/src/i18n/locales/ja/common.json+++ b/webui/src/i18n/locales/ja/common.json@@ -1,5 +1,96 @@{"remote": {+ "activeForgetWarning": "この接続を使用しているすべてのタブが切断されます。未保存の内容が失われる可能性があります。",+ "saved": "保存済み",+ "pair": {+ "expiringDevice": "認証は {{date}} に期限切れになります。",+ "expiredDevice": "認証の期限が切れました。再接続する前にペアリングし直してください。",+ "introHint": "サーバーのターミナルでコマンドを実行して接続します。",+ "copiedTitle": "コマンドをコピーしました",+ "afterCopyHint": "サーバーのターミナルに貼り付けて実行します。承認後、表示されたリンクをこのパソコンで開いてください。",+ "copyAgain": "もう一度コピー",+ "otherWays": "ほかの接続方法",+ "helpTitle": "利用条件とヘルプ",+ "validityHint": "コマンドは10分間有効です。承認前にアクセス権限を確認してください。",+ "linkDescription": "サーバーでコマンドを実行し、端末のリンクからここに戻ります。",+ "preparing": "接続を準備しています…",+ "linkRunHint": "クラウド端末にコマンドを貼り付け、このコンピューターを承認してください。有効期限は10分です。",+ "showCommand": "コマンドを表示",+ "checkingLink": "接続リンクを確認しています…",+ "returnTitle": "2. nanobot に戻る",+ "returnHint": "承認後、このコンピューターで端末のリンクを開くと、接続情報が自動入力されます。",+ "pasteInstead": "代わりに接続コードを使う",+ "confirmLinkDescription": "自分の信頼できるサーバー端末から取得したリンクまたはコードであることを確認してください。",+ "route": "ネットワーク経路…",+ "direct": "直接接続",+ "savedRoute": "保存済みのネットワーク経路",+ "routeDescription": "VPN や既存の特殊な SSH 経路向けの設定です。",+ "routeHint": "同じサーバーへの保存済み SSH 接続の経路だけを利用します。認証鍵や認証情報はコピーしません。",+ "title": "SSH の設定なしで接続",+ "description": "サーバーのコンソールでコマンドを実行し、接続コードをここに貼り付けます。",+ "steps": {+ "run": "ペアリングコマンドをサーバーの端末で実行します。",+ "paste": "サーバーが返したコードを貼り付けます。",+ "connect": "サーバーを確認し、nanobot を開きます。"+ },+ "requirements": "nanobot をインストールした Linux サーバー向けです。SSH 接続は必要ですが、中継サービスや WebUI の公開は不要です。",+ "useSSH": "既存の SSH 設定を使用",+ "start": "コマンドを取得",+ "runTitle": "1. サーバーで実行",+ "runHint": "クラウド管理画面の端末にコマンドを貼り付け、案内に従ってください。サーバーにもこの機能に対応した nanobot が必要です。",+ "command": "ペアリングコマンド",+ "copy": "コマンドをコピー",+ "copied": "コピーしました",+ "copyFailed": "コピーできませんでした。上のコマンドを選択してコピーしてください。",+ "code": "接続コード",+ "codeHint": "端末に表示された nbpc1. で始まるコードを使用します。このローカル要求でのみ有効です。",+ "expired": "要求が期限切れです。新しいコマンドを取得してください。サーバーで認可済みなら、端末に表示された取消コマンドを実行してください。",+ "restart": "新しいコマンドを取得",+ "review": "接続情報を確認",+ "confirmTitle": "この nanobot を開きますか?",+ "confirmDescription": "ご自身の信頼できるサーバー端末からコピーしたコードでのみ続行してください。",+ "access": "このコンピューターは、この nanobot のチャット、設定、有効なツールへ完全にアクセスできます。",+ "expiry": "認可の有効期限は {{date}} です。SSH と nanobot の既存のポート公開設定は変更しません。",+ "security": "接続の詳細と認可の取消",+ "fingerprint": "接続先の SSH サーバーは、サーバー端末のこの指紋と一致する必要があります:",+ "revoke": "新規接続の認可を取り消すには、サーバーで次を実行し、開いているリモートセッションも閉じてください:",+ "retryHint": "ペアリングは保存済みです。サーバーのコマンドを再実行せずに再試行できます。ネットワークや VPN による SSH の遮断は回避できません。",+ "forgetHint": "削除するのはローカル一覧の接続だけで、サーバーの認可は残ります。取消にはサーバーで次を実行してください:"+ },+ "setup": {+ "progress": "接続設定",+ "server": "サーバー",+ "nanobot": "nanobot",+ "signedIn": "SSH 接続済み",+ "changeServer": "変更",+ "chooseNanobot": "どの nanobot を開きますか?",+ "yourNanobot": "あなたの nanobot",+ "serviceAccount": "実行アカウントは {{user}} です。このアカウントの既存の sudo 権限を使用します。",+ "notFound": "nanobot の設定が見つかりません",+ "notFoundHint": "nanobot がインストール済みで稼働中か確認してください。Docker や独自構成の場合は、管理者に設定パスとサービスアカウントを確認してください。",+ "limitedSearch": "自分の設定と nanobot システムサービスを確認しました。他の構成ではパスの指定が必要です。",+ "manualLocation": "別の場所を指定",+ "keyHint": "このコンピューター上の SSH 秘密鍵ファイルのパスです。鍵の内容や API キーではありません。パスワードのみの SSH ログインは未対応です。",+ "locationHint": "サーバー上のパスとアカウントです。インストールや権限変更は行いません。",+ "sshSettings": "SSH ログイン設定",+ "checking": "ログインして nanobot を検索中…",+ "opening": "既存の nanobot を開いています…",+ "openNanobot": "nanobot を開く",+ "chooseFile": "ファイルを選択:{{field}}",+ "pickingFile": "システムダイアログでファイルを選択してください…"+ },+ "searchHosts": "ホストを検索…",+ "noMatchingHosts": "一致するホストがありません",+ "commandHint": "ユーザー名@サーバーを入力するか SSH ホストを選択してください。既存の設定でログインし、nanobot を探します。",+ "commandImported": "SSH 設定を入力しました。「接続オプション」で確認できます。",+ "hostPlaceholder": "Host alias or user@server",+ "addressHint": "Your existing SSH username, key and port are used automatically.",+ "manualAddress": "No matching alias. You can connect with the address above.",+ "connectionOptions": "Connection options",+ "editDescription": "Save your changes here, then connect when you’re ready.",+ "save": "Save changes",+ "saving": "Saving…",+ "connect": "Connect","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.",@@ -11,19 +102,11 @@"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)",+ "portPlaceholder": "From SSH config","loading": "Loading connections…","retry": "Retry","unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",@@ -39,20 +122,17 @@"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.",+ "add": "Add server",+ "addTitle": "Connect to a server",+ "addDescription": "Connect to an existing nanobot. Chats and settings stay on the 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}}",@@ -65,6 +145,28 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "disconnected": "この共有接続は閉じられました。必要なときに再接続できます。",+ "instance_changed": "このサーバーへの接続が変わりました。再接続すると画面が再読み込みされ、未送信の下書きが失われる場合があります。",+ "pair_authorization_rejected": "サーバーがこのデバイスの鍵を受け付けなくなりました。認可が取り消されたか期限切れの可能性があります。サーバーのコンソールから再度ペアリングしてください。",+ "pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",+ "pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",+ "pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",+ "pair_expired": "This pairing request expired. Generate a new command.",+ "pair_authorization_expired": "This device authorization expired. Pair the server again.",+ "pair_used": "This request was already used. Generate a new one.",+ "pair_limit": "Close unused pairing windows and try again.",+ "pair_managed": "Pair again to change the server or credentials.",+ "ssh_connection_closed": "接続の確立中に SSH が切断されました。鍵の問題とは限りません。VPN・プロキシを確認するか、端末で接続できる SSH 設定を使用してください。",+ "ssh_refused": "サーバーが SSH 接続を拒否しました。ポートと SSH サービスを確認してください。",+ "ssh_host_not_found": "サーバー名を解決できません。アドレスを確認するか、SSH 設定からホストを選んでください。",+ "ssh_too_many_keys": "SSH が試した鍵が多すぎます。SSH 設定で正しい鍵と IdentitiesOnly yes を指定してください。",+ "duplicate_instance": "この nanobot は別の SSH アドレスで接続済みです。ホスト切り替えから既存の接続を選んでください。",+ "ssh_agent_refused": "SSH エージェントが鍵の使用を拒否しました。鍵管理アプリで解除・承認して再試行してください。ターミナルでのみ接続できる場合は、そのターミナルから nanobot を再起動してください。",+ "ssh_key_permissions": "SSH が秘密鍵ファイルの権限を拒否しました。自分のアカウントだけがアクセスできるようにして再試行してください。",+ "ssh_config_invalid": "OpenSSH が接続設定を読み取れませんでした。選択した SSH 設定をターミナルで確認してください。",+ "ssh_forwarding_denied": "SSH ログインは成功しましたが、サーバーがポート転送を拒否しました。nanobot のループバックポートへの転送を管理者に許可してもらってください。",+ "probe_failed": "SSH ログインは成功しましたが、nanobot の確認を実行できませんでした。このアカウントで非対話型の Python コマンドを実行できるか確認してください。",+ "invalid_ssh_command": "ホスト別名、ユーザー@サーバー、または -p、-i、-F、-l を含む ssh コマンドを入力してください。空白を含むパスは引用符で囲んでください。他のオプションは SSH 設定に記述し、リモートコマンドは含めないでください。","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.",@@ -79,10 +181,11 @@"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.",+ "file_picker_unavailable": "ファイル選択画面を開けませんでした。ローカルファイルのパスを入力してください。","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_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.","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.",@@ -92,7 +195,7 @@"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.",+ "invalid_profile": "Check the address, port and Connection options fields.","profile_not_found": "This saved server no longer exists. Refresh the list.","profile_limit": "You can save up to 20 servers.","connection_limit": "Disconnect an existing server before opening another connection.",diff --git a/webui/src/i18n/locales/ko/common.json b/webui/src/i18n/locales/ko/common.jsonindex a4c43a05d..d5ce1f7fb 100644--- a/webui/src/i18n/locales/ko/common.json+++ b/webui/src/i18n/locales/ko/common.json@@ -1,5 +1,96 @@{"remote": {+ "activeForgetWarning": "이 연결을 사용하는 모든 탭의 연결이 끊어집니다. 저장하지 않은 내용이 손실될 수 있습니다.",+ "saved": "저장됨",+ "pair": {+ "expiringDevice": "인증이 {{date}}에 만료됩니다.",+ "expiredDevice": "인증이 만료되었습니다. 다시 연결하기 전에 서버를 다시 페어링하세요.",+ "introHint": "서버 터미널에서 명령어를 실행해 연결하세요.",+ "copiedTitle": "명령어 복사 완료",+ "afterCopyHint": "서버 터미널에 붙여넣어 실행하세요. 승인 후 표시된 링크를 이 컴퓨터에서 여세요.",+ "copyAgain": "다시 복사",+ "otherWays": "다른 연결 방법",+ "helpTitle": "사용 조건 및 도움말",+ "validityHint": "명령어는 10분 동안 유효합니다. 승인 전에 접근 권한을 확인하세요.",+ "linkDescription": "서버에서 명령을 실행한 후 터미널의 링크로 돌아오세요.",+ "preparing": "연결 준비 중…",+ "linkRunHint": "클라우드 터미널에 명령을 붙여넣고 이 컴퓨터를 승인하세요. 명령은 10분간 유효합니다.",+ "showCommand": "명령 보기",+ "checkingLink": "연결 링크 확인 중…",+ "returnTitle": "2. nanobot으로 돌아가기",+ "returnHint": "승인 후 이 컴퓨터에서 터미널의 링크를 열면 연결 정보가 자동으로 입력됩니다.",+ "pasteInstead": "대신 연결 코드 사용",+ "confirmLinkDescription": "본인의 신뢰할 수 있는 서버 터미널에서 받은 링크나 코드인지 확인하세요.",+ "route": "네트워크 경로…",+ "direct": "직접 연결",+ "savedRoute": "저장된 네트워크 경로",+ "routeDescription": "VPN 또는 기존의 특수 SSH 경로 설정입니다.",+ "routeHint": "같은 서버의 저장된 SSH 연결에서 네트워크 경로만 재사용합니다. 로그인 키나 자격 증명은 복사하지 않습니다.",+ "title": "SSH 설정 없이 연결",+ "description": "서버 콘솔에서 명령 하나를 실행한 뒤 연결 코드를 여기에 붙여넣으세요.",+ "steps": {+ "run": "페어링 명령을 서버 터미널에 복사해 실행하세요.",+ "paste": "서버가 생성한 코드를 붙여넣으세요.",+ "connect": "서버를 확인하고 nanobot을 여세요."+ },+ "requirements": "nanobot이 설치된 Linux 서버용입니다. SSH 연결은 가능해야 하며 중계 서버나 공개 WebUI는 필요하지 않습니다.",+ "useSSH": "기존 SSH 설정 사용",+ "start": "페어링 명령 받기",+ "runTitle": "1. 서버에서 실행",+ "runHint": "클라우드 콘솔의 터미널에 명령을 붙여넣고 안내를 따르세요. 서버에도 이 기능을 지원하는 nanobot 버전이 필요합니다.",+ "command": "페어링 명령",+ "copy": "명령 복사",+ "copied": "복사됨",+ "copyFailed": "복사하지 못했습니다. 위 명령을 선택해 직접 복사하세요.",+ "code": "연결 코드",+ "codeHint": "터미널의 nbpc1.로 시작하는 코드를 사용하세요. 이 로컬 페어링 요청에만 유효합니다.",+ "expired": "요청이 만료되었습니다. 새 명령을 받으세요. 서버에서 이미 승인했다면 터미널에 표시된 취소 명령을 사용하세요.",+ "restart": "새 명령 받기",+ "review": "연결 정보 확인",+ "confirmTitle": "이 nanobot을 열까요?",+ "confirmDescription": "본인의 신뢰할 수 있는 서버 터미널에서 복사한 코드로만 진행하세요.",+ "access": "이 컴퓨터는 이 nanobot의 채팅, 설정, 활성화된 도구에 완전히 접근할 수 있습니다.",+ "expiry": "기기 승인 만료일은 {{date}}입니다. 기존 SSH 및 nanobot 포트 공개 설정은 변경하지 않습니다.",+ "security": "연결 정보 및 승인 취소",+ "fingerprint": "SSH 서버는 서버 콘솔의 다음 지문과 일치해야 합니다:",+ "revoke": "새 연결의 승인을 취소하려면 서버에서 다음 명령을 실행하고 열린 원격 세션도 닫으세요:",+ "retryHint": "페어링이 저장되었습니다. 서버 명령을 다시 실행하지 않고 재시도할 수 있습니다. 네트워크나 VPN의 SSH 차단은 우회할 수 없습니다.",+ "forgetHint": "잊기는 로컬 목록에서 연결만 제거하며 서버 승인은 남습니다. 취소하려면 서버에서 실행하세요:"+ },+ "setup": {+ "progress": "연결 설정",+ "server": "서버",+ "nanobot": "nanobot",+ "signedIn": "SSH 연결됨",+ "changeServer": "변경",+ "chooseNanobot": "어떤 nanobot을 열까요?",+ "yourNanobot": "내 nanobot",+ "serviceAccount": "{{user}} 계정으로 실행됩니다. 이 계정의 기존 sudo 권한을 사용합니다.",+ "notFound": "nanobot 설정을 찾지 못했습니다",+ "notFoundHint": "nanobot이 설치되어 실행 중인지 확인하세요. Docker 또는 사용자 지정 설치는 관리자에게 설정 경로와 서비스 계정을 문의하세요.",+ "limitedSearch": "내 설정과 nanobot 시스템 서비스를 확인했습니다. 다른 설치는 경로 지정이 필요할 수 있습니다.",+ "manualLocation": "다른 위치 지정",+ "keyHint": "이 컴퓨터에 있는 SSH 개인 키 파일의 경로입니다. 키 내용이나 API 키가 아닙니다. 비밀번호만 사용하는 SSH 로그인은 아직 지원하지 않습니다.",+ "locationHint": "서버의 경로와 계정입니다. 설치하거나 권한을 변경하지 않습니다.",+ "sshSettings": "SSH 로그인 설정",+ "checking": "로그인하고 nanobot을 찾는 중…",+ "opening": "기존 nanobot을 여는 중…",+ "openNanobot": "nanobot 열기",+ "chooseFile": "파일 선택: {{field}}",+ "pickingFile": "시스템 창에서 파일을 선택하세요…"+ },+ "searchHosts": "호스트 검색…",+ "noMatchingHosts": "일치하는 호스트가 없습니다",+ "commandHint": "사용자@서버를 입력하거나 SSH 호스트를 선택하세요. 기존 설정으로 로그인한 뒤 nanobot을 찾습니다.",+ "commandImported": "SSH 설정을 입력했습니다. 연결 옵션에서 확인할 수 있습니다.",+ "hostPlaceholder": "Host alias or user@server",+ "addressHint": "Your existing SSH username, key and port are used automatically.",+ "manualAddress": "No matching alias. You can connect with the address above.",+ "connectionOptions": "Connection options",+ "editDescription": "Save your changes here, then connect when you’re ready.",+ "save": "Save changes",+ "saving": "Saving…",+ "connect": "Connect","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.",@@ -11,19 +102,11 @@"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)",+ "portPlaceholder": "From SSH config","loading": "Loading connections…","retry": "Retry","unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",@@ -39,20 +122,17 @@"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.",+ "add": "Add server",+ "addTitle": "Connect to a server",+ "addDescription": "Connect to an existing nanobot. Chats and settings stay on the 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}}",@@ -65,6 +145,28 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "disconnected": "공유 연결이 종료되었습니다. 준비되면 다시 연결하세요.",+ "instance_changed": "이 서버 연결이 변경되었습니다. 다시 연결하면 화면이 새로고침되어 보내지 않은 초안이 사라질 수 있습니다.",+ "pair_authorization_rejected": "서버가 이 기기의 키를 더 이상 허용하지 않습니다. 권한이 취소되었거나 만료되었을 수 있습니다. 서버 콘솔에서 다시 페어링하세요.",+ "pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",+ "pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",+ "pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",+ "pair_expired": "This pairing request expired. Generate a new command.",+ "pair_authorization_expired": "This device authorization expired. Pair the server again.",+ "pair_used": "This request was already used. Generate a new one.",+ "pair_limit": "Close unused pairing windows and try again.",+ "pair_managed": "Pair again to change the server or credentials.",+ "ssh_connection_closed": "설정 중 SSH 연결이 종료되었습니다. 키 문제로 단정할 수 없습니다. VPN·프록시를 확인하거나 터미널에서 작동하는 SSH 설정을 사용하세요.",+ "ssh_refused": "서버가 SSH를 거부했습니다. 포트와 SSH 서비스가 실행 중인지 확인하세요.",+ "ssh_host_not_found": "서버 이름을 확인할 수 없습니다. 주소를 확인하거나 SSH 설정의 호스트를 선택하세요.",+ "ssh_too_many_keys": "SSH가 너무 많은 키를 시도했습니다. SSH 설정에 올바른 키와 IdentitiesOnly yes를 지정하세요.",+ "duplicate_instance": "이 nanobot은 다른 SSH 주소로 이미 연결되어 있습니다. 호스트 전환에서 기존 연결을 사용하세요.",+ "ssh_agent_refused": "SSH 에이전트가 키 사용을 거부했습니다. 키 관리자에서 잠금을 해제하거나 승인한 후 다시 시도하세요. 터미널에서만 연결된다면 해당 터미널에서 nanobot을 다시 시작하세요.",+ "ssh_key_permissions": "SSH가 개인 키 파일 권한을 거부했습니다. 본인 계정만 파일에 접근하도록 제한한 후 다시 시도하세요.",+ "ssh_config_invalid": "OpenSSH가 연결 설정을 읽지 못했습니다. 터미널에서 선택한 SSH 설정을 확인하세요.",+ "ssh_forwarding_denied": "SSH 로그인은 성공했지만 서버가 포트 전달을 차단했습니다. 관리자에게 nanobot의 루프백 포트 전달을 허용해 달라고 요청하세요.",+ "probe_failed": "SSH 로그인은 성공했지만 nanobot 확인을 실행하지 못했습니다. 이 계정에서 비대화형 Python 명령을 실행할 수 있는지 확인하세요.",+ "invalid_ssh_command": "호스트 별칭, 사용자@서버 또는 -p, -i, -F, -l 옵션이 있는 ssh 명령을 입력하세요. 공백이 있는 경로는 따옴표로 감싸세요. 다른 옵션은 SSH 설정에 넣으세요. 원격 명령은 지원하지 않습니다.","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.",@@ -79,10 +181,11 @@"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.",+ "file_picker_unavailable": "파일 선택 창을 열 수 없습니다. 로컬 파일 경로를 직접 입력할 수 있습니다.","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_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.","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.",@@ -92,7 +195,7 @@"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.",+ "invalid_profile": "Check the address, port and Connection options fields.","profile_not_found": "This saved server no longer exists. Refresh the list.","profile_limit": "You can save up to 20 servers.","connection_limit": "Disconnect an existing server before opening another connection.",diff --git a/webui/src/i18n/locales/pt-BR/common.json b/webui/src/i18n/locales/pt-BR/common.jsonindex 80cd07bd3..3f62debb5 100644--- a/webui/src/i18n/locales/pt-BR/common.json+++ b/webui/src/i18n/locales/pt-BR/common.json@@ -1,5 +1,96 @@{"remote": {+ "activeForgetWarning": "Todas as abas que usam esta conexão serão desconectadas. O trabalho não salvo pode ser perdido.",+ "saved": "Salvo",+ "pair": {+ "expiringDevice": "A autorização expira em {{date}}.",+ "expiredDevice": "A autorização expirou. Pareie este servidor novamente antes de reconectar.",+ "introHint": "Execute um comando no terminal do servidor para conectar.",+ "copiedTitle": "Comando copiado",+ "afterCopyHint": "Cole no terminal do servidor. Após autorizar, abra o link exibido neste computador.",+ "copyAgain": "Copiar novamente",+ "otherWays": "Outras formas",+ "helpTitle": "Requisitos e ajuda",+ "validityHint": "Os comandos expiram em 10 minutos. Revise as permissões antes de autorizar.",+ "linkDescription": "Execute um comando no servidor e volte pelo link do terminal.",+ "preparing": "Preparando a conexão…",+ "linkRunHint": "Cole o comando no terminal da nuvem e autorize este computador. Ele é válido por 10 minutos.",+ "showCommand": "Ver comando",+ "checkingLink": "Verificando o link…",+ "returnTitle": "2. Voltar ao nanobot",+ "returnHint": "Após autorizar, abra o link do terminal neste computador. Os dados da conexão serão preenchidos automaticamente.",+ "pasteInstead": "Usar um código de conexão",+ "confirmLinkDescription": "Continue apenas se o link ou código veio do terminal do seu próprio servidor confiável.",+ "route": "Rota de rede…",+ "direct": "Conexão direta",+ "savedRoute": "Rota de rede salva",+ "routeDescription": "Para uma VPN ou rota SSH especial existente.",+ "routeHint": "Reutilize a rota de rede de uma conexão SSH salva com o mesmo servidor, sem copiar suas chaves ou credenciais.",+ "title": "Conectar sem configurar SSH",+ "description": "Execute um comando no console do servidor e cole o código de conexão aqui.",+ "steps": {+ "run": "Copie o comando de pareamento para o terminal do servidor.",+ "paste": "Cole o código fornecido pelo servidor.",+ "connect": "Confirme o servidor e abra o nanobot."+ },+ "requirements": "Para servidores Linux com nanobot instalado. O SSH deve estar acessível; não é necessário um intermediário nem uma WebUI pública.",+ "useSSH": "Usar configurações SSH",+ "start": "Obter comando",+ "runTitle": "1. Executar no servidor",+ "runHint": "Abra o terminal do console de nuvem, cole o comando e siga as instruções. O servidor também precisa desta versão do nanobot.",+ "command": "Comando de pareamento",+ "copy": "Copiar comando",+ "copied": "Copiado",+ "copyFailed": "Não foi possível copiar. Selecione e copie o comando acima.",+ "code": "Código de conexão",+ "codeHint": "Use o código que começa com nbpc1. Ele só funciona com esta solicitação local.",+ "expired": "A solicitação expirou. Gere um novo comando. Se já a autorizou no servidor, use o comando de revogação exibido lá.",+ "restart": "Gerar novo comando",+ "review": "Revisar conexão",+ "confirmTitle": "Abrir este nanobot?",+ "confirmDescription": "Continue apenas com um código copiado do seu próprio terminal de servidor confiável.",+ "access": "Este computador terá acesso completo às conversas, configurações e ferramentas habilitadas deste nanobot.",+ "expiry": "A autorização expira em {{date}}. A exposição configurada das portas SSH e nanobot não muda.",+ "security": "Detalhes e revogação",+ "fingerprint": "O servidor SSH deve corresponder a esta impressão digital do console:",+ "revoke": "Para revogar novas conexões, execute isto no servidor e feche as sessões remotas abertas:",+ "retryHint": "O pareamento foi salvo. Tente novamente sem executar o comando outra vez. Ele não contorna bloqueios de SSH pela rede ou VPN.",+ "forgetHint": "Esquecer remove a conexão da lista, não a autorização do servidor. Para revogar, execute no servidor:"+ },+ "setup": {+ "progress": "Configuração da conexão",+ "server": "Servidor",+ "nanobot": "nanobot",+ "signedIn": "SSH conectado",+ "changeServer": "Alterar",+ "chooseNanobot": "Qual nanobot deseja abrir?",+ "yourNanobot": "Seu nanobot",+ "serviceAccount": "Executado como {{user}}. Serão usadas as permissões sudo existentes dessa conta.",+ "notFound": "Configuração do nanobot não encontrada",+ "notFoundHint": "Verifique se o nanobot está instalado e em execução. Para Docker ou instalações personalizadas, peça ao administrador o caminho e a conta do serviço.",+ "limitedSearch": "Sua configuração e os serviços nanobot do sistema foram verificados. Outras instalações podem exigir um caminho.",+ "manualLocation": "Especificar outro local",+ "keyHint": "Caminho da chave SSH privada neste computador, não seu conteúdo nem uma chave de API. Login SSH apenas com senha ainda não é suportado.",+ "locationHint": "Caminho e conta no servidor. Nada será instalado e nenhuma permissão será alterada.",+ "sshSettings": "Configurações de login SSH",+ "checking": "Entrando e procurando nanobot…",+ "opening": "Abrindo o nanobot existente…",+ "openNanobot": "Abrir nanobot",+ "chooseFile": "Escolher arquivo: {{field}}",+ "pickingFile": "Escolha um arquivo na janela do sistema…"+ },+ "searchHosts": "Buscar hosts…",+ "noMatchingHosts": "Nenhum host encontrado",+ "commandHint": "Digite usuário@servidor ou escolha um host SSH. Entraremos com suas configurações existentes e procuraremos nanobot.",+ "commandImported": "Opções SSH preenchidas. Você pode revisá-las nas opções de conexão.",+ "hostPlaceholder": "Host alias or user@server",+ "addressHint": "Your existing SSH username, key and port are used automatically.",+ "manualAddress": "No matching alias. You can connect with the address above.",+ "connectionOptions": "Connection options",+ "editDescription": "Save your changes here, then connect when you’re ready.",+ "save": "Save changes",+ "saving": "Saving…",+ "connect": "Connect","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.",@@ -11,19 +102,11 @@"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)",+ "portPlaceholder": "From SSH config","loading": "Loading connections…","retry": "Retry","unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",@@ -39,20 +122,17 @@"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.",+ "add": "Add server",+ "addTitle": "Connect to a server",+ "addDescription": "Connect to an existing nanobot. Chats and settings stay on the 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}}",@@ -65,6 +145,28 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "disconnected": "Esta conexão compartilhada foi fechada. Reconecte quando quiser.",+ "instance_changed": "A conexão com este servidor mudou. A reconexão recarregará a tela; rascunhos não enviados poderão ser perdidos.",+ "pair_authorization_rejected": "O servidor não aceita mais a chave deste dispositivo. A autorização pode ter sido revogada ou expirado. Faça o pareamento novamente no console do servidor.",+ "pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",+ "pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",+ "pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",+ "pair_expired": "This pairing request expired. Generate a new command.",+ "pair_authorization_expired": "This device authorization expired. Pair the server again.",+ "pair_used": "This request was already used. Generate a new one.",+ "pair_limit": "Close unused pairing windows and try again.",+ "pair_managed": "Pair again to change the server or credentials.",+ "ssh_connection_closed": "A conexão SSH foi encerrada durante a configuração. Isso não confirma um problema de chave. Verifique a VPN/proxy ou use os ajustes SSH que funcionam no terminal.",+ "ssh_refused": "O servidor recusou SSH. Verifique a porta e se o serviço SSH está ativo.",+ "ssh_host_not_found": "Não foi possível resolver o nome. Verifique o endereço ou escolha um host da configuração SSH.",+ "ssh_too_many_keys": "SSH tentou chaves demais. Especifique a chave correta com IdentitiesOnly yes na configuração SSH.",+ "duplicate_instance": "Este nanobot já está conectado por outro endereço SSH. Use a conexão existente em Alternar host.",+ "ssh_agent_refused": "O agente SSH recusou o uso da chave. Desbloqueie ou autorize a chave no gerenciador e tente novamente. Se funcionar apenas no terminal, reinicie o nanobot por esse terminal.",+ "ssh_key_permissions": "O SSH rejeitou as permissões do arquivo de chave privada. Restrinja o acesso à sua conta e tente novamente.",+ "ssh_config_invalid": "O OpenSSH não conseguiu ler as configurações de conexão. Verifique a configuração SSH selecionada no terminal.",+ "ssh_forwarding_denied": "O SSH conectou, mas o servidor bloqueou o encaminhamento de portas. Peça ao administrador que permita o encaminhamento para a porta de loopback do nanobot.",+ "probe_failed": "O SSH conectou, mas não conseguiu verificar o nanobot. Confirme se esta conta pode executar comandos Python não interativos.",+ "invalid_ssh_command": "Use um alias, usuário@servidor ou ssh com -p, -i, -F e -l. Coloque caminhos com espaços entre aspas. Adicione outras opções à configuração SSH; comandos remotos não são compatíveis.","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.",@@ -79,10 +181,11 @@"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.",+ "file_picker_unavailable": "Não foi possível abrir o seletor. Você pode colar o caminho de um arquivo local.","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_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.","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.",@@ -92,7 +195,7 @@"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.",+ "invalid_profile": "Check the address, port and Connection options fields.","profile_not_found": "This saved server no longer exists. Refresh the list.","profile_limit": "You can save up to 20 servers.","connection_limit": "Disconnect an existing server before opening another connection.",diff --git a/webui/src/i18n/locales/vi/common.json b/webui/src/i18n/locales/vi/common.jsonindex a7c309f9e..6da9e0cba 100644--- a/webui/src/i18n/locales/vi/common.json+++ b/webui/src/i18n/locales/vi/common.json@@ -1,5 +1,96 @@{"remote": {+ "activeForgetWarning": "Tất cả thẻ đang dùng kết nối này sẽ bị ngắt. Nội dung chưa lưu có thể bị mất.",+ "saved": "Đã lưu",+ "pair": {+ "expiringDevice": "Quyền truy cập hết hạn vào {{date}}.",+ "expiredDevice": "Quyền truy cập đã hết hạn. Hãy ghép nối lại máy chủ trước khi kết nối lại.",+ "introHint": "Chạy một lệnh trong terminal máy chủ để kết nối.",+ "copiedTitle": "Đã sao chép lệnh",+ "afterCopyHint": "Dán và chạy trong terminal máy chủ. Sau khi cấp quyền, mở liên kết được trả về trên máy tính này.",+ "copyAgain": "Sao chép lại",+ "otherWays": "Cách khác",+ "helpTitle": "Yêu cầu và trợ giúp",+ "validityHint": "Lệnh hết hạn sau 10 phút. Kiểm tra quyền truy cập trước khi cấp quyền.",+ "linkDescription": "Chạy lệnh trên máy chủ, rồi quay lại bằng liên kết trong terminal.",+ "preparing": "Đang chuẩn bị kết nối…",+ "linkRunHint": "Dán lệnh vào terminal đám mây và cấp quyền cho máy tính này. Lệnh có hiệu lực trong 10 phút.",+ "showCommand": "Xem lệnh",+ "checkingLink": "Đang kiểm tra liên kết…",+ "returnTitle": "2. Quay lại nanobot",+ "returnHint": "Sau khi cấp quyền, mở liên kết trong terminal trên máy tính này. Thông tin kết nối sẽ được điền tự động.",+ "pasteInstead": "Dùng mã kết nối",+ "confirmLinkDescription": "Chỉ tiếp tục nếu liên kết hoặc mã đến từ terminal máy chủ đáng tin cậy của chính bạn.",+ "route": "Đường truyền mạng…",+ "direct": "Kết nối trực tiếp",+ "savedRoute": "Đường truyền đã lưu",+ "routeDescription": "Dành cho VPN hoặc tuyến SSH đặc biệt đã có.",+ "routeHint": "Dùng lại đường truyền của kết nối SSH đã lưu tới cùng máy chủ, không sao chép khóa hay thông tin đăng nhập.",+ "title": "Kết nối không cần cấu hình SSH",+ "description": "Chạy một lệnh trong bảng điều khiển máy chủ, rồi dán mã kết nối vào đây.",+ "steps": {+ "run": "Sao chép lệnh ghép nối vào terminal máy chủ.",+ "paste": "Dán mã do máy chủ cung cấp.",+ "connect": "Xác nhận máy chủ và mở nanobot."+ },+ "requirements": "Dành cho máy chủ Linux đã cài nanobot. SSH vẫn phải truy cập được; không cần máy chủ trung gian hay WebUI công khai.",+ "useSSH": "Dùng cấu hình SSH có sẵn",+ "start": "Lấy lệnh ghép nối",+ "runTitle": "1. Chạy trên máy chủ",+ "runHint": "Mở terminal của bảng điều khiển đám mây, dán lệnh và làm theo hướng dẫn. Máy chủ cũng cần phiên bản nanobot hỗ trợ tính năng này.",+ "command": "Lệnh ghép nối",+ "copy": "Sao chép lệnh",+ "copied": "Đã sao chép",+ "copyFailed": "Không thể sao chép. Hãy chọn và sao chép lệnh ở trên.",+ "code": "Mã kết nối",+ "codeHint": "Dùng mã bắt đầu bằng nbpc1. trong terminal. Mã chỉ dùng được với yêu cầu cục bộ này.",+ "expired": "Yêu cầu đã hết hạn. Hãy tạo lệnh mới. Nếu đã cấp quyền trên máy chủ, hãy dùng lệnh thu hồi được hiển thị ở đó.",+ "restart": "Lấy lệnh mới",+ "review": "Kiểm tra kết nối",+ "confirmTitle": "Mở nanobot này?",+ "confirmDescription": "Chỉ tiếp tục với mã được sao chép từ terminal máy chủ đáng tin cậy của chính bạn.",+ "access": "Máy tính này sẽ có toàn quyền truy cập trò chuyện, cài đặt và công cụ đã bật của nanobot này.",+ "expiry": "Quyền thiết bị hết hạn vào {{date}}. Phạm vi mở cổng SSH và nanobot hiện có không thay đổi.",+ "security": "Chi tiết và thu hồi quyền",+ "fingerprint": "Máy chủ SSH phải khớp với dấu vân tay từ bảng điều khiển này:",+ "revoke": "Để thu hồi kết nối mới, chạy lệnh này trên máy chủ và đóng các phiên từ xa đang mở:",+ "retryHint": "Đã lưu ghép nối. Bạn có thể thử lại mà không chạy lại lệnh trên máy chủ. Ghép nối không vượt qua việc chặn SSH của mạng hoặc VPN.",+ "forgetHint": "Quên chỉ xóa kết nối khỏi danh sách, không thu hồi quyền trên máy chủ. Để thu hồi, chạy trên máy chủ:"+ },+ "setup": {+ "progress": "Thiết lập kết nối",+ "server": "Máy chủ",+ "nanobot": "nanobot",+ "signedIn": "Đã kết nối SSH",+ "changeServer": "Đổi",+ "chooseNanobot": "Bạn muốn mở nanobot nào?",+ "yourNanobot": "nanobot của bạn",+ "serviceAccount": "Chạy bằng tài khoản {{user}}. Sử dụng quyền sudo hiện có của tài khoản này.",+ "notFound": "Không tìm thấy cấu hình nanobot",+ "notFoundHint": "Kiểm tra nanobot đã được cài và đang chạy. Với Docker hoặc cài đặt tùy chỉnh, hãy hỏi người triển khai về đường dẫn và tài khoản dịch vụ.",+ "limitedSearch": "Đã kiểm tra cấu hình của bạn và các dịch vụ hệ thống nanobot. Cài đặt khác có thể cần chỉ định đường dẫn.",+ "manualLocation": "Chỉ định vị trí khác",+ "keyHint": "Đường dẫn tệp khóa SSH riêng trên máy này, không phải nội dung khóa hay khóa API. Chưa hỗ trợ đăng nhập SSH chỉ bằng mật khẩu.",+ "locationHint": "Đường dẫn và tài khoản trên máy chủ. Không cài đặt hay thay đổi quyền.",+ "sshSettings": "Thiết lập đăng nhập SSH",+ "checking": "Đang đăng nhập và tìm nanobot…",+ "opening": "Đang mở nanobot hiện có…",+ "openNanobot": "Mở nanobot",+ "chooseFile": "Chọn tệp: {{field}}",+ "pickingFile": "Chọn tệp trong hộp thoại hệ thống…"+ },+ "searchHosts": "Tìm máy chủ…",+ "noMatchingHosts": "Không có máy chủ phù hợp",+ "commandHint": "Nhập người_dùng@máy_chủ hoặc chọn máy SSH. Chúng tôi sẽ dùng thiết lập hiện có để đăng nhập, rồi tìm nanobot.",+ "commandImported": "Đã điền các tùy chọn SSH. Bạn có thể xem lại trong Tùy chọn kết nối.",+ "hostPlaceholder": "Host alias or user@server",+ "addressHint": "Your existing SSH username, key and port are used automatically.",+ "manualAddress": "No matching alias. You can connect with the address above.",+ "connectionOptions": "Connection options",+ "editDescription": "Save your changes here, then connect when you’re ready.",+ "save": "Save changes",+ "saving": "Saving…",+ "connect": "Connect","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.",@@ -11,19 +102,11 @@"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)",+ "portPlaceholder": "From SSH config","loading": "Loading connections…","retry": "Retry","unavailable": "Open this page from a locally running nanobot to connect to servers over SSH.",@@ -39,20 +122,17 @@"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.",+ "add": "Add server",+ "addTitle": "Connect to a server",+ "addDescription": "Connect to an existing nanobot. Chats and settings stay on the 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}}",@@ -65,6 +145,28 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "disconnected": "Kết nối dùng chung này đã đóng. Bạn có thể kết nối lại khi sẵn sàng.",+ "instance_changed": "Kết nối đến máy chủ này đã thay đổi. Kết nối lại sẽ tải lại giao diện; bản nháp chưa gửi có thể bị mất.",+ "pair_authorization_rejected": "Máy chủ không còn chấp nhận khóa của thiết bị này. Quyền truy cập có thể đã bị thu hồi hoặc hết hạn. Hãy ghép nối lại từ bảng điều khiển máy chủ.",+ "pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",+ "pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",+ "pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",+ "pair_expired": "This pairing request expired. Generate a new command.",+ "pair_authorization_expired": "This device authorization expired. Pair the server again.",+ "pair_used": "This request was already used. Generate a new one.",+ "pair_limit": "Close unused pairing windows and try again.",+ "pair_managed": "Pair again to change the server or credentials.",+ "ssh_connection_closed": "Kết nối SSH đóng trong khi thiết lập. Chưa thể kết luận là lỗi khóa. Kiểm tra VPN/proxy hoặc dùng thiết lập SSH hoạt động trong terminal.",+ "ssh_refused": "Máy chủ từ chối SSH. Kiểm tra cổng và dịch vụ SSH.",+ "ssh_host_not_found": "Không phân giải được tên máy chủ. Kiểm tra địa chỉ hoặc chọn máy từ cấu hình SSH.",+ "ssh_too_many_keys": "SSH thử quá nhiều khóa. Chỉ định khóa đúng và IdentitiesOnly yes trong cấu hình SSH.",+ "duplicate_instance": "Nanobot này đã được kết nối qua một địa chỉ SSH khác. Hãy dùng kết nối hiện có trong menu Chuyển máy chủ.",+ "ssh_agent_refused": "SSH agent từ chối sử dụng khóa. Hãy mở khóa hoặc chấp thuận trong trình quản lý khóa rồi thử lại. Nếu chỉ kết nối được từ terminal, hãy khởi động lại nanobot từ terminal đó.",+ "ssh_key_permissions": "SSH từ chối quyền của tệp khóa riêng. Hãy giới hạn quyền truy cập cho tài khoản của bạn rồi thử lại.",+ "ssh_config_invalid": "OpenSSH không đọc được thiết lập kết nối. Hãy kiểm tra cấu hình SSH đã chọn trong terminal.",+ "ssh_forwarding_denied": "Đã đăng nhập SSH nhưng máy chủ chặn chuyển tiếp cổng. Hãy nhờ quản trị viên cho phép chuyển tiếp đến cổng loopback của nanobot.",+ "probe_failed": "Đã đăng nhập SSH nhưng không chạy được bước kiểm tra nanobot. Hãy xác nhận tài khoản này chạy được lệnh Python không tương tác.",+ "invalid_ssh_command": "Dùng bí danh, người_dùng@máy_chủ hoặc ssh với -p, -i, -F và -l. Đặt đường dẫn có dấu cách trong dấu nháy. Các tùy chọn khác cần đặt trong cấu hình SSH; không hỗ trợ lệnh từ xa.","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.",@@ -79,10 +181,11 @@"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.",+ "file_picker_unavailable": "Không thể mở hộp thoại chọn tệp. Bạn có thể dán đường dẫn tệp cục bộ.","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_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.","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.",@@ -92,7 +195,7 @@"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.",+ "invalid_profile": "Check the address, port and Connection options fields.","profile_not_found": "This saved server no longer exists. Refresh the list.","profile_limit": "You can save up to 20 servers.","connection_limit": "Disconnect an existing server before opening another connection.",diff --git a/webui/src/i18n/locales/zh-CN/common.json b/webui/src/i18n/locales/zh-CN/common.jsonindex bf11a02c3..754754ea8 100644--- a/webui/src/i18n/locales/zh-CN/common.json+++ b/webui/src/i18n/locales/zh-CN/common.json@@ -1,5 +1,96 @@{"remote": {+ "activeForgetWarning": "也会断开正在使用此连接的标签页,未保存的内容可能丢失。",+ "saved": "已保存",+ "pair": {+ "expiringDevice": "授权将于 {{date}} 到期。",+ "expiredDevice": "授权已到期,重新连接前请再次配对。",+ "introHint": "在服务器终端运行一条命令,即可开始连接。",+ "copiedTitle": "命令已复制",+ "afterCopyHint": "去服务器终端粘贴运行。确认授权后,点击返回链接回到这里。",+ "copyAgain": "再次复制",+ "otherWays": "其他连接方式",+ "helpTitle": "使用条件与帮助",+ "validityHint": "命令 10 分钟内有效。授权前,请确认访问权限。",+ "linkDescription": "在服务器运行命令,再点击终端里的链接回到这里。",+ "preparing": "正在准备连接…",+ "linkRunHint": "将命令粘贴到云服务器终端,按提示授权这台电脑。命令有效期为 10 分钟。",+ "showCommand": "查看命令",+ "checkingLink": "正在核对连接链接…",+ "returnTitle": "2. 返回 nanobot",+ "returnHint": "授权后,在这台电脑上打开终端给出的链接,连接信息会自动填好。",+ "pasteInstead": "改用连接码",+ "confirmLinkDescription": "请确认链接或连接码来自你自己的可信服务器终端。",+ "route": "网络连接方式…",+ "direct": "直接连接",+ "savedRoute": "已保存的网络路径",+ "routeDescription": "适用于 VPN 或已有特殊 SSH 网络路径。",+ "routeHint": "可以借用同一服务器已有 SSH 连接的网络路径。不会复制其登录密钥或凭据。",+ "title": "无需配置 SSH,连接服务器",+ "description": "在云服务器终端运行一条命令,再把连接码贴回来。",+ "steps": {+ "run": "把配对命令复制到服务器终端运行。",+ "paste": "贴回服务器生成的连接码。",+ "connect": "确认服务器,打开 nanobot。"+ },+ "requirements": "适用于已安装 nanobot 的 Linux 服务器。仍需 SSH 网络可达;不需要中继,也不用公开 WebUI。",+ "useSSH": "使用已有 SSH 配置",+ "start": "获取配对命令",+ "runTitle": "1. 在服务器上运行",+ "runHint": "打开云控制台的终端,粘贴命令并按提示操作。服务器也需要安装支持此功能的 nanobot 版本。",+ "command": "配对命令",+ "copy": "复制命令",+ "copied": "已复制",+ "copyFailed": "复制失败,请选中上面的命令手动复制。",+ "code": "连接码",+ "codeHint": "粘贴终端里以 nbpc1. 开头的连接码,只能用于本次本地配对。",+ "expired": "配对请求已过期,请重新生成命令。如果已在服务器授权,请用终端显示的撤销命令清理旧授权。",+ "restart": "重新获取命令",+ "review": "确认连接信息",+ "confirmTitle": "打开这个 nanobot?",+ "confirmDescription": "请确认连接码来自你自己的可信服务器终端。",+ "access": "这台电脑将能访问此 nanobot 的聊天、设置,以及已启用的工具。",+ "expiry": "设备授权有效期至 {{date}}。不会更改服务器现有的 SSH 和 nanobot 端口开放范围。",+ "security": "连接详情与撤销授权",+ "fingerprint": "连接时会核对服务器终端提供的 SSH 指纹:",+ "revoke": "如需撤销新连接,在服务器运行以下命令,并关闭已打开的远程会话:",+ "retryHint": "配对已保存,无需重复运行服务器命令。若网络或 VPN 阻断 SSH,配对无法绕过该限制。",+ "forgetHint": "忘记连接只会从本地列表移除,不会撤销服务器授权。撤销设备请在服务器运行:"+ },+ "setup": {+ "progress": "连接设置",+ "server": "服务器",+ "nanobot": "nanobot",+ "signedIn": "SSH 已连接",+ "changeServer": "更改",+ "chooseNanobot": "打开哪一个 nanobot?",+ "yourNanobot": "你的 nanobot",+ "serviceAccount": "运行账户为 {{user}}。打开时将使用已有的 sudo 权限。",+ "notFound": "没有找到 nanobot 配置",+ "notFoundHint": "请确认服务器已安装并运行 nanobot。Docker 或自定义部署需要向部署者获取配置路径和服务账户。",+ "limitedSearch": "已检查你的配置和 nanobot 系统服务。其他部署方式可能需要在下方指定路径。",+ "manualLocation": "指定其他位置",+ "keyHint": "填写这台电脑上的 SSH 私钥文件路径,不是密钥内容或模型 API Key。暂不支持仅用 SSH 密码登录。",+ "locationHint": "这里填写服务器上的路径和账户。不会安装程序或修改权限。",+ "sshSettings": "SSH 登录设置",+ "checking": "正在登录并寻找 nanobot…",+ "opening": "正在打开已有的 nanobot…",+ "openNanobot": "打开 nanobot",+ "chooseFile": "选择文件:{{field}}",+ "pickingFile": "请在系统窗口中选择文件…"+ },+ "searchHosts": "搜索主机…",+ "noMatchingHosts": "没有匹配的主机",+ "commandHint": "填写 用户名@服务器,或选择已有 SSH 主机。我们会先登录服务器,再寻找 nanobot。",+ "commandImported": "已填入 SSH 设置,可在「连接选项」中查看。",+ "hostPlaceholder": "主机别名或 用户名@服务器",+ "addressHint": "自动沿用已有 SSH 配置中的用户名、密钥和端口。",+ "manualAddress": "没有匹配的别名,也可以直接连接上面输入的地址。",+ "connectionOptions": "连接选项",+ "editDescription": "保存连接设置,不会立即切换到服务器。",+ "save": "保存修改",+ "saving": "正在保存…",+ "connect": "连接","localShort": "本地","disconnectTitle": "断开与 {{name}} 的连接?","disconnectDescription": "将关闭此服务器页面及共享的 SSH 连接,可能丢失未保存的内容,并影响其他正在使用此连接的标签页。服务器上的 nanobot 会继续运行。",@@ -11,19 +102,11 @@"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)",+ "portPlaceholder": "沿用 SSH 配置","loading": "正在读取连接…","retry": "重试","unavailable": "请从本地运行的 nanobot 打开此页面,才能通过 SSH 连接服务器。",@@ -39,20 +122,17 @@"current": "正在使用","remote": "远程","returnLocal": "切回本地 nanobot",- "add": "连接远程 nanobot…",- "addTitle": "连接远程 nanobot",- "addDescription": "连接服务器上已经运行的 nanobot。",+ "add": "添加服务器",+ "addTitle": "连接服务器",+ "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",@@ -65,6 +145,28 @@"forgetTitle": "忘记 {{name}}?","forgetDescription": "只移除本机保存的连接。服务器上的 nanobot、密钥和会话都不会被删除。","errors": {+ "disconnected": "此共享连接已断开,需要时可重新连接。",+ "instance_changed": "此服务器的连接已发生变化。重新连接会重新打开页面,未发送的草稿可能丢失。",+ "pair_authorization_rejected": "服务器不再接受这台设备的密钥,授权可能已撤销或过期。请从服务器终端重新配对。",+ "pair_route_mismatch": "请选择指向同一台服务器的 SSH 连接。",+ "pair_route_unsupported": "此连接使用了跳板机,请使用原有 SSH 连接入口。",+ "pair_invalid": "连接码无效,或不属于本次配对,请从服务器终端重新复制。",+ "pair_expired": "配对请求已过期,请重新获取命令。",+ "pair_authorization_expired": "设备授权已过期,请重新配对。",+ "pair_used": "此请求已使用,请重新获取命令。",+ "pair_limit": "请关闭其他配对窗口后重试。",+ "pair_managed": "更换服务器或凭据请重新配对。",+ "ssh_connection_closed": "SSH 连接在建立过程中断开,还不能判断是密钥问题。请检查 VPN/代理,或使用终端中能登录的 SSH 配置。",+ "ssh_refused": "服务器拒绝了 SSH 连接。请检查 SSH 端口及服务是否运行。",+ "ssh_host_not_found": "无法解析服务器名称。请检查地址,或从 SSH 配置中选择主机。",+ "ssh_too_many_keys": "SSH 尝试了过多密钥。请在 SSH 配置中指定正确密钥,并设置 IdentitiesOnly yes。",+ "duplicate_instance": "这个 nanobot 已通过另一个 SSH 地址连接,请在「切换主机」中使用已有连接。",+ "ssh_agent_refused": "SSH 密钥代理未同意使用密钥。请在密钥管理器中解锁或确认后重试。如果只有终端能连接,请从那个终端重新启动 nanobot。",+ "ssh_key_permissions": "SSH 拒绝使用权限过宽的私钥文件。请将文件访问权限限制为你的账号后重试。",+ "ssh_config_invalid": "OpenSSH 无法读取这些连接设置,请在终端检查所选 SSH 配置。",+ "ssh_forwarding_denied": "SSH 已登录,但服务器禁止端口转发。请让管理员允许转发到 nanobot 的回环端口。",+ "probe_failed": "SSH 已登录,但未能运行 nanobot 检查。请确认该账号能执行非交互式 Python 命令。",+ "invalid_ssh_command": "可输入主机别名、用户名@服务器,或含 -p、-i、-F、-l 的 ssh 命令。含空格的路径请加引号;其他选项请写入 SSH 配置,不支持附带远程命令。","view_limit": "已保留 3 个服务器界面。请在管理连接中断开其中一个,再打开新服务器。","view_load_failed": "服务器界面加载较慢,请重试。当前界面保持不变。","same_instance": "这是你当前正在使用的 nanobot,无需再次连接。",@@ -79,10 +181,11 @@"host_key_unknown": "本机还没有验证过这台服务器。请先与服务器管理员核对 SSH 指纹后再连接。","host_key_changed": "服务器的 SSH 身份发生了变化,已阻止连接。请先与管理员确认,不要跳过这个警告。","local_file_not_found": "本机找不到指定的 SSH 配置文件或私钥。",+ "file_picker_unavailable": "无法打开文件选择窗口,也可以直接填写本机文件路径。","runtime_user_denied": "SSH 已登录,但不能免密切换到这个运行账号,请与服务器管理员确认。","python_unavailable": "服务器需要 python3 来读取已有的 nanobot 配置。",- "config_not_found": "找不到 nanobot 配置,请在「高级」中填写它在服务器上的路径。",- "config_permission": "SSH 账号无权读取 nanobot 配置,请在「高级」中填写 nanobot 的运行账号。",+ "config_not_found": "找不到 nanobot 配置,请在「连接选项」中填写它在服务器上的路径。",+ "config_permission": "SSH 账号无权读取 nanobot 配置,请在「连接选项」中填写 nanobot 的运行账号。","config_invalid": "无法读取服务器上的 nanobot 配置。","webui_disabled": "服务器的 WebUI 尚未启用,请先在服务器上开启。","webui_auth_required": "服务器需要在配置中设置 WebUI 登录密钥。这里不需要模型 Key。",@@ -92,7 +195,7 @@"webui_unavailable": "Gateway 在运行,但没有安装 WebUI。","remote_unreachable": "SSH 已连接,但 nanobot WebUI 没有响应,请确认它正在运行。","profile_store_invalid": "无法读取已保存的连接,原文件未被覆盖。",- "invalid_profile": "请检查服务器地址、端口和高级选项。",+ "invalid_profile": "请检查服务器地址、端口和连接选项。","profile_not_found": "这个连接已不存在,请刷新列表。","profile_limit": "最多可以保存 20 台服务器。","connection_limit": "请先断开一台服务器,再建立新连接。",diff --git a/webui/src/i18n/locales/zh-TW/common.json b/webui/src/i18n/locales/zh-TW/common.jsonindex 09d6fb16b..b12bc2df6 100644--- a/webui/src/i18n/locales/zh-TW/common.json+++ b/webui/src/i18n/locales/zh-TW/common.json@@ -1,5 +1,96 @@{"remote": {+ "activeForgetWarning": "也會中斷正在使用此連線的分頁,未儲存的內容可能遺失。",+ "saved": "已儲存",+ "pair": {+ "expiringDevice": "授權將於 {{date}} 到期。",+ "expiredDevice": "授權已到期,重新連線前請再次配對。",+ "introHint": "在伺服器終端執行一條指令,即可開始連線。",+ "copiedTitle": "指令已複製",+ "afterCopyHint": "到伺服器終端貼上執行。確認授權後,點擊返回連結回到這裡。",+ "copyAgain": "再次複製",+ "otherWays": "其他連線方式",+ "helpTitle": "使用條件與說明",+ "validityHint": "指令 10 分鐘內有效。授權前,請確認存取權限。",+ "linkDescription": "在伺服器執行命令,再點擊終端裡的連結回到這裡。",+ "preparing": "正在準備連線…",+ "linkRunHint": "將命令貼到雲端伺服器終端,依提示授權這台電腦。命令有效期為 10 分鐘。",+ "showCommand": "檢視命令",+ "checkingLink": "正在核對連線連結…",+ "returnTitle": "2. 返回 nanobot",+ "returnHint": "授權後,在這台電腦上開啟終端提供的連結,連線資訊會自動填入。",+ "pasteInstead": "改用連線碼",+ "confirmLinkDescription": "請確認連結或連線碼來自你自己的可信伺服器終端。",+ "route": "網路連線方式…",+ "direct": "直接連線",+ "savedRoute": "已儲存的網路路徑",+ "routeDescription": "適用於 VPN 或既有的特殊 SSH 網路路徑。",+ "routeHint": "可沿用同一伺服器既有 SSH 連線的網路路徑,不會複製登入金鑰或憑證。",+ "title": "無需設定 SSH,連線伺服器",+ "description": "在雲端伺服器終端執行一條指令,再把連線碼貼回來。",+ "steps": {+ "run": "複製配對指令,在伺服器終端執行。",+ "paste": "貼回伺服器產生的連線碼。",+ "connect": "確認伺服器並開啟 nanobot。"+ },+ "requirements": "適用於已安裝 nanobot 的 Linux 伺服器。仍需能透過 SSH 連線;不需要中繼,也不用公開 WebUI。",+ "useSSH": "使用既有 SSH 設定",+ "start": "取得配對指令",+ "runTitle": "1. 在伺服器上執行",+ "runHint": "開啟雲端控制台終端,貼上指令並依提示操作。伺服器也需要支援此功能的 nanobot 版本。",+ "command": "配對指令",+ "copy": "複製指令",+ "copied": "已複製",+ "copyFailed": "複製失敗,請選取上方指令手動複製。",+ "code": "連線碼",+ "codeHint": "貼上終端中以 nbpc1. 開頭的連線碼,只能用於本次本機配對。",+ "expired": "配對請求已過期,請重新產生指令。若已在伺服器授權,請使用終端顯示的撤銷指令清除舊授權。",+ "restart": "重新取得指令",+ "review": "確認連線資訊",+ "confirmTitle": "開啟這個 nanobot?",+ "confirmDescription": "請確認連線碼來自你自己的可信伺服器終端。",+ "access": "這台電腦將能存取此 nanobot 的聊天、設定與已啟用工具。",+ "expiry": "裝置授權有效至 {{date}}。不會變更伺服器現有的 SSH 和 nanobot 連接埠開放範圍。",+ "security": "連線詳情與撤銷授權",+ "fingerprint": "連線時會核對伺服器終端提供的 SSH 指紋:",+ "revoke": "若要撤銷新連線,請在伺服器執行以下指令,並關閉已開啟的遠端工作階段:",+ "retryHint": "配對已儲存,無需重複執行伺服器指令。若網路或 VPN 阻擋 SSH,配對無法繞過該限制。",+ "forgetHint": "忘記連線只會移除本機列表項目,不會撤銷伺服器授權。撤銷裝置請在伺服器執行:"+ },+ "setup": {+ "progress": "連線設定",+ "server": "伺服器",+ "nanobot": "nanobot",+ "signedIn": "SSH 已連線",+ "changeServer": "變更",+ "chooseNanobot": "開啟哪一個 nanobot?",+ "yourNanobot": "你的 nanobot",+ "serviceAccount": "執行帳戶為 {{user}}。開啟時將使用既有的 sudo 權限。",+ "notFound": "找不到 nanobot 設定",+ "notFoundHint": "請確認伺服器已安裝並執行 nanobot。Docker 或自訂部署需要向部署者取得設定路徑和服務帳戶。",+ "limitedSearch": "已檢查你的設定和 nanobot 系統服務。其他部署方式可能需要在下方指定路徑。",+ "manualLocation": "指定其他位置",+ "keyHint": "填寫這台電腦上的 SSH 私密金鑰檔案路徑,不是金鑰內容或模型 API Key。暫不支援僅用 SSH 密碼登入。",+ "locationHint": "這裡填寫伺服器上的路徑和帳戶。不會安裝程式或修改權限。",+ "sshSettings": "SSH 登入設定",+ "checking": "正在登入並尋找 nanobot…",+ "opening": "正在開啟既有的 nanobot…",+ "openNanobot": "開啟 nanobot",+ "chooseFile": "選擇檔案:{{field}}",+ "pickingFile": "請在系統視窗中選擇檔案…"+ },+ "searchHosts": "搜尋主機…",+ "noMatchingHosts": "沒有符合的主機",+ "commandHint": "填寫 使用者名稱@伺服器,或選擇既有 SSH 主機。我們會先登入伺服器,再尋找 nanobot。",+ "commandImported": "已填入 SSH 設定,可在「連線選項」中查看。",+ "hostPlaceholder": "主機別名或 使用者名稱@伺服器",+ "addressHint": "自動沿用既有 SSH 設定中的使用者名稱、金鑰和連接埠。",+ "manualAddress": "沒有符合的別名,也可以直接連線到上方輸入的位址。",+ "connectionOptions": "連線選項",+ "editDescription": "儲存連線設定,不會立即切換到伺服器。",+ "save": "儲存變更",+ "saving": "正在儲存…",+ "connect": "連線","localShort": "本地","disconnectTitle": "中斷與 {{name}} 的連線?","disconnectDescription": "將關閉此伺服器頁面及共用的 SSH 連線,可能遺失未儲存的內容,並影響其他正在使用此連線的分頁。伺服器上的 nanobot 會繼續執行。",@@ -11,19 +102,11 @@"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)",+ "portPlaceholder": "沿用 SSH 設定","loading": "正在讀取連線…","retry": "重試","unavailable": "請從本機執行的 nanobot 開啟此頁面,才能透過 SSH 連線伺服器。",@@ -39,20 +122,17 @@"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.",+ "add": "新增伺服器",+ "addTitle": "連線伺服器",+ "addDescription": "連線至已執行的 nanobot,聊天和設定留在伺服器。","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}}",@@ -65,6 +145,28 @@"forgetTitle": "Forget {{name}}?","forgetDescription": "Only this saved connection will be removed. nanobot, its keys and conversations on the server will stay untouched.","errors": {+ "disconnected": "此共用連線已中斷,需要時可重新連線。",+ "instance_changed": "此伺服器的連線已發生變化。重新連線會重新開啟頁面,未傳送的草稿可能遺失。",+ "pair_authorization_rejected": "伺服器不再接受這台裝置的金鑰,授權可能已撤銷或過期。請從伺服器終端重新配對。",+ "pair_route_mismatch": "Choose an SSH connection that resolves to this same server.",+ "pair_route_unsupported": "This saved route uses a jump host. Use the existing SSH connection instead.",+ "pair_invalid": "This code is invalid or belongs to another request. Copy it again from your server terminal.",+ "pair_expired": "This pairing request expired. Generate a new command.",+ "pair_authorization_expired": "This device authorization expired. Pair the server again.",+ "pair_used": "This request was already used. Generate a new one.",+ "pair_limit": "Close unused pairing windows and try again.",+ "pair_managed": "Pair again to change the server or credentials.",+ "ssh_connection_closed": "SSH 連線在建立過程中中斷,尚無法判斷是否為金鑰問題。請檢查 VPN/代理,或使用終端機中能登入的 SSH 設定。",+ "ssh_refused": "伺服器拒絕了 SSH 連線。請檢查 SSH 連接埠及服務是否執行。",+ "ssh_host_not_found": "無法解析伺服器名稱。請檢查位址,或從 SSH 設定中選擇主機。",+ "ssh_too_many_keys": "SSH 嘗試了過多金鑰。請在 SSH 設定中指定正確金鑰,並設定 IdentitiesOnly yes。",+ "duplicate_instance": "這個 nanobot 已透過另一個 SSH 位址連線,請在「切換主機」中使用現有連線。",+ "ssh_agent_refused": "SSH 金鑰代理未同意使用金鑰。請在金鑰管理器中解鎖或確認後重試。如果只有終端機能連線,請從該終端機重新啟動 nanobot。",+ "ssh_key_permissions": "SSH 拒絕使用權限過寬的私鑰檔案。請將檔案存取權限限制為你的帳號後重試。",+ "ssh_config_invalid": "OpenSSH 無法讀取這些連線設定,請在終端機檢查所選 SSH 設定。",+ "ssh_forwarding_denied": "SSH 已登入,但伺服器禁止連接埠轉送。請讓管理員允許轉送至 nanobot 的回環連接埠。",+ "probe_failed": "SSH 已登入,但未能執行 nanobot 檢查。請確認該帳號能執行非互動式 Python 指令。",+ "invalid_ssh_command": "可輸入主機別名、使用者@伺服器,或含 -p、-i、-F、-l 的 ssh 指令。含空格的路徑請加引號;其他選項請寫入 SSH 設定,不支援附帶遠端指令。","view_limit": "已保留 3 个服务器界面。请在管理连接中断开其中一个,再打开新服务器。","view_load_failed": "服务器界面加载较慢,请重试。当前界面保持不变。","same_instance": "This is the nanobot you are already using. No remote connection is needed.",@@ -79,10 +181,11 @@"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.",+ "file_picker_unavailable": "無法開啟檔案選擇視窗,也可以直接填寫本機檔案路徑。","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_not_found": "nanobot's config wasn't found. Set its server-side path in Connection options.",+ "config_permission": "This SSH user can't read nanobot's config. Set the nanobot service account in Connection options.","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.",@@ -92,7 +195,7 @@"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.",+ "invalid_profile": "Check the address, port and Connection options fields.","profile_not_found": "This saved server no longer exists. Refresh the list.","profile_limit": "You can save up to 20 servers.","connection_limit": "Disconnect an existing server before opening another connection.",diff --git a/webui/src/lib/remote-instances.ts b/webui/src/lib/remote-instances.tsindex 6f792d66d..330a121b9 100644--- a/webui/src/lib/remote-instances.ts+++ b/webui/src/lib/remote-instances.ts@@ -11,6 +11,17 @@ export interface RemoteProfile {config_path: string;runtime_user: string;connected: boolean;+ gateway_id?: string;+ view_id?: string;+ connection_error?: string;+ paired?: boolean;+ revoke_command?: string;+ authorized_until?: number;+}++/** Persistent setup problems need a repair path, not an endless Retry button. */+export function needsRemoteSetup(code: string): boolean {+ return /^(pair_|host_key_|ssh_auth_failed$|ssh_agent_refused$|ssh_key_permissions$|ssh_config_|local_file_not_found$|remote_auth_failed$|incompatible_gateway$|webui_disabled$|profile_not_found$)/.test(code);}export interface RemoteDirectory {@@ -32,9 +43,22 @@ export interface RemoteConnection {hostname: string;config_path: string;gateway_id: string;+ view_id?: string;url: string;}+export interface RemoteLocation {+ config_path: string;+ runtime_user: string;+ service: string;+}++export interface RemoteInspection {+ hostname: string;+ candidates: RemoteLocation[];+ incomplete: boolean;+}+export async function readRemoteInstances(token: string): Promise<RemoteDirectory> {const response = await fetchWithTimeout("/api/remote-instances", {headers: { Authorization: `Bearer ${token}` },@@ -47,7 +71,7 @@ export async function readRemoteInstances(token: string): Promise<RemoteDirectorexport function remoteAction<T>(client: WebUIMutationTransport, action: string, payload: Record<string, unknown>,): Promise<T> {- return client.requestMutation<T>(`remote.${action}`, payload, 65_000);+ return client.requestMutation<T>(`remote.${action}`, payload, action === "pick_file" ? 310_000 : 65_000);}/** Never let a server response navigate the shell to an arbitrary origin. */@@ -62,6 +86,23 @@ export function validateRemoteConnection(connection: RemoteConnection): RemoteCoexport type SelectedRemote = Pick<RemoteConnection, "id" | "name" | "hostname">;const SELECTED_REMOTE = "nanobot.remote-instance";+const RECENT_REMOTES = "nanobot.recent-remote-instances";++/** Only profile IDs are persisted, never connection URLs or credentials. */+export function readRecentRemotes(): string[] {+ try {+ const value: unknown = JSON.parse(window.localStorage.getItem(RECENT_REMOTES) || "[]");+ return Array.isArray(value) ? [...new Set(value.filter((id): id is string =>+ typeof id === "string" && /^[a-f0-9-]{36}$/.test(id)))].slice(0, 20) : [];+ } catch { return []; }+}++export function rememberRecentRemote(id: string, previous: string[]): string[] {+ const next = [id, ...previous.filter((item) => item !== id)].slice(0, 20);+ try { window.localStorage.setItem(RECENT_REMOTES, JSON.stringify(next)); }+ catch { /* Switching still works when browser storage is disabled. */ }+ return next;+}export function readSelectedRemote(): SelectedRemote | null {try {diff --git a/webui/src/lib/remote-pair-return.ts b/webui/src/lib/remote-pair-return.tsnew file mode 100644index 000000000..64ec47f7c--- /dev/null+++ b/webui/src/lib/remote-pair-return.ts@@ -0,0 +1,51 @@+/** One-shot handoff from a trusted server console, held in memory, never storage. */+export interface PairReturn { id: string; code: string }++let pending: PairReturn | null = null;+const listeners = new Set<() => void>();++export function parsePairReturn(hash: string): PairReturn | null {+ const [path, query = ""] = hash.split("?", 2);+ if (path !== "#/remote") return null;+ const params = new URLSearchParams(query);+ if (!params.has("pairing")) return null;+ const invalid = { id: "", code: "" };+ const code = params.get("pairing") || "";+ if (params.getAll("pairing").length !== 1 || code.length > 32768 || !/^nbpc1\.[A-Za-z0-9_-]+$/.test(code)) return invalid;+ try {+ const encoded = code.slice(6).replace(/-/g, "+").replace(/_/g, "/");+ const envelope: unknown = JSON.parse(atob(encoded.padEnd(Math.ceil(encoded.length / 4) * 4, "=")));+ if (!envelope || typeof envelope !== "object" || !("id" in envelope)+ || typeof envelope.id !== "string" || !/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(envelope.id)) return invalid;+ // The backend must decrypt and validate this. A parsed ID grants no access.+ return { id: envelope.id, code };+ } catch { return invalid; }+}++export function initializePairReturn(): void {+ const returned = parsePairReturn(window.location.hash);+ if (!returned) return;+ window.history.replaceState(null, "", `${window.location.pathname}${window.location.search}#/remote`);+ // A remote iframe must never become a local connection controller.+ if (window.top === window && window.location.protocol === "http:"+ && ["127.0.0.1", "localhost", "[::1]"].includes(window.location.hostname)) {+ pending = returned;+ listeners.forEach((listener) => listener());+ }+}++export function readPairReturn(): PairReturn | null { return pending; }+export function subscribePairReturn(listener: () => void): () => void {+ listeners.add(listener);+ return () => { listeners.delete(listener); };+}+export function clearPairReturn(): void {+ pending = null;+ listeners.forEach((listener) => listener());+}++export function pairingReturnOrigin(): string {+ return window.top === window && window.location.protocol === "http:"+ && ["127.0.0.1", "localhost", "[::1]"].includes(window.location.hostname)+ ? window.location.origin : "";+}diff --git a/webui/src/lib/ssh-address.ts b/webui/src/lib/ssh-address.tsnew file mode 100644index 000000000..81077515d--- /dev/null+++ b/webui/src/lib/ssh-address.ts@@ -0,0 +1,60 @@+/** Import connection fields, never execute a pasted command or shell syntax. */+export interface SSHAddress {+ host: string;+ port?: number;+ identity_file?: string;+ ssh_config?: string;+}++export function parseSSHAddress(input: string): SSHAddress {+ const text = input.trim();+ const invalid = () => new Error("invalid_ssh_command");+ const validHost = (host: string) => /^[a-zA-Z0-9][a-zA-Z0-9._:@-]{0,252}$/.test(host);+ if (!/^ssh\s/.test(text)) {+ if (!validHost(text)) throw invalid();+ return { host: text };+ }+ // A deliberately small grammar: quoted paths (including Windows paths),+ // a destination and -p/-i/-F/-l. No expansions, remote commands or flags+ // that change trust, forwarding, or execute a local ProxyCommand.+ if (/[;$`|&<>]/.test(text) || [...text].some((char) => char.charCodeAt(0) < 32 && char !== "\t")) throw invalid();+ const token = /\s*(?:"([^"]*)"|'([^']*)'|([^\s"']+))(?:\s+|$)/gy;+ const words: string[] = [];+ while (token.lastIndex < text.length) {+ const match = token.exec(text);+ if (!match) throw invalid();+ words.push(match[1] ?? match[2] ?? match[3]);+ }+ words.shift(); // ssh+ const result: SSHAddress = { host: "" };+ const seen = new Set<string>();+ let user = "";+ for (let index = 0; index < words.length; index++) {+ const word = words[index];+ if (!word.startsWith("-")) {+ if (result.host || !validHost(word)) throw invalid();+ result.host = word;+ continue;+ }+ // Options after the destination are a remote command in ssh, not options.+ if (result.host) throw invalid();+ const flag = word.slice(0, 2);+ if (!["-p", "-i", "-F", "-l"].includes(flag) || seen.has(flag)) throw invalid();+ seen.add(flag);+ const value = word.length > 2 ? word.slice(2) : words[++index];+ if (!value || value.startsWith("-") || value.length > 2048) throw invalid();+ if (flag === "-p") {+ if (!/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 65535) throw invalid();+ result.port = Number(value);+ } else if (flag === "-i") result.identity_file = value;+ else if (flag === "-F") result.ssh_config = value;+ else {+ if (!/^[a-zA-Z0-9_][a-zA-Z0-9._-]*$/.test(value)) throw invalid();+ user = value;+ }+ }+ if (!result.host || (user && result.host.includes("@"))) throw invalid();+ if (user) result.host = `${user}@${result.host}`;+ if (!validHost(result.host)) throw invalid();+ return result;+}diff --git a/webui/src/main.tsx b/webui/src/main.tsxindex 06eca3dec..717d4fc36 100644--- a/webui/src/main.tsx+++ b/webui/src/main.tsx@@ -4,6 +4,7 @@ import App from "./App";import "./globals.css";import { initializeI18n } from "./i18n";import { initializeLoopbackRuntimeHost } from "./lib/runtime";+import { initializePairReturn } from "./lib/remote-pair-return";// `crypto.randomUUID` is only defined in secure contexts (HTTPS or localhost).// LAN access over plain HTTP leaves it undefined, which crashes components that@@ -24,6 +25,8 @@ if (typeof globalThis.crypto !== "undefined" && !("randomUUID" in globalThis.cryconst root = document.getElementById("root");if (!root) throw new Error("root element missing");+initializePairReturn();+window.addEventListener("hashchange", initializePairReturn);initializeLoopbackRuntimeHost();async function renderWebui(container: HTMLElement) {diff --git a/webui/src/tests/app-layout.test.tsx b/webui/src/tests/app-layout.test.tsxindex b3a71cc10..7ba88795d 100644--- a/webui/src/tests/app-layout.test.tsx+++ b/webui/src/tests/app-layout.test.tsx@@ -1,6 +1,7 @@import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";import userEvent from "@testing-library/user-event";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { Window as HappyWindow } from "happy-dom";import i18n from "@/i18n";import type {@@ -11,6 +12,8 @@ import type {WorkspaceScopePayload,} from "@/lib/types";+(window as unknown as HappyWindow).happyDOM.settings.disableIframePageLoading = true;+const connectSpy = vi.fn();const refreshSpy = vi.fn();const createChatSpy = vi.fn().mockResolvedValue("chat-1");@@ -318,6 +321,7 @@ describe("App layout", () => {sessionUpdateHandlers.clear();sidebarStateUpdateHandlers.clear();window.history.replaceState(null, "", "/");+ sessionStorage.removeItem("nanobot.remote-instance");Reflect.deleteProperty(window, "nanobotHost");setNavigatorPlatform("Linux x86_64");localStorage.removeItem("nanobot-webui.sidebar");@@ -688,16 +692,19 @@ describe("App layout", () => {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(within(sidebar).queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();+ fireEvent.pointerDown(await within(sidebar).findByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Manage connections…" }));+ expect(await screen.findByRole("heading", { name: "Remote connections" })).toBeVisible();expect(sidebar).toBeVisible();- expect(screen.queryByRole("dialog")).not.toBeInTheDocument();- expect(remote).toHaveAttribute("aria-current", "page");+ fireEvent.click(await screen.findByRole("button", { name: "Add server" }));+ fireEvent.pointerDown(screen.getByRole("button", { name: "Other ways" }), { button: 0, ctrlKey: false });+ fireEvent.click(screen.getByRole("menuitem", { name: "Use existing SSH settings" }));+ const host = await screen.findByRole("textbox", { name: "SSH address" });+ expect(screen.getByRole("dialog", { name: "Connect to a server" })).toContainElement(host);expect(window.location.hash).toBe("#/remote");expect(document.title).toBe("Remote connections · nanobot");+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));fireEvent.click(within(sidebar).getByRole("button", { name: "New topic" }));expect(window.location.hash).toBe("#/new");expect(screen.queryByRole("textbox", { name: "SSH address" })).not.toBeInTheDocument();@@ -705,8 +712,64 @@ describe("App layout", () => {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");+ expect(await screen.findByRole("button", { name: "Add server" })).toBeVisible();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(within(sidebar).queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();+ });++ it("closes the mobile sidebar when managing connections from its host menu", async () => {+ const user = userEvent.setup();+ requestMutationSpy.mockResolvedValue({ hosts: [], files: [], incomplete: false });+ vi.stubGlobal("matchMedia", vi.fn().mockImplementation((query: string) => ({+ matches: !query.includes("1024px"), media: query, onchange: null,+ addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(),+ removeEventListener: vi.fn(), dispatchEvent: vi.fn(),+ })));+ mockFetchRoutes({+ "/api/settings": baseSettingsPayload(),+ "/api/remote-instances": { available: true, profiles: [] },+ });+ render(<App />);+ await waitFor(() => expect(connectSpy).toHaveBeenCalled());+ await user.click(await screen.findByRole("button", { name: "Toggle sidebar" }));+ const sheet = await screen.findByRole("dialog");+ fireEvent.pointerDown(await within(sheet).findByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Manage connections…" }));+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());+ expect(await screen.findByRole("heading", { name: "Remote connections" })).toBeVisible();+ expect(window.location.hash).toBe("#/remote");+ expect(screen.queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();+ await waitFor(() => expect(document.body.style.pointerEvents).not.toBe("none"));+ await user.click(screen.getByRole("button", { name: "Add server" }));+ expect(await screen.findByRole("dialog", { name: "Add server" })).toBeVisible();+ });++ it("releases the mobile sidebar modal when switching to a server", async () => {+ const user = userEvent.setup();+ vi.stubGlobal("matchMedia", vi.fn().mockImplementation((query: string) => ({+ matches: !query.includes("1024px"), media: query, onchange: null,+ addListener: vi.fn(), removeListener: vi.fn(), addEventListener: vi.fn(),+ removeEventListener: vi.fn(), dispatchEvent: vi.fn(),+ })));+ const profile = { id: "3b968d52-081d-4898-9970-ff0a1fc93817", name: "Team server",+ host: "team", port: null, ssh_config: "", identity_file: "",+ config_path: "~/.nanobot/config.json", runtime_user: "", connected: false };+ requestMutationSpy.mockResolvedValue({ ...profile, hostname: "team-host", gateway_id: "remote-gateway",+ url: "http://127.0.0.1:23456/#/?bootstrapSecret=test-only" });+ mockFetchRoutes({+ "/api/settings": baseSettingsPayload(),+ "/api/remote-instances": { available: true, profiles: [profile] },+ });+ render(<App />);+ await user.click(await screen.findByRole("button", { name: "Toggle sidebar" }));+ const sheet = await screen.findByRole("dialog");+ await user.click(await within(sheet).findByRole("button", { name: "Switch host" }));+ await user.click(await screen.findByRole("menuitem", { name: "Team server team" }));+ const frame = await screen.findByTitle("nanobot on Team server");+ fireEvent.load(frame);+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());+ await waitFor(() => expect(document.body.style.pointerEvents).not.toBe("none"));+ expect(frame).toBeVisible();});it("opens a remote setup deep link after reloading without opening Settings", async () => {@@ -717,7 +780,8 @@ describe("App layout", () => {"/api/remote-instances": { available: true, profiles: [] },});render(<App />);- expect(await screen.findByRole("region", { name: "From your SSH config" })).toBeVisible();+ expect(await screen.findByRole("button", { name: "Add server" })).toBeVisible();+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();expect(screen.getByRole("navigation", { name: "Sidebar navigation" })).toBeVisible();expect(screen.queryByRole("navigation", { name: "Settings sections" })).not.toBeInTheDocument();expect(window.location.hash).toBe("#/remote");diff --git a/webui/src/tests/host-sessions.test.tsx b/webui/src/tests/host-sessions.test.tsxindex a827e97ea..94b9fca6f 100644--- a/webui/src/tests/host-sessions.test.tsx+++ b/webui/src/tests/host-sessions.test.tsx@@ -40,6 +40,75 @@ beforeEach(() => {afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });describe("host session lifecycle", () => {+ it("clears a failed reconnect only after that host's loaded view recovers", async () => {+ const { result } = renderHook(useHostSessions);+ await ready(result, 0);+ mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) => ({ ...p, connected: false })) });+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });+ mocks.request.mockRejectedValueOnce(new Error("ssh_unreachable"));+ await act(async () => { await expect(result.current.connect(ids[0])).rejects.toThrow("ssh_unreachable"); });+ expect(result.current.error).toBe("ssh_unreachable");+ mocks.read.mockResolvedValue(directory);+ await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });+ expect(result.current.frames[0].offline).toBe(false);+ expect(result.current.error).toBe("");+ });++ it("does not clear a failed destination because the active host is healthy", 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"); });+ await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });+ expect(result.current.error).toBe("ssh_unreachable");+ expect(result.current.selected?.id).toBe(ids[0]);+ });++ it("ignores a stale health failure that arrives after reconnect succeeds", async () => {+ const { result } = renderHook(useHostSessions);+ await ready(result, 0);+ mocks.read.mockResolvedValue({ ...directory, profiles: [] });+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });+ const stale = deferred<typeof directory>();+ mocks.read.mockReturnValueOnce(stale.promise);+ await act(async () => { await vi.advanceTimersByTimeAsync(5_000); });+ mocks.read.mockResolvedValue(directory);+ await act(async () => { await result.current.connect(ids[0]); });+ await act(async () => { stale.resolve({ ...directory, profiles: [] }); });+ expect(result.current.frames[0].failures).toBe(0);+ expect(result.current.directory?.profiles).toHaveLength(4);+ });++ it("keeps an old gateway view offline when another tab connects a new gateway", async () => {+ const { result } = renderHook(useHostSessions);+ await ready(result, 0);+ mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) =>+ p.id === ids[0] ? { ...p, gateway_id: "restarted-gateway" } : p) });+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });+ expect(result.current.frames[0].offline).toBe(true);+ expect(result.current.selected?.id).toBe(ids[0]);+ });++ it("does not revive an old proxy view after the local gateway restarts", async () => {+ const { result } = renderHook(useHostSessions);+ await ready(result, 0);+ mocks.read.mockResolvedValue({ ...directory, profiles: directory.profiles.map((p) =>+ p.id === ids[0] ? { ...p, view_id: "new-local-proxy-session" } : p) });+ await act(async () => { await vi.advanceTimersByTimeAsync(10_000); });+ expect(result.current.frames[0].offline).toBe(true);+ expect(result.current.frames[0].error).toBe("instance_changed");+ });++ it("does not report a successful disconnect as failed when refreshing the list fails", async () => {+ const { result } = renderHook(useHostSessions);+ await ready(result, 0);+ mocks.read.mockRejectedValue(new Error("directory_unavailable"));+ await act(async () => { await expect(result.current.disconnect(ids[0])).resolves.toBeUndefined(); });+ expect(result.current.selected).toBeNull();+ expect(result.current.frames).toHaveLength(0);+ expect(result.current.directoryError).toBe(true);+ });+it("keeps the current host until the destination view loads, then switches warm without RPC", async () => {const { result } = renderHook(useHostSessions);await ready(result, 0);@@ -115,7 +184,10 @@ describe("host session lifecycle", () => {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; });+ await act(async () => { await vi.advanceTimersByTimeAsync(59_999); });+ expect(result.current.pending?.id).toBe(ids[1]);+ expect(result.current.selected?.id).toBe(ids[0]);+ await act(async () => { await vi.advanceTimersByTimeAsync(1); await rejected; });expect(result.current.selected?.id).toBe(ids[0]);expect(result.current.frames).toHaveLength(1);await ready(result, 1);diff --git a/webui/src/tests/host-switcher.test.tsx b/webui/src/tests/host-switcher.test.tsxnew file mode 100644index 000000000..cf16893bf--- /dev/null+++ b/webui/src/tests/host-switcher.test.tsx@@ -0,0 +1,253 @@+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { HostNavigationContext, HostSwitcher, RemoteHostMenu, type HostPicker } from "@/components/remote/HostSwitcher";+import { readRecentRemotes, rememberRecentRemote } from "@/lib/remote-instances";++vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: {+ status: "open", onStatus: () => () => {},+} }) }));++function picker(count: number): HostPicker {+ return {+ kind: "shell", name: "Local", hostname: "My-Mac", localName: "My-Mac",+ currentId: null, recentIds: [], pending: null, error: "", offline: false,+ profiles: Array.from({ length: count }, (_, index) => ({+ id: `00000000-0000-4000-8000-${String(index + 1).padStart(12, "0")}`,+ name: index === 1 ? "研发服务器" : `Server ${index + 1}`,+ host: `ubuntu@host-${index + 1}.test`, ready: false,+ })),+ select: vi.fn(), manage: vi.fn(), cancel: vi.fn(), clearError: vi.fn(), restoreFocus: vi.fn(),+ };+}++async function openMenu(value: HostPicker) {+ const view = render(<HostNavigationContext.Provider value={value}><HostSwitcher /></HostNavigationContext.Provider>);+ await userEvent.click(screen.getByRole("button", { name: "Switch host" }));+ await screen.findByRole("menu");+ return view;+}++beforeEach(() => window.localStorage.clear());+afterEach(() => { cleanup(); vi.restoreAllMocks(); });++describe("host switcher", () => {+ it("keeps the current host identity visible until a pending switch is ready", async () => {+ const value = picker(2);+ value.pending = value.profiles[0];+ render(<HostNavigationContext.Provider value={value}><HostSwitcher /></HostNavigationContext.Provider>);+ const trigger = screen.getByRole("button", { name: "Switch host" });+ expect(within(trigger).getByText("Local", { exact: true })).toBeVisible();+ expect(trigger).toHaveAttribute("title", expect.stringContaining("Connecting to Server 1"));+ expect(within(trigger).getByRole("status")).toHaveTextContent("Local · My-Mac · Connected · Connecting to Server 1");+ await userEvent.click(trigger);+ expect(screen.getByRole("menuitem", { name: "Local nanobot My-Mac" })).toHaveAttribute("aria-current", "true");+ expect(screen.getByRole("menuitem", { name: "Server 1 [email protected]" })).not.toHaveAttribute("aria-current");+ });++ it("does not label a healthy host offline when switching to another host fails", async () => {+ const value = { ...picker(2), error: "Destination SSH is unreachable" };+ render(<HostNavigationContext.Provider value={value}><HostSwitcher /></HostNavigationContext.Provider>);+ const trigger = screen.getByRole("button", { name: "Switch host" });+ expect(within(trigger).getByRole("status")).toHaveTextContent("Local · My-Mac · Connected");+ expect(trigger).toHaveAttribute("title", expect.stringContaining(value.error));+ expect(trigger).not.toHaveTextContent("Offline");+ await userEvent.click(trigger);+ expect(screen.getByRole("alert")).toHaveTextContent(value.error);+ });++ it("keeps a truly disconnected host offline independently of switch errors", () => {+ const value = { ...picker(2), offline: true, name: "Team server", hostname: "team-host" };+ render(<HostNavigationContext.Provider value={value}><HostSwitcher /></HostNavigationContext.Provider>);+ expect(screen.getByRole("status")).toHaveTextContent("Team server · team-host · Server connection lost");+ });++ it("keeps remote sidebar identity and connection status separate from pending or failed switches", () => {+ const value = { kind: "embedded" as const, name: "Team server", hostname: "team-host", pendingName: "Another server", open: vi.fn() };+ const view = render(<HostNavigationContext.Provider value={value}><HostSwitcher /></HostNavigationContext.Provider>);+ const trigger = screen.getByRole("button", { name: "Switch host" });+ expect(within(trigger).getByText("Team server", { exact: true })).toBeVisible();+ expect(within(trigger).getByRole("status")).toHaveTextContent("Team server · team-host · Connected · Connecting to Another server");+ view.rerender(<HostNavigationContext.Provider value={{ ...value, pendingName: undefined, error: "Destination SSH is unreachable" }}><HostSwitcher /></HostNavigationContext.Provider>);+ expect(within(trigger).getByRole("status")).toHaveTextContent("Team server · team-host · Connected");+ expect(trigger).toHaveAttribute("title", expect.stringContaining("Destination SSH is unreachable"));+ });+ it.each([0, 1, 5])("keeps %i saved hosts simple without search", async (count) => {+ await openMenu(picker(count));+ expect(screen.queryByRole("textbox")).not.toBeInTheDocument();+ expect(screen.getAllByRole("menuitem")).toHaveLength(count + 2);+ });++ it.each([6, 10, 20])("searches %i saved hosts, with management outside the scroll area", async (count) => {+ await openMenu(picker(count));+ const input = screen.getByRole("textbox", { name: "Search hosts…" });+ await waitFor(() => expect(input).toHaveFocus());+ const group = screen.getByRole("group", { name: "Switch host" });+ expect(within(group).getAllByRole("menuitem")).toHaveLength(count + 1);+ expect(group).toHaveClass("overflow-y-auto", "min-h-0");+ expect(group).not.toContainElement(screen.getByRole("menuitem", { name: "Manage connections…" }));+ await userEvent.type(input, "HOST-6.TEST");+ expect(within(group).getAllByRole("menuitem")).toHaveLength(1);+ expect(within(group).getByText("Server 6")).toBeVisible();+ expect(input).toHaveFocus();+ });++ it("finds names with spaces, non-Latin names and the local machine", async () => {+ await openMenu(picker(20));+ const input = screen.getByRole("textbox");+ await userEvent.type(input, "Server 20");+ expect(screen.getByRole("menuitem", { name: "Server 20 [email protected]" })).toBeVisible();+ fireEvent.change(input, { target: { value: "研发" } });+ expect(screen.getByRole("menuitem", { name: "研发服务器 [email protected]" })).toBeVisible();+ fireEvent.change(input, { target: { value: "My-Mac" } });+ expect(screen.getByRole("menuitem", { name: "Local nanobot My-Mac" })).toBeVisible();+ expect(screen.queryByText("Server 20")).not.toBeInTheDocument();+ });++ it("keeps search focused while the pointer crosses results", async () => {+ await openMenu(picker(10));+ const input = screen.getByRole("textbox");+ await waitFor(() => expect(input).toHaveFocus());+ const row = screen.getByRole("menuitem", { name: "Server 1 [email protected]" });+ fireEvent.pointerMove(row, { pointerType: "mouse", clientX: 25 });+ fireEvent.pointerOut(row, { pointerType: "mouse" });+ expect(input).toHaveFocus();+ await userEvent.type(input, "Server 10");+ expect(screen.getByRole("menuitem", { name: "Server 10 [email protected]" })).toBeVisible();+ });++ it("supports arrow navigation back to search, then Enter selection", async () => {+ const value = picker(10);+ await openMenu(value);+ const input = screen.getByRole("textbox");+ await userEvent.type(input, "host-10");+ await userEvent.keyboard("{ArrowDown}");+ expect(screen.getByRole("menuitem", { name: "Server 10 [email protected]" })).toHaveFocus();+ await userEvent.keyboard("{ArrowUp}");+ expect(input).toHaveFocus();+ await userEvent.keyboard("{Enter}");+ expect(value.select).toHaveBeenCalledWith(value.profiles[9].id);+ await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());+ });++ it("does not connect or close when confirming IME input", async () => {+ const value = picker(10);+ await openMenu(value);+ const input = screen.getByRole("textbox");+ fireEvent.compositionStart(input);+ fireEvent.change(input, { target: { value: "研发" } });+ fireEvent.keyDown(input, { key: "Enter", isComposing: true });+ fireEvent.keyDown(input, { key: "Escape", isComposing: true });+ expect(value.select).not.toHaveBeenCalled();+ expect(screen.getByRole("menu")).toBeVisible();+ fireEvent.compositionEnd(input);+ fireEvent.keyDown(input, { key: "Enter" });+ expect(value.select).toHaveBeenCalledWith(value.profiles[1].id);+ });++ it("does not select a host on empty search Enter", async () => {+ const value = picker(10);+ await openMenu(value);+ await waitFor(() => expect(screen.getByRole("textbox")).toHaveFocus());+ await userEvent.keyboard("{Enter}");+ expect(value.select).not.toHaveBeenCalled();+ });++ it("shows an empty result without hiding management or selecting it on Enter", async () => {+ const value = picker(10);+ await openMenu(value);+ await userEvent.type(screen.getByRole("textbox"), "missing");+ expect(screen.getByRole("status", { name: "" })).toHaveTextContent("No matching hosts");+ await userEvent.keyboard("{Enter}");+ expect(value.select).not.toHaveBeenCalled();+ expect(value.manage).not.toHaveBeenCalled();+ await userEvent.keyboard("{ArrowDown}{Enter}");+ expect(value.manage).toHaveBeenCalledOnce();+ });++ it("clears search on reopen and restores focus on Escape", async () => {+ const value = picker(10);+ await openMenu(value);+ await userEvent.type(screen.getByRole("textbox"), "Server 10");+ await userEvent.keyboard("{Escape}");+ await waitFor(() => expect(value.restoreFocus).toHaveBeenCalled());+ await userEvent.click(screen.getByRole("button", { name: "Switch host" }));+ expect(await screen.findByRole("textbox")).toHaveValue("");+ expect(screen.getAllByRole("menuitem")).toHaveLength(12);+ });++ it("pins local, then current and recent hosts, without live reordering or duplicates", async () => {+ const value = picker(20);+ value.currentId = value.profiles[19].id;+ value.recentIds = [value.profiles[8].id, value.currentId, "deleted-id"];+ const rendered = await openMenu(value);+ const names = () => within(screen.getByRole("group")).getAllByRole("menuitem").map((item) => item.textContent);+ expect(names().slice(0, 4)).toEqual(["Local nanobotMy-Mac", "Server [email protected]", "Server [email protected]", "Server [email protected]"]);+ const before = names();+ rendered.rerender(<HostNavigationContext.Provider value={{ ...value, recentIds: [value.profiles[5].id] }}><HostSwitcher /></HostNavigationContext.Provider>);+ expect(names()).toEqual(before);+ });++ it("uses the same searchable menu for the parent-owned remote sidebar", async () => {+ const value = picker(20);+ render(<RemoteHostMenu picker={value} anchor={{ left: 48, top: 540, width: 160, height: 32 }} onClose={vi.fn()} />);+ const input = await screen.findByRole("textbox");+ await userEvent.type(input, "host-20");+ await userEvent.click(screen.getByRole("menuitem", { name: "Server 20 [email protected]" }));+ expect(value.select).toHaveBeenCalledWith(value.profiles[19].id);+ });++ it("keeps search available if the directory shrinks while filtering", async () => {+ const value = picker(10);+ const rendered = await openMenu(value);+ await userEvent.type(screen.getByRole("textbox"), "host-10");+ rendered.rerender(<HostNavigationContext.Provider value={{ ...value, profiles: value.profiles.slice(0, 5) }}><HostSwitcher /></HostNavigationContext.Provider>);+ const input = screen.getByRole("textbox");+ expect(input).toHaveValue("host-10");+ await userEvent.clear(input);+ expect(within(screen.getByRole("group")).getAllByRole("menuitem")).toHaveLength(6);+ });++ it("does not autofocus search and summon the keyboard on touch devices", async () => {+ const original = window.matchMedia.bind(window);+ vi.spyOn(window, "matchMedia").mockImplementation((query) => ({ ...original(query), matches: query === "(pointer: coarse)" }));+ await openMenu(picker(20));+ expect(screen.getByRole("menu")).toHaveFocus();+ expect(screen.getByRole("textbox")).not.toHaveFocus();+ await userEvent.click(screen.getByRole("menuitem", { name: "Server 20 [email protected]" }));+ await waitFor(() => expect(screen.queryByRole("menu")).not.toBeInTheDocument());+ });++ it("keeps cancel and errors accessible even when no hosts match", async () => {+ const value = picker(20);+ value.pending = value.profiles[3]; value.error = "Try again";+ await openMenu(value);+ await userEvent.type(screen.getByRole("textbox"), "missing");+ expect(screen.getByRole("alert")).toHaveTextContent("Try again");+ await userEvent.click(screen.getByRole("button", { name: "Close" }));+ expect(value.clearError).toHaveBeenCalledOnce();+ await userEvent.click(screen.getByRole("menuitem", { name: "Cancel switch" }));+ expect(value.cancel).toHaveBeenCalledOnce();+ });+});++describe("recent host preferences", () => {+ it("keeps only bounded, unique profile IDs and ignores malformed storage", () => {+ window.localStorage.setItem("nanobot.recent-remote-instances", "not json");+ expect(readRecentRemotes()).toEqual([]);+ const ids = picker(25).profiles.map(({ id }) => id);+ window.localStorage.setItem("nanobot.recent-remote-instances", JSON.stringify([null, "http://secret", ids[0], ...ids]));+ expect(readRecentRemotes()).toEqual(ids.slice(0, 20));+ const next = rememberRecentRemote(ids[5], readRecentRemotes());+ expect(next).toHaveLength(20);+ expect(next[0]).toBe(ids[5]);+ expect(readRecentRemotes()).toEqual(next);+ });++ it("keeps switching available when browser storage is disabled", () => {+ vi.spyOn(window.localStorage, "getItem").mockImplementation(() => { throw new Error("disabled"); });+ vi.spyOn(window.localStorage, "setItem").mockImplementation(() => { throw new Error("disabled"); });+ expect(readRecentRemotes()).toEqual([]);+ expect(rememberRecentRemote(picker(1).profiles[0].id, [])).toEqual([picker(1).profiles[0].id]);+ });+});diff --git a/webui/src/tests/pair-route.test.tsx b/webui/src/tests/pair-route.test.tsxnew file mode 100644index 000000000..3571d066b--- /dev/null+++ b/webui/src/tests/pair-route.test.tsx@@ -0,0 +1,78 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { PairRouteSettings } from "@/components/remote/PairRouteSettings";+import i18n from "@/i18n";++const mocks = vi.hoisted(() => ({ action: vi.fn(), refresh: vi.fn(), config: "" }));+vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: { requestMutation: mocks.action } }) }));+vi.mock("@/components/remote/RemoteInstances", () => ({ useRemoteConnections: () => ({ refresh: mocks.refresh, directory: { profiles: [{ id: "paired", paired: true, ssh_config: mocks.config }, { id: "ssh", name: "Team SSH", paired: false }] } }) }));++beforeEach(async () => { await i18n.changeLanguage("en"); mocks.action.mockReset().mockResolvedValue({}); mocks.refresh.mockReset().mockResolvedValue(undefined); mocks.config = ""; });+afterEach(cleanup);++async function chooseSSH() {+ await userEvent.click(screen.getByRole("combobox"));+ await userEvent.click(screen.getByRole("option", { name: "Team SSH" }));+}++describe("paired network route", () => {+ it("does not mislabel a saved custom route as a direct connection", () => {+ mocks.config = "/private/paired/ssh_route";+ render(<PairRouteSettings id="paired" />);+ expect(screen.getByRole("combobox")).toHaveTextContent("Saved network route");+ expect(screen.getByRole("button", { name: "Save changes" })).toBeDisabled();+ expect(mocks.action).not.toHaveBeenCalled();+ });+ it("shows direct only when no saved route is configured", () => {+ render(<PairRouteSettings id="paired" />);+ expect(screen.getByRole("combobox")).toHaveTextContent("Direct connection");+ expect(screen.getByRole("button", { name: "Save changes" })).toBeDisabled();+ });+ it("shows saving, then confirms the saved route without connecting", async () => {+ let finish!: (value: unknown) => void;+ mocks.action.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ render(<PairRouteSettings id="paired" />);+ await chooseSSH();+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));+ expect(screen.getByRole("button", { name: "Saving…" })).toBeDisabled();+ expect(screen.getByRole("combobox")).toBeDisabled();+ await act(async () => finish({}));+ expect(screen.getByRole("status")).toHaveTextContent("Saved");+ expect(screen.getByRole("button", { name: "Save changes" })).toBeDisabled();+ expect(mocks.action).toHaveBeenCalledOnce();+ expect(mocks.action).toHaveBeenCalledWith("remote.pair_route", { id: "paired", route_id: "ssh" }, 65000);+ });+ it("preserves the chosen route after a failed save and allows retry", async () => {+ mocks.action.mockRejectedValueOnce(new Error("pair_route_mismatch"));+ render(<PairRouteSettings id="paired" />);+ await chooseSSH();+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));+ expect(await screen.findByRole("alert")).toHaveTextContent("same server");+ expect(screen.getByRole("combobox")).toHaveTextContent("Team SSH");+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));+ await waitFor(() => expect(screen.queryByRole("alert")).toBeNull());+ expect(screen.getByRole("status")).toHaveTextContent("Saved");+ });+ it("distinguishes a saved route from a subsequent failed directory refresh", async () => {+ mocks.refresh.mockRejectedValue(new Error("offline"));+ render(<PairRouteSettings id="paired" />);+ await chooseSSH();+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));+ expect(await screen.findByRole("alert")).toHaveTextContent("Couldn't read your saved servers");+ expect(screen.getByRole("status")).toHaveTextContent("Saved");+ expect(screen.getByRole("button", { name: "Save changes" })).toBeDisabled();+ expect(mocks.action).toHaveBeenCalledOnce();+ });+ it("does not dismiss a different screen when a closed editor finishes saving", async () => {+ let finish!: (value: unknown) => void;+ mocks.action.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ const saved = vi.fn();+ const view = render(<PairRouteSettings id="paired" onSaved={saved} />);+ await chooseSSH();+ fireEvent.click(screen.getByRole("button", { name: "Save changes" }));+ view.unmount();+ await act(async () => finish({}));+ expect(saved).not.toHaveBeenCalled();+ });+});diff --git a/webui/src/tests/quick-pair.test.tsx b/webui/src/tests/quick-pair.test.tsxnew file mode 100644index 000000000..e048af368--- /dev/null+++ b/webui/src/tests/quick-pair.test.tsx@@ -0,0 +1,263 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { QuickPairSetup } from "@/components/remote/QuickPairSetup";+import { Dialog, DialogContent } from "@/components/ui/dialog";+import i18n from "@/i18n";++const mocks = vi.hoisted(() => {+ const action = vi.fn();+ return { action, client: { requestMutation: action }, connect: vi.fn(), refresh: vi.fn(), cancel: vi.fn(), copy: vi.fn() };+});+vi.mock("@/providers/ClientProvider", () => ({ useClient: () => ({ client: mocks.client }) }));+vi.mock("@/components/remote/RemoteInstances", () => ({ useRemoteConnections: () => ({ connect: mocks.connect, refresh: mocks.refresh, cancel: mocks.cancel, directory: { profiles: [] } }) }));+vi.mock("@/lib/clipboard", () => ({ copyTextToClipboard: mocks.copy }));+const request = () => ({ id: "request-1", command: "nanobot remote pair nbpr1.public", expires: Date.now() / 1000 + 600 });+const preview = { id: "request-1", host: "ubuntu@server", hostname: "team", fingerprint: "SHA256:trusted-server", authorized_until: Date.now() / 1000 + 86400, revoke_command: "nanobot remote revoke request-1" };++beforeEach(async () => {+ await i18n.changeLanguage("en");+ mocks.action.mockReset().mockImplementation(async (action: string) => {+ if (action === "remote.pair_start") return request();+ if (action === "remote.pair_preview") return preview;+ if (action === "remote.pair_finish") return { id: "paired-server" };+ return {};+ });+ mocks.copy.mockReset().mockResolvedValue(true);+ mocks.connect.mockReset().mockResolvedValue(undefined);+ mocks.refresh.mockReset().mockResolvedValue(undefined);+});+afterEach(() => { cleanup(); vi.useRealTimers(); vi.restoreAllMocks(); });+const view = (onSSH = vi.fn(), onClose = vi.fn()) => render(<Dialog open><DialogContent><QuickPairSetup onSSH={onSSH} onClose={onClose} /></DialogContent></Dialog>);+function chooseOtherWay(name: string) {+ fireEvent.pointerDown(screen.getByRole("button", { name: "Other ways" }), { button: 0, ctrlKey: false });+ fireEvent.click(screen.getByRole("menuitem", { name }));+}++async function reviewed() {+ await screen.findByRole("button", { name: "Copy command" });+ chooseOtherWay("Use a connection code instead");+ fireEvent.change(await screen.findByRole("textbox", { name: "Connection code" }), { target: { value: "nbpc1.encrypted" } });+ fireEvent.click(screen.getByRole("button", { name: "Review connection" }));+ await screen.findByRole("heading", { name: "Open this nanobot?" });+}++describe("quick pairing", () => {+ it("never asks a returning user to copy another command while validating their link", async () => {+ mocks.action.mockImplementation(() => new Promise(() => {}));+ render(<Dialog open><DialogContent><QuickPairSetup returned={{ id: "request-1", code: "nbpc1.encrypted" }} onSSH={vi.fn()} onClose={vi.fn()} /></DialogContent></Dialog>);+ expect(screen.getByRole("heading", { name: "Review connection" })).toBeVisible();+ expect(screen.queryByRole("button", { name: "Copy command" })).toBeNull();+ expect(screen.queryByText("Run one command in your server terminal to connect.")).toBeNull();+ expect(screen.getByRole("button", { name: "Review connection" })).toBeDisabled();+ expect(mocks.connect).not.toHaveBeenCalled();+ });+ it("shows only the next action and reveals requirements on demand", async () => {+ view();+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());+ expect(screen.getByText(/For Linux servers/).closest(".inline-disclosure")).toHaveAttribute("aria-hidden", "true");+ expect(screen.queryByRole("menuitem")).toBeNull();+ expect(screen.getByText(/After authorizing/)).toHaveAttribute("aria-hidden", "true");+ chooseOtherWay("Requirements & help");+ expect(screen.getByText(/For Linux servers/)).toBeVisible();+ expect(screen.getByText(/Commands expire after 10 minutes/)).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "View command" }));+ expect(screen.getByText(request().command)).toBeVisible();+ expect(screen.getByText(/For Linux servers/).closest(".inline-disclosure")).toHaveAttribute("aria-hidden", "true");+ });+ it("keeps closed command details mounted but inert for reversible transitions", async () => {+ view();+ const toggle = await screen.findByRole("button", { name: "View command" });+ const panel = document.getElementById(toggle.getAttribute("aria-controls")!);+ expect(panel).toHaveAttribute("data-state", "closed");+ expect(panel).toHaveAttribute("inert");+ fireEvent.click(toggle);+ expect(panel).toHaveAttribute("data-state", "open");+ expect(panel).not.toHaveAttribute("inert");+ expect(toggle).toHaveAttribute("aria-expanded", "true");+ fireEvent.click(toggle);+ expect(document.getElementById(toggle.getAttribute("aria-controls")!)).toBe(panel);+ expect(panel).toHaveAttribute("aria-hidden", "true");+ expect(panel).toHaveAttribute("inert");+ });+ it("keeps preparation in the button, and delays its indicator without delaying readiness", async () => {+ vi.useFakeTimers();+ let finish!: (value: ReturnType<typeof request>) => void;+ mocks.action.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ view();+ const button = screen.getByRole("button", { name: "Copy command" });+ expect(button).toBeDisabled();+ expect(button).toHaveAttribute("aria-busy", "true");+ expect(screen.queryByText("Preparing your connection…")).toBeNull();+ act(() => { vi.advanceTimersByTime(199); });+ expect(button).toHaveTextContent("Copy command");+ act(() => { vi.advanceTimersByTime(1); });+ expect(button).toHaveTextContent("Preparing your connection…");+ expect(screen.getByRole("status").closest("button")).toBe(button);+ await act(async () => finish(request()));+ expect(button).toHaveTextContent("Copy command");+ expect(button).toBeEnabled();+ expect(button).toHaveAttribute("aria-busy", "false");+ });+ it("does not flash a delayed status after fast preparation finishes", async () => {+ vi.useFakeTimers();+ view();+ await act(async () => {});+ act(() => { vi.advanceTimersByTime(250); });+ expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled();+ expect(screen.queryByText("Preparing your connection…")).toBeNull();+ });+ it("preserves the pasted code and SSH fallback during a slow review", async () => {+ const ssh = vi.fn();+ view(ssh);+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());+ chooseOtherWay("Use a connection code instead");+ fireEvent.change(screen.getByRole("textbox", { name: "Connection code" }), { target: { value: "nbpc1.unfinished" } });+ mocks.action.mockImplementation(() => new Promise(() => {}));+ vi.useFakeTimers();+ fireEvent.click(screen.getByRole("button", { name: "Review connection" }));+ act(() => { vi.advanceTimersByTime(200); });+ expect(screen.getByRole("textbox", { name: "Connection code" })).toHaveValue("nbpc1.unfinished");+ expect(screen.getByRole("button", { name: "Checking the connection link…" })).toBeDisabled();+ chooseOtherWay("Use existing SSH settings");+ expect(ssh).toHaveBeenCalledOnce();+ });+ it("advances only after copying succeeds and never implies a server connection", async () => {+ let finish!: (success: boolean) => void;+ mocks.copy.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ view();+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());+ fireEvent.click(screen.getByRole("button", { name: "Copy command" }));+ expect(screen.getByRole("heading", { name: "Add server" })).toBeVisible();+ await act(async () => finish(true));+ expect(screen.getByRole("heading", { name: "Command copied" })).toBeVisible();+ expect(screen.getByText(/Paste it into your server terminal/)).toBeVisible();+ expect(screen.getByRole("button", { name: "Copy again" })).toBeEnabled();+ expect(screen.getByRole("button", { name: "Copy again" })).toHaveClass("border", "border-input");+ expect(screen.getByRole("dialog")).toHaveAccessibleDescription(i18n.t("remote.pair.afterCopyHint"));+ expect(mocks.connect).not.toHaveBeenCalled();+ expect(mocks.action.mock.calls.map(([action]) => action)).toEqual(["remote.pair_start"]);+ });+ it("exposes the command when the clipboard fails without claiming it was copied", async () => {+ mocks.copy.mockResolvedValue(false);+ view();+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());+ fireEvent.click(screen.getByRole("button", { name: "Copy command" }));+ await screen.findByRole("alert");+ expect(screen.getByText(request().command)).toBeVisible();+ expect(screen.getByRole("heading", { name: "Add server" })).toBeVisible();+ expect(screen.queryByRole("button", { name: "Copy again" })).toBeNull();+ });+ it("keeps a manual code when returning to the simpler command screen", async () => {+ view();+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());+ chooseOtherWay("Use a connection code instead");+ await waitFor(() => expect(screen.getByRole("textbox", { name: "Connection code" })).toHaveFocus());+ fireEvent.change(screen.getByRole("textbox", { name: "Connection code" }), { target: { value: "nbpc1.unfinished" } });+ fireEvent.click(screen.getByRole("button", { name: "Back" }));+ expect(screen.queryByRole("textbox")).toBeNull();+ chooseOtherWay("Use a connection code instead");+ expect(screen.getByRole("textbox", { name: "Connection code" })).toHaveValue("nbpc1.unfinished");+ });+ it("replaces copied guidance with recovery when the invitation expires", async () => {+ const timer = vi.spyOn(window, "setTimeout");+ view();+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());+ fireEvent.click(screen.getByRole("button", { name: "Copy command" }));+ await screen.findByRole("heading", { name: "Command copied" });+ const expiry = timer.mock.calls.find(([, delay]) => typeof delay === "number" && delay > 599_000)?.[0];+ expect(typeof expiry).toBe("function");+ act(() => { if (typeof expiry === "function") expiry(); });+ expect(screen.queryByRole("heading", { name: "Command copied" })).toBeNull();+ expect(screen.getByText(/This request has expired/)).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Get a new command" }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());+ expect(screen.queryByText(/This request has expired/)).toBeNull();+ });+ it("can revisit the receipt from return-link confirmation without a disabled copy dead end", async () => {+ render(<Dialog open><DialogContent><QuickPairSetup returned={{ id: "request-1", code: "nbpc1.encrypted" }} onSSH={vi.fn()} onClose={vi.fn()} /></DialogContent></Dialog>);+ await screen.findByRole("heading", { name: "Open this nanobot?" });+ fireEvent.click(screen.getByRole("button", { name: "Back" }));+ expect(screen.getByRole("textbox", { name: "Connection code" })).toHaveValue("nbpc1.encrypted");+ expect(screen.getByRole("button", { name: "Review connection" })).toBeEnabled();+ expect(screen.queryByRole("button", { name: "Copy command" })).toBeNull();+ expect(mocks.connect).not.toHaveBeenCalled();+ });+ it("prepares one command when Add server opens and keeps the SSH entry", async () => {+ const ssh = vi.fn(); view(ssh);+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());+ expect(mocks.action.mock.calls.filter(([action]) => action === "remote.pair_start")).toHaveLength(1);+ expect(screen.queryByRole("textbox", { name: /Private key/ })).toBeNull();+ expect(screen.queryByRole("textbox", { name: "Connection code" })).toBeNull();+ chooseOtherWay("Use existing SSH settings");+ expect(ssh).toHaveBeenCalledOnce();+ });+ it("reviews public details before storing and opening the connection", async () => {+ const close = vi.fn(); view(vi.fn(), close); await reviewed();+ expect(mocks.action).not.toHaveBeenCalledWith("remote.pair_finish", expect.anything(), expect.anything());+ expect(screen.getByText(/full access/)).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ await waitFor(() => expect(close).toHaveBeenCalledOnce());+ expect(mocks.connect).toHaveBeenCalledWith("paired-server", expect.any(Function));+ });+ it("keeps the receipt and saved profile after a network failure, retries without re-authorizing", async () => {+ mocks.connect.mockRejectedValueOnce(new Error("ssh_connection_closed"));+ view(); await reviewed(); fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ await screen.findByRole("alert");+ expect(screen.getByText(/Pairing is saved/)).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));+ await waitFor(() => expect(mocks.connect).toHaveBeenCalledTimes(2));+ expect(mocks.action.mock.calls.filter(([action]) => action === "remote.pair_finish")).toHaveLength(1);+ });+ it("shows an actionable invalid-code error without losing the pasted value", async () => {+ mocks.action.mockImplementation(async (action: string) => {+ if (action === "remote.pair_start") return request();+ if (action === "remote.pair_preview") throw new Error("pair_invalid");+ return {};+ });+ view(); await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());+ chooseOtherWay("Use a connection code instead");+ fireEvent.change(await screen.findByRole("textbox", { name: "Connection code" }), { target: { value: "bad-code" } });+ fireEvent.click(screen.getByRole("button", { name: "Review connection" }));+ expect(await screen.findByRole("alert")).toHaveTextContent(/invalid/);+ expect(screen.getByRole("textbox", { name: "Connection code" })).toHaveValue("bad-code");+ });+ it("cleans up an invitation returned after closing the dialog", async () => {+ let resolve!: (value: ReturnType<typeof request>) => void;+ mocks.action.mockImplementation((action: string) => action === "remote.pair_start" ? new Promise((done) => { resolve = done; }) : Promise.resolve({}));+ const result = view();+ result.unmount(); await act(async () => resolve(request()));+ expect(mocks.action).toHaveBeenCalledWith("remote.pair_cancel", { id: "request-1" }, 65000);+ });+ it("keeps a displayed invitation when navigating away so the return link survives", async () => {+ const result = view();+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());+ result.unmount();+ expect(mocks.action.mock.calls.some(([action]) => action === "remote.pair_cancel")).toBe(false);+ });+ it("reviews a returned receipt without generating another key or connecting automatically", async () => {+ render(<Dialog open><DialogContent><QuickPairSetup returned={{ id: "request-1", code: "nbpc1.encrypted" }} onSSH={vi.fn()} onClose={vi.fn()} /></DialogContent></Dialog>);+ await screen.findByRole("heading", { name: "Open this nanobot?" });+ expect(mocks.action).toHaveBeenCalledWith("remote.pair_preview", { id: "request-1", code: "nbpc1.encrypted" }, 65000);+ expect(mocks.action.mock.calls.some(([action]) => action === "remote.pair_start" || action === "remote.pair_finish")).toBe(false);+ expect(mocks.connect).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ await waitFor(() => expect(mocks.connect).toHaveBeenCalledOnce());+ });+ it("offers a fresh command when a returned link is invalid", async () => {+ mocks.action.mockRejectedValue(new Error("pair_invalid"));+ render(<Dialog open><DialogContent><QuickPairSetup returned={{ id: "", code: "" }} onSSH={vi.fn()} onClose={vi.fn()} /></DialogContent></Dialog>);+ expect(await screen.findByRole("alert")).toHaveTextContent(/invalid/);+ expect(screen.getByRole("button", { name: "Get a new command" })).toBeEnabled();+ expect(screen.queryByRole("button", { name: "Copy command" })).toBeNull();+ expect(mocks.connect).not.toHaveBeenCalled();+ });+ it("recovers from preparation failure without showing a stuck preparing state", async () => {+ mocks.action.mockRejectedValueOnce(new Error("local_io_error"));+ view();+ await screen.findByRole("alert");+ expect(screen.queryByText("Preparing your connection…")).toBeNull();+ fireEvent.click(screen.getByRole("button", { name: "Get a new command" }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Copy command" })).toBeEnabled());+ expect(screen.queryByRole("alert")).toBeNull();+ });+});diff --git a/webui/src/tests/remote-instances.test.tsx b/webui/src/tests/remote-instances.test.tsxindex c1d072b55..c3f1a588f 100644--- a/webui/src/tests/remote-instances.test.tsx+++ b/webui/src/tests/remote-instances.test.tsx@@ -1,12 +1,13 @@import { act, cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";-import { useState } from "react";+import { useEffect, 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 { readSelectedRemote, readRecentRemotes, rememberSelectedRemote, validateRemoteConnection, type RemoteConnection } from "@/lib/remote-instances";import i18n from "@/i18n";+import { clearPairReturn, initializePairReturn } from "@/lib/remote-pair-return";import type { Window as HappyWindow } from "happy-dom";(window as unknown as HappyWindow).happyDOM.settings.disableIframePageLoading = true;@@ -15,7 +16,14 @@ 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" };+ const inspect = vi.fn();+ return { read: vi.fn(), request, discover, inspect, onStatus, client: { status: "open", requestMutation: (action: string, payload: unknown, timeout: number) => {+ // Quick pairing prepares a local-only invitation when Add server opens;+ // these tests track SSH/config mutations separately from that lifecycle.+ if (action === "remote.pair_start") return Promise.resolve({ id: "pending-pair", command: "nanobot remote pair nbpr1.public", expires: Date.now() / 1000 + 600 });+ if (action === "remote.pair_cancel") return Promise.resolve({ cancelled: true });+ return action === "remote.discover" ? discover(payload) : action === "remote.inspect" ? inspect(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) => ({@@ -27,13 +35,17 @@ const connection: RemoteConnection = { ...profile, hostname: "team-host", gatewaconst noop = () => {};function LocalShell({ collapsed = false, initialRemote = false }) {const [remotePage, setRemotePage] = useState(initialRemote);+ useEffect(() => {+ const route = () => setRemotePage(window.location.hash === "#/remote");+ window.addEventListener("hashchange", route);+ return () => window.removeEventListener("hashchange", route);+ }, []);return <><Sidebar collapsed={collapsed} sessions={[]} activeKey={null} loading={false} newChatActive={false}- onNewChat={() => setRemotePage(false)} onSelect={noop} onRequestDelete={noop} onTogglePin={noop}+ onNewChat={() => { window.location.hash = "/new"; 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></>;@@ -43,16 +55,18 @@ const view = (collapsed = false, initialRemote = false) => render(<RemoteInstancbeforeEach(async () => {await i18n.changeLanguage("en");window.sessionStorage.clear(); window.localStorage.clear();+ window.history.replaceState(null, "", "#/new");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.inspect.mockReset().mockResolvedValue({ hostname: "team-host", candidates: [{ config_path: "~/.nanobot/config.json", runtime_user: "", service: "" }], 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(); });+afterEach(() => { cleanup(); clearPairReturn(); vi.restoreAllMocks(); vi.unstubAllGlobals(); });async function readyRemote() {const frame = await screen.findByTitle("nanobot on Team server");@@ -61,44 +75,298 @@ async function readyRemote() {return frame;}async function chooseHost(name: string) {- fireEvent.pointerDown(screen.getByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });+ fireEvent.pointerDown(await screen.findByRole("button", { name: i18n.t("remote.switchHost") }), { button: 0, ctrlKey: false });fireEvent.click(await screen.findByRole("menuitem", { name }));}async function openDirectory() {- fireEvent.click(await screen.findByRole("button", { name: "Remote connections" }));+ await chooseHost(i18n.t("remote.manageConnections"));+ await screen.findByRole("heading", { name: i18n.t("remote.title") });+}+function chooseExistingSSH() {+ fireEvent.pointerDown(screen.getByRole("button", { name: i18n.t("remote.pair.otherWays") }), { button: 0, ctrlKey: false });+ fireEvent.click(screen.getByRole("menuitem", { name: i18n.t("remote.pair.useSSH") }));}describe("remote instance UX", () => {- it("places remote connections after Channels with the existing sidebar button style", async () => {+ it("lets directory users cancel a cold connection before it takes over", async () => {+ let finish!: (value: RemoteConnection) => void;+ mocks.request.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ view(false, true);+ fireEvent.click(await screen.findByRole("button", { name: "Team server [email protected]" }));+ expect(await screen.findByText("Connecting to Team server…")).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Cancel switch" }));+ expect(screen.getByRole("button", { name: "Add server" })).toBeEnabled();+ await act(async () => finish(connection));+ expect(readSelectedRemote()).toBeNull();+ expect(screen.queryByTitle("nanobot on Team server")).toBeNull();+ });+ it("keeps SSH progress in the action and preserves a cancelable form", async () => {+ mocks.inspect.mockImplementation(() => new Promise(() => {}));+ await addAndInspect();+ const action = await screen.findByRole("button", { name: "Signing in and looking for nanobot…" });+ expect(action).toBeDisabled();+ expect(within(screen.getByRole("dialog")).getByRole("status").closest("button")).toBe(action);+ expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue(profile.host);+ expect(screen.getByRole("button", { name: "Cancel" })).toBeEnabled();+ });+ it("keeps editing compact and only suggests SSH hosts after changing the destination", async () => {+ view(false, true);+ fireEvent.pointerDown(await screen.findByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Edit connection" }));+ const address = screen.getByRole("textbox", { name: "SSH address" });+ expect(address).toHaveValue(profile.host);+ expect(mocks.discover).not.toHaveBeenCalled();+ expect(screen.queryByText("From your SSH config")).toBeNull();+ fireEvent.change(address, { target: { value: "[email protected]" } });+ await waitFor(() => expect(mocks.discover).toHaveBeenCalledOnce());+ expect(mocks.request).not.toHaveBeenCalled();+ });+ it("warns about live views before forgetting but cancellation does not disconnect", async () => {+ mocks.read.mockResolvedValue({ available: true, machine_name: "Xubin-Mac", profiles: [{ ...profile, connected: true }] });+ view(false, true);+ fireEvent.pointerDown(await screen.findByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Forget server" }));+ const dialog = await screen.findByRole("dialog", { name: "Forget Team server?" });+ expect(within(dialog).getByRole("note")).toHaveTextContent("Unsaved work may be lost");+ expect(within(dialog).getByRole("note")).toHaveTextContent("tabs using this connection");+ fireEvent.click(within(dialog).getByRole("button", { name: "Cancel" }));+ expect(mocks.request).not.toHaveBeenCalled();+ });+ const pairId = "c6f4f0b0-99d2-4b90-883e-903353a4a0dc";+ const pairCode = `nbpc1.${btoa(JSON.stringify({ id: pairId, data: "encrypted" })).replace(/=+$/, "")}`;+ function prepareReturn() {+ mocks.request.mockImplementation(async (action: string) => action === "remote.pair_preview" ? {+ id: pairId, hostname: "New server", host: "[email protected]", fingerprint: "SHA256:verified",+ authorized_until: Date.now() / 1000 + 86400, revoke_command: "nanobot remote revoke device",+ } : connection);+ window.history.replaceState(null, "", `http://localhost:3000/#/remote?pairing=${pairCode}`);+ initializePairReturn();+ }+ it("opens a returned link locally instead of restoring another selected server", async () => {+ rememberSelectedRemote(connection);+ prepareReturn();+ view(false, true);+ expect(await screen.findByRole("heading", { name: "Open this nanobot?" })).toBeVisible();+ expect(screen.getByText("New server")).toBeVisible();+ expect(window.location.hash).toBe("#/remote");+ expect(mocks.request.mock.calls.some(([action]) => action === "remote.connect" || action === "remote.pair_finish")).toBe(false);+ });+ it("brings a same-tab return link out of a remote view without closing its tunnel", async () => {+ view(false, true);+ fireEvent.click(await screen.findByRole("button", { name: "Team server [email protected]" }));+ await readyRemote();+ mocks.request.mockClear();+ await act(async () => { prepareReturn(); });+ expect(await screen.findByRole("heading", { name: "Open this nanobot?" })).toBeVisible();+ expect(readSelectedRemote()).toBeNull();+ expect(mocks.request.mock.calls.some(([action]) => action === "remote.disconnect" || action === "remote.connect" || action === "remote.pair_finish")).toBe(false);+ });++ it("chooses a local SSH config file and discovers its hosts without uploading contents", async () => {+ mocks.request.mockResolvedValue({ path: "/local/team/ssh_config" });+ mocks.discover.mockImplementation(async ({ ssh_config }) => ({ files: [], incomplete: false,+ hosts: ssh_config ? [{ host: "cloud-team", source: ssh_config, ssh_config }] : [],+ }));+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();+ fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: "[email protected]" } });+ fireEvent.click(screen.getByRole("button", { name: "Connection options" }));+ fireEvent.click(screen.getByRole("button", { name: "Choose file: SSH config file (optional)" }));+ await waitFor(() => expect(screen.getByRole("textbox", { name: "SSH config file (optional)" })).toHaveValue("/local/team/ssh_config"));+ expect(mocks.request).toHaveBeenCalledWith("remote.pick_file", {}, 310_000);+ expect(await screen.findByRole("button", { name: "Use cloud-team" })).toBeVisible();+ expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue("[email protected]");+ fireEvent.click(screen.getByRole("button", { name: "Use cloud-team" }));+ expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue("cloud-team");+ });++ it("keeps an existing private key path when file selection is cancelled", async () => {+ mocks.request.mockResolvedValue({ path: null });+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();+ fireEvent.click(screen.getByRole("button", { name: "Connection options" }));+ fireEvent.change(screen.getByRole("textbox", { name: "Private key path (optional)" }), { target: { value: "/local/ssh-key" } });+ fireEvent.click(screen.getByRole("button", { name: "Choose file: Private key path (optional)" }));+ await waitFor(() => expect(screen.getByRole("button", { name: "Choose file: Private key path (optional)" })).toBeEnabled());+ expect(screen.getByRole("textbox", { name: "Private key path (optional)" })).toHaveValue("/local/ssh-key");+ });++ it("does not apply a late file choice to a new editor", async () => {+ let finish!: (value: unknown) => void;+ mocks.request.mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();+ fireEvent.click(screen.getByRole("button", { name: "Connection options" }));+ fireEvent.click(screen.getByRole("button", { name: "Choose file: Private key path (optional)" }));+ expect(screen.getByRole("button", { name: "Connect" })).toBeDisabled();+ expect(screen.getByText("Choose a file in the system dialog…")).toBeVisible();+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();+ fireEvent.click(screen.getByRole("button", { name: "Connection options" }));+ await act(async () => finish({ path: "/old/choice" }));+ expect(screen.getByRole("textbox", { name: "Private key path (optional)" })).toHaveValue("");+ });++ async function addAndInspect() {+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();+ fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: profile.host } });+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ }++ it("offers a discovered service account without connecting until confirmed", async () => {+ mocks.inspect.mockResolvedValue({ hostname: "team-host", incomplete: false, candidates: [{+ config_path: "/var/lib/nanobot/.nanobot/config.json", runtime_user: "nanobot", service: "nanobot-team.service",+ }] });+ await addAndInspect();+ expect(await screen.findByText("SSH connected")).toBeVisible();+ expect(screen.getByRole("radio")).toBeChecked();+ expect(screen.getByText(/Runs as nanobot/)).toBeVisible();+ expect(screen.queryByRole("textbox", { name: "SSH address" })).not.toBeInTheDocument();+ expect(mocks.request.mock.calls.some(([action]) => action === "remote.connect")).toBe(false);+ fireEvent.click(screen.getByRole("button", { name: "Open nanobot" }));+ await readyRemote();+ expect(mocks.request).toHaveBeenCalledWith("remote.save", { id: profile.id, profile: expect.objectContaining({+ config_path: "/var/lib/nanobot/.nanobot/config.json", runtime_user: "nanobot",+ }) }, 65_000);+ expect(mocks.inspect).toHaveBeenCalledTimes(1);+ });++ it("switches when the verified app is ready without waiting for every iframe resource", async () => {+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Team server [email protected]" }));+ const frame = await screen.findByTitle("nanobot on Team server");+ const source = { postMessage: vi.fn() };+ Object.defineProperty(frame, "contentWindow", { value: source });+ const origin = new URL(connection.url).origin;+ await act(async () => window.dispatchEvent(new MessageEvent("message", {+ data: { channel: HOST_BRIDGE, type: "hello" }, source: source as unknown as Window, origin,+ })));+ const nonce = source.postMessage.mock.calls[0][0].nonce;+ await act(async () => window.dispatchEvent(new MessageEvent("message", {+ data: { channel: HOST_BRIDGE, type: "ready", nonce: "wrong" }, source: source as unknown as Window, origin,+ })));+ expect(readSelectedRemote()).toBeNull();+ await act(async () => window.dispatchEvent(new MessageEvent("message", {+ data: { channel: HOST_BRIDGE, type: "ready", nonce }, source: source as unknown as Window, origin,+ })));+ await waitFor(() => expect(readSelectedRemote()?.id).toBe(profile.id));+ });++ it("gives a cold page time to load and keeps its failed setup retryable", async () => {+ const timer = vi.spyOn(window, "setTimeout");+ await addAndInspect();+ await screen.findByTitle("nanobot on Team server");+ const deadline = timer.mock.calls.find(([, delay]) => delay === 60_000);+ expect(deadline).toBeDefined();+ await act(async () => { (deadline![0] as () => void)(); });+ expect(await screen.findByRole("alert")).toHaveTextContent(i18n.t("remote.errors.view_load_failed"));+ expect(screen.queryByRole("button", { name: "SSH login settings" })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Open nanobot" }));+ await readyRemote();+ });++ it("requires an explicit choice between multiple discovered nanobots", async () => {+ mocks.inspect.mockResolvedValue({ hostname: "team-host", incomplete: false, candidates: [+ { config_path: "/srv/one/config.json", runtime_user: "", service: "" },+ { config_path: "/srv/two/config.json", runtime_user: "nanobot", service: "nanobot-two.service" },+ ] });+ await addAndInspect();+ await screen.findByText("SSH connected");+ expect(screen.getByRole("button", { name: "Open nanobot" })).toBeDisabled();+ fireEvent.click(screen.getByRole("radio", { name: /nanobot-two.service/ }));+ expect(screen.getByRole("button", { name: "Open nanobot" })).toBeEnabled();+ fireEvent.click(screen.getByRole("button", { name: "Open nanobot" }));+ await readyRemote();+ expect(mocks.request).toHaveBeenCalledWith("remote.save", { id: profile.id, profile: expect.objectContaining({ config_path: "/srv/two/config.json" }) }, 65_000);+ });++ it("asks for the server location only after SSH succeeds but discovery finds nothing", async () => {+ mocks.inspect.mockResolvedValue({ hostname: "team-host", candidates: [], incomplete: true });+ await addAndInspect();+ expect(await screen.findByText("No nanobot configuration found")).toBeVisible();+ expect(screen.getByText("SSH connected")).toBeVisible();+ fireEvent.change(screen.getByRole("textbox", { name: "Server's nanobot config path" }), { target: { value: "/srv/bot/config.json" } });+ fireEvent.click(screen.getByRole("button", { name: "Open nanobot" }));+ await readyRemote();+ expect(mocks.inspect).toHaveBeenCalledTimes(1);+ });++ it("recovers a handshake failure through SSH settings without blaming nanobot or a missing key", async () => {+ mocks.inspect.mockRejectedValue(new Error("ssh_connection_closed"));+ await addAndInspect();+ expect(await screen.findByRole("alert")).toHaveTextContent("does not confirm a key problem");+ expect(screen.queryByText("SSH connected")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "SSH login settings" }));+ expect(screen.getByRole("textbox", { name: "Private key path (optional)" })).toBeVisible();+ expect(screen.queryByRole("textbox", { name: "Server's nanobot config path" })).not.toBeInTheDocument();+ expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue(profile.host);+ });++ it("does not resume inspection or auto-connect after cancelling the dialog", async () => {+ let resolve!: (value: unknown) => void;+ mocks.inspect.mockReturnValue(new Promise((done) => { resolve = done; }));+ await addAndInspect();+ await waitFor(() => expect(mocks.inspect).toHaveBeenCalledTimes(1));+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ await act(async () => resolve({ hostname: "server", candidates: [{ config_path: "/srv/bot/config.json", runtime_user: "", service: "" }], incomplete: false }));+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(mocks.request.mock.calls.some(([action]) => action === "remote.connect")).toBe(false);+ expect(mocks.request.mock.calls.filter(([action]) => action === "remote.save")).toHaveLength(1);+ });++ it("verifies a first-contact host before resuming discovery instead of connecting blindly", async () => {+ mocks.inspect.mockRejectedValueOnce(new Error("host_key_unknown")).mockResolvedValue({+ hostname: "team-host", candidates: [], incomplete: false,+ });+ mocks.request.mockImplementation(async (action: string) => action === "remote.save" ? { id: profile.id }+ : action === "remote.fingerprint" ? { fingerprint: "SHA256:verified-test", challenge: "nonce" } : {});+ await addAndInspect();+ await screen.findByText("SHA256:verified-test");+ fireEvent.click(screen.getByRole("button", { name: "Fingerprint matches · Connect" }));+ expect(await screen.findByText("No nanobot configuration found")).toBeVisible();+ expect(mocks.inspect).toHaveBeenCalledTimes(2);+ expect(mocks.request.mock.calls.some(([action]) => action === "remote.connect")).toBe(false);+ });++ it("changing the server requires discovery again and preserves typed SSH settings", async () => {+ mocks.inspect.mockResolvedValue({ hostname: "team-host", candidates: [], incomplete: false });+ await addAndInspect();+ await screen.findByText("SSH connected");+ fireEvent.click(screen.getByRole("button", { name: "Change" }));+ expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue(profile.host);+ fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: "[email protected]" } });+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ await screen.findByText("SSH connected");+ expect(mocks.inspect).toHaveBeenCalledTimes(2);+ });++ it("uses only the footer host menu to reach connection management", 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");+ await screen.findByRole("button", { name: "Switch host" });+ expect(screen.queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();expect(screen.queryByText("This machine")).not.toBeInTheDocument();- fireEvent.click(entry);- await screen.findByRole("heading", { name: "Remote connections" });+ await openDirectory();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();+ expect(screen.getByRole("button", { name: "Add server" })).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" });+ const switcher = await screen.findByRole("button", { name: "Switch host" });+ expect(screen.queryByRole("button", { name: "Remote connections" })).not.toBeInTheDocument();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" });+ await openDirectory();});it("moves the remote picker into a verified sidebar and can return local through its parent-owned menu", async () => {@@ -129,12 +397,13 @@ describe("remote instance UX", () => {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: "远程连接" }));+ await openDirectory();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: "返回" }));+ fireEvent.click(screen.getByRole("button", { name: "添加服务器" }));+ chooseExistingSSH();+ expect(screen.getByRole("heading", { name: "连接服务器" })).toBeInTheDocument();+ expect(screen.getByRole("dialog", { name: "连接服务器" })).toBeVisible();+ 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();@@ -150,6 +419,7 @@ describe("remote instance UX", () => {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");+ expect(readRecentRemotes()).toEqual([profile.id]);const storedValues = Array.from({ length: window.localStorage.length }, (_, index) =>window.localStorage.getItem(window.localStorage.key(index) || ""));expect(JSON.stringify(storedValues)).not.toContain("private-secret");@@ -164,6 +434,7 @@ describe("remote instance UX", () => {expect(screen.getByRole("heading", { name: "Remote connections" })).toBeVisible();expect(mocks.request.mock.calls.some(([action]) => action === "remote.disconnect")).toBe(false);expect(readSelectedRemote()).toBeNull();+ expect(readRecentRemotes()).toEqual([profile.id]);expect(mocks.request.mock.calls.some(([action]) => String(action).includes("stop"))).toBe(false);});@@ -254,17 +525,176 @@ describe("remote instance UX", () => {});it("saves once and preserves entered fields when SSH authentication fails", async () => {+ mocks.inspect.mockRejectedValue(new Error("ssh_auth_failed"));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…" }));+ view(); await openDirectory(); fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();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: "Connect" }));await screen.findByRole("alert");expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue("[email protected]");- expect(screen.getByRole("button", { name: "Save & connect" })).toBeEnabled();+ expect(screen.getByRole("button", { name: "Connect" })).toBeEnabled();expect(mocks.request.mock.calls.filter(([action]) => action === "remote.save")).toHaveLength(1);+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ await waitFor(() => expect(mocks.request.mock.calls.filter(([action]) => action === "remote.save")).toHaveLength(2));+ expect(mocks.inspect).toHaveBeenCalledWith({ id: profile.id });+ expect(mocks.request.mock.calls.some(([action]) => action === "remote.connect")).toBe(false);+ expect(mocks.request.mock.calls.filter(([action]) => action === "remote.save")[1][1]).toMatchObject({ id: profile.id });+ });++ it("edits in the same dialog but only saves, without connecting or switching", async () => {+ view(); await openDirectory();+ fireEvent.pointerDown(screen.getByRole("button", { name: "Manage Team server" }), { button: 0, ctrlKey: false });+ fireEvent.click(await screen.findByRole("menuitem", { name: "Edit connection" }));+ const dialog = await screen.findByRole("dialog", { name: "Edit connection" });+ expect(within(dialog).getByRole("textbox", { name: "SSH address" })).toHaveValue(profile.host);+ fireEvent.click(within(dialog).getByRole("button", { name: "Connection options" }));+ fireEvent.change(within(dialog).getByRole("textbox", { name: "Name (optional)" }), { target: { value: "Renamed server" } });+ fireEvent.click(within(dialog).getByRole("button", { name: "Save changes" }));+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());+ expect(mocks.request).toHaveBeenCalledTimes(1);+ expect(mocks.request).toHaveBeenCalledWith("remote.save", {+ id: profile.id, profile: expect.objectContaining({ host: profile.host, name: "Renamed server" }),+ }, 65_000);+ expect(readSelectedRemote()).toBeNull();+ expect(screen.getByRole("heading", { name: "Remote connections" })).toBeVisible();+ });++ it.each(["en", "zh-CN"])("keeps server login separate from nanobot location (%s)", async (language) => {+ await i18n.changeLanguage(language);+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: i18n.t("remote.add") }));+ chooseExistingSSH();+ fireEvent.click(screen.getByRole("button", { name: i18n.t("remote.connectionOptions") }));+ const port = screen.getByRole("spinbutton", { name: i18n.t("remote.sshPort") });+ const key = screen.getByRole("textbox", { name: i18n.t("remote.identity_file") });+ expect(screen.queryByRole("textbox", { name: i18n.t("remote.runtime_user") })).not.toBeInTheDocument();+ expect(screen.queryByRole("textbox", { name: i18n.t("remote.config_path") })).not.toBeInTheDocument();+ expect(port).toHaveClass("h-10");+ expect(key).toHaveClass("h-10");+ });++ it("imports a pasted SSH command into the existing connection options", async () => {+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();+ const address = screen.getByRole("textbox", { name: "SSH address" });+ fireEvent.change(address, { target: { value: 'ssh -p2222 -i "~/.ssh/team key" -l ubuntu example.test' } });+ fireEvent.blur(address);+ expect(address).toHaveValue("[email protected]");+ expect(screen.getByRole("status")).toHaveTextContent(i18n.t("remote.commandImported"));+ expect(mocks.request).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Connection options" }));+ expect(screen.getByRole("spinbutton", { name: "SSH port" })).toHaveValue(2222);+ expect(screen.getByRole("textbox", { name: "Private key path (optional)" })).toHaveValue("~/.ssh/team key");+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ await readyRemote();+ expect(mocks.request).toHaveBeenCalledWith("remote.save", {+ id: "", profile: expect.objectContaining({ host: "[email protected]", name: "[email protected]", port: 2222, identity_file: "~/.ssh/team key" }),+ }, 65_000);+ });++ it("parses Enter submission without requiring a blur and preserves fields after failure", async () => {+ mocks.request.mockImplementation(async (action: string) => {+ if (action === "remote.save") return { id: profile.id };+ throw new Error("ssh_agent_refused");+ });+ view(); await openDirectory(); fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();+ const address = screen.getByRole("textbox", { name: "SSH address" });+ fireEvent.change(address, { target: { value: "ssh -p 2222 [email protected]" } });+ fireEvent.submit(address.closest("form")!);+ const alert = await screen.findByRole("alert");+ expect(alert).toHaveTextContent(i18n.t("remote.errors.ssh_agent_refused"));+ expect(alert.closest(".overflow-y-auto")).toBeNull();+ expect(address).toHaveValue("[email protected]");+ fireEvent.click(screen.getByRole("button", { name: "Connection options" }));+ expect(screen.getByRole("spinbutton", { name: "SSH port" })).toHaveValue(2222);+ expect(screen.getByRole("button", { name: "Connect" })).toBeEnabled();+ });++ it("doesn't save or execute a command with unsupported flags", async () => {+ view(); await openDirectory(); fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();+ const address = screen.getByRole("textbox", { name: "SSH address" });+ fireEvent.change(address, { target: { value: "ssh -o ProxyCommand=unsafe team" } });+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ expect(await screen.findByRole("alert")).toHaveTextContent(i18n.t("remote.errors.invalid_ssh_command"));+ expect(address).toHaveValue("ssh -o ProxyCommand=unsafe team");+ expect(mocks.request).not.toHaveBeenCalled();+ });++ it("closes a successful add dialog so returning local shows the directory", async () => {+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();+ fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: profile.host } });+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ await readyRemote();+ await chooseHost("Local nanobot Xubin-Mac");+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(screen.getByRole("heading", { name: "Remote connections" })).toBeVisible();+ });++ it("cancels a dialog's pending connection without a late jump or error", async () => {+ let finish: ((result: RemoteConnection) => void) | undefined;+ mocks.request.mockImplementation(async (action: string) => action === "remote.save" ? { id: profile.id }+ : new Promise<RemoteConnection>((resolve) => { finish = resolve; }));+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();+ fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: profile.host } });+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ await waitFor(() => expect(finish).toBeDefined());+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ await act(async () => { finish?.(connection); });+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(screen.queryByTitle("nanobot on Team server")).not.toBeInTheDocument();+ expect(screen.queryByRole("alert")).not.toBeInTheDocument();+ expect(readSelectedRemote()).toBeNull();+ });++ it("keeps verification in one dialog and Back preserves setup without trusting", async () => {+ mocks.request.mockImplementation(async (action: string) => {+ if (action === "remote.save") return { id: profile.id };+ 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: "Add server" }));+ chooseExistingSSH();+ fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: profile.host } });+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ await screen.findByText("SHA256:example");+ expect(screen.getAllByRole("dialog")).toHaveLength(1);+ fireEvent.click(screen.getByRole("button", { name: "Back" }));+ expect(screen.getByRole("textbox", { name: "SSH address" })).toHaveValue(profile.host);+ expect(screen.getAllByRole("dialog")).toHaveLength(1);+ expect(mocks.request.mock.calls.some(([action]) => action === "remote.trust")).toBe(false);+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ });++ it("does not reopen verification after cancelling a pending fingerprint read", async () => {+ let finish: ((value: { fingerprint: string; challenge: string }) => void) | undefined;+ mocks.request.mockImplementation(async (action: string) => {+ if (action === "remote.save") return { id: profile.id };+ if (action === "remote.connect") throw new Error("host_key_unknown");+ return new Promise<{ fingerprint: string; challenge: string }>((resolve) => { finish = resolve; });+ });+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();+ fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { target: { value: profile.host } });+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ await waitFor(() => expect(finish).toBeDefined());+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ await act(async () => { finish?.({ fingerprint: "SHA256:example", challenge: "one-use" }); });+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();+ expect(screen.queryByText("SHA256:example")).not.toBeInTheDocument();});it("doesn't create privileged controls on an unsupported remote gateway", async () => {@@ -280,20 +710,26 @@ describe("remote instance UX", () => {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();+ expect(screen.queryByRole("button", { name: "Add server" })).not.toBeInTheDocument();});- it("offers existing SSH hosts or manual inline setup for the first server", async () => {+ it("keeps the directory quiet and offers one focused add-server dialog", 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…" }));+ expect(mocks.discover).not.toHaveBeenCalled();+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();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();+ const dialog = screen.getByRole("dialog", { name: "Connect to a server" });+ expect(dialog).toContainElement(host);+ expect(host).toHaveFocus();+ expect(within(dialog).getAllByRole("textbox")).toHaveLength(1);+ expect(screen.getByRole("button", { name: "Add server", hidden: true })).toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Connect" })).toBeDisabled();+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));+ await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());+ expect(screen.getByRole("button", { name: "Add server" })).toHaveFocus();+ expect(screen.getByRole("heading", { name: "Remote connections" })).toBeVisible();});it("does not navigate to a remote instance after leaving a pending connection", async () => {@@ -313,9 +749,11 @@ describe("remote instance UX", () => {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.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();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: "Connect" }));+ fireEvent.click(screen.getByRole("button", { name: "Cancel" }));fireEvent.click(screen.getByRole("button", { name: "New topic" }));await act(async () => { finish?.({ id: profile.id }); });expect(mocks.request).toHaveBeenCalledTimes(1);@@ -324,7 +762,7 @@ describe("remote instance UX", () => {it("keeps cached servers visible during refresh and lets users retry failed reads", async () => {view();- await screen.findByRole("button", { name: "Remote connections" });+ await screen.findByRole("button", { name: "Switch host" });mocks.read.mockRejectedValue(new Error("directory_unavailable"));await openDirectory();await screen.findByRole("alert");@@ -361,53 +799,82 @@ describe("remote instance UX", () => {{ host: "staging", source: "/home/test/.ssh/hosts", ssh_config: "" },], files: ["/home/test/.ssh/config"], incomplete: false });view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();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" } });+ const address = screen.getByRole("textbox", { name: "SSH address" });+ fireEvent.keyDown(address, { key: "ArrowDown" });+ expect(screen.getByRole("button", { name: "Use team-sg" })).toHaveFocus();+ fireEvent.keyDown(document.activeElement!, { key: "ArrowDown" });+ expect(screen.getByRole("button", { name: "Use staging" })).toHaveFocus();+ fireEvent.keyDown(document.activeElement!, { key: "ArrowUp" });+ fireEvent.keyDown(document.activeElement!, { key: "ArrowUp" });+ expect(address).toHaveFocus();+ fireEvent.change(screen.getByRole("textbox", { name: "SSH address" }), { 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" }));+ fireEvent.click(screen.getByRole("button", { name: "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" } });+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();+ fireEvent.click(screen.getByRole("button", { name: "Connection options" }));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.change(screen.getByRole("textbox", { name: "SSH config file (optional)" }), { target: { value: "/team/ssh_config" } });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);+ expect(screen.queryByRole("button", { name: "Read hosts" })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Connect" }));+ await readyRemote();+ expect(mocks.request).toHaveBeenCalledWith("remote.save", expect.objectContaining({ profile: expect.objectContaining({ host: "team", ssh_config: "/team/ssh_config" }) }), 65_000);});it("keeps manual entry available for an invalid discovery response", async () => {mocks.discover.mockResolvedValue({ hosts: [{}], files: [], incomplete: false });view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();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("ignores late SSH suggestions after changing the config file", async () => {+ let finishOld: ((value: unknown) => void) | undefined;+ mocks.discover.mockImplementation(({ ssh_config }: { ssh_config: string }) => ssh_config+ ? Promise.resolve({ hosts: [{ host: "custom-team", source: ssh_config, ssh_config }], files: [ssh_config], incomplete: false })+ : new Promise((resolve) => { finishOld = resolve; }));+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();+ await waitFor(() => expect(finishOld).toBeDefined());+ fireEvent.click(screen.getByRole("button", { name: "Connection options" }));+ fireEvent.change(screen.getByRole("textbox", { name: "SSH config file (optional)" }), { target: { value: "/team/config" } });+ await screen.findByRole("button", { name: "Use custom-team" });+ await act(async () => { finishOld?.({ hosts: [{ host: "stale-host", source: "/default", ssh_config: "" }], files: ["/default"], incomplete: false }); });+ expect(screen.queryByRole("button", { name: "Use stale-host" })).not.toBeInTheDocument();+ expect(screen.getByRole("button", { name: "Use custom-team" })).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();+ fireEvent.click(screen.getByRole("button", { name: "Add server" }));+ chooseExistingSSH();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();});@@ -447,6 +914,84 @@ describe("remote instance UX", () => {expect(screen.getByTitle("nanobot on Team server")).toBe(frame);expect(frame.parentElement).not.toHaveAttribute("inert");});++ it("rechecks on wake and network recovery without reloading or switching hosts", async () => {+ vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");+ const rendered = view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Team server [email protected]" }));+ const frame = await readyRemote();+ mocks.read.mockClear();+ await act(async () => { window.dispatchEvent(new Event("online")); });+ expect(mocks.read).toHaveBeenCalledTimes(1);+ await act(async () => { document.dispatchEvent(new Event("visibilitychange")); });+ expect(mocks.read).toHaveBeenCalledTimes(2);+ await screen.findByText("Server connection lost");+ mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, connected: true }] });+ await act(async () => { window.dispatchEvent(new Event("pageshow")); });+ expect(mocks.read).toHaveBeenCalledTimes(3);+ expect(screen.queryByText("Server connection lost")).not.toBeInTheDocument();+ expect(screen.getByTitle("nanobot on Team server")).toBe(frame);+ expect(readSelectedRemote()?.id).toBe(profile.id);+ expect(mocks.request.mock.calls.filter(([action]) => action === "remote.connect")).toHaveLength(1);+ rendered.unmount();+ mocks.read.mockClear();+ window.dispatchEvent(new Event("online"));+ document.dispatchEvent(new Event("visibilitychange"));+ expect(mocks.read).not.toHaveBeenCalled();+ });++ it("coalesces wake signals while a health check is in flight", async () => {+ vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Team server [email protected]" }));+ await readyRemote();+ let finish: ((result: unknown) => void) | undefined;+ mocks.read.mockClear().mockImplementation(() => new Promise((resolve) => { finish = resolve; }));+ await act(async () => {+ window.dispatchEvent(new Event("online"));+ window.dispatchEvent(new Event("pageshow"));+ document.dispatchEvent(new Event("visibilitychange"));+ });+ expect(mocks.read).toHaveBeenCalledTimes(1);+ await act(async () => { finish?.({ available: true, profiles: [{ ...profile, connected: true }] }); });+ expect(readSelectedRemote()?.id).toBe(profile.id);+ });++ it.each(["pair_authorization_rejected", "remote_auth_failed", "host_key_changed", "incompatible_gateway"])("offers setup rather than endless reconnect for %s", async (code) => {+ vi.spyOn(document, "visibilityState", "get").mockReturnValue("visible");+ view(); await openDirectory();+ fireEvent.click(screen.getByRole("button", { name: "Team server [email protected]" }));+ await readyRemote();+ mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, connected: false, connection_error: code }] });+ await act(async () => { window.dispatchEvent(new Event("online")); });+ await act(async () => { window.dispatchEvent(new Event("pageshow")); });+ expect(screen.getByText(i18n.t(`remote.errors.${code}`))).toBeVisible();+ expect(screen.queryByRole("button", { name: "Reconnect" })).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: "Manage connections…" }));+ expect(readSelectedRemote()).toBeNull();+ expect(mocks.request.mock.calls.filter(([action]) => action === "remote.disconnect")).toHaveLength(0);+ });++ it("dismissing a restore error does not leave an endless opening screen", async () => {+ rememberSelectedRemote(connection);+ mocks.request.mockRejectedValue(new Error("ssh_unreachable"));+ view();+ await screen.findByText("Server connection lost");+ fireEvent.pointerDown(screen.getByRole("button", { name: "Switch host" }), { button: 0, ctrlKey: false });+ fireEvent.click(await screen.findByRole("button", { name: "Close" }));+ fireEvent.keyDown(screen.getByRole("menu"), { key: "Escape" });+ expect(screen.getByText("Server connection lost")).toBeVisible();+ expect(screen.getByRole("button", { name: "Reconnect" })).toBeVisible();+ expect(screen.queryByText("Opening your server…")).not.toBeInTheDocument();+ });++ it.each([[-1, true], [3, true], [30, false]])("shows only relevant device expiry hints at %i days", async (days, visible) => {+ mocks.read.mockResolvedValue({ available: true, profiles: [{ ...profile, paired: true,+ authorized_until: Math.floor(Date.now() / 1000) + days * 86400 }] });+ view(false, true);+ await screen.findByRole("button", { name: /Team server [email protected]/ });+ expect(!!screen.queryByText(days < 0 ? /Authorization expired/ : /Authorization expires/)).toBe(visible);+ });});it.each(["https://evil.example/", "http://[email protected]:23456/", "javascript:alert(1)", "http://127.0.0.1:23456/wrong"])("rejects unsafe navigation %s", (url) => {diff --git a/webui/src/tests/remote-pair-return.test.ts b/webui/src/tests/remote-pair-return.test.tsnew file mode 100644index 000000000..49d4bf502--- /dev/null+++ b/webui/src/tests/remote-pair-return.test.ts@@ -0,0 +1,37 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { clearPairReturn, initializePairReturn, parsePairReturn, readPairReturn, subscribePairReturn } from "@/lib/remote-pair-return";++const id = "c6f4f0b0-99d2-4b90-883e-903353a4a0dc";+const code = `nbpc1.${btoa(JSON.stringify({ id, data: "encrypted" })).replace(/=+$/, "")}`;+afterEach(() => { clearPairReturn(); vi.unstubAllGlobals(); });++describe("pairing return link", () => {+ it("parses only a bounded return receipt, never a hostname or executable action", () => {+ expect(parsePairReturn(`#/remote?pairing=${code}`)).toEqual({ id, code });+ expect(parsePairReturn(`#/new?pairing=${code}`)).toBeNull();+ expect(parsePairReturn("#/remote")).toBeNull();+ for (const invalid of ["bad", "nbpc1." + "A".repeat(32769), "nbpc1.e30", code + "&pairing=" + code]) {+ expect(parsePairReturn(`#/remote?pairing=${invalid}`)).toEqual({ id: "", code: "" });+ }+ });+ it("removes fragment data before notifying the UI, without persisting it", () => {+ const replaceState = vi.fn();+ const win = { top: null as unknown, location: { hash: `#/remote?pairing=${code}`, hostname: "127.0.0.1", protocol: "http:", pathname: "/", search: "" }, history: { replaceState } };+ win.top = win;+ vi.stubGlobal("window", win);+ const listener = vi.fn(() => expect(replaceState).toHaveBeenCalledWith(null, "", "/#/remote"));+ const unsubscribe = subscribePairReturn(listener);+ initializePairReturn();+ expect(readPairReturn()).toEqual({ id, code });+ expect(listener).toHaveBeenCalledOnce();+ unsubscribe();+ });+ it.each([true, false])("rejects a non-local controller (embedded=%s)", (embedded) => {+ const win = { top: null as unknown, location: { hash: `#/remote?pairing=${code}`, hostname: embedded ? "localhost" : "example.com", protocol: "http:", pathname: "/", search: "" }, history: { replaceState: vi.fn() } };+ win.top = embedded ? {} : win;+ vi.stubGlobal("window", win);+ initializePairReturn();+ expect(win.history.replaceState).toHaveBeenCalled();+ expect(readPairReturn()).toBeNull();+ });+});diff --git a/webui/src/tests/ssh-address.test.ts b/webui/src/tests/ssh-address.test.tsnew file mode 100644index 000000000..e5a12cbbb--- /dev/null+++ b/webui/src/tests/ssh-address.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from "vitest";+import { parseSSHAddress } from "@/lib/ssh-address";++describe("SSH address import", () => {+ it.each(["team", "[email protected]", "user@2001:db8::1"])("keeps the address %s", (host) => {+ expect(parseSSHAddress(` ${host} `)).toEqual({ host });+ });+ it("imports quoted paths, a login user and port without running a command", () => {+ expect(parseSSHAddress('ssh -p 2222 -l ubuntu -i "~/.ssh/team key" -F ~/.ssh/work team')).toEqual({+ host: "ubuntu@team", port: 2222, identity_file: "~/.ssh/team key", ssh_config: "~/.ssh/work",+ });+ });+ it("supports attached option values and preserves Windows path separators", () => {+ expect(parseSSHAddress('ssh -p2222 -i "C:\\Users\\User Name\\.ssh\\id_ed25519" team')).toEqual({+ host: "team", port: 2222, identity_file: "C:\\Users\\User Name\\.ssh\\id_ed25519",+ });+ expect(() => parseSSHAddress("ssh -F'bad' host")).toThrow("invalid_ssh_command");+ expect(parseSSHAddress("ssh -i '/tmp/my key' team")).toEqual({ host: "team", identity_file: "/tmp/my key" });+ });+ it.each([+ "", "ssh -p", "ssh -p 0 team", "ssh -p 65536 team", "ssh -p 2.5 team",+ "ssh -p 22 -p 23 team", "ssh -i", 'ssh -i "unterminated team',+ "ssh -l root ubuntu@team", "ssh -l root", "ssh one two", "ssh team -p 22",+ "ssh -o StrictHostKeyChecking=no team", "ssh -J jump team", "ssh -A team",+ "ssh team whoami", "ssh team; whoami", "ssh team && whoami", "ssh team\nwhoami",+ "ssh -i $(touch) team", "ssh -i $HOME/key team", "https://team", "user@host;evil",+ ])("rejects ambiguous or unsupported input without silently discarding it: %s", (text) => {+ expect(() => parseSSHAddress(text)).toThrow("invalid_ssh_command");+ });+});