Skip to content

Preserve image clipboard targets and content across editor changes - #25176

Merged
nwparker merged 2 commits into
mainfrom
nwparker/markdown-image-clipboard-target
Oct 4, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/markdown-image-clipboard-target

Conversation

@nwparker

@nwparker nwparker commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

An image paste now replaces the text you selected, even when importing the image takes time. Cutting an image writes it to the clipboard before deleting it.

What Changed

Image paste and picking capture the original selection ranges and map it through intervening edits. Completion inserts at that target while preserving a moved caret and current focus. Changed files, hosts, deleted or edited targets, and table changes that would include new cells cancel the pending operation with a visible notice. Concurrent imports retain their invocation order, using the same request tracker as large text pastes. Image-only blocks with an empty caret selection now use the existing verified clipboard writer instead of the empty-block cut path.

Why

The old image path captured one offset, left selected text behind, and could move the caret when an import completed. Image-only Cut could delete content without writing it. Reusing native selection mapping and the verified writer preserves table replacement, code-fence handling, and clipboard failure behavior without adding parallel clipboard logic. A canceled operation now explains what happened instead of silently dropping the paste.

Linked Issue

Found during the editor integration review; no linked issue.

Visual Proof

Select “world”, begin an image paste, then move to the line start and type a prefix while import is delayed. Finish the import and continue typing. Before, the image appears at the stale offset and “world” remains. After, the prefix and continued typing remain in place and the image replaces “world”.

Before After
Image inserts at the stale offset Image replaces the original selection

Editing the selected target during import cancels insertion, retains the edited text, and shows a retry notice.

Canceled image paste explains that the destination changed

Actual SSH image upload and cancellation, with remote byte verification. Actual SSH integration receipts.

Imported image at the original selection Changed target cancels with notice
Actual SSH image upload Actual SSH cancellation notice

Testing

  • I manually tested these changes locally
  • Automated tests added/updated

The combined editor suite passes 2,272 tests in 304 files, with three skipped tests. Full typecheck, full lint, changed-code quality, and fresh background Electron and relay builds pass. The combined editor sources match the tested integration; newer unrelated main changes and all four editor translation keys are preserved. Current-head CI is green, including all five unit-test shards, rendered checks, packaging, and final selection evidence.

Native Windows passes 121/121 tests across 12 files on a3ba3b7735e0; the only subsequent change is the rendered test caret setup, with identical production and unit-test sources. All 98 focused image tests pass.

Hidden rendered checks verify original-target replacement, moved-caret typing, and cancellation. Real SSH verification uploads and renders the image, checks its SHA256 and saved Markdown independently on the Linux host, and confirms unchanged local counterparts.

Clipboard persistence is replaced by a deferred file fixture; transport, rendering, and saves are real. Native system clipboard and picker interaction remain untested. The image test sets the caret through the editor selection API because hidden browser arrows can move the DOM selection without synchronizing the model; a no-paste control reproduced that issue.

Refreshed verification receipt. Existing before/after evidence remains above.

Review

Simplified the insertion API so every caller provides its captured selection; removed obsolete fixed-position and focus fallbacks, optional ordering, and duplicate selection rebuilding. This removes 20 production lines while retaining every regression case. The PR adds 206 net production lines beyond the shared code already merged in #25177. No library patches or dependency changes.

Reviewed cancellation, target ownership, operation ordering, selection mapping, clipboard-write failures, and cleanup after completion or editor destruction.

Agent skill upstream boundary

  • Not applicable; no agent skill changes.

Notes

Uses existing image import and host routing. No IPC or remote wire format changes.

User-facing trade-offs: editing or changing the original destination cancels the import and requires retrying. If the image file was already copied, it remains on disk and the notice says so; deleting it automatically could remove an existing or shared asset. Preserving focus in another control means clicking the editor to resume typing. The new cancellation notices use English fallback until translations are added.

