orca icon indicating copy to clipboard operation
orca copied to clipboard

fix(agents): cancel startup submit after terminal user input

Open OrcaWin opened this issue 4 months ago • 2 comments

Summary

  • track real user input per PTY, including paste intent before asynchronous clipboard reads
  • stop deferred launch-context delivery if the user takes over while the agent is still loading
  • cancel the delayed automatic Enter when typing or a paste reaches the composer after generated context

Root cause

This was an input-ordering race in the normal terminal, not a clipboard-size or dashboard-preview bug.

Submit-after-ready delivery sends generated linked-work-item context as a protected paste, waits briefly, then sends Enter through a separate runtime PTY path. Normal terminal input uses the mounted terminal transport. Because those operations were not serialized, a user paste could land between the generated context and the delayed Enter. The Enter then submitted the generated context together with the beginning of the user's five-line paste; Codex rendered the remaining protected paste as its pasted-character placeholder.

The fix captures a per-PTY user-input generation before readiness/delivery. If input changes before generated injection, delivery stops. If it changes after injection but before Enter, only the automatic submit is canceled, leaving the composer editable.

Reproduction

The regression uses synthetic local linked-context text and a five-line Windows-style bracketed paste. No external issue, PR, URL, or user clipboard content is used.

Screenshots

No visual change.

Testing

  • [x] 585 tests across agent draft delivery, clipboard paste, and the complete terminal connection suite
  • [x] renderer web typecheck
  • [x] base, type-aware, and React Doctor lint scans on all changed files
  • [x] max-lines ratchet
  • [x] deterministic coverage for user input both during readiness and between generated paste and delayed Enter

The changed-code wrapper currently hits a Windows spawnSync pnpm.cmd EINVAL; its three underlying scans were run directly and passed. React Doctor reports one pre-existing warning outside the changed lines.

Cross-platform review

The guard is keyed by the PTY id used for delivery, so it applies to local terminals, native Windows/ConPTY, WSL, SSH, and remote runtime terminals. Folder workspaces and git worktrees use the same terminal path.

Security and privacy

Only monotonic input generations are stored. Clipboard and linked-work-item contents are not logged or retained by the guard, and reproduction uses synthetic text only.

OrcaWin avatar Jul 30 '26 22:07 OrcaWin

Greptile Summary

This PR fixes an input-ordering race where the agent startup draft and a concurrent user paste could interleave writes to the same PTY. The fix introduces runTerminalPtyInputTransaction, a per-PTY promise-chain queue, and wraps both sendAgentDraftPasteContent and executeTerminalPastePlan with it so that only one operation writes to a given PTY at a time.

  • New terminal-pty-input-transaction.ts: a lightweight serializer using a module-level Map<string, Promise<void>> that chains operations by storing and awaiting the previous tail; the finally block correctly resolves the gate and cleans up the map entry regardless of success or failure.
  • agent-draft-paste-content.ts and terminal-paste-executor.ts: both public functions are now thin wrappers that acquire the transaction before delegating to the renamed *Now inner function.
  • Tests: a new terminal-paste-operation-order.test.ts directly exercises both orderings (startup-waits-for-user and user-waits-for-startup), cross-PTY isolation, and post-error recovery; pty-connection.test.ts extends an existing test with an explicit user-draft input before the composer prompt to confirm correct write ordering in the integration path.

Confidence Score: 5/5

Safe to merge; the transaction logic is correct, error paths release the lock in a finally block, and the race it fixes is well-tested at both unit and integration level.

The core change — chaining PTY writes through a promise queue — is correctly implemented: the previous tail is captured before the new one is registered, the lock is always released in a finally block, and the map entry is cleaned up only by the last queued operation. No existing behavior is changed for non-contended paths.

Files Needing Attention: terminal-paste-operation-order.test.ts — the new describe block does not call vi.resetModules() between tests, so a mid-test assertion failure could leave a stale map entry affecting subsequent tests.

