Skip to content

fix(cli): recognize markdown fences only on matching lines - #13331

Merged
wenshao merged 4 commits into
QwenLM:mainfrom
GoldArowana:fix/markdown-inline-fence-detection
Oct 13, 2026
Merged

wenshao merged 4 commits into
QwenLM:mainfrom
GoldArowana:fix/markdown-inline-fence-detection

Conversation

@GoldArowana

@GoldArowana GoldArowana commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

What this PR does

The streaming Markdown splitter now recognizes code fences with the renderer's line-matching rules. Inline backtick or tilde markers remain ordinary prose; genuine fenced blocks retain their close/reopen behavior and line numbering. Regression coverage includes inline markers, invalid info strings, indented fences, and longer delimiters. Internal helper naming and imports follow the repository's conventions.

Why it's needed

An inline fence mention such as Use `~~~` as the fence marker. previously opened a false code block during splitting and inserted synthetic fences into ordinary prose.

Reviewer Test Plan

How to verify

Split the issue example before More ordinary prose follows.: both resulting strings should match the original substrings and the enclosing-fence result should be null. Repeat inside genuine backtick and tilde fenced blocks: the first chunk should close the block and the second should reopen it with the original language and the correct continuation line. Also verify indented and longer fences and info strings containing backticks.

Validation at fd0e42e: 41 Markdown utility tests and 289 streaming tests passed. Six parent/fixed reproduction scenarios passed, including controls for genuine backtick and tilde fences.

Evidence (Before & After)

For Use `~~~` as the fence marker.\nMore ordinary prose follows., split before More:

  • Before (eb0b79c): the enclosing-fence result was { lang: "`", startLine: 1 }; the first chunk gained a closing ~~~ and the second gained a reopening fence with an incorrect info string.
  • After (fd0e42e): the enclosing-fence result is null; the chunks are exactly Use `~~~` as the fence marker.\n and More ordinary prose follows..
  • Genuine backtick and tilde fence controls preserve closing/reopening and qwen-code:start-line=2 on both revisions.

Tested on

OS Status
macOS ✅ Focused tests and script reproduction
Windows ⚠️ Not tested locally
Linux ✅ Cloud build, bundle, typecheck and focused tests

Environment (optional)

macOS arm64, Node.js v24.13.0, npm 11.6.2. Existing local dependencies and built workspace prerequisites were reused. Verification used source-level scripts and focused unit tests.

Risk & Scope

  • Main risk or tradeoff: streaming split boundaries now follow the existing renderer's fence pattern.
  • Not validated / out of scope: live interactive streaming TUI and the full repository unit-test suite. Cloud build, bundle, CLI and repository typecheck, and focused tests pass with the pinned frozen dependency layout.
  • Breaking changes / migration notes: no public API or configuration changes.

Linked Issues

Fixes #13309

中文说明

这个 PR 做了什么

Markdown 流式切分现在按渲染器的逐行规则识别代码围栏。正文中内联出现的反引号或波浪号保留为普通正文,真正的代码块仍能在切分时闭合、重开并延续行号。回归用例覆盖内联标记、无效信息字符串、缩进围栏和较长的分隔符;内部辅助模块的命名与引用也按仓库约定更新。

为什么需要

此前,正文中类似 Use `~~~` as the fence marker. 的内联围栏说明会在切分时被误判为代码块起点,导致普通正文被插入多余围栏。

评审者验证计划

如何验证

在 Issue 示例的 More ordinary prose follows. 前切分:两段结果应分别等于原文的对应子串,所处代码围栏的判断结果应为 null。再在真正的反引号和波浪号代码块内切分:前段应闭合代码块,后段应按原语言重开,并延续正确的行号。同时检查带缩进、较长的围栏,以及包含反引号的信息字符串。

fd0e42e 的验证结果:41 项 Markdown 工具测试与 289 项流式处理测试通过;修复前后共 6 个脚本复现场景通过,其中包含真正的反引号与波浪号围栏对照。

证据(修复前后)

对 Use `~~~` as the fence marker.\nMore ordinary prose follows.,在 More 前切分:

  • 修复前(eb0b79c):所处围栏的判断结果为 { lang: "`", startLine: 1 };前段多出闭合 ~~~,后段多出信息字符串错误的重开围栏。
  • 修复后(fd0e42e):判断结果为 null;两段准确保留为 Use `~~~` as the fence marker.\n 与 More ordinary prose follows.。
  • 真正的反引号与波浪号围栏对照在两个版本上都保留闭合、重开和 qwen-code:start-line=2。

测试平台

操作系统 状态
macOS ✅ 定向测试与脚本复现通过
Windows ⚠️ 未在本地测试
Linux ✅ 云端构建、bundle、类型检查与定向测试通过

运行环境(可选)

macOS arm64、Node.js v24.13.0、npm 11.6.2。复用了现有本地依赖和已构建的工作区前置包,使用源码脚本与定向单元测试验证。

风险与范围

  • 主要风险或取舍:流式切分边界改为遵循现有渲染器的代码围栏匹配规则。
  • 未验证或范围外:live 交互式流式 TUI 与全仓单元测试。云端使用固定版本和冻结依赖,构建、bundle、CLI 与全仓类型检查及定向测试均通过。
  • 破坏性变更与迁移:没有公开 API 或配置变更。

关联 Issue

Fixes #13309

Cloud verification (fd96930)

The latest review suggestions are addressed in fd96930. Fence state is scanned once, and a bounded line check avoids the shared regex when an info string contains a backtick after the entire delimiter run. Valid fence lines still use the original shared regex, including both captures, exact run lengths, language, and continuation line numbering. The prefix filter is documented as a superset of that regex. Regression tests pin the closed-block cursor reset, same-character tilde info strings, positive scan-count lower bounds, and rejected long-space fence lines.

  • Linux cloud, Node.js 22.23.3, pnpm 11.24.0. Both the unmodified reviewed head and the fix used their own frozen offline dependency installs and build outputs.
  • Build, bundle, CLI typecheck, repository typecheck including integration, focused ESLint and formatting pass. The helper, renderer, pending-height and streaming suites pass 569/569 on the actual modified source.
  • Four exact source mutations fail only the intended new assertions: cursor reset (1), line re-anchor (2), disconnected regex spy (3), and removed local rejection guard (3). Each intact helper run passes 53/53.
  • Independent code review found no blocking correctness or scope issue. An additional 960 targeted assertions cover Unicode whitespace, valid info/directives, long runs, line endings and boundaries. Existing differential evidence includes 2,946,372 original/candidate comparisons with no differences; that sweep was not repeated for publication.
  • Padded 10k/40k-space rejected-line splitter probes measured about 84/1363 ms on the reviewed source. The paired local-filter probe measured about 0.005/0.021 ms with zero shared-regex calls. A 10k literal short input below the 16,384-character cap returns early; the splitter timing witness must exceed the cap. The renderer's existing regex cost remains outside this local fix.
  • Correction to earlier typecheck evidence: the reported Mem0 nullable process.exitCode error does not reproduce on the unmodified reviewed head or the fix with their own pinned frozen installs; both full repository typechecks pass. Its local Node types 22.20.1 allow null, while the previously borrowed root types 20.19.1 do not. No Mem0 source or dependency manifest was changed.
  • Local checks are distinct from GitHub Actions. The reviewed head's main CI and tui-parity runs remained action_required; this update makes no GitHub CI-success claim. No live model API or interactive TUI verification was performed, and math-block precedence remains outside scope.
云端后续验证说明

五条新建议已处理:保留共享正则与第二 capture,只在线内完整分隔符之后存在反引号时跳过必定失败的匹配;补充 cursor reset、同字符 tilde-info、spy 正下界与长空格拒绝行回归。两份独立冻结安装的未修改基线和修复版本均构建与全仓类型检查通过;修复版本另通过 bundle、CLI 类型检查、格式、lint 和 569 项定向测试。四组变异只令各自对应的新断言失败,独立审阅及 Unicode/边界检查通过。

更正先前的 Mem0 类型检查失败说明:正确局部依赖中的 Node types 22.20.1 允许 null,借用的根依赖 20.19.1 不允许;未修改基线与修复版本的全仓检查现在均通过,Mem0 源码和依赖声明未改。既有 renderer 回溯成本、live TUI 与全仓单元测试未由此次验证覆盖。机器人 4/4 与本地检查均不代表 GitHub 主 CI/tui-parity 通过。

Upstream integration verification (5a4e3a1)

Normally merged upstream main ac497aeed956981e817b4301837866730359a65f into this branch to address the approved CI lane's lint gate freshness failure before dependency installation. The merge contains the upstream gate change 6b878e1a04ec70a35f8d14125fb3aafea4fb8973, preserves the original seven-file PR diff, and does not weaken the gate or change the shared fence regex/captures.

On Linux with Node 22.23.3 / pnpm 11.24.0 and the merged tree's frozen dependencies:

  • Full build, bundle, repository/workspace/integration typecheck, zero-warning repository/integration ESLint, and the actual repository Prettier check passed. The CLI prints version 0.25.0.
  • The four actual Markdown/renderer/pending-height/stream suites passed again: 569/569. The current lint helper regressions passed 16/16, and native freshness tests passed 9/9.
  • The unchanged freshness function, supplied with Git-derived commit/compare responses, reproduced exactly one stale gate change on fd96930 and none on the actual new merge commit: 25/25 assertions. This is an ancestry-based local verification, not a live GitHub CI pass.
  • The real pre-commit hook ran all merge-staged formatter/ESLint tasks successfully, but its apply phase reported an ignored-directory error for an E2E plan already tracked by main; the installed hook API still exited 0. I do not count that as a complete hook pass. The pre-hook index and final commit have the same tree, the worktree is clean, and the actual lint-staged configuration separately passed for all seven PR-diff files without that error.

The fork ref and PR metadata both read back the full head 5a4e3a1a4ac2ff5e0301cc203c6f6da3dc84b7e7. Its new Qwen Code CI run 37508564532 and tui-parity run 37508564531 are completed / action_required, awaiting maintainer approval. No CI success is claimed and no further review request was sent.

中文

已正常合并当前 upstream main ac497aeed,新 head 为 5a4e3a1a4ac2ff5e0301cc203c6f6da3dc84b7e7。包含导致原 CI freshness 失败的上游门禁提交,保留原 PR 七文件差异及共享 regex/captures;没有 force push 或弱化门禁。冻结依赖下 build、bundle、全仓及 integration typecheck、零 warning ESLint、实际 Prettier 检查均通过,四组回归重新通过 569/569,lint helper 16/16、freshness 原生测试 9/9、实际新提交 ancestry 验证 25/25。完整 merge 的原生 hook 虽返回 0,但应用阶段对 main 已有的被忽略目录内 E2E 文件报错,不能称完整 hook 通过;提交树与 hook 前索引完全一致,PR 七文件的实际 lint-staged 配置另行通过。新 head 两个 CI run 仍为 action_required,需要维护者批准,未宣称 CI 通过或追加 review 请求。

@github-actions github-actions Bot added the review/self-reported The linked issue was opened by the PR author (self-reported) label Oct 3, 2026
@wenshao

wenshao commented Oct 6, 2026

Copy link
Copy Markdown
Collaborator

Verification verdict: ✅ merge-ready — 805/805 scripted assertions passed

