Merge branch 'continuedev:main' into main

This commit is contained in:
Anoyi 2024-12-05 10:49:33 +08:00 • committed by GitHub
commit 5c21f2c281
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
63 changed files with 346 additions and 927 deletions

View file

@ -1,21 +1,27 @@
name: Write Core Utility Test
description: Generate unit tests for core utilities
---
Write jest tests for the provided code. Use best practices. Be clear and consise.
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/gui/src/components/mainInput/types.d.ts
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/util/fixtures.ts
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
The tests are to be put in a new file with the same filepath but with a .test.ts extension rather than a .ts extension
Avoid casting functions to the jest.Mock type. Instead, use `jest.mocked(fn)`
Use double quotes (or backticks if needed) for strings, and observe eslint import order standards

View file

@ -4,7 +4,7 @@ import path from "path";
import Parser from "web-tree-sitter";
import { Position } from "../../../..";
import { testIde } from "../../../../test/util/fixtures";
import { testIde } from "../../../../test/fixtures";
import { getAst, getTreePathAtCursor } from "../../../util/ast";
import { ImportDefinitionsService } from "../../ImportDefinitionsService";
import { RootPathContextService } from "../RootPathContextService";

View file

@ -1,4 +1,4 @@
import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir";
import { setUpTestDir, tearDownTestDir } from "../../../test/testDir";
import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases";
import {

View file

@ -2,7 +2,7 @@ import fs from "node:fs";
import path from "node:path";
import Mock from "../../../llm/llms/Mock";
import { testConfigHandler, testIde } from "../../../test/util/fixtures";
import { testConfigHandler, testIde } from "../../../test/fixtures";
import { CompletionProvider } from "../../CompletionProvider";
import { AutocompleteInput } from "../../util/types";

View file

@ -1,8 +1,8 @@
import fs from "node:fs";
import path from "node:path";
import { testConfigHandler } from "../test/util/fixtures";
import { TEST_DIR } from "../test/util/testDir";
import { testConfigHandler } from "../test/fixtures";
import { TEST_DIR } from "../test/testDir";
import { getConfigTsPath } from "../util/paths";
import { defaultConfig } from "./default";

View file

@ -4,12 +4,12 @@ import {
ContextProviderExtras,
ContextProviderWithParams,
IContextProvider,
} from "../../..";
import { ConfigHandler } from "../../../config/ConfigHandler";
import { contextProviderClassFromName } from "../../../context/providers";
import { ControlPlaneClient } from "../../../control-plane/client";
import FileSystemIde from "../../../util/filesystem";
import { TEST_DIR } from "../../util/testDir";
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { contextProviderClassFromName } from ".";
import { ControlPlaneClient } from "../../control-plane/client";
import FileSystemIde from "../../util/filesystem";
import { TEST_DIR } from "../../test/testDir";
const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
{ name: "diff", params: {} },

47
core/index.d.ts vendored
View file

@ -195,10 +195,12 @@ export interface CustomContextProvider {
description?: string;
renderInlineAs?: string;
type?: ContextProviderType;
getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]>;
loadSubmenuItems?: (
args: LoadSubmenuItemsArgs,
) => Promise<ContextSubmenuItem[]>;
@ -275,10 +277,12 @@ export interface Range {
start: Position;
end: Position;
}
export interface Position {
line: number;
character: number;
}
export interface FileEdit {
filepath: string;
range: Range;
@ -479,6 +483,7 @@ export interface LLMOptions {
// IBM watsonx Options
deploymentId?: string;
}
type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
Exclude<keyof T, Keys>
@ -535,6 +540,7 @@ export class Thread {
}
export type IdeType = "vscode" | "jetbrains";
export interface IdeInfo {
ideType: IdeType;
name: string;
@ -570,42 +576,68 @@ export interface IdeSettings {
export interface IDE {
getIdeInfo(): Promise<IdeInfo>;
getIdeSettings(): Promise<IdeSettings>;
getDiff(includeUnstaged: boolean): Promise<string[]>;
getClipboardContent(): Promise<{ text: string; copiedAt: string }>;
isTelemetryEnabled(): Promise<boolean>;
getUniqueId(): Promise<string>;
getTerminalContents(): Promise<string>;
getDebugLocals(threadIndex: number): Promise<string>;
getTopLevelCallStackSources(
threadIndex: number,
stackDepth: number,
): Promise<string[]>;
getAvailableThreads(): Promise<Thread[]>;
listFolders(): Promise<string[]>;
getWorkspaceDirs(): Promise<string[]>;
getWorkspaceConfigs(): Promise<ContinueRcJson[]>;
fileExists(filepath: string): Promise<boolean>;
writeFile(path: string, contents: string): Promise<void>;
showVirtualFile(title: string, contents: string): Promise<void>;
getContinueDir(): Promise<string>;
openFile(path: string): Promise<void>;
openUrl(url: string): Promise<void>;
runCommand(command: string): Promise<void>;
saveFile(filepath: string): Promise<void>;
readFile(filepath: string): Promise<string>;
readRangeInFile(filepath: string, range: Range): Promise<string>;
showLines(
filepath: string,
startLine: number,
endLine: number,
): Promise<void>;
showDiff(
filepath: string,
newContents: string,
stepIndex: number,
): Promise<void>;
getOpenFiles(): Promise<string[]>;
getCurrentFile(): Promise<
| undefined
| {
@ -614,21 +646,33 @@ export interface IDE {
contents: string;
}
>;
getPinnedFiles(): Promise<string[]>;
getSearchResults(query: string): Promise<string>;
subprocess(command: string, cwd?: string): Promise<[string, string]>;
getProblems(filepath?: string | undefined): Promise<Problem[]>;
getBranch(dir: string): Promise<string>;
getTags(artifactId: string): Promise<IndexTag[]>;
getRepoName(dir: string): Promise<string | undefined>;
showToast(
type: ToastType,
message: string,
...otherParams: any[]
): Promise<any>;
getGitRootPath(dir: string): Promise<string | undefined>;
listDir(dir: string): Promise<[string, FileType][]>;
getLastModified(files: string[]): Promise<{ [path: string]: number }>;
getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined>;
// LSP
@ -636,6 +680,7 @@ export interface IDE {
// Callbacks
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void;
pathSep(): Promise<string>;
}
@ -1035,6 +1080,7 @@ export interface EmbeddingsProvider {
id: string;
providerName: EmbeddingsProviderName;
maxChunkSize: number;
embed(chunks: string[]): Promise<number[][]>;
}
@ -1053,6 +1099,7 @@ export interface RerankerDescription {
export interface Reranker {
name: string;
rerank(query: string, chunks: Chunk[]): Promise<number[]>;
}

View file

@ -1,11 +1,11 @@
import { jest } from "@jest/globals";
import { testIde } from "../test/util/fixtures";
import { testIde } from "../test/fixtures";
import {
insertMockChunks,
mockPathAndCacheKey,
updateIndexAndAwaitGenerator,
} from "../test/util/indexing";
} from "./test/indexing";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";

View file

@ -5,13 +5,13 @@ import path from "node:path";
import { jest } from "@jest/globals";
import { ContinueServerClient } from "../continueServer/stubs/client.js";
import { testConfigHandler, testIde } from "../test/util/fixtures.js";
import { testConfigHandler, testIde } from "../test/fixtures.js";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
TEST_DIR,
} from "../test/util/testDir.js";
} from "../test/testDir.js";
import { getIndexSqlitePath } from "../util/paths.js";
import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
@ -76,8 +76,8 @@ describe("CodebaseIndexer", () => {
setUpTestDir();
execSync("git init", { cwd: TEST_DIR });
execSync("git config user.email \"test@example.com\"", { cwd: TEST_DIR });
execSync("git config user.name \"Test\"", { cwd: TEST_DIR });
execSync('git config user.email "test@example.com"', { cwd: TEST_DIR });
execSync('git config user.name "Test"', { cwd: TEST_DIR });
});
afterAll(async () => {
@ -100,9 +100,7 @@ describe("CodebaseIndexer", () => {
async function refreshIndexFiles(files: string[]) {
const updates = [];
for await (const update of codebaseIndexer.refreshFiles(
files,
)) {
for await (const update of codebaseIndexer.refreshFiles(files)) {
updates.push(update);
}
return updates;

View file

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

View file

@ -1,13 +1,13 @@
import { jest } from "@jest/globals";
import lance from "vectordb";
import { testConfigHandler, testIde } from "../test/util/fixtures";
import { testConfigHandler, testIde } from "../test/fixtures";
import {
mockPathAndCacheKey,
mockTag,
testContinueServerClient,
updateIndexAndAwaitGenerator,
} from "../test/util/indexing";
} from "./test/indexing";
import { getLanceDbPath } from "../util/paths";
import { LanceDbIndex } from "./LanceDbIndex";

View file

@ -1,14 +1,14 @@
import { jest } from "@jest/globals";
import { testIde } from "../../test/util/fixtures";
import { testIde } from "../../test/fixtures";
import {
mockFileContents,
mockFilename,
mockPathAndCacheKey,
testContinueServerClient,
updateIndexAndAwaitGenerator,
} from "../../test/util/indexing";
import { addToTestDir } from "../../test/util/testDir";
} from "../test/indexing";
import { addToTestDir } from "../../test/testDir";
import { DatabaseConnection, SqliteDb } from "../refreshIndex";
import { IndexResultType } from "../types";

View file

@ -3,7 +3,7 @@ import os from "os";
import { jest } from "@jest/globals";
import { ContinueConfig } from "../..";
import { testConfigHandler } from "../../test/util/fixtures";
import { testConfigHandler } from "../../test/fixtures";
import FileSystemIde from "../../util/filesystem";
import DocsCrawler, { ChromiumInstaller, type PageData } from "./DocsCrawler";

View file

@ -2,19 +2,12 @@ import { jest } from "@jest/globals";
import { IndexTag } from "../..";
import { IContinueServerClient } from "../../continueServer/interface";
import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex";
import { tagToString } from "../../indexing/refreshIndex";
import {
CodebaseIndex,
PathAndCacheKey,
RefreshIndexResults,
} from "../../indexing/types";
import { testIde } from "./fixtures";
import { addToTestDir, TEST_DIR } from "./testDir";
import { ChunkCodebaseIndex } from "../chunk/ChunkCodebaseIndex";
import { tagToString } from "../refreshIndex";
import { CodebaseIndex, PathAndCacheKey, RefreshIndexResults } from "../types";
import { testIde } from "../../test/fixtures";
import { addToTestDir, TEST_DIR } from "../../test/testDir";
export const mockFilename = "test.py";
export const mockPathAndCacheKey = {

View file

@ -6,7 +6,7 @@ import {
setUpTestDir,
tearDownTestDir,
addToTestDir,
} from "../test/util/testDir";
} from "../test/testDir";
import FileSystemIde from "../util/filesystem";
const ide = new FileSystemIde(TEST_DIR);

View file

@ -8,8 +8,8 @@ export default {
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",
"^uuid$": "uuid", // https://stackoverflow.com/a/73626360
'^@azure/(.*)$': '<rootDir>/node_modules/@azure/$1',
'^mssql$': '<rootDir>/node_modules/mssql'
"^@azure/(.*)$": "<rootDir>/node_modules/@azure/$1",
"^mssql$": "<rootDir>/node_modules/mssql",
},
extensionsToTreatAsEsm: [".ts"],
preset: "ts-jest/presets/default-esm",
@ -19,6 +19,8 @@ export default {
__dirname: path.dirname(fileURLToPath(import.meta.url)),
__filename: path.resolve(fileURLToPath(import.meta.url)),
},
globalSetup: "<rootDir>/jest.global-setup.ts",
setupFilesAfterEnv: ["<rootDir>/jest.setup-after-env.ts"],
maxWorkers: 1 // equivalent to CLI --runInBand
};

View file

@ -1,4 +1,4 @@
// https://github.com/mswjs/msw/issues/1576#issuecomment-1482643055
import fs from "fs";
import { TextDecoder, TextEncoder } from "util";
import { jest } from "@jest/globals";
@ -10,23 +10,21 @@ if (process.env.DEBUG === "jest") {
const globalThis = global as any;
globalThis.jest = jest;
// https://github.com/mswjs/msw/issues/1576#issuecomment-1482643055
globalThis.fetch = fetch;
globalThis.Request = Request;
globalThis.Response = Response;
globalThis.TextEncoder = TextEncoder;
globalThis.TextDecoder = TextDecoder;
// Trying to delete this when for some reason SQLite is still in use causes tests to fail
// globalThis.beforeAll(() => {
// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts`
// TODO - currently causing tests to fail because sqlite is still running for some reason
// const clearTestDirectory = () => {
// if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) {
// fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true });
// }
// });
// };
// globalThis.afterAll(() => {
// // We can ignore TS warnings here since we set this explicitly in `./jest.global-setup.ts`
// if (fs.existsSync(process.env.CONTINUE_GLOBAL_DIR!)) {
// fs.rmSync(process.env.CONTINUE_GLOBAL_DIR!, { recursive: true });
// }
// });
// globalThis.beforeAll(clearTestDirectory);
// globalThis.afterAll(clearTestDirectory);

View file

@ -1,10 +1,8 @@
import * as dotenv from "dotenv";
import { CompletionOptions } from "../";
import { BaseLLM } from "../llm/";
import OpenAI from "../llm/llms/OpenAI";
// jest.setTimeout(100_000);
import { CompletionOptions } from "..";
import { BaseLLM } from ".";
import OpenAI from "./llms/OpenAI";
dotenv.config();

View file

@ -7882,9 +7882,9 @@
}
},
"node_modules/dotenv": {
"version": "16.4.5",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.5.tgz",
"integrity": "sha512-ZmdL2rui+eB2YwhsWzjInR8LldtZHGDoQ1ugH85ppHKwpUHL7j7rN0Ti9NCnGiQbhaZ11FpR+7ao1dNsmduNUg==",
"version": "16.4.7",
"resolved": "https://registry.npmjs.org/dotenv/-/dotenv-16.4.7.tgz",
"integrity": "sha512-47qPchRCykZC03FhkYAhrvwU4xDBFIj1QPqaarj6mdM/hgUzfPHcpkHJOn3mJAufFeeAxAzeGsr5X0M4k6fLZQ==",
"engines": {
"node": ">=12"
},

View file

@ -3,7 +3,8 @@
"version": "1.0.13",
"description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js",
"scripts": {
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand",
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest",
"test:coverage": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --coverage && open ./coverage/lcov-report/index.html",
"tsc:check": "tsc -p ./ --noEmit",
"build:npm": "tsc -p ./tsconfig.npm.json",
"lint": "eslint . --ext ts",

View file

@ -43,7 +43,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
insertAtCursor: [{ text: string }, void];
copyText: [{ text: string }, void];
"jetbrains/editorInsetHeight": [{ height: number }, void];
"jetbrains/isOSREnabled": [undefined, void];
"jetbrains/isOSREnabled": [undefined, boolean];
"vscode/openMoveRightMarkdown": [undefined, void];
setGitHubAuthToken: [{ token: string }, void];
acceptDiff: [{ filepath: string; streamId?: string }, void];

View file

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

View file

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

View file

@ -1,6 +1,6 @@
import { ConfigHandler } from "../../config/ConfigHandler";
import { ControlPlaneClient } from "../../control-plane/client";
import FileSystemIde from "../../util/filesystem";
import { ConfigHandler } from "../config/ConfigHandler";
import { ControlPlaneClient } from "../control-plane/client";
import FileSystemIde from "../util/filesystem";
import { TEST_DIR } from "./testDir";

View file

@ -3,7 +3,7 @@ import os from "os";
import path from "path";
// Want this outside of the git repository so we can change branches in tests
export const TEST_DIR = path.join(os.tmpdir(), "testDir");
export const TEST_DIR = path.join(os.tmpdir(), "testWorkspaceDir");
export function setUpTestDir() {
if (fs.existsSync(TEST_DIR)) {

View file

@ -1,76 +0,0 @@
// File generated by Continue
import { dedentAndGetCommonWhitespace } from "../../util";
describe("dedentAndGetCommonWhitespace", () => {
let originalString: string;
beforeEach(() => {
// Setup any global variables or states if needed
originalString = " line1\n line2\n line3";
});
afterEach(() => {
// Tear down any changes to global variables or states if needed
originalString = "";
});
test("should dedent and return common whitespace for a simple case", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", " "]);
});
test("should handle empty string", () => {
const input = "";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["", ""]);
});
test("should handle string with only whitespace", () => {
const input = " ";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["", ""]);
});
test("should handle string with mixed whitespace and content", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([" line1\nline2\n line3", " "]);
});
test("should handle string with no common leading whitespace", () => {
const input = "line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([input, ""]);
});
test("should handle string with empty lines", () => {
const input = " line1\n\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\n\nline3", " "]);
});
test("should handle string with only empty lines", () => {
const input = "\n\n";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["\n\n", ""]);
});
test("should handle string with tabs as whitespace", () => {
const input = "\tline1\n\tline2\n\tline3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", "\t"]);
});
test("should handle string with mixed tabs and spaces", () => {
const input = "\t line1\n\t line2\n\t line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", "\t "]);
});
test("should handle string with different leading whitespace lengths", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([" line1\nline2\n line3", " "]);
});
});

