fix(agents): make pane retention transfer-aware instead of suppressor-based (#11310)
This commit is contained in:
@@ -2,19 +2,22 @@
|
||||
import { act, renderHook } from '@testing-library/react'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { useAppStore } from '@/store'
|
||||
import { resetAgentPaneAuthorityAliasesForTests } from '@/store/slices/agent-pane-authority'
|
||||
import type { AgentStatusEntry, AgentStatusState } from '../../../../shared/agent-status-types'
|
||||
import { makePaneKey } from '../../../../shared/stable-pane-id'
|
||||
import type { Repo, Worktree } from '../../../../shared/types'
|
||||
import type { Repo, TerminalTab, Worktree } from '../../../../shared/types'
|
||||
import { collectRetainedAgentsOnDisappear, useRetainedAgentsSync } from './useRetainedAgents'
|
||||
|
||||
const initialAppState = useAppStore.getInitialState()
|
||||
|
||||
beforeEach(() => {
|
||||
useAppStore.setState(initialAppState, true)
|
||||
resetAgentPaneAuthorityAliasesForTests()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
useAppStore.setState(initialAppState, true)
|
||||
resetAgentPaneAuthorityAliasesForTests()
|
||||
})
|
||||
|
||||
function makeRepo(): Repo {
|
||||
@@ -49,6 +52,19 @@ function makeWorktree(): Worktree {
|
||||
}
|
||||
}
|
||||
|
||||
function makeTab(overrides: Partial<TerminalTab> & { id: string }): TerminalTab {
|
||||
return {
|
||||
worktreeId: 'wt-1',
|
||||
title: 'Terminal',
|
||||
ptyId: null,
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function makeAgentRow(args: { paneKey: string; state: AgentStatusState; interrupted?: boolean }) {
|
||||
const entry: AgentStatusEntry = {
|
||||
state: args.state,
|
||||
@@ -65,16 +81,7 @@ function makeAgentRow(args: { paneKey: string; state: AgentStatusState; interrup
|
||||
return {
|
||||
paneKey: args.paneKey,
|
||||
entry,
|
||||
tab: {
|
||||
id: 'tab-1',
|
||||
worktreeId: 'wt-1',
|
||||
title: 'Terminal',
|
||||
ptyId: null,
|
||||
customTitle: null,
|
||||
color: null,
|
||||
sortOrder: 0,
|
||||
createdAt: 1
|
||||
},
|
||||
tab: makeTab({ id: 'tab-1' }),
|
||||
agentType: 'claude' as const,
|
||||
state: args.state,
|
||||
startedAt: 1
|
||||
@@ -92,7 +99,8 @@ describe('collectRetainedAgentsOnDisappear', () => {
|
||||
currentAgents: new Map(),
|
||||
retainedAgentsByPaneKey: {},
|
||||
retentionSuppressedPaneKeys: {},
|
||||
recentlyClosedAgentStatusTabIds: { 'tab-2': true }
|
||||
recentlyClosedAgentStatusTabIds: { 'tab-2': true },
|
||||
recentlyRetiredAgentStatusPaneKeys: {}
|
||||
})
|
||||
|
||||
expect(result.toRetain).toHaveLength(1)
|
||||
@@ -116,7 +124,8 @@ describe('collectRetainedAgentsOnDisappear', () => {
|
||||
currentAgents: new Map(),
|
||||
retainedAgentsByPaneKey: {},
|
||||
retentionSuppressedPaneKeys: {},
|
||||
recentlyClosedAgentStatusTabIds: {}
|
||||
recentlyClosedAgentStatusTabIds: {},
|
||||
recentlyRetiredAgentStatusPaneKeys: {}
|
||||
})
|
||||
|
||||
expect(result.toRetain).toEqual([])
|
||||
@@ -145,7 +154,8 @@ describe('collectRetainedAgentsOnDisappear', () => {
|
||||
currentAgents: new Map(),
|
||||
retainedAgentsByPaneKey: { 'tab-1:1': staleRetained },
|
||||
retentionSuppressedPaneKeys: {},
|
||||
recentlyClosedAgentStatusTabIds: {}
|
||||
recentlyClosedAgentStatusTabIds: {},
|
||||
recentlyRetiredAgentStatusPaneKeys: {}
|
||||
})
|
||||
|
||||
expect(result.toRetain).toHaveLength(1)
|
||||
@@ -170,7 +180,8 @@ describe('collectRetainedAgentsOnDisappear', () => {
|
||||
currentAgents: new Map(),
|
||||
retainedAgentsByPaneKey: { 'tab-1:1': sameRunRetained },
|
||||
retentionSuppressedPaneKeys: {},
|
||||
recentlyClosedAgentStatusTabIds: {}
|
||||
recentlyClosedAgentStatusTabIds: {},
|
||||
recentlyRetiredAgentStatusPaneKeys: {}
|
||||
})
|
||||
|
||||
expect(result.toRetain).toEqual([])
|
||||
@@ -186,7 +197,8 @@ describe('collectRetainedAgentsOnDisappear', () => {
|
||||
currentAgents: new Map(),
|
||||
retainedAgentsByPaneKey: {},
|
||||
retentionSuppressedPaneKeys: { 'tab-1:1': true },
|
||||
recentlyClosedAgentStatusTabIds: {}
|
||||
recentlyClosedAgentStatusTabIds: {},
|
||||
recentlyRetiredAgentStatusPaneKeys: {}
|
||||
})
|
||||
|
||||
expect(result.toRetain).toEqual([])
|
||||
@@ -203,7 +215,8 @@ describe('collectRetainedAgentsOnDisappear', () => {
|
||||
currentAgents: new Map(),
|
||||
retainedAgentsByPaneKey: {},
|
||||
retentionSuppressedPaneKeys: {},
|
||||
recentlyClosedAgentStatusTabIds: { 'tab-1': true }
|
||||
recentlyClosedAgentStatusTabIds: { 'tab-1': true },
|
||||
recentlyRetiredAgentStatusPaneKeys: {}
|
||||
})
|
||||
|
||||
expect(result.toRetain).toEqual([])
|
||||
@@ -245,4 +258,52 @@ describe('useRetainedAgentsSync', () => {
|
||||
expect(state.retainedAgentsByPaneKey[row.paneKey]).toBeUndefined()
|
||||
hook.unmount()
|
||||
})
|
||||
|
||||
it('does not leave a ghost row when a done pane detaches into another tab', async () => {
|
||||
const repo = makeRepo()
|
||||
const worktree = makeWorktree()
|
||||
const leafId = '11111111-1111-4111-8111-111111111111'
|
||||
const sourceTab = makeTab({ id: 'tab-source', ptyId: 'pty-a' })
|
||||
const targetTab = makeTab({ id: 'tab-target' })
|
||||
const sourcePaneKey = makePaneKey(sourceTab.id, leafId)
|
||||
const targetPaneKey = makePaneKey(targetTab.id, leafId)
|
||||
const row = makeAgentRow({ paneKey: sourcePaneKey, state: 'done' })
|
||||
useAppStore.setState({
|
||||
repos: [repo],
|
||||
worktreesByRepo: { [repo.id]: [worktree] },
|
||||
tabsByWorktree: { [worktree.id]: [sourceTab, targetTab] },
|
||||
ptyIdsByTabId: { [sourceTab.id]: ['pty-a'], [targetTab.id]: [] },
|
||||
agentStatusByPaneKey: { [sourcePaneKey]: { ...row.entry, tabId: sourceTab.id } },
|
||||
agentStatusEpoch: initialAppState.agentStatusEpoch + 1
|
||||
})
|
||||
const hook = renderHook(() => useRetainedAgentsSync())
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
})
|
||||
|
||||
act(() => {
|
||||
useAppStore.getState().syncPaneDetachPtyOwnership({
|
||||
detachedLeafId: leafId,
|
||||
detachedPtyId: 'pty-a',
|
||||
sourceLayout: {
|
||||
root: null,
|
||||
activeLeafId: null,
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: {}
|
||||
},
|
||||
sourceTabId: sourceTab.id,
|
||||
targetTabId: targetTab.id
|
||||
})
|
||||
})
|
||||
await act(async () => {
|
||||
await Promise.resolve()
|
||||
})
|
||||
|
||||
const state = useAppStore.getState()
|
||||
expect(state.agentStatusByPaneKey[targetPaneKey]?.state).toBe('done')
|
||||
expect(state.retainedAgentsByPaneKey[sourcePaneKey]).toBeUndefined()
|
||||
expect(state.retainedAgentsByPaneKey[targetPaneKey]).toBeUndefined()
|
||||
expect(state.retentionSuppressedPaneKeys[sourcePaneKey]).toBeUndefined()
|
||||
hook.unmount()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -4,7 +4,9 @@ import { useAppStore } from '@/store'
|
||||
import { isExplicitAgentStatusFresh } from '@/lib/agent-status'
|
||||
import type { DashboardAgentRow } from './useDashboardData'
|
||||
import type { RetainedAgentEntry } from '@/store/slices/agent-status'
|
||||
import type { Repo, TerminalTab, Worktree } from '../../../../shared/types'
|
||||
import type { FolderWorkspace, Repo, TerminalTab, Worktree } from '../../../../shared/types'
|
||||
import { folderWorkspaceKey } from '../../../../shared/workspace-scope'
|
||||
import { resolveAgentPaneAuthorityKey } from '@/store/slices/agent-pane-authority'
|
||||
import {
|
||||
AGENT_STATUS_STALE_AFTER_MS,
|
||||
type AgentStatusEntry
|
||||
@@ -22,6 +24,7 @@ type RetainedAgentSnapshot = Map<string, { row: DashboardAgentRow; worktreeId: s
|
||||
type RetainedAgentsSyncInputs = {
|
||||
repos: Repo[]
|
||||
worktreesByRepo: Record<string, Worktree[]>
|
||||
folderWorkspaces: FolderWorkspace[]
|
||||
tabsByWorktree: Record<string, TerminalTab[]>
|
||||
agentStatusByPaneKey: Record<string, AgentStatusEntry>
|
||||
}
|
||||
@@ -37,6 +40,7 @@ function paneKeyTabId(paneKey: string): string | null {
|
||||
function buildLiveTabIndex(args: {
|
||||
repos: Repo[]
|
||||
worktreesByRepo: Record<string, Worktree[]>
|
||||
folderWorkspaces: FolderWorkspace[]
|
||||
tabsByWorktree: Record<string, TerminalTab[]>
|
||||
}): {
|
||||
existingWorktreeIds: Set<string>
|
||||
@@ -59,6 +63,17 @@ function buildLiveTabIndex(args: {
|
||||
}
|
||||
}
|
||||
|
||||
for (const folderWorkspace of args.folderWorkspaces) {
|
||||
if (folderWorkspace.isArchived) {
|
||||
continue
|
||||
}
|
||||
const workspaceKey = folderWorkspaceKey(folderWorkspace.id)
|
||||
existingWorktreeIds.add(workspaceKey)
|
||||
for (const tab of args.tabsByWorktree[workspaceKey] ?? []) {
|
||||
tabIndex.set(tab.id, { tab, worktreeId: workspaceKey })
|
||||
}
|
||||
}
|
||||
|
||||
return { existingWorktreeIds, tabIndex }
|
||||
}
|
||||
|
||||
@@ -69,6 +84,7 @@ function agentStartedAt(entry: AgentStatusEntry): number {
|
||||
export function buildRetainedAgentsSyncSnapshot(args: RetainedAgentsSyncSnapshotInputs): {
|
||||
currentAgents: RetainedAgentSnapshot
|
||||
existingWorktreeIds: Set<string>
|
||||
tabIndex: Map<string, { tab: TerminalTab; worktreeId: string }>
|
||||
} {
|
||||
const { existingWorktreeIds, tabIndex } = buildLiveTabIndex(args)
|
||||
const currentAgents: RetainedAgentSnapshot = new Map()
|
||||
@@ -99,23 +115,33 @@ export function buildRetainedAgentsSyncSnapshot(args: RetainedAgentsSyncSnapshot
|
||||
})
|
||||
}
|
||||
|
||||
return { currentAgents, existingWorktreeIds }
|
||||
return { currentAgents, existingWorktreeIds, tabIndex }
|
||||
}
|
||||
|
||||
export function useRetainedAgentsSync(): void {
|
||||
const retainAgents = useAppStore((s) => s.retainAgents)
|
||||
const pruneRetainedAgents = useAppStore((s) => s.pruneRetainedAgents)
|
||||
const clearRetentionSuppressedPaneKeys = useAppStore((s) => s.clearRetentionSuppressedPaneKeys)
|
||||
const [repos, worktreesByRepo, tabsByWorktree, agentStatusEpoch] = useAppStore(
|
||||
useShallow((s) => [s.repos, s.worktreesByRepo, s.tabsByWorktree, s.agentStatusEpoch] as const)
|
||||
const [repos, worktreesByRepo, folderWorkspaces, tabsByWorktree, agentStatusEpoch] = useAppStore(
|
||||
useShallow(
|
||||
(s) =>
|
||||
[
|
||||
s.repos,
|
||||
s.worktreesByRepo,
|
||||
s.folderWorkspaces,
|
||||
s.tabsByWorktree,
|
||||
s.agentStatusEpoch
|
||||
] as const
|
||||
)
|
||||
)
|
||||
const prevAgentsRef = useRef<RetainedAgentSnapshot>(new Map())
|
||||
|
||||
useEffect(() => {
|
||||
const state = useAppStore.getState()
|
||||
const { currentAgents, existingWorktreeIds } = buildRetainedAgentsSyncSnapshot({
|
||||
const { currentAgents, existingWorktreeIds, tabIndex } = buildRetainedAgentsSyncSnapshot({
|
||||
repos: state.repos,
|
||||
worktreesByRepo: state.worktreesByRepo,
|
||||
folderWorkspaces: state.folderWorkspaces,
|
||||
tabsByWorktree: state.tabsByWorktree,
|
||||
agentStatusByPaneKey: state.agentStatusByPaneKey,
|
||||
now: Date.now()
|
||||
@@ -132,7 +158,9 @@ export function useRetainedAgentsSync(): void {
|
||||
currentAgents,
|
||||
retainedAgentsByPaneKey: retainedNow,
|
||||
retentionSuppressedPaneKeys,
|
||||
recentlyClosedAgentStatusTabIds: state.recentlyClosedAgentStatusTabIds
|
||||
recentlyClosedAgentStatusTabIds: state.recentlyClosedAgentStatusTabIds,
|
||||
recentlyRetiredAgentStatusPaneKeys: state.recentlyRetiredAgentStatusPaneKeys,
|
||||
tabIndex
|
||||
})
|
||||
// Why: batch retention into a single store mutation. Looping retainAgent
|
||||
// would trigger N set(...) calls and N subscriber notifications when
|
||||
@@ -149,6 +177,7 @@ export function useRetainedAgentsSync(): void {
|
||||
}, [
|
||||
repos,
|
||||
worktreesByRepo,
|
||||
folderWorkspaces,
|
||||
tabsByWorktree,
|
||||
agentStatusEpoch,
|
||||
retainAgents,
|
||||
@@ -157,12 +186,40 @@ export function useRetainedAgentsSync(): void {
|
||||
])
|
||||
}
|
||||
|
||||
function sameAgentRun(
|
||||
previous: { row: DashboardAgentRow },
|
||||
current: { row: DashboardAgentRow }
|
||||
): boolean {
|
||||
// Why: resume identity arrives on its own IPC event, so one side can be stamped
|
||||
// while the other is not. Only a session present on BOTH sides is decisive.
|
||||
const previousSession = previous.row.entry.providerSession
|
||||
const currentSession = current.row.entry.providerSession
|
||||
if (previousSession && currentSession) {
|
||||
return previousSession.key === currentSession.key && previousSession.id === currentSession.id
|
||||
}
|
||||
// Why: terminalHandle identifies the TERMINAL, not the run — a later agent started
|
||||
// in the same pty inherits it, so it only corroborates a matching run identity.
|
||||
// It is absent for ordinary local PTY agents, so it cannot be required.
|
||||
const previousHandle = previous.row.entry.terminalHandle
|
||||
const currentHandle = current.row.entry.terminalHandle
|
||||
if (previousHandle && currentHandle && previousHandle !== currentHandle) {
|
||||
return false
|
||||
}
|
||||
return (
|
||||
previous.row.startedAt === current.row.startedAt &&
|
||||
previous.row.agentType === current.row.agentType
|
||||
)
|
||||
}
|
||||
|
||||
export function collectRetainedAgentsOnDisappear(args: {
|
||||
previousAgents: Map<string, { row: DashboardAgentRow; worktreeId: string }>
|
||||
currentAgents: Map<string, { row: DashboardAgentRow; worktreeId: string }>
|
||||
retainedAgentsByPaneKey: Record<string, RetainedAgentEntry>
|
||||
retentionSuppressedPaneKeys: Record<string, true>
|
||||
recentlyClosedAgentStatusTabIds: Record<string, true>
|
||||
recentlyRetiredAgentStatusPaneKeys: Record<string, true>
|
||||
/** Live tabs by id; supplies the real destination tab when a pane key transferred. */
|
||||
tabIndex?: Map<string, { tab: TerminalTab }>
|
||||
}): {
|
||||
toRetain: RetainedAgentEntry[]
|
||||
consumedSuppressedPaneKeys: string[]
|
||||
@@ -174,21 +231,51 @@ export function collectRetainedAgentsOnDisappear(args: {
|
||||
if (args.currentAgents.has(paneKey)) {
|
||||
continue
|
||||
}
|
||||
const transferredPaneKey = resolveAgentPaneAuthorityKey(paneKey)
|
||||
const migrated =
|
||||
transferredPaneKey === paneKey ? undefined : args.currentAgents.get(transferredPaneKey)
|
||||
if (migrated && sameAgentRun(prev, migrated)) {
|
||||
continue
|
||||
}
|
||||
// Why: a different run already occupies the transferred key, so this row keeps
|
||||
// its own key rather than colliding with the live one.
|
||||
const ownerPaneKey = migrated ? paneKey : transferredPaneKey
|
||||
if (
|
||||
args.recentlyRetiredAgentStatusPaneKeys[paneKey] ||
|
||||
args.recentlyRetiredAgentStatusPaneKeys[ownerPaneKey]
|
||||
) {
|
||||
continue
|
||||
}
|
||||
// Why: skip only when the retained snapshot is for the SAME (or newer) run.
|
||||
// A reused paneKey (same tab+pane, fresh agent start after a prior run was
|
||||
// retained) produces a newer startedAt — we must overwrite so stale
|
||||
// completion data doesn't linger forever for the reused pane.
|
||||
const alreadyRetained = args.retainedAgentsByPaneKey[paneKey]
|
||||
const alreadyRetained = args.retainedAgentsByPaneKey[ownerPaneKey]
|
||||
if (alreadyRetained && alreadyRetained.startedAt >= prev.row.startedAt) {
|
||||
continue
|
||||
}
|
||||
if (args.retentionSuppressedPaneKeys[paneKey]) {
|
||||
consumedSuppressedPaneKeys.push(paneKey)
|
||||
const suppressedPaneKey = args.retentionSuppressedPaneKeys[paneKey]
|
||||
? paneKey
|
||||
: args.retentionSuppressedPaneKeys[ownerPaneKey]
|
||||
? ownerPaneKey
|
||||
: null
|
||||
if (suppressedPaneKey) {
|
||||
consumedSuppressedPaneKeys.push(suppressedPaneKey)
|
||||
continue
|
||||
}
|
||||
// Why: the row must land on the surface that owns the pane now — a detach
|
||||
// followed by a PTY exit before the next sync would otherwise retain it
|
||||
// under the abandoned source tab.
|
||||
const ownerTabId = paneKeyTabId(ownerPaneKey) ?? prev.row.tab.id
|
||||
// Why: prefer the real destination tab — reusing the source tab's title and
|
||||
// launchAgent under a different id would mislabel the retained row.
|
||||
const ownerTab =
|
||||
ownerTabId === prev.row.tab.id
|
||||
? prev.row.tab
|
||||
: (args.tabIndex?.get(ownerTabId)?.tab ?? { ...prev.row.tab, id: ownerTabId })
|
||||
// Why: PTY exit can remove the live row before closeTab plants a suppressor;
|
||||
// the closed-tab marker prevents re-retention.
|
||||
if (args.recentlyClosedAgentStatusTabIds[prev.row.tab.id]) {
|
||||
if (args.recentlyClosedAgentStatusTabIds[ownerTabId]) {
|
||||
continue
|
||||
}
|
||||
// Why: only keep a sticky snapshot when the agent finished cleanly
|
||||
@@ -201,9 +288,12 @@ export function collectRetainedAgentsOnDisappear(args: {
|
||||
continue
|
||||
}
|
||||
toRetain.push({
|
||||
entry: prev.row.entry,
|
||||
entry:
|
||||
ownerPaneKey === paneKey
|
||||
? prev.row.entry
|
||||
: { ...prev.row.entry, paneKey: ownerPaneKey, tabId: ownerTabId },
|
||||
worktreeId: prev.worktreeId,
|
||||
tab: prev.row.tab,
|
||||
tab: ownerTab,
|
||||
agentType: prev.row.agentType,
|
||||
startedAt: prev.row.startedAt
|
||||
})
|
||||
|
||||
@@ -4,12 +4,37 @@ import {
|
||||
type AgentStatusEntry,
|
||||
type AgentStatusState
|
||||
} from '../../../../shared/agent-status-types'
|
||||
import type { Repo, TerminalTab, Worktree } from '../../../../shared/types'
|
||||
import type { FolderWorkspace, Repo, TerminalTab, Worktree } from '../../../../shared/types'
|
||||
import { folderWorkspaceKey } from '../../../../shared/workspace-scope'
|
||||
import { makePaneKey } from '../../../../shared/stable-pane-id'
|
||||
import { buildRetainedAgentsSyncSnapshot } from './useRetainedAgents'
|
||||
|
||||
const ACTIVE_PANE_KEY = makePaneKey('tab-active', '22222222-2222-4222-8222-222222222222')
|
||||
const ARCHIVED_PANE_KEY = makePaneKey('tab-archived', '33333333-3333-4333-8333-333333333333')
|
||||
const FOLDER_PANE_KEY = makePaneKey('tab-folder', '44444444-4444-4444-8444-444444444444')
|
||||
const ARCHIVED_FOLDER_PANE_KEY = makePaneKey(
|
||||
'tab-folder-archived',
|
||||
'55555555-5555-4555-8555-555555555555'
|
||||
)
|
||||
|
||||
function makeFolderWorkspace(overrides?: Partial<FolderWorkspace>): FolderWorkspace {
|
||||
return {
|
||||
id: 'folder-1',
|
||||
projectGroupId: 'group-1',
|
||||
name: 'Folder',
|
||||
folderPath: '/repo/folder',
|
||||
linkedTask: null,
|
||||
comment: '',
|
||||
isArchived: false,
|
||||
isUnread: false,
|
||||
isPinned: false,
|
||||
sortOrder: 0,
|
||||
lastActivityAt: 1,
|
||||
createdAt: 1,
|
||||
updatedAt: 1,
|
||||
...overrides
|
||||
}
|
||||
}
|
||||
|
||||
function makeRepo(): Repo {
|
||||
return {
|
||||
@@ -90,6 +115,7 @@ describe('buildRetainedAgentsSyncSnapshot', () => {
|
||||
const snapshot = buildRetainedAgentsSyncSnapshot({
|
||||
repos: [repo],
|
||||
worktreesByRepo: { [repo.id]: [activeWorktree, archivedWorktree] },
|
||||
folderWorkspaces: [],
|
||||
tabsByWorktree: {
|
||||
[activeWorktree.id]: [activeTab],
|
||||
[archivedWorktree.id]: [archivedTab]
|
||||
@@ -115,4 +141,37 @@ describe('buildRetainedAgentsSyncSnapshot', () => {
|
||||
expect(snapshot.currentAgents.get(ACTIVE_PANE_KEY)?.row.state).toBe('idle')
|
||||
expect(snapshot.currentAgents.get(ARCHIVED_PANE_KEY)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('builds live rows for non-archived folder workspaces and skips archived ones', () => {
|
||||
const folderWorkspace = makeFolderWorkspace()
|
||||
const archivedFolderWorkspace = makeFolderWorkspace({ id: 'folder-2', isArchived: true })
|
||||
const workspaceKey = folderWorkspaceKey(folderWorkspace.id)
|
||||
const archivedWorkspaceKey = folderWorkspaceKey(archivedFolderWorkspace.id)
|
||||
const tab = makeTab({ id: 'tab-folder', worktreeId: workspaceKey })
|
||||
const archivedTab = makeTab({ id: 'tab-folder-archived', worktreeId: archivedWorkspaceKey })
|
||||
|
||||
const snapshot = buildRetainedAgentsSyncSnapshot({
|
||||
repos: [],
|
||||
worktreesByRepo: {},
|
||||
folderWorkspaces: [folderWorkspace, archivedFolderWorkspace],
|
||||
tabsByWorktree: { [workspaceKey]: [tab], [archivedWorkspaceKey]: [archivedTab] },
|
||||
agentStatusByPaneKey: {
|
||||
[FOLDER_PANE_KEY]: makeEntry({
|
||||
paneKey: FOLDER_PANE_KEY,
|
||||
state: 'done',
|
||||
updatedAt: 10_000
|
||||
}),
|
||||
[ARCHIVED_FOLDER_PANE_KEY]: makeEntry({
|
||||
paneKey: ARCHIVED_FOLDER_PANE_KEY,
|
||||
state: 'done',
|
||||
updatedAt: 10_000
|
||||
})
|
||||
},
|
||||
now: 10_000
|
||||
})
|
||||
|
||||
expect([...snapshot.existingWorktreeIds]).toEqual([workspaceKey])
|
||||
expect(snapshot.currentAgents.get(FOLDER_PANE_KEY)?.worktreeId).toBe(workspaceKey)
|
||||
expect(snapshot.currentAgents.get(ARCHIVED_FOLDER_PANE_KEY)).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,8 +1,11 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { makePaneKey } from '../../../../shared/stable-pane-id'
|
||||
import {
|
||||
countAgentPaneAuthorityAliasesForTests,
|
||||
forgetAgentPaneAuthorityAliasesByTabIds,
|
||||
resetAgentPaneAuthorityAliasesForTests,
|
||||
resolveAgentPaneAuthorityKey
|
||||
resolveAgentPaneAuthorityKey,
|
||||
transferAgentPaneAuthorityAlias
|
||||
} from './agent-pane-authority'
|
||||
import { createTestStore } from './store-test-helpers'
|
||||
|
||||
@@ -97,6 +100,7 @@ describe('agent pane authority', () => {
|
||||
store.getState().dropAgentStatusByTabPrefix('tab-source')
|
||||
|
||||
expect(resolveAgentPaneAuthorityKey(SOURCE)).toBe(FINAL)
|
||||
expect(resolveAgentPaneAuthorityKey(TARGET)).toBe(FINAL)
|
||||
expect(store.getState().sleepingAgentSessionsByPaneKey[FINAL]).toMatchObject({
|
||||
paneKey: FINAL,
|
||||
tabId: 'tab-final',
|
||||
@@ -122,4 +126,47 @@ describe('agent pane authority', () => {
|
||||
expect(store.getState().agentStatusByPaneKey[FINAL]).toBeUndefined()
|
||||
expect(store.getState().recentlyRetiredAgentStatusPaneKeys[SOURCE]).toBe(true)
|
||||
})
|
||||
|
||||
it('forgets aliases for purged tabs and caps unbounded detach churn', () => {
|
||||
const leafId = '66666666-6666-4666-8666-666666666666'
|
||||
transferAgentPaneAuthorityAlias({
|
||||
fromPaneKey: makePaneKey('tab-purged', leafId),
|
||||
toPaneKey: makePaneKey('tab-kept', leafId),
|
||||
ptyId: 'pty-1'
|
||||
})
|
||||
expect(countAgentPaneAuthorityAliasesForTests()).toBe(1)
|
||||
|
||||
forgetAgentPaneAuthorityAliasesByTabIds(['tab-kept'])
|
||||
expect(countAgentPaneAuthorityAliasesForTests()).toBe(0)
|
||||
|
||||
// Why: pty exit and workspace purge do not retire, so the cap is the backstop.
|
||||
for (let index = 0; index < 600; index += 1) {
|
||||
transferAgentPaneAuthorityAlias({
|
||||
fromPaneKey: makePaneKey(`tab-from-${index}`, leafId),
|
||||
toPaneKey: makePaneKey(`tab-to-${index}`, leafId),
|
||||
ptyId: `pty-${index}`
|
||||
})
|
||||
}
|
||||
expect(countAgentPaneAuthorityAliasesForTests()).toBeLessThanOrEqual(512)
|
||||
expect(resolveAgentPaneAuthorityKey(makePaneKey('tab-from-599', leafId))).toBe(
|
||||
makePaneKey('tab-to-599', leafId)
|
||||
)
|
||||
})
|
||||
|
||||
it('clears the alias when a pane moves back to a key it previously left', () => {
|
||||
const store = createTestStore()
|
||||
store.getState().setAgentStatus(SOURCE, { state: 'working', prompt: 'source' })
|
||||
|
||||
store
|
||||
.getState()
|
||||
.transferAgentPaneAuthority({ fromPaneKey: SOURCE, toPaneKey: TARGET, ptyId: 'pty-1' })
|
||||
store
|
||||
.getState()
|
||||
.transferAgentPaneAuthority({ fromPaneKey: TARGET, toPaneKey: SOURCE, ptyId: 'pty-1' })
|
||||
|
||||
expect(resolveAgentPaneAuthorityKey(SOURCE)).toBe(SOURCE)
|
||||
expect(resolveAgentPaneAuthorityKey(TARGET)).toBe(SOURCE)
|
||||
store.getState().setAgentStatus(SOURCE, { state: 'done', prompt: 'back home' })
|
||||
expect(store.getState().agentStatusByPaneKey[SOURCE]?.prompt).toBe('back home')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -7,6 +7,21 @@ type AgentPaneAuthorityAlias = {
|
||||
|
||||
const aliasesByPhysicalPaneKey = new Map<string, AgentPaneAuthorityAlias>()
|
||||
|
||||
// Why: teardown paths that never retire (pty exit, workspace purge) would otherwise
|
||||
// leak an entry per detach for the renderer's lifetime; evict oldest-first.
|
||||
const MAX_AGENT_PANE_AUTHORITY_ALIASES = 512
|
||||
|
||||
function evictOldestAgentPaneAuthorityAliases(): void {
|
||||
// Why: mirrors the main-process alias bound (boundPaneKeyAliases) — insertion-order eviction.
|
||||
while (aliasesByPhysicalPaneKey.size > MAX_AGENT_PANE_AUTHORITY_ALIASES) {
|
||||
const oldestPaneKey = aliasesByPhysicalPaneKey.keys().next().value
|
||||
if (!oldestPaneKey) {
|
||||
break
|
||||
}
|
||||
aliasesByPhysicalPaneKey.delete(oldestPaneKey)
|
||||
}
|
||||
}
|
||||
|
||||
export type AgentPaneAuthorityTransfer = {
|
||||
physicalPaneKey: string
|
||||
previousOwnerPaneKey: string
|
||||
@@ -38,14 +53,28 @@ export function transferAgentPaneAuthorityAlias(args: {
|
||||
}
|
||||
}
|
||||
const ptyId = args.ptyId?.trim() || aliasesByPhysicalPaneKey.get(physicalPaneKey)?.ptyId || null
|
||||
if (physicalPaneKey !== args.toPaneKey) {
|
||||
// Why: the process keeps posting its original ORCA_PANE_KEY after detach;
|
||||
// one physical-to-owner alias keeps chained moves on the current surface.
|
||||
aliasesByPhysicalPaneKey.set(physicalPaneKey, {
|
||||
// Why: every key that resolved to the old owner must follow the move in one hop,
|
||||
// or a chained detach leaves an intermediate key routing to a dead pane.
|
||||
const formerOwnerPaneKeys = new Set([physicalPaneKey, previousOwnerPaneKey])
|
||||
for (const [candidatePhysicalPaneKey, alias] of aliasesByPhysicalPaneKey) {
|
||||
if (alias.ownerPaneKey === previousOwnerPaneKey) {
|
||||
formerOwnerPaneKeys.add(candidatePhysicalPaneKey)
|
||||
}
|
||||
}
|
||||
for (const formerOwnerPaneKey of formerOwnerPaneKeys) {
|
||||
if (formerOwnerPaneKey === args.toPaneKey) {
|
||||
// Why: the pane came back to this key, so it owns itself again.
|
||||
aliasesByPhysicalPaneKey.delete(formerOwnerPaneKey)
|
||||
continue
|
||||
}
|
||||
// Why: re-insert so an alias refreshed by a later move is not the eviction victim.
|
||||
aliasesByPhysicalPaneKey.delete(formerOwnerPaneKey)
|
||||
aliasesByPhysicalPaneKey.set(formerOwnerPaneKey, {
|
||||
ownerPaneKey: args.toPaneKey,
|
||||
ptyId
|
||||
})
|
||||
}
|
||||
evictOldestAgentPaneAuthorityAliases()
|
||||
return {
|
||||
physicalPaneKey,
|
||||
previousOwnerPaneKey,
|
||||
@@ -81,6 +110,28 @@ export function retireAgentPaneAuthorityAliasesByOwnerTab(tabId: string): string
|
||||
return [...retiredPaneKeys]
|
||||
}
|
||||
|
||||
/** Drop aliases whose physical or owner pane belongs to a purged tab. */
|
||||
export function forgetAgentPaneAuthorityAliasesByTabIds(tabIds: Iterable<string>): void {
|
||||
const doomedTabIds = tabIds instanceof Set ? tabIds : new Set(tabIds)
|
||||
if (doomedTabIds.size === 0) {
|
||||
return
|
||||
}
|
||||
for (const [physicalPaneKey, alias] of aliasesByPhysicalPaneKey) {
|
||||
const physicalTabId = parsePaneKey(physicalPaneKey)?.tabId
|
||||
const ownerTabId = parsePaneKey(alias.ownerPaneKey)?.tabId
|
||||
if (
|
||||
(physicalTabId && doomedTabIds.has(physicalTabId)) ||
|
||||
(ownerTabId && doomedTabIds.has(ownerTabId))
|
||||
) {
|
||||
aliasesByPhysicalPaneKey.delete(physicalPaneKey)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function countAgentPaneAuthorityAliasesForTests(): number {
|
||||
return aliasesByPhysicalPaneKey.size
|
||||
}
|
||||
|
||||
export function resetAgentPaneAuthorityAliasesForTests(): void {
|
||||
aliasesByPhysicalPaneKey.clear()
|
||||
}
|
||||
|
||||
@@ -46,6 +46,13 @@ const mockApi = {
|
||||
globalThis.window = { api: mockApi }
|
||||
|
||||
import { createTestStore, seedStore, makeWorktree, makeTab } from './store-test-helpers'
|
||||
import { makePaneKey } from '../../../../shared/stable-pane-id'
|
||||
import {
|
||||
countAgentPaneAuthorityAliasesForTests,
|
||||
resetAgentPaneAuthorityAliasesForTests,
|
||||
resolveAgentPaneAuthorityKey,
|
||||
transferAgentPaneAuthorityAlias
|
||||
} from './agent-pane-authority'
|
||||
|
||||
const WT = 'repo1::/path/wt1'
|
||||
const TAB = 'tab-1'
|
||||
@@ -138,4 +145,27 @@ describe('bulk worktree purge evicts pane-scoped agent/unread/input maps (leak r
|
||||
expect(s.unreadTerminalTabs[OTHER_TAB]).toBe(true)
|
||||
expect(s.lastTerminalInputAtByPaneKey[OTHER_PANE]).toBe(2)
|
||||
})
|
||||
|
||||
it('purgeWorktreeTerminalState forgets pane-authority aliases for the removed tabs', () => {
|
||||
resetAgentPaneAuthorityAliasesForTests()
|
||||
const store = createTestStore()
|
||||
const leafId = '77777777-7777-4777-8777-777777777777'
|
||||
const sourcePaneKey = makePaneKey('tab-detached', leafId)
|
||||
const ownerPaneKey = makePaneKey(TAB, leafId)
|
||||
seedPaneState(store)
|
||||
transferAgentPaneAuthorityAlias({
|
||||
fromPaneKey: sourcePaneKey,
|
||||
toPaneKey: ownerPaneKey,
|
||||
ptyId: 'pty-1'
|
||||
})
|
||||
expect(resolveAgentPaneAuthorityKey(sourcePaneKey)).toBe(ownerPaneKey)
|
||||
|
||||
store.getState().purgeWorktreeTerminalState([WT])
|
||||
|
||||
// Why: the alias registry outlives the store maps, so a purged tab must not
|
||||
// keep routing status posts to a pane that no longer exists.
|
||||
expect(resolveAgentPaneAuthorityKey(sourcePaneKey)).toBe(sourcePaneKey)
|
||||
expect(countAgentPaneAuthorityAliasesForTests()).toBe(0)
|
||||
resetAgentPaneAuthorityAliasesForTests()
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1303,69 +1303,55 @@ export const createAgentStatusSlice: StateCreator<AppState, [], [], AgentStatusS
|
||||
const to = transfer.ownerPaneKey
|
||||
const targetTabId = getTabIdFromPaneKey(to) ?? undefined
|
||||
const targetLeafId = getLeafIdFromPaneKey(to) ?? undefined
|
||||
set((s) => {
|
||||
// Plant a one-shot suppressor on the source key so useRetainedAgentsSync —
|
||||
// which only sees `from` vanish, not the migration — can't resurrect a ghost row.
|
||||
const movedSuppressors = movePaneKeyedRecord(s.retentionSuppressedPaneKeys, from, to)
|
||||
// Guard on fromWasLive: a suppressor is consumed only on a live→gone transition, else it leaks.
|
||||
const fromWasLive = from in s.agentStatusByPaneKey
|
||||
const retentionSuppressedPaneKeys: Record<string, true> =
|
||||
fromWasLive && !(from in movedSuppressors)
|
||||
? { ...movedSuppressors, [from]: true }
|
||||
: movedSuppressors
|
||||
return {
|
||||
agentStatusByPaneKey: movePaneKeyedRecord(s.agentStatusByPaneKey, from, to, (entry) => ({
|
||||
set((s) => ({
|
||||
agentStatusByPaneKey: movePaneKeyedRecord(s.agentStatusByPaneKey, from, to, (entry) => ({
|
||||
...entry,
|
||||
paneKey: to,
|
||||
tabId: targetTabId
|
||||
})),
|
||||
// Why: retention/sidebar consumers gate on the epoch; a moved live row is a
|
||||
// pane-key change they must observe, not a silent remap.
|
||||
...(from in s.agentStatusByPaneKey
|
||||
? { agentStatusEpoch: s.agentStatusEpoch + 1, sortEpoch: s.sortEpoch + 1 }
|
||||
: {}),
|
||||
runtimeAgentOrchestrationByPaneKey: movePaneKeyedRecord(
|
||||
s.runtimeAgentOrchestrationByPaneKey,
|
||||
from,
|
||||
to
|
||||
),
|
||||
retainedAgentsByPaneKey: movePaneKeyedRecord(
|
||||
s.retainedAgentsByPaneKey,
|
||||
from,
|
||||
to,
|
||||
(retained) => ({
|
||||
...retained,
|
||||
entry: { ...retained.entry, paneKey: to, tabId: targetTabId },
|
||||
tab: targetTabId ? { ...retained.tab, id: targetTabId } : retained.tab
|
||||
})
|
||||
),
|
||||
sleepingAgentSessionsByPaneKey: movePaneKeyedRecord(
|
||||
s.sleepingAgentSessionsByPaneKey,
|
||||
from,
|
||||
to,
|
||||
(record) => ({ ...record, paneKey: to, tabId: targetTabId })
|
||||
),
|
||||
agentLaunchConfigByPaneKey: movePaneKeyedRecord(
|
||||
s.agentLaunchConfigByPaneKey,
|
||||
from,
|
||||
to,
|
||||
(entry) => ({
|
||||
...entry,
|
||||
paneKey: to,
|
||||
tabId: targetTabId
|
||||
})),
|
||||
runtimeAgentOrchestrationByPaneKey: movePaneKeyedRecord(
|
||||
s.runtimeAgentOrchestrationByPaneKey,
|
||||
from,
|
||||
to
|
||||
),
|
||||
retainedAgentsByPaneKey: movePaneKeyedRecord(
|
||||
s.retainedAgentsByPaneKey,
|
||||
from,
|
||||
to,
|
||||
(retained) => ({
|
||||
...retained,
|
||||
entry: { ...retained.entry, paneKey: to, tabId: targetTabId },
|
||||
tab: targetTabId ? { ...retained.tab, id: targetTabId } : retained.tab
|
||||
})
|
||||
),
|
||||
sleepingAgentSessionsByPaneKey: movePaneKeyedRecord(
|
||||
s.sleepingAgentSessionsByPaneKey,
|
||||
from,
|
||||
to,
|
||||
(record) => ({ ...record, paneKey: to, tabId: targetTabId })
|
||||
),
|
||||
agentLaunchConfigByPaneKey: movePaneKeyedRecord(
|
||||
s.agentLaunchConfigByPaneKey,
|
||||
from,
|
||||
to,
|
||||
(entry) => ({
|
||||
...entry,
|
||||
identity: { ...entry.identity, tabId: targetTabId, leafId: targetLeafId }
|
||||
})
|
||||
),
|
||||
acknowledgedAgentsByPaneKey: movePaneKeyedRecord(s.acknowledgedAgentsByPaneKey, from, to),
|
||||
paneForegroundAgentByPaneKey: movePaneKeyedRecord(
|
||||
s.paneForegroundAgentByPaneKey,
|
||||
from,
|
||||
to
|
||||
),
|
||||
unreadTerminalPanes: movePaneKeyedRecord(s.unreadTerminalPanes, from, to),
|
||||
unreadAgentCompletionPanes: movePaneKeyedRecord(s.unreadAgentCompletionPanes, from, to),
|
||||
lastTerminalInputAtByPaneKey: movePaneKeyedRecord(
|
||||
s.lastTerminalInputAtByPaneKey,
|
||||
from,
|
||||
to
|
||||
),
|
||||
cacheTimerByKey: movePaneKeyedRecord(s.cacheTimerByKey, from, to),
|
||||
retentionSuppressedPaneKeys
|
||||
}
|
||||
})
|
||||
identity: { ...entry.identity, tabId: targetTabId, leafId: targetLeafId }
|
||||
})
|
||||
),
|
||||
acknowledgedAgentsByPaneKey: movePaneKeyedRecord(s.acknowledgedAgentsByPaneKey, from, to),
|
||||
paneForegroundAgentByPaneKey: movePaneKeyedRecord(s.paneForegroundAgentByPaneKey, from, to),
|
||||
unreadTerminalPanes: movePaneKeyedRecord(s.unreadTerminalPanes, from, to),
|
||||
unreadAgentCompletionPanes: movePaneKeyedRecord(s.unreadAgentCompletionPanes, from, to),
|
||||
lastTerminalInputAtByPaneKey: movePaneKeyedRecord(s.lastTerminalInputAtByPaneKey, from, to),
|
||||
cacheTimerByKey: movePaneKeyedRecord(s.cacheTimerByKey, from, to),
|
||||
retentionSuppressedPaneKeys: movePaneKeyedRecord(s.retentionSuppressedPaneKeys, from, to)
|
||||
}))
|
||||
if (typeof window !== 'undefined') {
|
||||
window.api?.agentStatus?.transferPaneAuthority?.({
|
||||
fromPaneKey: from,
|
||||
|
||||
@@ -65,6 +65,8 @@ describe('syncPaneDetachPtyOwnership agent identity', () => {
|
||||
}
|
||||
})
|
||||
|
||||
const epochBeforeDetach = store.getState().agentStatusEpoch
|
||||
|
||||
store.getState().syncPaneDetachPtyOwnership({
|
||||
detachedLeafId,
|
||||
detachedPtyId: 'pty-droid',
|
||||
@@ -103,9 +105,10 @@ describe('syncPaneDetachPtyOwnership agent identity', () => {
|
||||
tabId: targetTabId,
|
||||
providerSession: { key: 'session_id', id: 'session-1' }
|
||||
})
|
||||
// Why: detach plants a one-shot suppressor on the source key so the sidebar
|
||||
// retention hook can't resurrect the migrated pane as an unclickable ghost row.
|
||||
expect(state.retentionSuppressedPaneKeys[sourcePaneKey]).toBe(true)
|
||||
expect(state.retentionSuppressedPaneKeys[sourcePaneKey]).toBeUndefined()
|
||||
expect(state.retentionSuppressedPaneKeys[targetPaneKey]).toBeUndefined()
|
||||
// Why: the retention effect only reruns on an epoch bump; a moved live row must trigger it.
|
||||
expect(state.agentStatusEpoch).toBeGreaterThan(epochBeforeDetach)
|
||||
expect(state.paneForegroundAgentByPaneKey[siblingPaneKey]).toEqual({
|
||||
agent: 'antigravity',
|
||||
shellForeground: false
|
||||
|
||||
@@ -1,48 +1,86 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { makePaneKey } from '../../../../shared/stable-pane-id'
|
||||
import { collectRetainedAgentsOnDisappear } from '@/components/dashboard/useRetainedAgents'
|
||||
import {
|
||||
resetAgentPaneAuthorityAliasesForTests,
|
||||
resolveAgentPaneAuthorityKey
|
||||
} from './agent-pane-authority'
|
||||
import { createTestStore, makeTab, makeWorktree, seedStore } from './store-test-helpers'
|
||||
import type { AgentStatusEntry } from '../../../../shared/agent-status-types'
|
||||
import type { TerminalTab } from '../../../../shared/types'
|
||||
import type { DashboardAgentRow } from '@/components/dashboard/useDashboardData'
|
||||
|
||||
// Detaching a completed split pane migrates the paneKey `sourceTab:leaf → targetTab:leaf`;
|
||||
// these tests pin the store→hook contract that stops the sidebar resurrecting a ghost row.
|
||||
|
||||
const WORKTREE_ID = 'repo::/repo/worktree'
|
||||
const SOURCE_TAB = 'tab-source'
|
||||
const TARGET_TAB = 'tab-target'
|
||||
const FINAL_TAB = 'tab-final'
|
||||
const LEAF = '11111111-1111-4111-8111-111111111111'
|
||||
const SIBLING_LEAF = '22222222-2222-4222-8222-222222222222'
|
||||
const SOURCE_PANE_KEY = makePaneKey(SOURCE_TAB, LEAF)
|
||||
const TARGET_PANE_KEY = makePaneKey(TARGET_TAB, LEAF)
|
||||
const FINAL_PANE_KEY = makePaneKey(FINAL_TAB, LEAF)
|
||||
|
||||
function makeDoneEntry(paneKey: string, tabId: string): AgentStatusEntry {
|
||||
beforeEach(() => {
|
||||
resetAgentPaneAuthorityAliasesForTests()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
resetAgentPaneAuthorityAliasesForTests()
|
||||
})
|
||||
|
||||
function makeDoneEntry(args: {
|
||||
paneKey: string
|
||||
tabId: string
|
||||
startedAt: number
|
||||
agentType: AgentStatusEntry['agentType']
|
||||
terminalHandle?: string
|
||||
providerSession?: AgentStatusEntry['providerSession']
|
||||
}): AgentStatusEntry {
|
||||
return {
|
||||
state: 'done',
|
||||
prompt: 'Fix it',
|
||||
updatedAt: 100,
|
||||
stateStartedAt: 100,
|
||||
paneKey,
|
||||
tabId,
|
||||
updatedAt: args.startedAt,
|
||||
stateStartedAt: args.startedAt,
|
||||
paneKey: args.paneKey,
|
||||
tabId: args.tabId,
|
||||
terminalTitle: 'Claude',
|
||||
stateHistory: [],
|
||||
agentType: 'claude',
|
||||
agentType: args.agentType,
|
||||
terminalHandle: args.terminalHandle,
|
||||
providerSession: args.providerSession,
|
||||
interrupted: false
|
||||
}
|
||||
}
|
||||
|
||||
function makeRow(paneKey: string, tabId: string): DashboardAgentRow {
|
||||
function makeRow(
|
||||
paneKey: string,
|
||||
tabId: string,
|
||||
startedAt = 100,
|
||||
overrides?: {
|
||||
agentType?: AgentStatusEntry['agentType']
|
||||
terminalHandle?: string
|
||||
providerSession?: AgentStatusEntry['providerSession']
|
||||
}
|
||||
): DashboardAgentRow {
|
||||
const agentType = overrides?.agentType ?? 'claude'
|
||||
return {
|
||||
paneKey,
|
||||
entry: makeDoneEntry(paneKey, tabId),
|
||||
entry: makeDoneEntry({
|
||||
paneKey,
|
||||
tabId,
|
||||
startedAt,
|
||||
agentType,
|
||||
terminalHandle: overrides?.terminalHandle,
|
||||
providerSession: overrides?.providerSession
|
||||
}),
|
||||
tab: makeTab({ id: tabId, worktreeId: WORKTREE_ID }),
|
||||
agentType: 'claude',
|
||||
agentType,
|
||||
state: 'done',
|
||||
startedAt: 100
|
||||
startedAt
|
||||
}
|
||||
}
|
||||
|
||||
function detachDoneAgentAndReadStore() {
|
||||
function createDetachStore() {
|
||||
const store = createTestStore()
|
||||
seedStore(store, {
|
||||
worktreesByRepo: {
|
||||
@@ -51,16 +89,24 @@ function detachDoneAgentAndReadStore() {
|
||||
tabsByWorktree: {
|
||||
[WORKTREE_ID]: [
|
||||
makeTab({ id: SOURCE_TAB, worktreeId: WORKTREE_ID, ptyId: 'pty-a' }),
|
||||
makeTab({ id: TARGET_TAB, worktreeId: WORKTREE_ID, ptyId: null })
|
||||
makeTab({ id: TARGET_TAB, worktreeId: WORKTREE_ID, ptyId: null }),
|
||||
makeTab({ id: FINAL_TAB, worktreeId: WORKTREE_ID, ptyId: null })
|
||||
]
|
||||
},
|
||||
ptyIdsByTabId: { [SOURCE_TAB]: ['pty-a', 'pty-sibling'], [TARGET_TAB]: [] }
|
||||
})
|
||||
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
|
||||
state: 'done',
|
||||
prompt: 'Fix it',
|
||||
agentType: 'claude'
|
||||
ptyIdsByTabId: {
|
||||
[SOURCE_TAB]: ['pty-a', 'pty-sibling'],
|
||||
[TARGET_TAB]: [],
|
||||
[FINAL_TAB]: []
|
||||
}
|
||||
})
|
||||
return store
|
||||
}
|
||||
|
||||
function detach(
|
||||
store: ReturnType<typeof createDetachStore>,
|
||||
sourceTabId: string,
|
||||
targetTabId: string
|
||||
) {
|
||||
store.getState().syncPaneDetachPtyOwnership({
|
||||
detachedLeafId: LEAF,
|
||||
detachedPtyId: 'pty-a',
|
||||
@@ -70,70 +116,317 @@ function detachDoneAgentAndReadStore() {
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { [SIBLING_LEAF]: 'pty-sibling' }
|
||||
},
|
||||
sourceTabId: SOURCE_TAB,
|
||||
targetTabId: TARGET_TAB
|
||||
sourceTabId,
|
||||
targetTabId
|
||||
})
|
||||
}
|
||||
|
||||
function collect(args: {
|
||||
currentPaneKey?: string
|
||||
currentTabId?: string
|
||||
currentStartedAt?: number
|
||||
currentAgentType?: AgentStatusEntry['agentType']
|
||||
terminalHandle?: string
|
||||
previousProviderSession?: AgentStatusEntry['providerSession']
|
||||
currentProviderSession?: AgentStatusEntry['providerSession']
|
||||
retiredPaneKeys?: Record<string, true>
|
||||
tabIndex?: Map<string, { tab: TerminalTab }>
|
||||
}) {
|
||||
return collectRetainedAgentsOnDisappear({
|
||||
previousAgents: new Map([
|
||||
[
|
||||
SOURCE_PANE_KEY,
|
||||
{
|
||||
row: makeRow(SOURCE_PANE_KEY, SOURCE_TAB, 100, {
|
||||
terminalHandle: args.terminalHandle,
|
||||
providerSession: args.previousProviderSession
|
||||
}),
|
||||
worktreeId: WORKTREE_ID
|
||||
}
|
||||
]
|
||||
]),
|
||||
currentAgents:
|
||||
args.currentPaneKey && args.currentTabId
|
||||
? new Map([
|
||||
[
|
||||
args.currentPaneKey,
|
||||
{
|
||||
row: makeRow(args.currentPaneKey, args.currentTabId, args.currentStartedAt, {
|
||||
agentType: args.currentAgentType,
|
||||
terminalHandle: args.terminalHandle,
|
||||
providerSession: args.currentProviderSession
|
||||
}),
|
||||
worktreeId: WORKTREE_ID
|
||||
}
|
||||
]
|
||||
])
|
||||
: new Map(),
|
||||
retainedAgentsByPaneKey: {},
|
||||
retentionSuppressedPaneKeys: {},
|
||||
recentlyClosedAgentStatusTabIds: {},
|
||||
recentlyRetiredAgentStatusPaneKeys: args.retiredPaneKeys ?? {},
|
||||
tabIndex: args.tabIndex
|
||||
})
|
||||
return store.getState()
|
||||
}
|
||||
|
||||
describe('detach completed split pane → sidebar retention', () => {
|
||||
it('plants a source-key suppressor so the retention hook drops the migrated pane', () => {
|
||||
const state = detachDoneAgentAndReadStore()
|
||||
it('recognizes the same run at its transferred authority without a suppressor', () => {
|
||||
const store = createDetachStore()
|
||||
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
|
||||
state: 'done',
|
||||
prompt: 'Fix it',
|
||||
agentType: 'claude'
|
||||
})
|
||||
|
||||
detach(store, SOURCE_TAB, TARGET_TAB)
|
||||
const state = store.getState()
|
||||
const result = collect({ currentPaneKey: TARGET_PANE_KEY, currentTabId: TARGET_TAB })
|
||||
|
||||
// Status migrated to the new tab's pane key.
|
||||
expect(state.agentStatusByPaneKey[SOURCE_PANE_KEY]).toBeUndefined()
|
||||
expect(state.agentStatusByPaneKey[TARGET_PANE_KEY]?.state).toBe('done')
|
||||
|
||||
// The retention hook sees the old key vanish (prevRef held source, current
|
||||
// holds target). Feed it the REAL post-detach suppressor state.
|
||||
const result = collectRetainedAgentsOnDisappear({
|
||||
previousAgents: new Map([
|
||||
[SOURCE_PANE_KEY, { row: makeRow(SOURCE_PANE_KEY, SOURCE_TAB), worktreeId: WORKTREE_ID }]
|
||||
]),
|
||||
currentAgents: new Map([
|
||||
[TARGET_PANE_KEY, { row: makeRow(TARGET_PANE_KEY, TARGET_TAB), worktreeId: WORKTREE_ID }]
|
||||
]),
|
||||
retainedAgentsByPaneKey: {},
|
||||
retentionSuppressedPaneKeys: state.retentionSuppressedPaneKeys,
|
||||
recentlyClosedAgentStatusTabIds: {}
|
||||
})
|
||||
|
||||
// No ghost row; the one-shot suppressor is consumed instead of retained.
|
||||
expect(state.retentionSuppressedPaneKeys[SOURCE_PANE_KEY]).toBeUndefined()
|
||||
expect(result.toRetain).toEqual([])
|
||||
expect(result.consumedSuppressedPaneKeys).toEqual([SOURCE_PANE_KEY])
|
||||
expect(result.consumedSuppressedPaneKeys).toEqual([])
|
||||
})
|
||||
|
||||
it('does not plant a suppressor when the detached pane never had a live agent', () => {
|
||||
const store = createTestStore()
|
||||
seedStore(store, {
|
||||
worktreesByRepo: {
|
||||
repo: [makeWorktree({ id: WORKTREE_ID, repoId: 'repo', path: '/repo/worktree' })]
|
||||
},
|
||||
it('recognizes the same run after chained transfers', () => {
|
||||
const store = createDetachStore()
|
||||
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
|
||||
state: 'done',
|
||||
prompt: 'Fix it',
|
||||
agentType: 'claude'
|
||||
})
|
||||
|
||||
detach(store, SOURCE_TAB, TARGET_TAB)
|
||||
detach(store, TARGET_TAB, FINAL_TAB)
|
||||
|
||||
expect(collect({ currentPaneKey: FINAL_PANE_KEY, currentTabId: FINAL_TAB }).toRetain).toEqual(
|
||||
[]
|
||||
)
|
||||
// Why: every intermediate key must resolve to the CURRENT owner, not the previous hop.
|
||||
expect(resolveAgentPaneAuthorityKey(SOURCE_PANE_KEY)).toBe(FINAL_PANE_KEY)
|
||||
expect(resolveAgentPaneAuthorityKey(TARGET_PANE_KEY)).toBe(FINAL_PANE_KEY)
|
||||
})
|
||||
|
||||
it('keeps every intermediate key routed after a fourth move', () => {
|
||||
const store = createDetachStore()
|
||||
const EXTRA_TAB = 'tab-extra'
|
||||
const extraPaneKey = makePaneKey(EXTRA_TAB, LEAF)
|
||||
store.setState({
|
||||
tabsByWorktree: {
|
||||
[WORKTREE_ID]: [
|
||||
makeTab({ id: SOURCE_TAB, worktreeId: WORKTREE_ID, ptyId: 'pty-a' }),
|
||||
makeTab({ id: TARGET_TAB, worktreeId: WORKTREE_ID, ptyId: null })
|
||||
...(store.getState().tabsByWorktree[WORKTREE_ID] ?? []),
|
||||
makeTab({ id: EXTRA_TAB, worktreeId: WORKTREE_ID, ptyId: null })
|
||||
]
|
||||
},
|
||||
ptyIdsByTabId: { [SOURCE_TAB]: ['pty-a', 'pty-sibling'], [TARGET_TAB]: [] }
|
||||
}
|
||||
})
|
||||
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
|
||||
state: 'done',
|
||||
prompt: 'Fix it',
|
||||
agentType: 'claude'
|
||||
})
|
||||
|
||||
// No setAgentStatus here: a plain terminal pane with no agent.
|
||||
store.getState().syncPaneDetachPtyOwnership({
|
||||
detachedLeafId: LEAF,
|
||||
detachedPtyId: 'pty-a',
|
||||
sourceLayout: {
|
||||
root: { type: 'leaf', leafId: SIBLING_LEAF },
|
||||
activeLeafId: SIBLING_LEAF,
|
||||
expandedLeafId: null,
|
||||
ptyIdsByLeafId: { [SIBLING_LEAF]: 'pty-sibling' }
|
||||
},
|
||||
sourceTabId: SOURCE_TAB,
|
||||
targetTabId: TARGET_TAB
|
||||
detach(store, SOURCE_TAB, TARGET_TAB)
|
||||
detach(store, TARGET_TAB, FINAL_TAB)
|
||||
detach(store, FINAL_TAB, EXTRA_TAB)
|
||||
|
||||
for (const formerKey of [SOURCE_PANE_KEY, TARGET_PANE_KEY, FINAL_PANE_KEY]) {
|
||||
expect(resolveAgentPaneAuthorityKey(formerKey)).toBe(extraPaneKey)
|
||||
}
|
||||
store.getState().setAgentStatus(TARGET_PANE_KEY, { state: 'done', prompt: 'late post' })
|
||||
expect(store.getState().agentStatusByPaneKey[extraPaneKey]?.prompt).toBe('late post')
|
||||
})
|
||||
|
||||
it('still retains the source when a different run occupies the transferred key', () => {
|
||||
const store = createDetachStore()
|
||||
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
|
||||
state: 'done',
|
||||
prompt: 'Fix it',
|
||||
agentType: 'claude'
|
||||
})
|
||||
|
||||
// Why: a suppressor is only consumed on a live→gone transition. The source
|
||||
// key was never live, so planting one here would leak it forever.
|
||||
detach(store, SOURCE_TAB, TARGET_TAB)
|
||||
const result = collect({
|
||||
currentPaneKey: TARGET_PANE_KEY,
|
||||
currentTabId: TARGET_TAB,
|
||||
currentStartedAt: 900
|
||||
})
|
||||
|
||||
expect(result.toRetain).toHaveLength(1)
|
||||
expect(result.toRetain[0]?.entry.paneKey).toBe(SOURCE_PANE_KEY)
|
||||
})
|
||||
|
||||
it('still retains when a new agent reuses the pty and inherits its terminal handle', () => {
|
||||
const store = createDetachStore()
|
||||
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
|
||||
state: 'done',
|
||||
prompt: 'Fix it',
|
||||
agentType: 'claude'
|
||||
})
|
||||
|
||||
detach(store, SOURCE_TAB, TARGET_TAB)
|
||||
// Why: terminalHandle is pty-scoped, so a fresh codex run carries the same handle.
|
||||
const result = collect({
|
||||
currentPaneKey: TARGET_PANE_KEY,
|
||||
currentTabId: TARGET_TAB,
|
||||
currentStartedAt: 900,
|
||||
currentAgentType: 'codex',
|
||||
terminalHandle: 'term_shared'
|
||||
})
|
||||
|
||||
expect(result.toRetain).toHaveLength(1)
|
||||
expect(result.toRetain[0]?.entry.paneKey).toBe(SOURCE_PANE_KEY)
|
||||
})
|
||||
|
||||
it('treats differing terminal handles as different runs', () => {
|
||||
const store = createDetachStore()
|
||||
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
|
||||
state: 'done',
|
||||
prompt: 'Fix it',
|
||||
agentType: 'claude'
|
||||
})
|
||||
|
||||
detach(store, SOURCE_TAB, TARGET_TAB)
|
||||
// Why: identical startedAt/agentType can collide, so a differing handle is the
|
||||
// only signal that these are separate terminals.
|
||||
const result = collectRetainedAgentsOnDisappear({
|
||||
previousAgents: new Map([
|
||||
[
|
||||
SOURCE_PANE_KEY,
|
||||
{
|
||||
row: makeRow(SOURCE_PANE_KEY, SOURCE_TAB, 100, { terminalHandle: 'term_source' }),
|
||||
worktreeId: WORKTREE_ID
|
||||
}
|
||||
]
|
||||
]),
|
||||
currentAgents: new Map([
|
||||
[
|
||||
TARGET_PANE_KEY,
|
||||
{
|
||||
row: makeRow(TARGET_PANE_KEY, TARGET_TAB, 100, { terminalHandle: 'term_other' }),
|
||||
worktreeId: WORKTREE_ID
|
||||
}
|
||||
]
|
||||
]),
|
||||
retainedAgentsByPaneKey: {},
|
||||
retentionSuppressedPaneKeys: {},
|
||||
recentlyClosedAgentStatusTabIds: {},
|
||||
recentlyRetiredAgentStatusPaneKeys: {}
|
||||
})
|
||||
|
||||
expect(result.toRetain).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('recognizes the same run when resume identity lands only after the move', () => {
|
||||
const store = createDetachStore()
|
||||
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
|
||||
state: 'done',
|
||||
prompt: 'Fix it',
|
||||
agentType: 'claude'
|
||||
})
|
||||
|
||||
detach(store, SOURCE_TAB, TARGET_TAB)
|
||||
// Why: recordAgentProviderSession is its own IPC event, so the destination can be
|
||||
// stamped while the pre-move snapshot is not. A one-sided session is not evidence
|
||||
// of a different run.
|
||||
const result = collect({
|
||||
currentPaneKey: TARGET_PANE_KEY,
|
||||
currentTabId: TARGET_TAB,
|
||||
currentProviderSession: { key: 'session_id', id: 'session-1' }
|
||||
})
|
||||
|
||||
expect(result.toRetain).toEqual([])
|
||||
})
|
||||
|
||||
it('treats mismatched resume identities as different runs', () => {
|
||||
const store = createDetachStore()
|
||||
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
|
||||
state: 'done',
|
||||
prompt: 'Fix it',
|
||||
agentType: 'claude'
|
||||
})
|
||||
|
||||
detach(store, SOURCE_TAB, TARGET_TAB)
|
||||
const result = collect({
|
||||
currentPaneKey: TARGET_PANE_KEY,
|
||||
currentTabId: TARGET_TAB,
|
||||
previousProviderSession: { key: 'session_id', id: 'session-1' },
|
||||
currentProviderSession: { key: 'session_id', id: 'session-2' }
|
||||
})
|
||||
|
||||
expect(result.toRetain).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('recognizes a handle-less local pty run at its transferred authority', () => {
|
||||
const store = createDetachStore()
|
||||
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
|
||||
state: 'done',
|
||||
prompt: 'Fix it',
|
||||
agentType: 'claude'
|
||||
})
|
||||
|
||||
detach(store, SOURCE_TAB, TARGET_TAB)
|
||||
// Why: ordinary local PTY statuses route with connectionId only, so terminalHandle
|
||||
// is undefined on both sides — requiring a handle here would resurrect the ghost.
|
||||
const result = collect({ currentPaneKey: TARGET_PANE_KEY, currentTabId: TARGET_TAB })
|
||||
|
||||
expect(result.toRetain[0]?.entry.terminalHandle).toBeUndefined()
|
||||
expect(result.toRetain).toEqual([])
|
||||
})
|
||||
|
||||
it('does not resurrect the source when the transferred owner immediately closes', () => {
|
||||
const store = createDetachStore()
|
||||
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
|
||||
state: 'done',
|
||||
prompt: 'Fix it',
|
||||
agentType: 'claude'
|
||||
})
|
||||
|
||||
detach(store, SOURCE_TAB, TARGET_TAB)
|
||||
store.getState().dropAgentStatusByTabPrefix(TARGET_TAB)
|
||||
const retiredPaneKeys = store.getState().recentlyRetiredAgentStatusPaneKeys
|
||||
|
||||
expect(retiredPaneKeys[SOURCE_PANE_KEY]).toBe(true)
|
||||
expect(retiredPaneKeys[TARGET_PANE_KEY]).toBe(true)
|
||||
expect(collect({ retiredPaneKeys }).toRetain).toEqual([])
|
||||
})
|
||||
|
||||
it('retains at the transferred surface when the destination pty exits before the next sync', () => {
|
||||
const store = createDetachStore()
|
||||
store.getState().setAgentStatus(SOURCE_PANE_KEY, {
|
||||
state: 'done',
|
||||
prompt: 'Fix it',
|
||||
agentType: 'claude'
|
||||
})
|
||||
|
||||
detach(store, SOURCE_TAB, TARGET_TAB)
|
||||
store.getState().removeAgentStatus(TARGET_PANE_KEY)
|
||||
|
||||
// Why: the retention effect coalesced the move and the exit into one pass, so it
|
||||
// only ever sees the source key vanish.
|
||||
const destinationTab = makeTab({
|
||||
id: TARGET_TAB,
|
||||
worktreeId: WORKTREE_ID,
|
||||
title: 'Destination',
|
||||
launchAgent: 'codex'
|
||||
})
|
||||
const retained = collect({
|
||||
tabIndex: new Map([[TARGET_TAB, { tab: destinationTab }]])
|
||||
}).toRetain
|
||||
expect(retained).toHaveLength(1)
|
||||
expect(retained[0]?.entry.paneKey).toBe(TARGET_PANE_KEY)
|
||||
expect(retained[0]?.entry.tabId).toBe(TARGET_TAB)
|
||||
// Why: the row must carry the DESTINATION tab's identity, not the source tab's
|
||||
// title/launchAgent relabeled with a new id — sidebar agent-type resolution reads both.
|
||||
expect(retained[0]?.tab).toBe(destinationTab)
|
||||
expect(retained[0]?.tab.title).toBe('Destination')
|
||||
})
|
||||
|
||||
it('does not create suppressors for a plain terminal detach', () => {
|
||||
const store = createDetachStore()
|
||||
|
||||
detach(store, SOURCE_TAB, TARGET_TAB)
|
||||
|
||||
expect(store.getState().retentionSuppressedPaneKeys[SOURCE_PANE_KEY]).toBeUndefined()
|
||||
expect(store.getState().retentionSuppressedPaneKeys[TARGET_PANE_KEY]).toBeUndefined()
|
||||
})
|
||||
|
||||
@@ -56,6 +56,7 @@ import { requestVirtualizedScrollAnchorRecord } from '@/hooks/requestVirtualized
|
||||
import { forgetAgentHibernationTabOutput } from '@/lib/agent-hibernation-output-activity'
|
||||
import { forgetForegroundTerminalTabs } from '@/lib/foreground-terminal-tabs'
|
||||
import { forgetAgentStartupDeliveriesForTabs } from '@/lib/agent-startup-delivery-guards'
|
||||
import { forgetAgentPaneAuthorityAliasesByTabIds } from './agent-pane-authority'
|
||||
import { branchName } from '@/lib/git-utils'
|
||||
import { markInputQuietSchedulerInput, scheduleAfterInputQuiet } from '@/lib/input-quiet-scheduler'
|
||||
import { clearSessionCommitDraftForWorktree } from '@/lib/source-control-commit-draft-session'
|
||||
@@ -2293,6 +2294,9 @@ function buildWorktreePurgeState(s: AppState, worktreeIds: string[]): Partial<Ap
|
||||
// Why: same rationale for doomed tabs' foreground last-seen timestamps and agent-startup delivery guards — retired tab ids never recur.
|
||||
forgetForegroundTerminalTabs(doomedTabIds)
|
||||
forgetAgentStartupDeliveriesForTabs(doomedTabIds)
|
||||
// Why: pane-authority aliases outlive the store maps they route to, so a purged
|
||||
// tab would leave a permanent entry pointing at a pane that no longer exists.
|
||||
forgetAgentPaneAuthorityAliasesByTabIds(doomedTabIds)
|
||||
// Why: per-page browser maps are keyed by page id, so collect every page of a doomed workspace to evict here (the authoritative-scan reconcile skips closeBrowserTab's cleanup).
|
||||
for (const workspaceId of doomedBrowserWorkspaceIds) {
|
||||
for (const page of s.browserPagesByWorkspace[workspaceId] ?? []) {
|
||||
|
||||
Reference in New Issue
Block a user