Important Files Changed

Filename Overview
src/renderer/src/components/terminal-pane/terminal-pty-input-transaction.ts New module implementing a per-PTY promise-chaining serialization queue; logic is correct with proper error-safe cleanup in the finally block
src/renderer/src/lib/agent-draft-paste-content.ts Wraps the public sendAgentDraftPasteContent in a transaction, extracting the prior implementation into sendAgentDraftPasteContentNow; the rename is clean and the logic is unchanged
src/renderer/src/components/terminal-pane/terminal-paste-executor.ts Applies the same extract-and-wrap pattern for executeTerminalPastePlan; chunked writes now hold the PTY transaction lock for the duration of the operation
src/renderer/src/components/terminal-pane/terminal-paste-operation-order.test.ts New test file covering uncontended start, startup-after-user-paste ordering, user-paste-after-startup ordering, cross-PTY isolation, and post-error recovery; does not reset module-level transactionTails state between tests
src/renderer/src/components/terminal-pane/pty-connection.test.ts Renames and extends one existing test to send explicit user input before the composer prompt, verifying that the startup draft is ordered after both real user inputs

Sequence Diagram

sequenceDiagram
    participant User as User Input (onData)
    participant Executor as executeTerminalPastePlan
    participant Draft as sendAgentDraftPasteContent
    participant TxQueue as runTerminalPtyInputTransaction (pty-1)
    participant PTY as PTY Write

    User->>Executor: paste triggered
    Executor->>TxQueue: acquire lock (pty-1)
    TxQueue-->>Executor: lock granted (no previous)
    Executor->>PTY: BRACKETED_PASTE_START
    Executor->>PTY: chunk1 (user-line-1)
    Note over Executor: yieldToEventLoop()
    Draft->>TxQueue: acquire lock (pty-1)
    Note over TxQueue: previous = user-paste lock, queues behind it
    Executor->>PTY: chunk2 (user-line-2)
    Executor->>PTY: BRACKETED_PASTE_END
    Executor->>TxQueue: release lock
    TxQueue-->>Draft: lock granted
    Draft->>PTY: BRACKETED_PASTE_START + content + BRACKETED_PASTE_END
    Draft->>TxQueue: release lock

Reviews (8): Last reviewed commit: "perf(terminal): keep uncontended paste d..." | Re-trigger Greptile

greptile-apps avatar Jul 30 '26 22:07 greptile-apps

Review Change Stack

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▶️ Resume reviews
  • [ ] 🔍 Trigger review
📝 Walkthrough

Walkthrough

Terminal user input now updates PTY and pane input generations through unified handling. Clipboard and primary-selection paste flows record intent before retrieving or executing pasted text. Agent paste submission captures input checkpoints and stops when user input occurs before or during paste or before submission. Tests cover input generation, paste-intent ordering, startup-draft cancellation, split isolation, and interrupted chunked paste.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 14.29% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description explains the change and testing, but it omits required AI Review Report, Security Audit, and Notes sections and lacks the required Screenshots heading. Add the required Screenshots, AI Review Report, Security Audit, and Notes sections; document the security review and explicitly confirm macOS, Linux, and Windows compatibility checks.
✅ Passed checks (3 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 identifies the main change: serializing startup context and user paste operations.
✨ 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.

coderabbitai[bot] avatar Jul 30 '26 23:07 coderabbitai[bot]

Superseded validation

The earlier version of this comment exercised explicit submit-after-ready, not the normal linked-worktree draft path, so it was not evidence for the reported incident.

The PR has been reworked around the reproduced nested bracketed-paste race. Current Windows Electron/ConPTY validation and screenshots are in the updated PR description:

User paste frame in flight Serialized completion
Typed input and large user paste are in flight before linked context Typed input, large paste, and linked context are preserved

OrcaWin avatar Jul 31 '26 03:07 OrcaWin