View file

@ -1,51 +0,0 @@
// File generated by Continue
import { getLastNPathParts } from "../../util";
describe("getLastNPathParts", () => {
const SEP_REGEX = /[\\/]+/;
beforeAll(() => {
// Setup code if needed
});
afterAll(() => {
// Teardown code if needed
});
test("returns the last N parts of a filepath with forward slashes", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt");
});
test("returns the last N parts of a filepath with backward slashes", () => {
const filepath = "C:\\home\\user\\documents\\project\\file.txt";
expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
});
test("returns the last part if N is 1", () => {
const filepath = "/home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 1)).toBe("file.txt");
});
test("returns the entire path if N is greater than the number of parts", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 10)).toBe(
"home/user/documents/project/file.txt",
);
});
test("returns an empty string if N is 0", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 0)).toBe("");
});
test("handles paths with mixed forward and backward slashes", () => {
const filepath = "home\\user/documents\\project/file.txt";
expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
});
test("handles edge case with empty filepath", () => {
const filepath = "";
expect(getLastNPathParts(filepath, 2)).toBe("");
});
});

View file

@ -1,40 +0,0 @@
// This file is generated by Continue
import { longestCommonSubsequence } from "../../util/lcs";
describe("longestCommonSubsequence", () => {
beforeAll(() => {
// Setup if needed
});
afterAll(() => {
// Teardown if needed
});
test("should return the longest common subsequence for non-empty strings", () => {
expect(longestCommonSubsequence("abcde", "ace")).toBe("ace");
expect(longestCommonSubsequence("abc", "abc")).toBe("abc");
expect(longestCommonSubsequence("abc", "def")).toBe("");
});
test("should handle cases where one or both strings are empty", () => {
expect(longestCommonSubsequence("", "abc")).toBe("");
expect(longestCommonSubsequence("abc", "")).toBe("");
expect(longestCommonSubsequence("", "")).toBe("");
});
test("should handle cases with no common subsequence", () => {
expect(longestCommonSubsequence("abc", "def")).toBe("");
expect(longestCommonSubsequence("xyz", "abc")).toBe("");
});
test("should handle cases with special characters", () => {
expect(longestCommonSubsequence("a!@#b$c", "!@#$")).toBe("!@#$");
expect(longestCommonSubsequence("a!@#b$c", "xyz")).toBe("");
});
test("should handle long strings efficiently", () => {
const str1 = "a".repeat(1000) + "b".repeat(1000);
const str2 = "a".repeat(1000) + "c".repeat(1000);
expect(longestCommonSubsequence(str1, str2)).toBe("a".repeat(1000));
});
});

