Merge branch 'main' into nate/openai-adapters

This commit is contained in:
Nate 2024-12-08 09:47:17 -08:00
commit 24a8bdd556
170 changed files with 3872 additions and 2426 deletions

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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

7
.gitignore vendored
View file

@ -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
*.vsix
binary/.continue

View file

@ -29,14 +29,23 @@ export class ImportDefinitionsService {
return this.cache.get(filepath);
}
private async _getFileInfo(filepath: string): Promise<FileInfo> {
private async _getFileInfo(filepath: string): Promise<FileInfo | null> {
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,

View file

@ -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";

View file

@ -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 {

View file

@ -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;

View file

@ -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) {

View file

@ -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";

View file

@ -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<string, string> = {
diff: diff.join("\n"),

View file

@ -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: {} },

View file

@ -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<number[]> {
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()();
}
}
}

View file

@ -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,
};
};

View file

@ -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 [];

View file

@ -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;

View file

@ -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<string> = new Set();
private selectedModelTitle: string | undefined;
private async config() {
return this.configHandler.loadConfig();
}
private async getSelectedModel() {
return await this.configHandler.llmFromTitle(this.selectedModelTitle);
}
invoke<T extends keyof ToCoreProtocol>(
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(

61
core/index.d.ts vendored
View file

@ -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<ContextItem[]>;
loadSubmenuItems?: (
args: LoadSubmenuItemsArgs,
) => Promise<ContextSubmenuItem[]>;
@ -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<T, Keys extends keyof T = keyof T> = Pick<
T,
Exclude<keyof T, Keys>
@ -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<IdeInfo>;
getIdeSettings(): Promise<IdeSettings>;
getDiff(includeUnstaged: boolean): Promise<string[]>;
getClipboardContent(): Promise<{ text: string; copiedAt: string }>;
isTelemetryEnabled(): Promise<boolean>;
getUniqueId(): Promise<string>;
getTerminalContents(): Promise<string>;
getDebugLocals(threadIndex: number): Promise<string>;
getTopLevelCallStackSources(
threadIndex: number,
stackDepth: number,
): Promise<string[]>;
getAvailableThreads(): Promise<Thread[]>;
listFolders(): Promise<string[]>;
getWorkspaceDirs(): Promise<string[]>;
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
fileExists(filepath: string): Promise<boolean>;
writeFile(path: string, contents: string): Promise<void>;
showVirtualFile(title: string, contents: string): Promise<void>;
getContinueDir(): Promise<string>;
openFile(path: string): Promise<void>;
openUrl(url: string): Promise<void>;
runCommand(command: string): Promise<void>;
saveFile(filepath: string): Promise<void>;
readFile(filepath: string): Promise<string>;
readRangeInFile(filepath: string, range: Range): Promise<string>;
showLines(
filepath: string,
startLine: number,
endLine: number,
): Promise<void>;
showDiff(
filepath: string,
newContents: string,
stepIndex: number,
): Promise<void>;
getOpenFiles(): Promise<string[]>;
getCurrentFile(): Promise<
| undefined
| {
@ -612,21 +650,33 @@ export interface IDE {
contents: string;
}
>;
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
subprocess(command: string, cwd?: string): Promise<[string, string]>;
getProblems(filepath?: string | undefined): Promise<Problem[]>;
getBranch(dir: string): Promise<string>;
getTags(artifactId: string): Promise<IndexTag[]>;
getRepoName(dir: string): Promise<string | undefined>;
showToast(
type: ToastType,
message: string,
...otherParams: any[]
): Promise<any>;
getGitRootPath(dir: string): Promise<string | undefined>;
listDir(dir: string): Promise<[string, FileType][]>;
getLastModified(files: string[]): Promise<{ [path: string]: number }>;
getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined>;
// LSP
@ -634,6 +684,7 @@ export interface IDE {
// Callbacks
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void;
pathSep(): Promise<string>;
}
@ -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<number[][]>;
}
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<number[]>;
}

View file

@ -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";

View file

@ -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;

View file

@ -145,9 +145,7 @@ export class CodebaseIndexer {
}
}
async *refreshFiles(
files: string[],
): AsyncGenerator<IndexingProgressUpdate> {
async *refreshFiles(files: string[]): AsyncGenerator<IndexingProgressUpdate> {
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;
}

View file

@ -4,7 +4,7 @@ import {
insertMockChunks,
mockPathAndCacheKey,
updateIndexAndAwaitGenerator,
} from "../test/util/indexing";
} from "./test/indexing";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";

View file

@ -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";

View file

@ -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";

View file

@ -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";

View file

@ -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];

View file

@ -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);
}

View file

@ -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 = {

View file

@ -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);

View file

@ -8,8 +8,8 @@ export default {
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",
"^uuid$": "uuid", // https://stackoverflow.com/a/73626360
'^@azure/(.*)$': '<rootDir>/node_modules/@azure/$1',
'^mssql$': '<rootDir>/node_modules/mssql'
"^@azure/(.*)$": "<rootDir>/node_modules/@azure/$1",
"^mssql$": "<rootDir>/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: "<rootDir>/jest.global-setup.ts",
setupFilesAfterEnv: ["<rootDir>/jest.setup-after-env.ts"],
maxWorkers: 1 // equivalent to CLI --runInBand
};

View file

@ -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);

View file

@ -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)) {

View file

@ -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();

View file

@ -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;

View file

@ -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 {

39
core/llm/llms/Test.ts Normal file
View file

@ -0,0 +1,39 @@
import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js";
import { BaseLLM } from "../index.js";
const RESPONSES: Record<string, string> = {
"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<string> {
yield this.findResponse(prompt) || `PROMPT: ${prompt}`;
}
protected async *_streamChat(
messages: ChatMessage[],
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<ChatMessage> {
for (const char of HARDCODED_CHAT_RESPONSE) {
yield {
role: "assistant",
content: char,
};
}
}
}
export default TestLLM;

View file

@ -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,

View file

@ -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"
},

View file

@ -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",

View file

@ -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<DiffLine>,
];
"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[] },
];
};

View file

@ -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 & {

View file

@ -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",

View file

@ -1 +0,0 @@
scratch.test.ts

View file

@ -1,2 +0,0 @@
def average(nums: list) -> float:
pass

View file

@ -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";

View file

@ -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)) {

View file

@ -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", " "]);
});
});

View file

@ -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("");
});
});

View file

@ -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));
});
});

View file

@ -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 } } });
});
});

View file

@ -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");
});
});

View file

@ -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 },
});
});
});

View file

@ -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);
});
});
});

View file

@ -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 },
});
});
});

View file

@ -1,7 +1,7 @@
export class PrecalculatedLruCache<V> {
private items: [string, V][] = [];
constructor(
private readonly calculateValue: (key: string) => Promise<V>,
private readonly calculateValue: (key: string) => Promise<V | null>,
private readonly N: number,
) {}
@ -11,7 +11,11 @@ export class PrecalculatedLruCache<V> {
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) {

View file

@ -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 =

1
core/util/constants.ts Normal file
View file

@ -0,0 +1 @@
export const NEW_SESSION_TITLE = "New Session";

View file

@ -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,
});

View file

@ -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<T>(
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,
};

View file

@ -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();
}

View file

@ -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)

View file

@ -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

View file

@ -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 <T>(
apiCall: () => Promise<T>,
@ -18,8 +18,12 @@ const withExponentialBackoff = async <T>(
(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

View file

@ -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)

View file

@ -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"
{

View file

@ -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

View file

@ -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

View file

@ -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

View file

@ -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"]
}
}
}
}
```

View file

@ -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

View file

@ -110,6 +110,7 @@ const sidebars = {
},
"customize/context-providers",
"customize/slash-commands",
"customize/tools",
"customize/development-data",
{
type: "category",

BIN
docs/static/img/tool-use-example.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 105 KiB

View file

@ -1,6 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Prompt Logs" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="mkdir -p ./binary/.continue/logs &amp;&amp; touch ./binary/.continue/logs/prompt.log &amp;&amp; tail -f ./binary/.continue/logs/prompt.log" />
<option name="SCRIPT_TEXT" value="mkdir -p ./extensions/.continue-debug/logs &amp;&amp; touch ./extensions/.continue-debug/logs/prompt.log &amp;&amp; tail -f ./extensions/.continue-debug/logs/prompt.log" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />

View file

@ -1,6 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Start Core Dev Server (CE)" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="export CONTINUE_DEVELOPMENT=true &amp;&amp; export CONTINUE_GLOBAL_DIR=$PROJECT_DIR$/binary/.continue &amp;&amp; node out/index.js" />
<option name="SCRIPT_TEXT" value="export CONTINUE_DEVELOPMENT=true &amp;&amp; export CONTINUE_GLOBAL_DIR=$PROJECT_DIR$/extensions/.continue-debug &amp;&amp; node out/index.js" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />

View file

@ -2,7 +2,7 @@
<configuration default="false" name="Start Core Dev Server" type="NodeJSConfigurationType" path-to-js-file="out/index.js" working-dir="$PROJECT_DIR$/binary">
<envs>
<env name="CONTINUE_DEVELOPMENT" value="true" />
<env name="CONTINUE_GLOBAL_DIR" value="$PROJECT_DIR$/binary/.continue" />
<env name="CONTINUE_GLOBAL_DIR" value="$PROJECT_DIR$/extensions/.continue-debug" />
</envs>
<method v="2" />
</configuration>

View file

@ -71,7 +71,7 @@ This should open a new instance on IntelliJ with the extension installed.
### Accessing files in the `.continue` directory
When running the `Start Core Dev Server` task, we set the location of your Continue directory to `./binary/.continue`. This is to
When running the `Start Core Dev Server` task, we set the location of your Continue directory to `./extensions/.continue-debug`. This is to
allow for changes to your `config.json` and other files during development, without affecting your actual configuration.
### Reloading changes

View file

@ -3,7 +3,7 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=0.0.82
pluginVersion=0.0.83
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension

View file

@ -123,4 +123,28 @@ class ViewHistoryAction : AnAction() {
val continuePluginService = getContinuePluginService(e.project) ?: return
continuePluginService.sendToWebview("viewHistory", null)
}
}
class OpenConfigAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val continuePluginService = getContinuePluginService(e.project) ?: return
val params = mapOf("profileId" to null)
continuePluginService.coreMessenger?.request("config/openProfile", params, null) { _ -> }
}
}
class OpenMorePageAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val continuePluginService = getContinuePluginService(e.project) ?: return
continuePluginService.continuePluginWindow?.content?.components?.get(0)?.requestFocus()
val params = mapOf("path" to "/more", "toggle" to true)
continuePluginService.sendToWebview("navigateTo", params)
}
}
class OpenAccountDialogAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val continuePluginService = getContinuePluginService(e.project) ?: return
continuePluginService.sendToWebview("openDialogMessage", "account")
}
}

View file

@ -12,7 +12,7 @@ class ContinueAuthDialog(private val onTokenEntered: (String) -> Unit) : DialogW
init {
init()
title = "Enter Continue Authentication Token"
title = "Continue authentication"
}
override fun createCenterPanel(): JComponent {

View file

@ -51,6 +51,7 @@ import java.net.NetworkInterface
import java.nio.charset.Charset
import java.nio.file.Paths
import java.util.*
import kotlin.coroutines.resume
fun uuid(): String {
@ -106,7 +107,9 @@ class AsyncFileSaveListener(private val ideProtocolClient: IdeProtocolClient) :
for (event in events) {
if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith(
".continue\\config.json"
) || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json") || event.path.endsWith(".continuerc.json")
) || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json") || event.path.endsWith(
".continuerc.json"
)
) {
return object : AsyncFileListener.ChangeApplier {
override fun afterVfsChange() {
@ -662,18 +665,41 @@ class IdeProtocolClient(
var llm = getModelByRole(config, "applyCodeBlock")
if (llm == null) {
val models = (config as? Map<*, *>)?.get("models") as? List<Map<*, *>>
llm = models?.find { model -> model["title"] == curSelectedModelTitle } as Map<String, Any>
llm = try {
suspendCancellableCoroutine { continuation ->
continuePluginService.coreMessenger?.request(
"config/getSerializedProfileInfo",
null,
null
) { response ->
val models =
((response as Map<String, Any>)["config"] as Map<String, Any>)["models"] as List<Map<String, Any>>
val foundModel = models.find { it["title"] == curSelectedModelTitle }
if (llm == null) {
showToast("error", "Model '$curSelectedModelTitle' not found in config.")
if (foundModel == null) {
launch {
showToast(
"error",
"Model '$curSelectedModelTitle' not found in config."
)
}
continuation.resume(null)
} else {
continuation.resume(foundModel)
}
}
}
} catch (e: Exception) {
launch { showToast("error", "Failed to fetch model configuration") }
respond(null)
return@launch
}
}
val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: ""
val prompt =
"The following code was suggested as an edit:\n```\n${text}\n```\nPlease apply it to the previous code."

View file

@ -271,12 +271,6 @@ class ContinueExtensionConfigurable : Configurable {
* it's a simple integer without dot notation, making it easier to compare.
*/
private fun shouldRenderOffScreen(): Boolean {
// With the 0.0.77 release, non-Mac users have been reporting issues with paste functionality
// in the browser. Disabling OSR for all non-Mac users for now.
if (!SystemInfo.isMac) {
return false
}
val minBuildNumber = 233
val applicationInfo = ApplicationInfo.getInstance()
val currentBuildNumber = applicationInfo.build.baselineVersion

View file

@ -28,7 +28,6 @@ class ContinueBrowser(val project: Project, url: String) {
private val heightChangeListeners = mutableListOf<(Int) -> Unit>()
private val PASS_THROUGH_TO_CORE = listOf(
"update/modelChange",
"ping",
"abort",
"history/list",
@ -138,7 +137,7 @@ class ContinueBrowser(val project: Project, url: String) {
}
"jetbrains/isOSREnabled" -> {
sendToWebview( "jetbrains/isOSREnabled", isOSREnabled)
respond(isOSREnabled)
}
"onLoad" -> {
@ -268,7 +267,9 @@ class ContinueBrowser(val project: Project, url: String) {
val jsCode = buildJavaScript(jsonData)
try {
this.browser.executeJavaScriptAsync(jsCode)
this.browser.executeJavaScriptAsync(jsCode).onError {
println("Failed to execute jsCode error: ${it.message}")
}
} catch (error: IllegalStateException) {
println("Webview not initialized yet $error")
}

View file

@ -15,7 +15,7 @@
<ProviderFactory
implementation="com.github.continuedev.continueintellijextension.continue.ConfigJsonSchemaProviderFactory"/>
</extensions>
<extensions defaultExtensionNs="JavaScript.JsonSchema">
<extensions defaultExtensionNs="JavaScript.JsonSchema">
<ProviderFactory
implementation="com.github.continuedev.continueintellijextension.continue.ConfigRcJsonSchemaProviderFactory"/>
</extensions>
@ -120,10 +120,10 @@
<action id="continue.newContinueSession"
icon="AllIcons.General.Add"
class="com.github.continuedev.continueintellijextension.actions.NewContinueSessionAction"
text="Start New Continue Session"
description="Start New Continue Session">
text="New Session"
description="New Session">
<override-text place="GoToAction" text="Continue: New Session"/>
<override-text place="GoToAction" text="New Session"/>
</action>
<action id="continue.viewHistory"
@ -131,9 +131,41 @@
class="com.github.continuedev.continueintellijextension.actions.ViewHistoryAction"
text="View History"
description="View History">
<override-text place="GoToAction" text="Continue: View History"/>
<override-text place="GoToAction" text="View History"/>
</action>
<action id="continue.openConfig"
class="com.github.continuedev.continueintellijextension.actions.OpenConfigAction"
icon="AllIcons.General.GearPlain"
text="Open Continue Config"
description="Open Continue Config">
<override-text place="GoToAction" text="Open Continue Config"/>
</action>
<action id="continue.openAccountDialog"
class="com.github.continuedev.continueintellijextension.actions.OpenAccountDialogAction"
icon="AllIcons.CodeWithMe.CwmAccess"
text="Account"
description="Account">
<override-text place="GoToAction" text="Account"/>
</action>
<action id="continue.openMorePage"
class="com.github.continuedev.continueintellijextension.actions.OpenMorePageAction"
icon="AllIcons.Actions.MoreHorizontal"
text="More"
description="More">
<override-text place="GoToAction" text="More"/>
</action>
<group id="ContinueSidebarActionsGroup">
<reference ref="continue.newContinueSession"/>
<reference ref="continue.viewHistory"/>
<reference ref="continue.openConfig"/>
<reference ref="continue.openAccountDialog"/>
<reference ref="continue.openMorePage"/>
</group>
<action id="continue.focusContinueInput"
class="com.github.continuedev.continueintellijextension.actions.FocusContinueInputAction"
text="Add selected code to context"
@ -146,11 +178,6 @@
<override-text place="GoToAction" text="Continue: Add Highlighted Code to Context and Clear Chat"/>
</action>
<group id="ContinueSidebarActionsGroup">
<reference ref="continue.newContinueSession"/>
<reference ref="continue.viewHistory"/>
</group>
<action id="com.github.continuedev.continueintellijextension.autocomplete.AcceptAutocompleteAction"
class="com.github.continuedev.continueintellijextension.autocomplete.AcceptAutocompleteAction"
text="Accept Autocomplete Suggestion" description="Accept Autocomplete Suggestion">

View file

@ -16,4 +16,11 @@ gui/**
.devcontainer
.github
continue_rc_schema.json
continue_rc_schema.json
e2e/_output
e2e/.test-extensions
e2e/storage
e2e/vsix
e2e/test-continue/*
!e2e/test-continue/config.json

View file

@ -21,6 +21,7 @@ esbuild.js
esbuild.test.mjs
importMetaUrl.js
scripts
e2e
server/exe/**
!out/node_modules/**

View file

@ -2642,6 +2642,7 @@
"properties": {
"name": {
"enum": [
"bedrock",
"cohere",
"voyage",
"llm",
@ -2743,6 +2744,32 @@
}
}
},
{
"if": {
"properties": {
"name": {
"enum": ["bedrock"]
}
},
"required": ["name"]
},
"then": {
"properties": {
"params": {
"type": "object",
"properties": {
"model": {
"enum": [
"cohere.rerank-v3-5:0",
"amazon.rerank-v1:0"
]
}
},
"required": ["model"]
}
}
}
},
{
"if": {
"properties": {

View file

@ -0,0 +1,27 @@
import { WebElement } from "vscode-extension-tester";
export class TestUtils {
public static async waitForElement(
locatorFn: () => Promise<WebElement>,
timeout: number = 5000,
interval: number = 500,
): Promise<WebElement> {
const startTime = Date.now();
while (Date.now() - startTime < timeout) {
try {
const element = await locatorFn();
if (element) {
return element;
}
} catch (e) {
if (Date.now() - startTime >= timeout) {
throw new Error(`Element not found after ${timeout}ms timeout`);
}
}
await new Promise((resolve) => setTimeout(resolve, interval));
}
throw new Error(`Element not found after ${timeout}ms timeout`);
}
}

View file

@ -0,0 +1,59 @@
import {
WebDriver,
WebElement,
WebView,
Workbench,
} from "vscode-extension-tester";
import { GUISelectors } from "../selectors/GUI.selectors";
import { TestUtils } from "../TestUtils";
export class GUIActions {
public static switchToReactIframe = async (driver: WebDriver) => {
const iframes = await GUISelectors.getAllIframes(driver);
let continueIFrame: WebElement | undefined = undefined;
for (let i = 0; i < iframes.length; i++) {
const iframe = iframes[i];
const src = await iframe.getAttribute("src");
if (src.includes("extensionId=Continue.continue")) {
continueIFrame = iframe;
break;
}
}
if (!continueIFrame) {
throw new Error("Could not find continue iframe");
}
await driver.switchTo().frame(continueIFrame);
await new Promise((res) => {
setTimeout(res, 500);
});
const reactIFrame = await GUISelectors.getReactIframe(driver);
if (!reactIFrame) {
throw new Error("Could not find React iframe");
}
await driver.switchTo().frame(reactIFrame);
};
public static openGui = async () => {
return new Workbench().executeCommand("continue.focusContinueInput");
};
public static selectModelFromDropdown = async (
view: WebView,
option: string,
) => {
const dropdownButton = await GUISelectors.getModelDropdownButton(view);
await dropdownButton.click();
const dropdownOption = await TestUtils.waitForElement(() => {
return GUISelectors.getModelDropdownOption(view, option);
});
await dropdownOption.click();
};
}

View file

@ -0,0 +1,18 @@
#!/bin/bash
# echo pwd
echo "Current directory: $(pwd)"
# Find the latest VSIX file in the build directory
latest_vsix=$(ls -t ./build/continue-*.vsix | head -n1)
if [ -z "$latest_vsix" ]; then
echo "No VSIX file found in build directory"
exit 1
fi
# Create e2e/vsix directory if it doesn't exist
mkdir -p "./e2e/vsix"
# Copy the file to e2e directory with fixed name
cp "$latest_vsix" "./e2e/vsix/continue.vsix"

View file

@ -0,0 +1,40 @@
import { By, WebDriver, WebView } from "vscode-extension-tester";
import { SelectorUtils } from "./SelectorUtils";
export class GUISelectors {
public static getDescription(view: WebView) {
return view.findWebElement(By.xpath("//*[contains(text(), 'Quickly')]"));
}
public static getTipTapEditor(view: WebView) {
return view.findWebElement(By.className("tiptap"));
}
public static getAllIframes(driver: WebDriver) {
return driver.findElements(By.css("iframe"));
}
public static getReactIframe(driver: WebDriver) {
return driver.findElement(By.css("iframe"));
}
public static getSubmitInputButton(view: WebView) {
return SelectorUtils.getElementByDataTestId(view, "submit-input-button");
}
public static getModelDropdownButton(view: WebView) {
return SelectorUtils.getElementByDataTestId(view, "model-select-button");
}
public static getModelDropdownOption(view: WebView, option: string) {
return view.findWebElement(
By.xpath(`//*[@role="listbox"]//*[contains(text(), "${option}")]`),
);
}
public static getThreadMessageByText(view: WebView, text: string) {
return view.findWebElement(
By.xpath(`//*[@class="thread-message"]//*[contains(text(), "${text}")]`),
);
}
}

