Repository navigation
fix(remote-runtime): materialize the host surface when reconnecting a terminal pane - #11542
Conversation
📝 WalkthroughWalkthroughThe remote PTY transport centralizes host-surface activation and alternates reconnect recovery between activation and bounded inventory listing. Tests cover PTY-death recovery, stale and transient activation failures, replacement-handle rebinding, and bounded polling. E2E controls force terminal errors and hold stream-end events. A new E2E journey validates replacement materialization for paired hosts. Reliability-gate configuration registers the build and E2E validation. 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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.
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts (1)
513-543: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winRetry activation after an inconclusive missing-surface check. A classified activation error sets
surfaceActivated = true, permanently selectingsession.tabs.list. If that list still returns the matchingpending-handlesurface, the loop never activates again, so the PTY cannot be re-materialized before timeout.
src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts#L513-L543: poll once to establish absence after a missing activation error, but retry activation when inventory confirms the requested surface still exists without a ready handle.src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts#L1490-L1587: add the missing-error → pending-inventory → retried-activation sequence.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 8a4a7a5f-ce5a-45f7-ae8f-2e5d095ef1ff
📥 Commits
Reviewing files that changed from the base of the PR and between 9eede00 and 096bc24d386970a2ec4b07128c1ba81aede0b5f1.
📒 Files selected for processing (2)
src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
| @@ -508,6 +536,11 @@ export function createRemoteRuntimePtyTransport( | |||
| } catch (error) { | |||
| // Why: the inventory can race the reconnect that invalidated the handle; unknown liveness must not retire the pane. | |||
| lastListError = error | |||
| // Why: a missing surface must be proven by an inventory snapshot, not by a | |||
| // failed activate; transient activate failures retry the materialize. | |||
| if (isMissingHostSessionSurfaceError(error)) { | |||
| surfaceActivated = true | |||
There was a problem hiding this comment.
lastListError name now covers activate errors too
lastListError is also set when the first activate call throws (line 538), including the tab_not_found / terminal_not_found path that sets surfaceActivated = true. If the budget expires right after that catch block, finishWithUnknownLiveness() logs "host session inventory unavailable during reconnect: tab_not_found". The message accurately describes "something went wrong during reconnect" but the framing ("inventory unavailable") is misleading when the actual failure was an activate RPC, not a list. Renaming to lastRequestError (or similar) would keep the log statement honest without changing any behavior.
Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!
Greptile SummaryThis PR fixes a reconnect deadlock where a remote-runtime terminal pane with a dead host PTY could never recover —
Confidence Score: 5/5Safe to merge — the change is narrowly scoped to the reconnect polling loop and preserves all existing retirement and unknown-liveness contracts. The fix replaces one RPC call (the first Files Needing Attention: No files require special attention; both changed files are well-covered by the updated and new test cases.
|
| Filename | Overview |
|---|---|
| src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts | Adds activateHostSessionSurface and isMissingHostSessionSurfaceError helpers; rewires waitForResubscribeHostSessionHandle to call session.tabs.activate once before falling back to inventory polling, with correct retire/unknown-liveness contract preserved. |
| src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts | Adds a regression test for the pending-handle/terminal: null case, verifying the activate params, rebind callback, and no-retire contract. Updates the first-list-timeout bound from toBe(15_000) to (14_000, 15_000] to account for the one-backoff offset introduced by the leading activate. |
Reviews (1): Last reviewed commit: "fix(remote-runtime): materialize the hos..." | Re-trigger Greptile
… pane A remote-runtime pane whose host-side PTY died (host app restart/update, or a workspace the host window never opened) could never reconnect: the host keeps publishing the surface as `pending-handle`/`terminal: null`, and only `session.tabs.activate` materializes a PTY for that tab/leaf identity. The reconnect path polled `session.tabs.list` for 15s, gave up, and the 60s recovery deadline flipped the pane to "Remote runtime disconnected" — where the Reconnect button re-ran the same list-only polling. The only recovery was a human opening that project on the host. The reconnect now opens with the same activate the first attach uses, so the host re-materializes the PTY for the exact tab/leaf. A missing surface must still be proven by an inventory snapshot, so `tab_not_found`/`terminal_not_found` from the activate does not retire the pane, and transient activate failures retry the materialize inside the existing budget. Fixes stablyai#11541
096bc24 to
a8d08ce
Compare
|
Note GitHub couldn't provide a complete incremental comparison for this pull request, so CodeRabbit is performing a full review instead. This review may take a little longer. |
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (6)
src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts (1)
1978-2077: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a companion test for a non-missing activation error.
This test covers only the
tab_not_foundbranch. No test covers an activation failure whose message is nottab_not_foundorterminal_not_found, for examplemethod_not_foundfrom a host runtime withoutsession.tabs.activate. That branch keepsnextRequestat'activate'inremote-runtime-pty-transport.tsand never issuessession.tabs.list, which is the regression described in the comment onremote-runtime-pty-transport.tsLine 719-731.Add a case where the first activation rejects with
method_not_foundand inventory publishes a ready replacement handle. Assert that asession.tabs.listcall is issued and that the pane rebinds to the replacement.src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts (1)
565-571: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueDocument why the hold guard sits after
recordInbound().The guard placement is load-bearing. It runs after
stream.watchdog.recordInbound()on Line 564, so a held stream keeps its inbound activity credit and the watchdog does not triggerrecoverStalledStream. That preserves the intended fault: a stream that looks live while its host PTY is gone.A future refactor could hoist this guard above Line 564 and silently change the watchdog outcome. Add a one-line
// Why:comment, matching the existing convention in this file.♻️ Proposed comment
stream.watchdog.recordInbound() + // Why: held streams must keep inbound credit so the watchdog does not + // convert a suppressed end into stall recovery. if ( event.type === 'end' && e2eConfig.exposeStore && e2eHeldRemoteEndTerminals.has(stream.terminal) ) { return }As per coding guidelines: "Comments must be concise, non-obvious, and brief—prefer one line."
Source: Coding guidelines
tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts (4)
20-43: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the unused
processedInputPathplumbing, or assert on it.The fixture writes every processed input line to
processedInputPaththroughappendFileSync, but no assertion ever reads that file. The test verifies the replacement PTY throughterminal.readon Line 244 and through rendered terminal content on Line 250.The path is threaded through five places for no effect: the declaration on Line 22, the fixture argument on Line 28, the
appendFileSynccall on Line 37, the command build on Line 56, and the truncation on Line 123.Either drop the file entirely, or add an assertion that the replacement PTY received the marker on its stdin. The second option is stronger, because it proves the host wired stdin to the new PTY rather than only echoing to the output buffer.
89-116: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueCapture the worktree id inside the poll instead of re-evaluating.
Lines 93-100 and 104-111 run the same
page.evaluateexpression twice. The poll already computes the id, so the second evaluation is redundant. It also re-reads the worktree list after the poll succeeded.
runMaterializationJourneyalready uses the capture-inside-poll pattern forreplacementHandleon Lines 200-220. Match it here.♻️ Proposed refactor
async function waitForClientWorktree(page: Page, expectedId?: string): Promise<string> { + let worktreeId: string | null = null await expect .poll( - () => - page.evaluate( + async () => { + worktreeId = await page.evaluate( (id) => window.__store ?.getState() .allWorktrees() .find((worktree) => !id || worktree.id === id)?.id ?? null, expectedId - ), + ) + return worktreeId + }, { timeout: 30_000 } ) .not.toBeNull() - const worktreeId = await page.evaluate( - (id) => - window.__store - ?.getState() - .allWorktrees() - .find((worktree) => !id || worktree.id === id)?.id ?? null, - expectedId - ) if (!worktreeId) { throw new Error('Paired client did not receive the host workspace') } return worktreeId }
225-264: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTwo small robustness notes on the I/O check and teardown.
First, Line 228 sends
echo ${marker}\r, but the fixture is not a shell. It echoesLIVE:${input}for each received line, so the host writes backLIVE:echo MATERIALIZED_<ts>. The assertions still pass because the returned line containsmarker. Theechoprefix implies shell execution that does not happen. Send the baremarkerso the intent matches the fixture.Second, Line 264 closes the host tab as the final statement. If any assertion between Lines 179 and 263 fails,
terminal.closeTabnever runs and the host keeps the terminal. The per-testfinallyblocks dispose the client and the headless host, so this does not leak across tests. Wrapping the journey body intry/finallywould still make failures cleaner for the shared headed host.
158-197: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick winCentralize the
__remoteTerminalMultiplexAckGatetype in this spec.Lines 159-163 and 183-190 duplicate partial gate method shapes as inline window intersections. Declare one module-scope union for the needed methods, or export the multiplexer gateway type and import it here, so gate changes fail typecheck in this test rather than becoming stale runtime checks.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: bb9f269c-9c91-44d3-8238-75683ee0cbdd
📒 Files selected for processing (5)
config/reliability-gates.jsoncsrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.tssrc/renderer/src/runtime/remote-runtime-terminal-multiplexer.tstests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts
| if (request === 'list' && retryActivationAfterInventory) { | ||
| nextRequest = 'activate' | ||
| retryActivationAfterInventory = false | ||
| } | ||
| } catch (error) { | ||
| // Why: the inventory can race the reconnect that invalidated the handle; unknown liveness must not retire the pane. | ||
| lastListError = error | ||
| lastRequestError = error | ||
| // Why: activation absence is provisional until inventory confirms it. | ||
| if (request === 'activate' && isMissingHostSessionSurfaceError(error)) { | ||
| nextRequest = 'list' | ||
| retryActivationAfterInventory = true | ||
| } | ||
| } |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Find host-side registration and any capability gating for session.tabs.activate.
set -uo pipefail
echo '--- session.tabs.activate references ---'
rg -n --glob '!**/node_modules/**' "session\.tabs\.activate" .
echo '--- method registration / dispatch tables mentioning tabs.activate ---'
rg -n -C 4 --glob '!**/node_modules/**' "'tabs\.activate'|\"tabs\.activate\"|tabs\.activate:" .
echo '--- existing capability constants for session tab methods ---'
rg -n -C 3 --glob '!**/node_modules/**' 'RUNTIME_CAPABILITY' . | rg -i -C 3 'tab|session|activate'
echo '--- how method_not_found is handled on reconnect paths ---'
rg -n -C 4 --glob '!**/node_modules/**' "method_not_found" src/renderer/src/components/terminal-pane src/renderer/src/runtimeRepository: stablyai/orca
Length of output: 50369
🏁 Script executed:
#!/bin/bash
set -uo pipefail
FILE="src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts"
echo "=== file size ==="
wc -l "$FILE"
echo "=== imports and constants around activate/list ==="
sed -n '1,90p' "$FILE"
echo "=== activate/list handler around success and catch ==="
sed -n '680,745p' "$FILE"
echo "=== missing-surface helpers ==="
rg -n -C 3 "isMissingHostSessionSurfaceError|tab_not_found|terminal_not_found|method_not_found|resolvePaneUnavailable|HOST_SESSION_ATTACH_TIMEOUT_MS|HOST_SESSION_INVENTORY_BACKOFF" "$FILE"
echo "=== surrounding attach timeout / loop variables ==="
sed -n '700,760p' "$FILE"
echo "=== tests around activate errors/fallback ==="
sed -n '730,855p' src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts
sed -n '780,1085p' src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts
echo "=== session-tabs dispatch references ==="
sed -n '1,130p' src/main/runtime/rpc/methods/session-tabs.ts
sed -n '350,385p' src/main/runtime/runtime-rpc.tsRepository: stablyai/orca
Length of output: 35765
Route activation failures back to inventory polling.
Non-missing activation errors keep nextRequest = 'activate', so the recovery loop can burn the attach timeout retrying session.tabs.activate without issuing session.tabs.list. Use the missing-surface case only for re-arming activation.
🐛 Proposed fix to keep inventory polling reachable
} catch (error) {
// Why: the inventory can race the reconnect that invalidated the handle; unknown liveness must not retire the pane.
lastRequestError = error
- // Why: activation absence is provisional until inventory confirms it.
- if (request === 'activate' && isMissingHostSessionSurfaceError(error)) {
- nextRequest = 'list'
- retryActivationAfterInventory = true
+ if (request === 'activate') {
+ // Why: a failed activation must not starve inventory polling; absence is provisional until inventory confirms it.
+ nextRequest = 'list'
+ retryActivationAfterInventory = isMissingHostSessionSurfaceError(error)
}
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (request === 'list' && retryActivationAfterInventory) { | |
| nextRequest = 'activate' | |
| retryActivationAfterInventory = false | |
| } | |
| } catch (error) { | |
| // Why: the inventory can race the reconnect that invalidated the handle; unknown liveness must not retire the pane. | |
| lastListError = error | |
| lastRequestError = error | |
| // Why: activation absence is provisional until inventory confirms it. | |
| if (request === 'activate' && isMissingHostSessionSurfaceError(error)) { | |
| nextRequest = 'list' | |
| retryActivationAfterInventory = true | |
| } | |
| } | |
| if (request === 'list' && retryActivationAfterInventory) { | |
| nextRequest = 'activate' | |
| retryActivationAfterInventory = false | |
| } | |
| } catch (error) { | |
| // Why: the inventory can race the reconnect that invalidated the handle; unknown liveness must not retire the pane. | |
| lastRequestError = error | |
| if (request === 'activate') { | |
| // Why: a failed activation must not starve inventory polling; absence is provisional until inventory confirms it. | |
| nextRequest = 'list' | |
| retryActivationAfterInventory = isMissingHostSessionSurfaceError(error) | |
| } | |
| } |
| const host = await launchHeadlessPairedRuntimeHost() | ||
| await host.client.call('repo.add', { path: testRepoPath, kind: 'folder' }) | ||
| const client = await launchPairedElectronClient( | ||
| host.offer, | ||
| testInfo, | ||
| 'headless-folder-materialization-client' | ||
| ).catch(async (error) => { | ||
| await host.dispose() | ||
| throw error | ||
| }) |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Dispose the headless host if repo.add fails.
Line 294 launches the headless host. Line 295 then calls repo.add outside any try and outside the .catch guard on Lines 300-303. If repo.add throws or times out, host.dispose() never runs.
Per tests/e2e/helpers/headless-paired-runtime-host.ts Lines 186-247, dispose closes the Electron app, runs cleanupE2EDaemons, and removes the temp userDataDir. Skipping it leaves a live Electron process, a running daemon, and a temp directory behind. That host holds a single-instance lock and a serve port, so a later test that launches its own headless host can fail. In serial mode the failure propagates to the rest of the suite.
The client launch on Lines 296-303 already guards against exactly this leak. Extend the same protection to repo.add.
🐛 Proposed fix
const host = await launchHeadlessPairedRuntimeHost()
- await host.client.call('repo.add', { path: testRepoPath, kind: 'folder' })
- const client = await launchPairedElectronClient(
- host.offer,
- testInfo,
- 'headless-folder-materialization-client'
- ).catch(async (error) => {
- await host.dispose()
- throw error
- })
try {
+ await host.client.call('repo.add', { path: testRepoPath, kind: 'folder' })
+ const client = await launchPairedElectronClient(
+ host.offer,
+ testInfo,
+ 'headless-folder-materialization-client'
+ )
+ try {
await showClient(client.app, client.page)
await runMaterializationJourney(
client.page,
client.environmentId,
await waitForClientWorktree(client.page)
)
expect(await client.getDirectSshAttemptTargetIds()).toEqual([])
+ } finally {
+ await client.dispose()
+ }
} finally {
- await client.dispose()
await host.dispose()
}
Jinwoo-H
left a comment
There was a problem hiding this comment.
Thanks for adding the exact-leaf activation path and the paired-runtime coverage. I validated current head a8d08ce08a in an isolated worktree, but it is not safe to merge yet.
Blocking findings:
waitForResubscribeHostSessionHandledoes not re-activate when the first activation races host publication and returns the previous ready handle, then authoritative inventory later exposes the exactpending-handlesurface. The activation result selects list polling, and the list result only re-arms activation whenretryActivationAfterInventorywas set by a classified missing activation error. A deterministic test against the current head observedactivate, list, list, listinstead ofactivate, list, activate; the pane never obtained the replacement handle.- A non-missing activation failure such as
method_not_foundnever falls back to authoritative inventory. A deterministic old-host test observedactivate, activate, activateinstead ofactivate, list, so a ready replacement already visible through inventory is ignored. This also means transient/non-classified activation errors do not satisfy the required inventory safety boundary. - The changed-spec E2E gate does not execute the new tests. Both tests are tagged
@headful, while changed-spec CI always runs theelectron-headlessproject, whosegrepInvertexcludes them. CI therefore fails withError: No tests found.The reliability-gate command separately nameselectron-headful, so the durable command and required changed-spec job disagree.
Validation evidence:
- Required transport + recovery-state suites at the PR head: 121/121 passed.
- Full typecheck: passed.
- Copied STA-3002 oracle: the unmodified test stops at its pre-fix-only assertion that reconnect must first perform more than one list poll (
0observed). Removing only that obsolete intermediate assertion leaves the actual acceptance oracle unchanged; activation, exact handle rebind, and restored input/output then pass 1/1. - Added deterministic adversarial tests: current head fails 2/2 as described above. A local candidate that makes activation immediately inventory-confirmed and re-arms activation only when exact inventory is pending passes the full affected suites 123/123, typecheck, formatting, and STA-3002 1/1; I did not push it because the live paired journey still failed.
- Real paired-runtime validation after locally removing the selector mismatch: Playwright selected both headed-host and headless-folder-host topologies, but the headed-host journey failed to materialize a replacement (1 failed, 1 did not run). Adding an authoritative
pending-handlepublication barrier did not make it pass, so the E2E fault/recovery handoff also needs correction before this can be considered proven. - Current GitHub checks: 42 passed, 1 failed (
e2e / changed e2e specs), with the failure being the selector issue above.
Please update the state machine so activation never proves absence, authoritative inventory alone can retire, non-missing activation failures inventory-fallback, and an exact pending inventory re-arms activation inside the existing bounded window. Then repair the changed-spec selector and make both paired-runtime topologies genuinely pass. I will re-review promptly.
…ecovery Reconnect activation could still strand a pane two ways. A first activation that raced host publication returned the pre-restart handle, and the exact inventory that followed saw only a pending handle — but the loop then list-polled for the rest of its window instead of activating again. An activation that failed for any non-missing reason (an older host without session.tabs.activate, a transport error) kept retrying activation with no inventory fallback at all. Alternate the two requests instead: an activation response never proves absence, so inventory always follows it, and inventory that still publishes the surface without a ready handle re-activates. Only inventory may retire the pane. Materializing the surface also had to work on the host. Activating a parked pane retired its owner, signalled the PTY exit, then read "nothing left to retire" in persistence as a competing owner and threw terminal_pane_owner_changed — destroying the pane it was asked to rebuild, with no fresh spawn. An already-absent persisted binding is a completed retirement, not a conflict. The paired E2E tags were @headful, which the changed-spec CI lane (electron-headless) greps out, so CI reported "No tests found". Neither test needs pointer capture; drop the tags and point the gate at the same project.
|
Pushed 1. Stale-ready activation raceThe first recovery activation can race host publication and answer with the pre-restart handle. The exact inventory that follows then sees only a pending handle — but the loop kept list-polling for the rest of its window and never activated again, so the surface was never materialized. Observed on the previous head: 2. Non-missing activation failure had no inventory fallbackActivation was only retried through inventory after a classified missing error. Any other failure — Observed on the previous head: Both are fixed by alternating the two requests inside the existing bounded backoff window. An activation response is never absence proof, so inventory always follows it; inventory that still publishes the surface without a ready handle re-activates. Retirement is now reachable only from an inventory response, which tightens the previous behavior where a successful activation response missing the surface could retire the pane. Two regression tests assert the exact call sequences, not counts:
Both also assert the pane is neither retired nor errored ( 3. Host-side: activation destroyed the pane it was asked to rebuildThe paired E2E could not pass, and it was not a harness problem. With no fault injection at all, a single Traced to An already-absent persisted binding is a completed retirement, not a conflict. The genuine owner-change guard (a different persisted ptyId/incarnation) and the unknown-liveness guard ( Covered by 4. CI:
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts (1)
1983-2073: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winConsider extracting a shared helper for the reconnect-recovery test setup.
Each of these two tests, and the two sibling tests added in the same PR (per the line-range summary at 1886-1981 and 2159-2258), repeats the same setup: create the transport, attach, wait for the initial subscribe, clear
runtimeCall, build a snapshot payload, installruntimeCall.mockImplementation, firesubscriptionCallbacks.onResponsewithterminal_handle_stale, advance fake timers, assert the method sequence, assert the resulting subscribe payload and rebind, assert no exit/error callback, thendestroy().Extract a small helper that takes only the varying parts (the activation/list mock behavior and the expected method sequence) to reduce this duplication across the four new tests.
Also applies to: 2075-2157
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 446bc227-ef00-4031-bc37-d89bea242638
📒 Files selected for processing (6)
config/reliability-gates.jsoncsrc/main/ipc/pty.test.tssrc/main/ipc/pty.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.tssrc/renderer/src/components/terminal-pane/remote-runtime-pty-transport.tstests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
Jinwoo-H
left a comment
There was a problem hiding this comment.
Approving on the strength of the reconnect state machine, the host materialization fix, and green CI (43 checks; e2e / changed e2e specs now genuinely selects and runs the spec — headed paired host ✓ 21.5s — instead of reporting "No tests found").
Not merging: the headless folder-host topology is still unproven. It is marked test.fixme because terminal.stopExact cannot park a PTY on an orca serve host (terminal_exact_stop_failed — stopAndWait's keep-history verification window expires before the parked PTY is observed gone), so the fault can't be set up and the reconnect path is never reached. That precondition fails identically on this PR's base, so it is a pre-existing exact-stop defect rather than something this change introduced, and it deserves its own issue. The recovery behavior itself was confirmed by hand in that topology.
Leaving the merge call to a maintainer who can decide whether shipping without headless paired coverage is acceptable given the defect is pre-existing.
…face and dead-ending the pane (#12650) When a remote runtime went unreachable (laptop sleep, Tailscale drop), the UI filled with dozens of repeated timeout errors until it was nearly unusable, and the affected terminal then accepted no input after connectivity returned — leaving "close the session and resume it in a new one" as the only escape. Four causes, three of which were still live: - Errors accumulated into one ever-growing surface with no de-duplication or cap. - Queue-overload rejections lose their structured error code crossing the IPC boundary, so they were never classified as recoverable and surfaced raw. - A transient failure misclassified as fatal called `recovery.cancel()`, setting the pane to an idle phase — which unmounts the Reconnect banner and makes manual retry, online and resume triggers all no-ops. A true dead end, and the reason recreating the session was the only way out. - Dismissing an error cleared the surface but not the dedup memory, so an identical fatal error recurring in the same outage was suppressed forever while the pane looked healthy; dedup also compared single lines, so multi-line errors never matched and stacked without bound. The ordinary reconnect loop was already fixed in v1.4.150/160 — bounded backoff, a Reconnect banner and auto-recovery already ship. This fixes what remained. Note the fix routes fatal resubscribe failures back through the shared terminal error handler: bypassing it had silently dropped stale-handle re-resolution, terminal-gone retirement, SSH-expired recovery and oversized-snapshot suppression — a stuck-pane regression inside the stuck-pane fix, caught in review and covered by 6 dedicated tests. Verified: reproductions red on main before the fix; after rebasing onto #11542, reverting the dead-end fix still turns its test red. Follow-up STA-3456 tracks preserving typed error codes across the IPC boundary so classification stops matching message text.
…ition (#12671) `retireMobileSessionSurfacesForPty` called `getWorkspaceSession()` / `setWorkspaceSession()` with no host id, so every retirement wrote to the LOCAL partition — while its sibling `retirePersistedStablePaneOwner` correctly scopes to the SSH execution host. For an SSH pane exiting cleanly this is not a harmless misdirected write. Measured on main: the write went to the local partition instead of `ssh:conn-1`; the SSH partition still held the dead PTY binding; the local partition gained a bogus topology revision for an SSH repo; and the published tab list contained a RESURRECTED leaf hydrated back from the stale SSH partition. The wrong-partition write was accepted — a tombstone recorded and the revision advanced for a surface that could not be found. Found during independent review of #11542; pre-existing, not caused by it. Fixes STA-3463.
…agent rows (#12664) After a laptop sleep against a remote machine, the sidebar agent count came back lower than the number of open terminal tabs — rows vanished for panes whose tab and host process were both still alive. The client mirror deletes a mirrored pane's agent status whenever the host snapshot carries none for it, unless the client's own byte-derived entry is still fresh. But for a remote pane the client is the ONLY writer of that status, and a laptop closed past the 30-minute staleness boundary makes every such entry stale by definition — so the first snapshot after wake erased the sidebar row of every pane the client owned. Freshness was the wrong gate. It exists to arbitrate between two competing writers, but on the delete branch the host published nothing, so there was nothing to arbitrate and "my status is old" quietly became "delete this pane". The branch now gates on ownership: a pane this renderer claimed and wrote keeps its entry and decays to idle through the normal staleness boundary, exactly like a local pane. Teardown releases the claim, which is how the host takes the pane back. That reverses a contract #12641 pinned, so its test was updated in place with the reasoning inline rather than deleted — the old premise was that going stale hands the pane back to the host, which does not hold when the host has no value to hand back. The assertion is now stricter: the entry must be retained AND read as stale so consumers render it idle. This is the sidebar-count half of STA-3107. The blank-terminal half was fixed by #11542 and is proven so: reverting that fix in a six-pane harness makes exactly one of six panes fail to resubscribe while its siblings recover, matching the report. A remaining gap is documented in the PR: a pane the client never wrote status for stays host-authoritative and can still lose its row. Separating "the host has no opinion" from "the host proved there is no agent" needs the origin marker tracked as STA-3455.
The park guard refused every activation of a `worktree-sleep` pane, but opening the tab is the documented wake gesture for exactly those records (#11598) — and three of the four sleep topologies never clear the record, so the pane was stranded `pending-handle` forever. Carry the caller's intent explicitly instead of inferring it. `intent` is an additive optional field on `session.tabs.activate`; absent means user intent, so a client that predates it keeps today's behavior. Only an `automatic` activation consults the park guard. Intent is set honestly at every sender: mobile tab taps and the pending- terminal follow-up, the paired desktop/web tab click, and the renderer's pane-open attach are 'user'; the reconnect probe in `waitForResubscribeHostSessionHandle` (#11542) is 'automatic'. Also pin the host-partitioned sleeping-record lookup: the workspace-session test stub answered for any host id, so hardcoding 'local' left the suite green. It now answers for one partition, and three SSH reattach tests that silently relied on the loose stub were corrected to their real partition.
…3465) (#12672) `activateMobileSessionTab` gated only on `publicTab.status !== 'ready'`. A deliberately slept pane publishes as `pending-handle` indefinitely — indistinguishable at that call site from a pane awaiting reconnect — so the reconnect probe added by #11542 respawned it with a re-resolved agent launch, waking something the user had deliberately put to sleep. The first attempt refused activation for any pane with a `worktree-sleep` record, applied to every path. Independent review found that broke the documented wake gesture: opening the tab IS how those panes are meant to cold-restore (`wake-sleeping-agents-in-background.ts`: "Those panes cold-restore --resume when their own tab is opened"). A mobile tap sends the byte-identical call the reproduction test used, and in three of four topologies no wake clears the record first — so the tap became a permanent no-op with no feedback. This carries intent explicitly instead of inferring it. A new shared `TabActivationIntent` ('user' | 'automatic') rides the existing ActivateTab schema as an optional additive field; `isAutomaticTabActivation` returns true only for an explicit 'automatic', so an absent value is permissive BY CONSTRUCTION in one place — an older client that does not send it keeps today's behavior rather than silently losing its wake gesture. The field is required on the mobile helper's params, so no call site can be added without declaring who asked. Every user path (mobile tab switches, paired tab clicks, shortcuts, palette, the pane's own open) is labelled 'user'. The only automatic sender in the codebase is `waitForResubscribeHostSessionHandle`, the #11542 reconnect probe. Verified per topology: user activation materializes a parked pane under headless serve, a paired runtime client, a completed agent with restoreOnTabOpenOnly, and a running agent whose wake cleared the record. The automatic probe is refused without retiring the surface, and #11542's reconnect tests stay green. Also fixes a test fixture that made a real bug untestable: the store stub ignored the host id, so mutating the partition lookup to 'local' left the suite green. Correcting it exposed three existing SSH reattach tests that had been relying on that looseness — their workspace session sat in the local partition while their repo was SSH-hosted, a store production would never read. Production was always right; the tests described an impossible world. Fixes STA-3465.
… terminal pane (stablyai#11542) Reconnect could never recover a terminal pane whose host-side process was gone (host restarted, or the workspace was never opened there): recovery only polled the tab inventory, which can never create the surface it is waiting for, so Reconnect spun for ~60s and gave up permanently. Verified with a deterministic reproduction: on main the recovery path issues 51 inventory polls and zero activations across both an automatic online trigger and a manual Reconnect click; with this change the pane re-materializes, rebinds and accepts input. Review found and fixed three further defects beyond the original change: - an activation answered with a stale ready handle left the loop polling forever instead of re-activating; - a non-missing activation failure (e.g. an older host without the method) never fell back to inventory; - host-side, activating a parked surface permanently deleted the host tab, because an already-absent persisted binding was read as a competing owner *after* the destructive retirement had already run. Independent review confirmed by mutation testing that every production change is covered by a test that fails when it is reverted, that only an authoritative inventory can retire a pane, that the loop is bounded under every failure mode, and that the unknown-liveness guard (proven death required before retirement) is intact. Fixes STA-3002.
…face and dead-ending the pane (stablyai#12650) When a remote runtime went unreachable (laptop sleep, Tailscale drop), the UI filled with dozens of repeated timeout errors until it was nearly unusable, and the affected terminal then accepted no input after connectivity returned — leaving "close the session and resume it in a new one" as the only escape. Four causes, three of which were still live: - Errors accumulated into one ever-growing surface with no de-duplication or cap. - Queue-overload rejections lose their structured error code crossing the IPC boundary, so they were never classified as recoverable and surfaced raw. - A transient failure misclassified as fatal called `recovery.cancel()`, setting the pane to an idle phase — which unmounts the Reconnect banner and makes manual retry, online and resume triggers all no-ops. A true dead end, and the reason recreating the session was the only way out. - Dismissing an error cleared the surface but not the dedup memory, so an identical fatal error recurring in the same outage was suppressed forever while the pane looked healthy; dedup also compared single lines, so multi-line errors never matched and stacked without bound. The ordinary reconnect loop was already fixed in v1.4.150/160 — bounded backoff, a Reconnect banner and auto-recovery already ship. This fixes what remained. Note the fix routes fatal resubscribe failures back through the shared terminal error handler: bypassing it had silently dropped stale-handle re-resolution, terminal-gone retirement, SSH-expired recovery and oversized-snapshot suppression — a stuck-pane regression inside the stuck-pane fix, caught in review and covered by 6 dedicated tests. Verified: reproductions red on main before the fix; after rebasing onto stablyai#11542, reverting the dead-end fix still turns its test red. Follow-up STA-3456 tracks preserving typed error codes across the IPC boundary so classification stops matching message text.
…ition (stablyai#12671) `retireMobileSessionSurfacesForPty` called `getWorkspaceSession()` / `setWorkspaceSession()` with no host id, so every retirement wrote to the LOCAL partition — while its sibling `retirePersistedStablePaneOwner` correctly scopes to the SSH execution host. For an SSH pane exiting cleanly this is not a harmless misdirected write. Measured on main: the write went to the local partition instead of `ssh:conn-1`; the SSH partition still held the dead PTY binding; the local partition gained a bogus topology revision for an SSH repo; and the published tab list contained a RESURRECTED leaf hydrated back from the stale SSH partition. The wrong-partition write was accepted — a tombstone recorded and the revision advanced for a surface that could not be found. Found during independent review of stablyai#11542; pre-existing, not caused by it. Fixes STA-3463.
…agent rows (stablyai#12664) After a laptop sleep against a remote machine, the sidebar agent count came back lower than the number of open terminal tabs — rows vanished for panes whose tab and host process were both still alive. The client mirror deletes a mirrored pane's agent status whenever the host snapshot carries none for it, unless the client's own byte-derived entry is still fresh. But for a remote pane the client is the ONLY writer of that status, and a laptop closed past the 30-minute staleness boundary makes every such entry stale by definition — so the first snapshot after wake erased the sidebar row of every pane the client owned. Freshness was the wrong gate. It exists to arbitrate between two competing writers, but on the delete branch the host published nothing, so there was nothing to arbitrate and "my status is old" quietly became "delete this pane". The branch now gates on ownership: a pane this renderer claimed and wrote keeps its entry and decays to idle through the normal staleness boundary, exactly like a local pane. Teardown releases the claim, which is how the host takes the pane back. That reverses a contract stablyai#12641 pinned, so its test was updated in place with the reasoning inline rather than deleted — the old premise was that going stale hands the pane back to the host, which does not hold when the host has no value to hand back. The assertion is now stricter: the entry must be retained AND read as stale so consumers render it idle. This is the sidebar-count half of STA-3107. The blank-terminal half was fixed by stablyai#11542 and is proven so: reverting that fix in a six-pane harness makes exactly one of six panes fail to resubscribe while its siblings recover, matching the report. A remaining gap is documented in the PR: a pane the client never wrote status for stays host-authoritative and can still lose its row. Separating "the host has no opinion" from "the host proved there is no agent" needs the origin marker tracked as STA-3455.
…3465) (stablyai#12672) `activateMobileSessionTab` gated only on `publicTab.status !== 'ready'`. A deliberately slept pane publishes as `pending-handle` indefinitely — indistinguishable at that call site from a pane awaiting reconnect — so the reconnect probe added by stablyai#11542 respawned it with a re-resolved agent launch, waking something the user had deliberately put to sleep. The first attempt refused activation for any pane with a `worktree-sleep` record, applied to every path. Independent review found that broke the documented wake gesture: opening the tab IS how those panes are meant to cold-restore (`wake-sleeping-agents-in-background.ts`: "Those panes cold-restore --resume when their own tab is opened"). A mobile tap sends the byte-identical call the reproduction test used, and in three of four topologies no wake clears the record first — so the tap became a permanent no-op with no feedback. This carries intent explicitly instead of inferring it. A new shared `TabActivationIntent` ('user' | 'automatic') rides the existing ActivateTab schema as an optional additive field; `isAutomaticTabActivation` returns true only for an explicit 'automatic', so an absent value is permissive BY CONSTRUCTION in one place — an older client that does not send it keeps today's behavior rather than silently losing its wake gesture. The field is required on the mobile helper's params, so no call site can be added without declaring who asked. Every user path (mobile tab switches, paired tab clicks, shortcuts, palette, the pane's own open) is labelled 'user'. The only automatic sender in the codebase is `waitForResubscribeHostSessionHandle`, the stablyai#11542 reconnect probe. Verified per topology: user activation materializes a parked pane under headless serve, a paired runtime client, a completed agent with restoreOnTabOpenOnly, and a running agent whose wake cleared the record. The automatic probe is refused without retiring the surface, and stablyai#11542's reconnect tests stay green. Also fixes a test fixture that made a real bug untestable: the store stub ignored the host id, so mutating the partition lookup to 'local' left the suite green. Correcting it exposed three existing SSH reattach tests that had been relying on that looseness — their workspace session sat in the local partition while their repo was SSH-hosted, a store production would never read. Production was always right; the tests described an impossible world. Fixes STA-3465.
Summary
Fixes #11541.
A remote-runtime terminal pane whose host-side PTY is gone could never reconnect.
Reconnectspun for ~60s and fell back toRemote runtime disconnected; the only way out was to walk to the host machine, open that project, and let its renderer respawn the terminals.Cause: the host publishes such a surface as
status: 'pending-handle',terminal: null, and onlysession.tabs.activatematerializes a PTY for a pending surface (OrcaRuntimeService.activateMobileSessionTab→createHeadlessMobileSessionTerminal({ identity: { tabId, leafId } })). The first-attach path (waitForHostSessionHandle) does exactly that, but the reconnect path (waitForResubscribeHostSessionHandle, also used by theReconnectbutton viaretryRecovery()) only polledsession.tabs.listforHOST_SESSION_ATTACH_TIMEOUT_MS. It was waiting for a handle that nothing on the host would ever mint, so the pane was stranded until a human intervened on the host.The reconnect now opens with the same activate, then falls back to inventory polling:
tabId/leafIdidentity, so the pane rebinds to the revived PTY instead of a fresh unrelated tab.ready(the host guards onpublicTab.status !== 'ready'), so healthy reconnects behave exactly as before apart from one activate instead of one list.tab_not_found/terminal_not_foundfrom the activate does not retire the pane, and any other activate failure retries the materialize on the next poll inside the existing 15s budget.HOST_SESSION_ATTACH_TIMEOUT_MSand the recovery deadline/backoff are untouched.Reproduction that this fixes (macOS host + macOS client, both 1.4.160): work in a host project from a paired desktop client, restart Orca on the host (auto-update / quit / reboot), then reconnect from the client. Before:
Reconnectnever recovers. After: the pane reattaches on the first retry without touching the host.Screenshots
No visual change. The reconnect banner, its copy, and the button are untouched; only what the retry asks the host for changed.
Testing
pnpm lintpnpm typecheck(all three projects: node, tc.cli, tc.web)pnpm test— ranpnpm vitest run --config config/vitest.config.ts src/renderer(2012 files, 18259 tests, all green) and the affected file (86 tests). The top-levelpnpm testscript could not start in this environment: itsensure-native-runtime.mjspreflight rebuildsnode-ptyfor the local Node and fails on Node 22 (package.jsonwants Node 24), so vitest never runs. The failure is the preflight, not a test.pnpm buildmaterializes a host surface whose PTY died instead of polling a dead inventory— the host publishes the surface aspending-handle/terminal: null, the stale-handle path fires, and the test asserts the reconnect issuessession.tabs.activatefortabId/leafIdwithnotifyClients: false, navigation: 'caller', then rebinds and resubscribes to the materialized handle without retiring the pane. Reverting the fix leaves it polling and the assertion fails.reattaches from a later host snapshot after bounded replacement polling stops: the firstsession.tabs.listof a reconnect now happens one backoff after the materialize, so its timeout is> 14_000rather than exactly15_000. The intent of that check (inventory timeouts are clipped to the remaining budget and shrink toward the deadline) is preserved.AI Review Report
Reviewed with the GJC coding agent, focused on the reconnect state machine and on not regressing pane retirement.
nullfromwaitForResubscribeHostSessionHandlecallsretireRemoteTerminalId(), which firesonPtyExit. The review flagged the naive version, where atab_not_foundfrom the activate would retire a pane during a host restart race. Changed so only an inventory snapshot that omits the surface returnsnull; a failed activate records unknown liveness and keeps the pane, matching the pre-existing "unknown liveness must not retire the pane" contract.HOST_SESSION_ATTACH_TIMEOUT_MS(it is passed the remaining budget as its RPC timeout), so no new unbounded work, no extra timers, and no change to the recovery backoff or the 60s deadline.requireReplacementstill rejects a returned handle identical to the stale one.isWebTerminalSurfaceTabId), i.e. panes mirroring another Orca's session. The non-mirror branch (resolvePersistedHostPane(), used by SSH and local worktrees) is untouched. On the host, the materialize path works both with a renderer window attached and headlessorca serve, becausecreateHeadlessMobileSessionTerminalspawns a runtime-owned PTY viacreateTerminal({ focus: false, tabId, leafId })and does not require a window. Folder workspaces use the same worktree selector plumbing and are unaffected.launchAgentstartup itself (existing behavior for pending agent tabs), so a revived agent pane is not downgraded to a plain shell by this change.session.tabs.activatereplaces the firstsession.tabs.listper recovery attempt. No added polling, no new allocations in hot paths. Steady-state reconnects (surface alreadyready) resolve on that first response exactly as they did on the first list.Security Audit
session.tabs.activate, which is already in the paired-client allowlist and is what the first attach calls.toRuntimeWorktreeSelector(worktreeId),toHostSessionTabId(tabId),leafId). Nothing from the host response is used as a path, command, or shell input; the returned handle flows through the samefindReadyHostSessionHandlevalidation as before.notifyClients: false, navigation: 'caller'keeps the effect scoped to the calling device — no host navigation and no fan-out to other paired clients.rememberHostTerminalTabCountcountspending-handlesurfaces, which suppressesensureWebRuntimeWorktreeTerminalAfterWakerespawn, and a client'sworktree.activatenever asks the host to background-mount anything (resumeSleepingAgentsnext to it is gated onclientKind === 'mobile'). Both are separate defence-in-depth fixes; this PR intentionally changes one behavior.Notes
authoritativeWindowId != null,graphStatus: 'ready') where the affected workspace was not open, which is the state that leaves restored tabs atpendingActivationSpawnwith no PTY.