Repository navigation
fix(terminal): preserve typing while a remote pane reattaches - #23701
Conversation
|
Navigate logical layers of code changes, visualize relationships, and explore their blast radius. Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
No actionable comments were generated in the recent review. 🎉 ℹ️ Recent review info⚙️ Run configurationConfiguration used: Repository UI Review profile: CHILL Plan: Advanced Run ID: 📒 Files selected for processing (5)
💤 Files with no reviewable changes (2)
🚧 Files skipped from review as they are similar to previous changes (1)
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 7 remain after this review. 📝 WalkthroughWalkthroughThe remote runtime transport now wraps input handling to buffer ordinary input during remote reattachment. The wrapper flushes input when the expected PTY session remains active and clears buffered input on connection completion, attach, disconnect, detach, or destroy. Tests cover these cases and input sent while pane resolution is pending. Recovery reconnects use a configurable connector. The end-to-end interactivity probe now attaches a scenario-named screenshot to its report. Priority: ➖ Normal Merge Risk: ⚪ Minimal · up to Input intended for a restored terminal is not sent to a replacement terminal. No actionable merge-blocking issue is established, so the change is ready for normal checks. Architecture SummaryArchitecture risk: 🟠 High · up to The change affects 2 systems. Changed systems: Architecture concerns Review detailsSystems and components
Before / after behavior
Reliability and maintainability
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches 💡 2📝 Generate docstrings 💡
🛠️ Fix failing CI checks 💡
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 |
|
There was a problem hiding this comment.
ℹ️ No critical issues — one coverage question inline.
Reviewed changes
- Remote reattach input buffering — a
PtyTransportdecorator (remote-reattach-input-buffer.ts) reuses the existing boundedcreatePtyPreconnectInputBufferto retain ordinary and acknowledged typing during a remoteconnect, flushing it only to the original terminal id. - Query replies stay immediate —
sendInput/sendInputAcceptedskip buffering forkind === 'query-reply';sendInputImmediateis left on the delegate. - Lifecycle cleanup — pending input is dropped and acknowledged writes settle
falseon replacement id,connectfailure,attach,disconnect,detach, anddestroy. - Wiring —
createRemoteRuntimePtyTransportnow returnswithRemoteReattachInputBuffer(transport). - Tests — 8 buffer unit tests plus an integration test that pauses
terminal.resolvePane, types before binding, and asserts the resultingInputframe; e2e only adds a per-scenario screenshot attach.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| clear() | ||
| const expectedId = options.sessionId | ||
| const buffer = | ||
| expectedId && parseRemoteRuntimePtyId(expectedId) ? createPtyPreconnectInputBuffer() : null |
There was a problem hiding this comment.
Buffering is gated on parseRemoteRuntimePtyId(options.sessionId), so a remote transport whose sessionId is a host-native handle falls through unbuffered. connect still supports that shape — remote-runtime-pty-transport-pane-handle-resolution.test.ts:64 connects with sessionId: 'ssh:hub-private@@pty-2' and resolves it via terminal.resolvePane to remote:hub-env@@hub-terminal-1 — so typing during that await is dropped exactly as before this PR. Was that path intentionally out of scope, or should the buffer cover it?
Technical details
# Non-`remote:` reattach session ids bypass the type-ahead buffer
## Affected sites
- `src/renderer/src/components/terminal-pane/remote-reattach-input-buffer.ts:18-19` — buffer only created when `parseRemoteRuntimePtyId(expectedId)` is truthy.
- `src/renderer/src/components/terminal-pane/remote-reattach-input-buffer.ts:26` — `isCurrent` compares `transport.getPtyId() === expectedId`, so keying on the requested id cannot match the resolved id for these paths.
## Why it happens
`createRemoteRuntimePtyTransport` can be handed a host-native id (HUB/SSH wake hint). `connect` only buffers when the id is `remote:`-encoded; for any other id it resolves the pane through `terminal.resolvePane` and then binds a *new* `remote:` id, so there is no pre-bind retention window.
## Required outcome
Decide whether typing during a non-`remote:` remote reattach must be retained. If yes, the flush guard needs the post-connect id (e.g. `PtyConnectResult.id`, or `transport.getPtyId()` once bound) rather than `options.sessionId`.
## Open questions for the human
- Is the HUB-native wake path reachable from a user-visible restored pane where immediate typing occurs?There was a problem hiding this comment.
ℹ️ No critical issues — one coverage suggestion inline.
Reviewed changes
- Routed recovery reconnects through the buffered wrapper:
createRemoteRuntimePtyTransportnow keeps aconnectForRecoveryindirection, exposessetConnectForRecovery, andwithRemoteReattachInputBufferpoints it at the wrappedconnect, so the recoverable-failure replay (replayLastTransportEntryPoint, line 889) and the host-authorityretryRecoverybranch (line 2720) no longer bypass input buffering. - Added the optional
setConnectForRecoveryhook toPtyTransport; the default remains the rawtransport.connect.
I traced the recovery path end to end: RemoteRuntimePtyRecoveryState.schedule retries on a setTimeout (so no synchronous re-entrant connect), and retryRecovery's connect branch only runs in disconnected, after any in-flight connect has returned — so the new indirection does not race the wrapper's buffer lifecycle.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| flushPendingClaimInput(nextStream) | ||
| } | ||
|
|
||
| let connectForRecovery: PtyTransport['connect'] = (options) => transport.connect(options) |
There was a problem hiding this comment.
This routes recovery reconnects through the buffered wrapper, but nothing exercises the new indirection: the harness delegate in remote-reattach-input-buffer.test.ts has no setConnectForRecovery, so connectForRecovery stays on its raw default and the recovery paths are never buffered in tests. A case that drives a recoverable connect failure (or retryRecovery()) and asserts type-ahead is retained until the original id rebinds would lock in the behavior this commit fixes.
Technical details
# Recovery reconnect buffering has no test
## Affected sites
- `src/renderer/src/components/terminal-pane/remote-reattach-input-buffer.test.ts` — `createHarness`'s delegate has no `setConnectForRecovery`, so `withRemoteReattachInputBuffer`'s `transport.setConnectForRecovery?.()` is a no-op and `connectForRecovery` is never redirected.
- `src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts:2177` — the default `connectForRecovery` calls raw `transport.connect`; only the wrapper override makes `replayLastTransportEntryPoint` (line 889) and `retryRecovery` (line 2720) buffered.
## Required outcome
- A test that triggers either recovery connect path and asserts pre-bind typing is buffered and flushed to the original endpoint (and dropped on replacement), so removing the `connectForRecovery` wiring fails.| const expectedId = options.existingPtyId | ||
| const buffer = parseRemoteRuntimePtyId(expectedId) ? createPtyPreconnectInputBuffer() : null | ||
| pending = buffer | ||
| pendingExpectedId = expectedId |
There was a problem hiding this comment.
Legacy attach typing is discarded
When a restored terminal attaches with a legacy ID such as remote:terminal-1, the buffer expects that exact ID, but the transport reports an environment-qualified ID such as remote:env-1@@terminal-1. The IDs never match, so typing entered during attachment is discarded instead of reaching the original terminal.
Knowledge Base Used: Terminal runtime and interaction
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: a3df5f35-c2b6-4806-9aef-1b71399461e5
📒 Files selected for processing (3)
src/renderer/src/components/terminal-pane/pty-transport-types.tssrc/renderer/src/components/terminal-pane/remote-reattach-input-buffer.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 3 remain after this review.
There was a problem hiding this comment.
Important
The new attach buffering is never released when an attach ends without becoming writable, and recovery re-entry still calls the raw attach. Both leave type-ahead undelivered on restored remote panes.
Reviewed changes
- Added the optional
setConnectionReadyhook toPtyTransportand callnotifyConnectionReady()at eachconnected = truetransition, so a wrapper can flush retained input when an asynchronous attach becomes writable. - Extended
withRemoteReattachInputBufferto retain type-ahead duringattach, keyed onoptions.existingPtyId, flushed through the newsetConnectionReadycallback; extracted a sharedflushhelper and addedpendingExpectedId.
⚠️ Recovery-replayed attach bypasses the buffered wrapper
replayLastTransportEntryPoint still calls the raw transport.attach(lastAttachOptions) while its sibling connect branch was routed through connectForRecovery. The reconnect button, online/resume, and recoverable-failure retries all replay through it, so keystrokes typed during a reconnect-triggered reattach are dropped exactly as before this PR — the wrapper's attach buffering is only reachable when callers invoke the wrapped transport directly.
Technical details
# Recovery-replayed attach never enters the wrapper
## Affected sites
- `src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts:885` — `replayLastTransportEntryPoint` calls raw `transport.attach(lastAttachOptions)`; the adjacent connect branch on `:889` was changed to `connectForRecovery` in `e7880c6`.
- `src/renderer/src/components/terminal-pane/remote-reattach-input-buffer.ts:63-70` — the new attach buffering only runs when the wrapper's `attach` is invoked.
## Why it matters
`lastAttachOptions` is recorded by restored-pane attaches (the wrapped `attach` delegates to the raw one). When the connection later drops, `retryRecovery()` (`:2712`) and the parked external trigger (`:957`) call `replayLastTransportEntryPoint`, which takes the raw-attach branch. Because the wrapper's `attach` never runs, `pending` is never set and `clear()` is never called, so typing during the replay reaches `transport.sendInput`, which returns `false` while `connected === false`.
## Required outcome
Route the recovery replay of `attach` through the wrapper the same way `connect` is (e.g. a `setAttachForRecovery` companion to `setConnectForRecovery`), so recovery re-entry cannot bypass retention.
## Open questions
- Is the recovery attach replay intentionally excluded because something else covers it? No other buffering path was found for it.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues in
fa5c7f6— it only moves when the connection-ready flush fires. The two findings raised againstca2b95d(attach buffer not released on failure paths; recovery-replayed attach bypasses the wrapper) still stand.
Reviewed changes
- Moved
notifyConnectionReady()to fire afterawait subscribeToHandle()inattachHostSessionMirror(line 1009),adoptResolvedHostPane(1297),recoverExpiredHostPane(1361), and the fresh-create connect path (2397), so retained input flushes through the established multiplexed stream rather than the pre-subscribeterminal.sendfallback.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Advanced
Run ID: 3aff71b8-fabc-4ba9-93ed-07191de495e8
📒 Files selected for processing (3)
src/renderer/src/components/terminal-pane/remote-reattach-input-buffer.test.tssrc/renderer/src/components/terminal-pane/remote-reattach-input-buffer.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 4 remain after this review.
There was a problem hiding this comment.
Caution
The new lazy buffering accepts input in every disconnected state and the same-handle recovery path never flushes it. This regresses existing transport tests: remote-runtime-pty-transport-stream-reconnect.test.ts has 3 failures — :469 expects detached sendInput to return false and now gets true, and :574/:602 time out because sendInputAccepted never settles. All 14 pass at fa5c7f6.
Reviewed changes
- Broadened input retention in
withRemoteReattachInputBufferfrompending?.isBuffering()to also fire when!transport.isConnected(), with a newensurePending()that lazily creates the buffer, so recovery re-entry through the rawattachpath can now retain type-ahead without asetAttachForRecoverycompanion. - Flush trigger now falls back to the live
transport.getPtyId()whenpendingExpectedIdis null. - Added one unit test for the wrapper-
attachreadiness flush; it does not exercise the recovery/lazy path this commit exists to cover.
🚨 Same-handle resubscribe recovery can never flush retained input
notifyConnectionReady() is the only trigger for the wrapper's flush, and the same-handle recovery path (resubscribeAfterTransportClose) calls subscribeToHandle() without ever calling it. With the new !transport.isConnected() catch-all, typing during such a recovery is retained (sendInput returns true) instead of returning false so the caller arms recovery, and it is never delivered once the stream is back — it also keeps pending.isBuffering() true, so subsequent keystrokes stay trapped until a full attach/connect/disconnect clears the wrapper.
Technical details
# Recovery resubscribe has no release hook for the new lazy buffer
## Affected sites
- `src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts:1746` — `resubscribeAfterTransportClose` resolves through `subscribeToHandle` at `:1811`, `:1838`, `:1845` but never calls `notifyConnectionReady()`; notifications exist only at `:1009`, `:1297`, `:1361`, `:2397`.
- `src/renderer/src/components/terminal-pane/remote-reattach-input-buffer.ts:57` — retention now triggers on `!transport.isConnected()`, and `isConnected()` is false through the whole recovery window (`recoveryBlocksIo()`, stream detached, attachment not ready), so the lazy buffer is created on every recoverable partition, not only during a pending reattach.
- `src/renderer/src/components/terminal-pane/remote-reattach-input-buffer.ts:97-104` — `setConnectionReady` is the sole flush trigger.
## Why it matters
Before `b0f4b56`, a disconnected `sendInput` delegated to the raw transport and returned `false`, which is what signals callers to arm recovery. Now it is accepted and held, but the resubscribe success transition (`setAttachmentReady(true)` at `:2049`) does not notify the wrapper, so the held bytes are neither delivered nor rejected, and the buffer stays buffering after the pane is healthy.
## Required outcome
- Retain only while a reattach is genuinely pending and guaranteed a release; do not accept input on paths that never reach `notifyConnectionReady()`.
- Ensure every success transition that can release a retained buffer notifies the wrapper, and every terminal/failure transition clears it.
## Open questions
- Is retaining input across a same-handle resubscribe intended at all? If so the resubscribe success path needs its own flush signal; if not, the `!isConnected()` condition needs to exclude recovery I/O-blocked states.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
| sendInput(data, kind) { | ||
| if ( | ||
| kind !== 'query-reply' && | ||
| (pending?.isBuffering() === true || (!connectionReady && !transport.isConnected())) |
There was a problem hiding this comment.
Typing lost during stream recovery When a remote stream drops, recovery resubscribes without calling the wrapper’s
connect or attach, so connectionReady stays true. Typing during recovery bypasses the buffer, but the underlying transport rejects ordinary writes until recovery completes. The typed command is lost.
Knowledge Base Used:
There was a problem hiding this comment.
Important
69b205c fixes the detached-input regression from the previous review — remote-runtime-pty-transport-stream-reconnect.test.ts passes again (14/14). But five other transport tests still fail on this branch, and they pass on main (a880c88) and at the first PR commit 1dbedf61e5, so the regression was introduced between ca2b95d and fa5c7f6 and predates this commit.
Reviewed changes
- Latched
connectionReadyinwithRemoteReattachInputBuffer: the!transport.isConnected()retention now applies only before the transport's firstsetConnectionReadysignal, so typing while detached after a successful connection delegates to the raw transport and returnsfalseagain — restoring the "reject so the caller arms recovery" contract instead of holding undeliverable input. - Reset the latch inside
clear(), whichconnect,attach,disconnect,detach, anddestroyall route through, so a fresh reattach re-enables retention.
⚠️ Five transport fallback/coalescing tests fail on this branch
pnpm test src/renderer/src/components/terminal-pane/remote-runtime-pty-transport reports 5 failed / 151. They fail because the wrapper's attach now retains input (and returns true) during the attach window, so the one-shot terminal.send fallback and the input frames these tests assert are never produced. The branch needs to be green here before merge — either the interception should let the fallback/coalescing paths still run, or these tests need to be deliberately updated to the new contract.
Technical details
# Attach-window retention bypasses the fallback and coalescing paths
## Failing tests
- `src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-input-fallback.test.ts`
- `:66` `reports rejected input from the one-shot runtime fallback` — `onWriteUnavailable` never called (input retained instead of attempted via `terminal.send`).
- `:109` `reports terminal_not_writable from the one-shot runtime fallback` — same.
- `:154` `does not report a delayed fallback rejection after same-handle reattach` — first runtime call is `terminal.resolvePane`, not `terminal.send`.
- `:325` `does not send queued input through a stale stream during remote handle replacement` — `sendInput` returns `true` where the test asserts `false` (wrapper `attach` created a pending buffer keyed on `remote:env-1@@terminal-new`).
- `src/renderer/src/components/terminal-pane/remote-runtime-pty-transport-input-coalescing.test.ts:159` `replays a claim before separately framed input and query replies` — expected 3 `Input` frames, got 1.
## Root cause
`withRemoteReattachInputBuffer.attach` (`remote-reattach-input-buffer.ts:71-78`) sets `pending` whenever `existingPtyId` parses as `remote:`, so `sendInput` during the attach window is enqueued and returns `true` instead of reaching the raw transport's `inputBatcher` / one-shot `terminal.send` fallback. Baseline: 23 tests pass for these two files on `main` and at `1dbedf61e5`.
## Required outcome
- Decide whether attach-window rejection (the tested contract, e.g. hold input disabled until `terminal.resolvePane` validates the replacement handle) is superseded by retention. If retained intentionally, update these tests and the fallback/coalescing expectations together; if not, the wrapper must not intercept these paths.
## Open questions
- Several of these assert a "do not accept while detached" contract that this PR is deliberately changing, so some may be intended test updates rather than product bugs.DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No critical issues — one cleanup inline.
d680a61adds only debug tracing; no behavioral change.
Reviewed changes
- Debug tracing added —
withRemoteReattachInputBuffernow emitsconsole.warn('[remote-reattach-debug] ...')on everysendInput, everyattach, and every connection-ready callback (d680a61). No production or test code reads the[remote-reattach-debug]output.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No behavioral issues — the delta only adds more
[remote-reattach-debug]console tracing. Minor cleanup inline.
Reviewed changes
- Added
console.warn('[remote-reattach-debug] connect'/'connected', ...)around the wrapper'sconnectdelegate, extending the tracing introduced ind680a61. - Forwarded the paired client's
remote-reattach-debugconsole output inpaired-remote-terminal-parked-reveal-interactivity.spec.ts.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
ℹ️ No new issues in this delta.
b55e5ccis a clean redesign of the retention path: it drops thesetConnectionReadyhook, theconnectionReadylatch, and the attach-window buffering, and instead buffers from wrapper construction and flushes insideconnect. Theremote-runtime-pty-transportsuite is green (151/151, including the 5 fallback/coalescing tests that were failing through69b205c) andpnpm tc:webpasses.
Reviewed changes
- Retention moved to a construction-time buffer —
withRemoteReattachInputBuffernow seedspendingwhen the wrapper is created and flushes it at the end ofconnect(so typing on the restored screen before the firstconnectcall, and during it, is delivered to the original endpoint or dropped on a replacement). - Attach-window buffering removed —
attachnow only setsenteredand clears; input during an attach window delegates to the raw transport again, which is what restored the one-shot fallback and coalescing paths. - Debug scaffolding removed — every
[remote-reattach-debug]console.warnblock and the paired-client e2e console forward are gone. - Tests reworked — the attach/readiness cases were replaced by a pre-connect retention test and a fresh-spawn discard test; the integration test now types before
connectbegins and asserts a singleprobe-cold-parked\rframe.
DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

ELI5
Typing immediately into a restored remote terminal could silently lose the whole command. Keep typing entered before connect starts and during reconnect until the original terminal can receive it.
What Changed
Wrap the remote terminal transport with the existing bounded preconnection input buffer. Ordinary and acknowledged input wait for reattachment; terminal query replies remain immediate. Flush only to the original terminal ID and discard pending input on replacement, disconnect, detach, destruction, or failure. No remote protocol change.
Why
Linux CI captured every keystroke reaching xterm while the transport still had no handle. Waiting longer in the test would hide a user-visible loss of input. Reusing the existing bounded buffer preserves input order and prevents an unfinished command reaching a replacement terminal.
Linked Issue
CI regression investigation; no existing issue.
Visual Proof
Before: Linux reproduction and diagnostics show restored cold/reconnected terminals dropping input before binding. The failure screenshots show the host window, so they are not a useful client comparison.
After (local macOS, hidden renderer): reconnect restores the terminal and the host echoes
LINE:probe-reconnect-parkedwithout switching tabs. Linux validation will run on this PR.Testing
Review
Agent skill upstream boundary
Checklist
Follow-up: recovery-triggered reconnects now use the same wrapped connect entry point, so retries cannot bypass the buffer.
The runtime English catalog also includes the compact-agent label required by the merged-base localization scan.