Skip to content

[P1] fix(mobile): restore folder session tab snapshots - #11868

Closed
brennanb2025 wants to merge 28 commits into
mainfrom
brennanb2025/mobile-folder-session-tab-snapshot
Closed

brennanb2025 wants to merge 28 commits into
mainfrom
brennanb2025/mobile-folder-session-tab-snapshot

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Restore usable Orca Mobile session tabs for folder workspaces while keeping every persisted session and PTY bound to the local, SSH, or relay host that owns it.

This head fixes the post-restart input failure found during native acceptance. Previously, reconnect could restore the folder tab and scrollback and report the terminal as ready, but typed input disappeared because the restarted runtime had discovered the surviving PTY without attaching to it. Activating the restored tab now reattaches its persisted session once for the current runtime generation before input is accepted.

Follow-up review found two concurrency problems in that recovery path. First, concurrent mobile or paired renderer/mobile activation could issue duplicate local reattachments or SSH pty.attach calls. Second, after those duplicate calls were coalesced, whichever caller entered first also decided whether the shared operation activated the host tab. A navigation-only caller entering just before a host-focus caller performed one successful reattach but could leave the prior host tab active.

The shared operation now owns only physical reattachment. After it completes, every caller rechecks its own folder mutation and SSH reconnect generation, then applies its own client navigation or host/headless activation intent. This closes the backend/session-entry blocker documented in #11751 and complements #11767 and #11647 without merging or broadening them.

Before and after

Before, restored PTY inventory was treated as writable ownership, so input could fail after restart. The first attachment fix corrected that, and the first concurrency follow-up ensured concurrent callers shared one exact-surface reattach. However, the shared promise still captured the first caller's host-navigation flag. If phone-local navigation reserved the operation before a concurrent host-focus request, the host-focus waiter only updated client projections and activeTabId stayed on the prior tab.

After, exact-surface callers still share one local, direct-SSH, or relay reattach, but the shared materialization is navigation-neutral. Each waiter revalidates its own deletion/recreation and reconnect fences before it can publish navigation or activate the restored headless tab. Navigation-first and host-first calls both end on the requested host tab, stale callers cannot publish or focus, and paired renderer/mobile restoration still avoids focusing a renderer that has not adopted the runtime-owned tab.

What changed

  • Recover folder terminal tabs from persisted workspace sessions when an attached renderer omits the folder snapshot, including ordinary local terminals and runtime-owned SSH/serve terminals.
  • Reattach inventory-restored runtime-owned terminals before returning a writable activation after runtime restart or reconnect.
  • Coalesce concurrent restored-terminal activation per exact host/session/tab/leaf surface while preserving independent work across other hosts, sessions, tabs, and leaves.
  • Keep shared reattachment navigation-neutral, then apply each caller's host/headless activation only after its own mutation and reconnect fence passes.
  • Route folder and Git session reads through explicit execution-host ownership, fail closed on ambiguous raw/scoped aliases, and isolate duplicate repository IDs and paths across local and SSH hosts.
  • Partition PTY inventory by provider and fence asynchronous refreshes against folder catalog, path, transport, host, and relay-generation changes.
  • Make folder removal durable across host partitions: prune tab, layout, browser, sleeping, PTY, and reconnect state; retain bounded removal tombstones; and publish empty state when the same folder identity is recreated.
  • Preserve paired-renderer rescue and the one-read-per-host graph hydration bound.

Behavior covered

  • Folder workspaces and Git worktrees.
  • Local, direct SSH, and runtime-owned relay hosts.
  • Navigation-first then host-focus and host-focus then navigation activation order, with one physical reattach and the requested host tab active.
  • Duplicate repository IDs and paths on different hosts.
  • Wrong-host and ambiguous-owner rejection.
  • Runtime restart/reconnect attachment, concurrent and repeated activation, paired renderer/mobile restoration, retry after rejection, last-tab close, restart/reopen recovery, folder deletion, delayed stale writes, same-ID recreation, and refresh races.
  • Raw and worktree: owner aliases, worktree-less PTY recovery, and provider-scoped PTY IDs.

Verification

  • Exact head: c1e48f61df9975598fd3752b6e25adde3824592a (activation-order implementation 206bbc83510a13eef6f570cac39d259e42d9dabe, from 8d35b014c19d5e7f3fb8c238cc7dcfea15c22748).
  • Focused affected suite: 1,394 tests passed with one existing skip across the main runtime, PTY IPC, folder mutation races, and the exact materialization-key suite.
  • Order-sensitive regressions cover both local folder caller orders, navigation-first Git-worktree activation, and navigation-first SSH relay attachment. They verify one provider reattach/pty.attach, writable terminal input, and the requested final host tab.
  • Reconnect-generation and folder deletion/recreation races reject every stale waiter before client publication or host focus.
  • The uncached Node typecheck passed on the exact head.
  • Default, native-plugin, and type-aware Oxlint scans over the changed files passed; the max-lines ratchet and git diff --check passed.
  • mobile/pnpm-lock.yaml is byte-for-byte unchanged from 8d35b014c19d5e7f3fb8c238cc7dcfea15c22748 (Git blob 9788413f92587fc2e15f3de5ea0f504a02841778).
  • No simulator was started or used for this implementation pass.

Native acceptance context

The prior exact-head native pass validated folder/Git switching, local terminal creation and input, last-tab close/reopen, deletion and same-path recreation, and duplicate-path partitioning. It also captured the blocking pre-fix reconnect state below: the authenticated remount restored the old tab and scrollback, while native input produced no output and CLI send returned zero bytes.

folder-authenticated-reconnect.png

That screenshot documents the failure at 72010c7311d26ed88ad3c275de954f0dd07d9d94; the current head fixes the attachment decision and its remaining concurrency/activation-order races with production-path tests. This implementation pass intentionally did not start or use a simulator, so native revalidation remains separate.

The isolated native profile had no SSH targets, so direct SSH, relay, and cross-host duplicate behavior are covered by automated tests rather than that native run.

Security and compatibility

No new RPC, authentication, dependency, command, renderer, or filesystem surface. The fix reuses the existing provider reattach path and its explicit local/SSH routing. Ambiguous ownership is rejected rather than guessed, and stale asynchronous work remains fenced before mutation, publication, or focus.

Latest fresh exact-head review fixes

A fresh review of a9b9dfbe99b7b809a5e2435a6270fafa17a3173e found two remaining P1 PTY ownership bugs.

Host-aware reservation paths

Before, any workspace path beginning with two slashes looked like a Windows UNC path to the reservation key. On a POSIX or SSH filesystem, distinct paths such as //Server/Share and //server/share could therefore be lowercased to the same key and share one PTY.

After, the reservation uses the path rules of the host that actually runs the PTY. Native Windows, WSL, and known Windows SSH/relay hosts still fold equivalent drive and UNC spellings. Linux, macOS, known POSIX remotes, and unknown remotes keep leading-double-slash paths and Unicode spellings byte-for-byte distinct. Raw worktree IDs and their worktree: form still meet when they identify the same surface, and paired renderer/mobile callers still share one provider operation.

Creator-only retirement before stale checks

Before, the runtime checked the workspace-inventory fence immediately after provider spawn, before installing creator-only cleanup. An adopted relay result that omitted the unrelated isReattach flag could be mistaken for a new PTY and shut down, while a genuinely new local result could leave its terminal handle, pending registration, or early-exit fence behind.

After, an idempotent retirement token is created immediately when the provider returns. The provider's claim disposition decides ownership: only a result proven newly created may be shut down or have its binding, lease, provider state, and ownership removed. Adopted, reattached, reused, and coalesced-waiter results are never retired. Runtime admission state is cleared exactly once, cleanup failures cannot replace the original error or block later rollback steps, all reservation waiters receive that original error, and retry starts with a clear reservation.

Latest verification

  • Finished head: b7f31677c81bc988089e3cb8eb82e993ec58779f (reviewed head a9b9dfbe99b7b809a5e2435a6270fafa17a3173e; GitHub base 072133fb279449b681034651052c036149da51f3).
  • The prior 15-file suite plus both new host-flavor suites passed under Node 24: 17 files, 2,097 tests passed, and one existing test skipped.
  • Regressions cover POSIX and SSH leading-double-slash distinctions; Windows drive and UNC equivalence; WSL, direct-SSH, relay, and unknown-platform routing; NFC/NFD separation; raw/worktree: aliases; and renderer/mobile coalescing.
  • PTY lifecycle regressions cover an adopted relay result without isReattach, fresh local real-runtime cleanup, SSH/relay-style binding and lease cleanup, concurrent waiter error delivery, retry, nested cleanup failure, and no double retirement.
  • The uncached Node 24 node-project TypeScript check passed.
  • Full default, native-plugin, and type-aware Oxlint passed. The changed-code gate reported zero new code-quality, type-aware, or React Doctor findings across 36 PR-changed files.
  • Max-lines ratchet, PR-changed formatter check, reliability manifest check, commit hooks, and git diff --check passed.
  • GitHub settled with 42 successful checks, one intentionally skipped E2E check, and no failures or pending checks; Greptile Review completed successfully.
  • mobile/pnpm-lock.yaml remains byte-for-byte unchanged from the reviewed head (Git blob 9788413f92587fc2e15f3de5ea0f504a02841778; SHA-256 c27ea16a5b176291cb14227fc44970f47b9e3d7e61c8cf8e6433109db3967487).
  • No simulator, Electron, Computer Use, or UI automation was started or used for this implementation pass.

Final fresh-review follow-up

A fresh same-model/xhigh complete review of the reviewed head b7f31677c81bc988089e3cb8eb82e993ec58779f found two remaining concurrency races in the restored-terminal path.

Shared PTY reservation retirement

Before, the caller that physically created a coalesced PTY kept unconditional cleanup authority. If that creator became stale or its renderer was destroyed while the provider was still pending, it could kill the PTY after a live runtime or renderer waiter had already received the shared result.

After, creator and waiter calls receive independent one-use retirement claims only when a fresh spawn is shared. An abandoning caller releases its claim; the PTY is retired only after every participant abandons it, while the first live adopter cancels retirement for all peers. Creator-only cleanup remains unchanged, adopted/reattached results are never retired, and provider exit plus rejection/retry paths clear reservation state.

Fresh materialization coalescing

Before, the shared materialization key did not include the folder-routing fence or SSH reconnect generation captured by the caller. A current activation could therefore join an older promise and inherit its obsolete rejection after reconnect or a folder host/path mutation.

After, materialization identity includes the captured folder-routing fingerprint and reconnect generation in addition to the existing host/workspace/session/tab/leaf surface. Same-freshness callers still perform one physical attachment, while a current caller starts one independent retry instead of inheriting a stale promise; the stale caller remains fenced from publication and host focus.

Final follow-up verification

  • Finished head: 1466ce80505f6fd0d152e4997fdb6bbdf278f7d4 (reviewed head b7f31677c81bc988089e3cb8eb82e993ec58779f; GitHub base 072133fb279449b681034651052c036149da51f3).
  • Node 24.18.1 affected suite: 22 files, 2,148 tests passed, and one existing test skipped. This includes the prior 17-file suite plus reservation lifecycle, materialization freshness, and adjacent background-spawn coverage.
  • Deterministic regressions cover destroyed renderer creator with a live runtime waiter, stale runtime creator with a live renderer waiter, the reverse waiter-retirement direction, all-participants-abandon cleanup, creator-only cleanup, rejection/retry cleanup, and successful adoption.
  • Reconnect-generation and folder host/path mutation regressions prove an obsolete rejection is isolated, the current caller retries once, the stale caller cannot focus, and unchanged same-freshness activation still coalesces.
  • Node 24 node-project and web-project TypeScript checks passed.
  • Default, native-plugin, and type-aware Oxlint passed over all 19 follow-up files. The changed-code gate reported zero new code-quality, type-aware, or React Doctor findings across all 44 PR-changed files.
  • Max-lines ratchet, 19-file formatting check, reliability manifest, commit hooks, and git diff --check passed.
  • mobile/pnpm-lock.yaml remains byte-for-byte unchanged from the reviewed head (SHA-256 c27ea16a5b176291cb14227fc44970f47b9e3d7e61c8cf8e6433109db3967487).
  • No simulator, Electron, screenshot, Computer Use, or UI automation work was run for this implementation follow-up.

Same-ID folder route reservation follow-up

Before, the outer mobile materialization key separated folder-route and SSH reconnect generations, but the lower renderer/runtime PTY reservation key did not carry the resolved final cwd or that captured freshness. A current activation could therefore join an obsolete same-pane creator after a same-ID folder mutation, inherit its tab_not_found rejection, or share its retirement outcome.

After, both lower reservation branches include the same captured route/reconnect freshness and the host-aware canonical final spawn path. Unchanged renderer/runtime callers still share one provider operation, while a changed folder route starts an independent operation; the obsolete runtime creator may retire only its own PTY, and the current new-path result and binding survive.

Follow-up validation

  • Finished head: 1700901ae6 from reviewed head 1466ce80505f6fd0d152e4997fdb6bbdf278f7d4.
  • Node 24.18.0 focused suite: 7 files and 476 tests passed, covering both stale-runtime-creator and stale-renderer-creator route mutations plus unchanged one-operation coalescing.
  • Node-project and web-project TypeScript checks passed.
  • Default, native-plugin, and type-aware Oxlint passed on all 6 follow-up files; changed-code quality reported zero new code-quality, type-aware, or React Doctor findings across 45 PR-changed files.
  • Max-lines ratchet, formatter check, reliability manifest, commit hooks, and git diff --check passed.
  • mobile/pnpm-lock.yaml remains byte-for-byte unchanged at SHA-256 c27ea16a5b176291cb14227fc44970f47b9e3d7e61c8cf8e6433109db3967487.
  • No Electron, simulator, screenshot, Computer Use, or UI automation work was needed for this backend-only follow-up.

Provisional pane-waiter cleanup follow-up

Before, paired runtime/renderer materialization still showed one shared terminal to the user, but the lower call that became a waiter had already minted daemon hook/overlay state and cached geometry. A renderer waiter could also prepare a Claude Agent Teams identity for a terminal handle that was never registered, leaving team state with no PTY exit path to release it.

After, both lower PTY entry points discard only the no-session identity minted by that losing request before awaiting the existing reservation. The renderer path also discards only its prepared-but-unused Agent Teams leader handle. Caller-supplied session identities, current/creator-owned PTYs, provider routing, final-cwd and route/reconnect freshness, and the shared provider operation remain unchanged.

