feat(cli): attach terminal clients to the selected Desktop [skip ci]

NAN-104 requires terminal chat and browser attachment without granting a client ownership of Desktop's gateway. Resolve bounded short-lived credentials over authenticated current-user IPC, pin both Desktop and gateway identities, and reject replacement instances or incompatible clients before any mutation.

Reuse the existing TUI artifact resolver behind a narrow Desktop-only entrypoint, keep credentials out of argv/environment/files, and preserve Python-mode reconnect and gateway leases. Add protocol, real-gateway, and anonymous IPC regression coverage; matching native-host and Windows acceptance remain release gates.
This commit is contained in:
Xubin Ren committed 2026-09-08 10:04:15 +08:00
1 parent b373a95f5c
commit 48e7c4f697
20 files changed
+797 -52

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
"""Terminal capability metadata is authenticated and does not allocate tokens."""
import json
from types import SimpleNamespace
from websockets.datastructures import Headers
from websockets.http11 import Request
from nanobot.channels.websocket.runtime import WebSocketConfig
from nanobot.webui.gateway_tokens import GatewayTokenStore
from nanobot.webui.ws_http import GatewayHTTPHandler
def test_terminal_probe_is_private_stable_and_does_not_issue_credentials():
handler = object.__new__(GatewayHTTPHandler)
handler.config = WebSocketConfig(token_issue_secret="fixture-secret")
handler.tokens = GatewayTokenStore(max_tokens=0)
connection = SimpleNamespace(remote_address=("127.0.0.1", 10000))
request = Request("/webui/terminal", Headers({"Host": "127.0.0.1:8765"}))
assert handler._handle_bootstrap(connection, request, terminal_probe=True).status_code == 401
request.headers["X-Nanobot-Auth"] = "fixture-secret"
for _ in range(3):
response = handler._handle_bootstrap(connection, request, terminal_probe=True)
assert response.status_code == 200
assert json.loads(response.body) == {
"protocolVersion": 1, "gatewayId": handler.tokens.instance_id,
}
assert "no-store" in response.headers["Cache-Control"]
assert not handler.tokens.api_tokens and not handler.tokens.issued_tokens
assert GatewayTokenStore().instance_id != handler.tokens.instance_id
+49
View File
@@ -211,6 +211,55 @@ async def test_gateway_webui_bootstrap_message_and_thread_hydration(tmp_path: Pa
_stop_gateway(process)
@pytest.mark.asyncio
async def test_desktop_terminal_identity_and_independent_client_lifetime(tmp_path: Path) -> None:
"""Two terminal clients exercise real authentication, framing and gateway lifetime."""
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)
base_url = f"http://127.0.0.1:{ws_port}"
try:
first = _wait_for_bootstrap(base_url, process, log_path)
terminal = first["terminal"]
assert terminal["protocolVersion"] == 1
unauthenticated = httpx.get(f"{base_url}/webui/terminal", trust_env=False)
assert unauthenticated.status_code == 401
probe = _get_bootstrap(f"{base_url}/webui/terminal")
assert probe == terminal # Contains no token or config information.
second = _get_bootstrap(f"{base_url}/webui/bootstrap")
assert second["terminal"] == terminal
identity_query = f'&terminal_protocol=1&terminal_instance={terminal["gatewayId"]}'
first_url = f'{first["ws_url"]}?token={first["token"]}&client_id=terminal-one'
# A rejected wrong-instance upgrade must not consume the one-use WS token.
with pytest.raises(websockets.exceptions.InvalidStatus) as wrong:
async with websockets.connect(first_url + "&terminal_protocol=1&terminal_instance=wrong"):
pytest.fail("Wrong gateway identity accepted")
assert wrong.value.response.status_code == 409
async with websockets.connect(first_url + identity_query) as one:
assert (await _recv_until(one, "ready"))["terminal"] == terminal
second_url = f'{second["ws_url"]}?token={second["token"]}&client_id=terminal-two'
async with websockets.connect(second_url + identity_query) as two:
assert (await _recv_until(two, "ready"))["terminal"] == terminal
await one.close()
await two.send(json.dumps({"type": "new_chat"}))
chat_id = (await _recv_until(two, "attached"))["chat_id"]
await two.send(json.dumps({"type": "message", "chat_id": chat_id,
"content": "/model", "webui": True, "turn_id": "terminal-model"}))
assert "custom/smoke-model" in (await _recv_until(two, "message"))["text"]
await _recv_until(two, "turn_end")
assert process.poll() is None
after = _get_bootstrap(f"{base_url}/webui/bootstrap")
assert after["terminal"] == terminal
# The ordinary WebUI ready frame remains unchanged (no opt-in metadata).
async with websockets.connect(f'{after["ws_url"]}?token={after["token"]}&client_id=browser') as browser:
assert "terminal" not in await _recv_until(browser, "ready")
finally:
_stop_gateway(process)
def test_gateway_restart_restores_a_completed_answer_without_replaying_model(
tmp_path: Path,
) -> None: