diff --git a/src/renderer/src/components/WorktreeJumpPalette.tsx b/src/renderer/src/components/WorktreeJumpPalette.tsx
index 33c50e133..defa9db4a 100644
--- a/src/renderer/src/components/WorktreeJumpPalette.tsx
+++ b/src/renderer/src/components/WorktreeJumpPalette.tsx
@@ -151,6 +151,11 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
// jump palette. Without this, clicking between panes would desync the
// palette's spinner from the sidebar's spinner.
const runtimePaneTitlesByTabId = useAppStore((s) => s.runtimePaneTitlesByTabId)
+ // Why: ptyIdsByTabId is the live-pty source of truth — without it,
+ // getWorktreeStatus would treat slept tabs as live (their preserved
+ // tab.ptyId is a wake-hint sessionId, not a liveness signal) and the jump
+ // palette dot would lie green even though the sidebar dot is correctly grey.
+ const ptyIdsByTabId = useAppStore((s) => s.ptyIdsByTabId)
const prCache = useAppStore((s) => s.prCache)
const issueCache = useAppStore((s) => s.issueCache)
const activeWorktreeId = useAppStore((s) => s.activeWorktreeId)
@@ -224,9 +229,24 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
const sortedWorktrees = useMemo(
() =>
hasQuery
- ? sortWorktreesSmart(visibleWorktrees, tabsByWorktree, repoMap, prCache)
+ ? sortWorktreesSmart(
+ visibleWorktrees,
+ tabsByWorktree,
+ repoMap,
+ prCache,
+ undefined,
+ ptyIdsByTabId
+ )
: switchableWorktreesForRows,
- [hasQuery, visibleWorktrees, switchableWorktreesForRows, tabsByWorktree, repoMap, prCache]
+ [
+ hasQuery,
+ visibleWorktrees,
+ switchableWorktreesForRows,
+ tabsByWorktree,
+ repoMap,
+ prCache,
+ ptyIdsByTabId
+ ]
)
const browserSortedWorktrees = useMemo(() => {
@@ -236,8 +256,15 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
// tab on the default-branch worktree before toggling hide-on should still
// be able to Cmd+J back to it — the setting hides the *workspace row*,
// not the browser tabs that live inside it.
- return sortWorktreesSmart(allWorktrees, tabsByWorktree, repoMap, prCache)
- }, [allWorktrees, tabsByWorktree, repoMap, prCache])
+ return sortWorktreesSmart(
+ allWorktrees,
+ tabsByWorktree,
+ repoMap,
+ prCache,
+ undefined,
+ ptyIdsByTabId
+ )
+ }, [allWorktrees, tabsByWorktree, repoMap, prCache, ptyIdsByTabId])
// Why: browser rows need worktree lookups for repo badge colors, and browser
// search intentionally includes archived worktrees. This map must cover all
@@ -833,6 +860,7 @@ export default function WorktreeJumpPalette(): React.JSX.Element | null {
const status = getWorktreeStatus(
tabsByWorktree[worktree.id] ?? [],
browserTabsByWorktree[worktree.id] ?? [],
+ ptyIdsByTabId,
runtimePaneTitlesByTabId
)
const statusLabel = getWorktreeStatusLabel(status)
diff --git a/src/renderer/src/components/right-sidebar/index.tsx b/src/renderer/src/components/right-sidebar/index.tsx
index 87697ffe8..bc196b046 100644
--- a/src/renderer/src/components/right-sidebar/index.tsx
+++ b/src/renderer/src/components/right-sidebar/index.tsx
@@ -305,9 +305,7 @@ function RightSidebarInner(): React.JSX.Element {
{activityBarIcons}
-
- {closeButton}
-
+ {closeButton}
@@ -328,9 +326,7 @@ function RightSidebarInner(): React.JSX.Element {
{visibleItems.find((item) => item.id === effectiveTab)?.title ?? ''}
-
- {closeButton}
-
+ {closeButton}
)}
diff --git a/src/renderer/src/components/sidebar/WorktreeCard.test.ts b/src/renderer/src/components/sidebar/WorktreeCard.test.ts
index a0a70ea04..24aa69d63 100644
--- a/src/renderer/src/components/sidebar/WorktreeCard.test.ts
+++ b/src/renderer/src/components/sidebar/WorktreeCard.test.ts
@@ -30,15 +30,18 @@ function makeTerminalTab(title: string): TerminalTab {
describe('getWorktreeStatus', () => {
it('treats browser-only worktrees as active', () => {
- expect(getWorktreeStatus([], [{ id: 'browser-1' }])).toBe('active')
+ expect(getWorktreeStatus([], [{ id: 'browser-1' }], {})).toBe('active')
})
it('keeps terminal agent states higher priority than browser presence', () => {
- expect(getWorktreeStatus([makeTerminalTab('permission needed')], [{ id: 'browser-1' }])).toBe(
- 'permission'
- )
- expect(getWorktreeStatus([makeTerminalTab('working hard')], [{ id: 'browser-1' }])).toBe(
- 'working'
- )
+ // Why: liveness gate now requires ptyIdsByTabId, not tab.ptyId. Pass a
+ // populated live-pty map so this assertion exercises the live-tab branch.
+ const livePtyIds = { 'tab-1': ['pty-1'] }
+ expect(
+ getWorktreeStatus([makeTerminalTab('permission needed')], [{ id: 'browser-1' }], livePtyIds)
+ ).toBe('permission')
+ expect(
+ getWorktreeStatus([makeTerminalTab('working hard')], [{ id: 'browser-1' }], livePtyIds)
+ ).toBe('working')
})
})
diff --git a/src/renderer/src/components/sidebar/WorktreeCard.tsx b/src/renderer/src/components/sidebar/WorktreeCard.tsx
index ca783da65..12c565a35 100644
--- a/src/renderer/src/components/sidebar/WorktreeCard.tsx
+++ b/src/renderer/src/components/sidebar/WorktreeCard.tsx
@@ -22,8 +22,8 @@ import WorktreeCardAgents from './WorktreeCardAgents'
import { cn } from '@/lib/utils'
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
import {
- getWorktreeStatus,
getWorktreeStatusLabel,
+ resolveWorktreeStatus,
type WorktreeStatus
} from '@/lib/worktree-status'
import { isExplicitAgentStatusFresh } from '@/lib/agent-status'
@@ -39,6 +39,10 @@ import {
FilledBellIcon
} from './WorktreeCardHelpers'
import { IssueSection, PrSection, CommentSection } from './WorktreeCardMeta'
+import {
+ selectLivePtyIdsForWorktree,
+ selectRuntimePaneTitlesForWorktree
+} from './worktree-card-status-inputs'
type WorktreeCardProps = {
worktree: Worktree
@@ -123,23 +127,21 @@ const WorktreeCard = React.memo(function WorktreeCard({
// ── GRANULAR selectors: only subscribe to THIS worktree's data ──
const tabs = useAppStore((s) => s.tabsByWorktree[worktree.id] ?? EMPTY_TABS)
const browserTabs = useAppStore((s) => s.browserTabsByWorktree[worktree.id] ?? EMPTY_BROWSER_TABS)
- // Why: split-pane tabs expose per-pane titles that the aggregate
- // `tab.title` does not preserve (onActivePaneChange overwrites it with the
- // focused pane's title). getWorktreeStatus needs those pane titles to keep
- // the sidebar spinner reflecting *any* working pane, not just the focused
- // one. Narrow the subscription to this worktree's tabs via useShallow so
- // unrelated pane-title updates do not re-render every sidebar card.
+ // Why: keep these as separate shallow selectors. Combining them into one
+ // returned object nests freshly-created maps under fresh keys, so Zustand's
+ // shallow memoization sees every unrelated store write as a change and
+ // re-renders every mounted card.
+ // tab.ptyId is the wake-hint sessionId preserved across sleep, not a
+ // liveness signal; sleep-then-card-render would lie the dot green if we
+ // read tab.ptyId; ptyIdsByTabId is the source of truth.
+ // tab.title is the focused-pane title (onActivePaneChange overwrites it),
+ // so the per-pane title map is needed to keep the sidebar spinner
+ // reflecting *any* working pane, not just the focused one.
const runtimePaneTitlesForWorktree = useAppStore(
- useShallow((s) => {
- const out: Record> = {}
- for (const tab of s.tabsByWorktree[worktree.id] ?? []) {
- const paneTitles = s.runtimePaneTitlesByTabId[tab.id]
- if (paneTitles) {
- out[tab.id] = paneTitles
- }
- }
- return out
- })
+ useShallow((s) => selectRuntimePaneTitlesForWorktree(s, worktree.id))
+ )
+ const ptyIdsForWorktree = useAppStore(
+ useShallow((s) => selectLivePtyIdsForWorktree(s, worktree.id))
)
const branch = branchDisplayName(worktree.branch)
@@ -245,21 +247,33 @@ const WorktreeCard = React.memo(function WorktreeCard({
})
)
- const status: WorktreeStatus = useMemo(() => {
- if (hasPermission) {
- return 'permission'
- }
- // Compute the heuristic once so we can let 'working' beat done without
- // letting quieter heuristic states ('active'/'inactive') erase a done.
- const heuristic = getWorktreeStatus(tabs, browserTabs, runtimePaneTitlesForWorktree)
- if (heuristic === 'working') {
- return 'working'
- }
- if (hasLiveDone || hasRetainedDone) {
- return 'done'
- }
- return heuristic
- }, [tabs, browserTabs, runtimePaneTitlesForWorktree, hasPermission, hasLiveDone, hasRetainedDone])
+ // Why: resolveWorktreeStatus enforces the runtime-liveness precondition —
+ // when no tab in this worktree has a live PTY (and no browser tab exists)
+ // it short-circuits to 'inactive' before consulting hook-reported state or
+ // retained-done snapshots. That keeps the dot honest across sleep, crash,
+ // and slept-with-retained-done while preserving the row data used by the
+ // inline agents list (retained 'done' rows still render inside the card).
+ const status: WorktreeStatus = useMemo(
+ () =>
+ resolveWorktreeStatus({
+ tabs,
+ browserTabs,
+ ptyIdsByTabId: ptyIdsForWorktree,
+ runtimePaneTitlesByTabId: runtimePaneTitlesForWorktree,
+ hasPermission,
+ hasLiveDone,
+ hasRetainedDone
+ }),
+ [
+ tabs,
+ browserTabs,
+ ptyIdsForWorktree,
+ runtimePaneTitlesForWorktree,
+ hasPermission,
+ hasLiveDone,
+ hasRetainedDone
+ ]
+ )
const showPR = cardProps.includes('pr')
const showCI = cardProps.includes('ci')
diff --git a/src/renderer/src/components/sidebar/WorktreeList.tsx b/src/renderer/src/components/sidebar/WorktreeList.tsx
index 536e53894..d2b0fe0e1 100644
--- a/src/renderer/src/components/sidebar/WorktreeList.tsx
+++ b/src/renderer/src/components/sidebar/WorktreeList.tsx
@@ -18,7 +18,8 @@ import { isGitRepoKind } from '../../../../shared/repo-kind'
import {
buildExplicitEntriesByTabId,
buildWorktreeComparator,
- computeSmartScore
+ computeSmartScore,
+ hasAnyLivePty
} from './smart-sort'
import {
type GroupHeaderRow,
@@ -511,6 +512,7 @@ const WorktreeList = React.memo(function WorktreeList() {
// Read tabsByWorktree when needed for filtering or sorting
const needsTabs = showActiveOnly || sortBy === 'smart'
const tabsByWorktree = useAppStore((s) => (needsTabs ? s.tabsByWorktree : null))
+ const ptyIdsByTabId = useAppStore((s) => (needsTabs ? s.ptyIdsByTabId : null))
const browserTabsByWorktree = useAppStore((s) =>
showActiveOnly ? s.browserTabsByWorktree : null
)
@@ -601,10 +603,7 @@ const WorktreeList = React.memo(function WorktreeList() {
// Instead, restore the pre-shutdown order from the persisted sortOrder
// snapshot, and switch to the live smart score once PTYs start spawning.
if (sortBy === 'smart' && !sessionHasHadPty.current) {
- const hasAnyLivePty = Object.values(state.tabsByWorktree)
- .flat()
- .some((t) => t.ptyId)
- if (hasAnyLivePty) {
+ if (hasAnyLivePty(state.tabsByWorktree, state.ptyIdsByTabId)) {
sessionHasHadPty.current = true
} else {
nonArchivedWorktrees.sort(
@@ -642,7 +641,8 @@ const WorktreeList = React.memo(function WorktreeList() {
state.prCache,
now,
state.agentStatusByPaneKey,
- explicitByTabId
+ explicitByTabId,
+ state.ptyIdsByTabId
)
])
)
@@ -657,7 +657,8 @@ const WorktreeList = React.memo(function WorktreeList() {
null,
state.agentStatusByPaneKey,
precomputedScores,
- explicitByTabId
+ explicitByTabId,
+ state.ptyIdsByTabId
)
)
return nonArchivedWorktrees.map((w) => w.id)
@@ -684,6 +685,7 @@ const WorktreeList = React.memo(function WorktreeList() {
filterRepoIds,
showActiveOnly,
tabsByWorktree,
+ ptyIdsByTabId,
browserTabsByWorktree,
activeWorktreeId,
hideDefaultBranchWorkspace,
@@ -697,6 +699,7 @@ const WorktreeList = React.memo(function WorktreeList() {
hideDefaultBranchWorkspace,
repoMap,
tabsByWorktree,
+ ptyIdsByTabId,
browserTabsByWorktree,
sortedIds,
worktreeMap,
diff --git a/src/renderer/src/components/sidebar/smart-sort.test.ts b/src/renderer/src/components/sidebar/smart-sort.test.ts
index b56f9c2c0..ca81d96ae 100644
--- a/src/renderer/src/components/sidebar/smart-sort.test.ts
+++ b/src/renderer/src/components/sidebar/smart-sort.test.ts
@@ -6,6 +6,7 @@ import {
computeSmartScore,
CREATE_GRACE_MS,
effectiveRecentActivity,
+ sortWorktreesSmart,
type SmartSortOverride
} from './smart-sort'
import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
@@ -138,6 +139,26 @@ describe('computeSmartScore', () => {
)
})
+ it('does not reward slept wake-hint tabs as live terminals', () => {
+ const slept = makeWorktree({ id: 'slept' })
+ const tabsByWorktree = {
+ [slept.id]: [
+ makeTab({
+ id: 'tab-slept',
+ worktreeId: slept.id,
+ ptyId: 'wake-hint-session',
+ title: 'codex working'
+ })
+ ]
+ }
+
+ expect(
+ computeSmartScore(slept, tabsByWorktree, repoMap, null, NOW, undefined, undefined, {
+ 'tab-slept': []
+ })
+ ).toBe(0)
+ })
+
it('uses the current branch PR cache instead of persisted linkedPR metadata', () => {
const staleLinked = makeWorktree({
id: 'stale-linked',
@@ -441,6 +462,42 @@ describe('buildWorktreeComparator', () => {
})
})
+describe('sortWorktreesSmart', () => {
+ it('keeps cold-start persisted order when only slept wake-hint tabs exist', () => {
+ const persistedFirst = makeWorktree({
+ id: 'persisted-first',
+ displayName: 'Persisted First',
+ sortOrder: 20
+ })
+ const sleptWorking = makeWorktree({
+ id: 'slept-working',
+ displayName: 'Slept Working',
+ sortOrder: 0
+ })
+ const tabsByWorktree = {
+ [sleptWorking.id]: [
+ makeTab({
+ id: 'tab-slept',
+ worktreeId: sleptWorking.id,
+ ptyId: 'wake-hint-session',
+ title: 'codex working'
+ })
+ ]
+ }
+
+ const sorted = sortWorktreesSmart(
+ [sleptWorking, persistedFirst],
+ tabsByWorktree,
+ repoMap,
+ null,
+ undefined,
+ { 'tab-slept': [] }
+ )
+
+ expect(sorted.map((worktree) => worktree.id)).toEqual(['persisted-first', 'slept-working'])
+ })
+})
+
describe('buildWorktreeComparator — recent (lastActivityAt)', () => {
it('sorts by lastActivityAt descending (most recent first)', () => {
const older = makeWorktree({
diff --git a/src/renderer/src/components/sidebar/smart-sort.ts b/src/renderer/src/components/sidebar/smart-sort.ts
index 54867cef8..cf3c56c92 100644
--- a/src/renderer/src/components/sidebar/smart-sort.ts
+++ b/src/renderer/src/components/sidebar/smart-sort.ts
@@ -1,4 +1,5 @@
import { detectAgentStatusFromTitle, isExplicitAgentStatusFresh } from '@/lib/agent-status'
+import { tabHasLivePty } from '@/lib/tab-has-live-pty'
import { branchName } from '@/lib/git-utils'
import type { Worktree, Repo, TerminalTab } from '../../../../shared/types'
import {
@@ -47,6 +48,24 @@ export type SmartSortOverride = {
hasRecentPRSignal: boolean
}
+function terminalTabIsLive(
+ tab: TerminalTab,
+ ptyIdsByTabId?: Record | null
+): boolean {
+ // Why: slept terminals retain tab.ptyId as a wake hint, so the live PTY map is
+ // the source of truth once callers can provide it.
+ return ptyIdsByTabId ? tabHasLivePty(ptyIdsByTabId, tab.id) : Boolean(tab.ptyId)
+}
+
+export function hasAnyLivePty(
+ tabsByWorktree: Record,
+ ptyIdsByTabId?: Record | null
+): boolean {
+ return Object.values(tabsByWorktree)
+ .flat()
+ .some((tab) => terminalTabIsLive(tab, ptyIdsByTabId))
+}
+
// Why: building this index once at the sort call site reduces the smart-
// score computation from O(N × E × T) to O(E) build + O(T) lookups per
// worktree. Before, each worktree's score computation scanned the full
@@ -105,9 +124,10 @@ function computeSmartScoreFromSignals(
hasRecentPR: boolean,
now: number,
agentStatusByPaneKey?: Record,
- explicitByTabId?: Map
+ explicitByTabId?: Map,
+ ptyIdsByTabId?: Record | null
): number {
- const liveTabs = tabs.filter((t) => t.ptyId)
+ const liveTabs = tabs.filter((tab) => terminalTabIsLive(tab, ptyIdsByTabId))
let score = 0
@@ -239,7 +259,8 @@ export function buildWorktreeComparator(
smartSortOverrides: Record | null = null,
agentStatusByPaneKey?: Record,
precomputedScores?: Map,
- explicitByTabId?: Map
+ explicitByTabId?: Map,
+ ptyIdsByTabId?: Record | null
): (a: Worktree, b: Worktree) => number {
// Why: when the caller does not pre-build the tabId index but does provide
// the source map, build it ONCE here and close over it. Array.sort invokes
@@ -293,7 +314,8 @@ export function buildWorktreeComparator(
smartA.hasRecentPRSignal,
now,
agentStatusByPaneKey,
- resolvedExplicitByTabId
+ resolvedExplicitByTabId,
+ ptyIdsByTabId
)
const scoreB =
precomputedScores && !smartSortOverrides?.[b.id]
@@ -304,7 +326,8 @@ export function buildWorktreeComparator(
smartB.hasRecentPRSignal,
now,
agentStatusByPaneKey,
- resolvedExplicitByTabId
+ resolvedExplicitByTabId,
+ ptyIdsByTabId
)
return (
scoreB - scoreA ||
@@ -357,13 +380,10 @@ export function sortWorktreesSmart(
tabsByWorktree: Record,
repoMap: Map,
prCache: Record | null,
- agentStatusByPaneKey?: Record
+ agentStatusByPaneKey?: Record,
+ ptyIdsByTabId?: Record | null
): Worktree[] {
- const hasAnyLivePty = Object.values(tabsByWorktree)
- .flat()
- .some((t) => t.ptyId)
-
- if (!hasAnyLivePty) {
+ if (!hasAnyLivePty(tabsByWorktree, ptyIdsByTabId)) {
// Cold start: use persisted sortOrder snapshot
return [...worktrees].sort(
(a, b) => b.sortOrder - a.sortOrder || a.displayName.localeCompare(b.displayName)
@@ -395,7 +415,8 @@ export function sortWorktreesSmart(
prCache,
now,
agentStatusByPaneKey,
- explicitByTabId
+ explicitByTabId,
+ ptyIdsByTabId
)
])
)
@@ -414,7 +435,8 @@ export function sortWorktreesSmart(
null,
agentStatusByPaneKey,
precomputedScores,
- explicitByTabId
+ explicitByTabId,
+ ptyIdsByTabId
)
)
}
@@ -439,7 +461,8 @@ export function computeSmartScore(
prCache: Record | null,
now: number = Date.now(),
agentStatusByPaneKey?: Record,
- explicitByTabId?: Map
+ explicitByTabId?: Map,
+ ptyIdsByTabId?: Record | null
): number {
return computeSmartScoreFromSignals(
worktree,
@@ -451,6 +474,7 @@ export function computeSmartScore(
repoMap ? hasRecentPRSignal(worktree, repoMap, prCache) : worktree.linkedPR !== null,
now,
agentStatusByPaneKey,
- explicitByTabId
+ explicitByTabId,
+ ptyIdsByTabId
)
}
diff --git a/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts b/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts
new file mode 100644
index 000000000..1b010a43d
--- /dev/null
+++ b/src/renderer/src/components/sidebar/useWorktreeAgentRows.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest'
+import {
+ AGENT_STATUS_STALE_AFTER_MS,
+ type AgentStatusEntry
+} from '../../../../shared/agent-status-types'
+import type { TerminalTab } from '../../../../shared/types'
+import type { RetainedAgentEntry } from '@/store/slices/agent-status'
+import { buildWorktreeAgentRows } from './useWorktreeAgentRows'
+
+function makeTab(id: string): TerminalTab {
+ return {
+ id,
+ worktreeId: 'wt-1',
+ ptyId: null,
+ title: 'Claude',
+ customTitle: null,
+ color: null,
+ sortOrder: 0,
+ createdAt: 0
+ }
+}
+
+function makeEntry(
+ paneKey: string,
+ startedAt: number,
+ overrides?: Partial
+): AgentStatusEntry {
+ return {
+ paneKey,
+ state: 'done',
+ stateStartedAt: startedAt,
+ updatedAt: startedAt,
+ stateHistory: [],
+ prompt: 'finished prompt',
+ agentType: 'claude',
+ terminalTitle: undefined,
+ interrupted: false,
+ ...overrides
+ }
+}
+
+function makeRetained(paneKey: string, worktreeId: string, startedAt: number): RetainedAgentEntry {
+ return {
+ entry: makeEntry(paneKey, startedAt),
+ worktreeId,
+ tab: makeTab(paneKey.slice(0, paneKey.indexOf(':'))),
+ agentType: 'claude',
+ startedAt
+ }
+}
+
+describe('buildWorktreeAgentRows', () => {
+ it('includes retained rows even when their original tab is no longer current', () => {
+ const rows = buildWorktreeAgentRows({
+ tabs: [makeTab('tab-1')],
+ entries: [],
+ // Why: useWorktreeAgentRows filters retained snapshots by worktreeId, not
+ // current tab membership. This is the sidebar behavior that sleep cleanup
+ // must counter by dropping worktree-scoped retained rows.
+ retained: [makeRetained('tab-orphan:0', 'wt-1', 1000)],
+ now: 2000
+ })
+
+ expect(rows.map((row) => row.paneKey)).toEqual(['tab-orphan:0'])
+ expect(rows[0].state).toBe('done')
+ })
+
+ it('prefers a live row over a retained snapshot with the same paneKey', () => {
+ const liveEntry = makeEntry('tab-1:0', 2000)
+ const rows = buildWorktreeAgentRows({
+ tabs: [makeTab('tab-1')],
+ entries: [liveEntry],
+ retained: [makeRetained('tab-1:0', 'wt-1', 1000)],
+ now: 3000
+ })
+
+ expect(rows).toHaveLength(1)
+ expect(rows[0].entry).toBe(liveEntry)
+ expect(rows[0].startedAt).toBe(2000)
+ })
+
+ it('decays a stale working entry to idle but leaves a stale done entry alone', () => {
+ // Why: the freshness scheduler ticks agentStatusEpoch when an entry crosses
+ // the stale boundary; the row state machine must collapse working/blocked/
+ // waiting to idle but preserve done. Sleep is the most common path that
+ // freezes hook entries past their TTL.
+ const staleAt = 1000
+ const freshDoneAt = 2000
+ const now = staleAt + AGENT_STATUS_STALE_AFTER_MS + 1
+ const rows = buildWorktreeAgentRows({
+ tabs: [makeTab('tab-1'), makeTab('tab-2')],
+ entries: [
+ makeEntry('tab-1:0', staleAt, { state: 'working', updatedAt: staleAt }),
+ makeEntry('tab-2:0', freshDoneAt, { state: 'done', updatedAt: freshDoneAt })
+ ],
+ retained: [],
+ now
+ })
+
+ const working = rows.find((r) => r.paneKey === 'tab-1:0')
+ const done = rows.find((r) => r.paneKey === 'tab-2:0')
+ expect(working?.state).toBe('idle')
+ expect(done?.state).toBe('done')
+ })
+})
diff --git a/src/renderer/src/components/sidebar/useWorktreeAgentRows.ts b/src/renderer/src/components/sidebar/useWorktreeAgentRows.ts
index e5d3bebfc..c0330715a 100644
--- a/src/renderer/src/components/sidebar/useWorktreeAgentRows.ts
+++ b/src/renderer/src/components/sidebar/useWorktreeAgentRows.ts
@@ -18,6 +18,67 @@ const EMPTY_TABS: TerminalTab[] = []
const EMPTY_LIVE_ENTRIES: AgentStatusEntry[] = []
const EMPTY_RETAINED: RetainedAgentEntry[] = []
+export function buildWorktreeAgentRows(args: {
+ tabs: TerminalTab[]
+ entries: AgentStatusEntry[]
+ retained: RetainedAgentEntry[]
+ now: number
+}): DashboardAgentRow[] {
+ const rows: DashboardAgentRow[] = []
+ const seenPaneKeys = new Set()
+
+ const entriesByTabId = new Map()
+ for (const entry of args.entries) {
+ const colonIndex = entry.paneKey.indexOf(':')
+ if (colonIndex === -1) {
+ continue
+ }
+ const tabId = entry.paneKey.slice(0, colonIndex)
+ const bucket = entriesByTabId.get(tabId)
+ if (bucket) {
+ bucket.push(entry)
+ } else {
+ entriesByTabId.set(tabId, [entry])
+ }
+ }
+
+ for (const tab of args.tabs) {
+ const explicitEntries = entriesByTabId.get(tab.id) ?? []
+ for (const entry of explicitEntries) {
+ const isFresh = isExplicitAgentStatusFresh(entry, args.now, AGENT_STATUS_STALE_AFTER_MS)
+ const shouldDecay =
+ !isFresh &&
+ (entry.state === 'working' || entry.state === 'blocked' || entry.state === 'waiting')
+ rows.push({
+ paneKey: entry.paneKey,
+ entry,
+ tab,
+ agentType: entry.agentType ?? 'unknown',
+ state: shouldDecay ? 'idle' : entry.state,
+ startedAt: entry.stateHistory[0]?.startedAt ?? entry.stateStartedAt
+ })
+ seenPaneKeys.add(entry.paneKey)
+ }
+ }
+
+ for (const ra of args.retained) {
+ if (seenPaneKeys.has(ra.entry.paneKey)) {
+ continue
+ }
+ rows.push({
+ paneKey: ra.entry.paneKey,
+ entry: ra.entry,
+ tab: ra.tab,
+ agentType: ra.agentType,
+ state: 'done',
+ startedAt: ra.startedAt
+ })
+ }
+
+ rows.sort((a, b) => a.startedAt - b.startedAt)
+ return rows
+}
+
/**
* Narrow per-worktree agent row hook used by the WorktreeCard inline agents
* list. Produces live hook-reported agents plus retained "done" snapshots,
@@ -75,64 +136,15 @@ export function useWorktreeAgentRows(worktreeId: string): DashboardAgentRow[] {
const agentStatusEpoch = useAppStore((s) => s.agentStatusEpoch)
return useMemo(() => {
- const rows: DashboardAgentRow[] = []
- const seenPaneKeys = new Set()
// Why: Date.now() is read inside the memo (not as a dep) so stale-decay
// recalculates whenever agentStatusEpoch ticks — same pattern as
// useDashboardData.
- const now = Date.now()
-
- const entriesByTabId = new Map()
- for (const entry of entries) {
- const colonIndex = entry.paneKey.indexOf(':')
- if (colonIndex === -1) {
- continue
- }
- const tabId = entry.paneKey.slice(0, colonIndex)
- const bucket = entriesByTabId.get(tabId)
- if (bucket) {
- bucket.push(entry)
- } else {
- entriesByTabId.set(tabId, [entry])
- }
- }
-
- const worktreeTabs = tabs ?? []
- for (const tab of worktreeTabs) {
- const explicitEntries = entriesByTabId.get(tab.id) ?? []
- for (const entry of explicitEntries) {
- const isFresh = isExplicitAgentStatusFresh(entry, now, AGENT_STATUS_STALE_AFTER_MS)
- const shouldDecay =
- !isFresh &&
- (entry.state === 'working' || entry.state === 'blocked' || entry.state === 'waiting')
- rows.push({
- paneKey: entry.paneKey,
- entry,
- tab,
- agentType: entry.agentType ?? 'unknown',
- state: shouldDecay ? 'idle' : entry.state,
- startedAt: entry.stateHistory[0]?.startedAt ?? entry.stateStartedAt
- })
- seenPaneKeys.add(entry.paneKey)
- }
- }
-
- for (const ra of retained) {
- if (seenPaneKeys.has(ra.entry.paneKey)) {
- continue
- }
- rows.push({
- paneKey: ra.entry.paneKey,
- entry: ra.entry,
- tab: ra.tab,
- agentType: ra.agentType,
- state: 'done',
- startedAt: ra.startedAt
- })
- }
-
- rows.sort((a, b) => a.startedAt - b.startedAt)
- return rows
+ return buildWorktreeAgentRows({
+ tabs: tabs ?? [],
+ entries,
+ retained,
+ now: Date.now()
+ })
// eslint-disable-next-line react-hooks/exhaustive-deps
- }, [tabs, entries, retained, worktreeId, agentStatusEpoch])
+ }, [tabs, entries, retained, agentStatusEpoch])
}
diff --git a/src/renderer/src/components/sidebar/visible-worktrees.test.ts b/src/renderer/src/components/sidebar/visible-worktrees.test.ts
index c855e58bd..d53d8095d 100644
--- a/src/renderer/src/components/sidebar/visible-worktrees.test.ts
+++ b/src/renderer/src/components/sidebar/visible-worktrees.test.ts
@@ -1,3 +1,4 @@
+/* eslint-disable max-lines */
import { describe, expect, it } from 'vitest'
import {
computeClearFilterActions,
@@ -42,42 +43,54 @@ function makeWorktree(id: string, repoId = 'repo1'): Worktree {
}
}
+function makeRepo(id: string, displayName: string, badgeColor: string): Repo {
+ return { id, path: `/${id}`, displayName, badgeColor, addedAt: 0 }
+}
+
const repoMap = new Map([
- [
- 'repo1',
- {
- id: 'repo1',
- path: '/repo1',
- displayName: 'Repo 1',
- badgeColor: '#000',
- addedAt: 0
- }
- ],
- [
- 'repo2',
- {
- id: 'repo2',
- path: '/repo2',
- displayName: 'Repo 2',
- badgeColor: '#111',
- addedAt: 0
- }
- ]
+ ['repo1', makeRepo('repo1', 'Repo 1', '#000')],
+ ['repo2', makeRepo('repo2', 'Repo 2', '#111')]
])
+type VisibleOptions = Parameters[2]
+
+function visibleOptions(overrides: Partial = {}): VisibleOptions {
+ return {
+ filterRepoIds: [],
+ showActiveOnly: false,
+ tabsByWorktree: {},
+ ptyIdsByTabId: {},
+ browserTabsByWorktree: {},
+ activeWorktreeId: null,
+ hideDefaultBranchWorkspace: false,
+ repoMap,
+ ...overrides
+ }
+}
+
+type FilterState = Parameters[0]
+
+function filterState(overrides: Partial = {}): FilterState {
+ return {
+ showActiveOnly: false,
+ filterRepoIds: [],
+ hideDefaultBranchWorkspace: false,
+ ...overrides
+ }
+}
+
describe('computeVisibleWorktreeIds', () => {
it('treats browser-tab worktrees as active for the active-only filter', () => {
const wt = makeWorktree('wt-browser')
- const result = computeVisibleWorktreeIds({ repo1: [wt] }, [wt.id], {
- filterRepoIds: [],
- showActiveOnly: true,
- tabsByWorktree: {},
- browserTabsByWorktree: { [wt.id]: [{ id: 'browser-1' }] },
- activeWorktreeId: null,
- hideDefaultBranchWorkspace: false,
- repoMap
- })
+ const result = computeVisibleWorktreeIds(
+ { repo1: [wt] },
+ [wt.id],
+ visibleOptions({
+ showActiveOnly: true,
+ browserTabsByWorktree: { [wt.id]: [{ id: 'browser-1' }] }
+ })
+ )
expect(result).toEqual([wt.id])
})
@@ -85,33 +98,48 @@ describe('computeVisibleWorktreeIds', () => {
it('keeps the currently active worktree visible even without PTYs', () => {
const wt = makeWorktree('wt-active')
- const result = computeVisibleWorktreeIds({ repo1: [wt] }, [wt.id], {
- filterRepoIds: [],
- showActiveOnly: true,
- tabsByWorktree: {},
- browserTabsByWorktree: {},
- activeWorktreeId: wt.id,
- hideDefaultBranchWorkspace: false,
- repoMap
- })
+ const result = computeVisibleWorktreeIds(
+ { repo1: [wt] },
+ [wt.id],
+ visibleOptions({
+ showActiveOnly: true,
+ activeWorktreeId: wt.id
+ })
+ )
expect(result).toEqual([wt.id])
})
+ it('does not treat slept wake-hint tabs as active terminals', () => {
+ const wt = makeWorktree('wt-slept')
+
+ const result = computeVisibleWorktreeIds(
+ { repo1: [wt] },
+ [wt.id],
+ visibleOptions({
+ showActiveOnly: true,
+ tabsByWorktree: { [wt.id]: [makeTab('tab-slept', wt.id, 'wake-hint-session')] },
+ // Sleep preserves tab.ptyId as the wake hint but clears live PTY ids.
+ ptyIdsByTabId: { 'tab-slept': [] }
+ })
+ )
+
+ expect(result).toEqual([])
+ })
+
it('hides branch-backed main worktrees when default branch workspaces are hidden', () => {
const main = makeWorktree('main')
const feature = makeWorktree('feature')
main.isMainWorktree = true
- const result = computeVisibleWorktreeIds({ repo1: [main, feature] }, [main.id, feature.id], {
- filterRepoIds: [],
- showActiveOnly: false,
- tabsByWorktree: {},
- browserTabsByWorktree: {},
- activeWorktreeId: main.id,
- hideDefaultBranchWorkspace: true,
- repoMap
- })
+ const result = computeVisibleWorktreeIds(
+ { repo1: [main, feature] },
+ [main.id, feature.id],
+ visibleOptions({
+ activeWorktreeId: main.id,
+ hideDefaultBranchWorkspace: true
+ })
+ )
expect(result).toEqual([feature.id])
})
@@ -121,15 +149,11 @@ describe('computeVisibleWorktreeIds', () => {
folder.isMainWorktree = true
folder.branch = ''
- const result = computeVisibleWorktreeIds({ repo1: [folder] }, [folder.id], {
- filterRepoIds: [],
- showActiveOnly: false,
- tabsByWorktree: {},
- browserTabsByWorktree: {},
- activeWorktreeId: null,
- hideDefaultBranchWorkspace: true,
- repoMap
- })
+ const result = computeVisibleWorktreeIds(
+ { repo1: [folder] },
+ [folder.id],
+ visibleOptions({ hideDefaultBranchWorkspace: true })
+ )
expect(result).toEqual([folder.id])
})
@@ -145,15 +169,7 @@ describe('computeVisibleWorktreeIds', () => {
const result = computeVisibleWorktreeIds(
{ repo1: [main1, feature1], repo2: [main2, feature2] },
[main1.id, feature1.id, main2.id, feature2.id],
- {
- filterRepoIds: [],
- showActiveOnly: false,
- tabsByWorktree: {},
- browserTabsByWorktree: {},
- activeWorktreeId: null,
- hideDefaultBranchWorkspace: true,
- repoMap
- }
+ visibleOptions({ hideDefaultBranchWorkspace: true })
)
expect(result).toEqual([feature1.id, feature2.id])
@@ -168,15 +184,17 @@ describe('computeVisibleWorktreeIds', () => {
// main doesn't slip back in via the "active worktree is always visible"
// exception that showActiveOnly grants. Feature stays because it has a
// live PTY.
- const result = computeVisibleWorktreeIds({ repo1: [main, feature] }, [main.id, feature.id], {
- filterRepoIds: [],
- showActiveOnly: true,
- tabsByWorktree: { [feature.id]: [makeTab('t1', feature.id, 'p1')] },
- browserTabsByWorktree: {},
- activeWorktreeId: main.id,
- hideDefaultBranchWorkspace: true,
- repoMap
- })
+ const result = computeVisibleWorktreeIds(
+ { repo1: [main, feature] },
+ [main.id, feature.id],
+ visibleOptions({
+ showActiveOnly: true,
+ tabsByWorktree: { [feature.id]: [makeTab('t1', feature.id, 'p1')] },
+ ptyIdsByTabId: { t1: ['p1'] },
+ activeWorktreeId: main.id,
+ hideDefaultBranchWorkspace: true
+ })
+ )
expect(result).toEqual([feature.id])
})
@@ -197,15 +215,10 @@ describe('computeVisibleWorktreeIds', () => {
const result = computeVisibleWorktreeIds(
{ repo1: [main1, feature1], repo2: [main2, feature2] },
[main1.id, feature1.id, main2.id, feature2.id],
- {
+ visibleOptions({
filterRepoIds: ['repo2'],
- showActiveOnly: false,
- tabsByWorktree: {},
- browserTabsByWorktree: {},
- activeWorktreeId: null,
- hideDefaultBranchWorkspace: true,
- repoMap
- }
+ hideDefaultBranchWorkspace: true
+ })
)
expect(result).toEqual([feature2.id])
@@ -234,58 +247,28 @@ describe('isDefaultBranchWorkspace', () => {
describe('sidebarHasActiveFilters', () => {
it('returns false when no filters are active', () => {
- expect(
- sidebarHasActiveFilters({
- showActiveOnly: false,
- filterRepoIds: [],
- hideDefaultBranchWorkspace: false
- })
- ).toBe(false)
+ expect(sidebarHasActiveFilters(filterState())).toBe(false)
})
it('returns true when only hideDefaultBranchWorkspace is active', () => {
// Why: regression guard for the empty-sidebar escape hatch. If hide is
// omitted from the filter union, a user whose only worktree is the
// default-branch row sees "No worktrees found" with no way back.
- expect(
- sidebarHasActiveFilters({
- showActiveOnly: false,
- filterRepoIds: [],
- hideDefaultBranchWorkspace: true
- })
- ).toBe(true)
+ expect(sidebarHasActiveFilters(filterState({ hideDefaultBranchWorkspace: true }))).toBe(true)
})
it('returns true when only showActiveOnly is active', () => {
- expect(
- sidebarHasActiveFilters({
- showActiveOnly: true,
- filterRepoIds: [],
- hideDefaultBranchWorkspace: false
- })
- ).toBe(true)
+ expect(sidebarHasActiveFilters(filterState({ showActiveOnly: true }))).toBe(true)
})
it('returns true when only filterRepoIds is non-empty', () => {
- expect(
- sidebarHasActiveFilters({
- showActiveOnly: false,
- filterRepoIds: ['repo1'],
- hideDefaultBranchWorkspace: false
- })
- ).toBe(true)
+ expect(sidebarHasActiveFilters(filterState({ filterRepoIds: ['repo1'] }))).toBe(true)
})
})
describe('computeClearFilterActions', () => {
it('returns no-op actions when nothing is set', () => {
- expect(
- computeClearFilterActions({
- showActiveOnly: false,
- filterRepoIds: [],
- hideDefaultBranchWorkspace: false
- })
- ).toEqual({
+ expect(computeClearFilterActions(filterState())).toEqual({
resetShowActiveOnly: false,
resetFilterRepoIds: false,
resetHideDefaultBranchWorkspace: false
@@ -296,13 +279,7 @@ describe('computeClearFilterActions', () => {
// Why: verifies the empty-sidebar escape hatch actually clears the hide
// flag. A regression here would leave users stuck on "No worktrees found"
// because the only active filter would never clear.
- expect(
- computeClearFilterActions({
- showActiveOnly: false,
- filterRepoIds: [],
- hideDefaultBranchWorkspace: true
- })
- ).toEqual({
+ expect(computeClearFilterActions(filterState({ hideDefaultBranchWorkspace: true }))).toEqual({
resetShowActiveOnly: false,
resetFilterRepoIds: false,
resetHideDefaultBranchWorkspace: true
@@ -312,11 +289,12 @@ describe('computeClearFilterActions', () => {
it('does not flag hideDefaultBranchWorkspace when it is already off', () => {
// Why: avoids issuing a pointless IPC write on every Clear Filters click
// in the common case where hide was never on.
- const actions = computeClearFilterActions({
- showActiveOnly: true,
- filterRepoIds: ['repo1'],
- hideDefaultBranchWorkspace: false
- })
+ const actions = computeClearFilterActions(
+ filterState({
+ showActiveOnly: true,
+ filterRepoIds: ['repo1']
+ })
+ )
expect(actions.resetHideDefaultBranchWorkspace).toBe(false)
expect(actions.resetShowActiveOnly).toBe(true)
expect(actions.resetFilterRepoIds).toBe(true)
@@ -324,11 +302,13 @@ describe('computeClearFilterActions', () => {
it('flags every active filter simultaneously', () => {
expect(
- computeClearFilterActions({
- showActiveOnly: true,
- filterRepoIds: ['repo1', 'repo2'],
- hideDefaultBranchWorkspace: true
- })
+ computeClearFilterActions(
+ filterState({
+ showActiveOnly: true,
+ filterRepoIds: ['repo1', 'repo2'],
+ hideDefaultBranchWorkspace: true
+ })
+ )
).toEqual({
resetShowActiveOnly: true,
resetFilterRepoIds: true,
diff --git a/src/renderer/src/components/sidebar/visible-worktrees.ts b/src/renderer/src/components/sidebar/visible-worktrees.ts
index 85a185d6e..68015c62c 100644
--- a/src/renderer/src/components/sidebar/visible-worktrees.ts
+++ b/src/renderer/src/components/sidebar/visible-worktrees.ts
@@ -1,5 +1,6 @@
import type { Worktree, Repo, TerminalTab } from '../../../../shared/types'
import { buildWorktreeComparator, sortWorktreesSmart } from './smart-sort'
+import { tabHasLivePty } from '@/lib/tab-has-live-pty'
import { useAppStore } from '@/store'
import { getAllWorktreesFromState, getRepoMapFromState } from '@/store/selectors'
@@ -79,6 +80,7 @@ export function computeVisibleWorktreeIds(
filterRepoIds: string[]
showActiveOnly: boolean
tabsByWorktree: Record | null
+ ptyIdsByTabId: Record | null
browserTabsByWorktree?: Record | null
activeWorktreeId?: string | null
// Why required: every caller (WorktreeList, getVisibleWorktreeIds
@@ -108,7 +110,9 @@ export function computeVisibleWorktreeIds(
if (opts.showActiveOnly) {
all = all.filter((w) => {
const tabs = opts.tabsByWorktree?.[w.id] ?? []
- const hasLiveTerminal = tabs.some((t) => t.ptyId)
+ const hasLiveTerminal = tabs.some((tab) =>
+ opts.ptyIdsByTabId ? tabHasLivePty(opts.ptyIdsByTabId, tab.id) : false
+ )
const hasBrowserTabs = (opts.browserTabsByWorktree?.[w.id] ?? []).length > 0
// Why: "Active only" should reflect the surfaces Orca can actually
// restore into, not just PTY-backed terminals. A browser-tab worktree is
@@ -181,7 +185,8 @@ export function getVisibleWorktreeIds(): string[] {
state.tabsByWorktree,
repoMap,
state.prCache,
- state.agentStatusByPaneKey
+ state.agentStatusByPaneKey,
+ state.ptyIdsByTabId
).map((w) => w.id)
} else {
const sorted = [...allWorktrees].sort(
@@ -192,7 +197,10 @@ export function getVisibleWorktreeIds(): string[] {
state.prCache,
Date.now(),
null,
- state.agentStatusByPaneKey
+ state.agentStatusByPaneKey,
+ undefined,
+ undefined,
+ state.ptyIdsByTabId
)
)
sortedIds = sorted.map((w) => w.id)
@@ -202,6 +210,7 @@ export function getVisibleWorktreeIds(): string[] {
filterRepoIds: state.filterRepoIds,
showActiveOnly: state.showActiveOnly,
tabsByWorktree: state.tabsByWorktree,
+ ptyIdsByTabId: state.ptyIdsByTabId,
browserTabsByWorktree: state.browserTabsByWorktree,
activeWorktreeId: state.activeWorktreeId,
hideDefaultBranchWorkspace: state.hideDefaultBranchWorkspace,
diff --git a/src/renderer/src/components/sidebar/worktree-card-status-inputs.test.ts b/src/renderer/src/components/sidebar/worktree-card-status-inputs.test.ts
new file mode 100644
index 000000000..ce6aa8f79
--- /dev/null
+++ b/src/renderer/src/components/sidebar/worktree-card-status-inputs.test.ts
@@ -0,0 +1,94 @@
+import { describe, expect, it } from 'vitest'
+import { shallow } from 'zustand/shallow'
+import type { TerminalTab } from '../../../../shared/types'
+import {
+ selectLivePtyIdsForWorktree,
+ selectRuntimePaneTitlesForWorktree
+} from './worktree-card-status-inputs'
+
+type SelectorState = Parameters[0]
+
+function makeTab(id: string, worktreeId: string): TerminalTab {
+ return {
+ id,
+ worktreeId,
+ ptyId: 'pty-1',
+ title: 'Terminal 1',
+ customTitle: null,
+ color: null,
+ sortOrder: 0,
+ createdAt: 0
+ }
+}
+
+describe('worktree card status input selectors', () => {
+ it('stays shallow-equal when unrelated tabs receive PTY ids or pane titles', () => {
+ const worktreeId = 'repo1::/path/wt1'
+ const paneTitles = { 0: 'codex [working]' }
+ const ptyIds = ['pty-1']
+ const state: SelectorState = {
+ tabsByWorktree: {
+ [worktreeId]: [makeTab('tab-1', worktreeId)]
+ },
+ runtimePaneTitlesByTabId: {
+ 'tab-1': paneTitles
+ },
+ ptyIdsByTabId: {
+ 'tab-1': ptyIds
+ }
+ }
+ const unrelatedUpdate: SelectorState = {
+ ...state,
+ runtimePaneTitlesByTabId: {
+ ...state.runtimePaneTitlesByTabId,
+ 'other-tab': { 0: 'claude [permission]' }
+ },
+ ptyIdsByTabId: {
+ ...state.ptyIdsByTabId,
+ 'other-tab': ['pty-other']
+ }
+ }
+
+ // Why: WorktreeCard wraps these selectors in useShallow. The selected
+ // maps must expose stable per-tab values at the top level so unrelated
+ // PTY/title churn does not re-render every sidebar card.
+ expect(
+ shallow(
+ selectRuntimePaneTitlesForWorktree(state, worktreeId),
+ selectRuntimePaneTitlesForWorktree(unrelatedUpdate, worktreeId)
+ )
+ ).toBe(true)
+ expect(
+ shallow(
+ selectLivePtyIdsForWorktree(state, worktreeId),
+ selectLivePtyIdsForWorktree(unrelatedUpdate, worktreeId)
+ )
+ ).toBe(true)
+ })
+
+ it('changes when this worktree receives a new live PTY id list', () => {
+ const worktreeId = 'repo1::/path/wt1'
+ const state: SelectorState = {
+ tabsByWorktree: {
+ [worktreeId]: [makeTab('tab-1', worktreeId)]
+ },
+ runtimePaneTitlesByTabId: {},
+ ptyIdsByTabId: {
+ 'tab-1': ['pty-1']
+ }
+ }
+ const updated: SelectorState = {
+ ...state,
+ ptyIdsByTabId: {
+ 'tab-1': ['pty-2']
+ }
+ }
+
+ expect(
+ shallow(
+ selectLivePtyIdsForWorktree(state, worktreeId),
+ selectLivePtyIdsForWorktree(updated, worktreeId)
+ )
+ ).toBe(false)
+ })
+})
diff --git a/src/renderer/src/components/sidebar/worktree-card-status-inputs.ts b/src/renderer/src/components/sidebar/worktree-card-status-inputs.ts
new file mode 100644
index 000000000..d0552e89f
--- /dev/null
+++ b/src/renderer/src/components/sidebar/worktree-card-status-inputs.ts
@@ -0,0 +1,37 @@
+import type { AppState } from '@/store/types'
+
+// Why: these selectors return fresh maps whose top-level values preserve
+// underlying per-tab references, so callers must compare them shallowly.
+
+type WorktreeCardStatusInputState = Pick<
+ AppState,
+ 'tabsByWorktree' | 'runtimePaneTitlesByTabId' | 'ptyIdsByTabId'
+>
+
+export function selectRuntimePaneTitlesForWorktree(
+ state: WorktreeCardStatusInputState,
+ worktreeId: string
+): Record> {
+ const out: Record> = {}
+ for (const tab of state.tabsByWorktree[worktreeId] ?? []) {
+ const paneTitles = state.runtimePaneTitlesByTabId[tab.id]
+ if (paneTitles) {
+ out[tab.id] = paneTitles
+ }
+ }
+ return out
+}
+
+export function selectLivePtyIdsForWorktree(
+ state: WorktreeCardStatusInputState,
+ worktreeId: string
+): Record {
+ const out: Record = {}
+ for (const tab of state.tabsByWorktree[worktreeId] ?? []) {
+ const ids = state.ptyIdsByTabId[tab.id]
+ if (ids && ids.length > 0) {
+ out[tab.id] = ids
+ }
+ }
+ return out
+}
diff --git a/src/renderer/src/lib/agent-status-count.test.ts b/src/renderer/src/lib/agent-status-count.test.ts
index 035c073ae..dac9294b3 100644
--- a/src/renderer/src/lib/agent-status-count.test.ts
+++ b/src/renderer/src/lib/agent-status-count.test.ts
@@ -43,6 +43,14 @@ function worktrees(...ids: string[]): Record {
}
}
+// Why: build a live-pty map from tab ids so each test can declare which tabs
+// are actually alive without manually tracking parallel `tab.ptyId` values.
+// `tab.ptyId` is the wake-hint sessionId preserved across sleep, not a
+// liveness signal — slept-tab tests below pin the gap.
+function livePtyMap(...tabIds: string[]): Record {
+ return Object.fromEntries(tabIds.map((id, i) => [id, [`pty-${i}`]]))
+}
+
describe('countWorkingAgents', () => {
it('counts each live working tab when pane-level titles are unavailable', () => {
expect(
@@ -55,6 +63,7 @@ describe('countWorkingAgents', () => {
'wt-2': [makeTab({ id: 'tab-3', worktreeId: 'wt-2', title: '⠋ Codex is thinking' })]
},
runtimePaneTitlesByTabId: {},
+ ptyIdsByTabId: livePtyMap('tab-1', 'tab-2', 'tab-3'),
worktreesByRepo: worktrees('wt-1', 'wt-2')
})
).toBe(3)
@@ -73,6 +82,7 @@ describe('countWorkingAgents', () => {
3: '✳ Claude Code'
}
},
+ ptyIdsByTabId: livePtyMap('tab-1'),
worktreesByRepo: worktrees('wt-1')
})
).toBe(2)
@@ -86,10 +96,11 @@ describe('countWorkingAgents', () => {
makeTab({ id: 'tab-1', title: '✳ Claude Code' }),
makeTab({ id: 'tab-2', title: '✋ Gemini CLI' }),
makeTab({ id: 'tab-3', title: 'bash' }),
- makeTab({ id: 'tab-4', title: '⠂ Claude Code', ptyId: null })
+ makeTab({ id: 'tab-4', title: '⠂ Claude Code' })
]
},
runtimePaneTitlesByTabId: {},
+ ptyIdsByTabId: livePtyMap('tab-1', 'tab-2', 'tab-3'),
worktreesByRepo: worktrees('wt-1')
})
).toBe(0)
@@ -107,6 +118,7 @@ describe('countWorkingAgents', () => {
2: 'bash'
}
},
+ ptyIdsByTabId: livePtyMap('tab-1'),
worktreesByRepo: worktrees('wt-1')
})
).toBe(0)
@@ -120,10 +132,47 @@ describe('countWorkingAgents', () => {
'wt-deleted': [makeTab({ id: 'tab-2', worktreeId: 'wt-deleted', title: '✦ Gemini CLI' })]
},
runtimePaneTitlesByTabId: {},
+ ptyIdsByTabId: livePtyMap('tab-1', 'tab-2'),
worktreesByRepo: worktrees('wt-1')
})
).toBe(1)
})
+
+ // Why: sleep preserves runtimePaneTitlesByTabId and tab.ptyId as wake hints
+ // while ptyIdsByTabId[tab.id] is cleared to []. Both branches of the
+ // counter (primary pane-titles and tab-title fallback) must respect that
+ // liveness gate — otherwise the title-bar agent count, dock badge, and
+ // workingAgentsPerWorktree aggregates report ghost activity for slept
+ // worktrees.
+ it('returns 0 for a slept tab whose preserved pane titles still match working (primary branch)', () => {
+ expect(
+ countWorkingAgents({
+ tabsByWorktree: {
+ 'wt-1': [makeTab({ id: 'tab-1', title: '⠂ Claude Code' })]
+ },
+ runtimePaneTitlesByTabId: {
+ 'tab-1': { 0: '⠂ Claude Code' }
+ },
+ // Slept: live-pty array is empty even though tab.ptyId is set as a
+ // wake-hint sessionId.
+ ptyIdsByTabId: { 'tab-1': [] },
+ worktreesByRepo: worktrees('wt-1')
+ })
+ ).toBe(0)
+ })
+
+ it('returns 0 for a slept tab whose preserved tab.title still matches working (fallback branch)', () => {
+ expect(
+ countWorkingAgents({
+ tabsByWorktree: {
+ 'wt-1': [makeTab({ id: 'tab-1', title: '⠂ Claude Code' })]
+ },
+ runtimePaneTitlesByTabId: {},
+ ptyIdsByTabId: { 'tab-1': [] },
+ worktreesByRepo: worktrees('wt-1')
+ })
+ ).toBe(0)
+ })
})
describe('getWorkingAgentsPerWorktree', () => {
@@ -140,6 +189,7 @@ describe('getWorkingAgentsPerWorktree', () => {
3: '✳ Claude Code'
}
},
+ ptyIdsByTabId: livePtyMap('tab-1'),
worktreesByRepo: worktrees('wt-1')
})
).toEqual({
@@ -160,6 +210,7 @@ describe('getWorkingAgentsPerWorktree', () => {
'wt-deleted': [makeTab({ id: 'tab-2', worktreeId: 'wt-deleted', title: '✦ Gemini CLI' })]
},
runtimePaneTitlesByTabId: {},
+ ptyIdsByTabId: livePtyMap('tab-1', 'tab-2'),
worktreesByRepo: worktrees('wt-1')
})
).toEqual({
@@ -168,4 +219,34 @@ describe('getWorkingAgentsPerWorktree', () => {
}
})
})
+
+ // See countWorkingAgents slept-tab tests above — the same liveness gate
+ // applies here on both branches of the per-worktree aggregation.
+ it('returns nothing for a slept tab whose preserved pane titles still match working (primary branch)', () => {
+ expect(
+ getWorkingAgentsPerWorktree({
+ tabsByWorktree: {
+ 'wt-1': [makeTab({ id: 'tab-1', title: '⠂ Claude Code' })]
+ },
+ runtimePaneTitlesByTabId: {
+ 'tab-1': { 0: '⠂ Claude Code' }
+ },
+ ptyIdsByTabId: { 'tab-1': [] },
+ worktreesByRepo: worktrees('wt-1')
+ })
+ ).toEqual({})
+ })
+
+ it('returns nothing for a slept tab whose preserved tab.title still matches working (fallback branch)', () => {
+ expect(
+ getWorkingAgentsPerWorktree({
+ tabsByWorktree: {
+ 'wt-1': [makeTab({ id: 'tab-1', title: '⠂ Claude Code' })]
+ },
+ runtimePaneTitlesByTabId: {},
+ ptyIdsByTabId: { 'tab-1': [] },
+ worktreesByRepo: worktrees('wt-1')
+ })
+ ).toEqual({})
+ })
})
diff --git a/src/renderer/src/lib/agent-status.ts b/src/renderer/src/lib/agent-status.ts
index b0ea35ecd..471d5a2ed 100644
--- a/src/renderer/src/lib/agent-status.ts
+++ b/src/renderer/src/lib/agent-status.ts
@@ -4,6 +4,7 @@ import type {
AgentStatusState,
AgentType
} from '../../../shared/agent-status-types'
+import { tabHasLivePty } from './tab-has-live-pty'
import type { WorktreeStatus } from './worktree-status'
// Re-export from shared module so existing renderer imports continue to work.
@@ -28,6 +29,14 @@ import {
type AgentQueryArgs = {
tabsByWorktree: Record
runtimePaneTitlesByTabId: Record>
+ // Why: title-scraped agent activity (pane titles, tab.title) survives sleep
+ // because runtimePaneTitlesByTabId is intentionally preserved under
+ // keepIdentifiers for wake recovery. Without the live-PTY map, slept tabs
+ // whose preserved titles still match a working pattern would surface as
+ // working agents through the title-bar count, dock badge, and per-worktree
+ // aggregates. Threading ptyIdsByTabId lets every title-scrape branch gate
+ // on actual liveness (`tabHasLivePty`).
+ ptyIdsByTabId: Record
worktreesByRepo: Record
}
@@ -45,6 +54,7 @@ export type WorktreeAgents = {
export function getWorkingAgentsPerWorktree({
tabsByWorktree,
runtimePaneTitlesByTabId,
+ ptyIdsByTabId,
worktreesByRepo
}: AgentQueryArgs): Record {
const validIds = collectWorktreeIds(worktreesByRepo)
@@ -61,6 +71,13 @@ export function getWorkingAgentsPerWorktree({
const agents: WorkingAgentEntry[] = []
for (const tab of tabs) {
+ // Why: title-scraped activity must be gated on actual PTY liveness.
+ // runtimePaneTitlesByTabId is preserved under sleep (keepIdentifiers),
+ // so a slept tab whose pane titles still match a working pattern would
+ // surface as a working agent without this gate.
+ if (!tabHasLivePty(ptyIdsByTabId, tab.id)) {
+ continue
+ }
const paneTitles = runtimePaneTitlesByTabId[tab.id]
if (paneTitles && Object.keys(paneTitles).length > 0) {
for (const [paneIdStr, title] of Object.entries(paneTitles)) {
@@ -76,7 +93,7 @@ export function getWorkingAgentsPerWorktree({
}
}
}
- } else if (tab.ptyId && detectAgentStatusFromTitle(tab.title) === 'working') {
+ } else if (detectAgentStatusFromTitle(tab.title) === 'working') {
const label = getAgentLabel(tab.title)
if (label) {
agents.push({ label, status: 'working', tabId: tab.id, paneId: null })
@@ -196,6 +213,7 @@ export function mapAgentStatusStateToVisualStatus(state: AgentStatusState): Work
export function countWorkingAgents({
tabsByWorktree,
runtimePaneTitlesByTabId,
+ ptyIdsByTabId,
worktreesByRepo
}: AgentQueryArgs): number {
const validIds = collectWorktreeIds(worktreesByRepo)
@@ -206,7 +224,7 @@ export function countWorkingAgents({
continue
}
for (const tab of tabs) {
- count += countWorkingAgentsForTab(tab, runtimePaneTitlesByTabId)
+ count += countWorkingAgentsForTab(tab, runtimePaneTitlesByTabId, ptyIdsByTabId)
}
}
@@ -225,8 +243,17 @@ function collectWorktreeIds(worktreesByRepo: Record): Set>
+ runtimePaneTitlesByTabId: Record>,
+ ptyIdsByTabId: Record
): number {
+ // Why: liveness precondition shared with getWorkingAgentsPerWorktree.
+ // runtimePaneTitlesByTabId is preserved under sleep (keepIdentifiers) and
+ // tab.ptyId is the wake-hint sessionId, not a liveness signal. Without
+ // this gate, slept tabs whose preserved titles still match a working
+ // pattern would inflate the title-bar agent count and dock badge.
+ if (!tabHasLivePty(ptyIdsByTabId, tab.id)) {
+ return 0
+ }
let count = 0
const paneTitles = runtimePaneTitlesByTabId[tab.id]
// Why: split-pane tabs can host multiple concurrent agents, but the
@@ -242,11 +269,7 @@ function countWorkingAgentsForTab(
}
return count
}
- // Why: restored session tabs can keep the last agent title even before a
- // PTY reconnects (or after the PTY is gone). Count only live PTY-backed
- // tab fallbacks so the titlebar matches the sidebar's notion of
- // "actively running" instead of surfacing stale pre-shutdown state.
- if (tab.ptyId && detectAgentStatusFromTitle(tab.title) === 'working') {
+ if (detectAgentStatusFromTitle(tab.title) === 'working') {
count += 1
}
return count
diff --git a/src/renderer/src/lib/tab-has-live-pty.test.ts b/src/renderer/src/lib/tab-has-live-pty.test.ts
new file mode 100644
index 000000000..5772ee9b8
--- /dev/null
+++ b/src/renderer/src/lib/tab-has-live-pty.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest'
+import { tabHasLivePty } from './tab-has-live-pty'
+
+describe('tabHasLivePty', () => {
+ it('returns false for an empty map', () => {
+ expect(tabHasLivePty({}, 'tab-1')).toBe(false)
+ })
+
+ it('returns false for a missing tab id', () => {
+ expect(tabHasLivePty({ 'other-tab': ['pty-1'] }, 'tab-1')).toBe(false)
+ })
+
+ it('returns false for a tab whose live-pty array is empty (sleep / pre-spawn)', () => {
+ // Why: sleep clears ptyIdsByTabId[tab.id] to [] while keeping tab.ptyId as
+ // a wake-hint sessionId — that shape is the central regression this helper
+ // exists to catch.
+ expect(tabHasLivePty({ 'tab-1': [] }, 'tab-1')).toBe(false)
+ })
+
+ it('returns true for a tab with at least one live pty id', () => {
+ expect(tabHasLivePty({ 'tab-1': ['pty-1'] }, 'tab-1')).toBe(true)
+ })
+
+ it('returns true for a tab with multiple live pty ids (split panes)', () => {
+ expect(tabHasLivePty({ 'tab-1': ['pty-1', 'pty-2'] }, 'tab-1')).toBe(true)
+ })
+})
diff --git a/src/renderer/src/lib/tab-has-live-pty.ts b/src/renderer/src/lib/tab-has-live-pty.ts
new file mode 100644
index 000000000..acb9a1c9f
--- /dev/null
+++ b/src/renderer/src/lib/tab-has-live-pty.ts
@@ -0,0 +1,13 @@
+/**
+ * True iff `tabId` has at least one live PTY tracked in the live-PTY map.
+ *
+ * Why: tab.ptyId is the wake-hint sessionId, not a liveness signal — sleep
+ * preserves it so wake can pass it as args.sessionId to pty.spawn and
+ * reattach to the same on-disk daemon history dir / relay session. Reads of
+ * "is this tab alive?" must go through the live-PTY map (ptyIdsByTabId),
+ * which is the source of truth for live PTYs in the renderer (every
+ * pty.spawn writes it; every pty.kill / shutdown clears it).
+ */
+export function tabHasLivePty(ptyIdsByTabId: Record, tabId: string): boolean {
+ return (ptyIdsByTabId[tabId]?.length ?? 0) > 0
+}
diff --git a/src/renderer/src/lib/worktree-status.test.ts b/src/renderer/src/lib/worktree-status.test.ts
index 28c77248b..6861853bf 100644
--- a/src/renderer/src/lib/worktree-status.test.ts
+++ b/src/renderer/src/lib/worktree-status.test.ts
@@ -1,14 +1,23 @@
import { describe, expect, it } from 'vitest'
-import { getWorktreeStatus, getWorktreeStatusLabel } from './worktree-status'
+import { getWorktreeStatus, getWorktreeStatusLabel, resolveWorktreeStatus } from './worktree-status'
-describe('worktree-status', () => {
+// Why: build a live-pty map from tab ids so each test can declare which
+// tabs are alive without manually tracking parallel `tab.ptyId` values.
+// `tab.ptyId` is the wake-hint sessionId preserved across sleep, not a
+// liveness signal — slept-tab tests below pin the gap.
+function livePtyMap(...tabIds: string[]): Record {
+ return Object.fromEntries(tabIds.map((id, i) => [id, [`pty-${i}`]]))
+}
+
+describe('getWorktreeStatus', () => {
it('prioritizes permission over other live activity states', () => {
const status = getWorktreeStatus(
[
- { id: 'tab-1', ptyId: 'pty-working', title: 'claude [working]' },
- { id: 'tab-2', ptyId: 'pty-permission', title: 'claude [permission]' }
+ { id: 'tab-1', title: 'claude [working]' },
+ { id: 'tab-2', title: 'claude [permission]' }
],
- [{ id: 'browser-1' }]
+ [{ id: 'browser-1' }],
+ livePtyMap('tab-1', 'tab-2')
)
expect(status).toBe('permission')
@@ -16,13 +25,13 @@ describe('worktree-status', () => {
})
it('treats browser-only worktrees as active', () => {
- const status = getWorktreeStatus([], [{ id: 'browser-1' }])
+ const status = getWorktreeStatus([], [{ id: 'browser-1' }], {})
expect(status).toBe('active')
})
it('returns inactive when neither tabs nor browser state are live', () => {
- expect(getWorktreeStatus([], [])).toBe('inactive')
+ expect(getWorktreeStatus([], [], {})).toBe('inactive')
})
it('reports working when any pane in a split-pane tab is working even if tab.title is idle', () => {
@@ -31,8 +40,9 @@ describe('worktree-status', () => {
// use-terminal-pane-lifecycle.ts). If the focused pane is idle while
// another pane is still working, the sidebar spinner must stay spinning.
const status = getWorktreeStatus(
- [{ id: 'tab-1', ptyId: 'pty-1', title: 'claude [done]' }],
+ [{ id: 'tab-1', title: 'claude [done]' }],
[],
+ livePtyMap('tab-1'),
{ 'tab-1': { 0: 'codex [working]', 1: 'claude [done]' } }
)
@@ -41,11 +51,132 @@ describe('worktree-status', () => {
it('prefers pane-level permission status over tab.title', () => {
const status = getWorktreeStatus(
- [{ id: 'tab-1', ptyId: 'pty-1', title: 'claude [done]' }],
+ [{ id: 'tab-1', title: 'claude [done]' }],
[],
+ livePtyMap('tab-1'),
{ 'tab-1': { 0: 'claude [permission]', 1: 'claude [done]' } }
)
expect(status).toBe('permission')
})
+
+ // Why: sleep clears ptyIdsByTabId[tab.id] to [] but preserves tab.ptyId
+ // as a wake-hint sessionId. Reading tab.ptyId for liveness was the bug —
+ // pin the new behavior so it can't regress.
+ it('returns inactive for a slept tab (ptyIdsByTabId empty even if heuristic title matches working)', () => {
+ const status = getWorktreeStatus([{ id: 'tab-1', title: 'claude [working]' }], [], {
+ 'tab-1': []
+ })
+
+ expect(status).toBe('inactive')
+ })
+
+ it('returns active when ptyIdsByTabId has entries (live precondition)', () => {
+ const status = getWorktreeStatus([{ id: 'tab-1', title: 'bash' }], [], livePtyMap('tab-1'))
+
+ expect(status).toBe('active')
+ })
+})
+
+describe('resolveWorktreeStatus', () => {
+ // Why: WorktreeCard layers permission > working > done > heuristic on top
+ // of the title-heuristic base. The slept-with-retained-done case is the
+ // specific UX rule: retained `done` rows survive in the inline agents
+ // list, but the worktree dot must be grey when nothing is alive.
+ it('returns inactive when no tab has a live pty, even if a retained-done row exists', () => {
+ const status = resolveWorktreeStatus({
+ tabs: [{ id: 'tab-1', title: 'claude [done]' }],
+ browserTabs: [],
+ // Slept: live-pty array empty; tab.ptyId would be the wake-hint sessionId.
+ ptyIdsByTabId: { 'tab-1': [] },
+ hasPermission: false,
+ hasLiveDone: false,
+ hasRetainedDone: true
+ })
+
+ expect(status).toBe('inactive')
+ })
+
+ it('returns inactive on slept worktree even when hasPermission is true (precondition wins)', () => {
+ const status = resolveWorktreeStatus({
+ tabs: [{ id: 'tab-1', title: 'claude [permission]' }],
+ browserTabs: [],
+ ptyIdsByTabId: { 'tab-1': [] },
+ hasPermission: true,
+ hasLiveDone: false,
+ hasRetainedDone: false
+ })
+
+ expect(status).toBe('inactive')
+ })
+
+ it('promotes to permission when live and hasPermission', () => {
+ const status = resolveWorktreeStatus({
+ tabs: [{ id: 'tab-1', title: 'bash' }],
+ browserTabs: [],
+ ptyIdsByTabId: livePtyMap('tab-1'),
+ hasPermission: true,
+ hasLiveDone: false,
+ hasRetainedDone: false
+ })
+
+ expect(status).toBe('permission')
+ })
+
+ it('lets heuristic working beat hasLiveDone (newer in-progress signal wins)', () => {
+ const status = resolveWorktreeStatus({
+ tabs: [{ id: 'tab-1', title: 'claude [working]' }],
+ browserTabs: [],
+ ptyIdsByTabId: livePtyMap('tab-1'),
+ hasPermission: false,
+ hasLiveDone: true,
+ hasRetainedDone: false
+ })
+
+ expect(status).toBe('working')
+ })
+
+ // Why: title-heuristic permission must beat hasLiveDone/hasRetainedDone —
+ // the priority "permission > working > done > heuristic" applies to BOTH
+ // sources of permission (the args.hasPermission overlay AND the heuristic
+ // 'permission' return). Otherwise a tab title scraping "permission" would
+ // be silently downgraded to 'done' whenever a separate done overlay exists.
+ it('honors heuristic permission over hasLiveDone (priority: permission > done)', () => {
+ const status = resolveWorktreeStatus({
+ tabs: [{ id: 'tab-1', title: 'claude [permission]' }],
+ browserTabs: [],
+ ptyIdsByTabId: livePtyMap('tab-1'),
+ hasPermission: false,
+ hasLiveDone: true,
+ hasRetainedDone: false
+ })
+
+ expect(status).toBe('permission')
+ })
+
+ it('promotes to done when live and hasRetainedDone (no working heuristic)', () => {
+ const status = resolveWorktreeStatus({
+ tabs: [{ id: 'tab-1', title: 'bash' }],
+ browserTabs: [],
+ ptyIdsByTabId: livePtyMap('tab-1'),
+ hasPermission: false,
+ hasLiveDone: false,
+ hasRetainedDone: true
+ })
+
+ expect(status).toBe('done')
+ })
+
+ it('falls through to active heuristic when nothing else applies', () => {
+ const status = resolveWorktreeStatus({
+ tabs: [{ id: 'tab-1', title: 'bash' }],
+ browserTabs: [],
+ ptyIdsByTabId: livePtyMap('tab-1'),
+ hasPermission: false,
+ hasLiveDone: false,
+ hasRetainedDone: false
+ })
+
+ expect(status).toBe('active')
+ })
})
diff --git a/src/renderer/src/lib/worktree-status.ts b/src/renderer/src/lib/worktree-status.ts
index 008966216..1c10f6868 100644
--- a/src/renderer/src/lib/worktree-status.ts
+++ b/src/renderer/src/lib/worktree-status.ts
@@ -1,4 +1,5 @@
import { detectAgentStatusFromTitle } from '@/lib/agent-status'
+import { tabHasLivePty } from '@/lib/tab-has-live-pty'
import type { TerminalTab } from '../../../shared/types'
export type WorktreeStatus = 'active' | 'working' | 'permission' | 'done' | 'inactive'
@@ -12,11 +13,18 @@ const STATUS_LABELS: Record = {
}
export function getWorktreeStatus(
- tabs: Pick[],
+ tabs: Pick[],
browserTabs: { id: string }[],
+ ptyIdsByTabId: Record,
runtimePaneTitlesByTabId: Record> = {}
): WorktreeStatus {
- const liveTabs = tabs.filter((tab) => tab.ptyId)
+ // Why: liveness gates every promotion. tab.ptyId is the wake-hint sessionId
+ // preserved across sleep (so wake can reattach to the same daemon history
+ // dir / relay session) — it is *not* a liveness signal. ptyIdsByTabId is the
+ // source of truth: sleep clears it to []; pty.spawn writes it; pty.kill
+ // clears it. Reading the live-pty map keeps the dot honest after sleep,
+ // crash, or any path where the wake-hint outlives the actual PTY.
+ const liveTabs = tabs.filter((tab) => tabHasLivePty(ptyIdsByTabId, tab.id))
// Why: a split-pane tab can host multiple concurrent agents, but `tab.title`
// only reflects the most-recently-focused pane (see onActivePaneChange in
@@ -65,3 +73,68 @@ function tabHasStatus(
export function getWorktreeStatusLabel(status: WorktreeStatus): string {
return STATUS_LABELS[status]
}
+
+/**
+ * Apply the WorktreeCard priority overlay (permission > working > done >
+ * heuristic) on top of the title-heuristic base. The live-pty precondition is
+ * inherited via getWorktreeStatus: when no tab in this worktree has a live
+ * PTY and no browser tab exists, getWorktreeStatus returns 'inactive' and
+ * none of the promotion paths fire — so the worktree dot stays grey across
+ * sleep, renderer crash + rehydration, and any other path where wake-hint
+ * sessionIds outlive the actual PTY. On sleep specifically,
+ * `dropAgentStatusByWorktree` also clears retained rows for the worktree, so
+ * this precondition is the second line of defense; the rehydration-from-disk
+ * path is where retained 'done' rows can outlive the live PTY and the
+ * precondition does the load-bearing work.
+ *
+ * Argument semantics (sourced by the WorktreeCard caller from the store):
+ * - `tabs`, `browserTabs`: the worktree's terminal and browser tabs.
+ * - `ptyIdsByTabId`: live-PTY map narrowed to this worktree (the liveness
+ * gate; see tabHasLivePty).
+ * - `runtimePaneTitlesByTabId`: per-tab pane title map narrowed to this
+ * worktree (used by the title-heuristic for split-pane spinners).
+ * - `hasPermission`: any fresh hook entry in {blocked, waiting} for a tab in
+ * this worktree.
+ * - `hasLiveDone`: any fresh hook entry in {done} for a tab in this worktree.
+ * - `hasRetainedDone`: any retained-agent snapshot scoped to this worktreeId.
+ */
+export function resolveWorktreeStatus(args: {
+ tabs: Pick[]
+ browserTabs: { id: string }[]
+ ptyIdsByTabId: Record
+ runtimePaneTitlesByTabId?: Record>
+ hasPermission: boolean
+ hasLiveDone: boolean
+ hasRetainedDone: boolean
+}): WorktreeStatus {
+ const heuristic = getWorktreeStatus(
+ args.tabs,
+ args.browserTabs,
+ args.ptyIdsByTabId,
+ args.runtimePaneTitlesByTabId ?? {}
+ )
+ // Why: liveness precondition. Without any live PTY (and no browser tab),
+ // agent-state hooks and retained-done snapshots must not promote the dot
+ // off grey — the agent process is gone the instant pty.kill fires.
+ if (heuristic === 'inactive') {
+ return 'inactive'
+ }
+ if (args.hasPermission) {
+ return 'permission'
+ }
+ // Why: heuristic 'permission' must outrank heuristic 'working' (a tab can
+ // be "working" while another pane in the same tab is blocked on permission;
+ // the user-actionable signal wins). Both this branch and the args.hasPermission
+ // branch above return 'permission' — they're separated only because
+ // args.hasPermission must also outrank heuristic 'working' below.
+ if (heuristic === 'permission') {
+ return 'permission'
+ }
+ if (heuristic === 'working') {
+ return 'working'
+ }
+ if (args.hasLiveDone || args.hasRetainedDone) {
+ return 'done'
+ }
+ return heuristic
+}
diff --git a/src/renderer/src/store/slices/agent-status.ts b/src/renderer/src/store/slices/agent-status.ts
index 41203950b..be0a5ebff 100644
--- a/src/renderer/src/store/slices/agent-status.ts
+++ b/src/renderer/src/store/slices/agent-status.ts
@@ -71,6 +71,21 @@ export type AgentStatusSlice = {
* remaining agent rows (live or retained) must not reappear. */
dropAgentStatusByTabPrefix: (tabIdPrefix: string) => void
+ /** Remove all entries for a worktree AND suppress re-retention for live rows.
+ * Used on worktree sleep/remove — the whole worktree surface is folding, so
+ * retained rows must drop even if their original tab is no longer present.
+ *
+ * Note on orphan-live asymmetry: liveKeys are matched against tab prefixes
+ * derived from `tabsByWorktree[worktreeId]`. Live entries belonging to the
+ * same worktree but whose tab has already been pruned from `tabsByWorktree`
+ * (an orphan-live race) are not swept here. The retained side has a
+ * fallback (`retained.worktreeId === worktreeId`); the live side does not,
+ * because live entries do not carry a worktreeId. In practice the gap is
+ * bounded — `removeAgentStatus` is called on PTY exit — and dropping an
+ * orphan-live entry on shutdown is best-effort, so accepting the asymmetry
+ * is the simpler tradeoff. */
+ dropAgentStatusByWorktree: (worktreeId: string) => void
+
/** Retain agent snapshots (called by the top-level retention sync effect).
* Accepts an array so multiple agents disappearing in the same frame
* produce a single set(...) — avoids intermediate states visible
@@ -91,6 +106,15 @@ export type AgentStatusSlice = {
clearRetentionSuppressedPaneKeys: (paneKeys: string[]) => void
}
+function paneKeyMatchesAnyTabPrefix(paneKey: string, tabPrefixes: string[]): boolean {
+ for (const prefix of tabPrefixes) {
+ if (paneKey.startsWith(prefix)) {
+ return true
+ }
+ }
+ return false
+}
+
export const createAgentStatusSlice: StateCreator = (
set,
get
@@ -466,6 +490,13 @@ export const createAgentStatusSlice: StateCreator !(k in s.retentionSuppressedPaneKeys))
let nextRetentionSuppressedPaneKeys = s.retentionSuppressedPaneKeys
if (suppressorAdds.length > 0) {
@@ -494,6 +525,84 @@ export const createAgentStatusSlice: StateCreator {
+ let hadLive = false
+ set((s) => {
+ const tabPrefixes = (s.tabsByWorktree[worktreeId] ?? []).map((tab) => `${tab.id}:`)
+ const liveKeys = Object.keys(s.agentStatusByPaneKey).filter((k) =>
+ paneKeyMatchesAnyTabPrefix(k, tabPrefixes)
+ )
+ const retainedKeys = Object.entries(s.retainedAgentsByPaneKey)
+ .filter(
+ ([paneKey, retained]) =>
+ retained.worktreeId === worktreeId || paneKeyMatchesAnyTabPrefix(paneKey, tabPrefixes)
+ )
+ .map(([paneKey]) => paneKey)
+ const retainedKeySet = new Set(retainedKeys)
+ // See removeAgentStatus for rationale on ack cleanup. Current tabs are
+ // swept by prefix; orphan retained rows are swept by their retained key.
+ let nextAck = s.acknowledgedAgentsByPaneKey
+ const ackKeys = Object.keys(nextAck).filter(
+ (k) => paneKeyMatchesAnyTabPrefix(k, tabPrefixes) || retainedKeySet.has(k)
+ )
+ if (ackKeys.length > 0) {
+ nextAck = { ...nextAck }
+ for (const key of ackKeys) {
+ delete nextAck[key]
+ }
+ }
+ // Mirror dropAgentStatusByTabPrefix: when nothing live or retained
+ // changed, narrow the return to just the ack delta (or s) so we don't
+ // emit a new top-level state object that re-renders full-state
+ // subscribers for nothing.
+ if (liveKeys.length === 0 && retainedKeys.length === 0) {
+ if (nextAck !== s.acknowledgedAgentsByPaneKey) {
+ return { acknowledgedAgentsByPaneKey: nextAck }
+ }
+ return s
+ }
+ hadLive = liveKeys.length > 0
+
+ const nextLive =
+ liveKeys.length > 0 ? { ...s.agentStatusByPaneKey } : s.agentStatusByPaneKey
+ for (const key of liveKeys) {
+ delete nextLive[key]
+ }
+
+ const nextRetained =
+ retainedKeys.length > 0 ? { ...s.retainedAgentsByPaneKey } : s.retainedAgentsByPaneKey
+ for (const key of retainedKeys) {
+ delete nextRetained[key]
+ }
+
+ // Why: a worktree-level teardown folds the whole surface. Current live
+ // rows need one-shot suppressors so the retention sync cannot recreate a
+ // done row from the previous render after sleep/remove has hidden it.
+ const suppressorAdds = liveKeys.filter((k) => !(k in s.retentionSuppressedPaneKeys))
+ let nextRetentionSuppressedPaneKeys = s.retentionSuppressedPaneKeys
+ if (suppressorAdds.length > 0) {
+ nextRetentionSuppressedPaneKeys = { ...s.retentionSuppressedPaneKeys }
+ for (const key of suppressorAdds) {
+ nextRetentionSuppressedPaneKeys[key] = true
+ }
+ }
+
+ return {
+ agentStatusByPaneKey: nextLive,
+ retainedAgentsByPaneKey: nextRetained,
+ retentionSuppressedPaneKeys: nextRetentionSuppressedPaneKeys,
+ ...(nextAck !== s.acknowledgedAgentsByPaneKey
+ ? { acknowledgedAgentsByPaneKey: nextAck }
+ : {}),
+ agentStatusEpoch: hadLive ? s.agentStatusEpoch + 1 : s.agentStatusEpoch,
+ sortEpoch: hadLive ? s.sortEpoch + 1 : s.sortEpoch
+ }
+ })
+ if (hadLive) {
+ queueMicrotask(() => freshness.schedule())
+ }
+ },
+
retainAgents: (entries) => {
// Why: retained entries are a pure read-overlay — consumers read
// retainedAgentsByPaneKey directly each render, so no sort/status epoch
diff --git a/src/renderer/src/store/slices/store-cascades.test.ts b/src/renderer/src/store/slices/store-cascades.test.ts
index 2870e6595..ed4f74631 100644
--- a/src/renderer/src/store/slices/store-cascades.test.ts
+++ b/src/renderer/src/store/slices/store-cascades.test.ts
@@ -1353,3 +1353,263 @@ describe('setActiveWorktree', () => {
expect(s.activeFileId).toBe(fileId)
})
})
+
+// Why: sleep (`shutdownWorktreeTerminals(wt, { keepIdentifiers: true })`)
+// kills the PTYs but preserves wake hints (tab.ptyId, ptyIdsByLeafId, the
+// runtime pane titles) so wake can reattach to the same daemon-history dir
+// or relay session. Before the sleep-statuses fix, the live agent-status
+// rows were also preserved — so a Claude that was mid-turn at sleep time
+// kept its row in the inline agents list as "working" until the 30-min
+// stale TTL decayed it. Sleep now drops live entries and retained `done`
+// snapshots for the whole worktree, so the card folds to a single grey signal.
+describe('shutdownWorktreeTerminals (sleep) — agent status hygiene', () => {
+ beforeEach(() => {
+ vi.clearAllMocks()
+ mockApi.pty.kill.mockResolvedValue(undefined)
+ })
+
+ it('drops live agentStatusByPaneKey entries on sleep so the working row disappears', async () => {
+ const store = createTestStore()
+ const wt = 'repo1::/path/wt1'
+
+ seedStore(store, {
+ worktreesByRepo: {
+ repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
+ },
+ tabsByWorktree: {
+ [wt]: [makeTab({ id: 'tab-1', worktreeId: wt })]
+ },
+ ptyIdsByTabId: { 'tab-1': ['pty-1'] }
+ })
+
+ store.getState().setAgentStatus('tab-1:0', {
+ state: 'working',
+ prompt: 'p',
+ agentType: 'claude'
+ })
+ expect(store.getState().agentStatusByPaneKey['tab-1:0']).toBeDefined()
+
+ await store.getState().shutdownWorktreeTerminals(wt, { keepIdentifiers: true })
+
+ const s = store.getState()
+ expect(s.agentStatusByPaneKey['tab-1:0']).toBeUndefined()
+ })
+
+ it('drops retainedAgentsByPaneKey entries for the slept worktree', async () => {
+ const store = createTestStore()
+ const wt = 'repo1::/path/wt1'
+ const otherWt = 'repo1::/path/wt2'
+
+ seedStore(store, {
+ worktreesByRepo: {
+ repo1: [
+ makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' }),
+ makeWorktree({ id: otherWt, repoId: 'repo1', path: '/path/wt2' })
+ ]
+ },
+ tabsByWorktree: {
+ [wt]: [makeTab({ id: 'tab-1', worktreeId: wt })],
+ [otherWt]: [makeTab({ id: 'tab-2', worktreeId: otherWt })]
+ },
+ ptyIdsByTabId: { 'tab-1': ['pty-1'] }
+ })
+
+ // Plant one current-tab row and one orphan row. Retained rows render by
+ // worktreeId, so sleep must sweep both instead of only tab prefixes.
+ store.getState().retainAgents([
+ {
+ entry: {
+ paneKey: 'tab-1:0',
+ state: 'done',
+ stateStartedAt: 1000,
+ updatedAt: 1000,
+ stateHistory: [],
+ prompt: 'finished prompt',
+ agentType: 'claude',
+ terminalTitle: undefined,
+ interrupted: false
+ },
+ worktreeId: wt,
+ tab: makeTab({ id: 'tab-1', worktreeId: wt, title: 'Claude' }),
+ agentType: 'claude',
+ startedAt: 1000
+ },
+ {
+ entry: {
+ paneKey: 'tab-orphan:0',
+ state: 'done',
+ stateStartedAt: 1001,
+ updatedAt: 1001,
+ stateHistory: [],
+ prompt: 'orphaned finished prompt',
+ agentType: 'claude',
+ terminalTitle: undefined,
+ interrupted: false
+ },
+ worktreeId: wt,
+ tab: makeTab({ id: 'tab-orphan', worktreeId: wt, title: 'Claude' }),
+ agentType: 'claude',
+ startedAt: 1001
+ },
+ {
+ entry: {
+ paneKey: 'tab-2:0',
+ state: 'done',
+ stateStartedAt: 1002,
+ updatedAt: 1002,
+ stateHistory: [],
+ prompt: 'other prompt',
+ agentType: 'claude',
+ terminalTitle: undefined,
+ interrupted: false
+ },
+ worktreeId: otherWt,
+ tab: makeTab({ id: 'tab-2', worktreeId: otherWt, title: 'Claude' }),
+ agentType: 'claude',
+ startedAt: 1002
+ }
+ ])
+ expect(store.getState().retainedAgentsByPaneKey['tab-1:0']).toBeDefined()
+ expect(store.getState().retainedAgentsByPaneKey['tab-orphan:0']).toBeDefined()
+ expect(store.getState().retainedAgentsByPaneKey['tab-2:0']).toBeDefined()
+ store.getState().acknowledgeAgents(['tab-1:0', 'tab-orphan:0', 'tab-2:0'])
+
+ await store.getState().shutdownWorktreeTerminals(wt, { keepIdentifiers: true })
+
+ expect(store.getState().retainedAgentsByPaneKey['tab-1:0']).toBeUndefined()
+ expect(store.getState().retainedAgentsByPaneKey['tab-orphan:0']).toBeUndefined()
+ expect(store.getState().retainedAgentsByPaneKey['tab-2:0']).toBeDefined()
+ expect(store.getState().acknowledgedAgentsByPaneKey['tab-1:0']).toBeUndefined()
+ expect(store.getState().acknowledgedAgentsByPaneKey['tab-orphan:0']).toBeUndefined()
+ expect(store.getState().acknowledgedAgentsByPaneKey['tab-2:0']).toBeGreaterThan(0)
+ })
+
+ it('clears prior acknowledgements on sleep because the worktree surface is folded', async () => {
+ const store = createTestStore()
+ const wt = 'repo1::/path/wt1'
+
+ seedStore(store, {
+ worktreesByRepo: {
+ repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
+ },
+ tabsByWorktree: {
+ [wt]: [makeTab({ id: 'tab-1', worktreeId: wt })]
+ },
+ ptyIdsByTabId: { 'tab-1': ['pty-1'] }
+ })
+
+ store.getState().setAgentStatus('tab-1:0', {
+ state: 'working',
+ prompt: 'p',
+ agentType: 'claude'
+ })
+ store.getState().acknowledgeAgents(['tab-1:0'])
+ const ackBeforeSleep = store.getState().acknowledgedAgentsByPaneKey['tab-1:0']
+ expect(ackBeforeSleep).toBeGreaterThan(0)
+
+ await store.getState().shutdownWorktreeTerminals(wt, { keepIdentifiers: true })
+
+ expect(store.getState().acknowledgedAgentsByPaneKey['tab-1:0']).toBeUndefined()
+ })
+
+ it('plants retention suppressors on sleep so a previously-live `done` cannot re-retain', async () => {
+ const store = createTestStore()
+ const wt = 'repo1::/path/wt1'
+
+ seedStore(store, {
+ worktreesByRepo: {
+ repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
+ },
+ tabsByWorktree: {
+ [wt]: [makeTab({ id: 'tab-1', worktreeId: wt })]
+ },
+ ptyIdsByTabId: { 'tab-1': ['pty-1'] }
+ })
+
+ store.getState().setAgentStatus('tab-1:0', {
+ state: 'done',
+ prompt: 'p',
+ agentType: 'claude'
+ })
+ expect(store.getState().retentionSuppressedPaneKeys['tab-1:0']).toBeUndefined()
+
+ await store.getState().shutdownWorktreeTerminals(wt, { keepIdentifiers: true })
+
+ // Why: sleep folds retained rows too, so the next retention sync must not
+ // recreate a `done` row from the previous render after the user slept it.
+ expect(store.getState().retentionSuppressedPaneKeys['tab-1:0']).toBe(true)
+ })
+
+ it('preserves existing retention suppressors across sleep (identity-preserved suppressor map)', async () => {
+ const store = createTestStore()
+ const wt = 'repo1::/path/wt1'
+
+ seedStore(store, {
+ worktreesByRepo: {
+ repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
+ },
+ tabsByWorktree: {
+ [wt]: [makeTab({ id: 'tab-1', worktreeId: wt })]
+ },
+ ptyIdsByTabId: { 'tab-1': ['pty-1'] },
+ retentionSuppressedPaneKeys: { 'tab-1:0': true }
+ })
+
+ expect(store.getState().retentionSuppressedPaneKeys['tab-1:0']).toBe(true)
+
+ await store.getState().shutdownWorktreeTerminals(wt, { keepIdentifiers: true })
+
+ // Why: an existing suppressor was planted by a prior dismissal flow; sleep
+ // must not erase it (would resurface a row the user already dismissed).
+ expect(store.getState().retentionSuppressedPaneKeys['tab-1:0']).toBe(true)
+ })
+
+ it('still wipes retained + ack entries under remove-worktree shutdown', async () => {
+ const store = createTestStore()
+ const wt = 'repo1::/path/wt1'
+
+ seedStore(store, {
+ worktreesByRepo: {
+ repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })]
+ },
+ tabsByWorktree: {
+ [wt]: [makeTab({ id: 'tab-1', worktreeId: wt })]
+ },
+ ptyIdsByTabId: { 'tab-1': ['pty-1'] }
+ })
+
+ store.getState().setAgentStatus('tab-1:0', {
+ state: 'working',
+ prompt: 'p',
+ agentType: 'claude'
+ })
+ store.getState().acknowledgeAgents(['tab-1:0'])
+ store.getState().retainAgents([
+ {
+ entry: {
+ paneKey: 'tab-1:0',
+ state: 'done',
+ stateStartedAt: 1000,
+ updatedAt: 1000,
+ stateHistory: [],
+ prompt: 'p',
+ agentType: 'claude',
+ terminalTitle: undefined,
+ interrupted: false
+ },
+ worktreeId: wt,
+ tab: makeTab({ id: 'tab-1', worktreeId: wt, title: 'Claude' }),
+ agentType: 'claude',
+ startedAt: 1000
+ }
+ ])
+
+ // Default opts (no keepIdentifiers) => remove-worktree path.
+ await store.getState().shutdownWorktreeTerminals(wt)
+
+ const s = store.getState()
+ expect(s.agentStatusByPaneKey['tab-1:0']).toBeUndefined()
+ expect(s.retainedAgentsByPaneKey['tab-1:0']).toBeUndefined()
+ expect(s.acknowledgedAgentsByPaneKey['tab-1:0']).toBeUndefined()
+ })
+})
diff --git a/src/renderer/src/store/slices/store-session-cascades.test.ts b/src/renderer/src/store/slices/store-session-cascades.test.ts
index e5301fd63..331c10cdb 100644
--- a/src/renderer/src/store/slices/store-session-cascades.test.ts
+++ b/src/renderer/src/store/slices/store-session-cascades.test.ts
@@ -744,6 +744,57 @@ describe('terminal slice behaviors', () => {
expect(store.getState().tabsByWorktree[worktreeId][0].pendingActivationSpawn).toBeUndefined()
})
+ it('bumps activation generation for slept wake-hint tabs with no live PTY', () => {
+ const store = createTestStore()
+ const worktreeId = 'repo1::/path/wt1'
+
+ store.setState({
+ repos: [
+ { id: 'repo1', path: '/repo1', displayName: 'Repo 1', badgeColor: '#000', addedAt: 0 }
+ ],
+ worktreesByRepo: {
+ repo1: [makeWorktree({ id: worktreeId, repoId: 'repo1', path: '/path/wt1' })]
+ },
+ tabsByWorktree: {
+ [worktreeId]: [
+ makeTab({
+ id: 'tab-1',
+ worktreeId,
+ ptyId: 'wake-hint-session',
+ generation: 2
+ })
+ ]
+ },
+ ptyIdsByTabId: { 'tab-1': [] },
+ unifiedTabsByWorktree: {
+ [worktreeId]: [
+ {
+ id: 'tab-1',
+ entityId: 'tab-1',
+ groupId: 'group-1',
+ worktreeId,
+ contentType: 'terminal',
+ label: 'Terminal 1',
+ customLabel: null,
+ color: null,
+ sortOrder: 0,
+ createdAt: 1
+ }
+ ]
+ },
+ groupsByWorktree: {
+ [worktreeId]: [{ id: 'group-1', worktreeId, activeTabId: 'tab-1', tabOrder: ['tab-1'] }]
+ },
+ activeGroupIdByWorktree: { [worktreeId]: 'group-1' }
+ })
+
+ store.getState().setActiveWorktree(worktreeId)
+
+ const tab = store.getState().tabsByWorktree[worktreeId][0]
+ expect(tab.generation).toBe(3)
+ expect(tab.pendingActivationSpawn).toBe(true)
+ })
+
// Why: the FIRST activation of a worktree tags every tab — even if tab.ptyId
// already looks live, because reconnectPersistedTerminals can re-populate
// tab.ptyId with a restored daemon session ID before the pane mounts, making
diff --git a/src/renderer/src/store/slices/tabs.ts b/src/renderer/src/store/slices/tabs.ts
index 60108dcb2..01b1951e6 100644
--- a/src/renderer/src/store/slices/tabs.ts
+++ b/src/renderer/src/store/slices/tabs.ts
@@ -1285,6 +1285,15 @@ export const createTabsSlice: StateCreator = (set,
if (unifiedTerminalEntityIds.has(tab.id)) {
return false
}
+ // Why: this is a one-shot migration filter for tabs not yet promoted
+ // to unifiedTabs — keeping the wake-hint `tab.ptyId` clause is
+ // intentional. tab.ptyId is the preserved sessionId (so wake can
+ // reattach to the same daemon-history dir / relay session); a slept
+ // tab will have `livePtyIds` empty *and* `tab.ptyId` populated, and
+ // we want it included in the migration sweep so reconcile picks it
+ // up. Reconcile fires again post-reattach, so the eventual live PTY
+ // also routes through this branch. Do *not* repurpose this as an
+ // "is this tab alive?" check — those reads must use ptyIdsByTabId.
const livePtyIds = state.ptyIdsByTabId[tab.id] ?? []
return livePtyIds.length > 0 || tab.ptyId != null
})
diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts
index 3555aec40..562abda05 100644
--- a/src/renderer/src/store/slices/terminals.ts
+++ b/src/renderer/src/store/slices/terminals.ts
@@ -1125,17 +1125,12 @@ export const createTerminalSlice: StateCreator
}
})
- // Why: under remove-worktree, sweep agent-status rows so a tab killed in
- // the 'done' state doesn't leave the WorktreeCard dot blue. Under sleep,
- // the agent-status describes the live agent process which the user
- // expects to survive sleep — skip the drop so wake renders the prior
- // status until the next event arrives. (Mirror of the pattern in
- // closeTab / pane-close, which drop their own rows explicitly.)
- if (!keepIdentifiers) {
- for (const tab of tabs) {
- get().dropAgentStatusByTabPrefix(tab.id)
- }
- }
+ // Why: sleep/remove fold the whole worktree surface. The live PTY bindings
+ // were cleared above and kill is about to run, so live rows are stale;
+ // retained rows are folded too so a grey slept card does not keep a green
+ // "done" row. Sweep by worktreeId because retained snapshots can outlive
+ // their original tab.
+ get().dropAgentStatusByWorktree(worktreeId)
if (ptyIds.length === 0) {
return
@@ -1686,13 +1681,16 @@ export const createTerminalSlice: StateCreator
const tabLevelPtyId = pendingReconnectPtyIdByTabId[tabId]
const hasLeafMappings = Object.keys(leafPtyMap).length > 0
- // Why: restore ptyId on the tab so getWorktreeStatus() sees it as
- // active (green dot) even before the terminal pane mounts — including
- // deferred SSH worktrees whose connection isn't established yet. Without
- // this, the sidebar "show active only" filter hides SSH worktrees and
- // the user must manually search for them. The actual PTY reattach is
- // handled later by pty-connection.ts when the terminal pane mounts;
- // this block only sets the visual state.
+ // Why: populate the wake-hint and the live-pty map so the worktree
+ // dot lights up green even before the terminal pane mounts —
+ // including deferred SSH worktrees whose connection isn't established
+ // yet. tab.ptyId carries the wake-hint sessionId (consumed by
+ // pty-connection.ts on remount); ptyIdsByTabId is the source of
+ // truth getWorktreeStatus reads for liveness. Without the live-pty
+ // population, the sidebar "show active only" filter hides SSH
+ // worktrees and the user must manually search for them. The actual
+ // PTY reattach is handled later by pty-connection.ts when the
+ // terminal pane mounts; this block only sets the visual state.
console.warn(
`[reconnect-terminals] tab=${tabId} tabLevelPtyId=${tabLevelPtyId} supportsDeferredReattach=${supportsDeferredReattach} hasLeafMappings=${hasLeafMappings}`
)
diff --git a/src/renderer/src/store/slices/worktrees.ts b/src/renderer/src/store/slices/worktrees.ts
index e63607205..5074b8cb2 100644
--- a/src/renderer/src/store/slices/worktrees.ts
+++ b/src/renderer/src/store/slices/worktrees.ts
@@ -9,6 +9,7 @@ import {
type WorktreeSlice
} from './worktree-helpers'
import { ensureHooksConfirmed } from '@/lib/ensure-hooks-confirmed'
+import { tabHasLivePty } from '@/lib/tab-has-live-pty'
export type { WorktreeSlice, WorktreeDeleteState } from './worktree-helpers'
function arraysShallowEqual(a: string[] | undefined, b: string[] | undefined): boolean {
@@ -875,10 +876,13 @@ export const createWorktreeSlice: StateCreator
// live to allDead even though the next updateTabPtyId is a reattach.
// Tracking first-activation per worktree is the reliable signal.
//
- // Generation is still only bumped when tabs are allDead — a live tab
- // remount would kill the user's running shell.
+ // Generation is still only bumped when tabs have no live PTY — a live
+ // tab remount would kill the user's running shell.
const tabs = s.tabsByWorktree[worktreeId ?? ''] ?? []
- const allDead = worktreeId && tabs.length > 0 && tabs.every((tab) => !tab.ptyId)
+ const allDead =
+ worktreeId != null &&
+ tabs.length > 0 &&
+ tabs.every((tab) => !tabHasLivePty(s.ptyIdsByTabId, tab.id))
const isFirstActivation = worktreeId != null && !s.everActivatedWorktreeIds.has(worktreeId)
const shouldTagTabs = worktreeId != null && tabs.length > 0 && isFirstActivation
const nextEverActivated = isFirstActivation