Skip to content

fix(remote-runtime): materialize the host surface when reconnecting a terminal pane - #11542

Merged
Jinwoo-H merged 4 commits into
stablyai:mainfrom
planderdev:fix/remote-runtime-reconnect-materializes-host-surface
Aug 5, 2026
Merged

Jinwoo-H merged 4 commits into
stablyai:mainfrom
planderdev:fix/remote-runtime-reconnect-materializes-host-surface

Conversation

@planderdev

Copy link
Copy Markdown
Contributor

Summary

Fixes #11541.

A remote-runtime terminal pane whose host-side PTY is gone could never reconnect. Reconnect spun for ~60s and fell back to Remote 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 only session.tabs.activate materializes 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 the Reconnect button via retryRecovery()) only polled session.tabs.list for HOST_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:

  • The materialize targets the exact tabId/leafId identity, so the pane rebinds to the revived PTY instead of a fresh unrelated tab.
  • It is a no-op when the surface is already ready (the host guards on publicTab.status !== 'ready'), so healthy reconnects behave exactly as before apart from one activate instead of one list.
  • A missing surface must still be proven by an inventory snapshot: tab_not_found / terminal_not_found from 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_MS and 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: Reconnect never 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 lint
  • pnpm typecheck (all three projects: node, tc.cli, tc.web)
  • pnpm test — ran pnpm vitest run --config config/vitest.config.ts src/renderer (2012 files, 18259 tests, all green) and the affected file (86 tests). The top-level pnpm test script could not start in this environment: its ensure-native-runtime.mjs preflight rebuilds node-pty for the local Node and fails on Node 22 (package.json wants Node 24), so vitest never runs. The failure is the preflight, not a test.
  • pnpm build
  • Added a regression test: materializes a host surface whose PTY died instead of polling a dead inventory — the host publishes the surface as pending-handle/terminal: null, the stale-handle path fires, and the test asserts the reconnect issues session.tabs.activate for tabId/leafId with notifyClients: 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.
  • Updated one assertion in reattaches from a later host snapshot after bounded replacement polling stops: the first session.tabs.list of a reconnect now happens one backoff after the materialize, so its timeout is > 14_000 rather than exactly 15_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.

  • Behavior risk (retirement): null from waitForResubscribeHostSessionHandle calls retireRemoteTerminalId(), which fires onPtyExit. The review flagged the naive version, where a tab_not_found from the activate would retire a pane during a host restart race. Changed so only an inventory snapshot that omits the surface returns null; a failed activate records unknown liveness and keeps the pane, matching the pre-existing "unknown liveness must not retire the pane" contract.
  • Loop/budget risk: the materialize runs at most once per successful attempt and shares 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. requireReplacement still rejects a returned handle identical to the stale one.
  • Cross-platform (macOS/Linux/Windows): pure renderer RPC sequencing. No paths, no shell, no keyboard shortcuts, no platform APIs, no Electron-specific behavior. Nothing to guard per platform.
  • Remote/SSH/local: only reachable for web-surface mirror tabs (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 headless orca serve, because createHeadlessMobileSessionTerminal spawns a runtime-owned PTY via createTerminal({ focus: false, tabId, leafId }) and does not require a window. Folder workspaces use the same worktree selector plumbing and are unaffected.
  • Agents/integrations/git providers: agent-neutral and provider-neutral. The host's materialize re-resolves the tab's launchAgent startup itself (existing behavior for pending agent tabs), so a revived agent pane is not downgraded to a plain shell by this change.
  • Performance: one session.tabs.activate replaces the first session.tabs.list per recovery attempt. No added polling, no new allocations in hot paths. Steady-state reconnects (surface already ready) resolve on that first response exactly as they did on the first list.
  • UI quality: no UI change; the banner simply stops being a dead end.

Security Audit

  • No new IPC channels, no new RPC methods, no protocol/capability changes. It reuses session.tabs.activate, which is already in the paired-client allowlist and is what the first attach calls.
  • Parameters are the pane's own already-validated identity (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 same findReadyHostSessionHandle validation 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.
  • No secrets, credentials, tokens, environment, or command execution touched. No new dependencies. Error messages are matched, not constructed from user input.
  • Follow-up (out of scope, noted in [Bug]: Remote-runtime terminal reconnect can never recover a host surface whose PTY died — reconnect polls session.tabs.list but only session.tabs.activate materializes it #11541): rememberHostTerminalTabCount counts pending-handle surfaces, which suppresses ensureWebRuntimeWorktreeTerminalAfterWake respawn, and a client's worktree.activate never asks the host to background-mount anything (resumeSleepingAgents next to it is gated on clientKind === 'mobile'). Both are separate defence-in-depth fixes; this PR intentionally changes one behavior.

Notes

@coderabbitai

coderabbitai Bot commented Jul 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

The 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)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the primary change: materializing the host surface during remote-runtime terminal reconnect.
Description check ✅ Passed The description includes all required sections, detailed testing status, AI review coverage, security audit, and platform notes.
Linked Issues check ✅ Passed The implementation satisfies [#11541] by activating exact host surfaces, preserving bounded recovery, and retiring panes only after inventory confirmation.
Out of Scope Changes check ✅ Passed The changes remain within scope and provide supporting host-side fixes, regression tests, E2E coverage, and reliability-gate updates for [#11541].

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 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 win

Retry activation after an inconclusive missing-surface check. A classified activation error sets surfaceActivated = true, permanently selecting session.tabs.list. If that list still returns the matching pending-handle surface, 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.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts

Comment on lines +496 to +542
@@ -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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 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-apps

greptile-apps Bot commented Jul 30, 2026

Copy link
Copy Markdown

Greptile Summary

This PR fixes a reconnect deadlock where a remote-runtime terminal pane with a dead host PTY could never recover — Reconnect would spin for 60 s and give up because the host only mints an attachable handle inside session.tabs.activate, not session.tabs.list. The reconnect path (waitForResubscribeHostSessionHandle) now issues one activate on its first iteration to materialize the surface before falling back to inventory polling.

  • Core fix: waitForResubscribeHostSessionHandle calls the new activateHostSessionSurface helper on the first iteration (surfaceActivated = false); subsequent iterations and all timeout-budget accounting are unchanged.
  • Retire contract preserved: tab_not_found / terminal_not_found from the activate sets surfaceActivated = true (switching to list polling) rather than returning null, so only a confirmed inventory snapshot can retire the pane.
  • Test coverage: a new regression test covers the full pending-handle → activate → rebind → no-retire path; the existing timeout-bound test is correctly tightened to (14 000, 15 000] to account for the one-backoff offset.

Confidence Score: 5/5

Safe 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 session.tabs.list) with session.tabs.activate on reconnect, leaving the timeout budget, backoff math, and retire logic untouched. The surfaceActivated flag correctly gates the transition to list polling, and the isMissingHostSessionSurfaceError path explicitly avoids retiring the pane on an unconfirmed activate error. The only finding is a minor naming issue (lastListError now also holds activate errors), which has no behavioral impact.

Files Needing Attention: No files require special attention; both changed files are well-covered by the updated and new test cases.

Important Files Changed

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

lightofjeju and others added 3 commits August 4, 2026 21:59
… 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
@Jinwoo-H
Jinwoo-H force-pushed the fix/remote-runtime-reconnect-materializes-host-surface branch from 096bc24 to a8d08ce Compare August 5, 2026 02:00
@coderabbitai

coderabbitai Bot commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🧹 Nitpick comments (6)
src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts (1)

1978-2077: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a companion test for a non-missing activation error.

This test covers only the tab_not_found branch. No test covers an activation failure whose message is not tab_not_found or terminal_not_found, for example method_not_found from a host runtime without session.tabs.activate. That branch keeps nextRequest at 'activate' in remote-runtime-pty-transport.ts and never issues session.tabs.list, which is the regression described in the comment on remote-runtime-pty-transport.ts Line 719-731.

Add a case where the first activation rejects with method_not_found and inventory publishes a ready replacement handle. Assert that a session.tabs.list call 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 value

Document 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 trigger recoverStalledStream. 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 value

Remove the unused processedInputPath plumbing, or assert on it.

The fixture writes every processed input line to processedInputPath through appendFileSync, but no assertion ever reads that file. The test verifies the replacement PTY through terminal.read on 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 appendFileSync call 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 value

Capture the worktree id inside the poll instead of re-evaluating.

Lines 93-100 and 104-111 run the same page.evaluate expression twice. The poll already computes the id, so the second evaluation is redundant. It also re-reads the worktree list after the poll succeeded.

runMaterializationJourney already uses the capture-inside-poll pattern for replacementHandle on 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 value

Two 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 echoes LIVE:${input} for each received line, so the host writes back LIVE:echo MATERIALIZED_<ts>. The assertions still pass because the returned line contains marker. The echo prefix implies shell execution that does not happen. Send the bare marker so 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.closeTab never runs and the host keeps the terminal. The per-test finally blocks dispose the client and the headless host, so this does not leak across tests. Wrapping the journey body in try/finally would still make failures cleaner for the shared headed host.


158-197: 🗄️ Data Integrity & Integration | 🔵 Trivial | ⚡ Quick win

Centralize the __remoteTerminalMultiplexAckGate type 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

📥 Commits

Reviewing files that changed from the base of the PR and between 549816c and a8d08ce.

📒 Files selected for processing (5)
  • config/reliability-gates.jsonc
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • src/renderer/src/runtime/remote-runtime-terminal-multiplexer.ts
  • tests/e2e/paired-remote-terminal-materialization-reconnect.spec.ts

Comment on lines 719 to 731
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
}
}

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.

