Merge branch 'continuedev:main' into add_llamastack

This commit is contained in:
Kai Wu 2025-06-27 09:35:47 -07:00 • committed by GitHub
commit f916723e9f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
49 changed files with 1553 additions and 730 deletions

View file

@ -0,0 +1,35 @@
---
name: New protocol message
description: Create a new protocol message from core/gui/ide to core/gui/ide
---
Create a new protocol message by taking the following steps:
## 1. Define the message type
Add your new message type definition to the appropriate file in the `protocol/` directory with correct TypeScript typing.
## 2. Check for duplicates
Verify that no existing message type already provides the same functionality.
## 3. Add to passThrough (if webview ↔ core)
If your message is between webview and core, add it to `core/protocol/passThrough.ts`.
## 4. Add to IntelliJ constants (if webview ↔ core)
If your message is between webview and core, add it to `extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt`.
## 5. Implement the message handler
Implement the message in the appropriate location:
- **Messages to core**: `core/core.ts`
- **Messages to GUI**: `useWebviewListener` hook
- **Messages to VS Code IDE**: `VsCodeMessenger.ts`
- **Messages to JetBrains IDE**: `IdeProtocolClient.kt`
## 6. Test the implementation
Verify that your message works correctly in both VS Code and JetBrains IDEs if applicable.

View file

@ -0,0 +1,5 @@
---
name: Don't be overeager
---
Avoid over-eagerly adding new features. You should solve the problem at hand and then can propose further work.

View file

@ -104,6 +104,14 @@ jobs:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- name: Build packages (Windows)
run: ./scripts/build-packages.ps1
if: matrix.os == 'windows-latest'
- name: Build packages (Unix)
run: ./scripts/build-packages.sh
if: matrix.os != 'windows-latest'
- name: Install extension Dependencies
run: |
cd extensions/vscode

View file

@ -99,6 +99,14 @@ jobs:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- name: Build packages (Windows)
run: ./scripts/build-packages.ps1
if: matrix.os == 'windows-latest'
- name: Build packages (Unix)
run: ./scripts/build-packages.sh
if: matrix.os != 'windows-latest'
- name: Install extension Dependencies
run: |
cd extensions/vscode

3
.vscode/tasks.json vendored
View file

@ -103,6 +103,9 @@
"clear": true
},
"options": {
"env": {
"SKIP_INSTALLS": "true"
},
"cwd": "${workspaceFolder}/extensions/vscode"
}
},

View file