Checklist

  • Focused clipboard change; before/after, mechanism, and approach explained.
  • Before/after screenshots attached.
  • Self-reviewed for correctness, security, performance, and cross-platform/remote behavior.
  • Native Windows tests, the macOS editor suite, full typecheck/lint, fresh build, changed-code quality, and real SSH integration pass. Current-head CI is green, including all five unit-test shards, rendered checks, packaging, and final selection evidence.

@coderabbitai

coderabbitai Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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

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: 43049e79-4cee-4dd4-8a35-354c1b24d186
📥 Commits

Reviewing files that changed from the base of the PR and between 87eeefead98eb730776cae484490b935f0fb9d55 and a3ba3b7.

📒 Files selected for processing (7)
  • 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-image-insertion-target.test.ts
  • src/renderer/src/components/editor/rich-markdown-image-insertion-target.ts
  • src/renderer/src/components/editor/rich-markdown-paste-image.test.ts
  • src/renderer/src/components/editor/rich-markdown-paste-image.ts
  • src/renderer/src/components/editor/useLocalImagePick.ts

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


📝 Walkthrough

Walkthrough

The change adds tracked insertion targets for asynchronous rich-Markdown image paste and local image picking. Targets map through editor transactions and become unavailable when selection, resolver context, or editor state invalidates them. Image insertion uses the tracked range and provides cancellation feedback when insertion cannot proceed. Cut handling now distinguishes blocks containing non-text atoms from empty blocks. Unit and end-to-end tests cover these behaviors.

Priority: ➖ Normal

Merge Risk: ⚪ Minimal · up to a3ba3

No actionable issue remains from this review; the change is mergeable after normal checks.

Security Architecture Review

Security architecture risk: ⚪ Minimal · up to a3ba3

The reviewed changes preserve existing file and host ownership checks while preventing delayed image operations from modifying stale destinations. No material security risk was identified in the changed flows.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The reviewed operation remains scoped to an editor document and an image import into the captured note directory under existing runtime ownership controls. The change does not introduce an additional production caller or greater import authority.

Trust Boundaries and Controls

  • observed — Clipboard and picked image paths still reach the existing runtime import sink through workspace, connection, and expected-host checks. The live-range callback controls subsequent editor mutation; it does not replace or bypass those file-operation checks.

Resilience and Maintainability Implications

  • observed — Request-order metadata coordinates pending insertions independently of completion order. Target invalidation is terminal, disposal is idempotent, and transaction and destruction listeners are removed. Inspected tests assert concurrent ordering, appended-transaction mapping, undo behavior, interruption, and cleanup.
