Skip to content

armgit / eve

Public Imported from GitHub
0

The Open Framework for Building Agents

Improve TUI Markdown presentation (#3371)

Colton Paddena7f238788d31
diff --git a/.changeset/tui-markdown-rendering.md b/.changeset/tui-markdown-rendering.md
new file mode 100644
index 000000000..f170155e7
--- /dev/null
+++ b/.changeset/tui-markdown-rendering.md
@@ -0,0 +1,5 @@
+---
+"eve": patch
+---
+
+Improve development TUI Markdown with clearer headings, block spacing, clickable links, responsive bordered tables, and code panels. Set `EVE_TUI_RENDER_MARKDOWN=0` to show assistant and subagent responses without Markdown parsing or styling.
diff --git a/docs/guides/dev-tui.md b/docs/guides/dev-tui.md
index f4abdb20c..d90168713 100644
--- a/docs/guides/dev-tui.md
+++ b/docs/guides/dev-tui.md
@@ -87,7 +87,7 @@ Use `eve dev` flags to control tool calls, reasoning, subagents, connection auth
eve dev --tools full --reasoning collapsed --logs all
```
-Use `--host` and `--port` to bind the local server, or `--no-ui` to run without the terminal UI. See the [`eve dev` CLI reference](../reference/cli#eve-dev) for the complete option list, accepted values, and defaults.
+Use `--host` and `--port` to bind the local server, or `--no-ui` to run without the terminal UI. Set `EVE_TUI_RENDER_MARKDOWN=0` to show assistant and subagent responses without Markdown parsing or styling; `1` (the default) enables Markdown rendering. See the [`eve dev` CLI reference](../reference/cli#eve-dev) for the complete option list, accepted values, and defaults.
## Connect to a deployment
diff --git a/packages/eve/src/cli/dev/tui/blocks.test.ts b/packages/eve/src/cli/dev/tui/blocks.test.ts
index 8b45caf49..cee0fdc9b 100644
--- a/packages/eve/src/cli/dev/tui/blocks.test.ts
+++ b/packages/eve/src/cli/dev/tui/blocks.test.ts
@@ -17,9 +17,46 @@ describe("renderBlockLines", () => {
expect(render({ kind: "user", body: "hello there" })).toEqual(["│ hello there"]);
});
- it("marks the assistant with the brand triangle", () => {
+ it("marks rendered assistant Markdown with the brand triangle", () => {
const lines = render({ kind: "assistant", body: "all done" });
- expect(lines[0]).toBe("▲ all done");
+ expect(lines).toEqual(["▲ all done"]);
+ });
+
+ it("keeps an inline image on the preceding prose row", () => {
+ const lines = renderBlockLines(
+ {
+ kind: "assistant",
+ body: "Visit [eve](https://github.com/vercel-labs/eve) or view this image: ![eve logo](https://eve.dev/logo.png).",
+ },
+ 80,
+ theme,
+ ctx,
+ );
+
+ expect(lines).toHaveLength(1);
+ expect(stripAnsi(lines[0] ?? "")).toBe(
+ "▲ Visit eve or view this image:\u00a0▧\u00a0eve\u00a0logo.",
+ );
+
+ const wrapped = renderBlockLines(
+ {
+ kind: "assistant",
+ body: "Visit [eve](https://github.com/vercel-labs/eve) or view this image: ![eve logo](https://eve.dev/logo.png).",
+ },
+ 35,
+ theme,
+ ctx,
+ ).map(stripAnsi);
+ expect(wrapped).toEqual(["▲ Visit eve or view this", " image:\u00a0▧\u00a0eve\u00a0logo."]);
+ });
+
+ it("preserves prose Markdown when Markdown rendering is disabled", () => {
+ const lines = renderBlockLines({ kind: "assistant", body: "**bold**\n\n- item" }, 60, theme, {
+ ...ctx,
+ renderMarkdown: false,
+ }).map(stripAnsi);
+
+ expect(lines).toEqual(["▲ **bold**", " ", " - item"]);
});
it("colors per-item status markers in a mixed command result", () => {
diff --git a/packages/eve/src/cli/dev/tui/blocks.ts b/packages/eve/src/cli/dev/tui/blocks.ts
index bd5ba617f..cce716626 100644
--- a/packages/eve/src/cli/dev/tui/blocks.ts
+++ b/packages/eve/src/cli/dev/tui/blocks.ts
@@ -154,6 +154,8 @@ export interface ToolGroupItem {
export interface RenderBlockContext {
/** Current shared square-pulse frame for live activity blocks. */
activityPulse: string;
+ /** Whether prose responses are parsed and styled as Markdown. */
+ renderMarkdown?: boolean;
/**
* Kind and title of the block rendered immediately above this one. Lets a
* sandbox block detect that it continues a run (label suppressed, lines
@@ -220,7 +222,7 @@ function renderBody(
return renderUser(block, width, theme);
case "assistant":
case "subagent-step":
- return renderProse(block, width, theme);
+ return renderProse(block, width, theme, context);
case "reasoning":
return renderReasoning(block, width, theme);
case "tool":
@@ -279,7 +281,12 @@ function renderUser(block: Block, width: number, theme: Theme): string[] {
return rows;
}
-function renderProse(block: Block, width: number, theme: Theme): string[] {
+function renderProse(
+ block: Block,
+ width: number,
+ theme: Theme,
+ context: RenderBlockContext,
+): string[] {
const rows: string[] = [];
const isSubagent = block.kind === "subagent-step";
// A collapsed child message is one activity row in its section — the
@@ -292,9 +299,9 @@ function renderProse(block: Block, width: number, theme: Theme): string[] {
if (line === undefined) return [];
return [theme.colors.dim(sliceVisible(line, Math.max(1, width)))];
}
- // Bold at the terminal's DEFAULT foreground: black on a light theme,
- // white on a dark one. Explicit bright-white (SGR 97) would vanish on
- // light backgrounds.
+ // The brand anchors every top-level response; Markdown styles the content
+ // following it, rather than replacing the response gutter.
+ const markdown = context.renderMarkdown ?? true;
const glyph = isSubagent ? "" : `${theme.colors.bold(theme.glyph.brand)} `;
const indent = isSubagent ? "" : " ";
@@ -308,7 +315,7 @@ function renderProse(block: Block, width: number, theme: Theme): string[] {
}
if (body.length > 0) {
- const rendered = renderMarkdown(body, width - indent.length)
+ const rendered = (markdown ? renderMarkdown(body, width - indent.length) : body)
.split("\n")
.flatMap((line) => wrapVisibleLine(line, width - indent.length));
rendered.forEach((line, index) => {
diff --git a/packages/eve/src/cli/dev/tui/markdown.test.ts b/packages/eve/src/cli/dev/tui/markdown.test.ts
index 939a2a58e..006426786 100644
--- a/packages/eve/src/cli/dev/tui/markdown.test.ts
+++ b/packages/eve/src/cli/dev/tui/markdown.test.ts
@@ -1,7 +1,16 @@
import { describe, expect, it } from "vitest";
-import { renderMarkdown } from "./markdown.js";
-import { stripAnsi } from "#cli/ui/terminal-text.js";
+import { detectMarkdownRendering, renderMarkdown } from "./markdown.js";
+import { stripAnsi, visibleLength } from "#cli/ui/terminal-text.js";
+
+describe("detectMarkdownRendering", () => {
+ it("disables Markdown rendering only for an explicit false override", () => {
+ expect(detectMarkdownRendering({ EVE_TUI_RENDER_MARKDOWN: "0" })).toBe(false);
+ expect(detectMarkdownRendering({ EVE_TUI_RENDER_MARKDOWN: "false" })).toBe(false);
+ expect(detectMarkdownRendering({ EVE_TUI_RENDER_MARKDOWN: "1" })).toBe(true);
+ expect(detectMarkdownRendering({})).toBe(true);
+ });
+});
describe("renderMarkdown", () => {
it("preserves underscores inside URLs", () => {
@@ -19,36 +28,82 @@ describe("renderMarkdown", () => {
expect(rendered).toContain(hook);
});
- it("still applies emphasis to non-URL text", () => {
+ it("separates top-level Markdown blocks even when marked absorbs source blank rows", () => {
+ const rendered = stripAnsi(
+ renderMarkdown("# Title\n\n## Overview\n\nParagraph.\n\n- First\n- Second\n\n---"),
+ );
+
+ expect(rendered).toBe(
+ "Title\n\nOverview\n\nParagraph.\n\n• First\n• Second\n\n────────────────────────────────────────────────────────────",
+ );
+ });
+
+ it("uses level-specific heading styles without a leading glyph", () => {
+ expect(renderMarkdown("# one")).toBe("\x1b[1m\x1b[4mone\x1b[24m\x1b[22m");
+ expect(renderMarkdown("## two")).toBe("\x1b[1mtwo\x1b[22m");
+ expect(renderMarkdown("### three")).toBe("\x1b[4mthree\x1b[24m");
+ expect(renderMarkdown("#### four")).toBe("\x1b[1m\x1b[2mfour\x1b[22m");
+ expect(renderMarkdown("##### five")).toBe("\x1b[2m\x1b[4mfive\x1b[24m\x1b[22m");
+ expect(renderMarkdown("###### six")).toBe("\x1b[2msix\x1b[22m");
+ });
+
+ it("restores heading styles after inline spans", () => {
+ const linked = renderMarkdown("# [linked](https://example.com) trailing");
+ expect(linked).toContain("\x1b[24m\x1b]8;;\x1b\\\x1b[4m trailing");
+
+ const dimmed = renderMarkdown("###### **strong** trailing");
+ expect(dimmed).toContain("\x1b[22m\x1b[2m trailing");
+ });
+
+ it("applies inline emphasis and muted inline code", () => {
expect(renderMarkdown("_italic_")).toBe("\x1b[3mitalic\x1b[23m");
expect(renderMarkdown("**bold**")).toBe("\x1b[1mbold\x1b[22m");
+ expect(renderMarkdown("`code`")).toBe("\x1b[38;5;245mcode\x1b[39m");
});
- it("applies emphasis around a shielded URL", () => {
- const rendered = renderMarkdown("see _https://example.com/a_b_ now");
- expect(rendered).toContain("https://example.com/a_b");
+ it("renders links and images as OSC-8 underlined labels", () => {
+ expect(renderMarkdown("[the docs](https://example.com)")).toBe(
+ "\x1b]8;;https://example.com\x1b\\\x1b[4mthe docs\x1b[24m\x1b]8;;\x1b\\",
+ );
+ expect(renderMarkdown("![diagram](https://example.com/image.png)")).toBe(
+ "\x1b]8;;https://example.com/image.png\x1b\\\x1b[4m▧\u00a0diagram\x1b[24m\x1b]8;;\x1b\\",
+ );
});
- it("renders fenced code, task lists, links, and strikethrough semantically", () => {
- const rendered = renderMarkdown(
- "- [x] Read [the docs](https://example.com)\n\n~~~ts\nconst ok = true;\n~~~\n\n~~old~~",
+ it("dims list markers and aligns continuations to their visible width", () => {
+ expect(renderMarkdown("1. Ordered item\n2. Another item")).toBe(
+ "\x1b[2m1.\x1b[22m Ordered item\n\x1b[2m2.\x1b[22m Another item",
+ );
+ expect(stripAnsi(renderMarkdown("- first line \n continuation"))).toBe(
+ "• first line\n continuation",
);
-
- expect(rendered).toContain("• ☑ Read the docs (\x1b[36mhttps://example.com\x1b[39m)");
- expect(rendered).toContain(" \x1b[2mts\x1b[22m");
- expect(rendered).toContain("\x1b[2m│\x1b[22m \x1b[36mconst ok = true;\x1b[39m");
- expect(rendered).toContain("\x1b[9mold\x1b[29m");
});
- it("fits wide tables to the available terminal width", () => {
- const rendered = renderMarkdown(
- "| Name | Description |\n| --- | --- |\n| alpha | a very long description |",
- 24,
- );
+ it("renders boxed tables and falls back to vertical rows when narrow", () => {
+ const source = "| Name | Description |\n| --- | --- |\n| alpha | a very long description |";
+ const wide = renderMarkdown(source, 80);
+ expect(stripAnsi(wide)).toContain("┌───────┬─────────────────────────┐");
+ expect(stripAnsi(wide)).toContain("│ Name │ Description │");
+ expect(stripAnsi(wide)).toContain("├───────┼─────────────────────────┤");
+ expect(stripAnsi(wide)).toContain("└───────┴─────────────────────────┘");
+
+ const narrow = renderMarkdown(source, 18);
+ expect(stripAnsi(narrow)).toContain("┌────────────────┐");
+ expect(stripAnsi(narrow)).toContain("│Name: alpha │");
+ expect(stripAnsi(narrow)).toContain("│Description: a v│");
+ for (const line of narrow.split("\n")) {
+ expect(visibleLength(stripAnsi(line))).toBeLessThanOrEqual(18);
+ }
- for (const line of rendered.split("\n")) {
- expect(stripAnsi(line).length).toBeLessThanOrEqual(24);
+ for (const width of [1, 2]) {
+ for (const line of renderMarkdown(source, width).split("\n")) {
+ expect(visibleLength(stripAnsi(line))).toBeLessThanOrEqual(width);
+ }
}
- expect(rendered).toContain("…");
+ });
+
+ it("replaces graphemes that cannot fit narrow code rows", () => {
+ const rendered = stripAnsi(renderMarkdown("```text\n😀x\n```", 1));
+ expect(rendered).toBe("?\nx");
});
});
diff --git a/packages/eve/src/cli/dev/tui/markdown.ts b/packages/eve/src/cli/dev/tui/markdown.ts
index 596a1a7b8..888e2fe51 100644
--- a/packages/eve/src/cli/dev/tui/markdown.ts
+++ b/packages/eve/src/cli/dev/tui/markdown.ts
@@ -1,51 +1,67 @@
import { lexer, type TableCell, type Token } from "#compiled/marked/index.js";
-import { sliceVisible, visibleLength } from "#cli/ui/terminal-text.js";
+import { sliceVisible, stripAnsi, visibleLength } from "#cli/ui/terminal-text.js";
+import { graphemes } from "#shared/text-boundaries.js";
type TableAlignment = "left" | "center" | "right";
const ansi = {
bold: "\x1b[1m",
boldOff: "\x1b[22m",
- cyan: "\x1b[36m",
- cyanOff: "\x1b[39m",
+ inlineCode: "\x1b[38;5;245m",
+ inlineCodeOff: "\x1b[39m",
dim: "\x1b[2m",
dimOff: "\x1b[22m",
italic: "\x1b[3m",
italicOff: "\x1b[23m",
strike: "\x1b[9m",
strikeOff: "\x1b[29m",
+ underline: "\x1b[4m",
+ underlineOff: "\x1b[24m",
};
const tableSeparator = "─";
+const tableColumnSeparator = " │ ";
+const tableBorderWidth = 3;
+const maxLinkUrlBytes = 2083;
-/** Renders parsed GFM blocks to terminal text, fitting tables to `width`. */
+/**
+ * Whether prose responses should be parsed and styled as Markdown.
+ * `EVE_TUI_RENDER_MARKDOWN=0` bypasses Markdown parsing and styling.
+ */
+export function detectMarkdownRendering(env?: {
+ readonly EVE_TUI_RENDER_MARKDOWN?: string;
+}): boolean {
+ const override = env?.EVE_TUI_RENDER_MARKDOWN ?? process.env.EVE_TUI_RENDER_MARKDOWN;
+ if (override === "0" || override === "false") return false;
+ return true;
+}
+
+/** Renders parsed GFM blocks for terminal presentation. */
export function renderMarkdown(input: string, width = Number.POSITIVE_INFINITY): string {
- return trimTrailingBlankRows(renderBlocks(lexer(input), width)).join("\n");
+ return trimTrailingBlankRows(renderBlocks(lexer(input), width, true)).join("\n");
}
-function renderBlocks(tokens: readonly Token[], width: number): string[] {
+function renderBlocks(tokens: readonly Token[], width: number, separateBlocks = false): string[] {
const rows: string[] = [];
for (const token of tokens) {
switch (token.type) {
case "space":
pushBlankRow(rows);
break;
- case "heading": {
- const glyph = token.depth === 1 ? "█" : token.depth === 2 ? "■" : "▶";
- rows.push(`${glyph} ${ansi.bold}${renderInline(token.tokens)}${ansi.boldOff}`);
+ case "heading":
+ rows.push(renderHeading(token.depth ?? 1, token.tokens));
break;
- }
case "paragraph":
case "text":
rows.push(...renderInline(token.tokens, token.text).split("\n"));
break;
case "code":
- rows.push(...renderCodeBlock(token));
+ rows.push(...renderCodeBlock(token, width));
break;
case "blockquote":
rows.push(
- ...renderBlocks(token.tokens ?? [], Math.max(8, width - 2)).map(
+ ...renderBlocks(token.tokens ?? [], Math.max(1, width - 2)).map(
(row) => `${ansi.dim}│${ansi.dimOff} ${row}`,
),
);
@@ -72,16 +88,84 @@ function renderBlocks(tokens: readonly Token[], width: number): string[] {
}
break;
}
+ if (separateBlocks && isVisibleBlock(token)) pushBlankRow(rows);
}
return rows;
}
-function renderCodeBlock(token: Token): string[] {
- const rows: string[] = [];
- if (token.lang?.trim()) rows.push(` ${ansi.dim}${token.lang.trim()}${ansi.dimOff}`);
+function isVisibleBlock(token: Token): boolean {
+ return token.type !== "space" && token.type !== "def";
+}
+
+function renderHeading(depth: number, tokens: readonly Token[] | undefined): string {
+ const underlined = depth === 1 || depth === 3 || depth === 5;
+ const bold = depth === 1 || depth === 2 || depth === 4;
+ const dim = depth === 4 || depth === 5 || depth >= 6;
+ const content = renderInline(tokens, "", {
+ restoreAfterStrong: dim && !bold ? ansi.dim : "",
+ restoreUnderlineAfterLink: underlined,
+ suppressBold: bold,
+ });
+ switch (depth) {
+ case 1:
+ return `${ansi.bold}${ansi.underline}${content}${ansi.underlineOff}${ansi.boldOff}`;
+ case 2:
+ return `${ansi.bold}${content}${ansi.boldOff}`;
+ case 3:
+ return `${ansi.underline}${content}${ansi.underlineOff}`;
+ case 4:
+ return `${ansi.bold}${ansi.dim}${content}${ansi.boldOff}`;
+ case 5:
+ return `${ansi.dim}${ansi.underline}${content}${ansi.underlineOff}${ansi.dimOff}`;
+ default:
+ return `${ansi.dim}${content}${ansi.dimOff}`;
+ }
+}
+
+function renderCodeBlock(token: Token, width: number): string[] {
+ const language = token.lang?.trim() ?? "";
const codeRows = (token.text ?? "").replace(/\n$/u, "").split("\n");
- for (const row of codeRows) {
- rows.push(`${ansi.dim}│${ansi.dimOff} ${ansi.cyan}${row}${ansi.cyanOff}`);
+ const codeWidth = Math.max(1, ...codeRows.map(visibleLength));
+ if (!Number.isFinite(width) || width > 5) {
+ const panelWidth = Math.min(
+ Number.isFinite(width) ? Math.floor(width) : codeWidth,
+ Math.max(6, codeWidth, visibleLength(language) + 4),
+ );
+ const header =
+ language.length > 0 ? codePanelHeader(language, panelWidth) : codePanelRule(panelWidth);
+ return [
+ header,
+ ...codeRows.flatMap((row) => wrapCodeRow(row, panelWidth)),
+ codePanelRule(panelWidth),
+ ];
+ }
+ return codeRows.flatMap((row) => wrapCodeRow(row, Math.max(1, Math.floor(width))));
+}
+
+function codePanelHeader(language: string, width: number): string {
+ const label = sliceVisible(language, Math.max(1, width - 4)) || "?";
+ return `${ansi.dim}─ ${label} ${tableSeparator.repeat(Math.max(0, width - 3 - visibleLength(label)))}${ansi.dimOff}`;
+}
+
+function codePanelRule(width: number): string {
+ return `${ansi.dim}${tableSeparator.repeat(width)}${ansi.dimOff}`;
+}
+
+function wrapCodeRow(row: string, width: number): string[] {
+ if (row.length === 0) return [""];
+ const indent = row.match(/^[\t ]*/u)?.[0] ?? "";
+ const rows: string[] = [];
+ let remaining = row;
+ let continuation = false;
+ while (remaining.length > 0) {
+ const prefix = continuation && visibleLength(indent) < width ? indent : "";
+ const available = Math.max(1, width - visibleLength(prefix));
+ const fitting = sliceVisible(remaining, available);
+ const fallback = fitting.length === 0 ? firstGraphemeFallback(remaining) : undefined;
+ const content = fallback?.rendered ?? fitting;
+ rows.push(`${prefix}${content}`);
+ remaining = remaining.slice(fallback?.consumed ?? fitting.length);
+ continuation = true;
}
return rows;
}
@@ -90,59 +174,104 @@ function renderList(token: Token, width: number): string[] {
const rows: string[] = [];
let ordinal = typeof token.start === "number" ? token.start : 1;
for (const item of token.items ?? []) {
- const marker = token.ordered ? `${ordinal}.` : "•";
- const task = item.checked === true ? "☑ " : item.checked === false ? "☐ " : "";
- const itemRows = renderBlocks(item.tokens ?? [], Math.max(8, width - marker.length - 1));
+ const marker = token.ordered
+ ? `${ansi.dim}${ordinal}.${ansi.dimOff}`
+ : `${ansi.dim}•${ansi.dimOff}`;
+ const markerWidth = token.ordered ? `${ordinal}.`.length : 1;
+ const task = item.checked === true ? "✓ " : item.checked === false ? "☐ " : "";
+ const itemRows = renderBlocks(item.tokens ?? [], Math.max(1, width - markerWidth - 1));
const nonemptyRows = itemRows.length === 0 ? [""] : itemRows;
nonemptyRows.forEach((row, index) => {
- rows.push(index === 0 ? `${marker} ${task}${row}` : `${" ".repeat(marker.length + 1)}${row}`);
+ rows.push(index === 0 ? `${marker} ${task}${row}` : `${" ".repeat(markerWidth + 1)}${row}`);
});
ordinal += 1;
}
return rows;
}
-function renderInline(tokens: readonly Token[] | undefined, fallback = ""): string {
+interface InlineOptions {
+ readonly restoreAfterStrong?: string;
+ readonly restoreUnderlineAfterLink?: boolean;
+ readonly suppressBold?: boolean;
+}
+
+function renderInline(
+ tokens: readonly Token[] | undefined,
+ fallback = "",
+ options: InlineOptions = {},
+): string {
if (tokens === undefined) return fallback;
- return tokens.map(renderInlineToken).join("");
+
+ let rendered = "";
+ for (const token of tokens) {
+ // Keep the introducing word with an image label so normal word wrapping
+ // cannot leave the image alone.
+ if (token.type === "image" && rendered.endsWith(" ")) {
+ rendered = `${rendered.slice(0, -1)}\u00a0`;
+ }
+ rendered += renderInlineToken(token, options);
+ }
+ return rendered;
}
-function renderInlineToken(token: Token): string {
+function renderInlineToken(token: Token, options: InlineOptions): string {
switch (token.type) {
case "text":
- return renderInline(token.tokens, token.text ?? "");
- case "strong":
- return `${ansi.bold}${renderInline(token.tokens, token.text)}${ansi.boldOff}`;
+ return renderInline(token.tokens, token.text ?? "", options);
+ case "strong": {
+ const content = renderInline(token.tokens, token.text, options);
+ return options.suppressBold
+ ? content
+ : `${ansi.bold}${content}${ansi.boldOff}${options.restoreAfterStrong ?? ""}`;
+ }
case "em":
- return `${ansi.italic}${renderInline(token.tokens, token.text)}${ansi.italicOff}`;
+ return `${ansi.italic}${renderInline(token.tokens, token.text, options)}${ansi.italicOff}`;
case "del":
- return `${ansi.strike}${renderInline(token.tokens, token.text)}${ansi.strikeOff}`;
+ return `${ansi.strike}${renderInline(token.tokens, token.text, options)}${ansi.strikeOff}`;
case "codespan":
- return `${ansi.cyan}${token.text ?? ""}${ansi.cyanOff}`;
- case "link": {
- const label = renderInline(token.tokens, token.text);
- const href = token.href ?? "";
- if (href.length === 0 || label === href) return `${ansi.cyan}${label}${ansi.cyanOff}`;
- return `${label} (${ansi.cyan}${href}${ansi.cyanOff})`;
- }
- case "image": {
- const label = token.text?.trim() || "image";
- const href = token.href ?? "";
- return href.length === 0 ? `[${label}]` : `[${label}] (${ansi.cyan}${href}${ansi.cyanOff})`;
- }
+ return `${ansi.inlineCode}${token.text ?? ""}${ansi.inlineCodeOff}`;
+ case "link":
+ return renderLink(
+ renderInline(token.tokens, token.text, options),
+ token.href ?? "",
+ options.restoreUnderlineAfterLink,
+ );
+ case "image":
+ return renderLink(
+ `▧\u00a0${(token.text?.trim() || "image").replaceAll(" ", "\u00a0")}`,
+ token.href ?? "",
+ options.restoreUnderlineAfterLink,
+ );
case "br":
return "\n";
case "checkbox":
- return token.checked ? "☑ " : "☐ ";
+ return token.checked ? "✓ " : "☐ ";
case "escape":
return token.text ?? "";
case "html":
return token.text ?? token.raw ?? "";
default:
- return renderInline(token.tokens, token.text ?? token.raw ?? "");
+ return renderInline(token.tokens, token.text ?? token.raw ?? "", options);
}
}
+function renderLink(label: string, href: string, restoreUnderline = false): string {
+ if (!isSafeLinkUrl(href)) return label;
+ const restore = restoreUnderline ? ansi.underline : "";
+ return `\x1b]8;;${href}\x1b\\${ansi.underline}${label}${ansi.underlineOff}\x1b]8;;\x1b\\${restore}`;
+}
+
+function isSafeLinkUrl(href: string): boolean {
+ return (
+ href.length > 0 &&
+ Buffer.byteLength(href, "utf8") <= maxLinkUrlBytes &&
+ [...href].every((character) => {
+ const codePoint = character.codePointAt(0) ?? 0;
+ return codePoint >= 0x20 && codePoint !== 0x7f && (codePoint < 0x80 || codePoint > 0x9f);
+ })
+ );
+}
+
function renderTable(token: Token, width: number): string[] {
const header = token.header ?? [];
if (header.length === 0) return [];
@@ -153,16 +282,26 @@ function renderTable(token: Token, width: number): string[] {
);
const allRows = [renderedHeader, ...renderedRows];
const widths = alignments.map((_, column) =>
- Math.max(3, ...allRows.map((row) => visibleLength(row[column] ?? ""))),
+ Math.max(1, ...allRows.map((row) => visibleLength(row[column] ?? ""))),
);
- fitTableWidths(widths, width);
-
- const boldHeader = renderedHeader.map((cell) => `${ansi.bold}${cell}${ansi.boldOff}`);
- return [
- formatTableRow(boldHeader, widths, alignments),
- widths.map((columnWidth) => tableSeparator.repeat(columnWidth)).join(" "),
- ...renderedRows.map((row) => formatTableRow(row, widths, alignments)),
- ];
+ const gridWidth =
+ widths.reduce((sum, columnWidth) => sum + columnWidth, 0) +
+ widths.length * tableBorderWidth +
+ 1;
+ if (widths.length > 0 && (!Number.isFinite(width) || gridWidth <= width)) {
+ const boldHeader = renderedHeader.map((cell) => `${ansi.bold}${cell}${ansi.boldOff}`);
+ return [
+ formatTableBorder(widths, "┌", "┬", "┐"),
+ formatBoxedTableRow(boldHeader, widths, alignments),
+ formatTableBorder(widths, "├", "┼", "┤"),
+ ...renderedRows.flatMap((row, index) => [
+ formatBoxedTableRow(row, widths, alignments),
+ ...(index + 1 < renderedRows.length ? [formatTableBorder(widths, "├", "┼", "┤")] : []),
+ ]),
+ formatTableBorder(widths, "└", "┴", "┘"),
+ ];
+ }
+ return renderVerticalTable(renderedHeader, renderedRows, width);
}
function renderTableCell(cell: TableCell): string {
@@ -177,37 +316,79 @@ function normalizeAlignment(value: "center" | "left" | "right" | null | undefine
return value ?? "left";
}
-function fitTableWidths(widths: number[], width: number): void {
- if (!Number.isFinite(width)) return;
- const separators = Math.max(0, widths.length - 1) * 2;
- const budget = Math.max(widths.length * 3, Math.floor(width) - separators);
- while (widths.reduce((sum, value) => sum + value, 0) > budget) {
- const widest = Math.max(...widths);
- const index = widths.findIndex((value) => value === widest && value > 3);
- if (index === -1) return;
- widths[index] = widest - 1;
- }
+function renderVerticalTable(
+ header: readonly string[],
+ rows: readonly string[][],
+ width: number,
+): string[] {
+ const availableWidth = Number.isFinite(width) ? Math.max(1, Math.floor(width)) : 80;
+ if (availableWidth <= 2) return renderNarrowTable(header, rows, availableWidth);
+
+ const innerWidth = availableWidth - 2;
+ const rule = `${ansi.dim}┌${tableSeparator.repeat(innerWidth)}┐${ansi.dimOff}`;
+ const divider = `${ansi.dim}├${tableSeparator.repeat(innerWidth)}┤${ansi.dimOff}`;
+ const bottom = `${ansi.dim}└${tableSeparator.repeat(innerWidth)}┘${ansi.dimOff}`;
+ const output = [rule];
+ rows.forEach((row, rowIndex) => {
+ header.forEach((name, column) => {
+ output.push(...boxedTableLines(`${name}: ${row[column] ?? ""}`, innerWidth));
+ });
+ if (rowIndex + 1 < rows.length) output.push(divider);
+ });
+ output.push(bottom);
+ return output;
}
-function formatTableRow(
- row: readonly string[],
+function renderNarrowTable(
+ header: readonly string[],
+ rows: readonly string[][],
+ width: number,
+): string[] {
+ return rows.flatMap((row) =>
+ header.map((name, column) => {
+ const content = stripAnsi(`${name}: ${row[column] ?? ""}`);
+ const fitting = sliceVisible(content, width);
+ return fitting.length > 0 ? fitting : firstGraphemeFallback(content).rendered;
+ }),
+ );
+}
+
+function boxedTableLines(content: string, width: number): string[] {
+ const lines: string[] = [];
+ let remaining = content;
+ do {
+ const fitting = sliceVisible(remaining, width);
+ const fallback = fitting.length === 0 ? firstGraphemeFallback(remaining) : undefined;
+ const prefix = fallback?.rendered ?? fitting;
+ const padding = " ".repeat(Math.max(0, width - visibleLength(prefix)));
+ lines.push(`${ansi.dim}│${ansi.dimOff}${prefix}${padding}${ansi.dim}│${ansi.dimOff}`);
+ remaining = remaining.slice(fallback?.consumed ?? fitting.length);
+ } while (remaining.length > 0);
+ return lines;
+}
+
+function firstGraphemeFallback(text: string): { consumed: number; rendered: string } {
+ const first = graphemes(text)[0];
+ return { consumed: first?.text.length ?? 1, rendered: "?" };
+}
+
+function formatTableBorder(
widths: readonly number[],
- alignments: readonly TableAlignment[],
+ left: string,
+ middle: string,
+ right: string,
): string {
- return row
- .map((cell, index) =>
- alignTableCell(
- fitTableCell(cell, widths[index] ?? 3),
- widths[index] ?? 3,
- alignments[index] ?? "left",
- ),
- )
- .join(" ");
+ return `${left}${widths.map((width) => tableSeparator.repeat(width + 2)).join(middle)}${right}`;
}
-function fitTableCell(cell: string, width: number): string {
- if (visibleLength(cell) <= width) return cell;
- return `${sliceVisible(cell, Math.max(1, width - 1))}…`;
+function formatBoxedTableRow(
+ row: readonly string[],
+ widths: readonly number[],
+ alignments: readonly TableAlignment[],
+): string {
+ return `│ ${row
+ .map((cell, index) => alignTableCell(cell, widths[index] ?? 1, alignments[index] ?? "left"))
+ .join(tableColumnSeparator)} │`;
}
function alignTableCell(cell: string, width: number, alignment: TableAlignment): string {
@@ -221,7 +402,7 @@ function alignTableCell(cell: string, width: number, alignment: TableAlignment):
}
function horizontalRuleWidth(width: number): number {
- return Number.isFinite(width) ? Math.max(3, Math.min(40, Math.floor(width))) : 40;
+ return Number.isFinite(width) ? Math.max(1, Math.floor(width)) : 60;
}
function pushBlankRow(rows: string[]): void {
diff --git a/packages/eve/src/cli/dev/tui/terminal-renderer.ts b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
index eff0642cb..8e819d7dd 100644
--- a/packages/eve/src/cli/dev/tui/terminal-renderer.ts
+++ b/packages/eve/src/cli/dev/tui/terminal-renderer.ts
@@ -103,6 +103,7 @@ import {
type ProviderPickerEvent,
} from "./provider-picker.js";
import { buildAgentHeader } from "./agent-header.js";
+import { detectMarkdownRendering } from "./markdown.js";
import {
EMPTY_LINE,
PromptHistory,
@@ -288,6 +289,7 @@ export type TerminalRendererOptions = {
logs?: LogDisplayMode;
color?: boolean;
unicode?: boolean;
+ renderMarkdown?: boolean;
/** The process's diagnostics recorder (log, dump, stats); local sessions only. */
diagnostics?: DevDiagnostics;
/** Slash commands available in this local or remote session. */
@@ -367,6 +369,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
readonly #live: LiveRegion;
readonly #altScreen: AltScreen;
readonly #theme: Theme;
+ readonly #renderMarkdown: boolean;
readonly #tools: TerminalPartDisplayMode;
readonly #reasoning: TerminalPartDisplayMode;
readonly #subagents: TerminalPartDisplayMode;
@@ -629,6 +632,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
color: options?.color ?? true,
unicode: options?.unicode ?? detectUnicode(),
});
+ this.#renderMarkdown = options?.renderMarkdown ?? detectMarkdownRendering();
this.#tools = options?.tools ?? "auto-collapsed";
this.#reasoning = options?.reasoning ?? "auto-collapsed";
this.#subagents = options?.subagents ?? "auto-collapsed";
@@ -4118,6 +4122,7 @@ export class TerminalRenderer implements AgentTUIRenderer {
#renderBlock(block: DisplayBlock, width: number, previous: PreviousBlock | undefined): string[] {
const context: Parameters<typeof renderBlockLines>[3] = {
+ renderMarkdown: this.#renderMarkdown,
activityPulse: this.#progressPulseGlyph(
this.#activityPulseStartedAtMs,
this.#theme.unicode ? PROGRESS_PULSE_GLYPH : PROGRESS_PULSE_ASCII_GLYPH,
diff --git a/packages/eve/src/cli/ui/terminal-text.test.ts b/packages/eve/src/cli/ui/terminal-text.test.ts
index b20a7b2e4..ea7bb0d9c 100644
--- a/packages/eve/src/cli/ui/terminal-text.test.ts
+++ b/packages/eve/src/cli/ui/terminal-text.test.ts
@@ -30,7 +30,19 @@ describe("stripAnsi", () => {
it("strips CSI sequences and unsafe terminal controls", () => {
const input = "a\x1b[31mb\x1b[0mc\x1b]0;title\x07d";
- expect(stripAnsi(input)).toBe("abc]0;titled");
+ expect(stripAnsi(input)).toBe("abcd");
+ });
+
+ it("treats renderer-owned OSC-8 links as zero-width terminal controls", () => {
+ const link = "\x1b]8;;https://example.com/a-long-path\x1b\\label\x1b]8;;\x1b\\";
+
+ expect(stripAnsi(link)).toBe("label");
+ expect(visibleLength(link)).toBe(5);
+ expect(sliceVisible(link, 5)).toBe(link);
+ expect(wrapVisibleLine(link, 3)).toEqual([
+ "\x1b]8;;https://example.com/a-long-path\x1b\\lab",
+ "el\x1b]8;;\x1b\\",
+ ]);
});
});
diff --git a/packages/eve/src/cli/ui/terminal-text.ts b/packages/eve/src/cli/ui/terminal-text.ts
index 6e9a87cfd..db7d879a9 100644
--- a/packages/eve/src/cli/ui/terminal-text.ts
+++ b/packages/eve/src/cli/ui/terminal-text.ts
@@ -4,12 +4,21 @@ const ansiEscape = String.fromCharCode(27);
const ansiPattern = new RegExp(`${ansiEscape}\\[[0-?]*[ -/]*[@-~]`, "g");
const ansiPrefixPattern = new RegExp(`^${ansiEscape}\\[[0-?]*[ -/]*[@-~]`);
+// OSC 8 links are renderer-owned terminal controls. Their target is not
+// visible text and must not affect wrapping, table geometry, or clipping.
+const oscPattern = new RegExp(
+ `${ansiEscape}\\][^${ansiEscape}\\x07]*(?:\\x07|${ansiEscape}\\\\)`,
+ "g",
+);
+const oscPrefixPattern = new RegExp(
+ `^${ansiEscape}\\][^${ansiEscape}\\x07]*(?:\\x07|${ansiEscape}\\\\)`,
+);
const emojiPresentationPattern = /\p{Emoji_Presentation}/u;
const extendedPictographicPattern = /\p{Extended_Pictographic}/u;
const keycapPattern = /^[#*0-9]\u{fe0f}?\u{20e3}$/u;
export function stripAnsi(input: string): string {
- return stripTerminalControls(input.replaceAll(ansiPattern, ""));
+ return stripTerminalControls(input.replaceAll(ansiPattern, "").replaceAll(oscPattern, ""));
}
export function stripTerminalControls(input: string): string {
@@ -151,15 +160,18 @@ function terminalTextUnits(input: string): TerminalTextUnit[] {
let index = 0;
while (index < input.length) {
const remaining = input.slice(index);
- const ansiMatch = remaining.match(ansiPrefixPattern);
- if (ansiMatch !== null) {
- units.push({ text: ansiMatch[0], width: 0, ansi: true });
- index += ansiMatch[0].length;
+ const control = terminalControlPrefix(remaining);
+ if (control !== undefined) {
+ units.push({ text: control, width: 0, ansi: true });
+ index += control.length;
continue;
}
const nextAnsi = remaining.search(ansiPattern);
- const plain = remaining.slice(0, nextAnsi === -1 ? remaining.length : nextAnsi);
+ const nextOsc = remaining.search(oscPattern);
+ const nextControl =
+ nextAnsi === -1 ? nextOsc : nextOsc === -1 ? nextAnsi : Math.min(nextAnsi, nextOsc);
+ const plain = remaining.slice(0, nextControl === -1 ? remaining.length : nextControl);
for (const grapheme of graphemes(plain)) {
units.push({ text: grapheme.text, width: terminalGraphemeWidth(grapheme.text), ansi: false });
}
@@ -168,6 +180,10 @@ function terminalTextUnits(input: string): TerminalTextUnit[] {
return units;
}
+function terminalControlPrefix(input: string): string | undefined {
+ return input.match(ansiPrefixPattern)?.[0] ?? input.match(oscPrefixPattern)?.[0];
+}
+
/**
* Word-wraps a single logical line to `width` visible columns, preserving
* ANSI styling and never splitting inside an escape sequence. Breaks on the