Merge branch 'main' into nate/config-yaml

This commit is contained in:
Nate 2024-12-09 18:45:58 -08:00
commit 3f0bda4775
153 changed files with 4904 additions and 948 deletions

View file

@ -0,0 +1,41 @@
name: Write Core Unit 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.
IMPORTANT Use ESM to import modules, do NOT use `require` anywhere
Tests are to be described in an adjacent file with a path identical except for a `.test.ts` rather than a `.ts` file extension
Use double quotes (or backticks if needed) for strings
The code being tested is used in IDE extensions, and it:
- accesses code workspaces through the IDE ("workspace directories")
- persists extension-related data to the the local machine of the user ("global directory"), and
- uses configuration via a `ConfigHandler`, which is stored in either the global directory (default) or accesed via a remote "control plane" using the `ControlPlaneClient`
Jest testing setup includes
- @core/test/jest.global-setup.ts initializes a temporary global directory, which is where files that store persisted extension data live.
- @core/test/testDir.ts provides utils for creating and working with the temporary workspace directory. Use `setUpTestDir` and `tearDownTestDir` explicitly in tests that work with workspace files
- @core/test/jest.setup-after-env.ts gives tests access to node and jest globals
@core/test/fixtures.ts provides fixtures that should be used in tests to emulate extension behavior
- import `testIde` for IDE/workspace operations
- import `testConfigHandler` for any ConfigHandler needs
- import `testControlPlaneClient` for control plane operations
- import `ideSettingsPromise` for any IdeSettings needs
- import `testLLM` for any ILLM/BaseLLM needs. Set the `completion` property to the desired completion, e.g. `testLLM.completion = "Desired completion";`
Do NOT write tests for any files in `core/test`, only use them as helpers for testing other files. If no other files are provided, warn the user and write no tests.
IMPORTANT: Do NOT mock the fixtures above other than using `jest.spyOn`. DO mock 3rd party modules, etc. when sensible.
Instead, generate actual mock files and data for operations
Pure mocks should only be used to emulate specific network responses/error or hard-to-duplicate errors, or to prevent long-duration tests
Additional types can be imported from @core/index.d.ts
If any needed types, functions, constants, or classes are still not found, warn the user and do not generate tests.
Write the comment "// Generated by continue" at the top of the generated code/file (not the filepath)

View file

@ -1,27 +0,0 @@
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

5
.gitignore vendored
View file

@ -152,7 +152,6 @@ Icon
Icon?
.continuerc.json
.prompts/
.aider*
notes.md
@ -167,6 +166,4 @@ extensions/intellij/.idea/**
extensions/intellij/bin
extensions/.continue-debug/
*.vsix
binary/.continue
*.vsix

34
.vscode/tasks.json vendored
View file

@ -1,12 +1,29 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "tsc:watch",
"type": "npm",
"script": "tsc:watch",
"isBackground": true,
"problemMatcher": {
"base": "$tsc-watch",
"background": {
"activeOnStart": true,
"beginsPattern": "Starting compilation in watch mode...",
"endsPattern": "Found 0 errors"
}
},
"presentation": {
"revealProblems": "onProblem"
}
},
// Compile and bundle the extension
{
"label": "vscode-extension:build",
"dependsOn": [
// To detect compile errors
"vscode-extension:tsc",
// TSC type checking
"tsc:watch",
// To build the React app that is used in the extension
"vscode-extension:continue-ui:build",
// // To bundle the code the same way we do for publishing
@ -46,17 +63,6 @@
}
]
},
{
"label": "vscode-extension:tsc",
"type": "npm",
"script": "tsc",
"path": "extensions/vscode",
"problemMatcher": ["$tsc"],
"presentation": {
"revealProblems": "onProblem",
"clear": true
}
},
// Build the React app. It gets bundled into the extension as a file resource and has a seprate build step
{
"label": "vscode-extension:continue-ui:build",
@ -80,7 +86,7 @@
// Build the extension
"vscode-extension:build",
// To detect compile errors - this type checks both the extension and the tests
"vscode-extension:tsc",
"tsc:watch",
"vscode-extension:tests:esbuild"
]
},

View file

@ -48,7 +48,9 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.13",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "^1.0.10",
"@modelcontextprotocol/sdk": "^1.0.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
@ -81,7 +83,7 @@
"node-html-markdown": "^1.3.0",
"ollama": "^0.4.6",
"onnxruntime-node": "1.14.0",
"openai": "^4.20.1",
"openai": "^4.76.0",
"p-limit": "^6.1.0",
"partial-json": "^0.1.7",
"pg": "^8.11.3",

View file

@ -1,5 +1,5 @@
import { TODO } from "core/util";
import { MessageIde } from "core/util/messageIde";
import { MessageIde } from "core/protocol/messenger/messageIde";
export class IpcIde extends MessageIde {
constructor(messenger: TODO) {

View file

@ -1,5 +1,5 @@
import { IProtocol } from "core/protocol/index.js";
import { IMessenger, type Message } from "core/util/messenger";
import { IMessenger, type Message } from "core/protocol/messenger";
import { ChildProcessWithoutNullStreams } from "node:child_process";
import * as fs from "node:fs";
import net from "node:net";

View file

@ -1,5 +1,5 @@
import { IProtocol } from "core/protocol";
import { IMessenger, Message } from "core/util/messenger";
import { IMessenger, Message } from "core/protocol/messenger";
import net from "net";
import { v4 as uuidv4 } from "uuid";

View file

@ -2,7 +2,7 @@ process.env.IS_BINARY = "true";
import { Command } from "commander";
import { Core } from "core/core";
import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
import { IMessenger } from "core/util/messenger";
import { IMessenger } from "core/protocol/messenger";
import { getCoreLogsPath, getPromptLogsPath } from "core/util/paths";
import fs from "node:fs";
import { IpcIde } from "./IpcIde";

View file

@ -2,8 +2,7 @@ import { SerializedContinueConfig } from "core";
// import Mock from "core/llm/llms/Mock.js";
import { FromIdeProtocol, ToIdeProtocol } from "core/protocol/index.js";
import FileSystemIde from "core/util/filesystem";
import { IMessenger } from "core/util/messenger";
import { ReverseMessageIde } from "core/util/reverseMessageIde";
import { IMessenger } from "core/protocol/messenger";
import fs from "fs";
import {
ChildProcessWithoutNullStreams,
@ -133,7 +132,7 @@ describe("Test Suite", () => {
fs.mkdirSync(testDir);
}
const ide = new FileSystemIde(testDir);
const reverseIde = new ReverseMessageIde(messenger.on.bind(messenger), ide);
// const reverseIde = new ReverseMessageIde(messenger.on.bind(messenger), ide);
// Wait for core to set itself up
await new Promise((resolve) => setTimeout(resolve, 1000));

View file

@ -7,7 +7,8 @@
"sourceMap": true,
"rootDirs": ["src", "../core"],
"allowJs": true,
"strict": true /* enable all strict type-checking options */,
"skipLibCheck": true,
"strict": true /* enable all strict tsc:watching options */,
/* Additional Checks */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */

3
core/.gitignore vendored
View file

@ -3,6 +3,5 @@ target
**/.DS_Store
npm-debug.log*
.env
.continue-test
testDir
test/.continue-test
coverage

View file

@ -3,7 +3,7 @@ import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
import { IDE, ILLM } from "../index.js";
import OpenAI from "../llm/llms/OpenAI.js";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
import { EXPERIMENTS, PosthogFeatureFlag, Telemetry } from "../util/posthog.js";
import { PosthogFeatureFlag, Telemetry } from "../util/posthog.js";
import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js";
import { ContextRetrievalService } from "./context/ContextRetrievalService.js";
@ -59,6 +59,11 @@ export class CompletionProvider {
return undefined;
}
// Temporary fix for JetBrains autocomplete bug as described in https://github.com/continuedev/continue/pull/3022
if (llm.model === undefined && llm.completionOptions?.model !== undefined) {
llm.model = llm.completionOptions.model;
}
// Ignore empty API keys for Mistral since we currently write
// a template provider without one during onboarding
if (llm.providerName === "mistral" && llm.apiKey === "") {

149
core/commands/util.test.ts Normal file
View file

@ -0,0 +1,149 @@
import { ctxItemToRifWithContents } from "./util";
import { ContextItemWithId, RangeInFileWithContents } from "../index";
describe("ctxItemToRifWithContents", () => {
it("should parse start and end lines from the item name when format is valid", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "1" },
name: "myFunction(10-20)",
content: "function content",
description: "test description",
uri: { type: "file", value: "/path/to/file" },
};
const expected: RangeInFileWithContents = {
filepath: "/path/to/file",
range: {
start: { line: 10, character: 0 },
end: { line: 20, character: 0 },
},
contents: "function content",
};
const result = ctxItemToRifWithContents(item);
expect(result).toEqual(expected);
});
it("should set startLine and endLine to 0 when name format is invalid", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "2" },
name: "myFunction",
content: "function content",
description: "test description",
uri: { type: "file", value: "/path/to/file" },
};
const expected: RangeInFileWithContents = {
filepath: "/path/to/file",
range: {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
},
contents: "function content",
};
const result = ctxItemToRifWithContents(item);
expect(result).toEqual(expected);
});
it("should handle missing uri by setting filepath to empty string", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "3" },
name: "myFunction(10-20)",
content: "function content",
description: "test description",
};
const expected: RangeInFileWithContents = {
filepath: "",
range: {
start: { line: 10, character: 0 },
end: { line: 20, character: 0 },
},
contents: "function content",
};
const result = ctxItemToRifWithContents(item);
expect(result).toEqual(expected);
});
it("should handle uri with undefined value by setting filepath to empty string", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "4" },
name: "myFunction(10-20)",
content: "function content",
description: "test description",
};
const expected: RangeInFileWithContents = {
filepath: "",
range: {
start: { line: 10, character: 0 },
end: { line: 20, character: 0 },
},
contents: "function content",
};
const result = ctxItemToRifWithContents(item);
expect(result).toEqual(expected);
});
it("should handle invalid line numbers gracefully", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "6" },
name: "myFunction(invalid-lines)",
content: "function content",
description: "test description",
uri: { type: "file", value: "/path/to/file" },
};
const result = ctxItemToRifWithContents(item);
expect(result.range.start.line).toBeNaN();
expect(result.range.end.line).toBeNaN();
});
it("should handle missing closing parenthesis in name", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "7" },
name: "myFunction(10-20",
content: "function content",
description: "test description",
uri: { type: "file", value: "/path/to/file" },
};
const expected: RangeInFileWithContents = {
filepath: "/path/to/file",
range: {
start: { line: 10, character: 0 },
end: { line: 20, character: 0 },
},
contents: "function content",
};
const result = ctxItemToRifWithContents(item);
expect(result).toEqual(expected);
});
it("should handle name with multiple '-' characters", () => {
const item: ContextItemWithId = {
id: { providerTitle: "testProvider", itemId: "8" },
name: "myFunction(10-20-30)",
content: "function content",
description: "test description",
uri: { type: "file", value: "/path/to/file" },
};
const expected: RangeInFileWithContents = {
filepath: "/path/to/file",
range: {
start: { line: 10, character: 0 },
end: { line: 20, character: 0 },
},
contents: "function content",
};
const result = ctxItemToRifWithContents(item);
expect(result).toEqual(expected);
});
});

View file