@ -3,13 +3,13 @@ const fs = require("fs");
const path = require("path");
const ncp = require("ncp").ncp;
const { rimrafSync } = require("rimraf");
const {
validateFilesPresent,
execCmdSync,
autodetectPlatformAndArch,
} = require("../scripts/util");
const { downloadRipgrep } = require("./utils/ripgrep");
const { validateFilesPresent } = require("../scripts/util");
const { ALL_TARGETS, TARGET_TO_LANCEDB } = require("./utils/targets");
const { fork } = require("child_process");
const {
installAndCopyNodeModules,
} = require("../extensions/vscode/scripts/install-copy-nodemodule");
const { bundleBinary } = require("./utils/bundle-binary");
const bin = path.join(__dirname, "bin");
const out = path.join(__dirname, "out");
@ -29,8 +29,6 @@ function cleanSlate() {
const esbuildOutputFile = "out/index.js";
let targets = [...ALL_TARGETS];
const [currentPlatform, currentArch] = autodetectPlatformAndArch();
const assetBackups = [
"node_modules/win-ca/lib/crypt32-ia32.node.bak",
"node_modules/win-ca/lib/crypt32-x64.node.bak",
@ -78,85 +76,6 @@ async function buildWithEsbuild() {
});
}
async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
console.log(`Copying ${packageName} to ${toCopy}`);
// This is a way to install only one package without npm trying to install all the dependencies
// Create a temporary directory for installing the package
const adjustedName = packageName.replace(/@/g, "").replace("/", "-");
const tempDir = path.join(
__dirname,
"tmp",
`continue-node_modules-${adjustedName}`,
);
const currentDir = process.cwd();
// // Remove the dir we will be copying to
// rimrafSync(`node_modules/${toCopy}`);
// // Ensure the temporary directory exists
fs.mkdirSync(tempDir, { recursive: true });
try {
// Move to the temporary directory
process.chdir(tempDir);
// Initialize a new package.json and install the package
execCmdSync(`npm init -y && npm i -f ${packageName} --no-save`);
console.log(
`Contents of: ${packageName}`,
fs.readdirSync(path.join(tempDir, "node_modules", toCopy)),
);
// Without this it seems the file isn't completely written to disk
await new Promise((resolve) => setTimeout(resolve, 2000));
// Copy the installed package back to the current directory
await new Promise((resolve, reject) => {
ncp(
path.join(tempDir, "node_modules", toCopy),
path.join(currentDir, "node_modules", toCopy),
{ dereference: true },
(error) => {
if (error) {
console.error(
`[error] Error copying ${packageName} package`,
error,
);
reject(error);
} else {
resolve();
}
},
);
});
} finally {
// Clean up the temporary directory
// rimrafSync(tempDir);
// Return to the original directory
process.chdir(currentDir);
}
}
/**
* Downloads and installs ripgrep binaries for the specified target
*
* @param {string} target - Target platform-arch (e.g., 'darwin-x64')
* @param {string} targetDir - Directory to install ripgrep to
* @returns {Promise<void>}
*/
async function downloadRipgrepForTarget(target, targetDir) {
console.log(`[info] Downloading ripgrep for ${target}...`);
try {
await downloadRipgrep(target, targetDir);
console.log(`[info] Successfully installed ripgrep for ${target}`);
} catch (error) {
console.error(`[error] Failed to download ripgrep for ${target}:`, error);
throw error;
}
}
(async () => {
if (esbuildOnly) {
await buildWithEsbuild();
@ -181,16 +100,21 @@ async function downloadRipgrepForTarget(target, targetDir) {
),
);
console.log("[info] Downloading prebuilt lancedb...");
const copyLanceDBPromises = [];
for (const target of targets) {
if (TARGET_TO_LANCEDB[target]) {
console.log(`[info] Downloading for ${target}...`);
await installNodeModuleInTempDirAndCopyToCurrent(
TARGET_TO_LANCEDB[target],
"@lancedb",
);
if (!TARGET_TO_LANCEDB[target]) {
continue;
}
console.log(`[info] Downloading for ${target}...`);
copyLanceDBPromises.push(
installAndCopyNodeModules(TARGET_TO_LANCEDB[target], "@lancedb"),
);
}
await Promise.all(copyLanceDBPromises).catch(() => {
console.error("[error] Failed to copy LanceDB");
process.exit(1);
});
console.log("[info] Copied all LanceDB");
// tree-sitter-wasm
const treeSitterWasmsDir = path.join(out, "tree-sitter-wasms");
@ -252,59 +176,16 @@ async function downloadRipgrepForTarget(target, targetDir) {
"out/llamaTokenizerWorkerPool.mjs",
);
const buildBinaryPromises = [];
console.log("[info] Building binaries with pkg...");
for (const target of targets) {
const targetDir = `bin/${target}`;
fs.mkdirSync(targetDir, { recursive: true });
console.log(`[info] Building ${target}...`);
execCmdSync(
`npx pkg --no-bytecode --public-packages "*" --public --compress GZip pkgJson/${target} --out-path ${targetDir}`,
);
// Download and unzip prebuilt sqlite3 binary for the target
console.log("[info] Downloading node-sqlite3");
const downloadUrl =
// node-sqlite3 doesn't have a pre-built binary for win32-arm64
target === "win32-arm64"
? "https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz"
: `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${
target
}.tar.gz`;
execCmdSync(`curl -L -o ${targetDir}/build.tar.gz ${downloadUrl}`);
execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`);
// Copy to build directory for testing
try {
const [platform, arch] = target.split("-");
if (platform === currentPlatform && arch === currentArch) {
fs.copyFileSync(
`${targetDir}/build/Release/node_sqlite3.node`,
`build/node_sqlite3.node`,
);
}
} catch (error) {
console.log("[warn] Could not copy node_sqlite to build");
console.log(error);
}
fs.unlinkSync(`${targetDir}/build.tar.gz`);
// copy @lancedb to bin folders
console.log("[info] Copying @lancedb files to bin");
fs.copyFileSync(
`node_modules/${TARGET_TO_LANCEDB[target]}/index.node`,
`${targetDir}/index.node`,
);
// Download and install ripgrep for the target
await downloadRipgrepForTarget(target, targetDir);
// Informs the `continue-binary` of where to look for node_sqlite3.node
// https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
fs.writeFileSync(`${targetDir}/package.json`, "");
buildBinaryPromises.push(bundleBinary(target));
}
await Promise.all(buildBinaryPromises).catch(() => {
console.error("[error] Failed to build binaries");
process.exit(1);
});
console.log("[info] All binaries built");
// Cleanup - this is needed when running locally
fs.rmSync("out/package.json");
@ -331,4 +212,5 @@ async function downloadRipgrepForTarget(target, targetDir) {
validateFilesPresent(pathsToVerify);
console.log("[info] Done!");
process.exit(0);
})();

View file

@ -53,9 +53,9 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.13",
"@continuedev/fetch": "^1.0.14",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "^1.0.32",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",
@ -106,7 +106,6 @@
"sqlite3": "^5.1.7",
"system-ca": "^1.0.3",
"tar": "^7.4.3",
"tree-sitter-structured-text": "^0.0.1",
"tree-sitter-wasms": "^0.1.11",
"uuid": "^9.0.1",
"vectordb": "^0.4.20",
@ -145,7 +144,6 @@
"myers-diff": "^2.1.0",
"onnxruntime-common": "1.14.0",
"onnxruntime-web": "1.14.0",
"tree-sitter-cli": "^0.22.5",
"ts-jest": "^29.1.1",
"typescript": "^5.6.3",
"vitest": "^3.1.4"

View file

@ -0,0 +1,103 @@
/**
* @file Builds the binary for the specified target. It is also intended to run as a child process.
*/
const {
execCmdSync,
autodetectPlatformAndArch,
} = require("../../scripts/util");
const { downloadRipgrep } = require("./ripgrep");
const { TARGET_TO_LANCEDB } = require("../utils/targets");
const fs = require("fs");
const {
downloadSqlite,
} = require("../../extensions/vscode/scripts/download-copy-sqlite-esbuild");
const { fork } = require("child_process");
async function downloadNodeSqlite(target, targetDir) {
const [currentPlatform, currentArch] = autodetectPlatformAndArch();
// Download and unzip prebuilt sqlite3 binary for the target
console.log("[info] Downloading node-sqlite3");
await downloadSqlite(target, `${targetDir}/build.tar.gz`);
execCmdSync(`cd ${targetDir} && tar -xvzf build.tar.gz`);
// Copy to build directory for testing
try {
const [platform, arch] = target.split("-");
if (platform === currentPlatform && arch === currentArch) {
fs.copyFileSync(
`${targetDir}/build/Release/node_sqlite3.node`,
`build/node_sqlite3.node`,
);
}
} catch (error) {
console.log("[warn] Could not copy node_sqlite to build");
console.log(error);
}
fs.unlinkSync(`${targetDir}/build.tar.gz`);
}
/**
* @param {string} target the platform to build for
*/
async function bundleForBinary(target) {
const targetDir = `bin/${target}`;
fs.mkdirSync(targetDir, { recursive: true });
console.log(`[info] Building ${target}...`);
execCmdSync(
`npx pkg --no-bytecode --public-packages "*" --public --compress GZip pkgJson/${target} --out-path ${targetDir}`,
);
// copy @lancedb to bin folders
console.log("[info] Copying @lancedb files to bin");
fs.copyFileSync(
`node_modules/${TARGET_TO_LANCEDB[target]}/index.node`,
`${targetDir}/index.node`,
);
const downloadPromises = [];
downloadPromises.push(downloadRipgrep(target, targetDir));
downloadPromises.push(downloadNodeSqlite(target, targetDir));
await Promise.all(downloadPromises);
// Informs the `continue-binary` of where to look for node_sqlite3.node
// https://www.npmjs.com/package/bindings#:~:text=The%20searching%20for,file%20is%20found
fs.writeFileSync(`${targetDir}/package.json`, "");
}
process.on("message", (msg) => {
bundleForBinary(msg.payload.target)
.then(() => process.send({ done: true }))
.catch((error) => {
console.error(error); // show the error in the parent process
process.send({ error: true });
});
});
/**
* @param {string} target the platform to bundle for
*/
async function bundleBinary(target) {
const child = fork(__filename, { stdio: "inherit" });
child.send({
payload: {
target,
},
});
return new Promise((resolve, reject) => {
child.on("message", (msg) => {
if (msg.error) {
reject();
} else {
resolve();
}
});
});
}
module.exports = {
bundleBinary,
};

View file

@ -16,7 +16,7 @@
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.14",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "1.0.42",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",

View file

@ -53,7 +53,7 @@
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.14",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "1.0.42",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@modelcontextprotocol/sdk": "^1.12.0",
"@mozilla/readability": "^0.5.0",
"@octokit/rest": "^20.1.1",

10
core/rules.md Normal file
View file

@ -0,0 +1,10 @@
# `core` rules
Whenever a new protocol message is added to the `protocol/` directory, check the following:
- It's type is defined correctly
- If it is a message from webview to core or vice versa:
- It has been added to `core/protocol/passThrough.ts`
- It has been added to `extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/constants/MessageTypes.kt`
- It is implemented in either `core/core.ts` (for messages to the core), in a `useWebviewListener` (for messages to the gui), or in `VsCodeMessenger.ts` for VS Code or `IdeProtocolClient.kt` for JetBriains (for messages to the IDE).
- It does not duplicate functionality from another message type that already exists.

View file

@ -9,6 +9,7 @@ src/client
exe
bin
assets
tmp
gui/**

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.50",
"version": "1.1.52",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.50",
"version": "1.1.52",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@ -108,7 +108,7 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.13",
"@continuedev/fetch": "^1.0.14",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@modelcontextprotocol/sdk": "^1.12.0",

View file

@ -0,0 +1,191 @@
const { fork } = require("child_process");
const fs = require("fs");
const https = require("https");
const path = require("path");
const { rimrafSync } = require("rimraf");
const { execCmdSync } = require("../../../scripts/util");
/**
* download a file using nodejs http
* @param {string} url
* @param {string} outputPath
* @param {number} maxRedirects
*/
async function downloadFile(url, outputPath, maxRedirects = 5) {
return new Promise((resolve, reject) => {
const downloadWithRedirects = (currentUrl, redirectCount = 0) => {
if (redirectCount > maxRedirects) {
return reject(new Error(`Too many redirects (${maxRedirects})`));
}
const request = https.get(currentUrl, (response) => {
if (
response.statusCode >= 300 &&
response.statusCode < 400 &&
response.headers.location
) {
return downloadWithRedirects(
response.headers.location,
redirectCount + 1,
);
}
if (response.statusCode !== 200) {
return reject(
new Error(`HTTP ${response.statusCode}: ${response.statusMessage}`),
);
}
const outputDir = path.dirname(outputPath);
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir, { recursive: true });
}
const writeStream = fs.createWriteStream(outputPath);
const totalSize = parseInt(response.headers["content-length"], 10);
let downloadedSize = 0;
response.on("data", (chunk) => {
downloadedSize += chunk.length;
if (totalSize) {
const percent = ((downloadedSize / totalSize) * 100).toFixed(1);
process.stdout.write(
`\rDownloading: ${percent}% (${downloadedSize}/${totalSize} bytes)`,
);
}
});
response.pipe(writeStream);
writeStream.on("finish", () => {
console.log(`\nDownload completed: ${outputPath}`);
resolve(outputPath);
});
writeStream.on("error", reject);
response.on("error", reject);
});
request.on("error", reject);
request.setTimeout(30000, () => {
request.destroy();
reject(new Error("Request timeout"));
});
};
downloadWithRedirects(url);
});
}
/**
*
* @param {string} target platform specific target
* @param {string} targetDir the directory to download into
*/
async function downloadSqlite(target, targetDir) {
const downloadUrl =
// node-sqlite3 doesn't have a pre-built binary for win32-arm64
target === "win32-arm64"
? "https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz"
: `https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-${
target
}.tar.gz`;
await downloadFile(downloadUrl, targetDir);
}
async function installAndCopySqlite(target) {
// Replace the installed with pre-built
console.log("[info] Downloading pre-built sqlite3 binary");
rimrafSync("../../core/node_modules/sqlite3/build");
await downloadSqlite(target, "../../core/node_modules/sqlite3/build.tar.gz");
execCmdSync("cd ../../core/node_modules/sqlite3 && tar -xvzf build.tar.gz");
fs.unlinkSync("../../core/node_modules/sqlite3/build.tar.gz");
}
async function installAndCopyEsbuild(target) {
// Download and unzip esbuild
console.log("[info] Downloading pre-built esbuild binary");
rimrafSync("node_modules/@esbuild");
fs.mkdirSync("node_modules/@esbuild", { recursive: true });
await downloadFile(
`https://continue-server-binaries.s3.us-west-1.amazonaws.com/${target}/esbuild.zip`,
"node_modules/@esbuild/esbuild.zip",
);
execCmdSync("cd node_modules/@esbuild && unzip esbuild.zip");
fs.unlinkSync("node_modules/@esbuild/esbuild.zip");
}
process.on("message", (msg) => {
const { operation, target } = msg.payload;
if (operation === "sqlite") {
installAndCopySqlite(target)
.then(() => process.send({ done: true }))
.catch((error) => {
console.error(error); // show the error in the parent process
process.send({ error: true });
});
}
if (operation === "esbuild") {
installAndCopyEsbuild(target)
.then(() => process.send({ done: true }))
.catch((error) => {
console.error(error); // show the error in the parent process
process.send({ error: true });
});
}
});
/**
* @param {string} target the platform to build for
*/
async function copySqlite(target) {
const child = fork(__filename, { stdio: "inherit", cwd: process.cwd() });
child.send({
payload: {
operation: "sqlite",
target,
},
});
return new Promise((resolve, reject) => {
child.on("message", (msg) => {
if (msg.error) {
reject();
} else {
resolve();
}
});
});
}
/**
* @param {string} target the platform to build for
*/
async function copyEsbuild(target) {
const child = fork(__filename, { stdio: "inherit", cwd: process.cwd() });
child.send({
payload: {
operation: "esbuild",
target,
},
});
return new Promise((resolve, reject) => {
child.on("message", (msg) => {
if (msg.error) {
reject();
} else {
resolve();
}
});
});
}
module.exports = {
downloadSqlite,
copySqlite,
copyEsbuild,
};

View file

@ -1,4 +1,5 @@
const fs = require("fs");
const { writeBuildTimestamp } = require("./utils");
const esbuild = require("esbuild");
@ -49,7 +50,7 @@ const esbuildConfig = {
],
};
(async () => {
void (async () => {
// Create .buildTimestamp.js before starting the first build
writeBuildTimestamp();
// Bundles the extension into one file

View file

@ -0,0 +1,126 @@
/**
* @file Generate config.yaml file from template. Also intended to run as a child process.
*/
const { fork } = require("child_process");
const fs = require("fs");
const path = require("path");
const { execCmdSync } = require("../../../scripts/util");
const { continueDir } = require("./utils");
async function generateConfigYamlSchema() {
process.chdir(path.join(continueDir, "packages", "config-yaml"));
execCmdSync("npm install");
execCmdSync("npm run build");
execCmdSync("npm run generate-schema");
fs.copyFileSync(
path.join("schema", "config-yaml-schema.json"),
path.join(continueDir, "extensions", "vscode", "config-yaml-schema.json"),
);
console.log("[info] Generated config.yaml schema");
}
async function copyConfigSchema() {
process.chdir(path.join(continueDir, "extensions", "vscode"));
// Modify and copy for .continuerc.json
const schema = JSON.parse(fs.readFileSync("config_schema.json", "utf8"));
schema.$defs.SerializedContinueConfig.properties.mergeBehavior = {
type: "string",
enum: ["merge", "overwrite"],
default: "merge",
title: "Merge behavior",
markdownDescription:
"If set to 'merge', .continuerc.json will be applied on top of config.json (arrays and objects are merged). If set to 'overwrite', then every top-level property of .continuerc.json will overwrite that property from config.json.",
"x-intellij-html-description":
"<p>If set to <code>merge</code>, <code>.continuerc.json</code> will be applied on top of <code>config.json</code> (arrays and objects are merged). If set to <code>overwrite</code>, then every top-level property of <code>.continuerc.json</code> will overwrite that property from <code>config.json</code>.</p>",
};
fs.writeFileSync("continue_rc_schema.json", JSON.stringify(schema, null, 2));
// Copy config schemas to intellij
fs.copyFileSync(
"config_schema.json",
path.join(
"..",
"intellij",
"src",
"main",
"resources",
"config_schema.json",
),
);
fs.copyFileSync(
"continue_rc_schema.json",
path.join(
"..",
"intellij",
"src",
"main",
"resources",
"continue_rc_schema.json",
),
);
}
process.on("message", (msg) => {
const { operation } = msg.payload;
if (operation === "generate") {
generateConfigYamlSchema()
.then(() => process.send({ done: true }))
.catch((error) => {
console.error(error); // show the error in the parent process
process.send({ error: true });
});
}
if (operation === "copy") {
copyConfigSchema()
.then(() => process.send({ done: true }))
.catch((error) => {
console.error(error); // show the error in the parent process
process.send({ error: true });
});
}
});
async function generateAndCopyConfigYamlSchema() {
// Generate and copy over config-yaml-schema.json
const generateConfigYamlChild = fork(
path.join(__dirname, "generate-copy-config.js"),
{
stdio: "inherit",
},
);
generateConfigYamlChild.send({ payload: { operation: "generate" } });
await new Promise((resolve, reject) => {
generateConfigYamlChild.on("message", (msg) => {
if (msg.error) {
reject();
}
resolve();
});
});
// Copy config schemas to intellij
const copyConfigSchemaChild = fork(
path.join(__dirname, "generate-copy-config.js"),
{
stdio: "inherit",
},
);
copyConfigSchemaChild.send({ payload: { operation: "copy" } });
await new Promise((resolve, reject) => {
copyConfigSchemaChild.on("message", (msg) => {
if (msg.error) {
reject();
}
resolve();
});
});
}
module.exports = {
generateAndCopyConfigYamlSchema,
};

View file

@ -0,0 +1,113 @@
/**
* @file Copy lancedb to the current directory. It is also intended to run as a child process.
*/
const { fork } = require("child_process");
const fs = require("fs");
const path = require("path");
const ncp = require("ncp").ncp;
const { execCmdSync } = require("../../../scripts/util");
async function installNodeModuleInTempDirAndCopyToCurrent(packageName, toCopy) {
console.log(`Copying ${packageName} to ${toCopy}`);
// This is a way to install only one package without npm trying to install all the dependencies
// Create a temporary directory for installing the package
const adjustedName = packageName.replace(/@/g, "").replace("/", "-");
const currentDir = process.cwd();
const tempDir = path.join(
currentDir,
"tmp",
`continue-node_modules-${adjustedName}`,
);
// // Remove the dir we will be copying to
// rimrafSync(`node_modules/${toCopy}`);
// // Ensure the temporary directory exists
fs.mkdirSync(tempDir, { recursive: true });
try {
// Move to the temporary directory
process.chdir(tempDir);
// Initialize a new package.json and install the package
execCmdSync(`npm init -y && npm i -f ${packageName} --no-save`);
console.log(
`Contents of: ${packageName}`,
fs.readdirSync(path.join(tempDir, "node_modules", toCopy)),
);
// Without this it seems the file isn't completely written to disk
await new Promise((resolve) => setTimeout(resolve, 2000));
// Copy the installed package back to the current directory
await new Promise((resolve, reject) => {
ncp(
path.join(tempDir, "node_modules", toCopy),
path.join(currentDir, "node_modules", toCopy),
{ dereference: true },
(error) => {
if (error) {
console.error(
`[error] Error copying ${packageName} package`,
error,
);
reject(error);
} else {
resolve();
}
},
);
});
} finally {
// Clean up the temporary directory
// rimrafSync(tempDir);
// Return to the original directory
process.chdir(currentDir);
}
}
process.on("message", (msg) => {
installNodeModuleInTempDirAndCopyToCurrent(
msg.payload.packageName,
msg.payload.toCopy,
)
.then(() => process.send({ done: true }))
.catch((error) => {
console.error(error); // show the error in the parent process
process.send({ error: true });
});
});
/**
* invoke a child process to install a node module into temporary directory and copy it over into node modules
* @param {string} packageName the module to install and copy
* @param {string} toCopy directory to copy into inside node modules
*/
async function installAndCopyNodeModules(packageName, toCopy) {
const child = fork(__filename, { stdio: "inherit", cwd: process.cwd() });
child.send({
payload: {
packageName,
toCopy,
},
});
return new Promise((resolve, reject) => {
child.on("message", (msg) => {
if (msg.error) {
reject();
} else {
resolve();
}
});
});
}
module.exports = {
installAndCopyNodeModules,
};

View file

@ -0,0 +1,79 @@
/**
* @file Install node modules for the VS Code extension and gui. This is also intended to run as a child process.
*/
const { fork } = require("child_process");
const path = require("path");
const { execCmdSync } = require("../../../scripts/util");
const { continueDir } = require("./utils");
async function installNodeModulesInGui() {
process.chdir(path.join(continueDir, "gui"));
execCmdSync("npm install");
console.log("[info] npm install in gui completed");
}
async function installNodeModulesInVscode() {
process.chdir(path.join(continueDir, "extensions", "vscode"));
execCmdSync("npm install");
console.log("[info] npm install in extensions/vscode completed");
}
process.on("message", (msg) => {
const { targetDir } = msg.payload;
if (targetDir === "gui") {
installNodeModulesInGui()
.then(() => process.send({ done: true }))
.catch((error) => {
console.error(error); // show the error in the parent process
process.send({ error: true });
});
} else if (targetDir === "vscode") {
installNodeModulesInVscode()
.then(() => process.send({ done: true }))
.catch((error) => {
console.error(error); // show the error in the parent process
process.send({ error: true });
});
}
});
async function npmInstall() {
const installVscodeChild = fork(__filename, {
stdio: "inherit",
});
installVscodeChild.send({ payload: { targetDir: "vscode" } });
const installGuiChild = fork(__filename, {
stdio: "inherit",
});
installGuiChild.send({ payload: { targetDir: "gui" } });
await Promise.all([
new Promise((resolve, reject) => {
installVscodeChild.on("message", (msg) => {
if (msg.error) {
reject();
}
resolve();
});
}),
new Promise((resolve, reject) => {
installGuiChild.on("message", (msg) => {
if (msg.error) {
reject();
}
resolve();
});
}),
]).catch((error) => {
console.error(error);
process.exit(1);
});
}
module.exports = {
npmInstall,
};

View file

@ -10,11 +10,11 @@ const {
autodetectPlatformAndArch,
} = require("../../../scripts/util/index");
const {
copyConfigSchema,
writeBuildTimestamp,
generateConfigYamlSchema,
} = require("./utils");
const { copySqlite, copyEsbuild } = require("./download-copy-sqlite-esbuild");
const { generateAndCopyConfigYamlSchema } = require("./generate-copy-config");
const { installAndCopyNodeModules } = require("./install-copy-nodemodule");
const { npmInstall } = require("./npm-install");
const { writeBuildTimestamp, continueDir } = require("./utils");
// Clear folders that will be packaged to ensure clean slate
rimrafSync(path.join(__dirname, "..", "bin"));
@ -27,6 +27,8 @@ if (!fs.existsSync(guiDist)) {
fs.mkdirSync(guiDist, { recursive: true });
}
const skipInstalls = process.env.SKIP_INSTALLS === "true";
// Get the target to package for
let target = undefined;
const args = process.argv;
@ -36,10 +38,10 @@ if (args[2] === "--target") {
let os;
let arch;
if (!target) {
[os, arch] = autodetectPlatformAndArch();
} else {
if (target) {
[os, arch] = target.split("-");
} else {
[os, arch] = autodetectPlatformAndArch();
}
if (os === "alpine") {
@ -67,28 +69,14 @@ const isMacTarget = target?.startsWith("darwin");
void (async () => {
console.log("[info] Packaging extension for target ", target);
// Generate and copy over config-yaml-schema.json
generateConfigYamlSchema();
// Copy config schemas to intellij
copyConfigSchema();
if (!process.cwd().endsWith("vscode")) {
// This is sometimes run from root dir instead (e.g. in VS Code tasks)
process.chdir("extensions/vscode");
}
// Make sure we have an initial timestamp file
writeBuildTimestamp();
// Install node_modules //
execCmdSync("npm install");
console.log("[info] npm install in extensions/vscode completed");
if (!skipInstalls) {
await Promise.all([generateAndCopyConfigYamlSchema(), npmInstall()]);
}
process.chdir("../../gui");
execCmdSync("npm install");
console.log("[info] npm install in gui completed");
process.chdir(path.join(continueDir, "gui"));
if (isInGitHubAction) {
execCmdSync("npm run build");
@ -280,122 +268,32 @@ void (async () => {
);
});
async function installNodeModuleInTempDirAndCopyToCurrent(
packageName,
toCopy,
) {
console.log(`Copying ${packageName} to ${toCopy}`);
// This is a way to install only one package without npm trying to install all the dependencies
// Create a temporary directory for installing the package
const adjustedName = packageName.replace(/@/g, "").replace("/", "-");
const tempDir = `/tmp/continue-node_modules-${adjustedName}`;
const currentDir = process.cwd();
// Remove the dir we will be copying to
rimrafSync(`node_modules/${toCopy}`);
// Ensure the temporary directory exists
fs.mkdirSync(tempDir, { recursive: true });
try {
// Move to the temporary directory
process.chdir(tempDir);
// Initialize a new package.json and install the package
execCmdSync(`npm init -y && npm i -f ${packageName} --no-save`);
if (!skipInstalls) {
// GitHub Actions doesn't support ARM, so we need to download pre-saved binaries
// 02/07/25 - the above comment is out of date, there is now support for ARM runners on GitHub Actions
if (isArmTarget) {
// lancedb binary
const packageToInstall = {
"darwin-arm64": "@lancedb/vectordb-darwin-arm64",
"linux-arm64": "@lancedb/vectordb-linux-arm64-gnu",
"win32-arm64": "@lancedb/vectordb-win32-arm64-msvc",
}[target];
console.log(
`Contents of: ${packageName}`,
fs.readdirSync(path.join(tempDir, "node_modules", toCopy)),
"[info] Downloading pre-built lancedb binary: " + packageToInstall,
);
// Without this it seems the file isn't completely written to disk
// Ideally we validate file integrity in the validation at the end
await new Promise((resolve) => setTimeout(resolve, 2000));
// Copy the installed package back to the current directory
await new Promise((resolve, reject) => {
ncp(
path.join(tempDir, "node_modules", toCopy),
path.join(currentDir, "node_modules", toCopy),
{ dereference: true },
(error) => {
if (error) {
console.error(
`[error] Error copying ${packageName} package`,
error,
);
reject(error);
} else {
resolve();
}
},
);
});
} finally {
// Clean up the temporary directory
// rimrafSync(tempDir);
// Return to the original directory
process.chdir(currentDir);
await Promise.all([
copyEsbuild(target),
copySqlite(target),
installAndCopyNodeModules(packageToInstall, "@lancedb"),
]);
} else {
// Download esbuild from npm in tmp and copy over
console.log("[info] npm installing esbuild binary");
await installAndCopyNodeModules("esbuild@0.17.19", "@esbuild");
}
}
// GitHub Actions doesn't support ARM, so we need to download pre-saved binaries
// 02/07/25 - the above comment is out of date, there is now support for ARM runners on GitHub Actions
if (isArmTarget) {
// lancedb binary
const packageToInstall = {
"darwin-arm64": "@lancedb/vectordb-darwin-arm64",
"linux-arm64": "@lancedb/vectordb-linux-arm64-gnu",
"win32-arm64": "@lancedb/vectordb-win32-arm64-msvc",
}[target];
console.log(
"[info] Downloading pre-built lancedb binary: " + packageToInstall,
);
await installNodeModuleInTempDirAndCopyToCurrent(
packageToInstall,
"@lancedb",
);
// Replace the installed with pre-built
console.log("[info] Downloading pre-built sqlite3 binary");
rimrafSync("../../core/node_modules/sqlite3/build");
const downloadUrl = {
"darwin-arm64":
"https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v6-darwin-arm64.tar.gz",
"linux-arm64":
"https://github.com/TryGhost/node-sqlite3/releases/download/v5.1.7/sqlite3-v5.1.7-napi-v3-linux-arm64.tar.gz",
// node-sqlite3 doesn't have a pre-built binary for win32-arm64
"win32-arm64":
"https://continue-server-binaries.s3.us-west-1.amazonaws.com/win32-arm64/node_sqlite3.tar.gz",
}[target];
execCmdSync(
`curl -L -o ../../core/node_modules/sqlite3/build.tar.gz ${downloadUrl}`,
);
execCmdSync("cd ../../core/node_modules/sqlite3 && tar -xvzf build.tar.gz");
fs.unlinkSync("../../core/node_modules/sqlite3/build.tar.gz");
// Download and unzip esbuild
console.log("[info] Downloading pre-built esbuild binary");
rimrafSync("node_modules/@esbuild");
fs.mkdirSync("node_modules/@esbuild", { recursive: true });
execCmdSync(
`curl -o node_modules/@esbuild/esbuild.zip https://continue-server-binaries.s3.us-west-1.amazonaws.com/${target}/esbuild.zip`,
);
execCmdSync(`cd node_modules/@esbuild && unzip esbuild.zip`);
fs.unlinkSync("node_modules/@esbuild/esbuild.zip");
} else {
// Download esbuild from npm in tmp and copy over
console.log("npm installing esbuild binary");
await installNodeModuleInTempDirAndCopyToCurrent(
"esbuild@0.17.19",
"@esbuild",
);
}
console.log("[info] Copying sqlite node binding from core");
await new Promise((resolve, reject) => {
ncp(
@ -465,7 +363,7 @@ void (async () => {
);
// delete esbuild/bin because platform-specific @esbuild is downloaded
fs.rmdirSync(`out/node_modules/esbuild/bin`, { recursive: true });
fs.rmSync(`out/node_modules/esbuild/bin`, { recursive: true });
console.log(`[info] Copied ${NODE_MODULES_TO_COPY.join(", ")}`);
@ -534,4 +432,6 @@ void (async () => {
`out/node_modules/@lancedb/vectordb-${target}${isWinTarget ? "-msvc" : ""}${isLinuxTarget ? "-gnu" : ""}/index.node`,
`out/node_modules/esbuild/lib/main.js`,
]);
process.exit(0);
})();

View file

@ -1,68 +1,13 @@
const fs = require("fs");
const ncp = require("ncp").ncp;
const path = require("path");
const ncp = require("ncp").ncp;
const { rimrafSync } = require("rimraf");
const {
validateFilesPresent,
execCmdSync,
autodetectPlatformAndArch,
} = require("../../../scripts/util/index");
const { execCmdSync } = require("../../../scripts/util/index");
const continueDir = path.join(__dirname, "..", "..", "..");
function generateConfigYamlSchema() {
process.chdir(path.join(continueDir, "packages", "config-yaml"));
execCmdSync("npm install");
execCmdSync("npm run build");
execCmdSync("npm run generate-schema");
fs.copyFileSync(
path.join("schema", "config-yaml-schema.json"),
path.join(continueDir, "extensions", "vscode", "config-yaml-schema.json"),
);
console.log("[info] Generated config.yaml schema");
}
function copyConfigSchema() {
process.chdir(path.join(continueDir, "extensions", "vscode"));
// Modify and copy for .continuerc.json
const schema = JSON.parse(fs.readFileSync("config_schema.json", "utf8"));
schema.$defs.SerializedContinueConfig.properties.mergeBehavior = {
type: "string",
enum: ["merge", "overwrite"],
default: "merge",
title: "Merge behavior",
markdownDescription:
"If set to 'merge', .continuerc.json will be applied on top of config.json (arrays and objects are merged). If set to 'overwrite', then every top-level property of .continuerc.json will overwrite that property from config.json.",
"x-intellij-html-description":
"<p>If set to <code>merge</code>, <code>.continuerc.json</code> will be applied on top of <code>config.json</code> (arrays and objects are merged). If set to <code>overwrite</code>, then every top-level property of <code>.continuerc.json</code> will overwrite that property from <code>config.json</code>.</p>",
};
fs.writeFileSync("continue_rc_schema.json", JSON.stringify(schema, null, 2));
// Copy config schemas to intellij
fs.copyFileSync(
"config_schema.json",
path.join(
"..",
"intellij",
"src",
"main",
"resources",
"config_schema.json",
),
);
fs.copyFileSync(
"continue_rc_schema.json",
path.join(
"..",
"intellij",
"src",
"main",
"resources",
"continue_rc_schema.json",
),
);
}
function copyTokenizers() {
fs.copyFileSync(
path.join(__dirname, "../../../core/llm/llamaTokenizerWorkerPool.mjs"),
@ -77,22 +22,6 @@ function copyTokenizers() {
console.log("[info] Copied llamaTokenizer");
}
function installNodeModules() {
// Make sure we are in the right directory
if (!process.cwd().endsWith("vscode")) {
process.chdir(path.join(continueDir, "extensions", "vscode"));
}
// Install node_modules //
execCmdSync("npm install");
console.log("[info] npm install in extensions/vscode completed");
process.chdir(path.join(continueDir, "gui"));
execCmdSync("npm install");
console.log("[info] npm install in gui completed");
}
async function buildGui(isGhAction) {
// Make sure we are in the right directory
if (!process.cwd().endsWith("gui")) {
@ -536,15 +465,13 @@ async function copyScripts() {
// in the build
function writeBuildTimestamp() {
fs.writeFileSync(
"src/.buildTimestamp.ts",
path.join(continueDir, "extensions/vscode", "src/.buildTimestamp.ts"),
`export default "${new Date().toISOString()}";\n`,
);
}
module.exports = {
generateConfigYamlSchema,
copyConfigSchema,
installNodeModules,
continueDir,
buildGui,
copyOnnxRuntimeFromNodeModules,
copyTreeSitterWasms,

9
gui/package-lock.json generated
View file

@ -114,7 +114,7 @@
"@aws-sdk/credential-providers": "^3.778.0",
"@continuedev/config-types": "^1.0.13",
"@continuedev/config-yaml": "file:../packages/config-yaml",
"@continuedev/fetch": "^1.0.13",
"@continuedev/fetch": "^1.0.14",
"@continuedev/llm-info": "^1.0.8",
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
"@modelcontextprotocol/sdk": "^1.12.0",
@ -215,7 +215,7 @@
},
"../packages/config-yaml": {
"name": "@continuedev/config-yaml",
"version": "1.0.94",
"version": "1.0.95",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@ -226,10 +226,15 @@
"config-yaml": "dist/cli.js"
},
"devDependencies": {
"@semantic-release/changelog": "^6.0.3",
"@semantic-release/git": "^10.0.1",
"@semantic-release/github": "^9.2.6",
"@semantic-release/npm": "^10.0.6",
"@types/jest": "^29.5.14",
"@types/node": "^20.0.0",
"cross-env": "^7.0.3",
"jest": "^29.7.0",
"semantic-release": "^21.1.2",
"ts-jest": "^29.2.3",
"ts-node": "^10.9.2",
"zod-to-json-schema": "^3.24.5"

View file

@ -11,8 +11,10 @@ import { IdeMessengerContext } from "../../../context/IdeMessenger";
import { useIdeMessengerRequest } from "../../../hooks/useIdeMessengerRequest";
import { useWebviewListener } from "../../../hooks/useWebviewListener";
import { useAppSelector } from "../../../redux/hooks";
import { selectCurrentToolCallApplyState } from "../../../redux/selectors/selectCurrentToolCall";
import { selectApplyStateByStreamId } from "../../../redux/slices/sessionSlice";
import {
selectApplyStateByStreamId,
selectApplyStateByToolCallId,
} from "../../../redux/slices/sessionSlice";
import { getFontSize } from "../../../util";
import Spinner from "../../gui/Spinner";
import { isTerminalCodeBlock } from "../utils";
@ -54,6 +56,7 @@ export interface StepContainerPreToolbarProps {
codeBlockIndex: number; // To track which codeblock we are applying
isLastCodeblock: boolean;
codeBlockStreamId: string;
forceToolCallId?: string; // If this is defined, we will use this streamId instead of the one from the codeBlock
range?: string;
children: any;
expanded?: boolean;
@ -68,6 +71,7 @@ export function StepContainerPreToolbar({
codeBlockIndex,
isLastCodeblock,
codeBlockStreamId,
forceToolCallId,
range,
children,
expanded,
@ -99,8 +103,8 @@ export function StepContainerPreToolbar({
const applyState = useAppSelector((state) =>
selectApplyStateByStreamId(state, codeBlockStreamId),
);
const currentToolCallApplyState = useAppSelector(
selectCurrentToolCallApplyState,
const toolCallApplyState = useAppSelector((state) =>
selectApplyStateByToolCallId(state, forceToolCallId),
);
/**
@ -147,7 +151,7 @@ export function StepContainerPreToolbar({
setRelativeFilepathUri(resolvedUri);
}
};
getRelativeFilepathUri();
void getRelativeFilepathUri();
}, [relativeFilepath, ideMessenger.ide]);
async function getFileUriToApplyTo() {
@ -173,7 +177,7 @@ export function StepContainerPreToolbar({
async function onClickApply() {
const fileUri = await getFileUriToApplyTo();
if (!fileUri) {
ideMessenger.ide.showToast(
void ideMessenger.ide.showToast(
"error",
"Could not resolve filepath to apply changes",
);
@ -188,7 +192,7 @@ export function StepContainerPreToolbar({
});
setAppliedFileUri(fileUri);
refreshFileExists();
void refreshFileExists();
}
function onClickInsertAtCursor() {
@ -198,7 +202,7 @@ export function StepContainerPreToolbar({
async function handleDiffAction(action: "accept" | "reject") {
const filepath = await getFileUriToApplyTo();
if (!filepath) {
ideMessenger.ide.showToast(
void ideMessenger.ide.showToast(
"error",
`Could not resolve filepath to ${action} changes`,
);
@ -233,10 +237,7 @@ export function StepContainerPreToolbar({
}
const renderActionButtons = () => {
const isPendingToolCall =
currentToolCallApplyState &&
currentToolCallApplyState.streamId === applyState?.streamId &&
currentToolCallApplyState.status === "not-started";
const isPendingToolCall = toolCallApplyState?.status === "not-started";
if (isGeneratingCodeBlock || isPendingToolCall) {
const numLines = codeBlockContent.split("\n").length;
@ -271,7 +272,7 @@ export function StepContainerPreToolbar({
return (
<ApplyActions
disableManualApply={disableManualApply}
applyState={applyState}
applyState={toolCallApplyState ?? applyState}
onClickApply={onClickApply}
onClickAccept={() => handleDiffAction("accept")}
onClickReject={() => handleDiffAction("reject")}
@ -293,6 +294,7 @@ export function StepContainerPreToolbar({
<ToolbarDiv isExpanded={isExpanded} className="find-widget-skip gap-3">
<div className="max-w-[50% flex flex-row items-center">
<ChevronDownIcon
data-testid="toggle-codeblock"
onClick={() => setIsExpanded(!isExpanded)}
className={`text-lightgray h-3.5 w-3.5 flex-shrink-0 cursor-pointer hover:brightness-125 ${
isExpanded ? "rotate-0" : "-rotate-90"

View file

@ -126,7 +126,7 @@ interface StyledMarkdownPreviewProps {
itemIndex?: number;
useParentBackgroundColor?: boolean;
disableManualApply?: boolean;
forceStreamId?: string;
toolCallId?: string;
expandCodeblocks?: boolean;
}
@ -196,11 +196,6 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
const itemIndexRef = useUpdatingRef(props.itemIndex);
const codeblockStreamIds = useRef<string[]>([]);
useEffect(() => {
if (props.forceStreamId) {
codeblockStreamIds.current = [props.forceStreamId];
}
}, [props.forceStreamId, codeblockStreamIds]);
const [reactContent, setMarkdownSource] = useRemark({
remarkPlugins: [
@ -295,8 +290,7 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
const isLastCodeblock = preChildProps["data-islastcodeblock"];
if (codeblockStreamIds.current[codeBlockIndex] === undefined) {
codeblockStreamIds.current[codeBlockIndex] =
props.forceStreamId ?? uuidv4();
codeblockStreamIds.current[codeBlockIndex] = uuidv4();
}
return (
@ -308,7 +302,8 @@ const StyledMarkdownPreview = memo(function StyledMarkdownPreview(
relativeFilepath={relativeFilePath}
isLastCodeblock={isLastCodeblock}
range={range}
codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]}
codeBlockStreamId={codeblockStreamIds.current[codeBlockIndex]} // ignored if toolCallId stream state is found
forceToolCallId={props.toolCallId}
expanded={props.expandCodeblocks}
disableManualApply={props.disableManualApply}
>

View file

@ -330,7 +330,10 @@ export function createEditorConfig(options: {
],
editorProps: {
attributes: {
class: "outline-none overflow-hidden",
"data-testid": props.isMainInput
? "editor-input-main"
: `editor-input-${props.inputId}`,
class: "ProseMirror outline-none overflow-hidden",
style: `font-size: ${getFontSize()}px;`,
},
},

View file

@ -1,7 +1,6 @@
import { IDE, PromptLog } from "core";
import { ChatMessage, IDE, PromptLog } from "core";
import { AuthType } from "core/control-plane/AuthTypes";
import {
FromIdeProtocol,
FromWebviewProtocol,
ToCoreProtocol,
ToWebviewProtocol,
@ -13,73 +12,83 @@ import {
GeneratorYieldType,
WebviewSingleProtocolMessage,
} from "core/protocol/util";
import { ChatMessage } from "../redux/store";
import { IIdeMessenger } from "./IdeMessenger";
async function defaultMockHandleMessage<T extends keyof FromWebviewProtocol>(
messageType: T,
data: FromWebviewProtocol[T][0],
): Promise<FromWebviewProtocol[T][1]> {
function returnFor<K extends keyof FromWebviewProtocol>(
_: K,
value: FromWebviewProtocol[K][1],
): FromWebviewProtocol[T][1] {
return value as unknown as FromWebviewProtocol[T][1];
}
type MockResponses = Partial<{
[K in keyof FromWebviewProtocol]: FromWebviewProtocol[K][1];
}>;
switch (messageType) {
case "history/list":
return returnFor("history/list", [
{
title: "Session 1",
sessionId: "session-1",
dateCreated: new Date().toString(),
workspaceDirectory: "/tmp",
},
]);
case "getControlPlaneSessionInfo":
return returnFor("getControlPlaneSessionInfo", {
AUTH_TYPE: AuthType.WorkOsStaging,
accessToken: "",
account: {
label: "",
id: "",
},
});
case "config/getSerializedProfileInfo":
return returnFor("config/getSerializedProfileInfo", {
organizations: [],
profileId: "test-profile",
result: {
config: undefined,
errors: [],
configLoadInterrupted: false,
},
selectedOrgId: "local",
});
default:
throw new Error(`Unknown message type ${messageType}`);
}
}
const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = {
fileExists: true,
getCurrentFile: {
isUntitled: false,
contents: "Current file contents",
path: "file:///Users/user/workspace1/current_file.py",
},
"controlPlane/getFreeTrialStatus": {
autocompleteLimit: 1000,
optedInToFreeTrial: false,
chatLimit: 1000,
autocompleteCount: 0,
chatCount: 0,
},
getWorkspaceDirs: [
"file:///Users/user/workspace1",
"file:///Users/user/workspace2",
],
"history/list": [
{
title: "Session 1",
sessionId: "session-1",
dateCreated: new Date().toString(),
workspaceDirectory: "/tmp",
},
],
"history/save": undefined,
getControlPlaneSessionInfo: {
AUTH_TYPE: AuthType.WorkOsStaging,
accessToken: "",
account: {
label: "",
id: "",
},
},
"config/getSerializedProfileInfo": {
organizations: [],
profileId: "test-profile",
result: {
config: undefined,
errors: [],
configLoadInterrupted: false,
},
selectedOrgId: "local",
},
"chatDescriber/describe": "Session summary",
applyToFile: undefined,
acceptDiff: undefined,
};
const DEFAULT_CHAT_RESPONSE: ChatMessage[] = [
{
role: "assistant",
content: "This is a test",
},
];
export class MockIdeMessenger implements IIdeMessenger {
ide: IDE;
private messageHandlers: Map<
keyof FromIdeProtocol,
Array<(data: any) => void>
> = new Map();
constructor() {
this.ide = new MessageIde(
(messageType, data) => {
throw new Error("Not implemented");
async (messageType, data) => {
const response = await this.request.bind(this)(messageType, data);
if (response.status === "error") {
throw new Error(response.error);
} else {
return response.content;
}
},
(messageType, callback) => {
// Store the callback in our handlers map
if (!this.messageHandlers.has(messageType)) {
this.messageHandlers.set(messageType, []);
}
this.messageHandlers.get(messageType)?.push(callback);
return;
},
);
}
@ -109,16 +118,38 @@ export class MockIdeMessenger implements IIdeMessenger {
);
}
responses: MockResponses = { ...DEFAULT_MOCK_CORE_RESPONSES };
chatResponse: ChatMessage[] = DEFAULT_CHAT_RESPONSE;
chatStreamDelay: number = 0;
setChatResponseText(text: string): void {
this.chatResponse = [
{
role: "assistant",
content: text,
},
];
}
async *llmStreamChat(
msg: ToCoreProtocol["llm/streamChat"][0],
cancelToken: AbortSignal,
): AsyncGenerator<ChatMessage[], PromptLog | undefined> {
yield [
{
role: "assistant",
content: "This is a test",
},
];
for (const response of this.chatResponse) {
if (cancelToken.aborted) {
console.log("MockIdeMessenger: Stream aborted");
return undefined;
}
console.log(
"MockIdeMessenger: Yielding chunk",
JSON.stringify(response, null, 2),
);
yield [response];
if (this.chatStreamDelay > 0) {
await new Promise((resolve) =>
setTimeout(resolve, this.chatStreamDelay),
);
}
}
return undefined;
}
@ -133,12 +164,16 @@ export class MockIdeMessenger implements IIdeMessenger {
messageType: T,
data: FromWebviewProtocol[T][0],
): Promise<WebviewSingleProtocolMessage<T>> {
const content = await defaultMockHandleMessage(messageType, data);
return {
status: "success",
content,
done: true,
};
if (messageType in this.responses) {
const content = this.responses[messageType];
return {
status: "success",
content,
done: true,
};
}
console.error(messageType);
throw new Error("MockIdeMessenger: No response defined for " + messageType);
}
respond<T extends keyof ToWebviewProtocol>(
@ -157,4 +192,10 @@ export class MockIdeMessenger implements IIdeMessenger {
> {
return undefined;
}
resetMocks(): void {
this.responses = { ...DEFAULT_MOCK_CORE_RESPONSES };
this.chatResponse = DEFAULT_CHAT_RESPONSE;
this.chatStreamDelay = 0;
}
}

View file

@ -20,6 +20,7 @@ import {
import {
acceptToolCall,
addContextItemsAtIndex,
selectCurrentToolCall,
setHasReasoningEnabled,
updateApplyState,
} from "../redux/slices/sessionSlice";
@ -244,6 +245,10 @@ function ParallelListeners() {
dispatch(updateIndexingStatus(data));
});
const autoAcceptEditToolDiffs = useAppSelector(
(store) => store.config.config.ui?.autoAcceptEditToolDiffs,
);
const currentToolCall = useAppSelector(selectCurrentToolCall);
useWebviewListener(
"updateApplyState",
async (state) => {
@ -259,30 +264,45 @@ function ParallelListeners() {
// Handle apply status updates that are associated with current tool call
if (
state.status === "closed" &&
currentToolCallApplyState &&
currentToolCallApplyState.streamId === state.streamId
) {
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
dispatch(
acceptToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
// dispatch(setToolCallOutput([]));
void dispatch(
streamResponseAfterToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
if (state.status === "done" && autoAcceptEditToolDiffs) {
console.log("AUTO ACCEPTED");
ideMessenger.post("acceptDiff", {
streamId: state.streamId,
filepath: state.filepath,
});
}
if (state.status === "closed") {
if (currentToolCall?.status !== "canceled") {
dispatch(
acceptToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
}
// const output: ContextItem = {
// name: "Edit tool output",
// content: "Completed edit",
// description: "",
// };
// dispatch(setToolCallOutput([]));
void dispatch(
streamResponseAfterToolCall({
toolCallId: currentToolCallApplyState.toolCallId!,
}),
);
}
}
}
},
[currentToolCallApplyState, history],
[
currentToolCall,
currentToolCallApplyState,
autoAcceptEditToolDiffs,
ideMessenger,
],
);
useEffect(() => {

View file

@ -1,161 +0,0 @@
import { screen, waitFor } from "@testing-library/dom";
import { act } from "@testing-library/react";
import { renderWithProviders } from "../../util/test/render";
import { Chat } from "./Chat";
describe("Chat page test", () => {
it("should render input box", async () => {
await renderWithProviders(<Chat />);
expect(await screen.findByTestId("continue-input-box")).toBeInTheDocument();
});
it("should be able to toggle modes", async () => {
await renderWithProviders(<Chat />);
expect(screen.getByText("Chat")).toBeInTheDocument();
// Simulate cmd+. keyboard shortcut to toggle modes
act(() => {
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: ".",
metaKey: true, // cmd key on Mac
}),
);
});
// Check that it switched to Agent mode
expect(await screen.findByText("Agent")).toBeInTheDocument();
act(() => {
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: ".",
metaKey: true, // cmd key on Mac
}),
);
});
// Check that it switched back to Chat mode
expect(await screen.findByText("Chat")).toBeInTheDocument();
});
it.skip("should send a message and receive a response", async () => {
const { user, container } = await renderWithProviders(<Chat />);
const inputBox = await waitFor(() =>
container.querySelector(".ProseMirror")!.querySelector("p"),
);
expect(inputBox).toBeDefined();
const sendButton = await screen.findByTestId("submit-input-button");
await act(async () => {
// Focus input box
inputBox!.focus();
// Type message
await user.type(inputBox!, "Hello, world!");
sendButton.click();
});
expect(await screen.findByText("Hello, world!")).toBeInTheDocument();
});
it("should handle apply updates and display the accept / reject all buttons", async () => {
const { ideMessenger } = await renderWithProviders(<Chat />);
// Use queryByText which returns null when element isn't found
const acceptAllButton = screen.queryByText("Accept All");
const rejectAllButton = screen.queryByText("Reject All");
// Assert that the buttons don't exist
expect(acceptAllButton).not.toBeInTheDocument();
expect(rejectAllButton).not.toBeInTheDocument();
for (let i = 0; i < 5; i++) {
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "streaming",
streamId: `12345`,
});
}
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "done",
streamId: "12345",
});
// Wait for the buttons to appear
await waitFor(() => {
expect(
screen.getByTestId("accept-reject-all-buttons"),
).toBeInTheDocument();
});
// IDE sends back message that it is done
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "closed",
streamId: "12345",
});
// Wait for the buttons to disappear
await waitFor(() => {
expect(
screen.queryByTestId("edit-accept-button"),
).not.toBeInTheDocument();
expect(
screen.queryByTestId("edit-reject-button"),
).not.toBeInTheDocument();
});
});
it("should show apply cancellation", async () => {
const { ideMessenger } = await renderWithProviders(<Chat />);
// Spy on the request method of ideMessenger
const messengerPostSpy = vi.spyOn(ideMessenger, "post");
for (let i = 0; i < 5; i++) {
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "streaming",
streamId: `12345`,
});
}
// Wait for applying toolbar to appear
await waitFor(() => {
const cancelApplyButton = screen.getByTestId(
"notch-applying-cancel-button",
);
const applyingText = screen.getByTestId("notch-applying-text");
expect(cancelApplyButton).toBeInTheDocument();
expect(applyingText).toBeInTheDocument();
});
const cancelApplyButton = screen.getByTestId(
"notch-applying-cancel-button",
);
cancelApplyButton.click();
// Verify that rejectDiff message has been posted to ideMessenger
expect(messengerPostSpy).toHaveBeenCalledWith("rejectDiff", {});
// Now simulate the IDE sending back a message that the apply state is closed
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "closed",
streamId: "12345",
});
await waitFor(() => {
const cancelApplyButton = screen.queryByTestId(
"notch-applying-cancel-button",
);
const applyingText = screen.queryByTestId("notch-applying-text");
expect(cancelApplyButton).not.toBeInTheDocument();
expect(applyingText).not.toBeInTheDocument();
});
// Cleanup spy
messengerPostSpy.mockRestore();
});
});

View file

@ -42,12 +42,12 @@ import {
setDialogMessage,
setShowDialog,
} from "../../redux/slices/uiSlice";
import { cancelStream } from "../../redux/thunks/cancelStream";
import { streamEditThunk } from "../../redux/thunks/edit";
import { loadLastSession } from "../../redux/thunks/session";
import { streamResponseThunk } from "../../redux/thunks/streamResponse";
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
import { cancelStream } from "../../redux/thunks/cancelStream";
import { getLocalStorage, setLocalStorage } from "../../util/localStorage";
import { EmptyChatBody } from "./EmptyChatBody";
import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
@ -125,14 +125,14 @@ export function Chat() {
useEffect(() => {
// Cmd + Backspace to delete current step
const listener = (e: any) => {
const listener = (e: KeyboardEvent) => {
if (
e.key === "Backspace" &&
(jetbrains ? e.altKey : isMetaEquivalentKeyPressed(e)) &&
!e.shiftKey
) {
dispatch(cancelStream());
ideMessenger.post("rejectDiff", {}); // just always cancel, if not in applying won't matter
void dispatch(cancelStream());
if (isInEdit) ideMessenger.post("rejectDiff", {});
}
};
window.addEventListener("keydown", listener);
@ -140,7 +140,7 @@ export function Chat() {
return () => {
window.removeEventListener("keydown", listener);
};
}, [isStreaming, jetbrains]);
}, [isStreaming, jetbrains, isInEdit]);
const { widget, highlights } = useFindWidget(
stepsDivRef,

View file

@ -1,12 +1,5 @@
import { getMarkdownLanguageTagForFile } from "core/util";
import { useEffect } from "react";
import { v4 as uuidv4 } from "uuid";
import StyledMarkdownPreview from "../../../components/StyledMarkdownPreview";
import { useAppDispatch, useAppSelector } from "../../../redux/hooks";
import {
selectApplyStateByToolCallId,
updateApplyState,
} from "../../../redux/slices/sessionSlice";
type EditToolCallProps = {
relativeFilePath: string;
@ -16,24 +9,6 @@ type EditToolCallProps = {
};
export function EditFile(props: EditToolCallProps) {
const dispatch = useAppDispatch();
const applyState = useAppSelector((state) =>
selectApplyStateByToolCallId(state, props.toolCallId),
);
useEffect(() => {
if (!applyState) {
dispatch(
updateApplyState({
streamId: uuidv4(),
toolCallId: props.toolCallId,
status: "not-started",
}),
);
}
}, [applyState, props.toolCallId]);
if (!props.relativeFilePath || !props.changes) {
return null;
}
@ -45,7 +20,7 @@ export function EditFile(props: EditToolCallProps) {
isRenderingInStepContainer
disableManualApply
source={src}
forceStreamId={applyState?.streamId}
toolCallId={props.toolCallId}
expandCodeblocks={false}
itemIndex={props.historyIndex}
/>

View file

@ -0,0 +1,80 @@
import { act } from "@testing-library/react";
import { renderWithProviders } from "../../../util/test/render";
import {
getElementByTestId,
verifyNotPresentByTestId,
verifyNotPresentByText,
} from "../../../util/test/utils";
import { Chat } from "../Chat";
test("Chat apply scenarios: handle apply updates and display the accept / reject all buttons", async () => {
const { ideMessenger } = await renderWithProviders(<Chat />);
// Use queryByText which returns null when element isn't found
await verifyNotPresentByText("Accept All");
await verifyNotPresentByText("Reject All");
for (let i = 0; i < 5; i++) {
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "streaming",
streamId: `12345`,
});
}
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "done",
streamId: "12345",
});
// Wait for the buttons to appear
await getElementByTestId("accept-reject-all-buttons");
// IDE sends back message that it is done
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "closed",
streamId: "12345",
});
// Wait for the buttons to disappear
await verifyNotPresentByTestId("edit-accept-button");
await verifyNotPresentByTestId("edit-reject-button");
});
test("Chat apply scenarios: show apply cancellation", async () => {
const { ideMessenger } = await renderWithProviders(<Chat />);
// Spy on the request method of ideMessenger
const messengerPostSpy = vi.spyOn(ideMessenger, "post");
for (let i = 0; i < 5; i++) {
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "streaming",
streamId: `12345`,
});
}
// Wait for applying toolbar to appear
await getElementByTestId("notch-applying-text");
await act(async () => {
const cancelApplyButton = await getElementByTestId(
"notch-applying-cancel-button",
);
cancelApplyButton.click();
});
// Verify that rejectDiff message has been posted to ideMessenger
expect(messengerPostSpy).toHaveBeenCalledWith("rejectDiff", {});
// Now simulate the IDE sending back a message that the apply state is closed
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "closed",
streamId: "12345",
});
await verifyNotPresentByTestId("notch-applying-text");
await verifyNotPresentByTestId("notch-applying-cancel-button");
// Cleanup spy
messengerPostSpy.mockRestore();
});

View file

@ -0,0 +1,61 @@
import { act } from "@testing-library/react";
import { addAndSelectMockLlm } from "../../../util/test/config";
import { renderWithProviders } from "../../../util/test/render";
import {
getElementByTestId,
getElementByText,
sendInputWithMockedResponse,
} from "../../../util/test/utils";
import { Chat } from "../Chat";
test("should render input box", async () => {
await renderWithProviders(<Chat />);
await getElementByTestId("continue-input-box");
});
test("should be able to toggle modes", async () => {
await renderWithProviders(<Chat />);
await getElementByText("Chat");
// Simulate cmd+. keyboard shortcut to toggle modes
act(() => {
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: ".",
metaKey: true, // cmd key on Mac
}),
);
});
// Check that it switched to Agent mode
await getElementByText("Agent");
act(() => {
document.dispatchEvent(
new KeyboardEvent("keydown", {
key: ".",
metaKey: true, // cmd key on Mac
}),
);
});
await getElementByText("Chat");
});
test("should send a message and receive a response", async () => {
const { ideMessenger, store } = await renderWithProviders(<Chat />);
// First add and select the mock LLM
await act(async () => {
addAndSelectMockLlm(store, ideMessenger);
});
const CONTENT = "Expected response";
const INPUT = "User input";
await sendInputWithMockedResponse(ideMessenger, INPUT, [
{ role: "assistant", content: CONTENT },
]);
await getElementByText(CONTENT);
});

View file

@ -0,0 +1,231 @@
import { BuiltInToolNames } from "core/tools/builtIn";
import {
addAndSelectMockLlm,
triggerConfigUpdate,
} from "../../../util/test/config";
import { renderWithProviders } from "../../../util/test/render";
import { Chat } from "../Chat";
import { waitFor } from "@testing-library/dom";
import { ChatMessage } from "core";
import { toggleToolSetting } from "../../../redux/slices/uiSlice";
import {
getElementByTestId,
getElementByText,
sendInputWithMockedResponse,
verifyNotPresentByTestId,
} from "../../../util/test/utils";
const EDIT_WORKSPACE_DIR = "file:///workspace";
const EDIT_FILEPATH = "test.txt";
const EDIT_FILE_URI = `${EDIT_WORKSPACE_DIR}/${EDIT_FILEPATH}`;
const EDIT_CHANGES = "New content";
const EDIT_TOOL_CALL_ID = "known-id";
const EDIT_MESSAGES: ChatMessage[] = [
{
role: "assistant",
content: "",
toolCalls: [
{
id: EDIT_TOOL_CALL_ID,
function: {
name: BuiltInToolNames.EditExistingFile,
arguments: JSON.stringify({
filepath: EDIT_FILEPATH,
changes: EDIT_CHANGES,
}),
},
},
],
},
];
const POST_EDIT_RESPONSE = "Edit applied successfully";
beforeEach(() => {
vi.clearAllMocks();
});
test("Edit run with ask first policy and no auto apply", async () => {
// Setup
const { ideMessenger, store, user } = await renderWithProviders(<Chat />);
ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR];
const messengerPostSpy = vi.spyOn(ideMessenger, "post");
addAndSelectMockLlm(store, ideMessenger);
// Send the input that will respond with an edit tool call
await sendInputWithMockedResponse(
ideMessenger,
"Edit this file",
EDIT_MESSAGES,
);
// Toggle the codeblock and make sure the changes show
const toggleCodeblockChevron = await getElementByTestId("toggle-codeblock");
await user.click(toggleCodeblockChevron);
await getElementByText(EDIT_CHANGES);
// Pending tool call - find and click the accept button
const acceptToolCallButton = await getElementByTestId(
"accept-tool-call-button",
);
await user.click(acceptToolCallButton);
// Tool call, check that applyToFile was called for edit
await waitFor(() => {
expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", {
streamId: expect.any(String),
filepath: EDIT_FILE_URI,
text: EDIT_CHANGES,
toolCallId: EDIT_TOOL_CALL_ID,
});
});
// Extract stream ID and initiate mock streaming
const streamId = messengerPostSpy.mock.calls.find(
(call) => call[0] === "applyToFile",
)?.[1]?.streamId;
expect(streamId).toBeDefined();
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "streaming",
streamId,
toolCallId: EDIT_TOOL_CALL_ID,
filepath: EDIT_FILE_URI,
});
// Mid stream, should show applying in notch
await getElementByTestId("notch-applying-text");
await getElementByTestId("notch-applying-cancel-button");
// Close the stream
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "done",
streamId,
toolCallId: EDIT_TOOL_CALL_ID,
filepath: EDIT_FILE_URI,
});
// Verify accept/reject buttons are present
const acceptButton = await getElementByTestId("edit-accept-button");
await getElementByTestId("edit-reject-button");
// Accept the changes, which should trigger a response after the tool call
await user.click(acceptButton);
expect(messengerPostSpy).toHaveBeenCalledWith("acceptDiff", {
streamId,
filepath: EDIT_FILE_URI,
});
ideMessenger.setChatResponseText(POST_EDIT_RESPONSE);
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "closed",
streamId,
toolCallId: EDIT_TOOL_CALL_ID,
filepath: EDIT_FILE_URI,
});
await verifyNotPresentByTestId("edit-accept-button");
await verifyNotPresentByTestId("edit-reject-button");
await getElementByText(POST_EDIT_RESPONSE);
});
test("Edit run with no policy and yolo mode", async () => {
// Setup
const { ideMessenger, store, user } = await renderWithProviders(<Chat />);
ideMessenger.responses["getWorkspaceDirs"] = [EDIT_WORKSPACE_DIR];
const messengerPostSpy = vi.spyOn(ideMessenger, "post");
addAndSelectMockLlm(store, ideMessenger);
// Enable automatic edit and yolo mode
store.dispatch(toggleToolSetting(BuiltInToolNames.EditExistingFile));
triggerConfigUpdate({
store,
ideMessenger,
editConfig: (current) => {
current.ui = {
...current.ui,
autoAcceptEditToolDiffs: true, // Enable auto-accept for edit tool diffs
};
return current;
},
});
expect(store.getState().config.config.ui?.autoAcceptEditToolDiffs).toBe(true);
// Send the input that will respond with an edit tool call
await sendInputWithMockedResponse(
ideMessenger,
"Edit this file",
EDIT_MESSAGES,
);
// Toggle the codeblock and make sure the changes show
const toggleCodeblockChevron = await getElementByTestId("toggle-codeblock");
await user.click(toggleCodeblockChevron);
await getElementByText(EDIT_CHANGES);
// Make sure there's no pending tool call
verifyNotPresentByTestId("accept-tool-call-button");
// Tool call, check that applyToFile was called for edit
await waitFor(() => {
expect(messengerPostSpy).toHaveBeenCalledWith("applyToFile", {
streamId: expect.any(String),
filepath: EDIT_FILE_URI,
text: EDIT_CHANGES,
toolCallId: EDIT_TOOL_CALL_ID,
});
});
// Extract stream ID and initiate mock streaming
const streamId = messengerPostSpy.mock.calls.find(
(call) => call[0] === "applyToFile",
)?.[1]?.streamId;
expect(streamId).toBeDefined();
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "streaming",
streamId,
toolCallId: EDIT_TOOL_CALL_ID,
filepath: EDIT_FILE_URI,
});
// Mid stream, should show applying in notch
await getElementByTestId("notch-applying-text");
await getElementByTestId("notch-applying-cancel-button");
// Close the stream
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "done",
streamId,
toolCallId: EDIT_TOOL_CALL_ID,
filepath: EDIT_FILE_URI,
});
await waitFor(() => {
expect(messengerPostSpy).toHaveBeenCalledWith("acceptDiff", {
streamId,
filepath: EDIT_FILE_URI,
});
});
// Close the stream, ensure response is shown and diff buttons are not present
ideMessenger.setChatResponseText(POST_EDIT_RESPONSE);
ideMessenger.mockMessageToWebview("updateApplyState", {
status: "closed",
streamId,
toolCallId: EDIT_TOOL_CALL_ID,
filepath: EDIT_FILE_URI,
});
await verifyNotPresentByTestId("edit-accept-button");
await verifyNotPresentByTestId("edit-reject-button");
await getElementByText(POST_EDIT_RESPONSE);
});

View file

@ -657,7 +657,9 @@ export const selectApplyStateByToolCallId = createSelector(
(state: RootState, toolCallId?: string) => toolCallId,
],
(states, toolCallId) => {
return states.find((state) => state.toolCallId === toolCallId);
if (toolCallId) {
return states.find((state) => state.toolCallId === toolCallId);
}
},
);

View file

@ -23,11 +23,6 @@ import sessionReducer from "./slices/sessionSlice";
import tabsReducer from "./slices/tabsSlice";
import uiReducer from "./slices/uiSlice";
export interface ChatMessage {
role: "system" | "user" | "assistant";
content: string;
}
const rootReducer = combineReducers({
session: sessionReducer,
ui: uiReducer,

View file

@ -19,7 +19,6 @@ export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
async (_, { dispatch, extra, getState }) => {
const state = getState();
const toolCallState = selectCurrentToolCall(state);
if (!toolCallState) {
return;
}
@ -61,19 +60,15 @@ export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
) {
// Tool is called on client side
const {
output: clientToolOuput,
output: clientToolOutput,
respondImmediately,
errorMessage: clientToolError,
} = await callClientTool(toolCallState, {
dispatch,
ideMessenger: extra.ideMessenger,
streamId: state.session.codeBlockApplyStates.states.find(
(state) =>
state.toolCallId && state.toolCallId === toolCallState.toolCallId,
)?.streamId,
getState,
});
output = clientToolOuput;
output = clientToolOutput;
errorMessage = clientToolError;
streamResponse = respondImmediately;
} else {

View file

@ -17,6 +17,7 @@ import {
import {
newSession,
setActive,
setInactive,
setIsInEdit,
setMainEditorContentTrigger,
setMode,
@ -61,6 +62,8 @@ export const streamEditThunk = createAsyncThunk<
range: codeToEdit[0] as RangeInFileWithContents,
});
dispatch(setInactive());
if (response.status === "error") {
throw new Error(response.error);
}

View file

@ -8,6 +8,8 @@ import { selectSelectedChatModel } from "../slices/configSlice";
import {
abortStream,
addPromptCompletionPair,
setActive,
setInactive,
setToolGenerated,
streamUpdate,
} from "../slices/sessionSlice";
@ -53,6 +55,8 @@ export const streamNormalInput = createAsyncThunk<
};
}
dispatch(setActive());
// Send request
const gen = extra.ideMessenger.llmStreamChat(
{
@ -76,6 +80,8 @@ export const streamNormalInput = createAsyncThunk<
next = await gen.next();
}
dispatch(setInactive());
// Attach prompt log and end thinking for reasoning models
if (next.done && next.value) {
dispatch(addPromptCompletionPair([next.value]));

View file

@ -4,11 +4,7 @@ import { constructMessages } from "core/llm/constructMessages";
import { renderContextItems } from "core/util/messageContent";
import { getBaseSystemMessage } from "../../util";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
addContextItemsAtIndex,
setActive,
streamUpdate,
} from "../slices/sessionSlice";
import { addContextItemsAtIndex, streamUpdate } from "../slices/sessionSlice";
import { ThunkApiType } from "../store";
import { findToolCall } from "../util";
import { resetStateForNewMessage } from "./resetStateForNewMessage";
@ -63,8 +59,6 @@ export const streamResponseAfterToolCall = createAsyncThunk<
}),
);
dispatch(setActive());
const updatedHistory = getState().session.history;
const messageMode = getState().session.mode;

View file

@ -1,6 +1,5 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import StreamErrorDialog from "../../pages/gui/StreamError";
import { setInactive } from "../slices/sessionSlice";
import { setDialogMessage, setShowDialog } from "../slices/uiSlice";
import { ThunkApiType } from "../store";
import { cancelStream } from "./cancelStream";
@ -22,7 +21,6 @@ export const streamThunkWrapper = createAsyncThunk<
}),
);
}
dispatch(setInactive());
} catch (e) {
dispatch(cancelStream());
dispatch(setDialogMessage(<StreamErrorDialog error={e} />));

View file

@ -8,7 +8,6 @@ export interface ClientToolExtras {
getState: () => RootState;
dispatch: AppThunkDispatch;
ideMessenger: IIdeMessenger;
streamId?: string;
}
export interface ClientToolOutput {

View file

@ -1,14 +1,11 @@
import { resolveRelativePathInDir } from "core/util/ideUtils";
import { v4 as uuid } from "uuid";
import { ClientToolImpl } from "./callClientTool";
export const editToolImpl: ClientToolImpl = async (
args,
toolCallId,
extras,
) => {
if (!extras.streamId) {
throw new Error("Invalid apply state");
}
const firstUriMatch = await resolveRelativePathInDir(
args.filepath,
extras.ideMessenger.ide,
@ -16,30 +13,14 @@ export const editToolImpl: ClientToolImpl = async (
if (!firstUriMatch) {
throw new Error(`${args.filepath} does not exist`);
}
const apply = await extras.ideMessenger.request("applyToFile", {
streamId: extras.streamId,
const streamId = uuid();
extras.ideMessenger.post("applyToFile", {
streamId,
text: args.changes,
toolCallId,
filepath: firstUriMatch,
});
if (apply.status === "error") {
throw new Error(apply.error);
}
const state = extras.getState();
const autoAccept = !!state.config.config.ui?.autoAcceptEditToolDiffs;
if (autoAccept) {
const out = await extras.ideMessenger.request("acceptDiff", {
streamId: extras.streamId,
filepath: firstUriMatch,
});
if (out.status === "error") {
throw new Error(out.error);
}
return {
respondImmediately: true,
output: undefined, // TODO - feed edit results back to model (also in parallel listeners)
};
}
return {
respondImmediately: false,
output: undefined, // No immediate output.

View file

@ -1,12 +1,12 @@
import { MessageModes, ModelDescription } from "core";
import { ProfileDescription } from "core/config/ProfileLifecycleManager";
import _ from "lodash";
import { KeyboardEvent } from "react";
import { getLocalStorage } from "./localStorage";
import {
DEFAULT_CHAT_SYSTEM_MESSAGE,
DEFAULT_AGENT_SYSTEM_MESSAGE,
DEFAULT_CHAT_SYSTEM_MESSAGE,
} from "core/llm/constructMessages";
import _ from "lodash";
import { KeyboardEvent as ReactKeyboardEvent } from "react";
import { getLocalStorage } from "./localStorage";
export type Platform = "mac" | "linux" | "windows" | "unknown";
@ -26,7 +26,7 @@ export function getPlatform(): Platform {
export function isMetaEquivalentKeyPressed({
metaKey,
ctrlKey,
}: KeyboardEvent): boolean {
}: KeyboardEvent | ReactKeyboardEvent): boolean {
const platform = getPlatform();
switch (platform) {
case "mac":

View file

@ -0,0 +1,67 @@
import { EnhancedStore } from "@reduxjs/toolkit";
import { BrowserSerializedContinueConfig, ModelDescription } from "core";
import { SerializedOrgWithProfiles } from "core/config/ProfileLifecycleManager";
import { copyOf } from "core/util";
import { MockIdeMessenger } from "../../context/MockIdeMessenger";
interface TestConfigUpdateParams {
store: EnhancedStore;
ideMessenger: MockIdeMessenger;
newProfileId?: string;
newOrgId?: string;
newOrgs?: SerializedOrgWithProfiles[];
editConfig?: (
current: BrowserSerializedContinueConfig,
) => BrowserSerializedContinueConfig;
}
export function triggerConfigUpdate({
store,
ideMessenger,
editConfig,
newOrgs,
newOrgId,
newProfileId,
}: TestConfigUpdateParams) {
const state = store.getState();
ideMessenger.mockMessageToWebview("configUpdate", {
organizations: newOrgs ?? state.profiles.organizations,
selectedOrgId: newOrgId ?? state.profiles.selectedOrganizationId,
profileId: newProfileId ?? state.profiles.selectedProfileId,
result: {
config: editConfig
? editConfig(copyOf(state.config.config))
: state.config.config,
configLoadInterrupted: false,
errors: [],
},
});
}
export function addAndSelectChatModel(
store: EnhancedStore,
ideMessenger: MockIdeMessenger,
llmDesc: ModelDescription,
) {
triggerConfigUpdate({
store,
ideMessenger,
editConfig(current) {
current.modelsByRole.chat.push(llmDesc);
current.selectedModelByRole.chat = llmDesc;
return current;
},
});
}
export function addAndSelectMockLlm(
store: EnhancedStore,
ideMessenger: MockIdeMessenger,
) {
addAndSelectChatModel(store, ideMessenger, {
model: "mock",
provider: "mock",
title: "Mock LLM",
underlyingProviderName: "mock",
});
}

102
gui/src/util/test/utils.ts Normal file
View file

@ -0,0 +1,102 @@
import { screen, waitFor } from "@testing-library/dom";
import { act } from "@testing-library/react";
import { Editor } from "@tiptap/core";
import { ChatMessage } from "core";
import { MockIdeMessenger } from "../../context/MockIdeMessenger";
function logDomText() {
const bodyText = document.body.innerHTML;
const parser = new DOMParser();
const doc = parser.parseFromString(bodyText, "text/html");
let cleaned = doc.body.textContent ?? "";
cleaned = cleaned?.replace(
"No resultsAaModelsRulesDocsPromptsToolsMCPCreate your first assistant",
"",
);
cleaned = cleaned?.replace(
"Alt⏎ Active file⏎ Enter⏎Log in to access a free trial of theModels Add-OnLog in to Continue HubOr, configure your own models",
"",
);
cleaned = cleaned.replaceAll("Select model", "");
cleaned = cleaned.replaceAll("Mock LLM", "");
cleaned = cleaned.replaceAll(/^Chat|Chat$/g, "");
console.log(cleaned || "No body content");
}
export function logAllTestIds() {
const elements = document.querySelectorAll("*");
const testIds = Array.from(elements)
.map((el) => Array.from(el.attributes))
.flat()
.filter((a) => a.name === "data-testid")
.map((a) => a.value);
console.log("Available test ids", testIds);
}
export async function getElementByTestId(testId: string): Promise<HTMLElement> {
try {
const testIdElement = await waitFor(() => screen.findByTestId(testId));
expect(testIdElement).toBeInTheDocument();
return testIdElement;
} catch (e) {
logAllTestIds();
throw new Error(`Element with testId "${testId}" not found`);
}
}
export async function verifyNotPresentByTestId(testId: string): Promise<void> {
const element = await waitFor(() => screen.queryByTestId(testId));
expect(element).not.toBeInTheDocument();
}
export async function verifyNotPresentByText(text: string): Promise<void> {
const element = screen.queryByText(text);
expect(element).not.toBeInTheDocument();
}
export async function getElementByText(text: string): Promise<HTMLElement> {
try {
const textElement = await waitFor(() => screen.findByText(text));
expect(textElement).toBeInTheDocument();
return textElement;
} catch (e) {
logDomText();
throw new Error(`Element with text "${text}" not found.`);
}
}
export async function getMainEditor(): Promise<Editor> {
const editorElement = await getElementByTestId("editor-input-main");
if ("editor" in editorElement) {
return editorElement.editor as Editor;
} else {
throw new Error("Main editor not found within editor container");
}
}
export async function sendInputWithMockedResponse(
ideMessenger: MockIdeMessenger,
input: string,
response: ChatMessage[],
): Promise<void> {
// Setup the mock response before any actions
ideMessenger.chatResponse = response;
// Wait for the editor to be in the document
const editor = await getMainEditor();
// Find the submit button
const sendButton = await getElementByTestId("submit-input-button");
// Insert content into the editor
await act(async () => {
editor.commands.insertContent(input);
});
await getElementByText(input);
// Click the send button
await act(async () => {
sendButton.click();
});
}

View file

@ -32,5 +32,18 @@ export default defineConfig({
globals: true,
environment: "jsdom",
setupFiles: "./src/util/test/setupTests.ts",
onConsoleLog(log, type) {
if (type === "stderr") {
if (
[
"contentEditable",
"An update to Chat inside a test was not wrapped in act",
].some((text) => log.includes(text))
) {
return false;
}
}
return true;
},
},
});

View file

@ -1,12 +1,12 @@
{
"name": "@continuedev/config-yaml",
"version": "1.0.94",
"version": "1.0.95",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "@continuedev/config-yaml",
"version": "1.0.94",
"version": "1.0.95",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",

13
scripts/build-packages.ps1 Executable file
View file

@ -0,0 +1,13 @@
Push-Location packages
Push-Location "openai-adapters"
npm ci
npm run build
Pop-Location
Push-Location "config-yaml"
npm ci
npm run build
Pop-Location
Pop-Location

13
scripts/build-packages.sh Executable file
View file

@ -0,0 +1,13 @@
# Build @continuedev packages for monorepo style linking
cd packages
cd openai-adapters
npm ci
npm run build
cd ..
cd config-yaml
npm ci
npm run build

View file

@ -57,7 +57,7 @@ pushd extensions/vscode
# This does way too many things inline but is the common denominator between many of the scripts
npm install
npm link @continuedev/core
npm run prepackage
# npm run prepackage # not required since npm run package has prescript of prepackage
npm run package
popd