Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

fix: render markdown links without color (#729)

yxlyx7876f6d8b16e
diff --git a/TUI/markdown_tests.zig b/TUI/markdown_tests.zig
index ebb840c2..7afb0c60 100644
--- a/TUI/markdown_tests.zig
+++ b/TUI/markdown_tests.zig
@@ -6,6 +6,7 @@
const std = @import("std");
const diff = @import("diff.zig");
+const dump = @import("dump.zig");
const syntax = @import("syntax.zig");
const theme_mod = @import("theme.zig");
@@ -46,6 +47,59 @@ test "render paints headers, code, bold, and bullets" {
try std.testing.expect(std.mem.indexOf(u8, text, theme_mod.emerald) != null);
}
+test "render keeps the issue URL exact while hiding bold delimiters" {
+ const url = "https://github.com/justrach/codegraff/issues/728";
+ const out = try render(std.testing.allocator, "**https://github.com/justrach/codegraff/issues/728**", theme_mod.emerald);
+ defer std.testing.allocator.free(out);
+ const visible = try dump.visible(std.testing.allocator, out);
+ defer std.testing.allocator.free(visible);
+ try std.testing.expectEqualStrings(url, visible);
+ try std.testing.expect(std.mem.indexOf(u8, visible, "**") == null);
+}
+
+test "renderThemed keeps the issue URL exact while hiding bold delimiters" {
+ const url = "https://github.com/justrach/codegraff/issues/728";
+ const out = try renderThemed(std.testing.allocator, "**https://github.com/justrach/codegraff/issues/728**", theme_mod.of(.night), 80);
+ defer std.testing.allocator.free(out);
+ const visible = try dump.visible(std.testing.allocator, out);
+ defer std.testing.allocator.free(visible);
+ try std.testing.expectEqualStrings(url, visible);
+ try std.testing.expect(std.mem.indexOf(u8, visible, "**") == null);
+}
+
+test "render keeps a label before a bold URL" {
+ const out = try render(std.testing.allocator, "Issue #728: **https://github.com/justrach/codegraff/issues/728**", theme_mod.emerald);
+ defer std.testing.allocator.free(out);
+ const visible = try dump.visible(std.testing.allocator, out);
+ defer std.testing.allocator.free(visible);
+ try std.testing.expectEqualStrings("Issue #728: https://github.com/justrach/codegraff/issues/728", visible);
+ try std.testing.expect(std.mem.indexOf(u8, visible, "**") == null);
+}
+
+test "renderThemed leaves punctuation outside a bold URL" {
+ const out = try renderThemed(std.testing.allocator, "See **https://github.com/justrach/codegraff/issues/728**, then continue.", theme_mod.of(.night), 80);
+ defer std.testing.allocator.free(out);
+ const visible = try dump.visible(std.testing.allocator, out);
+ defer std.testing.allocator.free(visible);
+ try std.testing.expectEqualStrings("See https://github.com/justrach/codegraff/issues/728, then continue.", visible);
+ try std.testing.expect(std.mem.indexOf(u8, visible, "**") == null);
+}
+
+test "render and renderThemed preserve an unwrapped URL ending in /**" {
+ const url = "https://github.com/justrach/codegraff/issues/728/**";
+ const plain = try render(std.testing.allocator, url, theme_mod.emerald);
+ defer std.testing.allocator.free(plain);
+ const plain_visible = try dump.visible(std.testing.allocator, plain);
+ defer std.testing.allocator.free(plain_visible);
+ try std.testing.expectEqualStrings(url, plain_visible);
+
+ const themed = try renderThemed(std.testing.allocator, url, theme_mod.of(.night), 80);
+ defer std.testing.allocator.free(themed);
+ const themed_visible = try dump.visible(std.testing.allocator, themed);
+ defer std.testing.allocator.free(themed_visible);
+ try std.testing.expectEqualStrings(url, themed_visible);
+}
+
test "the code band stays open to the row end and is released on the next line" {
const th = theme_mod.of(.night);
const code_bg = syntax.codeBg(false);
diff --git a/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx b/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx
index 8546bc22..333abe89 100644
--- a/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx
+++ b/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx
@@ -28,6 +28,7 @@ const SHIFTED_PAIRING = [
"**Note:** use x**2 then open **http://localhost:3003**",
"- **Web:** 2**10 at **http://localhost:3003**",
];
+const GITHUB_ISSUE_URL = "https://github.com/justrach/codegraff/issues/728";
function linkTargets(html: string): string[] {
const targets: string[] = [];
@@ -39,6 +40,16 @@ function linkTargets(html: string): string[] {
return targets;
}
+function renderedUrlButtons(html: string): Array<{ label: string; title: string }> {
+ const buttons: Array<{ label: string; title: string }> = [];
+ const pattern = /<button\b[^>]*\btitle="([^"]*)"[^>]*>([^<]*)<\/button>/g;
+ let match: RegExpExecArray | null;
+ while ((match = pattern.exec(html)) !== null) {
+ buttons.push({ title: match[1], label: match[2] });
+ }
+ return buttons;
+}
+
test("a stray ** earlier in the line never lands in the link target", () => {
for (const text of SHIFTED_PAIRING) {
const html = renderToStaticMarkup(<MarkdownRenderer text={text} />);
@@ -77,6 +88,41 @@ test("does not truncate a URL whose own tail is a delimiter pair", () => {
const url = "https://example.com/glob/**";
const html = renderToStaticMarkup(<MarkdownRenderer text={`See ${url} for details.`} />);
expect(linkTargets(html)).toContain(url);
+ expect(renderedUrlButtons(html)).toEqual([{ label: url, title: url }]);
+});
+
+test("renders the exact GitHub issue repro with clean visible emphasis", () => {
+ const html = renderToStaticMarkup(
+ <MarkdownRenderer text={`**${GITHUB_ISSUE_URL}**`} />,
+ );
+
+ expect(html).toContain("font-medium");
+ expect(renderedUrlButtons(html)).toEqual([
+ { label: GITHUB_ISSUE_URL, title: GITHUB_ISSUE_URL },
+ ]);
+ expect(html).not.toContain("**");
+});
+
+test("keeps a bold URL target exact beside its label and punctuation", () => {
+ const html = renderToStaticMarkup(
+ <MarkdownRenderer text={`Open GitHub issue: **${GITHUB_ISSUE_URL}**.`} />,
+ );
+
+ expect(html).toContain("Open GitHub issue: ");
+ expect(html).toContain("</button></span>.");
+ expect(renderedUrlButtons(html)).toEqual([
+ { label: GITHUB_ISSUE_URL, title: GITHUB_ISSUE_URL },
+ ]);
+});
+
+test("keeps an explicit labeled GitHub link href exact", () => {
+ const html = renderToStaticMarkup(
+ <MarkdownRenderer text={`Read [issue 728](${GITHUB_ISSUE_URL}).`} />,
+ );
+
+ expect(html).toContain(`href="${GITHUB_ISSUE_URL}"`);
+ expect(html).toContain(">issue 728</a>.");
+ expect(html).not.toContain(`${GITHUB_ISSUE_URL}**`);
});
test("keeps a bold-wrapped URL bold and its target clean", () => {
diff --git a/scripts/test-pty-markdown.py b/scripts/test-pty-markdown.py
index a158c452..1fa82369 100755
--- a/scripts/test-pty-markdown.py
+++ b/scripts/test-pty-markdown.py
@@ -17,24 +17,32 @@ ACCENT = b"\x1b[38;2;5;150;105m"
def main() -> None:
with tempfile.TemporaryDirectory(prefix="graff-md-pty-") as tmp:
- result = run_to_exit(
+ base_env = {
+ "HOME": tmp,
+ "LMSTUDIO_API_KEY": "local-pty-test",
+ "GRAFF_FLEET": "off",
+ "GRAFF_NO_TELEMETRY": "1",
+ }
+ color_result = run_to_exit(
GRAFF,
["--selftest-markdown", "--no-telemetry"],
cwd=tmp,
- env={
- "HOME": tmp,
- "LMSTUDIO_API_KEY": "local-pty-test",
- "GRAFF_FLEET": "off",
- "GRAFF_NO_TELEMETRY": "1",
- },
+ env=base_env,
unset_env=("CODEX_HOME", "NO_COLOR"),
rows=30,
cols=100,
timeout=15.0,
)
- if result.timed_out or result.exit_code != 0:
- raise SystemExit(
- f"Markdown self-test failed: exit={result.exit_code} timed_out={result.timed_out}"
+ plain_result = run_to_exit(
+ GRAFF,
+ ["--selftest-markdown", "--no-telemetry"],
+ cwd=tmp,
+ env=base_env,
+ unset_env=("CODEX_HOME",),
+ color=False,
+ rows=30,
+ cols=100,
+ timeout=15.0,
)
expected = (
"◆ Gaps",
@@ -47,14 +55,33 @@ def main() -> None:
"☑ Sanitize public errors.",
" ◦ Preserve private incident detail.",
"│ Public errors must never expose secrets.",
+ "• Link: https://github.com/justrach/codegraff/issues/728",
)
- missing = [line for line in expected if line not in result.text]
- if missing:
- raise SystemExit(f"Markdown render missing {missing!r}\n--- transcript ---\n{result.text}")
+ for mode, result in (("color", color_result), ("no-color", plain_result)):
+ if result.timed_out or result.exit_code != 0:
+ raise SystemExit(
+ f"Markdown {mode} self-test failed: exit={result.exit_code} "
+ f"timed_out={result.timed_out}"
+ )
+ missing = [line for line in expected if line not in result.text]
+ if missing:
+ raise SystemExit(
+ f"Markdown {mode} render missing {missing!r}\n--- transcript ---\n{result.text}"
+ )
+ link_line = next(
+ (line for line in result.text.splitlines() if "https://github.com/" in line),
+ None,
+ )
+ if link_line != expected[-1]:
+ raise SystemExit(
+ f"Markdown {mode} link line is not exact: {link_line!r}"
+ )
+ if b"\x1b[" in plain_result.raw:
+ raise SystemExit("Markdown no-color render unexpectedly contains ANSI")
for ansi in (ACCENT, b"\x1b[33m", b"\x1b[32m"):
- if ansi not in result.raw:
+ if ansi not in color_result.raw:
raise SystemExit(f"Markdown render missing ANSI style {ansi!r}")
- print("ok PTY Markdown headings, lists, tasks, quotes, inline styles, and ANSI")
+ print("ok PTY Markdown color/no-color links, blocks, inline styles, and ANSI")
if __name__ == "__main__":
diff --git a/src/agent_render.zig b/src/agent_render.zig
index 5d66f50a..669c0950 100644
--- a/src/agent_render.zig
+++ b/src/agent_render.zig
@@ -47,6 +47,13 @@ pub fn streamMarkdown(self: *Agent, text: []const u8) void {
if (!self.sub and !main_mod.json_mode) _ = tick_gate.setLineStart(atLineStart(self));
}
+pub fn deinitMarkdown(self: *Agent) void {
+ self.md_buf.deinit(self.gpa);
+ self.md_word.deinit(self.gpa);
+ for (self.md_table.items) |row| self.gpa.free(row);
+ self.md_table.deinit(self.gpa);
+}
+
/// True when the renderer has nothing painted on the current row: it committed
/// its last line with a newline and holds no prefix. A still-held/classifying
/// line has printed nothing yet but counts as mid-line anyway — a tick delayed
@@ -57,7 +64,7 @@ pub fn atLineStart(self: *const Agent) bool {
pub const MdKind = enum { classify, hold, prose, header, fenced, pre };
-pub const MdSpan = enum { normal, star, bold, bold_star, code };
+pub const MdSpan = enum { normal, star, bold_empty, bold, bold_star, code };
const TaskItem = struct { checked: bool, text: []const u8 };
@@ -250,12 +257,18 @@ pub fn mdSpanByte(self: *Agent, w: *Io.Writer, b: u8) void {
},
.star => if (b == '*') {
self.mdStyle(w, style.bold);
- self.md_span = .bold;
+ self.md_span = .bold_empty;
} else {
self.mdWrapByte(w, '*'); // lone star is literal
self.md_span = .normal;
self.mdSpanByte(w, b);
},
+ .bold_empty => if (b == '*') {
+ self.md_span = .bold_star;
+ } else {
+ self.md_span = .bold;
+ self.mdSpanByte(w, b);
+ },
.bold => switch (b) {
'*' => self.md_span = .bold_star,
else => self.mdWrapByte(w, b),
@@ -339,6 +352,10 @@ pub fn mdSpanEnd(self: *Agent, w: *Io.Writer) void {
switch (self.md_span) {
.normal => {},
.star => w.writeByte('*') catch {},
+ .bold_empty => {
+ w.writeAll(style.reset) catch {};
+ w.writeAll("**") catch {};
+ },
.bold, .code => w.writeAll(style.reset) catch {},
.bold_star => {
w.writeByte('*') catch {};
diff --git a/src/agent_stream_stall_test.zig b/src/agent_stream_stall_test.zig
index 5aa44ced..5def4e0a 100644
--- a/src/agent_stream_stall_test.zig
+++ b/src/agent_stream_stall_test.zig
@@ -16,6 +16,7 @@ const http = @import("http.zig");
const http_stall = @import("http_stall.zig");
const agent_stream = @import("agent_stream.zig");
const Agent = @import("agent.zig").Agent;
+const deinitMarkdown = @import("agent_render.zig").deinitMarkdown;
const nowMs = @import("agent_ws_mock.zig").nowMs;
/// One chat-completions delta with visible prose: the reader grows
@@ -184,6 +185,7 @@ test "#680: each stall reconnect widens the between-lines wait the SSE reader ar
.label = "",
.out = &out.writer,
};
+ defer deinitMarkdown(&agent);
// All three attempts run before any assertion, so a failure can never
// leave the server blocked in accept() with the join waiting on it.
diff --git a/src/engine_sink.zig b/src/engine_sink.zig
index 36b9299d..c76af170 100644
--- a/src/engine_sink.zig
+++ b/src/engine_sink.zig
@@ -207,7 +207,8 @@ fn lifecycleEmit(ctx: *anyopaque, ev: Stamped) void {
}
/// Today's interactive rendering, relocated behind the event contract. Every
-/// branch is the old inline agent_stream.zig code path, gate for gate.
+/// branch is the old inline agent_stream.zig code path, except no-color answer
+/// text now shares the Markdown renderer so link targets exclude delimiters (#729).
fn tuiEmit(ctx: *anyopaque, ev: Stamped) void {
const a: *Agent = @ptrCast(@alignCast(ctx));
if (hosted_frontend) return hostedEmit(a, ev.event);
@@ -224,13 +225,9 @@ fn tuiEmit(ctx: *anyopaque, ev: Stamped) void {
.text_delta => |d| {
if (a.thinking_open) render.closeThinkingBlock(a); // reasoning -> answer transition
render.spinnerStop(a); // first visible byte: clear the thinking line
- if (main_mod.use_color) {
- a.streamMarkdown(d.text);
- } else if (a.out) |w| {
- w.writeAll(d.text) catch return;
- w.flush() catch return;
- if (!a.sub) _ = tick_gate.setLineStart(d.text[d.text.len - 1] == '\n'); // #tui-tick
- }
+ // Empty style strings make this plain text when color is off, but
+ // Markdown delimiters still stay out of terminal link targets (#729).
+ a.streamMarkdown(d.text);
},
// Meta-tool argument prose renders like answer text — spinner handoff
// included — with two deliberate differences from .text_delta, both
diff --git a/src/engine_sink_tests.zig b/src/engine_sink_tests.zig
index 2637f302..b69edee5 100644
--- a/src/engine_sink_tests.zig
+++ b/src/engine_sink_tests.zig
@@ -9,6 +9,7 @@ const Io = std.Io;
const main_mod = @import("main.zig");
const agent_mod = @import("agent.zig");
const Agent = agent_mod.Agent;
+const deinitMarkdown = @import("agent_render.zig").deinitMarkdown;
const engine_events = @import("engine_events.zig");
const EngineEvent = engine_events.EngineEvent;
@@ -304,6 +305,7 @@ test "TuiSink renders a plain text delta exactly as the no-color TTY did" {
var aw: Io.Writer.Allocating = .init(std.testing.allocator);
defer aw.deinit();
var a = testAgent(&aw.writer);
+ defer deinitMarkdown(&a);
const s = tuiSink(&a);
s.emit(undefined, .{ .text_delta = .{ .text = "plain\n" } });
try std.testing.expectEqualStrings("plain\n", aw.writer.buffered());
@@ -312,6 +314,56 @@ test "TuiSink renders a plain text delta exactly as the no-color TTY did" {
try std.testing.expectEqualStrings("plain\n\n", aw.writer.buffered());
}
+test "TuiSink excludes bold delimiters from no-color URL output (#729)" {
+ const saved_color = main_mod.use_color;
+ main_mod.use_color = false;
+ defer main_mod.use_color = saved_color;
+ const ansi = @import("ansi.zig");
+ const saved_style = ansi.style;
+ ansi.style = .{};
+ defer ansi.style = saved_style;
+
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+ defer deinitMarkdown(&a);
+ const s = tuiSink(&a);
+
+ s.emit(undefined, .{ .text_delta = .{ .text = "**https://github.com/justrach/codegraff/" } });
+ s.emit(undefined, .{ .text_delta = .{ .text = "issues/728**\n" } });
+ try std.testing.expectEqualStrings(
+ "https://github.com/justrach/codegraff/issues/728\n",
+ aw.writer.buffered(),
+ );
+
+ aw.clearRetainingCapacity();
+ s.emit(undefined, .{ .text_delta = .{ .text = "Issue: **https://github.com/justrach/codegraff/issues/728**.\n" } });
+ try std.testing.expectEqualStrings(
+ "Issue: https://github.com/justrach/codegraff/issues/728.\n",
+ aw.writer.buffered(),
+ );
+}
+
+test "TuiSink preserves a no-color URL ending in a legal star pair (#729)" {
+ const saved_color = main_mod.use_color;
+ main_mod.use_color = false;
+ defer main_mod.use_color = saved_color;
+ const ansi = @import("ansi.zig");
+ const saved_style = ansi.style;
+ ansi.style = .{};
+ defer ansi.style = saved_style;
+
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a = testAgent(&aw.writer);
+ defer deinitMarkdown(&a);
+ const s = tuiSink(&a);
+
+ const url = "https://example.com/path/**";
+ s.emit(undefined, .{ .text_delta = .{ .text = url ++ "\n" } });
+ try std.testing.expectEqualStrings(url ++ "\n", aw.writer.buffered());
+}
+
const swap: engine_events.ProviderFallback = .{
.from_provider = "codex",
.from_model = "gpt-5.5",
diff --git a/src/http_client_integration_tests.zig b/src/http_client_integration_tests.zig
index 74624e6d..553f3352 100644
--- a/src/http_client_integration_tests.zig
+++ b/src/http_client_integration_tests.zig
@@ -3,6 +3,7 @@
const std = @import("std");
const Io = std.Io;
const Agent = @import("agent.zig").Agent;
+const deinitMarkdown = @import("agent_render.zig").deinitMarkdown;
const http = @import("http.zig");
const http_client = @import("http_client.zig");
const mock = @import("agent_ws_mock.zig");
@@ -182,6 +183,7 @@ test "TUI turn agent and actual runSub child share the recovered generation" {
ctx.provider = p;
var root = try repl_turn.turnAgent(&ctx, gpa, arena_state.allocator(), .{}, &output.writer, &approvals);
defer root.tools_used.deinit(gpa);
+ defer deinitMarkdown(&root);
http_client.injectConstructionTlsForTest(0);
_ = try root.request(null);
@@ -312,6 +314,7 @@ test "later root and child recover after the retry ladder exhausts TLS generatio
var tracer: trace.Tracer = .{ .io = io, .gpa = gpa, .out = &trace_output.writer, .start = Io.Timestamp.now(io, .awake) };
var root = childAgent(gpa, arena, io, &runtime.client, provider(url));
+ defer deinitMarkdown(&root);
root.sub = false;
root.label = "test-root";
root.out = &output.writer;
diff --git a/src/session_settings.zig b/src/session_settings.zig
index bccb4adb..e82cb105 100644
--- a/src/session_settings.zig
+++ b/src/session_settings.zig
@@ -312,6 +312,7 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:
\\- [x] Sanitize public errors.
\\ - Preserve private incident detail.
\\> Public errors must never expose secrets.
+ \\- Link: **https://github.com/justrach/codegraff/issues/728**
);
probe.flushStreamTail();
out.writeByte('\n') catch {};