@ -95,14 +95,6 @@ export const defaultSlashCommandsJetBrains = [
export const defaultConfig: SerializedContinueConfig = {
models: [DEFAULT_CHAT_MODEL_CONFIG],
tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
customCommands: [
{
name: "test",
prompt:
"{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
description: "Write unit tests for highlighted code",
},
],
contextProviders: defaultContextProvidersVsCode,
slashCommands: defaultSlashCommandsVscode,
};
@ -110,14 +102,6 @@ export const defaultConfig: SerializedContinueConfig = {
export const defaultConfigJetBrains: SerializedContinueConfig = {
models: [DEFAULT_CHAT_MODEL_CONFIG],
tabAutocompleteModel: DEFAULT_AUTOCOMPLETE_MODEL_CONFIG,
customCommands: [
{
name: "test",
prompt:
"{{{ input }}}\n\nWrite a comprehensive set of unit tests for the selected code. It should setup, run tests that check for correctness including important edge cases, and teardown. Ensure that the tests are complete and sophisticated. Give the tests just as chat output, don't edit any file.",
description: "Write unit tests for highlighted code",
},
],
contextProviders: defaultContextProvidersJetBrains,
slashCommands: defaultSlashCommandsJetBrains,
};

View file

@ -846,6 +846,7 @@ declare global {
codeBlockToolbarPosition?: "top" | "bottom";
fontSize?: number;
displayRawMarkdown?: boolean;
codeWrap?: boolean;
}
interface ContextMenuConfig {

View file

@ -1,5 +1,5 @@
import { Chunk } from "../../index.js";
import { deduplicateArray } from "../../util/index.js";
import { Chunk } from "../../index";
import { deduplicateArray } from "../../util/index";
export function deduplicateChunks(chunks: Chunk[]): Chunk[] {
return deduplicateArray(chunks, (a, b) => {

View file

@ -0,0 +1,117 @@
// Generated by Continue
import { Chunk } from "../../index";
import { deduplicateChunks } from "./util";
describe("deduplicateChunks", () => {
it("returns an empty array when given an empty array", () => {
const chunks: Chunk[] = [];
const result = deduplicateChunks(chunks);
expect(result).toEqual([]);
});
it("returns the same array when given an array with no duplicates", () => {
const chunks: Chunk[] = [
{
filepath: "file1.ts",
startLine: 0,
endLine: 1,
content: "chunk 1",
digest: "",
index: 0,
},
{
filepath: "file2.ts",
startLine: 2,
endLine: 3,
content: "chunk 2",
digest: "",
index: 1,
},
];
const result = deduplicateChunks(chunks);
expect(result).toEqual(chunks);
});
it("removes duplicate chunks", () => {
const chunks: Chunk[] = [
{
filepath: "file1.ts",
startLine: 0,
endLine: 1,
content: "chunk 1",
digest: "",
index: 0,
},
{
filepath: "file1.ts",
startLine: 0,
endLine: 1,
content: "chunk 1 duplicate",
digest: "",
index: 0,
},
{
filepath: "file2.ts",
startLine: 2,
endLine: 3,
content: "chunk 2",
digest: "",
index: 1,
},
];
const result = deduplicateChunks(chunks);
expect(result).toEqual([
{
filepath: "file1.ts",
startLine: 0,
endLine: 1,
content: "chunk 1",
digest: "",
index: 0,
},
{
filepath: "file2.ts",
startLine: 2,
endLine: 3,
content: "chunk 2",
digest: "",
index: 1,
},
]);
});
it("handles chunks with different contents but the same file lines as duplicates", () => {
const chunks: Chunk[] = [
{
filepath: "file1.ts",
startLine: 0,
endLine: 1,
content: "chunk 1",
digest: "",
index: 0,
},
{
filepath: "file1.ts",
startLine: 0,
endLine: 1,
content: "chunk 1 different content",
digest: "",
index: 0,
},
];
const result = deduplicateChunks(chunks);
expect(result).toEqual([
{
filepath: "file1.ts",
startLine: 0,
endLine: 1,
content: "chunk 1",
digest: "",
index: 0,
},
]);
});
});

View file

@ -37,7 +37,7 @@ import { TTS } from "./util/tts";
import type { ContextItemId, IDE, IndexingProgressUpdate } from ".";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import type { IMessenger, Message } from "./util/messenger";
import type { IMessenger, Message } from "./protocol/messenger";
export class Core {
// implements IMessenger<ToCoreProtocol, FromCoreProtocol>

View file

@ -19,6 +19,14 @@ describe("Test myers diff function", () => {
E
`;
const diffLines = myersDiff(linesA, linesB);
console.log(diffLines);
expect(diffLines).toEqual([
{ type: "same", line: "A" },
{ type: "same", line: "B" },
{ type: "old", line: "C" },
{ type: "old", line: "D" },
{ type: "new", line: "C'" },
{ type: "new", line: "D'" },
{ type: "same", line: "E" },
]);
});
});

200
core/diff/util.test.ts Normal file
View file

@ -0,0 +1,200 @@
// Generated by continue
import { matchLine, streamLines, generateLines } from "./util";
import { ChatMessage } from "../index";
import { jest } from "@jest/globals";
describe.skip("matchLine", () => {
it("should match empty lines if the first old line is also empty", () => {
const newLine = " ";
const oldLines = [" ", "some code"];
const result = matchLine(newLine, oldLines);
expect(result).toEqual({
matchIndex: 0,
isPerfectMatch: true,
newLine: "",
});
});
it("should return matchIndex -1 if newLine is an end bracket and i > 4", () => {
const newLine = "}";
const oldLines = ["line 1", "line 2", "line 3", "line 4", "line 5", "}"];
const result = matchLine(newLine, oldLines);
expect(result).toEqual({
matchIndex: -1,
isPerfectMatch: false,
newLine: "}",
});
});
it("should match end bracket if within first 5 lines", () => {
const newLine = "}";
const oldLines = ["line 1", "line 2", "line 3", "}", "line 5", "}"];
const result = matchLine(newLine, oldLines);
expect(result).toEqual({
matchIndex: 3,
isPerfectMatch: true,
newLine: "}",
});
});
it("should match lines perfectly", () => {
const newLine = "const a = 5;";
const oldLines = ["let b = 6;", "const a = 5;", "console.log(a);"];
const result = matchLine(newLine, oldLines);
expect(result).toEqual({
matchIndex: 1,
isPerfectMatch: true,
newLine: "const a = 5;",
});
});
it("should match lines with tolerable differences", () => {
const newLine = "console.log(a);";
const oldLines = ["const a = 5;", "console.log(b);", "console.log( a );"];
const result = matchLine(newLine, oldLines);
expect(result).toEqual({
matchIndex: 2,
isPerfectMatch: false,
newLine: "console.log(a);",
});
});
it("should return matchIndex -1 if no match found", () => {
const newLine = "new line that does not exist";
const oldLines = ["line 1", "line 2", "line 3"];
const result = matchLine(newLine, oldLines);
expect(result).toEqual({
matchIndex: -1,
isPerfectMatch: false,
newLine: "new line that does not exist",
});
});
it("should fix indentation if permissible and line length > 8", () => {
const newLine = " const a = 5;";
const oldLines = ["const a = 5;"];
const result = matchLine(newLine, oldLines, false);
expect(result).toEqual({
matchIndex: 0,
isPerfectMatch: true,
newLine: "const a = 5;",
});
});
it("should not fix indentation if not permissible and line length is short", () => {
const newLine = " for";
const oldLines = ["for"];
const result = matchLine(newLine, oldLines, false);
expect(result).toEqual({
matchIndex: 0,
isPerfectMatch: false,
newLine: " for",
});
});
it("should fix indentation even if line length <=8 when permissiveAboutIndentation is true", () => {
const newLine = " for";
const oldLines = ["for"];
const result = matchLine(newLine, oldLines, true);
expect(result).toEqual({
matchIndex: 0,
isPerfectMatch: true,
newLine: "for",
});
});
it("should match lines that are empty strings", () => {
const newLine = "";
const oldLines = [""];
const result = matchLine(newLine, oldLines);
expect(result).toEqual({
matchIndex: 0,
isPerfectMatch: true,
newLine: "",
});
});
});
describe("streamLines", () => {
it("should split chunks into lines correctly", async () => {
async function* streamCompletion(): AsyncGenerator<string> {
yield "line1\nline";
yield "2\nline3\n";
yield "line4";
}
const resultLines: string[] = [];
for await (const line of streamLines(streamCompletion())) {
resultLines.push(line);
}
expect(resultLines).toEqual(["line1", "line2", "line3", "line4"]);
});
it("should handle ChatMessage chunks", async () => {
const messageChunk1: ChatMessage = {
role: "assistant",
content: "line1\nline",
};
const messageChunk2: ChatMessage = {
role: "assistant",
content: "2\nline3\n",
};
const messageChunk3: ChatMessage = {
role: "assistant",
content: "line4",
};
// const spy = jest.spyOn(messageContentModule, "renderChatMessage");
async function* streamCompletion(): AsyncGenerator<ChatMessage> {
yield messageChunk1;
yield messageChunk2;
yield messageChunk3;
}
const resultLines: string[] = [];
for await (const line of streamLines(streamCompletion())) {
resultLines.push(line);
}
expect(resultLines).toEqual(["line1", "line2", "line3", "line4"]);
// expect(spy).toHaveBeenCalledTimes(3);
});
it("should log lines if log parameter is true", async () => {
const consoleSpy = jest.spyOn(console, "log").mockImplementation(() => {});
async function* streamCompletion(): AsyncGenerator<string> {
yield "line1\nline2\n";
yield "line3";
}
const resultLines: string[] = [];
for await (const line of streamLines(streamCompletion(), true)) {
resultLines.push(line);
}
expect(resultLines).toEqual(["line1", "line2", "line3"]);
expect(consoleSpy).toHaveBeenCalledWith(
"Streamed lines: ",
"line1\nline2\nline3",
);
consoleSpy.mockRestore();
});
});
describe("generateLines", () => {
it("should yield the lines provided in the array", async () => {
const lines = ["line1", "line2", "line3"];
const resultLines: string[] = [];
for await (const line of generateLines(lines)) {
resultLines.push(line);
}
expect(resultLines).toEqual(lines);
});
});

View file

@ -0,0 +1,109 @@
// Generated by continue
import { findInAst } from "./findInAst";
import Parser from "web-tree-sitter";
describe("findInAst", () => {
it("should find a node matching the criterion", () => {
const mockAst = createMockSyntaxNode("root", [
createMockSyntaxNode("child1", []),
createMockSyntaxNode("function", [createMockSyntaxNode("child2", [])]),
]);
const criterion = (node: Parser.SyntaxNode) => node.type === "function";
const result = findInAst(mockAst, criterion);
expect(result).not.toBeNull();
expect(result!.type).toBe("function");
});
it("should return null if no node matches the criterion", () => {
const mockAst = createMockSyntaxNode("root", [
createMockSyntaxNode("child1", []),
createMockSyntaxNode("child2", []),
]);
const criterion = (node: Parser.SyntaxNode) => node.type === "function";
const result = findInAst(mockAst, criterion);
expect(result).toBeNull();
});
it("should find a nested node matching the criterion", () => {
const mockAst = createMockSyntaxNode("root", [
createMockSyntaxNode("child1", [
createMockSyntaxNode("child2", [createMockSyntaxNode("function", [])]),
]),
createMockSyntaxNode("child3", []),
]);
const criterion = (node: Parser.SyntaxNode) => node.type === "function";
const result = findInAst(mockAst, criterion);
expect(result).not.toBeNull();
expect(result!.type).toBe("function");
});
it("should return the first node matching the criterion in depth-first traversal", () => {
const firstFunctionNode = createMockSyntaxNode("function", []);
const secondFunctionNode = createMockSyntaxNode("function", []);
const mockAst = createMockSyntaxNode("root", [
firstFunctionNode, // First function node
createMockSyntaxNode("child1", [
secondFunctionNode, // Second function node
]),
]);
const criterion = (node: Parser.SyntaxNode) => node.type === "function";
const result = findInAst(mockAst, criterion);
expect(result).not.toBeNull();
expect(result!.type).toBe("function");
expect(JSON.stringify(result)).toBe(JSON.stringify(firstFunctionNode)); // Ensure it's the first function node
});
it("should return the root node if it matches the criterion", () => {
const mockAst = createMockSyntaxNode("function", [
createMockSyntaxNode("child1", []),
createMockSyntaxNode("child2", []),
]);
const criterion = (node: Parser.SyntaxNode) => node.type === "function";
const result = findInAst(mockAst, criterion);
expect(result).not.toBeNull();
expect(result!.type).toBe("function");
expect(result).toBe(mockAst);
});
it("should return null when searching an empty tree", () => {
const mockAst = createMockSyntaxNode("root", []);
const criterion = (node: Parser.SyntaxNode) => node.type === "function";
const result = findInAst(mockAst, criterion);
expect(result).toBeNull();
});
});
function createMockSyntaxNode(
type: string,
children: Parser.SyntaxNode[],
): Parser.SyntaxNode {
// Define minimal properties of SyntaxNode required for the test
const node: Partial<Parser.SyntaxNode> = {
type,
children,
childCount: children.length,
child: (index: number) => {
return children[index] || null;
},
};
return node as Parser.SyntaxNode;
}

View file

@ -0,0 +1,77 @@
// Generated by continue
import { addIndentation } from "./streamDiffLines";
import type { DiffLine } from "../index";
describe("addIndentation", () => {
async function* mockDiffLineGenerator(lines: DiffLine[]) {
for (const line of lines) {
yield line;
}
}
test("should add indentation to each line", async () => {
const lines: DiffLine[] = [
{ type: "same", line: "Line 1" },
{ type: "new", line: "Line 2" },
{ type: "old", line: "Line 3" },
];
const indentation = " ";
const generator = addIndentation(mockDiffLineGenerator(lines), indentation);
const result: DiffLine[] = [];
for await (const diffLine of generator) {
result.push(diffLine);
}
expect(result).toEqual([
{ type: "same", line: " Line 1" },
{ type: "new", line: " Line 2" },
{ type: "old", line: " Line 3" },
]);
});
test("should handle empty generator", async () => {
const lines: DiffLine[] = [];
const indentation = "\t";
const generator = addIndentation(mockDiffLineGenerator(lines), indentation);
const result: DiffLine[] = [];
for await (const diffLine of generator) {
result.push(diffLine);
}
expect(result).toEqual([]);
});
test("should handle no indentation", async () => {
const lines: DiffLine[] = [{ type: "same", line: "Line 1" }];
const indentation = "";
const generator = addIndentation(mockDiffLineGenerator(lines), indentation);
const result: DiffLine[] = [];
for await (const diffLine of generator) {
result.push(diffLine);
}
expect(result).toEqual([{ type: "same", line: "Line 1" }]);
});
test("should propagate errors from the source generator", async () => {
async function* errorGenerator(): AsyncGenerator<DiffLine> {
throw new Error("Test error");
}
const indentation = " ";
const generator = addIndentation(errorGenerator(), indentation);
await expect(async () => {
for await (const _ of generator) {
// Consume the generator
}
}).rejects.toThrow("Test error");
});
});

View file

@ -30,7 +30,7 @@ function constructPrompt(
});
}
async function* addIndentation(
export async function* addIndentation(
diffLineGenerator: AsyncGenerator<DiffLine>,
indentation: string,
): AsyncGenerator<DiffLine> {
@ -96,8 +96,11 @@ export async function* streamDiffLines(
const completion =
typeof prompt === "string"
? llm.streamComplete(prompt, new AbortController().signal, { raw: true, prediction })
: llm.streamChat(prompt, new AbortController().signal, {
? llm.streamComplete(prompt, new AbortController().signal, {
raw: true,
prediction,
})
: llm.streamChat(prompt, new AbortController().signal, {
prediction,
});

2
core/index.d.ts vendored
View file

@ -390,6 +390,7 @@ export interface InputModifiers {
export interface SymbolWithRange extends RangeInFile {
name: string;
type: Parser.SyntaxNode["type"];
content: string;
}
export type FileSymbolMap = Record<string, SymbolWithRange[]>;
@ -968,6 +969,7 @@ export interface ContinueUIConfig {
displayRawMarkdown?: boolean;
showChatScrollbar?: boolean;
getChatTitles?: boolean;
codeWrap?: boolean;
}
interface ContextMenuConfig {

View file

@ -135,7 +135,6 @@ describe("CodebaseIndexer", () => {
del: number,
) {
const plan = await getIndexPlan();
console.log("PLAN: ", plan);
expect(plan.compute).toHaveLength(compute);
expect(plan.addTag).toHaveLength(addTag);
expect(plan.removeTag).toHaveLength(removeTag);

View file

@ -0,0 +1,87 @@
// Generated by continue
// core/indexing/chunk/basic.test.ts
import { basicChunker } from "./basic.js";
import { countTokensAsync } from "../../llm/countTokens";
import { ChunkWithoutID } from "../../index";
// jest.mock("../../llm/countTokens", () => ({
// countTokensAsync: jest.fn(),
// }));
describe.skip("basicChunker", () => {
beforeEach(() => {
jest.resetAllMocks();
});
it("should yield no chunks for empty content", async () => {
const contents = "";
const maxChunkSize = 10;
const chunks: ChunkWithoutID[] = [];
for await (const chunk of basicChunker(contents, maxChunkSize)) {
chunks.push(chunk);
}
expect(chunks).toHaveLength(0);
});
it("should yield a single chunk if whole content fits within the max size", async () => {
(countTokensAsync as jest.Mock).mockResolvedValue(1);
const contents = "line1\nline2\nline3";
const maxChunkSize = 10;
const expectedChunks: ChunkWithoutID[] = [
{ content: "line1\nline2\nline3\n", startLine: 0, endLine: 2 },
];
const chunks: ChunkWithoutID[] = [];
for await (const chunk of basicChunker(contents, maxChunkSize)) {
chunks.push(chunk);
}
expect(chunks).toEqual(expectedChunks);
});
it("should yield multiple chunks when content exceeds the max size", async () => {
(countTokensAsync as jest.Mock).mockImplementation(async (line: string) => {
if (line === "line3") return 5;
return 3; // Mock returning 3 tokens per line except for "line3"
});
const contents = "line1\nline2\nline3\nline4\nline5";
const maxChunkSize = 8;
const expectedChunks: ChunkWithoutID[] = [
{ content: "line1\nline2\n", startLine: 0, endLine: 1 },
{ content: "line3\n", startLine: 2, endLine: 2 },
{ content: "line4\nline5\n", startLine: 3, endLine: 4 },
];
const chunks: ChunkWithoutID[] = [];
for await (const chunk of basicChunker(contents, maxChunkSize)) {
chunks.push(chunk);
}
expect(chunks).toEqual(expectedChunks);
});
it("should skip lines that exceed the max chunk size", async () => {
(countTokensAsync as jest.Mock).mockImplementation(async (line: string) => {
if (line === "line3") return 15; // Making it explicitly exceed max size
return 3;
});
const contents = "line1\nline2\nline3\nline4\nline5";
const maxChunkSize = 8;
const expectedChunks: ChunkWithoutID[] = [
{ content: "line1\nline2\n", startLine: 0, endLine: 1 },
{ content: "line4\nline5\n", startLine: 3, endLine: 4 },
];
const chunks: ChunkWithoutID[] = [];
for await (const chunk of basicChunker(contents, maxChunkSize)) {
chunks.push(chunk);
}
expect(chunks).toEqual(expectedChunks);
});
});

View file

@ -18,7 +18,7 @@ import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbed
import { FromCoreProtocol, ToCoreProtocol } from "../../protocol";
import { fetchFavicon, getFaviconBase64 } from "../../util/fetchFavicon";
import { GlobalContext } from "../../util/GlobalContext";
import { IMessenger } from "../../util/messenger";
import { IMessenger } from "../../protocol/messenger";
import {
editConfigJson,
getDocsSqlitePath,

View file

@ -0,0 +1,283 @@
// Generated by continue
import { getAllSuggestedDocs } from "./index";
import { testIde } from "../../../test/fixtures";
import {
setUpTestDir,
tearDownTestDir,
addToTestDir,
} from "../../../test/testDir";
import fetch, { RequestInfo } from "node-fetch";
jest.mock("node-fetch", undefined, {
virtual: false,
});
describe.skip("getAllSuggestedDocs", () => {
beforeEach(() => {
setUpTestDir();
jest.clearAllMocks();
});
afterEach(() => {
tearDownTestDir();
jest.restoreAllMocks();
});
it("should return package docs for JavaScript and Python projects", async () => {
// Set up test files
addToTestDir([
[
"package.json",
JSON.stringify({
dependencies: {
express: "^4.17.1",
lodash: "^4.17.21",
},
devDependencies: {
typescript: "^4.0.0",
},
}),
],
["requirements.txt", "requests==2.25.1\nflask==1.1.2"],
]);
const mockedFetch = fetch as jest.MockedFunction<typeof fetch>;
mockedFetch.mockImplementation((url: URL | RequestInfo) => {
if (url.toString().includes("registry.npmjs.org/express")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
homepage: "https://expressjs.com/",
name: "express",
description: "Fast, unopinionated, minimalist web framework",
license: "MIT",
}),
}) as any;
} else if (url.toString().includes("registry.npmjs.org/lodash")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
homepage: "https://lodash.com/",
name: "lodash",
description: "Lodash modular utilities.",
license: "MIT",
}),
}) as any;
} else if (url.toString().includes("pypi.org/pypi/requests/json")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
info: {
home_page: "https://docs.python-requests.org/",
name: "requests",
summary: "Python HTTP for Humans.",
license: "Apache 2.0",
},
}),
}) as any;
} else if (url.toString().includes("pypi.org/pypi/flask/json")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
info: {
home_page: "https://palletsprojects.com/p/flask/",
name: "flask",
summary:
"A simple framework for building complex web applications.",
license: "BSD-3-Clause",
},
}),
}) as any;
} else {
return Promise.reject(new Error(`Unhandled URL: ${url}`));
}
});
const results = await getAllSuggestedDocs(testIde);
expect(results).toHaveLength(4);
expect(results).toEqual(
expect.arrayContaining([
expect.objectContaining({
packageInfo: expect.objectContaining({ name: "express" }),
details: expect.objectContaining({
docsLink: "https://expressjs.com/",
}),
}),
expect.objectContaining({
packageInfo: expect.objectContaining({ name: "lodash" }),
details: expect.objectContaining({
docsLink: "https://lodash.com/",
}),
}),
expect.objectContaining({
packageInfo: expect.objectContaining({ name: "requests" }),
details: expect.objectContaining({
docsLink: "https://docs.python-requests.org/",
}),
}),
expect.objectContaining({
packageInfo: expect.objectContaining({ name: "flask" }),
details: expect.objectContaining({
docsLink: "https://palletsprojects.com/p/flask/",
}),
}),
]),
);
// Verify no errors are present
results.forEach((result) => {
expect(result.error).toBeUndefined();
});
});
it("should handle packages without documentation links", async () => {
addToTestDir([
[
"package.json",
JSON.stringify({
dependencies: {
"no-docs-package": "^1.0.0",
},
}),
],
]);
// Mock fetch
const mockedFetch = fetch as jest.MockedFunction<typeof fetch>;
mockedFetch.mockImplementation((url: RequestInfo | URL) => {
if (url.toString().includes("registry.npmjs.org/no-docs-package")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
name: "no-docs-package",
description: "A package without docs",
license: "MIT",
// No homepage provided
}),
}) as any;
} else {
return Promise.reject(new Error(`Unhandled URL: ${url}`));
}
});
const results = await getAllSuggestedDocs(testIde);
expect(results).toHaveLength(1);
expect(results[0].error).toContain(
"No documentation link found for no-docs-package",
);
expect(results[0].details).toBeUndefined();
});
it("should handle errors when fetching package details", async () => {
addToTestDir([
[
"package.json",
JSON.stringify({
dependencies: {
"error-package": "^1.0.0",
},
}),
],
]);
// Mock fetch
const mockedFetch = fetch as jest.MockedFunction<typeof fetch>;
mockedFetch.mockImplementation((url: URL | RequestInfo) => {
if (url.toString().includes("registry.npmjs.org/error-package")) {
return Promise.resolve({
ok: false,
}) as any;
} else {
return Promise.reject(new Error(`Unhandled URL: ${url}`));
}
});
const results = await getAllSuggestedDocs(testIde);
expect(results).toHaveLength(1);
expect(results[0].error).toContain(
"Error getting package details for error-package",
);
expect(results[0].details).toBeUndefined();
});
it("should handle workspaces with no package files", async () => {
const results = await getAllSuggestedDocs(testIde);
expect(results).toEqual([]);
});
it("should handle packages with GitHub documentation links", async () => {
addToTestDir([
[
"package.json",
JSON.stringify({
dependencies: {
"github-docs-package": "^1.0.0",
},
}),
],
]);
// Mock fetch
const mockedFetch = fetch as jest.MockedFunction<typeof fetch>;
mockedFetch.mockImplementation((url: URL | RequestInfo) => {
if (url.toString().includes("registry.npmjs.org/github-docs-package")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
homepage: "https://github.com/user/repo",
name: "github-docs-package",
description: "A package with GitHub docs",
license: "MIT",
}),
}) as any;
} else {
return Promise.reject(new Error(`Unhandled URL: ${url}`));
}
});
const results = await getAllSuggestedDocs(testIde);
expect(results).toHaveLength(1);
expect(results[0].details?.docsLink).toBe("https://github.com/user/repo");
expect(results[0].details?.docsLinkWarning).toBe(
"Github docs not supported, find the docs site",
);
});
it("should handle packages with non-docs links", async () => {
addToTestDir([["requirements.txt", "non-docs-package==1.0.0"]]);
// Mock fetch
const mockedFetch = fetch as jest.MockedFunction<typeof fetch>;
mockedFetch.mockImplementation((url: URL | RequestInfo) => {
if (url.toString().includes("pypi.org/pypi/non-docs-package/json")) {
return Promise.resolve({
ok: true,
json: jest.fn().mockResolvedValue({
info: {
home_page: "https://somewebsite.com",
name: "non-docs-package",
summary: "A package with non-docs homepage",
license: "MIT",
},
}),
}) as any;
} else {
return Promise.reject(new Error(`Unhandled URL: ${url}`));
}
});
const results = await getAllSuggestedDocs(testIde);
expect(results).toHaveLength(1);
expect(results[0].details?.docsLink).toBe("https://somewebsite.com");
expect(results[0].details?.docsLinkWarning).toBe(
"May not be a docs site, check the URL",
);
});
});

View file

@ -19,8 +19,14 @@ 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
// collectCoverage: true,
collectCoverageFrom: [
"**/*.{js,ts}", // Adjust this pattern to match files you want coverage for
"!**/node_modules/**", // Exclude node_modules
"!**/vendor/**",
// "!**/autocomplete/context/root-path-context/test/files/**",
],
globalSetup: "<rootDir>/test/jest.global-setup.ts",
setupFilesAfterEnv: ["<rootDir>/test/jest.setup-after-env.ts"],
maxWorkers: 1, // equivalent to CLI --runInBand
};

View file

@ -0,0 +1,109 @@
// Generated by continue
import { ChatMessage, MessagePart } from "../index.js";
import {
compileChatMessages,
countTokens,
countTokensAsync,
pruneLinesFromBottom,
pruneLinesFromTop,
pruneRawPromptFromTop,
pruneStringFromBottom,
pruneStringFromTop,
} from "./countTokens.js";
describe.skip("countTokens", () => {
it("should count tokens for a simple string", () => {
const content = "Hello world!";
const tokenCount = countTokens(content, "gpt-4");
expect(tokenCount).toBeGreaterThan(0);
});
it("should count tokens for an array of MessagePart", () => {
const content: MessagePart[] = [{ type: "text", text: "Hello world!" }];
const tokenCount = countTokens(content, "gpt-4");
expect(tokenCount).toBeGreaterThan(0);
});
});
describe.skip("countTokensAsync", () => {
it("should count tokens asynchronously for a simple string", async () => {
const content = "Hello world!";
const tokenCount = await countTokensAsync(content, "gpt-4");
expect(tokenCount).toBeGreaterThan(0);
});
it("should count tokens asynchronously for an array of MessagePart", async () => {
const content: MessagePart[] = [{ type: "text", text: "Hello world!" }];
const tokenCount = await countTokensAsync(content, "gpt-4");
expect(tokenCount).toBeGreaterThan(0);
});
});
describe.skip("pruneLinesFromTop", () => {
it("should prune lines from the top to fit within max tokens", () => {
const prompt = "Line 1\nLine 2\nLine 3\nLine 4";
const pruned = pruneLinesFromTop(prompt, 5, "gpt-4");
expect(pruned.split("\n").length).toBeLessThan(prompt.split("\n").length);
});
});
describe.skip("pruneLinesFromBottom", () => {
it("should prune lines from the bottom to fit within max tokens", () => {
const prompt = "Line 1\nLine 2\nLine 3\nLine 4";
const pruned = pruneLinesFromBottom(prompt, 5, "gpt-4");
expect(pruned.split("\n").length).toBeLessThan(prompt.split("\n").length);
});
});
describe.skip("pruneRawPromptFromTop", () => {
it("should prune string from the top based on maxTokens", () => {
const result = pruneRawPromptFromTop("gpt-4", 5, "Hello world!", 2);
expect(result.length).toBeLessThan("Hello world!".length);
});
});
describe.skip("pruneStringFromTop", () => {
it("should prune string from the top based on maxTokens", () => {
const result = pruneStringFromTop("gpt-4", 5, "Hello world!");
expect(result.length).toBeLessThan("Hello world!".length);
});
});
describe.skip("pruneStringFromBottom", () => {
it("should prune string from the bottom based on maxTokens", () => {
const result = pruneStringFromBottom("gpt-4", 5, "Hello world!");
expect(result.length).toBeLessThan("Hello world!".length);
});
});
describe.skip("compileChatMessages", () => {
it("should compile and handle an empty or undefined message list", () => {
const compiled = compileChatMessages("gpt-4", undefined, 100, 50, false);
expect(compiled.length).toBe(0);
});
it("should compile chat messages without truncating if within context length", () => {
const msgs: ChatMessage[] = [
{ role: "user", content: "Hello world!" },
{ role: "assistant", content: "Hi there!" },
];
const compiled = compileChatMessages("gpt-4", msgs, 100, 10, false);
expect(compiled.length).toBe(2);
});
it("should throw an error if maxTokens is close to or exceeds contextLength", () => {
expect(() => {
compileChatMessages("gpt-4", [], 100, 90, false);
}).toThrow();
});
it("should filter out any empty or system messages", () => {
const msgs: ChatMessage[] = [
{ role: "system", content: "" },
{ role: "user", content: "" },
{ role: "assistant", content: "Hi there!" },
];
const compiled = compileChatMessages("gpt-4", msgs, 100, 10, false);
expect(compiled.length).toBe(1);
});
});

View file

@ -1,17 +1,22 @@
import { ChatMessage, CompletionOptions } 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 = "test";
private findResponse(prompt: string) {
return Object.entries(RESPONSES).find(([key]) => prompt.includes(key))?.[1];
// Matches TEST_USER_MESSAGE_ followed by digits, preceded and followed by non-digit characters
const matches = Array.from(
prompt.matchAll(/[^0-9]*TEST_USER_MESSAGE_(\d+)[^0-9]*/g),
);
if (matches.length > 0) {
const lastMatch = matches[matches.length - 1];
const number = lastMatch[1];
return `TEST_LLM_RESPONSE_${number}`;
}
return undefined;
}
protected async *_streamComplete(

View file

@ -1,10 +1,12 @@
import path from "node:path";
import { parentPort } from "node:worker_threads";
import {
env,
pipeline,
} from "../../vendor/node_modules/@xenova/transformers/types/transformers";
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider";
const { parentPort } = require("node:worker_threads");
env.allowLocalModels = true;
env.allowRemoteModels = false;

View file

@ -0,0 +1,302 @@
// Generated by continue
import { ChatMessage } from "../../index";
import {
anthropicTemplateMessages,
chatmlTemplateMessages,
codeLlama70bTemplateMessages,
deepseekTemplateMessages,
gemmaTemplateMessage,
graniteTemplateMessages,
llama2TemplateMessages,
llama3TemplateMessages,
llavaTemplateMessages,
neuralChatTemplateMessages,
openchatTemplateMessages,
phi2TemplateMessages,
phindTemplateMessages,
templateAlpacaMessages,
xWinCoderTemplateMessages,
zephyrTemplateMessages,
} from "./chat.js";
describe.skip("Chat Templates", () => {
describe("llama2TemplateMessages", () => {
it("should generate the correct prompt with system message and user messages", () => {
const messages: ChatMessage[] = [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there!" },
{ role: "user", content: "How are you?" },
];
const prompt = llama2TemplateMessages(messages);
const expectedPrompt = `<s>[INST] <<SYS>>
You are a helpful assistant.
<</SYS>>
Hello [/INST]Hi there!</s><s>[INST] How are you? [/INST]`;
expect(prompt).toBe(expectedPrompt);
});
it("should generate the correct prompt without system message", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Tell me a joke." },
];
const prompt = llama2TemplateMessages(messages);
const expectedPrompt = `[INST] Tell me a joke. [/INST]`;
expect(prompt).toBe(expectedPrompt);
});
it("should skip initial assistant messages", () => {
const messages: ChatMessage[] = [
{ role: "assistant", content: "Initial assistant message." },
{ role: "user", content: "What is the time?" },
];
const prompt = llama2TemplateMessages(messages);
const expectedPrompt = `[INST] What is the time? [/INST]`;
expect(prompt).toBe(expectedPrompt);
});
it("should handle empty messages", () => {
const messages: ChatMessage[] = [];
const prompt = llama2TemplateMessages(messages);
expect(prompt).toBe("");
});
it("should handle messages with empty system message", () => {
const messages: ChatMessage[] = [
{ role: "system", content: "" },
{ role: "user", content: "Hello" },
];
const prompt = llama2TemplateMessages(messages);
const expectedPrompt = `[INST] Hello [/INST]`;
expect(prompt).toBe(expectedPrompt);
});
});
describe("anthropicTemplateMessages", () => {
it("should generate the correct prompt with user and assistant messages", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi there!" },
{ role: "user", content: "How are you?" },
];
const prompt = anthropicTemplateMessages(messages);
const expectedPrompt =
"\n\nHuman: Hello \n\nAssistant: Hi there! \n\nHuman: How are you? \n\nAssistant:";
expect(prompt).toBe(expectedPrompt);
});
it("should start with 'Hello.' if first message is not from user or system", () => {
const messages: ChatMessage[] = [
{ role: "assistant", content: "I am an assistant." },
{ role: "user", content: "Tell me a joke." },
];
const prompt = anthropicTemplateMessages(messages);
const expectedPrompt =
"\n\nHuman: Hello.\n\nAssistant: I am an assistant. \n\nHuman: Tell me a joke. \n\nAssistant:";
expect(prompt).toBe(expectedPrompt);
});
it("should handle empty messages", () => {
const messages: ChatMessage[] = [];
const prompt = anthropicTemplateMessages(messages);
const expectedPrompt = "\n\nHuman: Hello.\n\nAssistant:";
expect(prompt).toBe(expectedPrompt);
});
});
describe("llavaTemplateMessages", () => {
it("should generate the correct prompt with user messages", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Describe this image." },
];
const prompt = llavaTemplateMessages(messages);
const expectedPrompt =
"A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions.USER: <image>Describe this image.ASSISTANT: ";
expect(prompt).toBe(expectedPrompt);
});
});
describe("zephyrTemplateMessages", () => {
it("should generate the correct prompt with system and user messages", () => {
const messages: ChatMessage[] = [
{ role: "system", content: "System message." },
{ role: "user", content: "Hello" },
];
const prompt = zephyrTemplateMessages(messages);
const expectedPrompt =
"<|system|>System message.</s>\n<|user|>\nHello</s>\n<|assistant|>\n";
expect(prompt).toBe(expectedPrompt);
});
it("should handle empty system message", () => {
const messages: ChatMessage[] = [
{ role: "system", content: "" },
{ role: "user", content: "Hello" },
];
const prompt = zephyrTemplateMessages(messages);
const expectedPrompt =
"<|system|> </s>\n<|user|>\nHello</s>\n<|assistant|>\n";
expect(prompt).toBe(expectedPrompt);
});
});
describe("chatmlTemplateMessages", () => {
it("should generate the correct prompt with system and user messages", () => {
const messages: ChatMessage[] = [
{ role: "system", content: "System prompt" },
{ role: "user", content: "Hello" },
];
const prompt = chatmlTemplateMessages(messages);
const expectedPrompt =
"<|im_start|>system\nSystem prompt<|im_end|>\n<|im_start|>user\nHello<|im_end|>\n<|im_start|>assistant\n";
expect(prompt).toBe(expectedPrompt);
});
});
describe("templateAlpacaMessages", () => {
it("should generate the correct prompt with user message", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Explain recursion." },
];
const prompt = templateAlpacaMessages(messages);
const expectedPrompt =
"Below is an instruction that describes a task. Write a response that appropriately completes the request.\n\n### Instruction:\nExplain recursion.\n\n### Response:\n";
expect(prompt).toBe(expectedPrompt);
});
});
describe("deepseekTemplateMessages", () => {
it("should generate the correct prompt with user and assistant messages", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "What is polymorphism in OOP?" },
{ role: "assistant", content: "Explanation of polymorphism." },
];
const prompt = deepseekTemplateMessages(messages);
const expectedPrompt =
"You are an AI programming assistant, utilizing the DeepSeek Coder model, developed by DeepSeek Company, and you only answer questions related to computer science. For politically sensitive questions, security and privacy issues, and other non-computer science questions, you will refuse to answer.\n### Instruction:\nWhat is polymorphism in OOP?\n### Response:\nExplanation of polymorphism.<|EOT|>\n";
expect(prompt).toBe(expectedPrompt);
});
});
describe("phi2TemplateMessages", () => {
it("should generate the correct prompt with system and user messages", () => {
const messages: ChatMessage[] = [
{ role: "system", content: "System message." },
{ role: "user", content: "Tell me a story." },
];
const prompt = phi2TemplateMessages(messages);
const expectedPrompt =
"\n\nInstruct: System message. \n\nInstruct: Tell me a story. \n\nOutput: ";
expect(prompt).toBe(expectedPrompt);
});
});
describe("phindTemplateMessages", () => {
it("should generate the correct prompt with system and user messages", () => {
const messages: ChatMessage[] = [
{ role: "system", content: "System prompt" },
{ role: "user", content: "What's the weather?" },
];
const prompt = phindTemplateMessages(messages);
const expectedPrompt =
"### System Prompt\nSystem prompt\n\n### User Message\nWhat's the weather?\n### Assistant\n";
expect(prompt).toBe(expectedPrompt);
});
});
describe("openchatTemplateMessages", () => {
it("should generate the correct prompt with user and assistant messages", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "Hello" },
{ role: "assistant", content: "Hi!" },
{ role: "user", content: "How are you?" },
];
const prompt = openchatTemplateMessages(messages);
const expectedPrompt =
"GPT4 Correct User: Hello<|end_of_turn|>GPT4 Correct Assistant: Hi!<|end_of_turn|>GPT4 Correct User: How are you?<|end_of_turn|>GPT4 Correct Assistant:";
expect(prompt).toBe(expectedPrompt);
});
});
describe("xWinCoderTemplateMessages", () => {
it("should generate the correct prompt with system and user messages", () => {
const messages: ChatMessage[] = [
{ role: "system", content: "System prompt" },
{ role: "user", content: "Explain closures in JavaScript." },
];
const prompt = xWinCoderTemplateMessages(messages);
const expectedPrompt =
"<system>: System prompt<user>: Explain closures in JavaScript.<AI>: ";
expect(prompt).toBe(expectedPrompt);
});
});
describe("codeLlama70bTemplateMessages", () => {
it("should generate the correct prompt with multiple messages", () => {
const messages: ChatMessage[] = [
{ role: "system", content: "System prompt" },
{ role: "user", content: "First user query" },
{ role: "assistant", content: "Model response to first query" },
{ role: "user", content: "Second user query" },
];
const prompt = codeLlama70bTemplateMessages(messages);
const expectedPrompt =
"<s>Source: system\n\n System prompt <step> Source: user\n\n First user query <step> Source: assistant\n\n Model response to first query <step> Source: user\n\n Second user query <step> Source: assistant\nDestination: user\n\n";
expect(prompt).toBe(prompt); // Since the function returns prompt
});
});
describe("llama3TemplateMessages", () => {
it("should generate the correct prompt with messages", () => {
const messages: ChatMessage[] = [
{ role: "system", content: "System prompt" },
{ role: "user", content: "Tell me about AI." },
];
const prompt = llama3TemplateMessages(messages);
const expectedPrompt =
"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\nSystem prompt<|eot_id|>\n<|start_header_id|>user<|end_header_id|>\nTell me about AI.<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n";
expect(prompt).toBe(expectedPrompt);
});
});
describe("gemmaTemplateMessage", () => {
it("should generate the correct prompt with messages", () => {
const messages: ChatMessage[] = [
{ role: "user", content: "How do I reverse a string in Python?" },
];
const prompt = gemmaTemplateMessage(messages);
const expectedPrompt =
"<start_of_turn>user\nHow do I reverse a string in Python?<end_of_turn>\n<start_of_turn>model\n";
expect(prompt).toBe(expectedPrompt);
});
});
describe("graniteTemplateMessages", () => {
it("should generate the correct prompt with system, user, and assistant messages", () => {
const messages: ChatMessage[] = [
{ role: "system", content: "System prompt" },
{ role: "user", content: "What's the capital of France?" },
{ role: "assistant", content: "Paris is the capital of France." },
];
const prompt = graniteTemplateMessages(messages);
const expectedPrompt =
"\n\nSystem:\n System prompt\n\nQuestion:\nWhat's the capital of France?\n\nAnswer:\nParis is the capital of France.\n\n";
expect(prompt).toBe(expectedPrompt);
});
});
describe("neuralChatTemplateMessages", () => {
it("should generate the correct prompt with system and user messages", () => {
const messages: ChatMessage[] = [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "Tell me a joke." },
];
const prompt = neuralChatTemplateMessages(messages);
const expectedPrompt =
"### System:\nYou are a helpful assistant.\n### User:\nTell me a joke.\n### Assistant:\n";
expect(prompt).toBe(expectedPrompt);
});
});
});

View file

@ -1,6 +1,6 @@
import { v4 as uuidv4 } from "uuid";
import type { IProtocol } from "../protocol/index.js";
import type { IProtocol } from "../index";
export interface Message<T = any> {
messageType: string;
@ -76,7 +76,9 @@ export class InProcessMessenger<
messageId?: string,
): ToProtocol[T][1] {
const listener = this.myTypeListeners.get(messageType);
if (!listener) {return;}
if (!listener) {
return;
}
const msg: Message = {
messageType: messageType as string,

View file

@ -1,8 +1,5 @@
import {
GetGhTokenArgs,
ToIdeFromWebviewOrCoreProtocol,
} from "../protocol/ide.js";
import { FromIdeProtocol } from "../protocol/index.js";
import { GetGhTokenArgs, ToIdeFromWebviewOrCoreProtocol } from "../ide";
import { FromIdeProtocol } from "..";
import type {
ContinueRcJson,
@ -16,7 +13,7 @@ import type {
Range,
RangeInFile,
Thread,
} from "../index.js";
} from "../..";
export class MessageIde implements IDE {
constructor(

View file

@ -1,7 +1,7 @@
import { IDE } from "../index.js";
import { ToIdeFromWebviewOrCoreProtocol } from "../protocol/ide.js";
import { IDE } from "../../index";
import { ToIdeFromWebviewOrCoreProtocol } from "../ide";
import { Message } from "./messenger.js";
import { Message } from ".";
export class ReverseMessageIde {
private on<T extends keyof ToIdeFromWebviewOrCoreProtocol>(

View file

@ -1,5 +1,6 @@
import { ConfigHandler } from "../config/ConfigHandler";
import { ControlPlaneClient } from "../control-plane/client";
import Mock from "../llm/llms/Mock";
import FileSystemIde from "../util/filesystem";
import { TEST_DIR } from "./testDir";
@ -18,3 +19,9 @@ export const testConfigHandler = new ConfigHandler(
async (text) => {},
testControlPlaneClient,
);
export const testLLM = new Mock({
model: "mock-model",
title: "Mock LLM",
uniqueId: "not-unique",
});

View file

@ -1,6 +1,8 @@
import fs from "fs";
import path from "path";
// Sets up the GLOBAL directory for testing - equivalent to ~/.continue
// IMPORTANT: the CONTINUE_GLOBAL_DIR environment variable is used in utils/paths for getting all local paths
export default async function () {
process.env.CONTINUE_GLOBAL_DIR = path.join(__dirname, ".continue-test");
if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR)) {

View file

@ -1,9 +1,10 @@
import fs from "fs";
import { TextDecoder, TextEncoder } from "util";
import { jest } from "@jest/globals";
import fetch, { Request, Response } from "node-fetch";
console.log("Process debug", process.env.DEBUG);
if (process.env.DEBUG === "jest") {
jest.setTimeout(5 * 60 * 1000);
}

View file

@ -18,6 +18,12 @@ export function tearDownTestDir() {
}
}
/*
accepts array of items in 3 formats, e.g.
"index/" creates index directory
"index/index.ts" creates an empty index/index.ts
["index/index.ts", "hello"] creates index/index.ts with contents "hello"
*/
export function addToTestDir(paths: (string | string[])[]) {
for (const p of paths) {
const filepath = path.join(TEST_DIR, Array.isArray(p) ? p[0] : p);

View file

@ -1,6 +1,9 @@
import childProcess from "node:child_process";
import util from "node:util";
import { ToolImpl } from ".";
const util = require("node:util");
const asyncExec = util.promisify(require("node:child_process").exec);
const asyncExec = util.promisify(childProcess.exec);
export const runTerminalCommandImpl: ToolImpl = async (args, extras) => {
const ideInfo = await extras.ide.getIdeInfo();

View file

@ -0,0 +1,140 @@
// core/util/GlobalContext.test.ts
import { GlobalContext, GlobalContextType } from "./GlobalContext";
import fs from "node:fs";
import path from "path";
import { getGlobalContextFilePath } from "./paths";
describe("GlobalContext", () => {
let globalContext: GlobalContext;
const globalContextFilePath = getGlobalContextFilePath();
beforeEach(() => {
// Remove the global context file if it exists
if (fs.existsSync(globalContextFilePath)) {
fs.unlinkSync(globalContextFilePath);
}
globalContext = new GlobalContext();
});
afterEach(() => {
// Clean up
if (fs.existsSync(globalContextFilePath)) {
fs.unlinkSync(globalContextFilePath);
}
});
it("should update and get a boolean value correctly", () => {
globalContext.update("indexingPaused", true);
const value = globalContext.get("indexingPaused");
expect(value).toBe(true);
});
it("should update and get a string value correctly", () => {
globalContext.update("selectedTabAutocompleteModel", "test-model");
const value = globalContext.get("selectedTabAutocompleteModel");
expect(value).toBe("test-model");
});
it("should update and get an object value correctly", () => {
const workspaceIdentifier = "workspace-1";
globalContext.update("lastSelectedProfileForWorkspace", {
[workspaceIdentifier]: "profile-1",
});
const value = globalContext.get("lastSelectedProfileForWorkspace");
expect(value).toEqual({ "workspace-1": "profile-1" });
});
it("should handle non-existent global context file gracefully on get", () => {
const value = globalContext.get("indexingPaused");
expect(value).toBeUndefined();
});
it("should handle non-existent global context file gracefully on update", () => {
globalContext.update("indexingPaused", true);
const value = globalContext.get("indexingPaused");
expect(value).toBe(true);
});
it("should overwrite existing values", () => {
globalContext.update("indexingPaused", true);
expect(globalContext.get("indexingPaused")).toBe(true);
globalContext.update("indexingPaused", false);
expect(globalContext.get("indexingPaused")).toBe(false);
});
it("should handle JSON parsing errors gracefully on get", () => {
// Write invalid JSON to the file
fs.writeFileSync(globalContextFilePath, "{ invalid json }");
const consoleWarnMock = jest
.spyOn(console, "warn")
.mockImplementation(() => {});
const value = globalContext.get("indexingPaused");
expect(value).toBeUndefined();
expect(consoleWarnMock).toHaveBeenCalledWith(
expect.stringContaining("Error parsing global context")
);
// Clean up
consoleWarnMock.mockRestore();
});
it("should handle JSON parsing errors gracefully on update", () => {
// Write invalid JSON to the file
fs.writeFileSync(globalContextFilePath, "{ invalid json }");
const consoleWarnMock = jest
.spyOn(console, "warn")
.mockImplementation(() => {});
// Attempt to update
globalContext.update("indexingPaused", true);
// The update should have been skipped due to JSON parsing error
// So attempting to get the value should return undefined
const value = globalContext.get("indexingPaused");
expect(value).toBeUndefined();
expect(consoleWarnMock).toHaveBeenCalledWith(
expect.stringContaining("Error updating global context")
);
// Clean up
consoleWarnMock.mockRestore();
});
it("should update and retrieve multiple values correctly", () => {
globalContext.update("indexingPaused", true);
globalContext.update("selectedTabAutocompleteModel", "test-model");
globalContext.update("hasDismissedConfigTsNoticeJetBrains", false);
expect(globalContext.get("indexingPaused")).toBe(true);
expect(globalContext.get("selectedTabAutocompleteModel")).toBe(
"test-model"
);
expect(globalContext.get("hasDismissedConfigTsNoticeJetBrains")).toBe(
false
);
});
it("should handle updating hasAlreadyCreatedAPromptFile correctly", () => {
globalContext.update("hasAlreadyCreatedAPromptFile", true);
expect(globalContext.get("hasAlreadyCreatedAPromptFile")).toBe(true);
});
it("should handle curEmbeddingsProviderId correctly", () => {
globalContext.update("curEmbeddingsProviderId", "test-provider-id");
expect(globalContext.get("curEmbeddingsProviderId")).toBe(
"test-provider-id"
);
});
it("should not crash or throw when getting a key that hasn't been set", () => {
expect(
globalContext.get("hasAlreadyCreatedAPromptFile")
).toBeUndefined();
});
});

View file

@ -0,0 +1,64 @@
import { PrecalculatedLruCache } from "./LruCache";
describe("PrecalculatedLruCache", () => {
const N = 2;
let calculateValue: jest.MockedFunction<(key: string) => Promise<number>>;
let cache: PrecalculatedLruCache<number>;
beforeEach(() => {
calculateValue = jest.fn(async (key: string) => {
return parseInt(key, 10) * 2;
});
cache = new PrecalculatedLruCache<number>(calculateValue, N);
});
it("should calculate and cache values", async () => {
await cache.initKey("1");
expect(calculateValue).toHaveBeenCalledWith("1");
expect(cache.get("1")).toBe(2);
});
it("should not recalculate cached values", async () => {
await cache.initKey("1");
calculateValue.mockClear();
await cache.initKey("1");
expect(calculateValue).not.toHaveBeenCalled();
expect(cache.get("1")).toBe(2);
});
it("should evict least recently used items when capacity is exceeded", async () => {
await cache.initKey("1");
await cache.initKey("2");
await cache.initKey("3"); // Exceeds capacity, should evict "1"
expect(cache.get("1")).toBeUndefined();
expect(cache.get("2")).toBe(4);
expect(cache.get("3")).toBe(6);
});
it("should update LRU order when keys are accessed", async () => {
await cache.initKey("1");
await cache.initKey("2");
// Access "1" to make it most recently used
await cache.initKey("1");
await cache.initKey("3"); // Exceeds capacity, should evict "2"
expect(cache.get("1")).toBe(2);
expect(cache.get("2")).toBeUndefined();
expect(cache.get("3")).toBe(6);
});
it("should handle get for keys not initialized", () => {
expect(cache.get("not-initialized")).toBeUndefined();
});
it("should propagate errors from calculateValue", async () => {
calculateValue.mockRejectedValue(new Error("Calculation failed"));
await expect(cache.initKey("error")).rejects.toThrow("Calculation failed");
expect(cache.get("error")).toBeUndefined();
});
});

View file

@ -0,0 +1,91 @@
import { ChatDescriber } from "./chatDescriber";
import { testLLM } from "../test/fixtures";
import { LLMFullCompletionOptions } from "..";
describe("ChatDescriber", () => {
beforeEach(() => {
// Reset the prompt to the initial value before each test
ChatDescriber.prompt =
"Given the following... please reply with a short summary that is 4-12 words in length, you should summarize what the user is asking for OR what the user is trying to accomplish. You should only respond with the summary, no additional text or explanation, you don't need ending punctuation.\n\n";
});
afterEach(() => {
jest.restoreAllMocks();
});
describe("describe method", () => {
it("should return undefined if ChatDescriber.prompt is undefined", async () => {
ChatDescriber.prompt = undefined;
const result = await ChatDescriber.describe(testLLM, {}, "Test message");
expect(result).toBeUndefined();
});
it("should return undefined if message is empty after cleaning", async () => {
const message = " ";
const result = await ChatDescriber.describe(testLLM, {}, message);
expect(result).toBeUndefined();
});
it("should set completionOptions.maxTokens to 6", async () => {
const message = "Test message";
const completionOptions: LLMFullCompletionOptions = { temperature: 0.7 };
testLLM.chat = jest.fn().mockResolvedValue({ content: "Test response" });
await ChatDescriber.describe(testLLM, completionOptions, message);
expect(completionOptions.maxTokens).toBe(6);
});
it("should call model.chat with correct parameters", async () => {
const message = "Test message";
const cleanedMessage = "Test message";
const expectedPrompt = ChatDescriber.prompt + cleanedMessage;
const completionOptions: LLMFullCompletionOptions = {};
testLLM.chat = jest.fn().mockResolvedValue({ content: "Test response" });
await ChatDescriber.describe(testLLM, completionOptions, message);
expect(testLLM.chat).toHaveBeenCalledWith(
[
{
role: "user",
content: expectedPrompt,
},
],
expect.any(AbortSignal),
completionOptions,
);
});
it("should return processed content from the model response", async () => {
const message = "Test message";
const modelResponseContent = "Model response content";
const expectedResult = "Model response content";
testLLM.chat = jest
.fn()
.mockResolvedValue({ content: modelResponseContent });
const result = await ChatDescriber.describe(testLLM, {}, message);
expect(result).toBe(expectedResult);
});
it("should propagate error if model.chat throws an error", async () => {
const message = "Test message";
const completionOptions: LLMFullCompletionOptions = {};
testLLM.chat = jest.fn().mockRejectedValue(new Error("Chat error"));
await expect(
ChatDescriber.describe(testLLM, completionOptions, message),
).rejects.toThrow("Chat error");
});
});
});

View file

@ -2,7 +2,7 @@ import { ILLM, LLMFullCompletionOptions } from "..";
import { removeQuotesAndEscapes, removeCodeBlocksAndTrim } from ".";
import type { IMessenger } from "./messenger";
import type { IMessenger } from "../protocol/messenger";
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
export class ChatDescriber {

View file

@ -1,155 +0,0 @@
import { dedent } from "./index";
describe("dedent function", () => {
it("should remove common leading whitespace from all lines", () => {
const result = dedent`
Hello
World
!
`;
expect(result).toBe("Hello\n World\n !");
});
it("should handle strings with no indentation", () => {
const result = dedent`Hello
World
!`;
expect(result).toBe("Hello\nWorld\n!");
});
it("should handle strings with mixed indentation", () => {
const result = dedent`
Hello
World
!
`;
expect(result).toBe(" Hello\nWorld\n !");
});
it("should remove leading and trailing empty lines", () => {
const result = dedent`
Hello
World
`;
expect(result).toBe("Hello\nWorld");
});
it("should handle empty strings", () => {
const result = dedent``;
expect(result).toBe("");
});
it("should handle strings with only whitespace", () => {
const result = dedent`
`;
expect(result).toBe("");
});
it.skip("should handle strings with tabs", () => {
const result = dedent`
\tHello
\t\tWorld
\t\t\t!
`;
expect(result).toBe("\tHello\n\t\tWorld\n\t\t\t!");
});
it("should handle interpolated values", () => {
const world = "World";
const result = dedent`
Hello ${world}
How are you?
`;
expect(result).toBe("Hello World\n How are you?");
});
it("should handle multiple interpolated values", () => {
const greeting = "Hello";
const name = "Alice";
const question = "How are you?";
const result = dedent`
${greeting} ${name}
${question}
`;
expect(result).toBe("Hello Alice\n How are you?");
});
it("should handle interpolated values with different indentation", () => {
const value1 = "foo";
const value2 = "bar";
const result = dedent`
${value1}
${value2}
`;
expect(result).toBe("foo\n bar");
});
it("should handle a single line with indentation", () => {
const result = dedent` Hello World!`;
expect(result).toBe("Hello World!");
});
it("should handle a string with only one non-empty line", () => {
const result = dedent`
Hello World!
`;
expect(result).toBe("Hello World!");
});
it("should handle a string with Unicode characters", () => {
const result = dedent`
こんにちは
世界
`;
expect(result).toBe("こんにちは\n 世界");
});
it("should handle a string with emoji", () => {
const result = dedent`
🌍
🌎
🌏
`;
expect(result).toBe("🌍\n 🌎\n 🌏");
});
it.skip("should handle a string with CRLF line endings", () => {
const result = dedent`
Hello\r
World\r
`;
expect(result).toBe("Hello\r\n World");
});
it("should not count empty lines in the minimum indentation", () => {
const result = dedent`
Hello
World
`;
expect(result).toBe("Hello\n\nWorld");
});
it("should work with templated strings", () => {
const language = "typescript";
const code = "console.log('hello');\nconsole.log('world');";
const result = dedent`
This is the prefix of the file:
\`\`\`${language}
${code}
\`\`\``;
expect(result).toBe(`\
This is the prefix of the file:
\`\`\`${language}
${code}
\`\`\``);
});
});

View file

@ -0,0 +1,83 @@
// Generated by continue
import { extractMinimalStackTraceInfo } from "./extractMinimalStackTraceInfo";
describe("extractMinimalStackTraceInfo", () => {
it("should return an empty string when stack is not a string or an empty string", () => {
expect(extractMinimalStackTraceInfo(undefined)).toBe("");
expect(extractMinimalStackTraceInfo(null)).toBe("");
expect(extractMinimalStackTraceInfo(1234)).toBe("");
expect(extractMinimalStackTraceInfo({})).toBe("");
expect(extractMinimalStackTraceInfo([])).toBe("");
expect(extractMinimalStackTraceInfo(true)).toBe("");
expect(extractMinimalStackTraceInfo("")).toBe("");
});
it("should extract minimal stack trace info from a valid stack trace", () => {
const stack = `Error: Something went wrong
at FunctionOne (/Users/user/project/file1.ts:10:15)
at FunctionTwo (/Users/user/project/file2.ts:20:25)
at FunctionThree (/Users/user/project/file3.ts:30:35)
at node_modules/some_module/index.js:40:45
at FunctionFour (/Users/user/project/file4.ts:50:55)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
`;
const expected = "FunctionOne, FunctionTwo, FunctionThree, FunctionFour";
expect(extractMinimalStackTraceInfo(stack)).toBe(expected);
});
it("should return an empty string if no matching lines are found", () => {
const stack = `Error: Something went wrong
at node_modules/some_module/index.js:40:45
at processTicksAndRejections (node:internal/process/task_queues:96:5)
`;
expect(extractMinimalStackTraceInfo(stack)).toBe("");
});
it("should handle stack traces without 'at ' at the beginning of lines", () => {
const stack = `Error: Something went wrong
in FunctionOne (/Users/user/project/file1.ts:10:15)
in FunctionTwo (/Users/user/project/file2.ts:20:25)
`;
expect(extractMinimalStackTraceInfo(stack)).toBe("");
});
it("should handle stack traces with varying whitespace", () => {
const stack = `Error: Something went wrong
at FunctionOne (/Users/user/project/file1.ts:10:15)
at FunctionTwo(/Users/user/project/file2.ts:20:25)
at FunctionThree (/Users/user/project/file3.ts:30:35)
`;
const expected = "FunctionOne, FunctionTwo(), FunctionThree";
expect(extractMinimalStackTraceInfo(stack)).toBe(expected);
});
it("should correctly handle function names with spaces and special characters", () => {
const stack = `Error: Something went wrong
at Object.Function One (/Users/user/project/file1.ts:10:15)
at Module.<anonymous> (/Users/user/project/file2.ts:20:25)
at Function_Two (/Users/user/project/file3.ts:30:35)
`;
const expected = "Object.Function One, Module.<anonymous>, Function_Two";
expect(extractMinimalStackTraceInfo(stack)).toBe(expected);
});
it("should handle stack traces with anonymous functions", () => {
const stack = `Error: Something went wrong
at /Users/user/project/file1.ts:10:15
at /Users/user/project/file2.ts:20:25
at node_modules/some_module/index.js:40:45
`;
expect(extractMinimalStackTraceInfo(stack)).toBe("");
});
it("should handle lines without parentheses", () => {
const stack = `Error: Something went wrong
at FunctionOne
at FunctionTwo
at FunctionThree (/Users/user/project/file3.ts:30:35)
`;
const expected = "FunctionOne, FunctionTwo, FunctionThree";
expect(extractMinimalStackTraceInfo(stack)).toBe(expected);
});
});

View file

@ -5,12 +5,29 @@
* @returns A string containing the minimal stack trace information.
*/
export function extractMinimalStackTraceInfo(stack: unknown): string {
if (typeof stack !== "string") {return "";}
const lines = stack.split("\n");
if (typeof stack !== "string") {
return "";
}
const lines = stack
.trim()
.split("\n")
.map((line) => line.trim());
const minimalLines = lines.filter((line) => {
return line.trimStart().startsWith("at ") && !line.includes("node_modules");
return (
line.startsWith("at ") &&
!line.includes("node_modules") &&
!line.includes("node:internal")
);
});
return minimalLines
.map((line) => line.trimStart().replace("at ", "").split(" (").slice(0, 1))
.map((line) => line.replace("at ", "").split(" (").slice(0, 1))
.flatMap((parts) =>
parts.map(
// to be safe, remove any lingering paths - anonymous function case
(part) =>
part.replace(/(?:[A-Za-z]:[\\/]|[\\/])[^\n]*?:\d+:\d+/g, "").trim(),
),
)
.filter((part) => !!part) // remove empty string parts (anonymous functions case)
.join(", ");
}

View file

@ -0,0 +1,274 @@
// Generated by continue
import {
findFaviconPath,
getFaviconBase64,
fetchFavicon,
} from "./fetchFavicon";
describe("findFaviconPath", () => {
afterEach(() => {
jest.restoreAllMocks();
});
it("should return the favicon URL when a favicon link is present", async () => {
const mockHtml = `
<html>
<head>
<link rel="icon" href="/favicon.ico">
</head>
<body></body>
</html>
`;
const mockResponse = {
ok: true,
text: jest.fn().mockResolvedValue(mockHtml),
};
global.fetch = jest.fn().mockResolvedValue(mockResponse);
const url = new URL("https://example.com");
const faviconPath = await findFaviconPath(url);
expect(faviconPath).toBe("https://example.com/favicon.ico");
expect(global.fetch).toHaveBeenCalledWith("https://example.com");
});
it("should return undefined when no favicon link is present", async () => {
const mockHtml = `
<html>
<head></head>
<body></body>
</html>
`;
const mockResponse = {
ok: true,
text: jest.fn().mockResolvedValue(mockHtml),
};
global.fetch = jest.fn().mockResolvedValue(mockResponse);
const url = new URL("https://example.com");
const faviconPath = await findFaviconPath(url);
expect(faviconPath).toBeUndefined();
expect(global.fetch).toHaveBeenCalledWith("https://example.com");
});
it("should handle fetch errors gracefully and return undefined", async () => {
global.fetch = jest.fn().mockRejectedValue(new Error("Network error"));
const url = new URL("https://example.com");
const faviconPath = await findFaviconPath(url);
expect(faviconPath).toBeUndefined();
expect(global.fetch).toHaveBeenCalledWith("https://example.com");
});
it("should handle non-OK responses and return undefined", async () => {
const mockResponse = {
ok: false,
status: 404,
};
global.fetch = jest.fn().mockResolvedValue(mockResponse);
const url = new URL("https://example.com");
const faviconPath = await findFaviconPath(url);
expect(faviconPath).toBeUndefined();
expect(global.fetch).toHaveBeenCalledWith("https://example.com");
});
it("should handle relative favicon URLs", async () => {
const mockHtml = `
<html>
<head>
<link rel="icon" href="favicon.ico">
</head>
<body></body>
</html>
`;
const mockResponse = {
ok: true,
text: jest.fn().mockResolvedValue(mockHtml),
};
global.fetch = jest.fn().mockResolvedValue(mockResponse);
const url = new URL("https://example.com");
const faviconPath = await findFaviconPath(url);
expect(faviconPath).toBe("https://example.com/favicon.ico");
expect(global.fetch).toHaveBeenCalledWith("https://example.com");
});
});
describe("getFaviconBase64", () => {
afterEach(() => {
jest.restoreAllMocks();
});
it("should return base64 data URI of the favicon", async () => {
const iconData = "icon data";
const arrayBuffer = new TextEncoder().encode(iconData).buffer;
const mockResponse = {
ok: true,
arrayBuffer: jest.fn().mockResolvedValue(arrayBuffer),
headers: {
get: jest.fn().mockReturnValue("image/png"),
},
};
global.fetch = jest.fn().mockResolvedValue(mockResponse);
global.btoa = jest
.fn()
.mockImplementation((str) =>
Buffer.from(str, "binary").toString("base64"),
);
const faviconUrl = "https://example.com/favicon.ico";
const base64DataUri = await getFaviconBase64(faviconUrl);
const expectedBase64 = Buffer.from(iconData).toString("base64");
expect(base64DataUri).toBe(`data:image/png;base64,${expectedBase64}`);
expect(global.fetch).toHaveBeenCalledWith(faviconUrl);
});
it("should handle fetch errors gracefully and return undefined", async () => {
global.fetch = jest.fn().mockRejectedValue(new Error("Network error"));
const faviconUrl = "https://example.com/favicon.ico";
const base64DataUri = await getFaviconBase64(faviconUrl);
expect(base64DataUri).toBeUndefined();
expect(global.fetch).toHaveBeenCalledWith(faviconUrl);
});
it("should handle non-OK responses and return undefined", async () => {
const mockResponse = {
ok: false,
status: 404,
};
global.fetch = jest.fn().mockResolvedValue(mockResponse);
const faviconUrl = "https://example.com/favicon.ico";
const base64DataUri = await getFaviconBase64(faviconUrl);
expect(base64DataUri).toBeUndefined();
expect(global.fetch).toHaveBeenCalledWith(faviconUrl);
});
it("should use default mime type if content-type header is missing", async () => {
const iconData = "icon data";
const arrayBuffer = new TextEncoder().encode(iconData).buffer;
const mockResponse = {
ok: true,
arrayBuffer: jest.fn().mockResolvedValue(arrayBuffer),
headers: {
get: jest.fn().mockReturnValue(null),
},
};
global.fetch = jest.fn().mockResolvedValue(mockResponse);
global.btoa = jest
.fn()
.mockImplementation((str) =>
Buffer.from(str, "binary").toString("base64"),
);
const faviconUrl = "https://example.com/favicon.ico";
const base64DataUri = await getFaviconBase64(faviconUrl);
const expectedBase64 = Buffer.from(iconData).toString("base64");
expect(base64DataUri).toBe(`data:image/x-icon;base64,${expectedBase64}`);
expect(global.fetch).toHaveBeenCalledWith(faviconUrl);
});
});
describe("fetchFavicon", () => {
afterEach(() => {
jest.restoreAllMocks();
});
it("should return base64 data URI of the favicon when favicon is found", async () => {
const url = new URL("https://example.com");
// Mock fetch for homepage
const homepageHtml = `
<html>
<head>
<link rel="icon" href="/favicon.ico">
</head>
<body></body>
</html>
`;
const homepageResponse = {
ok: true,
text: jest.fn().mockResolvedValue(homepageHtml),
};
// Mock fetch for favicon
const iconData = "icon data";
const arrayBuffer = new TextEncoder().encode(iconData).buffer;
const faviconResponse = {
ok: true,
arrayBuffer: jest.fn().mockResolvedValue(arrayBuffer),
headers: {
get: jest.fn().mockReturnValue("image/png"),
},
};
const fetchMock = jest.fn();
fetchMock.mockResolvedValueOnce(homepageResponse); // First fetch call
fetchMock.mockResolvedValueOnce(faviconResponse); // Second fetch call
global.fetch = fetchMock;
global.btoa = jest
.fn()
.mockImplementation((str) =>
Buffer.from(str, "binary").toString("base64"),
);
const result = await fetchFavicon(url);
const expectedBase64 = Buffer.from(iconData).toString("base64");
expect(result).toBe(`data:image/png;base64,${expectedBase64}`);
expect(global.fetch).toHaveBeenCalledTimes(2);
expect(global.fetch).toHaveBeenCalledWith("https://example.com");
expect(global.fetch).toHaveBeenCalledWith(
"https://example.com/favicon.ico",
);
});
it("should return undefined when favicon is not found", async () => {
const url = new URL("https://example.com");
// Mock fetch for homepage
const homepageHtml = `
<html>
<head></head>
<body></body>
</html>
`;
const homepageResponse = {
ok: true,
text: jest.fn().mockResolvedValue(homepageHtml),
};
const fetchMock = jest.fn();
fetchMock.mockResolvedValueOnce(homepageResponse); // First fetch call
global.fetch = fetchMock;
const result = await fetchFavicon(url);
expect(result).toBeUndefined();
expect(global.fetch).toHaveBeenCalledTimes(1);
expect(global.fetch).toHaveBeenCalledWith("https://example.com");
});
});

View file

@ -0,0 +1,214 @@
// Generated by continue
import generateRepoMap from "./generateRepoMap";
import { testIde, testLLM } from "../test/fixtures";
import {
setUpTestDir,
tearDownTestDir,
addToTestDir,
TEST_DIR,
} from "../test/testDir";
import fs from "fs";
import path from "path";
import { getRepoMapFilePath } from "./paths";
import { CodeSnippetsCodebaseIndex } from "../indexing/CodeSnippetsIndex";
describe.skip("generateRepoMap", () => {
beforeEach(() => {
setUpTestDir();
});
afterEach(() => {
tearDownTestDir();
jest.restoreAllMocks();
});
it("should generate a repo map with signatures included", async () => {
// Arrange
// Create sample files in the test directory
addToTestDir([
["file1.js", "function foo() {}\nfunction bar() {}"],
["subdir/file2.py", "def foo(): pass\ndef bar(): pass"],
]);
// Do not mock testIde.getWorkspaceDirs
// Mock CodeSnippetsCodebaseIndex.getPathsAndSignatures
jest
.spyOn(CodeSnippetsCodebaseIndex, "getPathsAndSignatures")
.mockImplementation(async (dirs, offset, limit) => {
// Return test data
return {
groupedByPath: {
[path.join(TEST_DIR, "file1.js")]: [
"function foo() {}",
"function bar() {}",
],
[path.join(TEST_DIR, "subdir/file2.py")]: [
"def foo():",
"def bar():",
],
},
hasMore: false,
};
});
// Set testLLM properties
testLLM.contextLength = 2048;
testLLM.countTokens = jest.fn().mockReturnValue(10);
// Act
const repoMapContent = await generateRepoMap(testLLM, testIde, {
includeSignatures: true,
});
// Assert
const expectedContent =
"Below is a repository map. \n" +
"For each file in the codebase, " +
"this map contains the name of the file, and the signature for any " +
"classes, methods, or functions in the file.\n\n" +
"file1.js:\n" +
"\tfunction foo() {}\n" +
"\t...\n" +
"\tfunction bar() {}\n\n" +
"subdir/file2.py:\n" +
"\tdef foo():\n" +
"\t...\n" +
"\tdef bar():\n\n";
expect(repoMapContent).toBe(expectedContent);
// Also check that the repo map file was created at the correct path
const repoMapPath = getRepoMapFilePath();
expect(fs.existsSync(repoMapPath)).toBe(true);
const fileContent = fs.readFileSync(repoMapPath, "utf8");
expect(fileContent).toBe(expectedContent);
});
it("should generate a repo map without signatures when includeSignatures is false", async () => {
// Arrange
// Create sample files in the test directory
addToTestDir([
["file1.js", "function foo() {}\nfunction bar() {}"],
["subdir/file2.py", "def foo(): pass\ndef bar(): pass"],
]);
// Do not mock testIde.getWorkspaceDirs
// Mock CodeSnippetsCodebaseIndex.getPathsAndSignatures
jest
.spyOn(CodeSnippetsCodebaseIndex, "getPathsAndSignatures")
.mockImplementation(async (dirs, offset, limit) => {
// Return test data
return {
groupedByPath: {
[path.join(TEST_DIR, "file1.js")]: [],
[path.join(TEST_DIR, "subdir/file2.py")]: [],
},
hasMore: false,
};
});
// Set testLLM properties
testLLM.contextLength = 2048;
testLLM.countTokens = jest.fn().mockReturnValue(10);
// Act
const repoMapContent = await generateRepoMap(testLLM, testIde, {
includeSignatures: false,
});
// Assert
const expectedContent =
"Below is a repository map. \n" +
"For each file in the codebase, " +
"this map contains the name of the file, and the signature for any " +
"classes, methods, or functions in the file.\n\n" +
"file1.js\n" +
"subdir/file2.py\n";
expect(repoMapContent).toBe(expectedContent);
// Also check that the repo map file was created at the correct path
const repoMapPath = getRepoMapFilePath();
expect(fs.existsSync(repoMapPath)).toBe(true);
const fileContent = fs.readFileSync(repoMapPath, "utf8");
expect(fileContent).toBe(expectedContent);
});
it("should handle file read errors gracefully", async () => {
// Arrange
// Create sample files in the test directory
addToTestDir([
["file1.js", "function foo() {}\nfunction bar() {}"],
["subdir/file2.py", "def foo(): pass\ndef bar(): pass"],
]);
// Do not mock testIde.getWorkspaceDirs
// Mock CodeSnippetsCodebaseIndex.getPathsAndSignatures
jest
.spyOn(CodeSnippetsCodebaseIndex, "getPathsAndSignatures")
.mockImplementation(async (dirs, offset, limit) => {
// Return test data
return {
groupedByPath: {
[path.join(TEST_DIR, "file1.js")]: ["function foo() {}"],
[path.join(TEST_DIR, "subdir/file2.py")]: ["def foo():"],
},
hasMore: false,
};
});
// Mock fs.promises.readFile to throw an error when reading file1.js
jest
.spyOn(fs.promises, "readFile")
.mockImplementation((filePath, encoding) => {
if (filePath === path.join(TEST_DIR, "file1.js")) {
return Promise.reject(new Error("File not found"));
}
return fs.promises.readFile(filePath, encoding);
});
// Spy on console.error
const consoleErrorSpy = jest
.spyOn(console, "error")
.mockImplementation(() => {});
// Set testLLM properties
testLLM.contextLength = 2048;
testLLM.countTokens = jest.fn().mockReturnValue(10);
// Act
const repoMapContent = await generateRepoMap(testLLM, testIde, {
includeSignatures: true,
});
// Assert
const expectedContent =
"Below is a repository map. \n" +
"For each file in the codebase, " +
"this map contains the name of the file, and the signature for any " +
"classes, methods, or functions in the file.\n\n" +
"subdir/file2.py:\n" +
"\tdef foo():\n\n" +
"file1.js\n"; // file1.js is added in writeRemainingPaths
expect(repoMapContent).toBe(expectedContent);
// Also check that an error was logged
expect(consoleErrorSpy).toHaveBeenCalledWith(
expect.stringContaining(
"Failed to read file:\n" +
` Path: ${path.join(TEST_DIR, "file1.js")}\n` +
" Error: File not found",
),
);
// Clean up mock
consoleErrorSpy.mockRestore();
});
});

View file

@ -0,0 +1,48 @@
// Generated by continue
import { resolveRelativePathInWorkspace } from "./ideUtils";
import { testIde } from "../test/fixtures";
import { IDE } from "..";
describe("resolveRelativePathInWorkspace", () => {
let mockIde: IDE;
beforeEach(() => {
mockIde = testIde;
});
it("should return the full path if the path is already absolute", async () => {
const mockPath = "/absolute/path/to/file.txt";
jest.spyOn(mockIde, "pathSep").mockResolvedValue("/");
const result = await resolveRelativePathInWorkspace(mockPath, mockIde);
expect(result).toBe(mockPath);
});
it("should resolve a relative path to a full path within workspace directories", async () => {
const relativePath = "relative/path/to/file.txt";
const workspaces = ["/workspace/one", "/workspace/two"];
const expectedFullPath = `/workspace/one/${relativePath}`;
jest.spyOn(mockIde, "pathSep").mockResolvedValue("/");
jest.spyOn(mockIde, "getWorkspaceDirs").mockResolvedValue(workspaces);
jest
.spyOn(mockIde, "fileExists")
.mockImplementation(async (path) => path === expectedFullPath);
const result = await resolveRelativePathInWorkspace(relativePath, mockIde);
expect(result).toBe(expectedFullPath);
});
it("should return undefined if the relative path does not exist in any workspace directory", async () => {
const relativePath = "non/existent/path.txt";
const workspaces = ["/workspace/one", "/workspace/two"];
jest.spyOn(mockIde, "pathSep").mockResolvedValue("/");
jest.spyOn(mockIde, "getWorkspaceDirs").mockResolvedValue(workspaces);
jest.spyOn(mockIde, "fileExists").mockResolvedValue(false);
const result = await resolveRelativePathInWorkspace(relativePath, mockIde);
expect(result).toBeUndefined();
});
});

View file

@ -0,0 +1,89 @@
// Generated by continue
import { incrementalParseJson } from "./incrementalParseJson";
describe("incrementalParseJson", () => {
it("should return [true, parsedJson] for valid JSON object", () => {
const raw = '{"key": "value"}';
const [isValid, parsed] = incrementalParseJson(raw);
expect(isValid).toBe(true);
expect(parsed).toEqual({ key: "value" });
});
it("should return [true, parsedJson] for valid JSON array", () => {
const raw = "[1, 2, 3]";
const [isValid, parsed] = incrementalParseJson(raw);
expect(isValid).toBe(true);
expect(parsed).toEqual([1, 2, 3]);
});
it("should return [false, partialParsedJson] for incomplete JSON object", () => {
const raw = '{"key": "value"';
const [isValid, parsed] = incrementalParseJson(raw);
expect(isValid).toBe(false);
expect(parsed).toEqual({ key: "value" });
});
it("should return [false, partialParsedJson] for incomplete JSON array", () => {
const raw = "[1, 2, 3";
const [isValid, parsed] = incrementalParseJson(raw);
expect(isValid).toBe(false);
expect(parsed).toEqual([1, 2, 3]);
});
it("should return [false, {}] for completely invalid JSON", () => {
const raw = "Hello, World!";
const [isValid, parsed] = incrementalParseJson(raw);
expect(isValid).toBe(false);
expect(parsed).toEqual({});
});
it("should return [false, {}] for empty string", () => {
const raw = "";
const [isValid, parsed] = incrementalParseJson(raw);
expect(isValid).toBe(false);
expect(parsed).toEqual({});
});
it("should return [false, {}] for invalid JSON syntax", () => {
const raw = "{key: 'value'}";
const [isValid, parsed] = incrementalParseJson(raw);
expect(isValid).toBe(false);
expect(parsed).toEqual({});
});
it("should handle whitespace-only string", () => {
const raw = " ";
const [isValid, parsed] = incrementalParseJson(raw);
expect(isValid).toBe(false);
expect(parsed).toEqual({});
});
it("should handle numeric string", () => {
const raw = "12345";
const [isValid, parsed] = incrementalParseJson(raw);
expect(isValid).toBe(true);
expect(parsed).toEqual(12345);
});
it("should handle boolean true string", () => {
const raw = "true";
const [isValid, parsed] = incrementalParseJson(raw);
expect(isValid).toBe(true);
expect(parsed).toEqual(true);
});
it("should handle boolean false string", () => {
const raw = "false";
const [isValid, parsed] = incrementalParseJson(raw);
expect(isValid).toBe(true);
expect(parsed).toEqual(false);
});
it("should handle null string", () => {
const raw = "null";
const [isValid, parsed] = incrementalParseJson(raw);
expect(isValid).toBe(true);
expect(parsed).toBeNull();
});
});

View file

@ -1,8 +1,19 @@
// File generated by Continue
import {
dedent,
dedentAndGetCommonWhitespace,
deduplicateArray,
getLastNPathParts,
copyOf,
getBasename,
getMarkdownLanguageTagForFile,
getRelativePath,
getUniqueFilePath,
groupByLastNPathParts,
removeCodeBlocksAndTrim,
removeQuotesAndEscapes,
shortestRelativePaths,
splitPath,
} from "./";
describe("getLastNPathParts", () => {
@ -198,3 +209,492 @@ describe("dedentAndGetCommonWhitespace", () => {
expect(output).toEqual([" line1\nline2\n line3", " "]);
});
});
describe("dedent function", () => {
it("should remove common leading whitespace from all lines", () => {
const result = dedent`
Hello
World
!
`;
expect(result).toBe("Hello\n World\n !");
});
it("should handle strings with no indentation", () => {
const result = dedent`Hello
World
!`;
expect(result).toBe("Hello\nWorld\n!");
});
it("should handle strings with mixed indentation", () => {
const result = dedent`
Hello
World
!
`;
expect(result).toBe(" Hello\nWorld\n !");
});
it("should remove leading and trailing empty lines", () => {
const result = dedent`
Hello
World
`;
expect(result).toBe("Hello\nWorld");
});
it("should handle empty strings", () => {
const result = dedent``;
expect(result).toBe("");
});
it("should handle strings with only whitespace", () => {
const result = dedent`
`;
expect(result).toBe("");
});
it("should handle interpolated values", () => {
const world = "World";
const result = dedent`
Hello ${world}
How are you?
`;
expect(result).toBe("Hello World\n How are you?");
});
it("should handle multiple interpolated values", () => {
const greeting = "Hello";
const name = "Alice";
const question = "How are you?";
const result = dedent`
${greeting} ${name}
${question}
`;
expect(result).toBe("Hello Alice\n How are you?");
});
it("should handle interpolated values with different indentation", () => {
const value1 = "foo";
const value2 = "bar";
const result = dedent`
${value1}
${value2}
`;
expect(result).toBe("foo\n bar");
});
it("should handle a single line with indentation", () => {
const result = dedent` Hello World!`;
expect(result).toBe("Hello World!");
});
it("should handle a string with only one non-empty line", () => {
const result = dedent`
Hello World!
`;
expect(result).toBe("Hello World!");
});
it("should handle a string with Unicode characters", () => {
const result = dedent`
こんにちは
世界
`;
expect(result).toBe("こんにちは\n 世界");
});
it("should handle a string with emoji", () => {
const result = dedent`
🌍
🌎
🌏
`;
expect(result).toBe("🌍\n 🌎\n 🌏");
});
it.skip("should handle a string with CRLF line endings", () => {
const result = dedent`
Hello\r
World\r
`;
expect(result).toBe("Hello\r\n World");
});
it.skip("should handle strings with tabs", () => {
const result = dedent`
\tHello
\t\tWorld
\t\t\t!
`;
expect(result).toBe("\tHello\n\t\tWorld\n\t\t\t!");
});
it("should not count empty lines in the minimum indentation", () => {
const result = dedent`
Hello
World
`;
expect(result).toBe("Hello\n\nWorld");
});
it("should work with templated strings", () => {
const language = "typescript";
const code = "console.log('hello');\nconsole.log('world');";
const result = dedent`
This is the prefix of the file:
\`\`\`${language}
${code}
\`\`\``;
expect(result).toBe(`\
This is the prefix of the file:
\`\`\`${language}
${code}
\`\`\``);
});
});
describe("removeQuotesAndEscapes", () => {
it("should remove surrounding double quotes and unescape characters", () => {
const input = '"Hello \\"World\\""';
const output = removeQuotesAndEscapes(input);
expect(output).toBe('Hello "World"');
});
it("should remove surrounding single quotes and unescape characters", () => {
const input = "'It\\'s a test'";
const output = removeQuotesAndEscapes(input);
expect(output).toBe("It's a test");
});
it("should handle smart quotes and remove them", () => {
const input = "“Smart Quotes”";
const output = removeQuotesAndEscapes(input);
expect(output).toBe("Smart Quotes");
});
it("should remove backticks if present", () => {
const input = "`Some code snippet`";
const output = removeQuotesAndEscapes(input);
expect(output).toBe("Some code snippet");
});
it("should handle multiple layers of quotes", () => {
const input = "\"\"''``Nested``''\"\"";
const output = removeQuotesAndEscapes(input);
expect(output).toBe("Nested");
});
it("should handle strings without quotes", () => {
const input = "No quotes here";
const output = removeQuotesAndEscapes(input);
expect(output).toBe("No quotes here");
});
it("should handle empty strings", () => {
const input = "";
const output = removeQuotesAndEscapes(input);
expect(output).toBe("");
});
it("should handle strings with only escape sequences", () => {
const input = "\\n\\t\\\\";
const output = removeQuotesAndEscapes(input);
expect(output).toBe("\n\t\\");
});
});
describe("getBasename", () => {
it("should return the base name of a Unix-style path", () => {
const filepath = "/home/user/documents/file.txt";
const output = getBasename(filepath);
expect(output).toBe("file.txt");
});
it("should return the base name of a Windows-style path", () => {
const filepath = "C:\\Users\\User\\Documents\\file.txt";
const output = getBasename(filepath);
expect(output).toBe("file.txt");
});
it("should handle paths with mixed separators", () => {
const filepath = "C:/Users\\User/Documents/file.txt";
const output = getBasename(filepath);
expect(output).toBe("file.txt");
});
it("should return an empty string for empty input", () => {
const filepath = "";
const output = getBasename(filepath);
expect(output).toBe("");
});
});
describe("groupByLastNPathParts", () => {
it("should group filepaths by their last N parts", () => {
const filepaths = [
"/a/b/c/d/file1.txt",
"/x/y/z/file1.txt",
"/a/b/c/d/file2.txt",
];
const output = groupByLastNPathParts(filepaths, 2);
expect(output).toEqual({
"d/file1.txt": ["/a/b/c/d/file1.txt"],
"z/file1.txt": ["/x/y/z/file1.txt"],
"d/file2.txt": ["/a/b/c/d/file2.txt"],
});
});
it("should handle an empty array", () => {
const filepaths: string[] = [];
const output = groupByLastNPathParts(filepaths, 2);
expect(output).toEqual({});
});
it("should handle N greater than path parts", () => {
const filepaths = ["/file.txt"];
const output = groupByLastNPathParts(filepaths, 5);
expect(output).toEqual({ "/file.txt": ["/file.txt"] });
});
});
describe("getUniqueFilePath", () => {
it("should return a unique file path within the group", () => {
const item = "/a/b/c/file.txt";
const itemGroups = {
"c/file.txt": ["/a/b/c/file.txt", "/x/y/c/file.txt"],
};
const output = getUniqueFilePath(item, itemGroups);
expect(output).toBe("b/c/file.txt");
});
it("should return the last two parts if unique", () => {
const item = "/a/b/c/file.txt";
const itemGroups = {
"c/file.txt": ["/a/b/c/file.txt"],
};
const output = getUniqueFilePath(item, itemGroups);
expect(output).toBe("c/file.txt");
});
it("should handle when additional parts are needed to make it unique", () => {
const item = "/a/b/c/d/e/file.txt";
const itemGroups = {
"e/file.txt": ["/a/b/c/d/e/file.txt", "/x/y/z/e/file.txt"],
};
const output = getUniqueFilePath(item, itemGroups);
expect(output).toBe("d/e/file.txt");
});
});
describe("shortestRelativePaths", () => {
it("should return shortest unique paths", () => {
const paths = [
"/a/b/c/file.txt",
"/a/b/d/file.txt",
"/a/b/d/file2.txt",
"/x/y/z/file.txt",
];
const output = shortestRelativePaths(paths);
expect(output).toEqual([
"c/file.txt",
"d/file.txt",
"file2.txt",
"z/file.txt",
]);
});
it("should handle empty array", () => {
const paths: string[] = [];
const output = shortestRelativePaths(paths);
expect(output).toEqual([]);
});
it("should handle paths with same base names", () => {
const paths = [
"/a/b/c/d/file.txt",
"/a/b/c/e/file.txt",
"/a/b/f/g/h/file.txt",
];
const output = shortestRelativePaths(paths);
expect(output).toEqual(["d/file.txt", "e/file.txt", "h/file.txt"]);
});
it("should handle paths where entire path is needed", () => {
const paths = ["/a/b/c/file.txt", "/a/b/c/file.txt", "/a/b/c/file.txt"];
const output = shortestRelativePaths(paths);
expect(output).toEqual(["file.txt", "file.txt", "file.txt"]);
});
});
describe("splitPath", () => {
it("should split Unix-style paths", () => {
const path = "/a/b/c/d/e.txt";
const output = splitPath(path);
expect(output).toEqual(["", "a", "b", "c", "d", "e.txt"]);
});
it("should split Windows-style paths", () => {
const path = "C:\\Users\\User\\Documents\\file.txt";
const output = splitPath(path);
expect(output).toEqual(["C:", "Users", "User", "Documents", "file.txt"]);
});
it("should handle withRoot parameter", () => {
const path = "/a/b/c/d/e.txt";
const withRoot = "/a/b";
const output = splitPath(path, withRoot);
expect(output).toEqual(["b", "c", "d", "e.txt"]);
});
it("should handle empty path", () => {
const path = "";
const output = splitPath(path);
expect(output).toEqual([""]);
});
it("should handle paths with multiple consecutive separators", () => {
const path = "/a//b/c/d/e.txt";
const output = splitPath(path);
expect(output).toEqual(["", "a", "", "b", "c", "d", "e.txt"]);
});
});
describe("getRelativePath", () => {
it("should return the relative path with respect to workspace directories", () => {
const filepath = "/workspace/project/src/file.ts";
const workspaceDirs = ["/workspace/project"];
const output = getRelativePath(filepath, workspaceDirs);
expect(output).toBe("src/file.ts");
});
it("should return the filename if not in any workspace", () => {
const filepath = "/other/place/file.ts";
const workspaceDirs = ["/workspace/project"];
const output = getRelativePath(filepath, workspaceDirs);
expect(output).toBe("file.ts");
});
it("should handle multiple workspace directories", () => {
const filepath = "/workspace2/project/src/file.ts";
const workspaceDirs = ["/workspace/project", "/workspace2/project"];
const output = getRelativePath(filepath, workspaceDirs);
expect(output).toBe("src/file.ts");
});
it("should handle Windows-style paths", () => {
const filepath = "C:\\workspace\\project\\src\\file.ts";
const workspaceDirs = ["C:\\workspace\\project"];
const output = getRelativePath(filepath, workspaceDirs);
expect(output).toBe("src/file.ts");
});
it("should handle paths with spaces or special characters", () => {
const filepath = "/workspace/project folder/src/file.ts";
const workspaceDirs = ["/workspace/project folder"];
const output = getRelativePath(filepath, workspaceDirs);
expect(output).toBe("src/file.ts");
});
});
describe("getMarkdownLanguageTagForFile", () => {
it("should return correct language tag for known extensions", () => {
expect(getMarkdownLanguageTagForFile("test.py")).toBe("python");
expect(getMarkdownLanguageTagForFile("test.tsx")).toBe("tsx");
expect(getMarkdownLanguageTagForFile("test.java")).toBe("java");
expect(getMarkdownLanguageTagForFile("test.md")).toBe("markdown");
expect(getMarkdownLanguageTagForFile("test.sh")).toBe("shell");
expect(getMarkdownLanguageTagForFile("test.sql")).toBe("sql");
});
it("should return the extension if not in the known list", () => {
expect(getMarkdownLanguageTagForFile("file.unknownext")).toBe("unknownext");
});
it("should handle filenames without extension", () => {
expect(getMarkdownLanguageTagForFile("Makefile")).toBe("Makefile");
});
it("should handle filenames with multiple dots", () => {
expect(getMarkdownLanguageTagForFile("archive.tar.gz")).toBe("gz");
});
it("should handle edge case with empty string as filename", () => {
expect(getMarkdownLanguageTagForFile("")).toBe("");
});
it("should correctly identify files with no extensions", () => {
expect(getMarkdownLanguageTagForFile("README")).toBe("README");
});
});
describe("copyOf", () => {
it("should create a deep copy of an object", () => {
const original = { a: 1, b: { c: 2 } };
const copied = copyOf(original);
expect(copied).toEqual(original);
expect(copied).not.toBe(original);
expect(copied.b).not.toBe(original.b);
});
it("should handle arrays", () => {
const original = [1, 2, { a: 3 }];
const copied = copyOf(original);
expect(copied).toEqual(original);
expect(copied).not.toBe(original);
expect(copied[2]).not.toBe(original[2]);
});
it("should return null for null input", () => {
expect(copyOf(null)).toBeNull();
});
it("should return undefined for undefined input", () => {
expect(copyOf(undefined)).toBeUndefined();
});
it("should handle objects with circular references gracefully", () => {
// This may not be feasible with JSON.stringify – consider alternative methods like a library for deep cloning.
const a: any = {};
a.self = a;
expect(() => copyOf(a)).toThrow(); // Ideally, handle circular refs before calling JSON.stringify
});
});
describe("removeCodeBlocksAndTrim", () => {
it("should remove code blocks from text", () => {
const text =
"Here is some text.\n```javascript\nconsole.log('Hello');\n```\nMore text.";
const output = removeCodeBlocksAndTrim(text);
expect(output).toBe("Here is some text.\n\nMore text.");
});
it("should remove multiple code blocks", () => {
const text =
"Text before.\n```code block 1```\nBetween code blocks.\n```code block 2```\nText after.";
const output = removeCodeBlocksAndTrim(text);
expect(output).toBe("Text before.\n\nBetween code blocks.\n\nText after.");
});
it("should handle text without code blocks", () => {
const text = "No code blocks here.";
const output = removeCodeBlocksAndTrim(text);
expect(output).toBe("No code blocks here.");
});
it("should trim whitespace from the result", () => {
const text = " \n```code```\n ";
const output = removeCodeBlocksAndTrim(text);
expect(output).toBe("");
});
});

View file

@ -1,18 +1,18 @@
export function removeQuotesAndEscapes(output: string): string {
output = output.trim();
export function removeQuotesAndEscapes(input: string): string {
let output = input.trim();
// Replace smart quotes
output = output.replace("“", '"');
output = output.replace("”", '"');
output = output.replace("‘", "'");
output = output.replace("’", "'");
output = output.replaceAll("“", '"');
output = output.replaceAll("”", '"');
output = output.replaceAll("‘", "'");
output = output.replaceAll("’", "'");
// Remove escapes
output = output.replace('\\"', '"');
output = output.replace("\\'", "'");
output = output.replace("\\n", "\n");
output = output.replace("\\t", "\t");
output = output.replace("\\\\", "\\");
output = output.replaceAll('\\"', '"');
output = output.replaceAll("\\'", "'");
output = output.replaceAll("\\n", "\n");
output = output.replaceAll("\\t", "\t");
output = output.replaceAll("\\\\", "\\");
while (
(output.startsWith('"') && output.endsWith('"')) ||
(output.startsWith("'") && output.endsWith("'"))
@ -192,63 +192,37 @@ export function getRelativePath(
}
export function getMarkdownLanguageTagForFile(filepath: string): string {
const extToLangMap: { [key: string]: string } = {
py: "python",
js: "javascript",
jsx: "jsx",
tsx: "tsx",
ts: "typescript",
java: "java",
go: "go",
rb: "ruby",
rs: "rust",
c: "c",
cpp: "cpp",
cs: "csharp",
php: "php",
scala: "scala",
swift: "swift",
kt: "kotlin",
md: "markdown",
json: "json",
html: "html",
css: "css",
sh: "shell",
yaml: "yaml",
toml: "toml",
tex: "latex",
sql: "sql",
ps1: "powershell",
};
const ext = filepath.split(".").pop();
switch (ext) {
case "py":
return "python";
case "js":
return "javascript";
case "jsx":
return "jsx";
case "tsx":
return "tsx";
case "ts":
return "typescript";
case "java":
return "java";
case "go":
return "go";
case "rb":
return "ruby";
case "rs":
return "rust";
case "c":
return "c";
case "cpp":
return "cpp";
case "cs":
return "csharp";
case "php":
return "php";
case "scala":
return "scala";
case "swift":
return "swift";
case "kt":
return "kotlin";
case "md":
return "markdown";
case "json":
return "json";
case "html":
return "html";
case "css":
return "css";
case "sh":
return "shell";
case "yaml":
return "yaml";
case "toml":
return "toml";
case "tex":
return "latex";
case "sql":
return "sql";
case "ps1":
return "powershell";
default:
return ext ?? "";
}
return ext ? (extToLangMap[ext] ?? ext) : "";
}
export function copyOf(obj: any): any {
@ -257,6 +231,7 @@ export function copyOf(obj: any): any {
}
return JSON.parse(JSON.stringify(obj));
}
``;
export function deduplicateArray<T>(
array: T[],

View file

@ -0,0 +1,74 @@
import { stripImages, renderChatMessage, renderContextItems, normalizeToMessageParts } from "./messageContent.js";
import { ChatMessage, ContextItem, MessageContent, MessagePart } from "../index.js";
describe("messageContent utility functions", () => {
describe("stripImages", () => {
it("should return the string as is if messageContent is a string", () => {
const content: MessageContent = "This is a test message.";
expect(stripImages(content)).toBe("This is a test message.");
});
it("should strip out image parts and join text parts of a message", () => {
const content: MessageContent = [
{ type: "text", text: "This is" },
{ type: "imageUrl", imageUrl: { url: "http://example.com/image1.png" } },
{ type: "text", text: "a test message." },
];
expect(stripImages(content)).toBe("This is\na test message.");
});
});
describe("renderChatMessage", () => {
it("should render user, assistant, or system messages with stripped image content", () => {
const message: ChatMessage = {
role: "assistant",
content: [
{ type: "text", text: "Hello," },
{ type: "imageUrl", imageUrl: { url: "http://example.com/image.png" } },
{ type: "text", text: "world!" },
],
};
expect(renderChatMessage(message)).toBe("Hello,\nworld!");
});
it("should render tool messages as is", () => {
const message: ChatMessage = {
role: "tool",
content: "Command output message",
toolCallId: "1",
};
expect(renderChatMessage(message)).toBe("Command output message");
});
});
describe("renderContextItems", () => {
it("should concatenate the content of context items with two newlines", () => {
const items: ContextItem[] = [
{ content: "Context Item 1", name: "Item1", description: "Description1" },
{ content: "Context Item 2", name: "Item2", description: "Description2" },
];
expect(renderContextItems(items)).toBe("Context Item 1\n\nContext Item 2");
});
});
describe("normalizeToMessageParts", () => {
it("should normalize user, assistant, or system messages to MessagePart array", () => {
const message: ChatMessage = {
role: "user",
content: "This is a test message.",
};
const expected: MessagePart[] = [{ type: "text", text: "This is a test message." }];
expect(normalizeToMessageParts(message)).toEqual(expected);
});
it("should normalize tool messages to MessagePart array", () => {
const message: ChatMessage = {
role: "tool",
content: "Tool message content",
toolCallId: "1",
};
const expected: MessagePart[] = [{ type: "text", text: "Tool message content" }];
expect(normalizeToMessageParts(message)).toEqual(expected);
});
});
});

View file

@ -3,7 +3,7 @@ import {
ContextItem,
MessageContent,
MessagePart,
} from "../index.js";
} from "../index";
export function stripImages(messageContent: MessageContent): string {
if (typeof messageContent === "string") {

View file

@ -14,6 +14,10 @@ dotenv.config();
const CONTINUE_GLOBAL_DIR =
process.env.CONTINUE_GLOBAL_DIR ?? path.join(os.homedir(), ".continue");
// export const DEFAULT_CONFIG_TS_CONTENTS = `import { Config } from "./types"\n\nexport function modifyConfig(config: Config): Config {
// return config;
// }`;
export const DEFAULT_CONFIG_TS_CONTENTS = `export function modifyConfig(config: Config): Config {
return config;
}`;
@ -113,10 +117,6 @@ export function getConfigYamlPath(ideType: IdeType): string {
return p;
}
export function getConfigJsonUri(): string {
return getContinueGlobalUri() + "/config.json";
}
export function getConfigTsPath(): string {
const p = path.join(getContinueGlobalPath(), "config.ts");
if (!fs.existsSync(p)) {

View file

@ -1,8 +1,8 @@
// This file is generated by Continue
import {
intersection,
getRangeInString,
intersection,
maxPosition,
minPosition,
union,
@ -80,8 +80,7 @@ describe("union", () => {
});
});
// TODO
test.skip("should handle edge case where start and end lines are the same", () => {
test("should handle edge case where start and end lines are the same", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 5 },

View file

@ -58,17 +58,27 @@ export function intersection(a: Range, b: Range): Range | null {
}
export function union(a: Range, b: Range): Range {
const startLine = Math.min(a.start.line, b.start.line);
const endLine = Math.max(a.end.line, b.end.line);
let start: Position;
if (a.start.line === b.start.line) {
start = {
line: a.start.line,
character: Math.min(a.start.character, b.start.character),
};
} else if (a.start.line < b.start.line) start = a.start;
else start = b.start;
const startCharacter =
startLine === a.start.line ? a.start.character : b.start.character;
const endCharacter =
endLine === a.end.line ? a.end.character : b.end.character;
let end: Position;
if (a.end.line === b.end.line) {
end = {
line: a.end.line,
character: Math.max(a.end.character, b.end.character),
};
} else if (a.end.line > b.end.line) end = a.end;
else end = b.end;
return {
start: { line: startLine, character: startCharacter },
end: { line: endLine, character: endCharacter },
start,
end,
};
}

View file

@ -279,6 +279,7 @@ export async function getSymbolsForFile(
line: node.endPosition.row + 1,
},
},
content: node.text,
});
}
}

View file

@ -3,7 +3,7 @@ import os from "node:os";
import { removeCodeBlocksAndTrim } from ".";
import type { IMessenger } from "./messenger";
import type { IMessenger } from "../protocol/messenger";
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
// The amount of time before a process is declared

View file

@ -0,0 +1,142 @@
// Generated by continue
import {
withExponentialBackoff,
APIError,
RETRY_AFTER_HEADER,
} from "./withExponentialBackoff";
describe.skip("withExponentialBackoff", () => {
it("should return result when apiCall succeeds on first attempt", async () => {
// Arrange
const apiCall = jest.fn().mockResolvedValue("Success");
// Act
const result = await withExponentialBackoff(apiCall);
// Assert
expect(result).toBe("Success");
expect(apiCall).toHaveBeenCalledTimes(1);
});
it("should throw error when apiCall fails with non-429 error", async () => {
// Arrange
const error = new Error("Some error");
const apiCall = jest.fn().mockRejectedValue(error);
// Act & Assert
await expect(withExponentialBackoff(apiCall)).rejects.toThrow("Some error");
expect(apiCall).toHaveBeenCalledTimes(1);
});
it("should retry when apiCall fails with 429 and no Retry-After header", async () => {
// Arrange
const apiCall = jest.fn();
const firstError: APIError = new Error("Rate limit");
firstError.response = {
status: 429,
headers: {
get: () => null, // No Retry-After header
},
} as unknown as Response;
// First call fails with 429, second call succeeds
apiCall.mockRejectedValueOnce(firstError).mockResolvedValueOnce("Success");
// Act
const result = await withExponentialBackoff(
apiCall,
5,
0.01, // initialDelaySeconds
);
// Assert
expect(result).toBe("Success");
expect(apiCall).toHaveBeenCalledTimes(2);
});
it("should retry when apiCall fails with 429 and Retry-After header", async () => {
// Arrange
const apiCall = jest.fn();
const firstError: APIError = new Error("Rate limit");
firstError.response = {
status: 429,
headers: {
get: (headerName: string) => {
if (headerName === RETRY_AFTER_HEADER) {
return "0.02";
}
return null;
},
},
} as unknown as Response;
// First call fails with 429, second call succeeds
apiCall.mockRejectedValueOnce(firstError).mockResolvedValueOnce("Success");
jest.useFakeTimers();
const promise = withExponentialBackoff(apiCall, 5, 0.01);
// Advance timers to cover the delay
await jest.advanceTimersByTimeAsync(20);
const result = await promise;
// Assert
expect(result).toBe("Success");
expect(apiCall).toHaveBeenCalledTimes(2);
jest.useRealTimers();
});
it("should throw error after maxTries reached", async () => {
// Arrange
const apiCall = jest.fn();
const error: APIError = new Error("Rate limit");
error.response = {
status: 429,
headers: {
get: () => null,
},
} as unknown as Response;
apiCall.mockRejectedValue(error);
const maxTries = 3;
const initialDelaySeconds = 0.01;
// Act & Assert
await expect(
withExponentialBackoff(apiCall, maxTries, initialDelaySeconds),
).rejects.toThrow("Failed to make API call after max tries");
expect(apiCall).toHaveBeenCalledTimes(maxTries);
});
it("should not call if maxTries is 0", async () => {
const apiCall = jest.fn();
const error: APIError = new Error("Rate limit");
error.response = {
status: 429,
headers: {
get: () => null,
},
} as unknown as Response;
apiCall.mockRejectedValue(error);
const maxTries = 0;
const initialDelaySeconds = 0.01;
await expect(
withExponentialBackoff(apiCall, maxTries, initialDelaySeconds),
).rejects.toThrow("Failed to make API call after max tries");
expect(apiCall).toHaveBeenCalledTimes(0);
});
});

View file

@ -1,4 +1,4 @@
interface APIError extends Error {
export interface APIError extends Error {
response?: Response;
}
@ -6,18 +6,15 @@ export const RETRY_AFTER_HEADER = "Retry-After";
const withExponentialBackoff = async <T>(
apiCall: () => Promise<T>,
maxRetries = 5,
maxTries = 5,
initialDelaySeconds = 1,
) => {
for (let attempt = 0; attempt < maxRetries; attempt++) {
for (let attempt = 0; attempt < maxTries; attempt++) {
try {
const result = await apiCall();
return result;
} catch (error: any) {
if (
(error as APIError).response?.status === 429 &&
attempt < maxRetries - 1
) {
if ((error as APIError).response?.status === 429) {
const retryAfter = (error as APIError).response?.headers.get(
RETRY_AFTER_HEADER,
);
@ -35,7 +32,7 @@ const withExponentialBackoff = async <T>(
}
}
}
throw new Error(`Failed to make API call after ${maxRetries} retries`);
throw new Error(`Failed to make API call after ${maxTries} retries`);
};
export { withExponentialBackoff };

View file

@ -33,9 +33,12 @@ export function modifyConfig(config: Config): Config {
name: "commit",
description: "Write a commit message",
run: async function* (sdk) {
const diff = await sdk.ide.getDiff();
// The getDiff function takes a boolean parameter that indicates whether
// to include unstaged changes in the diff or not.
const diff = await sdk.ide.getDiff(false); // Pass false to exclude unstaged changes
for await (const message of sdk.llm.streamComplete(
`${diff}\n\nWrite a commit message for the above changes. Use no more than 20 tokens to give a brief description in the imperative mood (e.g. 'Add feature' not 'Added feature'):`,
new AbortController().signal,
{
maxTokens: 20,
},
@ -47,7 +50,6 @@ export function modifyConfig(config: Config): Config {
return config;
}
```
<!-- TODO: We need a config.ts reference -->
<!-- For full `config.ts` reference, see [here](reference/config-ts.md). -->

View file

@ -50,9 +50,12 @@ export function modifyConfig(config: Config): Config {
name: "commit",
description: "Write a commit message",
run: async function* (sdk) {
const diff = await sdk.ide.getDiff();
// The getDiff function takes a boolean parameter that indicates whether
// to include unstaged changes in the diff or not.
const diff = await sdk.ide.getDiff(false); // Pass false to exclude unstaged changes
for await (const message of sdk.llm.streamComplete(
`${diff}\n\nWrite a commit message for the above changes. Use no more than 20 tokens to give a brief description in the imperative mood (e.g. 'Add feature' not 'Added feature'):`,
new AbortController().signal,
{
maxTokens: 20,
},

View file

@ -51,7 +51,7 @@ Many [context provider](../context-providers.md) can be referenced by typing "@"
- `@terminal` - The contents of the terminal
- `@https://github.com/continuedev/continue` - The contents of a URL
- `@src/index.ts` - The contents of a file
- `@src/index.ts` - The contents of a file (VS Code only)
## Feedback

View file

@ -44,9 +44,12 @@ export function modifyConfig(config: Config): Config {
name: "commit",
description: "Write a commit message",
run: async function* (sdk) {
const diff = await sdk.ide.getDiff(true);
// The getDiff function takes a boolean parameter that indicates whether
// to include unstaged changes in the diff or not.
const diff = await sdk.ide.getDiff(false); // Pass false to exclude unstaged changes
for await (const message of sdk.llm.streamComplete(
`${diff}\n\nWrite a commit message for the above changes. Use no more than 20 tokens to give a brief description in the imperative mood (e.g. 'Add feature' not 'Added feature'):`,
new AbortController().signal,
{
maxTokens: 20,
},

View file

@ -33,9 +33,12 @@ export function modifyConfig(config: Config): Config {
name: "commit",
description: "Write a commit message",
run: async function* (sdk) {
const diff = await sdk.ide.getDiff();
// getDiff 函数接受一个布尔参数,该参数指示是否
// 在 diff 中包含未暂存的更改。
const diff = await sdk.ide.getDiff(false); // 传递 false 以排除未暂存的更改
for await (const message of sdk.llm.streamComplete(
`${diff}\n\nWrite a commit message for the above changes. Use no more than 20 tokens to give a brief description in the imperative mood (e.g. 'Add feature' not 'Added feature'):`,
new AbortController().signal,
{
maxTokens: 20,
},

View file

@ -44,9 +44,12 @@ export function modifyConfig(config: Config): Config {
name: "commit",
description: "Write a commit message",
run: async function* (sdk) {
const diff = await sdk.ide.getDiff();
// getDiff 函数接受一个布尔参数,该参数指示是否
// 在 diff 中包含未暂存的更改。
const diff = await sdk.ide.getDiff(false); // 传递 false 以排除未暂存的更改
for await (const message of sdk.llm.streamComplete(
`${diff}\n\nWrite a commit message for the above changes. Use no more than 20 tokens to give a brief description in the imperative mood (e.g. 'Add feature' not 'Added feature'):`,
new AbortController().signal,
{
maxTokens: 20,
},

View file

@ -10597,9 +10597,9 @@
}
},
"node_modules/nanoid": {
"version": "3.3.7",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.7.tgz",
"integrity": "sha512-eSRppjcPIatRIMC1U6UngP8XFcz8MQWGQdt1MTBQ7NaAmvXDfvNxbvWV3x2y6CdEUciCSsDHDQZbhYaB8QEo2g==",
"version": "3.3.8",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.8.tgz",
"integrity": "sha512-WNLf5Sd8oZxOm+TzppcYk8gVOgP+l58xNy58D0nbUnOxOWRWvlcCV4kUF7ltmI6PsrLl/BgKEyS4mqsGChFN0w==",
"funding": [
{
"type": "github",

View file

@ -0,0 +1,25 @@
package com.github.continuedev.continueintellijextension.actions
import com.github.continuedev.continueintellijextension.autocomplete.AcceptAutocompleteAction
import com.github.continuedev.continueintellijextension.services.ContinueExtensionSettings
import com.intellij.openapi.actionSystem.ActionPromoter
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.components.ServiceManager
import org.jetbrains.annotations.NotNull
class ContinueActionPromote : ActionPromoter {
override fun promote(@NotNull actions: List<AnAction>, @NotNull context: DataContext): List<AnAction>? {
if (actions.none { it is AcceptAutocompleteAction }) {
return null
} else {
val settings = ServiceManager.getService(ContinueExtensionSettings::class.java)
if (!settings.continueState.showIDECompletionSideBySide) {
return null;
}
return actions.filterIsInstance<AcceptAutocompleteAction>()
}
}
}

View file

@ -98,8 +98,7 @@ class AutocompleteService(private val project: Project) {
if (shouldRenderCompletion(finalTextToInsert, column, lineLength, editor)) {
renderCompletion(editor, offset, finalTextToInsert)
pendingCompletion = pendingCompletion?.copy(text = finalTextToInsert)
pendingCompletion = PendingCompletion(editor, offset, completionId, finalTextToInsert)
// Hide auto-popup
// AutoPopupController.getInstance(project).cancelAllRequests()
}
@ -152,8 +151,8 @@ class AutocompleteService(private val project: Project) {
return
}
if (isInjectedFile(editor)) return
// Don't render completions when code completion dropdown is visible
if (!autocompleteLookupListener.isLookupEmpty()) {
// Skip rendering completions if the code completion dropdown is already visible and the IDE completion side-by-side setting is disabled
if (shouldSkipRender(ServiceManager.getService(ContinueExtensionSettings::class.java))) {
return
}
@ -210,6 +209,10 @@ class AutocompleteService(private val project: Project) {
}
}
private fun shouldSkipRender(settings: ContinueExtensionSettings) =
!settings.continueState.showIDECompletionSideBySide && !autocompleteLookupListener.isLookupEmpty()
private fun splitKeepingDelimiters(input: String, delimiterPattern: String = "\\s+"): List<String> {
val initialSplit = input.split("(?<=$delimiterPattern)|(?=$delimiterPattern)".toRegex())
.filter { it.isNotEmpty() }

View file

@ -32,6 +32,7 @@ class ContinueSettingsComponent : DumbAware {
val enableContinueTeamsBeta: JCheckBox = JCheckBox("Enable Continue for Teams Beta")
val enableOSR: JCheckBox = JCheckBox("Enable Off-Screen Rendering")
val displayEditorTooltip: JCheckBox = JCheckBox("Display Editor Tooltip")
val showIDECompletionSideBySide: JCheckBox = JCheckBox("Show IDE completions side-by-side")
init {
val constraints = GridBagConstraints()
@ -63,6 +64,8 @@ class ContinueSettingsComponent : DumbAware {
constraints.gridy++
panel.add(displayEditorTooltip, constraints)
constraints.gridy++
panel.add(showIDECompletionSideBySide, constraints)
constraints.gridy++
// Add a "filler" component that takes up all remaining vertical space
constraints.weighty = 1.0
@ -94,6 +97,7 @@ open class ContinueExtensionSettings : PersistentStateComponent<ContinueExtensio
var enableContinueTeamsBeta: Boolean = false
var enableOSR: Boolean = shouldRenderOffScreen()
var displayEditorTooltip: Boolean = true
var showIDECompletionSideBySide: Boolean = false
}
var continueState: ContinueState = ContinueState()
@ -206,7 +210,8 @@ class ContinueExtensionConfigurable : Configurable {
mySettingsComponent?.enableTabAutocomplete?.isSelected != settings.continueState.enableTabAutocomplete ||
mySettingsComponent?.enableContinueTeamsBeta?.isSelected != settings.continueState.enableContinueTeamsBeta ||
mySettingsComponent?.enableOSR?.isSelected != settings.continueState.enableOSR ||
mySettingsComponent?.displayEditorTooltip?.isSelected != settings.continueState.displayEditorTooltip
mySettingsComponent?.displayEditorTooltip?.isSelected != settings.continueState.displayEditorTooltip ||
mySettingsComponent?.showIDECompletionSideBySide?.isSelected != settings.continueState.showIDECompletionSideBySide
return modified
}
@ -220,6 +225,8 @@ class ContinueExtensionConfigurable : Configurable {
mySettingsComponent?.enableContinueTeamsBeta?.isSelected ?: false
settings.continueState.enableOSR = mySettingsComponent?.enableOSR?.isSelected ?: true
settings.continueState.displayEditorTooltip = mySettingsComponent?.displayEditorTooltip?.isSelected ?: true
settings.continueState.showIDECompletionSideBySide =
mySettingsComponent?.showIDECompletionSideBySide?.isSelected ?: false
ApplicationManager.getApplication().messageBus.syncPublisher(SettingsListener.TOPIC)
.settingsUpdated(settings.continueState)
@ -235,6 +242,8 @@ class ContinueExtensionConfigurable : Configurable {
mySettingsComponent?.enableContinueTeamsBeta?.isSelected = settings.continueState.enableContinueTeamsBeta
mySettingsComponent?.enableOSR?.isSelected = settings.continueState.enableOSR
mySettingsComponent?.displayEditorTooltip?.isSelected = settings.continueState.displayEditorTooltip
mySettingsComponent?.showIDECompletionSideBySide?.isSelected =
settings.continueState.showIDECompletionSideBySide
ContinueExtensionSettings.instance.addRemoteSyncJob()
}

View file

@ -38,6 +38,8 @@
id="AutocompleteSpinnerWidget"/>
<notificationGroup id="Continue"
displayType="BALLOON"/>
<actionPromoter order="last"
implementation="com.github.continuedev.continueintellijextension.actions.ContinueActionPromote"/>
</extensions>
<resource-bundle>messages.MyBundle</resource-bundle>

View file

@ -0,0 +1,25 @@
package com.github.continuedev.continueintellijextension
import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.impl.ImaginaryEditor
import com.intellij.testFramework.TestDataPath
import com.intellij.testFramework.fixtures.BasePlatformTestCase
@TestDataPath("\$CONTENT_ROOT/src/test/testData")
class DiffStreamTest : BasePlatformTestCase() {
fun `test getAllInlaysForEditor`() {
myFixture.configureByText("index.ts", "console.log('Hello World!');")
val editor = ImaginaryEditor(myFixture.project, myFixture.editor.document)
val diffStreamService = project.service<DiffStreamService>()
val diffStreamHandler = DiffStreamHandler(project, editor, 0, 1, { -> }, { -> })
diffStreamService.register(diffStreamHandler, editor)
diffStreamHandler.streamDiffLinesToEditor()
assertEquals(editor.document.text, myFixture.file.text)
}
}

View file

@ -1252,9 +1252,15 @@
"properties": {
"model": {
"enum": [
"Qwen/QwQ-32B-Preview",
"Qwen/Qwen2.5-Coder-32B-Instruct",
"Qwen/Qwen2.5-Coder-7B-Instruct",
"Pro/Qwen/Qwen2.5-Coder-7B-Instruct"
"Pro/Qwen/Qwen2.5-Coder-7B-Instruct",
"Tencent/Hunyuan-A52B-Instruct",
"nvidia/Llama-3.1-Nemotron-70B-Instruct",
"Qwen/Qwen2-VL-72B-Instruct",
"TeleAI/TeleMM",
"deepseek-ai/DeepSeek-V2.5"
]
}
}
@ -2923,6 +2929,11 @@
"x-intellij-html-description": "If set to <code>true</code>, a scrollbar will be displayed in the chat window to navigate through messages.",
"default": false,
"type": "boolean"
},
"codeWrap": {
"type": "boolean",
"description": "If set to true, code in pre blocks will wrap.",
"default": false
}
}
},

View file

@ -1,3 +1,4 @@
import { expect } from "chai";
import { WebElement } from "vscode-extension-tester";
export class TestUtils {
@ -24,4 +25,38 @@ export class TestUtils {
throw new Error(`Element not found after ${timeout}ms timeout`);
}
public static async expectNoElement(
locatorFn: () => Promise<WebElement>,
timeout: number = 1000,
interval: number = 200,
): Promise<void> {
const startTime = Date.now();
let elementFound = false;
while (Date.now() - startTime < timeout) {
try {
const element = await locatorFn();
if (element) {
elementFound = true;
break;
}
} catch (e) {
// Continue if there's an error (element not found)
}
await new Promise((resolve) => setTimeout(resolve, interval));
}
expect(elementFound).to.be.false;
}
public static generateTestMessagePair(id: number = 0): {
userMessage: string;
llmResponse: string;
} {
return {
userMessage: `TEST_USER_MESSAGE_${id}`,
llmResponse: `TEST_LLM_RESPONSE_${id}`,
};
}
}

View file

@ -1,4 +1,5 @@
import {
Key,
WebDriver,
WebElement,
WebView,
@ -56,4 +57,21 @@ export class GUIActions {
await dropdownOption.click();
};
public static async sendMessage({
view,
message,
inputFieldIndex,
}: {
view: WebView;
message: string;
inputFieldIndex: number;
}) {
const editor = await GUISelectors.getMessageInputFieldAtIndex(
view,
inputFieldIndex,
);
await editor.sendKeys(message);
await editor.sendKeys(Key.ENTER);
}
}

View file

@ -6,8 +6,16 @@ export class GUISelectors {
return view.findWebElement(By.xpath("//*[contains(text(), 'Quickly')]"));
}
public static getTipTapEditor(view: WebView) {
return view.findWebElement(By.className("tiptap"));
public static getMessageInputFields(view: WebView) {
return view.findWebElements(By.className("tiptap"));
}
public static async getMessageInputFieldAtIndex(
view: WebView,
index: number,
) {
const elements = await view.findWebElements(By.className("tiptap"));
return elements[index];
}
public static getAllIframes(driver: WebDriver) {
@ -26,6 +34,19 @@ export class GUISelectors {
return SelectorUtils.getElementByDataTestId(view, "model-select-button");
}
public static getNthHistoryTableRow(view: WebView, index: number) {
return SelectorUtils.getElementByDataTestId(view, `history-row-${index}`);
}
public static getNthMessageDeleteButton(view: WebView, index: number) {
const adjustedIndex = 1 + index * 2;
return SelectorUtils.getElementByDataTestId(
view,
`delete-button-${adjustedIndex}`,
);
}
public static getModelDropdownOption(view: WebView, option: string) {
return view.findWebElement(
By.xpath(`//*[@role="listbox"]//*[contains(text(), "${option}")]`),
@ -37,4 +58,12 @@ export class GUISelectors {
By.xpath(`//*[@class="thread-message"]//*[contains(text(), "${text}")]`),
);
}
public static getHistoryNavButton(view: WebView) {
return SelectorUtils.getElementByAriaLabel(view, "View History");
}
public static getNewSessionNavButton(view: WebView) {
return SelectorUtils.getElementByAriaLabel(view, "New Session");
}
}

View file

@ -13,4 +13,17 @@ export class SelectorUtils {
): Promise<WebElement> {
return view.findWebElement(By.css(`[data-testid='${testId}']`));
}
/**
* Finds a web element by its aria-label attribute within a WebView.
* @param view - The WebView to search within.
* @param ariaLabel - The aria-label value to search for.
* @returns A promise that resolves to the WebElement found.
*/
public static getElementByAriaLabel(
view: WebView,
ariaLabel: string,
): Promise<WebElement> {
return view.findWebElement(By.css(`[aria-label='${ariaLabel}']`));
}
}

View file

@ -3,6 +3,7 @@ import {
WebView,
WebDriver,
VSBrowser,
Key,
} from "vscode-extension-tester";
import { expect } from "chai";
import { GUIActions } from "../actions/GUI.actions";
@ -10,14 +11,19 @@ import { GUISelectors } from "../selectors/GUI.selectors";
import * as path from "path";
import { TestUtils } from "../TestUtils";
const DEFAULT_TIMEOUT = 30_000;
describe("GUI Test", () => {
let view: WebView;
let driver: WebDriver;
before(async function () {
this.timeout(10000000);
this.timeout(DEFAULT_TIMEOUT);
await VSBrowser.instance.openResources(path.join("e2e/test-continue"));
});
beforeEach(async function () {
this.timeout(DEFAULT_TIMEOUT);
await GUIActions.openGui();
@ -25,35 +31,223 @@ describe("GUI Test", () => {
driver = view.getDriver();
await GUIActions.switchToReactIframe(driver);
await GUIActions.selectModelFromDropdown(view, "TEST LLM");
// await new Promise((res) => {
// setTimeout(res, 10000000);
// setTimeout(res, DEFAULT_TIMEOUT);
// });
});
after(async () => {
afterEach(async function () {
this.timeout(DEFAULT_TIMEOUT);
await view.switchBack();
await new EditorView().closeAllEditors();
});
it("should display correct panel description", async () => {
const description = await GUISelectors.getDescription(view);
describe("Onboarding", () => {
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);
expect(await description.getText()).has.string(
"Quickly get up and running using our API keys.",
);
}).timeout(DEFAULT_TIMEOUT);
});
it("should allow typing text in the editor", async () => {
await GUIActions.selectModelFromDropdown(view, "Mock");
await GUIActions.selectModelFromDropdown(view, "TEST LLM");
describe("Chat", () => {
it("Can submit message by pressing enter", async () => {
const [messageInput] = await GUISelectors.getMessageInputFields(view);
const messagePair = TestUtils.generateTestMessagePair();
await messageInput.sendKeys(messagePair.userMessage);
await messageInput.sendKeys(Key.ENTER);
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, messagePair.llmResponse),
);
});
const tiptap = await GUISelectors.getTipTapEditor(view);
it("Can submit message by button click", async () => {
const [messageInput] = await GUISelectors.getMessageInputFields(view);
const messagePair = TestUtils.generateTestMessagePair();
await messageInput.sendKeys(messagePair.userMessage);
(await GUISelectors.getSubmitInputButton(view)).click();
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, messagePair.llmResponse),
);
});
await tiptap.sendKeys("How are you?");
(await GUISelectors.getSubmitInputButton(view)).click();
it.only("Can delete messages", async () => {
const { userMessage: userMessage0, llmResponse: llmResponse0 } =
TestUtils.generateTestMessagePair(0);
await GUIActions.sendMessage({
view,
message: userMessage0,
inputFieldIndex: 0,
});
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse0),
);
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, "I'm fine"),
);
}).timeout(20_000);
const { userMessage: userMessage1, llmResponse: llmResponse1 } =
TestUtils.generateTestMessagePair(1);
await GUIActions.sendMessage({
view,
message: userMessage1,
inputFieldIndex: 1,
});
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse1),
);
const { userMessage: userMessage2, llmResponse: llmResponse2 } =
TestUtils.generateTestMessagePair(2);
await GUIActions.sendMessage({
view,
message: userMessage2,
inputFieldIndex: 2,
});
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse2),
);
GUISelectors.getThreadMessageByText(view, llmResponse1);
await (await GUISelectors.getNthMessageDeleteButton(view, 1)).click();
await TestUtils.expectNoElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse1),
);
GUISelectors.getThreadMessageByText(view, llmResponse0);
await (await GUISelectors.getNthMessageDeleteButton(view, 0)).click();
await TestUtils.expectNoElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse0),
);
GUISelectors.getThreadMessageByText(view, llmResponse2);
await (await GUISelectors.getNthMessageDeleteButton(view, 0)).click();
await TestUtils.expectNoElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse2),
);
}).timeout(DEFAULT_TIMEOUT);
it("Can edit messages", async () => {
const { userMessage: userMessage0, llmResponse: llmResponse0 } =
TestUtils.generateTestMessagePair(0);
await GUIActions.sendMessage({
view,
message: userMessage0,
inputFieldIndex: 0,
});
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse0),
);
const { userMessage: userMessage1, llmResponse: llmResponse1 } =
TestUtils.generateTestMessagePair(1);
await GUIActions.sendMessage({
view,
message: userMessage1,
inputFieldIndex: 1,
});
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse1),
);
const { userMessage: userMessage2, llmResponse: llmResponse2 } =
TestUtils.generateTestMessagePair(2);
await GUIActions.sendMessage({
view,
message: userMessage2,
inputFieldIndex: 2,
});
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse2),
);
const secondInputField = await GUISelectors.getMessageInputFieldAtIndex(
view,
1,
);
await secondInputField.clear();
const { userMessage: userMessage3, llmResponse: llmResponse3 } =
TestUtils.generateTestMessagePair(3);
await GUIActions.sendMessage({
view,
message: userMessage3,
inputFieldIndex: 1,
});
await GUISelectors.getThreadMessageByText(view, llmResponse0);
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse3),
);
await Promise.all([
TestUtils.expectNoElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse1),
),
TestUtils.expectNoElement(() =>
GUISelectors.getThreadMessageByText(view, llmResponse2),
),
]);
}).timeout(DEFAULT_TIMEOUT);
});
describe("Chat Paths", () => {
it("chat → history → chat", async () => {
const messagePair1 = TestUtils.generateTestMessagePair(1);
await GUIActions.sendMessage({
view,
message: messagePair1.userMessage,
inputFieldIndex: 0,
});
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, messagePair1.llmResponse),
);
const messagePair2 = TestUtils.generateTestMessagePair(2);
await GUIActions.sendMessage({
view,
message: messagePair2.userMessage,
inputFieldIndex: 1,
});
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, messagePair2.llmResponse),
);
/**
* SWITCHING BACK AND FORTH
* We are switching back and forth here because the history is broken.
* It only updates once a another chat is opened, so we need to open a
* different chat first.
*/
await view.switchBack();
await (await GUISelectors.getHistoryNavButton(view)).click();
await GUIActions.switchToReactIframe(driver);
await (await GUISelectors.getNthHistoryTableRow(view, 0)).click();
await view.switchBack();
await (await GUISelectors.getHistoryNavButton(view)).click();
/**
* END OF SWITCHING BACK AND FORTH
*/
await GUIActions.switchToReactIframe(driver);
await (await GUISelectors.getNthHistoryTableRow(view, 0)).click();
await GUISelectors.getThreadMessageByText(view, messagePair1.llmResponse);
await GUISelectors.getThreadMessageByText(view, messagePair2.llmResponse);
const messagePair3 = TestUtils.generateTestMessagePair(3);
await GUIActions.sendMessage({
view,
message: messagePair3.userMessage,
inputFieldIndex: 2,
});
await TestUtils.waitForElement(() =>
GUISelectors.getThreadMessageByText(view, messagePair3.llmResponse),
);
}).timeout(DEFAULT_TIMEOUT);
});
});

View file

@ -77,6 +77,7 @@
"cargo-cp-artifact": "^0.1",
"chai": "^4.5.0",
"esbuild": "0.17.19",
"esbuild-visualizer": "^0.6.0",
"eslint": "^8.28.0",
"glob": "^8.0.3",
"json-schema-to-typescript": "^12.0.0",
@ -102,10 +103,9 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "../packages/config-yaml",
"@continuedev/fetch": "^1.0.3",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "../packages/openai-adapters",
"@continuedev/openai-adapters": "^1.0.10",
"@modelcontextprotocol/sdk": "^1.0.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
@ -5351,6 +5351,23 @@
"@esbuild/win32-x64": "0.17.19"
}
},
"node_modules/esbuild-visualizer": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/esbuild-visualizer/-/esbuild-visualizer-0.6.0.tgz",
"integrity": "sha512-oNK3JAhC7+re93VTtUdWJKTDVnA2qXPAjCAoaw9OxEFUXztszw3kcaK46u1U790T8FdUBAWv6F9Xt59P8nJCVA==",
"dev": true,
"dependencies": {
"open": "^8.4.0",
"picomatch": "^2.3.1",
"yargs": "^17.6.2"
},
"bin": {
"esbuild-visualizer": "dist/bin/cli.js"
},
"engines": {
"node": ">=18"
}
},
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "0.9.242",
"version": "0.9.248",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -602,6 +602,7 @@
"vscode:prepublish": "npm run esbuild-base -- --minify",
"esbuild": "npm run esbuild-base -- --sourcemap",
"esbuild-watch": "npm run esbuild-base -- --sourcemap --watch",
"esbuild:visualize": "esbuild-visualizer --metadata ./build/meta.json --filename ./build/stats.html --open",
"tsc": "tsc -p ./",
"tsc:check": "tsc -p ./ --noEmit",
"tsc-watch": "tsc -watch -p ./",
@ -619,6 +620,7 @@
"build-debug:rust": "npm run build:rust --",
"build-release:rust": "npm run build:rust -- --release",
"e2e:compile": "tsc -p ./tsconfig.e2e.json",
"e2e:build": "npm --prefix ../../gui run build && npm run package",
"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",
@ -627,7 +629,7 @@
"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:all": "npm run e2e:build && 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"
},
@ -651,6 +653,7 @@
"cargo-cp-artifact": "^0.1",
"chai": "^4.5.0",
"esbuild": "0.17.19",
"esbuild-visualizer": "^0.6.0",
"eslint": "^8.28.0",
"glob": "^8.0.3",
"json-schema-to-typescript": "^12.0.0",