Waiter-cleanup validation

  • Finished and pushed head: 5ad243ec9dde03a7cc7838638ac754a01db16fc1 from reviewed head 1700901ae698448ee96b63637097c6fdd8768aec.
  • Node 24.18.0 focused affected suite: 3 files and 436 tests passed (full PTY IPC, pane reservation, and Agent Teams PTY-exit coverage).
  • New real registerPtyHandlers regressions cover runtime-creator/renderer-waiter and renderer-creator/runtime-waiter races with no caller session, distinct minted IDs, overlay and ptySizes cleanup, prepared Agent Teams handle/team eviction, caller-supplied identity preservation in both directions, and one provider spawn for unchanged routing.
  • The existing changed-folder-route matrix passed in both creator directions and still performs two independent provider operations while preserving the current route result.
  • All Node, CLI, and web TypeScript project checks passed under Node 24.
  • Full default, native-plugin, and type-aware Oxlint passed. The changed-code gate reported zero new code-quality, type-aware, or React Doctor findings across 45 PR-changed files.
  • Reliability manifest (57 gates), max-lines ratchet, localization and bundled-skill verifiers, affected-file formatter check, commit hooks, and git diff --check passed.
  • pnpm install --frozen-lockfile --ignore-scripts passed; no root or mobile lockfile changed.
  • No Electron, simulator, screenshot, Computer Use, or UI automation was needed for this backend-only follow-up.

Renderer creator/runtime waiter ownership follow-up

Before and after

Before, a full runtime createTerminal request could become the waiter behind a renderer-created PTY after it had already prepared a fresh terminal handle and Claude Agent Teams launch identity. When the shared reservation resolved, the runtime waiter treated the creator result as its own spawn, rebound the live PTY to the waiter handle, replaced creator title/launch metadata, and leaked the unused waiter team; pre-spawn and post-await inventory or disconnect rejection could leak the same provisional team.

After, createTerminal checks both rejection fences while its team remains provisional, removes that team by its exact team ID/token, and branches on spawnDisposition: awaited before registration or publication. A live waiter adopts the already-registered creator handle, workspace, pane, title, launch metadata, and execution-host metadata without rewriting them; stale waiters release only their reservation claim, caller-supplied session identities are not cleared, and changed folder routes remain isolated from the old reservation.

Exact validation

  • Finished and pushed head: ced9fd53215d55ac7ec55ee3d3e21714ee3e3ccf from reviewed head 5ad243ec9dde03a7cc7838638ac754a01db16fc1.
  • Node 24.18.0 affected matrix: 8 files, 1,449 tests passed, and one existing test skipped. The matrix covers full runtime, full PTY IPC, pane reservations, Claude Agent Teams service and PTY-exit cleanup, folder mutation races, folder session tabs, and terminal materialization freshness.
  • New deterministic teammate-mode regressions cover renderer creator/runtime waiter success, one unchanged-route provider operation, creator handle/title/launch metadata preservation, exact waiter-team cleanup, caller-owned session preservation, pre-spawn and post-await inventory/disconnect fences, and two-operation changed-route isolation.
  • All Node, CLI, and web TypeScript projects passed under Node 24.18.0.
  • Full default, native-plugin, and type-aware Oxlint passed. The changed-code gate reported zero new code-quality, type-aware, or React Doctor findings across 47 PR-changed files.
  • Reliability manifest (57 gates), max-lines ratchet, affected-file formatter check, commit hooks, git diff --check, and clean-worktree checks passed.
  • pnpm install --frozen-lockfile --ignore-scripts passed. Root lockfile blob 491c536773bea156b9c5a5ccfcd20f86f875cdfd and mobile lockfile blob 9788413f92587fc2e15f3de5ea0f504a02841778 are unchanged.
  • No Electron instance, simulator, screenshot, Computer Use, or UI automation was started or used for this backend-only follow-up.

2026-08-01 exact-head iPad recovery — artifact proven, matrix blocked

  • Exact-head gate: local HEAD and PR head matched ced9fd53215d55ac7ec55ee3d3e21714ee3e3ccf; Node was 24.18.0, Xcode was 26.6 (17F113), and no source, configuration, or lockfile was edited.
  • A fresh isolated direct build reproduced the Xcode Planning-build deadlock. Four compiler-discovery clang -v -E -dM children blocked in write() to SwiftBuild-owned pipes while sampled SWBBuildService remained idle in its main run loop, narrowing the failure to Xcode/SwiftBuild pipe backpressure rather than the compiler or SDK.
  • The prior successful Orca.app was recovered and proven byte-equivalent for current head. It was built while the worktree was at 72010c7311d26ed88ad3c275de954f0dd07d9d94; the full mobile tree plus root package.json, pnpm-lock.yaml, pnpm-workspace.yaml, and config/patches have identical Git objects at 72010c and ced9fd; the Xcode build matches; strict codesign passes; and the native executable hashes remain 527562c6568e6a535881a83f050249db1bf15dbf67565da6378397f156393e22 and e16d7a504c0e83c208d20545793c88f10fd8b5180e4d71a4eff66842287009ec.
  • Node-24 repository Expo run:ios --binary reinstalled that proven app on approved iPad C589AF84-2F0C-4978-952B-748933DE6804 and dispatched the port-8087 development URL. Current-run Orca AX then showed Welcome back, nine host rows, Pair Desktop, and the genuine pairing screen instructions.
  • Metro did not record a device bundle request before the emulator stream failed, so cached JS provenance was not assumed and no feature behavior is claimed from those observations.
  • Both pre-existing Orca emulator helpers then disappeared. The supported attach path repeatedly allocated the approved iPad to reserved port 3100 instead of approved port 3101—even when coordinator-approved localhost port guarding made attach return emulator_helper_failed—so each exact wrong-port helper was immediately stopped without UI input and QA stopped as directed.
  • Result: folder/Git restoration, reconnect/remount, restored scrollback/input/new output, switching identity, last-tab reopen, background/foreground, deletion/recreation, duplicate host/path isolation, retained input, orientation, feature AX, and SSH/relay remain unvalidated in this recovery run. No current-run screenshot was attached; the existing image above remains explicitly attributed to the earlier 72010c run.
  • Smallest external action: restore the original Orca-managed reserved iPhone/3100 and approved iPad/3101 helpers, or provide a supported way to pin the approved iPad attach to 3101, then rerun exact-head Metro pairing and the complete matrix. PR remains open and was not merged.

2026-08-01 genuine exact-head iPad retry — core regression passed, stream lost

Before and after

Before this fix, a runtime restart could restore the folder tab and its scrollback while leaving the surviving PTY unattached: native input disappeared and the restored surface was not genuinely writable. In this current run, the exact-head runtime restart restored the same folder terminal/PTY/incarnation, preserved a complete draft entered while offline, re-enabled Send after automatic reconnect, and executed the retained command; folder scrollback grew from 605 to 802 bytes.

Current-run provenance

  • Exact local and PR head: ced9fd53215d55ac7ec55ee3d3e21714ee3e3ccf.
  • Approved iPad: C589AF84-2F0C-4978-952B-748933DE6804, on required port 3101; reserved iPhone 50FD514C-96F6-446E-AC90-D07A24CAB3A0 remained on 3100 and was not targeted; protected B48D04BD-B0BF-4463-A59D-7F2AFE5FD8E4 was never targeted.
  • The repository Expo run:ios --binary flow reinstalled the already-proven native artifact. Its complete repository-controlled native inputs are byte-equivalent from build commit 72010c7311d26ed88ad3c275de954f0dd07d9d94 through ced9fd; executable hashes remain 527562c6568e6a535881a83f050249db1bf15dbf67565da6378397f156393e22 and e16d7a504c0e83c208d20545793c88f10fd8b5180e4d71a4eff66842287009ec.
  • The current pairing token was entered through orca emulator, AX-verified byte-for-byte before Save, and connected the iPad to the exact-head Node 24 runtime on port 62921.
  • The cached device bundle came from the prior 72010c run. The complete mobile tree is identical through ced9fd (d80587ae529682449deec5a5834ff5fc0f7fc5fb) and no direct mobile imports of the later shared backend changes were found, but Metro recorded no current device fetch; this is not presented as a fresh current-head bundle request.

