fix(tui): preserve readability when terminal theme is unknown

This commit is contained in:
chengyongru authored and chengyongru committed 2026-09-29 11:28:53 +08:00
1 parent 4f7479ca64
commit cf25e91b17
14 files changed
+185 -101

No files matched your search

+5
View File
@@ -17,6 +17,11 @@ Assistant math written with `$...$`, `$$...$$`, `\\(...\\)`, or `\\[...\\]` is p
Unicode plain text so formulas remain readable in terminals without a math renderer. Currency and Unicode plain text so formulas remain readable in terminals without a math renderer. Currency and
LaTeX inside inline or fenced code remain literal. LaTeX inside inline or fenced code remain literal.
Automatic theme selection follows the terminal's OSC 10/11 responses. Until a response
arrives, the TUI uses the terminal's default foreground and background without semantic
colors or color animations. Terminals that do not answer keep this readable fallback.
Use `nanobot --theme light` or `nanobot --theme dark` to select a color palette explicitly.
## Herdr pane titles ## Herdr pane titles
When Herdr supplies `HERDR_ENV=1` and `HERDR_PANE_ID`, nanobot keeps the same full-screen layout, controls, and navigation available in any other terminal. Its only host-specific behavior is reporting the latest user task as the Herdr pane title through the supported pane CLI. Creating a new chat, switching to a chat without a task, and exiting the TUI clear that title. Nanobot does not report agent lifecycle, session, model, Git branch, workspace, or action metadata to Herdr. When Herdr supplies `HERDR_ENV=1` and `HERDR_PANE_ID`, nanobot keeps the same full-screen layout, controls, and navigation available in any other terminal. Its only host-specific behavior is reporting the latest user task as the Herdr pane title through the supported pane CLI. Creating a new chat, switching to a chat without a task, and exiting the TUI clear that title. Nanobot does not report agent lifecycle, session, model, Git branch, workspace, or action metadata to Herdr.
+30 -4
View File
@@ -391,7 +391,7 @@ describe("NanobotTui layout", () => {
expect(ui.status.plainText).toContain("Pasted Image #1") expect(ui.status.plainText).toContain("Pasted Image #1")
const placeholderStyle = ui.composer.syntaxStyle?.getStyle("image.placeholder") const placeholderStyle = ui.composer.syntaxStyle?.getStyle("image.placeholder")
expect(placeholderStyle?.bold).toBeTrue() expect(placeholderStyle?.bold).toBeTrue()
expect(placeholderStyle?.fg?.toInts().slice(0, 3)).toEqual([239, 142, 48]) expect(placeholderStyle?.fg?.intent).toBe("default")
const placeholderStyleId = ui.composer.syntaxStyle?.getStyleId("image.placeholder") const placeholderStyleId = ui.composer.syntaxStyle?.getStyleId("image.placeholder")
if (placeholderStyleId === null || placeholderStyleId === undefined) { if (placeholderStyleId === null || placeholderStyleId === undefined) {
throw new Error("image placeholder style was not registered") throw new Error("image placeholder style was not registered")
@@ -431,7 +431,7 @@ describe("NanobotTui layout", () => {
expect(userContent).toBeInstanceOf(StyledText) expect(userContent).toBeInstanceOf(StyledText)
const imageChunk = (userContent as StyledText).chunks.find(({ text }) => text === "[Image #1]") const imageChunk = (userContent as StyledText).chunks.find(({ text }) => text === "[Image #1]")
expect(imageChunk?.attributes).toBe(TextAttributes.BOLD) expect(imageChunk?.attributes).toBe(TextAttributes.BOLD)
expect(imageChunk?.fg?.toInts().slice(0, 3)).toEqual([239, 142, 48]) expect(imageChunk?.fg?.intent).toBe("default")
await setup.mockInput.typeText("这是什么? ") await setup.mockInput.typeText("这是什么? ")
setup.mockInput.pressKey("v", { ctrl: true }) setup.mockInput.pressKey("v", { ctrl: true })
@@ -2439,7 +2439,7 @@ describe("NanobotTui layout", () => {
expect((app as unknown as { palette: { referenceBackground: string } }).palette.referenceBackground).toBe("#FAFAFA") expect((app as unknown as { palette: { referenceBackground: string } }).palette.referenceBackground).toBe("#FAFAFA")
}) })
test("falls back to the dark palette when terminal theme probing has no answer", async () => { test.each(["dark", "light"] as const)("uses terminal defaults until a late %s theme response", async (mode) => {
setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" }) setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })
let connected = false let connected = false
setup.renderer.waitForThemeMode = async () => null setup.renderer.waitForThemeMode = async () => null
@@ -2464,8 +2464,32 @@ describe("NanobotTui layout", () => {
transcript.user("Unknown terminal background") transcript.user("Unknown terminal background")
expect(connected).toBe(true) expect(connected).toBe(true)
expect((app as unknown as { palette: { referenceBackground: string } }).palette.referenceBackground).toBe("#0E0F11") const ui = app as unknown as { composer: TextareaRenderable; status: TextRenderable }
expect(ui.composer.textColor.intent).toBe("default")
expect(ui.composer.backgroundColor.intent).toBe("default")
expect([...transcript.userRows][0]?.backgroundColor.intent).toBe("default") expect([...transcript.userRows][0]?.backgroundColor.intent).toBe("default")
app.accept({ event: "delta", chat_id: "chat", text: "Readable answer" })
app.accept({ event: "stream_end", chat_id: "chat" })
await setup.flush()
expect(setup.captureCharFrame()).toContain("Readable answer")
for (const line of setup.captureSpans().lines) {
for (const span of line.spans) {
if (span.text.trim()) expect(span.fg.intent).toBe("default")
}
}
// Active status must not turn the default color into guessed RGB shimmer colors.
app.accept({ event: "reasoning_delta", chat_id: "chat", text: "thinking" })
await setup.flush()
for (const chunk of (ui.status.content as StyledText).chunks) {
expect(chunk.fg?.intent).toBe("default")
}
setup.renderer.emit(CliRenderEvents.THEME_MODE, mode)
await setup.flush()
expect(ui.composer.textColor.intent).toBe("rgb")
expect(ui.composer.textColor.toInts().slice(0, 3)).toEqual(
mode === "light" ? [24, 24, 27] : [236, 237, 238],
)
expect([...transcript.userRows][0]?.backgroundColor.intent).toBe("rgb")
}) })
test("keeps semantic colors legible in both terminal appearances", async () => { test("keeps semantic colors legible in both terminal appearances", async () => {
@@ -2487,6 +2511,7 @@ describe("NanobotTui layout", () => {
expect(turnContrast).toBeLessThan(1.5) expect(turnContrast).toBeLessThan(1.5)
} }
setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")
assertContrast() assertContrast()
expect(internals.palette.accent).toBe("#EF8E30") expect(internals.palette.accent).toBe("#EF8E30")
expect(internals.palette.user).toBe("#EF8E30") expect(internals.palette.user).toBe("#EF8E30")
@@ -2613,6 +2638,7 @@ describe("NanobotTui layout", () => {
test("animates one stable status line while the agent works", async () => { test("animates one stable status line while the agent works", async () => {
setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" }) setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })
const app = mount(setup) const app = mount(setup)
setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")
app.accept({ event: "attached", chat_id: "chat" }) app.accept({ event: "attached", chat_id: "chat" })
app.accept({ event: "reasoning_delta", chat_id: "chat", text: "hidden reasoning" }) app.accept({ event: "reasoning_delta", chat_id: "chat", text: "hidden reasoning" })
await Bun.sleep(130) await Bun.sleep(130)
+48 -23
View File
@@ -9,8 +9,10 @@ import {
createCliRenderer, createCliRenderer,
decodePasteBytes, decodePasteBytes,
getTreeSitterClient, getTreeSitterClient,
parseColor,
stripAnsiSequences, stripAnsiSequences,
type CliRenderer, type CliRenderer,
type ColorInput,
type KeyEvent, type KeyEvent,
type PasteEvent, type PasteEvent,
type TextChunk, type TextChunk,
@@ -138,19 +140,19 @@ interface ChatClient {
interface Palette { interface Palette {
referenceBackground: string referenceBackground: string
text: string text: ColorInput
muted: string muted: ColorInput
faint: string faint: ColorInput
border: string border: ColorInput
accent: string accent: ColorInput
link: string link: ColorInput
success: string success: ColorInput
warning: string warning: ColorInput
error: string error: ColorInput
user: string user: ColorInput
userBackground: string userBackground: ColorInput
warm: string warm: ColorInput
cool: string cool: ColorInput
} }
const DARK: Palette = { const DARK: Palette = {
@@ -189,6 +191,25 @@ const LIGHT: Palette = {
cool: "#0F766E", cool: "#0F766E",
} }
// Until the terminal answers OSC 10/11, its default foreground is the only
// text color known to match its default background.
const TERMINAL: Palette = {
...DARK,
text: RGBA.defaultForeground(),
muted: RGBA.defaultForeground(),
faint: RGBA.defaultForeground(),
border: RGBA.defaultForeground(),
accent: RGBA.defaultForeground(),
link: RGBA.defaultForeground(),
success: RGBA.defaultForeground(),
warning: RGBA.defaultForeground(),
error: RGBA.defaultForeground(),
user: RGBA.defaultForeground(),
userBackground: RGBA.defaultBackground(),
warm: RGBA.defaultForeground(),
cool: RGBA.defaultForeground(),
}
const COMPOSER_PLACEHOLDER = "Ask nanobot anything" const COMPOSER_PLACEHOLDER = "Ask nanobot anything"
const ACTIVE_COMPOSER_PLACEHOLDER = "Enter send now · Tab send next" const ACTIVE_COMPOSER_PLACEHOLDER = "Enter send now · Tab send next"
const COMPACT_ACTIVE_COMPOSER_PLACEHOLDER = "Enter now · Tab next" const COMPACT_ACTIVE_COMPOSER_PLACEHOLDER = "Enter now · Tab next"
@@ -251,8 +272,8 @@ const LOCAL_COMMANDS: TuiCommand[] = [
] ]
function syntaxStyle(palette: Palette): SyntaxStyle { function syntaxStyle(palette: Palette): SyntaxStyle {
const color = (value: string) => { const color = (value: ColorInput) => {
const parsed = RGBA.fromHex(value) const parsed = parseColor(value)
return { fg: parsed } return { fg: parsed }
} }
return SyntaxStyle.fromStyles({ return SyntaxStyle.fromStyles({
@@ -278,7 +299,7 @@ function syntaxStyle(palette: Palette): SyntaxStyle {
function composerSyntaxStyle(palette: Palette): SyntaxStyle { function composerSyntaxStyle(palette: Palette): SyntaxStyle {
return SyntaxStyle.fromStyles({ return SyntaxStyle.fromStyles({
[IMAGE_PLACEHOLDER_STYLE]: { fg: RGBA.fromHex(palette.accent), bold: true }, [IMAGE_PLACEHOLDER_STYLE]: { fg: parseColor(palette.accent), bold: true },
}) })
} }
@@ -374,9 +395,12 @@ function shimmerStatus(
frame: number, frame: number,
palette: Palette, palette: Palette,
): StyledText { ): StyledText {
if (palette === TERMINAL) {
return new StyledText([{ __isChunk: true, text: label + suffix, fg: parseColor(palette.text) }])
}
const chars = Array.from(label) const chars = Array.from(label)
const base = RGBA.fromHex(palette.muted).toInts() const base = parseColor(palette.muted).toInts()
const highlight = RGBA.fromHex(palette.accent).toInts() const highlight = parseColor(palette.accent).toInts()
// Sweep immediately, then leave a quiet pause before repeating. The text // Sweep immediately, then leave a quiet pause before repeating. The text
// keeps a constant width throughout, so the footer never jitters. // keeps a constant width throughout, so the footer never jitters.
const position = frame % (chars.length + SHIMMER_PAUSE) const position = frame % (chars.length + SHIMMER_PAUSE)
@@ -395,7 +419,7 @@ function shimmerStatus(
), ),
} }
}) })
chunks.push({ __isChunk: true, text: suffix, fg: RGBA.fromHex(palette.muted) }) chunks.push({ __isChunk: true, text: suffix, fg: parseColor(palette.muted) })
return new StyledText(chunks) return new StyledText(chunks)
} }
@@ -602,7 +626,8 @@ export class NanobotTui {
this.sessionModelPreset = options.chatId ? undefined : null this.sessionModelPreset = options.chatId ? undefined : null
this.backgroundKnown = options.theme !== "auto" || renderer.themeMode !== null this.backgroundKnown = options.theme !== "auto" || renderer.themeMode !== null
this.activeThemeMode = this.resolveThemeMode(renderer.themeMode) this.activeThemeMode = this.resolveThemeMode(renderer.themeMode)
this.palette = this.activeThemeMode === "light" ? LIGHT : DARK this.palette = !this.backgroundKnown ? TERMINAL
: this.activeThemeMode === "light" ? LIGHT : DARK
this.composerSyntax = composerSyntaxStyle(this.palette) this.composerSyntax = composerSyntaxStyle(this.palette)
this.host = host this.host = host
this.transcript = new Transcript( this.transcript = new Transcript(
@@ -913,8 +938,8 @@ export class NanobotTui {
this.runtimeControls.preload() this.runtimeControls.preload()
this.renderer.start() this.renderer.start()
// OpenTUI learns the real terminal background through OSC 10/11. Wait for // OpenTUI learns the real terminal background through OSC 10/11. Wait for
// that bounded probe after first paint. The neutral terminal background is // that bounded probe after first paint. Terminal-default foreground and
// safe to render immediately, and the detected palette can be applied later. // background keep the first frame readable before a palette is detected.
if (this.options.theme === "auto") await this.renderer.waitForThemeMode(1_000) if (this.options.theme === "auto") await this.renderer.waitForThemeMode(1_000)
if (this.quitting) return if (this.quitting) return
if (this.options.theme === "auto" && this.renderer.themeMode) { if (this.options.theme === "auto" && this.renderer.themeMode) {
@@ -2195,7 +2220,7 @@ export class NanobotTui {
private composerSurface(): RGBA { private composerSurface(): RGBA {
return this.backgroundKnown return this.backgroundKnown
? RGBA.fromHex(this.palette.userBackground) ? parseColor(this.palette.userBackground)
: RGBA.defaultBackground() : RGBA.defaultBackground()
} }
+4 -3
View File
@@ -2,14 +2,15 @@ import {
BoxRenderable, BoxRenderable,
TextRenderable, TextRenderable,
type CliRenderer, type CliRenderer,
type ColorInput,
} from "@opentui/core" } from "@opentui/core"
import type { SessionContextSnapshot } from "./protocol" import type { SessionContextSnapshot } from "./protocol"
export interface ContextPanelTheme { export interface ContextPanelTheme {
text: string text: ColorInput
border: string border: ColorInput
accent: string accent: ColorInput
} }
export function formatTokenCount(value: number): string { export function formatTokenCount(value: number): string {
+9 -8
View File
@@ -7,6 +7,7 @@ import {
TextAttributes, TextAttributes,
TextRenderable, TextRenderable,
type CliRenderer, type CliRenderer,
type ColorInput,
type KeyEvent, type KeyEvent,
type TreeSitterClient, type TreeSitterClient,
} from "@opentui/core" } from "@opentui/core"
@@ -15,14 +16,14 @@ import type { FileEditEvent, HistoryMessage } from "./protocol"
import { hideScrollbars } from "./scrollbox" import { hideScrollbars } from "./scrollbox"
export interface DiffViewerTheme { export interface DiffViewerTheme {
text: string text: ColorInput
muted: string muted: ColorInput
border: string border: ColorInput
accent: string accent: ColorInput
success: string success: ColorInput
error: string error: ColorInput
addedBackground: string | null addedBackground: ColorInput | null
removedBackground: string | null removedBackground: ColorInput | null
syntax: SyntaxStyle syntax: SyntaxStyle
} }
+7 -7
View File
@@ -1,4 +1,4 @@
import { RGBA, StyledText, TextAttributes, type TextChunk } from "@opentui/core" import { StyledText, TextAttributes, parseColor, type ColorInput, type TextChunk } from "@opentui/core"
export interface FooterHint { export interface FooterHint {
key: string key: string
@@ -7,10 +7,10 @@ export interface FooterHint {
} }
export interface FooterHintTheme { export interface FooterHintTheme {
accent: string accent: ColorInput
danger: string danger: ColorInput
muted: string muted: ColorInput
separator: string separator: ColorInput
} }
export type FooterMode = export type FooterMode =
@@ -100,11 +100,11 @@ function hint(key: string, label: string): FooterHint {
return { key, label } return { key, label }
} }
function chunk(text: string, color: string, bold = false): TextChunk { function chunk(text: string, color: ColorInput, bold = false): TextChunk {
return { return {
__isChunk: true, __isChunk: true,
text, text,
fg: RGBA.fromHex(color), fg: parseColor(color),
attributes: bold ? TextAttributes.BOLD : 0, attributes: bold ? TextAttributes.BOLD : 0,
} }
} }
+11 -9
View File
@@ -4,17 +4,19 @@ import {
StyledText, StyledText,
TextAttributes, TextAttributes,
TextRenderable, TextRenderable,
parseColor,
type CliRenderer, type CliRenderer,
type ColorInput,
type TextChunk, type TextChunk,
} from "@opentui/core" } from "@opentui/core"
export interface PickerMenuTheme { export interface PickerMenuTheme {
text: string text: ColorInput
muted: string muted: ColorInput
border: string border: ColorInput
accent?: string accent?: ColorInput
warning?: string warning?: ColorInput
selectedBackground?: string selectedBackground?: ColorInput
} }
interface PickerMenuOptions<T> { interface PickerMenuOptions<T> {
@@ -169,7 +171,7 @@ export class PickerMenu<T> {
fg: selected ? this.theme.text : this.theme.muted, fg: selected ? this.theme.text : this.theme.muted,
selectable: false, selectable: false,
...(selected && this.theme.selectedBackground ...(selected && this.theme.selectedBackground
? { backgroundColor: RGBA.fromHex(this.theme.selectedBackground) } ? { backgroundColor: parseColor(this.theme.selectedBackground) }
: {}), : {}),
attributes: selected ? TextAttributes.BOLD : 0, attributes: selected ? TextAttributes.BOLD : 0,
onMouseMove: () => { onMouseMove: () => {
@@ -197,10 +199,10 @@ export class PickerMenu<T> {
} }
} }
function chunk(text: string, color: string): TextChunk { function chunk(text: string, color: ColorInput): TextChunk {
return { return {
__isChunk: true, __isChunk: true,
text, text,
fg: RGBA.fromHex(color), fg: parseColor(color),
} }
} }
+7 -5
View File
@@ -4,16 +4,18 @@ import {
StyledText, StyledText,
TextAttributes, TextAttributes,
TextRenderable, TextRenderable,
parseColor,
type CliRenderer, type CliRenderer,
type ColorInput,
type TextChunk, type TextChunk,
} from "@opentui/core" } from "@opentui/core"
import { optionArrowUp } from "./platform-keys" import { optionArrowUp } from "./platform-keys"
export interface QueuePreviewTheme { export interface QueuePreviewTheme {
accent: string accent: ColorInput
muted: string muted: ColorInput
faint: string faint: ColorInput
} }
const MAX_VISIBLE = 3 const MAX_VISIBLE = 3
@@ -89,11 +91,11 @@ function oneLine(value: string): string {
return value.length > 240 ? `${preview}…` : preview return value.length > 240 ? `${preview}…` : preview
} }
function chunk(text: string, color: string, bold = false): TextChunk { function chunk(text: string, color: ColorInput, bold = false): TextChunk {
return { return {
__isChunk: true, __isChunk: true,
text, text,
fg: RGBA.fromHex(color), fg: parseColor(color),
attributes: bold ? TextAttributes.BOLD : 0, attributes: bold ? TextAttributes.BOLD : 0,
} }
} }
+12 -10
View File
@@ -4,19 +4,21 @@ import {
StyledText, StyledText,
TextAttributes, TextAttributes,
TextRenderable, TextRenderable,
parseColor,
type CliRenderer, type CliRenderer,
type ColorInput,
type TextChunk, type TextChunk,
} from "@opentui/core" } from "@opentui/core"
import type { RecoveryState } from "./protocol" import type { RecoveryState } from "./protocol"
export interface RecoveryNoticeTheme { export interface RecoveryNoticeTheme {
text: string text: ColorInput
muted: string muted: ColorInput
border: string border: ColorInput
accent: string accent: ColorInput
warning: string warning: ColorInput
error: string error: ColorInput
} }
interface RecoveryNoticeOptions { interface RecoveryNoticeOptions {
@@ -159,19 +161,19 @@ export class RecoveryNotice {
chunk(title, this.theme.text, true), chunk(title, this.theme.text, true),
]) ])
this.detail.content = new StyledText([chunk(` ${detail}`, this.theme.muted)]) this.detail.content = new StyledText([chunk(` ${detail}`, this.theme.muted)])
this.dismiss.fg = RGBA.fromHex(this.busy ? this.theme.muted : this.theme.text) this.dismiss.fg = parseColor(this.busy ? this.theme.muted : this.theme.text)
this.resume.visible = !contextUnavailable this.resume.visible = !contextUnavailable
this.resume.fg = RGBA.fromHex(this.busy ? this.theme.muted : this.theme.accent) this.resume.fg = parseColor(this.busy ? this.theme.muted : this.theme.accent)
this.dismiss.attributes = 0 this.dismiss.attributes = 0
this.resume.attributes = TextAttributes.BOLD this.resume.attributes = TextAttributes.BOLD
} }
} }
function chunk(text: string, color: string, bold = false): TextChunk { function chunk(text: string, color: ColorInput, bold = false): TextChunk {
return { return {
__isChunk: true, __isChunk: true,
text, text,
fg: RGBA.fromHex(color), fg: parseColor(color),
attributes: bold ? TextAttributes.BOLD : 0, attributes: bold ? TextAttributes.BOLD : 0,
} }
} }
+3 -2
View File
@@ -2,6 +2,7 @@ import {
TextRenderable, TextRenderable,
type BoxRenderable, type BoxRenderable,
type CliRenderer, type CliRenderer,
type ColorInput,
type KeyEvent, type KeyEvent,
} from "@opentui/core" } from "@opentui/core"
@@ -13,8 +14,8 @@ import {
import { PickerMenu, type PickerMenuTheme } from "./picker-menu" import { PickerMenu, type PickerMenuTheme } from "./picker-menu"
interface RuntimeControlsTheme extends PickerMenuTheme { interface RuntimeControlsTheme extends PickerMenuTheme {
accent: string accent: ColorInput
faint: string faint: ColorInput
} }
type Choice = type Choice =
+4 -4
View File
@@ -1,4 +1,4 @@
import { RGBA, type BoxRenderable, type CliRenderer, type TextChunk } from "@opentui/core" import { parseColor, type ColorInput, type BoxRenderable, type CliRenderer, type TextChunk } from "@opentui/core"
import { PickerMenu, type PickerMenuTheme } from "./picker-menu" import { PickerMenu, type PickerMenuTheme } from "./picker-menu"
import type { SessionSummary } from "./protocol" import type { SessionSummary } from "./protocol"
@@ -156,7 +156,7 @@ export class SessionMenu {
this.picker.setTheme(theme) this.picker.setTheme(theme)
} }
private marker(session: SessionMenuRow): { text: string; color: string } | null { private marker(session: SessionMenuRow): { text: string; color: ColorInput } | null {
if (this.interrupted(session)) { if (this.interrupted(session)) {
return { return {
text: "⚠", text: "⚠",
@@ -254,11 +254,11 @@ export class SessionMenu {
} }
} }
function chunk(text: string, color: string): TextChunk { function chunk(text: string, color: ColorInput): TextChunk {
return { return {
__isChunk: true, __isChunk: true,
text, text,
fg: RGBA.fromHex(color), fg: parseColor(color),
} }
} }
+14 -12
View File
@@ -9,7 +9,9 @@ import {
SyntaxStyle, SyntaxStyle,
TextAttributes, TextAttributes,
TextRenderable, TextRenderable,
parseColor,
type CliRenderer, type CliRenderer,
type ColorInput,
type TextChunk, type TextChunk,
type TreeSitterClient, type TreeSitterClient,
} from "@opentui/core" } from "@opentui/core"
@@ -26,12 +28,12 @@ import { hideScrollbars } from "./scrollbox"
import { mergeToolEvent, renderToolEvent } from "./tool-renderers" import { mergeToolEvent, renderToolEvent } from "./tool-renderers"
export interface TranscriptTheme { export interface TranscriptTheme {
text: string text: ColorInput
muted: string muted: ColorInput
error: string error: ColorInput
user: string user: ColorInput
userBackground: string | null userBackground: ColorInput | null
border: string border: ColorInput
syntax: SyntaxStyle syntax: SyntaxStyle
} }
@@ -144,7 +146,7 @@ export class Transcript {
private readonly onNavigationChange?: (state: TranscriptNavigation) => void, private readonly onNavigationChange?: (state: TranscriptNavigation) => void,
private readonly workspace = "", private readonly workspace = "",
) { ) {
this.codeRailColor = RGBA.fromHex(theme.border) this.codeRailColor = parseColor(theme.border)
this.root = new ScrollBoxRenderable(renderer, { this.root = new ScrollBoxRenderable(renderer, {
id: "nanobot-tui-transcript", id: "nanobot-tui-transcript",
width: "100%", width: "100%",
@@ -173,7 +175,7 @@ export class Transcript {
setTheme(theme: TranscriptTheme): void { setTheme(theme: TranscriptTheme): void {
const previousSyntax = this.theme.syntax const previousSyntax = this.theme.syntax
this.theme = theme this.theme = theme
this.codeRailColor = RGBA.fromHex(theme.border) this.codeRailColor = parseColor(theme.border)
for (const { renderable, tone } of this.styledText) renderable.fg = theme[tone] for (const { renderable, tone } of this.styledText) renderable.fg = theme[tone]
for (const { text, phase } of this.compactions.values()) { for (const { text, phase } of this.compactions.values()) {
text.fg = phase === "failed" ? theme.error : theme.muted text.fg = phase === "failed" ? theme.error : theme.muted
@@ -192,7 +194,7 @@ export class Transcript {
for (const frame of this.frames) frame.borderColor = theme.border for (const frame of this.frames) frame.borderColor = theme.border
for (const row of this.userRows) { for (const row of this.userRows) {
row.backgroundColor = theme.userBackground row.backgroundColor = theme.userBackground
? RGBA.fromHex(theme.userBackground) ? parseColor(theme.userBackground)
: RGBA.defaultBackground() : RGBA.defaultBackground()
} }
// Markdown may still be rendering this frame. Release the prior native // Markdown may still be rendering this frame. Release the prior native
@@ -609,7 +611,7 @@ export class Transcript {
const row = this.createRow(tone === "user" ? "user" : "notice", "row") const row = this.createRow(tone === "user" ? "user" : "notice", "row")
if (tone === "user") { if (tone === "user") {
row.backgroundColor = this.theme.userBackground row.backgroundColor = this.theme.userBackground
? RGBA.fromHex(this.theme.userBackground) ? parseColor(this.theme.userBackground)
: RGBA.defaultBackground() : RGBA.defaultBackground()
this.userRows.add(row) this.userRows.add(row)
} }
@@ -668,7 +670,7 @@ export class Transcript {
chunks.push({ chunks.push({
__isChunk: true, __isChunk: true,
text: label, text: label,
fg: RGBA.fromHex(this.theme.user), fg: parseColor(this.theme.user),
attributes: TextAttributes.BOLD, attributes: TextAttributes.BOLD,
}) })
cursor = start + label.length cursor = start + label.length
@@ -684,7 +686,7 @@ export class Transcript {
chunks.push({ chunks.push({
__isChunk: true, __isChunk: true,
text: label, text: label,
fg: RGBA.fromHex(this.theme.user), fg: parseColor(this.theme.user),
attributes: TextAttributes.BOLD, attributes: TextAttributes.BOLD,
}) })
} }
+17 -2
View File
@@ -5,10 +5,10 @@ import { createTestRenderer, type TestRendererSetup } from "@opentui/core/testin
import { UsagePanel, type UsagePanelTheme } from "./usage-panel" import { UsagePanel, type UsagePanelTheme } from "./usage-panel"
import type { SessionUsageSnapshot } from "./protocol" import type { SessionUsageSnapshot } from "./protocol"
const theme: UsagePanelTheme = { const theme = {
text: "#ECEDEE", muted: "#A1A1AA", border: "#3F3F46", accent: "#EF8E30", text: "#ECEDEE", muted: "#A1A1AA", border: "#3F3F46", accent: "#EF8E30",
cached: "#1795A2", warning: "#F5C451", error: "#F87171", cached: "#1795A2", warning: "#F5C451", error: "#F87171",
} } satisfies UsagePanelTheme
const snapshot: SessionUsageSnapshot = { const snapshot: SessionUsageSnapshot = {
context: { tokens: 9_000, windowTokens: 262_144 }, context: { tokens: 9_000, windowTokens: 262_144 },
rounds: [ rounds: [
@@ -83,6 +83,21 @@ describe("UsagePanel", () => {
} }
}) })
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 () => { 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" }) setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })
const panel = new UsagePanel(setup.renderer, theme) const panel = new UsagePanel(setup.renderer, theme)
+14 -12
View File
@@ -1,10 +1,11 @@
import { import {
BoxRenderable, BoxRenderable,
RGBA,
StyledText, StyledText,
TextAttributes, TextAttributes,
TextRenderable, TextRenderable,
parseColor,
type CliRenderer, type CliRenderer,
type ColorInput,
type TextChunk, type TextChunk,
} from "@opentui/core" } from "@opentui/core"
@@ -12,24 +13,24 @@ import { formatTokenCount } from "./context-panel"
import type { SessionUsageSnapshot } from "./protocol" import type { SessionUsageSnapshot } from "./protocol"
export interface UsagePanelTheme { export interface UsagePanelTheme {
text: string text: ColorInput
muted: string muted: ColorInput
border: string border: ColorInput
accent: string accent: ColorInput
cached: string cached: ColorInput
warning: string warning: ColorInput
error: string error: ColorInput
} }
function known(value: number | undefined): value is number { function known(value: number | undefined): value is number {
return typeof value === "number" && Number.isFinite(value) && value >= 0 return typeof value === "number" && Number.isFinite(value) && value >= 0
} }
function chunk(text: string, color: string, bold = false): TextChunk { function chunk(text: string, color: ColorInput, bold = false): TextChunk {
return { return {
__isChunk: true, __isChunk: true,
text, text,
fg: RGBA.fromHex(color), fg: parseColor(color),
attributes: bold ? TextAttributes.BOLD : 0, attributes: bold ? TextAttributes.BOLD : 0,
} }
} }
@@ -152,6 +153,7 @@ export class UsagePanel {
const slot = Math.max(1, Math.floor(width / rounds.length)) const slot = Math.max(1, Math.floor(width / rounds.length))
const barWidth = Math.min(3, Math.max(1, slot - 1)) const barWidth = Math.min(3, Math.max(1, slot - 1))
const blocks = " ▁▂▃▄▅▆▇█" const blocks = " ▁▂▃▄▅▆▇█"
const splitColors = !parseColor(theme.cached).equals(parseColor(theme.accent))
const bars = rounds.map((round, index) => { const bars = rounds.map((round, index) => {
const input = inputs[index] ?? 0 const input = inputs[index] ?? 0
const units = Math.max(1, Math.round(input / max * chartHeight * 8)) const units = Math.max(1, Math.round(input / max * chartHeight * 8))
@@ -166,9 +168,9 @@ export class UsagePanel {
const fill = Math.max(0, Math.min(8, units - row * 8)) const fill = Math.max(0, Math.min(8, units - row * 8))
const cachedFill = cachedUnits === null ? null const cachedFill = cachedUnits === null ? null
: Math.max(0, Math.min(fill, cachedUnits - row * 8)) : Math.max(0, Math.min(fill, cachedUnits - row * 8))
if (fill === 8 && cachedFill !== null && cachedFill > 0 && cachedFill < 8) { if (splitColors && fill === 8 && cachedFill !== null && cachedFill > 0 && cachedFill < 8) {
const cell = chunk((blocks[cachedFill] ?? " ").repeat(barWidth), theme.cached) const cell = chunk((blocks[cachedFill] ?? " ").repeat(barWidth), theme.cached)
cell.bg = RGBA.fromHex(theme.accent) cell.bg = parseColor(theme.accent)
chunks.push(cell) chunks.push(cell)
} else { } else {
// A partial top can contain three regions, but a cell has only two // A partial top can contain three regions, but a cell has only two