Skip to content

Commit 0ab6637

Browse files
committed
feat(tui): color plugin and MCP tool output by language
Generic tool output was drawn as plain text, and nothing knows its type: a plugin tool returns a string and an MCP text result carries no content type, so a JSON result from `browser` read as a grey wall. `syntax.tool_output` in tui.json maps a tool name or glob (`browser`, `github_*`, `*`) to a language id, `auto` or `none`; an exact name wins over globs and the most specific glob over the rest (packages/tui/src/util/tool-output.ts). `auto` colors output that is a JSON object or array: a bounded sniff (bracket pair, at most 100,000 characters, one parse) whose answer is cached by content. Only output that is shown is sniffed or colored. Unset by default, so output stays plain as upstream draws it. The output is one text renderable whose content becomes the same text as colored chunks when the parser worker answers, so it wraps exactly as the plain text does (test/cli/tui/tool-output.test.tsx compares the frames at 40, 80 and 160 columns), and it uses the non-red tool-code palette, since red means a failed tool call. The whole output is highlighted, once and cached, even while the block is collapsed: a preview cut through the middle of a JSON value does not parse, so the preview takes the whole output's highlights that fall inside the part it shares with the output, and its ellipsis stays plain. AI-Model: anthropic/claude-opus-5-5 AI-Variant: high AI-Tool: opencode 1.19.0-vt-227-dfb56f76c7 AI-Platform: linux AI-Harness: Vibeterm e6434eb AI-Session-ID: ses_ed1e2b932ffe6tTqhsOiGuYXRE
1 parent c1c1d4f commit 0ab6637

7 files changed

Lines changed: 307 additions & 2 deletions

File tree

