Skip to content

Studio: render escaped inline math in lists - #9796

Merged
mahiatlinux merged 26 commits into
unslothai:mainfrom
Imagineer99:fix/escaped-inline-math-lists
Aug 29, 2026
Merged

mahiatlinux merged 26 commits into
unslothai:mainfrom
Imagineer99:fix/escaped-inline-math-lists

Conversation

@Imagineer99

Copy link
Copy Markdown
Member

Summary

  • recover math-looking inline spans when a local model emits escaped dollar delimiters such as \$v_s\$
  • preserve escaped currency, prose, code spans, link destinations, incomplete spans, and display math
  • cover the reported list rendering case in preprocessing, streaming, and real Streamdown + KaTeX integration tests

Why

Markdown treats \$...\$ as literal dollars, so Studio displayed $v_s$ in list items even when the same reply's display equation rendered correctly. The preprocessor now selectively converts paired, math-looking escaped delimiters back to inline math before Streamdown parses the reply.

Validation

  • npm test — 5,209 passed
  • npm run typecheck
  • Playwright UI reproduction against the reported content:
    • before: 0 inline KaTeX nodes and 5 literal dollar spans
    • after: 5 inline KaTeX nodes and 0 literal dollar spans

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@danielhanchen

Copy link
Copy Markdown
Member

Confirmed the preprocessor in studio/frontend/src/lib/latex.ts left paired escaped dollar spans as literal dollars, and the added guards keep currency, code spans and link destinations untouched. Will get this reviewed.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Aug 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-08-29T06:26:06.648120Z 2336997 Manual request
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

chatgpt-codex-connector[bot]

This comment was marked as resolved.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 29, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Aug 29, 2026
@mahiatlinux

Copy link
Copy Markdown
Contributor

Reviewed and fixed the escaped inline math path.

The problem is real and in scope. An isolated Playwright run against merge base f86b1767f reproduced the reported behavior: the realistic response produced only its one display-math KaTeX node, while every \$...\$ inline expression remained literal. The same scene on pushed head 253a3fafd produced nine KaTeX nodes in both the running and completed response states, with zero katex-error nodes.

Concrete issues found and fixed:

  1. The original preprocessing approach operated before Markdown parsing, so it had to guess whether delimiters were prose, code, links, raw HTML, or existing math. The final implementation parses escaped math as a micromark text construct and installs it in the actual Studio Streamdown path: escaped-inline-math.ts, markdown-text.tsx, and markdown-text.tsx.

  2. Rejected or ambiguous escaped pairs could consume a later valid opener, and candidates could cross a code span, link, or HTML tag. That changed Markdown structure and hid later valid math. The tokenizer now rejects Markdown boundaries before creating an inlineMath node and lets normal Markdown parsing resume: escaped-inline-math.ts, escaped-inline-math.ts. Regression cases cover nested code, links, HTML, currency, prose, adjacent pairs, over-length pairs, and later valid openers: escaped-inline-math.test.ts.

  3. Raw <code>\$x_1\$</code> content was incorrectly converted to KaTeX because CommonMark parses text between inline HTML tags as normal text. The extension now tracks literal HTML tag state from micromark events and leaves code, pre, and textarea contents literal: escaped-inline-math.ts, with DOM coverage in escaped-inline-math.test.ts.

  4. The code-region scanner mishandled list and quote fence state, container exits, non-interrupting ordered markers, indented code after block boundaries, and inline backticks crossing Markdown blocks. This could mutate literals inside code or suppress valid transformations after an unclosed container fence. The scanner now follows list/quote state and uses block-scoped inline spans: latex.ts, latex.ts. Focused scanner and shared search-image regressions cover those cases.

  5. The stateful scanner initially made the existing 20,000-character streaming performance guard fail at 10.4x the plain-text cost. Top-level fences now use a candidate-driven fast path, while list, quote, and indented cases retain the stateful scan: latex.ts. The existing streaming cost guard passes again.

