Skip to content

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

Python

fix(gui): stray ** no longer shifts emphasis pairing into the link target (#197)

justrach1c048adb6609
diff --git a/gui/src/components/chat/ChatInlineText.test.tsx b/gui/src/components/chat/ChatInlineText.test.tsx
new file mode 100644
index 00000000..905a3a8c
--- /dev/null
+++ b/gui/src/components/chat/ChatInlineText.test.tsx
@@ -0,0 +1,29 @@
+import { expect, test } from "bun:test";
+import { renderToStaticMarkup } from "react-dom/server";
+
+import { ChatInlineText } from "./ChatInlineText";
+
+// ChatInlineText is the raw (non-Markdown) surface: user messages, status and
+// error rows, tool labels. Markdown delimiters reach the autolinker verbatim
+// here, so the link target must be cleaned by the matcher itself (#197).
+const WRAPPED = [
+ "**http://localhost:3003**",
+ "__http://localhost:3003__",
+ "_http://localhost:3003_",
+ "~~http://localhost:3003~~",
+ "Open **http://localhost:3003** now",
+ "Open __http://localhost:3003__ now",
+ "http://localhost:3003**",
+];
+
+test("never puts Markdown emphasis delimiters in the clickable target", () => {
+ for (const text of WRAPPED) {
+ const html = renderToStaticMarkup(<ChatInlineText text={text} />);
+ expect(html).toContain('title="http://localhost:3003"');
+ }
+});
+
+test("keeps legitimate trailing URL characters clickable", () => {
+ const html = renderToStaticMarkup(<ChatInlineText text="https://example.com/?q=*" />);
+ expect(html).toContain('title="https://example.com/?q=*"');
+});
diff --git a/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx b/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx
index 6e4f331d..f0a13473 100644
--- a/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx
+++ b/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx
@@ -16,6 +16,59 @@ test("autolinks a bare URL in plain text into a clickable control", () => {
expect(html).toContain("https://react.dev/learn");
});
+// #197 (follow-up report): the originally filed `**http://host**` repro was
+// fixed in the matcher, but the defect survived one level up. A literal `**`
+// earlier in the paragraph shifted the parser's emphasis pairing, so the bold
+// URL's closing `**` never became markup: it stayed inside the text node the
+// autolinker sees, rendered literally instead of as bold, and ended up in the
+// clickable target (`http://localhost:3003**`).
+const SHIFTED_PAIRING = [
+ "Pass **kwargs to the server at **http://localhost:3003**",
+ "The value 2**32 is at **http://localhost:3003**",
+ "**Note:** use x**2 then open **http://localhost:3003**",
+ "- **Web:** 2**10 at **http://localhost:3003**",
+];
+
+function linkTargets(html: string): string[] {
+ const targets: string[] = [];
+ const pattern = /title="([^"]*)"|href="([^"]*)"/g;
+ let match: RegExpExecArray | null;
+ while ((match = pattern.exec(html)) !== null) {
+ targets.push(match[1] ?? match[2]);
+ }
+ return targets;
+}
+
+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} />);
+ expect(linkTargets(html)).toContain("http://localhost:3003");
+ expect(html).not.toContain("http://localhost:3003**");
+ }
+});
+
+// Streaming re-renders the whole accumulated text on every delta, so every
+// prefix is a state a user can see and click.
+test("no streaming prefix ever produces a delimiter-tailed link target", () => {
+ for (const text of SHIFTED_PAIRING) {
+ for (let length = 1; length <= text.length; length += 1) {
+ const html = renderToStaticMarkup(<MarkdownRenderer text={text.slice(0, length)} />);
+ for (const target of linkTargets(html)) {
+ expect(target).not.toMatch(/(\*\*|__|~~)$/u);
+ }
+ }
+ }
+});
+
+test("keeps a bold-wrapped URL bold and its target clean", () => {
+ const html = renderToStaticMarkup(
+ <MarkdownRenderer text="Server at **http://localhost:3003** now" />,
+ );
+ expect(html).toContain("font-medium");
+ expect(linkTargets(html)).toContain("http://localhost:3003");
+ expect(html).not.toContain("**");
+});
+
test("renders unsafe markdown link schemes as plain text", () => {
const html = renderToStaticMarkup(
<MarkdownRenderer text="[click me](javascript:alert(1)) and [payload](data:text/html,test)" />,
diff --git a/gui/src/components/chat/markdown/parser.test.ts b/gui/src/components/chat/markdown/parser.test.ts
index 48566275..9aef1dc7 100644
--- a/gui/src/components/chat/markdown/parser.test.ts
+++ b/gui/src/components/chat/markdown/parser.test.ts
@@ -117,6 +117,30 @@ describe("parseInline", () => {
test("leaves unmatched markers as literal text", () => {
expect(parseInline("a * b")).toEqual([{ type: "text", value: "a * b" }]);
+ expect(parseInline("a ** b")).toEqual([{ type: "text", value: "a ** b" }]);
+ });
+
+ // #197: a literal `**` earlier in the paragraph (Python `**kwargs`, an
+ // exponent like `2**32`) used to be paired with the `**` that actually opens
+ // a later bold span, leaving that span's closing `**` glued to the following
+ // text — which the autolinker then swallowed into the link target. A closing
+ // run must bind to the *nearest* still-open run instead.
+ test("binds a closing ** to the nearest opener, not the first one", () => {
+ expect(parseInline("Pass **kwargs to **https://x.dev**")).toEqual([
+ { type: "text", value: "Pass **kwargs to " },
+ { type: "strong", children: [{ type: "text", value: "https://x.dev" }] },
+ ]);
+ expect(parseInline("2**32 at **https://x.dev**")).toEqual([
+ { type: "text", value: "2**32 at " },
+ { type: "strong", children: [{ type: "text", value: "https://x.dev" }] },
+ ]);
+ });
+
+ test("a run followed by a space cannot open emphasis", () => {
+ expect(parseInline("a * b **bold**")).toEqual([
+ { type: "text", value: "a * b " },
+ { type: "strong", children: [{ type: "text", value: "bold" }] },
+ ]);
});
});
diff --git a/gui/src/components/chat/markdown/parser.ts b/gui/src/components/chat/markdown/parser.ts
index ed18fcbf..867c649c 100644
--- a/gui/src/components/chat/markdown/parser.ts
+++ b/gui/src/components/chat/markdown/parser.ts
@@ -426,10 +426,8 @@ interface InlineMatch {
const HARD_BREAK_RE = /(?: {2,}|\\)\n/g;
const CODE_RE = /(`+)([\s\S]*?)\1/g;
-const STRONG_STAR_RE = /\*\*([\s\S]+?)\*\*/g;
const STRONG_UNDER_RE = /(?<![A-Za-z0-9])__([\s\S]+?)__(?![A-Za-z0-9])/g;
const DEL_RE = /~~([\s\S]+?)~~/g;
-const EM_STAR_RE = /\*([\s\S]+?)\*/g;
const EM_UNDER_RE = /(?<![A-Za-z0-9])_([\s\S]+?)_(?![A-Za-z0-9])/g;
const LINK_RE = /\[([^\]]*)\]\(\s*(<[^>]*>|[^)\s]+)(?:\s+"[^"]*")?\s*\)/g;
// Inline math: \( ... \) and $ ... $. The dollar form is deliberately narrow —
@@ -488,10 +486,10 @@ function nextInlineMatch(text: string, from: number): InlineMatch | null {
href: m[2].replace(/^<|>$/g, ""),
children: parseInline(m[1]),
}));
- pushCandidate(candidates, STRONG_STAR_RE, text, from, (m) => ({
- type: "strong",
- children: parseInline(m[1]),
- }));
+ const starEmphasis = findStarEmphasis(text, from);
+ if (starEmphasis) {
+ candidates.push(starEmphasis);
+ }
pushCandidate(candidates, STRONG_UNDER_RE, text, from, (m) => ({
type: "strong",
children: parseInline(m[1]),
@@ -500,10 +498,6 @@ function nextInlineMatch(text: string, from: number): InlineMatch | null {
type: "del",
children: parseInline(m[1]),
}));
- pushCandidate(candidates, EM_STAR_RE, text, from, (m) => ({
- type: "em",
- children: parseInline(m[1]),
- }));
pushCandidate(candidates, EM_UNDER_RE, text, from, (m) => ({
type: "em",
children: parseInline(m[1]),
@@ -519,6 +513,69 @@ function nextInlineMatch(text: string, from: number): InlineMatch | null {
return candidates[0];
}
+interface StarRun {
+ start: number;
+ end: number;
+}
+
+function isWhitespaceAt(text: string, index: number): boolean {
+ const char = index < 0 || index >= text.length ? undefined : text[index];
+ return char == null || /\s/u.test(char);
+}
+
+/**
+ * CommonMark-style `*` / `**` emphasis, replacing the old lazy
+ * "two asterisks, anything, two asterisks" regexes.
+ *
+ * A run of asterisks may only *open* when a non-space follows it and may only
+ * *close* when a non-space precedes it, and a closer binds to the **nearest**
+ * still-open run. #197: the lazy regexes paired the first two runs they saw, so
+ * a literal `**` in the prose — Python `**kwargs`, an exponent like `2**32` —
+ * stole the `**` that actually opened a later bold span. The bold URL's closing
+ * `**` was then left glued to the text node (`http://localhost:3003**`), where
+ * it both rendered literally and got swallowed into the autolinked target.
+ */
+function findStarEmphasis(text: string, from: number): InlineMatch | null {
+ const open: StarRun[] = [];
+ let index = from;
+
+ while (index < text.length) {
+ if (text[index] !== "*") {
+ index += 1;
+ continue;
+ }
+
+ let end = index + 1;
+ while (end < text.length && text[end] === "*") {
+ end += 1;
+ }
+
+ const canOpen = !isWhitespaceAt(text, end);
+ const opener = isWhitespaceAt(text, index - 1) ? undefined : open.pop();
+ if (opener != null) {
+ // Openers are consumed from the end of their run, closers from the
+ // start, so leftover asterisks stay literal text on either side.
+ const size = Math.min(opener.end - opener.start, end - index) >= 2 ? 2 : 1;
+ const start = opener.end - size;
+ return {
+ index: start,
+ length: index + size - start,
+ node: {
+ type: size === 2 ? "strong" : "em",
+ children: parseInline(text.slice(opener.end, index)),
+ },
+ };
+ }
+
+ if (canOpen) {
+ open.push({ start: index, end });
+ }
+ index = end;
+ }
+
+ return null;
+}
+
function pushCandidate(
out: InlineMatch[],
regex: RegExp,
diff --git a/gui/src/components/chat/utils/chatLinks.test.ts b/gui/src/components/chat/utils/chatLinks.test.ts
index 7c93cd29..c57c6d22 100644
--- a/gui/src/components/chat/utils/chatLinks.test.ts
+++ b/gui/src/components/chat/utils/chatLinks.test.ts
@@ -70,6 +70,34 @@ describe("getChatLinkMatches URL vs Markdown delimiters", () => {
expect(firstUrl("~~*https://example.com*~~")).toBe("https://example.com");
});
+ // #197 follow-up: the mirrored-delimiter rule only fires when the *same*
+ // delimiters sit immediately before the URL. Markdown that consumed the
+ // opening `**` elsewhere (a stray `**kwargs`/`2**32` earlier in the
+ // paragraph, or a second render pass over a text node) hands this matcher a
+ // candidate with a trailing `**` and nothing in front of it — the target must
+ // still come out clean.
+ test("strips an unpaired trailing ** with no leading delimiter", () => {
+ expect(firstUrl("http://localhost:3003**")).toBe("http://localhost:3003");
+ expect(firstUrl("open http://localhost:3003** now")).toBe("http://localhost:3003");
+ });
+
+ test("strips unpaired trailing __ and ~~", () => {
+ expect(firstUrl("http://localhost:3003__")).toBe("http://localhost:3003");
+ expect(firstUrl("http://localhost:3003~~")).toBe("http://localhost:3003");
+ });
+
+ test("strips underscore emphasis wrapping a bare URL", () => {
+ expect(firstUrl("__http://localhost:3003__")).toBe("http://localhost:3003");
+ expect(firstUrl("_http://localhost:3003_")).toBe("http://localhost:3003");
+ expect(firstUrl("Open __http://localhost:3003__ now")).toBe("http://localhost:3003");
+ });
+
+ test("preserves underscores that are part of the URL", () => {
+ expect(firstUrl("https://example.com/a_b_c")).toBe("https://example.com/a_b_c");
+ expect(firstUrl("https://example.com/a__b/c")).toBe("https://example.com/a__b/c");
+ expect(firstUrl("https://example.com/trailing_")).toBe("https://example.com/trailing_");
+ });
+
test("never splits a multi-byte trailing character (surrogate-safe)", () => {
// Trimming only removes ASCII markers, so a URL that legitimately ends in a
// multi-byte glyph (accents, emoji) is preserved byte-for-byte, never cut
diff --git a/gui/src/components/chat/utils/chatLinks.ts b/gui/src/components/chat/utils/chatLinks.ts
index 1d8fdb84..a99907a5 100644
--- a/gui/src/components/chat/utils/chatLinks.ts
+++ b/gui/src/components/chat/utils/chatLinks.ts
@@ -4,6 +4,9 @@ const FILE_PATH_PATTERN =
const PATH_BOUNDARY_PATTERN = /[\s([{"'`]/u;
const TRAILING_PUNCTUATION_PATTERN = /[.,;!?]+$/u;
const TRAILING_CLOSERS = new Set([")", "]", "}", ">", "'", '"', "`"]);
+// Paired Markdown emphasis delimiters. Never part of a link target, whichever
+// caller feeds getChatLinkMatches (#197).
+const EMPHASIS_PAIRS = ["**", "__", "~~"] as const;
const FILE_BASENAME_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/u;
const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/u;
const WINDOWS_UNC_PATH_PATTERN = /^\\\\/u;
@@ -96,13 +99,13 @@ function trimLinkCandidate(candidate: string): string {
}
function markdownClosingDelimiterBefore(text: string, start: number): string | null {
- const opening = text.slice(0, start).match(/[~*]+$/u)?.[0];
+ const opening = text.slice(0, start).match(/[~*_]+$/u)?.[0];
if (opening == null) {
return null;
}
for (let index = 0; index < opening.length; index += 1) {
- if (opening[index] === "*") {
+ if (opening[index] === "*" || opening[index] === "_") {
continue;
}
if (opening[index] !== "~" || opening[index + 1] !== "~") {
@@ -114,14 +117,45 @@ function markdownClosingDelimiterBefore(text: string, start: number): string | n
return [...opening].reverse().join("");
}
+/**
+ * Defense in depth for #197: whatever the caller hands us, a linkified URL must
+ * never start or end on a *paired* Markdown emphasis delimiter. Only pairs are
+ * stripped — a lone trailing `*` or `~` is a legitimate URL character
+ * (`?q=*`, `/~`) and is preserved (bb623af); the mirrored-delimiter pass above
+ * is what removes those when the text really did wrap the URL in `*…*`.
+ */
+function stripEmphasisBoundaries(value: string): string {
+ let result = value;
+ let stripped = true;
+
+ while (stripped && result.length > 0) {
+ stripped = false;
+ for (const pair of EMPHASIS_PAIRS) {
+ if (result.endsWith(pair)) {
+ result = trimLinkCandidate(result.slice(0, -pair.length));
+ stripped = true;
+ break;
+ }
+ if (result.startsWith(pair)) {
+ result = result.slice(pair.length);
+ stripped = true;
+ break;
+ }
+ }
+ }
+
+ return result;
+}
+
function trimMarkdownWrappedLinkCandidate(text: string, start: number, candidate: string): string {
const value = trimLinkCandidate(candidate);
const closingDelimiter = markdownClosingDelimiterBefore(text, start);
- if (closingDelimiter == null || !value.endsWith(closingDelimiter)) {
- return value;
- }
+ const mirrored =
+ closingDelimiter != null && value.endsWith(closingDelimiter)
+ ? trimLinkCandidate(value.slice(0, -closingDelimiter.length))
+ : value;
- return trimLinkCandidate(value.slice(0, -closingDelimiter.length));
+ return stripEmphasisBoundaries(mirrored);
}
function safeDecode(value: string): string {