Skip to content

fix(terminal): recover rejected paired-runtime input (STA-2830) - #12675

Merged
Jinwoo-H merged 2 commits into
mainfrom
fix/remote-input-write-unavailable
Aug 5, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
fix/remote-input-write-unavailable

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Summary

Fixes STA-2830's remaining silent-input invariant for paired-runtime terminals.

Commit 72245918a1 / #12589 already fixed the reported attach failure: subscribing to a never-activated daemon session now attaches its provider output pipeline without requiring the host renderer to open the project. That original attach state no longer reproduces on current main.

A narrower failure still reproduced: the renderer accepted an Input frame locally, the authoritative host runtime.sendTerminal rejected it before any process write, and the host discarded the rejection without sending any recovery signal. The pane therefore kept reporting success while the keystroke vanished.

This change:

  • classifies authoritative stream writes as delivered, rejected, or failed;
  • adds opcode WriteUnavailable = 17 for rejected writes;
  • capability-negotiates that opcode through the existing Subscribe JSON frame;
  • emits it for capable multiplex and legacy binary subscribers only;
  • decodes it into the pane's existing onWriteUnavailable recovery hook;
  • reports rejected terminal.send fallback results and terminal_not_writable failures through the same hook;
  • fences delayed host failures by stream identity and delayed renderer failures by pane lifecycle epoch;
  • registers the durable reliability invariant in config/reliability-gates.jsonc.

Reproduction on current main

Baseline: e5f49e0e1d (current origin/main when the oracle was established).

pnpm exec vitest run --config config/vitest.config.ts \
  src/main/runtime/rpc/terminal-multiplex.test.ts \
  --reporter=verbose \
  -t 'reports when locally accepted input never reaches the process'

Test-only oracle result before production changes:

  • subscribe completed;
  • the client Input handler accepted the frame;
  • authoritative sendTerminal was called exactly once;
  • the injected process-write record stayed empty;
  • the test failed only because raw opcode 17 never returned;
  • result: 1 failed, 58 skipped.

Compatibility

The new opcode is never sent without capabilities.writeUnavailable: 1 on that stream.

  • New client + old host: the optional capability key is ignored by the old Subscribe JSON decoder; the old host never emits opcode 17. Existing watchdog/fallback behavior remains unchanged.
  • Old client + new host: the old client omits the capability, so the new host never emits an opcode the old decoder would reject.
  • New client + new host: rejected authoritative writes emit opcode 17 and invoke the current pane generation's existing recovery hook.

Tests also reuse a multiplex stream ID and detach/reattach the same renderer handle before releasing held rejections; neither stale failure can recover the replacement stream or pane lifecycle.

Verification

Integrated deterministic gate:

pnpm exec vitest run --config config/vitest.config.ts \
  src/main/runtime/rpc/terminal-multiplex.test.ts \
  src/renderer/src/runtime/runtime-terminal-stream.test.ts \
  src/renderer/src/runtime/remote-runtime-terminal-parse-backpressure.test.ts \
  src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts \
  --reporter=dot

Result after rebasing onto 15ef69a814: 4 files, 197 tests passed.

Additional checks:

  • pnpm run typecheck — passed
  • changed-file oxlint — passed
  • changed-file oxfmt --check — passed
  • pnpm run check:reliability-gates — passed, 67 gates

Independent mutation evidence:

  1. Disable the host multiplex emitter: focused host oracle failed 1/1 because opcode 17 disappeared.
  2. Disable the renderer opcode decoder callback: focused pane oracle failed 1/1 because recovery was not invoked.
  3. Disable the pane-generation recovery callback: focused pane oracle failed 1/1.
  4. Disable rejected terminal.send fallback recovery: focused fallback oracle failed 1/1.

Each mutation was restored by the exact inverse edit; its focused oracle returned green before final validation.

Deliberate gaps

  • No live headed paired-Orca journey was collected for an injected host write rejection.
  • No live headless orca serve journey was collected.
  • Mixed installed-release behavior is proven at the wire-contract seam, not with packaged old/new binaries.
  • Linux, Windows, mobile, SSH, and WSL live runs were not collected. The change is transport-generic and does not alter provider routing.
  • Dead PTY records that remain incorrectly connected: true are still tracked separately in STA-2896; this PR makes rejected writes recoverable but does not rewrite graph-sync liveness.

Fixes STA-2830.

@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Terminal streaming now negotiates writeUnavailable support and defines a WriteUnavailable stream opcode. Runtime handlers classify terminal input as delivered, rejected, or failed, then notify compatible active streams for rejected writes. Renderer multiplexers and PTY transports forward these notifications while ignoring stale lifecycle results. Remote PTY rejection triggers pane recovery without local liveness probing. Tests cover compatible and legacy clients, replacement streams, fallback sends, liveness routing, pane remounting, and the reliability gate.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description has strong summary and verification details, but it omits the required Screenshots, AI Review Report, Security Audit, and Notes sections. Add all template sections, state “No visual change” if applicable, and summarize the AI cross-platform review, security audit, and platform-specific notes.
Docstring Coverage ⚠️ Warning Docstring coverage is 28.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the terminal fix and the specific issue of recovering rejected paired-runtime input.
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.
✨ 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.

… remount (STA-2830)

The WriteUnavailable signal reached the renderer and then died. `onWriteUnavailable`
routed to `requestTerminalPaneRecovery` with `requireAuthoritativeLiveness: true`,
which probes `pty:hasPty`. For a paired pane the id is `remote:<env>@@<handle>`:
`ptyOwnership` never holds it and `parseAppSshPtyId` ignores it, so the lookup
falls through to the local provider, whose "not in my table" came back as an
authoritative `false`. Recovery returned early and no remount ever happened.

Two fixes, both about not inventing evidence:

- `pty:hasPty` now returns null for a `remote:` id instead of routing it to the
  local provider, mirroring the guard `pty:kill` already has. Main cannot know
  another host's PTY state, so it says so.
- A host rejection now takes a distinct recovery reason, `input-rejected-by-host`,
  that consults no local probe. The probe is not made to lie: the frame itself is
  the evidence, it came from the process that owns the PTY over a live connection,
  and the remount preserves the session rather than destroying it. Local ids keep
  the probe, where a `false` really does mean the shell died.

Tests: a cross-boundary contract runs the real dispatcher, multiplexer, transport
and pty-connection together and requires the remount for every answer the probe
can give; an un-negotiated legacy binary subscriber must never receive opcode 17.
@Jinwoo-H

Jinwoo-H commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

The signal was delivered, then discarded

Independent review found that this PR's headline benefit was inert in production, and it reproduces: the WriteUnavailable opcode reached the renderer correctly, and then the recovery it fed never ran for the exact panes it was built for.

onWriteUnavailable routed into requestTerminalPaneRecovery with requireAuthoritativeLiveness: true, which first probes window.api.pty.hasPty. For a paired pane the id is remote:<env>@@<handle>. In src/main/ipc/pty.ts, ptyOwnership never holds that id and parseAppSshPtyId requires an ssh: prefix and returns null, so getProviderForPty falls through to the local provider, whose hasPty is ptyProcesses.has(id). The local registry has never heard of another host's PTY, so it answered a confident false — and requestTerminalPaneRecovery reads false as "the shell died, the dead-session reconcile owns this" and returns early. remountTerminalTabForRecovery was never called.

pty:kill already guards against exactly this routing hazard (args.id.startsWith('remote:') → throw, with the comment "unowned PTY routing could target the local provider"). pty:hasPty simply lacked the same protection.

What now carries it through

Two changes, both about not inventing evidence.

1. pty:hasPty stops fabricating an answer. It now returns null for a remote: id without consulting any provider, mirroring the guard pty:kill has. Main cannot know another host's PTY state, so it says unknown instead of manufacturing a dead. (The renderer's serve/web preload already answered null for everything; this makes the Electron path consistent with it.)

2. A host rejection takes a recovery path that needs no local liveness proof. New reason input-rejected-by-host, distinct from input-undeliverable, which skips the probe entirely.

