Elffuss BraidHub

kikocis/continue public

627d7d0d1f85 · 20.9 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 testHasCodebaseContextProvider() {
68 return (this as any).hasCodebaseContextProvider();
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 test("should index test folder without problem", async () => {
182 walkDirCache.invalidate();
183 addToTestDir([
184 ["test.ts", TEST_TS],
185 ["py/main.py", TEST_PY],
186 ]);
187
188 await expectPlan(2, 0, 0, 0);
189
190 const updates = await refreshIndex();
191 expect(updates.length).toBeGreaterThan(0);
192 });
193
194 test("should have created index folder with all necessary files", async () => {
195 const exists = await testIde.fileExists(
196 localPathToUri(getIndexSqlitePath()),
197 );
198 expect(exists).toBe(true);
199 });
200
201 test("should have indexed all of the files", async () => {
202 const indexed = await getAllIndexedFiles();
203 expect(indexed.length).toBe(2);
204 expect(indexed.some((file) => file.endsWith("test.ts"))).toBe(true);
205 expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true);
206 });
207
208 test("should successfuly re-index specific files", async () => {
209 // Could add more specific tests for this but uses similar logic
210 const before = await getAllIndexedFiles();
211 await codebaseIndexer.refreshCodebaseIndexFiles(before);
212
213 const after = await getAllIndexedFiles();
214 expect(after.length).toBe(before.length);
215 });
216
217 test("should successfully re-index after adding a file", async () => {
218 addToTestDir([["main.rs", TEST_RS]]);
219
220 await expectPlan(1, 0, 0, 0);
221
222 const updates = await refreshIndex();
223 expect(updates.length).toBeGreaterThan(0);
224
225 // Check that the new file was indexed
226 const files = await getAllIndexedFiles();
227 expect(files.length).toBe(3);
228 expect(files.some((file) => file.endsWith("main.rs"))).toBe(true);
229 });
230
231 test("should successfully re-index after deleting a file", async () => {
232 fs.rmSync(path.join(TEST_DIR_PATH, "main.rs"));
233
234 await expectPlan(0, 0, 0, 1);
235
236 const updates = await refreshIndex();
237 expect(updates.length).toBeGreaterThan(0);
238
239 // Check that the deleted file was removed from the index
240 const files = await getAllIndexedFiles();
241 expect(files.length).toBe(2);
242 expect(files.every((file) => !file.endsWith("main.rs"))).toBe(true);
243 });
244
245 test("shouldn't index any files when nothing changed", async () => {
246 await expectPlan(0, 0, 0, 0);
247 const updates = await refreshIndex();
248 expect(updates.length).toBeGreaterThan(0);
249 });
250
251 test("should create git repo for testing", async () => {
252 execSync(
253 `cd ${TEST_DIR_PATH} && git init && git checkout -b main && git add -A && git commit -m "First commit"`,
254 );
255 });
256
257 test.skip("should only re-index the changed files when changing branches", async () => {
258 execSync(`cd ${TEST_DIR_PATH} && git checkout -b test2`);
259 // Rewriting the file
260 addToTestDir([["test.ts", "// This is different"]]);
261
262 // Should re-compute test.ts, but just re-tag the .py file
263 await expectPlan(1, 1, 0, 0);
264
265 execSync(
266 `cd ${TEST_DIR_PATH} && git add -A && git commit -m "Change .ts file"`,
267 );
268 });
269
270 test.skip("shouldn't re-index anything when changing back to original branch", async () => {
271 execSync(`cd ${TEST_DIR_PATH} && git checkout main`);
272 await expectPlan(0, 0, 0, 0);
273 });
274
275 // New tests for the methods added from Core.ts
276 describe("New methods from Core.ts", () => {
277 // Simplified tests to focus on behavior, not implementation details
278 test("should call messenger with progress updates when refreshing codebase index", async () => {
279 jest
280 .spyOn(codebaseIndexer as any, "refreshDirs")
281 .mockImplementation(async function* () {
282 yield { status: "done", progress: 1, desc: "Completed" };
283 });
284
285 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
286
287 expect(mockMessenger.request).toHaveBeenCalledWith(
288 "indexProgress",
289 expect.anything(),
290 );
291 expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
292 providers: "all",
293 });
294 });
295
296 test("should call messenger with progress updates when refreshing specific files", async () => {
297 jest
298 .spyOn(codebaseIndexer as any, "refreshFiles")
299 .mockImplementation(async function* () {
300 yield { status: "done", progress: 1, desc: "Completed" };
301 });
302
303 await codebaseIndexer.refreshCodebaseIndexFiles(["/test/file.ts"]);
304
305 expect(mockMessenger.request).toHaveBeenCalledWith(
306 "indexProgress",
307 expect.anything(),
308 );
309 expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
310 providers: "all",
311 });
312 });
313
314 test("should abort previous indexing when starting a new one", async () => {
315 // Set up a situation where indexingCancellationController exists
316 const mockAbort = jest.fn();
317 const controller = { abort: mockAbort, signal: { aborted: false } };
318
319 // Access the private property in a type-safe way for testing
320 (codebaseIndexer as any).indexingCancellationController = controller;
321
322 // Mock refreshDirs to return immediately
323 jest
324 .spyOn(codebaseIndexer as any, "refreshDirs")
325 .mockImplementation(async function* () {
326 yield { status: "done", progress: 1, desc: "Completed" };
327 });
328
329 // Start indexing - this should call abort on the existing controller
330 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
331
332 // Verify abort was called
333 expect(mockAbort).toHaveBeenCalled();
334 });
335
336 test("should handle errors properly during indexing", async () => {
337 const testError = new Error("Test indexing error");
338
339 // Mock console.log to avoid printing errors
340 const consoleLogSpy = jest
341 .spyOn(console, "log")
342 .mockImplementation(() => {});
343
344 // Mock refreshDirs to throw an error
345 jest
346 .spyOn(codebaseIndexer as any, "refreshDirs")
347 .mockImplementation(() => {
348 throw testError;
349 });
350
351 // We don't need to mock AbortController because we're mocking the entire refreshDirs call
352 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
353
354 // Use the first argument only for the assertion since the second argument doesn't match exactly
355 expect(consoleLogSpy).toHaveBeenCalledWith(
356 `Failed refreshing codebase index directories: Error: ${testError.message}`,
357 );
358 expect(mockMessenger.request).toHaveBeenCalledWith(
359 "indexProgress",
360 expect.objectContaining({
361 status: "failed",
362 }),
363 );
364
365 consoleLogSpy.mockRestore();
366 });
367
368 test("should handle LLMError specially during indexing", async () => {
369 // Create a mock LLM
370 const mockLlm: any = {
371 providerName: "test-provider",
372 model: "test-model",
373 };
374
375 // Create a real LLMError
376 const llmError = new LLMError("Test LLM error", mockLlm);
377
378 // Mock console.log to avoid printing errors
379 jest.spyOn(console, "log").mockImplementation(() => {});
380
381 // Mock refreshDirs to throw an LLMError
382 jest
383 .spyOn(codebaseIndexer as any, "refreshDirs")
384 .mockImplementation(() => {
385 throw llmError;
386 });
387
388 // We don't need to mock AbortController because we're mocking the entire refreshDirs call
389 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
390
391 expect(mockMessenger.request).toHaveBeenCalledWith(
392 "reportError",
393 llmError,
394 );
395 expect(mockMessenger.request).toHaveBeenCalledWith(
396 "indexProgress",
397 expect.objectContaining({
398 status: "failed",
399 desc: "Test LLM error",
400 }),
401 );
402 });
403
404 test("should provide access to current indexing state", async () => {
405 const testState = {
406 progress: 0.5,
407 status: "indexing" as const,
408 desc: "Test state",
409 };
410
411 // Mock refreshDirs to set a specific state
412 jest
413 .spyOn(codebaseIndexer as any, "refreshDirs")
414 .mockImplementation(async function* () {
415 yield testState;
416 });
417
418 // We don't need to mock AbortController because we're mocking the entire refreshDirs call
419 await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
420
421 // Check that the state was updated
422 expect(codebaseIndexer.currentIndexingState).toEqual(testState);
423 });
424 });
425
426 // New describe block for testing handleConfigUpdate functionality
427 describe("handleConfigUpdate functionality", () => {
428 let testIndexer: TestCodebaseIndexer;
429 let mockRefreshCodebaseIndex: jest.MockedFunction<any>;
430 let mockGetWorkspaceDirs: jest.MockedFunction<any>;
431
432 beforeEach(() => {
433 testIndexer = new TestCodebaseIndexer(
434 testConfigHandler,
435 testIde,
436 mockMessenger as any,
437 false,
438 );
439
440 // Mock the refreshCodebaseIndex method to avoid actual indexing
441 mockRefreshCodebaseIndex = jest
442 .spyOn(testIndexer, "refreshCodebaseIndex")
443 .mockImplementation(async () => {});
444
445 // Mock getWorkspaceDirs to return test directories
446 mockGetWorkspaceDirs = jest
447 .spyOn(testIde, "getWorkspaceDirs")
448 .mockResolvedValue(["/test/workspace"]);
449 });
450
451 afterEach(() => {
452 jest.clearAllMocks();
453 });
454
455 describe("hasCodebaseContextProvider", () => {
456 test("should return true when codebase context provider is present", () => {
457 // Set up config with codebase context provider
458 (testIndexer as any).config = {
459 contextProviders: [
460 {
461 description: {
462 title: CodebaseContextProvider.description.title,
463 },
464 },
465 ],
466 };
467
468 const result = testIndexer.testHasCodebaseContextProvider();
469 expect(result).toBe(true);
470 });
471
472 test("should return false when no context providers are configured", () => {
473 (testIndexer as any).config = {
474 contextProviders: undefined,
475 };
476
477 const result = testIndexer.testHasCodebaseContextProvider();
478 expect(result).toBe(false);
479 });
480
481 test("should return false when context providers exist but no codebase provider", () => {
482 (testIndexer as any).config = {
483 contextProviders: [
484 {
485 description: {
486 title: "SomeOtherProvider",
487 },
488 },
489 ],
490 };
491
492 const result = testIndexer.testHasCodebaseContextProvider();
493 expect(result).toBe(false);
494 });
495
496 test("should return false when context providers is empty array", () => {
497 (testIndexer as any).config = {
498 contextProviders: [],
499 };
500
501 const result = testIndexer.testHasCodebaseContextProvider();
502 expect(result).toBe(false);
503 });
504 });
505
506 describe("handleConfigUpdate", () => {
507 test("should return early when newConfig is null", async () => {
508 const configResult: ConfigResult<ContinueConfig> = {
509 config: null as any,
510 errors: [],
511 configLoadInterrupted: false,
512 };
513
514 await testIndexer.testHandleConfigUpdate(configResult);
515
516 // These get called once on init, so we want them to not get called again
517 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
518 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
519 });
520
521 test("should return early when newConfig is undefined", async () => {
522 const configResult: ConfigResult<ContinueConfig> = {
523 config: undefined as any,
524 errors: [],
525 configLoadInterrupted: false,
526 };
527
528 await testIndexer.testHandleConfigUpdate(configResult);
529
530 // These get called once on init, so we want them to not get called again
531 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
532 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
533 });
534
535 test("should return early when no codebase context provider is present", async () => {
536 const configResult: ConfigResult<ContinueConfig> = {
537 config: {
538 contextProviders: [
539 {
540 description: {
541 title: "SomeOtherProvider",
542 },
543 },
544 ],
545 selectedModelByRole: {
546 embed: {
547 model: "test-model",
548 provider: "test-provider",
549 },
550 },
551 } as unknown as ContinueConfig,
552 errors: [],
553 configLoadInterrupted: false,
554 };
555
556 await testIndexer.testHandleConfigUpdate(configResult);
557
558 // These get called once on init, so we want them to not get called again
559 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
560 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
561 });
562
563 test("should return early when no embed model is configured", async () => {
564 const configResult: ConfigResult<ContinueConfig> = {
565 config: {
566 contextProviders: [
567 {
568 description: {
569 title: CodebaseContextProvider.description.title,
570 },
571 },
572 ],
573 selectedModelByRole: {
574 embed: undefined,
575 },
576 } as unknown as ContinueConfig,
577 errors: [],
578 configLoadInterrupted: false,
579 };
580
581 await testIndexer.testHandleConfigUpdate(configResult);
582
583 // These get called once on init, so we want them to not get called again
584 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(1);
585 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(1);
586 });
587
588 test("should call refreshCodebaseIndex when all conditions are met", async () => {
589 const configResult: ConfigResult<ContinueConfig> = {
590 config: {
591 contextProviders: [
592 {
593 description: {
594 title: CodebaseContextProvider.description.title,
595 },
596 },
597 ],
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 // These get called once on init, and we want them to get called again
612 expect(mockGetWorkspaceDirs).toHaveBeenCalledTimes(2);
613 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
614 expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
615 "/test/workspace",
616 ]);
617 });
618
619 test("should set config property before checking conditions", async () => {
620 const testConfig = {
621 contextProviders: [
622 {
623 description: {
624 title: CodebaseContextProvider.description.title,
625 },
626 },
627 ],
628 selectedModelByRole: {
629 embed: {
630 model: "test-model",
631 provider: "test-provider",
632 },
633 },
634 } as unknown as ContinueConfig;
635
636 const configResult: ConfigResult<ContinueConfig> = {
637 config: testConfig,
638 errors: [],
639 configLoadInterrupted: false,
640 };
641
642 await testIndexer.testHandleConfigUpdate(configResult);
643
644 // Verify that the config was set
645 expect((testIndexer as any).config).toBe(testConfig);
646 // These get called once on init, and we want them to get called again
647 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
648 });
649
650 test("should handle multiple context providers correctly", async () => {
651 const configResult: ConfigResult<ContinueConfig> = {
652 config: {
653 contextProviders: [
654 {
655 description: {
656 title: "SomeOtherProvider",
657 },
658 },
659 {
660 description: {
661 title: CodebaseContextProvider.description.title,
662 },
663 },
664 {
665 description: {
666 title: "AnotherProvider",
667 },
668 },
669 ],
670 selectedModelByRole: {
671 embed: {
672 model: "test-model",
673 provider: "test-provider",
674 },
675 },
676 } as unknown as ContinueConfig,
677 errors: [],
678 configLoadInterrupted: false,
679 };
680
681 await testIndexer.testHandleConfigUpdate(configResult);
682
683 // These get called once on init, and we want them to get called again
684 expect(mockRefreshCodebaseIndex).toHaveBeenCalledTimes(2);
685 expect(mockRefreshCodebaseIndex).toHaveBeenCalledWith([
686 "/test/workspace",
687 ]);
688 });
689 });
690 });
691});