Skip to content

fix(runtime): refuse to silently wake a deliberately slept pane (STA-3465) - #12672

Merged
Jinwoo-H merged 2 commits into
mainfrom
fix/refuse-to-wake-a-deliberately-slept-pane
Aug 5, 2026
Merged

Jinwoo-H merged 2 commits into
mainfrom
fix/refuse-to-wake-a-deliberately-slept-pane

Conversation

@Jinwoo-H

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

Copy link
Copy Markdown
Contributor

Fixes STA-3465.

Symptom

A pane the user deliberately put to sleep (workspace sleep, or automatic completed-agent hibernation) can be respawned behind their back, with a freshly re-resolved agent launch, by a background reconnect probe. The user never asked for it and never sees it coming.

Cause

OrcaRuntimeService.activateMobileSessionTab decides whether to materialize a PTY from the published status alone:

const shouldMaterializePendingTerminal =
  publicTab?.type === 'terminal' &&
  publicTab.status !== 'ready' &&
  (!targetsHost || !this.notifier?.focusTerminal || this.shouldMaterializeHeadlessMobileSessionTab(...))

pending-handle is produced by exactly one predicate — no connected leaf PTY and no connected matched PTY (toMobileSessionTabsResult). Sleeping a workspace intentionally keeps the tab and its pty-id bindings and kills only the process, so a slept pane publishes pending-handle indefinitely and is, at this call site, byte-for-byte indistinguishable from a pane whose PTY was lost and is awaiting reconnect.

With navigation: 'caller' — which is what #11542's reconnect recovery loop sends (activateHostSessionSurface in remote-runtime-pty-transport.ts) — targetsHost is false, so the first disjunct short-circuits and materialization is unconditional.

This is not new: the initial-attach path already called activate before #11542. #11542's reconnect fix depends on that respawn working for genuinely-awaiting panes, which is why it was not treated as blocking.

Did a positive "deliberately slept" marker already exist?

Partly, and this is the crux, so it is worth being precise.

  • Renderer-side "parking" (sleeping-record-park-exemption.ts, use-terminal-tab-cold-parking.ts) is ephemeral React state. It is never persisted and is invisible to main. It is a hidden-view unmount optimization, a different concept from a slept pane.
  • hasWorktreeSleepIntent is an in-memory renderer module-level Set, cleared in a finally. Also invisible to main.
  • The one durable artifact is SleepingAgentSessionRecord in sleepingAgentSessionsByPaneKey on the partitioned workspace session — which main already reads elsewhere. Its origin field is the usable marker: 'worktree-sleep' is written only by captureMode: 'manual-worktree-sleep' (user sleep) and 'completed-agent-hibernation', i.e. only by a deliberate takedown. 'live' and 'quit' captures describe a pane that was still running.

So a positive marker for "this pane's PTY was deliberately taken down" does exist and is reachable from this call site; it was simply never consulted. The codebase already treats it this way — see the comment on its own write path: "hibernated completions are intentional worktree-owned records."

Fix

Gate materialization on that marker instead of inferring intent from pending-handle:

publicTab.status !== 'ready' &&
!this.isDeliberatelyParkedPane(worktreeId, tab) &&
(...)

isDeliberatelyParkedPane looks the record up by pane key in the pane's own host partition (getWorkspaceSessionForWorktree) and returns true only for origin === 'worktree-sleep' with a matching worktree id.

This follows the established rule that an ambiguous state must never authorize a surprising action — except that here the state is not ambiguous, it is positively provable, so we can refuse precisely and only when we have proof.

Verification

Six new tests in src/main/runtime/orca-runtime.test.ts under deliberately parked pane activation (STA-3465). All assert the spawn call itself, not timing.

Reproduction (red on origin/main, green after):

  • refuses to respawn a deliberately slept pane on a reconnect-driven activate (navigation: 'caller')
  • refuses to respawn a deliberately slept pane on a headless host activate

Negative tests protecting #11542 (green before and after the fix, i.e. they prove nothing was broken):

  • still materializes a pane awaiting reconnect with no sleeping record
  • still materializes a pane whose record was captured while it was live (origin: 'live')
  • still materializes a pane whose record was captured at app quit (origin: 'quit')
  • ignores a park record that belongs to a different worktree

Mutation checks:

  • removing the !this.isDeliberatelyParkedPane(...) conjunct: 2 failed / 4 passed (the two reproductions go red).
  • weakening the predicate to mere record presence (record !== undefined) instead of the park origin: 3 failed / 3 passed — the live, quit and foreign-worktree cases go red. This is the important one: it demonstrates the negative tests have teeth and that a naive "has a sleeping record" gate would have broken fix(remote-runtime): materialize the host surface when reconnecting a terminal pane #11542.
  • Restored implementation: 6 passed.

