Show nested sub-project files in file-explorer name search (#6481)

When Quick Open and File Explorer name search fall back to git ls-files, expand nested git repo placeholders with a bounded readdir walk so monorepo parent workspaces include files inside sub-projects. Keep local main-process and SSH relay behavior aligned, including non-git root fallback and non-zero git failure handling.

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Brennan Benson
2026-06-28 23:56:05 -07:00
committed by GitHub
co-authored by Orca
parent b776506809
commit f8e8d5d149
12 changed files with 1017 additions and 213 deletions
+2 -2
View File
@@ -239,12 +239,12 @@ describe('normalizeQuickOpenRgLine', () => {
describe('buildGitLsFilesArgsForQuickOpen', () => {
it('primary pass is --cached --others --exclude-standard', () => {
const { primary } = buildGitLsFilesArgsForQuickOpen()
expect(primary).toEqual(['-z', '--cached', '--others', '--exclude-standard'])
expect(primary).toEqual(['-z', '-s', '--cached', '--others', '--exclude-standard'])
})
it('ignored pass surfaces ignored files without .env* pathspec whitelist', () => {
const { ignoredPass } = buildGitLsFilesArgsForQuickOpen()
expect(ignoredPass).toEqual(['-z', '--others', '--ignored', '--exclude-standard'])
expect(ignoredPass).toEqual(['-z', '-s', '--others', '--ignored', '--exclude-standard'])
expect(ignoredPass).not.toContain('.env*')
expect(ignoredPass).not.toContain(':(glob)**/.env*')
})
+11 -4
View File
@@ -377,9 +377,16 @@ export function buildGitLsFilesArgsForQuickOpen(
}
const trailingPathspecs = excludeSpecs.length > 0 ? ['--', '.', ...excludeSpecs] : []
// Why: newline output C-quotes tabs/newlines, which makes Quick Open return
// fake paths when rg is unavailable. NUL output preserves real Git paths.
const primary = ['-z', '--cached', '--others', '--exclude-standard', ...trailingPathspecs]
const ignoredPass = ['-z', '--others', '--ignored', '--exclude-standard', ...trailingPathspecs]
// Why: NUL preserves real Git paths; stage mode identifies gitlinks without
// lstat probes for ordinary tracked files.
const primary = ['-z', '-s', '--cached', '--others', '--exclude-standard', ...trailingPathspecs]
const ignoredPass = [
'-z',
'-s',
'--others',
'--ignored',
'--exclude-standard',
...trailingPathspecs
]
return { primary, ignoredPass }
}
+262
View File
@@ -0,0 +1,262 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
const { lstatMock } = vi.hoisted(() => ({
lstatMock: vi.fn()
}))
vi.mock('fs/promises', async () => {
const actual = await vi.importActual<typeof import('fs/promises')>('fs/promises') // eslint-disable-line @typescript-eslint/consistent-type-imports -- vi.importActual requires inline import()
lstatMock.mockImplementation(actual.lstat)
return {
...actual,
lstat: lstatMock
}
})
import { mkdtemp, mkdir, rm, symlink, writeFile } from 'fs/promises'
import { tmpdir } from 'os'
import { dirname, join } from 'path'
import {
classifyQuickOpenGitEntry,
createQuickOpenReaddirBudget,
expandQuickOpenGitFilesWithNestedRepos,
isQuickOpenReaddirBudgetError,
listQuickOpenFilesWithReaddir,
parseQuickOpenGitLsFilesEntry
} from './quick-open-readdir-walk'
const tempDirs: string[] = []
const SHA1 = '0123456789abcdef0123456789abcdef01234567'
const SHA256 = `${SHA1}89abcdef0123456789abcdef`
function staged(mode: string, path: string, sha = SHA1): string {
return `${mode} ${sha} 0\t${path}`
}
async function makeTempRoot(): Promise<string> {
const root = await mkdtemp(join(tmpdir(), 'orca-quick-open-readdir-'))
tempDirs.push(root)
return root
}
async function writeRel(root: string, relPath: string, content = 'x'): Promise<void> {
const absPath = join(root, ...relPath.split('/'))
await mkdir(dirname(absPath), { recursive: true })
await writeFile(absPath, content)
}
async function mkdirRel(root: string, relPath: string): Promise<void> {
await mkdir(join(root, ...relPath.split('/')), { recursive: true })
}
async function makeNestedRepo(root: string, relPath: string, gitEntry: 'dir' | 'file' = 'dir') {
await mkdirRel(root, relPath)
const gitPath = join(root, ...relPath.split('/'), '.git')
await (gitEntry === 'dir'
? mkdir(gitPath, { recursive: true })
: writeFile(gitPath, 'gitdir: ../.git/worktrees/example'))
}
afterEach(async () => {
vi.clearAllMocks()
await Promise.all(tempDirs.splice(0).map((dir) => rm(dir, { recursive: true, force: true })))
})
describe('quick-open readdir walk', () => {
it('parses git ls-files stage output and bare untracked entries', () => {
expect(parseQuickOpenGitLsFilesEntry(staged('100644', 'src/index.ts'))).toEqual({
path: 'src/index.ts',
isGitlink: false,
isUntrackedDir: false
})
expect(parseQuickOpenGitLsFilesEntry(staged('160000', 'packages/app'))).toEqual({
path: 'packages/app',
isGitlink: true,
isUntrackedDir: false
})
expect(parseQuickOpenGitLsFilesEntry(staged('100755', 'bin/run', SHA256))).toEqual({
path: 'bin/run',
isGitlink: false,
isUntrackedDir: false
})
expect(parseQuickOpenGitLsFilesEntry('scratch.txt')).toEqual({
path: 'scratch.txt',
isGitlink: false,
isUntrackedDir: false
})
expect(parseQuickOpenGitLsFilesEntry('packages/lib/')).toEqual({
path: 'packages/lib/',
isGitlink: false,
isUntrackedDir: true
})
})
it('keeps ordinary git entries without lstat calls', async () => {
await expect(
expandQuickOpenGitFilesWithNestedRepos({
rootPath: '/unused/root',
gitPaths: [
staged('100644', 'README.md'),
staged('100755', 'bin/run', SHA256),
'scratch.txt'
]
})
).resolves.toEqual(['README.md', 'bin/run', 'scratch.txt'])
expect(lstatMock).not.toHaveBeenCalled()
})
it('classifies nested repo placeholders without confusing extensionless files', async () => {
const root = await makeTempRoot()
await writeRel(root, 'Makefile')
await makeNestedRepo(root, 'packages/app')
await makeNestedRepo(root, 'packages/lib', 'file')
await mkdirRel(root, 'packages/unchecked')
await expect(classifyQuickOpenGitEntry(root, staged('100644', 'Makefile'))).resolves.toEqual({
kind: 'keep',
relPath: 'Makefile'
})
await expect(
classifyQuickOpenGitEntry(root, staged('160000', 'packages/app'))
).resolves.toEqual({
kind: 'fill-nested-repo',
relPath: 'packages/app'
})
await expect(classifyQuickOpenGitEntry(root, 'packages/lib/')).resolves.toEqual({
kind: 'fill-nested-repo',
relPath: 'packages/lib'
})
await expect(classifyQuickOpenGitEntry(root, 'packages/unchecked')).resolves.toEqual({
kind: 'keep',
relPath: 'packages/unchecked'
})
await expect(classifyQuickOpenGitEntry(root, 'packages/unchecked/')).resolves.toEqual({
kind: 'drop-placeholder',
relPath: 'packages/unchecked'
})
})
it('re-prefixes nested children and filters final workspace-relative paths', async () => {
const root = await makeTempRoot()
await writeRel(root, 'README.md')
await writeRel(root, 'Makefile')
await makeNestedRepo(root, 'packages/app')
await makeNestedRepo(root, 'packages/lib', 'file')
await mkdirRel(root, 'packages/empty')
await writeRel(root, 'packages/app/src/main.ts')
await writeRel(root, 'packages/app/node_modules/pkg/index.js')
await writeRel(root, 'packages/app/.git/config')
await writeRel(root, 'packages/app/linked-worktree/file.ts')
await writeRel(root, 'packages/lib/src/lib.ts')
await expect(
expandQuickOpenGitFilesWithNestedRepos({
rootPath: root,
gitPaths: [
staged('100644', 'README.md'),
staged('100644', 'Makefile'),
staged('160000', 'packages/app'),
'packages/lib/',
'packages/empty/'
],
excludePathPrefixes: ['packages/app/linked-worktree']
})
).resolves.toEqual([
'README.md',
'Makefile',
'packages/app/src/main.ts',
'packages/lib/src/lib.ts'
])
})
it('rejects on cap and shares one budget across nested subtrees', async () => {
const root = await makeTempRoot()
await makeNestedRepo(root, 'packages/app')
await makeNestedRepo(root, 'packages/lib')
await writeRel(root, 'packages/app/a.ts')
await writeRel(root, 'packages/app/b.ts')
await writeRel(root, 'packages/lib/c.ts')
await expect(
expandQuickOpenGitFilesWithNestedRepos({
rootPath: root,
gitPaths: [staged('160000', 'packages/app'), staged('160000', 'packages/lib')],
budget: createQuickOpenReaddirBudget({ maxFiles: 2 })
})
).rejects.toThrow('File listing exceeded')
})
it('prunes excluded nested subtrees during traversal without consuming the budget', async () => {
const root = await makeTempRoot()
await makeNestedRepo(root, 'packages/app')
await writeRel(root, 'packages/app/keep.ts')
// A large excluded subtree inside the nested repo: if it were walked before
// being filtered, it would exhaust the tiny budget and reject.
for (let i = 0; i < 20; i += 1) {
await writeRel(root, `packages/app/excluded/file-${i}.ts`)
}
await expect(
expandQuickOpenGitFilesWithNestedRepos({
rootPath: root,
gitPaths: [staged('160000', 'packages/app')],
excludePathPrefixes: ['packages/app/excluded'],
budget: createQuickOpenReaddirBudget({ maxFiles: 5 })
})
).resolves.toEqual(['packages/app/keep.ts'])
})
it('identifies budget errors so callers can translate only those to install-rg guidance', () => {
expect(isQuickOpenReaddirBudgetError(new Error('File listing timed out'))).toBe(true)
expect(isQuickOpenReaddirBudgetError(new Error('File listing exceeded 10000 files'))).toBe(true)
// Genuine git failures must keep their own message, not the install-rg toast.
expect(isQuickOpenReaddirBudgetError(new Error('git ls-files killed by SIGTERM'))).toBe(false)
expect(isQuickOpenReaddirBudgetError('File listing timed out')).toBe(false)
})
it('rejects on deadline instead of returning a partial list', async () => {
const root = await makeTempRoot()
await writeRel(root, 'src/index.ts')
await expect(
listQuickOpenFilesWithReaddir(root, {
budget: { remainingFiles: 10, deadlineMs: Date.now() - 1_000 }
})
).rejects.toThrow('File listing timed out')
})
it('does not list symlinked files or follow symlinked directories', async () => {
const root = await makeTempRoot()
await writeRel(root, 'src/index.ts')
await writeRel(root, 'target/file.ts')
try {
await symlink(join(root, 'src/index.ts'), join(root, 'src/link.ts'))
await symlink(join(root, 'target'), join(root, 'linked-dir'), 'dir')
} catch (err) {
if ((err as NodeJS.ErrnoException).code === 'EPERM') {
return
}
throw err
}
const files = await listQuickOpenFilesWithReaddir(root)
expect(files).toEqual(expect.arrayContaining(['src/index.ts', 'target/file.ts']))
expect(files).not.toContain('src/link.ts')
expect(files).not.toContain('linked-dir/file.ts')
})
it('fills nested repo paths containing spaces and glob metacharacters', async () => {
const root = await makeTempRoot()
await makeNestedRepo(root, 'packages/app [one] space')
await writeRel(root, 'packages/app [one] space/src/main.ts')
await expect(
expandQuickOpenGitFilesWithNestedRepos({
rootPath: root,
gitPaths: ['packages/app [one] space/']
})
).resolves.toEqual(['packages/app [one] space/src/main.ts'])
})
})
+251
View File
@@ -0,0 +1,251 @@
import { lstat, readdir } from 'fs/promises'
import { join, relative } from 'path'
import {
HIDDEN_DIR_BLOCKLIST,
shouldExcludeQuickOpenRelPath,
shouldIncludeQuickOpenPath
} from './quick-open-filter'
export const QUICK_OPEN_READDIR_MAX_FILES = 10_000
export const QUICK_OPEN_READDIR_TIMEOUT_MS = 10_000
export type QuickOpenReaddirBudget = {
remainingFiles: number
deadlineMs: number
}
export type QuickOpenGitEntryKind = 'keep' | 'fill-nested-repo' | 'drop-placeholder'
export type QuickOpenGitLsFilesEntry = {
path: string
isGitlink: boolean
isUntrackedDir: boolean
}
const GIT_LS_FILES_STAGE_ENTRY = /^([0-7]{6}) [0-9a-f]{40,64} [0-3]\t/
export function parseQuickOpenGitLsFilesEntry(entry: string): QuickOpenGitLsFilesEntry {
const match = GIT_LS_FILES_STAGE_ENTRY.exec(entry)
if (match) {
return {
path: entry.slice(match[0].length),
isGitlink: match[1] === '160000',
isUntrackedDir: false
}
}
return {
path: entry,
isGitlink: false,
isUntrackedDir: entry.endsWith('/')
}
}
export function createQuickOpenReaddirBudget(
opts: { maxFiles?: number; timeoutMs?: number; nowMs?: number } = {}
): QuickOpenReaddirBudget {
return {
remainingFiles: opts.maxFiles ?? QUICK_OPEN_READDIR_MAX_FILES,
deadlineMs: (opts.nowMs ?? Date.now()) + (opts.timeoutMs ?? QUICK_OPEN_READDIR_TIMEOUT_MS)
}
}
const FILE_LISTING_TIMED_OUT = 'File listing timed out'
const FILE_LISTING_EXCEEDED_PREFIX = 'File listing exceeded'
/**
* Why: the readdir walk can exhaust its cap/deadline even on the git path (a
* git monorepo parent with a huge nested repo). Callers translate only these
* budget errors into "install rg" guidance, leaving genuine git failures with
* their own messages.
*/
export function isQuickOpenReaddirBudgetError(error: unknown): boolean {
const message = error instanceof Error ? error.message : ''
return message === FILE_LISTING_TIMED_OUT || message.startsWith(FILE_LISTING_EXCEEDED_PREFIX)
}
function assertWithinDeadline(budget: QuickOpenReaddirBudget): void {
if (Date.now() > budget.deadlineMs) {
throw new Error(FILE_LISTING_TIMED_OUT)
}
}
function consumeFileBudget(budget: QuickOpenReaddirBudget): void {
if (budget.remainingFiles <= 0) {
throw new Error(`${FILE_LISTING_EXCEEDED_PREFIX} ${QUICK_OPEN_READDIR_MAX_FILES} files`)
}
budget.remainingFiles--
}
function shouldDescend(name: string): boolean {
return name !== 'node_modules' && !HIDDEN_DIR_BLOCKLIST.has(name)
}
function toRelPath(rootPath: string, absPath: string): string {
// Why: path.relative returns backslashes on Windows, while Quick Open paths
// are always stored and matched with POSIX separators.
return relative(rootPath, absPath).replace(/\\/g, '/')
}
function joinRootRel(rootPath: string, relPath: string): string {
return join(rootPath, ...relPath.split('/').filter(Boolean))
}
function normalizeGitEntry(entry: string): string {
return entry.replace(/\/+$/, '')
}
// Translate workspace-root-relative exclude prefixes into prefixes relative to
// a nested repo at `nestedRelPath`, so the nested walk can prune them during
// traversal. Prefixes outside the nested repo are dropped (they cannot match).
function rebaseExcludePrefixesForNestedRepo(
excludePathPrefixes: readonly string[],
nestedRelPath: string
): string[] {
const base = `${nestedRelPath}/`
const rebased: string[] = []
for (const prefix of excludePathPrefixes) {
if (prefix.startsWith(base)) {
rebased.push(prefix.slice(base.length))
}
}
return rebased
}
async function hasGitEntry(absPath: string): Promise<boolean> {
try {
const stat = await lstat(join(absPath, '.git'))
return stat.isDirectory() || stat.isFile()
} catch {
return false
}
}
export async function classifyQuickOpenGitEntry(
rootPath: string,
entry: string
): Promise<{ kind: QuickOpenGitEntryKind; relPath: string }> {
const parsed = parseQuickOpenGitLsFilesEntry(entry)
const relPath = normalizeGitEntry(parsed.path)
if (!relPath) {
return { kind: 'drop-placeholder', relPath }
}
if (!parsed.isGitlink && !parsed.isUntrackedDir) {
return { kind: 'keep', relPath }
}
let stat
try {
stat = await lstat(joinRootRel(rootPath, relPath))
} catch {
return { kind: 'drop-placeholder', relPath }
}
if (!stat.isDirectory()) {
return { kind: 'drop-placeholder', relPath }
}
if (await hasGitEntry(joinRootRel(rootPath, relPath))) {
return { kind: 'fill-nested-repo', relPath }
}
return { kind: 'drop-placeholder', relPath }
}
export async function listQuickOpenFilesWithReaddir(
rootPath: string,
opts: {
excludePathPrefixes?: readonly string[]
budget?: QuickOpenReaddirBudget
} = {}
): Promise<string[]> {
const files: string[] = []
const budget = opts.budget ?? createQuickOpenReaddirBudget()
const excludePathPrefixes = opts.excludePathPrefixes ?? []
async function walk(dir: string): Promise<void> {
assertWithinDeadline(budget)
let entries
try {
entries = await readdir(dir, { withFileTypes: true })
} catch {
// Why: permission denied on an individual subtree is common for broad
// roots. Skipping that subtree preserves the existing relay fallback.
return
}
for (const entry of entries) {
assertWithinDeadline(budget)
const name = entry.name
const absPath = join(dir, name)
const relPath = toRelPath(rootPath, absPath)
if (shouldExcludeQuickOpenRelPath(relPath, excludePathPrefixes)) {
continue
}
if (entry.isDirectory()) {
if (shouldDescend(name)) {
await walk(absPath)
}
continue
}
if (entry.isFile()) {
consumeFileBudget(budget)
files.push(relPath)
}
}
}
await walk(rootPath)
return files
}
export async function expandQuickOpenGitFilesWithNestedRepos(opts: {
rootPath: string
gitPaths: Iterable<string>
excludePathPrefixes?: readonly string[]
budget?: QuickOpenReaddirBudget
}): Promise<string[]> {
const files = new Set<string>()
const excludePathPrefixes = opts.excludePathPrefixes ?? []
const budget = opts.budget ?? createQuickOpenReaddirBudget()
const addFinalPath = (relPath: string): void => {
if (!relPath) {
return
}
if (shouldExcludeQuickOpenRelPath(relPath, excludePathPrefixes)) {
return
}
if (shouldIncludeQuickOpenPath(relPath)) {
files.add(relPath)
}
}
for (const rawPath of opts.gitPaths) {
assertWithinDeadline(budget)
const { kind, relPath } = await classifyQuickOpenGitEntry(opts.rootPath, rawPath)
if (kind === 'keep') {
addFinalPath(relPath)
continue
}
if (kind === 'drop-placeholder') {
continue
}
const nestedFiles = await listQuickOpenFilesWithReaddir(joinRootRel(opts.rootPath, relPath), {
// Why: exclude prefixes are workspace-root-relative; rebase them onto the
// nested repo so the walk prunes excluded subtrees during traversal
// instead of burning the shared budget and filtering them at the end.
excludePathPrefixes: rebaseExcludePrefixesForNestedRepo(excludePathPrefixes, relPath),
budget
})
for (const nestedFile of nestedFiles) {
addFinalPath(`${relPath}/${nestedFile}`)
}
}
return Array.from(files)
}