From c309bfb1bebbac47cc2b21ecb2d3ba53c6d3a2a6 Mon Sep 17 00:00:00 2001 From: Ting-Wai To <40179554+tingwai@users.noreply.github.com> Date: Wed, 17 Sep 2025 13:43:03 -0700 Subject: [PATCH] feat: revamp efficient file search and support fuzzy matching --- extensions/cli/package-lock.json | 135 +++---- extensions/cli/package.json | 4 +- .../src/e2e/home-directory-warning.test.ts | 256 ------------- .../cli/src/services/FileIndexService.test.ts | 55 ++- .../cli/src/services/FileIndexService.ts | 339 ++++++++---------- extensions/cli/src/ui/FileSearchUI.tsx | 195 ++++++---- extensions/cli/src/ui/IntroMessage.tsx | 15 - extensions/cli/src/ui/UserInput.tsx | 100 +++--- .../__tests__/UserInput.missingFile.test.tsx | 36 ++ 9 files changed, 470 insertions(+), 665 deletions(-) delete mode 100644 extensions/cli/src/e2e/home-directory-warning.test.ts create mode 100644 extensions/cli/src/ui/__tests__/UserInput.missingFile.test.tsx diff --git a/extensions/cli/package-lock.json b/extensions/cli/package-lock.json index 6f7b8795c..729edf086 100644 --- a/extensions/cli/package-lock.json +++ b/extensions/cli/package-lock.json @@ -9,7 +9,9 @@ "version": "0.0.0-dev", "license": "Apache-2.0", "dependencies": { - "@sentry/profiling-node": "^9.43.0" + "@sentry/profiling-node": "^9.43.0", + "fdir": "^6.4.2", + "fzf": "^0.5.2" }, "bin": { "cn": "dist/cn.js" @@ -236,11 +238,11 @@ }, "../../packages/config-yaml": { "name": "@continuedev/config-yaml", - "version": "1.0.96", + "version": "1.14.0", "dev": true, "license": "Apache-2.0", "dependencies": { - "@continuedev/config-types": "file:../config-types", + "@continuedev/config-types": "^1.0.14", "yaml": "^2.6.1", "zod": "^3.24.2" }, @@ -264,15 +266,15 @@ }, "../../packages/openai-adapters": { "name": "@continuedev/openai-adapters", - "version": "1.5.1", + "version": "1.14.0", "dev": true, "license": "Apache-2.0", "dependencies": { "@aws-sdk/client-bedrock-runtime": "^3.842.0", "@aws-sdk/credential-providers": "^3.840.0", "@continuedev/config-types": "^1.0.14", - "@continuedev/config-yaml": "^1.8.0", - "@continuedev/fetch": "^1.0.16", + "@continuedev/config-yaml": "^1.14.0", + "@continuedev/fetch": "^1.1.0", "dotenv": "^16.5.0", "google-auth-library": "^10.1.0", "json-schema": "^0.4.0", @@ -9478,6 +9480,23 @@ "reusify": "^1.0.4" } }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, "node_modules/fecha": { "version": "4.2.3", "resolved": "https://registry.npmjs.org/fecha/-/fecha-4.2.3.tgz", @@ -9906,6 +9925,12 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/fzf": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fzf/-/fzf-0.5.2.tgz", + "integrity": "sha512-Tt4kuxLXFKHy8KT40zwsUPUkg1CrsgY25FxA2U/j/0WgEDCk3ddc/zLTCCcbSHX9FcKtLuVaDGtGE/STWC+j3Q==", + "license": "BSD-3-Clause" + }, "node_modules/get-caller-file": { "version": "2.0.5", "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", @@ -12061,6 +12086,19 @@ "node": ">=8.6" } }, + "node_modules/micromatch/node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, "node_modules/mime": { "version": "4.0.7", "resolved": "https://registry.npmjs.org/mime/-/mime-4.0.7.tgz", @@ -15737,13 +15775,13 @@ "license": "ISC" }, "node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", - "dev": true, + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "devOptional": true, "license": "MIT", "engines": { - "node": ">=8.6" + "node": ">=12" }, "funding": { "url": "https://github.com/sponsors/jonschlinkert" @@ -18106,37 +18144,6 @@ "url": "https://github.com/sponsors/SuperchupuDev" } }, - "node_modules/tinyglobby/node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/tinyglobby/node_modules/picomatch": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", - "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/tinygradient": { "version": "1.1.5", "resolved": "https://registry.npmjs.org/tinygradient/-/tinygradient-1.1.5.tgz", @@ -18847,37 +18854,6 @@ "url": "https://opencollective.com/vitest" } }, - "node_modules/vite/node_modules/fdir": { - "version": "6.5.0", - "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", - "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12.0.0" - }, - "peerDependencies": { - "picomatch": "^3 || ^4" - }, - "peerDependenciesMeta": { - "picomatch": { - "optional": true - } - } - }, - "node_modules/vite/node_modules/picomatch": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", - "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/vitest": { "version": "3.2.4", "resolved": "https://registry.npmjs.org/vitest/-/vitest-3.2.4.tgz", @@ -18951,19 +18927,6 @@ } } }, - "node_modules/vitest/node_modules/picomatch": { - "version": "4.0.3", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", - "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", - "dev": true, - "license": "MIT", - "engines": { - "node": ">=12" - }, - "funding": { - "url": "https://github.com/sponsors/jonschlinkert" - } - }, "node_modules/w3c-xmlserializer": { "version": "5.0.0", "resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz", diff --git a/extensions/cli/package.json b/extensions/cli/package.json index 7f212fab6..61da44989 100644 --- a/extensions/cli/package.json +++ b/extensions/cli/package.json @@ -44,7 +44,9 @@ }, "homepage": "https://continue.dev", "dependencies": { - "@sentry/profiling-node": "^9.43.0" + "@sentry/profiling-node": "^9.43.0", + "fdir": "^6.4.2", + "fzf": "^0.5.2" }, "devDependencies": { "@continuedev/config-yaml": "file:../../packages/config-yaml", diff --git a/extensions/cli/src/e2e/home-directory-warning.test.ts b/extensions/cli/src/e2e/home-directory-warning.test.ts deleted file mode 100644 index a5caf9d52..000000000 --- a/extensions/cli/src/e2e/home-directory-warning.test.ts +++ /dev/null @@ -1,256 +0,0 @@ -import * as fs from "node:fs"; -import * as path from "node:path"; - -import { afterEach, beforeEach, describe, expect, it } from "vitest"; - -import { - cleanupTestContext, - createTestConfig, - createTestContext, - runCLI, - type CLITestContext, -} from "../test-helpers/cli-helpers.js"; -import { HOME_DIRECTORY_WARNING } from "../ui/IntroMessage.js"; - -describe("E2E: Home Directory Warning", () => { - let context: CLITestContext; - - const testConfig = `name: Test Assistant -version: 1.0.0 -schema: v1 -models: - - model: gpt-4 - provider: openai - apiKey: test-key - roles: - - chat`; - - beforeEach(async () => { - context = await createTestContext(); - }); - - afterEach(async () => { - await cleanupTestContext(context); - }); - - describe("home directory detection", () => { - it("should NOT show warning in headless mode even when running from home directory", async () => { - await createTestConfig(context, testConfig); - - // Simulate running from home directory using the isolated test dir - const result = await runCLI(context, { - args: ["-p", "--config", context.configPath!, "test prompt"], - env: { - OPENAI_API_KEY: "test-key", - // Ensure home vars point to the isolated test dir - HOME: context.testDir, - USERPROFILE: context.testDir, - HOMEDRIVE: path.parse(context.testDir).root, - HOMEPATH: path.relative( - path.parse(context.testDir).root, - context.testDir, - ), - CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"), - }, - timeout: 5000, - expectError: true, - }); - - // Should NOT contain the home directory warning in headless mode - const output = result.stdout + result.stderr; - expect(output).not.toContain(HOME_DIRECTORY_WARNING); - }); - - it("should show warning when running from home directory in TUI mode", async () => { - await createTestConfig(context, testConfig); - - // Test TUI mode (without -p flag) from an isolated "home" directory - const result = await runCLI(context, { - args: ["--config", context.configPath!], - env: { - OPENAI_API_KEY: "test-key", - HOME: context.testDir, - USERPROFILE: context.testDir, - HOMEDRIVE: path.parse(context.testDir).root, - HOMEPATH: path.relative( - path.parse(context.testDir).root, - context.testDir, - ), - CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"), - }, - timeout: 3000, - expectError: true, - }); - - // In TUI mode, if we get any meaningful output, check for warning - const output = result.stdout + result.stderr; - if ( - output.includes("Continue") || - output.includes("Agent") || - output.includes("Model") - ) { - expect(output).toContain(HOME_DIRECTORY_WARNING); - } else { - // TUI mode likely failed to start in test environment, which is expected - // The important thing is that it attempted TUI mode, not headless mode - expect(result.exitCode).toBeDefined(); - } - }); - - it("should NOT show warning in headless mode regardless of platform", async () => { - await createTestConfig(context, testConfig); - - // Test with different platform-specific environment variables - const platformEnvs: Record[] = [ - // Unix-style - { - HOME: context.testDir, - OPENAI_API_KEY: "test-key", - }, - // Windows-style - { - USERPROFILE: context.testDir, - HOMEDRIVE: path.parse(context.testDir).root, - HOMEPATH: path.relative( - path.parse(context.testDir).root, - context.testDir, - ), - OPENAI_API_KEY: "test-key", - }, - ]; - - for (const env of platformEnvs) { - const result = await runCLI(context, { - args: ["-p", "--config", context.configPath!, "test prompt"], - env: { - CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"), - ...env, - }, - timeout: 5000, - expectError: true, - }); - - // Should NOT contain warning in headless mode regardless of platform - const output = result.stdout + result.stderr; - expect(output).not.toContain(HOME_DIRECTORY_WARNING); - } - }); - - it("should NOT show warning in headless mode with symlinked home directories", async () => { - await createTestConfig(context, testConfig); - - // Create a symlink to the isolated home directory to simulate symlinked home paths - const realHome = fs.realpathSync(context.testDir); - const linkPath = path.join( - path.dirname(realHome), - `${path.basename(realHome)}-link`, - ); - try { - if (!fs.existsSync(linkPath)) { - fs.symlinkSync(realHome, linkPath, "dir"); - } - } catch { - // If symlink creation fails (e.g., on Windows without privileges), skip this specific scenario - } - - const result = await runCLI(context, { - args: ["-p", "--config", context.configPath!, "test prompt"], - env: { - OPENAI_API_KEY: "test-key", - // Point HOME to the symlink while cwd remains the real path - HOME: fs.existsSync(linkPath) ? linkPath : realHome, - USERPROFILE: fs.existsSync(linkPath) ? linkPath : realHome, - HOMEDRIVE: path.parse(realHome).root, - HOMEPATH: path.relative(path.parse(realHome).root, realHome), - CONTINUE_GLOBAL_DIR: path.join(realHome, ".continue-global"), - }, - timeout: 5000, - expectError: true, - }); - - // Should NOT detect home directory warning in headless mode even with resolved paths - const output = result.stdout + result.stderr; - expect(output).not.toContain(HOME_DIRECTORY_WARNING); - }); - - it("should work in TUI mode (when available)", async () => { - await createTestConfig(context, testConfig); - - // Test TUI mode behavior (though it may fail in test environment) - const result = await runCLI(context, { - args: ["--config", context.configPath!], - env: { - OPENAI_API_KEY: "test-key", - HOME: context.testDir, - USERPROFILE: context.testDir, - HOMEDRIVE: path.parse(context.testDir).root, - HOMEPATH: path.relative( - path.parse(context.testDir).root, - context.testDir, - ), - CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"), - }, - timeout: 3000, - expectError: true, - }); - - // Even if TUI fails to start properly in test environment, - // the warning should still be present in any output - const output = result.stdout + result.stderr; - if (output.includes("Continue")) { - // If we got any meaningful output, check for warning - expect(output).toContain(HOME_DIRECTORY_WARNING); - } - }); - }); - - describe("edge cases", () => { - it("should handle case where home directory cannot be determined", async () => { - await createTestConfig(context, testConfig); - - const result = await runCLI(context, { - args: ["-p", "--config", context.configPath!, "test prompt"], - env: { - OPENAI_API_KEY: "test-key", - CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"), - // Mask home directory environment variables so os.homedir() cannot derive a value - HOME: "", - USERPROFILE: "", - HOMEDRIVE: "", - HOMEPATH: "", - }, - timeout: 5000, - expectError: true, - }); - - // Should not crash when home directory cannot be determined - expect(result.exitCode).toBeDefined(); - const output = result.stdout + result.stderr; - // Should not show warning if home cannot be determined (and we're in headless mode anyway) - expect(output).not.toContain(HOME_DIRECTORY_WARNING); - }); - - it("should handle relative vs absolute path comparisons", async () => { - await createTestConfig(context, testConfig); - - // Use a HOME that is equivalent but not identical (e.g., with './') - const altHome = path.join(context.testDir, "."); - const result = await runCLI(context, { - args: ["-p", "--config", context.configPath!, "test prompt"], - env: { - OPENAI_API_KEY: "test-key", - HOME: altHome, - USERPROFILE: altHome, - HOMEDRIVE: path.parse(altHome).root, - HOMEPATH: path.relative(path.parse(altHome).root, altHome), - CONTINUE_GLOBAL_DIR: path.join(context.testDir, ".continue-global"), - }, - timeout: 5000, - expectError: true, - }); - - // Should handle path resolution correctly (no crash) - expect(result.exitCode).toBeDefined(); - }); - }); -}); diff --git a/extensions/cli/src/services/FileIndexService.test.ts b/extensions/cli/src/services/FileIndexService.test.ts index 9d5afb23a..193ca8b15 100644 --- a/extensions/cli/src/services/FileIndexService.test.ts +++ b/extensions/cli/src/services/FileIndexService.test.ts @@ -59,24 +59,25 @@ describe("FileIndexService", () => { expect(filePaths).toContain("README.md"); }); - it("should filter files correctly", async () => { + it("should filter files correctly with fzf", async () => { // Create test files fs.writeFileSync("component.tsx", "export default () =>
"); fs.writeFileSync("utils.ts", "export const util = () => {}"); - fs.writeFileSync("styles.css", ".test { color: red; }"); + fs.writeFileSync("readme.md", "# Documentation"); await service.initialize(); - // Test filtering by extension - const tsFiles = service.filterFiles("ts"); - expect(tsFiles.some((f) => f.path === "component.tsx")).toBe(true); - expect(tsFiles.some((f) => f.path === "utils.ts")).toBe(true); - expect(tsFiles.some((f) => f.path === "styles.css")).toBe(false); + // Test filtering with more specific terms that won't fuzzy match + const tsxFiles = await service.filterFiles("tsx"); + expect(tsxFiles.some((f) => f.path === "component.tsx")).toBe(true); + expect(tsxFiles.some((f) => f.path === "utils.ts")).toBe(false); + expect(tsxFiles.some((f) => f.path === "readme.md")).toBe(false); // Test filtering by name - const componentFiles = service.filterFiles("component"); + const componentFiles = await service.filterFiles("component"); expect(componentFiles.some((f) => f.path === "component.tsx")).toBe(true); expect(componentFiles.some((f) => f.path === "utils.ts")).toBe(false); + expect(componentFiles.some((f) => f.path === "readme.md")).toBe(false); }); it("should handle empty directory", async () => { @@ -123,7 +124,7 @@ describe("FileIndexService", () => { await service.initialize(); - const files = service.filterFiles(""); + const files = await service.filterFiles(""); expect(files[0].path).toBe("alpha.js"); expect(files[1].path).toBe("beta.js"); expect(files[2].path).toBe("zebra.js"); @@ -137,7 +138,7 @@ describe("FileIndexService", () => { await service.initialize(); - const filtered = service.filterFiles("test"); + const filtered = await service.filterFiles("test"); // Should include both files that match the filter expect(filtered.length).toBeGreaterThanOrEqual(2); @@ -155,7 +156,7 @@ describe("FileIndexService", () => { await service.initialize(); - const files = service.filterFiles("", 5); + const files = await service.filterFiles("", 5); expect(files.length).toBe(5); }); @@ -173,4 +174,36 @@ describe("FileIndexService", () => { await service.refreshIndex(); expect(service.getFiles().length).toBe(2); }); + + it("should handle fuzzy search with AsyncFzf", async () => { + // Create test files for fuzzy matching + fs.writeFileSync("user-service.ts", "export class UserService {}"); + fs.writeFileSync("user-model.ts", "export interface User {}"); + fs.writeFileSync("config.json", "{}"); + + await service.initialize(); + + // Test fuzzy search (should match both user files) + const userFiles = await service.filterFiles("usmo"); // us(er) mo(del) + expect(userFiles.length).equal(1); + expect(userFiles.some((f) => f.path === "user-model.ts")).toBe(true); + }); + + it("should find files with @ symbols when searched with @ pattern", async () => { + // Create test file with @ symbols in the name + fs.writeFileSync("test@123.txt", "test content"); + fs.writeFileSync("regular-file.js", "normal file"); + fs.writeFileSync("other@456.md", "other content"); + + await service.initialize(); + + // Search for "test@123" - should match "test@123.txt" + const results = await service.filterFiles("test@123"); + + expect(results.length).equal(1); + expect(results.some((f) => f.path === "test@123.txt")).toBe(true); + + // Should not match files that don't contain the @ pattern + expect(results.some((f) => f.path === "regular-file.js")).toBe(false); + }); }); diff --git a/extensions/cli/src/services/FileIndexService.ts b/extensions/cli/src/services/FileIndexService.ts index 3ef74c021..518ffe9c4 100644 --- a/extensions/cli/src/services/FileIndexService.ts +++ b/extensions/cli/src/services/FileIndexService.ts @@ -1,9 +1,7 @@ -import { glob, GlobOptionsWithFileTypesFalse } from "glob"; +import { fdir } from "fdir"; +import { AsyncFzf, FzfResultItem } from "fzf"; -import { FILE_IGNORE_PATTERNS, FILE_PATTERNS } from "../util/filePatterns.js"; -import { getFileWatcher } from "../util/fileWatcher.js"; -import { isGitRepo } from "../util/git.js"; -import { isInHomeDirectory } from "../util/isInHomeDirectory.js"; +import { FILE_IGNORE_PATTERNS } from "../util/filePatterns.js"; import { logger } from "../util/logger.js"; import { BaseService } from "./BaseService.js"; @@ -12,6 +10,7 @@ import { serviceContainer } from "./ServiceContainer.js"; export interface FileItem { path: string; displayName: string; + positions?: Set; } export interface FileIndexServiceState { @@ -21,9 +20,79 @@ export interface FileIndexServiceState { } export class FileIndexService extends BaseService { - private fileSet = new Set(); - private fileWatcherInitialized = false; - private fileWatcherUnsubscribe: (() => void) | null = null; + private fzf: AsyncFzf | null = null; + + // Helper to check if a file should be included based on FILE_PATTERNS + private shouldIncludeFile(filePath: string): boolean { + const fileName = filePath.split("/").pop()?.toLowerCase() || ""; + const ext = fileName.split(".").pop(); + + // Check if file matches any of the original FILE_PATTERNS + const supportedExtensions = [ + "ts", + "tsx", + "js", + "jsx", + "py", + "java", + "cpp", + "c", + "h", + "hpp", + "cs", + "go", + "rs", + "rb", + "php", + "swift", + "kt", + "scala", + "md", + "json", + "yaml", + "yml", + "xml", + "html", + "css", + "scss", + "sass", + "less", + "sql", + "sh", + "dockerfile", + "makefile", + "cmake", + "gradle", + "toml", + "ini", + "env", + "txt", + "log", + ]; + + // Check extension match + if (ext && supportedExtensions.includes(ext)) { + return true; + } + + // Check special file patterns + if ( + fileName.startsWith("readme") || + fileName.startsWith("license") || + fileName.startsWith("changelog") || + fileName === "package.json" || + fileName === "cargo.toml" || + fileName === "pyproject.toml" || + fileName === "composer.json" || + fileName === "gemfile" || + fileName === ".gitignore" || + fileName.startsWith(".env") + ) { + return true; + } + + return false; + } constructor() { super("FileIndexService", { @@ -35,23 +104,11 @@ export class FileIndexService extends BaseService { async doInitialize(): Promise { await this.performFullIndex(); - this.setupFileWatcher(); return this.getState(); } async cleanup(): Promise { - if (this.fileWatcherUnsubscribe) { - this.fileWatcherUnsubscribe(); - this.fileWatcherUnsubscribe = null; - } - - // Stop the file watcher to prevent resource leaks - if (this.fileWatcherInitialized) { - const watcher = getFileWatcher(); - watcher.stopWatching(); - } - - this.fileWatcherInitialized = false; + // No cleanup needed - no file watchers or subscriptions } /** @@ -65,37 +122,74 @@ export class FileIndexService extends BaseService { serviceContainer.set("fileIndex", currentState); } - private async performFullIndex(): Promise { + private async performFullIndex( + bypassTimeout: boolean = false, + ): Promise { this.setState({ isIndexing: true, error: null }); try { - const inGitRepo = isGitRepo(); + const currentDir = process.cwd(); + logger.debug(`Starting file index in directory: ${currentDir}`); - if (isInHomeDirectory()) { - this.setState({ - isIndexing: false, - error: "Skipping full index as in home directory", + // Create file indexing promise + const fileIndexPromise = new fdir() + .withFullPaths() + .withRelativePaths() + .filter((path) => { + // Use the helper function that implements original FILE_PATTERNS logic + return this.shouldIncludeFile(path); + }) + .exclude((dirName) => { + // Exclude directories based on FILE_IGNORE_PATTERNS + for (const pattern of FILE_IGNORE_PATTERNS) { + if (pattern.startsWith("**/") && pattern.endsWith("/**")) { + const excludeDirName = pattern.slice(3, -3); + if (dirName === excludeDirName) { + return true; + } + } + } + return false; + }) + .crawl(currentDir) + .withPromise(); + + let allFiles: string[]; + + if (bypassTimeout) { + // Manual refresh - wait for completion regardless of time + allFiles = await fileIndexPromise; + } else { + // Automatic indexing - race against 1-second timeout + const timeoutPromise = new Promise<"timeout">((resolve) => { + setTimeout(() => { + resolve("timeout"); + }, 1000); }); - return; + + const result = await Promise.race([fileIndexPromise, timeoutPromise]); + + if (result === "timeout") { + this.setState({ + files: [], + isIndexing: false, + error: "directory-too-large", + }); + return; + } + + allFiles = result as string[]; } - const allMatches = await this.throttledGlob(FILE_PATTERNS, { - maxDepth: inGitRepo ? 15 : 3, - ignore: FILE_IGNORE_PATTERNS, - dot: true, - absolute: false, - }); - - const uniqueFiles = [...new Set(allMatches)]; - this.fileSet.clear(); - uniqueFiles.forEach((file) => this.fileSet.add(file)); - - const files = uniqueFiles.map((path) => ({ + const fileItems = allFiles.map((path) => ({ path, displayName: path, })); - this.setState({ files, isIndexing: false }); + this.rebuildFzf(fileItems); + this.setState({ files: fileItems, isIndexing: false }); + + logger.debug(`Indexed ${fileItems.length} files`); } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error); @@ -104,116 +198,10 @@ export class FileIndexService extends BaseService { } } - private setupFileWatcher(): void { - if (this.fileWatcherInitialized) { - return; - } - - // Only enable file watching in git repositories - // Outside git repos (like home directory), file watching causes performance issues - // and provides little value since files change less predictably - const inGitRepo = isGitRepo(); - if (!inGitRepo) { - logger.debug("Skipping file watcher: not in a git repository"); - return; - } - - this.fileWatcherInitialized = true; - const watcher = getFileWatcher(); - - // Start watching the current directory - watcher.startWatching(); - - // Set up callback for incremental updates - this.fileWatcherUnsubscribe = watcher.onChange(() => { - this.handleFileSystemChange(); - }); - } - - private async handleFileSystemChange(): Promise { - try { - // Get current files from file system - const inGitRepo = isGitRepo(); - const allMatches = await this.throttledGlob(FILE_PATTERNS, { - maxDepth: inGitRepo ? 15 : 3, - ignore: FILE_IGNORE_PATTERNS, - dot: true, - absolute: false, - }); - - const currentFiles = new Set(allMatches); - const previousFiles = this.fileSet; - - // Find added and removed files - const addedFiles = [...currentFiles].filter( - (file) => !previousFiles.has(file), - ); - const removedFiles = [...previousFiles].filter( - (file) => !currentFiles.has(file), - ); - - // Only update if there are actual changes - if (addedFiles.length > 0 || removedFiles.length > 0) { - // Update internal file set - this.fileSet = currentFiles; - - // Create new files array - const files = [...currentFiles].map((path) => ({ - path, - displayName: path, - })); - - this.setState({ files }); - } - } catch (error) { - logger.error("Error handling file system change:", error); - const errorMessage = - error instanceof Error ? error.message : String(error); - this.setState({ error: errorMessage }); - } - } - - private async throttledGlob( - patterns: string[], - options: GlobOptionsWithFileTypesFalse, - batchSize = 100, - delay = 20, - ): Promise { - return new Promise((resolve, reject) => { - const allMatches: string[] = []; - let processed = 0; - let streamEnded = false; - - const globStream = glob.stream(patterns, options); - - globStream.on("data", (file: string) => { - allMatches.push(file); - processed++; - - if (processed % batchSize === 0) { - if (streamEnded) { - return; - } - globStream.pause(); - - setTimeout(() => { - if (streamEnded) { - return; - } - globStream.resume(); - }, delay); - } - }); - - globStream.on("end", () => { - streamEnded = true; - resolve(allMatches); - }); - - globStream.on("error", (err) => { - streamEnded = true; - reject(err); - }); + private rebuildFzf(files: FileItem[]): void { + this.fzf = new AsyncFzf(files, { + selector: (item: FileItem) => item.path, + casing: "case-insensitive", }); } @@ -230,11 +218,14 @@ export class FileIndexService extends BaseService { return this.getState().error; } - public async refreshIndex(): Promise { - await this.performFullIndex(); + public async refreshIndex(bypassTimeout: boolean = false): Promise { + await this.performFullIndex(bypassTimeout); } - public filterFiles(filterText: string, limit: number = 10): FileItem[] { + public async filterFiles( + filterText: string, + limit: number = 10, + ): Promise { const files = this.getFiles(); if (filterText.length === 0) { @@ -248,36 +239,16 @@ export class FileIndexService extends BaseService { .slice(0, limit); } - const lowerFilter = filterText.toLowerCase(); + // Use fzf for fuzzy search + if (!this.fzf) { + this.rebuildFzf(files); + } - return files - .filter((file) => { - return ( - file.displayName.toLowerCase().includes(lowerFilter) || - file.path.toLowerCase().includes(lowerFilter) - ); - }) - .sort((a, b) => { - const aFileName = a.path.split("/").pop() || a.path; - const bFileName = b.path.split("/").pop() || b.path; - - // Prioritize exact matches in file name - const aNameMatch = aFileName.toLowerCase().includes(lowerFilter); - const bNameMatch = bFileName.toLowerCase().includes(lowerFilter); - - if (aNameMatch && !bNameMatch) return -1; - if (!aNameMatch && bNameMatch) return 1; - - // Then prioritize files that start with the filter - const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter); - const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter); - - if (aStartsWith && !bStartsWith) return -1; - if (!aStartsWith && bStartsWith) return 1; - - // Finally, sort by file name - return aFileName.localeCompare(bFileName); - }) - .slice(0, limit); + const results = await this.fzf!.find(filterText); + return results.slice(0, limit).map((entry: FzfResultItem) => ({ + path: entry.item.path, + displayName: entry.item.displayName, + positions: entry.positions, + })); } } diff --git a/extensions/cli/src/ui/FileSearchUI.tsx b/extensions/cli/src/ui/FileSearchUI.tsx index 6c4d2c266..866c0af17 100644 --- a/extensions/cli/src/ui/FileSearchUI.tsx +++ b/extensions/cli/src/ui/FileSearchUI.tsx @@ -1,8 +1,12 @@ -import { Box, Text } from "ink"; +import { Box, Text, useInput } from "ink"; import React, { useEffect, useState } from "react"; import { useServices } from "../hooks/useService.js"; -import { FileIndexServiceState } from "../services/FileIndexService.js"; +import { + FileIndexServiceState, + FileItem, +} from "../services/FileIndexService.js"; +import { services } from "../services/index.js"; interface FileSearchUIProps { filter: string; @@ -11,10 +15,45 @@ interface FileSearchUIProps { onFilesUpdated?: (files: FileItem[]) => void; } -interface FileItem { - path: string; - displayName: string; -} +// Highlighting component for matched characters +const HighlightedText: React.FC<{ text: string; positions?: Set }> = ({ + text, + positions, +}) => { + if (!positions || positions.size === 0) { + return <>{text}; + } + + const chars = text.split(""); + const elements: React.ReactNode[] = []; + + chars.forEach((char, index) => { + if (positions.has(index)) { + elements.push( + + {char} + , + ); + } else { + elements.push(char); + } + }); + + return <>{elements}; +}; + +// Reusable container for consistent layout +const FileSearchContainer: React.FC<{ children: React.ReactNode }> = ({ + children, +}) => ( + + {children} + +); + +// Keyboard navigation shortcuts help text +const KEYBOARD_SHORTCUTS = + "↑/↓ to navigate, Enter to select, Tab to complete, Ctrl+r to refresh list"; const FileSearchUI: React.FC = ({ filter, @@ -23,89 +62,97 @@ const FileSearchUI: React.FC = ({ }) => { const [files, setFiles] = useState([]); - // Get file index service - const { services } = useServices<{ + // Get file index service state for reactive updates + const { services: serviceStates } = useServices<{ fileIndex: FileIndexServiceState; }>(["fileIndex"]); - const fileIndexService = services.fileIndex; + const fileIndexServiceState = serviceStates.fileIndex; useEffect(() => { - if (!fileIndexService) { + if (!fileIndexServiceState) { return; } - // Get filtered files from the service - const filteredFiles = fileIndexService.files - .filter((file) => { - if (filter.length === 0) { - return true; + // Use the FileIndexService's filterFiles method which includes fzf fuzzy matching + const fetchFilteredFiles = async () => { + try { + // console.log(`FileSearchUI: Filtering files with "${filter}", total files in state:`, fileIndexServiceState?.files?.length); + const filteredFiles = await services.fileIndex.filterFiles(filter, 10); + // console.log(`FileSearchUI: Filtered to ${filteredFiles.length} files`); + setFiles(filteredFiles); + + if (onFilesUpdated) { + onFilesUpdated(filteredFiles); } - const lowerFilter = filter.toLowerCase(); - return ( - file.displayName.toLowerCase().includes(lowerFilter) || - file.path.toLowerCase().includes(lowerFilter) - ); - }) - .sort((a, b) => { - if (filter.length === 0) { - // Sort alphabetically when no filter - const aFileName = a.path.split("/").pop() || a.path; - const bFileName = b.path.split("/").pop() || b.path; - return aFileName.localeCompare(bFileName); + } catch (error) { + // Suppress expected "search cancelled" errors from AsyncFzf when typing fast + const errorMessage = + error instanceof Error ? error.message : String(error); + if (!errorMessage.includes("search cancelled")) { + console.error("Error filtering files:", error); } + setFiles([]); + } + }; - const lowerFilter = filter.toLowerCase(); - const aFileName = a.path.split("/").pop() || a.path; - const bFileName = b.path.split("/").pop() || b.path; + fetchFilteredFiles(); + }, [fileIndexServiceState?.files, filter, onFilesUpdated]); - // Prioritize exact matches in file name - const aNameMatch = aFileName.toLowerCase().includes(lowerFilter); - const bNameMatch = bFileName.toLowerCase().includes(lowerFilter); - - if (aNameMatch && !bNameMatch) return -1; - if (!aNameMatch && bNameMatch) return 1; - - // Then prioritize files that start with the filter - const aStartsWith = aFileName.toLowerCase().startsWith(lowerFilter); - const bStartsWith = bFileName.toLowerCase().startsWith(lowerFilter); - - if (aStartsWith && !bStartsWith) return -1; - if (!aStartsWith && bStartsWith) return 1; - - // Finally, sort by file name - return aFileName.localeCompare(bFileName); - }) - .slice(0, 10); - - setFiles(filteredFiles); - - if (onFilesUpdated) { - onFilesUpdated(filteredFiles); + // Handle Ctrl+R to refresh file index + useInput((input, key) => { + if (key.ctrl && input === "r") { + services.fileIndex.refreshIndex(true); // Bypass timeout for manual refresh } - }, [fileIndexService?.files, filter, onFilesUpdated]); + }); - if (fileIndexService?.isIndexing) { + if (fileIndexServiceState?.error) { + // Special handling for directory too large error + if (fileIndexServiceState.error === "directory-too-large") { + return ( + + + Ctrl+r to refresh list (this may take several seconds) + + + ); + } + + // Other errors return ( - - Indexing files... - + + + Error indexing files: {fileIndexServiceState.error} + + ); } - if (fileIndexService?.error) { - return ( - - Error indexing files: {fileIndexService.error} - - ); - } + if (files.length === 0 && !fileIndexServiceState?.isIndexing) { + // Only show "No matching files found" if: + // 1. There are files in the index (so it's not a system issue) + // 2. There's actually a search filter (not just "@") + if ( + fileIndexServiceState?.files && + fileIndexServiceState.files.length > 0 && + filter.length > 0 + ) { + return ( + + + No matching files found + + + ); + } - if (files.length === 0) { + // Show keyboard navigation hints return ( - - No matching files found - + + + {KEYBOARD_SHORTCUTS} + + ); } @@ -118,7 +165,13 @@ const FileSearchUI: React.FC = ({ {" "} - @{file.displayName} + + @ + + ); @@ -126,7 +179,7 @@ const FileSearchUI: React.FC = ({ - ↑/↓ to navigate, Enter to select, Tab to complete + {KEYBOARD_SHORTCUTS} diff --git a/extensions/cli/src/ui/IntroMessage.tsx b/extensions/cli/src/ui/IntroMessage.tsx index 3adfc6a5a..1102c4717 100644 --- a/extensions/cli/src/ui/IntroMessage.tsx +++ b/extensions/cli/src/ui/IntroMessage.tsx @@ -4,16 +4,11 @@ import React, { useMemo } from "react"; import { getDisplayableAsciiArt } from "../asciiArt.js"; import { MCPService } from "../services/MCPService.js"; -import { isInHomeDirectory } from "../util/isInHomeDirectory.js"; import { isModelCapable } from "../utils/modelCapability.js"; import { ModelCapabilityWarning } from "./ModelCapabilityWarning.js"; import { TipsDisplay, shouldShowTip } from "./TipsDisplay.js"; -// Export the warning message for testing -export const HOME_DIRECTORY_WARNING = - "Run cn in a project directory for the best experience (currently in home directory)"; - interface IntroMessageProps { config?: AssistantUnrolled; model?: ModelConfig; @@ -27,8 +22,6 @@ const extractRuleNames = (rules: any[] = []): string[] => { ); }; -const userInHomeDirectory = isInHomeDirectory(); - const IntroMessage: React.FC = ({ config, model, @@ -139,14 +132,6 @@ const IntroMessage: React.FC = ({ {renderMcpPrompts()} {renderRules()} {renderMcpServers()} - - {/* Home directory warning */} - {userInHomeDirectory && ( - <> - {HOME_DIRECTORY_WARNING} - - - )} ); }; diff --git a/extensions/cli/src/ui/UserInput.tsx b/extensions/cli/src/ui/UserInput.tsx index 199e18fb2..238e06d49 100644 --- a/extensions/cli/src/ui/UserInput.tsx +++ b/extensions/cli/src/ui/UserInput.tsx @@ -167,8 +167,8 @@ const UserInput: React.FC = ({ >([]); const { exit } = useApp(); - // Get file index service - const { services } = useServices<{ + // Get file index service state for reactive updates (unused but needed for service initialization) + useServices<{ fileIndex: FileIndexServiceState; }>(["fileIndex"]); @@ -297,45 +297,39 @@ const UserInput: React.FC = ({ // Check if we're in a file search context const beforeCursor = text.slice(0, cursor); - const lastAtIndex = beforeCursor.lastIndexOf("@"); - if (lastAtIndex === -1) { - setShowFileSearch(false); - } else { - // Check if there's any whitespace between the last @ and cursor - const afterAt = beforeCursor.slice(lastAtIndex + 1); - - if (afterAt.includes(" ") || afterAt.includes("\n")) { - setShowFileSearch(false); - } else { - // We're in a file search context - check if there are matching files - const fileIndexService = services.fileIndex; - if (fileIndexService) { - const filteredFiles = fileIndexService.files.filter((file) => { - if (afterAt.length === 0) { - return true; - } - const lowerFilter = afterAt.toLowerCase(); - return ( - file.displayName.toLowerCase().includes(lowerFilter) || - file.path.toLowerCase().includes(lowerFilter) - ); - }); - - // If no files match, hide the dropdown to allow normal Enter behavior - if (filteredFiles.length === 0 && afterAt.length > 0) { - setShowFileSearch(false); - return; + // Find the first @ symbol that starts a file search context + // We need to find the last @ that has no space before it (or is at word boundary) + let firstAtIndex = -1; + for (let i = beforeCursor.length - 1; i >= 0; i--) { + if (beforeCursor[i] === "@") { + // Check if this @ is at the start of a word (preceded by space/newline or start of string) + const beforeAt = beforeCursor.slice(0, i); + const lastChar = beforeAt[beforeAt.length - 1]; + if (i === 0 || lastChar === " " || lastChar === "\n") { + // Check if there's any space/newline between this @ and cursor + const afterThis = beforeCursor.slice(i + 1); + if (!afterThis.includes(" ") && !afterThis.includes("\n")) { + firstAtIndex = i; + break; } } - - setShowFileSearch(true); - setFileSearchFilter(afterAt); - setSelectedFileIndex(0); - setShowSlashCommands(false); - setShowBashMode(false); } } + + if (firstAtIndex === -1) { + setShowFileSearch(false); + } else { + // Get ALL text after the @ symbol (including subsequent @ symbols) + const afterAt = beforeCursor.slice(firstAtIndex + 1); + + // We're in a file search context + setShowFileSearch(true); + setFileSearchFilter(afterAt); + setSelectedFileIndex(0); + setShowSlashCommands(false); + setShowBashMode(false); + } }; // Get filtered commands for navigation - using the same sorting logic as SlashCommandUI @@ -385,15 +379,32 @@ const UserInput: React.FC = ({ // Handle file selection const selectFile = async (filePath: string) => { const beforeCursor = inputText.slice(0, cursorPosition); - const lastAtIndex = beforeCursor.lastIndexOf("@"); - if (lastAtIndex !== -1) { - const beforeAt = inputText.slice(0, lastAtIndex); + // Find the first @ symbol that starts a file search context (same logic as updateFileSearchState) + let firstAtIndex = -1; + for (let i = beforeCursor.length - 1; i >= 0; i--) { + if (beforeCursor[i] === "@") { + // Check if this @ is at the start of a word (preceded by space/newline or start of string) + const beforeAt = beforeCursor.slice(0, i); + const lastChar = beforeAt[beforeAt.length - 1]; + if (i === 0 || lastChar === " " || lastChar === "\n") { + // Check if there's any space/newline between this @ and cursor + const afterThis = beforeCursor.slice(i + 1); + if (!afterThis.includes(" ") && !afterThis.includes("\n")) { + firstAtIndex = i; + break; + } + } + } + } + + if (firstAtIndex !== -1) { + const beforeAt = inputText.slice(0, firstAtIndex); const afterCursor = inputText.slice(cursorPosition); // Replace the partial file reference with the full file path const newText = beforeAt + "@" + filePath + " " + afterCursor; - const newCursorPos = lastAtIndex + 1 + filePath.length + 1; + const newCursorPos = firstAtIndex + 1 + filePath.length + 1; textBuffer.setText(newText); textBuffer.setCursor(newCursorPos); @@ -410,7 +421,14 @@ const UserInput: React.FC = ({ const content = await fs.readFile(absolutePath, "utf-8"); onFileAttached(absolutePath, content); } catch (error) { - console.error(`Error reading file ${filePath}:`, error); + // If file doesn't exist, just attach the filename without content + if (error instanceof Error && (error as any).code === "ENOENT") { + const path = await import("path"); + const absolutePath = path.resolve(filePath); + onFileAttached(absolutePath, filePath); + } else { + console.error(`Error reading file ${filePath}:`, error); + } } } } diff --git a/extensions/cli/src/ui/__tests__/UserInput.missingFile.test.tsx b/extensions/cli/src/ui/__tests__/UserInput.missingFile.test.tsx new file mode 100644 index 000000000..a0f6c41c6 --- /dev/null +++ b/extensions/cli/src/ui/__tests__/UserInput.missingFile.test.tsx @@ -0,0 +1,36 @@ +import * as path from "path"; + +import { describe, expect, it, vi } from "vitest"; + +// Test the missing file handling logic directly +describe("UserInput - Missing File Handling", () => { + it("should handle selecting non-existent files gracefully", async () => { + const mockOnFileAttached = vi.fn(); + + // Simulate the selectFile logic for a missing file + const filePath = "missing-file.txt"; + + try { + const fs = await import("fs/promises"); + const path = await import("path"); + const absolutePath = path.resolve(filePath); + const content = await fs.readFile(absolutePath, "utf-8"); + mockOnFileAttached(absolutePath, content); + } catch (error) { + // If file doesn't exist, just attach the filename without content + if (error instanceof Error && (error as any).code === "ENOENT") { + const path = await import("path"); + const absolutePath = path.resolve(filePath); + mockOnFileAttached(absolutePath, filePath); // Just the filename for missing file + } else { + console.error(`Error reading file ${filePath}:`, error); + } + } + + // Should have called onFileAttached with filename as content + expect(mockOnFileAttached).toHaveBeenCalledWith( + path.resolve(filePath), + filePath, + ); + }); +});