View file

@ -0,0 +1,16 @@
import { By, WebElement, WebView } from "vscode-extension-tester";
export class SelectorUtils {
/**
* Finds a web element by its data-testid attribute within a WebView.
* @param view - The WebView to search within.
* @param testId - The data-testid value to search for.
* @returns A promise that resolves to the WebElement found.
*/
public static getElementByDataTestId(
view: WebView,
testId: string,
): Promise<WebElement> {
return view.findWebElement(By.css(`[data-testid='${testId}']`));
}
}

View file

@ -0,0 +1,44 @@
{
"ui": {
"displayRawMarkdown": false
},
"models": [
{
"title": "TEST LLM",
"provider": "test",
"model": "this field is not used"
},
{
"title": "Mock",
"provider": "mock",
"model": "this field is not used"
}
],
"analytics": {
"provider": "continue-proxy"
},
"tabAutocompleteModel": {
"title": "Qwen",
"provider": "mistral",
"model": "codestral-latest",
"apiKey": ""
},
"tabAutocompleteOptions": {
"useCache": false
},
"contextProviders": [
{
"name": "docs"
},
{
"name": "diff"
},
{
"name": "url"
},
{
"name": "folder"
}
],
"docs": []
}

View file

@ -0,0 +1,59 @@
import {
EditorView,
WebView,
WebDriver,
VSBrowser,
} from "vscode-extension-tester";
import { expect } from "chai";
import { GUIActions } from "../actions/GUI.actions";
import { GUISelectors } from "../selectors/GUI.selectors";
import * as path from "path";
import { TestUtils } from "../TestUtils";
describe("GUI Test", () => {
let view: WebView;
let driver: WebDriver;
before(async function () {
this.timeout(10000000);
await VSBrowser.instance.openResources(path.join("e2e/test-continue"));
await GUIActions.openGui();
view = new WebView();
driver = view.getDriver();
await GUIActions.switchToReactIframe(driver);
// await new Promise((res) => {
// setTimeout(res, 10000000);
// });
});
after(async () => {
await view.switchBack();
await new EditorView().closeAllEditors();
});
it("should display correct panel description", async () => {
const description = await GUISelectors.getDescription(view);
expect(await description.getText()).has.string(
"Quickly get up and running using our API keys.",
);
}).timeout(20_000);
it("should allow typing text in the editor", async () => {
await GUIActions.selectModelFromDropdown(view, "Mock");
await GUIActions.selectModelFromDropdown(view, "TEST LLM");
const tiptap = await GUISelectors.getTipTapEditor(view);
await tiptap.sendKeys("How are you?");
(await GUISelectors.getSubmitInputButton(view)).click();
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, "I'm fine"),
);
}).timeout(20_000);
});

