refactor(tui): organize source by feature boundaries (#5975)
* refactor(tui): group source files by feature * refactor(tui): split app and gateway responsibilities
This commit is contained in:
1 parent
b7abbcd70b
commit
f18423800e
73 files changed
+6401
-6006
No files matched your search
@@ -0,0 +1,43 @@
|
||||
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 "../client"
|
||||
|
||||
const context: SessionContextSnapshot = {
|
||||
totalMessages: 8,
|
||||
archivedMessages: 0,
|
||||
replayMessages: 8,
|
||||
estimatedReplayTokens: 950,
|
||||
estimatedSummaryTokens: 0,
|
||||
estimatedSessionTokens: 950,
|
||||
archivedSummary: null,
|
||||
archivedSummaryAt: null,
|
||||
lastUsage: null,
|
||||
}
|
||||
|
||||
describe("ContextPanel", () => {
|
||||
let setup: TestRendererSetup | undefined
|
||||
|
||||
afterEach(() => {
|
||||
if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()
|
||||
setup = undefined
|
||||
})
|
||||
|
||||
test("omits explanatory copy when no compacted summary exists", async () => {
|
||||
setup = await createTestRenderer({ width: 80, height: 18, screenMode: "alternate-screen" })
|
||||
const panel = new ContextPanel(setup.renderer, {
|
||||
text: "#FFFFFF",
|
||||
border: "#555555",
|
||||
accent: "#EF8E30",
|
||||
})
|
||||
setup.renderer.root.add(panel.root)
|
||||
panel.show(context)
|
||||
await setup.renderOnce()
|
||||
|
||||
const frame = setup.captureCharFrame()
|
||||
expect(frame).toContain("~950 tokens · 8 replay · 0 archived")
|
||||
expect(frame).not.toContain("Agent context")
|
||||
expect(frame).not.toContain("no compacted summary")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,88 @@
|
||||
import {
|
||||
BoxRenderable,
|
||||
TextRenderable,
|
||||
type CliRenderer,
|
||||
type ColorInput,
|
||||
} from "@opentui/core"
|
||||
|
||||
import type { SessionContextSnapshot } from "../client"
|
||||
|
||||
export interface ContextPanelTheme {
|
||||
text: ColorInput
|
||||
border: ColorInput
|
||||
accent: ColorInput
|
||||
}
|
||||
|
||||
export function formatTokenCount(value: number): string {
|
||||
if (value < 1_000) return String(value)
|
||||
const compact = value >= 10_000 ? Math.round(value / 1_000) : Math.round(value / 100) / 10
|
||||
return `${compact}k`
|
||||
}
|
||||
|
||||
/** Read-only explanation of the session-owned context replayed to the agent. */
|
||||
export class ContextPanel {
|
||||
readonly root: BoxRenderable
|
||||
private readonly stats: TextRenderable
|
||||
private readonly summary: TextRenderable
|
||||
|
||||
constructor(renderer: CliRenderer, theme: ContextPanelTheme) {
|
||||
this.root = new BoxRenderable(renderer, {
|
||||
id: "nanobot-tui-context-panel",
|
||||
width: "100%",
|
||||
maxHeight: 9,
|
||||
flexShrink: 0,
|
||||
flexDirection: "column",
|
||||
border: true,
|
||||
borderStyle: "rounded",
|
||||
borderColor: theme.border,
|
||||
paddingLeft: 1,
|
||||
paddingRight: 1,
|
||||
visible: false,
|
||||
})
|
||||
this.stats = new TextRenderable(renderer, {
|
||||
id: "nanobot-tui-context-stats",
|
||||
content: "",
|
||||
width: "100%",
|
||||
fg: theme.accent,
|
||||
wrapMode: "word",
|
||||
})
|
||||
this.summary = new TextRenderable(renderer, {
|
||||
id: "nanobot-tui-context-summary",
|
||||
content: "",
|
||||
width: "100%",
|
||||
maxHeight: 6,
|
||||
fg: theme.text,
|
||||
wrapMode: "word",
|
||||
})
|
||||
this.root.add(this.stats)
|
||||
this.root.add(this.summary)
|
||||
}
|
||||
|
||||
get visible(): boolean {
|
||||
return this.root.visible
|
||||
}
|
||||
|
||||
show(context: SessionContextSnapshot): void {
|
||||
this.stats.content = `~${formatTokenCount(context.estimatedSessionTokens)} tokens · ${context.replayMessages} replay · ${context.archivedMessages} archived`
|
||||
this.summary.content = context.archivedSummary ?? ""
|
||||
this.root.visible = true
|
||||
}
|
||||
|
||||
hide(): void {
|
||||
this.root.visible = false
|
||||
}
|
||||
|
||||
resize(terminalHeight: number): void {
|
||||
const compact = terminalHeight < 14
|
||||
const medium = terminalHeight < 20
|
||||
this.summary.visible = !compact
|
||||
this.summary.maxHeight = medium ? 2 : 6
|
||||
this.root.maxHeight = compact ? 3 : medium ? 5 : 9
|
||||
}
|
||||
|
||||
setTheme(theme: ContextPanelTheme): void {
|
||||
this.root.borderColor = theme.border
|
||||
this.stats.fg = theme.accent
|
||||
this.summary.fg = theme.text
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
|
||||
import { latestTurnFileEdits, mergeFileEdits } from "./diff-viewer"
|
||||
|
||||
describe("DiffViewer projection", () => {
|
||||
test("merges lifecycle frames without losing the final unified patch", () => {
|
||||
const edits = mergeFileEdits(
|
||||
[{ call_id: "edit-1", tool: "edit_file", path: "src/app.ts", status: "editing" }],
|
||||
[{
|
||||
call_id: "edit-1",
|
||||
tool: "edit_file",
|
||||
path: "src/app.ts",
|
||||
status: "done",
|
||||
added: 2,
|
||||
deleted: 1,
|
||||
diff: { format: "unified", text: "--- a/src/app.ts\n+++ b/src/app.ts" },
|
||||
}],
|
||||
)
|
||||
|
||||
expect(edits).toHaveLength(1)
|
||||
expect(edits[0]?.status).toBe("done")
|
||||
expect(edits[0]?.diff?.text).toContain("+++ b/src/app.ts")
|
||||
})
|
||||
|
||||
test("uses only the newest user turn instead of leaking an older diff", () => {
|
||||
const oldEdit = {
|
||||
call_id: "old",
|
||||
tool: "edit_file",
|
||||
path: "old.ts",
|
||||
status: "done",
|
||||
diff: { format: "unified", text: "old" },
|
||||
}
|
||||
expect(latestTurnFileEdits([
|
||||
{ role: "user", content: "edit the old file" },
|
||||
{ role: "activity", content: "", fileEdits: [oldEdit] },
|
||||
{ role: "assistant", content: "done" },
|
||||
{ role: "user", content: "just explain it" },
|
||||
{ role: "assistant", content: "explained" },
|
||||
])).toEqual([])
|
||||
|
||||
expect(latestTurnFileEdits([
|
||||
{ role: "user", content: "edit the old file" },
|
||||
{ role: "activity", content: "", fileEdits: [oldEdit] },
|
||||
{ role: "assistant", content: "done" },
|
||||
])).toEqual([oldEdit])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,326 @@
|
||||
import {
|
||||
BoxRenderable,
|
||||
DiffRenderable,
|
||||
RGBA,
|
||||
ScrollBoxRenderable,
|
||||
SyntaxStyle,
|
||||
TextAttributes,
|
||||
TextRenderable,
|
||||
type CliRenderer,
|
||||
type ColorInput,
|
||||
type KeyEvent,
|
||||
type TreeSitterClient,
|
||||
} from "@opentui/core"
|
||||
|
||||
import type { FileEditEvent, HistoryMessage } from "../client"
|
||||
import { hideScrollbars } from "../rendering/scrollbox"
|
||||
|
||||
export interface DiffViewerTheme {
|
||||
text: ColorInput
|
||||
muted: ColorInput
|
||||
border: ColorInput
|
||||
accent: ColorInput
|
||||
success: ColorInput
|
||||
error: ColorInput
|
||||
addedBackground: ColorInput | null
|
||||
removedBackground: ColorInput | null
|
||||
syntax: SyntaxStyle
|
||||
}
|
||||
|
||||
interface DiffItem {
|
||||
key: string
|
||||
edit: FileEditEvent
|
||||
}
|
||||
|
||||
function editKey(edit: FileEditEvent): string {
|
||||
return [edit.call_id, edit.tool, edit.path].filter(Boolean).join("|") || "unknown"
|
||||
}
|
||||
|
||||
/** Merge start/end frames without discarding the final patch payload. */
|
||||
export function mergeFileEdits(
|
||||
previous: FileEditEvent[],
|
||||
incoming: FileEditEvent[],
|
||||
): FileEditEvent[] {
|
||||
const edits = new Map(previous.map((edit) => [editKey(edit), edit]))
|
||||
for (const edit of incoming) {
|
||||
const key = editKey(edit)
|
||||
edits.set(key, { ...edits.get(key), ...edit })
|
||||
}
|
||||
return [...edits.values()]
|
||||
}
|
||||
|
||||
/** File edits from the newest user turn only; never leak an older turn into /diff. */
|
||||
export function latestTurnFileEdits(messages: HistoryMessage[]): FileEditEvent[] {
|
||||
let edits: FileEditEvent[] = []
|
||||
for (let index = messages.length - 1; index >= 0; index -= 1) {
|
||||
const message = messages[index]
|
||||
if (!message) continue
|
||||
if (message.role === "user") break
|
||||
if (message.fileEdits?.length) edits = mergeFileEdits(edits, message.fileEdits)
|
||||
}
|
||||
return edits
|
||||
}
|
||||
|
||||
function filetype(path: string): string | undefined {
|
||||
const extension = path.split(".").at(-1)?.toLocaleLowerCase()
|
||||
return ({
|
||||
c: "c",
|
||||
cc: "cpp",
|
||||
cpp: "cpp",
|
||||
css: "css",
|
||||
go: "go",
|
||||
html: "html",
|
||||
java: "java",
|
||||
js: "javascript",
|
||||
json: "json",
|
||||
jsx: "javascript",
|
||||
md: "markdown",
|
||||
py: "python",
|
||||
rb: "ruby",
|
||||
rs: "rust",
|
||||
sh: "bash",
|
||||
sql: "sql",
|
||||
toml: "toml",
|
||||
ts: "typescript",
|
||||
tsx: "typescript",
|
||||
yaml: "yaml",
|
||||
yml: "yaml",
|
||||
} as Record<string, string | undefined>)[extension || ""]
|
||||
}
|
||||
|
||||
function stat(edit: FileEditEvent): string {
|
||||
const added = Math.max(0, edit.added || 0)
|
||||
const deleted = Math.max(0, edit.deleted || 0)
|
||||
return `+${added} -${deleted}`
|
||||
}
|
||||
|
||||
/** Full-screen, read-only projection of file-edit events owned by the session. */
|
||||
export class DiffViewer {
|
||||
readonly root: BoxRenderable
|
||||
private readonly header: TextRenderable
|
||||
private readonly fileHeader: TextRenderable
|
||||
private readonly scroll: ScrollBoxRenderable
|
||||
private readonly footer: TextRenderable
|
||||
private items: DiffItem[] = []
|
||||
private selected = 0
|
||||
|
||||
constructor(
|
||||
private readonly renderer: CliRenderer,
|
||||
private theme: DiffViewerTheme,
|
||||
private readonly treeSitterClient: TreeSitterClient,
|
||||
) {
|
||||
this.root = new BoxRenderable(renderer, {
|
||||
id: "nanobot-tui-diff-viewer",
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
zIndex: 100,
|
||||
flexDirection: "column",
|
||||
padding: 1,
|
||||
backgroundColor: RGBA.defaultBackground(),
|
||||
visible: false,
|
||||
})
|
||||
this.header = new TextRenderable(renderer, {
|
||||
id: "nanobot-tui-diff-header",
|
||||
content: "Diff · Last turn",
|
||||
width: "100%",
|
||||
height: 1,
|
||||
flexShrink: 0,
|
||||
fg: theme.text,
|
||||
attributes: TextAttributes.BOLD,
|
||||
})
|
||||
this.fileHeader = new TextRenderable(renderer, {
|
||||
id: "nanobot-tui-diff-file",
|
||||
content: "",
|
||||
width: "100%",
|
||||
minHeight: 1,
|
||||
maxHeight: 2,
|
||||
flexShrink: 0,
|
||||
fg: theme.muted,
|
||||
wrapMode: "word",
|
||||
})
|
||||
this.scroll = new ScrollBoxRenderable(renderer, {
|
||||
id: "nanobot-tui-diff-scroll",
|
||||
width: "100%",
|
||||
minHeight: 0,
|
||||
flexGrow: 1,
|
||||
scrollX: false,
|
||||
scrollY: true,
|
||||
viewportCulling: true,
|
||||
contentOptions: {
|
||||
flexDirection: "column",
|
||||
paddingTop: 1,
|
||||
paddingBottom: 1,
|
||||
},
|
||||
verticalScrollbarOptions: { visible: false },
|
||||
horizontalScrollbarOptions: { visible: false },
|
||||
})
|
||||
hideScrollbars(this.scroll)
|
||||
this.footer = new TextRenderable(renderer, {
|
||||
id: "nanobot-tui-diff-footer",
|
||||
content: "←/→ file · pgup/pgdn scroll · esc close",
|
||||
width: "100%",
|
||||
height: 1,
|
||||
flexShrink: 0,
|
||||
fg: theme.muted,
|
||||
})
|
||||
this.root.add(this.header)
|
||||
this.root.add(this.fileHeader)
|
||||
this.root.add(this.scroll)
|
||||
this.root.add(this.footer)
|
||||
}
|
||||
|
||||
get visible(): boolean {
|
||||
return this.root.visible
|
||||
}
|
||||
|
||||
show(edits: FileEditEvent[]): void {
|
||||
this.update(edits)
|
||||
this.root.visible = true
|
||||
}
|
||||
|
||||
update(edits: FileEditEvent[]): void {
|
||||
const selectedKey = this.items[this.selected]?.key
|
||||
this.items = edits.map((edit) => ({ key: editKey(edit), edit }))
|
||||
this.selected = Math.max(0, selectedKey
|
||||
? this.items.findIndex((item) => item.key === selectedKey)
|
||||
: Math.min(this.selected, this.items.length - 1))
|
||||
if (this.selected < 0) this.selected = 0
|
||||
this.render()
|
||||
}
|
||||
|
||||
hide(): void {
|
||||
this.root.visible = false
|
||||
}
|
||||
|
||||
handleKey(key: KeyEvent): boolean {
|
||||
if (!this.visible) return false
|
||||
if (key.name === "escape") {
|
||||
this.hide()
|
||||
return true
|
||||
}
|
||||
if (key.name === "pageup" || key.name === "pagedown") {
|
||||
const direction = key.name === "pageup" ? -1 : 1
|
||||
this.scroll.scrollBy(direction * Math.max(3, Math.floor(this.scroll.height * 0.75)))
|
||||
return true
|
||||
}
|
||||
if (key.name === "home") {
|
||||
this.scroll.scrollTo(0)
|
||||
return true
|
||||
}
|
||||
if (key.name === "end") {
|
||||
this.scroll.scrollTo(this.scroll.scrollHeight)
|
||||
return true
|
||||
}
|
||||
if (["[", "]", "left", "right"].includes(key.name)) {
|
||||
this.select(key.name === "[" || key.name === "left" ? -1 : 1)
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
resize(width: number): void {
|
||||
this.footer.content = width >= 58
|
||||
? "←/→ file · pgup/pgdn scroll · home/end · esc close"
|
||||
: "←/→ file · pgup/pgdn · esc"
|
||||
}
|
||||
|
||||
setTheme(theme: DiffViewerTheme): void {
|
||||
const previousSyntax = this.theme.syntax
|
||||
this.theme = theme
|
||||
this.header.fg = theme.text
|
||||
this.fileHeader.fg = theme.muted
|
||||
this.footer.fg = theme.muted
|
||||
this.render()
|
||||
void this.renderer.idle().catch(() => {}).finally(() => previousSyntax.destroy())
|
||||
}
|
||||
|
||||
destroy(): void {
|
||||
this.theme.syntax.destroy()
|
||||
}
|
||||
|
||||
private select(direction: -1 | 1): void {
|
||||
if (this.items.length < 2) return
|
||||
this.selected = (this.selected + direction + this.items.length) % this.items.length
|
||||
this.render()
|
||||
}
|
||||
|
||||
private render(): void {
|
||||
for (const child of [...this.scroll.getChildren()]) {
|
||||
this.scroll.remove(child)
|
||||
child.destroyRecursively()
|
||||
}
|
||||
const totalAdded = this.items.reduce((sum, item) => sum + Math.max(0, item.edit.added || 0), 0)
|
||||
const totalDeleted = this.items.reduce((sum, item) => sum + Math.max(0, item.edit.deleted || 0), 0)
|
||||
const count = this.items.length
|
||||
this.header.content = count
|
||||
? `Diff · Last turn · ${count} ${count === 1 ? "change" : "changes"} · +${totalAdded} -${totalDeleted}`
|
||||
: "Diff · Last turn"
|
||||
const item = this.items[this.selected]
|
||||
if (!item) {
|
||||
this.fileHeader.content = "No file changes in the last turn."
|
||||
this.scroll.add(this.text("Run an editing task, then use /diff to inspect its patch.", "muted"))
|
||||
return
|
||||
}
|
||||
const edit = item.edit
|
||||
const index = this.items.length > 1 ? `${this.selected + 1}/${this.items.length} · ` : ""
|
||||
const state = edit.status === "editing" ? " · editing" : edit.status === "error" ? " · failed" : ""
|
||||
this.fileHeader.content = `${index}${edit.path || "Unknown file"} · ${stat(edit)}${state}`
|
||||
const text = edit.diff?.format === "unified" ? edit.diff.text?.trimEnd() : ""
|
||||
if (text) {
|
||||
this.scroll.add(new DiffRenderable(this.renderer, {
|
||||
id: `nanobot-tui-diff-${this.selected}`,
|
||||
diff: text,
|
||||
width: "100%",
|
||||
height: "auto",
|
||||
flexShrink: 0,
|
||||
view: "unified",
|
||||
wrapMode: "char",
|
||||
showLineNumbers: true,
|
||||
fg: this.theme.text,
|
||||
filetype: filetype(edit.path || ""),
|
||||
syntaxStyle: this.theme.syntax,
|
||||
treeSitterClient: this.treeSitterClient,
|
||||
lineNumberFg: this.theme.muted,
|
||||
lineNumberBg: RGBA.defaultBackground(),
|
||||
contextBg: RGBA.defaultBackground(),
|
||||
contextContentBg: RGBA.defaultBackground(),
|
||||
addedBg: this.theme.addedBackground || RGBA.defaultBackground(),
|
||||
addedContentBg: this.theme.addedBackground || RGBA.defaultBackground(),
|
||||
addedLineNumberBg: this.theme.addedBackground || RGBA.defaultBackground(),
|
||||
removedBg: this.theme.removedBackground || RGBA.defaultBackground(),
|
||||
removedContentBg: this.theme.removedBackground || RGBA.defaultBackground(),
|
||||
removedLineNumberBg: this.theme.removedBackground || RGBA.defaultBackground(),
|
||||
addedSignColor: this.theme.success,
|
||||
removedSignColor: this.theme.error,
|
||||
selectionBg: this.theme.border,
|
||||
selectionFg: this.theme.text,
|
||||
}))
|
||||
if (edit.diff?.truncated) {
|
||||
this.scroll.add(this.text("… Diff truncated by the gateway; line counts may be larger.", "accent"))
|
||||
}
|
||||
return
|
||||
}
|
||||
const message = edit.status === "editing"
|
||||
? "The file is still being edited; its patch will appear when the tool finishes."
|
||||
: edit.status === "error"
|
||||
? edit.error || "The edit failed before a patch was produced."
|
||||
: edit.binary
|
||||
? "Binary file changed; an inline text diff is unavailable."
|
||||
: "This edit has no renderable patch."
|
||||
this.scroll.add(this.text(message, edit.status === "error" ? "error" : "muted"))
|
||||
}
|
||||
|
||||
private text(content: string, tone: "muted" | "error" | "accent"): TextRenderable {
|
||||
return new TextRenderable(this.renderer, {
|
||||
id: `nanobot-tui-diff-note-${this.selected}-${tone}`,
|
||||
content,
|
||||
width: "100%",
|
||||
minHeight: 1,
|
||||
fg: this.theme[tone],
|
||||
wrapMode: "word",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, expect, test } from "bun:test"
|
||||
|
||||
import { contextualFooterHints, footerHints, footerTelemetry } from "./footer-hints"
|
||||
|
||||
const theme = {
|
||||
accent: "#EF8E30",
|
||||
danger: "#F87171",
|
||||
muted: "#A1A1AA",
|
||||
separator: "#71717A",
|
||||
}
|
||||
|
||||
describe("footerHints", () => {
|
||||
test("separates normal and destructive shortcuts semantically", () => {
|
||||
const result = footerHints([
|
||||
{ key: "enter", label: "steer" },
|
||||
{ key: "ctrl+c", label: "stop", tone: "danger" },
|
||||
], theme)
|
||||
|
||||
expect(result.chunks.map(({ text }) => text).join("")).toBe("enter steer · ctrl+c stop")
|
||||
expect(result.chunks[0]?.fg?.toInts().slice(0, 3)).toEqual([239, 142, 48])
|
||||
expect(result.chunks[3]?.fg?.toInts().slice(0, 3)).toEqual([248, 113, 113])
|
||||
})
|
||||
|
||||
test("keeps passive composer modes free of permanent instructions", () => {
|
||||
const ready = contextualFooterHints("ready", 100, theme, "linux")
|
||||
const active = contextualFooterHints("active", 100, theme, "darwin")
|
||||
|
||||
expect(ready.chunks).toHaveLength(0)
|
||||
expect(active.chunks).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("shows the measured request's context-window percentage", () => {
|
||||
const result = footerTelemetry(14_700, 128_000, theme)
|
||||
|
||||
expect(result.chunks.map(({ text }) => text).join(""))
|
||||
.toBe("11% context")
|
||||
expect(result.chunks[0]?.fg?.toInts().slice(0, 3)).toEqual([239, 142, 48])
|
||||
})
|
||||
|
||||
test("clamps usage above the configured window", () => {
|
||||
const result = footerTelemetry(220_000, 200_000, theme)
|
||||
|
||||
expect(result.chunks.map(({ text }) => text).join(""))
|
||||
.toBe("100% context")
|
||||
})
|
||||
|
||||
test("does not guess without measured context or a valid window", () => {
|
||||
const missingContext = footerTelemetry(null, 128_000, theme)
|
||||
const missingWindow = footerTelemetry(1000, null, theme)
|
||||
const invalidWindow = footerTelemetry(1000, 0, theme)
|
||||
|
||||
expect(missingContext.chunks).toHaveLength(0)
|
||||
expect(missingWindow.chunks).toHaveLength(0)
|
||||
expect(invalidWindow.chunks).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,110 @@
|
||||
import { StyledText, TextAttributes, parseColor, type ColorInput, type TextChunk } from "@opentui/core"
|
||||
|
||||
export interface FooterHint {
|
||||
key: string
|
||||
label: string
|
||||
tone?: "normal" | "danger"
|
||||
}
|
||||
|
||||
export interface FooterHintTheme {
|
||||
accent: ColorInput
|
||||
danger: ColorInput
|
||||
muted: ColorInput
|
||||
separator: ColorInput
|
||||
}
|
||||
|
||||
export type FooterMode =
|
||||
| "mention"
|
||||
| "skill"
|
||||
| "runtime"
|
||||
| "active"
|
||||
| "branch"
|
||||
| "command"
|
||||
| "session"
|
||||
| "context"
|
||||
| "usage"
|
||||
| "history"
|
||||
| "ready"
|
||||
|
||||
export function contextualFooterHints(
|
||||
mode: FooterMode,
|
||||
width: number,
|
||||
theme: FooterHintTheme,
|
||||
_platform: string = process.platform,
|
||||
_shiftedEnter = false,
|
||||
): StyledText {
|
||||
return footerHints(hintsFor(mode, width), theme)
|
||||
}
|
||||
|
||||
/** Latest measured request's context-window occupancy. */
|
||||
export function footerTelemetry(
|
||||
contextTokens: number | null,
|
||||
contextWindowTokens: number | null,
|
||||
theme: FooterHintTheme,
|
||||
): StyledText {
|
||||
if (
|
||||
typeof contextTokens !== "number"
|
||||
|| !Number.isFinite(contextTokens)
|
||||
|| contextTokens < 0
|
||||
|| typeof contextWindowTokens !== "number"
|
||||
|| !Number.isFinite(contextWindowTokens)
|
||||
|| contextWindowTokens <= 0
|
||||
) return new StyledText([])
|
||||
const percentage = Math.min(100, Math.round(
|
||||
contextTokens * 100 / contextWindowTokens,
|
||||
))
|
||||
return new StyledText([chunk(`${percentage}% context`, theme.accent, true)])
|
||||
}
|
||||
|
||||
/** Give shortcuts visual hierarchy without turning the footer into a toolbar. */
|
||||
export function footerHints(hints: readonly FooterHint[], theme: FooterHintTheme): StyledText {
|
||||
const chunks: TextChunk[] = []
|
||||
hints.forEach((hint, index) => {
|
||||
if (index) chunks.push(chunk(" · ", theme.separator))
|
||||
const color = hint.tone === "danger" ? theme.danger : theme.accent
|
||||
chunks.push(chunk(hint.key, color, true))
|
||||
chunks.push(chunk(` ${hint.label}`, theme.muted))
|
||||
})
|
||||
return new StyledText(chunks)
|
||||
}
|
||||
|
||||
function hintsFor(
|
||||
mode: FooterMode,
|
||||
width: number,
|
||||
): FooterHint[] {
|
||||
if (mode === "runtime") return width >= 64
|
||||
? [hint("↑↓/click", "choose"), hint("enter", "apply"), hint("esc", "close")]
|
||||
: [hint("enter", "apply"), hint("esc", "close")]
|
||||
if (mode === "mention" || mode === "skill") return width >= 64
|
||||
? [hint("↑↓", "choose"), hint("tab/enter", "insert"), hint("esc", "close")]
|
||||
: [hint("enter", "insert"), hint("esc", "close")]
|
||||
if (mode === "active") return []
|
||||
if (mode === "branch") return width >= 64
|
||||
? [hint("type", "filter"), hint("↑↓", "choose"), hint("enter", "branch"), hint("esc", "close")]
|
||||
: [hint("enter", "branch"), hint("esc", "close")]
|
||||
if (mode === "command") return width >= 72
|
||||
? [hint("↑↓", "choose"), hint("tab", "complete"), hint("esc", "close")]
|
||||
: [hint("tab", "complete"), hint("esc", "close")]
|
||||
if (mode === "session") return width >= 64
|
||||
? [hint("type", "filter"), hint("↑↓", "choose"), hint("enter", "open"), hint("esc", "close")]
|
||||
: [hint("enter", "open"), hint("esc", "close")]
|
||||
if (mode === "usage") return [hint("←→", "round"), hint("esc", "close")]
|
||||
if (mode === "context") return [hint("esc", "close"), hint("pgup/pgdn", "scroll")]
|
||||
if (mode === "history") return width >= 72
|
||||
? [hint("ctrl+end", "latest"), hint("pgup/pgdn", "scroll")]
|
||||
: width >= 48 ? [hint("ctrl+end", "latest")] : []
|
||||
return []
|
||||
}
|
||||
|
||||
function hint(key: string, label: string): FooterHint {
|
||||
return { key, label }
|
||||
}
|
||||
|
||||
function chunk(text: string, color: ColorInput, bold = false): TextChunk {
|
||||
return {
|
||||
__isChunk: true,
|
||||
text,
|
||||
fg: parseColor(color),
|
||||
attributes: bold ? TextAttributes.BOLD : 0,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,179 @@
|
||||
import {
|
||||
BoxRenderable,
|
||||
RGBA,
|
||||
StyledText,
|
||||
TextAttributes,
|
||||
TextRenderable,
|
||||
parseColor,
|
||||
type CliRenderer,
|
||||
type ColorInput,
|
||||
type TextChunk,
|
||||
} from "@opentui/core"
|
||||
|
||||
import type { RecoveryState } from "../client"
|
||||
|
||||
export interface RecoveryNoticeTheme {
|
||||
text: ColorInput
|
||||
muted: ColorInput
|
||||
border: ColorInput
|
||||
accent: ColorInput
|
||||
warning: ColorInput
|
||||
error: ColorInput
|
||||
}
|
||||
|
||||
interface RecoveryNoticeOptions {
|
||||
onContinue: () => void
|
||||
onDismiss: () => void
|
||||
}
|
||||
|
||||
/** A quiet action surface for a gateway-owned interrupted turn. */
|
||||
export class RecoveryNotice {
|
||||
readonly root: BoxRenderable
|
||||
private readonly title: TextRenderable
|
||||
private readonly detail: TextRenderable
|
||||
private readonly dismiss: TextRenderable
|
||||
private readonly resume: TextRenderable
|
||||
private state: RecoveryState | null = null
|
||||
private busy = false
|
||||
|
||||
constructor(
|
||||
renderer: CliRenderer,
|
||||
private theme: RecoveryNoticeTheme,
|
||||
options: RecoveryNoticeOptions,
|
||||
) {
|
||||
this.root = new BoxRenderable(renderer, {
|
||||
id: "nanobot-tui-recovery-notice",
|
||||
width: "100%",
|
||||
height: 4,
|
||||
flexShrink: 0,
|
||||
flexDirection: "column",
|
||||
border: true,
|
||||
borderStyle: "rounded",
|
||||
borderColor: theme.border,
|
||||
paddingLeft: 1,
|
||||
paddingRight: 1,
|
||||
visible: false,
|
||||
backgroundColor: RGBA.defaultBackground(),
|
||||
})
|
||||
const header = new BoxRenderable(renderer, {
|
||||
id: "nanobot-tui-recovery-header",
|
||||
width: "100%",
|
||||
height: 1,
|
||||
flexDirection: "row",
|
||||
alignItems: "center",
|
||||
gap: 2,
|
||||
})
|
||||
this.title = new TextRenderable(renderer, {
|
||||
id: "nanobot-tui-recovery-title",
|
||||
width: "auto",
|
||||
minWidth: 0,
|
||||
flexGrow: 1,
|
||||
height: 1,
|
||||
truncate: true,
|
||||
selectable: false,
|
||||
})
|
||||
this.detail = new TextRenderable(renderer, {
|
||||
id: "nanobot-tui-recovery-detail",
|
||||
width: "100%",
|
||||
height: 1,
|
||||
truncate: true,
|
||||
selectable: false,
|
||||
})
|
||||
this.dismiss = this.action(renderer, "dismiss", "Dismiss", options.onDismiss)
|
||||
this.resume = this.action(renderer, "continue", "Continue", options.onContinue, true)
|
||||
header.add(this.title)
|
||||
header.add(this.dismiss)
|
||||
header.add(this.resume)
|
||||
this.root.add(header)
|
||||
this.root.add(this.detail)
|
||||
}
|
||||
|
||||
get visible(): boolean {
|
||||
return this.root.visible
|
||||
}
|
||||
|
||||
show(state: RecoveryState): void {
|
||||
this.state = state
|
||||
this.busy = false
|
||||
this.root.visible = true
|
||||
this.render()
|
||||
}
|
||||
|
||||
hide(): void {
|
||||
this.state = null
|
||||
this.busy = false
|
||||
this.root.visible = false
|
||||
}
|
||||
|
||||
setBusy(busy: boolean): void {
|
||||
this.busy = busy
|
||||
if (this.visible) this.render()
|
||||
}
|
||||
|
||||
setTheme(theme: RecoveryNoticeTheme): void {
|
||||
this.theme = theme
|
||||
this.root.borderColor = theme.border
|
||||
if (this.visible) this.render()
|
||||
}
|
||||
|
||||
private action(
|
||||
renderer: CliRenderer,
|
||||
id: string,
|
||||
label: string,
|
||||
callback: () => void,
|
||||
primary = false,
|
||||
): TextRenderable {
|
||||
return new TextRenderable(renderer, {
|
||||
id: `nanobot-tui-recovery-${id}`,
|
||||
content: label,
|
||||
width: label.length,
|
||||
height: 1,
|
||||
flexShrink: 0,
|
||||
selectable: false,
|
||||
onMouseOver: () => {
|
||||
if (this.busy) return
|
||||
const target = primary ? this.resume : this.dismiss
|
||||
target.attributes = TextAttributes.BOLD | TextAttributes.UNDERLINE
|
||||
},
|
||||
onMouseOut: () => this.render(),
|
||||
onMouseDown: (event) => {
|
||||
if (event.button !== 0 || this.busy) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
renderer.clearSelection()
|
||||
callback()
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
private render(): void {
|
||||
if (!this.state) return
|
||||
const failed = this.state.status === "failed"
|
||||
const contextUnavailable = this.state.can_continue === false
|
||||
const title = failed ? "Recovery failed" : "Task interrupted"
|
||||
const detail = failed
|
||||
? "Review the saved task before continuing."
|
||||
: contextUnavailable
|
||||
? "This task can’t be resumed safely. Dismiss to start a new message."
|
||||
: "Review the saved context. Tools will not replay automatically."
|
||||
this.title.content = new StyledText([
|
||||
chunk("⚠ ", failed ? this.theme.error : this.theme.warning),
|
||||
chunk(title, this.theme.text, true),
|
||||
])
|
||||
this.detail.content = new StyledText([chunk(` ${detail}`, this.theme.muted)])
|
||||
this.dismiss.fg = parseColor(this.busy ? this.theme.muted : this.theme.text)
|
||||
this.resume.visible = !contextUnavailable
|
||||
this.resume.fg = parseColor(this.busy ? this.theme.muted : this.theme.accent)
|
||||
this.dismiss.attributes = 0
|
||||
this.resume.attributes = TextAttributes.BOLD
|
||||
}
|
||||
}
|
||||
|
||||
function chunk(text: string, color: ColorInput, bold = false): TextChunk {
|
||||
return {
|
||||
__isChunk: true,
|
||||
text,
|
||||
fg: parseColor(color),
|
||||
attributes: bold ? TextAttributes.BOLD : 0,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
import {
|
||||
TextRenderable,
|
||||
type BoxRenderable,
|
||||
type CliRenderer,
|
||||
type ColorInput,
|
||||
type KeyEvent,
|
||||
} from "@opentui/core"
|
||||
|
||||
import {
|
||||
fetchRuntimeControls,
|
||||
type ApiReauthenticator,
|
||||
type WorkspaceScopePayload,
|
||||
} from "../client"
|
||||
import { PickerMenu, type PickerMenuTheme } from "../menus/picker-menu"
|
||||
|
||||
interface RuntimeControlsTheme extends PickerMenuTheme {
|
||||
accent: ColorInput
|
||||
faint: ColorInput
|
||||
}
|
||||
|
||||
type Choice =
|
||||
| { kind: "model"; name: string; label: string; detail: string }
|
||||
| { kind: "access"; mode: "restricted" | "full"; label: string; detail: string }
|
||||
|
||||
const CONTROLS_CACHE_MS = 10_000
|
||||
|
||||
interface RuntimeControlsOptions {
|
||||
apiUrl: string
|
||||
apiToken: string
|
||||
model: string
|
||||
modelPreset: string
|
||||
workspace: string
|
||||
access: string
|
||||
reauthenticateApi?: ApiReauthenticator
|
||||
available: () => boolean
|
||||
beforeOpen: () => void
|
||||
refreshScope: () => Promise<void>
|
||||
onModel: (name: string) => void
|
||||
onAccess: (scope: WorkspaceScopePayload) => void
|
||||
onStatus: (message: string) => void
|
||||
onVisibilityChange: (visible: boolean) => void
|
||||
}
|
||||
|
||||
/** Model and workspace policy controls expose one small, mouse-optional interface. */
|
||||
export class RuntimeControls {
|
||||
readonly modelText: TextRenderable
|
||||
readonly accessText: TextRenderable
|
||||
readonly contextText: TextRenderable
|
||||
readonly menuRoot: BoxRenderable
|
||||
private readonly menu: PickerMenu<Choice>
|
||||
private kind: Choice["kind"] | null = null
|
||||
private model: string
|
||||
private modelPreset: string
|
||||
private modelPresets: Array<{ name: string; model: string }>
|
||||
private canUseFullAccess: boolean
|
||||
private controlsLoaded = false
|
||||
private controlsLoadedAt = 0
|
||||
private controlsPromise: Promise<void> | null = null
|
||||
private scope: WorkspaceScopePayload
|
||||
|
||||
constructor(
|
||||
private readonly renderer: CliRenderer,
|
||||
private theme: RuntimeControlsTheme,
|
||||
private readonly options: RuntimeControlsOptions,
|
||||
) {
|
||||
this.model = options.model
|
||||
this.modelPreset = options.modelPreset
|
||||
this.modelPresets = [{ name: options.modelPreset, model: options.model }]
|
||||
this.scope = {
|
||||
project_path: options.workspace,
|
||||
access_mode: options.access.toLocaleLowerCase().includes("full") ? "full" : "restricted",
|
||||
}
|
||||
this.canUseFullAccess = this.scope.access_mode === "full"
|
||||
this.menu = new PickerMenu<Choice>(renderer, theme, {
|
||||
id: "nanobot-tui-runtime-menu",
|
||||
maxWidth: 64,
|
||||
searchText: (choice) => `${choice.label} ${choice.detail}`,
|
||||
render: (choice) => `${choice.label}${choice.detail ? ` ${choice.detail}` : ""}`,
|
||||
onSelect: (choice) => this.apply(choice),
|
||||
})
|
||||
this.menuRoot = this.menu.root
|
||||
this.modelText = this.controlText(renderer, "model", () => void this.openModel())
|
||||
this.accessText = this.controlText(renderer, "access", () => void this.openAccess())
|
||||
this.contextText = new TextRenderable(renderer, {
|
||||
id: "nanobot-tui-context-text",
|
||||
content: "",
|
||||
height: 1,
|
||||
flexShrink: 0,
|
||||
fg: theme.faint,
|
||||
selectable: false,
|
||||
})
|
||||
this.render()
|
||||
}
|
||||
|
||||
get visible(): boolean {
|
||||
return this.menu.visible
|
||||
}
|
||||
|
||||
get workspaceScope(): WorkspaceScopePayload {
|
||||
return this.scope
|
||||
}
|
||||
|
||||
updateModel(model: string, preset: string): void {
|
||||
this.model = model
|
||||
this.modelPreset = preset
|
||||
this.render()
|
||||
}
|
||||
|
||||
updateContext(text: string): void {
|
||||
this.contextText.content = text
|
||||
}
|
||||
|
||||
/** Warm the small settings payload while the user is reading the first frame. */
|
||||
preload(): void {
|
||||
void this.load().catch(() => {})
|
||||
}
|
||||
|
||||
useApiConnection(apiUrl: string, apiToken: string): void {
|
||||
this.options.apiUrl = apiUrl
|
||||
this.options.apiToken = apiToken
|
||||
this.controlsLoaded = false
|
||||
this.controlsLoadedAt = 0
|
||||
this.preload()
|
||||
}
|
||||
|
||||
updateWorkspaceScope(scope: WorkspaceScopePayload): void {
|
||||
this.scope = scope
|
||||
this.render()
|
||||
}
|
||||
|
||||
resize(width: number): void {
|
||||
this.accessText.visible = width >= 58
|
||||
this.contextText.visible = width >= 96
|
||||
}
|
||||
|
||||
choose(): boolean {
|
||||
const choice = this.menu.current()
|
||||
if (!choice) return false
|
||||
this.apply(choice)
|
||||
return true
|
||||
}
|
||||
|
||||
handleKey(key: KeyEvent): boolean {
|
||||
if (!this.visible) return false
|
||||
if (!key.ctrl && !key.meta && (key.name === "up" || key.name === "down")) {
|
||||
this.menu.move(key.name === "up" ? -1 : 1)
|
||||
} else if (key.name === "escape") {
|
||||
this.hide()
|
||||
} else {
|
||||
return false
|
||||
}
|
||||
key.preventDefault()
|
||||
return true
|
||||
}
|
||||
|
||||
hide(): void {
|
||||
if (!this.visible) return
|
||||
this.kind = null
|
||||
this.menu.hide()
|
||||
this.renderColors()
|
||||
this.options.onVisibilityChange(false)
|
||||
}
|
||||
|
||||
setTheme(theme: RuntimeControlsTheme): void {
|
||||
this.theme = theme
|
||||
this.menu.setTheme(theme)
|
||||
this.contextText.fg = theme.faint
|
||||
this.renderColors()
|
||||
}
|
||||
|
||||
private controlText(
|
||||
renderer: CliRenderer,
|
||||
id: "model" | "access",
|
||||
open: () => void,
|
||||
): TextRenderable {
|
||||
const text = new TextRenderable(renderer, {
|
||||
id: `nanobot-tui-${id}-text`,
|
||||
content: "",
|
||||
height: 1,
|
||||
flexShrink: id === "model" ? 1 : 0,
|
||||
fg: this.theme.muted,
|
||||
selectable: false,
|
||||
onMouseOver: () => { text.fg = this.theme.accent },
|
||||
onMouseOut: () => this.renderColors(),
|
||||
onMouseDown: (event) => {
|
||||
if (event.button !== 0) return
|
||||
event.preventDefault()
|
||||
event.stopPropagation()
|
||||
this.renderer.clearSelection()
|
||||
open()
|
||||
},
|
||||
})
|
||||
return text
|
||||
}
|
||||
|
||||
private async load(force = false): Promise<void> {
|
||||
if (force && Date.now() - this.controlsLoadedAt >= CONTROLS_CACHE_MS) {
|
||||
this.controlsLoaded = false
|
||||
}
|
||||
if (this.controlsLoaded) return
|
||||
if (this.controlsPromise) return this.controlsPromise
|
||||
if (!this.options.apiUrl || !this.options.apiToken) {
|
||||
this.controlsLoaded = true
|
||||
this.controlsLoadedAt = Date.now()
|
||||
return
|
||||
}
|
||||
this.controlsPromise = (async () => {
|
||||
const controls = await fetchRuntimeControls(
|
||||
this.options.apiUrl,
|
||||
this.options.apiToken,
|
||||
this.options.reauthenticateApi,
|
||||
)
|
||||
const presets = new Map(controls.modelPresets.map((preset) => [
|
||||
preset.name.toLocaleLowerCase(),
|
||||
preset,
|
||||
]))
|
||||
if (!presets.has(this.modelPreset.toLocaleLowerCase())) {
|
||||
presets.set(this.modelPreset.toLocaleLowerCase(), {
|
||||
name: this.modelPreset,
|
||||
model: this.model,
|
||||
})
|
||||
}
|
||||
this.modelPresets = [...presets.values()]
|
||||
this.canUseFullAccess = controls.canUseFullAccess
|
||||
this.controlsLoaded = true
|
||||
this.controlsLoadedAt = Date.now()
|
||||
})().finally(() => { this.controlsPromise = null })
|
||||
return this.controlsPromise
|
||||
}
|
||||
|
||||
private async openModel(): Promise<void> {
|
||||
if (!this.canOpen()) return
|
||||
try {
|
||||
await this.load(true)
|
||||
} catch (error) {
|
||||
this.options.onStatus(error instanceof Error ? error.message : String(error))
|
||||
return
|
||||
}
|
||||
this.options.beforeOpen()
|
||||
this.kind = "model"
|
||||
const choices: Choice[] = this.modelPresets
|
||||
.map((preset) => ({
|
||||
kind: "model" as const,
|
||||
name: preset.name,
|
||||
label: `${preset.name === this.modelPreset ? "●" : " "} ${preset.name}`,
|
||||
detail: preset.model,
|
||||
}))
|
||||
.sort((left, right) => Number(right.name === this.modelPreset)
|
||||
- Number(left.name === this.modelPreset))
|
||||
this.menu.show(choices, "", rendererLimit(this.renderer.height))
|
||||
this.opened()
|
||||
}
|
||||
|
||||
private async openAccess(): Promise<void> {
|
||||
if (!this.canOpen()) return
|
||||
try {
|
||||
await Promise.all([this.load(true), this.options.refreshScope()])
|
||||
} catch (error) {
|
||||
this.options.onStatus(error instanceof Error ? error.message : String(error))
|
||||
return
|
||||
}
|
||||
this.options.beforeOpen()
|
||||
this.kind = "access"
|
||||
const choices: Choice[] = [{
|
||||
kind: "access",
|
||||
mode: "restricted",
|
||||
label: `${this.scope.access_mode === "restricted" ? "●" : " "} Workspace access`,
|
||||
detail: "project files only",
|
||||
}]
|
||||
if (this.canUseFullAccess || this.scope.access_mode === "full") choices.push({
|
||||
kind: "access",
|
||||
mode: "full",
|
||||
label: `${this.scope.access_mode === "full" ? "●" : " "} Full access`,
|
||||
detail: "all local files and tools",
|
||||
})
|
||||
choices.sort((left, right) => Number(
|
||||
right.kind === "access" && right.mode === this.scope.access_mode,
|
||||
) - Number(left.kind === "access" && left.mode === this.scope.access_mode))
|
||||
this.menu.show(choices)
|
||||
this.opened()
|
||||
}
|
||||
|
||||
private canOpen(): boolean {
|
||||
if (this.options.available()) return true
|
||||
this.options.onStatus("Preparing chat…")
|
||||
return false
|
||||
}
|
||||
|
||||
private opened(): void {
|
||||
this.renderColors()
|
||||
this.options.onVisibilityChange(true)
|
||||
}
|
||||
|
||||
private apply(choice: Choice): void {
|
||||
this.hide()
|
||||
if (choice.kind === "model") {
|
||||
if (choice.name !== this.modelPreset) this.options.onModel(choice.name)
|
||||
return
|
||||
}
|
||||
if (choice.mode === this.scope.access_mode) return
|
||||
if (choice.mode === "full" && !this.canUseFullAccess) {
|
||||
this.options.onStatus("Full access is only available from a trusted local gateway")
|
||||
return
|
||||
}
|
||||
this.options.onAccess({
|
||||
...this.scope,
|
||||
access_mode: choice.mode,
|
||||
restrict_to_workspace: choice.mode === "restricted",
|
||||
})
|
||||
}
|
||||
|
||||
private render(): void {
|
||||
this.modelText.content = `${this.modelPreset} ▾`
|
||||
const access = this.scope.access_mode === "full" ? "full access" : "workspace access"
|
||||
this.accessText.content = ` ${access} ▾`
|
||||
this.renderColors()
|
||||
}
|
||||
|
||||
private renderColors(): void {
|
||||
this.modelText.fg = this.kind === "model" && this.visible
|
||||
? this.theme.accent
|
||||
: this.theme.muted
|
||||
this.accessText.fg = (
|
||||
(this.kind === "access" && this.visible) || this.scope.access_mode === "full"
|
||||
) ? this.theme.accent : this.theme.muted
|
||||
}
|
||||
}
|
||||
|
||||
function rendererLimit(height: number): number {
|
||||
return height >= 20 ? 8 : 4
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { afterEach, describe, expect, test } from "bun:test"
|
||||
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 "../client"
|
||||
|
||||
const theme = {
|
||||
text: "#ECEDEE", muted: "#A1A1AA", border: "#3F3F46", accent: "#EF8E30",
|
||||
cached: "#1795A2", warning: "#F5C451", error: "#F87171",
|
||||
} satisfies UsagePanelTheme
|
||||
const snapshot: SessionUsageSnapshot = {
|
||||
context: { tokens: 9_000, windowTokens: 262_144 },
|
||||
rounds: [
|
||||
{ prompt_tokens: 3_000, completion_tokens: 200 },
|
||||
{ prompt_tokens: 6_000, completion_tokens: 400, cached_tokens: 0 },
|
||||
{ prompt_tokens: 9_000, completion_tokens: 800, cached_tokens: 6_000, generation_ms: 1500, estimated_tokens: 20 },
|
||||
],
|
||||
}
|
||||
|
||||
describe("UsagePanel", () => {
|
||||
let setup: TestRendererSetup | undefined
|
||||
afterEach(() => {
|
||||
if (setup && !setup.renderer.isDestroyed) setup.renderer.destroy()
|
||||
setup = undefined
|
||||
})
|
||||
|
||||
test("renders context occupancy and selects logical-round details without inventing cache data", async () => {
|
||||
setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })
|
||||
const panel = new UsagePanel(setup.renderer, theme)
|
||||
setup.renderer.root.add(panel.root)
|
||||
panel.resize(80, 30)
|
||||
panel.show(snapshot)
|
||||
await setup.renderOnce()
|
||||
const frame = setup.captureCharFrame()
|
||||
expect(frame).toContain("Context 9k / 262k")
|
||||
expect(frame).toContain("3%")
|
||||
expect(frame).toContain("Input tokens · max 9k")
|
||||
expect(frame).toContain("Round 3/3 · In 9,000 · Out 800")
|
||||
expect(frame).toContain("Cache 67% · 1.5s · includes estimated usage")
|
||||
expect(frame).toContain("Uncached")
|
||||
expect(frame).toContain("Unknown cache")
|
||||
expect(frame).toContain("███")
|
||||
const rows = frame.split("\n")
|
||||
const detailsIndex = rows.findIndex((row) => row.includes("Round 3/3"))
|
||||
expect(rows[detailsIndex - 1]).toContain("███")
|
||||
panel.move(-1)
|
||||
await setup.renderOnce()
|
||||
expect(setup.captureCharFrame()).toContain("Cache 0%")
|
||||
panel.move(-1)
|
||||
panel.move(-1)
|
||||
await setup.renderOnce()
|
||||
expect(setup.captureCharFrame()).toContain("Round 1/3 · In 3,000 · Out 200")
|
||||
expect(setup.captureCharFrame()).toContain("Cache ?")
|
||||
})
|
||||
|
||||
test("splits cached foreground and uncached background at eighth-row precision without color bleed", async () => {
|
||||
setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })
|
||||
const panel = new UsagePanel(setup.renderer, theme)
|
||||
setup.renderer.root.add(panel.root)
|
||||
panel.show({ context: null, rounds: [{ prompt_tokens: 1000, cached_tokens: 800 }] })
|
||||
const barSpans = () => setup!.captureSpans().lines.flatMap((line) =>
|
||||
line.spans.filter((span) => /[▁▂▃▄▅▆▇█]/u.test(span.text)))
|
||||
|
||||
for (const palette of [theme, { ...theme, accent: "#B94D0B", cached: "#0F766E" }]) {
|
||||
panel.setTheme(palette)
|
||||
for (const [height, glyphs] of [[30, ["███", "▆▆▆", "███", "███", "███", "███"]], [18, ["▆▆▆"]]] as const) {
|
||||
setup.resize(80, height)
|
||||
panel.resize(80, height)
|
||||
await setup.renderOnce()
|
||||
const bars = barSpans()
|
||||
expect(bars.map((span) => span.text.trim())).toEqual([...glyphs])
|
||||
const cachedColor = RGBA.fromHex(palette.cached)
|
||||
const uncachedColor = RGBA.fromHex(palette.accent)
|
||||
const split = bars.find((span) => span.text.includes("▆"))!
|
||||
expect(split.fg.equals(cachedColor)).toBe(true)
|
||||
expect(split.bg.equals(uncachedColor)).toBe(true)
|
||||
// Every solid cell below the split is cached; the cell above is uncached.
|
||||
expect(bars.filter((span) => span.fg.equals(cachedColor)).length).toBe(height === 30 ? 5 : 1)
|
||||
expect(setup.captureSpans().lines.flatMap((line) => line.spans)
|
||||
.filter((span) => span.bg.equals(uncachedColor)).map((span) => span.text)).toEqual(["▆▆▆"])
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test("preserves full bar heights when cache colors use terminal defaults", async () => {
|
||||
setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })
|
||||
const panel = new UsagePanel(setup.renderer, {
|
||||
...theme, accent: RGBA.defaultForeground(), cached: RGBA.defaultForeground(),
|
||||
})
|
||||
setup.renderer.root.add(panel.root)
|
||||
panel.resize(80, 30)
|
||||
panel.show({ context: null, rounds: [{ prompt_tokens: 1000, cached_tokens: 800 }] })
|
||||
await setup.renderOnce()
|
||||
const bars = setup.captureSpans().lines.flatMap((line) =>
|
||||
line.spans.filter((span) => /[▁▂▃▄▅▆▇█]/u.test(span.text)))
|
||||
expect(bars.map((span) => span.text.trim())).toEqual(Array(6).fill("███"))
|
||||
expect(bars.every((span) => span.fg.intent === "default")).toBe(true)
|
||||
})
|
||||
|
||||
test("quantizes the cache boundary from raw tokens rather than the rounded total height", async () => {
|
||||
setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })
|
||||
const panel = new UsagePanel(setup.renderer, theme)
|
||||
setup.renderer.root.add(panel.root)
|
||||
panel.resize(80, 30)
|
||||
panel.show({ context: null, rounds: [
|
||||
{ prompt_tokens: 480 },
|
||||
{ prompt_tokens: 254, cached_tokens: 215 },
|
||||
] })
|
||||
await setup.renderOnce()
|
||||
const bars = setup.captureSpans().lines.flatMap((line) =>
|
||||
line.spans.filter((span) => /[▁▂▃▄▅▆▇█]/u.test(span.text)))
|
||||
const cached = bars.filter((span) => span.fg.equals(RGBA.fromHex(theme.cached)))
|
||||
// Total: round(25.4) = 25 eighths; cache: round(21.5) = 22, not round(25 * 215/254) = 21.
|
||||
expect(cached.map((span) => span.text.trim())).toEqual(["▆▆▆", "███", "███"])
|
||||
expect(bars.some((span) => span.text.includes("▁") && span.fg.equals(RGBA.fromHex(theme.accent)))).toBe(true)
|
||||
})
|
||||
|
||||
test("preserves a partial top's empty space when cached and uncached input share it", async () => {
|
||||
setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })
|
||||
const panel = new UsagePanel(setup.renderer, theme)
|
||||
setup.renderer.root.add(panel.root)
|
||||
panel.resize(80, 30)
|
||||
for (const [input, cachedTokens, glyph, color] of [
|
||||
[300, 240, "▆", theme.cached], [300, 180, "▆", theme.accent],
|
||||
[100, 80, "▅", theme.cached], [1, 0, "▁", theme.accent],
|
||||
] as const) {
|
||||
panel.show({ context: null, rounds: [
|
||||
{ prompt_tokens: 1000 }, { prompt_tokens: input, cached_tokens: cachedTokens },
|
||||
] })
|
||||
await setup.renderOnce()
|
||||
const spans = setup.captureSpans().lines.flatMap((line) => line.spans)
|
||||
const top = spans.find((span) => span.text.includes(glyph))!
|
||||
expect(top.text.trim()).toBe(glyph.repeat(3))
|
||||
expect(top.fg.equals(RGBA.fromHex(color))).toBe(true)
|
||||
expect(top.bg.equals(RGBA.fromHex(theme.accent))).toBe(false)
|
||||
expect(top.bg.equals(RGBA.fromHex(theme.cached))).toBe(false)
|
||||
expect(setup.captureCharFrame()).toContain(`Cache ${Math.round(cachedTokens / input * 100)}%`)
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps unknown, zero, and fully cached bars unblended", async () => {
|
||||
setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })
|
||||
const panel = new UsagePanel(setup.renderer, theme)
|
||||
setup.renderer.root.add(panel.root)
|
||||
panel.resize(80, 30)
|
||||
for (const [cachedTokens, color] of [[undefined, theme.muted], [0, theme.accent], [1000, theme.cached], [2000, theme.cached]] as const) {
|
||||
panel.show({ context: null, rounds: [{ prompt_tokens: 1000, cached_tokens: cachedTokens }] })
|
||||
await setup.renderOnce()
|
||||
const bars = setup.captureSpans().lines.flatMap((line) =>
|
||||
line.spans.filter((span) => span.text.includes("█")))
|
||||
expect(bars.length).toBe(6)
|
||||
for (const bar of bars) {
|
||||
expect(bar.text.trim()).toBe("███")
|
||||
expect(bar.fg.equals(RGBA.fromHex(color))).toBe(true)
|
||||
expect(bar.bg.equals(RGBA.fromHex(theme.accent))).toBe(false)
|
||||
expect(bar.bg.equals(RGBA.fromHex(theme.cached))).toBe(false)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
test("keeps zero context distinct from unknown capacity and missing usage", async () => {
|
||||
setup = await createTestRenderer({ width: 80, height: 26, screenMode: "alternate-screen" })
|
||||
const panel = new UsagePanel(setup.renderer, theme)
|
||||
setup.renderer.root.add(panel.root)
|
||||
panel.show({ context: { tokens: 0, windowTokens: 1000 }, rounds: [] })
|
||||
await setup.renderOnce()
|
||||
expect(setup.captureCharFrame()).toContain("Context 0 / 1k")
|
||||
expect(setup.captureCharFrame()).toContain("0%")
|
||||
panel.show({ context: { tokens: 9000 }, rounds: [] })
|
||||
await setup.renderOnce()
|
||||
expect(setup.captureCharFrame()).toContain("Context 9k / ?")
|
||||
expect(setup.captureCharFrame()).not.toContain("0%")
|
||||
panel.show({ context: null, rounds: [] })
|
||||
await setup.renderOnce()
|
||||
expect(setup.captureCharFrame()).toContain("Context unavailable")
|
||||
expect(setup.captureCharFrame()).toContain("No model-call usage available yet")
|
||||
})
|
||||
|
||||
test("clamps context and cached portions without losing the actual input count", async () => {
|
||||
setup = await createTestRenderer({ width: 80, height: 26, screenMode: "alternate-screen" })
|
||||
const panel = new UsagePanel(setup.renderer, theme)
|
||||
setup.renderer.root.add(panel.root)
|
||||
panel.show({
|
||||
context: { tokens: 2000, windowTokens: 1000 },
|
||||
rounds: [{ prompt_tokens: 2000, cached_tokens: 3000 }],
|
||||
})
|
||||
await setup.renderOnce()
|
||||
const frame = setup.captureCharFrame()
|
||||
expect(frame).toContain("Context 2k / 1k")
|
||||
expect(frame).toContain("100%")
|
||||
expect(frame).toContain("In 2,000 · Out ?")
|
||||
expect(frame).toContain("Cache 100%")
|
||||
})
|
||||
|
||||
test("does not rebuild hidden content and uses the latest dimensions and theme when reopened", async () => {
|
||||
setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })
|
||||
const panel = new UsagePanel(setup.renderer, theme)
|
||||
setup.renderer.root.add(panel.root)
|
||||
const body = panel.root.getChildren()[0] as TextRenderable
|
||||
const empty = body.content
|
||||
panel.resize(80, 30)
|
||||
panel.setTheme(theme)
|
||||
expect(body.content).toBe(empty)
|
||||
panel.show(snapshot)
|
||||
const content = body.content
|
||||
panel.hide()
|
||||
setup.resize(56, 18)
|
||||
panel.resize(56, 18)
|
||||
panel.setTheme({ ...theme, text: "#18181B", accent: "#B94D0B", cached: "#0F766E" })
|
||||
expect(body.content).toBe(content)
|
||||
panel.show(snapshot)
|
||||
await setup.renderOnce()
|
||||
expect(setup.captureCharFrame()).toContain("Context 9k / 262k")
|
||||
expect(panel.root.height).toBeLessThanOrEqual(6)
|
||||
const bars = setup.captureSpans().lines.flatMap((line) => line.spans)
|
||||
.filter((span) => /[▁▂▃▄▅▆▇█]/u.test(span.text))
|
||||
expect(bars.some((span) => span.fg.equals(RGBA.fromHex("#0F766E")))).toBe(true)
|
||||
})
|
||||
|
||||
test("collapses vertically in short terminals and retains data across resize and theme changes", async () => {
|
||||
setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })
|
||||
const panel = new UsagePanel(setup.renderer, theme)
|
||||
setup.renderer.root.add(panel.root)
|
||||
panel.show(snapshot)
|
||||
for (const [width, height, maxPanelHeight] of [[80, 30, 17], [56, 18, 6], [40, 10, 4]] as const) {
|
||||
setup.resize(width, height)
|
||||
panel.resize(width, height)
|
||||
await setup.renderOnce()
|
||||
expect(panel.root.height).toBeLessThanOrEqual(maxPanelHeight)
|
||||
expect(setup.captureCharFrame()).toContain("Context 9k / 262k")
|
||||
expect(setup.captureCharFrame()).toContain("3%")
|
||||
}
|
||||
setup.resize(80, 30)
|
||||
panel.resize(80, 30)
|
||||
panel.setTheme({ ...theme, text: "#18181B", border: "#D4D4D8" })
|
||||
await setup.renderOnce()
|
||||
expect(setup.captureCharFrame()).toContain("Round 3/3 · In 9,000 · Out 800")
|
||||
panel.hide()
|
||||
await setup.renderOnce()
|
||||
expect(setup.captureCharFrame()).not.toContain("Context")
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,214 @@
|
||||
import {
|
||||
BoxRenderable,
|
||||
StyledText,
|
||||
TextAttributes,
|
||||
TextRenderable,
|
||||
parseColor,
|
||||
type CliRenderer,
|
||||
type ColorInput,
|
||||
type TextChunk,
|
||||
} from "@opentui/core"
|
||||
|
||||
import { formatTokenCount } from "./context-panel"
|
||||
import type { SessionUsageSnapshot } from "../client"
|
||||
|
||||
export interface UsagePanelTheme {
|
||||
text: ColorInput
|
||||
muted: ColorInput
|
||||
border: ColorInput
|
||||
accent: ColorInput
|
||||
cached: ColorInput
|
||||
warning: ColorInput
|
||||
error: ColorInput
|
||||
}
|
||||
|
||||
function known(value: number | undefined): value is number {
|
||||
return typeof value === "number" && Number.isFinite(value) && value >= 0
|
||||
}
|
||||
|
||||
function chunk(text: string, color: ColorInput, bold = false): TextChunk {
|
||||
return {
|
||||
__isChunk: true,
|
||||
text,
|
||||
fg: parseColor(color),
|
||||
attributes: bold ? TextAttributes.BOLD : 0,
|
||||
}
|
||||
}
|
||||
|
||||
/** A bounded, read-only view of persisted model-call usage. */
|
||||
export class UsagePanel {
|
||||
readonly root: BoxRenderable
|
||||
private readonly body: TextRenderable
|
||||
private snapshot: SessionUsageSnapshot = { context: null, rounds: [] }
|
||||
private selected = 0
|
||||
private message = ""
|
||||
private width = 68
|
||||
private height = 24
|
||||
|
||||
constructor(renderer: CliRenderer, private theme: UsagePanelTheme) {
|
||||
this.root = new BoxRenderable(renderer, {
|
||||
id: "nanobot-tui-usage-panel",
|
||||
width: "100%",
|
||||
maxWidth: 72,
|
||||
flexShrink: 0,
|
||||
flexDirection: "column",
|
||||
border: true,
|
||||
borderStyle: "rounded",
|
||||
borderColor: theme.border,
|
||||
paddingLeft: 1,
|
||||
paddingRight: 1,
|
||||
visible: false,
|
||||
})
|
||||
this.body = new TextRenderable(renderer, {
|
||||
id: "nanobot-tui-usage-body",
|
||||
width: "100%",
|
||||
content: "",
|
||||
wrapMode: "none",
|
||||
})
|
||||
this.root.add(this.body)
|
||||
}
|
||||
|
||||
get visible(): boolean {
|
||||
return this.root.visible
|
||||
}
|
||||
|
||||
showMessage(message: string): void {
|
||||
this.message = message
|
||||
this.root.visible = true
|
||||
this.render()
|
||||
}
|
||||
|
||||
show(snapshot: SessionUsageSnapshot): void {
|
||||
this.snapshot = snapshot
|
||||
this.selected = Math.max(0, snapshot.rounds.length - 1)
|
||||
this.message = ""
|
||||
this.root.visible = true
|
||||
this.render()
|
||||
}
|
||||
|
||||
hide(): void {
|
||||
this.root.visible = false
|
||||
}
|
||||
|
||||
move(direction: -1 | 1): void {
|
||||
this.selected = Math.max(0, Math.min(this.snapshot.rounds.length - 1, this.selected + direction))
|
||||
this.render()
|
||||
}
|
||||
|
||||
resize(terminalWidth: number, terminalHeight: number): void {
|
||||
// The shell has one column of padding on each side; the panel adds four.
|
||||
this.width = Math.max(1, Math.min(72, terminalWidth - 2) - 4)
|
||||
this.height = terminalHeight
|
||||
this.render()
|
||||
}
|
||||
|
||||
setTheme(theme: UsagePanelTheme): void {
|
||||
this.theme = theme
|
||||
this.root.borderColor = theme.border
|
||||
this.render()
|
||||
}
|
||||
|
||||
private render(): void {
|
||||
if (!this.visible) return
|
||||
const { theme, width } = this
|
||||
const compact = this.height < 20
|
||||
const tiny = this.height < 14
|
||||
const chunks: TextChunk[] = []
|
||||
const line = (text: string, color = theme.text, bold = false) => {
|
||||
chunks.push(chunk(`${text}\n`, color, bold))
|
||||
}
|
||||
const heading = (left: string, right: string) => {
|
||||
line(`${left}${" ".repeat(Math.max(1, width - left.length - right.length))}${right}`)
|
||||
}
|
||||
if (this.message) {
|
||||
line("Usage", theme.accent, true)
|
||||
line(this.message, theme.muted)
|
||||
} else {
|
||||
const context = this.snapshot.context
|
||||
if (context && known(context.tokens)) {
|
||||
const window = context.windowTokens
|
||||
const percent = known(window) && window > 0
|
||||
? Math.min(100, Math.round(context.tokens / window * 100)) : null
|
||||
heading(
|
||||
`Context ${formatTokenCount(context.tokens)} / ${known(window) && window > 0 ? formatTokenCount(window) : "?"}`,
|
||||
percent === null ? "" : `${percent}%`,
|
||||
)
|
||||
if (percent !== null && !compact) {
|
||||
const filled = Math.round(percent / 100 * width)
|
||||
const color = percent >= 90 ? theme.error : percent >= 75 ? theme.warning : theme.muted
|
||||
chunks.push(chunk("━".repeat(filled), color), chunk(`${"─".repeat(width - filled)}\n`, theme.border))
|
||||
}
|
||||
} else {
|
||||
line("Context unavailable", theme.muted)
|
||||
}
|
||||
const rounds = this.snapshot.rounds
|
||||
if (!rounds.length) {
|
||||
line("No model-call usage available yet", theme.muted)
|
||||
} else {
|
||||
if (!compact) line("")
|
||||
const inputs = rounds.map((round) => round.prompt_tokens ?? 0)
|
||||
const max = Math.max(1, ...inputs)
|
||||
if (!tiny) heading(width < 48 ? "Rounds" : "Recent rounds", `Input tokens · max ${formatTokenCount(max)}`)
|
||||
const chartHeight = Math.max(1, Math.min(6, this.height - 18))
|
||||
const slot = Math.max(1, Math.floor(width / rounds.length))
|
||||
const barWidth = Math.min(3, Math.max(1, slot - 1))
|
||||
const blocks = " ▁▂▃▄▅▆▇█"
|
||||
const splitColors = !parseColor(theme.cached).equals(parseColor(theme.accent))
|
||||
const bars = rounds.map((round, index) => {
|
||||
const input = inputs[index] ?? 0
|
||||
const units = Math.max(1, Math.round(input / max * chartHeight * 8))
|
||||
// Quantize both boundaries from token counts, not the rounded bar height.
|
||||
const cachedUnits = known(round.cached_tokens)
|
||||
? Math.min(units, Math.round(Math.min(input, round.cached_tokens) / max * chartHeight * 8))
|
||||
: null
|
||||
return { units, cachedUnits }
|
||||
})
|
||||
for (let row = chartHeight - 1; row >= 0; row -= 1) {
|
||||
bars.forEach(({ units, cachedUnits }) => {
|
||||
const fill = Math.max(0, Math.min(8, units - row * 8))
|
||||
const cachedFill = cachedUnits === null ? null
|
||||
: Math.max(0, Math.min(fill, cachedUnits - row * 8))
|
||||
if (splitColors && fill === 8 && cachedFill !== null && cachedFill > 0 && cachedFill < 8) {
|
||||
const cell = chunk((blocks[cachedFill] ?? " ").repeat(barWidth), theme.cached)
|
||||
cell.bg = parseColor(theme.accent)
|
||||
chunks.push(cell)
|
||||
} else {
|
||||
// A partial top can contain three regions, but a cell has only two
|
||||
// colors. Preserve the empty space and use the larger filled segment.
|
||||
const color = cachedFill === null ? theme.muted
|
||||
: cachedFill > 0 && cachedFill * 2 >= fill ? theme.cached : theme.accent
|
||||
chunks.push(chunk((blocks[fill] ?? " ").repeat(barWidth), color))
|
||||
}
|
||||
chunks.push(chunk(" ".repeat(slot - barWidth), theme.muted))
|
||||
})
|
||||
line("")
|
||||
}
|
||||
const round = rounds[this.selected]
|
||||
if (round && !tiny) {
|
||||
const input = round.prompt_tokens ?? 0
|
||||
const count = (value: number | undefined) => known(value) ? value.toLocaleString("en-US") : "?"
|
||||
line(`${width < 48 ? "" : "Round "}${this.selected + 1}/${rounds.length} · In ${count(input)} · Out ${count(round.completion_tokens)}`)
|
||||
const cache = known(round.cached_tokens)
|
||||
? `${Math.round(Math.min(input, round.cached_tokens) / input * 100)}%` : "?"
|
||||
const time = known(round.generation_ms) ? ` · ${(round.generation_ms / 1000).toFixed(1)}s` : ""
|
||||
if (!compact) {
|
||||
const estimated = known(round.estimated_tokens) && round.estimated_tokens > 0
|
||||
line(`Cache ${cache}${time}${estimated && width >= 48 ? " · includes estimated usage" : ""}`, theme.muted)
|
||||
if (estimated && width < 48) line("Includes estimated usage", theme.muted)
|
||||
}
|
||||
}
|
||||
if (!compact) {
|
||||
chunks.push(
|
||||
chunk("■ ", theme.accent), chunk("Uncached ", theme.muted),
|
||||
chunk("■ ", theme.cached), chunk("Cached ", theme.muted),
|
||||
chunk(width < 48 ? "■ Unknown\n" : "■ Unknown cache\n", theme.muted),
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
// Keep the final newline from reserving an empty row in the retained layout.
|
||||
const last = chunks.at(-1)
|
||||
if (last) last.text = last.text.replace(/\n$/u, "")
|
||||
this.body.content = new StyledText(chunks)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user