View file

@ -1,100 +0,0 @@
// File generated by Continue
import { mergeJson } from "../../util/merge";
describe("mergeJson", () => {
it("should merge two simple JSON objects", () => {
const first = { a: 1, b: 2 };
const second = { b: 3, c: 4 };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1, b: 3, c: 4 });
});
it("should overwrite values when mergeBehavior is \"overwrite\"", () => {
const first = { a: 1, b: 2 };
const second = { b: 3, c: 4 };
const result = mergeJson(first, second, "overwrite");
expect(result).toEqual({ a: 1, b: 3, c: 4 });
});
it("should merge nested objects", () => {
const first = { a: { b: 1 } };
const second = { a: { c: 2 } };
const result = mergeJson(first, second);
expect(result).toEqual({ a: { b: 1, c: 2 } });
});
it("should merge arrays without mergeKeys", () => {
const first = { a: [1, 2] };
const second = { a: [3, 4] };
const result = mergeJson(first, second);
expect(result).toEqual({ a: [1, 2, 3, 4] });
});
it("should merge arrays with mergeKeys", () => {
const first = {
a: [
{ id: 1, value: "first" },
{ id: 2, value: "second" },
],
};
const second = {
a: [
{ id: 2, value: "updated" },
{ id: 3, value: "third" },
],
};
const mergeKeys = {
a: (item1: any, item2: any) => item1.id === item2.id,
};
const result = mergeJson(first, second, undefined, mergeKeys);
expect(result).toEqual({
a: [
{ id: 1, value: "first" },
{ id: 2, value: "updated" },
{ id: 3, value: "third" },
],
});
});
it("should handle non-object values correctly", () => {
const first = { a: 1, b: "string", c: true };
const second = { a: 2, b: "new string", c: false };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 2, b: "new string", c: false });
});
it("should handle null and undefined values correctly", () => {
const first = { a: 1, b: null };
const second = { b: 2, c: undefined };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1, b: 2, c: undefined });
});
it("should handle empty objects", () => {
const first = {};
const second = { a: 1 };
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1 });
});
it("should handle empty second object", () => {
const first = { a: 1 };
const second = {};
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1 });
});
it("should handle errors gracefully", () => {
const first = { a: 1 };
const second = { b: () => {} }; // Functions are not serializable in JSON
const result = mergeJson(first, second);
expect(result).toEqual({ a: 1, b: expect.any(Function) });
});
it("should merge deeply nested objects", () => {
const first = { a: { b: { c: 1 } } };
const second = { a: { b: { d: 2 } } };
const result = mergeJson(first, second);
expect(result).toEqual({ a: { b: { c: 1, d: 2 } } });
});
});

