Skip to content

fix(terminal): make primary-selection paste suppression single-shot - #10526

Merged
brennanb2025 merged 3 commits into
mainfrom
brennanb2025/p2-primary-selection-suppression
Jul 25, 2026
Merged

brennanb2025 merged 3 commits into
mainfrom
brennanb2025/p2-primary-selection-suppression

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Summary

On Linux, middle-clicking in the integrated terminal armed a 750ms window (PRIMARY_SELECTION_NATIVE_PASTE_SUPPRESSION_MS) that swallowed every paste event on the terminal surface for its full duration. Press Ctrl+V within 750ms of a middle-click paste and the keyboard paste was silently dropped — no error, no text, no feedback.

The armed window exists for exactly one reason: the terminal injects the primary selection into the PTY itself on middle-click, so Chromium's single follow-up native paste event has to be swallowed to avoid a double paste. #8993, which introduced the window, says so in its own commit message: "This swallows the single native paste event so the selection reaches the PTY exactly once." The 750ms is an upper bound on when that one event arrives — not a period during which all pastes should die. shouldSuppressPrimarySelectionNativePaste never cleared the deadline once consumed, so it kept answering true until it timed out.

Fix: make the suppression single-shot. consumePrimarySelectionNativePasteSuppression clears the deadline on first use, so the arm owes at most one event. 750ms stays as the expiry bound for that one event.

The rename makes the mutation obvious at the call site — the old name promised a pure predicate. usePrimarySelectionPaste is the only non-test consumer (TerminalPane only arms), and the short-circuit order is preserved so a paste outside the terminal surface never eats the arm.

Platform gating is untouched: armPrimarySelectionNativePasteSuppression still no-ops off Linux/X11, and setPrimarySelectionEnabled(false) still resets the deadline to 0.

17 net source lines across 2 files; the rest is test coverage.

Screenshots

No visual change — this is terminal input-event behavior with no UI surface.

Testing

  • pnpm lint — clean
  • pnpm typecheck — clean
  • pnpm test — the three touched files: 28 passed. Wider sweep: src/renderer/src/lib/ + src/renderer/src/hooks/ = 373 files / 3414 passed, and src/renderer/src/components/terminal-pane/ = 183 files / 2381 passed.
  • pnpm build — via CI verify
  • Added regression tests, verified non-vacuous

Non-vacuity was proven by reverting only the source logic (restoring the non-consuming predicate body while keeping the new name, so failures are about logic and not imports) and re-running:

× lets a real paste through after the follow-up is consumed inside the window
  → expected true to be false
× consumes only one follow-up per arm across repeated middle-clicks
  → expected true to be false
× swallows the first follow-up paste but not a later real paste in the same window
  → expected true to be false
× swallows one clipboard paste per arm, the event xterm forwards to the PTY
  → expected true to be false
 Tests  4 failed | 24 passed (28)

With the fix restored: Tests 28 passed (28).

The last two failures are from a new file, usePrimarySelectionPaste.terminal-native-paste.test.tsx. The existing hook test mocks @/lib/primary-selection wholesale, so it structurally cannot observe single-shot behavior — a same-file test there would pass with or without the fix. The new file wires the hook to the real module and dispatches two paste events at an .xterm-helper-textarea, asserting the first is prevented and the second is not — once as beforeinput, and once as a real paste ClipboardEvent, which is the event xterm actually forwards to the PTY. Those are the end-to-end assertions for the bug.

The short-circuit order in usePrimarySelectionPaste.ts also became load-bearing once consume gained a side effect: swapping the operands would burn the arm on an unrelated paste and let the real follow-up double-paste, while leaving defaultPrevented unchanged. That swap is now caught by asserting consume is never reached for a non-terminal target (verified by simulating the swap: the guard fails, and without it the swap was invisible).

Also kept from the existing suite: time-based expiry, the disable-clears-armed-state case, off-Linux no-arm, and "unrelated document paste is not swallowed while armed."

AI Review Report

Reviewed with parallel AI subagents (correctness/regression, and scope/standards) plus a throwaway runtime probe, looping until clean.

