Skip to content
Closed
Show file tree
Hide file tree
Changes from 12 commits
Commits
Show all changes
15 commits
Select commit Hold shift + click to select a range
5461a65
perf(filesearch): move recursive crawl + fzf index to worker_threads
callmeYe Apr 19, 2026
c70c58e
fix(filesearch): audit round 1 — worker lifecycle, error paths, and R…
callmeYe Apr 19, 2026
7df087e
fix(filesearch): audit round 2 — ignore fingerprint, dispose, and INS…
callmeYe Apr 19, 2026
ccf9df0
fix(filesearch): audit round 3 — harden worker boundary + graceful pa…
callmeYe Apr 19, 2026
f37a653
fix(filesearch): audit round 4 — release-blocker packaging + stale-ke…
callmeYe Apr 19, 2026
294a79e
fix(filesearch): audit round 5 — revert AbortError on post-dispose sy…
callmeYe Apr 19, 2026
a9915d1
perf(cli): prewarm file index at boot and hide transient loading indi…
callmeYe Apr 19, 2026
ee04405
perf(filesearch): add ripgrep crawl backend (gated; fdir stays default)
callmeYe Apr 19, 2026
3fdc49c
perf(filesearch): restore ripgrep as default after re-benchmarking on ~
callmeYe Apr 19, 2026
b15c289
fix(filesearch): audit round 6 — Windows rg paths + CR follow-ups
callmeYe Apr 20, 2026
6ffe02b
chore(vscode-ide-companion): drop dead glob helper + bracket-access d…
callmeYe Apr 20, 2026
a18a3fb
test(filesearch): Windows — tear down FileIndexService before rmdir'i…
callmeYe Apr 20, 2026
ea82f9d
fix(filesearch): audit round 7 — CR follow-ups from @yiliang114
callmeYe Apr 21, 2026
1f5ea90
merge: upstream/main into feat/filesearch-worker-p1
callmeYe Apr 21, 2026
44fcc11
fix(filesearch): audit round 8 — scoped transport install + unref() t…
callmeYe Apr 22, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 58 additions & 38 deletions esbuild.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,45 +72,65 @@ const external = [
'@teddyzhu/clipboard-win32-arm64-msvc',
];

