Skip to content

fix: hide completed Pi agent row after closing its terminal tab - #6584

Merged
nwparker merged 3 commits into
mainfrom
nwparker/fix-5913
Jul 11, 2026
Merged

nwparker merged 3 commits into
mainfrom
nwparker/fix-5913

Conversation

@nwparker

@nwparker nwparker commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Description

Fixes #5913.

Closing a terminal tab could leave Pi's completed compact agent row visible as Done on the workspace card. The stale entry was still in agentStatusByPaneKey, but its pane key referred to a tab that no longer existed in tabsByWorktree. The sidebar selector then used the entry's worktreeId fallback—originally added so active child agents can appear before their tab reaches the renderer—and rendered the orphan as live.

This PR hardens both lifecycle boundaries:

  • The workspace-card selector uses worktree attribution for tabless active rows, but not for a completed row whose tab is gone.
  • closeTab passes the closing worktree into agent-status teardown so it also removes completed, worktree-attributed orphan rows whose pane-key tab does not match the tab being closed. It preserves active pre-render child rows, completed rows with an open tab, and rows owned by other worktrees.

The branch was rebased onto current origin/main (c5669cceb5) and its terminal teardown conflict was resolved against the current cleanup path.

This PR supersedes community PR #5914 and preserves its original author credit in the commit.

Evidence of fix (before + after)

Before: current main selector behavior

On the rebased worktree, I temporarily restored the current-main unconditional fallback while keeping the regression assertion, then ran:

pnpm exec vitest run --config config/vitest.config.ts \
  src/renderer/src/components/sidebar/worktree-agent-row-selectors.test.ts \
  -t 'does not use worktree attribution for a completed row whose tab is gone'

Result: 1 failed. The production selector returned the stale row instead of []:

Received: [{ agentType: "pi", state: "done", tabId: "tab-1", worktreeId: "wt-1", ... }]

This reproduces the issue comment's post-close state: the completed Pi tab is absent from tabsByWorktree, but the live-status map still contains its attributed row.

After: PR head

Restoring the PR guard and running the same command produced:

Test Files  1 passed (1)
Tests       1 passed | 7 skipped (8)

The selector returned zero live rows for the orphaned done entry.

The source-level lifecycle test now calls closeTab itself. It proves that closing a tab removes the mismatched completed Pi orphan and its matching row, while retaining an active pre-render child row, a completed row with an open tab, and another worktree's orphan.

Electron sidebar evidence

I launched the rebased PR in an isolated Electron profile and injected the confirmed post-close state through the real renderer store:

  • Backing state: agentStatusByPaneKey contained a Pi done entry attributed to the visible worktree, and its tab was absent.
  • Visible workspace card: the stale completion sentinel had 0 matches and no compact Done row rendered.
  • Neighboring contract: a tabless worktree-attributed Pi working entry rendered on the same card as Working, proving the early active-row behavior remains visible.

The Pi CLI is not installed on this machine, so this Electron check exercises the production store/selector/render path but not a real Pi hook process or terminal teardown.

Validation commands

pnpm exec vitest run --config config/vitest.config.ts \
  src/renderer/src/components/sidebar/worktree-agent-row-selectors.test.ts \
  src/renderer/src/store/slices/agent-status-drop.test.ts \
  src/renderer/src/store/slices/agent-status-drop-ipc.test.ts \
  src/renderer/src/store/slices/store-cascades.test.ts
# 4 files passed, 137 tests passed

pnpm typecheck
# passed (node, CLI, and web)

pnpm exec oxlint <five changed TypeScript files>
# passed

pnpm check:reliability-gates
# passed, 31 gates

pnpm check:max-lines-ratchet
# passed, no new bypasses

git diff --check origin/main...HEAD
# passed

