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
refactor(tui): organize source by feature boundaries (#5975)
chengyongruf18423800ef1
diff --git a/tests/webui/test_notification_contract.py b/tests/webui/test_notification_contract.pyindex 46e72f9d7..589df0674 100644--- a/tests/webui/test_notification_contract.py+++ b/tests/webui/test_notification_contract.py@@ -33,7 +33,7 @@ def test_tui_source_archive_preserves_shared_module_import_path():spec.loader.exec_module(module)with tarfile.open(fileobj=io.BytesIO(module._source_archive(ROOT / "tui"))) as archive:names = set(archive.getnames())- assert "nanobot-tui-source/tui/src/protocol.ts" in names+ assert "nanobot-tui-source/tui/src/client/validation.ts" in namesassert "nanobot-tui-source/packages/client-events/notifications.ts" in namesassert "nanobot-tui-source/tui/bun.lock" in namesassert "nanobot-tui-source/LICENSE" in namesdiff --git a/tui/README.md b/tui/README.mdindex 30e7d0bb8..a319fd740 100644--- a/tui/README.md+++ b/tui/README.md@@ -9,6 +9,16 @@ bun run --cwd tui testbun run --cwd tui build```+## Source layout++Code under `src/` is grouped by responsibility: `app/` coordinates the retained UI, `client/`+owns gateway transport and API projections, `composer/` owns draft and queue state, `menus/` and+`views/` own interactive surfaces, `rendering/` owns transcript presentation, and `platform/`+contains host-specific integration. Unit and component tests stay beside the feature they cover;+cross-module behavior tests live with the owning `app/` or `client/` boundary. The production+build still starts from `src/index.ts`, so colocated `*.test.ts` files are not part of the compiled+executable.+`nanobot` (or the explicit `nanobot agent` form) launches this client, leases the shared local gateway or starts it on demand, and passes the local bootstrap endpoint through environment variables. The client paints before gateway readiness, retries bootstrap in the background, and obtains fresh WebSocket and REST credentials for each connection. Other terminals and the WebUI keep that gateway alive; the final interactive launcher to exit releases the on-demand process. `/detach` closes the TUI after promoting the gateway to persistent background mode, keeping any active agent turn running without clients; the restored terminal prints the exact stop command for that config and explicit workspace. `nanobot gateway --background` can start or promote it persistently before opening a client. Source checkouts automatically align dependencies with `bun.lock` before launch; released installs use a version-matched, checksum-verified archive that keeps the executable together with its licenses, notices, corresponding application source, source offer, and relinking instructions. Startup fails explicitly if the native client is unavailable. The legacy Python prompt is selected with `nanobot --classic` or `nanobot agent --classic`.The TUI uses OpenTUI's retained full-screen layout: the transcript reflows with the terminal while the composer stays fixed at the bottom. Mouse and keyboard scrolling operate inside the transcript, and leaving the TUI restores the previous terminal screen.diff --git a/tui/src/app.test.ts b/tui/src/app.test.tsdeleted file mode 100644index 3f4afb629..000000000--- a/tui/src/app.test.ts+++ /dev/null@@ -1,3726 +0,0 @@-import { afterEach, describe, expect, test } from "bun:test"-import {- BoxRenderable,- CliRenderEvents,- StyledText,- TextareaRenderable,- TextAttributes,- TextRenderable,-} from "@opentui/core"-import {- MockTreeSitterClient,- TestRecorder,- createTestRenderer,- setRendererCapabilities,- type TestRendererSetup,-} from "@opentui/core/testing"--import {- NanobotTui,- sessionExitMessage,- terminalModelFailureLine,- type AppOptions,-} from "./app"-import type {- MessageOptions,- RecoveryState,- SkillCandidate,- SlashCommand,- WorkspaceScopePayload,-} from "./protocol"-import type { TuiHost } from "./host"-import type { ClipboardImageReader } from "./clipboard-image"-import type { Transcript } from "./transcript"--const options: AppOptions = {- wsUrl: "ws://localhost.invalid/ws",- apiUrl: "",- apiToken: "",- model: "test/model",- modelPreset: "default",- workspace: "/tmp/nanobot-workspace",- version: "test",- access: "workspace access",- theme: "auto",-}--interface HiddenScrollBar {- visible: boolean- slider: { visible: boolean }- startArrow: { visible: boolean }- endArrow: { visible: boolean }-}--interface HiddenScrollBox {- verticalScrollBar: HiddenScrollBar- horizontalScrollBar: HiddenScrollBar-}--function occurrences(frame: string, value: string): number {- return frame.split(value).length - 1-}--test("formats a reusable session ID after exit", () => {- expect(sessionExitMessage("resume-chat")).toBe(- "Resume with: nanobot agent --session websocket:resume-chat\n",- )-})--test("formats actionable terminal model failures without inventing retries", () => {- expect(terminalModelFailureLine("billing")).toBe(- "Model provider quota is unavailable. "- + "Add credit or check billing for the provider account, then try again.",- )- expect(terminalModelFailureLine("unknown")).toBe(- "Model provider request failed. "- + "Check the provider configuration or service status, then try again.",- )-})-function contrastRatio(foreground: string, background: string): number {- const luminance = (color: string) => {- const channel = (offset: number) => {- const value = Number.parseInt(color.slice(offset, offset + 2), 16) / 255- return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4- }- return 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5)- }- const [lighter, darker] = [luminance(foreground), luminance(background)].sort((a, b) => b - a)- return ((lighter ?? 0) + 0.05) / ((darker ?? 0) + 0.05)-}--async function waitUntil(predicate: () => boolean, timeout = 1_000): Promise<void> {- const deadline = Date.now() + timeout- while (!predicate() && Date.now() < deadline) await Bun.sleep(5)- if (!predicate()) throw new Error(`condition was not met within ${timeout}ms`)-}--function client(- sent: string[] = [],- attached: string[] = [],- newChats: string[] = [],- sentOptions: MessageOptions[] = [],- forks: Array<{ source: string; before: number; title?: string }> = [],- scopes: WorkspaceScopePayload[] = [],-) {- return {- activeChatId: "chat",- connect() {},- close() {},- send(content: string, options: MessageOptions = {}) {- sent.push(content)- sentOptions.push(options)- return "turn"- },- attach(chatId: string) {- attached.push(chatId)- },- newChat(_scope?: WorkspaceScopePayload) {- newChats.push("new")- },- forkChat(source: string, before: number, title?: string) {- forks.push({ source, before, ...(title ? { title } : {}) })- },- setWorkspaceScope(scope: WorkspaceScopePayload) {- scopes.push(scope)- },- updateRecovery(- _action: "continue" | "dismiss",- _chatId: string,- recoveryId: string,- ): Promise<RecoveryState> {- return Promise.resolve({ status: "recovered" as const, recovery_id: recoveryId })- },- }-}--const mount = (setup: TestRendererSetup, sent: string[] = []) => NanobotTui.mount(- setup.renderer,- options,- client(sent),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),-)--describe("NanobotTui layout", () => {- let setup: TestRendererSetup | undefined-- afterEach(() => {- if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()- setup = undefined- })-- const createRenderer = (options: Parameters<typeof createTestRenderer>[0]) => createTestRenderer(options)-- test("keeps short transcripts and the composer anchored at the top", async () => {- setup = await createRenderer({- width: 100,- height: 18,- screenMode: "alternate-screen",- consoleMode: "disabled",- })- const app = mount(setup)- const ui = app as unknown as {- transcript: Transcript- title: BoxRenderable- status: TextRenderable- }- const positions = () => ({- transcriptHeight: ui.transcript.root.height,- titleY: ui.title.y,- statusY: ui.status.y,- })-- let anchoredPositions: ReturnType<typeof positions> | undefined- for (const height of [18, 30, 36]) {- setup.resize(100, height)- await setup.renderOnce()- expect(ui.title.y).toBe(ui.transcript.root.y + ui.transcript.root.height)- expect(ui.status.y + ui.status.height).toBeLessThan(setup.renderer.height)- if (!anchoredPositions) anchoredPositions = positions()- else expect(positions()).toEqual(anchoredPositions)- }-- ui.transcript.user("A short prompt")- await setup.renderOnce()- const promptPositions = positions()- expect(promptPositions.titleY).toBeGreaterThan(anchoredPositions?.titleY || 0)-- setup.resize(100, 40)- await setup.renderOnce()- expect(positions()).toEqual(promptPositions)- })-- test("reflows a single retained layout across terminal resizes", async () => {- setup = await createRenderer({- width: 100,- height: 30,- screenMode: "alternate-screen",- consoleMode: "disabled",- })- const app = mount(setup)-- for (const [width, height] of [[100, 30], [56, 18], [118, 36]] as const) {- setup.resize(width, height)- await setup.renderOnce()- const frame = setup.captureCharFrame()-- expect(setup.renderer.width).toBe(width)- expect(setup.renderer.height).toBe(height)- expect(occurrences(frame, "Ask nanobot anything")).toBe(1)- expect(occurrences(frame, "Ready")).toBe(0)- expect(occurrences(frame, "Getting ready…")).toBe(1)- expect(occurrences(frame, "default ▾")).toBe(1)- }-- app.accept({ event: "attached", chat_id: "chat" })- app.accept({ event: "delta", chat_id: "chat", text: "First **answer**." })- app.accept({ event: "stream_end", chat_id: "chat", resuming: true })- app.accept({- event: "message",- chat_id: "chat",- text: "read_file(config.json)",- kind: "tool_hint",- tool_events: [- { phase: "start", call_id: "read-1", name: "read_file", arguments: { path: "config.json" } },- { phase: "end", call_id: "read-1", name: "read_file" },- ],- })- app.accept({ event: "reasoning_delta", chat_id: "chat", text: "private chain of thought" })- app.accept({ event: "reasoning_end", chat_id: "chat" })- app.accept({ event: "delta", chat_id: "chat", text: "Second answer." })- app.accept({ event: "stream_end", chat_id: "chat" })- app.accept({ event: "turn_end", chat_id: "chat", latency_ms: 1200 })- await setup.flush()- const frame = setup.captureCharFrame()-- expect(occurrences(frame, "First **answer**.")).toBe(1)- expect(occurrences(frame, "Second answer.")).toBe(1)- expect(frame).toContain("✓ Read config.json")- expect(frame).not.toContain("› Read")- expect(frame).not.toContain("private chain of thought")- expect(frame).toContain("Ready · 1.2s")- })-- test("keeps model and access details in the composer controls only", async () => {- setup = await createRenderer({ width: 100, height: 24, screenMode: "alternate-screen" })- NanobotTui.mount(- setup.renderer,- {- ...options,- model: "provider/resolved-model",- modelPreset: "selected-preset",- access: "full access",- },- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- await setup.renderOnce()-- const frame = setup.captureCharFrame()- expect(frame).not.toContain("provider/resolved-model")- expect(frame).toContain("selected-preset ▾")- expect(occurrences(frame, "full access")).toBe(1)- expect(frame).toContain(options.workspace)- })-- test("uses the available transcript width before wrapping the workspace", async () => {- setup = await createRenderer({ width: 100, height: 24, screenMode: "alternate-screen" })- const workspace = String.raw`D:\Documents\GitHub\nanobot\.worktrees\responsive-header-fixture`- NanobotTui.mount(- setup.renderer,- { ...options, workspace },- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- await setup.renderOnce()-- const frame = setup.captureCharFrame()- const headerWidth = () => {- const border = setup?.captureCharFrame().split("\n").find((line) => line.includes("╭"))- if (!border) throw new Error("header border was not rendered")- return border.trim().length- }-- expect(frame).toContain(workspace)- expect(headerWidth()).toBe(setup.renderer.width - 4)-- setup.resize(120, 24)- await setup.renderOnce()- expect(headerWidth()).toBe(setup.renderer.width - 4)- })-- test("waits for an IME commit before reading the submitted text", async () => {- const sent: string[] = []- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = mount(setup, sent)- app.accept({ event: "attached", chat_id: "chat" })- await Bun.sleep(1)- const composer = (app as unknown as { composer: TextareaRenderable }).composer-- composer.setText("你")- composer.submit()- setTimeout(() => composer.setText("你好"), 0)- await waitUntil(() => sent.length > 0)-- expect(sent).toEqual(["你好"])- })-- test("keeps input typed immediately after Enter in the next draft", async () => {- const sent: string[] = []- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = mount(setup, sent)- app.accept({ event: "attached", chat_id: "chat" })- await Bun.sleep(1)- const composer = (app as unknown as { composer: TextareaRenderable }).composer-- composer.setText("first")- setup.mockInput.pressEnter()- for (const key of "next") setup.mockInput.pressKey(key)- await waitUntil(() => sent.length > 0)-- expect(sent).toEqual(["first"])- expect(composer.plainText).toBe("next")- })-- test("inserts newlines with Shift+Enter and the universal Ctrl+J fallback", async () => {- const sent: string[] = []- setup = await createRenderer({- width: 72,- height: 20,- screenMode: "alternate-screen",- kittyKeyboard: true,- })- const app = mount(setup, sent)- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- const ui = app as unknown as {- composer: TextareaRenderable- composerFrame: { height: number }- }-- await setup.mockInput.typeText("first")- setup.mockInput.pressEnter({ shift: true })- await setup.mockInput.typeText("second")- setup.mockInput.pressKey("j", { ctrl: true })- await setup.mockInput.typeText("third")- await setup.flush()-- expect(ui.composer.plainText).toBe("first\nsecond\nthird")- expect(sent).toEqual([])- expect(ui.composerFrame.height).toBeGreaterThanOrEqual(3)- })-- test("clears the placeholder on the first typed character", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = mount(setup)- const composer = (app as unknown as { composer: TextareaRenderable }).composer- await setup.renderOnce()- expect(setup.captureCharFrame()).toContain("Ask nanobot anything")-- setup.mockInput.typeText("bu")- await setup.flush()- const frame = setup.captureCharFrame()-- expect(composer.plainText).toBe("bu")- expect(composer.placeholder).toBeNull()- expect(frame).toContain("bu")- expect(frame).not.toContain("Ask nanobot anything")- expect(frame).not.toContain("buAsk nanobot anything")-- setup.mockInput.pressBackspace()- setup.mockInput.pressBackspace()- await setup.flush()- expect(composer.placeholder).toBe("Ask nanobot anything")- expect(setup.captureCharFrame()).toContain("Ask nanobot anything")- })-- test("compacts large pastes in the composer without changing the sent text", async () => {- const sent: string[] = []- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = mount(setup, sent)- app.accept({ event: "attached", chat_id: "chat" })- await Bun.sleep(1)- const ui = app as unknown as {- composer: TextareaRenderable- status: { plainText: string }- }- const pasted = Array.from({ length: 12 }, (_, index) => `line ${index + 1}`).join("\n")-- await setup.mockInput.pasteBracketedText(pasted)- await setup.flush()- expect(ui.composer.plainText).toBe("[Pasted 12 lines] ")- expect(ui.status.plainText).toContain("Pasted 12 lines")-- ui.composer.submit()- await waitUntil(() => sent.length === 1)- expect(sent).toEqual([pasted])- expect(ui.composer.plainText).toBe("")- })-- test("pastes clipboard images into removable placeholders and sends their data", async () => {- const sent: string[] = []- const sentOptions: MessageOptions[] = []- let disposed = false- const clipboard: ClipboardImageReader = {- read: async () => ({- mimeType: "image/png",- dataUrl: "data:image/png;base64,AAEC/w==",- }),- dispose: async () => { disposed = true },- }- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const transport = client(sent, [], [], sentOptions)- const recordSend = transport.send- transport.send = (content, messageOptions) => {- recordSend(content, messageOptions)- return `image-turn-${sent.length}`- }- const app = NanobotTui.mount(- setup.renderer,- options,- transport,- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- undefined,- clipboard,- )- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- const ui = app as unknown as {- composer: TextareaRenderable- draft: { imageCount: number }- promptHistory: string[]- status: { plainText: string }- transcript: {- userMessages: Set<{ renderable: TextRenderable }>- }- }-- setup.mockInput.pressKey("v", { ctrl: true })- await waitUntil(() => ui.composer.plainText === "[Image #1] ")- expect(ui.status.plainText).toContain("Pasted Image #1")- const placeholderStyle = ui.composer.syntaxStyle?.getStyle("image.placeholder")- expect(placeholderStyle?.bold).toBeTrue()- expect(placeholderStyle?.fg?.intent).toBe("default")- const placeholderStyleId = ui.composer.syntaxStyle?.getStyleId("image.placeholder")- if (placeholderStyleId === null || placeholderStyleId === undefined) {- throw new Error("image placeholder style was not registered")- }- expect(ui.composer.getLineHighlights(0)).toEqual([{- start: 0,- end: 10,- styleId: placeholderStyleId,- priority: 100,- hlRef: 0,- }])- ui.composer.setText("")- await waitUntil(() => ui.draft.imageCount === 0)- expect(ui.composer.getLineHighlights(0)).toEqual([])-- setup.mockInput.pressKey("v", { ctrl: true })- await waitUntil(() => ui.composer.plainText === "[Image #1] ")- await setup.mockInput.typeText("[Image #1]")- ui.composer.submit()- await waitUntil(() => ui.status.plainText.includes("Duplicate image placeholder"))- expect(sent).toEqual([])- ui.composer.setText("[Image #1]")- ui.composer.submit()- await waitUntil(() => sent.length === 1)- expect(sent).toEqual([""])- expect(ui.promptHistory).toEqual([])- expect(sentOptions[0]?.media).toEqual([{- data_url: "data:image/png;base64,AAEC/w==",- name: "clipboard-image-1.png",- }])- expect(sentOptions[0]).not.toHaveProperty("displayContent")- await setup.flush()- const frame = setup.captureCharFrame()- expect(frame).toContain("[Image #1]")- expect(frame).not.toContain("clipboard-image-1.png")- const userContent = [...ui.transcript.userMessages].at(-1)?.renderable.content- expect(userContent).toBeInstanceOf(StyledText)- const imageChunk = (userContent as StyledText).chunks.find(({ text }) => text === "[Image #1]")- expect(imageChunk?.attributes).toBe(TextAttributes.BOLD)- expect(imageChunk?.fg?.intent).toBe("default")-- await setup.mockInput.typeText("这是什么? ")- setup.mockInput.pressKey("v", { ctrl: true })- await waitUntil(() => ui.composer.plainText === "这是什么? [Image #1] ")- setup.mockInput.pressTab()- expect(ui.status.plainText).toContain("Images cannot be queued")- expect(ui.composer.plainText).toBe("这是什么? [Image #1] ")- ui.composer.submit()- await waitUntil(() => sent.length === 2)- expect(sent[1]).toBe("这是什么?")- expect(sentOptions[1]?.media).toHaveLength(1)- expect(sentOptions[1]).not.toHaveProperty("displayContent")- await setup.flush()- expect(setup.captureCharFrame()).toContain("这是什么? [Image #1]")-- setup.renderer.destroy()- expect(disposed).toBeTrue()- })-- test("keeps image placeholders atomic for cursor movement and deletion", async () => {- const clipboard: ClipboardImageReader = {- read: async () => ({- mimeType: "image/png",- dataUrl: "data:image/png;base64,AAEC/w==",- }),- dispose: async () => undefined,- }- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = NanobotTui.mount(- setup.renderer,- options,- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- undefined,- clipboard,- )- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- const ui = app as unknown as {- composer: TextareaRenderable- draft: { imageCount: number }- status: { plainText: string }- }-- setup.mockInput.pressKey("v", { ctrl: true })- await waitUntil(() => ui.composer.plainText === "[Image #1] ")- await setup.flush()- await setup.mockMouse.click(ui.composer.x + 5, ui.composer.y)- expect(ui.composer.cursorOffset > 0 && ui.composer.cursorOffset < 10).toBeFalse()- ui.composer.cursorOffset = 0- setup.mockInput.pressArrow("right")- await waitUntil(() => ui.composer.cursorOffset === 10)- setup.mockInput.pressArrow("left")- await waitUntil(() => ui.composer.cursorOffset === 0)-- setup.mockInput.pressArrow("right", { shift: true })- await waitUntil(() => ui.composer.cursorOffset === 10)- await setup.mockInput.typeText("replacement")- await waitUntil(() => ui.draft.imageCount === 0)- expect(ui.composer.plainText).toContain("replacement")- expect(ui.composer.plainText).not.toContain("Image #1")-- ui.composer.setText("")- setup.mockInput.pressKey("v", { ctrl: true })- await waitUntil(() => ui.composer.plainText === "[Image #1] ")- ui.composer.cursorOffset = 10- setup.mockInput.pressArrow("left", { shift: true })- await waitUntil(() => ui.composer.cursorOffset === 0)- await setup.mockInput.typeText("replacement")- await waitUntil(() => ui.draft.imageCount === 0)- expect(ui.composer.plainText).toContain("replacement")- expect(ui.composer.plainText).not.toContain("Image #1")-- ui.composer.setText("")- setup.mockInput.pressKey("v", { ctrl: true })- await waitUntil(() => ui.composer.plainText === "[Image #1] ")- ui.composer.cursorOffset = 0- setup.mockInput.pressKey("DELETE")- await waitUntil(() => ui.draft.imageCount === 0)- expect(ui.composer.plainText.trim()).toBe("")- expect(ui.status.plainText).toContain("Removed Image #1")-- ui.composer.setText("")- setup.mockInput.pressKey("v", { ctrl: true })- await waitUntil(() => ui.composer.plainText === "[Image #1] ")- ui.composer.cursorOffset = 10- setup.mockInput.pressBackspace()- await waitUntil(() => ui.draft.imageCount === 0)- expect(ui.composer.plainText.trim()).toBe("")-- ui.composer.setText("")- setup.mockInput.pressKey("v", { ctrl: true })- await waitUntil(() => ui.composer.plainText === "[Image #1] ")- ui.composer.setText("Image #1] ")- await waitUntil(() => ui.draft.imageCount === 0)- expect(ui.composer.plainText.trim()).toBe("")- })-- test("keeps clipboard failures visible while an agent turn is active", async () => {- const sent: string[] = []- const clipboard: ClipboardImageReader = {- read: async () => { throw new Error("No image in clipboard") },- dispose: async () => undefined,- }- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = NanobotTui.mount(- setup.renderer,- options,- client(sent),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- undefined,- clipboard,- )- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- const composer = (app as unknown as { composer: TextareaRenderable }).composer- composer.setText("start")- composer.submit()- await waitUntil(() => sent.length === 1)-- setup.mockInput.pressKey("v", { ctrl: true })- await waitUntil(() => setup?.captureCharFrame().includes("No image in clipboard") === true)- })-- test("keeps image placeholders out of command arguments", async () => {- const sent: string[] = []- const clipboard: ClipboardImageReader = {- read: async () => ({- mimeType: "image/png",- dataUrl: "data:image/png;base64,AAEC/w==",- }),- dispose: async () => undefined,- }- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = NanobotTui.mount(- setup.renderer,- options,- client(sent),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- undefined,- clipboard,- )- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- const ui = app as unknown as {- composer: TextareaRenderable- status: { plainText: string }- commandMenu: { setCommands(commands: SlashCommand[]): void }- }- ui.commandMenu.setCommands([{- command: "/model",- title: "Model",- description: "Show or switch model presets",- argHint: "[preset]",- lifecycle: "side_channel",- acceptsArgs: true,- }])-- await setup.mockInput.typeText("/model ")- setup.mockInput.pressKey("v", { ctrl: true })- await waitUntil(() => ui.composer.plainText === "/model [Image #1] ")- ui.composer.submit()- await waitUntil(() => ui.status.plainText.includes("Images cannot be used with commands"))-- expect(sent).toEqual([])- expect(ui.composer.plainText).toBe("/model [Image #1] ")- })-- test("ignores a clipboard result that finishes after the renderer is destroyed", async () => {- let resolveRead: ((image: {- mimeType: "image/png"- dataUrl: string- }) => void) | undefined- let disposed = false- const clipboard: ClipboardImageReader = {- read: () => new Promise((resolve) => { resolveRead = resolve }),- dispose: async () => { disposed = true },- }- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = NanobotTui.mount(- setup.renderer,- options,- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- undefined,- clipboard,- )- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)-- setup.mockInput.pressKey("v", { ctrl: true })- await waitUntil(() => resolveRead !== undefined)- setup.renderer.destroy()- resolveRead?.({ mimeType: "image/png", dataUrl: "data:image/png;base64,AAAA" })- await Bun.sleep(10)- expect(disposed).toBeTrue()- })-- test("steers with Enter, queues with Tab, and restores queued text with Alt+Up", async () => {- const sent: string[] = []- const sentOptions: MessageOptions[] = []- setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })- const app = NanobotTui.mount(- setup.renderer,- options,- client(sent, [], [], sentOptions),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- app.accept({ event: "attached", chat_id: "chat" })- const ui = app as unknown as {- ready: boolean- composer: TextareaRenderable- mentionCandidates: Array<Record<string, unknown>>- queuePreview: { root: { visible: boolean } }- status: { plainText: string }- }- await waitUntil(() => ui.ready)- ui.mentionCandidates = [{- kind: "cli",- name: "github",- displayName: "GitHub",- description: "CLI",- }]-- ui.composer.setText("first")- ui.composer.submit()- await waitUntil(() => sent.length === 1)- expect(ui.composer.placeholder).toBe("Enter send now · Tab send next")-- ui.composer.setText("one more detail")- await setup.flush()- expect(ui.composer.placeholder).toBeNull()-- ui.composer.setText("ask @github next")- ui.composer.submit()- await waitUntil(() => sent.length === 2)- expect(ui.status.plainText).not.toContain("Steering")- expect(ui.composer.placeholder).toBe("Enter send now · Tab send next")- expect(sentOptions[1]).toEqual({- cliApps: [{ name: "github" }],- mcpPresets: [],- sessionMentions: [],- })-- ui.composer.setText("after this turn")- setup.mockInput.pressTab()- await waitUntil(() => ui.composer.plainText === "")- expect(sent).toHaveLength(2)- expect(ui.queuePreview.root.visible).toBeTrue()-- setup.mockInput.pressArrow("up", { meta: true })- expect(ui.composer.plainText).toBe("after this turn")- expect(ui.queuePreview.root.visible).toBeFalse()- setup.mockInput.pressTab()- await waitUntil(() => ui.composer.plainText === "")-- app.accept({- event: "error",- chat_id: "chat",- turn_id: "failed-steering",- reason: "steering rejected",- })- expect((app as unknown as { activeTurn: boolean }).activeTurn).toBeTrue()-- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => ui.ready)- app.accept({ event: "goal_status", chat_id: "chat", status: "running", turn_id: "turn" })- app.accept({ event: "turn_end", chat_id: "chat", turn_id: "turn" })- await waitUntil(() => sent.length === 3)- expect(sent[2]).toBe("after this turn")- expect(ui.queuePreview.root.visible).toBeFalse()- app.accept({ event: "goal_status", chat_id: "chat", status: "idle", turn_id: "prior" })- expect((app as unknown as { activeTurn: boolean }).activeTurn).toBeTrue()- })-- test("projects user turns from another terminal without duplicating replayed history", async () => {- setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)-- const first = {- event: "user_message" as const,- chat_id: "chat",- text: "hello from terminal A",- turn_id: "remote-turn",- active_turn_id: "remote-turn",- starts_turn: true,- started_at: 1_700_000_000,- media_urls: [{- kind: "file" as const,- url: "/api/media/sig/report",- name: "report.pdf",- }],- }- app.accept(first)- app.accept(first)- app.accept({- event: "user_message",- chat_id: "chat",- text: "one more remote detail",- turn_id: "remote-steer",- active_turn_id: "remote-turn",- starts_turn: false,- media_urls: [{- kind: "image",- url: "/api/media/sig/image",- name: "clipboard-image-2.png",- }],- })- await setup.flush()-- const state = app as unknown as { activeTurn: boolean; activeTurnId: string | null }- const frame = setup.captureCharFrame()- expect(occurrences(frame, "hello from terminal A")).toBe(1)- expect(occurrences(frame, "Attachments: report.pdf")).toBe(1)- expect(occurrences(frame, "one more remote detail")).toBe(1)- expect(occurrences(frame, "[Image #2]")).toBe(1)- expect(frame).toContain("one more remote detail [Image #2]")- expect(frame).not.toContain("clipboard-image-2.png")- expect(state.activeTurn).toBeTrue()- expect(state.activeTurnId).toBe("remote-turn")-- app.accept({ event: "turn_end", chat_id: "chat", turn_id: "remote-turn" })- expect(state.activeTurn).toBeFalse()- })-- test("reconciles simultaneous submits to the gateway-owned turn", async () => {- const sent: string[] = []- setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })- const app = mount(setup, sent)- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)-- const ui = app as unknown as {- composer: TextareaRenderable- activeTurn: boolean- activeTurnId: string | null- }- ui.composer.setText("submitted from terminal B")- ui.composer.submit()- await waitUntil(() => sent.length === 1)- expect(ui.activeTurnId).toBe("turn")-- app.accept({- event: "message_accepted",- chat_id: "chat",- turn_id: "turn",- active_turn_id: "terminal-a-turn",- starts_turn: false,- started_at: 1_700_000_000,- })-- expect(ui.activeTurn).toBeTrue()- expect(ui.activeTurnId).toBe("terminal-a-turn")- })-- test("recalls submitted prompts without stealing multiline cursor movement", async () => {- const sent: string[] = []- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = mount(setup, sent)- app.accept({ event: "attached", chat_id: "chat" })- await Bun.sleep(1)- const composer = (app as unknown as { composer: TextareaRenderable }).composer- for (const [index, value] of ["first prompt", "second prompt"].entries()) {- composer.setText(value)- composer.submit()- await waitUntil(() => sent.length === index + 1)- app.accept({ event: "turn_end", chat_id: "chat" })- }-- setup.mockInput.pressArrow("up")- expect(composer.plainText).toBe("second prompt")- setup.mockInput.pressArrow("up")- expect(composer.plainText).toBe("first prompt")- setup.mockInput.pressArrow("down")- expect(composer.plainText).toBe("first prompt")- setup.mockInput.pressArrow("down")- expect(composer.plainText).toBe("second prompt")- setup.mockInput.pressArrow("down")- expect(composer.plainText).toBe("")-- setup.resize(36, 20)- const wrapped = "这是一段会在狭窄输入框中自动换行而不是显式换行的中文内容"- composer.setText(wrapped)- composer.cursorOffset = wrapped.length- await setup.renderOnce()- expect(composer.virtualLineCount).toBeGreaterThan(1)-- setup.mockInput.pressArrow("up")- expect(composer.plainText).toBe(wrapped)- })-- test("discovers and completes gateway slash commands without sending them", async () => {- setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })- const sent: string[] = []- const app = mount(setup, sent)- const ui = app as unknown as {- composer: TextareaRenderable- commandMenu: {- visible: boolean- setCommands(commands: SlashCommand[]): void- }- }- ui.commandMenu.setCommands([{- command: "/history",- title: "History",- description: "Show recent messages",- argHint: "[n]",- lifecycle: "side_channel",- acceptsArgs: true,- }])-- await setup.mockInput.typeText("/h")- expect(ui.commandMenu.visible).toBe(true)- setup.mockInput.pressTab()-- expect(ui.composer.plainText).toBe("/history ")- expect(ui.commandMenu.visible).toBe(false)- expect(sent).toEqual([])- })-- test("completes available skills with arrows, Enter, Tab, and Escape", async () => {- setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })- const sent: string[] = []- const app = mount(setup, sent)- const ui = app as unknown as {- ready: boolean- composer: TextareaRenderable- skillCandidates: SkillCandidate[]- skillMenu: { visible: boolean }- }- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => ui.ready)- ui.skillCandidates = [- { name: "simplify", description: "Simplify code", source: "workspace" },- { name: "verify", description: "Verify public behavior", source: "builtin" },- ]-- await setup.mockInput.typeText("$")- expect(ui.skillMenu.visible).toBe(true)- setup.mockInput.pressArrow("down")- setup.mockInput.pressEnter()- await waitUntil(() => ui.composer.plainText === "$verify ")- expect(ui.skillMenu.visible).toBe(false)- expect(sent).toEqual([])-- ui.composer.setText("")- await setup.mockInput.typeText("please $sim")- expect(ui.skillMenu.visible).toBe(true)- setup.mockInput.pressTab()- expect(ui.composer.plainText).toBe("please $simplify ")- expect(ui.skillMenu.visible).toBe(false)-- ui.composer.setText("")- await setup.mockInput.typeText("$")- expect(ui.skillMenu.visible).toBe(true)- setup.mockInput.pressEscape()- await waitUntil(() => !ui.skillMenu.visible)- expect(ui.skillMenu.visible).toBe(false)- expect(ui.composer.plainText).toBe("$")-- ui.composer.setText("")- await setup.mockInput.typeText("请用 $ver")- expect(ui.skillMenu.visible).toBe(true)- setup.mockInput.pressTab()- expect(ui.composer.plainText).toBe("请用 $verify ")- await setup.mockInput.typeText("now")- expect(ui.composer.plainText).toBe("请用 $verify now")-- ui.composer.setText("use $verify later")- ui.composer.cursorOffset = 8- await waitUntil(() => ui.skillMenu.visible)- ui.composer.cursorOffset = ui.composer.plainText.length- await waitUntil(() => !ui.skillMenu.visible)-- ui.composer.setText("")- await setup.mockInput.typeText("$missing")- expect(ui.skillMenu.visible).toBe(true)- ui.composer.submit()- await waitUntil(() => sent.length === 1)- expect(sent).toEqual(["$missing"])- expect(ui.skillMenu.visible).toBe(false)- })-- test("does not queue unmatched skill text when Tab dismisses completion", async () => {- setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })- const sent: string[] = []- const app = mount(setup, sent)- const ui = app as unknown as {- ready: boolean- composer: TextareaRenderable- skillCandidates: SkillCandidate[]- skillMenu: { visible: boolean }- queuePreview: { root: { visible: boolean } }- }- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => ui.ready)- ui.skillCandidates = [{- name: "verify",- description: "Verify public behavior",- source: "builtin",- }]-- ui.composer.setText("start an active turn")- ui.composer.submit()- await waitUntil(() => sent.length === 1)-- await setup.mockInput.typeText("$missing")- expect(ui.skillMenu.visible).toBe(true)- setup.mockInput.pressTab()-- expect(ui.composer.plainText).toBe("$missing")- expect(ui.skillMenu.visible).toBe(false)- expect(ui.queuePreview.root.visible).toBe(false)-- app.accept({ event: "turn_end", chat_id: "chat", turn_id: "turn" })- await Bun.sleep(1)- expect(sent).toEqual(["start an active turn"])- })-- test("runs bang commands through the gateway without steering the agent", async () => {- setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })- const sent: string[] = []- const sentOptions: MessageOptions[] = []- const app = NanobotTui.mount(- setup.renderer,- options,- client(sent, [], [], sentOptions),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- app.accept({ event: "attached", chat_id: "chat" })- const ui = app as unknown as { ready: boolean; composer: TextareaRenderable; activeTurn: boolean }- await waitUntil(() => ui.ready)-- app.accept({ event: "goal_status", chat_id: "chat", status: "running" })- ui.composer.setText("!pwd")- ui.composer.submit()-- await waitUntil(() => sent.length === 1)- expect(sent).toEqual(["!pwd"])- expect(sentOptions).toEqual([{ userShell: true }])- expect(ui.activeTurn).toBe(true)-- app.accept({ event: "message", chat_id: "chat", text: "/tmp/project", turn_id: "turn" })- await setup.flush()- expect(setup.captureCharFrame()).toContain("/tmp/project")- expect(ui.activeTurn).toBe(true)- })-- test("switches and creates gateway chats without replacing core slash commands", async () => {- setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })- const original = globalThis.fetch- globalThis.fetch = (() => Promise.resolve(new Response(JSON.stringify({- sessions: [- {- key: "websocket:chat",- title: "Current chat",- preview: "Current work",- updated_at: "2026-08-13T10:00:00Z",- },- {- key: "websocket:other",- title: "Release checklist",- preview: "Prepare stable release",- updated_at: "2026-08-12T10:00:00Z",- model_preset: "Deep Research",- },- ],- })))) as unknown as typeof fetch- const attached: string[] = []- const newChats: string[] = []- const transport = client([], attached, newChats)- const app = NanobotTui.mount(- setup.renderer,- { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },- transport,- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- app.accept({ event: "attached", chat_id: "chat" })- await Bun.sleep(1)- const ui = app as unknown as {- composer: TextareaRenderable- sessionMenu: { visible: boolean }- runtimeControls: { modelText: { plainText: string } }- }-- try {- ui.composer.setText("/sessions")- ui.composer.submit()- await waitUntil(() => ui.sessionMenu.visible)- expect(ui.composer.placeholder).toBe("Search sessions")-- ui.composer.setText("release")- ui.composer.submit()- await waitUntil(() => attached.length === 1)- expect(attached).toEqual(["other"])- expect(ui.runtimeControls.modelText.plainText).toBe("Deep Research ▾")- expect(ui.runtimeControls.modelText.plainText).not.toContain("test/model")-- app.accept({ event: "attached", chat_id: "other" })- await Bun.sleep(1)- ui.composer.setText("/new-chat")- ui.composer.submit()- await waitUntil(() => newChats.length === 1)- expect(newChats).toEqual(["new"])- expect(ui.runtimeControls.modelText.plainText).toBe("default ▾")- } finally {- globalThis.fetch = original- }- })-- test("switches away from a running session without losing its queued follow-ups", async () => {- setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })- const original = globalThis.fetch- globalThis.fetch = ((input: string | URL | Request) => {- const url = String(input)- if (url.endsWith("/api/sessions")) {- return Promise.resolve(new Response(JSON.stringify({- sessions: [- { key: "websocket:chat", title: "Running chat", run_started_at: 1_700_000_000 },- { key: "websocket:other", title: "Other chat" },- ],- })))- }- if (url.endsWith("/api/webui/sidebar-state")) {- return Promise.resolve(new Response(JSON.stringify({})))- }- return Promise.resolve(new Response(JSON.stringify({- schemaVersion: 3, projection: "events",- events: url.includes("websocket%3Aother") ? [- { event: "user_message", chat_id: "other", starts_turn: true, text: "saved question" },- { event: "stream_end", chat_id: "other", text: "saved answer" },- { event: "turn_end", chat_id: "other" },- ] : [],- page: { has_more_before: false },- })))- }) as typeof fetch- const sent: string[] = []- const attached: string[] = []- let activeChatId = "chat"- const base = client(sent, attached)- const transport = {- ...base,- get activeChatId() { return activeChatId },- attach(chatId: string) {- attached.push(chatId)- activeChatId = chatId- },- }- const app = NanobotTui.mount(- setup.renderer,- { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },- transport,- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- const ui = app as unknown as {- ready: boolean- activeTurn: boolean- composer: TextareaRenderable- sessionMenu: { visible: boolean }- queuePreview: { root: { visible: boolean } }- status: { plainText: string }- }-- try {- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => ui.ready)- app.accept({ event: "goal_status", chat_id: "chat", status: "running", turn_id: "turn" })- ui.composer.setText("follow up in chat")- setup.mockInput.pressTab()- await waitUntil(() => ui.composer.plainText === "")- expect(ui.queuePreview.root.visible).toBe(true)-- ui.composer.setText("/sessions")- ui.composer.submit()- await waitUntil(() => ui.sessionMenu.visible)- await Bun.sleep(120)- expect(ui.status.plainText).toContain("2 sessions")-- ui.composer.setText("other")- ui.composer.submit()- await waitUntil(() => attached.at(-1) === "other")- app.accept({ event: "attached", chat_id: "other" })- await waitUntil(() => ui.ready)- expect(ui.activeTurn).toBe(false)- expect(ui.queuePreview.root.visible).toBe(false)- await setup.flush()- expect(setup.captureCharFrame()).toContain("saved question")- expect(setup.captureCharFrame()).toContain("saved answer")-- ui.composer.setText("/sessions")- ui.composer.submit()- await waitUntil(() => ui.sessionMenu.visible)- ui.composer.setText("running")- ui.composer.submit()- await waitUntil(() => attached.at(-1) === "chat")- app.accept({ event: "attached", chat_id: "chat" })- app.accept({ event: "goal_status", chat_id: "chat", status: "running", turn_id: "turn" })- await waitUntil(() => ui.ready && ui.activeTurn)- expect(ui.queuePreview.root.visible).toBe(true)- expect(sent).toEqual([])-- app.accept({ event: "turn_end", chat_id: "chat", turn_id: "turn" })- await waitUntil(() => sent.length === 1)- expect(sent).toEqual(["follow up in chat"])- } finally {- globalThis.fetch = original- }- })-- test("refreshes expired API credentials before opening sessions", async () => {- setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })- const original = globalThis.fetch- let bootstrapRequests = 0- const sessionAuthorizations: Array<string | null> = []- globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {- const url = String(input)- const authorization = new Headers(init?.headers).get("Authorization")- if (url.endsWith("/webui/bootstrap")) {- bootstrapRequests += 1- return new Response(JSON.stringify({- ws_url: "ws://nanobot.test/ws",- token: "fresh-websocket-token",- api_token: "fresh-api-token",- }))- }- if (authorization === "Bearer expired-api-token") {- return new Response("Unauthorized", { status: 401 })- }- if (url.endsWith("/api/sessions")) {- sessionAuthorizations.push(authorization)- return new Response(JSON.stringify({- sessions: [{ key: "websocket:chat", title: "Current chat" }],- }))- }- return new Response("{}")- }) as typeof fetch- const app = NanobotTui.mount(- setup.renderer,- {- ...options,- bootstrapUrl: "http://nanobot.test/webui/bootstrap",- bootstrapSecret: "bootstrap-secret",- apiUrl: "http://nanobot.test",- apiToken: "expired-api-token",- },- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- app.accept({ event: "attached", chat_id: "chat" })- const ui = app as unknown as {- ready: boolean- composer: TextareaRenderable- sessionMenu: { visible: boolean }- status: { plainText: string }- }-- try {- await waitUntil(() => ui.ready)- ui.composer.setText("/sessions")- ui.composer.submit()-- await waitUntil(() => bootstrapRequests >= 1)- await waitUntil(() => ui.sessionMenu.visible)- expect(bootstrapRequests).toBe(1)- expect(sessionAuthorizations.at(-1)).toBe("Bearer fresh-api-token")- expect(ui.status.plainText).not.toContain("HTTP 401")- } finally {- globalThis.fetch = original- }- })-- test("tracks canonical presets without overwriting a session override", async () => {- setup = await createRenderer({ width: 96, height: 20, screenMode: "alternate-screen" })- const app = mount(setup)- const ui = app as unknown as { runtimeControls: { modelText: { plainText: string } } }-- app.accept({ event: "attached", chat_id: "chat", model_preset: "Codex" })- app.accept({- event: "turn_model_updated",- chat_id: "chat",- model_name: "openai/gpt-5.6",- model_preset: "Codex",- })- await setup.flush()- expect(ui.runtimeControls.modelText.plainText).toBe("Codex ▾")- expect(ui.runtimeControls.modelText.plainText).not.toContain("openai/gpt-5.6")-- app.accept({- event: "runtime_model_updated",- model_name: "deepseek/deepseek-chat",- model_preset: "DeepSeek",- })- await setup.flush()- expect(ui.runtimeControls.modelText.plainText).toBe("Codex ▾")- expect(ui.runtimeControls.modelText.plainText).not.toContain("DeepSeek")- })-- test("returns a default-following chat to the canonical default preset", async () => {- setup = await createRenderer({ width: 96, height: 20, screenMode: "alternate-screen" })- const app = NanobotTui.mount(- setup.renderer,- { ...options, model: "openai/gpt-5.6", modelPreset: "Codex" },- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- const ui = app as unknown as { runtimeControls: { modelText: { plainText: string } } }-- app.accept({ event: "attached", chat_id: "chat", model_preset: null })- app.accept({- event: "runtime_model_updated",- model_name: "deepseek/deepseek-chat",- model_preset: null,- })- await setup.flush()-- expect(ui.runtimeControls.modelText.plainText).toBe("default ▾")- expect(ui.runtimeControls.modelText.plainText).not.toContain("deepseek/deepseek-chat")- })-- test("refreshes the canonical preset after the model command completes", async () => {- setup = await createRenderer({ width: 96, height: 20, screenMode: "alternate-screen" })- const original = globalThis.fetch- globalThis.fetch = ((input: string | URL | Request) => {- if (String(input).endsWith("/api/webui/sidebar-state")) {- return Promise.resolve(new Response(JSON.stringify({})))- }- return Promise.resolve(new Response(JSON.stringify({- sessions: [{ key: "websocket:chat", model_preset: "Deep Research" }],- })))- }) as typeof fetch- const sent: string[] = []- const app = NanobotTui.mount(- setup.renderer,- { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },- client(sent),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- const ui = app as unknown as {- composer: TextareaRenderable- commandMenu: { setCommands(commands: SlashCommand[]): void }- runtimeControls: { modelText: { plainText: string } }- }-- try {- app.accept({ event: "attached", chat_id: "chat", model_preset: null })- ui.commandMenu.setCommands([{- command: "/model",- title: "Model",- description: "Show or switch model presets",- argHint: "[preset]",- lifecycle: "side_channel",- acceptsArgs: true,- }])- ui.composer.setText("/model deep research")- ui.composer.submit()- await waitUntil(() => sent.length === 1)- app.accept({- event: "message",- chat_id: "chat",- text: "Switched model preset to Deep Research.",- turn_id: "turn",- })- await waitUntil(() => ui.runtimeControls.modelText.plainText.includes("Deep Research"))-- expect(sent).toEqual(["/model deep research"])- } finally {- globalThis.fetch = original- }- })-- test("opens composer runtime controls by mouse and applies canonical choices", async () => {- const original = globalThis.fetch- const sent: string[] = []- const scopes: WorkspaceScopePayload[] = []- let settingsRequests = 0- let workspaceRequests = 0- globalThis.fetch = (async (input: string | URL | Request) => {- const url = String(input)- if (url.endsWith("/api/settings")) {- settingsRequests += 1- return new Response(JSON.stringify({- model_presets: [- { name: "default", model: "test/model" },- { name: "fast", model: "fast/model" },- ],- }))- }- if (url.endsWith("/api/workspaces")) {- workspaceRequests += 1- return new Response(JSON.stringify({- controls: { can_use_full_access: true },- }))- }- return new Response(JSON.stringify({ sessions: [] }))- }) as typeof fetch- setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })- const app = NanobotTui.mount(- setup.renderer,- { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },- client(sent, [], [], [], [], scopes),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- app.accept({ event: "attached", chat_id: "chat" })- const ui = app as unknown as {- runtimeControls: {- modelText: TextRenderable- accessText: TextRenderable- contextText: TextRenderable- visible: boolean- menuRoot: { getChildren(): unknown[] }- }- composer: TextareaRenderable- status: TextRenderable- meta: TextRenderable- }-- try {- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- await setup.renderOnce()- expect(setup.renderer.getCursorState()).toMatchObject({- style: "line",- blinking: false,- })- expect(ui.runtimeControls.modelText.selectable).toBe(false)- expect(ui.runtimeControls.accessText.selectable).toBe(false)- expect(ui.runtimeControls.contextText.selectable).toBe(false)- expect(ui.status.selectable).toBe(false)- expect(ui.meta.selectable).toBe(false)- app.accept({ event: "goal_status", chat_id: "chat", status: "running" })- await setup.flush()- await setup.mockMouse.click(- ui.runtimeControls.modelText.x + 2,- ui.runtimeControls.modelText.y,- )- await waitUntil(() => ui.runtimeControls.visible)- await setup.flush()- const modelRows = ui.runtimeControls.menuRoot.getChildren() as TextRenderable[]- expect(modelRows.every((row) => !row.selectable)).toBe(true)- const fast = modelRows.find((row) => row.plainText.includes("fast"))- if (!fast) throw new Error("fast model row was not rendered")- ui.composer.blur()- expect(ui.composer.focused).toBe(false)- await setup.mockMouse.click(fast.x + 2, fast.y)- await waitUntil(() => sent.includes("/model fast"))- expect(ui.composer.focused).toBe(true)-- await setup.mockMouse.click(- ui.runtimeControls.accessText.x + 2,- ui.runtimeControls.accessText.y,- )- await waitUntil(() => ui.runtimeControls.visible)- await setup.flush()- const accessRows = ui.runtimeControls.menuRoot.getChildren() as TextRenderable[]- const full = accessRows.find((row) => row.plainText.includes("Full access"))- if (!full) throw new Error("full access row was not rendered")- ui.composer.blur()- expect(ui.composer.focused).toBe(false)- await setup.mockMouse.click(full.x + 2, full.y)- expect(ui.composer.focused).toBe(true)-- expect(scopes).toEqual([{- project_path: "/tmp/nanobot-workspace",- access_mode: "full",- restrict_to_workspace: false,- }])-- await setup.mockMouse.click(- ui.runtimeControls.modelText.x + 2,- ui.runtimeControls.modelText.y,- )- await waitUntil(() => ui.runtimeControls.visible)- ui.composer.blur()- await setup.mockMouse.click(ui.status.x, ui.status.y)- expect(ui.runtimeControls.visible).toBe(false)- expect(ui.composer.focused).toBe(true)-- await setup.mockMouse.click(- ui.runtimeControls.accessText.x + 2,- ui.runtimeControls.accessText.y,- )- await waitUntil(() => ui.runtimeControls.visible)- ui.composer.blur()- await setup.mockMouse.click(ui.status.x, ui.status.y)- expect(ui.runtimeControls.visible).toBe(false)- expect(ui.composer.focused).toBe(true)- expect(settingsRequests).toBe(1)- expect(workspaceRequests).toBe(1)-- expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(true)- app.accept({ event: "goal_status", chat_id: "chat", status: "idle" })- } finally {- globalThis.fetch = original- }- })-- test("selects model presets beyond the runtime menu's visible limit", async () => {- const original = globalThis.fetch- const sent: string[] = []- globalThis.fetch = (async (input: string | URL | Request) => {- const url = String(input)- if (url.endsWith("/api/settings")) {- return new Response(JSON.stringify({- model_presets: [- { name: "default", model: "test/model" },- ...Array.from({ length: 10 }, (_, index) => ({- name: `preset-${index}`,- model: `test/model-${index}`,- })),- ],- }))- }- if (url.endsWith("/api/workspaces")) {- return new Response(JSON.stringify({ controls: { can_use_full_access: true } }))- }- return new Response(JSON.stringify({ sessions: [] }))- }) as typeof fetch- setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })- const app = NanobotTui.mount(- setup.renderer,- { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },- client(sent),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- app.accept({ event: "attached", chat_id: "chat" })- const ui = app as unknown as {- ready: boolean- runtimeControls: {- modelText: TextRenderable- visible: boolean- menuRoot: { getChildren(): unknown[] }- }- }-- try {- await waitUntil(() => ui.ready)- await setup.renderOnce()- await setup.mockMouse.click(- ui.runtimeControls.modelText.x + 2,- ui.runtimeControls.modelText.y,- )- await waitUntil(() => ui.runtimeControls.visible)- await setup.flush()- expect(ui.runtimeControls.menuRoot.getChildren()).toHaveLength(9)- expect(setup.captureCharFrame()).toContain("1–8 of 11 ↓")- expect(setup.captureCharFrame()).not.toContain("preset-8")-- for (let index = 0; index < 9; index += 1) setup.mockInput.pressArrow("down")- await setup.flush()- expect(setup.captureCharFrame()).toContain("› preset-8")- expect(setup.captureCharFrame()).toContain("3–10 of 11 ↑↓")-- setup.mockInput.pressEnter()- await waitUntil(() => sent.includes("/model preset-8"))- expect(ui.runtimeControls.visible).toBe(false)- } finally {- globalThis.fetch = original- }- })-- test("switches sessions only through the sessions command", async () => {- const original = globalThis.fetch- globalThis.fetch = ((input: string | URL | Request) => {- const url = String(input)- if (url.endsWith("/api/webui/sidebar-state")) {- return Promise.resolve(new Response(JSON.stringify({})))- }- return Promise.resolve(new Response(JSON.stringify({- sessions: [- { key: "websocket:chat", title: "Current chat", preview: "Current work" },- { key: "websocket:other", title: "Release checklist", preview: "Ship it" },- ],- })))- }) as typeof fetch- const attached: string[] = []- setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })- const app = NanobotTui.mount(- setup.renderer,- { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },- client([], attached),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- app.accept({ event: "attached", chat_id: "chat" })- const ui = app as unknown as {- composer: TextareaRenderable- sessionMenu: { visible: boolean; root: { getChildren(): unknown[] } }- title: { getChildren(): unknown[] }- }-- try {- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- await setup.renderOnce()- const titleItems = ui.title.getChildren() as TextRenderable[]- expect(titleItems.some((item) => item.id === "nanobot-tui-title-text")).toBe(false)- expect(ui.sessionMenu.visible).toBe(false)-- ui.composer.setText("/sessions")- ui.composer.submit()- await waitUntil(() => ui.sessionMenu.visible)- await setup.flush()- expect(ui.composer.placeholder).toBe("Search sessions")-- const rows = ui.sessionMenu.root.getChildren() as TextRenderable[]- const other = rows.find((row) => row.plainText.includes("Release checklist"))- if (!other) throw new Error("other session row was not rendered")- ui.composer.blur()- await setup.mockMouse.click(other.x + 2, other.y)- await waitUntil(() => attached.length === 1)- expect(attached).toEqual(["other"])- expect(ui.sessionMenu.visible).toBe(false)- expect(ui.composer.focused).toBe(true)- } finally {- globalThis.fetch = original- }- })-- test("offers clickable recovery actions without letting a late response revive stale state", async () => {- setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })- const calls: Array<{ action: string; chatId: string; recoveryId: string }> = []- let deferredResolve: ((state: RecoveryState) => void) | undefined- const recoveryClient = client()- recoveryClient.updateRecovery = (action, chatId, recoveryId) => {- calls.push({ action, chatId, recoveryId })- if (recoveryId === "recovery-1") {- return Promise.resolve({ status: "resuming", recovery_id: recoveryId })- }- if (action === "dismiss") {- return Promise.resolve({ status: "recovered", recovery_id: recoveryId })- }- return new Promise((resolve) => { deferredResolve = resolve })- }- const app = NanobotTui.mount(- setup.renderer,- options,- recoveryClient,- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- app.accept({- event: "attached",- chat_id: "chat",- recovery_state: {- status: "awaiting_user",- recovery_id: "recovery-1",- reason: "tool execution interrupted",- },- })- const ui = app as unknown as {- activeTurn: boolean- composer: TextareaRenderable- recoveryNotice: {- visible: boolean- dismiss: TextRenderable- resume: TextRenderable- }- status: TextRenderable- }-- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- await setup.renderOnce()- expect(setup.captureCharFrame()).toContain("⚠ Task interrupted")- expect(setup.captureCharFrame()).toContain("Tools will not replay automatically")- expect(ui.status.plainText).toContain("continue or dismiss")- expect(ui.activeTurn).toBe(false)- expect(ui.composer.focused).toBe(true)-- await setup.mockMouse.click(ui.recoveryNotice.resume.x + 1, ui.recoveryNotice.resume.y)- await waitUntil(() => calls.length === 1 && ui.activeTurn)- expect(calls[0]).toEqual({- action: "continue",- chatId: "chat",- recoveryId: "recovery-1",- })- expect(ui.recoveryNotice.visible).toBe(false)- expect(ui.status.plainText).toContain("Continuing")-- app.accept({- event: "recovery_state",- chat_id: "chat",- status: "awaiting_user",- recovery_id: "recovery-2",- })- await setup.renderOnce()- await setup.mockMouse.click(ui.recoveryNotice.resume.x + 1, ui.recoveryNotice.resume.y)- await waitUntil(() => calls.length === 2)- app.accept({- event: "recovery_state",- chat_id: "chat",- status: "recovered",- recovery_id: "recovery-2",- })- deferredResolve?.({ status: "resuming", recovery_id: "recovery-2" })- await Bun.sleep(1)-- expect(ui.recoveryNotice.visible).toBe(false)- expect(ui.activeTurn).toBe(false)- expect(ui.composer.focused).toBe(true)-- app.accept({- event: "recovery_state",- chat_id: "chat",- status: "awaiting_user",- recovery_id: "recovery-unavailable",- can_continue: false,- })- await setup.renderOnce()- const unavailableFrame = setup.captureCharFrame()- expect(unavailableFrame).toContain("can’t be resumed safely")- expect(unavailableFrame).not.toContain("Continue")- expect(ui.status.plainText).toContain("dismiss to start a new message")-- app.accept({- event: "recovery_state",- chat_id: "chat",- status: "awaiting_user",- recovery_id: "recovery-3",- })- await setup.renderOnce()- await setup.mockMouse.click(ui.recoveryNotice.dismiss.x + 1, ui.recoveryNotice.dismiss.y)- await waitUntil(() => calls.length === 3 && !ui.recoveryNotice.visible)- expect(calls[2]).toEqual({- action: "dismiss",- chatId: "chat",- recoveryId: "recovery-3",- })-- app.accept({- event: "recovery_state",- chat_id: "chat",- status: "awaiting_user",- recovery_id: "recovery-4",- can_continue: false,- })- await setup.renderOnce()- expect(ui.recoveryNotice.resume.visible).toBe(false)- expect(ui.recoveryNotice.dismiss.visible).toBe(true)- })-- test("preserves gateway slash lifecycle while local navigation stays in the same menu", async () => {- setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })- const sent: string[] = []- const app = mount(setup, sent)- app.accept({ event: "attached", chat_id: "chat" })- await Bun.sleep(1)- const ui = app as unknown as {- composer: TextareaRenderable- commandMenu: {- setCommands(commands: SlashCommand[]): void- }- activeTurn: boolean- }- ui.commandMenu.setCommands([{- command: "/new",- title: "New chat",- description: "Reset this chat",- argHint: "",- lifecycle: "finalize_active_turn",- acceptsArgs: false,- }, {- command: "/status",- title: "Status",- description: "Show status",- argHint: "",- lifecycle: "side_channel",- acceptsArgs: false,- }])-- app.accept({ event: "goal_status", chat_id: "chat", status: "running" })- ui.composer.setText("/status")- ui.composer.submit()- await waitUntil(() => sent.includes("/status"))- expect(ui.activeTurn).toBe(true)- app.accept({- event: "message",- chat_id: "chat",- text: "Runtime healthy",- turn_id: "turn",- })- await setup.flush()- expect(setup.captureCharFrame()).toContain("Runtime healthy")-- ui.composer.setText("/new")- ui.composer.submit()- await waitUntil(() => sent.includes("/new"))- expect(ui.activeTurn).toBe(false)- expect(sent).toEqual(["/status", "/new"])- await setup.flush()- expect(setup.captureCharFrame()).toContain("/new")- })-- test("blocks sends and ignores late session results after closing the picker", async () => {- setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })- const original = globalThis.fetch- let resolveFetch: ((response: Response) => void) | undefined- globalThis.fetch = ((input: string | URL | Request) => {- if (String(input).endsWith("/api/webui/sidebar-state")) {- return Promise.resolve(new Response(JSON.stringify({})))- }- return new Promise<Response>((resolve) => {- resolveFetch = resolve- })- }) as typeof fetch- const sent: string[] = []- const app = NanobotTui.mount(- setup.renderer,- { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },- client(sent),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- app.accept({ event: "attached", chat_id: "chat" })- await Bun.sleep(1)- const ui = app as unknown as {- composer: TextareaRenderable- sessionMenu: { visible: boolean }- sessionLoading: boolean- }-- try {- ui.composer.setText("/sessions")- ui.composer.submit()- await waitUntil(() => ui.sessionLoading)- ui.composer.setText("do not send")- ui.composer.submit()- await Bun.sleep(10)- expect(sent).toEqual([])-- setup.mockInput.pressEscape()- await Bun.sleep(10)- resolveFetch?.(new Response(JSON.stringify({ sessions: [] })))- await Bun.sleep(10)- expect(ui.sessionMenu.visible).toBe(false)- expect(ui.composer.plainText).toBe("")- } finally {- globalThis.fetch = original- }- })-- test("applies a query typed while sessions are still loading", async () => {- setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })- const original = globalThis.fetch- let resolveFetch: ((response: Response) => void) | undefined- globalThis.fetch = ((input: string | URL | Request) => {- if (String(input).endsWith("/api/webui/sidebar-state")) {- return Promise.resolve(new Response(JSON.stringify({})))- }- return new Promise<Response>((resolve) => {- resolveFetch = resolve- })- }) as typeof fetch- const app = NanobotTui.mount(- setup.renderer,- { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- app.accept({ event: "attached", chat_id: "chat" })- await Bun.sleep(1)- const ui = app as unknown as {- composer: TextareaRenderable- sessionMenu: { visible: boolean }- }-- try {- ui.composer.setText("/sessions")- ui.composer.submit()- await waitUntil(() => resolveFetch !== undefined)- ui.composer.setText("release")- resolveFetch!(new Response(JSON.stringify({- sessions: [- { key: "websocket:chat", title: "Current chat", preview: "Current work" },- { key: "websocket:other", title: "Release checklist", preview: "Ship it" },- ],- })))- await waitUntil(() => ui.sessionMenu.visible)- await setup.flush()- const frame = setup.captureCharFrame()- expect(frame).toContain("Release checklist")- expect(occurrences(frame, "Current chat")).toBe(0)- } finally {- globalThis.fetch = original- }- })-- test("shows compact session context without exposing private reasoning", async () => {- setup = await createRenderer({ width: 96, height: 26, screenMode: "alternate-screen" })- const original = globalThis.fetch- globalThis.fetch = ((input: string | URL | Request) => {- expect(String(input)).toContain("/api/sessions/websocket%3Achat/context")- return Promise.resolve(new Response(JSON.stringify({- total_messages: 24,- archived_messages: 16,- replay_messages: 10,- estimated_replay_tokens: 2048,- estimated_summary_tokens: 128,- estimated_session_tokens: 2176,- archived_summary: "The earlier turns agreed on a release plan.",- archived_summary_at: "2026-08-13T10:00:00Z",- })))- }) as typeof fetch- const app = NanobotTui.mount(- setup.renderer,- { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- app.accept({ event: "attached", chat_id: "chat" })- const ui = app as unknown as {- composer: TextareaRenderable- contextPanel: { visible: boolean }- runtimeControls: { contextText: { plainText: string } }- }-- try {- ui.composer.setText("/context")- ui.composer.submit()- await waitUntil(() => ui.contextPanel.visible)- await setup.flush()- expect(ui.runtimeControls.contextText.plainText).toContain("~2.2k ctx")- const frame = setup.captureCharFrame()-- expect(frame).toContain("~2.2k tokens · 10 replay · 16 archived")- expect(frame).toContain("The earlier turns agreed on a release plan.")- expect(frame).not.toContain("Agent context")- expect(frame).not.toContain("summary active")- expect(frame).not.toContain("memory, instructions, and skills are added separately")-- setup.resize(40, 10)- await setup.renderOnce()- const compact = setup.captureCharFrame()- expect(occurrences(compact, "Agent context")).toBe(0)- expect(occurrences(compact, "Ask nanobot anything")).toBe(1)-- setup.mockInput.pressEscape()- await waitUntil(() => !ui.contextPanel.visible)- expect(ui.contextPanel.visible).toBe(false)- } finally {- globalThis.fetch = original- }- })-- test("opens the latest turn diff as a full-screen, navigable view", async () => {- setup = await createRenderer({ width: 96, height: 28, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- app.accept({ event: "message_accepted", chat_id: "chat", turn_id: "edit-turn" })- app.accept({- event: "file_edit",- chat_id: "chat",- edits: [{- call_id: "edit-1",- tool: "edit_file",- path: "src/first.ts",- status: "done",- added: 2,- deleted: 1,- diff: {- format: "unified",- truncated: true,- text: [- "--- a/src/first.ts",- "+++ b/src/first.ts",- "@@ -1 +1,2 @@",- "-const oldValue = 1",- "+const newValue = 2",- "+export { newValue }",- ].join("\n"),- },- }, {- call_id: "edit-2",- tool: "write_file",- path: "src/second.py",- status: "done",- added: 1,- deleted: 0,- diff: {- format: "unified",- text: [- "--- a/src/second.py",- "+++ b/src/second.py",- "@@ -0,0 +1 @@",- "+print('hello')",- ].join("\n"),- },- }],- })- app.accept({ event: "turn_end", chat_id: "chat", turn_id: "edit-turn" })- const ui = app as unknown as {- composer: TextareaRenderable- diffViewer: {- visible: boolean- scroll: { getChildren(): Array<{ addedBg?: { toInts(): number[] } }> }- }- }-- ui.composer.setText("/diff")- ui.composer.submit()- await waitUntil(() => ui.diffViewer.visible)- await setup.flush()- let frame = setup.captureCharFrame()- expect(frame).toContain("Diff · Last turn · 2 changes · +3 -1")- expect(frame).toContain("1/2 · src/first.ts · +2 -1")- expect(frame).toContain("const newValue = 2")- expect(frame).toContain("Diff truncated by the gateway")- expect(frame).not.toContain("Ask nanobot anything")-- setup.mockInput.pressArrow("right")- await setup.flush()- frame = setup.captureCharFrame()- expect(frame).toContain("2/2 · src/second.py · +1 -0")- expect(frame).toContain("print('hello')")-- setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")- await setup.flush()- expect(ui.diffViewer.scroll.getChildren()[0]?.addedBg?.toInts().slice(0, 3)).toEqual([231, 246, 236])- expect(setup.captureCharFrame()).toContain("print('hello')")-- setup.resize(52, 18)- await setup.renderOnce()- expect(setup.captureCharFrame()).toContain("←/→ file · pgup/pgdn · esc")-- setup.mockInput.pressEscape()- await waitUntil(() => !ui.diffViewer.visible)- await setup.flush()- expect(setup.captureCharFrame()).toContain("Ask nanobot anything")- })-- test("loads earlier transcript pages in place when PageUp reaches the top", async () => {- setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })- const original = globalThis.fetch- const requests: string[] = []- globalThis.fetch = ((input: string | URL | Request) => {- const url = String(input)- requests.push(url)- const older = url.includes("before=older-page")- return Promise.resolve(new Response(JSON.stringify({- schemaVersion: 3, projection: "events",- events: older- ? [- { event: "user_message", chat_id: "chat", starts_turn: true, text: "oldest question" },- { event: "stream_end", chat_id: "chat", text: "oldest answer" },- ]- : [- { event: "user_message", chat_id: "chat", starts_turn: true, text: "recent question" },- { event: "stream_end", chat_id: "chat", text: "recent answer" },- ],- page: older- ? { has_more_before: false, before_cursor: null }- : { has_more_before: true, before_cursor: "older-page" },- })))- }) as typeof fetch- const app = NanobotTui.mount(- setup.renderer,- { ...options, apiUrl: "http://nanobot.test", apiToken: "secret", chatId: "chat" },- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )-- try {- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- setup.mockInput.pressKey("\u001B[5~")- await waitUntil(() => requests.length === 2)- await waitUntil(() => !(app as unknown as { historyLoadingOlder: boolean }).historyLoadingOlder)- await setup.flush()- const frame = setup.captureCharFrame()-- expect(frame.indexOf("oldest question")).toBeLessThan(frame.indexOf("recent question"))- expect(frame.indexOf("oldest answer")).toBeLessThan(frame.indexOf("recent answer"))- expect((app as unknown as { historyHasMore: boolean }).historyHasMore).toBe(false)-- const composer = (app as unknown as { composer: TextareaRenderable }).composer- setup.mockInput.pressArrow("up")- expect(composer.plainText).toBe("recent question")- setup.mockInput.pressArrow("up")- expect(composer.plainText).toBe("oldest question")- } finally {- globalThis.fetch = original- }- })-- test("survives rapid narrow resizes with long CJK and code", async () => {- setup = await createRenderer({ width: 100, height: 30, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({- event: "delta",- chat_id: "chat",- text: [- "中文、emoji 👨💻 and combining text é reflow with the terminal.",- "https://nanobot.test/a-very-long-unbroken-path-that-must-not-break-the-layout",- "```ts",- "const greeting = '你好,nanobot'",- "```",- ].join("\n\n"),- })- app.accept({ event: "stream_end", chat_id: "chat" })-- for (const [width, height] of [- [240, 80],- [42, 12],- [30, 9],- [20, 6],- [12, 4],- [8, 3],- [4, 2],- [84, 24],- [48, 14],- [110, 32],- ] as const) {- setup.resize(width, height)- await setup.renderOnce()- const frame = setup.captureCharFrame()- expect(setup.renderer.width).toBe(width)- expect(setup.renderer.height).toBe(height)- expect(frame).not.toContain("undefined")- expect(frame).not.toContain("Steer this turn…")- expect(frame).not.toContain("Ask a follow-up…")- if (width >= 40 && height >= 9) {- expect(occurrences(frame, "Enter send now · Tab send next")).toBe(1)- } else if (width >= 28 && height >= 9) {- expect(occurrences(frame, "Enter now · Tab next")).toBe(1)- }- expect(occurrences(frame, "default ▾")).toBe(height >= 14 ? 1 : 0)- }- })-- test("inherits the host background after long output fills the viewport", async () => {- setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({ event: "attached", chat_id: "chat" })- app.accept({- event: "delta",- chat_id: "chat",- text: Array.from({ length: 80 }, (_, index) => (- `### Section ${index + 1}\n中文长回答、**bold** and [link](https://nanobot.test/${index + 1})`- )).join("\n\n"),- })- app.accept({ event: "stream_end", chat_id: "chat" })- app.accept({ event: "turn_end", chat_id: "chat" })- await setup.flush()-- const internals = app as unknown as {- shell: { backgroundColor: { intent: string } }- composerFrame: { backgroundColor: { intent: string } }- composer: { backgroundColor: { intent: string } }- transcript: { root: HiddenScrollBox }- diffViewer: { scroll: HiddenScrollBox }- }- const lines = setup.captureSpans().lines- const spans = lines.flatMap((line) => line.spans)- const brandedRows = lines.filter((line) => (- line.spans.some((span) => span.bg.intent !== "default")- ))-- expect(internals.shell.backgroundColor.intent).toBe("default")- expect(internals.composerFrame.backgroundColor.intent).toBe("default")- expect(internals.composer.backgroundColor.intent).toBe("default")- expect(spans.length).toBeGreaterThan(0)- expect(brandedRows).toHaveLength(0)- for (const scrollBox of [internals.transcript.root, internals.diffViewer.scroll]) {- for (const bar of [scrollBox.verticalScrollBar, scrollBox.horizontalScrollBar]) {- expect(bar.visible).toBeFalse()- expect(bar.slider.visible).toBeFalse()- expect(bar.startArrow.visible).toBeFalse()- expect(bar.endArrow.visible).toBeFalse()- }- }- })-- test("reflows markdown tables without clipping columns or cell content", async () => {- setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({ event: "attached", chat_id: "chat" })- app.accept({- event: "delta",- chat_id: "chat",- text: [- "| Who | Content | Engagement |",- "| --- | --- | --- |",- "| @owner | A longer explanation that keeps context readable | 13 likes / 6 RT |",- "| @reader | Short follow-up | Low interaction |",- ].join("\n"),- })- app.accept({ event: "stream_end", chat_id: "chat" })- app.accept({ event: "turn_end", chat_id: "chat" })-- for (const width of [96, 54, 96]) {- setup.resize(width, 24)- await setup.flush()- const rendered = setup.captureCharFrame().replace(/\s+/gu, " ")-- expect(rendered).toContain("Who")- expect(rendered).toContain("Content")- expect(rendered).toContain("Engagement")- expect(rendered).toContain("@owner")- expect(rendered).toContain("longer explanation")- expect(rendered).toContain("keeps context")- expect(rendered).toContain("readable")- expect(rendered).toContain("13 likes / 6")- expect(rendered).toContain("RT")- expect(rendered).toContain("Low interaction")- expect((app as unknown as {- transcript: { root: HiddenScrollBox }- }).transcript.root.horizontalScrollBar.visible).toBeFalse()- }- })-- test("keeps finalized streamed Markdown link labels clickable", async () => {- setup = await createRenderer({ width: 100, height: 24, screenMode: "alternate-screen" })- setRendererCapabilities(setup.renderer, { hyperlinks: true })- const label = "HKUDS/nanobot#1234"- const url = "https://github.com/HKUDS/nanobot/pull/1234"- const content = `PR updated: [${label}](${url})`- const labelStart = content.indexOf(label)- const urlStart = content.indexOf(url)- const treeSitterClient = new MockTreeSitterClient({ autoResolveTimeout: 0 })- treeSitterClient.setMockResult({- highlights: [- [labelStart - 1, labelStart, "markup.link"],- [labelStart, labelStart + label.length, "markup.link.label"],- [labelStart + label.length, urlStart, "markup.link"],- [urlStart, urlStart + url.length, "markup.link.url"],- [urlStart + url.length, content.length, "markup.link"],- ],- })- const app = NanobotTui.mount(setup.renderer, options, client(), treeSitterClient)-- app.accept({ event: "attached", chat_id: "chat" })- app.accept({ event: "delta", chat_id: "chat", text: content })- app.accept({ event: "stream_end", chat_id: "chat" })- app.accept({ event: "turn_end", chat_id: "chat" })- await setup.flush()-- const lines = setup.captureCharFrame().split("\n")- const y = lines.findIndex((line) => line.includes(label))- const x = y >= 0 ? lines[y]!.indexOf(label) : -1- expect([x, y]).not.toContain(-1)-- for (let offset = 0; offset < label.length; offset += 1) {- expect(setup.renderer.getLinkAt(x + offset, y)).toBe(url)- }- })-- test("keeps streamed fenced code visible while completing the response", async () => {- setup = await createRenderer({ width: 100, height: 30, screenMode: "alternate-screen" })- const app = mount(setup)- const response = [- "Commit types:",- "",- "```text",- "feat:",- "fix:",- "perf:",- "docs:",- "test:",- "refactor:",- "chore:",- "```",- "",- "Include the reason in the body.",- ].join("\n")-- app.accept({ event: "attached", chat_id: "chat" })- app.accept({ event: "delta", chat_id: "chat", text: response })- await setup.flush()- expect(setup.captureCharFrame()).toContain("feat:")-- const recorder = new TestRecorder(setup.renderer)- recorder.rec()- app.accept({ event: "stream_end", chat_id: "chat" })- app.accept({ event: "turn_end", chat_id: "chat" })- await setup.flush()- recorder.stop()-- expect(recorder.recordedFrames.length).toBeGreaterThan(0)- expect(recorder.recordedFrames.every(({ frame }) => frame.includes("feat:"))).toBeTrue()- expect(recorder.recordedFrames.every(({ frame }) => /│\s+feat:/u.test(frame))).toBeTrue()- expect(recorder.recordedFrames.every(({ frame }) => (- frame.includes("Include the reason in the body.")- ))).toBeTrue()- })-- test("renders fenced plain text from light-theme history", async () => {- setup = await createRenderer({ width: 100, height: 30, screenMode: "alternate-screen" })- const app = NanobotTui.mount(- setup.renderer,- { ...options, theme: "light" },- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- const response = [- "Commit types:",- "",- "```text",- "feat:",- "fix:",- "perf:",- "docs:",- "test:",- "refactor:",- "chore:",- "```",- "",- "Include the reason in the body.",- ].join("\n")- const transcript = (app as unknown as { transcript: Transcript }).transcript-- transcript.history([{ role: "assistant", content: response }])- await setup.flush()-- const codeLine = setup.captureSpans().lines.find((line) => (- line.spans.some((span) => span.text.includes("feat:"))- ))- const code = codeLine?.spans.find((span) => span.text.includes("feat:"))- const rail = codeLine?.spans.find((span) => span.text.includes("│"))- const frame = setup.captureCharFrame()-- expect(frame).toContain("feat:")- expect(frame).toMatch(/│\s+feat:/u)- expect(code?.fg.toInts().slice(0, 3)).toEqual([24, 24, 27])- expect(rail?.fg.toInts().slice(0, 3)).toEqual([212, 212, 216])- })-- test("renders assistant LaTeX as Unicode text without changing code", async () => {- setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({- event: "delta",- chat_id: "chat",- text: [- "缓存率:",- "\\[\\text{缓存率}=\\frac{\\text{cached input tokens}}{\\text{total input tokens}}\\]",- "结果:\\(66{,}000 \\times 94\\% \\approx 62{,}040\\)",- "`\\(code\\)`",- ].join("\n"),- })- app.accept({ event: "stream_end", chat_id: "chat" })- const transcript = (app as unknown as {- transcript: { assistant(content: string): void }- }).transcript- transcript.assistant("历史公式:\\(x_1^2 + y_2^2 = z^2\\)")- await setup.flush()- const frame = setup.captureCharFrame()-- expect(frame).toContain("缓存率 = cached input tokens / total input tokens")- expect(frame).toContain("66,000 × 94% ≈ 62,040")- expect(frame).toContain("历史公式:x₁² + y₂² = z²")- expect(frame).toContain("\\(code\\)")- expect(frame).not.toContain("\\frac")- expect(frame).not.toContain("\\text")- })-- test("rethemes the complete retained interface when the terminal appearance changes", async () => {- setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({ event: "attached", chat_id: "chat" })- app.accept({ event: "delta", chat_id: "chat", text: "# Existing answer" })- app.accept({ event: "stream_end", chat_id: "chat" })- app.accept({ event: "message", chat_id: "chat", text: "tool", kind: "tool_hint" })- await setup.renderOnce()-- const internals = app as unknown as {- palette: { referenceBackground: string; text: string; border: string }- shell: { backgroundColor: { intent: string } }- composerFrame: {- backgroundColor: { intent: string; toInts(): number[] }- }- composer: {- backgroundColor: { intent: string; toInts(): number[] }- textColor: { toInts(): number[] }- syntaxStyle: { getStyle(name: string): { fg?: { toInts(): number[] } } | undefined } | null- }- transcript: {- markdown: Set<{ fg?: { toInts(): number[] }; syntaxStyle: object }>- frames: Set<{ borderColor: { toInts(): number[] } }>- userRows: Set<{ backgroundColor: { intent: string; toInts(): number[] } }>- userMessages: Set<{ renderable: TextRenderable }>- user(content: string, turnId?: string, media?: Array<{ kind: "image"; name: string }>): void- }- }- internals.transcript.user("Existing question", undefined, [{- kind: "image",- name: "clipboard-image-1.png",- }])- const userRow = [...internals.transcript.userRows][0]- const userMessage = [...internals.transcript.userMessages][0]- const markdown = [...internals.transcript.markdown][0]- const sessionFrame = [...internals.transcript.frames][0]- const darkSyntax = markdown?.syntaxStyle- const darkComposerSyntax = internals.composer.syntaxStyle-- expect(userRow?.backgroundColor.intent).toBe("default")-- setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")- await setup.flush()-- expect(internals.palette).toMatchObject({- referenceBackground: "#FAFAFA",- text: "#18181B",- border: "#D4D4D8",- })- expect(internals.shell.backgroundColor.intent).toBe("default")- expect(internals.composerFrame.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])- expect(internals.composer.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])- expect(internals.composer.textColor.toInts().slice(0, 3)).toEqual([24, 24, 27])- expect(sessionFrame?.borderColor.toInts().slice(0, 3)).toEqual([212, 212, 216])- expect(userRow?.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])- expect(markdown?.fg?.toInts().slice(0, 3)).toEqual([24, 24, 27])- expect(markdown?.syntaxStyle).not.toBe(darkSyntax)- expect(internals.composer.syntaxStyle).not.toBe(darkComposerSyntax)- expect(internals.composer.syntaxStyle?.getStyle("image.placeholder")?.fg?.toInts().slice(0, 3))- .toEqual([185, 77, 11])- const recolored = userMessage?.renderable.content as StyledText- expect(recolored.chunks.find(({ text }) => text === "[Image #1]")?.fg?.toInts().slice(0, 3))- .toEqual([185, 77, 11])- })-- test("distinguishes the composer with a quiet focus edge", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = NanobotTui.mount(- setup.renderer,- { ...options, theme: "light" },- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- const internals = app as unknown as {- ready: boolean- composerFrame: {- border: boolean | string[]- borderColor: { toInts(): number[] }- backgroundColor: { toInts(): number[] }- }- composer: {- backgroundColor: { toInts(): number[] }- placeholderColor: { toInts(): number[] }- }- }-- expect(internals.composerFrame.border).toEqual(["left"])- expect(internals.composerFrame.borderColor.toInts().slice(0, 3)).toEqual([185, 77, 11])- expect(internals.composerFrame.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])- expect(internals.composer.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])- expect(internals.composer.placeholderColor.toInts().slice(0, 3)).toEqual([111, 111, 120])-- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => internals.ready)- await setup.renderOnce()-- const composerLine = setup.captureCharFrame().split("\n")- .find((line) => line.includes("Ask nanobot anything")) || ""- expect(composerLine).toContain("│")- expect(composerLine).not.toContain("┌")- expect(composerLine).not.toContain("┐")- })-- test("uses asymmetric roles instead of chat bubbles", async () => {- setup = await createRenderer({ width: 72, height: 24, screenMode: "alternate-screen" })- const app = NanobotTui.mount(- setup.renderer,- { ...options, theme: "dark" },- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- app.accept({ event: "attached", chat_id: "chat" })- app.accept({ event: "delta", chat_id: "chat", text: "Agent **answer**" })- app.accept({ event: "stream_end", chat_id: "chat" })- app.accept({ event: "turn_end", chat_id: "chat" })- ;(app as unknown as { transcript: { user(content: string): void } }).transcript.user("User question")- await setup.flush()-- const frame = setup.captureCharFrame()- const userLine = frame.split("\n").find((line) => line.includes("User question")) || ""- const agentLine = frame.split("\n").find((line) => line.includes("Agent **answer**")) || ""- const headerLine = frame.split("\n").find((line) => line.includes(">_ nanobot")) || ""- const headerBorder = frame.split("\n").find((line) => line.includes("╭")) || ""-- expect(userLine).toContain("› User question")- expect(agentLine).toContain("• Agent **answer**")- expect(userLine).not.toContain("│")- expect(agentLine).not.toContain("│")- expect(headerLine).toContain("│")- expect(headerBorder.trim().length).toBe(setup.renderer.width - 4)-- const transcript = (app as unknown as {- transcript: {- userRows: Set<{ backgroundColor: { intent: string; toInts(): number[] } }>- styledText: Array<{- renderable: { id: string; fg: { toInts(): number[] } }- tone: string- }>- }- }).transcript- const userRow = [...transcript.userRows][0]- const assistantMarker = transcript.styledText.find(({ renderable, tone }) => (- tone === "muted" && renderable.id.includes("role-marker")- ))-- expect(userRow?.backgroundColor.intent).toBe("rgb")- expect(userRow?.backgroundColor.toInts().slice(0, 3)).toEqual([43, 44, 46])- expect(assistantMarker?.tone).toBe("muted")- expect(assistantMarker?.renderable.fg.toInts().slice(0, 3)).toEqual([161, 161, 170])- })-- test("aligns footer labels with transcript content", async () => {- setup = await createRenderer({ width: 72, height: 24, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({ event: "attached", chat_id: "chat" })- ;(app as unknown as { transcript: { user(content: string): void } })- .transcript.user("Aligned message")- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- await setup.renderOnce()-- const lines = setup.captureCharFrame().split("\n")- const lineContaining = (needle: string): string => {- const line = lines.find((candidate) => candidate.includes(needle))- if (!line) throw new Error(`${needle} was not rendered`)- return line- }- const messageLine = lineContaining("Aligned message")- const composerLine = lineContaining("Ask nanobot anything")- const contentColumn = messageLine.indexOf("Aligned message")-- expect(lineContaining("default ▾").indexOf("default ▾")).toBe(contentColumn)- expect(lineContaining("Ready").indexOf("Ready")).toBe(contentColumn)- expect(composerLine.indexOf("│")).toBe(messageLine.indexOf("›"))- expect(composerLine.indexOf("Ask nanobot anything")).toBe(contentColumn)- })-- test("shows context usage in the idle footer", async () => {- setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({ event: "attached", chat_id: "chat" })- app.accept({- event: "turn_end",- chat_id: "chat",- latency_ms: 1700,- usage: {- context_tokens: 14_700,- },- context_window_tokens: 128_000,- })- await setup.flush()-- const footer = setup.captureCharFrame().split("\n").find((line) => line.includes("Ready · 1.7s")) || ""- expect(footer).toContain("Ready · 1.7s")- expect(footer).toContain("11% context")- })-- test("keeps an explicit theme stable when the terminal reports another mode", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = NanobotTui.mount(- setup.renderer,- { ...options, theme: "light" },- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- const internals = app as unknown as { palette: { referenceBackground: string } }- Object.defineProperty(setup.renderer, "themeMode", { configurable: true, value: "dark" })-- await app.start()-- setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")- await setup.renderOnce()-- expect(internals.palette.referenceBackground).toBe("#FAFAFA")- })-- test("overlaps automatic terminal detection with connection startup", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- let connected = false- let rendered = false- let resolveMode: (mode: "light") => void = () => undefined- setup.renderer.start = () => { rendered = true }- setup.renderer.waitForThemeMode = () => new Promise((resolve) => {- resolveMode = resolve- })- Object.defineProperty(setup.renderer, "themeMode", { configurable: true, value: "light" })- const transport = client()- transport.connect = () => { connected = true }- const app = NanobotTui.mount(- setup.renderer,- options,- transport,- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )-- const starting = app.start()- await Bun.sleep(1)- expect(connected).toBe(true)- expect(rendered).toBe(true)-- resolveMode("light")- await starting- expect((app as unknown as { palette: { referenceBackground: string } }).palette.referenceBackground).toBe("#FAFAFA")- })-- test.each(["dark", "light"] as const)("uses terminal defaults until a late %s theme response", async (mode) => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- let connected = false- setup.renderer.waitForThemeMode = async () => null- Object.defineProperty(setup.renderer, "themeMode", { configurable: true, value: null })- const transport = client()- transport.connect = () => { connected = true }- const app = NanobotTui.mount(- setup.renderer,- options,- transport,- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )-- await app.start()-- const transcript = (app as unknown as {- transcript: {- userRows: Set<{ backgroundColor: { intent: string } }>- user(content: string): void- }- }).transcript- transcript.user("Unknown terminal background")-- expect(connected).toBe(true)- const ui = app as unknown as {- composer: TextareaRenderable- status: TextRenderable- shimmerFrame: number- renderActiveStatus(): void- }- expect(ui.composer.textColor.intent).toBe("default")- expect(ui.composer.backgroundColor.intent).toBe("default")- expect([...transcript.userRows][0]?.backgroundColor.intent).toBe("default")- app.accept({ event: "delta", chat_id: "chat", text: "Readable answer" })- app.accept({ event: "stream_end", chat_id: "chat" })- await setup.flush()- expect(setup.captureCharFrame()).toContain("Readable answer")- for (const line of setup.captureSpans().lines) {- for (const span of line.spans) {- if (span.text.trim()) expect(span.fg.intent).toBe("default")- }- }- // Keep the fallback readable without guessed RGB colors, but do not freeze- // the active-status animation while waiting for a terminal theme response.- app.accept({ event: "reasoning_delta", chat_id: "chat", text: "thinking" })- await setup.flush()- const terminalFrame = () => (ui.status.content as StyledText).chunks- .slice(0, "Thinking".length)- .map((chunk) => chunk.attributes ?? 0)- const firstFrame = terminalFrame()- ui.shimmerFrame += 1- ui.renderActiveStatus()- const secondFrame = terminalFrame()- expect(firstFrame).toContain(TextAttributes.BOLD)- expect(secondFrame).not.toEqual(firstFrame)- for (const chunk of (ui.status.content as StyledText).chunks) {- expect(chunk.fg?.intent).toBe("default")- }-- setup.renderer.emit(CliRenderEvents.THEME_MODE, mode)- await setup.flush()- const shimmerColors = new Set(- (ui.status.content as StyledText).chunks- .slice(0, "Thinking".length)- .map((chunk) => chunk.fg?.toInts().slice(0, 3).join(",")),- )- expect(shimmerColors.size).toBeGreaterThan(1)- expect(ui.composer.textColor.intent).toBe("rgb")- expect(ui.composer.textColor.toInts().slice(0, 3)).toEqual(- mode === "light" ? [24, 24, 27] : [236, 237, 238],- )- expect([...transcript.userRows][0]?.backgroundColor.intent).toBe("rgb")- })-- test("keeps semantic colors legible in both terminal appearances", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = mount(setup)- const internals = app as unknown as {- palette: Record<string, string> & { referenceBackground: string; faint: string }- }- const assertContrast = () => {- for (const tone of ["text", "muted", "accent", "link", "success", "error", "user", "warm", "cool"]) {- expect(contrastRatio(internals.palette[tone] ?? "", internals.palette.referenceBackground)).toBeGreaterThanOrEqual(4.5)- }- expect(contrastRatio(internals.palette.faint, internals.palette.referenceBackground)).toBeGreaterThanOrEqual(3)- const turnContrast = contrastRatio(- internals.palette.userBackground ?? "",- internals.palette.referenceBackground,- )- expect(turnContrast).toBeGreaterThan(1.05)- expect(turnContrast).toBeLessThan(1.5)- }-- setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")- assertContrast()- expect(internals.palette.accent).toBe("#EF8E30")- expect(internals.palette.user).toBe("#EF8E30")- setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")- assertContrast()- expect(internals.palette.accent).toBe("#B94D0B")- expect(internals.palette.user).toBe("#B94D0B")- })-- test("replaces streamed drafts with canonical stream-end text", async () => {- setup = await createRenderer({ width: 80, height: 20, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({ event: "delta", chat_id: "chat", text: "draft signed://expired" })- app.accept({- event: "stream_end",- chat_id: "chat",- text: "canonical https://nanobot.test/signed/current",- resuming: true,- merge_next: true,- })- app.accept({ event: "delta", chat_id: "chat", text: " tail" })- app.accept({- event: "stream_end",- chat_id: "chat",- text: "final https://nanobot.test/signed/current tail",- })- app.accept({ event: "turn_end", chat_id: "chat" })- await setup.flush()- const frame = setup.captureCharFrame()-- expect(frame).toContain("final https://nanobot.test/signed/current tail")- expect(frame).not.toContain("canonical https://nanobot.test/signed/current")- expect(frame).not.toContain("draft signed://expired")- })-- test("paints the first token immediately and coalesces the rest per frame", async () => {- setup = await createRenderer({ width: 80, height: 20, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({ event: "delta", chat_id: "chat", text: "first" })- const transcript = (app as unknown as {- transcript: {- live: { markdown: { content: string; streaming: boolean } } | null- }- }).transcript- const markdown = transcript.live?.markdown- expect(markdown?.content).toBe("first")-- for (let index = 0; index < 1_000; index += 1) {- app.accept({ event: "delta", chat_id: "chat", text: " token" })- }- expect(markdown?.content).toBe("first")-- app.accept({ event: "stream_end", chat_id: "chat" })- expect(markdown?.content).toBe(`first${" token".repeat(1_000)}`)- expect(markdown?.streaming).toBe(false)- })-- test("copies full-screen selections through OSC 52", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = mount(setup)- let copied = ""- setup.renderer.copyToClipboardOSC52 = (text: string) => {- copied = text- return true- }-- await setup.renderOnce()- app.accept({ event: "delta", chat_id: "chat", text: "selected answer" })- app.accept({ event: "stream_end", chat_id: "chat" })- await setup.flush()- const rows = setup.captureCharFrame().split("\n")- const y = rows.findIndex((row) => row.includes("selected answer"))- const x = rows[y]?.indexOf("selected answer") ?? -1- expect(x).toBeGreaterThanOrEqual(0)- expect(y).toBeGreaterThanOrEqual(0)-- await setup.mockMouse.drag(x, y, x + "selected answer".length, y)- expect(setup.renderer.getSelection()?.getSelectedText()).toBe("selected answer")- setup.mockInput.pressCtrlC()- await Bun.sleep(10)- await setup.flush()-- expect(copied).toBe("selected answer")- expect(setup.renderer.getSelection()).toBeNull()- })-- test("clears transcript selection when clicking non-content chrome", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = mount(setup)- const status = (app as unknown as { status: TextRenderable }).status- app.accept({ event: "delta", chat_id: "chat", text: "selectable answer" })- app.accept({ event: "stream_end", chat_id: "chat" })- await setup.flush()-- const rows = setup.captureCharFrame().split("\n")- const y = rows.findIndex((row) => row.includes("selectable answer"))- const x = rows[y]?.indexOf("selectable answer") ?? -1- await setup.mockMouse.drag(x, y, x + "selectable answer".length, y)- expect(setup.renderer.getSelection()?.getSelectedText()).toBe("selectable answer")-- await setup.mockMouse.click(status.x, status.y)- expect(setup.renderer.getSelection()).toBeNull()- })-- test("keeps text input focus when the focusable transcript is clicked", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = mount(setup)- const ui = app as unknown as {- composer: TextareaRenderable- transcript: {- root: { x: number; y: number; focused: boolean }- }- }- app.accept({ event: "delta", chat_id: "chat", text: "clickable answer" })- app.accept({ event: "stream_end", chat_id: "chat" })- await setup.flush()-- await setup.mockMouse.click(ui.transcript.root.x + 1, ui.transcript.root.y + 1)-- expect(ui.composer.focused).toBe(true)- expect(ui.transcript.root.focused).toBe(false)- })-- test("animates one stable status line while the agent works", async () => {- setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })- const app = mount(setup)- setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")- app.accept({ event: "attached", chat_id: "chat" })- app.accept({ event: "reasoning_delta", chat_id: "chat", text: "hidden reasoning" })- await Bun.sleep(130)- await setup.renderOnce()- let frame = setup.captureCharFrame()-- expect(frame).toMatch(/Thinking\s+0s/u)- expect(frame).not.toMatch(/[◐◓◑◒⠋⠙⠹⠸]/u)- expect(frame).not.toContain("hidden reasoning")- const ui = app as unknown as {- status: {- content: { chunks: Array<{ fg?: { toInts(): number[] } }> }- plainText: string- }- composer: TextareaRenderable- composerFrame: BoxRenderable- }- const status = ui.status- expect(status.plainText).toMatch(/^Thinking\s+0s/u)- expect(ui.composer.placeholder).toBe("Enter send now · Tab send next")- expect(ui.composerFrame.height).toBe(3)- const shimmerColors = new Set(- status.content.chunks- .slice(0, "Thinking".length)- .map((chunk) => chunk.fg?.toInts().join(",")),- )- expect(shimmerColors.size).toBeGreaterThan(1)- expect([...shimmerColors].some((value) => value?.startsWith("239,142,48"))).toBe(true)-- app.accept({- event: "message",- chat_id: "chat",- text: "running shell",- kind: "tool_hint",- tool_events: [{ phase: "start", name: "exec", arguments: { cmd: "pwd" } }],- })- await Bun.sleep(130)- await setup.renderOnce()- frame = setup.captureCharFrame()-- expect(frame).toMatch(/Working\s+0s/u)- expect(frame).not.toMatch(/[◐◓◑◒⠋⠙⠹⠸]/u)- expect(frame).toContain("› Running pwd")- expect(occurrences(frame, "pwd")).toBe(1)- expect(status.plainText).not.toContain("pwd")- app.accept({ event: "turn_end", chat_id: "chat" })- await setup.flush()- expect(ui.composer.placeholder).toBe("Ask nanobot anything")- })-- test("updates retry state in place and ends failed turns explicitly", async () => {- setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({ event: "attached", chat_id: "chat" })- app.accept({- event: "goal_status",- chat_id: "chat",- status: "running",- turn_id: "turn-1",- })- const ui = app as unknown as { status: { plainText: string } }-- app.accept({- event: "retry_status",- chat_id: "chat",- turn_id: "turn-1",- state: "waiting",- attempt: 1,- max_attempts: 4,- error_kind: "connection",- retry_after_s: 5,- })- expect(ui.status.plainText).toMatch(- /^Could not connect to the model provider · retrying in [45]s · attempt 1\/4/u,- )-- app.accept({- event: "retry_status",- chat_id: "chat",- turn_id: "turn-1",- state: "waiting",- attempt: 2,- max_attempts: 4,- error_kind: "connection",- retry_after_s: 3,- })- expect(ui.status.plainText).toContain("attempt 2/4")-- app.accept({- event: "retry_status",- chat_id: "chat",- turn_id: "turn-1",- state: "cleared",- attempt: 2,- max_attempts: 4,- error_kind: "connection",- })- expect(ui.status.plainText).not.toContain("retrying")-- app.accept({- event: "turn_end",- chat_id: "chat",- turn_id: "turn-1",- outcome: "failed",- failure_kind: "model",- failure_error_kind: "connection",- failure_attempts: 4,- failure_message: "Unlocalized server failure",- })- await setup.renderOnce()- const frame = setup.captureCharFrame()- const terminalFailure = "Could not connect to the model provider. The request still failed "- + "on attempt 4, so retries stopped. Check the provider configuration or service status, "- + "then try again."- expect(frame).toContain("Could not connect to the model provider.")- expect(frame.replace(/\s+/gu, " ")).toContain(terminalFailure)- expect(frame).not.toContain("Unlocalized server failure")- expect(frame).not.toContain("Last turn failed")- expect(ui.status.plainText).toBe("Ready")- })-- test("folds long tool traces without discarding their details", async () => {- setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({- event: "message",- chat_id: "chat",- text: "tool progress",- kind: "tool_hint",- tool_events: Array.from({ length: 10 }, (_, index) => ({- phase: "end",- call_id: `call-${index}`,- name: `tool_${index}`,- })),- })- await setup.renderOnce()- let frame = setup.captureCharFrame()-- expect(frame).toContain("7 earlier steps · Ctrl+O expand")- expect(frame).not.toContain("tool_0")- expect(frame).toContain("tool_7")- expect(frame).toContain("tool_9")-- setup.mockInput.pressKey("O", { ctrl: true })- await setup.renderOnce()- frame = setup.captureCharFrame()-- expect(frame).not.toContain("earlier steps")- expect(frame).toContain("tool_0")- expect(frame).toContain("tool_9")-- app.accept({ event: "turn_end", chat_id: "chat" })- app.accept({- event: "message",- chat_id: "chat",- text: "second tool group",- kind: "tool_hint",- tool_events: Array.from({ length: 8 }, (_, index) => ({- phase: "end",- call_id: `later-${index}`,- name: `later_${index}`,- })),- })- setup.mockInput.pressKey("O", { ctrl: true })- await setup.renderOnce()- const activities = [...(app as unknown as {- transcript: { activities: Set<{ expanded: boolean }> }- }).transcript.activities]-- expect(activities.map((activity) => activity.expanded)).toEqual([true, true])- setup.mockInput.pressKey("O", { ctrl: true })- await setup.renderOnce()- expect(activities.map((activity) => activity.expanded)).toEqual([true, false])- app.accept({ event: "turn_end", chat_id: "chat" })- })-- test("groups consecutive file activity only in the collapsed preview", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({- event: "message",- chat_id: "chat",- text: "file progress",- kind: "tool_hint",- tool_events: Array.from({ length: 6 }, (_, index) => ({- phase: "end" as const,- call_id: `read-${index}`,- name: "read_file",- arguments: { path: `/tmp/nanobot-workspace/src/file-${index}.ts` },- })),- })- await setup.renderOnce()- let frame = setup.captureCharFrame()-- expect(frame).toContain("6 steps · Ctrl+O expand")- expect(frame).toContain("✓ Read 6 files")- expect(frame).not.toContain("src/file-0.ts")-- setup.mockInput.pressKey("O", { ctrl: true })- await setup.renderOnce()- frame = setup.captureCharFrame()-- expect(frame).not.toContain("Read 6 files")- expect(frame).toContain("src/file-0.ts")- expect(frame).toContain("src/file-5.ts")- })-- test("supports keyboard transcript navigation without rebuilding the layout", async () => {- setup = await createRenderer({ width: 64, height: 16, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- for (let index = 0; index < 24; index += 1) {- app.accept({ event: "delta", chat_id: "chat", text: `answer ${index}` })- app.accept({ event: "stream_end", chat_id: "chat" })- }- await setup.flush()- const internals = app as unknown as {- status: { plainText: string }- transcript: {- root: {- scrollTop: number- scrollHeight: number- height: number- verticalScrollBar: { visible: boolean }- }- }- }- const scroll = internals.transcript.root-- setup.mockInput.pressKey("HOME", { ctrl: true })- await setup.renderOnce()- expect(scroll.scrollTop).toBe(0)-- app.accept({ event: "delta", chat_id: "chat", text: "new answer while reading above" })- app.accept({ event: "stream_end", chat_id: "chat" })- await setup.renderOnce()- expect(scroll.scrollTop).toBe(0)- expect(scroll.verticalScrollBar.visible).toBe(false)- expect(internals.status.plainText).toContain("Ctrl+End latest")-- setup.mockInput.pressKey("\u001B[6~")- await setup.renderOnce()- expect(scroll.scrollTop).toBeGreaterThan(0)-- setup.mockInput.pressKey("END", { ctrl: true })- await setup.renderOnce()- expect(scroll.scrollTop).toBeGreaterThanOrEqual(scroll.scrollHeight - scroll.height)- expect(scroll.verticalScrollBar.visible).toBe(false)- expect(internals.status.plainText).not.toContain("Ctrl+End latest")-- setup.mockInput.pressKey("HOME", { ctrl: true })- await waitUntil(() => internals.status.plainText.includes("Ctrl+End latest"))- expect(scroll.verticalScrollBar.visible).toBe(false)- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- await setup.renderOnce()- expect(scroll.verticalScrollBar.visible).toBe(false)- expect(internals.status.plainText).not.toContain("Ctrl+End latest")- })-- test("reconciles active state from attach hydration after reconnect", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = mount(setup)- const state = () => (app as unknown as { activeTurn: boolean }).activeTurn- app.accept({ event: "attached", chat_id: "chat" })- app.accept({ event: "delta", chat_id: "chat", text: "stale partial response" })- expect(state()).toBe(true)-- app.accept({ event: "attached", chat_id: "chat" })- await Bun.sleep(1)- await setup.flush()- expect(state()).toBe(false)- const restored = setup.captureCharFrame()- expect(restored).not.toContain("stale partial response")- expect(occurrences(restored, ">_ nanobot")).toBe(1)- app.accept({- event: "goal_status",- chat_id: "chat",- status: "running",- started_at: Date.now() / 1000 - 2,- })- expect(state()).toBe(true)- app.accept({ event: "goal_status", chat_id: "chat", status: "idle" })- expect(state()).toBe(false)- })-- test("shows actionable connection states without implementation details", async () => {- setup = await createRenderer({ width: 100, height: 20, screenMode: "alternate-screen" })- const app = mount(setup)- const ui = app as unknown as {- status: TextRenderable- handleStatus(- status: "starting" | "connecting" | "connected" | "reconnecting" | "unavailable" | "error",- detail?: string,- info?: {- endpoint: string- attempt: number- elapsedMs: number- health?: "ready" | "degraded" | "unreachable"- },- ): void- }-- ui.handleStatus("starting", undefined, {- endpoint: "127.0.0.1:8769",- attempt: 1,- elapsedMs: 0,- })- expect(ui.status.plainText).toBe("Getting ready…")-- ui.handleStatus("connecting")- expect(ui.status.plainText).toBe("Getting ready…")-- ui.handleStatus("connected")- expect(ui.status.plainText).toBe("Getting ready…")-- ui.handleStatus("error", "gateway sent an invalid event")- expect(ui.status.plainText).toBe("Getting ready…")- expect(ui.status.plainText).not.toContain("Unable")-- ui.handleStatus("reconnecting", "connection closed", {- endpoint: "127.0.0.1:8769",- attempt: 2,- elapsedMs: 800,- })- expect(ui.status.plainText).toBe("Resuming…")-- ui.handleStatus("reconnecting", "connection closed", {- endpoint: "127.0.0.1:8769",- attempt: 2,- elapsedMs: 900,- health: "degraded",- })- expect(ui.status.plainText).toBe("Resuming…")-- ui.handleStatus("unavailable", "connection refused", {- endpoint: "127.0.0.1:8769",- attempt: 7,- elapsedMs: 3_200,- health: "degraded",- })- expect(ui.status.plainText).toBe("Still getting ready…")- expect(ui.status.plainText).not.toContain("Unable")-- ui.handleStatus("unavailable", "connection refused", {- endpoint: "127.0.0.1:8769",- attempt: 8,- elapsedMs: 3_500,- health: "unreachable",- })- expect(ui.status.plainText).toBe("Nanobot is taking longer to respond…")- expect(ui.status.plainText).not.toContain("Unable")-- ui.handleStatus("error", "gateway bootstrap failed: HTTP 401", {- endpoint: "127.0.0.1:8769",- attempt: 9,- elapsedMs: 3_800,- })- expect(ui.status.plainText).toBe("Nanobot unavailable · restart nanobot")- expect(ui.status.plainText).not.toContain("gateway")- expect(ui.status.plainText).not.toContain("127.0.0.1")- expect(ui.status.plainText).not.toContain("HTTP")- expect(ui.status.plainText).not.toContain("attempt")- })-- test.each([- ["succeeded", "Conversation compacted"],- ["cancelled", "Conversation compaction cancelled"],- ] as const)("updates idle compaction in place to %s", async (phase, copy) => {- setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })- const app = mount(setup)- const ui = app as unknown as {- activeTurn: boolean- transcript: Transcript- composer: TextareaRenderable- }- ui.composer.setText("unfinished draft")- const event = { event: "context_compaction", chat_id: "chat", compaction_id: "idle" } as const- app.accept({ ...event, phase: "started" })- await setup.renderOnce()- expect(setup.captureCharFrame()).toContain("Compacting conversation…")- const rows = ui.transcript.root.getChildren()- app.accept({ ...event, phase })- app.accept({ ...event, phase })- app.accept({ ...event, phase: "started" })- app.accept({ ...event, chat_id: "another-chat", compaction_id: "other", phase: "failed" })- await setup.renderOnce()- const frame = setup.captureCharFrame()- expect(occurrences(frame, copy)).toBe(1)- expect(frame).not.toContain("Compacting conversation")- expect(frame).not.toContain("Could not compact")- expect(ui.transcript.root.getChildren()).toEqual(rows)- expect(ui.activeTurn).toBe(false)- expect(ui.composer.plainText).toBe("unfinished draft")- })-- test("keeps compaction separate from progress and streamed answers", async () => {- setup = await createRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })- const app = mount(setup)- app.accept({ event: "delta", chat_id: "chat", text: "Answer before " })- app.accept({ event: "message", chat_id: "chat", text: "First step", kind: "progress" })- const event = { event: "context_compaction", chat_id: "chat", compaction_id: "capacity" } as const- app.accept({ ...event, phase: "started" })- app.accept({ event: "message", chat_id: "chat", text: "Second step", kind: "progress" })- app.accept({ ...event, phase: "succeeded" })- app.accept({ event: "delta", chat_id: "chat", text: "and after compaction" })- expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(true)- app.accept({ event: "stream_end", chat_id: "chat" })- app.accept({ event: "turn_end", chat_id: "chat" })- await setup.flush()- const frame = setup.captureCharFrame()- expect(frame).toContain("Answer before and after compaction")- expect(frame.indexOf("First step")).toBeLessThan(frame.indexOf("Conversation compacted"))- expect(frame.indexOf("Conversation compacted")).toBeLessThan(frame.indexOf("Second step"))- expect(occurrences(frame, "Conversation compacted")).toBe(1)- })-- test("preserves compaction rows through pagination, theming, and session reset", async () => {- setup = await createRenderer({ width: 80, height: 28, screenMode: "alternate-screen" })- const app = mount(setup)- const ui = app as unknown as {- transcript: Transcript- palette: { error: string }- }- ui.transcript.history([- { role: "activity", content: "", compaction: { id: "recent", phase: "succeeded" } },- { role: "assistant", content: "Recent answer" },- ])- await setup.flush()- await ui.transcript.prependHistory([- { role: "assistant", content: "Earlier answer" },- { role: "activity", content: "", compaction: { id: "older", phase: "failed" } },- { role: "activity", content: "", compaction: { id: "recent", phase: "started" } },- ])- await setup.flush()- ui.transcript.scrollToEdge("top")- await setup.renderOnce()- const frame = setup.captureCharFrame()- expect(occurrences(frame, "Conversation compacted")).toBe(1)- expect(frame).not.toContain("Compacting conversation")- expect(frame).toContain("Earlier answer")- expect(frame.indexOf("Earlier answer")).toBeLessThan(frame.indexOf("Could not compact conversation"))- expect(frame).toContain("Recent answer")- expect(frame.indexOf("Could not compact conversation")).toBeLessThan(frame.indexOf("Recent answer"))- setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")- await setup.flush()- const failure = ui.transcript.root.getChildren()- .flatMap((row) => row.getChildren())- .find((child) => child instanceof TextRenderable && child.plainText.includes("Could not compact"))- expect(failure).toBeInstanceOf(TextRenderable)- expect((failure as TextRenderable).fg.toInts().slice(0, 3)).toEqual([- 1, 3, 5,- ].map((offset) => Number.parseInt(ui.palette.error.slice(offset, offset + 2), 16)))- ui.transcript.reset({ workspace: "workspace", version: "test" })- app.accept({ event: "context_compaction", chat_id: "chat", compaction_id: "recent", phase: "started" })- await setup.renderOnce()- expect(setup.captureCharFrame()).toContain("Compacting conversation…")- expect(setup.captureCharFrame()).not.toContain("Conversation compacted")- })-- test("deduplicates compaction history against events queued during hydration", async () => {- setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })- const original = globalThis.fetch- let resolveFetch: (value: Response) => void = () => undefined- globalThis.fetch = (() => new Promise<Response>((resolve) => {- resolveFetch = resolve- })) as unknown as typeof fetch- const app = NanobotTui.mount(- setup.renderer,- { ...options, apiUrl: "http://nanobot.test", apiToken: "token", chatId: "chat" },- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- try {- app.accept({ event: "attached", chat_id: "chat" })- const event = { event: "context_compaction", chat_id: "chat", compaction_id: "idle" } as const- app.accept({ ...event, phase: "started" })- app.accept({ ...event, phase: "succeeded" })- resolveFetch(Response.json({- schemaVersion: 3, projection: "events",- events: [{ event: "context_compaction", chat_id: "chat", compaction_id: "idle", phase: "succeeded" }],- }))- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- await setup.renderOnce()- const frame = setup.captureCharFrame()- expect(occurrences(frame, "Conversation compacted")).toBe(1)- expect(frame).not.toContain("Compacting conversation")- expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(false)- } finally {- globalThis.fetch = original- }- })-- test("replays events after asynchronous history hydration", async () => {- setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })- const original = globalThis.fetch- let resolveFetch: (value: Response) => void = () => undefined- globalThis.fetch = (() => new Promise<Response>((resolve) => {- resolveFetch = resolve- })) as unknown as typeof fetch- const app = NanobotTui.mount(- setup.renderer,- { ...options, apiUrl: "http://nanobot.test", apiToken: "token", chatId: "chat" },- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )-- try {- app.accept({ event: "attached", chat_id: "chat" })- app.accept({ event: "delta", chat_id: "chat", text: "live after reconnect" })- expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(false)- resolveFetch(new Response(JSON.stringify({- schemaVersion: 3, projection: "events",- events: [{ event: "stream_end", chat_id: "chat", text: "persisted before reconnect" }],- page: { has_more_before: false },- })))- await Bun.sleep(5)- await setup.flush()- const frame = setup.captureCharFrame()-- expect(frame.indexOf("persisted before reconnect")).toBeLessThan(- frame.indexOf("live after reconnect"),- )- expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(true)- app.accept({ event: "turn_end", chat_id: "chat" })- } finally {- globalThis.fetch = original- }- })-- test("blocks submission until reconnect history is hydrated", async () => {- const sent: string[] = []- setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })- const original = globalThis.fetch- let request = 0- let resolveReconnect: (value: Response) => void = () => undefined- globalThis.fetch = (() => {- request += 1- if (request === 1) {- return Promise.resolve(new Response(JSON.stringify({- schemaVersion: 3, projection: "events",- events: [{ event: "stream_end", chat_id: "chat", text: "initial history" }],- page: { has_more_before: false },- })))- }- return new Promise<Response>((resolve) => {- resolveReconnect = resolve- })- }) as unknown as typeof fetch- const app = NanobotTui.mount(- setup.renderer,- { ...options, apiUrl: "http://nanobot.test", apiToken: "token", chatId: "chat" },- client(sent),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- const ui = app as unknown as {- composer: TextareaRenderable- ready: boolean- status: TextRenderable- }- const composer = ui.composer-- try {- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => (app as unknown as { ready: boolean }).ready)- app.accept({ event: "attached", chat_id: "chat" })- composer.setText("sent during reconnect")- composer.submit()- await waitUntil(() => ui.status.plainText.includes("Not sent"))-- expect(sent).toEqual([])- expect(composer.plainText).toBe("sent during reconnect")- expect(ui.status.plainText).toContain("Not sent · press Enter to retry when ready")-- resolveReconnect(new Response(JSON.stringify({- schemaVersion: 3, projection: "events",- events: [{ event: "stream_end", chat_id: "chat", text: "restored history" }],- page: { has_more_before: false },- })))- await waitUntil(() => ui.ready)- expect(ui.status.plainText).toBe("Not sent · press Enter to retry")- composer.submit()- await waitUntil(() => sent.length === 1)- await setup.flush()- const frame = setup.captureCharFrame()-- expect(sent).toEqual(["sent during reconnect"])- expect(frame.indexOf("restored history")).toBeLessThan(frame.indexOf("sent during reconnect"))- } finally {- globalThis.fetch = original- }- })-- test("preserves drafts while a reconnected socket waits to attach", async () => {- const sent: string[] = []- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const app = mount(setup, sent)- const composer = (app as unknown as { composer: TextareaRenderable }).composer- const connection = app as unknown as {- ready: boolean- submitPending: boolean- handleStatus(- status: "reconnecting" | "connected",- detail?: string,- info?: { endpoint: string; attempt: number; elapsedMs: number },- ): void- }-- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => connection.ready)- connection.handleStatus("reconnecting", "connection closed", {- endpoint: "127.0.0.1:8769",- attempt: 1,- elapsedMs: 0,- })- connection.handleStatus("connected")- composer.setText("draft before attach")- composer.submit()- await waitUntil(() => !connection.submitPending)- composer.submit()- await waitUntil(() => !connection.submitPending)-- expect(sent).toEqual([])- expect(composer.plainText).toBe("draft before attach")-- app.accept({ event: "attached", chat_id: "chat" })- app.accept({ event: "attached", chat_id: "chat" })- await waitUntil(() => connection.ready)- expect(sent).toEqual([])- composer.submit()- await waitUntil(() => sent.length === 1)- app.accept({ event: "attached", chat_id: "chat" })- await Bun.sleep(5)-- expect(sent).toEqual(["draft before attach"])- })-- test("destroys the renderer and transport together", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- let closed = false- const exited: string[] = []- const transport = client()- transport.close = () => { closed = true }- const app = NanobotTui.mount(- setup.renderer,- {- ...options,- chatId: "original-chat",- onExit: (chatId) => {- expect(setup?.renderer.isDestroyed).toBe(true)- exited.push(chatId)- },- },- transport,- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )-- app.stop()- app.stop()-- expect(closed).toBe(true)- expect(setup.renderer.isDestroyed).toBe(true)- expect(exited).toEqual(["chat"])- })-- test("exits after Ctrl+C input dispatch completes on an idle empty composer", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- let closed = false- const transport = client()- transport.close = () => { closed = true }- NanobotTui.mount(- setup.renderer,- options,- transport,- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )-- setup.mockInput.pressCtrlC()-- expect(closed).toBe(false)- expect(setup.renderer.isDestroyed).toBe(false)- await waitUntil(() => closed)- expect(setup.renderer.isDestroyed).toBe(true)- })-- test("accepts the exit command before the gateway connection is ready", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- let closed = false- const transport = client()- transport.close = () => { closed = true }- const app = NanobotTui.mount(- setup.renderer,- options,- transport,- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- const composer = (app as unknown as { composer: TextareaRenderable }).composer-- composer.setText("exit")- composer.submit()- await waitUntil(() => closed)-- expect(setup.renderer.isDestroyed).toBe(true)- })-- test("discovers and runs the local /exit command", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const sent: string[] = []- let closed = false- const transport = client(sent)- transport.close = () => { closed = true }- const app = NanobotTui.mount(- setup.renderer,- options,- transport,- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- const ui = app as unknown as {- composer: TextareaRenderable- commandMenu: { visible: boolean }- }-- await setup.mockInput.typeText("/exit")- await setup.flush()- expect(ui.commandMenu.visible).toBe(true)- expect(setup.captureCharFrame()).toContain("/exit")-- expect(ui.composer.plainText).toBe("/exit")- ui.composer.submit()- await waitUntil(() => closed)-- expect(sent).toEqual([])- expect(setup.renderer.isDestroyed).toBe(true)- })-- test("detaches without sending a message or reporting a normal exit", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- const sent: string[] = []- const detached: string[] = []- const exited: string[] = []- let closed = false- const transport = client(sent)- transport.close = () => { closed = true }- const app = NanobotTui.mount(- setup.renderer,- {- ...options,- onDetach: (chatId) => { if (chatId) detached.push(chatId) },- onExit: (chatId) => { exited.push(chatId) },- },- transport,- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- const ui = app as unknown as {- composer: TextareaRenderable- commandMenu: { visible: boolean }- }-- await setup.mockInput.typeText("/detach")- await setup.flush()- expect(ui.commandMenu.visible).toBe(true)- expect(setup.captureCharFrame()).toContain("/detach")-- ui.composer.submit()- await waitUntil(() => closed)-- expect(sent).toEqual([])- expect(detached).toEqual(["chat"])- expect(exited).toEqual([])- expect(setup.renderer.isDestroyed).toBe(true)- })-- test("detaches before the gateway assigns a chat ID", async () => {- setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })- let detached = false- const transport = { ...client(), activeChatId: "" }- const app = NanobotTui.mount(- setup.renderer,- { ...options, onDetach: (chatId) => {- expect(chatId).toBeUndefined()- detached = true- } },- transport,- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- )- const composer = (app as unknown as { composer: TextareaRenderable }).composer-- composer.setText("/detach")- composer.submit()- await waitUntil(() => detached)-- expect(setup.renderer.isDestroyed).toBe(true)- })-})--describe("NanobotTui with a Herdr pane title reporter", () => {- test("keeps the full terminal experience while reporting task titles", async () => {- const setup = await createTestRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })- const titles: string[] = []- let released = false- const host: TuiHost = {- reportTitle(title) { titles.push(title) },- release() { released = true },- }- const app = NanobotTui.mount(- setup.renderer,- options,- client(),- new MockTreeSitterClient({ autoResolveTimeout: 0 }),- host,- )- const ui = app as unknown as {- composer: TextareaRenderable- composerFrame: BoxRenderable- }-- await setup.mockInput.typeText("/")- await setup.flush()- const commandFrame = setup.captureCharFrame()- expect(commandFrame).toContain("/sessions")- expect(commandFrame).toContain("/new-chat")- expect(commandFrame).toContain("/branch")- setup.mockInput.pressEscape()- ui.composer.setText("")-- app.accept({ event: "attached", chat_id: "chat" })- app.accept({- event: "user_message",- chat_id: "chat",- text: "Ship the Herdr integration",- turn_id: "turn-1",- starts_turn: true,- })- app.accept({- event: "message",- chat_id: "chat",- text: "",- kind: "tool_hint",- tool_events: [{ phase: "end", call_id: "read", name: "read_file", arguments: { path: "app.ts" } }],- })- await setup.flush()- const activeFrame = setup.captureCharFrame()- expect(activeFrame).toContain(">_ nanobot")- expect(activeFrame).toContain("default ▾")- expect(occurrences(activeFrame, "› Ship the Herdr integration")).toBe(1)- expect(occurrences(activeFrame, "app.ts")).toBe(1)- expect(ui.composer.placeholder).toBe("Enter send now · Tab send next")- expect(ui.composerFrame.height).toBe(3)- expect(titles).toEqual(["Ship the Herdr integration"])-- app.accept({- event: "turn_end",- chat_id: "chat",- turn_id: "turn-1",- goal_state: {- active: false,- status: "blocked",- ui_summary: "Approval required",- },- })- app.accept({- event: "user_message",- chat_id: "chat",- text: "Approved",- turn_id: "turn-2",- starts_turn: true,- })-- expect(titles).toEqual(["Ship the Herdr integration", "Approved"])-- app.stop()- expect(released).toBe(true)- })-})--if (process.platform !== "win32") {- test("restores the terminal after SIGTERM", async () => {- const child = Bun.spawn(["bun", "src/index.ts"], {- cwd: import.meta.dir.replace(/\/src$/u, ""),- env: {- ...process.env,- NANOBOT_TUI_WS_URL: "ws://127.0.0.1:9/ws",- NANOBOT_TUI_API_URL: "",- NANOBOT_TUI_API_TOKEN: "",- NANOBOT_TUI_CHAT_ID: "resume-chat",- NANOBOT_TUI_MODEL: "test/model",- NANOBOT_TUI_WORKSPACE: "/tmp/nanobot-test",- NANOBOT_TUI_VERSION: "test",- NANOBOT_TUI_ACCESS: "workspace access",- NANOBOT_TUI_THEME: "dark",- },- stdout: "pipe",- stderr: "pipe",- })- const decoder = new TextDecoder()- let output = ""- const collectOutput = (async () => {- const reader = child.stdout.getReader()- while (true) {- const { done, value } = await reader.read()- if (done) break- output += decoder.decode(value, { stream: true })- }- output += decoder.decode()- })()-- // Slow Intel runners can spend more than 250 ms importing OpenTUI. Wait- // for terminal setup, which happens after the signal handlers are- // registered, before exercising shutdown.- await waitUntil(() => output.includes("\x1b[?1049h"), 5_000)- child.kill("SIGTERM")- const exitCode = await child.exited- await collectOutput- const error = await new Response(child.stderr).text()-- expect(exitCode).toBe(0)- expect(error).toBe("")- expect(output).toContain("\x1b[?1049h")- expect(output).toContain("\x1b[?1049l")- expect(output.indexOf("\x1b[?1049l")).toBeLessThan(output.indexOf("Resume with:"))- expect(output).toContain(- "Resume with: nanobot agent --session websocket:resume-chat\n",- )- })-}diff --git a/tui/src/app-event-queue.test.ts b/tui/src/app/app-event-queue.test.tssimilarity index 98%rename from tui/src/app-event-queue.test.tsrename to tui/src/app/app-event-queue.test.tsindex 62f07063d..cf77e6152 100644--- a/tui/src/app-event-queue.test.ts+++ b/tui/src/app/app-event-queue.test.ts@@ -4,7 +4,7 @@ import type { TextareaRenderable } from "@opentui/core"import { createTestRenderer, MockTreeSitterClient } from "@opentui/core/testing"import { NanobotTui } from "./app"-import type { InboundEvent, NanobotClient } from "./protocol"+import type { InboundEvent, NanobotClient } from "../client"async function waitUntil(predicate: () => boolean): Promise<void> {const deadline = Date.now() + 2_000diff --git a/tui/src/app.ts b/tui/src/app/app.tssimilarity index 79%rename from tui/src/app.tsrename to tui/src/app/app.tsindex 8d0c193a3..f9ec367f7 100644--- a/tui/src/app.ts+++ b/tui/src/app/app.ts@@ -2,10 +2,8 @@ import {BoxRenderable,CliRenderEvents,RGBA,- StyledText,SyntaxStyle,TextareaRenderable,- TextAttributes,TextRenderable,createCliRenderer,decodePasteBytes,@@ -13,10 +11,8 @@ import {parseColor,stripAnsiSequences,type CliRenderer,- type ColorInput,type KeyEvent,type PasteEvent,- type TextChunk,type ThemeMode,type TreeSitterClient,} from "@opentui/core"@@ -44,486 +40,93 @@ import {type MentionCandidate,type MessageOptions,type RecoveryState,- type RetryStatus,type SkillCandidate,type SlashCommand,type SessionSummary,type TokenUsage,type WorkspaceScopePayload,-} from "./protocol"+} from "../client"import {CommandMenu,resolveSlashCommandLifecycle,- type CommandMenuTheme,type ResolvedSlashCommandLifecycle,- type TuiCommand,-} from "./command-menu"-import { SessionMenu, sessionLabel } from "./session-menu"-import { ContextPanel, formatTokenCount, type ContextPanelTheme } from "./context-panel"-import { UsagePanel, type UsagePanelTheme } from "./usage-panel"+} from "../menus/command-menu"+import { SessionMenu, sessionLabel } from "../menus/session-menu"+import { ContextPanel, formatTokenCount } from "../views/context-panel"+import { UsagePanel } from "../views/usage-panel"import {DiffViewer,latestTurnFileEdits,mergeFileEdits,- type DiffViewerTheme,-} from "./diff-viewer"-import {- Transcript,- type TranscriptNavigation,- type TranscriptTheme,-} from "./transcript"-import { ComposerDraft, MAX_DRAFT_IMAGES } from "./composer-draft"+} from "../views/diff-viewer"+import { Transcript, type TranscriptNavigation } from "../rendering/transcript"+import { ComposerDraft, MAX_DRAFT_IMAGES } from "../composer/composer-draft"import {createClipboardImageReader,type ClipboardImageReader,-} from "./clipboard-image"-import { BranchMenu, branchPoints } from "./branch-menu"+} from "../composer/clipboard-image"+import { BranchMenu, branchPoints } from "../menus/branch-menu"import {MentionMenu,insertMention,mentionOptions,mentionQuery,type MentionQuery,-} from "./mention-menu"+} from "../menus/mention-menu"import {insertSkill,SkillMenu,skillQuery,type SkillQuery,-} from "./skill-menu"-import { PromptQueue, type QueuedPrompt } from "./prompt-queue"-import { QueuePreview, type QueuePreviewTheme } from "./queue-preview"-import { RecoveryNotice, type RecoveryNoticeTheme } from "./recovery-notice"-import { RuntimeControls } from "./runtime-controls"+} from "../menus/skill-menu"+import { PromptQueue, type QueuedPrompt } from "../composer/prompt-queue"+import { QueuePreview } from "../composer/queue-preview"+import { RecoveryNotice } from "../views/recovery-notice"+import { RuntimeControls } from "../views/runtime-controls"import {contextualFooterHints,footerTelemetry,type FooterMode,- type FooterHintTheme,-} from "./footer-hints"-import { configureOpenTuiEnvironment, createTuiHost, type TuiHost } from "./host"--interface AppOptions {- resolveConnection?: () => Promise<GatewayConnection>- desktopGatewayId?: string- wsUrl?: string- bootstrapUrl?: string- bootstrapSecret?: string- healthUrl?: string- apiUrl: string- apiToken: string- chatId?: string- model: string- modelPreset: string- workspace: string- version: string- access: string- theme: "auto" | ThemeMode- onDetach?: (chatId?: string) => void- onExit?: (chatId: string) => void-}--interface ChatClient {- readonly activeChatId: string- connect(): void- close(): void- send(content: string, options?: MessageOptions): string- attach(chatId: string): void- newChat(scope?: WorkspaceScopePayload): void- forkChat?(sourceChatId: string, beforeUserIndex: number, title?: string): void- setWorkspaceScope(scope: WorkspaceScopePayload): void- updateRecovery(- action: "continue" | "dismiss",- chatId: string,- recoveryId: string,- ): Promise<RecoveryState>-}--interface Palette {- referenceBackground: string- text: ColorInput- muted: ColorInput- faint: ColorInput- border: ColorInput- accent: ColorInput- link: ColorInput- success: ColorInput- warning: ColorInput- error: ColorInput- user: ColorInput- userBackground: ColorInput- warm: ColorInput- cool: ColorInput-}--const DARK: Palette = {- referenceBackground: "#0E0F11",- text: "#ECEDEE",- muted: "#A1A1AA",- faint: "#71717A",- border: "#3F3F46",- accent: "#EF8E30",- link: "#60A5FA",- success: "#5CC489",- warning: "#F5C451",- error: "#F87171",- user: "#EF8E30",- // Codex-style turn anchor: 12% white over the reference dark background.- userBackground: "#2B2C2E",- warm: "#C26A25",- cool: "#1795A2",-}--const LIGHT: Palette = {- referenceBackground: "#FAFAFA",- text: "#18181B",- muted: "#6F6F78",- faint: "#8A8A94",- border: "#D4D4D8",- accent: "#B94D0B",- link: "#1D4ED8",- success: "#166534",- warning: "#A16207",- error: "#B91C1C",- user: "#B94D0B",- // Codex-style turn anchor: 4% black over the reference light background.- userBackground: "#F0F0F0",- warm: "#C2410C",- cool: "#0F766E",-}--// Until the terminal answers OSC 10/11, its default foreground is the only-// text color known to match its default background.-const TERMINAL: Palette = {- ...DARK,- text: RGBA.defaultForeground(),- muted: RGBA.defaultForeground(),- faint: RGBA.defaultForeground(),- border: RGBA.defaultForeground(),- accent: RGBA.defaultForeground(),- link: RGBA.defaultForeground(),- success: RGBA.defaultForeground(),- warning: RGBA.defaultForeground(),- error: RGBA.defaultForeground(),- user: RGBA.defaultForeground(),- userBackground: RGBA.defaultBackground(),- warm: RGBA.defaultForeground(),- cool: RGBA.defaultForeground(),-}+} from "../views/footer-hints"+import { copyWithSystemClipboard } from "../platform/clipboard"+import { configureOpenTuiEnvironment, createTuiHost, type TuiHost } from "../platform/host"+import { LOCAL_COMMANDS } from "./commands"+import { CooperativeEventQueue } from "./event-queue"+import {+ ACTIVE_COMPOSER_PLACEHOLDER,+ COMPACT_ACTIVE_COMPOSER_PLACEHOLDER,+ COMPOSER_PLACEHOLDER,+ createAppLayout,+} from "./layout"+import {+ connectionStatusText,+ formatElapsed,+ retryStatusLine,+ terminalModelFailureLine,+ type RenderedRetryStatus,+} from "./status"+import {+ DARK,+ IMAGE_PLACEHOLDER_STYLE,+ LIGHT,+ SHIMMER_INTERVAL_MS,+ TERMINAL,+ commandMenuTheme,+ composerSyntaxStyle,+ contextPanelTheme,+ diffViewerTheme,+ footerHintTheme,+ queuePreviewTheme,+ recoveryNoticeTheme,+ runtimeControlsTheme,+ shimmerStatus,+ transcriptTheme,+ usagePanelTheme,+ type Palette,+} from "./theme"+import type { AppOptions, ChatClient } from "./types"-const COMPOSER_PLACEHOLDER = "Ask nanobot anything"-const ACTIVE_COMPOSER_PLACEHOLDER = "Enter send now · Tab send next"-const COMPACT_ACTIVE_COMPOSER_PLACEHOLDER = "Enter now · Tab next"-// Transcript rows start one cell inside the shell; text follows their two-cell role marker.-const TRANSCRIPT_EDGE_INSET = 1-const TRANSCRIPT_TEXT_INSET = TRANSCRIPT_EDGE_INSET + 2-const IMAGE_PLACEHOLDER_STYLE = "image.placeholder"-const SHIMMER_PAUSE = 16-const SHIMMER_BAND = 4-const TERMINAL_SHIMMER_BAND = 1-const SHIMMER_INTERVAL_MS = 80-const EVENT_BATCH_SIZE = 64-const EVENT_BATCH_BUDGET_MS = 4const SESSION_REFRESH_INTERVAL_MS = 1_000-const LOCAL_COMMANDS: TuiCommand[] = [- {- command: "/sessions",- title: "Sessions",- description: "Find and switch conversations",- action: "sessions",- },- {- command: "/new-chat",- title: "New saved chat",- description: "Keep this conversation and start another",- action: "new-chat",- },- {- command: "/context",- title: "Agent context",- description: "Explain what this session contributes to the next prompt",- action: "context",- },- {- command: "/usage",- title: "Token usage",- description: "Show context occupancy and recent model-call input tokens",- action: "usage",- },- {- command: "/diff",- title: "Last turn diff",- description: "Inspect file changes from the latest turn",- action: "diff",- },- {- command: "/branch",- title: "Branch from reply",- description: "Continue from an earlier completed reply",- action: "branch",- },- {- command: "/detach",- title: "Detach",- description: "Close this terminal UI and keep the agent running",- action: "detach",- },- {- command: "/exit",- title: "Exit",- description: "Close this terminal UI",- action: "exit",- },-]--function syntaxStyle(palette: Palette): SyntaxStyle {- const color = (value: ColorInput) => {- const parsed = parseColor(value)- return { fg: parsed }- }- return SyntaxStyle.fromStyles({- default: color(palette.text),- keyword: { ...color(palette.accent), bold: true },- string: color(palette.success),- comment: { ...color(palette.muted), italic: true },- number: color(palette.link),- function: color(palette.warm),- type: color(palette.cool),- variable: color(palette.text),- property: color(palette.link),- "markup.heading": { ...color(palette.accent), bold: true },- "markup.strong": { ...color(palette.text), bold: true },- "markup.italic": { ...color(palette.muted), italic: true },- "markup.link": { ...color(palette.link), underline: true },- "markup.link.label": { ...color(palette.link), underline: true },- "markup.link.url": { ...color(palette.link), underline: true },- "markup.raw": color(palette.warm),- conceal: color(palette.faint),- })-}--function composerSyntaxStyle(palette: Palette): SyntaxStyle {- return SyntaxStyle.fromStyles({- [IMAGE_PLACEHOLDER_STYLE]: { fg: parseColor(palette.accent), bold: true },- })-}--function transcriptTheme(palette: Palette, backgroundKnown: boolean): TranscriptTheme {- return {- text: palette.text,- muted: palette.muted,- error: palette.error,- user: palette.user,- userBackground: backgroundKnown ? palette.userBackground : null,- border: palette.border,- syntax: syntaxStyle(palette),- }-}--function commandMenuTheme(palette: Palette): CommandMenuTheme {- return {- text: palette.text,- muted: palette.muted,- border: palette.border,- accent: palette.accent,- warning: palette.warning,- selectedBackground: palette.userBackground,- }-}--function runtimeControlsTheme(palette: Palette) {- return {- ...commandMenuTheme(palette),- accent: palette.accent,- faint: palette.faint,- }-}--function contextPanelTheme(palette: Palette): ContextPanelTheme {- return {- text: palette.text,- border: palette.border,- accent: palette.accent,- }-}--function usagePanelTheme(palette: Palette): UsagePanelTheme {- return { ...palette, cached: palette.cool }-}--function diffViewerTheme(palette: Palette, backgroundKnown: boolean): DiffViewerTheme {- const light = palette === LIGHT- return {- text: palette.text,- muted: palette.muted,- border: palette.border,- accent: palette.accent,- success: palette.success,- error: palette.error,- addedBackground: backgroundKnown ? light ? "#E7F6EC" : "#142D22" : null,- removedBackground: backgroundKnown ? light ? "#FCE8EA" : "#352024" : null,- syntax: syntaxStyle(palette),- }-}--function queuePreviewTheme(palette: Palette): QueuePreviewTheme {- return {- accent: palette.accent,- muted: palette.muted,- faint: palette.faint,- }-}--function recoveryNoticeTheme(palette: Palette): RecoveryNoticeTheme {- return {- text: palette.text,- muted: palette.muted,- border: palette.border,- accent: palette.accent,- warning: palette.warning,- error: palette.error,- }-}--function footerHintTheme(palette: Palette): FooterHintTheme {- return {- accent: palette.accent,- danger: palette.error,- muted: palette.muted,- separator: palette.faint,- }-}--function shimmerStatus(- label: string,- suffix: string,- frame: number,- palette: Palette,-): StyledText {- const chars = Array.from(label)- // Sweep immediately, then leave a quiet pause before repeating. The text- // keeps a constant width throughout, so the footer never jitters.- const position = frame % (chars.length + SHIMMER_PAUSE)- if (palette === TERMINAL) {- // Terminal-default colors cannot be interpolated without guessing the- // terminal theme, so move a bold band while preserving native color intent.- const foreground = parseColor(palette.text)- const chunks: TextChunk[] = chars.map((text, index) => ({- __isChunk: true,- text,- fg: foreground,- attributes: Math.abs(index - position) <= TERMINAL_SHIMMER_BAND- ? TextAttributes.BOLD- : 0,- }))- chunks.push({ __isChunk: true, text: suffix, fg: foreground })- return new StyledText(chunks)- }- const base = parseColor(palette.muted).toInts()- const highlight = parseColor(palette.accent).toInts()- const chunks: TextChunk[] = chars.map((text, index) => {- const distance = Math.abs(index - position)- const intensity = distance > SHIMMER_BAND- ? 0- : (1 + Math.cos(Math.PI * distance / SHIMMER_BAND)) / 2- return {- __isChunk: true,- text,- fg: RGBA.fromInts(- Math.round(base[0] + (highlight[0] - base[0]) * intensity),- Math.round(base[1] + (highlight[1] - base[1]) * intensity),- Math.round(base[2] + (highlight[2] - base[2]) * intensity),- ),- }- })- chunks.push({ __isChunk: true, text: suffix, fg: parseColor(palette.muted) })- return new StyledText(chunks)-}--function formatElapsed(milliseconds: number): string {- const seconds = Math.max(0, Math.floor(milliseconds / 1000))- if (seconds < 60) return `${seconds}s`- return `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, "0")}s`-}--function connectionStatusText(- status: ConnectionStatus,- info?: ConnectionStatusInfo,-): string {- if (["starting", "connecting", "connected"].includes(status)) return "Getting ready…"- if (status === "reconnecting") return "Resuming…"- if (status === "unavailable") {- return info?.health === "degraded"- ? "Still getting ready…"- : "Nanobot is taking longer to respond…"- }- if (status === "error") return "Nanobot unavailable · restart nanobot"- return "Session ended"-}--function retryFailureLabel(errorKind: string): string {- if (errorKind === "billing") return "Model provider quota is unavailable"- if (errorKind === "connection") return "Could not connect to the model provider"- if (errorKind === "timeout") return "Model provider request timed out"- if (errorKind === "rate_limit") return "Model provider rate limit reached"- if (errorKind === "server") return "Model provider service error"- return "Model provider request failed"-}--export function terminalModelFailureLine(errorKind?: string, attempts?: number): string {- const reason = retryFailureLabel(errorKind || "unknown")- if (errorKind === "billing") {- return `${reason}. Add credit or check billing for the provider account, then try again.`- }- const retryResult = typeof attempts === "number" && Number.isInteger(attempts) && attempts > 0- ? ` The request still failed on attempt ${attempts}, so retries stopped.`- : ""- return `${reason}.${retryResult} Check the provider configuration or service status, then try again.`-}--interface RenderedRetryStatus extends RetryStatus {- nextRetryAtMs?: number-}--function retryStatusLine(status: RenderedRetryStatus, nowMs = Date.now()): string {- const label = retryFailureLabel(status.error_kind)- if (status.state === "exhausted") return `${label} · ending turn`- if (status.state === "recovered") return "Connection restored"- if (status.state === "cleared") return "Retry status cleared"- const remaining = Math.max(- 0,- Math.ceil(((status.nextRetryAtMs ?? nowMs) - nowMs) / 1000),- )- const attempt = status.max_attempts- ? `${status.attempt}/${status.max_attempts}`- : String(status.attempt)- return `${label} · retrying in ${remaining}s · attempt ${attempt}`-}--export function sessionExitMessage(chatId: string): string {- const sessionId = `websocket:${chatId}`- return `Resume with: nanobot agent --session ${sessionId}\n`-}--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")-}-export class NanobotTui {private readonly renderer: CliRendererprivate readonly transcript: Transcript@@ -568,9 +171,7 @@ export class NanobotTui {private historyLoadingOlder = falseprivate attachedOnce = falseprivate pendingEvents: InboundEvent[] | null = null- private eventQueue: Array<InboundEvent | (() => void)> = []- private eventDrain: ReturnType<typeof setImmediate> | null = null- private followUpPending = false+ private readonly eventQueue: CooperativeEventQueue<InboundEvent>private hydrationId = 0private ready = falseprivate shimmerFrame = 0@@ -647,6 +248,10 @@ export class NanobotTui {: this.activeThemeMode === "light" ? LIGHT : DARKthis.composerSyntax = composerSyntaxStyle(this.palette)this.host = host+ this.eventQueue = new CooperativeEventQueue({+ dispatch: (event) => this.accept(event),+ paused: () => this.quitting || this.submitPending || Boolean(this.pendingEvents),+ })this.transcript = new Transcript(renderer,transcriptTheme(this.palette, this.backgroundKnown),@@ -716,52 +321,6 @@ export class NanobotTui {onStatus: (status, detail, info) => this.handleStatus(status, detail, info),})- // The terminal owns its canvas. Keeping the default-background intent is- // essential in embedded terminals, where painting our own near-black RGB- // only colors occupied cells and turns long output into dark strips.- this.renderer.setBackgroundColor(RGBA.defaultBackground())- this.shell = new BoxRenderable(renderer, {- id: "nanobot-tui-footer",- width: "100%",- height: "100%",- paddingLeft: 1,- paddingRight: 1,- flexDirection: "column",- backgroundColor: RGBA.defaultBackground(),- onMouseDown: (event) => {- if (event.button !== 0) return- if (!this.diffViewer.visible) {- // OpenTUI applies automatic focus after mouse handlers run. Prevent- // a focusable transcript ancestor from stealing text focus back- // after the composer has been restored here.- event.preventDefault()- this.composer.focus()- }- // Runtime pickers are transient popovers. A primary click anywhere- // outside their trigger or body dismisses them; hide() restores the- // composer focus through the shared visibility callback.- this.dismissRuntimeControls()- if (this.sessionLoading || this.sessionMenu.visible) {- this.closeSessions()- }- // Selection belongs to transcript/input content, never to empty chrome.- // Clearing it here prevents default-background cells from lingering as- // opaque blocks in terminals with differential repainting.- if (event.target && !event.target.selectable) {- this.renderer.clearSelection()- }- },- })- this.title = new BoxRenderable(renderer, {- id: "nanobot-tui-title",- width: "100%",- height: 1,- flexShrink: 0,- flexDirection: "row",- alignItems: "center",- paddingLeft: TRANSCRIPT_TEXT_INSET,- backgroundColor: RGBA.defaultBackground(),- })this.runtimeControls = new RuntimeControls(renderer,runtimeControlsTheme(this.palette),@@ -794,113 +353,55 @@ export class NanobotTui {},},)- this.title.add(this.runtimeControls.modelText)- this.title.add(this.runtimeControls.accessText)- this.title.add(this.runtimeControls.contextText)- const composerSurface = this.composerSurface()- this.composerFrame = new BoxRenderable(renderer, {- id: "nanobot-tui-composer-frame",- minHeight: 1,- flexShrink: 0,- marginLeft: TRANSCRIPT_EDGE_INSET,- border: ["left"],- borderColor: this.palette.accent,- paddingLeft: 1,- paddingRight: 1,- backgroundColor: composerSurface,- })- this.composer = new TextareaRenderable(renderer, {- id: "nanobot-tui-composer",- width: "100%",- minHeight: 1,- maxHeight: 8,- wrapMode: "word",- placeholder: COMPOSER_PLACEHOLDER,- placeholderColor: this.palette.muted,- textColor: this.palette.text,- focusedTextColor: this.palette.text,- backgroundColor: composerSurface,- focusedBackgroundColor: composerSurface,- cursorColor: this.palette.accent,- syntaxStyle: this.composerSyntax,- // A steady line cursor avoids the block-cell trails produced by some- // terminals when a retained full-screen UI redraws around the composer.- cursorStyle: { style: "line", blinking: false },- showCursor: true,- keyBindings: [- { name: "return", shift: true, action: "newline" },- { name: "return", meta: true, action: "newline" },- { name: "return", ctrl: true, action: "newline" },- { name: "j", ctrl: true, action: "newline" },- { name: "linefeed", action: "newline" },- { name: "return", action: "submit" },- ],- onCursorChange: () => {- this.keepComposerCursorOutsideImages()- if (!this.sessionMenu.visible && !this.branchMenu.visible) this.syncComposerMenus()+ const layout = createAppLayout(+ renderer,+ this.palette,+ this.composerSyntax,+ this.composerSurface(),+ {+ transcript: this.transcript,+ commandMenu: this.commandMenu,+ sessionMenu: this.sessionMenu,+ mentionMenu: this.mentionMenu,+ skillMenu: this.skillMenu,+ branchMenu: this.branchMenu,+ contextPanel: this.contextPanel,+ usagePanel: this.usagePanel,+ runtimeControls: this.runtimeControls,+ queuePreview: this.queuePreview,+ recoveryNotice: this.recoveryNotice,+ diffViewer: this.diffViewer,},- onContentChange: () => this.handleComposerContentChange(),- onMouseDown: () => queueMicrotask(() => this.keepComposerCursorOutsideImages()),- onMouseUp: () => queueMicrotask(() => this.keepComposerCursorOutsideImages()),- onMouseDrag: () => queueMicrotask(() => this.keepComposerCursorOutsideImages()),- onMouseDragEnd: () => queueMicrotask(() => this.keepComposerCursorOutsideImages()),- // IMEs may commit their final composed glyph after Enter. Matching the- // OpenCode/OpenTUI integration, defer twice before reading plainText.- onSubmit: () => this.deferSubmit(),- onPaste: (event) => {- this.flushSubmit()- if (!this.composer.isDestroyed) this.handlePaste(event)+ {+ onPrimaryMouseDown: () => {+ const restoreComposerFocus = !this.diffViewer.visible+ if (restoreComposerFocus) this.composer.focus()+ // Runtime pickers are transient popovers. A primary click anywhere+ // outside their trigger or body dismisses them; hide() restores the+ // composer focus through the shared visibility callback.+ this.dismissRuntimeControls()+ if (this.sessionLoading || this.sessionMenu.visible) this.closeSessions()+ return restoreComposerFocus+ },+ onComposerCursorChange: () => {+ this.keepComposerCursorOutsideImages()+ if (!this.sessionMenu.visible && !this.branchMenu.visible) this.syncComposerMenus()+ },+ onComposerContentChange: () => this.handleComposerContentChange(),+ onComposerPointer: () => this.keepComposerCursorOutsideImages(),+ onSubmit: () => this.deferSubmit(),+ onPaste: (event) => {+ this.flushSubmit()+ if (!this.composer.isDestroyed) this.handlePaste(event)+ },},- })- this.status = new TextRenderable(renderer, {- id: "nanobot-tui-status",- content: "Getting ready…",- fg: this.palette.muted,- height: 1,- width: "auto",- minWidth: 0,- flexGrow: 1,- flexShrink: 1,- selectable: false,- })- this.meta = new TextRenderable(renderer, {- id: "nanobot-tui-meta",- content: "",- fg: this.palette.faint,- height: 1,- width: "auto",- flexShrink: 1,- selectable: false,- })-- const statusRow = new BoxRenderable(renderer, {- id: "nanobot-tui-status-row",- width: "100%",- height: 1,- flexShrink: 0,- flexDirection: "row",- justifyContent: "space-between",- gap: 2,- paddingLeft: TRANSCRIPT_TEXT_INSET,- })- this.composerFrame.add(this.composer)- statusRow.add(this.status)- statusRow.add(this.meta)- this.shell.add(this.transcript.root)- this.shell.add(this.commandMenu.root)- this.shell.add(this.sessionMenu.root)- this.shell.add(this.mentionMenu.root)- this.shell.add(this.skillMenu.root)- this.shell.add(this.branchMenu.root)- this.shell.add(this.contextPanel.root)- this.shell.add(this.usagePanel.root)- this.shell.add(this.runtimeControls.menuRoot)- this.shell.add(this.title)- this.shell.add(this.queuePreview.root)- this.shell.add(this.recoveryNotice.root)- this.shell.add(this.composerFrame)- this.shell.add(statusRow)- this.shell.add(this.diffViewer.root)+ )+ this.shell = layout.shell+ this.title = layout.title+ this.composerFrame = layout.composerFrame+ this.composer = layout.composer+ this.status = layout.status+ this.meta = layout.metathis.renderer.root.add(this.shell)this.renderer.keyInput.on("keypress", this.handleKey)@@ -984,7 +485,7 @@ export class NanobotTui {try {if (!this.composer.isDestroyed) this.submit()} finally {- this.scheduleEventDrain()+ this.eventQueue.resume()}}@@ -1143,45 +644,11 @@ export class NanobotTui {private enqueueEvent(event: InboundEvent): void {if (this.quitting) returnif (event.event === "attached") {- this.clearEventQueue()+ this.eventQueue.clear()this.accept(event)return}- this.eventQueue.push(event)- this.scheduleEventDrain()- }-- private scheduleEventDrain(): void {- if (- this.eventDrain || this.quitting || this.submitPending- || this.pendingEvents || !this.eventQueue.length- ) return- this.eventDrain = setImmediate(() => {- this.eventDrain = null- const started = performance.now()- let processed = 0- // Yield between output batches so terminal input can run. Keep queued- // output paused until an IME-delayed submit has read the composer.- while (!this.submitPending && !this.quitting && processed < this.eventQueue.length) {- const event = this.eventQueue[processed++]!- if (typeof event === "function") event()- else this.accept(event)- if (processed >= EVENT_BATCH_SIZE || performance.now() - started >= EVENT_BATCH_BUDGET_MS) break- }- this.eventQueue.splice(0, processed)- this.scheduleEventDrain()- if (!this.eventQueue.length && this.followUpPending) {- this.followUpPending = false- this.sendNextFollowUp()- }- })- }-- private clearEventQueue(): void {- if (this.eventDrain) clearImmediate(this.eventDrain)- this.eventDrain = null- this.eventQueue = []- this.followUpPending = false+ this.eventQueue.enqueue(event)}accept(event: InboundEvent): void {@@ -1474,8 +941,8 @@ export class NanobotTui {private flushPendingEvents(): void {const events = this.pendingEventsthis.pendingEvents = null- if (events?.length) this.eventQueue = [...events, ...this.eventQueue]- this.scheduleEventDrain()+ if (events?.length) this.eventQueue.prepend(events)+ else this.eventQueue.resume()}private clearRecoveryState(): void {@@ -1596,8 +1063,7 @@ export class NanobotTui {// Render already-received output before the disconnect notice, but block// submissions immediately when the transport becomes unavailable.if (this.eventQueue.length) {- this.eventQueue.push(() => this.applyStatus(status, info))- this.scheduleEventDrain()+ this.eventQueue.enqueueTask(() => this.applyStatus(status, info))return}this.applyStatus(status, info)@@ -1705,7 +1171,7 @@ export class NanobotTui {if (!this.ready || this.activeTurn || this.quitting) return// Hydration may have queued an active-turn snapshot for this session.if (this.eventQueue.length) {- this.followUpPending = true+ this.eventQueue.whenIdle(() => this.sendNextFollowUp())return}const prompt = this.promptQueue.takeFollowUp()@@ -3089,7 +2555,7 @@ export class NanobotTui {private handleDestroy = (): void => {this.quitting = true- this.clearEventQueue()+ this.eventQueue.clear()this.usageRequest?.abort()this.clipboardPasteGeneration += 1if (this.shimmerTimer) clearInterval(this.shimmerTimer)@@ -3103,4 +2569,5 @@ export class NanobotTui {}}-export type { AppOptions }+export { sessionExitMessage, terminalModelFailureLine } from "./status"+export type { AppOptions } from "./types"diff --git a/tui/src/app/commands.ts b/tui/src/app/commands.tsnew file mode 100644index 000000000..e2f7961b9--- /dev/null+++ b/tui/src/app/commands.ts@@ -0,0 +1,52 @@+import type { TuiCommand } from "../menus/command-menu"++export const LOCAL_COMMANDS: TuiCommand[] = [+ {+ command: "/sessions",+ title: "Sessions",+ description: "Find and switch conversations",+ action: "sessions",+ },+ {+ command: "/new-chat",+ title: "New saved chat",+ description: "Keep this conversation and start another",+ action: "new-chat",+ },+ {+ command: "/context",+ title: "Agent context",+ description: "Explain what this session contributes to the next prompt",+ action: "context",+ },+ {+ command: "/usage",+ title: "Token usage",+ description: "Show context occupancy and recent model-call input tokens",+ action: "usage",+ },+ {+ command: "/diff",+ title: "Last turn diff",+ description: "Inspect file changes from the latest turn",+ action: "diff",+ },+ {+ command: "/branch",+ title: "Branch from reply",+ description: "Continue from an earlier completed reply",+ action: "branch",+ },+ {+ command: "/detach",+ title: "Detach",+ description: "Close this terminal UI and keep the agent running",+ action: "detach",+ },+ {+ command: "/exit",+ title: "Exit",+ description: "Close this terminal UI",+ action: "exit",+ },+]diff --git a/tui/src/app/composer.test.ts b/tui/src/app/composer.test.tsnew file mode 100644index 000000000..3becc829b--- /dev/null+++ b/tui/src/app/composer.test.ts@@ -0,0 +1,761 @@+import { afterEach, describe, expect, test } from "bun:test"+import { StyledText, TextareaRenderable, TextAttributes, TextRenderable } from "@opentui/core"+import { MockTreeSitterClient, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"+import { NanobotTui } from "./app"+import type { MessageOptions, SkillCandidate, SlashCommand } from "../client"+import type { ClipboardImageReader } from "../composer/clipboard-image"+import { options, client, mount, waitUntil, occurrences } from "./test-support"++describe("NanobotTui composer", () => {+ let setup: TestRendererSetup | undefined++ afterEach(() => {+ if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()+ setup = undefined+ })++ const createRenderer = (rendererOptions: Parameters<typeof createTestRenderer>[0]) => (+ createTestRenderer(rendererOptions)+ )+ test("waits for an IME commit before reading the submitted text", async () => {+ const sent: string[] = []+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup, sent)+ app.accept({ event: "attached", chat_id: "chat" })+ await Bun.sleep(1)+ const composer = (app as unknown as { composer: TextareaRenderable }).composer++ composer.setText("你")+ composer.submit()+ setTimeout(() => composer.setText("你好"), 0)+ await waitUntil(() => sent.length > 0)++ expect(sent).toEqual(["你好"])+ })++ test("keeps input typed immediately after Enter in the next draft", async () => {+ const sent: string[] = []+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup, sent)+ app.accept({ event: "attached", chat_id: "chat" })+ await Bun.sleep(1)+ const composer = (app as unknown as { composer: TextareaRenderable }).composer++ composer.setText("first")+ setup.mockInput.pressEnter()+ for (const key of "next") setup.mockInput.pressKey(key)+ await waitUntil(() => sent.length > 0)++ expect(sent).toEqual(["first"])+ expect(composer.plainText).toBe("next")+ })++ test("inserts newlines with Shift+Enter and the universal Ctrl+J fallback", async () => {+ const sent: string[] = []+ setup = await createRenderer({+ width: 72,+ height: 20,+ screenMode: "alternate-screen",+ kittyKeyboard: true,+ })+ const app = mount(setup, sent)+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ const ui = app as unknown as {+ composer: TextareaRenderable+ composerFrame: { height: number }+ }++ await setup.mockInput.typeText("first")+ setup.mockInput.pressEnter({ shift: true })+ await setup.mockInput.typeText("second")+ setup.mockInput.pressKey("j", { ctrl: true })+ await setup.mockInput.typeText("third")+ await setup.flush()++ expect(ui.composer.plainText).toBe("first\nsecond\nthird")+ expect(sent).toEqual([])+ expect(ui.composerFrame.height).toBeGreaterThanOrEqual(3)+ })++ test("clears the placeholder on the first typed character", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup)+ const composer = (app as unknown as { composer: TextareaRenderable }).composer+ await setup.renderOnce()+ expect(setup.captureCharFrame()).toContain("Ask nanobot anything")++ setup.mockInput.typeText("bu")+ await setup.flush()+ const frame = setup.captureCharFrame()++ expect(composer.plainText).toBe("bu")+ expect(composer.placeholder).toBeNull()+ expect(frame).toContain("bu")+ expect(frame).not.toContain("Ask nanobot anything")+ expect(frame).not.toContain("buAsk nanobot anything")++ setup.mockInput.pressBackspace()+ setup.mockInput.pressBackspace()+ await setup.flush()+ expect(composer.placeholder).toBe("Ask nanobot anything")+ expect(setup.captureCharFrame()).toContain("Ask nanobot anything")+ })++ test("compacts large pastes in the composer without changing the sent text", async () => {+ const sent: string[] = []+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup, sent)+ app.accept({ event: "attached", chat_id: "chat" })+ await Bun.sleep(1)+ const ui = app as unknown as {+ composer: TextareaRenderable+ status: { plainText: string }+ }+ const pasted = Array.from({ length: 12 }, (_, index) => `line ${index + 1}`).join("\n")++ await setup.mockInput.pasteBracketedText(pasted)+ await setup.flush()+ expect(ui.composer.plainText).toBe("[Pasted 12 lines] ")+ expect(ui.status.plainText).toContain("Pasted 12 lines")++ ui.composer.submit()+ await waitUntil(() => sent.length === 1)+ expect(sent).toEqual([pasted])+ expect(ui.composer.plainText).toBe("")+ })++ test("pastes clipboard images into removable placeholders and sends their data", async () => {+ const sent: string[] = []+ const sentOptions: MessageOptions[] = []+ let disposed = false+ const clipboard: ClipboardImageReader = {+ read: async () => ({+ mimeType: "image/png",+ dataUrl: "data:image/png;base64,AAEC/w==",+ }),+ dispose: async () => { disposed = true },+ }+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const transport = client(sent, [], [], sentOptions)+ const recordSend = transport.send+ transport.send = (content, messageOptions) => {+ recordSend(content, messageOptions)+ return `image-turn-${sent.length}`+ }+ const app = NanobotTui.mount(+ setup.renderer,+ options,+ transport,+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ undefined,+ clipboard,+ )+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ const ui = app as unknown as {+ composer: TextareaRenderable+ draft: { imageCount: number }+ promptHistory: string[]+ status: { plainText: string }+ transcript: {+ userMessages: Set<{ renderable: TextRenderable }>+ }+ }++ setup.mockInput.pressKey("v", { ctrl: true })+ await waitUntil(() => ui.composer.plainText === "[Image #1] ")+ expect(ui.status.plainText).toContain("Pasted Image #1")+ const placeholderStyle = ui.composer.syntaxStyle?.getStyle("image.placeholder")+ expect(placeholderStyle?.bold).toBeTrue()+ expect(placeholderStyle?.fg?.intent).toBe("default")+ const placeholderStyleId = ui.composer.syntaxStyle?.getStyleId("image.placeholder")+ if (placeholderStyleId === null || placeholderStyleId === undefined) {+ throw new Error("image placeholder style was not registered")+ }+ expect(ui.composer.getLineHighlights(0)).toEqual([{+ start: 0,+ end: 10,+ styleId: placeholderStyleId,+ priority: 100,+ hlRef: 0,+ }])+ ui.composer.setText("")+ await waitUntil(() => ui.draft.imageCount === 0)+ expect(ui.composer.getLineHighlights(0)).toEqual([])++ setup.mockInput.pressKey("v", { ctrl: true })+ await waitUntil(() => ui.composer.plainText === "[Image #1] ")+ await setup.mockInput.typeText("[Image #1]")+ ui.composer.submit()+ await waitUntil(() => ui.status.plainText.includes("Duplicate image placeholder"))+ expect(sent).toEqual([])+ ui.composer.setText("[Image #1]")+ ui.composer.submit()+ await waitUntil(() => sent.length === 1)+ expect(sent).toEqual([""])+ expect(ui.promptHistory).toEqual([])+ expect(sentOptions[0]?.media).toEqual([{+ data_url: "data:image/png;base64,AAEC/w==",+ name: "clipboard-image-1.png",+ }])+ expect(sentOptions[0]).not.toHaveProperty("displayContent")+ await setup.flush()+ const frame = setup.captureCharFrame()+ expect(frame).toContain("[Image #1]")+ expect(frame).not.toContain("clipboard-image-1.png")+ const userContent = [...ui.transcript.userMessages].at(-1)?.renderable.content+ expect(userContent).toBeInstanceOf(StyledText)+ const imageChunk = (userContent as StyledText).chunks.find(({ text }) => text === "[Image #1]")+ expect(imageChunk?.attributes).toBe(TextAttributes.BOLD)+ expect(imageChunk?.fg?.intent).toBe("default")++ await setup.mockInput.typeText("这是什么? ")+ setup.mockInput.pressKey("v", { ctrl: true })+ await waitUntil(() => ui.composer.plainText === "这是什么? [Image #1] ")+ setup.mockInput.pressTab()+ expect(ui.status.plainText).toContain("Images cannot be queued")+ expect(ui.composer.plainText).toBe("这是什么? [Image #1] ")+ ui.composer.submit()+ await waitUntil(() => sent.length === 2)+ expect(sent[1]).toBe("这是什么?")+ expect(sentOptions[1]?.media).toHaveLength(1)+ expect(sentOptions[1]).not.toHaveProperty("displayContent")+ await setup.flush()+ expect(setup.captureCharFrame()).toContain("这是什么? [Image #1]")++ setup.renderer.destroy()+ expect(disposed).toBeTrue()+ })++ test("keeps image placeholders atomic for cursor movement and deletion", async () => {+ const clipboard: ClipboardImageReader = {+ read: async () => ({+ mimeType: "image/png",+ dataUrl: "data:image/png;base64,AAEC/w==",+ }),+ dispose: async () => undefined,+ }+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = NanobotTui.mount(+ setup.renderer,+ options,+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ undefined,+ clipboard,+ )+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ const ui = app as unknown as {+ composer: TextareaRenderable+ draft: { imageCount: number }+ status: { plainText: string }+ }++ setup.mockInput.pressKey("v", { ctrl: true })+ await waitUntil(() => ui.composer.plainText === "[Image #1] ")+ await setup.flush()+ await setup.mockMouse.click(ui.composer.x + 5, ui.composer.y)+ expect(ui.composer.cursorOffset > 0 && ui.composer.cursorOffset < 10).toBeFalse()+ ui.composer.cursorOffset = 0+ setup.mockInput.pressArrow("right")+ await waitUntil(() => ui.composer.cursorOffset === 10)+ setup.mockInput.pressArrow("left")+ await waitUntil(() => ui.composer.cursorOffset === 0)++ setup.mockInput.pressArrow("right", { shift: true })+ await waitUntil(() => ui.composer.cursorOffset === 10)+ await setup.mockInput.typeText("replacement")+ await waitUntil(() => ui.draft.imageCount === 0)+ expect(ui.composer.plainText).toContain("replacement")+ expect(ui.composer.plainText).not.toContain("Image #1")++ ui.composer.setText("")+ setup.mockInput.pressKey("v", { ctrl: true })+ await waitUntil(() => ui.composer.plainText === "[Image #1] ")+ ui.composer.cursorOffset = 10+ setup.mockInput.pressArrow("left", { shift: true })+ await waitUntil(() => ui.composer.cursorOffset === 0)+ await setup.mockInput.typeText("replacement")+ await waitUntil(() => ui.draft.imageCount === 0)+ expect(ui.composer.plainText).toContain("replacement")+ expect(ui.composer.plainText).not.toContain("Image #1")++ ui.composer.setText("")+ setup.mockInput.pressKey("v", { ctrl: true })+ await waitUntil(() => ui.composer.plainText === "[Image #1] ")+ ui.composer.cursorOffset = 0+ setup.mockInput.pressKey("DELETE")+ await waitUntil(() => ui.draft.imageCount === 0)+ expect(ui.composer.plainText.trim()).toBe("")+ expect(ui.status.plainText).toContain("Removed Image #1")++ ui.composer.setText("")+ setup.mockInput.pressKey("v", { ctrl: true })+ await waitUntil(() => ui.composer.plainText === "[Image #1] ")+ ui.composer.cursorOffset = 10+ setup.mockInput.pressBackspace()+ await waitUntil(() => ui.draft.imageCount === 0)+ expect(ui.composer.plainText.trim()).toBe("")++ ui.composer.setText("")+ setup.mockInput.pressKey("v", { ctrl: true })+ await waitUntil(() => ui.composer.plainText === "[Image #1] ")+ ui.composer.setText("Image #1] ")+ await waitUntil(() => ui.draft.imageCount === 0)+ expect(ui.composer.plainText.trim()).toBe("")+ })++ test("keeps clipboard failures visible while an agent turn is active", async () => {+ const sent: string[] = []+ const clipboard: ClipboardImageReader = {+ read: async () => { throw new Error("No image in clipboard") },+ dispose: async () => undefined,+ }+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = NanobotTui.mount(+ setup.renderer,+ options,+ client(sent),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ undefined,+ clipboard,+ )+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ const composer = (app as unknown as { composer: TextareaRenderable }).composer+ composer.setText("start")+ composer.submit()+ await waitUntil(() => sent.length === 1)++ setup.mockInput.pressKey("v", { ctrl: true })+ await waitUntil(() => setup?.captureCharFrame().includes("No image in clipboard") === true)+ })++ test("keeps image placeholders out of command arguments", async () => {+ const sent: string[] = []+ const clipboard: ClipboardImageReader = {+ read: async () => ({+ mimeType: "image/png",+ dataUrl: "data:image/png;base64,AAEC/w==",+ }),+ dispose: async () => undefined,+ }+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = NanobotTui.mount(+ setup.renderer,+ options,+ client(sent),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ undefined,+ clipboard,+ )+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ const ui = app as unknown as {+ composer: TextareaRenderable+ status: { plainText: string }+ commandMenu: { setCommands(commands: SlashCommand[]): void }+ }+ ui.commandMenu.setCommands([{+ command: "/model",+ title: "Model",+ description: "Show or switch model presets",+ argHint: "[preset]",+ lifecycle: "side_channel",+ acceptsArgs: true,+ }])++ await setup.mockInput.typeText("/model ")+ setup.mockInput.pressKey("v", { ctrl: true })+ await waitUntil(() => ui.composer.plainText === "/model [Image #1] ")+ ui.composer.submit()+ await waitUntil(() => ui.status.plainText.includes("Images cannot be used with commands"))++ expect(sent).toEqual([])+ expect(ui.composer.plainText).toBe("/model [Image #1] ")+ })++ test("ignores a clipboard result that finishes after the renderer is destroyed", async () => {+ let resolveRead: ((image: {+ mimeType: "image/png"+ dataUrl: string+ }) => void) | undefined+ let disposed = false+ const clipboard: ClipboardImageReader = {+ read: () => new Promise((resolve) => { resolveRead = resolve }),+ dispose: async () => { disposed = true },+ }+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = NanobotTui.mount(+ setup.renderer,+ options,+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ undefined,+ clipboard,+ )+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)++ setup.mockInput.pressKey("v", { ctrl: true })+ await waitUntil(() => resolveRead !== undefined)+ setup.renderer.destroy()+ resolveRead?.({ mimeType: "image/png", dataUrl: "data:image/png;base64,AAAA" })+ await Bun.sleep(10)+ expect(disposed).toBeTrue()+ })++ test("steers with Enter, queues with Tab, and restores queued text with Alt+Up", async () => {+ const sent: string[] = []+ const sentOptions: MessageOptions[] = []+ setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })+ const app = NanobotTui.mount(+ setup.renderer,+ options,+ client(sent, [], [], sentOptions),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ app.accept({ event: "attached", chat_id: "chat" })+ const ui = app as unknown as {+ ready: boolean+ composer: TextareaRenderable+ mentionCandidates: Array<Record<string, unknown>>+ queuePreview: { root: { visible: boolean } }+ status: { plainText: string }+ }+ await waitUntil(() => ui.ready)+ ui.mentionCandidates = [{+ kind: "cli",+ name: "github",+ displayName: "GitHub",+ description: "CLI",+ }]++ ui.composer.setText("first")+ ui.composer.submit()+ await waitUntil(() => sent.length === 1)+ expect(ui.composer.placeholder).toBe("Enter send now · Tab send next")++ ui.composer.setText("one more detail")+ await setup.flush()+ expect(ui.composer.placeholder).toBeNull()++ ui.composer.setText("ask @github next")+ ui.composer.submit()+ await waitUntil(() => sent.length === 2)+ expect(ui.status.plainText).not.toContain("Steering")+ expect(ui.composer.placeholder).toBe("Enter send now · Tab send next")+ expect(sentOptions[1]).toEqual({+ cliApps: [{ name: "github" }],+ mcpPresets: [],+ sessionMentions: [],+ })++ ui.composer.setText("after this turn")+ setup.mockInput.pressTab()+ await waitUntil(() => ui.composer.plainText === "")+ expect(sent).toHaveLength(2)+ expect(ui.queuePreview.root.visible).toBeTrue()++ setup.mockInput.pressArrow("up", { meta: true })+ expect(ui.composer.plainText).toBe("after this turn")+ expect(ui.queuePreview.root.visible).toBeFalse()+ setup.mockInput.pressTab()+ await waitUntil(() => ui.composer.plainText === "")++ app.accept({+ event: "error",+ chat_id: "chat",+ turn_id: "failed-steering",+ reason: "steering rejected",+ })+ expect((app as unknown as { activeTurn: boolean }).activeTurn).toBeTrue()++ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => ui.ready)+ app.accept({ event: "goal_status", chat_id: "chat", status: "running", turn_id: "turn" })+ app.accept({ event: "turn_end", chat_id: "chat", turn_id: "turn" })+ await waitUntil(() => sent.length === 3)+ expect(sent[2]).toBe("after this turn")+ expect(ui.queuePreview.root.visible).toBeFalse()+ app.accept({ event: "goal_status", chat_id: "chat", status: "idle", turn_id: "prior" })+ expect((app as unknown as { activeTurn: boolean }).activeTurn).toBeTrue()+ })++ test("projects user turns from another terminal without duplicating replayed history", async () => {+ setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)++ const first = {+ event: "user_message" as const,+ chat_id: "chat",+ text: "hello from terminal A",+ turn_id: "remote-turn",+ active_turn_id: "remote-turn",+ starts_turn: true,+ started_at: 1_700_000_000,+ media_urls: [{+ kind: "file" as const,+ url: "/api/media/sig/report",+ name: "report.pdf",+ }],+ }+ app.accept(first)+ app.accept(first)+ app.accept({+ event: "user_message",+ chat_id: "chat",+ text: "one more remote detail",+ turn_id: "remote-steer",+ active_turn_id: "remote-turn",+ starts_turn: false,+ media_urls: [{+ kind: "image",+ url: "/api/media/sig/image",+ name: "clipboard-image-2.png",+ }],+ })+ await setup.flush()++ const state = app as unknown as { activeTurn: boolean; activeTurnId: string | null }+ const frame = setup.captureCharFrame()+ expect(occurrences(frame, "hello from terminal A")).toBe(1)+ expect(occurrences(frame, "Attachments: report.pdf")).toBe(1)+ expect(occurrences(frame, "one more remote detail")).toBe(1)+ expect(occurrences(frame, "[Image #2]")).toBe(1)+ expect(frame).toContain("one more remote detail [Image #2]")+ expect(frame).not.toContain("clipboard-image-2.png")+ expect(state.activeTurn).toBeTrue()+ expect(state.activeTurnId).toBe("remote-turn")++ app.accept({ event: "turn_end", chat_id: "chat", turn_id: "remote-turn" })+ expect(state.activeTurn).toBeFalse()+ })++ test("reconciles simultaneous submits to the gateway-owned turn", async () => {+ const sent: string[] = []+ setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })+ const app = mount(setup, sent)+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)++ const ui = app as unknown as {+ composer: TextareaRenderable+ activeTurn: boolean+ activeTurnId: string | null+ }+ ui.composer.setText("submitted from terminal B")+ ui.composer.submit()+ await waitUntil(() => sent.length === 1)+ expect(ui.activeTurnId).toBe("turn")++ app.accept({+ event: "message_accepted",+ chat_id: "chat",+ turn_id: "turn",+ active_turn_id: "terminal-a-turn",+ starts_turn: false,+ started_at: 1_700_000_000,+ })++ expect(ui.activeTurn).toBeTrue()+ expect(ui.activeTurnId).toBe("terminal-a-turn")+ })++ test("recalls submitted prompts without stealing multiline cursor movement", async () => {+ const sent: string[] = []+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup, sent)+ app.accept({ event: "attached", chat_id: "chat" })+ await Bun.sleep(1)+ const composer = (app as unknown as { composer: TextareaRenderable }).composer+ for (const [index, value] of ["first prompt", "second prompt"].entries()) {+ composer.setText(value)+ composer.submit()+ await waitUntil(() => sent.length === index + 1)+ app.accept({ event: "turn_end", chat_id: "chat" })+ }++ setup.mockInput.pressArrow("up")+ expect(composer.plainText).toBe("second prompt")+ setup.mockInput.pressArrow("up")+ expect(composer.plainText).toBe("first prompt")+ setup.mockInput.pressArrow("down")+ expect(composer.plainText).toBe("first prompt")+ setup.mockInput.pressArrow("down")+ expect(composer.plainText).toBe("second prompt")+ setup.mockInput.pressArrow("down")+ expect(composer.plainText).toBe("")++ setup.resize(36, 20)+ const wrapped = "这是一段会在狭窄输入框中自动换行而不是显式换行的中文内容"+ composer.setText(wrapped)+ composer.cursorOffset = wrapped.length+ await setup.renderOnce()+ expect(composer.virtualLineCount).toBeGreaterThan(1)++ setup.mockInput.pressArrow("up")+ expect(composer.plainText).toBe(wrapped)+ })++ test("discovers and completes gateway slash commands without sending them", async () => {+ setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })+ const sent: string[] = []+ const app = mount(setup, sent)+ const ui = app as unknown as {+ composer: TextareaRenderable+ commandMenu: {+ visible: boolean+ setCommands(commands: SlashCommand[]): void+ }+ }+ ui.commandMenu.setCommands([{+ command: "/history",+ title: "History",+ description: "Show recent messages",+ argHint: "[n]",+ lifecycle: "side_channel",+ acceptsArgs: true,+ }])++ await setup.mockInput.typeText("/h")+ expect(ui.commandMenu.visible).toBe(true)+ setup.mockInput.pressTab()++ expect(ui.composer.plainText).toBe("/history ")+ expect(ui.commandMenu.visible).toBe(false)+ expect(sent).toEqual([])+ })++ test("completes available skills with arrows, Enter, Tab, and Escape", async () => {+ setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })+ const sent: string[] = []+ const app = mount(setup, sent)+ const ui = app as unknown as {+ ready: boolean+ composer: TextareaRenderable+ skillCandidates: SkillCandidate[]+ skillMenu: { visible: boolean }+ }+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => ui.ready)+ ui.skillCandidates = [+ { name: "simplify", description: "Simplify code", source: "workspace" },+ { name: "verify", description: "Verify public behavior", source: "builtin" },+ ]++ await setup.mockInput.typeText("$")+ expect(ui.skillMenu.visible).toBe(true)+ setup.mockInput.pressArrow("down")+ setup.mockInput.pressEnter()+ await waitUntil(() => ui.composer.plainText === "$verify ")+ expect(ui.skillMenu.visible).toBe(false)+ expect(sent).toEqual([])++ ui.composer.setText("")+ await setup.mockInput.typeText("please $sim")+ expect(ui.skillMenu.visible).toBe(true)+ setup.mockInput.pressTab()+ expect(ui.composer.plainText).toBe("please $simplify ")+ expect(ui.skillMenu.visible).toBe(false)++ ui.composer.setText("")+ await setup.mockInput.typeText("$")+ expect(ui.skillMenu.visible).toBe(true)+ setup.mockInput.pressEscape()+ await waitUntil(() => !ui.skillMenu.visible)+ expect(ui.skillMenu.visible).toBe(false)+ expect(ui.composer.plainText).toBe("$")++ ui.composer.setText("")+ await setup.mockInput.typeText("请用 $ver")+ expect(ui.skillMenu.visible).toBe(true)+ setup.mockInput.pressTab()+ expect(ui.composer.plainText).toBe("请用 $verify ")+ await setup.mockInput.typeText("now")+ expect(ui.composer.plainText).toBe("请用 $verify now")++ ui.composer.setText("use $verify later")+ ui.composer.cursorOffset = 8+ await waitUntil(() => ui.skillMenu.visible)+ ui.composer.cursorOffset = ui.composer.plainText.length+ await waitUntil(() => !ui.skillMenu.visible)++ ui.composer.setText("")+ await setup.mockInput.typeText("$missing")+ expect(ui.skillMenu.visible).toBe(true)+ ui.composer.submit()+ await waitUntil(() => sent.length === 1)+ expect(sent).toEqual(["$missing"])+ expect(ui.skillMenu.visible).toBe(false)+ })++ test("does not queue unmatched skill text when Tab dismisses completion", async () => {+ setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })+ const sent: string[] = []+ const app = mount(setup, sent)+ const ui = app as unknown as {+ ready: boolean+ composer: TextareaRenderable+ skillCandidates: SkillCandidate[]+ skillMenu: { visible: boolean }+ queuePreview: { root: { visible: boolean } }+ }+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => ui.ready)+ ui.skillCandidates = [{+ name: "verify",+ description: "Verify public behavior",+ source: "builtin",+ }]++ ui.composer.setText("start an active turn")+ ui.composer.submit()+ await waitUntil(() => sent.length === 1)++ await setup.mockInput.typeText("$missing")+ expect(ui.skillMenu.visible).toBe(true)+ setup.mockInput.pressTab()++ expect(ui.composer.plainText).toBe("$missing")+ expect(ui.skillMenu.visible).toBe(false)+ expect(ui.queuePreview.root.visible).toBe(false)++ app.accept({ event: "turn_end", chat_id: "chat", turn_id: "turn" })+ await Bun.sleep(1)+ expect(sent).toEqual(["start an active turn"])+ })++ test("runs bang commands through the gateway without steering the agent", async () => {+ setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })+ const sent: string[] = []+ const sentOptions: MessageOptions[] = []+ const app = NanobotTui.mount(+ setup.renderer,+ options,+ client(sent, [], [], sentOptions),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ app.accept({ event: "attached", chat_id: "chat" })+ const ui = app as unknown as { ready: boolean; composer: TextareaRenderable; activeTurn: boolean }+ await waitUntil(() => ui.ready)++ app.accept({ event: "goal_status", chat_id: "chat", status: "running" })+ ui.composer.setText("!pwd")+ ui.composer.submit()++ await waitUntil(() => sent.length === 1)+ expect(sent).toEqual(["!pwd"])+ expect(sentOptions).toEqual([{ userShell: true }])+ expect(ui.activeTurn).toBe(true)++ app.accept({ event: "message", chat_id: "chat", text: "/tmp/project", turn_id: "turn" })+ await setup.flush()+ expect(setup.captureCharFrame()).toContain("/tmp/project")+ expect(ui.activeTurn).toBe(true)+ })+})diff --git a/tui/src/app/event-queue.ts b/tui/src/app/event-queue.tsnew file mode 100644index 000000000..8c63ac9d0--- /dev/null+++ b/tui/src/app/event-queue.ts@@ -0,0 +1,94 @@+type EventTask<T> =+ | { kind: "event"; event: T }+ | { kind: "task"; run: () => void }++interface CooperativeEventQueueOptions<T> {+ dispatch(event: T): void+ paused(): boolean+ batchSize?: number+ batchBudgetMs?: number+}++/**+ * Drains gateway events cooperatively so repaint and terminal input stay responsive.+ * A caller-owned pause predicate keeps IME submission and history hydration atomic.+ */+export class CooperativeEventQueue<T> {+ private readonly dispatch: (event: T) => void+ private readonly paused: () => boolean+ private readonly batchSize: number+ private readonly batchBudgetMs: number+ private items: Array<EventTask<T>> = []+ private drain: ReturnType<typeof setImmediate> | null = null+ private idleTask: (() => void) | null = null++ constructor(options: CooperativeEventQueueOptions<T>) {+ this.dispatch = options.dispatch+ this.paused = options.paused+ this.batchSize = options.batchSize ?? 64+ this.batchBudgetMs = options.batchBudgetMs ?? 4+ }++ get length(): number {+ return this.items.length+ }++ enqueue(event: T): void {+ this.items.push({ kind: "event", event })+ this.resume()+ }++ enqueueTask(run: () => void): void {+ this.items.push({ kind: "task", run })+ this.resume()+ }++ prepend(events: readonly T[]): void {+ if (events.length) {+ this.items = [+ ...events.map((event): EventTask<T> => ({ kind: "event", event })),+ ...this.items,+ ]+ }+ this.resume()+ }++ whenIdle(task: () => void): void {+ this.idleTask = task+ this.resume()+ }++ resume(): void {+ if (this.drain || this.paused()) return+ if (!this.items.length) {+ const idleTask = this.idleTask+ this.idleTask = null+ idleTask?.()+ return+ }+ this.drain = setImmediate(() => this.drainBatch())+ }++ clear(): void {+ if (this.drain) clearImmediate(this.drain)+ this.drain = null+ this.items = []+ this.idleTask = null+ }++ private drainBatch(): void {+ this.drain = null+ const started = performance.now()+ let processed = 0+ // Keep each item in the queue while it runs. Handlers can then defer work+ // until every event already accepted by the transport has been projected.+ while (!this.paused() && processed < this.items.length) {+ const task = this.items[processed++]!+ if (task.kind === "task") task.run()+ else this.dispatch(task.event)+ if (processed >= this.batchSize || performance.now() - started >= this.batchBudgetMs) break+ }+ this.items.splice(0, processed)+ this.resume()+ }+}diff --git a/tui/src/app/host-lifecycle.test.ts b/tui/src/app/host-lifecycle.test.tsnew file mode 100644index 000000000..1d7bf0863--- /dev/null+++ b/tui/src/app/host-lifecycle.test.ts@@ -0,0 +1,156 @@+import { describe, expect, test } from "bun:test"+import { join } from "node:path"+import { BoxRenderable, TextareaRenderable } from "@opentui/core"+import { MockTreeSitterClient, createTestRenderer } from "@opentui/core/testing"++import { NanobotTui, sessionExitMessage, terminalModelFailureLine } from "./app"+import type { TuiHost } from "../platform/host"+import { client, occurrences, options, waitUntil } from "./test-support"++test("formats a reusable session ID after exit", () => {+ expect(sessionExitMessage("resume-chat")).toBe(+ "Resume with: nanobot agent --session websocket:resume-chat\n",+ )+})++test("formats actionable terminal model failures without inventing retries", () => {+ expect(terminalModelFailureLine("billing")).toBe(+ "Model provider quota is unavailable. "+ + "Add credit or check billing for the provider account, then try again.",+ )+ expect(terminalModelFailureLine("unknown")).toBe(+ "Model provider request failed. "+ + "Check the provider configuration or service status, then try again.",+ )+})++describe("NanobotTui with a Herdr pane title reporter", () => {+ test("keeps the full terminal experience while reporting task titles", async () => {+ const setup = await createTestRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })+ const titles: string[] = []+ let released = false+ const host: TuiHost = {+ reportTitle(title) { titles.push(title) },+ release() { released = true },+ }+ const app = NanobotTui.mount(+ setup.renderer,+ options,+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ host,+ )+ const ui = app as unknown as {+ composer: TextareaRenderable+ composerFrame: BoxRenderable+ }++ await setup.mockInput.typeText("/")+ await setup.flush()+ const commandFrame = setup.captureCharFrame()+ expect(commandFrame).toContain("/sessions")+ expect(commandFrame).toContain("/new-chat")+ expect(commandFrame).toContain("/branch")+ setup.mockInput.pressEscape()+ ui.composer.setText("")++ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({+ event: "user_message",+ chat_id: "chat",+ text: "Ship the Herdr integration",+ turn_id: "turn-1",+ starts_turn: true,+ })+ app.accept({+ event: "message",+ chat_id: "chat",+ text: "",+ kind: "tool_hint",+ tool_events: [{ phase: "end", call_id: "read", name: "read_file", arguments: { path: "app.ts" } }],+ })+ await setup.flush()+ const activeFrame = setup.captureCharFrame()+ expect(activeFrame).toContain(">_ nanobot")+ expect(activeFrame).toContain("default ▾")+ expect(occurrences(activeFrame, "› Ship the Herdr integration")).toBe(1)+ expect(occurrences(activeFrame, "app.ts")).toBe(1)+ expect(ui.composer.placeholder).toBe("Enter send now · Tab send next")+ expect(ui.composerFrame.height).toBe(3)+ expect(titles).toEqual(["Ship the Herdr integration"])++ app.accept({+ event: "turn_end",+ chat_id: "chat",+ turn_id: "turn-1",+ goal_state: {+ active: false,+ status: "blocked",+ ui_summary: "Approval required",+ },+ })+ app.accept({+ event: "user_message",+ chat_id: "chat",+ text: "Approved",+ turn_id: "turn-2",+ starts_turn: true,+ })++ expect(titles).toEqual(["Ship the Herdr integration", "Approved"])++ app.stop()+ expect(released).toBe(true)+ })+})++if (process.platform !== "win32") {+ test("restores the terminal after SIGTERM", async () => {+ const child = Bun.spawn(["bun", "src/index.ts"], {+ cwd: join(import.meta.dir, "..", ".."),+ env: {+ ...process.env,+ NANOBOT_TUI_WS_URL: "ws://127.0.0.1:9/ws",+ NANOBOT_TUI_API_URL: "",+ NANOBOT_TUI_API_TOKEN: "",+ NANOBOT_TUI_CHAT_ID: "resume-chat",+ NANOBOT_TUI_MODEL: "test/model",+ NANOBOT_TUI_WORKSPACE: "/tmp/nanobot-test",+ NANOBOT_TUI_VERSION: "test",+ NANOBOT_TUI_ACCESS: "workspace access",+ NANOBOT_TUI_THEME: "dark",+ },+ stdout: "pipe",+ stderr: "pipe",+ })+ const decoder = new TextDecoder()+ let output = ""+ const collectOutput = (async () => {+ const reader = child.stdout.getReader()+ while (true) {+ const { done, value } = await reader.read()+ if (done) break+ output += decoder.decode(value, { stream: true })+ }+ output += decoder.decode()+ })()++ // Slow Intel runners can spend more than 250 ms importing OpenTUI. Wait+ // for terminal setup, which happens after the signal handlers are+ // registered, before exercising shutdown.+ await waitUntil(() => output.includes("\x1b[?1049h"), 5_000)+ child.kill("SIGTERM")+ const exitCode = await child.exited+ await collectOutput+ const error = await new Response(child.stderr).text()++ expect(exitCode).toBe(0)+ expect(error).toBe("")+ expect(output).toContain("\x1b[?1049h")+ expect(output).toContain("\x1b[?1049l")+ expect(output.indexOf("\x1b[?1049l")).toBeLessThan(output.indexOf("Resume with:"))+ expect(output).toContain(+ "Resume with: nanobot agent --session websocket:resume-chat\n",+ )+ })+}diff --git a/tui/src/app/index.ts b/tui/src/app/index.tsnew file mode 100644index 000000000..b52042bd5--- /dev/null+++ b/tui/src/app/index.ts@@ -0,0 +1 @@+export * from "./app"diff --git a/tui/src/app/layout.test.ts b/tui/src/app/layout.test.tsnew file mode 100644index 000000000..af4841563--- /dev/null+++ b/tui/src/app/layout.test.ts@@ -0,0 +1,775 @@+import { afterEach, describe, expect, test } from "bun:test"+import { BoxRenderable, CliRenderEvents, StyledText, TextareaRenderable, TextAttributes, TextRenderable } from "@opentui/core"+import { MockTreeSitterClient, TestRecorder, setRendererCapabilities, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"+import { NanobotTui } from "./app"+import type { Transcript } from "../rendering/transcript"+import { options, client, mount, waitUntil, occurrences, contrastRatio, HiddenScrollBox } from "./test-support"++describe("NanobotTui layout and themes", () => {+ let setup: TestRendererSetup | undefined++ afterEach(() => {+ if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()+ setup = undefined+ })++ const createRenderer = (rendererOptions: Parameters<typeof createTestRenderer>[0]) => (+ createTestRenderer(rendererOptions)+ )+ test("keeps short transcripts and the composer anchored at the top", async () => {+ setup = await createRenderer({+ width: 100,+ height: 18,+ screenMode: "alternate-screen",+ consoleMode: "disabled",+ })+ const app = mount(setup)+ const ui = app as unknown as {+ transcript: Transcript+ title: BoxRenderable+ status: TextRenderable+ }+ const positions = () => ({+ transcriptHeight: ui.transcript.root.height,+ titleY: ui.title.y,+ statusY: ui.status.y,+ })++ let anchoredPositions: ReturnType<typeof positions> | undefined+ for (const height of [18, 30, 36]) {+ setup.resize(100, height)+ await setup.renderOnce()+ expect(ui.title.y).toBe(ui.transcript.root.y + ui.transcript.root.height)+ expect(ui.status.y + ui.status.height).toBeLessThan(setup.renderer.height)+ if (!anchoredPositions) anchoredPositions = positions()+ else expect(positions()).toEqual(anchoredPositions)+ }++ ui.transcript.user("A short prompt")+ await setup.renderOnce()+ const promptPositions = positions()+ expect(promptPositions.titleY).toBeGreaterThan(anchoredPositions?.titleY || 0)++ setup.resize(100, 40)+ await setup.renderOnce()+ expect(positions()).toEqual(promptPositions)+ })++ test("reflows a single retained layout across terminal resizes", async () => {+ setup = await createRenderer({+ width: 100,+ height: 30,+ screenMode: "alternate-screen",+ consoleMode: "disabled",+ })+ const app = mount(setup)++ for (const [width, height] of [[100, 30], [56, 18], [118, 36]] as const) {+ setup.resize(width, height)+ await setup.renderOnce()+ const frame = setup.captureCharFrame()++ expect(setup.renderer.width).toBe(width)+ expect(setup.renderer.height).toBe(height)+ expect(occurrences(frame, "Ask nanobot anything")).toBe(1)+ expect(occurrences(frame, "Ready")).toBe(0)+ expect(occurrences(frame, "Getting ready…")).toBe(1)+ expect(occurrences(frame, "default ▾")).toBe(1)+ }++ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({ event: "delta", chat_id: "chat", text: "First **answer**." })+ app.accept({ event: "stream_end", chat_id: "chat", resuming: true })+ app.accept({+ event: "message",+ chat_id: "chat",+ text: "read_file(config.json)",+ kind: "tool_hint",+ tool_events: [+ { phase: "start", call_id: "read-1", name: "read_file", arguments: { path: "config.json" } },+ { phase: "end", call_id: "read-1", name: "read_file" },+ ],+ })+ app.accept({ event: "reasoning_delta", chat_id: "chat", text: "private chain of thought" })+ app.accept({ event: "reasoning_end", chat_id: "chat" })+ app.accept({ event: "delta", chat_id: "chat", text: "Second answer." })+ app.accept({ event: "stream_end", chat_id: "chat" })+ app.accept({ event: "turn_end", chat_id: "chat", latency_ms: 1200 })+ await setup.flush()+ const frame = setup.captureCharFrame()++ expect(occurrences(frame, "First **answer**.")).toBe(1)+ expect(occurrences(frame, "Second answer.")).toBe(1)+ expect(frame).toContain("✓ Read config.json")+ expect(frame).not.toContain("› Read")+ expect(frame).not.toContain("private chain of thought")+ expect(frame).toContain("Ready · 1.2s")+ })++ test("keeps model and access details in the composer controls only", async () => {+ setup = await createRenderer({ width: 100, height: 24, screenMode: "alternate-screen" })+ NanobotTui.mount(+ setup.renderer,+ {+ ...options,+ model: "provider/resolved-model",+ modelPreset: "selected-preset",+ access: "full access",+ },+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ await setup.renderOnce()++ const frame = setup.captureCharFrame()+ expect(frame).not.toContain("provider/resolved-model")+ expect(frame).toContain("selected-preset ▾")+ expect(occurrences(frame, "full access")).toBe(1)+ expect(frame).toContain(options.workspace)+ })++ test("uses the available transcript width before wrapping the workspace", async () => {+ setup = await createRenderer({ width: 100, height: 24, screenMode: "alternate-screen" })+ const workspace = String.raw`D:\Documents\GitHub\nanobot\.worktrees\responsive-header-fixture`+ NanobotTui.mount(+ setup.renderer,+ { ...options, workspace },+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ await setup.renderOnce()++ const frame = setup.captureCharFrame()+ const headerWidth = () => {+ const border = setup?.captureCharFrame().split("\n").find((line) => line.includes("╭"))+ if (!border) throw new Error("header border was not rendered")+ return border.trim().length+ }++ expect(frame).toContain(workspace)+ expect(headerWidth()).toBe(setup.renderer.width - 4)++ setup.resize(120, 24)+ await setup.renderOnce()+ expect(headerWidth()).toBe(setup.renderer.width - 4)+ })++ test("survives rapid narrow resizes with long CJK and code", async () => {+ setup = await createRenderer({ width: 100, height: 30, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({+ event: "delta",+ chat_id: "chat",+ text: [+ "中文、emoji 👨💻 and combining text é reflow with the terminal.",+ "https://nanobot.test/a-very-long-unbroken-path-that-must-not-break-the-layout",+ "```ts",+ "const greeting = '你好,nanobot'",+ "```",+ ].join("\n\n"),+ })+ app.accept({ event: "stream_end", chat_id: "chat" })++ for (const [width, height] of [+ [240, 80],+ [42, 12],+ [30, 9],+ [20, 6],+ [12, 4],+ [8, 3],+ [4, 2],+ [84, 24],+ [48, 14],+ [110, 32],+ ] as const) {+ setup.resize(width, height)+ await setup.renderOnce()+ const frame = setup.captureCharFrame()+ expect(setup.renderer.width).toBe(width)+ expect(setup.renderer.height).toBe(height)+ expect(frame).not.toContain("undefined")+ expect(frame).not.toContain("Steer this turn…")+ expect(frame).not.toContain("Ask a follow-up…")+ if (width >= 40 && height >= 9) {+ expect(occurrences(frame, "Enter send now · Tab send next")).toBe(1)+ } else if (width >= 28 && height >= 9) {+ expect(occurrences(frame, "Enter now · Tab next")).toBe(1)+ }+ expect(occurrences(frame, "default ▾")).toBe(height >= 14 ? 1 : 0)+ }+ })++ test("inherits the host background after long output fills the viewport", async () => {+ setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({+ event: "delta",+ chat_id: "chat",+ text: Array.from({ length: 80 }, (_, index) => (+ `### Section ${index + 1}\n中文长回答、**bold** and [link](https://nanobot.test/${index + 1})`+ )).join("\n\n"),+ })+ app.accept({ event: "stream_end", chat_id: "chat" })+ app.accept({ event: "turn_end", chat_id: "chat" })+ await setup.flush()++ const internals = app as unknown as {+ shell: { backgroundColor: { intent: string } }+ composerFrame: { backgroundColor: { intent: string } }+ composer: { backgroundColor: { intent: string } }+ transcript: { root: HiddenScrollBox }+ diffViewer: { scroll: HiddenScrollBox }+ }+ const lines = setup.captureSpans().lines+ const spans = lines.flatMap((line) => line.spans)+ const brandedRows = lines.filter((line) => (+ line.spans.some((span) => span.bg.intent !== "default")+ ))++ expect(internals.shell.backgroundColor.intent).toBe("default")+ expect(internals.composerFrame.backgroundColor.intent).toBe("default")+ expect(internals.composer.backgroundColor.intent).toBe("default")+ expect(spans.length).toBeGreaterThan(0)+ expect(brandedRows).toHaveLength(0)+ for (const scrollBox of [internals.transcript.root, internals.diffViewer.scroll]) {+ for (const bar of [scrollBox.verticalScrollBar, scrollBox.horizontalScrollBar]) {+ expect(bar.visible).toBeFalse()+ expect(bar.slider.visible).toBeFalse()+ expect(bar.startArrow.visible).toBeFalse()+ expect(bar.endArrow.visible).toBeFalse()+ }+ }+ })++ test("reflows markdown tables without clipping columns or cell content", async () => {+ setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({+ event: "delta",+ chat_id: "chat",+ text: [+ "| Who | Content | Engagement |",+ "| --- | --- | --- |",+ "| @owner | A longer explanation that keeps context readable | 13 likes / 6 RT |",+ "| @reader | Short follow-up | Low interaction |",+ ].join("\n"),+ })+ app.accept({ event: "stream_end", chat_id: "chat" })+ app.accept({ event: "turn_end", chat_id: "chat" })++ for (const width of [96, 54, 96]) {+ setup.resize(width, 24)+ await setup.flush()+ const rendered = setup.captureCharFrame().replace(/\s+/gu, " ")++ expect(rendered).toContain("Who")+ expect(rendered).toContain("Content")+ expect(rendered).toContain("Engagement")+ expect(rendered).toContain("@owner")+ expect(rendered).toContain("longer explanation")+ expect(rendered).toContain("keeps context")+ expect(rendered).toContain("readable")+ expect(rendered).toContain("13 likes / 6")+ expect(rendered).toContain("RT")+ expect(rendered).toContain("Low interaction")+ expect((app as unknown as {+ transcript: { root: HiddenScrollBox }+ }).transcript.root.horizontalScrollBar.visible).toBeFalse()+ }+ })++ test("keeps finalized streamed Markdown link labels clickable", async () => {+ setup = await createRenderer({ width: 100, height: 24, screenMode: "alternate-screen" })+ setRendererCapabilities(setup.renderer, { hyperlinks: true })+ const label = "HKUDS/nanobot#1234"+ const url = "https://github.com/HKUDS/nanobot/pull/1234"+ const content = `PR updated: [${label}](${url})`+ const labelStart = content.indexOf(label)+ const urlStart = content.indexOf(url)+ const treeSitterClient = new MockTreeSitterClient({ autoResolveTimeout: 0 })+ treeSitterClient.setMockResult({+ highlights: [+ [labelStart - 1, labelStart, "markup.link"],+ [labelStart, labelStart + label.length, "markup.link.label"],+ [labelStart + label.length, urlStart, "markup.link"],+ [urlStart, urlStart + url.length, "markup.link.url"],+ [urlStart + url.length, content.length, "markup.link"],+ ],+ })+ const app = NanobotTui.mount(setup.renderer, options, client(), treeSitterClient)++ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({ event: "delta", chat_id: "chat", text: content })+ app.accept({ event: "stream_end", chat_id: "chat" })+ app.accept({ event: "turn_end", chat_id: "chat" })+ await setup.flush()++ const lines = setup.captureCharFrame().split("\n")+ const y = lines.findIndex((line) => line.includes(label))+ const x = y >= 0 ? lines[y]!.indexOf(label) : -1+ expect([x, y]).not.toContain(-1)++ for (let offset = 0; offset < label.length; offset += 1) {+ expect(setup.renderer.getLinkAt(x + offset, y)).toBe(url)+ }+ })++ test("keeps streamed fenced code visible while completing the response", async () => {+ setup = await createRenderer({ width: 100, height: 30, screenMode: "alternate-screen" })+ const app = mount(setup)+ const response = [+ "Commit types:",+ "",+ "```text",+ "feat:",+ "fix:",+ "perf:",+ "docs:",+ "test:",+ "refactor:",+ "chore:",+ "```",+ "",+ "Include the reason in the body.",+ ].join("\n")++ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({ event: "delta", chat_id: "chat", text: response })+ await setup.flush()+ expect(setup.captureCharFrame()).toContain("feat:")++ const recorder = new TestRecorder(setup.renderer)+ recorder.rec()+ app.accept({ event: "stream_end", chat_id: "chat" })+ app.accept({ event: "turn_end", chat_id: "chat" })+ await setup.flush()+ recorder.stop()++ expect(recorder.recordedFrames.length).toBeGreaterThan(0)+ expect(recorder.recordedFrames.every(({ frame }) => frame.includes("feat:"))).toBeTrue()+ expect(recorder.recordedFrames.every(({ frame }) => /│\s+feat:/u.test(frame))).toBeTrue()+ expect(recorder.recordedFrames.every(({ frame }) => (+ frame.includes("Include the reason in the body.")+ ))).toBeTrue()+ })++ test("renders fenced plain text from light-theme history", async () => {+ setup = await createRenderer({ width: 100, height: 30, screenMode: "alternate-screen" })+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, theme: "light" },+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ const response = [+ "Commit types:",+ "",+ "```text",+ "feat:",+ "fix:",+ "perf:",+ "docs:",+ "test:",+ "refactor:",+ "chore:",+ "```",+ "",+ "Include the reason in the body.",+ ].join("\n")+ const transcript = (app as unknown as { transcript: Transcript }).transcript++ transcript.history([{ role: "assistant", content: response }])+ await setup.flush()++ const codeLine = setup.captureSpans().lines.find((line) => (+ line.spans.some((span) => span.text.includes("feat:"))+ ))+ const code = codeLine?.spans.find((span) => span.text.includes("feat:"))+ const rail = codeLine?.spans.find((span) => span.text.includes("│"))+ const frame = setup.captureCharFrame()++ expect(frame).toContain("feat:")+ expect(frame).toMatch(/│\s+feat:/u)+ expect(code?.fg.toInts().slice(0, 3)).toEqual([24, 24, 27])+ expect(rail?.fg.toInts().slice(0, 3)).toEqual([212, 212, 216])+ })++ test("renders assistant LaTeX as Unicode text without changing code", async () => {+ setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({+ event: "delta",+ chat_id: "chat",+ text: [+ "缓存率:",+ "\\[\\text{缓存率}=\\frac{\\text{cached input tokens}}{\\text{total input tokens}}\\]",+ "结果:\\(66{,}000 \\times 94\\% \\approx 62{,}040\\)",+ "`\\(code\\)`",+ ].join("\n"),+ })+ app.accept({ event: "stream_end", chat_id: "chat" })+ const transcript = (app as unknown as {+ transcript: { assistant(content: string): void }+ }).transcript+ transcript.assistant("历史公式:\\(x_1^2 + y_2^2 = z^2\\)")+ await setup.flush()+ const frame = setup.captureCharFrame()++ expect(frame).toContain("缓存率 = cached input tokens / total input tokens")+ expect(frame).toContain("66,000 × 94% ≈ 62,040")+ expect(frame).toContain("历史公式:x₁² + y₂² = z²")+ expect(frame).toContain("\\(code\\)")+ expect(frame).not.toContain("\\frac")+ expect(frame).not.toContain("\\text")+ })++ test("rethemes the complete retained interface when the terminal appearance changes", async () => {+ setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({ event: "delta", chat_id: "chat", text: "# Existing answer" })+ app.accept({ event: "stream_end", chat_id: "chat" })+ app.accept({ event: "message", chat_id: "chat", text: "tool", kind: "tool_hint" })+ await setup.renderOnce()++ const internals = app as unknown as {+ palette: { referenceBackground: string; text: string; border: string }+ shell: { backgroundColor: { intent: string } }+ composerFrame: {+ backgroundColor: { intent: string; toInts(): number[] }+ }+ composer: {+ backgroundColor: { intent: string; toInts(): number[] }+ textColor: { toInts(): number[] }+ syntaxStyle: { getStyle(name: string): { fg?: { toInts(): number[] } } | undefined } | null+ }+ transcript: {+ markdown: Set<{ fg?: { toInts(): number[] }; syntaxStyle: object }>+ frames: Set<{ borderColor: { toInts(): number[] } }>+ userRows: Set<{ backgroundColor: { intent: string; toInts(): number[] } }>+ userMessages: Set<{ renderable: TextRenderable }>+ user(content: string, turnId?: string, media?: Array<{ kind: "image"; name: string }>): void+ }+ }+ internals.transcript.user("Existing question", undefined, [{+ kind: "image",+ name: "clipboard-image-1.png",+ }])+ const userRow = [...internals.transcript.userRows][0]+ const userMessage = [...internals.transcript.userMessages][0]+ const markdown = [...internals.transcript.markdown][0]+ const sessionFrame = [...internals.transcript.frames][0]+ const darkSyntax = markdown?.syntaxStyle+ const darkComposerSyntax = internals.composer.syntaxStyle++ expect(userRow?.backgroundColor.intent).toBe("default")++ setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")+ await setup.flush()++ expect(internals.palette).toMatchObject({+ referenceBackground: "#FAFAFA",+ text: "#18181B",+ border: "#D4D4D8",+ })+ expect(internals.shell.backgroundColor.intent).toBe("default")+ expect(internals.composerFrame.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])+ expect(internals.composer.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])+ expect(internals.composer.textColor.toInts().slice(0, 3)).toEqual([24, 24, 27])+ expect(sessionFrame?.borderColor.toInts().slice(0, 3)).toEqual([212, 212, 216])+ expect(userRow?.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])+ expect(markdown?.fg?.toInts().slice(0, 3)).toEqual([24, 24, 27])+ expect(markdown?.syntaxStyle).not.toBe(darkSyntax)+ expect(internals.composer.syntaxStyle).not.toBe(darkComposerSyntax)+ expect(internals.composer.syntaxStyle?.getStyle("image.placeholder")?.fg?.toInts().slice(0, 3))+ .toEqual([185, 77, 11])+ const recolored = userMessage?.renderable.content as StyledText+ expect(recolored.chunks.find(({ text }) => text === "[Image #1]")?.fg?.toInts().slice(0, 3))+ .toEqual([185, 77, 11])+ })++ test("distinguishes the composer with a quiet focus edge", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, theme: "light" },+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ const internals = app as unknown as {+ ready: boolean+ composerFrame: {+ border: boolean | string[]+ borderColor: { toInts(): number[] }+ backgroundColor: { toInts(): number[] }+ }+ composer: {+ backgroundColor: { toInts(): number[] }+ placeholderColor: { toInts(): number[] }+ }+ }++ expect(internals.composerFrame.border).toEqual(["left"])+ expect(internals.composerFrame.borderColor.toInts().slice(0, 3)).toEqual([185, 77, 11])+ expect(internals.composerFrame.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])+ expect(internals.composer.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])+ expect(internals.composer.placeholderColor.toInts().slice(0, 3)).toEqual([111, 111, 120])++ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => internals.ready)+ await setup.renderOnce()++ const composerLine = setup.captureCharFrame().split("\n")+ .find((line) => line.includes("Ask nanobot anything")) || ""+ expect(composerLine).toContain("│")+ expect(composerLine).not.toContain("┌")+ expect(composerLine).not.toContain("┐")+ })++ test("uses asymmetric roles instead of chat bubbles", async () => {+ setup = await createRenderer({ width: 72, height: 24, screenMode: "alternate-screen" })+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, theme: "dark" },+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({ event: "delta", chat_id: "chat", text: "Agent **answer**" })+ app.accept({ event: "stream_end", chat_id: "chat" })+ app.accept({ event: "turn_end", chat_id: "chat" })+ ;(app as unknown as { transcript: { user(content: string): void } }).transcript.user("User question")+ await setup.flush()++ const frame = setup.captureCharFrame()+ const userLine = frame.split("\n").find((line) => line.includes("User question")) || ""+ const agentLine = frame.split("\n").find((line) => line.includes("Agent **answer**")) || ""+ const headerLine = frame.split("\n").find((line) => line.includes(">_ nanobot")) || ""+ const headerBorder = frame.split("\n").find((line) => line.includes("╭")) || ""++ expect(userLine).toContain("› User question")+ expect(agentLine).toContain("• Agent **answer**")+ expect(userLine).not.toContain("│")+ expect(agentLine).not.toContain("│")+ expect(headerLine).toContain("│")+ expect(headerBorder.trim().length).toBe(setup.renderer.width - 4)++ const transcript = (app as unknown as {+ transcript: {+ userRows: Set<{ backgroundColor: { intent: string; toInts(): number[] } }>+ styledText: Array<{+ renderable: { id: string; fg: { toInts(): number[] } }+ tone: string+ }>+ }+ }).transcript+ const userRow = [...transcript.userRows][0]+ const assistantMarker = transcript.styledText.find(({ renderable, tone }) => (+ tone === "muted" && renderable.id.includes("role-marker")+ ))++ expect(userRow?.backgroundColor.intent).toBe("rgb")+ expect(userRow?.backgroundColor.toInts().slice(0, 3)).toEqual([43, 44, 46])+ expect(assistantMarker?.tone).toBe("muted")+ expect(assistantMarker?.renderable.fg.toInts().slice(0, 3)).toEqual([161, 161, 170])+ })++ test("aligns footer labels with transcript content", async () => {+ setup = await createRenderer({ width: 72, height: 24, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({ event: "attached", chat_id: "chat" })+ ;(app as unknown as { transcript: { user(content: string): void } })+ .transcript.user("Aligned message")+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ await setup.renderOnce()++ const lines = setup.captureCharFrame().split("\n")+ const lineContaining = (needle: string): string => {+ const line = lines.find((candidate) => candidate.includes(needle))+ if (!line) throw new Error(`${needle} was not rendered`)+ return line+ }+ const messageLine = lineContaining("Aligned message")+ const composerLine = lineContaining("Ask nanobot anything")+ const contentColumn = messageLine.indexOf("Aligned message")++ expect(lineContaining("default ▾").indexOf("default ▾")).toBe(contentColumn)+ expect(lineContaining("Ready").indexOf("Ready")).toBe(contentColumn)+ expect(composerLine.indexOf("│")).toBe(messageLine.indexOf("›"))+ expect(composerLine.indexOf("Ask nanobot anything")).toBe(contentColumn)+ })++ test("shows context usage in the idle footer", async () => {+ setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({+ event: "turn_end",+ chat_id: "chat",+ latency_ms: 1700,+ usage: {+ context_tokens: 14_700,+ },+ context_window_tokens: 128_000,+ })+ await setup.flush()++ const footer = setup.captureCharFrame().split("\n").find((line) => line.includes("Ready · 1.7s")) || ""+ expect(footer).toContain("Ready · 1.7s")+ expect(footer).toContain("11% context")+ })++ test("keeps an explicit theme stable when the terminal reports another mode", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, theme: "light" },+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ const internals = app as unknown as { palette: { referenceBackground: string } }+ Object.defineProperty(setup.renderer, "themeMode", { configurable: true, value: "dark" })++ await app.start()++ setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")+ await setup.renderOnce()++ expect(internals.palette.referenceBackground).toBe("#FAFAFA")+ })++ test("overlaps automatic terminal detection with connection startup", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ let connected = false+ let rendered = false+ let resolveMode: (mode: "light") => void = () => undefined+ setup.renderer.start = () => { rendered = true }+ setup.renderer.waitForThemeMode = () => new Promise((resolve) => {+ resolveMode = resolve+ })+ Object.defineProperty(setup.renderer, "themeMode", { configurable: true, value: "light" })+ const transport = client()+ transport.connect = () => { connected = true }+ const app = NanobotTui.mount(+ setup.renderer,+ options,+ transport,+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )++ const starting = app.start()+ await Bun.sleep(1)+ expect(connected).toBe(true)+ expect(rendered).toBe(true)++ resolveMode("light")+ await starting+ expect((app as unknown as { palette: { referenceBackground: string } }).palette.referenceBackground).toBe("#FAFAFA")+ })++ test.each(["dark", "light"] as const)("uses terminal defaults until a late %s theme response", async (mode) => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ let connected = false+ setup.renderer.waitForThemeMode = async () => null+ Object.defineProperty(setup.renderer, "themeMode", { configurable: true, value: null })+ const transport = client()+ transport.connect = () => { connected = true }+ const app = NanobotTui.mount(+ setup.renderer,+ options,+ transport,+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )++ await app.start()++ const transcript = (app as unknown as {+ transcript: {+ userRows: Set<{ backgroundColor: { intent: string } }>+ user(content: string): void+ }+ }).transcript+ transcript.user("Unknown terminal background")++ expect(connected).toBe(true)+ const ui = app as unknown as {+ composer: TextareaRenderable+ status: TextRenderable+ shimmerFrame: number+ renderActiveStatus(): void+ }+ expect(ui.composer.textColor.intent).toBe("default")+ expect(ui.composer.backgroundColor.intent).toBe("default")+ expect([...transcript.userRows][0]?.backgroundColor.intent).toBe("default")+ app.accept({ event: "delta", chat_id: "chat", text: "Readable answer" })+ app.accept({ event: "stream_end", chat_id: "chat" })+ await setup.flush()+ expect(setup.captureCharFrame()).toContain("Readable answer")+ for (const line of setup.captureSpans().lines) {+ for (const span of line.spans) {+ if (span.text.trim()) expect(span.fg.intent).toBe("default")+ }+ }+ // Keep the fallback readable without guessed RGB colors, but do not freeze+ // the active-status animation while waiting for a terminal theme response.+ app.accept({ event: "reasoning_delta", chat_id: "chat", text: "thinking" })+ await setup.flush()+ const terminalFrame = () => (ui.status.content as StyledText).chunks+ .slice(0, "Thinking".length)+ .map((chunk) => chunk.attributes ?? 0)+ const firstFrame = terminalFrame()+ ui.shimmerFrame += 1+ ui.renderActiveStatus()+ const secondFrame = terminalFrame()+ expect(firstFrame).toContain(TextAttributes.BOLD)+ expect(secondFrame).not.toEqual(firstFrame)+ for (const chunk of (ui.status.content as StyledText).chunks) {+ expect(chunk.fg?.intent).toBe("default")+ }++ setup.renderer.emit(CliRenderEvents.THEME_MODE, mode)+ await setup.flush()+ const shimmerColors = new Set(+ (ui.status.content as StyledText).chunks+ .slice(0, "Thinking".length)+ .map((chunk) => chunk.fg?.toInts().slice(0, 3).join(",")),+ )+ expect(shimmerColors.size).toBeGreaterThan(1)+ expect(ui.composer.textColor.intent).toBe("rgb")+ expect(ui.composer.textColor.toInts().slice(0, 3)).toEqual(+ mode === "light" ? [24, 24, 27] : [236, 237, 238],+ )+ expect([...transcript.userRows][0]?.backgroundColor.intent).toBe("rgb")+ })++ test("keeps semantic colors legible in both terminal appearances", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup)+ const internals = app as unknown as {+ palette: Record<string, string> & { referenceBackground: string; faint: string }+ }+ const assertContrast = () => {+ for (const tone of ["text", "muted", "accent", "link", "success", "error", "user", "warm", "cool"]) {+ expect(contrastRatio(internals.palette[tone] ?? "", internals.palette.referenceBackground)).toBeGreaterThanOrEqual(4.5)+ }+ expect(contrastRatio(internals.palette.faint, internals.palette.referenceBackground)).toBeGreaterThanOrEqual(3)+ const turnContrast = contrastRatio(+ internals.palette.userBackground ?? "",+ internals.palette.referenceBackground,+ )+ expect(turnContrast).toBeGreaterThan(1.05)+ expect(turnContrast).toBeLessThan(1.5)+ }++ setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")+ assertContrast()+ expect(internals.palette.accent).toBe("#EF8E30")+ expect(internals.palette.user).toBe("#EF8E30")+ setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")+ assertContrast()+ expect(internals.palette.accent).toBe("#B94D0B")+ expect(internals.palette.user).toBe("#B94D0B")+ })+})diff --git a/tui/src/app/layout.ts b/tui/src/app/layout.tsnew file mode 100644index 000000000..689334e47--- /dev/null+++ b/tui/src/app/layout.ts@@ -0,0 +1,207 @@+import {+ BoxRenderable,+ RGBA,+ TextareaRenderable,+ TextRenderable,+ type CliRenderer,+ type PasteEvent,+ type SyntaxStyle,+} from "@opentui/core"++import type { QueuePreview } from "../composer/queue-preview"+import type { BranchMenu } from "../menus/branch-menu"+import type { CommandMenu } from "../menus/command-menu"+import type { MentionMenu } from "../menus/mention-menu"+import type { SessionMenu } from "../menus/session-menu"+import type { SkillMenu } from "../menus/skill-menu"+import type { Transcript } from "../rendering/transcript"+import type { ContextPanel } from "../views/context-panel"+import type { DiffViewer } from "../views/diff-viewer"+import type { RecoveryNotice } from "../views/recovery-notice"+import type { RuntimeControls } from "../views/runtime-controls"+import type { UsagePanel } from "../views/usage-panel"+import type { Palette } from "./theme"++export const COMPOSER_PLACEHOLDER = "Ask nanobot anything"+export const ACTIVE_COMPOSER_PLACEHOLDER = "Enter send now · Tab send next"+export const COMPACT_ACTIVE_COMPOSER_PLACEHOLDER = "Enter now · Tab next"++const TRANSCRIPT_EDGE_INSET = 1+const TRANSCRIPT_TEXT_INSET = TRANSCRIPT_EDGE_INSET + 2++interface LayoutComponents {+ transcript: Transcript+ commandMenu: CommandMenu+ sessionMenu: SessionMenu+ mentionMenu: MentionMenu+ skillMenu: SkillMenu+ branchMenu: BranchMenu+ contextPanel: ContextPanel+ usagePanel: UsagePanel+ runtimeControls: RuntimeControls+ queuePreview: QueuePreview+ recoveryNotice: RecoveryNotice+ diffViewer: DiffViewer+}++interface LayoutHandlers {+ onPrimaryMouseDown(): boolean+ onComposerCursorChange(): void+ onComposerContentChange(): void+ onComposerPointer(): void+ onSubmit(): void+ onPaste(event: PasteEvent): void+}++export interface AppLayout {+ shell: BoxRenderable+ title: BoxRenderable+ composerFrame: BoxRenderable+ composer: TextareaRenderable+ status: TextRenderable+ meta: TextRenderable+}++export function createAppLayout(+ renderer: CliRenderer,+ palette: Palette,+ composerSyntax: SyntaxStyle,+ composerSurface: RGBA,+ components: LayoutComponents,+ handlers: LayoutHandlers,+): AppLayout {+ // The terminal owns its canvas. Keeping the default-background intent is+ // essential in embedded terminals, where painting our own near-black RGB+ // only colors occupied cells and turns long output into dark strips.+ renderer.setBackgroundColor(RGBA.defaultBackground())+ const shell = new BoxRenderable(renderer, {+ id: "nanobot-tui-footer",+ width: "100%",+ height: "100%",+ paddingLeft: 1,+ paddingRight: 1,+ flexDirection: "column",+ backgroundColor: RGBA.defaultBackground(),+ onMouseDown: (event) => {+ if (event.button !== 0) return+ if (handlers.onPrimaryMouseDown()) event.preventDefault()+ // Selection belongs to transcript/input content, never to empty chrome.+ // Clearing it here prevents default-background cells from lingering as+ // opaque blocks in terminals with differential repainting.+ if (event.target && !event.target.selectable) renderer.clearSelection()+ },+ })+ const title = new BoxRenderable(renderer, {+ id: "nanobot-tui-title",+ width: "100%",+ height: 1,+ flexShrink: 0,+ flexDirection: "row",+ alignItems: "center",+ paddingLeft: TRANSCRIPT_TEXT_INSET,+ backgroundColor: RGBA.defaultBackground(),+ })+ title.add(components.runtimeControls.modelText)+ title.add(components.runtimeControls.accessText)+ title.add(components.runtimeControls.contextText)++ const composerFrame = new BoxRenderable(renderer, {+ id: "nanobot-tui-composer-frame",+ minHeight: 1,+ flexShrink: 0,+ marginLeft: TRANSCRIPT_EDGE_INSET,+ border: ["left"],+ borderColor: palette.accent,+ paddingLeft: 1,+ paddingRight: 1,+ backgroundColor: composerSurface,+ })+ const composer = new TextareaRenderable(renderer, {+ id: "nanobot-tui-composer",+ width: "100%",+ minHeight: 1,+ maxHeight: 8,+ wrapMode: "word",+ placeholder: COMPOSER_PLACEHOLDER,+ placeholderColor: palette.muted,+ textColor: palette.text,+ focusedTextColor: palette.text,+ backgroundColor: composerSurface,+ focusedBackgroundColor: composerSurface,+ cursorColor: palette.accent,+ syntaxStyle: composerSyntax,+ // A steady line cursor avoids the block-cell trails produced by some+ // terminals when a retained full-screen UI redraws around the composer.+ cursorStyle: { style: "line", blinking: false },+ showCursor: true,+ keyBindings: [+ { name: "return", shift: true, action: "newline" },+ { name: "return", meta: true, action: "newline" },+ { name: "return", ctrl: true, action: "newline" },+ { name: "j", ctrl: true, action: "newline" },+ { name: "linefeed", action: "newline" },+ { name: "return", action: "submit" },+ ],+ onCursorChange: handlers.onComposerCursorChange,+ onContentChange: handlers.onComposerContentChange,+ onMouseDown: () => queueMicrotask(handlers.onComposerPointer),+ onMouseUp: () => queueMicrotask(handlers.onComposerPointer),+ onMouseDrag: () => queueMicrotask(handlers.onComposerPointer),+ onMouseDragEnd: () => queueMicrotask(handlers.onComposerPointer),+ // IMEs may commit their final composed glyph after Enter. Matching the+ // OpenCode/OpenTUI integration, defer twice before reading plainText.+ onSubmit: handlers.onSubmit,+ onPaste: handlers.onPaste,+ })+ const status = new TextRenderable(renderer, {+ id: "nanobot-tui-status",+ content: "Getting ready…",+ fg: palette.muted,+ height: 1,+ width: "auto",+ minWidth: 0,+ flexGrow: 1,+ flexShrink: 1,+ selectable: false,+ })+ const meta = new TextRenderable(renderer, {+ id: "nanobot-tui-meta",+ content: "",+ fg: palette.faint,+ height: 1,+ width: "auto",+ flexShrink: 1,+ selectable: false,+ })+ const statusRow = new BoxRenderable(renderer, {+ id: "nanobot-tui-status-row",+ width: "100%",+ height: 1,+ flexShrink: 0,+ flexDirection: "row",+ justifyContent: "space-between",+ gap: 2,+ paddingLeft: TRANSCRIPT_TEXT_INSET,+ })+ composerFrame.add(composer)+ statusRow.add(status)+ statusRow.add(meta)++ shell.add(components.transcript.root)+ shell.add(components.commandMenu.root)+ shell.add(components.sessionMenu.root)+ shell.add(components.mentionMenu.root)+ shell.add(components.skillMenu.root)+ shell.add(components.branchMenu.root)+ shell.add(components.contextPanel.root)+ shell.add(components.usagePanel.root)+ shell.add(components.runtimeControls.menuRoot)+ shell.add(title)+ shell.add(components.queuePreview.root)+ shell.add(components.recoveryNotice.root)+ shell.add(composerFrame)+ shell.add(statusRow)+ shell.add(components.diffViewer.root)++ return { shell, title, composerFrame, composer, status, meta }+}diff --git a/tui/src/app/lifecycle.test.ts b/tui/src/app/lifecycle.test.tsnew file mode 100644index 000000000..18fef9cf0--- /dev/null+++ b/tui/src/app/lifecycle.test.ts@@ -0,0 +1,552 @@+import { afterEach, describe, expect, test } from "bun:test"+import { CliRenderEvents, TextareaRenderable, TextRenderable } from "@opentui/core"+import { MockTreeSitterClient, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"+import { NanobotTui } from "./app"+import type { Transcript } from "../rendering/transcript"+import { options, client, mount, waitUntil, occurrences } from "./test-support"++describe("NanobotTui lifecycle", () => {+ let setup: TestRendererSetup | undefined++ afterEach(() => {+ if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()+ setup = undefined+ })++ const createRenderer = (rendererOptions: Parameters<typeof createTestRenderer>[0]) => (+ createTestRenderer(rendererOptions)+ )+ test("reconciles active state from attach hydration after reconnect", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup)+ const state = () => (app as unknown as { activeTurn: boolean }).activeTurn+ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({ event: "delta", chat_id: "chat", text: "stale partial response" })+ expect(state()).toBe(true)++ app.accept({ event: "attached", chat_id: "chat" })+ await Bun.sleep(1)+ await setup.flush()+ expect(state()).toBe(false)+ const restored = setup.captureCharFrame()+ expect(restored).not.toContain("stale partial response")+ expect(occurrences(restored, ">_ nanobot")).toBe(1)+ app.accept({+ event: "goal_status",+ chat_id: "chat",+ status: "running",+ started_at: Date.now() / 1000 - 2,+ })+ expect(state()).toBe(true)+ app.accept({ event: "goal_status", chat_id: "chat", status: "idle" })+ expect(state()).toBe(false)+ })++ test("shows actionable connection states without implementation details", async () => {+ setup = await createRenderer({ width: 100, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup)+ const ui = app as unknown as {+ status: TextRenderable+ handleStatus(+ status: "starting" | "connecting" | "connected" | "reconnecting" | "unavailable" | "error",+ detail?: string,+ info?: {+ endpoint: string+ attempt: number+ elapsedMs: number+ health?: "ready" | "degraded" | "unreachable"+ },+ ): void+ }++ ui.handleStatus("starting", undefined, {+ endpoint: "127.0.0.1:8769",+ attempt: 1,+ elapsedMs: 0,+ })+ expect(ui.status.plainText).toBe("Getting ready…")++ ui.handleStatus("connecting")+ expect(ui.status.plainText).toBe("Getting ready…")++ ui.handleStatus("connected")+ expect(ui.status.plainText).toBe("Getting ready…")++ ui.handleStatus("error", "gateway sent an invalid event")+ expect(ui.status.plainText).toBe("Getting ready…")+ expect(ui.status.plainText).not.toContain("Unable")++ ui.handleStatus("reconnecting", "connection closed", {+ endpoint: "127.0.0.1:8769",+ attempt: 2,+ elapsedMs: 800,+ })+ expect(ui.status.plainText).toBe("Resuming…")++ ui.handleStatus("reconnecting", "connection closed", {+ endpoint: "127.0.0.1:8769",+ attempt: 2,+ elapsedMs: 900,+ health: "degraded",+ })+ expect(ui.status.plainText).toBe("Resuming…")++ ui.handleStatus("unavailable", "connection refused", {+ endpoint: "127.0.0.1:8769",+ attempt: 7,+ elapsedMs: 3_200,+ health: "degraded",+ })+ expect(ui.status.plainText).toBe("Still getting ready…")+ expect(ui.status.plainText).not.toContain("Unable")++ ui.handleStatus("unavailable", "connection refused", {+ endpoint: "127.0.0.1:8769",+ attempt: 8,+ elapsedMs: 3_500,+ health: "unreachable",+ })+ expect(ui.status.plainText).toBe("Nanobot is taking longer to respond…")+ expect(ui.status.plainText).not.toContain("Unable")++ ui.handleStatus("error", "gateway bootstrap failed: HTTP 401", {+ endpoint: "127.0.0.1:8769",+ attempt: 9,+ elapsedMs: 3_800,+ })+ expect(ui.status.plainText).toBe("Nanobot unavailable · restart nanobot")+ expect(ui.status.plainText).not.toContain("gateway")+ expect(ui.status.plainText).not.toContain("127.0.0.1")+ expect(ui.status.plainText).not.toContain("HTTP")+ expect(ui.status.plainText).not.toContain("attempt")+ })++ test.each([+ ["succeeded", "Conversation compacted"],+ ["cancelled", "Conversation compaction cancelled"],+ ] as const)("updates idle compaction in place to %s", async (phase, copy) => {+ setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })+ const app = mount(setup)+ const ui = app as unknown as {+ activeTurn: boolean+ transcript: Transcript+ composer: TextareaRenderable+ }+ ui.composer.setText("unfinished draft")+ const event = { event: "context_compaction", chat_id: "chat", compaction_id: "idle" } as const+ app.accept({ ...event, phase: "started" })+ await setup.renderOnce()+ expect(setup.captureCharFrame()).toContain("Compacting conversation…")+ const rows = ui.transcript.root.getChildren()+ app.accept({ ...event, phase })+ app.accept({ ...event, phase })+ app.accept({ ...event, phase: "started" })+ app.accept({ ...event, chat_id: "another-chat", compaction_id: "other", phase: "failed" })+ await setup.renderOnce()+ const frame = setup.captureCharFrame()+ expect(occurrences(frame, copy)).toBe(1)+ expect(frame).not.toContain("Compacting conversation")+ expect(frame).not.toContain("Could not compact")+ expect(ui.transcript.root.getChildren()).toEqual(rows)+ expect(ui.activeTurn).toBe(false)+ expect(ui.composer.plainText).toBe("unfinished draft")+ })++ test("keeps compaction separate from progress and streamed answers", async () => {+ setup = await createRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({ event: "delta", chat_id: "chat", text: "Answer before " })+ app.accept({ event: "message", chat_id: "chat", text: "First step", kind: "progress" })+ const event = { event: "context_compaction", chat_id: "chat", compaction_id: "capacity" } as const+ app.accept({ ...event, phase: "started" })+ app.accept({ event: "message", chat_id: "chat", text: "Second step", kind: "progress" })+ app.accept({ ...event, phase: "succeeded" })+ app.accept({ event: "delta", chat_id: "chat", text: "and after compaction" })+ expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(true)+ app.accept({ event: "stream_end", chat_id: "chat" })+ app.accept({ event: "turn_end", chat_id: "chat" })+ await setup.flush()+ const frame = setup.captureCharFrame()+ expect(frame).toContain("Answer before and after compaction")+ expect(frame.indexOf("First step")).toBeLessThan(frame.indexOf("Conversation compacted"))+ expect(frame.indexOf("Conversation compacted")).toBeLessThan(frame.indexOf("Second step"))+ expect(occurrences(frame, "Conversation compacted")).toBe(1)+ })++ test("preserves compaction rows through pagination, theming, and session reset", async () => {+ setup = await createRenderer({ width: 80, height: 28, screenMode: "alternate-screen" })+ const app = mount(setup)+ const ui = app as unknown as {+ transcript: Transcript+ palette: { error: string }+ }+ ui.transcript.history([+ { role: "activity", content: "", compaction: { id: "recent", phase: "succeeded" } },+ { role: "assistant", content: "Recent answer" },+ ])+ await setup.flush()+ await ui.transcript.prependHistory([+ { role: "assistant", content: "Earlier answer" },+ { role: "activity", content: "", compaction: { id: "older", phase: "failed" } },+ { role: "activity", content: "", compaction: { id: "recent", phase: "started" } },+ ])+ await setup.flush()+ ui.transcript.scrollToEdge("top")+ await setup.renderOnce()+ const frame = setup.captureCharFrame()+ expect(occurrences(frame, "Conversation compacted")).toBe(1)+ expect(frame).not.toContain("Compacting conversation")+ expect(frame).toContain("Earlier answer")+ expect(frame.indexOf("Earlier answer")).toBeLessThan(frame.indexOf("Could not compact conversation"))+ expect(frame).toContain("Recent answer")+ expect(frame.indexOf("Could not compact conversation")).toBeLessThan(frame.indexOf("Recent answer"))+ setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")+ await setup.flush()+ const failure = ui.transcript.root.getChildren()+ .flatMap((row) => row.getChildren())+ .find((child) => child instanceof TextRenderable && child.plainText.includes("Could not compact"))+ expect(failure).toBeInstanceOf(TextRenderable)+ expect((failure as TextRenderable).fg.toInts().slice(0, 3)).toEqual([+ 1, 3, 5,+ ].map((offset) => Number.parseInt(ui.palette.error.slice(offset, offset + 2), 16)))+ ui.transcript.reset({ workspace: "workspace", version: "test" })+ app.accept({ event: "context_compaction", chat_id: "chat", compaction_id: "recent", phase: "started" })+ await setup.renderOnce()+ expect(setup.captureCharFrame()).toContain("Compacting conversation…")+ expect(setup.captureCharFrame()).not.toContain("Conversation compacted")+ })++ test("deduplicates compaction history against events queued during hydration", async () => {+ setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })+ const original = globalThis.fetch+ let resolveFetch: (value: Response) => void = () => undefined+ globalThis.fetch = (() => new Promise<Response>((resolve) => {+ resolveFetch = resolve+ })) as unknown as typeof fetch+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, apiUrl: "http://nanobot.test", apiToken: "token", chatId: "chat" },+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ try {+ app.accept({ event: "attached", chat_id: "chat" })+ const event = { event: "context_compaction", chat_id: "chat", compaction_id: "idle" } as const+ app.accept({ ...event, phase: "started" })+ app.accept({ ...event, phase: "succeeded" })+ resolveFetch(Response.json({+ schemaVersion: 3, projection: "events",+ events: [{ event: "context_compaction", chat_id: "chat", compaction_id: "idle", phase: "succeeded" }],+ }))+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ await setup.renderOnce()+ const frame = setup.captureCharFrame()+ expect(occurrences(frame, "Conversation compacted")).toBe(1)+ expect(frame).not.toContain("Compacting conversation")+ expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(false)+ } finally {+ globalThis.fetch = original+ }+ })++ test("replays events after asynchronous history hydration", async () => {+ setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })+ const original = globalThis.fetch+ let resolveFetch: (value: Response) => void = () => undefined+ globalThis.fetch = (() => new Promise<Response>((resolve) => {+ resolveFetch = resolve+ })) as unknown as typeof fetch+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, apiUrl: "http://nanobot.test", apiToken: "token", chatId: "chat" },+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )++ try {+ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({ event: "delta", chat_id: "chat", text: "live after reconnect" })+ expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(false)+ resolveFetch(new Response(JSON.stringify({+ schemaVersion: 3, projection: "events",+ events: [{ event: "stream_end", chat_id: "chat", text: "persisted before reconnect" }],+ page: { has_more_before: false },+ })))+ await Bun.sleep(5)+ await setup.flush()+ const frame = setup.captureCharFrame()++ expect(frame.indexOf("persisted before reconnect")).toBeLessThan(+ frame.indexOf("live after reconnect"),+ )+ expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(true)+ app.accept({ event: "turn_end", chat_id: "chat" })+ } finally {+ globalThis.fetch = original+ }+ })++ test("blocks submission until reconnect history is hydrated", async () => {+ const sent: string[] = []+ setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })+ const original = globalThis.fetch+ let request = 0+ let resolveReconnect: (value: Response) => void = () => undefined+ globalThis.fetch = (() => {+ request += 1+ if (request === 1) {+ return Promise.resolve(new Response(JSON.stringify({+ schemaVersion: 3, projection: "events",+ events: [{ event: "stream_end", chat_id: "chat", text: "initial history" }],+ page: { has_more_before: false },+ })))+ }+ return new Promise<Response>((resolve) => {+ resolveReconnect = resolve+ })+ }) as unknown as typeof fetch+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, apiUrl: "http://nanobot.test", apiToken: "token", chatId: "chat" },+ client(sent),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ const ui = app as unknown as {+ composer: TextareaRenderable+ ready: boolean+ status: TextRenderable+ }+ const composer = ui.composer++ try {+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ app.accept({ event: "attached", chat_id: "chat" })+ composer.setText("sent during reconnect")+ composer.submit()+ await waitUntil(() => ui.status.plainText.includes("Not sent"))++ expect(sent).toEqual([])+ expect(composer.plainText).toBe("sent during reconnect")+ expect(ui.status.plainText).toContain("Not sent · press Enter to retry when ready")++ resolveReconnect(new Response(JSON.stringify({+ schemaVersion: 3, projection: "events",+ events: [{ event: "stream_end", chat_id: "chat", text: "restored history" }],+ page: { has_more_before: false },+ })))+ await waitUntil(() => ui.ready)+ expect(ui.status.plainText).toBe("Not sent · press Enter to retry")+ composer.submit()+ await waitUntil(() => sent.length === 1)+ await setup.flush()+ const frame = setup.captureCharFrame()++ expect(sent).toEqual(["sent during reconnect"])+ expect(frame.indexOf("restored history")).toBeLessThan(frame.indexOf("sent during reconnect"))+ } finally {+ globalThis.fetch = original+ }+ })++ test("preserves drafts while a reconnected socket waits to attach", async () => {+ const sent: string[] = []+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup, sent)+ const composer = (app as unknown as { composer: TextareaRenderable }).composer+ const connection = app as unknown as {+ ready: boolean+ submitPending: boolean+ handleStatus(+ status: "reconnecting" | "connected",+ detail?: string,+ info?: { endpoint: string; attempt: number; elapsedMs: number },+ ): void+ }++ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => connection.ready)+ connection.handleStatus("reconnecting", "connection closed", {+ endpoint: "127.0.0.1:8769",+ attempt: 1,+ elapsedMs: 0,+ })+ connection.handleStatus("connected")+ composer.setText("draft before attach")+ composer.submit()+ await waitUntil(() => !connection.submitPending)+ composer.submit()+ await waitUntil(() => !connection.submitPending)++ expect(sent).toEqual([])+ expect(composer.plainText).toBe("draft before attach")++ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => connection.ready)+ expect(sent).toEqual([])+ composer.submit()+ await waitUntil(() => sent.length === 1)+ app.accept({ event: "attached", chat_id: "chat" })+ await Bun.sleep(5)++ expect(sent).toEqual(["draft before attach"])+ })++ test("destroys the renderer and transport together", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ let closed = false+ const exited: string[] = []+ const transport = client()+ transport.close = () => { closed = true }+ const app = NanobotTui.mount(+ setup.renderer,+ {+ ...options,+ chatId: "original-chat",+ onExit: (chatId) => {+ expect(setup?.renderer.isDestroyed).toBe(true)+ exited.push(chatId)+ },+ },+ transport,+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )++ app.stop()+ app.stop()++ expect(closed).toBe(true)+ expect(setup.renderer.isDestroyed).toBe(true)+ expect(exited).toEqual(["chat"])+ })++ test("exits after Ctrl+C input dispatch completes on an idle empty composer", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ let closed = false+ const transport = client()+ transport.close = () => { closed = true }+ NanobotTui.mount(+ setup.renderer,+ options,+ transport,+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )++ setup.mockInput.pressCtrlC()++ expect(closed).toBe(false)+ expect(setup.renderer.isDestroyed).toBe(false)+ await waitUntil(() => closed)+ expect(setup.renderer.isDestroyed).toBe(true)+ })++ test("accepts the exit command before the gateway connection is ready", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ let closed = false+ const transport = client()+ transport.close = () => { closed = true }+ const app = NanobotTui.mount(+ setup.renderer,+ options,+ transport,+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ const composer = (app as unknown as { composer: TextareaRenderable }).composer++ composer.setText("exit")+ composer.submit()+ await waitUntil(() => closed)++ expect(setup.renderer.isDestroyed).toBe(true)+ })++ test("discovers and runs the local /exit command", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const sent: string[] = []+ let closed = false+ const transport = client(sent)+ transport.close = () => { closed = true }+ const app = NanobotTui.mount(+ setup.renderer,+ options,+ transport,+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ const ui = app as unknown as {+ composer: TextareaRenderable+ commandMenu: { visible: boolean }+ }++ await setup.mockInput.typeText("/exit")+ await setup.flush()+ expect(ui.commandMenu.visible).toBe(true)+ expect(setup.captureCharFrame()).toContain("/exit")++ expect(ui.composer.plainText).toBe("/exit")+ ui.composer.submit()+ await waitUntil(() => closed)++ expect(sent).toEqual([])+ expect(setup.renderer.isDestroyed).toBe(true)+ })++ test("detaches without sending a message or reporting a normal exit", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const sent: string[] = []+ const detached: string[] = []+ const exited: string[] = []+ let closed = false+ const transport = client(sent)+ transport.close = () => { closed = true }+ const app = NanobotTui.mount(+ setup.renderer,+ {+ ...options,+ onDetach: (chatId) => { if (chatId) detached.push(chatId) },+ onExit: (chatId) => { exited.push(chatId) },+ },+ transport,+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ const ui = app as unknown as {+ composer: TextareaRenderable+ commandMenu: { visible: boolean }+ }++ await setup.mockInput.typeText("/detach")+ await setup.flush()+ expect(ui.commandMenu.visible).toBe(true)+ expect(setup.captureCharFrame()).toContain("/detach")++ ui.composer.submit()+ await waitUntil(() => closed)++ expect(sent).toEqual([])+ expect(detached).toEqual(["chat"])+ expect(exited).toEqual([])+ expect(setup.renderer.isDestroyed).toBe(true)+ })++ test("detaches before the gateway assigns a chat ID", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ let detached = false+ const transport = { ...client(), activeChatId: "" }+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, onDetach: (chatId) => {+ expect(chatId).toBeUndefined()+ detached = true+ } },+ transport,+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ const composer = (app as unknown as { composer: TextareaRenderable }).composer++ composer.setText("/detach")+ composer.submit()+ await waitUntil(() => detached)++ expect(setup.renderer.isDestroyed).toBe(true)+ })+})diff --git a/tui/src/app/sessions.test.ts b/tui/src/app/sessions.test.tsnew file mode 100644index 000000000..d8713bc23--- /dev/null+++ b/tui/src/app/sessions.test.ts@@ -0,0 +1,995 @@+import { afterEach, describe, expect, test } from "bun:test"+import { CliRenderEvents, TextareaRenderable, TextRenderable } from "@opentui/core"+import { MockTreeSitterClient, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"+import { NanobotTui } from "./app"+import type { RecoveryState, SlashCommand, WorkspaceScopePayload } from "../client"+import { options, client, mount, waitUntil, occurrences } from "./test-support"++describe("NanobotTui session navigation", () => {+ let setup: TestRendererSetup | undefined++ afterEach(() => {+ if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()+ setup = undefined+ })++ const createRenderer = (rendererOptions: Parameters<typeof createTestRenderer>[0]) => (+ createTestRenderer(rendererOptions)+ )+ test("switches and creates gateway chats without replacing core slash commands", async () => {+ setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })+ const original = globalThis.fetch+ globalThis.fetch = (() => Promise.resolve(new Response(JSON.stringify({+ sessions: [+ {+ key: "websocket:chat",+ title: "Current chat",+ preview: "Current work",+ updated_at: "2026-08-13T10:00:00Z",+ },+ {+ key: "websocket:other",+ title: "Release checklist",+ preview: "Prepare stable release",+ updated_at: "2026-08-12T10:00:00Z",+ model_preset: "Deep Research",+ },+ ],+ })))) as unknown as typeof fetch+ const attached: string[] = []+ const newChats: string[] = []+ const transport = client([], attached, newChats)+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },+ transport,+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ app.accept({ event: "attached", chat_id: "chat" })+ await Bun.sleep(1)+ const ui = app as unknown as {+ composer: TextareaRenderable+ sessionMenu: { visible: boolean }+ runtimeControls: { modelText: { plainText: string } }+ }++ try {+ ui.composer.setText("/sessions")+ ui.composer.submit()+ await waitUntil(() => ui.sessionMenu.visible)+ expect(ui.composer.placeholder).toBe("Search sessions")++ ui.composer.setText("release")+ ui.composer.submit()+ await waitUntil(() => attached.length === 1)+ expect(attached).toEqual(["other"])+ expect(ui.runtimeControls.modelText.plainText).toBe("Deep Research ▾")+ expect(ui.runtimeControls.modelText.plainText).not.toContain("test/model")++ app.accept({ event: "attached", chat_id: "other" })+ await Bun.sleep(1)+ ui.composer.setText("/new-chat")+ ui.composer.submit()+ await waitUntil(() => newChats.length === 1)+ expect(newChats).toEqual(["new"])+ expect(ui.runtimeControls.modelText.plainText).toBe("default ▾")+ } finally {+ globalThis.fetch = original+ }+ })++ test("switches away from a running session without losing its queued follow-ups", async () => {+ setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })+ const original = globalThis.fetch+ globalThis.fetch = ((input: string | URL | Request) => {+ const url = String(input)+ if (url.endsWith("/api/sessions")) {+ return Promise.resolve(new Response(JSON.stringify({+ sessions: [+ { key: "websocket:chat", title: "Running chat", run_started_at: 1_700_000_000 },+ { key: "websocket:other", title: "Other chat" },+ ],+ })))+ }+ if (url.endsWith("/api/webui/sidebar-state")) {+ return Promise.resolve(new Response(JSON.stringify({})))+ }+ return Promise.resolve(new Response(JSON.stringify({+ schemaVersion: 3, projection: "events",+ events: url.includes("websocket%3Aother") ? [+ { event: "user_message", chat_id: "other", starts_turn: true, text: "saved question" },+ { event: "stream_end", chat_id: "other", text: "saved answer" },+ { event: "turn_end", chat_id: "other" },+ ] : [],+ page: { has_more_before: false },+ })))+ }) as typeof fetch+ const sent: string[] = []+ const attached: string[] = []+ let activeChatId = "chat"+ const base = client(sent, attached)+ const transport = {+ ...base,+ get activeChatId() { return activeChatId },+ attach(chatId: string) {+ attached.push(chatId)+ activeChatId = chatId+ },+ }+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },+ transport,+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ const ui = app as unknown as {+ ready: boolean+ activeTurn: boolean+ composer: TextareaRenderable+ sessionMenu: { visible: boolean }+ queuePreview: { root: { visible: boolean } }+ status: { plainText: string }+ }++ try {+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => ui.ready)+ app.accept({ event: "goal_status", chat_id: "chat", status: "running", turn_id: "turn" })+ ui.composer.setText("follow up in chat")+ setup.mockInput.pressTab()+ await waitUntil(() => ui.composer.plainText === "")+ expect(ui.queuePreview.root.visible).toBe(true)++ ui.composer.setText("/sessions")+ ui.composer.submit()+ await waitUntil(() => ui.sessionMenu.visible)+ await Bun.sleep(120)+ expect(ui.status.plainText).toContain("2 sessions")++ ui.composer.setText("other")+ ui.composer.submit()+ await waitUntil(() => attached.at(-1) === "other")+ app.accept({ event: "attached", chat_id: "other" })+ await waitUntil(() => ui.ready)+ expect(ui.activeTurn).toBe(false)+ expect(ui.queuePreview.root.visible).toBe(false)+ await setup.flush()+ expect(setup.captureCharFrame()).toContain("saved question")+ expect(setup.captureCharFrame()).toContain("saved answer")++ ui.composer.setText("/sessions")+ ui.composer.submit()+ await waitUntil(() => ui.sessionMenu.visible)+ ui.composer.setText("running")+ ui.composer.submit()+ await waitUntil(() => attached.at(-1) === "chat")+ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({ event: "goal_status", chat_id: "chat", status: "running", turn_id: "turn" })+ await waitUntil(() => ui.ready && ui.activeTurn)+ expect(ui.queuePreview.root.visible).toBe(true)+ expect(sent).toEqual([])++ app.accept({ event: "turn_end", chat_id: "chat", turn_id: "turn" })+ await waitUntil(() => sent.length === 1)+ expect(sent).toEqual(["follow up in chat"])+ } finally {+ globalThis.fetch = original+ }+ })++ test("refreshes expired API credentials before opening sessions", async () => {+ setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })+ const original = globalThis.fetch+ let bootstrapRequests = 0+ const sessionAuthorizations: Array<string | null> = []+ globalThis.fetch = (async (input: string | URL | Request, init?: RequestInit) => {+ const url = String(input)+ const authorization = new Headers(init?.headers).get("Authorization")+ if (url.endsWith("/webui/bootstrap")) {+ bootstrapRequests += 1+ return new Response(JSON.stringify({+ ws_url: "ws://nanobot.test/ws",+ token: "fresh-websocket-token",+ api_token: "fresh-api-token",+ }))+ }+ if (authorization === "Bearer expired-api-token") {+ return new Response("Unauthorized", { status: 401 })+ }+ if (url.endsWith("/api/sessions")) {+ sessionAuthorizations.push(authorization)+ return new Response(JSON.stringify({+ sessions: [{ key: "websocket:chat", title: "Current chat" }],+ }))+ }+ return new Response("{}")+ }) as typeof fetch+ const app = NanobotTui.mount(+ setup.renderer,+ {+ ...options,+ bootstrapUrl: "http://nanobot.test/webui/bootstrap",+ bootstrapSecret: "bootstrap-secret",+ apiUrl: "http://nanobot.test",+ apiToken: "expired-api-token",+ },+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ app.accept({ event: "attached", chat_id: "chat" })+ const ui = app as unknown as {+ ready: boolean+ composer: TextareaRenderable+ sessionMenu: { visible: boolean }+ status: { plainText: string }+ }++ try {+ await waitUntil(() => ui.ready)+ ui.composer.setText("/sessions")+ ui.composer.submit()++ await waitUntil(() => bootstrapRequests >= 1)+ await waitUntil(() => ui.sessionMenu.visible)+ expect(bootstrapRequests).toBe(1)+ expect(sessionAuthorizations.at(-1)).toBe("Bearer fresh-api-token")+ expect(ui.status.plainText).not.toContain("HTTP 401")+ } finally {+ globalThis.fetch = original+ }+ })++ test("tracks canonical presets without overwriting a session override", async () => {+ setup = await createRenderer({ width: 96, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup)+ const ui = app as unknown as { runtimeControls: { modelText: { plainText: string } } }++ app.accept({ event: "attached", chat_id: "chat", model_preset: "Codex" })+ app.accept({+ event: "turn_model_updated",+ chat_id: "chat",+ model_name: "openai/gpt-5.6",+ model_preset: "Codex",+ })+ await setup.flush()+ expect(ui.runtimeControls.modelText.plainText).toBe("Codex ▾")+ expect(ui.runtimeControls.modelText.plainText).not.toContain("openai/gpt-5.6")++ app.accept({+ event: "runtime_model_updated",+ model_name: "deepseek/deepseek-chat",+ model_preset: "DeepSeek",+ })+ await setup.flush()+ expect(ui.runtimeControls.modelText.plainText).toBe("Codex ▾")+ expect(ui.runtimeControls.modelText.plainText).not.toContain("DeepSeek")+ })++ test("returns a default-following chat to the canonical default preset", async () => {+ setup = await createRenderer({ width: 96, height: 20, screenMode: "alternate-screen" })+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, model: "openai/gpt-5.6", modelPreset: "Codex" },+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ const ui = app as unknown as { runtimeControls: { modelText: { plainText: string } } }++ app.accept({ event: "attached", chat_id: "chat", model_preset: null })+ app.accept({+ event: "runtime_model_updated",+ model_name: "deepseek/deepseek-chat",+ model_preset: null,+ })+ await setup.flush()++ expect(ui.runtimeControls.modelText.plainText).toBe("default ▾")+ expect(ui.runtimeControls.modelText.plainText).not.toContain("deepseek/deepseek-chat")+ })++ test("refreshes the canonical preset after the model command completes", async () => {+ setup = await createRenderer({ width: 96, height: 20, screenMode: "alternate-screen" })+ const original = globalThis.fetch+ globalThis.fetch = ((input: string | URL | Request) => {+ if (String(input).endsWith("/api/webui/sidebar-state")) {+ return Promise.resolve(new Response(JSON.stringify({})))+ }+ return Promise.resolve(new Response(JSON.stringify({+ sessions: [{ key: "websocket:chat", model_preset: "Deep Research" }],+ })))+ }) as typeof fetch+ const sent: string[] = []+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },+ client(sent),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ const ui = app as unknown as {+ composer: TextareaRenderable+ commandMenu: { setCommands(commands: SlashCommand[]): void }+ runtimeControls: { modelText: { plainText: string } }+ }++ try {+ app.accept({ event: "attached", chat_id: "chat", model_preset: null })+ ui.commandMenu.setCommands([{+ command: "/model",+ title: "Model",+ description: "Show or switch model presets",+ argHint: "[preset]",+ lifecycle: "side_channel",+ acceptsArgs: true,+ }])+ ui.composer.setText("/model deep research")+ ui.composer.submit()+ await waitUntil(() => sent.length === 1)+ app.accept({+ event: "message",+ chat_id: "chat",+ text: "Switched model preset to Deep Research.",+ turn_id: "turn",+ })+ await waitUntil(() => ui.runtimeControls.modelText.plainText.includes("Deep Research"))++ expect(sent).toEqual(["/model deep research"])+ } finally {+ globalThis.fetch = original+ }+ })++ test("opens composer runtime controls by mouse and applies canonical choices", async () => {+ const original = globalThis.fetch+ const sent: string[] = []+ const scopes: WorkspaceScopePayload[] = []+ let settingsRequests = 0+ let workspaceRequests = 0+ globalThis.fetch = (async (input: string | URL | Request) => {+ const url = String(input)+ if (url.endsWith("/api/settings")) {+ settingsRequests += 1+ return new Response(JSON.stringify({+ model_presets: [+ { name: "default", model: "test/model" },+ { name: "fast", model: "fast/model" },+ ],+ }))+ }+ if (url.endsWith("/api/workspaces")) {+ workspaceRequests += 1+ return new Response(JSON.stringify({+ controls: { can_use_full_access: true },+ }))+ }+ return new Response(JSON.stringify({ sessions: [] }))+ }) as typeof fetch+ setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },+ client(sent, [], [], [], [], scopes),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ app.accept({ event: "attached", chat_id: "chat" })+ const ui = app as unknown as {+ runtimeControls: {+ modelText: TextRenderable+ accessText: TextRenderable+ contextText: TextRenderable+ visible: boolean+ menuRoot: { getChildren(): unknown[] }+ }+ composer: TextareaRenderable+ status: TextRenderable+ meta: TextRenderable+ }++ try {+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ await setup.renderOnce()+ expect(setup.renderer.getCursorState()).toMatchObject({+ style: "line",+ blinking: false,+ })+ expect(ui.runtimeControls.modelText.selectable).toBe(false)+ expect(ui.runtimeControls.accessText.selectable).toBe(false)+ expect(ui.runtimeControls.contextText.selectable).toBe(false)+ expect(ui.status.selectable).toBe(false)+ expect(ui.meta.selectable).toBe(false)+ app.accept({ event: "goal_status", chat_id: "chat", status: "running" })+ await setup.flush()+ await setup.mockMouse.click(+ ui.runtimeControls.modelText.x + 2,+ ui.runtimeControls.modelText.y,+ )+ await waitUntil(() => ui.runtimeControls.visible)+ await setup.flush()+ const modelRows = ui.runtimeControls.menuRoot.getChildren() as TextRenderable[]+ expect(modelRows.every((row) => !row.selectable)).toBe(true)+ const fast = modelRows.find((row) => row.plainText.includes("fast"))+ if (!fast) throw new Error("fast model row was not rendered")+ ui.composer.blur()+ expect(ui.composer.focused).toBe(false)+ await setup.mockMouse.click(fast.x + 2, fast.y)+ await waitUntil(() => sent.includes("/model fast"))+ expect(ui.composer.focused).toBe(true)++ await setup.mockMouse.click(+ ui.runtimeControls.accessText.x + 2,+ ui.runtimeControls.accessText.y,+ )+ await waitUntil(() => ui.runtimeControls.visible)+ await setup.flush()+ const accessRows = ui.runtimeControls.menuRoot.getChildren() as TextRenderable[]+ const full = accessRows.find((row) => row.plainText.includes("Full access"))+ if (!full) throw new Error("full access row was not rendered")+ ui.composer.blur()+ expect(ui.composer.focused).toBe(false)+ await setup.mockMouse.click(full.x + 2, full.y)+ expect(ui.composer.focused).toBe(true)++ expect(scopes).toEqual([{+ project_path: "/tmp/nanobot-workspace",+ access_mode: "full",+ restrict_to_workspace: false,+ }])++ await setup.mockMouse.click(+ ui.runtimeControls.modelText.x + 2,+ ui.runtimeControls.modelText.y,+ )+ await waitUntil(() => ui.runtimeControls.visible)+ ui.composer.blur()+ await setup.mockMouse.click(ui.status.x, ui.status.y)+ expect(ui.runtimeControls.visible).toBe(false)+ expect(ui.composer.focused).toBe(true)++ await setup.mockMouse.click(+ ui.runtimeControls.accessText.x + 2,+ ui.runtimeControls.accessText.y,+ )+ await waitUntil(() => ui.runtimeControls.visible)+ ui.composer.blur()+ await setup.mockMouse.click(ui.status.x, ui.status.y)+ expect(ui.runtimeControls.visible).toBe(false)+ expect(ui.composer.focused).toBe(true)+ expect(settingsRequests).toBe(1)+ expect(workspaceRequests).toBe(1)++ expect((app as unknown as { activeTurn: boolean }).activeTurn).toBe(true)+ app.accept({ event: "goal_status", chat_id: "chat", status: "idle" })+ } finally {+ globalThis.fetch = original+ }+ })++ test("selects model presets beyond the runtime menu's visible limit", async () => {+ const original = globalThis.fetch+ const sent: string[] = []+ globalThis.fetch = (async (input: string | URL | Request) => {+ const url = String(input)+ if (url.endsWith("/api/settings")) {+ return new Response(JSON.stringify({+ model_presets: [+ { name: "default", model: "test/model" },+ ...Array.from({ length: 10 }, (_, index) => ({+ name: `preset-${index}`,+ model: `test/model-${index}`,+ })),+ ],+ }))+ }+ if (url.endsWith("/api/workspaces")) {+ return new Response(JSON.stringify({ controls: { can_use_full_access: true } }))+ }+ return new Response(JSON.stringify({ sessions: [] }))+ }) as typeof fetch+ setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },+ client(sent),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ app.accept({ event: "attached", chat_id: "chat" })+ const ui = app as unknown as {+ ready: boolean+ runtimeControls: {+ modelText: TextRenderable+ visible: boolean+ menuRoot: { getChildren(): unknown[] }+ }+ }++ try {+ await waitUntil(() => ui.ready)+ await setup.renderOnce()+ await setup.mockMouse.click(+ ui.runtimeControls.modelText.x + 2,+ ui.runtimeControls.modelText.y,+ )+ await waitUntil(() => ui.runtimeControls.visible)+ await setup.flush()+ expect(ui.runtimeControls.menuRoot.getChildren()).toHaveLength(9)+ expect(setup.captureCharFrame()).toContain("1–8 of 11 ↓")+ expect(setup.captureCharFrame()).not.toContain("preset-8")++ for (let index = 0; index < 9; index += 1) setup.mockInput.pressArrow("down")+ await setup.flush()+ expect(setup.captureCharFrame()).toContain("› preset-8")+ expect(setup.captureCharFrame()).toContain("3–10 of 11 ↑↓")++ setup.mockInput.pressEnter()+ await waitUntil(() => sent.includes("/model preset-8"))+ expect(ui.runtimeControls.visible).toBe(false)+ } finally {+ globalThis.fetch = original+ }+ })++ test("switches sessions only through the sessions command", async () => {+ const original = globalThis.fetch+ globalThis.fetch = ((input: string | URL | Request) => {+ const url = String(input)+ if (url.endsWith("/api/webui/sidebar-state")) {+ return Promise.resolve(new Response(JSON.stringify({})))+ }+ return Promise.resolve(new Response(JSON.stringify({+ sessions: [+ { key: "websocket:chat", title: "Current chat", preview: "Current work" },+ { key: "websocket:other", title: "Release checklist", preview: "Ship it" },+ ],+ })))+ }) as typeof fetch+ const attached: string[] = []+ setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },+ client([], attached),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ app.accept({ event: "attached", chat_id: "chat" })+ const ui = app as unknown as {+ composer: TextareaRenderable+ sessionMenu: { visible: boolean; root: { getChildren(): unknown[] } }+ title: { getChildren(): unknown[] }+ }++ try {+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ await setup.renderOnce()+ const titleItems = ui.title.getChildren() as TextRenderable[]+ expect(titleItems.some((item) => item.id === "nanobot-tui-title-text")).toBe(false)+ expect(ui.sessionMenu.visible).toBe(false)++ ui.composer.setText("/sessions")+ ui.composer.submit()+ await waitUntil(() => ui.sessionMenu.visible)+ await setup.flush()+ expect(ui.composer.placeholder).toBe("Search sessions")++ const rows = ui.sessionMenu.root.getChildren() as TextRenderable[]+ const other = rows.find((row) => row.plainText.includes("Release checklist"))+ if (!other) throw new Error("other session row was not rendered")+ ui.composer.blur()+ await setup.mockMouse.click(other.x + 2, other.y)+ await waitUntil(() => attached.length === 1)+ expect(attached).toEqual(["other"])+ expect(ui.sessionMenu.visible).toBe(false)+ expect(ui.composer.focused).toBe(true)+ } finally {+ globalThis.fetch = original+ }+ })++ test("offers clickable recovery actions without letting a late response revive stale state", async () => {+ setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })+ const calls: Array<{ action: string; chatId: string; recoveryId: string }> = []+ let deferredResolve: ((state: RecoveryState) => void) | undefined+ const recoveryClient = client()+ recoveryClient.updateRecovery = (action, chatId, recoveryId) => {+ calls.push({ action, chatId, recoveryId })+ if (recoveryId === "recovery-1") {+ return Promise.resolve({ status: "resuming", recovery_id: recoveryId })+ }+ if (action === "dismiss") {+ return Promise.resolve({ status: "recovered", recovery_id: recoveryId })+ }+ return new Promise((resolve) => { deferredResolve = resolve })+ }+ const app = NanobotTui.mount(+ setup.renderer,+ options,+ recoveryClient,+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ app.accept({+ event: "attached",+ chat_id: "chat",+ recovery_state: {+ status: "awaiting_user",+ recovery_id: "recovery-1",+ reason: "tool execution interrupted",+ },+ })+ const ui = app as unknown as {+ activeTurn: boolean+ composer: TextareaRenderable+ recoveryNotice: {+ visible: boolean+ dismiss: TextRenderable+ resume: TextRenderable+ }+ status: TextRenderable+ }++ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ await setup.renderOnce()+ expect(setup.captureCharFrame()).toContain("⚠ Task interrupted")+ expect(setup.captureCharFrame()).toContain("Tools will not replay automatically")+ expect(ui.status.plainText).toContain("continue or dismiss")+ expect(ui.activeTurn).toBe(false)+ expect(ui.composer.focused).toBe(true)++ await setup.mockMouse.click(ui.recoveryNotice.resume.x + 1, ui.recoveryNotice.resume.y)+ await waitUntil(() => calls.length === 1 && ui.activeTurn)+ expect(calls[0]).toEqual({+ action: "continue",+ chatId: "chat",+ recoveryId: "recovery-1",+ })+ expect(ui.recoveryNotice.visible).toBe(false)+ expect(ui.status.plainText).toContain("Continuing")++ app.accept({+ event: "recovery_state",+ chat_id: "chat",+ status: "awaiting_user",+ recovery_id: "recovery-2",+ })+ await setup.renderOnce()+ await setup.mockMouse.click(ui.recoveryNotice.resume.x + 1, ui.recoveryNotice.resume.y)+ await waitUntil(() => calls.length === 2)+ app.accept({+ event: "recovery_state",+ chat_id: "chat",+ status: "recovered",+ recovery_id: "recovery-2",+ })+ deferredResolve?.({ status: "resuming", recovery_id: "recovery-2" })+ await Bun.sleep(1)++ expect(ui.recoveryNotice.visible).toBe(false)+ expect(ui.activeTurn).toBe(false)+ expect(ui.composer.focused).toBe(true)++ app.accept({+ event: "recovery_state",+ chat_id: "chat",+ status: "awaiting_user",+ recovery_id: "recovery-unavailable",+ can_continue: false,+ })+ await setup.renderOnce()+ const unavailableFrame = setup.captureCharFrame()+ expect(unavailableFrame).toContain("can’t be resumed safely")+ expect(unavailableFrame).not.toContain("Continue")+ expect(ui.status.plainText).toContain("dismiss to start a new message")++ app.accept({+ event: "recovery_state",+ chat_id: "chat",+ status: "awaiting_user",+ recovery_id: "recovery-3",+ })+ await setup.renderOnce()+ await setup.mockMouse.click(ui.recoveryNotice.dismiss.x + 1, ui.recoveryNotice.dismiss.y)+ await waitUntil(() => calls.length === 3 && !ui.recoveryNotice.visible)+ expect(calls[2]).toEqual({+ action: "dismiss",+ chatId: "chat",+ recoveryId: "recovery-3",+ })++ app.accept({+ event: "recovery_state",+ chat_id: "chat",+ status: "awaiting_user",+ recovery_id: "recovery-4",+ can_continue: false,+ })+ await setup.renderOnce()+ expect(ui.recoveryNotice.resume.visible).toBe(false)+ expect(ui.recoveryNotice.dismiss.visible).toBe(true)+ })++ test("preserves gateway slash lifecycle while local navigation stays in the same menu", async () => {+ setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })+ const sent: string[] = []+ const app = mount(setup, sent)+ app.accept({ event: "attached", chat_id: "chat" })+ await Bun.sleep(1)+ const ui = app as unknown as {+ composer: TextareaRenderable+ commandMenu: {+ setCommands(commands: SlashCommand[]): void+ }+ activeTurn: boolean+ }+ ui.commandMenu.setCommands([{+ command: "/new",+ title: "New chat",+ description: "Reset this chat",+ argHint: "",+ lifecycle: "finalize_active_turn",+ acceptsArgs: false,+ }, {+ command: "/status",+ title: "Status",+ description: "Show status",+ argHint: "",+ lifecycle: "side_channel",+ acceptsArgs: false,+ }])++ app.accept({ event: "goal_status", chat_id: "chat", status: "running" })+ ui.composer.setText("/status")+ ui.composer.submit()+ await waitUntil(() => sent.includes("/status"))+ expect(ui.activeTurn).toBe(true)+ app.accept({+ event: "message",+ chat_id: "chat",+ text: "Runtime healthy",+ turn_id: "turn",+ })+ await setup.flush()+ expect(setup.captureCharFrame()).toContain("Runtime healthy")++ ui.composer.setText("/new")+ ui.composer.submit()+ await waitUntil(() => sent.includes("/new"))+ expect(ui.activeTurn).toBe(false)+ expect(sent).toEqual(["/status", "/new"])+ await setup.flush()+ expect(setup.captureCharFrame()).toContain("/new")+ })++ test("blocks sends and ignores late session results after closing the picker", async () => {+ setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })+ const original = globalThis.fetch+ let resolveFetch: ((response: Response) => void) | undefined+ globalThis.fetch = ((input: string | URL | Request) => {+ if (String(input).endsWith("/api/webui/sidebar-state")) {+ return Promise.resolve(new Response(JSON.stringify({})))+ }+ return new Promise<Response>((resolve) => {+ resolveFetch = resolve+ })+ }) as typeof fetch+ const sent: string[] = []+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },+ client(sent),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ app.accept({ event: "attached", chat_id: "chat" })+ await Bun.sleep(1)+ const ui = app as unknown as {+ composer: TextareaRenderable+ sessionMenu: { visible: boolean }+ sessionLoading: boolean+ }++ try {+ ui.composer.setText("/sessions")+ ui.composer.submit()+ await waitUntil(() => ui.sessionLoading)+ ui.composer.setText("do not send")+ ui.composer.submit()+ await Bun.sleep(10)+ expect(sent).toEqual([])++ setup.mockInput.pressEscape()+ await Bun.sleep(10)+ resolveFetch?.(new Response(JSON.stringify({ sessions: [] })))+ await Bun.sleep(10)+ expect(ui.sessionMenu.visible).toBe(false)+ expect(ui.composer.plainText).toBe("")+ } finally {+ globalThis.fetch = original+ }+ })++ test("applies a query typed while sessions are still loading", async () => {+ setup = await createRenderer({ width: 80, height: 24, screenMode: "alternate-screen" })+ const original = globalThis.fetch+ let resolveFetch: ((response: Response) => void) | undefined+ globalThis.fetch = ((input: string | URL | Request) => {+ if (String(input).endsWith("/api/webui/sidebar-state")) {+ return Promise.resolve(new Response(JSON.stringify({})))+ }+ return new Promise<Response>((resolve) => {+ resolveFetch = resolve+ })+ }) as typeof fetch+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ app.accept({ event: "attached", chat_id: "chat" })+ await Bun.sleep(1)+ const ui = app as unknown as {+ composer: TextareaRenderable+ sessionMenu: { visible: boolean }+ }++ try {+ ui.composer.setText("/sessions")+ ui.composer.submit()+ await waitUntil(() => resolveFetch !== undefined)+ ui.composer.setText("release")+ resolveFetch!(new Response(JSON.stringify({+ sessions: [+ { key: "websocket:chat", title: "Current chat", preview: "Current work" },+ { key: "websocket:other", title: "Release checklist", preview: "Ship it" },+ ],+ })))+ await waitUntil(() => ui.sessionMenu.visible)+ await setup.flush()+ const frame = setup.captureCharFrame()+ expect(frame).toContain("Release checklist")+ expect(occurrences(frame, "Current chat")).toBe(0)+ } finally {+ globalThis.fetch = original+ }+ })++ test("shows compact session context without exposing private reasoning", async () => {+ setup = await createRenderer({ width: 96, height: 26, screenMode: "alternate-screen" })+ const original = globalThis.fetch+ globalThis.fetch = ((input: string | URL | Request) => {+ expect(String(input)).toContain("/api/sessions/websocket%3Achat/context")+ return Promise.resolve(new Response(JSON.stringify({+ total_messages: 24,+ archived_messages: 16,+ replay_messages: 10,+ estimated_replay_tokens: 2048,+ estimated_summary_tokens: 128,+ estimated_session_tokens: 2176,+ archived_summary: "The earlier turns agreed on a release plan.",+ archived_summary_at: "2026-08-13T10:00:00Z",+ })))+ }) as typeof fetch+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, apiUrl: "http://nanobot.test", apiToken: "secret" },+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )+ app.accept({ event: "attached", chat_id: "chat" })+ const ui = app as unknown as {+ composer: TextareaRenderable+ contextPanel: { visible: boolean }+ runtimeControls: { contextText: { plainText: string } }+ }++ try {+ ui.composer.setText("/context")+ ui.composer.submit()+ await waitUntil(() => ui.contextPanel.visible)+ await setup.flush()+ expect(ui.runtimeControls.contextText.plainText).toContain("~2.2k ctx")+ const frame = setup.captureCharFrame()++ expect(frame).toContain("~2.2k tokens · 10 replay · 16 archived")+ expect(frame).toContain("The earlier turns agreed on a release plan.")+ expect(frame).not.toContain("Agent context")+ expect(frame).not.toContain("summary active")+ expect(frame).not.toContain("memory, instructions, and skills are added separately")++ setup.resize(40, 10)+ await setup.renderOnce()+ const compact = setup.captureCharFrame()+ expect(occurrences(compact, "Agent context")).toBe(0)+ expect(occurrences(compact, "Ask nanobot anything")).toBe(1)++ setup.mockInput.pressEscape()+ await waitUntil(() => !ui.contextPanel.visible)+ expect(ui.contextPanel.visible).toBe(false)+ } finally {+ globalThis.fetch = original+ }+ })++ test("opens the latest turn diff as a full-screen, navigable view", async () => {+ setup = await createRenderer({ width: 96, height: 28, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ app.accept({ event: "message_accepted", chat_id: "chat", turn_id: "edit-turn" })+ app.accept({+ event: "file_edit",+ chat_id: "chat",+ edits: [{+ call_id: "edit-1",+ tool: "edit_file",+ path: "src/first.ts",+ status: "done",+ added: 2,+ deleted: 1,+ diff: {+ format: "unified",+ truncated: true,+ text: [+ "--- a/src/first.ts",+ "+++ b/src/first.ts",+ "@@ -1 +1,2 @@",+ "-const oldValue = 1",+ "+const newValue = 2",+ "+export { newValue }",+ ].join("\n"),+ },+ }, {+ call_id: "edit-2",+ tool: "write_file",+ path: "src/second.py",+ status: "done",+ added: 1,+ deleted: 0,+ diff: {+ format: "unified",+ text: [+ "--- a/src/second.py",+ "+++ b/src/second.py",+ "@@ -0,0 +1 @@",+ "+print('hello')",+ ].join("\n"),+ },+ }],+ })+ app.accept({ event: "turn_end", chat_id: "chat", turn_id: "edit-turn" })+ const ui = app as unknown as {+ composer: TextareaRenderable+ diffViewer: {+ visible: boolean+ scroll: { getChildren(): Array<{ addedBg?: { toInts(): number[] } }> }+ }+ }++ ui.composer.setText("/diff")+ ui.composer.submit()+ await waitUntil(() => ui.diffViewer.visible)+ await setup.flush()+ let frame = setup.captureCharFrame()+ expect(frame).toContain("Diff · Last turn · 2 changes · +3 -1")+ expect(frame).toContain("1/2 · src/first.ts · +2 -1")+ expect(frame).toContain("const newValue = 2")+ expect(frame).toContain("Diff truncated by the gateway")+ expect(frame).not.toContain("Ask nanobot anything")++ setup.mockInput.pressArrow("right")+ await setup.flush()+ frame = setup.captureCharFrame()+ expect(frame).toContain("2/2 · src/second.py · +1 -0")+ expect(frame).toContain("print('hello')")++ setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")+ await setup.flush()+ expect(ui.diffViewer.scroll.getChildren()[0]?.addedBg?.toInts().slice(0, 3)).toEqual([231, 246, 236])+ expect(setup.captureCharFrame()).toContain("print('hello')")++ setup.resize(52, 18)+ await setup.renderOnce()+ expect(setup.captureCharFrame()).toContain("←/→ file · pgup/pgdn · esc")++ setup.mockInput.pressEscape()+ await waitUntil(() => !ui.diffViewer.visible)+ await setup.flush()+ expect(setup.captureCharFrame()).toContain("Ask nanobot anything")+ })+})diff --git a/tui/src/app/status.ts b/tui/src/app/status.tsnew file mode 100644index 000000000..f43bb6679--- /dev/null+++ b/tui/src/app/status.ts@@ -0,0 +1,66 @@+import type { ConnectionStatus, ConnectionStatusInfo, RetryStatus } from "../client"++export function formatElapsed(milliseconds: number): string {+ const seconds = Math.max(0, Math.floor(milliseconds / 1000))+ if (seconds < 60) return `${seconds}s`+ return `${Math.floor(seconds / 60)}m ${String(seconds % 60).padStart(2, "0")}s`+}++export function connectionStatusText(+ status: ConnectionStatus,+ info?: ConnectionStatusInfo,+): string {+ if (["starting", "connecting", "connected"].includes(status)) return "Getting ready…"+ if (status === "reconnecting") return "Resuming…"+ if (status === "unavailable") {+ return info?.health === "degraded"+ ? "Still getting ready…"+ : "Nanobot is taking longer to respond…"+ }+ if (status === "error") return "Nanobot unavailable · restart nanobot"+ return "Session ended"+}++function retryFailureLabel(errorKind: string): string {+ if (errorKind === "billing") return "Model provider quota is unavailable"+ if (errorKind === "connection") return "Could not connect to the model provider"+ if (errorKind === "timeout") return "Model provider request timed out"+ if (errorKind === "rate_limit") return "Model provider rate limit reached"+ if (errorKind === "server") return "Model provider service error"+ return "Model provider request failed"+}++export function terminalModelFailureLine(errorKind?: string, attempts?: number): string {+ const reason = retryFailureLabel(errorKind || "unknown")+ if (errorKind === "billing") {+ return `${reason}. Add credit or check billing for the provider account, then try again.`+ }+ const retryResult = typeof attempts === "number" && Number.isInteger(attempts) && attempts > 0+ ? ` The request still failed on attempt ${attempts}, so retries stopped.`+ : ""+ return `${reason}.${retryResult} Check the provider configuration or service status, then try again.`+}++export interface RenderedRetryStatus extends RetryStatus {+ nextRetryAtMs?: number+}++export function retryStatusLine(status: RenderedRetryStatus, nowMs = Date.now()): string {+ const label = retryFailureLabel(status.error_kind)+ if (status.state === "exhausted") return `${label} · ending turn`+ if (status.state === "recovered") return "Connection restored"+ if (status.state === "cleared") return "Retry status cleared"+ const remaining = Math.max(+ 0,+ Math.ceil(((status.nextRetryAtMs ?? nowMs) - nowMs) / 1000),+ )+ const attempt = status.max_attempts+ ? `${status.attempt}/${status.max_attempts}`+ : String(status.attempt)+ return `${label} · retrying in ${remaining}s · attempt ${attempt}`+}++export function sessionExitMessage(chatId: string): string {+ const sessionId = `websocket:${chatId}`+ return `Resume with: nanobot agent --session ${sessionId}\n`+}diff --git a/tui/src/app/test-support.ts b/tui/src/app/test-support.tsnew file mode 100644index 000000000..dfc434b8e--- /dev/null+++ b/tui/src/app/test-support.ts@@ -0,0 +1,96 @@+import { MockTreeSitterClient, type TestRendererSetup } from "@opentui/core/testing"++import type { MessageOptions, RecoveryState, WorkspaceScopePayload } from "../client"+import { NanobotTui, type AppOptions } from "./app"++export const options: AppOptions = {+ wsUrl: "ws://localhost.invalid/ws",+ apiUrl: "",+ apiToken: "",+ model: "test/model",+ modelPreset: "default",+ workspace: "/tmp/nanobot-workspace",+ version: "test",+ access: "workspace access",+ theme: "auto",+}++interface HiddenScrollBar {+ visible: boolean+ slider: { visible: boolean }+ startArrow: { visible: boolean }+ endArrow: { visible: boolean }+}++export interface HiddenScrollBox {+ verticalScrollBar: HiddenScrollBar+ horizontalScrollBar: HiddenScrollBar+}++export function occurrences(frame: string, value: string): number {+ return frame.split(value).length - 1+}++export function contrastRatio(foreground: string, background: string): number {+ const luminance = (color: string) => {+ const channel = (offset: number) => {+ const value = Number.parseInt(color.slice(offset, offset + 2), 16) / 255+ return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4+ }+ return 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5)+ }+ const [lighter, darker] = [luminance(foreground), luminance(background)].sort((a, b) => b - a)+ return ((lighter ?? 0) + 0.05) / ((darker ?? 0) + 0.05)+}++export async function waitUntil(predicate: () => boolean, timeout = 1_000): Promise<void> {+ const deadline = Date.now() + timeout+ while (!predicate() && Date.now() < deadline) await Bun.sleep(5)+ if (!predicate()) throw new Error(`condition was not met within ${timeout}ms`)+}++export function client(+ sent: string[] = [],+ attached: string[] = [],+ newChats: string[] = [],+ sentOptions: MessageOptions[] = [],+ forks: Array<{ source: string; before: number; title?: string }> = [],+ scopes: WorkspaceScopePayload[] = [],+) {+ return {+ activeChatId: "chat",+ connect() {},+ close() {},+ send(content: string, messageOptions: MessageOptions = {}) {+ sent.push(content)+ sentOptions.push(messageOptions)+ return "turn"+ },+ attach(chatId: string) {+ attached.push(chatId)+ },+ newChat(_scope?: WorkspaceScopePayload) {+ newChats.push("new")+ },+ forkChat(source: string, before: number, title?: string) {+ forks.push({ source, before, ...(title ? { title } : {}) })+ },+ setWorkspaceScope(scope: WorkspaceScopePayload) {+ scopes.push(scope)+ },+ updateRecovery(+ _action: "continue" | "dismiss",+ _chatId: string,+ recoveryId: string,+ ): Promise<RecoveryState> {+ return Promise.resolve({ status: "recovered" as const, recovery_id: recoveryId })+ },+ }+}++export const mount = (setup: TestRendererSetup, sent: string[] = []) => NanobotTui.mount(+ setup.renderer,+ options,+ client(sent),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+)diff --git a/tui/src/app/theme.ts b/tui/src/app/theme.tsnew file mode 100644index 000000000..b88ac2826--- /dev/null+++ b/tui/src/app/theme.ts@@ -0,0 +1,261 @@+import {+ RGBA,+ StyledText,+ SyntaxStyle,+ TextAttributes,+ parseColor,+ type ColorInput,+ type TextChunk,+} from "@opentui/core"++import type { QueuePreviewTheme } from "../composer/queue-preview"+import type { CommandMenuTheme } from "../menus/command-menu"+import type { TranscriptTheme } from "../rendering/transcript"+import type { ContextPanelTheme } from "../views/context-panel"+import type { DiffViewerTheme } from "../views/diff-viewer"+import type { FooterHintTheme } from "../views/footer-hints"+import type { RecoveryNoticeTheme } from "../views/recovery-notice"+import type { UsagePanelTheme } from "../views/usage-panel"++export const IMAGE_PLACEHOLDER_STYLE = "image.placeholder"+export const SHIMMER_INTERVAL_MS = 80+const SHIMMER_PAUSE = 16+const SHIMMER_BAND = 4+const TERMINAL_SHIMMER_BAND = 1++export interface Palette {+ referenceBackground: string+ text: ColorInput+ muted: ColorInput+ faint: ColorInput+ border: ColorInput+ accent: ColorInput+ link: ColorInput+ success: ColorInput+ warning: ColorInput+ error: ColorInput+ user: ColorInput+ userBackground: ColorInput+ warm: ColorInput+ cool: ColorInput+}++export const DARK: Palette = {+ referenceBackground: "#0E0F11",+ text: "#ECEDEE",+ muted: "#A1A1AA",+ faint: "#71717A",+ border: "#3F3F46",+ accent: "#EF8E30",+ link: "#60A5FA",+ success: "#5CC489",+ warning: "#F5C451",+ error: "#F87171",+ user: "#EF8E30",+ // Codex-style turn anchor: 12% white over the reference dark background.+ userBackground: "#2B2C2E",+ warm: "#C26A25",+ cool: "#1795A2",+}++export const LIGHT: Palette = {+ referenceBackground: "#FAFAFA",+ text: "#18181B",+ muted: "#6F6F78",+ faint: "#8A8A94",+ border: "#D4D4D8",+ accent: "#B94D0B",+ link: "#1D4ED8",+ success: "#166534",+ warning: "#A16207",+ error: "#B91C1C",+ user: "#B94D0B",+ // Codex-style turn anchor: 4% black over the reference light background.+ userBackground: "#F0F0F0",+ warm: "#C2410C",+ cool: "#0F766E",+}++// Until the terminal answers OSC 10/11, its default foreground is the only+// text color known to match its default background.+export const TERMINAL: Palette = {+ ...DARK,+ text: RGBA.defaultForeground(),+ muted: RGBA.defaultForeground(),+ faint: RGBA.defaultForeground(),+ border: RGBA.defaultForeground(),+ accent: RGBA.defaultForeground(),+ link: RGBA.defaultForeground(),+ success: RGBA.defaultForeground(),+ warning: RGBA.defaultForeground(),+ error: RGBA.defaultForeground(),+ user: RGBA.defaultForeground(),+ userBackground: RGBA.defaultBackground(),+ warm: RGBA.defaultForeground(),+ cool: RGBA.defaultForeground(),+}+++export function syntaxStyle(palette: Palette): SyntaxStyle {+ const color = (value: ColorInput) => {+ const parsed = parseColor(value)+ return { fg: parsed }+ }+ return SyntaxStyle.fromStyles({+ default: color(palette.text),+ keyword: { ...color(palette.accent), bold: true },+ string: color(palette.success),+ comment: { ...color(palette.muted), italic: true },+ number: color(palette.link),+ function: color(palette.warm),+ type: color(palette.cool),+ variable: color(palette.text),+ property: color(palette.link),+ "markup.heading": { ...color(palette.accent), bold: true },+ "markup.strong": { ...color(palette.text), bold: true },+ "markup.italic": { ...color(palette.muted), italic: true },+ "markup.link": { ...color(palette.link), underline: true },+ "markup.link.label": { ...color(palette.link), underline: true },+ "markup.link.url": { ...color(palette.link), underline: true },+ "markup.raw": color(palette.warm),+ conceal: color(palette.faint),+ })+}++export function composerSyntaxStyle(palette: Palette): SyntaxStyle {+ return SyntaxStyle.fromStyles({+ [IMAGE_PLACEHOLDER_STYLE]: { fg: parseColor(palette.accent), bold: true },+ })+}++export function transcriptTheme(palette: Palette, backgroundKnown: boolean): TranscriptTheme {+ return {+ text: palette.text,+ muted: palette.muted,+ error: palette.error,+ user: palette.user,+ userBackground: backgroundKnown ? palette.userBackground : null,+ border: palette.border,+ syntax: syntaxStyle(palette),+ }+}++export function commandMenuTheme(palette: Palette): CommandMenuTheme {+ return {+ text: palette.text,+ muted: palette.muted,+ border: palette.border,+ accent: palette.accent,+ warning: palette.warning,+ selectedBackground: palette.userBackground,+ }+}++export function runtimeControlsTheme(palette: Palette) {+ return {+ ...commandMenuTheme(palette),+ accent: palette.accent,+ faint: palette.faint,+ }+}++export function contextPanelTheme(palette: Palette): ContextPanelTheme {+ return {+ text: palette.text,+ border: palette.border,+ accent: palette.accent,+ }+}++export function usagePanelTheme(palette: Palette): UsagePanelTheme {+ return { ...palette, cached: palette.cool }+}++export function diffViewerTheme(palette: Palette, backgroundKnown: boolean): DiffViewerTheme {+ const light = palette === LIGHT+ return {+ text: palette.text,+ muted: palette.muted,+ border: palette.border,+ accent: palette.accent,+ success: palette.success,+ error: palette.error,+ addedBackground: backgroundKnown ? light ? "#E7F6EC" : "#142D22" : null,+ removedBackground: backgroundKnown ? light ? "#FCE8EA" : "#352024" : null,+ syntax: syntaxStyle(palette),+ }+}++export function queuePreviewTheme(palette: Palette): QueuePreviewTheme {+ return {+ accent: palette.accent,+ muted: palette.muted,+ faint: palette.faint,+ }+}++export function recoveryNoticeTheme(palette: Palette): RecoveryNoticeTheme {+ return {+ text: palette.text,+ muted: palette.muted,+ border: palette.border,+ accent: palette.accent,+ warning: palette.warning,+ error: palette.error,+ }+}++export function footerHintTheme(palette: Palette): FooterHintTheme {+ return {+ accent: palette.accent,+ danger: palette.error,+ muted: palette.muted,+ separator: palette.faint,+ }+}++export function shimmerStatus(+ label: string,+ suffix: string,+ frame: number,+ palette: Palette,+): StyledText {+ const chars = Array.from(label)+ // Sweep immediately, then leave a quiet pause before repeating. The text+ // keeps a constant width throughout, so the footer never jitters.+ const position = frame % (chars.length + SHIMMER_PAUSE)+ if (palette === TERMINAL) {+ // Terminal-default colors cannot be interpolated without guessing the+ // terminal theme, so move a bold band while preserving native color intent.+ const foreground = parseColor(palette.text)+ const chunks: TextChunk[] = chars.map((text, index) => ({+ __isChunk: true,+ text,+ fg: foreground,+ attributes: Math.abs(index - position) <= TERMINAL_SHIMMER_BAND+ ? TextAttributes.BOLD+ : 0,+ }))+ chunks.push({ __isChunk: true, text: suffix, fg: foreground })+ return new StyledText(chunks)+ }+ const base = parseColor(palette.muted).toInts()+ const highlight = parseColor(palette.accent).toInts()+ const chunks: TextChunk[] = chars.map((text, index) => {+ const distance = Math.abs(index - position)+ const intensity = distance > SHIMMER_BAND+ ? 0+ : (1 + Math.cos(Math.PI * distance / SHIMMER_BAND)) / 2+ return {+ __isChunk: true,+ text,+ fg: RGBA.fromInts(+ Math.round(base[0] + (highlight[0] - base[0]) * intensity),+ Math.round(base[1] + (highlight[1] - base[1]) * intensity),+ Math.round(base[2] + (highlight[2] - base[2]) * intensity),+ ),+ }+ })+ chunks.push({ __isChunk: true, text: suffix, fg: parseColor(palette.muted) })+ return new StyledText(chunks)+}diff --git a/tui/src/app/transcript.test.ts b/tui/src/app/transcript.test.tsnew file mode 100644index 000000000..da9689b7a--- /dev/null+++ b/tui/src/app/transcript.test.ts@@ -0,0 +1,450 @@+import { afterEach, describe, expect, test } from "bun:test"+import { BoxRenderable, CliRenderEvents, TextareaRenderable, TextRenderable } from "@opentui/core"+import { MockTreeSitterClient, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"+import { NanobotTui } from "./app"+import { options, client, mount, waitUntil, occurrences } from "./test-support"++describe("NanobotTui transcript", () => {+ let setup: TestRendererSetup | undefined++ afterEach(() => {+ if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()+ setup = undefined+ })++ const createRenderer = (rendererOptions: Parameters<typeof createTestRenderer>[0]) => (+ createTestRenderer(rendererOptions)+ )+ test("loads earlier transcript pages in place when PageUp reaches the top", async () => {+ setup = await createRenderer({ width: 80, height: 22, screenMode: "alternate-screen" })+ const original = globalThis.fetch+ const requests: string[] = []+ globalThis.fetch = ((input: string | URL | Request) => {+ const url = String(input)+ requests.push(url)+ const older = url.includes("before=older-page")+ return Promise.resolve(new Response(JSON.stringify({+ schemaVersion: 3, projection: "events",+ events: older+ ? [+ { event: "user_message", chat_id: "chat", starts_turn: true, text: "oldest question" },+ { event: "stream_end", chat_id: "chat", text: "oldest answer" },+ ]+ : [+ { event: "user_message", chat_id: "chat", starts_turn: true, text: "recent question" },+ { event: "stream_end", chat_id: "chat", text: "recent answer" },+ ],+ page: older+ ? { has_more_before: false, before_cursor: null }+ : { has_more_before: true, before_cursor: "older-page" },+ })))+ }) as typeof fetch+ const app = NanobotTui.mount(+ setup.renderer,+ { ...options, apiUrl: "http://nanobot.test", apiToken: "secret", chatId: "chat" },+ client(),+ new MockTreeSitterClient({ autoResolveTimeout: 0 }),+ )++ try {+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ setup.mockInput.pressKey("\u001B[5~")+ await waitUntil(() => requests.length === 2)+ await waitUntil(() => !(app as unknown as { historyLoadingOlder: boolean }).historyLoadingOlder)+ await setup.flush()+ const frame = setup.captureCharFrame()++ expect(frame.indexOf("oldest question")).toBeLessThan(frame.indexOf("recent question"))+ expect(frame.indexOf("oldest answer")).toBeLessThan(frame.indexOf("recent answer"))+ expect((app as unknown as { historyHasMore: boolean }).historyHasMore).toBe(false)++ const composer = (app as unknown as { composer: TextareaRenderable }).composer+ setup.mockInput.pressArrow("up")+ expect(composer.plainText).toBe("recent question")+ setup.mockInput.pressArrow("up")+ expect(composer.plainText).toBe("oldest question")+ } finally {+ globalThis.fetch = original+ }+ })++ test("replaces streamed drafts with canonical stream-end text", async () => {+ setup = await createRenderer({ width: 80, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({ event: "delta", chat_id: "chat", text: "draft signed://expired" })+ app.accept({+ event: "stream_end",+ chat_id: "chat",+ text: "canonical https://nanobot.test/signed/current",+ resuming: true,+ merge_next: true,+ })+ app.accept({ event: "delta", chat_id: "chat", text: " tail" })+ app.accept({+ event: "stream_end",+ chat_id: "chat",+ text: "final https://nanobot.test/signed/current tail",+ })+ app.accept({ event: "turn_end", chat_id: "chat" })+ await setup.flush()+ const frame = setup.captureCharFrame()++ expect(frame).toContain("final https://nanobot.test/signed/current tail")+ expect(frame).not.toContain("canonical https://nanobot.test/signed/current")+ expect(frame).not.toContain("draft signed://expired")+ })++ test("paints the first token immediately and coalesces the rest per frame", async () => {+ setup = await createRenderer({ width: 80, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({ event: "delta", chat_id: "chat", text: "first" })+ const transcript = (app as unknown as {+ transcript: {+ live: { markdown: { content: string; streaming: boolean } } | null+ }+ }).transcript+ const markdown = transcript.live?.markdown+ expect(markdown?.content).toBe("first")++ for (let index = 0; index < 1_000; index += 1) {+ app.accept({ event: "delta", chat_id: "chat", text: " token" })+ }+ expect(markdown?.content).toBe("first")++ app.accept({ event: "stream_end", chat_id: "chat" })+ expect(markdown?.content).toBe(`first${" token".repeat(1_000)}`)+ expect(markdown?.streaming).toBe(false)+ })++ test("copies full-screen selections through OSC 52", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup)+ let copied = ""+ setup.renderer.copyToClipboardOSC52 = (text: string) => {+ copied = text+ return true+ }++ await setup.renderOnce()+ app.accept({ event: "delta", chat_id: "chat", text: "selected answer" })+ app.accept({ event: "stream_end", chat_id: "chat" })+ await setup.flush()+ const rows = setup.captureCharFrame().split("\n")+ const y = rows.findIndex((row) => row.includes("selected answer"))+ const x = rows[y]?.indexOf("selected answer") ?? -1+ expect(x).toBeGreaterThanOrEqual(0)+ expect(y).toBeGreaterThanOrEqual(0)++ await setup.mockMouse.drag(x, y, x + "selected answer".length, y)+ expect(setup.renderer.getSelection()?.getSelectedText()).toBe("selected answer")+ setup.mockInput.pressCtrlC()+ await Bun.sleep(10)+ await setup.flush()++ expect(copied).toBe("selected answer")+ expect(setup.renderer.getSelection()).toBeNull()+ })++ test("clears transcript selection when clicking non-content chrome", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup)+ const status = (app as unknown as { status: TextRenderable }).status+ app.accept({ event: "delta", chat_id: "chat", text: "selectable answer" })+ app.accept({ event: "stream_end", chat_id: "chat" })+ await setup.flush()++ const rows = setup.captureCharFrame().split("\n")+ const y = rows.findIndex((row) => row.includes("selectable answer"))+ const x = rows[y]?.indexOf("selectable answer") ?? -1+ await setup.mockMouse.drag(x, y, x + "selectable answer".length, y)+ expect(setup.renderer.getSelection()?.getSelectedText()).toBe("selectable answer")++ await setup.mockMouse.click(status.x, status.y)+ expect(setup.renderer.getSelection()).toBeNull()+ })++ test("keeps text input focus when the focusable transcript is clicked", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup)+ const ui = app as unknown as {+ composer: TextareaRenderable+ transcript: {+ root: { x: number; y: number; focused: boolean }+ }+ }+ app.accept({ event: "delta", chat_id: "chat", text: "clickable answer" })+ app.accept({ event: "stream_end", chat_id: "chat" })+ await setup.flush()++ await setup.mockMouse.click(ui.transcript.root.x + 1, ui.transcript.root.y + 1)++ expect(ui.composer.focused).toBe(true)+ expect(ui.transcript.root.focused).toBe(false)+ })++ test("animates one stable status line while the agent works", async () => {+ setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })+ const app = mount(setup)+ setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")+ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({ event: "reasoning_delta", chat_id: "chat", text: "hidden reasoning" })+ await Bun.sleep(130)+ await setup.renderOnce()+ let frame = setup.captureCharFrame()++ expect(frame).toMatch(/Thinking\s+0s/u)+ expect(frame).not.toMatch(/[◐◓◑◒⠋⠙⠹⠸]/u)+ expect(frame).not.toContain("hidden reasoning")+ const ui = app as unknown as {+ status: {+ content: { chunks: Array<{ fg?: { toInts(): number[] } }> }+ plainText: string+ }+ composer: TextareaRenderable+ composerFrame: BoxRenderable+ }+ const status = ui.status+ expect(status.plainText).toMatch(/^Thinking\s+0s/u)+ expect(ui.composer.placeholder).toBe("Enter send now · Tab send next")+ expect(ui.composerFrame.height).toBe(3)+ const shimmerColors = new Set(+ status.content.chunks+ .slice(0, "Thinking".length)+ .map((chunk) => chunk.fg?.toInts().join(",")),+ )+ expect(shimmerColors.size).toBeGreaterThan(1)+ expect([...shimmerColors].some((value) => value?.startsWith("239,142,48"))).toBe(true)++ app.accept({+ event: "message",+ chat_id: "chat",+ text: "running shell",+ kind: "tool_hint",+ tool_events: [{ phase: "start", name: "exec", arguments: { cmd: "pwd" } }],+ })+ await Bun.sleep(130)+ await setup.renderOnce()+ frame = setup.captureCharFrame()++ expect(frame).toMatch(/Working\s+0s/u)+ expect(frame).not.toMatch(/[◐◓◑◒⠋⠙⠹⠸]/u)+ expect(frame).toContain("› Running pwd")+ expect(occurrences(frame, "pwd")).toBe(1)+ expect(status.plainText).not.toContain("pwd")+ app.accept({ event: "turn_end", chat_id: "chat" })+ await setup.flush()+ expect(ui.composer.placeholder).toBe("Ask nanobot anything")+ })++ test("updates retry state in place and ends failed turns explicitly", async () => {+ setup = await createRenderer({ width: 96, height: 24, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({ event: "attached", chat_id: "chat" })+ app.accept({+ event: "goal_status",+ chat_id: "chat",+ status: "running",+ turn_id: "turn-1",+ })+ const ui = app as unknown as { status: { plainText: string } }++ app.accept({+ event: "retry_status",+ chat_id: "chat",+ turn_id: "turn-1",+ state: "waiting",+ attempt: 1,+ max_attempts: 4,+ error_kind: "connection",+ retry_after_s: 5,+ })+ expect(ui.status.plainText).toMatch(+ /^Could not connect to the model provider · retrying in [45]s · attempt 1\/4/u,+ )++ app.accept({+ event: "retry_status",+ chat_id: "chat",+ turn_id: "turn-1",+ state: "waiting",+ attempt: 2,+ max_attempts: 4,+ error_kind: "connection",+ retry_after_s: 3,+ })+ expect(ui.status.plainText).toContain("attempt 2/4")++ app.accept({+ event: "retry_status",+ chat_id: "chat",+ turn_id: "turn-1",+ state: "cleared",+ attempt: 2,+ max_attempts: 4,+ error_kind: "connection",+ })+ expect(ui.status.plainText).not.toContain("retrying")++ app.accept({+ event: "turn_end",+ chat_id: "chat",+ turn_id: "turn-1",+ outcome: "failed",+ failure_kind: "model",+ failure_error_kind: "connection",+ failure_attempts: 4,+ failure_message: "Unlocalized server failure",+ })+ await setup.renderOnce()+ const frame = setup.captureCharFrame()+ const terminalFailure = "Could not connect to the model provider. The request still failed "+ + "on attempt 4, so retries stopped. Check the provider configuration or service status, "+ + "then try again."+ expect(frame).toContain("Could not connect to the model provider.")+ expect(frame.replace(/\s+/gu, " ")).toContain(terminalFailure)+ expect(frame).not.toContain("Unlocalized server failure")+ expect(frame).not.toContain("Last turn failed")+ expect(ui.status.plainText).toBe("Ready")+ })++ test("folds long tool traces without discarding their details", async () => {+ setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({+ event: "message",+ chat_id: "chat",+ text: "tool progress",+ kind: "tool_hint",+ tool_events: Array.from({ length: 10 }, (_, index) => ({+ phase: "end",+ call_id: `call-${index}`,+ name: `tool_${index}`,+ })),+ })+ await setup.renderOnce()+ let frame = setup.captureCharFrame()++ expect(frame).toContain("7 earlier steps · Ctrl+O expand")+ expect(frame).not.toContain("tool_0")+ expect(frame).toContain("tool_7")+ expect(frame).toContain("tool_9")++ setup.mockInput.pressKey("O", { ctrl: true })+ await setup.renderOnce()+ frame = setup.captureCharFrame()++ expect(frame).not.toContain("earlier steps")+ expect(frame).toContain("tool_0")+ expect(frame).toContain("tool_9")++ app.accept({ event: "turn_end", chat_id: "chat" })+ app.accept({+ event: "message",+ chat_id: "chat",+ text: "second tool group",+ kind: "tool_hint",+ tool_events: Array.from({ length: 8 }, (_, index) => ({+ phase: "end",+ call_id: `later-${index}`,+ name: `later_${index}`,+ })),+ })+ setup.mockInput.pressKey("O", { ctrl: true })+ await setup.renderOnce()+ const activities = [...(app as unknown as {+ transcript: { activities: Set<{ expanded: boolean }> }+ }).transcript.activities]++ expect(activities.map((activity) => activity.expanded)).toEqual([true, true])+ setup.mockInput.pressKey("O", { ctrl: true })+ await setup.renderOnce()+ expect(activities.map((activity) => activity.expanded)).toEqual([true, false])+ app.accept({ event: "turn_end", chat_id: "chat" })+ })++ test("groups consecutive file activity only in the collapsed preview", async () => {+ setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({+ event: "message",+ chat_id: "chat",+ text: "file progress",+ kind: "tool_hint",+ tool_events: Array.from({ length: 6 }, (_, index) => ({+ phase: "end" as const,+ call_id: `read-${index}`,+ name: "read_file",+ arguments: { path: `/tmp/nanobot-workspace/src/file-${index}.ts` },+ })),+ })+ await setup.renderOnce()+ let frame = setup.captureCharFrame()++ expect(frame).toContain("6 steps · Ctrl+O expand")+ expect(frame).toContain("✓ Read 6 files")+ expect(frame).not.toContain("src/file-0.ts")++ setup.mockInput.pressKey("O", { ctrl: true })+ await setup.renderOnce()+ frame = setup.captureCharFrame()++ expect(frame).not.toContain("Read 6 files")+ expect(frame).toContain("src/file-0.ts")+ expect(frame).toContain("src/file-5.ts")+ })++ test("supports keyboard transcript navigation without rebuilding the layout", async () => {+ setup = await createRenderer({ width: 64, height: 16, screenMode: "alternate-screen" })+ const app = mount(setup)+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ for (let index = 0; index < 24; index += 1) {+ app.accept({ event: "delta", chat_id: "chat", text: `answer ${index}` })+ app.accept({ event: "stream_end", chat_id: "chat" })+ }+ await setup.flush()+ const internals = app as unknown as {+ status: { plainText: string }+ transcript: {+ root: {+ scrollTop: number+ scrollHeight: number+ height: number+ verticalScrollBar: { visible: boolean }+ }+ }+ }+ const scroll = internals.transcript.root++ setup.mockInput.pressKey("HOME", { ctrl: true })+ await setup.renderOnce()+ expect(scroll.scrollTop).toBe(0)++ app.accept({ event: "delta", chat_id: "chat", text: "new answer while reading above" })+ app.accept({ event: "stream_end", chat_id: "chat" })+ await setup.renderOnce()+ expect(scroll.scrollTop).toBe(0)+ expect(scroll.verticalScrollBar.visible).toBe(false)+ expect(internals.status.plainText).toContain("Ctrl+End latest")++ setup.mockInput.pressKey("\u001B[6~")+ await setup.renderOnce()+ expect(scroll.scrollTop).toBeGreaterThan(0)++ setup.mockInput.pressKey("END", { ctrl: true })+ await setup.renderOnce()+ expect(scroll.scrollTop).toBeGreaterThanOrEqual(scroll.scrollHeight - scroll.height)+ expect(scroll.verticalScrollBar.visible).toBe(false)+ expect(internals.status.plainText).not.toContain("Ctrl+End latest")++ setup.mockInput.pressKey("HOME", { ctrl: true })+ await waitUntil(() => internals.status.plainText.includes("Ctrl+End latest"))+ expect(scroll.verticalScrollBar.visible).toBe(false)+ app.accept({ event: "attached", chat_id: "chat" })+ await waitUntil(() => (app as unknown as { ready: boolean }).ready)+ await setup.renderOnce()+ expect(scroll.verticalScrollBar.visible).toBe(false)+ expect(internals.status.plainText).not.toContain("Ctrl+End latest")+ })+})diff --git a/tui/src/app/types.ts b/tui/src/app/types.tsnew file mode 100644index 000000000..11cd9f57c--- /dev/null+++ b/tui/src/app/types.ts@@ -0,0 +1,44 @@+import type { ThemeMode } from "@opentui/core"++import type {+ GatewayConnection,+ MessageOptions,+ RecoveryState,+ WorkspaceScopePayload,+} from "../client"++export interface AppOptions {+ resolveConnection?: () => Promise<GatewayConnection>+ desktopGatewayId?: string+ wsUrl?: string+ bootstrapUrl?: string+ bootstrapSecret?: string+ healthUrl?: string+ apiUrl: string+ apiToken: string+ chatId?: string+ model: string+ modelPreset: string+ workspace: string+ version: string+ access: string+ theme: "auto" | ThemeMode+ onDetach?: (chatId?: string) => void+ onExit?: (chatId: string) => void+}++export interface ChatClient {+ readonly activeChatId: string+ connect(): void+ close(): void+ send(content: string, options?: MessageOptions): string+ attach(chatId: string): void+ newChat(scope?: WorkspaceScopePayload): void+ forkChat?(sourceChatId: string, beforeUserIndex: number, title?: string): void+ setWorkspaceScope(scope: WorkspaceScopePayload): void+ updateRecovery(+ action: "continue" | "dismiss",+ chatId: string,+ recoveryId: string,+ ): Promise<RecoveryState>+}diff --git a/tui/src/usage-app.test.ts b/tui/src/app/usage-app.test.tssimilarity index 99%rename from tui/src/usage-app.test.tsrename to tui/src/app/usage-app.test.tsindex 5ccbd5b4f..755d86791 100644--- a/tui/src/usage-app.test.ts+++ b/tui/src/app/usage-app.test.ts@@ -3,8 +3,8 @@ import { type TextareaRenderable } from "@opentui/core"import { MockTreeSitterClient, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"import { NanobotTui } from "./app"-import type { UsagePanel } from "./usage-panel"-import type { RecoveryState } from "./protocol"+import type { UsagePanel } from "../views/usage-panel"+import type { RecoveryState } from "../client"const originalFetch = globalThis.fetchconst page = (input = 9000) => ({diff --git a/tui/src/client/api.ts b/tui/src/client/api.tsnew file mode 100644index 000000000..31241d4d0--- /dev/null+++ b/tui/src/client/api.ts@@ -0,0 +1,529 @@+import { isRecoveryState } from "../../../packages/client-events/notifications"++import type {+ ApiReauthenticator,+ GatewayApiConnection,+ HistoryMessage,+ HistorySnapshot,+ InboundEvent,+ MentionCandidate,+ RuntimeControls,+ SessionContextSnapshot,+ SessionSummary,+ SessionUsageSnapshot,+ SkillCandidate,+ SlashCommand,+ SlashCommandLifecycle,+ TokenUsage,+} from "./types"+import {+ decodeInboundEvent,+ isRecord,+ isTokenUsage,+ isWorkspaceScope,+ optional,+} from "./validation"++const SKILL_REFERENCE_NAME = /^[A-Za-z0-9_-]+$/u+const SLASH_COMMAND_LIFECYCLES = new Set([+ "side_channel",+ "finalize_active_turn",+ "stop_active_turn",+ "agent_turn",+ "agent_turn_with_args",+])++async function fetchApi(+ apiUrl: string,+ apiToken: string,+ path: string,+ reauthenticate?: ApiReauthenticator,+ signal?: AbortSignal,+): Promise<Response> {+ const request = (connection: GatewayApiConnection) => {+ signal?.throwIfAborted()+ return fetch(`${connection.apiUrl}${path}`, {+ headers: { Authorization: `Bearer ${connection.apiToken}` },+ ...(signal ? { signal } : {}),+ })+ }+ const response = await request({ apiUrl, apiToken })+ signal?.throwIfAborted()+ if (response.status !== 401 || !reauthenticate) return response+ return request(await reauthenticate(apiToken))+}++type HistoryEvent = Extract<InboundEvent, { event:+ | "user_message" | "message" | "file_edit" | "delta" | "stream_end"+ | "reasoning_delta" | "reasoning_end" | "context_compaction" | "turn_end"+}> & { round_usages?: TokenUsage[] }++interface ThreadPage {+ events: HistoryEvent[]+ page?: { has_more_before?: boolean; before_cursor?: string; user_message_offset?: number }+}++function parseHistoryEvents(values: unknown[]): HistoryEvent[] {+ const events: HistoryEvent[] = []+ const seen = new Set<string>()+ for (const value of values) {+ const event = decodeInboundEvent(value)+ if (!event || !isRecord(value) || !optional(value.turn_id, "string")) {+ throw new Error("Invalid history event")+ }+ if (typeof value.projection_id === "string") {+ if (seen.has(value.projection_id)) continue+ seen.add(value.projection_id)+ }+ switch (event.event) {+ case "user_message":+ case "message":+ case "file_edit":+ case "delta":+ case "stream_end":+ case "reasoning_delta":+ case "reasoning_end":+ case "context_compaction":+ events.push(event)+ break+ case "turn_end":+ events.push({+ ...event,+ round_usages: Array.isArray(value.round_usages) ? value.round_usages.filter(isTokenUsage) : [],+ })+ break+ default:+ throw new Error(`Unsupported history event: ${event.event}`)+ }+ }+ return events+}++async function fetchThreadPage(+ apiUrl: string,+ apiToken: string,+ chatId: string,+ beforeCursor?: string | null,+ reauthenticate?: ApiReauthenticator,+ signal?: AbortSignal,+): Promise<ThreadPage> {+ if (!apiUrl || !apiToken) return { events: [] }+ const key = encodeURIComponent(`websocket:${chatId}`)+ const params = new URLSearchParams({ limit: "120", direction: "latest" })+ if (beforeCursor) params.set("before", beforeCursor)+ const response = await fetchApi(+ apiUrl,+ apiToken,+ `/api/sessions/${key}/webui-thread?${params}`,+ reauthenticate,+ signal,+ )+ if (response.status === 404) return { events: [] }+ if (!response.ok) throw new Error(`history request failed: HTTP ${response.status}`)+ const payload: unknown = await response.json()+ if (!isRecord(payload) || typeof payload.schemaVersion !== "number") {+ throw new Error("Invalid history response")+ }+ const page = isRecord(payload.page) ? payload.page : undefined+ const pagination = {+ has_more_before: page?.has_more_before === true,+ before_cursor: typeof page?.before_cursor === "string" ? page.before_cursor : undefined,+ user_message_offset: typeof page?.user_message_offset === "number" ? page.user_message_offset : undefined,+ }+ if (payload.projection === "events" && Array.isArray(payload.events)) {+ return { events: parseHistoryEvents(payload.events), page: pagination }+ }+ throw new Error("Unsupported history response format")+}++/** Same recent model-call samples and context boundary as the WebUI usage popover. */+export async function fetchSessionUsage(+ apiUrl: string,+ apiToken: string,+ chatId: string,+ reauthenticate?: ApiReauthenticator,+ signal?: AbortSignal,+): Promise<SessionUsageSnapshot> {+ const payload = await fetchThreadPage(apiUrl, apiToken, chatId, undefined, reauthenticate, signal)+ signal?.throwIfAborted()+ const snapshot: SessionUsageSnapshot = { context: null, rounds: [] }+ const seenTurns = new Set<unknown>()+ let contextResolved = false+ for (const event of [...payload.events].reverse()) {+ if (event.event === "context_compaction" && event.phase === "succeeded") contextResolved = true+ if (event.event !== "turn_end") continue+ const usage = event.usage+ if (!contextResolved && typeof usage?.context_tokens === "number"+ && Number.isFinite(usage.context_tokens) && usage.context_tokens >= 0) {+ const window = event.context_window_tokens+ snapshot.context = {+ tokens: usage.context_tokens,+ ...(typeof window === "number" && Number.isFinite(window) && window > 0+ ? { windowTokens: window } : {}),+ }+ contextResolved = true+ }+ const turnKey = event.turn_id || event+ if (seenTurns.has(turnKey)) continue+ seenTurns.add(turnKey)+ for (const round of [...(event.round_usages ?? [])].reverse()) {+ if (snapshot.rounds.length >= 8) break+ if (typeof round.prompt_tokens === "number"+ && Number.isFinite(round.prompt_tokens) && round.prompt_tokens > 0) {+ snapshot.rounds.push(round)+ }+ }+ }+ snapshot.rounds.reverse()+ return snapshot+}++export async function fetchHistory(+ apiUrl: string,+ apiToken: string,+ chatId: string,+ beforeCursor?: string | null,+ reauthenticate?: ApiReauthenticator,+): Promise<HistorySnapshot> {+ const payload = await fetchThreadPage(apiUrl, apiToken, chatId, beforeCursor, reauthenticate)+ let userIndex = typeof payload.page?.user_message_offset === "number"+ ? Math.max(0, payload.page.user_message_offset)+ : 0+ const messages: HistoryMessage[] = []+ let stream: { row: HistoryMessage; turnId?: string } | null = null+ let lastAnswer: { row: HistoryMessage; turnId?: string } | null = null+ for (const event of payload.events) {+ switch (event.event) {+ case "user_message": {+ if (event.starts_turn) stream = null+ const media = event.media_urls ?? []+ if (!event.text.trim() && !media.length) break+ userIndex += 1+ messages.push({+ role: "user", content: event.text,+ ...(media.length ? { media } : {}),+ ...(event.turn_id ? { turnId: event.turn_id } : {}),+ })+ lastAnswer = null+ break+ }+ case "delta":+ case "stream_end":+ if (!stream || stream.turnId !== event.turn_id) {+ const row: HistoryMessage = { role: "assistant", content: "", forkIndex: userIndex }+ messages.push(row)+ stream = { row, turnId: event.turn_id }+ }+ if (event.event === "delta") stream.row.content += event.text+ else if (event.text !== undefined) stream.row.content = event.text+ lastAnswer = stream+ if (event.event === "stream_end" && !(event.resuming && event.merge_next)) stream = null+ break+ case "message":+ if (event.kind === "reasoning") break+ if (event.kind === "tool_hint" || event.kind === "progress") {+ messages.push({+ role: "activity", content: event.text,+ ...(event.tool_events?.length ? { toolEvents: event.tool_events } : {}),+ })+ } else {+ // A final message can repeat the answer already saved by stream_end.+ if (stream && stream.turnId === event.turn_id) stream.row.content = event.text+ else if (!lastAnswer || lastAnswer.turnId !== event.turn_id || lastAnswer.row.content !== event.text) {+ const row: HistoryMessage = { role: "assistant", content: event.text, forkIndex: userIndex }+ messages.push(row)+ lastAnswer = { row, turnId: event.turn_id }+ }+ stream = null+ }+ break+ case "file_edit":+ if (event.edits.length) messages.push({ role: "activity", content: "", fileEdits: event.edits })+ break+ case "context_compaction":+ stream = null+ messages.push({+ role: "activity", content: "",+ compaction: { id: event.compaction_id, phase: event.phase },+ })+ break+ case "turn_end":+ stream = null+ lastAnswer = null+ break+ case "reasoning_delta":+ case "reasoning_end":+ break+ }+ }+ return {+ messages: messages.filter((row) => row.role !== "assistant" || row.content.trim()),+ hasMoreBefore: payload.page?.has_more_before === true,+ beforeCursor: typeof payload.page?.before_cursor === "string"+ ? payload.page.before_cursor+ : null,+ userMessageOffset: typeof payload.page?.user_message_offset === "number"+ ? Math.max(0, payload.page.user_message_offset)+ : 0,+ }+}++export async function fetchSessionContext(+ apiUrl: string,+ apiToken: string,+ chatId: string,+ reauthenticate?: ApiReauthenticator,+): Promise<SessionContextSnapshot | null> {+ if (!apiUrl || !apiToken) return null+ const key = encodeURIComponent(`websocket:${chatId}`)+ const response = await fetchApi(+ apiUrl,+ apiToken,+ `/api/sessions/${key}/context`,+ reauthenticate,+ )+ if (response.status === 404) return null+ if (!response.ok) throw new Error(`context request failed: HTTP ${response.status}`)+ const value = await response.json() as Record<string, unknown>+ const number = (key: string) => typeof value[key] === "number" ? value[key] as number : 0+ return {+ totalMessages: number("total_messages"),+ archivedMessages: number("archived_messages"),+ replayMessages: number("replay_messages"),+ estimatedReplayTokens: number("estimated_replay_tokens"),+ estimatedSummaryTokens: number("estimated_summary_tokens"),+ estimatedSessionTokens: number("estimated_session_tokens"),+ archivedSummary: typeof value.archived_summary === "string" ? value.archived_summary : null,+ archivedSummaryAt: typeof value.archived_summary_at === "string"+ ? value.archived_summary_at+ : null,+ lastUsage: isTokenUsage(value.last_usage) ? value.last_usage : null,+ }+}++export async function fetchSlashCommands(+ apiUrl: string,+ apiToken: string,+ reauthenticate?: ApiReauthenticator,+): Promise<SlashCommand[]> {+ if (!apiUrl || !apiToken) return []+ const response = await fetchApi(apiUrl, apiToken, "/api/commands", reauthenticate)+ if (!response.ok) throw new Error(`command request failed: HTTP ${response.status}`)+ const payload = await response.json() as { commands?: unknown[] }+ return (payload.commands || []).flatMap((value) => {+ if (+ !isRecord(value)+ || typeof value.command !== "string"+ || typeof value.lifecycle !== "string"+ || !SLASH_COMMAND_LIFECYCLES.has(value.lifecycle)+ ) return []+ return [{+ command: value.command,+ title: typeof value.title === "string" ? value.title : value.command,+ description: typeof value.description === "string" ? value.description : "",+ argHint: typeof value.arg_hint === "string" ? value.arg_hint : "",+ lifecycle: value.lifecycle as SlashCommandLifecycle,+ acceptsArgs: value.accepts_args === true,+ }]+ })+}++export async function fetchAvailableSkills(+ apiUrl: string,+ apiToken: string,+ reauthenticate?: ApiReauthenticator,+): Promise<SkillCandidate[]> {+ if (!apiUrl || !apiToken) return []+ const response = await fetchApi(apiUrl, apiToken, "/api/webui/skills", reauthenticate)+ if (!response.ok) throw new Error(`skill request failed: HTTP ${response.status}`)+ const payload = await response.json() as { skills?: unknown[] }+ return (payload.skills || []).flatMap((value) => {+ if (+ !isRecord(value)+ || typeof value.name !== "string"+ || !SKILL_REFERENCE_NAME.test(value.name)+ || value.enabled !== true+ || value.available !== true+ ) return []+ return [{+ name: value.name,+ description: typeof value.description === "string" ? value.description : value.name,+ source: typeof value.source === "string" ? value.source : "unknown",+ }]+ })+}++export async function fetchRuntimeControls(+ apiUrl: string,+ apiToken: string,+ reauthenticate?: ApiReauthenticator,+): Promise<RuntimeControls> {+ if (!apiUrl || !apiToken) return { modelPresets: [], canUseFullAccess: false }+ const [settingsResponse, workspacesResponse] = await Promise.all([+ fetchApi(apiUrl, apiToken, "/api/settings", reauthenticate),+ fetchApi(apiUrl, apiToken, "/api/workspaces", reauthenticate).catch(() => null),+ ])+ if (!settingsResponse.ok) {+ throw new Error(`settings request failed: HTTP ${settingsResponse.status}`)+ }+ const settings = await settingsResponse.json() as { model_presets?: unknown[] }+ const workspaces = workspacesResponse?.ok+ ? await workspacesResponse.json() as { controls?: unknown }+ : {}+ const modelPresets = (settings.model_presets || []).flatMap((value) => {+ if (!isRecord(value) || typeof value.name !== "string" || typeof value.model !== "string") {+ return []+ }+ const name = value.name.trim()+ return name ? [{ name, model: value.model.trim() }] : []+ })+ const controls = isRecord(workspaces.controls) ? workspaces.controls : {}+ return {+ modelPresets,+ canUseFullAccess: controls.can_use_full_access === true,+ }+}++export async function fetchSessions(+ apiUrl: string,+ apiToken: string,+ reauthenticate?: ApiReauthenticator,+): Promise<SessionSummary[]> {+ if (!apiUrl || !apiToken) return []+ const [response, sidebarResponse] = await Promise.all([+ fetchApi(apiUrl, apiToken, "/api/sessions", reauthenticate),+ fetchApi(apiUrl, apiToken, "/api/webui/sidebar-state", reauthenticate).catch(() => null),+ ])+ if (!response.ok) throw new Error(`session request failed: HTTP ${response.status}`)+ const payload = await response.json() as { sessions?: unknown[] }+ let sidebar: Record<string, unknown> = {}+ if (sidebarResponse?.ok) {+ try {+ const value: unknown = await sidebarResponse.json()+ if (isRecord(value)) sidebar = value+ } catch {+ // Session navigation remains available against older or damaged sidebar state.+ }+ }+ const pinned = new Set(Array.isArray(sidebar.pinned_keys) ? sidebar.pinned_keys : [])+ const archived = new Set(Array.isArray(sidebar.archived_keys) ? sidebar.archived_keys : [])+ const titles = isRecord(sidebar.title_overrides) ? sidebar.title_overrides : {}+ return (payload.sessions || []).flatMap((value) => {+ if (!isRecord(value) || typeof value.key !== "string" || !value.key.startsWith("websocket:")) {+ return []+ }+ const chatId = value.key.slice("websocket:".length)+ if (!chatId) return []+ const titleOverride = titles[value.key]+ return [{+ chatId,+ title: typeof titleOverride === "string"+ ? titleOverride+ : typeof value.title === "string" ? value.title : "",+ preview: typeof value.preview === "string" ? value.preview : "",+ createdAt: typeof value.created_at === "string" ? value.created_at : null,+ updatedAt: typeof value.updated_at === "string" ? value.updated_at : null,+ runStartedAt: typeof value.run_started_at === "number" ? value.run_started_at : null,+ modelPreset: typeof value.model_preset === "string" && value.model_preset.trim()+ ? value.model_preset.trim()+ : null,+ ...(isRecoveryState(value.recovery_state)+ ? { recoveryState: value.recovery_state }+ : {}),+ ...(isWorkspaceScope(value.workspace_scope) ? { workspaceScope: value.workspace_scope } : {}),+ pinned: pinned.has(value.key),+ archived: archived.has(value.key),+ }]+ })+}++function sessionMentionName(session: SessionSummary): string {+ const label = (session.title || session.preview || "session")+ .normalize("NFKC")+ .replace(/\s+/gu, "-")+ .replace(/[^\p{L}\p{N}_-]+/gu, "")+ .replace(/-+/gu, "-")+ .replace(/^-|-$/gu, "")+ return Array.from(label || "session").slice(0, 40).join("")+}++/** Installed capabilities and saved chats share one mention namespace. */+export async function fetchMentionCandidates(+ apiUrl: string,+ apiToken: string,+ reauthenticate?: ApiReauthenticator,+): Promise<MentionCandidate[]> {+ if (!apiUrl || !apiToken) return []+ const [sessions, appsResponse, mcpResponse] = await Promise.all([+ fetchSessions(apiUrl, apiToken, reauthenticate),+ fetchApi(+ apiUrl,+ apiToken,+ "/api/settings/cli-apps?installed_only=1",+ reauthenticate,+ ).catch(() => null),+ fetchApi(apiUrl, apiToken, "/api/settings/mcp-presets", reauthenticate).catch(() => null),+ ])+ const used = new Set<string>()+ const uniqueName = (raw: string) => {+ const base = raw || "session"+ let name = base+ let suffix = 2+ while (used.has(name.toLocaleLowerCase())) name = `${base}-${suffix++}`+ used.add(name.toLocaleLowerCase())+ return name+ }+ const candidates: MentionCandidate[] = []+ if (appsResponse?.ok) {+ const payload = await appsResponse.json() as { apps?: unknown[] }+ for (const value of payload.apps || []) {+ if (!isRecord(value) || value.installed !== true || typeof value.name !== "string") continue+ const name = uniqueName(value.name)+ candidates.push({+ kind: "cli",+ name,+ ...(name === value.name ? {} : { targetName: value.name }),+ displayName: typeof value.display_name === "string" ? value.display_name : name,+ description: typeof value.description === "string" ? value.description : "CLI app",+ })+ }+ }+ if (mcpResponse?.ok) {+ const payload = await mcpResponse.json() as { presets?: unknown[] }+ for (const value of payload.presets || []) {+ if (+ !isRecord(value)+ || value.installed !== true+ || value.configured !== true+ || typeof value.name !== "string"+ ) continue+ const name = uniqueName(value.name)+ candidates.push({+ kind: "mcp",+ name,+ ...(name === value.name ? {} : { targetName: value.name }),+ displayName: typeof value.display_name === "string" ? value.display_name : name,+ description: typeof value.description === "string" ? value.description : "MCP server",+ })+ }+ }+ for (const session of sessions) {+ const name = uniqueName(sessionMentionName(session))+ candidates.push({+ kind: "session",+ name,+ displayName: sessionLabelForMention(session),+ description: session.preview || "Saved session",+ session: {+ name,+ session_key: `websocket:${session.chatId}`,+ title: session.title || undefined,+ },+ })+ }+ return candidates+}++function sessionLabelForMention(session: SessionSummary): string {+ return (session.title || session.preview || "Untitled chat").replace(/\s+/gu, " ").trim()+}diff --git a/tui/src/protocol.test.ts b/tui/src/client/client.test.tssimilarity index 99%rename from tui/src/protocol.test.tsrename to tui/src/client/client.test.tsindex 1bb5da5b2..222d0d1d4 100644--- a/tui/src/protocol.test.ts+++ b/tui/src/client/client.test.ts@@ -17,7 +17,7 @@ import {type ConnectionStatus,type ConnectionStatusInfo,type InboundEvent,-} from "./protocol"+} from "."class FakeSocket {static readonly OPEN = 1diff --git a/tui/src/client/connection.ts b/tui/src/client/connection.tsnew file mode 100644index 000000000..96a96f110--- /dev/null+++ b/tui/src/client/connection.ts@@ -0,0 +1,144 @@+import type { GatewayConnection, GatewayHealthStatus } from "./types"+import { isRecord } from "./validation"++export class GatewayConnectionError extends Error {+ constructor(message: string, readonly retryable: boolean) {+ super(message)+ this.name = "GatewayConnectionError"+ }+}++/** Resolve fresh short-lived credentials once the local gateway is reachable. */+export async function fetchGatewayConnection(+ bootstrapUrl: string,+ bootstrapSecret: string,+ apiUrl: string,+ clientId: string,+): Promise<GatewayConnection> {+ const response = await fetch(bootstrapUrl, {+ headers: bootstrapSecret ? { "X-Nanobot-Auth": bootstrapSecret } : {},+ })+ if (!response.ok) {+ const retryable = response.status === 408 || response.status === 429 || response.status >= 500+ throw new GatewayConnectionError(+ `gateway bootstrap failed: HTTP ${response.status}`,+ retryable,+ )+ }+ let payload: unknown+ try {+ payload = await response.json()+ } catch {+ throw new GatewayConnectionError("gateway bootstrap response is invalid", false)+ }+ if (!isRecord(payload)) {+ throw new GatewayConnectionError("gateway bootstrap response is invalid", false)+ }+ if (typeof payload.ws_url !== "string" || !payload.ws_url.trim()) {+ throw new GatewayConnectionError("gateway bootstrap response is missing ws_url", false)+ }+ let wsUrl: URL+ try {+ wsUrl = new URL(payload.ws_url)+ } catch {+ throw new GatewayConnectionError("gateway bootstrap response has an invalid ws_url", false)+ }+ if (wsUrl.protocol !== "ws:" && wsUrl.protocol !== "wss:") {+ throw new GatewayConnectionError("gateway bootstrap response has an invalid ws_url", false)+ }+ if (typeof payload.token === "string" && payload.token) {+ wsUrl.searchParams.append("token", payload.token)+ }+ wsUrl.searchParams.append("client_id", clientId)+ return {+ wsUrl: wsUrl.toString(),+ apiUrl,+ apiToken: typeof payload.api_token === "string" ? payload.api_token : "",+ }+}++/** Read gateway readiness without sending bootstrap or API credentials. */+export async function fetchGatewayHealth(+ healthUrl: string,+ timeoutMs = 400,+): Promise<GatewayHealthStatus> {+ const controller = new AbortController()+ const timer = setTimeout(() => controller.abort(), timeoutMs)+ try {+ const response = await fetch(healthUrl, { signal: controller.signal })+ if (response.status !== 200 && response.status !== 503) return "unreachable"+ const payload: unknown = await response.json()+ if (!isRecord(payload)) return "unreachable"+ if (+ response.status === 503+ && payload.status === "degraded"+ && payload.ready === false+ && payload.process === "alive"+ ) return "degraded"+ if (response.status === 200 && payload.status === "ok" && payload.ready !== false) {+ return "ready"+ }+ return "unreachable"+ } catch {+ return "unreachable"+ } finally {+ clearTimeout(timer)+ }+}++/** Return only the authority users can act on, never credentials or an authenticated path. */+export function connectionEndpoint(value: string | undefined): string {+ if (!value) return "local gateway"+ try {+ return new URL(value).host || "local gateway"+ } catch {+ return "local gateway"+ }+}++/** Reduce arbitrary fetch/WebSocket errors to a small set of credential-safe reasons. */+export function sanitizeConnectionFailure(error: unknown): string {+ const signals: string[] = []+ const seen = new Set<unknown>()+ const collect = (value: unknown): void => {+ if (value === null || value === undefined || seen.has(value)) return+ if (typeof value === "object") seen.add(value)+ if (typeof value === "string") {+ signals.push(value)+ return+ }+ if (value instanceof Error) {+ signals.push(value.name, value.message)+ collect(value.cause)+ if (value instanceof AggregateError) {+ for (const nested of value.errors) collect(nested)+ }+ return+ }+ if (!isRecord(value)) return+ if (typeof value.code === "string") signals.push(value.code)+ collect(value.cause)+ if (Array.isArray(value.errors)) {+ for (const nested of value.errors) collect(nested)+ }+ }+ collect(error)+ const signal = signals.join(" ")+ if (/ECONNREFUSED|connection refused/iu.test(signal)) return "connection refused"+ if (/ETIMEDOUT|timed? out|timeout/iu.test(signal)) return "connection timed out"+ if (/ENOTFOUND|EAI_AGAIN|name not resolved|host not found/iu.test(signal)) {+ return "host not found"+ }+ if (/certificate|TLS|SSL/iu.test(signal)) return "secure connection failed"+ const bootstrapStatus = signal.match(/gateway bootstrap failed:\s*HTTP\s*(\d{3})/iu)+ if (bootstrapStatus?.[1]) return `gateway bootstrap failed: HTTP ${bootstrapStatus[1]}`+ if (/bootstrap response is missing ws_url/iu.test(signal)) {+ return "gateway bootstrap response is missing ws_url"+ }+ if (/bootstrap response (?:has an invalid ws_url|is invalid)/iu.test(signal)) {+ return "gateway bootstrap response is invalid"+ }+ if (/gateway is still starting/iu.test(signal)) return "gateway is still starting"+ if (/fetch failed|failed to fetch|network error/iu.test(signal)) return "network request failed"+ return "connection failed"+}diff --git a/tui/src/history-events.test.ts b/tui/src/client/history.test.tssimilarity index 98%rename from tui/src/history-events.test.tsrename to tui/src/client/history.test.tsindex 219af38f1..dd1c123eb 100644--- a/tui/src/history-events.test.ts+++ b/tui/src/client/history.test.ts@@ -1,5 +1,5 @@import { afterEach, expect, test } from "bun:test"-import { fetchHistory, fetchSessionUsage } from "./protocol"+import { fetchHistory, fetchSessionUsage } from "."const originalFetch = globalThis.fetchafterEach(() => { globalThis.fetch = originalFetch })diff --git a/tui/src/client/index.ts b/tui/src/client/index.tsnew file mode 100644index 000000000..2fd12f3c9--- /dev/null+++ b/tui/src/client/index.ts@@ -0,0 +1,48 @@+export {+ fetchAvailableSkills,+ fetchHistory,+ fetchMentionCandidates,+ fetchRuntimeControls,+ fetchSessionContext,+ fetchSessionUsage,+ fetchSessions,+ fetchSlashCommands,+} from "./api"+export {+ GatewayConnectionError,+ connectionEndpoint,+ fetchGatewayConnection,+ fetchGatewayHealth,+ sanitizeConnectionFailure,+} from "./connection"+export { NanobotClient } from "./nanobot-client"+export type {+ ApiReauthenticator,+ ClientOptions,+ ConnectionStatus,+ ConnectionStatusInfo,+ ContextCompaction,+ FileEditEvent,+ GatewayApiConnection,+ GatewayConnection,+ GatewayHealthStatus,+ HistoryMessage,+ HistorySnapshot,+ InboundEvent,+ MediaAttachment,+ MentionCandidate,+ MessageOptions,+ OutboundMedia,+ RecoveryState,+ RetryStatus,+ RuntimeControls,+ SessionContextSnapshot,+ SessionSummary,+ SessionUsageSnapshot,+ SkillCandidate,+ SlashCommand,+ SlashCommandLifecycle,+ TokenUsage,+ ToolProgressEvent,+ WorkspaceScopePayload,+} from "./types"diff --git a/tui/src/client/nanobot-client.ts b/tui/src/client/nanobot-client.tsnew file mode 100644index 000000000..137cd3285--- /dev/null+++ b/tui/src/client/nanobot-client.ts@@ -0,0 +1,415 @@+import { isRecoveryState } from "../../../packages/client-events/notifications"++import {+ GatewayConnectionError,+ connectionEndpoint,+ sanitizeConnectionFailure,+} from "./connection"+import type {+ ClientOptions,+ ConnectionStatusInfo,+ GatewayHealthStatus,+ MessageOptions,+ OutboundEvent,+ RecoveryState,+ WorkspaceScopePayload,+} from "./types"+import { decodeInboundEvent, decodeWebUIResponse, isRecord } from "./validation"++export class NanobotClient {+ private identityVerified = false+ private handshakeTimer: ReturnType<typeof setTimeout> | null = null+ private socket: WebSocket | null = null+ private chatId = ""+ private workspaceScope?: WorkspaceScopePayload+ private reconnectTimer: ReturnType<typeof setTimeout> | null = null+ private reconnectAttempt = 0+ private closedByClient = false+ private opening = false+ private connectedOnce = false+ private connectionAttempt = 0+ private retryStartedAt = 0+ private nextRetryAt = 0+ private lastFailure = ""+ private healthStatus: GatewayHealthStatus | undefined+ private failureEscalationTimer: ReturnType<typeof setTimeout> | null = null+ private readonly endpoint: string+ private readonly pendingMutations = new Map<string, {+ resolve: (value: unknown) => void+ reject: (error: Error) => void+ timer: ReturnType<typeof setTimeout>+ }>()++ constructor(private readonly options: ClientOptions) {+ this.endpoint = options.targetEndpoint || connectionEndpoint(options.url)+ }++ get activeChatId(): string {+ return this.chatId+ }++ connect(): void {+ this.closedByClient = false+ this.connectionAttempt = 0+ this.reconnectAttempt = 0+ this.retryStartedAt = Date.now()+ this.nextRetryAt = 0+ this.lastFailure = ""+ this.healthStatus = undefined+ void this.open()+ }++ 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()+ let url = this.options.url+ try {+ if (this.options.resolveConnection) {+ const connection = await this.options.resolveConnection()+ if (this.closedByClient) return+ this.options.onConnection?.(connection)+ url = connection.wsUrl+ }+ } catch (error) {+ if (!this.closedByClient) {+ this.lastFailure = sanitizeConnectionFailure(error)+ if (error instanceof GatewayConnectionError && !error.retryable) {+ this.clearFailureEscalation()+ this.options.onStatus("error", this.lastFailure, this.connectionInfo())+ return+ }+ await this.checkHealthAndScheduleReconnect()+ }+ return+ } finally {+ this.opening = false+ }+ if (!url) {+ this.options.onStatus("error", "gateway URL is not configured", this.connectionInfo())+ return+ }+ let socket: WebSocket+ try {+ socket = new WebSocket(url)+ } catch (error) {+ this.lastFailure = sanitizeConnectionFailure(error)+ await this.checkHealthAndScheduleReconnect()+ return+ }+ 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+ this.connectedOnce = true+ this.connectionAttempt = 0+ this.reconnectAttempt = 0+ this.retryStartedAt = 0+ this.nextRetryAt = 0+ this.lastFailure = ""+ this.healthStatus = "ready"+ this.clearFailureEscalation()+ this.options.onStatus("connected", undefined, this.connectionInfo())+ })+ socket.addEventListener("message", (message) => {+ if (this.socket === socket) this.handleMessage(String(message.data))+ })+ socket.addEventListener("error", () => {+ if (this.socket !== socket) return+ if (this.options.reconnect === false) { this.desktopFailure(); return }+ this.lastFailure = "connection failed"+ this.reportRetryState()+ })+ socket.addEventListener("close", () => {+ if (this.socket !== socket) return+ this.socket = null+ this.rejectPendingMutations("gateway connection closed")+ if (this.closedByClient) {+ this.options.onStatus("closed")+ return+ }+ if (this.options.reconnect === false) { this.desktopFailure(); return }+ if (opened) {+ this.connectionAttempt = 0+ this.reconnectAttempt = 0+ this.retryStartedAt = Date.now()+ }+ if (!this.lastFailure) this.lastFailure = "connection closed"+ this.reportRetryState()+ void this.checkHealthAndScheduleReconnect()+ })+ }++ close(): void {+ if (this.handshakeTimer) clearTimeout(this.handshakeTimer)+ this.handshakeTimer = null+ this.closedByClient = true+ if (this.reconnectTimer) clearTimeout(this.reconnectTimer)+ this.reconnectTimer = null+ this.clearFailureEscalation()+ const socket = this.socket+ this.socket = null+ socket?.close()+ this.rejectPendingMutations("gateway connection closed")+ }++ send(content: string, options: MessageOptions = {}): string {+ if (!this.chatId) throw new Error("chat is not ready")+ const turnId = crypto.randomUUID()+ this.write({+ type: "message",+ chat_id: this.chatId,+ content,+ turn_id: turnId,+ webui: true,+ ...(this.workspaceScope ? { workspace_scope: this.workspaceScope } : {}),+ ...(options.userShell ? { user_shell: true } : {}),+ ...(options.media?.length ? { media: options.media } : {}),+ ...(options.cliApps?.length ? { cli_apps: options.cliApps } : {}),+ ...(options.mcpPresets?.length ? { mcp_presets: options.mcpPresets } : {}),+ ...(options.sessionMentions?.length+ ? { session_mentions: options.sessionMentions }+ : {}),+ })+ return turnId+ }++ attach(chatId: string): void {+ if (!chatId) throw new Error("chat id is required")+ this.workspaceScope = undefined+ this.write({ type: "attach", chat_id: chatId })+ }++ newChat(scope?: WorkspaceScopePayload): void {+ this.workspaceScope = scope+ this.write({ type: "new_chat", ...(scope ? { workspace_scope: scope } : {}) })+ }++ forkChat(sourceChatId: string, beforeUserIndex: number, title?: string): void {+ this.write({+ type: "fork_chat",+ source_chat_id: sourceChatId,+ before_user_index: beforeUserIndex,+ ...(title?.trim() ? { title: title.trim() } : {}),+ })+ }++ setWorkspaceScope(scope: WorkspaceScopePayload): void {+ if (!this.chatId) throw new Error("chat is not ready")+ this.workspaceScope = scope+ this.write({ type: "set_workspace_scope", chat_id: this.chatId, workspace_scope: scope })+ }++ updateRecovery(+ action: "continue" | "dismiss",+ chatId: string,+ recoveryId: string,+ ): Promise<RecoveryState> {+ return this.requestMutation<unknown>(`recovery.${action}`, {+ chat_id: chatId,+ recovery_id: recoveryId,+ }).then((result) => {+ if (!isRecoveryState(result)) throw new Error("gateway returned an invalid recovery state")+ return result+ })+ }++ private requestMutation<T>(+ action: string,+ 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"))+ }+ const requestId = crypto.randomUUID()+ const frame = JSON.stringify({+ type: "webui_request",+ request_id: requestId,+ action,+ payload,+ } satisfies OutboundEvent)+ return new Promise<T>((resolve, reject) => {+ const timer = setTimeout(() => {+ this.pendingMutations.delete(requestId)+ reject(new Error(`gateway request timed out after ${timeoutMs}ms`))+ }, timeoutMs)+ this.pendingMutations.set(requestId, {+ resolve: (value) => resolve(value as T),+ reject,+ timer,+ })+ try {+ this.socket?.send(frame)+ } catch {+ clearTimeout(timer)+ this.pendingMutations.delete(requestId)+ reject(new Error("could not send gateway request"))+ }+ })+ }++ private rejectPendingMutations(message: string): void {+ for (const pending of this.pendingMutations.values()) {+ clearTimeout(pending.timer)+ pending.reject(new Error(message))+ }+ this.pendingMutations.clear()+ }++ private handleMessage(raw: string): void {+ let value: unknown+ 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) {+ // 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+ }+ 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+ }+ if (response) {+ const pending = this.pendingMutations.get(response.request_id)+ if (!pending) return+ clearTimeout(pending.timer)+ this.pendingMutations.delete(response.request_id)+ if (response.ok) pending.resolve(response.result)+ else pending.reject(new Error(response.error?.message || "gateway request failed"))+ return+ }+ const event = decodeInboundEvent(value)+ if (event === undefined) return+ if (event === null) {+ this.options.onStatus("error", "gateway sent an invalid event")+ return+ }++ if (event.event === "ready") {+ const requestedChatId = this.chatId || this.options.chatId+ if (requestedChatId) {+ this.chatId = requestedChatId+ this.write({ type: "attach", chat_id: this.chatId })+ } else {+ this.newChat(this.options.initialWorkspaceScope)+ }+ } else if (event.event === "attached") {+ this.chatId = event.chat_id+ } else if (event.event === "session_updated" && event.workspace_scope) {+ this.workspaceScope = event.workspace_scope+ }+ this.options.onEvent(event)+ }++ private scheduleReconnect(): void {+ if (this.reconnectTimer || this.closedByClient) return+ if (!this.retryStartedAt) this.retryStartedAt = Date.now()+ const base = this.options.reconnectDelayMs ?? 500+ const maxDelay = this.connectedOnce+ ? 8_000+ : this.options.startupRetryMaxDelayMs ?? 8_000+ const delay = Math.min(maxDelay, base * 2 ** Math.min(this.reconnectAttempt++, 4))+ this.nextRetryAt = Date.now() + delay+ this.reportRetryState()+ this.reconnectTimer = setTimeout(() => {+ this.reconnectTimer = null+ void this.open()+ }, delay)+ }++ private async checkHealthAndScheduleReconnect(): Promise<void> {+ if (this.options.reconnect === false) { this.desktopFailure(); return }+ if (this.options.checkHealth) {+ try {+ this.healthStatus = await this.options.checkHealth()+ } catch {+ this.healthStatus = "unreachable"+ }+ }+ if (!this.closedByClient) this.scheduleReconnect()+ }++ private connectionInfo(): ConnectionStatusInfo {+ return {+ endpoint: this.endpoint,+ attempt: Math.max(1, this.connectionAttempt),+ elapsedMs: this.retryStartedAt ? Math.max(0, Date.now() - this.retryStartedAt) : 0,+ ...(this.nextRetryAt+ ? { retryInMs: Math.max(0, this.nextRetryAt - Date.now()) }+ : {}),+ ...(this.healthStatus ? { health: this.healthStatus } : {}),+ }+ }++ 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())+ return+ }+ const phase = this.options.resolveConnection ? "starting" : "connecting"+ this.options.onStatus(phase, undefined, this.connectionInfo())+ }++ private reportRetryState(): void {+ const info = this.connectionInfo()+ if (this.connectedOnce) {+ this.options.onStatus("reconnecting", this.lastFailure, info)+ return+ }+ const failureDelay = this.options.startupFailureDelayMs ?? 3_000+ if (info.elapsedMs >= failureDelay) {+ this.clearFailureEscalation()+ this.options.onStatus("unavailable", this.lastFailure, info)+ return+ }+ this.reportConnectionProgress()+ if (this.failureEscalationTimer) return+ this.failureEscalationTimer = setTimeout(() => {+ this.failureEscalationTimer = null+ if (this.closedByClient || this.connectedOnce || !this.lastFailure) return+ this.options.onStatus("unavailable", this.lastFailure, this.connectionInfo())+ }, Math.max(0, failureDelay - info.elapsedMs))+ }++ private clearFailureEscalation(): void {+ if (this.failureEscalationTimer) clearTimeout(this.failureEscalationTimer)+ this.failureEscalationTimer = null+ }++ 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")+ }+ this.socket.send(JSON.stringify(event))+ }+}diff --git a/tui/src/client/types.ts b/tui/src/client/types.tsnew file mode 100644index 000000000..d6b8c8963--- /dev/null+++ b/tui/src/client/types.ts@@ -0,0 +1,341 @@+import type {+ ContextCompaction,+ NotificationEvent,+ RecoveryState,+} from "../../../packages/client-events/notifications"++export type {+ ContextCompaction,+ RecoveryState,+ RetryStatus,+} from "../../../packages/client-events/notifications"++export type ConnectionStatus =+ | "starting"+ | "connecting"+ | "connected"+ | "reconnecting"+ | "unavailable"+ | "closed"+ | "error"++export interface ConnectionStatusInfo {+ endpoint: string+ attempt: number+ elapsedMs: number+ retryInMs?: number+ health?: GatewayHealthStatus+}++export type GatewayHealthStatus = "ready" | "degraded" | "unreachable"++export interface ToolProgressEvent {+ version?: number+ phase?: "start" | "end" | "error" | string+ call_id?: string+ name?: string+ arguments?: unknown+ result?: unknown+ error?: unknown+ files?: unknown[]+ embeds?: unknown[]+}++export interface FileEditEvent {+ version?: number+ call_id?: string+ tool?: string+ path?: string+ absolute_path?: string+ phase?: "start" | "end" | "error" | string+ added?: number+ deleted?: number+ approximate?: boolean+ status?: "editing" | "done" | "error" | string+ operation?: "edit" | "delete" | string+ binary?: boolean+ error?: string+ diff?: FileDiff+}++interface FileDiff {+ format: "unified" | string+ context?: number+ truncated?: boolean+ text?: string+}++export interface MediaAttachment {+ kind: "image" | "video" | "file"+ url: string+ name?: string+}++export interface OutboundMedia {+ data_url: string+ name?: string+}++export interface WorkspaceScopePayload {+ project_path: string+ project_name?: string+ access_mode: "restricted" | "full"+ restrict_to_workspace?: boolean+}++export interface RuntimeControls {+ modelPresets: Array<{ name: string; model: string }>+ canUseFullAccess: boolean+}++export type InboundEvent =+ | { event: "ready"; chat_id: string; client_id: string }+ | {+ event: "attached"+ chat_id: string+ model_preset?: string | null+ usage?: TokenUsage+ recovery_state?: RecoveryState+ }+ | {+ event: "message_accepted"+ chat_id: string+ turn_id: string+ starts_turn?: boolean+ active_turn_id?: string+ started_at?: number+ }+ | {+ event: "user_message"+ chat_id: string+ text: string+ turn_id?: string+ active_turn_id?: string+ starts_turn: boolean+ started_at?: number+ media_urls?: MediaAttachment[]+ }+ | {+ event: "message"+ chat_id: string+ text: string+ kind?: "tool_hint" | "progress" | "reasoning"+ tool_events?: ToolProgressEvent[]+ turn_id?: string+ }+ | { event: "file_edit"; chat_id: string; edits: FileEditEvent[]; turn_id?: string }+ | { event: "delta"; chat_id: string; text: string; stream_id?: string; turn_id?: string }+ | {+ event: "stream_end"+ chat_id: string+ text?: string+ stream_id?: string+ resuming?: boolean+ merge_next?: boolean+ turn_id?: string+ }+ | { event: "reasoning_delta"; chat_id: string; text: string; turn_id?: string }+ | { event: "reasoning_end"; chat_id: string; turn_id?: string }+ | {+ event: "turn_end"+ chat_id: string+ latency_ms?: number+ turn_id?: string+ usage?: TokenUsage+ context_window_tokens?: number+ goal_state?: Record<string, unknown>+ outcome?: "completed" | "failed" | "cancelled" | "interrupted"+ failure_kind?: string+ failure_error_kind?: string+ failure_attempts?: number+ failure_message?: string+ }+ | {+ event: "goal_status"+ chat_id: string+ status: "running" | "idle"+ started_at?: number+ turn_id?: string+ }+ | { event: "goal_state"; chat_id: string; goal_state: Record<string, unknown> }+ | NotificationEvent+ | {+ event: "session_updated"+ chat_id: string+ scope?: string+ workspace_scope?: WorkspaceScopePayload+ }+ | { event: "runtime_model_updated"; model_name: string; model_preset?: string | null }+ | {+ event: "turn_model_updated"+ chat_id: string+ model_name: string+ model_preset?: string | null+ context_window_tokens?: number+ }+ | { event: "error"; chat_id?: string; detail?: string; reason?: string; turn_id?: string }++export type OutboundEvent =+ | { type: "new_chat"; workspace_scope?: WorkspaceScopePayload }+ | { type: "fork_chat"; source_chat_id: string; before_user_index: number; title?: string }+ | { type: "attach"; chat_id: string }+ | { type: "set_workspace_scope"; chat_id: string; workspace_scope: WorkspaceScopePayload }+ | {+ type: "webui_request"+ request_id: string+ action: string+ payload: Record<string, unknown>+ }+ | {+ type: "message"+ chat_id: string+ content: string+ turn_id: string+ webui: true+ workspace_scope?: WorkspaceScopePayload+ media?: OutboundMedia[]+ cli_apps?: Array<{ name: string }>+ mcp_presets?: Array<{ name: string }>+ session_mentions?: SessionMention[]+ }++export interface ClientOptions {+ expectedGatewayId?: string+ reconnect?: boolean+ url?: string+ resolveConnection?: () => Promise<GatewayConnection>+ checkHealth?: () => Promise<GatewayHealthStatus>+ onConnection?: (connection: GatewayConnection) => void+ targetEndpoint?: string+ startupFailureDelayMs?: number+ startupRetryMaxDelayMs?: number+ chatId?: string+ initialWorkspaceScope?: WorkspaceScopePayload+ reconnectDelayMs?: number+ onEvent: (event: InboundEvent) => void+ onStatus: (status: ConnectionStatus, detail?: string, info?: ConnectionStatusInfo) => void+}++export interface GatewayApiConnection {+ apiUrl: string+ apiToken: string+}++export interface GatewayConnection extends GatewayApiConnection {+ wsUrl: string+}++export type ApiReauthenticator = (+ rejectedApiToken: string,+) => Promise<GatewayApiConnection>++export interface HistoryMessage {+ role: "user" | "assistant" | "activity"+ content: string+ turnId?: string+ media?: MediaAttachment[]+ toolEvents?: ToolProgressEvent[]+ fileEdits?: FileEditEvent[]+ compaction?: ContextCompaction+ forkIndex?: number+}++export interface HistorySnapshot {+ messages: HistoryMessage[]+ hasMoreBefore: boolean+ beforeCursor: string | null+ userMessageOffset: number+}++export interface TokenUsage {+ prompt_tokens?: number+ completion_tokens?: number+ cached_tokens?: number+ cache_write_tokens?: number+ total_tokens?: number+ context_tokens?: number+ request_count?: number+ provider_tokens?: number+ estimated_tokens?: number+ cost_usd?: number+ generation_ms?: number+ measured_completion_tokens?: number+ ttft_ms?: number+ timed_requests?: number+}++export interface SessionUsageSnapshot {+ context: { tokens: number; windowTokens?: number } | null+ rounds: TokenUsage[]+}++export interface SessionContextSnapshot {+ totalMessages: number+ archivedMessages: number+ replayMessages: number+ estimatedReplayTokens: number+ estimatedSummaryTokens: number+ estimatedSessionTokens: number+ archivedSummary: string | null+ archivedSummaryAt: string | null+ lastUsage: TokenUsage | null+}++interface SessionMention {+ name: string+ session_key: string+ title?: string+}++export interface MentionCandidate {+ kind: "session" | "cli" | "mcp"+ name: string+ targetName?: string+ displayName: string+ description: string+ session?: SessionMention+}++export interface SkillCandidate {+ name: string+ description: string+ source: string+}++export interface MessageOptions {+ media?: OutboundMedia[]+ cliApps?: Array<{ name: string }>+ mcpPresets?: Array<{ name: string }>+ sessionMentions?: SessionMention[]+ userShell?: boolean+}++export interface SlashCommand {+ command: string+ title: string+ description: string+ argHint: string+ lifecycle: SlashCommandLifecycle+ acceptsArgs: boolean+}++export type SlashCommandLifecycle =+ | "side_channel"+ | "finalize_active_turn"+ | "stop_active_turn"+ | "agent_turn"+ | "agent_turn_with_args"++export interface SessionSummary {+ chatId: string+ title: string+ preview: string+ createdAt: string | null+ updatedAt: string | null+ runStartedAt: number | null+ modelPreset: string | null+ recoveryState?: RecoveryState | null+ workspaceScope?: WorkspaceScopePayload | null+ pinned: boolean+ archived: boolean+}diff --git a/tui/src/usage-protocol.test.ts b/tui/src/client/usage.test.tssimilarity index 99%rename from tui/src/usage-protocol.test.tsrename to tui/src/client/usage.test.tsindex 95ba2c75c..dc1d5a90c 100644--- a/tui/src/usage-protocol.test.ts+++ b/tui/src/client/usage.test.ts@@ -1,6 +1,6 @@import { afterEach, describe, expect, mock, test } from "bun:test"-import { fetchSessionUsage } from "./protocol"+import { fetchSessionUsage } from "."const apiUrl = "http://nanobot.test"const apiToken = "usage-token"diff --git a/tui/src/client/validation.ts b/tui/src/client/validation.tsnew file mode 100644index 000000000..99b8cd94d--- /dev/null+++ b/tui/src/client/validation.ts@@ -0,0 +1,237 @@+import { decodeNotification, isRecoveryState } from "../../../packages/client-events/notifications"++import type {+ FileEditEvent,+ InboundEvent,+ MediaAttachment,+ TokenUsage,+ ToolProgressEvent,+ WorkspaceScopePayload,+} from "./types"++interface FileDiff {+ format: "unified" | string+ context?: number+ truncated?: boolean+ text?: string+}++const CHAT_EVENTS = new Set([+ "attached",+ "message_accepted",+ "user_message",+ "message",+ "file_edit",+ "delta",+ "stream_end",+ "reasoning_delta",+ "reasoning_end",+ "retry_status",+ "turn_end",+ "goal_status",+ "goal_state",+ "recovery_state",+ "context_compaction",+ "session_updated",+ "turn_model_updated",+ "error",+])++export function isRecord(value: unknown): value is Record<string, unknown> {+ return Boolean(value) && typeof value === "object" && !Array.isArray(value)+}++export function optional(value: unknown, type: "boolean" | "number" | "string"): boolean {+ return value === undefined || typeof value === type+}++function isToolEvent(value: unknown): value is ToolProgressEvent {+ if (!isRecord(value)) return false+ return optional(value.version, "number")+ && optional(value.phase, "string")+ && optional(value.call_id, "string")+ && optional(value.name, "string")+ && (value.files === undefined || Array.isArray(value.files))+ && (value.embeds === undefined || Array.isArray(value.embeds))+}++function isFileEdit(value: unknown): value is FileEditEvent {+ if (!isRecord(value)) return false+ return optional(value.version, "number")+ && optional(value.call_id, "string")+ && optional(value.tool, "string")+ && optional(value.path, "string")+ && optional(value.absolute_path, "string")+ && optional(value.phase, "string")+ && optional(value.status, "string")+ && optional(value.added, "number")+ && optional(value.deleted, "number")+ && optional(value.approximate, "boolean")+ && optional(value.operation, "string")+ && optional(value.binary, "boolean")+ && optional(value.error, "string")+ && (value.diff === undefined || isFileDiff(value.diff))+}++function isFileDiff(value: unknown): value is FileDiff {+ if (!isRecord(value) || typeof value.format !== "string") return false+ return optional(value.context, "number")+ && optional(value.truncated, "boolean")+ && optional(value.text, "string")+}++export function isTokenUsage(value: unknown): value is TokenUsage {+ if (!isRecord(value)) return false+ return [+ "prompt_tokens",+ "completion_tokens",+ "cached_tokens",+ "cache_write_tokens",+ "total_tokens",+ "context_tokens",+ "request_count",+ "provider_tokens",+ "estimated_tokens",+ "cost_usd",+ "generation_ms",+ "measured_completion_tokens",+ "ttft_ms",+ "timed_requests",+ ].every((key) => optional(value[key], "number"))+}++function isMediaAttachment(value: unknown): value is MediaAttachment {+ return isRecord(value)+ && (value.kind === "image" || value.kind === "video" || value.kind === "file")+ && typeof value.url === "string"+ && optional(value.name, "string")+}++export function isWorkspaceScope(value: unknown): value is WorkspaceScopePayload {+ return isRecord(value)+ && typeof value.project_path === "string"+ && (value.access_mode === "restricted" || value.access_mode === "full")+ && optional(value.project_name, "string")+ && optional(value.restrict_to_workspace, "boolean")+}++export interface WebUIResponseEvent {+ event: "webui_response"+ request_id: string+ ok: boolean+ result?: unknown+ error?: { status: number; message: string }+}++export function decodeWebUIResponse(value: unknown): WebUIResponseEvent | null | undefined {+ if (!isRecord(value) || value.event !== "webui_response") return undefined+ if (typeof value.request_id !== "string" || typeof value.ok !== "boolean") return null+ if (value.ok) return value as unknown as WebUIResponseEvent+ return isRecord(value.error)+ && typeof value.error.status === "number"+ && typeof value.error.message === "string"+ ? value as unknown as WebUIResponseEvent+ : null+}++export function decodeInboundEvent(value: unknown): InboundEvent | null | undefined {+ if (!isRecord(value)) return null+ const record = value+ const name = record.event+ if (typeof name !== "string") return null+ if (name === "ready") {+ return typeof record.chat_id === "string" && typeof record.client_id === "string"+ ? value as InboundEvent+ : null+ }+ if (name === "runtime_model_updated") {+ return typeof record.model_name === "string"+ && (record.model_preset === undefined+ || record.model_preset === null+ || typeof record.model_preset === "string")+ ? value as InboundEvent+ : null+ }+ if (name === "error" && (record.chat_id === undefined || typeof record.chat_id === "string")) {+ return optional(record.detail, "string") && optional(record.reason, "string")+ ? value as InboundEvent+ : null+ }+ if (!CHAT_EVENTS.has(name)) return undefined // Forward-compatible additive event.+ if (typeof record.chat_id !== "string") return null+ if (+ name === "attached"+ && ((record.model_preset !== undefined+ && record.model_preset !== null+ && typeof record.model_preset !== "string")+ || (record.usage !== undefined && !isTokenUsage(record.usage))+ || (record.recovery_state !== undefined && !isRecoveryState(record.recovery_state)))+ ) return null+ if (+ ["user_message", "message", "delta", "reasoning_delta"].includes(name)+ && typeof record.text !== "string"+ ) {+ return null+ }+ if (+ ["message_accepted", "user_message"].includes(name)+ && (+ (name === "user_message" && typeof record.starts_turn !== "boolean")+ || !optional(record.starts_turn, "boolean")+ || !optional(record.active_turn_id, "string")+ || !optional(record.started_at, "number")+ )+ ) return null+ if (+ name === "user_message"+ && record.media_urls !== undefined+ && (!Array.isArray(record.media_urls) || !record.media_urls.every(isMediaAttachment))+ ) return null+ if (+ name === "message"+ && record.tool_events !== undefined+ && (!Array.isArray(record.tool_events) || !record.tool_events.every(isToolEvent))+ ) return null+ if (name === "file_edit" && (!Array.isArray(record.edits) || !record.edits.every(isFileEdit))) {+ return null+ }+ if (+ name === "stream_end"+ && (!optional(record.text, "string")+ || !optional(record.resuming, "boolean")+ || !optional(record.merge_next, "boolean"))+ ) return null+ if (+ name === "turn_end"+ && (!optional(record.latency_ms, "number")+ || !optional(record.context_window_tokens, "number")+ || (record.usage !== undefined && !isTokenUsage(record.usage))+ || (record.goal_state !== undefined && !isRecord(record.goal_state))+ || (record.outcome !== undefined+ && !["completed", "failed", "cancelled", "interrupted"].includes(String(record.outcome)))+ || !optional(record.failure_kind, "string")+ || !optional(record.failure_error_kind, "string")+ || (record.failure_attempts !== undefined+ && (typeof record.failure_attempts !== "number"+ || !Number.isInteger(record.failure_attempts)+ || record.failure_attempts < 1))+ || !optional(record.failure_message, "string"))+ ) return null+ if (name === "goal_status" && record.status !== "running" && record.status !== "idle") return null+ if (name === "goal_state" && !isRecord(record.goal_state)) return null+ if (decodeNotification(record) === null) return null+ if (+ name === "session_updated"+ && (!optional(record.scope, "string")+ || (record.workspace_scope !== undefined && !isWorkspaceScope(record.workspace_scope)))+ ) return null+ if (+ name === "turn_model_updated"+ && (typeof record.model_name !== "string"+ || (record.model_preset !== undefined+ && record.model_preset !== null+ && typeof record.model_preset !== "string")+ || !optional(record.context_window_tokens, "number"))+ ) return null+ return value as InboundEvent+}diff --git a/tui/src/clipboard-image.test.ts b/tui/src/composer/clipboard-image.test.tssimilarity index 100%rename from tui/src/clipboard-image.test.tsrename to tui/src/composer/clipboard-image.test.tsdiff --git a/tui/src/clipboard-image.ts b/tui/src/composer/clipboard-image.tssimilarity index 100%rename from tui/src/clipboard-image.tsrename to tui/src/composer/clipboard-image.tsdiff --git a/tui/src/composer-draft.test.ts b/tui/src/composer/composer-draft.test.tssimilarity index 100%rename from tui/src/composer-draft.test.tsrename to tui/src/composer/composer-draft.test.tsdiff --git a/tui/src/composer-draft.ts b/tui/src/composer/composer-draft.tssimilarity index 99%rename from tui/src/composer-draft.tsrename to tui/src/composer/composer-draft.tsindex 04b1d391a..0e69a42af 100644--- a/tui/src/composer-draft.ts+++ b/tui/src/composer/composer-draft.ts@@ -1,4 +1,4 @@-import type { OutboundMedia } from "./protocol"+import type { OutboundMedia } from "../client"const LARGE_PASTE_CHARS = 1_000const LARGE_PASTE_LINES = 10diff --git a/tui/src/prompt-queue.test.ts b/tui/src/composer/prompt-queue.test.tssimilarity index 100%rename from tui/src/prompt-queue.test.tsrename to tui/src/composer/prompt-queue.test.tsdiff --git a/tui/src/prompt-queue.ts b/tui/src/composer/prompt-queue.tssimilarity index 93%rename from tui/src/prompt-queue.tsrename to tui/src/composer/prompt-queue.tsindex 419f0cdfc..aaa5bfd22 100644--- a/tui/src/prompt-queue.ts+++ b/tui/src/composer/prompt-queue.ts@@ -1,4 +1,4 @@-import type { MessageOptions } from "./protocol"+import type { MessageOptions } from "../client"export interface QueuedPrompt {content: stringdiff --git a/tui/src/queue-preview.test.ts b/tui/src/composer/queue-preview.test.tssimilarity index 100%rename from tui/src/queue-preview.test.tsrename to tui/src/composer/queue-preview.test.tsdiff --git a/tui/src/queue-preview.ts b/tui/src/composer/queue-preview.tssimilarity index 97%rename from tui/src/queue-preview.tsrename to tui/src/composer/queue-preview.tsindex 926b79d3d..404e69020 100644--- a/tui/src/queue-preview.ts+++ b/tui/src/composer/queue-preview.ts@@ -10,7 +10,7 @@ import {type TextChunk,} from "@opentui/core"-import { optionArrowUp } from "./platform-keys"+import { optionArrowUp } from "../platform/platform-keys"export interface QueuePreviewTheme {accent: ColorInputdiff --git a/tui/src/index.ts b/tui/src/index.tsindex ba7337354..4b6865c67 100644--- a/tui/src/index.ts+++ b/tui/src/index.ts@@ -1,5 +1,5 @@import { NanobotTui, sessionExitMessage, type AppOptions } from "./app"-import { desktopConnectionSource } from "./desktop"+import { desktopConnectionSource } from "./platform/desktop"if (process.argv.slice(2).join(" ") === "--desktop-protocol") {process.stdout.write("1\n")diff --git a/tui/src/branch-menu.test.ts b/tui/src/menus/branch-menu.test.tssimilarity index 100%rename from tui/src/branch-menu.test.tsrename to tui/src/menus/branch-menu.test.tsdiff --git a/tui/src/branch-menu.ts b/tui/src/menus/branch-menu.tssimilarity index 96%rename from tui/src/branch-menu.tsrename to tui/src/menus/branch-menu.tsindex 393ea27b0..5be10e743 100644--- a/tui/src/branch-menu.ts+++ b/tui/src/menus/branch-menu.ts@@ -1,7 +1,7 @@import { type BoxRenderable, type CliRenderer } from "@opentui/core"import { PickerMenu, type PickerMenuTheme } from "./picker-menu"-import type { HistoryMessage } from "./protocol"+import type { HistoryMessage } from "../client"export interface BranchPoint {beforeUserIndex: numberdiff --git a/tui/src/command-menu.test.ts b/tui/src/menus/command-menu.test.tssimilarity index 98%rename from tui/src/command-menu.test.tsrename to tui/src/menus/command-menu.test.tsindex cfe88fedd..7c9bdcbc0 100644--- a/tui/src/command-menu.test.ts+++ b/tui/src/menus/command-menu.test.ts@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"import { CommandMenu, resolveSlashCommandLifecycle } from "./command-menu"-import type { SlashCommand } from "./protocol"+import type { SlashCommand } from "../client"const commands: SlashCommand[] = [{diff --git a/tui/src/command-menu.ts b/tui/src/menus/command-menu.tssimilarity index 98%rename from tui/src/command-menu.tsrename to tui/src/menus/command-menu.tsindex 58cdb2cb4..f3a752371 100644--- a/tui/src/command-menu.ts+++ b/tui/src/menus/command-menu.ts@@ -1,6 +1,6 @@import { type BoxRenderable, type CliRenderer } from "@opentui/core"-import type { SlashCommand, SlashCommandLifecycle } from "./protocol"+import type { SlashCommand, SlashCommandLifecycle } from "../client"import { PickerMenu, type PickerMenuTheme } from "./picker-menu"export type CommandMenuTheme = PickerMenuThemediff --git a/tui/src/mention-menu.test.ts b/tui/src/menus/mention-menu.test.tssimilarity index 97%rename from tui/src/mention-menu.test.tsrename to tui/src/menus/mention-menu.test.tsindex c67437b98..f4c9c4546 100644--- a/tui/src/mention-menu.test.ts+++ b/tui/src/menus/mention-menu.test.ts@@ -1,7 +1,7 @@import { describe, expect, test } from "bun:test"import { insertMention, mentionOptions, mentionQuery } from "./mention-menu"-import type { MentionCandidate } from "./protocol"+import type { MentionCandidate } from "../client"const candidates: MentionCandidate[] = [{ kind: "cli", name: "github", displayName: "GitHub", description: "CLI" },diff --git a/tui/src/mention-menu.ts b/tui/src/menus/mention-menu.tssimilarity index 97%rename from tui/src/mention-menu.tsrename to tui/src/menus/mention-menu.tsindex 901a1bbf4..e18385cc8 100644--- a/tui/src/mention-menu.ts+++ b/tui/src/menus/mention-menu.ts@@ -1,7 +1,7 @@import { type BoxRenderable, type CliRenderer } from "@opentui/core"import { PickerMenu, type PickerMenuTheme } from "./picker-menu"-import type { MentionCandidate, MessageOptions } from "./protocol"+import type { MentionCandidate, MessageOptions } from "../client"export interface MentionQuery {query: stringdiff --git a/tui/src/picker-menu.test.ts b/tui/src/menus/picker-menu.test.tssimilarity index 100%rename from tui/src/picker-menu.test.tsrename to tui/src/menus/picker-menu.test.tsdiff --git a/tui/src/picker-menu.ts b/tui/src/menus/picker-menu.tssimilarity index 100%rename from tui/src/picker-menu.tsrename to tui/src/menus/picker-menu.tsdiff --git a/tui/src/session-menu.test.ts b/tui/src/menus/session-menu.test.tssimilarity index 99%rename from tui/src/session-menu.test.tsrename to tui/src/menus/session-menu.test.tsindex 4df6c1818..37b7d8776 100644--- a/tui/src/session-menu.test.ts+++ b/tui/src/menus/session-menu.test.ts@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"import { SessionMenu, sessionLabel } from "./session-menu"-import type { SessionSummary } from "./protocol"+import type { SessionSummary } from "../client"const sessions: SessionSummary[] = [{diff --git a/tui/src/session-menu.ts b/tui/src/menus/session-menu.tssimilarity index 99%rename from tui/src/session-menu.tsrename to tui/src/menus/session-menu.tsindex 3809bdd91..81417ba92 100644--- a/tui/src/session-menu.ts+++ b/tui/src/menus/session-menu.ts@@ -1,7 +1,7 @@import { parseColor, type ColorInput, type BoxRenderable, type CliRenderer, type TextChunk } from "@opentui/core"import { PickerMenu, type PickerMenuTheme } from "./picker-menu"-import type { SessionSummary } from "./protocol"+import type { SessionSummary } from "../client"type SessionMenuRow = SessionSummary & { active: boolean; unread: boolean }diff --git a/tui/src/skill-menu.test.ts b/tui/src/menus/skill-menu.test.tssimilarity index 98%rename from tui/src/skill-menu.test.tsrename to tui/src/menus/skill-menu.test.tsindex 7d35f1ca9..fb81aba0c 100644--- a/tui/src/skill-menu.test.ts+++ b/tui/src/menus/skill-menu.test.ts@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"import { insertSkill, SkillMenu, skillQuery } from "./skill-menu"-import type { SkillCandidate } from "./protocol"+import type { SkillCandidate } from "../client"const skills: SkillCandidate[] = [{ name: "simplify", description: "Simplify code", source: "workspace" },diff --git a/tui/src/skill-menu.ts b/tui/src/menus/skill-menu.tssimilarity index 98%rename from tui/src/skill-menu.tsrename to tui/src/menus/skill-menu.tsindex 16f2f0216..a1d3ff8ff 100644--- a/tui/src/skill-menu.ts+++ b/tui/src/menus/skill-menu.ts@@ -1,7 +1,7 @@import { type BoxRenderable, type CliRenderer } from "@opentui/core"import { PickerMenu, type PickerMenuTheme } from "./picker-menu"-import type { SkillCandidate } from "./protocol"+import type { SkillCandidate } from "../client"export interface SkillQuery {query: stringdiff --git a/tui/src/platform/clipboard.ts b/tui/src/platform/clipboard.tsnew file mode 100644index 000000000..fad25cdc2--- /dev/null+++ b/tui/src/platform/clipboard.ts@@ -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")+}diff --git a/tui/src/desktop.test.ts b/tui/src/platform/desktop.test.tssimilarity index 100%rename from tui/src/desktop.test.tsrename to tui/src/platform/desktop.test.tsdiff --git a/tui/src/desktop.ts b/tui/src/platform/desktop.tssimilarity index 98%rename from tui/src/desktop.tsrename to tui/src/platform/desktop.tsindex 49309440d..e050ae242 100644--- a/tui/src/desktop.ts+++ b/tui/src/platform/desktop.ts@@ -1,4 +1,4 @@-import type { GatewayConnection } from "./protocol"+import type { GatewayConnection } from "../client"type Environment = Record<string, string | undefined>diff --git a/tui/src/host.test.ts b/tui/src/platform/host.test.tssimilarity index 100%rename from tui/src/host.test.tsrename to tui/src/platform/host.test.tsdiff --git a/tui/src/host.ts b/tui/src/platform/host.tssimilarity index 100%rename from tui/src/host.tsrename to tui/src/platform/host.tsdiff --git a/tui/src/platform-keys.ts b/tui/src/platform/platform-keys.tssimilarity index 100%rename from tui/src/platform-keys.tsrename to tui/src/platform/platform-keys.tsdiff --git a/tui/src/protocol.ts b/tui/src/protocol.tsdeleted file mode 100644index 1790ed842..000000000--- a/tui/src/protocol.ts+++ /dev/null@@ -1,1598 +0,0 @@-import { decodeNotification, isRecoveryState } from "../../packages/client-events/notifications"-import type { ContextCompaction, NotificationEvent, RecoveryState } from "../../packages/client-events/notifications"-export type { ContextCompaction, RecoveryState, RetryStatus } from "../../packages/client-events/notifications"--export type ConnectionStatus =- | "starting"- | "connecting"- | "connected"- | "reconnecting"- | "unavailable"- | "closed"- | "error"--export interface ConnectionStatusInfo {- endpoint: string- attempt: number- elapsedMs: number- retryInMs?: number- health?: GatewayHealthStatus-}--export type GatewayHealthStatus = "ready" | "degraded" | "unreachable"--export interface ToolProgressEvent {- version?: number- phase?: "start" | "end" | "error" | string- call_id?: string- name?: string- arguments?: unknown- result?: unknown- error?: unknown- files?: unknown[]- embeds?: unknown[]-}--export interface FileEditEvent {- version?: number- call_id?: string- tool?: string- path?: string- absolute_path?: string- phase?: "start" | "end" | "error" | string- added?: number- deleted?: number- approximate?: boolean- status?: "editing" | "done" | "error" | string- operation?: "edit" | "delete" | string- binary?: boolean- error?: string- diff?: FileDiff-}--interface FileDiff {- format: "unified" | string- context?: number- truncated?: boolean- text?: string-}--export interface MediaAttachment {- kind: "image" | "video" | "file"- url: string- name?: string-}--export interface OutboundMedia {- data_url: string- name?: string-}--export interface WorkspaceScopePayload {- project_path: string- project_name?: string- access_mode: "restricted" | "full"- restrict_to_workspace?: boolean-}--export interface RuntimeControls {- modelPresets: Array<{ name: string; model: string }>- canUseFullAccess: boolean-}--export type InboundEvent =- | { event: "ready"; chat_id: string; client_id: string }- | {- event: "attached"- chat_id: string- model_preset?: string | null- usage?: TokenUsage- recovery_state?: RecoveryState- }- | {- event: "message_accepted"- chat_id: string- turn_id: string- starts_turn?: boolean- active_turn_id?: string- started_at?: number- }- | {- event: "user_message"- chat_id: string- text: string- turn_id?: string- active_turn_id?: string- starts_turn: boolean- started_at?: number- media_urls?: MediaAttachment[]- }- | {- event: "message"- chat_id: string- text: string- kind?: "tool_hint" | "progress" | "reasoning"- tool_events?: ToolProgressEvent[]- turn_id?: string- }- | { event: "file_edit"; chat_id: string; edits: FileEditEvent[]; turn_id?: string }- | { event: "delta"; chat_id: string; text: string; stream_id?: string; turn_id?: string }- | {- event: "stream_end"- chat_id: string- text?: string- stream_id?: string- resuming?: boolean- merge_next?: boolean- turn_id?: string- }- | { event: "reasoning_delta"; chat_id: string; text: string; turn_id?: string }- | { event: "reasoning_end"; chat_id: string; turn_id?: string }- | {- event: "turn_end"- chat_id: string- latency_ms?: number- turn_id?: string- usage?: TokenUsage- context_window_tokens?: number- goal_state?: Record<string, unknown>- outcome?: "completed" | "failed" | "cancelled" | "interrupted"- failure_kind?: string- failure_error_kind?: string- failure_attempts?: number- failure_message?: string- }- | {- event: "goal_status"- chat_id: string- status: "running" | "idle"- started_at?: number- turn_id?: string- }- | { event: "goal_state"; chat_id: string; goal_state: Record<string, unknown> }- | NotificationEvent- | {- event: "session_updated"- chat_id: string- scope?: string- workspace_scope?: WorkspaceScopePayload- }- | { event: "runtime_model_updated"; model_name: string; model_preset?: string | null }- | {- event: "turn_model_updated"- chat_id: string- model_name: string- model_preset?: string | null- context_window_tokens?: number- }- | { event: "error"; chat_id?: string; detail?: string; reason?: string; turn_id?: string }--type OutboundEvent =- | { type: "new_chat"; workspace_scope?: WorkspaceScopePayload }- | { type: "fork_chat"; source_chat_id: string; before_user_index: number; title?: string }- | { type: "attach"; chat_id: string }- | { type: "set_workspace_scope"; chat_id: string; workspace_scope: WorkspaceScopePayload }- | {- type: "webui_request"- request_id: string- action: string- payload: Record<string, unknown>- }- | {- type: "message"- chat_id: string- content: string- turn_id: string- webui: true- workspace_scope?: WorkspaceScopePayload- media?: OutboundMedia[]- cli_apps?: Array<{ name: string }>- mcp_presets?: Array<{ name: string }>- session_mentions?: SessionMention[]- }--export interface ClientOptions {- expectedGatewayId?: string- reconnect?: boolean- url?: string- resolveConnection?: () => Promise<GatewayConnection>- checkHealth?: () => Promise<GatewayHealthStatus>- onConnection?: (connection: GatewayConnection) => void- targetEndpoint?: string- startupFailureDelayMs?: number- startupRetryMaxDelayMs?: number- chatId?: string- initialWorkspaceScope?: WorkspaceScopePayload- reconnectDelayMs?: number- onEvent: (event: InboundEvent) => void- onStatus: (status: ConnectionStatus, detail?: string, info?: ConnectionStatusInfo) => void-}--export interface GatewayApiConnection {- apiUrl: string- apiToken: string-}--export interface GatewayConnection extends GatewayApiConnection {- wsUrl: string-}--export type ApiReauthenticator = (- rejectedApiToken: string,-) => Promise<GatewayApiConnection>--export class GatewayConnectionError extends Error {- constructor(message: string, readonly retryable: boolean) {- super(message)- this.name = "GatewayConnectionError"- }-}--export interface HistoryMessage {- role: "user" | "assistant" | "activity"- content: string- turnId?: string- media?: MediaAttachment[]- toolEvents?: ToolProgressEvent[]- fileEdits?: FileEditEvent[]- compaction?: ContextCompaction- forkIndex?: number-}--export interface HistorySnapshot {- messages: HistoryMessage[]- hasMoreBefore: boolean- beforeCursor: string | null- userMessageOffset: number-}--export interface TokenUsage {- prompt_tokens?: number- completion_tokens?: number- cached_tokens?: number- cache_write_tokens?: number- total_tokens?: number- context_tokens?: number- request_count?: number- provider_tokens?: number- estimated_tokens?: number- cost_usd?: number- generation_ms?: number- measured_completion_tokens?: number- ttft_ms?: number- timed_requests?: number-}--export interface SessionUsageSnapshot {- context: { tokens: number; windowTokens?: number } | null- rounds: TokenUsage[]-}--export interface SessionContextSnapshot {- totalMessages: number- archivedMessages: number- replayMessages: number- estimatedReplayTokens: number- estimatedSummaryTokens: number- estimatedSessionTokens: number- archivedSummary: string | null- archivedSummaryAt: string | null- lastUsage: TokenUsage | null-}--interface SessionMention {- name: string- session_key: string- title?: string-}--export interface MentionCandidate {- kind: "session" | "cli" | "mcp"- name: string- targetName?: string- displayName: string- description: string- session?: SessionMention-}--export interface SkillCandidate {- name: string- description: string- source: string-}--export interface MessageOptions {- media?: OutboundMedia[]- cliApps?: Array<{ name: string }>- mcpPresets?: Array<{ name: string }>- sessionMentions?: SessionMention[]- userShell?: boolean-}--export interface SlashCommand {- command: string- title: string- description: string- argHint: string- lifecycle: SlashCommandLifecycle- acceptsArgs: boolean-}--export type SlashCommandLifecycle =- | "side_channel"- | "finalize_active_turn"- | "stop_active_turn"- | "agent_turn"- | "agent_turn_with_args"--export interface SessionSummary {- chatId: string- title: string- preview: string- createdAt: string | null- updatedAt: string | null- runStartedAt: number | null- modelPreset: string | null- recoveryState?: RecoveryState | null- workspaceScope?: WorkspaceScopePayload | null- pinned: boolean- archived: boolean-}--const SKILL_REFERENCE_NAME = /^[A-Za-z0-9_-]+$/u--const SLASH_COMMAND_LIFECYCLES = new Set([- "side_channel",- "finalize_active_turn",- "stop_active_turn",- "agent_turn",- "agent_turn_with_args",-])--const CHAT_EVENTS = new Set([- "attached",- "message_accepted",- "user_message",- "message",- "file_edit",- "delta",- "stream_end",- "reasoning_delta",- "reasoning_end",- "retry_status",- "turn_end",- "goal_status",- "goal_state",- "recovery_state",- "context_compaction",- "session_updated",- "turn_model_updated",- "error",-])--function isRecord(value: unknown): value is Record<string, unknown> {- return Boolean(value) && typeof value === "object" && !Array.isArray(value)-}--function optional(value: unknown, type: "boolean" | "number" | "string"): boolean {- return value === undefined || typeof value === type-}--function isToolEvent(value: unknown): value is ToolProgressEvent {- if (!isRecord(value)) return false- return optional(value.version, "number")- && optional(value.phase, "string")- && optional(value.call_id, "string")- && optional(value.name, "string")- && (value.files === undefined || Array.isArray(value.files))- && (value.embeds === undefined || Array.isArray(value.embeds))-}--function isFileEdit(value: unknown): value is FileEditEvent {- if (!isRecord(value)) return false- return optional(value.version, "number")- && optional(value.call_id, "string")- && optional(value.tool, "string")- && optional(value.path, "string")- && optional(value.absolute_path, "string")- && optional(value.phase, "string")- && optional(value.status, "string")- && optional(value.added, "number")- && optional(value.deleted, "number")- && optional(value.approximate, "boolean")- && optional(value.operation, "string")- && optional(value.binary, "boolean")- && optional(value.error, "string")- && (value.diff === undefined || isFileDiff(value.diff))-}--function isFileDiff(value: unknown): value is FileDiff {- if (!isRecord(value) || typeof value.format !== "string") return false- return optional(value.context, "number")- && optional(value.truncated, "boolean")- && optional(value.text, "string")-}--function isTokenUsage(value: unknown): value is TokenUsage {- if (!isRecord(value)) return false- return [- "prompt_tokens",- "completion_tokens",- "cached_tokens",- "cache_write_tokens",- "total_tokens",- "context_tokens",- "request_count",- "provider_tokens",- "estimated_tokens",- "cost_usd",- "generation_ms",- "measured_completion_tokens",- "ttft_ms",- "timed_requests",- ].every((key) => optional(value[key], "number"))-}--function isMediaAttachment(value: unknown): value is MediaAttachment {- return isRecord(value)- && (value.kind === "image" || value.kind === "video" || value.kind === "file")- && typeof value.url === "string"- && optional(value.name, "string")-}--function isWorkspaceScope(value: unknown): value is WorkspaceScopePayload {- return isRecord(value)- && typeof value.project_path === "string"- && (value.access_mode === "restricted" || value.access_mode === "full")- && optional(value.project_name, "string")- && optional(value.restrict_to_workspace, "boolean")-}--interface WebUIResponseEvent {- event: "webui_response"- request_id: string- ok: boolean- result?: unknown- error?: { status: number; message: string }-}--function decodeWebUIResponse(value: unknown): WebUIResponseEvent | null | undefined {- if (!isRecord(value) || value.event !== "webui_response") return undefined- if (typeof value.request_id !== "string" || typeof value.ok !== "boolean") return null- if (value.ok) return value as unknown as WebUIResponseEvent- return isRecord(value.error)- && typeof value.error.status === "number"- && typeof value.error.message === "string"- ? value as unknown as WebUIResponseEvent- : null-}--function decodeInboundEvent(value: unknown): InboundEvent | null | undefined {- if (!isRecord(value)) return null- const record = value- const name = record.event- if (typeof name !== "string") return null- if (name === "ready") {- return typeof record.chat_id === "string" && typeof record.client_id === "string"- ? value as InboundEvent- : null- }- if (name === "runtime_model_updated") {- return typeof record.model_name === "string"- && (record.model_preset === undefined- || record.model_preset === null- || typeof record.model_preset === "string")- ? value as InboundEvent- : null- }- if (name === "error" && (record.chat_id === undefined || typeof record.chat_id === "string")) {- return optional(record.detail, "string") && optional(record.reason, "string")- ? value as InboundEvent- : null- }- if (!CHAT_EVENTS.has(name)) return undefined // Forward-compatible additive event.- if (typeof record.chat_id !== "string") return null- if (- name === "attached"- && ((record.model_preset !== undefined- && record.model_preset !== null- && typeof record.model_preset !== "string")- || (record.usage !== undefined && !isTokenUsage(record.usage))- || (record.recovery_state !== undefined && !isRecoveryState(record.recovery_state)))- ) return null- if (- ["user_message", "message", "delta", "reasoning_delta"].includes(name)- && typeof record.text !== "string"- ) {- return null- }- if (- ["message_accepted", "user_message"].includes(name)- && (- (name === "user_message" && typeof record.starts_turn !== "boolean")- || !optional(record.starts_turn, "boolean")- || !optional(record.active_turn_id, "string")- || !optional(record.started_at, "number")- )- ) return null- if (- name === "user_message"- && record.media_urls !== undefined- && (!Array.isArray(record.media_urls) || !record.media_urls.every(isMediaAttachment))- ) return null- if (- name === "message"- && record.tool_events !== undefined- && (!Array.isArray(record.tool_events) || !record.tool_events.every(isToolEvent))- ) return null- if (name === "file_edit" && (!Array.isArray(record.edits) || !record.edits.every(isFileEdit))) {- return null- }- if (- name === "stream_end"- && (!optional(record.text, "string")- || !optional(record.resuming, "boolean")- || !optional(record.merge_next, "boolean"))- ) return null- if (- name === "turn_end"- && (!optional(record.latency_ms, "number")- || !optional(record.context_window_tokens, "number")- || (record.usage !== undefined && !isTokenUsage(record.usage))- || (record.goal_state !== undefined && !isRecord(record.goal_state))- || (record.outcome !== undefined- && !["completed", "failed", "cancelled", "interrupted"].includes(String(record.outcome)))- || !optional(record.failure_kind, "string")- || !optional(record.failure_error_kind, "string")- || (record.failure_attempts !== undefined- && (typeof record.failure_attempts !== "number"- || !Number.isInteger(record.failure_attempts)- || record.failure_attempts < 1))- || !optional(record.failure_message, "string"))- ) return null- if (name === "goal_status" && record.status !== "running" && record.status !== "idle") return null- if (name === "goal_state" && !isRecord(record.goal_state)) return null- if (decodeNotification(record) === null) return null- if (- name === "session_updated"- && (!optional(record.scope, "string")- || (record.workspace_scope !== undefined && !isWorkspaceScope(record.workspace_scope)))- ) return null- if (- name === "turn_model_updated"- && (typeof record.model_name !== "string"- || (record.model_preset !== undefined- && record.model_preset !== null- && typeof record.model_preset !== "string")- || !optional(record.context_window_tokens, "number"))- ) return null- return value as InboundEvent-}--async function fetchApi(- apiUrl: string,- apiToken: string,- path: string,- reauthenticate?: ApiReauthenticator,- signal?: AbortSignal,-): Promise<Response> {- const request = (connection: GatewayApiConnection) => {- signal?.throwIfAborted()- return fetch(`${connection.apiUrl}${path}`, {- headers: { Authorization: `Bearer ${connection.apiToken}` },- ...(signal ? { signal } : {}),- })- }- const response = await request({ apiUrl, apiToken })- signal?.throwIfAborted()- if (response.status !== 401 || !reauthenticate) return response- return request(await reauthenticate(apiToken))-}--type HistoryEvent = Extract<InboundEvent, { event:- | "user_message" | "message" | "file_edit" | "delta" | "stream_end"- | "reasoning_delta" | "reasoning_end" | "context_compaction" | "turn_end"-}> & { round_usages?: TokenUsage[] }--interface ThreadPage {- events: HistoryEvent[]- page?: { has_more_before?: boolean; before_cursor?: string; user_message_offset?: number }-}--function parseHistoryEvents(values: unknown[]): HistoryEvent[] {- const events: HistoryEvent[] = []- const seen = new Set<string>()- for (const value of values) {- const event = decodeInboundEvent(value)- if (!event || !isRecord(value) || !optional(value.turn_id, "string")) {- throw new Error("Invalid history event")- }- if (typeof value.projection_id === "string") {- if (seen.has(value.projection_id)) continue- seen.add(value.projection_id)- }- switch (event.event) {- case "user_message":- case "message":- case "file_edit":- case "delta":- case "stream_end":- case "reasoning_delta":- case "reasoning_end":- case "context_compaction":- events.push(event)- break- case "turn_end":- events.push({- ...event,- round_usages: Array.isArray(value.round_usages) ? value.round_usages.filter(isTokenUsage) : [],- })- break- default:- throw new Error(`Unsupported history event: ${event.event}`)- }- }- return events-}--async function fetchThreadPage(- apiUrl: string,- apiToken: string,- chatId: string,- beforeCursor?: string | null,- reauthenticate?: ApiReauthenticator,- signal?: AbortSignal,-): Promise<ThreadPage> {- if (!apiUrl || !apiToken) return { events: [] }- const key = encodeURIComponent(`websocket:${chatId}`)- const params = new URLSearchParams({ limit: "120", direction: "latest" })- if (beforeCursor) params.set("before", beforeCursor)- const response = await fetchApi(- apiUrl,- apiToken,- `/api/sessions/${key}/webui-thread?${params}`,- reauthenticate,- signal,- )- if (response.status === 404) return { events: [] }- if (!response.ok) throw new Error(`history request failed: HTTP ${response.status}`)- const payload: unknown = await response.json()- if (!isRecord(payload) || typeof payload.schemaVersion !== "number") {- throw new Error("Invalid history response")- }- const page = isRecord(payload.page) ? payload.page : undefined- const pagination = {- has_more_before: page?.has_more_before === true,- before_cursor: typeof page?.before_cursor === "string" ? page.before_cursor : undefined,- user_message_offset: typeof page?.user_message_offset === "number" ? page.user_message_offset : undefined,- }- if (payload.projection === "events" && Array.isArray(payload.events)) {- return { events: parseHistoryEvents(payload.events), page: pagination }- }- throw new Error("Unsupported history response format")-}--/** Same recent model-call samples and context boundary as the WebUI usage popover. */-export async function fetchSessionUsage(- apiUrl: string,- apiToken: string,- chatId: string,- reauthenticate?: ApiReauthenticator,- signal?: AbortSignal,-): Promise<SessionUsageSnapshot> {- const payload = await fetchThreadPage(apiUrl, apiToken, chatId, undefined, reauthenticate, signal)- signal?.throwIfAborted()- const snapshot: SessionUsageSnapshot = { context: null, rounds: [] }- const seenTurns = new Set<unknown>()- let contextResolved = false- for (const event of [...payload.events].reverse()) {- if (event.event === "context_compaction" && event.phase === "succeeded") contextResolved = true- if (event.event !== "turn_end") continue- const usage = event.usage- if (!contextResolved && typeof usage?.context_tokens === "number"- && Number.isFinite(usage.context_tokens) && usage.context_tokens >= 0) {- const window = event.context_window_tokens- snapshot.context = {- tokens: usage.context_tokens,- ...(typeof window === "number" && Number.isFinite(window) && window > 0- ? { windowTokens: window } : {}),- }- contextResolved = true- }- const turnKey = event.turn_id || event- if (seenTurns.has(turnKey)) continue- seenTurns.add(turnKey)- for (const round of [...(event.round_usages ?? [])].reverse()) {- if (snapshot.rounds.length >= 8) break- if (typeof round.prompt_tokens === "number"- && Number.isFinite(round.prompt_tokens) && round.prompt_tokens > 0) {- snapshot.rounds.push(round)- }- }- }- snapshot.rounds.reverse()- return snapshot-}--export async function fetchHistory(- apiUrl: string,- apiToken: string,- chatId: string,- beforeCursor?: string | null,- reauthenticate?: ApiReauthenticator,-): Promise<HistorySnapshot> {- const payload = await fetchThreadPage(apiUrl, apiToken, chatId, beforeCursor, reauthenticate)- let userIndex = typeof payload.page?.user_message_offset === "number"- ? Math.max(0, payload.page.user_message_offset)- : 0- const messages: HistoryMessage[] = []- let stream: { row: HistoryMessage; turnId?: string } | null = null- let lastAnswer: { row: HistoryMessage; turnId?: string } | null = null- for (const event of payload.events) {- switch (event.event) {- case "user_message": {- if (event.starts_turn) stream = null- const media = event.media_urls ?? []- if (!event.text.trim() && !media.length) break- userIndex += 1- messages.push({- role: "user", content: event.text,- ...(media.length ? { media } : {}),- ...(event.turn_id ? { turnId: event.turn_id } : {}),- })- lastAnswer = null- break- }- case "delta":- case "stream_end":- if (!stream || stream.turnId !== event.turn_id) {- const row: HistoryMessage = { role: "assistant", content: "", forkIndex: userIndex }- messages.push(row)- stream = { row, turnId: event.turn_id }- }- if (event.event === "delta") stream.row.content += event.text- else if (event.text !== undefined) stream.row.content = event.text- lastAnswer = stream- if (event.event === "stream_end" && !(event.resuming && event.merge_next)) stream = null- break- case "message":- if (event.kind === "reasoning") break- if (event.kind === "tool_hint" || event.kind === "progress") {- messages.push({- role: "activity", content: event.text,- ...(event.tool_events?.length ? { toolEvents: event.tool_events } : {}),- })- } else {- // A final message can repeat the answer already saved by stream_end.- if (stream && stream.turnId === event.turn_id) stream.row.content = event.text- else if (!lastAnswer || lastAnswer.turnId !== event.turn_id || lastAnswer.row.content !== event.text) {- const row: HistoryMessage = { role: "assistant", content: event.text, forkIndex: userIndex }- messages.push(row)- lastAnswer = { row, turnId: event.turn_id }- }- stream = null- }- break- case "file_edit":- if (event.edits.length) messages.push({ role: "activity", content: "", fileEdits: event.edits })- break- case "context_compaction":- stream = null- messages.push({- role: "activity", content: "",- compaction: { id: event.compaction_id, phase: event.phase },- })- break- case "turn_end":- stream = null- lastAnswer = null- break- case "reasoning_delta":- case "reasoning_end":- break- }- }- return {- messages: messages.filter((row) => row.role !== "assistant" || row.content.trim()),- hasMoreBefore: payload.page?.has_more_before === true,- beforeCursor: typeof payload.page?.before_cursor === "string"- ? payload.page.before_cursor- : null,- userMessageOffset: typeof payload.page?.user_message_offset === "number"- ? Math.max(0, payload.page.user_message_offset)- : 0,- }-}--export async function fetchSessionContext(- apiUrl: string,- apiToken: string,- chatId: string,- reauthenticate?: ApiReauthenticator,-): Promise<SessionContextSnapshot | null> {- if (!apiUrl || !apiToken) return null- const key = encodeURIComponent(`websocket:${chatId}`)- const response = await fetchApi(- apiUrl,- apiToken,- `/api/sessions/${key}/context`,- reauthenticate,- )- if (response.status === 404) return null- if (!response.ok) throw new Error(`context request failed: HTTP ${response.status}`)- const value = await response.json() as Record<string, unknown>- const number = (key: string) => typeof value[key] === "number" ? value[key] as number : 0- return {- totalMessages: number("total_messages"),- archivedMessages: number("archived_messages"),- replayMessages: number("replay_messages"),- estimatedReplayTokens: number("estimated_replay_tokens"),- estimatedSummaryTokens: number("estimated_summary_tokens"),- estimatedSessionTokens: number("estimated_session_tokens"),- archivedSummary: typeof value.archived_summary === "string" ? value.archived_summary : null,- archivedSummaryAt: typeof value.archived_summary_at === "string"- ? value.archived_summary_at- : null,- lastUsage: isTokenUsage(value.last_usage) ? value.last_usage : null,- }-}--export async function fetchSlashCommands(- apiUrl: string,- apiToken: string,- reauthenticate?: ApiReauthenticator,-): Promise<SlashCommand[]> {- if (!apiUrl || !apiToken) return []- const response = await fetchApi(apiUrl, apiToken, "/api/commands", reauthenticate)- if (!response.ok) throw new Error(`command request failed: HTTP ${response.status}`)- const payload = await response.json() as { commands?: unknown[] }- return (payload.commands || []).flatMap((value) => {- if (- !isRecord(value)- || typeof value.command !== "string"- || typeof value.lifecycle !== "string"- || !SLASH_COMMAND_LIFECYCLES.has(value.lifecycle)- ) return []- return [{- command: value.command,- title: typeof value.title === "string" ? value.title : value.command,- description: typeof value.description === "string" ? value.description : "",- argHint: typeof value.arg_hint === "string" ? value.arg_hint : "",- lifecycle: value.lifecycle as SlashCommandLifecycle,- acceptsArgs: value.accepts_args === true,- }]- })-}--export async function fetchAvailableSkills(- apiUrl: string,- apiToken: string,- reauthenticate?: ApiReauthenticator,-): Promise<SkillCandidate[]> {- if (!apiUrl || !apiToken) return []- const response = await fetchApi(apiUrl, apiToken, "/api/webui/skills", reauthenticate)- if (!response.ok) throw new Error(`skill request failed: HTTP ${response.status}`)- const payload = await response.json() as { skills?: unknown[] }- return (payload.skills || []).flatMap((value) => {- if (- !isRecord(value)- || typeof value.name !== "string"- || !SKILL_REFERENCE_NAME.test(value.name)- || value.enabled !== true- || value.available !== true- ) return []- return [{- name: value.name,- description: typeof value.description === "string" ? value.description : value.name,- source: typeof value.source === "string" ? value.source : "unknown",- }]- })-}--export async function fetchRuntimeControls(- apiUrl: string,- apiToken: string,- reauthenticate?: ApiReauthenticator,-): Promise<RuntimeControls> {- if (!apiUrl || !apiToken) return { modelPresets: [], canUseFullAccess: false }- const [settingsResponse, workspacesResponse] = await Promise.all([- fetchApi(apiUrl, apiToken, "/api/settings", reauthenticate),- fetchApi(apiUrl, apiToken, "/api/workspaces", reauthenticate).catch(() => null),- ])- if (!settingsResponse.ok) {- throw new Error(`settings request failed: HTTP ${settingsResponse.status}`)- }- const settings = await settingsResponse.json() as { model_presets?: unknown[] }- const workspaces = workspacesResponse?.ok- ? await workspacesResponse.json() as { controls?: unknown }- : {}- const modelPresets = (settings.model_presets || []).flatMap((value) => {- if (!isRecord(value) || typeof value.name !== "string" || typeof value.model !== "string") {- return []- }- const name = value.name.trim()- return name ? [{ name, model: value.model.trim() }] : []- })- const controls = isRecord(workspaces.controls) ? workspaces.controls : {}- return {- modelPresets,- canUseFullAccess: controls.can_use_full_access === true,- }-}--export async function fetchSessions(- apiUrl: string,- apiToken: string,- reauthenticate?: ApiReauthenticator,-): Promise<SessionSummary[]> {- if (!apiUrl || !apiToken) return []- const [response, sidebarResponse] = await Promise.all([- fetchApi(apiUrl, apiToken, "/api/sessions", reauthenticate),- fetchApi(apiUrl, apiToken, "/api/webui/sidebar-state", reauthenticate).catch(() => null),- ])- if (!response.ok) throw new Error(`session request failed: HTTP ${response.status}`)- const payload = await response.json() as { sessions?: unknown[] }- let sidebar: Record<string, unknown> = {}- if (sidebarResponse?.ok) {- try {- const value: unknown = await sidebarResponse.json()- if (isRecord(value)) sidebar = value- } catch {- // Session navigation remains available against older or damaged sidebar state.- }- }- const pinned = new Set(Array.isArray(sidebar.pinned_keys) ? sidebar.pinned_keys : [])- const archived = new Set(Array.isArray(sidebar.archived_keys) ? sidebar.archived_keys : [])- const titles = isRecord(sidebar.title_overrides) ? sidebar.title_overrides : {}- return (payload.sessions || []).flatMap((value) => {- if (!isRecord(value) || typeof value.key !== "string" || !value.key.startsWith("websocket:")) {- return []- }- const chatId = value.key.slice("websocket:".length)- if (!chatId) return []- const titleOverride = titles[value.key]- return [{- chatId,- title: typeof titleOverride === "string"- ? titleOverride- : typeof value.title === "string" ? value.title : "",- preview: typeof value.preview === "string" ? value.preview : "",- createdAt: typeof value.created_at === "string" ? value.created_at : null,- updatedAt: typeof value.updated_at === "string" ? value.updated_at : null,- runStartedAt: typeof value.run_started_at === "number" ? value.run_started_at : null,- modelPreset: typeof value.model_preset === "string" && value.model_preset.trim()- ? value.model_preset.trim()- : null,- ...(isRecoveryState(value.recovery_state)- ? { recoveryState: value.recovery_state }- : {}),- ...(isWorkspaceScope(value.workspace_scope) ? { workspaceScope: value.workspace_scope } : {}),- pinned: pinned.has(value.key),- archived: archived.has(value.key),- }]- })-}--function sessionMentionName(session: SessionSummary): string {- const label = (session.title || session.preview || "session")- .normalize("NFKC")- .replace(/\s+/gu, "-")- .replace(/[^\p{L}\p{N}_-]+/gu, "")- .replace(/-+/gu, "-")- .replace(/^-|-$/gu, "")- return Array.from(label || "session").slice(0, 40).join("")-}--/** Installed capabilities and saved chats share one mention namespace. */-export async function fetchMentionCandidates(- apiUrl: string,- apiToken: string,- reauthenticate?: ApiReauthenticator,-): Promise<MentionCandidate[]> {- if (!apiUrl || !apiToken) return []- const [sessions, appsResponse, mcpResponse] = await Promise.all([- fetchSessions(apiUrl, apiToken, reauthenticate),- fetchApi(- apiUrl,- apiToken,- "/api/settings/cli-apps?installed_only=1",- reauthenticate,- ).catch(() => null),- fetchApi(apiUrl, apiToken, "/api/settings/mcp-presets", reauthenticate).catch(() => null),- ])- const used = new Set<string>()- const uniqueName = (raw: string) => {- const base = raw || "session"- let name = base- let suffix = 2- while (used.has(name.toLocaleLowerCase())) name = `${base}-${suffix++}`- used.add(name.toLocaleLowerCase())- return name- }- const candidates: MentionCandidate[] = []- if (appsResponse?.ok) {- const payload = await appsResponse.json() as { apps?: unknown[] }- for (const value of payload.apps || []) {- if (!isRecord(value) || value.installed !== true || typeof value.name !== "string") continue- const name = uniqueName(value.name)- candidates.push({- kind: "cli",- name,- ...(name === value.name ? {} : { targetName: value.name }),- displayName: typeof value.display_name === "string" ? value.display_name : name,- description: typeof value.description === "string" ? value.description : "CLI app",- })- }- }- if (mcpResponse?.ok) {- const payload = await mcpResponse.json() as { presets?: unknown[] }- for (const value of payload.presets || []) {- if (- !isRecord(value)- || value.installed !== true- || value.configured !== true- || typeof value.name !== "string"- ) continue- const name = uniqueName(value.name)- candidates.push({- kind: "mcp",- name,- ...(name === value.name ? {} : { targetName: value.name }),- displayName: typeof value.display_name === "string" ? value.display_name : name,- description: typeof value.description === "string" ? value.description : "MCP server",- })- }- }- for (const session of sessions) {- const name = uniqueName(sessionMentionName(session))- candidates.push({- kind: "session",- name,- displayName: sessionLabelForMention(session),- description: session.preview || "Saved session",- session: {- name,- session_key: `websocket:${session.chatId}`,- title: session.title || undefined,- },- })- }- return candidates-}--function sessionLabelForMention(session: SessionSummary): string {- return (session.title || session.preview || "Untitled chat").replace(/\s+/gu, " ").trim()-}--/** Resolve fresh short-lived credentials once the local gateway is reachable. */-export async function fetchGatewayConnection(- bootstrapUrl: string,- bootstrapSecret: string,- apiUrl: string,- clientId: string,-): Promise<GatewayConnection> {- const response = await fetch(bootstrapUrl, {- headers: bootstrapSecret ? { "X-Nanobot-Auth": bootstrapSecret } : {},- })- if (!response.ok) {- const retryable = response.status === 408 || response.status === 429 || response.status >= 500- throw new GatewayConnectionError(- `gateway bootstrap failed: HTTP ${response.status}`,- retryable,- )- }- let payload: unknown- try {- payload = await response.json()- } catch {- throw new GatewayConnectionError("gateway bootstrap response is invalid", false)- }- if (!isRecord(payload)) {- throw new GatewayConnectionError("gateway bootstrap response is invalid", false)- }- if (typeof payload.ws_url !== "string" || !payload.ws_url.trim()) {- throw new GatewayConnectionError("gateway bootstrap response is missing ws_url", false)- }- let wsUrl: URL- try {- wsUrl = new URL(payload.ws_url)- } catch {- throw new GatewayConnectionError("gateway bootstrap response has an invalid ws_url", false)- }- if (wsUrl.protocol !== "ws:" && wsUrl.protocol !== "wss:") {- throw new GatewayConnectionError("gateway bootstrap response has an invalid ws_url", false)- }- if (typeof payload.token === "string" && payload.token) {- wsUrl.searchParams.append("token", payload.token)- }- wsUrl.searchParams.append("client_id", clientId)- return {- wsUrl: wsUrl.toString(),- apiUrl,- apiToken: typeof payload.api_token === "string" ? payload.api_token : "",- }-}--/** Read gateway readiness without sending bootstrap or API credentials. */-export async function fetchGatewayHealth(- healthUrl: string,- timeoutMs = 400,-): Promise<GatewayHealthStatus> {- const controller = new AbortController()- const timer = setTimeout(() => controller.abort(), timeoutMs)- try {- const response = await fetch(healthUrl, { signal: controller.signal })- if (response.status !== 200 && response.status !== 503) return "unreachable"- const payload: unknown = await response.json()- if (!isRecord(payload)) return "unreachable"- if (- response.status === 503- && payload.status === "degraded"- && payload.ready === false- && payload.process === "alive"- ) return "degraded"- if (response.status === 200 && payload.status === "ok" && payload.ready !== false) {- return "ready"- }- return "unreachable"- } catch {- return "unreachable"- } finally {- clearTimeout(timer)- }-}--/** Return only the authority users can act on, never credentials or an authenticated path. */-export function connectionEndpoint(value: string | undefined): string {- if (!value) return "local gateway"- try {- return new URL(value).host || "local gateway"- } catch {- return "local gateway"- }-}--/** Reduce arbitrary fetch/WebSocket errors to a small set of credential-safe reasons. */-export function sanitizeConnectionFailure(error: unknown): string {- const signals: string[] = []- const seen = new Set<unknown>()- const collect = (value: unknown): void => {- if (value === null || value === undefined || seen.has(value)) return- if (typeof value === "object") seen.add(value)- if (typeof value === "string") {- signals.push(value)- return- }- if (value instanceof Error) {- signals.push(value.name, value.message)- collect(value.cause)- if (value instanceof AggregateError) {- for (const nested of value.errors) collect(nested)- }- return- }- if (!isRecord(value)) return- if (typeof value.code === "string") signals.push(value.code)- collect(value.cause)- if (Array.isArray(value.errors)) {- for (const nested of value.errors) collect(nested)- }- }- collect(error)- const signal = signals.join(" ")- if (/ECONNREFUSED|connection refused/iu.test(signal)) return "connection refused"- if (/ETIMEDOUT|timed? out|timeout/iu.test(signal)) return "connection timed out"- if (/ENOTFOUND|EAI_AGAIN|name not resolved|host not found/iu.test(signal)) {- return "host not found"- }- if (/certificate|TLS|SSL/iu.test(signal)) return "secure connection failed"- const bootstrapStatus = signal.match(/gateway bootstrap failed:\s*HTTP\s*(\d{3})/iu)- if (bootstrapStatus?.[1]) return `gateway bootstrap failed: HTTP ${bootstrapStatus[1]}`- if (/bootstrap response is missing ws_url/iu.test(signal)) {- return "gateway bootstrap response is missing ws_url"- }- if (/bootstrap response (?:has an invalid ws_url|is invalid)/iu.test(signal)) {- return "gateway bootstrap response is invalid"- }- if (/gateway is still starting/iu.test(signal)) return "gateway is still starting"- if (/fetch failed|failed to fetch|network error/iu.test(signal)) return "network request failed"- return "connection failed"-}--export class NanobotClient {- private identityVerified = false- private handshakeTimer: ReturnType<typeof setTimeout> | null = null- private socket: WebSocket | null = null- private chatId = ""- private workspaceScope?: WorkspaceScopePayload- private reconnectTimer: ReturnType<typeof setTimeout> | null = null- private reconnectAttempt = 0- private closedByClient = false- private opening = false- private connectedOnce = false- private connectionAttempt = 0- private retryStartedAt = 0- private nextRetryAt = 0- private lastFailure = ""- private healthStatus: GatewayHealthStatus | undefined- private failureEscalationTimer: ReturnType<typeof setTimeout> | null = null- private readonly endpoint: string- private readonly pendingMutations = new Map<string, {- resolve: (value: unknown) => void- reject: (error: Error) => void- timer: ReturnType<typeof setTimeout>- }>()-- constructor(private readonly options: ClientOptions) {- this.endpoint = options.targetEndpoint || connectionEndpoint(options.url)- }-- get activeChatId(): string {- return this.chatId- }-- connect(): void {- this.closedByClient = false- this.connectionAttempt = 0- this.reconnectAttempt = 0- this.retryStartedAt = Date.now()- this.nextRetryAt = 0- this.lastFailure = ""- this.healthStatus = undefined- void this.open()- }-- 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()- let url = this.options.url- try {- if (this.options.resolveConnection) {- const connection = await this.options.resolveConnection()- if (this.closedByClient) return- this.options.onConnection?.(connection)- url = connection.wsUrl- }- } catch (error) {- if (!this.closedByClient) {- this.lastFailure = sanitizeConnectionFailure(error)- if (error instanceof GatewayConnectionError && !error.retryable) {- this.clearFailureEscalation()- this.options.onStatus("error", this.lastFailure, this.connectionInfo())- return- }- await this.checkHealthAndScheduleReconnect()- }- return- } finally {- this.opening = false- }- if (!url) {- this.options.onStatus("error", "gateway URL is not configured", this.connectionInfo())- return- }- let socket: WebSocket- try {- socket = new WebSocket(url)- } catch (error) {- this.lastFailure = sanitizeConnectionFailure(error)- await this.checkHealthAndScheduleReconnect()- return- }- 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- this.connectedOnce = true- this.connectionAttempt = 0- this.reconnectAttempt = 0- this.retryStartedAt = 0- this.nextRetryAt = 0- this.lastFailure = ""- this.healthStatus = "ready"- this.clearFailureEscalation()- this.options.onStatus("connected", undefined, this.connectionInfo())- })- socket.addEventListener("message", (message) => {- if (this.socket === socket) this.handleMessage(String(message.data))- })- socket.addEventListener("error", () => {- if (this.socket !== socket) return- if (this.options.reconnect === false) { this.desktopFailure(); return }- this.lastFailure = "connection failed"- this.reportRetryState()- })- socket.addEventListener("close", () => {- if (this.socket !== socket) return- this.socket = null- this.rejectPendingMutations("gateway connection closed")- if (this.closedByClient) {- this.options.onStatus("closed")- return- }- if (this.options.reconnect === false) { this.desktopFailure(); return }- if (opened) {- this.connectionAttempt = 0- this.reconnectAttempt = 0- this.retryStartedAt = Date.now()- }- if (!this.lastFailure) this.lastFailure = "connection closed"- this.reportRetryState()- void this.checkHealthAndScheduleReconnect()- })- }-- close(): void {- if (this.handshakeTimer) clearTimeout(this.handshakeTimer)- this.handshakeTimer = null- this.closedByClient = true- if (this.reconnectTimer) clearTimeout(this.reconnectTimer)- this.reconnectTimer = null- this.clearFailureEscalation()- const socket = this.socket- this.socket = null- socket?.close()- this.rejectPendingMutations("gateway connection closed")- }-- send(content: string, options: MessageOptions = {}): string {- if (!this.chatId) throw new Error("chat is not ready")- const turnId = crypto.randomUUID()- this.write({- type: "message",- chat_id: this.chatId,- content,- turn_id: turnId,- webui: true,- ...(this.workspaceScope ? { workspace_scope: this.workspaceScope } : {}),- ...(options.userShell ? { user_shell: true } : {}),- ...(options.media?.length ? { media: options.media } : {}),- ...(options.cliApps?.length ? { cli_apps: options.cliApps } : {}),- ...(options.mcpPresets?.length ? { mcp_presets: options.mcpPresets } : {}),- ...(options.sessionMentions?.length- ? { session_mentions: options.sessionMentions }- : {}),- })- return turnId- }-- attach(chatId: string): void {- if (!chatId) throw new Error("chat id is required")- this.workspaceScope = undefined- this.write({ type: "attach", chat_id: chatId })- }-- newChat(scope?: WorkspaceScopePayload): void {- this.workspaceScope = scope- this.write({ type: "new_chat", ...(scope ? { workspace_scope: scope } : {}) })- }-- forkChat(sourceChatId: string, beforeUserIndex: number, title?: string): void {- this.write({- type: "fork_chat",- source_chat_id: sourceChatId,- before_user_index: beforeUserIndex,- ...(title?.trim() ? { title: title.trim() } : {}),- })- }-- setWorkspaceScope(scope: WorkspaceScopePayload): void {- if (!this.chatId) throw new Error("chat is not ready")- this.workspaceScope = scope- this.write({ type: "set_workspace_scope", chat_id: this.chatId, workspace_scope: scope })- }-- updateRecovery(- action: "continue" | "dismiss",- chatId: string,- recoveryId: string,- ): Promise<RecoveryState> {- return this.requestMutation<unknown>(`recovery.${action}`, {- chat_id: chatId,- recovery_id: recoveryId,- }).then((result) => {- if (!isRecoveryState(result)) throw new Error("gateway returned an invalid recovery state")- return result- })- }-- private requestMutation<T>(- action: string,- 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"))- }- const requestId = crypto.randomUUID()- const frame = JSON.stringify({- type: "webui_request",- request_id: requestId,- action,- payload,- } satisfies OutboundEvent)- return new Promise<T>((resolve, reject) => {- const timer = setTimeout(() => {- this.pendingMutations.delete(requestId)- reject(new Error(`gateway request timed out after ${timeoutMs}ms`))- }, timeoutMs)- this.pendingMutations.set(requestId, {- resolve: (value) => resolve(value as T),- reject,- timer,- })- try {- this.socket?.send(frame)- } catch {- clearTimeout(timer)- this.pendingMutations.delete(requestId)- reject(new Error("could not send gateway request"))- }- })- }-- private rejectPendingMutations(message: string): void {- for (const pending of this.pendingMutations.values()) {- clearTimeout(pending.timer)- pending.reject(new Error(message))- }- this.pendingMutations.clear()- }-- private handleMessage(raw: string): void {- let value: unknown- 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) {- // 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- }- 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- }- if (response) {- const pending = this.pendingMutations.get(response.request_id)- if (!pending) return- clearTimeout(pending.timer)- this.pendingMutations.delete(response.request_id)- if (response.ok) pending.resolve(response.result)- else pending.reject(new Error(response.error?.message || "gateway request failed"))- return- }- const event = decodeInboundEvent(value)- if (event === undefined) return- if (event === null) {- this.options.onStatus("error", "gateway sent an invalid event")- return- }-- if (event.event === "ready") {- const requestedChatId = this.chatId || this.options.chatId- if (requestedChatId) {- this.chatId = requestedChatId- this.write({ type: "attach", chat_id: this.chatId })- } else {- this.newChat(this.options.initialWorkspaceScope)- }- } else if (event.event === "attached") {- this.chatId = event.chat_id- } else if (event.event === "session_updated" && event.workspace_scope) {- this.workspaceScope = event.workspace_scope- }- this.options.onEvent(event)- }-- private scheduleReconnect(): void {- if (this.reconnectTimer || this.closedByClient) return- if (!this.retryStartedAt) this.retryStartedAt = Date.now()- const base = this.options.reconnectDelayMs ?? 500- const maxDelay = this.connectedOnce- ? 8_000- : this.options.startupRetryMaxDelayMs ?? 8_000- const delay = Math.min(maxDelay, base * 2 ** Math.min(this.reconnectAttempt++, 4))- this.nextRetryAt = Date.now() + delay- this.reportRetryState()- this.reconnectTimer = setTimeout(() => {- this.reconnectTimer = null- void this.open()- }, delay)- }-- private async checkHealthAndScheduleReconnect(): Promise<void> {- if (this.options.reconnect === false) { this.desktopFailure(); return }- if (this.options.checkHealth) {- try {- this.healthStatus = await this.options.checkHealth()- } catch {- this.healthStatus = "unreachable"- }- }- if (!this.closedByClient) this.scheduleReconnect()- }-- private connectionInfo(): ConnectionStatusInfo {- return {- endpoint: this.endpoint,- attempt: Math.max(1, this.connectionAttempt),- elapsedMs: this.retryStartedAt ? Math.max(0, Date.now() - this.retryStartedAt) : 0,- ...(this.nextRetryAt- ? { retryInMs: Math.max(0, this.nextRetryAt - Date.now()) }- : {}),- ...(this.healthStatus ? { health: this.healthStatus } : {}),- }- }-- 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())- return- }- const phase = this.options.resolveConnection ? "starting" : "connecting"- this.options.onStatus(phase, undefined, this.connectionInfo())- }-- private reportRetryState(): void {- const info = this.connectionInfo()- if (this.connectedOnce) {- this.options.onStatus("reconnecting", this.lastFailure, info)- return- }- const failureDelay = this.options.startupFailureDelayMs ?? 3_000- if (info.elapsedMs >= failureDelay) {- this.clearFailureEscalation()- this.options.onStatus("unavailable", this.lastFailure, info)- return- }- this.reportConnectionProgress()- if (this.failureEscalationTimer) return- this.failureEscalationTimer = setTimeout(() => {- this.failureEscalationTimer = null- if (this.closedByClient || this.connectedOnce || !this.lastFailure) return- this.options.onStatus("unavailable", this.lastFailure, this.connectionInfo())- }, Math.max(0, failureDelay - info.elapsedMs))- }-- private clearFailureEscalation(): void {- if (this.failureEscalationTimer) clearTimeout(this.failureEscalationTimer)- this.failureEscalationTimer = null- }-- 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")- }- this.socket.send(JSON.stringify(event))- }-}diff --git a/tui/src/latex.test.ts b/tui/src/rendering/latex.test.tssimilarity index 100%rename from tui/src/latex.test.tsrename to tui/src/rendering/latex.test.tsdiff --git a/tui/src/latex.ts b/tui/src/rendering/latex.tssimilarity index 100%rename from tui/src/latex.tsrename to tui/src/rendering/latex.tsdiff --git a/tui/src/scrollbox.ts b/tui/src/rendering/scrollbox.tssimilarity index 100%rename from tui/src/scrollbox.tsrename to tui/src/rendering/scrollbox.tsdiff --git a/tui/src/tool-renderers.test.ts b/tui/src/rendering/tool-renderers.test.tssimilarity index 100%rename from tui/src/tool-renderers.test.tsrename to tui/src/rendering/tool-renderers.test.tsdiff --git a/tui/src/tool-renderers.ts b/tui/src/rendering/tool-renderers.tssimilarity index 98%rename from tui/src/tool-renderers.tsrename to tui/src/rendering/tool-renderers.tsindex f5bd9c299..3be8fb8c0 100644--- a/tui/src/tool-renderers.ts+++ b/tui/src/rendering/tool-renderers.ts@@ -1,4 +1,4 @@-import type { ToolProgressEvent } from "./protocol"+import type { ToolProgressEvent } from "../client"export interface ToolRenderOptions {workspace?: stringdiff --git a/tui/src/transcript.ts b/tui/src/rendering/transcript.tssimilarity index 99%rename from tui/src/transcript.tsrename to tui/src/rendering/transcript.tsindex 98ab4c012..bf33ba72a 100644--- a/tui/src/transcript.ts+++ b/tui/src/rendering/transcript.ts@@ -1,4 +1,4 @@-import { acceptsCompactionPhase } from "../../packages/client-events/notifications"+import { acceptsCompactionPhase } from "../../../packages/client-events/notifications"import {BoxRenderable,CodeRenderable,@@ -22,7 +22,7 @@ import type {HistoryMessage,MediaAttachment,ToolProgressEvent,-} from "./protocol"+} from "../client"import { renderLatexAsUnicode } from "./latex"import { hideScrollbars } from "./scrollbox"import { mergeToolEvent, renderToolEvent } from "./tool-renderers"diff --git a/tui/src/context-panel.test.ts b/tui/src/views/context-panel.test.tssimilarity index 95%rename from tui/src/context-panel.test.tsrename to tui/src/views/context-panel.test.tsindex 15c48d15f..965559b1f 100644--- a/tui/src/context-panel.test.ts+++ b/tui/src/views/context-panel.test.ts@@ -2,7 +2,7 @@ import { afterEach, describe, expect, test } from "bun:test"import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"import { ContextPanel } from "./context-panel"-import type { SessionContextSnapshot } from "./protocol"+import type { SessionContextSnapshot } from "../client"const context: SessionContextSnapshot = {totalMessages: 8,diff --git a/tui/src/context-panel.ts b/tui/src/views/context-panel.tssimilarity index 97%rename from tui/src/context-panel.tsrename to tui/src/views/context-panel.tsindex ef949c6ed..32405afe0 100644--- a/tui/src/context-panel.ts+++ b/tui/src/views/context-panel.ts@@ -5,7 +5,7 @@ import {type ColorInput,} from "@opentui/core"-import type { SessionContextSnapshot } from "./protocol"+import type { SessionContextSnapshot } from "../client"export interface ContextPanelTheme {text: ColorInputdiff --git a/tui/src/diff-viewer.test.ts b/tui/src/views/diff-viewer.test.tssimilarity index 100%rename from tui/src/diff-viewer.test.tsrename to tui/src/views/diff-viewer.test.tsdiff --git a/tui/src/diff-viewer.ts b/tui/src/views/diff-viewer.tssimilarity index 98%rename from tui/src/diff-viewer.tsrename to tui/src/views/diff-viewer.tsindex 893d99ccd..3b80342f1 100644--- a/tui/src/diff-viewer.ts+++ b/tui/src/views/diff-viewer.ts@@ -12,8 +12,8 @@ import {type TreeSitterClient,} from "@opentui/core"-import type { FileEditEvent, HistoryMessage } from "./protocol"-import { hideScrollbars } from "./scrollbox"+import type { FileEditEvent, HistoryMessage } from "../client"+import { hideScrollbars } from "../rendering/scrollbox"export interface DiffViewerTheme {text: ColorInputdiff --git a/tui/src/footer-hints.test.ts b/tui/src/views/footer-hints.test.tssimilarity index 100%rename from tui/src/footer-hints.test.tsrename to tui/src/views/footer-hints.test.tsdiff --git a/tui/src/footer-hints.ts b/tui/src/views/footer-hints.tssimilarity index 100%rename from tui/src/footer-hints.tsrename to tui/src/views/footer-hints.tsdiff --git a/tui/src/recovery-notice.ts b/tui/src/views/recovery-notice.tssimilarity index 99%rename from tui/src/recovery-notice.tsrename to tui/src/views/recovery-notice.tsindex c9bc58d88..e8e9b5b0d 100644--- a/tui/src/recovery-notice.ts+++ b/tui/src/views/recovery-notice.ts@@ -10,7 +10,7 @@ import {type TextChunk,} from "@opentui/core"-import type { RecoveryState } from "./protocol"+import type { RecoveryState } from "../client"export interface RecoveryNoticeTheme {text: ColorInputdiff --git a/tui/src/runtime-controls.ts b/tui/src/views/runtime-controls.tssimilarity index 99%rename from tui/src/runtime-controls.tsrename to tui/src/views/runtime-controls.tsindex 516580b4c..80b2f966f 100644--- a/tui/src/runtime-controls.ts+++ b/tui/src/views/runtime-controls.ts@@ -10,8 +10,8 @@ import {fetchRuntimeControls,type ApiReauthenticator,type WorkspaceScopePayload,-} from "./protocol"-import { PickerMenu, type PickerMenuTheme } from "./picker-menu"+} from "../client"+import { PickerMenu, type PickerMenuTheme } from "../menus/picker-menu"interface RuntimeControlsTheme extends PickerMenuTheme {accent: ColorInputdiff --git a/tui/src/usage-panel.test.ts b/tui/src/views/usage-panel.test.tssimilarity index 99%rename from tui/src/usage-panel.test.tsrename to tui/src/views/usage-panel.test.tsindex d7d4d184d..ebdf22b8b 100644--- a/tui/src/usage-panel.test.ts+++ b/tui/src/views/usage-panel.test.ts@@ -3,7 +3,7 @@ import { RGBA, type TextRenderable } from "@opentui/core"import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"import { UsagePanel, type UsagePanelTheme } from "./usage-panel"-import type { SessionUsageSnapshot } from "./protocol"+import type { SessionUsageSnapshot } from "../client"const theme = {text: "#ECEDEE", muted: "#A1A1AA", border: "#3F3F46", accent: "#EF8E30",diff --git a/tui/src/usage-panel.ts b/tui/src/views/usage-panel.tssimilarity index 99%rename from tui/src/usage-panel.tsrename to tui/src/views/usage-panel.tsindex 3e32231a2..6d87e2c36 100644--- a/tui/src/usage-panel.ts+++ b/tui/src/views/usage-panel.ts@@ -10,7 +10,7 @@ import {} from "@opentui/core"import { formatTokenCount } from "./context-panel"-import type { SessionUsageSnapshot } from "./protocol"+import type { SessionUsageSnapshot } from "../client"export interface UsagePanelTheme {text: ColorInput