Merge branch 'continuedev:main' into main

This commit is contained in:
xiaohuanxiong3 2025-07-02 08:02:26 +08:00 • committed by GitHub
commit 4ebb8030ff
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
354 changed files with 29577 additions and 5131 deletions

View file

@ -0,0 +1,9 @@
---
name: Add Continue pun easter eggs
description: Adds an easter egg whenever the "continue" keyword
pattern: "continue"
---
Our product name is "Continue", so whenever the "continue" statement is used in our codebase, you should add a comment joking about the use of the continue keyword in the Continue codebase
Do not add a comment if the use of "continue" is not in a code continue statement

View file

@ -0,0 +1,8 @@
---
patterns: ["EditAggregator", "processEdit"]
glob: "**/*.tsx"
name: "Enforce EditAggregator Singleton"
description: "Ensure that EditAggregator is used as a singleton in the codebase."
---
When you encounter usage of EditAggregator, be sure that this is compatible with the singleton nature of the EditAggregator class. If you are creating a new instance of EditAggregator, you should instead use the existing singleton. Refer to the `aggregateEdits.ts` to examine how the singleton pattern is used. Do not create a new instance of EditAggregator.

View file

@ -0,0 +1,7 @@
---
name: Update docs from GitHub PR
description: Provide a PR link to update docs based on
alwaysApply: false
---
When provided with a GitHub PR URL, use the GitHub CLI (`gh pr view <PR_URL> --json title,body,commits,files,additions,deletions,changedFiles`) to fetch comprehensive PR details including title, description, commits, changed files, and diff statistics. Analyze the PR content to identify what documentation in the `docs` folder needs to be updated, created, or modified. Update relevant documentation files to reflect the changes, new features, bug fixes, or improvements described in the PR. Ensure documentation changes are accurate, well-structured, and maintain consistency with existing docs formatting and style.

View file

@ -0,0 +1,4 @@
If the user's request is vague and you don't have enough information to confidently answer, you can either
- In Chat OR Agent mode, stop and ask questions to clarify before proceeding
- In Agent mode, use tools to discover more information, starting with the glob/grep tools if available.

View file

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

View file

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

View file

@ -0,0 +1,6 @@
---
name: Programming principles
description: Guidelines for coding fundamentals in this project
---
Use functional programming paradigms whenever possible. Modifying existing classes or creating singletons where needed is acceptable. but otherwise, use functions.

View file

@ -0,0 +1 @@
Always create comprehensive unit tests for new pure functions. Tests should cover normal cases, edge cases, and boundary conditions.

View file

