Skip to content

fix(terminal): keep a dead app's input modes recoverable after a refuted proof - #23474

Merged
Jinwoo-H merged 1 commit into
mainfrom
fix/scanner-refuted-proof-keeps-modes
Sep 27, 2026
Merged

Jinwoo-H merged 1 commit into
mainfrom
fix/scanner-refuted-proof-keeps-modes

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{+}}}$​110 $\color{#cf222e}{\Huge{\mathbf{−}}}$​28 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​82
Prod 2 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​8 $\color{#cf222e}{\Huge{\mathbf{−}}}$​16 $\color{#cf222e}{\Huge{\mathbf{−}}}$​8

ELI5

When a terminal program crashes without switching its special keyboard or mouse modes back off, Orca's terminal host is supposed to switch them off once the shell prompt returns. One stray "command finished" signal could make the host give up on that for good, so a later real crash left the shell receiving garbage key codes. The host now keeps checking until the modes are actually cleared.

What Changed

The local terminal daemon (#22735, #22739) watches for the shell's command-finished mark (OSC 133;D). When a command left input modes armed (Kitty keyboard, mouse or focus reporting, or the alternate screen), the daemon checks that the shell owns the foreground again. If it does, it injects a reset into the output stream.

  • Before: at the first command-finished mark, the command's armed modes were marked as handled whether or not that check confirmed. The alternate-screen trigger was used up the same way. A full-screen agent's nested command shells leak their own command-finished marks onto the main terminal, as fix(terminal): disarm stale TUI modes when a pane confirms return to shell #9608 notes. The first leaked mark got a correct "still running" answer and used up the only trigger. When the agent later died for real, nothing recovered the terminal.
  • After: every command-finished mark re-checks while a command's mode, or the alternate screen, is still on. Only the injected reset, or the program switching the mode off itself, clears it. The scanner loses its one-shot flag, and prompt-owned modes still retire as before. The change is two production files, and it is a net deletion.

Why

A bounded retry was considered first. It still loses recovery once an agent has run more than a couple of nested commands, since each one can leak a mark. Re-checking at every mark adds no state.

Checks that can never succeed (a wsl.exe spawn, or Windows without job reads): these already answer "no" immediately, without starting any process, so the hold resolves within microtasks.

Cost while an agent is alive and leaking marks: each leaked mark holds that terminal's output until the check resolves. That's one process read, about 100 ms at p95, and output is released unchanged after 750 ms at most. The renderer's #9608 path already does a foreground read at each of these marks for agent terminals.

Stopped jobs (Ctrl+Z): they refute cheaply at each prompt until resumed or killed. After a resume the app still owns its modes; after a kill, the next mark recovers.

Linked Issue

N/A (maintainer fix to unreleased #22739)

Visual Proof

N/A: host-side stream logic, covered by unit tests; no UI change.

Testing

  • I manually tested these changes locally
  • Automated tests added/updated, or explained why not below

New scanner, barrier, session and mirror tests:

  • Five leaked command-finished marks followed by the real death still recover.
  • A live app leaking marks is asked at every mark, never reset, and its output arrives in order and unmodified.
  • The real death arrives while a leaked mark's check is still pending: the reset is injected once, and output order is preserved.
  • A confirmed recovery resets once, and the next prompt starts no new check.

Results:

  • With the previous code, 7 of the new or changed tests fail. With this change, all 84 pass.
  • The daemon and provider suites pass: 3315 tests.
  • The only failures there are 2 repro-13767 tests, which also fail on unmodified main locally.
  • pnpm run typecheck is clean.

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

  • Security: no impact.
  • Cross-platform: the check is POSIX ps or Windows job membership. On WSL and builds without job reads it answers "no" immediately.
  • SSH: no change. The relay does not run this barrier yet.
  • Mobile: no impact.
  • Compatibility: no wire change.
  • Performance: at most one extra process read per mark while an armed mode remains and the check keeps refuting. Besides a live agent leaking marks, that also covers a stopped job, a nested subshell, or an rc file that runs exec on another shell.

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)

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

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: c4f8ae6b-c6f2-4615-a754-df5f30d4524a

📥 Commits

Reviewing files that changed from the base of the PR and between fed9343c7b66092410d61e2fbfb5d8837fdaf93e and 71ecc3c.

📒 Files selected for processing (2)
  • src/main/daemon/terminal-shell-armed-input-mode-recovery.test.ts
  • src/main/daemon/terminal-shell-recovery-barrier.test.ts

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


📝 Walkthrough

Walkthrough

Command-owned input modes remain active after command-end markers. The lifecycle scanner now checks every OSC 133;D for active input modes or alternate-screen activity. Tests cover repeated foreground confirmation attempts, confirmed recovery grounding, output ordering, mouse tracking, and shell ownership confirmation.

Priority: ➖ Normal

Merge Risk: 🔵 Low · up to 71ecc

Repeated command-end markers may increase terminal-daemon work when foreground confirmation is unavailable. This is a bounded merge risk that warrants owner awareness.

Security Architecture Review

Security architecture risk: 🟡 Moderate · up to 71ecc

Repeated checks fix a real recovery failure, but a program that emits many command-end markers may impose substantially more work on the terminal daemon. An exceptional shutdown path may also leave its ownership model stale. The extent of either effect in production is not established.

Retained concerns

  • Medium · security · inferred: Repeated command-end markers can cause repeated proof episodes and rescanning of queued output; dense terminal-controlled output may consume disproportionate daemon CPU.
  • Low · reliability · inferred: After more than 16 nested pending episodes, an interruption flush can release remaining output without scanning it, potentially leaving terminal ownership state stale. The new repeated-trigger behavior makes that exceptional path easier to reach.
Security review details

Security Blast Radius

  • inferred — The directly supported exposure is terminal-output processing in the local daemon. Whether sustained processing of one session affects other sessions was not established.

Security Findings and Attack Paths

  • inferred — A terminal program that leaves modes active and emits many command-end markers can induce repeated recovery processing. Successive suffix scans provide a conditional CPU-exhaustion path; practical exploitability depends on emission shape and size.

Trust Boundaries and Controls

  • observed — A marker alone does not authorize a reset: only confirmation for the current pending episode, while the barrier is alive, reaches the grounding path. Refutation preserves the chance to recover at a later marker.

Resilience and Maintainability Implications

  • inferred — Preserving command-owned modes after a refuted proof repairs the lost-recovery case, but it also removes the previous one-shot work limit for the same mode occupancy.

Hardening Proposals

  • proposed — Bound work per output chunk or resume scanning from a cursor, while retaining the ability to check a later genuine command exit; exercise dense-marker, interruption-flush, and unavailable-proof cases.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 66.67% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 3 functions across 11 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 terminal recovery fix and matches the primary change: keeping a dead app’s input modes recoverable after a refuted proof.
Description check ✅ Passed The description follows the required template and explains the user impact, mechanism, rationale, testing, compatibility considerations, and checklist status. The maintainer-specific Linked Issue exce…
  • Fix all pre-merge checks with AI
✨ 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.

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

Caution

Some comments are outside the diff and can’t be posted inline due to GitHub limitations.

⚠️ Outside diff range comments (1)

🟡 Minor · Process the state-only suffix in one pass. · terminal-shell-recovery-barrier.ts:204

src/main/daemon/terminal-shell-recovery-barrier.ts:204
🚀 Performance & Scalability | 🟡 Minor | ⚡ Quick win

Process the state-only suffix in one pass.

When confirmShellForeground is unavailable, consumeForStateOnly re-scans the remaining suffix after each unclean OSC 133;D. With altActive still true, every marker stops scanner.scan, so the total scan work can grow quadratically for a large emission. The current emission is released first, but this synchronous replay can delay later PTY emissions.

Add a state-only scanner path that processes the suffix once while applying every marker's state transition.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: eb86e937-a5a2-4eb8-8da2-cc2f1bd2d5fe

📥 Commits

Reviewing files that changed from the base of the PR and between 838769d and d59e86065fce53d06f01a85a8953e05b7cd17d8b.

📒 Files selected for processing (11)
  • src/main/daemon/pty-subprocess-wsl-launch.test.ts
  • src/main/daemon/pty-subprocess/pty-shell-foreground-confirmation.ts
  • src/main/daemon/pty-subprocess/subprocess-handle.ts
  • src/main/daemon/session-output-pipeline.ts
  • src/main/daemon/terminal-armed-input-modes.ts
  • src/main/daemon/terminal-shell-armed-input-mode-recovery.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/main/runtime/pty-shell-ownership-mirror.test.ts

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

@Jinwoo-H
Jinwoo-H force-pushed the fix/scanner-refuted-proof-keeps-modes branch from d59e860 to fed9343 Compare September 27, 2026 21:53

@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 — two small test-quality nits.

Reviewed changes

  • Repeated, not one-shot, unclean-death checks — TerminalShellLifecycleScanner loses uncleanTriggerArmed, and TerminalArmedInputModes.markCommandEnd() no longer demotes command-owned modes to stale, so every OSC 133;D with a command mode or the alternate screen still active re-opens a recovery episode.
  • Unprovable terminals never pause — TerminalShellRecoveryBarrier now takes confirmShellForeground: (() => Promise<boolean>) | undefined and releases bytes without holding when it is absent; subprocess-handle.ts omits the proof for wsl.exe/non-shell spawns via the new canConfirmPtyShellForeground gate, and session-output-pipeline.ts propagates the absence instead of coercing to false.
  • Test coverage — new scanner, barrier, session, mirror, and WSL-gate tests for leaked-D recovery, the live-TUI "ask at every D" path, and the no-proof terminal.

I checked the main correctness question this redesign raises — whether a live agent's leaked D could ever get a confirmed proof and ground a running app. confirmShellForegroundProcess (src/main/providers/agent-foreground-process.ts:91) sorts matching shells by depth and inspects only the shallowest, which is the spawned root, so a nested shell's foreground + cannot confirm. That holds for the direct POSIX spawn, the macOS login trampoline, and the Windows job checks (windows-shell-alone-in-job.ts). No issue there.

Technical details
# Verification of the confirmed-proof concern

## Affected sites
- src/main/providers/agent-foreground-process.ts:99-108 — `foregroundShell` selection and `confirmed` computation.
- src/main/providers/agent-foreground-process.test.ts:249-271 — fixtures where a depth-3/nested shell is `S+` while the root shell is not; all resolve `false`.

## Required outcome
- No change required. Recorded so a future reviewer does not re-open the "nested shell confirms" question.

ℹ️ Nitpicks

  • src/main/daemon/terminal-shell-armed-input-mode-recovery.test.ts:347 — the comment "the one-shot trigger re-arms only on a new enable" is now stale; this PR removes the one-shot. The test still passes, but only because the leftover ?1003 command-owned mode keeps re-triggering, not because of the fresh ?1000h arm — worth updating the comment or the test's intent.

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

@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 changes to review — the head advanced (d59e860 → fed9343) but the diff against main is byte-identical.

Reviewed changes

  • Nothing new since the prior review. The two minor test-quality notes from that review (terminal-shell-armed-input-mode-recovery.test.ts:394 vacuous assertion; stale one-shot comment at line 347) still apply and are not repeated here.

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

…ted proof

A command's armed input modes were demoted at the first OSC 133;D whether or
not the foreground proof confirmed, and the alternate-screen trigger was spent
the same way. A full-screen agent's nested command shells leak their own D onto
the main PTY; the refuted proof for that stray D used up the only trigger, so
the app's real death later went unrecovered.

Every D now re-asks while a command's mode (or the alternate screen) is still
up; only the confirmed ground or the app's own disable clears it. Proofs that
can never succeed (wsl.exe, no Windows job reads) already refute immediately
without spawning anything. The accepted cost is one process read plus a bounded
output hold per D while a command-owned mode stays up and the proof keeps
refuting: a live agent leaking D, a stopped job, a nested subshell, or an rc
that execs another shell.
@Jinwoo-H
Jinwoo-H force-pushed the fix/scanner-refuted-proof-keeps-modes branch from fed9343 to 71ecc3c Compare September 27, 2026 21:59

@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 — the new commit narrows the change to the two production files and the repeated-trigger fix, and the prior review's only open thread is resolved.

Reviewed changes

  • Reverted the optional-proof/no-pause design — TerminalShellRecoveryBarrier, subprocess-handle, session-output-pipeline, and pty-shell-foreground-confirmation return to main; canConfirmPtyShellForeground and the WSL gate test are gone. The reverted files are byte-identical to base, so no fresh code to review there.
  • Kept the repeated unclean-death trigger — TerminalShellLifecycleScanner drops uncleanTriggerArmed and uncleanDeath = markCommandEnd() || altActive; markCommandEnd() no longer demotes command-owned modes, so every 133;D with a command mode or the alt screen still up re-asks.
  • Reworked the tests to match — scanner/barrier/session/mirror cases now assert re-asking at every D, byte-identical in-order release on refutation, recovery when the real death D arrives while a stray D is still being proven, and no re-trigger after a confirmed ground; the no-proof terminal tests were removed with the feature.

I verified the reversion's load-bearing claim — that unprovable terminals refute without spawning — holds: confirmShellForegroundProcess early-returns on !isShellProcess (src/main/providers/agent-foreground-process.ts:73), and isWindowsShellAloneInJob returns false on absent job membership before reading the process table (src/main/providers/windows-shell-alone-in-job.ts:27). Ran the four changed suites (81 pass) and pnpm tc:node (clean).

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

@Jinwoo-H
Jinwoo-H merged commit 618a8b0 into main Sep 27, 2026
45 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