View file

@ -20,6 +20,31 @@ const esbuildConfig = {
inject: ["./scripts/importMetaUrl.js"],
define: { "import.meta.url": "importMetaUrl" },
supported: { "dynamic-import": false },
metafile: true,
plugins: [
{
name: "on-end-plugin",
setup(build) {
build.onEnd((result) => {
if (result.errors.length > 0) {
console.error("Build failed with errors:", result.errors);
throw new Error(result.errors);
} else {
try {
const fs = require("fs");
fs.writeFileSync(
"./build/meta.json",
JSON.stringify(result.metafile, null, 2),
);
} catch (e) {
console.error("Failed to write esbuild meta file", e);
}
console.log("VS Code Extension esbuild complete"); // used verbatim in vscode tasks to detect completion
}
});
},
},
],
};
(async () => {
@ -30,5 +55,4 @@ const esbuildConfig = {
} else {
await esbuild.build(esbuildConfig);
}
console.log("VS Code Extension esbuild complete"); // Used in task endpattern to signal completion
})();
})();

View file

@ -15,8 +15,8 @@ if (!fs.existsSync("build")) {
const isPreRelease = args.includes("--pre-release");
let command = isPreRelease
? "npx vsce package --out ./build patch --pre-release --no-dependencies" // --yarn"
: "npx vsce package --out ./build patch --no-dependencies"; // --yarn";
? "npx vsce package --out ./build --pre-release --no-dependencies" // --yarn"
: "npx vsce package --out ./build --no-dependencies"; // --yarn";
if (target) {
command += ` --target ${target}`;

View file

@ -5,7 +5,7 @@ import { ConfigHandler } from "core/config/ConfigHandler";
import { controlPlaneEnv, EXTENSION_NAME } from "core/control-plane/env";
import { Core } from "core/core";
import { FromCoreProtocol, ToCoreProtocol } from "core/protocol";
import { InProcessMessenger } from "core/util/messenger";
import { InProcessMessenger } from "core/protocol/messenger";
import { getConfigJsonPath, getConfigTsPath } from "core/util/paths";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";

View file

@ -17,7 +17,7 @@ import {
WEBVIEW_TO_CORE_PASS_THROUGH,
} from "core/protocol/passThrough";
import { getBasename } from "core/util";
import { InProcessMessenger, Message } from "core/util/messenger";
import { InProcessMessenger, Message } from "core/protocol/messenger";
import * as vscode from "vscode";
import { stripImages } from "core/util/messageContent";

View file

@ -4,12 +4,12 @@ import path from "path";
import { FromWebviewProtocol, ToWebviewProtocol } from "core/protocol";
import { WebviewMessengerResult } from "core/protocol/util";
import { extractMinimalStackTraceInfo } from "core/util/extractMinimalStackTraceInfo";
import { Message } from "core/util/messenger";
import { Message } from "core/protocol/messenger";
import { Telemetry } from "core/util/posthog";
import { v4 as uuidv4 } from "uuid";
import * as vscode from "vscode";
import { IMessenger } from "../../../core/util/messenger";
import { IMessenger } from "../../../core/protocol/messenger";
import { showFreeTrialLoginMessage } from "./util/messages";
import { getExtensionUri } from "./util/vscode";
@ -33,7 +33,8 @@ export async function showTutorial() {
}
export class VsCodeWebviewProtocol
implements IMessenger<FromWebviewProtocol, ToWebviewProtocol> {
implements IMessenger<FromWebviewProtocol, ToWebviewProtocol>
{
listeners = new Map<
keyof FromWebviewProtocol,
((message: Message) => any)[]
@ -127,7 +128,7 @@ export class VsCodeWebviewProtocol
message = message.split("\n").filter((l: string) => l !== "")[1];
try {
message = JSON.parse(message).message;
} catch { }
} catch {}
if (message.includes("exceeded")) {
message +=
" To keep using Continue, you can set up a local model or use your own API key.";
@ -181,7 +182,7 @@ export class VsCodeWebviewProtocol
});
}
constructor(private readonly reloadConfig: () => void) { }
constructor(private readonly reloadConfig: () => void) {}
invoke<T extends keyof FromWebviewProtocol>(
messageType: T,
data: FromWebviewProtocol[T][0],

31
gui/package-lock.json generated
View file

@ -7,6 +7,7 @@
"name": "gui",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-yaml": "^1.0.0",
"@headlessui/react": "^1.7.17",
"@heroicons/react": "^2.0.18",
"@reduxjs/toolkit": "^2.3.0",
@ -106,10 +107,10 @@
"@aws-sdk/client-sagemaker-runtime": "^3.621.0",
"@aws-sdk/credential-providers": "^3.620.1",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "../packages/config-yaml",
"@continuedev/fetch": "^1.0.3",
"@continuedev/config-yaml": "^1.0.0",
"@continuedev/fetch": "^1.0.4",
"@continuedev/llm-info": "^1.0.2",
"@continuedev/openai-adapters": "../packages/openai-adapters",
"@continuedev/openai-adapters": "^1.0.10",
"@modelcontextprotocol/sdk": "^1.0.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.0.2",
@ -544,6 +545,15 @@
"integrity": "sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw==",
"dev": true
},
"node_modules/@continuedev/config-yaml": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/@continuedev/config-yaml/-/config-yaml-1.0.0.tgz",
"integrity": "sha512-NwagzzpnPLbMC3delzFSjWiFv5fp8ReFjdMQF0ko0Xg+U0Myja90k/J7JWGegF/SZMABxc/OJchElJFr58TwGA==",
"dependencies": {
"yaml": "^2.6.1",
"zod": "^3.23.8"
}
},
"node_modules/@emotion/is-prop-valid": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/@emotion/is-prop-valid/-/is-prop-valid-1.3.1.tgz",
@ -14043,10 +14053,9 @@
"dev": true
},
"node_modules/yaml": {
"version": "2.5.1",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.5.1.tgz",
"integrity": "sha512-bLQOjaX/ADgQ20isPJRvF0iRUHIxVhYvr53Of7wGcWlO2jvtUlH5m87DsmulFVxRpNLOnI4tB6p/oh8D7kpn9Q==",
"dev": true,
"version": "2.6.1",
"resolved": "https://registry.npmjs.org/yaml/-/yaml-2.6.1.tgz",
"integrity": "sha512-7r0XPzioN/Q9kXBro/XPnA6kznR73DHq+GXh5ON7ZozRO6aMjbmiBuKste2wslTFkC5d1dw0GooOCepZXJ2SAg==",
"bin": {
"yaml": "bin.mjs"
},
@ -14066,6 +14075,14 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/zod": {
"version": "3.23.8",
"resolved": "https://registry.npmjs.org/zod/-/zod-3.23.8.tgz",
"integrity": "sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
},
"node_modules/zwitch": {
"version": "2.0.4",
"resolved": "https://registry.npmjs.org/zwitch/-/zwitch-2.0.4.tgz",

Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 88 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

After

Width:  |  Height:  |  Size: 32 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.6 KiB

After

Width:  |  Height:  |  Size: 24 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

After

Width:  |  Height:  |  Size: 40 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 22 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 181 KiB

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