Skip to content

Keep large Markdown pastes at their original selection - #25177

Merged
nwparker merged 1 commit into
mainfrom
nwparker/markdown-large-paste-target
Oct 4, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/markdown-large-paste-target

Conversation

@nwparker

@nwparker nwparker commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

ELI5

A large Markdown paste now stays where you started it, even if you move the caret while it loads.

What Changed

The paste records the original selection before measuring the clipboard text, maps that selection through edits, and advances each chunk from the previous chunk's end. Literal clipboard text bypasses paste-formatting rules, and a temporary history guard separates accepted user edits during pauses without splitting ordinary typing or composition updates. Measuring jobs leave existing history alone, and cancellation closes a paste boundary only when it still needs one. Normal document-link conversion maps the continuation point so the remaining text still arrives. External edits inside the target still cancel the paste. A shared request tracker keeps concurrent operations in their original order. It preserves the current caret and formatting. Changed files, unavailable editors, and table changes that would include new cells also cancel the remaining paste and show a notice.

Why

The previous code inserted each chunk at the current caret, so moving it could replace the wrong text or split the paste across paragraphs. Tracking the original selection keeps the interface responsive and preserves native replacement. Uninterrupted chunks undo together; edits made during a pause undo separately, in their original order.

Linked Issue

Found during the editor integration review; no linked issue.

Visual Proof

Paste 82,500 bytes over “world”, then move the caret to the second paragraph during clipboard measurement. Before, the payload appears in the second paragraph. After, it replaces “world”; typing still follows the moved caret.

Before After
Large paste follows the moved caret Large paste stays at the original selection

Actual SSH large paste in the original paragraph. Exact token counts, caret behavior, concurrent order, and saved bytes are verified in Actual SSH integration receipts.

Actual SSH large paste

Complete paste with committed composition and current caret

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 final combined merge matches the tested integration. Current-head CI is green, including all five unit-test shards, rendered checks, packaging, and final verification.

Native Windows passes 64/64 tests across six files on 4accb09e5193, including all 54 focused production paste regressions. Tests cover literal bytes, native selections, request order, partial cancellation, Undo, composition metadata, appended changes, and cleanup.

Hidden rendered checks preserve the original selection and current caret. Real Linux SSH readback verifies exact saved bytes, all 5,500 payload tokens, concurrent request order, and unchanged local counterparts. Browser composition changes preedit n into committed 你 during a paused paste; all 82,500 bytes arrive and four chronological Undo steps restore the original text. Native OS IME remains untested.

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

Review

Simplified the Undo state and kept captured-target checks in the paste executor; reused existing test fixtures. This removes eight production lines and 28 repeated test lines while retaining every regression case. The PR now adds 194 net production lines. No library patches or dependency changes.

Reviewed caret and formatting preservation, mapped selections, Undo boundaries, changed file ownership, and listener cleanup. Changes derived from an inserted chunk continue the paste; an external action starts one Undo boundary at its first document change, including an appended change. Later appended changes stay in that action's Undo step.

Agent skill upstream boundary

  • Not applicable; no agent skill changes.

Notes

Cancellation is now visible: a changed target before insertion shows a cancellation notice; a partial paste shows that it stopped before finishing. Moving focus to another control also stops the remaining paste. Earlier inserted text remains unless the user separately edits or undoes it, and the remaining text may need to be pasted again. An uninterrupted paste uses one Undo step; interleaved user edits undo in chronological segments. The two notices use English fallback text until translations are added.

The file and host guard uses the editor's existing context change signal. Clipboard text remains bounded by the existing size and chunk limits.

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • Before/after screenshots attached
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered
  • 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 verification.

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

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: 139ac581-b3cd-4224-aafb-e78504b19f31
📥 Commits

Reviewing files that changed from the base of the PR and between 49da7613d9fae9e1e86a734f7fc16240191d42f3 and 4accb09.

📒 Files selected for processing (2)
  • src/renderer/src/components/editor/rich-markdown-large-text-paste.fidelity.test.ts
  • src/renderer/src/components/editor/rich-markdown-large-text-paste.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.


📝 Walkthrough

Walkthrough

