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" } from "../views/footer-hints"
import { copyWithSystemClipboard } from "../platform/clipboard" import { copyWithSystemClipboard } from "../platform/clipboard"
import { configureOpenTuiEnvironment, createTuiHost, type TuiHost } from "../platform/host" import { configureOpenTuiEnvironment, createTuiHost, type TuiHost } from "../platform/host"
import { applySelectionColors } from "../platform/selection"
import { LOCAL_COMMANDS } from "./commands" import { LOCAL_COMMANDS } from "./commands"
import { CooperativeEventQueue } from "./event-queue" import { CooperativeEventQueue } from "./event-queue"
import { import {
@@ -404,6 +405,10 @@ export class NanobotTui {
this.status = layout.status this.status = layout.status
this.meta = layout.meta this.meta = layout.meta
this.renderer.root.add(this.shell) 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.keyInput.on("keypress", this.handleKey)
this.renderer.on(CliRenderEvents.THEME_MODE, this.handleTheme) this.renderer.on(CliRenderEvents.THEME_MODE, this.handleTheme)
@@ -1729,6 +1734,8 @@ export class NanobotTui {
this.composerFrame.borderColor = this.palette.accent this.composerFrame.borderColor = this.palette.accent
this.composer.backgroundColor = surface this.composer.backgroundColor = surface
this.composer.focusedBackgroundColor = 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 this.composer.placeholderColor = this.palette.muted
} }
+121 -8
View File
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, test } from "bun:test" 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 { MockTreeSitterClient, TestRecorder, setRendererCapabilities, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"
import { NanobotTui } from "./app" import { NanobotTui } from "./app"
import type { Transcript } from "../rendering/transcript" 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.borderColor.toInts().slice(0, 3)).toEqual([185, 77, 11])
expect(internals.composerFrame.backgroundColor.toInts().slice(0, 3)).toEqual([240, 240, 240]) 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.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" }) app.accept({ event: "attached", chat_id: "chat" })
await waitUntil(() => internals.ready) await waitUntil(() => internals.ready)
@@ -528,6 +528,118 @@ describe("NanobotTui layout and themes", () => {
expect(composerLine).not.toContain("┐") 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 () => { test("uses asymmetric roles instead of chat bubbles", async () => {
setup = await createRenderer({ width: 72, height: 24, screenMode: "alternate-screen" }) setup = await createRenderer({ width: 72, height: 24, screenMode: "alternate-screen" })
const app = NanobotTui.mount( const app = NanobotTui.mount(
@@ -750,11 +862,12 @@ describe("NanobotTui layout and themes", () => {
const internals = app as unknown as { const internals = app as unknown as {
palette: Record<string, string> & { referenceBackground: string; faint: string } palette: Record<string, string> & { referenceBackground: string; faint: string }
} }
const assertContrast = () => { const assertContrast = (backgrounds: string[]) => {
for (const tone of ["text", "muted", "accent", "link", "success", "error", "user", "warm", "cool"]) { for (const background of backgrounds) {
expect(contrastRatio(internals.palette[tone] ?? "", internals.palette.referenceBackground)).toBeGreaterThanOrEqual(4.5) 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( const turnContrast = contrastRatio(
internals.palette.userBackground ?? "", internals.palette.userBackground ?? "",
internals.palette.referenceBackground, internals.palette.referenceBackground,
@@ -764,11 +877,11 @@ describe("NanobotTui layout and themes", () => {
} }
setup.renderer.emit(CliRenderEvents.THEME_MODE, "dark") 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.accent).toBe("#EF8E30")
expect(internals.palette.user).toBe("#EF8E30") expect(internals.palette.user).toBe("#EF8E30")
setup.renderer.emit(CliRenderEvents.THEME_MODE, "light") setup.renderer.emit(CliRenderEvents.THEME_MODE, "light")
assertContrast() assertContrast([internals.palette.referenceBackground, "#FDF6E3"])
expect(internals.palette.accent).toBe("#B94D0B") expect(internals.palette.accent).toBe("#B94D0B")
expect(internals.palette.user).toBe("#B94D0B") expect(internals.palette.user).toBe("#B94D0B")
}) })
+5 -5
View File
@@ -1,7 +1,6 @@
import { import {
BoxRenderable, BoxRenderable,
RGBA, RGBA,
TextareaRenderable,
TextRenderable, TextRenderable,
type CliRenderer, type CliRenderer,
type PasteEvent, type PasteEvent,
@@ -9,6 +8,7 @@ import {
} from "@opentui/core" } from "@opentui/core"
import type { QueuePreview } from "../composer/queue-preview" import type { QueuePreview } from "../composer/queue-preview"
import { ComposerTextarea } from "../composer/textarea"
import type { BranchMenu } from "../menus/branch-menu" import type { BranchMenu } from "../menus/branch-menu"
import type { CommandMenu } from "../menus/command-menu" import type { CommandMenu } from "../menus/command-menu"
import type { MentionMenu } from "../menus/mention-menu" import type { MentionMenu } from "../menus/mention-menu"
@@ -57,7 +57,7 @@ export interface AppLayout {
shell: BoxRenderable shell: BoxRenderable
title: BoxRenderable title: BoxRenderable
composerFrame: BoxRenderable composerFrame: BoxRenderable
composer: TextareaRenderable composer: ComposerTextarea
status: TextRenderable status: TextRenderable
meta: TextRenderable meta: TextRenderable
} }
@@ -116,7 +116,7 @@ export function createAppLayout(
paddingRight: 1, paddingRight: 1,
backgroundColor: composerSurface, backgroundColor: composerSurface,
}) })
const composer = new TextareaRenderable(renderer, { const composer = new ComposerTextarea(renderer, {
id: "nanobot-tui-composer", id: "nanobot-tui-composer",
width: "100%", width: "100%",
minHeight: 1, minHeight: 1,
@@ -128,10 +128,10 @@ export function createAppLayout(
focusedTextColor: palette.text, focusedTextColor: palette.text,
backgroundColor: composerSurface, backgroundColor: composerSurface,
focusedBackgroundColor: composerSurface, focusedBackgroundColor: composerSurface,
selectionBg: palette.selection.background,
selectionFg: palette.selection.foreground,
cursorColor: palette.accent, cursorColor: palette.accent,
syntaxStyle: composerSyntax, 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 }, cursorStyle: { style: "line", blinking: false },
showCursor: true, showCursor: true,
keyBindings: [ keyBindings: [
+20 -3
View File
@@ -1,9 +1,9 @@
import { afterEach, describe, expect, test } from "bun:test" 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 { MockTreeSitterClient, createTestRenderer, type TestRendererSetup } from "@opentui/core/testing"
import { NanobotTui } from "./app" import { NanobotTui } from "./app"
import type { RecoveryState, SlashCommand, WorkspaceScopePayload } from "../client" 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", () => { describe("NanobotTui session navigation", () => {
let setup: TestRendererSetup | undefined 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 () => { 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) const app = mount(setup)
app.accept({ event: "attached", chat_id: "chat" }) app.accept({ event: "attached", chat_id: "chat" })
await waitUntil(() => (app as unknown as { ready: boolean }).ready) 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).toContain("Diff truncated by the gateway")
expect(frame).not.toContain("Ask nanobot anything") 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") setup.mockInput.pressArrow("right")
await setup.flush() await setup.flush()
frame = setup.captureCharFrame() 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 { FooterHintTheme } from "../views/footer-hints"
import type { RecoveryNoticeTheme } from "../views/recovery-notice" import type { RecoveryNoticeTheme } from "../views/recovery-notice"
import type { UsagePanelTheme } from "../views/usage-panel" import type { UsagePanelTheme } from "../views/usage-panel"
import type { SelectionColors } from "../platform/selection"
export const IMAGE_PLACEHOLDER_STYLE = "image.placeholder" export const IMAGE_PLACEHOLDER_STYLE = "image.placeholder"
export const SHIMMER_INTERVAL_MS = 80 export const SHIMMER_INTERVAL_MS = 80
@@ -38,13 +39,14 @@ export interface Palette {
userBackground: ColorInput userBackground: ColorInput
warm: ColorInput warm: ColorInput
cool: ColorInput cool: ColorInput
selection: SelectionColors
} }
export const DARK: Palette = { export const DARK: Palette = {
referenceBackground: "#0E0F11", referenceBackground: "#0E0F11",
text: "#ECEDEE", text: "#ECEDEE",
muted: "#A1A1AA", muted: "#A1A1AA",
faint: "#71717A", faint: "#A1A1AA",
border: "#3F3F46", border: "#3F3F46",
accent: "#EF8E30", accent: "#EF8E30",
link: "#60A5FA", link: "#60A5FA",
@@ -54,15 +56,16 @@ export const DARK: Palette = {
user: "#EF8E30", user: "#EF8E30",
// Codex-style turn anchor: 12% white over the reference dark background. // Codex-style turn anchor: 12% white over the reference dark background.
userBackground: "#2B2C2E", userBackground: "#2B2C2E",
warm: "#C26A25", warm: "#E9965A",
cool: "#1795A2", cool: "#36B8C7",
selection: { background: RGBA.fromHex("#3F3F46"), foreground: RGBA.fromHex("#ECEDEE") },
} }
export const LIGHT: Palette = { export const LIGHT: Palette = {
referenceBackground: "#FAFAFA", referenceBackground: "#FAFAFA",
text: "#18181B", text: "#18181B",
muted: "#6F6F78", muted: "#62626B",
faint: "#8A8A94", faint: "#62626B",
border: "#D4D4D8", border: "#D4D4D8",
accent: "#B94D0B", accent: "#B94D0B",
link: "#1D4ED8", link: "#1D4ED8",
@@ -74,6 +77,7 @@ export const LIGHT: Palette = {
userBackground: "#F0F0F0", userBackground: "#F0F0F0",
warm: "#C2410C", warm: "#C2410C",
cool: "#0F766E", cool: "#0F766E",
selection: { background: RGBA.fromHex("#D4D4D8"), foreground: RGBA.fromHex("#18181B") },
} }
// Until the terminal answers OSC 10/11, its default foreground is the only // Until the terminal answers OSC 10/11, its default foreground is the only
@@ -93,6 +97,7 @@ export const TERMINAL: Palette = {
userBackground: RGBA.defaultBackground(), userBackground: RGBA.defaultBackground(),
warm: RGBA.defaultForeground(), warm: RGBA.defaultForeground(),
cool: 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, error: palette.error,
addedBackground: backgroundKnown ? light ? "#E7F6EC" : "#142D22" : null, addedBackground: backgroundKnown ? light ? "#E7F6EC" : "#142D22" : null,
removedBackground: backgroundKnown ? light ? "#FCE8EA" : "#352024" : null, removedBackground: backgroundKnown ? light ? "#FCE8EA" : "#352024" : null,
selectionBackground: palette.selection.background,
selectionForeground: palette.selection.foreground,
syntax: syntaxStyle(palette), 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 error: ColorInput
addedBackground: ColorInput | null addedBackground: ColorInput | null
removedBackground: ColorInput | null removedBackground: ColorInput | null
selectionBackground: ColorInput
selectionForeground: ColorInput
syntax: SyntaxStyle syntax: SyntaxStyle
} }
@@ -295,8 +297,8 @@ export class DiffViewer {
removedLineNumberBg: this.theme.removedBackground || RGBA.defaultBackground(), removedLineNumberBg: this.theme.removedBackground || RGBA.defaultBackground(),
addedSignColor: this.theme.success, addedSignColor: this.theme.success,
removedSignColor: this.theme.error, removedSignColor: this.theme.error,
selectionBg: this.theme.border, selectionBg: this.theme.selectionBackground,
selectionFg: this.theme.text, selectionFg: this.theme.selectionForeground,
})) }))
if (edit.diff?.truncated) { if (edit.diff?.truncated) {
this.scroll.add(this.text("… Diff truncated by the gateway; line counts may be larger.", "accent")) this.scroll.add(this.text("… Diff truncated by the gateway; line counts may be larger.", "accent"))
@@ -179,7 +179,6 @@ function CliAppMentionToken({
isHero?: boolean; isHero?: boolean;
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const color = app.brand_color || INLINE_TOKEN_HIGHLIGHT_COLOR;
const displayName = app.display_name?.trim() || app.name; const displayName = app.display_name?.trim() || app.name;
const mentionName = variant === "message" const mentionName = variant === "message"
? displayName ? displayName
@@ -195,7 +194,6 @@ function CliAppMentionToken({
title={t("thread.composer.mentions.cliTitle", { title={t("thread.composer.mentions.cliTitle", {
name: variant === "message" ? `${displayName} (${label})` : displayName, name: variant === "message" ? `${displayName} (${label})` : displayName,
})} })}
color={color}
className={variant === "composer" ? "font-normal" : "inline-flex max-w-full items-baseline [overflow-wrap:anywhere]"} className={variant === "composer" ? "font-normal" : "inline-flex max-w-full items-baseline [overflow-wrap:anywhere]"}
> >
<span <span
@@ -250,7 +248,6 @@ function McpPresetMentionToken({
isHero?: boolean; isHero?: boolean;
}) { }) {
const { t } = useTranslation(); const { t } = useTranslation();
const color = preset.brand_color || INLINE_TOKEN_HIGHLIGHT_COLOR;
const displayName = preset.display_name?.trim() || preset.name; const displayName = preset.display_name?.trim() || preset.name;
const mentionName = variant === "message" const mentionName = variant === "message"
? displayName ? displayName
@@ -266,7 +263,6 @@ function McpPresetMentionToken({
title={t("thread.composer.mentions.mcpTitle", { title={t("thread.composer.mentions.mcpTitle", {
name: variant === "message" ? `${displayName} (${label})` : displayName, name: variant === "message" ? `${displayName} (${label})` : displayName,
})} })}
color={color}
className={variant === "composer" ? "font-normal" : "inline-flex max-w-full items-baseline [overflow-wrap:anywhere]"} className={variant === "composer" ? "font-normal" : "inline-flex max-w-full items-baseline [overflow-wrap:anywhere]"}
> >
<span <span
+10 -29
View File
@@ -22,7 +22,6 @@ interface CodeBlockProps {
interface HighlightedCodeProps { interface HighlightedCodeProps {
language?: string; language?: string;
code: string; code: string;
isDark: boolean;
chrome: "default" | "none"; chrome: "default" | "none";
showLineNumbers: boolean; showLineNumbers: boolean;
wrapLongLines: boolean; wrapLongLines: boolean;
@@ -46,13 +45,9 @@ const ANSI_LANGUAGES = new Set(["ansi", "ansi-output"]);
const LazyHighlightedCode = lazy(async () => { const LazyHighlightedCode = lazy(async () => {
const [ const [
{ default: SyntaxHighlighter }, { default: SyntaxHighlighter },
{ default: oneDark },
{ default: oneLight },
{ ViewportCodeRows }, { ViewportCodeRows },
] = await Promise.all([ ] = await Promise.all([
import("react-syntax-highlighter/dist/esm/prism-async-light"), import("react-syntax-highlighter/dist/esm/prism-async-light"),
import("react-syntax-highlighter/dist/esm/styles/prism/one-dark"),
import("react-syntax-highlighter/dist/esm/styles/prism/one-light"),
import("@/components/ViewportCodeRows"), import("@/components/ViewportCodeRows"),
]); ]);
@@ -60,29 +55,16 @@ const LazyHighlightedCode = lazy(async () => {
default({ default({
language, language,
code, code,
isDark,
chrome, chrome,
showLineNumbers, showLineNumbers,
wrapLongLines, wrapLongLines,
viewportHighlight, viewportHighlight,
}: HighlightedCodeProps) { }: HighlightedCodeProps) {
const theme = isDark ? oneDark : oneLight;
const transparentTheme = chrome === "none" ? {
...theme,
'pre[class*="language-"]': {
...theme['pre[class*="language-"]'],
background: "transparent",
},
'code[class*="language-"]': {
...theme['code[class*="language-"]'],
background: "transparent",
},
} : theme;
return ( return (
<SyntaxHighlighter <SyntaxHighlighter
language={language || "text"} language={language || "text"}
style={transparentTheme} useInlineStyles={false}
style={{}}
customStyle={{ customStyle={{
background: "transparent", background: "transparent",
margin: 0, margin: 0,
@@ -105,7 +87,7 @@ const LazyHighlightedCode = lazy(async () => {
lineNumberStyle={{ lineNumberStyle={{
minWidth: "2.6em", minWidth: "2.6em",
paddingRight: "1.15rem", paddingRight: "1.15rem",
color: isDark ? "rgba(212, 212, 216, 0.45)" : "rgba(63, 63, 70, 0.68)", color: "var(--code-comment)",
fontFamily: CODE_FONT_STACK, fontFamily: CODE_FONT_STACK,
userSelect: "none", userSelect: "none",
}} }}
@@ -125,8 +107,8 @@ function renderPlainText(value: string): ReactNode {
return value; return value;
} }
function renderAnsiText(value: string): ReactNode { function renderAnsiText(value: string, theme: "light" | "dark"): ReactNode {
return parseAnsiSegments(value).map((segment, index) => ( return parseAnsiSegments(value, theme).map((segment, index) => (
<span key={index} style={segment.style}> <span key={index} style={segment.style}>
{segment.text} {segment.text}
</span> </span>
@@ -168,14 +150,14 @@ function CodeTextBlock({
<code className="text-inherit"> <code className="text-inherit">
{showLineNumbers && compact ? ( {showLineNumbers && compact ? (
<span className="flex min-w-max"> <span className="flex min-w-max">
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground/60" <span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"
style={{ minWidth: "4.25em" }}>{lines.map((_, index) => index + 1).join("\n")}</span> style={{ minWidth: "4.25em" }}>{lines.map((_, index) => index + 1).join("\n")}</span>
<span>{renderText(code)}</span> <span>{renderText(code)}</span>
</span> </span>
) : showLineNumbers ? ( ) : showLineNumbers ? (
lines.map((line, index) => ( lines.map((line, index) => (
<span key={index} className="flex min-w-max"> <span key={index} className="flex min-w-max">
<span className="w-10 shrink-0 select-none pr-4 text-right text-muted-foreground/60"> <span className="w-10 shrink-0 select-none pr-4 text-right text-muted-foreground">
{index + 1} {index + 1}
</span> </span>
<span className="whitespace-pre">{renderText(line || " ")}</span> <span className="whitespace-pre">{renderText(line || " ")}</span>
@@ -264,7 +246,7 @@ export const CodeBlock = memo(function CodeBlock({
<div <div
ref={rootRef} ref={rootRef}
className={cn( className={cn(
"not-prose relative", "not-prose relative code-content",
useViewportHighlight ? "overflow-visible" : "overflow-hidden", useViewportHighlight ? "overflow-visible" : "overflow-hidden",
hasChrome && "rounded-floating bg-secondary/70", hasChrome && "rounded-floating bg-secondary/70",
className, className,
@@ -277,7 +259,7 @@ export const CodeBlock = memo(function CodeBlock({
chrome={chrome} chrome={chrome}
showLineNumbers={showLineNumbers} showLineNumbers={showLineNumbers}
testId="ansi-code" testId="ansi-code"
renderText={renderAnsiText} renderText={(value) => renderAnsiText(value, isDark ? "dark" : "light")}
compact={useViewportHighlight} compact={useViewportHighlight}
/> />
) : highlight && withinHighlightBudget && (!deferHighlight || highlightedSource === code) ? ( ) : highlight && withinHighlightBudget && (!deferHighlight || highlightedSource === code) ? (
@@ -295,7 +277,6 @@ export const CodeBlock = memo(function CodeBlock({
<LazyHighlightedCode <LazyHighlightedCode
language={syntaxLanguage} language={syntaxLanguage}
code={code} code={code}
isDark={isDark}
chrome={chrome} chrome={chrome}
showLineNumbers={showLineNumbers} showLineNumbers={showLineNumbers}
wrapLongLines={wrapLongLines} wrapLongLines={wrapLongLines}
@@ -317,7 +298,7 @@ export const CodeBlock = memo(function CodeBlock({
onClick={onCopy} onClick={onCopy}
className={cn( className={cn(
"absolute right-2.5 top-2.5 z-10 inline-flex h-8 w-8 items-center justify-center rounded-full", "absolute right-2.5 top-2.5 z-10 inline-flex h-8 w-8 items-center justify-center rounded-full",
"text-muted-foreground/75 transition-colors hover:text-foreground", "text-muted-foreground transition-colors hover:text-foreground",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/60",
)} )}
aria-label={copyLabel} aria-label={copyLabel}
+1 -1
View File
@@ -108,7 +108,7 @@ export function FileReferenceChip({
> >
{display === "path" && directory ? ( {display === "path" && directory ? (
<> <>
<span className="text-muted-foreground/65">{directory}</span> <span className="text-muted-foreground">{directory}</span>
<span className={cn("font-semibold", interactive && "text-sky-700 dark:text-sky-200")}>{name}</span> <span className={cn("font-semibold", interactive && "text-sky-700 dark:text-sky-200")}>{name}</span>
</> </>
) : ( ) : (
@@ -13,7 +13,7 @@ export function InlineTokenHighlight({
}: { }: {
children: ReactNode; children: ReactNode;
className?: string; className?: string;
color: string; color?: string;
testId?: string; testId?: string;
title?: string; title?: string;
}) { }) {
@@ -22,7 +22,7 @@ export function InlineTokenHighlight({
data-testid={testId} data-testid={testId}
title={title} title={title}
className={cn( className={cn(
"relative inline font-[550] transition-colors duration-150", "relative inline font-[550] text-foreground transition-colors duration-150",
className, className,
)} )}
style={{ color }} style={{ color }}
+1 -1
View File
@@ -261,7 +261,7 @@ export function MessageBlockMenuActions({
{timestampLabel || automationSourceLabel ? ( {timestampLabel || automationSourceLabel ? (
<div <div
data-message-block-metadata data-message-block-metadata
className={cn("mt-0.5 w-full border-t border-border/45 px-1.5 pt-1 leading-4", sheet ? "px-2 text-xs text-muted-foreground" : "text-[10px] text-muted-foreground/45")} className={cn("mt-0.5 w-full border-t border-border/45 px-1.5 pt-1 leading-4 text-muted-foreground", sheet ? "px-2 text-xs" : "text-[10px]")}
> >
{timestampLabel ? ( {timestampLabel ? (
<time <time
+1 -1
View File
@@ -17,7 +17,7 @@ const CodeChunk = memo(function CodeChunk({ rows, text, start, stylesheet, useIn
}) { }) {
return ( return (
<span data-code-chunk={start / CHUNK_LINES} className="flex min-w-max"> <span data-code-chunk={start / CHUNK_LINES} className="flex min-w-max">
<span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground/60" <span aria-hidden className="shrink-0 select-none pr-[1.15rem] text-right text-muted-foreground"
style={{ minWidth: "4.25em" }}> style={{ minWidth: "4.25em" }}>
{rows.map((_, index) => start + index + 1).join("\n")} {rows.map((_, index) => start + index + 1).join("\n")}
</span> </span>
@@ -131,7 +131,7 @@ export function ComposerUsagePopover({
aria-label={triggerLabel} aria-label={triggerLabel}
className={cn( className={cn(
"touch-target inline-flex size-5 shrink-0 items-center justify-center rounded-full", "touch-target inline-flex size-5 shrink-0 items-center justify-center rounded-full",
"text-muted-foreground/75 transition-colors hover:text-foreground/85", "text-muted-foreground transition-colors hover:text-foreground",
"focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring", "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
showLabel && "w-auto gap-1.5 px-2 text-xs", showLabel && "w-auto gap-1.5 px-2 text-xs",
)} )}
@@ -154,7 +154,7 @@ export function ComposerUsagePopover({
"size-[15px] shrink-0 -rotate-90", "size-[15px] shrink-0 -rotate-90",
status === "critical" && "text-destructive", status === "critical" && "text-destructive",
status === "caution" && "text-amber-600 dark:text-amber-400", status === "caution" && "text-amber-600 dark:text-amber-400",
status === "normal" && "text-muted-foreground/75", status === "normal" && "text-muted-foreground",
)} )}
> >
<circle <circle
@@ -38,7 +38,7 @@ export function StreamErrorNotice({ error, onDismiss }: StreamErrorNoticeProps)
/> />
<div className="flex-1"> <div className="flex-1">
<p className="font-medium">{title}</p> <p className="font-medium">{title}</p>
<p className="mt-0.5 text-destructive/80">{body}</p> <p className="mt-0.5 text-destructive">{body}</p>
</div> </div>
<Button <Button
variant="ghost" variant="ghost"
@@ -2645,7 +2645,7 @@ export function ThreadComposer({
aria-label={inputAriaLabel ?? t("thread.composer.inputAria")} aria-label={inputAriaLabel ?? t("thread.composer.inputAria")}
className={cn( className={cn(
inputTextClasses, inputTextClasses,
"relative z-10 block caret-foreground placeholder:text-muted-foreground/70", "relative z-10 block caret-foreground placeholder:text-muted-foreground",
"focus:outline-none focus-visible:outline-none", "focus:outline-none focus-visible:outline-none",
"disabled:cursor-not-allowed", "disabled:cursor-not-allowed",
hasMentionDecorations && "text-transparent selection:bg-primary/20", hasMentionDecorations && "text-transparent selection:bg-primary/20",
@@ -9,12 +9,12 @@ export function DiffPair({ added, deleted }: { added: number; deleted: number })
<DiffValue <DiffValue
sign="+" sign="+"
value={added} value={added}
className="text-emerald-600/75 dark:text-emerald-300/75" className="text-diff-added-foreground"
/> />
<DiffValue <DiffValue
sign="-" sign="-"
value={deleted} value={deleted}
className="text-rose-600/70 dark:text-rose-300/75" className="text-diff-deleted-foreground"
/> />
</span> </span>
); );
@@ -1,7 +1,6 @@
import { Suspense, lazy, type ReactNode } from "react"; import { Suspense, lazy, type ReactNode } from "react";
import type { SyntaxHighlighterProps } from "react-syntax-highlighter"; import type { SyntaxHighlighterProps } from "react-syntax-highlighter";
import { useThemeValue } from "@/hooks/useTheme";
import type { RenderableFileDiffLine } from "@/lib/file-diff"; import type { RenderableFileDiffLine } from "@/lib/file-diff";
import { cn } from "@/lib/utils"; import { cn } from "@/lib/utils";
@@ -10,10 +9,6 @@ interface DiffSyntaxHighlightProps {
lines: RenderableFileDiffLine[]; lines: RenderableFileDiffLine[];
} }
interface LoadedDiffSyntaxHighlightProps extends DiffSyntaxHighlightProps {
isDark: boolean;
}
type RendererArgs = Parameters<NonNullable<SyntaxHighlighterProps["renderer"]>>[0]; type RendererArgs = Parameters<NonNullable<SyntaxHighlighterProps["renderer"]>>[0];
type SyntaxNode = RendererArgs["rows"][number]; type SyntaxNode = RendererArgs["rows"][number];
@@ -33,26 +28,21 @@ const LazyDiffSyntaxHighlight = lazy(async () => {
const [ const [
{ default: SyntaxHighlighter }, { default: SyntaxHighlighter },
{ default: createSyntaxElement }, { default: createSyntaxElement },
{ default: oneDark },
{ default: oneLight },
] = await Promise.all([ ] = await Promise.all([
import("react-syntax-highlighter/dist/esm/prism-async-light"), import("react-syntax-highlighter/dist/esm/prism-async-light"),
import("react-syntax-highlighter/dist/esm/create-element"), import("react-syntax-highlighter/dist/esm/create-element"),
import("react-syntax-highlighter/dist/esm/styles/prism/one-dark"),
import("react-syntax-highlighter/dist/esm/styles/prism/one-light"),
]); ]);
return { return {
default: function LoadedDiffSyntaxHighlight({ default: function LoadedDiffSyntaxHighlight({
language, language,
lines, lines,
isDark, }: DiffSyntaxHighlightProps) {
}: LoadedDiffSyntaxHighlightProps) {
const theme = isDark ? oneDark : oneLight;
const code = lines.map((line) => line.content || " ").join("\n"); const code = lines.map((line) => line.content || " ").join("\n");
return ( return (
<SyntaxHighlighter <SyntaxHighlighter
language={language} language={language}
style={theme} useInlineStyles={false}
style={{}}
PreTag="div" PreTag="div"
CodeTag="div" CodeTag="div"
customStyle={{ customStyle={{
@@ -71,6 +61,7 @@ const LazyDiffSyntaxHighlight = lazy(async () => {
}, },
}} }}
data-language={language} data-language={language}
className="code-content"
data-testid="syntax-highlighted-diff-hunk" data-testid="syntax-highlighted-diff-hunk"
renderer={({ rows, stylesheet, useInlineStyles }) => ( renderer={({ rows, stylesheet, useInlineStyles }) => (
<DiffLineTable <DiffLineTable
@@ -96,10 +87,9 @@ const LazyDiffSyntaxHighlight = lazy(async () => {
}); });
export function DiffSyntaxHighlight({ language, lines }: DiffSyntaxHighlightProps) { export function DiffSyntaxHighlight({ language, lines }: DiffSyntaxHighlightProps) {
const isDark = useThemeValue() === "dark";
return ( return (
<Suspense fallback={<PlainDiffLines lines={lines} />}> <Suspense fallback={<PlainDiffLines lines={lines} />}>
<LazyDiffSyntaxHighlight language={language} lines={lines} isDark={isDark} /> <LazyDiffSyntaxHighlight language={language} lines={lines} />
</Suspense> </Suspense>
); );
} }
@@ -148,22 +138,22 @@ function DiffLineRow({
<tr <tr
className={cn( className={cn(
"border-0", "border-0",
kind === "add" && "bg-emerald-500/[0.09] dark:bg-emerald-300/[0.11]", kind === "add" && "bg-diff-added",
kind === "delete" && "bg-rose-500/[0.09] dark:bg-rose-300/[0.11]", kind === "delete" && "bg-diff-deleted",
)} )}
> >
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground/55"> <td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground">
{line.old_lineno ?? ""} {line.old_lineno ?? ""}
</td> </td>
<td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground/55"> <td className="w-10 select-none border-r border-border/35 px-1.5 text-right text-muted-foreground">
{line.new_lineno ?? ""} {line.new_lineno ?? ""}
</td> </td>
<td <td
className={cn( className={cn(
"w-5 select-none px-1 text-center", "w-5 select-none px-1 text-center",
kind === "add" && "text-emerald-600/80 dark:text-emerald-300/85", kind === "add" && "text-diff-added-foreground",
kind === "delete" && "text-rose-600/80 dark:text-rose-300/85", kind === "delete" && "text-diff-deleted-foreground",
kind === "context" && "text-muted-foreground/45", kind === "context" && "text-muted-foreground",
)} )}
> >
{marker} {marker}
@@ -326,7 +326,7 @@ function FileUnifiedDiff({
aria-hidden aria-hidden
/> />
<span className="min-w-0 flex-1">{viewDiffLabel}</span> <span className="min-w-0 flex-1">{viewDiffLabel}</span>
<span className="shrink-0 text-muted-foreground/65">{lineCountLabel}</span> <span className="shrink-0 text-muted-foreground">{lineCountLabel}</span>
</button> </button>
<DisclosureContent id={contentId} open={open} onExitComplete={releaseBody}> <DisclosureContent id={contentId} open={open} onExitComplete={releaseBody}>
{shouldRenderBody ? renderBody() : null} {shouldRenderBody ? renderBody() : null}
@@ -35,13 +35,13 @@ export function ThinkingReasoningShell({
const headerClassName = "touch-target inline-flex h-7 min-w-0 items-center gap-1.5 rounded-md px-1.5"; const headerClassName = "touch-target inline-flex h-7 min-w-0 items-center gap-1.5 rounded-md px-1.5";
const headerContent = ( const headerContent = (
<> <>
<Activity className={cn("h-3.5 w-3.5 shrink-0", active ? "activity-current" : "text-muted-foreground/65")} strokeWidth={1.5} aria-hidden> <Activity className={cn("h-3.5 w-3.5 shrink-0", active ? "activity-current" : "text-muted-foreground")} strokeWidth={1.5} aria-hidden>
{active ? <path className="activity-current-trace" pathLength={100} d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2" /> : null} {active ? <path className="activity-current-trace" pathLength={100} d="M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2" /> : null}
</Activity> </Activity>
<span <span
data-sheen-text={active ? label : undefined} data-sheen-text={active ? label : undefined}
className={cn( className={cn(
"min-w-0 truncate text-[12px] font-normal leading-4 text-muted-foreground/65", "min-w-0 truncate text-[12px] font-normal leading-4 text-muted-foreground",
active && "streaming-text-sheen", active && "streaming-text-sheen",
)} )}
> >
+55 -4
View File
@@ -24,15 +24,24 @@
--secondary: 0 0% 96.1%; --secondary: 0 0% 96.1%;
--secondary-foreground: 0 0% 9%; --secondary-foreground: 0 0% 9%;
--muted: 0 0% 96.1%; --muted: 0 0% 96.1%;
--muted-foreground: 0 0% 45.1%; --muted-foreground: 240 4% 40%;
--accent: 0 0% 96.1%; --accent: 0 0% 96.1%;
--accent-foreground: 0 0% 9%; --accent-foreground: 0 0% 9%;
--destructive: 0 84.2% 60.2%; --destructive: 0 73.7% 41.8%;
--destructive-foreground: 0 0% 98%; --destructive-foreground: 0 0% 98%;
--border: 40 8% 90.5%; --border: 40 8% 90.5%;
--input: 40 8% 90.5%; --input: 40 8% 90.5%;
--ring: 0 0% 3.9%; --ring: 0 0% 3.9%;
--inline-token-highlight: #ef8e30; --inline-token-highlight: #ad450b;
--code-comment: #62626b;
--code-string: #166534;
--code-keyword: #7e22ce;
--code-function: #1d4ed8;
--code-property: #854d0e;
--diff-added: rgb(16 185 129 / 0.09);
--diff-added-foreground: #047857;
--diff-deleted: rgb(244 63 94 / 0.09);
--diff-deleted-foreground: #be123c;
--usage-token: 29 86% 56%; --usage-token: 29 86% 56%;
--session-handle-lightness: 0.5; --session-handle-lightness: 0.5;
--session-handle-chroma: 0.12; --session-handle-chroma: 0.12;
@@ -78,7 +87,7 @@
--secondary: var(--card); --secondary: var(--card);
--secondary-foreground: 0 0% 98%; --secondary-foreground: 0 0% 98%;
--muted: var(--card); --muted: var(--card);
--muted-foreground: 0 0% 65%; --muted-foreground: 0 0% 72%;
--accent: 0 0% 25%; --accent: 0 0% 25%;
--accent-foreground: 0 0% 98%; --accent-foreground: 0 0% 98%;
/* Destructive text needs contrast on dark surfaces; filled controls use a dark label. */ /* Destructive text needs contrast on dark surfaces; filled controls use a dark label. */
@@ -88,6 +97,15 @@
--input: var(--border); --input: var(--border);
--ring: 0 0% 83.1%; --ring: 0 0% 83.1%;
--inline-token-highlight: #ef8e30; --inline-token-highlight: #ef8e30;
--code-comment: #c8c8d0;
--code-string: #b5d99c;
--code-keyword: #e3a5f7;
--code-function: #93c5fd;
--code-property: #f6c177;
--diff-added: rgb(110 231 183 / 0.11);
--diff-added-foreground: #6ee7b7;
--diff-deleted: rgb(253 164 175 / 0.11);
--diff-deleted-foreground: #fda4af;
--session-handle-lightness: 0.75; --session-handle-lightness: 0.75;
--session-handle-chroma: 0.11; --session-handle-chroma: 0.11;
--temporary-control-active: #ef8e30; --temporary-control-active: #ef8e30;
@@ -1617,3 +1635,36 @@
@keyframes workspace-directory-shimmer { @keyframes workspace-directory-shimmer {
to { transform: translateX(100%); } to { transform: translateX(100%); }
} }
/* Prism classes are generated at runtime, outside Tailwind's source inventory. */
.code-content {
color: hsl(var(--foreground));
}
/* Flattened JSX tokens retain the ancestor tag class; let inner token types win. */
.code-content .token.tag {
color: var(--code-property);
}
.code-content :is(.token.comment, .token.prolog, .token.doctype, .token.cdata, .linenumber) {
color: var(--code-comment);
}
.code-content .token.comment {
font-style: italic;
}
.code-content :is(.token.string, .token.char, .token.attr-value, .token.regex, .token.inserted) {
color: var(--code-string);
}
.code-content :is(.token.keyword, .token.selector, .token.important, .token.atrule) {
color: var(--code-keyword);
}
.code-content :is(.token.function, .token.operator, .token.entity, .token.url) {
color: var(--code-function);
}
.code-content :is(.token.number, .token.boolean, .token.constant, .token.symbol, .token.attr-name, .token.class-name, .token.builtin, .token.property, .token.deleted) {
color: var(--code-property);
}
.code-content :is(.token.bold, .token.important) {
font-weight: 600;
}
.code-content .token.italic {
font-style: italic;
}
+47 -18
View File
@@ -13,15 +13,18 @@ type AnsiStyle = {
}; };
type AnsiState = { type AnsiState = {
backgroundColor?: string; backgroundColor?: AnsiColor;
bold: boolean; bold: boolean;
color?: string; color?: AnsiColor;
dim: boolean; dim: boolean;
inverse: boolean; inverse: boolean;
italic: boolean; italic: boolean;
underline: boolean; underline: boolean;
}; };
type AnsiColor = number | string;
type AnsiTheme = "light" | "dark";
const ESC = String.fromCharCode(27); const ESC = String.fromCharCode(27);
const ANSI_PATTERN = new RegExp(`${ESC}\\[[0-?]*[ -/]*[@-~]`, "g"); const ANSI_PATTERN = new RegExp(`${ESC}\\[[0-?]*[ -/]*[@-~]`, "g");
@@ -47,6 +50,22 @@ const ANSI_BRIGHT_COLORS = [
"#ffffff", "#ffffff",
]; ];
const ANSI_PALETTE = [...ANSI_COLORS, ...ANSI_BRIGHT_COLORS];
const ANSI_FOREGROUNDS: Record<AnsiTheme, string[]> = {
light: [
"#18181b", "#b91c1c", "#166534", "#854d0e",
"#1d4ed8", "#7e22ce", "#0e7490", "#52525b",
"#62626b", "#b91c1c", "#166534", "#854d0e",
"#1d4ed8", "#86198f", "#155e75", "#3f3f46",
],
dark: [
"#a1a1aa", "#fca5a5", "#86efac", "#fde047",
"#93c5fd", "#d8b4fe", "#67e8f9", "#e5e7eb",
"#a1a1aa", "#fca5a5", "#86efac", "#fef08a",
"#93c5fd", "#e9d5ff", "#a5f3fc", "#ffffff",
],
};
const RGB_STEPS = [0, 95, 135, 175, 215, 255]; const RGB_STEPS = [0, 95, 135, 175, 215, 255];
export function hasAnsi(value: string): boolean { export function hasAnsi(value: string): boolean {
@@ -61,6 +80,8 @@ export function stripAnsi(value: string): string {
function initialState(): AnsiState { function initialState(): AnsiState {
return { return {
backgroundColor: undefined,
color: undefined,
bold: false, bold: false,
dim: false, dim: false,
inverse: false, inverse: false,
@@ -69,10 +90,9 @@ function initialState(): AnsiState {
}; };
} }
function colorFrom256(value: number): string | undefined { function colorFrom256(value: number): AnsiColor | undefined {
if (value < 0 || value > 255) return undefined; if (value < 0 || value > 255) return undefined;
if (value < 8) return ANSI_COLORS[value]; if (value < 16) return value;
if (value < 16) return ANSI_BRIGHT_COLORS[value - 8];
if (value < 232) { if (value < 232) {
const offset = value - 16; const offset = value - 16;
const red = RGB_STEPS[Math.floor(offset / 36)]; const red = RGB_STEPS[Math.floor(offset / 36)];
@@ -110,7 +130,7 @@ function applyExtendedColor(
const mode = params[index + 1]; const mode = params[index + 1];
if (mode === 5) { if (mode === 5) {
const color = colorFrom256(params[index + 2]); const color = colorFrom256(params[index + 2]);
if (color) state[key] = color; if (color !== undefined) state[key] = color;
return index + 2; return index + 2;
} }
if (mode === 2) { if (mode === 2) {
@@ -152,13 +172,13 @@ function applySgrParams(state: AnsiState, params: number[]): void {
} else if (code === 49) { } else if (code === 49) {
delete state.backgroundColor; delete state.backgroundColor;
} else if (code >= 30 && code <= 37) { } else if (code >= 30 && code <= 37) {
state.color = ANSI_COLORS[code - 30]; state.color = code - 30;
} else if (code >= 40 && code <= 47) { } else if (code >= 40 && code <= 47) {
state.backgroundColor = ANSI_COLORS[code - 40]; state.backgroundColor = code - 40;
} else if (code >= 90 && code <= 97) { } else if (code >= 90 && code <= 97) {
state.color = ANSI_BRIGHT_COLORS[code - 90]; state.color = code - 90 + 8;
} else if (code >= 100 && code <= 107) { } else if (code >= 100 && code <= 107) {
state.backgroundColor = ANSI_BRIGHT_COLORS[code - 100]; state.backgroundColor = code - 100 + 8;
} else if (code === 38) { } else if (code === 38) {
index = applyExtendedColor(state, params, index, "color"); index = applyExtendedColor(state, params, index, "color");
} else if (code === 48) { } else if (code === 48) {
@@ -167,12 +187,21 @@ function applySgrParams(state: AnsiState, params: number[]): void {
} }
} }
function styleFromState(state: AnsiState): AnsiStyle | undefined { function styleFromState(state: AnsiState, theme: AnsiTheme): AnsiStyle | undefined {
const foreground = state.inverse ? state.backgroundColor : state.color; // Explicit color pairs retain the output's palette; standalone foregrounds
const background = state.inverse ? state.color : state.backgroundColor; // use colors selected for the UI surface. RGB and extended colors stay literal.
const palette = state.backgroundColor === undefined ? ANSI_FOREGROUNDS[theme] : ANSI_PALETTE;
const foreground = typeof state.color === "number" ? palette[state.color] : state.color;
const background = typeof state.backgroundColor === "number"
? ANSI_PALETTE[state.backgroundColor] : state.backgroundColor;
const style: AnsiStyle = {}; const style: AnsiStyle = {};
if (foreground) style.color = foreground; if (state.inverse) {
if (background) style.backgroundColor = background; style.color = background ?? "hsl(var(--background))";
style.backgroundColor = foreground ?? "hsl(var(--foreground))";
} else {
if (foreground) style.color = foreground;
if (background) style.backgroundColor = background;
}
if (state.bold) style.fontWeight = 700; if (state.bold) style.fontWeight = 700;
if (state.dim) style.opacity = 0.72; if (state.dim) style.opacity = 0.72;
if (state.italic) style.fontStyle = "italic"; if (state.italic) style.fontStyle = "italic";
@@ -180,7 +209,7 @@ function styleFromState(state: AnsiState): AnsiStyle | undefined {
return Object.keys(style).length ? style : undefined; return Object.keys(style).length ? style : undefined;
} }
export function parseAnsiSegments(value: string): AnsiSegment[] { export function parseAnsiSegments(value: string, theme: AnsiTheme): AnsiSegment[] {
const segments: AnsiSegment[] = []; const segments: AnsiSegment[] = [];
const state = initialState(); const state = initialState();
let cursor = 0; let cursor = 0;
@@ -191,7 +220,7 @@ export function parseAnsiSegments(value: string): AnsiSegment[] {
if (index > cursor) { if (index > cursor) {
segments.push({ segments.push({
text: value.slice(cursor, index), text: value.slice(cursor, index),
style: styleFromState(state), style: styleFromState(state, theme),
}); });
} }
const params = normalizedSgrParams(match[0]); const params = normalizedSgrParams(match[0]);
@@ -202,7 +231,7 @@ export function parseAnsiSegments(value: string): AnsiSegment[] {
if (cursor < value.length) { if (cursor < value.length) {
segments.push({ segments.push({
text: value.slice(cursor), text: value.slice(cursor),
style: styleFromState(state), style: styleFromState(state, theme),
}); });
} }
@@ -1611,7 +1611,7 @@ describe("AgentActivityCluster", () => {
<AgentActivityCluster messages={messages} isTurnStreaming={false} hasBodyBelow={false} />, <AgentActivityCluster messages={messages} isTurnStreaming={false} hasBodyBelow={false} />,
); );
expect(screen.getByText(/^Worked/)).toBe(header); expect(screen.getByText(/^Worked/)).toBe(header);
expect(header).toHaveClass("text-muted-foreground/65"); expect(header).toHaveClass("text-muted-foreground");
expect(header).not.toHaveAttribute("data-sheen-text"); expect(header).not.toHaveAttribute("data-sheen-text");
}); });
+12 -27
View File
@@ -5,27 +5,19 @@ import { describe, expect, it, vi } from "vitest";
import { CodeBlock } from "@/components/CodeBlock"; import { CodeBlock } from "@/components/CodeBlock";
import { ThemeProvider } from "@/hooks/useTheme"; import { ThemeProvider } from "@/hooks/useTheme";
const mockedStyles = vi.hoisted(() => ({
dark: { pre: { background: "#111" } },
light: { pre: { background: "#fff" } },
}));
vi.mock("react-syntax-highlighter/dist/esm/prism-async-light", () => ({ vi.mock("react-syntax-highlighter/dist/esm/prism-async-light", () => ({
default: ({ default: ({
children, children,
language, language,
style,
customStyle, customStyle,
}: { }: {
children: string; children: string;
language?: string; language?: string;
style: Record<string, unknown>;
customStyle?: React.CSSProperties; customStyle?: React.CSSProperties;
}) => ( }) => (
<pre <pre
data-testid="highlighted-code" data-testid="highlighted-code"
data-language={language} data-language={language}
data-theme={style === mockedStyles.dark ? "dark" : "light"}
style={customStyle} style={customStyle}
> >
<code>{children}</code> <code>{children}</code>
@@ -33,14 +25,6 @@ vi.mock("react-syntax-highlighter/dist/esm/prism-async-light", () => ({
), ),
})); }));
vi.mock("react-syntax-highlighter/dist/esm/styles/prism/one-dark", () => ({
default: mockedStyles.dark,
}));
vi.mock("react-syntax-highlighter/dist/esm/styles/prism/one-light", () => ({
default: mockedStyles.light,
}));
describe("CodeBlock", () => { describe("CodeBlock", () => {
it("renders and copies a large code block in full without pagination", async () => { it("renders and copies a large code block in full without pagination", async () => {
const user = userEvent.setup(); const user = userEvent.setup();
@@ -220,7 +204,7 @@ describe("CodeBlock", () => {
"ansi", "ansi",
); );
expect(screen.queryByText("ansi")).not.toBeInTheDocument(); expect(screen.queryByText("ansi")).not.toBeInTheDocument();
expect(screen.getByText("PASS")).toHaveStyle({ color: "#0dbc79" }); expect(screen.getByText("PASS")).toHaveStyle({ color: "#86efac" });
expect(screen.getByText("<script>alert(1)</script>")).toBeInTheDocument(); expect(screen.getByText("<script>alert(1)</script>")).toBeInTheDocument();
expect(document.querySelector("script")).toBeNull(); expect(document.querySelector("script")).toBeNull();
}); });
@@ -241,6 +225,13 @@ describe("CodeBlock", () => {
}); });
}); });
it("clears ANSI foreground and background colors on reset", () => {
render(<CodeBlock language="ansi" code={"\x1b[31;47merror\x1b[0m normal"} />);
expect(screen.getByText("error")).toHaveStyle({ color: "#cd3131", backgroundColor: "#e5e5e5" });
expect(screen.getByText("normal")).not.toHaveAttribute("style");
});
it("copies ANSI output as clean text", async () => { it("copies ANSI output as clean text", async () => {
const user = userEvent.setup(); const user = userEvent.setup();
const writeText = vi.fn().mockResolvedValue(undefined); const writeText = vi.fn().mockResolvedValue(undefined);
@@ -314,7 +305,7 @@ describe("CodeBlock", () => {
try { try {
const { rerender } = render( const { rerender } = render(
<ThemeProvider theme="dark"> <ThemeProvider theme="dark">
<CodeBlock language="ts" code="const value = 1;" /> <CodeBlock language="ansi" code={"\x1b[32mPASS\x1b[0m"} />
</ThemeProvider>, </ThemeProvider>,
); );
@@ -323,14 +314,11 @@ describe("CodeBlock", () => {
await Promise.resolve(); await Promise.resolve();
}); });
expect(screen.getByTestId("highlighted-code")).toHaveAttribute( expect(screen.getByText("PASS")).toHaveStyle({ color: "#86efac" });
"data-theme",
"dark",
);
rerender( rerender(
<ThemeProvider theme="light"> <ThemeProvider theme="light">
<CodeBlock language="ts" code="const value = 1;" /> <CodeBlock language="ansi" code={"\x1b[32mPASS\x1b[0m"} />
</ThemeProvider>, </ThemeProvider>,
); );
@@ -338,10 +326,7 @@ describe("CodeBlock", () => {
await Promise.resolve(); await Promise.resolve();
}); });
expect(screen.getByTestId("highlighted-code")).toHaveAttribute( expect(screen.getByText("PASS")).toHaveStyle({ color: "#166534" });
"data-theme",
"light",
);
expect(observer).not.toHaveBeenCalled(); expect(observer).not.toHaveBeenCalled();
} finally { } finally {
vi.stubGlobal("MutationObserver", originalMutationObserver); vi.stubGlobal("MutationObserver", originalMutationObserver);
@@ -1,9 +1,18 @@
import { readFileSync } from "node:fs";
import { resolve } from "node:path";
import { render, screen, waitFor } from "@testing-library/react"; import { render, screen, waitFor } from "@testing-library/react";
import { parse } from "postcss";
import { describe, expect, it } from "vitest"; import { describe, expect, it } from "vitest";
import { DiffSyntaxHighlight } from "@/components/thread/activity/DiffSyntaxHighlight"; import { DiffSyntaxHighlight } from "@/components/thread/activity/DiffSyntaxHighlight";
import { ThemeProvider } from "@/hooks/useTheme"; import { ThemeProvider } from "@/hooks/useTheme";
const globalStyles = parse(readFileSync(resolve(process.cwd(), "src/globals.css"), "utf8"));
// happy-dom does not apply cascade layers; retain the real rules and their order.
globalStyles.walkAtRules("layer", (layer) => {
layer.replaceWith(...(layer.nodes ?? []));
});
describe("DiffSyntaxHighlight with Prism", () => { describe("DiffSyntaxHighlight with Prism", () => {
it("loads the TSX grammar and renders styled syntax tokens", async () => { it("loads the TSX grammar and renders styled syntax tokens", async () => {
render( render(
@@ -50,10 +59,11 @@ describe("DiffSyntaxHighlight with Prism", () => {
await waitFor( await waitFor(
() => { () => {
const tokens = highlighted.querySelectorAll<HTMLElement>( const tokens = highlighted.querySelectorAll<HTMLElement>(
'td:last-child span[style*="color"]', "td:last-child .token",
); );
expect(tokens).not.toHaveLength(0); expect(tokens).not.toHaveLength(0);
expect(new Set([...tokens].map((token) => token.style.color)).size).toBeGreaterThan(1); expect(highlighted.querySelector(".token.keyword")).not.toBeNull();
expect(highlighted.querySelector(".token.string")).not.toBeNull();
}, },
{ timeout: 10_000 }, { timeout: 10_000 },
); );
@@ -62,6 +72,56 @@ describe("DiffSyntaxHighlight with Prism", () => {
expect(highlighted.querySelectorAll("tbody tr")).toHaveLength(4); expect(highlighted.querySelectorAll("tbody tr")).toHaveLength(4);
}); });
it.each(["light", "dark"] as const)(
"preserves nested JSX token colors in the %s appearance",
async (appearance) => {
const { container } = render(
<div className={appearance === "dark" ? "dark" : ""}>
<style>{globalStyles.toString()}</style>
<DiffSyntaxHighlight
language="tsx"
lines={[{
kind: "add",
old_lineno: null,
new_lineno: 1,
content: '<span className={enabled ? "yes" : "no"} onClick={() => save(new Event("ok"))}>ready</span>',
}]}
/>
</div>,
);
const highlighted = await screen.findByTestId(
"syntax-highlighted-diff-hunk",
{},
{ timeout: 10_000 },
);
await waitFor(() => {
expect(highlighted.querySelector(".token.function")).not.toBeNull();
}, { timeout: 10_000 });
const colors = getComputedStyle(
appearance === "dark" ? container.firstElementChild! : document.documentElement,
);
const tokens = [...highlighted.querySelectorAll<HTMLElement>(".token")];
for (const [text, category, variable] of [
['"yes"', "string", "--code-string"],
["new", "keyword", "--code-keyword"],
["save", "function", "--code-function"],
["=>", "operator", "--code-function"],
["className", "attr-name", "--code-property"],
["span", "tag", "--code-property"],
]) {
const token = tokens.find(
(node) => node.textContent === text && node.classList.contains(category),
);
const expectedColor = colors.getPropertyValue(variable).trim();
expect(token, `${category}: ${text}`).toBeDefined();
expect(expectedColor).not.toBe("");
expect.soft(getComputedStyle(token!).color, `${category}: ${text}`).toBe(expectedColor);
}
},
);
it("preserves markdown table line boundaries", async () => { it("preserves markdown table line boundaries", async () => {
const lines = [ const lines = [
"## 发布安排", "## 发布安排",
+2 -10
View File
@@ -48,14 +48,6 @@ vi.mock("react-syntax-highlighter/dist/esm/create-element", () => ({
), ),
})); }));
vi.mock("react-syntax-highlighter/dist/esm/styles/prism/one-dark", () => ({
default: { dark: { color: "#fff" } },
}));
vi.mock("react-syntax-highlighter/dist/esm/styles/prism/one-light", () => ({
default: { light: { color: "#111" } },
}));
describe("DiffSyntaxHighlight", () => { describe("DiffSyntaxHighlight", () => {
it("highlights a complete hunk while preserving diff rows and line numbers", async () => { it("highlights a complete hunk while preserving diff rows and line numbers", async () => {
render( render(
@@ -81,10 +73,10 @@ describe("DiffSyntaxHighlight", () => {
expect(highlighted).toHaveAttribute("data-language", "typescript"); expect(highlighted).toHaveAttribute("data-language", "typescript");
expect(screen.getAllByTestId("syntax-token")).toHaveLength(3); expect(screen.getAllByTestId("syntax-token")).toHaveLength(3);
expect(screen.getByText("return oldValue;", { exact: false }).closest("tr")).toHaveClass( expect(screen.getByText("return oldValue;", { exact: false }).closest("tr")).toHaveClass(
"bg-rose-500/[0.09]", "bg-diff-deleted",
); );
expect(screen.getByText("return newValue;", { exact: false }).closest("tr")).toHaveClass( expect(screen.getByText("return newValue;", { exact: false }).closest("tr")).toHaveClass(
"bg-emerald-500/[0.09]", "bg-diff-added",
); );
expect(screen.getAllByText("5")).toHaveLength(2); expect(screen.getAllByText("5")).toHaveLength(2);
expect(screen.getAllByTestId("syntax-token").some((node) => node.textContent?.endsWith("\n"))).toBe(false); expect(screen.getAllByTestId("syntax-token").some((node) => node.textContent?.endsWith("\n"))).toBe(false);
+4 -4
View File
@@ -663,8 +663,8 @@ describe("MessageBubble", () => {
expect(token).toHaveClass("font-[550]"); expect(token).toHaveClass("font-[550]");
expect(token.className).not.toContain("rounded"); expect(token.className).not.toContain("rounded");
expect(token.className).not.toContain("px-"); expect(token.className).not.toContain("px-");
expect(token.getAttribute("style")).toContain("color: #0B5CFF"); expect(token).toHaveClass("text-foreground");
expect(token.getAttribute("style")).not.toContain("text-shadow"); expect(token.style.textShadow).toBe("");
const logo = screen.getByTestId("message-cli-mention-logo-zoom"); const logo = screen.getByTestId("message-cli-mention-logo-zoom");
expect(logo).toHaveClass("h-[1.1em]", "w-[1.1em]", "rounded-[0.25em]", "top-1/2", "-translate-y-1/2"); expect(logo).toHaveClass("h-[1.1em]", "w-[1.1em]", "rounded-[0.25em]", "top-1/2", "-translate-y-1/2");
expect(logo.parentElement).toHaveClass("mr-1", "w-[1.1em]"); expect(logo.parentElement).toHaveClass("mr-1", "w-[1.1em]");
@@ -716,7 +716,7 @@ describe("MessageBubble", () => {
expect(token).toHaveTextContent("@Draw.io"); expect(token).toHaveTextContent("@Draw.io");
expect(token.className).not.toContain("rounded"); expect(token.className).not.toContain("rounded");
expect(token.className).not.toContain("px-"); expect(token.className).not.toContain("px-");
expect(token.getAttribute("style")).toContain("color: #F08705"); expect(token).toHaveClass("text-foreground");
expect(screen.getByTestId("message-cli-mention-logo-drawio")).toBeInTheDocument(); expect(screen.getByTestId("message-cli-mention-logo-drawio")).toBeInTheDocument();
}); });
@@ -733,7 +733,7 @@ describe("MessageBubble", () => {
const token = screen.getByTestId("message-mcp-mention-browserbase"); const token = screen.getByTestId("message-mcp-mention-browserbase");
expect(token).toHaveTextContent("@Browserbase"); expect(token).toHaveTextContent("@Browserbase");
expect(token).toHaveAttribute("title", "MCP server: Browserbase (@browserbase)"); expect(token).toHaveAttribute("title", "MCP server: Browserbase (@browserbase)");
expect(token.getAttribute("style")).toContain("color: #111827"); expect(token).toHaveClass("text-foreground");
const logo = screen.getByTestId("message-mcp-mention-logo-browserbase"); const logo = screen.getByTestId("message-mcp-mention-logo-browserbase");
expect(logo).toHaveClass("h-[1.1em]", "w-[1.1em]", "rounded-[0.25em]", "top-1/2", "-translate-y-1/2"); expect(logo).toHaveClass("h-[1.1em]", "w-[1.1em]", "rounded-[0.25em]", "top-1/2", "-translate-y-1/2");
expect(logo.parentElement).toHaveClass("mr-1", "w-[1.1em]"); expect(logo.parentElement).toHaveClass("mr-1", "w-[1.1em]");
@@ -57,7 +57,7 @@ describe("ThinkingReasoningShell", () => {
view.rerender(shell(false)); view.rerender(shell(false));
expect(screen.getByRole("button", { name: "Worked, Collapse activity details" })).toBe(button); expect(screen.getByRole("button", { name: "Worked, Collapse activity details" })).toBe(button);
expect(screen.getByText("Worked")).toHaveClass("text-muted-foreground/65"); expect(screen.getByText("Worked")).toHaveClass("text-muted-foreground");
expect(screen.getByText("Worked")).not.toHaveAttribute("data-sheen-text"); expect(screen.getByText("Worked")).not.toHaveAttribute("data-sheen-text");
expect(button.className).toBe(headerClass); expect(button.className).toBe(headerClass);
expect(screen.getByTestId("agent-activity-content")).toBe(content); expect(screen.getByTestId("agent-activity-content")).toBe(content);
+4 -5
View File
@@ -2506,8 +2506,8 @@ describe("ThreadComposer", () => {
expect(token.className).not.toContain("zoom-in"); expect(token.className).not.toContain("zoom-in");
expect(token.className).not.toContain("px-"); expect(token.className).not.toContain("px-");
expect(token.className).not.toContain("mx-"); expect(token.className).not.toContain("mx-");
expect(token.getAttribute("style")).toContain("color: #5C5543"); expect(token).toHaveClass("text-foreground");
expect(token.getAttribute("style")).not.toContain("text-shadow"); expect(token.style.textShadow).toBe("");
expect(screen.queryByTestId("composer-cli-app-tray")).not.toBeInTheDocument(); expect(screen.queryByTestId("composer-cli-app-tray")).not.toBeInTheDocument();
const logo = screen.getByTestId("composer-cli-mention-logo-gimp"); const logo = screen.getByTestId("composer-cli-mention-logo-gimp");
expect(logo.className).toContain("top-1/2"); expect(logo.className).toContain("top-1/2");
@@ -2543,7 +2543,7 @@ describe("ThreadComposer", () => {
expect(name).toHaveClass("[-webkit-text-stroke:0.4px_currentColor]"); expect(name).toHaveClass("[-webkit-text-stroke:0.4px_currentColor]");
}); });
it("uses the shared accent when an installed CLI app has no brand metadata", () => { it("uses the theme foreground when an installed CLI app has no brand metadata", () => {
const mention = "@obsidian-agent-cli"; const mention = "@obsidian-agent-cli";
const app: CliAppInfo = { const app: CliAppInfo = {
name: "obsidian-agent-cli", name: "obsidian-agent-cli",
@@ -2575,8 +2575,7 @@ describe("ThreadComposer", () => {
}); });
const token = screen.getByTestId("composer-cli-mention-obsidian-agent-cli"); const token = screen.getByTestId("composer-cli-mention-obsidian-agent-cli");
expect(token.getAttribute("style")).toContain("var(--inline-token-highlight)"); expect(token).toHaveClass("text-foreground");
expect(token.getAttribute("style")).not.toContain("var(--primary)");
}); });
it.each([ it.each([
+1 -1
View File
@@ -765,7 +765,7 @@ describe("ThreadMessages", () => {
const timestamp = menu.querySelector<HTMLElement>("[data-message-timestamp]")!; const timestamp = menu.querySelector<HTMLElement>("[data-message-timestamp]")!;
expect(timestamp).toBeInTheDocument(); expect(timestamp).toBeInTheDocument();
expect(timestamp).toHaveClass("min-h-[var(--message-block-control-size)]"); expect(timestamp).toHaveClass("min-h-[var(--message-block-control-size)]");
expect(timestamp.parentElement).toHaveClass("border-t", "text-muted-foreground/45"); expect(timestamp.parentElement).toHaveClass("border-t", "text-muted-foreground");
expect(toolbar).not.toContainElement(timestamp); expect(toolbar).not.toContainElement(timestamp);
expect(timestamp).not.toHaveAttribute("tabindex"); expect(timestamp).not.toHaveAttribute("tabindex");
expect(timestamp.querySelector("svg")).not.toBeInTheDocument(); expect(timestamp.querySelector("svg")).not.toBeInTheDocument();
+8
View File
@@ -92,6 +92,14 @@ export default {
DEFAULT: "hsl(var(--destructive))", DEFAULT: "hsl(var(--destructive))",
foreground: "hsl(var(--destructive-foreground))", foreground: "hsl(var(--destructive-foreground))",
}, },
"diff-added": {
DEFAULT: "var(--diff-added)",
foreground: "var(--diff-added-foreground)",
},
"diff-deleted": {
DEFAULT: "var(--diff-deleted)",
foreground: "var(--diff-deleted-foreground)",
},
border: "hsl(var(--border))", border: "hsl(var(--border))",
input: "hsl(var(--input))", input: "hsl(var(--input))",
ring: "hsl(var(--ring))", ring: "hsl(var(--ring))",