diff --git a/core/.gitignore b/core/.gitignore index 646c15e7c..ad1c54334 100644 --- a/core/.gitignore +++ b/core/.gitignore @@ -3,4 +3,5 @@ target **/.DS_Store npm-debug.log* .env -.continue-test \ No newline at end of file +.continue-test +testDir \ No newline at end of file diff --git a/core/config/load.ts b/core/config/load.ts index 3077768d8..a9b2ba94f 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -587,7 +587,9 @@ async function loadFullConfigNode( // Try config.ts first const configJsPath = getConfigJsPath(); const module = await import(configJsPath); - delete require.cache[require.resolve(configJsPath)]; + if (typeof require !== "undefined") { + delete require.cache[require.resolve(configJsPath)]; + } if (!module.modifyConfig) { throw new Error("config.ts does not export a modifyConfig function."); } @@ -604,7 +606,9 @@ async function loadFullConfigNode( ideSettings.remoteConfigServerUrl, ); const module = await import(configJsPathForRemote); - delete require.cache[require.resolve(configJsPathForRemote)]; + if (typeof require !== "undefined") { + delete require.cache[require.resolve(configJsPathForRemote)]; + } if (!module.modifyConfig) { throw new Error("config.ts does not export a modifyConfig function."); } diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index efef51c72..7cc57a153 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -1,10 +1,10 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; import { IContinueServerClient } from "../continueServer/interface.js"; import { IDE, IndexTag, IndexingProgressUpdate } from "../index.js"; +import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js"; import { FullTextSearchCodebaseIndex } from "./FullTextSearch.js"; import { LanceDbIndex } from "./LanceDbIndex.js"; -import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js"; import { getComputeDeleteAddRemove } from "./refreshIndex.js"; import { CodebaseIndex, @@ -28,12 +28,12 @@ export class PauseToken { export class CodebaseIndexer { constructor( private readonly configHandler: ConfigHandler, - private readonly ide: IDE, + protected readonly ide: IDE, private readonly pauseToken: PauseToken, private readonly continueServerClient: IContinueServerClient, ) {} - private async getIndexesToBuild(): Promise { + protected async getIndexesToBuild(): Promise { const config = await this.configHandler.loadConfig(); const indexes = [ diff --git a/core/indexing/LanceDbIndex.ts b/core/indexing/LanceDbIndex.ts index 2e0054d5b..aefd24048 100644 --- a/core/indexing/LanceDbIndex.ts +++ b/core/indexing/LanceDbIndex.ts @@ -1,4 +1,5 @@ // NOTE: vectordb requirement must be listed in extensions/vscode to avoid error +import { RunResult } from "sqlite3"; import { v4 as uuidv4 } from "uuid"; import { Table } from "vectordb"; import { IContinueServerClient } from "../continueServer/interface.js"; @@ -20,7 +21,6 @@ import { PathAndCacheKey, RefreshIndexResults, } from "./types.js"; -import { RunResult } from "sqlite3"; // LanceDB converts to lowercase, so names must all be lowercase interface LanceDbRow { @@ -269,7 +269,15 @@ export class LanceDbIndex implements CodebaseIndex { console.log(results.compute); const dbRows = await this.computeRows(results.compute); - this.insertRows(sqlite, dbRows); + await this.insertRows(sqlite, dbRows); + await Promise.all( + results.compute.map((item) => { + addComputedLanceDbRows( + item, + dbRows.filter((row) => row.path === item.path), + ); + }), + ); await markComplete(results.compute, IndexResultType.Compute); let accumulatedProgress = 0; diff --git a/core/indexing/TestCodebaseIndex.ts b/core/indexing/TestCodebaseIndex.ts new file mode 100644 index 000000000..234bcbc3e --- /dev/null +++ b/core/indexing/TestCodebaseIndex.ts @@ -0,0 +1,69 @@ +import type { IndexTag, IndexingProgressUpdate } from "../index.js"; +import { DatabaseConnection, SqliteDb } from "./refreshIndex.js"; +import { + IndexResultType, + MarkCompleteCallback, + RefreshIndexResults, + type CodebaseIndex, +} from "./types.js"; + +/** + * This is a CodebaseIndex used for testing which files get indexed. + * It maintains a SQLite database of all file/tag pairs + */ +export class TestCodebaseIndex implements CodebaseIndex { + relativeExpectedTime: number = 0.1; + artifactId = "__test__"; + + private static async _createTables(db: DatabaseConnection) { + await db.exec(`CREATE TABLE IF NOT EXISTS test_index ( + id INTEGER PRIMARY KEY, + path TEXT NOT NULL, + branch TEXT NOT NULL, + directory TEXT NOT NULL + )`); + } + + async *update( + tag: IndexTag, + results: RefreshIndexResults, + markComplete: MarkCompleteCallback, + repoName: string | undefined, + ): AsyncGenerator { + const db = await SqliteDb.get(); + await TestCodebaseIndex._createTables(db); + + for (const item of [...results.compute, ...results.addTag]) { + await db.run( + `INSERT INTO test_index (path, branch, directory) VALUES (?, ?, ?)`, + [item.path, tag.branch, tag.directory], + ); + } + + for (const item of [...results.del, ...results.removeTag]) { + await db.run( + `DELETE FROM test_index WHERE path = ? AND branch = ? AND directory = ?`, + [item.path, tag.branch, tag.directory], + ); + } + + markComplete(results.compute, IndexResultType.Compute); + markComplete(results.addTag, IndexResultType.AddTag); + markComplete(results.del, IndexResultType.Delete); + markComplete(results.removeTag, IndexResultType.RemoveTag); + } + + async getIndexedFilesForTags(tags: IndexTag[]): Promise { + const db = await SqliteDb.get(); + await TestCodebaseIndex._createTables(db); + + const rows = await db.all( + `SELECT path FROM test_index WHERE (branch, directory) IN (VALUES ${tags + .map(() => "(?, ?)") + .join(", ")})`, + tags.flatMap((tag) => [tag.branch, tag.directory]), + ); + + return rows.map((row: any) => row.path); + } +} diff --git a/core/indexing/chunk/chunk.ts b/core/indexing/chunk/chunk.ts index 0cfd72fae..92adea72f 100644 --- a/core/indexing/chunk/chunk.ts +++ b/core/indexing/chunk/chunk.ts @@ -50,22 +50,24 @@ export async function* chunkDocument({ contents, maxChunkSize, )) { - chunkPromises.push(new Promise(async (resolve) => { - if (await countTokensAsync(chunkWithoutId.content) > maxChunkSize) { - console.debug( - `Chunk with more than ${maxChunkSize} tokens constructed: `, + chunkPromises.push( + new Promise(async (resolve) => { + if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) { + console.debug( + `Chunk with more than ${maxChunkSize} tokens constructed: `, + filepath, + countTokens(chunkWithoutId.content), + ); + return resolve(undefined); + } + resolve({ + ...chunkWithoutId, + digest, + index, filepath, - countTokens(chunkWithoutId.content), - ); - return resolve(undefined); - } - resolve({ - ...chunkWithoutId, - digest, - index, - filepath, - }); - })); + }); + }), + ); index++; } for await (const chunk of chunkPromises) { diff --git a/core/indexing/chunk/code.ts b/core/indexing/chunk/code.ts index ac0811212..7e3fff2b3 100644 --- a/core/indexing/chunk/code.ts +++ b/core/indexing/chunk/code.ts @@ -232,7 +232,7 @@ export async function* codeChunker( const parser = await getParserForFile(filepath); if (parser === undefined) { - console.warn(`Failed to load parser for file ${filepath}: `); + console.debug(`Failed to load parser for file ${filepath}: `); return; } diff --git a/core/jest.global-setup.ts b/core/jest.global-setup.ts index ee9cddde4..cf374a702 100644 --- a/core/jest.global-setup.ts +++ b/core/jest.global-setup.ts @@ -1,5 +1,9 @@ +import fs from "fs"; import path from "path"; export default async function () { process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test"); + if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) { + fs.rmSync(process.env.CONTINUE_GLOBAL_DIR, { recursive: true }); + } } diff --git a/core/llm/llms/SageMaker.ts b/core/llm/llms/SageMaker.ts index 02c6ed5b5..6a5890e67 100644 --- a/core/llm/llms/SageMaker.ts +++ b/core/llm/llms/SageMaker.ts @@ -1,17 +1,17 @@ import { - SageMakerRuntimeClient, - InvokeEndpointWithResponseStreamCommand + InvokeEndpointWithResponseStreamCommand, + SageMakerRuntimeClient } from "@aws-sdk/client-sagemaker-runtime"; import { fromIni } from "@aws-sdk/credential-providers"; -const jinja = require("jinja-js"); +// @ts-ignore +import jinja from "jinja-js"; import { ChatMessage, CompletionOptions, LLMOptions, - MessageContent, - ModelProvider, + ModelProvider } from "../../index.js"; import { BaseLLM } from "../index.js"; diff --git a/core/test/indexing/CodebaseIndexer.skip.ts b/core/test/indexing/CodebaseIndexer.skip.ts deleted file mode 100644 index df2d6518b..000000000 --- a/core/test/indexing/CodebaseIndexer.skip.ts +++ /dev/null @@ -1,178 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import { ConfigHandler } from "../../config/ConfigHandler.js"; -import { ContinueServerClient } from "../../continueServer/stubs/client.js"; -import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer.js"; -import { LanceDbIndex } from "../../indexing/LanceDbIndex.js"; -import TransformersJsEmbeddingsProvider from "../../indexing/embeddings/TransformersJsEmbeddingsProvider.js"; -import FileSystemIde from "../../util/filesystem.js"; -import { - getIndexFolderPath, - getIndexSqlitePath, - getLanceDbPath, -} from "../../util/paths.js"; -import { - addToTestDir, - setUpTestDir, - tearDownTestDir, - TEST_DIR, -} from "../testUtils/testDir.js"; -import { jest } from "@jest/globals"; - -jest.useFakeTimers(); - -const TEST_TS = `\ -function main() { - console.log("Hello, world!"); -} - -class Foo { - constructor(public bar: string) {} -} -`; - -const TEST_PY = `\ -def main(): - print("Hello, world!") - -class Foo: - def __init__(self, bar: str): - self.bar = bar -`; - -const TEST_RS = `\ -fn main() { - println!("Hello, world!"); -} - -struct Foo { - bar: String, -} -`; - -// These are more like integration tests, whereas we should separately test -// the individual CodebaseIndex classes -describe.skip("CodebaseIndexer", () => { - const ide = new FileSystemIde(TEST_DIR); - const ideSettingsPromise = ide.getIdeSettings(); - const configHandler = new ConfigHandler( - ide, - ideSettingsPromise, - async (text) => {}, - undefined as any, // TODO - ); - const pauseToken = new PauseToken(false); - const continueServerClient = new ContinueServerClient(undefined, undefined); - const codebaseIndexer = new CodebaseIndexer( - configHandler, - ide, - pauseToken, - continueServerClient, - ); - const lancedbIndex = new LanceDbIndex( - new TransformersJsEmbeddingsProvider(), - ide.readFile.bind(ide), - continueServerClient, - ); - - beforeAll(async () => { - setUpTestDir(); - }); - - afterAll(async () => { - tearDownTestDir(); - }); - - test("should index test folder without problem", async () => { - addToTestDir([ - ["test.ts", TEST_TS], - ["py/main.py", TEST_PY], - ]); - const abortController = new AbortController(); - const abortSignal = abortController.signal; - - const updates = []; - for await (const update of codebaseIndexer.refresh( - [TEST_DIR], - abortSignal, - )) { - updates.push(update); - } - - expect(updates.length).toBeGreaterThan(0); - }); - - test("should have created index folder with all necessary files", async () => { - expect(fs.existsSync(getIndexFolderPath())).toBe(true); - expect(fs.existsSync(getIndexSqlitePath())).toBe(true); - expect(fs.existsSync(getLanceDbPath())).toBe(true); - }); - - test("should be able to query lancedb index", async () => { - const chunks = await lancedbIndex.retrieve( - "What is the main function doing?", - 10, - await ide.getTags(lancedbIndex.artifactId), - undefined, - ); - - expect(chunks.length).toBe(2); - // Check that the main function from both files is returned - expect(chunks.some((chunk) => chunk.filepath.endsWith("test.ts"))).toBe( - true, - ); - expect(chunks.some((chunk) => chunk.filepath.endsWith("main.py"))).toBe( - true, - ); - }); - - test("should successfully re-index after adding a file", async () => { - addToTestDir([["main.rs", TEST_RS]]); - const abortController = new AbortController(); - const abortSignal = abortController.signal; - const updates = []; - for await (const update of codebaseIndexer.refresh( - [TEST_DIR], - abortSignal, - )) { - updates.push(update); - } - expect(updates.length).toBeGreaterThan(0); - // Check that the new file was indexed - const chunks = await lancedbIndex.retrieve( - "What is the main function doing?", - 3, - await ide.getTags(lancedbIndex.artifactId), - undefined, - ); - expect(chunks.length).toBe(3); - expect(chunks.some((chunk) => chunk.filepath.endsWith("main.rs"))).toBe( - true, - ); - }); - - test("should successfully re-index after deleting a file", async () => { - fs.rmSync(path.join(TEST_DIR, "main.rs")); - const abortController = new AbortController(); - const abortSignal = abortController.signal; - const updates = []; - for await (const update of codebaseIndexer.refresh( - [TEST_DIR], - abortSignal, - )) { - updates.push(update); - } - expect(updates.length).toBeGreaterThan(0); - // Check that the deleted file was removed from the index - const chunks = await lancedbIndex.retrieve( - "What is the main function doing?", - 10, - await ide.getTags(lancedbIndex.artifactId), - undefined, - ); - expect(chunks.length).toBe(2); - expect(chunks.every((chunk) => !chunk.filepath.endsWith("main.rs"))).toBe( - true, - ); - }); -}); diff --git a/core/test/indexing/CodebaseIndexer.test.ts b/core/test/indexing/CodebaseIndexer.test.ts new file mode 100644 index 000000000..7e92d0865 --- /dev/null +++ b/core/test/indexing/CodebaseIndexer.test.ts @@ -0,0 +1,192 @@ +import { jest } from "@jest/globals"; +import fs from "node:fs"; +import path from "node:path"; +import { ConfigHandler } from "../../config/ConfigHandler.js"; +import { ContinueServerClient } from "../../continueServer/stubs/client.js"; +import { ControlPlaneClient } from "../../control-plane/client.js"; +import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer.js"; +import { getComputeDeleteAddRemove } from "../../indexing/refreshIndex.js"; +import { TestCodebaseIndex } from "../../indexing/TestCodebaseIndex.js"; +import { CodebaseIndex } from "../../indexing/types.js"; +import { walkDir } from "../../indexing/walkDir.js"; +import FileSystemIde from "../../util/filesystem.js"; +import { getIndexSqlitePath } from "../../util/paths.js"; +import { + addToTestDir, + setUpTestDir, + tearDownTestDir, + TEST_DIR, +} from "../testUtils/testDir.js"; + +jest.useFakeTimers(); + +const TEST_TS = `\ +function main() { + console.log("Hello, world!"); +} + +class Foo { + constructor(public bar: string) {} +} +`; + +const TEST_PY = `\ +def main(): + print("Hello, world!") + +class Foo: + def __init__(self, bar: str): + self.bar = bar +`; + +const TEST_RS = `\ +fn main() { + println!("Hello, world!"); +} + +struct Foo { + bar: String, +} +`; + +// A subclass of CodebaseIndexer that adds a new CodebaseIndex +class TestCodebaseIndexer extends CodebaseIndexer { + protected async getIndexesToBuild(): Promise { + return [new TestCodebaseIndex()]; + } +} + +// These are more like integration tests, whereas we should separately test +// the individual CodebaseIndex classes +describe("CodebaseIndexer", () => { + const ide = new FileSystemIde(TEST_DIR); + const ideSettingsPromise = ide.getIdeSettings(); + const configHandler = new ConfigHandler( + ide, + ideSettingsPromise, + async (text) => {}, + new ControlPlaneClient(Promise.resolve(undefined)), + ); + const pauseToken = new PauseToken(false); + const continueServerClient = new ContinueServerClient(undefined, undefined); + const codebaseIndexer = new TestCodebaseIndexer( + configHandler, + ide, + pauseToken, + continueServerClient, + ); + const testIndex = new TestCodebaseIndex(); + + beforeAll(async () => { + tearDownTestDir(); + setUpTestDir(); + }); + + afterAll(async () => { + tearDownTestDir(); + }); + + async function refreshIndex() { + const abortController = new AbortController(); + const abortSignal = abortController.signal; + + const updates = []; + for await (const update of codebaseIndexer.refresh( + [TEST_DIR], + abortSignal, + )) { + updates.push(update); + } + return updates; + } + + async function getAllIndexedFiles() { + const files = await testIndex.getIndexedFilesForTags( + await ide.getTags(testIndex.artifactId), + ); + return files; + } + + async function getIndexPlan() { + const workspaceFiles = await walkDir(TEST_DIR, ide); + const [tag] = await ide.getTags(testIndex.artifactId); + const stats = await ide.getLastModified(workspaceFiles); + + const [results, lastUpdated, markComplete] = + await getComputeDeleteAddRemove( + tag, + { ...stats }, + (filepath) => ide.readFile(filepath), + undefined, + ); + return results; + } + + async function expectPlan( + compute: number, + addTag: number, + removeTag: number, + del: number, + ) { + const results = await getIndexPlan(); + expect(results.compute).toHaveLength(compute); + expect(results.addTag).toHaveLength(addTag); + expect(results.removeTag).toHaveLength(removeTag); + expect(results.del).toHaveLength(del); + } + + test("should index test folder without problem", async () => { + addToTestDir([ + ["test.ts", TEST_TS], + ["py/main.py", TEST_PY], + ]); + + await expectPlan(2, 0, 0, 0); + + const updates = await refreshIndex(); + expect(updates.length).toBeGreaterThan(0); + }); + + test("should have created index folder with all necessary files", async () => { + expect(fs.existsSync(getIndexSqlitePath())).toBe(true); + }); + + test("should have indexed all of the files", async () => { + const indexed = await getAllIndexedFiles(); + expect(indexed.length).toBe(2); + expect(indexed.some((file) => file.endsWith("test.ts"))).toBe(true); + expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true); + }); + + test("should successfully re-index after adding a file", async () => { + addToTestDir([["main.rs", TEST_RS]]); + + await expectPlan(1, 0, 0, 0); + + const updates = await refreshIndex(); + expect(updates.length).toBeGreaterThan(0); + + // Check that the new file was indexed + const files = await getAllIndexedFiles(); + expect(files.length).toBe(3); + expect(files.some((file) => file.endsWith("main.rs"))).toBe(true); + }); + + test("should successfully re-index after deleting a file", async () => { + fs.rmSync(path.join(TEST_DIR, "main.rs")); + + await expectPlan(0, 0, 0, 1); + + const updates = await refreshIndex(); + expect(updates.length).toBeGreaterThan(0); + + // Check that the deleted file was removed from the index + const files = await getAllIndexedFiles(); + expect(files.length).toBe(2); + expect(files.every((file) => !file.endsWith("main.rs"))).toBe(true); + }); + + test("shouldn't index any files when nothing changed", async () => { + await expectPlan(0, 0, 0, 0); + }); +}); diff --git a/core/test/testUtils/testDir.ts b/core/test/testUtils/testDir.ts index 33a636d08..094086ebd 100644 --- a/core/test/testUtils/testDir.ts +++ b/core/test/testUtils/testDir.ts @@ -11,17 +11,22 @@ export function setUpTestDir() { } export function tearDownTestDir() { - fs.rmSync(TEST_DIR, { recursive: true }); + if (fs.existsSync(TEST_DIR)) { + fs.rmSync(TEST_DIR, { recursive: true }); + } } export function addToTestDir(paths: (string | string[])[]) { for (const p of paths) { + const filepath = path.join(TEST_DIR, Array.isArray(p) ? p[0] : p); + fs.mkdirSync(path.dirname(filepath), { recursive: true }); + if (Array.isArray(p)) { - fs.writeFileSync(path.join(TEST_DIR, p[0]), p[1]); + fs.writeFileSync(filepath, p[1]); } else if (p.endsWith("/")) { - fs.mkdirSync(path.join(TEST_DIR, p), { recursive: true }); + fs.mkdirSync(filepath, { recursive: true }); } else { - fs.writeFileSync(path.join(TEST_DIR, p), ""); + fs.writeFileSync(filepath, ""); } } } diff --git a/core/util/filesystem.ts b/core/util/filesystem.ts index 978fa0829..330776518 100644 --- a/core/util/filesystem.ts +++ b/core/util/filesystem.ts @@ -45,12 +45,17 @@ class FileSystemIde implements IDE { async getGitHubAuthToken(): Promise { return undefined; } - getLastModified(files: string[]): Promise<{ [path: string]: number }> { - return new Promise((resolve) => { - resolve({ - [files[0]]: 1234567890, - }); - }); + async getLastModified(files: string[]): Promise<{ [path: string]: number }> { + const result: { [path: string]: number } = {}; + for (const file of files) { + try { + const stats = fs.statSync(file); + result[file] = stats.mtimeMs; + } catch (error) { + console.error(`Error getting last modified time for ${file}:`, error); + } + } + return result; } getGitRootPath(dir: string): Promise { return Promise.resolve(dir); @@ -78,8 +83,13 @@ class FileSystemIde implements IDE { return Promise.resolve(undefined); } - getTags(artifactId: string): Promise { - return Promise.resolve([]); + async getTags(artifactId: string): Promise { + const directory =(await this.getWorkspaceDirs())[0] + return [{ + artifactId, + branch: await this.getBranch(directory), + directory + }] } getIdeInfo(): Promise { diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index fd28cddb1..f4ab86c60 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -92,7 +92,7 @@ export async function getParserForFile(filepath: string) { return parser; } catch (e) { - console.error("Unable to load language for file", filepath, e); + console.debug("Unable to load language for file", filepath, e); return undefined; } } @@ -120,7 +120,7 @@ export async function getLanguageForFile( } return language; } catch (e) { - console.error("Unable to load language for file", filepath, e); + console.debug("Unable to load language for file", filepath, e); return undefined; } }