Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(chat): syntax-color fenced code blocks with Monaco colorize

reviewd5e4218f3ca3
diff --git a/src/renderer/lib/codeHighlight.test.ts b/src/renderer/lib/codeHighlight.test.ts
new file mode 100644
index 000000000..598e9a5b1
--- /dev/null
+++ b/src/renderer/lib/codeHighlight.test.ts
@@ -0,0 +1,145 @@
+// @vitest-environment jsdom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { fenceLanguage, highlightCodeBlocks } from './codeHighlight'
+
+/**
+ * Syntax colors for the ⌘M chat view's fenced code blocks (glue: nodes/CodeHighlight.tsx). The fence
+ * names a language through marked's `language-<x>` class; the colorizer is injected, so nothing here
+ * loads Monaco. What is pinned: which fences are colored, that a block is colored once, and that the
+ * colored block's TEXT is still exactly what the agent wrote — the code-block Copy reads it.
+ */
+
+describe('fenceLanguage', () => {
+ it.each([
+ ['language-ts', 'typescript'],
+ ['language-tsx', 'typescript'],
+ ['language-jsx', 'javascript'],
+ ['language-mjs', 'javascript'],
+ ['language-SH', 'shell'],
+ ['language-zsh', 'shell'],
+ ['language-console', 'shell'],
+ ['language-py', 'python'],
+ ['language-yml', 'yaml'],
+ ['language-jsonc', 'json'],
+ ['language-xml', 'xml'],
+ ['language-scss', 'scss'],
+ ['language-kt', 'kotlin'],
+ ['language-h', 'c'],
+ ['language-c++', 'cpp'],
+ ['language-cs', 'csharp'],
+ ['language-Dockerfile', 'dockerfile'],
+ ['language-toml', 'ini'],
+ ['language-ps1', 'powershell']
+ ])('%s → %s', (cls, id) => expect(fenceLanguage(cls)).toBe(id))
+
+ it('is null for no class, an unknown language and a diff fence', () => {
+ expect(fenceLanguage('')).toBeNull()
+ expect(fenceLanguage('language-foo')).toBeNull()
+ expect(fenceLanguage('language-diff')).toBeNull()
+ expect(fenceLanguage('language-patch')).toBeNull()
+ })
+
+ it('never answers with an inherited property name (the fence text is the agent’s)', () => {
+ expect(fenceLanguage('language-constructor')).toBeNull()
+ expect(fenceLanguage('language-__proto__')).toBeNull()
+ expect(fenceLanguage('language-toString')).toBeNull()
+ })
+})
+
+/** What Monaco 0.57's `editor.colorize` actually returns (measured): every space and tab rendered as
+ * U+00A0, `<`/`>`/`&` escaped, and EVERY line — the last included — ended with `<br/>`. */
+function monacoShaped(text: string): string {
+ return text
+ .split('\n')
+ .map((line) => {
+ if (line === '') return '<span><span></span></span><br/>'
+ const shown = line.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/[ \t]/g, '\u00a0')
+ return `<span><span class="mtk6">${shown}</span></span><br/>`
+ })
+ .join('')
+}
+
+describe('highlightCodeBlocks', () => {
+ let root: HTMLDivElement
+ beforeEach(() => {
+ root = document.createElement('div')
+ document.body.appendChild(root)
+ })
+ afterEach(() => root.remove())
+
+ it('colors a known fence once, keeps newlines, and leaves unknown and plain blocks alone', async () => {
+ root.innerHTML =
+ '<pre><code class="language-ts">const a = 1\nlet b</code></pre><pre><code class="language-foo">x</code></pre><pre><code>y</code></pre>'
+ const colorize = vi.fn(async (t: string) =>
+ t
+ .split('\n')
+ .map((l) => `<span class="mtk5">${l}</span>`)
+ .join('<br/>')
+ )
+
+ await highlightCodeBlocks(root, colorize)
+ await highlightCodeBlocks(root, colorize)
+
+ expect(colorize).toHaveBeenCalledTimes(1)
+ expect(colorize).toHaveBeenCalledWith('const a = 1\nlet b', 'typescript')
+ const code = root.querySelector('code')!
+ expect(code.dataset.highlighted).toBe('typescript')
+ expect(code.querySelectorAll('span.mtk5')).toHaveLength(2)
+ expect(code.textContent).toBe('const a = 1\nlet b')
+ expect(root.querySelectorAll('code')[1].innerHTML).toBe('x')
+ expect(root.querySelectorAll('code')[2].innerHTML).toBe('y')
+ })
+
+ it('keeps the source text exactly through Monaco’s output shape', async () => {
+ // Spaces, a tab, markup characters, and the newline marked leaves before </code>.
+ const source = 'if (a < b && c) {\n\treturn "x"\n}\n'
+ const escaped = source.replace(/&/g, '&amp;').replace(/</g, '&lt;')
+ root.innerHTML = `<pre><code class="language-js">${escaped}</code></pre>`
+
+ await highlightCodeBlocks(root, async (t) => monacoShaped(t))
+
+ const code = root.querySelector('code')!
+ expect(code.dataset.highlighted).toBe('javascript')
+ expect(code.querySelectorAll('span.mtk6')).toHaveLength(3)
+ // Not one U+00A0: a pasted `npm run build` with them is a single word to a shell.
+ expect(code.textContent).toBe(source)
+ })
+
+ it('leaves the block as it was when the colorizer’s text cannot be lined up with the source', async () => {
+ root.innerHTML = '<pre><code class="language-go">\tx := 1</code></pre>'
+ // A tab expanded to two cells: one character more than the source has.
+ const colorize = async () => '<span class="mtk6">\u00a0\u00a0x\u00a0:=\u00a01</span>'
+
+ await highlightCodeBlocks(root, colorize)
+
+ const code = root.querySelector('code')!
+ expect(code.hasAttribute('data-highlighted')).toBe(false)
+ expect(code.innerHTML).toBe('\tx := 1')
+ })
+
+ it('a rejected colorize leaves the block unchanged', async () => {
+ root.innerHTML = '<pre><code class="language-py">print(1)</code></pre>'
+
+ await highlightCodeBlocks(root, async () => {
+ throw new Error('no tokenizer')
+ })
+
+ const code = root.querySelector('code')!
+ expect(code.hasAttribute('data-highlighted')).toBe(false)
+ expect(code.innerHTML).toBe('print(1)')
+ })
+
+ it('does not touch a block that left the document while it was being colored', async () => {
+ root.innerHTML = '<pre><code class="language-sh">ls</code></pre>'
+ const code = root.querySelector('code')!
+ let finish: (html: string) => void = () => {}
+ const run = highlightCodeBlocks(root, () => new Promise<string>((r) => (finish = r)))
+
+ root.innerHTML = '' // the message re-rendered: React replaced the container's children
+ finish('<span class="mtk6">ls</span>')
+ await run
+
+ expect(code.hasAttribute('data-highlighted')).toBe(false)
+ expect(code.innerHTML).toBe('ls')
+ })
+})
diff --git a/src/renderer/lib/codeHighlight.ts b/src/renderer/lib/codeHighlight.ts
new file mode 100644
index 000000000..4292fb6ce
--- /dev/null
+++ b/src/renderer/lib/codeHighlight.ts
@@ -0,0 +1,128 @@
+/**
+ * Syntax colors for the fenced code blocks of the ⌘M chat view (React + Monaco glue:
+ * nodes/CodeHighlight.tsx). The Markdown is already HTML in the DOM by the time this runs, so the
+ * blocks are found there: marked names a fence's language as the `language-<x>` class on its
+ * `<code>`, and the colorizer is injected — this module never loads Monaco.
+ */
+
+/** Colors `text` as `language` and returns the HTML: token spans, lines separated by `<br/>`. */
+export type Colorize = (text: string, language: string) => Promise<string>
+
+/**
+ * Fence name (lower-cased) → Monaco language id. The table is the whole contract: a fence it does
+ * not name stays plain. A Map, not an object literal — the fence text is the agent's, and
+ * `language-constructor` must not find `Object.prototype.constructor`.
+ */
+const FENCE_LANGUAGES: ReadonlyMap<string, string | null> = new Map([
+ ...aliases('typescript', 'ts', 'typescript', 'tsx'),
+ ...aliases('javascript', 'js', 'javascript', 'mjs', 'cjs', 'jsx'),
+ ...aliases('shell', 'sh', 'bash', 'shell', 'zsh', 'console'),
+ ...aliases('python', 'py', 'python'),
+ ...aliases('yaml', 'yml', 'yaml'),
+ ...aliases('json', 'json', 'jsonc'),
+ ...aliases('markdown', 'md', 'markdown'),
+ ...aliases('rust', 'rs', 'rust'),
+ ...aliases('go', 'go'),
+ ...aliases('ruby', 'rb', 'ruby'),
+ ...aliases('sql', 'sql'),
+ ...aliases('html', 'html'),
+ ...aliases('xml', 'xml'),
+ ...aliases('css', 'css'),
+ ...aliases('scss', 'scss'),
+ ...aliases('less', 'less'),
+ ...aliases('swift', 'swift'),
+ ...aliases('kotlin', 'kotlin', 'kt'),
+ ...aliases('java', 'java'),
+ ...aliases('c', 'c', 'h'),
+ ...aliases('cpp', 'cpp', 'cc', 'hpp', 'c++'),
+ ...aliases('csharp', 'cs', 'csharp'),
+ ...aliases('dockerfile', 'dockerfile'),
+ ...aliases('ini', 'ini', 'toml'),
+ ...aliases('graphql', 'graphql'),
+ ...aliases('lua', 'lua'),
+ ...aliases('php', 'php'),
+ ...aliases('powershell', 'ps1', 'powershell'),
+ ...aliases('r', 'r'),
+ ...aliases('scala', 'scala'),
+ ...aliases('dart', 'dart'),
+ // Named so the omission reads as a decision: Monaco has no diff grammar, so a diff stays plain.
+ ...aliases(null, 'diff', 'patch')
+])
+
+function aliases(language: string | null, ...names: string[]): Array<[string, string | null]> {
+ return names.map((name) => [name, language])
+}
+
+/** The Monaco language id for a `<code>` element's class (`language-ts` → `typescript`), or null. */
+export function fenceLanguage(className: string): string | null {
+ const m = /(?:^|\s)language-(\S+)/.exec(className)
+ return m === null ? null : (FENCE_LANGUAGES.get(m[1].toLowerCase()) ?? null)
+}
+
+/** The fenced blocks under `root` that still want colors, with the language each is colored as. */
+export function highlightableBlocks(root: ParentNode): Array<{ code: HTMLElement; language: string }> {
+ const blocks: Array<{ code: HTMLElement; language: string }> = []
+ for (const code of Array.from(root.querySelectorAll<HTMLElement>('pre > code'))) {
+ if (code.hasAttribute('data-highlighted')) continue
+ const language = fenceLanguage(code.className)
+ if (language !== null) blocks.push({ code, language })
+ }
+ return blocks
+}
+
+/**
+ * Color every fenced block under `root` in a language the table knows, once each (the colored block
+ * is marked `data-highlighted="<language>"`). A block that left the document while it was being
+ * colored is not touched, and one the colorizer rejects — or whose output cannot be lined up with
+ * its text — stays as it was.
+ */
+export async function highlightCodeBlocks(root: ParentNode, colorize: Colorize): Promise<void> {
+ await Promise.all(
+ highlightableBlocks(root).map(async ({ code, language }) => {
+ const source = code.textContent ?? ''
+ let html: string
+ try {
+ html = await colorize(source, language)
+ } catch {
+ return
+ }
+ if (!code.isConnected || code.hasAttribute('data-highlighted')) return
+ const colored = withSourceText(code.ownerDocument, html, source)
+ if (colored === null) return
+ code.replaceChildren(colored)
+ code.dataset.highlighted = language
+ })
+ )
+}
+
+/**
+ * The colorizer's HTML as a fragment whose text is exactly `source`, or null when the two cannot be
+ * lined up.
+ *
+ * Monaco's `colorize` renders for display, not for copying (measured on 0.57): every space and tab
+ * comes back as U+00A0, and every line — the last one included — ends with `<br/>`. The code-block
+ * Copy reads the block's `textContent`, and a pasted `npm run build` whose spaces are U+00A0 is one
+ * word to a shell. So the `<br/>`s become `\n`, the extra one after the last line is dropped, and
+ * each text node is then rewritten with the run of `source` it renders: the spans keep Monaco's
+ * colors, the characters are the agent's own. That needs one rendered character per source
+ * character — which is why the glue asks Monaco for `tabSize: 1` — and any output that does not
+ * add up to the source's length (a tab expanded to two cells, a dropped BOM) is refused, not
+ * guessed at: the block stays plain rather than copying wrong.
+ */
+function withSourceText(doc: Document, html: string, source: string): DocumentFragment | null {
+ const lines = html.split(/<br\s*\/?>/i)
+ if (lines.length === source.split('\n').length + 1 && lines[lines.length - 1] === '') lines.pop()
+ // A <template> parses inertly: nothing in it loads or runs before it is checked.
+ const template = doc.createElement('template')
+ template.innerHTML = lines.join('\n')
+ const walker = doc.createTreeWalker(template.content, NodeFilter.SHOW_TEXT)
+ let at = 0
+ for (let node = walker.nextNode(); node !== null; node = walker.nextNode()) {
+ const text = node as Text
+ const end = at + text.data.length
+ if (end > source.length) return null
+ text.data = source.slice(at, end)
+ at = end
+ }
+ return at === source.length ? template.content : null
+}
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 79f716a9c..cdfd84e99 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -55,6 +55,7 @@ import type { PermissionAnswer } from '@shared/agents/permission-answer'
import { ChatComposer } from './ChatComposer'
import { ChatTurnActions } from './ChatTurnActions'
import { useCodeBlockCopy } from './CodeBlockCopy'
+import { useCodeHighlight } from './CodeHighlight'
import { assistantTurnEnds } from '../lib/chatThread'
import { groupToolCalls, partPosition } from '../lib/chatToolGroups'
import { ChatToolGroup } from './ChatToolGroup'
@@ -65,11 +66,13 @@ import { chatPageDirection, pageChatThread } from '../lib/chatPageKeys'
// turn-finish reload, each keystroke re-render). Text is stable per message, so cache per text.
// `breaks`: a single newline is a line break, as Claude Code's own TUI renders it — without it a
// multi-line prompt, or a reply quoting one line by line (`> a` / `> b`), collapsed onto one line.
-// Every code block gets a Copy button in its top-right corner (useCodeBlockCopy).
+// Every code block gets a Copy button in its top-right corner (useCodeBlockCopy), and a fenced block
+// whose language lib/codeHighlight.ts names is syntax-colored by Monaco (useCodeHighlight).
export const MarkdownText = memo(function MarkdownText({ text }: { text: string }) {
const html = useMemo(() => renderMarkdown(text, { breaks: true }), [text])
const ref = useRef<HTMLDivElement>(null)
const copyButtons = useCodeBlockCopy(ref, html)
+ useCodeHighlight(ref, html)
return (
<>
<div ref={ref} className="term-chat__text" dangerouslySetInnerHTML={{ __html: html }} />
diff --git a/src/renderer/nodes/CodeBlockCopy.test.tsx b/src/renderer/nodes/CodeBlockCopy.test.tsx
index 37f3a6cda..d2d3b53ca 100644
--- a/src/renderer/nodes/CodeBlockCopy.test.tsx
+++ b/src/renderer/nodes/CodeBlockCopy.test.tsx
@@ -14,6 +14,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
vi.mock('../session/session', () => ({ useSession: () => ({ api: {} }) }))
import { MarkdownText } from './ChatPanel'
+import { setColorizerLoaderForTests } from './CodeHighlight'
let host: HTMLDivElement
let root: Root
@@ -21,6 +22,9 @@ const writeText = vi.fn()
beforeEach(() => {
writeText.mockClear()
+ // The sh/js fences below would load the real Monaco to color them; it never arrives here (the
+ // coloring has its own test, CodeHighlight.test.tsx), so these blocks stay plain.
+ setColorizerLoaderForTests(() => new Promise(() => {}))
;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = { clipboard: { writeText } }
host = document.createElement('div')
document.body.appendChild(host)
@@ -29,6 +33,7 @@ beforeEach(() => {
afterEach(async () => {
await act(async () => root.unmount())
host.remove()
+ setColorizerLoaderForTests(null)
})
const TWO_BLOCKS = 'Run `npm test`, then:\n\n```sh\nnpm run build\n```\n\nand\n\n```js\nif (a < b) {}\n```\n'
diff --git a/src/renderer/nodes/CodeHighlight.test.tsx b/src/renderer/nodes/CodeHighlight.test.tsx
new file mode 100644
index 000000000..e89755706
--- /dev/null
+++ b/src/renderer/nodes/CodeHighlight.test.tsx
@@ -0,0 +1,107 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest'
+import { DEFAULT_SETTINGS } from '@shared/types'
+import { useSettings } from '../state/settings'
+
+/**
+ * Syntax colors on the ⌘M chat view's fenced code blocks (pure half: lib/codeHighlight.ts). Pins the
+ * glue: Monaco is loaded only for a message that has a block to color, and through the injected
+ * loader (never the real Monaco here); the block is colored once; the corner Copy still copies the
+ * agent's text; and the token colors follow the app theme, which Monaco holds globally.
+ */
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+vi.mock('../session/session', () => ({ useSession: () => ({ api: {} }) }))
+
+import { MarkdownText } from './ChatPanel'
+import { setColorizerLoaderForTests, type Colorizer } from './CodeHighlight'
+
+/** Monaco 0.57's measured `colorize` shape: U+00A0 for spaces, `<br/>` after every line. */
+function monacoShaped(text: string): string {
+ return text
+ .split('\n')
+ .map((line) =>
+ line === ''
+ ? '<span><span></span></span><br/>'
+ : `<span><span class="mtk6">${line.replace(/ /g, '\u00a0')}</span></span><br/>`
+ )
+ .join('')
+}
+
+let host: HTMLDivElement
+let root: Root
+const writeText = vi.fn()
+let colorize: Mock<Colorizer['colorize']>
+let setTheme: Mock<Colorizer['setTheme']>
+let loader: Mock<() => Promise<Colorizer>>
+
+beforeEach(() => {
+ writeText.mockClear()
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ clipboard: { writeText },
+ settings: { save: vi.fn(async () => {}) }
+ }
+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS } })
+ colorize = vi.fn(async (text: string) => monacoShaped(text))
+ setTheme = vi.fn()
+ loader = vi.fn(async () => ({ colorize, setTheme }))
+ setColorizerLoaderForTests(loader)
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(async () => {
+ await act(async () => root.unmount())
+ host.remove()
+ setColorizerLoaderForTests(null)
+})
+
+const TS_BLOCK = 'Try:\n\n```ts\nconst a = 1\nlet b\n```\n'
+
+async function render(text: string): Promise<void> {
+ await act(async () => root.render(<MarkdownText text={text} />))
+ await act(async () => {
+ await new Promise((r) => setTimeout(r, 0))
+ })
+}
+
+describe('code block syntax colors', () => {
+ it('colors a fenced block in a known language, and Copy still copies the agent’s text', async () => {
+ await render(TS_BLOCK)
+
+ const code = host.querySelector('code[data-highlighted="typescript"]')
+ expect(code).not.toBeNull()
+ expect(code!.querySelectorAll('span.mtk6')).toHaveLength(2)
+
+ await act(async () => host.querySelector<HTMLButtonElement>('button[aria-label="Copy code"]')!.click())
+
+ expect(writeText).toHaveBeenCalledWith('const a = 1\nlet b')
+ })
+
+ it('colors the same message once', async () => {
+ await render(TS_BLOCK)
+ await render(TS_BLOCK)
+
+ expect(colorize).toHaveBeenCalledTimes(1)
+ expect(loader).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not load Monaco for a message with nothing to color', async () => {
+ await render('Run `npm test`, then:\n\n```\nplain\n```\n\nand\n\n```diff\n-a\n+b\n```\n')
+
+ expect(loader).not.toHaveBeenCalled()
+ expect(host.querySelector('code[data-highlighted]')).toBeNull()
+ })
+
+ it('puts Monaco on the app theme, and keeps it there when the theme changes', async () => {
+ await render(TS_BLOCK)
+ expect(setTheme).toHaveBeenLastCalledWith('dark')
+
+ await act(async () => useSettings.setState({ settings: { ...DEFAULT_SETTINGS, appTheme: 'light' } }))
+
+ expect(setTheme).toHaveBeenLastCalledWith('light')
+ })
+})
diff --git a/src/renderer/nodes/CodeHighlight.tsx b/src/renderer/nodes/CodeHighlight.tsx
new file mode 100644
index 000000000..24bffe789
--- /dev/null
+++ b/src/renderer/nodes/CodeHighlight.tsx
@@ -0,0 +1,79 @@
+import { useEffect, useRef, type RefObject } from 'react'
+import { highlightCodeBlocks, highlightableBlocks, type Colorize } from '../lib/codeHighlight'
+import { monacoTheme, type ResolvedAppTheme } from '../lib/appTheme'
+import { useAppTheme } from '../state/useAppTheme'
+
+/** What the chat needs from Monaco: its colorizer, and the global theme the token colors follow. */
+export interface Colorizer {
+ colorize: Colorize
+ setTheme: (theme: ResolvedAppTheme) => void
+}
+
+// Monaco is several MB of JS in its own lazy chunk (lazyMonacoNodes.tsx); the chat view only asks
+// for it once a message actually holds a block to color.
+async function loadMonacoColorizer(): Promise<Colorizer> {
+ const { monaco } = await import('../editor/monaco-setup')
+ return {
+ // tabSize 1, so a tab renders as ONE character and the colored text lines up with the source
+ // character for character (lib/codeHighlight.ts puts the real tab back, as wide as in a plain block).
+ colorize: (text, language) => monaco.editor.colorize(text, language, { tabSize: 1 }),
+ // The same global theme the editor and diff nodes set (see monacoTheme).
+ setTheme: (theme) => monaco.editor.setTheme(monacoTheme(theme))
+ }
+}
+
+let loader: () => Promise<Colorizer> = loadMonacoColorizer
+let loading: Promise<Colorizer> | null = null
+let loaded: Colorizer | null = null
+
+/** Monaco's colorizer, imported once. A failed import leaves every block plain until a reload. */
+function loadColorizer(): Promise<Colorizer> {
+ if (loading === null) {
+ loading = loader().then((colorizer) => (loaded = colorizer))
+ loading.catch((err: unknown) => console.warn('[chat] code highlighting unavailable:', err))
+ }
+ return loading
+}
+
+/** Replace the Monaco loader (null = the real one again) and forget anything already loaded. */
+export function setColorizerLoaderForTests(next: (() => Promise<Colorizer>) | null): void {
+ loader = next ?? loadMonacoColorizer
+ loading = null
+ loaded = null
+}
+
+/**
+ * Syntax colors on every fenced block in a language lib/codeHighlight.ts knows, in a
+ * rendered-Markdown container of the ⌘M chat view. Like useCodeBlockCopy, it works on the DOM
+ * after each new HTML string — in a passive effect, so after that hook's layout effect has wrapped
+ * the `<pre>`s. Coloring swaps a block's inner nodes, never the `<pre>` or `<code>` the Copy button
+ * reads, and leaves its text exactly as the agent wrote it.
+ */
+export function useCodeHighlight(container: RefObject<HTMLElement | null>, html: string): void {
+ // Read when the colorizer arrives, not when the effect ran: the import is async.
+ const theme = useAppTheme()
+ const themeRef = useRef(theme)
+ themeRef.current = theme
+
+ useEffect(() => {
+ const root = container.current
+ if (root === null || highlightableBlocks(root).length === 0) return
+ let current = true
+ loadColorizer().then(
+ (colorizer) => {
+ if (!current) return
+ colorizer.setTheme(themeRef.current)
+ return highlightCodeBlocks(root, colorizer.colorize)
+ },
+ () => {}
+ )
+ return () => {
+ current = false
+ }
+ }, [container, html])
+
+ // Monaco's token colors live in one global stylesheet; re-assert the theme when the app's moves.
+ useEffect(() => {
+ loaded?.setTheme(theme)
+ }, [theme])
+}
diff --git a/src/renderer/styles.chat-view.test.ts b/src/renderer/styles.chat-view.test.ts
index 6cd12f571..9d3195050 100644
--- a/src/renderer/styles.chat-view.test.ts
+++ b/src/renderer/styles.chat-view.test.ts
@@ -108,3 +108,9 @@ describe('the shared .term-chat__input (plan "Revise…", question "Other") keep
expect(ruleBody('.term-chat__msg--assistant .term-chat__text > p:last-child')).toMatch(/margin-bottom:\s*0;/)
})
})
+
+describe('⌘M code block syntax colors', () => {
+ it('a colored block keeps its whitespace: the code is split across token spans', () => {
+ expect(ruleBody('.term-chat__text pre code[data-highlighted]')).toMatch(/white-space:\s*pre;/)
+ })
+})
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index b814c4f3f..83e1c39bf 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -3583,6 +3583,11 @@ body,
.term-chat__code > pre {
margin: 0;
}
+/* A syntax-colored block (nodes/CodeHighlight.tsx): its text is split across Monaco's token spans,
+ which must not collapse the code's spaces or line breaks. */
+.term-chat__text pre code[data-highlighted] {
+ white-space: pre;
+}
/* Same control as the per-turn Copy (.term-chat__action), in the block's top-right corner. Hidden
until the block is hovered or the button is keyboard-focused, and kept while it says "Copied".
A solid backing so the code underneath does not show through it. */