perf(renderer): purge three orphaned tab/worktree module maps on removal (#7562)
Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
@@ -1,6 +1,13 @@
|
||||
import { useAppStore } from '@/store'
|
||||
import type { AgentStartupPlan } from '@/lib/tui-agent-startup'
|
||||
import { parsePaneKey } from '../../../shared/stable-pane-id'
|
||||
import {
|
||||
agentStartupDeliveryKey as deliveryKey,
|
||||
clearConsumedAgentStartupDeliveriesForTests,
|
||||
isAgentStartupDeliveryConsumed,
|
||||
markAgentStartupDeliveryConsumed,
|
||||
releaseAgentStartupDeliveryConsumed
|
||||
} from './agent-startup-delivery-guards'
|
||||
|
||||
type AppStoreSnapshot = ReturnType<typeof useAppStore.getState>
|
||||
|
||||
@@ -13,7 +20,6 @@ type PendingAgentStartupDelivery = {
|
||||
}
|
||||
|
||||
const pendingAgentStartupDeliveries = new Map<string, PendingAgentStartupDelivery>()
|
||||
const consumedAgentStartupDeliveries = new Set<string>()
|
||||
const staleStartupRecheckTimers = new Map<string, ReturnType<typeof globalThis.setTimeout>>()
|
||||
let unsubscribePendingAgentStartupDeliveries: (() => void) | null = null
|
||||
|
||||
@@ -99,7 +105,7 @@ function stopPendingAgentStartupSubscriptionIfIdle(): void {
|
||||
|
||||
export function queuePendingAgentStartupDelivery(delivery: PendingAgentStartupDelivery): void {
|
||||
const key = deliveryKey(delivery)
|
||||
if (consumedAgentStartupDeliveries.has(key)) {
|
||||
if (isAgentStartupDeliveryConsumed(key)) {
|
||||
return
|
||||
}
|
||||
pendingAgentStartupDeliveries.set(key, delivery)
|
||||
@@ -109,7 +115,7 @@ export function queuePendingAgentStartupDelivery(delivery: PendingAgentStartupDe
|
||||
|
||||
export function resetAgentStartupDelayedDeliveryForTests(): void {
|
||||
pendingAgentStartupDeliveries.clear()
|
||||
consumedAgentStartupDeliveries.clear()
|
||||
clearConsumedAgentStartupDeliveriesForTests()
|
||||
for (const timer of staleStartupRecheckTimers.values()) {
|
||||
globalThis.clearTimeout(timer)
|
||||
}
|
||||
@@ -124,10 +130,10 @@ export function beginAgentStartupDeliveryAttempt(args: {
|
||||
launchToken: string
|
||||
}): boolean {
|
||||
const key = deliveryKey(args)
|
||||
if (consumedAgentStartupDeliveries.has(key)) {
|
||||
if (isAgentStartupDeliveryConsumed(key)) {
|
||||
return false
|
||||
}
|
||||
consumedAgentStartupDeliveries.add(key)
|
||||
markAgentStartupDeliveryConsumed(key)
|
||||
pendingAgentStartupDeliveries.delete(key)
|
||||
clearStaleStartupRecheck(key)
|
||||
return true
|
||||
@@ -138,13 +144,7 @@ export function releaseAgentStartupDeliveryAttempt(args: {
|
||||
tabId: string
|
||||
launchToken: string
|
||||
}): void {
|
||||
consumedAgentStartupDeliveries.delete(deliveryKey(args))
|
||||
}
|
||||
|
||||
function deliveryKey(
|
||||
delivery: Pick<PendingAgentStartupDelivery, 'worktreeId' | 'tabId' | 'launchToken'>
|
||||
): string {
|
||||
return `${delivery.worktreeId}\0${delivery.tabId}\0${delivery.launchToken}`
|
||||
releaseAgentStartupDeliveryConsumed(deliveryKey(args))
|
||||
}
|
||||
|
||||
function flushPendingAgentStartupDeliveries(): void {
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
// Leaf module (imports nothing from the store) holding the consumed
|
||||
// agent-startup-delivery guard set, so store slices can purge it on tab/worktree
|
||||
// removal without creating a store → agent-startup-delayed-delivery → store
|
||||
// import cycle.
|
||||
|
||||
export function agentStartupDeliveryKey(delivery: {
|
||||
worktreeId: string
|
||||
tabId: string
|
||||
launchToken: string
|
||||
}): string {
|
||||
return `${delivery.worktreeId}\0${delivery.tabId}\0${delivery.launchToken}`
|
||||
}
|
||||
|
||||
const consumedAgentStartupDeliveries = new Set<string>()
|
||||
|
||||
export function isAgentStartupDeliveryConsumed(key: string): boolean {
|
||||
return consumedAgentStartupDeliveries.has(key)
|
||||
}
|
||||
|
||||
export function markAgentStartupDeliveryConsumed(key: string): void {
|
||||
consumedAgentStartupDeliveries.add(key)
|
||||
}
|
||||
|
||||
export function releaseAgentStartupDeliveryConsumed(key: string): void {
|
||||
consumedAgentStartupDeliveries.delete(key)
|
||||
}
|
||||
|
||||
export function clearConsumedAgentStartupDeliveriesForTests(): void {
|
||||
consumedAgentStartupDeliveries.clear()
|
||||
}
|
||||
|
||||
// Why: one consumed guard is recorded per launch that reached delivery and is
|
||||
// never released on the happy path, so guards for removed tabs/worktrees would
|
||||
// accumulate for the renderer's whole session. Drop them when the owning tab is
|
||||
// closed or its worktree is removed.
|
||||
export function forgetAgentStartupDeliveriesForTabs(tabIds: Iterable<string>): void {
|
||||
const tabIdSet = tabIds instanceof Set ? tabIds : new Set(tabIds)
|
||||
if (tabIdSet.size === 0) {
|
||||
return
|
||||
}
|
||||
for (const key of consumedAgentStartupDeliveries) {
|
||||
// agentStartupDeliveryKey() is `${worktreeId}\0${tabId}\0${launchToken}`.
|
||||
const tabId = key.split('\0')[1] ?? ''
|
||||
if (tabIdSet.has(tabId)) {
|
||||
consumedAgentStartupDeliveries.delete(key)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,15 @@ export function getForegroundTerminalTabLastSeenAtById(): Record<string, number>
|
||||
return Object.fromEntries(foregroundTerminalTabLastSeenAtById)
|
||||
}
|
||||
|
||||
// Why: retired terminal tab ids never recur, so their last-seen timestamps would
|
||||
// accumulate for the renderer's whole session. Drop them when a tab is closed or
|
||||
// its worktree is removed (mirrors forgetAgentHibernationTabOutput).
|
||||
export function forgetForegroundTerminalTabs(tabIds: Iterable<string>): void {
|
||||
for (const tabId of tabIds) {
|
||||
foregroundTerminalTabLastSeenAtById.delete(tabId)
|
||||
}
|
||||
}
|
||||
|
||||
export function resetForegroundTerminalTabIdsForTests(): void {
|
||||
explicitForegroundTerminalTabIds = new Set()
|
||||
visibleTerminalTabClaimsByToken.clear()
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* Memory-leak regression: three module-level maps keyed by tab/worktree id grew
|
||||
* monotonically over a session because no removal path evicted their entries.
|
||||
*
|
||||
* - `detachedHeadAutoDerivedDisplayNames` (worktrees.ts) — worktree-keyed; only
|
||||
* self-evicted when a branch reappeared, so a worktree removed while detached
|
||||
* leaked its entry.
|
||||
* - `foregroundTerminalTabLastSeenAtById` (lib/foreground-terminal-tabs) —
|
||||
* tab-keyed; gained an entry per foregrounded tab, never dropped on close.
|
||||
* - `consumedAgentStartupDeliveries` (lib/agent-startup-delivery-guards) —
|
||||
* (worktreeId,tabId,launchToken)-keyed; one permanent guard per delivery,
|
||||
* only released on the retry path, so removed tabs/worktrees leaked it.
|
||||
*
|
||||
* worktreeId and tabId are unbounded, ephemeral key spaces (fresh ids, never reused).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import type * as AgentStatusModule from '@/lib/agent-status'
|
||||
import {
|
||||
getForegroundTerminalTabLastSeenAtById,
|
||||
resetForegroundTerminalTabIdsForTests,
|
||||
setForegroundTerminalTabIds
|
||||
} from '@/lib/foreground-terminal-tabs'
|
||||
import {
|
||||
beginAgentStartupDeliveryAttempt,
|
||||
resetAgentStartupDelayedDeliveryForTests
|
||||
} from '@/lib/agent-startup-delayed-delivery'
|
||||
|
||||
vi.mock('sonner', () => ({
|
||||
toast: { info: vi.fn(), success: vi.fn(), error: vi.fn(), warning: vi.fn() }
|
||||
}))
|
||||
|
||||
vi.mock('@/components/terminal-pane/pty-dispatcher', () => ({
|
||||
restorePtyDataHandlersAfterFailedShutdown: vi.fn(),
|
||||
unregisterPtyDataHandlers: vi.fn()
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/agent-status', async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof AgentStatusModule>()
|
||||
return { ...actual, detectAgentStatusFromTitle: vi.fn().mockReturnValue(null) }
|
||||
})
|
||||
|
||||
const mockApi = {
|
||||
worktrees: {
|
||||
list: vi.fn().mockResolvedValue([]),
|
||||
remove: vi.fn().mockResolvedValue(undefined),
|
||||
forceDeletePreservedBranch: vi.fn().mockResolvedValue({ deleted: true }),
|
||||
updateMeta: vi.fn().mockResolvedValue({})
|
||||
},
|
||||
pty: { kill: vi.fn().mockResolvedValue(undefined) },
|
||||
runtimeEnvironments: { call: vi.fn().mockResolvedValue({ ok: true, result: {} }) }
|
||||
}
|
||||
|
||||
// @ts-expect-error -- minimal window.api stub for the store under test
|
||||
globalThis.window = { api: mockApi }
|
||||
|
||||
import { createTestStore, seedStore, makeWorktree, makeTab } from './store-test-helpers'
|
||||
import {
|
||||
getDetachedHeadAutoDerivedDisplayNameForTests,
|
||||
setDetachedHeadAutoDerivedDisplayNameForTests
|
||||
} from './worktrees'
|
||||
|
||||
const WT1 = 'repo1::/path/wt1'
|
||||
const WT2 = 'repo1::/path/wt2'
|
||||
const TAB1 = 'tab-wt1'
|
||||
const TAB2 = 'tab-wt2'
|
||||
const TOKEN1 = 'launch-1'
|
||||
const TOKEN2 = 'launch-2'
|
||||
|
||||
function seedMaps(store: ReturnType<typeof createTestStore>): void {
|
||||
seedStore(store, {
|
||||
worktreesByRepo: {
|
||||
repo1: [
|
||||
makeWorktree({ id: WT1, repoId: 'repo1', path: '/path/wt1' }),
|
||||
makeWorktree({ id: WT2, repoId: 'repo1', path: '/path/wt2' })
|
||||
]
|
||||
},
|
||||
tabsByWorktree: {
|
||||
[WT1]: [makeTab({ id: TAB1, worktreeId: WT1 })],
|
||||
[WT2]: [makeTab({ id: TAB2, worktreeId: WT2 })]
|
||||
}
|
||||
})
|
||||
setDetachedHeadAutoDerivedDisplayNameForTests(WT1, 'wt1 (a1b2c3d)')
|
||||
setDetachedHeadAutoDerivedDisplayNameForTests(WT2, 'wt2 (e4f5g6h)')
|
||||
// Records a last-seen timestamp for both tabs.
|
||||
setForegroundTerminalTabIds([TAB1, TAB2])
|
||||
// Consumes a startup delivery guard for each tab.
|
||||
expect(
|
||||
beginAgentStartupDeliveryAttempt({ worktreeId: WT1, tabId: TAB1, launchToken: TOKEN1 })
|
||||
).toBe(true)
|
||||
expect(
|
||||
beginAgentStartupDeliveryAttempt({ worktreeId: WT2, tabId: TAB2, launchToken: TOKEN2 })
|
||||
).toBe(true)
|
||||
}
|
||||
|
||||
// A second begin returns false while the guard is still present, true once it is
|
||||
// cleared — so this observes the consumed-set without reaching into internals.
|
||||
function startupGuardCleared(worktreeId: string, tabId: string, launchToken: string): boolean {
|
||||
return beginAgentStartupDeliveryAttempt({ worktreeId, tabId, launchToken })
|
||||
}
|
||||
|
||||
describe('tab/worktree removal evicts the module maps it previously leaked', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockApi.worktrees.remove.mockResolvedValue(undefined)
|
||||
resetForegroundTerminalTabIdsForTests()
|
||||
resetAgentStartupDelayedDeliveryForTests()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
resetForegroundTerminalTabIdsForTests()
|
||||
resetAgentStartupDelayedDeliveryForTests()
|
||||
})
|
||||
|
||||
it('bulk purgeWorktreeTerminalState drops the removed worktree/tab entries only', () => {
|
||||
const store = createTestStore()
|
||||
seedMaps(store)
|
||||
|
||||
store.getState().purgeWorktreeTerminalState([WT1])
|
||||
|
||||
// Removed worktree/tab: all three maps evicted.
|
||||
expect(getDetachedHeadAutoDerivedDisplayNameForTests(WT1)).toBeUndefined()
|
||||
expect(getForegroundTerminalTabLastSeenAtById()[TAB1]).toBeUndefined()
|
||||
expect(startupGuardCleared(WT1, TAB1, TOKEN1)).toBe(true)
|
||||
// Surviving worktree/tab: retained (guard over-eviction).
|
||||
expect(getDetachedHeadAutoDerivedDisplayNameForTests(WT2)).toBe('wt2 (e4f5g6h)')
|
||||
expect(getForegroundTerminalTabLastSeenAtById()[TAB2]).toBeGreaterThan(0)
|
||||
expect(startupGuardCleared(WT2, TAB2, TOKEN2)).toBe(false)
|
||||
})
|
||||
|
||||
it('single removeWorktree drops the removed worktree/tab entries only', async () => {
|
||||
const store = createTestStore()
|
||||
seedMaps(store)
|
||||
|
||||
const result = await store.getState().removeWorktree(WT1)
|
||||
expect(result).toEqual({ ok: true })
|
||||
|
||||
expect(getDetachedHeadAutoDerivedDisplayNameForTests(WT1)).toBeUndefined()
|
||||
expect(getForegroundTerminalTabLastSeenAtById()[TAB1]).toBeUndefined()
|
||||
expect(startupGuardCleared(WT1, TAB1, TOKEN1)).toBe(true)
|
||||
expect(getDetachedHeadAutoDerivedDisplayNameForTests(WT2)).toBe('wt2 (e4f5g6h)')
|
||||
expect(getForegroundTerminalTabLastSeenAtById()[TAB2]).toBeGreaterThan(0)
|
||||
expect(startupGuardCleared(WT2, TAB2, TOKEN2)).toBe(false)
|
||||
})
|
||||
|
||||
it('closeTab drops the closed tab foreground + startup entries only', () => {
|
||||
const store = createTestStore()
|
||||
seedMaps(store)
|
||||
|
||||
store.getState().closeTab(TAB1)
|
||||
|
||||
// closeTab is tab-scoped: the tab-keyed maps drop, the worktree-keyed one stays.
|
||||
expect(getForegroundTerminalTabLastSeenAtById()[TAB1]).toBeUndefined()
|
||||
expect(startupGuardCleared(WT1, TAB1, TOKEN1)).toBe(true)
|
||||
expect(getForegroundTerminalTabLastSeenAtById()[TAB2]).toBeGreaterThan(0)
|
||||
expect(startupGuardCleared(WT2, TAB2, TOKEN2)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -39,6 +39,8 @@ import { WINDOWS_GIT_BASH_SHELL } from '../../../../shared/windows-terminal-shel
|
||||
import type { AgentStartedTelemetry } from '../../lib/worktree-activation'
|
||||
import { scheduleRuntimeGraphSync } from '@/runtime/sync-runtime-graph'
|
||||
import { forgetAgentHibernationTabOutput } from '@/lib/agent-hibernation-output-activity'
|
||||
import { forgetForegroundTerminalTabs } from '@/lib/foreground-terminal-tabs'
|
||||
import { forgetAgentStartupDeliveriesForTabs } from '@/lib/agent-startup-delivery-guards'
|
||||
import { clearTransientTerminalState, emptyLayoutSnapshot } from './terminal-helpers'
|
||||
import { isClaudeAgent } from '@/lib/agent-status'
|
||||
import { classifyTitleActivity } from '@/lib/pane-agent-evidence'
|
||||
@@ -1338,6 +1340,10 @@ export const createTerminalSlice: StateCreator<AppState, [], [], TerminalSlice>
|
||||
// a fresh leafId at epoch 0), so drop the panes' hibernation output epochs to
|
||||
// keep that module-level map from growing for the renderer's whole lifetime.
|
||||
forgetAgentHibernationTabOutput(tabId)
|
||||
// Why: same rationale for the tab's foreground last-seen timestamp and any
|
||||
// consumed agent-startup delivery guards — retired tab ids never recur.
|
||||
forgetForegroundTerminalTabs([tabId])
|
||||
forgetAgentStartupDeliveriesForTabs([tabId])
|
||||
for (const tabs of Object.values(get().unifiedTabsByWorktree)) {
|
||||
const workspaceItem = tabs.find(
|
||||
(entry) => entry.contentType === 'terminal' && entry.entityId === tabId
|
||||
|
||||
@@ -42,6 +42,8 @@ import { moveFocusToRendererBeforeFocusedWebviewHidden } from './browser-webview
|
||||
import { toast } from 'sonner'
|
||||
import { requestVirtualizedScrollAnchorRecord } from '@/hooks/requestVirtualizedScrollAnchorRecord'
|
||||
import { forgetAgentHibernationTabOutput } from '@/lib/agent-hibernation-output-activity'
|
||||
import { forgetForegroundTerminalTabs } from '@/lib/foreground-terminal-tabs'
|
||||
import { forgetAgentStartupDeliveriesForTabs } from '@/lib/agent-startup-delivery-guards'
|
||||
import { branchName } from '@/lib/git-utils'
|
||||
import { markInputQuietSchedulerInput, scheduleAfterInputQuiet } from '@/lib/input-quiet-scheduler'
|
||||
import { clearSessionCommitDraftForWorktree } from '@/lib/source-control-commit-draft-session'
|
||||
@@ -1451,6 +1453,19 @@ export function resetHostedReviewLinkMutationGenerationForTests(): void {
|
||||
hostedReviewLinkWorktreeIdAliases.clear()
|
||||
}
|
||||
|
||||
export function setDetachedHeadAutoDerivedDisplayNameForTests(
|
||||
worktreeId: string,
|
||||
displayName: string
|
||||
): void {
|
||||
detachedHeadAutoDerivedDisplayNames.set(worktreeId, displayName)
|
||||
}
|
||||
|
||||
export function getDetachedHeadAutoDerivedDisplayNameForTests(
|
||||
worktreeId: string
|
||||
): string | undefined {
|
||||
return detachedHeadAutoDerivedDisplayNames.get(worktreeId)
|
||||
}
|
||||
|
||||
function hostedReviewLinksAreCleared(worktree: Worktree): boolean {
|
||||
return HOSTED_REVIEW_LINK_KEYS.every((key) => worktree[key] == null) && !worktree.pushTarget
|
||||
}
|
||||
@@ -1828,7 +1843,14 @@ function buildWorktreePurgeState(s: AppState, worktreeIds: string[]): Partial<Ap
|
||||
for (const workspace of s.browserTabsByWorktree[id] ?? []) {
|
||||
doomedBrowserWorkspaceIds.add(workspace.id)
|
||||
}
|
||||
// Why: drop this worktree's auto-derived detached-HEAD display name so the
|
||||
// module-level map doesn't retain removed worktrees for the whole session.
|
||||
detachedHeadAutoDerivedDisplayNames.delete(id)
|
||||
}
|
||||
// Why: same rationale for the doomed tabs' foreground last-seen timestamps and
|
||||
// consumed agent-startup delivery guards — retired tab ids never recur.
|
||||
forgetForegroundTerminalTabs(doomedTabIds)
|
||||
forgetAgentStartupDeliveriesForTabs(doomedTabIds)
|
||||
// Why: the per-page browser maps are keyed by page id, not worktree/workspace id.
|
||||
// Collect every page owned by a doomed workspace so this bulk purge can evict
|
||||
// them. (The single removeWorktree path clears these via closeBrowserTab, but the
|
||||
@@ -3102,6 +3124,13 @@ export const createWorktreeSlice: StateCreator<AppState, [], [], WorktreeSlice>
|
||||
const tabs = get().tabsByWorktree[worktreeId] ?? []
|
||||
const tabIds = new Set(tabs.map((t) => t.id))
|
||||
|
||||
// Why: this path deletes tabsByWorktree wholesale (not via closeTab), so
|
||||
// purge the module-level maps keyed by this worktree/its tabs here too —
|
||||
// matching buildWorktreePurgeState so retired ids don't accumulate.
|
||||
detachedHeadAutoDerivedDisplayNames.delete(worktreeId)
|
||||
forgetForegroundTerminalTabs(tabIds)
|
||||
forgetAgentStartupDeliveriesForTabs(tabIds)
|
||||
|
||||
// Why: deletion is async (backend + terminal/browser teardown awaited
|
||||
// above), so snapshot the sidebar's current top-row anchor in the same
|
||||
// tick we remove the row. Recording at click time goes stale across the
|
||||
|
||||
Reference in New Issue
Block a user