Skip to content

fix(editor): make markdown images inline so a paragraph stays schema-valid - #19746

Merged
nwparker merged 2 commits into
mainfrom
fix/rich-markdown-inline-image
Sep 11, 2026
Merged

nwparker merged 2 commits into
mainfrom
fix/rich-markdown-inline-image

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 9, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​691 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​688
Prod 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​82 $\color{#cf222e}{\Huge{\mathbf{−}}}$​6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​76

What

An inline markdown image made the rich-markdown editor throw a RangeError and its React error boundary tear the surface down. Report 0e46c048 (Orca 1.4.198, macOS 25.3.0):

boundary_id  : editor.rich-markdown
surface      : rich-markdown-editor
error_name   : RangeError
error_message: Invalid content for node paragraph: <".\nnh ", code(".crx"), " (tham chiếu, KHÔNG chặn
stack        : e.checkContent <- Se <- Ce <- _e (recursive) <- ge <- e.replace

Fix evidence

Image was registered with only allowBase64: true, keeping the TipTap default inline: false / group: 'block' — but paragraph is content: 'inline*'. The markdown pipeline nevertheless nests images inline, and Schema.nodeFromJSON performs no content validation, so the editor happily builds a schema-invalid document that renders and serializes fine. It only detonates on the first ProseMirror step that reassembles that paragraph.

Important: the Vietnamese text, the newline and the code(".crx") in the error message are innocent bystanders. ProseMirror truncates its content dump with content.toString().slice(0, 50), which is why the offending image child never appears in the message — and why this read as a text-encoding problem when it is not.

Every image placement, measured before and after:

markdown source before after
text ![a](x) more doc.check() RangeError valid, md byte-identical
![a](x) standalone valid (top-level block) valid (paragraph > image), md byte-identical
- item ![a](x) RangeError valid, md byte-identical
- ![a](x) RangeError valid, md byte-identical
table cell | ![a](x) | RangeError valid, md byte-identical
> ![a](x) RangeError valid, md byte-identical
![a](x "t") (title) RangeError valid, md byte-identical

Which operations threw on the bad document (all now clean): doc.check(), tr.insertText, tr.delete, tr.addMark — every one routes through doc.replace → checkContent. setContent / getMarkdown / normalizeSoftBreaks did not throw, which is exactly why the document loaded fine and blew up later on the user's first keystroke.

command before after
pnpm test src/renderer/src/components/editor/ 209 files, 1419 passed 209 files, 1422 passed (+3)
pnpm tc — clean
pnpm run check:code-quality:changed — 0 new findings

ELI5

The editor has a rulebook saying what can go inside what. It said "a picture is a big block that stands on its own line" and "a paragraph may only contain small inline things like text."

But when you write a picture in the middle of a sentence, the markdown reader puts the picture inside the paragraph — a big block inside a container that only allows small things. The rulebook was never consulted at load time, so the document opened fine and looked fine.

The rulebook only gets checked when the editor rebuilds that paragraph, which happens the moment you type in it. Then it noticed the illegal shape, threw, and the whole editor panel disappeared.

The fix tells the rulebook the truth — in markdown, a picture is an inline thing — so the document is legal in the first place.

Trade-offs

Honest list of behaviour changes:

  1. Document shape changed: a standalone image is now paragraph > image instead of a top-level image block. Markdown output is byte-identical in every case above, so nothing the user sees or saves changes — but anything that pattern-matches on the doc JSON shape would see the difference.
  2. Image nodeView wrapper is now <span> (display:inline-block) instead of <div>. Required: a block div inside a <p> would break surrounding text onto its own line. Visual result for a standalone image is unchanged.
  3. New RichMarkdownParagraph extension replaces StarterKit's paragraph. inline: true alone is not sufficient — upstream's paragraph parseMarkdown unconditionally hoists a lone image out of its paragraph, which with an inline image produces an inline node directly under doc (block+): the same invalid-document class, just relocated. The override changes only that branch and delegates everything else (notably &nbsp; empty-paragraph handling) to Paragraph.config.parseMarkdown.
  4. Rejected alternative: normalizing the parsed doc by splitting paragraphs around a block image. That rewrites the user's markdown on save (text ![img](a) more → text\n\n![img](a)\n\nmore) — content mangling on a document they only opened. Not acceptable.
  5. Pre-existing, not fixed here: a linked image [![i](x.png)](https://example.com) loses its link. Separate parser defect, out of scope, filed for follow-up.

Adversarial review

1 loop to clean. The reviewer re-derived the mechanism from scratch and proved it empirically rather than trusting the brief — reverting inline: true and re-running a 13-case probe showed 12 of 13 image placements produced an invalid document at baseline.

Findings, 3 of 4 fixed in that loop:

  • (high) The same RangeError still fired from <details><summary>. Upstream's detailsSummary is content: 'text*', but Orca's details parseMarkdown feeds it richer content — a live second path to the identical crash that the original fix missed entirely. Fixed.
  • (medium) RichMarkdownParagraph was load-bearing but no test failed without it — deleting it would silently reintroduce a doc-level variant of the crash. Pinned with a test.
  • (low) The "markdown images are inline" rationale comment sat ~110 lines from the option it explains. Moved.
  • (low, not fixed) The linked-image regression above — verified pre-existing at HEAD, not introduced here.

Fixes the crash in report 0e46c048.

…valid

Image was registered as a block node while paragraph is content:'inline*',
but the markdown pipeline nests an inline image as a paragraph child.
Schema.nodeFromJSON does not validate content, so the editor built a
schema-invalid document that rendered fine and threw on the first step
that reassembled the paragraph - i.e. on the user's next keystroke.

Report 0e46c048 (1.4.198, macOS): RangeError "Invalid content for node
paragraph" from checkContent via Node.replace, tearing down the
editor.rich-markdown boundary.

Register Image as inline and override paragraph's parseMarkdown so a lone
image is not hoisted out of its paragraph. Also fixes the same crash class
reachable through details/summary. Markdown output is byte-identical.
@coderabbitai

coderabbitai Bot commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

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: ad4657b2-ab8d-4cfc-b79a-e0dbefad6bb3

📥 Commits

Reviewing files that changed from the base of the PR and between 85f76be and 23e0df9.

📒 Files selected for processing (12)
  • src/renderer/src/components/editor/markdown-round-trip.test.ts
  • src/renderer/src/components/editor/rich-markdown-image-insert-code-block.test.ts
  • src/renderer/src/components/editor/rich-markdown-image-insert-content.ts
  • src/renderer/src/components/editor/rich-markdown-image-insert.test.ts
  • src/renderer/src/components/editor/rich-markdown-image-insert.ts
  • src/renderer/src/components/editor/rich-markdown-inline-image-paragraph.test.ts
  • src/renderer/src/components/editor/rich-markdown-paragraph.test.ts
  • src/renderer/src/components/editor/rich-markdown-paragraph.ts
  • src/renderer/src/components/github/use-image-input.test.ts
  • src/renderer/src/components/github/use-image-input.ts
  • tests/e2e/helpers/markdown-inline-image.ts
  • tests/e2e/rich-markdown-inline-image.spec.ts

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


📝 Walkthrough

Walkthrough

The editor now accepts inline content in details summaries and preserves images and inline math after text replacement. Paragraph parsing keeps image tokens inside paragraphs, including standalone images, list items, and table cells. Image insertion preserves code fences. New tests cover document validity, editor transactions, rendering, and end-to-end markdown editing.

Priority: ⬆️ High

Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to 23e0d

Inline-image parsing and insertion paths preserve valid editor structure across prose, details summaries, and fenced code blocks, with targeted regression coverage.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description gives strong technical context, rationale, trade-offs, and test results, but it does not follow the required template. It omits the mandatory linked issue, visual proof section, AI dis… Add the required template sections and complete them. Include a real issue reference after "Fixes #"; attach before-and-after visual proof or state "N/A" with a reason; document AI usage; complete Review, Agent skill upstream boundary, Note…
Docstring Coverage ⚠️ Warning Docstring coverage is 9.52% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 21 functions across 15 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the primary change: making Markdown images inline to keep paragraphs schema-valid. It is concise and specific.
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.
Full details: Description check

Explanation

The description gives strong technical context, rationale, trade-offs, and test results, but it does not follow the required template. It omits the mandatory linked issue, visual proof section, AI disclosure, review section, agent-skill boundary checkbox, notes, and checklist confirmations.

Resolution

Add the required template sections and complete them. Include a real issue reference after "Fixes #"; attach before-and-after visual proof or state "N/A" with a reason; document AI usage; complete Review, Agent skill upstream boundary, Notes, and Checklist sections; and use the required ELI5, What Changed, and Why headings or clearly map the existing content to them.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

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

Reviewed the full diff: the Image extension flipped to inline: true, a new RichMarkdownParagraph that stops upstream from hoisting a lone inline image out of its paragraph, an OrcaDetailsSummary widening content from text* to inline*, the image nodeView wrapper moving from <div> to <span> with display: inline-block, and five new tests pinning each of those behaviors.

  • Inline image schema fix — Image.configure({ inline: true }) makes the markdown-parsed paragraph > image shape schema-valid, so the first edit no longer throws RangeError in checkContent.
  • Paragraph parse override — RichMarkdownParagraph wraps a lone image in a paragraph rather than letting upstream hoist it into an inline node directly under doc (block+), delegating all other cases (including &nbsp; empty-paragraph handling) to Paragraph.config.parseMarkdown.
  • Details summary widening — OrcaDetailsSummary moves content from text* to inline*, closing the parallel crash path for image/inline-math in <summary>.
  • NodeView wrapper — <span> with display: inline-block keeps the image in inline content without introducing a block box.
  • Test coverage — each new assertion discriminates against the pre-fix behavior (I confirmed the hoisting logic in @tiptap/[email protected] and the text* summary schema in @tiptap/extension-details, and ran the changed suites locally: 58/58 pass).

I verified the fix mechanism against the upstream sources and confirmed the markdown round-trip stays byte-identical across the reported placements. The linked-image-is-lost regression is pre-existing and out of scope as documented.

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

@nwparker

Copy link
Copy Markdown
Contributor

Visual proof — real Orca Electron app, before/after

Captured by driving the actual Electron app through Playwright (_electron.launch(), headless, ORCA_BACKGROUND_LAUNCH semantics), opening a real .md file in the rich-markdown editor and pressing real keys. Not a mock, not a unit-test render.

Method: the fix commit (85f76be) was cherry-picked onto current main (027acb4) so both runs use an otherwise identical build. Same fixture file, same clicks, same keystroke in both columns.

Fixture (![alt](inline-dot.png) is a real 22×22 PNG on disk next to the markdown):

# Inline image crash repro

Some text ![alt](inline-dot.png) more text

1. Document as loaded

Before (main) After (this PR)
before after
Image is a block node — it breaks the sentence onto three lines. The paragraph is already schema-invalid here; it just hasn't been touched yet. Image is inline: Some text 🟠 more text on one line.

2. After typing exactly one character (X at the paragraph start)

Before (main) After (this PR)
before after
The image is gone. One keystroke silently destroyed it — the editor is left holding XSome text more text. Unrecoverable content loss on a document the user only opened. XSome text 🟠 more text. Character landed, image intact, still inline.

Full app window for the same moment — before / after:

Before (main) After (this PR)
before after

3. The reported RangeError, reproduced live

Select the paragraph and click Bold in the toolbar (toggleBold → tr.addMark → doc.replace → checkContent):

Before (main) After (this PR)
before after
Text stays un-bolded — the command threw and did nothing. Renderer console, captured verbatim from the running app: Bold applied to the whole paragraph, image still inline, console clean.
RangeError: Invalid content for node paragraph: <bold("Some text "), image, " more text">

That is the crash from report 0e46c048, same node type, same checkContent frame.

4. The <details><summary> variant

<details class="orca-details" open>
<summary>Toggle ![alt](inline-dot.png) label</summary>

Body

</details>

Loaded:

Before (main) After (this PR)
before after

After one keystroke in the summary:

Before (main) After (this PR)
before after
Summary collapses to Toggle X label — the image was replaced by the typed character. Toggle 🟠 labelX — image preserved inline, character appended.

Harness result

The proof was built as an assertion first, then screenshotted — the same spec is red on main and green on this PR:

main this PR
paragraph inline image survives one keystroke ✘ ✓
details-summary inline image survives one keystroke ✘ ✓
formatting command over the inline image does not throw ✘ (RangeError) ✓

One caveat worth recording: the RichMarkdownErrorBoundary did not trip in these runs. The RangeError is raised inside a DOM/ProseMirror handler, so it escapes as an uncaught renderer error rather than a React render error — the user-visible outcome in the app is the silent image loss and the dead formatting command shown above. The boundary-caught variant in report 0e46c048 is the same throw reached via a React-render path.

…d into it

Making the image node inline meant it could no longer be fitted into
codeBlock (content:'text*', marks:''), so inserting one with the cursor
inside a fence made ProseMirror close the block at the insertion point:
the remaining code escaped as plain prose and the language attribute was
lost, and autosave wrote that markdown to the user's file. The pre-fix
block image split the fence into two intact blocks instead.

Resolve the insert content against the target position: when an inline
image cannot be fitted where the caret sits, wrap it in a paragraph so
ProseMirror splits the block and both halves keep their ``` fencing and
language. Prose insertion is unchanged. Every production insert path now
shares that resolution - the toolbar picker, the slash command and the
clipboard-screenshot paste through insertRichMarkdownImageFromPath, plus
the GitHub/GitLab composer's image-URL insert - each with a regression
test.

Also guard the unchecked cast of Paragraph.config.parseMarkdown: a Tiptap
upgrade that drops the field would otherwise turn every paragraph parse
into a TypeError and take the whole editor down, instead of degrading to
parseInline.

Four of the new round-trip cases asserted only on getMarkdown(), which
walks the document without running NodeType.checkContent and so emits
byte-identical output from a schema-invalid document - they passed on the
pre-fix code. roundTripMarkdown now runs doc.check(), the list-item and
table-cell case performs a real edit, and the standalone-image case types
beside the image. All twelve cases now fail on the merge-base.

Adds an Electron e2e spec driving the real renderer: a paragraph image and
a toggle-summary image each survive a keystroke, and Bold over a selection
spanning the image keeps it.

@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

Reviewed the single new commit on top of the prior approval: the image insert paths now resolve their content against the target position, a new buildRichMarkdownImageInsertContent helper wraps the image in a paragraph when it cannot fit inline, a defensive guard on the upstream Paragraph.config.parseMarkdown cast, and a set of strengthened plus new regression tests including an Electron e2e spec.

  • Insert-position resolution — buildRichMarkdownImageInsertContent checks $pos.parent.canReplaceWith(index, index, imageType) and, when an inline image cannot be fitted (e.g. inside a codeBlock text*), wraps it in a paragraph so ProseMirror splits the fence instead of dissolving it and dropping the language attribute. Wired into both production paths: insertRichMarkdownImageFromPath and the GitHub/GitLab useImageInput URL insert.
  • Paragraph parser guard — baseParseMarkdown is now typed | undefined and falls back to parseInline, so a future Tiptap upgrade that drops the field degrades instead of throwing a TypeError on every paragraph parse.
  • Test hardening — four round-trip cases that only walked getMarkdown() (which skips checkContent) now assert doc.check() or perform a real edit; each insert path gains a code-block regression test; the e2e spec drives the real renderer for paragraph keystroke, summary keystroke, and Bold-over-image.

I verified the split-vs-dissolve mechanism against the codeBlock text* schema and ran the changed suites (image-insert, code-block, paragraph, use-image-input, round-trip, inline-image-paragraph): 64 tests pass.

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

@nwparker
nwparker merged commit fb9ba4b into main Sep 11, 2026
34 checks passed
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.

2 participants