Skip to content

Prevent sleeping agents from getting stranded in stale terminals - #6800

Merged
brennanb2025 merged 2 commits into
mainfrom
brennanb2025/fix-stale-agent-terminal
Jun 29, 2026
Merged

brennanb2025 merged 2 commits into
mainfrom
brennanb2025/fix-stale-agent-terminal

Conversation

@brennanb2025

@brennanb2025 brennanb2025 commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Prevent active sleeping-agent records from being claimed by preserved terminal panes unless the pane has restorable PTY/session identity and will connect during the current worktree activation.
  • Fresh-resume active hidden/layout-only sleep records instead of leaving the worktree with no running agent.
  • Keep completed hibernation evidence passive: it can preserve displayable history, but it cannot launch a new agent or suppress an active same-provider wake.

Boundary: this does not change terminal cold-restore command construction or provider resume protocols. It only changes the renderer decision about whether a sleeping agent record is already owned by a preserved pane versus needs a fresh agent tab.

Design Approach

The failure mode was in resumeSleepingAgentSessionsForWorktree: a stable-pane worktree-sleep record could be treated as owned just because the tab/layout still existed. If the preserved pane had no restorable PTY/session identity, or was hidden and would not mount/connect during activation, that ownership suppressed fresh launch and stranded the agent record.

The fix extracts pane-ownership checks into sleeping-agent-pane-ownership.ts and makes ownership require all of the following for active records:

  • matching preserved tab/layout identity
  • restorable PTY/session identity for the pane
  • evidence the pane will connect now, either as the focused terminal tab or as a visible terminal in another split group

Completed hibernation records are treated as passive evidence: displayable preserved panes may keep them, but they never start work.

Design Review

Design review completed cleanly after confirming the change targets the activation/resume decision layer instead of terminal cold-restore internals. The reviewed design kept the scope to sleeping-agent activation, stale preserved-pane ownership, split visibility, completed evidence, SSH/cross-platform assumptions, and focused regression tests.

Implementation

Implemented as designed, with one structural deviation: pane-ownership logic was moved into a dedicated module so the existing resume file did not grow a broad mixed-responsibility helper section.

Notable behavior details:

  • ownership is rechecked inside the resume loop because an earlier fresh launch can change active terminal state
  • visible non-focused split-group terminals can still own records
  • hidden/unmounted tabs with stale preserved state fresh-resume
  • passive completed duplicate evidence is cleared when an active same-provider record launches
  • duplicate active records for the same provider session launch from the newest active snapshot when no pane owns the session

Completeness / Headline Status

Headline behavior status: implemented.

Completeness verification found the original issue path covered: stale active sleep records no longer get suppressed by preserved panes that cannot connect, and duplicate/passive evidence no longer blocks active same-provider wake. The exact long-idle wall-clock reproduction was not rerun, but the minimized persisted state that causes the frozen/no-agent outcome is covered by unit and Electron validation.

Broad App Consistency

Source-of-truth behavior compared: terminal pane cold restore and worktree activation should either reconnect an owned visible preserved pane or fresh-launch the sleeping active agent record. Neighboring surfaces checked were terminal tabs, split-group visible terminals, sleeping-agent session records, completed hibernation evidence, and startup pending agent banners.

The PR preserves split-pane behavior for visible terminal groups, fixes hidden/layout-only preserved panes that incorrectly claimed ownership, and intentionally leaves terminal command construction/cold-restore fallback behavior unchanged.

Risks / Non-goals / Ambiguities

  • Accepted performance shape: the activation path now rechecks pane-owned claim keys in a way that is O(n^2) in sleeping records. That record count is terminal-pane scale, the path runs during worktree activation/startup hydration, and the perf audit accepted this over caching because state can change during the loop.
  • No live SSH runtime was exercised because the diff only changes renderer state decisions over opaque tab, pane, PTY, and provider-session IDs; no SSH relay, RPC, auth, or filesystem behavior changed.
  • The exact “leave it idle for a long time” timing was not reproduced end to end; validation used deterministic stale-state reproduction instead.
  • Non-goal: changing cold-restore command construction or adding a fallback when connectPanePty itself cannot build a provider resume command.

Perf Audit

Perf audit passed. Touched hot path is worktree activation / startup hydration of sleeping-agent records. The accepted O(n^2) gap is bounded by sleeping-record count and avoids stale cached ownership when earlier records fresh-launch and mutate active terminal state.

Code Review Loop

  • Initial code-review loop: 4 rounds, final clean. Fixes included visible split-pane ownership, completed-evidence ordering, and completed-without-pane launch prevention.
  • Final post-extraction code-review loop: 2 rounds, final clean. Fix included dynamic ownership recheck after earlier fresh resumes.

