Skip to content

fix(ssh): keep keystrokes typed while a restored SSH terminal reattaches - #24166

Merged
OrcaWin merged 1 commit into
mainfrom
OrcaWin/ssh-restore-early-input
Oct 1, 2026
Merged

OrcaWin merged 1 commit into
mainfrom
OrcaWin/ssh-restore-early-input

Conversation

@OrcaWin

@OrcaWin OrcaWin commented Sep 30, 2026 •

Copy link
Copy Markdown
Collaborator
Files Added Deleted Net
Test 1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​175 0 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​175
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​44 $\color{#cf222e}{\Huge{\mathbf{−}}}$​3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​41

ELI5

After Orca restarts, a remote (SSH) terminal reconnects to the shell it already had. For a moment while it reconnects, the terminal already has keyboard focus but isn't wired to the shell yet. Whatever you typed in that moment was thrown away, so the start of your command disappeared and only the rest ran. Now those keys are held and sent, in order, as soon as the terminal is wired up.

What Changed

Before: a restored SSH terminal that gets rebuilt while reconnecting (it is remounted with a fresh terminal view) grabs focus right away, but its connection only becomes usable after the remote relay answers the reattach. Keys typed in that ~tens of milliseconds were refused and silently dropped. With printf '...' > file; printf MARKER the shell received '...' > file; printf MARKER — the marker printed, the file was never written (the e2e ssh-cold-activation-restore.spec.ts:209 flake: readRemoteProof(...) → null, losing printf or prin).

After: those keys are held and delivered in the order they were typed once the pane reattaches to the same remote shell.

Mechanism: the renderer's IPC terminal transport already has a bounded pre-connect input buffer (bufferInputUntilConnect, used by split panes waiting on a working directory). It is now also turned on for SSH panes that are going to reattach to an existing PTY (a restored leaf PTY id, the tab's PTY id, or a deferred SSH session id). The buffer is flushed through the normal write queue right after the reattach binds, before any later keystroke, so nothing is reordered. It stays bounded (1024 entries / fixed size); anything past that is refused as before.

If the reattach does not bind (the remote shell is gone) or the pane gives up and spawns a fresh shell instead, the held keys are dropped with a [pty-transport] dropped keys typed while the terminal was connecting warning rather than being typed into a different shell.

Why

I traced the path end to end against the Docker SSH relay: main's pty:write → SSH PTY provider → mux pty.data → relay writeData all accept and deliver every byte once the pane is bound. The loss is one layer up: after a remount the new pane's transport rejects input until its reattach connect() resolves, and nothing buffered it. Forcing a remount right before typing in the e2e reproduces it every time without this change (printf → f ..., 2/2 failed) and passes with it (3/3); the in-renderer trace showed the rejected keys were exactly the ones typed with connected=false.

Fixing it in the transport reuses the existing buffer and flush-order guarantees instead of adding a new queue in main or the relay, and needs no wire change (old relays and hosts see the same writes, just not dropped). Buffering is limited to reattaches: typeahead into a fresh shell could land ahead of a startup/agent command, so fresh spawns keep today's behavior.

Linked Issue

Fixes flaky e2e tests/e2e/ssh-cold-activation-restore.spec.ts:209 (failed on #24133, #24135, #24148).

Visual Proof

N/A — no visual change; the fix is that typed characters are no longer lost during an invisible reconnect window. Covered by the unit test and the e2e below.

Testing

  • New pty-connection-ssh-reattach-early-input.test.ts drives a restored SSH pane through the real IPC transport: keys typed while the reattach spawn is in flight arrive in order after it binds (fails without the fix: received "ok" instead of "printf ok"), and a failed reattach drops them with the warning instead of writing them.

  • pnpm test src/renderer/src/components/terminal-pane src/renderer/src/store (8242 passed), pnpm tc, pnpm run check:code-quality:changed, pnpm run audit:anti-slop.

  • Local macOS + Docker SSH relay: ORCA_E2E_SSH_DOCKER=1 playwright test tests/e2e/ssh-cold-activation-restore.spec.ts passes; with a forced remount just before typing (temporary instrumentation, not committed) it fails 2/2 before and passes 3/3 after.

  • I manually tested these changes locally

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

AI Disclosure

Written with Claude Code (Claude Opus).

Review

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

Renderer-only; no RPC/stream/wire changes, so mixed client/host versions are unaffected. Applies on all platforms and to folder workspaces (keyed on the SSH connection and PTY identity, not git). Local terminals and fresh SSH spawns are unchanged.

Checklist

  • This PR is small and focused
  • I explained what changed and why (ELI5, the user-facing before/after, the mechanism, and why over the alternatives)
  • 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)

A restored SSH pane that remounts takes keyboard focus as soon as its new
xterm mounts, but its transport only binds once the relay answers the
reattach. Keys typed in that window were refused by the transport and lost,
so the start of a command vanished while the rest ran against the live shell.

Buffer input on SSH panes that reattach to an existing PTY and flush it in
order once the reattach binds. If the reattach fails or the pane falls back
to a fresh shell, drop the buffered keys with a console warning instead of
typing them into a replacement shell.

Co-Authored-By: Claude <noreply@anthropic.com>
@greptile-apps

greptile-apps Bot commented Sep 30, 2026 •

Copy link
Copy Markdown

RetriggerConfidence Score: 5/5

[Medium risk] Buffers keystrokes during SSH terminal reattach.

The PR appears safe to merge; no actionable regression was identified.

Summary