On the governing rule — unprovable liveness must never authorize destroying a session, and an ambiguous answer must never be read as proof — to be explicit about which option I took:

  • I did not make the probe return a confident true where liveness is unknown. I made it answer less: null instead of a fabricated false. Nothing was taught to lie.
  • The recovery is authorized by a positive fact, not by an inference from silence: a WriteUnavailable frame is the process that owns the PTY stating it refused this specific write, delivered over a live, capability-negotiated connection. That is not a liveness claim at all, and it is not the ambiguous case the rule protects.
  • Nothing is destroyed. remountTerminalTabForRecovery bumps the tab generation; detach() preserves the PTY and the remote transport's disconnect() does not call terminal.close (only the create-retry cleanup path does). The remount rebuilds the renderer over the session it already had.
  • The requireAuthoritativeLiveness gate's stated purpose is to stop a disconnected remote pane from remount-churning on every cooldown window while the user types. A WriteUnavailable frame cannot arrive from a disconnected pane, so that gate was protecting against a scenario this signal excludes by construction.

Local (daemon / app-SSH) ids keep the probe: there main's registry genuinely can answer, and a false really does mean the shell died, where remounting would race the dead-session reconcile. The split is on whether main can speak for the id, not on convenience. Budget, cooldown, and the input quarantine all still apply unchanged.

Proving the whole chain

Every pre-existing test for this signal stopped at the transport callback, which is exactly why the dead last hop went unnoticed — and an in-renderer test could not have caught it, because they all mock window.api.pty.hasPty to return true.

New: tests/e2e/paired-runtime-rejected-input-remount.unit.test.ts bridges the real terminal.multiplex dispatcher to the real renderer multiplexer, remote transport, and pty-connection over one subscription. It types into the pane, the runtime refuses the write, and it requires both hops: the host emits opcode 17, and remountTerminalTabForRecovery is called. It is parametrized over every answer main can produce for a remote: id — fabricated dead, unknown, thrown probe — so the conclusion does not depend on which one occurs.

