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

+17 -5
View File
@@ -34,6 +34,7 @@ import {
type ConnectionStatusInfo,
type FileEditEvent,
type GatewayApiConnection,
type GatewayConnection,
type HistoryMessage,
type InboundEvent,
type MentionCandidate,
@@ -98,6 +99,8 @@ import {
import { configureOpenTuiEnvironment, createTuiHost, type TuiHost } from "./host"
interface AppOptions {
resolveConnection?: () => Promise<GatewayConnection>
desktopGatewayId?: string
wsUrl?: string
bootstrapUrl?: string
bootstrapSecret?: string
@@ -573,7 +576,7 @@ export class NanobotTui {
this.defaultModelPreset = options.modelPreset
this.modelName = options.model
this.modelPreset = options.modelPreset
this.apiReauthenticator = options.bootstrapUrl
this.apiReauthenticator = options.bootstrapUrl || options.resolveConnection
? (rejectedApiToken) => this.refreshApiConnection(rejectedApiToken)
: undefined
this.sessionModelPreset = options.chatId ? undefined : null
@@ -615,7 +618,13 @@ export class NanobotTui {
},
)
this.client = client || new NanobotClient({
...(options.bootstrapUrl
...(options.resolveConnection ? {
resolveConnection: options.resolveConnection,
onConnection: (connection: GatewayConnection) => this.useGatewayConnection(connection.apiUrl, connection.apiToken),
expectedGatewayId: options.desktopGatewayId,
reconnect: false,
targetEndpoint: "Nanobot Desktop",
} : options.bootstrapUrl
? {
resolveConnection: () => fetchGatewayConnection(
options.bootstrapUrl || "",
@@ -636,7 +645,7 @@ export class NanobotTui {
}
: { url: options.wsUrl }),
chatId: options.chatId,
initialWorkspaceScope: {
initialWorkspaceScope: options.desktopGatewayId ? undefined : {
project_path: options.workspace,
access_mode: options.access.toLocaleLowerCase().includes("full") ? "full" : "restricted",
},
@@ -1442,12 +1451,12 @@ export class NanobotTui {
return { apiUrl: this.options.apiUrl, apiToken: this.options.apiToken }
}
if (this.apiRefreshPromise) return this.apiRefreshPromise
const refresh = fetchGatewayConnection(
const refresh = (this.options.resolveConnection ? this.options.resolveConnection() : fetchGatewayConnection(
this.options.bootstrapUrl || "",
this.options.bootstrapSecret || "",
this.options.apiUrl,
`tui-${process.pid}`,
).then((connection) => {
)).then((connection) => {
this.updateGatewayApiConnection(connection.apiUrl, connection.apiToken)
return connection
})
@@ -1468,6 +1477,9 @@ export class NanobotTui {
// accurate user-facing state unless the protocol supplied connection diagnostics.
if (status === "error" && !info) return
this.connectionMessage = connectionStatusText(status, info)
if (this.options.desktopGatewayId && status === "error") {
this.connectionMessage = "Desktop disconnected or incompatible · exit and run nanobot to reconnect"
}
if (status === "connected") {
this.ready = false
this.renderConnectionMessage()
+62
View File
@@ -0,0 +1,62 @@
import { describe, expect, test } from "bun:test"
import { desktopConnectionSource } from "./desktop"
const instanceId = "b370a67d-1dbb-4b7c-9b22-c5f72ad8f5f0"
const gatewayId = "a277eeea-a422-4691-aac5-2c7348a95140"
const connection = {
protocolVersion: 1, gatewayId,
apiUrl: "http://127.0.0.1:8765", wsUrl: "ws://127.0.0.1:8765/ws",
wsToken: "test-ws-secret", apiToken: "test-api-secret",
}
function source(value: unknown = connection, exitCode = 0) {
// This test helper uses synthetic values only. Production passes no tokens in argv.
const script = `const input = JSON.parse(await Bun.stdin.text());
if (input.instanceId !== ${JSON.stringify(instanceId)} || input.gatewayId !== ${JSON.stringify(gatewayId)}) process.exit(9);
process.stdout.write(${JSON.stringify(JSON.stringify(value))}); process.exit(${exitCode});`
return desktopConnectionSource({
NANOBOT_TUI_DESKTOP_RESOLVER: JSON.stringify([process.execPath, "-e", script]),
NANOBOT_TUI_DESKTOP_TARGET: JSON.stringify({ instanceId, gatewayId }),
})!
}
describe("Desktop credential resolver", () => {
test("does nothing for a normal Python TUI", () => {
expect(desktopConnectionSource({})).toBeUndefined()
})
test("fails closed for incomplete launcher metadata", () => {
expect(() => desktopConnectionSource({ NANOBOT_TUI_DESKTOP_TARGET: "{}" })).toThrow("Invalid Desktop")
})
test("refreshes through a pipe and pins the websocket to the chosen gateway", async () => {
const resolver = source()
for (let refresh = 0; refresh < 2; refresh++) {
const result = await resolver.resolve()
const ws = new URL(result.wsUrl)
expect(ws.searchParams.get("terminal_instance")).toBe(gatewayId)
expect(ws.searchParams.get("terminal_protocol")).toBe("1")
expect(ws.searchParams.get("token")).toBe(connection.wsToken)
expect(result.apiToken).toBe(connection.apiToken)
expect(result.apiUrl).toBe(connection.apiUrl)
}
})
test("accepts equivalent explicit and implicit HTTP default ports", async () => {
const result = await source({ ...connection, apiUrl: "http://127.0.0.1:80", wsUrl: "ws://127.0.0.1/ws" }).resolve()
expect(result.apiUrl).toBe("http://127.0.0.1")
})
for (const patch of [
{ protocolVersion: 2 }, { gatewayId: instanceId }, { apiToken: "" },
{ wsToken: "unsafe\nvalue" }, { wsUrl: "ws://external.example:8765/ws" },
{ apiUrl: "http://localhost:8765" }, { wsUrl: "ws://127.0.0.1:8766/ws" },
{ wsUrl: "ws://127.0.0.1:8765/ws?token=unexpected" },
{ apiUrl: "http://user:password@127.0.0.1:8765" },
{ apiUrl: "http://127.0.0.1:0" }, { apiUrl: "http://127.0.0.1:8765/api" },
]) {
test(`rejects untrusted connection fields: ${Object.keys(patch)[0]} ${JSON.stringify(patch)}`, async () => {
await expect(source({ ...connection, ...patch }).resolve()).rejects.toThrow("Selected Desktop is unavailable")
})
}
test("does not expose malformed, oversized, or failed helper output", async () => {
for (const resolver of [source("test-secret"), source("x".repeat(9000)), source(connection, 3)]) {
await expect(resolver.resolve()).rejects.toThrow("Selected Desktop is unavailable")
}
})
})
+87
View File
@@ -0,0 +1,87 @@
import type { GatewayConnection } from "./protocol"
type Environment = Record<string, string | undefined>
export interface DesktopConnectionSource {
gatewayId: string
resolve: () => Promise<GatewayConnection>
}
export function desktopConnectionSource(environment: Environment = process.env): DesktopConnectionSource | undefined {
const rawCommand = environment.NANOBOT_TUI_DESKTOP_RESOLVER
const rawTarget = environment.NANOBOT_TUI_DESKTOP_TARGET
if (!rawCommand && !rawTarget) return undefined
try {
const command: unknown = JSON.parse(rawCommand || "")
const target: unknown = JSON.parse(rawTarget || "")
if (!Array.isArray(command) || command.length < 2
|| !command.every((part): part is string => typeof part === "string" && part.length > 0)
|| !record(target) || typeof target.instanceId !== "string"
|| !uuid(target.instanceId) || typeof target.gatewayId !== "string" || !uuid(target.gatewayId)) throw new Error()
const gatewayId = target.gatewayId
const request = JSON.stringify({ instanceId: target.instanceId, gatewayId }) + "\n"
if (request.length > 8192) throw new Error()
return { gatewayId, resolve: () => resolveDesktopConnection(command, request, gatewayId) }
} catch {
throw new Error("Invalid Desktop terminal launcher configuration")
}
}
async function resolveDesktopConnection(command: string[], request: string, gatewayId: string): Promise<GatewayConnection> {
const child = Bun.spawn(command, {
stdin: "pipe", stdout: "pipe", stderr: "ignore",
})
const timer = setTimeout(() => child.kill(), 8_000)
try {
child.stdin.write(request)
child.stdin.end()
const reader = child.stdout.getReader()
const chunks: Uint8Array[] = []
let length = 0
try {
for (;;) {
const next = await reader.read()
if (next.done) break
length += next.value.byteLength
if (length > 8192) throw new Error()
chunks.push(next.value)
}
} finally { reader.releaseLock() }
if (await child.exited !== 0) throw new Error()
const value: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8"))
if (!record(value) || value.protocolVersion !== 1 || value.gatewayId !== gatewayId) throw new Error()
const api = endpoint(value.apiUrl, "http:")
const ws = endpoint(value.wsUrl, "ws:")
if (api.host !== ws.host || api.pathname !== "/"
|| !token(value.wsToken) || !token(value.apiToken)) throw new Error()
ws.searchParams.set("token", value.wsToken)
ws.searchParams.set("client_id", `tui-${process.pid}`)
ws.searchParams.set("terminal_protocol", "1")
ws.searchParams.set("terminal_instance", gatewayId)
return { wsUrl: ws.toString(), apiUrl: api.origin, apiToken: value.apiToken }
} catch {
// The helper response contains secrets; never expose its raw errors/output.
throw new Error("Selected Desktop is unavailable or incompatible; reconnect from the terminal")
} finally {
clearTimeout(timer)
child.kill()
await child.exited
}
}
function record(value: unknown): value is Record<string, unknown> {
return typeof value === "object" && value !== null && !Array.isArray(value)
}
function uuid(value: string): boolean {
return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/iu.test(value)
}
function token(value: unknown): value is string {
return typeof value === "string" && /^[\x21-\x7e]{1,2048}$/u.test(value)
}
function endpoint(value: unknown, protocol: string): URL {
if (typeof value !== "string" || /[\s\\\x00-\x1f\x7f]/u.test(value)) throw new Error()
const url = new URL(value)
if (url.protocol !== protocol || !["127.0.0.1", "[::1]"].includes(url.hostname)
|| url.port === "0" || url.username || url.password || url.search || url.hash) throw new Error()
return url
}
+14 -7
View File
@@ -1,4 +1,11 @@
import { NanobotTui, sessionExitMessage, type AppOptions } from "./app"
import { desktopConnectionSource } from "./desktop"
if (process.argv.slice(2).join(" ") === "--desktop-protocol") {
process.stdout.write("1\n")
process.exit(0)
}
const desktop = desktopConnectionSource()
// Keep in sync with _TUI_DETACH_EXIT_CODE in nanobot/cli/tui_launcher.py.
const TUI_DETACH_EXIT_CODE = 90
@@ -15,11 +22,11 @@ const wsUrl = process.env.NANOBOT_TUI_WS_URL?.trim() || ""
const healthUrl = process.env.NANOBOT_TUI_HEALTH_URL?.trim() || ""
const gatewayStopCommand = process.env.NANOBOT_TUI_GATEWAY_STOP_COMMAND?.trim()
|| "nanobot gateway stop"
if (!bootstrapUrl && !wsUrl) {
if (!desktop && !bootstrapUrl && !wsUrl) {
throw new Error("NANOBOT_TUI_BOOTSTRAP_URL or NANOBOT_TUI_WS_URL is required")
}
const options: AppOptions = {
...(bootstrapUrl
...(desktop ? { resolveConnection: desktop.resolve, desktopGatewayId: desktop.gatewayId } : bootstrapUrl
? {
bootstrapUrl,
bootstrapSecret: process.env.NANOBOT_TUI_BOOTSTRAP_SECRET?.trim() || "",
@@ -38,11 +45,11 @@ const options: AppOptions = {
onDetach: (chatId) => {
process.exitCode = TUI_DETACH_EXIT_CODE
process.stdout.write("Detached; the agent continues in the background.\n")
if (chatId) process.stdout.write(sessionExitMessage(chatId))
process.stdout.write(`Stop it with: ${gatewayStopCommand}\n`)
if (!desktop && chatId) process.stdout.write(sessionExitMessage(chatId))
process.stdout.write(desktop ? "Desktop remains running. Reconnect with nanobot.\n" : `Stop it with: ${gatewayStopCommand}\n`)
},
onExit: (chatId) => {
process.stdout.write(sessionExitMessage(chatId))
process.stdout.write(desktop ? "Disconnected from Desktop; its backend remains running.\n" : sessionExitMessage(chatId))
},
}
@@ -62,11 +69,11 @@ for (const signal of ["SIGHUP", "SIGINT", "SIGTERM"] as const) {
process.once("exit", () => app?.stop())
process.once("uncaughtException", (error) => {
shutdown(1)
process.stderr.write(`${error instanceof Error ? error.stack || error.message : String(error)}\n`)
process.stderr.write(desktop ? "Desktop terminal connection failed. No backend was started.\n" : `${error instanceof Error ? error.stack || error.message : String(error)}\n`)
})
process.once("unhandledRejection", (error) => {
shutdown(1)
process.stderr.write(`${error instanceof Error ? error.stack || error.message : String(error)}\n`)
process.stderr.write(desktop ? "Desktop terminal connection failed. No backend was started.\n" : `${error instanceof Error ? error.stack || error.message : String(error)}\n`)
})
app = await NanobotTui.create(options)
+66
View File
@@ -50,6 +50,72 @@ async function waitUntil(predicate: () => boolean, timeout = 1_000): Promise<voi
if (!predicate()) throw new Error(`condition was not met within ${timeout}ms`)
}
describe("Desktop attach-only protocol", () => {
const gatewayId = "4d7d6bea-6d4b-4da1-975f-3d835c986c50"
async function fixture(run: (client: NanobotClient, socket: FakeSocket, statuses: ConnectionStatus[], attempts: () => number) => Promise<void>) {
const original = globalThis.WebSocket
let socket: FakeSocket | undefined
let attempts = 0
const statuses: ConnectionStatus[] = []
Object.defineProperty(globalThis, "WebSocket", {
configurable: true,
value: class extends FakeSocket { constructor() { super(); socket = this } },
})
const client = new NanobotClient({
expectedGatewayId: gatewayId, reconnect: false, reconnectDelayMs: 1,
resolveConnection: async () => {
attempts++
return { wsUrl: "ws://127.0.0.1:8765/ws", apiUrl: "http://127.0.0.1:8765", apiToken: "fixture" }
},
onEvent: () => {}, onStatus: (status) => statuses.push(status),
})
try {
client.connect()
await waitUntil(() => !!socket)
socket!.emit("open")
await run(client, socket!, statuses, () => attempts)
} finally {
client.close()
Object.defineProperty(globalThis, "WebSocket", { configurable: true, value: original })
}
}
for (const terminal of [undefined, { protocolVersion: 2, gatewayId }, { protocolVersion: 1, gatewayId: "other" }]) {
test(`rejects missing or changed handshake before any mutation: ${JSON.stringify(terminal)}`, async () => {
await fixture(async (client, socket, statuses, attempts) => {
expect(() => client.newChat()).toThrow("Desktop identity not verified")
await expect(client.updateRecovery("continue", "chat", "recovery")).rejects.toThrow("Desktop identity not verified")
socket.emit("message", { data: JSON.stringify({ event: "ready", chat_id: "", client_id: "test", terminal }) })
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("connects once, never replays a task and never reconnects after a disconnect", async () => {
await fixture(async (client, socket, statuses, attempts) => {
socket.emit("message", { data: JSON.stringify({ event: "ready", chat_id: "", client_id: "test", terminal: { protocolVersion: 1, gatewayId } }) })
expect(socket.sent.map((frame) => JSON.parse(frame).type)).toEqual(["new_chat"])
socket.emit("message", { data: JSON.stringify({ event: "attached", chat_id: "desktop-chat" }) })
client.send("one task")
socket.emit("close")
await Bun.sleep(20)
expect(attempts()).toBe(1)
expect(socket.sent.map((frame) => JSON.parse(frame).type)).toEqual(["new_chat", "message"])
expect(() => client.send("another task")).toThrow()
expect(statuses.at(-1)).toBe("error")
})
})
test("explicit client exit sends no lifecycle command", async () => {
await fixture(async (client, socket) => {
client.close()
expect(socket.sent).toHaveLength(0)
expect(socket.readyState).toBe(3)
})
})
})
describe("gateway protocol", () => {
test("bootstraps fresh websocket and API credentials", async () => {
const original = globalThis.fetch
+33
View File
@@ -192,6 +192,8 @@ type OutboundEvent =
}
export interface ClientOptions {
expectedGatewayId?: string
reconnect?: boolean
url?: string
resolveConnection?: () => Promise<GatewayConnection>
checkHealth?: () => Promise<GatewayHealthStatus>
@@ -1072,6 +1074,8 @@ export function sanitizeConnectionFailure(error: unknown): string {
}
export class NanobotClient {
private identityVerified = false
private handshakeTimer: ReturnType<typeof setTimeout> | null = null
private socket: WebSocket | null = null
private chatId = ""
private workspaceScope?: WorkspaceScopePayload
@@ -1115,6 +1119,7 @@ export class NanobotClient {
private async open(): Promise<void> {
if (this.socket || this.opening || this.closedByClient) return
this.opening = true
this.identityVerified = !this.options.expectedGatewayId
this.nextRetryAt = 0
this.connectionAttempt += 1
this.reportConnectionProgress()
@@ -1154,6 +1159,9 @@ export class NanobotClient {
}
let opened = false
this.socket = socket
if (this.options.expectedGatewayId) {
this.handshakeTimer = setTimeout(() => this.desktopFailure(), 8_000)
}
socket.addEventListener("open", () => {
if (this.socket !== socket) return
opened = true
@@ -1172,6 +1180,7 @@ export class NanobotClient {
})
socket.addEventListener("error", () => {
if (this.socket !== socket) return
if (this.options.reconnect === false) { this.desktopFailure(); return }
this.lastFailure = "connection failed"
this.reportRetryState()
})
@@ -1183,6 +1192,7 @@ export class NanobotClient {
this.options.onStatus("closed")
return
}
if (this.options.reconnect === false) { this.desktopFailure(); return }
if (opened) {
this.connectionAttempt = 0
this.reconnectAttempt = 0
@@ -1195,6 +1205,8 @@ export class NanobotClient {
}
close(): void {
if (this.handshakeTimer) clearTimeout(this.handshakeTimer)
this.handshakeTimer = null
this.closedByClient = true
if (this.reconnectTimer) clearTimeout(this.reconnectTimer)
this.reconnectTimer = null
@@ -1271,6 +1283,9 @@ export class NanobotClient {
payload: Record<string, unknown> = {},
timeoutMs = 20_000,
): Promise<T> {
if (this.options.expectedGatewayId && !this.identityVerified) {
return Promise.reject(new Error("Desktop identity not verified"))
}
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
return Promise.reject(new Error("gateway connection is not open"))
}
@@ -1314,10 +1329,21 @@ export class NanobotClient {
try {
value = JSON.parse(raw) as unknown
} catch {
if (!this.identityVerified && this.options.expectedGatewayId) { this.desktopFailure(); return }
this.options.onStatus("error", "gateway sent invalid JSON")
return
}
const response = decodeWebUIResponse(value)
if (!this.identityVerified) {
if (!isRecord(value) || value.event !== "ready" || !isRecord(value.terminal)
|| value.terminal.protocolVersion !== 1 || value.terminal.gatewayId !== this.options.expectedGatewayId) {
this.desktopFailure()
return
}
this.identityVerified = true
if (this.handshakeTimer) clearTimeout(this.handshakeTimer)
this.handshakeTimer = null
}
if (response === null) {
this.options.onStatus("error", "gateway sent an invalid event")
return
@@ -1371,6 +1397,7 @@ export class NanobotClient {
}
private async checkHealthAndScheduleReconnect(): Promise<void> {
if (this.options.reconnect === false) { this.desktopFailure(); return }
if (this.options.checkHealth) {
try {
this.healthStatus = await this.options.checkHealth()
@@ -1393,6 +1420,11 @@ export class NanobotClient {
}
}
private desktopFailure(): void {
this.close()
this.options.onStatus("error", "Desktop disconnected or is incompatible; reconnect from the terminal", this.connectionInfo())
}
private reportConnectionProgress(): void {
if (this.connectedOnce) {
this.options.onStatus("reconnecting", this.lastFailure || undefined, this.connectionInfo())
@@ -1429,6 +1461,7 @@ export class NanobotClient {
}
private write(event: OutboundEvent): void {
if (this.options.expectedGatewayId && !this.identityVerified) throw new Error("Desktop identity not verified")
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
throw new Error("gateway connection is not open")
}