fix(ui): keep theme text and selections readable (#6226)

* fix(ui): keep theme text and selections readable

* fix(tui): theme the blank composer cursor cell

* refactor(webui): centralize diff theme colors

* fix(tui): keep conversation selections readable

* fix(ui): preserve nested syntax colors and selection lifetimes
This commit is contained in:
chengyongru authored and GitHub committed 2026-10-15 15:21:28 +08:00
1 parent 73c2441abc
commit c24153db86
32 files changed
+451 -165

No files matched your search

+7
View File
@@ -90,6 +90,7 @@ import {
} from "../views/footer-hints"
import { copyWithSystemClipboard } from "../platform/clipboard"
import { configureOpenTuiEnvironment, createTuiHost, type TuiHost } from "../platform/host"
import { applySelectionColors } from "../platform/selection"
import { LOCAL_COMMANDS } from "./commands"
import { CooperativeEventQueue } from "./event-queue"
import {
@@ -404,6 +405,10 @@ export class NanobotTui {
this.status = layout.status
this.meta = layout.meta
this.renderer.root.add(this.shell)
this.shell.renderBefore = () => {
const selection = this.renderer.getSelection()
if (selection) applySelectionColors(selection, this.palette.selection)
}
this.renderer.keyInput.on("keypress", this.handleKey)
this.renderer.on(CliRenderEvents.THEME_MODE, this.handleTheme)
@@ -1729,6 +1734,8 @@ export class NanobotTui {
this.composerFrame.borderColor = this.palette.accent
this.composer.backgroundColor = surface
this.composer.focusedBackgroundColor = surface
this.composer.selectionBg = this.palette.selection.background
this.composer.selectionFg = this.palette.selection.foreground
this.composer.placeholderColor = this.palette.muted
}
+121 -8
View File
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, test } from "bun:test"
import { BoxRenderable, CliRenderEvents, StyledText, TextareaRenderable, TextAttributes, TextRenderable } from "@opentui/core"
import { BoxRenderable, CliRenderEvents, StyledText, TextareaRenderable, TextAttributes, TextRenderable, rgbToHex } from "@opentui/core"
import { MockTreeSitterClient, TestRecorder, setRendererCapabilities, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"
import { NanobotTui } from "./app"
import type { Transcript } from "../rendering/transcript"
@@ -515,7 +515,7 @@ describe("NanobotTui layout and themes", () => {
expect(internals.composerFrame.borderColor.toInts().slice(0, 3)).toEqual([185, 77, 11])
expect(internals.composerFrame.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])
expect(internals.composer.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240])
expect(internals.composer.placeholderColor.toInts().slice(0, 3)).toEqual([111, 111, 120])
expect(internals.composer.placeholderColor.toInts().slice(0, 3)).toEqual([98, 98, 107])
app.accept({ event: "attached", chat_id: "chat" })
await waitUntil(() => internals.ready)
@@ -528,6 +528,118 @@ describe("NanobotTui layout and themes", () => {
expect(composerLine).not.toContain("┐")
})
test.each(["light", "dark", "auto"] as const)(
"keeps the %s composer cursor cell readable at the end of input",
async (theme) => {
setup = await createRenderer({ width: 72, height: 20, screenMode: "alternate-screen" })
const app = NanobotTui.mount(
setup.renderer,
{ ...options, theme },
client(),
new MockTreeSitterClient({ autoResolveTimeout: 0 }),
)
const ui = app as unknown as { ready: boolean; composer: TextareaRenderable }
app.accept({ event: "attached", chat_id: "chat" })
await waitUntil(() => ui.ready)
await setup.mockInput.pressKeys([..."Draft 中文🙂"])
const expectCursorCell = async () => {
await setup!.flush()
const cursor = setup!.renderer.getCursorState()
const spans = setup!.captureSpans().lines[cursor.y - 1]!.spans
let column = 1
const cell = spans.find((span) => {
const containsCursor = column <= cursor.x && cursor.x < column + span.width
column += span.width
return containsCursor
})!
expect(cursor.visible).toBe(true)
const buffer = setup!.renderer.currentRenderBuffer
expect(buffer.buffers.char[(cursor.y - 1) * buffer.width + cursor.x - 1]).toBe(32)
expect(cell.fg.equals(ui.composer.textColor)).toBe(true)
expect(cell.bg.equals(ui.composer.backgroundColor)).toBe(true)
}
await expectCursorCell()
setup.mockInput.pressKey("HOME")
setup.mockInput.pressKey("END")
await expectCursorCell()
setup.mockInput.pressArrow("left")
setup.mockInput.pressArrow("right")
await expectCursorCell()
setup.mockInput.pressBackspace()
await expectCursorCell()
expect(ui.composer.plainText).toBe("Draft 中文")
setup.resize(18, 20)
await expectCursorCell()
},
)
test.each(["light", "dark", "auto"] as const)(
"keeps %s conversation selections readable across Markdown blocks",
async (theme) => {
setup = await createRenderer({ width: 96, height: 48, screenMode: "alternate-screen" })
const app = NanobotTui.mount(
setup.renderer,
{ ...options, theme },
client(),
new MockTreeSitterClient({ autoResolveTimeout: 0 }),
)
const ui = app as unknown as { transcript: Transcript; composer: TextareaRenderable }
ui.transcript.user("User selection text")
ui.transcript.assistant([
"Normal selection text",
"**Bold selection text**",
"- List selection text",
"```text\nCode selection text\n```",
"| Heading |\n| --- |\n| Table selection text |",
].join("\n\n"))
await setup.flush()
for (const text of [
"User selection text", "Normal selection text", "Bold selection text",
"List selection text", "Code selection text", "Table selection text",
]) {
setup.renderer.clearSelection()
await setup.flush()
const lines = setup.captureCharFrame().split("\n")
const y = lines.findIndex((line) => line.includes(text))
const x = lines[y]!.indexOf(text)
await setup.mockMouse.drag(x, y, x + text.length, y)
await setup.flush()
expect(setup.renderer.getSelection()?.getSelectedText()).toContain(text)
const selected = setup.captureSpans().lines[y]!.spans.find((span) => span.text.includes(text))!
expect(selected.fg.intent).toBe("rgb")
expect(selected.bg.intent).toBe("rgb")
expect(contrastRatio(rgbToHex(selected.fg), rgbToHex(selected.bg))).toBeGreaterThanOrEqual(4.5)
}
if (theme === "auto") {
for (const mode of ["light", "dark"] as const) {
setup.renderer.emit(CliRenderEvents.THEME_MODE, mode)
await setup.flush()
expect(setup.renderer.getSelection()?.getSelectedText()).toContain("Table selection text")
const selected = setup.captureSpans().lines.flatMap((line) => line.spans)
.find((span) => span.text.includes("Table selection text"))!
expect(selected.fg.intent).toBe("rgb")
expect(selected.bg.intent).toBe("rgb")
expect(contrastRatio(rgbToHex(selected.fg), rgbToHex(selected.bg))).toBeGreaterThanOrEqual(4.5)
}
}
setup.renderer.clearSelection()
await setup.mockInput.typeText("Composer selection text")
setup.mockInput.pressKey("HOME", { shift: true })
await setup.flush()
expect(ui.composer.getSelectedText()).toBe("Composer selection text")
const selected = setup.captureSpans().lines.flatMap((line) => line.spans)
.find((span) => span.text.includes("Composer selection text"))!
expect(selected.fg.intent).toBe("rgb")
expect(selected.bg.intent).toBe("rgb")
expect(contrastRatio(rgbToHex(selected.fg), rgbToHex(selected.bg))).toBeGreaterThanOrEqual(4.5)
},
)
test("uses asymmetric roles instead of chat bubbles", async () => {
setup = await createRenderer({ width: 72, height: 24, screenMode: "alternate-screen" })
const app = NanobotTui.mount(
@@ -750,11 +862,12 @@ describe("NanobotTui layout and themes", () => {
const internals = app as unknown as {
palette: Record<string, string> & { referenceBackground: string; faint: string }
}
const assertContrast = () => {
for (const tone of ["text", "muted", "accent", "link", "success", "error", "user", "warm", "cool"]) {
expect(contrastRatio(internals.palette[tone] ?? "", internals.palette.referenceBackground)).toBeGreaterThanOrEqual(4.5)
const assertContrast = (backgrounds: string[]) => {
for (const background of backgrounds) {
for (const tone of ["text", "muted", "faint", "accent", "link", "success", "error", "user", "warm", "cool"]) {
expect(contrastRatio(internals.palette[tone] ?? "", background)).toBeGreaterThanOrEqual(4.5)
}
}
expect(contrastRatio(internals.palette.faint, internals.palette.referenceBackground)).toBeGreaterThanOrEqual(3)
const turnContrast = contrastRatio(
internals.palette.userBackground ?? "",
internals.palette.referenceBackground,
@@ -764,11 +877,11 @@ describe("NanobotTui layout and themes", () => {
}
setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark")
assertContrast()
assertContrast([internals.palette.referenceBackground, "#282C34", "#282A36", "#282828", "#002B36"])
expect(internals.palette.accent).toBe("#EF8E30")
expect(internals.palette.user).toBe("#EF8E30")
setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")
assertContrast()
assertContrast([internals.palette.referenceBackground, "#FDF6E3"])
expect(internals.palette.accent).toBe("#B94D0B")
expect(internals.palette.user).toBe("#B94D0B")
})
+5 -5
View File
@@ -1,7 +1,6 @@
import {
BoxRenderable,
RGBA,
TextareaRenderable,
TextRenderable,
type CliRenderer,
type PasteEvent,
@@ -9,6 +8,7 @@ import {
} from "@opentui/core"
import type { QueuePreview } from "../composer/queue-preview"
import { ComposerTextarea } from "../composer/textarea"
import type { BranchMenu } from "../menus/branch-menu"
import type { CommandMenu } from "../menus/command-menu"
import type { MentionMenu } from "../menus/mention-menu"
@@ -57,7 +57,7 @@ export interface AppLayout {
shell: BoxRenderable
title: BoxRenderable
composerFrame: BoxRenderable
composer: TextareaRenderable
composer: ComposerTextarea
status: TextRenderable
meta: TextRenderable
}
@@ -116,7 +116,7 @@ export function createAppLayout(
paddingRight: 1,
backgroundColor: composerSurface,
})
const composer = new TextareaRenderable(renderer, {
const composer = new ComposerTextarea(renderer, {
id: "nanobot-tui-composer",
width: "100%",
minHeight: 1,
@@ -128,10 +128,10 @@ export function createAppLayout(
focusedTextColor: palette.text,
backgroundColor: composerSurface,
focusedBackgroundColor: composerSurface,
selectionBg: palette.selection.background,
selectionFg: palette.selection.foreground,
cursorColor: palette.accent,
syntaxStyle: composerSyntax,
// A steady line cursor avoids the block-cell trails produced by some
// terminals when a retained full-screen UI redraws around the composer.
cursorStyle: { style: "line", blinking: false },
showCursor: true,
keyBindings: [
+20 -3
View File
@@ -1,9 +1,9 @@
import { afterEach, describe, expect, test } from "bun:test"
import { CliRenderEvents, TextareaRenderable, TextRenderable } from "@opentui/core"
import { CliRenderEvents, TextareaRenderable, TextRenderable, rgbToHex } from "@opentui/core"
import { MockTreeSitterClient, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"
import { NanobotTui } from "./app"
import type { RecoveryState, SlashCommand, WorkspaceScopePayload } from "../client"
import { options, client, mount, waitUntil, occurrences } from "./test-support"
import { options, client, mount, waitUntil, occurrences, contrastRatio } from "./test-support"
describe("NanobotTui session navigation", () => {
let setup: TestRendererSetup | undefined
@@ -907,7 +907,7 @@ describe("NanobotTui session navigation", () => {
})
test("opens the latest turn diff as a full-screen, navigable view", async () => {
setup = await createRenderer({ width: 96, height: 28, screenMode: "alternate-screen" })
setup = await createRenderer({ width: 96, height: 28, screenMode: "alternate-screen", consoleMode: "disabled" })
const app = mount(setup)
app.accept({ event: "attached", chat_id: "chat" })
await waitUntil(() => (app as unknown as { ready: boolean }).ready)
@@ -972,6 +972,23 @@ describe("NanobotTui session navigation", () => {
expect(frame).toContain("Diff truncated by the gateway")
expect(frame).not.toContain("Ask nanobot anything")
const rows = frame.split("\n")
const y = rows.findIndex((row) => row.includes("const newValue = 2"))
const x = rows[y]!.indexOf("const newValue = 2")
await setup.mockMouse.drag(x, y, x + "const newValue = 2".length, y)
await setup.flush()
expect(setup.renderer.getSelection()?.getSelectedText()).toBe("const newValue = 2")
const selected = setup.captureSpans().lines[y]!.spans.find((span) => span.text.includes("const newValue = 2"))!
expect(selected.fg.intent).toBe("rgb")
expect(selected.bg.intent).toBe("rgb")
expect(contrastRatio(rgbToHex(selected.fg), rgbToHex(selected.bg))).toBeGreaterThanOrEqual(4.5)
setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")
await setup.flush()
expect(setup.renderer.console.visible).toBe(false)
expect(setup.captureCharFrame()).toContain("const newValue = 2")
setup.renderer.clearSelection()
setup.mockInput.pressArrow("right")
await setup.flush()
frame = setup.captureCharFrame()
+12 -5
View File
@@ -16,6 +16,7 @@ import type { DiffViewerTheme } from "../views/diff-viewer"
import type { FooterHintTheme } from "../views/footer-hints"
import type { RecoveryNoticeTheme } from "../views/recovery-notice"
import type { UsagePanelTheme } from "../views/usage-panel"
import type { SelectionColors } from "../platform/selection"
export const IMAGE_PLACEHOLDER_STYLE = "image.placeholder"
export const SHIMMER_INTERVAL_MS = 80
@@ -38,13 +39,14 @@ export interface Palette {
userBackground: ColorInput
warm: ColorInput
cool: ColorInput
selection: SelectionColors
}
export const DARK: Palette = {
referenceBackground: "#0E0F11",
text: "#ECEDEE",
muted: "#A1A1AA",
faint: "#71717A",
faint: "#A1A1AA",
border: "#3F3F46",
accent: "#EF8E30",
link: "#60A5FA",
@@ -54,15 +56,16 @@ export const DARK: Palette = {
user: "#EF8E30",
// Codex-style turn anchor: 12% white over the reference dark background.
userBackground: "#2B2C2E",
warm: "#C26A25",
cool: "#1795A2",
warm: "#E9965A",
cool: "#36B8C7",
selection: { background: RGBA.fromHex("#3F3F46"), foreground: RGBA.fromHex("#ECEDEE") },
}
export const LIGHT: Palette = {
referenceBackground: "#FAFAFA",
text: "#18181B",
muted: "#6F6F78",
faint: "#8A8A94",
muted: "#62626B",
faint: "#62626B",
border: "#D4D4D8",
accent: "#B94D0B",
link: "#1D4ED8",
@@ -74,6 +77,7 @@ export const LIGHT: Palette = {
userBackground: "#F0F0F0",
warm: "#C2410C",
cool: "#0F766E",
selection: { background: RGBA.fromHex("#D4D4D8"), foreground: RGBA.fromHex("#18181B") },
}
// Until the terminal answers OSC 10/11, its default foreground is the only
@@ -93,6 +97,7 @@ export const TERMINAL: Palette = {
userBackground: RGBA.defaultBackground(),
warm: RGBA.defaultForeground(),
cool: RGBA.defaultForeground(),
selection: { background: RGBA.fromHex("#93C5FD"), foreground: RGBA.fromHex("#18181B") },
}
@@ -182,6 +187,8 @@ export function diffViewerTheme(palette: Palette, backgroundKnown: boolean): Dif
error: palette.error,
addedBackground: backgroundKnown ? light ? "#E7F6EC" : "#142D22" : null,
removedBackground: backgroundKnown ? light ? "#FCE8EA" : "#352024" : null,
selectionBackground: palette.selection.background,
selectionForeground: palette.selection.foreground,
syntax: syntaxStyle(palette),
}
}
+19
View File
@@ -0,0 +1,19 @@
import { TextareaRenderable, type OptimizedBuffer } from "@opentui/core"
export class ComposerTextarea extends TextareaRenderable {
override renderCursor(buffer: OptimizedBuffer): void {
if (this.focused && this.showCursor) {
const { visualCol, visualRow } = this.visualCursor
const x = this.x + visualCol
const y = this.y + visualRow
if (x >= 0 && x < buffer.width && y >= 0 && y < buffer.height) {
const index = y * buffer.width + x
const { char, fg } = buffer.buffers
// OpenTUI clears unused editor cells with a white foreground. Hosts
// that draw a cursor by reversing the cell use that color as its fill.
if (char[index] === 32) fg.set(this.textColor.buffer, index * 4)
}
}
super.renderCursor(buffer)
}
}
+30
View File
@@ -0,0 +1,30 @@
import {
EditBufferRenderable,
TextBufferRenderable,
TextTableRenderable,
type RGBA,
type Selection,
} from "@opentui/core"
export interface SelectionColors {
background: RGBA
foreground: RGBA
}
export function applySelectionColors(selection: Selection, colors: SelectionColors): void {
for (const renderable of selection.selectedRenderables) {
if (renderable.isDestroyed) continue
if (renderable instanceof TextBufferRenderable || renderable instanceof EditBufferRenderable) {
renderable.selectionBg = colors.background
renderable.selectionFg = colors.foreground
} else if (renderable instanceof TextTableRenderable) {
// OpenTUI 0.5.11 exposes table selection colors only at construction.
// Update its retained palette without replacing streaming table cells.
const table = renderable as unknown as { _selectionBg?: RGBA; _selectionFg?: RGBA }
if (table._selectionBg === colors.background && table._selectionFg === colors.foreground) continue
table._selectionBg = colors.background
table._selectionFg = colors.foreground
renderable.onSelectionChanged(selection)
}
}
}
+4 -2
View File
@@ -24,6 +24,8 @@ export interface DiffViewerTheme {
error: ColorInput
addedBackground: ColorInput | null
removedBackground: ColorInput | null
selectionBackground: ColorInput
selectionForeground: ColorInput
syntax: SyntaxStyle
}
@@ -295,8 +297,8 @@ export class DiffViewer {
removedLineNumberBg: this.theme.removedBackground || RGBA.defaultBackground(),
addedSignColor: this.theme.success,
removedSignColor: this.theme.error,
selectionBg: this.theme.border,
selectionFg: this.theme.text,
selectionBg: this.theme.selectionBackground,
selectionFg: this.theme.selectionForeground,
}))
if (edit.diff?.truncated) {
this.scroll.add(this.text("… Diff truncated by the gateway; line counts may be larger.", "accent"))