diff --git a/.continue/prompts/core-util-test.prompt b/.continue/prompts/core-util-test.prompt new file mode 100644 index 000000000..6cc7351a2 --- /dev/null +++ b/.continue/prompts/core-util-test.prompt @@ -0,0 +1,27 @@ +name: Write Core Utility Test +description: Generate unit tests for core utilities +--- +Write jest tests for the provided code. +Use jest version ^29 (e.g. jest 29.7.0) + +Use best practices. Be clear and consise. +Aim for 100% code coverage where reasonable. +Multiple tests can be written, split up tests for best clarity and readability. +Only use typescript, and if the file/code is not typescript, warn the user. +Use given types to generate mock data if needed. + +Additional types can be imported from @core/index.d.ts +If any needed type declaration is still not found, warn the user. + +Existing test fixtures can be found in @core/test/fixtures.ts +- import and use `testIde` for any IDE type needs +- import and use `testControlPlaneClient` for any ControlPlaneClient needs +- import and use `testConfigHandler` for any ConfigHandler needs +- import and use `ideSettingsPromise` for any IdeSettings needs + +Do NOT write tests for `core/test/util/fixtures.ts` or `core/index.d.ts`, only use them as helpers for testing other files. If no other files are attached, just warn the user. + +// This note is for if using edit mode to encourage it to create new files +The tests are to be put in a new file with the same filepath but with a .test.ts extension rather than a .ts extension +Avoid casting functions to the jest.Mock type. Instead, use `jest.mocked(fn)` +Use double quotes (or backticks if needed) for strings, and observe eslint import order standards \ No newline at end of file diff --git a/.github/workflows/main.yaml b/.github/workflows/main.yaml index b73cdb3ad..ae0359027 100644 --- a/.github/workflows/main.yaml +++ b/.github/workflows/main.yaml @@ -49,11 +49,11 @@ jobs: platform: alpine arch: x64 npm_config_arch: x64 - - os: macos-12 # should migrate this to the newer x64 version of macos-14 + - os: macos-13 platform: darwin arch: x64 npm_config_arch: x64 - - os: macos-12 # same here, especially + - os: macos-13 platform: darwin arch: arm64 npm_config_arch: arm64 diff --git a/.github/workflows/pr_checks.yaml b/.github/workflows/pr_checks.yaml index a879c3d9d..02bd2c333 100644 --- a/.github/workflows/pr_checks.yaml +++ b/.github/workflows/pr_checks.yaml @@ -5,6 +5,11 @@ on: branches: - main + paths: + - "extensions/vscode/**" + - "core/**" + - "gui/**" + jobs: tsc-check: runs-on: ubuntu-latest @@ -83,6 +88,15 @@ jobs: npx tsc --noEmit npm run lint + - name: Install Xvfb for Linux and run e2e tests + run: | + sudo apt-get install -y xvfb # Install Xvfb + Xvfb :99 & # Start Xvfb + export DISPLAY=:99 # Export the display number to the environment + cd extensions/vscode + npm run package + npm run e2e:ci + - name: core checks run: | cd core diff --git a/.github/workflows/preview.yaml b/.github/workflows/preview.yaml index a65e79c7f..bd5f4b7ac 100644 --- a/.github/workflows/preview.yaml +++ b/.github/workflows/preview.yaml @@ -49,11 +49,11 @@ jobs: platform: alpine arch: x64 npm_config_arch: x64 - - os: macos-12 # should migrate this to the newer x64 version of macos-14 + - os: macos-13 platform: darwin arch: x64 npm_config_arch: x64 - - os: macos-12 # same here, especially + - os: macos-13 platform: darwin arch: arm64 npm_config_arch: arm64 diff --git a/.gitignore b/.gitignore index 9621811de..7c18e6b16 100644 --- a/.gitignore +++ b/.gitignore @@ -135,9 +135,7 @@ cached_embeddings.pkl .ruff_cache codeql -**/.continue .DS_Store -.continue .test .tiktoken_cache @@ -153,7 +151,6 @@ continue_server.dist Icon Icon? -.continue .continuerc.json .prompts/ .aider* @@ -170,4 +167,6 @@ extensions/intellij/.idea/** extensions/intellij/bin extensions/.continue-debug/ -*.vsix \ No newline at end of file +*.vsix + +binary/.continue \ No newline at end of file diff --git a/core/autocomplete/context/ImportDefinitionsService.ts b/core/autocomplete/context/ImportDefinitionsService.ts index 128dbf78e..309310738 100644 --- a/core/autocomplete/context/ImportDefinitionsService.ts +++ b/core/autocomplete/context/ImportDefinitionsService.ts @@ -29,14 +29,23 @@ export class ImportDefinitionsService { return this.cache.get(filepath); } - private async _getFileInfo(filepath: string): Promise { + private async _getFileInfo(filepath: string): Promise { const parser = await getParserForFile(filepath); if (!parser) { return { imports: {}, }; } - const ast = parser.parse(await this.ide.readFile(filepath), undefined, { + + let fileContents: string | undefined = undefined; + try { + fileContents = await this.ide.readFile(filepath); + } catch (err) { + // File removed + return null; + } + + const ast = parser.parse(fileContents, undefined, { includedRanges: [ { startIndex: 0, diff --git a/core/autocomplete/context/root-path-context/test/testUtils.ts b/core/autocomplete/context/root-path-context/test/testUtils.ts index 7a5c22aba..207b1d6d4 100644 --- a/core/autocomplete/context/root-path-context/test/testUtils.ts +++ b/core/autocomplete/context/root-path-context/test/testUtils.ts @@ -4,7 +4,7 @@ import path from "path"; import Parser from "web-tree-sitter"; import { Position } from "../../../.."; -import { testIde } from "../../../../test/util/fixtures"; +import { testIde } from "../../../../test/fixtures"; import { getAst, getTreePathAtCursor } from "../../../util/ast"; import { ImportDefinitionsService } from "../../ImportDefinitionsService"; import { RootPathContextService } from "../RootPathContextService"; diff --git a/core/autocomplete/filtering/test/filter.test.ts b/core/autocomplete/filtering/test/filter.test.ts index e6c07b951..594e061ad 100644 --- a/core/autocomplete/filtering/test/filter.test.ts +++ b/core/autocomplete/filtering/test/filter.test.ts @@ -1,4 +1,4 @@ -import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir"; +import { setUpTestDir, tearDownTestDir } from "../../../test/testDir"; import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases"; import { diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index 8adaa101a..db8d99131 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -1,8 +1,8 @@ import fs from "node:fs"; import path from "node:path"; -import Mock from "../../../llm/llms/Mock"; -import { testConfigHandler, testIde } from "../../../test/util/fixtures"; +import MockLLM from "../../../llm/llms/Mock"; +import { testConfigHandler, testIde } from "../../../test/fixtures"; import { CompletionProvider } from "../../CompletionProvider"; import { AutocompleteInput } from "../../util/types"; @@ -30,7 +30,7 @@ export async function testAutocompleteFiltering( const { prefix, suffix } = parseFimExample(test.input); // Setup necessary objects - const llm = new Mock({ + const llm = new MockLLM({ model: "mock", }); llm.completion = test.llmOutput; diff --git a/core/commands/slash/commit.ts b/core/commands/slash/commit.ts index 8fc1ae27b..c2d09adba 100644 --- a/core/commands/slash/commit.ts +++ b/core/commands/slash/commit.ts @@ -5,7 +5,7 @@ const CommitMessageCommand: SlashCommand = { name: "commit", description: "Generate a commit message for current changes", run: async function* ({ ide, llm, params }) { - const includeUnstaged = params?.includeUnstaged ?? false; + const includeUnstaged = params?.includeUnstaged ?? true; const diff = await ide.getDiff(includeUnstaged); if (diff.length === 0) { diff --git a/core/config/ConfigHandler.test.ts b/core/config/ConfigHandler.test.ts index 26de42ec7..e7d90f492 100644 --- a/core/config/ConfigHandler.test.ts +++ b/core/config/ConfigHandler.test.ts @@ -1,8 +1,8 @@ import fs from "node:fs"; import path from "node:path"; -import { testConfigHandler } from "../test/util/fixtures"; -import { TEST_DIR } from "../test/util/testDir"; +import { testConfigHandler } from "../test/fixtures"; +import { TEST_DIR } from "../test/testDir"; import { getConfigTsPath } from "../util/paths"; import { defaultConfig } from "./default"; diff --git a/core/config/promptFile.ts b/core/config/promptFile.ts index 5020fc112..de17a7120 100644 --- a/core/config/promptFile.ts +++ b/core/config/promptFile.ts @@ -173,7 +173,7 @@ async function renderPrompt( const helpers = getContextProviderHelpers(context); // A few context providers that don't need to be in config.json to work in .prompt files - const diff = await context.ide.getDiff(false); + const diff = await context.ide.getDiff(true); const currentFile = await context.ide.getCurrentFile(); const inputData: Record = { diff: diff.join("\n"), diff --git a/core/test/context/providers/index.skip.ts b/core/context/providers/_context-providers.test.ts similarity index 83% rename from core/test/context/providers/index.skip.ts rename to core/context/providers/_context-providers.test.ts index 1d4e9f1b1..7e0fdbd73 100644 --- a/core/test/context/providers/index.skip.ts +++ b/core/context/providers/_context-providers.test.ts @@ -4,12 +4,12 @@ import { ContextProviderExtras, ContextProviderWithParams, IContextProvider, -} from "../../.."; -import { ConfigHandler } from "../../../config/ConfigHandler"; -import { contextProviderClassFromName } from "../../../context/providers"; -import { ControlPlaneClient } from "../../../control-plane/client"; -import FileSystemIde from "../../../util/filesystem"; -import { TEST_DIR } from "../../util/testDir"; +} from "../.."; +import { ConfigHandler } from "../../config/ConfigHandler"; +import { contextProviderClassFromName } from "."; +import { ControlPlaneClient } from "../../control-plane/client"; +import FileSystemIde from "../../util/filesystem"; +import { TEST_DIR } from "../../test/testDir"; const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [ { name: "diff", params: {} }, diff --git a/core/context/rerankers/bedrock.ts b/core/context/rerankers/bedrock.ts new file mode 100644 index 000000000..071910bd9 --- /dev/null +++ b/core/context/rerankers/bedrock.ts @@ -0,0 +1,99 @@ +import { + BedrockRuntimeClient, + InvokeModelCommand, +} from "@aws-sdk/client-bedrock-runtime"; +import { fromIni } from "@aws-sdk/credential-providers"; +import { Chunk, Reranker, RerankerName } from "../../index.js"; + +export class BedrockReranker implements Reranker { + name: RerankerName = "bedrock"; + + static defaultOptions = { + region: "us-east-1", + model: "amazon.rerank-v1:0", + profile: "bedrock", + }; + + private supportedModels = ["amazon.rerank-v1:0", "cohere.rerank-v3-5:0"]; + + constructor( + private readonly params: { + region?: string; + model?: string; + profile?: string; + } = {}, + ) { + if (params.model && !this.supportedModels.includes(params.model)) { + throw new Error( + `Unsupported model: ${params.model}. Supported models are: ${this.supportedModels.join(", ")}`, + ); + } + } + + async rerank(query: string, chunks: Chunk[]): Promise { + if (!query || !chunks.length) { + throw new Error("Query and chunks must not be empty"); + } + + try { + const credentials = await this._getCredentials(); + const client = new BedrockRuntimeClient({ + region: this.params.region ?? BedrockReranker.defaultOptions.region, + credentials, + }); + + const model = this.params.model ?? BedrockReranker.defaultOptions.model; + + // Base payload for both models + const payload: any = { + query: query, + documents: chunks.map((chunk) => chunk.content), + top_n: chunks.length, + }; + + // Add api_version for Cohere model + if (model.startsWith("cohere.rerank")) { + payload.api_version = 2; + } + + const input = { + body: JSON.stringify(payload), + modelId: model, + accept: "*/*", + contentType: "application/json", + }; + + const command = new InvokeModelCommand(input); + const response = await client.send(command); + + if (!response.body) { + throw new Error("Empty response received from Bedrock"); + } + + const responseBody = JSON.parse(new TextDecoder().decode(response.body)); + + // Sort results by index to maintain original order + return responseBody.results + .sort((a: any, b: any) => a.index - b.index) + .map((result: any) => result.relevance_score); + } catch (error) { + console.error("Error in BedrockReranker.rerank:", error); + throw error; + } + } + + private async _getCredentials() { + try { + const credentials = await fromIni({ + profile: this.params.profile ?? BedrockReranker.defaultOptions.profile, + ignoreCache: true, + })(); + return credentials; + } catch (e) { + console.warn( + `AWS profile with name ${this.params.profile ?? BedrockReranker.defaultOptions.profile} not found in ~/.aws/credentials, using default profile`, + ); + return await fromIni()(); + } + } +} diff --git a/core/context/rerankers/index.ts b/core/context/rerankers/index.ts index 9b1db230d..ba6af849c 100644 --- a/core/context/rerankers/index.ts +++ b/core/context/rerankers/index.ts @@ -1,5 +1,6 @@ import { RerankerName } from "../../index.js"; +import { BedrockReranker } from "./bedrock.js"; import { CohereReranker } from "./cohere.js"; import { ContinueProxyReranker } from "./ContinueProxyReranker.js"; import { FreeTrialReranker } from "./freeTrial.js"; @@ -9,9 +10,10 @@ import { VoyageReranker } from "./voyage.js"; export const AllRerankers: { [key in RerankerName]: any } = { cohere: CohereReranker, + bedrock: BedrockReranker, llm: LLMReranker, voyage: VoyageReranker, "free-trial": FreeTrialReranker, "huggingface-tei": HuggingFaceTEIReranker, "continue-proxy": ContinueProxyReranker, -}; +}; \ No newline at end of file diff --git a/core/context/retrieval/repoMapRequest.ts b/core/context/retrieval/repoMapRequest.ts index 57f2b339e..5c82ace95 100644 --- a/core/context/retrieval/repoMapRequest.ts +++ b/core/context/retrieval/repoMapRequest.ts @@ -66,7 +66,6 @@ This is the question that you should select relevant files for: "${input}"`; new AbortController().signal, ); const content = renderChatMessage(response); - console.debug("Repo map retrieval response: ", content); if (!content.includes("\n")) { return []; diff --git a/core/continueServer/stubs/client.ts b/core/continueServer/stubs/client.ts index f9377b1af..49f02fb65 100644 --- a/core/continueServer/stubs/client.ts +++ b/core/continueServer/stubs/client.ts @@ -15,7 +15,7 @@ export class ContinueServerClient implements IContinueServerClient { this.url = typeof serverUrl !== "string" || serverUrl === "" ? undefined - : new URL(serverUrl); + : new URL(serverUrl.endsWith("/") ? serverUrl : `${serverUrl}/`); } catch (e) { console.warn("Invalid Continue server url", e); this.url = undefined; diff --git a/core/core.ts b/core/core.ts index 1eaef976d..ddfacf5b9 100644 --- a/core/core.ts +++ b/core/core.ts @@ -23,6 +23,7 @@ import { getAllSuggestedDocs } from "./indexing/docs/suggestions"; import { defaultIgnoreFile } from "./indexing/ignore.js"; import Ollama from "./llm/llms/Ollama"; import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile"; +import { callTool } from "./tools/callTool"; import { ChatDescriber } from "./util/chatDescriber"; import { logDevData } from "./util/devdata"; import { DevDataSqliteDb } from "./util/devdataSqlite"; @@ -36,7 +37,6 @@ import { TTS } from "./util/tts"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; import type { FromCoreProtocol, ToCoreProtocol } from "./protocol"; -import { callTool } from "./tools/callTool"; import type { IMessenger, Message } from "./util/messenger"; export class Core { @@ -56,16 +56,10 @@ export class Core { private abortedMessageIds: Set = new Set(); - private selectedModelTitle: string | undefined; - private async config() { return this.configHandler.loadConfig(); } - private async getSelectedModel() { - return await this.configHandler.llmFromTitle(this.selectedModelTitle); - } - invoke( messageType: T, data: ToCoreProtocol[T][0], @@ -155,10 +149,10 @@ export class Core { // Index on initialization void this.ide.getWorkspaceDirs().then(async (dirs) => { // Respect pauseCodebaseIndexOnStart user settings - this.indexingPauseToken.paused = true; if (ideSettings.pauseCodebaseIndexOnStart) { + this.indexingPauseToken.paused = true; void this.messenger.request("indexProgress", { - progress: 1, + progress: 0, desc: "Initial Indexing Skipped", status: "paused", }); @@ -197,11 +191,6 @@ export class Core { void this.ide.showToast("error", err.message); }); - // New - on("update/modelChange", (msg) => { - this.selectedModelTitle = msg.data; - }); - on("update/selectTabAutocompleteModel", async (msg) => { this.globalContext.update("selectedTabAutocompleteModel", msg.data); void this.configHandler.reloadConfig(); @@ -309,9 +298,10 @@ export class Core { }); on("context/getContextItems", async (msg) => { - const { name, query, fullInput, selectedCode } = msg.data; + const { name, query, fullInput, selectedCode, selectedModelTitle } = + msg.data; const config = await this.config(); - const llm = await this.getSelectedModel(); + const llm = await this.configHandler.llmFromTitle(selectedModelTitle); const provider = config.contextProviders?.find( (provider) => provider.description.title === name, ); @@ -510,8 +500,10 @@ export class Core { }); on("chatDescriber/describe", async (msg) => { - const currentModel = await this.getSelectedModel(); - return await ChatDescriber.describe(currentModel, {}, msg.data); + const currentModel = await this.configHandler.llmFromTitle( + msg.data.selectedModelTitle, + ); + return await ChatDescriber.describe(currentModel, {}, msg.data.text); }); async function* runNodeJsSlashCommand( @@ -788,7 +780,7 @@ export class Core { } }); - on("tools/call", async ({ data: { toolCall } }) => { + on("tools/call", async ({ data: { toolCall, selectedModelTitle } }) => { const config = await this.configHandler.loadConfig(); const tool = config.tools.find( (t) => t.function.name === toolCall.function.name, @@ -798,7 +790,7 @@ export class Core { throw new Error(`Tool ${toolCall.function.name} not found`); } - const llm = await this.getSelectedModel(); + const llm = await this.configHandler.llmFromTitle(selectedModelTitle); const contextItems = await callTool( tool.uri ?? tool.function.name, @@ -842,6 +834,8 @@ export class Core { this.indexingCancellationController.signal, )) { let updateToSend = { ...update }; + // TODO reconsider this status overwrite? + // original goal was to not concern users with edge noncritical errors if (update.status === "failed") { updateToSend.status = "done"; updateToSend.desc = "Indexing complete"; @@ -866,10 +860,7 @@ export class Core { this.indexingCancellationController && !this.indexingCancellationController.signal.aborted ) { - return console.debug( - "Codebase indexing already in progress, skipping indexing of files\n" + - files.join("\n"), - ); + return; } this.indexingCancellationController = new AbortController(); for await (const update of (await this.codebaseIndexerPromise).refreshFiles( diff --git a/core/index.d.ts b/core/index.d.ts index cc1d827c8..13cd3e3b8 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -42,11 +42,18 @@ export interface IndexingProgressUpdate { progress: number; desc: string; shouldClearIndexes?: boolean; - status: "loading" | "indexing" | "done" | "failed" | "paused" | "disabled"; + status: + | "loading" + | "indexing" + | "done" + | "failed" + | "paused" + | "disabled" + | "cancelled"; debugInfo?: string; } -// This is more or less a V2 of IndexingProgressUpdate +// This is more or less a V2 of IndexingProgressUpdate for docs etc. export interface IndexingStatus { id: string; type: "docs"; @@ -192,10 +199,12 @@ export interface CustomContextProvider { description?: string; renderInlineAs?: string; type?: ContextProviderType; + getContextItems( query: string, extras: ContextProviderExtras, ): Promise; + loadSubmenuItems?: ( args: LoadSubmenuItemsArgs, ) => Promise; @@ -272,10 +281,12 @@ export interface Range { start: Position; end: Position; } + export interface Position { line: number; character: number; } + export interface FileEdit { filepath: string; range: Range; @@ -418,7 +429,6 @@ export interface ChatHistoryItem { modifiers?: InputModifiers; promptLogs?: PromptLog[]; toolCallState?: ToolCallState; - mode?: MessageModes; isGatheringContext?: boolean; checkpoint?: Checkpoint; isBeforeCheckpoint?: boolean; @@ -477,6 +487,7 @@ export interface LLMOptions { // IBM watsonx Options deploymentId?: string; } + type RequireAtLeastOne = Pick< T, Exclude @@ -533,6 +544,7 @@ export class Thread { } export type IdeType = "vscode" | "jetbrains"; + export interface IdeInfo { ideType: IdeType; name: string; @@ -568,42 +580,68 @@ export interface IdeSettings { export interface IDE { getIdeInfo(): Promise; + getIdeSettings(): Promise; + getDiff(includeUnstaged: boolean): Promise; + getClipboardContent(): Promise<{ text: string; copiedAt: string }>; + isTelemetryEnabled(): Promise; + getUniqueId(): Promise; + getTerminalContents(): Promise; + getDebugLocals(threadIndex: number): Promise; + getTopLevelCallStackSources( threadIndex: number, stackDepth: number, ): Promise; + getAvailableThreads(): Promise; + listFolders(): Promise; + getWorkspaceDirs(): Promise; + getWorkspaceConfigs(): Promise; + fileExists(filepath: string): Promise; + writeFile(path: string, contents: string): Promise; + showVirtualFile(title: string, contents: string): Promise; + getContinueDir(): Promise; + openFile(path: string): Promise; + openUrl(url: string): Promise; + runCommand(command: string): Promise; + saveFile(filepath: string): Promise; + readFile(filepath: string): Promise; + readRangeInFile(filepath: string, range: Range): Promise; + showLines( filepath: string, startLine: number, endLine: number, ): Promise; + showDiff( filepath: string, newContents: string, stepIndex: number, ): Promise; + getOpenFiles(): Promise; + getCurrentFile(): Promise< | undefined | { @@ -612,21 +650,33 @@ export interface IDE { contents: string; } >; + getPinnedFiles(): Promise; + getSearchResults(query: string): Promise; + subprocess(command: string, cwd?: string): Promise<[string, string]>; + getProblems(filepath?: string | undefined): Promise; + getBranch(dir: string): Promise; + getTags(artifactId: string): Promise; + getRepoName(dir: string): Promise; + showToast( type: ToastType, message: string, ...otherParams: any[] ): Promise; + getGitRootPath(dir: string): Promise; + listDir(dir: string): Promise<[string, FileType][]>; + getLastModified(files: string[]): Promise<{ [path: string]: number }>; + getGitHubAuthToken(args: GetGhTokenArgs): Promise; // LSP @@ -634,6 +684,7 @@ export interface IDE { // Callbacks onDidChangeActiveTextEditor(callback: (filepath: string) => void): void; + pathSep(): Promise; } @@ -760,6 +811,7 @@ type ModelProvider = | "nvidia" | "vllm" | "mock" + | "test" | "cerebras" | "askSage" | "vertexai" @@ -1033,11 +1085,13 @@ export interface EmbeddingsProvider { id: string; providerName: EmbeddingsProviderName; maxChunkSize: number; + embed(chunks: string[]): Promise; } export type RerankerName = | "cohere" + | "bedrock" | "voyage" | "llm" | "free-trial" @@ -1051,6 +1105,7 @@ export interface RerankerDescription { export interface Reranker { name: string; + rerank(query: string, chunks: Chunk[]): Promise; } diff --git a/core/indexing/CodeSnippetsIndex.test.ts b/core/indexing/CodeSnippetsIndex.test.ts index 97d086d23..814927725 100644 --- a/core/indexing/CodeSnippetsIndex.test.ts +++ b/core/indexing/CodeSnippetsIndex.test.ts @@ -1,11 +1,11 @@ import { jest } from "@jest/globals"; -import { testIde } from "../test/util/fixtures"; +import { testIde } from "../test/fixtures"; import { insertMockChunks, mockPathAndCacheKey, updateIndexAndAwaitGenerator, -} from "../test/util/indexing"; +} from "./test/indexing"; import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex"; import { DatabaseConnection, SqliteDb } from "./refreshIndex"; diff --git a/core/indexing/CodebaseIndexer.test.ts b/core/indexing/CodebaseIndexer.test.ts index ee2f108f7..950e23ffd 100644 --- a/core/indexing/CodebaseIndexer.test.ts +++ b/core/indexing/CodebaseIndexer.test.ts @@ -5,13 +5,13 @@ import path from "node:path"; import { jest } from "@jest/globals"; import { ContinueServerClient } from "../continueServer/stubs/client.js"; -import { testConfigHandler, testIde } from "../test/util/fixtures.js"; +import { testConfigHandler, testIde } from "../test/fixtures.js"; import { addToTestDir, setUpTestDir, tearDownTestDir, TEST_DIR, -} from "../test/util/testDir.js"; +} from "../test/testDir.js"; import { getIndexSqlitePath } from "../util/paths.js"; import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js"; @@ -76,8 +76,8 @@ describe("CodebaseIndexer", () => { setUpTestDir(); execSync("git init", { cwd: TEST_DIR }); - execSync("git config user.email \"test@example.com\"", { cwd: TEST_DIR }); - execSync("git config user.name \"Test\"", { cwd: TEST_DIR }); + execSync('git config user.email "test@example.com"', { cwd: TEST_DIR }); + execSync('git config user.name "Test"', { cwd: TEST_DIR }); }); afterAll(async () => { @@ -100,9 +100,7 @@ describe("CodebaseIndexer", () => { async function refreshIndexFiles(files: string[]) { const updates = []; - for await (const update of codebaseIndexer.refreshFiles( - files, - )) { + for await (const update of codebaseIndexer.refreshFiles(files)) { updates.push(update); } return updates; diff --git a/core/indexing/CodebaseIndexer.ts b/core/indexing/CodebaseIndexer.ts index 5c70f8bad..af204a723 100644 --- a/core/indexing/CodebaseIndexer.ts +++ b/core/indexing/CodebaseIndexer.ts @@ -145,9 +145,7 @@ export class CodebaseIndexer { } } - async *refreshFiles( - files: string[], - ): AsyncGenerator { + async *refreshFiles(files: string[]): AsyncGenerator { let progress = 0; if (files.length === 0) { yield { @@ -192,9 +190,9 @@ export class CodebaseIndexer { if (dirs.length === 0) { yield { - progress, + progress: 1, desc: "Nothing to index", - status: "disabled", + status: "done", }; return; } @@ -238,9 +236,9 @@ export class CodebaseIndexer { directoryFiles.push(p); if (abortSignal.aborted) { yield { - progress: 1, + progress: 0, desc: "Indexing cancelled", - status: "disabled", + status: "cancelled", }; return; } @@ -263,9 +261,9 @@ export class CodebaseIndexer { // Handle pausing in this loop because it's the only one really taking time if (abortSignal.aborted) { yield { - progress: 1, + progress: 0, desc: "Indexing cancelled", - status: "disabled", + status: "cancelled", }; return; } diff --git a/core/indexing/FullTextSearchCodebaseIndex.test.ts b/core/indexing/FullTextSearchCodebaseIndex.test.ts index d46e47fd4..3aefafaaa 100644 --- a/core/indexing/FullTextSearchCodebaseIndex.test.ts +++ b/core/indexing/FullTextSearchCodebaseIndex.test.ts @@ -4,7 +4,7 @@ import { insertMockChunks, mockPathAndCacheKey, updateIndexAndAwaitGenerator, -} from "../test/util/indexing"; +} from "./test/indexing"; import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex"; import { DatabaseConnection, SqliteDb } from "./refreshIndex"; diff --git a/core/indexing/LanceDbIndex.test.ts b/core/indexing/LanceDbIndex.test.ts index f0c711e93..1d15117fd 100644 --- a/core/indexing/LanceDbIndex.test.ts +++ b/core/indexing/LanceDbIndex.test.ts @@ -1,13 +1,13 @@ import { jest } from "@jest/globals"; import lance from "vectordb"; -import { testConfigHandler, testIde } from "../test/util/fixtures"; +import { testConfigHandler, testIde } from "../test/fixtures"; import { mockPathAndCacheKey, mockTag, testContinueServerClient, updateIndexAndAwaitGenerator, -} from "../test/util/indexing"; +} from "./test/indexing"; import { getLanceDbPath } from "../util/paths"; import { LanceDbIndex } from "./LanceDbIndex"; diff --git a/core/indexing/chunk/ChunkCodebaseIndex.test.ts b/core/indexing/chunk/ChunkCodebaseIndex.test.ts index c2f95d560..3f7904991 100644 --- a/core/indexing/chunk/ChunkCodebaseIndex.test.ts +++ b/core/indexing/chunk/ChunkCodebaseIndex.test.ts @@ -1,14 +1,14 @@ import { jest } from "@jest/globals"; -import { testIde } from "../../test/util/fixtures"; +import { testIde } from "../../test/fixtures"; import { mockFileContents, mockFilename, mockPathAndCacheKey, testContinueServerClient, updateIndexAndAwaitGenerator, -} from "../../test/util/indexing"; -import { addToTestDir } from "../../test/util/testDir"; +} from "../test/indexing"; +import { addToTestDir } from "../../test/testDir"; import { DatabaseConnection, SqliteDb } from "../refreshIndex"; import { IndexResultType } from "../types"; diff --git a/core/indexing/docs/DocsCrawler.skip.ts b/core/indexing/docs/DocsCrawler.skip.ts index 57d712fed..97226c296 100644 --- a/core/indexing/docs/DocsCrawler.skip.ts +++ b/core/indexing/docs/DocsCrawler.skip.ts @@ -3,7 +3,7 @@ import os from "os"; import { jest } from "@jest/globals"; import { ContinueConfig } from "../.."; -import { testConfigHandler } from "../../test/util/fixtures"; +import { testConfigHandler } from "../../test/fixtures"; import FileSystemIde from "../../util/filesystem"; import DocsCrawler, { ChromiumInstaller, type PageData } from "./DocsCrawler"; diff --git a/core/indexing/docs/DocsService.ts b/core/indexing/docs/DocsService.ts index 6e841f6be..b52577a5f 100644 --- a/core/indexing/docs/DocsService.ts +++ b/core/indexing/docs/DocsService.ts @@ -7,9 +7,9 @@ import { ContinueConfig, EmbeddingsProvider, IDE, + IdeInfo, IndexingStatus, SiteIndexingConfig, - IdeInfo, } from "../.."; import { ConfigHandler } from "../../config/ConfigHandler"; import { addContextProvider } from "../../config/util"; @@ -69,7 +69,6 @@ export type AddParams = { favicon?: string; }; - /* General process: - On config update: @@ -476,8 +475,6 @@ export default class DocsService { const embeddings: number[][] = []; // Create embeddings of retrieved articles - console.debug(`Creating embeddings for ${articles.length} articles`); - for (let i = 0; i < articles.length; i++) { const article = articles[i]; diff --git a/core/indexing/docs/article.ts b/core/indexing/docs/article.ts index 1bc74c62e..2ae0e7995 100644 --- a/core/indexing/docs/article.ts +++ b/core/indexing/docs/article.ts @@ -25,59 +25,75 @@ function breakdownArticleComponent( max_chunk_size: number, ): Chunk[] { const chunks: Chunk[] = []; - const lines = article.body.split("\n"); let startLine = 0; let endLine = 0; let content = ""; let index = 0; - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - if (content.length + line.length <= max_chunk_size) { - content += `${line}\n`; - endLine = i; - } else { - chunks.push({ - content: content.trim(), - startLine: startLine, - endLine: endLine, - otherMetadata: { - title: cleanHeader(article.title), - }, - index: index, - filepath: new URL( - `${subpath}#${cleanFragment(article.title)}`, - url, - ).toString(), - digest: subpath, - }); - content = `${line}\n`; - startLine = i; - endLine = i; - index += 1; - } - } - - // Push the last chunk - if (content) { + const createChunk = ( + chunkContent: string, + chunkStartLine: number, + chunkEndLine: number, + ) => { chunks.push({ - content: content.trim(), - startLine: startLine, - endLine: endLine, + content: chunkContent.trim(), + startLine: chunkStartLine, + endLine: chunkEndLine, otherMetadata: { title: cleanHeader(article.title), }, - index: index, + index: index++, filepath: new URL( `${subpath}#${cleanFragment(article.title)}`, url, ).toString(), digest: subpath, }); + }; + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + + // Handle oversized lines by splitting them + if (line.length > max_chunk_size) { + // First push any accumulated content + if (content.trim().length > 0) { + createChunk(content, startLine, endLine); + content = ""; + } + + // Split the long line into chunks + let remainingLine = line; + let subLineStart = i; + while (remainingLine.length > 0) { + const chunk = remainingLine.slice(0, max_chunk_size); + createChunk(chunk, subLineStart, i); + remainingLine = remainingLine.slice(max_chunk_size); + } + startLine = i + 1; + continue; + } + + // Normal line handling + if (content.length + line.length + 1 <= max_chunk_size) { + content += `${line}\n`; + endLine = i; + } else { + if (content.trim().length > 0) { + createChunk(content, startLine, endLine); + } + content = `${line}\n`; + startLine = i; + endLine = i; + } + } + + // Push the last chunk + if (content.trim().length > 0) { + createChunk(content, startLine, endLine); } - // Don't use small chunks. Probably they're a mistake. Definitely they'll confuse the embeddings model. return chunks.filter((c) => c.content.trim().length > 20); } diff --git a/core/test/util/indexing.ts b/core/indexing/test/indexing.ts similarity index 84% rename from core/test/util/indexing.ts rename to core/indexing/test/indexing.ts index 16137236a..413c37e75 100644 --- a/core/test/util/indexing.ts +++ b/core/indexing/test/indexing.ts @@ -2,19 +2,12 @@ import { jest } from "@jest/globals"; import { IndexTag } from "../.."; import { IContinueServerClient } from "../../continueServer/interface"; -import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex"; -import { tagToString } from "../../indexing/refreshIndex"; -import { - CodebaseIndex, - PathAndCacheKey, - RefreshIndexResults, -} from "../../indexing/types"; - -import { testIde } from "./fixtures"; -import { addToTestDir, TEST_DIR } from "./testDir"; - - +import { ChunkCodebaseIndex } from "../chunk/ChunkCodebaseIndex"; +import { tagToString } from "../refreshIndex"; +import { CodebaseIndex, PathAndCacheKey, RefreshIndexResults } from "../types"; +import { testIde } from "../../test/fixtures"; +import { addToTestDir, TEST_DIR } from "../../test/testDir"; export const mockFilename = "test.py"; export const mockPathAndCacheKey = { diff --git a/core/indexing/walkDir.test.ts b/core/indexing/walkDir.test.ts index 748e958e9..25ffdfc37 100644 --- a/core/indexing/walkDir.test.ts +++ b/core/indexing/walkDir.test.ts @@ -6,7 +6,7 @@ import { setUpTestDir, tearDownTestDir, addToTestDir, -} from "../test/util/testDir"; +} from "../test/testDir"; import FileSystemIde from "../util/filesystem"; const ide = new FileSystemIde(TEST_DIR); diff --git a/core/jest.config.js b/core/jest.config.js index b92d03e5e..d58b0b510 100644 --- a/core/jest.config.js +++ b/core/jest.config.js @@ -8,8 +8,8 @@ export default { moduleNameMapper: { "^(\\.{1,2}/.*)\\.js$": "$1", "^uuid$": "uuid", // https://stackoverflow.com/a/73626360 - '^@azure/(.*)$': '/node_modules/@azure/$1', - '^mssql$': '/node_modules/mssql' + "^@azure/(.*)$": "/node_modules/@azure/$1", + "^mssql$": "/node_modules/mssql", }, extensionsToTreatAsEsm: [".ts"], preset: "ts-jest/presets/default-esm", @@ -19,6 +19,8 @@ export default { __dirname: path.dirname(fileURLToPath(import.meta.url)), __filename: path.resolve(fileURLToPath(import.meta.url)), }, + globalSetup: "/jest.global-setup.ts", setupFilesAfterEnv: ["/jest.setup-after-env.ts"], + maxWorkers: 1 // equivalent to CLI --runInBand }; diff --git a/core/jest.setup-after-env.ts b/core/jest.setup-after-env.ts index b5fbacc11..53f94ecea 100644 --- a/core/jest.setup-after-env.ts +++ b/core/jest.setup-after-env.ts @@ -1,4 +1,4 @@ -// https://github.com/mswjs/msw/issues/1576#issuecomment-1482643055 +import fs from "fs"; import { TextDecoder, TextEncoder } from "util"; import { jest } from "@jest/globals"; @@ -10,23 +10,21 @@ if (process.env.DEBUG === "jest") { const globalThis = global as any; +globalThis.jest = jest; + +// https://github.com/mswjs/msw/issues/1576#issuecomment-1482643055 globalThis.fetch = fetch; globalThis.Request = Request; globalThis.Response = Response; globalThis.TextEncoder = TextEncoder; globalThis.TextDecoder = TextDecoder; -// Trying to delete this when for some reason SQLite is still in use causes tests to fail -// globalThis.beforeAll(() => { -// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` +// TODO - currently causing tests to fail because sqlite is still running for some reason +// const clearTestDirectory = () => { // if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { // fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); // } -// }); +// }; -// globalThis.afterAll(() => { -// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts` -// if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) { -// fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true }); -// } -// }); +// globalThis.beforeAll(clearTestDirectory); +// globalThis.afterAll(clearTestDirectory); diff --git a/core/llm/constructMessages.ts b/core/llm/constructMessages.ts index b1cb0da93..cb7890098 100644 --- a/core/llm/constructMessages.ts +++ b/core/llm/constructMessages.ts @@ -1,7 +1,10 @@ import { ChatHistoryItem, ChatMessage, MessagePart } from "../index.js"; import { normalizeToMessageParts } from "../util/messageContent.js"; + import { modelSupportsTools } from "./autodetect.js"; +const CUSTOM_SYS_MSG_MODEL_FAMILIES = ["sonnet", "gpt-4o", "mistral-large"]; + const SYSTEM_MESSAGE = `When generating new code: 1. Always produce a single code block. @@ -64,7 +67,7 @@ const TOOL_USE_RULES = `When using tools, follow the following guidelines: - Avoid calling tools unless they are absolutely necessary. For example, if you are asked a simple programming question you do not need web search. As another example, if the user asks you to explain something about code, do not create a new file.`; function constructSystemPrompt(model: string): string | null { - if (model.includes("sonnet")) { + if (CUSTOM_SYS_MSG_MODEL_FAMILIES.some((family) => model.includes(family))) { return SYSTEM_MESSAGE + "\n\n" + TOOL_USE_RULES; } if (modelSupportsTools(model)) { diff --git a/core/test/llm.test.ts b/core/llm/llm.test.ts similarity index 95% rename from core/test/llm.test.ts rename to core/llm/llm.test.ts index cf42e128a..cb2218d1d 100644 --- a/core/test/llm.test.ts +++ b/core/llm/llm.test.ts @@ -1,10 +1,8 @@ import * as dotenv from "dotenv"; -import { CompletionOptions } from "../"; -import { BaseLLM } from "../llm/"; -import OpenAI from "../llm/llms/OpenAI"; - -// jest.setTimeout(100_000); +import { CompletionOptions } from ".."; +import { BaseLLM } from "."; +import OpenAI from "./llms/OpenAI"; dotenv.config(); diff --git a/core/llm/llms/Mock.ts b/core/llm/llms/Mock.ts index 5f3880e3c..6f564cce7 100644 --- a/core/llm/llms/Mock.ts +++ b/core/llm/llms/Mock.ts @@ -1,7 +1,7 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; import { BaseLLM } from "../index.js"; -class Mock extends BaseLLM { +class MockLLM extends BaseLLM { public completion: string = "Test Completion"; static providerName: ModelProvider = "mock"; @@ -27,4 +27,4 @@ class Mock extends BaseLLM { } } -export default Mock; +export default MockLLM; diff --git a/core/llm/llms/OpenAI.ts b/core/llm/llms/OpenAI.ts index 1a0b43c96..c8daa4e6f 100644 --- a/core/llm/llms/OpenAI.ts +++ b/core/llm/llms/OpenAI.ts @@ -72,7 +72,8 @@ class OpenAI extends BaseLLM { } protected supportsPrediction(model: string): boolean { - return ["gpt-4o-mini", "gpt-4o"].includes(model); + const SUPPORTED_MODELS = ["gpt-4o-mini", "gpt-4o", "mistral-large"]; + return SUPPORTED_MODELS.some((m) => model.includes(m)); } private convertTool(tool: Tool): any { diff --git a/core/llm/llms/Test.ts b/core/llm/llms/Test.ts new file mode 100644 index 000000000..b35984f3e --- /dev/null +++ b/core/llm/llms/Test.ts @@ -0,0 +1,39 @@ +import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; +import { BaseLLM } from "../index.js"; + +const RESPONSES: Record = { + "How are you?": "I'm fine", +}; + +const HARDCODED_CHAT_RESPONSE = "THIS IS A HARDCODED RESPONSE"; + +class TestLLM extends BaseLLM { + static providerName: ModelProvider = "test"; + + private findResponse(prompt: string) { + return Object.entries(RESPONSES).find(([key]) => prompt.includes(key))?.[1]; + } + + protected async *_streamComplete( + prompt: string, + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + yield this.findResponse(prompt) || `PROMPT: ${prompt}`; + } + + protected async *_streamChat( + messages: ChatMessage[], + signal: AbortSignal, + options: CompletionOptions, + ): AsyncGenerator { + for (const char of HARDCODED_CHAT_RESPONSE) { + yield { + role: "assistant", + content: char, + }; + } + } +} + +export default TestLLM; diff --git a/core/llm/llms/index.ts b/core/llm/llms/index.ts index 632607ed1..9604cb9f6 100644 --- a/core/llm/llms/index.ts +++ b/core/llm/llms/index.ts @@ -31,7 +31,7 @@ import LlamaCpp from "./LlamaCpp"; import Llamafile from "./Llamafile"; import LMStudio from "./LMStudio"; import Mistral from "./Mistral"; -import Mock from "./Mock"; +import MockLLM from "./Mock"; import Moonshot from "./Moonshot"; import Msty from "./Msty"; import Nebius from "./Nebius"; @@ -50,6 +50,7 @@ import Vllm from "./Vllm"; import WatsonX from "./WatsonX"; import xAI from "./xAI"; import SiliconFlow from "./SiliconFlow"; +import TestLLM from "./Test"; const LLMs = [ Anthropic, @@ -87,7 +88,8 @@ const LLMs = [ Nvidia, Vllm, SambaNova, - Mock, + MockLLM, + TestLLM, Cerebras, Asksage, Nebius, diff --git a/core/package-lock.json b/core/package-lock.json index fec878d31..a4f3c9c1d 100644 --- a/core/package-lock.json +++ b/core/package-lock.json @@ -7906,9 +7906,9 @@ } }, "node_modules/dotenv": { - "version": "16.4.5", - "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz", - "integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==", + "version": "16.4.7", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz", + "integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==", "engines": { "node": ">=12" }, diff --git a/core/package.json b/core/package.json index 977a6668f..ed66a7252 100644 --- a/core/package.json +++ b/core/package.json @@ -3,7 +3,8 @@ "version": "1.0.13", "description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js", "scripts": { - "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand", + "test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest", + "test:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage && open ./coverage/lcov-report/index.html", "tsc:check": "tsc -p ./ --noEmit", "build:npm": "tsc -p ./tsconfig.npm.json", "lint": "eslint . --ext ts", diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 35785d359..369470c59 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -39,7 +39,6 @@ export interface ListHistoryOptions { } export type ToCoreFromIdeOrWebviewProtocol = { - "update/modelChange": [string, void]; "update/selectTabAutocompleteModel": [string, void]; // Special @@ -76,6 +75,7 @@ export type ToCoreFromIdeOrWebviewProtocol = { query: string; fullInput: string; selectedCode: RangeInFile[]; + selectedModelTitle: string; }, ContextItemWithId[], ]; @@ -136,7 +136,13 @@ export type ToCoreFromIdeOrWebviewProtocol = { }, ProtocolGeneratorType, ]; - "chatDescriber/describe": [string, string | undefined]; + "chatDescriber/describe": [ + { + selectedModelTitle: string; + text: string; + }, + string | undefined, + ]; "stats/getTokensPerDay": [ undefined, { day: string; promptTokens: number; generatedTokens: number }[], @@ -174,5 +180,8 @@ export type ToCoreFromIdeOrWebviewProtocol = { "profiles/switch": [{ id: string }, undefined]; "auth/getAuthUrl": [undefined, { url: string }]; - "tools/call": [{ toolCall: ToolCall }, { contextItems: ContextItem[] }]; + "tools/call": [ + { toolCall: ToolCall; selectedModelTitle: string }, + { contextItems: ContextItem[] }, + ]; }; diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 91fa40395..4cadecbf4 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -43,7 +43,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { insertAtCursor: [{ text: string }, void]; copyText: [{ text: string }, void]; "jetbrains/editorInsetHeight": [{ height: number }, void]; - "jetbrains/isOSREnabled": [undefined, void]; + "jetbrains/isOSREnabled": [undefined, boolean]; "vscode/openMoveRightMarkdown": [undefined, void]; setGitHubAuthToken: [{ token: string }, void]; acceptDiff: [{ filepath: string; streamId?: string }, void]; @@ -56,7 +56,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { { accept: boolean; onlyFirst: boolean; filepath: string }, void, ]; - "edit/escape": [undefined, void]; + "edit/exit": [{ shouldFocusEditor: boolean }, void]; }; export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { diff --git a/core/protocol/passThrough.ts b/core/protocol/passThrough.ts index bbcfbf3f2..d5299614f 100644 --- a/core/protocol/passThrough.ts +++ b/core/protocol/passThrough.ts @@ -6,7 +6,6 @@ import { // Message types to pass through from webview to core export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] = [ - "update/modelChange", "ping", "abort", "history/list", diff --git a/core/test/.gitignore b/core/test/.gitignore deleted file mode 100644 index 227f3fc4f..000000000 --- a/core/test/.gitignore +++ /dev/null @@ -1 +0,0 @@ -scratch.test.ts \ No newline at end of file diff --git a/core/test/editme.py b/core/test/editme.py deleted file mode 100644 index c6077fb3b..000000000 --- a/core/test/editme.py +++ /dev/null @@ -1,2 +0,0 @@ -def average(nums: list) -> float: - pass diff --git a/core/test/util/fixtures.ts b/core/test/fixtures.ts similarity index 68% rename from core/test/util/fixtures.ts rename to core/test/fixtures.ts index e0aa06d14..add71d029 100644 --- a/core/test/util/fixtures.ts +++ b/core/test/fixtures.ts @@ -1,6 +1,6 @@ -import { ConfigHandler } from "../../config/ConfigHandler"; -import { ControlPlaneClient } from "../../control-plane/client"; -import FileSystemIde from "../../util/filesystem"; +import { ConfigHandler } from "../config/ConfigHandler"; +import { ControlPlaneClient } from "../control-plane/client"; +import FileSystemIde from "../util/filesystem"; import { TEST_DIR } from "./testDir"; diff --git a/core/test/util/testDir.ts b/core/test/testDir.ts similarity index 92% rename from core/test/util/testDir.ts rename to core/test/testDir.ts index 62cbbb02c..0eae7ad0b 100644 --- a/core/test/util/testDir.ts +++ b/core/test/testDir.ts @@ -3,7 +3,7 @@ import os from "os"; import path from "path"; // Want this outside of the git repository so we can change branches in tests -export const TEST_DIR = path.join(os.tmpdir(), "testDir"); +export const TEST_DIR = path.join(os.tmpdir(), "testWorkspaceDir"); export function setUpTestDir() { if (fs.existsSync(TEST_DIR)) { diff --git a/core/test/_testEnv.test.ts b/core/test/testEnv.test.ts similarity index 100% rename from core/test/_testEnv.test.ts rename to core/test/testEnv.test.ts diff --git a/core/test/util/dedentAndGetCommonWhitespace.test.ts b/core/test/util/dedentAndGetCommonWhitespace.test.ts deleted file mode 100644 index 5f3c6a4be..000000000 --- a/core/test/util/dedentAndGetCommonWhitespace.test.ts +++ /dev/null @@ -1,76 +0,0 @@ -// File generated by Continue -import { dedentAndGetCommonWhitespace } from "../../util"; - -describe("dedentAndGetCommonWhitespace", () => { - let originalString: string; - - beforeEach(() => { - // Setup any global variables or states if needed - originalString = " line1\n line2\n line3"; - }); - - afterEach(() => { - // Tear down any changes to global variables or states if needed - originalString = ""; - }); - - test("should dedent and return common whitespace for a simple case", () => { - const input = " line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\nline2\nline3", " "]); - }); - - test("should handle empty string", () => { - const input = ""; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["", ""]); - }); - - test("should handle string with only whitespace", () => { - const input = " "; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["", ""]); - }); - - test("should handle string with mixed whitespace and content", () => { - const input = " line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual([" line1\nline2\n line3", " "]); - }); - - test("should handle string with no common leading whitespace", () => { - const input = "line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual([input, ""]); - }); - - test("should handle string with empty lines", () => { - const input = " line1\n\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\n\nline3", " "]); - }); - - test("should handle string with only empty lines", () => { - const input = "\n\n"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["\n\n", ""]); - }); - - test("should handle string with tabs as whitespace", () => { - const input = "\tline1\n\tline2\n\tline3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\nline2\nline3", "\t"]); - }); - - test("should handle string with mixed tabs and spaces", () => { - const input = "\t line1\n\t line2\n\t line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual(["line1\nline2\nline3", "\t "]); - }); - - test("should handle string with different leading whitespace lengths", () => { - const input = " line1\n line2\n line3"; - const output = dedentAndGetCommonWhitespace(input); - expect(output).toEqual([" line1\nline2\n line3", " "]); - }); -}); diff --git a/core/test/util/getLastNPathParts.test.ts b/core/test/util/getLastNPathParts.test.ts deleted file mode 100644 index ba72b4520..000000000 --- a/core/test/util/getLastNPathParts.test.ts +++ /dev/null @@ -1,51 +0,0 @@ -// File generated by Continue -import { getLastNPathParts } from "../../util"; - -describe("getLastNPathParts", () => { - const SEP_REGEX = /[\\/]+/; - - beforeAll(() => { - // Setup code if needed - }); - - afterAll(() => { - // Teardown code if needed - }); - - test("returns the last N parts of a filepath with forward slashes", () => { - const filepath = "home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt"); - }); - - test("returns the last N parts of a filepath with backward slashes", () => { - const filepath = "C:\\home\\user\\documents\\project\\file.txt"; - expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); - }); - - test("returns the last part if N is 1", () => { - const filepath = "/home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 1)).toBe("file.txt"); - }); - - test("returns the entire path if N is greater than the number of parts", () => { - const filepath = "home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 10)).toBe( - "home/user/documents/project/file.txt", - ); - }); - - test("returns an empty string if N is 0", () => { - const filepath = "home/user/documents/project/file.txt"; - expect(getLastNPathParts(filepath, 0)).toBe(""); - }); - - test("handles paths with mixed forward and backward slashes", () => { - const filepath = "home\\user/documents\\project/file.txt"; - expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt"); - }); - - test("handles edge case with empty filepath", () => { - const filepath = ""; - expect(getLastNPathParts(filepath, 2)).toBe(""); - }); -}); diff --git a/core/test/util/lcs.test.ts b/core/test/util/lcs.test.ts deleted file mode 100644 index da10cdf90..000000000 --- a/core/test/util/lcs.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -// This file is generated by Continue -import { longestCommonSubsequence } from "../../util/lcs"; - -describe("longestCommonSubsequence", () => { - beforeAll(() => { - // Setup if needed - }); - - afterAll(() => { - // Teardown if needed - }); - - test("should return the longest common subsequence for non-empty strings", () => { - expect(longestCommonSubsequence("abcde", "ace")).toBe("ace"); - expect(longestCommonSubsequence("abc", "abc")).toBe("abc"); - expect(longestCommonSubsequence("abc", "def")).toBe(""); - }); - - test("should handle cases where one or both strings are empty", () => { - expect(longestCommonSubsequence("", "abc")).toBe(""); - expect(longestCommonSubsequence("abc", "")).toBe(""); - expect(longestCommonSubsequence("", "")).toBe(""); - }); - - test("should handle cases with no common subsequence", () => { - expect(longestCommonSubsequence("abc", "def")).toBe(""); - expect(longestCommonSubsequence("xyz", "abc")).toBe(""); - }); - - test("should handle cases with special characters", () => { - expect(longestCommonSubsequence("a!@#b$c", "!@#$")).toBe("!@#$"); - expect(longestCommonSubsequence("a!@#b$c", "xyz")).toBe(""); - }); - - test("should handle long strings efficiently", () => { - const str1 = "a".repeat(1000) + "b".repeat(1000); - const str2 = "a".repeat(1000) + "c".repeat(1000); - expect(longestCommonSubsequence(str1, str2)).toBe("a".repeat(1000)); - }); -}); diff --git a/core/test/util/merge.test.ts b/core/test/util/merge.test.ts deleted file mode 100644 index cf7ba99d5..000000000 --- a/core/test/util/merge.test.ts +++ /dev/null @@ -1,100 +0,0 @@ -// File generated by Continue -import { mergeJson } from "../../util/merge"; - -describe("mergeJson", () => { - it("should merge two simple JSON objects", () => { - const first = { a: 1, b: 2 }; - const second = { b: 3, c: 4 }; - const result = mergeJson(first, second); - expect(result).toEqual({ a: 1, b: 3, c: 4 }); - }); - - it("should overwrite values when mergeBehavior is \"overwrite\"", () => { - const first = { a: 1, b: 2 }; - const second = { b: 3, c: 4 }; - const result = mergeJson(first, second, "overwrite"); - expect(result).toEqual({ a: 1, b: 3, c: 4 }); - }); - - it("should merge nested objects", () => { - const first = { a: { b: 1 } }; - const second = { a: { c: 2 } }; - const result = mergeJson(first, second); - expect(result).toEqual({ a: { b: 1, c: 2 } }); - }); - - it("should merge arrays without mergeKeys", () => { - const first = { a: [1, 2] }; - const second = { a: [3, 4] }; - const result = mergeJson(first, second); - expect(result).toEqual({ a: [1, 2, 3, 4] }); - }); - - it("should merge arrays with mergeKeys", () => { - const first = { - a: [ - { id: 1, value: "first" }, - { id: 2, value: "second" }, - ], - }; - const second = { - a: [ - { id: 2, value: "updated" }, - { id: 3, value: "third" }, - ], - }; - const mergeKeys = { - a: (item1: any, item2: any) => item1.id === item2.id, - }; - const result = mergeJson(first, second, undefined, mergeKeys); - expect(result).toEqual({ - a: [ - { id: 1, value: "first" }, - { id: 2, value: "updated" }, - { id: 3, value: "third" }, - ], - }); - }); - - it("should handle non-object values correctly", () => { - const first = { a: 1, b: "string", c: true }; - const second = { a: 2, b: "new string", c: false }; - const result = mergeJson(first, second); - expect(result).toEqual({ a: 2, b: "new string", c: false }); - }); - - it("should handle null and undefined values correctly", () => { - const first = { a: 1, b: null }; - const second = { b: 2, c: undefined }; - const result = mergeJson(first, second); - expect(result).toEqual({ a: 1, b: 2, c: undefined }); - }); - - it("should handle empty objects", () => { - const first = {}; - const second = { a: 1 }; - const result = mergeJson(first, second); - expect(result).toEqual({ a: 1 }); - }); - - it("should handle empty second object", () => { - const first = { a: 1 }; - const second = {}; - const result = mergeJson(first, second); - expect(result).toEqual({ a: 1 }); - }); - - it("should handle errors gracefully", () => { - const first = { a: 1 }; - const second = { b: () => {} }; // Functions are not serializable in JSON - const result = mergeJson(first, second); - expect(result).toEqual({ a: 1, b: expect.any(Function) }); - }); - - it("should merge deeply nested objects", () => { - const first = { a: { b: { c: 1 } } }; - const second = { a: { b: { d: 2 } } }; - const result = mergeJson(first, second); - expect(result).toEqual({ a: { b: { c: 1, d: 2 } } }); - }); -}); diff --git a/core/test/util/ranges/getRangeInString.test.ts b/core/test/util/ranges/getRangeInString.test.ts deleted file mode 100644 index e0a4df67a..000000000 --- a/core/test/util/ranges/getRangeInString.test.ts +++ /dev/null @@ -1,105 +0,0 @@ -// This file is generated by Continue - -import { getRangeInString } from "../../../util/ranges"; - -describe.skip("getRangeInString", () => { - let content: string; - - beforeEach(() => { - content = `Line 1 -Line 2 -Line 3 -Line 4 -Line 5`; - }); - - afterEach(() => { - content = ""; - }); - - test("should return substring within the same line", () => { - const range = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 4 }, - }; - expect(getRangeInString(content, range)).toBe("Line"); - }); - - test("should return substring spanning multiple lines", () => { - const range = { - start: { line: 1, character: 2 }, - end: { line: 3, character: 3 }, - }; - const expected = `ne 2 -Line 3 -Line 4`; - expect(getRangeInString(content, range)).toBe(expected); - }); - - test("should handle range that starts and ends at the same character", () => { - const range = { - start: { line: 2, character: 0 }, - end: { line: 2, character: 0 }, - }; - expect(getRangeInString(content, range)).toBe("L"); - }); - - test("should handle range that spans entire content", () => { - const range = { - start: { line: 0, character: 0 }, - end: { line: 4, character: 5 }, - }; - expect(getRangeInString(content, range)).toBe(content); - }); - - test("should handle range that spans to the end of the last line", () => { - const range = { - start: { line: 3, character: 2 }, - end: { line: 4, character: 5 }, - }; - const expected = `ne 4 -Line 5`; - expect(getRangeInString(content, range)).toBe(expected); - }); - - test("should handle empty content", () => { - content = ""; - const range = { - start: { line: 0, character: 0 }, - end: { line: 0, character: 0 }, - }; - expect(getRangeInString(content, range)).toBe(""); - }); - - test("should handle invalid range (start line > end line)", () => { - const range = { - start: { line: 3, character: 0 }, - end: { line: 2, character: 0 }, - }; - expect(getRangeInString(content, range)).toBe(""); - }); - - test("should handle invalid range (start character > end character on same line)", () => { - const range = { - start: { line: 1, character: 5 }, - end: { line: 1, character: 2 }, - }; - expect(getRangeInString(content, range)).toBe(""); - }); - - test("should handle range that starts and ends at the same line but different characters", () => { - const range = { - start: { line: 1, character: 2 }, - end: { line: 1, character: 6 }, - }; - expect(getRangeInString(content, range)).toBe("ne 2"); - }); - - test("should handle range that starts and ends at the same line and same characters", () => { - const range = { - start: { line: 1, character: 2 }, - end: { line: 1, character: 2 }, - }; - expect(getRangeInString(content, range)).toBe("n"); - }); -}); diff --git a/core/test/util/ranges/intersection.test.ts b/core/test/util/ranges/intersection.test.ts deleted file mode 100644 index 397dbc1a8..000000000 --- a/core/test/util/ranges/intersection.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -// This file is generated by Continue - -import { intersection } from "../../../util/ranges"; - -interface Position { - line: number; - character: number; -} - -interface Range { - start: Position; - end: Position; -} - -describe("intersection", () => { - let rangeA: Range; - let rangeB: Range; - - beforeEach(() => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 3, character: 5 }, - }; - - rangeB = { - start: { line: 2, character: 2 }, - end: { line: 4, character: 0 }, - }; - }); - - test("returns correct intersection for overlapping ranges", () => { - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 2, character: 2 }, - end: { line: 3, character: 5 }, - }); - }); - - test("returns null for non-overlapping ranges", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 2, character: 0 }, - }; - - rangeB = { - start: { line: 3, character: 0 }, - end: { line: 4, character: 0 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toBeNull(); - }); - - // TODO - test.skip("returns correct intersection for single line overlap", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 5 }, - }; - - rangeB = { - start: { line: 1, character: 3 }, - end: { line: 2, character: 0 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 3 }, - end: { line: 1, character: 5 }, - }); - }); - - test("returns null for single line non-overlapping ranges", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 2 }, - }; - - rangeB = { - start: { line: 1, character: 3 }, - end: { line: 1, character: 5 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toBeNull(); - }); - - test("returns correct intersection when one range is fully within another", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 4, character: 5 }, - }; - - rangeB = { - start: { line: 2, character: 2 }, - end: { line: 3, character: 3 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 2, character: 2 }, - end: { line: 3, character: 3 }, - }); - }); - - test("returns correct intersection when ranges touch at the edge", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 2, character: 0 }, - }; - - rangeB = { - start: { line: 2, character: 0 }, - end: { line: 3, character: 0 }, - }; - - const result = intersection(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 2, character: 0 }, - end: { line: 2, character: 0 }, - }); - }); -}); diff --git a/core/test/util/ranges/maxMinPosition.test.ts b/core/test/util/ranges/maxMinPosition.test.ts deleted file mode 100644 index 0468df1cd..000000000 --- a/core/test/util/ranges/maxMinPosition.test.ts +++ /dev/null @@ -1,70 +0,0 @@ -import { maxPosition, minPosition } from "../../../util/ranges"; - -// This file is generated by Continue -interface Position { - line: number; - character: number; -} - -describe("Position comparison functions", () => { - let pos1: Position; - let pos2: Position; - let pos3: Position; - let pos4: Position; - - beforeAll(() => { - // Setup: Initializing positions - pos1 = { line: 1, character: 5 }; - pos2 = { line: 2, character: 3 }; - pos3 = { line: 1, character: 7 }; - pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality - }); - - describe("maxPosition", () => { - it("should return the position with the greater line number", () => { - expect(maxPosition(pos1, pos2)).toEqual(pos2); - }); - - it("should return the position with the greater character number when lines are equal", () => { - expect(maxPosition(pos1, pos3)).toEqual(pos3); - }); - - it("should return the first position when both positions are equal", () => { - expect(maxPosition(pos2, pos4)).toEqual(pos2); - }); - - it("should handle positions with negative line numbers", () => { - const posNegative = { line: -1, character: 0 }; - expect(maxPosition(posNegative, pos1)).toEqual(pos1); - }); - - it("should handle positions with negative character numbers", () => { - const posNegativeChar = { line: 1, character: -1 }; - expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1); - }); - }); - - describe("minPosition", () => { - it("should return the position with the lesser line number", () => { - expect(minPosition(pos1, pos2)).toEqual(pos1); - }); - - it("should return the position with the lesser character number when lines are equal", () => { - expect(minPosition(pos1, pos3)).toEqual(pos1); - }); - - it("should return the first position when both positions are equal", () => { - expect(minPosition(pos2, pos4)).toEqual(pos2); - }); - - it("should handle positions with negative line numbers", () => { - const posNegative = { line: -1, character: 0 }; - expect(minPosition(posNegative, pos1)).toEqual(posNegative); - }); - - it("should handle positions with negative character numbers", () => { - const posNegativeChar = { line: 1, character: -1 }; - expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar); - }); - }); -}); diff --git a/core/test/util/ranges/union.test.ts b/core/test/util/ranges/union.test.ts deleted file mode 100644 index 9d06a97b4..000000000 --- a/core/test/util/ranges/union.test.ts +++ /dev/null @@ -1,92 +0,0 @@ -import { union } from "../../../util/ranges"; - -// This file is generated by Continue -interface Position { - line: number; - character: number; -} - -interface Range { - start: Position; - end: Position; -} - -describe("union", () => { - let rangeA: Range; - let rangeB: Range; - - beforeEach(() => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 3, character: 5 }, - }; - - rangeB = { - start: { line: 2, character: 3 }, - end: { line: 4, character: 2 }, - }; - }); - - test("should return the union of two overlapping ranges", () => { - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 4, character: 2 }, - }); - }); - - test("should return the union when ranges are identical", () => { - const result = union(rangeA, rangeA); - expect(result).toEqual(rangeA); - }); - - test("should return the union when ranges do not overlap but are adjacent", () => { - rangeB = { - start: { line: 3, character: 5 }, - end: { line: 4, character: 2 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 4, character: 2 }, - }); - }); - - test("should return the union when one range is completely within the other", () => { - rangeB = { - start: { line: 2, character: 1 }, - end: { line: 2, character: 4 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual(rangeA); - }); - - test("should return the union when ranges do not overlap and are not adjacent", () => { - rangeB = { - start: { line: 4, character: 3 }, - end: { line: 5, character: 1 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 5, character: 1 }, - }); - }); - - // TODO - test.skip("should handle edge case where start and end lines are the same", () => { - rangeA = { - start: { line: 1, character: 0 }, - end: { line: 1, character: 5 }, - }; - rangeB = { - start: { line: 1, character: 3 }, - end: { line: 1, character: 7 }, - }; - const result = union(rangeA, rangeB); - expect(result).toEqual({ - start: { line: 1, character: 0 }, - end: { line: 1, character: 7 }, - }); - }); -}); diff --git a/core/util/LruCache.ts b/core/util/LruCache.ts index f6d923fed..86925a6bc 100644 --- a/core/util/LruCache.ts +++ b/core/util/LruCache.ts @@ -1,7 +1,7 @@ export class PrecalculatedLruCache { private items: [string, V][] = []; constructor( - private readonly calculateValue: (key: string) => Promise, + private readonly calculateValue: (key: string) => Promise, private readonly N: number, ) {} @@ -11,7 +11,11 @@ export class PrecalculatedLruCache { if (index < 0) { // Calculate info for new file - const value: V = await this.calculateValue(key); + const value: V | null = await this.calculateValue(key); + + if (value === null) { + return; + } this.items.push([key, value]); if (this.items.length > this.N) { diff --git a/core/util/chatDescriber.ts b/core/util/chatDescriber.ts index b52fd7696..70b7a27b7 100644 --- a/core/util/chatDescriber.ts +++ b/core/util/chatDescriber.ts @@ -1,23 +1,9 @@ import { ILLM, LLMFullCompletionOptions } from ".."; -import { removeQuotesAndEscapes } from "."; +import { removeQuotesAndEscapes, removeCodeBlocksAndTrim } from "."; -import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; import type { IMessenger } from "./messenger"; - -/** - * Removes code blocks from a message. - * - * Return modified message text. - */ -function removeCodeBlocksAndTrim(msgText: string): string { - const codeBlockRegex = /```[\s\S]*?```/g; - - // Remove code blocks from the message text - const textWithoutCodeBlocks = msgText.replace(codeBlockRegex, ""); - - return textWithoutCodeBlocks.trim(); -} +import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; export class ChatDescriber { static prompt: string | undefined = diff --git a/core/util/constants.ts b/core/util/constants.ts new file mode 100644 index 000000000..188fc0005 --- /dev/null +++ b/core/util/constants.ts @@ -0,0 +1 @@ +export const NEW_SESSION_TITLE = "New Session"; diff --git a/core/test/util/history.test.ts b/core/util/history.test.ts similarity index 95% rename from core/test/util/history.test.ts rename to core/util/history.test.ts index 270e81248..dbcf69619 100644 --- a/core/test/util/history.test.ts +++ b/core/util/history.test.ts @@ -1,8 +1,9 @@ import { v4 as uuidv4 } from "uuid"; -import { Session } from "../.."; -import historyManager from "../../util/history"; -import { getSessionFilePath } from "../../util/paths"; +import { Session } from ".."; +import { NEW_SESSION_TITLE } from "./constants"; +import historyManager from "./history"; +import { getSessionFilePath } from "./paths"; const sessionId = uuidv4(); const testSession: Session = { @@ -31,7 +32,7 @@ describe("No sessions have been created", () => { const session = historyManager.load(testSessionId); expect(session).toEqual({ history: [], - title: "Failed to load session", + title: NEW_SESSION_TITLE, workspaceDirectory: "", sessionId: testSessionId, }); diff --git a/core/util/history.ts b/core/util/history.ts index 053c23455..622c2c9ce 100644 --- a/core/util/history.ts +++ b/core/util/history.ts @@ -3,8 +3,8 @@ import * as fs from "fs"; import { Session, SessionMetadata } from "../index.js"; import { ListHistoryOptions } from "../protocol/core.js"; +import { NEW_SESSION_TITLE } from "./constants.js"; import { getSessionFilePath, getSessionsListPath } from "./paths.js"; - function safeParseArray( value: string, errorMessage: string = "Error parsing array", @@ -80,7 +80,7 @@ class HistoryManager { console.log(`Error loading session: ${e}`); return { history: [], - title: "Failed to load session", + title: NEW_SESSION_TITLE, workspaceDirectory: "", sessionId: sessionId, }; diff --git a/core/util/index.ts b/core/util/index.ts index 7f46278f9..9a896baff 100644 --- a/core/util/index.ts +++ b/core/util/index.ts @@ -328,3 +328,17 @@ export function dedent(strings: TemplateStringsArray, ...values: any[]) { return lines.join("\n"); } + +/** + * Removes code blocks from a message. + * + * Return modified message text. + */ +export function removeCodeBlocksAndTrim(text: string): string { + const codeBlockRegex = /```[\s\S]*?```/g; + + // Remove code blocks from the message text + const textWithoutCodeBlocks = text.replace(codeBlockRegex, ""); + + return textWithoutCodeBlocks.trim(); +} diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 8029c0609..daa12827d 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -231,7 +231,13 @@ export async function getSymbolsForFile( return; } - const tree = parser.parse(contents); + let tree: Parser.Tree; + try { + tree = parser.parse(contents); + } catch (e) { + console.log(`Error parsing file: ${filepath}`); + return; + } // console.log(`file: ${filepath}`); // Function to recursively find all named nodes (classes and functions) diff --git a/core/util/tts.ts b/core/util/tts.ts index efae302c2..1fd41607c 100644 --- a/core/util/tts.ts +++ b/core/util/tts.ts @@ -1,6 +1,8 @@ import { exec, ChildProcess } from "child_process"; import os from "node:os"; +import { removeCodeBlocksAndTrim } from "."; + import type { IMessenger } from "./messenger"; import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; @@ -8,27 +10,13 @@ import type { FromCoreProtocol, ToCoreProtocol } from "../protocol"; // a zombie after executing .kill() const ttsKillTimeout: number = 5000; -/** - * Removes code blocks from a message. - * - * Return modified message text. - */ -function removeCodeBlocks(msgText: string): string { - const codeBlockRegex = /```[\s\S]*?```/g; - - // Remove code blocks from the message text - const textWithoutCodeBlocks = msgText.replace(codeBlockRegex, ""); - - return textWithoutCodeBlocks.trim(); -} - /** * Cleans a message text to safely be used in 'exec' context on host. * * Return modified message text. */ -function sanitizeMessageForTTS(message: string): string { - message = removeCodeBlocks(message); +export function sanitizeMessageForTTS(message: string): string { + message = removeCodeBlocksAndTrim(message); // Remove or replace problematic characters message = message diff --git a/core/util/withExponentialBackoff.ts b/core/util/withExponentialBackoff.ts index efe9d95c1..84b301b26 100644 --- a/core/util/withExponentialBackoff.ts +++ b/core/util/withExponentialBackoff.ts @@ -2,7 +2,7 @@ interface APIError extends Error { response?: Response; } -const RETRY_AFTER_HEADER = "Retry-After"; +export const RETRY_AFTER_HEADER = "Retry-After"; const withExponentialBackoff = async ( apiCall: () => Promise, @@ -18,8 +18,12 @@ const withExponentialBackoff = async ( (error as APIError).response?.status === 429 && attempt < maxRetries - 1 ) { - const retryAfter = (error as APIError).response?.headers.get(RETRY_AFTER_HEADER); - const delay = retryAfter ? parseInt(retryAfter, 10) : initialDelaySeconds * 2 ** attempt; + const retryAfter = (error as APIError).response?.headers.get( + RETRY_AFTER_HEADER, + ); + const delay = retryAfter + ? parseInt(retryAfter, 10) + : initialDelaySeconds * 2 ** attempt; console.log( `Hit rate limit. Retrying in ${delay} seconds (attempt ${ attempt + 1 diff --git a/docs/docs/chat/how-to-customize.md b/docs/docs/chat/how-to-customize.md index 9df6ec020..ee26a6a84 100644 --- a/docs/docs/chat/how-to-customize.md +++ b/docs/docs/chat/how-to-customize.md @@ -12,3 +12,4 @@ There are a number of different ways to customize Chat - You can create your own [custom code RAG](../customize/tutorials/custom-code-rag.md) - You can configure [`@Docs`](../customize/deep-dives/docs.md) - You can [build your own context provider](../customize/tutorials/build-your-own-context-provider.md) +- You can configure and create custom [tools](../customize/tools.md) diff --git a/docs/docs/customize/context-providers.md b/docs/docs/customize/context-providers.md index 2c7708cac..024786e14 100644 --- a/docs/docs/customize/context-providers.md +++ b/docs/docs/customize/context-providers.md @@ -444,7 +444,7 @@ Available connection types: ### `@Debugger` -Reference the contents of the local variables in the debugger. +Reference the contents of the local variables in the debugger. Currently only available in VS Code. ```json title="config.json" { diff --git a/docs/docs/customize/deep-dives/configuration.md b/docs/docs/customize/deep-dives/configuration.md index dab15ac4c..62f79952e 100644 --- a/docs/docs/customize/deep-dives/configuration.md +++ b/docs/docs/customize/deep-dives/configuration.md @@ -31,7 +31,7 @@ The format of `.continuerc.json` is the same as `config.json`, plus one _additio Example -```json title="config.json" +```json title=".continuerc.json" { "tabAutocompleteOptions": { "disable": true diff --git a/docs/docs/customize/deep-dives/rules.md b/docs/docs/customize/deep-dives/rules.md index 30100aaeb..f53135b50 100644 --- a/docs/docs/customize/deep-dives/rules.md +++ b/docs/docs/customize/deep-dives/rules.md @@ -5,7 +5,7 @@ keywords: [rules, .continuerules, system, prompt, message] # `.continuerules` -You can create a project-specific system message by adding a `.continuerules` file to the root of your project. This file is raw text and its contents will be inserted into the system message for all LLM requests. +You can create a project-specific system message by adding a `.continuerules` file to the root of your project. This file is raw text and its contents will be inserted into the system message for all chat requests. Rules are not used for autocomplete. ## Simple Examples diff --git a/docs/docs/customize/model-providers/top-level/bedrock.md b/docs/docs/customize/model-providers/top-level/bedrock.md index 8d46c5ad9..fb88d5ae0 100644 --- a/docs/docs/customize/model-providers/top-level/bedrock.md +++ b/docs/docs/customize/model-providers/top-level/bedrock.md @@ -46,9 +46,19 @@ We recommend configuring [`amazon.titan-embed-text-v2:0`](https://docs.aws.amazo ## Reranking model -Bedrock currently does not offer any reranking models. +We recommend configuring `cohere.rerank-v3-5:0` as your reranking model, you may also use `amazon.rerank-v1:0`. -[Click here](../../model-types/reranking.md) to see a list of reranking model providers. +```json title="~/.continue/config.json" +{ + "reranker": { + "name": "bedrock", + "params": { + "model": "cohere.rerank-v3-5:0", + "region": "us-west-2" + } + } +} +``` ## Authentication diff --git a/docs/docs/customize/tools.md b/docs/docs/customize/tools.md new file mode 100644 index 000000000..f18e40387 --- /dev/null +++ b/docs/docs/customize/tools.md @@ -0,0 +1,33 @@ +--- +title: Tools +description: Tool use and customization +keywords: [tool, use, function calling, claude, automatic] +--- + +Tools allow Continue to take action in your IDE and beyond (when you give permission). Currently, they are only supported with [Anthropic](./model-providers/top-level/anthropic.md). To use tools, click on the icon in the input toolbar like below. + +![tools](/img/tool-use-example.png) + +To let you balance speed and safety, each tool can be set to 1 of 3 modes: + +- `Automatic`: When the LLM requests to use the tool, Continue will automatically call it and send the response to the LLM. +- `Allowed`: When the LLM requests to use the tool, Continue will first give you the opportunity to "Cancel" or "Continue" with the tool. +- `Disabled`: The LLM will not know about or be able to use the tool. + +### Custom tools + +Currently custom tools can be configured using the [Model Context Protocol](https://modelcontextprotocol.io/introduction), a standard proposed by Anthropic to unify prompts, context, and tool use. Read their [quickstart](https://modelcontextprotocol.io/quickstart) to learn how to set up a local server and then configure your `config.json` like this: + +```json title="~/.continue/config.json" +{ + "experimental": { + "modelContextProtocolServer": { + "transport": { + "type": "stdio", + "command": "uvx", + "args": ["mcp-server-sqlite", "--db-path", "/Users/NAME/test.db"] + } + } + } +} +``` diff --git a/docs/docs/reference.md b/docs/docs/reference.md index 0a5c02aad..df3f08e75 100644 --- a/docs/docs/reference.md +++ b/docs/docs/reference.md @@ -206,10 +206,11 @@ Configuration for the reranker model used in response ranking. **Properties:** -- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei` +- `name` (**required**): Reranker name, e.g., `cohere`, `voyage`, `llm`, `free-trial`, `huggingface-tei`, `bedrock` - `params`: - `model`: Model name - `apiKey`: Api key + - `region`: Region (for Bedrock only) Example diff --git a/docs/sidebars.js b/docs/sidebars.js index 11f2e2fd3..caa6fdc52 100644 --- a/docs/sidebars.js +++ b/docs/sidebars.js @@ -110,6 +110,7 @@ const sidebars = { }, "customize/context-providers", "customize/slash-commands", + "customize/tools", "customize/development-data", { type: "category", diff --git a/docs/static/img/tool-use-example.png b/docs/static/img/tool-use-example.png new file mode 100644 index 000000000..63f1c456a Binary files /dev/null and b/docs/static/img/tool-use-example.png differ diff --git a/extensions/intellij/.run/Prompt Logs.run.xml b/extensions/intellij/.run/Prompt Logs.run.xml index 23fec409a..ce8c399dd 100644 --- a/extensions/intellij/.run/Prompt Logs.run.xml +++ b/extensions/intellij/.run/Prompt Logs.run.xml @@ -1,6 +1,6 @@ -