Suites: src/main + src/shared 23240 passed; the 6 failures (ssh-connection-sftp-namespace, pty-subprocess, port-scan-command-execution) reproduce identically on clean origin/main in this environment and are unrelated. pnpm run typecheck, oxlint, oxfmt --check clean.

Deliberate trade-off, please sanity-check

The guard applies to every activate path, not only the navigation: 'caller' reconnect probe. I chose that over keying off navigation because a navigation-routing flag is a weak proxy for user intent, and because the headless orca serve topology (no focusTerminal notifier) would otherwise still let a background probe through the second disjunct.

The consequence: tapping a slept pane on a mobile client no longer respawns it through this path. The dedicated wake flows (resume-sleeping-agent-session, sleeping-agent-session-launch, wake-sleeping-agents-in-background) are unaffected — they clear the record before relaunching, and they do not route through activateMobileSessionTab.

Known residual gap (deliberately not fixed here)

A deliberately slept plain shell pane, or an agent pane with no captured provider session, leaves no durable record at all — sleepingRecordFromEntry only produces one for a resumable TUI agent with a provider session id. Those panes remain indistinguishable from awaiting-reconnect panes and will still be materialized.

Closing that gap properly needs a new pane-scoped durable marker written by shutdownWorktreeTerminals for every pane it kills under shutdownReason: 'manual-sleep' (schema + renderer store + hydration + clear-on-wake), which is a materially larger change than this one and is not needed for the reported harm. The harm called out in STA-3465 is specifically "respawns it with a re-resolved agent launch", and that is exactly the case that does carry a record. Happy to file the follow-up if you want the general case covered.

`activateMobileSessionTab` decided whether to materialize a pane from
`publicTab.status !== 'ready'` alone. A pane the user put to sleep publishes
`pending-handle` indefinitely, so it was indistinguishable there from a pane
whose PTY was lost and is awaiting reconnect — and activating it respawned it
with a freshly re-resolved agent launch the user never asked for.