Red/green: 3 failed → 3 passed. On the delivery-only implementation the first assertion (host frame arrives) passed and the remount assertion failed in all three cases; after the fix all three pass. It lives under tests/e2e/*.unit.test.ts because that is this repo's sanctioned home for cross-boundary tests — tsconfig.tc.web.json will not let a file under src/renderer import main modules.

The surviving mutant

Deleting the legacy-binary capability gate at src/main/runtime/rpc/methods/terminal.ts left the suite fully green. That gate is the one protection for the mobile transport, whose vendored opcode enum knows only 1-6 and 12.

Added: an un-negotiated legacy binary subscriber (terminalBinaryStream: 1 and nothing else) must never receive opcode 17. It shares a runtime with a capable subscriber that is driven second, so the capable client's frame proves the rejection had already been processed for both — the silence is a decision, not a race.

Verified by deleting the gate: 1 failed / 62 passed. Restored by re-applying the edit (no git checkout), re-verified green.

Mutation results for every production change

Mutation Result
Delete the legacy-binary capability gate 1 failed / 62 passed
Remove the remote: guard from pty:hasPty red, received false — the fabricated dead
Revert the recovery reason routing in pty-connection 3 failed / 0 passed
Make terminal-pane-recovery probe for input-rejected-by-host too 3 failed / 0 passed

Each was restored by re-applying the edit and re-verified green.

Gate title

terminal-input.remote-write-rejection-recovery was titled "Rejected paired-runtime terminal input reaches pane recovery", which overstated what was proven — no test carried the signal into a remount. Now that one does, the entry is retitled "Rejected paired-runtime terminal input remounts the pane" and its invariant, oracle, commands, test files, assertion refs, evidence run, and red/green evidence are updated to match, including the new pty:hasPty liveness-routing surface. The superseded evidence run was dropped because its command is no longer a gate command; the replacement run is a superset.

Verification

  • Gate command set: 678 passed / 0 failed
  • src/renderer/src/components/terminal-pane/, src/main/daemon/, and fix(terminal): attach never-activated daemon sessions on remote subscribe and provider-read fallback #12589's terminal-subscriber-driven-daemon-attach.test.ts: 4405 passed / 3 skipped
  • src/main/ipc/, src/main/runtime/, tests/e2e/: 6472 passed / 16 skipped
  • pnpm run typecheck (node, cli, web): clean
  • oxlint (whole repo): clean
  • oxfmt --check: clean on every touched file (7 pre-existing unrelated offenders in tests/ untouched)
  • pnpm run check:reliability-gates: passed for 67 gates

@Jinwoo-H
Jinwoo-H merged commit d15939c into main Aug 5, 2026
43 checks passed

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

🧹 Nitpick comments (1)
tests/e2e/paired-runtime-rejected-input-remount.unit.test.ts (1)

425-427: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Move the per-test teardown into afterEach.

binding.dispose() and _resetTerminalPaneRecoveryForTests() run only on the success path. If any vi.waitFor above times out, the binding stays live. Its timers and store subscribers then keep running against the previous module instance after afterEach deletes globalThis.window, which can turn one failing case into cascading failures or unhandled errors in the remaining parametrized cases.

Register the teardown as soon as the binding exists.

♻️ Proposed teardown that survives a failed assertion
   afterEach(() => {
+    cleanup?.()
+    cleanup = null
     delete (globalThis as { window?: unknown }).window
   })
+let cleanup: (() => void) | null = null
       const binding = connectPanePty(pane as never, createManager() as never, deps as never)
+      cleanup = () => {
+        binding.dispose()
+        _resetTerminalPaneRecoveryForTests()
+      }
       await vi.waitFor(() => {
         expect(deps.paneTransportsRef.current.get(1)?.getPtyId()).toBe(REMOTE_PTY_ID)
       })
-      binding.dispose()
-      _resetTerminalPaneRecoveryForTests()
     })

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 24fcd206-56c9-4805-8ce0-80115d3dabe9

📥 Commits

Reviewing files that changed from the base of the PR and between 6ef8990 and d8734fa.

📒 Files selected for processing (8)
  • config/reliability-gates.jsonc
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/runtime/rpc/terminal-multiplex.test.ts
  • src/renderer/src/components/terminal-pane/pty-connection.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-recovery.test.ts
  • src/renderer/src/components/terminal-pane/terminal-pane-recovery.ts
  • tests/e2e/paired-runtime-rejected-input-remount.unit.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/main/runtime/rpc/terminal-multiplex.test.ts
  • config/reliability-gates.jsonc

enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…lyai#12675)

With a desktop client paired to a remote Orca runtime, terminal panes could report connected, writable, and `terminal.send` returning accepted — yet keystrokes never reached the agent. No error, no banner, no recovery; input silently vanished.

The ticket was really two bugs. The attach half was already fixed by stablyai#12589 (subscriber-driven daemon attach), confirmed by reproducing against current main. This fixes the remaining half: a write the host refuses had no way to tell anyone.

A capability-negotiated `WriteUnavailable` opcode carries that refusal back to the client, where it feeds the pane's pre-existing recovery hook. Capability gating matters because decoders reject unknown opcodes on desktop — and, worse, silently drop them on mobile — so the signal is negotiated in the subscribe handshake. Verified per direction: an old host strips the unknown Subscribe key, an old client omits it so the host never emits, and capability cannot be inherited across resubscribe.

Independent review then found the signal was being delivered and discarded: recovery demanded an authoritative liveness answer, and `pty:hasPty` had no `remote:` guard, so a paired pane's id fell through to the LOCAL provider, which returned false, and recovery bailed before remounting. Every test stopped at the transport boundary, so all of them passed while the pane stayed just as stuck. `pty:kill` already had exactly that guard.

The fix makes main answer LESS rather than claim more: `pty:hasPty` now returns unknown for a `remote:` id instead of a fabricated false, because main cannot speak for another host's PTY. The remount is then authorized by positive evidence — the process that owns the PTY stating it refused this specific write over a live negotiated connection — not by inference from silence. Local and app-SSH ids keep the probe, where a false genuinely means the shell died. Nothing is destroyed on this path; the remount rebuilds the renderer over the session it already had.

An end-to-end test now carries a rejected write from the host through to an actual remount, which no prior test did. A surviving mutant was also killed: the legacy-binary capability gate could previously be deleted with nothing turning red.

The reliability gate stays experimental — live paired journeys and mixed installed-release evidence remain uncollected. Fixes STA-2830.
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