Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
92 changes: 91 additions & 1 deletion src/renderer/src/components/Terminal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,24 @@
import BrowserPane from './browser-pane/BrowserPane'
import { RetainedBrowserPaneOverlayLayer } from './browser-pane/BrowserPaneOverlayLayer'
import EmulatorPaneOverlayLayer from './emulator-pane/EmulatorPaneOverlayLayer'
import { useBrowserAutomationVisibilityForAny } from './browser-pane/browser-automation-visibility'

Check warning on line 50 in src/renderer/src/components/Terminal.tsx

View workflow job for this annotation

GitHub Actions / static analysis

import(no-duplicates)

Modules should not be imported multiple times in the same file
import { useBrowserMobileDriverForAny } from '@/lib/pane-manager/browser-mobile-driver-state'

Check warning on line 51 in src/renderer/src/components/Terminal.tsx

View workflow job for this annotation

GitHub Actions / static analysis

import(no-duplicates)

Modules should not be imported multiple times in the same file
import TerminalPaneOverlayLayer from './terminal-pane/TerminalPaneOverlayLayer'
import {
collectBrowserWebviewIds,
destroyRemovedBrowserWebview,
destroyWorkspaceWebviews
destroyWorkspaceWebviews,
destroyWorktreeBrowserGuests
} from '../store/slices/browser-webview-cleanup'
import {
browserTabVisibilityPageIds,
selectBrowserGuestEvictionWorktreeIds,
touchBrowserGuestWorktreeRecency,
worktreeHoldsLiveBrowserGuests
} from './browser-pane/browser-guest-worktree-retention'
import { hasLiveBrowserGuest } from './browser-pane/webview-registry'
import { isBrowserAutomationVisible } from './browser-pane/browser-automation-visibility'
import { isBrowserPageMobileDriven } from '@/lib/pane-manager/browser-mobile-driver-state'
import {
handleSwitchRecentTab,
handleSwitchTab,
Expand Down Expand Up @@ -273,6 +283,8 @@

function Terminal(): React.JSX.Element | null {
const mountedWorktreeIdsRef = useRef(new Set<string>())
// Why an array: browser-guest eviction needs activation order (LRU), not just membership.
const browserGuestWorktreeRecencyRef = useRef<string[]>([])
const measurableBackgroundWorktreeIdsRef = useRef(new Set<string>())
const terminalWorktreeHiddenSinceRef = useRef(new Map<string, number>())
// Why two extra clocks: hiddenSince survives a background-measure window (so
Expand Down Expand Up @@ -793,6 +805,8 @@
>(() => new Set())
// Why a ref: eviction captures buffers exactly once per force-park episode, before the unmount render.
const forceParkedCaptureDoneRef = useRef(new Set<string>())
// Why state: browser-guest eviction mutates mountedWorktreeIdsRef in an effect; the bump re-renders so evicted surfaces unmount.
const [, setBrowserGuestEvictionRevision] = useState(0)
// Tab restriction for targeted background mounts (wake/resume); a worktree absent from this map mounts all its tabs.
const backgroundMountTabIdsByWorktreeRef = useRef(new Map<string, ReadonlySet<string>>())
// Why: only cold-activation deferral (not targeted mounts, which share the map above) creates watcher coverage for every unmounted tab.
Expand Down Expand Up @@ -1142,6 +1156,82 @@
terminalSshParkingEnabled,
workspaceSurfaces
])
// Browser-guest retention budget (#12137 follow-up): hidden worktrees keep
// webview guests alive for instant revisits, but only the most recently
// activated few. Older ones are FULLY destroyed through the sanctioned
// cleanup path and their surfaces unmounted — destroyed-then-recreated is
// safe; detached-but-alive is the STA-3228 blank-forever state.
useEffect(() => {
if (!renderedActiveWorktreeId) {
return
}
const recency = browserGuestWorktreeRecencyRef.current
touchBrowserGuestWorktreeRecency(recency, renderedActiveWorktreeId)
const surfaceIds = new Set(workspaceSurfaces.map((workspace) => workspace.id))
for (let index = recency.length - 1; index >= 0; index--) {
if (!surfaceIds.has(recency[index])) {
recency.splice(index, 1)
}
}
const state = useAppStore.getState()
const portalWorktreeIds = new Set(activityTerminalPortals.map((portal) => portal.worktreeId))
// Why appended: a mounted worktree missing from recency (background mount) ranks oldest.
const recencyIds = new Set(recency)
const orderedWorktreeIds = [
...recency,
...workspaceSurfaces.map((workspace) => workspace.id).filter((id) => !recencyIds.has(id))
]
const evictedWorktreeIds = selectBrowserGuestEvictionWorktreeIds({
orderedWorktreeIds,
activeWorktreeId: renderedActiveWorktreeId,
isRetained: (worktreeId) => mountedWorktreeIdsRef.current.has(worktreeId),
holdsLiveGuests: (worktreeId) =>
worktreeHoldsLiveBrowserGuests(
state.browserTabsByWorktree[worktreeId] ?? [],
state.browserPagesByWorkspace,
hasLiveBrowserGuest
),
// Why each guard: automation/mobile keeps a hidden guest painted for a
// remote controller; measure windows and targeted background mounts need
// the surface; Activity portals render panes from it; exempt ptys and
// pending spawns would be orphaned or dropped by a surface unmount.
isEvictable: (worktreeId) => {
const guestPinned = (state.browserTabsByWorktree[worktreeId] ?? []).some((tab) =>
browserTabVisibilityPageIds(tab).some(
(pageId) => isBrowserAutomationVisible(pageId) || isBrowserPageMobileDriven(pageId)
)
)
if (
guestPinned ||
measurableBackgroundWorktreeIdsRef.current.has(worktreeId) ||
backgroundMountTabIdsByWorktreeRef.current.has(worktreeId) ||
portalWorktreeIds.has(worktreeId)
) {
return false
}
const terminalTabs = state.tabsByWorktree[worktreeId] ?? []
return (
!terminalTabs.some((tab) =>
hasPendingRetentionSpawnWork(tab, state.pendingStartupByTabId)
) && selectEvictionExemptTerminalTabIds(worktreeId, terminalTabs).size === 0
)
}
})
if (evictedWorktreeIds.length === 0) {
return
}
for (const worktreeId of evictedWorktreeIds) {
destroyWorktreeBrowserGuests(
state.browserTabsByWorktree,
state.browserPagesByWorkspace,
worktreeId
)
mountedWorktreeIdsRef.current.delete(worktreeId)
backgroundMountTabIdsByWorktreeRef.current.delete(worktreeId)
activationDeferredMountTabIdsByWorktreeRef.current.delete(worktreeId)
}
Comment thread
greptile-apps[bot] marked this conversation as resolved.
Resolved
setBrowserGuestEvictionRevision((revision) => revision + 1)
}, [renderedActiveWorktreeId, workspaceSurfaces, activityTerminalPortals])
// Why: a slow post-reconnect step exposes workspaceSessionReady before hydration can populate snapshot capabilities.
if (
renderedActiveWorktreeId &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,31 @@ describe('BrowserPaneOverlayLayer', () => {
expect(view.container.querySelectorAll('[data-browser-overlay-tab-id]')).toHaveLength(2)
})

it('discards the retained latch when eviction unmounts the worktree surface', () => {
const view = render(
<RetainedBrowserPaneOverlayLayer worktreeId="wt-1" isWorktreeActive mountEligible />
)
expect(view.container.querySelectorAll('[data-browser-overlay-tab-id]')).toHaveLength(2)

// Guest-budget eviction removes the worktree from mountedWorktreeIdsRef, unmounting the layer.
view.unmount()

// A revisit mounts a fresh layer: the latch must reset, deferring until eligible again.
const revisit = render(
<RetainedBrowserPaneOverlayLayer
worktreeId="wt-1"
isWorktreeActive={false}
mountEligible={false}
/>
)
expect(revisit.container.querySelectorAll('[data-browser-overlay-tab-id]')).toHaveLength(0)

revisit.rerender(
<RetainedBrowserPaneOverlayLayer worktreeId="wt-1" isWorktreeActive mountEligible />
)
expect(revisit.container.querySelectorAll('[data-browser-overlay-tab-id]')).toHaveLength(2)
})

it('does not retain browser slots from an eligible render that never commits', () => {
const pending = new Promise<never>(() => {})
const BlockCommit = ({ blocked }: { blocked: boolean }): null => {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,177 @@
import { describe, expect, it } from 'vitest'
import type { BrowserPage, BrowserWorkspace } from '../../../../shared/types'
import {
BROWSER_GUEST_HIDDEN_WORKTREE_RETENTION_LIMIT,
browserTabVisibilityPageIds,
selectBrowserGuestEvictionWorktreeIds,
touchBrowserGuestWorktreeRecency,
worktreeHoldsLiveBrowserGuests
} from './browser-guest-worktree-retention'

function browserTab(
id: string,
pageIds: string[] = [],
activePageId: string | null = null
): BrowserWorkspace {
return {
id,
worktreeId: 'wt-1',
label: id,
sessionProfileId: null,
pageIds,
activePageId,
url: 'about:blank',
title: id,
loading: false,
faviconUrl: null,
canGoBack: false,
canGoForward: false,
loadError: null,
createdAt: 1
}
}

function page(id: string, workspaceId: string): BrowserPage {
return {
id,
workspaceId,
worktreeId: 'wt-1',
url: 'about:blank',
title: id,
loading: false,
faviconUrl: null,
canGoBack: false,
canGoForward: false,
loadError: null,
createdAt: 1
}
}

type SelectionOverrides = Partial<Parameters<typeof selectBrowserGuestEvictionWorktreeIds>[0]>

function selectEvicted(overrides: SelectionOverrides): string[] {
return selectBrowserGuestEvictionWorktreeIds({
orderedWorktreeIds: [],
activeWorktreeId: null,
isRetained: () => true,
holdsLiveGuests: () => true,
isEvictable: () => true,
...overrides
})
}

describe('selectBrowserGuestEvictionWorktreeIds', () => {
const sixWorktrees = ['wt-1', 'wt-2', 'wt-3', 'wt-4', 'wt-5', 'wt-6']

it('is a no-op while retained guest-holding worktrees fit the budget', () => {
expect(
selectEvicted({
orderedWorktreeIds: sixWorktrees.slice(0, BROWSER_GUEST_HIDDEN_WORKTREE_RETENTION_LIMIT)
})
).toEqual([])
})

it('evicts the least-recently-activated worktrees beyond the budget', () => {
expect(selectEvicted({ orderedWorktreeIds: sixWorktrees })).toEqual(['wt-5', 'wt-6'])
})

it('never evicts or counts the active worktree', () => {
// Active most-recent: five hidden holders remain, so only the LRU one goes.
expect(selectEvicted({ orderedWorktreeIds: sixWorktrees, activeWorktreeId: 'wt-1' })).toEqual([
'wt-6'
])
// Active in LRU position: it is spared even though it ranks past the budget.
expect(selectEvicted({ orderedWorktreeIds: sixWorktrees, activeWorktreeId: 'wt-6' })).toEqual([
'wt-5'
])
})

it('counts only worktrees that actually hold live guests', () => {
const holders = new Set(['wt-5', 'wt-6'])
expect(
selectEvicted({
orderedWorktreeIds: sixWorktrees,
holdsLiveGuests: (worktreeId) => holders.has(worktreeId)
})
).toEqual([])
})

it('skips worktrees that are no longer retained', () => {
expect(
selectEvicted({
orderedWorktreeIds: sixWorktrees,
isRetained: (worktreeId) => worktreeId !== 'wt-1' && worktreeId !== 'wt-2'
})
).toEqual([])
})

it('keeps a non-evictable worktree retained over budget instead of evicting it', () => {
expect(
selectEvicted({
orderedWorktreeIds: sixWorktrees,
isEvictable: (worktreeId) => worktreeId !== 'wt-5'
})
).toEqual(['wt-6'])
})

it('lets a protected worktree within the budget occupy a retained slot', () => {
expect(
selectEvicted({
orderedWorktreeIds: ['wt-1', 'wt-2', 'wt-3', 'wt-4', 'wt-5'],
isEvictable: (worktreeId) => worktreeId !== 'wt-3'
})
).toEqual(['wt-5'])
})

it('counts duplicated recency entries once', () => {
expect(
selectEvicted({ orderedWorktreeIds: ['wt-1', 'wt-1', 'wt-2', 'wt-3', 'wt-4', 'wt-5'] })
).toEqual(['wt-5'])
})

it('honors a custom limit', () => {
expect(selectEvicted({ orderedWorktreeIds: sixWorktrees.slice(0, 3), limit: 1 })).toEqual([
'wt-2',
'wt-3'
])
})
})

describe('worktreeHoldsLiveBrowserGuests', () => {
it('detects live guests keyed by page id', () => {
const tabs = [browserTab('workspace-1', ['page-1'])]
const pages = { 'workspace-1': [page('page-1', 'workspace-1')] }

expect(worktreeHoldsLiveBrowserGuests(tabs, pages, (id) => id === 'page-1')).toBe(true)
expect(worktreeHoldsLiveBrowserGuests(tabs, pages, () => false)).toBe(false)
})

it('falls back to the workspace tab id for legacy sessions without pages', () => {
const tabs = [browserTab('legacy-workspace')]

expect(worktreeHoldsLiveBrowserGuests(tabs, {}, (id) => id === 'legacy-workspace')).toBe(true)
})
})

describe('browserTabVisibilityPageIds', () => {
it('mirrors the overlay slot derivation: pageIds, then activePageId, then tab id', () => {
expect(browserTabVisibilityPageIds(browserTab('tab-1', ['page-1', 'page-2']))).toEqual([
'page-1',
'page-2'
])
expect(browserTabVisibilityPageIds(browserTab('tab-1', [], 'page-3'))).toEqual(['page-3'])
expect(browserTabVisibilityPageIds(browserTab('tab-1'))).toEqual(['tab-1'])
})
})

describe('touchBrowserGuestWorktreeRecency', () => {
it('moves a re-activated worktree to the front without duplicating it', () => {
const recency = ['wt-2', 'wt-1']

touchBrowserGuestWorktreeRecency(recency, 'wt-1')
expect(recency).toEqual(['wt-1', 'wt-2'])

touchBrowserGuestWorktreeRecency(recency, 'wt-3')
expect(recency).toEqual(['wt-3', 'wt-1', 'wt-2'])
})
})
Loading
Loading