Reduce tab update churn

Narrows tab-bar subscriptions and avoids no-op terminal/unified-tab map churn without changing polling freshness.
This commit is contained in:
Neil
2026-05-21 20:45:02 -07:00
committed by GitHub
parent a97191d4aa
commit a0ca64b0f8
6 changed files with 221 additions and 60 deletions
@@ -38,6 +38,8 @@ import {
} from '@/components/ui/dropdown-menu'
const isWindows = navigator.userAgent.includes('Windows')
type GitStatusEntries = ReturnType<typeof useAppStore.getState>['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 <webview> elements run in a separate process, so clicking
// inside one never dispatches a pointerdown on the renderer document.
@@ -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.
@@ -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'
@@ -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 {
@@ -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')
+88 -55
View File
@@ -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<string, TerminalTab[]> | null = null
let terminalTabOwnerCache = new Map<string, string>()
function getTerminalTabOwnerWorktreeId(
tabsByWorktree: Record<string, TerminalTab[]>,
tabId: string
): string | null {
if (terminalTabOwnerCacheSource !== tabsByWorktree) {
const nextCache = new Map<string, string>()
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<AppState, [], [], TerminalSlice>
// 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<AppState, [], [], TerminalSlice>
// 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<AppState> = 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<AppState, [], [], TerminalSlice>
// 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<AppState, [], [], TerminalSlice>
// 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 {