diff --git a/src/renderer/src/components/tab-bar/TabBar.tsx b/src/renderer/src/components/tab-bar/TabBar.tsx index a095ad2a6..b6585c001 100644 --- a/src/renderer/src/components/tab-bar/TabBar.tsx +++ b/src/renderer/src/components/tab-bar/TabBar.tsx @@ -38,6 +38,8 @@ import { } from '@/components/ui/dropdown-menu' const isWindows = navigator.userAgent.includes('Windows') +type GitStatusEntries = ReturnType['gitStatusByWorktree'][string] +const EMPTY_GIT_STATUS_ENTRIES: GitStatusEntries = [] type TabBarProps = { tabs: (TerminalTab & { unifiedTabId?: string })[] @@ -144,7 +146,9 @@ function TabBarInner({ const newTerminalShortcut = useShortcutLabel('tab.newTerminal') const newBrowserShortcut = useShortcutLabel('tab.newBrowser') const newFileShortcut = useShortcutLabel('tab.newMarkdown') - const gitStatusByWorktree = useAppStore((s) => s.gitStatusByWorktree) + const gitStatusEntries = useAppStore( + (s) => s.gitStatusByWorktree[worktreeId] ?? EMPTY_GIT_STATUS_ENTRIES + ) const defaultWindowsShell = useAppStore( (s) => s.settings?.terminalWindowsShell ?? 'powershell.exe' ) @@ -154,10 +158,7 @@ function TabBarInner({ const windowsTerminalCapabilities = useWindowsTerminalCapabilities(isWindows) const resolvedGroupId = groupId ?? worktreeId - const statusByRelativePath = useMemo( - () => buildStatusMap(gitStatusByWorktree[worktreeId] ?? []), - [worktreeId, gitStatusByWorktree] - ) + const statusByRelativePath = useMemo(() => buildStatusMap(gitStatusEntries), [gitStatusEntries]) // Why: Electron elements run in a separate process, so clicking // inside one never dispatches a pointerdown on the renderer document. diff --git a/src/renderer/src/store/slices/runtime-pane-title-sort-epoch.test.ts b/src/renderer/src/store/slices/runtime-pane-title-sort-epoch.test.ts index 8f39b0db3..c09129ba5 100644 --- a/src/renderer/src/store/slices/runtime-pane-title-sort-epoch.test.ts +++ b/src/renderer/src/store/slices/runtime-pane-title-sort-epoch.test.ts @@ -59,6 +59,32 @@ describe('runtimePaneTitle → sortEpoch', () => { expect(store.getState().sortEpoch).toBe(baseline) }) + it('does not enumerate terminal tabs when the classification is unchanged', () => { + const store = createTestStore() + seedStore(store, { + worktreesByRepo: { + repo1: [makeWorktree({ id: 'wt-bg', repoId: 'repo1', path: '/path/wt-bg' })] + }, + tabsByWorktree: { + 'wt-bg': [makeTab({ id: 'tab-1', worktreeId: 'wt-bg' })] + } + }) + store.getState().setRuntimePaneTitle('tab-1', 1, '⠋ Claude') + const baseline = store.getState().sortEpoch + store.setState({ + tabsByWorktree: new Proxy(store.getState().tabsByWorktree, { + ownKeys() { + throw new Error('tabsByWorktree should not be enumerated') + } + }) + }) + + store.getState().setRuntimePaneTitle('tab-1', 1, '⠙ Claude') + + expect(store.getState().runtimePaneTitlesByTabId['tab-1']?.[1]).toBe('⠙ Claude') + expect(store.getState().sortEpoch).toBe(baseline) + }) + it('bumps sortEpoch when clearing a classified title back to none', () => { const store = createTestStore() seedStore(store, { @@ -75,6 +101,32 @@ describe('runtimePaneTitle → sortEpoch', () => { expect(store.getState().sortEpoch).toBeGreaterThan(baseline) }) + it('does not enumerate terminal tabs when clearing an unclassified title', () => { + const store = createTestStore() + seedStore(store, { + worktreesByRepo: { + repo1: [makeWorktree({ id: 'wt-bg', repoId: 'repo1', path: '/path/wt-bg' })] + }, + tabsByWorktree: { + 'wt-bg': [makeTab({ id: 'tab-1', worktreeId: 'wt-bg' })] + } + }) + store.getState().setRuntimePaneTitle('tab-1', 1, 'shell prompt') + const baseline = store.getState().sortEpoch + store.setState({ + tabsByWorktree: new Proxy(store.getState().tabsByWorktree, { + ownKeys() { + throw new Error('tabsByWorktree should not be enumerated') + } + }) + }) + + store.getState().clearRuntimePaneTitle('tab-1', 1) + + expect(store.getState().runtimePaneTitlesByTabId['tab-1']).toBeUndefined() + expect(store.getState().sortEpoch).toBe(baseline) + }) + it('does not bump sortEpoch when the changing pane belongs to the active worktree (set)', () => { // Why: clicking a slept worktree wakes it; the PTY remount briefly // reclassifies its title, which must NOT re-rank the active worktree. diff --git a/src/renderer/src/store/slices/store-cascades.test.ts b/src/renderer/src/store/slices/store-cascades.test.ts index 69a3110c9..4531884c6 100644 --- a/src/renderer/src/store/slices/store-cascades.test.ts +++ b/src/renderer/src/store/slices/store-cascades.test.ts @@ -1358,6 +1358,65 @@ describe('setActiveWorktree', () => { }) }) + it('preserves terminal and unified tab map references when a live title repeats', () => { + const store = createTestStore() + const wt = 'repo1::/path/wt1' + + seedStore(store, { + worktreesByRepo: { + repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })] + } + }) + + const first = store.getState().createTab(wt) + store.getState().updateTabTitle(first.id, 'Claude Code') + const tabsByWorktree = store.getState().tabsByWorktree + const unifiedTabsByWorktree = store.getState().unifiedTabsByWorktree + const sortEpoch = store.getState().sortEpoch + + store.getState().updateTabTitle(first.id, 'Claude Code') + + expect(store.getState().tabsByWorktree).toBe(tabsByWorktree) + expect(store.getState().unifiedTabsByWorktree).toBe(unifiedTabsByWorktree) + expect(store.getState().sortEpoch).toBe(sortEpoch) + }) + + it('repairs a stale unified tab label when a live title repeats', () => { + const store = createTestStore() + const wt = 'repo1::/path/wt1' + + seedStore(store, { + worktreesByRepo: { + repo1: [makeWorktree({ id: wt, repoId: 'repo1', path: '/path/wt1' })] + } + }) + + const first = store.getState().createTab(wt) + store.getState().updateTabTitle(first.id, 'Claude Code') + const tabsByWorktree = store.getState().tabsByWorktree + store.setState((state) => ({ + unifiedTabsByWorktree: { + ...state.unifiedTabsByWorktree, + [wt]: state.unifiedTabsByWorktree[wt].map((tab) => + tab.contentType === 'terminal' && tab.entityId === first.id + ? { ...tab, label: 'stale' } + : tab + ) + } + })) + + store.getState().updateTabTitle(first.id, 'Claude Code') + + expect(store.getState().tabsByWorktree).toBe(tabsByWorktree) + expect( + store + .getState() + .unifiedTabsByWorktree[wt]?.find( + (tab) => tab.contentType === 'terminal' && tab.entityId === first.id + )?.label + ).toBe('Claude Code') + }) + it('clears stale background browser tab type when closing the last browser tab', () => { const store = createTestStore() const wt = 'repo1::/path/wt1' diff --git a/src/renderer/src/store/slices/tab-group-state.ts b/src/renderer/src/store/slices/tab-group-state.ts index b5d634cee..5a7c76694 100644 --- a/src/renderer/src/store/slices/tab-group-state.ts +++ b/src/renderer/src/store/slices/tab-group-state.ts @@ -208,6 +208,12 @@ export function patchTab( if (!found) { return null } + const patchChangesTab = (Object.keys(patch) as (keyof Tab)[]).some( + (key) => found.tab[key] !== patch[key] + ) + if (!patchChangesTab) { + return null + } const { worktreeId } = found const tabs = tabsByWorktree[worktreeId] ?? [] return { diff --git a/src/renderer/src/store/slices/tabs.test.ts b/src/renderer/src/store/slices/tabs.test.ts index 550946376..53a456d8b 100644 --- a/src/renderer/src/store/slices/tabs.test.ts +++ b/src/renderer/src/store/slices/tabs.test.ts @@ -975,6 +975,16 @@ describe('TabsSlice', () => { expect(store.getState().unifiedTabsByWorktree[WT][0].label).toBe('zsh') }) + it('setTabLabel preserves tab map references when the label is unchanged', () => { + const tab = store.getState().createUnifiedTab(WT, 'terminal') + store.getState().setTabLabel(tab.id, 'zsh') + const before = store.getState().unifiedTabsByWorktree + + store.getState().setTabLabel(tab.id, 'zsh') + + expect(store.getState().unifiedTabsByWorktree).toBe(before) + }) + it('setTabCustomLabel updates customLabel', () => { const tab = store.getState().createUnifiedTab(WT, 'terminal') store.getState().setTabCustomLabel(tab.id, 'my-term') diff --git a/src/renderer/src/store/slices/terminals.ts b/src/renderer/src/store/slices/terminals.ts index 5bb9b503e..46a864c5f 100644 --- a/src/renderer/src/store/slices/terminals.ts +++ b/src/renderer/src/store/slices/terminals.ts @@ -3,6 +3,7 @@ import type { StateCreator } from 'zustand' import type { AppState } from '../types' import type { SetupSplitDirection, + Tab, TerminalLayoutSnapshot, TerminalTab, Worktree, @@ -67,6 +68,40 @@ function getFallbackTabTitle(tab: TerminalTab, index?: number): string { ) } +let terminalTabOwnerCacheSource: Record | null = null +let terminalTabOwnerCache = new Map() + +function getTerminalTabOwnerWorktreeId( + tabsByWorktree: Record, + tabId: string +): string | null { + if (terminalTabOwnerCacheSource !== tabsByWorktree) { + const nextCache = new Map() + for (const [worktreeId, tabs] of Object.entries(tabsByWorktree)) { + for (const tab of tabs) { + nextCache.set(tab.id, worktreeId) + } + } + terminalTabOwnerCacheSource = tabsByWorktree + terminalTabOwnerCache = nextCache + } + return terminalTabOwnerCache.get(tabId) ?? null +} + +function updateUnifiedTerminalLabel( + unifiedTabs: Tab[], + terminalTabId: string, + label: string +): Tab[] | null { + const unifiedIndex = unifiedTabs.findIndex( + (entry) => entry.contentType === 'terminal' && entry.entityId === terminalTabId + ) + if (unifiedIndex === -1 || unifiedTabs[unifiedIndex]?.label === label) { + return null + } + return unifiedTabs.map((entry, index) => (index === unifiedIndex ? { ...entry, label } : entry)) +} + function isWindowsRendererRuntime(): boolean { return typeof navigator !== 'undefined' && navigator.userAgent.includes('Windows') } @@ -812,38 +847,47 @@ export const createTerminalSlice: StateCreator // unchanged) would break shallow-equality checks in unrelated // selectors and trigger spurious re-renders across background // worktrees on every OSC title frame. - let ownerWorktreeId: string | null = null - let ownerTabs: TerminalTab[] | null = null - for (const [wId, tabs] of Object.entries(s.tabsByWorktree)) { - const idx = tabs.findIndex((t) => t.id === tabId) - if (idx === -1) { - continue - } - const t = tabs[idx] - const nextTitle = title.trim() || getFallbackTabTitle(t) - if (t.title === nextTitle) { - return s - } - ownerWorktreeId = wId - ownerTabs = tabs.map((tab) => - tab.id === tabId - ? { - ...tab, - // Why: PTYs can briefly emit an empty title while an agent exits. - // Keep the stable fallback label instead of rendering a blank tab. - title: nextTitle, - defaultTitle: - tab.defaultTitle ?? - (/^Terminal \d+$/.test(tab.title) ? tab.title : undefined) ?? - (/^Terminal \d+$/.test(nextTitle) ? nextTitle : undefined) - } - : tab - ) - break - } - if (!ownerWorktreeId || !ownerTabs) { + const ownerWorktreeId = getTerminalTabOwnerWorktreeId(s.tabsByWorktree, tabId) + if (!ownerWorktreeId) { return s } + const tabs = s.tabsByWorktree[ownerWorktreeId] ?? [] + const tabIndex = tabs.findIndex((t) => t.id === tabId) + const currentTab = tabs[tabIndex] + if (!currentTab) { + return s + } + const nextTitle = title.trim() || getFallbackTabTitle(currentTab) + const currentUnifiedTabs = s.unifiedTabsByWorktree[ownerWorktreeId] ?? [] + const unifiedTabsWithUpdatedLabel = updateUnifiedTerminalLabel( + currentUnifiedTabs, + tabId, + nextTitle + ) + if (currentTab.title === nextTitle) { + return unifiedTabsWithUpdatedLabel + ? { + unifiedTabsByWorktree: { + ...s.unifiedTabsByWorktree, + [ownerWorktreeId]: unifiedTabsWithUpdatedLabel + } + } + : s + } + const ownerTabs = tabs.map((tab) => + tab.id === tabId + ? { + ...tab, + // Why: PTYs can briefly emit an empty title while an agent exits. + // Keep the stable fallback label instead of rendering a blank tab. + title: nextTitle, + defaultTitle: + tab.defaultTitle ?? + (/^Terminal \d+$/.test(tab.title) ? tab.title : undefined) ?? + (/^Terminal \d+$/.test(nextTitle) ? nextTitle : undefined) + } + : tab + ) scheduleRuntimeGraphSync() const nextTabsByWorktree = { ...s.tabsByWorktree, [ownerWorktreeId]: ownerTabs } // Agent status is derived from terminal titles and affects sort scoring, @@ -854,20 +898,17 @@ export const createTerminalSlice: StateCreator // title update). Bumping sortEpoch here would reorder the sidebar // on click — the exact bug PR #209 intended to fix. const isActive = ownerWorktreeId === s.activeWorktreeId - return isActive + const nextState: Partial = isActive ? { tabsByWorktree: nextTabsByWorktree } : { tabsByWorktree: nextTabsByWorktree, sortEpoch: s.sortEpoch + 1 } + if (unifiedTabsWithUpdatedLabel) { + nextState.unifiedTabsByWorktree = { + ...s.unifiedTabsByWorktree, + [ownerWorktreeId]: unifiedTabsWithUpdatedLabel + } + } + return nextState }) - const item = Object.values(get().unifiedTabsByWorktree) - .flat() - .find((entry) => entry.contentType === 'terminal' && entry.entityId === tabId) - if (item) { - const resolvedTitle = - Object.values(get().tabsByWorktree) - .flat() - .find((tab) => tab.id === tabId)?.title ?? title.trim() - get().setTabLabel(item.id, resolvedTitle) - } }, setRuntimePaneTitle: (tabId, paneId, title) => { @@ -892,13 +933,9 @@ export const createTerminalSlice: StateCreator // re-emits its working title) — bumping would re-rank the sidebar on // click, the exact bug PR #209 fixed for updateTabTitle. If no owner // is found the pane is orphaned; skip the bump as unsafe. - let ownerWorktreeId: string | null = null - for (const [wId, tabs] of Object.entries(s.tabsByWorktree)) { - if (tabs.some((t) => t.id === tabId)) { - ownerWorktreeId = wId - break - } - } + const ownerWorktreeId = classificationChanged + ? getTerminalTabOwnerWorktreeId(s.tabsByWorktree, tabId) + : null const isActive = ownerWorktreeId !== null && ownerWorktreeId === s.activeWorktreeId const shouldBump = classificationChanged && ownerWorktreeId !== null && !isActive return { @@ -936,13 +973,9 @@ export const createTerminalSlice: StateCreator // fire as a side-effect of a click-driven PTY teardown in the active // worktree must not re-rank the sidebar. Skip bumping when no owner is // found (orphaned pane) for the same safety reason. - let ownerWorktreeId: string | null = null - for (const [wId, tabs] of Object.entries(s.tabsByWorktree)) { - if (tabs.some((t) => t.id === tabId)) { - ownerWorktreeId = wId - break - } - } + const ownerWorktreeId = hadClassification + ? getTerminalTabOwnerWorktreeId(s.tabsByWorktree, tabId) + : null const isActive = ownerWorktreeId !== null && ownerWorktreeId === s.activeWorktreeId const shouldBump = hadClassification && ownerWorktreeId !== null && !isActive return {