Skip to content

Fix terminal paste cancellation after xterm focus replacement - #16819

Closed
brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/sta-3834-paste-cancelled-r1
Closed

brennanb2025 wants to merge 1 commit into
mainfrom
brennanb2025/sta-3834-paste-cancelled-r1

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​33 $\color{#cf222e}{\Huge{\mathbf{−}}}$​8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​25
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​31 $\color{#cf222e}{\Huge{\mathbf{−}}}$​9 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​22

ELI5

A paste could begin in the right terminal, wait for the clipboard, and then be cancelled because xterm replaced its hidden input element during that wait. Orca now remembers that the original input belonged to the pane, then accepts xterm's valid replacement only while the same pane and PTY still own focus.

In plainer words: you click into a terminal pane and press paste. Orca has to go and fetch the
clipboard, which takes a moment. During that moment the terminal widget sometimes quietly swaps out
the invisible box that receives your keystrokes — normal behaviour on its part. Orca was checking
"is the exact box I started with still on screen?", found a different one, decided the paste must be
aimed somewhere else, and cancelled it. Your text never arrived, even though the pane was right
there still accepting typing. Orca now checks the thing that actually matters — that the same pane
and the same running terminal still hold focus.

User-facing before / after

Before After
You paste into a terminal and the terminal widget replaces its hidden input while the clipboard is being read The paste was cancelled. Nothing arrived, and the pane still took typing normally, so there was no clue why The paste lands in the pane you aimed it at
Focus genuinely moves to a different pane mid-paste Cancelled Still cancelled — that is the case the guard exists for
Focus moves to something that isn't a terminal Cancelled Still cancelled
The pane's terminal is replaced by a different one mid-paste — Refused, so text can't land in the wrong process

When it bites

Reported on Linux, where the hidden-input replacement is most frequent, but the code path is the same
on every platform. It hits anyone pasting into a terminal pane, and it looks like the paste silently
did nothing.

What Changed

  • Capture terminal-pane focus ownership synchronously when paste dispatch begins.
  • Validate the current helper plus the existing pane, leaf, transport, and PTY identities before execution.
  • Keep rejecting focus that moves to another pane or a non-terminal control.
  • Add a red/green regression contract for xterm helper replacement and a wrong-owner safety case.

Why

STA-3834 / #13623 reports Linux pastes being cancelled even though input to the same pane remains available. The stale guard rechecked whether the original xterm helper was still contained after asynchronous clipboard reading; when xterm detached and replaced that helper, Orca rejected the valid current target.

Linked Issue

Fixes #13623

Linear: https://linear.app/stably/issue/STA-3834/bug-paste-cancelled

Visual Proof

The focused Electron journey delays clipboard delivery, replaces the xterm helper during the wait, and proves the marker reaches the terminal. It passed three consecutive recorded runs.

page@e8e076686077dc6a81c0e9b812d12162.webm

Baseline proof is deterministic rather than visual: the new helper-replacement unit contract failed before the fix (expected true, received false) and passes with this commit.

Testing

  • I manually tested these changes locally

  • Automated tests added/updated, or explained why not below

  • pnpm test across 8 focused terminal clipboard/paste suites: 96 passed.

  • pnpm tc:web: passed.

  • Explicit oxlint and oxfmt --check on all 3 changed files: passed.

  • Electron Playwright clipboard-blur journey: passed once in the focused validation and 3/3 in the recorded visual-proof run.

  • E2E-mode Electron bundle: passed.

  • pnpm run check:code-quality:changed: blocked before lint by a pre-existing Node 26 engine-warning JSON parse failure; direct changed-file lint passed.

Actual Linux desktop + Wispr Flow reproduction remains unverified; validation used the shared renderer path in Electron on macOS.

Review

Two adversarial review-until-clean rounds found no remaining in-scope issues. The scope excludes STA-5272's broader deferred-paste feature and cancellation-presentation changes.

Terminal reliability contract

  • Invariant (terminal-input.paste-focus-ownership): a paste started in a terminal pane may survive xterm helper replacement only while current focus remains in that pane and pane/leaf/transport/PTY identity is unchanged.
  • Failure source: STA-3834 / [Bug]: Paste cancelled #13623.
  • Oracle: the red/green helper-replacement unit contract plus the Electron delayed-clipboard journey that proves terminal delivery.
  • Gate: accepted gap—config/reliability-gates.jsonc has no dedicated paste-focus gate; the focused unit and Electron tests are not yet a manifest gate.
  • Coverage: the shared renderer check is platform-neutral and preserves existing local/daemon/SSH/remote/WSL PTY routing structurally. Electron macOS was exercised; Linux/Wispr, Windows/ConPTY, physical SSH, paired web, and mobile/relay were not exercised. Mobile paste interaction is unaffected.
  • Performance budget: one bounded focus snapshot and DOM containment check per paste; no polling, timers, subprocesses, collection scans, render subscriptions, or retained growth added.
  • Diagnostics: existing paste execution reasons remain visible through the terminal error path; the unit failure and Electron recording distinguish stale helper ownership from wrong-pane focus.
  • Residual gap: real Linux/Wispr behavior and cross-provider live runs remain unproved.

Agent skill upstream boundary

  • Not applicable, or this change follows docs/reference/agent-skill-sharing-upstream-boundary.md and copies or mechanically translates no upstream skill-installer source, tests, fixtures, registry entries, path tables, comments, or documentation.

Notes

No wire, persisted-state, Git, filesystem, path, shell, provider, or subprocess contract changes. Folder workspaces and Git providers are unaffected.

Checklist

  • This PR is small and focused
  • I explained what changed and why (including ELI5)
  • Before/after screenshots or videos attached for UI changes, or N/A with reason
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered (or N/A)
  • pnpm lint, pnpm typecheck, pnpm test, and pnpm build pass (or CI will cover; local preferred)

@coderabbitai

coderabbitai Bot commented Aug 27, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 79f6ce93-30d1-4d12-844d-b2a399f34b07

📥 Commits

Reviewing files that changed from the base of the PR and between 9253634 and 44b98f3.

📒 Files selected for processing (3)
  • src/renderer/src/components/terminal-pane/TerminalPane.tsx
  • src/renderer/src/components/terminal-pane/terminal-paste-target-state.test.ts
  • src/renderer/src/components/terminal-pane/terminal-paste-target-state.ts

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


📝 Walkthrough

Walkthrough

The terminal paste flow now captures a dispatch-time focus snapshot with the focused element and pane ownership. Clipboard and app-menu paste paths pass this snapshot through paste execution. Focus validation accepts dispatch focus outside the pane and continues to validate pane-owned focus changes. Tests cover retained focus, focus changes, transient blur, helper replacement, and non-pane-owned dispatch focus.

Merge Risk: ⚪ Minimal · up to 44b98

This localized change corrects terminal paste handling when xterm replaces its internal input while preserving pane and terminal ownership checks; no actionable merge-blocking risk remains after normal checks and review.

🚥 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 4 functions across 3 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 The changes address issue #13623 by preserving paste across valid xterm helper replacement while continuing to reject focus changes to another pane or non-terminal control.
Out of Scope Changes check ✅ Passed The changes are limited to terminal paste focus tracking and regression tests. No unrelated code or scope expansion is evident.
Title check ✅ Passed The title clearly and concisely identifies the primary change: preventing terminal paste cancellation after xterm focus replacement.
Description check ✅ Passed The description is mostly complete. It includes the ELI5, change summary, rationale, linked issue, visual proof, testing results, review notes, scope considerations, and checklist status. It also clea…
Full details: Description check

Explanation

The description is mostly complete. It includes the ELI5, change summary, rationale, linked issue, visual proof, testing results, review notes, scope considerations, and checklist status. It also clearly documents that some platform-specific validation and full required commands remain unverified.

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review verification (exact head 44b98f3 / PR #16819): completed three focused adversarial passes over pane-focus ownership, xterm helper replacement, pane/leaf/transport/PTY guards, lifecycle, remote/folder boundaries, and stale-branch behavior. No proven in-scope issues found; no production edits were needed. terminal-paste-target-state.test.ts passed (11/11), pnpm tc:web passed, reliability manifest passed (99 gates), changed-file oxlint and oxfmt checks passed, and all current GitHub checks passed. The changed-code-quality wrapper is blocked by a pre-existing Node 26 engine-warning JSON parse failure; direct oxlint passes. Merge verdict: merge-ready from code-review scope, with Linux/Wispr, physical SSH, paired web/mobile, and dedicated reliability-gate execution still unverified.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

QA evidence (macOS Electron via Playwright CDP only): attached to the exact worktree identity Orca: brennanb2025/sta-3834-paste-cancelled-r1 on renderer port 5176. I exercised a real terminal paste through the visible terminal input while delaying clipboard resolution and replacing the focused .xterm-helper-textarea; the rendered terminal visibly printed STA3834_VISIBLE_1787849762 and returned to a shell prompt, with one helper focused afterward. Full-window screenshot: sta3834-paste-proof-final.png. Backing evidence: focused target-state unit tests 11/11 pass and target identity checks remain pane/leaf/transport/PTY scoped. Not exercised: real Linux/Wispr Flow, Windows/ConPTY, physical SSH, paired web/mobile/relay, and a dedicated reliability-manifest gate for paste focus.

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Review loop r1 — recommend superseding this PR

Reviewed 44b98f3706d0072f4c47fb4adcd3ae36cd047ce3, rebased onto current origin/main (7bbb8adc61) before testing. Gates on the rebased tree: pnpm tc exit 0, oxlint exit 0 on all 3 files, oxfmt --check clean, git diff --check clean, 8 focused paste suites = 86/86 passing. Nothing here is unsafe — but I believe the change is a behavioral no-op, so I'd rather flag that than sign off.

Why I think it's a no-op

The diff changes exactly one thing: when paneContainer.contains(dispatchElement) is evaluated — execute time before, dispatch time (as ownedByPane) after. document.activeElement was already read at dispatch on both sides, and the rest of isTerminalPanePasteFocusCurrent is unchanged. That timing only matters if containment can flip between dispatch and execute, and I could not find a way for it to flip while the pane is mounted:

  1. .xterm-helper-textarea is created at exactly one site in the shipped @xterm/xterm bundle, inside open().
  2. Orca calls terminal.open(xtermContainer) exactly once per pane — src/renderer/src/lib/pane-manager/pane-lifecycle.ts:46, in createPane. No second open(), no reattach that rebuilds xterm's DOM.
  3. Live DOM probe in a dev build: the helper node and the .pane node keep their identity, and pane.contains(helper) stays true, across window resize, blur, and a pane split (which reparents containers).
  4. isTargetCurrent runs isPanePasteTargetMounted before the focus check (pane id+leafId in getPanes(), paneTransports.get(paneId) === transport, isConnected(), getPtyId() === ptyId), so a disposed or rebuilt pane is rejected earlier and never reaches the focus check.
  5. Remount was the strongest counter-candidate and fails too: teardown does paneTransports.clear() and managerRef.current = null (use-terminal-pane-lifecycle.ts:2014-2018), so a stale closure fails the mount check first.

Differential: I ran the pre-fix and post-fix predicates side by side over a real DOM built to match the live pane structure, with 12 focus candidates used as both the dispatch focus and the execute focus, crossed with requireSameFocusedElement true/false — 288/288 combinations agree, zero disagreements. The only way I could produce a disagreement was to physically detach the dispatch element from the pane mid-paste, which is the premise above.

On the red/green claim

It reproduces — ablating the ownedByPane gate back to the pre-fix containment check fails "keeps keyboard-owned paste current when xterm replaces its helper textarea" with expected false to be true. But the test replaces paneContainer with a contains mock whose accepted-element list flips from the original helper to the replacement, and real DOM containment does not flip that way while the pane is mounted. The double manufactures the state that makes the fix look load-bearing.

Ablation table

Hunk ablated Result Caught by
ownedByPane gate → pre-fix contains(activeElementAtDispatch) 1 failed / 10 passed "keeps keyboard-owned paste current when xterm replaces its helper textarea"
ownedByPane gate deleted (branch removed, not stubbed) 1 failed / 10 passed "rejects a replacement helper when the dispatch focus was never owned by the pane"
captureTerminalPanePasteFocusSnapshot forced to ownedByPane: true 11 passed — uncovered none
TerminalPane.tsx capture sites not pinnable structural — TerminalPane.tsx has no unit harness

That third row is a real gap regardless of the rest: the negative test hand-builds { element, ownedByPane: false } rather than calling the real capture function, so regressing the capture to always-true passes everything.

Can a paste still be silently dropped? Yes — and not from this code path

Measured in a dev build: with focus outside the terminal container (document.activeElement === body, which is what an external dictation/overlay tool leaves behind), Cmd+V produces no paste and no toast at all — onKeyPaste is bound to the TerminalPane root container with {capture:true}, so a keydown targeted at body never reaches it. That matches the instrumented follow-up in #13623. Separately, terminal-clipboard-paste.ts:55-64 swallows a non-size readClipboardText failure and, with no image on the clipboard, returns reason:'empty' with no error callback — a read failure surfaces to the user as "nothing on the clipboard".

Once a paste actually executes, drops are not silent: every non-pasted status calls setTerminalError(...) and TerminalErrorToast renders durably until dismissed.

Other things checked

Suggestion

I'd supersede rather than patch. The two reachable defects look like: a paste aimed at a terminal whose pane doesn't hold DOM focus is discarded with no signal (routing is getActivePane() while ownership is tested against document.activeElement), and the clipboard-read-error-as-empty case above. The first is essentially STA-5272's deferred-paste work, which this PR explicitly scopes out — so it's a design call rather than something to bolt on here. I deliberately didn't push a speculative redesign.

Not verified: live mid-paste PTY-replacement run, Linux/Wispr Flow reproduction, Windows/ConPTY, packaged build (dev-mode CDP is blind to packaged regressions), physical SSH, relay, paired web, and mobile legs.

@OrcaWin

OrcaWin commented Oct 26, 2026

Copy link
Copy Markdown
Collaborator

Closing because the helper-replacement premise does not occur in the current terminal lifecycle, so this change does not repair the reported paste failure.

I reviewed the full diff at 44b98f3706d0072f4c47fb4adcd3ae36cd047ce3 and independently checked the later review's conclusion:

  • The only behavioral change is evaluating paneContainer.contains(dispatchElement) at dispatch rather than execution.
  • The shipped @xterm/xterm version (6.1.0-beta.304) creates its helper textarea once, in CoreBrowserTerminal.open(). Orca opens each newly created pane once; splitting/reparenting retains that pane's DOM. There is no production helper-replacement path.
  • Rebuilding a pane clears its transport map/manager, so a stale paste fails isTerminalPanePasteTargetCurrent before reaching this focus check.
  • A differential check using the actual main and PR predicates agreed across all 288 combinations of 12 focus targets and both ownership modes. Detaching the original helper manually produces the test's difference, but that is the manufactured transition rather than a shipped lifecycle transition.

The actual inert-focus routing and clipboard-read-error cases remain useful work and are addressed separately by #17020. This closure does not claim that the reported Linux/Wispr failure is fixed, and is unrelated to merge conflicts. If a real helper-detachment path is found, that evidence would justify revisiting this guard.

@OrcaWin OrcaWin closed this Oct 26, 2026
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.

[Bug]: Paste cancelled

2 participants