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
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
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")
const placeholderStyle = ui.composer.syntaxStyle?.getStyle("image.placeholder")
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")
if (placeholderStyleId === null || placeholderStyleId === undefined) {
throw new Error("image placeholder style was not registered")
@@ -431,7 +431,7 @@ describe("NanobotTui layout", () => {
expect(userContent).toBeInstanceOf(StyledText)
const imageChunk = (userContent as StyledText).chunks.find(({ text }) => text === "[Image #1]")
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("这是什么? ")
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")
})
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" })
let connected = false
setup.renderer.waitForThemeMode = async () => null
@@ -2464,8 +2464,32 @@ describe("NanobotTui layout", () => {
transcript.user("Unknown terminal background")
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")
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 () => {
@@ -2487,6 +2511,7 @@ describe("NanobotTui layout", () => {
expect(turnContrast).toBeLessThan(1.5)
}
setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")
assertContrast()
expect(internals.palette.accent).toBe("#EF8E30")
expect(internals.palette.user).toBe("#EF8E30")
@@ -2613,6 +2638,7 @@ describe("NanobotTui layout", () => {
test("animates one stable status line while the agent works", async () => {
setup = await createRenderer({ width: 88, height: 24, screenMode: "alternate-screen" })
const app = mount(setup)
setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")
app.accept({ event: "attached", chat_id: "chat" })
app.accept({ event: "reasoning_delta", chat_id: "chat", text: "hidden reasoning" })
await Bun.sleep(130)
+48 -23
View File
@@ -9,8 +9,10 @@ import {
createCliRenderer,
decodePasteBytes,
getTreeSitterClient,
parseColor,
stripAnsiSequences,
type CliRenderer,
type ColorInput,
type KeyEvent,
type PasteEvent,
type TextChunk,
@@ -138,19 +140,19 @@ interface ChatClient {
interface Palette {
referenceBackground: string
text: string
muted: string
faint: string
border: string
accent: string
link: string
success: string
warning: string
error: string
user: string
userBackground: string
warm: string
cool: string
text: ColorInput
muted: ColorInput
faint: ColorInput
border: ColorInput
accent: ColorInput
link: ColorInput
success: ColorInput
warning: ColorInput
error: ColorInput
user: ColorInput
userBackground: ColorInput
warm: ColorInput
cool: ColorInput
}
const DARK: Palette = {
@@ -189,6 +191,25 @@ const LIGHT: Palette = {
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 ACTIVE_COMPOSER_PLACEHOLDER = "Enter send now · Tab send next"
const COMPACT_ACTIVE_COMPOSER_PLACEHOLDER = "Enter now · Tab next"
@@ -251,8 +272,8 @@ const LOCAL_COMMANDS: TuiCommand[] = [
]
function syntaxStyle(palette: Palette): SyntaxStyle {
const color = (value: string) => {
const parsed = RGBA.fromHex(value)
const color = (value: ColorInput) => {
const parsed = parseColor(value)
return { fg: parsed }
}
return SyntaxStyle.fromStyles({
@@ -278,7 +299,7 @@ function syntaxStyle(palette: Palette): SyntaxStyle {
function composerSyntaxStyle(palette: Palette): SyntaxStyle {
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,
palette: Palette,
): StyledText {
if (palette === TERMINAL) {
return new StyledText([{ __isChunk: true, text: label + suffix, fg: parseColor(palette.text) }])
}
const chars = Array.from(label)
const base = RGBA.fromHex(palette.muted).toInts()
const highlight = RGBA.fromHex(palette.accent).toInts()
const base = parseColor(palette.muted).toInts()
const highlight = parseColor(palette.accent).toInts()
// Sweep immediately, then leave a quiet pause before repeating. The text
// keeps a constant width throughout, so the footer never jitters.
const position = frame % (chars.length + SHIMMER_PAUSE)
@@ -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)
}
@@ -602,7 +626,8 @@ export class NanobotTui {
this.sessionModelPreset = options.chatId ? undefined : null
this.backgroundKnown = options.theme !== "auto" || renderer.themeMode !== null
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.host = host
this.transcript = new Transcript(
@@ -913,8 +938,8 @@ export class NanobotTui {
this.runtimeControls.preload()
this.renderer.start()
// OpenTUI learns the real terminal background through OSC 10/11. Wait for
// that bounded probe after first paint. The neutral terminal background is
// safe to render immediately, and the detected palette can be applied later.
// that bounded probe after first paint. Terminal-default foreground and
// background keep the first frame readable before a palette is detected.
if (this.options.theme === "auto") await this.renderer.waitForThemeMode(1_000)
if (this.quitting) return
if (this.options.theme === "auto" && this.renderer.themeMode) {
@@ -2195,7 +2220,7 @@ export class NanobotTui {
private composerSurface(): RGBA {
return this.backgroundKnown
? RGBA.fromHex(this.palette.userBackground)
? parseColor(this.palette.userBackground)
: RGBA.defaultBackground()
}
+4 -3
View File
@@ -2,14 +2,15 @@ import {
BoxRenderable,
TextRenderable,
type CliRenderer,
type ColorInput,
} from "@opentui/core"
import type { SessionContextSnapshot } from "./protocol"
export interface ContextPanelTheme {
text: string
border: string
accent: string
text: ColorInput
border: ColorInput
accent: ColorInput
}
export function formatTokenCount(value: number): string {
+9 -8
View File
@@ -7,6 +7,7 @@ import {
TextAttributes,
TextRenderable,
type CliRenderer,
type ColorInput,
type KeyEvent,
type TreeSitterClient,
} from "@opentui/core"
@@ -15,14 +16,14 @@ import type { FileEditEvent, HistoryMessage } from "./protocol"
import { hideScrollbars } from "./scrollbox"
export interface DiffViewerTheme {
text: string
muted: string
border: string
accent: string
success: string
error: string
addedBackground: string | null
removedBackground: string | null
text: ColorInput
muted: ColorInput
border: ColorInput
accent: ColorInput
success: ColorInput
error: ColorInput
addedBackground: ColorInput | null
removedBackground: ColorInput | null
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 {
key: string
@@ -7,10 +7,10 @@ export interface FooterHint {
}
export interface FooterHintTheme {
accent: string
danger: string
muted: string
separator: string
accent: ColorInput
danger: ColorInput
muted: ColorInput
separator: ColorInput
}
export type FooterMode =
@@ -100,11 +100,11 @@ function hint(key: string, label: string): FooterHint {
return { key, label }
}
function chunk(text: string, color: string, bold = false): TextChunk {
function chunk(text: string, color: ColorInput, bold = false): TextChunk {
return {
__isChunk: true,
text,
fg: RGBA.fromHex(color),
fg: parseColor(color),
attributes: bold ? TextAttributes.BOLD : 0,
}
}
+11 -9
View File
@@ -4,17 +4,19 @@ import {
StyledText,
TextAttributes,
TextRenderable,
parseColor,
type CliRenderer,
type ColorInput,
type TextChunk,
} from "@opentui/core"
export interface PickerMenuTheme {
text: string
muted: string
border: string
accent?: string
warning?: string
selectedBackground?: string
text: ColorInput
muted: ColorInput
border: ColorInput
accent?: ColorInput
warning?: ColorInput
selectedBackground?: ColorInput
}
interface PickerMenuOptions<T> {
@@ -169,7 +171,7 @@ export class PickerMenu<T> {
fg: selected ? this.theme.text : this.theme.muted,
selectable: false,
...(selected && this.theme.selectedBackground
? { backgroundColor: RGBA.fromHex(this.theme.selectedBackground) }
? { backgroundColor: parseColor(this.theme.selectedBackground) }
: {}),
attributes: selected ? TextAttributes.BOLD : 0,
onMouseMove: () => {
@@ -197,10 +199,10 @@ export class PickerMenu<T> {
}
}
function chunk(text: string, color: string): TextChunk {
function chunk(text: string, color: ColorInput): TextChunk {
return {
__isChunk: true,
text,
fg: RGBA.fromHex(color),
fg: parseColor(color),
}
}
+7 -5
View File
@@ -4,16 +4,18 @@ import {
StyledText,
TextAttributes,
TextRenderable,
parseColor,
type CliRenderer,
type ColorInput,
type TextChunk,
} from "@opentui/core"
import { optionArrowUp } from "./platform-keys"
export interface QueuePreviewTheme {
accent: string
muted: string
faint: string
accent: ColorInput
muted: ColorInput
faint: ColorInput
}
const MAX_VISIBLE = 3
@@ -89,11 +91,11 @@ function oneLine(value: string): string {
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 {
__isChunk: true,
text,
fg: RGBA.fromHex(color),
fg: parseColor(color),
attributes: bold ? TextAttributes.BOLD : 0,
}
}
+12 -10
View File
@@ -4,19 +4,21 @@ import {
StyledText,
TextAttributes,
TextRenderable,
parseColor,
type CliRenderer,
type ColorInput,
type TextChunk,
} from "@opentui/core"
import type { RecoveryState } from "./protocol"
export interface RecoveryNoticeTheme {
text: string
muted: string
border: string
accent: string
warning: string
error: string
text: ColorInput
muted: ColorInput
border: ColorInput
accent: ColorInput
warning: ColorInput
error: ColorInput
}
interface RecoveryNoticeOptions {
@@ -159,19 +161,19 @@ export class RecoveryNotice {
chunk(title, this.theme.text, true),
])
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.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.resume.attributes = TextAttributes.BOLD
}
}
function chunk(text: string, color: string, bold = false): TextChunk {
function chunk(text: string, color: ColorInput, bold = false): TextChunk {
return {
__isChunk: true,
text,
fg: RGBA.fromHex(color),
fg: parseColor(color),
attributes: bold ? TextAttributes.BOLD : 0,
}
}
+3 -2
View File
@@ -2,6 +2,7 @@ import {
TextRenderable,
type BoxRenderable,
type CliRenderer,
type ColorInput,
type KeyEvent,
} from "@opentui/core"
@@ -13,8 +14,8 @@ import {
import { PickerMenu, type PickerMenuTheme } from "./picker-menu"
interface RuntimeControlsTheme extends PickerMenuTheme {
accent: string
faint: string
accent: ColorInput
faint: ColorInput
}
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 type { SessionSummary } from "./protocol"
@@ -156,7 +156,7 @@ export class SessionMenu {
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)) {
return {
text: "⚠",
@@ -254,11 +254,11 @@ export class SessionMenu {
}
}
function chunk(text: string, color: string): TextChunk {
function chunk(text: string, color: ColorInput): TextChunk {
return {
__isChunk: true,
text,
fg: RGBA.fromHex(color),
fg: parseColor(color),
}
}
+14 -12
View File
@@ -9,7 +9,9 @@ import {
SyntaxStyle,
TextAttributes,
TextRenderable,
parseColor,
type CliRenderer,
type ColorInput,
type TextChunk,
type TreeSitterClient,
} from "@opentui/core"
@@ -26,12 +28,12 @@ import { hideScrollbars } from "./scrollbox"
import { mergeToolEvent, renderToolEvent } from "./tool-renderers"
export interface TranscriptTheme {
text: string
muted: string
error: string
user: string
userBackground: string | null
border: string
text: ColorInput
muted: ColorInput
error: ColorInput
user: ColorInput
userBackground: ColorInput | null
border: ColorInput
syntax: SyntaxStyle
}
@@ -144,7 +146,7 @@ export class Transcript {
private readonly onNavigationChange?: (state: TranscriptNavigation) => void,
private readonly workspace = "",
) {
this.codeRailColor = RGBA.fromHex(theme.border)
this.codeRailColor = parseColor(theme.border)
this.root = new ScrollBoxRenderable(renderer, {
id: "nanobot-tui-transcript",
width: "100%",
@@ -173,7 +175,7 @@ export class Transcript {
setTheme(theme: TranscriptTheme): void {
const previousSyntax = this.theme.syntax
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 { text, phase } of this.compactions.values()) {
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 row of this.userRows) {
row.backgroundColor = theme.userBackground
? RGBA.fromHex(theme.userBackground)
? parseColor(theme.userBackground)
: RGBA.defaultBackground()
}
// 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")
if (tone === "user") {
row.backgroundColor = this.theme.userBackground
? RGBA.fromHex(this.theme.userBackground)
? parseColor(this.theme.userBackground)
: RGBA.defaultBackground()
this.userRows.add(row)
}
@@ -668,7 +670,7 @@ export class Transcript {
chunks.push({
__isChunk: true,
text: label,
fg: RGBA.fromHex(this.theme.user),
fg: parseColor(this.theme.user),
attributes: TextAttributes.BOLD,
})
cursor = start + label.length
@@ -684,7 +686,7 @@ export class Transcript {
chunks.push({
__isChunk: true,
text: label,
fg: RGBA.fromHex(this.theme.user),
fg: parseColor(this.theme.user),
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 type { SessionUsageSnapshot } from "./protocol"
const theme: UsagePanelTheme = {
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: [
@@ -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 () => {
setup = await createTestRenderer({ width: 80, height: 30, screenMode: "alternate-screen" })
const panel = new UsagePanel(setup.renderer, theme)
+14 -12
View File
@@ -1,10 +1,11 @@
import {
BoxRenderable,
RGBA,
StyledText,
TextAttributes,
TextRenderable,
parseColor,
type CliRenderer,
type ColorInput,
type TextChunk,
} from "@opentui/core"
@@ -12,24 +13,24 @@ import { formatTokenCount } from "./context-panel"
import type { SessionUsageSnapshot } from "./protocol"
export interface UsagePanelTheme {
text: string
muted: string
border: string
accent: string
cached: string
warning: string
error: string
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: string, bold = false): TextChunk {
function chunk(text: string, color: ColorInput, bold = false): TextChunk {
return {
__isChunk: true,
text,
fg: RGBA.fromHex(color),
fg: parseColor(color),
attributes: bold ? TextAttributes.BOLD : 0,
}
}
@@ -152,6 +153,7 @@ export class UsagePanel {
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))
@@ -166,9 +168,9 @@ export class UsagePanel {
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 (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)
cell.bg = RGBA.fromHex(theme.accent)
cell.bg = parseColor(theme.accent)
chunks.push(cell)
} else {
// A partial top can contain three regions, but a cell has only two