Skip to content

fix(ssh): restore the reconnect model-paint gate dropped by #15166 - #16361

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/sta-5395-restore-ssh-reconnect-model-gate
Aug 25, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/sta-5395-restore-ssh-reconnect-model-gate

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 3 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​217 $\color{#cf222e}{\Huge{\mathbf{−}}}$​4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​213
Prod 5 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​109 $\color{#cf222e}{\Huge{\mathbf{−}}}$​11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​98

What broke

#15166 split pty-connection.ts into modules and dropped the "paint from main's model on SSH reconnect" half of the reattach gate. Only the park-reveal half survived:

// pty-connection/apply-reattach-payload.ts:113 on main
const modelSnapshot = ctx.revealFollowsTerminalPark ? (ctx.prefetchedParkModelSnapshot ?? …) : null

So on a plain SSH reconnect — network drop, wake, reload — that is not a park-reveal, modelSnapshot is unconditionally null and the pane repaints from the relay replay tail alone. That tail is capped at REPLAY_BUFFER_MAX = 100*1024 (src/relay/pty-handler.ts) and cannot rebuild a full-screen frame whose start it no longer holds.

This regressed v1.4.188's #14844 (feat(ssh): verify host keys, and restore panes correctly across a reconnect) — the exact fragmentation that PR fixed. Gate-identifier occurrences: v1.4.188 26 → origin/main 21. sshReconnectPaintsFromModel and lastAlternateScreenTransition survived in ssh-reattach-model-restore.ts with zero production callers.

git log -S on both identifiers returns exactly two commits — 24e662adc1 (#14844, added) and 7a72f341f7 (#15166, removed the callers). Nothing since; there was no fix anywhere to cherry-pick.

Live A/B evidence

Docker node:20-bullseye + sshd, real repo, relay built and deployed by Orca, SSH target connected from inside the app. In the SSH pane: enter alt screen, paint a full-screen frame once, then emit ~171 KB of cursor-addressed updates with no repaint — sized against the 100 KiB relay cap so the frame start is evicted. Then a real network drop (docker network disconnect), wait reconnecting → connected, read the xterm buffer.

Arm Result after reconnect
main (gate-less) bufType:"normal" — not even alt screen. Row 0 is literal garbage 30;1Hupd-0003312 (tail begins mid-escape and prints as text). Frame marker gone, both static rows gone
Same commit + this restore bufType:"alternate", frame marker intact, STATIC-ROW-3, STATIC-ROW-45, full frame restored

Decisive detail: a pre-drop probe of window.api.pty.getMainBufferSnapshot returned {source:'headless', alternateScreen:true, holdsMarker:true} — main's model held the good payload at reconnect time and the code discarded it.

What this restores

  1. followsDirectSshReconnect — a PENDING-only read of directSshPaneRetryByTabId[tabId]. Deliberately not directSshRetryAttempt, which also accepts the live binding and so stays truthy for every later remount of the generation.
  2. reconnectMayUseModel = followsDirectSshReconnect && !revealFollowsTerminalPark — keeps park and reconnect mutually exclusive.
  3. The replayTransition === 'exited' veto, computed before the probe. Ordering is load-bearing: probing first spends the 750 ms SSH_REATTACH_MODEL_SNAPSHOT_TIMEOUT_MS inside the structural-replay coordinator, with live PTY bytes deferred, only to discard the answer.
  4. Fetch through ctx.fetchSshMainModelReattachSnapshot — the same memoized single-flight probe the park path uses, so no second timeout.
  5. sshReconnectPaintsFromModel({snapshot, hasReplay, replayTransition, altFrameWouldBeSkipped}).
  6. modelSnapshot = revealSnapshot ?? (paintsReconnectFromModel ? reconnectSnapshot : null) — park precedence preserved.
  7. kittyKeyboardModes.scanReplay(replay) placed after applySnapshotKittyKeyboardModes. Note this is not a bug on main today — the degraded relay path does its own resetForSnapshot() + scanReplay(). But any fix that restores model painting must re-add the layered scan, or the fix itself introduces a stale-flag-stack bug: the snapshot sets the pre-outage baseline and the replay layers the outage's kitty pushes on top. Omitted, Option/Alt chords encode against stale flags; inverted, the baseline clobbers the outage pushes.

The original Why: comments from 617f7c8de3 are transplanted verbatim — including the second paragraph of the model-snapshot comment that #15166 deleted, which is the only signal a future reader has that the reconnect case exists at all.

apply-reattach-payload.ts lands at 356 lines, under the split's 400 budget. No max-lines suppression added.

The test — and why the old one could not catch this

The only prior coverage was ssh-reconnect-model-paint-gate.test.ts, which calls the pure function directly. It stayed green through the entire removal, validating a gate nothing consulted. The full suite was green on a tree carrying this bug.

This PR adds pty-connection/reattach-payload-ssh-reconnect-model-paint.test.ts, a call-site test over createReattachPayloadHandlers:

  • (a) non-park SSH reconnect ctx, replay with no 1049 transition ⇒ probe called, model bytes painted, relay tail not painted, and scanReplay fires after the snapshot kitty baseline.
  • (b) replay containing \x1b[?1049l ⇒ probe never issued (proves the veto precedes the fetch), relay bytes painted.
  • (c) park + reconnect both armed ⇒ prefetched park snapshot wins, probe never issued.

RED — case (a) on unfixed main

4 production files reverted to origin/main @ 2960fe9193, test files kept. Assertions are expect.soft so an unhooked gate reports every invariant it broke:

 ❯ .../reattach-payload-ssh-reconnect-model-paint.test.ts (3 tests | 1 failed)
   × paints a non-park SSH reconnect from main model and layers the replay over the kitty baseline

AssertionError: expected "vi.fn()" to be called 1 times, but got 0 times

AssertionError: expected '…' to contain 'MODEL-FULL-SCREEN-FRAME'
  Expected: "MODEL-FULL-SCREEN-FRAME"
  Received: "[0m[2J[3J[H30;1Hupd-0003312<reset>"

AssertionError: expected '…' not to contain '30;1Hupd-0003312'
  Expected: "30;1Hupd-0003312"
  Received: "[0m[2J[3J[H30;1Hupd-0003312<reset>"

AssertionError: expected [ …(4) ] to include 'kitty:snapshot-baseline'

 Test Files  1 failed (1)
      Tests  1 failed | 2 passed (3)

The Received value is the bug verbatim: the pane paints 30;1Hupd-0003312, the same garbled mid-escape tail the live A/B captured in row 0.

GREEN — with the fix

 Test Files  1 passed (1)
      Tests  3 passed (3)

One existing test changed — please read this bit

pty-connection-direct-ssh-reattach-retry.test.ts had a case named "uses the SSH relay replay for a reconnect even when main has an alt-screen model". git log -S shows it was added by #15166 itself (7a72f341f7), in the same PR that removed the gate — its commit log reads "Simplify reconnect model restoration by removing the conditional model snapshot probe and using relay replay directly." No pre-split counterpart existed. It pins the regressed behavior, so it blocks the restore.

Its fixture is a reconnect whose replay is '9l\r\n$ real-shell-output' — a tail whose \x1b[?1049l lost its ESC to byte eviction. lastAlternateScreenTransition cannot read a transition there (documented in its own comment: "A tail can begin mid-escape, so the first chunk is ordinary text and simply fails to match"), so under #14844's shipped contract the model wins.

I rewrote it into two cases against a shared fixture rather than deleting it:

  • paints a reconnect from the alt-screen model when the replay shows no alt-screen exit — the original fixture, expectation flipped to v1.4.188's contract. This one is also RED on main (expected "vi.fn()" to be called at least once).
  • uses the SSH relay replay for a reconnect once the replay shows the app left alt screen — same fixture with a readable \x1b[?1049l. Pins that the relay still wins and the probe is never issued.

Net that file goes 7 → 8 tests, all passing.

Known limitation, pre-existing in v1.4.188, not addressed here: in that first fixture the shell really did leave alt screen, and painting the model discards real-shell-output. The gate cannot see it because the ESC was evicted. Closing that hole means new heuristics #14844 never had, which is outside a restore — flagging it rather than smuggling it in.

Verification

  • oxfmt clean; oxlint clean.
  • check:code-quality:changed: 0 new findings (code quality, type-aware, React Doctor) across 7 changed files.
  • check:max-lines-ratchet: OK, no new bypasses.
  • Full src/renderer/src/components/terminal-pane/ suite: 392 files / 3780 tests passed.

Fixes STA-5395

#15166 split pty-connection.ts and dropped the "paint from main's model on SSH
reconnect" half of the reattach gate that shipped in v1.4.188 (#14844), leaving
only the park-reveal half. A non-park SSH reconnect has repainted from the
~100KiB relay tail ever since, which cannot rebuild a full-screen frame whose
start it no longer holds.

Restores followsDirectSshReconnect (PENDING-only retry read), reconnectMayUseModel,
the exited-transition veto computed before the probe, and the kitty scanReplay
layered after the snapshot baseline. Adds a call-site test over
createReattachPayloadHandlers, because the surviving pure-function test stayed
green through the entire removal.

Fixes STA-5395
@coderabbitai

coderabbitai Bot commented Aug 25, 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: Pro Plus

Run ID: 89d2b4d0-d5de-4bdc-a317-a63ddd87b760

📥 Commits

Reviewing files that changed from the base of the PR and between 0531d3a and a8f457b.

📒 Files selected for processing (7)
  • src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-reattach-retry.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/apply-reattach-payload.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-payload-context.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-payload-context.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-payload-ssh-reconnect-model-paint.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler.ts
  • src/renderer/src/components/terminal-pane/pty-connection/resolve-ssh-reconnect-model-paint.ts

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


📝 Walkthrough

Walkthrough

Direct SSH reattach handling now tracks reconnect-specific model-paint eligibility. Reattach payload application checks replay transitions and snapshot width before using a main-process model snapshot. Park snapshots remain prioritized for terminal-park reveals. Structural payload application now uses shouldApplyStructuralPayload. Tests cover model painting, replay behavior, alternate-screen exits, and snapshot precedence.

Merge Risk: ⚪ Minimal · up to a8f45

The change restores model-backed SSH reconnect rendering while preserving park and replay behavior, with targeted tests and validation passing; no actionable merge-blocking risk remains.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 10.00% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 10 functions across 8 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 identifies the main change: restoring the SSH reconnect model-paint gate.
Description check ✅ Passed The description is detailed and directly explains the regression, restoration approach, tests, verification results, and linked issue. It does not reproduce every template heading or checklist item, b…
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 is detailed and directly explains the regression, restoration approach, tests, verification results, and linked issue. It does not reproduce every template heading or checklist item, but it provides the critical required information and is mostly complete.

✨ 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 coderabbitai 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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 5dcbed5d-be8f-4d2a-8d1f-43fd0910a322

📥 Commits

Reviewing files that changed from the base of the PR and between b6a24ec and 0531d3a.

📒 Files selected for processing (7)
  • src/renderer/src/components/terminal-pane/pty-connection-direct-ssh-reattach-retry.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/agent-idle-working-handlers.ts
  • src/renderer/src/components/terminal-pane/pty-connection/apply-reattach-payload.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-payload-context.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-payload-context.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-payload-ssh-reconnect-model-paint.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection/reattach-result-handler.ts

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

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Independent QA — SSH reconnect model-paint gate

Verdict: LAND

HEAD: a8f457b318ee92727561a2b8fcabd3a1a3ed4500 (a8f457b318)

Target shape: Throwaway Linux Docker node:20-bullseye + sshd (aarch64), dedicated user-defined network, host port 127.0.0.1:2222 → container :22. Not ssh localhost. Real /work/demo-project (GitHub HTTPS clone failed with no credentials in the container; cloned from a local git bundle). Isolated Electron: ORCA_DEV_USER_DATA_PATH=/tmp/orca-ssh-test-1787635612/orca-user-data, CDP 9339, renderer 5178 (5173 already occupied). window.api.app.getIdentity() matched this worktree/branch (sta-5395-ssh-reconnect-gate @ brennanb2025/sta-5395-restore-ssh-reconnect-model-gate). pnpm build:relay completed (linux-arm64 + other platforms) before connect.

User action: Add Project → Add remote host → Add SSH host (orca-qa-linux-ssh, [email protected]:2222, temp ed25519 identity) → Connect. Open project on SSH host /work/demo-project. In Terminal 1, typed node .orca-qa-paint-hold.mjs 59 135 (alt screen, FRAME-START-STA5395 / STATIC-ROW-3 / STATIC-ROW-45 / STATIC-ROW-57, then ~180 KiB of cursor-addressed upd-NNNNNNN with no full repaint so the 100 KiB relay tail cannot hold the frame start). Real network drop via docker network disconnect. Overlay showed SSH connection required; store went reconnecting (Relay channel lost. Reconnecting...) then error (Connection lost before handshake) while isolated. Restored the network, clicked overlay Retry.

Negative/safety path: New Terminal (Terminal 2) painted NEG-FRAME-SHOULD-NOT-SURVIVE, disconnected again, wrote a readable alt-screen exit (printf of \033[?1049l + real-shell-output) into that PTY during the outage, restored network, Retry.

Visible result: After Retry, Terminal 1 restored the full alt-screen frame (FRAME-START-STA5395, STATIC-ROW-3, STATIC-ROW-45, STATIC-ROW-57) with surrounding Orca chrome, a live bash prompt/cursor, and 1 host connected. No mid-escape garbage such as 30;1Hupd-… printed as text. Pre-reconnect, main’s headless snapshot was {source:'headless', alternateScreen:true, holds FRAME-START}. Terminal 2 after the readable exit restored as a normal shell (Terminated + echoed printf/real-shell-output + prompt), not a full-screen alt TUI.

Restored post-reconnect (Terminal 1, model paint):

04-post-reconnect-restored-frame.png

Outage overlay before Retry:

02-outage-ssh-connection-required.png

Negative path (Terminal 2, readable alt-screen exit during outage → relay/shell, not a restored TUI frame):

05-negative-alt-exit-relay.png

Remote backing / process continuity: Bash PTY 6204 on pts/0 survived both drops (Ss+ /bin/bash --rcfile /root/.orca-relay/shell-ready/bash/rcfile). Relay: first connect deployed relay.js --detached; reconnects logged Existing relay socket found, attempting reconnect... / Relay started successfully / pty.attach succeeded … replay=true for pty-1 and pty-2. Relay log: socket client closed → handshake OK → client accepted (twice). git -C /work/demo-project status --short --branch → ## main...origin/main plus only the throwaway paint script.

Logs inspected: Playwright console 0 errors. Renderer: [pty-connection] Attempting reattach / Reattach result: {replay: true} for both tabs. Electron: mux Connection timed out (no ack received), Relay channel lost … triggering reconnect, keepalive timeout while isolated, then existing-socket relay reconnect. Expected pty:inspectProcess CONNECTION_LOST during the drop. No unexpected renderer exceptions.

Cleanup: Docker container orca-ssh-test-1787635612 and its network, temp key + user-data dir, Electron PID 62813 process group (command verified to include this worktree + overlay config before kill), playwright session. Worktree git status --short empty — no evidence images committed.

Remaining gap: While the container was isolated, the auto-reconnect ladder ended at Connection lost before handshake instead of recovering on its own; the user-visible Retry after the network returned is what remounted the pane. That ladder behavior is outside this restore. The + New tab control immediately after the first reconnect did not spawn a PTY until New Terminal from the tab menu (pre-existing). Terminal 2’s 1049l was injected as a shell printf (readable in the tail, including the echoed command).

@brennanb2025

Copy link
Copy Markdown
Contributor Author

Final review status — LAND

Reviewed and validated at exact HEAD a8f457b318ee92727561a2b8fcabd3a1a3ed4500.

Review loops

  • Initial readiness audit: PASS with no P0/P1/P2 candidates.
  • Equal-model review/fix loop found and fixed two meaningful issues:
    • empty/missing relay replay could skip the model path and leave the fresh reconnect pane blank;
    • ineligible reconnects performed avoidable replay scans and duplicate/unused geometry reads.
  • Fix commit a8f457b318 was pushed with handler-level and full-connectPanePty regressions.
  • Fresh equal-model review of the complete patched diff returned CLEAN with no edits.
  • Final exhaustive readiness audit: PASS, zero P0/P1/P2 candidates; findings-severity counsel skipped because there were no candidates.

Verification

  • Full PR CI is green: 49 successful checks and one expected skipped aggregate, including Node 24/26 matrices, static analysis, typecheck, cross-version wire compatibility, Windows packaging, changed E2E, and Docker SSH parking/isolation.
  • Focused review gates passed across reconnect/model selection, direct-SSH reliability, park/replay/live-byte ordering, queue caps, changed-code quality, max-lines, and the reliability manifest.
  • Performance review found no new polling, subprocess fanout, unbounded retention, listener/timer lifecycle, or renderer hot-path work. The exit veto precedes the bounded snapshot probe, the replay tail is scanned once only when eligible, the probe stays memoized, and live output retains existing byte/chunk caps.
  • No mobile-facing, wire, persisted-state, dependency, security, path, shell, native-module, or provider contract changed.

Real SSH / Electron proof

Independent QA used a throwaway Linux Docker SSH target and real remote repo, built the relay from this head, launched an isolated Electron instance, verified its worktree identity over CDP, and drove the complete UI flow:

  1. Add/connect SSH host and remote repo.
  2. Paint a full alternate-screen frame.
  3. Emit ~180 KiB of cursor-addressed updates so the 100 KiB relay tail cannot rebuild it.
  4. Disconnect the Docker network.
  5. Restore the network and use the visible Retry action.
  6. Confirm the full frame and static rows restore without fragmented mid-escape garbage.
  7. Exercise the readable alternate-screen-exit safety path and confirm the normal shell/replay wins instead of restoring a stale TUI frame.

Screenshots, process continuity, logs, and cleanup evidence: #16361 (comment)

Residual risk

  • Automatic recovery ended at “Connection lost before handshake” while the target was isolated; the visible Retry action after network restoration remounted the pane. That reconnect-ladder behavior is pre-existing and outside this focused paint restoration.
  • A relay tail whose leading ESC byte was already evicted cannot prove an alternate-screen exit; this is the explicitly documented pre-existing limitation of the restored shipped contract.
  • Physical Windows/WSL client and additional DNS/half-open/sleep journeys were not rerun; this PR does not change those connection mechanisms.

Worktree and upstream are clean and synchronized at a8f457b318. QA container, network, temporary keys/profile, Playwright session, and launched Electron process were removed. Final verdict: LAND.

@brennanb2025
brennanb2025 merged commit 656e489 into main Aug 25, 2026
50 checks passed
paidaxingyo666 pushed a commit to paidaxingyo666/Manta that referenced this pull request Aug 25, 2026
…15166 (stablyai#16361)

* fix(ssh): restore the reconnect model-paint gate dropped by stablyai#15166

stablyai#15166 split pty-connection.ts and dropped the "paint from main's model on SSH
reconnect" half of the reattach gate that shipped in v1.4.188 (stablyai#14844), leaving
only the park-reveal half. A non-park SSH reconnect has repainted from the
~100KiB relay tail ever since, which cannot rebuild a full-screen frame whose
start it no longer holds.

Restores followsDirectSshReconnect (PENDING-only retry read), reconnectMayUseModel,
the exited-transition veto computed before the probe, and the kitty scanReplay
layered after the snapshot baseline. Adds a call-site test over
createReattachPayloadHandlers, because the surviving pure-function test stayed
green through the entire removal.

Fixes STA-5395

* fix(ssh): restore empty-tail reconnect snapshots

(cherry picked from commit 656e489)
dallascrilley pushed a commit to dallascrilley/orca that referenced this pull request Aug 27, 2026
…15166 (stablyai#16361)

* fix(ssh): restore the reconnect model-paint gate dropped by stablyai#15166

stablyai#15166 split pty-connection.ts and dropped the "paint from main's model on SSH
reconnect" half of the reattach gate that shipped in v1.4.188 (stablyai#14844), leaving
only the park-reveal half. A non-park SSH reconnect has repainted from the
~100KiB relay tail ever since, which cannot rebuild a full-screen frame whose
start it no longer holds.

Restores followsDirectSshReconnect (PENDING-only retry read), reconnectMayUseModel,
the exited-transition veto computed before the probe, and the kitty scanReplay
layered after the snapshot baseline. Adds a call-site test over
createReattachPayloadHandlers, because the surviving pure-function test stayed
green through the entire removal.

Fixes STA-5395

* fix(ssh): restore empty-tail reconnect snapshots
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…15166 (stablyai#16361)

* fix(ssh): restore the reconnect model-paint gate dropped by stablyai#15166

stablyai#15166 split pty-connection.ts and dropped the "paint from main's model on SSH
reconnect" half of the reattach gate that shipped in v1.4.188 (stablyai#14844), leaving
only the park-reveal half. A non-park SSH reconnect has repainted from the
~100KiB relay tail ever since, which cannot rebuild a full-screen frame whose
start it no longer holds.

Restores followsDirectSshReconnect (PENDING-only retry read), reconnectMayUseModel,
the exited-transition veto computed before the probe, and the kitty scanReplay
layered after the snapshot baseline. Adds a call-site test over
createReattachPayloadHandlers, because the surviving pure-function test stayed
green through the entire removal.

Fixes STA-5395

* fix(ssh): restore empty-tail reconnect snapshots
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