From c7a1eb910d17cf638bd7e11d0a549effad8e67cd Mon Sep 17 00:00:00 2001 From: chengyongru <61816729+chengyongru@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:04:05 +0800 Subject: [PATCH] fix(webui): prevent single-dollar math from crossing code spans (#6646) --- webui/browser/fixture.tsx | 3 + .../browser/markdown-dollar-refs-fixture.tsx | 34 ++++++ webui/browser/markdown-dollar-refs.spec.ts | 37 ++++++ webui/bun.lock | 1 + webui/package-lock.json | 1 + webui/package.json | 1 + webui/src/lib/remark-tex-math.ts | 32 ++++- .../tests/fixtures/markdown-dollar-refs.md | 24 ++++ .../src/tests/markdown-text-renderer.test.tsx | 114 ++++++++++++++++++ 9 files changed, 245 insertions(+), 2 deletions(-) create mode 100644 webui/browser/markdown-dollar-refs-fixture.tsx create mode 100644 webui/browser/markdown-dollar-refs.spec.ts create mode 100644 webui/src/tests/fixtures/markdown-dollar-refs.md diff --git a/webui/browser/fixture.tsx b/webui/browser/fixture.tsx index 15e72555b..fac7d74eb 100644 --- a/webui/browser/fixture.tsx +++ b/webui/browser/fixture.tsx @@ -44,6 +44,7 @@ import { ComposerActionFixture } from "./composer-action-fixture"; import { MobileChatLayoutFixture } from "./mobile-chat-layout-fixture"; import { ThemeToggleFixture } from "./theme-toggle-fixture"; import { DisplayMathFixture } from "./display-math-fixture"; +import { MarkdownDollarRefsFixture } from "./markdown-dollar-refs-fixture"; import { AttachmentLayoutFixture } from "./attachment-layout-fixture"; import { LoadedSessionSearchFixture } from "./loaded-session-search-fixture"; import { AppearanceFixture } from "./appearance-fixture"; @@ -267,6 +268,8 @@ createRoot(document.getElementById("root")!).render( ? : parameters.get("case") === "display-math" ? + : parameters.get("case") === "markdown-dollar-refs" + ? : parameters.get("case") === "code-wrapping" ? : parameters.get("case") === "typography" diff --git a/webui/browser/markdown-dollar-refs-fixture.tsx b/webui/browser/markdown-dollar-refs-fixture.tsx new file mode 100644 index 000000000..f9ab7d75b --- /dev/null +++ b/webui/browser/markdown-dollar-refs-fixture.tsx @@ -0,0 +1,34 @@ +import { useState } from "react"; + +import { MessageBubble } from "@/components/MessageBubble"; +import dollarRefsFixture from "@/tests/fixtures/markdown-dollar-refs.md?raw"; + +const source = dollarRefsFixture.replaceAll("\r\n", "\n"); +const codeStart = source.indexOf("`$defs`"); +const ends = [codeStart + 1, codeStart + 2, codeStart + 4, codeStart + 7, source.length]; +const precedenceExamples = [ + "**$ref** supports `$defs / definitions`.", + "**$ref** in C:\\Users\\me uses `$defs`.", + "A $x`$th`", + "Explicit \\(f(`x')\\)th`code`.", +].join("\n\n"); + +export function MarkdownDollarRefsFixture() { + const [step, setStep] = useState(0); + const [streaming, setStreaming] = useState(true); + return
+ +
+ +
+
+ +
+
+ +
+
; +} diff --git a/webui/browser/markdown-dollar-refs.spec.ts b/webui/browser/markdown-dollar-refs.spec.ts new file mode 100644 index 000000000..e16bd0a21 --- /dev/null +++ b/webui/browser/markdown-dollar-refs.spec.ts @@ -0,0 +1,37 @@ +import { expect, test } from "@playwright/test"; + +for (const width of [1280, 390]) { + test(`preserves dollar references while streaming at ${width}px`, async ({ page }, info) => { + const errors: string[] = []; + page.on("pageerror", (error) => errors.push(error.message)); + await page.setViewportSize({ width, height: 844 }); + await page.goto("/browser/fixture.html?case=markdown-dollar-refs"); + const reply = page.getByRole("region", { name: "Reported assistant reply" }); + const formulas = page.getByRole("region", { name: "Inline formulas" }); + const precedence = page.getByRole("region", { name: "Code and math precedence" }); + async function expectPrecedence() { + await expect(precedence.locator("strong")).toHaveText(["$ref", "$ref"]); + await expect(precedence.locator("code")).toHaveText(["$defs / definitions", "$defs", "$th", "code"]); + await expect(precedence.locator("annotation")).toHaveText(["f(`x')"]); + await expect(precedence.locator(".katex-error")).toHaveCount(0); + } + await expectPrecedence(); + await expect(formulas.locator("annotation")).toHaveText(["n", "\\text{`value`}"]); + await expect(formulas.locator(".katex-error")).toHaveCount(0); + for (let step = 0; step < 5; step++) { + await expect(reply.locator("strong").filter({ hasText: "已经有一份完整的 $ref 解析器" })).toHaveCount(1); + await expect(reply.locator(".katex")).toHaveCount(0); + if (step < 4) await page.getByRole("button", { name: "Advance stream" }).click(); + } + await expect(reply.locator("code").filter({ hasText: "_resolve_local_schema_ref" })).toHaveCount(1); + await expect(reply.locator("code").filter({ hasText: "$defs" }).first()).toHaveText("$defs"); + await expect(reply).toContainText("用一个词总结这个 PR"); + await page.getByRole("button", { name: "Complete" }).click(); + await expect(reply.locator("[data-assistant-selectable=true]")).toHaveCount(1); + await expect(reply.locator("strong").filter({ hasText: "已经有一份完整的 $ref 解析器" })).toHaveCount(1); + await expect(reply.locator(".katex")).toHaveCount(0); + await expectPrecedence(); + expect(errors).toEqual([]); + if (width === 1280) await page.screenshot({ path: info.outputPath("reported-message.png"), fullPage: true }); + }); +} diff --git a/webui/bun.lock b/webui/bun.lock index 2b372f8ee..f0b9781c5 100644 --- a/webui/bun.lock +++ b/webui/bun.lock @@ -22,6 +22,7 @@ "diff": "^9.0.0", "i18next": "^26.0.6", "lucide-react": "^0.469.0", + "micromark-core-commonmark": "^2.0.3", "micromark-factory-space": "^2.0.1", "motion": "^14.4.0", "pele": "1.9.0", diff --git a/webui/package-lock.json b/webui/package-lock.json index 97ace9dad..b3f326774 100644 --- a/webui/package-lock.json +++ b/webui/package-lock.json @@ -25,6 +25,7 @@ "diff": "^9.0.0", "i18next": "^26.0.6", "lucide-react": "^0.469.0", + "micromark-core-commonmark": "^2.0.3", "micromark-factory-space": "^2.0.1", "micromark-util-decode-string": "^2.0.1", "motion": "^14.4.0", diff --git a/webui/package.json b/webui/package.json index 7a7be27a5..de1916251 100644 --- a/webui/package.json +++ b/webui/package.json @@ -35,6 +35,7 @@ "diff": "^9.0.0", "i18next": "^26.0.6", "lucide-react": "^0.469.0", + "micromark-core-commonmark": "^2.0.3", "micromark-factory-space": "^2.0.1", "motion": "^14.4.0", "pele": "1.9.0", diff --git a/webui/src/lib/remark-tex-math.ts b/webui/src/lib/remark-tex-math.ts index 4734f9552..a672ebfc1 100644 --- a/webui/src/lib/remark-tex-math.ts +++ b/webui/src/lib/remark-tex-math.ts @@ -1,10 +1,12 @@ import type { Root } from "mdast"; +import { codeText } from "micromark-core-commonmark"; import { factorySpace } from "micromark-factory-space"; -import type { Code, Construct, Effects, Extension, State, Token } from "micromark-util-types"; +import type { Code, Construct, Effects, Extension, State, Token, TokenizeContext } from "micromark-util-types"; import type { Plugin } from "unified"; import type {} from "micromark-extension-math"; const BACKSLASH = 92; +const BACKTICK = 96; const DOLLAR = 36; const LEFT_PAREN = 40; const RIGHT_PAREN = 41; @@ -120,11 +122,24 @@ const nonLazyContinuation: Construct = { }; // Model output commonly uses `$...$`; numeric-only spans are usually prices, not formulas. -function tokenizeGuardedDollarMathText(effects: Effects, ok: State, nok: State): State { +function tokenizeGuardedDollarMathText( + this: TokenizeContext, effects: Effects, ok: State, nok: State, +): State { + const currentOffset = () => this.now().offset; let hasMathSignal = false; let hasContent = false; let firstDataCode: Code = null; let previousDataCode: Code = null; + let codeSpanEnd = 0; + const codeSpan: Construct = { + partial: true, + tokenize(effects, ok, nok) { + return codeText.tokenize.call(this, effects, (code) => { + codeSpanEnd = this.events[this.events.length - 1][1].end.offset; + return ok(code); + }, nok); + }, + }; return start; @@ -149,7 +164,14 @@ function tokenizeGuardedDollarMathText(effects: Effects, ok: State, nok: State): return nok(code); } + if (code === BACKTICK && currentOffset() >= codeSpanEnd) { + return effects.check(codeSpan, data, unmatchedBackticks)(code); + } + if (code === DOLLAR) { + // A single-dollar formula cannot end inside a complete Markdown code span. + // Formulas with crossing backticks can use the explicit TeX delimiters. + if (currentOffset() < codeSpanEnd) return nok(code); effects.exit("mathTextData"); effects.enter("mathTextSequence"); effects.consume(code); @@ -162,6 +184,12 @@ function tokenizeGuardedDollarMathText(effects: Effects, ok: State, nok: State): return code === BACKSLASH ? escaped : data; } + function unmatchedBackticks(code: Code): State | undefined { + if (code !== BACKTICK) return data(code); + consumeData(code); + return unmatchedBackticks; + } + function escaped(code: Code): State | undefined { if (code === null || isLineEnding(code)) { effects.exit("mathTextData"); diff --git a/webui/src/tests/fixtures/markdown-dollar-refs.md b/webui/src/tests/fixtures/markdown-dollar-refs.md new file mode 100644 index 000000000..c39b2e1b8 --- /dev/null +++ b/webui/src/tests/fixtures/markdown-dollar-refs.md @@ -0,0 +1,24 @@ +我先把你的第二个问题答清楚,因为它决定了第一个问题怎么答。 + +**nanobot 不用 JSON Schema 的规范实现。** 没有 `jsonschema` 依赖,`base.py` 里 `validate_json_schema_value` 是手写的子集校验器——只认 `type`/`required`/`properties`/`additionalProperties`/`enum`/`min`/`max`/`items` 这些。所以"不认 `$ref`/`anyOf`"不是违反 MCP 规范,是自建校验器不完整。MCP 规范本身也没要求客户端本地校验,责任在 server 一侧。 + +另外有个作者和我之前都没提的事:`mcp.py` 里**已经有一份完整的 $ref 解析器** `_resolve_local_schema_ref`,支持 JSON Pointer 全路径、`~0`/`~1` 转义、嵌套。它在构造 wrapper 时就把 server 给的本地 ref 全部提升到根 `$defs`。PR 又在 `base.py` 写了一个简化版(只认单段 `#/$defs/x`、`#/definitions/x`,不处理转义和嵌套路径)。对 MCP 工具能用,是因为规整层已经兜住了;但同一件事现在有两套实现。 + +**具体误拒的例子(我实测了,不是推测):** + +`def book(addr: Address | None = None)` 这种签名,FastMCP 输出 `anyOf: [{$ref: Address}, {type: null}]`,nanobot 的 `_normalize_nullable_schema` 把它折叠成 `{$ref: "#/$defs/Address", nullable: true}`。 + +然后传 `{"addr": null}` 的结果: + +- main:`[]`,通过。 +- PR:`["addr should be object"]`,被拦。 + +原因是新代码先按 `$ref` 解析出的 Address 去校验 `None`,报错了;兄弟关键字 `nullable: true` 虽然判定通过,但只是 `extend`,前面那条错误留在结果里。嵌套可选字段一样中招:`{"user": {"address": null}}` → `["user.address should be object"]`。 + +模型显式吐 `null` 的情况不算高频,但确实会发生,而且这是**从能用到不能用**的变化,测试里一条都没覆盖(作者的 ref 测试全是必填)。 + +顺带一个小例子:`oneOf: [{type: integer}, {type: number}]` 传 `3`,被判 `"should match exactly one of the allowed schemas"`——3 同时匹配两支。这是 schema 作者自己写得不严谨,Pydantic 一般发 `anyOf`,所以低频,但 `oneOf` 的严格判定会放大这类问题。 + +**修法很简单**:`$ref` 分支前先走原有的 nullable 判断——`schema.get("nullable")` 为真且 `val is None` 时直接放行,不要去校验被引用的子 schema。 + +用一个词总结这个 PR:方向对,实现漏了 nullable,外加重复了一份已经有更好版本的解析器。 diff --git a/webui/src/tests/markdown-text-renderer.test.tsx b/webui/src/tests/markdown-text-renderer.test.tsx index 51f48b3fb..69b53555c 100644 --- a/webui/src/tests/markdown-text-renderer.test.tsx +++ b/webui/src/tests/markdown-text-renderer.test.tsx @@ -3,6 +3,7 @@ import { beforeAll, describe, expect, it, vi } from "vitest"; import { FilePreviewAvailabilityProvider } from "@/components/FilePreviewAvailabilityContext"; import MarkdownTextRenderer from "@/components/MarkdownTextRenderer"; +import dollarRefsFixture from "@/tests/fixtures/markdown-dollar-refs.md?raw"; // Exercise the asynchronous math boundary once, then test the loaded grammar cases. @@ -1099,6 +1100,119 @@ describe("MarkdownTextRenderer", () => { expect(container.querySelectorAll("strong")).toHaveLength(3); }); + it.each([false, true])("preserves the reported dollar references through completion (streaming=%s)", (streaming) => { + const source = dollarRefsFixture.replaceAll("\r\n", "\n"); + const { container, rerender } = render( + {source}, + ); + + function expectReportedMessage() { + const strong = [...container.querySelectorAll("strong")].map((element) => element.textContent); + const code = [...container.querySelectorAll("code")].map((element) => element.textContent); + expect(strong).toContain("已经有一份完整的 $ref 解析器"); + expect(code).toEqual(expect.arrayContaining(["_resolve_local_schema_ref", "~0", "~1", "$defs", "#/$defs/x", "#/definitions/x"])); + expect(container.querySelector(".katex")).toBeNull(); + expect(container).toHaveTextContent("用一个词总结这个 PR"); + } + + expectReportedMessage(); + rerender({source}); + expectReportedMessage(); + }); + + it("keeps the reported formatting while its code span streams and after completion", () => { + const source = dollarRefsFixture.replaceAll("\r\n", "\n"); + const codeStart = source.indexOf("`$defs`"); + const { container, rerender } = render({""}); + + for (const end of [codeStart, codeStart + 1, codeStart + 2, codeStart + 4, codeStart + 7, source.length]) { + rerender({source.slice(0, end)}); + expect(container.querySelector(".katex"), `code prefix length: ${end - codeStart}`).toBeNull(); + expect([...container.querySelectorAll("strong")].some((node) => node.textContent === "已经有一份完整的 $ref 解析器")).toBe(true); + } + rerender({source}); + expect(container.querySelector(".katex")).toBeNull(); + expect(screen.getByText("_resolve_local_schema_ref").tagName).toBe("CODE"); + expect(screen.getByText("$defs").tagName).toBe("CODE"); + }); + + it.each([ + "**$ref** followed by `value=$defs`.", + "**$ref** followed by `` `value=$defs` ``.", + "**$ref** followed by `first` then `value=$defs`.", + "**$ref** followed by `resolve(` then `value=$defs`.", + "**$ref** followed by `\\n` then `value=$defs`.", + "**$ref** (see `$defs`).", + "**$ref** followed by `\\path=$defs`.", + "**$ref** followed by `\\$escaped and $defs`.", + "**$ref** followed by \\{literal `value=$defs`.", + "**$ref** supports `$defs / definitions`.", + "**$ref** in C:\\Users\\me uses `$defs`.", + "**$ref** followed by `$ / literal dollar and $defs`.", + ])("preserves a closing dollar inside a complete code span: %s", (source) => { + const { container } = render({source}); + expect(container.querySelector("strong")).toHaveTextContent("$ref"); + expect(container.querySelector(".katex")).toBeNull(); + expect(container.querySelector("code:last-child")).toHaveTextContent("$defs"); + }); + + it("keeps code immediately after a literal dollar renderable", () => { + const { container } = render({"$`$defs`"}); + expect(container).toHaveTextContent("$$defs"); + expect(screen.getByText("$defs").tagName).toBe("CODE"); + expect(container.querySelector(".katex")).toBeNull(); + }); + + it.each(["$x$km", "$x$2", "$a+b$meters"])("keeps inline math before an adjacent suffix: %s", (source) => { + const { container } = render({source}); + expect(container.querySelector(".katex-error")).toBeNull(); + expect(container.querySelector("annotation")?.textContent).toBe(source.slice(1, source.indexOf("$", 1))); + }); + + it.each(["$x`$", "$\\text{`value`}$", "$\\text{`\\$`}$", "$\\verb|`|$"])( + "keeps literal backticks in valid inline math: %s", (source) => { + const { container } = render({source}); + expect(container.querySelector(".katex-error")).toBeNull(); + expect(container.querySelector("annotation")?.textContent).toBe(source.slice(1, -1)); + }, + ); + + it.each([ + ["A $x`$th`", "$th"], + ["A $f(`x')$th`code`.", "x')$th"], + ["A $\\verb|`|$th`code`.", "|$th"], + ])("prefers complete code over a crossing single-dollar formula: %s", (source, code) => { + const { container } = render({source}); + expect(container.querySelector(".katex")).toBeNull(); + expect(container.querySelector("code")).toHaveTextContent(code); + }); + + it.each(["x`", "\\text{`quoted'}", "f(`quoted')", "\\verb|`|", "x`\\text{hello `a `b}"])( + "keeps explicit TeX math separate from following Markdown code: %s", (formula) => { + const source = `\\(${formula}\\)th **important** then \`code\`.`; + const { container, rerender } = render({source}); + function expectMathAndCode() { + expect(container.querySelector(".katex-error")).toBeNull(); + expect(container.querySelector("annotation")?.textContent).toBe(formula); + expect(screen.getByText("important").tagName).toBe("STRONG"); + expect(screen.getByText("code").tagName).toBe("CODE"); + } + expectMathAndCode(); + rerender({source}); + expectMathAndCode(); + }, + ); + + it("preserves escaped dollar references, code, and ordinary inline formulas", () => { + const { container } = render( + {"Escaped \\$ref and $defs, code `$x$`, math $a*b*c$ and $x_i$."}, + ); + expect(container).toHaveTextContent("Escaped $ref and $defs"); + expect(screen.getByText("$x$").tagName).toBe("CODE"); + expect([...container.querySelectorAll("annotation")].map((node) => node.textContent)).toEqual(["a*b*c", "x_i"]); + expect(container.querySelector(".katex-error")).toBeNull(); + }); + it("renders guarded single-dollar inline math", () => { const { container } = render(