Skip to content

feat: add KaTeX rendering and markdown parsers for AI answers 📝 - #916

Closed
Wisesofthemall wants to merge 2 commits into
colorstackorg:mainfrom
Wisesofthemall:ask-ai-formatting/2-parsers
Closed

Wisesofthemall wants to merge 2 commits into
colorstackorg:mainfrom
Wisesofthemall:ask-ai-formatting/2-parsers

Conversation

@Wisesofthemall

@Wisesofthemall Wisesofthemall commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Description ✏️

Part 2 of 3 for #914. Depends on #915. The PR comes from a fork, so it can't be stacked on #915's branch, and its diff includes #915's commit. Please review only the last commit, 6111c37, until #915 merges. Nothing uses this code yet; PR 3 switches it on.

This PR turns raw AI output into structured tokens a renderer can map to elements. Everything lives in packages/utils/src/ai-formatting/:

  • katex.ts: safeKatexRender(latex, displayMode), exported as @oyster/utils/katex so that the main entry doesn't pull in KaTeX.

    • It fixes stray braces, normalizes, then calls katex.renderToString with throwOnError: true.
    • On any error it returns the escaped LaTeX source instead of KaTeX's red error output.
    • Adds katex (0.19) as a dependency of @oyster/utils.
  • preprocess.ts: preprocessContent runs once on the whole answer:

    • converts \(...\) to $...$ and \[...\] to $$...$$
    • converts HTML math spans the model sometimes emits
    • strips stray HTML tags and a leading "Here's the answer" line
    • masks code fences first, so none of this touches code
  • inline.ts: parseInline produces tokens for bold, italic, inline code, math, [ref:N] citations and http(s) links.

    • Inline code is masked before anything else runs, so `price = $5` is never treated as math.
    • Bold is parsed first and outermost, so **solve $x^2$** keeps both the bold and the math.
    • Single-$ math comes from the scanner added in feat: add math core for formatting AI answers 🧮 #915, never from a regex.
    • Italics need flanking and digit guards, so the asterisks in 5 * 3 * 2 are left as text.
  • blocks.ts: parseAiMarkdown is a line-by-line parser for:

    • fenced code
    • $$ display math (on one line, with trailing text, or across lines)
    • headings, blockquotes, horizontal rules and tables (with math in cells)
    • lists; ordered lists keep their start number
    • paragraphs

    Images are shown as links, so the page never loads arbitrary image URLs.

This uses a small hand-written parser instead of a library like marked, for two reasons:

  • [ref:N] citations have to render as React components in the middle of a sentence.
  • The prose never goes through dangerouslySetInnerHTML; only KaTeX's own escaped output does.

Screenshots 📸

