From ef298d75efa7f61b61926ba4afc7e564238a0c7c Mon Sep 17 00:00:00 2001 From: just-zzp <264744947+just-zzp@users.noreply.github.com> Date: Sun, 19 Jul 2026 10:53:51 +0900 Subject: [PATCH 1/4] fix(source-control): preserve section collapse state --- .../right-sidebar/SourceControl.tsx | 24 +--- .../SourceControl.virtual-file-list.test.tsx | 18 ++- ...ce-control-section-collapse-state.test.tsx | 120 ++++++++++++++++++ .../source-control-section-collapse-state.ts | 111 ++++++++++++++++ 4 files changed, 250 insertions(+), 23 deletions(-) create mode 100644 src/renderer/src/components/right-sidebar/source-control-section-collapse-state.test.tsx create mode 100644 src/renderer/src/components/right-sidebar/source-control-section-collapse-state.ts diff --git a/src/renderer/src/components/right-sidebar/SourceControl.tsx b/src/renderer/src/components/right-sidebar/SourceControl.tsx index c1574bd8b8c5..ef19d9a5f8f2 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.tsx @@ -115,6 +115,7 @@ import { type SourceControlEntryGroups, type SourceControlSectionArea } from './source-control-section-order' +import { useSourceControlSectionCollapseState } from './source-control-section-collapse-state' import { SourceControlVirtualFileList } from './source-control-virtual-file-list' import { selectReviewCacheData, selectReviewCacheEntry } from './review-cache-entry-selection' import { @@ -544,7 +545,6 @@ const SOURCE_CONTROL_TREE_INDENT_PX = 12 const SOURCE_CONTROL_TREE_DIRECTORY_PADDING_PX = 8 const SOURCE_CONTROL_TREE_FILE_PADDING_PX = 20 const EMPTY_GIT_HISTORY_STATE: GitHistoryPanelState = { status: 'idle' } -const DEFAULT_COLLAPSED_SECTIONS = ['history'] as const const SUBMODULE_WORKTREE_ONLY_LABEL = 'Stage inside submodule' const SUBMODULE_WORKTREE_ONLY_TOOLTIP = 'The parent repo (including Stage All) cannot stage file changes inside a submodule' @@ -552,10 +552,6 @@ const SUBMODULE_LOADING_LABEL = 'Loading submodule changes…' const SUBMODULE_EMPTY_LABEL = 'No changes in submodule' const SUBMODULE_ERROR_LABEL = 'Failed to load submodule changes' -function createDefaultCollapsedSections(): Set { - return new Set(DEFAULT_COLLAPSED_SECTIONS) -} - function useCopyFeedbackState(resetValue: T): [T, (value: T) => void] { const [value, setValue] = useState(resetValue) const resetTimerRef = useRef(null) @@ -1054,9 +1050,8 @@ function SourceControlInner(): React.JSX.Element { ]) const [filterExpanded, setFilterExpanded] = useState(false) - const [collapsedSections, setCollapsedSections] = useState>( - createDefaultCollapsedSections - ) + const { collapsedSections, toggleSection } = + useSourceControlSectionCollapseState(activeWorktreeId) const persistedSourceControlViewMode = normalizeSourceControlViewMode( settings?.sourceControlViewMode ) @@ -2074,7 +2069,6 @@ function SourceControlInner(): React.JSX.Element { // worktree's UI state doesn't leak into the new one. useEffect(() => { setFilterExpanded(false) - setCollapsedSections(createDefaultCollapsedSections()) setCollapsedTreeDirs(new Set()) setBaseRefDialogOpen(false) setPendingDiscard(null) @@ -5106,18 +5100,6 @@ function SourceControlInner(): React.JSX.Element { worktreePath ]) - const toggleSection = useCallback((section: string) => { - setCollapsedSections((prev) => { - const next = new Set(prev) - if (next.has(section)) { - next.delete(section) - } else { - next.add(section) - } - return next - }) - }, []) - const toggleTreeDir = useCallback((key: string) => { setCollapsedTreeDirs((prev) => { const next = new Set(prev) diff --git a/src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx b/src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx index 2dc5f0bc474d..a4fd9b224bfa 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx @@ -11,6 +11,7 @@ import { SOURCE_CONTROL_FILE_ROW_OVERSCAN, SOURCE_CONTROL_VIRTUALIZE_MIN_ROWS } from './source-control-virtual-file-list' +import { clearSourceControlSectionCollapseStateForTests } from './source-control-section-collapse-state' const mocks = vi.hoisted(() => { const activeRepo = { @@ -195,6 +196,7 @@ class NoopResizeObserver { beforeEach(() => { globalThis.IS_REACT_ACT_ENVIRONMENT = true + clearSourceControlSectionCollapseStateForTests() resetState() container = document.createElement('div') document.body.appendChild(container) @@ -235,6 +237,7 @@ beforeEach(() => { afterEach(() => { act(() => root.unmount()) container.remove() + clearSourceControlSectionCollapseStateForTests() vi.unstubAllGlobals() vi.restoreAllMocks() }) @@ -339,7 +342,7 @@ describe('SourceControl virtualized changed-files list', () => { expect(row('src/file-000.ts')?.className).toContain('bg-accent/60') }) - it('collapses and re-expands a virtualized section', () => { + it('keeps a virtualized section collapsed across a Source Control remount', () => { resetState({ gitStatusByWorktree: { [mocks.activeWorktree.id]: manyEntries(500) } }) @@ -357,8 +360,19 @@ describe('SourceControl virtualized changed-files list', () => { expect(mountedRows().length).toBe(0) expect(virtualList()).toBeNull() + // Simulate visiting Explorer or Checks, which fully unmounts Source Control. + act(() => root.unmount()) + root = createRoot(container) + renderSourceControl() + + expect(mountedRows().length).toBe(0) + expect(virtualList()).toBeNull() + + const remountedChangesHeader = Array.from(container.querySelectorAll('button')).find((button) => + button.textContent?.includes('Changes') + ) act(() => { - changesHeader?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + remountedChangesHeader?.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) expect(mountedRows().length).toBeGreaterThan(0) expect(mountedRows().length).toBeLessThanOrEqual(MAX_MOUNTED_ROWS) diff --git a/src/renderer/src/components/right-sidebar/source-control-section-collapse-state.test.tsx b/src/renderer/src/components/right-sidebar/source-control-section-collapse-state.test.tsx new file mode 100644 index 000000000000..24e07e7cc13e --- /dev/null +++ b/src/renderer/src/components/right-sidebar/source-control-section-collapse-state.test.tsx @@ -0,0 +1,120 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { + clearSourceControlSectionCollapseStateForTests, + getSourceControlSectionCollapseStateCountForTests, + MAX_PERSISTED_SOURCE_CONTROL_SECTION_STATES, + seedSourceControlSectionCollapseStateForTests, + useSourceControlSectionCollapseState, + type SourceControlCollapsibleSectionId +} from './source-control-section-collapse-state' + +let container: HTMLDivElement +let root: Root + +function Probe({ + worktreeId, + section +}: { + worktreeId: string + section: SourceControlCollapsibleSectionId +}): React.JSX.Element { + const { collapsedSections, toggleSection } = useSourceControlSectionCollapseState(worktreeId) + return ( + + ) +} + +function renderProbe(worktreeId: string, section: SourceControlCollapsibleSectionId): void { + act(() => root.render()) +} + +function readCollapsed(): string | null { + return container.querySelector('button')?.getAttribute('data-collapsed') ?? null +} + +function toggle(): void { + act(() => { + container.querySelector('button')?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) +} + +describe('useSourceControlSectionCollapseState', () => { + beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + clearSourceControlSectionCollapseStateForTests() + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) + }) + + afterEach(() => { + act(() => root.unmount()) + container.remove() + clearSourceControlSectionCollapseStateForTests() + }) + + it('restores a worktree section after the hook consumer remounts', () => { + renderProbe('wt-a', 'unstaged') + expect(readCollapsed()).toBe('false') + + toggle() + expect(readCollapsed()).toBe('true') + + act(() => root.unmount()) + root = createRoot(container) + renderProbe('wt-a', 'unstaged') + + expect(readCollapsed()).toBe('true') + }) + + it('isolates disclosure choices between worktrees', () => { + renderProbe('wt-a', 'unstaged') + toggle() + expect(readCollapsed()).toBe('true') + + renderProbe('wt-b', 'unstaged') + expect(readCollapsed()).toBe('false') + + renderProbe('wt-a', 'unstaged') + expect(readCollapsed()).toBe('true') + }) + + it('keeps history collapsed by default and drops restored defaults from the cache', () => { + renderProbe('wt-a', 'history') + expect(readCollapsed()).toBe('true') + + toggle() + expect(readCollapsed()).toBe('false') + expect(getSourceControlSectionCollapseStateCountForTests()).toBe(1) + + toggle() + expect(readCollapsed()).toBe('true') + expect(getSourceControlSectionCollapseStateCountForTests()).toBe(0) + }) + + it('bounds non-default worktree state retained by the renderer session', () => { + const newestIndex = MAX_PERSISTED_SOURCE_CONTROL_SECTION_STATES + 24 + for (let index = 0; index <= newestIndex; index++) { + seedSourceControlSectionCollapseStateForTests(`wt-${index}`, new Set(['history', 'unstaged'])) + } + + expect(getSourceControlSectionCollapseStateCountForTests()).toBe( + MAX_PERSISTED_SOURCE_CONTROL_SECTION_STATES + ) + + renderProbe('wt-0', 'unstaged') + expect(readCollapsed()).toBe('false') + renderProbe(`wt-${newestIndex}`, 'unstaged') + expect(readCollapsed()).toBe('true') + }) +}) diff --git a/src/renderer/src/components/right-sidebar/source-control-section-collapse-state.ts b/src/renderer/src/components/right-sidebar/source-control-section-collapse-state.ts new file mode 100644 index 000000000000..d79513836fb9 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/source-control-section-collapse-state.ts @@ -0,0 +1,111 @@ +import { useCallback, useState } from 'react' +import type { SourceControlDisplaySectionId } from './source-control-section-order' + +export type SourceControlCollapsibleSectionId = SourceControlDisplaySectionId | 'branch' | 'history' + +const DEFAULT_COLLAPSED_SECTIONS: ReadonlySet = new Set([ + 'history' +]) + +// Why: Source Control unmounts when another right-sidebar tab is selected. +// Keep disclosure choices in a bounded renderer-session cache so tab and +// worktree round trips restore them without turning transient UI into settings. +export const MAX_PERSISTED_SOURCE_CONTROL_SECTION_STATES = 512 +const collapsedSectionsByWorktreeId = new Map< + string, + ReadonlySet +>() + +function trimPersistedSectionStates(): void { + while (collapsedSectionsByWorktreeId.size > MAX_PERSISTED_SOURCE_CONTROL_SECTION_STATES) { + const oldestWorktreeId = collapsedSectionsByWorktreeId.keys().next().value + if (oldestWorktreeId === undefined) { + break + } + collapsedSectionsByWorktreeId.delete(oldestWorktreeId) + } +} + +function matchesDefaultState( + collapsedSections: ReadonlySet +): boolean { + return ( + collapsedSections.size === DEFAULT_COLLAPSED_SECTIONS.size && + Array.from(DEFAULT_COLLAPSED_SECTIONS).every((section) => collapsedSections.has(section)) + ) +} + +function readCollapsedSections( + worktreeId: string | null +): ReadonlySet { + return worktreeId + ? (collapsedSectionsByWorktreeId.get(worktreeId) ?? DEFAULT_COLLAPSED_SECTIONS) + : DEFAULT_COLLAPSED_SECTIONS +} + +function persistCollapsedSections( + worktreeId: string, + collapsedSections: ReadonlySet +): void { + collapsedSectionsByWorktreeId.delete(worktreeId) + if (matchesDefaultState(collapsedSections)) { + return + } + collapsedSectionsByWorktreeId.set(worktreeId, collapsedSections) + trimPersistedSectionStates() +} + +export type SourceControlSectionCollapseControls = { + collapsedSections: ReadonlySet + toggleSection: (section: SourceControlCollapsibleSectionId) => void +} + +export function useSourceControlSectionCollapseState( + worktreeId: string | null +): SourceControlSectionCollapseControls { + const [rendered, setRendered] = useState<{ + worktreeId: string | null + collapsedSections: ReadonlySet + }>(() => ({ worktreeId, collapsedSections: readCollapsedSections(worktreeId) })) + + // Why: the component stays mounted across worktree switches, so read the + // incoming worktree's cache instead of briefly exposing the previous state. + const collapsedSections = + rendered.worktreeId === worktreeId + ? rendered.collapsedSections + : readCollapsedSections(worktreeId) + + const toggleSection = useCallback( + (section: SourceControlCollapsibleSectionId): void => { + if (!worktreeId) { + return + } + const next = new Set(readCollapsedSections(worktreeId)) + if (next.has(section)) { + next.delete(section) + } else { + next.add(section) + } + persistCollapsedSections(worktreeId, next) + setRendered({ worktreeId, collapsedSections: next }) + }, + [worktreeId] + ) + + return { collapsedSections, toggleSection } +} + +export function clearSourceControlSectionCollapseStateForTests(): void { + collapsedSectionsByWorktreeId.clear() +} + +export function getSourceControlSectionCollapseStateCountForTests(): number { + return collapsedSectionsByWorktreeId.size +} + +export function seedSourceControlSectionCollapseStateForTests( + worktreeId: string, + collapsedSections: ReadonlySet +): void { + persistCollapsedSections(worktreeId, collapsedSections) +} From 8c3bf6aeffebba573fdcb31f51298db843d67cd3 Mon Sep 17 00:00:00 2001 From: just-zzp <264744947+just-zzp@users.noreply.github.com> Date: Sun, 19 Jul 2026 11:20:07 +0900 Subject: [PATCH 2/4] test(source-control): strengthen remount regression --- .../right-sidebar/SourceControl.virtual-file-list.test.tsx | 1 + .../right-sidebar/source-control-section-collapse-state.ts | 5 ++--- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx b/src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx index a4fd9b224bfa..37b71fdcc9f1 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx @@ -371,6 +371,7 @@ describe('SourceControl virtualized changed-files list', () => { const remountedChangesHeader = Array.from(container.querySelectorAll('button')).find((button) => button.textContent?.includes('Changes') ) + expect(remountedChangesHeader).toBeTruthy() act(() => { remountedChangesHeader?.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) diff --git a/src/renderer/src/components/right-sidebar/source-control-section-collapse-state.ts b/src/renderer/src/components/right-sidebar/source-control-section-collapse-state.ts index d79513836fb9..6e13f6e07970 100644 --- a/src/renderer/src/components/right-sidebar/source-control-section-collapse-state.ts +++ b/src/renderer/src/components/right-sidebar/source-control-section-collapse-state.ts @@ -7,9 +7,8 @@ const DEFAULT_COLLAPSED_SECTIONS: ReadonlySet 'history' ]) -// Why: Source Control unmounts when another right-sidebar tab is selected. -// Keep disclosure choices in a bounded renderer-session cache so tab and -// worktree round trips restore them without turning transient UI into settings. +// Why: Source Control unmounts with its sidebar tab, so a bounded session cache restores +// disclosure choices without promoting transient UI state to persistent settings. export const MAX_PERSISTED_SOURCE_CONTROL_SECTION_STATES = 512 const collapsedSectionsByWorktreeId = new Map< string, From c92dafa3ed72f03d7991c1478cb8436003698348 Mon Sep 17 00:00:00 2001 From: Neil Date: Fri, 23 Oct 2026 05:48:38 -0700 Subject: [PATCH 3/4] fix(source-control): preserve section disclosure across panel remounts Adapt just-zzp's #9405 fix to the current panel modules and existing bounded map, with runtime/host/occupant isolation. Part of #9403; Session History remains separate. Co-authored-by: just-zzp <264744947+just-zzp@users.noreply.github.com> --- .../SourceControl.virtual-file-list.test.tsx | 13 +- .../panel/section-collapse-state.test.tsx | 163 ++++++++++++++++++ .../panel/section-collapse-state.ts | 46 +++++ .../source-control/panel/use-panel-state.ts | 1 + .../panel/use-panel-view-state.ts | 34 ++-- 5 files changed, 233 insertions(+), 24 deletions(-) create mode 100644 src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.test.tsx create mode 100644 src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.ts diff --git a/src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx b/src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx index 4d3c172c1ba9..1d49dc920a82 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.virtual-file-list.test.tsx @@ -328,7 +328,7 @@ describe('SourceControl virtualized changed-files list', () => { expect(row('src/file-000.ts')?.className).toContain('bg-accent/60') }) - it('collapses and re-expands a virtualized section', () => { + it('retains a collapsed virtualized section across panel remount', () => { resetState({ gitStatusByWorktree: { [mocks.activeWorktree.id]: manyEntries(500) } }) @@ -346,8 +346,17 @@ describe('SourceControl virtualized changed-files list', () => { expect(mountedRows().length).toBe(0) expect(virtualList()).toBeNull() + act(() => root.unmount()) + root = createRoot(container) + renderSourceControl() + expect(mountedRows().length).toBe(0) + expect(virtualList()).toBeNull() + + const remountedHeader = Array.from(container.querySelectorAll('button')).find((button) => + button.textContent?.includes('Changes') + ) act(() => { - changesHeader?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + remountedHeader?.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) expect(mountedRows().length).toBeGreaterThan(0) expect(mountedRows().length).toBeLessThanOrEqual(MAX_MOUNTED_ROWS) diff --git a/src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.test.tsx b/src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.test.tsx new file mode 100644 index 000000000000..a542fe1ce901 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.test.tsx @@ -0,0 +1,163 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { makeWorktree } from '@/store/slices/worktrees-slice-test-fixtures' +import type { Worktree } from '../../../../../../shared/worktree/types' +import { useSourceControlPanelViewState } from './use-panel-view-state' + +let container: HTMLDivElement +let root: Root +let prefix: string +let nextPrefix = 0 + +function workspace(id: string, overrides: Partial = {}): Worktree { + return makeWorktree({ id: `${prefix}-${id}`, repoId: 'repo', hostId: 'local', ...overrides }) +} + +function Probe({ worktree }: { worktree: Worktree | null }) { + const { collapsedSections, toggleSection } = useSourceControlPanelViewState({ + activeWorktreeId: worktree?.id ?? null, + activeWorktree: worktree, + settings: null, + updateSettings: vi.fn() + }) + return ( + <> + {['unstaged', 'history'].map((section) => ( + + ))} + + ) +} + +function render(worktree: Worktree | null): void { + act(() => root.render()) +} + +function expanded(section = 'unstaged'): string | null { + return ( + container.querySelector(`[data-section="${section}"]`)?.getAttribute('aria-expanded') ?? null + ) +} + +function toggle(section = 'unstaged'): void { + act(() => { + container + .querySelector(`[data-section="${section}"]`) + ?.dispatchEvent(new MouseEvent('click', { bubbles: true })) + }) +} + +function remount(worktree: Worktree | null): void { + act(() => root.unmount()) + root = createRoot(container) + render(worktree) +} + +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + prefix = `section-state-${++nextPrefix}` + container = document.createElement('div') + document.body.appendChild(container) + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) + container.remove() +}) + +describe('Source Control session disclosure choices', () => { + it('restores mixed choices after remount and preserves rapid toggles', () => { + const a = workspace('a') + render(a) + toggle() + toggle('history') + remount(a) + expect(expanded()).toBe('false') + expect(expanded('history')).toBe('true') + act(() => { + toggle() + toggle() + }) + expect(expanded()).toBe('false') + }) + + it('isolates workspaces and restores the original choices on return', () => { + const a = workspace('a') + render(a) + toggle() + render(workspace('b')) + expect(expanded()).toBe('true') + expect(expanded('history')).toBe('false') + render(a) + expect(expanded()).toBe('false') + }) + + it.each([ + { hostId: 'ssh:other' as const }, + { runtimeOwnerEnvironmentId: 'other-runtime' }, + { instanceId: 'replacement' } + ])('isolates the same locator with a different owner or occupant: %j', (replacement) => { + const a = workspace('a', { instanceId: 'original' }) + render(a) + toggle() + render({ ...a, ...replacement }) + expect(expanded()).toBe('true') + render(a) + expect(expanded()).toBe('false') + }) + + it('retains canonical identity across locator changes', () => { + const a = workspace('a', { + identity: { key: `${prefix}-occupant`, executionHostId: 'local', instanceId: 'original' } + }) + render(a) + toggle() + remount({ ...a, id: `${prefix}-renamed` }) + expect(expanded()).toBe('false') + }) + + it('restores defaults and does not persist choices without a workspace', () => { + const a = workspace('a') + render(a) + toggle() + toggle() + remount(a) + expect(expanded()).toBe('true') + expect(expanded('history')).toBe('false') + render(null) + toggle() + expect(expanded()).toBe('true') + }) + + it('evicts old non-default choices while preserving recently visited workspaces', () => { + const first = workspace('first') + const second = workspace('second') + render(first) + toggle() + render(second) + toggle() + for (let index = 0; index < 510; index++) { + render(workspace(`filler-${index}`)) + toggle() + } + render(first) + expect(expanded()).toBe('false') + render(workspace('overflow')) + toggle() + render(second) + expect(expanded()).toBe('true') + render(first) + expect(expanded()).toBe('false') + }) +}) diff --git a/src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.ts b/src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.ts new file mode 100644 index 000000000000..9503b503f460 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.ts @@ -0,0 +1,46 @@ +import { useCallback, useState } from 'react' +import { BoundedMap } from '../../../../../../shared/bounded-map' + +const DEFAULT_COLLAPSED_SECTIONS = new Set(['history']) +const collapsedSectionsByWorkspace = new BoundedMap>({ maxEntries: 512 }) + +function readCollapsedSections(workspaceKey: string | null): Set { + return workspaceKey + ? (collapsedSectionsByWorkspace.get(workspaceKey) ?? DEFAULT_COLLAPSED_SECTIONS) + : DEFAULT_COLLAPSED_SECTIONS +} + +export function useSourceControlSectionCollapseState(workspaceKey: string | null) { + const [rendered, setRendered] = useState(() => ({ + workspaceKey, + collapsedSections: readCollapsedSections(workspaceKey) + })) + const collapsedSections = + rendered.workspaceKey === workspaceKey + ? rendered.collapsedSections + : readCollapsedSections(workspaceKey) + + const toggleSection = useCallback( + (section: string) => { + if (!workspaceKey) { + return + } + const next = new Set(readCollapsedSections(workspaceKey)) + if (next.has(section)) { + next.delete(section) + } else { + next.add(section) + } + // Why: retain only non-default choices across sidebar tab unmounts in this renderer session. + if (next.size === 1 && next.has('history')) { + collapsedSectionsByWorkspace.delete(workspaceKey) + } else { + collapsedSectionsByWorkspace.set(workspaceKey, next) + } + setRendered({ workspaceKey, collapsedSections: next }) + }, + [workspaceKey] + ) + + return { collapsedSections, toggleSection } +} diff --git a/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-state.ts b/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-state.ts index 529b1b524b09..327ff85718c0 100644 --- a/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-state.ts +++ b/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-state.ts @@ -36,6 +36,7 @@ export function useSourceControlPanelState() { }) const viewState = useSourceControlPanelViewState({ activeWorktreeId, + activeWorktree, settings, updateSettings: storeActions.updateSettings }) diff --git a/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-view-state.ts b/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-view-state.ts index 5b46ce01973e..0eb58489de5b 100644 --- a/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-view-state.ts +++ b/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-view-state.ts @@ -1,16 +1,12 @@ import { useCallback, useMemo, useRef, useState } from 'react' +import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity' +import { useSourceControlSectionCollapseState } from './section-collapse-state' import { resolveSourceControlGroupOrder } from '../listing/section-order' import { getNextSourceControlViewMode } from './header-toolbar' import { normalizeSourceControlViewMode } from '../commit/commit-drafts' import type { SourceControlStoreActions } from '../listing/use-store-actions' import type { SourceControlWorktreeContext } from '../listing/use-worktree-context' -const DEFAULT_COLLAPSED_SECTIONS = ['history'] as const - -function createDefaultCollapsedSections(): Set { - return new Set(DEFAULT_COLLAPSED_SECTIONS) -} - /** * Local presentation state for the Source Control panel: filter, collapsed sections/directories, * list-vs-tree mode and the base-ref dialog, plus the per-worktree reset that keeps a worktree @@ -18,10 +14,12 @@ function createDefaultCollapsedSections(): Set { */ export function useSourceControlPanelViewState({ activeWorktreeId, + activeWorktree, settings, updateSettings }: { activeWorktreeId: string | null + activeWorktree: SourceControlWorktreeContext['activeWorktree'] settings: SourceControlWorktreeContext['settings'] updateSettings: SourceControlStoreActions['updateSettings'] }) { @@ -30,9 +28,14 @@ export function useSourceControlPanelViewState({ const [fileListScrollElement, setFileListScrollElement] = useState(null) const isMac = useMemo(() => navigator.userAgent.includes('Mac'), []) const [filterExpanded, setFilterExpanded] = useState(false) - const [collapsedSections, setCollapsedSections] = useState>( - createDefaultCollapsedSections - ) + const sectionStateKey = activeWorktree + ? JSON.stringify([ + activeWorktree.runtimeOwnerEnvironmentId ?? null, + activeWorktree.identity?.key ?? getWorktreeHostIdentity(activeWorktree), + activeWorktree.instanceId ?? null + ]) + : null + const { collapsedSections, toggleSection } = useSourceControlSectionCollapseState(sectionStateKey) const persistedSourceControlViewMode = normalizeSourceControlViewMode( settings?.sourceControlViewMode ) @@ -57,7 +60,6 @@ export function useSourceControlPanelViewState({ if (viewStateWorktreeId !== activeWorktreeId) { setViewStateWorktreeId(activeWorktreeId) setFilterExpanded(false) - setCollapsedSections(createDefaultCollapsedSections()) setCollapsedTreeDirs(new Set()) setBaseRefDialogOpen(false) // Why: don't reset defaultBaseRef here — it's repo-scoped (resolved on activeRepo change); resetting would clobber non-main defaults. @@ -65,18 +67,6 @@ export function useSourceControlPanelViewState({ // Why: don't reset commit-in-flight state — it's per-worktree; resetting would re-enable Commit for an incoming worktree mid-commit. } - const toggleSection = useCallback((section: string) => { - setCollapsedSections((prev) => { - const next = new Set(prev) - if (next.has(section)) { - next.delete(section) - } else { - next.add(section) - } - return next - }) - }, []) - const toggleTreeDir = useCallback((key: string) => { setCollapsedTreeDirs((prev) => { const next = new Set(prev) From 39dd7a464a6876c3d119fcf5f0ada414be7f639e Mon Sep 17 00:00:00 2001 From: Neil Date: Fri, 23 Oct 2026 22:54:30 -0700 Subject: [PATCH 4/4] fix(source-control): key retained disclosure by active worktree id Narrow the remount fix to the existing per-worktree reset: a bounded renderer-session map keyed by activeWorktreeId restores section disclosure after the panel unmounts, while a worktree switch still never inherits another worktree's view. --- .../panel/section-collapse-state.test.tsx | 163 ------------------ .../panel/section-collapse-state.ts | 46 ----- .../source-control/panel/use-panel-state.ts | 1 - .../panel/use-panel-view-state.test.tsx | 63 +++++++ .../panel/use-panel-view-state.ts | 49 ++++-- 5 files changed, 100 insertions(+), 222 deletions(-) delete mode 100644 src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.test.tsx delete mode 100644 src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.ts create mode 100644 src/renderer/src/components/right-sidebar/source-control/panel/use-panel-view-state.test.tsx diff --git a/src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.test.tsx b/src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.test.tsx deleted file mode 100644 index a542fe1ce901..000000000000 --- a/src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.test.tsx +++ /dev/null @@ -1,163 +0,0 @@ -// @vitest-environment happy-dom - -import { act } from 'react' -import { createRoot, type Root } from 'react-dom/client' -import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' -import { makeWorktree } from '@/store/slices/worktrees-slice-test-fixtures' -import type { Worktree } from '../../../../../../shared/worktree/types' -import { useSourceControlPanelViewState } from './use-panel-view-state' - -let container: HTMLDivElement -let root: Root -let prefix: string -let nextPrefix = 0 - -function workspace(id: string, overrides: Partial = {}): Worktree { - return makeWorktree({ id: `${prefix}-${id}`, repoId: 'repo', hostId: 'local', ...overrides }) -} - -function Probe({ worktree }: { worktree: Worktree | null }) { - const { collapsedSections, toggleSection } = useSourceControlPanelViewState({ - activeWorktreeId: worktree?.id ?? null, - activeWorktree: worktree, - settings: null, - updateSettings: vi.fn() - }) - return ( - <> - {['unstaged', 'history'].map((section) => ( - - ))} - - ) -} - -function render(worktree: Worktree | null): void { - act(() => root.render()) -} - -function expanded(section = 'unstaged'): string | null { - return ( - container.querySelector(`[data-section="${section}"]`)?.getAttribute('aria-expanded') ?? null - ) -} - -function toggle(section = 'unstaged'): void { - act(() => { - container - .querySelector(`[data-section="${section}"]`) - ?.dispatchEvent(new MouseEvent('click', { bubbles: true })) - }) -} - -function remount(worktree: Worktree | null): void { - act(() => root.unmount()) - root = createRoot(container) - render(worktree) -} - -beforeEach(() => { - globalThis.IS_REACT_ACT_ENVIRONMENT = true - prefix = `section-state-${++nextPrefix}` - container = document.createElement('div') - document.body.appendChild(container) - root = createRoot(container) -}) - -afterEach(() => { - act(() => root.unmount()) - container.remove() -}) - -describe('Source Control session disclosure choices', () => { - it('restores mixed choices after remount and preserves rapid toggles', () => { - const a = workspace('a') - render(a) - toggle() - toggle('history') - remount(a) - expect(expanded()).toBe('false') - expect(expanded('history')).toBe('true') - act(() => { - toggle() - toggle() - }) - expect(expanded()).toBe('false') - }) - - it('isolates workspaces and restores the original choices on return', () => { - const a = workspace('a') - render(a) - toggle() - render(workspace('b')) - expect(expanded()).toBe('true') - expect(expanded('history')).toBe('false') - render(a) - expect(expanded()).toBe('false') - }) - - it.each([ - { hostId: 'ssh:other' as const }, - { runtimeOwnerEnvironmentId: 'other-runtime' }, - { instanceId: 'replacement' } - ])('isolates the same locator with a different owner or occupant: %j', (replacement) => { - const a = workspace('a', { instanceId: 'original' }) - render(a) - toggle() - render({ ...a, ...replacement }) - expect(expanded()).toBe('true') - render(a) - expect(expanded()).toBe('false') - }) - - it('retains canonical identity across locator changes', () => { - const a = workspace('a', { - identity: { key: `${prefix}-occupant`, executionHostId: 'local', instanceId: 'original' } - }) - render(a) - toggle() - remount({ ...a, id: `${prefix}-renamed` }) - expect(expanded()).toBe('false') - }) - - it('restores defaults and does not persist choices without a workspace', () => { - const a = workspace('a') - render(a) - toggle() - toggle() - remount(a) - expect(expanded()).toBe('true') - expect(expanded('history')).toBe('false') - render(null) - toggle() - expect(expanded()).toBe('true') - }) - - it('evicts old non-default choices while preserving recently visited workspaces', () => { - const first = workspace('first') - const second = workspace('second') - render(first) - toggle() - render(second) - toggle() - for (let index = 0; index < 510; index++) { - render(workspace(`filler-${index}`)) - toggle() - } - render(first) - expect(expanded()).toBe('false') - render(workspace('overflow')) - toggle() - render(second) - expect(expanded()).toBe('true') - render(first) - expect(expanded()).toBe('false') - }) -}) diff --git a/src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.ts b/src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.ts deleted file mode 100644 index 9503b503f460..000000000000 --- a/src/renderer/src/components/right-sidebar/source-control/panel/section-collapse-state.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { useCallback, useState } from 'react' -import { BoundedMap } from '../../../../../../shared/bounded-map' - -const DEFAULT_COLLAPSED_SECTIONS = new Set(['history']) -const collapsedSectionsByWorkspace = new BoundedMap>({ maxEntries: 512 }) - -function readCollapsedSections(workspaceKey: string | null): Set { - return workspaceKey - ? (collapsedSectionsByWorkspace.get(workspaceKey) ?? DEFAULT_COLLAPSED_SECTIONS) - : DEFAULT_COLLAPSED_SECTIONS -} - -export function useSourceControlSectionCollapseState(workspaceKey: string | null) { - const [rendered, setRendered] = useState(() => ({ - workspaceKey, - collapsedSections: readCollapsedSections(workspaceKey) - })) - const collapsedSections = - rendered.workspaceKey === workspaceKey - ? rendered.collapsedSections - : readCollapsedSections(workspaceKey) - - const toggleSection = useCallback( - (section: string) => { - if (!workspaceKey) { - return - } - const next = new Set(readCollapsedSections(workspaceKey)) - if (next.has(section)) { - next.delete(section) - } else { - next.add(section) - } - // Why: retain only non-default choices across sidebar tab unmounts in this renderer session. - if (next.size === 1 && next.has('history')) { - collapsedSectionsByWorkspace.delete(workspaceKey) - } else { - collapsedSectionsByWorkspace.set(workspaceKey, next) - } - setRendered({ workspaceKey, collapsedSections: next }) - }, - [workspaceKey] - ) - - return { collapsedSections, toggleSection } -} diff --git a/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-state.ts b/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-state.ts index 327ff85718c0..529b1b524b09 100644 --- a/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-state.ts +++ b/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-state.ts @@ -36,7 +36,6 @@ export function useSourceControlPanelState() { }) const viewState = useSourceControlPanelViewState({ activeWorktreeId, - activeWorktree, settings, updateSettings: storeActions.updateSettings }) diff --git a/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-view-state.test.tsx b/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-view-state.test.tsx new file mode 100644 index 000000000000..ad3f8ae71118 --- /dev/null +++ b/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-view-state.test.tsx @@ -0,0 +1,63 @@ +// @vitest-environment happy-dom + +import { act } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { useSourceControlPanelViewState } from './use-panel-view-state' + +let container: HTMLDivElement +let root: Root +let toggle: (section: string) => void = () => {} +let collapsed = new Set() + +function Probe({ worktreeId }: { worktreeId: string | null }) { + const viewState = useSourceControlPanelViewState({ + activeWorktreeId: worktreeId, + settings: null, + updateSettings: vi.fn() + }) + toggle = viewState.toggleSection + collapsed = viewState.collapsedSections + return null +} + +function render(worktreeId: string | null): void { + act(() => root.render()) +} + +function remount(worktreeId: string | null): void { + act(() => root.unmount()) + root = createRoot(container) + render(worktreeId) +} + +beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + container = document.createElement('div') + root = createRoot(container) +}) + +afterEach(() => { + act(() => root.unmount()) +}) + +describe('useSourceControlPanelViewState section disclosure', () => { + it('keeps a worktree choice across remount without leaking it to another worktree', () => { + render('wt-a') + act(() => toggle('unstaged')) + act(() => toggle('history')) + expect([...collapsed].sort()).toEqual(['unstaged']) + + remount('wt-a') + expect([...collapsed].sort()).toEqual(['unstaged']) + + render('wt-b') + expect([...collapsed].sort()).toEqual(['history']) + + remount('wt-b') + expect([...collapsed].sort()).toEqual(['history']) + + render('wt-a') + expect([...collapsed].sort()).toEqual(['unstaged']) + }) +}) diff --git a/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-view-state.ts b/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-view-state.ts index 0eb58489de5b..86d25fc7005f 100644 --- a/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-view-state.ts +++ b/src/renderer/src/components/right-sidebar/source-control/panel/use-panel-view-state.ts @@ -1,12 +1,27 @@ import { useCallback, useMemo, useRef, useState } from 'react' -import { getWorktreeHostIdentity } from '../../../../../../shared/worktree/host-qualified-identity' -import { useSourceControlSectionCollapseState } from './section-collapse-state' +import { BoundedMap } from '../../../../../../shared/bounded-map' import { resolveSourceControlGroupOrder } from '../listing/section-order' import { getNextSourceControlViewMode } from './header-toolbar' import { normalizeSourceControlViewMode } from '../commit/commit-drafts' import type { SourceControlStoreActions } from '../listing/use-store-actions' import type { SourceControlWorktreeContext } from '../listing/use-worktree-context' +const DEFAULT_COLLAPSED_SECTIONS = ['history'] as const + +function createDefaultCollapsedSections(): Set { + return new Set(DEFAULT_COLLAPSED_SECTIONS) +} + +// Why: the panel unmounts on sidebar tab switch; retain per-worktree disclosure for this renderer session. +const collapsedSectionsByWorktree = new BoundedMap>({ maxEntries: 512 }) + +function readCollapsedSections(worktreeId: string | null): Set { + return ( + (worktreeId ? collapsedSectionsByWorktree.get(worktreeId) : undefined) ?? + createDefaultCollapsedSections() + ) +} + /** * Local presentation state for the Source Control panel: filter, collapsed sections/directories, * list-vs-tree mode and the base-ref dialog, plus the per-worktree reset that keeps a worktree @@ -14,12 +29,10 @@ import type { SourceControlWorktreeContext } from '../listing/use-worktree-conte */ export function useSourceControlPanelViewState({ activeWorktreeId, - activeWorktree, settings, updateSettings }: { activeWorktreeId: string | null - activeWorktree: SourceControlWorktreeContext['activeWorktree'] settings: SourceControlWorktreeContext['settings'] updateSettings: SourceControlStoreActions['updateSettings'] }) { @@ -28,14 +41,9 @@ export function useSourceControlPanelViewState({ const [fileListScrollElement, setFileListScrollElement] = useState(null) const isMac = useMemo(() => navigator.userAgent.includes('Mac'), []) const [filterExpanded, setFilterExpanded] = useState(false) - const sectionStateKey = activeWorktree - ? JSON.stringify([ - activeWorktree.runtimeOwnerEnvironmentId ?? null, - activeWorktree.identity?.key ?? getWorktreeHostIdentity(activeWorktree), - activeWorktree.instanceId ?? null - ]) - : null - const { collapsedSections, toggleSection } = useSourceControlSectionCollapseState(sectionStateKey) + const [collapsedSections, setCollapsedSections] = useState>(() => + readCollapsedSections(activeWorktreeId) + ) const persistedSourceControlViewMode = normalizeSourceControlViewMode( settings?.sourceControlViewMode ) @@ -60,6 +68,7 @@ export function useSourceControlPanelViewState({ if (viewStateWorktreeId !== activeWorktreeId) { setViewStateWorktreeId(activeWorktreeId) setFilterExpanded(false) + setCollapsedSections(readCollapsedSections(activeWorktreeId)) setCollapsedTreeDirs(new Set()) setBaseRefDialogOpen(false) // Why: don't reset defaultBaseRef here — it's repo-scoped (resolved on activeRepo change); resetting would clobber non-main defaults. @@ -67,6 +76,22 @@ export function useSourceControlPanelViewState({ // Why: don't reset commit-in-flight state — it's per-worktree; resetting would re-enable Commit for an incoming worktree mid-commit. } + const toggleSection = useCallback( + (section: string) => { + const next = new Set(collapsedSections) + if (next.has(section)) { + next.delete(section) + } else { + next.add(section) + } + setCollapsedSections(next) + if (activeWorktreeId) { + collapsedSectionsByWorktree.set(activeWorktreeId, next) + } + }, + [activeWorktreeId, collapsedSections] + ) + const toggleTreeDir = useCallback((key: string) => { setCollapsedTreeDirs((prev) => { const next = new Set(prev)