From cb6da1cdd76da966765037fc896426a071a96183 Mon Sep 17 00:00:00 2001 From: ZinChl <123862319+ZinChl@users.noreply.github.com> Date: Tue, 29 Sep 2026 17:04:42 +0800 Subject: [PATCH] =?UTF-8?q?fix(files):=20=E6=90=9C=E7=B4=A2=E7=BB=93?= =?UTF-8?q?=E6=9E=9C=E9=87=8C=E7=9A=84=E7=9B=AE=E5=BD=95=E8=A1=8C=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E5=AF=BC=E8=88=AA=E6=96=87=E4=BB=B6=E6=A0=91=EF=BC=8C?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E5=BD=93=E6=96=87=E4=BB=B6=E6=89=93=E5=BC=80?= =?UTF-8?q?=20(#801)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 根因:`fs.search` 有意把目录名也算命中(「提示命中项所在的目录」),而搜索面板把 `matches` 里每一行都当成文件交给 `onOpenFile` → `fs.read`。宿主 `readText` 对目录 显式抛 `"" is a directory`(src/index.ts:197),于是点目录名必然报红。 改动: - `src/fs-search.ts`:结果新增 `dirs`(`matches` 里属于目录的子集,同种相对 '/'-分隔形式)。目录判定跟随符号链接(`stat`),与文件树行、`fs.read` 的 行为一致;悬空链接退回普通条目。 - `src/client/TreePanel.tsx`:目录行画文件夹字形(`data-dsh-search-dir`)并改为 **在树里展开该目录及其祖先**(`onToggle` 是翻转,故只碰折叠中的路径),同时清空 搜索框让树成为下一步看到的界面;文件行行为不变。 - `src/client/state.ts`:把 `revealPaths` 里的祖先目录推导抽成可复用的 `ancestorDirs(cwd, files)`(行为不变,UNC / Windows 前缀逻辑单点维护);顺带修掉 该注释里一个损坏的 `→` 字节。 - `src/client/sidebar.module.css`:结果行改 flex 并给目录行加令牌色,省略号移到 标签节点上(视觉对文件行不变,`tests/theme.spec.ts` 仍绿)。 验证: - `tests/fs-search.spec.ts`:`dirs` 上报 + 符号链接按目标分类(含悬空链接)。 - `tests/file-tree-search-persist.spec.tsx`:新增三条 jsdom 用例——目录命中只导航 不调 `onOpenFile`、嵌套命中只展开折叠祖先(已展开的父级不会被翻回去)、文件命中 仍走 `onOpenFile` 且保留结果列表。**回退 TreePanel.tsx 后前两条即红**(已实测)。 - `tests/state.spec.ts`:`ancestorDirs` 的 POSIX / 盘符 / UNC / 去重与过滤用例。 - `make check` 全绿:typecheck → lint → build → 137 文件 1498 用例 → check:consumer-types。 --- src/client/TreePanel.tsx | 54 ++++++++++++++----- src/client/api.ts | 6 ++- src/client/sidebar.module.css | 15 +++++- src/client/state.ts | 49 ++++++++++------- src/fs-search.ts | 43 ++++++++++++--- tests/file-tree-search-persist.spec.tsx | 72 +++++++++++++++++++++++-- tests/fs-search.spec.ts | 36 ++++++++++--- tests/state.spec.ts | 23 +++++++- 8 files changed, 246 insertions(+), 52 deletions(-) diff --git a/src/client/TreePanel.tsx b/src/client/TreePanel.tsx index 343877eb..64acbd8f 100644 --- a/src/client/TreePanel.tsx +++ b/src/client/TreePanel.tsx @@ -23,6 +23,7 @@ import clsx from 'clsx' import { IconFolderOpenRegular, IconRefreshOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import { api } from './api.ts' import type { BetterSidebarService } from './service.ts' +import { ancestorDirs } from './state.ts' import { FileTree } from './FileTree.tsx' import { IconUploadOutline16 } from './icons.tsx' import type { OpenInApp } from './open-in-app.ts' @@ -93,7 +94,7 @@ export function TreePanel(props: { onReferenceFile, onPathRenamed, onPathDeleted, visible, full, service, } = props const [query, setQuery] = useState('') - const [results, setResults] = useState<{ matches: string[]; truncated: boolean } | null>(null) + const [results, setResults] = useState<{ matches: string[]; dirs: string[]; truncated: boolean } | null>(null) const [error, setError] = useState(null) const [refreshTick, setRefreshTick] = useState(0) @@ -195,6 +196,27 @@ export function TreePanel(props: { }, [sessionId, cwd, needle]) const busy = upload !== null + /** Directory hits (the host reports them separately): a click navigates the + * tree for those rows instead of opening them as files. */ + const dirHits = new Set(results?.dirs) + + /** + * Jump to a DIRECTORY hit in the tree. Results include directories (they + * show where matches live) and `fs.read` refuses one, so opening such a row + * as a file surfaced a bare `"…" is a directory` error. Expand the folder + * and its ancestors instead — `onToggle` FLIPS a row, so only collapsed + * paths are touched — and clear the query so the tree, not the parked + * results panel, is what the user sees next. + */ + const openSearchDir = (rel: string): void => { + const target = resolveSidebarPath(cwd, rel) + if (cwd !== undefined) { + for (const path of [...ancestorDirs(cwd, [target]), target]) { + if (!expanded.includes(path)) onToggle(path) + } + } + setQuery('') + } return (
@@ -262,17 +284,25 @@ export function TreePanel(props: { {error === null && results !== null && results.matches.length === 0 && (
{t('editorSearchNoResults')}
)} - {error === null && results !== null && results.matches.map(rel => ( - - ))} + {error === null && results !== null && results.matches.map((rel) => { + const isDirHit = dirHits.has(rel) + return ( + + ) + })} {error === null && results?.truncated === true && (
{t('editorSearchTruncated')}
)} diff --git a/src/client/api.ts b/src/client/api.ts index 236fbef5..4bb3cd56 100644 --- a/src/client/api.ts +++ b/src/client/api.ts @@ -291,9 +291,11 @@ export const api = { fsTrees: (scope: SessionScope, paths: readonly string[], signal?: AbortSignal) => call<{ levels: FsLevel[] }>('fs.trees', scopePayload(scope, { paths: [...paths] }), signal), /** Global recursive file-name search rooted at the session cwd (the editor - * side panel's search box); matches are cwd-relative '/'-separated paths. */ + * side panel's search box); matches are cwd-relative '/'-separated paths, + * and `dirs` names the subset that is a directory (the list navigates the + * tree for those — `fs.read` refuses a directory). */ fsSearch: (scope: SessionScope, query: string, signal?: AbortSignal) => - call<{ matches: string[]; truncated: boolean }>('fs.search', scopePayload(scope, { query }), signal), + call<{ matches: string[]; dirs: string[]; truncated: boolean }>('fs.search', scopePayload(scope, { query }), signal), fsRead: (scope: SessionScope, path: string, signal?: AbortSignal) => call('fs.read', scopePayload(scope, { path }), signal), fsWrite: (scope: SessionScope, path: string, content: string) => diff --git a/src/client/sidebar.module.css b/src/client/sidebar.module.css index c39f86d6..fcb99b5f 100644 --- a/src/client/sidebar.module.css +++ b/src/client/sidebar.module.css @@ -1341,7 +1341,9 @@ body[data-dsh-sidebar-dragging] .bottomPanel { } .editorSearchResult { - display: block; + display: flex; + align-items: center; + gap: 6px; box-sizing: border-box; width: 100%; height: 28px; @@ -1355,6 +1357,17 @@ body[data-dsh-sidebar-dragging] .bottomPanel { text-align: left; cursor: pointer; overflow: hidden; +} + +/* A directory hit is a navigation target, not an openable file: the folder + glyph and the dimmer label say so before the click. */ +.editorSearchResultDir { + color: var(--dsw-alias-label-secondary); +} + +.editorSearchResultLabel { + min-width: 0; + overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } diff --git a/src/client/state.ts b/src/client/state.ts index c0c37f34..e5d63338 100644 --- a/src/client/state.ts +++ b/src/client/state.ts @@ -508,6 +508,33 @@ export function toggleExpanded(state: SidebarState, path: string): SidebarState return { ...state, expanded } } +/** + * The absolute ancestor directories between the explorer root (`cwd`) and each + * given path, EXCLUDING the paths themselves: the levels a lazy tree must have + * expanded before those rows can exist. Empty strings and non-strings are + * skipped; the result is de-duplicated in first-seen order. + * @param cwd - the explorer's root (session working directory). + * @param files - absolute paths whose ancestors are wanted. + */ +export function ancestorDirs(cwd: string | undefined, files: readonly string[]): string[] { + const found = new Set() + const rootParts = (cwd ?? '').split(/[\\/]+/).filter(part => part !== '') + for (const file of files) { + if (typeof file !== 'string' || file === '') continue + const parts = file.split(/[\\/]+/).filter(part => part !== '' && part !== '.') + const separator = file.includes('\\') ? '\\' : '/' + // Keep the original leading separator(s) when rebuilding ancestor dirs: + // FileTree matches expansion against ABSOLUTE paths, so dropping the + // root (POSIX `/w/src` → `w/src`) or a UNC prefix (`\\server\share`) + // would leave every ancestor collapsed and the row unreachable. + const prefix = file.startsWith('/') ? '/' : file.startsWith('\\\\') ? '\\\\' : file.startsWith('\\') ? '\\' : '' + for (let i = rootParts.length; i < parts.length - 1; i++) { + found.add(prefix + parts.slice(0, i + 1).join(separator)) + } + } + return [...found] +} + /** * Reveal files in the explorer: expand every ancestor directory between the * explorer root and each file (so the lazy tree actually shows the row) and @@ -519,25 +546,11 @@ export function toggleExpanded(state: SidebarState, path: string): SidebarState * @returns the next state, or the same reference when nothing is revealed. */ export function revealPaths(state: SidebarState, cwd: string | undefined, files: readonly string[]): SidebarState { - const expanded = new Set(state.expanded) - const revealed: string[] = [] - const rootParts = (cwd ?? '').split(/[\\/]+/).filter(part => part !== '') - for (const file of files) { - if (typeof file !== 'string' || file === '') continue - revealed.push(file) - const parts = file.split(/[\\/]+/).filter(part => part !== '' && part !== '.') - const separator = file.includes('\\') ? '\\' : '/' - // Keep the original leading separator(s) when rebuilding ancestor dirs: - // FileTree matches expansion against ABSOLUTE paths, so dropping the - // root (POSIX `/w/src` �W `w/src`) or a UNC prefix (`\\server\share`) - // would leave every ancestor collapsed and the row unreachable. - const prefix = file.startsWith('/') ? '/' : file.startsWith('\\\\') ? '\\\\' : file.startsWith('\\') ? '\\' : '' - for (let i = rootParts.length; i < parts.length - 1; i++) { - expanded.add(prefix + parts.slice(0, i + 1).join(separator)) - } - } + const revealed = files.filter(file => typeof file === 'string' && file !== '') if (revealed.length === 0) return state - return { ...state, expanded: [...expanded], revealed } + const expanded = new Set(state.expanded) + for (const dir of ancestorDirs(cwd, revealed)) expanded.add(dir) + return { ...state, expanded: [...expanded], revealed: [...revealed] } } /** Adjust one split divider: `i` is the left/top child index, delta in fractions. */ diff --git a/src/fs-search.ts b/src/fs-search.ts index c78d98f0..ee9cf2c3 100644 --- a/src/fs-search.ts +++ b/src/fs-search.ts @@ -11,14 +11,24 @@ * the flat list) and `maxVisited` (a runaway tree — a home directory root * — must not stall the host). Exceeding either stops early with * `truncated: true`. + * + * A hit can be a DIRECTORY (the list shows where matches live), so the result + * separates them: `fs.read` refuses a directory, and the client must navigate + * the tree for those rows instead of opening them as files. */ -import { opendir } from 'node:fs/promises' +import type { Dirent } from 'node:fs' +import { opendir, stat } from 'node:fs/promises' import { join, relative, sep } from 'node:path' /** One search: the relative paths of the matching entries (dirs included so * the client can hint where matches live) plus the truncation flag. */ export interface FsSearchResult { matches: string[] + /** The subset of `matches` that are DIRECTORIES (same relative, '/'-separated + * form). The client navigates the tree for these instead of opening them: + * `fs.read` refuses a directory, so treating a hit as a file surfaces a bare + * `"…" is a directory` error. */ + dirs: string[] truncated: boolean } @@ -60,6 +70,19 @@ const SEARCH_SKIP_DIRS = new Set([ '.dumi', ]) +/** + * Whether one matched entry is a DIRECTORY, following symlinks the way the + * tree and `fs.read` do: the dirent answers for real directories, a link is + * stat'ed (a link to a directory is a directory row — `fs.read` refuses it as + * a file), and an unresolvable link stays a plain entry. + */ +async function isDirectoryEntry(absolute: string, dirent: Dirent): Promise { + if (dirent.isDirectory()) return true + if (!dirent.isSymbolicLink()) return false + const info = await stat(absolute).catch(() => undefined) + return info?.isDirectory() === true +} + /** * Search `root` recursively for entries whose name contains `query` * (case-insensitive). @@ -67,16 +90,18 @@ const SEARCH_SKIP_DIRS = new Set([ * @param query - the name substring; empty matches nothing. * @param opts - budget overrides (tests). * @returns the matching paths RELATIVE to `root` ('/'-separated), sorted, - * plus whether a budget cut the walk short. An unreadable level is skipped - * (permission errors never fail the whole search). + * plus which of them are directories and whether a budget cut the walk + * short. An unreadable level is skipped (permission errors never fail the + * whole search). */ export async function searchFiles(root: string, query: string, opts: FsSearchOptions = {}): Promise { const needle = query.trim().toLowerCase() - if (needle === '') return { matches: [], truncated: false } + if (needle === '') return { matches: [], dirs: [], truncated: false } const maxMatches = opts.maxMatches ?? DEFAULT_MAX_MATCHES const maxVisited = opts.maxVisited ?? DEFAULT_MAX_VISITED const matches: string[] = [] + const dirs: string[] = [] let visited = 0 let truncated = false @@ -92,8 +117,11 @@ export async function searchFiles(root: string, query: string, opts: FsSearchOpt } // Dependency / VCS / build-output forests: never matched, never descended. if (dirent.isDirectory() && SEARCH_SKIP_DIRS.has(dirent.name.toLowerCase())) continue + const absolute = join(dir, dirent.name) if (dirent.name.toLowerCase().includes(needle)) { - matches.push(join(relative(root, dir), dirent.name)) + const hit = join(relative(root, dir), dirent.name) + matches.push(hit) + if (await isDirectoryEntry(absolute, dirent)) dirs.push(hit) if (matches.length >= maxMatches) { truncated = true return @@ -102,12 +130,13 @@ export async function searchFiles(root: string, query: string, opts: FsSearchOpt // Descend real directories only: a symlinked directory may point back // up the tree (cycle). if (dirent.isDirectory() && !dirent.isSymbolicLink()) { - await walk(join(dir, dirent.name)) + await walk(absolute) if (truncated) return } } } await walk(root) // '/' separators on every platform: the client joins onto the cwd itself. - return { matches: matches.sort().map(path => path.split(sep).join('/')), truncated } + const normalize = (path: string): string => path.split(sep).join('/') + return { matches: matches.sort().map(normalize), dirs: dirs.sort().map(normalize), truncated } } diff --git a/tests/file-tree-search-persist.spec.tsx b/tests/file-tree-search-persist.spec.tsx index 126b67f0..158da6fd 100644 --- a/tests/file-tree-search-persist.spec.tsx +++ b/tests/file-tree-search-persist.spec.tsx @@ -12,7 +12,7 @@ */ // @vitest-environment jsdom import { beforeAll, afterEach, describe, expect, it, vi } from 'vitest' -import { createElement } from 'react' +import { createElement, type ComponentProps } from 'react' import { createRoot, type Root } from 'react-dom/client' import { act } from 'react-dom/test-utils' import { TreePanel } from '../src/client/TreePanel.tsx' @@ -38,7 +38,8 @@ function defaultListing(path: string): Listing { const { fsTrees, fsSearch } = vi.hoisted(() => ({ fsTrees: vi.fn(async (_scope: unknown, paths: readonly string[]) => ({ levels: paths.map(path => defaultListing(path)) })), - fsSearch: vi.fn(async () => ({ matches: ['a.ts'], truncated: false })), + fsSearch: vi.fn(async (): Promise<{ matches: string[]; dirs: string[]; truncated: boolean }> => + ({ matches: ['a.ts'], dirs: [], truncated: false })), })) vi.mock('../src/client/api.ts', () => ({ @@ -58,7 +59,7 @@ interface Harness { unmount: () => void } -function mountPanel(): Harness { +function mountPanel(overrides: Partial> = {}): Harness { const container = document.createElement('div') document.body.append(container) const root: Root = createRoot(container) @@ -71,6 +72,7 @@ function mountPanel(): Harness { onToggle: () => {}, onOpenFile: () => {}, onReferenceFile: () => {}, + ...overrides, })) }) return { @@ -116,7 +118,8 @@ afterEach(() => { document.body.innerHTML = '' fsTrees.mockReset() fsTrees.mockImplementation(async (_scope: unknown, paths: readonly string[]) => ({ levels: paths.map(path => defaultListing(path)) })) - fsSearch.mockClear() + fsSearch.mockReset() + fsSearch.mockImplementation(async () => ({ matches: ['a.ts'], dirs: [], truncated: false })) }) describe('TreePanel search keeps the tree mounted', () => { @@ -184,3 +187,64 @@ describe('TreePanel refresh and truncated levels', () => { expect(notice).toBeDefined() }) }) + +describe('TreePanel directory hits navigate instead of opening', () => { + /** The search rows, in list order (the tree's own rows are not buttons here). */ + function resultRows(container: HTMLElement): HTMLButtonElement[] { + return [...resultsBody(container).querySelectorAll('button[class*="editorSearchResult"]')] + } + + it('expands a directory hit in the tree and never asks to open it as a file', async () => { + fsSearch.mockResolvedValue({ matches: ['src', 'src/a.ts'], dirs: ['src'], truncated: false }) + const onToggle = vi.fn() + const onOpenFile = vi.fn() + harness = mountPanel({ onToggle, onOpenFile }) + await act(async () => {}) + await search(harness.container, 'src') + + const dirRow = resultRows(harness.container).find(row => row.textContent === 'src')! + expect(dirRow.getAttribute('data-dsh-search-dir')).toBe('true') + expect(resultRows(harness.container).find(row => row.textContent === 'src/a.ts')! + .getAttribute('data-dsh-search-dir')).toBeNull() + + await act(async () => { dirRow.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) + // `fs.read` refuses a directory, so this row navigates instead of opening. + expect(onOpenFile).not.toHaveBeenCalled() + expect(onToggle).toHaveBeenCalledWith('/tmp/src') + // The query is cleared, so the tree (expanded at src) is what shows next. + expect(harness.container.querySelector('input[class*="editorSearchInput"]')!.value).toBe('') + expect(resultsBody(harness.container).hasAttribute('hidden')).toBe(true) + expect(treeBody(harness.container).hasAttribute('hidden')).toBe(false) + }) + + it('expands every ancestor of a nested hit, but only collapsed ones', async () => { + fsSearch.mockResolvedValue({ matches: ['src/deep', 'src/deep/a.ts'], dirs: ['src/deep'], truncated: false }) + const onToggle = vi.fn() + harness = mountPanel({ cwd: '/w/app', expanded: ['/w/app/src'], onToggle }) + await act(async () => {}) + await search(harness.container, 'deep') + + const dirRow = resultRows(harness.container).find(row => row.textContent === 'src/deep')! + await act(async () => { dirRow.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) + // /w/app is the explorer root and /w/app/src is already open: only the hit + // itself is toggled (a repeat toggle would COLLAPSE an open ancestor). + expect(onToggle).toHaveBeenCalledTimes(1) + expect(onToggle).toHaveBeenCalledWith('/w/app/src/deep') + }) + + it('still opens a file hit, leaving the expansion state untouched', async () => { + fsSearch.mockResolvedValue({ matches: ['src', 'src/a.ts'], dirs: ['src'], truncated: false }) + const onToggle = vi.fn() + const onOpenFile = vi.fn() + harness = mountPanel({ onToggle, onOpenFile }) + await act(async () => {}) + await search(harness.container, 'src') + + const fileRow = resultRows(harness.container).find(row => row.textContent === 'src/a.ts')! + await act(async () => { fileRow.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) + expect(onOpenFile).toHaveBeenCalledWith('/tmp/src/a.ts') + expect(onToggle).not.toHaveBeenCalled() + // A file open keeps the results list up (only a navigation clears it). + expect(resultsBody(harness.container).hasAttribute('hidden')).toBe(false) + }) +}) diff --git a/tests/fs-search.spec.ts b/tests/fs-search.spec.ts index ca10763f..515bdfe2 100644 --- a/tests/fs-search.spec.ts +++ b/tests/fs-search.spec.ts @@ -49,7 +49,7 @@ describe('fs-search', () => { const dir = makeFixture() try { const result = await searchFiles(dir, 'util') - expect(result).toEqual({ matches: ['src/util.ts'], truncated: false }) + expect(result).toEqual({ matches: ['src/util.ts'], dirs: [], truncated: false }) // A multi-level match list is sorted and relative (never absolute). const md = await searchFiles(dir, '.md') expect(md.truncated).toBe(false) @@ -68,8 +68,13 @@ describe('fs-search', () => { try { expect((await searchFiles(dir, 'index.ts')).matches).toEqual(['src/Index.TS']) expect((await searchFiles(dir, 'INDEX.TS')).matches).toEqual(['src/Index.TS']) - // Directory names match too (the client can hint where matches live). - expect((await searchFiles(dir, 'SRC')).matches).toEqual(['src']) + const dirHit = await searchFiles(dir, 'SRC') + // Directory names match too (the client can hint where matches live)… + expect(dirHit.matches).toEqual(['src']) + // …and they are reported as directories, so the list navigates the tree + // instead of opening one as a file (`fs.read` refuses a directory). + expect(dirHit).toEqual({ matches: ['src'], dirs: ['src'], truncated: false }) + expect((await searchFiles(dir, 'util')).dirs).toEqual([]) } finally { rmSync(dir, { recursive: true, force: true }) } @@ -111,8 +116,8 @@ describe('fs-search', () => { it('an empty (or whitespace) query matches nothing without walking', async () => { const dir = makeFixture() try { - expect(await searchFiles(dir, '')).toEqual({ matches: [], truncated: false }) - expect(await searchFiles(dir, ' ')).toEqual({ matches: [], truncated: false }) + expect(await searchFiles(dir, '')).toEqual({ matches: [], dirs: [], truncated: false }) + expect(await searchFiles(dir, ' ')).toEqual({ matches: [], dirs: [], truncated: false }) } finally { rmSync(dir, { recursive: true, force: true }) } @@ -126,7 +131,24 @@ describe('fs-search', () => { symlinkSync(dir, join(dir, 'loop')) symlinkSync(join(dir, 'src'), join(dir, 'src-link')) const result = await searchFiles(dir, 'util') - expect(result).toEqual({ matches: ['src/util.ts'], truncated: false }) + expect(result).toEqual({ matches: ['src/util.ts'], dirs: [], truncated: false }) + } finally { + rmSync(dir, { recursive: true, force: true }) + } + }) + + it.skipIf(!canSymlink)('classifies a symlinked hit by its target (link to a directory is a directory)', async () => { + const dir = makeFixture() + try { + symlinkSync(join(dir, 'src'), join(dir, 'src-link')) + symlinkSync(join(dir, 'README.md'), join(dir, 'readme-link.md')) + // `fs.read` stats through the link, so a link to a directory must be + // reported as a directory row too; a link to a file stays a file hit. + expect(await searchFiles(dir, 'src-link')).toEqual({ matches: ['src-link'], dirs: ['src-link'], truncated: false }) + expect(await searchFiles(dir, 'readme-link')).toEqual({ matches: ['readme-link.md'], dirs: [], truncated: false }) + // A dangling link cannot be classified, so it stays a plain entry. + symlinkSync(join(dir, 'gone'), join(dir, 'dangling-link')) + expect(await searchFiles(dir, 'dangling-link')).toEqual({ matches: ['dangling-link'], dirs: [], truncated: false }) } finally { rmSync(dir, { recursive: true, force: true }) } @@ -165,7 +187,7 @@ describe('fs-search', () => { const dir = makeFixture() try { const missing = join(dir, 'does-not-exist') - expect(await searchFiles(missing, 'x')).toEqual({ matches: [], truncated: false }) + expect(await searchFiles(missing, 'x')).toEqual({ matches: [], dirs: [], truncated: false }) } finally { rmSync(dir, { recursive: true, force: true }) } diff --git a/tests/state.spec.ts b/tests/state.spec.ts index f5ebf3aa..9c648924 100644 --- a/tests/state.spec.ts +++ b/tests/state.spec.ts @@ -1,6 +1,6 @@ import { afterEach, beforeEach, describe, expect, it } from 'vitest' import { - activateTab, allLeaves, BOTTOM_DEFAULT, BOTTOM_MIN, closeTab, CONVERSATION_MIN, createSidebarStore, + activateTab, allLeaves, ancestorDirs, BOTTOM_DEFAULT, BOTTOM_MIN, closeTab, CONVERSATION_MIN, createSidebarStore, insertLeafAt, makeDefaultState, moveTab, moveTabToEdge, openDiffTab, openTabInBottomPane, patchTab, resizeSplit, resizeSplitIn, revealPaths, sanitizeState, setBottomHeight, @@ -726,6 +726,27 @@ describe('revealPaths (show in folder)', () => { }) }) +describe('ancestorDirs (the levels a lazy tree must expand)', () => { + it('lists the absolute ancestors below the explorer root, excluding the path itself', () => { + // The root itself is not a level the tree expands, and the target is not + // its own ancestor. + expect(ancestorDirs('/w/src', ['/w/src/sub/deep/a.ts'])).toEqual(['/w/src/sub', '/w/src/sub/deep']) + expect(ancestorDirs('/w/src', ['/w/src/a.ts'])).toEqual([]) + }) + + it('keeps a Windows drive-letter root and a UNC prefix', () => { + expect(ancestorDirs('C:\\work', ['C:\\work\\src\\a.ts'])).toEqual(['C:\\work\\src']) + expect(ancestorDirs('\\\\server\\share', ['\\\\server\\share\\sub\\a.ts'])).toEqual(['\\\\server\\share\\sub']) + }) + + it('skips empty and non-string entries and de-duplicates shared ancestors', () => { + expect(ancestorDirs('/w', ['', '/w/a/b.ts', '/w/a/c.ts'])).toEqual(['/w/a']) + // Without a root there is nothing to anchor against, so every leading + // level is still reported (the caller only uses this when cwd is known). + expect(ancestorDirs(undefined, [undefined as unknown as string, '/a/b/c.ts'])).toEqual(['/a', '/a/b']) + }) +}) + describe('URL reset escape hatch (issue #369)', () => { // Same browser-global stubs as the v0.12.0 block above; loadState reads // window.location.search (reset param) and localStorage (persisted state).