Large Markdown pastes now track the original selection and editor context while inserting bounded chunks. The paste stops when the target becomes invalid or an external change overlaps it. The change adds history handling and distinct messages for interrupted pastes and cancellations. New tests cover selection mapping, undo behavior, paste fidelity, and end-to-end selection changes.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 4accb

Large Markdown pastes now stay anchored to the selection where the paste started. A paste stops with a notice when its target becomes invalid. The earlier concerns about lost chunks and missing messages appear addressed, and no blocking risk remains.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 4accb

The change strengthens paste targeting and stops remaining writes when the original editing context becomes invalid. No new security exposure was established in the reviewed paths. Residual uncertainty concerns interruption, concurrent operations, and recovery behavior.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — For the inspected path, attacker-controlled clipboard text can affect the document selected for a user-initiated paste. Ordering and target state are scoped to an editor instance; this path does not demonstrate additional service, credential, tenant, or infrastructure authority. Downstream behavior outside the inspected relationships remains unassessed.

Trust Boundaries and Controls

  • observed — Clipboard input is not used to choose a new editor or document. The handler respects previously handled events, requires an available editable editor, rejects oversized input, and checks focus, DOM identity, continuation policy, context version, and document continuity before each chunk.

Resilience and Maintainability Implications

  • observed — Cancellation contains further writes rather than rolling back accepted chunks. Idempotent disposal removes listeners and the temporary plugin, and a finally block conditionally closes the paste history boundary. Callback-exception recovery and native OS composition behavior were not directly demonstrated by the inspected tests.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 23 functions across 8 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 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 describes the main change: large Markdown pastes stay at their original selection.
Description check ✅ Passed The description covers the change, rationale, visual proof, testing, review, and checklist. It states that no issue is linked, although the template requires one for outside contributors, and the manu…
  • 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.

Important

A plugin's appendTransaction that overlaps the paste bookmark is treated as an interruption, so a large paste whose text contains a [[doc link]] ending exactly on a chunk boundary is silently truncated — reproduced deterministically below. The bookmark/position tracking itself is sound, and all 36 focused unit tests pass.

Reviewed changes

  • Selection-anchored chunked paste — executeRichMarkdownLargeTextPaste captures the paste-time selection as a SelectionBookmark, maps it through external edits via an editor.on('transaction') handler, and preserves the live caret/marks separately; the first chunk replaces the captured selection and later chunks advance from the previous chunk's insertionEnd.
  • History guard — new trackRichMarkdownLargePasteHistory plugin closes/splits undo history when the user edits during a yield, so uninterrupted chunks undo together and mid-paste edits undo separately.
  • Context-version cancellation — getRichMarkdownImageResolverContextVersion lets the paste cancel when the file/runtime resolver context changes mid-flight; availability now also requires editor.isEditable.
  • Coverage — ...selection.test.ts (25 cases), ...fidelity.test.ts, updated ...test.ts (36 total passing) plus a new Electron/CDP e2e spec.

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-large-paste-target branch 2 times, most recently from e2a66ac to 3d912af 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.

Important

The two new cancellation toasts reference i18n keys that are absent from en.json, so both localization gates fail. Add the keys before merging.

Reviewed changes

The delta since the prior pullfrog review (044e7509) reworks the two flagged behaviors and adds cancellation feedback.

  • Own-chunk plugin edits no longer abort the paste — the overlap-cancel in mapTransactions is gated on ownChunk, so a plugin appendTransaction reacting to the paste's own chunk (e.g. [[doc link]] auto-convert on a chunk boundary) is mapped through instead of cancelling; a genuine external edit overlapping the target still cancels.
  • Appended-only edits split undo history — trackRichMarkdownLargePasteHistory now sets externalBoundaryStarted and triggers closeHistory/onInterrupt for a doc change delivered only via appendedTransactions, so the doc-link auto-convert on a caret move stays out of the paste's undo event.
  • Cancellation feedback — cancelled pastes raise a toast.info distinguishing "stopped before it finished" from "target changed"; the size error is factored into showRichMarkdownLargePasteLimitError.
  • Checked storage access — getRichMarkdownImageResolverContextVersion reads editor.storage.image/contextVersion via in checks instead of Reflect.get, and the e2e spec reads the editor through .rich-markdown-editor.
  • Coverage — added fidelity/selection tests for the doc-link boundary continuation, appended-only undo segmentation, appended target replacement, and toast/no-toast assertions.

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

