Merge branch 'main' into current-file

This commit is contained in:
uinstinct 2025-05-20 14:19:33 +05:30
commit a5f7d556b4
91 changed files with 2154 additions and 954 deletions

View file

@ -0,0 +1,15 @@
name: IntelliJ Plugin Test Execution
version: 0.0.1
schema: v1
rules:
- name: IntelliJ Plugin Test Execution
rule: |-
Run IntelliJ plugin tests using Gradle with the fully qualified test class or method name:
```bash
# Run test class
./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest"
# Run specific test method
./gradlew test --tests "com.github.continuedev.continueintellijextension.unit.ApplyToFileHandlerTest.should*"
```
globs: extensions/intellij/**/*Test.kt

View file

@ -0,0 +1,10 @@
name: IntelliJ Test Standards
version: 0.0.1
schema: v1
rules:
- name: IntelliJ Test Standards
rule: When writing tests for the IntelliJ plugin, use the mockk library for
mocking. Prefer mockk's idiomatic syntax for creating and verifying mocks.
Always structure tests with clear Arrange-Act-Assert patterns and use
descriptive test names that indicate the scenario being tested.
globs: "**/test/**/*.kt"

View file

@ -0,0 +1,30 @@
name: unit-testing-rules
version: 0.0.1
schema: v1
rules:
- name: unit-testing-rules
rule: >-
For unit testing in this project:
1. The project uses Jest as the testing framework
2. Run tests using `npm test` from within the specific package/module
directory
3. Command structure: `cd [directory] && npm test -- [test file path]`
4. The test script uses experimental VM modules via NODE_OPTIONS flag
5. Test files follow the pattern `*.test.ts`
6. Tests must import Jest with `import { jest } from "@jest/globals";`
7. Run tests from within the specific package directory (e.g., `cd core`
for core module tests)
8. Write tests as top-level `test()` functions - DO NOT use `describe()`
blocks
9. Include the function name being tested in the test description for
clarity

29
.github/workflows/cla.yaml vendored Normal file
View file

@ -0,0 +1,29 @@
name: "CLA Assistant"
on:
issue_comment:
types: [ created ]
pull_request_target:
types: [ opened, closed, synchronize ]
permissions:
actions: write
contents: write
pull-requests: write
statuses: write
jobs:
CLAAssistant:
runs-on: ubuntu-latest
# Only run this workflow on the main repository (continuedev/continue)
if: github.repository == 'continuedev/continue'
steps:
- name: "CLA Assistant"
if: (contains(github.event.comment.body, 'recheck') || contains(github.event.comment.body, 'I have read the CLA Document and I hereby sign the CLA')) || github.event_name == 'pull_request_target'
uses: contributor-assistant/github-action@v2.6.1
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
path-to-signatures: "signatures/version1/cla.json"
path-to-document: "https://github.com/continuedev/continue/blob/main/docs/docs/CLA.md"
branch: cla-signatures
allowlist: dependabot[bot]

View file

@ -63,7 +63,7 @@ jobs:
- name: Bump version in gradle.properties
run: |
cd extensions/intelllij
cd extensions/intellij
awk '/pluginVersion=/{split($0,a,"="); split(a[2],b,"."); b[3]+=1; printf "%s=%s.%s.%s\n",a[1],b[1],b[2],b[3];next}1' gradle.properties > tmp && mv tmp gradle.properties
rm -rf tmp
NEW_VERSION=$(grep 'pluginVersion=' gradle.properties | cut -d'=' -f2)

View file

@ -235,10 +235,11 @@ jobs:
cd packages/config-yaml
npm run build
- name: Type check
- name: Type check and lint
run: |
cd gui
npx tsc --noEmit
npm run lint
binary-checks:
needs: [install-root, install-core, install-config-yaml]

3
.gitignore vendored
View file

@ -162,5 +162,8 @@ extensions/.continue-debug/
*.vsix
# intellij module library files
*.iml
.continuerules
**/.continue/assistants/

6
.idea/jsLinters/eslint.xml generated Normal file
View file

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="EslintConfiguration">
<option name="fix-on-save" value="true" />
</component>
</project>

1
.idea/prettier.xml generated
View file

@ -2,5 +2,6 @@
<project version="4">
<component name="PrettierConfiguration">
<option name="myConfigurationMode" value="AUTOMATIC" />
<option name="myRunOnSave" value="true" />
</component>
</project>

View file

