Skip to content

fix(runtime): prune stale headless session tabs - #9053

Closed
nikuscs wants to merge 4 commits into
stablyai:mainfrom
nikuscs:fix-headless-stale-session-tabs
Closed

nikuscs wants to merge 4 commits into
stablyai:mainfrom
nikuscs:fix-headless-stale-session-tabs

Conversation

@nikuscs

@nikuscs nikuscs commented Jul 16, 2026 •

Copy link
Copy Markdown

Summary

Fix stale headless terminal and agent state in worktree.ps after terminals are closed.

Problem

  • orca terminal list --json could return no terminals while orca worktree ps --json still reported a positive liveTerminalCount.
  • Persisted tabs with no live PTY were counted as active terminals.
  • Completed agent rows could remain after their tab was closed and reappear after restart.
  • Dead serve-owned tabs could remain visible to mobile and remote clients.

Changes

  • Count terminals only when the renderer graph or PTY provider confirms they are live.
  • Treat persisted tabs as restore data, not proof that a terminal is running.
  • Use fresh provider results when available.
  • Preserve the cached state when provider liveness cannot be checked.
  • Prune dead serve-owned tabs without removing live, pinned, pending, or unrelated tabs.
  • Clear persisted agent-hook rows when a terminal tab is closed.
  • Hide completed or stale agent rows when their terminal no longer exists.
  • Keep fresh active agent rows during short tab synchronization gaps.

Tests added

  • Prunes an unpersisted dead serve-owned tab missing from the desktop graph.
  • Does not materialize a dead tab selected before refresh.
  • Treats a tab pruned during close as successfully closed.
  • Prunes dead tabs from terminal listings and publishes the updated snapshot.
  • Keeps a serve-owned tab when its PTY is still live.
  • Keeps state when PTY liveness cannot be confirmed.
  • Does not automatically prune pinned tabs.
  • Prunes only the dead parent from a mixed snapshot.
  • Does not count a saved final tab after the provider confirms its PTY closed.
  • Does not count a stale graph leaf missing from fresh provider results.
  • Does not treat deferred startup hints as live terminals.
  • Removes retained completed agent rows when no live tab exists.
  • Clears agent-hook status when a serve-owned terminal tab is closed.

Validation

  • 796 runtime tests
  • 234 agent-hook and session projection tests
  • 62 remote-server parity and web session synchronization tests
  • pnpm typecheck
  • Oxlint on changed files
  • pnpm check:max-lines-ratchet
  • pnpm build reached packaging but failed because lipo could not find the generated architecture binaries in the local build environment

Screenshots

No visual changes.

Security

No security-sensitive behavior or permissions changed.

@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown
Contributor

Caution

Review failed

An error occurred during the review process. Please try again later.


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 commented Jul 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Runtime mobile session preparation now reconciles dead serve-owned terminal tabs using refreshed PTY liveness and protected-state checks. Pruned snapshots update metadata and are published, while activation and closing distinguish reconciled closures from unknown tabs. Host and worktree summaries now use refreshed live terminal data, and closed-tab agent status entries are removed. Tests cover pruning, lifecycle behavior, liveness, pinning, mixed snapshots, status filtering, and notifier calls.

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
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.
Title check ✅ Passed The title is concise and accurately summarizes the main runtime change: pruning stale session tabs.
Description check ✅ Passed The description is mostly complete, but it misses the template's AI Review Report, Security Audit, and Notes sections.

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

🧹 Nitpick comments (1)
src/main/runtime/orca-runtime.test.ts (1)

18158-18215: 🎯 Functional Correctness | 🔵 Trivial | ⚡ Quick win

Exercise multiple leaves under the stale parent.

This case has only one stale leaf, so it does not prove parent-level pruning. Add another dead terminal with parentTabId: 'stale-tab'; the existing expected result should verify that every child is removed.

Based on PR objectives, all tabs belonging to a dead serve-owned terminal parent must be pruned.


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: e0c7faf7-c14c-4111-a0ef-4683b6ce7b6a

📥 Commits

Reviewing files that changed from the base of the PR and between 92fc79e and aaca3a2.

📒 Files selected for processing (2)
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts

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.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: be5cb55d-d7c0-4934-9af9-c0a20edcf68e

📥 Commits

Reviewing files that changed from the base of the PR and between aaca3a2 and b151bd4.

📒 Files selected for processing (3)
  • src/main/index.ts
  • src/main/runtime/orca-runtime.test.ts
  • src/main/runtime/orca-runtime.ts

Comment on lines +6900 to 6908
private dropAgentStatusEntriesForClosedTab(tabId: string): void {
for (const paneKey of this.latestAgentStatusByPaneKey.keys()) {
if (parsePaneKey(paneKey)?.tabId === tabId) {
this.latestAgentStatusByPaneKey.delete(paneKey)
}
}
const generation = this.nextPtyLifecycleGeneration++
this.ptyLifecycleGenerationById.set(ptyId, generation)
return generation
this.dropAgentStatusEntriesByTabPrefixFn?.(tabId)
}

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

Ensure legacy pane keys are reliably matched for cleanup.

If parsePaneKey returns null/undefined for legacy pane keys (e.g., tabId:paneRuntimeId), those entries will be skipped and leak in memory. Checking if the paneKey starts with ${tabId}: provides a safe fallback that correctly captures both standard (tabId::leafId) and legacy formats for cleanup.