View file

@ -1,105 +0,0 @@
// This file is generated by Continue
import { getRangeInString } from "../../../util/ranges";
describe.skip("getRangeInString", () => {
let content: string;
beforeEach(() => {
content = `Line 1
Line 2
Line 3
Line 4
Line 5`;
});
afterEach(() => {
content = "";
});
test("should return substring within the same line", () => {
const range = {
start: { line: 1, character: 0 },
end: { line: 1, character: 4 },
};
expect(getRangeInString(content, range)).toBe("Line");
});
test("should return substring spanning multiple lines", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 3, character: 3 },
};
const expected = `ne 2
Line 3
Line 4`;
expect(getRangeInString(content, range)).toBe(expected);
});
test("should handle range that starts and ends at the same character", () => {
const range = {
start: { line: 2, character: 0 },
end: { line: 2, character: 0 },
};
expect(getRangeInString(content, range)).toBe("L");
});
test("should handle range that spans entire content", () => {
const range = {
start: { line: 0, character: 0 },
end: { line: 4, character: 5 },
};
expect(getRangeInString(content, range)).toBe(content);
});
test("should handle range that spans to the end of the last line", () => {
const range = {
start: { line: 3, character: 2 },
end: { line: 4, character: 5 },
};
const expected = `ne 4
Line 5`;
expect(getRangeInString(content, range)).toBe(expected);
});
test("should handle empty content", () => {
content = "";
const range = {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle invalid range (start line > end line)", () => {
const range = {
start: { line: 3, character: 0 },
end: { line: 2, character: 0 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle invalid range (start character > end character on same line)", () => {
const range = {
start: { line: 1, character: 5 },
end: { line: 1, character: 2 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle range that starts and ends at the same line but different characters", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 1, character: 6 },
};
expect(getRangeInString(content, range)).toBe("ne 2");
});
test("should handle range that starts and ends at the same line and same characters", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 1, character: 2 },
};
expect(getRangeInString(content, range)).toBe("n");
});
});

View file

@ -1,123 +0,0 @@
// This file is generated by Continue
import { intersection } from "../../../util/ranges";
interface Position {
line: number;
character: number;
}
interface Range {
start: Position;
end: Position;
}
describe("intersection", () => {
let rangeA: Range;
let rangeB: Range;
beforeEach(() => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 3, character: 5 },
};
rangeB = {
start: { line: 2, character: 2 },
end: { line: 4, character: 0 },
};
});
test("returns correct intersection for overlapping ranges", () => {
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 2 },
end: { line: 3, character: 5 },
});
});
test("returns null for non-overlapping ranges", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 2, character: 0 },
};
rangeB = {
start: { line: 3, character: 0 },
end: { line: 4, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toBeNull();
});
// TODO
test.skip("returns correct intersection for single line overlap", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 5 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 2, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 3 },
end: { line: 1, character: 5 },
});
});
test("returns null for single line non-overlapping ranges", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 2 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 1, character: 5 },
};
const result = intersection(rangeA, rangeB);
expect(result).toBeNull();
});
test("returns correct intersection when one range is fully within another", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 4, character: 5 },
};
rangeB = {
start: { line: 2, character: 2 },
end: { line: 3, character: 3 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 2 },
end: { line: 3, character: 3 },
});
});
test("returns correct intersection when ranges touch at the edge", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 2, character: 0 },
};
rangeB = {
start: { line: 2, character: 0 },
end: { line: 3, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 0 },
end: { line: 2, character: 0 },
});
});
});

View file

@ -1,70 +0,0 @@
import { maxPosition, minPosition } from "../../../util/ranges";
// This file is generated by Continue
interface Position {
line: number;
character: number;
}
describe("Position comparison functions", () => {
let pos1: Position;
let pos2: Position;
let pos3: Position;
let pos4: Position;
beforeAll(() => {
// Setup: Initializing positions
pos1 = { line: 1, character: 5 };
pos2 = { line: 2, character: 3 };
pos3 = { line: 1, character: 7 };
pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality
});
describe("maxPosition", () => {
it("should return the position with the greater line number", () => {
expect(maxPosition(pos1, pos2)).toEqual(pos2);
});
it("should return the position with the greater character number when lines are equal", () => {
expect(maxPosition(pos1, pos3)).toEqual(pos3);
});
it("should return the first position when both positions are equal", () => {
expect(maxPosition(pos2, pos4)).toEqual(pos2);
});
it("should handle positions with negative line numbers", () => {
const posNegative = { line: -1, character: 0 };
expect(maxPosition(posNegative, pos1)).toEqual(pos1);
});
it("should handle positions with negative character numbers", () => {
const posNegativeChar = { line: 1, character: -1 };
expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1);
});
});
describe("minPosition", () => {
it("should return the position with the lesser line number", () => {
expect(minPosition(pos1, pos2)).toEqual(pos1);
});
it("should return the position with the lesser character number when lines are equal", () => {
expect(minPosition(pos1, pos3)).toEqual(pos1);
});
it("should return the first position when both positions are equal", () => {
expect(minPosition(pos2, pos4)).toEqual(pos2);
});
it("should handle positions with negative line numbers", () => {
const posNegative = { line: -1, character: 0 };
expect(minPosition(posNegative, pos1)).toEqual(posNegative);
});
it("should handle positions with negative character numbers", () => {
const posNegativeChar = { line: 1, character: -1 };
expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar);
});
});
});

View file

@ -1,92 +0,0 @@
import { union } from "../../../util/ranges";
// This file is generated by Continue
interface Position {
line: number;
character: number;
}
interface Range {
start: Position;
end: Position;
}
describe("union", () => {
let rangeA: Range;
let rangeB: Range;
beforeEach(() => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 3, character: 5 },
};
rangeB = {
start: { line: 2, character: 3 },
end: { line: 4, character: 2 },
};
});
test("should return the union of two overlapping ranges", () => {
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 4, character: 2 },
});
});
test("should return the union when ranges are identical", () => {
const result = union(rangeA, rangeA);
expect(result).toEqual(rangeA);
});
test("should return the union when ranges do not overlap but are adjacent", () => {
rangeB = {
start: { line: 3, character: 5 },
end: { line: 4, character: 2 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 4, character: 2 },
});
});
test("should return the union when one range is completely within the other", () => {
rangeB = {
start: { line: 2, character: 1 },
end: { line: 2, character: 4 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual(rangeA);
});
test("should return the union when ranges do not overlap and are not adjacent", () => {
rangeB = {
start: { line: 4, character: 3 },
end: { line: 5, character: 1 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 5, character: 1 },
});
});
// TODO
test.skip("should handle edge case where start and end lines are the same", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 5 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 1, character: 7 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 1, character: 7 },
});
});
});