Genuine native outcomes

  • Folder snapshot restored and remained writable: scrollback grew from 275 to 605 bytes after current-run input/output.
  • Git snapshot restored independently and remained writable: scrollback grew from 156 to 426 bytes.
  • Folder/Git switching preserved correct workspace names, one-tab identity, controls, and distinct terminal handles.
  • Live Reconnect succeeded.
  • Stopping only the exact runtime created for this run left the full echo offline_retained_currentrun && pwd draft visible while Send was disabled. Restarting exact head at the same profile/port auto-reconnected, retained the draft, re-enabled Send, and executed it on the same terminal term_d8ad1fd0-2750-4445-b1b5-017010c21e87, PTY serve-cad76e80-9c7c-48d6-93b6-084589a8601e, incarnation 5cd67cd3-fbda-44be-a895-6f08f946a031.
  • Last-tab close passed: long-press Terminal 1 -> Close produced 0 tabs, No tabs in this session, and Create Tab.

Honest limitations and blocker

Immediately after tapping Create Tab, the owning Orca app/runtime and both Orca-managed emulator helpers disappeared. Orca later restarted, but orca emulator list remained running: false and ports 3100/3101 had no listeners. A later list finally showed the reserved iPhone on 3100; the single supported iPad attach then replaced it and reported the approved iPad on 3100 rather than required 3101. That exact iPad helper was immediately stopped without UI input, no third stream was created, and the explicit stop condition ended the retry.

Last-tab reopen, background/foreground, deletion/recreation, duplicate host/path isolation, and portrait/landscape/split-width checks therefore remain unrun. Ordinary folder -> Git -> folder unsent-draft retention did not pass (the field returned to its placeholder), so only the stronger offline/runtime-restart retained-input result is claimed. No safe SSH/relay target existed in the isolated profile, and no current-run screenshot is attached; the existing screenshot remains evidence only from the earlier 72010c run.

The smallest external action is to restore both intended helpers directly (reserved iPhone/3100 and approved iPad/3101), or fix/provide a supported attach path that preserves the iPhone stream and allocates the iPad to 3101, before resuming the remaining scenarios. No Xcode build was rerun, no source/configuration/lockfile was edited, and the PR remains open and unmerged.

Main integration (August 2, 2026)

GitHub previously marked this PR as conflicting with main. It now contains a normal merge commit—no rebase, force-push, or history rewrite—from main 922268af10932937d35ee25c6a2af50f5a4aabb6 into the previous PR head ced9fd53215d55ac7ec55ee3d3e21714ee3e3ccf. The current PR head is 4eded16e859df3459e0b4130417a314e6751ecb4.

The two genuine conflict files were src/main/persistence.ts and src/main/runtime/orca-runtime.ts. The persistence resolution keeps main’s current owner/spill-partition cleanup and topology-fence behavior, preserves the PR’s host-isolated legacy fallback and reconnect-target pruning, and avoids materializing unwritten host partitions. The runtime resolution keeps both main’s legacy numeric pane-key parser and the PR’s SSH PTY ID conversion. Merge-only compatibility work added the required PTY spawn disposition to main’s detached-pane test fixtures and moved background pane spawning into a focused module so the combined file remains under the max-lines limit.

Validation on Node 24:

  • Merged conflict/PR suite: 21 files, 2,189 tests passed, one existing skip.
  • Additional merge-path suites: detached restart 16/16; background launch 9/9; isolated relay agent execution 10/10; worktree directory polling 21/21.
  • Broad suite: 44,012 tests passed and 78 skipped. Four environment/current-main-only failures remained after isolation: three root-directory-guard assertions require Bash 4 associative arrays while macOS ships Bash 3, and the current-main deleted-macOS-daemon-cwd test still times out locally. The other four broad-run failures passed in isolation after removing Orca’s injected Git config or scheduler contention.
  • Root Node typecheck and mobile typecheck passed.
  • Full lint passed: default, native-plugin, type-aware, reliability manifest, max-lines ratchet, bundled-skill, and localization gates.
  • All 49 PR-changed files passed formatting; changed-code quality reported zero code-quality, type-aware, or React Doctor findings; git diff --check passed.
  • Root lockfile is unchanged from main (Git blob dbe19cf1e7acf98b90472a4a90329bd45d4fd1fe); mobile/pnpm-lock.yaml is unchanged from both main and the previous PR head (Git blob 9788413f92587fc2e15f3de5ea0f504a02841778).
  • No Electron app, simulator, native QA lane, Computer Use, or UI automation was started.

GitHub no longer reports a merge conflict. PR CI settled with 41 successful checks, one intentionally skipped E2E check, and no failures or pending PR Checks. Greptile Review is still running; fresh review and the remaining native revalidation are still required before merge.

Newest main reconciliation (August 3, 2026)

GitHub returned this PR to DIRTY / CONFLICTING because main advanced after the prior merge. The pre-reconciliation local, upstream, remote, and GitHub PR head was exactly 4eded16e859df3459e0b4130417a314e6751ecb4; its integrated base was 922268af10932937d35ee25c6a2af50f5a4aabb6. The first newly fetched base was b04bd82394b3d05dfeebb275a6be070f8680b0bf (42 commits beyond the prior base), and main advanced four more commits during validation to final base 17df980b7d76cf0e076b50915775f61dae885556.

Both bases were integrated with ordinary non-force merge commits: 00e6c3d4068e06adda59bd88c72396ebc48c21a7 for b04bd82394b3d05dfeebb275a6be070f8680b0bf, followed by the conflict-free 06c8863cf632712681fa60091396cc5be6eee1f7 for 17df980b7d76cf0e076b50915775f61dae885556. There was no rebase, force-push, history rewrite, or PR merge.

The genuine first-merge conflicts were src/main/ipc/pty.ts, src/main/ipc/pty.test.ts, src/main/runtime/orca-runtime.ts, and src/renderer/src/components/terminal-pane/pty-transport.ts. The resolution preserves the PR's host/path/freshness/session reservation identity, participant retirement, folder/Git and SSH/relay ownership, deletion/recreation and reconnect fences, while retaining current-main stable-pane hydration/adoption, degraded-daemon routing, provisional Agent Teams cleanup, and focus coalescing. src/shared/stable-pane-id.ts now also rejects a live or persisted stable pane owner when its host-aware spawn-time cwd no longer matches the current folder route.

Final Node 24 validation on 06c8863cf632712681fa60091396cc5be6eee1f7:

  • 23 root affected/integration test files passed: 2,375 tests passed and one existing test skipped.
  • The new mobile foreground-redial regression passed: 6 tests.
  • Node, CLI, web, and mobile TypeScript checks passed.
  • Default, native-plugin, type-aware, and mobile Oxlint passed.
  • Changed-code quality reported zero new code-quality, type-aware, or React Doctor findings across all 49 PR-changed files.
  • Max-lines ratchet passed with no new bypasses; the 62-gate reliability manifest passed.
  • All 49 PR-changed files passed formatting and git diff --check. The repository-wide formatter still identifies 14 unrelated current-main baseline files; none are in the PR diff.
  • Root and mobile lockfiles are byte-for-byte identical to final main: edd1f3e41e4defcc9f94f9d791fe7ceba3ba6f9c and 9788413f92587fc2e15f3de5ea0f504a02841778.

No simulator, Electron QA, screenshot, Computer Use, or OS-level UI automation was started. Fresh exact-head review, newly triggered CI, and the remaining native acceptance scenarios are still required before merge.

CI ordering-contract follow-up (August 3, 2026)

