Skip to content

[P2] fix(terminal): always close the bracketed-paste frame and hold the pty lock through submit - #11816

Merged
nwparker merged 1 commit into
mainfrom
nwparker/fix-terminal-paste-atomicity
Jul 31, 2026
Merged

nwparker merged 1 commit into
mainfrom
nwparker/fix-terminal-paste-atomicity

Conversation

@nwparker

@nwparker nwparker commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Two independent P2s found by the v1.4.163-rc.1..v1.4.163-rc.3 production release scan, both in the terminal paste path. Both leave the terminal in a state the user cannot easily diagnose or escape.

Bug A — an aborted chunked paste can leave the PTY stuck in bracketed-paste mode

A large paste (over TERMINAL_PASTE_DIRECT_MAX_BYTES, 64 KiB) is written to the PTY as a sequence of chunks: ESC[200~, the payload in pieces, then ESC[201~. The opening sequence puts the shell or TUI into bracketed-paste mode, where it buffers input as literal text instead of interpreting it. It stays there until the closing sequence arrives.

On origin/main, executeTerminalPastePlanNow closed that frame on exactly one of its four exit paths — the stale-target check. The other three returned immediately with the frame still open:

if (writeResult.timedOut) {
  return finish('cancelled', chunksWritten, 'operation-timeout')   // frame left open
}
if (!writeResult.value) {
  return finish('cancelled', chunksWritten, 'target-disconnected') // frame left open
}

and an exception thrown by writePty itself escaped the function without closing anything.

Impact: the terminal silently stops responding to input as input. Keystrokes and Enter are swallowed as paste payload; the shell never runs anything. There is no error, no indication of the mode, and no obvious recovery short of killing the terminal.

Fix: the chunk loop moves into writeChunks(), which returns a ChunkedPasteOutcome instead of returning from the outer function, and the close is a finally:

try {
  outcome = await writeChunks()
} finally {
  // Why: every exit, including an unexpected writer rejection, must leave the frame closed.
  closeTimedOut = (await closeBracketedPasteFrame()).timedOut
}

closeBracketedPasteFrame is idempotent (bracketedPasteOpen is cleared on entry), still respects canContinue(), is itself timeout-wrapped, and is wrapped in try/catch so a close failure cannot mask the real exit reason. The bracketedPasteOpen = bracketedPasteOpen && chunk !== BRACKETED_PASTE_END lines handle the one case where the close chunk itself is what failed — retrying it would emit a stray terminator. The pre-existing stale-target + close-timeout combination keeps reporting operation-timeout, so no existing caller sees a changed reason code.

Bug B — paste and its submit Enter were not one transaction

sendBracketedPasteToAgent pastes a draft and then, if submit is set, waits POST_PASTE_SUBMIT_DELAY_MS (50 ms) before sending \r. The delay is deliberate and documented: Claude Code can leave the prompt as editable text if paste-end and Enter land in the same PTY write.

On origin/main the paste took the per-PTY runTerminalPtyInputTransaction lock and then released it, leaving that 50 ms window unguarded. Anything else writing to the same PTY in that window interleaves between the payload and the Enter — so the Enter submits whatever is in the prompt at that moment, which is the first draft plus part of a second one.

Fix: take the lock once, around both:

return await runTerminalPtyInputTransaction(ptyId, async () => {
  const pasted = await sendAgentDraftPasteContentNow(settings, ptyId, content)
  if (!pasted || !submit) return pasted
  await new Promise<void>((resolve) => window.setTimeout(resolve, POST_PASTE_SUBMIT_DELAY_MS))
  return await sendRuntimePtyInputVerified(settings, ptyId, '\r')
})

runTerminalPtyInputTransaction is a promise-tail mutex and is not reentrant — naively wrapping the existing call would have deadlocked the PTY permanently. agent-draft-paste-content.ts therefore exports sendAgentDraftPasteContentNow, the non-locking inner variant, following the existing X / XNow convention in this module. sendAgentDraftPasteContent (the locking wrapper) is unchanged for its other callers. The 50 ms delay constant is unchanged — only relocated inside the lock.

ELI5

A. When you paste something big, Orca tells the terminal "everything until I say stop is text you should just sit on, not commands to run". If the paste is interrupted partway — the connection drops, the write times out — Orca was forgetting to say "stop". The terminal keeps waiting, so your typing goes into a void: you press Enter and nothing happens, with no error explaining why. Now the "stop" is sent on every possible way out, including crashes.

B. When Orca hands a drafted prompt to a coding agent, it does two things: paste the text, wait a beat, then press Enter. The beat is necessary — press Enter too fast and the agent leaves the text sitting there unsent. But Orca only held the "nobody else write to this terminal" lock for the paste, then let go during the beat. If a second paste started right then, it slipped in before the Enter — and the Enter submitted a mashup of both prompts. Now the lock is held across the whole thing, so nothing can wedge itself in the middle.

Screenshots

No visual change. Neither fix alters any rendered element. Bug A's symptom is an invisible terminal mode; bug B's symptom is a corrupted prompt string. Both are exercised through the PTY write stream, which is what the tests below assert on directly.

Proof of fix

Each fix was reverted independently so neither can take credit for the other.

Bug A — terminal-paste-executor.ts reverted to origin/main, tests kept:

 × closes an opened bracketed paste when a payload write is rejected
 × closes an opened bracketed paste when a payload write exceeds the safety timeout
 × closes an opened bracketed paste when the PTY writer throws

AssertionError: expected [ '^[[200~', '0123' ] to deeply equal [ Array(3) ]
AssertionError: expected [ '^[[200~', '0123' ] to deeply equal [ Array(3) ]
AssertionError: expected [ '^[[200~', '0123' ] to deeply equal [ Array(3) ]

 Test Files  1 failed (1)
      Tests  3 failed | 27 passed (30)

The actual array is the bug: the PTY received ESC[200~ and a payload chunk, and nothing else. The frame was opened and never closed, for all three failure modes.

Bug B — agent-paste-draft.ts and agent-draft-paste-content.ts reverted to origin/main, tests kept:

 × holds the PTY transaction across the paste and its submit Enter

AssertionError: expected [ …(7) ] to deeply equal [ Array(1) ]

 Test Files  1 failed (1)
      Tests  1 failed | 32 passed (33)

The test starts a competing paste on the same PTY during the 50 ms delay and asserts nothing lands between the payload and the Enter. Unfixed, the competing paste's 7 writes all land inside the window.

With both fixes restored: 2 files / 63 tests passed.

Proof of no regression

  • Targeted suite at branch tip: 2 files / 63 tests passed (30 in terminal-paste-coordinator.test.ts, 33 in agent-paste-draft.test.ts), of which 60 are pre-existing and unmodified.
  • Full desktop suite on the merged tree containing all eight scan fixes: 359 files / 3830 tests passed.
  • npx oxfmt --check and npx oxlint clean.
  • Deadlock specifically checked, since it is the failure mode this refactor invites and a test would hang rather than fail: verified by inspection that agent-paste-draft.ts:218 is the only lock acquisition on that path and :219 calls the non-locking …Now variant. sendAgentDraftPasteContent (the locking wrapper) has no remaining caller inside a transaction.
  • terminal-paste-executor.ts is 191 lines, within the 300-line cap. No max-lines disable added.
  • Existing reason codes are preserved, not just tests: the stale-target-plus-close-timeout path still reports operation-timeout, so no caller's error handling changes.

Deliberately not touched: agent-draft-paste-content.ts's own chunked-close logic (a separate path, already correct), everything introduced by #11612, and active-agent-note-send.ts:218 (a different call site that does not submit and therefore has no unguarded window).

Testing

  • pnpm lint — clean (oxlint, type-aware audit, reliability gates, max-lines ratchet, localization catalog/extraction/coverage); oxfmt --check clean via lint-staged
  • pnpm typecheck — clean (tsc: node + cli + web)
  • pnpm test (targeted at tip + full desktop suite on the combined tree)
  • pnpm build — not run; no build-graph, packaging, or dependency change
  • Added or updated high-quality tests that would catch regressions

AI Review Report

Reviewed by Claude Opus 5 as part of a 45-agent release scan with adversarial refutation. Risks checked:

  • Concurrency / deadlock. The dominant risk. runTerminalPtyInputTransaction is a per-ptyId promise-tail mutex with no reentrancy guard, so a double acquisition would wedge that PTY for the lifetime of the session with no error. Handled via the …Now split and verified by call-site inspection (a hang cannot be caught by a passing test).
  • Lock hold time. The critical section grows by POST_PASTE_SUBMIT_DELAY_MS (50 ms). That is bounded, applies only when submit is true, and is the whole point — the alternative is a submitted prompt containing two drafts. It is far shorter than the chunked-write phase the lock already covered.
  • Cleanup and error paths. The finally runs on the exception path too, which is the case origin/main handled worst. closeBracketedPasteFrame is idempotent and independently timeout-wrapped so a hung writer cannot make cleanup hang the paste.
  • Cross-platform: no platform branch, path, or shell handling. The bracketed-paste escape sequences and the PTY write API are identical on macOS, Linux, and Windows.
  • SSH / relay: both fixes are in the renderer and operate on ptyId, above the transport. A remote PTY reaches the same code, and the dropped-connection case (!writeResult.value → target-disconnected) is precisely the SSH failure mode bug A left the frame open on — so this matters more on SSH and relay than locally.

Security Audit

  • No new dependencies, no lockfile change, no install hooks.
  • No eval, no shell string construction, no path handling, no auth, no secrets, no network.
  • Terminal control sequences are the relevant surface. The only bytes this PR can newly cause to be written are BRACKETED_PASTE_END (ESC[201~), from the existing constant, on failure paths that previously wrote nothing. Writing a terminator without a matching opener is checked and prevented: closeBracketedPasteFrame returns immediately unless bracketedPasteOpen, clears the flag on entry so it cannot double-fire, and the chunk !== BRACKETED_PASTE_END guards stop a retry when the close chunk is itself what failed. No user-controlled data is added to the write stream.
  • Bug A's fix is a defensive improvement in its own right: leaving a terminal in bracketed-paste mode means subsequent keystrokes — potentially including things the user types believing they are running a command — accumulate in a paste buffer instead.
  • Bug B's fix closes a race that could cause an agent to receive and act on a prompt the user never composed. Local-only and not remotely triggerable, but it is an integrity issue rather than a cosmetic one.

Notes

  • Both bugs are hard to reproduce by hand — bug A needs a large paste interrupted mid-flight, bug B needs two pastes within a 50 ms window — and both fail silently rather than loudly, which is why they are worth pinning with tests even at P2.
  • Bug B's fix intentionally does not change POST_PASTE_SUBMIT_DELAY_MS. The delay exists for a real TUI behaviour in Claude Code; shortening it would trade this race for that one. The fix makes the window safe rather than smaller.

Made with Orca 🐋

@coderabbitai

coderabbitai Bot commented Jul 31, 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: 567ff62c-ef08-4a4c-bb7e-0d03770466f8

📥 Commits

Reviewing files that changed from the base of the PR and between e698241 and 3a605b7.

📒 Files selected for processing (5)
  • src/renderer/src/components/terminal-pane/terminal-paste-coordinator.test.ts
  • src/renderer/src/components/terminal-pane/terminal-paste-executor.ts
  • src/renderer/src/lib/agent-draft-paste-content.ts
  • src/renderer/src/lib/agent-paste-draft.test.ts
  • src/renderer/src/lib/agent-paste-draft.ts

📝 Walkthrough

Walkthrough

Chunked terminal paste execution now tracks write outcomes, detects stale or disconnected targets, applies write timeouts, and closes bracketed-paste frames in a best-effort finalizer. Agent draft paste sending now uses an immediate content-send API within a PTY input transaction. Delayed Enter submission remains conditional and serialized with the paste. Tests cover cleanup failures, timeouts, writer exceptions, and transaction ordering.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes both primary fixes: bracketed-paste cleanup and holding the PTY lock through submit.
Description check ✅ Passed The description covers the required sections, explains the fixes, documents testing, and includes AI review, security, and platform notes.
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.
✨ Finishing Touches
📝 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.

@greptile-apps

greptile-apps Bot commented Jul 31, 2026

Copy link
Copy Markdown

Greptile Summary

This PR fixes two independent bugs in the terminal paste path. Bug A ensures the bracketed-paste escape frame (ESC[200~ / ESC[201~) is always closed when chunked paste is interrupted, using a finally block around the chunk loop. Bug B extends the PTY write lock to cover both the paste payload and the subsequent submit Enter, preventing a competing paste from slipping into the 50 ms gap between them.

  • Bug A: writeChunks() is extracted as an inner function and wrapped in try/finally; closeBracketedPasteFrame() is idempotent, independently timeout-wrapped, and catches writer failures so that it never masks the original exit reason. Edge cases (failed close chunk, timed-out close on stale target) are handled with the bracketedPasteOpen && chunk !== BRACKETED_PASTE_END guard and the closeTimedOut && outcome.reason === 'stale-target' reporting path.
  • Bug B: sendBracketedPasteToAgent now wraps both the paste and the setTimeout + Enter inside a single runTerminalPtyInputTransaction call; to avoid deadlock, the inner call uses the new non-locking sendAgentDraftPasteContentNow export, following the existing X/XNow convention.

Confidence Score: 5/5

Safe to merge — both fixes are tightly scoped to the paste path, leave all existing reason codes and public interfaces unchanged, and are backed by targeted tests that directly reproduce the failure modes.

The finally approach in terminal-paste-executor.ts handles every exit path including throws, the idempotency guard on closeBracketedPasteFrame prevents double-close, and the bracketedPasteOpen && chunk !== BRACKETED_PASTE_END guard correctly handles a failed close-chunk without emitting a stray terminator. The lock extension in sendBracketedPasteToAgent correctly avoids re-entrancy deadlock by switching to the …Now variant, which is the only place in the call chain that acquires the PTY transaction lock. All five new test cases exercise the precise failure modes described, including the writer-throws path and the competing-paste-during-delay scenario.

Files Needing Attention: No files require special attention. The newly exported sendAgentDraftPasteContentNow carries a clear comment warning against calling it without holding the lock, and there are no other callers inside a transaction context.

Important Files Changed

Filename Overview
src/renderer/src/components/terminal-pane/terminal-paste-executor.ts Core fix for Bug A: chunk loop extracted into writeChunks(), closeBracketedPasteFrame() is idempotent and finally-guarded, all exit paths now close the frame correctly.
src/renderer/src/lib/agent-paste-draft.ts Core fix for Bug B: sendBracketedPasteToAgent wraps paste + delay + Enter in one runTerminalPtyInputTransaction; uses non-locking sendAgentDraftPasteContentNow to avoid deadlock.
src/renderer/src/lib/agent-draft-paste-content.ts sendAgentDraftPasteContentNow promoted from private to exported; comment explains the deadlock risk, existing locking wrapper sendAgentDraftPasteContent is unchanged.
src/renderer/src/components/terminal-pane/terminal-paste-coordinator.test.ts Five new tests covering all failure modes for Bug A: write rejection, write timeout, stale-target close timeout, canContinue=false skip, and writer throw. All correctly verify the closing sequence.
src/renderer/src/lib/agent-paste-draft.test.ts New test for Bug B starts a competing chunked paste during the 50 ms window and asserts the Enter lands before the competitor's open bracket — directly validates the lock-extension fix.

Sequence Diagram

sequenceDiagram
    participant C as Caller
    participant T as runTerminalPtyInputTransaction
    participant A as sendBracketedPasteToAgent
    participant P as sendAgentDraftPasteContentNow
    participant W as writeChunks / writePty

    Note over C,W: Bug B fix — paste + Enter held under one lock
    C->>T: acquire PTY lock (ptyId)
    T->>A: "execute(ptyId, content, submit=true)"
    A->>P: sendAgentDraftPasteContentNow (no inner lock)
    P->>W: write ESC[200~, payload chunks, ESC[201~
    W-->>P: ok
    P-->>A: "pasted=true"
    Note over A: wait POST_PASTE_SUBMIT_DELAY_MS (50ms) — still inside lock
    A->>W: sendRuntimePtyInputVerified('\r')
    W-->>A: ok
    A-->>T: true
    T-->>C: release lock

    Note over C,W: Bug A fix — every writeChunks exit closes the frame
    C->>W: executeTerminalPastePlanNow
    W->>W: "write ESC[200~  — bracketedPasteOpen=true"
    W->>W: write payload chunk — times out / rejected / throws
    Note over W: finally block runs regardless
    W->>W: closeBracketedPasteFrame() — write ESC[201~
    W-->>C: cancelled (frame safely closed)
Loading

Reviews (1): Last reviewed commit: "[P2] fix(terminal): always close the bra..." | Re-trigger Greptile

@nwparker
nwparker merged commit bd490b1 into main Jul 31, 2026
44 checks passed
@nwparker
nwparker deleted the nwparker/fix-terminal-paste-atomicity branch July 31, 2026 21:05
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 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.

1 participant