Skip to content

fix(terminal): resume a relaunched workspace's sleeping agents only when shown - #29459

Merged
Jinwoo-H merged 4 commits into
mainfrom
fix/relaunch-lazy-wake
Oct 17, 2026
Merged

Jinwoo-H merged 4 commits into
mainfrom
fix/relaunch-lazy-wake

Conversation

@Jinwoo-H

@Jinwoo-H Jinwoo-H commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 11 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​839 $\color{#cf222e}{\Huge{\mathbf{−}}}$​1 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​838
Prod 14 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​225 $\color{#cf222e}{\Huge{\mathbf{−}}}$​25 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​200

ELI5

When Orca restarts and its agents are asleep, opening a workspace used to wake every sleeping agent in it at once. Now only the agents you can actually see wake up. The others wake when you switch to their tab.

What Changed

Before: relaunch Orca (with every agent asleep, for example after a reboot), then open a workspace with five agent tabs. All five agents restart immediately, even though only one tab is on screen.

After: only the agents in panes on screen restart:

  • the tab you are looking at, including every pane of a split;
  • the visible tab of each side-by-side group.

Every other tab's agent restarts when you open that tab. This is the same thing that already happens to agents Orca puts to sleep while it is running. A phone opening the workspace, or a CLI or orchestration request for a specific terminal, still starts those agents immediately. Nothing new is shown, and a sleeping tab looks the same as before.

Mechanism: every terminal tab of the opened workspace is mounted, and each pane's connect step resumed its agent from the saved sleeping record without checking whether the pane was visible.

  • Now a hidden pane with a sleeping record arms the existing "wake when shown" hook used for in-session sleep (hibernatedWakeTarget) and starts nothing.
  • For a local session, the hidden pane first asks the host whether the session is still alive. Only a definite "exited" holds it, and the reveal re-runs the same reattach, so the restored scrollback is kept. A live or unknown session attaches as before.
  • A held pane counts as owning its agent, so workspace activation does not relaunch the agent in a second tab.
  • A background mount request for specific tabs marks those tabs' agents to start right away.

Why

The in-session sleep path already resumes only on show. Reusing its wake hook keeps one behaviour for both cases instead of a second, parallel mechanism.

I considered keeping hidden tabs unmounted instead. That still needs the same liveness question answered, and it would drop live agents' notifications.

Known limitations

  • Paired remote-server panes still resume when they mount. The renderer has no per-session liveness answer from a paired host, so holding them would risk treating "unknown" as "exited".
  • SSH panes are covered: the relay reports a gone session, and the pane then holds it.
  • Accepted, low:
    • The "Reopened N terminals" count after a newer-daemon hold release can undercount panes that are now held until shown.
    • If a phone wake hits a workspace with a sleeping record whose tab cannot be resolved, it still mounts the whole workspace, as on main.
    • A phone viewing a single held tab (without opening the workspace) shows it asleep until the workspace wake or a desktop reveal. This is the same as in-session sleep today.

Visual Proof

N/A for screenshots: nothing on screen changes. The behaviour is proven in a hidden real app (ORCA_BACKGROUND_LAUNCH=1, throwaway profile). The test uses a stand-in agent binary that logs every resume, kills the daemon while Orca is closed, then relaunches:

Scenario main this branch
3 agent tabs, open workspace all 3 resume only the visible one
switch to tab 2 n/a tab 2 resumes
phone wakes workspace n/a tab 3 resumes at once
split tab plus 1 hidden tab 3 resume both split panes, hidden tab stays asleep
side-by-side groups plus 1 tab behind them all resume both visible tabs only

The e2e spec is tests/e2e/relaunch-sleeping-agents-resume-on-view.spec.ts. All 3 tests fail on main and pass here.

Testing

  • I manually tested these changes locally (hidden Electron window, macOS)
  • Automated tests added/updated

New tests:

  • unit: pty-connection-hidden-sleeping-resume.spec.ts, hidden-agent-resume-deferral.test.ts, plus ownership and phone-wake cases;
  • e2e: as above.

Each regression test fails with its fix reverted. The renderer vitest suite, pnpm tc, and check:code-quality:changed pass.

Review

An adversarial review and three delta reviews were done. Their findings are fixed: ownership while held, in-flight and fallback windows, stale holds, re-captured records, legacy pane keys, and exits the held wake did not start.

Agent skill upstream boundary

  • Not applicable.

Notes

  • Mac / Linux / Windows: renderer-only.
  • SSH: holds on the relay's "session gone" answer.
  • Paired servers: see Known limitations.
  • Mobile: the phone wake is unchanged.

Checklist

  • This PR is small and focused
  • I explained what changed and why
  • N/A with reason for screenshots
  • Self-reviewed for correctness, security, and performance
  • Cross-platform, SSH/remote, and path/shortcut impact considered
  • typecheck, tests, and the changed-code gate pass locally; CI covers the rest

…hen shown

After a relaunch every terminal tab of the opened workspace mounts, and each
pane's connect resumed its agent from the saved sleeping record whether or
not the pane was visible, so all of them restarted at once.

A hidden pane with a sleeping record now arms the same reveal wake a
hibernated pane uses and spawns nothing. A hidden local reattach first asks
the host whether the session is still alive; only an authoritative "exited"
holds it, and the reveal re-runs the same reattach. Held panes count as
owning their record so the activation sweep does not relaunch them. Targeted
background mounts (phone, CLI, orchestration) still start their tabs'
agents immediately, and the phone wake still wakes held panes.
@coderabbitai

coderabbitai Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

📝 Walkthrough

The change adds one-time wake requests for sleeping-agent records selected by worktree and tab IDs. It adds hidden-pane resume deferral based on PTY liveness, with resume holds coordinated with wake, reattachment, and PTY exit paths. Unit and end-to-end tests cover hidden-pane wake behavior, fallback paths, and resume behavior after relaunch.

Priority: ➖ Normal

Merge Risk: 🔵 Low · up to a97fb

A narrow canceled-quit race can restart an agent unexpectedly when its pane becomes visible. The impact is localized, but a small eligibility check would prevent it.

Pre-merge checks: Passed 3 · Failed 2

Failed Failed checks: 2 warnings

Check name Status Explanation Resolution
Description check Warning The description is detailed and covers the user impact, mechanism, rationale, limitations, testing, visual proof, and checklist. However, the required Linked Issue section is incomplete because it con… Add the actual linked issue reference after Fixes #. Confirm that the issue is valid and directly tracks this change.
Docstring Coverage Warning Docstring coverage is 44.19% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 43 functions across 25 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Passed Passed checks: 3 passed
Check name Status Explanation
Title check Passed The title clearly and concisely describes the primary change: deferring resume of sleeping agents until their terminal panes are shown.
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.
Full details: Description check

Explanation

The description is detailed and covers the user impact, mechanism, rationale, limitations, testing, visual proof, and checklist. However, the required Linked Issue section is incomplete because it contains only Fixes # without an issue reference.

Resolution

Add the actual linked issue reference after Fixes #. Confirm that the issue is valid and directly tracks this change.

  • Fix all pre-merge checks with AI
✨ Finishing Touches: 💡 1
📝 Generate docstrings: 💡
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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 GitHub limitations.

⚠️ Outside diff range comments (2)

🟡 Minor · Preserve targeted passive records during… · background-terminal-worktree-mount.ts:36-47

src/renderer/src/components/terminal/background-terminal-worktree-mount.ts:36-47
🩺 Stability & Availability | 🟡 Minor | ⚡ Quick win

Preserve targeted passive records during activation.

When a targeted passive record has no preserved-pane owner, activation can clear it before the mounted pane consumes its wake request. The requested terminal may then remain asleep until the user opens its tab.

Add canonical passive claim keys to wokenClaimKeys before activation runs.

Suggested fix
-  for (const record of getCanonicalPassiveWakeRecords(backgroundWakeRecords, wokenClaimKeys)) {
+  const canonicalPassiveRecords = getCanonicalPassiveWakeRecords(
+    backgroundWakeRecords,
+    wokenClaimKeys
+  )
+  for (const record of canonicalPassiveRecords) {
     const tabId = getSleepingRecordTabId(record)
     if (tabId) {
       passiveTabIds.add(tabId)
     } else {
       hasUntargetablePassiveRecord = true
     }
+    wokenClaimKeys.add(getProviderSessionClaimKey(record))
   }
🟡 Minor · Keep legacy numeric records on the guarded path. · sleeping-agent-pane-ownership.ts:219-225

src/renderer/src/lib/sleeping-agent-pane-ownership.ts:219-225
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Keep legacy numeric records on the guarded path.

isPaneSpawnDeferred(record.paneKey) does not prove ownership when record.paneKey is a legacy numeric key. A remounted pane can reuse the numeric ID, select the old record without a stable-leaf check, and re-arm the hold under that legacy key. This branch then preserves the old record as owned before the existing provider-session and activation checks, so revealing the pane can restore the old agent.

Remove the legacy deferred shortcut.

Suggested fix
   const tabId = getLegacyPaneTabId(record)
   if (!tabId) {
     return false
   }
   const tab = worktreeTabs.find((candidate) => candidate.id === tabId) ?? null
-  if (tab && isPaneSpawnDeferred(record.paneKey)) {
-    return true
-  }
   const providerKeys = getLegacyProviderSessionKeysForTab(state, record.worktreeId, tabId)

ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: abfb5deb-92fc-4153-9c95-86030d49c069
📥 Commits

Reviewing files that changed from the base of the PR and between c3ee08a and cac01e8.

📒 Files selected for processing: 3
  • src/renderer/src/components/terminal-pane/pty-connection/spawn-deferred-sleep.ts
  • src/renderer/src/lib/sleeping-agent-pane-ownership.ts
  • src/renderer/src/lib/wake-sleeping-agents-in-background.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 5 remain after this review.

# Conflicts:
#	src/renderer/src/components/terminal-pane/pty-connection/pty-exit-hibernate.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: 1


ℹ️ Review info
⚙️ Run configuration
  • Configuration used: Repository UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: e8e4d381-4cb8-4694-a78a-257794b6a0fe
📥 Commits

Reviewing files that changed from the base of the PR and between cac01e8 and a97fb1d.

📒 Files selected for processing: 3
  • src/renderer/src/components/terminal-pane/pty-connection-sleeping-resume-banner.spec.ts
  • src/renderer/src/components/terminal-pane/pty-connection/deferred-cold-restore-and-snapshot.ts
  • src/renderer/src/components/terminal-pane/pty-connection/pty-exit-hibernate.ts

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 6 remain after this review.

Comment on lines +135 to +139
// Why claim keys: a held pane can wait a whole session, and a re-capture of the same session must not strand it.
if (
!currentRecord ||
getProviderSessionClaimKey(currentRecord) !== getProviderSessionClaimKey(target.record)
) {

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 | 🟡 Minor | ⚡ Quick win

🔎 Supported by static analysis

🏁 Script executed:

sed -n '100,190p' src/renderer/src/components/terminal-pane/pty-connection/pty-exit-hibernate.ts
sed -n '260,315p' src/renderer/src/components/terminal-pane/pty-connection/pty-exit-hibernate.ts
sed -n '55,95p' src/renderer/src/components/terminal-pane/pty-connection/session-reconcile-dispose.ts
rg -n -C 3 'noteArmsHibernatedPaneWake|consumeHibernatedAgentWake|origin: .quit.|origin === .quit.' src/renderer/src

Repository: stablyai/orca

Length of output: 42184


🏁 Script executed:

set -e
printf '%s\n' '--- direct caller and surrounding lifecycle ---'
nl -ba src/renderer/src/components/terminal-pane/pty-connection/session-reconcile-dispose.ts | sed -n '1,125p'
printf '%s\n' '--- hibernate helper and consumer complete blocks ---'
nl -ba src/renderer/src/components/terminal-pane/pty-connection/pty-exit-hibernate.ts | sed -n '1,180p'
printf '%s\n' '--- sleeping-record lookup and all definitions/callers ---'
rg -n -C 5 -F -- 'getSleepingRecordForPane' src/renderer/src/components/terminal-pane/pty-connection src/renderer/src
printf '%s\n' '--- provider claim key definition ---'
rg -n -C 8 -F -- 'getProviderSessionClaimKey' src/renderer/src
printf '%s\n' '--- record update/replacement operations ---'
rg -n -C 6 -e 'sleepingAgentSessionsByPaneKey' -e 'captureAllSleepingAgentSessions' -e 'updateSleeping' -e 'replace.*Sleeping' src/renderer/src/store src/renderer

Repository: stablyai/orca

Length of output: 45656


🏁 Script executed:

set -e
printf '%s\n' '--- sleeping record access ---'
nl -ba src/renderer/src/components/terminal-pane/pty-connection/sleeping-record-access.ts | sed -n '1,95p'
printf '%s\n' '--- claim key implementation ---'
nl -ba src/renderer/src/lib/sleeping-agent-pane-ownership.ts | sed -n '1,180p'
printf '%s\n' '--- capture/update definitions ---'
rg -n -F --glob '*.ts' -e 'captureAllSleepingAgentSessions' -e 'captureSleepingAgentSession' -e 'updateSleepingAgent' -e 'clearSleepingAgentSessionsByPaneKey' -e 'setSleepingAgent' src/renderer/src/store src/renderer/src/lib
printf '%s\n' '--- relevant capture implementation blocks ---'
rg -l -F --glob '*.ts' 'captureAllSleepingAgentSessions' src/renderer/src/store src/renderer/src/lib | while read -r f; do
  echo "FILE $f"
  rg -n -C 14 -F -- 'captureAllSleepingAgentSessions' "$f"
done
printf '%s\n' '--- wake/exit tests mentioning replacement or quit ---'
rg -n -C 8 -F --glob '*pty-exit-hibernate*' -e 'quit' -e 'replace' -e 'consume' -e 'visibility' -e 'same session' src/renderer/src/components/terminal-pane/pty-connection

Repository: stablyai/orca

Length of output: 42352


🏁 Script executed:

set -e
printf '%s\n' '--- recovery action implementation ---'
nl -ba src/renderer/src/store/slices/agent-status-recovery-actions.ts | sed -n '1,145p'
printf '%s\n' '--- capture runtime and record construction ---'
nl -ba src/renderer/src/store/slices/agent-status-runtime.ts | sed -n '1,230p'
printf '%s\n' '--- quit capture callers ---'
rg -n -C 8 -F -- 'captureAllSleepingAgentSessions(' src/renderer/src --glob '!**/*.test.ts'
printf '%s\n' '--- provider-session promotion tests ---'
nl -ba src/renderer/src/store/slices/agent-status-provider-session.test.ts | sed -n '1,75p'
nl -ba src/renderer/src/store/slices/agent-status-provider-session.test.ts | sed -n '210,260p'
printf '%s\n' '--- quit capture replacement tests ---'
nl -ba src/renderer/src/store/slices/agent-status-quit-capture.test.ts | sed -n '200,305p'

Repository: stablyai/orca

Length of output: 41885


🏁 Script executed:

set -e
printf '%s\n' '--- completed-record promotion predicate ---'
rg -n -C 12 -F -- 'isCompletedPiCompatibleAgentWithLiveRecoveryRecord' src/renderer/src
printf '%s\n' '--- persistence lifecycle ---'
nl -ba src/renderer/src/app-shell/use-app-session-persistence.ts | sed -n '1,175p'
printf '%s\n' '--- all visibility resume registrations/callers ---'
rg -n -C 8 -F -- 'noteVisibilityResume' src/renderer/src --glob '*.ts' --glob '*.tsx'
printf '%s\n' '--- hibernation record construction and origins ---'
rg -n -C 12 -e 'origin: .worktree-sleep.' -e 'captureMode: .manual-worktree-sleep.' -e 'hibernat' src/renderer/src/lib/agent-hibernation-coordinator.ts src/renderer/src/store/slices/agent-status-recovery-collection.ts src/renderer/src/store/slices/agent-status-sleeping-records.ts

Repository: stablyai/orca

Length of output: 42231


🏁 Script executed:

set -e
printf '%s\n' '--- live resume anchor predicate ---'
nl -ba src/renderer/src/lib/live-resume-anchor-record.ts | sed -n '1,65p'
printf '%s\n' '--- shutdown checkpoint persistence and abort ---'
nl -ba src/renderer/src/app-shell/shutdown-checkpoint-persist.ts | sed -n '1,180p'
nl -ba src/renderer/src/lib/shutdown-checkpoint-guard.ts | sed -n '1,180p'
printf '%s\n' '--- visibility lifecycle exact block ---'
nl -ba src/renderer/src/components/terminal-pane/use-terminal-pane-lifecycle.ts | sed -n '35,70p'

Repository: stablyai/orca

Length of output: 12569


🏁 Script executed:

set -e
printf '%s\n' '--- unload prevention callers ---'
rg -n -C 12 -F -- 'preventUnloadAndScheduleShutdownCheckpointReset' src/renderer/src
printf '%s\n' '--- close request coordinator ---'
nl -ba src/renderer/src/components/window-close-request-coordinator.ts | sed -n '1,260p'
printf '%s\n' '--- close request dispatch and checkpoint events ---'
rg -n -C 12 -e 'dispatchWindowCloseRequest' -e 'ORCA_RENDERER_UNLOAD_PREVENTED_EVENT' -e 'confirmWindowClose' src/renderer/src/components src/renderer/src/app-shell

Repository: stablyai/orca

Length of output: 41926


Recheck wake eligibility before consuming the target.

If a hidden hibernation exit arms a live/done record, a quit capture can replace that record with origin: 'quit' while preserving the provider-session claim key. A later visibility resume calls consumeHibernatedAgentWake() directly, and the consumer accepts the matching key and invokes wake(). This can resume a quit record that should follow the quit-resume path instead.

Suggested fix
--- "a/src/renderer/src/components/terminal-pane/pty-connection/pty-exit-hibernate.ts"
+++ "b/src/renderer/src/components/terminal-pane/pty-connection/pty-exit-hibernate.ts"
@@ -131,12 +131,13 @@
     if (session.deps.paneTransportsRef.current.get(session.pane.id) !== session.transport) {
       return null
     }
     const currentRecord = session.getSleepingRecordForPane(useAppStore.getState())?.record
     // Why claim keys: a held pane can wait a whole session, and a re-capture of the same session must not strand it.
     if (
       !currentRecord ||
+      !noteArmsHibernatedPaneWake(currentRecord) ||
       getProviderSessionClaimKey(currentRecord) !== getProviderSessionClaimKey(target.record)
     ) {
       session.hibernatedWakeTarget = null
       session.pendingHibernatedWakeTarget = null
       return null
📝 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
// Why claim keys: a held pane can wait a whole session, and a re-capture of the same session must not strand it.
if (
!currentRecord ||
getProviderSessionClaimKey(currentRecord) !== getProviderSessionClaimKey(target.record)
) {
// Why claim keys: a held pane can wait a whole session, and a re-capture of the same session must not strand it.
if (
!currentRecord ||
!noteArmsHibernatedPaneWake(currentRecord) ||
getProviderSessionClaimKey(currentRecord) !== getProviderSessionClaimKey(target.record)
) {

@Jinwoo-H
Jinwoo-H merged commit 4b1eabd into main Oct 17, 2026
78 of 79 checks passed
brennanb2025 added a commit that referenced this pull request Oct 21, 2026
…art (#31254)

* fix(terminal): hidden tabs reconnect to sessions that survived a restart

pty:hasPty answered from the provider's attached-this-run set, so right
after a restart every surviving session read as exited and #29459's
hidden-agent hold kept live hidden tabs disconnected until shown. On an
attached-set miss, ask the host through the provider's existing liveness
probe; providers without one (the in-process provider, its own sole
owner) keep their answer.

* test: remove liveness fixture type assertion
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