Skip to content

Studio: render \[ \] and \( \) LaTeX delimiters in chat - #6914

Merged
oobabooga merged 3 commits into
unslothai:mainfrom
oobabooga:studio-latex-bracket-delimiters
Jul 7, 2026
Merged

oobabooga merged 3 commits into
unslothai:mainfrom
oobabooga:studio-latex-bracket-delimiters

Conversation

@oobabooga

Copy link
Copy Markdown
Member

Models often write math with \[ ... \] (display) and \( ... \) (inline) delimiters, but the chat renderer showed them as literal text instead of equations. For example, \[ A = P e^{r t} \] rendered as [ A = P e^{r t} ].

The renderer uses remark-math, which only understands $...$ and $$...$$. preprocessLaTeX already ran on every message (to escape currency $), but it didn't touch bracket delimiters.

Reproduction

In Studio chat, tell the model to reply with the text below verbatim:

Compound interest has two standard forms: periodic compounding and the continuous limit.

**1. Periodic Compounding**
The balance after compounding \( n \) times per year is:

\[
A = P \left(1 + \frac{r}{n}\right)^{n t}
\]

*   \( P \) = principal
*   \( r \) = annual interest rate

**2. Continuous Compounding**
Taking the limit as \( n \to \infty \) gives:

\[
A = P e^{r t}
\]

*   \( e \) = Euler's number
*   \( t \) = time in years

On main the equations show as literal [ ... ] and ( ... ). With this change they render as math.

Fix

preprocessLaTeX now converts the bracket forms to dollar forms before the currency pass, so remark-math renders them:

  • \(...\) becomes inline $...$
  • \[...\] becomes a $$ block on its own lines (so it renders as a centered block, not inline)