The PR enables bounded preconnect input buffering for restored SSH panes and discards held keys when reattachment gives way to a fresh shell. It adds tests for successful reattachment and failed-reattach fallback.

Diagram
%%{init: {'theme': 'neutral'}}%%
flowchart LR
  A[Keys typed before SSH reattach] --> B[Bounded transport buffer]
  B --> C{Reattach outcome}
  C -->|Binds live PTY| D[Flush into ordered write queue]
  C -->|Fresh-shell fallback| E[Discard buffered keys and warn]
Loading

Reviews (1) · Last reviewed commit: "fix(ssh): keep keystrokes typed while a ..."

@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

  • SSH reattach type-ahead — a restored SSH pane now sets bufferInputUntilConnect, so keys typed during the relay round trip are held instead of refused, then flushed in order once the reattach binds.
  • Reattach-only predicate — buffersInputOnlyForSshReattach enables this only for SSH panes that already have a PTY identity (restored leaf id, tab ptyId, or deferred session id), leaving fresh spawns and split-pane cwd waits on their existing behavior.
  • Fresh-spawn safeguard — a fallback fresh shell abandons the held keys so they cannot run in the replacement shell, warning once via the new hasPendingInput/dropPreconnectInput path.
  • Tests — a new end-to-end IPC test covers in-order delivery after reattach and the drop-with-warning path; I confirmed both fail when the predicate is forced off.

This is renderer-only and reuses the transport's existing bounded pre-connect buffer, so there is no wire change and remote-runtime/local panes are untouched. The failure path is safe: main's SSH reattach either binds to the same shell or returns sessionExpired without binding, so flushPreconnectInput sees !connected and drops rather than delivering to a replacement shell.

Two non-blocking observations, neither actionable: the new drop warning also fires for the pre-existing local split-pane cwdPromise not-attached case (previously silent), and SSH now uses a different implementation than remote-runtime's withRemoteReattachInputBuffer for the same "buffer typeahead on a restored screen" guarantee.

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

@coderabbitai

coderabbitai Bot commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 1d6eb23f-2d4c-484b-80e9-4dee818f1504

📥 Commits

Reviewing files that changed from the base of the PR and between d74388f and f01e12c.

📒 Files selected for processing (6)
  • src/renderer/src/components/terminal-pane/pty-connection-ssh-reattach-early-input.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/fresh-spawn-start.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-input-recovery.ts
  • src/renderer/src/components/terminal-pane/pty-connection/ssh-reattach-input-buffering.ts
  • src/renderer/src/components/terminal-pane/pty-preconnect-input-buffer.ts
  • src/renderer/src/components/terminal-pane/pty-transport.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.


📝 Walkthrough

Walkthrough

Restored SSH panes now buffer input while reattachment is pending. The connection setup identifies sessions that buffer input only for reattachment, and the input buffer reports queued or in-flight input. If reattachment fails and a fresh spawn begins, the code abandons that input. The transport warns and clears pending input on failed attachment or abandonment, and clears it silently when destroyed. Tests check that input is not written before reattachment, that writes retain order after reattachment, and that dropped input produces a warning when the PTY is missing.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to f01e1

No actionable merge-blocking issue is identified. Restored SSH input is buffered during reattachment and discarded rather than forwarded to a replacement shell; merge after normal checks pass.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to f01e1

Normal reconnection and explicit replacement paths protect buffered keystrokes. However, another recovery path can bind a replacement shell before checking whether the buffered commands belong to it. This creates a potential wrong-shell replay risk, although broader access or privilege escalation has not been demonstrated.

Retained concerns

  • Medium · security · inferred: Reattachment-only input is not gated on successful attachment to the intended shell. If the connection layer suppresses a discarded session ID and binds a returned replacement PTY, buffered commands can be flushed before the explicit fresh-spawn abandonment path runs. Current-PTY checks prevent stale writes but do not establish original-shell ownership.
Security review details

Security Blast Radius

  • inferred — The identified exposure concerns queued terminal commands reaching a replacement process under the selected SSH connection. The evidence does not establish cross-connection access, cross-tenant exposure, or increased account privileges.

Security Findings and Attack Paths

  • inferred — The potential path is retained terminal input, suppression of a discarded requested session ID, a successful PTY response, binding, and automatic replay. Newly enabling SSH-only buffering makes this path security-relevant even though the underlying connection code is outside the listed changes. An attacker-triggered production sequence has not been demonstrated.

Trust Boundaries and Controls

  • observed — Explicit fresh spawn clears reattachment-only input before connecting, and attachment failure without a bound PTY drops it. The rejection-based regression fixture verifies that destructive-looking input is not written to the replacement shell. These controls do not cover direct binding of a returned replacement PTY inside connectIpcPty.

Resilience and Maintainability Implications

  • observed — Exit, disconnect, detach, and destruction clear pending input, while connection generations reject superseded completion paths. These controls contain stale writes during interruption and recovery, but do not substitute for original-shell identity validation.

Hardening Proposals

  • proposed — Carry reattachment-only input ownership into the connection layer and require successful attachment to the intended logical session before replay. Abandon that input before binding any replacement process, including replacement paths that bypass explicit fresh spawn.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 37.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and concisely describes the main change: preserving keystrokes while a restored SSH terminal reattaches.
Description check ✅ Passed The description is complete and directly aligned with the change. It explains the user impact, mechanism, rationale, testing, scope, compatibility, and AI disclosure. It provides a flaky e2e reference…
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Autopilot is currently an internal CodeRabbit preview.


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.

@OrcaWin
OrcaWin merged commit 7e5950c into main Oct 1, 2026
75 of 77 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