From bd2d29babbb2e9875fa0aea16193f672f7a64197 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Mon, 16 Nov 2026 23:56:21 -0800 Subject: [PATCH] perf(worktrees): read the index replacement list for folder children; split folder-lineage tests --- .../pinned-display-name-apply.test.ts | 366 +----------------- ...pinned-display-name-folder-lineage.test.ts | 342 ++++++++++++++++ .../pinned-display-name-test-fixtures.ts | 94 +++++ .../listing/worktree-catalog-index.ts | 30 +- .../metadata/cross-store-lineage-parents.ts | 6 +- 5 files changed, 473 insertions(+), 365 deletions(-) create mode 100644 src/renderer/src/hooks/ipc-events/pinned-display-name-folder-lineage.test.ts create mode 100644 src/renderer/src/hooks/ipc-events/pinned-display-name-test-fixtures.ts diff --git a/src/renderer/src/hooks/ipc-events/pinned-display-name-apply.test.ts b/src/renderer/src/hooks/ipc-events/pinned-display-name-apply.test.ts index bc208bc6005..d62cf550263 100644 --- a/src/renderer/src/hooks/ipc-events/pinned-display-name-apply.test.ts +++ b/src/renderer/src/hooks/ipc-events/pinned-display-name-apply.test.ts @@ -2,10 +2,8 @@ import { describe, expect, it, vi } from 'vitest' import type { Repo } from '../../../../shared/repository/repo-types' -import type { Tab } from '../../../../shared/workspace-layout/tab-groups/tab-types' import type { Worktree } from '../../../../shared/worktree/types' import { useAppStore } from '@/store/index' -import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host/execution-host' import { renderHook } from '@testing-library/react' import { getIndexedAllWorktrees, @@ -21,16 +19,6 @@ import { useWorktreeMap } from '@/store/slices/worktrees/listing/use-worktree-catalog' import type { WorktreeLineage } from '../../../../shared/worktree/lineage-types' -import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' -import { - folderWorkspaceKey, - worktreeWorkspaceKey -} from '../../../../shared/workspace/identity/workspace-scope' -import { - selectCrossStoreFolderChildrenById, - selectSidebarLineageParentIdentities -} from '@/store/slices/worktrees/metadata/cross-store-lineage-parents' -import { OWN_LINEAGE_STORE_KEY } from '../../../../shared/worktree/lineage/cross-store-lineage-resolution' import { getWorktreeHostIdentity } from '../../../../shared/worktree/host-qualified-identity' import { getCyclicProjectedWorktreeLineageIds, @@ -44,6 +32,15 @@ import type * as ChatTabName from '@/runtime/native-chat/naming/structured-chat- import { getLineageAncestorIndex } from '@/components/sidebar/worktree-list/listing/visible-worktree-indexes' import { applyLocalPinnedDisplayName } from './pinned-display-name-apply' +import { + CHAT_TABS, + TITLE, + chatTab, + countIterations, + repo, + row +} from './pinned-display-name-test-fixtures' + vi.mock('@/runtime/native-chat/naming/structured-chat-tab-name', async (importOriginal) => { const actual = await importOriginal() return { ...actual, resolveStructuredChatTabName: vi.fn(actual.resolveStructuredChatTabName) } @@ -54,92 +51,6 @@ vi.mock('@/components/workspace-surface-projection', async (importOriginal) => { return { ...actual, projectWorkspaceSurfaces: vi.fn(actual.projectWorkspaceSurfaces) } }) -const TITLE = 'Triage assigned issues prs' - -function folderWorkspace(id: string): FolderWorkspace { - return { - id, - projectGroupId: 'group-1', - name: 'Folder', - folderPath: '/folder', - linkedTask: null, - comment: '', - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - createdAt: 0, - updatedAt: 0 - } -} -const CHAT_TABS = 100 - -/** Counts full walks of an index, which is how a copy reads it. */ -function countIterations(target: Map | Worktree[]): () => number { - let walks = 0 - const iterate = target[Symbol.iterator].bind(target) - Object.defineProperty(target, Symbol.iterator, { - configurable: true, - value: () => { - walks++ - return iterate() - } - }) - return () => walks -} - -function repo(id: string): Repo { - return { id, path: '/work', displayName: id, badgeColor: '#000000', addedAt: 0 } -} - -function chatTab(worktreeId: string, index: number): Tab { - return { - id: `chat-${index}`, - entityId: `chat-${index}`, - groupId: `group-${index}`, - worktreeId, - contentType: 'agent-session', - agentSessionAgent: 'claude', - label: `Chat ${index}`, - customLabel: null, - color: null, - sortOrder: index, - createdAt: 0 - } -} - -function row(size: number, index: number, isArchived: boolean, onRead: () => void): Worktree { - const worktree: Worktree = { - id: `repo-${size}::/work/w${index}`, - repoId: `repo-${size}`, - path: `/work/w${index}`, - head: 'aaa', - branch: `refs/heads/w${index}`, - isBare: false, - isMainWorktree: false, - displayName: index === 0 ? 'batfish-2' : `w${index}`, - comment: '', - linkedIssue: null, - linkedPR: null, - linkedLinearIssue: null, - isArchived, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - instanceId: `instance-${size}-${index}` - } - Object.defineProperty(worktree, 'isArchived', { - enumerable: true, - get: () => { - onRead() - return isArchived - } - }) - return worktree -} - describe('applyLocalPinnedDisplayName', () => { it.each([750, 7500])('pins one title among %i rows without rescanning the catalog', (size) => { let otherReads = 0 @@ -459,102 +370,6 @@ describe('applyLocalPinnedDisplayName', () => { terminal.unmount() }) - it.each([750, 7500])('a title pin re-reads no row for folder parents among %i rows', (size) => { - let lineageReads = 0 - const rows = Array.from({ length: size }, (_, index) => { - const worktree = row(size + 1, index, false, () => {}) - // Row 0 is renamed; count only the other rows' folder-lineage reads. - Object.defineProperty(worktree, 'workspaceLineage', { - get: () => { - if (index !== 0) { - lineageReads++ - } - return undefined - } - }) - return worktree - }) - const repoId = `repo-${size + 1}` - const folder: FolderWorkspace = { - id: 'folder-1', - projectGroupId: 'group-1', - name: 'Folder', - folderPath: '/folder', - linkedTask: null, - comment: '', - isArchived: false, - isUnread: false, - isPinned: false, - sortOrder: 0, - lastActivityAt: 0, - createdAt: 0, - updatedAt: 0 - } - useAppStore.setState({ - repos: [repo(repoId)], - worktreesByRepo: { [repoId]: rows }, - detectedWorktreesByRepo: {}, - folderWorkspaces: [folder], - workspaceLineageByChildKey: {}, - crossStoreLineageByStoreKey: {}, - worktreeLineageById: {} - }) - expect(selectSidebarLineageParentIdentities(useAppStore.getState())).toBeUndefined() - lineageReads = 0 - - applyLocalPinnedDisplayName({ worktreeId: rows[0].id, displayName: TITLE }) - expect(selectSidebarLineageParentIdentities(useAppStore.getState())).toBeUndefined() - expect(lineageReads).toBe(0) - - // A row that now carries a folder parent must not keep the cached undefined. - const withFolderParent = { - ...rows[5], - workspaceLineage: { - parentWorkspaceKey: folderWorkspaceKey('folder-1'), - parentInstanceId: null, - childInstanceId: `instance-${size + 1}-5` - } - } - const pinnedRows = useAppStore.getState().worktreesByRepo[repoId] - useAppStore.setState({ - worktreesByRepo: { - [repoId]: [...pinnedRows.slice(0, 5), withFolderParent, ...pinnedRows.slice(6)] - } - }) - const parents = selectSidebarLineageParentIdentities(useAppStore.getState()) - expect(parents?.has(getWorktreeHostIdentity(withFolderParent))).toBe(true) - }) - - it('re-resolves folder parents when only the runtime owner changes', () => { - const child: Worktree = { ...row(18, 0, false, () => {}), repoId: 'repo-18' } - const withFolderParent = { - ...child, - workspaceLineage: { - parentWorkspaceKey: folderWorkspaceKey('folder-1'), - parentInstanceId: null, - childInstanceId: 'instance-18-0' - } - } - useAppStore.setState({ - repos: [repo('repo-18')], - worktreesByRepo: { 'repo-18': [withFolderParent] }, - detectedWorktreesByRepo: {}, - folderWorkspaces: [folderWorkspace('folder-1')], - workspaceLineageByChildKey: {}, - crossStoreLineageByStoreKey: {}, - worktreeLineageById: {} - }) - const identity = getWorktreeHostIdentity(withFolderParent) - expect(selectSidebarLineageParentIdentities(useAppStore.getState())?.has(identity)).toBe(true) - - const runtimeOwned = { ...withFolderParent, runtimeOwnerEnvironmentId: 'env-1' } - useAppStore.setState({ worktreesByRepo: { 'repo-18': [runtimeOwned] } }) - // A cold resolution files the row under env-1's store, where folder-1 is not listed. - expect( - selectSidebarLineageParentIdentities(useAppStore.getState())?.has(identity) ?? false - ).toBe(false) - }) - it('keeps the winning copy in the lineage index when a discarded copy moves', () => { const rows = Array.from({ length: 4 }, (_, index) => row(17, index, false, () => {})) const winner: Worktree = { ...rows[0] } @@ -609,101 +424,6 @@ describe('applyLocalPinnedDisplayName', () => { ).toBe('instance-current') }) - it('re-resolves parents when only a row inline lineage moves', () => { - const [a, b, c] = Array.from({ length: 3 }, (_, index) => row(20, index, false, () => {})) - const inlineLineage = (parent: Worktree): WorktreeLineage => ({ - worktreeId: c.id, - worktreeInstanceId: 'instance-20-2', - parentWorktreeId: parent.id, - parentWorktreeInstanceId: parent.instanceId ?? '', - origin: 'manual', - capture: { source: 'manual-action', confidence: 'explicit' }, - createdAt: 0 - }) - // A real folder edge on A keeps the selector resolving instead of returning undefined. - const aInFolder = { - ...a, - workspaceLineage: { - parentWorkspaceKey: folderWorkspaceKey('folder-1'), - parentInstanceId: null, - childInstanceId: 'instance-20-0' - } - } - const cUnderA = { ...c, lineage: inlineLineage(a) } - useAppStore.setState({ - repos: [repo('repo-20')], - worktreesByRepo: { 'repo-20': [aInFolder, b, cUnderA] }, - detectedWorktreesByRepo: {}, - folderWorkspaces: [folderWorkspace('folder-1')], - workspaceLineageByChildKey: {}, - crossStoreLineageByStoreKey: {}, - worktreeLineageById: {} - }) - const cIdentity = getWorktreeHostIdentity(c) - expect(selectSidebarLineageParentIdentities(useAppStore.getState())?.get(cIdentity)).toBe( - getWorktreeHostIdentity(a) - ) - - const cUnderB = { ...cUnderA, lineage: inlineLineage(b) } - useAppStore.setState({ worktreesByRepo: { 'repo-20': [aInFolder, b, cUnderB] } }) - expect(selectSidebarLineageParentIdentities(useAppStore.getState())?.get(cIdentity)).toBe( - getWorktreeHostIdentity(b) - ) - }) - - it.each([750, 7500])('a title pin resolves no folder children among %i rows', (size) => { - let hostReads = 0 - const rows = Array.from({ length: size }, (_, index) => { - const worktree = row(size + 2, index, false, () => {}) - // Row 0 is renamed; count only the other rows' host reads, which resolution does per row. - Object.defineProperty(worktree, 'hostId', { - get: () => { - if (index !== 0) { - hostReads++ - } - return undefined - } - }) - return worktree - }) - const repoId = `repo-${size + 2}` - // A saved edge to a folder in a store that is not available resolves to no child. - const childKey = worktreeWorkspaceKey(rows[5].id) - useAppStore.setState({ - repos: [repo(repoId)], - worktreesByRepo: { [repoId]: rows }, - detectedWorktreesByRepo: {}, - folderWorkspaces: [folderWorkspace('folder-1')], - workspaceLineageByChildKey: {}, - worktreeLineageById: {}, - crossStoreLineageByStoreKey: { - [OWN_LINEAGE_STORE_KEY]: { - [childKey]: { - childWorkspaceKey: childKey, - childInstanceId: `instance-${size + 2}-5`, - parent: { - installationId: 'unavailable-store', - workspaceKey: folderWorkspaceKey('folder-1'), - instanceId: 'folder-1' - }, - origin: 'manual', - capture: { source: 'manual-action', confidence: 'explicit' }, - createdAt: 0 - } - } - } - }) - const warm = selectCrossStoreFolderChildrenById(useAppStore.getState()) - expect(warm.size).toBe(0) - // The cold resolution does read every other row. - expect(hostReads).toBeGreaterThanOrEqual(size - 1) - hostReads = 0 - - applyLocalPinnedDisplayName({ worktreeId: rows[0].id, displayName: TITLE }) - expect(selectCrossStoreFolderChildrenById(useAppStore.getState())).toBe(warm) - expect(hostReads).toBe(0) - }) - it.each([750, 7500])( 'a title pin reuses the hidden-project ancestor map among %i rows', (size) => { @@ -748,72 +468,4 @@ describe('applyLocalPinnedDisplayName', () => { expect(ancestorWalks()).toBe(0) } ) - - it.each([750, 7500])('an unrelated rename keeps %i resolved folder children', (size) => { - let childHostReads = 0 - const children = Array.from({ length: size }, (_, index) => { - const child = row(size + 4, index, false, () => {}) - Object.defineProperty(child, 'hostId', { - enumerable: true, - get: () => { - childHostReads++ - return LOCAL_EXECUTION_HOST_ID - } - }) - return child - }) - const unrelated: Worktree = { - ...row(size + 5, 0, false, () => {}), - hostId: LOCAL_EXECUTION_HOST_ID - } - const childRepoId = `repo-${size + 4}` - const localRepoId = `repo-${size + 5}` - const records = Object.fromEntries( - children.map((child, index) => { - const childKey = worktreeWorkspaceKey(child.id) - return [ - childKey, - { - childWorkspaceKey: childKey, - childInstanceId: `instance-${size + 4}-${index}`, - parent: { - installationId: 'own-install', - workspaceKey: folderWorkspaceKey('folder-1'), - instanceId: 'folder-1' - }, - origin: 'manual', - capture: { source: 'manual-action', confidence: 'explicit' }, - createdAt: 0 - } - ] - }) - ) - useAppStore.setState({ - repos: [repo(childRepoId), repo(localRepoId)], - worktreesByRepo: { [childRepoId]: children, [localRepoId]: [unrelated] }, - detectedWorktreesByRepo: {}, - folderWorkspaces: [folderWorkspace('folder-1')], - workspaceLineageByChildKey: {}, - worktreeLineageById: {}, - ownLineageInstallationId: 'own-install', - crossStoreLineageByStoreKey: { [OWN_LINEAGE_STORE_KEY]: records } - }) - const warm = selectCrossStoreFolderChildrenById(useAppStore.getState()) - expect(warm.get('folder-1')).toHaveLength(size) - childHostReads = 0 - - for (const title of ['Unrelated one', 'Unrelated two']) { - applyLocalPinnedDisplayName({ worktreeId: unrelated.id, displayName: title }) - expect(selectCrossStoreFolderChildrenById(useAppStore.getState())).toBe(warm) - } - expect(childHostReads).toBe(0) - - // Retitling a child returns a new map with that child's title; the others stay the same rows. - applyLocalPinnedDisplayName({ worktreeId: children[0].id, displayName: TITLE }) - const retitled = selectCrossStoreFolderChildrenById(useAppStore.getState()) - expect(retitled).not.toBe(warm) - const folderChildren = retitled.get('folder-1') ?? [] - expect(folderChildren.find(({ id }) => id === children[0].id)?.displayName).toBe(TITLE) - expect(folderChildren.find(({ id }) => id === children[1].id)).toBe(children[1]) - }) }) diff --git a/src/renderer/src/hooks/ipc-events/pinned-display-name-folder-lineage.test.ts b/src/renderer/src/hooks/ipc-events/pinned-display-name-folder-lineage.test.ts new file mode 100644 index 00000000000..82062b5cb1d --- /dev/null +++ b/src/renderer/src/hooks/ipc-events/pinned-display-name-folder-lineage.test.ts @@ -0,0 +1,342 @@ +// @vitest-environment happy-dom + +import { describe, expect, it, vi } from 'vitest' +import type { Worktree } from '../../../../shared/worktree/types' +import { useAppStore } from '@/store/index' +import { LOCAL_EXECUTION_HOST_ID } from '../../../../shared/execution-host/execution-host' +import { getIndexedWorktreeMap } from '@/store/slices/worktrees/listing/worktree-catalog-index' +import { replacedWorktreeRows } from '@/store/slices/worktrees/listing/worktree-catalog-membership' +import type * as CatalogMembership from '@/store/slices/worktrees/listing/worktree-catalog-membership' +import type { WorktreeLineage } from '../../../../shared/worktree/lineage-types' +import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' +import { + folderWorkspaceKey, + worktreeWorkspaceKey +} from '../../../../shared/workspace/identity/workspace-scope' +import { + selectCrossStoreFolderChildrenById, + selectSidebarLineageParentIdentities +} from '@/store/slices/worktrees/metadata/cross-store-lineage-parents' +import { OWN_LINEAGE_STORE_KEY } from '../../../../shared/worktree/lineage/cross-store-lineage-resolution' +import { getWorktreeHostIdentity } from '../../../../shared/worktree/host-qualified-identity' +import { applyLocalPinnedDisplayName } from './pinned-display-name-apply' + +import { TITLE, folderWorkspace, repo, row } from './pinned-display-name-test-fixtures' + +vi.mock('@/store/slices/worktrees/listing/worktree-catalog-membership', async (importOriginal) => { + const actual = await importOriginal() + return { ...actual, replacedWorktreeRows: vi.fn(actual.replacedWorktreeRows) } +}) + +describe('applyLocalPinnedDisplayName folder lineage', () => { + it.each([750, 7500])('a title pin re-reads no row for folder parents among %i rows', (size) => { + let lineageReads = 0 + const rows = Array.from({ length: size }, (_, index) => { + const worktree = row(size + 1, index, false, () => {}) + // Row 0 is renamed; count only the other rows' folder-lineage reads. + Object.defineProperty(worktree, 'workspaceLineage', { + get: () => { + if (index !== 0) { + lineageReads++ + } + return undefined + } + }) + return worktree + }) + const repoId = `repo-${size + 1}` + const folder: FolderWorkspace = { + id: 'folder-1', + projectGroupId: 'group-1', + name: 'Folder', + folderPath: '/folder', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + createdAt: 0, + updatedAt: 0 + } + useAppStore.setState({ + repos: [repo(repoId)], + worktreesByRepo: { [repoId]: rows }, + detectedWorktreesByRepo: {}, + folderWorkspaces: [folder], + workspaceLineageByChildKey: {}, + crossStoreLineageByStoreKey: {}, + worktreeLineageById: {} + }) + expect(selectSidebarLineageParentIdentities(useAppStore.getState())).toBeUndefined() + lineageReads = 0 + + applyLocalPinnedDisplayName({ worktreeId: rows[0].id, displayName: TITLE }) + expect(selectSidebarLineageParentIdentities(useAppStore.getState())).toBeUndefined() + expect(lineageReads).toBe(0) + + // A row that now carries a folder parent must not keep the cached undefined. + const withFolderParent = { + ...rows[5], + workspaceLineage: { + parentWorkspaceKey: folderWorkspaceKey('folder-1'), + parentInstanceId: null, + childInstanceId: `instance-${size + 1}-5` + } + } + const pinnedRows = useAppStore.getState().worktreesByRepo[repoId] + useAppStore.setState({ + worktreesByRepo: { + [repoId]: [...pinnedRows.slice(0, 5), withFolderParent, ...pinnedRows.slice(6)] + } + }) + const parents = selectSidebarLineageParentIdentities(useAppStore.getState()) + expect(parents?.has(getWorktreeHostIdentity(withFolderParent))).toBe(true) + }) + + it('re-resolves folder parents when only the runtime owner changes', () => { + const child: Worktree = { ...row(18, 0, false, () => {}), repoId: 'repo-18' } + const withFolderParent = { + ...child, + workspaceLineage: { + parentWorkspaceKey: folderWorkspaceKey('folder-1'), + parentInstanceId: null, + childInstanceId: 'instance-18-0' + } + } + useAppStore.setState({ + repos: [repo('repo-18')], + worktreesByRepo: { 'repo-18': [withFolderParent] }, + detectedWorktreesByRepo: {}, + folderWorkspaces: [folderWorkspace('folder-1')], + workspaceLineageByChildKey: {}, + crossStoreLineageByStoreKey: {}, + worktreeLineageById: {} + }) + const identity = getWorktreeHostIdentity(withFolderParent) + expect(selectSidebarLineageParentIdentities(useAppStore.getState())?.has(identity)).toBe(true) + + const runtimeOwned = { ...withFolderParent, runtimeOwnerEnvironmentId: 'env-1' } + useAppStore.setState({ worktreesByRepo: { 'repo-18': [runtimeOwned] } }) + // A cold resolution files the row under env-1's store, where folder-1 is not listed. + expect( + selectSidebarLineageParentIdentities(useAppStore.getState())?.has(identity) ?? false + ).toBe(false) + }) + + it('re-resolves parents when only a row inline lineage moves', () => { + const [a, b, c] = Array.from({ length: 3 }, (_, index) => row(20, index, false, () => {})) + const inlineLineage = (parent: Worktree): WorktreeLineage => ({ + worktreeId: c.id, + worktreeInstanceId: 'instance-20-2', + parentWorktreeId: parent.id, + parentWorktreeInstanceId: parent.instanceId ?? '', + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 0 + }) + // A real folder edge on A keeps the selector resolving instead of returning undefined. + const aInFolder = { + ...a, + workspaceLineage: { + parentWorkspaceKey: folderWorkspaceKey('folder-1'), + parentInstanceId: null, + childInstanceId: 'instance-20-0' + } + } + const cUnderA = { ...c, lineage: inlineLineage(a) } + useAppStore.setState({ + repos: [repo('repo-20')], + worktreesByRepo: { 'repo-20': [aInFolder, b, cUnderA] }, + detectedWorktreesByRepo: {}, + folderWorkspaces: [folderWorkspace('folder-1')], + workspaceLineageByChildKey: {}, + crossStoreLineageByStoreKey: {}, + worktreeLineageById: {} + }) + const cIdentity = getWorktreeHostIdentity(c) + expect(selectSidebarLineageParentIdentities(useAppStore.getState())?.get(cIdentity)).toBe( + getWorktreeHostIdentity(a) + ) + + const cUnderB = { ...cUnderA, lineage: inlineLineage(b) } + useAppStore.setState({ worktreesByRepo: { 'repo-20': [aInFolder, b, cUnderB] } }) + expect(selectSidebarLineageParentIdentities(useAppStore.getState())?.get(cIdentity)).toBe( + getWorktreeHostIdentity(b) + ) + }) + + it.each([750, 7500])('a title pin resolves no folder children among %i rows', (size) => { + let hostReads = 0 + const rows = Array.from({ length: size }, (_, index) => { + const worktree = row(size + 2, index, false, () => {}) + // Row 0 is renamed; count only the other rows' host reads, which resolution does per row. + Object.defineProperty(worktree, 'hostId', { + get: () => { + if (index !== 0) { + hostReads++ + } + return undefined + } + }) + return worktree + }) + const repoId = `repo-${size + 2}` + // A saved edge to a folder in a store that is not available resolves to no child. + const childKey = worktreeWorkspaceKey(rows[5].id) + useAppStore.setState({ + repos: [repo(repoId)], + worktreesByRepo: { [repoId]: rows }, + detectedWorktreesByRepo: {}, + folderWorkspaces: [folderWorkspace('folder-1')], + workspaceLineageByChildKey: {}, + worktreeLineageById: {}, + crossStoreLineageByStoreKey: { + [OWN_LINEAGE_STORE_KEY]: { + [childKey]: { + childWorkspaceKey: childKey, + childInstanceId: `instance-${size + 2}-5`, + parent: { + installationId: 'unavailable-store', + workspaceKey: folderWorkspaceKey('folder-1'), + instanceId: 'folder-1' + }, + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 0 + } + } + } + }) + const warm = selectCrossStoreFolderChildrenById(useAppStore.getState()) + expect(warm.size).toBe(0) + // The cold resolution does read every other row. + expect(hostReads).toBeGreaterThanOrEqual(size - 1) + hostReads = 0 + + applyLocalPinnedDisplayName({ worktreeId: rows[0].id, displayName: TITLE }) + expect(selectCrossStoreFolderChildrenById(useAppStore.getState())).toBe(warm) + expect(hostReads).toBe(0) + }) + + it.each([750, 7500])('an unrelated rename keeps %i resolved folder children', (size) => { + let childHostReads = 0 + const children = Array.from({ length: size }, (_, index) => { + const child = row(size + 4, index, false, () => {}) + Object.defineProperty(child, 'hostId', { + enumerable: true, + get: () => { + childHostReads++ + return LOCAL_EXECUTION_HOST_ID + } + }) + return child + }) + const unrelated: Worktree = { + ...row(size + 5, 0, false, () => {}), + hostId: LOCAL_EXECUTION_HOST_ID + } + const childRepoId = `repo-${size + 4}` + const localRepoId = `repo-${size + 5}` + const records = Object.fromEntries( + children.map((child, index) => { + const childKey = worktreeWorkspaceKey(child.id) + return [ + childKey, + { + childWorkspaceKey: childKey, + childInstanceId: `instance-${size + 4}-${index}`, + parent: { + installationId: 'own-install', + workspaceKey: folderWorkspaceKey('folder-1'), + instanceId: 'folder-1' + }, + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 0 + } + ] + }) + ) + useAppStore.setState({ + repos: [repo(childRepoId), repo(localRepoId)], + worktreesByRepo: { [childRepoId]: children, [localRepoId]: [unrelated] }, + detectedWorktreesByRepo: {}, + folderWorkspaces: [folderWorkspace('folder-1')], + workspaceLineageByChildKey: {}, + worktreeLineageById: {}, + ownLineageInstallationId: 'own-install', + crossStoreLineageByStoreKey: { [OWN_LINEAGE_STORE_KEY]: records } + }) + const warm = selectCrossStoreFolderChildrenById(useAppStore.getState()) + expect(warm.get('folder-1')).toHaveLength(size) + childHostReads = 0 + + for (const title of ['Unrelated one', 'Unrelated two']) { + applyLocalPinnedDisplayName({ worktreeId: unrelated.id, displayName: title }) + expect(selectCrossStoreFolderChildrenById(useAppStore.getState())).toBe(warm) + } + expect(childHostReads).toBe(0) + + // Retitling a child returns a new map with that child's title; the others stay the same rows. + applyLocalPinnedDisplayName({ worktreeId: children[0].id, displayName: TITLE }) + const retitled = selectCrossStoreFolderChildrenById(useAppStore.getState()) + expect(retitled).not.toBe(warm) + const folderChildren = retitled.get('folder-1') ?? [] + expect(folderChildren.find(({ id }) => id === children[0].id)?.displayName).toBe(TITLE) + expect(folderChildren.find(({ id }) => id === children[1].id)).toBe(children[1]) + }) + + it.each([750, 7500])( + 'folder children reuse the index replacement list beside %i local rows', + (size) => { + const child: Worktree = { + ...row(size + 6, 0, false, () => {}), + hostId: LOCAL_EXECUTION_HOST_ID + } + const localRows = Array.from({ length: size }, (_, index) => + row(size + 7, index, false, () => {}) + ) + const childKey = worktreeWorkspaceKey(child.id) + const localRepoId = `repo-${size + 7}` + useAppStore.setState({ + repos: [repo(`repo-${size + 6}`), repo(localRepoId)], + worktreesByRepo: { [`repo-${size + 6}`]: [child], [localRepoId]: localRows }, + detectedWorktreesByRepo: {}, + folderWorkspaces: [folderWorkspace('folder-1')], + workspaceLineageByChildKey: {}, + worktreeLineageById: {}, + ownLineageInstallationId: 'own-install', + crossStoreLineageByStoreKey: { + [OWN_LINEAGE_STORE_KEY]: { + [childKey]: { + childWorkspaceKey: childKey, + childInstanceId: `instance-${size + 6}-0`, + parent: { + installationId: 'own-install', + workspaceKey: folderWorkspaceKey('folder-1'), + instanceId: 'folder-1' + }, + origin: 'manual', + capture: { source: 'manual-action', confidence: 'explicit' }, + createdAt: 0 + } + } + } + }) + const warm = selectCrossStoreFolderChildrenById(useAppStore.getState()) + expect(warm.get('folder-1')).toEqual([child]) + const slotWalks = vi.mocked(replacedWorktreeRows) + + for (const title of ['Local one', 'Local two']) { + applyLocalPinnedDisplayName({ worktreeId: localRows[3].id, displayName: title }) + // The shared index walks this write once; the selector must not walk it again. + getIndexedWorktreeMap(useAppStore.getState().worktreesByRepo) + slotWalks.mockClear() + expect(selectCrossStoreFolderChildrenById(useAppStore.getState())).toBe(warm) + expect(slotWalks).toHaveBeenCalledTimes(0) + } + } + ) +}) diff --git a/src/renderer/src/hooks/ipc-events/pinned-display-name-test-fixtures.ts b/src/renderer/src/hooks/ipc-events/pinned-display-name-test-fixtures.ts new file mode 100644 index 00000000000..d56c4db6c16 --- /dev/null +++ b/src/renderer/src/hooks/ipc-events/pinned-display-name-test-fixtures.ts @@ -0,0 +1,94 @@ +import type { FolderWorkspace } from '../../../../shared/folder-workspaces/folder-workspace-types' +import type { Repo } from '../../../../shared/repository/repo-types' +import type { Tab } from '../../../../shared/workspace-layout/tab-groups/tab-types' +import type { Worktree } from '../../../../shared/worktree/types' +export const TITLE = 'Triage assigned issues prs' + +export function folderWorkspace(id: string): FolderWorkspace { + return { + id, + projectGroupId: 'group-1', + name: 'Folder', + folderPath: '/folder', + linkedTask: null, + comment: '', + isArchived: false, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + createdAt: 0, + updatedAt: 0 + } +} +export const CHAT_TABS = 100 + +/** Counts full walks of an index, which is how a copy reads it. */ +export function countIterations(target: Map | Worktree[]): () => number { + let walks = 0 + const iterate = target[Symbol.iterator].bind(target) + Object.defineProperty(target, Symbol.iterator, { + configurable: true, + value: () => { + walks++ + return iterate() + } + }) + return () => walks +} + +export function repo(id: string): Repo { + return { id, path: '/work', displayName: id, badgeColor: '#000000', addedAt: 0 } +} + +export function chatTab(worktreeId: string, index: number): Tab { + return { + id: `chat-${index}`, + entityId: `chat-${index}`, + groupId: `group-${index}`, + worktreeId, + contentType: 'agent-session', + agentSessionAgent: 'claude', + label: `Chat ${index}`, + customLabel: null, + color: null, + sortOrder: index, + createdAt: 0 + } +} + +export function row( + size: number, + index: number, + isArchived: boolean, + onRead: () => void +): Worktree { + const worktree: Worktree = { + id: `repo-${size}::/work/w${index}`, + repoId: `repo-${size}`, + path: `/work/w${index}`, + head: 'aaa', + branch: `refs/heads/w${index}`, + isBare: false, + isMainWorktree: false, + displayName: index === 0 ? 'batfish-2' : `w${index}`, + comment: '', + linkedIssue: null, + linkedPR: null, + linkedLinearIssue: null, + isArchived, + isUnread: false, + isPinned: false, + sortOrder: 0, + lastActivityAt: 0, + instanceId: `instance-${size}-${index}` + } + Object.defineProperty(worktree, 'isArchived', { + enumerable: true, + get: () => { + onRead() + return isArchived + } + }) + return worktree +} diff --git a/src/renderer/src/store/slices/worktrees/listing/worktree-catalog-index.ts b/src/renderer/src/store/slices/worktrees/listing/worktree-catalog-index.ts index 6790e1df8a2..e9d06ac7e5c 100644 --- a/src/renderer/src/store/slices/worktrees/listing/worktree-catalog-index.ts +++ b/src/renderer/src/store/slices/worktrees/listing/worktree-catalog-index.ts @@ -43,6 +43,8 @@ type WorktreeSnapshot = WorktreeOverlay & { allWorktrees: Worktree[] | null /** Same object while no replacement could change lineage resolution; selectors key caches on it. */ lineageKey: WorktreeLineageKey + /** This write's replaced rows and the catalog they replaced; absent after a rebuild or compaction. */ + replacement?: { from: WeakRef; rows: readonly ReplacedWorktreeRow[] } } const EMPTY_OVERLAY: WorktreeOverlay = { @@ -73,7 +75,7 @@ function getWorktreeSnapshot(worktreesByRepo: AppState['worktreesByRepo']): Work const replaced = previousRows && replacedWorktreeRows(worktreesByRepo, previousRows) const snapshot = previousSnapshot && replaced - ? overlayWorktreeSnapshot(previousSnapshot, replaced, worktreesByRepo) + ? overlayWorktreeSnapshot(previousSnapshot, replaced, worktreesByRepo, previousRows) : viewOf(buildWorktreeSnapshot(worktreesByRepo), EMPTY_OVERLAY, null) worktreeSnapshotCache.set(worktreesByRepo, snapshot) lastIndexedRows = new WeakRef(worktreesByRepo) @@ -105,7 +107,8 @@ function viewOf( function overlayWorktreeSnapshot( previous: WorktreeSnapshot, replaced: readonly ReplacedWorktreeRow[], - worktreesByRepo: AppState['worktreesByRepo'] + worktreesByRepo: AppState['worktreesByRepo'], + previousRows: AppState['worktreesByRepo'] ): WorktreeSnapshot { if (replaced.length === 0) { return previous @@ -155,9 +158,14 @@ function overlayWorktreeSnapshot( ? previous.lineageKey : null // Compaction rebuilds the title catalog; with no structure moved, surfaces keep the same topology. - return rows.size > MAX_OVERLAY_ROWS - ? viewOf(buildWorktreeSnapshot(worktreesByRepo), EMPTY_OVERLAY, topology, lineageKey) - : viewOf(base, { rows, slots, firstById, byId, structureById }, topology, lineageKey) + if (rows.size > MAX_OVERLAY_ROWS) { + return viewOf(buildWorktreeSnapshot(worktreesByRepo), EMPTY_OVERLAY, topology, lineageKey) + } + return { + ...viewOf(base, { rows, slots, firstById, byId, structureById }, topology, lineageKey), + // Weak so this catalog never keeps the one it replaced alive. + replacement: { from: new WeakRef(previousRows), rows: replaced } + } } function rowsOf(snapshot: WorktreeSnapshot): Worktree[] { @@ -211,6 +219,18 @@ export function getWorktreeLineageKey( return getWorktreeSnapshot(worktreesByRepo).lineageKey } +/** The rows `next` replaced in `previous`, when `next` was indexed as an overlay of exactly that catalog; null asks the caller to refresh. */ +export function getIndexedReplacedRows( + next: AppState['worktreesByRepo'], + previous: AppState['worktreesByRepo'] +): readonly ReplacedWorktreeRow[] | null { + const snapshot = getWorktreeSnapshot(next) + if (worktreeSnapshotCache.get(previous) === snapshot) { + return [] + } + return snapshot.replacement?.from.deref() === previous ? snapshot.replacement.rows : null +} + /** Structural id map for paths, lineage, and cycles; a title write keeps its identity, so its rows may carry an older title. */ export function getIndexedWorktreeTopology( worktreesByRepo: AppState['worktreesByRepo'] diff --git a/src/renderer/src/store/slices/worktrees/metadata/cross-store-lineage-parents.ts b/src/renderer/src/store/slices/worktrees/metadata/cross-store-lineage-parents.ts index 2b587095a84..b6e20229583 100644 --- a/src/renderer/src/store/slices/worktrees/metadata/cross-store-lineage-parents.ts +++ b/src/renderer/src/store/slices/worktrees/metadata/cross-store-lineage-parents.ts @@ -18,6 +18,7 @@ import { } from '../../../../../../shared/worktree/lineage/folder-lineage-parents' import { getIndexedAllWorktrees, + getIndexedReplacedRows, getIndexedWorktreesById, getWorktreeLineageKey } from '../listing/worktree-catalog-index' @@ -26,7 +27,6 @@ import { selectWorktreesByRepo } from '../../../workspaces/catalog/workspace-record-fields' import type { AppState } from '../../../types' -import { replacedWorktreeRows } from '../listing/worktree-catalog-membership' type CrossStoreLineageInputs = Pick< AppState, @@ -219,8 +219,8 @@ export function selectCrossStoreFolderChildrenById( if (previous.catalog === worktreesByRepo) { return previous.result } - // Only the replaced rows are read; a write that touches no child keeps the returned children. - const replaced = replacedWorktreeRows(worktreesByRepo, previous.catalog) + // The index already listed this write's replaced rows; a write that touches no child keeps the children. + const replaced = getIndexedReplacedRows(worktreesByRepo, previous.catalog) const childIdentities = childIdentitiesOfRefs.get(refs) if ( replaced &&