Validation

  • pnpm run typecheck
  • pnpm run lint (passed with one unrelated existing warning in useGitStatusPolling.ts)
  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resume-sleeping-agent-session.test.ts (30 tests)
  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/terminal-pane/pty-connection.test.ts -t "sleeping|cold|preserved|restore" (37 tests, 198 skipped)
  • pnpm exec oxlint src/renderer/src/lib/resume-sleeping-agent-session.ts src/renderer/src/lib/sleeping-agent-pane-ownership.ts src/renderer/src/lib/resume-sleeping-agent-session.test.ts
  • pnpm exec oxfmt --check src/renderer/src/lib/resume-sleeping-agent-session.ts src/renderer/src/lib/sleeping-agent-pane-ownership.ts src/renderer/src/lib/resume-sleeping-agent-session.test.ts && git diff --check
  • After CodeRabbit duplicate-record fix: pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/lib/resume-sleeping-agent-session.test.ts, pnpm exec oxlint ..., pnpm exec oxfmt --check ... && git diff --check
  • Commit hooks also ran oxlint, oxlint --config config/oxlint-react-doctor.json, and oxfmt --write on staged files.

Product Validation Evidence

Brennan's PR process validation verdict: land.

Electron validation used the exact worktree/branch with a temporary profile and demo-project:

  • missing PTY binding fresh-resumes and clears active plus completed duplicate records
  • visible non-focused split group with restorable PTY does not duplicate fresh resume
  • hidden/unmounted tab with PTY fresh-resumes and clears the record
  • renderer console had 0 errors; warnings were development noise

Screenshot evidence: .playwright-cli/page-2026-06-29T22-51-44-780Z.png.

Post-PR Stabilization

Completed.

  • Initial 8-minute wait found one actionable CodeRabbit comment: duplicate active records for the same provider-session claim could launch the older snapshot first.
  • Fixed in d6cbc98 by selecting the newest active duplicate when no pane owns the provider session, with a regression assertion for newer launchConfig metadata.
  • Waited 8 minutes again after the push; CodeRabbit marked the comment addressed and reported no new actionable comments.
  • verify passed. Merge state is clean.
  • CodeRabbit still shows a generic docstring-coverage warning in its generated summary; this repo/file style does not require docstrings for these local helpers, and it was not an actionable line comment.

@coderabbitai

coderabbitai Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

A new sleeping-agent-pane-ownership.ts module adds claim-key generation, passive-completed evidence detection, stable/legacy pane ownership checks, and activation/connectivity logic. resume-sleeping-agent-session.ts now uses those helpers, adds claim-key-based record selection and clearing helpers, and rewrites the resume loop to deduplicate launches and clear stale or passive-completed records. The test file is updated with active-terminal state setup and new cases for ownership, duplicate handling, and completed-record clearing.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ❓ Inconclusive The PR description is detailed and covers most template topics, but it omits the required explicit cross-platform AI review and formal screenshots/testing sections. Add the template sections explicitly, especially screenshots, checklist-style testing, a cross-platform AI review, and a standalone security audit summary.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly matches the main change: preventing sleeping agents from being stranded in stale terminals.
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.

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

Run ID: 51daa445-0fa4-4168-b65e-6e89637713e2

📥 Commits

Reviewing files that changed from the base of the PR and between ab1aac2 and 7a1f778.

📒 Files selected for processing (3)
  • src/renderer/src/lib/resume-sleeping-agent-session.test.ts
  • src/renderer/src/lib/resume-sleeping-agent-session.ts
  • src/renderer/src/lib/sleeping-agent-pane-ownership.ts