PR Checks run 30855241742 passed every job except Node 24 and Node 26 shard 7 (and the dependent verify job). Both shards failed only src/main/ipc/pty-startup-barrier-ordering.test.ts: the conflict resolution had resolved the provider before the startup-barrier source contract under the name earlyProvider, then aliased it to provider inside the guarded block.

Commit 33d64d78aa8197b115104e911216921303ef113b preserves the runtime behavior while restoring the contract’s direct const provider = getProvider(args.connectionId) declaration after the pending runtime-create barrier. The exact PR head is now 33d64d78aa8197b115104e911216921303ef113b; current main and the integrated base remain 17df980b7d76cf0e076b50915775f61dae885556.

Post-fix validation passed under Node 24: the ordering regression plus the full PTY IPC suite (450 tests), the Node/CLI/web TypeScript checks, focused Oxlint, and git diff --check. The ordering regression also passed under Node 26 (1 test). A second pre-push fetch confirmed main had not advanced; the push was normal and non-force, no simulator or Electron/UI automation was started, and fresh exact-head review plus native acceptance remain required before merge.

Post-CI newest-main race reconciliation (August 3, 2026)

After PR Checks run 30855633590 completed with 41 successful jobs and one intentionally skipped E2E job on 33d64d78aa8197b115104e911216921303ef113b, the final remote race check found main had advanced from 17df980b7d76cf0e076b50915775f61dae885556 to 7de40ffbd8b1e087fb432a8dd2c0ccac0d658d1f. The single new main commit was 7de40ffbd8b1e087fb432a8dd2c0ccac0d658d1f (fix(terminal): stop keyboard effect re-registering on every pane render), changing TerminalPane.tsx and adding the focused expand/collapse render-stability implementation and regression.

Newest main merged conflict-free with a third ordinary non-force merge commit, 3604e28accedd79dbd6697cf16841b4f1d9b52cc; there was no rebase, force-push, history rewrite, or PR merge. Local/upstream/remote head before this final push was 33d64d78aa8197b115104e911216921303ef113b, and the exact pushed PR head is now 3604e28accedd79dbd6697cf16841b4f1d9b52cc with integrated base 7de40ffbd8b1e087fb432a8dd2c0ccac0d658d1f.

Node 24 final-merge validation passed four focused files and 456 tests: the startup-barrier ordering regression, full PTY IPC suite, expand/collapse suite, and new render-stability suite. Node/CLI/web and mobile TypeScript passed; full default, native-plugin, type-aware, and mobile Oxlint passed; changed-code quality reported zero findings across 49 files; the 62 reliability gates, max-lines ratchet, 49-file formatter check, and git diff --check passed. Root/mobile lockfiles still match newest main exactly at blobs edd1f3e41e4defcc9f94f9d791fe7ceba3ba6f9c and 9788413f92587fc2e15f3de5ea0f504a02841778; no simulator, Electron, Computer Use, or UI automation was started. Fresh exact-head review and native acceptance remain required before merge.

Final exact-head CI settlement

PR Checks run 30856329701 completed successfully on exact head 3604e28accedd79dbd6697cf16841b4f1d9b52cc: 41 jobs succeeded, E2E was intentionally skipped, and there were no failures or pending checks. A final fetch and live GitHub read confirmed local, upstream, remote, and PR heads all match that OID; current main, merge base, and GitHub base all match 7de40ffbd8b1e087fb432a8dd2c0ccac0d658d1f; GitHub reports MERGEABLE / CLEAN, not DIRTY / CONFLICTING.

@coderabbitai

coderabbitai Bot commented Aug 1, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

Adds deleted-folder workspace tombstones with normalized ownership data and bounded retention. Persistence cleanup handles workspace aliases, shared tabs, host partitions, SSH leases, reconnect targets, delayed writes, and ambiguous PTY bindings. Runtime recovery resolves canonical owners, fences PTY inventories, restores persisted sessions, filters stale snapshots, and handles workspace deletion and recreation. Tests cover persistence, ownership, recovery, and stale-spawn handling.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 7.84% 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
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly identifies the primary change: restoring folder session tab snapshots for mobile.
Description check ✅ Passed The description explains the user-visible change, risks, testing, security impact, platform limits, and follow-up status in substantial detail.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@greptile-apps

greptile-apps Bot commented Aug 1, 2026 •

Copy link
Copy Markdown

Greptile Summary

This PR fixes post-restart input failure in Orca Mobile folder workspace session tabs by properly reattaching the runtime to surviving PTYs before returning a writable activation. Before, PTY inventory refresh proved liveness but not attachment to the current runtime generation; after, serve/SSH-owned tabs that lack a live runtime PTY binding trigger an explicit reattach before the caller can send input.

  • Core reattach fix: shouldMaterializePendingTerminal now forces materialization for serve/SSH-owned tabs when hasLiveRuntimeSessionOwnedPtyBinding is false, even if the public tab already reports status === 'ready' from inventory. After materialization the caller applies its own host-activation intent independently.
  • Concurrency model: Concurrent activations share one physical reattach via pendingMobileTerminalMaterializations keyed on host/session/tab/leaf/freshness/reconnect-generation; each waiter rechecks its own mutation and reconnect fences before publishing navigation or activating the headless tab. PTY creation is coordinated across renderer/runtime via a new pane-spawn-reservation.ts retirement-token protocol.
  • Durable folder removal: Deleted folder workspaces now record tombstones (capped at 512 entries, pruned after 30 days) with per-host tab evidence; the overflow bucket system handles evicted entries across create/delete cycles.

Confidence Score: 5/5

The change is safe to merge. All critical paths have targeted automated test coverage (2,148 tests per the description), the core reattach fix is narrowly scoped to serve/SSH-owned tabs, and the retirement-token protocol is self-contained with a clear lifecycle bounded by PTY teardown.

No functional defects were found in the diff. The materialization coalescing key, retirement token protocol, and folder workspace mutation fences are all logically consistent. The only observations are minor: a linear scan in forgetPaneSpawnRetirement that is bounded in practice, a silent early-return in persistHeadlessTerminalActiveLeaf that is correct fail-closed behaviour but emits no diagnostic, and an intentional semantic change to inventory generation acceptance that is correctly cross-validated. The pre-existing resolveWorkspaceSessionRecordOwnerKey divergence between persistence.ts and orca-runtime.ts (flagged in earlier reviews) is unchanged. Tombstone size bounds added by this PR (MAX_TOMBSTONES=512, 30-day expiry) address the prior unbounded-growth concern.

Files Needing Attention: src/main/runtime/orca-runtime.ts and src/main/ipc/pty.ts carry the most complex logic changes; the retirement-token paths in pty.ts and the materialization coalescing in orca-runtime.ts are the highest-value areas for a second human read.

Important Files Changed