esbuild
.build({
entryPoints: ['packages/cli/index.ts'],
bundle: true,
outfile: 'dist/cli.js',
platform: 'node',
format: 'esm',
target: 'node20',
external,
packages: 'bundle',
inject: [path.resolve(__dirname, 'scripts/esbuild-shims.js')],
banner: {
js: `// Force strict mode and setup for ESM
const commonBundleOptions = {
bundle: true,
platform: 'node',
format: 'esm',
target: 'node20',
external,
packages: 'bundle',
define: {
'process.env.CLI_VERSION': JSON.stringify(pkg.version),
// Make global available for compatibility
global: 'globalThis',
},
loader: { '.node': 'file' },
plugins: [wasmBinaryPlugin, wasmLoader({ mode: 'embedded' })],
write: true,
keepNames: true,
};

const mainBuild = esbuild.build({
...commonBundleOptions,
entryPoints: ['packages/cli/index.ts'],
outfile: 'dist/cli.js',
inject: [path.resolve(__dirname, 'scripts/esbuild-shims.js')],
banner: {
js: `// Force strict mode and setup for ESM
"use strict";`,
},
alias: {
'is-in-ci': path.resolve(
__dirname,
'packages/cli/src/patches/is-in-ci.ts',
),
'@qwen-code/web-templates': path.resolve(
__dirname,
'packages/web-templates/src/index.ts',
),
// Resolve to userland punycode instead of deprecated node:punycode built-in
punycode: require.resolve('punycode/'),
},
define: {
'process.env.CLI_VERSION': JSON.stringify(pkg.version),
// Make global available for compatibility
global: 'globalThis',
},
loader: { '.node': 'file' },
plugins: [wasmBinaryPlugin, wasmLoader({ mode: 'embedded' })],
metafile: true,
write: true,
keepNames: true,
})
.then(({ metafile }) => {
},
alias: {
'is-in-ci': path.resolve(__dirname, 'packages/cli/src/patches/is-in-ci.ts'),
'@qwen-code/web-templates': path.resolve(
__dirname,
'packages/web-templates/src/index.ts',
),
// Resolve to userland punycode instead of deprecated node:punycode built-in
punycode: require.resolve('punycode/'),
},
metafile: true,
});

// The file-index worker runs in its own worker_threads process and must exist
// as a standalone file next to dist/cli.js so that `new URL('./fileIndexWorker.js',
// import.meta.url)` resolves at runtime (the main bundle's import.meta.url is
// dist/cli.js). We bundle it self-contained so fzf/fdir get inlined and no
// node_modules resolution is required from the published tarball.
const workerBuild = esbuild.build({
...commonBundleOptions,
entryPoints: ['packages/core/src/utils/filesearch/fileIndexWorker.ts'],
outfile: 'dist/fileIndexWorker.js',
// fdir and other transitive CJS deps use require() at runtime, which is
// not available in ESM output without this shim. Same pattern as the main
// CLI bundle above.
inject: [path.resolve(__dirname, 'scripts/esbuild-shims.js')],
banner: {
js: `"use strict";`,
},
});

Promise.all([mainBuild, workerBuild])
.then(([{ metafile }]) => {
if (process.env.DEV === 'true') {
writeFileSync('./dist/esbuild.json', JSON.stringify(metafile, null, 2));
}
Expand Down
30 changes: 30 additions & 0 deletions packages/cli/src/ui/AppContainer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ import {
type PermissionMode,
ToolConfirmationOutcome,
type WaitingToolCall,
FileIndexService,
} from '@qwen-code/qwen-code-core';
import { buildResumedHistoryItems } from './utils/resumeHistoryUtils.js';
import { validateAuthMethod } from '../config/auth.js';
Expand Down Expand Up @@ -312,6 +313,35 @@ export const AppContainer = (props: AppContainerProps) => {
await config.initialize();
setConfigInitialized(true);

// Pre-warm the file index so the first `@` keypress usually finds a
// ready-or-nearly-ready snapshot instead of kicking off a cold crawl.
// These options must match the ones useAtCompletion uses so both hit
// the same FileIndexService singleton (keyed by an options hash).
// Skip the prewarm entirely when recursive file search is disabled —
// otherwise users who opted out still pay for a full crawl on startup,
// and the worker they never use sticks around.
// Fire-and-forget: errors surface via the normal search path the next
// time the hook is used.
if (config.getEnableRecursiveFileSearch() !== false) {
try {
FileIndexService.for({

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Prewarm options duplicated with useAtCompletion

These options must be byte-for-byte identical to fileSearchOptions in useAtCompletion.ts:202 to hit the same FileIndexService singleton (keyed by sha256). The "must match" comment is correct but there's no compile-time or runtime guard — if one side drifts, you silently spawn two workers and the prewarm is wasted.

Suggestion: extract a shared buildFileSearchOptions(config) helper, use it in both places.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in ea82f9d. Extracted buildFileSearchOptions(config, cwd) into useAtCompletion.ts (exported) and rewired both call sites:

  • AppContainer.tsx prewarm: FileIndexService.for(buildFileSearchOptions(config, config.getTargetDir()))
  • useAtCompletion.ts hook: const fileSearchOptions = useMemo(() => buildFileSearchOptions(config, cwd), [config, cwd])

Both sites now go through the same helper, so a new field in FileSearchOptions is a compile-time change in one place. The "must match" drift risk is gone.

projectRoot: config.getTargetDir(),
ignoreDirs: [],
useGitignore:
config.getFileFilteringOptions()?.respectGitIgnore ?? true,
useQwenignore:
config.getFileFilteringOptions()?.respectQwenIgnore ?? true,
cache: true,
cacheTtl: 30,
enableRecursiveFileSearch: true,
enableFuzzySearch:
config.getFileFilteringEnableFuzzySearch() !== false,
});
} catch {
// ignore — the hook will spawn on demand if pre-warm throws.
}
}

const resumedSessionData = config.getResumedSessionData();
if (resumedSessionData) {
const historyItems = buildResumedHistoryItems(
Expand Down
3 changes: 0 additions & 3 deletions packages/cli/src/ui/components/Composer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@ import { useUIActions } from '../contexts/UIActionsContext.js';
import { useVimMode } from '../contexts/VimModeContext.js';
import { useConfig } from '../contexts/ConfigContext.js';
import { StreamingState } from '../types.js';
import { ConfigInitDisplay } from '../components/ConfigInitDisplay.js';
import { FeedbackDialog } from '../FeedbackDialog.js';
import { t } from '../../i18n/index.js';

Expand Down Expand Up @@ -78,8 +77,6 @@ export const Composer = () => {
/>
)}

{!uiState.isConfigInitialized && <ConfigInitDisplay />}

<QueuedMessageDisplay messageQueue={uiState.messageQueue} />

{uiState.isFeedbackDialogOpen && <FeedbackDialog />}
Expand Down
68 changes: 38 additions & 30 deletions packages/cli/src/ui/hooks/useAtCompletion.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import type {
FileSystemStructure,
} from '@qwen-code/qwen-code-core';
import {
FileIndexService,
FileSearchFactory,
createTmpDir,
cleanupTmpDir,
Expand Down Expand Up @@ -61,6 +62,12 @@ describe('useAtCompletion', () => {
});

afterEach(async () => {
// Dispose any live FileIndexService singletons before removing the
// temp dir. On Windows, an in-flight ripgrep child launched with
// `cwd: testRootDir` keeps a handle on the directory until it exits;
// rmdir'ing while that handle is open returns EBUSY. Resetting the
// service tears down the transport (and its rg subprocess) first.
await FileIndexService.__resetForTests();
if (testRootDir) {
await cleanupTmpDir(testRootDir);
}
Expand Down Expand Up @@ -116,12 +123,20 @@ describe('useAtCompletion', () => {
expect(result.current.suggestions.length).toBeGreaterThan(0);
});

expect(result.current.suggestions.map((s) => s.value)).toEqual([
'src/',
'src/components/',
'src/index.js',
'src/components/Button.tsx',
]);
// fzf ranks matches by score and breaks ties using list position,
// which depends on the crawler's emission order. That order is a
// ripgrep-vs-fdir implementation detail; asserting on the exact
// ranking was coupling this test to fdir's legacy breadth-first
// output. Content is what matters — all `src/` entries should be
// returned, nothing else.
expect(result.current.suggestions.map((s) => s.value).sort()).toEqual(
[
'src/',
'src/components/',
'src/components/Button.tsx',
'src/index.js',
].sort(),
);
});

it('should append a trailing slash to directory paths in suggestions', async () => {
Expand All @@ -139,24 +154,23 @@ describe('useAtCompletion', () => {
expect(result.current.suggestions.length).toBeGreaterThan(0);
});

expect(result.current.suggestions.map((s) => s.value)).toEqual([
'dir/',
'file.txt',
]);
expect(result.current.suggestions.map((s) => s.value).sort()).toEqual(
['dir/', 'file.txt'].sort(),
);
});
});

describe('UI State and Loading Behavior', () => {
it('should be in a loading state during initial file system crawl', async () => {
it('settles into non-loading state after initial file system crawl', async () => {
testRootDir = await createTmpDir({});
const { result } = renderHook(() =>
useTestHarnessForAtCompletion(true, '', mockConfig, testRootDir),
);

// It's initially true because the effect runs synchronously.
expect(result.current.isLoadingSuggestions).toBe(true);

// Wait for the loading to complete.
// The transient INITIALIZING → READY window no longer flashes the
// loading indicator synchronously; `isLoading` only flips to true if
// initialization stays slow past the 200 ms threshold. Either way, the
// steady state after a fast crawl is `false`.
await waitFor(() => {
expect(result.current.isLoadingSuggestions).toBe(false);
});
Expand Down Expand Up @@ -396,10 +410,9 @@ describe('useAtCompletion', () => {
expect(result.current.suggestions.length).toBeGreaterThan(0);
});

expect(result.current.suggestions.map((s) => s.value)).toEqual([
'src/',
'.gitignore',
]);
expect(result.current.suggestions.map((s) => s.value).sort()).toEqual(
['src/', '.gitignore'].sort(),
);
});

it('should work correctly when config is undefined', async () => {
Expand All @@ -417,10 +430,9 @@ describe('useAtCompletion', () => {
expect(result.current.suggestions.length).toBeGreaterThan(0);
});

expect(result.current.suggestions.map((s) => s.value)).toEqual([
'node_modules/',
'src/',
]);
expect(result.current.suggestions.map((s) => s.value).sort()).toEqual(
['node_modules/', 'src/'].sort(),
);
});

it('should reset and re-initialize when the cwd changes', async () => {
Expand Down Expand Up @@ -452,13 +464,9 @@ describe('useAtCompletion', () => {
rerender({ cwd: rootDir2, pattern: 'file' });
});

// After CWD changes, suggestions should be cleared and it should load again.
await waitFor(() => {
expect(result.current.isLoadingSuggestions).toBe(true);
expect(result.current.suggestions).toEqual([]);
});

// Wait for the new suggestions from the second directory
// After CWD changes, the RESET clears suggestions; the loading flash
// is no longer synchronous (suppressed for <200 ms inits), so we only
// assert the end state.
await waitFor(() => {
expect(result.current.suggestions.map((s) => s.value)).toEqual([
'file2.txt',
Expand Down
Loading