xonecas.io
64875
Mc

mini-coder / commit 42efa32

feat(ui): syntax-highlight shell tool previews

xonecas2026-04-11 42efa328a25c7bd84d2ff7b19bc1a1d7e2244970 parent 155412b

4 files changed

package.json+5−6
@@ -18,15 +18,14 @@
1818 "test": "bun test"
1919 },
2020 "dependencies": {
21- "@cel-tui/components": "^0.5.0",
22- "@cel-tui/core": "^0.5.0",
23- "@cel-tui/types": "^0.5.0",
24- "@mariozechner/pi-ai": "^0.66.1",
25- "diff": "^8.0.4"
21+ "@cel-tui/components": "^0.6.2",
22+ "@cel-tui/core": "^0.6.2",
23+ "@cel-tui/types": "^0.6.2",
24+ "@mariozechner/pi-ai": "^0.66.1"
2625 },
2726 "devDependencies": {
2827 "@biomejs/biome": "^2.4.11",
29- "@types/bun": "^1.3.11",
28+ "@types/bun": "^1.3.12",
3029 "lefthook": "^2.1.5",
3130 "prettier": "^3.8.2",
3231 "typescript": "^6.0.2"
src/ui.test.ts+6−0
@@ -55,6 +55,12 @@ function collectText(node: Node | null): string[] {
5555 if (node.type === "textinput") {
5656 return [];
5757 }
58+ if (
59+ node.type === "hstack" &&
60+ node.children.every((child) => child.type === "text")
61+ ) {
62+ return [node.children.map((child) => child.content).join("")];
63+ }
5864 return node.children.flatMap((child) => collectText(child));
5965 }
6066
src/ui/conversation.test.ts+165−1
@@ -40,6 +40,12 @@ function collectText(node: Node | null): string[] {
4040 if (node.type === "textinput") {
4141 return [];
4242 }
43+ if (
44+ node.type === "hstack" &&
45+ node.children.every((child) => child.type === "text")
46+ ) {
47+ return [node.children.map((child) => child.content).join("")];
48+ }
4349 return node.children.flatMap((child) => collectText(child));
4450 }
4551
@@ -524,6 +530,164 @@ describe("ui/conversation", () => {
524530 expect(text).not.toContain('"command": "echo hi"');
525531 });
526532
533+ test("renderAssistantMessage for a shell tool call syntax-highlights bash tokens", async () => {
534+ // Arrange
535+ const assistant = {
536+ content: [
537+ fauxToolCall(
538+ "shell",
539+ { command: 'if true; then echo "$HOME"; fi' },
540+ { id: "tool-1" },
541+ ),
542+ ],
543+ };
544+
545+ // Act
546+ const rows = await renderBufferRows(
547+ renderAssistantMessage(assistant, RENDER_OPTS),
548+ 48,
549+ 12,
550+ );
551+ const commandRow = rows.find((row) =>
552+ row.text.includes('if true; then echo "$HOME"; fi'),
553+ );
554+
555+ // Assert
556+ expect(commandRow).toBeDefined();
557+ expect(commandRow?.fgColors[commandRow.text.indexOf("if")]).toBe(
558+ DEFAULT_THEME.secondaryAccentText ?? null,
559+ );
560+ expect(commandRow?.fgColors[commandRow.text.indexOf("echo")]).toBe(
561+ DEFAULT_THEME.accentText ?? null,
562+ );
563+ expect(commandRow?.fgColors[commandRow.text.indexOf('"$HOME"')]).toBe(
564+ DEFAULT_THEME.diffAdded ?? null,
565+ );
566+ });
567+
568+ test("renderAssistantMessage for a multiline shell tool call preserves syntax state across lines", async () => {
569+ // Arrange
570+ const assistant = {
571+ content: [
572+ fauxToolCall(
573+ "shell",
574+ { command: "printf 'foo\nbar'" },
575+ { id: "tool-1" },
576+ ),
577+ ],
578+ };
579+
580+ // Act
581+ const rows = await renderBufferRows(
582+ renderAssistantMessage(assistant, {
583+ ...RENDER_OPTS,
584+ verbose: true,
585+ }),
586+ 32,
587+ 12,
588+ );
589+ const firstRow = rows.find((row) => row.text.includes("printf 'foo"));
590+ const secondRow = rows.find((row) => row.text.includes("bar'"));
591+
592+ // Assert
593+ expect(firstRow).toBeDefined();
594+ expect(secondRow).toBeDefined();
595+ expect(firstRow?.fgColors[firstRow.text.indexOf("foo")]).toBe(
596+ DEFAULT_THEME.diffAdded ?? null,
597+ );
598+ expect(secondRow?.fgColors[secondRow.text.indexOf("bar")]).toBe(
599+ DEFAULT_THEME.diffAdded ?? null,
600+ );
601+ });
602+
603+ test("renderAssistantMessage for a shell tool call uses theme-derived syntax colors", async () => {
604+ // Arrange
605+ const theme = {
606+ ...DEFAULT_THEME,
607+ accentText: "color14",
608+ secondaryAccentText: "color09",
609+ diffAdded: "color10",
610+ mutedText: "color13",
611+ toolText: "color15",
612+ } satisfies typeof DEFAULT_THEME;
613+ const assistant = {
614+ content: [
615+ fauxToolCall(
616+ "shell",
617+ { command: 'if true; then echo "$HOME"; fi' },
618+ { id: "tool-1" },
619+ ),
620+ ],
621+ };
622+
623+ // Act
624+ const rows = await renderBufferRows(
625+ renderAssistantMessage(assistant, {
626+ ...RENDER_OPTS,
627+ theme,
628+ }),
629+ 48,
630+ 12,
631+ );
632+ const commandRow = rows.find((row) =>
633+ row.text.includes('if true; then echo "$HOME"; fi'),
634+ );
635+
636+ // Assert
637+ expect(commandRow).toBeDefined();
638+ expect(commandRow?.fgColors[commandRow.text.indexOf("if")]).toBe(
639+ theme.secondaryAccentText ?? null,
640+ );
641+ expect(commandRow?.fgColors[commandRow.text.indexOf("echo")]).toBe(
642+ theme.accentText ?? null,
643+ );
644+ expect(commandRow?.fgColors[commandRow.text.indexOf('"$HOME"')]).toBe(
645+ theme.diffAdded ?? null,
646+ );
647+ });
648+
649+ test("renderAssistantMessage for a long single-token shell argument wraps through the tail in verbose mode", async () => {
650+ // Arrange
651+ const command = `printf ${"x".repeat(60)}TAIL`;
652+ const assistant = {
653+ content: [fauxToolCall("shell", { command }, { id: "tool-1" })],
654+ };
655+
656+ // Act
657+ const text = await renderVisibleText(
658+ renderAssistantMessage(assistant, {
659+ ...RENDER_OPTS,
660+ verbose: true,
661+ previewWidth: 24,
662+ }),
663+ 24,
664+ 20,
665+ );
666+
667+ // Assert
668+ expect(text.some((line) => line.includes("TAIL"))).toBe(true);
669+ });
670+
671+ test("renderAssistantMessage for a long single-token shell command uses wrapped preview height when verbose is off", () => {
672+ // Arrange
673+ const command = `printf ${"x".repeat(220)}TAIL`;
674+ const assistant = {
675+ content: [fauxToolCall("shell", { command }, { id: "tool-1" })],
676+ };
677+
678+ // Act
679+ const height = measureRenderedHeight(
680+ renderAssistantMessage(assistant, {
681+ ...RENDER_OPTS,
682+ previewWidth: 24,
683+ }),
684+ 24,
685+ );
686+
687+ // Assert
688+ expect(height).toBe(9);
689+ });
690+
527691 test("renderAssistantMessage for a wrapped shell command keeps a fixed preview height when verbose is off", () => {
528692 // Arrange
529693 const command = Array.from(
@@ -564,7 +728,7 @@ describe("ui/conversation", () => {
564728 );
565729
566730 // Assert
567- expect(text).toContain("IMPORTANT_PREFIX");
731+ expect(text.some((line) => line.includes("IMPORTANT_PREFIX"))).toBe(true);
568732 });
569733
570734 test("renderToolResult for a shell preview allows the outer conversation scroll to handle mouse wheel events", async () => {
src/ui/conversation.ts+231−33
@@ -8,9 +8,13 @@
88 * @module
99 */
1010
11-import { Markdown } from "@cel-tui/components";
11+import {
12+ Markdown,
13+ SyntaxHighlight,
14+ type SyntaxHighlightTheme,
15+} from "@cel-tui/components";
1216 import { HStack, measureContentHeight, Text, VStack } from "@cel-tui/core";
13-import type { Node } from "@cel-tui/types";
17+import type { Color, Node } from "@cel-tui/types";
1418 import type {
1519 AssistantMessage,
1620 TextContent,
@@ -33,6 +37,26 @@ const DEFAULT_TOOL_PREVIEW_WIDTH = 80;
3337 /** Horizontal columns consumed by tool-block padding and the left border. */
3438 const TOOL_BLOCK_CHROME_WIDTH = 4;
3539
40+/** ANSI16 fallback hex values for syntax-highlighter theme overrides. */
41+const ANSI_COLOR_HEX: Readonly<Record<Color, string>> = {
42+ color00: "#000000",
43+ color01: "#cd3131",
44+ color02: "#0dbc79",
45+ color03: "#e5e510",
46+ color04: "#2472c8",
47+ color05: "#bc3fbc",
48+ color06: "#11a8cd",
49+ color07: "#e5e5e5",
50+ color08: "#666666",
51+ color09: "#f14c4c",
52+ color10: "#23d18b",
53+ color11: "#f5f543",
54+ color12: "#3b8eea",
55+ color13: "#d670d6",
56+ color14: "#29b8db",
57+ color15: "#ffffff",
58+};
59+
3660 /** A pending tool result shown in the streaming tail. */
3761 export interface PendingToolResult {
3862 /** Tool call id from the assistant message. */
@@ -110,6 +134,13 @@ type ToolRenderLineKind =
110134 | "summary"
111135 | "error";
112136
137+interface HighlightedToolBodySpec {
138+ /** Full raw source content to syntax-highlight. */
139+ text: string;
140+ /** Registered lextide language id. */
141+ language: string;
142+}
143+
113144 interface ToolBlockSpec {
114145 /** Tool name shown in the header pill. */
115146 toolName: string;
@@ -117,6 +148,8 @@ interface ToolBlockSpec {
117148 direction: ToolRenderDirection;
118149 /** Logical body lines for the tool block. */
119150 bodyLines: readonly ToolRenderLine[];
151+ /** Optional syntax-highlighted body rendered from the full unsplit source. */
152+ highlightedBody?: HighlightedToolBodySpec;
120153 /** Whether `/verbose` preview rules apply to the body. */
121154 previewBody: boolean;
122155 }
@@ -339,6 +372,159 @@ function getToolHeaderColor(toolName: string, theme: Theme) {
339372 }
340373 }
341374
375+type SyntaxThemeRegistration = Exclude<SyntaxHighlightTheme, string>;
376+type SyntaxThemeTokenColor = NonNullable<
377+ SyntaxThemeRegistration["tokenColors"]
378+>[number];
379+
380+const graphemeSegmenter = new Intl.Segmenter(undefined, {
381+ granularity: "grapheme",
382+});
383+const shellSyntaxThemeCache = new WeakMap<Theme, SyntaxThemeRegistration>();
384+
385+function colorToHex(color: Color | undefined): string | undefined {
386+ return color ? ANSI_COLOR_HEX[color] : undefined;
387+}
388+
389+function pushSyntaxTokenColor(
390+ tokenColors: SyntaxThemeTokenColor[],
391+ scope: string | readonly string[],
392+ foreground: Color | undefined,
393+ fontStyle?: string,
394+): void {
395+ const foregroundHex = colorToHex(foreground);
396+ if (!foregroundHex && !fontStyle) {
397+ return;
398+ }
399+
400+ tokenColors.push({
401+ scope,
402+ settings: {
403+ ...(foregroundHex ? { foreground: foregroundHex } : {}),
404+ ...(fontStyle ? { fontStyle } : {}),
405+ },
406+ });
407+}
408+
409+function getShellSyntaxTheme(theme: Theme): SyntaxThemeRegistration {
410+ const cached = shellSyntaxThemeCache.get(theme);
411+ if (cached) {
412+ return cached;
413+ }
414+
415+ const tokenColors: SyntaxThemeTokenColor[] = [];
416+ pushSyntaxTokenColor(tokenColors, ["comment", "quote"], theme.mutedText);
417+ pushSyntaxTokenColor(
418+ tokenColors,
419+ ["keyword", "storage"],
420+ theme.secondaryAccentText,
421+ );
422+ pushSyntaxTokenColor(
423+ tokenColors,
424+ [
425+ "entity.name.function",
426+ "function",
427+ "meta.function-call",
428+ "support.function",
429+ "title",
430+ ],
431+ theme.accentText,
432+ );
433+ pushSyntaxTokenColor(
434+ tokenColors,
435+ [
436+ "built_in",
437+ "class",
438+ "entity.name.type",
439+ "entity.other.inherited-class",
440+ "support.class",
441+ "support.type",
442+ "type",
443+ ],
444+ theme.accentText,
445+ );
446+ pushSyntaxTokenColor(
447+ tokenColors,
448+ ["constant.language", "constant.numeric", "literal", "symbol"],
449+ theme.secondaryAccentText ?? theme.accentText,
450+ );
451+ pushSyntaxTokenColor(
452+ tokenColors,
453+ ["markup.inline", "string"],
454+ theme.diffAdded,
455+ );
456+ pushSyntaxTokenColor(tokenColors, "regexp", theme.diffRemoved);
457+ pushSyntaxTokenColor(
458+ tokenColors,
459+ ["attr", "attribute", "entity.other.attribute-name", "property"],
460+ theme.accentText,
461+ );
462+ pushSyntaxTokenColor(
463+ tokenColors,
464+ ["entity.name.tag", "name", "tag"],
465+ theme.accentText,
466+ );
467+
468+ const syntaxTheme: SyntaxThemeRegistration = {
469+ ...(colorToHex(theme.toolText) ? { fg: colorToHex(theme.toolText) } : {}),
470+ tokenColors,
471+ };
472+ shellSyntaxThemeCache.set(theme, syntaxTheme);
473+ return syntaxTheme;
474+}
475+
476+function splitHighlightedTextNode(
477+ node: Extract<Node, { type: "text" }>,
478+): Node[] {
479+ if (node.content === "") {
480+ return [Text("", node.props)];
481+ }
482+
483+ const parts = node.content.match(/\s+|\S+/gu);
484+ if (!parts) {
485+ return [Text(node.content, node.props)];
486+ }
487+
488+ const children: Node[] = [];
489+ for (const part of parts) {
490+ if (/^\s+$/u.test(part)) {
491+ children.push(Text(part, node.props));
492+ continue;
493+ }
494+
495+ for (const { segment } of graphemeSegmenter.segment(part)) {
496+ children.push(Text(segment, node.props));
497+ }
498+ }
499+
500+ return children;
501+}
502+
503+function normalizeHighlightedToolLine(line: Node): Node {
504+ if (line.type !== "hstack") {
505+ return line;
506+ }
507+
508+ const children = line.children.flatMap((child) => {
509+ return child.type === "text" ? splitHighlightedTextNode(child) : [child];
510+ });
511+ return HStack(line.props, children);
512+}
513+
514+function getHighlightedToolBodyLines(
515+ spec: HighlightedToolBodySpec,
516+ theme: Theme,
517+): Node[] {
518+ if (spec.text === "") {
519+ return [];
520+ }
521+
522+ const highlighted = SyntaxHighlight(spec.text, spec.language, {
523+ theme: getShellSyntaxTheme(theme),
524+ });
525+ return highlighted.children.map((line) => normalizeHighlightedToolLine(line));
526+}
527+
342528 /** Render a single styled text node for a tool line. */
343529 function renderToolLine(line: ToolRenderLine, theme: Theme): Node {
344530 switch (line.kind) {
@@ -374,41 +560,28 @@ function renderToolLines(
374560 return lines.map((line) => renderToolLine(line, theme));
375561 }
376562
377-function measureToolLinesHeight(
378- lines: readonly ToolRenderLine[],
379- width: number,
380- theme: Theme,
381-): number {
563+function measureToolNodesHeight(lines: readonly Node[], width: number): number {
382564 if (lines.length === 0) {
383565 return 0;
384566 }
385567
386- return measureContentHeight(VStack({}, renderToolLines(lines, theme)), {
387- width,
388- });
568+ return measureContentHeight(VStack({}, [...lines]), { width });
389569 }
390570
391-function measureToolLineHeight(
392- line: ToolRenderLine,
393- width: number,
394- theme: Theme,
395-): number {
396- return measureContentHeight(VStack({}, [renderToolLine(line, theme)]), {
397- width,
398- });
571+function measureToolNodeHeight(line: Node, width: number): number {
572+ return measureContentHeight(VStack({}, [line]), { width });
399573 }
400574
401-function countVisibleTailLines(
402- lines: readonly ToolRenderLine[],
575+function countVisibleTailNodes(
576+ lines: readonly Node[],
403577 width: number,
404- theme: Theme,
405578 maxRows: number,
406579 ): number {
407580 let remainingRows = maxRows;
408581 let visibleLineCount = 0;
409582
410583 for (let index = lines.length - 1; index >= 0; index--) {
411- const lineHeight = measureToolLineHeight(lines[index]!, width, theme);
584+ const lineHeight = measureToolNodeHeight(lines[index]!, width);
412585 if (lineHeight > remainingRows) {
413586 return visibleLineCount > 0 ? visibleLineCount : 1;
414587 }
@@ -432,8 +605,8 @@ function renderToolHeaderPill(
432605 ]);
433606 }
434607
435-function renderToolBody(
436- lines: readonly ToolRenderLine[],
608+function renderToolBodyFromNodes(
609+ lines: readonly Node[],
437610 previewBody: boolean,
438611 opts: Pick<ConversationRenderOpts, "previewWidth" | "theme" | "verbose">,
439612 ): { body: Node | null; summary?: ToolRenderLine } {
@@ -441,21 +614,19 @@ function renderToolBody(
441614 return { body: null };
442615 }
443616
444- const renderedLines = renderToolLines(lines, opts.theme);
445617 if (opts.verbose || !previewBody) {
446- return { body: VStack({}, renderedLines) };
618+ return { body: VStack({}, [...lines]) };
447619 }
448620
449621 const bodyWidth = getToolBodyWidth(opts.previewWidth);
450- const totalHeight = measureToolLinesHeight(lines, bodyWidth, opts.theme);
622+ const totalHeight = measureToolNodesHeight(lines, bodyWidth);
451623 if (totalHeight <= UI_TOOL_PREVIEW_ROWS) {
452- return { body: VStack({}, renderedLines) };
624+ return { body: VStack({}, [...lines]) };
453625 }
454626
455- const visibleLineCount = countVisibleTailLines(
627+ const visibleLineCount = countVisibleTailNodes(
456628 lines,
457629 bodyWidth,
458- opts.theme,
459630 UI_TOOL_PREVIEW_ROWS,
460631 );
461632 const previewLines = lines.slice(-visibleLineCount);
@@ -466,7 +637,7 @@ function renderToolBody(
466637 {
467638 height: UI_TOOL_PREVIEW_ROWS,
468639 },
469- renderToolLines(previewLines, opts.theme),
640+ [...previewLines],
470641 ),
471642 summary:
472643 hiddenLineCount > 0
@@ -478,12 +649,31 @@ function renderToolBody(
478649 };
479650 }
480651
652+function renderToolBody(
653+ spec: ToolBlockSpec,
654+ opts: Pick<ConversationRenderOpts, "previewWidth" | "theme" | "verbose">,
655+): { body: Node | null; summary?: ToolRenderLine } {
656+ if (spec.highlightedBody) {
657+ return renderToolBodyFromNodes(
658+ getHighlightedToolBodyLines(spec.highlightedBody, opts.theme),
659+ spec.previewBody,
660+ opts,
661+ );
662+ }
663+
664+ return renderToolBodyFromNodes(
665+ renderToolLines(spec.bodyLines, opts.theme),
666+ spec.previewBody,
667+ opts,
668+ );
669+}
670+
481671 /** Render a tool block with a left border and compact header pill. */
482672 function renderToolBlock(
483673 spec: ToolBlockSpec,
484674 opts: Pick<ConversationRenderOpts, "previewWidth" | "theme" | "verbose">,
485675 ): Node {
486- const body = renderToolBody(spec.bodyLines, spec.previewBody, opts);
676+ const body = renderToolBody(spec, opts);
487677 const children: Node[] = [
488678 HStack({}, [
489679 renderToolHeaderPill(spec.toolName, spec.direction, opts.theme),
@@ -511,10 +701,18 @@ function getToolContentText(content: ToolResultMessage["content"]): string {
511701 }
512702
513703 function buildShellToolCallSpec(args: Record<string, unknown>): ToolBlockSpec {
704+ const command = getToolArgString(args, "command");
514705 return {
515706 toolName: "shell",
516707 direction: "->",
517- bodyLines: splitToolTextLines(getToolArgString(args, "command"), "command"),
708+ bodyLines: splitToolTextLines(command, "command"),
709+ highlightedBody:
710+ command === ""
711+ ? undefined
712+ : {
713+ text: command,
714+ language: "bash",
715+ },
518716 previewBody: true,
519717 };
520718 }