pnpm lint passes oxlint, switch exhaustiveness, styled-scrollbar checks, reliability-manifest validation, and the max-lines ratchet, then stops on an unrelated current-main localization mismatch in ja.json for components.native-chat.composer.uploadingAttachments. This PR does not edit localization files.

ELI5

The sidebar has a backup rule: if an agent's tab has not appeared yet, use the workspace name on its badge so the user can still see that active agent. Pi could leave an old badge behind after its finished tab was closed, so the backup rule kept seating a ghost at the table.

Now the backup rule still helps agents that are actively working or waiting for attention, but it does not revive a finished agent whose tab is gone. Closing a tab also sweeps that specific kind of finished orphan from memory.

User-facing trade-offs

  • Improvement: closing a finished Pi terminal no longer leaves a misleading Done row on the workspace card.
  • Preserved behavior: active tabless child-agent rows still appear early; completed rows with a real open tab and rows in other worktrees remain untouched.
  • Completion timing: a done live-status entry that has no renderer tab is hidden rather than shown through the early-attribution fallback. Completed-session history remains the responsibility of the existing retained-agent path.
  • Close-time work: a user-triggered terminal close performs one bounded pass over the worktree's open tabs and current live agent entries to find mismatched completed orphans. It adds no polling, provider listing, subprocess, startup wait, or background wake loop.
  • Provider/platform scope: the rule is based on structured tab, worktree, and agent state—not process names, filesystem paths, or local-only APIs—so local, daemon, SSH, WSL, and remote-runtime status rows follow the same contract. Live Pi/SSH/WSL/remote-provider runs remain unverified here.

Terminal/session reliability proof

  • Reliability class: agent-session.tab-close-status-ownership.
  • Invariant: closing a terminal retires the tab's agent-status evidence and completed worktree-attributed orphans, without deleting active pre-render children, open-tab completions, or another worktree's rows.
  • Failure source: issue [Bug]: Pi compact agent row remains after closing its terminal tab #5913; Pi's completed row had mismatched pane/tab identity after close.
  • Product change type: runtime hardening plus deterministic renderer-state regression coverage.
  • Oracle: the production workspace-card selector returns zero rows for the confirmed orphan state, and the closeTab test proves the orphan is removed at the lifecycle source while the three preservation cases survive.
  • Performance risk inventory: touched paths are the workspace-card status index and user-triggered tab close. The selector adds one state comparison inside its existing bounded pass; close adds one bounded live-entry/open-tab scan. No typing, PTY output, focus, resize, startup, provider listing, SSH transport, WSL transport, hidden output, or mobile/relay loop changed.
  • No-regression evidence: 137 focused tests, full typecheck, changed-file oxlint, manifest validation, max-lines ratchet, and the Electron sidebar check above.
  • Provider/platform coverage: macOS Electron store/render path covered; local/daemon/SSH/WSL/remote-runtime and Linux/Windows are structurally unaffected by provider- or platform-specific code, but real integration runs were not performed. Mobile/relay does not consume this desktop workspace-card selector.
  • Diagnostics: no new logs or telemetry; future failures remain inspectable through tabsByWorktree, agentStatusByPaneKey, and the deterministic selector/closeTab assertions.
  • Manifest/promotion status: no dedicated gate (none). The existing agent-session.provider-ownership gate is unchanged and does not claim this display-cleanup invariant; a new manifest entry would be premature without a real Pi integration fixture.
  • Residual gaps: no installed Pi binary for a real hook-driven Electron close; no live SSH/WSL/remote-provider run; full repo lint is blocked by the unrelated localization mismatch described above.
  • Rollback/demotion rule: revert the orphan sweep/selector guard if a legitimate completed session with no tab must remain a live compact row, or if terminal-close profiling shows material latency; retain the red/green regression as the decision oracle.

Security audit

No new input parsing, command execution, path handling, auth, secret, dependency, IPC, or network surface is introduced. The fix operates on existing structured in-memory state.

Made with Orca 🐋

@coderabbitai

