Skip to content

fix(editor): preserve Markdown source across rich edits - #23280

Merged
nwparker merged 3 commits into
mainfrom
nwparker/bug-rich-markdown-editor-escapes-brackets-docume
Sep 27, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/bug-rich-markdown-editor-escapes-brackets-docume

Conversation

@nwparker

@nwparker nwparker commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​814 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​814
Prod 12 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​465 $\color{#cf222e}{\Huge{\mathbf{−}}}$​30 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​435

ELI5

Editing a paragraph should change that paragraph, not add backslashes and blank lines to callouts elsewhere in the article.

What Changed

The rich editor now excludes the automatically inserted empty paragraph below a final quote/list from saved Markdown until it is edited. That convenience paragraph was changing the document on the first interaction and triggering a whole-document rewrite.

When character-level source reconciliation cannot preserve the file, a second path matches parsed blocks, reuses unchanged source and checks the assembled document against the live editor before accepting it. It preserves source across the existing 50,000-character cutoff and uses a bounded block diff with a per-editor source baseline.

Includes the safe-underscore/nested-callout work from #22425, adapted from @nvimq #22123, and extends parser-validated optional escaping to tildes, asterisks and backticks. Unsafe or unproven unescapes retain the original escaped output.

The performance follow-up removes an upstream table detector's whole-suffix split, skips searches for markers absent from each lexer input, and guards details directive tokenizers before their regexes. Source reconciliation no longer reparses every block individually; provisional token spans are still accepted only after the complete assembled document matches the live editor.

Why

Changing only the escape regex leaves the whole-document rewrite intact. Raising the old size cutoff leaves fuzzy patch failures intact. Tracking the editor-only paragraph and preserving proven-equal blocks addresses both triggers without guessing whether saved Markdown keeps its meaning.

Linked Issue

Fixes #22014. Includes #22425; that PR remains open and is not modified by this PR.

Visual Proof

The original hidden-app reproduction failed the exact saved-file assertion: editing the first paragraph removed the blank line after YAML and inserted blank quote lines in two untouched callouts. The same article and a >50,000-character variant now pass all three successive saves and reopen with only the typed changes. Screenshots show the reopened article; exact file assertions are the proof of source preservation, since escaped and unescaped Markdown often render identically.

Reopened article

Testing

  • I manually tested these changes locally (automated hidden Electron interaction and direct screenshot inspection on macOS).

  • Automated tests added/updated.

  • Full editor unit packet: 1,804 passed, 2 skipped. An opt-in save benchmark is separate from the CI correctness gates.

  • Ten hidden Electron tests passed after rebuilding: article and large-document exact save/reopen; literal/link save/reopen in git, folder and paired-remote workspaces; nested toggles and table-row editing.

  • Renderer typecheck, changed-code quality and diff whitespace checks passed.

  • Regression coverage includes CRLF, repeated blocks, insertion/deletion, authored blank paragraphs, code source, unsafe delimiters and trailing-paragraph editing/undo/redo.

Review

Source reuse is accepted only when parsing the assembled result gives the intended document. Failed proofs keep the existing canonical fallback. Block matching is bounded to 256 changes; only the current source baseline is retained. The synthetic paragraph remains visible and editable; authored empty paragraphs are retained.

Agent skill upstream boundary

  • Not applicable; no skill source changes.

Notes

No filesystem routing, remote protocol, keyboard mapping or platform-specific code changes. Paired remote and folder workflows were tested on macOS; native Windows/Linux, live SSH and mobile were not exercised locally. Performance was profiled and remeasured on the same synthetic documents. At 447,784 characters / 12,001 blocks, three successive save commits improved from 8,014/3,774/3,761 ms to 506/295/288 ms (about 94%/92%/92% faster). At 110,284 characters, saves measured 129/96/65 ms; at 36,284 characters, 39/37/34 ms. The stress case still costs roughly half a second on its first preservation pass, so these results do not claim zero renderer jank or cross-platform latency guarantees. Full assembled-document parsing remains linear work needed for the safety proof. Reproduce with ORCA_BACKGROUND_LAUNCH=1 ORCA_MARKDOWN_SAVE_BENCHMARK=1 pnpm test src/renderer/src/components/editor/rich-markdown-save-benchmark.test.ts. Deterministic tests assert first-two-line table scanning, zero absent-marker suffix searches, nested lexer restoration and one full proof parse on repeated saves. This preserves callout source rather than adding a new styled alert node. Unsupported source boundaries retain the existing fallback.

Checklist

  • This PR is focused on Markdown source fidelity.
  • Explained before/after, mechanism and alternatives.
  • Reopened screenshot attached; before/after source behavior documented with exact assertions.
  • Self-reviewed for correctness, security and performance.
  • Cross-platform, SSH/remote and path/shortcut impact considered.
  • Focused local verification passed; CI covers remaining required checks.

@pullfrog

pullfrog Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor
  • Read complete raw diff via diffPath
  • Triage: understand editor markdown fidelity domain
  • Dispatch reviewfrog specialists for unresolved questions
  • Aggregate findings and draft review
  • Update PR summary snapshot
  • Submit review

Pullfrog  | View workflow run | via Pullfrog | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker marked this pull request as draft September 27, 2026 00:23
@coderabbitai

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

📝 Walkthrough

Walkthrough

The rich Markdown editor now validates optional escape removal against parsed nodes and serializes a document that excludes a still-tracked synthetic trailing paragraph. Serialization commits can reconcile edited blocks with their original Markdown source. Shared marker-based matching is used by block tokenizers. The changes add unit, end-to-end, and opt-in benchmark tests for source fidelity, tokenizer behavior, and serialization performance.

Priority: ➖ Normal

Severity of issue fixed: Medium

Merge Risk: 🟡 Moderate · up to 3007d

The normal test suite will fail until the expected search index is corrected. Fix the assertion before merging.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 3007d

The changes affect saved Markdown, but the new preservation path checks that its output reproduces the edited document and falls back when it cannot prove that. No introduced security issue was established; some security coverage remains incomplete.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The directly demonstrated effect is on Markdown parsed and saved through an editor instance. The inspected codec and source baseline are per editor; the evidence does not establish a new cross-service or cross-editor authority path.

Trust Boundaries and Controls

  • observed — Markdown source enters the editor parser before block spans are reused. A proposed saved-source candidate must parse to the live document; an unsuccessful proof leaves the commit on its canonical path.

Resilience and Maintainability Implications

  • observed — The tracked trailing paragraph is omitted only while it remains the recorded final node; the plugin clears tracking when a document-changing transaction touches it or replaces it. This limits unintended omission during edit and undo transitions.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.71% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 28 functions across 21 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 The PR meets the coding requirements in [#22014]. Block-source reconciliation reuses source for unchanged blocks and rejects unsafe assembled output. Literal serialization validates optional unescapes…
Out of Scope Changes check ✅ Passed The changes stay within [#22014]. Tokenizer guards, nested details and callout handling, table parity, EOL preservation, and performance tests support reliable parsing and preservation of untouched Ma…
Title check ✅ Passed The title clearly and concisely describes the primary change: preserving Markdown source across rich-editor edits.
Description check ✅ Passed The description follows the required template and explains the user impact, implementation, rationale, linked issue, testing, review notes, platform limitations, performance results, and checklist sta…
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

@nwparker
nwparker marked this pull request as ready for review September 27, 2026 00:39
@nwparker

Copy link
Copy Markdown
Contributor Author

@coderabbitai review

Please review current head ab85fffb14fa526fda584d1fa243ddb057da5668, including the performance follow-up. The prior review covered 21eb7b4a4ccf only. Focus on the full-document source-equivalence guard, nested lexer option restoration, and table/directive tokenizer parity. Local verification: 1,804 editor tests, renderer types, changed-code quality, and 10 hidden Electron tests passed. The reproducible stress benchmark and remaining first-save cost are documented in the PR body.

The docstring-coverage suggestion conflicts with this repository's AGENTS.md preference for concise, non-obvious comments only; please do not generate boilerplate documentation for coverage.

@nwparker

Copy link
Copy Markdown
Contributor Author

@pullfrog Please review PR #23280 at current head ab85fffb14fa526fda584d1fa243ddb057da5668, including the performance follow-up, and report any actionable findings. All current-head PR Checks are green. The earlier GitHub review run 36282267050 was on the superseded initial revision and remained in its first reported step for over twenty minutes, so I cancelled that stale run. Please ensure the active review/check covers the final head before marking it complete.

@pullfrog

pullfrog Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor
  • Read full PR diff end-to-end
  • Triage domain and identify unresolved questions
  • Dispatch reviewfrog specialists for unresolved questions
  • Aggregate findings, validate, draft review
  • Submit review

Pullfrog  | View workflow run | via Pullfrog | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 42b1a0cd-4db1-450c-9b08-1c88a672c14e

📥 Commits

Reviewing files that changed from the base of the PR and between 21eb7b4 and ab85fff.

📒 Files selected for processing (12)
  • src/renderer/src/components/editor/markdown-directive-tokenizer.ts
  • src/renderer/src/components/editor/markdown-tokenizer-start.test.ts
  • src/renderer/src/components/editor/markdown-tokenizer-start.ts
  • src/renderer/src/components/editor/raw-markdown-html.ts
  • src/renderer/src/components/editor/rich-markdown-block-source-work.test.ts
  • src/renderer/src/components/editor/rich-markdown-block-source.ts
  • src/renderer/src/components/editor/rich-markdown-details-extension.ts
  • src/renderer/src/components/editor/rich-markdown-extensions.ts
  • src/renderer/src/components/editor/rich-markdown-save-benchmark.test.ts
  • src/renderer/src/components/editor/rich-markdown-table.test.ts
  • src/renderer/src/components/editor/rich-markdown-table.ts
  • src/renderer/src/components/editor/tiptap-marked-facade.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review.

@coderabbitai

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor
⚠️ Action not completed

Already reviewed the last commit. Use @coderabbitai full review to rerun a review of the entire changeset.

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.

@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

Full initial review at ab85fff. The PR fixes #22014 by stopping whole-document rewrites on the first rich edit, via three interlocking mechanisms:

  • Synthetic trailing paragraph — StarterKit's trailingNode is disabled and replaced by RichMarkdownTrailingParagraph, which tracks the auto-inserted empty paragraph under a plugin key and strips it in getRichMarkdownSerializationDocument until edited. Stripping is gated on node identity (document.lastChild === synthetic), not on the mapping heuristic, so authored text cannot be dropped.
  • Block-source fallback — reconcileRichMarkdownBlockSource splits baseline and current into top-level blocks, reuses exact source for equal blocks (bounded diffArrays, maxEditLength: 256), and accepts the assembled result only when parse(candidate).eq(liveDoc), which keeps it sound even if block/separator bookkeeping drifts.
  • Tokenizer/perf guardrails — createMarkdownTokenizerStart registers a marker per start fn that RegistryLexer.blockTokens uses to skip absent-marker suffix scans; details directives are pre-checked with startsWith; the table start slices to two lines before upstream's whole-suffix split; optional-escape omission is extended to ~ ` * with per-block parser-equality proofs, and underscore unescape is restricted to intraword runs.

Verification this run: the new unit packet plus the pre-existing literal/reconcile/round-trip suites all pass (164 tests), and I confirmed the table-slice and marker-filter optimizations are behavior-preserving against the installed @tiptap/marked sources. A specialist trace of the trailing-paragraph invariant found no transaction sequence (undo/redo, paste, IME, setContent, block merge) that drops authored content.

ℹ️ Coordination with open PR #22425

#22425 (same author, still open) also adds src/renderer/src/components/editor/rich-markdown-escape-fidelity.test.ts and modifies rich-markdown-literal-serialization.ts, the same two files this PR adds/modifies. If both land, one will hit an add/add + edit conflict; whichever merges second should be rebased, and the other likely closed as superseded. Not a defect in this PR — flagging so merge order is deliberate.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

@nwparker

Copy link
Copy Markdown
Contributor Author

@coderabbitai review
@pullfrog Please review the final incremental commit 3007d9456a9b25dcd14edc40d270e44ce02f0d4f before merge. This addresses the case-insensitive details finding: it keeps the original regex semantics while retaining absent-marker filtering via the required < marker. Mixed/uppercase regression tests fail before the fix and pass afterward. Thirty focused tests, renderer types and changed-code quality pass; CI is running on this head. Your earlier reviews cover the preceding ab85fff commit.

@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

Incremental review of 3007d9456a (new since the prior pullfrog review at ab85fff).

  • Case-insensitive <details> start — the details HTML tokenizer's start changes from the case-sensitive createMarkdownTokenizerStart('<details') (plain indexOf) to registerMarkdownTokenizerStart('<', (source) => source.search(/<details\b/i)), so <Details>/<DETAILS> are located and clipped before the preceding paragraph can swallow them. matchDetailsHtmlBlock was already /i, so the start was the only case-sensitive piece.
  • Reusable marker registration — the marker is now recorded via an exported registerMarkdownTokenizerStart(marker, start); createMarkdownTokenizerStart delegates to it. The facade's absent-marker skip stays sound: '<' is a superset of /<details\b/i, so a start is only dropped when no match is possible.
  • Tests — new rich-markdown-details-case.test.ts (parses <details>/<Details>/<DETAILS>/<dEtAiLs> after prose as editable toggles) and a custom-marker case in markdown-tokenizer-start.test.ts; both pass (13 tests).

The broad '<' marker means the skip only engages for inputs with no < at all, but that matches the previous always-run behavior, so it is not a regression. No correctness, data-safety, or cross-platform concerns in the delta.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 96135c8e-b322-4b98-b8d4-99c6143349b4

📥 Commits

Reviewing files that changed from the base of the PR and between ab85fff and 3007d94.

📒 Files selected for processing (4)
  • src/renderer/src/components/editor/markdown-tokenizer-start.test.ts
  • src/renderer/src/components/editor/markdown-tokenizer-start.ts
  • src/renderer/src/components/editor/rich-markdown-details-case.test.ts
  • src/renderer/src/components/editor/rich-markdown-details-extension.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/components/editor/rich-markdown-details-extension.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

@coderabbitai

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor
⚠️ Action not completed

Already reviewed the last commit. Use @coderabbitai full review to rerun a review of the entire changeset.

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.

@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

Incremental review of 3007d9456a (new since the prior pullfrog review at ab85fff). Confirmed the case-insensitive <details> fix and its regression coverage.

  • Case-insensitive <details> start — the details tokenizer's start moves from the case-sensitive createMarkdownTokenizerStart('<details') to registerMarkdownTokenizerStart('<', (source) => source.search(/<details\b/i)). Previously the facade's absent-marker filter dropped the whole start function for <DETAILS>/<Details> inputs, so the preceding paragraph swallowed the tag; the new marker is retained whenever the input contains <.
  • Reusable marker registration — registerMarkdownTokenizerStart(marker, start) is exported and createMarkdownTokenizerStart delegates to it. The < marker is a superset of /<details\b/i, so the skip only engages when the input has no < at all, matching the prior always-run behavior.
  • Regression tests — new rich-markdown-details-case.test.ts parses <details>/<Details>/<DETAILS>/<dEtAiLs> after prose as editable toggles, and markdown-tokenizer-start.test.ts gains a custom-marker skip case.

Verification this run: both focused suites pass (13 tests). I reverted the extension to the pre-fix start locally and confirmed 3 of 4 mixed/uppercase cases fail, then re-ran green with the fix restored. The start semantics also match marked's blockTokens contract — startBlock functions are invoked with e.slice(1), so 'Prose\n<DETAILS>' correctly yields index 5, which is what the new test asserts.

Pullfrog  | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

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 escapes brackets document-wide on any edit, corrupting GitHub alerts and callouts

1 participant