@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

  • Registered the two interrupted-paste messages in the English catalog — 3d912afe adds stopped and cancelled under auto.components.editor.richMarkdownLargeTextPaste in src/renderer/src/i18n/locales/en.json, resolving the localization-gate failure from the prior review; verify-localization-extraction and verify-localization-catalogs both pass locally. No other net change (branch was rebased, SHAs shifted).

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

@nwparker
nwparker force-pushed the nwparker/markdown-large-paste-target branch 2 times, most recently from fe7542a to 49da761 Compare October 4, 2026 21:59

@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

This run re-reviewed the commits since the last Pullfrog review (fe7542a → 49da761): concurrent-paste ordering and the paste-history boundary refactor.

  • Shared insertion-order tracker — rich-markdown-clipboard-insertion-order.ts assigns a monotonic per-editor request order and tags the paste's chunk transactions via a PluginKey.
  • Request-order-aware bookmark mapping — mapTransactions maps the pending bookmark through concurrent insertions with assoc chosen by request order, so earlier-requested content lands before the paste and later-requested content after it, while the live caret is left alone.
  • History boundary moved into plugin state — trackRichMarkdownLargePasteHistory stores its external-boundary flag in plugin state and exposes hasExternalBoundary(); the final history close is skipped when an external edit already opened a boundary, keeping a cancelling edit grouped with subsequent typing.
  • Coverage — the fidelity suite now exercises both concurrent-paste completion schedules, earlier/later image insertion and ordinary typing, cancelling-edit Undo grouping, and the 16 MiB rejection path.

ℹ️ Pending-image ordering is exercised only with a synthesized transaction

The earlier image / later image cases dispatch a hand-built transaction carrying richMarkdownClipboardInsertionOrderKey; no production image path sets that key in this PR. The image handler that will tag it is in sibling PR #25176 (which ships the same rich-markdown-clipboard-insertion-order.ts), so text-paste ordering is real today while the image counterpart is only unit-tested here. Not blocking, but worth remembering if the two PRs land separately.

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

@nwparker
nwparker force-pushed the nwparker/markdown-large-paste-target branch from 49da761 to 4accb09 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

This run re-reviewed the delta since the last Pullfrog review (49da761 → 4accb09, the branch rebased onto a753aff). The commit is a behavior-preserving simplification of the paste executor plus test-fixture dedup, and all 54 focused unit tests pass locally.

  • Simplified the Undo state — dropped the needsHistoryBoundary flag and now key each chunk's closeHistory on pasteTime === null, which is equivalent because the history plugin's onInterrupt resets pasteTime; the guard and the time pin can no longer drift apart.
  • Moved the captured-target check into the executor — the loop now tests isEditorPasteTargetCurrent(editor, targetDom) || !options.canContinue, and handleRichMarkdownLargeTextPaste no longer builds a guardedOptions wrapper. Same effective predicate (destroyed / editable / connected / same DOM / focused / canContinue), one less layer.
  • Resolved the yield and chunk bounds once — chunkMaxBytes and yieldBetweenBatches are hoisted so measuring and chunking share the same resolved yield function.
  • Inlined small helpers — readPlainText, readHtmlText, and shouldHandleLargeRichMarkdownPaste folded into the handler.
  • Reused test fixtures — shared createProductionEditor / pasteEvent / pause / flush helpers replace duplicated setup in the fidelity suite, and the base unit suite's hand-rolled fake editor is replaced with a real tiptap Editor. No regression case was dropped (fidelity 17, selection 27, base 10 = 54).

ℹ️ Pending-image ordering is still exercised only with a synthesized transaction

Carried forward from the prior review, not new: the earlier image / later image fidelity cases dispatch a hand-built transaction carrying richMarkdownClipboardInsertionOrderKey; no production image path sets that key in this PR. The image handler that tags it lives in sibling PR #25176 (which ships the same rich-markdown-clipboard-insertion-order.ts). Text-paste ordering is real today; the image counterpart is only unit-tested here.

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

@nwparker
nwparker merged commit d3afb5c into main Oct 4, 2026
37 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.

1 participant