Risks checked and what came back:

  • Does it fix the reported bug? Yes. Verified against the production arm sequence, which arms twice per gesture — TerminalPane arms on both mousedown (TerminalPane.tsx:2663) and auxclick (TerminalPane.tsx:2740). A runtime probe confirmed arm→arm→consume leaves the window disarmed, so the follow-up is eaten and a subsequent real paste survives.
  • Double-paste regression (the main risk). Under the old code both paste and beforeinput were suppressed for the whole window; single-shot eats only the first. This is safe because only one of the two can reach the handler per native paste: Blink dispatches paste first, and the capture-phase preventDefault aborts the paste pipeline, so beforeinput never fires. It is also the event that matters — xterm forwards to the PTY from a paste listener on its textarea/element (@xterm/xterm CoreBrowserTerminal.ts), and does not listen to beforeinput. A probe confirmed a real paste ClipboardEvent is suppressed exactly once per arm.
  • Cross-platform (macOS / Linux / Windows). Explicitly checked. Behavior is Linux/X11-only by construction: armPrimarySelectionNativePasteSuppression early-returns unless isLinuxUserAgent(getUserAgent()), so macOS and Windows never arm and are byte-for-byte unaffected. No shortcuts, labels, paths, shell behavior, or Electron main-process code are touched — this is renderer-only DOM event handling. A macOS no-arm case is covered in the new test file.
  • SSH / folder workspaces / non-GitHub git providers. Not applicable: the change is entirely in the renderer's DOM paste path and never reaches PTY transport, workspace resolution, or any git provider.
  • Perf. Neutral-to-better. consume is the same O(1) numeric comparison the predicate was, on the same capture-phase handler, with no new allocation, timer, or listener. It now reduces work in the common case, since a disarmed window short-circuits on nativePasteSuppressionUntil === 0.
  • Scope. One concern only: one commit, 5 files, 17 net source lines. No unrelated changes, no drive-by refactors, no max-lines disables (AGENTS.md), no stale references to the old symbol name anywhere in the repo.

Security Audit

No new attack surface. No input parsing, no command execution, no path handling, no auth, no secrets, no dependency changes, and no IPC surface is touched. The change narrows when a DOM event is suppressed inside the renderer; it does not alter what text is read, where it comes from, or what is written to the PTY. Clipboard content still flows through the existing PRIMARY_SELECTION_MAX_LENGTH / maxBytes bounds, which are unchanged. If anything the change is defensively better: it shortens the window during which the app silently discards user input. No follow-up needed.

Notes

