feat(desktop): edit markdown directly in the rendered preview with format-preserving saves
Summary
- The markdown Preview view in the v2 file pane is now WYSIWYG-editable (type, checkboxes, bubble-menu formatting, ⌘S to save), with the existing CodeMirror "Markdown" source view still one toggle away.
- Saves never rewrite untouched parts of the file: edits are applied as a patch onto the original source, so bullet markers, hard-wrapped prose, setext headings, escapes, YAML front matter, raw HTML/comments, reference-link definitions, CRLF, and trailing-newline conventions all survive unless the user edits that exact block.
Why / Context
Markdown files already had source editing (CodeView), but the rendered preview was read-only — and naively flipping TipTap to editable would rewrite the whole file on save (tiptap-markdown normalizes *→-, _em_→*em*, unwraps hand-wrapped paragraphs, converts setext→ATX, adds \[ escapes, entity-escapes HTML, renumbers lists, and destroys front matter). That noise poisons git diffs and agent context. GitLab shipped node-attribute-level source preservation for this exact problem and retired it after four flag-gated years — this PR uses a much simpler text-level merge instead.
How It Works
mergeMarkdownEdits.ts:createMarkdownMerger(original, baseline)captures the serializer's output for the just-loaded document as a merge ancestor. On every keystroke,diff(baseline → current serialization)is applied onto the original bytes through the cacheddiff(baseline → original)alignment. Untouched regions emit original bytes; user hunks that overlap normalization noise resolve toward the user (only that block takes serializer form); content the parser drops entirely (HTML comments,[ref]:definitions) is preserved as original-side insertions unless an edit strictly spans it.- Line alignment is a patience diff (unique-line anchors, then fuzzy alphanumeric-signature anchors, exact LCS only for ≤400-line segments) — the naive LCS took 19s per keystroke on a 130KB doc where every block normalizes; this runs in 0.9ms.
applyExternalMarkdown()resets the editor's undo history whenever external content is applied (fs reload, conflict resolve). Without this, undo crosses the reload boundary, resurrects a stale document, and the merge reads externally-added content as user deletions → silent data loss (caught live via CDP).splitFrontMatter()keeps YAML front matter out of the editor (TipTap renders it as a mangled heading) and re-attaches the verbatim block on every emission, with a small "Front matter hidden" notice.TaskListTightnessglobal attribute keeps task lists tight on serialize (tiptap-markdown's tight-list handling only covers bullet/ordered lists).- The emitted (merged) text flows through the existing
fileDocumentStore, so dirty state, auto-pin, save-error banners, conflict alerts, and the source view all see format-preserved text — switching Preview↔Markdown mid-edit shows the preserved buffer.
Manual QA (all driven end-to-end over CDP against a git fixture repo, git diff as the oracle)
- Edit a paragraph → save → diff shows only that paragraph; setext title,
*bullets, HTML comment, table alignment,1./1.numbering untouched - Edit one bullet of a
*list → only the list hunk normalizes; no duplication/loss - Task checkbox click → one-character diff (
[ ]→[x]) - Front-matter file: banner shows, body edit saves with front matter byte-identical
- HTML-heavy file:
<div>,<img>,<kbd>,<br>,<details>all survive an adjacent edit - CRLF file: one-line diff,
^Mendings intact - Cross-mode: edit in Preview, toggle to Markdown (shows preserved buffer), edit there, back to Preview, save → single clean hunk
- External file change while clean → live reload; while dirty → conflict alert (Save/Don't Save/Cancel) with correct overwrite semantics
- Undo past an external reload → externally-added content survives save byte-identically
- Stress battery (recorded): 78-char typing burst, 8× mode-toggle spam while dirty, checkbox spam ×3 rounds, 15 undo/10 redo, typing under induced 120ms main-thread jank, external-write race, 3,600-line doc responsiveness, 10× save spam — zero console errors, no render-loop warnings, all diffs minimal
- Bubble-menu bold via double-click selection → one-line diff
Testing
bun run typecheck,bun run lint(clean)bun test— full desktop suite: 2709 pass; 50 new tests acrossmergeMarkdownEdits.test.ts(merge algebra incl. CRLF/EOF/large-doc/misalignment regressions),mergeMarkdownEdits.roundtrip.test.ts(real production TipTap extensions under happy-dom),splitFrontMatter.test.ts- Regression tests are mutation-verified (they fail against the pre-fix implementations)
Design Decisions
- Text-level merge instead of GitLab-style per-node source attrs: no per-node dirty tracking, no serializer wrappers to maintain per node type, trivially unit-testable; conflicts degrade to "touched block normalizes", never to corruption.
- Custom asymmetric merge instead of generic diff3: diff3 coalesces adjacent hunks, which both drops parser-invisible content (raw HTML next to an edit) and duplicated/lost lines mid-hunk — both observed as real corruption before the custom walk.
- Editable-in-preview instead of a third view: matches the v1 rendered-tab precedent and keeps the toggle binary.
Known Limitations
- Editing a block still normalizes that block (unavoidable with a serializer-based editor); everything else is byte-stable.
- ⌘S saves only while the editor has focus (same as CodeView).
- Files >1.5MB render read-only in Preview; source view handles editing there.
- Raw HTML renders as escaped literal text in the preview (pre-existing
html: falsebehavior); untouched HTML is preserved on save, but editing the exact block containing it loses the markup.
Follow-ups
- Scroll-position persistence for the preview view (CodeView already has it).
- Obsidian-style live preview (CM6 decorations) in the source view as a future fidelity-perfect editing mode.
Summary by cubic
Make the Markdown preview editable and save only user edits by merging changes onto the original bytes. Previously the v2 Preview was read-only and the v1 rendered tab rewrote the whole file; now both preserve untouched formatting and structure.
- Core merge: patience-diff alignment with exact LCS for small segments via
node-diff3; conflict unions favor user-touched blocks; rescues parser-dropped content in untouched gaps; indexed copying avoids V8 spread argument limits on large files. - Renderer:
TipTapMarkdownRendereradds preserveSourceFormatting with baseline tracking;applyExternalMarkdownresets undo on external reloads to prevent stale-content resurrection. - v2 Preview wiring: editable with preserveSourceFormatting; hides YAML front matter and reattaches verbatim on change; files >1.5MB fall back to read-only; ⌘S saves in-focus.
- v1 rendered tab: enables preserveSourceFormatting for format-preserving saves.
- Extensions/tests/deps: adds TaskList tightness attribute; comprehensive unit and round‑trip tests (CRLF/EOF/large-doc/front matter); adds
node-diff3dependency.
Behavioral note: editing a block still normalizes that block; untouched regions (including raw HTML) remain byte-identical unless edited.
Summary by CodeRabbit
- New Features
- Markdown editing now preserves source formatting, including comments, tables, list styles, line endings, and trailing newlines.
- YAML front matter is displayed separately and preserved when editing and saving documents.
- Task-list formatting is retained during editing.
- External document updates refresh the editor without carrying over undo history.
- Bug Fixes
- Improved markdown merging to prevent unintended content loss, duplication, or formatting changes.
- Large markdown documents remain available in read-only mode when they exceed the editing limit.
- Tests
- Expanded coverage for markdown editing, front matter handling, formatting preservation, and large documents.