‎packages/tui/src/config/index.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,10 @@ export const Syntax = Schema.Struct({
5050
description:
5151
"Show a plugin or MCP tool's input as a block with one key per line, nested objects and arrays included, when it is too long or nested for one line (default: false)",
5252
}),
53+
tool_output: Schema.optional(Schema.Record(Schema.String, Schema.String)).annotate({
54+
description:
55+
"Color plugin and MCP tool output by tool name or glob ('browser', 'github_*', '*'): a language id such as 'json', 'auto' to color output recognized as JSON, or 'none'. An exact name wins over globs, the most specific glob over the rest. Unset leaves output plain (default)",
56+
}),
5357
}).annotate({ description: "Syntax highlighting in tool calls" })
5458
export const Cursor = Schema.Struct({
5559
style: Schema.optional(Schema.Literals(["block", "underline", "line", "default"])).annotate({

‎packages/tui/src/routes/session/index.tsx‎

Lines changed: 69 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,11 @@ import {
3333
RGBA,
3434
type MouseEvent,
3535
type Renderable,
36+
StyledText,
37+
TextRenderable,
3638
treeSitterToTextChunks,
3739
type SimpleHighlight,
40+
type TextChunk,
3841
} from "@opentui/core"
3942
import { Prompt, type PromptRef } from "../../component/prompt"
4043
import type {
@@ -69,6 +72,7 @@ import { Sidebar } from "./sidebar"
6972
import { SubagentFooter } from "./subagent-footer.tsx"
7073
import { detectFiletype, filetype } from "../../util/filetype"
7174
import { highlightCached } from "../../util/highlight-cache"
75+
import { outputLanguage, previewHighlights } from "../../util/tool-output"
7276
import { narrowBashHighlights } from "../../util/bash-highlight"
7377
import { highlightHeredocs } from "../../util/heredoc"
7478
import { toolCodeTheme } from "../../theme/tool-code"
@@ -2264,6 +2268,10 @@ function GenericTool(props: ToolProps) {
22642268
return collapsed().output
22652269
})
22662270
const showOutput = createMemo(() => Boolean(props.output && ctx.showGenericToolOutput()))
2271+
// Only output that is shown is sniffed or colored.
2272+
const language = createMemo(() =>
2273+
showOutput() ? outputLanguage(ctx.tui.syntax?.tool_output, props.tool, output()) : undefined,
2274+
)
22672275
// The block's measured width, reported on layout and on resize only; until then an estimate.
22682276
const [inputWidth, setInputWidth] = createSignal<number>()
22692277
const inputBlock = createMemo(() => {
@@ -2298,7 +2306,9 @@ function GenericTool(props: ToolProps) {
22982306
}}
22992307
/>
23002308
<Show when={showOutput() && limited()}>
2301-
<text fg={theme.text}>{limited()}</text>
2309+
<Show when={language()} fallback={<text fg={theme.text}>{limited()}</text>}>
2310+
{(language) => <ToolOutputText output={output()} shown={limited()} language={language()} />}
2311+
</Show>
23022312
</Show>
23032313
</BlockTool>
23042314
)}
@@ -2323,7 +2333,9 @@ function GenericTool(props: ToolProps) {
23232333
>
23242334
<Show when={!collapsed().overflow || expanded() || limited()}>
23252335
<box gap={1}>
2326-
<text fg={theme.text}>{limited()}</text>
2336+
<Show when={language()} fallback={<text fg={theme.text}>{limited()}</text>}>
2337+
{(language) => <ToolOutputText output={output()} shown={limited()} language={language()} />}
2338+
</Show>
23272339
</box>
23282340
</Show>
23292341
</BlockTool>
@@ -2361,6 +2373,61 @@ export function ToolInput(props: {
23612373
)
23622374
}
23632375

2376+
// A tool's output colored as `language`. It is drawn plain at once and takes its colors when the
2377+
// parser worker answers, in the same non-red palette as a bash command: red means failure.
2378+
// `shown` is the output as displayed: the whole of it, or a collapsed preview that is a prefix of it
2379+
// plus an ellipsis. The whole output is highlighted, once and cached, because a preview cut through
2380+
// the middle of a JSON value does not parse; the preview takes the highlights that fall inside the
2381+
// part it shares with the output, and the ellipsis stays plain.
2382+
function ToolOutputText(props: { output: string; shown: string; language: string }) {
2383+
const { theme, toolSyntax } = useTheme()
2384+
const [highlighted, setHighlighted] = createSignal<{
2385+
output: string
2386+
language: string
2387+
highlights: SimpleHighlight[]
2388+
}>()
2389+
createEffect(() => {
2390+
const output = props.output
2391+
const language = props.language
2392+
highlightCached(output, language)
2393+
.then((result) => setHighlighted({ output, language, highlights: result.highlights ?? [] }))
2394+
.catch(() => setHighlighted(undefined))
2395+
})
2396+
const chunks = createMemo(() => {
2397+
const result = highlighted()
2398+
if (!result || result.output !== props.output || result.language !== props.language) return
2399+
if (result.highlights.length === 0) return
2400+
return treeSitterToTextChunks(
2401+
props.shown,
2402+
previewHighlights(props.shown, result.output, result.highlights),
2403+
toolSyntax(),
2404+
{ enabled: false },
2405+
)
2406+
})
2407+
return <StyledOutput content={props.shown} chunks={chunks()} fg={theme.text} />
2408+
}
2409+
2410+
// One text renderable whose content is the plain text, or the same text as colored chunks, so the
2411+
// colors never change how it wraps. Chunks are set on the renderable rather than drawn as one
2412+
// span each, which keeps a large output a single renderable.
2413+
export function StyledOutput(props: { content: string; chunks?: TextChunk[]; fg: RGBA }) {
2414+
let text: TextRenderable | undefined
2415+
const content = () => (props.chunks ? new StyledText(props.chunks) : props.content)
2416+
createEffect(() => {
2417+
const value = content()
2418+
if (text) text.content = value
2419+
})
2420+
return (
2421+
<text
2422+
fg={props.fg}
2423+
ref={(el: TextRenderable) => {
2424+
text = el
2425+
el.content = content()
2426+
}}
2427+
/>
2428+
)
2429+
}
2430+
23642431
function InlineTool(props: {
23652432
icon: string
23662433
iconColor?: RGBA
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import type { SimpleHighlight } from "@opentui/core"
2+
import { Schema } from "effect"
3+
4+
// Output larger than this is never sniffed or colored: parsing and highlighting it would cost
5+
// more than the colors are worth, and it is drawn as plain text exactly as before.
6+
export const OUTPUT_LANGUAGE_LIMIT = 100_000
7+
8+
// The language a tool's output is colored in, from `syntax.tool_output`: a map from a tool name or
9+
// a glob over tool names (`*` any run of characters, `?` one) to a language id, `auto` or `none`.
10+
// An exact name wins over any glob; among globs the one with the most literal characters wins.
11+
// `auto` sniffs the output and colors only what it recognizes; unset or `none` leaves it plain.
12+
export function outputLanguage(settings: Record<string, string> | undefined, tool: string, output: string) {
13+
if (!settings || output.length > OUTPUT_LANGUAGE_LIMIT) return
14+
const value = settings[tool] ?? bestGlob(settings, tool)
15+
if (!value || value === "none") return
16+
if (value === "auto") return detectOutputLanguage(output)
17+
return value
18+
}
19+
20+
function bestGlob(settings: Record<string, string>, tool: string) {
21+
return Object.entries(settings)
22+
.filter(([pattern]) => /[*?]/.test(pattern) && globToRegExp(pattern).test(tool))
23+
.toSorted(([a], [b]) => b.replace(/[*?]/g, "").length - a.replace(/[*?]/g, "").length)
24+
.at(0)?.[1]
25+
}
26+
27+
function globToRegExp(pattern: string) {
28+
const body = pattern
29+
.replace(/[.+^${}()|[\]\\]/g, "\\$&")
30+
.replace(/\*/g, ".*")
31+
.replace(/\?/g, ".")
32+
return new RegExp(`^${body}$`)
33+
}
34+
35+
const decodeJson = Schema.decodeUnknownOption(Schema.UnknownFromJsonString)
36+
const detected = new Map<string, string | undefined>()
37+
const DETECTED_ENTRIES = 500
38+
39+
// JSON is the only format sniffed: an output that starts and ends with a bracket pair and parses
40+
// as JSON. The answer is kept by content, so a remounted or reopened transcript parses nothing.
41+
export function detectOutputLanguage(output: string) {
42+
const text = output.trim()
43+
if (text.length < 2 || text.length > OUTPUT_LANGUAGE_LIMIT) return
44+
const pair = text[0] + text[text.length - 1]
45+
if (pair !== "{}" && pair !== "[]") return
46+
if (detected.has(text)) return detected.get(text)
47+
const language = decodeJson(text)._tag === "Some" ? "json" : undefined
48+
detected.set(text, language)
49+
if (detected.size > DETECTED_ENTRIES) detected.delete(detected.keys().next().value!)
50+
return language
51+
}
52+
53+
// The highlights of the whole output that fall inside the part of `shown` it shares with the
54+
// output, so a collapsed preview takes the colors the whole output parses to.
55+
export function previewHighlights(shown: string, output: string, highlights: SimpleHighlight[]) {
56+
const limit = Math.min(shown.length, output.length)
57+
let shared = 0
58+
while (shared < limit && shown[shared] === output[shared]) shared++
59+
if (shared === output.length) return highlights
60+
return highlights.flatMap((highlight): SimpleHighlight[] =>
61+
highlight[0] >= shared ? [] : [[highlight[0], Math.min(highlight[1], shared), highlight[2]]],
62+
)
63+
}
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { afterEach, expect, test } from "bun:test"
2+
import { RGBA, type TextChunk } from "@opentui/core"
3+
import { testRender, type JSX } from "@opentui/solid"
4+
import { StyledOutput } from "../../../src/routes/session"
5+
6+
let setup: Awaited<ReturnType<typeof testRender>> | undefined
7+
8+
afterEach(() => {
9+
setup?.renderer.destroy()
10+
setup = undefined
11+
})
12+
13+
const output = JSON.stringify(
14+
{
15+
p: "/console/u/0/developers/billing/projects/an-unusually-long-project-identifier/users-and-permissions/invite",
16+
els: ['- textbox "[email protected]" [ref=e174]', '- button "Send invite" [ref=e181]'],
17+
count: 2,
18+
ok: true,
19+
},
20+
null,
21+
2,
22+
)
23+
const fg = RGBA.fromHex("#eeeeee")
24+
25+
// Every token its own chunk, as the highlighter splits JSON.
26+
function chunks(): TextChunk[] {
27+
return output.split(/(\s+|[{}[\]:,])/).map((text, index) => ({
28+
__isChunk: true,
29+
text,
30+
fg: RGBA.fromHex(index % 3 === 0 ? "#fab283" : "#7fd88f"),
31+
}))
32+
}
33+
34+
async function frame(width: number, node: () => JSX.Element) {
35+
setup?.renderer.destroy()
36+
setup = await testRender(() => <box paddingLeft={3}>{node()}</box>, { width, height: 40 })
37+
await setup.renderOnce()
38+
return setup.captureCharFrame()
39+
}
40+
41+
for (const width of [40, 80, 160]) {
42+
test(`colored output wraps exactly like the plain text at ${width} columns`, async () => {
43+
const plain = await frame(width, () => <text fg={fg}>{output}</text>)
44+
const unstyled = await frame(width, () => <StyledOutput content={output} fg={fg} />)
45+
const colored = await frame(width, () => <StyledOutput content={output} chunks={chunks()} fg={fg} />)
46+
expect(unstyled).toBe(plain)
47+
expect(colored).toBe(plain)
48+
expect(plain).toContain('"count": 2')
49+
})
50+
}

‎packages/tui/test/config.test.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,10 @@ test("validates config constraints", () => {
112112
expect(() => decodeInfo({ datetime_format: { time: "" } })).toThrow()
113113
expect(decodeInfo({ syntax: { bash: false } })).toEqual({ syntax: { bash: false } })
114114
expect(() => decodeInfo({ syntax: { bash: "off" } })).toThrow()
115+
expect(decodeInfo({ syntax: { tool_output: { browser: "json", "*": "auto" } } })).toEqual({
116+
syntax: { tool_output: { browser: "json", "*": "auto" } },
117+
})
118+
expect(() => decodeInfo({ syntax: { tool_output: { browser: true } } })).toThrow()
115119
expect(decodeInfo({ syntax: { files: false } })).toEqual({ syntax: { files: false } })
116120
expect(() => decodeInfo({ syntax: { files: 1 } })).toThrow()
117121
expect(decodeInfo({ syntax: { tool_input: true } })).toEqual({ syntax: { tool_input: true } })
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import type { SimpleHighlight } from "@opentui/core"
2+
import { describe, expect, test } from "bun:test"
3+
import {
4+
OUTPUT_LANGUAGE_LIMIT,
5+
detectOutputLanguage,
6+
outputLanguage,
7+
previewHighlights,
8+
} from "../../src/util/tool-output"
9+
10+
const json = '{"p": "/console/invite", "els": ["- textbox \\"[email protected]\\" [ref=e174]"]}'
11+
12+
describe("outputLanguage", () => {
13+
test("leaves output plain when nothing is configured", () => {
14+
expect(outputLanguage(undefined, "browser", json)).toBeUndefined()
15+
expect(outputLanguage({}, "browser", json)).toBeUndefined()
16+
})
17+
18+
test("takes the exact tool name over any glob", () => {
19+
const settings = { "*": "auto", "browser*": "yaml", browser: "json" }
20+
expect(outputLanguage(settings, "browser", "x")).toBe("json")
21+
})
22+
23+
test("takes the glob with the most literal characters", () => {
24+
const settings = { "*": "markdown", "github_*": "json", "github_create_*": "yaml", "gh?b": "toml" }
25+
expect(outputLanguage(settings, "github_create_issue", "x")).toBe("yaml")
26+
expect(outputLanguage(settings, "github_list", "x")).toBe("json")
27+
expect(outputLanguage(settings, "gh_b", "x")).toBe("toml")
28+
expect(outputLanguage(settings, "context7_query", "x")).toBe("markdown")
29+
})
30+
31+
test("treats regex characters in a name literally", () => {
32+
expect(outputLanguage({ "a.b*": "json" }, "axb1", "x")).toBeUndefined()
33+
expect(outputLanguage({ "a.b*": "json" }, "a.b1", "x")).toBe("json")
34+
})
35+
36+
test("none switches a tool off under a broader glob", () => {
37+
expect(outputLanguage({ "*": "json", todo: "none" }, "todo", json)).toBeUndefined()
38+
})
39+
40+
test("auto colors only output recognized as JSON", () => {
41+
expect(outputLanguage({ "*": "auto" }, "browser", json)).toBe("json")
42+
expect(outputLanguage({ "*": "auto" }, "browser", "Navigated to https://x")).toBeUndefined()
43+
})
44+
45+
test("never colors output past the size limit", () => {
46+
const big = `[${'"x",'.repeat(OUTPUT_LANGUAGE_LIMIT / 4)}"x"]`
47+
expect(outputLanguage({ browser: "json" }, "browser", big)).toBeUndefined()
48+
})
49+
})
50+
51+
describe("detectOutputLanguage", () => {
52+
test("recognizes objects and arrays that parse", () => {
53+
expect(detectOutputLanguage(` ${json}\n`)).toBe("json")
54+
expect(detectOutputLanguage("[1, 2, 3]")).toBe("json")
55+
})
56+
57+
test("rejects text that only looks like JSON", () => {
58+
expect(detectOutputLanguage("{not json}")).toBeUndefined()
59+
expect(detectOutputLanguage("[ref=e174] clicked")).toBeUndefined()
60+
expect(detectOutputLanguage('{"a": 1} trailing')).toBeUndefined()
61+
expect(detectOutputLanguage('"a string"')).toBeUndefined()
62+
expect(detectOutputLanguage("42")).toBeUndefined()
63+
expect(detectOutputLanguage("")).toBeUndefined()
64+
})
65+
66+
test("answers the same content again from its cache", () => {
67+
const text = `{"n": ${Date.now()}}`
68+
expect(detectOutputLanguage(text)).toBe("json")
69+
expect(detectOutputLanguage(text)).toBe("json")
70+
})
71+
})
72+
73+
describe("previewHighlights", () => {
74+
const output = '{\n "p": "/x",\n "els": [1, 2]\n}'
75+
const highlights: SimpleHighlight[] = [
76+
[4, 7, "property"],
77+
[9, 13, "string"],
78+
[17, 22, "property"],
79+
[25, 26, "number"],
80+
]
81+
82+
test("keeps every highlight when the whole output is shown", () => {
83+
expect(previewHighlights(output, output, highlights)).toBe(highlights)
84+
})
85+
86+
test("keeps the highlights inside a collapsed preview and cuts the one it splits", () => {
87+
const shown = output.slice(0, 20) + "…"
88+
expect(previewHighlights(shown, output, highlights)).toEqual([
89+
[4, 7, "property"],
90+
[9, 13, "string"],
91+
[17, 20, "property"],
92+
])
93+
})
94+
95+
test("gives a line-collapsed preview the colors of the lines it keeps", () => {
96+
const shown = output.split("\n").slice(0, 2).join("\n") + "\n…"
97+
expect(previewHighlights(shown, output, highlights)).toEqual([
98+
[4, 7, "property"],
99+
[9, 13, "string"],
100+
])
101+
})
102+
})

‎packages/web/src/content/docs/tui.mdx‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -679,6 +679,21 @@ Tool calls are colored by language. Each part can be turned on or off under `syn
679679
- `heredoc` - Color each heredoc in a bash command in the language of the command that reads it. Defaults to `true`.
680680
- `files` - Detect the language of written, edited and patched files beyond their extension, so these are colored too: SQL, Dockerfiles (`Dockerfile`, `Containerfile`, `*.dockerfile`), ini-style config and systemd units (`.ini`, `.cfg`, `.conf`, `.service`, `.timer` and the other unit types), dotenv files, shell scripts, ERB, HAML, file names such as `Makefile`, `Gemfile` and `PKGBUILD`, and a `#!` line on a file with no known extension. Defaults to `true`. When `false`, only the file extension decides.
681681
- `tool_input` - Show a plugin or MCP tool's input as a block, one key per line. Defaults to `false`, which shows only the input's text, number and boolean values, as `[key=value, ...]` on the tool's line. With `true`, input that is all such values and fits in 80 characters stays on that line; anything longer, multi-line or nested becomes a block: keys and values in different colors, values colored by type, text unquoted with its newlines, tabs and quotes shown as themselves, nested objects indented beneath their key, and lists laid out as YAML writes them, `- ` items at their key's indent. Until you click the block, every value takes one row, cut with `…` where it no longer fits; clicking shows it whole. With `tool_output.collapse` set to `"never"` for the tool, values always show whole.
682+
- `tool_output` - Color plugin and MCP tool output, by tool name. Keys are tool names or globs (`*` matches any run of characters, `?` one); values are a language id such as `json`, `yaml` or `markdown`, `auto`, or `none`. An exact name wins over any glob, and the glob with the most literal characters wins over the others. `auto` colors output that is a JSON object or array and leaves anything else plain. Output over 100,000 characters stays plain. Unset by default, which leaves all output plain. Colored output wraps exactly as the plain text does.
683+
684+
With `tool_output`, for example:
685+
686+
```json title="tui.json"
687+
{
688+
"syntax": {
689+
"tool_output": {
690+
"browser": "json",
691+
"todo_*": "none",
692+
"*": "auto"
693+
}
694+
}
695+
}
696+
```
682697

683698
A heredoc's language comes from the command that consumes it:
684699

0 commit comments

Comments
 (0)