@ -3,44 +3,49 @@
## Table of Contents
- [Contributing to Continue](#contributing-to-continue)
- [Table of Contents](#table-of-contents)
- [Table of Contents](#table-of-contents)
- [❤️ Ways to Contribute](#️-ways-to-contribute)
- [👋 Continue Contribution Ideas](#-continue-contribution-ideas)
- [🐛 Report Bugs](#-report-bugs)
- [✨ Suggest Enhancements](#-suggest-enhancements)
- [📖 Updating / Improving Documentation](#-updating--improving-documentation)
- [Running the Documentation Server Locally](#running-the-documentation-server-locally)
- [Method 1: NPM Script](#method-1-npm-script)
- [Method 2: VS Code Task](#method-2-vs-code-task)
- [🧑‍💻 Contributing Code](#-contributing-code)
- [Environment Setup](#environment-setup)
- [Pre-requisites](#pre-requisites)
- [Fork the Continue Repository](#fork-the-continue-repository)
- [VS Code](#vs-code)
- [Debugging](#debugging)
- [JetBrains](#jetbrains)
- [Our Git Workflow](#our-git-workflow)
- [Development workflow](#development-workflow)
- [Formatting](#formatting)
- [Testing](#testing)
- [Review Process](#review-process)
- [Getting help](#getting-help)
- [Contribtuing new LLM Providers/Models](#contribtuing-new-llm-providersmodels)
- [Adding an LLM Provider](#adding-an-llm-provider)
- [Adding Models](#adding-models)
- [📐 Continue Architecture](#-continue-architecture)
- [Continue VS Code Extension](#continue-vs-code-extension)
- [Continue JetBrains Extension](#continue-jetbrains-extension)
- [👋 Continue Contribution Ideas](#-continue-contribution-ideas)
- [🐛 Report Bugs](#-report-bugs)
- [✨ Suggest Enhancements](#-suggest-enhancements)
- [📖 Updating / Improving Documentation](#-updating--improving-documentation)
- [Running the Documentation Server Locally](#running-the-documentation-server-locally)
- [Method 1: NPM Script](#method-1-npm-script)
- [Method 2: VS Code Task](#method-2-vs-code-task)
- [🧑‍💻 Contributing Code](#-contributing-code)
- [Environment Setup](#environment-setup)
- [Pre-requisites](#pre-requisites)
- [Fork the Continue Repository](#fork-the-continue-repository)
- [VS Code](#vs-code)
- [Debugging](#debugging)
- [JetBrains](#jetbrains)
- [Our Git Workflow](#our-git-workflow)
- [Development workflow](#development-workflow)
- [Formatting](#formatting)
- [Testing](#testing)
- [Review Process](#review-process)
- [Getting help](#getting-help)
- [Contribtuing new LLM Providers/Models](#contribtuing-new-llm-providersmodels)
- [Adding an LLM Provider](#adding-an-llm-provider)
- [Adding Models](#adding-models)
- [📐 Continue Architecture](#-continue-architecture)
- [Continue VS Code Extension](#continue-vs-code-extension)
- [Continue JetBrains Extension](#continue-jetbrains-extension)
- [Contibutor License Agreement](#contributor-license-agreement-cla)
# ❤️ Ways to Contribute
## 👋 Continue Contribution Ideas
[This GitHub project board](https://github.com/orgs/continuedev/projects/2) is a list of ideas for how you can contribute to Continue. These aren't the only ways, but are a great starting point if you are new to the project. You can also browse the list of [good first issues](https://github.com/continuedev/continue/issues?q=is:issue%20state:open%20label:good-first-issue).
[This GitHub project board](https://github.com/orgs/continuedev/projects/2) is a list of ideas for how you can
contribute to Continue. These aren't the only ways, but are a great starting point if you are new to the project. You
can also browse the list
of [good first issues](https://github.com/continuedev/continue/issues?q=is:issue%20state:open%20label:good-first-issue).
## 🐛 Report Bugs
If you find a bug, please [create an issue](https://github.com/continuedev/continue/issues) to report it! A great bug report includes:
If you find a bug, please [create an issue](https://github.com/continuedev/continue/issues) to report it! A great bug
report includes:
- A description of the bug
- Steps to reproduce
@ -50,19 +55,22 @@ If you find a bug, please [create an issue](https://github.com/continuedev/conti
## ✨ Suggest Enhancements
Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest an enhancement are:
Continue is quickly adding features, and we'd love to hear which are the most important to you. The best ways to suggest
an enhancement are:
- Create an issue
- First, check whether a similar proposal has already been made
- If not, [create an issue](https://github.com/continuedev/continue/issues)
- Please describe the enhancement in as much detail as you can, and why it would be useful
- First, check whether a similar proposal has already been made
- If not, [create an issue](https://github.com/continuedev/continue/issues)
- Please describe the enhancement in as much detail as you can, and why it would be useful
- Join the [Continue Discord](https://discord.gg/NWtdYexhMs) and tell us about your idea in the `#feedback` channel
## 📖 Updating / Improving Documentation
Continue is continuously improving, but a feature isn't complete until it is reflected in the documentation! If you see something out-of-date or missing, you can help by clicking "Edit this page" at the bottom of any page on [docs.continue.dev](https://docs.continue.dev).
Continue is continuously improving, but a feature isn't complete until it is reflected in the documentation! If you see
something out-of-date or missing, you can help by clicking "Edit this page" at the bottom of any page
on [docs.continue.dev](https://docs.continue.dev).
### Running the Documentation Server Locally
@ -70,7 +78,8 @@ You can run the documentation server locally using either of the following metho
#### Method 1: NPM Script
1. Open your terminal and navigate to the `docs` subdirectory of the project. The `docusaurus.config.js` file you'll see there is a sign you're in the right place.
1. Open your terminal and navigate to the `docs` subdirectory of the project. The `docusaurus.config.js` file you'll see
there is a sign you're in the right place.
2. Run the following command to install the necessary dependencies for the documentation server:
@ -92,17 +101,22 @@ You can run the documentation server locally using either of the following metho
3. Look for the `docs:start` task and select it.
This will start a local server and you can see the documentation rendered in your default browser, typically accessible at `http://localhost:3000`.
This will start a local server and you can see the documentation rendered in your default browser, typically accessible
at `http://localhost:3000`.
## 🧑‍💻 Contributing Code
We welcome contributions from developers of all experience levels - from first-time contributors to seasoned open source maintainers. While we aim to maintain high standards for reliability and maintainability, our goal is to keep the process as welcoming and straightforward as possible.
We welcome contributions from developers of all experience levels - from first-time contributors to seasoned open source
maintainers. While we aim to maintain high standards for reliability and maintainability, our goal is to keep the
process as welcoming and straightforward as possible.
### Environment Setup
#### Pre-requisites
You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct version of Node.js for this project by running the following command in the root of the project:
You should have Node.js version 20.19.0 (LTS) or higher installed. You can get it
on [nodejs.org](https://nodejs.org/en/download) or, if you are using NVM (Node Version Manager), you can set the correct
version of Node.js for this project by running the following command in the root of the project:
```bash
nvm use
@ -114,32 +128,39 @@ nvm use
2. Clone your forked repository to your local machine. Use: `git clone https://github.com/YOUR_USERNAME/continue.git`
3. Navigate to the cloned directory and make sure you are on the main branch. Create your feature/fix branch from there, like so: `git checkout -b 123-my-feature-branch`
3. Navigate to the cloned directory and make sure you are on the main branch. Create your feature/fix branch from there,
like so: `git checkout -b 123-my-feature-branch`
4. Send your pull request to the main branch.
#### VS Code
1. Open the VS Code command pallet (`cmd/ctrl+shift+p`) and select `Tasks: Run Task` and then select `install-all-dependencies`
1. Open the VS Code command pallet (`cmd/ctrl+shift+p`) and select `Tasks: Run Task` and then select
`install-all-dependencies`
2. Start debugging:
1. Switch to Run and Debug view
2. Select `Launch extension` from drop down
3. Hit play button
4. This will start the extension in debug mode and open a new VS Code window with it installed
1. The new VS Code window with the extension is referred to as the _Host VS Code_
2. The window you started debugging from is referred to as the _Main VS Code_
1. Switch to Run and Debug view
2. Select `Launch extension` from drop down
3. Hit play button
4. This will start the extension in debug mode and open a new VS Code window with it installed
1. The new VS Code window with the extension is referred to as the _Host VS Code_
2. The window you started debugging from is referred to as the _Main VS Code_
3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which you can install by right-clicking and selecting "Install Extension VSIX".
3. To package the extension, run `npm run package` in the `extensions/vscode` directory, select `Tasks: Run Task` and
then select `vscode-extension:package`. This will generate `extensions/vscode/build/continue-{VERSION}.vsix`, which
you can install by right-clicking and selecting "Install Extension VSIX".
##### Debugging
**Breakpoints** can be used in both the `core` and `extensions/vscode` folders while debugging, but are not currently supported inside of `gui` code.
**Breakpoints** can be used in both the `core` and `extensions/vscode` folders while debugging, but are not currently
supported inside of `gui` code.
**Hot-reloading** is enabled with Vite, so if you make any changes to the `gui`, they should be automatically reflected without rebuilding. In some cases, you may need to refresh the _Host VS Code_ window to see the changes.
**Hot-reloading** is enabled with Vite, so if you make any changes to the `gui`, they should be automatically reflected
without rebuilding. In some cases, you may need to refresh the _Host VS Code_ window to see the changes.
Similarly, any changes to `core` or `extensions/vscode` will be automatically included by just reloading the _Host VS Code_ window with cmd/ctrl+shift+p "Reload Window".
Similarly, any changes to `core` or `extensions/vscode` will be automatically included by just reloading the _Host VS
Code_ window with cmd/ctrl+shift+p "Reload Window".
#### JetBrains
@ -147,13 +168,20 @@ See [`intellij/CONTRIBUTING.md`](./extensions/intellij/CONTRIBUTING.md) for the
### Our Git Workflow
We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the `main` branch titled `v1.1.x-vscode`, which automatically triggers the workflow in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When a release has been sufficiently tested, we will create a new release titled `v1.0x-vscode`, triggering a similar workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow is well explained by <http://releaseflow.org>.
We keep a single permanent branch: `main`. When we are ready to create a "pre-release" version, we create a tag on the
`main` branch titled `v1.1.x-vscode`, which automatically triggers the workflow
in [preview.yaml](./.github/workflows/preview.yaml), which builds and releases a version of the VS Code extension. When
a release has been sufficiently tested, we will create a new release titled `v1.0x-vscode`, triggering a similar
workflow in [main.yaml](./.github/workflows/main.yaml), which will build and release a main release of the VS Code
extension. Any hotfixes can be made by creating a feature branch from the tag for the release in question. This workflow
is well explained by <http://releaseflow.org>.
### What makes a good PR?
To keep the Continue codebase clean and maintainable, we expect the following from our own team and all contributors:
- Open a new issue or comment on an existing one before writing code. This ensures your proposed changes are aligned with the project direction
- Open a new issue or comment on an existing one before writing code. This ensures your proposed changes are aligned
with the project direction
- Keep changes focused. Multiple unrelated fixes should be opened as separate PRs
- Write or update tests for new functionality
- Update relevant documentation in the `docs` folder
@ -161,18 +189,22 @@ To keep the Continue codebase clean and maintainable, we expect the following fr
### Formatting
Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
Continue uses [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) to format
JavaScript/TypeScript. Please install the Prettier extension in VS Code and enable "Format on Save" in your settings.
### Testing
We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we merge.
We have a mix of unit, functional, and e2e test suites, with a primary focus on functional testing. These tests run on
each pull request. If your PR causes one of these tests to fail, we will ask that you to resolve the issue before we
merge.
When contributing, please update or create the appropriate tests to help verify the correctness of your implementaiton.
### Review Process
- **Initial Review** - A maintainer will be assigned as primary reviewer
- **Feedback Loop** - The reviewer may request changes. We value your work, but also want to ensure the code is maintainable and follows our patterns.
- **Feedback Loop** - The reviewer may request changes. We value your work, but also want to ensure the code is
maintainable and follows our patterns.
- **Approval & Merge** - Once the PR is approved, it will be merged into the `main` branch.
### Getting help
@ -183,19 +215,53 @@ Join [#contribute on Discord](https://discord.gg/vapESyrFmJ) to engage with main
### Adding an LLM Provider
Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI, Ollama, Together, LM Studio, Msty, and more. You can find all of the existing providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can add it with the following steps:
Continue has support for more than a dozen different LLM "providers", making it easy to use models running on OpenAI,
Ollama, Together, LM Studio, Msty, and more. You can find all of the existing
providers [here](https://github.com/continuedev/continue/tree/main/core/llm/llms), and if you see one missing, you can
add it with the following steps:
1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a good simple example.
1. Create a new file in the `core/llm/llms` directory. The name of the file should be the name of the provider, and it
should export a class that extends `BaseLLM`. This class should contain the following minimal implementation. We
recommend viewing pre-existing providers for more details. The [LlamaCpp Provider](./core/llm/llms/LlamaCpp.ts) is a
good simple example.
2. Add your provider to the `LLMs` array in [core/llm/llms/index.ts](./core/llm/llms/index.ts).
3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array in [core/llm/autodetect.ts](./core/llm/autodetect.ts).
4. Add a documentation page for your provider in [`docs/docs/customize/model-providers/more`](./docs/docs/customize/model-providers/more). This should show an example of configuring your provider in `config.yaml` and explain what options are available.
3. If your provider supports images, add it to the `PROVIDER_SUPPORTS_IMAGES` array
in [core/llm/autodetect.ts](./core/llm/autodetect.ts).
4. Add a documentation page for your provider in [
`docs/docs/customize/model-providers/more`](./docs/docs/customize/model-providers/more). This should show an example
of configuring your provider in `config.yaml` and explain what options are available.
### Adding Models
While any model that works with a supported provider can be used with Continue, we keep a list of recommended models that can be automatically configured from the UI or `config.json`. The following files should be updated when adding a model:
While any model that works with a supported provider can be used with Continue, we keep a list of recommended models
that can be automatically configured from the UI or `config.json`. The following files should be updated when adding a
model:
- [AddNewModel page](./gui/src/pages/AddNewModel/configs/) - This directory defines which model options are shown in the side bar model selection UI. To add a new model:
1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts), following the lead of the many examples near the top of the file
2. Add the model within its provider's array to [configs/providers.ts](./gui/src/pages/AddNewModel/configs/providers.ts) (add provider if needed)
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts), and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
- [Prompt Templates](./core/llm/autodetect.ts) - In this file you'll find the `autodetectTemplateType` function. Make sure that for the model name you just added, this function returns the correct template type. This is assuming that the chat template for that model is already built in Continue. If not, you will have to add the template type and corresponding edit and chat templates.
- [AddNewModel page](./gui/src/pages/AddNewModel/configs/) - This directory defines which model options are shown in the
side bar model selection UI. To add a new model:
1. Add a `ModelPackage` entry for the model into [configs/models.ts](./gui/src/pages/AddNewModel/configs/models.ts),
following the lead of the many examples near the top of the file
2. Add the model within its provider's array
to [configs/providers.ts](./gui/src/pages/AddNewModel/configs/providers.ts) (add provider if needed)
- LLM Providers: Since many providers use their own custom strings to identify models, you'll have to add the
translation from Continue's model name (the one you added to `index.d.ts`) and the model string for each of these
providers: [Ollama](./core/llm/llms/Ollama.ts), [Together](./core/llm/llms/Together.ts),
and [Replicate](./core/llm/llms/Replicate.ts). You can find their full model lists
here: [Ollama](https://ollama.ai/library), [Together](https://docs.together.ai/docs/inference-models), [Replicate](https://replicate.com/collections/streaming-language-models).
- [Prompt Templates](./core/llm/autodetect.ts) - In this file you'll find the `autodetectTemplateType` function. Make
sure that for the model name you just added, this function returns the correct template type. This is assuming that
the chat template for that model is already built in Continue. If not, you will have to add the template type and
corresponding edit and chat templates.
## Contributor License Agreement (CLA)
We require all contributors to accept the CLA and have made it as easy as commenting on your PR:
1. Open your pull request.
2. Paste the following comment (or reply `recheck` if you’ve signed before):
```text
I have read the CLA Document and I hereby sign the CLA
```
3. The CLA‑Assistant bot records your signature in the repo and marks the status check as passed.

View file

@ -64,7 +64,7 @@ async function buildWithEsbuild() {
format: "cjs",
platform: "node",
sourcemap: true,
minify: true,
minify: !esbuildOnly,
treeShaking: true,
loader: {
// eslint-disable-next-line @typescript-eslint/naming-convention

View file

@ -33,6 +33,7 @@
"@types/jest": "^29.5.12",
"@types/uuid": "^9.0.8",
"@vercel/ncc": "^0.38.1",
"cross-env": "^7.0.3",
"esbuild": "0.19.11",
"jest": "^29.7.0",
"pkg": "^5.8.1",
@ -3196,6 +3197,25 @@
"node": "^14.15.0 || ^16.10.0 || >=18.0.0"
}
},
"node_modules/cross-env": {
"version": "7.0.3",
"resolved": "https://registry.npmjs.org/cross-env/-/cross-env-7.0.3.tgz",
"integrity": "sha512-+/HKd6EgcQCJGh2PSjZuUitQBQynKor4wrFbRg4DtAgS1aWO+gU52xpH7M9ScGgXSYmAVS9bIJ8EzuaGw0oNAw==",
"dev": true,
"license": "MIT",
"dependencies": {
"cross-spawn": "^7.0.1"
},
"bin": {
"cross-env": "src/bin/cross-env.js",
"cross-env-shell": "src/bin/cross-env-shell.js"
},
"engines": {
"node": ">=10.14",
"npm": ">=6",
"yarn": ">=1"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",

View file

@ -33,6 +33,7 @@
"@types/jest": "^29.5.12",
"@types/uuid": "^9.0.8",
"@vercel/ncc": "^0.38.1",
"cross-env": "^7.0.3",
"esbuild": "0.19.11",
"jest": "^29.7.0",
"pkg": "^5.8.1",

View file

@ -71,6 +71,21 @@ const qwenCoderFimTemplate: AutocompleteTemplate = {
},
};
const seedCoderFimTemplate: AutocompleteTemplate = {
template: "<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
completionOptions: {
stop: [
"<[end▁of▁sentence]>",
"<[fim-prefix]>",
"<[fim-middle]>",
"<[fim-suffix]>",
"<[PAD▁TOKEN]>",
"<[SEP▁TOKEN]>",
"<[begin▁of▁sentence]>",
],
},
};
const codestralFimTemplate: AutocompleteTemplate = {
template: "[SUFFIX]{{{suffix}}}[PREFIX]{{{prefix}}}",
completionOptions: {
@ -426,6 +441,10 @@ export function getTemplateForModel(model: string): AutocompleteTemplate {
return qwenCoderFimTemplate;
}
if (lowerCaseModel.includes("seed") && lowerCaseModel.includes("coder")) {
return seedCoderFimTemplate;
}
if (
lowerCaseModel.includes("starcoder") ||
lowerCaseModel.includes("star-coder") ||

View file

@ -255,7 +255,7 @@ export class ConfigHandler {
if (currentProfile) {
this.globalContext.update("lastSelectedProfileForWorkspace", {
...selectedProfiles,
[profileKey]: selectedProfiles.id ?? null,
[profileKey]: currentProfile.profileDescription.id,
});
}

50
core/index.d.ts vendored
View file

@ -197,15 +197,14 @@ export interface CustomContextProvider {
description?: string;
renderInlineAs?: string;
type?: ContextProviderType;
loadSubmenuItems?: (
args: LoadSubmenuItemsArgs,
) => Promise<ContextSubmenuItem[]>;
getContextItems(
query: string,
extras: ContextProviderExtras,
): Promise<ContextItem[]>;
loadSubmenuItems?: (
args: LoadSubmenuItemsArgs,
) => Promise<ContextSubmenuItem[]>;
}
export interface ContextSubmenuItem {
@ -459,6 +458,7 @@ export interface ChatHistoryItem {
toolCallState?: ToolCallState;
isGatheringContext?: boolean;
reasoning?: Reasoning;
appliedRules?: RuleWithSource[];
}
export interface LLMFullCompletionOptions extends BaseCompletionOptions {
@ -1168,6 +1168,7 @@ export interface MCPResource {
description?: string;
mimeType?: string;
}
export interface MCPTool {
name: string;
description?: string;
@ -1230,6 +1231,27 @@ export interface ApplyState {
toolCallId?: string;
}
export interface StreamDiffLinesPayload {
prefix: string;
highlighted: string;
suffix: string;
input: string;
language: string | undefined;
modelTitle: string | undefined;
includeRulesInSystemMessage: boolean;
}
export interface HighlightedCodePayload {
rangeInFileWithContents: RangeInFileWithContents;
prompt?: string;
shouldRun?: boolean;
}
export interface AcceptOrRejectDiffPayload {
filepath: string;
streamId?: string;
}
export interface RangeInFileWithContents {
filepath: string;
range: {
@ -1239,7 +1261,7 @@ export interface RangeInFileWithContents {
contents: string;
}
export type CodeToEdit = RangeInFileWithContents | FileWithContents;
export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
/**
* Represents the configuration for a quick action in the Code Lens.
@ -1498,17 +1520,19 @@ export interface TerminalOptions {
waitForCompletion?: boolean;
}
export type RuleSource =
| "default-chat"
| "default-agent"
| "model-chat-options"
| "model-agent-options"
| "rules-block"
| "json-systemMessage"
| ".continuerules";
export interface RuleWithSource {
name?: string;
slug?: string;
source:
| "default-chat"
| "default-agent"
| "model-chat-options"
| "model-agent-options"
| "rules-block"
| "json-systemMessage"
| ".continuerules";
source: RuleSource;
globs?: string | string[];
rule: string;
description?: string;

View file

@ -7,7 +7,7 @@ import {
getQueryForFile,
} from "../util/treeSitter";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import {
IndexResultType,
MarkCompleteCallback,
@ -29,6 +29,7 @@ import {
getLastNUriRelativePathParts,
getUriPathBasename,
} from "../util/uri";
import { tagToString } from "./utils";
type SnippetChunk = ChunkWithoutID & { title: string; signature: string };

View file

@ -3,13 +3,14 @@ import { RETRIEVAL_PARAMS } from "../util/parameters";
import { getUriPathBasename } from "../util/uri";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import {
IndexResultType,
MarkCompleteCallback,
RefreshIndexResults,
type CodebaseIndex,
} from "./types";
import { tagToString } from "./utils";
export interface RetrieveConfig {
tags: BranchAndDir[];
@ -97,11 +98,14 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
// Delete
for (const item of results.del) {
await db.run(`
await db.run(
`
DELETE FROM fts WHERE rowid IN (
SELECT id FROM fts_metadata WHERE path = ? AND cacheKey = ?
)
`,[item.path, item.cacheKey]);
`,
[item.path, item.cacheKey],
);
await db.run("DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?", [
item.path,
item.cacheKey,

View file

@ -14,7 +14,7 @@ import { getUriPathBasename } from "../util/uri";
import { basicChunker } from "./chunk/basic.js";
import { chunkDocument, shouldChunk } from "./chunk/chunk.js";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
import { DatabaseConnection, SqliteDb } from "./refreshIndex.js";
import {
CodebaseIndex,
IndexResultType,
@ -24,6 +24,7 @@ import {
} from "./types";
import type * as LanceType from "vectordb";
import { tagToString } from "./utils";
interface LanceDbRow {
uuid: string;

View file

@ -4,7 +4,7 @@ import { RunResult } from "sqlite3";
import { IContinueServerClient } from "../../continueServer/interface.js";
import { Chunk, IndexTag, IndexingProgressUpdate } from "../../index.js";
import { DatabaseConnection, SqliteDb, tagToString } from "../refreshIndex.js";
import { DatabaseConnection, SqliteDb } from "../refreshIndex.js";
import {
IndexResultType,
MarkCompleteCallback,
@ -13,8 +13,9 @@ import {
type CodebaseIndex,
} from "../types.js";
import { chunkDocument, shouldChunk } from "./chunk.js";
import { getUriPathBasename } from "../../util/uri.js";
import { tagToString } from "../utils.js";
import { chunkDocument, shouldChunk } from "./chunk.js";
export class ChunkCodebaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 1;

View file

@ -18,10 +18,6 @@ import {
export type DatabaseConnection = Database<sqlite3.Database>;
export function tagToString(tag: IndexTag): string {
return `${tag.directory}::${tag.branch}::${tag.artifactId}`;
}
export class SqliteDb {
static db: DatabaseConnection | null = null;

View file

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

View file

@ -0,0 +1,58 @@
import { IndexTag } from "..";
import { tagToString } from "./utils";
test("tagToString returns full tag string when under length limit", () => {
const tag: IndexTag = {
directory: "/normal/path/to/repo",
branch: "main",
artifactId: "12345",
};
expect(tagToString(tag)).toBe("/normal/path/to/repo::main::12345");
});
test("tagToString truncates beginning of directory when path is too long", () => {
// Create a very long directory path that exceeds MAX_DIR_LENGTH (200)
const longPrefix = "/very/long/path/that/will/be/truncated/";
const importantSuffix = "/user/important-project/src/feature";
const longPath = longPrefix + "x".repeat(200) + importantSuffix;
const tag: IndexTag = {
directory: longPath,
branch: "feature-branch",
artifactId: "67890",
};
const result = tagToString(tag);
// The result should keep the important suffix part
expect(result).toContain(importantSuffix);
// The result should NOT contain the beginning of the path
expect(result).not.toContain(longPrefix);
// The result should include the branch and artifactId
expect(result).toContain("::feature-branch::67890");
// The result should be within the MAX_TABLE_NAME_LENGTH limit (240)
expect(result.length).toBeLessThanOrEqual(240);
});
test("tagToString preserves branch and artifactId exactly, even when truncating", () => {
const longPath = "/a".repeat(300); // Much longer than MAX_DIR_LENGTH
const tag: IndexTag = {
directory: longPath,
branch: "release-v2.0",
artifactId: "build-123",
};
const result = tagToString(tag);
// Should contain the exact branch and artifactId
expect(result).toContain("::release-v2.0::build-123");
// Should contain the end of the path
expect(result).toContain("/a/a/a");
// Should not contain the full original path (it should be truncated)
expect(result.length).toBeLessThan(
longPath.length + "::release-v2.0::build-123".length,
);
// The result should be within the MAX_TABLE_NAME_LENGTH limit
expect(result.length).toBeLessThanOrEqual(240);
});

45
core/indexing/utils.ts Normal file
View file

@ -0,0 +1,45 @@
import { IndexTag } from "..";
// Maximum length for table names to stay under OS filename limits
const MAX_TABLE_NAME_LENGTH = 240;
// Leave room for branch and artifactId
const MAX_DIR_LENGTH = 200;
/**
* Converts an IndexTag to a string representation, safely handling long paths.
*
* The string is used as a table name and identifier in various places, so it needs
* to stay under OS filename length limits (typically 255 chars). This is especially
* important for dev containers where the directory path can be very long due to
* containing container configuration.
*
* The format is: "{directory}::{branch}::{artifactId}"
*
* To handle long paths:
* 1. First tries the full string - most backwards compatible
* 2. If too long, truncates directory from the beginning to maintain uniqueness
* (since final parts of paths are more unique than prefixes)
* 3. Finally ensures entire string stays under MAX_TABLE_NAME_LENGTH for OS compatibility
*
* @param tag The tag containing directory, branch, and artifactId
* @returns A string representation safe for use as a table name
*/
export function tagToString(tag: IndexTag): string {
const result = `${tag.directory}::${tag.branch}::${tag.artifactId}`;
if (result.length <= MAX_TABLE_NAME_LENGTH) {
return result;
}
// Truncate from the beginning of directory path to preserve the more unique end parts
const dir =
tag.directory.length > MAX_DIR_LENGTH
? tag.directory.slice(tag.directory.length - MAX_DIR_LENGTH)
: tag.directory;
return `${dir}::${tag.branch}::${tag.artifactId}`.slice(
0,
MAX_TABLE_NAME_LENGTH,
);
}

View file

@ -230,6 +230,7 @@ describe("LLM", () => {
testFim: true,
skip: false,
testToolCall: true,
timeout: 60000,
},
);
testLLM(

View file

@ -23,6 +23,29 @@ const matchesGlobs = (
return false;
};
/**
* Filters rules that apply to the given message
*/
export const getApplicableRules = (
userMessage: UserChatMessage | ToolResultChatMessage | undefined,
rules: RuleWithSource[],
): RuleWithSource[] => {
const filePathsFromMessage = userMessage
? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
: [];
return rules.filter((rule) => {
// A rule is active if it has no globs (applies to all files)
// or if at least one file path matches its globs
const hasNoGlobs = !rule.globs;
const matchesAnyFilePath = filePathsFromMessage.some((path) =>
matchesGlobs(path, rule.globs),
);
return hasNoGlobs || matchesAnyFilePath;
});
};
export const getSystemMessageWithRules = ({
baseSystemMessage,
userMessage,
@ -32,23 +55,11 @@ export const getSystemMessageWithRules = ({
userMessage: UserChatMessage | ToolResultChatMessage | undefined;
rules: RuleWithSource[];
}) => {
const filePathsFromMessage = userMessage
? extractPathsFromCodeBlocks(renderChatMessage(userMessage))
: [];
const applicableRules = getApplicableRules(userMessage, rules);
let systemMessage = baseSystemMessage ?? "";
for (const rule of rules) {
// A rule is active if it has no globs (applies to all files)
// or if at least one file path matches its globs
const hasNoGlobs = !rule.globs;
const matchesAnyFilePath = filePathsFromMessage.some((path) =>
matchesGlobs(path, rule.globs),
);
if (hasNoGlobs || matchesAnyFilePath) {
systemMessage += `\n\n${rule.rule}`;
}
for (const rule of applicableRules) {
systemMessage += `\n\n${rule.rule}`;
}
return systemMessage;

View file

@ -64,6 +64,8 @@ export const gptEditPrompt: PromptTemplateFunction = (history, otherData) => {
\`\`\`
The user's request is: "${otherData.userInput}"
DO NOT output any natural language, only output the code changes.
Here is the rewritten code:`);

View file

@ -15266,9 +15266,9 @@
}
},
"node_modules/undici": {
"version": "6.21.1",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.21.1.tgz",
"integrity": "sha512-q/1rj5D0/zayJB2FraXdaWxbhWiNKDvu8naDT2dl1yTlvJp4BLtOcp2a5BvgGNQpYYJzau7tf1WgKv3b+7mqpQ==",
"version": "6.21.3",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.21.3.tgz",
"integrity": "sha512-gBLkYIlEnSp8pFbT64yFgGE6UIB9tAkhukC23PmMDCe5Nd+cRqKxSjw5y54MK2AZMgZfJWMaNE4nYUHgi1XEOw==",
"license": "MIT",
"engines": {
"node": ">=18.17"

View file

@ -9,7 +9,7 @@ import { AutocompleteInput } from "../autocomplete/util/types";
import { SharedConfigSchema } from "../config/sharedConfig";
import { GlobalContextModelSelections } from "../util/GlobalContext";
import type {
import {
BrowserSerializedContinueConfig,
ChatMessage,
ContextItem,
@ -29,6 +29,7 @@ import type {
SessionMetadata,
SiteIndexingConfig,
SlashCommandDescription,
StreamDiffLinesPayload,
ToolCall,
} from "../";
import { SerializedOrgWithProfiles } from "../config/ProfileLifecycleManager";
@ -142,18 +143,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
},
AsyncGenerator<ChatMessage, PromptLog>,
];
streamDiffLines: [
{
prefix: string;
highlighted: string;
suffix: string;
input: string;
language: string | undefined;
modelTitle: string | undefined;
includeRulesInSystemMessage: boolean;
},
AsyncGenerator<DiffLine>,
];
streamDiffLines: [StreamDiffLinesPayload, AsyncGenerator<DiffLine>];
"chatDescriber/describe": [
{
text: string;

View file

@ -1,11 +1,13 @@
import { ToIdeFromWebviewOrCoreProtocol } from "./ide";
import { ToWebviewFromIdeOrCoreProtocol } from "./webview";
import type {
import {
ApplyState,
CodeToEdit,
SetCodeToEditPayload,
HighlightedCodePayload,
MessageContent,
RangeInFileWithContents,
AcceptOrRejectDiffPayload,
} from "../";
export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
@ -42,8 +44,8 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
"jetbrains/getColors": [undefined, Record<string, string>];
"vscode/openMoveRightMarkdown": [undefined, void];
setGitHubAuthToken: [{ token: string }, void];
acceptDiff: [{ filepath: string; streamId?: string }, void];
rejectDiff: [{ filepath: string; streamId?: string }, void];
acceptDiff: [AcceptOrRejectDiffPayload, void];
rejectDiff: [AcceptOrRejectDiffPayload, void];
"edit/sendPrompt": [
{
prompt: MessageContent;
@ -63,15 +65,8 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
focusContinueInput: [undefined, void];
focusContinueInputWithoutClear: [undefined, void];
focusContinueInputWithNewSession: [undefined, void];
highlightedCode: [
{
rangeInFileWithContents: RangeInFileWithContents;
prompt?: string;
shouldRun?: boolean;
},
void,
];
setCodeToEdit: [CodeToEdit, void];
highlightedCode: [HighlightedCodePayload, void];
setCodeToEdit: [SetCodeToEditPayload, void];
navigateTo: [{ path: string; toggle?: boolean }, void];
addModel: [undefined, void];

View file

@ -29,11 +29,12 @@ async function callHttpTool(
}),
});
const data = await response.json();
if (!response.ok) {
throw new Error(`Failed to call tool: ${url}`);
throw new Error(`Failed to call tool at ${url}:\n${JSON.stringify(data)}`);
}
const data = await response.json();
return data.output;
}
@ -84,7 +85,7 @@ async function callToolFromUri(
});
if (response.isError === true) {
throw new Error(`Failed to call tool: ${toolName}`);
throw new Error(JSON.stringify(response.content));
}
const contextItems: ContextItem[] = [];
@ -130,6 +131,37 @@ async function callToolFromUri(
}
}
async function callBuiltInTool(
functionName: string,
args: any,
extras: ToolExtras,
): Promise<ContextItem[]> {
switch (functionName) {
case BuiltInToolNames.ReadFile:
return await readFileImpl(args, extras);
case BuiltInToolNames.CreateNewFile:
return await createNewFileImpl(args, extras);
case BuiltInToolNames.GrepSearch:
return await grepSearchImpl(args, extras);
case BuiltInToolNames.FileGlobSearch:
return await fileGlobSearchImpl(args, extras);
case BuiltInToolNames.RunTerminalCommand:
return await runTerminalCommandImpl(args, extras);
case BuiltInToolNames.SearchWeb:
return await searchWebImpl(args, extras);
case BuiltInToolNames.ViewDiff:
return await viewDiffImpl(args, extras);
case BuiltInToolNames.LSTool:
return await lsToolImpl(args, extras);
case BuiltInToolNames.ReadCurrentlyOpenFile:
return await readCurrentlyOpenFileImpl(args, extras);
case BuiltInToolNames.CreateRuleBlock:
return await createRuleBlockImpl(args, extras);
default:
throw new Error(`Tool "${functionName}" not found`);
}
}
// Handles calls for core/non-client tools
// Returns an error context item if the tool call fails
// Note: Edit tool is handled on client
@ -141,44 +173,11 @@ export async function callTool(
contextItems: ContextItem[];
errorMessage: string | undefined;
}> {
const args = JSON.parse(callArgs || "{}");
const uri = tool.uri ?? tool.function.name;
try {
let contextItems: ContextItem[] = [];
switch (uri) {
case BuiltInToolNames.ReadFile:
contextItems = await readFileImpl(args, extras);
break;
case BuiltInToolNames.CreateNewFile:
contextItems = await createNewFileImpl(args, extras);
break;
case BuiltInToolNames.GrepSearch:
contextItems = await grepSearchImpl(args, extras);
break;
case BuiltInToolNames.FileGlobSearch:
contextItems = await fileGlobSearchImpl(args, extras);
break;
case BuiltInToolNames.RunTerminalCommand:
contextItems = await runTerminalCommandImpl(args, extras);
break;
case BuiltInToolNames.SearchWeb:
contextItems = await searchWebImpl(args, extras);
break;
case BuiltInToolNames.ViewDiff:
contextItems = await viewDiffImpl(args, extras);
break;
case BuiltInToolNames.LSTool:
contextItems = await lsToolImpl(args, extras);
break;
case BuiltInToolNames.ReadCurrentlyOpenFile:
contextItems = await readCurrentlyOpenFileImpl(args, extras);
break;
case BuiltInToolNames.CreateRuleBlock:
contextItems = await createRuleBlockImpl(args, extras);
break;
default:
contextItems = await callToolFromUri(uri, args, extras);
}
const args = JSON.parse(callArgs || "{}");
const contextItems = tool.uri
? await callToolFromUri(tool.uri, args, extras)
: await callBuiltInTool(tool.function.name, args, extras);
if (tool.faviconUrl) {
contextItems.forEach((item) => {
item.icon = tool.faviconUrl;

48
docs/docs/CLA.md Normal file
View file

@ -0,0 +1,48 @@
# Individual Contributor License Agreement (v1.0, Continue)
_Based on the Apache Software Foundation Individual CLA v 2.2._
By commenting **“I have read the CLA Document and I hereby sign the CLA”**
on a Pull Request, **you (“Contributor”) agree to the following terms** for any
past and future “Contributions” submitted to **Continue (the “Project”)**.
---
## 1. Definitions
- **“Contribution”** – any original work of authorship submitted to the Project
(code, documentation, designs, etc.).
- **“You” / “Your”** – the individual (or legal entity) posting the acceptance
comment.
## 2. Copyright License
You grant **Continue Dev, Inc.** and all recipients of software distributed by the
Project a perpetual, worldwide, non‑exclusive, royalty‑free, irrevocable
license to reproduce, prepare derivative works of, publicly display, publicly
perform, sublicense, and distribute Your Contributions and derivative works.
## 3. Patent License
You grant **Continue Dev, Inc.** and all recipients of the Project a perpetual,
worldwide, non‑exclusive, royalty‑free, irrevocable (except as below) patent
license to make, have made, use, sell, offer to sell, import, and otherwise
transfer Your Contributions alone or in combination with the Project.
If any entity brings patent litigation alleging that the Project or a
Contribution infringes a patent, the patent licenses granted by You to that
entity under this CLA terminate.
## 4. Representations
1. You are legally entitled to grant the licenses above.
2. Each Contribution is either Your original creation or You have authority to
submit it under this CLA.
3. Your Contributions are provided **“AS IS”** without warranties of any kind.
4. You will notify the Project if any statement above becomes inaccurate.
## 5. Miscellany
This Agreement is governed by the laws of the **State of California**, USA,
excluding its conflict‑of‑laws rules. If any provision is held unenforceable,
the remaining provisions remain in force.

View file

@ -206,7 +206,6 @@ chat, editing, and summarizing.
- `topP`: The cumulative probability for nucleus sampling.
- `topK`: Maximum number of tokens considered at each step.
- `stop`: An array of stop tokens that will terminate the completion.
- `n`: Number of completions to generate.
- `reasoning`: Boolean to enable thinking/reasoning for Anthropic Claude 3.7+ models.
- `reasoningBudgetTokens`: Budget tokens for thinking/reasoning in Anthropic Claude 3.7+ models.
- `requestOptions`: HTTP request options specific to the model.

View file

@ -7,8 +7,6 @@ keywords: [reload, delete, manually, logs, server, console]
import TabItem from "@theme/TabItem";
import Tabs from "@theme/Tabs";
The Continue VS Code extension is currently in beta, and the JetBrains extension is in Alpha. If you are having trouble, please follow the steps below.
1. [Check the logs](#check-the-logs)
2. [Try the latest pre-release](#download-the-latest-pre-release)
3. [Download an older version](#download-an-older-version)

View file

@ -65,6 +65,10 @@ const config = {
],
],
scripts: [
'!function(){var e,t,n;e="7aa28ed11570734",t=function(){Reo.init({clientID:"7aa28ed11570734"})},(n=document.createElement("script")).src="https://static.reo.dev/"+e+"/reo.js",n.defer=!0,n.onload=t,document.head.appendChild(n)}();',
],
themeConfig:
/** @type {import("@docusaurus/preset-classic").ThemeConfig} */
({

View file

@ -1,6 +1,6 @@
<component name="ProjectRunConfigurationManager">
<configuration default="false" name="Start Core Dev Server (CE)" type="ShConfigurationType">
<option name="SCRIPT_TEXT" value="cross-env 'PROJECT_DIR=&quot;$PROJECT_DIR$&quot;' node core-dev-server.js" />
<option name="SCRIPT_TEXT" value="npx cross-env 'PROJECT_DIR=&quot;$PROJECT_DIR$&quot;' node core-dev-server.js" />
<option name="INDEPENDENT_SCRIPT_PATH" value="true" />
<option name="SCRIPT_PATH" value="" />
<option name="SCRIPT_OPTIONS" value="" />

View file

@ -173,6 +173,12 @@ to run.
./gradlew test
```
Run a single test
```sh
./gradlew test --tests "com.github.continuedev.continueintellijextension.e2e.TESTNAME"
```
#### Identifying selectors
While the `runIdeForUiTests` task is running, you can visit the following URL

View file

@ -42,10 +42,12 @@ dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.5.0")
testImplementation("com.intellij.remoterobot:remote-robot:$remoteRobotVersion")
testImplementation("com.intellij.remoterobot:remote-fixtures:$remoteRobotVersion")
testImplementation("io.mockk:mockk:1.14.2")
testImplementation("org.junit.jupiter:junit-jupiter-api:5.10.0")
testRuntimeOnly("org.junit.jupiter:junit-jupiter-engine:5.9.2")
testImplementation("com.squareup.okhttp3:logging-interceptor:4.12.0")
implementation("com.automation-remarks:video-recorder-junit5:2.0")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.7.3")
// Exclude vulnerable Log4j from all dependencies
@ -62,6 +64,7 @@ dependencies {
// Add Log4j 2.x explicitly
implementation("org.apache.logging.log4j:log4j-core:2.20.0")
implementation("org.apache.logging.log4j:log4j-api:2.20.0")
testImplementation(kotlin("test"))
}
// Set the JVM language level used to build the project. Use Java 11 for 2020.3+, and Java 17 for
@ -162,6 +165,7 @@ tasks {
// This is to ensure we load the GUI with OSR enabled. We have logic that
// renders with OSR disabled below a particular IDE version.
// See ContinueExtensionSettingsService.kt for more info.
// Currently commented out however since test fail in CI with this version
// intellij {
// version.set("2024.1")
// }

View file

@ -3,13 +3,13 @@ pluginGroup=com.github.continuedev.continueintellijextension
pluginName=continue-intellij-extension
pluginRepositoryUrl=https://github.com/continuedev/continue
# SemVer format -> https://semver.org
pluginVersion=1.0.17
pluginVersion=1.0.18
# Supported build number ranges and IntelliJ Platform versions -> https://plugins.jetbrains.com/docs/intellij/build-number-ranges.html
pluginSinceBuild=223
# IntelliJ Platform Properties -> https://plugins.jetbrains.com/docs/intellij/tools-gradle-intellij-plugin.html#configuration-intellij-extension
platformType=IC
platformVersion=2022.3.3
#org.gradle.java.home=/opt/homebrew/opt/openjdk@17
# org.gradle.java.home=/opt/homebrew/opt/openjdk@17
#platformVersion = LATEST-EAP-SNAPSHOT
# Plugin Dependencies -> https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html
# Example: platformPlugins = com.intellij.java, com.jetbrains.php:203.4449.22

View file

@ -1,6 +1,5 @@
package com.github.continuedev.continueintellijextension.activities
import IntelliJIDE
import com.intellij.openapi.fileEditor.FileEditorManagerListener
import com.github.continuedev.continueintellijextension.auth.AuthListener
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService

View file

@ -0,0 +1,187 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.ApplyState
import com.github.continuedev.continueintellijextension.ApplyStateStatus
import com.github.continuedev.continueintellijextension.IDE
import com.github.continuedev.continueintellijextension.ToastType
import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
import com.github.continuedev.continueintellijextension.editor.EditorUtils
import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.github.continuedev.continueintellijextension.utils.castNestedOrNull
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
/**
* Handles applying text to a file with streaming diff preview
*/
class ApplyToFileHandler(
private val project: Project,
private val continuePluginService: ContinuePluginService,
private val ide: IDE,
private val params: ApplyToFileParams,
private val editorUtils: EditorUtils?,
private val diffStreamService: DiffStreamService
) {
suspend fun handleApplyToFile() {
// Notify webview that we're starting to stream
notifyStreamStarted()
if (editorUtils == null) {
ide.showToast(ToastType.ERROR, "No active editor to apply edits to")
notifyStreamClosed()
return
}
if (editorUtils.isDocumentEmpty()) {
editorUtils.insertTextIntoEmptyDocument(params.text)
notifyStreamClosed()
return
}
// Get the LLM configuration for applying edits
val llm = fetchApplyLLMConfig() ?: run {
ide.showToast(ToastType.ERROR, "Failed to fetch model configuration")
notifyStreamClosed()
return
}
setupAndStreamDiffs(editorUtils, llm)
}
private fun notifyStreamStarted() {
sendApplyStateUpdate(ApplyStateStatus.STREAMING)
}
private fun notifyStreamClosed(numDiffs: Int? = 0) {
sendApplyStateUpdate(ApplyStateStatus.CLOSED, numDiffs)
}
private fun sendApplyStateUpdate(
status: ApplyStateStatus,
numDiffs: Int? = null
) {
val payload = ApplyState(
streamId = params.streamId,
status = status.status,
numDiffs = numDiffs,
filepath = params.filepath,
fileContent = params.text,
toolCallId = params.toolCallId.toString()
)
continuePluginService.sendToWebview("updateApplyState", payload)
}
private suspend fun fetchApplyLLMConfig(): Any? {
return try {
suspendCancellableCoroutine { continuation ->
continuePluginService.coreMessenger?.request(
"config/getSerializedProfileInfo",
null,
null
) { response ->
try {
val selectedModels = response.castNestedOrNull<Map<String, Any>>(
"content",
"result",
"config",
"selectedModelByRole"
)
// If "apply" role model is not found, try "chat" role
val applyCodeBlockModel = selectedModels?.get("apply") ?: selectedModels?.get("chat")
if (applyCodeBlockModel != null) {
continuation.resume(applyCodeBlockModel)
} else {
// If neither "apply" nor "chat" models are available, return with exception
continuation.resumeWithException(IllegalStateException("No 'apply' or 'chat' model found in configuration."))
}
} catch (e: Exception) {
continuation.resumeWithException(e)
}
}
}
} catch (_: Exception) {
null
}
}
private fun setupAndStreamDiffs(editorUtils: EditorUtils, llm: Any) {
// Clear all diff blocks before running the diff stream
diffStreamService.reject(editorUtils.editor)
val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: ""
val prompt = buildApplyPrompt()
// Extract the code ranges (highlighted or full document)
val (prefix, highlighted, suffix) = editorUtils.extractCodeRanges()
// Get the line range for the diff stream
val rif = editorUtils.getHighlightedCode()
val startLine = rif?.range?.start?.line ?: 0
val endLine = rif?.range?.end?.line ?: (editorUtils.getLineCount() - 1)
// Create and register the diff stream handler
val diffStreamHandler = createDiffStreamHandler(editorUtils.editor, startLine, endLine)
diffStreamService.register(diffStreamHandler, editorUtils.editor)
// Stream the diffs
diffStreamHandler.streamDiffLinesToEditor(
prompt, prefix, highlighted, suffix, llmTitle, false
)
}
private fun buildApplyPrompt(): String {
return "The following code was suggested as an edit:\n```\n${params.text}\n```\nPlease apply it to the previous code."
}
private fun createDiffStreamHandler(
editor: Editor,
startLine: Int,
endLine: Int
): DiffStreamHandler {
return DiffStreamHandler(
project,
editor,
startLine,
endLine,
{},
{},
params.streamId,
params.toolCallId.toString()
)
}
companion object {
/**
* Factory method to create and execute a new handler for a single apply-to-file operation
*/
suspend fun apply(
project: Project,
continuePluginService: ContinuePluginService,
ide: IDE,
params: ApplyToFileParams
) {
val editorUtils = EditorUtils.getOrOpenEditor(project, params.filepath)
val diffStreamService = project.getService(DiffStreamService::class.java)
val handler = ApplyToFileHandler(
project,
continuePluginService,
ide,
params,
editorUtils,
diffStreamService
)
handler.handleApplyToFile()
}
}
}

View file

@ -62,7 +62,7 @@ class DiffManager(private val project: Project) : DumbAware {
file.createNewFile()
}
file.writeText(replacement)
openDiffWindow(URI(filepath).toString(), file.toURI().toString(), stepIndex)
openDiffWindow(UriUtils.parseUri(filepath).toString(), file.toURI().toString(), stepIndex)
}
private fun cleanUpFile(file2: String) {
@ -80,7 +80,8 @@ class DiffManager(private val project: Project) : DumbAware {
val diffInfo = diffInfoMap[file] ?: return
// Write contents to original file
val virtualFile = LocalFileSystem.getInstance().findFileByPath(URI(diffInfo.originalFilepath).path) ?: return
val virtualFile =
LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(diffInfo.originalFilepath).path) ?: return
val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: return
WriteCommandAction.runWriteCommandAction(project) {
document.setText(File(file).readText())
@ -119,8 +120,8 @@ class DiffManager(private val project: Project) : DumbAware {
lastFile2 = file2
// Create a DiffContent for each of the texts you want to compare
val content1: DiffContent = DiffContentFactory.getInstance().create(File(URI(file1)).readText())
val content2: DiffContent = DiffContentFactory.getInstance().create(File(URI(file2)).readText())
val content1: DiffContent = DiffContentFactory.getInstance().create(UriUtils.uriToFile(file1).readText())
val content2: DiffContent = DiffContentFactory.getInstance().create(UriUtils.uriToFile(file2).readText())
// Create a SimpleDiffRequest and populate it with the DiffContents and titles
val diffRequest = SimpleDiffRequest("Continue Diff", content1, content2, "Old", "New")

View file

@ -7,9 +7,7 @@ import com.intellij.openapi.project.guessProjectDir
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.net.URI
class GitService(
private val project: Project,
@ -52,7 +50,7 @@ class GitService(
} else {
ProcessBuilder("git", "diff", "--cached")
}
builder.directory(File(URI(workspaceDir)))
builder.directory(UriUtils.uriToFile(workspaceDir))
val process = withContext(Dispatchers.IO) {
builder.start()
}

View file

@ -1,13 +1,11 @@
package com.github.continuedev.continueintellijextension.`continue`
import IntelliJIDE
import com.github.continuedev.continueintellijextension.*
import com.github.continuedev.continueintellijextension.activities.ContinuePluginDisposable
import com.github.continuedev.continueintellijextension.activities.showTutorial
import com.github.continuedev.continueintellijextension.auth.AuthListener
import com.github.continuedev.continueintellijextension.auth.ContinueAuthService
import com.github.continuedev.continueintellijextension.editor.DiffStreamHandler
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
import com.github.continuedev.continueintellijextension.editor.EditorUtils
import com.github.continuedev.continueintellijextension.protocol.*
import com.github.continuedev.continueintellijextension.services.*
import com.github.continuedev.continueintellijextension.utils.*
@ -16,21 +14,15 @@ import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.components.ServiceManager
import com.intellij.openapi.components.service
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.SelectionModel
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.wm.ToolWindowManager
import kotlinx.coroutines.*
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
import java.lang.IllegalStateException
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
class IdeProtocolClient(
@ -39,6 +31,8 @@ class IdeProtocolClient(
private val project: Project
) : DumbAware {
private val ide: IDE = IntelliJIDE(project, continuePluginService)
private val diffStreamService = project.service<DiffStreamService>()
/**
* Create a dispatcher with limited parallelism to prevent UI freezing.
@ -46,6 +40,7 @@ class IdeProtocolClient(
*
* See this thread for details: https://github.com/continuedev/continue/issues/4098#issuecomment-2854865310
*/
@OptIn(ExperimentalCoroutinesApi::class)
private val limitedDispatcher = Dispatchers.IO.limitedParallelism(4)
init {
@ -447,7 +442,13 @@ class IdeProtocolClient(
)
val filepath = params.filepath;
acceptOrRejectDiff(filepath, true)
val editor = EditorUtils.getOrOpenEditor(project, filepath)?.editor
if (editor != null) {
diffStreamService.accept(editor)
}
respond(null)
}
"rejectDiff" -> {
@ -456,7 +457,13 @@ class IdeProtocolClient(
RejectDiffParams::class.java
)
val filepath = params.filepath;
acceptOrRejectDiff(filepath, false)
val editor = EditorUtils.getOrOpenEditor(project, filepath)?.editor
if (editor != null) {
diffStreamService.reject(editor)
}
respond(null)
}
"applyToFile" -> {
@ -464,141 +471,13 @@ class IdeProtocolClient(
dataElement.toString(),
ApplyToFileParams::class.java
)
val filepath = params.filepath
continuePluginService.sendToWebview(
"updateApplyState", mapOf(
"streamId" to params.streamId,
"status" to "streaming",
"fileContent" to params.text,
"toolCallId" to params.toolCallId,
"filepath" to filepath
)
ApplyToFileHandler.apply(
project,
continuePluginService,
ide,
params
)
fun closeStream() {
continuePluginService.sendToWebview(
"updateApplyState", mapOf(
"numDiffs" to 0,
"streamId" to params.streamId,
"status" to "closed",
"fileContent" to params.text,
"toolCallId" to params.toolCallId,
"filepath" to filepath
)
)
}
var editor: Editor? = null;
if (!filepath.isNullOrEmpty()) {
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
if (virtualFile != null) {
ApplicationManager.getApplication().invokeAndWait {
FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first()
}
}
}
editor = FileEditorManager.getInstance(project).selectedTextEditor
if (editor == null) {
ide.showToast(ToastType.ERROR, "No active editor to apply edits to")
closeStream()
respond(null)
return@launch
}
if (editor.document.text.trim().isEmpty()) {
WriteCommandAction.runWriteCommandAction(project) {
editor.document.insertString(0, params.text)
}
closeStream()
respond(null)
return@launch
}
val llm: Any = try {
suspendCancellableCoroutine { continuation ->
continuePluginService.coreMessenger?.request(
"config/getSerializedProfileInfo",
null,
null
) { response ->
try {
val selectedModels = response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "selectedModelByRole")
// If "apply" role model is not found, try "chat" role
val applyCodeBlockModel = selectedModels?.get("apply") ?: selectedModels?.get("chat")
if (applyCodeBlockModel != null) {
continuation.resume(applyCodeBlockModel)
} else {
// If neither "apply" nor "chat" models are available, return with exception
continuation.resumeWithException(IllegalStateException("No 'apply' or 'chat' model found in configuration."))
}
} catch (e: Exception) {
continuation.resumeWithException(e)
}
}
}
} catch (e: Exception) {
launch {
ide.showToast(
ToastType.ERROR, "Failed to fetch model configuration"
)
}
closeStream()
respond(null)
return@launch
}
val diffStreamService = project.service<DiffStreamService>()
// Clear all diff blocks before running the diff stream
diffStreamService.reject(editor)
val llmTitle = (llm as? Map<*, *>)?.get("title") as? String ?: ""
val prompt =
"The following code was suggested as an edit:\n```\n${params.text}\n```\nPlease apply it to the previous code."
val rif = getHighlightedCode()
val (prefix, highlighted, suffix) = if (rif == null) {
// If no highlight, use the whole document as highlighted
Triple("", editor.document.text, "")
} else {
val prefix = editor.document.getText(TextRange(0, rif.range.start.character))
val highlighted = rif.contents
val suffix =
editor.document.getText(TextRange(rif.range.end.character, editor.document.textLength))
// Remove the selection after processing
ApplicationManager.getApplication().invokeLater {
editor.selectionModel.removeSelection()
}
Triple(prefix, highlighted, suffix)
}
val diffStreamHandler =
DiffStreamHandler(
project,
editor,
rif?.range?.start?.line ?: 0,
rif?.range?.end?.line ?: (editor.document.lineCount - 1),
{},
{},
params.streamId,
params.toolCallId
)
diffStreamService.register(diffStreamHandler, editor)
diffStreamHandler.streamDiffLinesToEditor(
prompt, prefix, highlighted, suffix, llmTitle, false
)
respond(null)
}
@ -612,52 +491,15 @@ class IdeProtocolClient(
}
}
private fun getHighlightedCode(): RangeInFileWithContents? {
val result = ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> {
// Get the editor instance for the currently active editor window
val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return@runReadAction null
val virtualFile =
editor.let { FileDocumentManager.getInstance().getFile(it.document) } ?: return@runReadAction null
// Get the selection range and content
val selectionModel: SelectionModel = editor.selectionModel
val selectedText = selectionModel.selectedText ?: ""
val document = editor.document
val startOffset = selectionModel.selectionStart
val endOffset = selectionModel.selectionEnd
if (startOffset == endOffset) {
return@runReadAction null
}
val startLine = document.getLineNumber(startOffset)
val endLine = document.getLineNumber(endOffset)
val startChar = startOffset - document.getLineStartOffset(startLine)
val endChar = endOffset - document.getLineStartOffset(endLine)
return@runReadAction virtualFile.toUriOrNull()?.let {
RangeInFileWithContents(
it, Range(
Position(startLine, startChar),
Position(endLine, endChar)
), selectedText
)
}
}
return result
}
fun sendHighlightedCode(edit: Boolean = false) {
val rif = getHighlightedCode() ?: return
val editor = EditorUtils.getEditor(project)
val rif = editor?.getHighlightedCode() ?: return
continuePluginService.sendToWebview(
"highlightedCode",
mapOf(
"rangeInFileWithContents" to rif,
"edit" to edit
HighlightedCodePayload(
rangeInFileWithContents = rif,
shouldRun = edit
)
)
}
@ -667,28 +509,6 @@ class IdeProtocolClient(
continuePluginService.sendToWebview("acceptRejectDiff", AcceptRejectDiff(accepted, stepIndex), uuid())
}
fun acceptOrRejectDiff(filepath: String, accepted: Boolean) {
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
if (virtualFile != null) {
ApplicationManager.getApplication().invokeAndWait {
val openedEditor =
FileEditorManager.getInstance(project).openFile(virtualFile, true)?.first()
if (openedEditor != null) {
val editor: Editor? = FileEditorManager.getInstance(project).selectedTextEditor
if (editor != null) {
val diffStreamService = project.service<DiffStreamService>()
if (accepted) {
diffStreamService.accept(editor)
} else {
diffStreamService.reject(editor)
}
}
}
}
}
}
fun deleteAtIndex(index: Int) {
continuePluginService.sendToWebview("deleteAtIndex", DeleteAtIndex(index), uuid())

View file

@ -1,3 +1,5 @@
package com.github.continuedev.continueintellijextension.`continue`
import com.github.continuedev.continueintellijextension.*
import com.github.continuedev.continueintellijextension.constants.getContinueGlobalPath
import com.github.continuedev.continueintellijextension.constants.ContinueConstants
@ -167,7 +169,7 @@ class IntelliJIDE(
// Find any .continuerc.json files
for (file in contents) {
if (file.endsWith(".continuerc.json")) {
val fileContent = File(URI(file)).readText()
val fileContent = UriUtils.uriToFile(file).readText()
configs.add(fileContent)
}
}
@ -178,12 +180,12 @@ class IntelliJIDE(
}
override suspend fun fileExists(filepath: String): Boolean {
val file = File(URI(filepath))
val file = UriUtils.uriToFile(filepath)
return file.exists()
}
override suspend fun writeFile(path: String, contents: String) {
val file = File(URI(path))
val file = UriUtils.uriToFile(path)
file.parentFile?.mkdirs()
file.writeText(contents)
}
@ -201,7 +203,7 @@ class IntelliJIDE(
override suspend fun openFile(path: String) {
// Convert URI path to absolute file path
val filePath = File(URI(path)).absolutePath
val filePath = UriUtils.uriToFile(path).absolutePath
// Find the file using the absolute path
val file = withContext(Dispatchers.IO) {
LocalFileSystem.getInstance().refreshAndFindFileByPath(filePath)
@ -216,7 +218,7 @@ class IntelliJIDE(
override suspend fun openUrl(url: String) {
withContext(Dispatchers.IO) {
Desktop.browse(java.net.URI(url))
Desktop.browse(URI(url))
}
}
@ -226,7 +228,8 @@ class IntelliJIDE(
override suspend fun saveFile(filepath: String) {
ApplicationManager.getApplication().invokeLater {
val file = LocalFileSystem.getInstance().findFileByPath(URI(filepath).path) ?: return@invokeLater
val file =
LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(filepath).path) ?: return@invokeLater
val fileDocumentManager = FileDocumentManager.getInstance()
val document = fileDocumentManager.getDocument(file)
@ -239,7 +242,7 @@ class IntelliJIDE(
override suspend fun readFile(filepath: String): String {
return try {
val content = ApplicationManager.getApplication().runReadAction<String?> {
val virtualFile = LocalFileSystem.getInstance().findFileByPath(URI(filepath).path)
val virtualFile = LocalFileSystem.getInstance().findFileByPath(UriUtils.parseUri(filepath).path)
if (virtualFile != null && FileDocumentManager.getInstance().isFileModified(virtualFile)) {
return@runReadAction FileDocumentManager.getInstance().getDocument(virtualFile)?.text
}
@ -249,7 +252,7 @@ class IntelliJIDE(
if (content != null) {
content
} else {
val file = File(URI(filepath))
val file = UriUtils.uriToFile(filepath)
if (!file.exists() || file.isDirectory) return ""
withContext(Dispatchers.IO) {
FileInputStream(file).use { fis ->
@ -455,7 +458,7 @@ class IntelliJIDE(
return withContext(Dispatchers.IO) {
try {
val builder = ProcessBuilder("git", "rev-parse", "--abbrev-ref", "HEAD")
builder.directory(File(URI(dir)))
builder.directory(UriUtils.uriToFile(dir))
val process = builder.start()
val reader = BufferedReader(InputStreamReader(process.inputStream))
val output = reader.readLine()
@ -485,7 +488,7 @@ class IntelliJIDE(
override suspend fun getRepoName(dir: String): String? {
return withContext(Dispatchers.IO) {
val directory = File(URI(dir))
val directory = UriUtils.uriToFile(dir)
val targetDir = if (directory.isFile) directory.parentFile else directory
val builder = ProcessBuilder("git", "config", "--get", "remote.origin.url")
builder.directory(targetDir)
@ -549,7 +552,7 @@ class IntelliJIDE(
override suspend fun getGitRootPath(dir: String): String? {
return withContext(Dispatchers.IO) {
val builder = ProcessBuilder("git", "rev-parse", "--show-toplevel")
builder.directory(File(URI(dir)))
builder.directory(UriUtils.uriToFile(dir))
val process = builder.start()
val reader = BufferedReader(InputStreamReader(process.inputStream))
@ -560,7 +563,7 @@ class IntelliJIDE(
}
override suspend fun listDir(dir: String): List<List<Any>> {
val files = File(URI(dir)).listFiles()?.map {
val files = UriUtils.uriToFile(dir).listFiles()?.map {
listOf(it.name, if (it.isDirectory) FileType.DIRECTORY.value else FileType.FILE.value)
} ?: emptyList()
@ -569,7 +572,7 @@ class IntelliJIDE(
override suspend fun getFileStats(files: List<String>): Map<String, FileStats> {
return files.associateWith { file ->
FileStats(File(URI(file)).lastModified(), File(URI(file)).length())
FileStats(UriUtils.uriToFile(file).lastModified(), UriUtils.uriToFile(file).length())
}
}
@ -587,7 +590,7 @@ class IntelliJIDE(
}
private fun setFileOpen(filepath: String, open: Boolean = true) {
val file = LocalFileSystem.getInstance().findFileByPath(URI(filepath).path)
val file = LocalFileSystem.getInstance().findFileByPath(UriUtils.uriToFile(filepath).path)
file?.let {
if (open) {

View file

@ -0,0 +1,39 @@
package com.github.continuedev.continueintellijextension.`continue`
import java.io.File
import java.net.URI
/**
* Utility class for URI operations
*/
object UriUtils {
/**
* Parses a URI string into a URI object, handling special cases for Windows file paths
*/
fun parseUri(uri: String): URI {
try {
// Remove query parameters if present
val uriStr = uri.substringBefore("?")
// Handle Windows file paths with authority component
if (uriStr.startsWith("file://") && !uriStr.startsWith("file:///")) {
val path = uriStr.substringAfter("file://")
return URI("file:///$path")
}
// Standard URI handling for other cases
val uriWithoutQuery = URI(uriStr)
return uriWithoutQuery
} catch (e: Exception) {
println("Error parsing URI: $uri ${e.message}")
throw Exception("Invalid URI: $uri ${e.message}")
}
}
/**
* Converts a URI string to a File object
*/
fun uriToFile(uri: String): File {
return File(parseUri(uri))
}
}

View file

@ -1,5 +1,8 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.ApplyState
import com.github.continuedev.continueintellijextension.ApplyStateStatus
import com.github.continuedev.continueintellijextension.StreamDiffLinesPayload
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
@ -12,7 +15,6 @@ import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.fileEditor.TextEditor
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VirtualFile
import kotlin.math.max
import kotlin.math.min
@ -35,41 +37,41 @@ class DiffStreamHandler(
var index: Int, var highlighter: RangeHighlighter? = null, var diffBlock: VerticalDiffBlock? = null
)
private val diffBlocks: MutableList<VerticalDiffBlock> = mutableListOf()
private var curLine = CurLineState(startLine)
private var isRunning: Boolean = false
private var hasAcceptedOrRejectedBlock: Boolean = false
private val unfinishedHighlighters: MutableList<RangeHighlighter> = mutableListOf()
private val diffBlocks: MutableList<VerticalDiffBlock> = mutableListOf()
private val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
private val virtualFile = FileDocumentManager.getInstance().getFile(editor.document)
private val curLineKey = createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE", 0x40888888, editor)
private val unfinishedKey = createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888, editor)
init {
initUnfinishedRangeHighlights()
}
private fun sendUpdate(status: String) {
if(this.streamId == null) {
private fun sendUpdate(status: ApplyStateStatus) {
if (streamId == null) {
return
}
val virtualFile = getVirtualFile()
val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
continuePluginService.sendToWebview("updateApplyState", mapOf(
"numDiffs" to this.diffBlocks.size,
"streamId" to this.streamId,
"status" to status,
"fileContent" to "not implemented",
"toolCallId" to this.toolCallId,
"filepath" to virtualFile?.url
))
// Define a single payload and use it for sending
val payload = ApplyState(
streamId = streamId,
status = status.status,
numDiffs = diffBlocks.size,
filepath = virtualFile?.url,
fileContent = "not implemented",
toolCallId = toolCallId?.toString()
)
continuePluginService.sendToWebview("updateApplyState", payload)
}
fun acceptAll() {
editor.markupModel.removeAllHighlighters();
sendUpdate("closed")
resetState()
ApplicationManager.getApplication().invokeLater {
diffBlocks.toList().forEach { it.handleAccept() }
}
}
fun rejectAll() {
@ -77,26 +79,41 @@ class DiffStreamHandler(
// to our changes. However, if the user has accepted or rejected one or more diff blocks, there isn't a simple
// way to undo our changes without also undoing the diff that the user accepted or rejected.
if (hasAcceptedOrRejectedBlock) {
diffBlocks.forEach { it.handleReject() }
ApplicationManager.getApplication().invokeLater {
val blocksToReject = diffBlocks.toList()
blocksToReject.toList().forEach { it.handleReject() }
}
} else {
undoChanges()
// We have to manually call `handleClosedState`, but above,
// this is done by invoking the button handlers
setClosed()
}
sendUpdate("closed")
resetState()
}
fun streamDiffLinesToEditor(
input: String, prefix: String, highlighted: String, suffix: String, modelTitle: String, includeRulesInSystemMessage: Boolean
input: String,
prefix: String,
highlighted: String,
suffix: String,
modelTitle: String,
includeRulesInSystemMessage: Boolean
) {
isRunning = true
this.sendUpdate("streaming")
val continuePluginService = ServiceManager.getService(project, ContinuePluginService::class.java)
val virtualFile = getVirtualFile()
sendUpdate(ApplyStateStatus.STREAMING)
continuePluginService.coreMessenger?.request(
"streamDiffLines", createRequestParams(input, prefix, highlighted, suffix, virtualFile, modelTitle, includeRulesInSystemMessage), null
"streamDiffLines",
StreamDiffLinesPayload(
input = input,
prefix = prefix,
highlighted = highlighted,
suffix = suffix,
language = virtualFile?.fileType?.name,
modelTitle = modelTitle,
includeRulesInSystemMessage = includeRulesInSystemMessage
),
null
) { response ->
if (!isRunning) return@request
@ -104,7 +121,6 @@ class DiffStreamHandler(
if (response["done"] as? Boolean == true) {
handleFinishedResponse()
sendUpdate(if (diffBlocks.isEmpty()) "closed" else "done")
return@request
}
@ -113,6 +129,9 @@ class DiffStreamHandler(
}
private fun initUnfinishedRangeHighlights() {
val editorUtils = EditorUtils(editor)
val unfinishedKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_UNFINISHED_LINE", 0x20888888)
for (i in startLine..endLine) {
val highlighter = editor.markupModel.addLineHighlighter(
unfinishedKey, min(
@ -155,10 +174,11 @@ class DiffStreamHandler(
}
if (diffBlocks.isEmpty()) {
sendUpdate("closed")
onClose()
setClosed()
} else {
sendUpdate("done")
// TODO: It's confusing that we pass `DONE` here. What we're doing is updating the UI with the latest
// diff count. We should have a dedicated status for this.
sendUpdate(ApplyStateStatus.DONE)
}
}
@ -169,8 +189,6 @@ class DiffStreamHandler(
)
diffBlocks.add(diffBlock)
sendUpdate("streaming")
return diffBlock
}
@ -203,12 +221,17 @@ class DiffStreamHandler(
}
private fun updateProgressHighlighters(type: DiffLineType) {
val editorUtils = EditorUtils(editor)
val curLineKey = editorUtils.createTextAttributesKey("CONTINUE_DIFF_CURRENT_LINE", 0x40888888)
// Update the highlighter to show the current line
curLine.highlighter?.let { editor.markupModel.removeHighlighter(it) }
curLine.highlighter = editor.markupModel.addLineHighlighter(
curLineKey, min(curLine.index, max(0, editor.document.lineCount - 1)), HighlighterLayer.LAST
)
editorUtils.scrollToLine(curLine.index)
// Remove the unfinished lines highlighter
if (type != DiffLineType.OLD && unfinishedHighlighters.isNotEmpty()) {
editor.markupModel.removeHighlighter(unfinishedHighlighters.removeAt(0))
@ -242,15 +265,18 @@ class DiffStreamHandler(
curLine = CurLineState(startLine)
isRunning = false
// Close the Edit input
// Close the Edit input if editing
onClose()
}
private fun undoChanges() {
if (virtualFile == null) {
return
}
WriteCommandAction.runWriteCommandAction(project) {
val undoManager = UndoManager.getInstance(project)
val virtualFile = getVirtualFile() ?: return@runWriteCommandAction
val fileEditor = FileEditorManager.getInstance(project).getSelectedEditor(virtualFile) as TextEditor
if (undoManager.isUndoAvailable(fileEditor)) {
@ -260,33 +286,9 @@ class DiffStreamHandler(
undoManager.undo(fileEditor)
}
}
sendUpdate("done")
}
}
private fun getVirtualFile(): VirtualFile? {
return FileDocumentManager.getInstance().getFile(editor.document) ?: return null
}
private fun createRequestParams(
input: String,
prefix: String,
highlighted: String,
suffix: String,
virtualFile: VirtualFile?,
modelTitle: String,
includeRulesInSystemMessage: Boolean
): Map<String, Any?> {
return mapOf(
"input" to input,
"prefix" to prefix,
"highlighted" to highlighted,
"suffix" to suffix,
"language" to virtualFile?.fileType?.name,
"modelTitle" to modelTitle,
"includeRulesInSystemMessage" to includeRulesInSystemMessage,
)
}
private fun handleFinishedResponse() {
ApplicationManager.getApplication().invokeLater {
@ -296,6 +298,12 @@ class DiffStreamHandler(
onFinish()
cleanupProgressHighlighters()
if (diffBlocks.isEmpty()) {
setClosed()
} else {
sendUpdate(ApplyStateStatus.DONE)
}
}
}
@ -325,4 +333,10 @@ class DiffStreamHandler(
else -> throw Exception("Unknown diff line type: $type")
}
}
private fun setClosed() {
sendUpdate(ApplyStateStatus.CLOSED)
resetState()
onClose()
}
}

View file

@ -1,22 +1,167 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.Position
import com.github.continuedev.continueintellijextension.Range
import com.github.continuedev.continueintellijextension.utils.toUriOrNull
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.command.WriteCommandAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.SelectionModel
import com.intellij.openapi.editor.colors.TextAttributesKey
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.ui.JBColor
import com.intellij.openapi.editor.ScrollType
class EditorUtils {
fun isTerminal(editor: Editor): Boolean {
return editor.javaClass.name.contains("Terminal")
}
}
fun createTextAttributesKey(name: String, color: Int, editor: Editor): TextAttributesKey {
val attributes = TextAttributes().apply {
backgroundColor = JBColor(color, color)
}
return TextAttributesKey.createTextAttributesKey(name).also {
editor.colorsScheme.setAttributes(it, attributes)
/**
* Utility class for working with Editor instances.
*/
class EditorUtils(val editor: Editor) {
private val project: Project
get() = editor.project!!
/**
* Checks if the editor is a terminal editor
*/
fun isTerminal(): Boolean {
return editor.javaClass.name.contains("Terminal")
}
/**
* Checks if the document is empty (contains only whitespace)
*/
fun isDocumentEmpty(): Boolean {
return editor.document.text.trim().isEmpty()
}
/**
* Gets the total number of lines in the document
*/
fun getLineCount(): Int {
return editor.document.lineCount
}
/**
* Inserts text at the specified position in the document
*/
fun insertTextAtPos(pos: Int, text: String) {
WriteCommandAction.runWriteCommandAction(project) {
editor.document.insertString(pos, text)
}
}
/**
* Inserts text at the beginning of the document
*/
fun insertTextIntoEmptyDocument(text: String) {
insertTextAtPos(0, text)
}
/**
* Scrolls the editor to make the specified line visible
*/
fun scrollToLine(lineNumber: Int) {
val safeLineNumber = lineNumber.coerceIn(0, editor.document.lineCount - 1)
val lineStartOffset = editor.document.getLineStartOffset(safeLineNumber)
val logicalPosition = editor.offsetToLogicalPosition(lineStartOffset)
editor.scrollingModel.scrollTo(logicalPosition, ScrollType.CENTER_UP)
}
/**
* Extracts code ranges from the editor: (prefix, highlighted/selected text, suffix)
*/
fun extractCodeRanges(): Triple<String, String, String> {
val rif = getHighlightedCode()
return if (rif == null) {
// If no highlight, use the whole document as highlighted
Triple("", editor.document.text, "")
} else {
// Use the RangeInFileWithContents to get absolute offsets
val startOffset = rif.getStartOffset(editor.document)
val endOffset = rif.getEndOffset(editor.document)
val prefix = editor.document.getText(TextRange(0, startOffset))
val highlighted = rif.contents
val suffix = editor.document.getText(TextRange(endOffset, editor.document.textLength))
// Remove the selection after processing
ApplicationManager.getApplication().invokeLater {
editor.selectionModel.removeSelection()
}
Triple(prefix, highlighted, suffix)
}
}
/**
* Gets the selected code from the current editor.
* Returns null if there is no selection.
*/
fun getHighlightedCode(): RangeInFileWithContents? {
return ApplicationManager.getApplication().runReadAction<RangeInFileWithContents?> {
val virtualFile =
FileDocumentManager.getInstance().getFile(editor.document) ?: return@runReadAction null
// Get the selection range
val selectionModel: SelectionModel = editor.selectionModel
val startOffset = selectionModel.selectionStart
val endOffset = selectionModel.selectionEnd
if (startOffset == endOffset) {
return@runReadAction null
}
return@runReadAction virtualFile.toUriOrNull()?.let {
RangeInFileWithContents.fromSelection(
it,
editor.document,
startOffset,
endOffset
)
}
}
}
fun createTextAttributesKey(name: String, color: Int): TextAttributesKey {
val attributes = TextAttributes().apply {
backgroundColor = JBColor(color, color)
}
return TextAttributesKey.createTextAttributesKey(name).also {
editor.colorsScheme.setAttributes(it, attributes)
}
}
companion object {
/**
* Gets an editor for the currently selected file without opening any new files
*/
fun getEditor(project: Project): EditorUtils? {
val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null
return EditorUtils(editor)
}
/**
* Gets or opens an editor for the specified filepath and returns an EditorUtils instance
*/
fun getOrOpenEditor(project: Project, filepath: String?): EditorUtils? {
if (!filepath.isNullOrEmpty()) {
val virtualFile = VirtualFileManager.getInstance().findFileByUrl(filepath)
if (virtualFile != null) {
ApplicationManager.getApplication().invokeAndWait {
FileEditorManager.getInstance(project).openFile(virtualFile, true).first()
}
}
}
val editor = FileEditorManager.getInstance(project).selectedTextEditor ?: return null
return EditorUtils(editor)
}
}
}

View file

@ -120,7 +120,7 @@ fun openInlineEdit(project: Project?, editor: Editor) {
if (project == null) return
// Don't open in terminal
if (EditorUtils().isTerminal(editor)) {
if (EditorUtils(editor).isTerminal()) {
return
}
@ -131,7 +131,8 @@ fun openInlineEdit(project: Project?, editor: Editor) {
val modelTitles = mutableListOf<String>()
continuePluginService.coreMessenger?.request("config/getSerializedProfileInfo", null, null) { response ->
val modelsByRole = response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
val modelsByRole =
response.castNestedOrNull<Map<String, Any>>("content", "result", "config", "modelsByRole") ?: return@request
val role = if (modelsByRole.containsKey("edit")) "edit" else "chat"
modelsByRole.castNestedOrNull<List<*>>(role)
?.mapNotNull { it.castNestedOrNull<String>("title") }

View file

@ -0,0 +1,62 @@
package com.github.continuedev.continueintellijextension.editor
import com.github.continuedev.continueintellijextension.Position
import com.github.continuedev.continueintellijextension.Range
import com.intellij.openapi.editor.Document
import com.intellij.openapi.util.TextRange
/**
* Represents a range of text in a file with its contents.
* Provides utility methods for working with document positions and offsets.
*/
class RangeInFileWithContents(
val filepath: String,
val range: Range,
val contents: String
) {
/**
* Returns the absolute document offset for the start position
*/
fun getStartOffset(document: Document): Int {
return document.getLineStartOffset(range.start.line) + range.start.character
}
/**
* Returns the absolute document offset for the end position
*/
fun getEndOffset(document: Document): Int {
return document.getLineStartOffset(range.end.line) + range.end.character
}
companion object {
/**
* Create a RangeInFileWithContents from a document selection
*/
fun fromSelection(
filepath: String,
document: Document,
selectionStart: Int,
selectionEnd: Int
): RangeInFileWithContents {
val startLine = document.getLineNumber(selectionStart)
val endLine = document.getLineNumber(selectionEnd)
val startChar = selectionStart - document.getLineStartOffset(startLine)
val endChar = selectionEnd - document.getLineStartOffset(endLine)
val selectedText = document.getText(
TextRange(selectionStart, selectionEnd)
)
return RangeInFileWithContents(
filepath,
Range(
Position(startLine, startChar),
Position(endLine, endChar)
),
selectedText
)
}
}
}

View file

@ -32,8 +32,6 @@ class VerticalDiffBlock(
private var deletionInlay: Disposable? = null
private var textArea: JTextArea? = null // Used for calculation of the text area height when rendering buttons
private var hasRenderedDiffBlock: Boolean = false
private val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false)
private val greenKey = createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00, editor)
init {
val (acceptBtn, rejectBtn) = createButtons()
@ -78,6 +76,8 @@ class VerticalDiffBlock(
fun addNewLine(text: String, line: Int) {
val greenKey = EditorUtils(editor).createTextAttributesKey("CONTINUE_DIFF_NEW_LINE", 0x3000FF00)
if (line == editor.document.lineCount) {
editor.document.insertString(editor.document.textLength, "\n")
}
@ -97,7 +97,7 @@ class VerticalDiffBlock(
return
}
if (deletedLines.size > 0) {
if (deletedLines.isNotEmpty()) {
renderDeletedLinesInlay()
}
@ -107,20 +107,32 @@ class VerticalDiffBlock(
}
fun handleReject() {
revertDiff()
// Note that the logic for clearing editor UI state assumes that we do it
// prior to undoing the diff changes, changing this order will break things
clearEditorUI()
revertDiff()
onAcceptReject(this@VerticalDiffBlock, false)
}
fun handleAccept() {
clearEditorUI()
onAcceptReject(this@VerticalDiffBlock, true)
}
private fun refreshEditor() {
editor.contentComponent.revalidate()
editor.contentComponent.repaint()
}
private fun renderDeletedLinesInlay() {
val textArea = createDeletionTextArea(deletedLines.joinToString("\n"))
this.textArea = textArea
val editorComponentInlaysManager = EditorComponentInlaysManager.from(editor, false)
val newTextArea = createDeletionTextArea(deletedLines.joinToString("\n"))
val disposable = editorComponentInlaysManager.insert(startLine, textArea, true)
textArea = newTextArea
val disposable = editorComponentInlaysManager.insert(startLine, newTextArea, true)
deletionInlay = disposable
}
@ -158,7 +170,6 @@ class VerticalDiffBlock(
).apply {
addActionListener {
handleReject()
onAcceptReject(this@VerticalDiffBlock, false)
}
}
@ -171,7 +182,6 @@ class VerticalDiffBlock(
).apply {
addActionListener {
handleAccept()
onAcceptReject(this@VerticalDiffBlock, true)
}
}
@ -185,9 +195,6 @@ class VerticalDiffBlock(
refreshEditor()
}
private fun handleAccept() {
clearEditorUI()
}
private fun revertDiff() {
WriteCommandAction.runWriteCommandAction(project) {

View file

@ -1,6 +1,5 @@
package com.github.continuedev.continueintellijextension.services
import IntelliJIDE
import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
import com.github.continuedev.continueintellijextension.`continue`.CoreMessengerManager
import com.github.continuedev.continueintellijextension.`continue`.DiffManager

View file

@ -1,5 +1,6 @@
package com.github.continuedev.continueintellijextension
import com.github.continuedev.continueintellijextension.editor.RangeInFileWithContents
import com.google.gson.JsonElement
enum class ToastType(val value: String) {
@ -213,3 +214,40 @@ data class Message(
data class AcceptRejectDiff(val accepted: Boolean, val stepIndex: Int)
data class DeleteAtIndex(val index: Int)
enum class ApplyStateStatus(val status: String) {
NOT_STARTED("not-started"),
STREAMING("streaming"),
DONE("done"),
CLOSED("closed");
}
data class ApplyState(
val streamId: String,
val status: String,
val numDiffs: Int? = null,
val filepath: String? = null,
val fileContent: String? = null,
val toolCallId: String? = null
)
data class HighlightedCodePayload(
val rangeInFileWithContents: RangeInFileWithContents,
val prompt: String? = null,
val shouldRun: Boolean? = null
)
data class StreamDiffLinesPayload(
val prefix: String,
val highlighted: String,
val suffix: String,
val input: String,
val language: String?,
val modelTitle: String?,
val includeRulesInSystemMessage: Boolean
)
data class AcceptOrRejectDiffPayload(
val filepath: String,
val streamId: String? = null
)

View file

@ -0,0 +1,94 @@
package com.github.continuedev.continueintellijextension.unit
import com.github.continuedev.continueintellijextension.ApplyStateStatus
import com.github.continuedev.continueintellijextension.IDE
import com.github.continuedev.continueintellijextension.ApplyState
import com.github.continuedev.continueintellijextension.`continue`.ApplyToFileHandler
import com.github.continuedev.continueintellijextension.`continue`.CoreMessenger
import com.github.continuedev.continueintellijextension.editor.DiffStreamService
import com.github.continuedev.continueintellijextension.editor.EditorUtils
import com.github.continuedev.continueintellijextension.protocol.ApplyToFileParams
import com.github.continuedev.continueintellijextension.services.ContinuePluginService
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import io.mockk.*
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.test.runTest
import org.junit.jupiter.api.BeforeEach
import org.junit.jupiter.api.Test
@ExperimentalCoroutinesApi
class ApplyToFileHandlerTest {
// Mock all dependencies
private val mockProject = mockk<Project>(relaxed = true)
private val mockContinuePluginService = mockk<ContinuePluginService>(relaxed = true)
private val mockIde = mockk<IDE>(relaxed = true)
private val mockEditorUtils = mockk<EditorUtils>(relaxed = true)
private val mockDiffStreamService = mockk<DiffStreamService>(relaxed = true)
private val mockEditor = mockk<Editor>(relaxed = true)
private val mockCoreMessenger = mockk<CoreMessenger>(relaxed = true)
// Test subject
private lateinit var handler: ApplyToFileHandler
// Constants for testing
private val testParams = ApplyToFileParams(
"Sample text to apply",
"stream123",
"test/file.kt",
"tool-call-123"
)
@BeforeEach
fun setUp() {
// Common setup
every { mockEditorUtils.editor } returns mockEditor
every { mockContinuePluginService.coreMessenger } returns mockCoreMessenger
// Create the handler with mocked dependencies
handler = ApplyToFileHandler(
mockProject,
mockContinuePluginService,
mockIde,
testParams,
mockEditorUtils,
mockDiffStreamService
)
}
@Test
fun `should insert text directly when document is empty`() = runTest {
// Given
every { mockEditorUtils.isDocumentEmpty() } returns true
// When
handler.handleApplyToFile()
// Then
verify { mockEditorUtils.insertTextIntoEmptyDocument(testParams.text) }
verify(exactly = 0) { mockDiffStreamService.register(any(), any()) } // Ensure no diff streaming happened
// Verify notifications sent
verify {
mockContinuePluginService.sendToWebview(
eq("updateApplyState"),
withArg { payload ->
assert(payload is ApplyState)
assert((payload as ApplyState).status == ApplyStateStatus.STREAMING.status)
},
any()
)
}
verify {
mockContinuePluginService.sendToWebview(
eq("updateApplyState"),
withArg { payload ->
assert(payload is ApplyState)
assert((payload as ApplyState).status == ApplyStateStatus.CLOSED.status)
},
any()
)
}
}
}

View file

@ -0,0 +1,66 @@
package com.github.continuedev.continueintellijextension.unit
import com.github.continuedev.continueintellijextension.`continue`.UriUtils
import org.junit.jupiter.api.Disabled
import org.junit.jupiter.api.Test
import java.io.File
import kotlin.test.assertEquals
class UriUtilsTest {
@Test
fun testUriToFile() {
val uri = "file:///path/to/file"
val file = UriUtils.uriToFile(uri)
assertEquals(File("/path/to/file"), file)
}
@Disabled("Not working")
@Test
fun testUriToFileWithWindowsPath() {
val uri = "file:///C:/path/to/file"
val file = UriUtils.uriToFile(uri)
assertEquals(File("C:/path/to/file"), file)
}
@Test
fun shouldHandleAuthorityComponent() {
val uri = "file://C:/path/to/file"
val file = UriUtils.uriToFile(uri)
assertEquals(File("/C:/path/to/file"), file)
}
@Test
fun testUriToFileWithSpaces() {
val uri = "file:///path/to/file%20with%20spaces"
val file = UriUtils.uriToFile(uri)
assertEquals(File("/path/to/file with spaces"), file)
}
@Test
fun testUriToFileWithSpecialCharacters() {
val uri = "file:///path/to/file%23with%25special%26chars"
val file = UriUtils.uriToFile(uri)
assertEquals(File("/path/to/file#with%special&chars"), file)
}
@Test
fun testUriToFileWithQueryParams() {
val uri = "file:///path/to/file?param=value"
val file = UriUtils.uriToFile(uri)
assertEquals(File("/path/to/file"), file)
}
@Test
fun testUriToFileWithWSLPath() {
val uri = "file:///wsl$/Ubuntu/home/user/file.txt"
val file = UriUtils.uriToFile(uri)
assertEquals(File("/wsl$/Ubuntu/home/user/file.txt"), file)
}
@Test
fun testUriToFileWithWSLLocalhostPath() {
val uri = "file:///wsl.localhost/Ubuntu/home/user/file.txt"
val file = UriUtils.uriToFile(uri)
assertEquals(File("/wsl.localhost/Ubuntu/home/user/file.txt"), file)
}
}

View file

@ -0,0 +1,76 @@
/**
* Notes:
* - `sendIntellijMessage` isn't working, but keeping this around as an example of how we might be able to implement
* - Below is an AI generated summary of what the problem might be based on troubleshooting attempts
* - For details, see https://intellij-support.jetbrains.com/hc/en-us/community/posts/26714246086162--intellij-ui-test-robot-Error-when-attempting-to-click-on-DomElement-491
*
*
* The issue is with how the JCefBrowserFixture.executeJsInBrowser method handles JavaScript code execution.
* When trying to call window.postIntellijMessage, we're encountering these challenges:
*
* 1. **Double Injection Problem**: The postIntellijMessage function already uses JBCefJSQuery.inject internally.
* When we try to call it through executeJsInBrowser, we're essentially trying to pass it through another injection
* mechanism, creating nested injections that break.
*
* 2. **String Escaping Issues**: The way quotes are being escaped between the layers of execution is causing syntax
* errors in the final JavaScript that gets executed.
*
* 3. **Context Isolation**: The executeJsInBrowser method likely runs in a different execution context than where the
* function was defined, causing scope/reference issues.
*
* The key insight is that we cannot directly call a function that itself uses the JBCefJSQuery bridge through the test
* framework's executeJsInBrowser method. These bridge functions are designed to be called directly in the browser
* context, not through another layer of script injection.
*/
package com.github.continuedev.continueintellijextension.utils
import com.intellij.remoterobot.fixtures.JCefBrowserFixture
/**
* Utility functions for interacting with browser components in tests
*/
object BrowserUtils {
/**
* Sends a message to the webview using JCefBrowserFixture's executeJsInBrowser
*
* @param browser The JCefBrowserFixture to execute JavaScript in
* @param messageType The type of message to send
* @param messageData The data object to send as message payload
* @param messageId A unique ID for the message
*/
fun sendIntellijMessage(
browser: JCefBrowserFixture,
messageType: String,
messageData: Any,
messageId: String = "test-message-id"
) {
// Convert the messageData to a JSON string
val dataJson = when (messageData) {
is String -> "\"$messageData\""
else -> messageData.toString()
}
val jsCode = """
(function() {
window.postIntellijMessage(
"$messageType",
$dataJson,
"$messageId"
);
return true;
})();
""".trimIndent()
browser.executeJsInBrowser(jsCode)
}
}
// Extension function for JCefBrowserFixture for easier usage
fun JCefBrowserFixture.sendIntellijMessage(
messageType: String,
messageData: Any,
messageId: String = "test-message-id"
) {
BrowserUtils.sendIntellijMessage(this, messageType, messageData, messageId)
}

View file

@ -46,7 +46,7 @@ export class GUISelectors {
}
public static getToolCallStatusMessage(view: WebView) {
return SelectorUtils.getElementByDataTestId(view, "toggle-div-title");
return SelectorUtils.getElementByDataTestId(view, "tool-call-title");
}
public static getToolButton(view: WebView) {
@ -89,6 +89,14 @@ export class GUISelectors {
);
}
public static getRulesPeek(view: WebView) {
return SelectorUtils.getElementByDataTestId(view, "rules-peek");
}
public static getFirstRulesPeekItem(view: WebView) {
return SelectorUtils.getElementByDataTestId(view, "rules-peek-item");
}
public static getNthHistoryTableRow(view: WebView, index: number) {
return SelectorUtils.getElementByDataTestId(view, `history-row-${index}`);
}

View file

@ -245,6 +245,47 @@ describe("GUI Test", () => {
await GUIActions.selectModeFromDropdown(view, "Agent");
});
it("should display rules peek and show rule details", async () => {
// Send a message to trigger the model response
const [messageInput] = await GUISelectors.getMessageInputFields(view);
await messageInput.sendKeys("Hello");
await messageInput.sendKeys(Key.ENTER);
// Wait for the response to appear
await TestUtils.waitForSuccess(() =>
GUISelectors.getThreadMessageByText(view, "I'm going to call a tool:"),
);
// Verify that "1 rule" text appears
const rulesPeek = await TestUtils.waitForSuccess(() =>
GUISelectors.getRulesPeek(view),
);
const rulesPeekText = await rulesPeek.getText();
expect(rulesPeekText).to.include("1 rule");
// Click on the rules peek to expand it
await rulesPeek.click();
// Wait for the rule details to appear
const ruleItem = await TestUtils.waitForSuccess(() =>
GUISelectors.getFirstRulesPeekItem(view),
);
await TestUtils.waitForSuccess(async () => {
const text = await ruleItem.getText();
if (!text || text.trim() === "") {
throw new Error("Rule item text is empty");
}
return ruleItem;
});
// Verify the rule content
const ruleItemText = await ruleItem.getText();
expect(ruleItemText).to.include("Assistant rule");
expect(ruleItemText).to.include("Always applied");
expect(ruleItemText).to.include("TEST_SYS_MSG");
}).timeout(DEFAULT_TIMEOUT.MD);
it("should render tool call", async () => {
const [messageInput] = await GUISelectors.getMessageInputFields(view);
await messageInput.sendKeys("Hello");
@ -258,7 +299,9 @@ describe("GUI Test", () => {
expect(await statusMessage.getText()).contain(
"Continue viewed the git diff",
);
}).timeout(DEFAULT_TIMEOUT.MD);
// wait for 30 seconds, promise
await new Promise((resolve) => setTimeout(resolve, 30000));
}).timeout(DEFAULT_TIMEOUT.MD * 100);
it("should call tool after approval", async () => {
await GUIActions.toggleToolPolicy(view, "builtin_view_diff", 2);

View file

@ -1,12 +1,12 @@
{
"name": "continue",
"version": "1.1.34",
"version": "1.1.35",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "continue",
"version": "1.1.34",
"version": "1.1.35",
"license": "Apache-2.0",
"dependencies": {
"@continuedev/config-types": "^1.0.14",
@ -53,7 +53,7 @@
"svg-builder": "^2.0.0",
"systeminformation": "^5.23.7",
"tailwindcss": "^3.3.2",
"undici": "^6.2.0",
"undici": "^6.21.3",
"uuid": "^9.0.1",
"uuidv4": "^6.2.13",
"vectordb": "^0.4.20",
@ -13095,9 +13095,9 @@
"dev": true
},
"node_modules/undici": {
"version": "6.21.1",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.21.1.tgz",
"integrity": "sha512-q/1rj5D0/zayJB2FraXdaWxbhWiNKDvu8naDT2dl1yTlvJp4BLtOcp2a5BvgGNQpYYJzau7tf1WgKv3b+7mqpQ==",
"version": "6.21.3",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.21.3.tgz",
"integrity": "sha512-gBLkYIlEnSp8pFbT64yFgGE6UIB9tAkhukC23PmMDCe5Nd+cRqKxSjw5y54MK2AZMgZfJWMaNE4nYUHgi1XEOw==",
"license": "MIT",
"engines": {
"node": ">=18.17"

View file

@ -2,7 +2,7 @@
"name": "continue",
"icon": "media/icon.png",
"author": "Continue Dev, Inc",
"version": "1.1.34",
"version": "1.1.35",
"repository": {
"type": "git",
"url": "https://github.com/continuedev/continue"
@ -709,7 +709,7 @@
"svg-builder": "^2.0.0",
"systeminformation": "^5.23.7",
"tailwindcss": "^3.3.2",
"undici": "^6.2.0",
"undici": "^6.21.3",
"uuid": "^9.0.1",
"uuidv4": "^6.2.13",
"vectordb": "^0.4.20",

View file

@ -23,22 +23,16 @@ export interface VerticalDiffHandlerOptions {
}
export class VerticalDiffHandler implements vscode.Disposable {
public insertedInCurrentBlock = 0;
disposables: vscode.Disposable[] = [];
private currentLineIndex: number;
private cancelled = false;
private newLinesAdded = 0;
private deletionBuffer: string[] = [];
private removedLineDecorations: RemovedLineDecorationManager;
private addedLineDecorations: AddedLineDecorationManager;
private get fileUri() {
return this.editor.document.uri.toString();
}
public insertedInCurrentBlock = 0;
public get range(): vscode.Range {
const startLine = Math.min(this.startLine, this.endLine);
const endLine = Math.max(this.startLine, this.endLine);
return new vscode.Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER);
}
private _diffLinesQueue: DiffLine[] = [];
private _queueLock = false;
constructor(
private startLine: number,
@ -79,6 +73,308 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.disposables.push(disposable);
}
public get range(): vscode.Range {
const startLine = Math.min(this.startLine, this.endLine);
const endLine = Math.max(this.startLine, this.endLine);
return new vscode.Range(startLine, 0, endLine, Number.MAX_SAFE_INTEGER);
}
get isCancelled() {
return this.cancelled;
}
private get fileUri() {
return this.editor.document.uri.toString();
}
async clear(accept: boolean) {
vscode.commands.executeCommand(
"setContext",
"continue.streamingDiff",
false,
);
const removedRanges = this.removedLineDecorations.ranges;
if (accept) {
// Accept all: delete all the red ranges and clear green decorations
await this.deleteRangeLines(removedRanges.map((r) => r.range));
} else {
// Reject all: Re-insert red lines, delete green ones
for (const r of removedRanges) {
await this.deleteRangeLines([r.range]);
await this.insertTextAboveLine(r.range.start.line, r.line);
}
await this.deleteRangeLines(this.addedLineDecorations.ranges);
}
this.clearDecorations();
this.options.onStatusUpdate(
"closed",
this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0,
this.editor.document.getText(),
);
this.cancelled = true;
this.refreshCodeLens();
this.dispose();
}
dispose() {
this.disposables.forEach((disposable) => disposable.dispose());
}
async queueDiffLine(diffLine: DiffLine | undefined) {
if (diffLine) {
this._diffLinesQueue.push(diffLine);
}
if (this._queueLock || this.editor !== vscode.window.activeTextEditor) {
return;
}
this._queueLock = true;
while (this._diffLinesQueue.length) {
const line = this._diffLinesQueue.shift();
if (!line) {
break;
}
try {
await this._handleDiffLine(line);
} catch (e) {
// If editor is switched between calling _handleDiffLine and the edit actually being executed
this._diffLinesQueue.push(line);
break;
}
}
this._queueLock = false;
}
async run(diffLineGenerator: AsyncGenerator<DiffLine>) {
let diffLines = [];
try {
// As an indicator of loading
this.updateIndexLineDecorations();
for await (const diffLine of diffLineGenerator) {
if (this.isCancelled) {
return;
}
diffLines.push(diffLine);
await this.queueDiffLine(diffLine);
}
// Clear deletion buffer
await this.insertDeletionBuffer();
await this.reapplyWithMyersDiff(diffLines);
const range = new vscode.Range(this.startLine, 0, this.startLine, 0);
this.editor.revealRange(
range,
vscode.TextEditorRevealType.Default,
);
this.options.onStatusUpdate(
"done",
this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0,
this.editor.document.getText(),
);
// Reject on user typing
// const listener = vscode.workspace.onDidChangeTextDocument((e) => {
// if (URI.equal(e.document.uri.toString(), this.fileUri)) {
// this.clear(false);
// listener.dispose();
// }
// });
} catch (e) {
this.clearForFileUri(this.fileUri, false);
throw e;
}
return diffLines;
}
async acceptRejectBlock(
accept: boolean,
startLine: number,
numGreen: number,
numRed: number,
skipStatusUpdate?: boolean,
) {
if (numGreen > 0) {
// Delete the editor decoration
this.addedLineDecorations.deleteRangeStartingAt(startLine + numRed);
if (!accept) {
// Delete the actual lines
await this.deleteLinesAt(startLine + numRed, numGreen);
}
}
if (numRed > 0) {
const deleted =
this.removedLineDecorations.deleteRangesStartingAt(startLine);
await this.deleteLinesAt(startLine, numRed);
if (deleted && !accept) {
await this.insertTextAboveLine(
startLine,
deleted.map((r) => r.line).join("\n"),
);
}
}
// Shift everything below upward
const offset = -(accept ? numRed : numGreen);
this.removedLineDecorations.shiftDownAfterLine(startLine, offset);
this.addedLineDecorations.shiftDownAfterLine(startLine, offset);
// Shift the codelens objects
this.shiftCodeLensObjects(startLine, offset);
if (!skipStatusUpdate) {
const numDiffs =
this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0;
const status = numDiffs === 0 ? "closed" : undefined;
this.options.onStatusUpdate(
status,
numDiffs,
this.editor.document.getText(),
);
}
}
public updateLineDelta(
fileUri: string,
startLine: number,
lineDelta: number,
) {
// Retrieve the diff blocks for the given file
const blocks = this.editorToVerticalDiffCodeLens.get(fileUri);
if (!blocks) {
return;
}
// Update decorations
this.removedLineDecorations.shiftDownAfterLine(startLine, lineDelta);
this.addedLineDecorations.shiftDownAfterLine(startLine, lineDelta);
// Update code lens
this.shiftCodeLensObjects(startLine, lineDelta);
}
public hasDiffForCurrentFile(): boolean {
const diffBlocks = this.editorToVerticalDiffCodeLens.get(this.fileUri);
return diffBlocks !== undefined && diffBlocks.length > 0;
}
clearDecorations() {
this.removedLineDecorations.clear();
this.addedLineDecorations.clear();
this.clearIndexLineDecorations();
this.editorToVerticalDiffCodeLens.delete(this.fileUri);
this.refreshCodeLens();
}
/**
* This method is used to apply diff decorations after the intiial stream.
* This is to handle scenarios where we miscalculate the original diff blocks,
* and decide to follow up with a deterministic algorithm like Myers Diff once
* we have received all of the diff lines.
*/
async reapplyWithMyersDiff(diffLines: DiffLine[]) {
// Diff is messed up without this delay.
await new Promise((resolve) => setTimeout(resolve, 100));
// First, we reset the original diff by rejecting all pending diff blocks
const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) ?? [];
for (const block of blocks.reverse()) {
await this.acceptRejectBlock(
false,
block.start,
block.numGreen,
block.numRed,
true,
);
}
this.clearDecorations();
// Then, get our old/new file content based on the original lines
// We need the input to be "newline terminated" rather than
// newline separated, because myersDiff() would consider
// ["A"] => "A" and ["A", ""] => "A\n" to be the same single line.
// "A\n" and "A\n\n" are unambiguous.
const oldFileContent =
diffLines
.filter((line) => line.type === "same" || line.type === "old")
.map((line) => line.line)
.join("\n") + "\n";
const newFileContent =
diffLines
.filter((line) => line.type === "same" || line.type === "new")
.map((line) => line.line)
.join("\n") + "\n";
const myersDiffs = myersDiff(oldFileContent, newFileContent);
const replaceContent = myersDiffs
.map((diff) => (diff.type === "old" ? "" : diff.line))
.join("\n");
// Then, we insert our diff lines
await this.editor.edit((editBuilder) => {
editBuilder.replace(this.range, replaceContent),
{
undoStopAfter: false,
undoStopBefore: false,
};
});
// Lastly, we apply decorations
let numRed = 0;
let numGreen = 0;
const codeLensBlocks: VerticalDiffCodeLens[] = [];
myersDiffs.forEach((diff, index) => {
if (diff.type === "old") {
this.removedLineDecorations.addLine(this.startLine + index, diff.line);
numRed++;
} else if (diff.type === "new") {
this.addedLineDecorations.addLine(this.startLine + index);
numGreen++;
} else if (diff.type === "same" && (numRed > 0 || numGreen > 0)) {
codeLensBlocks.push({
numRed,
numGreen,
start: this.startLine + index - numRed - numGreen,
});
numRed = 0;
numGreen = 0;
}
});
if (numRed > 0 || numGreen > 0) {
codeLensBlocks.push({
numGreen,
numRed,
start: this.startLine + myersDiffs.length - numRed - numGreen,
});
}
this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks);
this.refreshCodeLens();
}
private async insertDeletionBuffer() {
if (this.deletionBuffer.length || this.insertedInCurrentBlock > 0) {
const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) || [];
@ -229,81 +525,6 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.editor.setDecorations(indexDecorationType, []);
}
async clear(accept: boolean) {
vscode.commands.executeCommand(
"setContext",
"continue.streamingDiff",
false,
);
const removedRanges = this.removedLineDecorations.ranges;
if (accept) {
// Accept all: delete all the red ranges and clear green decorations
await this.deleteRangeLines(removedRanges.map((r) => r.range));
} else {
// Reject all: Re-insert red lines, delete green ones
for (const r of removedRanges) {
await this.deleteRangeLines([r.range]);
await this.insertTextAboveLine(r.range.start.line, r.line);
}
await this.deleteRangeLines(this.addedLineDecorations.ranges);
}
this.clearDecorations();
this.options.onStatusUpdate(
"closed",
this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0,
this.editor.document.getText(),
);
this.cancelled = true;
this.refreshCodeLens();
this.dispose();
}
disposables: vscode.Disposable[] = [];
dispose() {
this.disposables.forEach((disposable) => disposable.dispose());
}
get isCancelled() {
return this.cancelled;
}
private _diffLinesQueue: DiffLine[] = [];
private _queueLock = false;
async queueDiffLine(diffLine: DiffLine | undefined) {
if (diffLine) {
this._diffLinesQueue.push(diffLine);
}
if (this._queueLock || this.editor !== vscode.window.activeTextEditor) {
return;
}
this._queueLock = true;
while (this._diffLinesQueue.length) {
const line = this._diffLinesQueue.shift();
if (!line) {
break;
}
try {
await this._handleDiffLine(line);
} catch (e) {
// If editor is switched between calling _handleDiffLine and the edit actually being executed
this._diffLinesQueue.push(line);
break;
}
}
this._queueLock = false;
}
private async _handleDiffLine(diffLine: DiffLine) {
switch (diffLine.type) {
case "same":
@ -323,104 +544,6 @@ export class VerticalDiffHandler implements vscode.Disposable {
}
}
async run(diffLineGenerator: AsyncGenerator<DiffLine>) {
let diffLines = [];
try {
// As an indicator of loading
this.updateIndexLineDecorations();
for await (const diffLine of diffLineGenerator) {
if (this.isCancelled) {
return;
}
diffLines.push(diffLine);
await this.queueDiffLine(diffLine);
}
// Clear deletion buffer
await this.insertDeletionBuffer();
await this.reapplyWithMyersDiff(diffLines);
const range = new vscode.Range(this.startLine, 0, this.startLine, 0);
this.editor.revealRange(
range,
vscode.TextEditorRevealType.Default,
);
this.options.onStatusUpdate(
"done",
this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0,
this.editor.document.getText(),
);
// Reject on user typing
// const listener = vscode.workspace.onDidChangeTextDocument((e) => {
// if (URI.equal(e.document.uri.toString(), this.fileUri)) {
// this.clear(false);
// listener.dispose();
// }
// });
} catch (e) {
this.clearForFileUri(this.fileUri, false);
throw e;
}
return diffLines;
}
async acceptRejectBlock(
accept: boolean,
startLine: number,
numGreen: number,
numRed: number,
skipStatusUpdate?: boolean,
) {
if (numGreen > 0) {
// Delete the editor decoration
this.addedLineDecorations.deleteRangeStartingAt(startLine + numRed);
if (!accept) {
// Delete the actual lines
await this.deleteLinesAt(startLine + numRed, numGreen);
}
}
if (numRed > 0) {
const deleted =
this.removedLineDecorations.deleteRangesStartingAt(startLine);
await this.deleteLinesAt(startLine, numRed);
if (deleted && !accept) {
await this.insertTextAboveLine(
startLine,
deleted.map((r) => r.line).join("\n"),
);
}
}
// Shift everything below upward
const offset = -(accept ? numRed : numGreen);
this.removedLineDecorations.shiftDownAfterLine(startLine, offset);
this.addedLineDecorations.shiftDownAfterLine(startLine, offset);
// Shift the codelens objects
this.shiftCodeLensObjects(startLine, offset);
if (!skipStatusUpdate) {
const numDiffs =
this.editorToVerticalDiffCodeLens.get(this.fileUri)?.length ?? 0;
const status = numDiffs === 0 ? "closed" : undefined;
this.options.onStatusUpdate(
status,
numDiffs,
this.editor.document.getText(),
);
}
}
private shiftCodeLensObjects(startLine: number, offset: number) {
// Shift the codelens objects
const blocks =
@ -437,128 +560,4 @@ export class VerticalDiffHandler implements vscode.Disposable {
this.refreshCodeLens();
}
public updateLineDelta(
fileUri: string,
startLine: number,
lineDelta: number,
) {
// Retrieve the diff blocks for the given file
const blocks = this.editorToVerticalDiffCodeLens.get(fileUri);
if (!blocks) {
return;
}
// Update decorations
this.removedLineDecorations.shiftDownAfterLine(startLine, lineDelta);
this.addedLineDecorations.shiftDownAfterLine(startLine, lineDelta);
// Update code lens
this.shiftCodeLensObjects(startLine, lineDelta);
}
public hasDiffForCurrentFile(): boolean {
const diffBlocks = this.editorToVerticalDiffCodeLens.get(this.fileUri);
return diffBlocks !== undefined && diffBlocks.length > 0;
}
clearDecorations() {
this.removedLineDecorations.clear();
this.addedLineDecorations.clear();
this.clearIndexLineDecorations();
this.editorToVerticalDiffCodeLens.delete(this.fileUri);
this.refreshCodeLens();
}
/**
* This method is used to apply diff decorations after the intiial stream.
* This is to handle scenarios where we miscalculate the original diff blocks,
* and decide to follow up with a deterministic algorithm like Myers Diff once
* we have received all of the diff lines.
*/
async reapplyWithMyersDiff(diffLines: DiffLine[]) {
// Diff is messed up without this delay.
await new Promise((resolve) => setTimeout(resolve, 100));
// First, we reset the original diff by rejecting all pending diff blocks
const blocks = this.editorToVerticalDiffCodeLens.get(this.fileUri) ?? [];
for (const block of blocks.reverse()) {
await this.acceptRejectBlock(
false,
block.start,
block.numGreen,
block.numRed,
true,
);
}
this.clearDecorations();
// Then, get our old/new file content based on the original lines
// We need the input to be "newline terminated" rather than
// newline separated, because myersDiff() would consider
// ["A"] => "A" and ["A", ""] => "A\n" to be the same single line.
// "A\n" and "A\n\n" are unambiguous.
const oldFileContent =
diffLines
.filter((line) => line.type === "same" || line.type === "old")
.map((line) => line.line)
.join("\n") + "\n";
const newFileContent =
diffLines
.filter((line) => line.type === "same" || line.type === "new")
.map((line) => line.line)
.join("\n") + "\n";
const myersDiffs = myersDiff(oldFileContent, newFileContent);
const replaceContent = myersDiffs
.map((diff) => (diff.type === "old" ? "" : diff.line))
.join("\n");
// Then, we insert our diff lines
await this.editor.edit((editBuilder) => {
editBuilder.replace(this.range, replaceContent),
{
undoStopAfter: false,
undoStopBefore: false,
};
});
// Lastly, we apply decorations
let numRed = 0;
let numGreen = 0;
const codeLensBlocks: VerticalDiffCodeLens[] = [];
myersDiffs.forEach((diff, index) => {
if (diff.type === "old") {
this.removedLineDecorations.addLine(this.startLine + index, diff.line);
numRed++;
} else if (diff.type === "new") {
this.addedLineDecorations.addLine(this.startLine + index);
numGreen++;
} else if (diff.type === "same" && (numRed > 0 || numGreen > 0)) {
codeLensBlocks.push({
numRed,
numGreen,
start: this.startLine + index - numRed - numGreen,
});
numRed = 0;
numGreen = 0;
}
});
if (numRed > 0 || numGreen > 0) {
codeLensBlocks.push({
numGreen,
numRed,
start: this.startLine + myersDiffs.length - numRed - numGreen,
});
}
this.editorToVerticalDiffCodeLens.set(this.fileUri, codeLensBlocks);
this.refreshCodeLens();
}
}

View file

@ -15,6 +15,7 @@ import {
import { stripImages } from "core/util/messageContent";
import * as vscode from "vscode";
import { DataLogger } from "core/data/log";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
import { ApplyManager } from "../apply";
import { VerticalDiffManager } from "../diff/vertical/manager";
@ -228,6 +229,18 @@ export class VsCodeMessenger {
),
rulesToInclude: config.rules,
});
// Log dev data
await DataLogger.getInstance().logDevData({
name: "editInteraction",
data: {
prompt: stripImages(prompt),
completion: fileAfterEdit ?? "",
modelProvider: model.providerName,
modelTitle: model.title ?? "",
},
});
return fileAfterEdit;
});

View file

@ -3,7 +3,7 @@
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint", "eslint-plugin-react"],
"parserOptions": {
"project": "gui/tsconfig.json"
"project": ["tsconfig.json", "tsconfig.node.json"]
},
"extends": [
// "eslint:recommended",

View file

@ -12,7 +12,8 @@
"test": "vitest run",
"test:coverage": "vitest run --coverage",
"test:ui": "vitest --ui",
"test:watch": "vitest"
"test:watch": "vitest",
"lint": "eslint --ext ts"
},
"dependencies": {
"@continuedev/config-yaml": "file:../packages/config-yaml",

View file

@ -22,6 +22,7 @@ export default function AcceptRejectAllButtons({
const ideMessenger = useContext(IdeMessengerContext);
const tinyFont = useFontSize(-3);
async function handleAcceptOrReject(status: AcceptOrRejectOutcome) {
for (const { filepath = "", streamId } of pendingApplyStates) {
ideMessenger.post(status, {

View file

@ -1,6 +1,5 @@
import { CheckIcon, PlayIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { ApplyState } from "core";
import { useEffect, useState } from "react";
import { getMetaKeyLabel } from "../../../util";
import Spinner from "../../gui/Spinner";
import { ToolTip } from "../../gui/Tooltip";
@ -16,47 +15,10 @@ interface ApplyActionsProps {
}
export function ApplyActions(props: ApplyActionsProps) {
const [hasRejected, setHasRejected] = useState(false);
const [showApplied, setShowApplied] = useState(false);
const isClosed = props.applyState?.status === "closed";
const isSuccessful = !hasRejected && props.applyState?.numDiffs === 0;
useEffect(() => {
if (isClosed && isSuccessful) {
setShowApplied(true);
const timer = setTimeout(() => {
setShowApplied(false);
}, 3_000);
return () => clearTimeout(timer);
}
}, [isClosed, isSuccessful]);
function onClickReject() {
props.onClickReject();
setHasRejected(true);
}
const applyButton = (text: string) => (
<HoverItem
data-tooltip-id="codeblock-apply-code-button-tooltip"
className="!p-0"
>
<button
data-testid="codeblock-toolbar-apply"
className="text-lightgray text-[${vscForeground}] flex cursor-pointer items-center border-none bg-transparent pl-0 text-xs outline-none hover:brightness-125"
onClick={props.onClickApply}
>
<div className="text-lightgray flex items-center gap-1">
<PlayIcon className="h-3.5 w-3.5" />
<span className="xs:inline hidden">{text}</span>
</div>
</button>
<ToolTip id="codeblock-apply-code-button-tooltip" place="top">
{text} Code
</ToolTip>
</HoverItem>
);
switch (props.applyState ? props.applyState.status : null) {
case "streaming":
return (
@ -94,21 +56,30 @@ export function ApplyActions(props: ApplyActionsProps) {
</div>
);
case "closed":
if (isSuccessful) {
if (showApplied || props.disableManualApply) {
return (
<span className="flex select-none items-center rounded bg-zinc-700 text-slate-400 max-sm:px-0.5 sm:pl-2">
<span className="max-sm:hidden">Applied</span>
<CheckIcon className="h-3.5 w-3.5 hover:brightness-125 sm:px-1" />
</span>
);
}
return applyButton("Reapply");
}
default:
if (props.disableManualApply) {
return null;
}
return applyButton("Apply");
return (
<HoverItem
data-tooltip-id="codeblock-apply-code-button-tooltip"
className="!p-0"
>
<button
data-testid="codeblock-toolbar-apply"
className="text-lightgray text-[${vscForeground}] flex cursor-pointer items-center border-none bg-transparent pl-0 text-xs outline-none hover:brightness-125"
onClick={props.onClickApply}
>
<div className="text-lightgray flex items-center gap-1">
<PlayIcon className="h-3.5 w-3.5" />
<span className="xs:inline hidden">Apply</span>
</div>
</button>
<ToolTip id="codeblock-apply-code-button-tooltip" place="top">
Apply Code
</ToolTip>
</HoverItem>
);
}
}

View file

@ -243,7 +243,7 @@ export function StepContainerPreToolbar({
const plural = numLines === 1 ? "" : "s";
if (isGeneratingCodeBlock) {
return (
<span className="text-lightgray inline-flex w-min items-center gap-2">
<span className="text-lightgray inline-flex items-center gap-2 text-right">
{!isExpanded ? `${numLines} line${plural}` : "Generating"}{" "}
<div>
<Spinner />
@ -252,7 +252,7 @@ export function StepContainerPreToolbar({
);
} else {
return (
<span className="text-lightgray inline-flex w-min items-center gap-2">
<span className="text-lightgray inline-flex items-center gap-2 text-right">
{`${numLines} line${plural} pending`}
</span>
);

View file

@ -6,15 +6,21 @@ interface ToggleProps {
children: React.ReactNode;
title: React.ReactNode;
icon?: ComponentType<React.SVGProps<SVGSVGElement>>;
testId?: string;
}
function ToggleDiv({ children, title, icon: Icon }: ToggleProps) {
function ToggleDiv({
children,
title,
icon: Icon,
testId = "context-items-peek",
}: ToggleProps) {
const [open, setOpen] = useState(false);
const [isHovered, setIsHovered] = useState(false);
return (
<div
className={`pl-2 pt-2`}
className={`pl-2`}
style={{
backgroundColor: vscBackground,
}}
@ -24,7 +30,7 @@ function ToggleDiv({ children, title, icon: Icon }: ToggleProps) {
onClick={() => setOpen((prev) => !prev)}
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
data-testid="context-items-peek"
data-testid={testId}
>
<div className="relative mr-1 h-4 w-4">
{Icon && !isHovered && !open ? (
@ -44,10 +50,7 @@ function ToggleDiv({ children, title, icon: Icon }: ToggleProps) {
</>
)}
</div>
<span
className="ml-1 text-xs text-gray-400 transition-colors duration-200"
data-testid="toggle-div-title"
>
<span className="ml-1 text-xs text-gray-400 transition-colors duration-200">
{title}
</span>
</div>

View file

@ -1,5 +1,5 @@
import { ChevronRightIcon, XMarkIcon } from "@heroicons/react/24/outline";
import { CodeToEdit } from "core";
import { SetCodeToEditPayload } from "core";
import { getMarkdownLanguageTagForFile } from "core/util";
import { getUriPathBasename } from "core/util/uri";
import { useContext, useMemo, useState } from "react";
@ -26,7 +26,7 @@ const NoPaddingWrapper = styled.div`
`;
interface CodeToEditItemProps {
code: CodeToEdit;
code: SetCodeToEditPayload;
}
function CodeToEditItem({ code }: CodeToEditItemProps) {
@ -143,6 +143,7 @@ function CodeToEditItem({ code }: CodeToEditItemProps) {
</div>
);
}
export default function CodeToEditCard() {
// Array from previous multi-file edit
const codeToEditArray = useAppSelector(

View file

@ -1,11 +1,12 @@
import { Editor, JSONContent } from "@tiptap/react";
import { ContextItemWithId, InputModifiers } from "core";
import { ContextItemWithId, InputModifiers, RuleWithSource } from "core";
import { useMemo } from "react";
import styled, { keyframes } from "styled-components";
import { defaultBorderRadius, vscBackground } from "..";
import { useAppSelector } from "../../redux/hooks";
import { selectSlashCommandComboBoxInputs } from "../../redux/selectors";
import { ContextItemsPeek } from "./belowMainInput/ContextItemsPeek";
import { RulesPeek } from "./belowMainInput/RulesPeek";
import { ToolbarOptions } from "./InputToolbar";
import { Lump } from "./Lump";
import { TipTapEditor } from "./TipTapEditor";
@ -20,6 +21,7 @@ interface ContinueInputBoxProps {
) => void;
editorState?: JSONContent;
contextItems?: ContextItemWithId[];
appliedRules?: RuleWithSource[];
hidden?: boolean;
inputId: string; // used to keep track of things per input in redux
}
@ -116,6 +118,8 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
}
: {};
const { appliedRules = [], contextItems = [] } = props;
return (
<div
className={`${props.hidden ? "hidden" : ""}`}
@ -143,10 +147,15 @@ function ContinueInputBox(props: ContinueInputBoxProps) {
/>
</GradientBorder>
</div>
<ContextItemsPeek
contextItems={props.contextItems}
isCurrentContextPeek={props.isLastUserInput}
/>
{(appliedRules.length > 0 || contextItems.length > 0) && (
<div className="mt-2 flex flex-col">
<RulesPeek appliedRules={props.appliedRules} />
<ContextItemsPeek
contextItems={props.contextItems}
isCurrentContextPeek={props.isLastUserInput}
/>
</div>
)}
</div>
);
}

View file

@ -2,7 +2,7 @@ import { useContext } from "react";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
import { exitEditMode } from "../../redux/thunks/editMode";
import AcceptRejectAllButtons from "../AcceptRejectAllButtons";
import AcceptRejectDiffButtons from "../AcceptRejectDiffButtons";
import { useMainEditor } from "./TipTapEditor";
const EditModeDetails = () => {
@ -28,7 +28,7 @@ const EditModeDetails = () => {
<div className="flex flex-col items-center justify-center pb-1 pt-3 text-xs italic text-gray-400">
<span className="">{`${editApplyState.numDiffs} diff${plural} remaining`}</span>
</div>
<AcceptRejectAllButtons
<AcceptRejectDiffButtons
applyStates={[editApplyState]}
onAcceptOrReject={async (outcome) => {
if (outcome === "acceptDiff") {

View file

@ -0,0 +1,122 @@
import { DocumentTextIcon, GlobeAltIcon } from "@heroicons/react/24/outline";
import { RuleSource, RuleWithSource } from "core";
import { ComponentType, useMemo, useState } from "react";
import ToggleDiv from "../../ToggleDiv";
interface RulesPeekProps {
appliedRules?: RuleWithSource[];
icon?: ComponentType<React.SVGProps<SVGSVGElement>>;
}
interface RulesPeekItemProps {
rule: RuleWithSource;
}
// Convert technical source to user-friendly text
const getSourceLabel = (source: RuleSource): string => {
switch (source) {
case "default-chat":
return "Default Chat";
case "default-agent":
return "Default Agent";
case "model-chat-options":
return "Model Chat Options";
case "model-agent-options":
return "Model Agent Options";
case "rules-block":
return "Rules Block";
case "json-systemMessage":
return "System Message";
case ".continuerules":
return "Project Rules";
default:
return source;
}
};
export function RulesPeekItem({ rule }: RulesPeekItemProps) {
const isGlobal = !rule.globs;
const [expanded, setExpanded] = useState(false);
// Define maximum length for rule text display
const maxRuleLength = 100;
const isRuleLong = rule.rule.length > maxRuleLength;
// Get the displayed rule text based on expanded state
const displayedRule =
isRuleLong && !expanded
? `${rule.rule.slice(0, maxRuleLength)}...`
: rule.rule;
const toggleExpand = () => {
if (isRuleLong) {
setExpanded(!expanded);
}
};
return (
<div
className={`group mr-2 flex flex-col overflow-hidden rounded px-1.5 py-1 text-xs hover:bg-white/10 ${isRuleLong ? "cursor-pointer hover:text-gray-200" : ""}`}
data-testid="rules-peek-item"
onClick={toggleExpand}
>
<div className="flex w-full items-center">
{isGlobal ? (
<GlobeAltIcon className="mr-2 h-4 w-4 flex-shrink-0 text-gray-400" />
) : (
<DocumentTextIcon className="mr-2 h-4 w-4 flex-shrink-0 text-gray-400" />
)}
<div className="flex min-w-0 flex-1 gap-2 text-xs">
<div className="max-w-[50%] flex-shrink-0 truncate font-medium">
{rule.name || "Assistant rule"}
</div>
<div className="min-w-0 flex-1 overflow-hidden truncate whitespace-nowrap text-xs text-gray-500">
{isGlobal
? "Always applied"
: `Pattern: ${typeof rule.globs === "string" ? rule.globs : Array.isArray(rule.globs) ? rule.globs.join(", ") : ""}`}
</div>
</div>
</div>
<div
className={`mt-1 whitespace-pre-line pl-6 pr-2 text-xs italic text-gray-300`}
title={
isRuleLong ? (expanded ? "Click to collapse" : "Click to expand") : ""
}
>
{displayedRule}
{isRuleLong && (
<span className="ml-1 text-gray-400 opacity-0 transition-opacity group-hover:opacity-100">
{expanded ? "(collapse)" : "(expand)"}
</span>
)}
</div>
<div className="mt-1 pl-6 pr-2 text-xs text-gray-500">
Source: {getSourceLabel(rule.source)}
</div>
</div>
);
}
export function RulesPeek({ appliedRules, icon }: RulesPeekProps) {
const rules = useMemo(() => {
return appliedRules ?? [];
}, [appliedRules]);
if (!rules || rules.length === 0) {
return null;
}
return (
<ToggleDiv
icon={icon}
title={`${rules.length} rule${rules.length > 1 ? "s" : ""}`}
testId="rules-peek"
>
{rules.map((rule, idx) => (
<RulesPeekItem key={`rule-${idx}`} rule={rule} />
))}
</ToggleDiv>
);
}

View file

@ -173,17 +173,24 @@ function ModeSelect() {
{mode === "chat" && <CheckIcon className="ml-auto h-3 w-3" />}
</ListboxOption>
<ListboxOption value="agent" disabled={!agentModeSupported}>
<ListboxOption
value="agent"
disabled={!agentModeSupported}
className={"gap-1"}
>
<div className="flex flex-row items-center gap-1.5">
<SparklesIcon className="h-3 w-3" />
<span className="">Agent</span>
</div>
{mode === "agent" && <CheckIcon className="ml-auto h-3 w-3" />}
{!agentModeSupported && <span> (Not supported)</span>}
{agentModeSupported ? (
mode === "agent" && <CheckIcon className="ml-auto h-3 w-3" />
) : (
<span>(Not supported)</span>
)}
</ListboxOption>
<div className="text-lightgray px-2 py-1">
{metaKeyLabel}. for next mode
{`${metaKeyLabel} . for next mode`}
</div>
</ListboxOptions>
</div>

View file

@ -166,7 +166,11 @@ function ModelSelect() {
useEffect(() => {
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === "'" && isMetaEquivalentKeyPressed(event as any)) {
if (
event.key === "'" &&
isMetaEquivalentKeyPressed(event as any) &&
!event.shiftKey // To prevent collisions w/ assistant toggle logic
) {
if (!selectedProfile) {
return;
}
@ -179,7 +183,7 @@ function ModelSelect() {
if (nextIndex < 0) nextIndex = options.length - 1;
const newModelTitle = options[nextIndex].value;
dispatch(
void dispatch(
updateSelectedModelByRole({
selectedProfile,
role: "chat",
@ -219,7 +223,7 @@ function ModelSelect() {
<Listbox
onChange={async (val: string) => {
if (val === selectedModel?.title) return;
dispatch(
void dispatch(
updateSelectedModelByRole({
selectedProfile,
role: mode === "edit" ? "edit" : "chat",

View file

@ -19,7 +19,6 @@ export const LocalStorageProvider: React.FC<{ children: React.ReactNode }> = ({
const [values, setValues] = useState<LocalStorageType>(DEFAULT_LOCAL_STORAGE);
// TODO setvalue
useEffect(() => {
const isJetbrains = getLocalStorage("ide") === "jetbrains";
let fontSize = getLocalStorage("fontSize") ?? (isJetbrains ? 15 : 14);

View file

@ -20,6 +20,15 @@ export function HelpCenterSection() {
<div className="py-5">
<h3 className="mb-4 mt-0 text-xl">Help center</h3>
<div className="-mx-4 flex flex-col">
<MoreHelpRow
title="Continue Hub"
description="Visit hub.continue.dev to explore custom assistants and blocks"
Icon={ArrowTopRightOnSquareIcon}
onClick={() =>
ideMessenger.post("openUrl", "https://hub.continue.dev/")
}
/>
<MoreHelpRow
title="Documentation"
description="Learn how to configure and use Continue"

View file

@ -1,8 +1,6 @@
import {
ArrowLeftIcon,
ChatBubbleOvalLeftIcon,
CodeBracketSquareIcon,
ExclamationTriangleIcon,
} from "@heroicons/react/24/outline";
import { Editor, JSONContent } from "@tiptap/react";
import { InputModifiers } from "core";
@ -20,7 +18,6 @@ import {
import { ErrorBoundary } from "react-error-boundary";
import styled from "styled-components";
import { Button, lightGray, vscBackground } from "../../components";
import AcceptRejectAllButtons from "../../components/AcceptRejectAllButtons";
import FeedbackDialog from "../../components/dialogs/FeedbackDialog";
import FreeTrialOverDialog from "../../components/dialogs/FreeTrialOverDialog";
import { useFindWidget } from "../../components/find/FindWidget";
@ -50,7 +47,7 @@ import {
import { cancelStream } from "../../redux/thunks/cancelStream";
import { streamEditThunk } from "../../redux/thunks/editMode";
import { loadLastSession } from "../../redux/thunks/session";
import { streamResponseThunk } from "../../redux/thunks/streamResponse";
import { streamResponseThunk } from "../../redux/thunks";
import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util";
import {
FREE_TRIAL_LIMIT_REQUESTS,
@ -64,6 +61,7 @@ import { EmptyChatBody } from "./EmptyChatBody";
import { ExploreDialogWatcher } from "./ExploreDialogWatcher";
import { ToolCallDiv } from "./ToolCallDiv";
import { useAutoScroll } from "./useAutoScroll";
import AcceptRejectDiffButtons from "../../components/AcceptRejectDiffButtons";
const StepsDiv = styled.div`
position: relative;
@ -74,7 +72,7 @@ const StepsDiv = styled.div`
}
.thread-message {
margin: 0px 0px 0px 1px;
margin: 0 0 0 1px;
}
`;
@ -112,7 +110,7 @@ export function Chat() {
(store) => store.config?.config.selectedModelByRole,
);
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const [stepsOpen, setStepsOpen] = useState<(boolean | undefined)[]>([]);
const [stepsOpen] = useState<(boolean | undefined)[]>([]);
const mainTextInputRef = useRef<HTMLInputElement>(null);
const stepsDivRef = useRef<HTMLDivElement>(null);
const history = useAppSelector((state) => state.session.history);
@ -134,6 +132,8 @@ export function Chat() {
return isJetBrains();
}, []);
useAutoScroll(stepsDivRef, history);
useEffect(() => {
// Cmd + Backspace to delete current step
const listener = (e: any) => {
@ -200,7 +200,7 @@ export function Chat() {
if (newCount >= FREE_TRIAL_LIMIT_REQUESTS) {
// Show this message whether using platform or not
// So that something happens if in new chat
ideMessenger.ide.showToast(
void ideMessenger.ide.showToast(
"error",
"You've reached the free trial limit. Please configure a model to continue.",
);
@ -284,8 +284,6 @@ export function Chat() {
const showScrollbar = showChatScrollbar ?? window.innerHeight > 5000;
useAutoScroll(stepsDivRef, history);
return (
<>
{widget}
@ -301,7 +299,7 @@ export function Chat() {
<div
key={item.message.id}
style={{
minHeight: index === history.length - 1 ? "25vh" : 0,
minHeight: index === history.length - 1 ? "200px" : 0,
}}
>
<ErrorBoundary
@ -320,6 +318,7 @@ export function Chat() {
isMainInput={false}
editorState={item.editorState}
contextItems={item.contextItems}
appliedRules={item.appliedRules}
inputId={item.message.id}
/>
</>
@ -355,23 +354,11 @@ export function Chat() {
<TimelineItem
item={item}
iconElement={
false ? (
<CodeBracketSquareIcon width="16px" height="16px" />
) : false ? (
<ExclamationTriangleIcon
width="16px"
height="16px"
color="red"
/>
) : (
<ChatBubbleOvalLeftIcon width="16px" height="16px" />
)
<ChatBubbleOvalLeftIcon width="16px" height="16px" />
}
open={
typeof stepsOpen[index] === "undefined"
? false
? false
: true
? true
: stepsOpen[index]!
}
onToggle={() => {}}
@ -391,7 +378,7 @@ export function Chat() {
<div className={"relative"}>
<>
{!isStreaming && mode !== "edit" && (
<AcceptRejectAllButtons
<AcceptRejectDiffButtons
applyStates={applyStates}
onAcceptOrReject={async () => {}}
/>

View file

@ -8,6 +8,10 @@ interface CreateFileToolCallProps {
}
export function CreateFile(props: CreateFileToolCallProps) {
if (!props.fileContents) {
return null;
}
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilepath ?? "output.txt")} ${props.relativeFilepath}\n${props.fileContents ?? ""}\n\`\`\``;
return props.relativeFilepath ? (

View file

@ -16,13 +16,12 @@ type EditToolCallProps = {
};
export function EditFile(props: EditToolCallProps) {
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.changes ?? ""}\n\`\`\``;
const dispatch = useAppDispatch();
const isStreaming = useAppSelector((state) => state.session.isStreaming);
const applyState = useAppSelector((state) =>
selectApplyStateByToolCallId(state, props.toolCallId),
);
useEffect(() => {
if (!applyState) {
dispatch(
@ -35,10 +34,12 @@ export function EditFile(props: EditToolCallProps) {
}
}, [applyState, props.toolCallId]);
if (!props.relativeFilePath) {
if (!props.relativeFilePath || !props.changes) {
return null;
}
const src = `\`\`\`${getMarkdownLanguageTagForFile(props.relativeFilePath ?? "test.txt")} ${props.relativeFilePath}\n${props.changes}\n\`\`\``;
return (
<StyledMarkdownPreview
isRenderingInStepContainer

View file

@ -61,7 +61,7 @@ export function SimpleToolCallUI({
</div>
<span
className="ml-1 text-xs text-gray-400 transition-colors duration-200"
data-testid="toggle-div-title"
data-testid="tool-call-title"
>
<ToolCallStatusMessage tool={tool} toolCallState={toolCallState} />
</span>

View file

@ -1,6 +1,8 @@
import { Tool, ToolCallState } from "core";
import Mustache from "mustache";
import { ReactNode } from "react";
import { getFontSize } from "../../../util";
import { useFontSize } from "../../../components/ui/font";
interface ToolCallStatusMessageProps {
tool: Tool | undefined;
@ -11,6 +13,7 @@ export function ToolCallStatusMessage({
tool,
toolCallState,
}: ToolCallStatusMessageProps) {
const fontSize = useFontSize();
if (!tool) return "Agent tool use";
const defaultToolDescription = (
@ -65,7 +68,7 @@ export function ToolCallStatusMessage({
message = futureMessage;
}
return (
<div className="block">
<div className="block" style={{ fontSize }}>
<span>Continue</span> {intro} {message}
</div>
);

View file

@ -1,16 +1,24 @@
import { useEffect, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import { ChatHistoryItemWithMessageId } from "../../redux/slices/sessionSlice";
/**
* Only reset scroll state when a new user message is added to the chat.
* We don't want to auto-scroll on new tool response messages.
*/
function getNumUserMsgs(history: ChatHistoryItemWithMessageId[]) {
return history.filter((msg) => msg.message.role === "user").length;
}
export const useAutoScroll = (
ref: React.RefObject<HTMLDivElement>,
history: unknown[],
history: ChatHistoryItemWithMessageId[],
) => {
const [userHasScrolled, setUserHasScrolled] = useState(false);
const numUserMsgs = useMemo(() => getNumUserMsgs(history), [history.length]);
useEffect(() => {
if (history.length) {
setUserHasScrolled(false);
}
}, [history.length]);
setUserHasScrolled(false);
}, [numUserMsgs]);
useEffect(() => {
if (!ref.current || history.length === 0) return;

View file

@ -1,10 +1,11 @@
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { ApplyState, CodeToEdit, MessageModes } from "core";
import { ApplyState, SetCodeToEditPayload, MessageModes } from "core";
import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
export interface EditModeState {
// Array because of previous multi-file edit functionality
// Keeping array to not break persisted redux for now
codeToEdit: CodeToEdit[];
codeToEdit: SetCodeToEditPayload[];
applyState: ApplyState;
returnToMode: MessageModes;
lastNonEditSessionWasEmpty: boolean;
@ -46,7 +47,7 @@ export const editModeStateSlice = createSlice({
{
payload,
}: PayloadAction<{
codeToEdit: CodeToEdit | CodeToEdit[];
codeToEdit: SetCodeToEditPayload | SetCodeToEditPayload[];
}>,
) => {
state.codeToEdit = Array.isArray(payload.codeToEdit)

View file

@ -15,6 +15,7 @@ import {
FileSymbolMap,
MessageModes,
PromptLog,
RuleWithSource,
Session,
SessionMetadata,
ToolCallDelta,
@ -31,7 +32,7 @@ import { findCurrentToolCall, findToolCall } from "../util";
// We need this to handle reorderings (e.g. a mid-array deletion) of the messages array.
// The proper fix is adding a UUID to all chat messages, but this is the temp workaround.
type ChatHistoryItemWithMessageId = ChatHistoryItem & {
export type ChatHistoryItemWithMessageId = ChatHistoryItem & {
message: ChatMessage & { id: string };
};
@ -247,6 +248,19 @@ export const sessionSlice = createSlice({
...payload.contextItems,
];
},
setAppliedRulesAtIndex: (
state,
{
payload,
}: PayloadAction<{
index: number;
appliedRules: RuleWithSource[];
}>,
) => {
if (state.history[payload.index]) {
state.history[payload.index].appliedRules = payload.appliedRules;
}
},
setInactive: (state) => {
const curMessage = state.history.at(-1);
@ -698,6 +712,7 @@ export const {
updateFileSymbols,
setContextItemsAtIndex,
addContextItemsAtIndex,
setAppliedRulesAtIndex,
setInactive,
streamUpdate,
newSession,

View file

@ -1,6 +1,10 @@
import { createAsyncThunk } from "@reduxjs/toolkit";
import { JSONContent } from "@tiptap/core";
import { CodeToEdit, MessageModes, RangeInFileWithContents } from "core";
import {
SetCodeToEditPayload,
MessageModes,
RangeInFileWithContents,
} from "core";
import { stripImages } from "core/util/messageContent";
import { resolveEditorContent } from "../../components/mainInput/TipTapEditor";
import {
@ -18,7 +22,7 @@ export const streamEditThunk = createAsyncThunk<
void,
{
editorState: JSONContent;
codeToEdit: CodeToEdit[];
codeToEdit: SetCodeToEditPayload[];
},
ThunkApiType
>(

View file

@ -1,12 +1,14 @@
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
import { JSONContent } from "@tiptap/core";
import { InputModifiers } from "core";
import { InputModifiers, ToolResultChatMessage, UserChatMessage } from "core";
import { constructMessages } from "core/llm/constructMessages";
import { getApplicableRules } from "core/llm/rules/getSystemMessageWithRules";
import posthog from "posthog-js";
import { v4 as uuidv4 } from "uuid";
import { getBaseSystemMessage } from "../../util";
import { selectSelectedChatModel } from "../slices/configSlice";
import {
setAppliedRulesAtIndex,
submitEditorAndInitAtIndex,
updateHistoryItemAtIndex,
} from "../slices/sessionSlice";
@ -84,17 +86,41 @@ export const streamResponseThunk = createAsyncThunk<
}),
);
// Construct messages from updated history
// Get updated history after the update
const updatedHistory = getState().session.history;
const messageMode = getState().session.mode
const baseChatOrAgentSystemMessage = getBaseSystemMessage(selectedChatModel, messageMode)
// Determine which rules apply to this message
const userMsg = updatedHistory[inputIndex].message;
const rules = getState().config.config.rules;
// Calculate applicable rules once
// We need to check the message type to match what getApplicableRules expects
const applicableRules = getApplicableRules(
userMsg.role === "user" || userMsg.role === "tool"
? (userMsg as UserChatMessage | ToolResultChatMessage)
: undefined,
rules,
);
// Store in history for UI display
dispatch(
setAppliedRulesAtIndex({
index: inputIndex,
appliedRules: applicableRules,
}),
);
const messageMode = getState().session.mode;
const baseChatOrAgentSystemMessage = getBaseSystemMessage(
selectedChatModel,
messageMode,
);
const messages = constructMessages(
messageMode,
[...updatedHistory],
baseChatOrAgentSystemMessage,
state.config.config.rules,
applicableRules,
);
posthog.capture("step run", {

View file

@ -31,3 +31,6 @@ class Test {
}
}

View file

@ -3,6 +3,7 @@ import * as http from "node:http";
import { AddressInfo } from "node:net";
import * as os from "node:os";
import * as path from "node:path";
import { pathToFileURL } from "url";
import { PackageIdentifier } from "./interfaces/slugs.js";
import { RegistryClient } from "./registryClient.js";
@ -134,6 +135,7 @@ describe("RegistryClient", () => {
describe("getContentFromFilePath", () => {
let absoluteFilePath: string;
let fileUrl: string;
let relativeFilePath: string;
beforeEach(() => {
@ -141,6 +143,11 @@ describe("RegistryClient", () => {
absoluteFilePath = path.join(tempDir, "absolute-path.yaml");
fs.writeFileSync(absoluteFilePath, "absolute file content", "utf8");
const urlFilePath = path.join(tempDir, "file-url-path.yaml");
fs.writeFileSync(urlFilePath, "file:// file content", "utf8");
const url = pathToFileURL(urlFilePath);
fileUrl = url.toString();
// Create a subdirectory and file in the temp directory
const subDir = path.join(tempDir, "sub");
fs.mkdirSync(subDir, { recursive: true });
@ -160,6 +167,14 @@ describe("RegistryClient", () => {
expect(result).toBe("absolute file content");
});
it("should read from local file url directly", () => {
const client = new RegistryClient();
const result = (client as any).getContentFromFilePath(fileUrl);
expect(result).toBe("file:// file content");
});
it("should use rootPath for relative paths when provided", () => {
const client = new RegistryClient({ rootPath: tempDir });

View file

@ -38,11 +38,9 @@ export class RegistryClient implements Registry {
private getContentFromFilePath(filepath: string): string {
if (filepath.startsWith("file://")) {
const pathWithoutProtocol = filepath.slice(7);
// For Windows file:///C:/path/to/file, we need to handle it properly
// On other systems, we might have file:///path/to/file
return fs.readFileSync(decodeURIComponent(pathWithoutProtocol), "utf8");
return fs.readFileSync(new URL(filepath), "utf8");
} else if (path.isAbsolute(filepath)) {
return fs.readFileSync(filepath, "utf8");
} else if (this.rootPath) {

View file

@ -1,6 +1,9 @@
import { z } from "zod";
import { baseDevDataAllSchema } from "../base.js";
/**
* The "editInteraction" event is sent whenever the user submits an input in edit mode and the model's response is completed
*/
export const editInteractionEventAllSchema = baseDevDataAllSchema.extend({
modelProvider: z.string(),
modelTitle: z.string(),

View file

@ -23,6 +23,11 @@ import {
chatInteractionEventSchema_0_2_0,
chatInteractionEventSchema_0_2_0_noCode,
} from "./chatInteraction/v0.2.0.js";
import { editInteractionEventAllSchema } from "./editInteraction/index.js";
import {
editInteractionEventSchema_0_2_0,
editInteractionEventSchema_0_2_0_noCode,
} from "./editInteraction/v0.2.0.js";
import { quickEditEventAllSchema } from "./quickEdit/index.js";
import {
quickEditEventSchema_0_1_0,
@ -66,7 +71,7 @@ const devEventAllVersionDataSchemas = z.object({
chatFeedback: chatFeedbackEventAllSchema,
tokensGenerated: tokensGeneratedEventAllSchema,
chatInteraction: chatInteractionEventAllSchema,
// editInteraction: editInteractionEventAllSchema,
editInteraction: editInteractionEventAllSchema,
});
// Version and level specific schemas are organized here
@ -91,14 +96,14 @@ export const devDataVersionedSchemas = {
chatFeedback: chatFeedbackEventSchema_0_2_0,
tokensGenerated: tokensGeneratedEventSchema_0_2_0,
chatInteraction: chatInteractionEventSchema_0_2_0,
// editInteraction: editInteractionEventSchema_0_2_0,
editInteraction: editInteractionEventSchema_0_2_0,
},
noCode: {
autocomplete: autocompleteEventSchema_0_2_0_noCode,
chatFeedback: chatFeedbackEventSchema_0_2_0_noCode,
tokensGenerated: tokensGeneratedEventSchema_0_2_0_noCode,
chatInteraction: chatInteractionEventSchema_0_2_0_noCode,
// editInteraction: editInteractionEventSchema_0_2_0_noCode,
editInteraction: editInteractionEventSchema_0_2_0_noCode,
},
},
};