Skip to content

fix: preserve user input during terminal scrollback replay - #19075

Merged
nwparker merged 5 commits into
mainfrom
nwparker/fix-user-input-during-terminal-replay
Sep 8, 2026
Merged

nwparker merged 5 commits into
mainfrom
nwparker/fix-user-input-during-terminal-replay

Conversation

@nwparker

@nwparker nwparker commented Sep 6, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​112 $\color{#cf222e}{\Huge{\mathbf{−}}}$​8 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​104
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​70 $\color{#cf222e}{\Huge{\mathbf{−}}}$​23 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​47

Typing into an SSH pane while its scrollback restores can lose the beginning of a command. The replay guard currently drops every xterm onData event, including real keyboard input. Reuse the existing xterm user-input signal to preserve input provenance through deferred forwarding, allowing classified user input during replay while continuing to suppress synthetic replies. If the internal signal is unavailable, replay keeps its existing conservative suppression.

The five-pane Docker SSH diagnostic reproduced the bug: the intended focused PTY emitted the complete input, the guard discarded its first 31 characters, and the remote process acknowledged exactly the remaining suffix. Evidence: https://github.com/stablyai/orca/actions/runs/34034754815 (failure attachment and [five-pane-replay-drops] log). Test PR #19071 depends on this application correction.

Validation: the new regression fails before the fix and passes afterward. Replay/input tests pass (47 focused), neighboring forwarding tests pass, and real-xterm tests verify classification and disposal. The hibernation mock now models multiple subscribers and verifies complete disposal; all 28 tests in the affected group pass. Changed-file lint passes. Isolated PR typecheck passed on the initial application head.

Rendered validation passed: https://github.com/stablyai/orca/actions/runs/34035380448 — five repetitions, 50 hide/reopen cycles and 250 pane inputs, with unchanged assertions and timeouts. This ran application code from bb08d40; latest head 1722741 only corrects two test mocks and leaves production code unchanged. Final PR CI passed on head 1722741: https://github.com/stablyai/orca/actions/runs/34035873852, including the full unit shards, typecheck, static analysis, packaging, changed E2E, and Docker SSH (33 passed, 1 skipped). Pullfrog completed successfully on the same head with no new issues.

Application change: leave open for user review. Test PR #19071 must wait for this fix to merge and then validate against that merged state.

Update at head 471ba09 (after reopen)

Rebased by merging origin/main (original commits intact). Two follow-up commits refine the guard beyond the keystroke fix: pointer-derived input that xterm also tags as user input stays suppressed during replay. Mouse reports are dropped because replayed bytes can leave mouse tracking armed until the guarded mode reset lands; wheel-synthesised cursor keys are dropped only while the pane is on the alternate buffer, because a dead-TUI restore exits alt via the guarded ?1049l and forwarding them would recall shell history at the fresh prompt. The same arrow bytes on the normal buffer can only be a keyboard arrow and survive. Both predicates live in terminal-pointer-input-sequences.ts; the two provenance-bound forwarders are created once per pane, not per keystroke.

Regression test covers keystroke-survives, DA1-dropped, mouse-dropped-then-forwarded-after-release, alt-buffer-arrow-dropped, normal-buffer-arrow-forwarded; each clause was mutation-verified (revert clause, test fails, restore). Local at 471ba09: pnpm tc 0; terminal-pane + typing-latency + dependent suites 449 files / 4308 tests; changed-file quality gate 0 findings.

Additional nested SSH filesystem validation

The excluded nested SSH lifecycle scenario that routes through a HUB without shared-control capability also loses real input on merged main. CI focus/data instrumentation captured the complete filesystem rename-verification command and Enter at xterm while its textarea was focused, but neither command echo nor its output marker reached the remote shell (baseline diagnostic).

With only this PR’s three production files added to the test corrections (normal Delete clicks and octal-encoded output-only markers), the unchanged legacy-transport filesystem scenario passed 3/3 repetitions, zero retries/skips (run 34042727431, validation head 6d8320c76b8854b5af77977cda523c48493435d7). Each execution verified remote rename, file deletion, directory deletion, and untouched local canaries. This adds nested paired-client legacy-transport evidence; it does not establish completion of the separate new-terminal activation or post-re-pair reload investigations.

@nwparker
nwparker marked this pull request as ready for review September 6, 2026 13:21
@coderabbitai

coderabbitai Bot commented Sep 6, 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: Team

Run ID: f4be3d07-5338-4ffa-99f0-edafccfce80f

📥 Commits

Reviewing files that changed from the base of the PR and between 6e11e6c and 471ba09.

📒 Files selected for processing (4)
  • src/renderer/src/components/terminal-pane/pty-connection-fresh-spawn-guards.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-input-forward.ts
  • src/renderer/src/components/terminal-pane/terminal-link-pty-mouse-suppression.ts
  • src/renderer/src/components/terminal-pane/terminal-pointer-input-sequences.ts

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


📝 Walkthrough

Walkthrough

The change adds provenance-aware terminal input classification using core user-input signals and xterm data events. It centralizes xterm mouse-report and wheel cursor-key detection. PTY forwarding now preserves real user input during replay while suppressing synthetic responses, mouse reports, and alternate-screen wheel sequences. Tests cover classification, listener disposal, hibernation wake behavior, and replay forwarding.

Merge Risk: ⚪ Minimal · up to 471ba

Terminal input is preserved during scrollback replay while synthetic replies and replay-related pointer input remain suppressed. The covered replay and input-classification paths indicate no outstanding merge-blocking risk.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the bug, implementation, tests, and validation in detail, but it does not follow the required template. It omits the required section headings and checklist items, does not pr… Update the description to include the template sections. Add a linked issue using Fixes #<issue-number>. Add visual proof or write N/A with a reason. Complete the Testing, AI Disclosure, Review, Agent skill upstream boundary, Notes, and…
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 7 functions across 9 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the primary change: preserving user input during terminal scrollback replay.
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.
Full details: Description check

Explanation

The description explains the bug, implementation, tests, and validation in detail, but it does not follow the required template. It omits the required section headings and checklist items, does not provide a Fixes # issue reference, and does not include the required visual-proof statement or attachment.

Resolution

Update the description to include the template sections. Add a linked issue using Fixes #&lt;issue-number&gt;. Add visual proof or write N/A with a reason. Complete the Testing, AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections. Preserve the existing technical explanation and validation evidence.

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

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • subscribeToTerminalInputData — new helper wrapping xterm onData with the existing onUserInput signal to tag each event with wasUserInput, using a boolean latch.
  • installPtyInputForward — routes input through the new helper, threads wasUserInput through the deferred forwarding hop, and drops only synthetic replies while replay is active.
  • Regression + classification tests — a real-xterm test pins the onUserInput-before-onData ordering, and a fresh-spawn regression test asserts user input is forwarded exactly once while a synthetic DA1 reply is suppressed.

I traced the correctness-critical assumption: xterm's CoreService.triggerDataEvent(data, wasUserInput) fires _onUserInput synchronously immediately before _onData, and every synthetic query/focus reply is emitted with wasUserInput=false. The latch is read-and-cleared before the listener runs, so re-entrancy is safe, and the onUserInput-unavailable fallback degrades to the existing conservative suppression (always-dropped during replay). No regression risk found — the rare triggerDataEvent(key, !useWin32InputMode && altGraph) win32 paths emit real keys as wasUserInput=false, which keeps them dropped during replay exactly as before the fix.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…once

Real keystrokes now survive the replay guard, but xterm flags pointer
reports as user input too, and replayed bytes can leave mouse tracking
armed until the guarded mode reset lands. Keep those suppressed so a
click on restoring scrollback cannot print SGR fragments on the prompt.
Hoist the two provenance-bound forwarders out of the per-keystroke path.
@nwparker nwparker reopened this Sep 7, 2026
@coderabbitai

coderabbitai Bot commented Sep 7, 2026

Copy link
Copy Markdown
Contributor

Note

GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer.

@nwparker

nwparker commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

Reopened (closed by accident). Brought up to date by merging origin/main (no history rewrite; the two original commits are intact) and added one follow-up commit, 6e11e6c:

  • Mouse reports stay suppressed while the replay guard is engaged. xterm's onUserInput flags pointer reports as user input, and replayed scrollback can leave mouse tracking armed until the guarded mode reset lands, so without this a click on restoring content would have printed SGR fragments on the fresh prompt. Once the guard releases, the same report forwards normally.
  • The two provenance-bound forwarders are hoisted out of the per-keystroke onData path (no closure allocation per event).
  • isXtermMouseReport moved to terminal-mouse-report-sequence.ts so both the link-click suppression and the input forward share it.
  • The regression test covers all three: keystroke survives replay, DA1 reply dropped, mouse report dropped during replay then forwarded after release. Mutation-verified: reverting the guard to the old unconditional drop fails it (0 calls); dropping the mouse clause fails it (2 calls).

Local: pnpm tc clean; terminal-pane + typing-latency suites 447 files / 4285 tests pass; changed-file quality gate 0 findings.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Mouse reports suppressed during replay — forwardPtyInput now drops xterm mouse reports even when they are flagged as user input, so a click on replayed scrollback with mouse tracking still armed can't print SGR fragments on the fresh prompt; keystrokes typed mid-restore still survive.
  • Shared isXtermMouseReport helper — the X10/SGR mouse-report classifier was extracted from terminal-link-pty-mouse-suppression.ts into terminal-mouse-report-sequence.ts and reused by the replay drop.
  • Once-bound forwarders — forwardUserInput / forwardUnclassifiedInput are bound once outside the onData listener, removing the per-keystroke closure allocation while preserving provenance through deferPtyInput's deferred callback.
  • Test coverage — the fresh-spawn regression test now covers mouse-report suppression both during and after replay, and the hibernation mock models multiple onUserInput subscribers with complete-disposal verification.

I traced the drop condition isPaneReplaying(...) && (!wasUserInput || isXtermMouseReport(data)) — it correctly distinguishes keystrokes (survive), synthetic replies (dropped), and mouse reports (dropped). The isXtermMouseReport extraction is a faithful move of pre-existing, already-shipped logic, and the once-bound forwarders are behavior-equivalent to the prior per-event closure through the deferred { data, forward } capture.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

xterm turns a wheel notch into cursor up/down when the active buffer has
no scrollback, and flags it as user input. During a dead-TUI restore that
frame is replayed on the alt buffer and only leaves it when the guarded
?1049l lands, so forwarding those arrows would recall shell history at
the fresh prompt. Suppress them on the alt buffer only; the same bytes on
the normal buffer can only be a keyboard arrow and still survive replay.
Group the pointer-derived predicates in terminal-pointer-input-sequences.
@nwparker

nwparker commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

Follow-up 471ba09 closes the one residual I had flagged: xterm turns a wheel notch into cursor up/down when the active buffer has no scrollback and tags it as user input. During a dead-TUI cold restore the alt frame is replayed and only exits via the guarded ?1049l, so forwarding those arrows would have recalled shell history at the fresh prompt. They are now suppressed only while the pane is on the alt buffer during replay; the same bytes on the normal buffer can only be a keyboard arrow and still survive. isXtermMouseReport and the new isXtermWheelCursorKey live together in terminal-pointer-input-sequences.ts.

Regression test extended and mutation-verified: removing the clause fails (2 calls), removing the alt-buffer condition fails (the normal-buffer arrow is wrongly dropped). Local: pnpm tc 0; terminal-pane + typing-latency + dependent suites 449 files / 4308 tests pass; changed-file quality gate 0 findings.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

✅ No new issues found.

Reviewed changes

  • Wheel cursor keys dropped during alt-screen replay — forwardPtyInput gains a third drop arm: the bare cursor up/down sequences (\x1b[A / \x1b[B / \x1bOA / \x1bOB) are dropped when the active buffer is the alternate screen, so a wheel over replayed TUI scrollback can't recall shell history once ?1049l re-exits the alt screen.
  • Shared pointer-input classifier — the mouse-report helper module was renamed terminal-mouse-report-sequence.ts → terminal-pointer-input-sequences.ts and extended with isXtermWheelCursorKey; terminal-link-pty-mouse-suppression.ts imports isXtermMouseReport from it.
  • Test coverage — the fresh-spawn regression test now exercises the wheel-over-alt-screen drop, the same-bytes-on-normal-buffer survival, and post-replay mouse reports; the hibernation mock's multi-subscriber model is unchanged.

I traced the load-bearing premise through the vendored xterm source: MouseService._handlePassiveWheel synthesizes exactly ESC O[/[ A/B (up/down by deltaY sign) when !buffer.hasScrollback, and emits each via triggerDataEvent(sequence, true) — flagged as user input, so a shape-based drop arm is required. The type === 'alternate' discriminant matches that trigger (the alternate buffer never has scrollback), and both application- and normal-cursor-key modes are covered by the SS3 and CSI forms.

ℹ️ Real arrow keys on an alt screen are dropped too

The drop intentionally can't distinguish a genuine Up/Down press from a wheel notch: xterm's keyboard path emits byte-identical sequences with the same wasUserInput=true (Keyboard.ts and MouseService both use ESC O/[/ A/B), and no public signal separates them. This narrows the PR's "preserve user input" guarantee for arrow keys during an alt-screen replay, but it remains strictly better than the pre-PR drop-everything behavior and the replay window is transient — no change warranted.

Pullfrog  | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@nwparker
nwparker merged commit 98b0c32 into main Sep 8, 2026
65 of 66 checks passed
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