It skips anything inside code blocks/spans, leaves escaped \\[ alone, and doesn't change existing $/$$ math or currency handling.

Verification

Reproduced with the text above (equations render after the change, literal before). Also ran ~85 cases through the real remark-math + rehype-katex pipeline covering the conversions, code blocks, currency, and malformed input. Lint and typecheck clean.

@gemini-code-assist gemini-code-assist Bot 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.

Code Review

This pull request introduces a preprocessing step to convert LaTeX bracket delimiters (\[...\] and \(...\)) into dollar-sign delimiters ($$...$$ and $...$) so they can be correctly tokenized by remark-math. It also updates the currency escaping logic to ignore these newly converted math regions, preventing false positives. There are no review comments, and the implementation looks solid, so I have no additional feedback to provide.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

@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: 4ad8aad171

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

Copy link
Copy Markdown
Member Author

@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: 3798aa0a05

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

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

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

ℹ️ About Codex in GitHub

Codex has been enabled to automatically 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 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

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

Copy link
Copy Markdown
Member Author

Thanks. I tested all five against the real render pipeline; four reproduce, one does not. Verdicts:

L81: Does not reproduce. tsc -b exits 0: in TS 5.9.3, RegExpIndicesArray extends Array<[number, number]>, so the element is not optional, and noUncheckedIndexedAccess is off. The build is not blocked.

L30: Real but self-healing: the moment the closing fence streams in, the content is left literal. Treating an unclosed opener as code-to-EOF would let one stray triple-backtick permanently swallow all math after it, which is a worse failure. Leaving as is.

L297: Real, but the math still renders, just detached from the list item. Reproducing container indentation in a string pass risks turning $$ into a code block at 4+ spaces, breaking the equation entirely. If this becomes a real complaint the right fix is a remark plugin, not more string surgery.

L66: Real parity gap with the inline-link protection, but the trigger (a URL literally containing \(...\)) is close to nonexistent in chat output. Deferring; easy to fold in if it ever shows up.

L220: This is the feature's inherent ambiguity. No body check separates \[1\] citations from real math like \[6\] or \[dx\], so any gate silently breaks real equations, a worse failure than a rare citation rendering as math. Keeping unconditional conversion, same as upstream LibreChat.

@oobabooga

Copy link
Copy Markdown
Member Author

CI is green, merging oobabooga#23

@oobabooga
oobabooga merged commit 93c9d6d into unslothai:main Jul 7, 2026
36 checks passed
Comment on lines +68 to +84
/**
* Find the destination spans of inline links/images, so a `\(...\)` written with
* escaped parens inside a URL isn't rewritten as math (which would break the
* link). Only the destination is returned, not the link text, so math in the
* visible text still converts. Sorted, non-overlapping (matches are disjoint).
*/
function findLinkDestinationRegions(content: string): Array<[number, number]> {
if (!content.includes("](")) return [];
const regions: Array<[number, number]> = [];
let match: RegExpExecArray | null;
LINK_DEST_RE.lastIndex = 0;
while ((match = LINK_DEST_RE.exec(content)) !== null) {
// `indices` is present (the `d` flag); group 1 spans the destination.
regions.push(match.indices![1]);
}
return regions;
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Reference-link definition URLs are not skipped, so a model that emits a reference definition whose URL contains escaped parens ([1]: https://example.com/a\(b\)) has that URL rewritten to .../a$b$. This extends findLinkDestinationRegions to also skip reference-definition destinations (bare and <...> forms), matching the existing inline-link handling. Verified locally: the 32 isolated + 27 render cases stay green and tsc (5.9.3, project config) is clean.

Suggested change
/**
* Find the destination spans of inline links/images, so a `\(...\)` written with
* escaped parens inside a URL isn't rewritten as math (which would break the
* link). Only the destination is returned, not the link text, so math in the
* visible text still converts. Sorted, non-overlapping (matches are disjoint).
*/
function findLinkDestinationRegions(content: string): Array<[number, number]> {
if (!content.includes("](")) return [];
const regions: Array<[number, number]> = [];
let match: RegExpExecArray | null;
LINK_DEST_RE.lastIndex = 0;
while ((match = LINK_DEST_RE.exec(content)) !== null) {
// `indices` is present (the `d` flag); group 1 spans the destination.
regions.push(match.indices![1]);
}
return regions;
}
/**
* Match a reference-link definition `[label]: DEST`, capturing the destination
* (group 1 for an angle `<...>` form, group 2 for a bare run) with the `d` flag.
* Anchored to line start (`m`) so only true definitions match. Escaped parens in
* such a URL are valid CommonMark and must not be rewritten as math.
*/
const REF_DEF_DEST_RE =
/^ {0,3}\[(?:\\.|[^\]\n\\])+\]:[^\S\n]*(?:<([^>\n]*)>|([^\s<][^\s]*))/gmd;
/**
* Find the destination spans of inline links/images and reference-link
* definitions, so a `\(...\)` written with escaped parens inside a URL isn't
* rewritten as math (which would break the link). Only the destination is
* returned, not the link text, so math in the visible text still converts.
* Sorted for isInRegion's binary search.
*/
function findLinkDestinationRegions(content: string): Array<[number, number]> {
const hasInline = content.includes("](");
const hasRefDef = content.includes("]:");
if (!hasInline && !hasRefDef) return [];
const regions: Array<[number, number]> = [];
let match: RegExpExecArray | null;
if (hasInline) {
LINK_DEST_RE.lastIndex = 0;
while ((match = LINK_DEST_RE.exec(content)) !== null) {
// `indices` is present (the `d` flag); group 1 spans the destination.
regions.push(match.indices![1]);
}
}
if (hasRefDef) {
REF_DEF_DEST_RE.lastIndex = 0;
while ((match = REF_DEF_DEST_RE.exec(content)) !== null) {
const span = match.indices![1] ?? match.indices![2];
if (span) regions.push(span);
}
}
// Inline-link and reference-def spans can interleave, so sort (they never
// overlap: a definition line is not also an inline destination).
regions.sort((a, b) => a[0] - b[0]);
return regions;
}

continue;
}
append(content.slice(last, match.index));
const wrapped = isDisplay ? `\n$$\n${body}\n$$\n` : `$${body}$`;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

When \[...\] sits inside an indented container (a list item or blockquote), the $$ fence is emitted at column 0, so the display block breaks out of the container (e.g. - step:\n \[x\] renders the equation outside the list). This preserves the opener line's leading indentation for the block, guarded to only trigger when the opener is preceded solely by whitespace, so inline (text \[x\]) and column-0 uses stay byte-identical. Verified against the existing cases.

Suggested change
const wrapped = isDisplay ? `\n$$\n${body}\n$$\n` : `$${body}$`;
let wrapped: string;
if (isDisplay) {
// Preserve the opener line's leading indentation so a display block that
// sits inside a list item (or other indented container) stays within it;
// a `$$` fence forced to column 0 would break out of the container. Only
// applied when the opener is preceded solely by whitespace on its line so
// inline uses (`text \[x\]`) keep the column-0 form.
const lineStart = content.lastIndexOf("\n", match.index - 1) + 1;
const prefix = content.slice(lineStart, match.index);
const indent = /^\s*$/.test(prefix) ? prefix : "";
wrapped = `\n${indent}$$\n${indent}${body}\n${indent}$$\n`;
} else {
wrapped = `$${body}$`;
}

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 8, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Jul 8, 2026
danielhanchen added a commit that referenced this pull request Jul 8, 2026
…6957)

* Studio: fix link, currency and indentation edge cases in LaTeX rendering

Follow-up to #6914. Three fixes to studio/frontend/src/lib/latex.ts:

- Skip reference-link definition URLs ([id]: url) during delimiter
  conversion, so escaped parens in such URLs are not rewritten as math.
- Preserve the opener line's indentation when emitting a display $$ block,
  so a \[...\] inside a list item stays part of the list.
- Stop a currency amount from pairing with a converted span's opening $,
  which swallowed the price into math (for example $5 + x \(y\)).

* Exclude GFM footnote definitions from the reference-URL skip

A footnote definition like [^1]: \(x\) had its body treated as a link
destination, so leading math was left literal. Skip [^...] labels.

* Merge overlapping link destination regions

A reference-def token can nest inline-link spans (for example
[1]: http://h/[a](b)/foo\(x\)), so the combined spans could overlap and
isInRegion's binary search missed the outer one, rewriting the URL. Merge
overlapping spans before the search.

* Guard lineStart when the display opener is at index 0

Behavior is unchanged (lastIndexOf clamps a negative fromIndex to 0), but
the explicit guard avoids relying on that implicit clamp.

* Scope to indentation and currency fixes

Drop the reference-link URL protection added earlier. It guards a case
models effectively never emit (escaped parens in a reference-style URL),
and approximating CommonMark reference definitions with a regex needs
open-ended special-casing. Keep the two high-value fixes: preserve display
math indentation (including multi-line bodies) inside a list item, and stop
a currency amount from pairing with a converted span's opening dollar sign.
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.

2 participants