🩺 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/runtime

Repository: 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.ts

Repository: 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.

Suggested change
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)
}
}

Comment on lines +294 to +303
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
})

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.

🩺 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 Jinwoo-H 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.

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:

  1. waitForResubscribeHostSessionHandle does not re-activate when the first activation races host publication and returns the previous ready handle, then authoritative inventory later exposes the exact pending-handle surface. The activation result selects list polling, and the list result only re-arms activation when retryActivationAfterInventory was set by a classified missing activation error. A deterministic test against the current head observed activate, list, list, list instead of activate, list, activate; the pane never obtained the replacement handle.
  2. A non-missing activation failure such as method_not_found never falls back to authoritative inventory. A deterministic old-host test observed activate, activate, activate instead of activate, 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.
  3. The changed-spec E2E gate does not execute the new tests. Both tests are tagged @headful, while changed-spec CI always runs the electron-headless project, whose grepInvert excludes them. CI therefore fails with Error: No tests found. The reliability-gate command separately names electron-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 (0 observed). 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-handle publication 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.
@Jinwoo-H

Jinwoo-H commented Aug 5, 2026

Copy link
Copy Markdown
Contributor

Pushed 0361bc1a0b addressing the two blocking defects from the last review, plus a host-side gap that the E2E surfaced.

1. Stale-ready activation race

The 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: activate / list / list / list …

2. Non-missing activation failure had no inventory fallback

Activation was only retried through inventory after a classified missing error. Any other failure — method_not_found on an older host, a transport error — kept retrying activation forever with no inventory fallback.

Observed on the previous head: activate / activate / activate …

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:

  • re-activates when a stale ready activation response precedes the pending surface → ['session.tabs.activate', 'session.tabs.list', 'session.tabs.activate']
  • falls back to inventory when activation fails for a non-missing reason → ['session.tabs.activate', 'session.tabs.list']

Both also assert the pane is neither retired nor errored (onPtyExit/onError never called) and that it rebinds to the replacement handle.

3. Host-side: activation destroyed the pane it was asked to rebuild

The paired E2E could not pass, and it was not a harness problem. With no fault injection at all, a single session.tabs.activate against a parked surface failed with terminal_pane_owner_changed and permanently deleted the host tab — a subsequent manual activate returned tab_not_found.

Traced to attachStablePaneOwner in src/main/ipc/pty.ts. Once the PTY is proven dead it retires the owner — runtime.onPtyExit(...), which removes the session tab — and then asks persistence to retire too. For a pane parked with keepHistory, persistence had already dropped the binding, so retirePersistedStablePaneOwner returned false, which the caller read as a competing owner and threw. The destructive half had already run and the fresh spawn never happened, so the pane was unrecoverable.

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 (terminal_pane_owner_unverified) are unchanged.

Covered by respawns a proven-dead owner whose persisted binding was already retired — red with terminal_pane_owner_changed before the fix, green after.

4. CI: changed e2e specs reported "No tests found"

Both specs were tagged @headful, and the changed-spec lane runs electron-headless, whose project config is grepInvert: /@headful/. Neither test needs focus or pointer capture (per tests/e2e/AGENTS.md, @headful is only for those), so the tags are dropped and the reliability-gate command now targets electron-headless to match.

Validation

  • remote-runtime-pty-transport.test.ts + pty.test.ts: 555 passed
  • remote-runtime-pty-transport.test.ts + remote-runtime-pty-recovery-state.test.ts: 123 passed
  • orca-runtime.test.ts + mobile-session-terminal-persistence-retirement.test.ts: 1033 passed, 1 skipped
  • pty.test.ts + pty-management.test.ts: 460 passed
  • typecheck, lint, format: clean
  • Headed paired-host E2E: 5/5 green, ~8s each

Independent oracle: the STA-3002 reproduction from the outage/stuck-reconnect suite (activation → rebind → input flow) is red on origin/main — 51 list-only inventory polls, zero activations — and green on this branch. Its intermediate listCallsAfterOutage > 1 checkpoint encodes the old list-polling cadence and is obsolete now that recovery activates immediately; that checkpoint alone was dropped, the activation/rebind/input assertions were kept.

Known gap: headless folder-host topology

The second E2E is marked test.fixme with the reason inline. Its fault injection cannot be set up against a headless orca serve host: terminal.stopExact returns terminal_exact_stop_failed because stopAndWait's keep-history verification window expires before the parked PTY is observed gone, so the pane never reaches pending-handle and the reconnect path is never reached. This precondition fails identically on this PR's base, so it is a pre-existing exact-stop defect, not a reconnect-activation one, and it deserves its own issue.

The behavior itself was confirmed in that topology with instrumented runs: the headless host materializes the pending surface on the same tab/leaf, and the client rebinds to the replacement PTY within one second. What blocked the assertion afterwards was that parking the host PTY clears the client's active-worktree selection, so reading the replacement through the active pane saw nothing; the spec now reselects the pane before that read (the rebind assertion itself is unchanged). That selection reset also looks worth a separate look.

@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)
src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts (1)

1983-2073: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Consider 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, install runtimeCall.mockImplementation, fire subscriptionCallbacks.onResponse with terminal_handle_stale, advance fake timers, assert the method sequence, assert the resulting subscribe payload and rebind, assert no exit/error callback, then destroy().

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

📥 Commits

Reviewing files that changed from the base of the PR and between a8d08ce and 0361bc1.

📒 Files selected for processing (6)
  • config/reliability-gates.jsonc
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.test.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-pty-transport.ts
  • tests/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 Jinwoo-H 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.

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.

@Jinwoo-H
Jinwoo-H merged commit cbc005c into stablyai:main Aug 5, 2026
45 checks passed
Jinwoo-H added a commit that referenced this pull request Aug 5, 2026
…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.
Jinwoo-H added a commit that referenced this pull request Aug 5, 2026
…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.
Jinwoo-H added a commit that referenced this pull request Aug 5, 2026
…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.
Jinwoo-H added a commit that referenced this pull request Aug 5, 2026
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.
Jinwoo-H added a commit that referenced this pull request Aug 5, 2026
…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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
… 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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

5 participants