Skip to content

fix(kimi-web): render inline KaTeX math with conservative $...$ delimiters#2105

Open
nothankyouzzz wants to merge 1 commit into
MoonshotAI:mainfrom
nothankyouzzz:fix/web-inline-katex
Open

fix(kimi-web): render inline KaTeX math with conservative $...$ delimiters#2105
nothankyouzzz wants to merge 1 commit into
MoonshotAI:mainfrom
nothankyouzzz:fix/web-inline-katex

Conversation

@nothankyouzzz

@nothankyouzzz nothankyouzzz commented Jul 23, 2026

Copy link
Copy Markdown

Related Issue

Resolve #1804

Problem

See linked issue. In short: kimi web disables markstream's inline math rule entirely (disableInlineMath in Markdown.vue), so $...$ inline formulas — the form models emit most — render as raw source. Only standalone $$...$$ blocks render.

What changed

Markdown.vue no longer disables the inline math rule; it replaces it (md.inline.ruler.at('math', …)) with a conservative pandoc-style variant (apps/kimi-web/src/lib/mathInline.ts):

  • the opening delimiter must be followed by a non-space character;
  • a closing $ must be preceded by a non-space and must not be followed by a digit; a candidate closer that fails these rules abandons the opener (no scanning across it), so math content never contains an unescaped $ — spans never cross;
  • the content must be non-empty, contain no backtick, and not be a bare number ($100$ stays a currency amount, while $3+4=7$ still renders);
  • \(...\) and inline $$...$$ keep working; math_block is untouched;
  • while streaming, an unclosed $ still renders progressively — but only when the partial content is unambiguously TeX (details below).

Why this rule set (trade-off analysis)

$ carries no type information in plain text, so any rule here is a heuristic — the question is which errors you accept. Options considered:

Option Verdict
Keep inline math disabled (status quo) Real formulas degrade to raw source — the reported bug
Re-enable markstream's built-in rule as-is Accepts any closed $...$ with no delimiter-adjacency checks: $HOME/bin and $PATH (two env vars in one sentence) becomes "math". Its mid-stream loading math has the same problem: any lone $ with math-ish text after it flickers as a formula
Enable only \(...\) (the proposal in #1804) Unambiguous, but models overwhelmingly emit $...$; fixes a fraction of real output
pandoc delimiter rules (this PR) The GitHub / GitLab / VS Code markdown-math standard; covers real $...$ math and the common false-positive shapes
pandoc + content sniffing (require TeX signals like \cmd, ^, _, =) Kills the residual $HOME/bin:$PATH edge, but also kills legitimate signal-free formulas ($x$, $t$, $D/R$); every exception carved out makes the rule set more special-cased
Try KaTeX render, fall back to text on error Doesn't discriminate — HOME/bin: is valid TeX and renders "successfully"

The chosen rule set is the pandoc standard plus one extra guard (bare-number content ⇒ currency). It is a sweet spot because the realistic false-positive shapes line up with what the rules already reject:

  • Prices ($5, $5 and $10, $1,000.50) — no valid closing delimiter, closing $ followed by a digit, or bare-number content;
  • Env vars & paths in prose ($PATH, $HOME/bin and $PATH) — no closing $, or closing $ preceded by a space;
  • Env vars & paths in code spans (`$HOME/bin:$PATH` — how models actually write shell content) — never reach the math rule at all: markdown-it's backticks rule consumes the whole span first, and the backtick guard stops a math span from closing across a code span.

Known residual edge: bare-text $HOME/bin:$PATH (no backticks, closing $ adjacent to a non-space) still parses as math — identical behavior to pandoc and GitHub; the escape hatch is \$, as on those platforms.

Streaming: guarded progressive rendering

The built-in rule rendered any unclosed $... as loading math mid-stream; the naive fix would be to wait for the closing $ and accept the raw-text flash. This PR keeps progressive rendering but guards it harder than the closed case, since partial content has no closing delimiter to vouch for it:

  • only a backslash command (\Sigma, \frac, …) qualifies as the TeX signal — the one signal with zero overlap with prices and shell syntax (_, ^, =, {} all appear in $MY_VAR, $PATH=$HOME, ${PATH});
  • the partial render stops at the first line break, so trailing prose is never swallowed;
  • settled messages (__markstreamFinal) never take this path — an unclosed $ in history stays literal;
  • when KaTeX can't parse a partial formula yet, MathInlineNode's fallback shows the raw source (its loading spinner is hidden via CSS — the raw text alone is the honest state).

Net effect: $\Sigma_t + \cdots$ renders live as it streams; $5, $PATH, $x never flash as math; simple signal-free formulas like $r_t$ appear the moment they close.

Testing

  • apps/kimi-web/src/lib/mathInline.test.ts: 19 unit tests — real formulas, prices, env vars, escaped dollars, unclosed $ (settled vs. streaming), TeX-signal gating, line-break cutoff, silent mode, $$...$$, \(...\), and a regression test for the opener-abandon semantics found in review;
  • property-based fuzzing in the same file: 80k seeded adversarial inputs (structured fragments + character noise, settled and streaming) asserting lossless round-trip, delimiter adjacency, no backtick/$ crossing, bare-number rejection, and TeX-signal gating of loading math;
  • verified through the real parser (getMarkdown + parseMarkdownToStructure) that inputs like $\Sigma_t$, $\leq t-1$, $w^\top\Sigma w$ produce math_inline nodes while $5, $PATH, $HOME/bin and $PATH stay literal — including inside **bold** spans, which exercise markstream's strong/math token fixups;
  • pnpm --filter kimi-web typecheck, pnpm --filter kimi-web test, pnpm --filter kimi-web build, and oxlint all green; manually verified in the running web app.

Checklist

  • I have read the CONTRIBUTING document.
  • I have linked a related issue, or explained the problem above.
  • I have added tests that prove my feature works.
  • Ran gen-changesets skill, or this PR needs no changeset. (Changeset included: @moonshot-ai/kimi-code patch — kimi-web is internal, but its build output ships inside the CLI bundle.)
  • Ran gen-docs skill, or this PR needs no doc update. (No doc update: bug fix restoring expected rendering; no docs page documents math delimiters.)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 637a984ee4

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread apps/kimi-web/src/lib/mathInline.ts Outdated
@changeset-bot

changeset-bot Bot commented Jul 23, 2026

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: d3f3aae

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
@moonshot-ai/kimi-code Patch

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

@nothankyouzzz
nothankyouzzz force-pushed the fix/web-inline-katex branch from d135a39 to f827abc Compare July 23, 2026 11:18
…iters

The web chat disabled markstream's inline `math` rule entirely, so
single-dollar formulas ($\Sigma_t$, $r_t$) rendered as raw source.
Replace the rule with a pandoc-style variant:

- the opening delimiter must be followed by a non-space character;
- a closing $ must be preceded by a non-space, must not be followed by
  a digit, and must not be part of a $$ pair; a candidate closer that
  fails these rules abandons the opener, so math content never contains
  an unescaped $ — spans never cross ('Costs $5 and $x$' renders the
  formula and keeps the price literal);
- content must be non-empty, contain no backtick, and not be a bare
  number ($100$ stays a currency amount);
- while streaming, an unclosed $ renders progressively only when the
  partial content contains a backslash command (the one TeX signal with
  zero overlap with prices and shell syntax), stopping at the first
  line break; settled messages never render partial math;
- \(...\) and inline $$...$$ keep working; `math_block` is
  untouched. MathInlineNode's loading spinner is hidden via CSS — the
  raw source alone is the honest fallback state.

Covered by unit tests plus property-based fuzz tests (80k seeded
adversarial inputs asserting lossless round-trip, delimiter adjacency,
no backtick/$ crossing, bare-number rejection, and TeX-signal gating
of loading math).
@nothankyouzzz
nothankyouzzz force-pushed the fix/web-inline-katex branch from f827abc to d3f3aae Compare July 23, 2026 11:26
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(web): enable \(...\) as inline math delimiter in kimi web

1 participant