Skip to content

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

Python

fix(gui): nested emphasis survives, and a URL's own ** / __ / ~~ tail stays in the target (#197)

justrachdd66fab6ed4d
diff --git a/gui/src/components/chat/ChatInlineText.test.tsx b/gui/src/components/chat/ChatInlineText.test.tsx
index 905a3a8c..23125831 100644
--- a/gui/src/components/chat/ChatInlineText.test.tsx
+++ b/gui/src/components/chat/ChatInlineText.test.tsx
@@ -13,7 +13,7 @@ const WRAPPED = [
"~~http://localhost:3003~~",
"Open **http://localhost:3003** now",
"Open __http://localhost:3003__ now",
- "http://localhost:3003**",
+ "**Note: open http://localhost:3003**",
];
test("never puts Markdown emphasis delimiters in the clickable target", () => {
@@ -23,7 +23,17 @@ test("never puts Markdown emphasis delimiters in the clickable target", () => {
}
});
+// The strip above is conditional on an opening delimiter earlier in the text:
+// `**`, `__` and `~~` are ordinary URL characters when nothing opened them.
+const UNWRAPPED = [
+ "https://example.com/?q=*",
+ "https://example.com/glob/**",
+ "https://docs.python.org/3/reference/datamodel.html#object.__init__",
+];
+
test("keeps legitimate trailing URL characters clickable", () => {
- const html = renderToStaticMarkup(<ChatInlineText text="https://example.com/?q=*" />);
- expect(html).toContain('title="https://example.com/?q=*"');
+ for (const text of UNWRAPPED) {
+ const html = renderToStaticMarkup(<ChatInlineText text={text} />);
+ expect(html).toContain(`title="${text}"`);
+ }
});
diff --git a/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx b/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx
index f0a13473..8546bc22 100644
--- a/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx
+++ b/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx
@@ -60,6 +60,25 @@ test("no streaming prefix ever produces a delimiter-tailed link target", () => {
}
});
+test("keeps a bold span bold when it contains nested emphasis and a URL", () => {
+ const html = renderToStaticMarkup(
+ <MarkdownRenderer text="**Note: see *this* file at http://localhost:3003**" />,
+ );
+ expect(html).toContain("font-medium");
+ expect(html).toContain("<em>this</em>");
+ expect(linkTargets(html)).toContain("http://localhost:3003");
+ expect(html).not.toContain("**");
+});
+
+// The autolinker only drops a trailing `**` when the text in front of the URL
+// actually opened one; an unpaired `**` that the parser left as literal text is
+// part of the target.
+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);
+});
+
test("keeps a bold-wrapped URL bold and its target clean", () => {
const html = renderToStaticMarkup(
<MarkdownRenderer text="Server at **http://localhost:3003** now" />,
diff --git a/gui/src/components/chat/markdown/parser.test.ts b/gui/src/components/chat/markdown/parser.test.ts
index 9aef1dc7..d7b397e3 100644
--- a/gui/src/components/chat/markdown/parser.test.ts
+++ b/gui/src/components/chat/markdown/parser.test.ts
@@ -142,6 +142,54 @@ describe("parseInline", () => {
{ type: "strong", children: [{ type: "text", value: "bold" }] },
]);
});
+
+ // The nearest-opener rule must not stop the scan at the first pair that
+ // *closes* — that pair is the inner one. Returning it abandons the enclosing
+ // run, so `**…**` degrades back to literal asterisks (the other half of #197).
+ test("keeps the enclosing span when emphasis nests", () => {
+ expect(parseInline("**bold *nested* end**")).toEqual([
+ {
+ type: "strong",
+ children: [
+ { type: "text", value: "bold " },
+ { type: "em", children: [{ type: "text", value: "nested" }] },
+ { type: "text", value: " end" },
+ ],
+ },
+ ]);
+ expect(parseInline("*it **st** it*")).toEqual([
+ {
+ type: "em",
+ children: [
+ { type: "text", value: "it " },
+ { type: "strong", children: [{ type: "text", value: "st" }] },
+ { type: "text", value: " it" },
+ ],
+ },
+ ]);
+ });
+
+ // CommonMark's rule of three: the interior `*` may not steal one asterisk
+ // from the opening `**`, which would leave a literal `**` glued to whatever
+ // follows — the exact precondition for the #197 link-target bug.
+ test("does not let an interior * split a bold span", () => {
+ expect(parseInline("**x*y**")).toEqual([
+ { type: "strong", children: [{ type: "text", value: "x*y" }] },
+ ]);
+ });
+
+ test("bolds a URL nested inside an emphasized sentence", () => {
+ expect(parseInline("**Note: see *this* at http://localhost:3003**")).toEqual([
+ {
+ type: "strong",
+ children: [
+ { type: "text", value: "Note: see " },
+ { type: "em", children: [{ type: "text", value: "this" }] },
+ { type: "text", value: " at http://localhost:3003" },
+ ],
+ },
+ ]);
+ });
});
describe("dropRedundantCodeHeadings", () => {
diff --git a/gui/src/components/chat/markdown/parser.ts b/gui/src/components/chat/markdown/parser.ts
index 867c649c..fb49c317 100644
--- a/gui/src/components/chat/markdown/parser.ts
+++ b/gui/src/components/chat/markdown/parser.ts
@@ -514,8 +514,11 @@ function nextInlineMatch(text: string, from: number): InlineMatch | null {
}
interface StarRun {
- start: number;
+ /** Index just past the run: emphasis content starts here. */
end: number;
+ /** Number of asterisks in the run. */
+ length: number;
+ canClose: boolean;
}
function isWhitespaceAt(text: string, index: number): boolean {
@@ -523,6 +526,33 @@ function isWhitespaceAt(text: string, index: number): boolean {
return char == null || /\s/u.test(char);
}
+/**
+ * CommonMark's "rule of three": when either side of a candidate pair can play
+ * both roles, a match is forbidden if the two run lengths sum to a multiple of
+ * 3 unless both are themselves multiples of 3. Without it the inner `*` of
+ * `**x*y**` would steal one asterisk from the opening `**` and the span would
+ * collapse into `*<em>x</em>y**`.
+ */
+function canPair(openerLength: number, closerLength: number, ambiguous: boolean): boolean {
+ if (!ambiguous) {
+ return true;
+ }
+ if ((openerLength + closerLength) % 3 !== 0) {
+ return true;
+ }
+ return openerLength % 3 === 0 && closerLength % 3 === 0;
+}
+
+function findOpenerIndex(open: StarRun[], closerLength: number, closerCanOpen: boolean): number {
+ for (let index = open.length - 1; index >= 0; index -= 1) {
+ const opener = open[index];
+ if (canPair(opener.length, closerLength, closerCanOpen || opener.canClose)) {
+ return index;
+ }
+ }
+ return -1;
+}
+
/**
* CommonMark-style `*` / `**` emphasis, replacing the old lazy
* "two asterisks, anything, two asterisks" regexes.
@@ -534,9 +564,17 @@ function isWhitespaceAt(text: string, index: number): boolean {
* 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.
+ *
+ * The scan does not stop at the first pair that closes. findInline expects the
+ * *earliest-starting* inline node (parseInline emits the text before it, the
+ * node, then recurses over the rest), and the first pair to close is usually
+ * the innermost one: in `**bold *nested* end**` the `*nested*` pair closes
+ * first, yet the node that must be returned is the enclosing `**…**`. Returning
+ * the inner one abandons the outer run and both `**` fall back to literal text.
*/
function findStarEmphasis(text: string, from: number): InlineMatch | null {
const open: StarRun[] = [];
+ let best: InlineMatch | null = null;
let index = from;
while (index < text.length) {
@@ -550,30 +588,39 @@ function findStarEmphasis(text: string, from: number): InlineMatch | null {
end += 1;
}
+ const length = end - index;
const canOpen = !isWhitespaceAt(text, end);
- const opener = isWhitespaceAt(text, index - 1) ? undefined : open.pop();
- if (opener != null) {
+ const canClose = !isWhitespaceAt(text, index - 1);
+ const openerIndex = canClose ? findOpenerIndex(open, length, canOpen) : -1;
+
+ if (openerIndex >= 0) {
+ const opener = open[openerIndex];
+ // Everything opened after the matched run is nested inside this span and
+ // is re-scanned by the recursive parseInline below, so drop it here.
+ open.length = openerIndex;
+
// 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 size = Math.min(opener.length, length) >= 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 (best == null || start < best.index) {
+ best = {
+ index: start,
+ length: index + size - start,
+ node: {
+ type: size === 2 ? "strong" : "em",
+ children: parseInline(text.slice(opener.end, index)),
+ },
+ };
+ }
+ } else if (canOpen) {
+ open.push({ end, length, canClose });
}
- if (canOpen) {
- open.push({ start: index, end });
- }
index = end;
}
- return null;
+ return best;
}
function pushCandidate(
diff --git a/gui/src/components/chat/utils/chatLinks.test.ts b/gui/src/components/chat/utils/chatLinks.test.ts
index c57c6d22..f762562a 100644
--- a/gui/src/components/chat/utils/chatLinks.test.ts
+++ b/gui/src/components/chat/utils/chatLinks.test.ts
@@ -71,19 +71,35 @@ describe("getChatLinkMatches URL vs Markdown delimiters", () => {
});
// #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");
+ // delimiters sit immediately before the URL. A bold span whose opener is
+ // further back in the line ("**Note: see <url>**") still has to yield a clean
+ // target, so a trailing pair is dropped when the text in front of the URL
+ // opened it.
+ test("strips a trailing pair opened earlier in the same text", () => {
+ expect(firstUrl("**Note: see http://localhost:3003**")).toBe("http://localhost:3003");
+ expect(firstUrl("__see http://localhost:3003__")).toBe("http://localhost:3003");
+ expect(firstUrl("~~gone: http://localhost:3003~~")).toBe("http://localhost:3003");
+ });
+
+ // ...but only then. `**`, `__` and `~~` are all legal URL characters, and
+ // stripping them unconditionally truncated real targets (regression of
+ // bb623af): Python's docs anchors are the canonical victim.
+ test("preserves a trailing pair that no opener precedes", () => {
+ expect(firstUrl("https://docs.python.org/3/reference/datamodel.html#object.__init__")).toBe(
+ "https://docs.python.org/3/reference/datamodel.html#object.__init__",
+ );
+ expect(firstUrl("see https://docs.python.org/3/library/functions.html#__import__ here")).toBe(
+ "https://docs.python.org/3/library/functions.html#__import__",
+ );
+ expect(firstUrl("https://example.com/x__")).toBe("https://example.com/x__");
+ expect(firstUrl("https://example.com/a~~")).toBe("https://example.com/a~~");
+ expect(firstUrl("https://example.com/glob/**")).toBe("https://example.com/glob/**");
+ });
+
+ test("reports the full span for a URL ending in a legal delimiter pair", () => {
+ const text = "https://docs.python.org/3/reference/datamodel.html#object.__init__";
+ const [match] = getChatLinkMatches(text);
+ expect(match).toMatchObject({ kind: "url", start: 0, end: text.length, value: text });
});
test("strips underscore emphasis wrapping a bare URL", () => {
diff --git a/gui/src/components/chat/utils/chatLinks.ts b/gui/src/components/chat/utils/chatLinks.ts
index a99907a5..04a147c4 100644
--- a/gui/src/components/chat/utils/chatLinks.ts
+++ b/gui/src/components/chat/utils/chatLinks.ts
@@ -4,8 +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).
+// Paired Markdown emphasis delimiters. Dropped from a link target only when the
+// preceding text actually opened the pair (#197); they are legal URL characters
+// otherwise (`#object.__init__`, `/glob/**`).
const EMPHASIS_PAIRS = ["**", "__", "~~"] as const;
const FILE_BASENAME_EXTENSION_PATTERN = /\.[A-Za-z0-9_-]+$/u;
const WINDOWS_DRIVE_PATH_PATTERN = /^[A-Za-z]:[\\/]/u;
@@ -118,29 +119,49 @@ function markdownClosingDelimiterBefore(text: string, start: number): string | n
}
/**
- * 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 `*…*`.
+ * Does the text in front of the URL contain a run that could have *opened* this
+ * emphasis pair? A delimiter run only opens when a non-space follows it, so
+ * `**Note: see ` opens but `2 ** 3 ` does not.
*/
-function stripEmphasisBoundaries(value: string): string {
+function hasEmphasisOpenerBefore(before: string, pair: string): boolean {
+ let index = before.indexOf(pair);
+ while (index >= 0) {
+ const next = before[index + pair.length];
+ if (next != null && !/\s/u.test(next)) {
+ return true;
+ }
+ index = before.indexOf(pair, index + 1);
+ }
+
+ return false;
+}
+
+/**
+ * Defense in depth for #197: a paired Markdown emphasis delimiter (`**`, `__`,
+ * `~~`) is not part of the link target when the surrounding text actually
+ * opened that pair earlier — `**Note: see http://x.test**` reaches this matcher
+ * with the opener too far from the URL for the mirrored pass above to see it.
+ *
+ * The strip stays *conditional* on that opener. `**`, `__` and `~~` are all
+ * legal URL characters, and an unconditional strip truncates real targets
+ * (`…/datamodel.html#object.__init__`, `…/glob/**`, `…/a~~`) — a regression of
+ * bb623af, which is why a lone trailing `*`/`~` was already left alone.
+ */
+function stripEmphasisBoundaries(before: string, value: string): string {
let result = value;
let stripped = true;
while (stripped && result.length > 0) {
stripped = false;
for (const pair of EMPHASIS_PAIRS) {
+ if (!hasEmphasisOpenerBefore(before, pair)) {
+ continue;
+ }
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;
- }
}
}
@@ -155,7 +176,7 @@ function trimMarkdownWrappedLinkCandidate(text: string, start: number, candidate
? trimLinkCandidate(value.slice(0, -closingDelimiter.length))
: value;
- return stripEmphasisBoundaries(mirrored);
+ return stripEmphasisBoundaries(text.slice(0, start), mirrored);
}
function safeDecode(value: string): string {