merge main
This commit is contained in:
commit
a2879d13de
538 changed files with 67159 additions and 58352 deletions
79
.continue/prompts/update-llm-info.prompt
Normal file
79
.continue/prompts/update-llm-info.prompt
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
name: Update LLM Info
|
||||
description: Updates Gemini blocks with latest information
|
||||
version: 2
|
||||
---
|
||||
I need you to update this repo with the latest information about large language models from certain providers.
|
||||
The information is stored in the `packages/llm-info` directory, which operates as its own npm package.
|
||||
Information is stored in a simple JSON format, with one file of models per "provider" (e.g. gemini, ollama, openai, etc).
|
||||
For example, Gemini model information is stored in `packages/llm-info/src/providers/gemini.ts`.
|
||||
|
||||
To make these updates for a given provider, perform the following steps one at a time:
|
||||
|
||||
1. VIEW CURRENT INFORMATION
|
||||
|
||||
To view the current llm info, read the file (e.g. `packages/llm-info/src/providers/gemini.ts`) using the read_file tool.
|
||||
If you do not see a tool for reading files, let me know.
|
||||
|
||||
For reference, here is the LLMInfo interface used to store the information:
|
||||
|
||||
```typescript
|
||||
export interface LlmInfo {
|
||||
model: string; // the model name used to distinguish the model at the API layer, e.g. "gemini-2.5-pro-preview-05-06"
|
||||
displayName?: string; // A fitting display name, e.g. "Gemini 2.5 Pro Preview"
|
||||
description?: string; // A short description of the model, as similar as possible to descriptions found on the provider's website
|
||||
contextLength?: number; // The size of the context window in tokens, often called "max input tokens" or "context length"
|
||||
maxCompletionTokens?: number; // The maximum number of tokens the model can output
|
||||
regex?: RegExp; // A regex expression to uniquely match the model name if it had some slight modifications/upgrades, e.g. /gemini-2\.5-pro-preview/i
|
||||
mediaTypes?: MediaType[]; // Input/output types supported by the model, e.g. [MediaType.Text, MediaType.Image]
|
||||
}
|
||||
|
||||
export enum MediaType {
|
||||
Text = "text",
|
||||
Image = "image",
|
||||
Audio = "audio",
|
||||
Video = "video",
|
||||
}
|
||||
|
||||
export const AllMediaTypes = [
|
||||
MediaType.Text,
|
||||
MediaType.Image,
|
||||
MediaType.Audio,
|
||||
MediaType.Video,
|
||||
];
|
||||
```
|
||||
|
||||
2. EXTRACT NEW INFORMATION
|
||||
|
||||
Fetch information from the internet using the search web and read url tools.
|
||||
If you do not see either of these tools, stop and let me know.
|
||||
|
||||
Retrieve the following sites per these providers, and consider these notes on how to extract the information:
|
||||
- "gemini": https://ai.google.dev/gemini-api/docs/models - maxCompletionTokens is called "Output token limit", contextLength is called "Input token limit"
|
||||
// TODO: add info for openai, ollama, etc
|
||||
|
||||
For any other providers, search the web for "latest [provider] models" and find the most relevant model information using your best judgement.
|
||||
Generally, ignore models that do not support text output. These models will be used in a coding assistant client that only supports text/image input and text/output, so extraneous capabilities can be ignored.
|
||||
Sometimes, "Experimental", "Preview", or similar versions of models are available. The latest-date version of each should have its own information maintained.
|
||||
|
||||
3. UPDATE THE INFORMATION
|
||||
|
||||
Use the edit file tool to submit updates to the relevant provider file (e.g. `packages/llm-info/src/providers/gemini.ts`).
|
||||
Let me know if you do not see a tool for editing files.
|
||||
|
||||
Generally, avoid making changes to existing information, as it is probably up to date.
|
||||
Primarily, focus on adding new models or adding missing information to existing models.
|
||||
NEVER delete any existing models, but let me know if you think one should be removed.
|
||||
Stop to ask me if you are unsure about any changes, and let me know if there are updates that seem nuanced, complex, or extremely notable.
|
||||
Provide a summary of changes after the fact.
|
||||
|
||||
4. ASK IF I WANT TO PUBLISH TO NPM
|
||||
After you are done updating everything, remind me that I need to publish the changes to npm.
|
||||
|
||||
// TODO too sensitive for now
|
||||
// If yes, update `packages/llm-info/package.json` with the new version number and then
|
||||
// - use the terminal tool to commit the changes
|
||||
// - use the terminal tool to publish changes to npm
|
||||
// If you do not see a tool for running terminal commands, let me know.
|
||||
|
||||
// User input
|
||||
Please update LLM Info for the following providers. If "all", update all providers mentioned above:
|
||||
13
.continue/rules/bigger-picture-description-rules.yaml
Normal file
13
.continue/rules/bigger-picture-description-rules.yaml
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
name: bigger-picture-description-rules
|
||||
version: 0.0.1
|
||||
schema: v1
|
||||
rules:
|
||||
- name: bigger-picture-description-rules
|
||||
rule: >-
|
||||
When a user asks how a certain part of the code works:
|
||||
|
||||
1. Describe what the code does in isolation.
|
||||
|
||||
2. If the code interacts with other parts of the codebase, describe how the code is imported and used in other parts of the codebase.
|
||||
|
||||
3. When describing each use-case, include the parent function for clarity.
|
||||
9
.continue/rules/continue-specificity.md
Normal file
9
.continue/rules/continue-specificity.md
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
---
|
||||
globs: /**/*.
|
||||
description: General questions about code completion should be answered specific to Continue
|
||||
---
|
||||
|
||||
# Continue Specificity
|
||||
|
||||
- In chat mode, if the user asks generally about code completion or developer tools, answer specifically regarding Continue and not other similar software.
|
||||
- Keep all suggestions and comments concentrated on Continue, unless the user asks otherwise. If the user does this, answer with no particular specificity to Continue.
|
||||
|
|
@ -13,4 +13,4 @@ description: Standards for writing and maintaining Continue Docs
|
|||
- Include cross-references to related documentation
|
||||
- Reference other docs with relative paths
|
||||
- Keep paragraphs concise and scannable
|
||||
- Use code blocks with appropriate language tags
|
||||
- Use code blocks with appropriate language tags
|
||||
|
|
|
|||
10
.continue/rules/gui-link-opening.md
Normal file
10
.continue/rules/gui-link-opening.md
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
---
|
||||
globs: gui/**/*
|
||||
description: Ensures consistent URL opening behavior in GUI components using the
|
||||
IDE messenger pattern
|
||||
alwaysApply: false
|
||||
---
|
||||
|
||||
# GUI Link Opening
|
||||
|
||||
When adding functionality to open external links in GUI components, use `ideMessenger.post("openUrl", url)` where `ideMessenger` is obtained from `useContext(IdeMessengerContext)`
|
||||
11
.continue/rules/llm-specificity.md
Normal file
11
.continue/rules/llm-specificity.md
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
---
|
||||
globs: core/llm/llms/**/*.{ts,test.ts}
|
||||
description: Tailor recommendations for LLM code based on which specific LLM is being used.
|
||||
---
|
||||
|
||||
# LLM Model Specificity
|
||||
|
||||
- Refer to the file name and names of big classes to determine which LLM is being used in a file.
|
||||
- Ground all observations and recommendations with knowledge of that LLM.
|
||||
- Consider items such as context length, architecture, speed, and such.
|
||||
- Pay attention to the parent classes in these files.
|
||||
|
|
@ -6,9 +6,11 @@
|
|||
},
|
||||
"plugins": ["@typescript-eslint", "import"],
|
||||
"rules": {
|
||||
"no-negated-condition": "warn",
|
||||
"@typescript-eslint/naming-convention": "off",
|
||||
"@typescript-eslint/no-floating-promises": "warn",
|
||||
"@typescript-eslint/semi": "warn",
|
||||
"@typescript-eslint/no-misused-promises": "error",
|
||||
"curly": "warn",
|
||||
"eqeqeq": "warn",
|
||||
"no-throw-literal": "warn",
|
||||
|
|
|
|||
22
.github/workflows/pr_checks.yaml
vendored
22
.github/workflows/pr_checks.yaml
vendored
|
|
@ -30,6 +30,24 @@ jobs:
|
|||
if: steps.root-cache.outputs.cache-hit != 'true'
|
||||
run: npm ci
|
||||
|
||||
prettier-check:
|
||||
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') }}
|
||||
|
||||
- name: Check code formatting with Prettier
|
||||
run: npx prettier --check "**/*.{js,jsx,ts,tsx,json,css,md}" --ignore-path .gitignore --ignore-path .prettierignore
|
||||
|
||||
install-config-yaml:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
|
|
@ -408,6 +426,7 @@ jobs:
|
|||
run: |
|
||||
cd core
|
||||
npm test
|
||||
npm run vitest
|
||||
env:
|
||||
IGNORE_API_KEY_TESTS: ${{ github.event.pull_request.head.repo.fork == true || github.actor == 'dependabot[bot]' }}
|
||||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
|
|
@ -416,6 +435,8 @@ jobs:
|
|||
MISTRAL_API_KEY: ${{ secrets.MISTRAL_API_KEY }}
|
||||
AZURE_OPENAI_API_KEY: ${{ secrets.AZURE_OPENAI_API_KEY }}
|
||||
AZURE_FOUNDRY_API_KEY: ${{ secrets.AZURE_FOUNDRY_API_KEY }}
|
||||
AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY: ${{ secrets.AZURE_FOUNDRY_MISTRAL_SMALL_API_KEY }}
|
||||
AZURE_OPENAI_GPT41_API_KEY: ${{ secrets.AZURE_OPENAI_GPT41_API_KEY }}
|
||||
|
||||
package-tests:
|
||||
runs-on: ubuntu-latest
|
||||
|
|
@ -859,6 +880,7 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
needs:
|
||||
- install-root
|
||||
- prettier-check
|
||||
- install-core
|
||||
- core-checks
|
||||
- install-gui
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ name: Submit Gradle Dependency Graph For Dependabot
|
|||
|
||||
on:
|
||||
push:
|
||||
branches: ['main']
|
||||
branches: ["main"]
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
|
@ -11,15 +11,15 @@ jobs:
|
|||
dependency-submission:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: 'temurin'
|
||||
java-version: 17
|
||||
- name: Generate and submit dependency graph
|
||||
uses: gradle/actions/dependency-submission@v4
|
||||
with:
|
||||
# The gradle project is not in the root of the repository.
|
||||
build-root-directory: extensions/intellij
|
||||
- name: Checkout sources
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: "temurin"
|
||||
java-version: 17
|
||||
- name: Generate and submit dependency graph
|
||||
uses: gradle/actions/dependency-submission@v4
|
||||
with:
|
||||
# The gradle project is not in the root of the repository.
|
||||
build-root-directory: extensions/intellij
|
||||
|
|
|
|||
2
.gitignore
vendored
2
.gitignore
vendored
|
|
@ -144,7 +144,9 @@ Icon?
|
|||
.continuerc.json
|
||||
.aider*
|
||||
|
||||
*.notes.md
|
||||
notes.md
|
||||
*.notes.md
|
||||
|
||||
manual-testing-sandbox/.idea/**
|
||||
manual-testing-sandbox/.continue/**
|
||||
|
|
|
|||
|
|
@ -15,4 +15,11 @@ gui/dist
|
|||
CHANGELOG.md
|
||||
**/continue_tutorial.py
|
||||
**/node_modules
|
||||
**/CODEOWNERS
|
||||
**/CODEOWNERS
|
||||
core/vendor
|
||||
coverage
|
||||
e2e
|
||||
extensions/vscode/gui
|
||||
extensions/vscode/models
|
||||
extensions/intellij/src/main/resources
|
||||
packages/continue-sdk
|
||||
|
|
@ -14,21 +14,21 @@ religion, or sexual identity and orientation.
|
|||
Examples of behavior that contributes to creating a positive environment
|
||||
include:
|
||||
|
||||
* Using welcoming and inclusive language
|
||||
* Being respectful of differing viewpoints and experiences
|
||||
* Gracefully accepting constructive criticism
|
||||
* Focusing on what is best for the community
|
||||
* Showing empathy towards other community members
|
||||
- Using welcoming and inclusive language
|
||||
- Being respectful of differing viewpoints and experiences
|
||||
- Gracefully accepting constructive criticism
|
||||
- Focusing on what is best for the community
|
||||
- Showing empathy towards other community members
|
||||
|
||||
Examples of unacceptable behavior by participants include:
|
||||
|
||||
* The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
- The use of sexualized language or imagery and unwelcome sexual attention or
|
||||
advances
|
||||
* Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
* Public or private harassment
|
||||
* Publishing others' private information, such as a physical or electronic
|
||||
- Trolling, insulting/derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information, such as a physical or electronic
|
||||
address, without explicit permission
|
||||
* Other conduct which could reasonably be considered inappropriate in a
|
||||
- Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Our Responsibilities
|
||||
|
|
|
|||
|
|
@ -123,6 +123,12 @@ version of Node.js for this project by running the following command in the root
|
|||
nvm use
|
||||
```
|
||||
|
||||
Then, install Vite globally
|
||||
|
||||
```bash
|
||||
npm i -g vite
|
||||
```
|
||||
|
||||
#### Fork the Continue Repository
|
||||
|
||||
1. Go to the [Continue GitHub repository](https://github.com/continuedev/continue) and fork it to your GitHub account.
|
||||
|
|
|
|||
|
|
@ -58,7 +58,6 @@ file
|
|||
|
||||

|
||||
|
||||
|
||||
</div>
|
||||
|
||||
## Getting Started
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
const path = require('path');
|
||||
const path = require("path");
|
||||
process.env.CONTINUE_DEVELOPMENT = true;
|
||||
|
||||
process.env.CONTINUE_GLOBAL_DIR = path.join(process.env.PROJECT_DIR, 'extensions', '.continue-debug');
|
||||
process.env.CONTINUE_GLOBAL_DIR = path.join(
|
||||
process.env.PROJECT_DIR,
|
||||
"extensions",
|
||||
".continue-debug",
|
||||
);
|
||||
|
||||
require('./out/index.js');
|
||||
require("./out/index.js");
|
||||
|
|
|
|||
5
binary/package-lock.json
generated
5
binary/package-lock.json
generated
|
|
@ -52,7 +52,7 @@
|
|||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.10",
|
||||
"@continuedev/fetch": "^1.0.13",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.25",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
|
|
@ -144,7 +144,8 @@
|
|||
"onnxruntime-common": "1.14.0",
|
||||
"onnxruntime-web": "1.14.0",
|
||||
"ts-jest": "^29.1.1",
|
||||
"typescript": "^5.6.3"
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^3.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20.19.0"
|
||||
|
|
|
|||
|
|
@ -1,7 +1,13 @@
|
|||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const logDirPath = path.join(__dirname, '..', 'extensions', '.continue-debug', 'logs');
|
||||
const logDirPath = path.join(
|
||||
__dirname,
|
||||
"..",
|
||||
"extensions",
|
||||
".continue-debug",
|
||||
"logs",
|
||||
);
|
||||
const logFilePath = path.join(logDirPath, "prompt.log");
|
||||
|
||||
// Ensure the log directory exists
|
||||
|
|
@ -12,7 +18,7 @@ if (!fs.existsSync(logDirPath)) {
|
|||
|
||||
// Create the log file if it doesn't exist
|
||||
if (!fs.existsSync(logFilePath)) {
|
||||
fs.writeFileSync(logFilePath, ''); // Create an empty file synchronously
|
||||
fs.writeFileSync(logFilePath, ""); // Create an empty file synchronously
|
||||
console.log("Created empty log file at " + logFilePath);
|
||||
}
|
||||
|
||||
|
|
@ -25,14 +31,16 @@ try {
|
|||
// console.clear();
|
||||
const stream = fs.createReadStream(logFilePath);
|
||||
stream.pipe(process.stdout);
|
||||
stream.on('error', (err) => {
|
||||
console.error('Error reading log file:', err.message);
|
||||
stream.on("error", (err) => {
|
||||
console.error("Error reading log file:", err.message);
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error while handling file change:', err.message);
|
||||
console.error("Error while handling file change:", err.message);
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error setting up file watcher:', err.message);
|
||||
console.log('You may need to restart the script after the extension generates the first log entry.');
|
||||
}
|
||||
console.error("Error setting up file watcher:", err.message);
|
||||
console.log(
|
||||
"You may need to restart the script after the extension generates the first log entry.",
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -39,4 +39,4 @@ module.exports = {
|
|||
TARGET_TO_RIPGREP_RELEASE,
|
||||
TARGET_TO_LANCEDB,
|
||||
RIPGREP_VERSION,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
16
core/__mocks__/@continuedev/fetch/index.ts
Normal file
16
core/__mocks__/@continuedev/fetch/index.ts
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
import { vi } from "vitest";
|
||||
|
||||
export const fetchwithRequestOptions = vi.fn(
|
||||
async (url, options, requestOptions) => {
|
||||
console.log("Mocked fetch called with:", url, options, requestOptions);
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: "OK",
|
||||
};
|
||||
},
|
||||
);
|
||||
|
||||
export const streamSse = vi.fn(function* () {
|
||||
yield "";
|
||||
});
|
||||
|
|
@ -1,5 +1,4 @@
|
|||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import { TRIAL_FIM_MODEL } from "../config/onboarding.js";
|
||||
import { IDE, ILLM } from "../index.js";
|
||||
import OpenAI from "../llm/llms/OpenAI.js";
|
||||
import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js";
|
||||
|
|
@ -75,11 +74,6 @@ export class CompletionProvider {
|
|||
|
||||
if (llm instanceof OpenAI) {
|
||||
llm.useLegacyCompletionsEndpoint = true;
|
||||
} else if (
|
||||
llm.providerName === "free-trial" &&
|
||||
llm.model !== TRIAL_FIM_MODEL
|
||||
) {
|
||||
llm.model = TRIAL_FIM_MODEL;
|
||||
}
|
||||
|
||||
return llm;
|
||||
|
|
@ -120,11 +114,12 @@ export class CompletionProvider {
|
|||
this.loggingService.markDisplayed(completionId, outcome);
|
||||
}
|
||||
|
||||
private async _getAutocompleteOptions() {
|
||||
private async _getAutocompleteOptions(llm: ILLM) {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
const options = {
|
||||
...DEFAULT_AUTOCOMPLETE_OPTS,
|
||||
...config?.tabAutocompleteOptions,
|
||||
...llm.autocompleteOptions,
|
||||
};
|
||||
return options;
|
||||
}
|
||||
|
|
@ -132,6 +127,7 @@ export class CompletionProvider {
|
|||
public async provideInlineCompletionItems(
|
||||
input: AutocompleteInput,
|
||||
token: AbortSignal | undefined,
|
||||
force?: boolean,
|
||||
): Promise<AutocompleteOutcome | undefined> {
|
||||
try {
|
||||
// Create abort signal if not given
|
||||
|
|
@ -142,18 +138,23 @@ export class CompletionProvider {
|
|||
token = controller.signal;
|
||||
}
|
||||
const startTime = Date.now();
|
||||
const options = await this._getAutocompleteOptions();
|
||||
|
||||
// Debounce
|
||||
if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const llm = await this._prepareLlm();
|
||||
if (!llm) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const options = await this._getAutocompleteOptions(llm);
|
||||
|
||||
// Debounce
|
||||
if (!force) {
|
||||
if (
|
||||
await this.debouncer.delayAndShouldDebounce(options.debounceDelay)
|
||||
) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
if (llm.promptTemplates?.autocomplete) {
|
||||
options.template = llm.promptTemplates.autocomplete as string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ export async function testRootPathContext(
|
|||
// @ts-ignore
|
||||
.spyOn(service, "getSnippets")
|
||||
// @ts-ignore
|
||||
.mockImplementation(async (_filepath, _endPosition) => {
|
||||
.mockImplementation((_filePath, _endPosition) => {
|
||||
return [];
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -74,7 +74,6 @@ export class StreamTransformPipeline {
|
|||
|
||||
const timeoutValue = helper.options.modelTimeout;
|
||||
|
||||
|
||||
lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, timeoutValue!);
|
||||
|
||||
const finalGenerator = streamWithNewLines(lineGenerator);
|
||||
|
|
|
|||
|
|
@ -215,21 +215,47 @@ describe("lineStream", () => {
|
|||
});
|
||||
|
||||
it("should handle unfenced code with a code block", async () => {
|
||||
const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```"]);
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle unfenced code with two code blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","```bash","ls -al","```"]);
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should remove lines before the first valid line", async () => {
|
||||
|
|
@ -242,7 +268,11 @@ describe("lineStream", () => {
|
|||
});
|
||||
|
||||
it("should remove outer blocks", async () => {
|
||||
const linesGenerator = await getLineGenerator(["```ts", "const x = 5;","```"]);
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```ts",
|
||||
"const x = 5;",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
|
@ -251,48 +281,119 @@ describe("lineStream", () => {
|
|||
});
|
||||
|
||||
it("should leave inner blocks intact", async () => {
|
||||
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```"]);
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should handle included inner ticks", async () => {
|
||||
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","echo ```test```","```","```"]);
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"echo ```test```",
|
||||
"```",
|
||||
"```",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;","```bash","echo ```test```","```"]);
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"echo ```test```",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should leave single inner blocks intact but not return trailing text", async () => {
|
||||
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","```","trailing text"]);
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"```",
|
||||
"trailing text",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should leave double inner blocks intact but not return trailing text", async () => {
|
||||
const linesGenerator = await getLineGenerator(["```md", "const x = 5;", "```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```","```","trailing text"]);
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"```md",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"const y = 10;",
|
||||
"```sh",
|
||||
"echo `hello world`",
|
||||
"```",
|
||||
"```",
|
||||
"trailing text",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```","const y = 10;","```sh","echo `hello world`","```"]);
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"const y = 10;",
|
||||
"```sh",
|
||||
"echo `hello world`",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
|
||||
it("should leave inner blocks intact but not return trailing or leading text", async () => {
|
||||
const linesGenerator = await getLineGenerator(["[CODE]", "const x = 5;", "```bash","ls -al","```","[/CODE]","trailing text"]);
|
||||
const linesGenerator = await getLineGenerator([
|
||||
"[CODE]",
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
"[/CODE]",
|
||||
"trailing text",
|
||||
]);
|
||||
|
||||
const result = lineStream.filterCodeBlockLines(linesGenerator);
|
||||
const filteredLines = await getFilteredLines(result);
|
||||
|
||||
expect(filteredLines).toEqual(["const x = 5;","```bash","ls -al","```"]);
|
||||
expect(filteredLines).toEqual([
|
||||
"const x = 5;",
|
||||
"```bash",
|
||||
"ls -al",
|
||||
"```",
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -350,12 +350,10 @@ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
|
|||
let nestCount = 0;
|
||||
|
||||
for await (const line of rawLines) {
|
||||
|
||||
|
||||
if (!seenFirstFence) {
|
||||
if (shouldRemoveLineBeforeStart(line)) {
|
||||
// Filter out starting ``` or START block
|
||||
continue
|
||||
continue;
|
||||
}
|
||||
// Regardless of a fence or START block start tracking the nesting level
|
||||
seenFirstFence = true;
|
||||
|
|
|
|||
|
|
@ -14,7 +14,11 @@ export class GeneratorReuseManager {
|
|||
) {
|
||||
this.currentGenerator?.cancel();
|
||||
|
||||
const listenableGen = new ListenableGenerator(gen, this.onError, abortController);
|
||||
const listenableGen = new ListenableGenerator(
|
||||
gen,
|
||||
this.onError,
|
||||
abortController,
|
||||
);
|
||||
listenableGen.listen((chunk) => (this.pendingCompletion += chunk ?? ""));
|
||||
|
||||
this.pendingGeneratorPrefix = prefix;
|
||||
|
|
@ -43,7 +47,11 @@ export class GeneratorReuseManager {
|
|||
if (!this.shouldReuseExistingGenerator(prefix)) {
|
||||
// Create a wrapper over the current generator to fix the prompt
|
||||
const abortController = new AbortController();
|
||||
this._createListenableGenerator(abortController, newGenerator(abortController.signal), prefix);
|
||||
this._createListenableGenerator(
|
||||
abortController,
|
||||
newGenerator(abortController.signal),
|
||||
prefix,
|
||||
);
|
||||
}
|
||||
|
||||
// Already typed characters are those that are new in the prefix from the old generator
|
||||
|
|
|
|||
|
|
@ -1,6 +1,10 @@
|
|||
import ignore from "ignore";
|
||||
|
||||
import { IDE } from "../..";
|
||||
import {
|
||||
getGlobalContinueIgArray,
|
||||
getWorkspaceContinueIgArray,
|
||||
} from "../../indexing/ignore";
|
||||
import { getConfigJsonPath } from "../../util/paths";
|
||||
import { findUriInDirs } from "../../util/uri";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
|
@ -50,7 +54,12 @@ export async function shouldPrefilter(
|
|||
}
|
||||
|
||||
// Check whether autocomplete is disabled for this file
|
||||
const disableInFiles = [...(helper.options.disableInFiles ?? []), "*.prompt"];
|
||||
const disableInFiles = [
|
||||
...(helper.options.disableInFiles ?? []),
|
||||
"*.prompt",
|
||||
...getGlobalContinueIgArray(),
|
||||
...(await getWorkspaceContinueIgArray(ide)),
|
||||
];
|
||||
if (await isDisabledForFile(helper.filepath, disableInFiles, ide)) {
|
||||
return true;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import { IDE, IdeInfo } from "../../index";
|
||||
import { IDE } from "../../index";
|
||||
import { findUriInDirs } from "../../util/uri";
|
||||
import { ContextRetrievalService } from "../context/ContextRetrievalService";
|
||||
import { GetLspDefinitionsFunction } from "../types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
import { openedFilesLruCache } from "../util/openedFilesLruCache";
|
||||
import { getDiffsFromCache } from "./gitDiffCache";
|
||||
|
||||
import {
|
||||
AutocompleteClipboardSnippet,
|
||||
|
|
@ -21,37 +23,17 @@ export interface SnippetPayload {
|
|||
recentlyVisitedRangesSnippets: AutocompleteCodeSnippet[];
|
||||
diffSnippets: AutocompleteDiffSnippet[];
|
||||
clipboardSnippets: AutocompleteClipboardSnippet[];
|
||||
recentlyOpenedFileSnippets: AutocompleteCodeSnippet[];
|
||||
}
|
||||
|
||||
function racePromise<T>(promise: Promise<T[]>): Promise<T[]> {
|
||||
function racePromise<T>(promise: Promise<T[]>, timeout = 100): Promise<T[]> {
|
||||
const timeoutPromise = new Promise<T[]>((resolve) => {
|
||||
setTimeout(() => resolve([]), 100);
|
||||
setTimeout(() => resolve([]), timeout);
|
||||
});
|
||||
|
||||
return Promise.race([promise, timeoutPromise]);
|
||||
}
|
||||
|
||||
class DiffSnippetsCache {
|
||||
private cache: Map<number, any> = new Map();
|
||||
private lastTimestamp: number = 0;
|
||||
|
||||
public set<T>(timestamp: number, value: T): T {
|
||||
// Clear old cache entry if exists
|
||||
if (this.lastTimestamp !== timestamp) {
|
||||
this.cache.clear();
|
||||
}
|
||||
this.lastTimestamp = timestamp;
|
||||
this.cache.set(timestamp, value);
|
||||
return value;
|
||||
}
|
||||
|
||||
public get(timestamp: number): any | undefined {
|
||||
return this.cache.get(timestamp);
|
||||
}
|
||||
}
|
||||
|
||||
const diffSnippetsCache = new DiffSnippetsCache();
|
||||
|
||||
// Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems,
|
||||
// or they might separately track recently edited ranges)
|
||||
async function getIdeSnippets(
|
||||
|
|
@ -112,43 +94,74 @@ const getClipboardSnippets = async (
|
|||
|
||||
const getDiffSnippets = async (
|
||||
ide: IDE,
|
||||
ideInfo: IdeInfo | undefined,
|
||||
): Promise<AutocompleteDiffSnippet[]> => {
|
||||
if (ideInfo?.ideType !== "vscode") {
|
||||
// Disabling for non-vscode IDEs for now
|
||||
// See https://github.com/continuedev/continue/issues/4130
|
||||
// https://github.com/continuedev/continue/issues/5819
|
||||
const diffs = await getDiffsFromCache(ide);
|
||||
|
||||
return diffs.map((item) => {
|
||||
return {
|
||||
content: item,
|
||||
type: AutocompleteSnippetType.Diff,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const getSnippetsFromRecentlyOpenedFiles = async (
|
||||
helper: HelperVars,
|
||||
ide: IDE,
|
||||
): Promise<AutocompleteCodeSnippet[]> => {
|
||||
if (helper.options.useRecentlyOpened === false) {
|
||||
return [];
|
||||
}
|
||||
const currentTimestamp = ide.getLastFileSaveTimestamp
|
||||
? ide.getLastFileSaveTimestamp()
|
||||
: Math.floor(Date.now() / 10000) * 10000; // Defaults to update once in every 10 seconds
|
||||
|
||||
// Check cache first
|
||||
const cached = diffSnippetsCache.get(
|
||||
currentTimestamp,
|
||||
) as AutocompleteDiffSnippet[];
|
||||
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
let diff: string[] = [];
|
||||
try {
|
||||
diff = await ide.getDiff(true);
|
||||
} catch (e) {
|
||||
console.error("Error getting diff for autocomplete", e);
|
||||
}
|
||||
const currentFileUri = `${helper.filepath}`;
|
||||
|
||||
return diffSnippetsCache.set(
|
||||
currentTimestamp,
|
||||
diff.map((item) => {
|
||||
return {
|
||||
content: item,
|
||||
type: AutocompleteSnippetType.Diff,
|
||||
};
|
||||
}),
|
||||
);
|
||||
// Get all file URIs excluding the current file
|
||||
const fileUrisToRead = [...openedFilesLruCache.entriesDescending()]
|
||||
.filter(([fileUri, _]) => fileUri !== currentFileUri)
|
||||
.map(([fileUri, _]) => fileUri);
|
||||
|
||||
// Create an array of promises that each read a file with timeout
|
||||
const fileReadPromises = fileUrisToRead.map((fileUri) => {
|
||||
// Create a promise that resolves to a snippet or null
|
||||
const readPromise = new Promise<AutocompleteCodeSnippet | null>(
|
||||
(resolve) => {
|
||||
ide
|
||||
.readFile(fileUri)
|
||||
.then((fileContent) => {
|
||||
if (!fileContent || fileContent.trim() === "") {
|
||||
resolve(null);
|
||||
return;
|
||||
}
|
||||
|
||||
resolve({
|
||||
filepath: fileUri,
|
||||
content: fileContent,
|
||||
type: AutocompleteSnippetType.Code,
|
||||
});
|
||||
})
|
||||
.catch((e) => {
|
||||
console.error(`Failed to read file ${fileUri}:`, e);
|
||||
resolve(null);
|
||||
});
|
||||
},
|
||||
);
|
||||
// Cut off at 80ms via racing promises
|
||||
return Promise.race([
|
||||
readPromise,
|
||||
new Promise<null>((resolve) => setTimeout(() => resolve(null), 80)),
|
||||
]);
|
||||
});
|
||||
|
||||
// Execute all file reads in parallel
|
||||
const results = await Promise.all(fileReadPromises);
|
||||
|
||||
// Filter out null results
|
||||
return results.filter(Boolean) as AutocompleteCodeSnippet[];
|
||||
} catch (e) {
|
||||
console.error("Error processing opened files cache:", e);
|
||||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
export const getAllSnippets = async ({
|
||||
|
|
@ -171,6 +184,7 @@ export const getAllSnippets = async ({
|
|||
ideSnippets,
|
||||
diffSnippets,
|
||||
clipboardSnippets,
|
||||
recentlyOpenedFileSnippets,
|
||||
] = await Promise.all([
|
||||
racePromise(contextRetrievalService.getRootPathSnippets(helper)),
|
||||
racePromise(
|
||||
|
|
@ -179,8 +193,9 @@ export const getAllSnippets = async ({
|
|||
IDE_SNIPPETS_ENABLED
|
||||
? racePromise(getIdeSnippets(helper, ide, getDefinitionsFromLsp))
|
||||
: [],
|
||||
racePromise(getDiffSnippets(ide, helper.ideInfo)),
|
||||
[], // racePromise(getDiffSnippets(ide)) // temporarily disabled, see https://github.com/continuedev/continue/pull/5882,
|
||||
racePromise(getClipboardSnippets(ide)),
|
||||
racePromise(getSnippetsFromRecentlyOpenedFiles(helper, ide)), // giving this one a little more time to complete
|
||||
]);
|
||||
|
||||
return {
|
||||
|
|
@ -191,5 +206,6 @@ export const getAllSnippets = async ({
|
|||
diffSnippets,
|
||||
clipboardSnippets,
|
||||
recentlyVisitedRangesSnippets: helper.input.recentlyVisitedRanges,
|
||||
recentlyOpenedFileSnippets,
|
||||
};
|
||||
};
|
||||
|
|
|
|||
84
core/autocomplete/snippets/gitDiffCache.test.ts
Normal file
84
core/autocomplete/snippets/gitDiffCache.test.ts
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import { GitDiffCache } from "./gitDiffCache";
|
||||
|
||||
beforeEach(() => {
|
||||
// Add this line to GitDiffCache class to make instance accessible
|
||||
(GitDiffCache as any).instance = null;
|
||||
});
|
||||
|
||||
test("GitDiffCache returns cached results within cache time", async () => {
|
||||
const mockDiff = ["file1.ts", "file2.ts"];
|
||||
const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
|
||||
const cache = GitDiffCache.getInstance(getDiffFn, 1); // 1 second cache
|
||||
|
||||
const result1 = await cache.get();
|
||||
const result2 = await cache.get();
|
||||
|
||||
expect(result1).toEqual(mockDiff);
|
||||
expect(result2).toEqual(mockDiff);
|
||||
expect(getDiffFn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("GitDiffCache refreshes cache after expiration", async () => {
|
||||
const mockDiff = ["file1.ts"];
|
||||
const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
|
||||
const cache = GitDiffCache.getInstance(getDiffFn, 0.1); // 100ms cache
|
||||
|
||||
const result1 = await cache.get();
|
||||
await new Promise((resolve) => setTimeout(resolve, 200)); // Wait for cache to expire
|
||||
const result2 = await cache.get();
|
||||
|
||||
expect(getDiffFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("GitDiffCache returns empty array on error", async () => {
|
||||
const getDiffFn = jest.fn().mockRejectedValue(new Error("Git error"));
|
||||
const cache = GitDiffCache.getInstance(getDiffFn);
|
||||
|
||||
const result = await cache.get();
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
test("GitDiffCache reuses pending request", async () => {
|
||||
const mockDiff = ["file1.ts"];
|
||||
let resolvePromise: (value: string[]) => void;
|
||||
const getDiffFn = jest.fn().mockImplementation(() => {
|
||||
return new Promise((resolve) => {
|
||||
resolvePromise = resolve;
|
||||
});
|
||||
});
|
||||
|
||||
const cache = GitDiffCache.getInstance(getDiffFn);
|
||||
|
||||
const promise1 = cache.get();
|
||||
const promise2 = cache.get();
|
||||
|
||||
resolvePromise!(mockDiff);
|
||||
|
||||
const [result1, result2] = await Promise.all([promise1, promise2]);
|
||||
|
||||
expect(result1).toEqual(mockDiff);
|
||||
expect(result2).toEqual(mockDiff);
|
||||
expect(getDiffFn).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("GitDiffCache invalidate clears cache", async () => {
|
||||
const mockDiff = ["file1.ts"];
|
||||
const getDiffFn = jest.fn().mockResolvedValue(mockDiff);
|
||||
const cache = GitDiffCache.getInstance(getDiffFn);
|
||||
|
||||
await cache.get();
|
||||
cache.invalidate();
|
||||
await cache.get();
|
||||
|
||||
expect(getDiffFn).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("GitDiffCache maintains singleton instance", () => {
|
||||
const getDiffFn1 = jest.fn();
|
||||
const getDiffFn2 = jest.fn();
|
||||
|
||||
const instance1 = GitDiffCache.getInstance(getDiffFn1);
|
||||
const instance2 = GitDiffCache.getInstance(getDiffFn2);
|
||||
|
||||
expect(instance1).toBe(instance2);
|
||||
});
|
||||
73
core/autocomplete/snippets/gitDiffCache.ts
Normal file
73
core/autocomplete/snippets/gitDiffCache.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import { IDE } from "../..";
|
||||
|
||||
type GetDiffFn = () => Promise<string[]>;
|
||||
|
||||
export class GitDiffCache {
|
||||
private static instance: GitDiffCache | null = null;
|
||||
private cachedDiff: string[] | undefined = undefined;
|
||||
private lastFetchTime: number = 0;
|
||||
private pendingRequest: Promise<string[]> | null = null;
|
||||
private getDiffFn: GetDiffFn;
|
||||
private cacheTimeMs: number;
|
||||
|
||||
private constructor(getDiffFn: GetDiffFn, cacheTimeSeconds: number = 60) {
|
||||
this.getDiffFn = getDiffFn;
|
||||
this.cacheTimeMs = cacheTimeSeconds * 1000;
|
||||
}
|
||||
|
||||
public static getInstance(
|
||||
getDiffFn: GetDiffFn,
|
||||
cacheTimeSeconds?: number,
|
||||
): GitDiffCache {
|
||||
if (!GitDiffCache.instance) {
|
||||
GitDiffCache.instance = new GitDiffCache(getDiffFn, cacheTimeSeconds);
|
||||
}
|
||||
return GitDiffCache.instance;
|
||||
}
|
||||
|
||||
private async getDiffPromise(): Promise<string[]> {
|
||||
try {
|
||||
const diff = await this.getDiffFn();
|
||||
this.cachedDiff = diff;
|
||||
this.lastFetchTime = Date.now();
|
||||
return this.cachedDiff;
|
||||
} catch (e) {
|
||||
console.error("Error fetching git diff:", e);
|
||||
return [];
|
||||
} finally {
|
||||
this.pendingRequest = null;
|
||||
}
|
||||
}
|
||||
|
||||
public async get(): Promise<string[]> {
|
||||
if (
|
||||
this.cachedDiff !== undefined &&
|
||||
Date.now() - this.lastFetchTime < this.cacheTimeMs
|
||||
) {
|
||||
return this.cachedDiff;
|
||||
}
|
||||
|
||||
// If there's already a request in progress, return that instead of starting a new one
|
||||
if (this.pendingRequest) {
|
||||
return this.pendingRequest;
|
||||
}
|
||||
|
||||
this.pendingRequest = this.getDiffPromise();
|
||||
return this.pendingRequest;
|
||||
}
|
||||
|
||||
public invalidate(): void {
|
||||
this.cachedDiff = undefined;
|
||||
this.pendingRequest = null;
|
||||
}
|
||||
}
|
||||
|
||||
// factory to make diff cache more testable
|
||||
export function getDiffFn(ide: IDE): GetDiffFn {
|
||||
return () => ide.getDiff(true);
|
||||
}
|
||||
|
||||
export async function getDiffsFromCache(ide: IDE): Promise<string[]> {
|
||||
const diffCache = GitDiffCache.getInstance(getDiffFn(ide));
|
||||
return await diffCache.get();
|
||||
}
|
||||
|
|
@ -72,7 +72,8 @@ const qwenCoderFimTemplate: AutocompleteTemplate = {
|
|||
};
|
||||
|
||||
const seedCoderFimTemplate: AutocompleteTemplate = {
|
||||
template: "<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
|
||||
template:
|
||||
"<[fim-prefix]>{{{prefix}}}<[fim-suffix]>{{{suffix}}}<[fim-middle]>",
|
||||
completionOptions: {
|
||||
stop: [
|
||||
"<[end▁of▁sentence]>",
|
||||
|
|
|
|||
|
|
@ -0,0 +1,434 @@
|
|||
/**
|
||||
* Comprehensive tests for formatOpenedFilesContext.ts
|
||||
*
|
||||
*/
|
||||
|
||||
import {
|
||||
AutocompleteCodeSnippet,
|
||||
AutocompleteDiffSnippet,
|
||||
AutocompleteSnippetType,
|
||||
} from "../../snippets/types";
|
||||
import { HelperVars } from "../../util/HelperVars";
|
||||
import { formatOpenedFilesContext } from "../formatOpenedFilesContext";
|
||||
|
||||
// Import the now-exported internal functions
|
||||
import {
|
||||
getRecencyAndSizeScore,
|
||||
rankByScore,
|
||||
setLogStats,
|
||||
trimSnippetForContext,
|
||||
} from "../formatOpenedFilesContext";
|
||||
|
||||
describe("formatOpenedFilesContext main function tests", () => {
|
||||
const mockHelper = {
|
||||
modelName: "test-model",
|
||||
} as HelperVars;
|
||||
|
||||
const TOKEN_BUFFER = 50;
|
||||
|
||||
// Create sample code snippets with various sizes
|
||||
const createCodeSnippet = (
|
||||
filepath: string,
|
||||
content: string,
|
||||
): AutocompleteCodeSnippet => ({
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath,
|
||||
content,
|
||||
});
|
||||
|
||||
const createDiffSnippet = (content: string): AutocompleteDiffSnippet => ({
|
||||
type: AutocompleteSnippetType.Diff,
|
||||
content,
|
||||
});
|
||||
|
||||
test("should return empty array when no snippets are provided", () => {
|
||||
const result = formatOpenedFilesContext(
|
||||
[],
|
||||
1000,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
test("should handle zero remaining token count", () => {
|
||||
const snippets = [
|
||||
createCodeSnippet("file1.ts", "content of file 1"),
|
||||
createCodeSnippet("file2.ts", "content of file 2"),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
snippets,
|
||||
0,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
test("should handle snippets with empty content", () => {
|
||||
const emptySnippets = [
|
||||
createCodeSnippet("empty1.ts", ""),
|
||||
createCodeSnippet("empty2.ts", ""),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
emptySnippets,
|
||||
1000,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBe(emptySnippets.length);
|
||||
});
|
||||
|
||||
test("should return all snippets when they all fit within token limit", () => {
|
||||
const smallSnippets = [
|
||||
createCodeSnippet("small1.ts", "a"),
|
||||
createCodeSnippet("small2.ts", "b"),
|
||||
createCodeSnippet("small3.ts", "c"),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
smallSnippets,
|
||||
1000,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBe(smallSnippets.length);
|
||||
});
|
||||
|
||||
test("should handle limited token count", () => {
|
||||
const snippets = Array(10)
|
||||
.fill(0)
|
||||
.map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
snippets,
|
||||
1, // Extremely small token count
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(Array.isArray(result)).toBe(true);
|
||||
});
|
||||
|
||||
test("should accept valid inputs with adequate token count", () => {
|
||||
const snippets = [
|
||||
createCodeSnippet("file1.ts", "Some content here"),
|
||||
createCodeSnippet("file2.ts", "More content here"),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
snippets,
|
||||
1000,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("should handle already added snippets parameter", () => {
|
||||
const snippets = [
|
||||
createCodeSnippet("file1.ts", "content of file 1"),
|
||||
createCodeSnippet("file2.ts", "content of file 2"),
|
||||
];
|
||||
|
||||
const alreadyAddedSnippets = [createDiffSnippet("diff content")];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
snippets,
|
||||
1000,
|
||||
mockHelper,
|
||||
alreadyAddedSnippets,
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBe(snippets.length);
|
||||
});
|
||||
|
||||
test("should handle large snippets by trimming them", () => {
|
||||
const largeSnippet = createCodeSnippet("large.ts", "x".repeat(10000));
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
[largeSnippet],
|
||||
200,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBe(1);
|
||||
expect(result[0].filepath).toBe(largeSnippet.filepath);
|
||||
expect(result[0].content.length).toBeLessThan(largeSnippet.content.length);
|
||||
});
|
||||
|
||||
test("should prioritize more recent snippets when not all fit", () => {
|
||||
const snippets = [
|
||||
createCodeSnippet("recent1.ts", "a".repeat(10)),
|
||||
createCodeSnippet("recent2.ts", "b".repeat(10000)),
|
||||
createCodeSnippet("recent3.ts", "c".repeat(10000)),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
snippets,
|
||||
200,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
expect(result.some((s) => s.filepath === "recent1.ts")).toBe(true);
|
||||
});
|
||||
|
||||
test("should handle a mix of large and small snippets effectively", () => {
|
||||
const mixedSnippets = [
|
||||
createCodeSnippet("small1.ts", "a".repeat(10)),
|
||||
createCodeSnippet("large1.ts", "b".repeat(5000)),
|
||||
createCodeSnippet("small2.ts", "c".repeat(10)),
|
||||
createCodeSnippet("large2.ts", "d".repeat(5000)),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
mixedSnippets,
|
||||
500,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
expect(result.some((s) => s.filepath.startsWith("small"))).toBe(true);
|
||||
});
|
||||
|
||||
test("should respect minimum token threshold when trimming", () => {
|
||||
const largeSnippets = [
|
||||
createCodeSnippet("large1.ts", "a".repeat(5000)),
|
||||
createCodeSnippet("large2.ts", "b".repeat(5000)),
|
||||
];
|
||||
|
||||
const result = formatOpenedFilesContext(
|
||||
largeSnippets,
|
||||
150,
|
||||
mockHelper,
|
||||
[],
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
expect(result.length).toBeLessThanOrEqual(1);
|
||||
|
||||
if (result.length > 0) {
|
||||
expect(result[0].content.length).toBeLessThan(
|
||||
largeSnippets[0].content.length,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Tests for rankByScore function
|
||||
describe("rankByScore function", () => {
|
||||
const createCodeSnippet = (
|
||||
filepath: string,
|
||||
content: string,
|
||||
): AutocompleteCodeSnippet => ({
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath,
|
||||
content,
|
||||
});
|
||||
|
||||
test("should return empty array when given empty array", () => {
|
||||
const result = rankByScore([]);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
|
||||
test("should rank snippets by score", () => {
|
||||
// Initialize logMin and logMax by calling setLogStats first
|
||||
const snippets = [
|
||||
createCodeSnippet("file1.ts", "a".repeat(10)),
|
||||
createCodeSnippet("file2.ts", "b".repeat(1000)),
|
||||
createCodeSnippet("file3.ts", "c".repeat(100)),
|
||||
];
|
||||
setLogStats(snippets);
|
||||
|
||||
const result = rankByScore(snippets);
|
||||
|
||||
expect(Array.isArray(result)).toBe(true);
|
||||
expect(result.length).toBeGreaterThan(0);
|
||||
|
||||
// The snippets should be ranked in some order, which may not match input order
|
||||
expect(result.map((s: { filepath: any }) => s.filepath)).not.toEqual(
|
||||
snippets.map((s) => s.filepath),
|
||||
);
|
||||
});
|
||||
|
||||
test("should limit the number of ranked snippets to defaultNumFilesUsed", () => {
|
||||
// Create more snippets than the default limit
|
||||
const manySnippets = Array(10)
|
||||
.fill(0)
|
||||
.map((_, i) => createCodeSnippet(`file${i}.ts`, `content of file ${i}`));
|
||||
setLogStats(manySnippets);
|
||||
|
||||
const result = rankByScore(manySnippets);
|
||||
|
||||
// The function should limit the number of snippets (defaultNumFilesUsed is 5)
|
||||
expect(result.length).toBeLessThanOrEqual(5);
|
||||
});
|
||||
});
|
||||
|
||||
// Tests for getRecencyAndSizeScore function
|
||||
describe("getRecencyAndSizeScore function", () => {
|
||||
const createCodeSnippet = (
|
||||
filepath: string,
|
||||
content: string,
|
||||
): AutocompleteCodeSnippet => ({
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath,
|
||||
content,
|
||||
});
|
||||
|
||||
test("recency score should decrease with higher index", () => {
|
||||
// Initialize log stats first
|
||||
const snippets = [
|
||||
createCodeSnippet("file1.ts", "a".repeat(100)),
|
||||
createCodeSnippet("file2.ts", "b".repeat(100)),
|
||||
];
|
||||
setLogStats(snippets);
|
||||
|
||||
// Test that score decreases with increasing index
|
||||
const score0 = getRecencyAndSizeScore(0, snippets[0]);
|
||||
const score1 = getRecencyAndSizeScore(1, snippets[0]);
|
||||
const score2 = getRecencyAndSizeScore(2, snippets[0]);
|
||||
|
||||
expect(score0).toBeGreaterThan(score1);
|
||||
expect(score1).toBeGreaterThan(score2);
|
||||
});
|
||||
|
||||
test("size score should be higher for smaller snippets", () => {
|
||||
// Initialize log stats first
|
||||
const snippets = [
|
||||
createCodeSnippet("small.ts", "a".repeat(50)),
|
||||
createCodeSnippet("medium.ts", "b".repeat(200)),
|
||||
createCodeSnippet("large.ts", "c".repeat(1000)),
|
||||
];
|
||||
setLogStats(snippets);
|
||||
|
||||
// Test with same recency index but different sizes
|
||||
const smallScore = getRecencyAndSizeScore(0, snippets[0]);
|
||||
const mediumScore = getRecencyAndSizeScore(0, snippets[1]);
|
||||
const largeScore = getRecencyAndSizeScore(0, snippets[2]);
|
||||
|
||||
// Scores should reflect preference for smaller snippets
|
||||
expect(smallScore).toBeGreaterThanOrEqual(mediumScore);
|
||||
expect(mediumScore).toBeGreaterThanOrEqual(largeScore);
|
||||
});
|
||||
|
||||
test("recency and size both affect the score with recency having more weight", () => {
|
||||
// Initialize log stats first
|
||||
const snippets = [
|
||||
createCodeSnippet("recent_large.ts", "a".repeat(1000)),
|
||||
createCodeSnippet("old_small.ts", "b".repeat(50)),
|
||||
];
|
||||
setLogStats(snippets);
|
||||
|
||||
// Test that recency and size both contribute to the score
|
||||
const recentLargeScore = getRecencyAndSizeScore(0, snippets[0]);
|
||||
const oldSmallScore = getRecencyAndSizeScore(1, snippets[1]);
|
||||
|
||||
// We're not making a direct comparison, just verifying the scoring mechanism works
|
||||
expect(recentLargeScore).toBeGreaterThan(0);
|
||||
expect(oldSmallScore).toBeGreaterThan(0);
|
||||
expect(oldSmallScore).toBeLessThan(1);
|
||||
});
|
||||
});
|
||||
|
||||
// Tests for setLogStats function
|
||||
describe("setLogStats function", () => {
|
||||
const createCodeSnippet = (
|
||||
filepath: string,
|
||||
content: string,
|
||||
): AutocompleteCodeSnippet => ({
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath,
|
||||
content,
|
||||
});
|
||||
|
||||
test("should set logMin and logMax based on snippet sizes", () => {
|
||||
const snippets = [
|
||||
createCodeSnippet("small.ts", "a".repeat(50)),
|
||||
createCodeSnippet("medium.ts", "b".repeat(200)),
|
||||
createCodeSnippet("large.ts", "c".repeat(1000)),
|
||||
];
|
||||
|
||||
// We can't directly test logMin and logMax as they're private
|
||||
// but we can verify that the function runs without errors
|
||||
expect(() => setLogStats(snippets)).not.toThrow();
|
||||
});
|
||||
|
||||
test("should handle empty snippets", () => {
|
||||
const emptySnippets = [
|
||||
createCodeSnippet("empty1.ts", ""),
|
||||
createCodeSnippet("empty2.ts", ""),
|
||||
];
|
||||
|
||||
expect(() => setLogStats(emptySnippets)).not.toThrow();
|
||||
});
|
||||
|
||||
test("should handle single snippet", () => {
|
||||
const singleSnippet = [createCodeSnippet("single.ts", "content")];
|
||||
|
||||
expect(() => setLogStats(singleSnippet)).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
// Tests for trimSnippetForContext function
|
||||
describe("trimSnippetForContext function", () => {
|
||||
const createCodeSnippet = (
|
||||
filepath: string,
|
||||
content: string,
|
||||
): AutocompleteCodeSnippet => ({
|
||||
type: AutocompleteSnippetType.Code,
|
||||
filepath,
|
||||
content,
|
||||
});
|
||||
|
||||
test("should return original snippet if it fits within token limit", () => {
|
||||
const snippet = createCodeSnippet("small.ts", "small content");
|
||||
const modelName = "test-model";
|
||||
const maxTokens = 1000; // Large enough to fit the snippet
|
||||
|
||||
const result = trimSnippetForContext(snippet, maxTokens, modelName);
|
||||
|
||||
// Should return the original snippet with its token count
|
||||
expect(result.newSnippet).toEqual(snippet);
|
||||
expect(typeof result.newTokens).toBe("number");
|
||||
expect(result.newTokens).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
test("should trim snippet content if it exceeds token limit", () => {
|
||||
const snippet = createCodeSnippet("large.ts", "a".repeat(1000));
|
||||
const modelName = "test-model";
|
||||
const maxTokens = 10; // Small enough to require trimming
|
||||
|
||||
const result = trimSnippetForContext(snippet, maxTokens, modelName);
|
||||
|
||||
// Should return a trimmed snippet
|
||||
expect(result.newSnippet.filepath).toBe(snippet.filepath);
|
||||
expect(result.newSnippet.type).toBe(snippet.type);
|
||||
expect(result.newSnippet.content.length).toBeLessThanOrEqual(
|
||||
snippet.content.length,
|
||||
);
|
||||
|
||||
// Token count should be less than or equal to maxTokens
|
||||
expect(result.newTokens).toBeLessThanOrEqual(maxTokens);
|
||||
});
|
||||
});
|
||||
|
|
@ -3,8 +3,10 @@ import { SnippetPayload } from "../snippets";
|
|||
import {
|
||||
AutocompleteCodeSnippet,
|
||||
AutocompleteSnippet,
|
||||
AutocompleteSnippetType,
|
||||
} from "../snippets/types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
import { formatOpenedFilesContext } from "./formatOpenedFilesContext";
|
||||
|
||||
import { isValidSnippet } from "./validation";
|
||||
|
||||
|
|
@ -42,17 +44,19 @@ export const getSnippets = (
|
|||
helper: HelperVars,
|
||||
payload: SnippetPayload,
|
||||
): AutocompleteSnippet[] => {
|
||||
|
||||
const snippets = {
|
||||
"clipboard": payload.clipboardSnippets,
|
||||
"recentlyVisitedRanges": payload.recentlyVisitedRangesSnippets,
|
||||
"recentlyEditedRanges": payload.recentlyEditedRangeSnippets,
|
||||
"diff": payload.diffSnippets,
|
||||
"base": shuffleArray(filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
helper.prunedCaretWindow,
|
||||
)),
|
||||
}
|
||||
clipboard: payload.clipboardSnippets,
|
||||
recentlyVisitedRanges: payload.recentlyVisitedRangesSnippets,
|
||||
recentlyEditedRanges: payload.recentlyEditedRangeSnippets,
|
||||
diff: payload.diffSnippets,
|
||||
recentlyOpenedFiles: payload.recentlyOpenedFileSnippets,
|
||||
base: shuffleArray(
|
||||
filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
helper.prunedCaretWindow,
|
||||
),
|
||||
),
|
||||
};
|
||||
|
||||
// Define snippets with their priorities
|
||||
const snippetConfigs: {
|
||||
|
|
@ -61,92 +65,133 @@ export const getSnippets = (
|
|||
defaultPriority: number;
|
||||
snippets: AutocompleteSnippet[];
|
||||
}[] = [
|
||||
{
|
||||
key: "clipboard",
|
||||
enabledOrPriority: helper.options.experimental_includeClipboard,
|
||||
defaultPriority: 1,
|
||||
snippets: payload.clipboardSnippets,
|
||||
},
|
||||
{
|
||||
key: "recentlyVisitedRanges",
|
||||
enabledOrPriority: helper.options.experimental_includeRecentlyVisitedRanges,
|
||||
defaultPriority: 2,
|
||||
snippets: payload.recentlyVisitedRangesSnippets,
|
||||
/* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
|
||||
{
|
||||
key: "clipboard",
|
||||
enabledOrPriority: helper.options.experimental_includeClipboard,
|
||||
defaultPriority: 1,
|
||||
snippets: payload.clipboardSnippets,
|
||||
},
|
||||
{
|
||||
key: "recentlyOpenedFiles",
|
||||
enabledOrPriority: helper.options.useRecentlyOpened,
|
||||
defaultPriority: 2,
|
||||
snippets: payload.recentlyOpenedFileSnippets,
|
||||
},
|
||||
{
|
||||
key: "recentlyVisitedRanges",
|
||||
enabledOrPriority:
|
||||
helper.options.experimental_includeRecentlyVisitedRanges,
|
||||
defaultPriority: 3,
|
||||
snippets: payload.recentlyVisitedRangesSnippets,
|
||||
/* TODO: recentlyVisitedRanges also contain contents from other windows like terminal or output
|
||||
if they are visible. We should handle them separately so that we can control their priority
|
||||
and whether they should be included or not. */
|
||||
},
|
||||
{
|
||||
key: "recentlyEditedRanges",
|
||||
enabledOrPriority: helper.options.experimental_includeRecentlyEditedRanges,
|
||||
defaultPriority: 3,
|
||||
snippets: payload.recentlyEditedRangeSnippets,
|
||||
},
|
||||
{
|
||||
key: "diff",
|
||||
enabledOrPriority: helper.options.experimental_includeDiff,
|
||||
defaultPriority: 4,
|
||||
snippets: payload.diffSnippets,
|
||||
// TODO: diff is commonly too large, thus anything lower in priority is not included.
|
||||
},
|
||||
{
|
||||
key: "base",
|
||||
enabledOrPriority: true,
|
||||
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
|
||||
snippets: shuffleArray(filterSnippetsAlreadyInCaretWindow(
|
||||
},
|
||||
{
|
||||
key: "recentlyEditedRanges",
|
||||
enabledOrPriority:
|
||||
helper.options.experimental_includeRecentlyEditedRanges,
|
||||
defaultPriority: 4,
|
||||
snippets: payload.recentlyEditedRangeSnippets,
|
||||
},
|
||||
{
|
||||
key: "diff",
|
||||
enabledOrPriority: helper.options.experimental_includeDiff,
|
||||
defaultPriority: 5,
|
||||
snippets: payload.diffSnippets,
|
||||
// TODO: diff is commonly too large, thus anything lower in priority is not included.
|
||||
},
|
||||
{
|
||||
key: "base",
|
||||
enabledOrPriority: true,
|
||||
defaultPriority: 99, // make sure it's the last one to be processed, but still possible to override
|
||||
snippets: shuffleArray(
|
||||
filterSnippetsAlreadyInCaretWindow(
|
||||
[...payload.rootPathSnippets, ...payload.importDefinitionSnippets],
|
||||
helper.prunedCaretWindow,
|
||||
)),
|
||||
// TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
|
||||
// always not inlucded due to diff being commonly large
|
||||
},
|
||||
];
|
||||
),
|
||||
),
|
||||
// TODO: Add this too to experimental config, maybe move upper in the order, since it's almost
|
||||
// always not inlucded due to diff being commonly large
|
||||
},
|
||||
];
|
||||
|
||||
// Create a readable order of enabled snippets
|
||||
const snippetOrder = snippetConfigs
|
||||
.filter(({ enabledOrPriority }) => enabledOrPriority)
|
||||
.map(({ key, enabledOrPriority, defaultPriority }) => ({
|
||||
key,
|
||||
priority: typeof enabledOrPriority === 'number' ? enabledOrPriority : defaultPriority,
|
||||
priority:
|
||||
typeof enabledOrPriority === "number"
|
||||
? enabledOrPriority
|
||||
: defaultPriority,
|
||||
}))
|
||||
.sort((a, b) => a.priority - b.priority);
|
||||
|
||||
// Log the snippet order for debugging - uncomment if needed
|
||||
/* console.log(
|
||||
'Snippet processing order:',
|
||||
snippetOrder
|
||||
.map(({ key, priority }) => `${key} (priority: ${priority})`).join("\n")
|
||||
); */
|
||||
|
||||
// Convert configs to prioritized snippets
|
||||
let prioritizedSnippets = snippetOrder
|
||||
.flatMap(({ key, priority }) =>
|
||||
snippets[key].map(snippet => ({ snippet, priority }))
|
||||
)
|
||||
.sort((a, b) => a.priority - b.priority)
|
||||
.map(({ snippet }) => snippet);
|
||||
|
||||
// Exclude Continue's own output as it makes it super-hard for users to test the autocomplete feature
|
||||
// while looking at the prompts in the Continue's output
|
||||
prioritizedSnippets = prioritizedSnippets.filter((snippet) =>
|
||||
!(snippet as AutocompleteCodeSnippet).filepath?.startsWith("output:extension-output-Continue.continue"));
|
||||
|
||||
const finalSnippets = [];
|
||||
let remainingTokenCount = getRemainingTokenCount(helper);
|
||||
|
||||
while (remainingTokenCount > 0 && prioritizedSnippets.length > 0) {
|
||||
const snippet = prioritizedSnippets.shift();
|
||||
if (!snippet || !isValidSnippet(snippet)) {
|
||||
continue;
|
||||
// tracks already added filepaths for deduplication
|
||||
const addedFilepaths = new Set<string>();
|
||||
|
||||
// Process snippets in priority order
|
||||
for (const { key } of snippetOrder) {
|
||||
// Special handling for recentlyOpenedFiles
|
||||
if (key === "recentlyOpenedFiles" && helper.options.useRecentlyOpened) {
|
||||
// Custom trimming
|
||||
const processedSnippets = formatOpenedFilesContext(
|
||||
payload.recentlyOpenedFileSnippets,
|
||||
remainingTokenCount,
|
||||
helper,
|
||||
finalSnippets,
|
||||
TOKEN_BUFFER,
|
||||
);
|
||||
|
||||
// Add processed snippets to finalSnippets respecting token limits
|
||||
for (const snippet of processedSnippets) {
|
||||
if (!isValidSnippet(snippet)) continue;
|
||||
|
||||
const snippetSize =
|
||||
countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER;
|
||||
|
||||
if (remainingTokenCount >= snippetSize) {
|
||||
finalSnippets.push(snippet);
|
||||
addedFilepaths.add(snippet.filepath);
|
||||
remainingTokenCount -= snippetSize;
|
||||
} else {
|
||||
continue; // Not enough tokens, try again with next snippet
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Normal processing for other snippet types
|
||||
const snippetsToProcess = snippets[key].filter(
|
||||
(snippet) =>
|
||||
snippet.type !== AutocompleteSnippetType.Code ||
|
||||
!addedFilepaths.has(snippet.filepath),
|
||||
);
|
||||
|
||||
for (const snippet of snippetsToProcess) {
|
||||
if (!isValidSnippet(snippet)) continue;
|
||||
|
||||
const snippetSize =
|
||||
countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER;
|
||||
|
||||
if (remainingTokenCount >= snippetSize) {
|
||||
finalSnippets.push(snippet);
|
||||
|
||||
if ((snippet as AutocompleteCodeSnippet).filepath) {
|
||||
addedFilepaths.add((snippet as AutocompleteCodeSnippet).filepath);
|
||||
}
|
||||
|
||||
remainingTokenCount -= snippetSize;
|
||||
} else {
|
||||
continue; // Not enough tokens, try again with next snippet
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const snippetSize =
|
||||
countTokens(snippet.content, helper.modelName) + TOKEN_BUFFER;
|
||||
|
||||
if (remainingTokenCount >= snippetSize) {
|
||||
finalSnippets.push(snippet);
|
||||
remainingTokenCount -= snippetSize;
|
||||
}
|
||||
// If we're out of tokens, no need to process more snippet types
|
||||
if (remainingTokenCount <= 0) break;
|
||||
}
|
||||
|
||||
return finalSnippets;
|
||||
|
|
|
|||
183
core/autocomplete/templating/formatOpenedFilesContext.ts
Normal file
183
core/autocomplete/templating/formatOpenedFilesContext.ts
Normal file
|
|
@ -0,0 +1,183 @@
|
|||
import { countTokens, pruneStringFromBottom } from "../../llm/countTokens";
|
||||
import {
|
||||
AutocompleteCodeSnippet,
|
||||
AutocompleteSnippet,
|
||||
AutocompleteSnippetType,
|
||||
} from "../snippets/types";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
let logMin: number;
|
||||
let logMax: number;
|
||||
|
||||
const numFilesConsidered = 10;
|
||||
const defaultNumFilesUsed = 5;
|
||||
const recencyWeight = 0.6;
|
||||
const sizeWeight = 0.4;
|
||||
const minSize = 10;
|
||||
const minTokensInSnippet = 125;
|
||||
|
||||
// Fits opened-file snippets into the remaining amount of prompt tokens
|
||||
export function formatOpenedFilesContext(
|
||||
recentlyOpenedFilesSnippets: AutocompleteCodeSnippet[],
|
||||
remainingTokenCount: number,
|
||||
helper: HelperVars,
|
||||
alreadyAddedSnippets: AutocompleteSnippet[],
|
||||
TOKEN_BUFFER: number,
|
||||
): AutocompleteCodeSnippet[] {
|
||||
if (recentlyOpenedFilesSnippets.length === 0) {
|
||||
return [];
|
||||
}
|
||||
|
||||
// deduplication; if a snippet is already added, don't include it here
|
||||
for (const snippet of alreadyAddedSnippets) {
|
||||
if (snippet.type !== AutocompleteSnippetType.Code) {
|
||||
continue;
|
||||
}
|
||||
recentlyOpenedFilesSnippets = recentlyOpenedFilesSnippets.filter(
|
||||
(s) => s.filepath !== snippet.filepath,
|
||||
);
|
||||
}
|
||||
|
||||
// Calculate how many full snippets would fit within the remaining token count
|
||||
let numSnippetsThatFit = 0;
|
||||
let totalTokens = 0;
|
||||
|
||||
const numFilesUsed = Math.min(
|
||||
defaultNumFilesUsed,
|
||||
recentlyOpenedFilesSnippets.length,
|
||||
);
|
||||
|
||||
for (let i = 0; i < recentlyOpenedFilesSnippets.length; i++) {
|
||||
const snippetTokens = countTokens(
|
||||
recentlyOpenedFilesSnippets[i].content,
|
||||
helper.modelName,
|
||||
);
|
||||
if (totalTokens + snippetTokens < remainingTokenCount - TOKEN_BUFFER) {
|
||||
totalTokens += snippetTokens;
|
||||
numSnippetsThatFit++;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// if all the untrimmed snippets, or more than a default value, fit, return the untrimmed snippets
|
||||
if (numSnippetsThatFit >= numFilesUsed) {
|
||||
return recentlyOpenedFilesSnippets.slice(0, numSnippetsThatFit);
|
||||
}
|
||||
|
||||
// If they don't fit, adaptively trim them.
|
||||
setLogStats(recentlyOpenedFilesSnippets);
|
||||
const topScoredSnippets = rankByScore(recentlyOpenedFilesSnippets);
|
||||
let N = topScoredSnippets.length;
|
||||
while (remainingTokenCount - TOKEN_BUFFER < N * minTokensInSnippet) {
|
||||
topScoredSnippets.pop();
|
||||
N = topScoredSnippets.length;
|
||||
if (N === 0) break;
|
||||
}
|
||||
|
||||
let trimmedSnippets = new Array<AutocompleteCodeSnippet>();
|
||||
|
||||
while (N > 0) {
|
||||
let W = 2 / (N + 1);
|
||||
let snippetTokenLimit = Math.floor(
|
||||
minTokensInSnippet +
|
||||
W * (remainingTokenCount - TOKEN_BUFFER - N * minTokensInSnippet),
|
||||
);
|
||||
|
||||
let trimmedSnippetAndTokenCount = trimSnippetForContext(
|
||||
topScoredSnippets[0],
|
||||
snippetTokenLimit,
|
||||
helper.modelName,
|
||||
);
|
||||
trimmedSnippets.push(trimmedSnippetAndTokenCount.newSnippet);
|
||||
remainingTokenCount -= trimmedSnippetAndTokenCount.newTokens;
|
||||
topScoredSnippets.shift();
|
||||
N = topScoredSnippets.length;
|
||||
}
|
||||
|
||||
return trimmedSnippets;
|
||||
}
|
||||
|
||||
// Rank snippets by recency and size
|
||||
const rankByScore = (
|
||||
snippets: AutocompleteCodeSnippet[],
|
||||
): AutocompleteCodeSnippet[] => {
|
||||
if (snippets.length === 0) return [];
|
||||
|
||||
const topSnippets = snippets.slice(0, numFilesConsidered);
|
||||
|
||||
// Sort by score (using original index for recency calculation)
|
||||
const scoredSnippets = topSnippets.map((snippet, i) => ({
|
||||
snippet,
|
||||
originalIndex: i,
|
||||
score: getRecencyAndSizeScore(i, snippet),
|
||||
}));
|
||||
|
||||
// Uncomment to debug. Logs the table of snippets with their scores (in order of recency).
|
||||
/* console.table(
|
||||
topSnippets.map((snippet, i) => ({
|
||||
filepath: "filepath" in snippet ? snippet.filepath : "unknown",
|
||||
recencyAndSizeScore: getRecencyAndSizeScore(i, snippet),
|
||||
})),
|
||||
); */
|
||||
|
||||
scoredSnippets.sort((a, b) => b.score - a.score);
|
||||
|
||||
return scoredSnippets
|
||||
.slice(0, Math.min(defaultNumFilesUsed, scoredSnippets.length))
|
||||
.map((item) => item.snippet);
|
||||
};
|
||||
|
||||
// Returns linear combination of recency and size scores
|
||||
// recency score is exponential decay over recency; log normalized score is used for size
|
||||
const getRecencyAndSizeScore = (
|
||||
index: number,
|
||||
snippet: AutocompleteSnippet,
|
||||
): number => {
|
||||
const recencyScore = Math.pow(1.15, -1 * index);
|
||||
|
||||
const logCurrent = Math.log(Math.max(snippet.content.length, minSize));
|
||||
const sizeScore =
|
||||
logMax === logMin ? 0.5 : 1 - (logCurrent - logMin) / (logMax - logMin);
|
||||
|
||||
return recencyWeight * recencyScore + sizeWeight * sizeScore;
|
||||
};
|
||||
|
||||
const setLogStats = (snippets: AutocompleteSnippet[]): void => {
|
||||
let contentSizes = snippets
|
||||
.slice(0, 10)
|
||||
.map((snippet) => snippet.content.length);
|
||||
logMin = Math.log(Math.max(Math.min(...contentSizes), minSize));
|
||||
logMax = Math.log(Math.max(Math.max(...contentSizes), minSize));
|
||||
return;
|
||||
};
|
||||
|
||||
function trimSnippetForContext(
|
||||
snippet: AutocompleteCodeSnippet,
|
||||
maxTokens: number,
|
||||
modelName: string,
|
||||
): { newSnippet: AutocompleteCodeSnippet; newTokens: number } {
|
||||
let numTokensInSnippet = countTokens(snippet.content, modelName);
|
||||
if (numTokensInSnippet <= maxTokens) {
|
||||
return { newSnippet: snippet, newTokens: numTokensInSnippet };
|
||||
}
|
||||
|
||||
let trimmedCode = pruneStringFromBottom(
|
||||
modelName,
|
||||
maxTokens,
|
||||
snippet.content,
|
||||
);
|
||||
|
||||
return {
|
||||
newSnippet: { ...snippet, content: trimmedCode },
|
||||
newTokens: countTokens(trimmedCode, modelName),
|
||||
};
|
||||
}
|
||||
|
||||
// Uncomment for testing
|
||||
export {
|
||||
getRecencyAndSizeScore,
|
||||
rankByScore,
|
||||
setLogStats,
|
||||
trimSnippetForContext,
|
||||
};
|
||||
|
|
@ -4,13 +4,13 @@ import { CompletionOptions } from "../..";
|
|||
import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo";
|
||||
import { HelperVars } from "../util/HelperVars";
|
||||
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
import { SnippetPayload } from "../snippets";
|
||||
import {
|
||||
AutocompleteTemplate,
|
||||
getTemplateForModel,
|
||||
} from "./AutocompleteTemplate";
|
||||
import { getSnippets } from "./filtering";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
import { formatSnippets } from "./formatting";
|
||||
import { getStopTokens } from "./getStopTokens";
|
||||
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import {
|
||||
AutocompleteClipboardSnippet,
|
||||
AutocompleteCodeSnippet,
|
||||
AutocompleteSnippet,
|
||||
AutocompleteSnippetType,
|
||||
} from "../snippets/types";
|
||||
|
|
@ -25,5 +26,13 @@ export const isValidSnippet = (snippet: AutocompleteSnippet): boolean => {
|
|||
return isValidClipboardSnippet(snippet);
|
||||
}
|
||||
|
||||
if (
|
||||
(snippet as AutocompleteCodeSnippet).filepath?.startsWith(
|
||||
"output:extension-output-Continue.continue",
|
||||
)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
};
|
||||
|
|
|
|||
|
|
@ -8,23 +8,23 @@ export class AutocompleteDebouncer {
|
|||
// Generate a unique ID for this request
|
||||
const requestId = uuidv4();
|
||||
this.currentRequestId = requestId;
|
||||
|
||||
|
||||
// Clear any existing timeout
|
||||
if (this.debounceTimeout) {
|
||||
clearTimeout(this.debounceTimeout);
|
||||
}
|
||||
|
||||
|
||||
// Create a new promise that resolves after the debounce delay
|
||||
return new Promise<boolean>((resolve) => {
|
||||
this.debounceTimeout = setTimeout(() => {
|
||||
// When the timeout completes, check if this is still the most recent request
|
||||
const shouldDebounce = this.currentRequestId !== requestId;
|
||||
|
||||
|
||||
// If this is the most recent request, it shouldn't be debounced
|
||||
if (!shouldDebounce) {
|
||||
this.currentRequestId = undefined;
|
||||
}
|
||||
|
||||
|
||||
resolve(shouldDebounce);
|
||||
}, debounceDelay);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { IDE, IdeInfo, TabAutocompleteOptions } from "../..";
|
||||
import { IDE, TabAutocompleteOptions } from "../..";
|
||||
import {
|
||||
countTokens,
|
||||
pruneLinesFromBottom,
|
||||
|
|
@ -21,7 +21,6 @@ export class HelperVars {
|
|||
lang: AutocompleteLanguageInfo;
|
||||
treePath: AstPath | undefined;
|
||||
workspaceUris: string[] = [];
|
||||
ideInfo: IdeInfo | undefined;
|
||||
|
||||
private _fileContents: string | undefined;
|
||||
private _fileLines: string[] | undefined;
|
||||
|
|
@ -44,7 +43,6 @@ export class HelperVars {
|
|||
if (this._fileContents !== undefined) {
|
||||
return;
|
||||
}
|
||||
this.ideInfo = await this.ide.getIdeInfo();
|
||||
this.workspaceUris = await this.ide.getWorkspaceDirs();
|
||||
|
||||
this._fileContents =
|
||||
|
|
|
|||
|
|
@ -1,65 +1,65 @@
|
|||
import {
|
||||
processTestCase,
|
||||
type CompletionTestCase,
|
||||
processTestCase,
|
||||
type CompletionTestCase,
|
||||
} from "./completionTestUtils";
|
||||
|
||||
describe("processTestCase utility", () => {
|
||||
it("processes simple console.log completion", () => {
|
||||
const testCase: CompletionTestCase = {
|
||||
original: "console.log(|cur||till|)",
|
||||
completion: "\"foo,\", bar",
|
||||
};
|
||||
it("processes simple console.log completion", () => {
|
||||
const testCase: CompletionTestCase = {
|
||||
original: "console.log(|cur||till|)",
|
||||
completion: '"foo,", bar',
|
||||
};
|
||||
|
||||
expect(processTestCase(testCase)).toEqual({
|
||||
input: {
|
||||
lastLineOfCompletionText: "\"foo,\", bar",
|
||||
currentText: ")",
|
||||
cursorPosition: "console.log(".length,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: "\"foo,\", bar",
|
||||
},
|
||||
});
|
||||
expect(processTestCase(testCase)).toEqual({
|
||||
input: {
|
||||
lastLineOfCompletionText: '"foo,", bar',
|
||||
currentText: ")",
|
||||
cursorPosition: "console.log(".length,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: '"foo,", bar',
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("processes simple console.log completion with overwriting", () => {
|
||||
const testCase: CompletionTestCase = {
|
||||
original: "console.log(|cur|)|till|",
|
||||
completion: "\"foo,\", bar);",
|
||||
};
|
||||
it("processes simple console.log completion with overwriting", () => {
|
||||
const testCase: CompletionTestCase = {
|
||||
original: "console.log(|cur|)|till|",
|
||||
completion: '"foo,", bar);',
|
||||
};
|
||||
|
||||
expect(processTestCase(testCase)).toEqual({
|
||||
input: {
|
||||
lastLineOfCompletionText: "\"foo,\", bar);",
|
||||
currentText: ")",
|
||||
cursorPosition: "console.log(".length,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: "\"foo,\", bar);",
|
||||
range: {
|
||||
start: "console.log(".length,
|
||||
end: "console.log()".length,
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(processTestCase(testCase)).toEqual({
|
||||
input: {
|
||||
lastLineOfCompletionText: '"foo,", bar);',
|
||||
currentText: ")",
|
||||
cursorPosition: "console.log(".length,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: '"foo,", bar);',
|
||||
range: {
|
||||
start: "console.log(".length,
|
||||
end: "console.log()".length,
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("partially applying completion", () => {
|
||||
const testCase: CompletionTestCase = {
|
||||
original: "|cur||till|fetch(\"https://example.com\");",
|
||||
completion: "await fetch(\"https://example.com\");",
|
||||
appliedCompletion: "await ",
|
||||
};
|
||||
it("partially applying completion", () => {
|
||||
const testCase: CompletionTestCase = {
|
||||
original: '|cur||till|fetch("https://example.com");',
|
||||
completion: 'await fetch("https://example.com");',
|
||||
appliedCompletion: "await ",
|
||||
};
|
||||
|
||||
expect(processTestCase(testCase)).toEqual({
|
||||
input: {
|
||||
lastLineOfCompletionText: "await fetch(\"https://example.com\");",
|
||||
currentText: "fetch(\"https://example.com\");",
|
||||
cursorPosition: 0,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: "await ",
|
||||
},
|
||||
});
|
||||
expect(processTestCase(testCase)).toEqual({
|
||||
input: {
|
||||
lastLineOfCompletionText: 'await fetch("https://example.com");',
|
||||
currentText: 'fetch("https://example.com");',
|
||||
cursorPosition: 0,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: "await ",
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,91 +1,94 @@
|
|||
export interface CompletionTestCase {
|
||||
original: string; // Text with |cur| and |till| markers
|
||||
completion: string; // Text to insert/overwrite
|
||||
appliedCompletion?: string | null;
|
||||
cursorMarker?: string;
|
||||
tillMarker?: string;
|
||||
original: string; // Text with |cur| and |till| markers
|
||||
completion: string; // Text to insert/overwrite
|
||||
appliedCompletion?: string | null;
|
||||
cursorMarker?: string;
|
||||
tillMarker?: string;
|
||||
}
|
||||
|
||||
export interface ProcessedTestCase {
|
||||
input: {
|
||||
lastLineOfCompletionText: string;
|
||||
currentText: string;
|
||||
cursorPosition: number;
|
||||
};
|
||||
expectedResult: {
|
||||
completionText: string;
|
||||
range?: {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
input: {
|
||||
lastLineOfCompletionText: string;
|
||||
currentText: string;
|
||||
cursorPosition: number;
|
||||
};
|
||||
expectedResult: {
|
||||
completionText: string;
|
||||
range?: {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Transforms human-readable test case into input and expected results.
|
||||
*
|
||||
*
|
||||
* - `original`: Your original text with |cur| marking where the cursor is before completion,
|
||||
* and |till| marking where the cursor should be after accepting completion (and this is
|
||||
* the end of the actual applied completion)
|
||||
* - `completion`: LLM completion output
|
||||
* - `appliedCompletion` (optional): part of the LLM completion output that is actually applied
|
||||
* (written between |cur| and |till| in the original)
|
||||
*
|
||||
*
|
||||
* For example, you have this line:
|
||||
*
|
||||
*
|
||||
* console.log("<cursor here>");
|
||||
*
|
||||
*
|
||||
* and expect it to be completed this way:
|
||||
*
|
||||
*
|
||||
* console.log("foo: ", bar<cursor here>);
|
||||
*
|
||||
*
|
||||
* with your completion coming from LLM being: `'foo: ", bar<cursor here>);'`
|
||||
*
|
||||
*
|
||||
* Your input to this function should be:
|
||||
* - original: `'console.log("|cur|"|till|);'`
|
||||
* - completion: `'foo: ", bar);'`
|
||||
* - appliedCompletion: `'foo: ", bar'`
|
||||
*
|
||||
*
|
||||
* Output: input and expected output of {@link core/autocomplete/util/processSingleLineCompletion/processSingleLineCompletion|processSingleLineCompletion()}
|
||||
*
|
||||
*
|
||||
*/
|
||||
export function processTestCase({
|
||||
original,
|
||||
completion,
|
||||
appliedCompletion = null,
|
||||
cursorMarker = "|cur|",
|
||||
tillMarker = "|till|",
|
||||
original,
|
||||
completion,
|
||||
appliedCompletion = null,
|
||||
cursorMarker = "|cur|",
|
||||
tillMarker = "|till|",
|
||||
}: CompletionTestCase): ProcessedTestCase {
|
||||
// Validate cursor marker
|
||||
if (!original.includes(cursorMarker)) {
|
||||
throw new Error("Cursor marker not found in original text");
|
||||
}
|
||||
// Validate cursor marker
|
||||
if (!original.includes(cursorMarker)) {
|
||||
throw new Error("Cursor marker not found in original text");
|
||||
}
|
||||
|
||||
const cursorPos = original.indexOf(cursorMarker);
|
||||
original = original.replace(cursorMarker, "");
|
||||
const cursorPos = original.indexOf(cursorMarker);
|
||||
original = original.replace(cursorMarker, "");
|
||||
|
||||
let tillPos = original.indexOf(tillMarker);
|
||||
if (tillPos < 0) {
|
||||
tillPos = cursorPos;
|
||||
} else {
|
||||
original = original.replace(tillMarker, "")
|
||||
}
|
||||
let tillPos = original.indexOf(tillMarker);
|
||||
if (tillPos < 0) {
|
||||
tillPos = cursorPos;
|
||||
} else {
|
||||
original = original.replace(tillMarker, "");
|
||||
}
|
||||
|
||||
// Calculate currentText based on what's between cursor and till marker
|
||||
const currentText = original.substring(cursorPos);
|
||||
// Calculate currentText based on what's between cursor and till marker
|
||||
const currentText = original.substring(cursorPos);
|
||||
|
||||
return {
|
||||
input: {
|
||||
lastLineOfCompletionText: completion,
|
||||
currentText,
|
||||
cursorPosition: cursorPos,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: appliedCompletion || completion,
|
||||
range: cursorPos === tillPos ? undefined : {
|
||||
start: cursorPos,
|
||||
end: tillPos,
|
||||
return {
|
||||
input: {
|
||||
lastLineOfCompletionText: completion,
|
||||
currentText,
|
||||
cursorPosition: cursorPos,
|
||||
},
|
||||
expectedResult: {
|
||||
completionText: appliedCompletion || completion,
|
||||
range:
|
||||
cursorPos === tillPos
|
||||
? undefined
|
||||
: {
|
||||
start: cursorPos,
|
||||
end: tillPos,
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
|
|
|||
20
core/autocomplete/util/openedFilesLruCache.ts
Normal file
20
core/autocomplete/util/openedFilesLruCache.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import QuickLRU from "quick-lru";
|
||||
|
||||
// The cache key and value are both a filepath string
|
||||
export type cacheElementType = string;
|
||||
|
||||
// maximum number of open files that can be cached
|
||||
const MAX_NUM_OPEN_CONTEXT_FILES = 20;
|
||||
|
||||
// stores which files are currently open in the IDE, in viewing order
|
||||
export const openedFilesLruCache = new QuickLRU<
|
||||
cacheElementType,
|
||||
cacheElementType
|
||||
>({
|
||||
maxSize: MAX_NUM_OPEN_CONTEXT_FILES,
|
||||
});
|
||||
|
||||
// used in core/core.ts to handle removals from the cache
|
||||
export const prevFilepaths = {
|
||||
filepaths: [] as string[],
|
||||
};
|
||||
|
|
@ -2,96 +2,94 @@ import { processTestCase } from "./completionTestUtils";
|
|||
import { processSingleLineCompletion } from "./processSingleLineCompletion";
|
||||
|
||||
describe("processSingleLineCompletion", () => {
|
||||
|
||||
it("should handle simple end of line completion", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|",
|
||||
completion: "\"Hello, world!\")",
|
||||
});
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition
|
||||
);
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
it("should handle simple end of line completion", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|",
|
||||
completion: '"Hello, world!")',
|
||||
});
|
||||
|
||||
it("should handle midline insert repeating the end of line", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|);|till|",
|
||||
completion: "\"Hello, world!\");",
|
||||
});
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition,
|
||||
);
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition
|
||||
);
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
});
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
it("should handle midline insert repeating the end of line", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|);|till|",
|
||||
completion: '"Hello, world!");',
|
||||
});
|
||||
|
||||
it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|)|till|",
|
||||
completion: "\"Hello, world!\");",
|
||||
});
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition,
|
||||
);
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition
|
||||
);
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
});
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
it("should handle midline insert repeating the end of line plus adding a semicolon", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|)|till|",
|
||||
completion: '"Hello, world!");',
|
||||
});
|
||||
|
||||
it("should handle simple midline insert", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|)",
|
||||
completion: "\"Hello, world!\"",
|
||||
});
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition,
|
||||
);
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition
|
||||
);
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
});
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
it("should handle simple midline insert", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur|)",
|
||||
completion: '"Hello, world!"',
|
||||
});
|
||||
|
||||
it("should handle complex dif with addition in the beginning", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "console.log(|cur||till|, \"param1\", )", // TODO
|
||||
completion: "\"Hello world!\", \"param1\", param1);",
|
||||
appliedCompletion: "\"Hello world!\""
|
||||
});
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition,
|
||||
);
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition
|
||||
);
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
});
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
it("should handle complex dif with addition in the beginning", () => {
|
||||
const testCase = processTestCase({
|
||||
original: 'console.log(|cur||till|, "param1", )', // TODO
|
||||
completion: '"Hello world!", "param1", param1);',
|
||||
appliedCompletion: '"Hello world!"',
|
||||
});
|
||||
|
||||
it("should handle simple insertion even with random equality", () => {
|
||||
const testCase = processTestCase({
|
||||
original: "print(f\"Foobar length: |cur||till|\")",
|
||||
completion: "{len(foobar)}",
|
||||
});
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition,
|
||||
);
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition
|
||||
);
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
});
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
it("should handle simple insertion even with random equality", () => {
|
||||
const testCase = processTestCase({
|
||||
original: 'print(f"Foobar length: |cur||till|")',
|
||||
completion: "{len(foobar)}",
|
||||
});
|
||||
|
||||
const result = processSingleLineCompletion(
|
||||
testCase.input.lastLineOfCompletionText,
|
||||
testCase.input.currentText,
|
||||
testCase.input.cursorPosition,
|
||||
);
|
||||
|
||||
expect(result).toEqual(testCase.expectedResult);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,92 +1,93 @@
|
|||
import * as Diff from "diff";
|
||||
|
||||
interface SingleLineCompletionResult {
|
||||
completionText: string;
|
||||
range?: {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
completionText: string;
|
||||
range?: {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
interface DiffType {
|
||||
count?: number;
|
||||
added?: boolean;
|
||||
removed?: boolean;
|
||||
value: string;
|
||||
count?: number;
|
||||
added?: boolean;
|
||||
removed?: boolean;
|
||||
value: string;
|
||||
}
|
||||
|
||||
|
||||
function diffPatternMatches(
|
||||
diffs: DiffType[],
|
||||
pattern: DiffPartType[],
|
||||
diffs: DiffType[],
|
||||
pattern: DiffPartType[],
|
||||
): boolean {
|
||||
if (diffs.length !== pattern.length) {
|
||||
return false;
|
||||
if (diffs.length !== pattern.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (let i = 0; i < diffs.length; i++) {
|
||||
const diff = diffs[i];
|
||||
const diffPartType: DiffPartType =
|
||||
!diff.added && !diff.removed ? "=" : diff.added ? "+" : "-";
|
||||
|
||||
if (diffPartType !== pattern[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < diffs.length; i++) {
|
||||
const diff = diffs[i];
|
||||
const diffPartType: DiffPartType =
|
||||
!diff.added && !diff.removed ? "=" : diff.added ? "+" : "-";
|
||||
|
||||
if (diffPartType !== pattern[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
return true;
|
||||
}
|
||||
|
||||
type DiffPartType = "+" | "-" | "=";
|
||||
|
||||
export function processSingleLineCompletion(
|
||||
lastLineOfCompletionText: string,
|
||||
currentText: string,
|
||||
cursorPosition: number
|
||||
lastLineOfCompletionText: string,
|
||||
currentText: string,
|
||||
cursorPosition: number,
|
||||
): SingleLineCompletionResult | undefined {
|
||||
const diffs: DiffType[] = Diff.diffWords(currentText, lastLineOfCompletionText);
|
||||
const diffs: DiffType[] = Diff.diffWords(
|
||||
currentText,
|
||||
lastLineOfCompletionText,
|
||||
);
|
||||
|
||||
if (diffPatternMatches(diffs, ["+"])) {
|
||||
// Just insert, we're already at the end of the line
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
diffPatternMatches(diffs, ["+", "="]) ||
|
||||
diffPatternMatches(diffs, ["+", "=", "+"])
|
||||
) {
|
||||
// The model repeated the text after the cursor to the end of the line
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
range: {
|
||||
start: cursorPosition,
|
||||
end: currentText.length + cursorPosition,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
diffPatternMatches(diffs, ["+", "-"]) ||
|
||||
diffPatternMatches(diffs, ["-", "+"])
|
||||
) {
|
||||
// We are midline and the model just inserted without repeating to the end of the line
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
};
|
||||
}
|
||||
|
||||
// For any other diff pattern, just use the first added part if available
|
||||
if (diffs[0]?.added) {
|
||||
return {
|
||||
completionText: diffs[0].value,
|
||||
};
|
||||
}
|
||||
|
||||
// Default case: treat as simple insertion
|
||||
if (diffPatternMatches(diffs, ["+"])) {
|
||||
// Just insert, we're already at the end of the line
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
completionText: lastLineOfCompletionText,
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
diffPatternMatches(diffs, ["+", "="]) ||
|
||||
diffPatternMatches(diffs, ["+", "=", "+"])
|
||||
) {
|
||||
// The model repeated the text after the cursor to the end of the line
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
range: {
|
||||
start: cursorPosition,
|
||||
end: currentText.length + cursorPosition,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
if (
|
||||
diffPatternMatches(diffs, ["+", "-"]) ||
|
||||
diffPatternMatches(diffs, ["-", "+"])
|
||||
) {
|
||||
// We are midline and the model just inserted without repeating to the end of the line
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
};
|
||||
}
|
||||
|
||||
// For any other diff pattern, just use the first added part if available
|
||||
if (diffs[0]?.added) {
|
||||
return {
|
||||
completionText: diffs[0].value,
|
||||
};
|
||||
}
|
||||
|
||||
// Default case: treat as simple insertion
|
||||
return {
|
||||
completionText: lastLineOfCompletionText,
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -19,14 +19,14 @@ const GenerateTerminalCommand: SlashCommand = {
|
|||
return;
|
||||
}
|
||||
|
||||
const gen =
|
||||
llm.streamComplete(`The user has made a request to run a shell command. Their description of what it should do is:
|
||||
const gen = llm.streamComplete(
|
||||
`The user has made a request to run a shell command. Their description of what it should do is:
|
||||
|
||||
"${input}"
|
||||
|
||||
Please write a shell command that will do what the user requested. Your output should consist of only the command itself, without any explanation or example output. Do not use any newlines. Only output the command that when inserted into the terminal will do precisely what was requested. Here is the command:`,
|
||||
new AbortController().signal
|
||||
);
|
||||
new AbortController().signal,
|
||||
);
|
||||
|
||||
const lines = streamLines(gen);
|
||||
let cmd = "";
|
||||
|
|
|
|||
|
|
@ -87,38 +87,40 @@ export class ProfileLifecycleManager {
|
|||
}
|
||||
|
||||
// Set pending config promise
|
||||
this.pendingConfigPromise = new Promise(async (resolve, reject) => {
|
||||
let result: ConfigResult<ContinueConfig>;
|
||||
// This try catch is expected to catch high-level errors that aren't block-specific
|
||||
// Like invalid json, invalid yaml, file read errors, etc.
|
||||
// NOT block-specific loading errors
|
||||
try {
|
||||
result = await this.profileLoader.doLoadConfig();
|
||||
} catch (e) {
|
||||
const message =
|
||||
e instanceof Error
|
||||
? `${e.message}\n${e.stack ? e.stack : ""}`
|
||||
: "Error loading config";
|
||||
result = {
|
||||
errors: [
|
||||
{
|
||||
fatal: true,
|
||||
message,
|
||||
},
|
||||
],
|
||||
config: undefined,
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
this.pendingConfigPromise = new Promise((resolve) => {
|
||||
void (async () => {
|
||||
let result: ConfigResult<ContinueConfig>;
|
||||
// This try catch is expected to catch high-level errors that aren't block-specific
|
||||
// Like invalid json, invalid yaml, file read errors, etc.
|
||||
// NOT block-specific loading errors
|
||||
try {
|
||||
result = await this.profileLoader.doLoadConfig();
|
||||
} catch (e) {
|
||||
const message =
|
||||
e instanceof Error
|
||||
? `${e.message}\n${e.stack ? e.stack : ""}`
|
||||
: "Error loading config";
|
||||
result = {
|
||||
errors: [
|
||||
{
|
||||
fatal: true,
|
||||
message,
|
||||
},
|
||||
],
|
||||
config: undefined,
|
||||
configLoadInterrupted: true,
|
||||
};
|
||||
}
|
||||
|
||||
if (result.config) {
|
||||
// Add registered context providers
|
||||
result.config.contextProviders = (
|
||||
result.config.contextProviders ?? []
|
||||
).concat(additionalContextProviders);
|
||||
}
|
||||
if (result.config) {
|
||||
// Add registered context providers
|
||||
result.config.contextProviders = (
|
||||
result.config.contextProviders ?? []
|
||||
).concat(additionalContextProviders);
|
||||
}
|
||||
|
||||
resolve(result);
|
||||
resolve(result);
|
||||
})();
|
||||
});
|
||||
|
||||
// Wait for the config promise to resolve
|
||||
|
|
|
|||
|
|
@ -46,12 +46,10 @@ import { useHub } from "../control-plane/env";
|
|||
import { BaseLLM } from "../llm";
|
||||
import { LLMClasses, llmFromDescription } from "../llm/llms";
|
||||
import CustomLLMClass from "../llm/llms/CustomLLM";
|
||||
import FreeTrial from "../llm/llms/FreeTrial";
|
||||
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 { allTools } from "../tools";
|
||||
import { copyOf } from "../util";
|
||||
import { GlobalContext } from "../util/GlobalContext";
|
||||
import mergeJson from "../util/merge";
|
||||
|
|
@ -67,6 +65,7 @@ import {
|
|||
} from "../util/paths";
|
||||
import { localPathToUri } from "../util/pathToUri";
|
||||
|
||||
import { baseToolDefinitions } from "../tools";
|
||||
import { modifyAnyConfigWithSharedConfig } from "./sharedConfig";
|
||||
import {
|
||||
getModelByRole,
|
||||
|
|
@ -244,7 +243,6 @@ async function intermediateToFinalConfig({
|
|||
llmLogger,
|
||||
workOsAccessToken,
|
||||
loadPromptFiles = true,
|
||||
allowFreeTrial = true,
|
||||
}: {
|
||||
config: Config;
|
||||
ide: IDE;
|
||||
|
|
@ -254,7 +252,6 @@ async function intermediateToFinalConfig({
|
|||
llmLogger: ILLMLogger;
|
||||
workOsAccessToken: string | undefined;
|
||||
loadPromptFiles?: boolean;
|
||||
allowFreeTrial?: boolean;
|
||||
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
const errors: ConfigValidationError[] = [];
|
||||
|
||||
|
|
@ -343,56 +340,43 @@ async function intermediateToFinalConfig({
|
|||
"summarize",
|
||||
]); // Default to chat role if not specified
|
||||
|
||||
if (allowFreeTrial) {
|
||||
// Obtain auth token (iff free trial being used)
|
||||
const freeTrialModels = models.filter(
|
||||
(model) => model.providerName === "free-trial",
|
||||
);
|
||||
if (freeTrialModels.length > 0) {
|
||||
const ghAuthToken = await ide.getGitHubAuthToken({});
|
||||
for (const model of freeTrialModels) {
|
||||
(model as FreeTrial).setupGhAuthToken(ghAuthToken);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Remove free trial models
|
||||
models = models.filter((model) => model.providerName !== "free-trial");
|
||||
// Free trial provider will be completely ignored
|
||||
let warnAboutFreeTrial = false;
|
||||
models = models.filter((model) => model.providerName !== "free-trial");
|
||||
if (models.filter((m) => m.providerName === "free-trial").length) {
|
||||
warnAboutFreeTrial = true;
|
||||
}
|
||||
|
||||
// Tab autocomplete model
|
||||
let tabAutocompleteModels: BaseLLM[] = [];
|
||||
const tabAutocompleteModels: BaseLLM[] = [];
|
||||
if (config.tabAutocompleteModel) {
|
||||
tabAutocompleteModels = (
|
||||
await Promise.all(
|
||||
(Array.isArray(config.tabAutocompleteModel)
|
||||
? config.tabAutocompleteModel
|
||||
: [config.tabAutocompleteModel]
|
||||
).map(async (desc) => {
|
||||
if ("title" in desc) {
|
||||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
config.completionOptions,
|
||||
);
|
||||
const autocompleteConfigs = Array.isArray(config.tabAutocompleteModel)
|
||||
? config.tabAutocompleteModel
|
||||
: [config.tabAutocompleteModel];
|
||||
|
||||
if (llm?.providerName === "free-trial") {
|
||||
if (!allowFreeTrial) {
|
||||
// This shouldn't happen
|
||||
throw new Error("Free trial cannot be used with control plane");
|
||||
}
|
||||
const ghAuthToken = await ide.getGitHubAuthToken({});
|
||||
(llm as FreeTrial).setupGhAuthToken(ghAuthToken);
|
||||
await Promise.all(
|
||||
autocompleteConfigs.map(async (desc) => {
|
||||
if ("title" in desc) {
|
||||
const llm = await llmFromDescription(
|
||||
desc,
|
||||
ide.readFile.bind(ide),
|
||||
uniqueId,
|
||||
ideSettings,
|
||||
llmLogger,
|
||||
config.completionOptions,
|
||||
);
|
||||
if (llm) {
|
||||
if (llm.providerName === "free-trial") {
|
||||
warnAboutFreeTrial = true;
|
||||
} else {
|
||||
tabAutocompleteModels.push(llm);
|
||||
}
|
||||
return llm;
|
||||
} else {
|
||||
return new CustomLLMClass(desc);
|
||||
}
|
||||
}),
|
||||
)
|
||||
).filter((x) => x !== undefined) as BaseLLM[];
|
||||
} else {
|
||||
tabAutocompleteModels.push(new CustomLLMClass(desc));
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
applyRequestOptionsToModels(tabAutocompleteModels, config);
|
||||
|
|
@ -458,7 +442,10 @@ async function intermediateToFinalConfig({
|
|||
return embedConfig;
|
||||
}
|
||||
const { provider, ...options } = embedConfig;
|
||||
if (provider === "transformers.js") {
|
||||
if (provider === "transformers.js" || provider === "free-trial") {
|
||||
if (provider === "free-trial") {
|
||||
warnAboutFreeTrial = true;
|
||||
}
|
||||
return new TransformersJsEmbeddingsProvider();
|
||||
} else {
|
||||
const cls = LLMClasses.find((c) => c.providerName === provider);
|
||||
|
|
@ -495,7 +482,10 @@ async function intermediateToFinalConfig({
|
|||
return rerankingConfig;
|
||||
}
|
||||
const { name, params } = config.reranker as RerankerDescription;
|
||||
|
||||
if (name === "free-trial") {
|
||||
warnAboutFreeTrial = true;
|
||||
return null;
|
||||
}
|
||||
if (name === "llm") {
|
||||
const llm = models.find((model) => model.title === params?.modelTitle);
|
||||
if (!llm) {
|
||||
|
|
@ -526,10 +516,18 @@ async function intermediateToFinalConfig({
|
|||
}
|
||||
const newReranker = getRerankingILLM(config.reranker);
|
||||
|
||||
if (warnAboutFreeTrial) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message:
|
||||
"Model provider 'free-trial' is no longer supported, will be ignored",
|
||||
});
|
||||
}
|
||||
|
||||
const continueConfig: ContinueConfig = {
|
||||
...config,
|
||||
contextProviders,
|
||||
tools: [...allTools],
|
||||
tools: [...baseToolDefinitions],
|
||||
mcpServerStatuses: [],
|
||||
slashCommands: config.slashCommands ?? [],
|
||||
modelsByRole: {
|
||||
|
|
@ -642,6 +640,7 @@ function llmToSerializedModelDescription(llm: ILLM): ModelDescription {
|
|||
capabilities: llm.capabilities,
|
||||
roles: llm.roles,
|
||||
configurationStatus: llm.getConfigurationStatus(),
|
||||
apiKeyLocation: llm.apiKeyLocation,
|
||||
};
|
||||
}
|
||||
|
||||
|
|
|
|||
241
core/config/loadLocalAssistants.test.ts
Normal file
241
core/config/loadLocalAssistants.test.ts
Normal file
|
|
@ -0,0 +1,241 @@
|
|||
import { walkDirCache } from "../indexing/walkDir";
|
||||
import { testIde } from "../test/fixtures";
|
||||
import { addToTestDir, setUpTestDir, tearDownTestDir } from "../test/testDir";
|
||||
import {
|
||||
getAllDotContinueDefinitionFiles,
|
||||
LoadAssistantFilesOptions,
|
||||
} from "./loadLocalAssistants";
|
||||
describe("getAllDotContinueDefinitionFiles with fileExtType option", () => {
|
||||
beforeEach(() => {
|
||||
setUpTestDir();
|
||||
walkDirCache.invalidate();
|
||||
|
||||
// Add test files to the test directory
|
||||
addToTestDir([
|
||||
".continue/assistants/",
|
||||
[".continue/assistants/assistant1.yaml", "yaml content 1"],
|
||||
[".continue/assistants/assistant2.yml", "yaml content 2"],
|
||||
[".continue/assistants/assistant3.md", "markdown content 1"],
|
||||
[".continue/assistants/assistant4.txt", "txt content"],
|
||||
]);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
tearDownTestDir();
|
||||
walkDirCache.invalidate();
|
||||
});
|
||||
|
||||
it("should return only YAML files when fileExtType is 'yaml'", async () => {
|
||||
const options: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false, // Only test workspace for simplicity
|
||||
includeWorkspace: true,
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const result = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
options,
|
||||
"assistants",
|
||||
);
|
||||
expect(result).toHaveLength(2);
|
||||
expect(result.map((f) => f.path.split("/").pop())).toEqual(
|
||||
expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
|
||||
);
|
||||
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"assistant3.md",
|
||||
);
|
||||
});
|
||||
|
||||
it("should return only Markdown files when fileExtType is 'markdown'", async () => {
|
||||
const options: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
fileExtType: "markdown",
|
||||
};
|
||||
|
||||
const result = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
options,
|
||||
"assistants",
|
||||
);
|
||||
expect(result).toHaveLength(1);
|
||||
expect(result.map((f) => f.path.split("/").pop())).toEqual([
|
||||
"assistant3.md",
|
||||
]);
|
||||
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"assistant1.yaml",
|
||||
);
|
||||
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"assistant2.yml",
|
||||
);
|
||||
});
|
||||
|
||||
it("should return all supported files when fileExtType is not specified", async () => {
|
||||
const options: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
// fileExtType not specified
|
||||
};
|
||||
|
||||
const result = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
options,
|
||||
"assistants",
|
||||
);
|
||||
expect(result).toHaveLength(3);
|
||||
expect(result.map((f) => f.path.split("/").pop())).toEqual(
|
||||
expect.arrayContaining([
|
||||
"assistant1.yaml",
|
||||
"assistant2.yml",
|
||||
"assistant3.md",
|
||||
]),
|
||||
);
|
||||
// Should not include .txt files
|
||||
expect(result.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"assistant4.txt",
|
||||
);
|
||||
});
|
||||
|
||||
it("should respect includeWorkspace option with fileExtType", async () => {
|
||||
// Test with includeWorkspace: false
|
||||
const workspaceOffOptions: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: false,
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const noWorkspaceResult = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
workspaceOffOptions,
|
||||
"assistants",
|
||||
);
|
||||
expect(noWorkspaceResult).toHaveLength(0);
|
||||
|
||||
// Test with includeWorkspace: true
|
||||
const workspaceOnOptions: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const workspaceResult = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
workspaceOnOptions,
|
||||
"assistants",
|
||||
);
|
||||
expect(workspaceResult).toHaveLength(2);
|
||||
expect(workspaceResult.map((f) => f.path.split("/").pop())).toEqual(
|
||||
expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
|
||||
);
|
||||
});
|
||||
|
||||
it("should return empty array when no files match the specified extension type", async () => {
|
||||
// Create a test directory with only non-matching files
|
||||
tearDownTestDir();
|
||||
walkDirCache.invalidate();
|
||||
setUpTestDir();
|
||||
addToTestDir([
|
||||
".continue/assistants/",
|
||||
[".continue/assistants/nonmatch1.txt", "txt content"],
|
||||
[".continue/assistants/nonmatch2.json", "json content"],
|
||||
]);
|
||||
|
||||
const options: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const result = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
options,
|
||||
"assistants",
|
||||
);
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should handle directories that don't exist", async () => {
|
||||
// Create a clean test directory without the assistants folder
|
||||
tearDownTestDir();
|
||||
setUpTestDir();
|
||||
|
||||
const options: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const result = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
options,
|
||||
"assistants",
|
||||
);
|
||||
expect(result).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should return correct file content", async () => {
|
||||
const options: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const result = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
options,
|
||||
"assistants",
|
||||
);
|
||||
expect(result).toHaveLength(2);
|
||||
const yamlFile = result.find((f) => f.path.includes("assistant1.yaml"));
|
||||
expect(yamlFile?.content).toBe("yaml content 1");
|
||||
});
|
||||
|
||||
it("should filter by file extension case sensitively", async () => {
|
||||
// Add files with uppercase extensions
|
||||
addToTestDir([
|
||||
[".continue/assistants/assistant5.YAML", "uppercase yaml"],
|
||||
[".continue/assistants/assistant6.YML", "uppercase yml"],
|
||||
[".continue/assistants/assistant7.MD", "uppercase md"],
|
||||
]);
|
||||
|
||||
const yamlOptions: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
fileExtType: "yaml",
|
||||
};
|
||||
|
||||
const yamlResult = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
yamlOptions,
|
||||
"assistants",
|
||||
);
|
||||
// Should only get lowercase extensions (current implementation)
|
||||
expect(yamlResult).toHaveLength(2);
|
||||
expect(yamlResult.map((f) => f.path.split("/").pop())).toEqual(
|
||||
expect.arrayContaining(["assistant1.yaml", "assistant2.yml"]),
|
||||
);
|
||||
expect(yamlResult.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"assistant5.YAML",
|
||||
);
|
||||
|
||||
const markdownOptions: LoadAssistantFilesOptions = {
|
||||
includeGlobal: false,
|
||||
includeWorkspace: true,
|
||||
fileExtType: "markdown",
|
||||
};
|
||||
|
||||
const markdownResult = await getAllDotContinueDefinitionFiles(
|
||||
testIde,
|
||||
markdownOptions,
|
||||
"assistants",
|
||||
);
|
||||
expect(markdownResult).toHaveLength(1);
|
||||
expect(markdownResult.map((f) => f.path.split("/").pop())).toEqual([
|
||||
"assistant3.md",
|
||||
]);
|
||||
expect(markdownResult.map((f) => f.path.split("/").pop())).not.toContain(
|
||||
"assistant7.MD",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
import ignore from "ignore";
|
||||
import * as URI from "uri-js";
|
||||
import { IDE } from "..";
|
||||
import {
|
||||
DEFAULT_IGNORE_DIRS,
|
||||
|
|
@ -12,18 +13,19 @@ import { joinPathsToUri } from "../util/uri";
|
|||
export const ASSISTANTS = "assistants";
|
||||
export const ASSISTANTS_FOLDER = `.continue/${ASSISTANTS}`;
|
||||
|
||||
export function isLocalAssistantFile(uri: string): boolean {
|
||||
export function isLocalDefinitionFile(uri: string): boolean {
|
||||
if (!uri.endsWith(".yaml") && !uri.endsWith(".yml") && !uri.endsWith(".md")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const normalizedUri = uri.replace(/\\/g, "/");
|
||||
const normalizedUri = URI.normalize(uri);
|
||||
return normalizedUri.includes(`/${ASSISTANTS_FOLDER}/`);
|
||||
}
|
||||
|
||||
async function getDefinitionFilesInDir(
|
||||
ide: IDE,
|
||||
dir: string,
|
||||
fileExtType?: "yaml" | "markdown",
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
try {
|
||||
const exists = await ide.fileExists(dir);
|
||||
|
|
@ -40,9 +42,19 @@ async function getDefinitionFilesInDir(
|
|||
overrideDefaultIgnores,
|
||||
source: "get assistant files",
|
||||
});
|
||||
const assistantFilePaths = uris.filter(
|
||||
(p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"),
|
||||
);
|
||||
let assistantFilePaths: string[];
|
||||
if (fileExtType === "yaml") {
|
||||
assistantFilePaths = uris.filter(
|
||||
(p) => p.endsWith(".yaml") || p.endsWith(".yml"),
|
||||
);
|
||||
} else if (fileExtType === "markdown") {
|
||||
assistantFilePaths = uris.filter((p) => p.endsWith(".md"));
|
||||
} else {
|
||||
assistantFilePaths = uris.filter(
|
||||
(p) => p.endsWith(".yaml") || p.endsWith(".yml") || p.endsWith(".md"),
|
||||
);
|
||||
}
|
||||
|
||||
const results = assistantFilePaths.map(async (uri) => {
|
||||
const content = await ide.readFile(uri); // make a try catch
|
||||
return { path: uri, content };
|
||||
|
|
@ -57,6 +69,7 @@ async function getDefinitionFilesInDir(
|
|||
export interface LoadAssistantFilesOptions {
|
||||
includeGlobal: boolean;
|
||||
includeWorkspace: boolean;
|
||||
fileExtType?: "yaml" | "markdown";
|
||||
}
|
||||
|
||||
export function getDotContinueSubDirs(
|
||||
|
|
@ -84,7 +97,7 @@ export function getDotContinueSubDirs(
|
|||
|
||||
/**
|
||||
* This method searches in both ~/.continue and workspace .continue
|
||||
* for all YAML files in the specified subdirctory, for example .continue/assistants or .continue/prompts
|
||||
* for all YAML/Markdown files in the specified subdirectory, for example .continue/assistants or .continue/prompts
|
||||
*/
|
||||
export async function getAllDotContinueDefinitionFiles(
|
||||
ide: IDE,
|
||||
|
|
@ -101,15 +114,14 @@ export async function getAllDotContinueDefinitionFiles(
|
|||
subDirName,
|
||||
);
|
||||
|
||||
// Get all assistant files from the directories
|
||||
const assistantFiles = (
|
||||
await Promise.all(fullDirs.map((dir) => getDefinitionFilesInDir(ide, dir)))
|
||||
// Get all definition files from the directories
|
||||
const definitionFiles = (
|
||||
await Promise.all(
|
||||
fullDirs.map((dir) =>
|
||||
getDefinitionFilesInDir(ide, dir, options.fileExtType),
|
||||
),
|
||||
)
|
||||
).flat();
|
||||
|
||||
return await Promise.all(
|
||||
assistantFiles.map(async (file) => {
|
||||
const content = await ide.readFile(file.path);
|
||||
return { path: file.path, content };
|
||||
}),
|
||||
);
|
||||
return definitionFiles;
|
||||
}
|
||||
|
|
|
|||
157
core/config/markdown/createMarkdownRule.test.ts
Normal file
157
core/config/markdown/createMarkdownRule.test.ts
Normal file
|
|
@ -0,0 +1,157 @@
|
|||
import {
|
||||
createMarkdownWithFrontmatter,
|
||||
createRuleFilePath,
|
||||
createRuleMarkdown,
|
||||
sanitizeRuleName,
|
||||
} from "./createMarkdownRule";
|
||||
import { parseMarkdownRule } from "./parseMarkdownRule";
|
||||
|
||||
describe("sanitizeRuleName", () => {
|
||||
it("should sanitize rule names for filenames", () => {
|
||||
expect(sanitizeRuleName("My Test Rule")).toBe("my-test-rule");
|
||||
expect(sanitizeRuleName("Rule with @#$% chars")).toBe("rule-with-chars");
|
||||
expect(sanitizeRuleName("Multiple spaces")).toBe("multiple-spaces");
|
||||
expect(sanitizeRuleName("UPPERCASE-rule")).toBe("uppercase-rule");
|
||||
expect(sanitizeRuleName("already-sanitized")).toBe("already-sanitized");
|
||||
});
|
||||
|
||||
it("should handle empty and edge case inputs", () => {
|
||||
expect(sanitizeRuleName("")).toBe("");
|
||||
expect(sanitizeRuleName(" ")).toBe("");
|
||||
expect(sanitizeRuleName("123")).toBe("123");
|
||||
expect(sanitizeRuleName("rule-with-numbers-123")).toBe(
|
||||
"rule-with-numbers-123",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createRuleFilePath", () => {
|
||||
it("should create correct rule file path", () => {
|
||||
const result = createRuleFilePath("/workspace", "My Test Rule");
|
||||
expect(result).toBe("/workspace/.continue/rules/my-test-rule.md");
|
||||
});
|
||||
|
||||
it("should handle special characters in rule name", () => {
|
||||
const result = createRuleFilePath("/home/user", "Rule with @#$% chars");
|
||||
expect(result).toBe("/home/user/.continue/rules/rule-with-chars.md");
|
||||
});
|
||||
|
||||
it("should handle edge case rule names", () => {
|
||||
const result = createRuleFilePath("/test", " Multiple Spaces ");
|
||||
expect(result).toBe("/test/.continue/rules/multiple-spaces.md");
|
||||
});
|
||||
});
|
||||
|
||||
describe("createMarkdownWithFrontmatter", () => {
|
||||
it("should create properly formatted markdown with frontmatter", () => {
|
||||
const frontmatter = {
|
||||
name: "Test Rule",
|
||||
description: "A test rule",
|
||||
globs: "*.ts",
|
||||
};
|
||||
const markdown = "# Test Rule\n\nThis is a test rule.";
|
||||
|
||||
const result = createMarkdownWithFrontmatter(frontmatter, markdown);
|
||||
|
||||
// The exact quote style doesn't matter as long as it parses correctly
|
||||
expect(result).toContain("name: Test Rule");
|
||||
expect(result).toContain("description: A test rule");
|
||||
expect(result).toContain("globs:");
|
||||
expect(result).toContain("*.ts");
|
||||
expect(result).toContain("---\n\n# Test Rule\n\nThis is a test rule.");
|
||||
});
|
||||
|
||||
it("should handle empty frontmatter", () => {
|
||||
const frontmatter = {};
|
||||
const markdown = "# Simple Rule\n\nJust markdown content.";
|
||||
|
||||
const result = createMarkdownWithFrontmatter(frontmatter, markdown);
|
||||
|
||||
const expected = `---
|
||||
{}
|
||||
---
|
||||
|
||||
# Simple Rule
|
||||
|
||||
Just markdown content.`;
|
||||
|
||||
expect(result).toBe(expected);
|
||||
});
|
||||
|
||||
it("should create content that can be parsed back correctly", () => {
|
||||
const originalFrontmatter = {
|
||||
name: "Roundtrip Test",
|
||||
description: "Testing roundtrip parsing",
|
||||
globs: ["*.js", "*.ts"],
|
||||
alwaysApply: true,
|
||||
};
|
||||
const originalMarkdown =
|
||||
"# Roundtrip Test\n\nThis should parse back correctly.";
|
||||
|
||||
const created = createMarkdownWithFrontmatter(
|
||||
originalFrontmatter,
|
||||
originalMarkdown,
|
||||
);
|
||||
const parsed = parseMarkdownRule(created);
|
||||
|
||||
expect(parsed.frontmatter).toEqual(originalFrontmatter);
|
||||
expect(parsed.markdown).toBe(originalMarkdown);
|
||||
});
|
||||
});
|
||||
|
||||
describe("createRuleMarkdown", () => {
|
||||
it("should create rule markdown with all options", () => {
|
||||
const result = createRuleMarkdown("Test Rule", "This is the rule content", {
|
||||
description: "Test description",
|
||||
globs: ["*.ts", "*.js"],
|
||||
alwaysApply: true,
|
||||
});
|
||||
|
||||
const parsed = parseMarkdownRule(result);
|
||||
|
||||
expect(parsed.frontmatter.description).toBe("Test description");
|
||||
expect(parsed.frontmatter.globs).toEqual(["*.ts", "*.js"]);
|
||||
expect(parsed.frontmatter.alwaysApply).toBe(true);
|
||||
expect(parsed.markdown).toBe("# Test Rule\n\nThis is the rule content");
|
||||
});
|
||||
|
||||
it("should create rule markdown with minimal options", () => {
|
||||
const result = createRuleMarkdown("Simple Rule", "Simple content");
|
||||
|
||||
const parsed = parseMarkdownRule(result);
|
||||
|
||||
expect(parsed.frontmatter.description).toBeUndefined();
|
||||
expect(parsed.frontmatter.globs).toBeUndefined();
|
||||
expect(parsed.frontmatter.alwaysApply).toBeUndefined();
|
||||
expect(parsed.markdown).toBe("# Simple Rule\n\nSimple content");
|
||||
});
|
||||
|
||||
it("should handle string globs", () => {
|
||||
const result = createRuleMarkdown("String Glob Rule", "Content", {
|
||||
globs: "*.py",
|
||||
});
|
||||
|
||||
const parsed = parseMarkdownRule(result);
|
||||
expect(parsed.frontmatter.globs).toBe("*.py");
|
||||
});
|
||||
|
||||
it("should trim description and globs", () => {
|
||||
const result = createRuleMarkdown("Trim Test", "Content", {
|
||||
description: " spaced description ",
|
||||
globs: " *.ts ",
|
||||
});
|
||||
|
||||
const parsed = parseMarkdownRule(result);
|
||||
expect(parsed.frontmatter.description).toBe("spaced description");
|
||||
expect(parsed.frontmatter.globs).toBe("*.ts");
|
||||
});
|
||||
|
||||
it("should handle alwaysApply false explicitly", () => {
|
||||
const result = createRuleMarkdown("Always Apply False", "Content", {
|
||||
alwaysApply: false,
|
||||
});
|
||||
|
||||
const parsed = parseMarkdownRule(result);
|
||||
expect(parsed.frontmatter.alwaysApply).toBe(false);
|
||||
});
|
||||
});
|
||||
75
core/config/markdown/createMarkdownRule.ts
Normal file
75
core/config/markdown/createMarkdownRule.ts
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
import * as YAML from "yaml";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
import { RuleFrontmatter } from "./parseMarkdownRule";
|
||||
|
||||
export const RULE_FILE_EXTENSION = "md";
|
||||
|
||||
/**
|
||||
* Sanitizes a rule name for use in filenames (removes special chars, replaces spaces with dashes)
|
||||
*/
|
||||
export function sanitizeRuleName(name: string): string {
|
||||
return name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9\s-]/g, "")
|
||||
.replace(/\s+/g, "-")
|
||||
.replace(/^-+|-+$/g, ""); // Remove leading/trailing dashes
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates the file path for a rule in the workspace .continue/rules directory
|
||||
*/
|
||||
export function createRuleFilePath(
|
||||
workspaceDir: string,
|
||||
ruleName: string,
|
||||
): string {
|
||||
const safeRuleName = sanitizeRuleName(ruleName);
|
||||
return joinPathsToUri(
|
||||
workspaceDir,
|
||||
".continue",
|
||||
"rules",
|
||||
`${safeRuleName}.${RULE_FILE_EXTENSION}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates markdown content with YAML frontmatter in the format expected by parseMarkdownRule
|
||||
*/
|
||||
export function createMarkdownWithFrontmatter(
|
||||
frontmatter: RuleFrontmatter,
|
||||
markdown: string,
|
||||
): string {
|
||||
const frontmatterStr = YAML.stringify(frontmatter).trim();
|
||||
return `---\n${frontmatterStr}\n---\n\n${markdown}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a rule markdown file content from rule components
|
||||
*/
|
||||
export function createRuleMarkdown(
|
||||
name: string,
|
||||
ruleContent: string,
|
||||
options: {
|
||||
description?: string;
|
||||
globs?: string | string[];
|
||||
alwaysApply?: boolean;
|
||||
} = {},
|
||||
): string {
|
||||
const frontmatter: RuleFrontmatter = {};
|
||||
|
||||
if (options.globs) {
|
||||
frontmatter.globs =
|
||||
typeof options.globs === "string" ? options.globs.trim() : options.globs;
|
||||
}
|
||||
|
||||
if (options.description) {
|
||||
frontmatter.description = options.description.trim();
|
||||
}
|
||||
|
||||
if (options.alwaysApply !== undefined) {
|
||||
frontmatter.alwaysApply = options.alwaysApply;
|
||||
}
|
||||
|
||||
const markdownBody = `# ${name}\n\n${ruleContent}`;
|
||||
|
||||
return createMarkdownWithFrontmatter(frontmatter, markdownBody);
|
||||
}
|
||||
3
core/config/markdown/index.ts
Normal file
3
core/config/markdown/index.ts
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
export * from "./createMarkdownRule";
|
||||
export * from "./loadMarkdownRules";
|
||||
export * from "./parseMarkdownRule";
|
||||
50
core/config/markdown/loadCodebaseRules.ts
Normal file
50
core/config/markdown/loadCodebaseRules.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import { ConfigValidationError } from "@continuedev/config-yaml";
|
||||
import { IDE, RuleWithSource } from "../..";
|
||||
import { walkDirs } from "../../indexing/walkDir";
|
||||
import { RULES_MARKDOWN_FILENAME } from "../../llm/rules/constants";
|
||||
import { getUriPathBasename } from "../../util/uri";
|
||||
import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
|
||||
|
||||
/**
|
||||
* Loads rules from rules.md files colocated in the codebase
|
||||
*/
|
||||
export async function loadCodebaseRules(ide: IDE): Promise<{
|
||||
rules: RuleWithSource[];
|
||||
errors: ConfigValidationError[];
|
||||
}> {
|
||||
const errors: ConfigValidationError[] = [];
|
||||
const rules: RuleWithSource[] = [];
|
||||
|
||||
try {
|
||||
// Get all files from the workspace
|
||||
const allFiles = await walkDirs(ide);
|
||||
|
||||
// Filter to just rules.md files
|
||||
const rulesMdFiles = allFiles.filter((file) => {
|
||||
const filename = getUriPathBasename(file);
|
||||
return filename === RULES_MARKDOWN_FILENAME;
|
||||
});
|
||||
|
||||
// Process each rules.md file
|
||||
for (const filePath of rulesMdFiles) {
|
||||
try {
|
||||
const content = await ide.readFile(filePath);
|
||||
const rule = convertMarkdownRuleToContinueRule(filePath, content);
|
||||
|
||||
rules.push(rule);
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Failed to parse colocated rule file ${filePath}: ${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Error loading colocated rule files: ${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
}
|
||||
|
||||
return { rules, errors };
|
||||
}
|
||||
161
core/config/markdown/loadCodebaseRules.vitest.ts
Normal file
161
core/config/markdown/loadCodebaseRules.vitest.ts
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { IDE } from "../..";
|
||||
import { walkDirs } from "../../indexing/walkDir";
|
||||
import { loadCodebaseRules } from "./loadCodebaseRules";
|
||||
import { convertMarkdownRuleToContinueRule } from "./parseMarkdownRule";
|
||||
|
||||
// Mock dependencies
|
||||
vi.mock("../../indexing/walkDir", () => ({
|
||||
walkDirs: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("./parseMarkdownRule", () => ({
|
||||
convertMarkdownRuleToContinueRule: vi.fn(),
|
||||
}));
|
||||
|
||||
describe("loadCodebaseRules", () => {
|
||||
// Mock IDE with properly typed mock functions
|
||||
const mockIde = {
|
||||
readFile: vi.fn() as unknown as IDE["readFile"] & {
|
||||
mockImplementation: Function;
|
||||
},
|
||||
} as unknown as IDE;
|
||||
|
||||
// Setup test files
|
||||
const mockFiles = [
|
||||
"src/rules.md",
|
||||
"src/redux/rules.md",
|
||||
"src/components/rules.md",
|
||||
"src/utils/helper.ts", // Non-rules file
|
||||
".continue/rules.md", // This should also be loaded
|
||||
];
|
||||
|
||||
// Mock rule content
|
||||
const mockRuleContent: Record<string, string> = {
|
||||
"src/rules.md": "# General Rules\nFollow coding standards",
|
||||
"src/redux/rules.md":
|
||||
'---\nglobs: "**/*.{ts,tsx}"\n---\n# Redux Rules\nUse Redux Toolkit',
|
||||
"src/components/rules.md":
|
||||
'---\nglobs: ["**/*.tsx", "**/*.jsx"]\n---\n# Component Rules\nUse functional components',
|
||||
".continue/rules.md": "# Global Rules\nFollow project guidelines",
|
||||
};
|
||||
|
||||
// Mock converted rules
|
||||
const mockConvertedRules: Record<string, any> = {
|
||||
"src/rules.md": {
|
||||
name: "General Rules",
|
||||
rule: "Follow coding standards",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/rules.md",
|
||||
},
|
||||
"src/redux/rules.md": {
|
||||
name: "Redux Rules",
|
||||
rule: "Use Redux Toolkit",
|
||||
globs: "**/*.{ts,tsx}",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/redux/rules.md",
|
||||
},
|
||||
"src/components/rules.md": {
|
||||
name: "Component Rules",
|
||||
rule: "Use functional components",
|
||||
globs: ["**/*.tsx", "**/*.jsx"],
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
},
|
||||
".continue/rules.md": {
|
||||
name: "Global Rules",
|
||||
rule: "Follow project guidelines",
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
},
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
// Setup mocks
|
||||
vi.resetAllMocks();
|
||||
|
||||
// Mock walkDirs to return our test files
|
||||
(walkDirs as any).mockResolvedValue(mockFiles);
|
||||
|
||||
// Mock readFile to return content based on path
|
||||
(mockIde.readFile as any).mockImplementation((path: string) => {
|
||||
return Promise.resolve(mockRuleContent[path] || "");
|
||||
});
|
||||
|
||||
// Mock convertMarkdownRuleToContinueRule to return converted rules
|
||||
(convertMarkdownRuleToContinueRule as any).mockImplementation(
|
||||
(path: string, content: string) => {
|
||||
return mockConvertedRules[path];
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.resetAllMocks();
|
||||
});
|
||||
it("should load rules from all rules.md files in the workspace", async () => {
|
||||
const { rules, errors } = await loadCodebaseRules(mockIde);
|
||||
|
||||
// Should find all rules.md files
|
||||
expect(walkDirs).toHaveBeenCalledWith(mockIde);
|
||||
|
||||
// Should read all rules.md files
|
||||
expect(mockIde.readFile).toHaveBeenCalledTimes(4);
|
||||
expect(mockIde.readFile).toHaveBeenCalledWith("src/rules.md");
|
||||
expect(mockIde.readFile).toHaveBeenCalledWith("src/redux/rules.md");
|
||||
expect(mockIde.readFile).toHaveBeenCalledWith("src/components/rules.md");
|
||||
expect(mockIde.readFile).toHaveBeenCalledWith(".continue/rules.md");
|
||||
|
||||
// Should convert all rules
|
||||
expect(convertMarkdownRuleToContinueRule).toHaveBeenCalledTimes(4);
|
||||
|
||||
// Should return all rules
|
||||
expect(rules).toHaveLength(4);
|
||||
expect(rules).toContainEqual(mockConvertedRules["src/rules.md"]);
|
||||
expect(rules).toContainEqual(mockConvertedRules["src/redux/rules.md"]);
|
||||
expect(rules).toContainEqual(mockConvertedRules["src/components/rules.md"]);
|
||||
expect(rules).toContainEqual(mockConvertedRules[".continue/rules.md"]);
|
||||
|
||||
// Should not have errors
|
||||
expect(errors).toHaveLength(0);
|
||||
});
|
||||
|
||||
it("should handle errors when reading a rule file", async () => {
|
||||
// Setup mock to throw for a specific file
|
||||
(mockIde.readFile as any).mockImplementation((path: string) => {
|
||||
if (path === "src/redux/rules.md") {
|
||||
return Promise.reject(new Error("Failed to read file"));
|
||||
}
|
||||
return Promise.resolve(mockRuleContent[path] || "");
|
||||
});
|
||||
|
||||
const { rules, errors } = await loadCodebaseRules(mockIde);
|
||||
|
||||
// Should still return other rules
|
||||
expect(rules).toHaveLength(3);
|
||||
expect(rules).toContainEqual(mockConvertedRules["src/rules.md"]);
|
||||
expect(rules).toContainEqual(mockConvertedRules["src/components/rules.md"]);
|
||||
expect(rules).toContainEqual(mockConvertedRules[".continue/rules.md"]);
|
||||
|
||||
// Should have one error
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(errors[0].message).toContain(
|
||||
"Failed to parse colocated rule file src/redux/rules.md",
|
||||
);
|
||||
});
|
||||
|
||||
it("should handle errors when walkDirs fails", async () => {
|
||||
// Setup mock to throw
|
||||
(walkDirs as any).mockRejectedValue(
|
||||
new Error("Failed to walk directories"),
|
||||
);
|
||||
const { rules, errors } = await loadCodebaseRules(mockIde);
|
||||
|
||||
// Should return no rules
|
||||
expect(rules).toHaveLength(0);
|
||||
|
||||
// Should have one error
|
||||
expect(errors).toHaveLength(1);
|
||||
expect(errors[0].message).toContain("Error loading colocated rule files");
|
||||
});
|
||||
});
|
||||
|
|
@ -17,7 +17,7 @@ export async function loadMarkdownRules(ide: IDE): Promise<{
|
|||
// Get all .md files from .continue/rules
|
||||
const markdownFiles = await getAllDotContinueDefinitionFiles(
|
||||
ide,
|
||||
{ includeGlobal: true, includeWorkspace: true },
|
||||
{ includeGlobal: true, includeWorkspace: true, fileExtType: "markdown" },
|
||||
"rules",
|
||||
);
|
||||
|
||||
|
|
|
|||
391
core/config/markdown/ruleCollocationApplication.vitest.ts
Normal file
391
core/config/markdown/ruleCollocationApplication.vitest.ts
Normal file
|
|
@ -0,0 +1,391 @@
|
|||
import path from "path";
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
ContextItemId,
|
||||
ContextItemWithId,
|
||||
RuleWithSource,
|
||||
UserChatMessage,
|
||||
} from "../..";
|
||||
|
||||
import { getApplicableRules } from "../../llm/rules/getSystemMessageWithRules";
|
||||
|
||||
describe("Rule Colocation Application", () => {
|
||||
// Create a set of rules in different directories
|
||||
const rules: RuleWithSource[] = [
|
||||
// Root level rule - should apply everywhere
|
||||
{
|
||||
name: "Root Rule",
|
||||
rule: "Follow project standards",
|
||||
source: "rules-block",
|
||||
ruleFile: ".continue/rules.md",
|
||||
},
|
||||
|
||||
// Nested directory rule without globs - should only apply to files in that directory
|
||||
{
|
||||
name: "React Components Rule",
|
||||
rule: "Use functional components with hooks",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
// No explicit globs - should implicitly only apply to files in that directory
|
||||
},
|
||||
|
||||
// Nested directory rule with explicit globs - should apply to matching files only
|
||||
{
|
||||
name: "Redux Rule",
|
||||
rule: "Use Redux Toolkit for state management",
|
||||
globs: "src/redux/**/*.{ts,tsx}",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/redux/rules.md",
|
||||
},
|
||||
|
||||
// Directory rule with specific file extension glob
|
||||
{
|
||||
name: "TypeScript Components Rule",
|
||||
rule: "Use TypeScript with React components",
|
||||
globs: "**/*.tsx", // Only apply to .tsx files
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
},
|
||||
|
||||
// Rule for a specific subdirectory with its own glob
|
||||
{
|
||||
name: "API Utils Rule",
|
||||
rule: "Follow API utility conventions",
|
||||
globs: "**/*.ts", // Only TypeScript files in this directory
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/api/rules.md",
|
||||
},
|
||||
];
|
||||
|
||||
// Mock user message and context for various scenarios
|
||||
let userMessageWithComponentFile: UserChatMessage;
|
||||
let userMessageWithReduxFile: UserChatMessage;
|
||||
let userMessageWithRootFile: UserChatMessage;
|
||||
let userMessageWithApiUtilFile: UserChatMessage;
|
||||
let userMessageWithComponentJsxFile: UserChatMessage;
|
||||
|
||||
let componentTsxContextItem: ContextItemWithId;
|
||||
let componentJsxContextItem: ContextItemWithId;
|
||||
let reduxContextItem: ContextItemWithId;
|
||||
let rootContextItem: ContextItemWithId;
|
||||
let apiUtilContextItem: ContextItemWithId;
|
||||
let otherUtilContextItem: ContextItemWithId;
|
||||
|
||||
beforeEach(() => {
|
||||
// Setup user messages with different code blocks
|
||||
userMessageWithComponentFile = {
|
||||
role: "user",
|
||||
content:
|
||||
"Can you help me with this component file?\n```tsx src/components/Button.tsx\nexport const Button = () => {...}\n```",
|
||||
};
|
||||
|
||||
userMessageWithComponentJsxFile = {
|
||||
role: "user",
|
||||
content:
|
||||
"Can you help me with this JSX component file?\n```jsx src/components/OldButton.jsx\nexport const OldButton = () => {...}\n```",
|
||||
};
|
||||
|
||||
userMessageWithReduxFile = {
|
||||
role: "user",
|
||||
content:
|
||||
'Can you help with this redux slice?\n```ts src/redux/userSlice.ts\nimport { createSlice } from "@reduxjs/toolkit";\n```',
|
||||
};
|
||||
|
||||
userMessageWithRootFile = {
|
||||
role: "user",
|
||||
content:
|
||||
"Can you help with this utility file?\n```ts src/utils/helpers.ts\nexport const formatDate = (date) => {...}\n```",
|
||||
};
|
||||
|
||||
userMessageWithApiUtilFile = {
|
||||
role: "user",
|
||||
content:
|
||||
"Can you help with this API utility file?\n```ts src/utils/api/requests.ts\nexport const fetchData = () => {...}\n```",
|
||||
};
|
||||
|
||||
// Setup context items
|
||||
componentTsxContextItem = {
|
||||
id: { providerTitle: "file", itemId: "context1" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/components/Button.tsx" },
|
||||
content: "export const Button = () => {...}",
|
||||
name: "Button.tsx",
|
||||
description: "Component file",
|
||||
};
|
||||
|
||||
componentJsxContextItem = {
|
||||
id: { providerTitle: "file", itemId: "context1b" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/components/OldButton.jsx" },
|
||||
content: "export const OldButton = () => {...}",
|
||||
name: "OldButton.jsx",
|
||||
description: "Component file",
|
||||
};
|
||||
|
||||
reduxContextItem = {
|
||||
id: { providerTitle: "file", itemId: "context2" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/redux/userSlice.ts" },
|
||||
content: 'import { createSlice } from "@reduxjs/toolkit";',
|
||||
name: "userSlice.ts",
|
||||
description: "Redux slice",
|
||||
};
|
||||
|
||||
rootContextItem = {
|
||||
id: { providerTitle: "file", itemId: "context3" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/utils/helpers.ts" },
|
||||
content: "export const formatDate = (date) => {...}",
|
||||
name: "helpers.ts",
|
||||
description: "Utility file",
|
||||
};
|
||||
|
||||
apiUtilContextItem = {
|
||||
id: { providerTitle: "file", itemId: "context4" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/utils/api/requests.ts" },
|
||||
content: "export const fetchData = () => {...}",
|
||||
name: "requests.ts",
|
||||
description: "API utility file",
|
||||
};
|
||||
|
||||
otherUtilContextItem = {
|
||||
id: { providerTitle: "file", itemId: "context5" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/utils/format.ts" },
|
||||
content: "export const formatCurrency = (amount) => {...}",
|
||||
name: "format.ts",
|
||||
description: "Formatting utility",
|
||||
};
|
||||
});
|
||||
|
||||
describe("Basic directory-specific rule application", () => {
|
||||
it("should apply root rules to all files", () => {
|
||||
// Test with component file
|
||||
let applicableRules = getApplicableRules(
|
||||
userMessageWithComponentFile,
|
||||
rules,
|
||||
[componentTsxContextItem],
|
||||
);
|
||||
expect(applicableRules.map((r) => r.name)).toContain("Root Rule");
|
||||
|
||||
// Test with redux file
|
||||
applicableRules = getApplicableRules(userMessageWithReduxFile, rules, [
|
||||
reduxContextItem,
|
||||
]);
|
||||
expect(applicableRules.map((r) => r.name)).toContain("Root Rule");
|
||||
|
||||
// Test with root-level file
|
||||
applicableRules = getApplicableRules(userMessageWithRootFile, rules, [
|
||||
rootContextItem,
|
||||
]);
|
||||
expect(applicableRules.map((r) => r.name)).toContain("Root Rule");
|
||||
});
|
||||
});
|
||||
|
||||
describe("Directory-specific rule application with implied globs", () => {
|
||||
it("should only apply component rules to files in the component directory when no globs specified", () => {
|
||||
// Create a rule without explicit globs but with a file path in the components directory
|
||||
const impliedComponentRule: RuleWithSource = {
|
||||
name: "Implied Components Rule",
|
||||
rule: "Use React component best practices",
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
// No explicit globs - should infer from directory
|
||||
};
|
||||
|
||||
// Test with component file - should apply the rule
|
||||
let applicableRules = getApplicableRules(
|
||||
userMessageWithComponentFile,
|
||||
[impliedComponentRule],
|
||||
[componentTsxContextItem],
|
||||
);
|
||||
expect(applicableRules.map((r) => r.name)).toContain(
|
||||
"Implied Components Rule",
|
||||
);
|
||||
|
||||
// Test with redux file - should NOT apply the component rule
|
||||
// This is failing currently - we need to fix the implementation
|
||||
applicableRules = getApplicableRules(
|
||||
userMessageWithReduxFile,
|
||||
[impliedComponentRule],
|
||||
[reduxContextItem],
|
||||
);
|
||||
|
||||
// THIS WILL FAIL - Current implementation doesn't restrict by directory
|
||||
expect(applicableRules.map((r) => r.name)).not.toContain(
|
||||
"Implied Components Rule",
|
||||
);
|
||||
|
||||
// Test with root-level file - should NOT apply the component rule
|
||||
// This is failing currently - we need to fix the implementation
|
||||
applicableRules = getApplicableRules(
|
||||
userMessageWithRootFile,
|
||||
[impliedComponentRule],
|
||||
[rootContextItem],
|
||||
);
|
||||
|
||||
// THIS WILL FAIL - Current implementation doesn't restrict by directory
|
||||
expect(applicableRules.map((r) => r.name)).not.toContain(
|
||||
"Implied Components Rule",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Combined directory and glob pattern matching", () => {
|
||||
it("should respect directory + glob pattern when both are present", () => {
|
||||
// Create a rule with explicit glob in a nested directory
|
||||
const typescriptComponentRule: RuleWithSource = {
|
||||
name: "TypeScript Component Rule",
|
||||
rule: "Use TypeScript with React components",
|
||||
globs: "**/*.tsx", // Only apply to .tsx files
|
||||
source: "rules-block",
|
||||
ruleFile: "src/components/rules.md",
|
||||
};
|
||||
|
||||
// Test with TSX component file - should apply
|
||||
let applicableRules = getApplicableRules(
|
||||
userMessageWithComponentFile,
|
||||
[typescriptComponentRule],
|
||||
[componentTsxContextItem],
|
||||
);
|
||||
expect(applicableRules.map((r) => r.name)).toContain(
|
||||
"TypeScript Component Rule",
|
||||
);
|
||||
|
||||
// Test with JSX component file - should NOT apply (wrong extension)
|
||||
// This test is likely to pass even with current implementation since the glob is explicit
|
||||
applicableRules = getApplicableRules(
|
||||
userMessageWithComponentJsxFile,
|
||||
[typescriptComponentRule],
|
||||
[componentJsxContextItem],
|
||||
);
|
||||
expect(applicableRules.map((r) => r.name)).not.toContain(
|
||||
"TypeScript Component Rule",
|
||||
);
|
||||
|
||||
// Test with TS file outside components directory - should NOT apply
|
||||
// This test will fail because current implementation doesn't consider directory boundaries
|
||||
applicableRules = getApplicableRules(
|
||||
userMessageWithReduxFile,
|
||||
[typescriptComponentRule],
|
||||
[reduxContextItem],
|
||||
);
|
||||
|
||||
// THIS WILL FAIL - Current impl only checks file extension, not directory
|
||||
expect(applicableRules.map((r) => r.name)).not.toContain(
|
||||
"TypeScript Component Rule",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Nested directory rules with globs", () => {
|
||||
it("should apply API utils rule only to files in that directory matching the glob", () => {
|
||||
// Create a rule for a specific subdirectory with its own glob
|
||||
const apiUtilsRule: RuleWithSource = {
|
||||
name: "API Utils Rule",
|
||||
rule: "Follow API utility conventions",
|
||||
globs: "**/*.ts", // Only TypeScript files in this directory
|
||||
source: "rules-block",
|
||||
ruleFile: "src/utils/api/rules.md",
|
||||
};
|
||||
|
||||
// Test with file in the API utils directory - should apply
|
||||
let applicableRules = getApplicableRules(
|
||||
userMessageWithApiUtilFile,
|
||||
[apiUtilsRule],
|
||||
[apiUtilContextItem],
|
||||
);
|
||||
expect(applicableRules.map((r) => r.name)).toContain("API Utils Rule");
|
||||
|
||||
// Test with TS file in general utils directory - should NOT apply
|
||||
// This test will fail because current implementation doesn't consider directory boundaries
|
||||
applicableRules = getApplicableRules(
|
||||
userMessageWithRootFile,
|
||||
[apiUtilsRule],
|
||||
[rootContextItem],
|
||||
);
|
||||
|
||||
// THIS WILL FAIL - Current impl only checks file extension, not directory
|
||||
expect(applicableRules.map((r) => r.name)).not.toContain(
|
||||
"API Utils Rule",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe("Rule application inference strategy", () => {
|
||||
it("should infer directory-specific glob patterns from rule file location", () => {
|
||||
// This test will propose the expected behavior for the feature:
|
||||
// When a rules.md file is colocated in a directory without explicit globs,
|
||||
// it should automatically create an implicit glob pattern for that directory.
|
||||
|
||||
function createRuleWithAutomaticGlobInference(
|
||||
ruleFilePath: string,
|
||||
): RuleWithSource {
|
||||
const directory = path.dirname(ruleFilePath);
|
||||
// The expected behavior would be to create an implicit glob like this:
|
||||
const expectedGlob = `${directory}/**/*`;
|
||||
|
||||
return {
|
||||
name: `Inferred Rule for ${directory}`,
|
||||
rule: `Follow standards for ${directory}`,
|
||||
source: "rules-block",
|
||||
ruleFile: ruleFilePath,
|
||||
// In a fixed implementation, these globs would be automatically inferred
|
||||
// globs: expectedGlob,
|
||||
};
|
||||
}
|
||||
|
||||
// Create rules for different directories
|
||||
const modelsRule = createRuleWithAutomaticGlobInference(
|
||||
"src/models/rules.md",
|
||||
);
|
||||
const servicesRule = createRuleWithAutomaticGlobInference(
|
||||
"src/services/rules.md",
|
||||
);
|
||||
|
||||
// Create context items for different files
|
||||
const modelFileContext: ContextItemWithId = {
|
||||
id: { providerTitle: "file", itemId: "models1" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/models/user.ts" },
|
||||
content: "export interface User {...}",
|
||||
name: "user.ts",
|
||||
description: "User model",
|
||||
};
|
||||
|
||||
const serviceFileContext: ContextItemWithId = {
|
||||
id: { providerTitle: "file", itemId: "services1" } as ContextItemId,
|
||||
uri: { type: "file", value: "src/services/auth.ts" },
|
||||
content: "export const login = () => {...}",
|
||||
name: "auth.ts",
|
||||
description: "Auth service",
|
||||
};
|
||||
|
||||
// Test with model file - should apply only the models rule
|
||||
const applicableModelsRules = getApplicableRules(
|
||||
undefined, // No user message needed
|
||||
[modelsRule, servicesRule],
|
||||
[modelFileContext],
|
||||
);
|
||||
|
||||
// These assertions will fail with current implementation
|
||||
// but represent the desired behavior
|
||||
expect(applicableModelsRules.map((r) => r.name)).toContain(
|
||||
"Inferred Rule for src/models",
|
||||
);
|
||||
expect(applicableModelsRules.map((r) => r.name)).not.toContain(
|
||||
"Inferred Rule for src/services",
|
||||
);
|
||||
|
||||
// Test with service file - should apply only the services rule
|
||||
const applicableServicesRules = getApplicableRules(
|
||||
undefined, // No user message needed
|
||||
[modelsRule, servicesRule],
|
||||
[serviceFileContext],
|
||||
);
|
||||
|
||||
// These assertions will fail with current implementation
|
||||
// but represent the desired behavior
|
||||
expect(applicableServicesRules.map((r) => r.name)).not.toContain(
|
||||
"Inferred Rule for src/models",
|
||||
);
|
||||
expect(applicableServicesRules.map((r) => r.name)).toContain(
|
||||
"Inferred Rule for src/services",
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,6 +1,5 @@
|
|||
import { ConfigYaml } from "@continuedev/config-yaml";
|
||||
|
||||
export const TRIAL_FIM_MODEL = "codestral-latest";
|
||||
export const LOCAL_ONBOARDING_PROVIDER_TITLE = "Ollama";
|
||||
export const LOCAL_ONBOARDING_FIM_MODEL = "qwen2.5-coder:1.5b-base";
|
||||
export const LOCAL_ONBOARDING_FIM_TITLE = "Qwen2.5-Coder 1.5B";
|
||||
|
|
@ -9,6 +8,21 @@ export const LOCAL_ONBOARDING_CHAT_TITLE = "Llama 3.1 8B";
|
|||
export const LOCAL_ONBOARDING_EMBEDDINGS_MODEL = "nomic-embed-text:latest";
|
||||
export const LOCAL_ONBOARDING_EMBEDDINGS_TITLE = "Nomic Embed";
|
||||
|
||||
const ANTHROPIC_MODEL_CONFIG = {
|
||||
slugs: ["anthropic/claude-3-7-sonnet", "anthropic/claude-4-sonnet"],
|
||||
apiKeyInputName: "ANTHROPIC_API_KEY",
|
||||
};
|
||||
const OPENAI_MODEL_CONFIG = {
|
||||
slugs: ["openai/gpt-4.1", "openai/o3", "openai/gpt-4.1-mini"],
|
||||
apiKeyInputName: "OPENAI_API_KEY",
|
||||
};
|
||||
|
||||
// TODO: These need updating on the hub
|
||||
const GEMINI_MODEL_CONFIG = {
|
||||
slugs: ["google/gemini-2.5-pro", "google/gemini-2.0-flash"],
|
||||
apiKeyInputName: "GEMINI_API_KEY",
|
||||
};
|
||||
|
||||
/**
|
||||
* We set the "best" chat + autocopmlete models by default
|
||||
* whenever a user doesn't have a config.json
|
||||
|
|
@ -50,3 +64,45 @@ export function setupLocalConfig(config: ConfigYaml): ConfigYaml {
|
|||
export function setupQuickstartConfig(config: ConfigYaml): ConfigYaml {
|
||||
return config;
|
||||
}
|
||||
|
||||
export function setupProviderConfig(
|
||||
config: ConfigYaml,
|
||||
provider: string,
|
||||
apiKey: string,
|
||||
): ConfigYaml {
|
||||
let newModels;
|
||||
|
||||
switch (provider) {
|
||||
case "openai":
|
||||
newModels = OPENAI_MODEL_CONFIG.slugs.map((slug) => ({
|
||||
uses: slug,
|
||||
with: {
|
||||
[OPENAI_MODEL_CONFIG.apiKeyInputName]: apiKey,
|
||||
},
|
||||
}));
|
||||
break;
|
||||
case "anthropic":
|
||||
newModels = ANTHROPIC_MODEL_CONFIG.slugs.map((slug) => ({
|
||||
uses: slug,
|
||||
with: {
|
||||
[ANTHROPIC_MODEL_CONFIG.apiKeyInputName]: apiKey,
|
||||
},
|
||||
}));
|
||||
break;
|
||||
case "gemini":
|
||||
newModels = GEMINI_MODEL_CONFIG.slugs.map((slug) => ({
|
||||
uses: slug,
|
||||
with: {
|
||||
[GEMINI_MODEL_CONFIG.apiKeyInputName]: apiKey,
|
||||
},
|
||||
}));
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unknown provider: ${provider}`);
|
||||
}
|
||||
|
||||
return {
|
||||
...config,
|
||||
models: [...(config.models ?? []), ...newModels],
|
||||
};
|
||||
}
|
||||
|
|
|
|||
|
|
@ -14,29 +14,52 @@ import {
|
|||
IDE,
|
||||
IdeSettings,
|
||||
ILLMLogger,
|
||||
RuleWithSource,
|
||||
SerializedContinueConfig,
|
||||
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";
|
||||
import { ControlPlaneProxyInfo } from "../../control-plane/analytics/IAnalyticsProvider.js";
|
||||
import { ControlPlaneClient } from "../../control-plane/client.js";
|
||||
import { getControlPlaneEnv } from "../../control-plane/env.js";
|
||||
import { TeamAnalytics } from "../../control-plane/TeamAnalytics.js";
|
||||
import ContinueProxy from "../../llm/llms/stubs/ContinueProxy";
|
||||
import { getConfigDependentToolDefinitions } from "../../tools";
|
||||
import { encodeMCPToolUri } from "../../tools/callTool";
|
||||
import { getMCPToolName } from "../../tools/mcpToolName";
|
||||
import { getConfigJsonPath, getConfigYamlPath } from "../../util/paths";
|
||||
import { localPathOrUriToPath } from "../../util/pathToUri";
|
||||
import { Telemetry } from "../../util/posthog";
|
||||
import { TTS } from "../../util/tts";
|
||||
import { getWorkspaceContinueRuleDotFiles } from "../getWorkspaceContinueRuleDotFiles";
|
||||
import { loadContinueConfigFromJson } from "../load";
|
||||
import { loadCodebaseRules } from "../markdown/loadCodebaseRules";
|
||||
import { loadMarkdownRules } from "../markdown/loadMarkdownRules";
|
||||
import { migrateJsonSharedConfig } from "../migrateSharedConfig";
|
||||
import { rectifySelectedModelsFromGlobalContext } from "../selectedModels";
|
||||
import { loadContinueConfigFromYaml } from "../yaml/loadYaml";
|
||||
|
||||
async function loadRules(ide: IDE) {
|
||||
const rules: RuleWithSource[] = [];
|
||||
const errors = [];
|
||||
|
||||
// Add rules from .continuerules files
|
||||
const { rules: yamlRules, errors: continueRulesErrors } =
|
||||
await getWorkspaceContinueRuleDotFiles(ide);
|
||||
rules.unshift(...yamlRules);
|
||||
errors.push(...continueRulesErrors);
|
||||
|
||||
// Add rules from markdown files in .continue/rules
|
||||
const { rules: markdownRules, errors: markdownRulesErrors } =
|
||||
await loadMarkdownRules(ide);
|
||||
rules.unshift(...markdownRules);
|
||||
errors.push(...markdownRulesErrors);
|
||||
|
||||
return { rules, errors };
|
||||
}
|
||||
export default async function doLoadConfig(options: {
|
||||
ide: IDE;
|
||||
ideSettingsPromise: Promise<IdeSettings>;
|
||||
|
|
@ -123,17 +146,17 @@ export default async function doLoadConfig(options: {
|
|||
// Remove ability have undefined errors, just have an array
|
||||
errors = [...(errors ?? [])];
|
||||
|
||||
// Add rules from .continuerules files
|
||||
const { rules, errors: continueRulesErrors } =
|
||||
await getWorkspaceContinueRuleDotFiles(ide);
|
||||
// Load rules and always include the RulesContextProvider
|
||||
const { rules, errors: rulesErrors } = await loadRules(ide);
|
||||
errors.push(...rulesErrors);
|
||||
newConfig.rules.unshift(...rules);
|
||||
errors.push(...continueRulesErrors);
|
||||
newConfig.contextProviders.push(new RulesContextProvider({}));
|
||||
|
||||
// Add rules from markdown files in .continue/rules
|
||||
const { rules: markdownRules, errors: markdownRulesErrors } =
|
||||
await loadMarkdownRules(ide);
|
||||
newConfig.rules.unshift(...markdownRules);
|
||||
errors.push(...markdownRulesErrors);
|
||||
// Add rules from colocated rules.md files in the codebase
|
||||
const { rules: codebaseRules, errors: codebaseRulesErrors } =
|
||||
await loadCodebaseRules(ide);
|
||||
newConfig.rules.unshift(...codebaseRules);
|
||||
errors.push(...codebaseRulesErrors);
|
||||
|
||||
// Rectify model selections for each role
|
||||
newConfig = rectifySelectedModelsFromGlobalContext(newConfig, profileId);
|
||||
|
|
@ -155,7 +178,7 @@ export default async function doLoadConfig(options: {
|
|||
displayTitle: server.name + " " + tool.name,
|
||||
function: {
|
||||
description: tool.description,
|
||||
name: tool.name,
|
||||
name: getMCPToolName(server, tool),
|
||||
parameters: tool.inputSchema,
|
||||
},
|
||||
faviconUrl: server.faviconUrl,
|
||||
|
|
@ -163,6 +186,7 @@ export default async function doLoadConfig(options: {
|
|||
type: "function" as const,
|
||||
uri: encodeMCPToolUri(server.id, tool.name),
|
||||
group: server.name,
|
||||
originalFunctionName: tool.name,
|
||||
}));
|
||||
newConfig.tools.push(...serverTools);
|
||||
|
||||
|
|
@ -176,12 +200,21 @@ export default async function doLoadConfig(options: {
|
|||
);
|
||||
newConfig.slashCommands.push(...serverSlashCommands);
|
||||
|
||||
const submenuItems = server.resources.map((resource) => ({
|
||||
title: resource.name,
|
||||
description: resource.description ?? resource.name,
|
||||
id: resource.uri,
|
||||
icon: server.faviconUrl,
|
||||
}));
|
||||
const submenuItems = server.resources
|
||||
.map((resource) => ({
|
||||
title: resource.name,
|
||||
description: resource.description ?? resource.name,
|
||||
id: resource.uri,
|
||||
icon: server.faviconUrl,
|
||||
}))
|
||||
.concat(
|
||||
server.resourceTemplates.map((template) => ({
|
||||
title: template.name,
|
||||
description: template.description ?? template.name,
|
||||
id: template.uriTemplate,
|
||||
icon: server.faviconUrl,
|
||||
})),
|
||||
);
|
||||
if (submenuItems.length > 0) {
|
||||
const serverContextProvider = new MCPContextProvider({
|
||||
submenuItems,
|
||||
|
|
@ -193,6 +226,12 @@ export default async function doLoadConfig(options: {
|
|||
}
|
||||
}
|
||||
|
||||
newConfig.tools.push(
|
||||
...getConfigDependentToolDefinitions({
|
||||
rules: newConfig.rules,
|
||||
}),
|
||||
);
|
||||
|
||||
// Detect duplicate tool names
|
||||
const counts: Record<string, number> = {};
|
||||
newConfig.tools.forEach((tool) => {
|
||||
|
|
@ -202,6 +241,7 @@ export default async function doLoadConfig(options: {
|
|||
counts[tool.function.name] = 1;
|
||||
}
|
||||
});
|
||||
|
||||
Object.entries(counts).forEach(([toolName, count]) => {
|
||||
if (count > 1) {
|
||||
errors!.push({
|
||||
|
|
@ -211,6 +251,26 @@ export default async function doLoadConfig(options: {
|
|||
}
|
||||
});
|
||||
|
||||
const ruleCounts: Record<string, number> = {};
|
||||
newConfig.rules.forEach((rule) => {
|
||||
if (rule.name) {
|
||||
if (ruleCounts[rule.name]) {
|
||||
ruleCounts[rule.name] = ruleCounts[rule.name] + 1;
|
||||
} else {
|
||||
ruleCounts[rule.name] = 1;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Object.entries(ruleCounts).forEach(([ruleName, count]) => {
|
||||
if (count > 1) {
|
||||
errors!.push({
|
||||
fatal: false,
|
||||
message: `Duplicate (${count}) rules named "${ruleName}" detected. This may cause unexpected behavior`,
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
newConfig.allowAnonymousTelemetry =
|
||||
newConfig.allowAnonymousTelemetry && (await ide.isTelemetryEnabled());
|
||||
|
||||
|
|
|
|||
|
|
@ -743,8 +743,6 @@ declare global {
|
|||
|
||||
getLastModified(files: string[]): Promise<{ [path: string]: number }>;
|
||||
|
||||
getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined>;
|
||||
|
||||
// LSP
|
||||
gotoDefinition(location: Location): Promise<RangeInFile[]>;
|
||||
|
||||
|
|
|
|||
344
core/config/usesFreeTrialApiKey.test.ts
Normal file
344
core/config/usesFreeTrialApiKey.test.ts
Normal file
|
|
@ -0,0 +1,344 @@
|
|||
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();
|
||||
});
|
||||
35
core/config/usesFreeTrialApiKey.ts
Normal file
35
core/config/usesFreeTrialApiKey.ts
Normal file
|
|
@ -0,0 +1,35 @@
|
|||
import { decodeSecretLocation, SecretType } from "@continuedev/config-yaml";
|
||||
import { BrowserSerializedContinueConfig } from "..";
|
||||
|
||||
/**
|
||||
* Helper function to determine if the config uses a free trial API key
|
||||
* @param config The serialized config object
|
||||
* @returns true if the config is using any free trial models
|
||||
*/
|
||||
export function usesFreeTrialApiKey(
|
||||
config: BrowserSerializedContinueConfig | null,
|
||||
): boolean {
|
||||
if (!config) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if the currently selected chat model uses free-trial provider
|
||||
const modelsByRole = config.modelsByRole;
|
||||
const allModels = [...Object.values(modelsByRole)].flat();
|
||||
|
||||
// Check if any of the chat models use free-trial provider
|
||||
try {
|
||||
const hasFreeTrial = allModels?.some(
|
||||
(model) =>
|
||||
model.apiKeyLocation &&
|
||||
decodeSecretLocation(model.apiKeyLocation).secretType ===
|
||||
SecretType.FreeTrial,
|
||||
);
|
||||
|
||||
return hasFreeTrial;
|
||||
} catch (e) {
|
||||
console.error("Error checking for free trial API key:", e);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
170
core/config/workspace/workspaceBlocks.test.ts
Normal file
170
core/config/workspace/workspaceBlocks.test.ts
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
import { BlockType } from "@continuedev/config-yaml";
|
||||
import { describe, expect, test } from "@jest/globals";
|
||||
import { RULE_FILE_EXTENSION } from "../markdown";
|
||||
import { findAvailableFilename, getFileContent } from "./workspaceBlocks";
|
||||
|
||||
describe("getFileContent", () => {
|
||||
test("returns markdown content for rules block type", () => {
|
||||
const result = getFileContent("rules");
|
||||
expect(result).toContain("# New Rule");
|
||||
expect(result).toContain("Your rule content");
|
||||
expect(result).toContain("A description of your rule");
|
||||
});
|
||||
|
||||
test("returns YAML content for non-rules block types", () => {
|
||||
const result = getFileContent("models");
|
||||
expect(result).toContain("name: New model");
|
||||
expect(result).toContain("version: 0.0.1");
|
||||
expect(result).toContain("schema: v1");
|
||||
expect(result).toContain("models:");
|
||||
expect(result).toContain("provider: anthropic");
|
||||
});
|
||||
|
||||
test("generates correct YAML for different block types", () => {
|
||||
const contextResult = getFileContent("context");
|
||||
expect(contextResult).toContain("name: New context");
|
||||
expect(contextResult).toContain("context:");
|
||||
expect(contextResult).toContain("provider: file");
|
||||
|
||||
const docsResult = getFileContent("docs");
|
||||
expect(docsResult).toContain("name: New doc");
|
||||
expect(docsResult).toContain("docs:");
|
||||
expect(docsResult).toContain("startUrl: https://docs.continue.dev");
|
||||
|
||||
const promptsResult = getFileContent("prompts");
|
||||
expect(promptsResult).toContain("name: New prompt");
|
||||
expect(promptsResult).toContain("prompts:");
|
||||
expect(promptsResult).toContain("thorough suite of unit tests");
|
||||
|
||||
const mcpResult = getFileContent("mcpServers");
|
||||
expect(mcpResult).toContain("name: New MCP server");
|
||||
expect(mcpResult).toContain("mcpServers:");
|
||||
expect(mcpResult).toContain("command: npx");
|
||||
});
|
||||
});
|
||||
|
||||
describe("findAvailableFilename", () => {
|
||||
test("returns base filename when it doesn't exist", async () => {
|
||||
const mockFileExists = async (uri: string) => false;
|
||||
|
||||
const result = await findAvailableFilename(
|
||||
"/workspace/.continue/models",
|
||||
"models",
|
||||
mockFileExists,
|
||||
);
|
||||
|
||||
expect(result).toBe("/workspace/.continue/models/new-model.yaml");
|
||||
});
|
||||
|
||||
test("returns filename with counter when base exists", async () => {
|
||||
const mockFileExists = async (uri: string) => {
|
||||
return uri === "/workspace/.continue/models/new-model.yaml";
|
||||
};
|
||||
|
||||
const result = await findAvailableFilename(
|
||||
"/workspace/.continue/models",
|
||||
"models",
|
||||
mockFileExists,
|
||||
);
|
||||
|
||||
expect(result).toBe("/workspace/.continue/models/new-model-1.yaml");
|
||||
});
|
||||
|
||||
test("increments counter until available filename is found", async () => {
|
||||
const existingFiles = new Set([
|
||||
"/workspace/.continue/context/new-context.yaml",
|
||||
"/workspace/.continue/context/new-context-1.yaml",
|
||||
"/workspace/.continue/context/new-context-2.yaml",
|
||||
]);
|
||||
|
||||
const mockFileExists = async (uri: string) => {
|
||||
return existingFiles.has(uri);
|
||||
};
|
||||
|
||||
const result = await findAvailableFilename(
|
||||
"/workspace/.continue/context",
|
||||
"context",
|
||||
mockFileExists,
|
||||
);
|
||||
|
||||
expect(result).toBe("/workspace/.continue/context/new-context-3.yaml");
|
||||
});
|
||||
|
||||
test("handles different block types correctly with proper extensions", async () => {
|
||||
const mockFileExists = async (uri: string) => false;
|
||||
|
||||
const testCases: Array<{ blockType: BlockType; expected: string }> = [
|
||||
{ blockType: "models", expected: "/test/new-model.yaml" },
|
||||
{ blockType: "context", expected: "/test/new-context.yaml" },
|
||||
{ blockType: "rules", expected: `/test/new-rule.${RULE_FILE_EXTENSION}` },
|
||||
{ blockType: "docs", expected: "/test/new-doc.yaml" },
|
||||
{ blockType: "prompts", expected: "/test/new-prompt.yaml" },
|
||||
{ blockType: "mcpServers", expected: "/test/new-mcp-server.yaml" },
|
||||
];
|
||||
|
||||
for (const { blockType, expected } of testCases) {
|
||||
const result = await findAvailableFilename(
|
||||
"/test",
|
||||
blockType,
|
||||
mockFileExists,
|
||||
);
|
||||
expect(result).toBe(expected);
|
||||
}
|
||||
});
|
||||
|
||||
test("respects custom extension parameter", async () => {
|
||||
const mockFileExists = async (uri: string) => false;
|
||||
|
||||
const result = await findAvailableFilename(
|
||||
"/test",
|
||||
"models",
|
||||
mockFileExists,
|
||||
"json",
|
||||
);
|
||||
|
||||
expect(result).toBe("/test/new-model.json");
|
||||
});
|
||||
|
||||
test("handles rules markdown files with counter", async () => {
|
||||
const existingFiles = new Set([
|
||||
`/workspace/.continue/rules/new-rule.${RULE_FILE_EXTENSION}`,
|
||||
`/workspace/.continue/rules/new-rule-1.${RULE_FILE_EXTENSION}`,
|
||||
]);
|
||||
|
||||
const mockFileExists = async (uri: string) => {
|
||||
return existingFiles.has(uri);
|
||||
};
|
||||
|
||||
const result = await findAvailableFilename(
|
||||
"/workspace/.continue/rules",
|
||||
"rules",
|
||||
mockFileExists,
|
||||
);
|
||||
|
||||
expect(result).toBe(
|
||||
`/workspace/.continue/rules/new-rule-2.${RULE_FILE_EXTENSION}`,
|
||||
);
|
||||
});
|
||||
|
||||
test("handles large counter values", async () => {
|
||||
const existingFiles = new Set(
|
||||
Array.from({ length: 100 }, (_, i) =>
|
||||
i === 0
|
||||
? "/workspace/.continue/prompts/new-prompt.yaml"
|
||||
: `/workspace/.continue/prompts/new-prompt-${i}.yaml`,
|
||||
),
|
||||
);
|
||||
|
||||
const mockFileExists = async (uri: string) => {
|
||||
return existingFiles.has(uri);
|
||||
};
|
||||
|
||||
const result = await findAvailableFilename(
|
||||
"/workspace/.continue/prompts",
|
||||
"prompts",
|
||||
mockFileExists,
|
||||
);
|
||||
|
||||
expect(result).toBe("/workspace/.continue/prompts/new-prompt-100.yaml");
|
||||
});
|
||||
});
|
||||
|
|
@ -2,10 +2,24 @@ import { BlockType, ConfigYaml } from "@continuedev/config-yaml";
|
|||
import * as YAML from "yaml";
|
||||
import { IDE } from "../..";
|
||||
import { joinPathsToUri } from "../../util/uri";
|
||||
import { RULE_FILE_EXTENSION, createRuleMarkdown } from "../markdown";
|
||||
|
||||
const BLOCK_TYPE_CONFIG: Record<
|
||||
BlockType,
|
||||
{ singular: string; filename: string }
|
||||
> = {
|
||||
context: { singular: "context", filename: "context" },
|
||||
models: { singular: "model", filename: "model" },
|
||||
rules: { singular: "rule", filename: "rule" },
|
||||
docs: { singular: "doc", filename: "doc" },
|
||||
prompts: { singular: "prompt", filename: "prompt" },
|
||||
mcpServers: { singular: "MCP server", filename: "mcp-server" },
|
||||
data: { singular: "data", filename: "data" },
|
||||
};
|
||||
|
||||
function getContentsForNewBlock(blockType: BlockType): ConfigYaml {
|
||||
const configYaml: ConfigYaml = {
|
||||
name: `New ${blockType.slice(0, -1)}`,
|
||||
name: `New ${BLOCK_TYPE_CONFIG[blockType]?.singular}`,
|
||||
version: "0.0.1",
|
||||
schema: "v1",
|
||||
};
|
||||
|
|
@ -64,6 +78,43 @@ function getContentsForNewBlock(blockType: BlockType): ConfigYaml {
|
|||
return configYaml;
|
||||
}
|
||||
|
||||
function getFileExtension(blockType: BlockType): string {
|
||||
return blockType === "rules" ? RULE_FILE_EXTENSION : "yaml";
|
||||
}
|
||||
|
||||
export function getFileContent(blockType: BlockType): string {
|
||||
if (blockType === "rules") {
|
||||
return createRuleMarkdown("New Rule", "Your rule content", {
|
||||
description: "A description of your rule",
|
||||
});
|
||||
} else {
|
||||
return YAML.stringify(getContentsForNewBlock(blockType));
|
||||
}
|
||||
}
|
||||
|
||||
export async function findAvailableFilename(
|
||||
baseDirUri: string,
|
||||
blockType: BlockType,
|
||||
fileExists: (uri: string) => Promise<boolean>,
|
||||
extension?: string,
|
||||
): Promise<string> {
|
||||
const baseFilename = `new-${BLOCK_TYPE_CONFIG[blockType]?.filename}`;
|
||||
const fileExtension = extension ?? getFileExtension(blockType);
|
||||
let counter = 0;
|
||||
let fileUri: string;
|
||||
|
||||
do {
|
||||
const suffix = counter === 0 ? "" : `-${counter}`;
|
||||
fileUri = joinPathsToUri(
|
||||
baseDirUri,
|
||||
`${baseFilename}${suffix}.${fileExtension}`,
|
||||
);
|
||||
counter++;
|
||||
} while (await fileExists(fileUri));
|
||||
|
||||
return fileUri;
|
||||
}
|
||||
|
||||
export async function createNewWorkspaceBlockFile(
|
||||
ide: IDE,
|
||||
blockType: BlockType,
|
||||
|
|
@ -77,21 +128,14 @@ export async function createNewWorkspaceBlockFile(
|
|||
|
||||
const baseDirUri = joinPathsToUri(workspaceDirs[0], `.continue/${blockType}`);
|
||||
|
||||
// Find the first available filename
|
||||
let counter = 0;
|
||||
let fileUri: string;
|
||||
do {
|
||||
const suffix = counter === 0 ? "" : `-${counter}`;
|
||||
fileUri = joinPathsToUri(
|
||||
baseDirUri,
|
||||
`new-${blockType.slice(0, -1)}${suffix}.yaml`,
|
||||
);
|
||||
counter++;
|
||||
} while (await ide.fileExists(fileUri));
|
||||
|
||||
await ide.writeFile(
|
||||
fileUri,
|
||||
YAML.stringify(getContentsForNewBlock(blockType)),
|
||||
const fileUri = await findAvailableFilename(
|
||||
baseDirUri,
|
||||
blockType,
|
||||
ide.fileExists.bind(ide),
|
||||
);
|
||||
|
||||
const fileContent = getFileContent(blockType);
|
||||
|
||||
await ide.writeFile(fileUri, fileContent);
|
||||
await ide.openFile(fileUri);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,12 +17,16 @@ export class LocalPlatformClient implements PlatformClient {
|
|||
private readonly ide: IDE,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* searches for the first valid secret file in order of ~/.continue/.env, <workspace>/.continue/.env, <workspace>/.env
|
||||
*/
|
||||
private async findSecretInEnvFiles(
|
||||
fqsn: FQSN,
|
||||
): Promise<SecretResult | undefined> {
|
||||
const secretValue =
|
||||
this.findSecretInLocalEnvFile(fqsn) ??
|
||||
(await this.findSecretInWorkspaceEnvFiles(fqsn));
|
||||
(await this.findSecretInWorkspaceEnvFiles(fqsn, true)) ??
|
||||
(await this.findSecretInWorkspaceEnvFiles(fqsn, false));
|
||||
|
||||
if (secretValue) {
|
||||
return {
|
||||
|
|
@ -52,12 +56,16 @@ export class LocalPlatformClient implements PlatformClient {
|
|||
|
||||
private async findSecretInWorkspaceEnvFiles(
|
||||
fqsn: FQSN,
|
||||
insideContinue: boolean,
|
||||
): Promise<string | undefined> {
|
||||
try {
|
||||
const workspaceDirs = await this.ide.getWorkspaceDirs();
|
||||
|
||||
for (const folder of workspaceDirs) {
|
||||
const envFilePath = joinPathsToUri(folder, ".env");
|
||||
const envFilePath = joinPathsToUri(
|
||||
folder,
|
||||
insideContinue ? ".continue" : "",
|
||||
".env",
|
||||
);
|
||||
try {
|
||||
const fileExists = await this.ide.fileExists(envFilePath);
|
||||
if (fileExists) {
|
||||
|
|
|
|||
233
core/config/yaml/LocalPlatformClient.vitest.ts
Normal file
233
core/config/yaml/LocalPlatformClient.vitest.ts
Normal file
|
|
@ -0,0 +1,233 @@
|
|||
import { FQSN, SecretResult, SecretType } from "@continuedev/config-yaml";
|
||||
import {
|
||||
afterEach,
|
||||
beforeEach,
|
||||
describe,
|
||||
expect,
|
||||
Mock,
|
||||
test,
|
||||
vi,
|
||||
} from "vitest";
|
||||
import { IDE } from "../..";
|
||||
import { ControlPlaneClient } from "../../control-plane/client";
|
||||
import { LocalPlatformClient } from "./LocalPlatformClient";
|
||||
|
||||
vi.mock("../../util/paths", { spy: true });
|
||||
|
||||
describe("LocalPlatformClient", () => {
|
||||
const testFQSN: FQSN = {
|
||||
packageSlugs: [
|
||||
{
|
||||
ownerSlug: "test-owner-slug",
|
||||
packageSlug: "test-package-slug",
|
||||
},
|
||||
],
|
||||
secretName: "TEST_CONTINUE_SECRET_KEY",
|
||||
};
|
||||
const testFQSN2: FQSN = {
|
||||
packageSlugs: [
|
||||
{
|
||||
ownerSlug: "test-owner-slug-2",
|
||||
packageSlug: "test-package-slug-2",
|
||||
},
|
||||
],
|
||||
secretName: "TEST_WORKSPACE_SECRET_KEY",
|
||||
};
|
||||
|
||||
const testResolvedFQSN: SecretResult = {
|
||||
found: true,
|
||||
fqsn: testFQSN,
|
||||
secretLocation: {
|
||||
secretName: testFQSN.secretName,
|
||||
secretType: SecretType.Organization,
|
||||
orgSlug: "test-org-slug",
|
||||
},
|
||||
};
|
||||
|
||||
let testControlPlaneClient: ControlPlaneClient;
|
||||
let testIde: IDE;
|
||||
beforeEach(
|
||||
/**dynamic import before each test for test isolation */
|
||||
async () => {
|
||||
const testFixtures = await import("../../test/fixtures");
|
||||
testControlPlaneClient = testFixtures.testControlPlaneClient;
|
||||
testIde = testFixtures.testIde;
|
||||
},
|
||||
);
|
||||
|
||||
let secretValue: string;
|
||||
let envKeyValues: Record<string, unknown>;
|
||||
let envKeyValuesString: string;
|
||||
beforeEach(
|
||||
/**generate unique env key value pairs for each test */
|
||||
() => {
|
||||
secretValue = Math.floor(Math.random() * 100) + "";
|
||||
envKeyValues = {
|
||||
TEST_CONTINUE_SECRET_KEY: secretValue,
|
||||
TEST_WORKSPACE_SECRET_KEY: secretValue + "-workspace",
|
||||
};
|
||||
envKeyValuesString = Object.entries(envKeyValues)
|
||||
.map(([key, value]) => `${key}=${value}`)
|
||||
.join("\n");
|
||||
},
|
||||
);
|
||||
|
||||
afterEach(() => {
|
||||
vi.resetAllMocks();
|
||||
vi.restoreAllMocks();
|
||||
vi.resetModules(); // clear dynamic imported module cache
|
||||
});
|
||||
|
||||
test("should not be able to resolve FQSNs if they do not exist", async () => {
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
|
||||
|
||||
expect(resolvedFQSNs.length).toBeGreaterThan(0);
|
||||
expect(resolvedFQSNs[0]?.found).toBe(false);
|
||||
});
|
||||
|
||||
test("should be able to resolve FQSNs if they exist", async () => {
|
||||
testControlPlaneClient.resolveFQSNs = vi.fn(async () => [testResolvedFQSN]);
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
|
||||
expect(testControlPlaneClient.resolveFQSNs).toHaveBeenCalled();
|
||||
expect(resolvedFQSNs).toEqual([testResolvedFQSN]);
|
||||
expect(resolvedFQSNs[0]?.found).toBe(true);
|
||||
});
|
||||
|
||||
describe("searches for secrets in local .env files", () => {
|
||||
let getContinueDotEnv: Mock;
|
||||
beforeEach(async () => {
|
||||
const utilPaths = await import("../../util/paths");
|
||||
getContinueDotEnv = vi.fn(() => envKeyValues);
|
||||
utilPaths.getContinueDotEnv = getContinueDotEnv;
|
||||
});
|
||||
|
||||
test("should be able to get secrets from ~/.continue/.env files", async () => {
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
|
||||
expect(getContinueDotEnv).toHaveBeenCalled();
|
||||
expect(resolvedFQSNs.length).toBe(1);
|
||||
expect(
|
||||
(resolvedFQSNs[0] as SecretResult & { value: unknown })?.value,
|
||||
).toBe(secretValue);
|
||||
console.log("debug1 resolved fqsn", resolvedFQSNs);
|
||||
});
|
||||
});
|
||||
|
||||
describe("should be able to get secrets from workspace .env files", () => {
|
||||
test("should get secrets from <workspace>/.continue/.env and <workspace>/.env", async () => {
|
||||
const originalIdeFileExists = testIde.fileExists;
|
||||
testIde.fileExists = vi.fn(async (fileUri: string) =>
|
||||
fileUri.includes(".env") ? true : originalIdeFileExists(fileUri),
|
||||
);
|
||||
|
||||
const originalIdeReadFile = testIde.readFile;
|
||||
const randomValueForContinueDirDotEnv =
|
||||
"continue-dir-" + Math.floor(Math.random() * 100);
|
||||
const randomValueForWorkspaceDotEnv =
|
||||
"dotenv-" + Math.floor(Math.random() * 100);
|
||||
|
||||
testIde.readFile = vi.fn(async (fileUri: string) => {
|
||||
// fileUri should contain .continue/.env and not .env
|
||||
if (fileUri.match(/.*\.continue\/\.env.*/gi)?.length) {
|
||||
return (
|
||||
envKeyValuesString.split("\n")[0] + randomValueForContinueDirDotEnv
|
||||
);
|
||||
}
|
||||
// filUri should contain .env and not .continue/.env
|
||||
else if (fileUri.match(/.*(?<!\.continue\/)\.env.*/gi)?.length) {
|
||||
return (
|
||||
envKeyValuesString.split("\n")[1] + randomValueForWorkspaceDotEnv
|
||||
);
|
||||
}
|
||||
return originalIdeReadFile(fileUri);
|
||||
});
|
||||
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([
|
||||
testFQSN,
|
||||
testFQSN2,
|
||||
]);
|
||||
|
||||
// both the secrets should be present as they are retrieved from different files
|
||||
|
||||
expect(resolvedFQSNs.length).toBe(2);
|
||||
|
||||
const continueDirSecretValue = (
|
||||
resolvedFQSNs[0] as SecretResult & { value: unknown }
|
||||
)?.value;
|
||||
const dotEnvSecretValue = (
|
||||
resolvedFQSNs[1] as SecretResult & { value: unknown }
|
||||
)?.value;
|
||||
expect(continueDirSecretValue).toContain(secretValue);
|
||||
expect(continueDirSecretValue).toContain(randomValueForContinueDirDotEnv);
|
||||
expect(dotEnvSecretValue).toContain(secretValue + "-workspace");
|
||||
expect(dotEnvSecretValue).toContain(randomValueForWorkspaceDotEnv);
|
||||
});
|
||||
|
||||
test("should first get secrets from <workspace>/.continue/.env and then <workspace>/.env", async () => {
|
||||
const originalIdeFileExists = testIde.fileExists;
|
||||
testIde.fileExists = vi.fn(async (fileUri: string) =>
|
||||
fileUri.includes(".env") ? true : originalIdeFileExists(fileUri),
|
||||
);
|
||||
|
||||
const randomValueForContinueDirDotEnv =
|
||||
"continue-dir-" + Math.floor(Math.random() * 100);
|
||||
const randomValueForWorkspaceDotEnv =
|
||||
"dotenv-" + Math.floor(Math.random() * 100);
|
||||
|
||||
const originalIdeReadFile = testIde.readFile;
|
||||
testIde.readFile = vi.fn(async (fileUri: string) => {
|
||||
// fileUri should contain .continue/.env and not .env
|
||||
if (fileUri.match(/.*\.continue\/\.env.*/gi)?.length) {
|
||||
return (
|
||||
envKeyValuesString.split("\n")[0] + randomValueForContinueDirDotEnv
|
||||
);
|
||||
}
|
||||
// filUri should contain .env and not .continue/.env
|
||||
else if (fileUri.match(/.*(?<!\.continue\/)\.env.*/gi)?.length) {
|
||||
return (
|
||||
envKeyValuesString.split("\n")[0] + randomValueForWorkspaceDotEnv
|
||||
);
|
||||
}
|
||||
return originalIdeReadFile(fileUri);
|
||||
});
|
||||
|
||||
const localPlatformClient = new LocalPlatformClient(
|
||||
null,
|
||||
testControlPlaneClient,
|
||||
testIde,
|
||||
);
|
||||
const resolvedFQSNs = await localPlatformClient.resolveFQSNs([testFQSN]);
|
||||
|
||||
expect(resolvedFQSNs.length).toBe(1);
|
||||
expect(
|
||||
(resolvedFQSNs[0] as SecretResult & { value: unknown })?.value,
|
||||
).toContain(secretValue);
|
||||
// we check that workspace <workspace>.continue/.env does not override the <workspace>/.env secret
|
||||
expect(
|
||||
(resolvedFQSNs[0] as SecretResult & { value: unknown })?.value,
|
||||
).toContain(randomValueForContinueDirDotEnv);
|
||||
expect(
|
||||
(resolvedFQSNs[0] as SecretResult & { value: unknown })?.value,
|
||||
).not.toContain(randomValueForWorkspaceDotEnv);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -32,15 +32,14 @@ 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 FreeTrial from "../../llm/llms/FreeTrial";
|
||||
import TransformersJsEmbeddingsProvider from "../../llm/llms/TransformersJsEmbeddingsProvider";
|
||||
import { slashCommandFromPromptFileV1 } from "../../promptFiles/v1/slashCommandFromPromptFile";
|
||||
import { getAllPromptFiles } from "../../promptFiles/v2/getPromptFiles";
|
||||
import { allTools } from "../../tools";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
import { modifyAnyConfigWithSharedConfig } from "../sharedConfig";
|
||||
|
||||
import { getControlPlaneEnvSync } from "../../control-plane/env";
|
||||
import { baseToolDefinitions } from "../../tools";
|
||||
import { getCleanUriPath } from "../../util/uri";
|
||||
import { getAllDotContinueDefinitionFiles } from "../loadLocalAssistants";
|
||||
import { LocalPlatformClient } from "./LocalPlatformClient";
|
||||
|
|
@ -98,7 +97,7 @@ async function loadConfigYaml(options: {
|
|||
for (const blockType of BLOCK_TYPES) {
|
||||
const localBlocks = await getAllDotContinueDefinitionFiles(
|
||||
ide,
|
||||
{ includeGlobal: true, includeWorkspace: true },
|
||||
{ includeGlobal: true, includeWorkspace: true, fileExtType: "yaml" },
|
||||
blockType,
|
||||
);
|
||||
allLocalBlocks.push(
|
||||
|
|
@ -118,10 +117,15 @@ async function loadConfigYaml(options: {
|
|||
// `Loading config.yaml from ${JSON.stringify(packageIdentifier)} with root path ${rootPath}`,
|
||||
// );
|
||||
|
||||
let config =
|
||||
overrideConfigYaml ??
|
||||
const errors: ConfigValidationError[] = [];
|
||||
|
||||
let config: AssistantUnrolled | undefined;
|
||||
|
||||
if (overrideConfigYaml) {
|
||||
config = overrideConfigYaml;
|
||||
} else {
|
||||
// This is how we allow use of blocks locally
|
||||
(await unrollAssistant(
|
||||
const unrollResult = await unrollAssistant(
|
||||
packageIdentifier,
|
||||
new RegistryClient({
|
||||
accessToken: await controlPlaneClient.getAccessToken(),
|
||||
|
|
@ -140,17 +144,23 @@ async function loadConfigYaml(options: {
|
|||
),
|
||||
renderSecrets: true,
|
||||
injectBlocks: allLocalBlocks,
|
||||
asConfigResult: true,
|
||||
},
|
||||
));
|
||||
);
|
||||
config = unrollResult.config;
|
||||
if (unrollResult.errors) {
|
||||
errors.push(...unrollResult.errors);
|
||||
}
|
||||
}
|
||||
|
||||
const errors = isAssistantUnrolledNonNullable(config)
|
||||
? validateConfigYaml(config)
|
||||
: [
|
||||
{
|
||||
if (config) {
|
||||
isAssistantUnrolledNonNullable(config)
|
||||
? errors.push(...validateConfigYaml(config))
|
||||
: errors.push({
|
||||
fatal: true,
|
||||
message: "Assistant includes blocks that don't exist",
|
||||
},
|
||||
];
|
||||
});
|
||||
}
|
||||
|
||||
if (errors?.some((error) => error.fatal)) {
|
||||
return {
|
||||
|
|
@ -176,24 +186,14 @@ async function configYamlToContinueConfig(options: {
|
|||
uniqueId: string;
|
||||
llmLogger: ILLMLogger;
|
||||
workOsAccessToken: string | undefined;
|
||||
allowFreeTrial?: boolean;
|
||||
}): Promise<{ config: ContinueConfig; errors: ConfigValidationError[] }> {
|
||||
let {
|
||||
config,
|
||||
ide,
|
||||
ideSettings,
|
||||
ideInfo,
|
||||
uniqueId,
|
||||
llmLogger,
|
||||
allowFreeTrial,
|
||||
} = options;
|
||||
allowFreeTrial = allowFreeTrial ?? true;
|
||||
let { config, ide, ideSettings, ideInfo, uniqueId, llmLogger } = options;
|
||||
|
||||
const localErrors: ConfigValidationError[] = [];
|
||||
|
||||
const continueConfig: ContinueConfig = {
|
||||
slashCommands: [],
|
||||
tools: [...allTools],
|
||||
tools: [...baseToolDefinitions],
|
||||
mcpServerStatuses: [],
|
||||
contextProviders: [],
|
||||
modelsByRole: {
|
||||
|
|
@ -302,9 +302,14 @@ async function configYamlToContinueConfig(options: {
|
|||
});
|
||||
|
||||
// Models
|
||||
let warnAboutFreeTrial = false;
|
||||
const defaultModelRoles: ModelRole[] = ["chat", "summarize", "apply", "edit"];
|
||||
for (const model of config.models ?? []) {
|
||||
model.roles = model.roles ?? defaultModelRoles; // Default to all 4 chat-esque roles if not specified
|
||||
|
||||
if (model.provider === "free-trial") {
|
||||
warnAboutFreeTrial = true;
|
||||
}
|
||||
try {
|
||||
const llms = await llmsFromModelConfig({
|
||||
model,
|
||||
|
|
@ -376,34 +381,12 @@ async function configYamlToContinueConfig(options: {
|
|||
);
|
||||
}
|
||||
|
||||
if (allowFreeTrial) {
|
||||
// Obtain auth token (iff free trial being used)
|
||||
const freeTrialModels = continueConfig.modelsByRole.chat.filter(
|
||||
(model) => model.providerName === "free-trial",
|
||||
);
|
||||
if (freeTrialModels.length > 0) {
|
||||
try {
|
||||
const ghAuthToken = await ide.getGitHubAuthToken({});
|
||||
for (const model of freeTrialModels) {
|
||||
(model as FreeTrial).setupGhAuthToken(ghAuthToken);
|
||||
}
|
||||
} catch (e) {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message: `Failed to obtain GitHub auth token for free trial:\n${e instanceof Error ? e.message : e}`,
|
||||
});
|
||||
// Remove free trial models
|
||||
continueConfig.modelsByRole.chat =
|
||||
continueConfig.modelsByRole.chat.filter(
|
||||
(model) => model.providerName !== "free-trial",
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Remove free trial models
|
||||
continueConfig.modelsByRole.chat = continueConfig.modelsByRole.chat.filter(
|
||||
(model) => model.providerName !== "free-trial",
|
||||
);
|
||||
if (warnAboutFreeTrial) {
|
||||
localErrors.push({
|
||||
fatal: false,
|
||||
message:
|
||||
"Model provider 'free-trial' is no longer supported, will be ignored.",
|
||||
});
|
||||
}
|
||||
|
||||
// Context providers
|
||||
|
|
|
|||
|
|
@ -68,6 +68,7 @@ async function modelConfigToBaseLLM({
|
|||
tools: model.capabilities?.includes("tool_use"),
|
||||
uploadImage: model.capabilities?.includes("image_input"),
|
||||
},
|
||||
autocompleteOptions: model.autocompleteOptions,
|
||||
};
|
||||
|
||||
// Model capabilities - need to be undefined if not found
|
||||
|
|
|
|||
|
|
@ -111,6 +111,7 @@ describe("MCPConnection", () => {
|
|||
errors: [],
|
||||
prompts: [],
|
||||
resources: [],
|
||||
resourceTemplates: [],
|
||||
tools: [],
|
||||
status: "not-connected",
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,14 +3,15 @@ import { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
|
|||
|
||||
import { SSEClientTransport } from "@modelcontextprotocol/sdk/client/sse.js";
|
||||
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
||||
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
|
||||
import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
||||
import { WebSocketClientTransport } from "@modelcontextprotocol/sdk/client/websocket.js";
|
||||
|
||||
import {
|
||||
MCPConnectionStatus,
|
||||
MCPOptions,
|
||||
MCPPrompt,
|
||||
MCPResource,
|
||||
MCPResourceTemplate,
|
||||
MCPServerStatus,
|
||||
MCPTool,
|
||||
} from "../..";
|
||||
|
|
@ -37,6 +38,7 @@ class MCPConnection {
|
|||
public prompts: MCPPrompt[] = [];
|
||||
public tools: MCPTool[] = [];
|
||||
public resources: MCPResource[] = [];
|
||||
public resourceTemplates: MCPResourceTemplate[] = [];
|
||||
private transport: Transport;
|
||||
private connectionPromise: Promise<unknown> | null = null;
|
||||
private stdioOutput: { stdout: string; stderr: string } = {
|
||||
|
|
@ -72,6 +74,7 @@ class MCPConnection {
|
|||
errors: this.errors,
|
||||
prompts: this.prompts,
|
||||
resources: this.resources,
|
||||
resourceTemplates: this.resourceTemplates,
|
||||
tools: this.tools,
|
||||
status: this.status,
|
||||
};
|
||||
|
|
@ -95,6 +98,7 @@ class MCPConnection {
|
|||
this.tools = [];
|
||||
this.prompts = [];
|
||||
this.resources = [];
|
||||
this.resourceTemplates = [];
|
||||
this.errors = [];
|
||||
this.stdioOutput = { stdout: "", stderr: "" };
|
||||
|
||||
|
|
@ -169,6 +173,23 @@ class MCPConnection {
|
|||
}
|
||||
this.errors.push(errorMessage);
|
||||
}
|
||||
|
||||
// Resource templates
|
||||
try {
|
||||
const { resourceTemplates } =
|
||||
await this.client.listResourceTemplates(
|
||||
{},
|
||||
{ signal: timeoutController.signal },
|
||||
);
|
||||
|
||||
this.resourceTemplates = resourceTemplates;
|
||||
} catch (e) {
|
||||
let errorMessage = `Error loading resource templates for MCP Server ${this.options.name}`;
|
||||
if (e instanceof Error) {
|
||||
errorMessage += `: ${e.message}`;
|
||||
}
|
||||
this.errors.push(errorMessage);
|
||||
}
|
||||
}
|
||||
|
||||
// Tools <—> Tools
|
||||
|
|
@ -337,9 +358,12 @@ class MCPConnection {
|
|||
requestInit: { headers: options.transport.requestOptions?.headers },
|
||||
});
|
||||
case "streamable-http":
|
||||
return new StreamableHTTPClientTransport(new URL(options.transport.url), {
|
||||
requestInit: { headers: options.transport.requestOptions?.headers },
|
||||
});
|
||||
return new StreamableHTTPClientTransport(
|
||||
new URL(options.transport.url),
|
||||
{
|
||||
requestInit: { headers: options.transport.requestOptions?.headers },
|
||||
},
|
||||
);
|
||||
default:
|
||||
throw new Error(
|
||||
`Unsupported transport type: ${(options.transport as any).type}`,
|
||||
|
|
|
|||
|
|
@ -24,7 +24,7 @@ class ContinueProxyContextProvider extends BaseContextProvider {
|
|||
this.options.title || ContinueProxyContextProvider.description.title,
|
||||
displayTitle:
|
||||
this.options.displayTitle ||
|
||||
this.options.name ||
|
||||
this.options.name ||
|
||||
ContinueProxyContextProvider.description.displayTitle,
|
||||
description:
|
||||
this.options.description ||
|
||||
|
|
|
|||
|
|
@ -17,16 +17,15 @@ class DiffContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const diff = await extras.ide.getDiff(
|
||||
this.options?.includeUnstaged ?? true,
|
||||
);
|
||||
const includeUnstaged = this.options?.includeUnstaged ?? true;
|
||||
const diffs = await extras.ide.getDiff(includeUnstaged); // TODO use diff cache (currently cache always includes unstaged)
|
||||
return [
|
||||
{
|
||||
description: "The current git diff",
|
||||
content:
|
||||
diff.length === 0
|
||||
diffs.length === 0
|
||||
? "Git shows no current changes."
|
||||
: `\`\`\`git diff\n${diff.join("\n")}\n\`\`\``,
|
||||
: `\`\`\`git diff\n${diffs.join("\n")}\n\`\`\``,
|
||||
name: "Git Diff",
|
||||
},
|
||||
];
|
||||
|
|
|
|||
|
|
@ -124,10 +124,10 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
|
|||
let urlMatches: RegExpExecArray | null;
|
||||
if (/https?.*/.test(remoteUrl)) {
|
||||
const pathname = new URL(remoteUrl).pathname;
|
||||
urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname)
|
||||
urlMatches = /\/(?<projectPath>.*?)(?:(?=\.git)|$)/.exec(pathname);
|
||||
} else {
|
||||
// ssh
|
||||
urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl)
|
||||
urlMatches = /:(?<projectPath>.*).git/.exec(remoteUrl);
|
||||
}
|
||||
|
||||
const project = urlMatches?.groups?.projectPath ?? null;
|
||||
|
|
|
|||
|
|
@ -38,27 +38,35 @@ class GoogleContextProvider extends BaseContextProvider {
|
|||
body: payload,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Failed to fetch Google search results: ${response.statusText}`,
|
||||
);
|
||||
}
|
||||
const results = await response.text();
|
||||
try {
|
||||
const parsed = JSON.parse(results);
|
||||
let content = `Google Search: ${query}\n\n`;
|
||||
const answerBox = parsed.answerBox;
|
||||
|
||||
const jsonResults = JSON.parse(results);
|
||||
let content = `Google Search: ${query}\n\n`;
|
||||
const answerBox = jsonResults.answerBox;
|
||||
if (answerBox) {
|
||||
content += `Answer Box (${answerBox.title}): ${answerBox.answer}\n\n`;
|
||||
}
|
||||
|
||||
if (answerBox) {
|
||||
content += `Answer Box (${answerBox.title}): ${answerBox.answer}\n\n`;
|
||||
for (const result of parsed.organic) {
|
||||
content += `${result.title}\n${result.link}\n${result.snippet}\n\n`;
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
content,
|
||||
name: "Google Search",
|
||||
description: "Google Search",
|
||||
},
|
||||
];
|
||||
} catch (e) {
|
||||
throw new Error(`Failed to parse Google search results: ${results}`);
|
||||
}
|
||||
|
||||
for (const result of jsonResults.organic) {
|
||||
content += `${result.title}\n${result.link}\n${result.snippet}\n\n`;
|
||||
}
|
||||
|
||||
return [
|
||||
{
|
||||
content,
|
||||
name: "Google Search",
|
||||
description: "Google Search",
|
||||
},
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -81,13 +81,17 @@ class GreptileContextProvider extends BaseContextProvider {
|
|||
}
|
||||
|
||||
// Parse the response as JSON
|
||||
const json = JSON.parse(rawText);
|
||||
|
||||
return json.sources.map((source: any) => ({
|
||||
description: source.filepath,
|
||||
content: `File: ${source.filepath}\nLines: ${source.linestart}-${source.lineend}\n\n${source.summary}`,
|
||||
name: (source.filepath.split("/").pop() ?? "").split("\\").pop() ?? "",
|
||||
}));
|
||||
try {
|
||||
const json = JSON.parse(rawText);
|
||||
return json.sources.map((source: any) => ({
|
||||
description: source.filepath,
|
||||
content: `File: ${source.filepath}\nLines: ${source.linestart}-${source.lineend}\n\n${source.summary}`,
|
||||
name:
|
||||
(source.filepath.split("/").pop() ?? "").split("\\").pop() ?? "",
|
||||
}));
|
||||
} catch (jsonError) {
|
||||
throw new Error(`Failed to parse Greptile response:\n${rawText}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error getting context items from Greptile:", error);
|
||||
throw new Error("Error getting context items from Greptile");
|
||||
|
|
|
|||
|
|
@ -20,10 +20,11 @@ class HttpContextProvider extends BaseContextProvider {
|
|||
try {
|
||||
const currentFile = await ide.getCurrentFile();
|
||||
// `isLocalhost` actually also returns true for other local addresses, not just localhost
|
||||
return await isLocalhost(url.hostname) ?
|
||||
(await ide.getWorkspaceDirs()).find(workspaceDirectory => {
|
||||
return currentFile?.path.startsWith(workspaceDirectory)
|
||||
}) : undefined
|
||||
return (await isLocalhost(url.hostname))
|
||||
? (await ide.getWorkspaceDirs()).find((workspaceDirectory) => {
|
||||
return currentFile?.path.startsWith(workspaceDirectory);
|
||||
})
|
||||
: undefined;
|
||||
} catch (e) {
|
||||
return undefined;
|
||||
}
|
||||
|
|
@ -44,12 +45,12 @@ class HttpContextProvider extends BaseContextProvider {
|
|||
HttpContextProvider.description.renderInlineAs,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const parsedUrl = new URL(this.options.url)
|
||||
const parsedUrl = new URL(this.options.url);
|
||||
const response = await extras.fetch(parsedUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
|
|
|
|||
|
|
@ -25,7 +25,7 @@ class JiraIssuesContextProvider extends BaseContextProvider {
|
|||
issueQuery: this.options.issueQuery,
|
||||
apiVersion: this.options.apiVersion,
|
||||
requestOptions: this.options.requestOptions,
|
||||
maxResults: this.options.maxResults
|
||||
maxResults: this.options.maxResults,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -20,6 +20,7 @@ class MCPContextProvider extends BaseContextProvider {
|
|||
displayTitle: "MCP",
|
||||
description: "Model Context Protocol",
|
||||
type: "submenu",
|
||||
renderInlineAs: "",
|
||||
};
|
||||
override get description(): ContextProviderDescription {
|
||||
return {
|
||||
|
|
@ -27,6 +28,7 @@ class MCPContextProvider extends BaseContextProvider {
|
|||
displayTitle: this.options["serverName"]
|
||||
? `${this.options["serverName"]} resources`
|
||||
: "MCP",
|
||||
renderInlineAs: "",
|
||||
description: "Model Context Protocol",
|
||||
type: "submenu",
|
||||
};
|
||||
|
|
@ -47,6 +49,18 @@ class MCPContextProvider extends BaseContextProvider {
|
|||
super(options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Continue experimentally supports resource templates (https://modelcontextprotocol.io/docs/concepts/resources#resource-templates)
|
||||
* by allowing specifically just the "query" variable in the template, which we will update with the full input of the user in the input box
|
||||
*/
|
||||
private insertInputToUriTemplate(uri: string, query: string): string {
|
||||
const TEMPLATE_VAR = "query";
|
||||
if (uri.includes(`{${TEMPLATE_VAR}}`)) {
|
||||
return uri.replace(`{${TEMPLATE_VAR}}`, encodeURIComponent(query));
|
||||
}
|
||||
return uri;
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
|
|
@ -58,7 +72,9 @@ class MCPContextProvider extends BaseContextProvider {
|
|||
throw new Error(`No MCP connection found for ${mcpId}`);
|
||||
}
|
||||
|
||||
const { contents } = await connection.client.readResource({ uri });
|
||||
const { contents } = await connection.client.readResource({
|
||||
uri: this.insertInputToUriTemplate(uri, extras.fullInput),
|
||||
});
|
||||
|
||||
return await Promise.all(
|
||||
contents.map(async (resource) => {
|
||||
|
|
|
|||
91
core/context/providers/RulesContextProvider.ts
Normal file
91
core/context/providers/RulesContextProvider.ts
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import { BaseContextProvider } from "..";
|
||||
import {
|
||||
ContextItem,
|
||||
ContextItemUri,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
ContextSubmenuItem,
|
||||
LoadSubmenuItemsArgs,
|
||||
RuleWithSource,
|
||||
} from "../..";
|
||||
import { getControlPlaneEnv } from "../../control-plane/env";
|
||||
|
||||
class RulesContextProvider extends BaseContextProvider {
|
||||
static description: ContextProviderDescription = {
|
||||
title: "rules",
|
||||
displayTitle: "Rules",
|
||||
description: "Mention rules files",
|
||||
type: "submenu",
|
||||
renderInlineAs: "",
|
||||
};
|
||||
|
||||
// This is only used within this class. Worst case if there are exact duplicates is that one always calls the other, but this is an extreme edge case
|
||||
// Can eventually pull in more metadata, but this is experimental
|
||||
private getIdFromRule(rule: RuleWithSource): string {
|
||||
return rule.ruleFile ?? rule.slug ?? rule.name ?? rule.rule;
|
||||
}
|
||||
|
||||
private getNameFromRule(rule: RuleWithSource): string {
|
||||
return rule.name ?? rule.slug ?? rule.ruleFile ?? rule.source;
|
||||
}
|
||||
|
||||
private getDescriptionFromRule(rule: RuleWithSource): string {
|
||||
return rule.description ?? rule.name ?? "";
|
||||
}
|
||||
|
||||
private getUriFromRule(
|
||||
rule: RuleWithSource,
|
||||
appUrl: string,
|
||||
): ContextItemUri | undefined {
|
||||
if (rule.ruleFile) {
|
||||
return {
|
||||
type: "file",
|
||||
value: rule.ruleFile,
|
||||
};
|
||||
}
|
||||
|
||||
if (rule.slug) {
|
||||
let url = `${appUrl}${rule.slug}`;
|
||||
return {
|
||||
type: "url",
|
||||
value: url,
|
||||
};
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
async getContextItems(
|
||||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
const rule = extras.config.rules.find(
|
||||
(rule) => this.getIdFromRule(rule) === query,
|
||||
);
|
||||
if (!rule) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const env = await getControlPlaneEnv(extras.ide.getIdeSettings());
|
||||
return [
|
||||
{
|
||||
name: this.getNameFromRule(rule),
|
||||
content: rule.rule,
|
||||
description: this.getDescriptionFromRule(rule),
|
||||
uri: this.getUriFromRule(rule, env.APP_URL),
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
async loadSubmenuItems(
|
||||
args: LoadSubmenuItemsArgs,
|
||||
): Promise<ContextSubmenuItem[]> {
|
||||
return args.config.rules.map((rule) => ({
|
||||
id: this.getIdFromRule(rule),
|
||||
description: this.getDescriptionFromRule(rule),
|
||||
title: this.getNameFromRule(rule),
|
||||
}));
|
||||
}
|
||||
}
|
||||
|
||||
export default RulesContextProvider;
|
||||
|
|
@ -7,6 +7,7 @@ import {
|
|||
ContextItem,
|
||||
ContextProviderDescription,
|
||||
ContextProviderExtras,
|
||||
FetchFunction,
|
||||
} from "../../index.js";
|
||||
import { fetchFavicon } from "../../util/fetchFavicon";
|
||||
|
||||
|
|
@ -22,42 +23,49 @@ class URLContextProvider extends BaseContextProvider {
|
|||
query: string,
|
||||
extras: ContextProviderExtras,
|
||||
): Promise<ContextItem[]> {
|
||||
try {
|
||||
const url = new URL(query);
|
||||
const icon = await fetchFavicon(url);
|
||||
const resp = await extras.fetch(url);
|
||||
const html = await resp.text();
|
||||
|
||||
const dom = new JSDOM(html);
|
||||
let reader = new Readability(dom.window.document);
|
||||
let article = reader.parse();
|
||||
const content = article?.content || "";
|
||||
const markdown = NodeHtmlMarkdown.translate(
|
||||
content,
|
||||
{},
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
|
||||
const title = article?.title || url.pathname;
|
||||
|
||||
return [
|
||||
{
|
||||
icon,
|
||||
description: url.toString(),
|
||||
content: markdown,
|
||||
name: title,
|
||||
uri: {
|
||||
type: "url",
|
||||
value: url.toString(),
|
||||
},
|
||||
},
|
||||
];
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
return [];
|
||||
}
|
||||
return await getUrlContextItems(query, extras.fetch);
|
||||
}
|
||||
}
|
||||
|
||||
export default URLContextProvider;
|
||||
|
||||
export async function getUrlContextItems(
|
||||
query: string,
|
||||
fetchFn: FetchFunction,
|
||||
): Promise<ContextItem[]> {
|
||||
try {
|
||||
const url = new URL(query);
|
||||
const icon = await fetchFavicon(url);
|
||||
const resp = await fetchFn(url);
|
||||
const html = await resp.text();
|
||||
|
||||
const dom = new JSDOM(html);
|
||||
let reader = new Readability(dom.window.document);
|
||||
let article = reader.parse();
|
||||
const content = article?.content || "";
|
||||
const markdown = NodeHtmlMarkdown.translate(
|
||||
content,
|
||||
{},
|
||||
undefined,
|
||||
undefined,
|
||||
);
|
||||
|
||||
const title = article?.title || url.pathname;
|
||||
|
||||
return [
|
||||
{
|
||||
icon,
|
||||
description: url.toString(),
|
||||
content: markdown,
|
||||
name: title,
|
||||
uri: {
|
||||
type: "url",
|
||||
value: url.toString(),
|
||||
},
|
||||
},
|
||||
];
|
||||
} catch (e) {
|
||||
console.log(e);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -25,6 +25,7 @@ import OSContextProvider from "./OSContextProvider";
|
|||
import PostgresContextProvider from "./PostgresContextProvider";
|
||||
import ProblemsContextProvider from "./ProblemsContextProvider";
|
||||
import RepoMapContextProvider from "./RepoMapContextProvider";
|
||||
import RulesContextProvider from "./RulesContextProvider";
|
||||
import SearchContextProvider from "./SearchContextProvider";
|
||||
import TerminalContextProvider from "./TerminalContextProvider";
|
||||
import URLContextProvider from "./URLContextProvider";
|
||||
|
|
@ -66,6 +67,7 @@ export const Providers: (typeof BaseContextProvider)[] = [
|
|||
MCPContextProvider,
|
||||
GitCommitContextProvider,
|
||||
ClipboardContextProvider,
|
||||
RulesContextProvider,
|
||||
];
|
||||
|
||||
export function contextProviderClassFromName(
|
||||
|
|
|
|||
|
|
@ -2,10 +2,10 @@
|
|||
import nlp from "wink-nlp-utils";
|
||||
|
||||
import { BranchAndDir, Chunk, ContinueConfig, IDE, ILLM } from "../../../";
|
||||
import { openedFilesLruCache } from "../../../autocomplete/util/openedFilesLruCache";
|
||||
import { chunkDocument } from "../../../indexing/chunk/chunk";
|
||||
import { FullTextSearchCodebaseIndex } from "../../../indexing/FullTextSearchCodebaseIndex";
|
||||
import { LanceDbIndex } from "../../../indexing/LanceDbIndex";
|
||||
import { recentlyEditedFilesCache } from "../recentlyEditedFilesCache";
|
||||
|
||||
const DEFAULT_CHUNK_SIZE = 384;
|
||||
|
||||
|
|
@ -85,7 +85,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
}
|
||||
|
||||
const tokens = this.getCleanedTrigrams(args.query).join(" OR ");
|
||||
|
||||
|
||||
return await this.ftsIndex.retrieve({
|
||||
n,
|
||||
text: tokens,
|
||||
|
|
@ -98,7 +98,7 @@ export default class BaseRetrievalPipeline implements IRetrievalPipeline {
|
|||
n: number,
|
||||
): Promise<Chunk[]> {
|
||||
const recentlyEditedFilesSlice = Array.from(
|
||||
recentlyEditedFilesCache.keys(),
|
||||
openedFilesLruCache.keys(),
|
||||
).slice(0, n);
|
||||
|
||||
// If the number of recently edited files is less than the retrieval limit,
|
||||
|
|
|
|||
|
|
@ -1,16 +0,0 @@
|
|||
import QuickLRU from "quick-lru";
|
||||
|
||||
import { ToWebviewOrCoreFromIdeProtocol } from "../../protocol/ide.js";
|
||||
|
||||
// The cache key and value are both a filepath string
|
||||
export type RecentlyEditedFilesCacheKeyAndValue =
|
||||
ToWebviewOrCoreFromIdeProtocol["didChangeActiveTextEditor"][0]["filepath"];
|
||||
|
||||
const MAX_NUM_RECENTLY_EDITED_FILES = 100;
|
||||
|
||||
export const recentlyEditedFilesCache = new QuickLRU<
|
||||
RecentlyEditedFilesCacheKeyAndValue,
|
||||
RecentlyEditedFilesCacheKeyAndValue
|
||||
>({
|
||||
maxSize: MAX_NUM_RECENTLY_EDITED_FILES,
|
||||
});
|
||||
|
|
@ -13,14 +13,10 @@ export interface OnPremSessionInfo {
|
|||
|
||||
export type ControlPlaneSessionInfo = HubSessionInfo | OnPremSessionInfo;
|
||||
|
||||
export function isHubSession(
|
||||
export function isOnPremSession(
|
||||
sessionInfo: ControlPlaneSessionInfo | undefined,
|
||||
): sessionInfo is HubSessionInfo {
|
||||
return (
|
||||
sessionInfo !== undefined &&
|
||||
(sessionInfo.AUTH_TYPE === AuthType.WorkOsProd ||
|
||||
sessionInfo.AUTH_TYPE === AuthType.WorkOsStaging)
|
||||
);
|
||||
): sessionInfo is OnPremSessionInfo {
|
||||
return sessionInfo !== undefined && sessionInfo.AUTH_TYPE === AuthType.OnPrem;
|
||||
}
|
||||
|
||||
export enum AuthType {
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ import fetch, { RequestInit, Response } from "node-fetch";
|
|||
import { OrganizationDescription } from "../config/ProfileLifecycleManager.js";
|
||||
import { IdeSettings, ModelDescription } from "../index.js";
|
||||
|
||||
import { ControlPlaneSessionInfo, isHubSession } from "./AuthTypes.js";
|
||||
import { ControlPlaneSessionInfo, isOnPremSession } from "./AuthTypes.js";
|
||||
import { getControlPlaneEnv } from "./env.js";
|
||||
|
||||
export interface ControlPlaneWorkspace {
|
||||
|
|
@ -23,6 +23,14 @@ export interface ControlPlaneWorkspace {
|
|||
|
||||
export interface ControlPlaneModelDescription extends ModelDescription {}
|
||||
|
||||
export interface FreeTrialStatus {
|
||||
optedInToFreeTrial: boolean;
|
||||
chatCount?: number;
|
||||
autocompleteCount?: number;
|
||||
chatLimit: number;
|
||||
autocompleteLimit: number;
|
||||
}
|
||||
|
||||
export const TRIAL_PROXY_URL =
|
||||
"https://proxy-server-blue-l6vsfbzhba-uw.a.run.app";
|
||||
|
||||
|
|
@ -63,17 +71,16 @@ export class ControlPlaneClient {
|
|||
|
||||
async getAccessToken(): Promise<string | undefined> {
|
||||
const sessionInfo = await this.sessionInfoPromise;
|
||||
return isHubSession(sessionInfo) ? sessionInfo.accessToken : undefined;
|
||||
return isOnPremSession(sessionInfo) ? undefined : sessionInfo?.accessToken;
|
||||
}
|
||||
|
||||
private async request(path: string, init: RequestInit): Promise<Response> {
|
||||
const sessionInfo = await this.sessionInfoPromise;
|
||||
const hubSession = isHubSession(sessionInfo);
|
||||
|
||||
const accessToken = hubSession ? sessionInfo.accessToken : undefined;
|
||||
const onPremSession = isOnPremSession(sessionInfo);
|
||||
const accessToken = await this.getAccessToken();
|
||||
|
||||
// Bearer token not necessary for on-prem auth type
|
||||
if (!accessToken && hubSession) {
|
||||
if (!accessToken && !onPremSession) {
|
||||
throw new Error("No access token");
|
||||
}
|
||||
|
||||
|
|
@ -160,4 +167,53 @@ export class ControlPlaneClient {
|
|||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
public async getFreeTrialStatus(): Promise<FreeTrialStatus | null> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const resp = await this.request("ide/free-trial-status", {
|
||||
method: "GET",
|
||||
});
|
||||
return (await resp.json()) as FreeTrialStatus;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* JetBrains does not support deep links, so we only check for `vsCodeUriScheme`
|
||||
* @param vsCodeUriScheme
|
||||
* @returns
|
||||
*/
|
||||
public async getModelsAddOnCheckoutUrl(
|
||||
vsCodeUriScheme?: string,
|
||||
): Promise<{ url: string } | null> {
|
||||
if (!(await this.isSignedIn())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
// LocalProfileLoader ID
|
||||
profile_id: "local",
|
||||
});
|
||||
|
||||
if (vsCodeUriScheme) {
|
||||
params.set("vscode_uri_scheme", vsCodeUriScheme);
|
||||
}
|
||||
|
||||
const resp = await this.request(
|
||||
`ide/get-models-add-on-checkout-url?${params.toString()}`,
|
||||
{
|
||||
method: "GET",
|
||||
},
|
||||
);
|
||||
return (await resp.json()) as { url: string };
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import {
|
|||
getStagingEnvironmentDotFilePath,
|
||||
} from "../util/paths";
|
||||
import { AuthType, ControlPlaneEnv } from "./AuthTypes";
|
||||
import { getMdmKeys } from "./mdm";
|
||||
import { getLicenseKeyData } from "./mdm/mdm";
|
||||
|
||||
export const EXTENSION_NAME = "continue";
|
||||
|
||||
|
|
@ -59,9 +59,9 @@ export function getControlPlaneEnvSync(
|
|||
ideTestEnvironment: IdeSettings["continueTestEnvironment"],
|
||||
): ControlPlaneEnv {
|
||||
// MDM override
|
||||
const mdmKeys = getMdmKeys();
|
||||
if (mdmKeys) {
|
||||
const { apiUrl } = mdmKeys;
|
||||
const licenseKeyData = getLicenseKeyData();
|
||||
if (licenseKeyData?.unsignedData?.apiUrl) {
|
||||
const { apiUrl } = licenseKeyData.unsignedData;
|
||||
return {
|
||||
AUTH_TYPE: AuthType.OnPrem,
|
||||
DEFAULT_CONTROL_PLANE_PROXY_URL: apiUrl,
|
||||
|
|
|
|||
|
|
@ -1,127 +0,0 @@
|
|||
import * as crypto from "crypto";
|
||||
import { LicenseData, validateLicenseKey } from "./mdm";
|
||||
|
||||
// We'll create a real key pair once for all tests
|
||||
const testKeyPair = crypto.generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
publicKeyEncoding: {
|
||||
type: "spki",
|
||||
format: "pem",
|
||||
},
|
||||
privateKeyEncoding: {
|
||||
type: "pkcs8",
|
||||
format: "pem",
|
||||
},
|
||||
});
|
||||
|
||||
// Custom function to create test licenses (replaces the original mock-dependent one)
|
||||
function createTestLicense(
|
||||
licenseData: LicenseData,
|
||||
useValidSignature: boolean = true,
|
||||
): string {
|
||||
// Convert license data to a string
|
||||
const licenseDataStr = JSON.stringify(licenseData);
|
||||
|
||||
// Create a signature with our generated private key
|
||||
const sign = crypto.createSign("SHA256");
|
||||
sign.update(licenseDataStr);
|
||||
sign.end();
|
||||
|
||||
let signature: string;
|
||||
if (useValidSignature) {
|
||||
signature = sign.sign(testKeyPair.privateKey, "base64");
|
||||
} else {
|
||||
// For invalid tests, create an intentionally wrong signature by signing different data
|
||||
const wrongSign = crypto.createSign("SHA256");
|
||||
wrongSign.update(licenseDataStr + "tampered");
|
||||
wrongSign.end();
|
||||
signature = wrongSign.sign(testKeyPair.privateKey, "base64");
|
||||
}
|
||||
// Combine data and signature into a license key
|
||||
const licenseKeyObj = {
|
||||
data: licenseDataStr,
|
||||
signature: signature,
|
||||
};
|
||||
|
||||
return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64");
|
||||
}
|
||||
|
||||
// We need to test the actual implementation - which we can't mock with ESM
|
||||
// Instead, we'll have tests that bypass validation or are expected to fail
|
||||
// depending on what we're testing
|
||||
|
||||
test("validateLicenseKey returns false for malformed license key", () => {
|
||||
// Test with a completely invalid license key
|
||||
const invalidLicenseKey = "not-a-valid-license-key";
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for invalid JSON in license key", () => {
|
||||
// Create a malformed but base64-encoded string
|
||||
const malformedLicenseKey = Buffer.from("this is not valid JSON").toString(
|
||||
"base64",
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(malformedLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for expired license", () => {
|
||||
// Without mocking, we expect this to fail signature verification
|
||||
// We're testing the date logic by itself
|
||||
const licenseData: LicenseData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago
|
||||
expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago
|
||||
};
|
||||
|
||||
// Create a license key - will fail verification but test logic still works
|
||||
const expiredLicenseKey = createTestLicense(licenseData);
|
||||
|
||||
// Test - expect false, either due to signature or expiration - both are valid test cases
|
||||
const result = validateLicenseKey(expiredLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for invalid signature", () => {
|
||||
// Create license data with valid dates
|
||||
const licenseData: LicenseData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day
|
||||
};
|
||||
|
||||
// Create a license with an invalid signature
|
||||
const invalidSignatureKey = createTestLicense(licenseData, false);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidSignatureKey);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
|
||||
test("validateLicenseKey handles JSON parsing errors gracefully", () => {
|
||||
// Create a base64 string that decodes to valid JSON but lacks required fields
|
||||
const invalidStructureKey = Buffer.from(
|
||||
JSON.stringify({
|
||||
notTheRightField: "wrong structure",
|
||||
}),
|
||||
).toString("base64");
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidStructureKey);
|
||||
|
||||
// Assert
|
||||
expect(result).toBe(false);
|
||||
});
|
||||
210
core/control-plane/mdm/mdm.test.ts
Normal file
210
core/control-plane/mdm/mdm.test.ts
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
import * as crypto from "crypto";
|
||||
import { LicenseKeyData, validateLicenseKey } from "./mdm";
|
||||
|
||||
// We'll create a real key pair once for all tests
|
||||
const testKeyPair = crypto.generateKeyPairSync("rsa", {
|
||||
modulusLength: 2048,
|
||||
publicKeyEncoding: {
|
||||
type: "spki",
|
||||
format: "pem",
|
||||
},
|
||||
privateKeyEncoding: {
|
||||
type: "pkcs8",
|
||||
format: "pem",
|
||||
},
|
||||
});
|
||||
|
||||
// Custom function to create test licenses with the new structure including unsignedData
|
||||
function createTestLicense(
|
||||
licenseData: LicenseKeyData,
|
||||
apiUrl: string = "https://api.continue.dev",
|
||||
useValidSignature: boolean = true,
|
||||
): string {
|
||||
// Convert license data to a string
|
||||
const licenseDataStr = JSON.stringify(licenseData);
|
||||
|
||||
// Create a signature with our generated private key
|
||||
const sign = crypto.createSign("SHA256");
|
||||
sign.update(licenseDataStr);
|
||||
sign.end();
|
||||
|
||||
let signature: string;
|
||||
if (useValidSignature) {
|
||||
signature = sign.sign(testKeyPair.privateKey, "base64");
|
||||
} else {
|
||||
// For invalid tests, create an intentionally wrong signature by signing different data
|
||||
const wrongSign = crypto.createSign("SHA256");
|
||||
wrongSign.update(licenseDataStr + "tampered");
|
||||
wrongSign.end();
|
||||
signature = wrongSign.sign(testKeyPair.privateKey, "base64");
|
||||
}
|
||||
|
||||
// Combine data, signature, and unsigned data into a license key
|
||||
const licenseKeyObj = {
|
||||
data: licenseDataStr,
|
||||
signature: signature,
|
||||
unsignedData: {
|
||||
apiUrl: apiUrl,
|
||||
},
|
||||
};
|
||||
|
||||
return Buffer.from(JSON.stringify(licenseKeyObj)).toString("base64");
|
||||
}
|
||||
|
||||
// We need to test the actual implementation - which we can't mock with ESM
|
||||
// Instead, we'll have tests that bypass validation or are expected to fail
|
||||
// depending on what we're testing
|
||||
|
||||
test("validateLicenseKey returns false for malformed license key", () => {
|
||||
// Test with a completely invalid license key
|
||||
const invalidLicenseKey = "not-a-valid-license-key";
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for invalid JSON in license key", () => {
|
||||
// Create a malformed but base64-encoded string
|
||||
const malformedLicenseKey = Buffer.from("this is not valid JSON").toString(
|
||||
"base64",
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(malformedLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for expired license", () => {
|
||||
// Without mocking, we expect this to fail signature verification
|
||||
// We're testing the date logic by itself
|
||||
const licenseData: LicenseKeyData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date(Date.now() - 2000 * 60 * 60 * 24).toISOString(), // Created 2 days ago
|
||||
expiresAt: new Date(Date.now() - 1000 * 60 * 60 * 24).toISOString(), // Expired 1 day ago
|
||||
};
|
||||
|
||||
// Create a license key with apiUrl in unsignedData - will fail verification but test logic still works
|
||||
const expiredLicenseKey = createTestLicense(
|
||||
licenseData,
|
||||
"https://api.continue.dev",
|
||||
);
|
||||
|
||||
// Test - expect false, either due to signature or expiration - both are valid test cases
|
||||
const result = validateLicenseKey(expiredLicenseKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey returns false for invalid signature", () => {
|
||||
// Create license data with valid dates
|
||||
const licenseData: LicenseKeyData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(), // Valid for 1 day
|
||||
};
|
||||
|
||||
// Create a license with an invalid signature but valid unsignedData structure
|
||||
const invalidSignatureKey = createTestLicense(
|
||||
licenseData,
|
||||
"https://api.continue.dev",
|
||||
false,
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidSignatureKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey handles JSON parsing errors gracefully", () => {
|
||||
// Create a base64 string that decodes to valid JSON but lacks required fields
|
||||
const invalidStructureKey = Buffer.from(
|
||||
JSON.stringify({
|
||||
notTheRightField: "wrong structure",
|
||||
}),
|
||||
).toString("base64");
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(invalidStructureKey);
|
||||
|
||||
// Assert
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey handles missing unsignedData gracefully", () => {
|
||||
// Create a license key structure without unsignedData field
|
||||
const licenseData: LicenseKeyData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
|
||||
};
|
||||
|
||||
const licenseDataStr = JSON.stringify(licenseData);
|
||||
const sign = crypto.createSign("SHA256");
|
||||
sign.update(licenseDataStr);
|
||||
sign.end();
|
||||
const signature = sign.sign(testKeyPair.privateKey, "base64");
|
||||
|
||||
// Create license key without unsignedData
|
||||
const licenseKeyObj = {
|
||||
data: licenseDataStr,
|
||||
signature: signature,
|
||||
// Missing unsignedData field
|
||||
};
|
||||
|
||||
const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
|
||||
"base64",
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(licenseKey);
|
||||
|
||||
// Assert - should fail due to signature verification with wrong public key
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
||||
test("validateLicenseKey handles invalid unsignedData structure", () => {
|
||||
// Create license data with valid dates
|
||||
const licenseData: LicenseKeyData = {
|
||||
customerId: "customer123",
|
||||
createdAt: new Date().toISOString(),
|
||||
expiresAt: new Date(Date.now() + 1000 * 60 * 60 * 24).toISOString(),
|
||||
};
|
||||
|
||||
const licenseDataStr = JSON.stringify(licenseData);
|
||||
const sign = crypto.createSign("SHA256");
|
||||
sign.update(licenseDataStr);
|
||||
sign.end();
|
||||
const signature = sign.sign(testKeyPair.privateKey, "base64");
|
||||
|
||||
// Create license key with invalid unsignedData structure
|
||||
const licenseKeyObj = {
|
||||
data: licenseDataStr,
|
||||
signature: signature,
|
||||
unsignedData: "not an object", // Should be an object with apiUrl
|
||||
};
|
||||
|
||||
const licenseKey = Buffer.from(JSON.stringify(licenseKeyObj)).toString(
|
||||
"base64",
|
||||
);
|
||||
|
||||
// Test - no mocks, real validation
|
||||
const result = validateLicenseKey(licenseKey);
|
||||
|
||||
// Assert - should fail due to signature verification with wrong public key
|
||||
expect(result.isValid).toBe(false);
|
||||
expect(result.licenseKeyData).toBeUndefined();
|
||||
});
|
||||
|
|
@ -6,7 +6,6 @@ import * as plist from "plist";
|
|||
|
||||
export interface MdmKeys {
|
||||
licenseKey: string;
|
||||
apiUrl: string;
|
||||
}
|
||||
|
||||
const CONTINUE_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
|
||||
|
|
@ -19,17 +18,30 @@ LXSsjLbeWHifRrQ18wj/PC990E33QaFGNFp0NcBXMPbq5eKYKEzKZ0GsxtLoGxar
|
|||
FQIDAQAB
|
||||
-----END PUBLIC KEY-----`;
|
||||
|
||||
export interface LicenseData {
|
||||
interface LicenseKeyUnsignedData {
|
||||
apiUrl: string;
|
||||
}
|
||||
|
||||
export interface LicenseKey {
|
||||
signature: string;
|
||||
data: string;
|
||||
unsignedData: LicenseKeyUnsignedData;
|
||||
}
|
||||
|
||||
export interface LicenseKeyData {
|
||||
customerId: string;
|
||||
createdAt: string;
|
||||
expiresAt: string;
|
||||
}
|
||||
|
||||
export function validateLicenseKey(licenseKey: string): boolean {
|
||||
export function validateLicenseKey(licenseKey: string): {
|
||||
isValid: boolean;
|
||||
licenseKeyData?: LicenseKey;
|
||||
} {
|
||||
try {
|
||||
// Decode the base64 license key
|
||||
const decodedString = Buffer.from(licenseKey, "base64").toString("utf8");
|
||||
const { data, signature } = JSON.parse(decodedString);
|
||||
const { data, signature, unsignedData } = JSON.parse(decodedString);
|
||||
|
||||
// Verify the signature
|
||||
const verify = crypto.createVerify("SHA256");
|
||||
|
|
@ -38,36 +50,31 @@ export function validateLicenseKey(licenseKey: string): boolean {
|
|||
|
||||
const isValid = verify.verify(CONTINUE_PUBLIC_KEY, signature, "base64");
|
||||
|
||||
if (!isValid) return false;
|
||||
if (!isValid) return { isValid: false };
|
||||
|
||||
// Check license expiration
|
||||
const licenseData: LicenseData = JSON.parse(data);
|
||||
const licenseData: LicenseKeyData = JSON.parse(data);
|
||||
const expirationDate = new Date(licenseData.expiresAt);
|
||||
const now = new Date();
|
||||
|
||||
return expirationDate > now;
|
||||
const isNotExpired = expirationDate > now;
|
||||
|
||||
if (!isNotExpired) return { isValid: false };
|
||||
|
||||
// Return both validation result and license key data
|
||||
const licenseKeyData: LicenseKey = {
|
||||
signature,
|
||||
data,
|
||||
unsignedData,
|
||||
};
|
||||
|
||||
return { isValid: true, licenseKeyData };
|
||||
} catch (error) {
|
||||
console.error("License validation error:", error);
|
||||
return false;
|
||||
return { isValid: false };
|
||||
}
|
||||
}
|
||||
|
||||
function extractConfigFromArray(config: any[]): Record<string, string> {
|
||||
const configObj: Record<string, string> = {};
|
||||
|
||||
for (let i = 0; i < config.length; i += 2) {
|
||||
if (i + 1 < config.length) {
|
||||
const key = config[i];
|
||||
const value = config[i + 1];
|
||||
if (typeof key === "string") {
|
||||
configObj[key] = value as string;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return configObj;
|
||||
}
|
||||
|
||||
const MACOS_MDM_PATHS = [
|
||||
// Organization-specific MDM plist
|
||||
"/Library/Managed Preferences/dev.continue.app.plist",
|
||||
|
|
@ -88,20 +95,15 @@ function readMdmKeysMacOS(): MdmKeys | undefined {
|
|||
|
||||
try {
|
||||
// Parse the plist file using the plist package
|
||||
const config = plist.parse(fileContent);
|
||||
const config = plist.parse(fileContent) as
|
||||
| { licenseKey: string | undefined }
|
||||
| undefined;
|
||||
|
||||
// Extract the relevant fields from the config
|
||||
// Config is an array of alternating keys and values
|
||||
if (Array.isArray(config)) {
|
||||
const configObj = extractConfigFromArray(config);
|
||||
|
||||
// Check if required keys are present
|
||||
if (configObj.licenseKey && configObj.apiUrl) {
|
||||
return {
|
||||
licenseKey: configObj.licenseKey,
|
||||
apiUrl: configObj.apiUrl,
|
||||
};
|
||||
}
|
||||
if (config && config?.licenseKey) {
|
||||
// Extract the license key from the configuration
|
||||
return { licenseKey: config?.licenseKey };
|
||||
} else {
|
||||
console.error("Invalid MDM configuration format");
|
||||
}
|
||||
} catch (parseError) {
|
||||
console.error(`Error parsing MDM configuration: ${parseError}`);
|
||||
|
|
@ -130,17 +132,11 @@ function readMdmKeysWindows(): MdmKeys | undefined {
|
|||
try {
|
||||
// Use REG QUERY command to read registry values
|
||||
const licenseKeyCmd = `reg query "${regPath}" /v licenseKey`;
|
||||
const apiUrlCmd = `reg query "${regPath}" /v apiUrl`;
|
||||
|
||||
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
|
||||
const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" });
|
||||
|
||||
// Extract values from command output
|
||||
const licenseKey = extractRegValue(licenseKeyOutput);
|
||||
const apiUrl = extractRegValue(apiUrlOutput);
|
||||
|
||||
if (licenseKey && apiUrl) {
|
||||
return { licenseKey, apiUrl };
|
||||
if (licenseKey) {
|
||||
return { licenseKey };
|
||||
}
|
||||
} catch (error) {
|
||||
// Registry key might not exist, fallback to HKEY_CURRENT_USER
|
||||
|
|
@ -149,17 +145,11 @@ function readMdmKeysWindows(): MdmKeys | undefined {
|
|||
// Try HKEY_CURRENT_USER if not found in HKEY_LOCAL_MACHINE
|
||||
try {
|
||||
const licenseKeyCmd = `reg query "${userRegPath}" /v licenseKey`;
|
||||
const apiUrlCmd = `reg query "${userRegPath}" /v apiUrl`;
|
||||
|
||||
const licenseKeyOutput = execSync(licenseKeyCmd, { encoding: "utf8" });
|
||||
const apiUrlOutput = execSync(apiUrlCmd, { encoding: "utf8" });
|
||||
|
||||
// Extract values from command output
|
||||
const licenseKey = extractRegValue(licenseKeyOutput);
|
||||
const apiUrl = extractRegValue(apiUrlOutput);
|
||||
|
||||
if (licenseKey && apiUrl) {
|
||||
return { licenseKey, apiUrl };
|
||||
if (licenseKey) {
|
||||
return { licenseKey };
|
||||
}
|
||||
} catch (error) {
|
||||
// Registry key might not exist in HKCU either
|
||||
|
|
@ -199,11 +189,10 @@ function readMdmKeysLinux(): MdmKeys | undefined {
|
|||
// Parse the JSON configuration file
|
||||
const config = JSON.parse(fileContent);
|
||||
|
||||
// Check if required keys are present
|
||||
if (config.licenseKey && config.apiUrl) {
|
||||
// Check if required key is present
|
||||
if (config.licenseKey) {
|
||||
return {
|
||||
licenseKey: config.licenseKey,
|
||||
apiUrl: config.apiUrl,
|
||||
};
|
||||
}
|
||||
} catch (parseError) {
|
||||
|
|
@ -241,17 +230,20 @@ function readMdmKeys(): MdmKeys | undefined {
|
|||
/**
|
||||
* Read and validate MDM keys from the operating system's configuration files or registry.
|
||||
*/
|
||||
export function getMdmKeys(): MdmKeys | undefined {
|
||||
export function getLicenseKeyData(): LicenseKey | undefined {
|
||||
try {
|
||||
const mdmKeys = readMdmKeys();
|
||||
|
||||
if (mdmKeys) {
|
||||
if (!validateLicenseKey(mdmKeys.licenseKey)) {
|
||||
const { isValid, licenseKeyData } = validateLicenseKey(
|
||||
mdmKeys.licenseKey,
|
||||
);
|
||||
if (!isValid) {
|
||||
console.error("Invalid license key found: ", mdmKeys.licenseKey);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return mdmKeys;
|
||||
return licenseKeyData;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
|
|
@ -260,3 +252,113 @@ export function getMdmKeys(): MdmKeys | undefined {
|
|||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeMdmKeysMacOS(licenseKey: string): boolean {
|
||||
try {
|
||||
// Write to user-specific MDM plist
|
||||
const userMdmPath = path.join(
|
||||
os.homedir(),
|
||||
"Library/Managed Preferences/dev.continue.app.plist",
|
||||
);
|
||||
|
||||
const config = {
|
||||
licenseKey,
|
||||
};
|
||||
|
||||
// Ensure directory exists
|
||||
fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
|
||||
|
||||
// Write the plist file
|
||||
const plistContent = plist.build(config);
|
||||
fs.writeFileSync(userMdmPath, plistContent, "utf8");
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error writing macOS MDM keys:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function writeMdmKeysWindows(licenseKey: string): boolean {
|
||||
try {
|
||||
const { execSync } = require("child_process");
|
||||
|
||||
// Use HKEY_CURRENT_USER to avoid needing admin privileges
|
||||
const userRegPath = "HKCU\\Software\\Continue\\MDM";
|
||||
|
||||
// Create the registry key if it doesn't exist
|
||||
try {
|
||||
execSync(`reg add "${userRegPath}" /f`);
|
||||
} catch (error) {
|
||||
// Key might already exist
|
||||
}
|
||||
|
||||
// Set the license key and API URL
|
||||
execSync(
|
||||
`reg add "${userRegPath}" /v licenseKey /t REG_SZ /d "${licenseKey}" /f`,
|
||||
);
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error writing Windows MDM keys:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function writeMdmKeysLinux(licenseKey: string): boolean {
|
||||
try {
|
||||
// Write to user-specific configuration
|
||||
const userMdmPath = path.join(os.homedir(), ".config/continue/mdm.json");
|
||||
|
||||
const config = {
|
||||
licenseKey,
|
||||
};
|
||||
|
||||
// Ensure directory exists
|
||||
fs.mkdirSync(path.dirname(userMdmPath), { recursive: true });
|
||||
|
||||
// Write the JSON configuration file
|
||||
fs.writeFileSync(userMdmPath, JSON.stringify(config, null, 2), "utf8");
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error("Error writing Linux MDM keys:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store the license key in the appropriate OS-specific location.
|
||||
* For now, we'll use a default API URL since it's not provided in the command.
|
||||
*/
|
||||
export function setMdmLicenseKey(licenseKey: string): boolean {
|
||||
try {
|
||||
// Validate the license key first
|
||||
const { isValid } = validateLicenseKey(licenseKey);
|
||||
if (!isValid) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const platform = os.platform();
|
||||
|
||||
switch (platform) {
|
||||
case "darwin":
|
||||
return writeMdmKeysMacOS(licenseKey);
|
||||
|
||||
case "win32":
|
||||
return writeMdmKeysWindows(licenseKey);
|
||||
|
||||
case "linux":
|
||||
return writeMdmKeysLinux(licenseKey);
|
||||
|
||||
default:
|
||||
console.error(
|
||||
`Setting MDM keys not supported on platform: ${platform}`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error setting MDM license key:", error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
|
@ -20,7 +20,7 @@ const modelDescriptionSchema = z.object({
|
|||
"nebius",
|
||||
"siliconflow",
|
||||
"scaleway",
|
||||
"watsonx"
|
||||
"watsonx",
|
||||
]),
|
||||
model: z.string(),
|
||||
apiKey: z.string().optional(),
|
||||
|
|
@ -88,13 +88,12 @@ const embeddingsProviderSchema = z.object({
|
|||
"ollama",
|
||||
"openai",
|
||||
"cohere",
|
||||
"free-trial",
|
||||
"gemini",
|
||||
"ovhcloud",
|
||||
"nebius",
|
||||
"siliconflow",
|
||||
"scaleway",
|
||||
"watsonx"
|
||||
"watsonx",
|
||||
]),
|
||||
apiBase: z.string().optional(),
|
||||
apiKey: z.string().optional(),
|
||||
|
|
|
|||
353
core/core.ts
353
core/core.ts
|
|
@ -3,18 +3,21 @@ import * as URI from "uri-js";
|
|||
import { v4 as uuidv4 } from "uuid";
|
||||
|
||||
import { CompletionProvider } from "./autocomplete/CompletionProvider";
|
||||
import {
|
||||
openedFilesLruCache,
|
||||
prevFilepaths,
|
||||
} from "./autocomplete/util/openedFilesLruCache";
|
||||
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 { recentlyEditedFilesCache } from "./context/retrieval/recentlyEditedFilesCache";
|
||||
import { ContinueServerClient } from "./continueServer/stubs/client";
|
||||
import { getAuthUrlForTokenPage } from "./control-plane/auth/index";
|
||||
import { getControlPlaneEnv } from "./control-plane/env";
|
||||
import { DevDataSqliteDb } from "./data/devdataSqlite";
|
||||
import { DataLogger } from "./data/log";
|
||||
import { CodebaseIndexer, PauseToken } from "./indexing/CodebaseIndexer";
|
||||
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
|
||||
import DocsService from "./indexing/docs/DocsService";
|
||||
import { countTokens } from "./llm/countTokens";
|
||||
import Ollama from "./llm/llms/Ollama";
|
||||
|
|
@ -34,6 +37,7 @@ import { getSymbolsForManyFiles } from "./util/treeSitter";
|
|||
import { TTS } from "./util/tts";
|
||||
|
||||
import {
|
||||
CompleteOnboardingPayload,
|
||||
ContextItemWithId,
|
||||
IdeSettings,
|
||||
ModelDescription,
|
||||
|
|
@ -41,42 +45,49 @@ import {
|
|||
type ContextItem,
|
||||
type ContextItemId,
|
||||
type IDE,
|
||||
type IndexingProgressUpdate,
|
||||
} from ".";
|
||||
|
||||
import { ConfigYaml } from "@continuedev/config-yaml";
|
||||
import { isLocalAssistantFile } from "./config/loadLocalAssistants";
|
||||
import { getDiffFn, GitDiffCache } from "./autocomplete/snippets/gitDiffCache";
|
||||
import { isLocalDefinitionFile } from "./config/loadLocalAssistants";
|
||||
import {
|
||||
setupBestConfig,
|
||||
setupLocalConfig,
|
||||
setupProviderConfig,
|
||||
setupQuickstartConfig,
|
||||
} from "./config/onboarding";
|
||||
import { createNewWorkspaceBlockFile } from "./config/workspace/workspaceBlocks";
|
||||
import { MCPManagerSingleton } from "./context/mcp/MCPManagerSingleton";
|
||||
import { setMdmLicenseKey } from "./control-plane/mdm/mdm";
|
||||
import { ApplyAbortManager } from "./edit/applyAbortManager";
|
||||
import { streamDiffLines } from "./edit/streamDiffLines";
|
||||
import { shouldIgnore } from "./indexing/shouldIgnore";
|
||||
import { walkDirCache } from "./indexing/walkDir";
|
||||
import { LLMError } from "./llm";
|
||||
import { LLMLogger } from "./llm/logger";
|
||||
import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants";
|
||||
import { llmStreamChat } from "./llm/streamChat";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import { OnboardingModes } from "./protocol/core";
|
||||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
import { getUriPathBasename } from "./util/uri";
|
||||
|
||||
const hasRulesFiles = (uris: string[]): boolean => {
|
||||
for (const uri of uris) {
|
||||
const filename = getUriPathBasename(uri);
|
||||
if (filename === RULES_MARKDOWN_FILENAME) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
export class Core {
|
||||
configHandler: ConfigHandler;
|
||||
codebaseIndexerPromise: Promise<CodebaseIndexer>;
|
||||
codeBaseIndexer: CodebaseIndexer;
|
||||
completionProvider: CompletionProvider;
|
||||
continueServerClientPromise: Promise<ContinueServerClient>;
|
||||
codebaseIndexingState: IndexingProgressUpdate;
|
||||
private docsService: DocsService;
|
||||
private globalContext = new GlobalContext();
|
||||
llmLogger = new LLMLogger();
|
||||
|
||||
private readonly indexingPauseToken = new PauseToken(
|
||||
this.globalContext.get("indexingPaused") === true,
|
||||
);
|
||||
|
||||
private messageAbortControllers = new Map<string, AbortController>();
|
||||
private addMessageAbortController(id: string): AbortController {
|
||||
const controller = new AbortController();
|
||||
|
|
@ -114,12 +125,6 @@ export class Core {
|
|||
// Ensure .continue directory is created
|
||||
migrateV1DevDataFiles();
|
||||
|
||||
this.codebaseIndexingState = {
|
||||
status: "loading",
|
||||
desc: "loading",
|
||||
progress: 0,
|
||||
};
|
||||
|
||||
const ideInfoPromise = messenger.request("getIdeInfo", undefined);
|
||||
const ideSettingsPromise = messenger.request("getIdeSettings", undefined);
|
||||
const sessionInfoPromise = messenger.request("getControlPlaneSessionInfo", {
|
||||
|
|
@ -140,28 +145,37 @@ export class Core {
|
|||
this.messenger,
|
||||
);
|
||||
|
||||
MCPManagerSingleton.getInstance().onConnectionsRefreshed = async () => {
|
||||
await this.configHandler.reloadConfig();
|
||||
MCPManagerSingleton.getInstance().onConnectionsRefreshed = () => {
|
||||
void this.configHandler.reloadConfig();
|
||||
};
|
||||
|
||||
this.configHandler.onConfigUpdate(async (result) => {
|
||||
const serializedResult = await this.configHandler.getSerializedConfig();
|
||||
this.messenger.send("configUpdate", {
|
||||
result: serializedResult,
|
||||
profileId:
|
||||
this.configHandler.currentProfile?.profileDescription.id || null,
|
||||
organizations: this.configHandler.getSerializedOrgs(),
|
||||
selectedOrgId: this.configHandler.currentOrg.id,
|
||||
});
|
||||
this.codeBaseIndexer = new CodebaseIndexer(
|
||||
this.configHandler,
|
||||
this.ide,
|
||||
this.messenger,
|
||||
this.globalContext.get("indexingPaused"),
|
||||
);
|
||||
|
||||
// update additional submenu context providers registered via VSCode API
|
||||
const additionalProviders =
|
||||
this.configHandler.getAdditionalSubmenuContextProviders();
|
||||
if (additionalProviders.length > 0) {
|
||||
this.messenger.send("refreshSubmenuItems", {
|
||||
providers: additionalProviders,
|
||||
this.configHandler.onConfigUpdate((result) => {
|
||||
void (async () => {
|
||||
const serializedResult = await this.configHandler.getSerializedConfig();
|
||||
this.messenger.send("configUpdate", {
|
||||
result: serializedResult,
|
||||
profileId:
|
||||
this.configHandler.currentProfile?.profileDescription.id || null,
|
||||
organizations: this.configHandler.getSerializedOrgs(),
|
||||
selectedOrgId: this.configHandler.currentOrg.id,
|
||||
});
|
||||
}
|
||||
|
||||
// update additional submenu context providers registered via VSCode API
|
||||
const additionalProviders =
|
||||
this.configHandler.getAdditionalSubmenuContextProviders();
|
||||
if (additionalProviders.length > 0) {
|
||||
this.messenger.send("refreshSubmenuItems", {
|
||||
providers: additionalProviders,
|
||||
});
|
||||
}
|
||||
})();
|
||||
});
|
||||
|
||||
// Dev Data Logger
|
||||
|
|
@ -170,38 +184,17 @@ export class Core {
|
|||
dataLogger.ideInfoPromise = ideInfoPromise;
|
||||
dataLogger.ideSettingsPromise = ideSettingsPromise;
|
||||
|
||||
// Codebase Indexer and ContinueServerClient depend on IdeSettings
|
||||
let codebaseIndexerResolve: (_: any) => void | undefined;
|
||||
this.codebaseIndexerPromise = new Promise(
|
||||
async (resolve) => (codebaseIndexerResolve = resolve),
|
||||
);
|
||||
|
||||
let continueServerClientResolve: (_: any) => void | undefined;
|
||||
this.continueServerClientPromise = new Promise(
|
||||
(resolve) => (continueServerClientResolve = resolve),
|
||||
);
|
||||
|
||||
void ideSettingsPromise.then((ideSettings) => {
|
||||
const continueServerClient = new ContinueServerClient(
|
||||
ideSettings.remoteConfigServerUrl,
|
||||
ideSettings.userToken,
|
||||
);
|
||||
continueServerClientResolve(continueServerClient);
|
||||
|
||||
codebaseIndexerResolve(
|
||||
new CodebaseIndexer(
|
||||
this.configHandler,
|
||||
this.ide,
|
||||
this.indexingPauseToken,
|
||||
continueServerClient,
|
||||
),
|
||||
);
|
||||
|
||||
// Index on initialization
|
||||
void this.ide.getWorkspaceDirs().then(async (dirs) => {
|
||||
// Respect pauseCodebaseIndexOnStart user settings
|
||||
if (ideSettings.pauseCodebaseIndexOnStart) {
|
||||
this.indexingPauseToken.paused = true;
|
||||
this.codeBaseIndexer.paused = true;
|
||||
void this.messenger.request("indexProgress", {
|
||||
progress: 0,
|
||||
desc: "Initial Indexing Skipped",
|
||||
|
|
@ -210,7 +203,7 @@ export class Core {
|
|||
return;
|
||||
}
|
||||
|
||||
void this.refreshCodebaseIndex(dirs);
|
||||
void this.codeBaseIndexer.refreshCodebaseIndex(dirs);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -362,6 +355,16 @@ export class Core {
|
|||
await this.messenger.request("openUrl", url);
|
||||
});
|
||||
|
||||
on("controlPlane/getFreeTrialStatus", async (msg) => {
|
||||
return this.configHandler.controlPlaneClient.getFreeTrialStatus();
|
||||
});
|
||||
|
||||
on("controlPlane/getModelsAddOnUpgradeUrl", async (msg) => {
|
||||
return this.configHandler.controlPlaneClient.getModelsAddOnCheckoutUrl(
|
||||
msg.data.vsCodeUriScheme,
|
||||
);
|
||||
});
|
||||
|
||||
on("mcp/reloadServer", async (msg) => {
|
||||
await MCPManagerSingleton.getInstance().refreshConnection(msg.data.id);
|
||||
});
|
||||
|
|
@ -536,7 +539,7 @@ export class Core {
|
|||
abortManager.clear(); // for now abort all streams
|
||||
});
|
||||
|
||||
on("completeOnboarding", this.handleCompleteOnboarding.bind(this));
|
||||
on("onboarding/complete", this.handleCompleteOnboarding.bind(this));
|
||||
|
||||
on("addAutocompleteModel", this.handleAddAutocompleteModel.bind(this));
|
||||
|
||||
|
|
@ -556,25 +559,24 @@ export class Core {
|
|||
}
|
||||
walkDirCache.invalidate();
|
||||
if (data?.shouldClearIndexes) {
|
||||
const codebaseIndexer = await this.codebaseIndexerPromise;
|
||||
await codebaseIndexer.clearIndexes();
|
||||
await this.codeBaseIndexer.clearIndexes();
|
||||
}
|
||||
|
||||
const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs());
|
||||
await this.refreshCodebaseIndex(dirs);
|
||||
await this.codeBaseIndexer.refreshCodebaseIndex(dirs);
|
||||
});
|
||||
on("index/setPaused", (msg) => {
|
||||
this.globalContext.update("indexingPaused", msg.data);
|
||||
this.indexingPauseToken.paused = msg.data;
|
||||
// Update using the new setter instead of token
|
||||
this.codeBaseIndexer.paused = msg.data;
|
||||
});
|
||||
on("index/indexingProgressBarInitialized", async (msg) => {
|
||||
// Triggered when progress bar is initialized.
|
||||
// If a non-default state has been stored, update the indexing display to that state
|
||||
if (this.codebaseIndexingState.status !== "loading") {
|
||||
void this.messenger.request(
|
||||
"indexProgress",
|
||||
this.codebaseIndexingState,
|
||||
);
|
||||
const currentState = this.codeBaseIndexer.currentIndexingState;
|
||||
|
||||
if (currentState.status !== "loading") {
|
||||
void this.messenger.request("indexProgress", currentState);
|
||||
}
|
||||
});
|
||||
|
||||
|
|
@ -594,7 +596,7 @@ export class Core {
|
|||
});
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (config && !config.disableIndexing) {
|
||||
await this.refreshCodebaseIndexFiles(toRefresh);
|
||||
await this.codeBaseIndexer.refreshCodebaseIndexFiles(toRefresh);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
|
@ -604,10 +606,14 @@ export class Core {
|
|||
walkDirCache.invalidate();
|
||||
void refreshIfNotIgnored(data.uris);
|
||||
|
||||
if (hasRulesFiles(data.uris)) {
|
||||
await this.configHandler.reloadConfig();
|
||||
}
|
||||
|
||||
// If it's a local assistant being created, we want to reload all assistants so it shows up in the list
|
||||
let localAssistantCreated = false;
|
||||
for (const uri of data.uris) {
|
||||
if (isLocalAssistantFile(uri)) {
|
||||
if (isLocalDefinitionFile(uri)) {
|
||||
localAssistantCreated = true;
|
||||
}
|
||||
}
|
||||
|
|
@ -621,10 +627,40 @@ export class Core {
|
|||
if (data?.uris?.length) {
|
||||
walkDirCache.invalidate();
|
||||
void refreshIfNotIgnored(data.uris);
|
||||
|
||||
if (hasRulesFiles(data.uris)) {
|
||||
await this.configHandler.reloadConfig();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
on("files/closed", async ({ data }) => {
|
||||
try {
|
||||
const fileUris = await this.ide.getOpenFiles();
|
||||
if (fileUris) {
|
||||
const filepaths = fileUris.map((uri) => uri.toString());
|
||||
|
||||
if (!prevFilepaths.filepaths.length) {
|
||||
prevFilepaths.filepaths = filepaths;
|
||||
}
|
||||
|
||||
// If there is a removal, including if the number of tabs is the same (which can happen with temp tabs)
|
||||
if (filepaths.length <= prevFilepaths.filepaths.length) {
|
||||
// Remove files from cache that are no longer open (i.e. in the cache but not in the list of opened tabs)
|
||||
for (const [key, _] of openedFilesLruCache.entriesDescending()) {
|
||||
if (!filepaths.includes(key)) {
|
||||
openedFilesLruCache.delete(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
prevFilepaths.filepaths = filepaths;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`didChangeVisibleTextEditors: failed to update openedFilesLruCache`,
|
||||
);
|
||||
}
|
||||
|
||||
if (data.uris) {
|
||||
this.messenger.send("didCloseFiles", {
|
||||
uris: data.uris,
|
||||
|
|
@ -632,7 +668,26 @@ export class Core {
|
|||
}
|
||||
});
|
||||
|
||||
on("files/opened", async () => {});
|
||||
on("files/opened", async ({ data: { uris } }) => {
|
||||
if (uris) {
|
||||
for (const filepath of uris) {
|
||||
try {
|
||||
const ignore = await shouldIgnore(filepath, this.ide);
|
||||
if (!ignore) {
|
||||
// Set the active file as most recently used (need to force recency update by deleting and re-adding)
|
||||
if (openedFilesLruCache.has(filepath)) {
|
||||
openedFilesLruCache.delete(filepath);
|
||||
}
|
||||
openedFilesLruCache.set(filepath, filepath);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`files/opened: failed to update openedFiles cache for ${filepath}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Docs, etc. indexing
|
||||
on("indexing/reindex", async (msg) => {
|
||||
|
|
@ -688,19 +743,6 @@ export class Core {
|
|||
return { url };
|
||||
});
|
||||
|
||||
on("didChangeActiveTextEditor", async ({ data: { filepath } }) => {
|
||||
try {
|
||||
const ignore = await shouldIgnore(filepath, this.ide);
|
||||
if (!ignore) {
|
||||
recentlyEditedFilesCache.set(filepath, filepath);
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(
|
||||
`didChangeActiveTextEditor: failed to update recentlyEditedFiles cache for ${filepath}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
on("tools/call", async ({ data: { toolCall } }) => {
|
||||
const { config } = await this.configHandler.loadConfig();
|
||||
if (!config) {
|
||||
|
|
@ -727,7 +769,8 @@ export class Core {
|
|||
this.messenger.send("toolCallPartialOutput", params);
|
||||
};
|
||||
|
||||
return await callTool(tool, toolCall.function.arguments, {
|
||||
return await callTool(tool, toolCall, {
|
||||
config,
|
||||
ide: this.ide,
|
||||
llm: config.selectedModelByRole.chat,
|
||||
fetch: (url, init) =>
|
||||
|
|
@ -735,6 +778,7 @@ export class Core {
|
|||
tool,
|
||||
toolCallId: toolCall.id,
|
||||
onPartialOutput,
|
||||
codeBaseIndexer: this.codeBaseIndexer,
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -754,6 +798,11 @@ export class Core {
|
|||
return isBackgrounded; // Return true to indicate the message was handled successfully
|
||||
},
|
||||
);
|
||||
|
||||
on("mdm/setLicenseKey", ({ data: { licenseKey } }) => {
|
||||
const isValid = setMdmLicenseKey(licenseKey);
|
||||
return isValid;
|
||||
});
|
||||
}
|
||||
|
||||
private async isItemTooBig(item: ContextItemWithId) {
|
||||
|
|
@ -811,8 +860,10 @@ export class Core {
|
|||
data,
|
||||
}: Message<{
|
||||
uris?: string[];
|
||||
}>) {
|
||||
}>): Promise<void> {
|
||||
if (data?.uris?.length) {
|
||||
const diffCache = GitDiffCache.getInstance(getDiffFn(this.ide));
|
||||
diffCache.invalidate();
|
||||
walkDirCache.invalidate(); // safe approach for now - TODO - only invalidate on relevant changes
|
||||
for (const uri of data.uris) {
|
||||
const currentProfileUri =
|
||||
|
|
@ -840,7 +891,8 @@ export class Core {
|
|||
uri.endsWith(".continuerc.json") ||
|
||||
uri.endsWith(".prompt") ||
|
||||
uri.endsWith(SYSTEM_PROMPT_DOT_FILE) ||
|
||||
(uri.includes(".continue") && uri.endsWith(".yaml"))
|
||||
(uri.includes(".continue") && uri.endsWith(".yaml")) ||
|
||||
uri.endsWith(RULES_MARKDOWN_FILENAME)
|
||||
) {
|
||||
await this.configHandler.reloadConfig();
|
||||
} else if (
|
||||
|
|
@ -857,7 +909,7 @@ export class Core {
|
|||
// Reindex the file
|
||||
const ignore = await shouldIgnore(uri, this.ide);
|
||||
if (!ignore) {
|
||||
await this.refreshCodebaseIndexFiles([uri]);
|
||||
await this.codeBaseIndexer.refreshCodebaseIndexFiles([uri]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -896,26 +948,25 @@ export class Core {
|
|||
}
|
||||
}
|
||||
|
||||
private async handleCompleteOnboarding(msg: Message<{ mode: string }>) {
|
||||
const mode = msg.data.mode;
|
||||
|
||||
if (mode === "Custom") {
|
||||
return;
|
||||
}
|
||||
private async handleCompleteOnboarding(
|
||||
msg: Message<CompleteOnboardingPayload>,
|
||||
) {
|
||||
const { mode, provider, apiKey } = msg.data;
|
||||
|
||||
let editConfigYamlCallback: (config: ConfigYaml) => ConfigYaml;
|
||||
|
||||
switch (mode) {
|
||||
case "Local":
|
||||
case OnboardingModes.LOCAL:
|
||||
editConfigYamlCallback = setupLocalConfig;
|
||||
break;
|
||||
|
||||
case "Quickstart":
|
||||
editConfigYamlCallback = setupQuickstartConfig;
|
||||
break;
|
||||
|
||||
case "Best":
|
||||
editConfigYamlCallback = setupBestConfig;
|
||||
case OnboardingModes.API_KEY:
|
||||
if (provider && apiKey) {
|
||||
editConfigYamlCallback = (config: ConfigYaml) =>
|
||||
setupProviderConfig(config, provider, apiKey);
|
||||
} else {
|
||||
editConfigYamlCallback = setupQuickstartConfig;
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
|
|
@ -1028,100 +1079,4 @@ export class Core {
|
|||
return [];
|
||||
}
|
||||
};
|
||||
|
||||
private indexingCancellationController: AbortController | undefined;
|
||||
private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) {
|
||||
console.debug(
|
||||
"Indexing failed with error: ",
|
||||
update.desc,
|
||||
update.debugInfo,
|
||||
);
|
||||
void Telemetry.capture(
|
||||
"indexing_error",
|
||||
{
|
||||
error: update.desc,
|
||||
stack: update.debugInfo,
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
private async refreshCodebaseIndex(paths: string[]) {
|
||||
if (this.indexingCancellationController) {
|
||||
this.indexingCancellationController.abort();
|
||||
}
|
||||
this.indexingCancellationController = new AbortController();
|
||||
try {
|
||||
for await (const update of (
|
||||
await this.codebaseIndexerPromise
|
||||
).refreshDirs(paths, this.indexingCancellationController.signal)) {
|
||||
let updateToSend = { ...update };
|
||||
|
||||
void this.messenger.request("indexProgress", updateToSend);
|
||||
this.codebaseIndexingState = updateToSend;
|
||||
|
||||
if (update.status === "failed") {
|
||||
void this.sendIndexingErrorTelemetry(update);
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.log(`Failed refreshing codebase index directories : ${e}`);
|
||||
this.handleIndexingError(e);
|
||||
}
|
||||
|
||||
this.messenger.send("refreshSubmenuItems", {
|
||||
providers: "dependsOnIndexing",
|
||||
});
|
||||
this.indexingCancellationController = undefined;
|
||||
}
|
||||
|
||||
private async refreshCodebaseIndexFiles(files: string[]) {
|
||||
// Can be cancelled by codebase index but not vice versa
|
||||
if (
|
||||
this.indexingCancellationController &&
|
||||
!this.indexingCancellationController.signal.aborted
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.indexingCancellationController = new AbortController();
|
||||
try {
|
||||
for await (const update of (
|
||||
await this.codebaseIndexerPromise
|
||||
).refreshFiles(files)) {
|
||||
let updateToSend = { ...update };
|
||||
|
||||
void this.messenger.request("indexProgress", updateToSend);
|
||||
this.codebaseIndexingState = updateToSend;
|
||||
|
||||
if (update.status === "failed") {
|
||||
void this.sendIndexingErrorTelemetry(update);
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.log(`Failed refreshing codebase index files : ${e}`);
|
||||
this.handleIndexingError(e);
|
||||
}
|
||||
|
||||
this.messenger.send("refreshSubmenuItems", {
|
||||
providers: "dependsOnIndexing",
|
||||
});
|
||||
this.indexingCancellationController = undefined;
|
||||
}
|
||||
|
||||
// private
|
||||
handleIndexingError(e: any) {
|
||||
if (e instanceof LLMError) {
|
||||
// Need to report this specific error to the IDE for special handling
|
||||
void this.messenger.request("reportError", e);
|
||||
}
|
||||
// broadcast indexing error
|
||||
let updateToSend: IndexingProgressUpdate = {
|
||||
progress: 0,
|
||||
status: "failed",
|
||||
desc: e.message,
|
||||
};
|
||||
void this.messenger.request("indexProgress", updateToSend);
|
||||
this.codebaseIndexingState = updateToSend;
|
||||
void this.sendIndexingErrorTelemetry(updateToSend);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
0
core/core_temp.ts
Normal file
0
core/core_temp.ts
Normal file
|
|
@ -18,6 +18,19 @@ const TEST_EVENT: DevDataLogEvent = {
|
|||
provider: "openai",
|
||||
},
|
||||
};
|
||||
|
||||
const TEST_AGENT_INTERACTION_EVENT: DevDataLogEvent = {
|
||||
name: "chatInteraction",
|
||||
data: {
|
||||
prompt: "Hello, world!",
|
||||
completion: "Hello, world!",
|
||||
modelProvider: "openai",
|
||||
modelTitle: "gpt-4",
|
||||
sessionId: "1234",
|
||||
tools: ["test-tool1"],
|
||||
},
|
||||
};
|
||||
|
||||
const SCHEMA = "0.2.0";
|
||||
|
||||
describe("DataLogger", () => {
|
||||
|
|
@ -157,6 +170,26 @@ describe("DataLogger", () => {
|
|||
expect(fileContent).toContain('"model":"gpt-4"');
|
||||
expect(fileContent).toContain('"eventName":"tokensGenerated"');
|
||||
});
|
||||
|
||||
it("should write agent interaction data to local file", async () => {
|
||||
// Call the method to log data locally
|
||||
await dataLogger.logLocalData(TEST_AGENT_INTERACTION_EVENT);
|
||||
|
||||
// Verify the file was created
|
||||
const filepath = getDevDataFilePath(
|
||||
TEST_AGENT_INTERACTION_EVENT.name,
|
||||
SCHEMA,
|
||||
);
|
||||
expect(fs.existsSync(filepath)).toBe(true);
|
||||
|
||||
// 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!"');
|
||||
expect(fileContent).toContain('"tools":["test-tool1"]');
|
||||
});
|
||||
});
|
||||
|
||||
describe("logDevData", () => {
|
||||
|
|
|
|||
|
|
@ -43,7 +43,7 @@ describe("isUnifiedDiffFormat", () => {
|
|||
expect(isUnifiedDiffFormat(diffWithoutFileHeaders)).toBe(true);
|
||||
});
|
||||
|
||||
it("should return true in case of empty lines", () => {
|
||||
it("should return true in case of empty lines", () => {
|
||||
const diffWithoutFileHeaders = `@@ -1,3 +1,4 @@
|
||||
line1
|
||||
|
||||
|
|
@ -83,16 +83,25 @@ describe("applyUnifiedDiff", () => {
|
|||
const expected = [
|
||||
{ type: "same", line: "func main() {" },
|
||||
{ type: "same", line: " scanner := bufio.NewScanner(os.Stdin)" },
|
||||
{ type: "same", line: " fmt.Println(\"Calculator started! Available operations:\")" },
|
||||
{ type: "same", line: " fmt.Println(\" + : Addition\")" },
|
||||
{ type: "same", line: " fmt.Println(\" - : Subtraction\")" },
|
||||
{ type: "same", line: " fmt.Println(\" * : Multiplication\")" },
|
||||
{ type: "same", line: " fmt.Println(\" / : Division\")" },
|
||||
{ type: "same", line: " fmt.Println(\" ^ : Power\")" },
|
||||
{ type: "same", line: " fmt.Println(\" √ : Square root (use only one number)\")" },
|
||||
{ type: "new", line: " fmt.Println(\" log: Logarithm (use 'log base number')\")" },
|
||||
{
|
||||
type: "same",
|
||||
line: ' fmt.Println("Calculator started! Available operations:")',
|
||||
},
|
||||
{ type: "same", line: ' fmt.Println(" + : Addition")' },
|
||||
{ type: "same", line: ' fmt.Println(" - : Subtraction")' },
|
||||
{ type: "same", line: ' fmt.Println(" * : Multiplication")' },
|
||||
{ type: "same", line: ' fmt.Println(" / : Division")' },
|
||||
{ type: "same", line: ' fmt.Println(" ^ : Power")' },
|
||||
{
|
||||
type: "same",
|
||||
line: ' fmt.Println(" √ : Square root (use only one number)")',
|
||||
},
|
||||
{
|
||||
type: "new",
|
||||
line: " fmt.Println(\" log: Logarithm (use 'log base number')\")",
|
||||
},
|
||||
{ type: "same", line: "}" },
|
||||
{ type: "same", line: "// End of file" }
|
||||
{ type: "same", line: "// End of file" },
|
||||
];
|
||||
|
||||
expect(result).toEqual(expected);
|
||||
|
|
@ -130,18 +139,18 @@ func main() {
|
|||
const expected = [
|
||||
{ type: "same", line: "package main" },
|
||||
{ type: "same", line: "" },
|
||||
{ type: "old", line: "import \"fmt\"" },
|
||||
{ type: "old", line: 'import "fmt"' },
|
||||
{ type: "new", line: "import (" },
|
||||
{ type: "new", line: " \"fmt\"" },
|
||||
{ type: "new", line: " \"time\"" },
|
||||
{ type: "new", line: ' "fmt"' },
|
||||
{ type: "new", line: ' "time"' },
|
||||
{ type: "new", line: ")" },
|
||||
{ type: "same", line: "" },
|
||||
{ type: "same", line: "func main() {" },
|
||||
{ type: "old", line: " fmt.Println(\"Hello\")" },
|
||||
{ type: "new", line: " fmt.Printf(\"The time is: %v\\n\", time.Now())" },
|
||||
{ type: "old", line: " fmt.Println(\"World\")" },
|
||||
{ type: "new", line: " fmt.Println(\"Goodbye!\")" },
|
||||
{ type: "same", line: "}" }
|
||||
{ type: "old", line: ' fmt.Println("Hello")' },
|
||||
{ type: "new", line: ' fmt.Printf("The time is: %v\\n", time.Now())' },
|
||||
{ type: "old", line: ' fmt.Println("World")' },
|
||||
{ type: "new", line: ' fmt.Println("Goodbye!")' },
|
||||
{ type: "same", line: "}" },
|
||||
];
|
||||
|
||||
expect(result).toEqual(expected);
|
||||
|
|
@ -379,29 +388,47 @@ func TestLargeNumbers(t *testing.T) {
|
|||
|
||||
expect(result[0].line).toEqual("package main");
|
||||
// 1st block
|
||||
expect(result[18].line).toEqual("\tfmt.Println(\" √ : Square root (use only one number)\")");
|
||||
expect(result[19].line).toEqual(" fmt.Println(\" log: Logarithm (use 'log base number')\")");
|
||||
expect(result[20].line).toEqual(" fmt.Println(\" Base must be > 0 and != 1, number must be > 0\")");
|
||||
// 2nd block
|
||||
expect(result[56]).toEqual({type: "same", line: "\t}"});
|
||||
expect(result[57]).toEqual({type: "new", line: "\t"});
|
||||
expect(result[58]).toEqual({type: "new", line: "\t// Handle logarithmic operations"});
|
||||
expect(result[73]).toEqual({type: "new", line: ""});
|
||||
expect(result[74]).toEqual({type: "same", line: "\tif len(parts) != 3 {"});
|
||||
// 3rd block
|
||||
expect(result[140]).toEqual({type: "same", line: "}"});
|
||||
expect(result[141]).toEqual({type: "new", line: ""});
|
||||
expect(result[142]).toEqual({type: "new", line: "func TestLogarithmicCases(t *testing.T) {"});
|
||||
expect(result[153]).toEqual({type: "new", line: "\t}"});
|
||||
expect(result[154]).toEqual({type: "same", line: "func TestSpecialCases(t *testing.T) {"});
|
||||
});
|
||||
expect(result[18].line).toEqual(
|
||||
'\tfmt.Println(" √ : Square root (use only one number)")',
|
||||
);
|
||||
expect(result[19].line).toEqual(
|
||||
" fmt.Println(\" log: Logarithm (use 'log base number')\")",
|
||||
);
|
||||
expect(result[20].line).toEqual(
|
||||
' fmt.Println(" Base must be > 0 and != 1, number must be > 0")',
|
||||
);
|
||||
// 2nd block
|
||||
expect(result[56]).toEqual({ type: "same", line: "\t}" });
|
||||
expect(result[57]).toEqual({ type: "new", line: "\t" });
|
||||
expect(result[58]).toEqual({
|
||||
type: "new",
|
||||
line: "\t// Handle logarithmic operations",
|
||||
});
|
||||
expect(result[73]).toEqual({ type: "new", line: "" });
|
||||
expect(result[74]).toEqual({
|
||||
type: "same",
|
||||
line: "\tif len(parts) != 3 {",
|
||||
});
|
||||
// 3rd block
|
||||
expect(result[140]).toEqual({ type: "same", line: "}" });
|
||||
expect(result[141]).toEqual({ type: "new", line: "" });
|
||||
expect(result[142]).toEqual({
|
||||
type: "new",
|
||||
line: "func TestLogarithmicCases(t *testing.T) {",
|
||||
});
|
||||
expect(result[153]).toEqual({ type: "new", line: "\t}" });
|
||||
expect(result[154]).toEqual({
|
||||
type: "same",
|
||||
line: "func TestSpecialCases(t *testing.T) {",
|
||||
});
|
||||
});
|
||||
|
||||
it("should throw error when hunk cannot be matched to source", () => {
|
||||
const sourceCode = `line1
|
||||
it("should throw error when hunk cannot be matched to source", () => {
|
||||
const sourceCode = `line1
|
||||
line2
|
||||
line3`;
|
||||
|
||||
const diffText = `--- a.txt
|
||||
const diffText = `--- a.txt
|
||||
+++ b.txt
|
||||
@@ -1,3 +1,4 @@
|
||||
missing1
|
||||
|
|
@ -409,7 +436,8 @@ missing1
|
|||
+newline2
|
||||
missing3`;
|
||||
|
||||
expect(() => applyUnifiedDiff(sourceCode, diffText))
|
||||
.toThrow("Hunk could not be applied cleanly to source code.");
|
||||
});
|
||||
expect(() => applyUnifiedDiff(sourceCode, diffText)).toThrow(
|
||||
"Hunk could not be applied cleanly to source code.",
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -8,7 +8,9 @@ import { DiffLine } from "../../index";
|
|||
export function isUnifiedDiffFormat(diff: string): boolean {
|
||||
const lines = diff.trim().split("\n");
|
||||
|
||||
if (lines.length < 3) {return false;}
|
||||
if (lines.length < 3) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let hasHunkHeader = false;
|
||||
let hasValidContent = false;
|
||||
|
|
@ -35,10 +37,13 @@ function extractBeforeLines(hunkLines: string[]): string[] {
|
|||
/**
|
||||
* Applies a unified diff to source code and returns an array of DiffLine objects.
|
||||
* Each DiffLine contains a type ("same", "new", or "old") and the line content.
|
||||
*
|
||||
*
|
||||
* @throws Error if the diff cannot be cleanly applied to the source
|
||||
*/
|
||||
export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): DiffLine[] {
|
||||
export function applyUnifiedDiff(
|
||||
sourceCode: string,
|
||||
unifiedDiffText: string,
|
||||
): DiffLine[] {
|
||||
const sourceLines = sourceCode.split(/\r?\n/);
|
||||
const hunks = parseUnifiedDiff(unifiedDiffText);
|
||||
const diffResult: DiffLine[] = [];
|
||||
|
|
@ -46,7 +51,11 @@ export function applyUnifiedDiff(sourceCode: string, unifiedDiffText: string): D
|
|||
|
||||
for (const hunk of hunks) {
|
||||
const hunkBeforeLines = extractBeforeLines(hunk.lines);
|
||||
const hunkStart = findHunkInSource(sourceLines, hunkBeforeLines, currentPos);
|
||||
const hunkStart = findHunkInSource(
|
||||
sourceLines,
|
||||
hunkBeforeLines,
|
||||
currentPos,
|
||||
);
|
||||
if (hunkStart === -1) {
|
||||
// All hunks must be found in the source code. If not, throw an error.
|
||||
throw new Error("Hunk could not be applied cleanly to source code.");
|
||||
|
|
@ -124,8 +133,16 @@ function parseUnifiedDiff(diffText: string): Hunk[] {
|
|||
*
|
||||
* Returns the index in sourceLines where the block begins, or -1 if no match is found.
|
||||
*/
|
||||
function findHunkInSource(sourceLines: string[], hunkBeforeLines: string[], startIndex: number): number {
|
||||
for (let i = startIndex; i <= sourceLines.length - hunkBeforeLines.length; i++) {
|
||||
function findHunkInSource(
|
||||
sourceLines: string[],
|
||||
hunkBeforeLines: string[],
|
||||
startIndex: number,
|
||||
): number {
|
||||
for (
|
||||
let i = startIndex;
|
||||
i <= sourceLines.length - hunkBeforeLines.length;
|
||||
i++
|
||||
) {
|
||||
let match = true;
|
||||
for (let j = 0; j < hunkBeforeLines.length; j++) {
|
||||
const sl = sourceLines[i + j];
|
||||
|
|
|
|||
38
core/index.d.ts
vendored
38
core/index.d.ts
vendored
|
|
@ -4,8 +4,8 @@ import {
|
|||
PromptTemplates,
|
||||
} from "@continuedev/config-yaml";
|
||||
import Parser from "web-tree-sitter";
|
||||
import { CodebaseIndexer } from "./indexing/CodebaseIndexer";
|
||||
import { LLMConfigurationStatuses } from "./llm/constants";
|
||||
import { GetGhTokenArgs } from "./protocol/ide";
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
|
|
@ -95,6 +95,8 @@ export interface ILLM
|
|||
get providerName(): string;
|
||||
get underlyingProviderName(): string;
|
||||
|
||||
autocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
|
||||
complete(
|
||||
prompt: string,
|
||||
signal: AbortSignal,
|
||||
|
|
@ -564,6 +566,7 @@ export interface LLMOptions {
|
|||
uniqueId?: string;
|
||||
baseAgentSystemMessage?: string;
|
||||
baseChatSystemMessage?: string;
|
||||
autocompleteOptions?: Partial<TabAutocompleteOptions>;
|
||||
contextLength?: number;
|
||||
maxStopWords?: number;
|
||||
completionOptions?: CompletionOptions;
|
||||
|
|
@ -776,10 +779,6 @@ export interface IDE {
|
|||
}
|
||||
>;
|
||||
|
||||
getLastFileSaveTimestamp?(): number;
|
||||
|
||||
updateLastFileSaveTimestamp?(): void;
|
||||
|
||||
getPinnedFiles(): Promise<string[]>;
|
||||
|
||||
getSearchResults(query: string): Promise<string>;
|
||||
|
|
@ -808,8 +807,6 @@ export interface IDE {
|
|||
|
||||
getFileStats(files: string[]): Promise<FileStatsMap>;
|
||||
|
||||
getGitHubAuthToken(args: GetGhTokenArgs): Promise<string | undefined>;
|
||||
|
||||
// Secret Storage
|
||||
readSecrets(keys: string[]): Promise<Record<string, string>>;
|
||||
|
||||
|
|
@ -976,6 +973,8 @@ export interface ToolExtras {
|
|||
toolCallId: string;
|
||||
contextItems: ContextItem[];
|
||||
}) => void;
|
||||
config: ContinueConfig;
|
||||
codeBaseIndexer?: CodebaseIndexer;
|
||||
}
|
||||
|
||||
export interface Tool {
|
||||
|
|
@ -996,6 +995,7 @@ export interface Tool {
|
|||
uri?: string;
|
||||
faviconUrl?: string;
|
||||
group: string;
|
||||
originalFunctionName?: string;
|
||||
}
|
||||
|
||||
interface ToolChoice {
|
||||
|
|
@ -1005,6 +1005,12 @@ interface ToolChoice {
|
|||
};
|
||||
}
|
||||
|
||||
export interface ConfigDependentToolParams {
|
||||
rules: RuleWithSource[];
|
||||
}
|
||||
|
||||
export type GetTool = (params: ConfigDependentToolParams) => Tool;
|
||||
|
||||
export interface BaseCompletionOptions {
|
||||
temperature?: number;
|
||||
topP?: number;
|
||||
|
|
@ -1091,6 +1097,7 @@ export interface RerankerDescription {
|
|||
params?: { [key: string]: any };
|
||||
}
|
||||
|
||||
// TODO: We should consider renaming this to AutocompleteOptions.
|
||||
export interface TabAutocompleteOptions {
|
||||
disable: boolean;
|
||||
maxPromptTokens: number;
|
||||
|
|
@ -1106,6 +1113,7 @@ export interface TabAutocompleteOptions {
|
|||
useCache: boolean;
|
||||
onlyMyCode: boolean;
|
||||
useRecentlyEdited: boolean;
|
||||
useRecentlyOpened: boolean;
|
||||
disableInFiles?: string[];
|
||||
useImports?: boolean;
|
||||
showWhateverWeHaveAtXMs?: number;
|
||||
|
|
@ -1175,6 +1183,7 @@ export interface MCPPrompt {
|
|||
// Leaving here to ideate on
|
||||
// export type ContinueConfigSource = "local-yaml" | "local-json" | "hub-assistant" | "hub"
|
||||
|
||||
// https://modelcontextprotocol.io/docs/concepts/resources#direct-resources
|
||||
export interface MCPResource {
|
||||
name: string;
|
||||
uri: string;
|
||||
|
|
@ -1182,6 +1191,14 @@ export interface MCPResource {
|
|||
mimeType?: string;
|
||||
}
|
||||
|
||||
// https://modelcontextprotocol.io/docs/concepts/resources#resource-templates
|
||||
export interface MCPResourceTemplate {
|
||||
uriTemplate: string;
|
||||
name: string;
|
||||
description?: string;
|
||||
mimeType?: string;
|
||||
}
|
||||
|
||||
export interface MCPTool {
|
||||
name: string;
|
||||
description?: string;
|
||||
|
|
@ -1198,6 +1215,7 @@ export interface MCPServerStatus extends MCPOptions {
|
|||
prompts: MCPPrompt[];
|
||||
tools: MCPTool[];
|
||||
resources: MCPResource[];
|
||||
resourceTemplates: MCPResourceTemplate[];
|
||||
}
|
||||
|
||||
export interface ContinueUIConfig {
|
||||
|
|
@ -1564,3 +1582,9 @@ export interface RuleWithSource {
|
|||
ruleFile?: string;
|
||||
alwaysApply?: boolean;
|
||||
}
|
||||
|
||||
export interface CompleteOnboardingPayload {
|
||||
mode: OnboardingModes;
|
||||
provider?: string;
|
||||
apiKey?: string;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { execSync } from "node:child_process";
|
|||
import fs from "node:fs";
|
||||
import path from "path";
|
||||
|
||||
import { ContinueServerClient } from "../continueServer/stubs/client.js";
|
||||
import { LLMError } from "../llm/index.js";
|
||||
import { testConfigHandler, testIde } from "../test/fixtures.js";
|
||||
import {
|
||||
addToTestDir,
|
||||
|
|
@ -59,16 +59,34 @@ class TestCodebaseIndexer extends CodebaseIndexer {
|
|||
}
|
||||
}
|
||||
|
||||
// Create a mock messenger type that doesn't require actual protocol imports
|
||||
type MockMessengerType = {
|
||||
send: jest.Mock;
|
||||
request: jest.Mock;
|
||||
invoke: jest.Mock;
|
||||
on: jest.Mock;
|
||||
onError: jest.Mock;
|
||||
};
|
||||
|
||||
// These are more like integration tests, whereas we should separately test
|
||||
// the individual CodebaseIndex classes
|
||||
describe("CodebaseIndexer", () => {
|
||||
const pauseToken = new PauseToken(false);
|
||||
const continueServerClient = new ContinueServerClient(undefined, undefined);
|
||||
|
||||
// Replace mockProgressReporter with mockMessenger
|
||||
const mockMessenger: MockMessengerType = {
|
||||
send: jest.fn(),
|
||||
request: jest.fn(async () => {}),
|
||||
invoke: jest.fn(),
|
||||
on: jest.fn(),
|
||||
onError: jest.fn(),
|
||||
};
|
||||
|
||||
const codebaseIndexer = new TestCodebaseIndexer(
|
||||
testConfigHandler,
|
||||
testIde,
|
||||
pauseToken,
|
||||
continueServerClient,
|
||||
mockMessenger as any,
|
||||
false,
|
||||
);
|
||||
const testIndex = new TestCodebaseIndex();
|
||||
|
||||
|
|
@ -89,6 +107,7 @@ describe("CodebaseIndexer", () => {
|
|||
|
||||
afterEach(() => {
|
||||
walkDirCache.invalidate();
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
async function refreshIndex() {
|
||||
|
|
@ -241,4 +260,155 @@ describe("CodebaseIndexer", () => {
|
|||
execSync(`cd ${TEST_DIR_PATH} && git checkout main`);
|
||||
await expectPlan(0, 0, 0, 0);
|
||||
});
|
||||
|
||||
// New tests for the methods added from Core.ts
|
||||
describe("New methods from Core.ts", () => {
|
||||
// Simplified tests to focus on behavior, not implementation details
|
||||
test("should call messenger with progress updates when refreshing codebase index", async () => {
|
||||
jest
|
||||
.spyOn(codebaseIndexer as any, "refreshDirs")
|
||||
.mockImplementation(async function* () {
|
||||
yield { status: "done", progress: 1, desc: "Completed" };
|
||||
});
|
||||
|
||||
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
|
||||
|
||||
expect(mockMessenger.request).toHaveBeenCalledWith(
|
||||
"indexProgress",
|
||||
expect.anything(),
|
||||
);
|
||||
expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
|
||||
providers: "all",
|
||||
});
|
||||
});
|
||||
|
||||
test("should call messenger with progress updates when refreshing specific files", async () => {
|
||||
jest
|
||||
.spyOn(codebaseIndexer as any, "refreshFiles")
|
||||
.mockImplementation(async function* () {
|
||||
yield { status: "done", progress: 1, desc: "Completed" };
|
||||
});
|
||||
|
||||
await codebaseIndexer.refreshCodebaseIndexFiles(["/test/file.ts"]);
|
||||
|
||||
expect(mockMessenger.request).toHaveBeenCalledWith(
|
||||
"indexProgress",
|
||||
expect.anything(),
|
||||
);
|
||||
expect(mockMessenger.send).toHaveBeenCalledWith("refreshSubmenuItems", {
|
||||
providers: "all",
|
||||
});
|
||||
});
|
||||
|
||||
test("should abort previous indexing when starting a new one", async () => {
|
||||
// Set up a situation where indexingCancellationController exists
|
||||
const mockAbort = jest.fn();
|
||||
const controller = { abort: mockAbort, signal: { aborted: false } };
|
||||
|
||||
// Access the private property in a type-safe way for testing
|
||||
(codebaseIndexer as any).indexingCancellationController = controller;
|
||||
|
||||
// Mock refreshDirs to return immediately
|
||||
jest
|
||||
.spyOn(codebaseIndexer as any, "refreshDirs")
|
||||
.mockImplementation(async function* () {
|
||||
yield { status: "done", progress: 1, desc: "Completed" };
|
||||
});
|
||||
|
||||
// Start indexing - this should call abort on the existing controller
|
||||
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
|
||||
|
||||
// Verify abort was called
|
||||
expect(mockAbort).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
test("should handle errors properly during indexing", async () => {
|
||||
const testError = new Error("Test indexing error");
|
||||
|
||||
// Mock console.log to avoid printing errors
|
||||
const consoleLogSpy = jest
|
||||
.spyOn(console, "log")
|
||||
.mockImplementation(() => {});
|
||||
|
||||
// Mock refreshDirs to throw an error
|
||||
jest
|
||||
.spyOn(codebaseIndexer as any, "refreshDirs")
|
||||
.mockImplementation(() => {
|
||||
throw testError;
|
||||
});
|
||||
|
||||
// We don't need to mock AbortController because we're mocking the entire refreshDirs call
|
||||
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
|
||||
|
||||
// Use the first argument only for the assertion since the second argument doesn't match exactly
|
||||
expect(consoleLogSpy).toHaveBeenCalledWith(
|
||||
`Failed refreshing codebase index directories: Error: ${testError.message}`,
|
||||
);
|
||||
expect(mockMessenger.request).toHaveBeenCalledWith(
|
||||
"indexProgress",
|
||||
expect.objectContaining({
|
||||
status: "failed",
|
||||
}),
|
||||
);
|
||||
|
||||
consoleLogSpy.mockRestore();
|
||||
});
|
||||
|
||||
test("should handle LLMError specially during indexing", async () => {
|
||||
// Create a mock LLM
|
||||
const mockLlm: any = {
|
||||
providerName: "test-provider",
|
||||
model: "test-model",
|
||||
};
|
||||
|
||||
// Create a real LLMError
|
||||
const llmError = new LLMError("Test LLM error", mockLlm);
|
||||
|
||||
// Mock console.log to avoid printing errors
|
||||
jest.spyOn(console, "log").mockImplementation(() => {});
|
||||
|
||||
// Mock refreshDirs to throw an LLMError
|
||||
jest
|
||||
.spyOn(codebaseIndexer as any, "refreshDirs")
|
||||
.mockImplementation(() => {
|
||||
throw llmError;
|
||||
});
|
||||
|
||||
// We don't need to mock AbortController because we're mocking the entire refreshDirs call
|
||||
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
|
||||
|
||||
expect(mockMessenger.request).toHaveBeenCalledWith(
|
||||
"reportError",
|
||||
llmError,
|
||||
);
|
||||
expect(mockMessenger.request).toHaveBeenCalledWith(
|
||||
"indexProgress",
|
||||
expect.objectContaining({
|
||||
status: "failed",
|
||||
desc: "Test LLM error",
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test("should provide access to current indexing state", async () => {
|
||||
const testState = {
|
||||
progress: 0.5,
|
||||
status: "indexing" as const,
|
||||
desc: "Test state",
|
||||
};
|
||||
|
||||
// Mock refreshDirs to set a specific state
|
||||
jest
|
||||
.spyOn(codebaseIndexer as any, "refreshDirs")
|
||||
.mockImplementation(async function* () {
|
||||
yield testState;
|
||||
});
|
||||
|
||||
// We don't need to mock AbortController because we're mocking the entire refreshDirs call
|
||||
await codebaseIndexer.refreshCodebaseIndex([TEST_DIR]);
|
||||
|
||||
// Check that the state was updated
|
||||
expect(codebaseIndexer.currentIndexingState).toEqual(testState);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,12 +1,15 @@
|
|||
import * as fs from "fs/promises";
|
||||
|
||||
import { ConfigHandler } from "../config/ConfigHandler.js";
|
||||
import { IContinueServerClient } from "../continueServer/interface.js";
|
||||
import { IDE, IndexingProgressUpdate, IndexTag } from "../index.js";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "../protocol";
|
||||
import type { IMessenger } from "../protocol/messenger";
|
||||
import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceInfo.js";
|
||||
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
|
||||
import { Telemetry } from "../util/posthog.js";
|
||||
import { findUriInDirs, getUriPathBasename } from "../util/uri.js";
|
||||
|
||||
import { ContinueServerClient } from "../continueServer/stubs/client";
|
||||
import { LLMError } from "../llm/index.js";
|
||||
import { getRootCause } from "../util/errors.js";
|
||||
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
|
||||
|
|
@ -41,6 +44,9 @@ export class CodebaseIndexer {
|
|||
* - To make as few requests as possible to the embeddings providers
|
||||
*/
|
||||
filesPerBatch = 500;
|
||||
private indexingCancellationController: AbortController | undefined;
|
||||
private codebaseIndexingState: IndexingProgressUpdate;
|
||||
private readonly pauseToken: PauseToken;
|
||||
|
||||
// Note that we exclude certain Sqlite errors that we do not want to clear the indexes on,
|
||||
// e.g. a `SQLITE_BUSY` error.
|
||||
|
|
@ -56,9 +62,32 @@ export class CodebaseIndexer {
|
|||
constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
protected readonly ide: IDE,
|
||||
private readonly pauseToken: PauseToken,
|
||||
private readonly continueServerClient: IContinueServerClient,
|
||||
) {}
|
||||
private readonly messenger?: IMessenger<ToCoreProtocol, FromCoreProtocol>,
|
||||
initialPaused: boolean = false,
|
||||
) {
|
||||
this.codebaseIndexingState = {
|
||||
status: "loading",
|
||||
desc: "loading",
|
||||
progress: 0,
|
||||
};
|
||||
|
||||
// Initialize pause token
|
||||
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;
|
||||
}
|
||||
|
||||
async clearIndexes() {
|
||||
const sqliteFilepath = getIndexSqlitePath();
|
||||
|
|
@ -88,10 +117,22 @@ export class CodebaseIndexer {
|
|||
return [];
|
||||
}
|
||||
|
||||
const ideSettings = await this.ide.getIdeSettings();
|
||||
if (!ideSettings) {
|
||||
return [];
|
||||
}
|
||||
const continueServerClient = new ContinueServerClient(
|
||||
ideSettings.remoteConfigServerUrl,
|
||||
ideSettings.userToken,
|
||||
);
|
||||
if (!continueServerClient) {
|
||||
return [];
|
||||
}
|
||||
|
||||
const indexes: CodebaseIndex[] = [
|
||||
new ChunkCodebaseIndex(
|
||||
this.ide.readFile.bind(this.ide),
|
||||
this.continueServerClient,
|
||||
continueServerClient,
|
||||
embeddingsModel.maxEmbeddingChunkSize,
|
||||
), // Chunking must come first
|
||||
];
|
||||
|
|
@ -504,4 +545,111 @@ export class CodebaseIndexer {
|
|||
completedIndexCount += 1;
|
||||
}
|
||||
}
|
||||
|
||||
// New methods using messenger directly
|
||||
|
||||
private updateProgress(update: IndexingProgressUpdate) {
|
||||
this.codebaseIndexingState = update;
|
||||
if (this.messenger) {
|
||||
void this.messenger.request("indexProgress", update);
|
||||
}
|
||||
}
|
||||
|
||||
private async sendIndexingErrorTelemetry(update: IndexingProgressUpdate) {
|
||||
console.debug(
|
||||
"Indexing failed with error: ",
|
||||
update.desc,
|
||||
update.debugInfo,
|
||||
);
|
||||
void Telemetry.capture(
|
||||
"indexing_error",
|
||||
{
|
||||
error: update.desc,
|
||||
stack: update.debugInfo,
|
||||
},
|
||||
false,
|
||||
);
|
||||
}
|
||||
|
||||
public async refreshCodebaseIndex(paths: string[]) {
|
||||
if (this.indexingCancellationController) {
|
||||
this.indexingCancellationController.abort();
|
||||
}
|
||||
this.indexingCancellationController = new AbortController();
|
||||
try {
|
||||
for await (const update of this.refreshDirs(
|
||||
paths,
|
||||
this.indexingCancellationController.signal,
|
||||
)) {
|
||||
this.updateProgress(update);
|
||||
|
||||
if (update.status === "failed") {
|
||||
await this.sendIndexingErrorTelemetry(update);
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.log(`Failed refreshing codebase index directories: ${e}`);
|
||||
await this.handleIndexingError(e);
|
||||
}
|
||||
|
||||
// Directly refresh submenu items
|
||||
if (this.messenger) {
|
||||
this.messenger.send("refreshSubmenuItems", {
|
||||
providers: "all",
|
||||
});
|
||||
}
|
||||
this.indexingCancellationController = undefined;
|
||||
}
|
||||
|
||||
public async refreshCodebaseIndexFiles(files: string[]) {
|
||||
// Can be cancelled by codebase index but not vice versa
|
||||
if (
|
||||
this.indexingCancellationController &&
|
||||
!this.indexingCancellationController.signal.aborted
|
||||
) {
|
||||
return;
|
||||
}
|
||||
this.indexingCancellationController = new AbortController();
|
||||
try {
|
||||
for await (const update of this.refreshFiles(files)) {
|
||||
this.updateProgress(update);
|
||||
|
||||
if (update.status === "failed") {
|
||||
await this.sendIndexingErrorTelemetry(update);
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.log(`Failed refreshing codebase index files: ${e}`);
|
||||
await this.handleIndexingError(e);
|
||||
}
|
||||
|
||||
// Directly refresh submenu items
|
||||
if (this.messenger) {
|
||||
this.messenger.send("refreshSubmenuItems", {
|
||||
providers: "all",
|
||||
});
|
||||
}
|
||||
this.indexingCancellationController = undefined;
|
||||
}
|
||||
|
||||
public async handleIndexingError(e: any) {
|
||||
if (e instanceof LLMError && this.messenger) {
|
||||
// Need to report this specific error to the IDE for special handling
|
||||
void this.messenger.request("reportError", e);
|
||||
}
|
||||
|
||||
// broadcast indexing error
|
||||
const updateToSend: IndexingProgressUpdate = {
|
||||
progress: 0,
|
||||
status: "failed",
|
||||
desc: e.message,
|
||||
};
|
||||
|
||||
this.updateProgress(updateToSend);
|
||||
void this.sendIndexingErrorTelemetry(updateToSend);
|
||||
}
|
||||
|
||||
public get currentIndexingState(): IndexingProgressUpdate {
|
||||
return this.codebaseIndexingState;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -97,8 +97,8 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
contents TEXT NOT NULL
|
||||
)`);
|
||||
|
||||
await new Promise((resolve) =>
|
||||
migrate(
|
||||
await new Promise((resolve) => {
|
||||
void migrate(
|
||||
"lancedb_sqlite_artifact_id_column",
|
||||
async () => {
|
||||
try {
|
||||
|
|
@ -118,8 +118,8 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
}
|
||||
},
|
||||
() => resolve(undefined),
|
||||
),
|
||||
);
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
private async computeRows(items: PathAndCacheKey[]): Promise<LanceDbRow[]> {
|
||||
|
|
@ -294,17 +294,27 @@ export class LanceDbIndex implements CodebaseIndex {
|
|||
);
|
||||
const cachedItems = await stmt.all();
|
||||
|
||||
const lanceRows: LanceDbRow[] = cachedItems.map(
|
||||
({ uuid, vector, startLine, endLine, contents }) => ({
|
||||
path,
|
||||
uuid,
|
||||
startLine,
|
||||
endLine,
|
||||
contents,
|
||||
cachekey: cacheKey,
|
||||
vector: JSON.parse(vector),
|
||||
}),
|
||||
);
|
||||
const lanceRows: LanceDbRow[] = [];
|
||||
for (const item of cachedItems) {
|
||||
try {
|
||||
const vector = JSON.parse(item.vector);
|
||||
const { uuid, startLine, endLine, contents } = item;
|
||||
|
||||
cachedItems.push({
|
||||
path,
|
||||
uuid,
|
||||
startLine,
|
||||
endLine,
|
||||
contents,
|
||||
cachekey: cacheKey,
|
||||
vector,
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
`LanceDBIndex, skipping ${item.path} due to invalid vector JSON:\n${item.vector}\n\nError: ${err}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (lanceRows.length > 0) {
|
||||
if (needToCreateLanceTable) {
|
||||
|
|
|
|||
|
|
@ -14,12 +14,14 @@ export async function* basicChunker(
|
|||
let startLine = 0;
|
||||
let currLine = 0;
|
||||
|
||||
const lineTokens = await Promise.all(contents.split("\n").map(async l => {
|
||||
return {
|
||||
line: l,
|
||||
tokenCount: await countTokensAsync(l),
|
||||
};
|
||||
}));
|
||||
const lineTokens = await Promise.all(
|
||||
contents.split("\n").map(async (l) => {
|
||||
return {
|
||||
line: l,
|
||||
tokenCount: await countTokensAsync(l),
|
||||
};
|
||||
}),
|
||||
);
|
||||
|
||||
for (const lt of lineTokens) {
|
||||
if (chunkTokens + lt.tokenCount > maxChunkSize - 5) {
|
||||
|
|
|
|||
|
|
@ -50,21 +50,23 @@ export async function* chunkDocument({
|
|||
maxChunkSize,
|
||||
)) {
|
||||
chunkPromises.push(
|
||||
new Promise(async (resolve) => {
|
||||
if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) {
|
||||
// console.debug(
|
||||
// `Chunk with more than ${maxChunkSize} tokens constructed: `,
|
||||
// filepath,
|
||||
// countTokens(chunkWithoutId.content),
|
||||
// );
|
||||
return resolve(undefined);
|
||||
}
|
||||
resolve({
|
||||
...chunkWithoutId,
|
||||
digest,
|
||||
index,
|
||||
filepath,
|
||||
});
|
||||
new Promise((resolve) => {
|
||||
void (async () => {
|
||||
if ((await countTokensAsync(chunkWithoutId.content)) > maxChunkSize) {
|
||||
// console.debug(
|
||||
// `Chunk with more than ${maxChunkSize} tokens constructed: `,
|
||||
// filepath,
|
||||
// countTokens(chunkWithoutId.content),
|
||||
// );
|
||||
return resolve(undefined);
|
||||
}
|
||||
resolve({
|
||||
...chunkWithoutId,
|
||||
digest,
|
||||
index,
|
||||
filepath,
|
||||
});
|
||||
})();
|
||||
}),
|
||||
);
|
||||
index++;
|
||||
|
|
|
|||
|
|
@ -30,7 +30,7 @@ describe.skip("codeChunker", () => {
|
|||
test("should capture small class and function from large python file", async () => {
|
||||
const extraLine = "# This is a comment";
|
||||
const myClass = "class MyClass:\n def __init__(self):\n pass";
|
||||
const myFunction = "def my_function():\n return \"Hello, World!\"";
|
||||
const myFunction = 'def my_function():\n return "Hello, World!"';
|
||||
|
||||
const file =
|
||||
Array(100).fill(extraLine).join("\n") +
|
||||
|
|
@ -67,7 +67,7 @@ describe.skip("codeChunker", () => {
|
|||
chunks[0].startsWith("class MyClass:\n def method1():\n ..."),
|
||||
).toBe(true);
|
||||
// The extra spaces seem to be a bug with tree-sitter-python
|
||||
expect(chunks).toContain("def method1():\n return \"Hello, 1!\"");
|
||||
expect(chunks).toContain("def method20():\n return \"Hello, 20!\"");
|
||||
expect(chunks).toContain('def method1():\n return "Hello, 1!"');
|
||||
expect(chunks).toContain('def method20():\n return "Hello, 20!"');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -101,23 +101,7 @@
|
|||
// // const originalEmbeddingsProvider =
|
||||
// // await docsService.getEmbeddingsProvider();
|
||||
|
||||
// // // Change embeddings provider
|
||||
// // editConfigJson((config) => ({
|
||||
// // ...config,
|
||||
// // embeddingsProvider: {
|
||||
// // provider: FreeTrial.providerName,
|
||||
// // },
|
||||
// // }));
|
||||
|
||||
// // await getReloadedConfig();
|
||||
|
||||
// // const { provider, isPreindexed} = await docsService.getEmbeddingsProvider();
|
||||
|
||||
// // // Verify reindexing
|
||||
// // const [originalVector] = await originalEmbeddingsProvider.embed(["test"]);
|
||||
// // const [newMockVector] = await provider.embed(["test"]);
|
||||
|
||||
// // expect(originalVector).not.toEqual(newMockVector);
|
||||
// // TODO removed this test when free trial provider was removed
|
||||
// // });
|
||||
|
||||
// test("Handles pulling down and adding pre-indexed docs", async () => {
|
||||
|
|
|
|||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue