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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(chat): recolor highlighted code blocks when the app theme changes
review787b7fce4cb4
diff --git a/src/renderer/lib/codeHighlight.test.ts b/src/renderer/lib/codeHighlight.test.tsindex 598e9a5b1..50493c343 100644--- a/src/renderer/lib/codeHighlight.test.ts+++ b/src/renderer/lib/codeHighlight.test.ts@@ -1,6 +1,6 @@// @vitest-environment jsdomimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import { fenceLanguage, highlightCodeBlocks } from './codeHighlight'+import { fenceLanguage, highlightCodeBlocks, recolorCodeBlocks } from './codeHighlight'/*** Syntax colors for the ⌘M chat view's fenced code blocks (glue: nodes/CodeHighlight.tsx). The fence@@ -142,4 +142,37 @@ describe('highlightCodeBlocks', () => {expect(code.hasAttribute('data-highlighted')).toBe(false)expect(code.innerHTML).toBe('ls')})++ it('recolors an already-colored block from its text, which is still the source afterwards', async () => {+ root.innerHTML = '<pre><code class="language-ts">const a = 1</code></pre>'+ await highlightCodeBlocks(root, async (t) => monacoShaped(t))+ // The other theme's color map: the same token, another class.+ const recolor = vi.fn(async (t: string) => monacoShaped(t).replace(/mtk6/g, 'mtk8'))++ await recolorCodeBlocks(root, recolor)++ const code = root.querySelector('code')!+ expect(recolor).toHaveBeenCalledWith('const a = 1', 'typescript')+ expect(code.querySelectorAll('span.mtk8')).toHaveLength(1)+ expect(code.querySelector('span.mtk6')).toBeNull()+ expect(code.dataset.highlighted).toBe('typescript')+ expect(code.textContent).toBe('const a = 1')+ })++ it('an older colorize that answers late does not land over a newer one', async () => {+ root.innerHTML = '<pre><code class="language-ts">x</code></pre>'+ let finishOld: (html: string) => void = () => {}+ let finishNew: (html: string) => void = () => {}+ const older = highlightCodeBlocks(root, () => new Promise<string>((r) => (finishOld = r)))+ const newer = recolorCodeBlocks(root, () => new Promise<string>((r) => (finishNew = r)))++ finishOld('<span class="mtk6">x</span>')+ await older+ finishNew('<span class="mtk8">x</span>')+ await newer++ const code = root.querySelector('code')!+ expect(code.querySelector('span.mtk8')).not.toBeNull()+ expect(code.querySelector('span.mtk6')).toBeNull()+ })})diff --git a/src/renderer/lib/codeHighlight.ts b/src/renderer/lib/codeHighlight.tsindex 4292fb6ce..44a0b22e6 100644--- a/src/renderer/lib/codeHighlight.ts+++ b/src/renderer/lib/codeHighlight.ts@@ -70,6 +70,11 @@ export function highlightableBlocks(root: ParentNode): Array<{ code: HTMLElementreturn blocks}+// The latest colorize asked for each block. Only its answer may land: a theme switch re-colors a+// block whose first colorize can still be in flight, and that older answer — in the old theme's+// classes — must not arrive after the new one and stay on screen.+const latestRequest = new WeakMap<Element, object>()+/*** 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@@ -80,13 +85,15 @@ export async function highlightCodeBlocks(root: ParentNode, colorize: Colorize):await Promise.all(highlightableBlocks(root).map(async ({ code, language }) => {const source = code.textContent ?? ''+ const request = {}+ latestRequest.set(code, request)let html: stringtry {html = await colorize(source, language)} catch {return}- if (!code.isConnected || code.hasAttribute('data-highlighted')) return+ if (!code.isConnected || latestRequest.get(code) !== request) returnconst colored = withSourceText(code.ownerDocument, html, source)if (colored === null) returncode.replaceChildren(colored)@@ -95,6 +102,20 @@ export async function highlightCodeBlocks(root: ParentNode, colorize: Colorize):)}+/**+ * Color the blocks under `root` again, the already-colored ones included — after a theme switch.+ * A token's class (`mtk<n>`) indexes the CURRENT theme's color map, and the light and dark maps+ * differ, so a block colored under the old theme keeps classes that now name other colors (a+ * keyword drawn in the comment color). Re-coloring from the block's text is lossless: that text is+ * exactly the source (see withSourceText).+ */+export function recolorCodeBlocks(root: ParentNode, colorize: Colorize): Promise<void> {+ for (const code of Array.from(root.querySelectorAll('pre > code[data-highlighted]'))) {+ code.removeAttribute('data-highlighted')+ }+ return highlightCodeBlocks(root, colorize)+}+/*** The colorizer's HTML as a fragment whose text is exactly `source`, or null when the two cannot be* lined up.diff --git a/src/renderer/nodes/CodeHighlight.test.tsx b/src/renderer/nodes/CodeHighlight.test.tsxindex e89755706..97fec847e 100644--- a/src/renderer/nodes/CodeHighlight.test.tsx+++ b/src/renderer/nodes/CodeHighlight.test.tsx@@ -96,6 +96,48 @@ describe('code block syntax colors', () => {expect(host.querySelector('code[data-highlighted]')).toBeNull()})+ it('a message mounted after Monaco has loaded is colored once too', async () => {+ await render(TS_BLOCK)+ const second = document.createElement('div')+ document.body.appendChild(second)+ const secondRoot = createRoot(second)+ await act(async () => secondRoot.render(<MarkdownText text={'```sh\nls -la\n```\n'} />))+ await act(async () => {+ await new Promise((r) => setTimeout(r, 0))+ })++ expect(colorize).toHaveBeenCalledTimes(2)+ expect(second.querySelector('code[data-highlighted="shell"]')).not.toBeNull()+ await act(async () => secondRoot.unmount())+ second.remove()+ })++ it('recolors a colored block when the theme changes, keeping its text', async () => {+ // Each theme numbers its token classes from its own color map, so a block colored under the old+ // theme reads the new stylesheet's colors through the wrong classes until it is colored again.+ let monacoThemeNow = 'dark'+ setTheme.mockImplementation((t) => {+ monacoThemeNow = t+ })+ colorize.mockImplementation(async (text) =>+ monacoShaped(text).replace(/mtk6/g, monacoThemeNow === 'light' ? 'mtk8' : 'mtk6')+ )+ await render(TS_BLOCK)+ expect(host.querySelectorAll('code span.mtk6')).toHaveLength(2)++ await act(async () => useSettings.setState({ settings: { ...DEFAULT_SETTINGS, appTheme: 'light' } }))+ await act(async () => {+ await new Promise((r) => setTimeout(r, 0))+ })++ expect(colorize).toHaveBeenCalledTimes(2)+ const code = host.querySelector('code[data-highlighted="typescript"]')!+ expect(code.querySelectorAll('span.mtk8')).toHaveLength(2)+ expect(code.querySelector('span.mtk6')).toBeNull()+ await act(async () => host.querySelector<HTMLButtonElement>('button[aria-label="Copy code"]')!.click())+ expect(writeText).toHaveBeenCalledWith('const a = 1\nlet b')+ })+it('puts Monaco on the app theme, and keeps it there when the theme changes', async () => {await render(TS_BLOCK)expect(setTheme).toHaveBeenLastCalledWith('dark')diff --git a/src/renderer/nodes/CodeHighlight.tsx b/src/renderer/nodes/CodeHighlight.tsxindex 24bffe789..fa04e88a7 100644--- a/src/renderer/nodes/CodeHighlight.tsx+++ b/src/renderer/nodes/CodeHighlight.tsx@@ -1,5 +1,5 @@import { useEffect, useRef, type RefObject } from 'react'-import { highlightCodeBlocks, highlightableBlocks, type Colorize } from '../lib/codeHighlight'+import { highlightCodeBlocks, highlightableBlocks, recolorCodeBlocks, type Colorize } from '../lib/codeHighlight'import { monacoTheme, type ResolvedAppTheme } from '../lib/appTheme'import { useAppTheme } from '../state/useAppTheme'@@ -72,8 +72,16 @@ export function useCodeHighlight(container: RefObject<HTMLElement | null>, html:}}, [container, html])- // Monaco's token colors live in one global stylesheet; re-assert the theme when the app's moves.+ // On a theme switch: put Monaco on the new theme (its token colors are one global stylesheet), then+ // color this container's blocks again — their classes index the old theme's color map. Skipped on+ // mount: nothing here is colored yet, and the effect above colors it in the current theme.+ const shownTheme = useRef(theme)useEffect(() => {- loaded?.setTheme(theme)- }, [theme])+ if (shownTheme.current === theme) return+ shownTheme.current = theme+ const root = container.current+ if (loaded === null || root === null) return+ loaded.setTheme(theme)+ void recolorCodeBlocks(root, loaded.colorize)+ }, [container, theme])}