refactor(tui): organize source by feature boundaries (#5975)
* refactor(tui): group source files by feature * refactor(tui): split app and gateway responsibilities
This commit is contained in:
1 parent
b7abbcd70b
commit
f18423800e
73 files changed
+6401
-6006
No files matched your search
@@ -0,0 +1,18 @@
|
||||
export async function copyWithSystemClipboard(text: string): Promise<void> {
|
||||
const commands = process.platform === "darwin"
|
||||
? [["pbcopy"]]
|
||||
: process.platform === "win32"
|
||||
? [["clip.exe"]]
|
||||
: [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"]]
|
||||
for (const command of commands) {
|
||||
try {
|
||||
const child = Bun.spawn(command, { stdin: "pipe", stdout: "ignore", stderr: "ignore" })
|
||||
child.stdin.write(text)
|
||||
child.stdin.end()
|
||||
if (await child.exited === 0) return
|
||||
} catch {
|
||||
// Try the next platform clipboard provider.
|
||||
}
|
||||
}
|
||||
throw new Error("no clipboard provider available")
|
||||
}
|
||||
@@ -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")
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { GatewayConnection } from "../client"
|
||||
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
|
||||
import {
|
||||
configureOpenTuiEnvironment,
|
||||
createTuiHost,
|
||||
} from "./host"
|
||||
|
||||
async function settle(): Promise<void> {
|
||||
await Bun.sleep(0)
|
||||
await Bun.sleep(0)
|
||||
}
|
||||
|
||||
describe("TUI host integration", () => {
|
||||
test("disables the explicit-width probe on Windows", () => {
|
||||
const environment: Record<string, string | undefined> = {}
|
||||
|
||||
configureOpenTuiEnvironment(environment, "win32")
|
||||
|
||||
expect(environment.OPENTUI_FORCE_EXPLICIT_WIDTH).toBe("false")
|
||||
})
|
||||
|
||||
test("preserves explicit probe choices and leaves other platforms unchanged", () => {
|
||||
const overridden = {
|
||||
OPENTUI_FORCE_EXPLICIT_WIDTH: "true",
|
||||
}
|
||||
const nonWindows: Record<string, string | undefined> = {}
|
||||
|
||||
configureOpenTuiEnvironment(overridden, "win32")
|
||||
configureOpenTuiEnvironment(nonWindows, "linux")
|
||||
|
||||
expect(overridden.OPENTUI_FORCE_EXPLICIT_WIDTH).toBe("true")
|
||||
expect(nonWindows.OPENTUI_FORCE_EXPLICIT_WIDTH).toBeUndefined()
|
||||
})
|
||||
|
||||
test("standalone terminals remain a no-op", async () => {
|
||||
const commands: string[][] = []
|
||||
const host = createTuiHost({}, async (command) => { commands.push([...command]) })
|
||||
|
||||
host.reportTitle("task")
|
||||
host.release()
|
||||
await settle()
|
||||
|
||||
expect(commands).toEqual([])
|
||||
})
|
||||
|
||||
test("requires both Herdr environment markers", async () => {
|
||||
const commands: string[][] = []
|
||||
const run = async (command: readonly string[]) => { commands.push([...command]) }
|
||||
|
||||
createTuiHost({ HERDR_ENV: "1" }, run).reportTitle("missing pane")
|
||||
createTuiHost({ HERDR_PANE_ID: "w1:p2" }, run).reportTitle("missing host")
|
||||
await settle()
|
||||
|
||||
expect(commands).toEqual([])
|
||||
})
|
||||
|
||||
test("reports only normalized pane title changes and clears the title on release", async () => {
|
||||
const commands: string[][] = []
|
||||
const host = createTuiHost(
|
||||
{ HERDR_ENV: "1", HERDR_PANE_ID: "w1:p2", HERDR_BIN_PATH: "/bin/herdr" },
|
||||
async (command) => { commands.push([...command]) },
|
||||
)
|
||||
|
||||
host.reportTitle(" Fix\nHerdr integration ")
|
||||
host.reportTitle("Fix Herdr integration")
|
||||
host.reportTitle("Review results")
|
||||
host.release()
|
||||
host.reportTitle("ignored after release")
|
||||
await settle()
|
||||
|
||||
expect(commands).toEqual([
|
||||
[
|
||||
"/bin/herdr", "pane", "report-metadata", "w1:p2",
|
||||
"--source", "nanobot:tui:metadata", "--seq", "1",
|
||||
"--title", "Fix Herdr integration",
|
||||
],
|
||||
[
|
||||
"/bin/herdr", "pane", "report-metadata", "w1:p2",
|
||||
"--source", "nanobot:tui:metadata", "--seq", "2",
|
||||
"--title", "Review results",
|
||||
],
|
||||
[
|
||||
"/bin/herdr", "pane", "report-metadata", "w1:p2",
|
||||
"--source", "nanobot:tui:metadata", "--seq", "3", "--clear-title",
|
||||
],
|
||||
])
|
||||
expect(commands.flat()).not.toContain("report-agent")
|
||||
expect(commands.flat()).not.toContain("report-agent-session")
|
||||
expect(commands.flat()).not.toContain("--token")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,89 @@
|
||||
export interface TuiHost {
|
||||
reportTitle(title: string): void
|
||||
release(): void
|
||||
}
|
||||
|
||||
type Environment = Record<string, string | undefined>
|
||||
type CommandRunner = (command: readonly string[]) => Promise<void>
|
||||
|
||||
const METADATA_SOURCE = "nanobot:tui:metadata"
|
||||
|
||||
export function configureOpenTuiEnvironment(
|
||||
environment: Environment = process.env,
|
||||
platform = process.platform,
|
||||
): void {
|
||||
if (platform !== "win32") return
|
||||
|
||||
// OpenTUI probes OSC 66 support on the main screen before its renderer is
|
||||
// active. Some Windows terminal hosts do not restore the cursor around that
|
||||
// probe, so shutdown resumes in terminal history instead of below the TUI.
|
||||
// Keep an explicit user choice, but use the safe default on Windows.
|
||||
environment.OPENTUI_FORCE_EXPLICIT_WIDTH ??= "false"
|
||||
}
|
||||
|
||||
class StandaloneHost implements TuiHost {
|
||||
reportTitle(): void {}
|
||||
release(): void {}
|
||||
}
|
||||
|
||||
class HerdrHost implements TuiHost {
|
||||
private sequence = 0
|
||||
private released = false
|
||||
private lastTitle = ""
|
||||
private queue: Promise<void> = Promise.resolve()
|
||||
|
||||
constructor(
|
||||
private readonly paneId: string,
|
||||
private readonly binary: string,
|
||||
private readonly run: CommandRunner,
|
||||
) {}
|
||||
|
||||
reportTitle(title: string): void {
|
||||
if (this.released) return
|
||||
const cleanTitle = normalize(title)
|
||||
if (cleanTitle === this.lastTitle) return
|
||||
this.lastTitle = cleanTitle
|
||||
const args = [
|
||||
"pane", "report-metadata", this.paneId,
|
||||
"--source", METADATA_SOURCE,
|
||||
"--seq", String(this.nextSequence()),
|
||||
cleanTitle ? "--title" : "--clear-title",
|
||||
]
|
||||
if (cleanTitle) args.push(cleanTitle)
|
||||
this.enqueue(args)
|
||||
}
|
||||
|
||||
release(): void {
|
||||
if (this.released) return
|
||||
this.reportTitle("")
|
||||
this.released = true
|
||||
}
|
||||
|
||||
private nextSequence(): number {
|
||||
this.sequence += 1
|
||||
return this.sequence
|
||||
}
|
||||
|
||||
private enqueue(args: string[]): void {
|
||||
const command = [this.binary, ...args]
|
||||
this.queue = this.queue.then(() => this.run(command)).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
function normalize(value: string, limit = 80): string {
|
||||
return value.replace(/[\u0000-\u001f\u007f]+/gu, " ").replace(/\s+/gu, " ").trim().slice(0, limit)
|
||||
}
|
||||
|
||||
async function runCommand(command: readonly string[]): Promise<void> {
|
||||
const child = Bun.spawn([...command], { stdout: "ignore", stderr: "ignore" })
|
||||
await child.exited
|
||||
}
|
||||
|
||||
export function createTuiHost(
|
||||
environment: Environment = process.env,
|
||||
run: CommandRunner = runCommand,
|
||||
): TuiHost {
|
||||
const paneId = environment.HERDR_PANE_ID?.trim() || ""
|
||||
if (environment.HERDR_ENV !== "1" || !paneId) return new StandaloneHost()
|
||||
return new HerdrHost(paneId, environment.HERDR_BIN_PATH?.trim() || "herdr", run)
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
export function optionArrowUp(platform: string = process.platform): string {
|
||||
return platform === "darwin" ? "⌥↑" : "alt+↑"
|
||||
}
|
||||
Reference in new issue
Block a user