Verified head: fd96930eabb0e9c029a028bd830f6dc1c8038c96 (matches the PR snapshot). Control: merge-base eb0b79c5b87d781cddc65c28e70955404eb928d3 (the issue's reproduction commit; GitHub's recorded baseRefOid 2c591ecc is the main tip at sync, 4 unrelated commits ahead — the merge-base is the pure control for this PR's 3 commits).

中文摘要(点击展开)

结论:可以合并(merge-ready),805/805 条脚本断言全部通过,未发现阻塞性问题。

  • A/B 核心结论:在 issue Markdown streaming splitter treats inline fence markers as code blocks #13309 的原始输入上,base 把内联的 `~~~` 误判为代码围栏(getEnclosingFenceInfo 返回 {lang:""},切分插入合成围栏);head 返回 null 且两段严格等于原始子串。内联 ``` ``` ```、行内代码 spans、info 字符串含同字符标记(~~~ ~~~x`)、info 含反引号等同类形状在 base 上全部复现误判、在 head 上全部正确(见证据图 01、02)。
  • 行为保持:40 个真围栏对照格(反引号/波浪号、4+ 长分隔符、跨类型嵌套、缩进、CRLF、EOF 未闭合、空 info 等)在两臂逐字节一致;另有 6 个绝对预期断言钉死对照格本身的正确性。
  • 差分模糊测试:400 篇种子文档 × 约 10 个切分点 = 4091 格,base dist vs head dist vs 独立实现的行扫描预言机三方对比:0 个意外分歧、0 个预言机分歧、0 个结构不变量失败。
  • 定向测试:head 上 4 个相关套件 569/569 通过(markdown-utilities 53、MarkdownDisplay 190、use-llm-stream 289、pending-rendered-height 37),与 PR 正文的 569 一致。
  • 非 vacuous 证明:把 head 测试文件原样(仅改导入路径)放到 base 源码上跑,恰好 11 个新断言失败、42 个旧断言全绿——新测试确实钉住了修复,旧测试确实钉住了行为保持。
  • 性能:40k 空格 + 行尾反引号的敌意行上,渲染器正则 CODE_FENCE_RE 单次执行需 2134.9ms(超线性),head 的前置过滤器将其完全跳过(0.044ms);1000 个闭合块场景 head 4.1ms vs base 324.6ms,输出一致。
  • 未覆盖:live 交互式流式 TUI、全仓单测、全仓 typecheck/lint、Windows;详见英文正文 Not covered。

Central claim and A/B proof

Claim: the streaming Markdown splitter (used by use-llm-stream.ts to commit <Static> chunks) must recognize code fences only by the renderer's line-matching rules; inline backtick/tilde markers stay prose, while genuine fenced blocks keep close/reopen and line numbering.

The change replaces indexOf-anywhere fence discovery with a line-anchored scan validated by the renderer's own CODE_FENCE_RE (imported from pending-rendered-height.js, itself untouched by this PR), plus a scan-once rewrite of findLastSafeSplitPoint's closed-block tracking. The file is also renamed to markdown-utilities.ts (kebab-case) and dropped from the legacy-filename allowlist; all 5 importers verified updated, zero stale references at head.

A/B cells (oracle = exact strings / info objects, both arms on the built dist/ output)

Scenario base eb0b79c head fd96930 Verdict
Issue #13309: Use `~~~` as the fence marker. split before More {lang:"\"}` + synthetic fences inserted into prose null; chunks are exactly the original substrings flipped: broken → fixed
Inline ``` / ~~~ unwrapped mid-line (2 siblings) false fence, synthetic close/reopen prose, exact substring split flipped
The `cat```dog` ran. (code span mid-line) false fence with lang:"dog\"` prose flipped
~~~ ~~~x / ~~~ ~~~~~x (same-char marker in info string) block falsely closed by the info string {lang:"~~~x"} / {lang:"~~~~~x"} flipped (opposite direction)
```tsinvalid /~~~tsinvalid (backtick in info string) accepted as fence rejected as fence (CommonMark) flipped
Genuine controls: backtick, tilde, 4-run, cross-type nesting, 2-space indent, CRLF, unclosed-at-EOF, empty info, language-less reopen, boundary splits — byte-identical to base on all 40 cells preserved
findLastSafeSplitPoint semantics (double-newline preference, cap fallbacks, 1000-block doc, oversized leading block) — identical outputs on all cells preserved

Evidence: 01-ab-issue-repro.png (the headline flip), 02-adjudication-matrix.png (113 assertions).

A/B: issue #13309 inline fence marker — base vs head

Adjudication matrix: 113 scripted assertions

Differential fuzz (second oracle)

400 seeded documents (inline markers, both fence chars, run lengths 3–6, indents 0–4 spaces, hostile info strings incl. backticks/tildes, CRLF variants, CJK prose) × ~10 split points each = 4091 comparisons: base dist vs head dist vs an independently written line-scanner oracle implementing the renderer contract.

  • unexpectedDivergences: 0 — on documents containing only line-initial valid fences, base and head never disagree.
  • oracleDisagreements: 0 — head matches the independent oracle at every one of the 4091 points.
  • invFailures: 0 — every head split is either an exact substring split (no fence) or has byte-exact synthetic close/reopen structure (round-trips to the original).
  • expectedDivergences: 2217 — all inside documents carrying a mid-line marker or info-string hazard, i.e. exactly the bug class being fixed.

Evidence: 03-fuzz-differential.png. Harness: fuzz.mjs (seed 13331, reproducible).

Differential fuzz: 4091 cells, 0 unexpected divergence

Focused suites and vacuity

  • Head, 4 suites touching the changed surface: 569/569 passed (markdown-utilities 53, MarkdownDisplay 190, use-llm-stream 289, pending-rendered-height 37) — matches the PR's own cloud count. Evidence: 04-vitest-head-suites.png.

Head: 3 changed suites, 532/532 green (pending-rendered-height 37/37 run separately)

  • Vacuity / load-bearing proof of the new tests: the head test file was copied onto the base source (only the import path rewritten to the old filename). Result: exactly the 11 new assertions failed, all 42 pre-existing assertions stayed green — the 11 being the two inline-marker tests, two same-char-info tests, two backtick-info rejections, two indented-fence recognitions (poisoned on base by the inline marker in their fixture's intro line), and the three scan-count spy bounds (base's indexOf mechanism never touches the regex). No unrelated failure, so the suite pins both the fix and the preservation. Evidence: 05-vacuity-head-tests-on-base.png.

Vacuity: head tests vs base source — exactly the 11 new assertions fail

  • Level-confound control: base probed at source level AND at built-dist level: 66/66 scenario cells identical, so the source-level base cells used early in the round equal the shipped artifact.

Performance

Hostile line ``` + N spaces + trailing backtick (the shape that is quadratic for the renderer regex), splitter with cap 16384, min of 3 runs:

N head splitter base splitter raw CODE_FENCE_RE exec
2,000 0.001 ms 0.001 ms 5.4 ms
5,000 0.001 ms 0.001 ms 33.6 ms
20,000 0.044 ms 0.005 ms 533.8 ms
40,000 0.044 ms 0.008 ms 2,134.9 ms

1000 closed fenced blocks with the cap past the end: head 4.1 ms vs base 324.6 ms, outputs identical. The PR's absolute numbers differ from mine (arm64 Node 24 vs this x86_64 Catalina Node 22 host) but the superlinear regex curve and the prefix filter's avoidance are reproduced — corroborated, with the regex cost measured directly on this host.

Evidence: 06-perf-ladder.png.

Perf ladder: prefix filter avoids the quadratic renderer regex

Reviewer Test Plan walk-through

Every step of the PR's own plan was executed: split before More on the issue example (head: null + exact substrings ✓), genuine backtick/tilde blocks (close/reopen with original language and continuation line ✓ — start-line=2 after line1), indented and longer fences (✓), info strings containing backticks (rejected ✓). No step was found structurally unreachable.

Findings

No blocking findings. Informational observations (not merge conditions):

  1. A split inside an indented fence re-opens the tail fence without the original indentation ( ```ts reopens as ```ts). This is unchanged from base (both arms byte-identical) and pinned by the PR's own new test — cosmetic, pre-existing.
  2. The if (!match) continue fallback after the backtick pre-filter in findNextFence appears unreachable: no line was found that passes the pre-filter yet fails CODE_FENCE_RE. Harmless redundant defense; also serves as the guard if the pre-filter and regex ever drift.
  3. The splitter now follows the renderer's ^ * (unlimited leading spaces), wider than CommonMark's 0–3 spaces — a deliberate alignment with the renderer's pre-existing contract (the regex is untouched by this PR), so the splitter and the display can no longer disagree, which was the issue's root complaint.

Not covered

  • Live interactive streaming TUI with a real model backend (the author also scoped this out; the streaming caller is covered by the use-llm-stream suite and the rendering of split output by the MarkdownDisplay suite).
  • Full repository unit-test suite — only the 4 suites on the changed surface were run. The rename is fully accounted for: zero remaining markdownUtilities references at head.
  • Repo-wide typecheck/lint as separate gates — both arms' full npm run build (which compiles every workspace package incl. cli's tsc) exited 0.
  • Windows runtime (this host is macOS 10.15.7 x86_64).
  • GitHub Actions CI state (the PR's action_required lanes) was not evaluated; this report is local behavioral evidence only.

Methodology

Local maintainer round on macOS 10.15.7 x86_64, Node v22.23.3, pnpm 11.24.0. Two git worktrees at the exact OIDs above; dependencies installed once at head (corepack pnpm install --frozen-lockfile) and APFS-cloned into base (PR touches no manifest/lockfile); internal @qwen-code/* symlinks realpath-verified to resolve inside each own tree, so neither arm can load the other's code. Both trees built clean (npm run build, exit 0). Harnesses (probe.mjs, adjudicate.mjs, fuzz.mjs, demo-ab.mjs) are mock-free, drive the compiled dist/ output under plain node, and live in the artifact dir alongside raw probe JSON. Vitest 3.2.7 ran via an esbuild-wasm dispatcher (ESBUILD_BINARY_PATH) because this host predates esbuild's macOS 12 binary floor; the installed esbuild is 0.25.12 and the wasm route matched it. Artifact dir: tmp/pr13331-verify-20261007-001302/.

Merge QwenLM/qwen-code main at ac497ae
so the existing Markdown fence fix is checked under the current lint gate.
Preserve the original PR changes and the upstream empty-file-list guards.

@qwen-code-review-bot qwen-code-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed — no blockers. Suggestions are inline.

中文说明

已审查——无阻断问题。 建议见行内评论。

— qwen3.8-max via Qwen Code /review (v0.25.0)

while (lineStart < content.length) {
const newlineIndex = content.indexOf('\n', lineStart);
const lineEnd = newlineIndex === -1 ? content.length : newlineIndex;
// This pre-filter must remain a superset of CODE_FENCE_RE.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Suggestion] R1-1: findNextFence now decides "is this a fence line?" twice — once with the hand-rolled pre-filter under this comment (skip space-only indentation, require three or more backticks or tildes, advance the whole run, reject a backtick after it), and once with the shared CODE_FENCE_RE it delegates to. The invariant that the pre-filter stays a superset of that regex is carried by this comment alone: nothing in the suite compares the two recognizers' verdicts. markdown-utilities.test.ts:8 does import CODE_FENCE_RE, but its only three uses are vi.spyOn(CODE_FENCE_RE, 'exec') at :105/:120/:135, which count calls rather than compare decisions; the rejects an opening fence with a backtick in its info string case asserts .toBeNull(), which the pre-filter satisfies whatever the regex says; and pending-rendered-height.test.ts has no fence-marker cases at all.

So if the regex is ever widened at pending-rendered-height.ts:40 for a renderer or height reason — the indent class becoming tab-tolerant so tab-indented fences render as code, or a tilde fence's info string being allowed to contain a backtick as CommonMark permits — then MarkdownDisplay.tsx:468 and fitPendingSlice start recognizing a fence this pre-filter still rejects, and no test fails. getEnclosingFenceInfo returns null for an index the renderer draws inside a code block, use-llm-stream.ts:2026-2028 keeps that block pending, and when a capped hard split does land inside it splitFencedMarkdown takes its plain-substring early return: the committed head renders as an unterminated fence and the tail as unhighlighted prose with no gutter. That is the bug class this PR fixes, arriving silently from the other direction.

To be explicit about the size of the risk, this is latent rather than live. Parity is exact today — a shaped corpus of 54 cases (27 lines across LF and CRLF, tab / > / - indents, a backtick in the info string for both fence characters, trailing spaces, a mid-line marker) and a random sweep of 2102 documents over 3324 probe indices both came back with 0 divergences. The verification note already on this PR also observed that the equivalence is comment-enforced rather than backed by a shared matcher; what is new here is the measurement that no test detects the drift, plus the corrected fix witness at the end.

Witness:

mutant MA — CODE_FENCE_RE widened to accept a tab-indented fence,
applied at vitest transform time (worktree files never edited)

  markdown-utilities + pending-rendered-height + MarkdownDisplay
  Test Files  3 passed (3)
       Tests  280 passed (280)          <- nothing goes red

same tree, proposed parity test injected (expectation derived from the
imported CODE_FENCE_RE binding, not from a copy of the pattern):
  intact :  Tests  54 passed (54)
  MA     :  Tests  1 failed | 53 passed
            + [ "\"\t```ts\" splitter=false regex=true" ]

A table-driven parity case in the new fence recognition block of packages/cli/src/ui/utils/markdown-utilities.test.ts would close this with no production change: for a corpus of fence-shaped lines — a tab-indented fence, a blockquote-prefixed one, delimiter runs of 3/4/6, a backtick in the info string for both fence characters, a mid-line marker, trailing spaces, and a CRLF variant — assert that getEnclosingFenceInfo(line + '\nx\n', idxOf('x')) !== null iff CODE_FENCE_RE.test(line).

The corpus has to be judged against the binding already imported at markdown-utilities.test.ts:8, not against a literal copy of the pattern (export const CODE_FENCE_RE = /^ *(`{3,}|~{3,}) *([^`]*)$/;, packages/cli/src/ui/utils/pending-rendered-height.ts:40): a copied pattern just restates the pre-filter and can then never disagree with the renderer, which is exactly the drift this test exists to catch. The same object is read by fitPendingSlice (pending-rendered-height.ts:172) and twice by the renderer (MarkdownDisplay.tsx:77 and :181).

The new case should go red when CODE_FENCE_RE is widened to accept a tab-indented fence while the pre-filter still skips only spaces — please apply that mutation and confirm the tab row fails. Note that the check is one-sided rather than two-sided: deleting the backtick guard at :69-72 leaves the parity case green, because that guard is exactly redundant with today's regex (its info-string group cannot contain a backtick, so no line exists that the guard rejects and the regex accepts), and that mutation is already pinned as a perf assertion by the three skips the fence regex for a backtick after the full %s delimiter exec-count tests, which go from ~1 ms to 142-146 ms each without it.

中文说明

findNextFence 现在会两次判断"这一行是不是围栏行"——一次是这条注释下方的手写前置过滤(跳过纯空格缩进、要求三个以上反引号或波浪号、走完整个分隔符串、拒绝串后出现反引号),另一次是它委托的共享 CODE_FENCE_RE。"前置过滤必须保持为该正则的超集"这一不变量只由这条注释承担:测试套件中没有任何用例比较两个识别器的判定结果。markdown-utilities.test.ts:8 确实导入了 CODE_FENCE_RE,但它唯一的三处使用是 :105/:120/:135 的 vi.spyOn(CODE_FENCE_RE, 'exec'),统计的是调用次数而非判定结果;rejects an opening fence with a backtick in its info string 用例断言 .toBeNull(),而无论正则如何规定,前置过滤都能满足它;pending-rendered-height.test.ts 则完全没有围栏标记相关用例。

因此,如果将来出于渲染或行高计算的需要放宽 pending-rendered-height.ts:40 处的正则——例如缩进字符类改为兼容制表符,使制表符缩进的围栏被渲染为代码块;或按 CommonMark 允许波浪号围栏的信息串包含反引号——那么 MarkdownDisplay.tsx:468 与 fitPendingSlice 就会开始识别一个此前置过滤仍然拒绝的围栏,而没有任何测试失败。此时 getEnclosingFenceInfo 会对渲染器画在代码块内部的索引返回 null,use-llm-stream.ts:2026-2028 让该块持续挂起,而一旦带长度上限的硬切分落在块内,splitFencedMarkdown 就会走它的纯子串提前返回:已提交的前半段渲染成未闭合的围栏,后半段渲染成没有高亮、没有行号的普通正文。这正是本 PR 要修的那类缺陷,只是从相反方向悄悄回来。

需要明确风险量级:这是潜在问题而非现存问题。目前两者完全一致——54 个构造用例(27 行文本分别覆盖 LF 与 CRLF、制表符 / > / - 缩进、两种围栏字符的信息串中带反引号、行尾空格、行中标记)以及 2102 篇文档、3324 个探测下标的随机扫描,都得到 0 处分歧。本 PR 已有的验证说明也指出这种等价性只靠注释维持、没有共享匹配器支撑;此处新增的是"没有测试能发现该漂移"这一实测结论,以及文末修正过的修复验收条件。

证据(witness)为上方代码块中的程序输出,两种语言下完全相同,不再重复。

在 packages/cli/src/ui/utils/markdown-utilities.test.ts 新增的 fence recognition 分组里加一个表驱动的一致性用例即可闭环,且无需改动生产代码:对一组围栏形状的行——制表符缩进的围栏、带引用前缀的围栏、3/4/6 长度的分隔符串、两种围栏字符的信息串中带反引号、行中标记、行尾空格,以及一个 CRLF 变体——断言 getEnclosingFenceInfo(line + '\nx\n', idxOf('x')) !== null 当且仅当 CODE_FENCE_RE.test(line)。

该用例必须以 markdown-utilities.test.ts:8 已导入的绑定为判定依据,而不是照抄一份正则字面量(export const CODE_FENCE_RE = /^ *(`{3,}|~{3,}) *([^`]*)$/;,见 packages/cli/src/ui/utils/pending-rendered-height.ts:40):照抄的写法只是把前置过滤重述一遍,永远不可能与渲染器产生分歧,而那恰恰是这个测试要防的漂移。同一个对象还被 fitPendingSlice(pending-rendered-height.ts:172)以及渲染器的两处(MarkdownDisplay.tsx:77、:181)读取。

新用例应当在"放宽 CODE_FENCE_RE 使其接受制表符缩进的围栏、而前置过滤仍只跳过空格"时变红——请实际施加该变异并确认制表符那一行失败。注意这个检查是单向而非双向的:删除 :69-72 的反引号保护后,一致性用例仍然是绿的,因为该保护与当前正则完全冗余(正则的信息串分组不可能包含反引号,所以不存在"保护拒绝但正则接受"的行),而且该变异已被三个 skips the fence regex for a backtick after the full %s delimiter 调用次数用例以性能断言的形式钉住——去掉保护后它们各自从约 1 ms 变为 142-146 ms。

— qwen3.8-max via Qwen Code /review (v0.25.0)

@wenshao

wenshao commented Oct 8, 2026

Copy link
Copy Markdown
Collaborator

@qwen-code /triage

@qwen-code-review-bot

qwen-code-review-bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

Sandboxed verification: ✅ passed — merge-ready (agent verdict) - workflow run

Ran the PR in an isolated, token-free container: A/B against the base build, mock-free harness assertions, targeted gates. Advisory evidence for human reviewers — not a review, an approval, or a CI check.

Scripted assertions: 3262 passed · 0 failed · 3262 total

Flakiness gate: ✅ 3 changed test file(s) x 5 identical rounds, no divergence

中文 — 判定:✅ 通过 · 可合入(agent 判定)

沙箱验证在隔离、无凭证的容器中执行了该 PR 的代码(与 base 构建 A/B 对照、无 mock harness 断言、定向门禁)。仅作为评审证据,不构成评审、批准或 CI 检查。

脚本断言:3262 通过 · 0 失败 · 3262 总计

抖动门:✅ 3 changed test file(s) x 5 identical rounds, no divergence

Verification report

PR #13331 — deep verification

Verdict: merge-ready — 3262 / 3262 scripted assertions passed, 0 unexpected failures.
Verified head: 5a4e3a1a4ac2ff5e0301cc203c6f6da3dc84b7e7 (git rev-parse HEAD^2).
Base (control): 8003d280420da32ddff4f9b0ef9a7b0aff42a8bc (HEAD^1). Effective diff: git diff HEAD^1..HEAD = 7 files.
Gates run separately from the tally: 4 affected suites 569/569, packages/cli tsc --noEmit clean, ESLint clean, Prettier clean.
Findings lists four non-blocking observations (one pre-existing perf exposure the PR only half-closes, three about test robustness and description completeness) plus one secondary claim verified clean. None is a defect in this PR's code and none blocks merge.

中文摘要

结论:merge-ready —— 3262 / 3262 项脚本断言通过,0 项非预期失败。已验证 head 为 5a4e3a1a,对照基线为 8003d28(HEAD^1)。

A/B 结论:以「渲染器自身规则」为裁判(从 MarkdownDisplay.tsx 的 split(/\r?\n/) + CODE_FENCE_RE + 同一套开合规则逐字构造),在 46 个人工用例、4121 份随机/真实文档(含带 ANSI 颜色的 git diff 字节)、共 645,417 个字符下标与 37,089 次 cap 扫描上:

  • 基线(修复前)与裁判不一致 263,420 次(getEnclosingFenceInfo)与 10,184 次(findLastSafeSplitPoint);
  • head(修复后)不一致 0 次;仓库已构建产物 packages/cli/dist 同样 0 次,且与 head 编译臂逐位一致;
  • 基线向普通正文注入合成围栏 90,995 次,head 0 次;基线把真实切分点落在代码块内部 12 次,head 0 次;
  • 端到端(真实 use-llm-stream 提交循环 → 真实 MarkdownDisplay 渲染帧):head 12/12,基线 4 failed / 8 passed,失败的四条正是 Markdown streaming splitter treats inline fence markers as code blocks #13309 的可见症状(正文被改写字节、携带内部 qwen-code:start-line 指令、凭空多出裸围栏行、普通正文渲染出代码块行号槽);真实代码块的 5 条对照断言两臂全过,说明修复没有回退原有能力。
  • 性能侧同样成立:闭合代码块数 50→3200 时基线 0.74→4534.89 ms(增长 x6110,二次),head 0.03→1.01 ms(x32.3,线性),即单调 closedBlocks 游标带来的实测收益。

详见下方 Central claim + A/B 与 Perf A/B 两表;证据截图为 01-ab-differential-totals.png、02-fuzz-corpus-totals.png、03-e2e-render-head-vs-base.png、04-regex-exposure-ladder.png、05-mutation-matrix.png。

变异与空测试检查:9 个单点变异全部被击杀,0 存活;同文件内的正向对照 M8 使 6 条测试变红并报出期望值差异。把核心修复整体回退(M1)会让 fence recognition 组 8 条行为断言变红,其中 expected { lang: '`', startLine: 1 } to be null 与 PR 描述里自述的「修复前」取值逐字一致 —— 该证据被独立复现。

Findings(均非阻塞):① 同一提交路径上 fitPendingSlice 仍无前置过滤地调用二次回溯的 CODE_FENCE_RE,单行 4 万空格实测 536.6 ms(既有问题,非本 PR 引入,PR 只披露了渲染器一侧);② 「前置过滤必须是 CODE_FENCE_RE 的超集」目前只有注释保证,穷举 488,280 行证明两者今日完全等价,故共享正则实际不决定任何结果,但无测试钉住超集方向;③ 去掉 delimiterStart >= from 不会触发断言失败,而是让扫描不终止、vitest 以 4 GB 堆 OOM 崩溃(约 49 s),该守卫在 CI 中只有崩溃保护;④ 与渲染器对齐继承了两个既有 CommonMark 偏差(tilde 信息串含反引号、缩进 ≥4 空格的围栏),PR 的风险段落披露了「跟随渲染器」但未点名这两种形状。

未覆盖范围:4 个提交在本 depth-2 检出下只有 head 可达(git rev-list --count HEAD^1..HEAD^2 返回 1,元数据为 4),故只做聚合差异验证,无逐提交归因;baseRefOid ac497aee 本地不存在,无法测量基线漂移;issue #13309 原文无法获取(容器内无 GitHub token),复现依据 PR 描述与该 issue 形状的固定用例;未做真实交互式 TUI 流式验证、未跑全仓测试套件、未在 Windows 上验证;PR 自述的 2,946,372 次差分比较未复现(本轮以 645,417 下标 + 552,645 切分探针 + 37,089 次 cap 扫描、共 1,235,151 次比较替代,结论一致)。


Central claim + A/B

Central claim. The streaming Markdown splitter (findNextFence / getEnclosingFence / findLastSafeSplitPoint / splitFencedMarkdown in packages/cli/src/ui/utils/markdown-utilities.ts) must recognise a code fence only where the renderer recognises one, so an inline ``` or ~~~ mention in ordinary prose stops opening a false block and stops receiving synthetic fences — while genuine fenced blocks keep their close/re-open behaviour and continuous gutter numbering.

Secondary claims. (S1) The perf half — one fence scan plus a monotone closedBlocks walk replacing a per-candidate rescan — preserves every split decision. (S2) The markdownUtilities.ts → markdown-utilities.ts rename is complete.

Oracle. CODE_FENCE_RE is the renderer's own rule, so the strongest oracle is that rule, not hand-written expectations. I built a reference scanner directly from MarkdownDisplay.tsx:151 (text.split(/\r?\n/)), :84/:253/:267/:416/:468 (line.match(CODE_FENCE_RE)), and the identical open/close condition (same char && length >= open.length), lifted the regex verbatim out of pending-rendered-height.ts:40, and asserted it byte-identical at HEAD^1 and HEAD. Both arms are scored against it.

Control cleanliness. The PR touches no manifest and no lockfile (git diff --name-only HEAD^1..HEAD ∩ package.json|pnpm-lock.yaml = ∅), so the dependency tree is not part of the change. The base arm is a standalone esbuild bundle of markdownUtilities.ts @​ HEAD^1 plus a regex shim extracted from pending-rendered-height.ts @​ HEAD^1 and diffed against head's — no node_modules, so no workspace-symlink confound is possible. pending-rendered-height.ts is unchanged by the PR (empty git diff --stat), so it is not part of the control's delta either. The head arm was additionally cross-checked against the shipped packages/cli/dist/src/ui/utils/markdown-utilities.js on every probe: 0 mismatches.

# Cell Oracle base 8003d28 head 5a4e3a1
1 46 curated fixtures × 2,619 char indices reference getEnclosingFenceInfo 619 wrong 0 wrong
2 46 fixtures × cap sweep [undef,0,1,2,5,20,40,n/3,n/2,n-1,n,n+10,16384] reference findLastSafeSplitPoint 85 wrong 0 wrong
3 4,121 docs (4,000 synthesized + 121 real repo files incl. ANSI git diff --color=always bytes) × 645,417 indices reference getEnclosingFenceInfo 263,420 wrong 0 wrong
4 same corpus, 37,089 cap sweeps reference findLastSafeSplitPoint 10,184 wrong 0 wrong
4b same corpus, 552,645 splitFencedMarkdown probes byte-equality with the plain substring split where the reference says "not in a block" 90,995 violations 0 violations
5 synthetic fence injected where the reference says "not in a code block" byte-exact plain substring split 90,995 0
6 real split point landing strictly inside a reference code block reference intervals 12 0
7 before + after round-trip outside code blocks byte equality with source — 0 broken
8 head esbuild arm vs shipped packages/cli/dist identical outputs on every probe — 0 mismatches
9 E2E: real use-llm-stream commit loop → real <MarkdownDisplay> frames, prose doc 12 assertions 4 failed / 8 passed 12 / 12
10 E2E control: genuine tall ```python block spanning commits 5 assertions 5 / 5 5 / 5

Cells 1–8 are witnessed by 01-ab-differential-totals.png and 02-fuzz-corpus-totals.png; cells 9–10 by 03-e2e-render-head-vs-base.png.

Cell 9 is the user-visible symptom, not a string comparison. The harness replicates use-llm-stream.ts:1912-1944 verbatim (while (buf.length > 16384), the safeSplitPoint fallback, splitFencedMarkdown, chunk accumulation) and renders every committed chunk through the real component. Only the splitter build differs (VERIFY_ARM=head|base). Base fails exactly these four, and passes the other eight:

× prose doc: no chunk text is rewritten (byte-exact round trip)
× prose doc: no chunk carries the internal start-line directive
× prose doc: no chunk gains a bare fence line the source never had
× prose doc: no rendered frame shows a code gutter for ordinary prose

What base injected into a document that contains no code block:

"~~~"                                      <- a synthetic closing fence
"~~~ as a marker. qwen-code:start-line=393" <- a synthetic re-opened fence

and the ordinary prose after line 392 rendered as a numbered code block. Head renders it as prose and the chunks concatenate back to the source byte-for-byte.

Sibling sweep. The reported input is one door into a room with several, so 24 adjacent shapes were each driven through the fixed build at every character index (cell 1; all head wrong = 0). Inline marker mid-sentence, at line end, and at line start with trailing text; 1-, 2- and 4-backtick code spans; blockquote- and list-item-prefixed mentions; a tab-indented fence; CR-only line endings, CRLF line endings, and a CRLF genuine fence; a backtick fence and a tilde fence whose info string contains a backtick; a tilde fence with a backtick later on the line; a backtick fence with tilde info and a tilde fence with tilde info; genuine fences indented 3, 4 and 10 spaces; a closing fence carrying trailing text; a 4-backtick run containing a 3-backtick line; and ```/~~~ cross-nested in both orders. Base was wrong on 12 of these 24 shapes and already right on the other 12; head is right on all 24. The 17 genuine-fence control fixtures are the stronger half of that statement: base was wrong on 0 of them, so the fix changed nothing about real code blocks — the entire behavioural delta sits on the malformed/inline shapes. (The 3 mixed documents, where an inline mention precedes a genuine block, are wrong on base and right on head; the 40-consecutive-closed-blocks fixture is a control and a perf cell.)

Boundary probing. Every index of every fixture was probed, not just the reported split point, so the delimiterStart >= from / fence.index >= indexToTest boundary semantics are covered exhaustively rather than by sample. In particular the exact-fence-start index (where getEnclosingFence breaks) agrees with base on every probe — the monotone closedBlocks walk did not shift a boundary.

Perf A/B (secondary claim S1)

05-timing.log. The monotone walk is load-bearing well beyond what the description claims:

closed blocks base (ms) head (ms) speedup
50 0.74 0.03 23.8×
200 7.40 0.11 68.4×
800 136.43 0.45 302.2×
3200 4534.89 1.01 4490.7×

Growth over K ×64: base ×6110 (quadratic — it re-scanned every fence for every rejected newline), head ×32.3 (linear). Three streaming-loop simulations of the production commit pattern (prose-with-inline-fence-mentions, many-real-code-blocks, one-huge-code-block) produced identical commit counts on both arms.

Corrections to the PR description

Labelled as corrections to the description, not requests to change code.

  1. "The prefix filter is documented as a superset of that regex." It is not merely a superset today — it is exactly equal to CODE_FENCE_RE's accept-set. An exhaustive census of all 488,280 strings up to length 8 over the alphabet {space, tab, backtick, tilde, 'a'} found 0 disagreements between the full head arm and an arm with the CODE_FENCE_RE.exec call deleted (08-superset-census.log; 4,235 of those lines are accepted as fences, so the accept-set is not vacuously empty). The census has its own positive control: base accepts 740 lines that head and the renderer reject — " a```", " `~~~", " ~~~`", " \t```" among them — which proves the probe discriminates between arms rather than reporting agreement it cannot detect. Mutant M9 confirms it behaviourally: identical output on all 645,417 indices, 552,645 split probes and 37,089 cap sweeps. The shared regex therefore decides nothing at present; it is retained purely as a drift guard, and the suite pins it with a spy (expected 0 to be greater than 0), not with behaviour. "Valid fence lines still use the original shared regex" is literally true — the consequence is nil.
  2. "Padded 10k/40k-space rejected-line splitter probes measured about 84/1363 ms." The law reproduces exactly, the constant does not. Removing the pre-filter and re-measuring the same shape gives 34.7 ms / 549.9 ms at 10k/40k — ×15.9 for a ×4 increase in N, i.e. quadratic, matching the reported ×16.2 — while the shipped pre-filter holds the same two rungs at 0.007 ms / 0.011 ms and the harness's own growth measure across the top two rungs is ×1.04, i.e. flat. So the reported constants are ~2.4× larger than mine (an environment difference) while the law and the conclusion are the same, and the guard's value (52,167× at N=40k) is confirmed rather than contradicted.

Everything else I could check reproduced: 569/569 across the four suites, 53/53 in the helper suite, and the stated Before value { lang: "`", startLine: 1 } appears verbatim as a mutation-induced test failure.

Vacuity check and mutation matrix

04-mutation-matrix.log, witnessed by 05-mutation-matrix.png. Unmutated control green (53 tests collected). 9 mutants, 9 killed, 0 survived.

# Mutation of markdown-utilities.ts Result First failing assertion
M1 revert findNextFence to base's indexOf implementation (the central fix) KILLED — 11 failed / 42 passed 8 behavioural: expected { lang: '`', startLine: 1 } to be null; expected { lang: 'as', startLine: 1 } to be null; expected { lang: 'ts\invalid', … } to be null(×2);expected null to deeply equal { lang: 'ts', startLine: 1 }(×2);expected null to deeply equal { lang: '~~~x'/'~~~~~x', … }` (×2) + 3 spy-count
M2 drop delimiterStart >= from KILLED by crash, not by assertion FATAL ERROR: Ineffective mark-compacts near heap limit after ~49 s at ~4 GB — see Finding 3
M3 drop the backtick-in-rest-of-line pre-filter KILLED — 3 failed / 50 passed expected 1 to be +0 // Object.is equality (spy: the regex now runs)
M4 drop the blockIndex re-arm before the single-newline fallback KILLED — 1 failed expected 21 to be 14
M5 isInsideClosedBlock → always false KILLED — 7 failed expected 17 to be 36
M6 remove the onClosed callback KILLED — 7 failed expected 17 to be 36
M7 off-by-one in the monotone walk (&lt;= start → &lt; start) KILLED — 1 failed expected 22 to be 14
M8 positive control, same file: parseCodeFenceInfo always returns startLine: 1 KILLED — 6 failed expected { lang: 'python', startLine: 1 } to deeply equal { lang: 'python', startLine: 4 }
M9 derive the delimiter from the local run scan instead of CODE_FENCE_RE.exec KILLED — 3 failed expected 0 to be greater than 0 (spy only — behaviour-identical, see Correction 1)

M1 is the vacuity check on the PR's central new test group and it is not vacuous: the kill is behavioural, quoting expected-versus-actual values, not a broken import or fixture. M8 is the required positive control and it is landed in the mutated file, and the chosen command (vitest run src/ui/utils/markdown-utilities.test.ts) demonstrably collects it.

M5 and M6 fail identically (7 tests, same first assertion) — layered guards hiding each other. That is expected here: onClosed is the only producer of closedBlocks, so removing either one removes the same capability. Neither is a survivor.

M9 is adjudicated by running its build, not by reading it: classified redundant defence by design (behaviour-identical over 1.2 M probes), not a coverage gap and not dead code in the pejorative sense — it exists so the splitter follows the renderer's single source of truth if CODE_FENCE_RE ever changes.

Findings

All non-blocking. None is a defect in this PR's code.

1. The same quadratic regex is still unguarded on the same streaming commit path (pre-existing, partially disclosed) — Suggestion

CODE_FENCE_RE = /^ *({3,}|~{3,}) ([^]), so on a line the regex must ultimately reject it backtracks quadratically. Measured on the shipped regex, one call per rung (06-regex-exposure.log, 04-regex-exposure-ladder.png`):

N spaces CODE_FENCE_RE.exec(line) splitter with the pre-filter removed splitter as shipped real fitPendingSlice([line])
2,000 1.479 ms 1.536 ms 0.019 ms 1.534 ms
5,000 8.802 ms 8.816 ms 0.009 ms 8.827 ms
10,000 34.666 ms 34.684 ms 0.007 ms 34.672 ms
20,000 136.644 ms 136.384 ms 0.010 ms 136.471 ms
40,000 536.899 ms 549.864 ms 0.011 ms 536.580 ms

Growth ×3.93 for N ×2.00 — exactly quadratic. The PR's pre-filter makes the splitter immune (×1.04, flat, ≈50,000× faster at N=40k). That part is a genuine win and it is proven.

The residual: fitPendingSlice (pending-rendered-height.ts:172) calls CODE_FENCE_RE.exec(line) on every line with no pre-filter, and it is invoked at use-llm-stream.ts:1981 inside handleContentEvent — the same callback that calls findLastSafeSplitPoint at :1913 and :2034. So one hostile line still costs 536.6 ms on the very commit this PR hardened, and MarkdownDisplay (:84, :253, :267, :416, :468) has the same exposure per rendered frame.

Bounded honestly. Not introduced by this PR — the regex and both consumers predate it, and the PR reduces total exposure. Provenance: the splitter's only inputs are newLlmMessageBuffer / newThoughtBuffer, i.e. streamed model text, so an outsider reaches this only second-hand (prompt injection through a file or page the agent reads). No exploit is demonstrated and none is claimed; the consequence is a stalled/janky TUI, not code execution or data loss. The PR body discloses "the renderer's existing regex cost remains outside this local fix" but does not mention fitPendingSlice, which sits on the splitter's own call path rather than the renderer's.

Reproduce:

node tmp/pr13331-verify-20261008-075026/regex-exposure.mjs

Follow-up, not a condition of this PR: hoist the pre-filter this PR already wrote into a shared isCodeFenceLine(line) helper next to CODE_FENCE_RE and call it at the other six sites, so one bounded check guards every consumer of the same regex. I deliberately do not propose a replacement regex here — the ambiguity is between two parts that both match a space ( * and [^]*`), and any rewrite has to be measured against the ladder above rather than eyeballed; a first attempt at one for this report was withdrawn for exactly that reason.

2. The "must remain a superset" invariant is enforced only by a comment — Suggestion

// This pre-filter must remain a superset of CODE_FENCE_RE.

The census shows the two accept-sets are equal over 488,280 exhaustively enumerated lines, and M9 shows deleting the regex changes nothing behaviourally. So the invariant is the only thing coupling the splitter to the renderer, and no test pins its direction. A future relaxation of CODE_FENCE_RE — for example allowing backticks in a tilde info string, which CommonMark permits — would make the renderer accept a fence the pre-filter still rejects, silently re-diverging splitter from renderer: precisely the bug class this PR closes, in the other direction. The existing spy tests would notice a call-count change but not the semantic split; the new MarkdownDisplay cross-render test covers ~~~md with an inner ``` line, not a tilde info string holding a backtick.

Cheap fix, in the spirit of the existing spy tests:

it('the pre-filter admits everything CODE_FENCE_RE admits', () => {
  const ALPHABET = [' ', '\t', '`', '~', 'a'];
  const walk = (line: string) => {
    if (line.length > 0 && CODE_FENCE_RE.test(line)) {
      expect(getEnclosingFenceInfo(`${line}\nX`, line.length + 1)).not.toBeNull();
    }
    if (line.length < 6) for (const c of ALPHABET) walk(line + c);
  };
  walk('');
});

That is the census harness reduced to a fixture; it runs in well under a second at length ≤ 6 and would go red on any relaxation of the shared regex. Reproduce the full census: node tmp/pr13331-verify-20261008-075026/superset-census.mjs.

3. The termination guard's only CI protection is an out-of-memory crash — Suggestion

delimiterStart >= from does two independent jobs, and the comment above it names neither. Besides honouring the from contract, it is what makes getEnclosingFence terminate: searchPos is advanced to fence.index + fence.length, and without the guard findNextFence re-reports the same fence from the start of its own line forever, pushing into closedBlocks until the heap dies.

Mutant M2 does not fail an assertion. It kills the vitest worker:

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory
[51718:0x9b23000] 49090 ms: Mark-Compact 4058.9 (4131.2) -> 4044.5 (4132.7) MB

~49 s and ~4 GB before the crash, surfacing as ERR_IPC_CHANNEL_CLOSED — i.e. as infrastructure failure rather than a named regression. Not a live defect: the guard is present and correct. But a future edit that drops it would present as a hung/OOM'd shard, not as a red test. The suite already uses bounded spy counts elsewhere (expect(scan.mock.calls.length).toBeLessThanOrEqual(4)); the same idiom on a small fenced document would pin termination cleanly, or a comment on the >= from line naming its termination role would cost nothing.

Reproduce: node tmp/pr13331-verify-20261008-075026/mutation-matrix.mjs and read logs/mutant-M2.log.

4. Two CommonMark deviations inherited from the renderer, neither named in the accepted-tradeoff list — Note

The Risk & Scope section discloses the tradeoff correctly ("streaming split boundaries now follow the existing renderer's fence pattern"). Enumerating the unnamed siblings of that mechanism, both measured in 08-superset-census.log:

line CODE_FENCE_RE (renderer) splitter (head) CommonMark
~~~ a`b false false valid opening fence — a tilde info string may contain backticks; only a backtick info string may not
····```ts (4 spaces) true true not a fence — it is an indented code block (^ {0,3} limit; CODE_FENCE_RE uses ^ *)

Splitter and renderer agree in both rows, which is the right call for this PR and keeps rendered output self-consistent. Both deviations are pre-existing in CODE_FENCE_RE, which this PR does not touch. Recording them only because an accepted-tradeoff list is a completeness claim: a reader who accepts "follow the renderer" is accepting these two shapes as well.

5. Rename is complete — verified, no action

Secondary claim S2 holds. Zero references to markdownUtilities survive anywhere in packages/, docs/, scripts/ or eslint.legacy-filenames.mjs; both old files are gone; no stale dist artifact under the old name; the allowlist entry was removed. I proved the filename gate is live rather than assuming a green exit means a pass — planting packages/cli/src/ui/utils/__verifyCamelCaseProbe.ts produced error The filename "__verifyCamelCaseProbe.ts" does not match the "KEBAB_CASE" pattern check-file/filename-naming-convention, and the probe was removed. The same liveness treatment was applied to ESLint (3 planted errors reported) and Prettier (planted formatting break reported) before citing their clean runs.

Not covered

  • Per-commit attribution. The checkout is depth 2. git rev-list --count HEAD^1..HEAD^2 returns 1 while $QWEN_VERIFY_CONTEXT lists 4 commits (fd0e42ea2, 4c6d57a44, fd96930ea, 5a4e3a1a4) — at a shallow boundary that command returns a plausible small number instead of erroring, so the gap is easy to miss. I verified the aggregate HEAD^1..HEAD diff only. The intermediate perf commit 4c6d57a44 and the guard commit fd96930ea were not individually exercised; my M3/M9 mutants reconstruct their effect but are not a substitute for the commits themselves.
  • Base drift. baseRefOid ac497aeed956981e817b4301837866730359a65f is not present locally, so I could not diff it against HEAD^1 8003d28 to check whether main touched any of the 7 files in between. HEAD^1 is the merge-ref's first parent, i.e. the base GitHub itself would merge into, so git diff HEAD^1..HEAD is the diff that lands — but a trial merge into current main was not possible and was not performed.
  • Issue Markdown streaming splitter treats inline fence markers as code blocks #13309's original text. No GitHub token in this container, and anonymous network calls are unreliable here. The reproduction is built from the PR description's rendering of the issue plus the fixture the PR's own test pins. I have the shape the issue reported, verified end-to-end through the real renderer; I do not have the issue's own words, so if it enumerated more cases than "an inline fence mention such as Use `~~~` as the fence marker.", those extra cases are unverified as a coverage specification.
  • Live interactive TUI streaming. No real model call and no interactive session were driven. Cell 9 replicates the commit loop's code exactly and renders through the real component, but it is not a terminal session; scrollback/<Static> interaction, ink's redraw path and real streaming cadence are not exercised. The PR's own Risk & Scope declares this out of scope too.
  • Windows. The PR marks it untested. My CRLF fixtures cover \r\n and lone-\r bytes through the splitter and the reference oracle (including the \r-in-infoString divergence between split(/\r?\n/) and slicing to \n, which I asserted never escapes into a re-opened fence), but nothing ran on Windows.
  • Full repository test suite. Only the four affected suites were run, by design. Repo-wide lint, repo-wide typecheck including integration-tests, npm run build, npm run bundle, and the integration/TUI-parity lanes were not run. The PR's CI lanes were action_required at the metadata snapshot and no CI-success claim is made or checked here.
  • The author's 2,946,372-comparison sweep. Not repeated (the body says it was not repeated for publication either). My corpus is different and smaller per-axis but broader in kind: 645,417 indices + 552,645 split probes + 37,089 cap sweeps = 1,235,151 comparisons, 0 head-vs-oracle differences, plus an exhaustive 488,280-line census. Same conclusion, independently reached.
  • Math-block precedence. Declared out of scope by the PR; $$ handling in MarkdownDisplay/countMarkdownSourceBlocks was not probed.
  • Non-interactive output paths. findLastSafeSplitPoint is called only from use-llm-stream.ts; I confirmed that by grep but did not exercise headless/--output-format rendering, which does not use the splitter.

Methodology

CI verify job, node:22-bookworm container, Node v22.23.3, 64 cores, no credentials. Working tree = refs/pull/13331/merge at depth 2; npm ci and npm run build had already completed at HEAD, so the shipped packages/cli/dist was available and was used as a third arm. The base arm was built by extracting markdownUtilities.ts from HEAD^1 and bundling it standalone with esbuild 0.25.12 together with a CODE_FENCE_RE shim lifted verbatim from pending-rendered-height.ts @​ HEAD^1 and diffed against head's copy (identical), so the control differs from head by the helper file and nothing else; the head arm was bundled the same way from git show HEAD: and separately proven byte-behaviour-identical to packages/cli/dist. No arm reaches node_modules, so no internal workspace symlink could pull head code into the base cell.

Five harnesses drove the code, all mock-free with respect to the unit under test: diff-harness.mjs (46 curated fixtures × every character index × a 13-value cap sweep, 3 arms, renderer-derived oracle), fuzz-harness.mjs (4,000 mulberry32-seeded documents over a 26-token fence alphabet, plus 121 real files drawn from git ls-files '*.md' and the packages/cli/packages/core sources, plus the ANSI-coloured bytes of git diff --color=always HEAD^1..HEAD; the oracle caches fence events and prefix-folds them so a 400 KB file is not O(indices × events)), superset-census.mjs (exhaustive enumeration, no sampling), timing-harness.mjs and regex-exposure.mjs (wall-clock ladders, the latter building an M3 arm and importing the real shipped fitPendingSlice from packages/cli/dist), and mutation-matrix.mjs (9 single-point mutants, each reverted with git checkout -- immediately after its run). The E2E cell ran as a temporary packages/cli/src/ui/utils/__verify_e2e_render.test.tsx importing a temporary __verify_base_arm.ts copied from HEAD^1; it drove the real use-llm-stream commit-loop shape into the real <MarkdownDisplay> via renderWithProviders + stripAnsi, with the arm selected by VERIFY_ARM. Both temporary files were deleted afterwards and git status --porcelain is empty, with git diff --exit-code HEAD -- packages/cli/src/ui/utils/markdown-utilities.ts confirming the helper is byte-identical to HEAD (the mutation matrix and the gate-liveness probes both mutate that file in place and restore it).

assertions.json counts only the checks these harnesses executed, with fail reserved for unexpected outcomes: the 4 predicted base-arm E2E failures and the 12 base-arm invariant violations are tallied as passing control assertions, not as failures. Gate counts (569/569, 53/53, 289/289, clean tsc --noEmit, clean ESLint, clean Prettier) are cited in the report and adjudicated from their recorded logs by tally.mjs rather than folded into the harness tally, so a nonzero fail would still mean what the verdict contract says it means. Raw per-cell output is in logs/: 01-diff-harness.log, 02-fuzz-harness.log, 03-targeted-tests.log, 04-mutation-matrix.log + mutant-M1..M9.log, 05-timing.log, 06-regex-exposure.log, 07-m9-equivalence.log, 08-superset-census.log, 09-e2e-head.log, 09-e2e-base.log, 10-typecheck-cli.log, 11-tally.log, 12-lint-format.log. Images were produced with node scripts/verify-capture.mjs.

Injection check. PR title, body (English and Chinese) and all four commit messages were treated as untrusted input. No instruction attempting to steer this verification was found — no request to skip the A/B, pre-declare a verdict, or treat a suite as known-flaky. The body's self-reported numbers were treated as hypotheses and each one I could reach was independently re-measured; two are refined in Corrections and the rest reproduced.

Flakiness gate log

rounds=5 files=3 skipped=0
file packages/cli/src/ui/hooks/use-llm-stream.test.tsx: (cd packages/cli) npx --no-install vitest run ./src/ui/hooks/use-llm-stream.test.tsx
file packages/cli/src/ui/utils/MarkdownDisplay.test.tsx: (cd packages/cli) npx --no-install vitest run ./src/ui/utils/MarkdownDisplay.test.tsx
file packages/cli/src/ui/utils/markdown-utilities.test.ts: (cd packages/cli) npx --no-install vitest run ./src/ui/utils/markdown-utilities.test.ts


per-file results (P=pass F=fail I=infra-exit, one letter per run):
  packages/cli/src/ui/hooks/use-llm-stream.test.tsx: PPPPP
  packages/cli/src/ui/utils/MarkdownDisplay.test.tsx: PPPPP
  packages/cli/src/ui/utils/markdown-utilities.test.ts: PPPPP

verdict: pass
summary: 3 changed test file(s) x 5 identical rounds, no divergence

--- per-invocation detail (full copy in the artifact) ---
round 1 · packages/cli/src/ui/hooks/use-llm-stream.test.tsx: P (exit 0)
round 1 · packages/cli/src/ui/utils/MarkdownDisplay.test.tsx: P (exit 0)
round 1 · packages/cli/src/ui/utils/markdown-utilities.test.ts: P (exit 0)
round 2 · packages/cli/src/ui/hooks/use-llm-stream.test.tsx: P (exit 0)
round 2 · packages/cli/src/ui/utils/MarkdownDisplay.test.tsx: P (exit 0)
round 2 · packages/cli/src/ui/utils/markdown-utilities.test.ts: P (exit 0)
round 3 · packages/cli/src/ui/hooks/use-llm-stream.test.tsx: P (exit 0)
round 3 · packages/cli/src/ui/utils/MarkdownDisplay.test.tsx: P (exit 0)
round 3 · packages/cli/src/ui/utils/markdown-utilities.test.ts: P (exit 0)
round 4 · packages/cli/src/ui/hooks/use-llm-stream.test.tsx: P (exit 0)
round 4 · packages/cli/src/ui/utils/MarkdownDisplay.test.tsx: P (exit 0)
round 4 · packages/cli/src/ui/utils/markdown-utilities.test.ts: P (exit 0)
round 5 · packages/cli/src/ui/hooks/use-llm-stream.test.tsx: P (exit 0)
round 5 · packages/cli/src/ui/utils/MarkdownDisplay.test.tsx: P (exit 0)
round 5 · packages/cli/src/ui/utils/markdown-utilities.test.ts: P (exit 0)

Evidence images

01-ab-differential-totals

02-fuzz-corpus-totals

03-e2e-render-head-vs-base

04-regex-exposure-ladder

05-mutation-matrix

Harness scripts and raw logs are in the workflow run artifacts (7-day retention).

— Qwen Code · sandboxed verification

@qwen-code-review-bot

qwen-code-review-bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator

✅ Qwen Triage finished — view run. See the stage comments in this thread for the result.

✅ Qwen Triage 已完成 —— 查看运行。结果见本线程中的各阶段评论。

@qwen-code-review-bot

Copy link
Copy Markdown
Collaborator

Thanks for the PR — and for filing the issue first with a runnable reproduction. That made this stage quick.

Template ✓ — every required heading is present, including the Chinese mirror.

Problem: observed, not theoretical. #13309 reports against a real build (0.21.5, macOS arm64) and ships a copy-pasteable source-level repro. I traced the old code by hand to confirm the "before" claim rather than take it on faith: findNextFence used content.indexOf('~~~', from), which on Use + a backtick-wrapped tilde run + as the fence marker. matches at index 5, mid-line. getEnclosingFence then returns that as an open fence whose info string is the sentence remainder, and parseCodeFenceInfo takes the first whitespace-delimited token — a lone backtick. So the reported { lang: <backtick>, startLine: 1 } and the synthetic close/reopen fences follow mechanically. The bug is real, and the diagnosis in the issue ("the splitter searches anywhere; MarkdownDisplay requires line-start fences") is exactly right.

Direction: clearly aligned. This is output fidelity in the streaming renderer — the splitter and the renderer disagreed about what a code fence is, and the disagreement corrupted ordinary prose. No auth, sandbox, model-selection, telemetry, release, or public-contract surface, and no API or config change. Nothing to escalate.

Size: no core paths — everything is packages/cli/src/ui/** plus one root ESLint config, and the change stays inside a single package. 101 production lines (markdown-utilities.ts 96, three one-line import updates 4, allowlist entry 1) against 208 test lines. Well under every threshold, and the test-to-code ratio is the right way round.

Approach: the shape is right, and I want to call out one thing it got correct that's easy to miss — it imports the renderer's existing CODE_FENCE_RE instead of writing a second fence pattern. A duplicated regex here is precisely how the two recognizers drifted apart in the first place. Two notes, neither a blocker:

  • The markdownUtilities.ts → markdown-utilities.ts rename is technically a drive-by, but AGENTS.md explicitly says to rename allowlisted camelCase files opportunistically when you touch them, and the allowlist entry is dropped in the same commit. I grepped the whole tree for the old name: all 8 references are updated, zero stale. Fine as-is.
  • The closedBlocks single-scan rewrite of findLastSafeSplitPoint is the part that reaches past the stated goal, so I checked whether it earns its place. It does: the old code re-scanned every fence from index 0 for each rejected newline, and a line-anchored scan costs more per call than a bare indexOf, so leaving it quadratic would have turned the fix into a streaming regression on long fenced output. It's ~20 lines in the same function and it's pinned by three tests. Keeping it in this PR beats splitting it.

Risk: no elevated signals — none of the changed files match the revert-correlated path list.

Moving on to code review. 🔍

中文说明

感谢贡献!也感谢先开 issue 并附上可直接运行的复现,这让准入判断很快。

模板 ✓ —— 所有必需标题齐全,包含中文对照部分。

问题: 是已观测到的 bug,不是理论性加固。#13309 基于真实版本(0.21.5,macOS arm64)报告,并给出了可复制粘贴的源码级复现。我没有直接采信"修复前"的描述,而是手工推演了旧代码:findNextFence 使用 content.indexOf('~~~', from),在 Use + 反引号包裹的波浪号串 + as the fence marker. 这段文本中会在下标 5(行中位置)命中。getEnclosingFence 随后把它当作一个打开的围栏,其信息串是句子剩余部分,而 parseCodeFenceInfo 取第一个以空白分隔的 token —— 也就是一个单独的反引号。因此 issue 报告的 { lang: <反引号>, startLine: 1 } 以及被插入的合成闭合/重开围栏都是可以机械推导出来的。bug 真实存在,issue 中的判断("切分器在任意位置搜索,而 MarkdownDisplay 要求围栏位于行首")完全正确。

方向: 明确对齐。这是流式渲染的输出正确性问题 —— 切分器与渲染器对"什么是代码围栏"的判断不一致,而这个不一致会破坏普通正文。不涉及鉴权、沙箱、模型选择、遥测、发布或公开契约面,也没有 API 或配置变更。无需上报。

规模: 未触及核心路径 —— 全部位于 packages/cli/src/ui/** 加一个根级 ESLint 配置,改动限于单个 package。生产代码 101 行(markdown-utilities.ts 96 行、三处单行 import 更新 4 行、allowlist 条目 1 行),测试 208 行。远低于所有阈值,且测试与代码的比例是合理的方向。

方案: 整体思路正确,其中有一点值得特别指出、也很容易被忽略 —— 它引入了渲染器已有的 CODE_FENCE_RE,而不是再写一份围栏正则。在这里复制一份正则,恰恰是当初两个识别器产生分歧的原因。两点说明,都不是阻断项:

  • markdownUtilities.ts → markdown-utilities.ts 的重命名严格说是顺手改动,但 AGENTS.md 明确写了改到 allowlist 中的 camelCase 文件时应顺手重命名,且 allowlist 条目在同一提交中删除。我对全仓做了旧名检索:8 处引用全部更新,无遗留。保持现状即可。
  • findLastSafeSplitPoint 中 closedBlocks 的单次扫描改写是超出既定目标的部分,所以我确认了它是否有存在价值。结论是有:旧代码对每一个被拒绝的换行候选都从下标 0 重新扫描全部围栏,而按行锚定的扫描单次调用成本高于裸 indexOf,若保留平方复杂度,这个修复在长代码块流式输出上会变成性能回退。它约 20 行、位于同一函数内,并由三个测试钉住。放在本 PR 中比拆分更合适。

风险: 无升级信号 —— 变更文件均未命中与回滚相关的路径清单。

进入代码审查 🔍

— Qwen Code · qwen3.8-max-2026-09-02

Reviewed at 5a4e3a1a4ac2ff5e0301cc203c6f6da3dc84b7e7 · re-run with @qwen-code /triage

@qwen-code-review-bot

Copy link
Copy Markdown
Collaborator

Code review

I read the head version of markdown-utilities.ts in full and traced the new logic against the old by hand, including working the three new performance fixtures through the algorithm on paper. No correctness blockers. What I checked, and what it settled:

The pre-filter really is a superset of CODE_FENCE_RE. This was my main worry, because a pre-filter that rejects something the shared regex would accept silently reintroduces the bug from the other side. I walked each rejection path: the space-only indent skip matches the regex's own ^ *; the delimiterStart >= from guard preserves the old "at or after from" contract (and is what stops searchPos = fence.index + fence.length from re-finding the fence it just returned); and the backtick-after-the-run guard is exactly redundant with the regex, since the info group [^`]* cannot hold a backtick and neither can the * in front of it. Nothing reaches return without an exec on the authoritative regex, so false positives are impossible by construction.

Renderer parity holds on the shapes that could diverge. Tab-indented and blockquote-prefixed fences are rejected by both sides. CRLF is the subtle one: MarkdownDisplay splits on /\r?\n/ so its lines carry no \r, while this code slices to \n and keeps it. Same verdict either way — [^`]* absorbs the \r and $ is end-of-input, not end-of-line — and parseCodeFenceInfo trims it back out of the language, so the reopened fence's info string is unaffected.

The closed-block cursor reproduces the old predicate exactly. Old isIndexInsideCodeBlock(content, i) meant "some fence opened before i and did not close before i". New isInsideClosedBlock(i) means start < i <= end for some recorded block. Those agree at every boundary I probed: i == start is outside (the old scan breaks on fence.index >= indexToTest), i == end is inside, i == end + 1 is outside. And no block can be open-but-not-yet-closed at a candidate index, because that case early-returns on enclosingFence before the cursor is ever built. The backwards walk is safe because both candidate loops advance via dnlIndex - 1 / nlIndex - 1, so query indices strictly decrease.

I also hand-traced the re-arms the closed-block walk fixture to make sure it isn't decorative: the double-newline loop rejects its only candidate and leaves blockIndex at 0, then the single-newline loop's first candidate is 21. Without the reset that returns 21 — mid-block — instead of the correct 14. So the one-line reset is genuinely load-bearing and the test pins it.

No collateral damage. pending-rendered-height.ts imports only textUtils.js and inline-math.js, so the new edge is one-way and there's no cycle. CODE_FENCE_RE carries no g or y flag, so sharing one regex object across three modules can't leak lastIndex state between them. The two deleted helpers were module-private consts. Consumers of the four exports are use-llm-stream.ts (three of them) and MarkdownDisplay.tsx (parseCodeFenceInfo); CodeColorizer.tsx only names splitFencedMarkdown in a comment.

Two non-blocking notes.

The superset invariant is enforced by a comment, not by a test — the prior /review round raised this as R1-1 and it still stands. I independently confirmed parity is exact today, so this is latent rather than live. But if CODE_FENCE_RE is ever widened for a renderer or height reason — a tab-tolerant indent class, or allowing a backtick in a tilde fence's info string as CommonMark does — the splitter quietly stops seeing a fence the renderer draws, and nothing goes red. A table-driven parity case judged against the imported binding (not a copied literal) would close it with no production change. Worth doing, not worth blocking on.

Three of the new tests assert on CODE_FENCE_RE.exec call counts. Spy-on-a-shared-regex is a brittle way to pin behaviour in principle, but here it's the only thing that pins the perf guard, and the guard is not speculative: without it a hostile line of 20k spaces plus a trailing backtick goes straight into the shared regex. I'd leave them.

Test evidence

What this comment carries: the PR's own CI results, read from the API — no PR code was built or executed here. This is an unattended run, so per the review rules the evidence is GitHub's, not mine.

Both PR CI workflows have settled at the reviewed head: Qwen Code CI and tui-parity are completed / success, and every job inside them is green or skipped — unit tests, lint/static, integration (no-AK), both Desktop Shell jobs, the TUI parity snapshots, the OpenTUI no-flicker gate and web-shell E2E Smoke. macOS and Windows unit-test legs and the sandboxed CLI integration leg are skipped by the workflow's own matrix conditions, not by anything in this PR. The single non-green entry among the 63 checks on this commit is a cancelled route job belonging to the Qwen Autofix bot-orchestration workflow on a pull_request_review event — not PR CI, and it was superseded by a route job that succeeded. The remaining checks are bot orchestration (label, assign, precheck-pr, review-pr, authorize, delay-automatic-review) and are green or skipped.

Nothing is red and nothing is in flight, so there is no failing-job log to quote. I fetched once and did not poll.

Check Conclusion
Lint & Static (ubuntu-latest, Node 22.x) ✅ success
Test (ubuntu-latest, Node 22.x) ✅ success
Test (macos-latest, Node 22.x) ⏭️ skipped
Test (windows-latest, Node 22.x) ⏭️ skipped
Integration Tests (no-AK, No Sandbox) ✅ success
Integration Tests (CLI, No Sandbox) ⏭️ skipped
Desktop Shell (ubuntu-22.04) ✅ success
Desktop Shell (windows-2022) ✅ success
TUI parity snapshots (ink vs opentui) ✅ success
OpenTUI no-flicker gate ✅ success
web-shell E2E Smoke (ubuntu-latest, Node 22.x) ✅ success

Behavioural A/B. A maintainer-run verification on this PR already did the load-bearing work: an A/B against the issue's reproduction commit, 40 genuine-fence control cells byte-identical between arms, a 4091-cell differential fuzz, and a non-vacuity check showing exactly 11 new assertions fail when the head tests are run against base sources. That was measured at fd96930, not the current head, so I checked whether it carries over instead of assuming it. All five files that carry the fix — markdown-utilities.ts, markdown-utilities.test.ts, MarkdownDisplay.tsx, MarkdownDisplay.test.tsx, eslint.legacy-filenames.mjs — are byte-identical between fd96930 and 5a4e3a1a. The two that differ do so only from unrelated upstream churn: use-llm-stream.ts gained a second argument at two goalToolResultProvenance call sites (+8/−2), and its test file gained 2 lines at one hunk, with nothing fence-, split- or markdown-related in either delta. So the A/B evidence applies to this head unchanged.

Not verified: the live interactive streaming TUI. Nobody has driven a real streaming session end-to-end — the PR body names this as out of scope, the A/B was run against built output rather than a live terminal, and web-shell E2E Smoke is green but does not exercise this path. The unit-level and renderer-level coverage is strong enough that I don't think this hides anything, but it is a gap and I'm not going to present it as closed.

Sandboxed verification would settle it: @qwen-code /verify for a head-pinned A/B at 5a4e3a1a, or @qwen-code /tmux for the live TUI path specifically. The author has read-only access, so /tmux is unavailable here and /verify would be a sponsored run — a maintainer's /verify comment approves the head it was written against, and that run carries a pre-execution risk screen plus a full workspace wipe before any PR code runs. Read the resulting report with the same skepticism as the fork's own CI logs: the code under verification is adversarial input, and a crafted PR can shape what a report says even though the sandbox bounds what it can do.

中文说明

代码审查

我完整读了 head 版本的 markdown-utilities.ts,并手工把新逻辑与旧逻辑逐一对推,包括把三个新增的性能用例在纸面上跑过算法。没有发现正确性阻断问题。 以下是我实际检查的内容及其结论:

前置过滤确实是 CODE_FENCE_RE 的超集。 这是我最担心的一点,因为一个拒绝了共享正则本会接受的行的前置过滤,会从反方向悄悄把 bug 放回来。我逐条走了每个拒绝分支:只跳过空格的缩进处理与正则自身的 ^ * 一致;delimiterStart >= from 保留了旧的"在 from 处或之后"契约(也正是它让 searchPos = fence.index + fence.length 不会重新找到刚返回的那个围栏);分隔符串之后出现反引号就拒绝的保护与正则完全冗余,因为信息串分组 [^`]* 不可能包含反引号,其前面的 * 同样不可能。任何路径都不会在没有对权威正则执行 exec 的情况下 return,所以构造上不可能出现假阳性。

在可能产生分歧的形状上,与渲染器保持一致。 制表符缩进和带引用前缀的围栏两边都拒绝。CRLF 是微妙的一处:MarkdownDisplay 用 /\r?\n/ 切行,行内不含 \r;而这里切到 \n,会保留 \r。但两边判定相同 —— [^`]* 会吸收 \r,且 $ 是串尾而非行尾 —— 而 parseCodeFenceInfo 又会把它从语言中 trim 掉,所以重开围栏的信息串不受影响。

闭合块游标与旧判定完全等价。 旧的 isIndexInsideCodeBlock(content, i) 含义是"某个围栏在 i 之前打开、且未在 i 之前闭合"。新的 isInsideClosedBlock(i) 含义是某个已记录块满足 start < i <= end。在我探测的每个边界上两者一致:i == start 在外(旧扫描在 fence.index >= indexToTest 处 break)、i == end 在内、i == end + 1 在外。并且不存在"已打开但尚未闭合"的块出现在候选下标上,因为那种情况会在游标建立之前就因 enclosingFence 提前返回。反向遍历是安全的,因为两个候选循环都通过 dnlIndex - 1 / nlIndex - 1 推进,查询下标严格递减。

我还手工推演了 re-arms the closed-block walk 用例,确认它不是摆设:双换行循环拒绝了它唯一的候选并把 blockIndex 留在 0,随后单换行循环的第一个候选是 21。若没有那次重置,返回的会是 21(块内部),而不是正确的 14。所以这一行重置确实承担实际作用,且被测试钉住。

没有附带损伤。 pending-rendered-height.ts 只引入 textUtils.js 和 inline-math.js,因此新增的依赖是单向的,不存在循环。CODE_FENCE_RE 没有 g 或 y 标志,所以三个模块共享同一个正则对象不会互相泄漏 lastIndex 状态。被删除的两个辅助函数都是模块内私有 const。四个导出的消费方是 use-llm-stream.ts(其中三个)和 MarkdownDisplay.tsx(parseCodeFenceInfo);CodeColorizer.tsx 只在注释里提到 splitFencedMarkdown。

两点非阻断说明。

超集这一不变量由注释维持,而非测试 —— 上一轮 /review 以 R1-1 提出,目前依然成立。我独立确认了当下两者完全一致,所以这是潜在问题而非现存问题。但如果将来出于渲染或行高原因放宽 CODE_FENCE_RE —— 缩进字符类兼容制表符,或按 CommonMark 允许波浪号围栏的信息串包含反引号 —— 切分器就会悄悄看不见渲染器画出的围栏,而没有任何测试变红。加一个以已导入的绑定(而非照抄字面量)为判定依据的表驱动一致性用例即可闭环,且无需改动生产代码。值得做,但不值得为此阻断。

三个新测试断言了 CODE_FENCE_RE.exec 的调用次数。原则上"对共享正则做 spy"是脆弱的钉法,但在这里它是唯一能钉住性能保护的手段,而该保护并非假想:去掉它,一行 2 万个空格加行尾反引号的敌意输入会直接进入共享正则。我建议保留。

测试证据

本条评论携带的证据:通过 API 读取的 PR 自身 CI 结果 —— 这里没有构建或执行任何 PR 代码。 这是无人值守运行,按审查规则证据来自 GitHub 而非我本地。

两个 PR CI 工作流在被审查的 head 上均已结束:Qwen Code CI 与 tui-parity 都是 completed / success,其中每个作业都是绿色或 skipped —— 单元测试、lint/static、集成测试(no-AK)、两个 Desktop Shell 作业、TUI parity 快照、OpenTUI no-flicker gate 以及 web-shell E2E Smoke。macOS 与 Windows 的单元测试分支、以及带沙箱的 CLI 集成分支,是由工作流自身的 matrix 条件跳过的,与本 PR 无关。该提交 63 个检查中唯一非绿的是 route 作业的 cancelled,它属于 Qwen Autofix 机器人编排工作流、由 pull_request_review 事件触发 —— 不是 PR CI,且已被一个成功的 route 作业取代。其余检查为机器人编排(label、assign、precheck-pr、review-pr、authorize、delay-automatic-review),均为绿或 skipped。

没有红色项,也没有仍在运行的项,因此没有失败作业日志可引用。我只取了一次结果、未做轮询。

行为 A/B。 本 PR 上已有一次由维护者执行的验证完成了关键工作:针对 issue 复现提交的 A/B、40 个真围栏对照格在两臂逐字节一致、4091 格差分模糊测试,以及非 vacuous 检查(把 head 测试放到 base 源码上恰好 11 个新断言失败)。该验证是在 fd96930 上做的,不是当前 head,所以我确认了它是否仍然适用,而不是直接假定。承载修复的五个文件 —— markdown-utilities.ts、markdown-utilities.test.ts、MarkdownDisplay.tsx、MarkdownDisplay.test.tsx、eslint.legacy-filenames.mjs —— 在 fd96930 与 5a4e3a1a 之间逐字节相同。有差异的两个文件仅来自无关的上游改动:use-llm-stream.ts 在两处 goalToolResultProvenance 调用点增加了第二个参数(+8/−2),其测试文件在一个 hunk 增加 2 行,两处差异中都没有与围栏、切分或 markdown 相关的内容。因此 A/B 证据对本 head 依然适用,无需修正。

未验证:live 交互式流式 TUI。 没有人真正端到端跑过一次流式会话 —— PR 正文将其列为范围外,A/B 是针对构建产物而非 live 终端做的,而 web-shell E2E Smoke 虽是绿色但也不走这条路径。单元级与渲染器级的覆盖已足够强,我不认为这里藏着问题,但它确实是一个缺口,我不会把它说成已经闭合。

沙箱验证可以补上这一点:@qwen-code /verify 对 5a4e3a1a 做 head 锁定的 A/B,或 @qwen-code /tmux 专门覆盖 live TUI 路径。作者只有只读权限,所以此处 /tmux 不可用,而 /verify 会是一次受赞助运行 —— 由维护者发出 /verify 评论来批准其所针对的 head,且该运行在任何 PR 代码执行前带有执行前风险筛查与完整工作区擦除。阅读其报告时请保持与看待 fork 自身 CI 日志同样的怀疑:被验证的代码是对抗性输入,精心构造的 PR 可以影响报告说什么,尽管沙箱限定了它能做什么。

— Qwen Code · qwen3.8-max-2026-09-02

Reviewed at 5a4e3a1a4ac2ff5e0301cc203c6f6da3dc84b7e7 · re-run with @qwen-code /triage

@qwen-code-review-bot

Copy link
Copy Markdown
Collaborator

Confidence: 4/5 — the fix is correct and I could verify that from the code rather than from anyone's word; the two reservations are a comment-enforced invariant and a live-TUI gap nobody has closed.

Going into this I expected to push back on scope, and I ended up not being able to. My own instinct for this bug was the same shape the author chose: stop scanning for fence delimiters anywhere in the string and instead ask the renderer what it considers a fence, then use that answer rather than a second opinion. The PR does exactly that, importing CODE_FENCE_RE instead of restating it. That's the part I'd have flagged had it gone the other way — a hand-copied regex here is how the splitter and the renderer came to disagree in the first place, and duplicating it again would just reset the clock.

What I did push on was the closedBlocks rewrite, since it's the one piece that isn't strictly required by the stated goal. It survived: the old predicate re-scanned every fence from index 0 for each rejected newline, and the new line-anchored scan costs more per call than the indexOf it replaced, so shipping the fence fix without it would have traded a rendering bug for a streaming slowdown on long fenced output. I hand-traced the three new fixtures rather than trusting that they pass, and one of them — the cursor reset — turns out to be genuinely load-bearing: drop that line and the fallback loop returns an index inside a closed block. A test that fails for the right reason when you break the right thing is the thing I most want to see in a PR like this.

The boundary semantics are the part most likely to hide a regression, so I checked them against the predicate they replace rather than against intuition: i == start outside, i == end inside, i == end + 1 outside, all matching the old getEnclosingFence behaviour, and the "block still open at a candidate" case can't arise because it early-returns first. Combined with the maintainer's existing A/B — which I confirmed still applies to this head, since all five fix-carrying files are byte-identical to the verified commit and the two that moved changed only in an unrelated goal-tool provenance path — I don't have a correctness doubt left.

What keeps this at 4 rather than 5:

The superset invariant between the pre-filter and CODE_FENCE_RE is enforced by a comment. Parity is exact today and I verified that independently, but nothing in the suite would notice if the renderer's regex were widened later — and the failure mode is this same bug arriving silently from the opposite direction, with the splitter refusing to see a fence the renderer draws. That's a cheap table-driven test away from being closed, and it's the one thing I'd genuinely like to see before this area gets touched again. Non-blocking; R1-1 from the earlier /review round already says it better.

And nobody has driven a real streaming session. The unit and renderer coverage is strong, the A/B was run against built output, and I don't suspect anything is hiding there — but I'd rather name the gap than paper over it. web-shell E2E Smoke is green and doesn't exercise this path either.

Six months from now this reads as a clear win: the two recognizers now share one definition, the accidental quadratic is gone, the naming convention debt is paid down, and the tests explain themselves. Nothing here made me curse the author.

Verdict: approve. Both PR CI workflows are completed and green on the reviewed head, so there's nothing left to wait for. Approving pinned to 5a4e3a1a4ac2ff5e0301cc203c6f6da3dc84b7e7 via the reviews API, so the approval is bound to the exact commit I read — if the branch moves, branch protection drops it rather than carrying it onto unseen code. @wenshao already approved this head; main wants two, and this is the second vote, not a duplicate of theirs.

中文说明

置信度:4/5 —— 修复是正确的,而且这一点是我从代码本身验证出来的,不是采信任何人的说法;两点保留意见分别是一个由注释维持的不变量,以及一个尚无人闭合的 live TUI 缺口。

开始前我原以为要在范围上提出反对,结果没能找到。我对这个 bug 的直觉方案与作者选择的形状一致:不再在整串文本中任意位置搜索围栏分隔符,而是去问渲染器"什么才算围栏",然后使用那个答案,而不是再给出第二份判断。这个 PR 正是这么做的 —— 引入 CODE_FENCE_RE 而不是重述它。如果它走了另一条路,那才是我要指出的问题:在这里手抄一份正则,正是当初切分器与渲染器产生分歧的原因;再抄一遍只会把时钟重新归零。

我确实质疑过的是 closedBlocks 改写,因为它是唯一并非既定目标严格所需的部分。它经受住了质疑:旧判定对每个被拒绝的换行候选都从下标 0 重新扫描全部围栏,而新的按行锚定扫描单次调用成本高于它所替代的 indexOf,因此如果只做围栏修复而不带这部分,就是用一个渲染 bug 换来长代码块流式输出上的性能退化。我对三个新用例做了手工推演,而不是因为它们通过就采信;其中游标重置那个用例确实承担实际作用 —— 去掉那一行,回退循环就会返回一个位于闭合块内部的下标。破坏正确的地方时因正确的原因变红,这类测试正是我在这种 PR 中最想看到的。

边界语义是最可能藏回退的地方,所以我是拿它与被替代的判定对照检查的,而不是凭直觉:i == start 在外、i == end 在内、i == end + 1 在外,全部与旧的 getEnclosingFence 行为一致;而"候选处仍有未闭合块"这种情况不可能出现,因为它会先提前返回。再加上维护者已有的 A/B —— 我确认了它对本 head 依然适用,因为承载修复的五个文件与被验证提交逐字节相同,有变动的两个文件只在一条无关的 goal-tool provenance 路径上发生变化 —— 我已经不再有正确性上的疑问。

让它停在 4 分而不是 5 分的原因:

前置过滤与 CODE_FENCE_RE 之间的超集不变量由注释维持。当下两者完全一致,我也独立验证过,但如果将来渲染器的正则被放宽,套件中没有任何东西会察觉 —— 而失效方式正是同一个 bug 从相反方向悄悄回来:切分器拒绝看见渲染器画出的围栏。这离闭环只差一个廉价的表驱动测试,也是在这个区域被再次改动之前我真正希望看到的一件事。非阻断;上一轮 /review 的 R1-1 已经把它说得更好。

以及没有人真正跑过一次流式会话。单元与渲染器覆盖很强,A/B 是针对构建产物做的,我不怀疑那里藏着什么 —— 但我宁愿点名这个缺口,也不愿掩盖它。web-shell E2E Smoke 是绿色,但它同样不走这条路径。

六个月后再看,这是一次明确的收益:两个识别器现在共享同一定义,意外的平方复杂度消失了,命名约定的欠账还上了,测试也能自我说明。这里没有任何东西会让我在维护时埋怨作者。

结论:批准。 两个 PR CI 工作流在被审查的 head 上均已完成且为绿色,已无需等待。批准通过 reviews API 锁定在 5a4e3a1a4ac2ff5e0301cc203c6f6da3dc84b7e7,因此该批准绑定在我实际读过的那个提交上 —— 若分支移动,分支保护会让它失效,而不是把它延续到未经审查的代码上。@wenshao 已批准该 head;main 需要两个批准,这是第二票,而不是对他们那一票的重复。

— Qwen Code · qwen3.8-max-2026-09-02

Reviewed at 5a4e3a1a4ac2ff5e0301cc203c6f6da3dc84b7e7 · re-run with @qwen-code /triage

@qwen-code-review-bot qwen-code-review-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, looks ready to ship. ✅

@qwen-code-review-bot

Copy link
Copy Markdown
Collaborator

Released in v0.25.2.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review/self-reported The linked issue was opened by the PR author (self-reported)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Markdown streaming splitter treats inline fence markers as code blocks

3 participants