coderabbitai Bot commented Jun 28, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 3c4312f0-65c3-47c3-936b-9bdb688efeff

📥 Commits

Reviewing files that changed from the base of the PR and between 84aa3b5 and b2bc6b9.

📒 Files selected for processing (2)
  • src/renderer/src/store/slices/agent-status-drop.test.ts
  • src/renderer/src/store/slices/agent-status.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/renderer/src/store/slices/agent-status.ts

📝 Walkthrough

Walkthrough

Completed agent entries are now hidden when their tabs are absent. Tab-close cleanup can identify completed orphan entries within the closing tab’s worktree and remove related status, launch, retention, and acknowledgement state. The closing tab now passes its worktree scope to cleanup, with tests covering removal of targeted entries and preservation of unrelated rows.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Description check ⚠️ Warning The description covers the fix and testing, but it is missing required template sections like Screenshots and an explicit AI Review Report. Add the required headings—Summary, Screenshots, Testing, AI Review Report, Security Audit, and Notes—and explicitly confirm cross-platform review.
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.
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title is concise and accurately summarizes the main user-visible fix.
Linked Issues check ✅ Passed The code matches #5913 by hiding completed orphan rows, preserving active tabless rows, and adding tests for close-tab cleanup.
Out of Scope Changes check ✅ Passed The selector change, close-tab cleanup, and regression tests are all directly tied to the stale Pi row fix.
✨ 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.

@nwparker

Copy link
Copy Markdown
Contributor Author

Evidence

1. Regression test fails on the pre-fix tree

With only the new test added and the source fallback reverted (git stash on the .ts), the selector returns the stale done Pi entry instead of []:

 ❯ src/renderer/src/components/sidebar/worktree-agent-row-selectors.test.ts:172:68
    expect(selectLiveAgentStatusEntriesForWorktree(state, 'wt-1')).toE…
 Test Files  1 failed (1)
      Tests  1 failed | 7 passed (8)

2. Passes after the fix (8/8)

$ ./node_modules/.bin/vitest run --config config/vitest.config.ts \
    src/renderer/src/components/sidebar/worktree-agent-row-selectors.test.ts
 Test Files  1 passed (1)
      Tests  8 passed (8)

3. Full sidebar suite — no neighboring regressions

$ ./node_modules/.bin/vitest run --config config/vitest.config.ts \
    src/renderer/src/components/sidebar/
 Test Files  149 passed (149)
      Tests  1261 passed (1261)

4. Live verification in the running Electron renderer (CDP attach)

Attached to the dev build of this branch (5913 @ nwparker/fix-5913) and exercised the actual fixed selectLiveAgentStatusEntriesForWorktree against both scenarios:

