fix(fs-search): direct-open for pasted paths + fragment path matching (#879)
A query carrying a path separator can never match an entry NAME — names
never contain separators — so pasting any path into the search box was
structurally guaranteed to return {matches:[],truncated:true} while the
walk burned its full 100k-visit budget (measured: 1.9s on a Rust repo
whose two worktree forests alone held 97k entries; real directories were
never reached).
searchFiles now routes by query shape, all three modalities sharing one
result contract:
- A query naming one path (absolute, ~/…, ./x, ../x) resolves through
resolveTarget — the SAME primitive fs.read uses, so ~ expands (#713),
dot-anchored spellings join onto the session cwd, and win32
WSL/dsh-remote namespaces reinterpret — then stats the target. The hit
is the RESOLVED path (resolve() strips shell-completion trailing
separators, which the client's exact-string row comparisons could never
match); a missing target answers empty immediately. Directory targets
ride the #801 dirs contract. The exclude pref does not apply: a pasted
path is explicit intent, same as the fs.read the click performs.
- A separator-carrying relative fragment (records/exp1) matches by
root-relative PATH in the walk; the engines are name matchers (fd has
no --full-path here, rg's globs are single-segment) so argv
construction is untouched.
- Plain name queries are unchanged, and no NAME query is stolen: on
POSIX a backslash is a name character (the ~\ gesture counts only on
win32; util.ts~ / ~$doc.docx / .env stay name queries).
SKIP_DIR_NAMES gains the budget-eating forests seen in the wild:
.worktrees/.worktree (git worktree layouts), target, venv/.venv and
__pycache__ — shared by the walk and both engine argvs as before.
Client: a directory hit OUTSIDE the cwd (newly reachable via the paste
branch) only clears the query — the tree is cwd-rooted, and the old
ancestorDirs call synthesized junk expanded entries for foreign paths.
Verified: vitest fs-search/smoke/search-persist suites green; full run
2171 passed with one failure proven pre-existing on the clean tree
(git.spec checkout case, host git lacks --end-of-options; #841);
typecheck/lint clean.
This commit is contained in:
1 parent
4e51e0789c
commit
0d9fee85b8
12 files changed
+471
-56
No files matched your search
@@ -31,7 +31,7 @@ import { IconUploadOutline16 } from './icons.tsx'
|
||||
import type { OpenInApp } from './open-in-app.ts'
|
||||
import type { OpenWithTarget } from './open-with.ts'
|
||||
import { t } from './locales.ts'
|
||||
import { resolveSidebarPath } from './paths.ts'
|
||||
import { isWithinWorkspace, resolveSidebarPath } from './paths.ts'
|
||||
import { IconButton } from './ui/index.ts'
|
||||
import { UploadOverlay } from './UploadOverlay.tsx'
|
||||
import {
|
||||
@@ -230,9 +230,14 @@ export function TreePanel(props: {
|
||||
* paths are touched — and clear the query so the tree, not the parked
|
||||
* results panel, is what the user sees next.
|
||||
*/
|
||||
// A directory hit OUTSIDE the cwd (a pasted absolute path from the
|
||||
// direct-open branch) has no tree rows to expand: the tree is cwd-rooted,
|
||||
// and `ancestorDirs` would synthesize cwd-length prefixes of a foreign
|
||||
// path that toggle nothing and persist as junk `expanded` entries. Such a
|
||||
// row only clears the query.
|
||||
const openSearchDir = (rel: string): void => {
|
||||
const target = resolveSidebarPath(cwd, rel)
|
||||
if (cwd !== undefined) {
|
||||
if (cwd !== undefined && isWithinWorkspace(cwd, target)) {
|
||||
for (const path of [...ancestorDirs(cwd, [target]), target]) {
|
||||
if (!expanded.includes(path)) onToggle(path)
|
||||
}
|
||||
|
||||
+10
-6
@@ -356,12 +356,16 @@ export const api = {
|
||||
*/
|
||||
fsTrees: (scope: SessionScope, paths: readonly string[], exclude?: readonly string[], signal?: AbortSignal) =>
|
||||
call<{ levels: FsLevel[] }>('fs.trees', scopePayload(scope, { paths: [...paths], exclude }), signal),
|
||||
/** Global recursive file-name search rooted at the session cwd (the editor
|
||||
* 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). `exclude` carries the
|
||||
* explorerExclude pref: matched entries never match and are never
|
||||
* descended (host-side, in lockstep with the tree). */
|
||||
/** Global recursive file search rooted at the session cwd (the editor
|
||||
* side panel's search box). A name query matches cwd-relative
|
||||
* '/'-separated paths; a separator-carrying fragment matches by PATH;
|
||||
* a query naming one path (absolute, `~/…`, `./x`, `../x`) is stat'ed
|
||||
* through the same resolution fs.read uses and yields the RESOLVED
|
||||
* absolute target as the single match. `dirs` names the subset that is a
|
||||
* directory (the list navigates the tree for those — `fs.read` refuses a
|
||||
* directory). `exclude` carries the explorerExclude pref: matched entries
|
||||
* never match and are never descended (host-side, in lockstep with the
|
||||
* tree; a pasted direct-open path is explicit intent and skips it). */
|
||||
fsSearch: (scope: SessionScope, query: string, exclude?: readonly string[], signal?: AbortSignal) =>
|
||||
call<{ matches: string[]; dirs: string[]; truncated: boolean }>('fs.search', scopePayload(scope, { query, exclude }), signal),
|
||||
fsRead: (scope: SessionScope, path: string, signal?: AbortSignal) =>
|
||||
|
||||
+125
-30
@@ -1,11 +1,28 @@
|
||||
/**
|
||||
* Recursive file-name search for the editor's merged-mode side panel.
|
||||
* Streams the tree with opendir and matches the query as a case-insensitive
|
||||
* substring of each entry's NAME (paths stay relative to the search root —
|
||||
* the client resolves them against the session cwd). No .gitignore semantics
|
||||
* (this is a name lookup, not a code search), but known noise directories
|
||||
* (`.git`, `node_modules`, package-manager stores, build caches) are
|
||||
* skipped outright and symlink directories are NOT descended (cycle safety).
|
||||
* Recursive file search for the editor's merged-mode side panel. Three query
|
||||
* modalities share one result contract:
|
||||
*
|
||||
* - A plain name query streams the tree with opendir and matches the query
|
||||
* as a case-insensitive substring of each entry's NAME (paths stay relative
|
||||
* to the search root — the client resolves them against the session cwd).
|
||||
* No .gitignore semantics (this is a name lookup, not a code search), but
|
||||
* known noise directories (`.git`, `node_modules`, package-manager
|
||||
* stores, build caches, worktree forests) are skipped outright and symlink
|
||||
* directories are NOT descended (cycle safety).
|
||||
* - A query carrying a path separator can never hit a NAME (names never
|
||||
* contain separators), so it matches against the entry's root-relative
|
||||
* PATH instead (#879): a pasted `records/exp1` finds the file at any
|
||||
* depth, which name matching structurally cannot (#306).
|
||||
* - A query that NAMES one path (an absolute path, a `~`-relative home
|
||||
* spelling, or a dot-anchored `./x` / `../x`) is an open-this-file
|
||||
* gesture, not a filter: `searchFiles` resolves the target through the
|
||||
* SAME primitive every fs route uses (`resolveTarget` — `~` expansion,
|
||||
* session-cwd join, win32 WSL / dsh-remote reinterpretation, lexical
|
||||
* resolve), stats it, and returns the RESOLVED path as the single hit (a
|
||||
* trailing separator from shell completion is stripped by the resolve, and
|
||||
* the client's resolveSidebarPath passes absolute paths through — the fs
|
||||
* routes reach any host-user path since the workspace fence came off). A
|
||||
* missing target is an immediate empty result.
|
||||
*
|
||||
* Two performance budgets bound the walk: `maxMatches` (the client renders
|
||||
* the flat list) and `maxVisited` (a runaway tree — a home directory root
|
||||
@@ -17,28 +34,34 @@
|
||||
* the tree for those rows instead of opening them as files.
|
||||
*
|
||||
* `searchFiles` (the dispatch the fs.search route calls) first tries the
|
||||
* probed native engines (fd / rg — see search-engines.ts); when none are
|
||||
* available or all failed at runtime it falls back to this walk (exported as
|
||||
* `searchFilesPlain` for tests). Both paths fill the same contract — the
|
||||
* `opts.exclude` probe included: the walk skips a match before descending,
|
||||
* the engine path post-filters its flat listing (see engineExcludeProbe).
|
||||
* probed native engines (fd / rg — see search-engines.ts) for NAME queries;
|
||||
* when none are available or all failed at runtime it falls back to this walk
|
||||
* (exported as `searchFilesPlain` for tests). Both paths fill the same
|
||||
* contract — the `opts.exclude` probe included: the walk skips a match
|
||||
* before descending, the engine path post-filters its flat listing (see
|
||||
* engineExcludeProbe). Separator queries never reach the engines: the
|
||||
* engines are name matchers (fd takes --fixed-strings without --full-path,
|
||||
* rg's globs match single path segments), so the walk owns the fragment
|
||||
* semantics alone.
|
||||
*/
|
||||
import type { Dirent } from 'node:fs'
|
||||
import { opendir, stat } from 'node:fs/promises'
|
||||
import { join, relative, sep } from 'node:path'
|
||||
import { isAbsolute, join, sep } from 'node:path'
|
||||
import { homedir } from 'node:os'
|
||||
import type { ExcludeTest } from './exclude-patterns.ts'
|
||||
import { resolveTarget } from './path-security.ts'
|
||||
import { SKIP_DIR_NAMES, runEngine, usableEngines } from './search-engines.ts'
|
||||
import { debugLog } from './search-debug.ts'
|
||||
|
||||
/** One search: the relative paths of the matching entries (dirs included so
|
||||
* the client can hint where matches live) plus the truncation flag. */
|
||||
/** One search: the paths of the matching entries (root-relative,
|
||||
* '/'-separated for tree searches; a direct-path query yields the RESOLVED
|
||||
* absolute target) 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. */
|
||||
/** The subset of `matches` that are DIRECTORIES (same form as their match
|
||||
* row). 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
|
||||
}
|
||||
@@ -93,11 +116,42 @@ async function isDirectoryEntry(absolute: string, dirent: Dirent): Promise<boole
|
||||
return info?.isDirectory() === true
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `query` carries a path separator: such a query can never hit an
|
||||
* entry NAME and takes the path branches instead of name matching. Only the
|
||||
* platform's own separators count — on POSIX a backslash is a legal name
|
||||
* character, not a separator (the engines must stay eligible for names
|
||||
* like `back\slash.ts`).
|
||||
*/
|
||||
function hasSeparator(query: string): boolean {
|
||||
return query.includes('/') || (process.platform === 'win32' && query.includes('\\'))
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `query` NAMES one path (a direct-open gesture) instead of
|
||||
* filtering: node's own absolute forms, the `~`-relative home spellings the
|
||||
* resolution primitive expands (#713 — the client's own `isAbsolutePath`
|
||||
* treats the same forms as absolute), and dot-anchored relative paths
|
||||
* (`./x`, `../x`). No entry NAME can take these shapes — a name never
|
||||
* contains a separator — so the predicate steals no name query, with one
|
||||
* platform-bent exception: the `~\` form counts only on win32, because on
|
||||
* POSIX a backslash is a legal name character and `~\foo` can be a file's
|
||||
* NAME. Plain fragments (`records/exp1`) stay with the path-fragment branch.
|
||||
*/
|
||||
function isDirectPathQuery(query: string): boolean {
|
||||
return isAbsolute(query)
|
||||
|| query === '~' || query.startsWith('~/') || (process.platform === 'win32' && query.startsWith('~\\'))
|
||||
|| /^\.+[/\\]/.test(query)
|
||||
}
|
||||
|
||||
/**
|
||||
* The plain-JS fallback walk: search `root` recursively for entries whose
|
||||
* name contains `query` (case-insensitive).
|
||||
* name contains `query` (case-insensitive), or — for a query carrying a
|
||||
* path separator, which no NAME can contain — whose root-relative path
|
||||
* does.
|
||||
* @param root - absolute search root.
|
||||
* @param query - the name substring; empty matches nothing.
|
||||
* @param query - the name substring, or the path fragment for
|
||||
* separator-carrying queries; empty matches nothing.
|
||||
* @param opts - budget overrides (tests).
|
||||
* @returns the matching paths RELATIVE to `root` ('/'-separated), sorted,
|
||||
* plus which of them are directories and whether a budget cut the walk
|
||||
@@ -109,13 +163,17 @@ export async function searchFilesPlain(root: string, query: string, opts: FsSear
|
||||
if (needle === '') return { matches: [], dirs: [], truncated: false }
|
||||
const maxMatches = opts.maxMatches ?? DEFAULT_MAX_MATCHES
|
||||
const maxVisited = opts.maxVisited ?? DEFAULT_MAX_VISITED
|
||||
// Path-fragment matching folds the needle's '/' onto the platform's own
|
||||
// separator (Windows users paste both styles); POSIX backslashes inside
|
||||
// the needle stay literal name characters.
|
||||
const pathNeedle = hasSeparator(needle) ? needle.replace(/\//g, sep) : undefined
|
||||
|
||||
const matches: string[] = []
|
||||
const dirs: string[] = []
|
||||
let visited = 0
|
||||
let truncated = false
|
||||
|
||||
const walk = async (dir: string): Promise<void> => {
|
||||
const walk = async (dir: string, relDir: string): Promise<void> => {
|
||||
if (truncated) return
|
||||
const level = await opendir(dir).catch(() => undefined)
|
||||
if (level === undefined) return
|
||||
@@ -130,14 +188,17 @@ export async function searchFilesPlain(root: string, query: string, opts: FsSear
|
||||
// gitdir) is VCS noise too — the name check covers both shapes,
|
||||
// parity with the engines' .git exclusion (SKIP_DIR_NAMES).
|
||||
if (SEARCH_SKIP_DIRS.has(dirent.name.toLowerCase())) continue
|
||||
const relativePath = relDir === '' ? dirent.name : `${relDir}${sep}${dirent.name}`
|
||||
const absolute = join(dir, dirent.name)
|
||||
// The user's exclude list removes entries from search exactly like the
|
||||
// tree listing (no match, no descent).
|
||||
if (opts.exclude !== undefined && opts.exclude(absolute, dirent.name)) continue
|
||||
if (dirent.name.toLowerCase().includes(needle)) {
|
||||
const hit = join(relative(root, dir), dirent.name)
|
||||
matches.push(hit)
|
||||
if (await isDirectoryEntry(absolute, dirent)) dirs.push(hit)
|
||||
const hit = pathNeedle === undefined
|
||||
? dirent.name.toLowerCase().includes(needle)
|
||||
: relativePath.toLowerCase().includes(pathNeedle)
|
||||
if (hit) {
|
||||
matches.push(relativePath)
|
||||
if (await isDirectoryEntry(absolute, dirent)) dirs.push(relativePath)
|
||||
if (matches.length >= maxMatches) {
|
||||
truncated = true
|
||||
return
|
||||
@@ -146,12 +207,12 @@ export async function searchFilesPlain(root: string, query: string, opts: FsSear
|
||||
// Descend real directories only: a symlinked directory may point back
|
||||
// up the tree (cycle).
|
||||
if (dirent.isDirectory() && !dirent.isSymbolicLink()) {
|
||||
await walk(absolute)
|
||||
await walk(absolute, relativePath)
|
||||
if (truncated) return
|
||||
}
|
||||
}
|
||||
}
|
||||
await walk(root)
|
||||
await walk(root, '')
|
||||
// '/' separators on every platform: the client joins onto the cwd itself.
|
||||
const normalize = (path: string): string => path.split(sep).join('/')
|
||||
return { matches: matches.sort().map(normalize), dirs: dirs.sort().map(normalize), truncated }
|
||||
@@ -190,7 +251,9 @@ function engineExcludeProbe(root: string, exclude: ExcludeTest): (relativePath:
|
||||
}
|
||||
|
||||
/**
|
||||
* The fs.search dispatch: native engines first (when verified and healthy),
|
||||
* The fs.search dispatch: an absolute query is stat'ed directly (see the
|
||||
* module header), a separator-carrying fragment goes to the walk, and plain
|
||||
* name queries run the native engines first (when verified and healthy) with
|
||||
* the plain walk as fallback. Engine output is normalized onto the walk
|
||||
* contract — root-relative, '/'-separated, sorted, and split into
|
||||
* matches/dirs — so the route and the client stay unchanged. A blank query
|
||||
@@ -204,8 +267,40 @@ function engineExcludeProbe(root: string, exclude: ExcludeTest): (relativePath:
|
||||
export async function searchFiles(root: string, query: string, opts: FsSearchOptions = {}): Promise<FsSearchResult> {
|
||||
const needle = query.trim()
|
||||
if (needle === '') return { matches: [], dirs: [], truncated: false }
|
||||
const maxMatches = opts.maxMatches ?? DEFAULT_MAX_MATCHES
|
||||
const started = performance.now()
|
||||
// #879: a query that NAMES one path is a direct-open gesture. Name
|
||||
// matching is guaranteed-empty for it (names never contain separators),
|
||||
// so the engines and the walk would only burn the visit budget to report
|
||||
// the same nothing. The target goes through the SAME resolution primitive
|
||||
// every fs route uses, so the hit opens exactly what the click's fs.read
|
||||
// opens — `~` expansion, session-cwd join for the dot-anchored spellings,
|
||||
// win32 WSL / dsh-remote reinterpretation — and the RESOLVED path is
|
||||
// returned, not the pasted spelling: resolve() strips the trailing
|
||||
// separator shell completion adds, and the client compares match rows
|
||||
// exactly against tree paths that never carry one. The user's exclude
|
||||
// list does not apply here — a pasted path is an explicit intent, and
|
||||
// fs.read applies no exclude either.
|
||||
if (isDirectPathQuery(needle)) {
|
||||
const target = resolveTarget(root, needle)
|
||||
const info = await stat(target).catch(() => undefined)
|
||||
const result: FsSearchResult = info === undefined
|
||||
? { matches: [], dirs: [], truncated: false }
|
||||
: info.isDirectory()
|
||||
? { matches: [target], dirs: [target], truncated: false }
|
||||
: { matches: [target], dirs: [], truncated: false }
|
||||
debugLog(`[dsh-search] engine=stat root=${relRoot(root)} query="${needle}" hits=${result.matches.length} truncated=${result.truncated} ${(performance.now() - started).toFixed(0)}ms`)
|
||||
return result
|
||||
}
|
||||
// A separator-carrying RELATIVE query is a path fragment (#879): it can
|
||||
// never hit a name, and the engines are name matchers (fd's
|
||||
// --fixed-strings has no --full-path; rg's globs match single segments),
|
||||
// so the walk's path matching is the single semantics for fragments.
|
||||
if (hasSeparator(needle)) {
|
||||
const result = await searchFilesPlain(root, query, opts)
|
||||
debugLog(`[dsh-search] engine=plain root=${relRoot(root)} query="${needle}" hits=${result.matches.length} truncated=${result.truncated} ${(performance.now() - started).toFixed(0)}ms`)
|
||||
return result
|
||||
}
|
||||
const maxMatches = opts.maxMatches ?? DEFAULT_MAX_MATCHES
|
||||
const isExcluded = opts.exclude === undefined ? undefined : engineExcludeProbe(root, opts.exclude)
|
||||
for (const probe of await usableEngines()) {
|
||||
try {
|
||||
|
||||
+7
-3
@@ -573,9 +573,13 @@ function buildApi(
|
||||
return { levels }
|
||||
},
|
||||
'fs.search': async (payload) => {
|
||||
// The editor side panel's global name search: rooted at the session
|
||||
// cwd (not caller-targetable — the walk is unbounded by design and
|
||||
// must never escape the workspace), budgeted inside searchFiles.
|
||||
// The editor side panel's global search. Name queries stay rooted at
|
||||
// the session cwd (not caller-targetable — the walk is unbounded by
|
||||
// design), budgeted inside searchFiles. A query carrying a path
|
||||
// separator can never match a NAME, so searchFiles routes it
|
||||
// differently: an absolute query stats its target (the same
|
||||
// any-host-path reach fs.read has had since the workspace fence came
|
||||
// off) and a relative fragment matches by path.
|
||||
const { cwd } = await cwdOf(payload)
|
||||
const record = payload as { exclude?: unknown }
|
||||
const query = requireString(payload, 'query')
|
||||
|
||||
+12
-1
@@ -215,7 +215,8 @@ export function escapeGlob(query: string): string {
|
||||
}
|
||||
|
||||
/** Directory names that are never useful filename-search results (VCS
|
||||
* internals, dependency forests, package-manager stores, build caches).
|
||||
* internals, dependency forests, package-manager stores, build caches,
|
||||
* worktree forests, language environments).
|
||||
* The plain walk in fs-search.ts builds its case-insensitive skip set
|
||||
* from this list, and BOTH engine argvs exclude every name — with
|
||||
* --no-ignore active an rg/fd run would otherwise re-enter node_modules
|
||||
@@ -238,6 +239,16 @@ export const SKIP_DIR_NAMES: readonly string[] = [
|
||||
'dist',
|
||||
'build',
|
||||
'out',
|
||||
// #879: git-worktree forests (both spellings; `.worktrees/` is the
|
||||
// layout DeepSeek Harness itself uses) burned the whole 100k visit budget
|
||||
// on real projects before the walk reached project files. Language
|
||||
// environments and their bytecode caches are noise of the same class.
|
||||
'.worktrees',
|
||||
'.worktree',
|
||||
'target',
|
||||
'venv',
|
||||
'.venv',
|
||||
'__pycache__',
|
||||
'.umi',
|
||||
'.umi-production',
|
||||
'.dumi',
|
||||
|
||||
Reference in new issue
Block a user