@brennanb2025
brennanb2025 merged commit a27278d into main Jun 29, 2026
1 check passed
@brennanb2025
brennanb2025 deleted the brennanb2025/fix-stale-agent-terminal branch June 29, 2026 23:49
Jinwoo-H added a commit that referenced this pull request Aug 5, 2026
…idden restorable panes (#12574)

* fix(runtime): report terminal handles disconnected on controller-proven PTY absence

leaf.connected mirrors the renderer graph (ptyId !== null), so a restored
surface whose PTY died with a prior process was listed connected/writable
forever with empty title/lastOutputAt/preview — the exact signature automation
saw on run6 workspaces after a restart. listTerminals now threads the
controller inventory it already fetches into buildTerminalSummary and demotes
only on proven absence, only for locally-scoped ids; unknown liveness and
SSH/remote scopes never demote, and no session or pane is retired.

* fix(terminal): stop forking hidden restorable panes into replacement resume tabs

paneWillConnectOnActivation still assumed the pre-keep-alive mount model, but
every non-parked tab of the active worktree mounts and connects hidden at 0x0.
Activation therefore appended a replacement resume tab per non-group-active
agent pane and handed it the sleeping record, stranding the hidden pane as a
bare shell — or forking two live surfaces onto one provider session when the
old PTY survived in the daemon. The predicate now answers "will mount and
connect": any non-web-mirror tab of the active worktree qualifies; non-active
worktrees still answer false so background wake keeps its append-based resume.

Contract change: reverses the hidden-tab expectation from #6800, whose premise
(hidden panes never connect) no longer holds; that test is updated in place.

* test(terminal): pin the remote-scope exemption and the web-mirror ownership exception

CodeRabbit flagged both exclusions as untested: a remote-runtime-scoped leaf
absent from the local inventory must stay connected (its inventory lives on
the remote host), and a web-mirror tab must not own sleeping-session recovery
(it never mounts a local pane), so the appended replacement remains its
correct resume path.

* fix(terminal): rescue just-spawned ptys from absence demotion; unpark panes owning sleeping records

Review (GPT verifier) confirmed two gaps:
- listTerminals demoted a live just-spawned PTY when listProcesses snapshotted
  before session registration (the sweep's hasPty rescue is leaf-gated), and
  federation reads one connected:false as exited. The summary's proven-absence
  check now also consults the provider's sync hasPty.
- Ordinary per-tab cold parking (30s hidden) kept a non-group-active pane
  unmounted, so a sleeping record it owns under the new ownership predicate
  could not cold-restore until the user revealed the tab. Per-tab parks now
  exempt panes owning a sleeping-session record; worktree-level parks are
  untouched (they clear on activation).

* fix(terminal): reconcile the daemon session cache on inventory; scope the park exemption to consumable records

Round-2 review confirmed two holes in the round-1 fixes:
- DaemonPtyAdapter.hasPty is cached activeSessionIds membership, and a
  successful listSessions never removed ids the authoritative inventory
  omitted — an exit missed while the socket was down kept hasPty true
  forever, and the new spawn/list-race rescue would trust it, reopening
  connected-forever for that pty. listProcesses now drops pre-request cached
  ids the inventory does not list alive (ids spawned mid-flight are snapshot-
  protected).
- The park exemption covered records a pane can never consume
  (automaticResumeBlockedBy, passive-completed evidence), pinning hidden
  panes mounted indefinitely. The exemption now lives in
  sleeping-record-park-exemption.ts and requires a consumable record.

Also pins the web-mirror replacement's resume claim and startup command
(CodeRabbit round-2).

---------

Co-authored-by: OrcaWin <[email protected]>
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…idden restorable panes (stablyai#12574)

* fix(runtime): report terminal handles disconnected on controller-proven PTY absence

leaf.connected mirrors the renderer graph (ptyId !== null), so a restored
surface whose PTY died with a prior process was listed connected/writable
forever with empty title/lastOutputAt/preview — the exact signature automation
saw on run6 workspaces after a restart. listTerminals now threads the
controller inventory it already fetches into buildTerminalSummary and demotes
only on proven absence, only for locally-scoped ids; unknown liveness and
SSH/remote scopes never demote, and no session or pane is retired.

* fix(terminal): stop forking hidden restorable panes into replacement resume tabs

paneWillConnectOnActivation still assumed the pre-keep-alive mount model, but
every non-parked tab of the active worktree mounts and connects hidden at 0x0.
Activation therefore appended a replacement resume tab per non-group-active
agent pane and handed it the sleeping record, stranding the hidden pane as a
bare shell — or forking two live surfaces onto one provider session when the
old PTY survived in the daemon. The predicate now answers "will mount and
connect": any non-web-mirror tab of the active worktree qualifies; non-active
worktrees still answer false so background wake keeps its append-based resume.

Contract change: reverses the hidden-tab expectation from stablyai#6800, whose premise
(hidden panes never connect) no longer holds; that test is updated in place.

* test(terminal): pin the remote-scope exemption and the web-mirror ownership exception

CodeRabbit flagged both exclusions as untested: a remote-runtime-scoped leaf
absent from the local inventory must stay connected (its inventory lives on
the remote host), and a web-mirror tab must not own sleeping-session recovery
(it never mounts a local pane), so the appended replacement remains its
correct resume path.

* fix(terminal): rescue just-spawned ptys from absence demotion; unpark panes owning sleeping records

Review (GPT verifier) confirmed two gaps:
- listTerminals demoted a live just-spawned PTY when listProcesses snapshotted
  before session registration (the sweep's hasPty rescue is leaf-gated), and
  federation reads one connected:false as exited. The summary's proven-absence
  check now also consults the provider's sync hasPty.
- Ordinary per-tab cold parking (30s hidden) kept a non-group-active pane
  unmounted, so a sleeping record it owns under the new ownership predicate
  could not cold-restore until the user revealed the tab. Per-tab parks now
  exempt panes owning a sleeping-session record; worktree-level parks are
  untouched (they clear on activation).

* fix(terminal): reconcile the daemon session cache on inventory; scope the park exemption to consumable records

Round-2 review confirmed two holes in the round-1 fixes:
- DaemonPtyAdapter.hasPty is cached activeSessionIds membership, and a
  successful listSessions never removed ids the authoritative inventory
  omitted — an exit missed while the socket was down kept hasPty true
  forever, and the new spawn/list-race rescue would trust it, reopening
  connected-forever for that pty. listProcesses now drops pre-request cached
  ids the inventory does not list alive (ids spawned mid-flight are snapshot-
  protected).
- The park exemption covered records a pane can never consume
  (automaticResumeBlockedBy, passive-completed evidence), pinning hidden
  panes mounted indefinitely. The exemption now lives in
  sleeping-record-park-exemption.ts and requires a consumable record.

Also pins the web-mirror replacement's resume claim and startup command
(CodeRabbit round-2).

---------

Co-authored-by: OrcaWin <[email protected]>
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