From 832df4548cf939854a61bbd35df236f62ef04190 Mon Sep 17 00:00:00 2001 From: Andreas Gohr Date: Thu, 26 Nov 2026 20:40:53 +0000 Subject: [PATCH] Colour the code blocks in chat output A code block in a thread showed plain text. The dashboard already had Shiki for the code pane of the review, so the code blocks now use the same highlighter. The highlighter accepts the short language names of code fences, such as `ts` and `sh`, and has the grammars for `tsx` and `jsx`. A block gets its colours when the message is complete. A block in a language without a grammar stays plain. --- dashboard/e2e/ux.test.ts | 46 ++++++++++++ .../assistant-ui/elements/code-highlight.tsx | 72 +++++++++++++++++++ .../assistant-ui/elements/markdown-text.tsx | 3 + dashboard/src/globals.css | 11 +-- dashboard/src/lib/highlight.test.ts | 16 +++++ dashboard/src/lib/highlight.ts | 62 ++++++++++++---- 6 files changed, 191 insertions(+), 19 deletions(-) create mode 100644 dashboard/src/components/assistant-ui/elements/code-highlight.tsx create mode 100644 dashboard/src/lib/highlight.test.ts diff --git a/dashboard/e2e/ux.test.ts b/dashboard/e2e/ux.test.ts index 3077663a..d1d0b956 100644 --- a/dashboard/e2e/ux.test.ts +++ b/dashboard/e2e/ux.test.ts @@ -740,6 +740,52 @@ test('a mermaid block shows its source while streaming, then a diagram that open } }); +// A code block gets syntax colours once the message is complete. A block in a +// language without a grammar stays plain. +test('a code block shows plain text while streaming, then syntax colours', async () => { + const code = '```ts\nconst answer: number = 42;\n```'; + const plain = '```klingon\nqaplah\n```'; + await start({ + prompts: [ + { + match: () => true, + updates: reply(`here it is\n\n${code}\n\nand another\n\n${plain}\n`), + hold: true, + }, + ], + }); + + const { page, errors, close } = await openPage( + stub.url, + `/boxes/${BOX.id}/threads/${BOX.threadId}`, + ); + try { + const input = page.getByLabel('Message input'); + await input.fill('show me code'); + await input.press('Control+Enter'); + + const block = page.locator('.aui-md-pre code').first(); + await expect + .poll(() => block.textContent(), { timeout: 10_000 }) + .toBe('const answer: number = 42;\n'); + expect(await block.locator('span').count()).toBe(0); + + stub.gateway.release(); + await expect.poll(() => block.locator('span').count(), { timeout: 10_000 }).toBeGreaterThan(1); + // The text stays the same, and a keyword gets a colour of its own. + expect(await block.textContent()).toBe('const answer: number = 42;\n'); + const colours = await block + .locator('span') + .evaluateAll((spans) => new Set(spans.map((span) => getComputedStyle(span).color)).size); + expect(colours).toBeGreaterThan(1); + expect(await page.locator('.aui-md-pre code').last().locator('span').count()).toBe(0); + await shoot(page, 'code-block-phone'); + expect(errors).toEqual([]); + } finally { + await close(); + } +}); + test('the mode switcher lists the advertised modes and sets one', async () => { await start({ modes: { diff --git a/dashboard/src/components/assistant-ui/elements/code-highlight.tsx b/dashboard/src/components/assistant-ui/elements/code-highlight.tsx new file mode 100644 index 00000000..b16b24f0 --- /dev/null +++ b/dashboard/src/components/assistant-ui/elements/code-highlight.tsx @@ -0,0 +1,72 @@ +"use client"; + +import { type CSSProperties, type FC, Fragment, useEffect, useState } from "react"; +import { useAuiState } from "@assistant-ui/react"; +import type { SyntaxHighlighterProps } from "@assistant-ui/react-markdown"; + +import { type Token, tokenizeLines } from "@/lib/highlight"; + +/** + * Shows a code block with syntax colouring. + * + * While the message is still streaming, the block shows plain text, so a + * growing block is not tokenized again for each change. The block also stays + * plain when no grammar exists for its language, or when the code is too long + * to tokenize. + * + * @param code The code of the block. + * @param language The language from the info string of the code fence. + * @param components The Pre and Code components that show the code. + */ +export const CodeHighlight: FC = ({ + code, + language, + components: { Pre, Code }, +}) => { + const streaming = useAuiState((s) => s.part.status.type === "running"); + const [result, setResult] = useState<{ + code: string; + language: string; + lines: Token[][] | null; + }>(); + + useEffect(() => { + if (streaming) return; + let current = true; + tokenizeLines(code, language).then( + (lines) => current && setResult({ code, language, lines }), + ); + return () => { + current = false; + }; + }, [code, language, streaming]); + + // A result for other code or another language is stale. + const lines = + result?.code === code && result.language === language + ? result.lines + : null; + + return ( + // Pre renders again only for a new markdown node, so the key makes it show the colours. +
+      
+        {lines
+          ? lines.map((tokens, i) => (
+              // biome-ignore lint/suspicious/noArrayIndexKey: lines have no id, and the block is replaced whole
+              
+                {i > 0 && "\n"}
+                {tokens.map((token, j) => (
+                  // The span carries both theme colours, and the stylesheet picks one.
+                  // biome-ignore lint/suspicious/noArrayIndexKey: tokens have no id, and a line is replaced whole
+                  
+                    {token.content}
+                  
+                ))}
+              
+            ))
+          : code}
+      
+    
+ ); +}; diff --git a/dashboard/src/components/assistant-ui/elements/markdown-text.tsx b/dashboard/src/components/assistant-ui/elements/markdown-text.tsx index 60b9811a..7204e92d 100644 --- a/dashboard/src/components/assistant-ui/elements/markdown-text.tsx +++ b/dashboard/src/components/assistant-ui/elements/markdown-text.tsx @@ -15,6 +15,7 @@ import { useParams } from "react-router"; import type { TextMessagePartProps } from "@assistant-ui/react"; import { CheckIcon, CopyIcon } from "lucide-react"; +import { CodeHighlight } from "@/components/assistant-ui/elements/code-highlight"; import { ImageZoom } from "@/components/assistant-ui/elements/image"; import { MermaidDiagram } from "@/components/assistant-ui/elements/mermaid-diagram"; import { TooltipIconButton } from "@/components/assistant-ui/elements/tooltip-icon-button"; @@ -379,4 +380,6 @@ const defaultComponents = memoizeMarkdownComponents({ ); }, CodeHeader, + // Boxes edit: colours the code of a block with the highlighter of the review. + SyntaxHighlighter: CodeHighlight, }); diff --git a/dashboard/src/globals.css b/dashboard/src/globals.css index e7604119..d50f6ec9 100644 --- a/dashboard/src/globals.css +++ b/dashboard/src/globals.css @@ -151,14 +151,17 @@ ); /* - * The review's code pane. Shiki puts the light and the dark colour of each - * token on its span as custom properties, and these rules pick one. + * The review's code pane and the code blocks in chat output. Shiki puts the + * light and the dark colour of each token on its span as custom properties, + * and these rules pick one. */ -[data-line] code span { +[data-line] code span, +.aui-md-pre code span { color: var(--shiki-light); } -.dark [data-line] code span { +.dark [data-line] code span, +.dark .aui-md-pre code span { color: var(--shiki-dark); } diff --git a/dashboard/src/lib/highlight.test.ts b/dashboard/src/lib/highlight.test.ts new file mode 100644 index 00000000..9697d029 --- /dev/null +++ b/dashboard/src/lib/highlight.test.ts @@ -0,0 +1,16 @@ +import assert from 'node:assert/strict'; +import { test } from 'vitest'; +import { tokenizeLines } from './highlight.ts'; + +test('an alias from a code fence selects the grammar of its language', async () => { + const lines = await tokenizeLines('const a = 1;\nlet b = 2;', 'TS'); + assert.ok(lines); + assert.equal(lines.length, 2); + assert.equal(lines[0]?.map((token) => token.content).join(''), 'const a = 1;'); + assert.ok(lines[0]?.some((token) => token.style['--shiki-light'] && token.style['--shiki-dark'])); +}); + +test('a language without a grammar stays plain', async () => { + assert.equal(await tokenizeLines('anything', 'klingon'), null); + assert.equal(await tokenizeLines('anything', ''), null); +}); diff --git a/dashboard/src/lib/highlight.ts b/dashboard/src/lib/highlight.ts index 1787679d..a068b880 100644 --- a/dashboard/src/lib/highlight.ts +++ b/dashboard/src/lib/highlight.ts @@ -1,9 +1,10 @@ /** - * Client-side syntax highlighting for the review's code pane. + * Client-side syntax highlighting for the review's code pane and for the code + * blocks in chat output. * - * The API sends plain text, so each line can be its own row. The engine, the - * themes and the grammars are imported lazily, so only the review route loads - * them. + * The text is tokenized into one token list per line, so each line can be its + * own row. The engine, the themes and the grammars are imported lazily, so only + * a view that shows code loads them. */ import type { HighlighterCore, LanguageInput, ThemedToken } from 'shiki/core'; @@ -23,10 +24,12 @@ export interface Token { style: Record; } -/** The grammars that the code pane can load, by the language name that the API reports. */ +/** The grammars that can be loaded, by language name. */ const GRAMMARS: Record = { typescript: () => import('@shikijs/langs/typescript'), + tsx: () => import('@shikijs/langs/tsx'), javascript: () => import('@shikijs/langs/javascript'), + jsx: () => import('@shikijs/langs/jsx'), json: () => import('@shikijs/langs/json'), css: () => import('@shikijs/langs/css'), scss: () => import('@shikijs/langs/scss'), @@ -61,14 +64,42 @@ const GRAMMARS: Record = { diff: () => import('@shikijs/langs/diff'), }; +/** Other names of the languages in {@link GRAMMARS}, as the info string of a markdown code fence often gives them. */ +const ALIASES: Record = { + ts: 'typescript', + mts: 'typescript', + cts: 'typescript', + js: 'javascript', + mjs: 'javascript', + cjs: 'javascript', + sh: 'bash', + shell: 'bash', + zsh: 'bash', + py: 'python', + yml: 'yaml', + md: 'markdown', + dockerfile: 'docker', + make: 'makefile', + golang: 'go', + rb: 'ruby', + rs: 'rust', + 'c++': 'cpp', + cs: 'csharp', + kt: 'kotlin', + htm: 'html', + patch: 'diff', +}; + /** - * Checks if a language has a grammar to load. + * Gives the name of the grammar for a language name or an alias. * - * @param language The language name that the API reports. - * @returns True when a grammar exists. + * @param language A language name that the API reports, or an alias of one. + * @returns The key in {@link GRAMMARS}, or null when no grammar exists. */ -function canHighlight(language: string): boolean { - return language in GRAMMARS; +function grammarName(language: string): string | null { + const name = language.toLowerCase(); + const resolved = ALIASES[name] ?? name; + return resolved in GRAMMARS ? resolved : null; } /** The shared highlighter, once {@link highlighter} has started creating it. */ @@ -109,7 +140,7 @@ const loaded = new Map>(); /** * Loads one grammar into the shared highlighter, at most once. * - * @param language The language name that the API reports. + * @param language A key in {@link GRAMMARS}. */ async function loadGrammar(language: string): Promise { const grammar = GRAMMARS[language]; @@ -163,19 +194,20 @@ export function withinLineLimit(content: string): boolean { * failure in the grammar. * * @param content The text of the file. - * @param language The language name that the API reports. + * @param language The language name that the API reports, or an alias of one. * @returns One token list per line, or null for a plain file. */ export async function tokenizeLines(content: string, language: string): Promise { - if (!canHighlight(language)) return null; + const grammar = grammarName(language); + if (!grammar) return null; if (!withinLineLimit(content)) return null; if (content.split('\n').some((line) => line.length > MAX_LINE)) return null; try { - await loadGrammar(language); + await loadGrammar(grammar); const core = await highlighter(); const { tokens } = core.codeToTokens(content, { - lang: language, + lang: grammar, themes: THEMES, // No default colour, so the page's .dark class picks the theme. defaultColor: false,