Merge pull request #806 from ZinChl/fix/search-result-directory-click

fix(files): 搜索结果里的目录行改为导航文件树,不再当文件打开(#801)
This commit is contained in:
Atlas Zeng authored and GitHub committed 2026-10-05 00:53:09 +08:00
commit 10e99dba7e
8 files changed
+246 -52

No files matched your search

+42 -12
View File
@@ -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<string | null>(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 (
<div className={clsx(css.editorTreePanel, full === true && css.editorTreePanelFull)}>
@@ -262,17 +284,25 @@ export function TreePanel(props: {
{error === null && results !== null && results.matches.length === 0 && (
<div className={css.editorSearchHint}>{t('editorSearchNoResults')}</div>
)}
{error === null && results !== null && results.matches.map(rel => (
<button
key={rel}
type="button"
className={css.editorSearchResult}
title={rel}
onClick={() => { onOpenFile(resolveSidebarPath(cwd, rel)) }}
>
{rel}
</button>
))}
{error === null && results !== null && results.matches.map((rel) => {
const isDirHit = dirHits.has(rel)
return (
<button
key={rel}
type="button"
className={clsx(css.editorSearchResult, isDirHit && css.editorSearchResultDir)}
title={rel}
data-dsh-search-dir={isDirHit ? 'true' : undefined}
onClick={() => {
if (isDirHit) openSearchDir(rel)
else onOpenFile(resolveSidebarPath(cwd, rel))
}}
>
{isDirHit && <IconFolderOpenRegular size={14} />}
<span className={css.editorSearchResultLabel}>{rel}</span>
</button>
)
})}
{error === null && results?.truncated === true && (
<div className={css.editorSearchHint}>{t('editorSearchTruncated')}</div>
)}
+4 -2
View File
@@ -292,9 +292,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<FsTextResult | FsBinaryResult>('fs.read', scopePayload(scope, { path }), signal),
fsWrite: (scope: SessionScope, path: string, content: string) =>
+14 -1
View File
@@ -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;
}
+31 -18
View File
@@ -520,6 +520,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<string>()
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
@@ -531,25 +558,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. */
+36 -7
View File
@@ -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<boolean> {
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<FsSearchResult> {
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 }
}
+68 -4
View File
@@ -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<ComponentProps<typeof TreePanel>> = {}): 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<HTMLButtonElement>('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<HTMLInputElement>('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)
})
})
+29 -7
View File
@@ -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 })
}
+22 -1
View File
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } 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,
@@ -760,6 +760,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).