Skip to content

fix(editor): stop the rich markdown editor from mangling dollar-heavy files - #20406

Open
averydev wants to merge 6 commits into
stablyai:mainfrom
averydev:fix/rich-markdown-dollar-escapes
Open

averydev wants to merge 6 commits into
stablyai:mainfrom
averydev:fix/rich-markdown-dollar-escapes

Conversation

@averydev

@averydev averydev commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

Open a markdown file full of dollar amounts in Orca's rich editor and it gets reformatted on the spot: escaped characters vanish, money turns into math equations, and the first save rewrites the whole file. This PR makes the editor read those files faithfully and write back only what you changed.

What Changed

  • rich-markdown-escaped-character.ts (new): a non-inclusive mark that owns marked's escape rule. \X parses to the character X carrying the mark, and the serializer-fidelity pass writes marked text back as \X per character, so escapes round-trip byte for byte inside table cells, links, emphasis, and list items. Inside a code mark the character is emitted bare; & < > are left to the serializer's entity encoding. A plain text node cannot do this (Tiptap 3.22.5's text serializer has no re-escape hook), an atom node cannot either (the serializer closes every active mark before a non-text node, so **cost \$5 total** split into **cost **\$**5 total**), and a mark's own renderMarkdown is one prefix for the whole run (\*\* would collapse to \**), hence the wrapper.
  • rich-markdown-serializer-fidelity.ts (new): wraps getMarkdown and rewrites the document JSON into its source form before Tiptap serializes it. Besides the escaped-character expansion it re-escapes | in table cell text (marked unescapes \| per cell before inline lexing, so a bare | split the row on the next load), escapes ( and ) in link and image destinations ([a](b\)c) came back as [a](b)c)), [ ] \ in image alt text, and " in titles.
  • rich-markdown-extensions.ts: BlockMath gets a start that only fires at a line start. marked ends a paragraph wherever a block tokenizer's start points, and upstream used indexOf('$$'), so costs $$ big split the paragraph.
  • rich-markdown-extensions.ts: InlineMath gets a Pandoc-style tokenizer. Both $ must touch the formula, the closing $ must not be followed by a digit, and an escaped \$ never closes a formula (costs $5 to \$x stays text). $E = mc^2$, $x_1$, a formula wrapped across a soft line break, and a trailing \\ still parse; $10 to $20, at $0, $x$2, $ x$, $x $ stay text. Known hole, same as Pandoc: price $5-$x still parses as math.
  • rich-markdown-source-reconcile.ts: when the source ends in exactly one newline that canonical lacks, branch 4 first patches the newline-stripped bodies and re-attaches the run; if that fails the branch-5/6 proof (a whitespace-only last line, for instance), it retries the whole-text patch that ran before, so no file does worse than before and the extra round trip only runs on that failure. A source ending in a blank line parses to a trailing empty paragraph, so canonical ends in \n\n too and goes straight to the whole-text patch. Canonical fallbacks now keep the source's single trailing newline instead of dropping it.

Why

Open a markdown file with dollar amounts (a finance doc, invoices, tax notes) in the rich editor and it is reformatted on load; the first save then rewrites the entire file.

  1. Backslash escapes are deleted on load. marked emits an escape inline token for \$, \*, \_, \[, and @tiptap/markdown 3.22.5 has no case for it, so the character is gone from the document the moment the file opens. cost was \$1,200 displays and saves as cost was 1,200.
  2. Money renders as math. The @tiptap/extension-mathematics tokenizer treats any same-line $…$ pair as LaTeX. (deficit −$509,542 by end-2020), so stock basis entered 2021 at $0 becomes one KaTeX atom, and because the latex is trimmed it serializes back as at$0.
  3. Any edit at the end of the file rewrites the whole file. In reconcileSerializedMarkdown, getMarkdown() emits no trailing newline for a source that ends in a single newline, while the on-disk source normally has one. For an end-of-document hunk the diff-match-patch context is end-of-text padding, so the patch lands one character late, the branch-6 round-trip proof fails, and the code falls back to canonical output for the entire document: every \$, every & → &amp;, every table re-padded. Middle-of-document edits were fine. Reproduces on a 57-character file.

Linked Issue

Fixes #20425

Visual Proof

Same fixture file opened in the rich editor, captured headless through the e2e harness (ORCA_BACKGROUND_LAUNCH=1, Playwright CDP) against the base commit 403b62a and against this branch.

Before (403b62a) After (this branch)
pr20406-before-rich-editor.png pr20406-after-rich-editor.png

Before: the $509,542 … at $0 span renders as italic KaTeX, every \$ is gone (cost was 1,200, Total: 1,235, Distribution 500). After: the file reads as written.

The same run then typed Added. at the end of the document and saved. What reached disk:

Fixture as opened
# Shareholder basis

(deficit −$509,542 by end-2020), so stock basis entered 2021 at $0.

Escaped: cost was \$1,200 and the fee was \$35 per filing. **Total: \$1,235** due.

R&D credits for Nell & Mary, 2018 & 2020.

| Item         | Amount |
|--------------|-------:|
| Basis        | $1,000 |
| Distribution | \$500  |

Trailing paragraph.
Before: whole file rewritten on save
# Shareholder basis

(deficit −$509,542 by end-2020), so stock basis entered 2021 at$0.

Escaped: cost was 1,200 and the fee was 35 per filing. **Total: 1,235** due.

R&amp;D credits for Nell &amp; Mary, 2018 &amp; 2020.


| Item         | Amount |
| ------------ | ------: |
| Basis        | $1,000 |
| Distribution | 500    |


Trailing paragraph. Added.
After: only the edit changed
# Shareholder basis

(deficit −$509,542 by end-2020), so stock basis entered 2021 at $0.

Escaped: cost was \$1,200 and the fee was \$35 per filing. **Total: \$1,235** due.

R&D credits for Nell & Mary, 2018 & 2020.

| Item         | Amount |
|--------------|-------:|
| Basis        | $1,000 |
| Distribution | \$500  |

Trailing paragraph. Added.

Testing

  • markdown-round-trip.test.ts: a battery of escapes (\$ \# 1\. \- \*\* \_ \ ~ \), including escapes inside bold, links, emphasis, and consecutive escapes inside bold, round-trips byte for byte and is stable on a second round trip; escapes under a code mark serialize bare and &/<fall back to entity encoding;|in table cells (code spans included),)in destinations,]in alt text, and"in titles round-trip; a mid-line$$no longer splits a paragraph while a$$` block still parses; escaped dollars survive in table cells and never become math; dollar amounts and the Pandoc-rejected shapes produce zero inline-math nodes; real inline math, wrapped math, and a trailing LaTeX line break still parse.
  • rich-markdown-source-reconcile.test.ts: end-of-file edits with a trailing-newline source (LF and CRLF), a source without a trailing newline, a real-serializer case with \$, & and a padded table that must keep its source bytes, typing into and deleting a trailing empty paragraph and appending after a whitespace-only last line (the shapes the first commits regressed), and a canonical fallback keeping the trailing newline.

pnpm tc, the full src/renderer/src/components/editor suite (1445 tests), check:code-quality:changed, check:max-lines-ratchet, and check:reliability-gates pass.

Tested on macOS. The change is renderer-side markdown parsing and serialization with no platform-specific code path; SSH and folder workspaces run the same renderer code, and nothing on the wire changes.

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

AI Disclosure

Written with Claude (Claude Code): investigation, fix, tests, and two adversarial three-agent review rounds whose findings were each reproduced with the real serializer before being acted on. Directed and reviewed by the author.

Review

AI code review summary (Claude Code, two adversarial three-reviewer rounds plus a final pass on the head commit):

  • Cross-platform (macOS / Linux / Windows): pure TypeScript in the renderer, no path or shell code. CRLF sources are covered by the reconcile tests (end-of-file edit, whitespace-only last line). No platform-specific risk found.
  • SSH / remote / local: the reconcile and serializer run in the renderer for local and remote files alike. No RPC params, stream frames, or published content change, so mixed client/host versions are unaffected. A whole-file canonical rewrite over SSH was the pre-existing cost this PR removes.
  • Agents and integrations: the rich editor extension set is shared by the live editor, rich-mode eligibility, and the reconcile serializer, and all three still build from createRichMarkdownExtensions, so detection and serialization cannot drift. The GitHub and Linear markdown composers use their own extension sets and are untouched. The markdown preview (remark-math) is unchanged and still renders $10 to $20 as math; that mismatch with the editor is noted below.
  • Performance: the inline-math regex has no ambiguous alternation and measured within noise of upstream on 20 KB lines and 5,000 dollar pairs; the block-math start pattern is a single scan per paragraph; the extra reconcile round trip runs only when the first patch attempt fails its proof. marked's pre-existing quadratic scan on underscore-heavy 100 KB paragraphs is unchanged.
  • UI quality: escaped characters render as ordinary text (a non-inclusive mark on a plain <span>), so cursor movement, Backspace, selection, copy, and find/replace behave as for any text. Money no longer renders as a KaTeX atom.
  • Security: no new inputs cross a trust boundary. The serializer pre-pass rewrites document JSON already in memory; the escape mark's parseHTML accepts only its own marker span and carries no attribute payload.
  • Review findings acted on: round one found the escape fix was parse-side only, the body-strip reconcile regressed blank-line-terminated files, and the math regex broke wrapped formulas; round two found an escape atom split any mark spanning it and disabled find/replace near it, a whitespace-only last line still fell to canonical, and an escaped \$ could close a formula. Each is fixed in a later commit with a regression test.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

  • Backwards compatibility: files that never held escapes, money-shaped $ pairs, or end-of-file edits serialize exactly as before; the reconcile keeps the previous whole-text patch as its second attempt so no file does worse than before.
  • Behaviour change worth a changelog line: $ x $ with spaces inside the delimiters is now text, per Pandoc's rule; upstream rendered it as math.
  • Out of scope, pre-existing on the base branch and unchanged here:
    • & → &amp; and table re-padding are still what the canonical serializer emits; the reconcile fix keeps them out of untouched regions, but a real edit inside such a line still canonicalizes that line.
    • Pre-existing on the base branch and unchanged here: a \+newline hard break is re-emitted as two spaces plus newline (same meaning); \[ \] inside link text comes back as bare balanced brackets (same meaning); marked's inline text scan is quadratic on underscore-heavy paragraphs (about 7 s at 100 KB, inside marked itself); an angle-bracket destination [a](<b c>) is treated as inline HTML by Orca's raw-HTML pass.
    • Upstream @tiptap/markdown 3.31.3 also fixes the escape drop. This PR does not bump TipTap.
    • The markdown preview's remark-math single-dollar handling is unchanged, so preview and editor disagree on $10 to $20.

Author

Elon musk is a nazi and I don’t use nazi software

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

… files

Opening a markdown file full of dollar amounts in rich mode reformatted it
on load, and any save then rewrote the whole file:

- marked emits an `escape` inline token for `\$`, `\*`, `\_`, `\[`; Tiptap's
  markdown parser has no case for it, so the escaped character was deleted
  from the document as soon as the file opened. The marked facade now
  rewrites escape tokens to text tokens, in place, so table cells keep them
  too.
- the inline-math tokenizer treated any same-line `$...$` pair as LaTeX, so
  "from $10 to $20" or "entered 2021 at $0" became a KaTeX atom whose text
  was trimmed. It now requires Pandoc-style boundaries: both `$` must touch
  the formula and the closing `$` must not be followed by a digit.
- the source-preserving reconcile mis-applied any edit at the end of a file
  whose source ends with a newline: getMarkdown never emits one, so the
  end-of-document hunk landed one character late, failed the round-trip
  proof, and fell back to canonical output for the entire file, rewriting
  every `\$`, `&` and table in it. It now patches the newline-stripped
  bodies and re-attaches the source's trailing newline run.
@coderabbitai

coderabbitai Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: fecd94d5-147e-4d82-b621-b5fcac92b1d8

📥 Commits

Reviewing files that changed from the base of the PR and between 24b18dd and e0a4cf1.

📒 Files selected for processing (3)
  • src/renderer/src/components/editor/markdown-round-trip.test.ts
  • src/renderer/src/components/editor/rich-markdown-extensions.ts
  • src/renderer/src/components/editor/rich-markdown-serializer-fidelity.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.


📝 Walkthrough

Walkthrough

The changes add source-preserving Markdown serialization for escaped characters, table pipes, link and image destinations, titles, and image alt text. Custom math tokenizers preserve escaped dollar signs, formula whitespace, multiline formulas, and block-math line boundaries. Source reconciliation now retries divergent patches and preserves applicable trailing newlines, line endings, and untouched source bytes. Tests cover these round-trip and reconciliation cases.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to e0a4c

The Markdown round-trip changes have no remaining concrete merge-blocking risk.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 18 functions across 7 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the primary change: preventing the rich Markdown editor from corrupting files containing many dollar signs.
Description check ✅ Passed The description is complete and relevant. It includes the required explanation, change summary, rationale, linked issue, visual proof, testing details, AI disclosure, review notes, boundary confirmati…
  • Fix all pre-merge checks with AI

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

  • Escaped characters survive load (tiptap-marked-facade.ts): RegistryLexer.inlineTokens now rewrites marked escape tokens into literal text tokens, so \$, \*, \_, \[ are no longer deleted by TipTap's parser. Applied to the caller-owned array so table cells are covered, and nested inline tokens flow through the same override.
  • Money stops becoming math (rich-markdown-extensions.ts): RichMarkdownInlineMath overrides InlineMath's tokenizer with a Pandoc-style pattern, keeping $10 to $20 and at $0 as text while still parsing $E = mc^2$ / $x_1$. Returned token shape matches upstream parseMarkdown, so no contract change.
  • End-of-document edits stop canonicalizing the file (rich-markdown-source-reconcile.ts): branch 4 now diffs/patches the newline-stripped bodies and re-attaches the source's trailing-newline run, so an EOF hunk no longer lands past the source newline and fails branch 6.
  • Tests: round-trip escape/money coverage plus a new end-of-document reconcile suite (LF, CRLF, no-trailing-newline) and a real-serializer dollar/ampersand case. I mutation-tested each fix — removing any one fails its new tests — and the full editor suite (1435 tests) passes.

ℹ️ Inline math with spaces adjacent to the delimiters no longer parses

The Pandoc rule intentionally requires the $ to touch the formula, so $ x $ now renders as literal text; upstream's /^\$([^$]+)\$/ parsed it as math (" x ".trim()). This is a real, user-visible change beyond the stated money scope, so it may deserve a changelog line if any docs use spaced math.

Technical details
# Spaced inline math is now text

## Affected sites
- `src/renderer/src/components/editor/rich-markdown-extensions.ts:57` — `INLINE_MATH_PATTERN` starts `^\$(?![\s$])` and ends `[^\s$\\]\$(?!\d)`, so whitespace adjacent to either delimiter disqualifies the span.

## Required outcome
- Confirm the tradeoff is intended (it matches Pandoc, and the code comment says so).
- If spaced math must keep rendering, relax the two whitespace guards without re-admitting `$10 to $20` / `at $0` (those are disqualified by the missing/space-adjacent closing `$`, not only the opener guard).

## Open questions for the human
- Do any Orca docs/templates rely on `$ x $` with spaces? If not, no change needed.

Pullfrog  | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

…econcile

Review findings on the first commit, all reproduced with the real serializer:

- Rewriting marked's `escape` token to text kept the character on load but
  the serializer never re-escapes, so `\# x` came back as `# x` and became a
  heading on the next open; `\$x\$` became inline math. Replace the facade
  rewrite with an inline atom node that owns the escape token and renders
  `\` + character, so escapes round-trip byte for byte in every container.
- The body-strip reconcile ran for every trailing-newline shape. A source
  ending in a blank line parses to a trailing empty paragraph, so canonical
  ends in `\n\n` too; stripping and re-attaching there duplicated the
  paragraph, failed the branch-6 proof, and canonicalized the whole file.
  Only strip when the source ends in exactly one newline that canonical
  lacks; every other shape patches correctly whole, as on main.
- Canonical fallbacks now keep the source's single trailing newline.
- The inline-math regex allowed neither a soft line break inside a formula
  nor a trailing LaTeX line break; both are valid and upstream accepted
  them. Drop the newline and backslash exclusions and the dead `.trim()`.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 9d5cc912-1a4e-474b-8a12-cb926396ad6e

📥 Commits

Reviewing files that changed from the base of the PR and between 09f2c2a and 3d9aa54.

📒 Files selected for processing (5)
  • src/renderer/src/components/editor/markdown-round-trip.test.ts
  • src/renderer/src/components/editor/rich-markdown-escaped-character.ts
  • src/renderer/src/components/editor/rich-markdown-extensions.ts
  • src/renderer/src/components/editor/rich-markdown-source-reconcile.test.ts
  • src/renderer/src/components/editor/rich-markdown-source-reconcile.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 8 remain after this review.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

The second commit reworks the first commit's escape handling and narrows the end-of-file reconcile, so this run reviewed the delta from 09f2c2a to 09f2c2a..3d9aa54 plus the surrounding code:

  • Added RichMarkdownEscapedCharacter (rich-markdown-escaped-character.ts, rich-markdown-extensions.ts): an inline atom node that owns marked's escape token, parses \X to one atom, and serializes it back as \X, so \$, \*, \_, \[, and a doubled backslash round-trip byte for byte (the prior parse-side text rewrite lost the backslash on save). Registered after RichMarkdownInlineMath, so escaped dollars stay atoms rather than math.
  • Relaxed the Pandoc inline-math pattern (rich-markdown-extensions.ts): a formula may now wrap a soft line break or end in a LaTeX \\, and the dead .trim() is gone; $10 to $20, at $0, $x$2, $ x$, $x $, and $5-$6 stay text.
  • Narrowed the end-of-file reconcile (rich-markdown-source-reconcile.ts): the trailing-newline body strip now runs only when the source ends in exactly one newline canonical lacks. A source ending in a blank line (trailing empty paragraph) therefore patches whole instead of duplicating its trailing paragraph and canonicalizing the file; canonical fallbacks re-attach the source's single trailing newline.
  • Extended the tests (markdown-round-trip.test.ts, rich-markdown-source-reconcile.test.ts): byte-for-byte escape round-trip including table cells, zero inline-math for money and Pandoc-rejected shapes, wrapped and \\-terminated math, blank-line-source and delete-trailing-paragraph reconcile cases, and the fallback newline.

Verified locally: the full src/renderer/src/components/editor suite passes (211 files, 1439 tests, 2 skipped).

ℹ️ The preserveEscapedCharacters facade rewrite is now redundant

The new atom node's markdownTokenizer runs before marked's built-in escape, so it consumes \X first and RegistryLexer.inlineTokens no longer sees an escape token for valid escapes. I removed the inlineTokens override locally and re-ran markdown-round-trip.test.ts: all 53 tests still pass. So the commit-1 parse-side rewrite is now dead code, and the commit message's "Replace the facade rewrite" claim does not match the tree. This is not blocking — worth deleting the helper and override, or noting why it stays.

Technical details
# Dead escape post-processing in the marked facade

## Affected sites
- `src/renderer/src/components/editor/tiptap-marked-facade.ts:17` — `preserveEscapedCharacters` converts marked `escape` tokens to `text` tokens.
- `src/renderer/src/components/editor/tiptap-marked-facade.ts:43` — the `inlineTokens` override applies it to every inline token array.
- `src/renderer/src/components/editor/rich-markdown-escaped-character.ts:29` — the atom `markdownTokenizer` runs first, so the facade hook is unreachable for valid escapes.

## Required outcome
- Remove the redundant facade rewrite (and `preserveEscapedCharacters`), or document the fallback the commit message says was replaced.

## Open questions for the human
- Was removing the facade rewrite intended in this commit? The tree still contains it.

Pullfrog  | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

…nuous

Second-round review of the atom approach: Tiptap's serializer closes every
active mark before a non-text inline node and reopens it after, so an
escape atom inside bold split the run (`**cost \$5 total**` came back as
`**cost **\$**5 total**`, which no longer parses as bold), a link containing
an escape became two links, and find/replace was disabled on any match
touching an escape because atoms are read-only.

The escape is now a non-inclusive mark on ordinary text. A mark's markdown
is one prefix for the whole run, so `getMarkdown` is wrapped to rewrite
marked text as `\X` per character before the manager serializes; inside a
code mark the character is emitted bare, and `& < >` are left to the
serializer's entity encoding. The mark is registered after `Markdown`
because that extension's onBeforeCreate installs the getMarkdown being
wrapped.

Also restores tiptap-marked-facade.ts to the base branch: the previous
commit meant to remove the escape-token rewrite there but restored the
file from the branch's own HEAD, leaving a dead override in the diff.
… math closers

Second-round review findings that survived the mark rewrite:

- A source whose last line is whitespace only (`Last.\n  \n`) has a trailing
  run of one newline, so the body strip ran, landed the end hunk after the
  spaces, failed the branch-6 proof, and canonicalized the whole file where
  the base branch had patched it correctly. The body strip is now the first
  attempt and the whole-text patch the second, so no file does worse than
  before; the extra round trip only runs when the first attempt fails.
- `costs $5 to \$x here` parsed as inline math with latex `5 to \`, because
  the tokenizer accepted an escaped `\$` as the closing delimiter. Escaped
  characters are now consumed inside the formula and cannot close it.
- The escaped-dollar test passed on the base branch for the wrong reason
  (the `\$` was deleted before the math tokenizer ran); it now also asserts
  the bytes round-trip, and a new test pins escapes as ordinary searchable
  text.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

The delta from 3d9aa54 to 7ac5338 reworks the escape handling and removes the now-dead facade code:

  • Escape atom becomes a mark (rich-markdown-escaped-character.ts): RichMarkdownEscapedCharacter is now a Mark (inclusive: false, keepOnSplit: false) applied to real text via helpers.applyMark, so emphasis, links, and find/replace stay continuous around an escape instead of an atom splitting the run.
  • getMarkdown re-escapes per character (rich-markdown-escaped-character.ts:53-64): the mark's onBeforeCreate wraps editor.getMarkdown to run escapeMarkedCharacters(editor.getJSON()) before manager.serialize(...), emitting \X per char; inside a code mark the char stays bare and & < > fall through to the serializer's entity encoding. Registration after Markdown in rich-markdown-extensions.ts is required and holds — lifecycle hooks run in the sorted, insertion-order-stable extension list.
  • Dead facade rewrite removed (tiptap-marked-facade.ts): the unreachable preserveEscapedCharacters / inlineTokens override from commit 1 is gone, resolving the prior review's cleanup note.
  • Tests extended (markdown-round-trip.test.ts, rich-markdown-source-reconcile.test.ts): escapes spanning bold/links/emphasis, consecutive escapes, code-mark and entity fallback, plus a real-serializer end-of-file reconcile case.

I also traced every serializer that bypasses getMarkdown. Only rich-markdown-review-annotations.ts:49 calls editor.markdown.serialize directly, and its output feeds a newline counter, so the mark's single-backslash renderMarkdown fallback cannot alter persisted or visible content. Both touched suites pass locally (89 tests).

Pullfrog  | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

The delta from 7ac5338 to d2c40f6 hardens the math tokenizer and the end-of-file reconcile:

  • Escaped dollars can no longer close a formula (rich-markdown-extensions.ts:57): INLINE_MATH_PATTERN is now /^\$(?![\s$])((?:\\[\s\S]|[^$\\])*?)(?<!\s)\$(?!\d)/. The group consumes \X as an escape, so /$\$ is formula content rather than a closer, and (?<!\s) replaces the old trailing-character guard so the closer still cannot follow whitespace. costs $5 to \$x stays text while $E = mc^2$, wrapped math, and a trailing \\ still parse.
  • Whole-text retry for the end-of-file patch (rich-markdown-source-reconcile.ts:92-148): branch 4 now builds an ordered attempts list — the newline-stripped body patch first when applicable, the whole-text patch always second — and each attempt goes through the extracted patchDivergentSource plus the branch-6 re-parse. A whitespace-only last line (where the body-strip hunk lands after the spaces and fails the proof) now keeps source style instead of falling to canonical, and any file that previously patched whole still does.
  • Tests (markdown-round-trip.test.ts, rich-markdown-source-reconcile.test.ts): escaped/money dollars stay text and round-trip byte for byte, doc.textContent proves escapes remain searchable text rather than atoms, and a real-serializer append to a whitespace-only final line preserves the source bytes.

I traced the two changes: the regex has no ambiguous alternation (the two group branches are mutually exclusive on the leading \), so no backtracking blowup, and the retry only doubles the throwaway re-parse on the body-strip failure path. Both touched suites pass locally on this HEAD (91 tests). Prior feedback — the dead facade rewrite — remains resolved.

Pullfrog  | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

…thful to source

Pre-existing serializer defects the review catalogued, now fixed in one
place: a serializer-fidelity extension that wraps getMarkdown and rewrites
the document JSON into its source form before Tiptap serializes it. The
escaped-character mark's per-character expansion moves there too.

- `\|` inside a table cell: marked unescapes it per cell before inline
  lexing, so the cell held a bare `|` that split the row on the next load
  and truncated it. Text inside tableCell/tableHeader now escapes `|`,
  code spans included, since the cell split happens before code lexing.
- `\)` inside a link or image destination came back bare and ended the
  destination early. Parentheses in destinations are escaped again.
  (Angle-bracket destinations are not an option: Orca's raw-HTML pass would
  placeholder them before parsing.) Image alt text escapes `[ ] \`, and
  link/image titles escape `"`.
- `$$` anywhere in a paragraph split it, because marked ends a paragraph
  wherever a block tokenizer's `start` points and upstream used
  `indexOf('$$')`. Display math now only starts at a line start.

@coderabbitai coderabbitai 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.

Actionable comments posted: 2


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 47f47097-6924-474e-a699-298079f40190

📥 Commits

Reviewing files that changed from the base of the PR and between d2c40f6 and 24b18dd.

📒 Files selected for processing (4)
  • src/renderer/src/components/editor/markdown-round-trip.test.ts
  • src/renderer/src/components/editor/rich-markdown-escaped-character.ts
  • src/renderer/src/components/editor/rich-markdown-extensions.ts
  • src/renderer/src/components/editor/rich-markdown-serializer-fidelity.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

@pullfrog pullfrog 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.

ℹ️ No critical issues — the c5 serializer-fidelity work is sound; one minor display-math regression inline.

Reviewed changes

The delta from d2c40f6 to 24b18dd splits the source-form rewrite into its own extension and widens the serializer fidelity pass:

  • Extracted the getMarkdown wrapper into RichMarkdownSerializerFidelity (rich-markdown-serializer-fidelity.ts, new): the escape re-application no longer lives on the mark's onBeforeCreate; the mark exports RICH_MARKDOWN_ESCAPED_CHARACTER_MARK and escapedCharacterSourceText, and the new Extension wraps getMarkdown after Markdown installs it.
  • Escapes more markdown syntax in the source form: | in table-cell text (code spans included), (/) in link href and image src, [/]/\ in image alt, and " in link/image title, so destinations, alt text, and cell contents re-parse identically.
  • Narrowed BlockMath's start to a line-start \n$$ so a mid-line $$ no longer ends a paragraph and opens display math (see inline note on indented math).
  • Tests extended (markdown-round-trip.test.ts): escaped pipes in table cells, escaped parentheses in destinations, escaped titles/alt, and a mid-line $$ staying prose while a real $$ block still parses.

Both touched suites pass locally at this HEAD (94 tests).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

…pipes in cell attributes

Review comments on the previous commit:

- Display math whose body holds a `$` (`$$\n\$5\n$$`) fell back to prose
  because the body pattern refused every dollar; it now runs to the
  closing `$$`.
- Display math indented by spaces or a tab no longer opened, because the
  line-start check wanted `$$` right after the newline. The start pattern
  tolerates the indent, and points marked at the newline rather than the
  first `$` so the indent does not stay behind in the paragraph.
- `|` inside a link or image attribute in a table cell was still written
  bare, so the row split on the next load. The cell context now reaches
  destinations, titles and alt text as well as text.

@pullfrog pullfrog 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.

✅ No new issues found.

Reviewed changes

This run re-reviewed the delta from 24b18dd to e0a4cf1, which closes the one finding from the prior review and fixes a related cell-parsing gap:

  • Indented display math parses again (rich-markdown-extensions.ts): start now uses BLOCK_MATH_START_PATTERN = /\n[ \t]*\$\$/ and returns the newline index, so whitespace/tab-indented $$ openers parse as display math while a mid-line $$ still stays prose. This resolves the c5 regression I flagged inline; the prior thread is retired. Pointing marked at the newline (rather than the first $) also keeps a tab indent out of the trailing paragraph.
  • Display-math bodies may hold $ (rich-markdown-extensions.ts): BLOCK_MATH_PATTERN is now /^[ \t]*\$\$((?:(?!\$\$)[\s\S])+?)\$\$/, so an escaped \$ inside the body no longer breaks the match (upstream [^$]+ refused it) while a literal $$ still closes the block.
  • Pipes in link/image attributes are escaped inside table cells (rich-markdown-serializer-fidelity.ts): the serializer-fidelity pass threads an insideTableCell context through linkMarkToSourceForm/imageToSourceForm and routes href, src, title, and alt through escapeTableCellPipes. This corrects the c5 claim that marked's cell splitter is link-aware: splitCells splits on any unescaped | (even inside (...) and quoted titles), then unescapes \| before inline lexing, so those pipes must be re-escaped to survive a round trip.
  • Tests (markdown-round-trip.test.ts): exact-output coverage for the three indented openers, an escaped-dollar body, and escaped pipes inside image alt/link text/link title in a cell, each with a second-round-trip stability assertion. The new cases are falsifiable — they fail on 24b18dd.

Verified locally at e0a4cf1: both touched suites pass (96 tests), the full src/renderer/src/components/editor suite passes (1447 tests, 2 skipped), and check:code-quality:changed reports 0 new findings across the 6 changed files.

Pullfrog  | View workflow run | Using openrouter/deepseek/deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏

@averydev

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@averydev

Copy link
Copy Markdown
Contributor Author

Orca is awesome and his is one of the the least pleasant aspects... this little bug. Would love to see this merged.

This branch has not been deployed

No deployments
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.

[Bug]: Rich markdown editor mangles dollar-heavy files on open and rewrites them on save

1 participant