{"doneOrphanRows":0,"doneOrphanStates":[],"activeChildRows":1,"activeChildStates":["working"]}
  • Orphaned done Pi entry whose tab is gone -> 0 rows (the stale compact row is swept; bug fixed).
  • Active working child entry whose tab is not yet in the renderer -> 1 row, state working (the Show worktree child agents inline #4371 early-child-agent fallback is preserved; no regression).

5. Local gate

  • oxlint on both changed files: clean.
  • tsgo --noEmit -p config/tsconfig.tc.web.json: clean (exit 0).

Before / after reasoning

Before: worktreeId = tabIdToWorktreeId.get(parsed.tabId) ?? entry.worktreeId. For a closed-tab done entry, tabIdToWorktreeId.get(...) is undefined, so the fallback entry.worktreeId re-attributes it -> buildWorktreeAgentRows renders a permanent Done row.

After: worktreeId = tabWorktreeId ?? (entry.state === 'done' ? undefined : entry.worktreeId). The done entry yields undefined and is skipped; non-done child entries keep the early-attribution behavior.

@nwparker

Copy link
Copy Markdown
Contributor Author

Note on the screenshot / live agent repro

The end-to-end visual repro (start a real Pi agent, let it reach Done, close its tab, watch the sidebar row vanish) is not deterministically drivable over CDP in this environment, since it needs a live Pi agent session. The bug is a pure selector-logic defect, so the decisive evidence is items (1)-(4) above: the regression test that fails pre-fix and passes post-fix, and the fixed selector exercised directly in the live Electron renderer returning 0 rows for the orphaned done entry while preserving 1 row for the active child entry. I attached the running dev build of this branch to confirm the fix is loaded in the renderer before running that eval.

@nwparker
nwparker force-pushed the nwparker/fix-5913 branch from ec722cd to 1d09e99 Compare June 30, 2026 00:44
@nwparker

nwparker commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor Author

Takeover update

Rebased this PR onto latest origin/main (v1.4.109-rc.0) and resolved the close-tab conflict without dropping the existing selector fix.

Tradeoff status: zero user-visible tradeoff remains. In addition to the selector backstop, closing a terminal tab now passes the closing worktree into dropAgentStatusByTabPrefix, which source-cleans completed worktree-attributed orphan live rows whose pane-key tab is no longer open. The cleanup is still narrow: it only targets done orphan rows for that worktree, so active pre-render child rows keep the early-attribution behavior.

Validation:

  • pnpm exec vitest run --config config/vitest.config.ts src/renderer/src/components/sidebar/worktree-agent-row-selectors.test.ts src/renderer/src/store/slices/agent-status-drop.test.ts src/renderer/src/store/slices/agent-status-drop-ipc.test.ts src/renderer/src/store/slices/agent-status-ack-cleanup.test.ts -> 4 files, 28 tests passed
  • pnpm exec oxlint src/renderer/src/store/slices/agent-status.ts src/renderer/src/store/slices/terminals.ts src/renderer/src/store/slices/agent-status-drop.test.ts src/renderer/src/components/sidebar/worktree-agent-row-selectors.ts src/renderer/src/components/sidebar/worktree-agent-row-selectors.test.ts -> clean
  • pnpm run typecheck:web -> clean
  • git merge-tree --write-tree origin/main HEAD -> clean merge tree

Note: this supersedes the body's earlier future-suggestion note about relying only on the selector. The selector remains as a defensive guard for stale/hydrated rows, but the normal renderer tab-close path now removes the completed Pi orphan at source.

nwparker and others added 2 commits July 10, 2026 03:08
A 'done' Pi agent entry lingers in agentStatusByPaneKey after its
terminal tab is closed: its paneKey's tabId no longer matches any open
tab, so dropAgentStatusByTabPrefix never sweeps it. The sidebar selector
getLiveEntriesByWorktree used an unconditional fallback
(tabIdToWorktreeId.get(parsed.tabId) ?? entry.worktreeId), added in
#4371 to surface early child-agent rows before their tab reaches the
renderer. That fallback re-attributed the orphaned 'done' entry to the
worktree, so buildWorktreeAgentRows rendered it as a stale live 'Done'
row forever (Codex/Claude tear down cleanly because their pane/tab
keying matches the closed tab).

Restrict the worktree-attribution fallback to non-'done' entries so
completed rows whose tab is gone are dropped, while still surfacing
active child rows whose tab has not yet reached the renderer.

Supersedes #5914 (adopted and re-verified).

Fixes #5913

Co-authored-by: Alberto Cuervo <[email protected]>
@nwparker
nwparker force-pushed the nwparker/fix-5913 branch from 1d09e99 to 84aa3b5 Compare July 10, 2026 10:15
@nwparker

Copy link
Copy Markdown
Contributor Author

Final current-head validation (supersedes the older takeover update): rebased onto origin/main c5669cc at head 84aa3b5; GitHub reports MERGEABLE/CLEAN. Exact production-selector red/green reproduced the stale pi/done row before the guard and zero rows after it. The closeTab lifecycle regression plus neighboring suites pass 137/137; full node/CLI/web typecheck, changed-file oxlint, reliability-manifest validation, max-lines ratchet, and diff check pass. Fresh GitHub verify and CodeRabbit checks both passed; CodeRabbit generated no actionable inline comments. The PR body now contains the requested Description, before/after Evidence, ELI5, User-facing trade-offs, and explicit reliability/provider/performance gaps. Full repo lint remains blocked only by the unrelated current-main ja.json localization mismatch documented in the body.

…lose

A completed-orphan key's tab is already gone, so buildRetainedAgentsSyncSnapshot
never snapshots it and no live->gone transition ever fires to consume a planted
retention suppressor. Planting one leaked a permanent retentionSuppressedPaneKeys
entry per swept orphan. Plant suppressors only for prefix-matched keys.

Co-authored-by: Orca <[email protected]>
@nwparker

Copy link
Copy Markdown
Contributor Author

Reviewed on top of latest main (clean rebase check; merge result verified byte-identical on all touched files).

  • Direction confirmed: the two-layer fix (selector guard + close-time orphan sweep) covers both the display path and the state-lifecycle source, including main-process rehydration of a stale entry.
  • One fix added during review: retention suppressors are no longer planted for swept completed-orphan keys — their tab is already gone, so no live→gone transition would ever consume the suppressor and each sweep leaked a permanent retentionSuppressedPaneKeys entry.
  • Validated: typecheck, oxlint on changed files, 138 affected tests, and a live Electron run — injected the confirmed post-close state through the real renderer store; no stale Done row rendered, a tabless working child still surfaced, and a real closeTab swept the orphan while preserving the open-tab completion, the active pre-render child, and another worktree's rows.
  • Known follow-up (pre-existing, untouched file): worktree-agent-activity-summary.ts has a parallel worktreeId fallback without the done+missing-tab guard, so after an app reload a rehydrated done-orphan can still drive the card's aggregate status dot to Done for up to 30 minutes (row stays hidden). Worth mirroring the guard there in a separate PR.

@nwparker
nwparker merged commit c51d955 into main Jul 11, 2026
2 of 3 checks passed
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
…lyai#6584)

* fix: sweep completed Pi agent row when its terminal tab is closed

A 'done' Pi agent entry lingers in agentStatusByPaneKey after its
terminal tab is closed: its paneKey's tabId no longer matches any open
tab, so dropAgentStatusByTabPrefix never sweeps it. The sidebar selector
getLiveEntriesByWorktree used an unconditional fallback
(tabIdToWorktreeId.get(parsed.tabId) ?? entry.worktreeId), added in
stablyai#4371 to surface early child-agent rows before their tab reaches the
renderer. That fallback re-attributed the orphaned 'done' entry to the
worktree, so buildWorktreeAgentRows rendered it as a stale live 'Done'
row forever (Codex/Claude tear down cleanly because their pane/tab
keying matches the closed tab).

Restrict the worktree-attribution fallback to non-'done' entries so
completed rows whose tab is gone are dropped, while still surfacing
active child rows whose tab has not yet reached the renderer.

Supersedes stablyai#5914 (adopted and re-verified).

Fixes stablyai#5913

Co-authored-by: Alberto Cuervo <[email protected]>

* fix: drop completed Pi orphan during tab close

* fix: skip retention suppressor for completed-orphan keys during tab close

A completed-orphan key's tab is already gone, so buildRetainedAgentsSyncSnapshot
never snapshots it and no live->gone transition ever fires to consume a planted
retention suppressor. Planting one leaked a permanent retentionSuppressedPaneKeys
entry per swept orphan. Plant suppressors only for prefix-matched keys.

Co-authored-by: Orca <[email protected]>

---------

Co-authored-by: Alberto Cuervo <[email protected]>
Co-authored-by: Orca <[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.

[Bug]: Pi compact agent row remains after closing its terminal tab

1 participant