Filename Overview
src/main/runtime/orca-runtime.ts Core runtime logic: adds materialization coalescing map, folder workspace mutation fences, and the key shouldMaterializePendingTerminal fix for serve/SSH tabs; navigation-intent is now separated from shared reattachment; large and complex but well-tested per description.
src/main/ipc/pane-spawn-reservation.ts New module: coordinates per-scope PTY spawn reservations with retirement-token protocol; creator and waiter tokens share one PaneSpawnRetirement; adoption cancels all tokens, release counts down to last abandoner. Logic is correct and bounded by PTY lifecycle via forgetPaneSpawnRetirement.
src/main/ipc/pty.ts Extends spawn path with CreatorOnlyPtyRetirementToken; retirement now centralises PTY shutdown, registration rollback, binding/lease cleanup, and ownership deletion; guards many catch-block cleanups behind !freshPtySetupRetirement to avoid double-work. Persistence-failure catch block removes inline PTY shutdown in favour of the outer retirement path.
src/main/persistence.ts Adds tombstone recording for deleted folder workspaces; deleteOwnerKeyedSessionFields now iterates alias key forms and handles exclusivelyRemovedTabIds to prevent shared-tab layout/activeTabId corruption; introduces a second resolveWorkspaceSessionRecordOwnerKey using alias enumeration (differs from the runtime's runtimeWorktreeIdsEqual approach - pre-existing concern).
src/main/deleted-folder-session-tombstones.ts New file: implements the tombstone system with MAX_TOMBSTONES=512 cap, 30-day retention, overflow-bucket eviction into 24-hour buckets, and bounded per-tombstone host/tab evidence; size is well-bounded addressing the previous P2 concern.
src/shared/stable-pane-id.ts Adds PaneSpawnReservationKey type and makePaneSpawnReservationKey; host-aware canonical path normalisation correctly dispatches Windows/WSL/POSIX rules; reservation key includes provider, connection, runtime, workspace, spawn path, freshness, session, and pane key.
src/main/runtime/mobile-terminal-materialization-key.ts New file: encodes materialization identity as JSON including workspaceFreshness and reconnectGeneration, ensuring stale callers cannot coalesce with current ones.
src/shared/terminal-spawn-reservation-freshness.ts New helper: encodes workspace and reconnect freshness as a JSON string; returns null when both inputs are null to avoid keying reservations on a null-only fingerprint unnecessarily.
src/main/ipc/pty-spawn-reservation-path-flavor.ts New helper: resolves path-canonicalisation flavor (posix/windows/unknown) from connection ID, WSL distro prefix, and local platform for use in reservation key construction.
src/main/deleted-folder-tombstone-overflow-normalization.ts New file: validates and normalises the overflow bucket array on load; prunes expired buckets and enforces per-kind identity caps.

Sequence Diagram

sequenceDiagram
    participant Caller as Mobile Activation Caller
    participant Runtime as OrcaRuntimeService
    participant Mat as pendingMobileTerminalMaterializations
    participant PTY as ptyController.spawn
    participant Reservation as PaneSpawnReservation
    participant Store as Persistence

    Caller->>Runtime: activateMobileSessionTab(worktreeId, tabId)
    Runtime->>Runtime: createMobileSessionFolderWorkspaceMutationFence()
    Runtime->>Runtime: refreshMobileSessionPtyRecords(fence, connectionId)
    Runtime->>Runtime: shouldMaterializePendingTerminal?
    Note over Runtime: status=ready AND hasServeOrSshOwned AND NOT hasLiveRuntimeSessionOwnedPtyBinding

    Runtime->>Mat: get(materializationKey)?
    alt No pending materialization
        Runtime->>Mat: set(materializationKey, promise)
        Runtime->>Runtime: "createRuntimeOwnedMobileSessionTerminal(targetsHost=false)"
        Runtime->>PTY: "spawn({ acceptWorkspaceInventory, spawnReservationFreshness })"
        alt Concurrent waiter joins
            PTY->>Reservation: awaitPaneSpawnReservation(existing)
            Reservation-->>PTY: result with spawnDisposition awaited
        end
        PTY->>PTY: reattach to surviving PTY
        PTY-->>Runtime: id with spawnDisposition reattached
        Runtime->>Store: persistHostSessionBinding
    else Existing materialization
        Runtime->>Mat: await existing promise
    end

    Runtime->>Runtime: acceptMaterialization() fence check
    Runtime->>Runtime: hasLiveRuntimeSessionOwnedPtyBinding?
    alt targetsHost AND tab not yet active
        Runtime->>Runtime: activateHeadlessMobileSessionTerminalTab()
    end
    Runtime->>Caller: applyMobileSessionTabNavigation()
Loading

Reviews (19): Last reviewed commit: "Merge origin/main into mobile-folder-ses..." | Re-trigger Greptile

@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 (7)
src/main/persistence.ts (2)

4630-4680: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the owner-keyed record list into one shared helper.

The same list of owner-keyed session records now appears three times: getWorkspaceSessionOwnerKeys (lines 2538-2552), workspaceSessionReferencesOwner (lines 4645-4659), and pruneDeletedFolderWorkspaceSessionOwners (lines 5105-5119). A future owner-keyed field added to one list and missed in the others silently breaks either ownership detection or deleted-folder pruning. Extract one accessor, for example getOwnerKeyedSessionRecords(session), and use it in all three places.


4941-4960: 🚀 Performance & Scalability | 🔵 Trivial | ⚖️ Poor tradeoff

Cache the catalog connection ids instead of recomputing them per write.

collectCatalogConnectionIds calls resolveWorkspaceSessionPtyConnectionId once per folder workspace. Each call performs linear scans over folderWorkspaces, projectGroups, and repos, plus inferFolderScopeConnectionIdForMigration. The cost is therefore O(folders × (folders + groups + repos)).

pruneDeletedFolderReconnectTargets runs on every setWorkspaceSession and every owner-bearing patchWorkspaceSession for a host that owns at least one tombstone, and it also rescans every host partition through collectWorkspaceSessionRemoteConnectionIds. On a large catalog this adds measurable work to each persistence write. Consider memoizing the catalog connection ids and invalidating them when repos, projectGroups, or folderWorkspaces change.

src/main/runtime/orca-runtime.ts (3)

4885-4904: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Use folderWorkspaceKey instead of the folder: literal.

Lines 4890 and 4894 build the workspace key with a template literal, while Line 4906 parses it with parseWorkspaceKey. The module already imports folderWorkspaceKey. Use it so the producer and the parser cannot diverge if the key format changes.

♻️ Proposed refactor
-        .map((folderId) => `folder:${folderId}`)
+        .map((folderId) => folderWorkspaceKey(folderId))
-        const worktreeId = `folder:${folderId}`
+        const worktreeId = folderWorkspaceKey(folderId)

4769-4793: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Rename the shadowed projectGroups binding.

Line 4769 declares projectGroups for the lazy initialization at Line 4830. Line 4777 declares a second const projectGroups inside the else block, which shadows it. Both are correct at runtime, but the outer variable stays null while the inner one holds a value in the same function. Rename the inner binding, for example fallbackProjectGroups, to remove the ambiguity.


29866-29883: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Name the tombstone retention bound.

Line 29875 hard-codes 512. The file already uses a named constant for the same bounded-tombstone pattern (MAX_NATIVE_CHAT_LAUNCH_DRAFT_RESOLUTION_TOMBSTONES). Add an equivalent constant, for example MAX_REMOVED_MOBILE_SESSION_TAB_TOMBSTONES, so the retention limit is discoverable and tunable in one place.

src/main/runtime/mobile-session-graph-owner-normalization.test.ts (1)

37-60: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Propagate worktreeId into the embedded snapshot fixture.

makeGraph accepts worktreeId but builds mobileSessionTabs from makeSnapshot() with the default WORKTREE_ID. In the scoped-alias test at Line 75, the graph tabs and leaves use the scoped key while the embedded snapshot still declares the raw owner. The scoped snapshot owner path is therefore not exercised. Pass worktreeId to makeSnapshot so the fixture matches the test name.

♻️ Proposed fixture change
-function makeGraph(worktreeId: string, title: string) {
+function makeGraph(worktreeId: string, title: string) {
   return {
     tabs: [
       {
         tabId: TAB_ID,
         worktreeId,
         title,
         activeLeafId: LEAF_ID,
         layout: null
       }
     ],
     leaves: [
       {
         tabId: TAB_ID,
         worktreeId,
         leafId: LEAF_ID,
         paneRuntimeId: 1,
         ptyId: PTY_ID,
         paneTitle: null
       }
     ],
-    mobileSessionTabs: [structuredClone(makeSnapshot())]
+    mobileSessionTabs: [structuredClone(makeSnapshot(worktreeId, title))]
   }
 }

Confirm the expected event payload after this change, because the snapshot title then also becomes Renamed.

src/main/runtime/mobile-session-pty-inventory-fencing.test.ts (1)

358-364: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use a distinct leafId value instead of INCARNATION_ID.

This fixture passes INCARNATION_ID as the leafId. The pane key and the incarnation id then share the same value. If the runtime confuses a leaf id with an incarnation id, this test still passes. Every other fixture in this cohort uses separate identifiers.

♻️ Proposed fixture change
-        ['local', makeSession({ worktreeId, ptyId, tabId: 'old-path-tab', leafId: INCARNATION_ID })]
+        [
+          'local',
+          makeSession({
+            worktreeId,
+            ptyId,
+            tabId: 'old-path-tab',
+            leafId: '99999999-9999-4999-8999-999999999999'
+          })
+        ]

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: f89ac062-2501-475d-aa5e-14ad63eec140

📥 Commits

Reviewing files that changed from the base of the PR and between 072133f and 750fa4c.

📒 Files selected for processing (12)
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/runtime/mobile-folder-session-stale-state.test.ts
  • src/main/runtime/mobile-folder-session-tabs.test.ts
  • src/main/runtime/mobile-session-folder-host-ownership.test.ts
  • src/main/runtime/mobile-session-graph-owner-normalization.test.ts
  • src/main/runtime/mobile-session-pty-host-partition.test.ts
  • src/main/runtime/mobile-session-pty-inventory-fencing.test.ts
  • src/main/runtime/mobile-session-worktreeless-pty-recovery.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/shared/constants.ts
  • src/shared/types.ts

Comment thread src/main/persistence.test.ts Resolved
Comment on lines +4696 to 4712
if (uniquePersistedHostIds.length > 1) {
throw new Error('workspace_session_host_ambiguous')
}
const exactHostIds = [
...new Set(
repos
.filter((repo) => areWorktreePathsEqual(repo.path, parsed.worktreePath))
.map((repo) => getRepoExecutionHostId(repo))
)
]
if (exactHostIds.length === 1) {
return exactHostIds[0]!
}
throw new Error('workspace_session_host_ambiguous')
}
const repo = repos[0] ?? this.store?.getRepo?.(getRepoIdFromWorktreeId(resolvedWorktreeId))
return repo ? getRepoExecutionHostId(repo) : LOCAL_EXECUTION_HOST_ID

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 | 🏗️ Heavy lift

Read-only session lookups can now throw workspace_session_host_ambiguous.

tryGetWorkspaceSessionHostIdForWorktree now throws when duplicate repository IDs resolve to more than one host. getWorkspaceSessionForWorktree (Line 4723) calls it without a guard, and several read-only callers reach it, for example getTerminalTopologyRevision (Line 15730) via listTerminals and adoptTerminalOrphans. Before this change those paths fell back to a repository-derived host and never threw, so terminal.list degraded gracefully.

Prefer failing closed only on write paths. For read paths, either catch the ambiguity in getWorkspaceSessionForWorktree and return null, or add an explicit non-throwing resolver used by readers.

🛠️ Proposed fix for read-only lookups
   private getWorkspaceSessionForWorktree(worktreeId: string): WorkspaceSessionState | null {
-    const hostId = this.tryGetWorkspaceSessionHostIdForWorktree(worktreeId)
-    return hostId ? (this.store?.getWorkspaceSession?.(hostId) ?? null) : null
+    let hostId: ExecutionHostId | null
+    try {
+      hostId = this.tryGetWorkspaceSessionHostIdForWorktree(worktreeId)
+    } catch {
+      // Ambiguous ownership is not readable; writers still fail closed.
+      return null
+    }
+    return hostId ? (this.store?.getWorkspaceSession?.(hostId) ?? null) : null
   }

Comment thread src/main/runtime/orca-runtime.ts Resolved

@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/main/deleted-folder-session-tombstones.ts (1)

41-71: 🚀 Performance & Scalability | 🔵 Trivial

Note the soft-cap trade-off: MAX_TOMBSTONES is not a hard ceiling during rapid churn.

excess eviction only removes entries once they pass MIN_DELETED_FOLDER_TOMBSTONE_RETENTION_MS (24 hours). If more than 512 folders are deleted within a 24-hour window, all tombstones stay in the persisted state until they age past 24 hours, so the map can temporarily exceed 512 entries by an unbounded amount tied to churn volume. This design is deliberate and covered by the "retains recent deletion fences before applying the tombstone soft cap" test, so it is not a defect. For very high churn scenarios (bulk automation deleting many folders quickly), consider whether an absolute ceiling is needed to bound persisted-file growth, independent of the 24-hour protection window.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 12ae2d29-fc11-4331-a799-c1a9ba2082c7

📥 Commits

Reviewing files that changed from the base of the PR and between 750fa4c and d2e128b.

📒 Files selected for processing (6)
  • src/main/deleted-folder-session-tombstones.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/runtime/mobile-folder-session-mutation-race.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/shared/types.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/shared/types.ts
  • src/main/persistence.ts
  • src/main/runtime/orca-runtime.ts

@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: 2

Caution

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

⚠️ Outside diff range comments (1)
src/main/runtime/orca-runtime.ts (1)

26082-26129: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Thread the folder-workspace mutation fence through runCreateMobileSessionTerminal's headless branch too.

createRuntimeOwnedMobileSessionTerminal now accepts and forwards acceptWorkspaceInventory (lines 26098, 26128-26129), and activateMobileSessionTab correctly builds this fence with createMobileSessionFolderWorkspaceMutationFence before calling it (around line 8137). This function has a second call site inside runCreateMobileSessionTerminal's !win branch (around lines 25833-25851). That call site does not call assertMobileSessionFolderWorkspaceExists or createMobileSessionFolderWorkspaceMutationFence, and does not pass acceptWorkspaceInventory.

runCreateMobileSessionTerminal performs real async work before that branch: resolveTerminalWorkspaceLaunchScope and resolveMobileSessionTerminalCommand (which can itself await markLocalWorkspaceTrustedForAgent/markRemoteWorkspaceTrustedForAgent). If the folder workspace's identity, connection, or execution host mutates during that window, this path spawns and binds the PTY without the fence rejecting it — the exact race this commit closes for activateMobileSessionTab and closeMobileSessionTab remains open for the createMobileSessionTerminal RPC's headless creation path.

hydrateHeadlessMobileSessionTabsFromWorkspaceSession does not substitute for this: it silently no-ops when the folder id no longer resolves to a host instead of signaling staleness, and resolveFolderWorkspaceLaunchScope only detects full deletion of the folder workspace id, not an in-place identity/host reassignment.

Mirror the pattern used in activateMobileSessionTab: assert existence, build the fence before the awaits, and pass it through to createRuntimeOwnedMobileSessionTerminal.

🛠️ Proposed fix for the missing fence in `runCreateMobileSessionTerminal`
   private async runCreateMobileSessionTerminal(
     worktreeSelector: string,
     opts: {...} = {}
   ): Promise<RuntimeMobileSessionCreateTerminalResult> {
     const pairedCreate = Boolean(opts.clientNavigationId)
     const graphEpoch = this.captureReadyGraphEpoch()
     const workspace = await this.resolveTerminalWorkspaceLaunchScope(worktreeSelector)
     const worktreeId = workspace.id
     const cwd = this.resolveWorkspaceTerminalStartupCwd(workspace, opts.cwd)
+    this.assertMobileSessionFolderWorkspaceExists(worktreeId)
+    const acceptWorkspaceInventory =
+      this.createMobileSessionFolderWorkspaceMutationFence(worktreeId)
     this.hydrateHeadlessMobileSessionTabsFromWorkspaceSession(worktreeId)
     ...
     const startupCommand = await this.resolveMobileSessionTerminalCommand(workspace, opts)
     this.assertStableReadyGraph(graphEpoch)
     if (opts.signal?.aborted) {
       throw new Error('client_disconnected')
     }
+    this.assertMobileSessionFolderWorkspaceExists(worktreeId)
+    if (acceptWorkspaceInventory?.() === false) {
+      throw new Error('tab_not_found')
+    }
     const win = this.getAvailableAuthoritativeWindow()
     if (!win) {
       return await this.createRuntimeOwnedMobileSessionTerminal(
         worktreeId,
         opts.activate !== false,
         opts.afterTabId,
         {
           command: startupCommand.command,
           cwd,
           env: startupCommand.env,
           envToDelete: startupCommand.envToDelete,
           startupCommandDelivery: startupCommand.startupCommandDelivery,
           launchAgent: startupCommand.launchAgent,
           viewMode: opts.viewMode,
           targetGroupId: opts.targetGroupId,
           launchConfig: startupCommand.launchConfig,
-          signal: opts.signal
+          signal: opts.signal,
+          acceptWorkspaceInventory
         }
       )
     }

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: b7c8cc57-e790-4bf5-aca9-13748043a973

📥 Commits

Reviewing files that changed from the base of the PR and between d2e128b and 889a4a9.

📒 Files selected for processing (8)
  • src/main/deleted-folder-session-tombstones.ts
  • src/main/ipc/pty.test.ts
  • src/main/ipc/pty.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/main/runtime/mobile-folder-session-mutation-race.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/shared/types.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • src/shared/types.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts

Comment thread src/main/ipc/pty.ts
Comment on lines +4151 to +4169
const assertWorkspaceInventoryAccepted = (): void => {
if (args.acceptWorkspaceInventory?.() === false) {
throw new Error('tab_not_found')
}
}
const rejectStaleWorkspaceSpawn = async (candidate: PtySpawnResult): Promise<void> => {
if (args.acceptWorkspaceInventory?.() !== false) {
return
}
if (candidate.isReattach !== true) {
try {
await provider.shutdown(candidate.id, { immediate: true })
} catch (error) {
console.warn('[pty] failed to clean up stale workspace spawn:', error)
}
clearProviderPtyState(candidate.id)
}
throw new Error('tab_not_found')
}

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.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Description: Inspect how cancelPendingPtyRegistration and releaseRejectedPtyRegistrationFence use incarnationId.
set -euo pipefail

FILE=$(fd -t f 'orca-runtime.ts' src/main/runtime | head -n1)
echo "Inspecting: $FILE"
rg -n -A 15 'cancelPendingPtyRegistration\s*\(' "$FILE" | head -n 60
echo "---"
rg -n -A 15 'releaseRejectedPtyRegistrationFence\s*\(' "$FILE" | head -n 60

Repository: stablyai/orca

Length of output: 3117


🏁 Script executed:

#!/bin/bash
set -euo pipefail

FILE=$(fd -t f 'pty.ts' src/main/ipc | head -n1)
echo "Inspecting: $FILE"
wc -l "$FILE"
sed -n '4100,4260p' "$FILE" | cat -n
echo "--- runtime functions ---"
ORCA=$(fd -t f 'orca-runtime.ts' src/main/runtime | head -n1)
sed -n '9940,10045p' "$ORCA" | cat -n
sed -n '25300,25380p' "$ORCA" | cat -n
echo "--- surrounding search ---"
rg -n "reportPtySpawnCommitted|rejectedRegistrationCandidate|cancelPendingPtyRegistration|releaseRejectedPtyRegistrationFence|agent_session_exited_during_start|agentSessionEnsure" $FILE $ORCA

Repository: stablyai/orca

Length of output: 23325


Move physical-commit handling before rejectStaleWorkspaceSpawn.

When args.acceptWorkspaceInventory?.() === false after a successful provider spawn, rejectStaleWorkspaceSpawn shuts down and throws before rejectedRegistrationCandidate receives the spawned result. The tab_not_found path then leaves rejectedRegistrationCandidate null, so releaseRejectedPtyRegistrationFence receives no incarnationId and cancelPendingPtyRegistration(..., rejectedRegistrationCandidate?.incarnationId) cannot match the pending registration. Do the same for reportPtySpawnCommitted() before the shutdown. Set rejectedRegistrationCandidate (and call reportPtySpawnCommitted()) before rejectStaleWorkspaceSpawn() in both the agentSessionEnsure spawn closure and the plain spawn else branch.

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

♻️ Duplicate comments (1)
src/main/deleted-folder-session-tombstones.ts (1)

22-25: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Unresolved: host-eviction can still drop a host owning a retained tab mapping.

This range is unchanged in the current revision. A previous review flagged that candidateHostIds.slice(-MAX_HOST_IDS) can evict a host that owns a retained tab mapping in retainedTabEntries, because Set does not move a duplicate host to the end of iteration order. Since lines 1-48 are marked unchanged, this issue is still present. Prioritize hosts referenced by retainedTabEntries before filling remaining capacity with other host IDs, as suggested in the earlier review.

Also applies to: 39-47


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 4e96809c-8f42-4011-a135-58dd654f0ba3

📥 Commits

Reviewing files that changed from the base of the PR and between e9e7dfb and 4d62514.

📒 Files selected for processing (4)
  • src/main/deleted-folder-session-tombstones.ts
  • src/main/persistence.test.ts
  • src/main/persistence.ts
  • src/shared/types.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • src/shared/types.ts
  • src/main/persistence.ts

Resolve conflicts between the folder-session snapshot work and main:

- persistence.ts: persistPtyBinding keeps main's boolean CAS on
  expectedBinding, run against the folder-aware resolved owner key so a
  stale caller returns false instead of throwing.
- orca-runtime.ts: syncMobileSessionTabs takes main's withheld-snapshot
  (unchanged worktrees) path over our normalized owner keys; resync
  requests echo the renderer's raw id since its delivery memo is keyed
  that way. storedMobileSnapshotHasStalePreservedTab takes main's
  identity-key param plus our workspaceSession arg.
- orca-runtime.ts: terminal materialization keeps our serve/SSH
  liveness check and main's parked-pane refusal for automatic activation.
- orca-runtime.test.ts: both sides inserted a block before the same
  test; keep both.
- pty.ts / pty-transport-types.ts: additive, union of both sides.
PTY inventory proves a session survived the restart, not that this runtime
generation attached to it. terminal.send carries no activation ordering, so a
client holding a handle could type while the reattach was still in flight and
have the input rejected against the unattached session.

Park the send on the pending reattach instead. The barrier sits on the send
path, so every caller — mobile, CLI, orchestration — inherits it rather than
each activation entry point having to gate first.

Keyed by the persisted session id, which is what a sender resolves from the
leaf and what materialization reattaches, so the two meet on the same key.
The wait is placed before the proven-absence probe: a session mid-attach would
otherwise read as absent and reject a legitimate send.
@brennanb2025

Copy link
Copy Markdown
Contributor Author

Close this older combined recovery patch after creating a GitHub issue for restored terminals that display correctly but ignore input. #19247 is the focused candidate for that remaining fix.

The remaining problem is tracked in #27649.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant