xonecas.io
64875
Mc

mini-coder / commit 04ecf26

feat: render assistant markdown with syntax highlighting

xonecas2026-04-12 04ecf26eb4ea9c78368232c9a071609639c01f50 parent f5f4770

3 files changed

spec.md+4−4
@@ -40,13 +40,13 @@ This replaces: `ai`, `@ai-sdk/anthropic`, `@ai-sdk/openai`, `@ai-sdk/google`, `@
4040 Declarative TUI framework with flexbox layout, built for exactly the kind of UI we need:
4141
4242 - **Primitives**: `VStack`, `HStack`, `Text`, `TextInput` — composable, flexbox-based.
43-- **Components**: `Markdown` (streaming-aware), `Button`, `Select`, `Divider`, `Spacer`.
43+- **Components**: `SyntaxHighlight` (streaming-aware), `Button`, `Select`, `Divider`, `Spacer`.
4444 - **Input**: Kitty keyboard protocol, proper key handling, mouse scroll/click.
4545 - **Rendering**: Differential cell-buffer rendering, synchronized output (no flicker).
4646 - **Scroll**: Controlled/uncontrolled scroll with stick-to-bottom support.
4747 - **Focus**: Tab/Shift+Tab traversal, controlled/uncontrolled focus.
4848
49-The chat example (`cel-tui/examples/chat.ts`) is essentially a skeleton of our UI. Markdown streaming, TextInput, scroll — it's all there.
49+The chat example (`cel-tui/examples/chat.ts`) is essentially a skeleton of our UI. TextInput, scroll, and streaming updates — it's all there.
5050
5151 This replaces: `yoctocolors`, `yoctomarkdown`, `yoctoselect`, and all our custom widget/rendering code.
5252
@@ -207,7 +207,7 @@ The core runtime. Streaming is the default behavior throughout the turn: user-vi
207207 2. **Build context** — construct a pi-ai `Context`: the system prompt (see [System prompt](#system-prompt)), the full message history, and the registered tool definitions (built-in + plugin tools). Git state in the session footer is refreshed at session start and after each turn.
208208
209209 3. **Stream to LLM** — call `streamSimple(model, context, options)` from pi-ai. Iterate over the event stream:
210- - `text_delta` / `thinking_delta` / `toolcall_delta` → update the in-progress assistant message and the UI incrementally (stream markdown, show thinking if enabled, accumulate tool call arguments as they arrive).
210+ - `text_delta` / `thinking_delta` / `toolcall_delta` → update the in-progress assistant message and the UI incrementally (stream raw markdown text, show thinking if enabled, accumulate tool call arguments as they arrive).
211211 - `toolcall_end` → finalize the structured tool call in the in-progress `AssistantMessage`.
212212 - `done` → append the `AssistantMessage` to history and DB. Update cumulative stats. If `stopReason` is `"toolUse"`, go to step 4. If `"stop"` or `"length"`, return to the input prompt.
213213 - `error` → display error in the log, return to the input prompt.
@@ -542,7 +542,7 @@ Message types and their rendering:
542542 Tool blocks share a common frame: a left border (`│`) plus a compact header pill naming the tool and direction (`tool ->` for assistant tool calls, `tool <-` for tool results). The body renders tool-specific content rather than raw JSON.
543543
544544 - **User messages**: displayed as plain text with a subtle background color to distinguish them from agent responses. No prefix or role indicator.
545-- **Assistant messages**: streamed markdown rendered via cel-tui's `Markdown` component on the default background. Thinking/reasoning content is collapsible (shown or hidden according to the user's persisted `/reasoning` preference; defaults to shown when no setting exists).
545+- **Assistant messages**: streamed raw markdown rendered via cel-tui's `SyntaxHighlight` component on the default background so the log stays copy-friendly and preserves markdown markers. Thinking/reasoning content is collapsible (shown or hidden according to the user's persisted `/reasoning` preference; defaults to shown when no setting exists).
546546 - **Tool calls — shell**: rendered in the shared tool frame. The assistant tool call streams the command as it arrives. The command preview and shell tool result body use [verbose tool rendering](#verbose-tool-rendering). Shell tool results render the tool output content below a `shell <-` header.
547547 - **Tool calls — edit**: rendered in the shared tool frame. The in-progress tool-call preview shows the target path plus the streamed replacement content, preserving whitespace. The preview body uses [verbose tool rendering](#verbose-tool-rendering). Successful results render a compact confirmation block (`edit <-` plus the file path); errors render the returned error text.
548548 - **Tool calls — readImage**: rendered in the shared tool frame. The assistant tool call streams the path as it arrives. Successful results render a compact result block (`read image <-` plus the file path) rather than rendering the image itself.
src/ui/conversation.test.ts+107−15
@@ -64,7 +64,15 @@ async function renderBufferRows(
6464 node: Node | null,
6565 cols = PREVIEW_WIDTH,
6666 rows = 24,
67-): Promise<Array<{ text: string; fgColors: Array<string | null> }>> {
67+): Promise<
68+ Array<{
69+ text: string;
70+ fgColors: Array<string | null>;
71+ bold: boolean[];
72+ italic: boolean[];
73+ underline: boolean[];
74+ }>
75+> {
6876 if (!node) {
6977 return [];
7078 }
@@ -79,16 +87,28 @@ async function renderBufferRows(
7987 throw new Error("Expected cel-tui to produce a render buffer");
8088 }
8189
82- const snapshot: Array<{ text: string; fgColors: Array<string | null> }> = [];
90+ const snapshot: Array<{
91+ text: string;
92+ fgColors: Array<string | null>;
93+ bold: boolean[];
94+ italic: boolean[];
95+ underline: boolean[];
96+ }> = [];
8397 for (let y = 0; y < rows; y++) {
8498 let text = "";
8599 const fgColors: Array<string | null> = [];
100+ const bold: boolean[] = [];
101+ const italic: boolean[] = [];
102+ const underline: boolean[] = [];
86103 for (let x = 0; x < cols; x++) {
87104 const cell = buffer.get(x, y);
88105 text += cell.char;
89106 fgColors.push(cell.fgColor);
107+ bold.push(cell.bold);
108+ italic.push(cell.italic);
109+ underline.push(cell.underline);
90110 }
91- snapshot.push({ text, fgColors });
111+ snapshot.push({ text, fgColors, bold, italic, underline });
92112 }
93113
94114 cel.stop();
@@ -119,18 +139,20 @@ afterEach(() => {
119139 });
120140
121141 describe("ui/conversation", () => {
122- test("renderAssistantMessage preserves visible paragraph order in streamed markdown", () => {
142+ test("renderAssistantMessage keeps raw markdown markers visible in assistant text", () => {
123143 // Arrange
124- const message = fauxAssistantMessage("First paragraph\n\nSecond paragraph");
144+ const message = fauxAssistantMessage(
145+ "# Heading\n\nUse **bold** and `code`.\n- item",
146+ );
125147
126148 // Act
127149 const text = collectText(renderAssistantMessage(message, RENDER_OPTS));
128- const firstParagraphIndex = text.indexOf("First paragraph");
129- const secondParagraphIndex = text.indexOf("Second paragraph");
130150
131151 // Assert
132- expect(firstParagraphIndex).toBeGreaterThanOrEqual(0);
133- expect(secondParagraphIndex).toBeGreaterThan(firstParagraphIndex);
152+ expect(text).toContain("# Heading");
153+ expect(text).toContain("Use **bold** and `code`.");
154+ expect(text).toContain("- item");
155+ expect(text).not.toContain("Use bold and code.");
134156 });
135157
136158 test("renderAssistantMessage with reasoning enabled shows thinking blocks", () => {
@@ -196,18 +218,88 @@ describe("ui/conversation", () => {
196218 expect(height).toBe(6);
197219 });
198220
199- test("renderAssistantMessage keeps markdown paragraph spacing inside a single text block", () => {
221+ test("renderAssistantMessage syntax-highlights markdown tokens with theme-derived colors", async () => {
200222 // Arrange
201- const message = fauxAssistantMessage("First paragraph\n\nSecond paragraph");
223+ const theme = {
224+ ...DEFAULT_THEME,
225+ accentText: "color14",
226+ secondaryAccentText: "color09",
227+ diffAdded: "color10",
228+ mutedText: "color13",
229+ } satisfies typeof DEFAULT_THEME;
230+ const message = fauxAssistantMessage("# Heading\n- item\n> quote\n`code`");
202231
203232 // Act
204- const height = measureRenderedHeight(
205- renderAssistantMessage(message, RENDER_OPTS),
206- PREVIEW_WIDTH,
233+ const rows = await renderBufferRows(
234+ renderAssistantMessage(message, {
235+ ...RENDER_OPTS,
236+ theme,
237+ }),
238+ 32,
239+ 12,
207240 );
241+ const headingRow = rows.find((row) => row.text.includes("# Heading"));
242+ const bulletRow = rows.find((row) => row.text.includes("- item"));
243+ const quoteRow = rows.find((row) => row.text.includes("> quote"));
244+ const codeRow = rows.find((row) => row.text.includes("`code`"));
208245
209246 // Assert
210- expect(height).toBe(3);
247+ expect(headingRow).toBeDefined();
248+ expect(bulletRow).toBeDefined();
249+ expect(quoteRow).toBeDefined();
250+ expect(codeRow).toBeDefined();
251+ expect(headingRow?.fgColors[headingRow.text.indexOf("#")]).toBe(
252+ theme.accentText ?? null,
253+ );
254+ expect(bulletRow?.fgColors[bulletRow.text.indexOf("-")]).toBe(
255+ theme.secondaryAccentText ?? null,
256+ );
257+ expect(quoteRow?.fgColors[quoteRow.text.indexOf(">")]).toBe(
258+ theme.mutedText ?? null,
259+ );
260+ expect(quoteRow?.italic[quoteRow.text.indexOf(">")]).toBe(true);
261+ expect(codeRow?.fgColors[codeRow.text.indexOf("`")]).toBe(
262+ theme.diffAdded ?? null,
263+ );
264+ });
265+
266+ test("renderAssistantMessage syntax-highlights markdown emphasis and links with style cues", async () => {
267+ // Arrange
268+ const theme = {
269+ ...DEFAULT_THEME,
270+ accentText: "color14",
271+ diffAdded: "color10",
272+ } satisfies typeof DEFAULT_THEME;
273+ const message = fauxAssistantMessage(
274+ "*italic* **bold** [label](https://example.com)",
275+ );
276+
277+ // Act
278+ const rows = await renderBufferRows(
279+ renderAssistantMessage(message, {
280+ ...RENDER_OPTS,
281+ theme,
282+ }),
283+ 64,
284+ 12,
285+ );
286+ const contentRow = rows.find((row) =>
287+ row.text.includes("*italic* **bold** [label](https://example.com)"),
288+ );
289+
290+ // Assert
291+ expect(contentRow).toBeDefined();
292+ expect(contentRow?.italic[contentRow.text.indexOf("*italic*")]).toBe(true);
293+ expect(contentRow?.bold[contentRow.text.indexOf("**bold**")]).toBe(true);
294+ expect(contentRow?.fgColors[contentRow.text.indexOf("label")]).toBe(
295+ theme.diffAdded ?? null,
296+ );
297+ expect(
298+ contentRow?.fgColors[contentRow.text.indexOf("https://example.com")],
299+ ).toBe(theme.accentText ?? null);
300+ expect(
301+ contentRow?.underline[contentRow.text.indexOf("https://example.com")],
302+ ).toBe(true);
211303 });
212304
213305 test("buildConversationLogNodes with a pending shell result keeps the streamed call and result append-only", () => {
src/ui/conversation.ts+81−30
@@ -9,7 +9,6 @@
99 */
1010
1111 import {
12- Markdown,
1312 SyntaxHighlight,
1413 type SyntaxHighlightTheme,
1514 } from "@cel-tui/components";
@@ -142,11 +141,15 @@ type ToolRenderLineKind =
142141 | "summary"
143142 | "error";
144143
145-interface HighlightedToolBodySpec {
144+type SyntaxThemeVariant = "markdown" | "shell";
145+
146+interface HighlightedBodySpec {
146147 /** Full raw source content to syntax-highlight. */
147148 text: string;
148149 /** Registered lextide language id. */
149150 language: string;
151+ /** Semantic theme variant for this highlighted content. */
152+ themeVariant: SyntaxThemeVariant;
150153 }
151154
152155 interface ToolBlockSpec {
@@ -157,7 +160,7 @@ interface ToolBlockSpec {
157160 /** Logical body lines for the tool block. */
158161 bodyLines: readonly ToolRenderLine[];
159162 /** Optional syntax-highlighted body rendered from the full unsplit source. */
160- highlightedBody?: HighlightedToolBodySpec;
163+ highlightedBody?: HighlightedBodySpec;
161164 /** Whether `/verbose` preview rules apply to the body. */
162165 previewBody: boolean;
163166 }
@@ -222,16 +225,25 @@ function renderUserMessage(msg: UserMessage, theme: Theme): Node {
222225 ]);
223226 }
224227
225-/** Render a markdown block with stable internal paragraph spacing. */
226-function renderMarkdownBlock(content: string): Node | null {
227- const children = Markdown(content).map((node) => {
228- if (node.type === "text" && node.content === "") {
229- return node;
230- }
231- return HStack({ padding: { x: 1 } }, [VStack({ flex: 1 }, [node])]);
232- });
228+/** Render a syntax-highlighted raw markdown block. */
229+function renderMarkdownTextBlock(content: string, theme: Theme): Node | null {
230+ if (content === "") {
231+ return null;
232+ }
233233
234- return children.length > 0 ? VStack({ gap: 0 }, children) : null;
234+ const children = getHighlightedBodyLines(
235+ {
236+ text: content,
237+ language: "markdown",
238+ themeVariant: "markdown",
239+ },
240+ theme,
241+ );
242+ if (children.length === 0) {
243+ return null;
244+ }
245+
246+ return HStack({ padding: { x: 1 } }, [VStack({ flex: 1 }, children)]);
235247 }
236248
237249 function getAssistantErrorMessage(
@@ -275,7 +287,7 @@ function renderAssistantContentBlock(
275287 opts: ConversationRenderOpts,
276288 ): Node | null {
277289 if (block.type === "text" && block.text) {
278- return renderMarkdownBlock(block.text);
290+ return renderMarkdownTextBlock(block.text, opts.theme);
279291 }
280292 if (block.type === "thinking" && block.thinking) {
281293 return renderThinkingBlock(block.thinking, opts);
@@ -388,7 +400,13 @@ type SyntaxThemeTokenColor = NonNullable<
388400 const graphemeSegmenter = new Intl.Segmenter(undefined, {
389401 granularity: "grapheme",
390402 });
391-const shellSyntaxThemeCache = new WeakMap<Theme, SyntaxThemeRegistration>();
403+const syntaxThemeCache: Record<
404+ SyntaxThemeVariant,
405+ WeakMap<Theme, SyntaxThemeRegistration>
406+> = {
407+ markdown: new WeakMap(),
408+ shell: new WeakMap(),
409+};
392410
393411 function colorToHex(color: Color | undefined): string | undefined {
394412 return color ? ANSI_COLOR_HEX[color] : undefined;
@@ -414,14 +432,11 @@ function pushSyntaxTokenColor(
414432 });
415433 }
416434
417-function getShellSyntaxTheme(theme: Theme): SyntaxThemeRegistration {
418- const cached = shellSyntaxThemeCache.get(theme);
419- if (cached) {
420- return cached;
421- }
422-
423- const tokenColors: SyntaxThemeTokenColor[] = [];
424- pushSyntaxTokenColor(tokenColors, ["comment", "quote"], theme.mutedText);
435+function pushShellSyntaxTokenColors(
436+ tokenColors: SyntaxThemeTokenColor[],
437+ theme: Theme,
438+): void {
439+ pushSyntaxTokenColor(tokenColors, "comment", theme.mutedText);
425440 pushSyntaxTokenColor(
426441 tokenColors,
427442 ["keyword", "storage"],
@@ -472,12 +487,47 @@ function getShellSyntaxTheme(theme: Theme): SyntaxThemeRegistration {
472487 ["entity.name.tag", "name", "tag"],
473488 theme.accentText,
474489 );
490+}
491+
492+function pushMarkdownSyntaxTokenColors(
493+ tokenColors: SyntaxThemeTokenColor[],
494+ theme: Theme,
495+): void {
496+ pushSyntaxTokenColor(tokenColors, "quote", theme.mutedText, "italic");
497+ pushSyntaxTokenColor(tokenColors, "section", theme.accentText, "bold");
498+ pushSyntaxTokenColor(
499+ tokenColors,
500+ "bullet",
501+ theme.secondaryAccentText,
502+ "bold",
503+ );
504+ pushSyntaxTokenColor(tokenColors, ["code", "string"], theme.diffAdded);
505+ pushSyntaxTokenColor(tokenColors, "link", theme.accentText, "underline");
506+ pushSyntaxTokenColor(tokenColors, "strong", undefined, "bold");
507+ pushSyntaxTokenColor(tokenColors, "emphasis", undefined, "italic");
508+}
509+
510+function getSyntaxTheme(
511+ theme: Theme,
512+ variant: SyntaxThemeVariant,
513+): SyntaxThemeRegistration {
514+ const cache = syntaxThemeCache[variant];
515+ const cached = cache.get(theme);
516+ if (cached) {
517+ return cached;
518+ }
519+
520+ const tokenColors: SyntaxThemeTokenColor[] = [];
521+ if (variant === "shell") {
522+ pushShellSyntaxTokenColors(tokenColors, theme);
523+ } else {
524+ pushMarkdownSyntaxTokenColors(tokenColors, theme);
525+ }
475526
476527 const syntaxTheme: SyntaxThemeRegistration = {
477- ...(colorToHex(theme.toolText) ? { fg: colorToHex(theme.toolText) } : {}),
478528 tokenColors,
479529 };
480- shellSyntaxThemeCache.set(theme, syntaxTheme);
530+ cache.set(theme, syntaxTheme);
481531 return syntaxTheme;
482532 }
483533
@@ -508,7 +558,7 @@ function splitHighlightedTextNode(
508558 return children;
509559 }
510560
511-function normalizeHighlightedToolLine(line: Node): Node {
561+function normalizeHighlightedLine(line: Node): Node {
512562 if (line.type !== "hstack") {
513563 return line;
514564 }
@@ -519,8 +569,8 @@ function normalizeHighlightedToolLine(line: Node): Node {
519569 return HStack(line.props, children);
520570 }
521571
522-function getHighlightedToolBodyLines(
523- spec: HighlightedToolBodySpec,
572+function getHighlightedBodyLines(
573+ spec: HighlightedBodySpec,
524574 theme: Theme,
525575 ): Node[] {
526576 if (spec.text === "") {
@@ -528,9 +578,9 @@ function getHighlightedToolBodyLines(
528578 }
529579
530580 const highlighted = SyntaxHighlight(spec.text, spec.language, {
531- theme: getShellSyntaxTheme(theme),
581+ theme: getSyntaxTheme(theme, spec.themeVariant),
532582 });
533- return highlighted.children.map((line) => normalizeHighlightedToolLine(line));
583+ return highlighted.children.map((line) => normalizeHighlightedLine(line));
534584 }
535585
536586 /** Render a single styled text node for a tool line. */
@@ -663,7 +713,7 @@ function renderToolBody(
663713 ): { body: Node | null; summary?: ToolRenderLine } {
664714 if (spec.highlightedBody) {
665715 return renderToolBodyFromNodes(
666- getHighlightedToolBodyLines(spec.highlightedBody, opts.theme),
716+ getHighlightedBodyLines(spec.highlightedBody, opts.theme),
667717 spec.previewBody,
668718 opts,
669719 );
@@ -720,6 +770,7 @@ function buildShellToolCallSpec(args: Record<string, unknown>): ToolBlockSpec {
720770 : {
721771 text: command,
722772 language: "bash",
773+ themeVariant: "shell",
723774 },
724775 previewBody: true,
725776 };