Testing performed:

  • 75 focused Node tests passed with concurrency 1: escaped-math parser, actual chat render pipeline, Markdown code regions, search-image scanner consumers, streaming corpus, retroactive edits, and the long-stream performance guard.
  • tsc -p tsconfig.test.json --noEmit passed.
  • Focused Biome and ESLint checks passed.
  • Playwright-only UI A/B used isolated merge-base/head installs and a mocked 17-chunk SSE response through the real provider picker, composer, assistant runtime, preprocessing, incremental cache, Streamdown, and KaTeX pipeline.
  • Playwright DOM facts for both running and completed states: KaTeX 1 -> 9, annotations gained v_s, f(r_s), f \to 0, f \to 1, r_s, x_1, y_2, and z^2; errors stayed 0; list items stayed 4; inline code stayed \$code_1\$; $5, $1,200, the literal escaped dollar, and the incomplete delimiter stayed non-math.
  • Captured and visually checked both labelled composites: streaming and completed response states. The ref override was local head 253a3fafd because the evidence was generated before that exact head was pushed; its base was the PR merge base f86b1767f.

Focused fork CI is being staged from the pushed head. I will link its result separately.

@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@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: f93474673e

ℹ️ 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 on lines +128 to +130
if (phase === "exit" && token.type === "characterEscape") {
updateLatexBracketState(state, context.sliceSerialize(token));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reset unmatched bracket math at block boundaries

When an unmatched \( or \[ appears earlier in the message, this persistent delimiter stack never clears, so every later \$…\$ candidate remains literal—even on subsequent paragraphs or list items. For example, `unfinished (

  • $v_s$fails to recoverv_s, although preprocessLaTeX` leaves the unmatched bracket opener as ordinary text. Reset unmatched bracket state when its Markdown block ends, or determine complete bracket-math ranges before suppressing escaped-dollar parsing.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Not reproducible at f934746. normalizeEscapedInlineMath(String.raw'unfinished \(\n\n- \$v_s\$') returns unfinished \\(\n\n- $v_s$; micromark starts a new tokenization context at the next Markdown block, so the WeakMap state does not persist across this boundary.

Comment thread studio/frontend/src/lib/latex.ts Resolved
@mahiatlinux

Copy link
Copy Markdown
Contributor

@codex review

@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: ec2e029b23

ℹ️ 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 studio/frontend/src/lib/latex.ts Resolved
Comment thread studio/frontend/src/lib/latex.ts Resolved
@mahiatlinux

Copy link
Copy Markdown
Contributor

Final review and convergence result for pushed head 23369979f.

The PR fixes a real Studio rendering defect. Merge-base f86b1767f left model-emitted escaped inline math literal in the real chat path. The final head renders it through KaTeX in both running and completed responses.

Concrete issues found and fixed:

  1. Escaped math normalization ran at the wrong layer and order. Streaming repair and currency handling could reinterpret delimiters before escaped math became real math. MarkdownTextImpl now normalizes escaped math before preprocessLaTeX and stabilizeStreamingMarkdown: markdown-text.tsx lines 737-760. This prevents remend from treating underscores inside \$...\$ as incomplete emphasis.

  2. Text replacement could not distinguish math from currency, code, links, raw HTML, nested Markdown, or bracket display math. The parser now accepts only bounded math-like bodies, rejects unbalanced braces and Markdown boundaries, and respects literal HTML and existing bracket-math state: escaped-inline-math.ts lines 127-153, escaped-inline-math.ts lines 259-397. Ambiguous prose and currency remain literal while valid later pairs still render.

  3. Converted adjacent or mixed-dollar spans could fuse into $$ and change inline math into display math. The normalization path now protects text bodies and inserts a separator only where two dollar boundaries would collide: escaped-inline-math.ts lines 482-510. This covers adjacent expressions, $5 next to math, and nested Markdown wrappers.

  4. Existing LaTeX preprocessing crossed code and Markdown container boundaries. Fences in lists or quotes, indented code, open inline-code tails, and link destinations could be rewritten as math. Code-region discovery now masks block code, scopes inline spans to Streamdown blocks, and retains the simple-fence fast path: latex.ts lines 99-211. Delimiter conversion checks both ends against code and link regions and preserves list indentation for display math: latex.ts lines 530-608.

  5. Streamdown split reference uses from their definitions, so [math][math-ref] could stay literal even when the definition existed later in the response. The scheduler now renders replies containing a reference use and definition as one Markdown document: streaming-render-schedule.ts lines 69-100.

  6. A 29-byte SSE boundary exposed a stale Streamdown cache. The stream first supplied [math-ref]: without a destination, then appended the URL. The old Boolean document key did not change, so the completed definition reused the incomplete parse. markdownRenderKey now includes reference-definition lines, and Streamdown remounts when they change: streaming-render-schedule.ts lines 82-94, markdown-text.tsx lines 772-808.

Verification:

  • 68 focused parser, LaTeX, list, code-region, streaming corpus, retro-edit, and scheduler tests passed.
  • 5 focused render-source scheduling tests passed after the final cache fix.
  • The existing long-stream cost regression passed in 2.98 seconds.
  • TypeScript typecheck passed.
  • Playwright A/B used isolated merge-base and head installs, Chromium, the real provider/chat/runtime/Streamdown/KaTeX path, and the exact same realistic response split into 41 SSE chunks.
  • Merge base produced 1 KaTeX node in streaming and completed states. Final head produced 16 in both states, with 0 KaTeX errors.
  • DOM assertions covered list items, normal prose, currency, inline code, fenced code, links and reference links, incomplete code and math delimiters, escaped dollars, display math, nested Markdown, comparison operators, and realistic model output.
  • The reference link resolved in both streaming and completed states. Raw code math stayed non-KaTeX, the incomplete code tail stayed inline code, currency stayed text, and display math stayed display math.
  • Labelled before/after screenshots were captured and inspected for streaming and completed states.
  • Final focused fork CI passed affected tests on Ubuntu and Windows plus Linux typecheck and production build: run 33230274872.

The remaining broad-workflow failures reproduce in unchanged upstream areas: five audio source-assertion tests, two Python dependency scans, and the MCP fixture waiting on a disabled button. The focused Markdown run, build, typecheck, lint, Linux chat UI, and relevant package audits pass.

@mahiatlinux mahiatlinux left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Verified escaped inline math end to end, fixed confirmed parser and streaming regressions, and validated the final head with focused cross-platform CI and Playwright evidence.

@mahiatlinux

Copy link
Copy Markdown
Contributor

All reviewed and fixed, LGTM. CI results

@mahiatlinux
mahiatlinux merged commit e584ffc into unslothai:main Aug 29, 2026
30 of 42 checks passed
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@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: e584ffc49f

ℹ️ 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 on lines +343 to +344
item = nested;
itemIndent = contentColumn + relativeIndent;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Track emptiness of the innermost same-line item

When a same-line nested item is empty, such as - -, this loop records the inner content column but openLists still computes emptyItem from the outer marker, whose remaining text is -. The following blank line therefore leaves the empty inner item open rather than dropping it as the existing blank-line logic requires. For example, in - -\n\n \\(x\\), the six-space line should be indented code relative to the still-open outer item, but the stale inner column makes it ordinary text, so findCodeBlockRegions allows preprocessLaTeX and search-image rewriting to modify code content. Return or otherwise propagate whether the final nested marker is empty.

Useful? React with 👍 / 👎.

Comment on lines +263 to +269
const start: State = (code) => {
const previousToken = this.events.at(-1)?.[1];
if (
code !== BACKSLASH ||
isInHtmlLiteral(this) ||
isInLatexBracketMath(this) ||
(this.previous === DOLLAR && previousToken?.type !== TOKEN)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Respect escaped backslashes before math openers

When an escaped-dollar sequence is itself escaped in Markdown, such as three backslashes before each dollar in \\\$x\\\$, micromark first consumes the initial backslash pair as a literal backslash and then invokes this construct on the third backslash. Because the start guard does not reject a backslash immediately following that escape token, the remaining \$x\$ is normalized into active math, changing text intended to render literally as \$x\$ into KaTeX. Check the preceding escape/run parity before accepting the opener.

Useful? React with 👍 / 👎.

danielhanchen added a commit that referenced this pull request Aug 30, 2026
…ordless pip install (#9959)

* Fix three CI regressions: code-span anchor, load-dispatch anchor, recordless pip install

Three unrelated failures, all reproduced locally first.

1. tests/studio/test_update_release_notes.py::test_code_span_closers_ignore_backslashes

   #9796 moved the code-span scanner into scanCodeSpans, which is defined ABOVE
   `export function codeSpans`. The test sliced the file from that export and
   counted `escaped(text` in the remainder, so the count went from 1 to 0 and
   the assertion "only an opener can be escaped" fired on a file where exactly
   one opener is still the only escaped thing. Count over the whole module and
   check the surviving call guards the opening run, so a wrapper moving again
   cannot read as "no opener is escaped either".

2. studio/backend/tests/test_parallel_slots_per_load.py::test_route_resolves_slots_once_before_dedupe_guard_and_load

   The GGUF load moved into _run_gguf_load_attempt, a health-wait helper defined
   above _load_model_impl, so `llama_backend.load_model` left the function body
   and .index() raised ValueError. Every ordering the test guards still holds.
   Anchor on whichever call the body dispatches a load through instead of on one
   backend's method name.

3. startup windows-latest

   pip will not replace a distribution whose .dist-info carries no RECORD, and an
   interrupted install leaves exactly that. The job reuses its venv, so the stub
   is not transient: once written, every later run dies the same way on
   "Cannot uninstall pydantic-core / no RECORD file was found". pip_install now
   retries once after clearing only the distributions pip named as unremovable,
   and only when it named one. pip's own hint is --ignore-installed, which would
   apply to every package in the command and skip real upgrades with it.

run() grows check=False so pip_install can inspect a failure instead of exiting
inside it; every existing caller keeps the old exit-on-failure behaviour.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Mirror the StageRoot branch into install.ps1's shared copy

#9890 added staging support to studio/setup.ps1 and put an early
`if ($StageRoot)` return inside Get-ManagedLlamaCppDir, which sits in the block
install.ps1 holds a byte-identical copy of. The copy never got it, so
test_denied_llama_cpp_preflight.py failed on exactly the drift it exists to
catch, taking Repo tests (CPU) down with it.

install.ps1 never assigns $StageRoot, and it runs under Set-StrictMode -Off from
line 25 onwards, so the read is $null there and the branch is inert. Parity is
what the block is for: the copies have to match or the next person edits one of
them and only finds out in production.

---------

Co-authored-by: danielhanchen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
danielhanchen added a commit that referenced this pull request Aug 30, 2026
findInlineCodeRegions masks every block region to spaces and rescans the result for code spans. When no backtick sits outside a block region that mask cannot contain one, so the scan can only return nothing and the rebuild is spent to learn that.

The streaming path calls this once per frame over a growing prefix, and preprocessLaTeX calls findCodeBlockRegions twice per frame, so the mask is O(n) per frame and O(n^2) over a reply.

Recovers most of the regression #9796 introduced: on the streaming-latex-retro-edit fixture the math arm goes from 217ms to 136ms and the measured ratio from 3.35x to 2.11x, against 1.5x before #9796.

The new test pins both directions, since an early return that fires too eagerly would look like a pure win.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants