Repository navigation
fix(editor): preserve escaped Markdown during reconciliation - #21531
Conversation
…ults Proactively classifying every Source-view markdown tab scanned content nobody was looking at in Rich mode. The toggle and banner now read a stored per-tab fault instead, recorded once Rich mode actually falls back, so Source-view tabs never scan speculatively.
verify:localization-extraction failed because the rich-markdown fallback banner's "Open preview" button called translate() with a key never added to en.json.
… 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.
…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()`.
…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.
…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.
# Conflicts:
# src/renderer/src/components/editor/rich-markdown-extensions.ts
…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. # Conflicts: # src/renderer/src/components/editor/rich-markdown-extensions.ts
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Delta since the prior pullfrog review (e9308cce12): two stack-preview syncs (3658e85591, 75a6733584) that adopt the markdown-better / markdown-fallback-preview layer commits f154eb43ca and bcf4aded0d. The layer code is now base-owned, so it reads as context in this PR's diff rather than new PR-authored behavior.
- Escaped attributes at the byte level — every
"/\in a title and every\/[/]in image alt text, replacing the bare-onlyhasBare/escapeBarepath, with round-trip symmetry covered byrich-markdown-attribute-encoding.test.ts. - Escaped
$in a text node when its paragraph also contains inline math or raw inline HTML, which is the case the block-level dollar pass deliberately skips. - Made code-span padding restoration byte-exact via per-boundary placeholder tokens (tabs/NBSP), and wrapped clipboard slices in a
docnode so block boundaries survive copy. - Added
rich-markdown-block-math.test.tscovering$$…$$at document and paragraph boundaries across repeated re-serialization. - Moved the
openPreviewlabel into the base i18n layer, so it no longer appears in this PR's diff. - All prior pullfrog threads are resolved. 131 targeted editor tests pass at HEAD (block-math, attribute-encoding, clipboard, code-span-padding, inline-math, round-trip).
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No critical issues — one base-owned edge case noted in the body.
Reviewed changes
Delta since the prior pullfrog review (75a6733584): one perf commit (077f87939b) and one stack-preview merge (b82ae71feb). No PR-authored line changed net.
- Fence-scanner perf rewrite — replaced the per-line
content.sliceplus anchoredFENCE_LINE/CLOSING_FENCE_SUFFIXregex with a sticky regex over the whole content and two char-code scans (hasClosingSuffix,hasBacktick), and addedconsumeRange(content, lineStart, lineEnd)to the tracker (consumedelegates to it). - Merge absorbs it — after
b82ae71feb,markdown-fence-scanner.tsis byte-identical tostack-preview(blob3d1de134eb, same as base's667ff6564f), so it no longer appears in this PR's diff. The remaining PR diff is unchanged from the prior review.
ℹ️ Fence tracker now accepts interleaved closer suffixes that marked rejects
hasClosingSuffix returns true when every character after the fence marker is one of ~, `, space, tab, or CR, in any order. marked's closing rule is \1[~]* *(?=\n|$)— fence characters first, then whitespace only — so a line like ``` ~~~now ends the fenced block here but stays code in marked. The module's ownfence boundaries against marked` test asserts this agreement, but its `closers` list has no whitespace-before-fence-character case, so the regression is uncovered. This file is base-owned (identical to `stack-preview`), so it is not introduced by this PR's net diff — the fix belongs on the shared scanner rather than here.
Technical details
# Fence closer suffix check is more permissive than marked
## Affected sites
- `src/renderer/src/components/editor/markdown-fence-scanner.ts:12` — `hasClosingSuffix` accepts `~` (126), `` ` `` (96), space (32), tab (9), CR (13) in any order; the pre-rewrite `CLOSING_FENCE_SUFFIX = /^[~`]*[ \t\r]*$/` (and marked's `\1[~`]* *(?=\n|$)`) require fence characters before whitespace.
## Evidence
- marked 17.0.6 `rules.block.fences`: `/^ {0,3}(`{3,}(?=[^`\n]*(?:\n|$))|~{3,})([^\n]*)(?:\n|$)(?:|([\s\S]*?)(?:\n|$))(?: {0,3}\1[~`]* *(?=\n|$)|$)/`.
- Probe against `getMarkdownFenceRanges` vs `marked.lexer` for ` ```\ncode\n``` ~~~\nAFTER <div>x</div>\n`: tracker `[[0,17]]`, marked `[[0,36]]` (block stays open). ` ```~~~ ` still agrees.
- Consumers of the ranges: `stripMarkdownCode`, `markdown-reference-link-normalization.ts`, `monaco-markdown-doc-link-decorations.ts`, and the fence checks in `raw-markdown-html.ts` / `markdown-code-span-scanner.ts`.
## Required outcome
- The suffix check must accept zero or more `~`/backtick followed by zero or more space/tab/CR (and nothing else), matching the old regex and marked.
- Add a `closers` entry like `'``` ~~~'` to `fence boundaries against marked` so the invariant is enforced.
## Open questions for the human
- Fix on `stack-preview`/`main` (shared scanner) rather than on this branch, so this PR's diff stays base-identical?DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No critical issues — the fence-closer ordering fix is correct; one whitespace gap remains.
Reviewed changes
Delta since the prior pullfrog review (b82ae71feb): two commits (faff773fab, ef0f15f41b) that fix the fence-closer suffix rule flagged in that review. The rest of the PR diff is unchanged.
- Fence suffix ordering —
hasClosingSuffixnow requires the~/backtick characters before any whitespace, matching marked's\1[~]* *closer, so a line like``` ~~~ ` no longer closes a block that marked leaves open. - Regression coverage — added
'``` ~'to thefence boundaries against markedcloser matrix and to thematches the parser on the closercases inmarkdown-scanner-boundaries.test.ts.
Verified locally: markdown-fence-scanner.test.ts (35) and markdown-scanner-boundaries.test.ts (15) pass.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Additional local risk check on the current reconciliation head: 351 focused tests passed, including source reconciliation, escaped destinations, literal serialization, block and inline math, round trips, save/reopen, and fence boundaries. |
# Conflicts: # src/renderer/src/components/editor/editor-panel-render-model.ts # src/renderer/src/components/editor/markdown-rich-mode.ts
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Delta since the prior pullfrog review (ef0f15f41b): one commit (70c46795b7, fix(editor): match parser fence whitespace) that closes the tab-suffix gap raised inline in that review. The rest of the PR diff is unchanged.
- Fence-closer whitespace narrowed to spaces —
hasClosingSuffixinmarkdown-fence-scanner.tsnow treats only charCode 32 as closing whitespace, dropping tab (9) and CR (13), so a```\tline no longer closes a fence the downstream parser keeps open. Fence characters are still required before any whitespace, and the redundant marker-character branch was dropped because the fallthrough already returnsfalse. CR removal is safe: every productionconsume/consumeRangecaller excludes the line terminator. - Regression coverage —
'```\t'was added to thematches the parser on the closermatrix inmarkdown-scanner-boundaries.test.ts; the assertion is exact (ranges equal marked's token length), so it fails against the old permissive branch.
Verified locally: markdown-fence-scanner.test.ts (35) and markdown-scanner-boundaries.test.ts (16) pass; oxlint is clean on both changed files. All prior Pullfrog threads are resolved.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Caution
This stack-preview merge drops the base's validateHtmlRoundTrip option from markdown-rich-mode.ts, but stack-preview's own markdown-rich-mode-eligibility-cache.ts still passes it. At HEAD the renderer typecheck fails (TS2353) and markdown-rich-mode-eligibility-cache.test.ts fails, so CI will block. Details inline.
Reviewed changes
Delta since the prior pullfrog review (70c46795b7): one stack-preview merge (9aa5f5724a). The merge itself is otherwise a clean union, but its resolution of markdown-rich-mode.ts is not.
- Base
validateHtmlRoundTripdropped — the mergedmarkdown-rich-mode.tskeeps only the PR'shasOnlyImageAltCommentsbranch and removes the base'svalidateHtmlRoundTripparameter and early-return, while the base-owned eligibility cache still forwards that option. This breakspnpm tc:weband a base-owned test. - Fence scanner is now base-owned —
markdown-fence-scanner.tsandmarkdown-scanner-boundaries.test.tsleft the PR diff because the whitespace fix was absorbed intostack-preview(34 → 32 files). - Render-model gating kept —
editor-panel-render-model.tskeeps the PR'smdViewMode === 'rich'gate instead of the base'svalidateHtmlRoundTrip: mdViewMode === 'rich'argument; that stronger optimization is fine, but it does not remove the cache module's parameter contract.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Delta since the prior pullfrog review (9aa5f5724a): one commit (bd96ccf2c1, fix(editor): keep reconciliation cache contract) that clears the CI-blocking merge loss flagged in that review. The rest of the PR diff is unchanged.
- Cache contract aligned with the merged eligibility API —
markdown-rich-mode-eligibility-cache.tsdropsvalidateHtmlRoundTripfrom its entry type, both signatures, the cache-key comparison, and the forwarded decision call, so the base-owned typed call compiles again. The author removed the option from the cache rather than restoring it inmarkdown-rich-mode.ts; sinceeditor-panel-render-model.tsgates classification onmdViewMode === 'rich'and no caller passes the option, that is coherent and Source mode still skips the HTML round trip. - Obsolete base test removed — the
supports a conservative source-mode decision without HTML round tripscase and itsvi/spy imports are deleted along with the parameter they exercised; the remaining cache tests still cover corpus eviction, LRU reordering, size override, and locale re-resolution.
Verified at head bd96ccf2c1: pnpm tc:web passes; markdown-rich-mode-eligibility-cache.test.ts (20), editor-panel-render-model.test.ts (23), markdown-rich-mode-comments.test.ts (39), EditorPanel.markdown-classification-memoization.test.tsx (6), and EditorContent.markdown-classification.test.tsx pass. All prior pullfrog threads are resolved.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Delta since the prior pullfrog review (bd96ccf2c1): one commit (da04300e78, fix(editor): preserve rich-mode validation option) that clears the CI-blocking merge loss by restoring the base contract instead of removing the option. The rest of the PR diff is unchanged.
validateHtmlRoundTriprestored inmarkdown-rich-mode.ts—getMarkdownRichModeUnsupportedReasonagain accepts{ validateHtmlRoundTrip = true }and short-circuits tohtmlMatcher!.reasonwhen false (inside the image-alt-comment bypass), andgetMarkdownRichModeEligibilityDecisionaccepts and forwards it.- Cache files reverted to base —
markdown-rich-mode-eligibility-cache.tsand its test return to thestack-previewversions (entry key, both signatures, forwarded call, and the conservative source-mode case), so neither file appears in the PR diff anymore (34 → 32 files). The render model still gates classification onmdViewMode === 'rich'and never passes the option, so the defaulttruepreserves existing behavior.
Verified at head da04300e78: pnpm tc:web passes; 106 targeted tests pass (markdown-rich-mode-eligibility-cache 21, editor-panel-render-model 23, markdown-rich-mode-comments 39, EditorContent.markdown-classification, EditorPanel.markdown-classification-memoization). All prior Pullfrog threads are resolved.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Delta since the prior pullfrog review (da04300e78): two commits (f1e67c8572, 78b6c8e0a1). Net effect is test-only.
- Added a source-mode validation-skip test —
editor-panel-render-model.test.tsnow spies ongetRichMarkdownHtmlValidationOutputandgetRichMarkdownRoundTripOutputand asserts neither runs whenmdViewMode === 'source', locking in the gate ateditor-panel-render-model.ts:132. The spy assertion can fail if themdViewMode === 'rich'gate regresses, so it is a real regression guard. - Merged
stack-previewinto the branch — no net change to any PR-authored file (git diff da04300e78..78b6c8e0a1 --statis just the test file above).
Verified at head 78b6c8e0a1: editor-panel-render-model.test.ts (24) passes.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
|
Latest stack reconciliation: restored |
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Delta since the prior pullfrog review (78b6c8e0a1): one commit (8336d0e04d) touching a single CSS rule. All prior pullfrog threads are resolved.
- Rich-mode code blocks now wrap instead of scrolling —
.rich-markdown-editor prereplacesoverflow-x: auto+white-space: pre !importantwithoverflow-x: hidden+white-space: pre-wrap !important+overflow-wrap: anywhere, so long code lines wrap at the container edge and over-long unbreakable tokens break mid-token. Source mode (Monaco) is unaffected, and the Markdown preview's.markdown-body prekeepsoverflow-x: auto, so rich-edit and preview now differ in code wrapping by design. - Identical to the target branch's copy — the same change already exists on
stack-previewase73483dbeawith the same blob (5069988384) and subject, so merging this branch introduces no net change against the base.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Delta since the prior pullfrog review (8336d0e04d): one test-only commit (b8fde03cf8). No production surface changed; the rest of the PR diff is unchanged, and all prior Pullfrog threads are resolved.
- Retry rich selection before clipboard assertions — in
tests/e2e/markdown-copy-formatting.spec.ts, the twoselectText()calls move inside theexpect.poll(async () => { … })callbacks, so the selection is re-attempted each poll iteration untilwindow.getSelection()?.toString()matches. Theformatted-selectionscreenshot attach moves to afterexpect(editor.locator('p')).toHaveText(...), still before the second selection, so it captures the same selected paragraph. Assertions stay exact (toBe/toContain), so a selection that never settles still times out rather than passing.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
Delta since the prior pullfrog review (b8fde03cf8): one merge commit (7e097ef02c, merge stack-preview into stack-reconcile).
- Merge with no net content —
git diff b8fde03cf8 7e097ef02cis empty: the merge result tree is byte-identical to the reviewedb8fde03cf8, and themarkdown-copy-formatting.spec.tsdiff blob hash is unchanged between the two checkouts. The merge absorbedstack-preview's CSS-wrap and e2e-selection commits, which this branch already carried as byte-identical equivalents. There is no new code to review; the prior review remains valid.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

ELI5
Changing one sentence should not rewrite nearby code, links, or escaped punctuation. This PR keeps unchanged Markdown intact and lets a changed draft recover from an earlier rich-editor error.
What Changed
Reconciles edits against the original source, preserves escaped prose and raw link/image destinations, and tracks preview failures against the exact draft that caused them. Removes the unused serializer. Includes the regression and cleanup work previously reviewed in #21532.
Why
Text encoding uses node context so code and link destinations keep their own rules. Reconciliation verifies that a source-preserving edit still represents the edited document, with a bounded fallback when it cannot. Fault state belongs to the draft and follows tab close, rename, restore, and workspace cleanup.
Linked Issue
Related to #9858; this partial compatibility improvement does not close full GFM support.
Visual Proof
Before the reconciliation edit: the document contains the original formatted link and unchanged tail.
After changing the label, saving, closing, and reopening: escaped punctuation and the unchanged tail remain intact.
Recorded repeated save/reopen flow: https://github.com/user-attachments/assets/914558da-3551-458d-862f-be2b053d739e
Testing
Final combined tree, 75a6733 (identical source tree to tested 3658e85):
monaco-content-sync.undo-history.test.ts:38expects LF while the Windows model returns CRLF; the same failure reproduces on base 030a1e0. Separately, all 271 focused parsing-layer tests passed on f154eb4. Native Windows/Linux Electron UI and live SSH network failures are not covered by the local paired-client scenario.All app launches used ORCA_BACKGROUND_LAUNCH=1. Screenshots were inspected; no visible windows were raised.
Review
Independent readiness audit found no remaining proven issues. No new dependencies, network sinks, credentials, persisted schemas, or mobile-facing/wire contracts. Reconciliation has a bounded diff budget; document caches use weak keys. Destination and escaped-text behavior remains coupled to source reconciliation, so this retains more inherent risk than the small UI/scanner layers. Fresh CI and bot review are required before merge.
Stack: main → #21574 → #21527 → #21575 → #21530 → #21531.
#21565 is on main. #21529 is folded into #21527, and #21532 into this branch; those stack merges are not on main yet.
Agent skill upstream boundary
Checklist