Elffuss BraidHub

kikocis/continue public

fc89067dc2f1 · 20.7 KiBRawPermalink
1/* eslint-disable max-lines-per-function */
2/* lint is not useful for test classes */
3import { jest } from "@jest/globals";
4import { execSync } from "node:child_process";
5import fs from "node:fs";
6import path from "path";
7
8import { LLMError } from "../llm/index.js";
9import { testConfigHandler, testIde } from "../test/fixtures.js";
10import {
11 addToTestDir,
12 setUpTestDir,
13 tearDownTestDir,
14 TEST_DIR,
15 TEST_DIR_PATH,
16} from "../test/testDir.js";
17import { getIndexSqlitePath } from "../util/paths.js";
18
19import { ConfigResult } from "@continuedev/config-yaml";
20import CodebaseContextProvider from "../context/providers/CodebaseContextProvider.js";
21import { ContinueConfig } from "../index.js";
22import { localPathToUri } from "../util/pathToUri.js";
23import { CodebaseIndexer } from "./CodebaseIndexer.js";
24import { getComputeDeleteAddRemove } from "./refreshIndex.js";
25import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
26import { CodebaseIndex } from "./types.js";
27import { walkDir, walkDirCache } from "./walkDir.js";
28
29jest.useFakeTimers();
30
31const TEST_TS = `\
32function main() {
33 console.log("Hello, world!");
34}
35
36class Foo {
37 constructor(public bar: string) {}
38}
39`;
40
41const TEST_PY = `\
42def main():
43 print("Hello, world!")
44
45class Foo:
46 def __init__(self, bar: str):
47 self.bar = bar
48`;
49
50const TEST_RS = `\
51fn main() {
52 println!("Hello, world!");
53}
54
55struct Foo {
56 bar: String,
57}
58`;
59
60// A subclass of CodebaseIndexer that adds a new CodebaseIndex
61class TestCodebaseIndexer extends CodebaseIndexer {
62 protected async getIndexesToBuild(): Promise<CodebaseIndex[]> {
63 return [new TestCodebaseIndex()];
64 }
65
66 // Add public methods to test private methods
67 public testHasIndexingProvider() {
68 return (this as any).hasIndexingContextProvider();
69 }
70
71 public async testHandleConfigUpdate(
72 configResult: ConfigResult<ContinueConfig>,
73 ) {
74 return (this as any).handleConfigUpdate({ config: configResult.config });
75 }
76}
77
78// Create a mock messenger type that doesn't require actual protocol imports
79type MockMessengerType = {
80 send: jest.Mock;
81 request: jest.Mock;
82 invoke: jest.Mock;
83 on: jest.Mock;
84 onError: jest.Mock;
85};
86
87// These are more like integration tests, whereas we should separately test
88// the individual CodebaseIndex classes
89describe("CodebaseIndexer", () => {
90 // Replace mockProgressReporter with mockMessenger
91 const mockMessenger: MockMessengerType = {
92 send: jest.fn(),
93 request: jest.fn(async () => {}),
94 invoke: jest.fn(),
95 on: jest.fn(),
96 onError: jest.fn(),
97 };
98
99 let codebaseIndexer: TestCodebaseIndexer;
100 let testIndex: TestCodebaseIndex;
101
102 beforeAll(async () => {
103 tearDownTestDir();
104 setUpTestDir();
105
106 execSync("git init", { cwd: TEST_DIR_PATH });
107 execSync('git config user.email "test@example.com"', {
108 cwd: TEST_DIR_PATH,
109 });
110 execSync('git config user.name "Test"', { cwd: TEST_DIR_PATH });
111
112 codebaseIndexer = new TestCodebaseIndexer(
113 testConfigHandler,
114 testIde,
115 mockMessenger as any,
116 false,
117 );
118 await codebaseIndexer.initPromise;
119 testIndex = new TestCodebaseIndex();
120 });
121
122 afterAll(async () => {
123 tearDownTestDir();
124 });
125
126 afterEach(() => {
127 walkDirCache.invalidate();
128 jest.clearAllMocks();
129 });
130
131 async function refreshIndex() {
132 const abortController = new AbortController();
133 const abortSignal = abortController.signal;
134
135 const updates = [];
136 for await (const update of codebaseIndexer.refreshDirs(
137 [TEST_DIR],
138 abortSignal,
139 )) {
140 updates.push(update);
141 }
142 return updates;
143 }
144
145 async function getAllIndexedFiles() {
146 const files = await testIndex.getIndexedFilesForTags(
147 await testIde.getTags(testIndex.artifactId),
148 );
149 return files;
150 }
151
152 async function getIndexPlan() {
153 const workspaceFiles = await walkDir(TEST_DIR, testIde);
154 const [tag] = await testIde.getTags(testIndex.artifactId);
155 const stats = await testIde.getFileStats(workspaceFiles);
156
157 const [results, lastUpdated, markComplete] =
158 await getComputeDeleteAddRemove(
159 tag,
160 { ...stats },
161 (filepath) => testIde.readFile(filepath),
162 undefined,
163 );
164 return results;
165 }
166
167 async function expectPlan(
168 compute: number,
169 addTag: number,
170 removeTag: number,
171 del: number,
172 ) {
173 const plan = await getIndexPlan();
174 expect(plan.compute).toHaveLength(compute);
175 expect(plan.addTag).toHaveLength(addTag);
176 expect(plan.removeTag).toHaveLength(removeTag);
177 expect(plan.del).toHaveLength(del);
178 return plan;
179 }
180
181 describe("Sequential Integration Tests", () => {
182 // These tests must run in sequence as they depend on each other
183 test("should index test folder without problem", async () => {
184 walkDirCache.invalidate();
185 addToTestDir([
186 ["test.ts", TEST_TS],
187 ["py/main.py", TEST_PY],
188 ]);
189
190 await expectPlan(2, 0, 0, 0);
191
192 const updates = await refreshIndex();
193 expect(updates.length).toBeGreaterThan(0);
194 });
195
196 test("should have created index folder with all necessary files", async () => {
197 const exists = await testIde.fileExists(
198 localPathToUri(getIndexSqlitePath()),
199 );
200 expect(exists).toBe(true);
201 });
202
203 test("should have indexed all of the files", async () => {
204 const indexed = await getAllIndexedFiles();
205 expect(indexed.length).toBe(2);
206 expect(indexed.some((file) => file.endsWith("test.ts"))).toBe(true);
207 expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true);
208 });
209
210 test("should successfuly re-index specific files", async () => {
211 // Could add more specific tests for this but uses similar logic
212 const before = await getAllIndexedFiles();
213 await codebaseIndexer.refreshCodebaseIndexFiles(before);
214
215 const after = await getAllIndexedFiles();
216 expect(after.length).toBe(before.length);
217 });
218
219 test("should successfully re-index after adding a file", async () => {
220 addToTestDir([["main.rs", TEST_RS]]);
221
222 await expectPlan(1, 0, 0, 0);
223
224 const updates = await refreshIndex();
225 expect(updates.length).toBeGreaterThan(0);
226
227 // Check that the new file was indexed
228 const files = await getAllIndexedFiles();
229 expect(files.length).toBe(3);
230 expect(files.some((file) => file.endsWith("main.rs"))).toBe(true);
231 });
232
233 test("should successfully re-index after deleting a file", async () => {
234 fs.rmSync(path.join(TEST_DIR_PATH, "main.rs"));
235
236 await expectPlan(0, 0, 0, 1);
237
238 const updates = await refreshIndex();
239 expect(updates.length).toBeGreaterThan(0);
240
241 // Check that the deleted file was removed from the index
242 const files = await getAllIndexedFiles();
243 expect(files.length).toBe(2);
244 expect(files.every((file) => !file.endsWith("main.rs"))).toBe(true);
245 });
246
247 test("shouldn't index any files when nothing changed", async () => {
248 await expectPlan(0, 0, 0, 0);
249 const updates = await refreshIndex();
250 expect(updates.length).toBeGreaterThan(0);
251 });
252
253 test("should create git repo for testing", async () => {
254 execSync(
255 `cd ${TEST_DIR_PATH} && git init && git checkout -b main && git add -A && git commit -m "First commit"`,
256 );
257 });
258
259 test.skip("should only re-index the changed files when changing branches", async () => {
260 execSync(`cd ${TEST_DIR_PATH} && git checkout -b test2`);
261 // Rewriting the file
262 addToTestDir([["test.ts", "// This is different"]]);
263
264 // Should re-compute test.ts, but just re-tag the .py file
265 await expectPlan(1, 1, 0, 0);
266
267 execSync(
268 `cd ${TEST_DIR_PATH} && git add -A && git commit -m "Change .ts file"`,
269 );
270 });
271
272 test.skip("shouldn't re-index anything when changing back to original branch", async () => {
273 execSync(`cd ${TEST_DIR_PATH} && git checkout main`);
274 await expectPlan(0, 0, 0, 0);
275 });
276 });
277
278 // Isolated unit tests for Core.ts methods
279 describe("Core.ts Methods (Isolated Unit Tests)", () => {
280 beforeAll(async () => {
281 // Clear database to ensure these tests don't interfere with sequential integration tests
282 await testIndex.clearDatabase();
283 });
284
285 afterEach(async () => {
286 // Clear after each test to ensure full isolation within this group
287 await testIndex.clearDatabase();
288 });
289
290 // Simplified tests to focus on behavior, not implementation details
291 test("should call messenger with progress updates when refreshing codebase index", async () => {
292 jest
293 .spyOn(codebaseIndexer as any, "refreshDirs")
294 .mockImplementation(async function* () {
295 yield { status: "done", progress: 1, desc: "Completed" };
296 });
297
298 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
299
300 expect(mockMessenger.request).toHaveBeenCalledWith(
301 "indexProgress",
302 expect.anything(),
303 );
304 expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
305 providers: "all",
306 });
307 });
308
309 test("should call messenger with progress updates when refreshing specific files", async () => {
310 jest
311 .spyOn(codebaseIndexer as any, "refreshFiles")
312 .mockImplementation(async function* () {
313 yield { status: "done", progress: 1, desc: "Completed" };
314 });
315
316 await codebaseIndexer.refreshCodebaseIndexFiles(["/test/file.ts"]);
317
318 expect(mockMessenger.request).toHaveBeenCalledWith(
319 "indexProgress",
320 expect.anything(),
321 );
322 expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
323 providers: "all",
324 });
325 });
326
327 test("should abort previous indexing when starting a new one", async () => {
328 // Set up a situation where indexingCancellationController exists
329 const mockAbort = jest.fn();
330 const controller = { abort: mockAbort, signal: { aborted: false } };
331
332 // Access the private property in a type-safe way for testing
333 (codebaseIndexer as any).indexingCancellationController = controller;
334
335 // Mock refreshDirs to return immediately
336 jest
337 .spyOn(codebaseIndexer as any, "refreshDirs")
338 .mockImplementation(async function* () {
339 yield { status: "done", progress: 1, desc: "Completed" };
340 });
341
342 // Start indexing - this should call abort on the existing controller
343 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
344
345 // Verify abort was called
346 expect(mockAbort).toHaveBeenCalled();
347 });
348
349 test("should handle errors properly during indexing", async () => {
350 const testError = new Error("Test indexing error");
351
352 // Mock console.log to avoid printing errors
353 const consoleLogSpy = jest
354 .spyOn(console, "log")
355 .mockImplementation(() => {});
356
357 // Mock refreshDirs to throw an error
358 jest
359 .spyOn(codebaseIndexer as any, "refreshDirs")
360 .mockImplementation(() => {
361 throw testError;
362 });
363
364 // We don't need to mock AbortController because we're mocking the entire refreshDirs call
365 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
366
367 // Use the first argument only for the assertion since the second argument doesn't match exactly
368 expect(consoleLogSpy).toHaveBeenCalledWith(
369 `Failed refreshing codebase index directories: Error: ${testError.message}`,
370 );
371 expect(mockMessenger.request).toHaveBeenCalledWith(
372 "indexProgress",
373 expect.objectContaining({
374 status: "failed",
375 }),
376 );
377
378 consoleLogSpy.mockRestore();
379 });
380
381 test("should handle LLMError specially during indexing", async () => {
382 // Create a mock LLM
383 const mockLlm: any = {
384 providerName: "test-provider",
385 model: "test-model",
386 };
387
388 // Create a real LLMError
389 const llmError = new LLMError("Test LLM error", mockLlm);
390
391 // Mock console.log to avoid printing errors
392 jest.spyOn(console, "log").mockImplementation(() => {});
393
394 // Mock refreshDirs to throw an LLMError
395 jest
396 .spyOn(codebaseIndexer as any, "refreshDirs")
397 .mockImplementation(() => {
398 throw llmError;
399 });
400
401 // We don't need to mock AbortController because we're mocking the entire refreshDirs call
402 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
403
404 expect(mockMessenger.request).toHaveBeenCalledWith(
405 "reportError",
406 llmError,
407 );
408 expect(mockMessenger.request).toHaveBeenCalledWith(
409 "indexProgress",
410 expect.objectContaining({
411 status: "failed",
412 desc: "Test LLM error",
413 }),
414 );
415 });
416
417 test("should provide access to current indexing state", async () => {
418 const testState = {
419 progress: 0.5,
420 status: "indexing" as const,
421 desc: "Test state",
422 };
423
424 // Mock refreshDirs to set a specific state
425 jest
426 .spyOn(codebaseIndexer as any, "refreshDirs")
427 .mockImplementation(async function* () {
428 yield testState;
429 });
430
431 // We don't need to mock AbortController because we're mocking the entire refreshDirs call
432 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
433
434 // Check that the state was updated
435 expect(codebaseIndexer.currentIndexingState).toEqual(testState);
436 });
437 });
438
439 // Isolated unit tests for configuration handling
440 describe("Configuration Handling (Isolated Unit Tests)", () => {
441 beforeAll(async () => {
442 // Clear database to ensure these tests don't interfere with other tests
443 await testIndex.clearDatabase();
444 });
445
446 afterEach(async () => {
447 // Clear after each test to ensure full isolation within this group
448 await testIndex.clearDatabase();
449 });
450 let testIndexer: TestCodebaseIndexer;
451 let mockRefreshCodebaseIndex: jest.MockedFunction<any>;
452 let mockGetWorkspaceDirs: jest.MockedFunction<any>;
453
454 beforeEach(() => {
455 testIndexer = new TestCodebaseIndexer(
456 testConfigHandler,
457 testIde,
458 mockMessenger as any,
459 false,
460 );
461
462 // Mock the refreshCodebaseIndex method to avoid actual indexing
463 mockRefreshCodebaseIndex = jest
464 .spyOn(testIndexer, "refreshCodebaseIndex")
465 .mockImplementation(async () => {});
466
467 // Mock getWorkspaceDirs to return test directories
468 mockGetWorkspaceDirs = jest
469 .spyOn(testIde, "getWorkspaceDirs")
470 .mockResolvedValue(["/test/workspace"]);
471 });
472
473 afterEach(() => {
474 jest.clearAllMocks();
475 });
476
477 describe("hasIndexingProvider", () => {
478 test("should return true when codebase context provider is present", () => {
479 // Set up config with codebase context provider
480 (testIndexer as any).config = {
481 contextProviders: [new CodebaseContextProvider({})],
482 };
483
484 const result = testIndexer.testHasIndexingProvider();
485 expect(result).toBe(true);
486 });
487
488 test("should return false when no context providers are configured", () => {
489 (testIndexer as any).config = {
490 contextProviders: undefined,
491 };
492
493 const result = testIndexer.testHasIndexingProvider();
494 expect(result).toBe(false);
495 });
496
497 test("should return false when context providers exist but no codebase provider", () => {
498 (testIndexer as any).config = {
499 contextProviders: [
500 {
501 description: {
502 title: "SomeOtherProvider",
503 },
504 },
505 ],
506 };
507
508 const result = testIndexer.testHasIndexingProvider();
509 expect(result).toBe(false);
510 });
511
512 test("should return false when context providers is empty array", () => {
513 (testIndexer as any).config = {
514 contextProviders: [],
515 };
516
517 const result = testIndexer.testHasIndexingProvider();
518 expect(result).toBe(false);
519 });
520 });
521
522 describe("handleConfigUpdate", () => {
523 test("should return early when newConfig is null", async () => {
524 const configResult: ConfigResult<ContinueConfig> = {
525 config: null as any,
526 errors: [],
527 configLoadInterrupted: false,
528 };
529
530 await testIndexer.testHandleConfigUpdate(configResult);
531
532 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0);
533 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0);
534 });
535
536 test("should return early when newConfig is undefined", async () => {
537 const configResult: ConfigResult<ContinueConfig> = {
538 config: undefined as any,
539 errors: [],
540 configLoadInterrupted: false,
541 };
542
543 await testIndexer.testHandleConfigUpdate(configResult);
544
545 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0);
546 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0);
547 });
548
549 test("should return early when no codebase context provider is present", async () => {
550 const configResult: ConfigResult<ContinueConfig> = {
551 config: {
552 contextProviders: [
553 {
554 description: {
555 title: "SomeOtherProvider",
556 },
557 },
558 ],
559 selectedModelByRole: {
560 embed: {
561 model: "test-model",
562 provider: "test-provider",
563 },
564 },
565 } as unknown as ContinueConfig,
566 errors: [],
567 configLoadInterrupted: false,
568 };
569
570 await testIndexer.testHandleConfigUpdate(configResult);
571
572 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0);
573 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0);
574 });
575
576 test("should return early when no embed model is configured", async () => {
577 const configResult: ConfigResult<ContinueConfig> = {
578 config: {
579 contextProviders: [new CodebaseContextProvider({})],
580 selectedModelByRole: {
581 embed: undefined,
582 },
583 } as unknown as ContinueConfig,
584 errors: [],
585 configLoadInterrupted: false,
586 };
587
588 await testIndexer.testHandleConfigUpdate(configResult);
589
590 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(0);
591 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(0);
592 });
593
594 test("should call refreshCodebaseIndex when all conditions are met", async () => {
595 const configResult: ConfigResult<ContinueConfig> = {
596 config: {
597 contextProviders: [new CodebaseContextProvider({})],
598 selectedModelByRole: {
599 embed: {
600 model: "test-model",
601 provider: "test-provider",
602 },
603 },
604 } as unknown as ContinueConfig,
605 errors: [],
606 configLoadInterrupted: false,
607 };
608
609 await testIndexer.testHandleConfigUpdate(configResult);
610
611 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
612 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
613 expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
614 "/test/workspace",
615 ]);
616 });
617
618 test("should set config property before checking conditions", async () => {
619 const testConfig = {
620 contextProviders: [new CodebaseContextProvider({})],
621 selectedModelByRole: {
622 embed: {
623 model: "test-model",
624 provider: "test-provider",
625 },
626 },
627 } as unknown as ContinueConfig;
628
629 const configResult: ConfigResult<ContinueConfig> = {
630 config: testConfig,
631 errors: [],
632 configLoadInterrupted: false,
633 };
634
635 await testIndexer.testHandleConfigUpdate(configResult);
636
637 // Verify that the config was set
638 expect((testIndexer as any).config).toBe(testConfig);
639 // These get called once on init, and we want them to get called again
640 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
641 });
642
643 test("should handle multiple context providers correctly", async () => {
644 const configResult: ConfigResult<ContinueConfig> = {
645 config: {
646 contextProviders: [
647 {
648 description: {
649 title: "SomeOtherProvider",
650 },
651 },
652 new CodebaseContextProvider({}),
653 {
654 description: {
655 title: "AnotherProvider",
656 },
657 },
658 ],
659 selectedModelByRole: {
660 embed: {
661 model: "test-model",
662 provider: "test-provider",
663 },
664 },
665 } as unknown as ContinueConfig,
666 errors: [],
667 configLoadInterrupted: false,
668 };
669
670 await testIndexer.testHandleConfigUpdate(configResult);
671
672 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
673 expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
674 "/test/workspace",
675 ]);
676 });
677 });
678 });
679});