refactor(tui): organize source by feature boundaries (#5975)

* refactor(tui): group source files by feature

* refactor(tui): split app and gateway responsibilities
This commit is contained in:
chengyongru authored and GitHub committed 2026-09-29 16:57:36 +08:00
1 parent b7abbcd70b
commit f18423800e
73 files changed
+6401 -6006

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
import { expect, test } from "bun:test"
import { branchPoints } from "./branch-menu"
test("branch points preserve absolute user indices from paginated history", () => {
expect(branchPoints([
{ role: "user", content: "question" },
{ role: "assistant", content: " first\nreply ", forkIndex: 11 },
{ role: "activity", content: "read_file" },
{ role: "assistant", content: "second", forkIndex: 12 },
])).toEqual([
{ beforeUserIndex: 11, preview: "first reply" },
{ beforeUserIndex: 12, preview: "second" },
])
})
+40
View File
@@ -0,0 +1,40 @@
import { type BoxRenderable, type CliRenderer } from "@opentui/core"
import { PickerMenu, type PickerMenuTheme } from "./picker-menu"
import type { HistoryMessage } from "../client"
export interface BranchPoint {
beforeUserIndex: number
preview: string
}
export function branchPoints(messages: HistoryMessage[]): BranchPoint[] {
return messages.flatMap((message) => (
message.role === "assistant" && typeof message.forkIndex === "number"
? [{ beforeUserIndex: message.forkIndex, preview: message.content.replace(/\s+/gu, " ").trim() }]
: []
))
}
export class BranchMenu {
readonly root: BoxRenderable
private readonly picker: PickerMenu<BranchPoint>
constructor(renderer: CliRenderer, theme: PickerMenuTheme) {
this.picker = new PickerMenu(renderer, theme, {
id: "nanobot-tui-branch-menu",
searchText: (point) => point.preview,
render: (point) => `After turn ${point.beforeUserIndex} ${point.preview}`,
emptyText: "No completed replies to branch from",
})
this.root = this.picker.root
}
get visible(): boolean { return this.picker.visible }
open(points: BranchPoint[], limit: number): void { this.picker.show(points, "", limit) }
update(query: string, limit: number): void { this.picker.update(query, limit) }
move(direction: -1 | 1): boolean { return this.picker.move(direction) }
choose(): BranchPoint | null { return this.picker.current() }
hide(): void { this.picker.hide() }
setTheme(theme: PickerMenuTheme): void { this.picker.setTheme(theme) }
}
+136
View File
@@ -0,0 +1,136 @@
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 "../client"
const commands: SlashCommand[] = [
{
command: "/help",
title: "Help",
description: "Show available commands",
argHint: "",
lifecycle: "side_channel",
acceptsArgs: false,
},
{
command: "/history",
title: "History",
description: "Show recent messages",
argHint: "[n]",
lifecycle: "side_channel",
acceptsArgs: true,
},
]
describe("CommandMenu", () => {
let setup: TestRendererSetup | undefined
afterEach(() => {
if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()
setup = undefined
})
test("discovers, navigates, and completes backend commands", async () => {
setup = await createTestRenderer({ width: 80, height: 18, screenMode: "alternate-screen" })
const menu = new CommandMenu(setup.renderer, {
text: "#FFFFFF",
muted: "#999999",
border: "#555555",
})
setup.renderer.root.add(menu.root)
menu.setCommands(commands)
menu.update("/h")
await setup.renderOnce()
const frame = setup.captureCharFrame()
expect(frame).toContain("› /help")
expect(frame).toContain("/history [n]")
expect(menu.completion("/h")).toBe("/help")
expect(menu.move(1)).toBe(true)
expect(menu.complete()).toBe("/history ")
expect(menu.visible).toBe(false)
})
test("hides outside the leading command token", async () => {
setup = await createTestRenderer({ width: 60, height: 12, screenMode: "alternate-screen" })
const menu = new CommandMenu(setup.renderer, {
text: "#FFFFFF",
muted: "#999999",
border: "#555555",
})
menu.setCommands(commands)
menu.update("explain /help")
expect(menu.visible).toBe(false)
menu.update("/history 5")
expect(menu.visible).toBe(false)
})
test("keeps gateway commands authoritative over local actions", async () => {
setup = await createTestRenderer({ width: 60, height: 12, screenMode: "alternate-screen" })
const menu = new CommandMenu(setup.renderer, {
text: "#FFFFFF",
muted: "#999999",
border: "#555555",
})
menu.setCommands(commands, [{
command: "/help",
title: "Local help",
description: "Must not replace nanobot help",
action: "sessions",
}, {
command: "/sessions",
title: "Sessions",
description: "Switch conversations",
action: "sessions",
}])
expect(menu.resolve("/help")?.source).toBe("gateway")
expect(menu.resolve("/sessions")).toMatchObject({
source: "tui",
command: { action: "sessions" },
})
})
test("discovers and completes the local exit action", async () => {
setup = await createTestRenderer({ width: 60, height: 12, screenMode: "alternate-screen" })
const menu = new CommandMenu(setup.renderer, {
text: "#FFFFFF",
muted: "#999999",
border: "#555555",
})
setup.renderer.root.add(menu.root)
menu.setCommands([], [{
command: "/exit",
title: "Exit",
description: "Close this terminal UI",
action: "exit",
}])
menu.update("/ex")
await setup.renderOnce()
expect(setup.captureCharFrame()).toContain("/exit")
expect(menu.completion("/ex")).toBe("/exit")
expect(menu.resolve("/exit")).toMatchObject({
source: "tui",
command: { action: "exit" },
})
})
test("resolves argument-sensitive command lifecycles", () => {
const goal: SlashCommand = {
command: "/goal",
title: "Goal",
description: "Start a long-running goal",
argHint: "<goal>",
lifecycle: "agent_turn_with_args",
acceptsArgs: true,
}
expect(resolveSlashCommandLifecycle("/goal", goal)).toBe("side_channel")
expect(resolveSlashCommandLifecycle("/goal ship it", goal)).toBe("agent_turn")
expect(resolveSlashCommandLifecycle("/help extra", commands[0]!)).toBeNull()
})
})
+146
View File
@@ -0,0 +1,146 @@
import { type BoxRenderable, type CliRenderer } from "@opentui/core"
import type { SlashCommand, SlashCommandLifecycle } from "../client"
import { PickerMenu, type PickerMenuTheme } from "./picker-menu"
export type CommandMenuTheme = PickerMenuTheme
type TuiCommandAction =
| "sessions"
| "new-chat"
| "context"
| "usage"
| "diff"
| "branch"
| "detach"
| "exit"
export interface TuiCommand {
command: string
title: string
description: string
action: TuiCommandAction
}
export type CommandChoice =
| { source: "gateway"; command: SlashCommand }
| { source: "tui"; command: TuiCommand }
export type ResolvedSlashCommandLifecycle = Exclude<SlashCommandLifecycle, "agent_turn_with_args">
function descriptor(choice: CommandChoice): SlashCommand | TuiCommand {
return choice.command
}
export function resolveSlashCommandLifecycle(
input: string,
command: SlashCommand,
): ResolvedSlashCommandLifecycle | null {
const name = input.split(/\s+/u, 1)[0] || ""
if (name.toLocaleLowerCase() !== command.command.toLocaleLowerCase()) return null
const args = input.slice(name.length).trim()
if (args && !command.acceptsArgs) return null
if (command.lifecycle === "agent_turn_with_args") {
return args ? "agent_turn" : "side_channel"
}
return command.lifecycle
}
/** Retained slash-command discovery with one small completion interface. */
export class CommandMenu {
readonly root: BoxRenderable
private readonly picker: PickerMenu<CommandChoice>
private commands: CommandChoice[] = []
private query = ""
constructor(
renderer: CliRenderer,
theme: CommandMenuTheme,
) {
this.picker = new PickerMenu(renderer, theme, {
id: "nanobot-tui-command-menu",
searchText: (choice) => {
const command = descriptor(choice)
return `${command.command} ${command.title}`
},
render: (choice) => {
const command = descriptor(choice)
const argHint = "argHint" in command ? command.argHint : ""
const hint = argHint ? ` ${argHint}` : ""
const detail = (command.description || command.title).replace(/\s+/gu, " ")
return `${command.command}${hint} ${detail}`
},
})
this.root = this.picker.root
}
get visible(): boolean {
return this.picker.visible
}
setCommands(commands: SlashCommand[], local: TuiCommand[] = []): void {
const gatewayNames = new Set(commands.map((command) => command.command.toLocaleLowerCase()))
this.commands = [
...commands.map((command): CommandChoice => ({ source: "gateway", command })),
...local
.filter((command) => !gatewayNames.has(command.command.toLocaleLowerCase()))
.map((command): CommandChoice => ({ source: "tui", command })),
].sort((left, right) => descriptor(left).command.localeCompare(descriptor(right).command))
this.update(this.query)
}
resolve(input: string): CommandChoice | null {
const name = input.trim().split(/\s+/u, 1)[0]?.toLocaleLowerCase()
if (!name) return null
return this.commands.find((choice) => {
const command = descriptor(choice)
if (command.command.toLocaleLowerCase() !== name) return false
if (choice.source === "tui") return input.trim().length === command.command.length
return resolveSlashCommandLifecycle(input.trim(), choice.command) !== null
}) || null
}
update(input: string, limit = 6): void {
const changed = input !== this.query
this.query = input
const token = /^\/[^\s]*$/u.test(input) ? input.toLocaleLowerCase() : ""
if (!token) {
this.hide()
return
}
if (changed || !this.picker.visible) this.picker.show(this.commands, token.slice(1), limit)
else this.picker.update(token.slice(1), limit)
}
move(direction: -1 | 1): boolean {
return this.picker.move(direction)
}
completion(input: string): string | null {
if (!this.visible) return null
const choice = this.picker.current()
if (!choice) return null
const command = descriptor(choice)
if (input.trim() === command.command) return null
const acceptsArgs = choice.source === "gateway" && choice.command.acceptsArgs
return `${command.command}${acceptsArgs ? " " : ""}`
}
complete(): string | null {
if (!this.visible) return null
const choice = this.picker.current()
if (!choice) return null
const command = descriptor(choice)
this.hide()
const acceptsArgs = choice.source === "gateway" && choice.command.acceptsArgs
return `${command.command}${acceptsArgs ? " " : ""}`
}
hide(): void {
this.picker.hide()
}
setTheme(theme: CommandMenuTheme): void {
this.picker.setTheme(theme)
}
}
+49
View File
@@ -0,0 +1,49 @@
import { describe, expect, test } from "bun:test"
import { insertMention, mentionOptions, mentionQuery } from "./mention-menu"
import type { MentionCandidate } from "../client"
const candidates: MentionCandidate[] = [
{ kind: "cli", name: "github", displayName: "GitHub", description: "CLI" },
{ kind: "mcp", name: "linear", displayName: "Linear", description: "MCP" },
{
kind: "session",
name: "release-plan",
displayName: "Release plan",
description: "Session",
session: { name: "release-plan", session_key: "websocket:release", title: "Release plan" },
},
]
describe("mention projection", () => {
test("finds and replaces only the mention under the cursor", () => {
const value = "ask @rel about this"
const query = mentionQuery(value, 8)
expect(query).toEqual({ query: "rel", start: 4, end: 8 })
expect(insertMention(value, candidates[2]!, query!).value).toBe("ask @release-plan about this")
})
test("keeps namespaced completion aliases separate from gateway capability ids", () => {
const options = mentionOptions("use @github-2", [{
kind: "mcp",
name: "github-2",
targetName: "github",
displayName: "GitHub MCP",
description: "MCP server",
}])
expect(options.mcpPresets).toEqual([{ name: "github" }])
})
test("maps visible mentions onto the gateway metadata lanes", () => {
expect(mentionOptions("Use @github with @linear and @release-plan", candidates)).toEqual({
cliApps: [{ name: "github" }],
mcpPresets: [{ name: "linear" }],
sessionMentions: [{
name: "release-plan",
session_key: "websocket:release",
title: "Release plan",
}],
})
})
})
+75
View File
@@ -0,0 +1,75 @@
import { type BoxRenderable, type CliRenderer } from "@opentui/core"
import { PickerMenu, type PickerMenuTheme } from "./picker-menu"
import type { MentionCandidate, MessageOptions } from "../client"
export interface MentionQuery {
query: string
start: number
end: number
}
export function mentionQuery(value: string, cursor: number): MentionQuery | null {
const end = Math.min(Math.max(cursor, 0), value.length)
const match = /(?:^|[\s([{])@([\p{L}\p{N}_-]*)$/u.exec(value.slice(0, end))
if (!match) return null
const valueQuery = match[1] ?? ""
const start = end - valueQuery.length - 1
return { query: valueQuery.toLocaleLowerCase(), start, end }
}
export function insertMention(
value: string,
candidate: MentionCandidate,
query: MentionQuery,
): { value: string; cursor: number } {
const suffix = value.slice(query.end)
const tail = /^\s/u.test(suffix) ? "" : " "
const inserted = `@${candidate.name}${tail}`
return {
value: `${value.slice(0, query.start)}${inserted}${suffix}`,
cursor: query.start + inserted.length,
}
}
export function mentionOptions(value: string, candidates: MentionCandidate[]): MessageOptions {
const names = new Set(
[...value.matchAll(/(?:^|[\s([{])@([\p{L}\p{N}_-]+)/gu)]
.flatMap((match) => match[1] ? [match[1].toLocaleLowerCase()] : []),
)
const selected = candidates.filter((candidate) => names.has(candidate.name.toLocaleLowerCase()))
return {
cliApps: selected
.filter((item) => item.kind === "cli")
.map((item) => ({ name: item.targetName || item.name })),
mcpPresets: selected
.filter((item) => item.kind === "mcp")
.map((item) => ({ name: item.targetName || item.name })),
sessionMentions: selected.flatMap((item) => item.session ? [item.session] : []),
}
}
export class MentionMenu {
readonly root: BoxRenderable
private readonly picker: PickerMenu<MentionCandidate>
constructor(renderer: CliRenderer, theme: PickerMenuTheme) {
this.picker = new PickerMenu(renderer, theme, {
id: "nanobot-tui-mention-menu",
searchText: (item) => `${item.name} ${item.displayName} ${item.description}`,
render: (item) => `${item.displayName} @${item.name} · ${item.kind}`,
emptyText: "No matching sessions or tools",
})
this.root = this.picker.root
}
get visible(): boolean { return this.picker.visible }
show(items: MentionCandidate[], query: string, limit: number): void {
this.picker.show(items, query, limit)
}
update(query: string, limit: number): void { this.picker.update(query, limit) }
move(direction: -1 | 1): boolean { return this.picker.move(direction) }
choose(): MentionCandidate | null { return this.picker.current() }
hide(): void { this.picker.hide() }
setTheme(theme: PickerMenuTheme): void { this.picker.setTheme(theme) }
}
+99
View File
@@ -0,0 +1,99 @@
import { afterEach, describe, expect, test } from "bun:test"
import { TextRenderable } from "@opentui/core"
import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"
import { PickerMenu } from "./picker-menu"
interface Choice {
id: string
label: string
}
const theme = {
text: "#FFFFFF",
muted: "#999999",
border: "#555555",
}
function choices(...ids: string[]): Choice[] {
return ids.map((id) => ({ id, label: `Choice ${id}` }))
}
describe("PickerMenu", () => {
let setup: TestRendererSetup | undefined
afterEach(() => {
if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()
setup = undefined
})
test("keeps overflow choices reachable inside a bounded visible window", async () => {
setup = await createTestRenderer({ width: 60, height: 14, screenMode: "alternate-screen" })
let picked = ""
const menu = new PickerMenu<Choice>(setup.renderer, theme, {
id: "test-picker",
key: (choice) => choice.id,
searchText: (choice) => choice.label,
render: (choice) => choice.label,
onSelect: (choice) => { picked = choice.id },
})
setup.renderer.root.add(menu.root)
menu.show(choices("0", "1", "2", "3", "4"), "", 3)
await setup.renderOnce()
expect(menu.root.getChildren().filter((child) => child.id !== "test-picker-overflow")).toHaveLength(3)
expect(setup.captureCharFrame()).toContain("1–3 of 5 ↓")
expect(setup.captureCharFrame()).not.toContain("Choice 3")
menu.move(1)
menu.move(1)
menu.move(1)
await setup.flush()
expect(menu.current()?.id).toBe("3")
expect(setup.captureCharFrame()).toContain("2–4 of 5 ↑↓")
expect(setup.captureCharFrame()).toContain("› Choice 3")
expect(setup.captureCharFrame()).not.toContain("Choice 0")
menu.move(1)
menu.move(1)
expect(menu.current()?.id).toBe("0")
menu.move(-1)
await setup.flush()
expect(menu.current()?.id).toBe("4")
expect(setup.captureCharFrame()).toContain("3–5 of 5 ↑")
const firstVisible = menu.root.getChildren()[0] as TextRenderable | undefined
if (!firstVisible) throw new Error("picker row was not rendered")
await setup.mockMouse.click(firstVisible.x + 2, firstVisible.y)
expect(picked).toBe("2")
expect(menu.current()?.id).toBe("2")
})
test("keeps preserved and filtered selections inside the visible window", async () => {
setup = await createTestRenderer({ width: 60, height: 14, screenMode: "alternate-screen" })
const menu = new PickerMenu<Choice>(setup.renderer, theme, {
id: "test-picker",
key: (choice) => choice.id,
searchText: (choice) => choice.id,
render: (choice) => choice.label,
})
setup.renderer.root.add(menu.root)
menu.show(choices("a", "b", "c", "d", "e"), "", 2)
menu.move(1)
menu.move(1)
menu.move(1)
expect(menu.current()?.id).toBe("d")
menu.replace(choices("e", "d", "a"))
await setup.renderOnce()
expect(menu.current()?.id).toBe("d")
expect(setup.captureCharFrame()).toContain("› Choice d")
expect(setup.captureCharFrame()).toContain("2–3 of 3 ↑")
menu.update("e", 2)
await setup.flush()
expect(menu.current()?.id).toBe("e")
expect(setup.captureCharFrame()).toContain("› Choice e")
expect(menu.root.getChildren()).toHaveLength(1)
})
})
+241
View File
@@ -0,0 +1,241 @@
import {
BoxRenderable,
RGBA,
StyledText,
TextAttributes,
TextRenderable,
parseColor,
type CliRenderer,
type ColorInput,
type TextChunk,
} from "@opentui/core"
export interface PickerMenuTheme {
text: ColorInput
muted: ColorInput
border: ColorInput
accent?: ColorInput
warning?: ColorInput
selectedBackground?: ColorInput
}
interface PickerMenuOptions<T> {
id: string
key?: (item: T) => string
searchText: (item: T) => string
render: (item: T, selected: boolean) => string | TextChunk[]
emptyText?: string
maxWidth?: number
onSelect?: (item: T) => void
}
/** Shared retained picker for command discovery and session navigation. */
export class PickerMenu<T> {
readonly root: BoxRenderable
private items: T[] = []
private matches: T[] = []
private selected = 0
private windowStart = 0
private query = ""
private limit = 6
constructor(
private readonly renderer: CliRenderer,
private theme: PickerMenuTheme,
private readonly options: PickerMenuOptions<T>,
) {
this.root = new BoxRenderable(renderer, {
id: options.id,
width: "100%",
...(options.maxWidth ? { maxWidth: options.maxWidth } : {}),
flexShrink: 0,
flexDirection: "column",
border: true,
borderStyle: "rounded",
borderColor: theme.border,
paddingLeft: 1,
paddingRight: 1,
backgroundColor: RGBA.defaultBackground(),
visible: false,
onMouseDown: (event) => {
if (event.button !== 0) return
event.preventDefault()
event.stopPropagation()
this.renderer.clearSelection()
},
})
}
get visible(): boolean {
return this.root.visible
}
show(items: T[], query = "", limit = 6): void {
this.items = items
this.root.visible = true
this.update(query, limit)
}
replace(items: T[]): void {
if (!this.visible) return
this.items = items
this.update(this.query, this.limit)
}
redraw(): void {
if (this.visible) this.render()
}
update(query: string, limit = this.limit): void {
if (!this.visible) return
const changed = query !== this.query
const previous = this.matches[this.selected]
const previousKey = previous === undefined ? null : this.options.key?.(previous)
this.query = query
this.limit = Math.max(1, limit)
const words = query.trim().toLocaleLowerCase().split(/\s+/u).filter(Boolean)
this.matches = this.items.filter((item) => {
const haystack = this.options.searchText(item).toLocaleLowerCase()
return words.every((word) => haystack.includes(word))
})
if (changed) {
this.selected = 0
this.windowStart = 0
} else {
const preserved = previous === undefined
? -1
: previousKey === null || previousKey === undefined
? this.matches.indexOf(previous)
: this.matches.findIndex((item) => this.options.key?.(item) === previousKey)
this.selected = preserved >= 0
? preserved
: Math.min(this.selected, Math.max(0, this.matches.length - 1))
}
this.keepSelectionVisible()
this.render()
}
move(direction: -1 | 1): boolean {
if (!this.visible || this.matches.length < 2) return false
this.selected = (this.selected + direction + this.matches.length) % this.matches.length
this.keepSelectionVisible()
this.render()
return true
}
current(): T | null {
return this.visible ? this.matches[this.selected] ?? null : null
}
hide(): void {
this.items = []
this.matches = []
this.selected = 0
this.windowStart = 0
this.query = ""
this.root.visible = false
this.clear()
}
setTheme(theme: PickerMenuTheme): void {
this.theme = theme
this.root.borderColor = theme.border
if (this.visible) this.render()
}
private render(): void {
this.clear()
if (this.matches.length === 0) {
this.root.add(new TextRenderable(this.renderer, {
id: `${this.options.id}-empty`,
content: this.options.emptyText || "No matches",
width: "100%",
height: 1,
fg: this.theme.muted,
selectable: false,
}))
return
}
const visibleMatches = this.matches.slice(this.windowStart, this.windowStart + this.limit)
for (const [visibleIndex, item] of visibleMatches.entries()) {
const index = this.windowStart + visibleIndex
const selected = index === this.selected
const rendered = this.options.render(item, selected)
const content = typeof rendered === "string"
? `${selected ? "›" : " "} ${rendered}`
: new StyledText([
chunk(`${selected ? "›" : " "} `, selected ? this.theme.text : this.theme.muted),
...rendered,
])
this.root.add(new TextRenderable(this.renderer, {
id: `${this.options.id}-${index}`,
content,
width: "100%",
height: 1,
wrapMode: "none",
fg: selected ? this.theme.text : this.theme.muted,
selectable: false,
...(selected && this.theme.selectedBackground
? { backgroundColor: parseColor(this.theme.selectedBackground) }
: {}),
attributes: selected ? TextAttributes.BOLD : 0,
onMouseMove: () => {
if (this.selected === index) return
this.selected = index
this.render()
},
onMouseDown: (event) => {
if (event.button !== 0) return
event.preventDefault()
event.stopPropagation()
this.renderer.clearSelection()
this.selected = index
this.options.onSelect?.(item)
},
}))
}
if (visibleMatches.length < this.matches.length) {
const end = this.windowStart + visibleMatches.length
const directions = `${this.windowStart > 0 ? "↑" : ""}${end < this.matches.length ? "↓" : ""}`
this.root.add(new TextRenderable(this.renderer, {
id: `${this.options.id}-overflow`,
content: ` ${this.windowStart + 1}–${end} of ${this.matches.length} ${directions}`,
width: "100%",
height: 1,
wrapMode: "none",
fg: this.theme.muted,
selectable: false,
}))
}
}
private keepSelectionVisible(): void {
if (this.matches.length === 0) {
this.selected = 0
this.windowStart = 0
return
}
const maxStart = Math.max(0, this.matches.length - this.limit)
if (this.selected < this.windowStart) {
this.windowStart = this.selected
} else if (this.selected >= this.windowStart + this.limit) {
this.windowStart = this.selected - this.limit + 1
}
this.windowStart = Math.min(Math.max(0, this.windowStart), maxStart)
}
private clear(): void {
for (const child of [...this.root.getChildren()]) {
this.root.remove(child)
child.destroyRecursively()
}
}
}
function chunk(text: string, color: ColorInput): TextChunk {
return {
__isChunk: true,
text,
fg: parseColor(color),
}
}
+263
View File
@@ -0,0 +1,263 @@
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 "../client"
const sessions: SessionSummary[] = [
{
chatId: "one",
title: "API migration",
preview: "Move authentication to the new client",
createdAt: "2026-08-12T10:00:00Z",
updatedAt: "2026-08-13T10:00:00Z",
runStartedAt: null,
modelPreset: "Codex",
pinned: true,
archived: false,
},
{
chatId: "two",
title: "Release checklist",
preview: "Prepare the stable release",
createdAt: "2026-08-11T10:00:00Z",
updatedAt: "2026-08-12T10:00:00Z",
runStartedAt: null,
modelPreset: null,
recoveryState: {
status: "awaiting_user",
recovery_id: "recovery-two",
reason: "tool execution interrupted",
},
pinned: false,
archived: false,
},
]
describe("SessionMenu", () => {
let setup: TestRendererSetup | undefined
afterEach(() => {
if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()
setup = undefined
})
test("marks, filters, and chooses gateway sessions", async () => {
setup = await createTestRenderer({ width: 80, height: 18, screenMode: "alternate-screen" })
const menu = new SessionMenu(setup.renderer, {
text: "#FFFFFF",
muted: "#999999",
border: "#555555",
accent: "#FF8A33",
warning: "#F5C451",
})
setup.renderer.root.add(menu.root)
menu.open(sessions, "one", 6, "Codex")
await setup.renderOnce()
expect(setup.captureCharFrame()).toContain("› ● API migration")
expect(setup.captureCharFrame()).not.toContain("Move authentication")
expect(setup.captureCharFrame()).not.toContain("Codex")
expect(menu.choose()?.chatId).toBe("one")
menu.update("release stable", 6)
await setup.renderOnce()
expect(setup.captureCharFrame()).toContain("⚠ Release checklist")
expect(menu.choose()?.chatId).toBe("two")
})
test("keeps generated multi-line titles on one terminal row", () => {
expect(sessionLabel({ ...sessions[0]!, title: "Release\n checklist" })).toBe(
"Release checklist",
)
})
test("animates running sessions and marks completed background sessions unread", async () => {
setup = await createTestRenderer({ width: 80, height: 18, screenMode: "alternate-screen" })
const menu = new SessionMenu(setup.renderer, {
text: "#FFFFFF",
muted: "#999999",
border: "#555555",
accent: "#FF8A33",
warning: "#F5C451",
})
setup.renderer.root.add(menu.root)
const running = {
...sessions[0]!,
chatId: "running",
title: "Background task",
runStartedAt: Date.now(),
pinned: false,
}
menu.open([sessions[0]!, running], "one", 6)
await setup.renderOnce()
expect(setup.captureCharFrame()).toMatch(/[⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏] Background task/u)
menu.replace([{ ...sessions[0]! }, { ...running, runStartedAt: null }], "one")
await setup.renderOnce()
expect(setup.captureCharFrame()).toContain("• Background task")
menu.markRead("running")
menu.replace([{ ...sessions[0]! }, { ...running, runStartedAt: null }], "running")
await setup.renderOnce()
expect(setup.captureCharFrame()).toContain("● Background task")
menu.hide()
})
test("prioritizes actionable sessions without moving keyboard selection on refresh", async () => {
setup = await createTestRenderer({ width: 80, height: 18, screenMode: "alternate-screen" })
const menu = new SessionMenu(setup.renderer, {
text: "#FFFFFF",
muted: "#999999",
border: "#555555",
accent: "#FF8A33",
warning: "#F5C451",
})
setup.renderer.root.add(menu.root)
const running = {
...sessions[0]!,
chatId: "running",
title: "Background task",
runStartedAt: Date.now(),
pinned: false,
}
const idle = { ...sessions[1]!, recoveryState: null }
menu.open([sessions[0]!, running, idle], "one", 6)
expect(menu.choose()?.chatId).toBe("one")
expect(menu.move(1)).toBe(true)
expect(menu.choose()?.chatId).toBe("running")
menu.replace([sessions[0]!, running, sessions[1]!], "one")
await setup.renderOnce()
expect(menu.choose()?.chatId).toBe("running")
const frame = setup.captureCharFrame()
expect(frame.indexOf("Release checklist")).toBeLessThan(frame.indexOf("Background task"))
menu.hide()
})
test("keeps keyboard selection when the pointer stays over the previous row", async () => {
setup = await createTestRenderer({ width: 80, height: 18, screenMode: "alternate-screen" })
const menu = new SessionMenu(setup.renderer, {
text: "#FFFFFF",
muted: "#999999",
border: "#555555",
accent: "#FF8A33",
warning: "#F5C451",
})
setup.renderer.root.add(menu.root)
menu.open(sessions, "one", 6)
await setup.renderOnce()
const firstRow = menu.root.getChildren()[0]
const secondRow = menu.root.getChildren()[1]
if (!firstRow || !secondRow) throw new Error("session rows were not rendered")
const firstPosition = { x: firstRow.x + 2, y: firstRow.y }
await setup.mockMouse.moveTo(secondRow.x + 2, secondRow.y)
await setup.flush()
expect(menu.choose()?.chatId).toBe("two")
await setup.mockMouse.moveTo(firstPosition.x, firstPosition.y)
await setup.flush()
expect(menu.choose()?.chatId).toBe("one")
expect(menu.move(1)).toBe(true)
await setup.flush()
expect(menu.choose()?.chatId).toBe("two")
})
test("shows compact workspace names only when they distinguish sessions", async () => {
setup = await createTestRenderer({ width: 100, height: 18, screenMode: "alternate-screen" })
const menu = new SessionMenu(setup.renderer, {
text: "#FFFFFF",
muted: "#999999",
border: "#555555",
accent: "#FF8A33",
warning: "#F5C451",
})
setup.renderer.root.add(menu.root)
const scoped = sessions.map((session) => ({
...session,
workspaceScope: {
project_path: "/work/nanobot",
project_name: "nanobot",
access_mode: "restricted" as const,
},
}))
menu.open(scoped, "one", 6)
await setup.renderOnce()
expect(setup.captureCharFrame()).not.toContain("nanobot · Codex")
menu.open([
scoped[0]!,
{
...scoped[1]!,
workspaceScope: {
project_path: "C:\\work\\desktop",
project_name: "desktop",
access_mode: "restricted",
},
},
], "one", 6)
await setup.renderOnce()
const frame = setup.captureCharFrame()
expect(frame).toContain("nanobot · Codex")
expect(frame).toContain("desktop")
menu.update("desktop", 6)
expect(menu.choose()?.chatId).toBe("two")
menu.open([
{
...scoped[0]!,
workspaceScope: {
project_path: "/work/frontend/nanobot",
project_name: "nanobot",
access_mode: "restricted",
},
},
{
...scoped[1]!,
workspaceScope: {
project_path: "/work/backend/nanobot",
project_name: "nanobot",
access_mode: "restricted",
},
},
], "one", 6)
await setup.renderOnce()
const duplicates = setup.captureCharFrame()
expect(duplicates).toContain("frontend/nanobot")
expect(duplicates).toContain("backend/nanobot")
})
test("shows only model overrides and keeps previews searchable", async () => {
setup = await createTestRenderer({ width: 80, height: 18, screenMode: "alternate-screen" })
const menu = new SessionMenu(setup.renderer, {
text: "#FFFFFF",
muted: "#999999",
border: "#555555",
accent: "#FF8A33",
warning: "#F5C451",
})
setup.renderer.root.add(menu.root)
menu.open(sessions, "one", 6, "Codex")
await setup.renderOnce()
const frame = setup.captureCharFrame()
expect(frame).not.toContain("Codex")
expect(frame).not.toContain("Prepare the stable release")
menu.update("prepare stable", 6)
await setup.renderOnce()
expect(menu.choose()?.chatId).toBe("two")
menu.replace([{ ...sessions[1]!, modelPreset: "Deep Research" }], "one", "Codex")
await setup.renderOnce()
expect(setup.captureCharFrame()).toContain("Deep Research")
menu.hide()
})
})
+289
View File
@@ -0,0 +1,289 @@
import { parseColor, type ColorInput, type BoxRenderable, type CliRenderer, type TextChunk } from "@opentui/core"
import { PickerMenu, type PickerMenuTheme } from "./picker-menu"
import type { SessionSummary } from "../client"
type SessionMenuRow = SessionSummary & { active: boolean; unread: boolean }
const SPINNER_FRAMES = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"]
export function sessionLabel(session: SessionSummary): string {
const label = session.title.trim() || session.preview.trim() || "Untitled chat"
return label.replace(/\s+/gu, " ")
}
function updatedLabel(value: string | null): string {
if (!value) return ""
const date = new Date(value)
if (Number.isNaN(date.valueOf())) return ""
const age = Math.max(0, Date.now() - date.valueOf())
if (age < 60_000) return "now"
if (age < 3_600_000) return `${Math.floor(age / 60_000)}m`
if (age < 86_400_000) return `${Math.floor(age / 3_600_000)}h`
return `${Math.floor(age / 86_400_000)}d`
}
/** Searchable session navigation over the gateway-owned session list. */
export class SessionMenu {
readonly root: BoxRenderable
private readonly picker: PickerMenu<SessionMenuRow>
private readonly workspaceLabels = new Map<string, string>()
private showWorkspaces = false
private spinnerFrame = 0
private spinnerTimer: ReturnType<typeof setInterval> | null = null
private rows: SessionMenuRow[] = []
private defaultModelPreset = ""
private readonly snapshots = new Map<string, {
preview: string
runStartedAt: number | null
}>()
private readonly unreadChatIds = new Set<string>()
constructor(
renderer: CliRenderer,
private theme: PickerMenuTheme,
onSelect?: (session: SessionSummary) => void,
) {
this.picker = new PickerMenu<SessionMenuRow>(renderer, theme, {
id: "nanobot-tui-session-menu",
key: (session) => session.chatId,
searchText: (session) => [
sessionLabel(session),
session.modelPreset || "",
session.preview,
session.chatId,
session.workspaceScope?.project_name || "",
session.workspaceScope?.project_path || "",
session.recoveryState?.status || "",
session.recoveryState?.reason || "",
].join(" "),
render: (session, selected) => {
const age = updatedLabel(session.updatedAt)
const detail = [
this.showWorkspaces ? this.workspaceLabel(session) : "",
this.modelOverride(session),
]
.filter(Boolean)
.join(" · ")
const marker = this.marker(session)
const foreground = this.interrupted(session)
? this.theme.warning || this.theme.accent || this.theme.text
: selected ? this.theme.text : this.theme.muted
return [
...(marker ? [chunk(`${marker.text} `, marker.color)] : []),
chunk(sessionLabel(session), foreground),
...(detail ? [chunk(` ${detail}`, this.theme.muted)] : []),
...(age ? [chunk(` ${age}`, this.theme.muted)] : []),
]
},
emptyText: "No matching sessions",
onSelect,
})
this.root = this.picker.root
}
get visible(): boolean {
return this.picker.visible
}
open(
sessions: SessionSummary[],
currentChatId: string,
limit: number,
defaultModelPreset = "",
): void {
this.defaultModelPreset = defaultModelPreset
this.observe(sessions, currentChatId)
this.rows = this.prepareRows(sessions, currentChatId)
this.picker.show(this.rows, "", limit)
this.syncSpinner()
}
replace(
sessions: SessionSummary[],
currentChatId: string,
defaultModelPreset = this.defaultModelPreset,
): void {
this.defaultModelPreset = defaultModelPreset
this.observe(sessions, currentChatId)
this.rows = this.prepareRows(sessions, currentChatId)
this.picker.replace(this.rows)
this.syncSpinner()
}
markRead(chatId: string): void {
this.unreadChatIds.delete(chatId)
}
private prepareRows(sessions: SessionSummary[], currentChatId: string): SessionMenuRow[] {
this.prepareWorkspaceLabels(sessions)
return sessions
.map((session) => ({
...session,
active: session.chatId === currentChatId,
unread: this.unreadChatIds.has(session.chatId),
}))
.sort((left, right) => {
return Number(right.active) - Number(left.active)
|| sessionPriority(right) - sessionPriority(left)
|| Number(right.pinned) - Number(left.pinned)
|| Number(left.archived) - Number(right.archived)
|| timestamp(right.updatedAt) - timestamp(left.updatedAt)
|| sessionLabel(left).localeCompare(sessionLabel(right))
})
}
update(query: string, limit: number): void {
this.picker.update(query, limit)
}
move(direction: -1 | 1): boolean {
return this.picker.move(direction)
}
choose(): SessionSummary | null {
return this.picker.current()
}
hide(): void {
this.stopSpinner()
this.rows = []
this.picker.hide()
}
setTheme(theme: PickerMenuTheme): void {
this.theme = theme
this.picker.setTheme(theme)
}
private marker(session: SessionMenuRow): { text: string; color: ColorInput } | null {
if (this.interrupted(session)) {
return {
text: "⚠",
color: this.theme.warning || this.theme.accent || this.theme.text,
}
}
if (session.runStartedAt !== null) {
return {
text: SPINNER_FRAMES[this.spinnerFrame % SPINNER_FRAMES.length] || SPINNER_FRAMES[0]!,
color: this.theme.accent || this.theme.text,
}
}
if (session.active) return { text: "●", color: this.theme.text }
if (session.unread) return { text: "•", color: this.theme.accent || this.theme.text }
if (session.pinned) return { text: "◆", color: this.theme.muted }
if (session.archived) return { text: "◇", color: this.theme.muted }
return null
}
private interrupted(session: SessionMenuRow): boolean {
return session.recoveryState?.status === "awaiting_user"
|| session.recoveryState?.status === "failed"
}
private observe(sessions: SessionSummary[], currentChatId: string): void {
const present = new Set<string>()
for (const session of sessions) {
present.add(session.chatId)
const previous = this.snapshots.get(session.chatId)
const active = session.chatId === currentChatId
const completed = previous !== undefined
&& previous.runStartedAt !== null
&& session.runStartedAt === null
const receivedContent = previous !== undefined && previous.preview !== session.preview
if (active) this.unreadChatIds.delete(session.chatId)
else if (completed || receivedContent) this.unreadChatIds.add(session.chatId)
this.snapshots.set(session.chatId, {
preview: session.preview,
runStartedAt: session.runStartedAt,
})
}
for (const chatId of this.snapshots.keys()) {
if (present.has(chatId)) continue
this.snapshots.delete(chatId)
this.unreadChatIds.delete(chatId)
}
}
private syncSpinner(): void {
if (!this.visible || !this.rows.some((session) => session.runStartedAt !== null)) {
this.stopSpinner()
return
}
if (this.spinnerTimer) return
this.spinnerTimer = setInterval(() => {
this.spinnerFrame = (this.spinnerFrame + 1) % SPINNER_FRAMES.length
this.picker.redraw()
}, 90)
;(this.spinnerTimer as unknown as { unref?: () => void }).unref?.()
}
private stopSpinner(): void {
if (this.spinnerTimer) clearInterval(this.spinnerTimer)
this.spinnerTimer = null
this.spinnerFrame = 0
}
private prepareWorkspaceLabels(sessions: SessionSummary[]): void {
this.workspaceLabels.clear()
const scopes = sessions.flatMap((session) => {
const path = normalizeWorkspacePath(session.workspaceScope?.project_path)
return path ? [{ path, name: session.workspaceScope?.project_name?.trim() || pathName(path) }] : []
})
const paths = new Set(scopes.map(({ path }) => path))
this.showWorkspaces = paths.size > 1
if (!this.showWorkspaces) return
const namePaths = new Map<string, Set<string>>()
for (const { path, name } of scopes) {
const pathsForName = namePaths.get(name) || new Set<string>()
pathsForName.add(path)
namePaths.set(name, pathsForName)
}
for (const { path, name } of scopes) {
this.workspaceLabels.set(path, namePaths.get(name)?.size === 1 ? name : shortPath(path))
}
}
private workspaceLabel(session: SessionSummary): string {
return this.workspaceLabels.get(normalizeWorkspacePath(session.workspaceScope?.project_path)) || ""
}
private modelOverride(session: SessionSummary): string {
const preset = session.modelPreset?.trim() || ""
return preset && preset !== this.defaultModelPreset ? preset : ""
}
}
function chunk(text: string, color: ColorInput): TextChunk {
return {
__isChunk: true,
text,
fg: parseColor(color),
}
}
function normalizeWorkspacePath(value: string | undefined): string {
return (value || "").trim().replace(/\\/gu, "/").replace(/\/+$/u, "")
}
function pathName(path: string): string {
return path.split("/").filter(Boolean).at(-1) || path
}
function shortPath(path: string): string {
const parts = path.split("/").filter(Boolean)
return parts.slice(-2).join("/") || path
}
function sessionPriority(session: SessionMenuRow): number {
if (session.recoveryState?.status === "awaiting_user"
|| session.recoveryState?.status === "failed") return 3
if (session.runStartedAt !== null) return 2
return session.unread ? 1 : 0
}
function timestamp(value: string | null): number {
if (!value) return 0
const parsed = Date.parse(value)
return Number.isNaN(parsed) ? 0 : parsed
}
+72
View File
@@ -0,0 +1,72 @@
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 "../client"
const skills: SkillCandidate[] = [
{ name: "simplify", description: "Simplify code", source: "workspace" },
{ name: "verify", description: "Verify public behavior", source: "builtin" },
]
describe("skill completion", () => {
let setup: TestRendererSetup | undefined
afterEach(() => {
if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()
setup = undefined
})
test("finds and replaces only the skill reference under the cursor", () => {
const value = "use $ver before release"
const query = skillQuery(value, 8)
expect(query).toEqual({ query: "ver", start: 4, end: 8 })
expect(insertSkill(value, skills[1]!, query!)).toEqual({
value: "use $verify before release",
cursor: 11,
})
})
test("matches backend token boundaries and replaces a whole token", () => {
expect(skillQuery("$", 1)).toEqual({ query: "", start: 0, end: 1 })
expect(skillQuery("run ($SIM", 9)).toEqual({ query: "sim", start: 5, end: 9 })
expect(skillQuery("price$ver", 9)).toBeNull()
expect(skillQuery("文$ver", 5)).toBeNull()
expect(skillQuery("$verify done", 12)).toBeNull()
const midToken = skillQuery("use $verify before release", 8)
expect(midToken).toEqual({ query: "ver", start: 4, end: 11 })
expect(insertSkill("use $verify before release", skills[1]!, midToken!).value)
.toBe("use $verify before release")
})
test("filters, navigates, and chooses available skills", async () => {
setup = await createTestRenderer({ width: 72, height: 16, screenMode: "alternate-screen" })
const menu = new SkillMenu(setup.renderer, {
text: "#FFFFFF",
muted: "#999999",
border: "#555555",
})
setup.renderer.root.add(menu.root)
menu.show(skills, "", 6)
await setup.renderOnce()
expect(setup.captureCharFrame()).toContain("› $simplify")
expect(setup.captureCharFrame()).toContain("$verify")
expect(menu.move(1)).toBe(true)
expect(menu.choose()).toEqual(skills[1]!)
menu.update("simp", 6)
expect(menu.choose()).toEqual(skills[0]!)
menu.show([
{ name: "alpha", description: "Verify workflow", source: "workspace" },
skills[1]!,
], "verify", 6)
expect(menu.choose()).toEqual(skills[1]!)
menu.show([skills[0]!], "verify", 6)
expect(menu.choose()).toBeNull()
})
})
+86
View File
@@ -0,0 +1,86 @@
import { type BoxRenderable, type CliRenderer } from "@opentui/core"
import { PickerMenu, type PickerMenuTheme } from "./picker-menu"
import type { SkillCandidate } from "../client"
export interface SkillQuery {
query: string
start: number
end: number
}
export function skillQuery(value: string, cursor: number): SkillQuery | null {
const cursorAt = Math.min(Math.max(cursor, 0), value.length)
const match = /(?:^|[^\p{L}\p{N}\p{M}\p{Pc}$])\$([A-Za-z0-9_-]*)$/u.exec(
value.slice(0, cursorAt),
)
if (!match) return null
const valueQuery = match[1] ?? ""
const start = cursorAt - valueQuery.length - 1
const remainder = /^[A-Za-z0-9_-]*/u.exec(value.slice(cursorAt))?.[0] || ""
return {
query: valueQuery.toLocaleLowerCase(),
start,
end: cursorAt + remainder.length,
}
}
export function insertSkill(
value: string,
candidate: SkillCandidate,
query: SkillQuery,
): { value: string; cursor: number } {
const suffix = value.slice(query.end)
const tail = /^\s/u.test(suffix) ? "" : " "
const inserted = `$${candidate.name}${tail}`
return {
value: `${value.slice(0, query.start)}${inserted}${suffix}`,
cursor: query.start + inserted.length,
}
}
export class SkillMenu {
readonly root: BoxRenderable
private readonly picker: PickerMenu<SkillCandidate>
private items: SkillCandidate[] = []
constructor(renderer: CliRenderer, theme: PickerMenuTheme) {
this.picker = new PickerMenu(renderer, theme, {
id: "nanobot-tui-skill-menu",
key: (item) => item.name,
searchText: (item) => `${item.name} ${item.description}`,
render: (item) => `$${item.name} ${item.description.replace(/\s+/gu, " ")}`,
emptyText: "No matching skills",
})
this.root = this.picker.root
}
get visible(): boolean { return this.picker.visible }
show(items: SkillCandidate[], query: string, limit: number): void {
this.items = items
this.picker.show(this.ranked(query), query, limit)
}
update(query: string, limit: number): void {
this.picker.show(this.ranked(query), query, limit)
}
move(direction: -1 | 1): boolean { return this.picker.move(direction) }
choose(): SkillCandidate | null { return this.picker.current() }
hide(): void { this.picker.hide() }
setTheme(theme: PickerMenuTheme): void { this.picker.setTheme(theme) }
private ranked(query: string): SkillCandidate[] {
const needle = query.toLocaleLowerCase()
if (!needle) return this.items
const score = (item: SkillCandidate): number => {
const name = item.name.toLocaleLowerCase()
if (name === needle) return 0
if (name.startsWith(needle)) return 1
if (name.includes(needle)) return 2
return 3
}
return this.items
.map((item, index) => ({ item, index, score: score(item) }))
.sort((left, right) => left.score - right.score || left.index - right.index)
.map(({ item }) => item)
}
}