🛠️ Proposed fix to cover legacy pane keys
   private dropAgentStatusEntriesForClosedTab(tabId: string): void {
     for (const paneKey of this.latestAgentStatusByPaneKey.keys()) {
-      if (parsePaneKey(paneKey)?.tabId === tabId) {
+      if (parsePaneKey(paneKey)?.tabId === tabId || paneKey.startsWith(`${tabId}:`)) {
         this.latestAgentStatusByPaneKey.delete(paneKey)
       }
     }
📝 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
private dropAgentStatusEntriesForClosedTab(tabId: string): void {
for (const paneKey of this.latestAgentStatusByPaneKey.keys()) {
if (parsePaneKey(paneKey)?.tabId === tabId) {
this.latestAgentStatusByPaneKey.delete(paneKey)
}
}
const generation = this.nextPtyLifecycleGeneration++
this.ptyLifecycleGenerationById.set(ptyId, generation)
return generation
this.dropAgentStatusEntriesByTabPrefixFn?.(tabId)
}
private dropAgentStatusEntriesForClosedTab(tabId: string): void {
for (const paneKey of this.latestAgentStatusByPaneKey.keys()) {
if (parsePaneKey(paneKey)?.tabId === tabId || paneKey.startsWith(`${tabId}:`)) {
this.latestAgentStatusByPaneKey.delete(paneKey)
}
}
this.dropAgentStatusEntriesByTabPrefixFn?.(tabId)
}

@AmethystLiang AmethystLiang added the orca-remote-server Remote Orca Server / orca serve / paired remote runtime label Jul 22, 2026
@AmethystLiang

Copy link
Copy Markdown
Contributor

Related to #9952 (sessions vanishing over remote Orca link).

@nwparker

Copy link
Copy Markdown
Contributor

Closing as superseded — every bug this PR describes is real, but all four were fixed on main while this sat open, by a stronger mechanism. Evidence below.

The decisive check

tests/e2e/remote-terminal-tab-retirement.unit.test.ts (merged in #10053) covers exactly this PR's domain: a pinned remote agent terminal whose PTY exits. Run against both trees:

Clean origin/main:

 RUN  v4.1.5 /private/tmp/prbash/main-9053-ctl

 Test Files  1 passed (1)
      Tests  1 passed (1)
   Duration  8.55s

This PR's head (d3a1d30):

 ❯ tests/e2e/remote-terminal-tab-retirement.unit.test.ts:189:37
    187|     expect(retiredPublication.publicationEpoch).toBe(livePublication.p…
    188|     expect(retiredPublication.snapshotVersion).toBeGreaterThan(livePub…
    189|     expect(retiredPublication.tabs).toEqual([])
       |                                     ^

 Test Files  1 failed (1)
      Tests  1 failed (1)

The pinned tab survives a genuine host PTY exit on this branch, because the "never auto-prune pinned tabs" rule outranks a real exit signal. main retires it correctly.

Main's runtime can't even be imported into this tree any more (Cannot find module '../../shared/agent-session-host-authority'), which is itself a measure of how far the two have diverged.

Each claim, against current main

  1. liveTerminalCount inflated by persisted tabs — fixed by fix(terminal): make remote workspace sleep converge #9874 (300ee19950), which deleted the same summary.liveTerminalCount = Math.max(summary.liveTerminalCount, tabs.length) line this PR removes.
  2. Persisted tabs treated as liveness proof — main added freshPtyLiveness gating on both the leaf and PTY loops (orca-runtime.ts:14552, :14596), plus ownership-conflict resolution this PR doesn't have.
  3. Dead serve-owned tabs visible to remote clients — solved host-authoritatively by fix(terminal): make remote agent sessions host-authoritative #9687: mobile-session-terminal-retirement.ts, mobile-session-terminal-persistence-retirement.ts, workspace-session-terminal-membership-authority.ts, driven from onPtyExit with durable persist-then-publish.
  4. Agent rows surviving tab close — main clears rows at three PTY-exit sites via clearAgentRowSnapshotsForPty, filters stale rows with isFreshNonDoneAgentStatus, and dropStatusEntriesByTabPrefix already exists, wired at ipc/agent-hooks.ts:99, with load-time TTL pruning of the on-disk cache.

Why not merge it anyway

The two designs are opposed, and adopting this one would be a regression:

  • main: event-driven and host-authoritative. A PTY exit is the single retirement trigger; persistence commits before publication; only individually-accepted surfaces are removed (exactOnly: true).
  • This PR: poll-driven and inference-based. reconcileDeadServeSessionTabs infers death from a tab's absence in a listProcesses() result, on every listMobileSessionTabs / activateMobileSessionTab / close call.

The guards here are real — null on controller timeout, and skipping when authoritativeWindowId === null or graphStatus !== 'ready' (which does close the startup race). But the staleness predicate ultimately rests on isServeOwnedPtyId, a bare ptyId.startsWith('serve-') test, and prunes any parent absent from this.tabs and persisted state. main deliberately stopped trusting a listing gap that way. Given @AmethystLiang linked this to #9952 ("Sessions appear to being killed at random over the remote Orca link" — still open), reintroducing polling-based pruning is a risk we shouldn't take.

Credit

@nikuscs — the diagnosis was correct and every symptom you reported was a real bug. orca terminal list --json disagreeing with worktree ps --json was exactly the right thing to chase. #9874 and #9687 landed a more durable fix for the same set of problems. Thanks for the careful writeup and the repro detail; it made verifying this straightforward.

Verified on macOS at d3a1d30 vs origin/main; no changes pushed to this branch.

@nwparker

Copy link
Copy Markdown
Contributor

Superseded by #9874 and #9687 — see the evidence comment above. Closing.

@nwparker nwparker closed this Jul 26, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

orca-remote-server Remote Orca Server / orca serve / paired remote runtime

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants