From 8a8826b2d65827f624dfe769e8cc25c0849c41ab Mon Sep 17 00:00:00 2001 From: Jinjing <6427696+AmethystLiang@users.noreply.github.com> Date: Sun, 5 Apr 2026 11:19:15 -0700 Subject: [PATCH] Cache worktree roots for filesystem auth and UI improvements (#306) * clean-up-repo-local-setup-script - Add authorization cache for worktree roots to improve filesystem read performance - Use ensureAuthorizedRootsCache instead of rebuilding on every list operation - Fix useMemo side effect in WorktreeList by returning sorted IDs directly - Add error display in QuickOpen and FileExplorer for unauthorized paths - Improve section order in SourceControl (unstaged, staged, untracked) - Add keyboard shortcut guard in WorktreeList for arrow keys - Address review findings from code quality checks * fix: update test mocks for filesystem-auth cache integration - filesystem.test.ts: invalidate auth roots cache in beforeEach to prevent stale cache state from leaking between tests - worktrees.test.ts / worktrees-windows.test.ts: add store.getRepos mock return value so rebuildAuthorizedRootsCache can iterate repos - worktrees-windows.test.ts: add third listWorktrees mock for the cache rebuild call consumed during worktrees:create * fix: resolve oxlint errors for max-lines and missing useEffect dependency - Extract repeated worktree mock data into shared variable to reduce worktrees.test.ts below the 300-line limit - Add missing 'toggleSidebar' to useEffect dependency array in App.tsx --- src/main/ipc/filesystem-auth.ts | 94 ++++++++++++++++--- src/main/ipc/filesystem.test.ts | 5 + src/main/ipc/filesystem.ts | 4 +- src/main/ipc/repos.ts | 5 +- src/main/ipc/worktrees-windows.test.ts | 40 ++++---- src/main/ipc/worktrees.test.ts | 91 +++++++++--------- src/main/ipc/worktrees.ts | 12 +++ src/renderer/src/App.tsx | 1 + src/renderer/src/components/QuickOpen.tsx | 12 ++- .../src/components/editor/DiffSectionItem.tsx | 8 +- .../components/right-sidebar/FileExplorer.tsx | 8 ++ .../right-sidebar/SourceControl.tsx | 2 +- .../right-sidebar/useFileExplorerTree.ts | 16 +++- .../src/components/sidebar/WorktreeList.tsx | 46 ++++++++- 14 files changed, 257 insertions(+), 87 deletions(-) diff --git a/src/main/ipc/filesystem-auth.ts b/src/main/ipc/filesystem-auth.ts index 59d629490..bbaab70fa 100644 --- a/src/main/ipc/filesystem-auth.ts +++ b/src/main/ipc/filesystem-auth.ts @@ -7,11 +7,18 @@ export const PATH_ACCESS_DENIED_MESSAGE = 'Access denied: path resolves outside allowed directories. If this blocks a legitimate workflow, please file a GitHub issue.' const authorizedExternalPaths = new Set() +const registeredWorktreeRoots = new Set() +let registeredWorktreeRootsDirty = true +let registeredWorktreeRootsRefresh: Promise | null = null export function authorizeExternalPath(targetPath: string): void { authorizedExternalPaths.add(resolve(targetPath)) } +export function invalidateAuthorizedRootsCache(): void { + registeredWorktreeRootsDirty = true +} + /** * Check whether resolvedTarget is equal to or a descendant of resolvedBase. * Uses relative() so it works with both `/` (Unix) and `\` (Windows) separators. @@ -46,9 +53,53 @@ export function isPathAllowed(targetPath: string, store: Store): boolean { if (authorizedExternalPaths.has(resolvedTarget)) { return true } + for (const authorizedPath of authorizedExternalPaths) { + if (isDescendantOrEqual(resolvedTarget, authorizedPath)) { + return true + } + } return getAllowedRoots(store).some((root) => isDescendantOrEqual(resolvedTarget, root)) } +export async function rebuildAuthorizedRootsCache(store: Store): Promise { + const nextRoots = new Set() + + for (const repo of store.getRepos()) { + try { + nextRoots.add(await normalizeExistingPath(repo.path)) + + const worktrees = await listWorktrees(repo.path) + for (const worktree of worktrees) { + nextRoots.add(await normalizeExistingPath(worktree.path)) + } + } catch (error) { + // Why: a single inaccessible repo (EACCES, EIO, etc.) must not break + // the entire cache rebuild — that would disable File Explorer and + // Quick Open for all other repos. We skip the failing repo and let + // the rest proceed. + console.warn(`[filesystem-auth] skipping repo ${repo.path} during cache rebuild:`, error) + } + } + + registeredWorktreeRoots.clear() + for (const root of nextRoots) { + registeredWorktreeRoots.add(root) + } + registeredWorktreeRootsDirty = false +} + +export async function ensureAuthorizedRootsCache(store: Store): Promise { + if (!registeredWorktreeRootsDirty) { + return + } + if (!registeredWorktreeRootsRefresh) { + registeredWorktreeRootsRefresh = rebuildAuthorizedRootsCache(store).finally(() => { + registeredWorktreeRootsRefresh = null + }) + } + await registeredWorktreeRootsRefresh +} + /** * Returns true if the error is an ENOENT (file-not-found) error. */ @@ -60,13 +111,13 @@ export function isENOENT(error: unknown): boolean { export async function resolveAuthorizedPath(targetPath: string, store: Store): Promise { const resolvedTarget = resolve(targetPath) - if (!isPathAllowed(resolvedTarget, store)) { + if (!(await isPathAllowedIncludingRegisteredWorktrees(resolvedTarget, store))) { throw new Error(PATH_ACCESS_DENIED_MESSAGE) } try { const realTarget = await realpath(resolvedTarget) - if (!isPathAllowed(realTarget, store)) { + if (!(await isPathAllowedIncludingRegisteredWorktrees(realTarget, store))) { throw new Error(PATH_ACCESS_DENIED_MESSAGE) } return realTarget @@ -77,13 +128,35 @@ export async function resolveAuthorizedPath(targetPath: string, store: Store): P const realParent = await realpath(dirname(resolvedTarget)) const candidateTarget = resolve(realParent, basename(resolvedTarget)) - if (!isPathAllowed(candidateTarget, store)) { + if (!(await isPathAllowedIncludingRegisteredWorktrees(candidateTarget, store))) { throw new Error(PATH_ACCESS_DENIED_MESSAGE) } return candidateTarget } } +async function isPathAllowedIncludingRegisteredWorktrees( + targetPath: string, + store: Store +): Promise { + if (isPathAllowed(targetPath, store)) { + return true + } + + await ensureAuthorizedRootsCache(store) + + // Why: external linked worktrees are already trusted for git operations. + // Cache their normalized roots once and reuse that index so quick-open and + // file explorer do not spawn `git worktree list` on every filesystem read. + for (const root of registeredWorktreeRoots) { + if (isDescendantOrEqual(targetPath, root)) { + return true + } + } + + return false +} + async function normalizeExistingPath(targetPath: string): Promise { try { return await realpath(targetPath) @@ -119,20 +192,11 @@ export async function resolveRegisteredWorktreePath( // symlinks). const normalizedTarget = await normalizeExistingPath(resolvedTarget) - for (const repo of store.getRepos()) { - const normalizedRepoPath = await normalizeExistingPath(repo.path) - - if (normalizedTarget === normalizedRepoPath) { + await ensureAuthorizedRootsCache(store) + for (const root of registeredWorktreeRoots) { + if (normalizedTarget === root) { return normalizedTarget } - - const worktrees = await listWorktrees(repo.path) - for (const worktree of worktrees) { - const normalizedWorktreePath = await normalizeExistingPath(worktree.path) - if (normalizedTarget === normalizedWorktreePath) { - return normalizedTarget - } - } } throw new Error('Access denied: unknown repository or worktree path') diff --git a/src/main/ipc/filesystem.test.ts b/src/main/ipc/filesystem.test.ts index 921ce6e82..08e86590d 100644 --- a/src/main/ipc/filesystem.test.ts +++ b/src/main/ipc/filesystem.test.ts @@ -70,6 +70,7 @@ vi.mock('../git/worktree', () => ({ })) import { registerFilesystemHandlers } from './filesystem' +import { invalidateAuthorizedRootsCache } from './filesystem-auth' describe('registerFilesystemHandlers', () => { const store = { @@ -114,6 +115,10 @@ describe('registerFilesystemHandlers', () => { handlers.set(channel, handler) }) + // Reset module-level auth cache so each test starts with a fresh dirty + // flag — prevents stale worktree data from a prior test's cache rebuild. + invalidateAuthorizedRootsCache() + realpathMock.mockImplementation(async (targetPath: string) => targetPath) listWorktreesMock.mockResolvedValue([ { diff --git a/src/main/ipc/filesystem.ts b/src/main/ipc/filesystem.ts index d0d85ad04..f1a88e221 100644 --- a/src/main/ipc/filesystem.ts +++ b/src/main/ipc/filesystem.ts @@ -32,7 +32,8 @@ import { resolveRegisteredWorktreePath, validateGitRelativeFilePath, isENOENT, - authorizeExternalPath + authorizeExternalPath, + rebuildAuthorizedRootsCache } from './filesystem-auth' import { listQuickOpenFiles } from './filesystem-list-files' import { registerFilesystemMutationHandlers } from './filesystem-mutations' @@ -73,6 +74,7 @@ function isBinaryBuffer(buffer: Buffer): boolean { } export function registerFilesystemHandlers(store: Store): void { + void rebuildAuthorizedRootsCache(store) const activeTextSearches = new Map>() // ─── Filesystem ───────────────────────────────────────── diff --git a/src/main/ipc/repos.ts b/src/main/ipc/repos.ts index ef6fc1e6c..4026fe356 100644 --- a/src/main/ipc/repos.ts +++ b/src/main/ipc/repos.ts @@ -4,6 +4,7 @@ import { randomUUID } from 'crypto' import type { Store } from '../persistence' import type { Repo } from '../../shared/types' import { REPO_COLORS } from '../../shared/constants' +import { rebuildAuthorizedRootsCache } from './filesystem-auth' import { isGitRepo, getGitUsername, @@ -48,12 +49,14 @@ export function registerRepoHandlers(mainWindow: BrowserWindow, store: Store): v } store.addRepo(repo) + await rebuildAuthorizedRootsCache(store) notifyReposChanged(mainWindow) return repo }) - ipcMain.handle('repos:remove', (_event, args: { repoId: string }) => { + ipcMain.handle('repos:remove', async (_event, args: { repoId: string }) => { store.removeRepo(args.repoId) + await rebuildAuthorizedRootsCache(store) notifyReposChanged(mainWindow) }) diff --git a/src/main/ipc/worktrees-windows.test.ts b/src/main/ipc/worktrees-windows.test.ts index 466088f31..24046938f 100644 --- a/src/main/ipc/worktrees-windows.test.ts +++ b/src/main/ipc/worktrees-windows.test.ts @@ -134,6 +134,15 @@ describe('registerWorktreeHandlers – Windows path handling', () => { handlers[channel] = handler }) + store.getRepos.mockReturnValue([ + { + id: 'repo-1', + path: 'C:\\repo', + displayName: 'repo', + badgeColor: '#000', + addedAt: 0 + } + ]) store.getRepo.mockReturnValue({ id: 'repo-1', path: 'C:\\repo', @@ -200,25 +209,20 @@ describe('registerWorktreeHandlers – Windows path handling', () => { }) it('preserves create-time metadata on the next list when Windows path formatting differs', async () => { + const worktreeEntry = { + path: 'C:/workspaces/improve-dashboard', + head: 'abc123', + branch: 'refs/heads/improve-dashboard', + isBare: false, + isMainWorktree: false + } + // Three calls: (1) worktrees:create finds the new worktree, + // (2) rebuildAuthorizedRootsCache enumerates worktrees for the repo, + // (3) worktrees:list enumerates worktrees again. listWorktreesMock - .mockResolvedValueOnce([ - { - path: 'C:/workspaces/improve-dashboard', - head: 'abc123', - branch: 'refs/heads/improve-dashboard', - isBare: false, - isMainWorktree: false - } - ]) - .mockResolvedValueOnce([ - { - path: 'C:/workspaces/improve-dashboard', - head: 'abc123', - branch: 'refs/heads/improve-dashboard', - isBare: false, - isMainWorktree: false - } - ]) + .mockResolvedValueOnce([worktreeEntry]) + .mockResolvedValueOnce([worktreeEntry]) + .mockResolvedValueOnce([worktreeEntry]) store.setWorktreeMeta.mockReturnValue({ lastActivityAt: 123, displayName: 'Improve Dashboard' diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index 890b28a5b..26faf9b07 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -101,30 +101,34 @@ describe('registerWorktreeHandlers', () => { } beforeEach(() => { - handleMock.mockReset() - removeHandlerMock.mockReset() - listWorktreesMock.mockReset() - addWorktreeMock.mockReset() - removeWorktreeMock.mockReset() - getGitUsernameMock.mockReset() - getDefaultBaseRefMock.mockReset() - getBranchConflictKindMock.mockReset() - getPRForBranchMock.mockReset() - getEffectiveHooksMock.mockReset() - createSetupRunnerScriptMock.mockReset() - shouldRunSetupForCreateMock.mockReset() - runHookMock.mockReset() - hasHooksFileMock.mockReset() - loadHooksMock.mockReset() - computeWorktreePathMock.mockReset() - ensurePathWithinWorkspaceMock.mockReset() - mainWindow.webContents.send.mockReset() - store.getRepos.mockReset() - store.getRepo.mockReset() - store.getSettings.mockReset() - store.getWorktreeMeta.mockReset() - store.setWorktreeMeta.mockReset() - store.removeWorktreeMeta.mockReset() + for (const m of [ + handleMock, + removeHandlerMock, + listWorktreesMock, + addWorktreeMock, + removeWorktreeMock, + getGitUsernameMock, + getDefaultBaseRefMock, + getBranchConflictKindMock, + getPRForBranchMock, + getEffectiveHooksMock, + createSetupRunnerScriptMock, + shouldRunSetupForCreateMock, + runHookMock, + hasHooksFileMock, + loadHooksMock, + computeWorktreePathMock, + ensurePathWithinWorkspaceMock, + mainWindow.webContents.send, + store.getRepos, + store.getRepo, + store.getSettings, + store.getWorktreeMeta, + store.setWorktreeMeta, + store.removeWorktreeMeta + ]) { + m.mockReset() + } for (const key of Object.keys(handlers)) { delete handlers[key] @@ -134,14 +138,15 @@ describe('registerWorktreeHandlers', () => { handlers[channel] = handler }) - store.getRepo.mockReturnValue({ + const repo = { id: 'repo-1', path: '/workspace/repo', displayName: 'repo', badgeColor: '#000', - addedAt: 0, - worktreeBaseRef: null - }) + addedAt: 0 + } + store.getRepos.mockReturnValue([repo]) + store.getRepo.mockReturnValue({ ...repo, worktreeBaseRef: null }) store.getSettings.mockReturnValue({ branchPrefix: 'none', nestWorkspaces: false, @@ -224,16 +229,18 @@ describe('registerWorktreeHandlers', () => { expect(addWorktreeMock).not.toHaveBeenCalled() }) + const createdWorktreeList = [ + { + path: '/workspace/improve-dashboard', + head: 'abc123', + branch: 'improve-dashboard', + isBare: false, + isMainWorktree: false + } + ] + it('returns a setup launch payload when setup should run', async () => { - listWorktreesMock.mockResolvedValue([ - { - path: '/workspace/improve-dashboard', - head: 'abc123', - branch: 'improve-dashboard', - isBare: false, - isMainWorktree: false - } - ]) + listWorktreesMock.mockResolvedValue(createdWorktreeList) getEffectiveHooksMock.mockReturnValue({ scripts: { setup: 'pnpm worktree:setup' @@ -269,15 +276,7 @@ describe('registerWorktreeHandlers', () => { }) it('still returns the created worktree when setup runner generation fails', async () => { - listWorktreesMock.mockResolvedValue([ - { - path: '/workspace/improve-dashboard', - head: 'abc123', - branch: 'improve-dashboard', - isBare: false, - isMainWorktree: false - } - ]) + listWorktreesMock.mockResolvedValue(createdWorktreeList) getEffectiveHooksMock.mockReturnValue({ scripts: { setup: 'pnpm worktree:setup' diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 380a01b96..b3122c9b0 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -32,6 +32,7 @@ import { formatWorktreeRemovalError, isOrphanedWorktreeError } from './worktree-logic' +import { rebuildAuthorizedRootsCache, ensureAuthorizedRootsCache } from './filesystem-auth' export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store): void { // Remove any previously registered handlers so we can re-register them @@ -44,6 +45,10 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store ipcMain.removeHandler('hooks:check') ipcMain.handle('worktrees:listAll', async () => { + // Why: use ensureAuthorizedRootsCache (not rebuild) to avoid redundantly + // listing git worktrees when the cache is already fresh — the handler + // itself calls listWorktrees for every repo below. + await ensureAuthorizedRootsCache(store) const repos = store.getRepos() const allWorktrees: Worktree[] = [] @@ -60,6 +65,10 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store }) ipcMain.handle('worktrees:list', async (_event, args: { repoId: string }) => { + // Why: use ensureAuthorizedRootsCache (not rebuild) to avoid redundantly + // listing git worktrees when the cache is already fresh — the handler + // itself calls listWorktrees below. + await ensureAuthorizedRootsCache(store) const repo = store.getRepo(args.repoId) if (!repo) { return [] @@ -160,6 +169,7 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store } const meta = store.setWorktreeMeta(worktreeId, metaUpdates) const worktree = mergeWorktree(repo.id, created, meta) + await rebuildAuthorizedRootsCache(store) let setup: CreateWorktreeResult['setup'] if (setupScript && shouldLaunchSetup) { @@ -213,12 +223,14 @@ export function registerWorktreeHandlers(mainWindow: BrowserWindow, store: Store console.warn(`[worktrees] Orphaned worktree detected at ${worktreePath}, cleaning up`) await rm(worktreePath, { recursive: true, force: true }).catch(() => {}) store.removeWorktreeMeta(args.worktreeId) + await rebuildAuthorizedRootsCache(store) notifyWorktreesChanged(mainWindow, repoId) return } throw new Error(formatWorktreeRemovalError(error, worktreePath, args.force ?? false)) } store.removeWorktreeMeta(args.worktreeId) + await rebuildAuthorizedRootsCache(store) notifyWorktreesChanged(mainWindow, repoId) } diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index 4565cdedf..db7b63743 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -381,6 +381,7 @@ function App(): React.JSX.Element { activeWorktreeId, openModal, repos.length, + toggleSidebar, setRightSidebarTab, setRightSidebarOpen, setQuickOpenVisible diff --git a/src/renderer/src/components/QuickOpen.tsx b/src/renderer/src/components/QuickOpen.tsx index d6a5f32cc..599ff3852 100644 --- a/src/renderer/src/components/QuickOpen.tsx +++ b/src/renderer/src/components/QuickOpen.tsx @@ -55,6 +55,7 @@ export default function QuickOpen(): React.JSX.Element | null { const [files, setFiles] = useState([]) const [selectedIndex, setSelectedIndex] = useState(0) const [loading, setLoading] = useState(false) + const [loadError, setLoadError] = useState(null) const inputRef = useRef(null) const listRef = useRef(null) @@ -88,6 +89,7 @@ export default function QuickOpen(): React.JSX.Element | null { setQuery('') setSelectedIndex(0) setFiles([]) + setLoadError(null) setLoading(true) void window.api.fs @@ -97,9 +99,12 @@ export default function QuickOpen(): React.JSX.Element | null { setFiles(result) } }) - .catch(() => { + .catch((error) => { if (!cancelled) { setFiles([]) + // Why: treating list-files failures as "no matches" hides the real + // cause when the active worktree path is unauthorized or stale. + setLoadError(error instanceof Error ? error.message : String(error)) } }) .finally(() => { @@ -232,6 +237,11 @@ export default function QuickOpen(): React.JSX.Element | null { Loading files... )} + {!loading && loadError && ( +
+ Could not load files: {loadError} +
+ )} {filtered.length === 0 && query.trim() && (
No matching files diff --git a/src/renderer/src/components/editor/DiffSectionItem.tsx b/src/renderer/src/components/editor/DiffSectionItem.tsx index c463db7a2..225ab68c5 100644 --- a/src/renderer/src/components/editor/DiffSectionItem.tsx +++ b/src/renderer/src/components/editor/DiffSectionItem.tsx @@ -19,7 +19,13 @@ function computeLineStats( original: string, modified: string, status: string -): { added: number; removed: number } { +): { added: number; removed: number } | null { + // Why: for very large files (e.g. package-lock.json), splitting and + // iterating synchronously in the React render cycle would block the + // main thread and freeze the UI. Return null to skip stats display. + if (original.length + modified.length > 500_000) { + return null + } if (status === 'added') { return { added: modified ? modified.split('\n').length : 0, removed: 0 } } diff --git a/src/renderer/src/components/right-sidebar/FileExplorer.tsx b/src/renderer/src/components/right-sidebar/FileExplorer.tsx index de2701f84..7cce65451 100644 --- a/src/renderer/src/components/right-sidebar/FileExplorer.tsx +++ b/src/renderer/src/components/right-sidebar/FileExplorer.tsx @@ -47,6 +47,7 @@ export default function FileExplorer(): React.JSX.Element { flatRows, rowsByPath, rootCache, + rootError, loadDir, refreshTree, refreshDir, @@ -267,6 +268,13 @@ export default function FileExplorer(): React.JSX.Element {
) } + if (rootError) { + return ( +
+ Could not load files for this worktree: {rootError} +
+ ) + } return (
No files in this worktree diff --git a/src/renderer/src/components/right-sidebar/SourceControl.tsx b/src/renderer/src/components/right-sidebar/SourceControl.tsx index 9c4d3fe7d..bd1500830 100644 --- a/src/renderer/src/components/right-sidebar/SourceControl.tsx +++ b/src/renderer/src/components/right-sidebar/SourceControl.tsx @@ -71,7 +71,7 @@ const STATUS_ICONS: Record< // are assigned area:'unstaged' by the parser — appear above "Staged Changes". // This keeps unresolved conflicts visible at the top of the list where the // user won't miss them. -const SECTION_ORDER = ['untracked', 'unstaged', 'staged'] as const +const SECTION_ORDER = ['unstaged', 'staged', 'untracked'] as const const SECTION_LABELS: Record<(typeof SECTION_ORDER)[number], string> = { staged: 'Staged Changes', unstaged: 'Changes', diff --git a/src/renderer/src/components/right-sidebar/useFileExplorerTree.ts b/src/renderer/src/components/right-sidebar/useFileExplorerTree.ts index 41628b050..d2b7be5aa 100644 --- a/src/renderer/src/components/right-sidebar/useFileExplorerTree.ts +++ b/src/renderer/src/components/right-sidebar/useFileExplorerTree.ts @@ -9,6 +9,7 @@ type UseFileExplorerTreeResult = { flatRows: TreeNode[] rowsByPath: Map rootCache: DirCache | undefined + rootError: string | null loadDir: (dirPath: string, depth: number, options?: { force?: boolean }) => Promise refreshTree: () => Promise refreshDir: (dirPath: string) => Promise @@ -20,6 +21,7 @@ export function useFileExplorerTree( expanded: Set ): UseFileExplorerTreeResult { const [dirCache, setDirCache] = useState>({}) + const [rootError, setRootError] = useState(null) const dirCacheRef = useRef(dirCache) dirCacheRef.current = dirCache @@ -38,6 +40,9 @@ export function useFileExplorerTree( })) try { const entries = await window.api.fs.readDir({ dirPath }) + if (depth === -1) { + setRootError(null) + } const children: TreeNode[] = entries .filter(shouldIncludeFileExplorerEntry) .map((entry) => ({ @@ -50,7 +55,14 @@ export function useFileExplorerTree( depth: depth + 1 })) setDirCache((prev) => ({ ...prev, [dirPath]: { children, loading: false } })) - } catch { + } catch (error) { + if (depth === -1) { + // Why: the old implementation collapsed root read failures into an + // empty tree, which made authorization/path bugs look like a real + // empty worktree. Preserve the message so the UI can distinguish + // "no files" from "could not read this worktree". + setRootError(error instanceof Error ? error.message : String(error)) + } setDirCache((prev) => ({ ...prev, [dirPath]: { children: [], loading: false } })) } }, @@ -111,6 +123,7 @@ export function useFileExplorerTree( const resetAndLoad = useCallback(() => { setDirCache({}) + setRootError(null) if (worktreePath) { void loadDir(worktreePath, -1, { force: true }) } @@ -121,6 +134,7 @@ export function useFileExplorerTree( flatRows, rowsByPath, rootCache, + rootError, loadDir, refreshTree, refreshDir, diff --git a/src/renderer/src/components/sidebar/WorktreeList.tsx b/src/renderer/src/components/sidebar/WorktreeList.tsx index 9af27a26d..2883fa7fc 100644 --- a/src/renderer/src/components/sidebar/WorktreeList.tsx +++ b/src/renderer/src/components/sidebar/WorktreeList.tsx @@ -36,6 +36,7 @@ const WorktreeList = React.memo(function WorktreeList() { groupBy === 'pr-status' || sortBy === 'recent' ? s.prCache : null ) + const sortEpoch = useAppStore((s) => s.sortEpoch) const scrollRef = useRef(null) const repoMap = useMemo(() => { @@ -46,7 +47,32 @@ const WorktreeList = React.memo(function WorktreeList() { return m }, [repos]) - // Flatten and filter the current live worktree data first. + // ── Stable sort order ────────────────────────────────────────── + // The sort order is cached and only recomputed when `sortEpoch` changes + // (worktree add/remove, terminal activity, backend refresh, etc.). + // Selection-triggered side-effects (clearing isUnread, GitHub refresh) + // do NOT bump sortEpoch, so clicking a card never reorders the list. + // + // Why useMemo instead of useEffect: the sort order must be computed + // synchronously *before* the worktrees memo reads it, otherwise the + // first render (and epoch bumps) would use stale/empty data from the ref. + const sortedIds = useMemo(() => { + const state = useAppStore.getState() + const allWorktrees: Worktree[] = Object.values(state.worktreesByRepo) + .flat() + .filter((w) => !w.isArchived) + const currentRepoMap = new Map(state.repos.map((r) => [r.id, r])) + const currentTabs = state.tabsByWorktree + allWorktrees.sort( + buildWorktreeComparator(sortBy, currentTabs, currentRepoMap, state.prCache, Date.now()) + ) + return allWorktrees.map((w) => w.id) + // sortEpoch is an intentional trigger: it's not read inside the memo, but + // its change signals that the sort order should be recomputed. + // oxlint-disable-next-line react-hooks/exhaustive-deps + }, [sortEpoch, sortBy, prCache]) + + // Flatten, filter, and apply stable sort order const visibleWorktrees = useMemo(() => { let all: Worktree[] = Object.values(worktreesByRepo).flat() @@ -78,8 +104,18 @@ const WorktreeList = React.memo(function WorktreeList() { }) } + // Apply cached sort order. Items not yet in the cache (e.g. brand-new + // worktrees before the next sortEpoch bump) are appended at the end. + const orderIndex = new Map(sortedIds.map((id, i) => [id, i])) + all.sort((a, b) => { + const ai = orderIndex.get(a.id) ?? Infinity + const bi = orderIndex.get(b.id) ?? Infinity + return ai - bi + }) + + return all - }, [worktreesByRepo, filterRepoIds, searchQuery, showActiveOnly, repoMap, tabsByWorktree]) + }, [worktreesByRepo, filterRepoIds, searchQuery, showActiveOnly, repoMap, tabsByWorktree, sortedIds]) const latestRecentSortInputsRef = useRef>({}) const frozenActiveRecentSortRef = useRef<{ @@ -275,6 +311,12 @@ const WorktreeList = React.memo(function WorktreeList() { const handleContainerKeyDown = useCallback( (e: React.KeyboardEvent) => { if (e.key === 'ArrowUp' || e.key === 'ArrowDown') { + // Why: only capture bare arrow keys when the list container itself is + // focused. If focus is on an inner input or button, arrow keys should + // perform their native function (e.g. cursor movement in text fields). + if (e.target !== e.currentTarget) { + return + } navigateWorktree(e.key === 'ArrowUp' ? 'up' : 'down') e.preventDefault() } else if (e.key === 'Enter') {