Skip to content

fix(relay): reset input modes a dead program left on in SSH terminals - #23488

Merged
Jinwoo-H merged 4 commits into
mainfrom
feat/relay-input-mode-ground
Sep 28, 2026
Merged

Jinwoo-H merged 4 commits into
mainfrom
feat/relay-input-mode-ground

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​289 $\color{#cf222e}{\Huge{\mathbf{−}}}$​46 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​243
Prod 4 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​89 $\color{#cf222e}{\Huge{\mathbf{−}}}$​42 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​47

ELI5

When a terminal program such as a coding agent or vim dies without cleaning up, the terminal can be left in special keyboard or mouse modes. After that, keys like Shift+Enter or Option chords send garbled input to the shell. Local terminals already clean this up automatically once the shell is back in control (#22739). SSH terminals didn't; this PR gives them the same cleanup.

What Changed

  • Before: in an SSH terminal, a program that crashed or was killed could leave keyboard, mouse or paste modes switched on (for example the Kitty keyboard protocol). The shell prompt then received encoded keystrokes and could be left painting on the alternate screen. Only the window's own resets (Ctrl+C, reconnect) sometimes papered over it.
  • After: SSH terminals behave like local ones. When a command finishes with modes still armed, the remote host checks that the shell really owns the terminal again, then puts a reset into the output stream. The Orca window, replay history and every attached client all see the same reset.
  • Mechanism:
    • src/relay/pty-handler.ts puts the existing TerminalShellRecoveryBarrier between each SSH terminal's startup ingress and its output emitter, using the same foreground proof the local daemon uses.
    • On teardown it flushes any held output before disposing the barrier.
    • terminal-shell-recovery-barrier.ts now holds back the whole "command finished" signal (OSC 133;D) during the check. It then releases the signal together with the reset as one output span that covers real raw bytes.
    • Previously the reset was a zero-length span, which SSH's credit-windowed delivery silently drops.

Why

  • Why share the barrier: reusing the daemon's barrier keeps one implementation of the cleanup policy across local and SSH instead of a second copy in the relay.
  • Why carry the reset on the held signal:
    • A reset with no raw bytes of its own is invisible to delivery layers that account by raw bytes.
    • Carrying it on the next output byte instead would need extra "reset owed" state and would delay the reset until the prompt paints.
  • Local daemon fix too: a zero-length span shares a sequence number with a snapshot taken during the check. Remote-runtime and preview subscribers drop anything at or below the snapshot's sequence, so they lost the reset. The one-character span survives.
  • Wire compatibility: no protocol change. SSH clients have accepted transformed frames, where the raw length differs from the text length, since feat(ssh): bound relay PTY output end to end #11005, and the relay already sends them. A new client paired with an older relay gets no barrier, which is the same as today.

Linked Issue

Follow-up to #22739 (local process-boundary cleanup); no separate issue.

Visual Proof

N/A: this changes byte-stream recovery after a program dies, and it's covered by stream-level tests rather than a UI change.

Testing

  • Automated tests added/updated
  • I manually tested these changes locally

Tests:

  • New src/relay/pty-handler-shell-recovery.test.ts runs 8 tests, each with source-credit delivery and with the older delivery path:
    • Proof succeeds: live output and replay both equal 133;D + reset + prompt.
    • Proof fails: bytes are unchanged.
    • A 20K chunk before the marker isn't stalled.
    • The PTY exiting mid-proof still delivers the held prompt.
  • Barrier unit tests are updated, and new ones check:
    • A terminator split across chunks (ESC | \).
    • Every emission covers at least one raw character on the confirm, refute and timeout paths.
  • Checked against the old code:
    • The source-credit tests fail when the old barrier is wired into the relay.
    • 6 of the 8 relay tests fail with no wiring at all.
  • pnpm run typecheck, check:code-quality:changed and build:relay pass.
  • The whole src/relay + src/main/daemon suite passes, apart from two repro-13767-shell-ready-marker-lost-to-exec tests that also fail on main.

Platforms: the remote foreground proof is ps stat on POSIX relays. Windows relays use job membership, and without job info the proof fails, which leaves the bytes unchanged.

Review

  • Delayed signal: on an unclean exit only, the "command finished" signal now reaches the window up to one foreground check later (usually ~100ms, at most 750ms). The prompt was already held for that long.
  • Signal split across chunks: the barrier holds only the part in the current chunk. That behaves like any chunk that splits an escape sequence today.
  • Very large signals: a signal over 4096 characters is held only in part, so it stays under the relay's 16K frame limit.

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

Ensure no issues in: Security, Cross-platoform support (Linux, Windows, Mac), Remote SSH, Mobile, general backwards compatibility, performance

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)

SSH relay PTYs now run the same recovery barrier as the local daemon:
between startup ingress and the replay buffer/publish sink, it pauses at
an OSC 133;D that closes a command which left input modes or the
alternate screen armed, proves the shell owns the PTY foreground on the
execution host, and on proof injects the process-boundary ground ahead of
the prompt. Teardown flushes held bytes through releaseRelayIngress.

The barrier now holds only the D marker's terminator and carries the
ground on it as one transformed emission over exactly one raw unit.
Previously the ground was a zero-raw emission, which source-credit
delivery accepts but never sends, so live output and replay diverged.
Every emission now covers at least one raw unit; refuted, timed-out,
overflowed and flushed episodes release the terminator unmodified.
…aw span

Treat a trigger end below 1 as unsplittable instead of trusting the
scanner's clamp, arm the bail timer before queueing the terminator, and
build the relay's startup ingress unconditionally beside its barrier.
@coderabbitai

coderabbitai Bot commented Sep 27, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

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

Important

Review skipped

Review was skipped as selected files did not have any reviewable changes.

⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: e2f8b364-f153-4cae-a44f-5fb751e0baf7

📥 Commits

Reviewing files that changed from the base of the PR and between 92e24c2 and 13c8eed.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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: 97badc3f-ca32-4262-91e1-79eb6a20b8ae

📥 Commits

Reviewing files that changed from the base of the PR and between c411408 and 92e24c2.

📒 Files selected for processing (6)
  • src/main/daemon/process-boundary-ground.test.ts
  • src/main/daemon/terminal-shell-lifecycle-scanner.test.ts
  • src/main/daemon/terminal-shell-lifecycle-scanner.ts
  • src/main/daemon/terminal-shell-recovery-barrier.test.ts
  • src/main/daemon/terminal-shell-recovery-barrier.ts
  • src/relay/pty-handler.ts

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


📝 Walkthrough

Walkthrough

The scanner now reports the start offset of an unclean-death trigger. The recovery barrier holds the complete marker during foreground confirmation and appends the process-boundary ground sequence to it when confirmation succeeds and the process remains alive. PtyHandler routes startup ingress through the barrier and flushes held output during ingress teardown. Tests cover marker splitting, proof outcomes, snapshots, published output, and replay.

Priority: ⬇️ Low

Merge Risk: ⚪ Minimal · up to 92e24

The reviewed terminal-recovery changes are mergeable after normal checks. No actionable issue remains from this review.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 92e24

The new SSH recovery path can briefly hold terminal output and send a reset to attached clients, but the inspected path requires confirmation that the shell is foregrounded and the terminal is alive. Failed confirmation releases the original output. No introduced security finding was established, though runtime coverage remains incomplete.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — A recovery decision affects the output stream for its managed PTY, including that PTY’s replay buffer and downstream client output; the inspected barrier does not itself select other PTYs or clients.

Security Findings and Attack Paths

  • inferred — A process able to write terminal output may supply marker bytes that initiate a recovery check. In the inspected path, those bytes alone do not authorize a reset: grounding additionally requires foreground confirmation and a live PTY.

Trust Boundaries and Controls

  • observed — The reset decision uses execution-host process evidence rather than trusting the command-finished marker as proof of shell ownership. A stale confirmation cannot set scanner ownership after its generation changes.

Resilience and Maintainability Implications

  • observed — Confirmation rejection, deadline expiry, and queue overflow settle pending output without grounding; teardown flushes held emissions before disposal. These paths limit a failed proof’s effect on output delivery.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 12.50% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 8 functions across 8 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 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 primary change: resetting input modes left active by dead programs in SSH terminals.
Description check ✅ Passed The description is complete and directly matches the implementation. It explains the user impact, mechanism, rationale, testing, platform considerations, limitations, and checklist status. It also ide…
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR

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.

… on an escape boundary

The scanner now reports where the unclean-death D mark starts; the
barrier releases everything before it and holds the mark itself (bounded
to 4K, so the grounded span stays inside a relay source frame). A
snapshot taken mid-proof therefore has no open OSC for consumers that do
not restore the pending escape tail. The relay defines PTY liveness once.

@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 critical issues — one test-coverage suggestion inline.

Reviewed changes

  • Relay wiring — src/relay/pty-handler.ts now builds a TerminalShellRecoveryBarrier per managed PTY (reusing confirmPtyShellForeground) between its startup ingress and output emitter, and teardown flushes then disposes it after drainAndClose().
  • Barrier emission shape — the OSC 133;D trigger's last raw byte is now held and re-emitted as one transformed span (terminator + ground, one raw unit) instead of a zero-length ground span, so credit-windowed delivery and sequence-based snapshot dedup stop dropping it. end >= 1 was added to splittable, the bail timer is armed before the terminator is queued, and releaseTerminator owns the ground release plus trySetOwner.
  • Type/wiring cleanups — confirmPtyShellForeground accepts shellPath: string | undefined; the relay's startup ingress is built unconditionally (??= → =).

Verified locally: pnpm test src/relay src/main/daemon passes (402 files, 4167 tests, 52 skipped), including the new src/relay/pty-handler-shell-recovery.test.ts. I traced the raw-sequence conservation (head end-1 + terminator 1 = the old trigger end) and the relay source-credit path (sourceLengthSu = rawLength = 1, indivisible, sent/acked once) — both are consistent with the PR's claim that the zero-length span previously died in delivery.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Flash (free via Pullfrog for OSS) | 𝕏

Comment on lines +132 to +133
if (sourceCredit) {
expect(frames.every((frame) => frame?.params?.sourceLengthSu !== undefined)).toBe(true)

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.

The source-credit assertion only checks that sourceLengthSu exists, so a regression reporting the grounded span's raw length as its payload length — which would over-drain the source window and advance the client model by ~250x — would still pass. Pin the grounded frame's sourceLengthSu (and rawLength) to 1; that one-raw-unit span is the entire fix this PR is built around.

Suggested change
if (sourceCredit) {
expect(frames.every((frame) => frame?.params?.sourceLengthSu !== undefined)).toBe(true)
if (sourceCredit) {
expect(frames.every((frame) => frame?.params?.sourceLengthSu !== undefined)).toBe(true)
const grounded = frames.find((frame) =>
String(frame?.params?.data ?? '').includes(PROCESS_BOUNDARY_GROUND)
)
expect(grounded?.params?.sourceLengthSu).toBe(1)

@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 (incremental since c411408)

  • Hold the whole OSC 133;D mark — terminal-shell-recovery-barrier.ts now holds the entire command-done marker (bounded to MAX_HELD_MARK_CHARS = 4096) and rides the ground on it, instead of holding only its last byte. This keeps a snapshot taken during the ownership proof ending before the marker, so the emulator has no dangling open OSC.
  • Scanner reports the marker start — terminal-shell-lifecycle-scanner.ts adds uncleanDeathTriggerStart so the barrier can split at the marker's start rather than arbitrarily; it clamps to 0 when the marker began in an earlier chunk.
  • Tests — new process-boundary-ground test asserts pendingEscapeTailAnsi is undefined mid-proof (this fails under the previous last-byte-only hold, so it genuinely pins the behavior), plus scanner and barrier assertions for the new split.

I read the incremental diff end to end and re-ran the whole src/relay + src/main/daemon suite on 92e24c2 (402 files, 4168 tests pass, 52 skipped). The raw-sequence arithmetic stays conserved (head start + held mark end-start = the old trigger end), no bytes are reordered, and the relay source-credit span remains one indivisible non-zero-length unit. The unaddressed item from my prior review (the relay test only asserting sourceLengthSu !== undefined rather than its value) still stands as an optional test-hardening suggestion; nothing new blocks merge.

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

@Jinwoo-H
Jinwoo-H merged commit 5219b8a into main Sep 28, 2026
87 of 89 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