From 8f2d88c4ec85a37acdabff5a71a894b75ec5bbfc Mon Sep 17 00:00:00 2001 From: Jinwoo-H Date: Mon, 1 Jun 2026 13:15:50 -0700 Subject: [PATCH] Cap mounted terminal renderer panes Co-authored-by: Orca --- src/renderer/src/components/Terminal.tsx | 122 +++++++++++++++++- .../src/components/settings/TerminalPane.tsx | 36 ++++++ .../components/settings/terminal-search.ts | 5 + .../TerminalPaneOverlayLayer.tsx | 7 +- .../terminal/terminal-live-tab-set.test.ts | 53 ++++++++ .../terminal/terminal-live-tab-set.ts | 68 ++++++++++ src/shared/constants.ts | 1 + src/shared/types.ts | 2 + 8 files changed, 292 insertions(+), 2 deletions(-) create mode 100644 src/renderer/src/components/terminal/terminal-live-tab-set.test.ts create mode 100644 src/renderer/src/components/terminal/terminal-live-tab-set.ts diff --git a/src/renderer/src/components/Terminal.tsx b/src/renderer/src/components/Terminal.tsx index d9f7b1466..145b6a5ca 100644 --- a/src/renderer/src/components/Terminal.tsx +++ b/src/renderer/src/components/Terminal.tsx @@ -53,6 +53,7 @@ import TabGroupSplitLayout from './tab-group/TabGroupSplitLayout' import { shouldAutoCreateInitialTerminal } from './terminal/initial-terminal' import { shouldRepairActiveTerminalTab } from './terminal/active-terminal-repair' import { addBackgroundMountedTerminalWorktree } from './terminal/background-terminal-worktree-mount' +import { computeLiveTerminalTabIds } from './terminal/terminal-live-tab-set' import { getEffectiveLayoutForWorktree as getEffectiveLayout, anyMountedWorktreeHasLayout as computeAnyMountedWorktreeHasLayout @@ -185,6 +186,9 @@ function Terminal(): React.JSX.Element | null { const renderedActiveWorktreeId = activeWorktreeId const activeView = useAppStore((s) => s.activeView) const tabsByWorktree = useAppStore((s) => s.tabsByWorktree) + const unifiedTabsByWorktree = useAppStore((s) => s.unifiedTabsByWorktree) + const ptyIdsByTabId = useAppStore((s) => s.ptyIdsByTabId) + const pendingStartupByTabId = useAppStore((s) => s.pendingStartupByTabId) const activeTabId = useAppStore((s) => s.activeTabId) const createTab = useAppStore((s) => s.createTab) const closeTab = useAppStore((s) => s.closeTab) @@ -206,6 +210,7 @@ function Terminal(): React.JSX.Element | null { const terminalShortcutPolicy = useAppStore( (s) => s.settings?.terminalShortcutPolicy ?? 'orca-first' ) + const maxLiveTerminalPanes = useAppStore((s) => s.settings?.maxLiveTerminalPanes ?? 0) const setActiveTabType = useAppStore((s) => s.setActiveTabType) const setActiveFile = useAppStore((s) => s.setActiveFile) const closeFile = useAppStore((s) => s.closeFile) @@ -242,6 +247,9 @@ function Terminal(): React.JSX.Element | null { const activityTerminalPortals: ActivityTerminalPortalTarget[] = useActivityTerminalPortals( activeView === 'activity' ) + const terminalTabRecencyByIdRef = useRef(new Map()) + const terminalTabRecencyCounterRef = useRef(0) + const [terminalTabRecencyRevision, setTerminalTabRecencyRevision] = useState(0) const tabs = useMemo( () => (renderedActiveWorktreeId ? (tabsByWorktree[renderedActiveWorktreeId] ?? []) : []), @@ -281,6 +289,111 @@ function Terminal(): React.JSX.Element | null { ? (browserTabsByWorktree[renderedActiveWorktreeId] ?? []).map((tab) => tab.id).join(',') : '' + const requiredLiveTerminalTabIds = useMemo(() => { + const ids = new Set() + + if (activeView === 'terminal' && renderedActiveWorktreeId) { + if (getEffectiveLayoutForWorktree(renderedActiveWorktreeId)) { + const groups = groupsByWorktree[renderedActiveWorktreeId] ?? [] + const activeUnifiedIdsByGroup = new Map() + for (const group of groups) { + activeUnifiedIdsByGroup.set(group.id, group.activeTabId) + } + for (const tab of unifiedTabsByWorktree[renderedActiveWorktreeId] ?? []) { + if ( + tab.contentType === 'terminal' && + activeUnifiedIdsByGroup.get(tab.groupId) === tab.id + ) { + ids.add(tab.entityId) + } + } + } else if (activeTabType === 'terminal' && activeTabId) { + ids.add(activeTabId) + } + } + + for (const tabsForWorktree of Object.values(unifiedTabsByWorktree)) { + for (const tab of tabsForWorktree) { + if (tab.contentType === 'terminal' && tab.isPinned === true) { + ids.add(tab.entityId) + } + } + } + + for (const portal of activityTerminalPortals) { + ids.add(portal.tabId) + } + + for (const tabId of Object.keys(pendingStartupByTabId)) { + ids.add(tabId) + } + + for (const [worktreeId, terminalTabs] of Object.entries(tabsByWorktree)) { + const isRemoteWorktree = getConnectionId(worktreeId) !== null + for (const tab of terminalTabs) { + const ptyIds = ptyIdsByTabId[tab.id] ?? [] + if (isRemoteWorktree || ptyIds.some(isRemoteRuntimePtyId)) { + ids.add(tab.id) + } + } + } + + return ids + }, [ + activeTabId, + activeTabType, + activeView, + activityTerminalPortals, + getEffectiveLayoutForWorktree, + groupsByWorktree, + pendingStartupByTabId, + ptyIdsByTabId, + renderedActiveWorktreeId, + tabsByWorktree, + unifiedTabsByWorktree + ]) + + const requiredLiveTerminalTabIdsKey = useMemo( + () => Array.from(requiredLiveTerminalTabIds).sort().join('\0'), + [requiredLiveTerminalTabIds] + ) + + useEffect(() => { + const knownTabIds = new Set( + Object.values(tabsByWorktree).flatMap((worktreeTabs) => worktreeTabs.map((tab) => tab.id)) + ) + let changed = false + + for (const tabId of Array.from(terminalTabRecencyByIdRef.current.keys())) { + if (!knownTabIds.has(tabId)) { + terminalTabRecencyByIdRef.current.delete(tabId) + changed = true + } + } + + for (const tabId of requiredLiveTerminalTabIds) { + terminalTabRecencyCounterRef.current += 1 + terminalTabRecencyByIdRef.current.set(tabId, terminalTabRecencyCounterRef.current) + changed = true + } + + if (changed) { + setTerminalTabRecencyRevision((revision) => revision + 1) + } + }, [requiredLiveTerminalTabIds, requiredLiveTerminalTabIdsKey, tabsByWorktree]) + + const liveTerminalTabIds = useMemo(() => { + // Why: recency is stored in a mutable ref, so this revision is the render + // signal that recomputes the live/cold pane split after visible tabs move. + void terminalTabRecencyRevision + return computeLiveTerminalTabIds({ + tabsByWorktree, + maxLiveTerminalPanes, + requiredTabIds: requiredLiveTerminalTabIds, + recentUseByTabId: terminalTabRecencyByIdRef.current + }) + }, [maxLiveTerminalPanes, requiredLiveTerminalTabIds, tabsByWorktree, terminalTabRecencyRevision]) + // Save confirmation dialog state const [saveDialogFileId, setSaveDialogFileId] = useState(null) const saveDialogFile = saveDialogFileId ? openFiles.find((f) => f.id === saveDialogFileId) : null @@ -1657,6 +1770,7 @@ function Terminal(): React.JSX.Element | null { isVisible={isVisible} shouldMeasureHiddenWorktree={shouldMeasureHiddenWorktree} activityTerminalPortals={activityTerminalPortals} + liveTerminalTabIds={liveTerminalTabIds} /> ) })} @@ -1720,6 +1834,9 @@ function Terminal(): React.JSX.Element | null { > {(tabsByWorktree[worktree.id] ?? []).map((tab) => { + if (liveTerminalTabIds && !liveTerminalTabIds.has(tab.id)) { + return null + } const activityTerminalPortal = findActivityTerminalPortal( activityTerminalPortals, { worktreeId: worktree.id, tabId: tab.id } @@ -1915,7 +2032,8 @@ const WorktreeSplitSurface = React.memo(function WorktreeSplitSurface({ focusedGroupId, isVisible, shouldMeasureHiddenWorktree, - activityTerminalPortals + activityTerminalPortals, + liveTerminalTabIds }: { worktreeId: string worktreePath: string @@ -1924,6 +2042,7 @@ const WorktreeSplitSurface = React.memo(function WorktreeSplitSurface({ isVisible: boolean shouldMeasureHiddenWorktree: boolean activityTerminalPortals: ActivityTerminalPortalTarget[] + liveTerminalTabIds: Set | null }): React.JSX.Element { const browserPageIds = useAppStore( useShallow((state) => @@ -1961,6 +2080,7 @@ const WorktreeSplitSurface = React.memo(function WorktreeSplitSurface({ worktreePath={worktreePath} isWorktreeActive={isVisible} activityTerminalPortals={activityTerminalPortals} + liveTerminalTabIds={liveTerminalTabIds} /> diff --git a/src/renderer/src/components/settings/TerminalPane.tsx b/src/renderer/src/components/settings/TerminalPane.tsx index 94ebd1243..4f6982066 100644 --- a/src/renderer/src/components/settings/TerminalPane.tsx +++ b/src/renderer/src/components/settings/TerminalPane.tsx @@ -229,6 +229,42 @@ export function TerminalPane({ } /> + + + ) : null, diff --git a/src/renderer/src/components/settings/terminal-search.ts b/src/renderer/src/components/settings/terminal-search.ts index 0773f85c3..72816ecff 100644 --- a/src/renderer/src/components/settings/terminal-search.ts +++ b/src/renderer/src/components/settings/terminal-search.ts @@ -58,6 +58,11 @@ export const TERMINAL_RENDERING_SEARCH_ENTRIES: SettingsSearchEntry[] = [ 'linux', 'vscode' ] + }, + { + title: 'Live Terminal Pane Limit', + description: 'Caps how many hidden terminal renderer panes stay mounted. 0 disables eviction.', + keywords: ['terminal', 'live panes', 'limit', 'lru', 'memory', 'xterm', 'renderer'] } ] diff --git a/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx b/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx index 08a44186a..08db5c9e4 100644 --- a/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx +++ b/src/renderer/src/components/terminal-pane/TerminalPaneOverlayLayer.tsx @@ -134,12 +134,14 @@ const TerminalPaneOverlayLayer = memo(function TerminalPaneOverlayLayer({ worktreeId, worktreePath, isWorktreeActive, - activityTerminalPortals = EMPTY_ACTIVITY_PORTALS + activityTerminalPortals = EMPTY_ACTIVITY_PORTALS, + liveTerminalTabIds = null }: { worktreeId: string worktreePath: string isWorktreeActive: boolean activityTerminalPortals?: ActivityTerminalPortalTarget[] + liveTerminalTabIds?: ReadonlySet | null }): React.JSX.Element | null { const { terminalTabs, unifiedTabs, groups, activeGroupId } = useAppStore( useShallow((state) => ({ @@ -213,6 +215,9 @@ const TerminalPaneOverlayLayer = memo(function TerminalPaneOverlayLayer({ worktreeId, tabId: terminalTab.id }) + if (liveTerminalTabIds && !liveTerminalTabIds.has(terminalTab.id)) { + return null + } return ( { + it('returns null when the live pane cap is disabled', () => { + expect( + computeLiveTerminalTabIds({ + tabsByWorktree: { 'wt-1': [tab('a', 1), tab('b', 2)] }, + maxLiveTerminalPanes: 0 + }) + ).toBeNull() + }) + + it('keeps required tabs even when they exceed the configured cap', () => { + const live = computeLiveTerminalTabIds({ + tabsByWorktree: { 'wt-1': [tab('visible-1', 1), tab('visible-2', 2), tab('cold', 3)] }, + maxLiveTerminalPanes: 1, + requiredTabIds: new Set(['visible-1', 'visible-2']) + }) + + expect(live).toEqual(new Set(['visible-1', 'visible-2'])) + }) + + it('fills remaining slots by recent use, then creation time', () => { + const live = computeLiveTerminalTabIds({ + tabsByWorktree: { + 'wt-1': [tab('old', 1), tab('newer', 2), tab('recent', 0), tab('visible', 3)] + }, + maxLiveTerminalPanes: 3, + requiredTabIds: new Set(['visible']), + recentUseByTabId: new Map([['recent', 10]]) + }) + + expect(live).toEqual(new Set(['visible', 'recent', 'newer'])) + }) +}) + +describe('normalizeMaxLiveTerminalPanes', () => { + it('clamps malformed and extreme values', () => { + expect(normalizeMaxLiveTerminalPanes(undefined)).toBe(0) + expect(normalizeMaxLiveTerminalPanes(-1)).toBe(0) + expect(normalizeMaxLiveTerminalPanes(3.8)).toBe(3) + expect(normalizeMaxLiveTerminalPanes(999)).toBe(500) + }) +}) diff --git a/src/renderer/src/components/terminal/terminal-live-tab-set.ts b/src/renderer/src/components/terminal/terminal-live-tab-set.ts new file mode 100644 index 000000000..add792444 --- /dev/null +++ b/src/renderer/src/components/terminal/terminal-live-tab-set.ts @@ -0,0 +1,68 @@ +import type { TerminalTab } from '../../../../shared/types' + +export const DISABLED_MAX_LIVE_TERMINAL_PANES = 0 + +export type TerminalLiveTab = Pick + +export type TerminalLiveTabSetArgs = { + tabsByWorktree: Record + maxLiveTerminalPanes: number | null | undefined + requiredTabIds?: ReadonlySet + recentUseByTabId?: ReadonlyMap +} + +export function normalizeMaxLiveTerminalPanes(value: unknown): number { + if (typeof value !== 'number' || !Number.isFinite(value)) { + return DISABLED_MAX_LIVE_TERMINAL_PANES + } + return Math.max(0, Math.min(500, Math.floor(value))) +} + +export function computeLiveTerminalTabIds({ + tabsByWorktree, + maxLiveTerminalPanes, + requiredTabIds = new Set(), + recentUseByTabId = new Map() +}: TerminalLiveTabSetArgs): Set | null { + const limit = normalizeMaxLiveTerminalPanes(maxLiveTerminalPanes) + if (limit === DISABLED_MAX_LIVE_TERMINAL_PANES) { + return null + } + + const allTabs = Object.values(tabsByWorktree).flat() + const allTabIds = new Set(allTabs.map((tab) => tab.id)) + const live = new Set() + for (const tabId of requiredTabIds) { + if (allTabIds.has(tabId)) { + live.add(tabId) + } + } + + const effectiveLimit = Math.max(limit, live.size) + if (live.size >= effectiveLimit) { + return live + } + + const candidates = allTabs + .filter((tab) => !live.has(tab.id)) + .sort((left, right) => { + const leftRecent = recentUseByTabId.get(left.id) ?? Number.NEGATIVE_INFINITY + const rightRecent = recentUseByTabId.get(right.id) ?? Number.NEGATIVE_INFINITY + if (leftRecent !== rightRecent) { + return rightRecent - leftRecent + } + if (left.createdAt !== right.createdAt) { + return right.createdAt - left.createdAt + } + return left.id.localeCompare(right.id) + }) + + for (const tab of candidates) { + if (live.size >= effectiveLimit) { + break + } + live.add(tab.id) + } + + return live +} diff --git a/src/shared/constants.ts b/src/shared/constants.ts index aeeaaf3e6..b71bcbd7e 100644 --- a/src/shared/constants.ts +++ b/src/shared/constants.ts @@ -227,6 +227,7 @@ export function getDefaultSettings(homedir: string): GlobalSettings { terminalAllowOsc52Clipboard: false, setupScriptLaunchMode: 'new-tab', terminalScrollbackBytes: 10_000_000, + maxLiveTerminalPanes: 0, httpProxyUrl: '', httpProxyBypassRules: '', openLinksInApp: true, diff --git a/src/shared/types.ts b/src/shared/types.ts index e54dcaf4a..e7254c18e 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -1992,6 +1992,8 @@ export type GlobalSettings = { * usable without the setup output crowding the initial pane. */ setupScriptLaunchMode: SetupScriptLaunchMode terminalScrollbackBytes: number + /** Max number of mounted xterm renderer panes to keep warm. 0 disables eviction. */ + maxLiveTerminalPanes?: number /** Optional app-level proxy for Electron networking and locally spawned PTYs. * Empty preserves system proxy settings plus inherited proxy env behavior. */ httpProxyUrl?: string