View file

@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>com.apple.security.cs.disable-library-validation</key>
<true/>
<key>com.apple.security.files.user-selected.read-write</key>
<true/>
<key>com.apple.security.files.downloads.read-write</key>
<true/>
<key>com.apple.security.files.documents.read-write</key>
<true/>
<key>com.apple.security.automation.apple-events</key>
<true/>
</dict>
</plist>

File diff suppressed because it is too large Load diff

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.9.242",
"version": "0.9.241",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -617,12 +617,25 @@
"package:pre-release": "node scripts/package.js --pre-release",
"build:rust": "cargo-cp-artifact -ac sync sync.node -- cargo build --manifest-path ../../sync/Cargo.toml --message-format=json-render-diagnostics",
"build-debug:rust": "npm run build:rust --",
"build-release:rust": "npm run build:rust -- --release"
"build-release:rust": "npm run build:rust -- --release",
"e2e:compile": "tsc -p ./tsconfig.e2e.json",
"e2e:create-storage": "mkdir -p ./e2e/storage",
"e2e:get-chromedriver": "extest get-chromedriver --storage ./e2e/storage",
"e2e:get-vscode": "extest get-vscode --storage ./e2e/storage",
"e2e:sign-vscode": "codesign --entitlements entitlements.plist --deep --force -s - './e2e/storage/Visual Studio Code.app'",
"e2e:copy-vsix": "chmod +x ./e2e/get-latest-vsix.sh && bash ./e2e/get-latest-vsix.sh",
"e2e:install-vsix": "extest install-vsix -f ./e2e/vsix/continue.vsix --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage",
"e2e:test": "extest run-tests './e2e/_output/tests/*.test.js' --code_settings settings.json --extensions_dir ./e2e/.test-extensions --storage ./e2e/storage",
"e2e:clean": "rm -rf ./e2e/_output",
"e2e:all": "npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:sign-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean",
"e2e:quick": "npm run e2e:compile && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test && npm run e2e:clean",
"e2e:ci": "npm run e2e:compile && npm run e2e:create-storage && npm run e2e:get-chromedriver && npm run e2e:get-vscode && npm run e2e:copy-vsix && npm run e2e:install-vsix && CONTINUE_GLOBAL_DIR=e2e/test-continue npm run e2e:test"
},
"devDependencies": {
"@biomejs/biome": "1.6.4",
"@nestjs/common": "^8.4.7",
"@openapitools/openapi-generator-cli": "^2.5.2",
"@types/chai": "^5.0.1",
"@types/cors": "^2.8.17",
"@types/express": "^4.17.21",
"@types/follow-redirects": "^1.14.4",
@ -636,6 +649,7 @@
"@typescript-eslint/eslint-plugin": "^5.45.0",
"@vscode/vsce": "^2.22.0",
"cargo-cp-artifact": "^0.1",
"chai": "^4.5.0",
"esbuild": "0.17.19",
"eslint": "^8.28.0",
"glob": "^8.0.3",
@ -645,7 +659,8 @@
"rimraf": "^5.0.5",
"typescript": "^5.3.3",
"vite": "^4.3.9",
"vsce": "^2.15.0"
"vsce": "^2.15.0",
"vscode-extension-tester": "^8.10.0"
},
"dependencies": {
"@electron/rebuild": "^3.2.10",

View file

@ -0,0 +1,8 @@
{
"typescript.updateImportsOnFileMove.enabled": "always",
"workbench.editor.enablePreview": true,
"git.autoRepositoryDetection": false,
"terminal.integrated.sendKeybindingsToShell": true,
"workbench.remoteIndicator.showExtensionRecommendations": false,
"extensions.ignoreRecommendations": true
}

View file

@ -22,9 +22,7 @@ export class ContinueGUIWebviewViewProvider
private updateDebugLogsStatus() {
const settings = vscode.workspace.getConfiguration(EXTENSION_NAME);
this.enableDebugLogs = settings.get<boolean>("enableDebugLogs", false);
if (this.enableDebugLogs) {
this.outputChannel.show(true);
} else {
if (!this.enableDebugLogs) {
this.outputChannel.hide();
}
}
@ -35,9 +33,7 @@ export class ContinueGUIWebviewViewProvider
if (event.affectsConfiguration("continue.enableDebugLogs")) {
const settings = vscode.workspace.getConfiguration(EXTENSION_NAME);
const enableDebugLogs = settings.get<boolean>("enableDebugLogs", false);
if (enableDebugLogs) {
this.outputChannel.show(true);
} else {
if (!enableDebugLogs) {
this.outputChannel.hide();
}
}

Some files were not shown because too many files have changed in this diff Show more