Platform-specific behavior and residual risks, stated honestly:

  • Not runtime-verified on real Linux/X11. Developed and reviewed on macOS. The Chromium event-sequence claims were checked in a real Electron probe (Electron 43.1.0 / Chromium 150, Orca's shipped runtime), which confirmed paste fires first, is cancelable, and that cancelling it at document capture suppresses beforeinput and input entirely. But that probe drove Editor::Paste, not an actual X11 middle-click; the real primary-selection follow-up on a Linux host is still unexercised. This is the one thing worth a Linux reviewer's eyes.
  • Arm without a follow-up. If a middle-click arms but no native follow-up ever arrives (empty primary selection, a Wayland compositor with no primary paste, or focus off the helper textarea), the deadline dangles and the first real paste inside 750ms is still eaten. Strictly better than today — where every paste in the window dies rather than one — but not zero. Fixing that would mean disarming on a signal this layer does not have.
  • Pre-existing arm/auxclick ordering (unchanged by this PR). TerminalPane arms on mousedown and re-arms on auxclick. If Chromium's native paste ever landed between those two, the consume would disarm and auxclick would immediately re-arm an unowed window. Checked against Blink: event_handler.cc dispatches pointerup/mouseup and then auxclick via DispatchMouseClickIfNeeded, and only then runs the paste — selection_controller.cc confirms the paste happens on mouse-up "after the event handlers have been fired." So the paste lands after both arms and the spare-arm path is not reachable. Left alone deliberately: touching it would mean changing TerminalPane, which is out of scope here.

Middle-clicking in the terminal armed a 750ms window that swallowed every
native paste event, not just Chromium's one follow-up — so a real Ctrl+V
inside that window was silently dropped on Linux.

Consume the deadline on first use (`shouldSuppress*` -> `consume*`) so the
arm owes exactly one event; 750ms stays as that event's expiry bound.
@coderabbitai

coderabbitai Bot commented Jul 25, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@brennanb2025, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 19 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 88fd6419-8eda-43d0-840c-db82036351b0

📥 Commits

Reviewing files that changed from the base of the PR and between 6df6e41 and f7ea787.

📒 Files selected for processing (1)
  • src/renderer/src/hooks/usePrimarySelectionPaste.terminal-native-paste.test.tsx
📝 Walkthrough

Walkthrough

Native primary-selection paste suppression now uses a consuming helper that clears the suppression deadline after the first eligible terminal-native paste. The paste hook calls this helper for terminal paste events. Existing unit tests are updated to the new API, and new integration tests cover Linux follow-up suppression, later paste allowance, unarmed terminals, and macOS behavior.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
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 and concisely describes the main change: making terminal primary-selection paste suppression single-shot.
Description check ✅ Passed The description follows the required template and includes summary, screenshots, testing, AI review, security audit, and notes.

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.

Review follow-ups on the single-shot suppression change; no source change.

The new real-module file only synthesized `beforeinput`. An Electron
probe (Chromium 150) showed `paste` fires first, is cancelable, and
cancelling it at document capture suppresses `beforeinput` entirely — and
xterm registers `handlePasteEvent` for `paste` only, never `beforeinput`.
So `paste` is the sole event that can double-write the PTY, and it was
the one event the end-to-end file did not exercise. Add it; it fails with
the fix reverted.

Consuming mutates, so `isTerminalNativePasteTarget(...) && consume()` is
now load-bearing: swapped operands would burn the arm on an unrelated
paste and let the real follow-up double-paste. The guarding test asserted
only `defaultPrevented`, which survives the swap — assert `consume` is
never reached instead.

Rename the mocked-file case that claimed to prove single-shot. With the
module mocked its sequence is dictated by the mock; it pins that the hook
re-asks per event rather than caching, so name it that.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review round — CodeRabbit disposition + subagent findings

CodeRabbit

CodeRabbit generated no actionable inline comments ("No actionable comments were generated in the recent review"). Its pre-merge checks came back 4 passed / 1 warning. Disposition of the one warning:

CodeRabbit item Disposition
Description check ⚠️ — "misses the required Summary, Screenshots, AI Review Report, Security Audit, and Notes sections" ACTIONED. The description has been rewritten against .github/pull_request_template.md, with all six sections filled in — including No visual change for Screenshots, a real Security Audit, and an AI Review Report that explicitly covers macOS/Linux/Windows as the template requires.
Title check ✅ / Docstring coverage ✅ / Linked issues ✅ / Out-of-scope ✅ No action needed.

Subagent review (2 agents, both Opus 5, same effort)

Both returned. They disagreed on the main functional question; adjudication below.

Actioned — pushed in 6df6e41 (tests only, no source change):

  1. The end-to-end file tested the wrong event. usePrimarySelectionPaste.terminal-native-paste.test.tsx only synthesized beforeinput. An Electron probe (Chromium 150, Orca's shipped runtime) showed paste fires first, is cancelable, and cancelling it at document capture kills beforeinput and input entirely — and @xterm/xterm's CoreBrowserTerminal.ts registers handlePasteEvent for 'paste' only, never beforeinput. So paste is the only event that can double-write the PTY, and it was the one the "end to end" file did not exercise. Added; it fails with the fix reverted.
  2. The newly load-bearing short-circuit was untested. Now that consume() mutates, isTerminalNativePasteTarget(...) && consume() is order-sensitive: swapped operands would burn the arm on an unrelated paste and let the real follow-up double-paste (i.e. [Bug]: Middle-click paste inserts the selection twice in the integrated terminal (Linux/X11) #8860 returns), while leaving defaultPrevented unchanged so the guarding test still passed. Now asserts consume is never reached for a non-terminal target. Verified by simulating the swap — the guard fails; without it the swap was invisible.
  3. A test title overclaimed. The mocked-file case named "lets a keyboard paste through once the armed follow-up has been consumed" cannot observe single-shot — the module is mocked, so its pass/fail is dictated by the mock. Renamed to what it actually pins (the hook re-asks per event rather than caching).

Declined, with reasoning:

  1. "TerminalPane arms twice per gesture, so a consume between mousedown and auxclick leaves a live spare arm that still eats the next Ctrl+V." Declined — not reachable. Blink event_handler.cc dispatches pointerup/mouseup and then auxclick via DispatchMouseClickIfNeeded, and only then runs the paste; selection_controller.cc states the paste happens on mouse-up "after the event handlers have been fired." The paste therefore lands after both arms. The second agent reached the opposite conclusion but only on the grounds that the ordering was unverified — it has now been verified from Blink source. Independently: even under the inverted ordering the result would be strictly better than main (one paste eaten instead of every paste for 750ms), and fixing it would require changing TerminalPane, which is out of scope for this PR.
  2. "Drop the two negative-control tests in the new file as duplicates." Declined — the unarmed and macOS cases are what give the positive assertion meaning (they rule out "suppression is simply always on/off"). They cost 12 lines in a 145-line file against an 800-line cap. Removing them is churn, not a fix.
  3. "The pre-existing test dispatching both beforeinput and paste asserts behavior the real code no longer provides." Declined — that test's subject is target scoping (the no-pending-DOM-target path), not event counting; mockReturnValue(true) stands in for "armed," and checking both event types pins that the handler is wired to both listeners. It asserts nothing false about single-shot.
  4. "The nativePasteSuppressionUntil === 0 clause is redundant since Date.now() > 0 always." Declined — correct that it never changes production behavior, but it documents 0 as the disarmed sentinel, which is exactly the state this change introduces. Deleting it trades clarity for nothing.

Verification

  • Revert-check (source logic reverted, tests kept): 4 failed | 24 passed (28). Restored: 28 passed (28). The tests are not vacuous.
  • pnpm typecheck, pnpm lint, check:max-lines-ratchet (0 new bypasses) all clean; CI verify passed on the parent commit.
  • Wider sweeps green: src/renderer/src/lib + hooks = 373 files / 3414 tests; components/terminal-pane = 183 files / 2381 tests.
  • Not verified: real Linux/X11 middle-click. All of this was done on macOS.

…atches

Round-2 review nit on my own round-1 change: once `dispatchClipboardPaste`
existed alongside it, a helper named `dispatchPaste` that dispatches
`beforeinput` inverted the reader's expectation. Match the sibling file's
`dispatchNativePasteBeforeInput` convention.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Round 2 — adversarial re-verify

A second independent agent re-ran the revert-check from scratch and tried to break the change. It reproduced 4 failed | 24 passed (28) exactly, and validated both round-1 additions by mutation rather than by inspection:

  • The new paste-ClipboardEvent test fails on revert, so it is load-bearing. new Event('paste') is not too weak a stand-in: the handler's only type discriminant is !(event instanceof InputEvent) and it never reads clipboardData, so a real ClipboardEvent drives the identical branch.
  • Swapping the && operands to consume() && isTerminalNativePasteTarget(...) produced 1 failed | 11 passed — the not.toHaveBeenCalled() assertion added in round 1 was the only thing in the entire suite that caught it.
  • Isolation: three shuffled runs (seeds 137/274/411) → 28 passed each; new file alone → 4 passed; all four primary-selection* files → 41 passed; full terminal-pane suite → 183 files / 2381 tests passed.

Actioned — pushed in f7ea787 (tests only): a naming inversion I introduced in round 1 — a helper named dispatchPaste that dispatches beforeinput, sitting next to dispatchClipboardPaste. Renamed to dispatchPasteBeforeInput, matching the sibling file's existing convention.

Declined, with reasoning:

  1. "The arm still eats one real paste when the native follow-up never arrives" (e.g. empty PRIMARY, or a Wayland compositor with no primary-paste path — and Chromium reports X11; Linux x86_64 in the UA even under Ozone/Wayland, so it can't be gated). Accurate, and already called out under Notes in the description. Declined as out of scope: it is inherent to arm-and-hope, it is strictly better than main (one lost paste rather than every paste for 750ms), and this PR narrows it rather than introducing it. The proposed remedy — clear the deadline on the first capture-phase keydown — is not safe as a drop-in: a user who middle-clicks and then types any key before the follow-up arrives would clear the arm and get the double-paste that fix(terminal): stop native middle-click paste inserting twice on Linux #8993 exists to prevent. Worth a follow-up with its own design, not a bolt-on here.
  2. "Consuming from the beforeinput listener can burn the arm without protecting the event that matters." Real reasoning, and the agent agrees it is not a live bug on Chromium 150. Declined deliberately. The proposed hardening — gate the terminal branch on event.type === 'paste' — is riskier than the status quo given we cannot runtime-verify on X11: if any real Linux configuration ever delivers the follow-up as beforeinput without a preceding cancelable paste, that gate reintroduces the [Bug]: Middle-click paste inserts the selection twice in the integrated terminal (Linux/X11) #8860 double-paste, which is a worse failure than the one it prevents. Listening to both, as today, is the conservative choice. Noted as a follow-up.
  3. "Any .xterm surface can burn another pane's arm." Declined — isTerminalNativePasteTarget is unchanged by this PR, and closing it means pane-scoped arming in TerminalPane, which is a different concern. The exposure is the few milliseconds between mouseup and the follow-up.
  4. "The two end-to-end tests depend on the real clock." Declined — the arm and the dispatch are separated only by variable declarations, so flipping an assertion needs a >750ms stall between adjacent statements. The sibling file already uses this pattern; adding fake timers here is churn.
  5. "Branch is 2 commits behind origin/main." No action — PR is MERGEABLE, and the diff against the merge-base is the real 5 files.

Scope re-checked and unchanged: one concern, one production behavior change (shouldSuppress* → consuming consume* plus the call swap); the other two commits are tests only. No max-lines disables; check:max-lines-ratchet reports OK — no new bypasses.

Still not verified: real Linux/X11 middle-click. All review and testing was done on macOS; the Chromium event-ordering claims come from an Electron probe and Blink source, not from a live X11 session.

@brennanb2025
brennanb2025 merged commit 9bc640a into main Jul 25, 2026
1 check passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…tablyai#10526)

* fix(terminal): make primary-selection paste suppression single-shot

Middle-clicking in the terminal armed a 750ms window that swallowed every
native paste event, not just Chromium's one follow-up — so a real Ctrl+V
inside that window was silently dropped on Linux.

Consume the deadline on first use (`shouldSuppress*` -> `consume*`) so the
arm owes exactly one event; 750ms stays as that event's expiry bound.

* test(terminal): cover the paste event xterm actually forwards to the PTY

Review follow-ups on the single-shot suppression change; no source change.

The new real-module file only synthesized `beforeinput`. An Electron
probe (Chromium 150) showed `paste` fires first, is cancelable, and
cancelling it at document capture suppresses `beforeinput` entirely — and
xterm registers `handlePasteEvent` for `paste` only, never `beforeinput`.
So `paste` is the sole event that can double-write the PTY, and it was
the one event the end-to-end file did not exercise. Add it; it fails with
the fix reverted.

Consuming mutates, so `isTerminalNativePasteTarget(...) && consume()` is
now load-bearing: swapped operands would burn the arm on an unrelated
paste and let the real follow-up double-paste. The guarding test asserted
only `defaultPrevented`, which survives the swap — assert `consume` is
never reached instead.

Rename the mocked-file case that claimed to prove single-shot. With the
module mocked its sequence is dictated by the mock; it pins that the hook
re-asks per event rather than caching, so name it that.

* test(terminal): name the beforeinput dispatcher for the event it dispatches

Round-2 review nit on my own round-1 change: once `dispatchClipboardPaste`
existed alongside it, a helper named `dispatchPaste` that dispatches
`beforeinput` inverted the reader's expectation. Match the sibling file's
`dispatchNativePasteBeforeInput` convention.
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