These were taken locally on the /ask-ai page with the full stack (#917) applied. A sample answer was stored in Redis so the page renders it without calling the AI. The sample's markdown source is in the collapsed section below the image.

Markdown parsing: headings, every list style (including a numbered list that starts at 4), a quote, a divider, a table, a code block, a link, and an image shown as a link:

Markdown kitchen sink

Sample answer source (2-markdown-kitchen-sink.md)
# Heading 1
## Heading 2
### Heading 3
#### Heading 4

A paragraph with **bold**, *italic*, **bold with *italic* inside**, `inline code` and a [link](https://www.colorstack.org) [ref:1].

- Bullet with **bold** at the start
- Bullet with a reference at the end [ref:2]
* Star bullet
• Dot bullet

1. First numbered item
2. Second numbered item with `code`
3. Third numbered item [ref:3]

Some text between lists.

4. A list that starts at 4
5. And continues at 5

> A quote from a Slack thread.
> It keeps going on a second line.

---

| Company | Interview rounds | Notes |
|---|:---:|---|
| Google | 4 to 5 | **Hard** but fair [ref:1] |
| Meta | 3 | Focus on *speed* |
| Startup | 2 | `take-home` project |

```python
def two_sum(nums, target):
    seen = {}
    for i, n in enumerate(nums):
        if target - n in seen:
            return [seen[target - n], i]
        seen[n] = i
```

![ColorStack logo](https://www.colorstack.org/logo.png)

Math with KaTeX: inline, inside bold, display, multi-line cases, in table cells, $7.23$ shown as 7.23, a repaired missing brace, and an invalid command shown as its source (no red error):

Math rendering Math rendering on mobile

On a 390px-wide phone the page doesn't scroll sideways (checked in headless Chrome).

Sample answer source (3-math.md)
**Time complexity** cheat sheet [ref:1]:

- Binary search: \(O(\log n)\)
- Merge sort: \(O(n \log n)\)
- Two nested loops: \(O(n^2)\)
- **Bold with math:** \(T(n) = 2T(n/2) + O(n)\)

The sum of the first \(n\) numbers is:

\[ \sum_{i=1}^{n} i = \frac{n(n+1)}{2} \]

A multi-line display block:

$$
f(n) = \begin{cases} 1 & n = 0 \\ n \cdot f(n-1) & n > 0 \end{cases}
$$

Dollar-sign math also works: $x^2 + y^2 = z^2$, $f(x)$ and $2x < 4$.

Inline $$a^2 + b^2$$ in a sentence, and the mean was $7.23$.

| Algorithm | Best | Worst |
|---|---|---|
| Quick sort | \(O(n \log n)\) | \(O(n^2)\) |
| Heap sort | \(O(n \log n)\) | \(O(n \log n)\) |

A missing brace gets fixed: \(\frac{1}{2\)

Broken LaTeX shows its source instead of a red error: \(\notacommand{x}\)

Test cases 🧪

Run with cd packages/utils && bun test (no database needed). 98 pass, 0 fail (60 from #915 plus 38 new).

Input Result
\(x^2\) / \[ \int f \] inline math / display math
\frac{ (invalid) <span class="math-fallback">\frac{</span>, never the red KaTeX error
w = abba \in \Sigma^*} renders (stray } dropped)
$w \in \Sigma^*$ and $L \subseteq \Sigma^*$ two formulas, no italics from the *s
5 * 3 * 2 plain text, no italics
**solve $x^2$** bold containing math
the mean was $7.23$ the mean was 7.23
Costs $5, $10, $20 and $x$. prices stay as text, only x is math
Run `price = $5` inline code, untouched
fenced code containing x = $x$ * 2 code block, verbatim
```mermaid with A[Mean ($\mu$)] source unchanged
A{p < 0.05?} --> B in a fence survives the HTML strip
<b>Note</b>: 2 < 3 and 5 > 4 Note: 2 < 3 and 5 > 4
1. **Apply early** [ref:2] ordered list item with bold and a citation
table row with $O(n \log n)$ math inside the cell
[click](javascript:alert(1)) plain text, not a link
Full test output (new tests)
src/ai-formatting/katex.test.ts:
(pass) safeKatexRender > Should render valid LaTeX.
(pass) safeKatexRender > Should render display math.
(pass) safeKatexRender > Should show the escaped source instead of the KaTeX error.
(pass) safeKatexRender > Should escape HTML in the fallback.
(pass) safeKatexRender > Should drop a stray closing brace and render.
src/ai-formatting/blocks.test.ts:
(pass) parseAiMarkdown > Should parse paragraphs and skip blank lines.
(pass) parseAiMarkdown > Should parse headings, longest prefix first.
(pass) parseAiMarkdown > Should parse unordered and ordered lists.
(pass) parseAiMarkdown > Should parse references inside list items.
(pass) parseAiMarkdown > Should parse fenced code verbatim.
(pass) parseAiMarkdown > Should keep mermaid source unchanged and drop empty fences.
(pass) parseAiMarkdown > Should parse display math on one line, with trailing text.
(pass) parseAiMarkdown > Should parse display math across lines.
(pass) parseAiMarkdown > Should parse \[ \] as display math.
(pass) parseAiMarkdown > Should parse blockquotes and start a new one on > ".
(pass) parseAiMarkdown > Should parse horizontal rules.
(pass) parseAiMarkdown > Should show images as links.
(pass) parseAiMarkdown > Should parse tables, with math in the cells.
(pass) parseAiMarkdown > Should parse a table without a separator row as body rows.
src/ai-formatting/preprocess.test.ts:
(pass) preprocessContent > Should convert \( \) to inline math.
(pass) preprocessContent > Should convert \[ \] to display math, across lines.
(pass) preprocessContent > Should strip the leading filler line.
(pass) preprocessContent > Should convert HTML math to $ delimiters.
(pass) preprocessContent > Should strip HTML tags but keep comparisons in prose.
(pass) preprocessContent > Should not touch fenced code.
(pass) preprocessContent > Should not convert \( inside fenced code.
src/ai-formatting/inline.test.ts:
(pass) parseInline > Should keep multiplication asterisks as text.
(pass) parseInline > Should keep math inside bold.
(pass) parseInline > Should not turn the * in two formulas into italics.
(pass) parseInline > Should keep the stray brace inside the math for KaTeX to fix.
(pass) parseInline > Should show a bare number wrapped in $ as plain text.
(pass) parseInline > Should treat $$ in a sentence as inline math.
(pass) parseInline > Should keep prices as text.
(pass) parseInline > Should not touch the contents of inline code.
(pass) parseInline > Should parse italics.
(pass) parseInline > Should fold typographic asterisks, but not the ∗ operator.
(pass) parseInline > Should parse thread references and links.
(pass) parseInline > Should not parse links that are not http(s).

 98 pass
 0 fail
Ran 98 tests across 6 files.

Type of Change 🐞

  • Feature - A non-breaking change which adds functionality.
  • Fix - A non-breaking change which fixes an issue.
  • Refactor - A change that neither fixes a bug nor adds a feature.
  • Documentation - A change only to in-code or markdown documentation.
  • Tests - A change that adds missing unit/integration tests.
  • Chore - A change that is likely none of the above.

Checklist ✅

  • I have done a self-review of my code.
  • I have manually tested my code (if applicable).
  • I have added/updated any relevant documentation (if applicable).

🤖 Generated with Claude Code

Wisesofthemall and others added 2 commits November 4, 2026 04:36
Adds the pure math helpers that decide which `$...$` spans are math and
which are prices, plus code masking and LaTeX cleanup. Nothing uses them
yet; they are the first piece of the fix for colorstackorg#914.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Adds `safeKatexRender` (falls back to the escaped source instead of
KaTeX's red error output), `preprocessContent` (normalizes `\(...\)` and
`\[...\]` to `$`/`$$` and strips stray HTML, never touching code), and the
inline and block parsers that turn raw AI output into tokens a renderer
can map to elements. Nothing uses them yet. Part of colorstackorg#914.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Wisesofthemall

Copy link
Copy Markdown
Contributor Author

Closing in favor of #918, which uses react-markdown instead of our own parsing logic, per the review feedback. Thanks!

@Wisesofthemall
Wisesofthemall deleted the ask-ai-formatting/2-parsers branch November 7, 2026 04:00
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.

1 participant