View file

@ -1,24 +1,10 @@
import { ILLM, LLMFullCompletionOptions } from "..";
import { removeQuotesAndEscapes } from ".";
import { removeQuotesAndEscapes, removeCodeBlocksAndTrim } from ".";
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
import type { IMessenger } from "./messenger";
/**
* Removes code blocks from a message.
*
* Return modified message text.
*/
function removeCodeBlocksAndTrim(msgText: string): string {
const codeBlockRegex = /```[\s\S]*?```/g;
// Remove code blocks from the message text
const textWithoutCodeBlocks = msgText.replace(codeBlockRegex, "");
return textWithoutCodeBlocks.trim();
}
export class ChatDescriber {
static prompt: string | undefined =
"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";

View file

@ -1,8 +1,8 @@
import { v4 as uuidv4 } from "uuid";
import { Session } from "../..";
import historyManager from "../../util/history";
import { getSessionFilePath } from "../../util/paths";
import { Session } from "..";
import historyManager from "./history";
import { getSessionFilePath } from "./paths";
const sessionId = uuidv4();
const testSession: Session = {

View file

@ -328,3 +328,17 @@ export function dedent(strings: TemplateStringsArray, ...values: any[]) {
return lines.join("\n");
}
/**
* Removes code blocks from a message.
*
* Return modified message text.
*/
export function removeCodeBlocksAndTrim(text: string): string {
const codeBlockRegex = /```[\s\S]*?```/g;
// Remove code blocks from the message text
const textWithoutCodeBlocks = text.replace(codeBlockRegex, "");
return textWithoutCodeBlocks.trim();
}

View file

@ -1,6 +1,8 @@
import { exec, ChildProcess } from "child_process";
import os from "node:os";
import { removeCodeBlocksAndTrim } from ".";
import type { IMessenger } from "./messenger";
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
@ -8,27 +10,13 @@ import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
// a zombie after executing .kill()
const ttsKillTimeout: number = 5000;
/**
* Removes code blocks from a message.
*
* Return modified message text.
*/
function removeCodeBlocks(msgText: string): string {
const codeBlockRegex = /```[\s\S]*?```/g;
// Remove code blocks from the message text
const textWithoutCodeBlocks = msgText.replace(codeBlockRegex, "");
return textWithoutCodeBlocks.trim();
}
/**
* Cleans a message text to safely be used in 'exec' context on host.
*
* Return modified message text.
*/
function sanitizeMessageForTTS(message: string): string {
message = removeCodeBlocks(message);
export function sanitizeMessageForTTS(message: string): string {
message = removeCodeBlocksAndTrim(message);
// Remove or replace problematic characters
message = message

View file

@ -2,7 +2,7 @@ interface APIError extends Error {
response?: Response;
}
const RETRY_AFTER_HEADER = "Retry-After";
export const RETRY_AFTER_HEADER = "Retry-After";
const withExponentialBackoff = async <T>(
apiCall: () => Promise<T>,
@ -18,8 +18,12 @@ const withExponentialBackoff = async <T>(
(error as APIError).response?.status === 429 &&
attempt < maxRetries - 1
) {
const retryAfter = (error as APIError).response?.headers.get(RETRY_AFTER_HEADER);
const delay = retryAfter ? parseInt(retryAfter, 10) : initialDelaySeconds * 2 ** attempt;
const retryAfter = (error as APIError).response?.headers.get(
RETRY_AFTER_HEADER,
);
const delay = retryAfter
? parseInt(retryAfter, 10)
: initialDelaySeconds * 2 ** attempt;
console.log(
`Hit rate limit. Retrying in ${delay} seconds (attempt ${
attempt + 1

View file

@ -138,7 +138,7 @@ class ContinueBrowser(val project: Project, url: String) {
}
"jetbrains/isOSREnabled" -> {
sendToWebview( "jetbrains/isOSREnabled", isOSREnabled)
respond(isOSREnabled)
}
"onLoad" -> {
@ -268,7 +268,9 @@ class ContinueBrowser(val project: Project, url: String) {
val jsCode = buildJavaScript(jsonData)
try {
this.browser.executeJavaScriptAsync(jsCode)
this.browser.executeJavaScriptAsync(jsCode).onError {
println("Failed to execute jsCode error: ${it.message}")
}
} catch (error: IllegalStateException) {
println("Webview not initialized yet $error")
}

View file

@ -112,7 +112,7 @@
"comment-json": "^4.2.3",
"dbinfoz": "^0.14.0",
"diff": "^7.0.0",
"dotenv": "^16.4.5",
"dotenv": "^16.4.7",
"fastest-levenshtein": "^1.0.16",
"follow-redirects": "^1.15.5",
"google-auth-library": "^9.14.2",

View file

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

2
gui/package-lock.json generated
View file

@ -121,7 +121,7 @@
"comment-json": "^4.2.3",
"dbinfoz": "^0.14.0",
"diff": "^7.0.0",
"dotenv": "^16.4.5",
"dotenv": "^16.4.7",
"fastest-levenshtein": "^1.0.16",
"follow-redirects": "^1.15.5",
"google-auth-library": "^9.14.2",

View file

@ -5,7 +5,7 @@ import CodeToEditListItem from "./CodeToEditListItem";
import type { CodeToEdit, RangeInFileWithContents } from "core";
import AddFileButton from "./AddFileButton";
import AddFileCombobox from "./AddFileCombobox";
import { XMarkIcon } from "@heroicons/react/24/outline";
import { PlusIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { useAppSelector } from "../../redux/hooks";
import {
addCodeToEdit,
@ -61,7 +61,7 @@ export default function CodeToEditCard() {
<AddFileButton onClick={() => setShowAddFileCombobox(true)} />
</div>
{codeToEdit.length > 0 && (
{codeToEdit.length > 0 ? (
<ul className="no-scrollbar my-0 mb-1.5 max-h-[50vh] list-outside list-none overflow-y-auto pl-0">
{codeToEdit.map((code, i) => (
<CodeToEditListItem
@ -72,6 +72,16 @@ export default function CodeToEditCard() {
/>
))}
</ul>
) : (
!showAddFileCombobox && (
<div
className="text-lightgray hover:bg-lightgray hover:text-vsc-foreground -mt-0.5 flex cursor-pointer items-center justify-center gap-1 rounded py-1 text-center text-xs transition-colors hover:bg-opacity-20"
onClick={() => setShowAddFileCombobox(true)}
>
<PlusIcon className="h-3.5 w-3.5" />
<span>Add a file to get started</span>
</div>
)
)}
{showAddFileCombobox && (

View file

@ -0,0 +1,20 @@
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
export interface PageHeaderProps {
onClick: () => void;
title: string;
}
export default function PageHeader({ onClick, title }: PageHeaderProps) {
return (
<div className="bg-vsc-background sticky top-0 m-0 flex items-center border-0 border-b border-solid border-b-zinc-700 bg-inherit p-0">
<div
className="cursor-pointer transition-colors duration-200 hover:text-zinc-100"
onClick={onClick}
>
<ArrowLeftIcon className="ml-3 inline-block h-3 w-3" />
<span className="m-2 inline-block text-base font-bold">{title}</span>
</div>
</div>
);
}

View file

@ -8,9 +8,11 @@ import { selectIsSingleRangeEditOrInsertion } from "../../redux/slices/sessionSl
export interface AcceptRejectAllButtonsProps {
pendingApplyStates: ApplyState[];
onAcceptOrReject?: () => void;
onAcceptOrReject?: (outcome: AcceptOrRejectOutcome) => void;
}
export type AcceptOrRejectOutcome = "acceptDiff" | "rejectDiff";
export default function AcceptRejectAllButtons({
pendingApplyStates,
onAcceptOrReject,
@ -18,7 +20,7 @@ export default function AcceptRejectAllButtons({
const ideMessenger = useContext(IdeMessengerContext);
const isSingleRangeEdit = useAppSelector(selectIsSingleRangeEditOrInsertion);
async function handleAcceptOrReject(status: "acceptDiff" | "rejectDiff") {
async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
for (const { filepath, streamId } of pendingApplyStates) {
ideMessenger.post(status, {
filepath,
@ -27,9 +29,10 @@ export default function AcceptRejectAllButtons({
}
if (onAcceptOrReject) {
onAcceptOrReject();
onAcceptOrReject(status);
}
}
return (
<div className="flex justify-center gap-2 border-b border-gray-200/25 p-1 px-3">
<button

View file

@ -58,12 +58,14 @@ export default function EditActions({ index, item }: EditActionsProps) {
{hasPendingApplies && (
<AcceptRejectAllButtons
pendingApplyStates={pendingApplyStates}
onAcceptOrReject={() => {
loadLastSession().catch((e) =>
console.error(`Failed to load last session: ${e}`),
);
onAcceptOrReject={(outcome) => {
if (outcome === "acceptDiff") {
loadLastSession().catch((e) =>
console.error(`Failed to load last session: ${e}`),
);
dispatch(exitEditMode());
dispatch(exitEditMode());
}
}}
/>
)}

View file

@ -1,6 +1,6 @@
import { AtSymbolIcon, PhotoIcon } from "@heroicons/react/24/outline";
import { InputModifiers } from "core";
import { modelSupportsImages } from "core/llm/autodetect";
import { modelSupportsImages, modelSupportsTools } from "core/llm/autodetect";
import { useRef } from "react";
import styled from "styled-components";
import {
@ -20,8 +20,14 @@ import { ToolTip } from "../gui/Tooltip";
import ModelSelect from "../modelSelection/ModelSelect";
import HoverItem from "./InputToolbar/HoverItem";
import ToggleToolsButton from "./InputToolbar/ToggleToolsButton";
import { useAppSelector } from "../../redux/hooks";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { selectDefaultModel } from "../../redux/slices/configSlice";
import {
selectHasCodeToEdit,
selectIsInEditMode,
} from "../../redux/slices/sessionSlice";
import { exitEditMode } from "../../redux/thunks";
import useHistory from "../../hooks/useHistory";
const StyledDiv = styled.div<{ isHidden?: boolean }>`
padding-top: 4px;
@ -49,6 +55,7 @@ const EnterButton = styled.button`
border-radius: ${defaultBorderRadius};
color: ${vscForeground};
cursor: pointer;
:disabled {
cursor: wait;
}
@ -76,9 +83,19 @@ interface InputToolbarProps {
}
function InputToolbar(props: InputToolbarProps) {
const dispatch = useAppDispatch();
const fileInputRef = useRef<HTMLInputElement | null>(null);
const defaultModel = useAppSelector(selectDefaultModel);
const useActiveFile = useAppSelector(selectUseActiveFile);
const isInEditMode = useAppSelector(selectIsInEditMode);
const hasCodeToEdit = useAppSelector(selectHasCodeToEdit);
const { loadLastSession } = useHistory(dispatch);
const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit;
const isEnterDisabled = props.disabled || isEditModeAndNoCodeToEdit;
const shouldRenderToolsButton =
defaultModel &&
modelSupportsTools(defaultModel.model) &&
!props.toolbarOptions?.hideTools;
const supportsImages =
defaultModel &&
@ -99,7 +116,7 @@ function InputToolbar(props: InputToolbarProps) {
>
<div className="flex items-center justify-start gap-2 whitespace-nowrap">
<ModelSelect />
<div className="xs:flex -mb-1 hidden items-center gap-1 text-gray-400 transition-colors duration-200">
<div className="xs:flex -mb-1 hidden items-center text-gray-400 transition-colors duration-200">
{props.toolbarOptions?.hideImageUpload ||
(supportsImages && (
<>
@ -138,13 +155,15 @@ function InputToolbar(props: InputToolbarProps) {
</HoverItem>
)}
{props.toolbarOptions?.hideTools || <ToggleToolsButton />}
{shouldRenderToolsButton && <ToggleToolsButton />}
</div>
</div>
<div className="flex items-center gap-2 whitespace-nowrap text-gray-400">
{props.toolbarOptions?.hideUseCodebase || (
<div className="hidden transition-colors duration-200 hover:underline sm:flex">
<div
className={`${shouldRenderToolsButton ? "md:flex" : "sm:flex"} hover:underline" hidden transition-colors duration-200`}
>
{props.activeKey === "Alt" ? (
<HoverItem className="underline">
{`${getAltKeyLabel()}⏎
@ -171,14 +190,33 @@ function InputToolbar(props: InputToolbarProps) {
</div>
)}
{isInEditMode && (
<HoverItem
className="hidden hover:underline sm:flex"
onClick={(e) => {
loadLastSession().catch((e) =>
console.error(`Failed to load last session: ${e}`),
);
dispatch(exitEditMode());
}}
>
<span>
<i>Esc</i> to exit
</span>
</HoverItem>
)}
<EnterButton
onClick={(e) => {
props.onEnter({
useCodebase: isMetaEquivalentKeyPressed(e as any),
noContext: useActiveFile ? e.altKey : !e.altKey,
});
onClick={async (e) => {
if (props.onEnter) {
props.onEnter({
useCodebase: isMetaEquivalentKeyPressed(e as any),
noContext: useActiveFile ? e.altKey : !e.altKey,
});
}
}}
disabled={props.disabled}
disabled={isEnterDisabled}
>
<span className="hidden md:inline">
⏎ {props.toolbarOptions?.enterText ?? "Enter"}

View file

@ -40,8 +40,6 @@ export default function ToolDropdown() {
const useTools = useAppSelector((state) => state.ui.useTools);
const availableTools = useAppSelector((state) => state.config.config.tools);
const defaultModel = useAppSelector(selectDefaultModel);
const [showAbove, setShowAbove] = useState(false);
useEffect(() => {
@ -59,10 +57,6 @@ export default function ToolDropdown() {
}
}, [isDropdownOpen]);
if (!defaultModel || !modelSupportsTools(defaultModel.model)) {
return null;
}
return (
<HoverItem onClick={() => dispatch(toggleUseTools())}>
<BackgroundDiv useTools={useTools}>

View file

@ -68,6 +68,7 @@ import { selectDefaultModel } from "../../redux/slices/configSlice";
import {
addCodeToEdit,
clearCodeToEdit,
selectHasCodeToEdit,
selectIsInEditMode,
} from "../../redux/slices/sessionSlice";
import { exitEditMode } from "../../redux/thunks";
@ -253,6 +254,8 @@ function TipTapEditor(props: TipTapEditorProps) {
const isInEditMode = useAppSelector(selectIsInEditMode);
const isInEditModeRef = useUpdatingRef(isInEditMode);
const hasCodeToEdit = useAppSelector(selectHasCodeToEdit);
const isEditModeAndNoCodeToEdit = isInEditMode && !hasCodeToEdit;
async function handleImageFile(
file: File,
@ -489,7 +492,6 @@ function TipTapEditor(props: TipTapEditorProps) {
),
allow: () => isInEditModeRef.current,
command: async ({ editor, range, props }) => {
console.log({ range });
editor.chain().focus().insertContentAt(range, "").run();
const filepath = props.id;
const contents = await ideMessenger.ide.readFile(filepath);
@ -630,7 +632,7 @@ function TipTapEditor(props: TipTapEditorProps) {
const onEnterRef = useUpdatingRef(
(modifiers: InputModifiers) => {
if (isStreaming) {
if (isStreaming || isEditModeAndNoCodeToEdit) {
return;
}

View file

@ -3,7 +3,7 @@ import { ApplyState } from "core";
import { useState } from "react";
import { lightGray, vscForeground } from "../..";
import { getMetaKeyLabel } from "../../../util";
import Spinner from "./Spinner";
import Spinner from "../../gui/Spinner";
import { ToolbarButtonWithTooltip } from "./ToolbarButtonWithTooltip";
interface ApplyActionsProps {

View file

@ -1,4 +1,4 @@
import Spinner from "./Spinner";
import Spinner from "../../gui/Spinner";
export interface GeneratingCodeLoaderProps {
showLineCount: boolean;

View file

@ -4,9 +4,9 @@ import { renderChatMessage } from "core/util/messageContent";
import { useCallback, useContext } from "react";
import { IdeMessengerContext } from "../context/IdeMessenger";
import { useLastSessionContext } from "../context/LastSessionContext";
import { useAppSelector } from "../redux/hooks";
import { newSession, updateSessionTitle } from "../redux/slices/sessionSlice";
import { getLocalStorage, setLocalStorage } from "../util/localStorage";
import { useAppSelector } from "../redux/hooks";
const MAX_TITLE_LENGTH = 100;
@ -52,6 +52,11 @@ function useHistory(dispatch: Dispatch) {
async function saveSession(openNewSession: boolean = true) {
if (history.length === 0) return;
if (openNewSession) {
dispatch(newSession());
updateLastSessionId(sessionId);
}
let currentTitle = title;
if (config?.ui?.getChatTitles && currentTitle === "New Session") {
try {
@ -91,10 +96,7 @@ function useHistory(dispatch: Dispatch) {
await ideMessenger.request("history/save", session);
if (openNewSession) {
dispatch(newSession());
updateLastSessionId(sessionId);
} else {
if (!openNewSession) {
dispatch(updateSessionTitle(newTitle));
}
}

View file

@ -7,15 +7,19 @@ export default function useIsOSREnabled() {
const [isOSREnabled, setIsOSREnabled] = useState(false);
const ideMessenger = useContext(IdeMessengerContext);
useWebviewListener("jetbrains/isOSREnabled", async (isOSREnabled) => {
setIsOSREnabled(isOSREnabled);
});
useEffect(() => {
if (isJetBrains()) {
ideMessenger.post("jetbrains/isOSREnabled", undefined);
(async () => {
await ideMessenger
.request("jetbrains/isOSREnabled", undefined)
.then((result) => {
if (result.status === "success") {
setIsOSREnabled(result.content);
}
});
})();
}
}, []);
}, [ideMessenger]);
return isOSREnabled;
}

View file

@ -16,6 +16,7 @@ import useHistory from "../../hooks/useHistory";
import MoreHelpRow from "./MoreHelpRow";
import IndexingProgress from "./IndexingProgress";
import DocsIndexingStatuses from "../../components/indexing/DocsIndexingStatuses";
import PageHeader from "../../components/PageHeader";
function MorePage() {
useNavigationListener();
@ -26,20 +27,7 @@ function MorePage() {
return (
<div className="overflow-y-scroll">
<div
className="sticky top-0 m-0 flex items-center border-0 border-b border-solid border-b-zinc-700 bg-inherit p-0"
style={{
backgroundColor: vscBackground,
}}
>
<div
className="cursor-pointer transition-colors duration-200 hover:text-zinc-100"
onClick={() => navigate("/")}
>
<ArrowLeftIcon className="ml-3 inline-block h-3 w-3" />
<span className="m-2 inline-block text-base font-bold">Chat</span>
</div>
</div>
<PageHeader onClick={() => navigate("/")} title="Chat" />
<div className="gap-2 divide-x-0 divide-y-2 divide-solid divide-zinc-700 px-4">
<div className="py-5">

View file

@ -70,6 +70,8 @@ import resolveEditorContent from "../../components/mainInput/resolveInput";
import AcceptRejectAllButtons from "../../components/StepContainer/AcceptRejectAllButtons";
import CodeToEditCard from "../../components/CodeToEditCard";
import { exitEditMode } from "../../redux/thunks/exitEditMode";
import PageHeader from "../../components/PageHeader";
import Spinner from "../../components/gui/Spinner";
const StopButton = styled.div`
background-color: ${vscBackground};
@ -135,7 +137,7 @@ export function Chat() {
const { showTutorialCard, closeTutorialCard } = useTutorialCard();
const defaultModel = useAppSelector(selectDefaultModel);
const ttsActive = useAppSelector((state) => state.ui.ttsActive);
const active = useAppSelector((state) => state.session.isStreaming);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]);
const mainTextInputRef = useRef<HTMLInputElement>(null);
const stepsDivRef = useRef<HTMLDivElement>(null);
@ -181,13 +183,9 @@ export function Chat() {
setIsAtBottom(true);
}, [stepsDivRef, setIsAtBottom]);
const returnToLastSessionButtonText = isInEditMode
? "Back to Chat"
: "Last Session";
useEffect(() => {
if (active) snapToBottom();
}, [active, snapToBottom]);
if (isStreaming) snapToBottom();
}, [isStreaming, snapToBottom]);
// useEffect(() => {
// setTimeout(() => {
@ -211,7 +209,7 @@ export function Chat() {
return () => {
window.removeEventListener("keydown", listener);
};
}, [active]);
}, [isStreaming]);
const handleScroll = () => {
// Temporary fix to account for additional height when code blocks are added
@ -228,7 +226,12 @@ export function Chat() {
const { widget, highlights } = useFindWidget(stepsDivRef);
const sendInput = useCallback(
(editorState: JSONContent, modifiers: InputModifiers, editor: Editor) => {
(
editorState: JSONContent,
modifiers: InputModifiers,
editor: Editor,
index?: number,
) => {
if (defaultModel?.provider === "free-trial") {
const u = getLocalStorage("ftc");
if (u) {
@ -259,7 +262,9 @@ export function Chat() {
? getMultifileEditPrompt(codeToEdit)
: undefined;
dispatch(streamResponseThunk({ editorState, modifiers, promptPreamble }));
dispatch(
streamResponseThunk({ editorState, modifiers, promptPreamble, index }),
);
// Increment localstorage counter for popup
const currentCount = getLocalStorage("mainTextEntryCounter");
@ -331,6 +336,21 @@ export function Chat() {
return (
<>
{isInEditMode && (
<PageHeader
title="Chat"
onClick={() => {
loadLastSession().catch((e) =>
console.error(`Failed to load last session: ${e}`),
);
if (isInEditMode) {
dispatch(exitEditMode());
}
}}
/>
)}
{widget}
<StepsDiv
ref={stepsDivRef}
@ -355,7 +375,9 @@ export function Chat() {
<>
{isInEditMode && index === 0 && <CodeToEditCard />}
<ContinueInputBox
onEnter={sendInput}
onEnter={(editorState, modifiers, editor) =>
sendInput(editorState, modifiers, editor, index)
}
isLastUserInput={isLastUserInput(index)}
isMainInput={false}
editorState={item.editorState}
@ -423,7 +445,7 @@ export function Chat() {
<ChatScrollAnchor
scrollAreaRef={stepsDivRef}
isAtBottom={isAtBottom}
trackVisibility={active}
trackVisibility={isStreaming}
/>
</StepsDiv>
@ -439,7 +461,7 @@ export function Chat() {
■ Stop TTS
</StopButton>
)}
{active && (
{isStreaming && (
<StopButton
onClick={() => {
dispatch(setInactive());
@ -466,49 +488,40 @@ export function Chat() {
<div
style={{
pointerEvents: active ? "none" : "auto",
pointerEvents: isStreaming ? "none" : "auto",
}}
>
<div className="flex flex-row items-center justify-between pb-1 pl-0.5 pr-2">
<div className="xs:inline hidden">
{history.length === 0 &&
getLastSessionId() &&
!hasPendingApplies ? (
<div className="xs:inline hidden">
<NewSessionButton
onClick={async () => {
loadLastSession().catch((e) =>
console.error(`Failed to load last session: ${e}`),
);
if (isInEditMode) {
dispatch(exitEditMode());
}
}}
className="flex items-center gap-2"
>
<ArrowLeftIcon className="h-3 w-3" />
{returnToLastSessionButtonText}
</NewSessionButton>
</div>
) : null}
</div>
{history.length === 0 && getLastSessionId() && !isInEditMode && (
<NewSessionButton
onClick={() =>
loadLastSession().catch((e) =>
console.error(`Failed to load last session: ${e}`),
)
}
className="xs:inline flex hidden items-center gap-2"
>
<ArrowLeftIcon className="h-3 w-3" />
Last Session
</NewSessionButton>
)}
<ConfigErrorIndicator />
</div>
{hasPendingApplies && isSingleRangeEditOrInsertion && (
<AcceptRejectAllButtons
pendingApplyStates={pendingApplyStates}
onAcceptOrReject={() => {
loadLastSession().catch((e) =>
console.error(`Failed to load last session: ${e}`),
);
onAcceptOrReject={(outcome) => {
if (outcome === "acceptDiff") {
loadLastSession().catch((e) =>
console.error(`Failed to load last session: ${e}`),
);
dispatch(exitEditMode());
dispatch(exitEditMode());
}
}}
/>
)}
{history.length === 0 && (
<>
{onboardingCard.show && (

View file

@ -6,7 +6,7 @@ import {
vscButtonBackground,
vscButtonForeground,
} from "../../../components";
import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner";
import Spinner from "../../../components/gui/Spinner";
import { selectCurrentToolCall } from "../../../redux/selectors/selectCurrentToolCall";
import { callTool } from "../../../redux/thunks/callTool";
import { cancelTool } from "../../../redux/thunks/cancelTool";

View file

@ -5,7 +5,7 @@ import {
} from "@heroicons/react/24/outline";
import { ToolCall, ToolCallState, ToolStatus } from "core";
import { vscButtonBackground } from "../../../components";
import Spinner from "../../../components/markdown/StepContainerPreToolbar/Spinner";
import Spinner from "../../../components/gui/Spinner";
import FunctionSpecificToolCallDiv from "./FunctionSpecificToolCallDiv";
import { ThreadDiv } from "./ThreadDiv";

View file

@ -1,45 +0,0 @@
import { ArrowLeftIcon } from "@heroicons/react/24/outline";
import { useNavigate } from "react-router-dom";
import { lightGray, vscBackground } from "../../components";
import { useNavigationListener } from "../../hooks/useNavigationListener";
import { getFontSize } from "../../util";
export const HistoryHeader = () => {
useNavigationListener();
const navigate = useNavigate();
return (
<div
className="sticky top-0 z-10"
style={{ backgroundColor: vscBackground, fontSize: getFontSize() }}
>
<div
className="m-0 flex items-center p-0"
style={{
borderBottom: `0.5px solid ${lightGray}`,
}}
>
<div
className="flex cursor-pointer items-center transition-colors duration-200 hover:text-zinc-100"
onClick={() => navigate("/")}
>
<ArrowLeftIcon
width="1.2em"
height="1.2em"
className="ml-4 inline-block"
/>
<span className="m-2 inline-block text-base font-bold">Chat</span>
</div>
</div>
{/* {workspacePaths && workspacePaths.length > 0 && (
<CheckDiv
checked={filteringByWorkspace}
onClick={() => setFilteringByWorkspace((prev) => !prev)}
title={`Show only sessions from ${lastPartOfPath(
workspacePaths[workspacePaths.length - 1]
)}/`}
/>
)} */}
</div>
);
};

View file

@ -1,11 +1,14 @@
import { useNavigate } from "react-router-dom";
import { History } from "../../components/History";
import PageHeader from "../../components/PageHeader";
import { getFontSize } from "../../util";
import { HistoryHeader } from "./HistoryHeader";
export default function HistoryPage() {
const navigate = useNavigate();
return (
<div className="overflow-y-scroll" style={{ fontSize: getFontSize() }}>
<HistoryHeader />
<PageHeader onClick={() => navigate("/")} title="Chat" />
<History />
</div>
);

View file

@ -526,6 +526,9 @@ export const sessionSlice = createSlice({
return selectIsSingleRangeEdit || isInsertion;
},
selectHasCodeToEdit: (state) => {
return state.codeToEdit.length > 0;
},
},
extraReducers: (builder) => {
addPassthroughCases(builder, [streamResponseThunk]);
@ -599,6 +602,7 @@ export const {
selectIsGatheringContext,
selectIsInEditMode,
selectIsSingleRangeEditOrInsertion,
selectHasCodeToEdit,
} = sessionSlice.selectors;
export default sessionSlice.reducer;

View file

@ -13,6 +13,7 @@ export const exitEditMode = createAsyncThunk<void, undefined, ThunkApiType>(
async (_, { dispatch, extra, getState }) => {
const state = getState();
const isInEditMode = selectIsInEditMode(state);
const codeToEdit = state.session.codeToEdit;
const isSingleRangeEditOrInsertion =
selectIsSingleRangeEditOrInsertion(state);
@ -21,6 +22,13 @@ export const exitEditMode = createAsyncThunk<void, undefined, ThunkApiType>(
}
dispatch(setMode("chat"));
for (const code of codeToEdit) {
extra.ideMessenger.post("rejectDiff", {
filepath: code.filepath,
});
}
dispatch(clearCodeToEdit());
dispatch(setEditDone());