| 1 | import { jest } from "@jest/globals"; |
| 2 | import { execSync } from "node:child_process"; |
| 3 | import fs from "node:fs"; |
| 4 | import path from "path"; |
| 5 | |
| 6 | import { LLMError } from "../llm/index.js"; |
| 7 | import { testConfigHandler, testIde } from "../test/fixtures.js"; |
| 8 | import { |
| 9 | addToTestDir, |
| 10 | setUpTestDir, |
| 11 | tearDownTestDir, |
| 12 | TEST_DIR, |
| 13 | TEST_DIR_PATH, |
| 14 | } from "../test/testDir.js"; |
| 15 | import { getIndexSqlitePath } from "../util/paths.js"; |
| 16 | |
| 17 | import { localPathToUri } from "../util/pathToUri.js"; |
| 18 | import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; |
| 19 | import { getComputeDeleteAddRemove } from "./refreshIndex.js"; |
| 20 | import { TestCodebaseIndex } from "./TestCodebaseIndex.js"; |
| 21 | import { CodebaseIndex } from "./types.js"; |
| 22 | import { walkDir, walkDirCache } from "./walkDir.js"; |
| 23 | |
| 24 | jest.useFakeTimers(); |
| 25 | |
| 26 | const TEST_TS = `\ |
| 27 | function main() { |
| 28 | console.log("Hello, world!"); |
| 29 | } |
| 30 | |
| 31 | class Foo { |
| 32 | constructor(public bar: string) {} |
| 33 | } |
| 34 | `; |
| 35 | |
| 36 | const TEST_PY = `\ |
| 37 | def main(): |
| 38 | print("Hello, world!") |
| 39 | |
| 40 | class Foo: |
| 41 | def __init__(self, bar: str): |
| 42 | self.bar = bar |
| 43 | `; |
| 44 | |
| 45 | const TEST_RS = `\ |
| 46 | fn main() { |
| 47 | println!("Hello, world!"); |
| 48 | } |
| 49 | |
| 50 | struct Foo { |
| 51 | bar: String, |
| 52 | } |
| 53 | `; |
| 54 | |
| 55 | // A subclass of CodebaseIndexer that adds a new CodebaseIndex |
| 56 | class TestCodebaseIndexer extends CodebaseIndexer { |
| 57 | protected async getIndexesToBuild(): Promise<CodebaseIndex[]> { |
| 58 | return [new TestCodebaseIndex()]; |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | // Create a mock messenger type that doesn't require actual protocol imports |
| 63 | type MockMessengerType = { |
| 64 | send: jest.Mock; |
| 65 | request: jest.Mock; |
| 66 | invoke: jest.Mock; |
| 67 | on: jest.Mock; |
| 68 | onError: jest.Mock; |
| 69 | }; |
| 70 | |
| 71 | // These are more like integration tests, whereas we should separately test |
| 72 | // the individual CodebaseIndex classes |
| 73 | describe("CodebaseIndexer", () => { |
| 74 | const pauseToken = new PauseToken(false); |
| 75 | |
| 76 | // Replace mockProgressReporter with mockMessenger |
| 77 | const mockMessenger: MockMessengerType = { |
| 78 | send: jest.fn(), |
| 79 | request: jest.fn(async () => {}), |
| 80 | invoke: jest.fn(), |
| 81 | on: jest.fn(), |
| 82 | onError: jest.fn(), |
| 83 | }; |
| 84 | |
| 85 | const codebaseIndexer = new TestCodebaseIndexer( |
| 86 | testConfigHandler, |
| 87 | testIde, |
| 88 | mockMessenger as any, |
| 89 | false, |
| 90 | ); |
| 91 | const testIndex = new TestCodebaseIndex(); |
| 92 | |
| 93 | beforeAll(async () => { |
| 94 | tearDownTestDir(); |
| 95 | setUpTestDir(); |
| 96 | |
| 97 | execSync("git init", { cwd: TEST_DIR_PATH }); |
| 98 | execSync('git config user.email "test@example.com"', { |
| 99 | cwd: TEST_DIR_PATH, |
| 100 | }); |
| 101 | execSync('git config user.name "Test"', { cwd: TEST_DIR_PATH }); |
| 102 | }); |
| 103 | |
| 104 | afterAll(async () => { |
| 105 | tearDownTestDir(); |
| 106 | }); |
| 107 | |
| 108 | afterEach(() => { |
| 109 | walkDirCache.invalidate(); |
| 110 | jest.clearAllMocks(); |
| 111 | }); |
| 112 | |
| 113 | async function refreshIndex() { |
| 114 | const abortController = new AbortController(); |
| 115 | const abortSignal = abortController.signal; |
| 116 | |
| 117 | const updates = []; |
| 118 | for await (const update of codebaseIndexer.refreshDirs( |
| 119 | [TEST_DIR], |
| 120 | abortSignal, |
| 121 | )) { |
| 122 | updates.push(update); |
| 123 | } |
| 124 | return updates; |
| 125 | } |
| 126 | |
| 127 | async function getAllIndexedFiles() { |
| 128 | const files = await testIndex.getIndexedFilesForTags( |
| 129 | await testIde.getTags(testIndex.artifactId), |
| 130 | ); |
| 131 | return files; |
| 132 | } |
| 133 | |
| 134 | async function getIndexPlan() { |
| 135 | const workspaceFiles = await walkDir(TEST_DIR, testIde); |
| 136 | const [tag] = await testIde.getTags(testIndex.artifactId); |
| 137 | const stats = await testIde.getFileStats(workspaceFiles); |
| 138 | |
| 139 | const [results, lastUpdated, markComplete] = |
| 140 | await getComputeDeleteAddRemove( |
| 141 | tag, |
| 142 | { ...stats }, |
| 143 | (filepath) => testIde.readFile(filepath), |
| 144 | undefined, |
| 145 | ); |
| 146 | return results; |
| 147 | } |
| 148 | |
| 149 | async function expectPlan( |
| 150 | compute: number, |
| 151 | addTag: number, |
| 152 | removeTag: number, |
| 153 | del: number, |
| 154 | ) { |
| 155 | const plan = await getIndexPlan(); |
| 156 | expect(plan.compute).toHaveLength(compute); |
| 157 | expect(plan.addTag).toHaveLength(addTag); |
| 158 | expect(plan.removeTag).toHaveLength(removeTag); |
| 159 | expect(plan.del).toHaveLength(del); |
| 160 | return plan; |
| 161 | } |
| 162 | |
| 163 | test("should index test folder without problem", async () => { |
| 164 | addToTestDir([ |
| 165 | ["test.ts", TEST_TS], |
| 166 | ["py/main.py", TEST_PY], |
| 167 | ]); |
| 168 | |
| 169 | await expectPlan(2, 0, 0, 0); |
| 170 | |
| 171 | const updates = await refreshIndex(); |
| 172 | expect(updates.length).toBeGreaterThan(0); |
| 173 | }); |
| 174 | |
| 175 | test("should have created index folder with all necessary files", async () => { |
| 176 | const exists = await testIde.fileExists( |
| 177 | localPathToUri(getIndexSqlitePath()), |
| 178 | ); |
| 179 | expect(exists).toBe(true); |
| 180 | }); |
| 181 | |
| 182 | test("should have indexed all of the files", async () => { |
| 183 | const indexed = await getAllIndexedFiles(); |
| 184 | expect(indexed.length).toBe(2); |
| 185 | expect(indexed.some((file) => file.endsWith("test.ts"))).toBe(true); |
| 186 | expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true); |
| 187 | }); |
| 188 | |
| 189 | test("should successfuly re-index specific files", async () => { |
| 190 | // Could add more specific tests for this but uses similar logic |
| 191 | const before = await getAllIndexedFiles(); |
| 192 | await codebaseIndexer.refreshCodebaseIndexFiles(before); |
| 193 | |
| 194 | const after = await getAllIndexedFiles(); |
| 195 | expect(after.length).toBe(before.length); |
| 196 | }); |
| 197 | |
| 198 | test("should successfully re-index after adding a file", async () => { |
| 199 | addToTestDir([["main.rs", TEST_RS]]); |
| 200 | |
| 201 | await expectPlan(1, 0, 0, 0); |
| 202 | |
| 203 | const updates = await refreshIndex(); |
| 204 | expect(updates.length).toBeGreaterThan(0); |
| 205 | |
| 206 | // Check that the new file was indexed |
| 207 | const files = await getAllIndexedFiles(); |
| 208 | expect(files.length).toBe(3); |
| 209 | expect(files.some((file) => file.endsWith("main.rs"))).toBe(true); |
| 210 | }); |
| 211 | |
| 212 | test("should successfully re-index after deleting a file", async () => { |
| 213 | fs.rmSync(path.join(TEST_DIR_PATH, "main.rs")); |
| 214 | |
| 215 | await expectPlan(0, 0, 0, 1); |
| 216 | |
| 217 | const updates = await refreshIndex(); |
| 218 | expect(updates.length).toBeGreaterThan(0); |
| 219 | |
| 220 | // Check that the deleted file was removed from the index |
| 221 | const files = await getAllIndexedFiles(); |
| 222 | expect(files.length).toBe(2); |
| 223 | expect(files.every((file) => !file.endsWith("main.rs"))).toBe(true); |
| 224 | }); |
| 225 | |
| 226 | test("shouldn't index any files when nothing changed", async () => { |
| 227 | await expectPlan(0, 0, 0, 0); |
| 228 | const updates = await refreshIndex(); |
| 229 | expect(updates.length).toBeGreaterThan(0); |
| 230 | }); |
| 231 | |
| 232 | test("should create git repo for testing", async () => { |
| 233 | execSync( |
| 234 | `cd ${TEST_DIR_PATH} && git init && git checkout -b main && git add -A && git commit -m "First commit"`, |
| 235 | ); |
| 236 | }); |
| 237 | |
| 238 | test.skip("should only re-index the changed files when changing branches", async () => { |
| 239 | execSync(`cd ${TEST_DIR_PATH} && git checkout -b test2`); |
| 240 | // Rewriting the file |
| 241 | addToTestDir([["test.ts", "// This is different"]]); |
| 242 | |
| 243 | // Should re-compute test.ts, but just re-tag the .py file |
| 244 | await expectPlan(1, 1, 0, 0); |
| 245 | |
| 246 | execSync( |
| 247 | `cd ${TEST_DIR_PATH} && git add -A && git commit -m "Change .ts file"`, |
| 248 | ); |
| 249 | }); |
| 250 | |
| 251 | test.skip("shouldn't re-index anything when changing back to original branch", async () => { |
| 252 | execSync(`cd ${TEST_DIR_PATH} && git checkout main`); |
| 253 | await expectPlan(0, 0, 0, 0); |
| 254 | }); |
| 255 | |
| 256 | // New tests for the methods added from Core.ts |
| 257 | describe("New methods from Core.ts", () => { |
| 258 | // Simplified tests to focus on behavior, not implementation details |
| 259 | test("should call messenger with progress updates when refreshing codebase index", async () => { |
| 260 | jest |
| 261 | .spyOn(codebaseIndexer as any, "refreshDirs") |
| 262 | .mockImplementation(async function* () { |
| 263 | yield { status: "done", progress: 1, desc: "Completed" }; |
| 264 | }); |
| 265 | |
| 266 | await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]); |
| 267 | |
| 268 | expect(mockMessenger.request).toHaveBeenCalledWith( |
| 269 | "indexProgress", |
| 270 | expect.anything(), |
| 271 | ); |
| 272 | expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", { |
| 273 | providers: "all", |
| 274 | }); |
| 275 | }); |
| 276 | |
| 277 | test("should call messenger with progress updates when refreshing specific files", async () => { |
| 278 | jest |
| 279 | .spyOn(codebaseIndexer as any, "refreshFiles") |
| 280 | .mockImplementation(async function* () { |
| 281 | yield { status: "done", progress: 1, desc: "Completed" }; |
| 282 | }); |
| 283 | |
| 284 | await codebaseIndexer.refreshCodebaseIndexFiles(["/test/file.ts"]); |
| 285 | |
| 286 | expect(mockMessenger.request).toHaveBeenCalledWith( |
| 287 | "indexProgress", |
| 288 | expect.anything(), |
| 289 | ); |
| 290 | expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", { |
| 291 | providers: "all", |
| 292 | }); |
| 293 | }); |
| 294 | |
| 295 | test("should abort previous indexing when starting a new one", async () => { |
| 296 | // Set up a situation where indexingCancellationController exists |
| 297 | const mockAbort = jest.fn(); |
| 298 | const controller = { abort: mockAbort, signal: { aborted: false } }; |
| 299 | |
| 300 | // Access the private property in a type-safe way for testing |
| 301 | (codebaseIndexer as any).indexingCancellationController = controller; |
| 302 | |
| 303 | // Mock refreshDirs to return immediately |
| 304 | jest |
| 305 | .spyOn(codebaseIndexer as any, "refreshDirs") |
| 306 | .mockImplementation(async function* () { |
| 307 | yield { status: "done", progress: 1, desc: "Completed" }; |
| 308 | }); |
| 309 | |
| 310 | // Start indexing - this should call abort on the existing controller |
| 311 | await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]); |
| 312 | |
| 313 | // Verify abort was called |
| 314 | expect(mockAbort).toHaveBeenCalled(); |
| 315 | }); |
| 316 | |
| 317 | test("should handle errors properly during indexing", async () => { |
| 318 | const testError = new Error("Test indexing error"); |
| 319 | |
| 320 | // Mock console.log to avoid printing errors |
| 321 | const consoleLogSpy = jest |
| 322 | .spyOn(console, "log") |
| 323 | .mockImplementation(() => {}); |
| 324 | |
| 325 | // Mock refreshDirs to throw an error |
| 326 | jest |
| 327 | .spyOn(codebaseIndexer as any, "refreshDirs") |
| 328 | .mockImplementation(() => { |
| 329 | throw testError; |
| 330 | }); |
| 331 | |
| 332 | // We don't need to mock AbortController because we're mocking the entire refreshDirs call |
| 333 | await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]); |
| 334 | |
| 335 | // Use the first argument only for the assertion since the second argument doesn't match exactly |
| 336 | expect(consoleLogSpy).toHaveBeenCalledWith( |
| 337 | `Failed refreshing codebase index directories: Error: ${testError.message}`, |
| 338 | ); |
| 339 | expect(mockMessenger.request).toHaveBeenCalledWith( |
| 340 | "indexProgress", |
| 341 | expect.objectContaining({ |
| 342 | status: "failed", |
| 343 | }), |
| 344 | ); |
| 345 | |
| 346 | consoleLogSpy.mockRestore(); |
| 347 | }); |
| 348 | |
| 349 | test("should handle LLMError specially during indexing", async () => { |
| 350 | // Create a mock LLM |
| 351 | const mockLlm: any = { |
| 352 | providerName: "test-provider", |
| 353 | model: "test-model", |
| 354 | }; |
| 355 | |
| 356 | // Create a real LLMError |
| 357 | const llmError = new LLMError("Test LLM error", mockLlm); |
| 358 | |
| 359 | // Mock console.log to avoid printing errors |
| 360 | jest.spyOn(console, "log").mockImplementation(() => {}); |
| 361 | |
| 362 | // Mock refreshDirs to throw an LLMError |
| 363 | jest |
| 364 | .spyOn(codebaseIndexer as any, "refreshDirs") |
| 365 | .mockImplementation(() => { |
| 366 | throw llmError; |
| 367 | }); |
| 368 | |
| 369 | // We don't need to mock AbortController because we're mocking the entire refreshDirs call |
| 370 | await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]); |
| 371 | |
| 372 | expect(mockMessenger.request).toHaveBeenCalledWith( |
| 373 | "reportError", |
| 374 | llmError, |
| 375 | ); |
| 376 | expect(mockMessenger.request).toHaveBeenCalledWith( |
| 377 | "indexProgress", |
| 378 | expect.objectContaining({ |
| 379 | status: "failed", |
| 380 | desc: "Test LLM error", |
| 381 | }), |
| 382 | ); |
| 383 | }); |
| 384 | |
| 385 | test("should provide access to current indexing state", async () => { |
| 386 | const testState = { |
| 387 | progress: 0.5, |
| 388 | status: "indexing" as const, |
| 389 | desc: "Test state", |
| 390 | }; |
| 391 | |
| 392 | // Mock refreshDirs to set a specific state |
| 393 | jest |
| 394 | .spyOn(codebaseIndexer as any, "refreshDirs") |
| 395 | .mockImplementation(async function* () { |
| 396 | yield testState; |
| 397 | }); |
| 398 | |
| 399 | // We don't need to mock AbortController because we're mocking the entire refreshDirs call |
| 400 | await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]); |
| 401 | |
| 402 | // Check that the state was updated |
| 403 | expect(codebaseIndexer.currentIndexingState).toEqual(testState); |
| 404 | }); |
| 405 | }); |
| 406 | }); |