🚥 Pre-merge checks | ✅ 3 | ❌ 1 | ❓ 1

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 2.94% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 34 functions across 17 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The description covers the required change, rationale, visual proof, testing, review, and checklist sections. It states that no issue is linked, but the template makes an issue conditional on contribu… Confirm whether the author is a maintainer. If not, add a link to an actual issue. If the author is a maintainer, confirm that the template’s maintainer exception applies.
✅ Passed checks (3 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 summarizes the main change: preserving image paste targets and content while the editor changes.
Full details: Description check

Explanation

The description covers the required change, rationale, visual proof, testing, review, and checklist sections. It states that no issue is linked, but the template makes an issue conditional on contributor status, which is not provided.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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.

Solid change — the moving selection target is well scoped, and the cancellation paths (overlap, deletedAcross, cell-selection structure, resolver context version, editor lifecycle) are each covered by tests that assert exact results.

Reviewed changes

This run reviewed the full PR (both commits) end to end against the base.

  • New selection-target mechanism — rich-markdown-image-insertion-target.ts captures the selection ranges (plus an optional multi-cell CellSelection), a resolver contextVersion, and a per-editor requestOrder, then remaps them through every root and appended transaction, disposing on overlap, deletion, or structural change.
  • Insertion uses the mapped range — rich-markdown-image-insert.ts replaces the mapped range (or cell selection) and preserves a moved live caret via updateSelection, falling back to the old insertPos/focus() path for legacy callers.
  • Paste and picker adopt the target — rich-markdown-paste-image.ts and useLocalImagePick.ts cancel when the file/host/runtime context or editor changes during the async window; the picker disposes pending targets on context change and unmount.
  • Context version signal — rich-markdown-image-context.ts exposes getRichMarkdownImageResolverContextVersion over the existing contextVersion.
  • Image-only cut — rich-markdown-cut-handler.ts adds a hasContentAtom guard so an empty-visible-text block holding an image/math atom writes to the clipboard before deletion rather than taking the empty-block delete path.
  • Concurrent-paste ordering — a PluginKey meta carries requestOrder so simultaneous same-caret pastes insert in request order regardless of completion order.

Verification: the five new/updated unit test files pass (71 tests). I also confirmed the ProseMirror API usage (StepMap.forEach, mapResult/deletedAcross, Transaction.before, appended-transaction ordering, CellSelection.replaceWith) against the installed prosemirror-* sources, and enumerated schema atoms for the cut guard — no correctness or data-loss issue found.

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

@nwparker
nwparker force-pushed the nwparker/markdown-image-clipboard-target branch from ee3c2cc to f1d33c7 Compare October 4, 2026 20:06

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

Important

The new cancellation toasts reference two i18n keys that were never added to en.json, so the required localization-extraction check fails on this branch. Details inline.

Reviewed changes

Reviewed the two commits added since the prior pullfrog review (d98bdbd9e4, f1d33c7504).

  • Cancellation now surfaces feedback — new rich-markdown-image-insertion-feedback.ts shows a toast.info when an async image paste/pick is canceled because the destination changed, distinguishing "try again" (before import) from "the imported file was kept" (after import); insertRichMarkdownImageFromPath, rich-markdown-paste-image.ts, and useLocalImagePick.ts now call it on the previously-silent !range / !getRange() paths.
  • Context version read via checked fields — getRichMarkdownImageResolverContextVersion now uses 'image' in editor.storage / 'contextVersion' in image instead of Reflect.get; behavior is unchanged.
  • Tests and e2e updated — cancellation paths assert the exact toast text and single-fire behavior; the e2e helper captures the selection around the paste event and asserts it is unchanged, and replaces Reflect-based DOM/global access with typed .rich-markdown-editor / globalThis access.

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

@nwparker
nwparker force-pushed the nwparker/markdown-image-clipboard-target branch from f1d33c7 to b17415b Compare October 4, 2026 20:18
@nwparker
nwparker requested a review from brennanb2025 as a code owner October 4, 2026 20:18

@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 delta since the prior pullfrog review (f1d33c7504..b17415b0d2).

  • Registered the cancellation toast keys — added richMarkdownImageInsertionFeedback.importedFileKept / destinationChanged to en.json, matching the inline fallbacks; node config/scripts/verify-localization-extraction.mjs now exits 0, so the localization gate this branch previously failed passes.
  • Added an e2e cancellation test — a second markdown-async-image-paste.spec.ts case edits the selected target while the clipboard import is pending, then asserts no image is inserted and the "Try again" toast becomes visible; the assertion would fail if the feedback call were removed, so it is real coverage.

The one open finding from the prior review (missing en.json keys) is addressed; the thread was replied to and resolved. The remaining production code is unchanged since the previously approved review.

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

@nwparker
nwparker force-pushed the nwparker/markdown-image-clipboard-target branch from b17415b to fb9cda9 Compare October 4, 2026 20:23

@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 delta since the prior pullfrog review (b17415b0d2..fb9cda9b54).

  • Stabilized the cancellation e2e proof — the image paste reports cancellation ... case now polls the sonner toast until it is mounted (data-mounted="true"), fully opaque, inside the viewport, and free of running/pending animations before capturing the screenshot, so the visual proof is no longer taken mid-animation.

Production code is unchanged since the previously approved review, and the earlier missing-en.json finding remains addressed.

Pullfrog  | View workflow run | Using deepseek-v4.1-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.

🧹 Nitpick comments (1)
tests/e2e/markdown-async-image-paste.spec.ts (1)

144-144: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Assert the image position after the delayed paste.

The paragraph-text assertion passes if the paste removes world but inserts the image before hello. The image-count assertion also passes. Assert that the image follows hello in the first paragraph, using document or DOM order, so this test detects insertion at a stale position.


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 20a1840e-36f2-4d16-9345-0861fd884bde
📥 Commits

Reviewing files that changed from the base of the PR and between f1d33c75041524ab38b55d34841e44d19e7425f0 and 19bc27e.

📒 Files selected for processing (2)
  • src/renderer/src/i18n/locales/en.json
  • tests/e2e/markdown-async-image-paste.spec.ts

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

@nwparker
nwparker force-pushed the nwparker/markdown-image-clipboard-target branch from a22491d to ad5bca4 Compare October 4, 2026 20:50

@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 delta since the prior pullfrog review (681bd4e96f..a22491daf8); production code is unchanged since the previously approved review.

  • Asserted the image lands after its original surrounding text — the delayed-paste e2e case now reads the first paragraph's document children and asserts they are exactly ['prefix continued hello ', 'image'], so a paste that removed world but inserted the image at a stale position ahead of hello is detected; the previous paragraph-text and image-count assertions could both pass in that case. This closes the outstanding CodeRabbit coverage nitpick at 5408051962.

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

@nwparker
nwparker force-pushed the nwparker/markdown-image-clipboard-target branch 2 times, most recently from 9820f9a to 87eeefe Compare October 4, 2026 21:57
@nwparker
nwparker force-pushed the nwparker/markdown-image-clipboard-target branch from 87eeefe to a3ba3b7 Compare October 4, 2026 22:54

@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 delta since the prior pullfrog review (a22491daf8..a3ba3b7; the branch was rebased and squashed to one commit on current main).

  • Simplified the image-insertion API — insertRichMarkdownImageFromPath dropped insertPos and canInsert and now takes a required getInsertionRange, so every caller supplies a captured target instead of relying on a fixed offset plus a separate re-check.
  • Removed the legacy insert fallback — the old insertPos / focus() branch is gone, so the (now unreachable) non-target path and its conditional updateSelection collapsed to updateSelection: selectionStillAtTarget; the ordering meta is always set from the now-required requestOrder.
  • Tightened the insertion-target contract — rich-markdown-image-insertion-target.ts no longer re-exports the key as richMarkdownImageInsertionKey, requestOrder is required rather than optional, and a redundant ranges = mapped.ranges.map(...) reassignment in the cell-selection branch was deleted (the mapping loop already produced the same values the guard verifies).
  • Updated tests to the new API — rich-markdown-image-insert.test.ts now drives a real editor, asserts insertContentAt(4, …, { updateSelection: true }), and checks the "imported file was kept" toast fires exactly once on a null range; rich-markdown-paste-image.test.ts now asserts getInsertionRange replaces insertPos/canInsert.

Verified both production callers (rich-markdown-paste-image.ts, useLocalImagePick.ts) pass a captured target, confirming the removed fields are unused, and that nothing imports the deleted alias. Ran the eight changed unit files (98 tests) and pnpm tc:web — all green. All prior pullfrog feedback remains addressed.

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

@nwparker
nwparker merged commit e246090 into main Oct 4, 2026
36 checks passed
Jinwoo-H added a commit that referenced this pull request Oct 5, 2026
…5351)

#25176 replaced insertPos with getInsertionRange and #24489 added a test
using insertPos; together they broke main's typecheck.
Jinwoo-H added a commit that referenced this pull request Oct 5, 2026
…5357)

#25176 and #24489 landed together and collided in
insertRichMarkdownImageFromPath. #25176 added three test files whose
@/store mock returns { settings, folderWorkspaces, worktreesByRepo }.
#24489 made the same function look up the open document with
state.openFiles.find(...) to pass document-folder access to the import.
Under the mock, openFiles is undefined, so the lookup throws, the catch
shows "Failed to insert image", and no image is inserted -- 38 tests
fail on main.

The real store always carries openFiles, so production behavior of both
PRs is intact; the mocks were just written against the pre-#24489 shape.
Add openFiles: [] to the three mocks.
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.

1 participant