Repository navigation
[P2] fix(terminal): always close the bracketed-paste frame and hold the pty lock through submit - #11816
Conversation
…he pty lock through submit Co-authored-by: Orca <[email protected]>
|
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (5)
📝 WalkthroughWalkthroughChunked 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)
✨ Finishing Touches📝 Generate docstrings
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. Comment |
Greptile SummaryThis PR fixes two independent bugs in the terminal paste path. Bug A ensures the bracketed-paste escape frame (
Confidence Score: 5/5Safe 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 Files Needing Attention: No files require special attention. The newly exported
|
| 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)
Reviews (1): Last reviewed commit: "[P2] fix(terminal): always close the bra..." | Re-trigger Greptile
…he pty lock through submit (stablyai#11816) Co-authored-by: Orca <[email protected]>
Summary
Two independent P2s found by the
v1.4.163-rc.1..v1.4.163-rc.3production 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, thenESC[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,executeTerminalPastePlanNowclosed that frame on exactly one of its four exit paths — the stale-target check. The other three returned immediately with the frame still open:and an exception thrown by
writePtyitself escaped the function without closing anything.Impact: the terminal silently stops responding to input as input. Keystrokes and
Enterare 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 aChunkedPasteOutcomeinstead of returning from the outer function, and the close is afinally:closeBracketedPasteFrameis idempotent (bracketedPasteOpenis cleared on entry), still respectscanContinue(), is itself timeout-wrapped, and is wrapped intry/catchso a close failure cannot mask the real exit reason. ThebracketedPasteOpen = bracketedPasteOpen && chunk !== BRACKETED_PASTE_ENDlines 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 reportingoperation-timeout, so no existing caller sees a changed reason code.Bug B — paste and its submit
Enterwere not one transactionsendBracketedPasteToAgentpastes a draft and then, ifsubmitis set, waitsPOST_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 andEnterland in the same PTY write.On
origin/mainthe paste took the per-PTYrunTerminalPtyInputTransactionlock 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 theEnter— so theEntersubmits 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:
runTerminalPtyInputTransactionis a promise-tail mutex and is not reentrant — naively wrapping the existing call would have deadlocked the PTY permanently.agent-draft-paste-content.tstherefore exportssendAgentDraftPasteContentNow, the non-locking inner variant, following the existingX/XNowconvention 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.tsreverted toorigin/main, tests kept:The
actualarray is the bug: the PTY receivedESC[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.tsandagent-draft-paste-content.tsreverted toorigin/main, tests kept: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
terminal-paste-coordinator.test.ts, 33 inagent-paste-draft.test.ts), of which 60 are pre-existing and unmodified.npx oxfmt --checkandnpx oxlintclean.agent-paste-draft.ts:218is the only lock acquisition on that path and:219calls the non-locking…Nowvariant.sendAgentDraftPasteContent(the locking wrapper) has no remaining caller inside a transaction.terminal-paste-executor.tsis 191 lines, within the 300-line cap. Nomax-linesdisable added.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, andactive-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 --checkclean via lint-stagedpnpm 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 changeAI Review Report
Reviewed by Claude Opus 5 as part of a 45-agent release scan with adversarial refutation. Risks checked:
runTerminalPtyInputTransactionis a per-ptyIdpromise-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…Nowsplit and verified by call-site inspection (a hang cannot be caught by a passing test).POST_PASTE_SUBMIT_DELAY_MS(50 ms). That is bounded, applies only whensubmitis 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.finallyruns on the exception path too, which is the caseorigin/mainhandled worst.closeBracketedPasteFrameis idempotent and independently timeout-wrapped so a hung writer cannot make cleanup hang the paste.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
eval, no shell string construction, no path handling, no auth, no secrets, no network.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:closeBracketedPasteFramereturns immediately unlessbracketedPasteOpen, clears the flag on entry so it cannot double-fire, and thechunk !== BRACKETED_PASTE_ENDguards stop a retry when the close chunk is itself what failed. No user-controlled data is added to the write stream.Notes
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 🐋