feat: revamp efficient file search and support fuzzy matching
This commit is contained in:
parent
5f61d188e3
commit
c309bfb1be
9 changed files with 470 additions and 665 deletions
135
extensions/cli/package-lock.json
generated
135
extensions/cli/package-lock.json
generated
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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",
|
||||
|
|
|
|||
|
|
@ -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<string, string>[] = [
|
||||
// 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();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -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 () => <div></div>");
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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<number>;
|
||||
}
|
||||
|
||||
export interface FileIndexServiceState {
|
||||
|
|
@ -21,9 +20,79 @@ export interface FileIndexServiceState {
|
|||
}
|
||||
|
||||
export class FileIndexService extends BaseService<FileIndexServiceState> {
|
||||
private fileSet = new Set<string>();
|
||||
private fileWatcherInitialized = false;
|
||||
private fileWatcherUnsubscribe: (() => void) | null = null;
|
||||
private fzf: AsyncFzf<FileItem[]> | 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<FileIndexServiceState> {
|
|||
|
||||
async doInitialize(): Promise<FileIndexServiceState> {
|
||||
await this.performFullIndex();
|
||||
this.setupFileWatcher();
|
||||
return this.getState();
|
||||
}
|
||||
|
||||
async cleanup(): Promise<void> {
|
||||
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<FileIndexServiceState> {
|
|||
serviceContainer.set("fileIndex", currentState);
|
||||
}
|
||||
|
||||
private async performFullIndex(): Promise<void> {
|
||||
private async performFullIndex(
|
||||
bypassTimeout: boolean = false,
|
||||
): Promise<void> {
|
||||
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<FileIndexServiceState> {
|
|||
}
|
||||
}
|
||||
|
||||
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<void> {
|
||||
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<string[]> {
|
||||
return new Promise<string[]>((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<FileIndexServiceState> {
|
|||
return this.getState().error;
|
||||
}
|
||||
|
||||
public async refreshIndex(): Promise<void> {
|
||||
await this.performFullIndex();
|
||||
public async refreshIndex(bypassTimeout: boolean = false): Promise<void> {
|
||||
await this.performFullIndex(bypassTimeout);
|
||||
}
|
||||
|
||||
public filterFiles(filterText: string, limit: number = 10): FileItem[] {
|
||||
public async filterFiles(
|
||||
filterText: string,
|
||||
limit: number = 10,
|
||||
): Promise<FileItem[]> {
|
||||
const files = this.getFiles();
|
||||
|
||||
if (filterText.length === 0) {
|
||||
|
|
@ -248,36 +239,16 @@ export class FileIndexService extends BaseService<FileIndexServiceState> {
|
|||
.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<FileItem>) => ({
|
||||
path: entry.item.path,
|
||||
displayName: entry.item.displayName,
|
||||
positions: entry.positions,
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<number> }> = ({
|
||||
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(
|
||||
<Text key={index} color="white">
|
||||
{char}
|
||||
</Text>,
|
||||
);
|
||||
} else {
|
||||
elements.push(char);
|
||||
}
|
||||
});
|
||||
|
||||
return <>{elements}</>;
|
||||
};
|
||||
|
||||
// Reusable container for consistent layout
|
||||
const FileSearchContainer: React.FC<{ children: React.ReactNode }> = ({
|
||||
children,
|
||||
}) => (
|
||||
<Box paddingX={1} marginX={1} marginBottom={1} flexDirection="column">
|
||||
<Box marginTop={1}>{children}</Box>
|
||||
</Box>
|
||||
);
|
||||
|
||||
// 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<FileSearchUIProps> = ({
|
||||
filter,
|
||||
|
|
@ -23,89 +62,97 @@ const FileSearchUI: React.FC<FileSearchUIProps> = ({
|
|||
}) => {
|
||||
const [files, setFiles] = useState<FileItem[]>([]);
|
||||
|
||||
// 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 (
|
||||
<FileSearchContainer>
|
||||
<Text color="gray" dimColor>
|
||||
Ctrl+r to refresh list (this may take several seconds)
|
||||
</Text>
|
||||
</FileSearchContainer>
|
||||
);
|
||||
}
|
||||
|
||||
// Other errors
|
||||
return (
|
||||
<Box paddingX={1} marginX={1} marginBottom={1}>
|
||||
<Text color="gray">Indexing files...</Text>
|
||||
</Box>
|
||||
<FileSearchContainer>
|
||||
<Text color="red">
|
||||
Error indexing files: {fileIndexServiceState.error}
|
||||
</Text>
|
||||
</FileSearchContainer>
|
||||
);
|
||||
}
|
||||
|
||||
if (fileIndexService?.error) {
|
||||
return (
|
||||
<Box paddingX={1} marginX={1} marginBottom={1}>
|
||||
<Text color="red">Error indexing files: {fileIndexService.error}</Text>
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
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 (
|
||||
<FileSearchContainer>
|
||||
<Text color="gray" dimColor>
|
||||
No matching files found
|
||||
</Text>
|
||||
</FileSearchContainer>
|
||||
);
|
||||
}
|
||||
|
||||
if (files.length === 0) {
|
||||
// Show keyboard navigation hints
|
||||
return (
|
||||
<Box paddingX={1} marginX={1} marginBottom={1}>
|
||||
<Text color="gray">No matching files found</Text>
|
||||
</Box>
|
||||
<FileSearchContainer>
|
||||
<Text color="gray" dimColor>
|
||||
{KEYBOARD_SHORTCUTS}
|
||||
</Text>
|
||||
</FileSearchContainer>
|
||||
);
|
||||
}
|
||||
|
||||
|
|
@ -118,7 +165,13 @@ const FileSearchUI: React.FC<FileSearchUIProps> = ({
|
|||
<Box key={file.path}>
|
||||
<Text color="white" bold={isSelected}>
|
||||
{" "}
|
||||
<Text color="green">@{file.displayName}</Text>
|
||||
<Text color="green" dimColor={!isSelected}>
|
||||
@
|
||||
<HighlightedText
|
||||
text={file.displayName}
|
||||
positions={file.positions}
|
||||
/>
|
||||
</Text>
|
||||
</Text>
|
||||
</Box>
|
||||
);
|
||||
|
|
@ -126,7 +179,7 @@ const FileSearchUI: React.FC<FileSearchUIProps> = ({
|
|||
|
||||
<Box marginTop={1}>
|
||||
<Text color="gray" dimColor>
|
||||
↑/↓ to navigate, Enter to select, Tab to complete
|
||||
{KEYBOARD_SHORTCUTS}
|
||||
</Text>
|
||||
</Box>
|
||||
</Box>
|
||||
|
|
|
|||
|
|
@ -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<IntroMessageProps> = ({
|
||||
config,
|
||||
model,
|
||||
|
|
@ -139,14 +132,6 @@ const IntroMessage: React.FC<IntroMessageProps> = ({
|
|||
{renderMcpPrompts()}
|
||||
{renderRules()}
|
||||
{renderMcpServers()}
|
||||
|
||||
{/* Home directory warning */}
|
||||
{userInHomeDirectory && (
|
||||
<>
|
||||
<Text color="yellow">{HOME_DIRECTORY_WARNING}</Text>
|
||||
<Text> </Text>
|
||||
</>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -167,8 +167,8 @@ const UserInput: React.FC<UserInputProps> = ({
|
|||
>([]);
|
||||
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<UserInputProps> = ({
|
|||
|
||||
// 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<UserInputProps> = ({
|
|||
// 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<UserInputProps> = ({
|
|||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Reference in a new issue