@ -6,25 +6,23 @@ rules:
rule: >-
For unit testing in this project:
1. The project uses Vitest and Jest for testing. Prefer Vitest
1. The project uses Jest as the testing framework
2. Run tests from within the specific package directory (e.g., `cd core && ..`
2. Run tests using `npm test` from within the specific package/module
directory
3. For vitest tests,
- Test files follow the pattern `*.vitest.ts`
- Run tests using `vitest` from within the specific package/module
directory: `cd [directory] && vitest -- [test file path]`
3. Command structure: `cd [directory] && npm test -- [test file path]`
4. For jest tests,
- Test files follow the pattern `*.test.ts`
- Run tests using `npm test` from within the specific package/module
directory: `cd [directory] && npm test -- [test file path]`
- The test script uses experimental VM modules via NODE_OPTIONS flag
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()`
5. For both
- Write tests as top-level `test()` functions - DO NOT use `describe()`
blocks
9. Include the function name being tested in the test description for
- Include the function name being tested in the test description for
clarity

View file

@ -0,0 +1,6 @@
---
name: Never use useEffect
regex: "useEffect"
---
TELL THE USER IN ALL CAPS THAT YOU REFUSE TO TAKE ANY FURTHER ACTION UNTIL THE `useEffect` IS REMOVED FROM THE CODE. IT IS A BAD PRACTICE AND SHOULD NEVER BE NECESSARY. YOU CAN SUGGEST A FIX TO REMOVE THE `useEffect` AND REPLACE IT WITH SOMETHING ELSE, BUT YOU SHOULD REFUSE TO DO ANY OTHER TASKS BEFORE THAT IS DONE.

View file

@ -0,0 +1,5 @@
---
globs: "extensions/vscode/src/commands.ts"
---
When adding new commands to the commands map, always create a separate helper function for the command logic instead of defining it inline. Follow the pattern of existing commands like `streamInlineEdit` - define the helper function below the commands map, then call it from within the command entry.

View file

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

View file

@ -75,6 +75,33 @@ jobs:
cd packages/config-yaml
npm ci
install-openai-adapters:
needs: install-root
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- uses: actions/cache@v4
with:
path: node_modules
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Install openai-adapters dependencies
if: steps.openai-adapters-cache.outputs.cache-hit != 'true'
run: |
cd packages/openai-adapters
npm ci
config-yaml-checks:
needs: install-config-yaml
runs-on: ubuntu-latest
@ -133,7 +160,7 @@ jobs:
npm ci
core-checks:
needs: [install-core, install-config-yaml]
needs: [install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -160,11 +187,21 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Type check and lint
run: |
cd core
@ -174,7 +211,8 @@ jobs:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
install-gui:
needs: [install-root, install-core, install-config-yaml]
needs:
[install-root, install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -205,11 +243,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Install gui dependencies
if: steps.gui-cache.outputs.cache-hit != 'true'
run: |
@ -221,7 +270,6 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
@ -242,6 +290,12 @@ jobs:
path: gui/node_modules
key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- uses: actions/cache@v4
id: config-yaml-cache
with:
@ -253,6 +307,11 @@ jobs:
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Type check and lint
run: |
cd gui
@ -260,7 +319,8 @@ jobs:
npm run lint
binary-checks:
needs: [install-root, install-core, install-config-yaml]
needs:
[install-root, install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -291,11 +351,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Install binary dependencies
if: steps.binary-cache.outputs.cache-hit != 'true'
run: |
@ -308,7 +379,8 @@ jobs:
npx tsc --noEmit
install-vscode:
needs: [install-root, install-core, install-config-yaml]
needs:
[install-root, install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -339,11 +411,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Install vscode dependencies
if: steps.vscode-cache.outputs.cache-hit != 'true'
run: |
@ -384,11 +467,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Type check and lint
run: |
cd extensions/vscode
@ -402,7 +496,7 @@ jobs:
npm run vitest
core-tests:
needs: [install-core, install-config-yaml]
needs: [install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -422,11 +516,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Run core tests
run: |
cd core
@ -476,7 +581,7 @@ jobs:
- uses: actions/checkout@v4
- name: Cache node modules
uses: actions/cache@v3
uses: actions/cache@v4
with:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
@ -515,7 +620,13 @@ jobs:
vscode-package-extension:
runs-on: ubuntu-latest
needs: [install-vscode, install-core, install-config-yaml]
needs:
[
install-vscode,
install-core,
install-config-yaml,
install-openai-adapters,
]
steps:
- uses: actions/checkout@v4
@ -541,11 +652,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Package extension
run: |
cd extensions/vscode
@ -559,7 +681,13 @@ jobs:
vscode-download-e2e-dependencies:
runs-on: ubuntu-latest
needs: [install-vscode, install-core, install-config-yaml]
needs:
[
install-vscode,
install-core,
install-config-yaml,
install-openai-adapters,
]
steps:
- uses: actions/checkout@v4
@ -612,6 +740,7 @@ jobs:
install-vscode,
install-core,
install-config-yaml,
install-openai-adapters,
]
runs-on: ubuntu-latest
# Tests requiring secrets need approval from maintainers
@ -658,11 +787,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Fix VSCode binary permissions
run: |
chmod +x extensions/vscode/e2e/storage/VSCode-linux-x64/code
@ -726,7 +866,8 @@ jobs:
path: extensions/vscode/e2e.log
gui-tests:
needs: [install-gui, install-core, install-config-yaml]
needs:
[install-gui, install-core, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -752,11 +893,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Install GUI dependencies
if: steps.gui-cache.outputs.cache-hit != 'true'
run: cd gui && npm ci
@ -769,7 +921,8 @@ jobs:
npm test
jetbrains-tests:
needs: [install-root, core-checks, install-config-yaml]
needs:
[install-root, core-checks, install-config-yaml, install-openai-adapters]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
@ -784,11 +937,22 @@ jobs:
path: packages/config-yaml/node_modules
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
- uses: actions/cache@v4
id: openai-adapters-cache
with:
path: packages/openai-adapters/node_modules
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
- name: Build config-yaml
run: |
cd packages/config-yaml
npm run build
- name: Build openai-adapters
run: |
cd packages/openai-adapters
npm run build
- name: Setup Java
uses: actions/setup-java@v4.5.0
with:
@ -903,6 +1067,7 @@ jobs:
- jetbrains-tests
- config-yaml-checks
- install-config-yaml
- install-openai-adapters
steps:
- name: Decide whether the needed jobs succeeded or failed

View file

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

View file

@ -9,38 +9,10 @@ on:
jobs:
release:
name: Release
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: Install dependencies
run: |
cd packages/config-yaml
npm ci
- name: Build
run: |
cd packages/config-yaml
npm run build
- name: Run tests
run: |
cd packages/config-yaml
npm test
- name: Release
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
run: |
cd packages/config-yaml
npx semantic-release
uses: ./.github/workflows/reusable-release.yml
with:
package-name: "config-yaml"
package-path: "packages/config-yaml"
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}

18
.github/workflows/release-fetch.yml vendored Normal file
View file

@ -0,0 +1,18 @@
name: Release @continuedev/fetch
on:
push:
branches:
- main
paths:
- "packages/fetch/**"
jobs:
release:
uses: ./.github/workflows/reusable-release.yml
with:
package-name: "fetch"
package-path: "packages/fetch"
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}

18
.github/workflows/release-llm-info.yml vendored Normal file
View file

@ -0,0 +1,18 @@
name: Release @continuedev/llm-info
on:
push:
branches:
- main
paths:
- "packages/llm-info/**"
jobs:
release:
uses: ./.github/workflows/reusable-release.yml
with:
package-name: "llm-info"
package-path: "packages/llm-info"
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}

View file

@ -0,0 +1,18 @@
name: Release @continuedev/openai-adapters
on:
push:
branches:
- main
paths:
- "packages/openai-adapters/**"
jobs:
release:
uses: ./.github/workflows/reusable-release.yml
with:
package-name: "openai-adapters"
package-path: "packages/openai-adapters"
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
SEMANTIC_RELEASE_NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}

55
.github/workflows/reusable-release.yml vendored Normal file
View file

@ -0,0 +1,55 @@
name: Reusable Release Workflow
on:
workflow_call:
inputs:
package-name:
required: true
type: string
package-path:
required: true
type: string
secrets:
SEMANTIC_RELEASE_GITHUB_TOKEN:
required: true
SEMANTIC_RELEASE_NPM_TOKEN:
required: true
permissions:
contents: write
issues: write
pull-requests: write
jobs:
release:
name: Release ${{ inputs.package-name }}
runs-on: ubuntu-latest
defaults:
run:
working-directory: ${{ inputs.package-path }}
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: Install dependencies
run: npm ci
- name: Build
run: npm run build
- name: Run tests
run: npm test
- name: Release
env:
GITHUB_TOKEN: ${{ secrets.SEMANTIC_RELEASE_GITHUB_TOKEN }}
NPM_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
NODE_AUTH_TOKEN: ${{ secrets.SEMANTIC_RELEASE_NPM_TOKEN }}
run: npx semantic-release

26
.vscode/launch.json vendored
View file

@ -73,32 +73,6 @@
"sourceMaps": true
// "preLaunchTask": "gui:dev"
},
// Has to be run after starting the server (separately or using the compound configuration)
{
"name": "Run tests",
"type": "extensionHost",
"request": "launch",
"cwd": "${workspaceFolder}/extensions/vscode",
"runtimeExecutable": "${execPath}",
"args": [
// Pass a directory to run tests in
"${workspaceFolder}/extensions/vscode/manual-testing-sandbox",
"--extensionDevelopmentPath=${workspaceFolder}/extensions/vscode",
"--extensionTestsPath=${workspaceFolder}/extensions/vscode/out/test/runner/mochaRunner"
],
"outFiles": [
// Allows setting breakpoints in test suites across the /src folder
"${workspaceFolder}/extensions/vscode/out/test/test-suites/**/*.js",
// Allows setting breakpoints in mocha test runner file
"${workspaceFolder}/extensions/vscode/out/test/runner/**/*.js"
],
"internalConsoleOptions": "openOnSessionStart",
"preLaunchTask": "vscode-extension:tests:build",
"env": {
// Avoid timing out when stopping on breakpoints during debugging in VSCode
"MOCHA_TIMEOUT": "0"
}
},
{
"name": "[Core] Jest Test Debugger, Current Open File",
"type": "node",

36
.vscode/tasks.json vendored
View file

@ -103,42 +103,12 @@
"clear": true
},
"options": {
"env": {
"SKIP_INSTALLS": "true"
},
"cwd": "${workspaceFolder}/extensions/vscode"
}
},
//
// Compile and bundle tests
{
"label": "vscode-extension:tests:build",
"dependsOn": [
// Build the extension
"vscode-extension:build",
// To detect compile errors - this type checks both the extension and the tests
"tsc:watch",
"vscode-extension:tests:esbuild"
]
},
{
"label": "vscode-extension:tests:esbuild",
"type": "npm",
"script": "build-test",
"path": "extensions/vscode",
"problemMatcher": [
{
"pattern": [
{
"regexp": "> (.*?):([0-9]+):([0-9]+): (warning|error): (.+)$",
"file": 1,
"line": 2,
"column": 3,
"severity": 4,
"message": 5
}
]
}
]
},
//
// Install or update all dependencies for all projects in the monrepo
{
"label": "install-all-dependencies",

View file

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

View file

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

View file

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

View file

@ -6,12 +6,36 @@ import {
} from "../filtering/streamTransforms/lineStream";
export interface AutocompleteLanguageInfo {
/**
* The display name of the language
*/
name: string;
/**
* Keywords that show up at the top-level of files. We often use these as stop words or soft breaks
*/
topLevelKeywords: string[];
/**
* The character that prefixes a single line comment
* We use this to format snippets from other files as large comment blocks
*/
singleLineComment?: string;
/**
* Semi-colon or other end of line indicator that may be used as a stop char
* or other parsing
*/
endOfLine: string[];
/**
* Strings that indicate we should filter out a line from completion
* Primarily currently used for .ipynb files
*/
lineFilters?: LineFilter[];
/**
* Similar to line filters, but characters. I think.
*/
charFilters?: CharacterFilter[];
/**
* Function that allows cusotmization of whether to use a multi-line completion on a per-language and completion basis
*/
useMultiline?: (args: { prefix: string; suffix: string }) => boolean;
}
@ -23,6 +47,14 @@ export const Typescript = {
endOfLine: [";"],
};
// JavaScript
export const JavaScript = {
name: "JavaScript",
topLevelKeywords: ["function", "class", "module", "export", "import"],
singleLineComment: "//",
endOfLine: [";"],
};
// Python
export const Python = {
name: "Python",
@ -336,7 +368,7 @@ export const Markdown: AutocompleteLanguageInfo = {
export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = {
ts: Typescript,
js: Typescript,
js: JavaScript,
tsx: Typescript,
json: Json,
jsx: Typescript,

View file

@ -70,4 +70,20 @@ export class ContextRetrievalService {
helper.treePath,
);
}
/**
* Initialize the import definitions cache for a file.
* This is normally done automatically when the active text editor changes,
* but needs to be called manually when using context fetching outside the normal flow.
*/
public async initializeForFile(filepath: string): Promise<void> {
try {
await (this.importDefinitionsService as any).cache.initKey(filepath);
} catch (e) {
console.warn(
`Failed to initialize import definitions cache for ${filepath}:`,
e,
);
}
}
}

View file

@ -209,3 +209,47 @@ export const getAllSnippets = async ({
recentlyOpenedFileSnippets,
};
};
export const getAllSnippetsWithoutRace = async ({
helper,
ide,
getDefinitionsFromLsp,
contextRetrievalService,
}: {
helper: HelperVars;
ide: IDE;
getDefinitionsFromLsp: GetLspDefinitionsFunction;
contextRetrievalService: ContextRetrievalService;
}): Promise<SnippetPayload> => {
const recentlyEditedRangeSnippets =
getSnippetsFromRecentlyEditedRanges(helper);
const [
rootPathSnippets,
importDefinitionSnippets,
ideSnippets,
diffSnippets,
clipboardSnippets,
recentlyOpenedFileSnippets,
] = await Promise.all([
contextRetrievalService.getRootPathSnippets(helper),
contextRetrievalService.getSnippetsFromImportDefinitions(helper),
IDE_SNIPPETS_ENABLED
? getIdeSnippets(helper, ide, getDefinitionsFromLsp)
: [],
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
getClipboardSnippets(ide),
getSnippetsFromRecentlyOpenedFiles(helper, ide),
]);
return {
rootPathSnippets,
importDefinitionSnippets,
ideSnippets,
recentlyEditedRangeSnippets,
diffSnippets,
clipboardSnippets,
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
recentlyOpenedFileSnippets,
};
};

View file

@ -0,0 +1,272 @@
/**
* CodeRenderer is a class that, when given a code string,
* highlights the code string using shiki and
* returns a svg representation of it.
* We could technically just call shiki's methods to do a
* one-liner syntax highlighting code, but
* a separate class for this is useful because
* we rarely ever need syntax highlighting outside of
* creating a render of it.
*/
import { JSDOM } from "jsdom";
import { BundledTheme, codeToHtml, getSingletonHighlighter } from "shiki";
import { escapeForSVG, kebabOfStr } from "../util/text";
interface CodeRendererOptions {
themesDir?: string;
theme?: string;
}
interface HTMLOptions {
theme?: string;
customCSS?: string;
containerClass?: string;
}
interface ConversionOptions extends HTMLOptions {
transparent?: boolean;
imageType: "svg";
}
interface Dimensions {
width: number;
height: number;
}
type DataUri = PngUri | SvgUri;
type PngUri = string;
type SvgUri = string;
export class CodeRenderer {
private static instance: CodeRenderer;
private currentTheme: string = "dark-plus";
private editorBackground: string = "#000000";
private editorForeground: string = "#FFFFFF";
private constructor() {}
static getInstance(): CodeRenderer {
if (!CodeRenderer.instance) {
CodeRenderer.instance = new CodeRenderer();
}
return CodeRenderer.instance;
}
public async setTheme(themeName: string): Promise<void> {
if (
this.themeExists(kebabOfStr(themeName)) ||
themeName === "Default Dark Modern"
) {
this.currentTheme =
themeName === "Default Dark Modern"
? "dark-plus"
: kebabOfStr(themeName);
const highlighter = await getSingletonHighlighter({
themes: [this.currentTheme],
});
const th = highlighter.getTheme(this.currentTheme);
this.editorBackground = th.bg;
this.editorForeground = th.fg;
} else {
this.currentTheme = "dark-plus";
}
}
async init(): Promise<void> {}
async close(): Promise<void> {}
themeExists(themeNameKebab: string): themeNameKebab is BundledTheme {
const themeArray: BundledTheme[] = [
"andromeeda",
"aurora-x",
"ayu-dark",
"catppuccin-frappe",
"catppuccin-latte",
"catppuccin-macchiato",
"catppuccin-mocha",
"dark-plus",
"dracula",
"dracula-soft",
"everforest-dark",
"everforest-light",
"github-dark",
"github-dark-default",
"github-dark-dimmed",
"github-dark-high-contrast",
"github-light",
"github-light-default",
"github-light-high-contrast",
"gruvbox-dark-hard",
"gruvbox-dark-medium",
"gruvbox-dark-soft",
"gruvbox-light-hard",
"gruvbox-light-medium",
"gruvbox-light-soft",
"houston",
"kanagawa-dragon",
"kanagawa-lotus",
"kanagawa-wave",
"laserwave",
"light-plus",
"material-theme",
"material-theme-darker",
"material-theme-lighter",
"material-theme-ocean",
"material-theme-palenight",
"min-dark",
"min-light",
"monokai",
"night-owl",
"nord",
"one-dark-pro",
"one-light",
"plastic",
"poimandres",
"red",
"rose-pine",
"rose-pine-dawn",
"rose-pine-moon",
"slack-dark",
"slack-ochin",
"snazzy-light",
"solarized-dark",
"solarized-light",
"synthwave-84",
"tokyo-night",
"vesper",
"vitesse-black",
"vitesse-dark",
"vitesse-light",
];
return themeArray.includes(themeNameKebab as BundledTheme);
}
async highlightCode(
code: string,
language: string = "javascript",
): Promise<string> {
return await codeToHtml(code, {
lang: language,
theme: this.currentTheme,
});
}
async convertToSVG(
code: string,
language: string = "javascript",
fontSize: number,
fontFamily: string,
dimensions: Dimensions,
lineHeight: number,
options: ConversionOptions,
): Promise<Buffer> {
const highlightedCodeHtml = await this.highlightCode(code, language);
const guts = this.convertShikiHtmlToSvgGut(
highlightedCodeHtml,
fontSize,
fontFamily,
lineHeight,
);
const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${dimensions.width}" height="${dimensions.height}">
<g>
<rect width="${dimensions.width}" height="${dimensions.height}" fill="${backgroundColor}" stroke="${this.editorForeground}" stroke-width="1" />
${guts}
</g>
</svg>`;
return Buffer.from(svg, "utf8");
}
convertShikiHtmlToSvgGut(
shikiHtml: string,
fontSize: number,
fontFamily: string,
lineHeight: number,
): string {
const dom = new JSDOM(shikiHtml);
const document = dom.window.document;
const lines = Array.from(document.querySelectorAll(".line"));
const svgLines = lines.map((line, index) => {
const spans = Array.from(line.childNodes)
.map((node) => {
if (node.nodeType === 3) {
return `<tspan xml:space="preserve">${escapeForSVG(node.textContent ?? "")}</tspan>`;
}
const el = node as HTMLElement;
const style = el.getAttribute("style") || "";
const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/);
const fill = colorMatch ? ` fill="${colorMatch[1]}"` : "";
const content = el.textContent || "";
return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
})
.join("");
const y = (index + 1) * lineHeight;
return `<text x="0" y="${y}" font-family="${fontFamily}" font-size="${fontSize.toString()}" xml:space="preserve">${spans}</text>`;
});
return `
${svgLines.join("\n")}
`.trim();
}
getBackgroundColor(shikiHtml: string): string {
const dom = new JSDOM(shikiHtml);
const document = dom.window.document;
const preElement = document.querySelector("pre");
let backgroundColor = "#333333"; // Default white background
if (preElement) {
const style = preElement.getAttribute("style") || "";
const bgColorMatch = style.match(/background-color:\s*(#[0-9a-fA-F]{6})/);
if (bgColorMatch) {
backgroundColor = bgColorMatch[1];
}
}
return backgroundColor;
}
async getDataUri(
code: string,
language: string = "javascript",
fontSize: number,
fontFamily: string,
dimensions: Dimensions,
lineHeight: number,
options: ConversionOptions,
): Promise<DataUri> {
switch (options.imageType) {
// case "png":
// const pngBuffer = await this.convertToPNG(
// code,
// language,
// fontSize,
// dimensions,
// lineHeight,
// options,
// );
// return `data:image/png;base64,${pngBuffer.data.toString("base64")}`;
case "svg":
const svgBuffer = await this.convertToSVG(
code,
language,
fontSize,
fontFamily,
dimensions,
lineHeight,
options,
);
return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
}
}
}

View file

@ -1,88 +0,0 @@
import { CustomCommand, SlashCommand, SlashCommandDescription } from "../";
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
import { replaceSlashCommandWithPromptInChatHistory } from "../promptFiles/v1/updateChatHistory";
import { renderPromptFileV2 } from "../promptFiles/v2/renderPromptFile";
import { renderChatMessage } from "../util/messageContent";
import SlashCommands from "./slash";
export function slashFromCustomCommand(
customCommand: CustomCommand,
): SlashCommand {
const commandName = customCommand.name.startsWith("/")
? customCommand.name.substring(1)
: customCommand.name;
return {
name: commandName,
description: customCommand.description ?? "",
prompt: customCommand.prompt,
run: async function* ({
input,
llm,
history,
ide,
completionOptions,
config,
selectedCode,
fetch,
abortController,
}) {
// Render prompt template
let renderedPrompt: string;
if (customCommand.prompt.includes("{{{ input }}}")) {
renderedPrompt = await renderTemplatedString(
customCommand.prompt,
ide.readFile.bind(ide),
{ input },
);
} else {
const renderedPromptFile = await renderPromptFileV2(
customCommand.prompt,
{
config,
llm,
ide,
selectedCode,
fetch,
fullInput: input,
embeddingsProvider: config.modelsByRole.embed[0],
reranker: config.modelsByRole.rerank[0],
},
);
renderedPrompt = renderedPromptFile[1];
}
// Replaces slash command messages with the rendered prompt
// which INCLUDES the input
const messages = replaceSlashCommandWithPromptInChatHistory(
history,
commandName,
renderedPrompt,
undefined,
);
for await (const chunk of llm.streamChat(
messages,
abortController.signal,
completionOptions,
)) {
yield renderChatMessage(chunk);
}
},
};
}
export function slashCommandFromDescription(
desc: SlashCommandDescription,
): SlashCommand | undefined {
const cmd = SlashCommands.find((cmd) => cmd.name === desc.name);
if (!cmd) {
return undefined;
}
return {
...cmd,
params: desc.params,
description: desc.description ?? cmd.description,
};
}

View file

@ -1,6 +1,6 @@
import { streamLines } from "../../diff/util.js";
import { SlashCommand } from "../../index.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
import { streamLines } from "../../../diff/util.js";
import { SlashCommand } from "../../../index.js";
import { removeQuotesAndEscapes } from "../../../util/index.js";
function commandIsPotentiallyDangerous(command: string) {
return (

View file

@ -1,5 +1,5 @@
import { SlashCommand } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { SlashCommand } from "../../../index.js";
import { renderChatMessage } from "../../../util/messageContent.js";
const CommitMessageCommand: SlashCommand = {
name: "commit",

View file

@ -1,6 +1,6 @@
import { ChatMessage, SlashCommand } from "../../index.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { ChatMessage, SlashCommand } from "../../../index.js";
import { removeQuotesAndEscapes } from "../../../util/index.js";
import { renderChatMessage } from "../../../util/messageContent.js";
const PROMPT = (
input: string,

View file

@ -1,6 +1,6 @@
import { streamResponse } from "@continuedev/fetch";
import { SlashCommand } from "../../index.js";
import { removeQuotesAndEscapes } from "../../util/index.js";
import { SlashCommand } from "../../../index.js";
import { removeQuotesAndEscapes } from "../../../util/index.js";
const HttpSlashCommand: SlashCommand = {
name: "http",

View file

@ -0,0 +1,37 @@
import {
SlashCommand,
SlashCommandDescription,
SlashCommandWithSource,
} from "../../..";
import GenerateTerminalCommand from "./cmd";
import CommitMessageCommand from "./commit";
import DraftIssueCommand from "./draftIssue";
import HttpSlashCommand from "./http";
import OnboardSlashCommand from "./onboard";
import ReviewMessageCommand from "./review";
import ShareSlashCommand from "./share";
const LegacyBuiltInSlashCommands: SlashCommand[] = [
DraftIssueCommand,
ShareSlashCommand,
GenerateTerminalCommand,
HttpSlashCommand,
CommitMessageCommand,
ReviewMessageCommand,
OnboardSlashCommand,
];
export function getLegacyBuiltInSlashCommandFromDescription(
desc: SlashCommandDescription,
): SlashCommandWithSource | undefined {
const cmd = LegacyBuiltInSlashCommands.find((cmd) => cmd.name === desc.name);
if (!cmd) {
return undefined;
}
return {
...cmd,
params: desc.params,
description: desc.description ?? cmd.description,
source: "built-in-legacy",
};
}

View file

@ -1,17 +1,17 @@
import ignore from "ignore";
import type { FileType, IDE, SlashCommand } from "../..";
import type { FileType, IDE, SlashCommand } from "../../..";
import {
DEFAULT_IGNORE,
getGlobalContinueIgArray,
gitIgArrayFromFile,
} from "../../indexing/ignore";
import { renderChatMessage } from "../../util/messageContent";
} from "../../../indexing/ignore";
import { renderChatMessage } from "../../../util/messageContent";
import {
findUriInDirs,
getUriPathBasename,
joinPathsToUri,
} from "../../util/uri";
} from "../../../util/uri";
const LANGUAGE_DEP_MGMT_FILENAMES = [
"package.json", // JavaScript (Node.js)

View file

@ -1,5 +1,5 @@
import { ChatMessage, SlashCommand } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { ChatMessage, SlashCommand } from "../../../index.js";
import { renderChatMessage } from "../../../util/messageContent.js";
const prompt = `
Review the following code, focusing on Readability, Maintainability, Code Smells, Speed, and Memory Performance. Provide feedback with these guidelines:

View file

@ -3,10 +3,10 @@ import { homedir } from "node:os";
import { fileURLToPath, pathToFileURL } from "node:url";
import path from "path";
import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js";
import { SlashCommand } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
import { getContinueGlobalPath } from "../../util/paths.js";
import { languageForFilepath } from "../../../autocomplete/constants/AutocompleteLanguageInfo.js";
import { SlashCommand } from "../../../index.js";
import { renderChatMessage } from "../../../util/messageContent.js";
import { getContinueGlobalPath } from "../../../util/paths.js";
// If useful elsewhere, helper funcs should move to core/util/index.ts or similar
function getOffsetDatetime(date: Date): Date {

View file

@ -0,0 +1,15 @@
import { CustomCommand, SlashCommandWithSource } from "../..";
export function convertCustomCommandToSlashCommand(
customCommand: CustomCommand,
): SlashCommandWithSource {
const commandName = customCommand.name.startsWith("/")
? customCommand.name.substring(1)
: customCommand.name;
return {
name: commandName,
description: customCommand.description ?? "",
prompt: customCommand.prompt,
source: "json-custom-command",
};
}

View file

@ -1,17 +0,0 @@
import GenerateTerminalCommand from "./cmd";
import CommitMessageCommand from "./commit";
import DraftIssueCommand from "./draftIssue";
import HttpSlashCommand from "./http";
import OnboardSlashCommand from "./onboard";
import ReviewMessageCommand from "./review";
import ShareSlashCommand from "./share";
export default [
DraftIssueCommand,
ShareSlashCommand,
GenerateTerminalCommand,
HttpSlashCommand,
CommitMessageCommand,
ReviewMessageCommand,
OnboardSlashCommand,
];

View file

@ -1,70 +0,0 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { PromptMessage } from "@modelcontextprotocol/sdk/types.js";
import { ChatMessage, SlashCommand } from "../../index.js";
import { renderChatMessage } from "../../util/messageContent.js";
export function constructMcpSlashCommand(
client: Client,
name: string,
description?: string,
args?: string[],
): SlashCommand {
return {
name,
description: description ?? "MCP Prompt",
params: {},
run: async function* (context) {
const argsObject: { [key: string]: string } = {};
const userInput = context.input.split(" ").slice(1).join(" ");
if (args) {
args.forEach((arg, i) => {
argsObject[arg] = ""; // userInput
});
}
const result = await client.getPrompt({ name, arguments: argsObject });
const mcpMessages: PromptMessage[] = result.messages;
const messages: ChatMessage[] = mcpMessages.map((msg) => {
if (msg.content.type !== "text") {
throw new Error(
"Continue currently only supports text prompts through MCP",
);
}
return {
content: msg.content.text,
role: msg.role,
};
});
if (messages.length === 0) {
yield "The MCP prompt returned no messages";
return;
}
if (userInput) {
const lastMessage = messages.at(-1);
if (!lastMessage || lastMessage.role !== "user") {
messages.push({
role: "user",
content: userInput,
});
} else {
let newContent = renderChatMessage(lastMessage);
if (newContent) {
newContent += "\n\n";
}
newContent += userInput;
lastMessage.content = newContent;
}
}
for await (const chunk of context.llm.streamChat(
messages,
context.abortController.signal,
context.completionOptions,
)) {
yield renderChatMessage(chunk);
}
},
};
}

View file

@ -0,0 +1,34 @@
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { SlashCommandWithSource } from "../../index.js";
export function constructMcpSlashCommand(
client: Client,
name: string,
description?: string,
args?: string[],
): SlashCommandWithSource {
return {
name,
description: description ?? "MCP Prompt",
source: "mcp-prompt",
params: {},
};
}
export function stringifyMcpPrompt(
prompt: Awaited<ReturnType<typeof Client.prototype.getPrompt>>,
): string {
const { messages } = prompt;
let stringified = "";
for (const message of messages) {
if (message.content.type === "text") {
stringified += `<${message.content.role}/>\n${message.content.text}\n<${message.content.role}/>`;
} else {
console.warn(
`MCP Prompt conversion warning: ${message.content.type} content is not yet supported, message skipped`,
);
}
}
return stringified;
}

View file

@ -0,0 +1,13 @@
import { Prompt } from "@continuedev/config-yaml";
import { SlashCommandWithSource } from "../..";
export function convertPromptBlockToSlashCommand(
prompt: Prompt,
): SlashCommandWithSource {
return {
name: prompt.name,
description: prompt.description ?? "",
prompt: prompt.prompt,
source: "yaml-prompt-block",
};
}

View file

@ -0,0 +1,21 @@
import { SlashCommandWithSource } from "../..";
import { parsePromptFile } from "../../promptFiles/parsePromptFile";
export function slashCommandFromPromptFile(
path: string,
content: string,
): SlashCommandWithSource | null {
const { name, description, systemMessage, prompt, version } = parsePromptFile(
path,
content,
);
return {
name,
description,
prompt,
source: version === 1 ? "prompt-file-v1" : "prompt-file-v2",
promptFile: path,
overrideSystemMessage: systemMessage,
};
}

View file

@ -16,7 +16,7 @@ export function rifWithContentsToContextItem(
return {
content: rif.contents,
name: `${basename} ${rangeStr}`,
description: `${relativePathOrBasename} ${rangeStr}`, // This is passed to the LLM - do not pass full URI
description: `${relativePathOrBasename} ${rangeStr}`,
id: {
providerTitle: "code",
itemId: uuidv4(),

View file

@ -1,5 +1,6 @@
import { ctxItemToRifWithContents } from "./util";
import { describe, expect, it } from "vitest";
import { ContextItemWithId, RangeInFileWithContents } from "../index";
import { ctxItemToRifWithContents } from "./util";
describe("ctxItemToRifWithContents", () => {
it("should parse start and end lines from the item name when format is valid", () => {

View file

@ -1,6 +1,7 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, test } from "vitest";
import { testConfigHandler } from "../test/fixtures";
import { TEST_DIR } from "../test/testDir";
import { getConfigTsPath } from "../util/paths";
@ -24,7 +25,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
);
});
test.skip("should add a system message from config.ts", async () => {
test("should add a system message from config.ts", async () => {
const configTs = `export function modifyConfig(config: Config): Config {
config.systemMessage = "SYSTEM";
return config;
@ -39,7 +40,7 @@ describe.skip("Test the ConfigHandler and E2E config loading", () => {
expect(config.systemMessage).toBe("SYSTEM");
});
test.skip("should acknowledge override from .continuerc.json", async () => {
test("should acknowledge override from .continuerc.json", async () => {
fs.writeFileSync(
path.join(TEST_DIR, ".continuerc.json"),
JSON.stringify({ systemMessage: "SYSTEM2" }),

View file

@ -30,14 +30,12 @@ import {
ModelDescription,
RerankerDescription,
SerializedContinueConfig,
SlashCommand,
SlashCommandWithSource,
} from "..";
import {
slashCommandFromDescription,
slashFromCustomCommand,
} from "../commands/index";
import { getLegacyBuiltInSlashCommandFromDescription } from "../commands/slash/built-in-legacy";
import { convertCustomCommandToSlashCommand } from "../commands/slash/customSlashCommand";
import { slashCommandFromPromptFile } from "../commands/slash/promptFileSlashCommand";
import { MCPManagerSingleton } from "../context/mcp/MCPManagerSingleton";
import CodebaseContextProvider from "../context/providers/CodebaseContextProvider";
import ContinueProxyContextProvider from "../context/providers/ContinueProxyContextProvider";
import CustomContextProviderClass from "../context/providers/CustomContextProvider";
import FileContextProvider from "../context/providers/FileContextProvider";
@ -48,8 +46,7 @@ import { LLMClasses, llmFromDescription } from "../llm/llms";
import CustomLLMClass from "../llm/llms/CustomLLM";
import { LLMReranker } from "../llm/llms/llm";
import TransformersJsEmbeddingsProvider from "../llm/llms/TransformersJsEmbeddingsProvider";
import { slashCommandFromPromptFileV1 } from "../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../promptFiles/v2/getPromptFiles";
import { getAllPromptFiles } from "../promptFiles/getPromptFiles";
import { copyOf } from "../util";
import { GlobalContext } from "../util/GlobalContext";
import mergeJson from "../util/merge";
@ -66,6 +63,7 @@ import {
import { localPathToUri } from "../util/pathToUri";
import { baseToolDefinitions } from "../tools";
import { resolveRelativePathInDir } from "../util/ideUtils";
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
import {
getModelByRole,
@ -174,15 +172,15 @@ async function serializedToIntermediateConfig(
ide: IDE,
): Promise<Config> {
// DEPRECATED - load custom slash commands
const slashCommands: SlashCommand[] = [];
const slashCommands: SlashCommandWithSource[] = [];
for (const command of initial.slashCommands || []) {
const newCommand = slashCommandFromDescription(command);
const newCommand = getLegacyBuiltInSlashCommandFromDescription(command);
if (newCommand) {
slashCommands.push(newCommand);
}
}
for (const command of initial.customCommands || []) {
slashCommands.push(slashFromCustomCommand(command));
slashCommands.push(convertCustomCommandToSlashCommand(command));
}
// DEPRECATED - load slash commands from v1 prompt files
@ -194,7 +192,7 @@ async function serializedToIntermediateConfig(
);
for (const file of promptFiles) {
const slashCommand = slashCommandFromPromptFileV1(file.path, file.content);
const slashCommand = slashCommandFromPromptFile(file.path, file.content);
if (slashCommand) {
slashCommands.push(slashCommand);
}
@ -254,7 +252,10 @@ async function intermediateToFinalConfig({
loadPromptFiles?: boolean;
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
const errors: ConfigValidationError[] = [];
const workspaceDirs = await ide.getWorkspaceDirs();
const getUriFromPath = (path: string) => {
return resolveRelativePathInDir(path, ide, workspaceDirs);
};
// Auto-detect models
let models: BaseLLM[] = [];
await Promise.all(
@ -263,6 +264,7 @@ async function intermediateToFinalConfig({
const llm = await llmFromDescription(
desc,
ide.readFile.bind(ide),
getUriFromPath,
uniqueId,
ideSettings,
llmLogger,
@ -284,6 +286,7 @@ async function intermediateToFinalConfig({
title: modelName,
},
ide.readFile.bind(ide),
getUriFromPath,
uniqueId,
ideSettings,
llmLogger,
@ -360,6 +363,7 @@ async function intermediateToFinalConfig({
const llm = await llmFromDescription(
desc,
ide.readFile.bind(ide),
getUriFromPath,
uniqueId,
ideSettings,
llmLogger,
@ -393,13 +397,7 @@ async function intermediateToFinalConfig({
| undefined
)?.params || {};
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
// Add codebase provider if indexing is enabled
...(!config.disableIndexing
? [new CodebaseContextProvider(codebaseContextParams)]
: []),
];
const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
({ description: { title } }) => title,
@ -529,7 +527,7 @@ async function intermediateToFinalConfig({
contextProviders,
tools: [...baseToolDefinitions],
mcpServerStatuses: [],
slashCommands: config.slashCommands ?? [],
slashCommands: [],
modelsByRole: {
chat: models,
edit: models,
@ -551,6 +549,17 @@ async function intermediateToFinalConfig({
rules: [],
};
for (const cmd of config.slashCommands ?? []) {
if ("source" in cmd) {
continueConfig.slashCommands.push(cmd);
} else {
continueConfig.slashCommands.push({
...cmd,
source: "config-ts-slash-command",
});
}
}
if (config.systemMessage) {
continueConfig.rules.unshift({
rule: config.systemMessage,
@ -651,9 +660,10 @@ async function finalToBrowserConfig(
return {
allowAnonymousTelemetry: final.allowAnonymousTelemetry,
completionOptions: final.completionOptions,
slashCommands: final.slashCommands?.map(
({ run, ...slashCommandDescription }) => slashCommandDescription,
),
slashCommands: final.slashCommands?.map(({ run, ...rest }) => ({
...rest,
isLegacy: !!run,
})),
contextProviders: final.contextProviders?.map((c) => c.description),
disableIndexing: final.disableIndexing,
disableSessionTitles: final.disableSessionTitles,
@ -975,7 +985,6 @@ async function loadContinueConfigFromJson(
export {
finalToBrowserConfig,
intermediateToFinalConfig,
loadContinueConfigFromJson,
type BrowserSerializedContinueConfig,
};

View file

@ -1,3 +1,4 @@
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { walkDirCache } from "../indexing/walkDir";
import { testIde } from "../test/fixtures";
import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir";

View file

@ -16,9 +16,9 @@ import {
ILLMLogger,
RuleWithSource,
SerializedContinueConfig,
SlashCommandDescWithSource,
Tool,
} from "../../";
import { constructMcpSlashCommand } from "../../commands/slash/mcp";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import MCPContextProvider from "../../context/providers/MCPContextProvider";
import RulesContextProvider from "../../context/providers/RulesContextProvider";
@ -190,14 +190,15 @@ export default async function doLoadConfig(options: {
}));
newConfig.tools.push(...serverTools);
const serverSlashCommands = server.prompts.map((prompt) =>
constructMcpSlashCommand(
server.client,
prompt.name,
prompt.description,
prompt.arguments?.map((a: any) => a.name),
),
);
const serverSlashCommands: SlashCommandDescWithSource[] =
server.prompts.map((prompt) => ({
name: prompt.name,
description: prompt.description ?? "MCP Prompt",
source: "mcp-prompt",
isLegacy: false,
mcpServerName: server.name, // Used in client to retrieve prompt
mcpArgs: prompt.arguments,
}));
newConfig.slashCommands.push(...serverSlashCommands);
const submenuItems = server.resources
@ -229,6 +230,8 @@ export default async function doLoadConfig(options: {
newConfig.tools.push(
...getConfigDependentToolDefinitions({
rules: newConfig.rules,
enableExperimentalTools:
newConfig.experimental?.enableExperimentalTools ?? false,
}),
);

View file

@ -19,6 +19,9 @@ export const sharedConfigSchema = z
readResponseTTS: z.boolean(),
promptPath: z.string(),
useCurrentFileAsContext: z.boolean(),
logEditingData: z.boolean(),
optInNextEditFeature: z.boolean(),
enableExperimentalTools: z.boolean(),
// `ui` in `ContinueConfig`
showSessionTabs: z.boolean(),
@ -157,6 +160,12 @@ export function modifyAnyConfigWithSharedConfig<
configCopy.experimental = {
...configCopy.experimental,
};
if (sharedConfig.enableExperimentalTools !== undefined) {
configCopy.experimental.enableExperimentalTools =
sharedConfig.enableExperimentalTools;
}
if (sharedConfig.promptPath !== undefined) {
configCopy.experimental.promptPath = sharedConfig.promptPath;
}
@ -171,6 +180,13 @@ export function modifyAnyConfigWithSharedConfig<
configCopy.experimental.useCurrentFileAsContext =
sharedConfig.useCurrentFileAsContext;
}
if (sharedConfig.logEditingData !== undefined) {
configCopy.experimental.logEditingData = sharedConfig.logEditingData;
}
if (sharedConfig.optInNextEditFeature !== undefined) {
configCopy.experimental.optInNextEditFeature =
sharedConfig.optInNextEditFeature;
}
return configCopy;
}

View file

@ -1,344 +0,0 @@
import { jest } from "@jest/globals";
import { BrowserSerializedContinueConfig } from "..";
// Create the mock before importing anything else
const mockDecodeSecretLocation = jest.fn();
// Mock the module
jest.unstable_mockModule("@continuedev/config-yaml", () => ({
SecretType: {
User: "user",
Organization: "organization",
FreeTrial: "free_trial",
},
decodeSecretLocation: mockDecodeSecretLocation,
}));
// Import after mocking
const { usesFreeTrialApiKey } = await import("./usesFreeTrialApiKey");
const { SecretType } = await import("@continuedev/config-yaml");
beforeEach(() => {
mockDecodeSecretLocation.mockReset();
});
test("usesFreeTrialApiKey should return false when config is null", () => {
const result = usesFreeTrialApiKey(null);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when config is undefined", () => {
const result = usesFreeTrialApiKey(undefined as any);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
underlyingProviderName: "test",
},
{
title: "Model 2",
provider: "test",
model: "test-model-2",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Model 2",
provider: "test",
model: "test-model-2",
apiKeyLocation: "organization:testorg/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.Organization,
orgSlug: "testorg",
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
{
title: "Free Trial Model",
provider: "test",
model: "free-trial-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Free Trial Edit Model",
provider: "test",
model: "free-trial-edit-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
});
test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
const consoleSpy = jest.spyOn(console, "error").mockImplementation(() => {});
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "invalid-secret-location",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation.mockImplementation(() => {
throw new Error("Invalid secret location format");
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(consoleSpy).toHaveBeenCalledWith(
"Error checking for free trial API key:",
expect.any(Error),
);
consoleSpy.mockRestore();
});
test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
});

View file

@ -0,0 +1,348 @@
import { beforeEach, describe, expect, test, vi } from "vitest";
import { BrowserSerializedContinueConfig } from "..";
// Create the mock before importing anything else
const mockDecodeSecretLocation = vi.fn();
// Mock the module
vi.mock("@continuedev/config-yaml", () => ({
SecretType: {
User: "user",
Organization: "organization",
FreeTrial: "free_trial",
},
decodeSecretLocation: mockDecodeSecretLocation,
}));
describe("usesFreeTrialApiKey", () => {
let usesFreeTrialApiKey: typeof import("./usesFreeTrialApiKey").usesFreeTrialApiKey;
let SecretType: typeof import("@continuedev/config-yaml").SecretType;
beforeEach(async () => {
mockDecodeSecretLocation.mockReset();
usesFreeTrialApiKey = (await import("./usesFreeTrialApiKey"))
.usesFreeTrialApiKey;
SecretType = (await import("@continuedev/config-yaml")).SecretType;
});
test("usesFreeTrialApiKey should return false when config is null", () => {
const result = usesFreeTrialApiKey(null);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when config is undefined", () => {
const result = usesFreeTrialApiKey(undefined as any);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when no models have apiKeyLocation", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
underlyingProviderName: "test",
},
{
title: "Model 2",
provider: "test",
model: "test-model-2",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
});
test("usesFreeTrialApiKey should return false when models have apiKeyLocation but none are free trial", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Model 2",
provider: "test",
model: "test-model-2",
apiKeyLocation: "organization:testorg/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.Organization,
orgSlug: "testorg",
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when at least one model uses free trial API key", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
{
title: "Free Trial Model",
provider: "test",
model: "free-trial-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
expect(mockDecodeSecretLocation).toHaveBeenCalledTimes(2);
});
test("usesFreeTrialApiKey should return true when free trial model is in a different role", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "user:testuser/api-key",
underlyingProviderName: "test",
},
],
edit: [
{
title: "Free Trial Edit Model",
provider: "test",
model: "free-trial-edit-model",
apiKeyLocation: "free_trial:owner/package/api-key",
underlyingProviderName: "test",
},
],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation
.mockReturnValueOnce({
secretType: SecretType.User,
userSlug: "testuser",
secretName: "api-key",
})
.mockReturnValueOnce({
secretType: SecretType.FreeTrial,
blockSlug: { ownerSlug: "owner", packageSlug: "package" },
secretName: "api-key",
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(true);
});
test("usesFreeTrialApiKey should return false and log error when decodeSecretLocation throws", () => {
const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [
{
title: "Model 1",
provider: "test",
model: "test-model",
apiKeyLocation: "invalid-secret-location",
underlyingProviderName: "test",
},
],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
mockDecodeSecretLocation.mockImplementation(() => {
throw new Error("Invalid secret location format");
});
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(consoleSpy).toHaveBeenCalledWith(
"Error checking for free trial API key:",
expect.any(Error),
);
consoleSpy.mockRestore();
});
test("usesFreeTrialApiKey should handle empty modelsByRole object", () => {
const config: BrowserSerializedContinueConfig = {
modelsByRole: {
chat: [],
edit: [],
apply: [],
summarize: [],
autocomplete: [],
rerank: [],
embed: [],
},
selectedModelByRole: {
chat: null,
edit: null,
apply: null,
summarize: null,
autocomplete: null,
rerank: null,
embed: null,
},
contextProviders: [],
slashCommands: [],
tools: [],
mcpServerStatuses: [],
usePlatform: false,
rules: [],
};
const result = usesFreeTrialApiKey(config);
expect(result).toBe(false);
expect(mockDecodeSecretLocation).not.toHaveBeenCalled();
});
});

View file

@ -1,3 +1,4 @@
import { describe, expect, it } from "vitest";
import { PromptTemplate } from "..";
import { serializePromptTemplates } from "./util";

View file

@ -1,5 +1,5 @@
import { BlockType, RULE_FILE_EXTENSION } from "@continuedev/config-yaml";
import { describe, expect, test } from "@jest/globals";
import { describe, expect, test } from "vitest";
import { findAvailableFilename, getFileContent } from "./workspaceBlocks";
describe("getFileContent", () => {

View file

@ -25,21 +25,20 @@ import {
ILLMLogger,
RuleWithSource,
} from "../..";
import { slashFromCustomCommand } from "../../commands";
import { MCPManagerSingleton } from "../../context/mcp/MCPManagerSingleton";
import CodebaseContextProvider from "../../context/providers/CodebaseContextProvider";
import DocsContextProvider from "../../context/providers/DocsContextProvider";
import FileContextProvider from "../../context/providers/FileContextProvider";
import { contextProviderClassFromName } from "../../context/providers/index";
import { ControlPlaneClient } from "../../control-plane/client";
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
import { getAllPromptFiles } from "../../promptFiles/getPromptFiles";
import { GlobalContext } from "../../util/GlobalContext";
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
import { convertPromptBlockToSlashCommand } from "../../commands/slash/promptBlockSlashCommand";
import { slashCommandFromPromptFile } from "../../commands/slash/promptFileSlashCommand";
import { getControlPlaneEnvSync } from "../../control-plane/env";
import { baseToolDefinitions } from "../../tools";
import { getToolsForIde } from "../../tools";
import { getCleanUriPath } from "../../util/uri";
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
import { LocalPlatformClient } from "./LocalPlatformClient";
@ -187,7 +186,7 @@ async function configYamlToContinueConfig(options: {
const continueConfig: ContinueConfig = {
slashCommands: [],
tools: [...baseToolDefinitions],
tools: await getToolsForIde(ide),
mcpServerStatuses: [],
contextProviders: [],
modelsByRole: {
@ -263,7 +262,7 @@ async function configYamlToContinueConfig(options: {
promptFiles.forEach((file) => {
try {
const slashCommand = slashCommandFromPromptFileV1(
const slashCommand = slashCommandFromPromptFile(
file.path,
file.content,
);
@ -286,7 +285,7 @@ async function configYamlToContinueConfig(options: {
config.prompts?.forEach((prompt) => {
try {
const slashCommand = slashFromCustomCommand(prompt);
const slashCommand = convertPromptBlockToSlashCommand(prompt);
continueConfig.slashCommands?.push(slashCommand);
} catch (e) {
localErrors.push({
@ -385,13 +384,7 @@ async function configYamlToContinueConfig(options: {
}
// Context providers
const codebaseContextParams: IContextProvider[] =
(config.context || []).find((cp) => cp.provider === "codebase")?.params ||
{};
const DEFAULT_CONTEXT_PROVIDERS = [
new FileContextProvider({}),
new CodebaseContextProvider(codebaseContextParams),
];
const DEFAULT_CONTEXT_PROVIDERS = [new FileContextProvider({})];
const DEFAULT_CONTEXT_PROVIDERS_TITLES = DEFAULT_CONTEXT_PROVIDERS.map(
({ description: { title } }) => title,

View file

@ -1,10 +1,10 @@
import { jest } from "@jest/globals";
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { beforeEach, describe, expect, it, vi } from "vitest";
import MCPConnection from "./MCPConnection";
describe("MCPConnection", () => {
beforeEach(() => {
jest.restoreAllMocks();
vi.restoreAllMocks();
});
describe("constructor", () => {
@ -131,10 +131,10 @@ describe("MCPConnection", () => {
it("should connect successfully", async () => {
const conn = new MCPConnection(options);
const mockConnect = jest
const mockConnect = vi
.spyOn(Client.prototype, "connect")
.mockResolvedValue(undefined);
const mockGetServerCapabilities = jest
const mockGetServerCapabilities = vi
.spyOn(Client.prototype, "getServerCapabilities")
.mockReturnValue({
resources: {},
@ -142,12 +142,12 @@ describe("MCPConnection", () => {
prompts: {},
});
const mockListResources = jest
const mockListResources = vi
.spyOn(Client.prototype, "listResources")
.mockResolvedValue({
resources: [{ name: "test-resource", uri: "test-uri" }],
});
const mockListTools = jest
const mockListTools = vi
.spyOn(Client.prototype, "listTools")
.mockResolvedValue({
tools: [
@ -159,7 +159,7 @@ describe("MCPConnection", () => {
},
],
});
const mockListPrompts = jest
const mockListPrompts = vi
.spyOn(Client.prototype, "listPrompts")
.mockResolvedValue({ prompts: [{ name: "test-prompt" }] });
@ -175,7 +175,7 @@ describe("MCPConnection", () => {
it("should handle custom connection timeout", async () => {
const conn = new MCPConnection({ ...options, timeout: 1500 });
const mockConnect = jest
const mockConnect = vi
.spyOn(Client.prototype, "connect")
.mockImplementation(
() => new Promise((resolve) => setTimeout(resolve, 1000)),
@ -190,7 +190,7 @@ describe("MCPConnection", () => {
it("should handle connection timeout", async () => {
const conn = new MCPConnection({ ...options, timeout: 1 });
const mockConnect = jest
const mockConnect = vi
.spyOn(Client.prototype, "connect")
.mockImplementation(
() => new Promise((resolve) => setTimeout(resolve, 100)),
@ -208,7 +208,7 @@ describe("MCPConnection", () => {
const conn = new MCPConnection(options);
conn.status = "connected";
const mockConnect = jest.spyOn(Client.prototype, "connect");
const mockConnect = vi.spyOn(Client.prototype, "connect");
const abortController = new AbortController();
await conn.connectClient(false, abortController.signal);
@ -219,7 +219,7 @@ describe("MCPConnection", () => {
it("should handle transport errors", async () => {
const conn = new MCPConnection(options);
const mockConnect = jest
const mockConnect = vi
.spyOn(Client.prototype, "connect")
.mockRejectedValue(new Error("spawn test-cmd ENOENT"));
@ -233,7 +233,7 @@ describe("MCPConnection", () => {
it.skip("should include stderr output in error message when stdio command fails", async () => {
// Clear any existing mocks to ensure we get real behavior
jest.restoreAllMocks();
vi.restoreAllMocks();
// Use a command that will definitely fail and produce stderr output
const failingOptions = {

View file

@ -161,4 +161,21 @@ export class MCPManagerSingleton {
client: connection.client,
}));
}
async getPrompt(
serverName: string,
promptName: string,
args: Record<string, string> = {},
) {
const connection = this.connections.get(serverName);
if (!connection) {
throw new Error(
`Error getting prompt: MCP Connection ${serverName} not found`,
);
}
return await connection.client.getPrompt({
name: promptName,
arguments: args,
});
}
}

View file

@ -1,3 +1,4 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { MCPOptions } from "../..";
import MCPConnection from "./MCPConnection";
import { MCPManagerSingleton } from "./MCPManagerSingleton";
@ -18,8 +19,8 @@ class TestMCPConnection extends MCPConnection {
} as any;
this.abortController = new AbortController();
this.connectClient = jest.fn().mockResolvedValue(undefined);
this.getStatus = jest
this.connectClient = vi.fn().mockResolvedValue(undefined);
this.getStatus = vi
.fn()
.mockReturnValue({ status: "connected", errors: [] });
}
@ -54,13 +55,12 @@ describe("MCPManagerSingleton", () => {
id: string,
options: MCPOptions,
): MCPConnection {
if (!this.connections.has(id)) {
const connection = new TestMCPConnection(options);
this.connections.set(id, connection);
return connection;
} else {
if (this.connections.has(id)) {
return this.connections.get(id)!;
}
const connection = new TestMCPConnection(options);
this.connections.set(id, connection);
return connection;
};
});
@ -103,7 +103,7 @@ describe("MCPManagerSingleton", () => {
"test-id",
testOptions,
) as TestMCPConnection;
const closeSpy = jest.spyOn(connection.client, "close");
const closeSpy = vi.spyOn(connection.client, "close");
await manager.removeConnection("test-id");
@ -133,8 +133,8 @@ describe("MCPManagerSingleton", () => {
"test-id",
testOptions,
) as TestMCPConnection;
const abortSpy = jest.spyOn(connection.abortController, "abort");
const closeSpy = jest.spyOn(connection.client, "close");
const abortSpy = vi.spyOn(connection.abortController, "abort");
const closeSpy = vi.spyOn(connection.client, "close");
// Remove it by setting empty server list
manager.setConnections([], false);
@ -192,7 +192,7 @@ describe("MCPManagerSingleton", () => {
});
it("should call onConnectionsRefreshed if defined", async () => {
const mockCallback = jest.fn();
const mockCallback = vi.fn();
manager.onConnectionsRefreshed = mockCallback;
manager.createConnection("test-id", testOptions);
@ -209,7 +209,7 @@ describe("MCPManagerSingleton", () => {
testOptions,
) as TestMCPConnection;
const mockStatus = { status: "connected", errors: [] };
connection.getStatus = jest.fn().mockReturnValue(mockStatus);
connection.getStatus = vi.fn().mockReturnValue(mockStatus);
const statuses = manager.getStatuses();
expect(statuses).toHaveLength(1);

View file

@ -56,7 +56,9 @@ class MCPContextProvider extends BaseContextProvider {
private insertInputToUriTemplate(uri: string, query: string): string {
const TEMPLATE_VAR = "query";
if (uri.includes(`{${TEMPLATE_VAR}}`)) {
return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(query));
// Sending an empty string will result in an error, so we instead send "null"
const queryOrNull = query.trim() === "" ? "null" : query;
return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(queryOrNull));
}
return uri;
}

View file

@ -21,7 +21,9 @@ class TerminalContextProvider extends BaseContextProvider {
return [
{
description: "The contents of the terminal",
content: `Current terminal contents:\n\n${content}`,
content: `Current terminal contents:\n\n${
content || "The terminal is empty."
}`,
name: "Terminal",
},
];

View file

@ -1,5 +1,6 @@
import fetch from "node-fetch";
import { afterAll, describe, expect, test } from "vitest";
import { contextProviderClassFromName } from ".";
import {
ContextProviderExtras,
@ -8,7 +9,7 @@ import {
} from "../..";
import { ConfigHandler } from "../../config/ConfigHandler";
import { LLMLogger } from "../../llm/logger";
import { TEST_DIR } from "../../test/testDir";
import { setUpTestDir, tearDownTestDir, TEST_DIR } from "../../test/testDir";
import FileSystemIde from "../../util/filesystem";
const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
@ -25,6 +26,7 @@ const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
async function getContextProviderExtras(
fullInput: string,
): Promise<ContextProviderExtras> {
setUpTestDir();
const ide = new FileSystemIde(TEST_DIR);
const ideSettingsPromise = ide.getIdeSettings();
const llmLogger = new LLMLogger();
@ -52,6 +54,10 @@ async function getContextProviderExtras(
}
describe.skip("Should successfully run all context providers", () => {
afterAll(() => {
tearDownTestDir();
});
const extrasPromise = getContextProviderExtras("Test");
CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => {

View file

@ -1,7 +1,9 @@
import { BaseContextProvider } from "../";
import { ContextProviderName } from "../../";
import { Telemetry } from "../../util/posthog";
import ClipboardContextProvider from "./ClipboardContextProvider";
import CodebaseContextProvider from "./CodebaseContextProvider";
import CodeContextProvider from "./CodeContextProvider";
import ContinueProxyContextProvider from "./ContinueProxyContextProvider";
import CurrentFileContextProvider from "./CurrentFileContextProvider";
@ -56,6 +58,7 @@ export const Providers: (typeof BaseContextProvider)[] = [
JiraIssuesContextProvider,
PostgresContextProvider,
DatabaseContextProvider,
CodebaseContextProvider,
CodeContextProvider,
CurrentFileContextProvider,
URLContextProvider,
@ -73,5 +76,12 @@ export const Providers: (typeof BaseContextProvider)[] = [
export function contextProviderClassFromName(
name: ContextProviderName,
): typeof BaseContextProvider | undefined {
return Providers.find((cls) => cls.description.title === name);
const provider = Providers.find((cls) => cls.description.title === name);
void Telemetry.capture("context_provider_load", {
providerName: name,
found: !!provider, // also capture those which user expected to be present
});
return provider;
}

View file

@ -1,4 +1,5 @@
import { Chunk } from "../../../";
import { Telemetry } from "../../../util/posthog";
import { findUriInDirs } from "../../../util/uri";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
@ -23,7 +24,8 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
try {
ftsChunks = await this.retrieveFts(args, ftsNFinal);
} catch (error) {
console.error("Error retrieving FTS chunks:", error);
await Telemetry.captureError("no_reranker_fts_retrieval", error);
// console.error("Error retrieving FTS chunks:", error);
}
let embeddingsChunks: Chunk[] = [];
@ -32,6 +34,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
? await this.retrieveEmbeddings(input, embeddingsNFinal)
: [];
} catch (error) {
await Telemetry.captureError("no_reranker_embeddings_retrieval", error);
console.error("Error retrieving embeddings:", error);
}
@ -40,6 +43,10 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(recentlyEditedNFinal);
} catch (error) {
await Telemetry.captureError(
"no_reranker_recently_edited_retrieval",
error,
);
console.error("Error retrieving recently edited files:", error);
}
@ -53,6 +60,7 @@ export default class NoRerankerRetrievalPipeline extends BaseRetrievalPipeline {
filterDirectory,
);
} catch (error) {
await Telemetry.captureError("no_reranker_repo_map_retrieval", error);
console.error("Error retrieving repo map chunks:", error);
}

View file

@ -1,5 +1,6 @@
import { Chunk } from "../../..";
import { RETRIEVAL_PARAMS } from "../../../util/parameters";
import { Telemetry } from "../../../util/posthog";
import { findUriInDirs } from "../../../util/uri";
import { requestFilesFromRepoMap } from "../repoMapRequest";
import { deduplicateChunks } from "../util";
@ -20,7 +21,8 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
try {
ftsChunks = await this.retrieveFts(args, nRetrieve);
} catch (error) {
console.error("Error retrieving FTS chunks:", error);
await Telemetry.captureError("reranker_fts_retrieval", error);
// console.error("Error retrieving FTS chunks:", error);
}
let embeddingsChunks: Chunk[] = [];
@ -29,6 +31,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
? await this.retrieveEmbeddings(input, nRetrieve)
: [];
} catch (error) {
await Telemetry.captureError("reranker_embeddings_retrieval", error);
console.error("Error retrieving embeddings chunks:", error);
}
@ -37,6 +40,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
recentlyEditedFilesChunks =
await this.retrieveAndChunkRecentlyEditedFiles(nRetrieve);
} catch (error) {
await Telemetry.captureError("reranker_recently_edited_retrieval", error);
console.error("Error retrieving recently edited files chunks:", error);
}
@ -50,6 +54,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
filterDirectory,
);
} catch (error) {
await Telemetry.captureError("reranker_repo_map_retrieval", error);
console.error("Error retrieving repo map chunks:", error);
}
@ -102,7 +107,7 @@ export default class RerankerRetrievalPipeline extends BaseRetrievalPipeline {
chunks.forEach((chunk, idx) => chunkIndexMap.set(chunk, idx));
results.sort(
(a, b) => scores[chunkIndexMap.get(a)!] - scores[chunkIndexMap.get(b)!],
(a, b) => scores[chunkIndexMap.get(b)!] - scores[chunkIndexMap.get(a)!],
);
results = results.slice(-this.options.nFinal);
return results;

View file

@ -1,6 +1,6 @@
// Generated by Continue
import { describe, expect, it } from "vitest";
import { Chunk } from "../../index";
import { deduplicateChunks } from "./util";
describe("deduplicateChunks", () => {

View file

@ -1,4 +1,5 @@
import * as crypto from "crypto";
import { expect, test } from "vitest";
import { LicenseKeyData, validateLicenseKey } from "./mdm";
// We'll create a real key pair once for all tests

View file

@ -10,7 +10,6 @@ import {
import { ConfigHandler } from "./config/ConfigHandler";
import { SYSTEM_PROMPT_DOT_FILE } from "./config/getWorkspaceContinueRuleDotFiles";
import { addModel, deleteModel } from "./config/util";
import CodebaseContextProvider from "./context/providers/CodebaseContextProvider";
import CurrentFileContextProvider from "./context/providers/CurrentFileContextProvider";
import { ContinueServerClient } from "./continueServer/stubs/client";
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
@ -21,7 +20,8 @@ import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
import DocsService from "./indexing/docs/DocsService";
import { countTokens } from "./llm/countTokens";
import Ollama from "./llm/llms/Ollama";
import { createNewPromptFileV2 } from "./promptFiles/v2/createNewPromptFile";
import { EditAggregator } from "./nextEdit/context/aggregateEdits";
import { createNewPromptFileV2 } from "./promptFiles/createNewPromptFile";
import { callTool } from "./tools/callTool";
import { ChatDescriber } from "./util/chatDescriber";
import { clipboardCache } from "./util/clipboardCache";
@ -41,6 +41,7 @@ import {
ContextItemWithId,
IdeSettings,
ModelDescription,
Position,
RangeInFile,
ToolCall,
type ContextItem,
@ -50,6 +51,7 @@ import {
import { BLOCK_TYPES, ConfigYaml } from "@continuedev/config-yaml";
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
import { stringifyMcpPrompt } from "./commands/slash/mcpSlashCommand";
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
import {
setupLocalConfig,
@ -66,6 +68,8 @@ import { walkDirCache } from "./indexing/walkDir";
import { LLMLogger } from "./llm/logger";
import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants";
import { llmStreamChat } from "./llm/streamChat";
import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
import { processSmallEdit } from "./nextEdit/context/processSmallEdit";
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
import { OnboardingModes } from "./protocol/core";
import type { IMessenger, Message } from "./protocol/messenger";
@ -381,6 +385,19 @@ export class Core {
on("mcp/reloadServer", async (msg) => {
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
});
on("mcp/getPrompt", async (msg) => {
const { serverName, promptName, args } = msg.data;
const prompt = await MCPManagerSingleton.getInstance().getPrompt(
serverName,
promptName,
args,
);
const stringifiedPrompt = stringifyMcpPrompt(prompt);
return {
prompt: stringifiedPrompt,
description: prompt.description,
};
});
// Context providers
on("context/addDocs", async (msg) => {
void this.docsService.indexAndAdd(msg.data);
@ -702,6 +719,52 @@ export class Core {
}
});
on("files/smallEdit", async ({ data }) => {
const EDIT_AGGREGATION_OPTIONS = {
deltaT: 1.0,
deltaL: 5,
maxEdits: 250,
maxDuration: 100.0,
contextSize: 5,
};
EditAggregator.getInstance(
EDIT_AGGREGATION_OPTIONS,
(
beforeAfterdiff: BeforeAfterDiff,
cursorPosBeforeEdit: Position,
cursorPosAfterPrevEdit: Position,
) => {
void processSmallEdit(
beforeAfterdiff,
cursorPosBeforeEdit,
cursorPosAfterPrevEdit,
data.configHandler,
data.getDefsFromLspFunction,
this.ide,
);
},
);
const workspaceDir =
data.actions.length > 0 ? data.actions[0].workspaceDir : undefined;
// Store the latest context data
const instance = EditAggregator.getInstance();
(instance as any).latestContextData = {
configHandler: data.configHandler,
getDefsFromLspFunction: data.getDefsFromLspFunction,
recentlyEditedRanges: data.recentlyEditedRanges,
recentlyVisitedRanges: data.recentlyVisitedRanges,
workspaceDir: workspaceDir,
};
// queueMicrotask prevents blocking the UI thread during typing
queueMicrotask(() => {
void EditAggregator.getInstance().processEdits(data.actions);
});
});
// Docs, etc. indexing
on("indexing/reindex", async (msg) => {
if (msg.data.type === "docs") {
@ -809,7 +872,7 @@ export class Core {
this.messenger.send("toolCallPartialOutput", params);
};
return await callTool(tool, toolCall, {
const result = await callTool(tool, toolCall, {
config,
ide: this.ide,
llm: config.selectedModelByRole.chat,
@ -820,6 +883,8 @@ export class Core {
onPartialOutput,
codeBaseIndexer: this.codeBaseIndexer,
});
return result;
}
private async isItemTooBig(item: ContextItemWithId) {
@ -1031,8 +1096,6 @@ export class Core {
// user doesn't need these in their config.json for the shortcuts to work
// option+enter
new CurrentFileContextProvider({}),
// cmd+enter
new CodebaseContextProvider({}),
].find((provider) => provider.description.title === name);
if (!provider) {
return [];
@ -1044,6 +1107,10 @@ export class Core {
itemId: uuidv4(),
};
void Telemetry.capture("context_provider_get_context_items", {
name: provider.description.title,
});
const items = await provider.getContextItems(query, {
config,
llm,

View file

View file

@ -1,13 +1,22 @@
import { DevDataLogEvent } from "@continuedev/config-yaml";
import fs from "fs";
import path from "path";
import {
afterAll,
beforeAll,
beforeEach,
describe,
expect,
it,
vi,
} from "vitest";
import { IdeInfo, IdeSettings } from "..";
import { Core } from "../core";
import { getDevDataFilePath } from "../util/paths";
import { DataLogger } from "./log";
// Only mock fetch, not fs
jest.mock("@continuedev/fetch");
vi.mock("@continuedev/fetch");
const TEST_EVENT: DevDataLogEvent = {
name: "tokensGenerated",
@ -54,7 +63,7 @@ describe("DataLogger", () => {
beforeEach(() => {
// Reset mocks
jest.clearAllMocks();
vi.clearAllMocks();
// Remove test file if it exists
if (fs.existsSync(testFilePath)) {
@ -67,7 +76,7 @@ describe("DataLogger", () => {
// Mock core and required promises
dataLogger.core = {
configHandler: {
loadConfig: jest.fn().mockResolvedValue({
loadConfig: vi.fn().mockResolvedValue({
config: {
data: [],
},
@ -78,7 +87,7 @@ describe("DataLogger", () => {
},
},
controlPlaneClient: {
getAccessToken: jest.fn().mockResolvedValue("test-access-token"),
getAccessToken: vi.fn().mockResolvedValue("test-access-token"),
},
},
} as unknown as Core;
@ -184,7 +193,6 @@ describe("DataLogger", () => {
// Read file contents and verify
const fileContent = fs.readFileSync(filepath, "utf8");
console.log("debug1 filecontent", fileContent);
expect(fileContent).toContain('"eventName":"chatInteraction"');
expect(fileContent).toContain('"prompt":"Hello, world!"');
expect(fileContent).toContain('"completion":"Hello, world!"');
@ -195,10 +203,10 @@ describe("DataLogger", () => {
describe("logDevData", () => {
it("should log data locally and to configured destinations", async () => {
// Spy on logLocalData and logToOneDestination
const logLocalDataSpy = jest
const logLocalDataSpy = vi
.spyOn(dataLogger, "logLocalData")
.mockResolvedValue();
const logToOneDestinationSpy = jest
const logToOneDestinationSpy = vi
.spyOn(dataLogger, "logToOneDestination")
.mockResolvedValue();
@ -212,7 +220,7 @@ describe("DataLogger", () => {
},
};
dataLogger.core!.configHandler.loadConfig = jest
dataLogger.core!.configHandler.loadConfig = vi
.fn()
.mockResolvedValue(mockConfig);

View file

@ -1,3 +1,5 @@
import { describe, expect, test } from "vitest";
import { dedent } from "../util";
import { myersDiff } from "./myers";

View file

@ -1,6 +1,8 @@
import fs from "node:fs";
import path from "node:path";
import { describe, expect, test } from "vitest";
// @ts-ignore no typings available
import { changed, diff as myersDiff } from "myers-diff";
import { streamDiff } from "../diff/streamDiff.js";
@ -54,12 +56,7 @@ function displayDiff(diff: DiffLine[]) {
}
async function expectDiff(file: string) {
const testFilePath = path.join(
__dirname,
"diff",
"test-examples",
file + ".diff",
);
const testFilePath = path.join(__dirname, "test-examples", file + ".diff");
const testFileContents = fs.readFileSync(testFilePath, "utf-8");
const [oldText, newText, expectedDiff] = testFileContents
.split("\n---\n")

View file

@ -1,8 +1,8 @@
// Generated by continue
import { matchLine, streamLines, generateLines } from "./util";
import { describe, expect, it, vi } from "vitest";
import { ChatMessage } from "../index";
import { jest } from "@jest/globals";
import { generateLines, matchLine, streamLines } from "./util";
describe.skip("matchLine", () => {
it("should match empty lines if the first old line is also empty", () => {
@ -146,7 +146,7 @@ describe("streamLines", () => {
content: "line4",
};
// const spy = jest.spyOn(messageContentModule, "renderChatMessage");
// const spy = vi.spyOn(messageContentModule, "renderChatMessage");
async function* streamCompletion(): AsyncGenerator<ChatMessage> {
yield messageChunk1;
@ -164,7 +164,7 @@ describe("streamLines", () => {
});
it("should log lines if log parameter is true", async () => {
const consoleSpy = jest.spyOn(console, "log").mockImplementation(() => {});
const consoleSpy = vi.spyOn(console, "log").mockImplementation(() => {});
async function* streamCompletion(): AsyncGenerator<string> {
yield "line1\nline2\n";

View file

@ -0,0 +1,386 @@
import { findSearchMatch } from "./findSearchMatch";
describe("findSearchMatch", () => {
describe("Exact matches", () => {
it("should find exact match at the beginning of file", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: fileContent.length,
});
});
it("should find exact match in the middle of file", () => {
const fileContent = `const a = 1;
function hello() {
console.log("world");
}
const b = 2;`;
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: 13 + searchContent.length,
});
});
it("should find exact match at the end of file", () => {
const fileContent = `const a = 1;
function hello() {
console.log("world");
}`;
const searchContent = `function hello() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: fileContent.length,
});
});
it("should find exact match with single line", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `const b = 2;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 13, // After "const a = 1;\n"
endIndex: 13 + searchContent.length,
});
});
it("should find exact match with whitespace preserved", () => {
const fileContent = `function test() {
const x = 1;
const y = 2;
}`;
const searchContent = ` const x = 1;
const y = 2;`;
const result = findSearchMatch(fileContent, searchContent);
// The actual indexOf result is 18, not 17
expect(result).toEqual({
startIndex: 18,
endIndex: 18 + searchContent.length,
});
});
});
describe("Trimmed matches", () => {
it("should find trimmed match when exact match fails due to leading newlines", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `\n\nfunction hello() {
console.log("world");
}\n\n`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: fileContent.length, // Uses trimmed length
});
});
it("should find trimmed match when exact match fails due to trailing newlines", () => {
const fileContent = `const a = 1;
function hello() {
return "world";
}
const b = 2;`;
const searchContent = `\nfunction hello() {
return "world";
}\n`;
const result = findSearchMatch(fileContent, searchContent);
// The function finds the exact match first (at index 12), not the trimmed match
expect(result).toEqual({
startIndex: 12,
endIndex: 12 + searchContent.length,
});
});
it("should find trimmed match for single line with extra whitespace", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `\n const b = 2; \n`;
const result = findSearchMatch(fileContent, searchContent);
const trimmedSearchContent = searchContent.trim();
const expectedStart = fileContent.indexOf(trimmedSearchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + trimmedSearchContent.length,
});
});
});
describe("Empty search content", () => {
it("should match at beginning for empty search content", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
});
});
it("should match at beginning for whitespace-only search content", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = "\n\n \t \n";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
});
});
it("should match at beginning for empty file and empty search", () => {
const fileContent = "";
const searchContent = "";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: 0,
});
});
});
describe("No matches", () => {
it("should return null when search content is not found", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `function goodbye() {
console.log("world");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should return null when trimmed search content is not found", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `\n\nfunction goodbye() {
console.log("world");
}\n\n`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should return null for non-existent single line", () => {
const fileContent = `const a = 1;
const b = 2;
const c = 3;`;
const searchContent = `const d = 4;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should return null for partial match", () => {
const fileContent = `function hello() {
console.log("world");
}`;
const searchContent = `function hello() {
console.log("universe");
}`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
});
describe("Edge cases", () => {
it("should handle empty file with non-empty search", () => {
const fileContent = "";
const searchContent = "function hello() {}";
const result = findSearchMatch(fileContent, searchContent);
expect(result).toBeNull();
});
it("should handle very large content", () => {
const repeatedLine = "const x = 1;\n";
const fileContent =
repeatedLine.repeat(1000) +
"const target = 2;\n" +
repeatedLine.repeat(1000);
const searchContent = "const target = 2;";
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = repeatedLine.length * 1000;
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
});
});
it("should handle special characters and symbols", () => {
const fileContent = `const regex = /[a-zA-Z]+/g;
const symbols = !@#$%^&*();
const unicode = "🚀 Hello 世界";`;
const searchContent = `const symbols = !@#$%^&*();`;
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
});
});
it("should prefer exact match over trimmed match", () => {
const fileContent = `function test() {
const x = 1;
}
function test() {
const x = 1;
}`;
const searchContent = `function test() {
const x = 1;
}`;
const result = findSearchMatch(fileContent, searchContent);
// Should find the first exact match, not a trimmed version
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
});
});
it("should handle multiple occurrences and return first match", () => {
const fileContent = `const a = 1;
const b = 2;
const a = 1;`;
const searchContent = `const a = 1;`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
});
});
});
describe("Real-world scenarios", () => {
it("should match typical function replacement", () => {
const fileContent = `class Calculator {
constructor() {
this.result = 0;
}
reset() {
this.result = 0;
return this;
}
add(value) {
this.result += value;
return this;
}
}`;
const searchContent = ` reset() {
this.result = 0;
return this;
}`;
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
});
});
it("should match import statement", () => {
const fileContent = `import React from 'react';
import { useState, useEffect } from 'react';
import './App.css';
function App() {
return <div>Hello World</div>;
}`;
const searchContent = `import { useState, useEffect } from 'react';`;
const result = findSearchMatch(fileContent, searchContent);
const expectedStart = fileContent.indexOf(searchContent);
expect(result).toEqual({
startIndex: expectedStart,
endIndex: expectedStart + searchContent.length,
});
});
it("should match comment block", () => {
const fileContent = `/**
* This is a comment
* that spans multiple lines
*/
function test() {
// Single line comment
return true;
}`;
const searchContent = `/**
* This is a comment
* that spans multiple lines
*/`;
const result = findSearchMatch(fileContent, searchContent);
expect(result).toEqual({
startIndex: 0,
endIndex: searchContent.length,
});
});
});
});

View file

@ -0,0 +1,55 @@
/**
* Represents a match result with start and end character positions
*/
export interface SearchMatchResult {
/** The starting character index of the match in the file content */
startIndex: number;
/** The ending character index of the match in the file content */
endIndex: number;
}
/**
* Find the exact match position for search content in file content.
* Uses simple exact matching with trimmed newlines for MVP.
*
* Matching Strategy:
* 1. If search content is empty, matches at the beginning of file (position 0)
* 2. Try exact string match first
* 3. Fallback to trimmed content match if exact match fails
*
* @param fileContent - The complete content of the file to search in
* @param searchContent - The content to search for
* @returns Match result with character positions, or null if no match found
*/
export function findSearchMatch(
fileContent: string,
searchContent: string,
): SearchMatchResult | null {
// Strip leading/trailing newlines for basic matching strategy
const trimmedSearchContent = searchContent.trim();
if (trimmedSearchContent === "") {
// Empty search content matches the beginning of the file
return { startIndex: 0, endIndex: 0 };
}
// Try exact match first
const exactIndex = fileContent.indexOf(searchContent);
if (exactIndex !== -1) {
return {
startIndex: exactIndex,
endIndex: exactIndex + searchContent.length,
};
}
// Fallback: try trimmed content match
const trimmedIndex = fileContent.indexOf(trimmedSearchContent);
if (trimmedIndex !== -1) {
return {
startIndex: trimmedIndex,
endIndex: trimmedIndex + trimmedSearchContent.length,
};
}
return null;
}

View file

@ -0,0 +1,390 @@
import {
parseAllSearchReplaceBlocks,
parseSearchReplaceBlock,
} from "./parseSearchReplaceBlock";
describe("parseSearchReplaceBlock", () => {
describe("Complete blocks", () => {
it("should parse a complete basic search/replace block", () => {
const content = `------- SEARCH
reset() {
this.result = 0;
return this;
}
=======
// Resets the calculator result to 0 and returns the instance for method chaining
reset() {
this.result = 0;
return this;
}
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe(`reset() {
this.result = 0;
return this;
}`);
expect(result.replaceContent)
.toBe(`// Resets the calculator result to 0 and returns the instance for method chaining
reset() {
this.result = 0;
return this;
}`);
expect(result.error).toBeUndefined();
});
it("should handle different marker lengths", () => {
const content = `------- SEARCH
old content
=========
new content
+++++++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe("old content");
expect(result.replaceContent).toBe("new content");
});
it("should handle empty search content", () => {
const content = `------- SEARCH
=======
new content
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe("");
expect(result.replaceContent).toBe("new content");
});
it("should handle empty replace content (deletion)", () => {
const content = `------- SEARCH
old content to delete
=======
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe("old content to delete");
expect(result.replaceContent).toBe("");
});
it("should handle both empty search and replace content", () => {
const content = `------- SEARCH
=======
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
expect(result.searchContent).toBe("");
expect(result.replaceContent).toBe("");
});
});
describe("Incomplete blocks", () => {
it("should handle incomplete search block", () => {
const content = `------- SEARCH
some content`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.searchContent).toBe("some content");
expect(result.replaceContent).toBe("");
expect(result.error).toBeUndefined();
});
it("should handle incomplete replace block", () => {
const content = `------- SEARCH
old content
=======
new content`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.searchContent).toBe("old content");
expect(result.replaceContent).toBe("new content");
expect(result.error).toBeUndefined();
});
});
describe("Error cases", () => {
it("should error on search end without start", () => {
const content = `=======
some content
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.error).toBe(
"Found search block end marker without matching start marker",
);
});
it("should error on replace end without replace start", () => {
const content = `+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.error).toBe(
"Found replace block end marker without matching replace start marker",
);
});
});
describe("Regex pattern validation", () => {
it("should match various search start patterns", () => {
const patterns = ["--- SEARCH", "------- SEARCH", "------------- SEARCH"];
patterns.forEach((pattern) => {
const content = `${pattern}
content
=======
replacement
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
});
});
it("should match various search end patterns", () => {
const patterns = ["===", "=======", "=============="];
patterns.forEach((pattern) => {
const content = `------- SEARCH
content
${pattern}
replacement
+++++++ REPLACE`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
});
});
it("should match various replace end patterns", () => {
const patterns = [
"+++ REPLACE",
"+++++++ REPLACE",
"+++++++++++ REPLACE",
];
patterns.forEach((pattern) => {
const content = `------- SEARCH
content
=======
replacement
${pattern}`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(true);
});
});
it("should not match invalid patterns", () => {
const invalidPatterns = [
"-- SEARCH", // Too few dashes
"SEARCH", // No markers
"== SEARCH", // Wrong markers
"=== REPLACE", // Wrong end marker
"++++ SEARCH", // Wrong markers for search
];
invalidPatterns.forEach((pattern) => {
const content = `${pattern}
content`;
const result = parseSearchReplaceBlock(content);
expect(result.isComplete).toBe(false);
expect(result.searchContent).toBe(""); // Should not enter search mode
});
});
});
});
describe("parseAllSearchReplaceBlocks", () => {
it("should parse multiple complete blocks", () => {
const content = `------- SEARCH
old code 1
=======
new code 1
+++++++ REPLACE
------- SEARCH
old code 2
=======
new code 2
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe("old code 1");
expect(blocks[0].replaceContent).toBe("new code 1");
expect(blocks[1].searchContent).toBe("old code 2");
expect(blocks[1].replaceContent).toBe("new code 2");
});
it("should handle blocks with different content", () => {
const content = `------- SEARCH
function old() {
return 1;
}
=======
function new() {
return 2;
}
+++++++ REPLACE
------- SEARCH
const x = 'old';
=======
const x = 'new';
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe(`function old() {
return 1;
}`);
expect(blocks[0].replaceContent).toBe(`function new() {
return 2;
}`);
expect(blocks[1].searchContent).toBe(`const x = 'old';`);
expect(blocks[1].replaceContent).toBe(`const x = 'new';`);
});
it("should handle deletion blocks (empty replace content)", () => {
const content = `------- SEARCH
code to keep
=======
modified code
+++++++ REPLACE
------- SEARCH
code to delete
=======
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe("code to keep");
expect(blocks[0].replaceContent).toBe("modified code");
expect(blocks[1].searchContent).toBe("code to delete");
expect(blocks[1].replaceContent).toBe(""); // Deletion
});
it("should handle insertion blocks (empty search content)", () => {
const content = `------- SEARCH
existing code
=======
modified existing code
+++++++ REPLACE
------- SEARCH
=======
new code to insert
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe("existing code");
expect(blocks[0].replaceContent).toBe("modified existing code");
expect(blocks[1].searchContent).toBe(""); // Insertion
expect(blocks[1].replaceContent).toBe("new code to insert");
});
it("should skip incomplete blocks", () => {
const content = `------- SEARCH
incomplete block
------- SEARCH
complete block
=======
replacement
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(1);
expect(blocks[0].searchContent).toBe("complete block");
expect(blocks[0].replaceContent).toBe("replacement");
});
it("should handle single block", () => {
const content = `------- SEARCH
single block
=======
replacement
+++++++ REPLACE`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(1);
expect(blocks[0].searchContent).toBe("single block");
expect(blocks[0].replaceContent).toBe("replacement");
});
it("should return empty array when no complete blocks found", () => {
const content = `------- SEARCH
incomplete
=======
missing replace marker`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(0);
});
it("should handle blocks with extra content between them", () => {
const content = `Some other content here
------- SEARCH
block 1
=======
replacement 1
+++++++ REPLACE
More content in between
------- SEARCH
block 2
=======
replacement 2
+++++++ REPLACE
Trailing content`;
const blocks = parseAllSearchReplaceBlocks(content);
expect(blocks).toHaveLength(2);
expect(blocks[0].searchContent).toBe("block 1");
expect(blocks[0].replaceContent).toBe("replacement 1");
expect(blocks[1].searchContent).toBe("block 2");
expect(blocks[1].replaceContent).toBe("replacement 2");
});
it("should throw error for malformed blocks", () => {
const content = `------- SEARCH
content
+++++++ REPLACE`; // Missing =======
expect(() => parseAllSearchReplaceBlocks(content)).toThrow(
"Found replace block end marker without matching replace start marker",
);
});
});

View file

@ -0,0 +1,147 @@
// Search and replace block markers using flexible regex patterns
const SEARCH_BLOCK_START_REGEX = /^[-]{3,} SEARCH$/;
const SEARCH_BLOCK_END_REGEX = /^[=]{3,}$/;
const REPLACE_BLOCK_END_REGEX = /^[+]{3,} REPLACE$/;
export interface SearchReplaceBlockResult {
/** Whether a complete search/replace block has been parsed */
isComplete: boolean;
/** The content to search for in the file */
searchContent?: string;
/** The content to replace the search content with */
replaceContent?: string;
/** Error message if parsing failed */
error?: string;
}
/**
* Parses a search and replace block from content.
*
* Expected format:
* ------- SEARCH
* [content to find]
* =======
* [content to replace with]
* +++++++ REPLACE
*
* @param content - The content to parse
* @returns ParseResult with completion status and extracted content
*/
export function parseSearchReplaceBlock(
content: string,
): SearchReplaceBlockResult {
const lines = content.split("\n");
let currentSearchContent = "";
let currentReplaceContent = "";
let inSearch = false;
let inReplace = false;
for (const line of lines) {
if (SEARCH_BLOCK_START_REGEX.test(line)) {
inSearch = true;
inReplace = false;
currentSearchContent = "";
currentReplaceContent = "";
continue;
}
if (SEARCH_BLOCK_END_REGEX.test(line)) {
if (!inSearch) {
return {
isComplete: false,
error: "Found search block end marker without matching start marker",
};
}
inSearch = false;
inReplace = true;
continue;
}
if (REPLACE_BLOCK_END_REGEX.test(line)) {
if (!inReplace) {
return {
isComplete: false,
error:
"Found replace block end marker without matching replace start marker",
};
}
// Complete block found
return {
isComplete: true,
searchContent: currentSearchContent.trim(),
replaceContent: currentReplaceContent.trim(),
};
}
// Accumulate content
if (inSearch) {
currentSearchContent += line + "\n";
} else if (inReplace) {
currentReplaceContent += line + "\n";
}
}
// Block is not yet complete
return {
isComplete: false,
searchContent: currentSearchContent.trim(),
replaceContent: currentReplaceContent.trim(),
};
}
/**
* Parses all complete search and replace blocks from content.
*
* @param content - The content containing multiple search/replace blocks
* @returns Array of complete search/replace blocks found
* @throws Error if any malformed blocks are encountered
*/
export function parseAllSearchReplaceBlocks(
content: string,
): SearchReplaceBlockResult[] {
const blocks: SearchReplaceBlockResult[] = [];
const lines = content.split("\n");
let currentBlockLines: string[] = [];
let inBlock = false;
for (const line of lines) {
if (SEARCH_BLOCK_START_REGEX.test(line)) {
// Start of new block
if (inBlock && currentBlockLines.length > 0) {
// Process previous incomplete block if any
const blockContent = currentBlockLines.join("\n");
const result = parseSearchReplaceBlock(blockContent);
if (result.isComplete) {
blocks.push(result);
} else if (result.error) {
// Fail fast on any parsing error
throw new Error(result.error);
}
// If incomplete but no error, it's just a partial block - continue processing
}
currentBlockLines = [line];
inBlock = true;
} else if (inBlock) {
currentBlockLines.push(line);
// Check if this line completes the current block
if (REPLACE_BLOCK_END_REGEX.test(line)) {
const blockContent = currentBlockLines.join("\n");
const result = parseSearchReplaceBlock(blockContent);
if (result.isComplete) {
blocks.push(result);
} else if (result.error) {
// Fail fast on any parsing error
throw new Error(result.error);
}
currentBlockLines = [];
inBlock = false;
}
}
}
return blocks;
}

88
core/index.d.ts vendored
View file

@ -731,6 +731,8 @@ export interface IDE {
isTelemetryEnabled(): Promise<boolean>;
isWorkspaceRemote(): Promise<boolean>;
getUniqueId(): Promise<string>;
getTerminalContents(): Promise<string>;
@ -836,15 +838,44 @@ export interface ContinueSDK {
abortController: AbortController;
}
export interface SlashCommand {
/* Be careful changing SlashCommand or SlashCommandDescription, config.ts can break */
export interface SlashCommandDescription {
name: string;
description: string;
prompt?: string;
params?: { [key: string]: any };
promptFile?: string;
}
export interface SlashCommand extends SlashCommandDescription {
run: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>;
}
export interface SlashCommandWithSource extends SlashCommandDescription {
run?: (sdk: ContinueSDK) => AsyncGenerator<string | undefined>; // Optional - only needed for legacy
source: SlashCommandSource;
promptFile?: string;
overrideSystemMessage?: string;
}
export type SlashCommandSource =
| "built-in-legacy"
| "built-in"
| "json-custom-command"
| "config-ts-slash-command"
| "yaml-prompt-block"
| "mcp-prompt"
| "prompt-file-v1"
| "prompt-file-v2"
| "invokable-rule";
export interface SlashCommandDescWithSource extends SlashCommandDescription {
isLegacy: boolean; // Maps to if slashcommand.run exists
source: SlashCommandSource;
promptFile?: string;
mcpServerName?: string;
mcpArgs?: MCPPromptArgs;
}
// Config
export type StepName =
@ -945,8 +976,6 @@ export interface ContextProviderWithParams {
params: { [key: string]: any };
}
export type SlashCommandDescription = Omit<SlashCommand, "run">;
export interface CustomCommand {
name: string;
prompt: string;
@ -1007,6 +1036,7 @@ interface ToolChoice {
export interface ConfigDependentToolParams {
rules: RuleWithSource[];
enableExperimentalTools: boolean;
}
export type GetTool = (params: ConfigDependentToolParams) => Tool;
@ -1170,14 +1200,16 @@ export type MCPConnectionStatus =
| "error"
| "not-connected";
export type MCPPromptArgs = {
name: string;
description?: string;
required?: boolean;
}[];
export interface MCPPrompt {
name: string;
description?: string;
arguments?: {
name: string;
description?: string;
required?: boolean;
}[];
arguments?: MCPPromptArgs;
}
// Leaving here to ideate on
@ -1226,6 +1258,7 @@ export interface ContinueUIConfig {
codeWrap?: boolean;
showSessionTabs?: boolean;
autoAcceptEditToolDiffs?: boolean;
logEditingData?: boolean;
}
export interface ContextMenuConfig {
@ -1289,6 +1322,14 @@ export interface ShowFilePayload {
filepath: string;
}
export interface ApplyToFilePayload {
streamId: string;
filepath?: string;
text: string;
toolCallId?: string;
isSearchAndReplace?: boolean;
}
export interface RangeInFileWithContents {
filepath: string;
range: {
@ -1298,6 +1339,16 @@ export interface RangeInFileWithContents {
contents: string;
}
export interface RangeInFileWithNextEditInfo {
filepath: string;
range: Range;
fileContents: string;
editText: string;
afterCursorPos: Position;
beforeCursorPos: Position;
workspaceDir: string;
}
export type SetCodeToEditPayload = RangeInFileWithContents | FileWithContents;
/**
@ -1334,6 +1385,7 @@ export interface ExperimentalConfig {
modelRoles?: ExperimentalModelRoles;
defaultContext?: DefaultContextProvider[];
promptPath?: string;
enableExperimentalTools?: boolean;
/**
* Quick actions are a way to add custom commands to the Code Lens of
@ -1358,6 +1410,16 @@ export interface ExperimentalConfig {
* If enabled, will add the current file as context.
*/
useCurrentFileAsContext?: boolean;
/**
* If enabled, will save data on the user's editing processes
*/
logEditingData?: boolean;
/**
* If enabled, will enable next edit in place of autocomplete
*/
optInNextEditFeature?: boolean;
}
export interface AnalyticsConfig {
@ -1442,7 +1504,7 @@ export interface Config {
/** Request options that will be applied to all models and context providers */
requestOptions?: RequestOptions;
/** The list of slash commands that will be available in the sidebar */
slashCommands?: SlashCommand[];
slashCommands?: (SlashCommand | SlashCommandWithSource)[];
/** Each entry in this array will originally be a ContextProviderWithParams, the same object from your config.json, but you may add CustomContextProviders.
* A CustomContextProvider requires you only to define a title and getContextItems function. When you type '@title <query>', Continue will call `getContextItems(query)`.
*/
@ -1479,7 +1541,7 @@ export interface ContinueConfig {
// systemMessage?: string;
completionOptions?: BaseCompletionOptions;
requestOptions?: RequestOptions;
slashCommands: SlashCommand[];
slashCommands: SlashCommandWithSource[];
contextProviders: IContextProvider[];
disableSessionTitles?: boolean;
disableIndexing?: boolean;
@ -1502,7 +1564,7 @@ export interface BrowserSerializedContinueConfig {
// systemMessage?: string;
completionOptions?: BaseCompletionOptions;
requestOptions?: RequestOptions;
slashCommands: SlashCommandDescription[];
slashCommands: SlashCommandDescWithSource[];
contextProviders: ContextProviderDescription[];
disableIndexing?: boolean;
disableSessionTitles?: boolean;
@ -1577,12 +1639,12 @@ export interface RuleWithSource {
slug?: string;
source: RuleSource;
globs?: string | string[];
regex?: string | string[];
rule: string;
description?: string;
ruleFile?: string;
alwaysApply?: boolean;
}
export interface CompleteOnboardingPayload {
mode: OnboardingModes;
provider?: string;

View file

@ -124,14 +124,6 @@ describe("CodebaseIndexer", () => {
return updates;
}
async function refreshIndexFiles(files: string[]) {
const updates = [];
for await (const update of codebaseIndexer.refreshFiles(files)) {
updates.push(update);
}
return updates;
}
async function getAllIndexedFiles() {
const files = await testIndex.getIndexedFilesForTags(
await testIde.getTags(testIndex.artifactId),
@ -197,7 +189,7 @@ describe("CodebaseIndexer", () => {
test("should successfuly re-index specific files", async () => {
// Could add more specific tests for this but uses similar logic
const before = await getAllIndexedFiles();
await refreshIndexFiles(before);
await codebaseIndexer.refreshCodebaseIndexFiles(before);
const after = await getAllIndexedFiles();
expect(after.length).toBe(before.length);

View file

@ -43,7 +43,7 @@ export class CodebaseIndexer {
* - To limit memory usage for indexes that perform computations locally, e.g. FTS
* - To make as few requests as possible to the embeddings providers
*/
filesPerBatch = 500;
filesPerBatch = 200;
private indexingCancellationController: AbortController | undefined;
private codebaseIndexingState: IndexingProgressUpdate;
private readonly pauseToken: PauseToken;
@ -75,16 +75,10 @@ export class CodebaseIndexer {
this.pauseToken = new PauseToken(initialPaused);
}
/**
* Set the paused state of the indexer
*/
set paused(value: boolean) {
this.pauseToken.paused = value;
}
/**
* Get the current paused state of the indexer
*/
get paused(): boolean {
return this.pauseToken.paused;
}
@ -235,7 +229,9 @@ export class CodebaseIndexer {
}
}
async *refreshFiles(files: string[]): AsyncGenerator<IndexingProgressUpdate> {
private async *refreshFiles(
files: string[],
): AsyncGenerator<IndexingProgressUpdate> {
let progress = 0;
if (files.length === 0) {
yield {
@ -525,7 +521,7 @@ export class CodebaseIndexer {
repoName,
)) {
yield {
progress: progress,
progress,
desc,
status: "indexing",
};

View file

@ -63,13 +63,12 @@ export async function* chunkDocument({
resolve({
...chunkWithoutId,
digest,
index,
index: index++,
filepath,
});
})();
}),
);
index++;
}
for await (const chunk of chunkPromises) {
if (!chunk) {

View file

@ -1,5 +1,5 @@
const DEFAULT_MAX_TOKENS = 4096;
const DEFAULT_CONTEXT_LENGTH = 8192;
const DEFAULT_CONTEXT_LENGTH = 32_768;
const DEFAULT_TEMPERATURE = 0.5;
const DEFAULT_ARGS = {

View file

@ -19,10 +19,12 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE_URL =
export const DEFAULT_AGENT_SYSTEM_MESSAGE_URL =
"https://github.com/continuedev/continue/blob/main/core/llm/constructMessages.ts";
const EDIT_MESSAGE = `\
export const CODEBLOCK_FORMATTING_INSTRUCTIONS = `\
Always include the language and file name in the info string when you write code blocks.
If you are editing "src/main.py" for example, your code block should start with '\`\`\`python src/main.py'
`;
export const EDIT_CODE_INSTRUCTIONS = `\
When addressing code modification requests, present a concise code snippet that
emphasizes only the necessary changes and uses abbreviated placeholders for
unmodified sections. For example:
@ -69,14 +71,15 @@ export const DEFAULT_CHAT_SYSTEM_MESSAGE = `\
If the user asks to make changes to files offer that they can use the Apply Button on the code block, or switch to Agent Mode to make the suggested updates automatically.
If needed consisely explain to the user they can switch to agent mode using the Mode Selector dropdown and provide no other details.
${EDIT_MESSAGE}
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
${EDIT_CODE_INSTRUCTIONS}
</important_rules>`;
export const DEFAULT_AGENT_SYSTEM_MESSAGE = `\
<important_rules>
You are in agent mode.
${EDIT_MESSAGE}
${CODEBLOCK_FORMATTING_INSTRUCTIONS}
</important_rules>`;
/**

View file

@ -1,6 +1,10 @@
import { ChatMessage, LLMOptions } from "..";
import { allModelProviders } from "@continuedev/llm-info";
import { LlmInfo } from "@continuedev/llm-info/dist/types";
import { BaseLLM } from ".";
import { DEFAULT_CONTEXT_LENGTH } from "./constants";
import { LLMClasses } from "./llms";
import { LLMLogger } from "./logger";
class DummyLLM extends BaseLLM {
@ -140,4 +144,31 @@ describe("BaseLLM", () => {
describe("*streamChat", () => {
// TODO: Implement tests for *streamChat method
});
describe("default context length", () => {
allModelProviders.map((modelProvider) => {
const LLMClass = LLMClasses.find(
(llm) => llm.providerName === modelProvider.id,
);
if (!LLMClass) {
throw new Error(`did not find LLM provider for ${modelProvider.id}`);
}
const testContextLength = (llmInfo: LlmInfo) => () => {
const llm = new LLMClass({ model: llmInfo.model });
if (llmInfo.contextLength) {
expect(llm.contextLength).toEqual(llmInfo.contextLength);
} else {
expect(llm.contextLength).toEqual(DEFAULT_CONTEXT_LENGTH);
}
};
describe(`${modelProvider.id}`, () => {
modelProvider.models.forEach((llmInfo) => {
test(
`should have correct context length for ${llmInfo.model}`,
testContextLength(llmInfo),
);
});
});
});
});
});

View file

@ -292,6 +292,7 @@ export abstract class BaseLLM implements ILLM {
apiKey: this.apiKey ?? "",
apiBase: this.apiBase,
requestOptions: this.requestOptions,
env: this._llmOptions.env,
});
}
@ -491,28 +492,32 @@ export abstract class BaseLLM implements ILLM {
const msgsCopy = messages ? messages.map((msg) => ({ ...msg })) : [];
let formatted = "";
for (const msg of msgsCopy) {
let contentToShow = "";
if (msg.role === "tool") {
contentToShow = msg.content;
} else if (msg.role === "assistant" && msg.toolCalls) {
contentToShow = msg.toolCalls
?.map(
(toolCall) =>
`${toolCall.function?.name}(${toolCall.function?.arguments})`,
)
.join("\n");
} else if ("content" in msg) {
if (Array.isArray(msg.content)) {
msg.content = renderChatMessage(msg);
}
contentToShow = msg.content;
}
formatted += `<${msg.role}>\n${contentToShow}\n\n`;
formatted += this._formatChatMessage(msg);
}
return formatted;
}
private _formatChatMessage(msg: ChatMessage): string {
let contentToShow = "";
if (msg.role === "tool") {
contentToShow = msg.content;
} else if (msg.role === "assistant" && msg.toolCalls) {
contentToShow = msg.toolCalls
?.map(
(toolCall) =>
`${toolCall.function?.name}(${toolCall.function?.arguments})`,
)
.join("\n");
} else if ("content" in msg) {
if (Array.isArray(msg.content)) {
msg.content = renderChatMessage(msg);
}
contentToShow = msg.content;
}
return `<${msg.role}>\n${contentToShow}\n\n`;
}
protected async *_streamFim(
prefix: string,
suffix: string,
@ -568,11 +573,12 @@ export abstract class BaseLLM implements ILLM {
const result = fromChatCompletionChunk(chunk);
if (result) {
const content = renderChatMessage(result);
const formattedContent = this._formatChatMessage(result);
interaction?.logItem({
kind: "chunk",
chunk: content,
chunk: formattedContent,
});
completion += content;
completion += formattedContent;
yield content;
}
}
@ -931,7 +937,7 @@ export abstract class BaseLLM implements ILLM {
);
const msg = fromChatResponse(response);
yield msg;
completion = renderChatMessage(msg);
completion = this._formatChatMessage(msg);
} else {
// Stream true
const stream = this.openaiAdapter.chatCompletionStream(
@ -944,7 +950,7 @@ export abstract class BaseLLM implements ILLM {
for await (const chunk of stream) {
const result = fromChatCompletionChunk(chunk);
if (result) {
completion += result.content;
completion += this._formatChatMessage(result);
interaction?.logItem({
kind: "message",
message: result,
@ -960,7 +966,7 @@ export abstract class BaseLLM implements ILLM {
completionOptions,
)) {
if (chunk.role === "assistant") {
completion += chunk.content;
completion += this._formatChatMessage(chunk);
} else if (chunk.role === "thinking") {
thinking += chunk.content;
}

View file

@ -8,7 +8,6 @@ class Anthropic extends BaseLLM {
static providerName = "anthropic";
static defaultOptions: Partial<LLMOptions> = {
model: "claude-3-5-sonnet-latest",
contextLength: 200_000,
completionOptions: {
model: "claude-3-5-sonnet-latest",
maxTokens: 8192,

View file

@ -48,7 +48,6 @@ class Bedrock extends BaseLLM {
static defaultOptions: Partial<LLMOptions> = {
region: "us-east-1",
model: "anthropic.claude-3-sonnet-20240229-v1:0",
contextLength: 200_000,
profile: "bedrock",
};
@ -547,7 +546,7 @@ class Bedrock extends BaseLLM {
}
// EMBED //
async embed(chunks: string[]): Promise<number[][]> {
async _embed(chunks: string[]): Promise<number[][]> {
const credentials = await this._getCredentials();
const client = new BedrockRuntimeClient({
region: this.region,

View file

@ -25,16 +25,7 @@ class HuggingFaceTEIEmbeddingsProvider extends BaseLLM {
});
}
async embed(chunks: string[]) {
const batchedChunks = this.getBatchedChunks(chunks);
const results = await Promise.all(
batchedChunks.map((batch) => this.doEmbedRequest(batch)),
);
return results.flat();
}
async doEmbedRequest(batch: string[]): Promise<number[][]> {
async _embed(batch: string[]): Promise<number[][]> {
const headers: Record<string, string> = {
"Content-Type": "application/json",
};

View file

@ -405,7 +405,6 @@ class Ollama extends BaseLLM implements ModelInstaller {
parameters: tool.function.parameters,
},
}));
chatOptions.stream = false; // Cannot set stream = true for tools calls
}
const headers: Record<string, string> = {
"Content-Type": "application/json",

View file

@ -141,7 +141,7 @@ class SageMaker extends BaseLLM {
}
}
async embed(chunks: string[]) {
async _embed(chunks: string[]) {
const credentials = await this._getCredentials();
const client = new SageMakerRuntimeClient({
region: this.region,

View file

@ -2,6 +2,7 @@ import { ChatMessage, CompletionOptions } from "../../index.js";
import { BaseLLM } from "../index.js";
const HARDCODED_CHAT_RESPONSE = "THIS IS A HARDCODED RESPONSE";
const NEXT_EDIT_COMPLETION: string = "<|editable_region_start|>\nHELLO\n";
class TestLLM extends BaseLLM {
static providerName = "test";
@ -24,7 +25,15 @@ class TestLLM extends BaseLLM {
signal: AbortSignal,
options: CompletionOptions,
): AsyncGenerator<string> {
yield this.findResponse(prompt) || `PROMPT: ${prompt}`;
if (
prompt === "NEXT_EDIT" ||
prompt ===
"<|im_start|>user\nNEXT_EDIT<|im_end|>\n<|im_start|>assistant\n"
) {
yield NEXT_EDIT_COMPLETION;
} else {
yield this.findResponse(prompt) || `PROMPT: ${prompt}`;
}
}
protected async *_streamChat(

View file

@ -1,3 +1,4 @@
import Handlebars from "handlebars";
import {
BaseCompletionOptions,
IdeSettings,
@ -6,10 +7,9 @@ import {
JSONModelDescription,
LLMOptions,
} from "../..";
import { renderTemplatedString } from "../../promptFiles/v1/renderTemplatedString";
import { renderTemplatedString } from "../../util/handlebars/renderTemplatedString";
import { DEFAULT_CHAT_SYSTEM_MESSAGE } from "../constructMessages";
import { BaseLLM } from "../index";
import Anthropic from "./Anthropic";
import Asksage from "./Asksage";
import Azure from "./Azure";
@ -121,6 +121,7 @@ export const LLMClasses = [
export async function llmFromDescription(
desc: JSONModelDescription,
readFile: (filepath: string) => Promise<string>,
getUriFromPath: (path: string) => Promise<string | undefined>,
uniqueId: string,
ideSettings: IdeSettings,
llmLogger: ILLMLogger,
@ -142,9 +143,12 @@ export async function llmFromDescription(
baseChatSystemMessage = DEFAULT_CHAT_SYSTEM_MESSAGE;
baseChatSystemMessage += "\n\n";
baseChatSystemMessage += await renderTemplatedString(
Handlebars,
desc.systemMessage,
readFile,
{},
[],
readFile,
getUriFromPath,
);
}

View file

@ -7,6 +7,7 @@ import {
} from "../..";
import { renderChatMessage } from "../../util/messageContent";
import { getCleanUriPath } from "../../util/uri";
import { extractContentFromCodeBlock } from "../utils/extractContentFromCodeBlocks";
import { extractPathsFromCodeBlocks } from "../utils/extractPathsFromCodeBlocks";
import { RulePolicies } from "./types";
@ -52,6 +53,47 @@ const matchesGlobs = (
return false;
};
/**
* Checks if file content matches any of the provided regex regex
*
* @param fileContent - The content of the file to check
* @param regex - A single regex pattern string or array of regex pattern strings
* @returns true if the content matches any pattern (or if no regex is provided), false otherwise
*/
const contentMatchesRegex = (
fileContent: string,
regex: string | string[],
): boolean => {
// Handle single string pattern
if (typeof regex === "string") {
try {
const expression = new RegExp(regex);
return expression.test(fileContent);
} catch (e) {
console.error(`Invalid regex pattern: ${regex}`, e);
return false;
}
}
// Handle array of regex
if (Array.isArray(regex)) {
if (regex.length === 0) return true;
// Content must match at least one pattern
return regex.some((pattern) => {
try {
const regex = new RegExp(pattern);
return regex.test(fileContent);
} catch (e) {
console.error(`Invalid regex pattern: ${pattern}`, e);
return false;
}
});
}
return false;
};
/**
* Determines if a file path is within a specific directory or its subdirectories
*
@ -103,25 +145,67 @@ const isGlobalRule = (rule: RuleWithSource): boolean => {
return true;
}
// Root-level rules with no globs are implicitly global
if (isRootLevelRule(rule) && !rule.globs && rule.alwaysApply !== false) {
// Root-level rules with no globs or regex are implicitly global
if (
isRootLevelRule(rule) &&
!rule.globs &&
!rule.regex &&
rule.alwaysApply !== false
) {
return true;
}
return false;
};
const checkGlobsAndRegex = ({
rule,
filePaths,
fileContents,
}: {
rule: RuleWithSource;
filePaths: string[];
fileContents: Record<string, string>;
}) => {
const matchingFiles = rule.globs
? filePaths.filter((filePath) => matchesGlobs(filePath, rule.globs))
: filePaths;
// If no files match the globs, don't apply the rule
if (matchingFiles.length === 0) {
return false;
}
// Now check for pattern matches in file contents if regex are specified
if (rule.regex) {
// Check if any of the matching files also match the content regex
return matchingFiles.some((filePath) => {
const content = fileContents[filePath];
// If we don't have the content, we can't check regex
if (!content) return false;
return contentMatchesRegex(content, rule.regex!);
});
}
// If we have no regex or if we couldn't check regex (no content),
// just go with the glob matches
return matchingFiles.length > 0;
};
/**
* Determines if a rule should be applied based on its alwaysApply property and file path matching
* Determines if a rule should be applied based on its properties and file matching
*
* @param rule - The rule to check
* @param filePaths - Array of file paths to check against the rule's globs
* @param fileContents - Map of file paths to their contents for pattern matching
* @param rulePolicies - Optional policies that can override normal rule behavior
* @returns true if the rule should be applied, false otherwise
*/
export const shouldApplyRule = (
rule: RuleWithSource,
filePaths: string[],
rulePolicies: RulePolicies = {},
fileContents: Record<string, string> = {},
): boolean => {
const policy = rulePolicies[rule.name || ""];
@ -157,40 +241,27 @@ export const shouldApplyRule = (
isFileInDirectory(filePath, ruleDirPath),
);
// If no files are in this directory, don't apply the rule
if (filesInRuleDirectory.length === 0) {
return false;
}
// If we have globs, check if any files in this directory match them
if (rule.globs) {
return filesInRuleDirectory.some((filePath) =>
matchesGlobs(filePath, rule.globs),
);
}
// No globs but files are in this directory, so apply the rule
return true;
return checkGlobsAndRegex({
filePaths: filesInRuleDirectory,
fileContents,
rule,
});
}
// For root-level rules:
// If alwaysApply is explicitly false, only apply if there are globs AND they match
if (rule.alwaysApply === false) {
if (!rule.globs) {
return false;
}
return filePaths.some((path) => matchesGlobs(path, rule.globs));
// If alwaysApply is explicitly false, we need to check globs and/or regex
if (
rule.alwaysApply === false &&
rule.globs === undefined &&
rule.regex === undefined
) {
return false;
}
// Default behavior for root rules with globs:
// - Only apply if they match the globs
if (rule.globs) {
return filePaths.some((path) => matchesGlobs(path, rule.globs));
}
// This point should not be reached as we've handled all cases above
return false;
return checkGlobsAndRegex({
filePaths,
fileContents,
rule,
});
};
/**
@ -220,10 +291,34 @@ export const getApplicableRules = (
// Combine file paths from both sources
const allFilePaths = [...filePathsFromMessage, ...filePathsFromContextItems];
// Create a map of file paths to their contents for pattern matching
const fileContents: Record<string, string> = {};
// Extract contents from context items with file URIs
contextItems.forEach((item) => {
if (item.uri?.type === "file" && item.uri?.value) {
fileContents[item.uri.value] = item.content;
}
});
// Extract contents from code blocks in the message for paths that don't have content yet
if (userMessage) {
const messageContent = renderChatMessage(userMessage);
filePathsFromMessage.forEach((path) => {
// Only extract content if we don't already have it from context items
if (!fileContents[path]) {
const blockContent = extractContentFromCodeBlock(messageContent, path);
if (blockContent) {
fileContents[path] = blockContent;
}
}
});
}
// Apply shouldApplyRule to all rules - this will handle global rules, rule policies,
// and path matching in a consistent way
const applicableRules = rules.filter((rule) =>
shouldApplyRule(rule, allFilePaths, rulePolicies),
shouldApplyRule(rule, allFilePaths, rulePolicies, fileContents),
);
return applicableRules;

View file

@ -1,6 +1,14 @@
import { describe, expect, it } from "vitest";
import { RuleWithSource } from "../..";
import { shouldApplyRule } from "./getSystemMessageWithRules";
import {
ContextItemId,
ContextItemWithId,
RuleWithSource,
UserChatMessage,
} from "../..";
import {
getApplicableRules,
shouldApplyRule,
} from "./getSystemMessageWithRules";
import { RulePolicies } from "./types";
describe("Rule colocation glob matching", () => {
@ -244,3 +252,228 @@ describe("Rule policies", () => {
).toBe(false);
});
});
describe("Content pattern matching", () => {
it("should apply rules when file content matches pattern", () => {
// Rule with pattern to match React component files
const reactComponentRule: RuleWithSource = {
name: "React Component Rule",
rule: "Follow React component standards",
regex: "export (function|const) \\w+.*\\(",
source: "rules-block",
ruleFile: "src/components/rules.md",
};
// File that matches the pattern
const filePath = "src/components/Button.tsx";
const fileContents = {
[filePath]:
"export function Button() { return <button>Click me</button> }",
};
expect(
shouldApplyRule(reactComponentRule, [filePath], {}, fileContents),
).toBe(true);
// File that doesn't match the pattern
const nonMatchingContents = {
[filePath]:
"import React from 'react'; // Just an import, not a component",
};
expect(
shouldApplyRule(reactComponentRule, [filePath], {}, nonMatchingContents),
).toBe(false);
});
it("should support multiple regex regex as an array", () => {
// Rule with multiple regex
const multiPatternRule: RuleWithSource = {
name: "Multi-Pattern Rule",
rule: "Apply to functions or classes",
regex: ["function\\s+\\w+", "class\\s+\\w+"],
source: "rules-block",
ruleFile: "src/utils/rules.md",
};
const filePath = "src/utils/helper.ts";
// Content with function - should match
const functionContent = {
[filePath]: "function formatDate(date) { return date.toISOString(); }",
};
expect(
shouldApplyRule(multiPatternRule, [filePath], {}, functionContent),
).toBe(true);
// Content with class - should match
const classContent = {
[filePath]:
"class DateFormatter { format(date) { return date.toISOString(); } }",
};
expect(
shouldApplyRule(multiPatternRule, [filePath], {}, classContent),
).toBe(true);
// Content with neither - should not match
const nonMatchingContent = {
[filePath]: "const PI = 3.14159;",
};
expect(
shouldApplyRule(multiPatternRule, [filePath], {}, nonMatchingContent),
).toBe(false);
});
it("should apply rules based on both globs and regex when both are specified", () => {
// Rule with both glob and pattern restrictions
const typescriptClassRule: RuleWithSource = {
name: "TypeScript Class Rule",
rule: "Follow class standards in TypeScript",
globs: "**/*.ts",
regex: "class\\s+\\w+",
source: "rules-block",
ruleFile: "src/models/rules.md",
};
const tsFilePath = "src/models/User.ts";
const jsFilePath = "src/models/Product.js";
// TypeScript file with class - should match
const tsClassContent = {
[tsFilePath]: "export class User { constructor(public name: string) {} }",
};
expect(
shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsClassContent),
).toBe(true);
// TypeScript file without class - should not match
const tsNonClassContent = {
[tsFilePath]: "export const createUser = (name: string) => ({ name });",
};
expect(
shouldApplyRule(typescriptClassRule, [tsFilePath], {}, tsNonClassContent),
).toBe(false);
// JavaScript file with class - should not match due to glob
const jsClassContent = {
[jsFilePath]:
"export class Product { constructor(name) { this.name = name; } }",
};
expect(
shouldApplyRule(typescriptClassRule, [jsFilePath], {}, jsClassContent),
).toBe(false);
});
it("should extract file content from messages for pattern matching", () => {
// Rule with pattern
const arrowFunctionRule: RuleWithSource = {
name: "Arrow Function Rule",
rule: "Use arrow functions for better this binding",
regex: "const\\s+\\w+\\s*=\\s*\\(",
source: "rules-block",
ruleFile: "src/utils/rules.md",
};
// Message with code block containing a matching pattern
const messageWithArrowFn: UserChatMessage = {
role: "user",
content:
"Can you check this code?\n```typescript src/utils/formatter.ts\nconst format = (date) => {\n return date.toISOString();\n};\n```",
};
// Create context item to match the file in the message
const contextItem: ContextItemWithId = {
id: { providerTitle: "file", itemId: "formatter" } as ContextItemId,
uri: { type: "file", value: "src/utils/formatter.ts" },
content: "const format = (date) => {\n return date.toISOString();\n};",
name: "formatter.ts",
description: "Utility formatter",
};
// Should match the pattern
const applicableRules = getApplicableRules(
messageWithArrowFn,
[arrowFunctionRule],
[contextItem],
);
expect(applicableRules).toHaveLength(1);
expect(applicableRules[0].name).toBe("Arrow Function Rule");
// Message with code block that doesn't match the pattern
const messageWithoutArrowFn: UserChatMessage = {
role: "user",
content:
"Can you check this code?\n```typescript src/utils/formatter.ts\nfunction format(date) {\n return date.toISOString();\n}\n```",
};
// Context item with non-matching content
const nonMatchingContextItem: ContextItemWithId = {
id: { providerTitle: "file", itemId: "formatter2" } as ContextItemId,
uri: { type: "file", value: "src/utils/formatter.ts" },
content: "function format(date) {\n return date.toISOString();\n}",
name: "formatter.ts",
description: "Utility formatter",
};
// Should not match the pattern
const nonApplicableRules = getApplicableRules(
messageWithoutArrowFn,
[arrowFunctionRule],
[nonMatchingContextItem],
);
expect(nonApplicableRules).toHaveLength(0);
});
it("should handle invalid regex regex gracefully", () => {
// Rule with invalid regex pattern
const invalidRegexRule: RuleWithSource = {
name: "Invalid Regex Rule",
rule: "This rule has an invalid regex pattern",
regex: "([unclosed parenthesis",
source: "rules-block",
ruleFile: "src/utils/rules.md",
};
const filePath = "src/utils/helper.ts";
const fileContents = {
[filePath]: "function helper() { return true; }",
};
// Should not throw an error but gracefully not apply the rule
expect(
shouldApplyRule(invalidRegexRule, [filePath], {}, fileContents),
).toBe(false);
});
it("should respect directory restrictions for pattern rules", () => {
// Rule with pattern in a nested directory
const nestedPatternRule: RuleWithSource = {
name: "Nested Pattern Rule",
rule: "Apply only to model files with interfaces",
regex: "interface\\s+\\w+",
source: "rules-block",
ruleFile: "src/models/rules.md",
};
// File in the correct directory with matching content
const modelFilePath = "src/models/User.ts";
const modelContents = {
[modelFilePath]: "export interface User { id: string; name: string; }",
};
expect(
shouldApplyRule(nestedPatternRule, [modelFilePath], {}, modelContents),
).toBe(true);
// File outside the directory with matching content - should not match
const utilFilePath = "src/utils/types.ts";
const utilContents = {
[utilFilePath]:
"export interface Config { apiUrl: string; timeout: number; }",
};
expect(
shouldApplyRule(nestedPatternRule, [utilFilePath], {}, utilContents),
).toBe(false);
});
});

View file

@ -59,6 +59,12 @@ export async function* llmStreamChat(
},
true,
);
if (!slashCommand.run) {
console.error(
`Slash command ${command.name} (${command.source}) has no run function`,
);
throw new Error(`Slash command not found`);
}
const gen = slashCommand.run({
input,

View file

@ -0,0 +1,94 @@
import { extractContentFromCodeBlock } from "./extractContentFromCodeBlocks";
describe("extractContentFromCodeBlock", () => {
it("should extract content from code block with language and filepath", () => {
const content = "```typescript src/main.ts\nconst x = 1;\n```";
expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
"const x = 1;",
);
});
it("should extract content from code block with filepath only (no language)", () => {
const content = "```test.js\nclass Calculator { }\n```";
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
"class Calculator { }",
);
});
it("should extract content from code block with line ranges", () => {
const content = "```js test.js (19-25)\nfunction test() {}\n```";
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
"function test() {}",
);
});
it("should handle multiple code blocks and find the right one", () => {
const content =
"```typescript src/main.ts\nconst x = 1;\n```\n" +
"```test.js\nclass Calculator { }\n```\n" +
"```js utils.js (19-25)\nfunction test() {}\n```";
expect(extractContentFromCodeBlock(content, "src/main.ts")).toBe(
"const x = 1;",
);
expect(extractContentFromCodeBlock(content, "test.js")).toBe(
"class Calculator { }",
);
expect(extractContentFromCodeBlock(content, "utils.js")).toBe(
"function test() {}",
);
});
it("should handle paths with special regex characters", () => {
const content =
"```typescript src/special+chars.ts[123]\nconst special = true;\n```";
expect(
extractContentFromCodeBlock(content, "src/special+chars.ts[123]"),
).toBe("const special = true;");
});
it("should handle multiline content", () => {
const content =
"```typescript src/multi-line.ts\n" +
"function example() {\n" +
" const x = 1;\n" +
" return x + 2;\n" +
"}\n" +
"```";
const expected =
"function example() {\n" + " const x = 1;\n" + " return x + 2;\n" + "}";
expect(extractContentFromCodeBlock(content, "src/multi-line.ts")).toBe(
expected,
);
});
it("should return undefined when path doesn't exist in any code block", () => {
const content = "```typescript src/main.ts\nconst x = 1;\n```";
expect(
extractContentFromCodeBlock(content, "nonexistent.ts"),
).toBeUndefined();
});
it("should extract content when the path has directory structure", () => {
const content =
"```js src/components/Button.jsx\nconst Button = () => <button>Click me</button>;\n```";
expect(
extractContentFromCodeBlock(content, "src/components/Button.jsx"),
).toBe("const Button = () => <button>Click me</button>;");
});
it("should match exact paths only", () => {
const content =
"```typescript src/utils.ts\nconst util = {};\n```\n" +
"```typescript src/utils/index.ts\nconst index = {};\n```";
expect(extractContentFromCodeBlock(content, "src/utils.ts")).toBe(
"const util = {};",
);
expect(extractContentFromCodeBlock(content, "src/utils/index.ts")).toBe(
"const index = {};",
);
});
});

View file

@ -0,0 +1,33 @@
/**
* Extracts content from code blocks with given path
* @param content The full message content
* @param path The file path to look for
* @returns The content of the code block if found, undefined otherwise
*/
export function extractContentFromCodeBlock(
content: string,
path: string,
): string | undefined {
// Escape special characters in the path for regex
const escapedPath = path.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
// Match the code block with this path
// This regex looks for:
// 1. Code block start with the path (```[language] path)
// 2. The content until the closing ```
// The path can be:
// - With language: ```typescript src/main.ts
// - Without language: ```src/main.ts
// - With line ranges: ```js src/main.ts (1-10)
const regex = new RegExp(
`\`\`\`[^\\n]*\\b${escapedPath}(?:\\s+\\([\\d-]+\\))?[^\\n]*\\n([\\s\\S]*?)\\n\`\`\``,
"m",
);
const match = content.match(regex);
if (match && match[1]) {
return match[1];
}
return undefined;
}

View file

@ -1,17 +1,14 @@
import { ConfigHandler } from "../config/ConfigHandler.js";
import { IDE, ILLM } from "../index.js";
import { ChatMessage, IDE, ILLM } from "../index.js";
import OpenAI from "../llm/llms/OpenAI.js";
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
import { shouldCompleteMultiline } from "../autocomplete/classification/shouldCompleteMultiline.js";
import { ContextRetrievalService } from "../autocomplete/context/ContextRetrievalService.js";
import { BracketMatchingService } from "../autocomplete/filtering/BracketMatchingService.js";
import { CompletionStreamer } from "../autocomplete/generation/CompletionStreamer.js";
import { postprocessCompletion } from "../autocomplete/postprocessing/index.js";
import { shouldPrefilter } from "../autocomplete/prefiltering/index.js";
import { getAllSnippets } from "../autocomplete/snippets/index.js";
import { renderPrompt } from "../autocomplete/templating/index.js";
import { getAllSnippetsWithoutRace } from "../autocomplete/snippets/index.js";
import { GetLspDefinitionsFunction } from "../autocomplete/types.js";
import { AutocompleteDebouncer } from "../autocomplete/util/AutocompleteDebouncer.js";
import { AutocompleteLoggingService } from "../autocomplete/util/AutocompleteLoggingService.js";
@ -21,6 +18,14 @@ import {
AutocompleteInput,
AutocompleteOutcome,
} from "../autocomplete/util/types.js";
import { replaceEscapedCharacters } from "../util/text.js";
import {
Prompt,
renderDefaultSystemPrompt,
renderDefaultUserPrompt,
renderPrompt,
} from "./templating/NextEditPromptEngine.js";
// import { renderPrompt } from "./templating/NextEditPromptEngine.js";
const autocompleteCache = AutocompleteLruCache.get();
@ -33,6 +38,8 @@ const ERRORS_TO_IGNORE = [
];
export class NextEditProvider {
private static instance: NextEditProvider | null = null;
private autocompleteCache = AutocompleteLruCache.get();
public errorsShown: Set<string> = new Set();
private bracketMatchingService = new BracketMatchingService();
@ -40,16 +47,54 @@ export class NextEditProvider {
private completionStreamer: CompletionStreamer;
private loggingService = new AutocompleteLoggingService();
private contextRetrievalService: ContextRetrievalService;
private endpointType: "default" | "fineTuned";
private diffContext: string = "";
constructor(
private constructor(
private readonly configHandler: ConfigHandler,
private readonly ide: IDE,
private readonly _injectedGetLlm: () => Promise<ILLM | undefined>,
private readonly _onError: (e: any) => void,
private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction,
endpointType: "default" | "fineTuned",
) {
this.completionStreamer = new CompletionStreamer(this.onError.bind(this));
this.contextRetrievalService = new ContextRetrievalService(this.ide);
this.endpointType = endpointType;
}
public static initialize(
configHandler: ConfigHandler,
ide: IDE,
injectedGetLlm: () => Promise<ILLM | undefined>,
onError: (e: any) => void,
getDefinitionsFromLsp: GetLspDefinitionsFunction,
endpointType: "default" | "fineTuned",
): NextEditProvider {
if (!NextEditProvider.instance) {
NextEditProvider.instance = new NextEditProvider(
configHandler,
ide,
injectedGetLlm,
onError,
getDefinitionsFromLsp,
endpointType,
);
}
return NextEditProvider.instance;
}
public static getInstance(): NextEditProvider {
if (!NextEditProvider.instance) {
throw new Error(
"NextEditProvider has not been initialized. Call initialize() first.",
);
}
return NextEditProvider.instance;
}
public addDiffToContext(diff: string): void {
this.diffContext = diff;
}
private async _prepareLlm(): Promise<ILLM | undefined> {
@ -174,7 +219,7 @@ export class NextEditProvider {
}
const [snippetPayload, workspaceDirs] = await Promise.all([
getAllSnippets({
getAllSnippetsWithoutRace({
helper,
ide: this.ide,
getDefinitionsFromLsp: this.getDefinitionsFromLsp,
@ -183,100 +228,241 @@ export class NextEditProvider {
this.ide.getWorkspaceDirs(),
]);
const { prompt, prefix, suffix, completionOptions } = renderPrompt({
snippetPayload,
workspaceDirs,
helper,
});
// TODO: Toggle between the default endpoint and the finetuned endpoint.
const prompts: Prompt[] = [];
// Completion
let completion: string | undefined = "";
const cache = await autocompleteCache;
const cachedCompletion = helper.options.useCache
? await cache.get(helper.prunedPrefix)
: undefined;
let cacheHit = false;
if (cachedCompletion) {
// Cache
cacheHit = true;
completion = cachedCompletion;
if (this.endpointType === "default") {
prompts.push(renderDefaultSystemPrompt());
prompts.push(renderDefaultUserPrompt(snippetPayload, helper));
} else {
const multiline =
!helper.options.transform || shouldCompleteMultiline(helper);
prompts.push(
// await renderFineTunedUserPrompt(snippetPayload, this.ide, helper),
// await renderFineTunedBasicUserPrompt(
// snippetPayload,
// this.ide,
// helper,
// this.diffContext,
// ),
renderPrompt(helper, this.diffContext),
);
}
const completionStream =
this.completionStreamer.streamCompletionWithFilters(
token,
llm,
prefix,
suffix,
prompt,
multiline,
completionOptions,
helper,
);
for await (const update of completionStream) {
completion += update;
}
// Don't postprocess if aborted
if (token.aborted) {
if (this.endpointType === "default") {
const msg: ChatMessage = await llm.chat(prompts, token);
if (typeof msg.content === "string") {
const nextCompletion = JSON.parse(msg.content).newCode;
const outcomeNext: AutocompleteOutcome = {
time: Date.now() - startTime,
completion: nextCompletion,
prefix: "",
suffix: "",
prompt: "",
modelProvider: llm.underlyingProviderName,
modelName: llm.model,
completionOptions: null,
cacheHit: false,
filepath: helper.filepath,
numLines: nextCompletion.split("\n").length,
completionId: helper.input.completionId,
gitRepo: await this.ide.getRepoName(helper.filepath),
uniqueId: await this.ide.getUniqueId(),
timestamp: Date.now(),
...helper.options,
};
return outcomeNext;
} else {
return undefined;
}
// const body = {
// model: defaultModel,
// messages: prompts,
// // max_tokens: 15000,
// // stop: ["<|editable_region_end|>"],
// };
//
// const resp = await fetch(defaultEndpoint, {
// method: "POST",
// headers: {
// Authorization: `Bearer ${mercuryToken} `,
// "Content-Type": "application/json",
// },
// body: JSON.stringify(body),
// });
//
// const respJson = await resp.json();
const processedCompletion = helper.options.transform
? postprocessCompletion({
completion,
prefix: helper.prunedPrefix,
suffix: helper.prunedSuffix,
llm,
})
: completion;
// TODO: Do some zod schema validation here if needed.
} else {
// const testController = new AbortController();
// const msg: ChatMessage = await llm.chat(prompts, testController.signal);
// const testToken = testController.signal;
const msg: ChatMessage = await llm.chat(prompts, token);
if (typeof msg.content === "string") {
// TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
const nextCompletion = replaceEscapedCharacters(
msg.content.split("<|editable_region_start|>\n")[1],
).replace(/\n$/, "");
completion = processedCompletion;
// const diffLines = myersDiff(helper.fileContents, nextCompletion);
// const diff = getRenderableDiff(diffLines);
const outcomeNext: AutocompleteOutcome = {
time: Date.now() - startTime,
completion: nextCompletion,
prefix: "",
suffix: "",
prompt: "",
modelProvider: llm.underlyingProviderName,
modelName: llm.model,
completionOptions: null,
cacheHit: false,
filepath: helper.filepath,
numLines: nextCompletion.split("\n").length,
completionId: helper.input.completionId,
gitRepo: await this.ide.getRepoName(helper.filepath),
uniqueId: await this.ide.getUniqueId(),
timestamp: Date.now(),
...helper.options,
};
return outcomeNext;
} else {
return undefined;
}
// const body = {
// model: fineTunedModel,
// messages: prompts,
// max_tokens: 15000,
// stop: ["<|editable_region_end|>"],
// };
//
// const resp = await fetch(fineTunedEndpoint, {
// method: "POST",
// headers: {
// Authorization: `Bearer ${mercuryToken} `,
// "Content-Type": "application/json",
// },
// body: JSON.stringify(body),
// });
//
// const respJson = await resp.json();
//
// const nextCompletion = respJson.choices[0].message.content
// .split("<|editable_region_start|>\n")[1]
// .split("<|editable_region_end|>")[0]
// .slice(1)
// .slice(0, -1)
// .replaceAll("\\n", "\n")
// .replaceAll('\\"', '"');
//
// const outcomeNext: AutocompleteOutcome = {
// time: Date.now() - startTime,
// completion: nextCompletion,
// prefix: "",
// suffix: "",
// prompt: "",
// modelProvider: llm.underlyingProviderName,
// modelName: llm.model,
// completionOptions: null,
// cacheHit: false,
// filepath: helper.filepath,
// numLines: nextCompletion.split("\n").length,
// completionId: helper.input.completionId,
// gitRepo: await this.ide.getRepoName(helper.filepath),
// uniqueId: await this.ide.getUniqueId(),
// timestamp: Date.now(),
// ...helper.options,
// };
// return outcomeNext;
}
if (!completion) {
return undefined;
}
// // Completion
// let completion: string | undefined = "";
const outcome: AutocompleteOutcome = {
time: Date.now() - startTime,
completion,
prefix,
suffix,
prompt,
modelProvider: llm.underlyingProviderName,
modelName: llm.model,
completionOptions,
cacheHit,
filepath: helper.filepath,
numLines: completion.split("\n").length,
completionId: helper.input.completionId,
gitRepo: await this.ide.getRepoName(helper.filepath),
uniqueId: await this.ide.getUniqueId(),
timestamp: Date.now(),
...helper.options,
};
// const cache = await autocompleteCache;
// const cachedCompletion = helper.options.useCache
// ? await cache.get(helper.prunedPrefix)
// : undefined;
// let cacheHit = false;
// if (cachedCompletion) {
// // Cache
// cacheHit = true;
// completion = cachedCompletion;
// } else {
// const multiline =
// !helper.options.transform || shouldCompleteMultiline(helper);
//////////
// const completionStream =
// this.completionStreamer.streamCompletionWithFilters(
// token,
// llm,
// prefix,
// suffix,
// prompt,
// multiline,
// completionOptions,
// helper,
// );
// Save to cache
if (!outcome.cacheHit && helper.options.useCache) {
(await this.autocompleteCache)
.put(outcome.prefix, outcome.completion)
.catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
}
// for await (const update of completionStream) {
// completion += update;
// }
// When using the JetBrains extension, Mark as displayed
const ideType = (await this.ide.getIdeInfo()).ideType;
if (ideType === "jetbrains") {
this.markDisplayed(input.completionId, outcome);
}
// // Don't postprocess if aborted
// if (token.aborted) {
// return undefined;
// }
return outcome;
// const processedCompletion = helper.options.transform
// ? postprocessCompletion({
// completion,
// prefix: helper.prunedPrefix,
// suffix: helper.prunedSuffix,
// llm,
// })
// : completion;
// completion = processedCompletion;
// }
// if (!completion) {
// return undefined;
// }
// const outcome: AutocompleteOutcome = {
// time: Date.now() - startTime,
// completion,
// prefix,
// suffix,
// prompt,
// modelProvider: llm.underlyingProviderName,
// modelName: llm.model,
// completionOptions,
// cacheHit,
// filepath: helper.filepath,
// numLines: completion.split("\n").length,
// completionId: helper.input.completionId,
// gitRepo: await this.ide.getRepoName(helper.filepath),
// uniqueId: await this.ide.getUniqueId(),
// timestamp: Date.now(),
// ...helper.options,
// };
// //////////
// // Save to cache
// if (!outcome.cacheHit && helper.options.useCache) {
// (await this.autocompleteCache)
// .put(outcome.prefix, outcome.completion)
// .catch((e) => console.warn(`Failed to save to cache: ${e.message}`));
// }
// // When using the JetBrains extension, Mark as displayed
// const ideType = (await this.ide.getIdeInfo()).ideType;
// if (ideType === "jetbrains") {
// this.markDisplayed(input.completionId, outcome);
// }
// return outcome;
} catch (e: any) {
this.onError(e);
} finally {

29
core/nextEdit/README.md Normal file
View file

@ -0,0 +1,29 @@
# Next Edit Prediction
## What is it?
## How is it different from autocomplete?
## Where are we right now?
- Users can decide to switch between autocomplete and next edit.
- Next edit triggers at the same time autocomplete is triggered, via vscode's inline completion provider.
- The following happens after the trigger:
- User's current cursor position is captured.
- We define an editable range, ±5 lines from the current cursor position.
- User's most recent edit is captured as a unified diff. (this is currently buggy)
- This is sent to the model, which returns a new editable range with next edit predictions.
- We display this new editable range in a SVG decoration.
- User can either tab to accept or esc to reject.
- On accept, the old editable range will be replaced by the new editable region. The cursor will be moved to the last line containing some change.
- On reject, nothing happens.
## What needs to be worked on?
- User edit captures.
- Find a better way to trigger next edit (this links back to the diff capture problem).
- We can see that next edit triggers as soon as the user accepts a change. This is because autocomplete runs the same way.
- I think autocomplete has some filter logic that doesn't display the ghost text under some conditions, which I am guessing are the following:
- The model does not have any more completions to create.
- The prediction at the cursor location has been cached.
- JetBrains integration.

View file

@ -1 +1,6 @@
export const IS_NEXT_EDIT_ACTIVE = false;
export const NEXT_EDIT_EDITABLE_REGION_TOP_MARGIN = 5;
export const NEXT_EDIT_EDITABLE_REGION_BOTTOM_MARGIN = 5;
export const USER_CURSOR_IS_HERE_TOKEN = "<|user_cursor_is_here|>";
export const EDITABLE_REGION_START_TOKEN = "<|editable_region_start|>";
export const EDITABLE_REGION_END_TOKEN = "<|editable_region_end|>";

View file

@ -0,0 +1,575 @@
import { Position, RangeInFileWithNextEditInfo } from "../..";
import {
BeforeAfterDiff,
DiffFormatType,
createBeforeAfterDiff,
createDiff,
} from "./diffFormatting";
interface ClusterState {
beforeState: string; // stores content of cluster before edit
startRange: { minLine: number; maxLine: number };
currentRange: { minLine: number; maxLine: number };
edits: RangeInFileWithNextEditInfo[]; // store small edits that form the cluster
firstTimestamp: number;
lastTimestamp: number;
lastLine: number;
firstEditBeforeCursor: { line: number; character: number }; // cursor position before the first edit in the cluster
lastEditAfterCursor: { line: number; character: number }; // cursor position after the last edit in the previous cluster
}
interface FileState {
activeClusters: ClusterState[]; // Stores active clusters for the file
currentContent: string; // Stores the current content of the file
priorComparisons: string[]; // Stores prior comparisons for the file (not currently used, but kept for future use)
processingQueue: Array<() => Promise<void>>; // Stores a queue of small edits to be processed into clusters
isProcessing: boolean;
}
export interface EditClusterConfig {
deltaT: number; // Time threshold in seconds; if exceeded, a new cluster is created
deltaL: number; // Line threshold; if the user jumps more than this many lines, a new cluster is created
maxEdits: number; // Maximum number of edits in a cluster
maxDuration: number; // Maximum total duration of an edit in seconds
contextSize: number; // Number of previous edits to store; not currently used but kept for future use
contextLines: number; // Used for computations involving deltaL
}
export class EditAggregator {
private fileStates: Map<string, FileState> = new Map();
public config: EditClusterConfig;
private previousEditFinalCursorPosition: Position;
private lastProcessedFilePath: string | null = null;
public onComparisonFinalized: (
diff: BeforeAfterDiff,
beforeCursorPos: Position,
afterPrevEditCursorPos: Position,
) => void;
private static _instance: EditAggregator | null = null;
public static getInstance(
config?: Partial<EditClusterConfig>,
onComparisonFinalized?: (
diff: BeforeAfterDiff,
beforeCursorPos: Position,
afterPrevEditCursorPos: Position,
) => void,
): EditAggregator {
// Create instance if it doesn't exist
if (!EditAggregator._instance) {
EditAggregator._instance = new EditAggregator(
config,
onComparisonFinalized,
);
}
// Update instance if new parameters are provided
else if (config || onComparisonFinalized) {
if (config) {
EditAggregator._instance.config = {
deltaT: config.deltaT ?? EditAggregator._instance.config.deltaT,
deltaL: config.deltaL ?? EditAggregator._instance.config.deltaL,
maxEdits: config.maxEdits ?? EditAggregator._instance.config.maxEdits,
maxDuration:
config.maxDuration ?? EditAggregator._instance.config.maxDuration,
contextSize:
config.contextSize ?? EditAggregator._instance.config.contextSize,
contextLines:
config.contextLines ?? EditAggregator._instance.config.contextLines,
};
}
if (onComparisonFinalized) {
EditAggregator._instance.onComparisonFinalized = onComparisonFinalized;
}
}
return EditAggregator._instance;
}
constructor(
config: Partial<EditClusterConfig> = {},
onComparisonFinalized: (
diff: BeforeAfterDiff,
beforeCursorPos: Position,
afterPrevEditCursorPos: Position,
) => void = () => {},
) {
this.config = {
deltaT: config.deltaT ?? 1.0,
deltaL: config.deltaL ?? 5,
maxEdits: config.maxEdits ?? 500,
maxDuration: config.maxDuration ?? 100.0,
contextSize: config.contextSize ?? 5,
contextLines: config.contextLines ?? 3,
};
this.onComparisonFinalized = onComparisonFinalized;
this.previousEditFinalCursorPosition = { line: 0, character: 0 };
}
async processEdit(
edit: RangeInFileWithNextEditInfo,
timestamp: number = Date.now(),
): Promise<void> {
const filePath = edit.filepath;
// If we're switching to a different file, finalize all clusters from the previous file
if (this.lastProcessedFilePath && this.lastProcessedFilePath !== filePath) {
await this.finalizeClustersForFile(this.lastProcessedFilePath);
}
// Update the last processed file path
this.lastProcessedFilePath = filePath;
if (!this.fileStates.has(filePath)) {
this.fileStates.set(filePath, {
activeClusters: [],
currentContent: edit.fileContents,
priorComparisons: [],
processingQueue: [],
isProcessing: false,
});
}
const fileState = this.fileStates.get(filePath)!;
const task = async () => {
await this._processEditInternal(edit, timestamp, fileState);
};
fileState.processingQueue.push(task);
if (!fileState.isProcessing) {
void this._processQueue(filePath);
}
}
private async _processQueue(filePath: string): Promise<void> {
const fileState = this.fileStates.get(filePath);
if (!fileState) return;
fileState.isProcessing = true;
// Process chunks of (5) edits instead of one at a time
while (fileState.processingQueue.length > 0) {
const tasks = fileState.processingQueue.splice(0, 5);
if (tasks.length > 0) {
try {
await Promise.all(tasks.map((task) => task()));
} catch (error) {
console.error(`Error processing edits in ${filePath}:`, error);
}
// Yield to the event loop to prevent blocking
await new Promise((resolve) => setTimeout(resolve, 0));
}
}
fileState.isProcessing = false;
}
private async _processEditInternal(
edit: RangeInFileWithNextEditInfo,
timestamp: number,
fileState: FileState,
): Promise<void> {
const filePath = edit.filepath;
const editLine = edit.range.start.line;
const currentFileLines = fileState.currentContent.split("\n");
const clustersToFinalize = this.identifyClustersToFinalize(
fileState,
edit,
timestamp,
false,
);
for (const cluster of clustersToFinalize) {
await this.finalizeCluster(filePath, cluster, fileState);
}
let suitableCluster = this.findSuitableCluster(
fileState,
editLine,
timestamp,
);
// Check if adding this edit would exceed deltaL lines for the cluster
if (suitableCluster) {
const potentialMinLine = Math.min(
suitableCluster.currentRange.minLine,
Math.max(0, editLine - this.config.contextLines),
);
const potentialMaxLine = Math.max(
suitableCluster.currentRange.maxLine,
Math.min(
currentFileLines.length - 1,
editLine + this.config.contextLines,
),
);
const potentialLineSpan = potentialMaxLine - potentialMinLine + 1;
if (potentialLineSpan > this.config.deltaL * 2) {
// Auto-finalize the current cluster before creating a new one
await this.finalizeCluster(filePath, suitableCluster, fileState);
suitableCluster = null;
}
}
// initialize a cluster
if (!suitableCluster) {
suitableCluster = {
beforeState: fileState.currentContent,
startRange: {
minLine: Math.max(0, editLine - this.config.contextLines),
maxLine: Math.min(
currentFileLines.length - 1,
editLine + this.config.contextLines,
),
},
currentRange: {
minLine: Math.max(0, editLine - this.config.contextLines),
maxLine: Math.min(
currentFileLines.length - 1,
editLine + this.config.contextLines,
),
},
edits: [],
firstTimestamp: timestamp,
lastTimestamp: timestamp,
lastLine: editLine,
firstEditBeforeCursor: edit.beforeCursorPos,
lastEditAfterCursor: edit.afterCursorPos,
};
fileState.activeClusters.push(suitableCluster);
}
suitableCluster.edits.push(edit);
suitableCluster.lastTimestamp = timestamp;
suitableCluster.lastLine = editLine;
suitableCluster.lastEditAfterCursor = edit.afterCursorPos;
const isWhitespaceOnly = this.isWhitespaceOnlyEdit(
edit,
fileState.currentContent,
);
if (!isWhitespaceOnly) {
suitableCluster.currentRange.minLine = Math.min(
suitableCluster.currentRange.minLine,
Math.max(0, editLine - this.config.contextLines),
);
suitableCluster.currentRange.maxLine = Math.max(
suitableCluster.currentRange.maxLine,
Math.min(
currentFileLines.length - 1,
editLine + this.config.contextLines,
),
);
}
fileState.currentContent = edit.fileContents;
const isStructuralEdit =
edit.editText.includes("\n") ||
edit.range.start.line !== edit.range.end.line;
if (isStructuralEdit) {
const additionalClustersToFinalize = fileState.activeClusters.filter(
(c) =>
c !== suitableCluster && this.clustersOverlap(c, suitableCluster),
);
for (const cluster of additionalClustersToFinalize) {
await this.finalizeCluster(filePath, cluster, fileState);
}
}
}
private isWhitespaceOnlyEdit(
edit: RangeInFileWithNextEditInfo,
currentContent: string,
): boolean {
const lines = currentContent.split("\n");
const line = edit.range.start.line;
if (line >= lines.length) return false;
if (edit.range.start.line === edit.range.end.line) {
const beforeEdit = lines[line];
const afterEdit =
beforeEdit.substring(0, edit.range.start.character) +
edit.editText +
beforeEdit.substring(edit.range.end.character);
return beforeEdit.trim() === afterEdit.trim();
}
return false;
}
private clustersOverlap(
cluster1: ClusterState,
cluster2: ClusterState,
): boolean {
return (
cluster1.currentRange.minLine <=
cluster2.currentRange.maxLine + this.config.deltaL &&
cluster1.currentRange.maxLine >=
cluster2.currentRange.minLine - this.config.deltaL
);
}
async processEdits(edits: RangeInFileWithNextEditInfo[]): Promise<void> {
const timestamp = Date.now();
// Only process the last edit during rapid typing
if (this.getProcessingQueueSize() > 50) {
if (edits.length > 0) {
await this.processEdit(edits[edits.length - 1], timestamp);
}
return;
}
for (const edit of edits) {
await this.processEdit(edit, timestamp);
}
}
/**
* Finalizes all clusters for a specific file
*/
private async finalizeClustersForFile(filePath: string): Promise<void> {
const fileState = this.fileStates.get(filePath);
if (!fileState) return;
// Create a copy of the clusters to finalize to avoid modifying array during iteration
const clustersToFinalize = [...fileState.activeClusters];
for (const cluster of clustersToFinalize) {
await this.finalizeCluster(filePath, cluster, fileState);
}
}
async finalizeAllClusters(): Promise<void> {
const filePromises: Promise<void>[] = [];
this.fileStates.forEach((fileState, filePath) => {
const filePromise = this.finalizeClustersForFile(filePath);
filePromises.push(filePromise);
});
await Promise.all(filePromises);
}
private findSuitableCluster(
fileState: FileState,
editLine: number,
timestamp: number,
): ClusterState | null {
const activeClusters = [...fileState.activeClusters];
for (const cluster of activeClusters) {
// If we're outside the line range but within the time window,
// we should finalize the current cluster
const isOutsideLineRange =
editLine < cluster.currentRange.minLine - this.config.deltaL ||
editLine > cluster.currentRange.maxLine + this.config.deltaL;
const isWithinTimeWindow =
(timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT;
// If user quickly jumped far away, finalize this cluster before continuing
if (isOutsideLineRange && isWithinTimeWindow) {
void this.finalizeCluster(
cluster.edits[0].filepath,
cluster,
fileState,
);
}
}
// Now look for a suitable cluster for the new edit
for (const cluster of fileState.activeClusters) {
const isOnSameLine = editLine === cluster.lastLine;
const isWithinTimeWindow =
(timestamp - cluster.lastTimestamp) / 1000 <= this.config.deltaT;
const isWithinLineRange =
editLine >= cluster.currentRange.minLine - this.config.deltaL &&
editLine <= cluster.currentRange.maxLine + this.config.deltaL;
const isWithinEditLimit = cluster.edits.length < this.config.maxEdits;
const isWithinDurationLimit =
(timestamp - cluster.firstTimestamp) / 1000 <= this.config.maxDuration;
if (
(isOnSameLine || (isWithinTimeWindow && isWithinLineRange)) &&
isWithinEditLimit &&
isWithinDurationLimit
) {
return cluster;
}
}
return null;
}
private identifyClustersToFinalize(
fileState: FileState,
edit: RangeInFileWithNextEditInfo,
timestamp: number,
isStructuralEdit: boolean,
): ClusterState[] {
const clustersToFinalize: ClusterState[] = [];
const editLine = edit.range.start.line;
fileState.activeClusters.forEach((cluster) => {
const timeSinceLastEdit = (timestamp - cluster.lastTimestamp) / 1000;
const isOnDifferentLineByNumber = cluster.lastLine !== editLine;
const isOnDifferentLineByNewline = edit.editText.includes("\n");
// Use different time thresholds for different types of line change detection
const shouldFinalizeByLineNumber =
isOnDifferentLineByNumber && timeSinceLastEdit > this.config.deltaT;
const shouldFinalizeByNewline =
isOnDifferentLineByNewline &&
timeSinceLastEdit > this.config.deltaT * 1.5;
// Finalize if we moved to a different line AND the time gap exceeds the respective threshold
const shouldFinalizeByTime =
shouldFinalizeByLineNumber || shouldFinalizeByNewline;
const shouldFinalizeByCount =
cluster.edits.length >= this.config.maxEdits;
const shouldFinalizeByDuration =
(timestamp - cluster.firstTimestamp) / 1000 > this.config.maxDuration;
// For structural edits, use the combined line detection
const isOnDifferentLine =
isOnDifferentLineByNumber || isOnDifferentLineByNewline;
const shouldFinalizeByStructuralEdit =
isStructuralEdit && isOnDifferentLine;
if (
shouldFinalizeByTime ||
shouldFinalizeByCount ||
shouldFinalizeByDuration ||
shouldFinalizeByStructuralEdit
) {
clustersToFinalize.push(cluster);
}
});
return clustersToFinalize;
}
private async finalizeCluster(
filePath: string,
cluster: ClusterState,
fileState: FileState,
): Promise<void> {
const beforeContent = cluster.beforeState;
const afterContent = fileState.currentContent;
// Skip whitespace-only diffs
const isWhitespaceOnlyDiff =
beforeContent.replace(/\s+/g, "") === afterContent.replace(/\s+/g, "");
if (isWhitespaceOnlyDiff) {
fileState.activeClusters = fileState.activeClusters.filter(
(c) => c !== cluster,
);
return;
}
const diff = createDiff(
beforeContent,
afterContent,
filePath,
DiffFormatType.Unified,
); // Used for checks, not for final output
// Skip diffs with too many changed lines
const changedLineCount = this.countChangedLines(diff);
if (changedLineCount > this.config.deltaL * 2) {
fileState.activeClusters = fileState.activeClusters.filter(
(c) => c !== cluster,
);
return;
}
fileState.priorComparisons.push(diff);
if (fileState.priorComparisons.length > this.config.contextSize) {
fileState.priorComparisons.shift();
}
fileState.activeClusters = fileState.activeClusters.filter(
(c) => c !== cluster,
);
// Give format-agnostic diff to the callback
const fullFileVersionsDiff = createBeforeAfterDiff(
beforeContent,
afterContent,
filePath,
);
// Store this cluster's final cursor position for future reference
this.previousEditFinalCursorPosition = cluster.lastEditAfterCursor;
this.onComparisonFinalized(
fullFileVersionsDiff,
cluster.firstEditBeforeCursor,
this.previousEditFinalCursorPosition,
);
}
private countChangedLines(diff: string): number {
let count = 0;
let addedLines = new Set<number>();
let removedLines = new Set<number>();
// Parse the diff lines
const lines = diff.split("\n");
for (const line of lines) {
if (
line.startsWith("+++ ") ||
line.startsWith("--- ") ||
line.startsWith("@@")
) {
continue; // Skip header lines
}
if (line.startsWith("+")) {
addedLines.add(count);
count++;
} else if (line.startsWith("-")) {
removedLines.add(count);
count++;
}
}
return Math.max(addedLines.size, removedLines.size);
}
getActiveClusterCount(): number {
let count = 0;
this.fileStates.forEach((fileState) => {
count += fileState.activeClusters.length;
});
return count;
}
getProcessingQueueSize(): number {
let count = 0;
this.fileStates.forEach((fileState) => {
count += fileState.processingQueue.length;
});
return count;
}
resetState(): void {
this.fileStates.clear();
this.lastProcessedFilePath = null;
}
}

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