Gate materialization on the durable sleeping record's `origin`. Only a
worktree-owned capture ('worktree-sleep', written by workspace sleep and by
completed-agent hibernation) records a deliberate takedown; 'live' and 'quit'
captures describe a pane that was still running, so reconnect-driven
materialization (#11542) is unchanged for them.
@coderabbitai

coderabbitai Bot commented Aug 5, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Warning

Review limit reached

@Jinwoo-H, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 43 seconds

You've used all free OSS reviews for now. Wait for the free limit to reset to keep reviewing this public repository.

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 73fae7af-4ca8-4072-909e-ecf8a99c8e3f

📥 Commits

Reviewing files that changed from the base of the PR and between 917c71f and ddb4498.

📒 Files selected for processing (14)
  • mobile/app/h/[hostId]/session/[worktreeId].tsx
  • mobile/src/session/mobile-session-tab-activation.test.ts
  • mobile/src/session/mobile-session-tab-activation.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts
  • src/main/runtime/rpc/methods/session-tabs-schemas.ts
  • src/main/runtime/rpc/methods/session-tabs.test.ts
  • src/main/runtime/rpc/methods/session-tabs.ts
  • src/renderer/src/components/terminal-pane/remote-runtime-outage-toast-flood-and-stuck-reconnect.test.ts
  • 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/web-runtime-session.test.ts
  • src/renderer/src/runtime/web-runtime-session.ts
  • src/shared/tab-activation-intent.ts
📝 Walkthrough

Walkthrough

The runtime now skips pending terminal materialization for panes with matching worktree-sleep records. Live and quit captures remain eligible for reconnection. Regression tests cover parked panes, reconnecting panes, worktree matching, and pending-handle preservation.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description explains the change, cause, tests, preserved reconnect behavior, and residual gap, but omits required review and security sections. Add the Screenshots, AI Review Report, Security Audit, and Notes sections, and list the required test checks with completion status.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly identifies the runtime fix and the STA-3465 behavior addressed.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 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.

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

Jinwoo-H commented Aug 5, 2026

Copy link
Copy Markdown
Contributor Author

Rework: refuse only automatic wakes, not the user's tap

The independent review was right to block this. Thanks — the finding was decisive and the fix below is a direct response to it.

What was wrong

The guard refused activation for any pane whose SleepingAgentSessionRecord.origin === 'worktree-sleep', on every activate path. But opening the tab is the designed wake gesture for exactly those records. From wake-sleeping-agents-in-background.ts:

a workspace the user explicitly slept must not respawn every finished agent because a phone opened it. Those panes cold-restore --resume when their own tab is opened, which is also what the desktop does (#11598).

Whether anything else clears the record first depends on topology, and three of four never do:

  1. Headless orca serve — no wake at all (sleepingAgentWake: 'unsupported-headless'). Permanent no-op.
  2. Paired desktop/web client (clientKind: 'runtime') — no wake is even requested; the gate is mobile-only.
  3. Desktop present, manual sleep of a completed agent — restoreOnTabOpenOnly: true, which the background wake skips and resume classifies pane-owned. The record survives by design.
  4. Desktop present, manual sleep of a running agent — works; resume relaunches and clears.

So in three of four topologies the pane was stranded pending-handle forever with no way back.

What the rework does

The underlying bug is still real and still fixed: pending-handle alone cannot distinguish a deliberately parked pane from one awaiting reconnect. The fix is to stop asking the pane and start asking the caller.

Mechanism — an additive optional intent: 'user' | 'automatic' on session.tabs.activate params (src/shared/tab-activation-intent.ts). Not a new stream opcode: unknown JSON keys are ignored by older hosts, so this is safe across mixed versions with no capability negotiation. Absent means permissive (treated as user intent), so a client that predates the field keeps its wake gesture — that default is pinned by its own test.

The guard is now (!isAutomaticTabActivation(opts.intent) || !this.isDeliberatelyParkedPane(...)). isDeliberatelyParkedPane itself is unchanged.

Every call site, labelled honestly:

Call site Intent
mobile/app/h/[hostId]/session/[worktreeId].tsx — switchTab, switchSessionTab (×2), pending-terminal follow-up effect user
web-runtime-session.ts callWebRuntimeSessionTabMethod — paired tab click, number shortcut, jump palette, Terminal.tsx user
remote-runtime-pty-transport.ts waitForHostSessionHandle — the pane's own open/attach user
remote-runtime-pty-transport.ts waitForResubscribeHostSessionHandle — the #11542 reconnect probe automatic

intent is a required field on the mobile helper's param type, so no mobile call site can add an activation without declaring who asked.

Test evidence

New/reworked coverage in orca-runtime.test.ts (13 tests in the STA-3465 block):

  • Per topology, a user activation still materializes a deliberately parked pane — headless serve (asserting sleepingAgentWake === 'unsupported-headless' and that the record survives first), paired clientKind: 'runtime' (asserting resumeSleepingAgents is never called), completed agent with restoreOnTabOpenOnly: true, and running agent whose wake cleared the record.
  • An automatic probe does not respawn a parked pane — both the bare and leafId param forms.
  • Absent intent behaves permissively.
  • fix(remote-runtime): materialize the host surface when reconnecting a terminal pane #11542 is intact — an automatic activate still materializes a pane with no record, and with a live, quit, or foreign-worktree record.

Plus session-tabs.test.ts (intent forwarded; omitted intent passes nothing through), remote-runtime-pty-transport.test.ts (pane-open sends intent: 'user'), and the #11542 stuck-reconnect test now asserts every reconnect activate carries intent: 'automatic'.

The test gap the review found

makeRuntimeStoreWithWorkspaceSession stubbed getWorkspaceSession: () => session ignoring hostId, so hardcoding the partition lookup to 'local' left the block green. The stub now answers for one partition only, and a new test puts the parked pane on an ssh:ssh-1 host.

Fixing the stub exposed three existing SSH reattach tests that had been relying on the loose behavior (their session lived in the local partition while their repo was SSH-hosted); they now declare 'ssh:ssh-1', which is what production actually reads.

Mutation results

Mutation Result
Remove the guard conjunct 3 fail (both automatic-probe refusals + partition test)
Weaken predicate to record !== undefined 3 fail (live, quit, foreign-worktree)
Hardcode partition lookup to 'local' now fails — 1 in this block, 6 across the file (was green in-block before)
Flip absent-intent default to restrictive (intent !== 'user') 1 fail (old-client compatibility)
Mislabel the reconnect probe as 'user' 1 fail (the #11542 stuck-reconnect test)

Verification

@Jinwoo-H
Jinwoo-H merged commit a766ee4 into main Aug 5, 2026
43 checks passed
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

Development

Successfully merging this pull request may close these issues.

1 participant