Skip to content

Your lightweight open-source personal agent.

fix(cli): isolate Desktop compatibility probes [skip ci]

Xubin Ren9a594f74ff89
diff --git a/nanobot/cli/desktop_tui.py b/nanobot/cli/desktop_tui.py
index 2a85e4e7b..dfc876e65 100644
--- a/nanobot/cli/desktop_tui.py
+++ b/nanobot/cli/desktop_tui.py
@@ -110,12 +110,15 @@ def launch_desktop_tui(target: DesktopTarget) -> int:
if cache is not None and not Path(cache).is_absolute():
raise DesktopTargetError("Desktop client cache must be absolute")
command = resolve_tui_command(data_dir=Path(cache)) if cache else resolve_tui_command()
+ # An old client may ignore the probe flag. It must not consume terminal
+ # input or connect using credentials inherited from another TUI session.
+ env = {key: value for key, value in os.environ.items() if not key.startswith("NANOBOT_TUI_")}
probe = subprocess.run(
[*command, "--desktop-protocol"], capture_output=True, timeout=15, check=False,
+ stdin=subprocess.DEVNULL, env=env,
)
if probe.returncode != 0 or probe.stdout.strip() != b"1":
raise DesktopTargetError("The terminal client does not support Desktop attachment")
- env = {key: value for key, value in os.environ.items() if not key.startswith("NANOBOT_TUI_")}
env["NANOBOT_TUI_DESKTOP_RESOLVER"] = json.dumps([
sys.executable, "-I", "-S", str(Path(__file__).resolve()), "--resolve",
])
diff --git a/tests/cli/test_desktop_tui.py b/tests/cli/test_desktop_tui.py
index fbf0a62ec..f39c56e7d 100644
--- a/tests/cli/test_desktop_tui.py
+++ b/tests/cli/test_desktop_tui.py
@@ -71,7 +71,13 @@ def test_launcher_has_no_gateway_ownership_and_no_credentials_in_child_env(monke
process = MagicMock()
process.wait.return_value = 90
process.poll.return_value = 90
- monkeypatch.setattr(desktop_tui.subprocess, "run", lambda *a, **kw: subprocess.CompletedProcess(a, 0, b"1\n", b""))
+ def probe(args, **kw):
+ assert args == ["terminal-client", "--desktop-protocol"]
+ assert kw["stdin"] == subprocess.DEVNULL
+ assert not any(key.startswith("NANOBOT_TUI_") for key in kw["env"])
+ assert "unrelated-bootstrap" not in json.dumps((args, kw))
+ return subprocess.CompletedProcess(args, 0, b"1\n", b"")
+ monkeypatch.setattr(desktop_tui.subprocess, "run", probe)
def start(args, **kw):
calls.append((args, kw))
return process
@@ -92,6 +98,30 @@ def test_launcher_has_no_gateway_ownership_and_no_credentials_in_child_env(monke
process.terminate.assert_not_called()
+def test_protocol_probe_is_isolated_in_a_real_child(monkeypatch):
+ # Older clients ignore --desktop-protocol and consume normal connection env.
+ # Probe them without credentials or terminal input, before allowing launch.
+ command = [sys.executable, "-I", "-S", "-c", """
+import os, sys
+keys = {key for key in os.environ if key.startswith('NANOBOT_TUI_')}
+if sys.argv[-1] == '--desktop-protocol':
+ if keys:
+ sys.exit(7)
+ if sys.stdin.buffer.read(1):
+ sys.exit(8)
+ print(1)
+else:
+ assert keys == {'NANOBOT_TUI_DESKTOP_TARGET', 'NANOBOT_TUI_DESKTOP_RESOLVER'}
+ sys.exit(90)
+"""]
+ monkeypatch.setattr(tui_launcher, "resolve_tui_command", lambda: command)
+ monkeypatch.delenv("NANOBOT_DESKTOP_CLIENT_CACHE", raising=False)
+ monkeypatch.setenv("NANOBOT_TUI_BOOTSTRAP_URL", "http://127.0.0.1:1/webui/bootstrap")
+ monkeypatch.setenv("NANOBOT_TUI_BOOTSTRAP_SECRET", "unrelated-bootstrap")
+ monkeypatch.setenv("NANOBOT_TUI_DESKTOP_RESOLVER", "unrelated-resolver")
+ assert desktop_tui.launch_desktop_tui(target()) == 0
+
+
def test_unsupported_desktop_does_not_install_or_launch_a_client(monkeypatch):
chosen = target()
chosen.request.return_value = DesktopReply("ready", frozenset({"webui"}))
diff --git a/tests/cli/test_tui_launcher.py b/tests/cli/test_tui_launcher.py
index 4df9bd24b..409998608 100644
--- a/tests/cli/test_tui_launcher.py
+++ b/tests/cli/test_tui_launcher.py
@@ -18,9 +18,9 @@ from nanobot.cli.tui_launcher import (
_initial_tui_chat_id,
_initial_tui_workspace,
_resolve_source_tui_command,
- resolve_tui_command,
_websocket_chat_id,
launch_tui,
+ resolve_tui_command,
)
from nanobot.config.schema import Config, ModelPresetConfig
@@ -228,9 +228,15 @@ def test_launcher_keeps_the_tui_alive_while_an_existing_gateway_recovers(
monkeypatch.setattr("nanobot.gateway.GatewayRuntime", FakeRuntime)
monkeypatch.setattr("nanobot.cli.tui_launcher.resolve_tui_command", lambda: ["nanobot-tui"])
+ # Stub only this launcher's child; lease cleanup still needs real subprocess
+ # calls to check live process state (including ps on macOS/Linux).
monkeypatch.setattr(
- "nanobot.cli.tui_launcher.subprocess.Popen",
- lambda *args, **kwargs: FakeProcess(),
+ tui_launcher,
+ "subprocess",
+ SimpleNamespace(
+ Popen=lambda *args, **kwargs: FakeProcess(),
+ TimeoutExpired=subprocess.TimeoutExpired,
+ ),
)
monkeypatch.setattr(
"nanobot.cli.tui_launcher._webui_endpoint_reachable",
diff --git a/tui/src/protocol.test.ts b/tui/src/protocol.test.ts
index 21f53a740..de3db5ae2 100644
--- a/tui/src/protocol.test.ts
+++ b/tui/src/protocol.test.ts
@@ -107,6 +107,20 @@ describe("Desktop attach-only protocol", () => {
expect(statuses.at(-1)).toBe("error")
})
})
+ for (const fields of [{}, { chat_id: "" }, { chat_id: 1, client_id: "test" }, { chat_id: "", client_id: null }]) {
+ test(`rejects an incomplete ready frame even with matching identity: ${JSON.stringify(fields)}`, async () => {
+ await fixture(async (client, socket, statuses, attempts) => {
+ socket.emit("message", { data: JSON.stringify({ event: "ready", terminal: { protocolVersion: 1, gatewayId }, ...fields }) })
+ expect(() => client.newChat()).toThrow("Desktop identity not verified")
+ await expect(client.updateRecovery("continue", "chat", "recovery")).rejects.toThrow("Desktop identity not verified")
+ await Bun.sleep(20)
+ expect(socket.sent).toHaveLength(0)
+ expect(socket.readyState).toBe(3)
+ expect(statuses.at(-1)).toBe("error")
+ expect(attempts()).toBe(1)
+ })
+ })
+ }
test("explicit client exit sends no lifecycle command", async () => {
await fixture(async (client, socket) => {
client.close()
diff --git a/tui/src/protocol.ts b/tui/src/protocol.ts
index 6eaccfe8a..40771f8b2 100644
--- a/tui/src/protocol.ts
+++ b/tui/src/protocol.ts
@@ -1335,7 +1335,9 @@ export class NanobotClient {
}
const response = decodeWebUIResponse(value)
if (!this.identityVerified) {
- if (!isRecord(value) || value.event !== "ready" || !isRecord(value.terminal)
+ // Matching metadata is insufficient: an invalid ready frame must not
+ // unlock mutations or cancel the bounded compatibility handshake.
+ if (!isRecord(value) || decodeInboundEvent(value)?.event !== "ready" || !isRecord(value.terminal)
|| value.terminal.protocolVersion !== 1 || value.terminal.gatewayId !== this.options.expectedGatewayId) {
this.desktopFailure()
return