Merge branch 'main' into dallin/nested-md-code
This commit is contained in:
commit
9bf97e4195
269 changed files with 9497 additions and 1673 deletions
4
.changes/unreleased/Added-20241113-165958.yaml
Normal file
4
.changes/unreleased/Added-20241113-165958.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: .continuerules file to set system prompt
|
||||
time: 2024-11-13T16:59:58.544875-08:00
|
||||
4
.changes/unreleased/Added-20241113-170006.yaml
Normal file
4
.changes/unreleased/Added-20241113-170006.yaml
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
project: extensions/vscode
|
||||
kind: Added
|
||||
body: .prompt files v2
|
||||
time: 2024-11-13T17:00:06.855468-08:00
|
||||
2
.github/workflows/auto-assign.yaml
vendored
2
.github/workflows/auto-assign.yaml
vendored
|
|
@ -14,7 +14,7 @@ jobs:
|
|||
uses: pozil/auto-assign-issue@v2
|
||||
with:
|
||||
repo-token: ${{ secrets.CI_GITHUB_TOKEN }}
|
||||
assignees: sestinj,Patrick-Erichsen
|
||||
assignees: sestinj,Patrick-Erichsen,tomasz-stefaniak,RomneyDa
|
||||
numOfAssignee: 1
|
||||
- name: "Add default labels"
|
||||
uses: actions-ecosystem/action-add-labels@v1
|
||||
|
|
|
|||
22
.github/workflows/main.yaml
vendored
22
.github/workflows/main.yaml
vendored
|
|
@ -213,8 +213,8 @@ jobs:
|
|||
git config --local user.email "action@github.com"
|
||||
git config --local user.name "GitHub Action"
|
||||
|
||||
- name: Pull latest changes
|
||||
run: git pull origin main
|
||||
- name: Pull latest changes from release
|
||||
run: git fetch origin ${{ github.ref }} && git checkout ${{ github.ref }}
|
||||
|
||||
# 1. Download the artifacts
|
||||
- uses: actions/download-artifact@v4
|
||||
|
|
@ -237,21 +237,3 @@ jobs:
|
|||
run: |
|
||||
cd extensions/vscode
|
||||
npx ovsx publish -p ${{ secrets.VSX_REGISTRY_TOKEN }} --packagePath ../../vsix-artifacts/*.vsix
|
||||
|
||||
# 4. Update the package.json version and push changes
|
||||
# - name: Update version in package.json
|
||||
# run: |
|
||||
# cd extensions/vscode
|
||||
# npm version patch
|
||||
|
||||
# - name: Commit changes
|
||||
# run: |
|
||||
# git config --local user.email "action@github.com"
|
||||
# git config --local user.name "GitHub Action"
|
||||
# git commit -am "💚 Update package.json version [skip ci]"
|
||||
|
||||
# - name: Push changes
|
||||
# uses: ad-m/github-push-action@master
|
||||
# with:
|
||||
# github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
# branch: ${{ github.ref }}
|
||||
|
|
|
|||
1
.instructions
Normal file
1
.instructions
Normal file
|
|
@ -0,0 +1 @@
|
|||
Give concise responses.
|
||||
33
binary/package-lock.json
generated
33
binary/package-lock.json
generated
|
|
@ -74,7 +74,7 @@
|
|||
"jsdom": "^24.0.0",
|
||||
"launchdarkly-node-client-sdk": "^3.2.0",
|
||||
"llm-code-highlighter": "^0.0.14",
|
||||
"lru-cache": "^10.2.2",
|
||||
"lru-cache": "^11.0.2",
|
||||
"mac-ca": "^3.1.0",
|
||||
"node-fetch": "^3.3.2",
|
||||
"node-html-markdown": "^1.3.0",
|
||||
|
|
@ -99,6 +99,7 @@
|
|||
"vectordb": "^0.4.20",
|
||||
"web-tree-sitter": "^0.21.0",
|
||||
"win-ca": "^3.5.1",
|
||||
"wink-nlp-utils": "^2.1.0",
|
||||
"workerpool": "^9.1.3",
|
||||
"yaml": "^2.4.2",
|
||||
"zod": "^3.23.8"
|
||||
|
|
@ -135,12 +136,12 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@75lb/deep-merge": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.1.tgz",
|
||||
"integrity": "sha512-xvgv6pkMGBA6GwdyJbNAnDmfAIR/DfWhrj9jgWh3TY7gRm3KO46x/GPjRg6wJ0nOepwqrNxFfojebh0Df4h4Tw==",
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz",
|
||||
"integrity": "sha512-08K9ou5VNbheZFxM5tDWoqjA3ImC50DiuuJ2tj1yEPRfkp8lLLg6XAaJ4On+a0yAXor/8ay5gHnAIshRM44Kpw==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"lodash.assignwith": "^4.2.0",
|
||||
"lodash": "^4.17.21",
|
||||
"typical": "^7.1.1"
|
||||
},
|
||||
"engines": {
|
||||
|
|
@ -2749,12 +2750,12 @@
|
|||
}
|
||||
},
|
||||
"node_modules/braces": {
|
||||
"version": "3.0.2",
|
||||
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz",
|
||||
"integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==",
|
||||
"version": "3.0.3",
|
||||
"resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz",
|
||||
"integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"fill-range": "^7.0.1"
|
||||
"fill-range": "^7.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8"
|
||||
|
|
@ -3545,9 +3546,9 @@
|
|||
"optional": true
|
||||
},
|
||||
"node_modules/fill-range": {
|
||||
"version": "7.0.1",
|
||||
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz",
|
||||
"integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==",
|
||||
"version": "7.1.1",
|
||||
"resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz",
|
||||
"integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"to-regex-range": "^5.0.1"
|
||||
|
|
@ -5037,10 +5038,10 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/lodash.assignwith": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.assignwith/-/lodash.assignwith-4.2.0.tgz",
|
||||
"integrity": "sha512-ZznplvbvtjK2gMvnQ1BR/zqPFZmS6jbK4p+6Up4xcRYA7yMIwxHCfbTcrYxXKzzqLsQ05eJPVznEW3tuwV7k1g==",
|
||||
"node_modules/lodash": {
|
||||
"version": "4.17.21",
|
||||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
|
||||
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/lodash.camelcase": {
|
||||
|
|
|
|||
|
|
@ -261,13 +261,10 @@ export class CompletionProvider {
|
|||
|
||||
//////////
|
||||
|
||||
// Do some stuff later so as not to block return. Latency matters
|
||||
const completionToCache = outcome.completion;
|
||||
setTimeout(async () => {
|
||||
if (!outcome.cacheHit) {
|
||||
(await this.autocompleteCache).put(outcome.prefix, completionToCache);
|
||||
}
|
||||
}, 100);
|
||||
// Save to cache
|
||||
if (!outcome.cacheHit) {
|
||||
(await this.autocompleteCache).put(outcome.prefix, outcome.completion);
|
||||
}
|
||||
|
||||
// When using the JetBrains extension, Mark as displayed
|
||||
const ideType = (await this.ide.getIdeInfo()).ideType;
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ Continue now provides support for tab autocomplete in [VS Code](https://marketpl
|
|||
We recommend setting up tab-autocomplete with a local Ollama instance. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model:
|
||||
|
||||
```bash
|
||||
ollama run starcoder:3b
|
||||
ollama run qwen2.5-coder:1.5b
|
||||
```
|
||||
|
||||
Once it has been downloaded, you should begin to see completions in VS Code.
|
||||
|
|
@ -17,9 +17,9 @@ Once it has been downloaded, you should begin to see completions in VS Code.
|
|||
You can also set up tab-autocomplete with a local LM Studio instance by following these steps:
|
||||
|
||||
1. Download the latest version of LM Studio from [here](https://lmstudio.ai/)
|
||||
2. Download a model (e.g. search for `second-state/StarCoder2-3B-GGUF` and choose one of the options there)
|
||||
2. Download a model (e.g. search for `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF` and choose one of the options there)
|
||||
3. Go to the server section (button is on the left), select your model from the dropdown at the top, and click "Start Server"
|
||||
4. Go to the "My Models" section (button is on the left), find your selected model, and copy the name the path (example: `second-state/StarCoder2-3B-GGUF/starcoder2-3b-Q8_0.gguf`); this will be used as the "model" attribute in Continue
|
||||
4. Go to the "My Models" section (button is on the left), find your selected model, and copy the name the path (example: `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/qwen2.5-coder-1.5b-instruct-q4_k_m.gguf`); this will be used as the "model" attribute in Continue
|
||||
5. Go to Continue and modify the configurations for a [custom model](#setting-up-a-custom-model)
|
||||
6. Set the "provider" to `lmstudio` and the "model" to the path copied earlier
|
||||
|
||||
|
|
@ -28,8 +28,8 @@ Example:
|
|||
```json title="config.json"
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "Starcoder2 3b",
|
||||
"model": "second-state/StarCoder2-3B-GGUF/starcoder2-3b-Q8_0.gguf",
|
||||
"title": "Qwen2.5-Coder 1.5b",
|
||||
"model": "Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF",
|
||||
"provider": "lmstudio",
|
||||
},
|
||||
...
|
||||
|
|
@ -69,11 +69,9 @@ If you aren't yet familiar with the available options, you can learn more in our
|
|||
|
||||
### What model should I use?
|
||||
|
||||
If you are running the model locally, we recommend `starcoder:3b`.
|
||||
If you are running the model locally, we recommend `qwen2.5-coder:1.5b`.
|
||||
|
||||
If you find it to be too slow, you should try `deepseek-coder:1.3b-base`.
|
||||
|
||||
If you have a bit more compute, or are running a model in the cloud, you can upgrade to `deepseek-coder:6.7b-base`.
|
||||
If you have a bit more compute, or are running a model in the cloud, you can upgrade to `qwen2.5-coder:7b`.
|
||||
|
||||
Regardless of what you are willing to spend, we do not recommend using GPT or Claude for autocomplete. Learn why [below](#i-want-better-completions-should-i-use-gpt-4).
|
||||
|
||||
|
|
@ -83,7 +81,7 @@ The following can be configured in `config.json`:
|
|||
|
||||
### `tabAutocompleteModel`
|
||||
|
||||
This is just another object like the ones in the `"models"` array of `config.json`. You can choose and configure any model you would like, but we strongly suggest using a small model made for tab-autocomplete, such as `deepseek-1b`, `starcoder-1b`, or `starcoder-3b`.
|
||||
This is just another object like the ones in the `"models"` array of `config.json`. You can choose and configure any model you would like, but we strongly suggest using a small model made for tab-autocomplete, such as `deepseek-1b`, `qwen2.5-coder:1.5b`, or `starcoder-3b`.
|
||||
|
||||
### `tabAutocompleteOptions`
|
||||
|
||||
|
|
@ -105,7 +103,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
|
|||
"tabAutocompleteModel": {
|
||||
"title": "Tab Autocomplete Model",
|
||||
"provider": "ollama",
|
||||
"model": "starcoder:3b",
|
||||
"model": "qwen2.5-coder:1.5b",
|
||||
"apiBase": "https://<my endpoint>"
|
||||
},
|
||||
"tabAutocompleteOptions": {
|
||||
|
|
@ -128,7 +126,7 @@ Follow these steps to ensure that everything is set up correctly:
|
|||
|
||||
1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar).
|
||||
2. Make sure you have downloaded Ollama.
|
||||
3. Run `ollama run starcoder:3b` to verify that the model is downloaded.
|
||||
3. Run `ollama run qwen2.5-coder:1.5b` to verify that the model is downloaded.
|
||||
4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere.
|
||||
5. Make sure that you aren't also using another Ollama model for chat. This will cause Ollama to constantly load and unload the models from memory, resulting in slow responses (or none at all) for both.
|
||||
6. Check the output of the logs to find any potential errors (cmd/ctrl+shift+p -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains).
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ import { IDE } from "../..";
|
|||
import { RangeInFileWithContents } from "../../commands/util";
|
||||
import { PrecalculatedLruCache } from "../../util/LruCache";
|
||||
import {
|
||||
TSQueryType,
|
||||
getFullLanguageName,
|
||||
getParserForFile,
|
||||
getQueryForFile,
|
||||
} from "../../util/treeSitter";
|
||||
|
|
@ -47,7 +47,11 @@ export class ImportDefinitionsService {
|
|||
},
|
||||
],
|
||||
});
|
||||
const query = await getQueryForFile(filepath, TSQueryType.Imports);
|
||||
const language = getFullLanguageName(filepath);
|
||||
const query = await getQueryForFile(
|
||||
filepath,
|
||||
`import-queries/${language}.scm`,
|
||||
);
|
||||
if (!query) {
|
||||
return {
|
||||
imports: {},
|
||||
|
|
|
|||
|
|
@ -4,11 +4,31 @@ import { LRUCache } from "lru-cache";
|
|||
import Parser from "web-tree-sitter";
|
||||
|
||||
import { IDE } from "../../..";
|
||||
import { getQueryForFile } from "../../../util/treeSitter";
|
||||
import {
|
||||
getFullLanguageName,
|
||||
getQueryForFile,
|
||||
IGNORE_PATH_PATTERNS,
|
||||
LanguageName,
|
||||
} from "../../../util/treeSitter";
|
||||
import { AstPath } from "../../util/ast";
|
||||
import { ImportDefinitionsService } from "../ImportDefinitionsService";
|
||||
import { AutocompleteSnippet } from "../ranking";
|
||||
|
||||
function getSyntaxTreeString(
|
||||
node: Parser.SyntaxNode,
|
||||
indent: string = "",
|
||||
): string {
|
||||
let result = "";
|
||||
const nodeInfo = `${node.type} [${node.startPosition.row}:${node.startPosition.column} - ${node.endPosition.row}:${node.endPosition.column}]`;
|
||||
result += `${indent}${nodeInfo}\n`;
|
||||
|
||||
for (const child of node.children) {
|
||||
result += getSyntaxTreeString(child, indent + " ");
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
export class RootPathContextService {
|
||||
private cache = new LRUCache<string, AutocompleteSnippet[]>({
|
||||
max: 100,
|
||||
|
|
@ -24,10 +44,15 @@ export class RootPathContextService {
|
|||
}
|
||||
|
||||
private static TYPES_TO_USE = new Set([
|
||||
"arrow_function",
|
||||
"generator_function_declaration",
|
||||
"program",
|
||||
"function_declaration",
|
||||
"function_definition",
|
||||
"method_definition",
|
||||
"method_declaration",
|
||||
"class_declaration",
|
||||
"class_definition",
|
||||
]);
|
||||
|
||||
/**
|
||||
|
|
@ -49,6 +74,7 @@ export class RootPathContextService {
|
|||
node: Parser.SyntaxNode,
|
||||
): Promise<AutocompleteSnippet[]> {
|
||||
const snippets: AutocompleteSnippet[] = [];
|
||||
const language = getFullLanguageName(filepath);
|
||||
|
||||
let query: Parser.Query | undefined;
|
||||
switch (node.type) {
|
||||
|
|
@ -56,9 +82,13 @@ export class RootPathContextService {
|
|||
this.importDefinitionsService.get(filepath);
|
||||
break;
|
||||
default:
|
||||
// const type = node.type;
|
||||
// console.log(getSyntaxTreeString(node));
|
||||
// debugger;
|
||||
|
||||
query = await getQueryForFile(
|
||||
filepath,
|
||||
`root-path-context-queries/${node.type}`,
|
||||
`root-path-context-queries/${language}/${node.type}.scm`,
|
||||
);
|
||||
break;
|
||||
}
|
||||
|
|
@ -67,15 +97,24 @@ export class RootPathContextService {
|
|||
return snippets;
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
query.matches(node).map(async (match) => {
|
||||
for (const item of match.captures) {
|
||||
const queries = query.matches(node).map(async (match) => {
|
||||
for (const item of match.captures) {
|
||||
try {
|
||||
const endPosition = item.node.endPosition;
|
||||
const newSnippets = await this.getSnippets(filepath, endPosition);
|
||||
const newSnippets = await this.getSnippets(
|
||||
filepath,
|
||||
endPosition,
|
||||
language,
|
||||
);
|
||||
snippets.push(...newSnippets);
|
||||
} catch (e) {
|
||||
debugger;
|
||||
throw e;
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
await Promise.all(queries);
|
||||
|
||||
return snippets;
|
||||
}
|
||||
|
|
@ -83,6 +122,7 @@ export class RootPathContextService {
|
|||
private async getSnippets(
|
||||
filepath: string,
|
||||
endPosition: Parser.Point,
|
||||
language: LanguageName,
|
||||
): Promise<AutocompleteSnippet[]> {
|
||||
const definitions = await this.ide.gotoDefinition({
|
||||
filepath,
|
||||
|
|
@ -92,11 +132,20 @@ export class RootPathContextService {
|
|||
},
|
||||
});
|
||||
const newSnippets = await Promise.all(
|
||||
definitions.map(async (def) => ({
|
||||
...def,
|
||||
contents: await this.ide.readRangeInFile(def.filepath, def.range),
|
||||
})),
|
||||
definitions
|
||||
.filter((definition) => {
|
||||
const isIgnoredPath = IGNORE_PATH_PATTERNS[language]?.some(
|
||||
(pattern) => pattern.test(definition.filepath),
|
||||
);
|
||||
|
||||
return !isIgnoredPath;
|
||||
})
|
||||
.map(async (def) => ({
|
||||
...def,
|
||||
contents: await this.ide.readRangeInFile(def.filepath, def.range),
|
||||
})),
|
||||
);
|
||||
|
||||
return newSnippets;
|
||||
}
|
||||
|
||||
|
|
@ -112,6 +161,8 @@ export class RootPathContextService {
|
|||
RootPathContextService.TYPES_TO_USE.has(node.type),
|
||||
)) {
|
||||
const key = RootPathContextService.keyFromNode(parentKey, astNode);
|
||||
// const type = astNode.type;
|
||||
// debugger;
|
||||
|
||||
const foundInCache = this.cache.get(key);
|
||||
const newSnippets =
|
||||
|
|
|
|||
|
|
@ -1,41 +1,55 @@
|
|||
import { PYTHON_TEST_CASES, TYPESCRIPT_TEST_CASES } from "./testCases";
|
||||
import { testRootPathContext } from "./testUtils";
|
||||
|
||||
const TEST_CASES = [
|
||||
...PYTHON_TEST_CASES,
|
||||
...TYPESCRIPT_TEST_CASES,
|
||||
{
|
||||
description: "function",
|
||||
fileName: "file1.ts",
|
||||
range: {
|
||||
start: { line: 10, character: 2 },
|
||||
end: { line: 10, character: 24 },
|
||||
},
|
||||
positions: [
|
||||
{ row: 9, column: 34 }, // Person
|
||||
{ row: 9, column: 44 }, // Address
|
||||
nodeType: "function_definition",
|
||||
fileName: "file1.php",
|
||||
language: "PHP",
|
||||
cursorPosition: { line: 12, character: 32 },
|
||||
definitionPositions: [
|
||||
{ row: 10, column: 26 }, // Person
|
||||
{ row: 10, column: 44 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
description: "class method",
|
||||
fileName: "file1.ts",
|
||||
range: {
|
||||
start: { line: 22, character: 4 },
|
||||
end: { line: 22, character: 30 },
|
||||
},
|
||||
positions: [
|
||||
{ row: 13, column: 29 }, // BaseClass
|
||||
{ row: 13, column: 55 }, // FirstInterface
|
||||
{ row: 13, column: 72 }, // SecondInterface
|
||||
{ row: 21, column: 33 }, // Person
|
||||
{ row: 21, column: 43 }, // Address
|
||||
nodeType: "method_declaration",
|
||||
fileName: "file1.php",
|
||||
language: "PHP",
|
||||
cursorPosition: { line: 26, character: 35 },
|
||||
definitionPositions: [
|
||||
{ row: 15, column: 29 }, // BaseClass
|
||||
{ row: 15, column: 55 }, // FirstInterface
|
||||
{ row: 15, column: 72 }, // SecondInterface
|
||||
{ row: 25, column: 43 }, // Person
|
||||
{ row: 25, column: 61 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_declaration",
|
||||
fileName: "file1.go",
|
||||
language: "Go",
|
||||
cursorPosition: { line: 7, character: 21 },
|
||||
definitionPositions: [
|
||||
{ row: 6, column: 33 }, // models.User
|
||||
{ row: 6, column: 50 }, // models.Address
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
describe("RootPathContextService", () => {
|
||||
describe("TypeScript should return expected snippets when editing inside a:", () => {
|
||||
describe("should look for correct type definitions", () => {
|
||||
test.each(TEST_CASES)(
|
||||
"should look for correct type definitions when editing inside a $description",
|
||||
async ({ fileName, range, positions }) => {
|
||||
await testRootPathContext("typescript", fileName, range, positions);
|
||||
"$language: $nodeType",
|
||||
async ({ fileName, cursorPosition, definitionPositions }) => {
|
||||
await testRootPathContext(
|
||||
"files",
|
||||
fileName,
|
||||
cursorPosition,
|
||||
definitionPositions,
|
||||
);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -0,0 +1,26 @@
|
|||
# File: base_module.py
|
||||
|
||||
class BaseClass:
|
||||
def __init__(self):
|
||||
print("BaseClass initialized")
|
||||
|
||||
class Collection:
|
||||
def __init__(self):
|
||||
print("Collection initialized")
|
||||
|
||||
class Address:
|
||||
def __init__(self, street: str, city: str, zip_code: str):
|
||||
self.street = street
|
||||
self.city = city
|
||||
self.zip_code = zip_code
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.street}, {self.city}, {self.zip_code}"
|
||||
|
||||
class Person:
|
||||
def __init__(self, name: str, address: Address):
|
||||
self.name = name
|
||||
self.address = address
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.name} lives at {self.address}"
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"core/autocomplete/context/root-path-context/test/files/models"
|
||||
)
|
||||
|
||||
func getAddress(user *models.User) *models.Address {
|
||||
return user.Address
|
||||
}
|
||||
|
|
@ -0,0 +1,32 @@
|
|||
<?php
|
||||
|
||||
namespace BaseNamespace;
|
||||
|
||||
use BaseNamespace\BaseClass;
|
||||
use BaseNamespace\Interfaces\FirstInterface;
|
||||
use BaseNamespace\Interfaces\SecondInterface;
|
||||
use BaseNamespace\Person;
|
||||
use BaseNamespace\Address;
|
||||
|
||||
function getAddress(Person $person): Address
|
||||
{
|
||||
return $person->getAddress();
|
||||
}
|
||||
|
||||
class Group extends BaseClass implements FirstInterface, SecondInterface
|
||||
{
|
||||
private array $people;
|
||||
|
||||
public function __construct(array $people)
|
||||
{
|
||||
parent::__construct();
|
||||
$this->people = $people;
|
||||
}
|
||||
|
||||
public function getPersonAddress(Person $person): Address
|
||||
{
|
||||
return getAddress($person);
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
||||
|
|
@ -0,0 +1,11 @@
|
|||
class Group(BaseClass, Person):
|
||||
pass
|
||||
|
||||
class Group(metaclass=MetaGroup):
|
||||
pass
|
||||
|
||||
class Group(BaseClass[Address], Gathering[Person]):
|
||||
pass
|
||||
|
||||
class Group(List[Address], Person[str]):
|
||||
pass
|
||||
|
|
@ -0,0 +1,42 @@
|
|||
from typing import List, Union, TypeVar, Generic
|
||||
|
||||
T = TypeVar('T')
|
||||
|
||||
class Address:
|
||||
pass
|
||||
|
||||
class Person:
|
||||
pass
|
||||
|
||||
class PersonWithGeneric(Generic[T]):
|
||||
pass
|
||||
|
||||
|
||||
def get_address(person: Person) -> Address:
|
||||
pass
|
||||
|
||||
def get_group_address(people: Group[Person]) -> Group[Address]:
|
||||
pass
|
||||
|
||||
def log_person(person: Person) -> None:
|
||||
pass
|
||||
|
||||
def get_hardcoded_address() -> Address:
|
||||
pass
|
||||
|
||||
def log_person_or_address(value: Union[Person, Address]) -> Union[Person, Address]:
|
||||
pass
|
||||
|
||||
def log_person_and_address(person: Person, address: Address) -> None:
|
||||
pass
|
||||
|
||||
def get_address_generator(person: Person) -> Generator[Address, None, None]:
|
||||
yield
|
||||
|
||||
|
||||
class Group:
|
||||
def log_person_and_address(self, person: Person, address: Address) -> None:
|
||||
pass
|
||||
|
||||
async def get_person(address: Address) -> Person:
|
||||
pass
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
// @ts-nocheck
|
||||
|
||||
const getAddress = (person: Person): Address => {
|
||||
// TODO
|
||||
};
|
||||
|
||||
const logPerson = (person: Person) => {
|
||||
// TODO
|
||||
};
|
||||
|
||||
const getHardcodedAddress = (): Address => {
|
||||
// TODO
|
||||
};
|
||||
|
||||
const getAddresses = (people: Person[]): Address[] => {
|
||||
// TODO
|
||||
};
|
||||
|
||||
const logPersonWithAddres = (person: Person<Address>): Person<Address> => {
|
||||
// TODO
|
||||
};
|
||||
|
||||
const logPersonOrAddress = (person: Person | Address): Person | Address => {
|
||||
// TODO
|
||||
};
|
||||
|
||||
const logPersonAndAddress = (person: Person, address: Address) => {
|
||||
// TODO
|
||||
};
|
||||
|
|
@ -0,0 +1,35 @@
|
|||
// @ts-nocheck
|
||||
|
||||
class Group {
|
||||
getPersonAddress(person: Person): Address {
|
||||
// TODO
|
||||
}
|
||||
|
||||
getHardcodedAddress(): Address {
|
||||
// TODO
|
||||
}
|
||||
|
||||
addPerson(person: Person) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
addPeople(people: Person[]) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
getAddresses(people: Person[]): Address[] {
|
||||
// TODO
|
||||
}
|
||||
|
||||
logPersonWithAddress(person: Person<Address>): Person<Address> {
|
||||
// TODO
|
||||
}
|
||||
|
||||
logPersonOrAddress(person: Person | Address): Person | Address {
|
||||
// TODO
|
||||
}
|
||||
|
||||
logPersonAndAddress(person: Person, address: Address) {
|
||||
// TODO
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
// @ts-nocheck
|
||||
|
||||
class Group extends BaseClass {}
|
||||
|
||||
class Group implements FirstInterface {}
|
||||
|
||||
class Group extends BaseClass implements FirstInterface, SecondInterface {}
|
||||
|
||||
class Group extends BaseClass<User> implements FirstInterface<User> {}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
// @ts-nocheck
|
||||
|
||||
function getAddress(person: Person): Address {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function getFirstAddress(people: Person[]): Address {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function logPerson(person: Person) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function getHardcodedAddress(): Address {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function getAddresses(people: Person[]): Address[] {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function logPersonWithAddress(person: Person<Address>): Person<Address> {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function logPersonOrAddress(person: Person | Address): Person | Address {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function logPersonAndAddress(person: Person, address: Address) {
|
||||
// TODO
|
||||
}
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
// @ts-nocheck
|
||||
|
||||
function* getAddress(person: Person): Address {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function* getFirstAddress(people: Person[]): Address {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function* logPerson(person: Person) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function* getHardcodedAddress(): Address {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function* getAddresses(people: Person[]): Address[] {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function* logPersonWithAddress(person: Person<Address>): Person<Address> {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function* logPersonOrAddress(person: Person | Address): Person | Address {
|
||||
// TODO
|
||||
}
|
||||
|
||||
function* logPersonAndAddress(person: Person, address: Address) {
|
||||
// TODO
|
||||
}
|
||||
|
|
@ -0,0 +1,2 @@
|
|||
export * from "./python";
|
||||
export * from "./typescript";
|
||||
|
|
@ -0,0 +1,145 @@
|
|||
export const FUNCTIONS = [
|
||||
{
|
||||
nodeType: "function_definition with argument and return type",
|
||||
fileName: "python/functions.py",
|
||||
language: "Python",
|
||||
cursorPosition: { line: 15, character: 8 },
|
||||
definitionPositions: [
|
||||
{ row: 14, column: 30 }, // Person
|
||||
{ row: 14, column: 42 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType:
|
||||
"function_definition with generic argument and generic return type",
|
||||
fileName: "python/functions.py",
|
||||
language: "Python",
|
||||
cursorPosition: { line: 18, character: 8 },
|
||||
definitionPositions: [
|
||||
{ row: 17, column: 35 }, // Group
|
||||
{ row: 17, column: 42 }, // Person
|
||||
{ row: 17, column: 53 }, // Group
|
||||
{ row: 17, column: 61 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_definition with single argument and None return type",
|
||||
fileName: "python/functions.py",
|
||||
language: "Python",
|
||||
cursorPosition: { line: 21, character: 8 },
|
||||
definitionPositions: [
|
||||
{ row: 20, column: 29 }, // Person
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_definition with no arguments and single return type",
|
||||
fileName: "python/functions.py",
|
||||
language: "Python",
|
||||
cursorPosition: { line: 24, character: 8 },
|
||||
definitionPositions: [
|
||||
{ row: 23, column: 38 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_definition with Union arguments and Union return type",
|
||||
fileName: "python/functions.py",
|
||||
language: "Python",
|
||||
cursorPosition: { line: 27, character: 8 },
|
||||
definitionPositions: [
|
||||
{ row: 26, column: 45 }, // Person
|
||||
{ row: 26, column: 54 }, // Address
|
||||
{ row: 26, column: 72 }, // Person
|
||||
{ row: 26, column: 81 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType:
|
||||
"function_definition with multiple arguments and None return type",
|
||||
fileName: "python/functions.py",
|
||||
language: "Python",
|
||||
cursorPosition: { line: 30, character: 8 },
|
||||
definitionPositions: [
|
||||
{ row: 29, column: 41 }, // Person
|
||||
{ row: 29, column: 59 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_definition with one argument and Generator return type",
|
||||
fileName: "python/functions.py",
|
||||
language: "Python",
|
||||
cursorPosition: { line: 33, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 32, column: 40 }, // Person
|
||||
{ row: 32, column: 62 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_definition inside a class",
|
||||
fileName: "python/functions.py",
|
||||
language: "Python",
|
||||
cursorPosition: { line: 38, character: 12 },
|
||||
definitionPositions: [
|
||||
{ row: 37, column: 51 }, // Person
|
||||
{ row: 37, column: 69 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_definition of an async function",
|
||||
fileName: "python/functions.py",
|
||||
language: "Python",
|
||||
cursorPosition: { line: 41, character: 8 },
|
||||
definitionPositions: [
|
||||
{ row: 40, column: 37 }, // Address
|
||||
{ row: 40, column: 48 }, // Person
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export const CLASSES = [
|
||||
{
|
||||
nodeType: "class_definition with multiple superclasses",
|
||||
fileName: "python/classes.py",
|
||||
language: "Python",
|
||||
cursorPosition: { line: 1, character: 8 },
|
||||
definitionPositions: [
|
||||
{ row: 0, column: 21 }, // BaseClass
|
||||
{ row: 0, column: 29 }, // Person
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "class_definition with multiple superclasses",
|
||||
fileName: "python/classes.py",
|
||||
language: "Python",
|
||||
cursorPosition: { line: 4, character: 8 },
|
||||
definitionPositions: [
|
||||
{ row: 3, column: 31 }, // MetaGroup
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "class_definition with generic superclasses",
|
||||
fileName: "python/classes.py",
|
||||
language: "Python",
|
||||
cursorPosition: { line: 7, character: 8 },
|
||||
definitionPositions: [
|
||||
{ row: 6, column: 21 }, // BaseClass
|
||||
{ row: 6, column: 29 }, // Address
|
||||
{ row: 6, column: 41 }, // Gathering
|
||||
{ row: 6, column: 48 }, // Person
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "class_definition with generic superclasses (built in types)",
|
||||
fileName: "python/classes.py",
|
||||
language: "Python",
|
||||
cursorPosition: { line: 10, character: 8 },
|
||||
definitionPositions: [
|
||||
{ row: 9, column: 24 }, // Address
|
||||
{ row: 9, column: 33 }, // Person
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export const PYTHON_TEST_CASES = [
|
||||
// ...FUNCTIONS,
|
||||
...CLASSES,
|
||||
];
|
||||
|
|
@ -0,0 +1,397 @@
|
|||
const FUNCTIONS = [
|
||||
{
|
||||
nodeType: "function_declaration with a param and a return type",
|
||||
fileName: "typescript/functions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 3, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 2, column: 34 }, // Person
|
||||
{ row: 2, column: 44 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_declaration with array param",
|
||||
fileName: "typescript/functions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 7, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 6, column: 39 }, // Person
|
||||
{ row: 6, column: 51 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_declaration without return type",
|
||||
fileName: "typescript/functions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 11, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 10, column: 33 }, // Person
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_declaration without params",
|
||||
fileName: "typescript/functions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 15, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 14, column: 39 }, // Person
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_declaration with array params and array return type",
|
||||
fileName: "typescript/functions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 19, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 18, column: 36 }, // Person
|
||||
{ row: 18, column: 48 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType:
|
||||
"function_declaration with generic params and generic return type",
|
||||
fileName: "typescript/functions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 23, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 22, column: 44 }, // Person
|
||||
{ row: 22, column: 52 }, // Address
|
||||
{ row: 22, column: 62 }, // Person
|
||||
{ row: 22, column: 70 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType:
|
||||
"function_declaration with union type params and union return type",
|
||||
fileName: "typescript/functions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 27, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 26, column: 42 }, // Person
|
||||
{ row: 26, column: 52 }, // Address
|
||||
{ row: 26, column: 61 }, // Person
|
||||
{ row: 26, column: 71 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_declaration with two arguments",
|
||||
fileName: "typescript/functions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 31, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 30, column: 43 }, // Person
|
||||
{ row: 30, column: 61 }, // Address
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const GENERATORS = [
|
||||
{
|
||||
nodeType: "function_declaration with a param and a return type",
|
||||
fileName: "typescript/generators.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 3, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 2, column: 35 }, // Person
|
||||
{ row: 2, column: 45 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_declaration with array param",
|
||||
fileName: "typescript/generators.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 7, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 6, column: 40 }, // Person
|
||||
{ row: 6, column: 52 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_declaration without return type",
|
||||
fileName: "typescript/generators.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 11, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 10, column: 34 }, // Person
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_declaration without params",
|
||||
fileName: "typescript/generators.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 15, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 14, column: 40 }, // Person
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_declaration with array params and array return type",
|
||||
fileName: "typescript/generators.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 19, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 18, column: 37 }, // Person
|
||||
{ row: 18, column: 49 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType:
|
||||
"function_declaration with generic params and generic return type",
|
||||
fileName: "typescript/generators.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 23, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 22, column: 45 }, // Person
|
||||
{ row: 22, column: 53 }, // Address
|
||||
{ row: 22, column: 63 }, // Person
|
||||
{ row: 22, column: 71 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType:
|
||||
"function_declaration with union type params and union return type",
|
||||
fileName: "typescript/generators.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 27, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 26, column: 43 }, // Person
|
||||
{ row: 26, column: 53 }, // Address
|
||||
{ row: 26, column: 62 }, // Person
|
||||
{ row: 26, column: 72 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "function_declaration with two arguments",
|
||||
fileName: "typescript/generators.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 31, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 30, column: 44 }, // Person
|
||||
{ row: 30, column: 62 }, // Address
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const ARROW_FUNCTIONS = [
|
||||
{
|
||||
nodeType: "arrow_function with a param and a return type",
|
||||
fileName: "typescript/arrowFunctions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 3, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 2, column: 34 }, // Person
|
||||
{ row: 2, column: 44 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "arrow_function without return type",
|
||||
fileName: "typescript/arrowFunctions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 7, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 6, column: 33 }, // Person
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "arrow_function without params",
|
||||
fileName: "typescript/arrowFunctions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 11, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 10, column: 39 }, // Person
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "arrow_function with array params and array return type",
|
||||
fileName: "typescript/arrowFunctions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 15, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 14, column: 36 }, // Person
|
||||
{ row: 14, column: 48 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "arrow_function with generic params and generic return type",
|
||||
fileName: "typescript/arrowFunctions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 19, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 18, column: 43 }, // Person
|
||||
{ row: 18, column: 51 }, // Address
|
||||
{ row: 18, column: 61 }, // Person
|
||||
{ row: 18, column: 69 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "arrow_function with union type params and union return type",
|
||||
fileName: "typescript/arrowFunctions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 23, character: 9 },
|
||||
definitionPositions: [
|
||||
{ row: 22, column: 42 }, // Person
|
||||
{ row: 22, column: 52 }, // Address
|
||||
{ row: 22, column: 61 }, // Person
|
||||
{ row: 22, column: 71 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "arrow_function with two arguments",
|
||||
fileName: "typescript/arrowFunctions.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 27, character: 11 },
|
||||
definitionPositions: [
|
||||
{ row: 26, column: 43 }, // Person
|
||||
{ row: 26, column: 61 }, // Address
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const CLASS_METHODS = [
|
||||
{
|
||||
nodeType: "method_declaration with a param and a return type",
|
||||
fileName: "typescript/classMethods.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 4, character: 11 },
|
||||
definitionPositions: [
|
||||
{ row: 3, column: 33 }, // Person
|
||||
{ row: 3, column: 43 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "method_declaration without arguments",
|
||||
fileName: "typescript/classMethods.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 8, character: 11 },
|
||||
definitionPositions: [
|
||||
{ row: 7, column: 32 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "method_declaration without return type",
|
||||
fileName: "typescript/classMethods.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 12, character: 11 },
|
||||
definitionPositions: [
|
||||
{ row: 11, column: 26 }, // Person
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "method_declaration with array type arguments",
|
||||
fileName: "typescript/classMethods.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 16, character: 11 },
|
||||
definitionPositions: [
|
||||
{ row: 15, column: 26 }, // Person
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType:
|
||||
"method_declaration with array type arguments and array type return",
|
||||
fileName: "typescript/classMethods.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 20, character: 11 },
|
||||
definitionPositions: [
|
||||
{ row: 19, column: 29 }, // Person
|
||||
{ row: 19, column: 41 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType:
|
||||
"method_declaration with with generic params and generic return type",
|
||||
fileName: "typescript/classMethods.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 24, character: 11 },
|
||||
definitionPositions: [
|
||||
{ row: 23, column: 37 }, // Person
|
||||
{ row: 23, column: 45 }, // Address
|
||||
{ row: 23, column: 55 }, // Person
|
||||
{ row: 23, column: 63 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "method_declaration with union type params and union return type",
|
||||
fileName: "typescript/classMethods.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 28, character: 11 },
|
||||
definitionPositions: [
|
||||
{ row: 27, column: 35 }, // Person
|
||||
{ row: 27, column: 45 }, // Address
|
||||
{ row: 27, column: 54 }, // Person
|
||||
{ row: 27, column: 64 }, // Address
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "method_declaration with two arguments",
|
||||
fileName: "typescript/classMethods.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 32, character: 11 },
|
||||
definitionPositions: [
|
||||
{ row: 31, column: 36 }, // Person
|
||||
{ row: 31, column: 54 }, // Address
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
const CLASS_DEFINITIONS = [
|
||||
{
|
||||
nodeType: "class_declaration with base class",
|
||||
fileName: "typescript/classes.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 2, character: 31 },
|
||||
definitionPositions: [
|
||||
{ row: 2, column: 29 }, // BaseClass
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "class_declaration with interface",
|
||||
fileName: "typescript/classes.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 4, character: 39 },
|
||||
definitionPositions: [
|
||||
{ row: 4, column: 37 }, // FirstInterface
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "class_declaration with base class and multiple interfaces",
|
||||
fileName: "typescript/classes.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 6, character: 74 },
|
||||
definitionPositions: [
|
||||
{ row: 6, column: 29 }, // BaseClass
|
||||
{ row: 6, column: 55 }, // FirstInterface
|
||||
{ row: 6, column: 72 }, // SecondInterface
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "class_declaration with base class and multiple interfaces",
|
||||
fileName: "typescript/classes.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 6, character: 74 },
|
||||
definitionPositions: [
|
||||
{ row: 6, column: 29 }, // BaseClass
|
||||
{ row: 6, column: 55 }, // FirstInterface
|
||||
{ row: 6, column: 72 }, // SecondInterface
|
||||
],
|
||||
},
|
||||
{
|
||||
nodeType: "class_declaration with generic base class and generic interface",
|
||||
fileName: "typescript/classes.ts",
|
||||
language: "TypeScript",
|
||||
cursorPosition: { line: 8, character: 69 },
|
||||
definitionPositions: [
|
||||
{ row: 8, column: 29 }, // BaseClass
|
||||
{ row: 8, column: 61 }, // FirstInterface
|
||||
{ row: 8, column: 34 }, // User
|
||||
{ row: 8, column: 66 }, // User
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export const TYPESCRIPT_TEST_CASES = [
|
||||
...FUNCTIONS,
|
||||
...GENERATORS,
|
||||
...ARROW_FUNCTIONS,
|
||||
...CLASS_METHODS,
|
||||
...CLASS_DEFINITIONS,
|
||||
];
|
||||
|
|
@ -3,46 +3,32 @@ import fs from "fs";
|
|||
import path from "path";
|
||||
|
||||
import Parser from "web-tree-sitter";
|
||||
import { Range } from "../../../..";
|
||||
import { Position } from "../../../..";
|
||||
import { testIde } from "../../../../test/util/fixtures";
|
||||
import { getAst, getTreePathAtCursor } from "../../../util/ast";
|
||||
import { ImportDefinitionsService } from "../../ImportDefinitionsService";
|
||||
import { RootPathContextService } from "../RootPathContextService";
|
||||
|
||||
function splitTextAtRange(fileContent: string, range: Range): [string, string] {
|
||||
function splitTextAtPosition(
|
||||
fileContent: string,
|
||||
position: Position,
|
||||
): [string, string] {
|
||||
const lines = fileContent.split("\n");
|
||||
let currentPos = 0;
|
||||
|
||||
if (range.start.line === range.end.line) {
|
||||
// If range is on the same line, calculate position once
|
||||
for (let i = 0; i < range.start.line; i++) {
|
||||
currentPos += lines[i].length + 1; // +1 for the newline character
|
||||
}
|
||||
const startPos = currentPos + range.start.character;
|
||||
const endPos = currentPos + range.end.character;
|
||||
return [fileContent.slice(0, startPos), fileContent.slice(endPos)];
|
||||
// Calculate position based on the provided line and character
|
||||
for (let i = 0; i < position.line; i++) {
|
||||
currentPos += lines[i].length + 1; // +1 for the newline character
|
||||
}
|
||||
const splitPos = currentPos + position.character;
|
||||
|
||||
// Calculate position of range start
|
||||
for (let i = 0; i < range.start.line; i++) {
|
||||
currentPos += lines[i].length + 1;
|
||||
}
|
||||
const startPos = currentPos + range.start.character;
|
||||
|
||||
// Calculate position of range end
|
||||
currentPos = 0;
|
||||
for (let i = 0; i < range.end.line; i++) {
|
||||
currentPos += lines[i].length + 1;
|
||||
}
|
||||
const endPos = currentPos + range.end.character;
|
||||
|
||||
return [fileContent.slice(0, startPos), fileContent.slice(endPos)];
|
||||
return [fileContent.slice(0, splitPos), fileContent.slice(splitPos)];
|
||||
}
|
||||
|
||||
export async function testRootPathContext(
|
||||
folderName: string,
|
||||
relativeFilepath: string,
|
||||
rangeToFill: Range,
|
||||
position: Position,
|
||||
expectedDefinitionPositions: Parser.Point[],
|
||||
) {
|
||||
// Create a mocked instance of RootPathContextService
|
||||
|
|
@ -76,9 +62,9 @@ export async function testRootPathContext(
|
|||
|
||||
// Get results of root path context
|
||||
const startPath = path.join(testFolderPath, relativeFilepath);
|
||||
const [prefix, suffix] = splitTextAtRange(
|
||||
const [prefix, suffix] = splitTextAtPosition(
|
||||
fs.readFileSync(startPath, "utf8"),
|
||||
rangeToFill,
|
||||
position,
|
||||
);
|
||||
const fileContents = prefix + suffix;
|
||||
const ast = await getAst(startPath, fileContents);
|
||||
|
|
@ -98,6 +84,7 @@ export async function testRootPathContext(
|
|||
index + 1,
|
||||
expect.any(String), // filepath argument
|
||||
position,
|
||||
expect.any(String), // language argument
|
||||
);
|
||||
});
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,25 +0,0 @@
|
|||
import {
|
||||
Address,
|
||||
Person,
|
||||
BaseClass,
|
||||
FirstInterface,
|
||||
SecondInterface,
|
||||
// @ts-ignore
|
||||
} from "./types";
|
||||
|
||||
function getAddress(person: Person): Address {
|
||||
return person.address;
|
||||
}
|
||||
|
||||
class Group extends BaseClass implements FirstInterface, SecondInterface {
|
||||
people: Person[];
|
||||
|
||||
constructor(people: Person[]) {
|
||||
super();
|
||||
this.people = people;
|
||||
}
|
||||
|
||||
getPersonAddress(person: Person): Address {
|
||||
return getAddress(person);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,3 +1,13 @@
|
|||
export const BRACKETS: { [key: string]: string } = {
|
||||
"(": ")",
|
||||
"{": "}",
|
||||
"[": "]",
|
||||
};
|
||||
export const BRACKETS_REVERSE: { [key: string]: string } = {
|
||||
")": "(",
|
||||
"}": "{",
|
||||
"]": "[",
|
||||
};
|
||||
/**
|
||||
* We follow the policy of only completing bracket pairs that we started
|
||||
* But sometimes we started the pair in a previous autocomplete suggestion
|
||||
|
|
@ -6,30 +16,18 @@ export class BracketMatchingService {
|
|||
private openingBracketsFromLastCompletion: string[] = [];
|
||||
private lastCompletionFile: string | undefined = undefined;
|
||||
|
||||
static BRACKETS: { [key: string]: string } = { "(": ")", "{": "}", "[": "]" };
|
||||
static BRACKETS_REVERSE: { [key: string]: string } = {
|
||||
")": "(",
|
||||
"}": "{",
|
||||
"]": "[",
|
||||
};
|
||||
|
||||
handleAcceptedCompletion(completion: string, filepath: string) {
|
||||
this.openingBracketsFromLastCompletion = [];
|
||||
const stack: string[] = [];
|
||||
|
||||
for (let i = 0; i < completion.length; i++) {
|
||||
const char = completion[i];
|
||||
if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) {
|
||||
if (Object.keys(BRACKETS).includes(char)) {
|
||||
// It's an opening bracket
|
||||
stack.push(char);
|
||||
} else if (
|
||||
Object.values(BracketMatchingService.BRACKETS).includes(char)
|
||||
) {
|
||||
} else if (Object.values(BRACKETS).includes(char)) {
|
||||
// It's a closing bracket
|
||||
if (
|
||||
stack.length === 0 ||
|
||||
BracketMatchingService.BRACKETS[stack.pop()!] !== char
|
||||
) {
|
||||
if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
@ -63,17 +61,12 @@ export class BracketMatchingService {
|
|||
(prefix.split("\n").pop() ?? "") + (suffix.split("\n")[0] ?? "");
|
||||
for (let i = 0; i < currentLine.length; i++) {
|
||||
const char = currentLine[i];
|
||||
if (Object.keys(BracketMatchingService.BRACKETS).includes(char)) {
|
||||
if (Object.keys(BRACKETS).includes(char)) {
|
||||
// It's an opening bracket
|
||||
stack.push(char);
|
||||
} else if (
|
||||
Object.values(BracketMatchingService.BRACKETS).includes(char)
|
||||
) {
|
||||
} else if (Object.values(BRACKETS).includes(char)) {
|
||||
// It's a closing bracket
|
||||
if (
|
||||
stack.length === 0 ||
|
||||
BracketMatchingService.BRACKETS[stack.pop()!] !== char
|
||||
) {
|
||||
if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
|
@ -87,7 +80,7 @@ export class BracketMatchingService {
|
|||
if (suffix[i] === " ") {
|
||||
continue;
|
||||
}
|
||||
const openBracket = BracketMatchingService.BRACKETS_REVERSE[suffix[i]];
|
||||
const openBracket = BRACKETS_REVERSE[suffix[i]];
|
||||
if (!openBracket) {
|
||||
break;
|
||||
}
|
||||
|
|
@ -115,19 +108,14 @@ export class BracketMatchingService {
|
|||
const allLines = all.split("\n");
|
||||
for (let i = 0; i < chunk.length; i++) {
|
||||
const char = chunk[i];
|
||||
if (Object.values(BracketMatchingService.BRACKETS).includes(char)) {
|
||||
if (Object.values(BRACKETS).includes(char)) {
|
||||
// It's a closing bracket
|
||||
if (
|
||||
stack.length === 0 ||
|
||||
BracketMatchingService.BRACKETS[stack.pop()!] !== char
|
||||
) {
|
||||
if (stack.length === 0 || BRACKETS[stack.pop()!] !== char) {
|
||||
// If the stack is empty or the top of the stack doesn't match the current closing bracket
|
||||
yield chunk.slice(0, i);
|
||||
return; // Stop the generator if the closing bracket doesn't have a matching opening bracket in the stream
|
||||
}
|
||||
} else if (
|
||||
Object.keys(BracketMatchingService.BRACKETS).includes(char)
|
||||
) {
|
||||
} else if (Object.keys(BRACKETS).includes(char)) {
|
||||
// It's an opening bracket
|
||||
stack.push(char);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { stopAtStopTokens } from "./charStream";
|
|||
import {
|
||||
avoidEmptyComments,
|
||||
avoidPathLine,
|
||||
noDoubleNewlineAfterClosingBracket,
|
||||
showWhateverWeHaveAtXMs,
|
||||
skipPrefixes,
|
||||
stopAtLines,
|
||||
|
|
@ -47,6 +48,7 @@ export class StreamTransformPipeline {
|
|||
);
|
||||
lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment);
|
||||
lineGenerator = skipPrefixes(lineGenerator);
|
||||
lineGenerator = noDoubleNewlineAfterClosingBracket(lineGenerator);
|
||||
|
||||
for (const lineFilter of helper.lang.lineFilters ?? []) {
|
||||
lineGenerator = lineFilter({ lines: lineGenerator, fullStop });
|
||||
|
|
|
|||
|
|
@ -157,4 +157,20 @@ describe("stopAtStopTokens", () => {
|
|||
|
||||
expect(output.join("")).toBe("Hello world!");
|
||||
});
|
||||
|
||||
it("should handle stop token when remaining buffer is smaller than maximum stop token length", async () => {
|
||||
const mockStream = createMockStream(["Hello world!STOP"]);
|
||||
const stopTokens: string[] = [
|
||||
"STOP",
|
||||
"STOP_TOKEN_THAT_IS_LARGER_THAN_BUFFER",
|
||||
];
|
||||
const result = stopAtStopTokens(mockStream, stopTokens);
|
||||
|
||||
const output = [];
|
||||
for await (const char of result) {
|
||||
output.push(char);
|
||||
}
|
||||
|
||||
expect(output.join("")).toBe("Hello world!");
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -70,7 +70,8 @@ export async function* noFirstCharNewline(stream: AsyncGenerator<string>) {
|
|||
* 2. Otherwise, buffers incoming chunks and checks for stop tokens.
|
||||
* 3. Yields characters one by one if no stop token is found at the start of the buffer.
|
||||
* 4. Stops yielding and returns if a stop token is encountered.
|
||||
* 5. After the stream ends, yields any remaining buffered characters.
|
||||
* 5. After the stream ends, filters encountered stop tokens in remaining buffer.
|
||||
* 6. Yields any remaining buffered characters.
|
||||
*/
|
||||
export async function* stopAtStopTokens(
|
||||
stream: AsyncGenerator<string>,
|
||||
|
|
@ -106,6 +107,10 @@ export async function* stopAtStopTokens(
|
|||
}
|
||||
}
|
||||
}
|
||||
// Filter out the possible stop tokens from remaining buffer
|
||||
stopTokens.forEach((token) => {
|
||||
buffer = buffer.replace(token, "");
|
||||
});
|
||||
|
||||
// Yield any remaining characters in the buffer
|
||||
for (const char of buffer) {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { distance } from "fastest-levenshtein";
|
|||
|
||||
import { DiffLine } from "../../..";
|
||||
import { LineStream } from "../../../diff/util";
|
||||
import { BRACKETS, BRACKETS_REVERSE } from "../BracketMatchingService";
|
||||
|
||||
export type LineFilter = (args: {
|
||||
lines: LineStream;
|
||||
|
|
@ -545,3 +546,43 @@ export async function* showWhateverWeHaveAtXMs(
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function* noDoubleNewlineAfterClosingBracket(
|
||||
lines: LineStream,
|
||||
): LineStream {
|
||||
const bracketTypeCounts = new Map<string, number>();
|
||||
|
||||
for await (const line of lines) {
|
||||
if (line.trim() === "") {
|
||||
// Double newline detected
|
||||
// Check if any bracket counts are negative
|
||||
let hasNegativeCount = false;
|
||||
for (const count of bracketTypeCounts.values()) {
|
||||
if (count < 0) {
|
||||
hasNegativeCount = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (hasNegativeCount) {
|
||||
// Stop the generator if we've closed brackets we didn't open
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
yield line;
|
||||
|
||||
// Update bracket counts
|
||||
for (const char of line) {
|
||||
if (BRACKETS[char]) {
|
||||
// It's an opening bracket
|
||||
const count = bracketTypeCounts.get(char) || 0;
|
||||
bracketTypeCounts.set(char, count + 1);
|
||||
} else if (BRACKETS_REVERSE[char]) {
|
||||
// It's a closing bracket
|
||||
const openingBracket = BRACKETS_REVERSE[char];
|
||||
const count = bracketTypeCounts.get(openingBracket) || 0;
|
||||
bracketTypeCounts.set(openingBracket, count - 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,166 @@
|
|||
import { noDoubleNewlineAfterClosingBracket } from "./lineStream";
|
||||
|
||||
describe("noDoubleNewlineAfterClosingBracket", () => {
|
||||
// Helper function to convert an array to an async generator
|
||||
async function* arrayToAsyncGenerator<T>(array: T[]): AsyncGenerator<T> {
|
||||
for (const item of array) {
|
||||
yield item;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper function to collect lines from the async generator
|
||||
async function collectLines(lines: AsyncIterable<string>): Promise<string[]> {
|
||||
const result: string[] = [];
|
||||
for await (const line of lines) {
|
||||
result.push(line);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
test("should yield all lines when no double newline and no unmatched brackets", async () => {
|
||||
const inputLines = [
|
||||
"function test() {",
|
||||
' console.log("Hello World");',
|
||||
"}",
|
||||
];
|
||||
const lines = arrayToAsyncGenerator(inputLines);
|
||||
const outputLines = await collectLines(
|
||||
noDoubleNewlineAfterClosingBracket(lines),
|
||||
);
|
||||
|
||||
expect(outputLines).toEqual(inputLines);
|
||||
});
|
||||
|
||||
test("should yield all lines when double newline but brackets are matched", async () => {
|
||||
const inputLines = [
|
||||
"function test() {",
|
||||
' console.log("Hello World");',
|
||||
"}",
|
||||
"",
|
||||
"",
|
||||
"// End of function",
|
||||
];
|
||||
const lines = arrayToAsyncGenerator(inputLines);
|
||||
const outputLines = await collectLines(
|
||||
noDoubleNewlineAfterClosingBracket(lines),
|
||||
);
|
||||
|
||||
expect(outputLines).toEqual(inputLines);
|
||||
});
|
||||
|
||||
test("should stop yielding after double newline when unmatched closing bracket is found before double newline", async () => {
|
||||
const inputLines = [
|
||||
// "function test() {",
|
||||
' console.log("Hello World");',
|
||||
// Unmatched closing bracket
|
||||
"}",
|
||||
"",
|
||||
"",
|
||||
"// This should not be yielded",
|
||||
'console.log("End");',
|
||||
];
|
||||
const expectedOutputLines = [' console.log("Hello World");', "}"];
|
||||
const lines = arrayToAsyncGenerator(inputLines);
|
||||
const outputLines = await collectLines(
|
||||
noDoubleNewlineAfterClosingBracket(lines),
|
||||
);
|
||||
|
||||
expect(outputLines).toEqual(expectedOutputLines);
|
||||
});
|
||||
|
||||
test("should yield all lines when unmatched brackets but no double newline", async () => {
|
||||
const inputLines = [
|
||||
"function test() {",
|
||||
' console.log("Hello World");',
|
||||
"}",
|
||||
// Unmatched closing bracket
|
||||
")",
|
||||
"// Continue code",
|
||||
'console.log("End");',
|
||||
];
|
||||
const lines = arrayToAsyncGenerator(inputLines);
|
||||
const outputLines = await collectLines(
|
||||
noDoubleNewlineAfterClosingBracket(lines),
|
||||
);
|
||||
|
||||
expect(outputLines).toEqual(inputLines);
|
||||
});
|
||||
|
||||
test("should continue yielding if unmatched closing bracket occurs after double newline", async () => {
|
||||
const inputLines = [
|
||||
"function test() {",
|
||||
' console.log("Hello World");',
|
||||
"}",
|
||||
"",
|
||||
"",
|
||||
// Unmatched closing bracket after double newline
|
||||
")",
|
||||
'console.log("End");',
|
||||
];
|
||||
const lines = arrayToAsyncGenerator(inputLines);
|
||||
const outputLines = await collectLines(
|
||||
noDoubleNewlineAfterClosingBracket(lines),
|
||||
);
|
||||
|
||||
expect(outputLines).toEqual(inputLines);
|
||||
});
|
||||
|
||||
test("should yield all lines when brackets are matched even with double newline", async () => {
|
||||
const inputLines = [
|
||||
"const arr = [",
|
||||
" 1, 2, 3,",
|
||||
"];",
|
||||
"",
|
||||
"",
|
||||
"console.log(arr);",
|
||||
];
|
||||
const lines = arrayToAsyncGenerator(inputLines);
|
||||
const outputLines = await collectLines(
|
||||
noDoubleNewlineAfterClosingBracket(lines),
|
||||
);
|
||||
|
||||
expect(outputLines).toEqual(inputLines);
|
||||
});
|
||||
|
||||
test("should stop yielding when unmatched closing bracket occurs before double newline", async () => {
|
||||
const inputLines = [
|
||||
"if (condition) {",
|
||||
" doSomething();",
|
||||
"}",
|
||||
// Unmatched closing bracket
|
||||
"}",
|
||||
"",
|
||||
"",
|
||||
"doSomethingElse();",
|
||||
];
|
||||
const expectedOutputLines = [
|
||||
"if (condition) {",
|
||||
" doSomething();",
|
||||
"}",
|
||||
"}",
|
||||
];
|
||||
const lines = arrayToAsyncGenerator(inputLines);
|
||||
const outputLines = await collectLines(
|
||||
noDoubleNewlineAfterClosingBracket(lines),
|
||||
);
|
||||
|
||||
expect(outputLines).toEqual(expectedOutputLines);
|
||||
});
|
||||
|
||||
test("should yield all lines when no unmatched closing brackets and double newline", async () => {
|
||||
const inputLines = [
|
||||
"while (true) {",
|
||||
" // Infinite loop",
|
||||
"}",
|
||||
"",
|
||||
"",
|
||||
"// Loop exited",
|
||||
];
|
||||
const lines = arrayToAsyncGenerator(inputLines);
|
||||
const outputLines = await collectLines(
|
||||
noDoubleNewlineAfterClosingBracket(lines),
|
||||
);
|
||||
|
||||
expect(outputLines).toEqual(inputLines);
|
||||
});
|
||||
});
|
||||
|
|
@ -14,7 +14,7 @@ const filterTestCases = (tests: AutocompleteFileringTestInput[]) => {
|
|||
return tests;
|
||||
};
|
||||
|
||||
describe("llms/Mock", () => {
|
||||
describe("Autocomplete filtering tests", () => {
|
||||
beforeAll(async () => {
|
||||
tearDownTestDir();
|
||||
setUpTestDir();
|
||||
|
|
@ -24,27 +24,25 @@ describe("llms/Mock", () => {
|
|||
tearDownTestDir();
|
||||
});
|
||||
|
||||
describe("Autocomplete Filtering Tests", () => {
|
||||
beforeEach(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
});
|
||||
beforeEach(async () => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
});
|
||||
|
||||
describe("Should return unmodified LLM output", () => {
|
||||
it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))(
|
||||
"$description",
|
||||
async (testCase) => {
|
||||
await testAutocompleteFiltering(testCase);
|
||||
},
|
||||
);
|
||||
});
|
||||
describe("Should return unmodified LLM output", () => {
|
||||
it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))(
|
||||
"$description",
|
||||
async (testCase) => {
|
||||
await testAutocompleteFiltering(testCase);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe("Should return modified LLM output", () => {
|
||||
it.each(filterTestCases(TEST_CASES_WITH_DIFF))(
|
||||
"$description",
|
||||
async (testCase) => {
|
||||
await testAutocompleteFiltering(testCase);
|
||||
},
|
||||
);
|
||||
});
|
||||
describe("Should return modified LLM output", () => {
|
||||
it.each(filterTestCases(TEST_CASES_WITH_DIFF))(
|
||||
"$description",
|
||||
async (testCase) => {
|
||||
await testAutocompleteFiltering(testCase);
|
||||
},
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -63,7 +63,7 @@ function sayHello() {
|
|||
`,
|
||||
llmOutput: `world!");
|
||||
`,
|
||||
expectedCompletion: "world!\");",
|
||||
expectedCompletion: 'world!");',
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete Java when inside a block",
|
||||
|
|
@ -131,10 +131,6 @@ public class Calculator {
|
|||
}
|
||||
`,
|
||||
expectedCompletion: `
|
||||
}
|
||||
|
||||
public void subtract(double number) {
|
||||
result -= number;
|
||||
}`,
|
||||
},
|
||||
{
|
||||
|
|
@ -489,8 +485,8 @@ echo calculateArea(5, 3);`,
|
|||
$colors = array("Red", "Green", <|fim|>);
|
||||
|
||||
echo "First color is: " . $colors[0];`,
|
||||
llmOutput: "\"Blue\"",
|
||||
expectedCompletion: "\"Blue\"",
|
||||
llmOutput: '"Blue"',
|
||||
expectedCompletion: '"Blue"',
|
||||
filename: "colors.php",
|
||||
},
|
||||
{
|
||||
|
|
@ -775,8 +771,10 @@ func main() {
|
|||
FROM users u
|
||||
WHERE u.active = 1
|
||||
<|fim|>`,
|
||||
llmOutput: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
|
||||
expectedCompletion: " AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
|
||||
llmOutput:
|
||||
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
|
||||
expectedCompletion:
|
||||
" AND EXISTS (SELECT 1 FROM transactions t WHERE t.user_id = u.id AND t.amount > 100)",
|
||||
},
|
||||
{
|
||||
description:
|
||||
|
|
@ -817,8 +815,8 @@ func main() {
|
|||
<p>Description text.</p>
|
||||
</div>
|
||||
</div>`,
|
||||
llmOutput: "alt=\"Description of image\"",
|
||||
expectedCompletion: "alt=\"Description of image\"",
|
||||
llmOutput: 'alt="Description of image"',
|
||||
expectedCompletion: 'alt="Description of image"',
|
||||
filename: "test.html",
|
||||
},
|
||||
{
|
||||
|
|
@ -930,8 +928,8 @@ public class App {
|
|||
<|fim|>
|
||||
]
|
||||
}`,
|
||||
llmOutput: ", { \"id\": 3, \"name\": \"Charlie\" }",
|
||||
expectedCompletion: ", { \"id\": 3, \"name\": \"Charlie\" }",
|
||||
llmOutput: ', { "id": 3, "name": "Charlie" }',
|
||||
expectedCompletion: ', { "id": 3, "name": "Charlie" }',
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete within a CSV record",
|
||||
|
|
@ -1237,8 +1235,8 @@ class Counter {
|
|||
:age 30
|
||||
<|fim|>
|
||||
(println "User information loaded"))`,
|
||||
llmOutput: ":location \"Unknown\"}",
|
||||
expectedCompletion: ":location \"Unknown\"}",
|
||||
llmOutput: ':location "Unknown"}',
|
||||
expectedCompletion: ':location "Unknown"}',
|
||||
filename: "test.clj",
|
||||
},
|
||||
{
|
||||
|
|
@ -1301,8 +1299,8 @@ if (grade >= 90) {
|
|||
} else {
|
||||
print("C")
|
||||
}`,
|
||||
llmOutput: "print(\"B\")",
|
||||
expectedCompletion: "print(\"B\")",
|
||||
llmOutput: 'print("B")',
|
||||
expectedCompletion: 'print("B")',
|
||||
},
|
||||
{
|
||||
description: "Should autocomplete R ggplot2 plot structure",
|
||||
|
|
@ -1324,8 +1322,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) +
|
|||
<|fim|>
|
||||
}
|
||||
}`,
|
||||
llmOutput: "s\"Hello, my name is $name and I am $age years old.\"",
|
||||
expectedCompletion: "s\"Hello, my name is $name and I am $age years old.\"",
|
||||
llmOutput: 's"Hello, my name is $name and I am $age years old."',
|
||||
expectedCompletion: 's"Hello, my name is $name and I am $age years old."',
|
||||
},
|
||||
|
||||
{
|
||||
|
|
@ -1335,8 +1333,8 @@ ggplot(data=mtcars, aes(x=wt, y=mpg)) +
|
|||
case class Person(name: String, age: Int, address: Address)
|
||||
|
||||
val alice = Person("Alice", 30, Address("Wonderland", <|fim|>))`,
|
||||
llmOutput: "\"12345\")",
|
||||
expectedCompletion: "\"12345\")",
|
||||
llmOutput: '"12345")',
|
||||
expectedCompletion: '"12345")',
|
||||
},
|
||||
|
||||
{
|
||||
|
|
@ -2066,8 +2064,8 @@ export default {
|
|||
<ChildComponent <|fim|> />
|
||||
</main>
|
||||
`,
|
||||
llmOutput: "name=\"World\"",
|
||||
expectedCompletion: "name=\"World\"",
|
||||
llmOutput: 'name="World"',
|
||||
expectedCompletion: 'name="World"',
|
||||
},
|
||||
|
||||
{
|
||||
|
|
|
|||
215
core/autocomplete/generation/GeneratorReuseManager.test.ts
Normal file
215
core/autocomplete/generation/GeneratorReuseManager.test.ts
Normal file
|
|
@ -0,0 +1,215 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import { GeneratorReuseManager } from "./GeneratorReuseManager";
|
||||
|
||||
function createMockGenerator(
|
||||
data: string[],
|
||||
delay: number = 0,
|
||||
): () => AsyncGenerator<string> {
|
||||
const mockGenerator = async function* () {
|
||||
for (const chunk of data) {
|
||||
yield chunk;
|
||||
|
||||
if (delay > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||
}
|
||||
}
|
||||
};
|
||||
const newGenerator = jest
|
||||
.fn<() => AsyncGenerator<string>>()
|
||||
.mockReturnValue(mockGenerator());
|
||||
|
||||
return newGenerator;
|
||||
}
|
||||
|
||||
describe("GeneratorReuseManager", () => {
|
||||
let reuseManager: GeneratorReuseManager;
|
||||
let onErrorMock: jest.Mock;
|
||||
|
||||
beforeEach(() => {
|
||||
onErrorMock = jest.fn();
|
||||
reuseManager = new GeneratorReuseManager(onErrorMock);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.clearAllMocks();
|
||||
});
|
||||
|
||||
test("creates new generator when there is no current generator", async () => {
|
||||
const data = ["hello ", "world"];
|
||||
const newGenerator = createMockGenerator(data);
|
||||
|
||||
const prefix = "";
|
||||
|
||||
const generator = reuseManager.getGenerator(prefix, newGenerator, true);
|
||||
|
||||
const output: string[] = [];
|
||||
for await (const chunk of generator) {
|
||||
output.push(chunk);
|
||||
}
|
||||
|
||||
expect(output).toEqual(data);
|
||||
expect(newGenerator).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("reuses generator when prefix matches pending completion", async () => {
|
||||
const newGenerator = createMockGenerator(["llo ", "world"]);
|
||||
|
||||
// First call with initial prefix
|
||||
const prefix1 = "he";
|
||||
const generator1 = reuseManager.getGenerator(prefix1, newGenerator, true);
|
||||
|
||||
const output1: string[] = [];
|
||||
for await (const chunk of generator1) {
|
||||
output1.push(chunk);
|
||||
}
|
||||
|
||||
expect(output1).toEqual(["llo ", "world"]);
|
||||
|
||||
// Second call with extended prefix that matches pending completion
|
||||
const prefix2 = "hello ";
|
||||
const generator2 = reuseManager.getGenerator(prefix2, newGenerator, true);
|
||||
|
||||
const output2: string[] = [];
|
||||
for await (const chunk of generator2) {
|
||||
output2.push(chunk);
|
||||
}
|
||||
|
||||
expect(output2).toEqual(["world"]);
|
||||
|
||||
// Ensure generator was reused (newGenerator should be called only once)
|
||||
expect(newGenerator).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("creates new generator when prefix does not match pending completion", async () => {
|
||||
const data = ["goodbye ", "world"];
|
||||
const newGenerator = createMockGenerator(data);
|
||||
|
||||
// Initial generator with different prefix
|
||||
reuseManager.pendingGeneratorPrefix = "hello ";
|
||||
reuseManager.pendingCompletion = "world";
|
||||
|
||||
const prefix = "good";
|
||||
const generator = reuseManager.getGenerator(prefix, newGenerator, true);
|
||||
|
||||
const output: string[] = [];
|
||||
for await (const chunk of generator) {
|
||||
output.push(chunk);
|
||||
}
|
||||
|
||||
expect(output).toEqual(data);
|
||||
// Ensure a new generator was created
|
||||
expect(newGenerator).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("handles multiline=false by stopping at newline", async () => {
|
||||
const data = ["first line\n", "second line"];
|
||||
const newGenerator = createMockGenerator(data);
|
||||
|
||||
const prefix = "";
|
||||
const generator = reuseManager.getGenerator(prefix, newGenerator, false);
|
||||
|
||||
const output: string[] = [];
|
||||
for await (const chunk of generator) {
|
||||
output.push(chunk);
|
||||
}
|
||||
|
||||
expect(output).toEqual(["first line"]);
|
||||
// Ensure it stops after the first newline
|
||||
});
|
||||
|
||||
test("handles multiline=true by not stopping at newline", async () => {
|
||||
const data = ["first line\n", "second line"];
|
||||
const newGenerator = createMockGenerator(data);
|
||||
|
||||
const prefix = "";
|
||||
const generator = reuseManager.getGenerator(prefix, newGenerator, true);
|
||||
|
||||
const output: string[] = [];
|
||||
for await (const chunk of generator) {
|
||||
output.push(chunk);
|
||||
}
|
||||
|
||||
expect(output).toEqual(data);
|
||||
});
|
||||
|
||||
test("cancels previous generator when creating a new one", async () => {
|
||||
const data1 = ["data from generator 1", "not generated"];
|
||||
const data2 = ["data from generator 2"];
|
||||
|
||||
const newGenerator1 = createMockGenerator(data1, 1000); // Delay so we have the chance to cancel it
|
||||
const newGenerator2 = createMockGenerator(data2);
|
||||
|
||||
const prefix1 = "prefix1";
|
||||
const prefix2 = "prefix2";
|
||||
|
||||
// First generator
|
||||
const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
|
||||
const output1: string[] = [];
|
||||
for await (const chunk of generator1) {
|
||||
output1.push(chunk);
|
||||
// Simulate the generator being canceled before completing
|
||||
reuseManager.currentGenerator?.cancel();
|
||||
}
|
||||
|
||||
expect(output1.length).toEqual(1);
|
||||
expect(output1[0]).toEqual(data1[0]);
|
||||
|
||||
// Second generator
|
||||
const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
|
||||
const output2: string[] = [];
|
||||
for await (const chunk of generator2) {
|
||||
output2.push(chunk);
|
||||
}
|
||||
|
||||
expect(output2).toEqual(data2);
|
||||
});
|
||||
|
||||
test("calls onError when generator throws an error", async () => {
|
||||
const error = new Error("Generator error");
|
||||
const mockGenerator = async function* () {
|
||||
throw error;
|
||||
};
|
||||
const newGenerator = jest
|
||||
.fn<() => AsyncGenerator<string>>()
|
||||
.mockReturnValue(mockGenerator());
|
||||
|
||||
const prefix = "";
|
||||
const generator = reuseManager.getGenerator(prefix, newGenerator, true);
|
||||
|
||||
const output: string[] = [];
|
||||
await expect(async () => {
|
||||
for await (const chunk of generator) {
|
||||
output.push(chunk);
|
||||
}
|
||||
}).not.toThrow(); // getGenerator handles errors internally
|
||||
|
||||
expect(onErrorMock).toHaveBeenCalledWith(error);
|
||||
expect(output).toEqual([]);
|
||||
});
|
||||
|
||||
test("handles backspacing by creating new generator when prefix is shorter", async () => {
|
||||
const data = ["hello world"];
|
||||
const newGenerator1 = createMockGenerator(data);
|
||||
const newGenerator2 = createMockGenerator(data);
|
||||
|
||||
// First prefix
|
||||
const prefix1 = "hello world";
|
||||
const generator1 = reuseManager.getGenerator(prefix1, newGenerator1, true);
|
||||
const output1: string[] = [];
|
||||
for await (const chunk of generator1) {
|
||||
output1.push(chunk);
|
||||
}
|
||||
|
||||
// Simulate backspace (prefix is shorter)
|
||||
const prefix2 = "hello worl";
|
||||
const generator2 = reuseManager.getGenerator(prefix2, newGenerator2, true);
|
||||
const output2: string[] = [];
|
||||
for await (const chunk of generator2) {
|
||||
output2.push(chunk);
|
||||
}
|
||||
|
||||
// Ensure a new generator was created
|
||||
expect(newGenerator1).toHaveBeenCalledTimes(1);
|
||||
expect(newGenerator2).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
|
@ -21,47 +21,54 @@ export class GeneratorReuseManager {
|
|||
this.currentGenerator = listenableGen;
|
||||
}
|
||||
|
||||
private shouldReuseExistingGenerator(prefix: string): boolean {
|
||||
return (
|
||||
!!this.currentGenerator &&
|
||||
!!this.pendingGeneratorPrefix &&
|
||||
(this.pendingGeneratorPrefix + this.pendingCompletion).startsWith(
|
||||
prefix,
|
||||
) &&
|
||||
// for e.g. backspace
|
||||
this.pendingGeneratorPrefix?.length <= prefix?.length
|
||||
);
|
||||
}
|
||||
|
||||
async *getGenerator(
|
||||
prefix: string,
|
||||
newGenerator: () => AsyncGenerator<string>,
|
||||
multiline: boolean,
|
||||
): AsyncGenerator<string> {
|
||||
// Check if current can be reused
|
||||
if (
|
||||
!(
|
||||
this.currentGenerator &&
|
||||
this.pendingGeneratorPrefix &&
|
||||
(this.pendingGeneratorPrefix + this.pendingCompletion).startsWith(
|
||||
prefix,
|
||||
) &&
|
||||
// for e.g. backspace
|
||||
this.pendingGeneratorPrefix?.length <= prefix?.length
|
||||
)
|
||||
) {
|
||||
// If we can't reuse, then create a new generator
|
||||
if (!this.shouldReuseExistingGenerator(prefix)) {
|
||||
// Create a wrapper over the current generator to fix the prompt
|
||||
this._createListenableGenerator(newGenerator(), prefix);
|
||||
}
|
||||
|
||||
let alreadyTyped = prefix.slice(this.pendingGeneratorPrefix?.length) || "";
|
||||
// Already typed characters are those that are new in the prefix from the old generator
|
||||
let typedSinceLastGenerator =
|
||||
prefix.slice(this.pendingGeneratorPrefix?.length) || "";
|
||||
for await (let chunk of this.currentGenerator?.tee() ?? []) {
|
||||
if (!chunk) {
|
||||
continue;
|
||||
}
|
||||
while (chunk.length && alreadyTyped.length) {
|
||||
if (chunk[0] === alreadyTyped[0]) {
|
||||
alreadyTyped = alreadyTyped.slice(1);
|
||||
|
||||
// Ignore already typed characters in the completion
|
||||
while (chunk.length && typedSinceLastGenerator.length) {
|
||||
if (chunk[0] === typedSinceLastGenerator[0]) {
|
||||
typedSinceLastGenerator = typedSinceLastGenerator.slice(1);
|
||||
chunk = chunk.slice(1);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Break at newline unless we are in multiline mode
|
||||
const newLineIndex = chunk.indexOf("\n");
|
||||
if (multiline || newLineIndex === -1) {
|
||||
yield chunk;
|
||||
} else {
|
||||
if (newLineIndex >= 0 && !multiline) {
|
||||
yield chunk.slice(0, newLineIndex);
|
||||
break;
|
||||
} else if (chunk !== "") {
|
||||
yield chunk;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
149
core/autocomplete/generation/ListenableGenerator.test.ts
Normal file
149
core/autocomplete/generation/ListenableGenerator.test.ts
Normal file
|
|
@ -0,0 +1,149 @@
|
|||
import { jest } from "@jest/globals";
|
||||
import { ListenableGenerator } from "./ListenableGenerator";
|
||||
|
||||
describe("ListenableGenerator", () => {
|
||||
// Helper function to create an async generator
|
||||
async function* asyncGenerator<T>(values: T[], delay = 0) {
|
||||
for (const value of values) {
|
||||
if (delay > 0) {
|
||||
await new Promise((resolve) => setTimeout(resolve, delay));
|
||||
}
|
||||
yield value;
|
||||
}
|
||||
}
|
||||
|
||||
it("should yield values from the source generator via tee()", async () => {
|
||||
const values = [1, 2, 3];
|
||||
const source = asyncGenerator(values);
|
||||
const onError = jest.fn();
|
||||
|
||||
const lg = new ListenableGenerator<number>(source, onError);
|
||||
|
||||
const result: number[] = [];
|
||||
for await (const value of lg.tee()) {
|
||||
result.push(value);
|
||||
}
|
||||
|
||||
expect(result).toEqual(values);
|
||||
expect(onError).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("should allow listeners to receive values", async () => {
|
||||
const values = [1, 2, 3];
|
||||
const source = asyncGenerator(values, 10); // Introduce delay to simulate async behavior
|
||||
const onError = jest.fn();
|
||||
|
||||
const lg = new ListenableGenerator<number>(source, onError);
|
||||
|
||||
const listener = jest.fn();
|
||||
|
||||
// Add listener after some delay to simulate late subscription
|
||||
setTimeout(() => {
|
||||
lg.listen(listener);
|
||||
}, 15);
|
||||
|
||||
// Wait for generator to finish
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(1);
|
||||
expect(listener).toHaveBeenCalledWith(2);
|
||||
expect(listener).toHaveBeenCalledWith(3);
|
||||
// Listener should receive null at the end
|
||||
expect(listener).toHaveBeenCalledWith(null);
|
||||
});
|
||||
|
||||
it("should buffer values for listeners added after some values have been yielded", async () => {
|
||||
const values = [1, 2, 3];
|
||||
const source = asyncGenerator(values, 10);
|
||||
const onError = jest.fn();
|
||||
|
||||
const lg = new ListenableGenerator<number>(source, onError);
|
||||
|
||||
const initialListener = jest.fn();
|
||||
|
||||
lg.listen(initialListener);
|
||||
|
||||
// Wait for the first value to be yielded
|
||||
await new Promise((resolve) => setTimeout(resolve, 15));
|
||||
|
||||
// Add a second listener
|
||||
const newListener = jest.fn();
|
||||
lg.listen(newListener);
|
||||
|
||||
// Wait for generator to finish
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
|
||||
// Both listeners should have received all values
|
||||
[initialListener, newListener].forEach((listener) => {
|
||||
expect(listener).toHaveBeenCalledWith(1);
|
||||
expect(listener).toHaveBeenCalledWith(2);
|
||||
expect(listener).toHaveBeenCalledWith(3);
|
||||
expect(listener).toHaveBeenCalledWith(null);
|
||||
});
|
||||
});
|
||||
|
||||
it("should handle cancellation", async () => {
|
||||
const values = [1, 2, 3, 4, 5];
|
||||
const source = asyncGenerator(values, 10);
|
||||
const onError = jest.fn();
|
||||
|
||||
const lg = new ListenableGenerator<number>(source, onError);
|
||||
|
||||
const result: number[] = [];
|
||||
const teeIterator = lg.tee();
|
||||
|
||||
const consume = async () => {
|
||||
for await (const value of teeIterator) {
|
||||
result.push(value);
|
||||
if (value === 3) {
|
||||
lg.cancel();
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
await consume();
|
||||
|
||||
expect(result).toEqual([1, 2, 3]);
|
||||
expect(lg["_isEnded"]).toBe(true);
|
||||
});
|
||||
|
||||
it("should call onError when the source generator throws an error", async () => {
|
||||
async function* errorGenerator() {
|
||||
yield 1;
|
||||
throw new Error("Test error");
|
||||
}
|
||||
|
||||
const source = errorGenerator();
|
||||
const onError = jest.fn();
|
||||
|
||||
const lg = new ListenableGenerator<number>(source, onError);
|
||||
|
||||
const result: number[] = [];
|
||||
for await (const value of lg.tee()) {
|
||||
result.push(value);
|
||||
}
|
||||
|
||||
expect(result).toEqual([1]);
|
||||
expect(onError).toHaveBeenCalledTimes(1);
|
||||
expect(onError).toHaveBeenCalledWith(new Error("Test error"));
|
||||
});
|
||||
|
||||
it("should notify listeners when the generator ends", async () => {
|
||||
const values = [1, 2, 3];
|
||||
const source = asyncGenerator(values);
|
||||
const onError = jest.fn();
|
||||
|
||||
const lg = new ListenableGenerator<number>(source, onError);
|
||||
|
||||
const listener = jest.fn();
|
||||
lg.listen(listener);
|
||||
|
||||
// Wait for the generator to finish
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
|
||||
expect(listener).toHaveBeenCalledWith(1);
|
||||
expect(listener).toHaveBeenCalledWith(2);
|
||||
expect(listener).toHaveBeenCalledWith(3);
|
||||
expect(listener).toHaveBeenCalledWith(null);
|
||||
});
|
||||
});
|
||||
|
|
@ -37,6 +37,7 @@ export class AutocompleteLoggingService {
|
|||
|
||||
if (this._outcomes.has(completionId)) {
|
||||
const outcome = this._outcomes.get(completionId)!;
|
||||
outcome.accepted = true;
|
||||
this.logAutocompleteOutcome(outcome);
|
||||
this._outcomes.delete(completionId);
|
||||
return outcome;
|
||||
|
|
@ -94,7 +95,6 @@ export class AutocompleteLoggingService {
|
|||
}
|
||||
|
||||
private logAutocompleteOutcome(outcome: AutocompleteOutcome) {
|
||||
outcome.accepted = true;
|
||||
logDevData("autocomplete", outcome);
|
||||
const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome;
|
||||
void Telemetry.capture(
|
||||
|
|
|
|||
27
core/config/getSystemPromptDotFile.ts
Normal file
27
core/config/getSystemPromptDotFile.ts
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
import { IDE } from "..";
|
||||
|
||||
export const SYSTEM_PROMPT_DOT_FILE = ".continuerules";
|
||||
|
||||
export async function getSystemPromptDotFile(ide: IDE): Promise<string | null> {
|
||||
const dirs = await ide.getWorkspaceDirs();
|
||||
|
||||
let prompts: string[] = [];
|
||||
const pathSep = await ide.pathSep();
|
||||
for (const dir of dirs) {
|
||||
const dotFile = `${dir}${pathSep}${SYSTEM_PROMPT_DOT_FILE}`;
|
||||
if (await ide.fileExists(dotFile)) {
|
||||
try {
|
||||
const content = await ide.readFile(dotFile);
|
||||
prompts.push(content);
|
||||
} catch (e) {
|
||||
// ignore if file doesn't exist
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!prompts.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return prompts.join("\n\n");
|
||||
}
|
||||
|
|
@ -64,6 +64,7 @@ import {
|
|||
defaultSlashCommandsJetBrains,
|
||||
defaultSlashCommandsVscode,
|
||||
} from "./default";
|
||||
import { getSystemPromptDotFile } from "./getSystemPromptDotFile";
|
||||
import {
|
||||
DEFAULT_PROMPTS_FOLDER,
|
||||
getPromptFiles,
|
||||
|
|
@ -215,7 +216,10 @@ async function serializedToIntermediateConfig(
|
|||
promptFiles.push(...readAllGlobalPromptFiles());
|
||||
|
||||
for (const file of promptFiles) {
|
||||
slashCommands.push(slashCommandFromPromptFile(file.path, file.content));
|
||||
const slashCommand = slashCommandFromPromptFile(file.path, file.content);
|
||||
if (slashCommand) {
|
||||
slashCommands.push(slashCommand);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -732,6 +736,11 @@ async function loadFullConfigNode(
|
|||
return { errors, config: undefined, configLoadInterrupted: true };
|
||||
}
|
||||
|
||||
const systemPromptDotFile = await getSystemPromptDotFile(ide);
|
||||
if (systemPromptDotFile) {
|
||||
serialized.systemMessage = systemPromptDotFile;
|
||||
}
|
||||
|
||||
// Convert serialized to intermediate config
|
||||
let intermediate = await serializedToIntermediateConfig(serialized, ide);
|
||||
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { FREE_TRIAL_MODELS } from "./default";
|
|||
|
||||
export const TRIAL_FIM_MODEL = "codestral-latest";
|
||||
export const ONBOARDING_LOCAL_MODEL_TITLE = "Ollama";
|
||||
export const LOCAL_ONBOARDING_FIM_MODEL = "starcoder2:3b";
|
||||
export const LOCAL_ONBOARDING_FIM_MODEL = "qwen2.5-coder:1.5b";
|
||||
export const LOCAL_ONBOARDING_CHAT_MODEL = "llama3.1:8b";
|
||||
export const LOCAL_ONBOARDING_CHAT_TITLE = "Llama 3.1 8B";
|
||||
|
||||
|
|
@ -35,7 +35,7 @@ export function setupLocalConfig(
|
|||
...config.models.filter((model) => model.provider !== "free-trial"),
|
||||
],
|
||||
tabAutocompleteModel: {
|
||||
title: "Starcoder 3b",
|
||||
title: "Qwen2.5-Coder 1.5B",
|
||||
provider: "ollama",
|
||||
model: LOCAL_ONBOARDING_FIM_MODEL,
|
||||
},
|
||||
|
|
|
|||
|
|
@ -3,13 +3,19 @@ import path from "path";
|
|||
import Handlebars from "handlebars";
|
||||
import * as YAML from "yaml";
|
||||
|
||||
import { BaseContextProvider } from "../context";
|
||||
import { walkDir } from "../indexing/walkDir";
|
||||
import { stripImages } from "../llm/images";
|
||||
import { renderTemplatedString } from "../promptFiles/v1/renderTemplatedString";
|
||||
import { getBasename } from "../util/index";
|
||||
|
||||
import type { ChatHistory, ChatHistoryItem, ChatMessage, ContextItem, ContinueSDK, IContextProvider, IDE, SlashCommand } from "..";
|
||||
import type {
|
||||
ChatMessage,
|
||||
ContextItem,
|
||||
ContinueSDK,
|
||||
IContextProvider,
|
||||
IDE,
|
||||
SlashCommand,
|
||||
} from "..";
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER = ".prompts";
|
||||
|
||||
|
|
@ -93,12 +99,16 @@ export async function createNewPromptFile(
|
|||
export function slashCommandFromPromptFile(
|
||||
path: string,
|
||||
content: string,
|
||||
): SlashCommand {
|
||||
const { name, description, systemMessage, prompt } = parsePromptFile(
|
||||
): SlashCommand | null {
|
||||
const { name, description, systemMessage, prompt, version } = parsePromptFile(
|
||||
path,
|
||||
content,
|
||||
);
|
||||
|
||||
if (version !== 1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
name,
|
||||
description,
|
||||
|
|
@ -134,6 +144,7 @@ function parsePromptFile(path: string, content: string) {
|
|||
const preamble = YAML.parse(preambleRaw) ?? {};
|
||||
const name = preamble.name ?? getBasename(path).split(".prompt")[0];
|
||||
const description = preamble.description ?? name;
|
||||
const version = preamble.version ?? 2;
|
||||
|
||||
let systemMessage: string | undefined = undefined;
|
||||
if (prompt.includes("<system>")) {
|
||||
|
|
@ -141,7 +152,7 @@ function parsePromptFile(path: string, content: string) {
|
|||
prompt = prompt.split("</system>")[1].trim();
|
||||
}
|
||||
|
||||
return { name, description, systemMessage, prompt };
|
||||
return { name, description, systemMessage, prompt, version };
|
||||
}
|
||||
|
||||
function extractUserInput(input: string, commandName: string): string {
|
||||
|
|
@ -151,7 +162,11 @@ function extractUserInput(input: string, commandName: string): string {
|
|||
return input;
|
||||
}
|
||||
|
||||
async function renderPrompt(prompt: string, context: ContinueSDK, userInput: string) {
|
||||
async function renderPrompt(
|
||||
prompt: string,
|
||||
context: ContinueSDK,
|
||||
userInput: string,
|
||||
) {
|
||||
const helpers = getContextProviderHelpers(context);
|
||||
|
||||
// A few context providers that don't need to be in config.json to work in .prompt files
|
||||
|
|
|
|||
|
|
@ -34,6 +34,18 @@ export function validateConfig(config: SerializedContinueConfig) {
|
|||
message: `Model at index ${index} has an invalid 'provider'.`,
|
||||
});
|
||||
}
|
||||
|
||||
if (model.contextLength && model.completionOptions?.maxTokens) {
|
||||
const difference =
|
||||
model.contextLength - model.completionOptions.maxTokens;
|
||||
|
||||
if (difference < 1000) {
|
||||
errors.push({
|
||||
fatal: false,
|
||||
message: `Model "${model.title}" has a contextLength of ${model.contextLength} and a maxTokens of ${model.completionOptions.maxTokens}. This leaves only ${difference} tokens for input context and will likely result in your inputs being truncated.`,
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -92,7 +92,7 @@ class DocsContextProvider extends BaseContextProvider {
|
|||
await docsService.isJetBrainsAndPreIndexedDocsProvider();
|
||||
|
||||
if (isJetBrainsAndPreIndexedDocsProvider) {
|
||||
await extras.ide.showToast(
|
||||
void extras.ide.showToast(
|
||||
"error",
|
||||
`${DocsService.preIndexedDocsEmbeddingsProvider.id} is configured as ` +
|
||||
"the embeddings provider, but it cannot be used with JetBrains. " +
|
||||
|
|
|
|||
82
core/core.ts
82
core/core.ts
|
|
@ -83,7 +83,7 @@ export class Core {
|
|||
constructor(
|
||||
private readonly messenger: IMessenger<ToCoreProtocol, FromCoreProtocol>,
|
||||
private readonly ide: IDE,
|
||||
private readonly onWrite: (text: string) => Promise<void> = async () => { },
|
||||
private readonly onWrite: (text: string) => Promise<void> = async () => {},
|
||||
) {
|
||||
// Ensure .continue directory is created
|
||||
setupInitialDotContinueDirectory();
|
||||
|
|
@ -149,7 +149,7 @@ export class Core {
|
|||
void this.ide.getWorkspaceDirs().then(async (dirs) => {
|
||||
// Respect pauseCodebaseIndexOnStart user settings
|
||||
if (ideSettings.pauseCodebaseIndexOnStart) {
|
||||
await this.messenger.request("indexProgress", {
|
||||
void this.messenger.request("indexProgress", {
|
||||
progress: 1,
|
||||
desc: "Initial Indexing Skipped",
|
||||
status: "paused",
|
||||
|
|
@ -174,7 +174,7 @@ export class Core {
|
|||
this.configHandler,
|
||||
ide,
|
||||
getLlm,
|
||||
(e) => { },
|
||||
(e) => {},
|
||||
(..._) => Promise.resolve([]),
|
||||
);
|
||||
|
||||
|
|
@ -684,9 +684,14 @@ export class Core {
|
|||
await codebaseIndexer.clearIndexes();
|
||||
}
|
||||
|
||||
const dirs = data?.dirs ?? await this.ide.getWorkspaceDirs();
|
||||
const dirs = data?.dirs ?? (await this.ide.getWorkspaceDirs());
|
||||
await this.refreshCodebaseIndex(dirs);
|
||||
});
|
||||
on("index/forceReIndexFiles", async ({ data }) => {
|
||||
if (data?.files?.length) {
|
||||
await this.refreshCodebaseIndexFiles(data.files);
|
||||
}
|
||||
});
|
||||
on("index/setPaused", (msg) => {
|
||||
new GlobalContext().update("indexingPaused", msg.data);
|
||||
this.indexingPauseToken.paused = msg.data;
|
||||
|
|
@ -722,14 +727,29 @@ export class Core {
|
|||
}
|
||||
|
||||
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(dirs: string[]) {
|
||||
private async refreshCodebaseIndex(paths: string[]) {
|
||||
if (this.indexingCancellationController) {
|
||||
this.indexingCancellationController.abort();
|
||||
}
|
||||
this.indexingCancellationController = new AbortController();
|
||||
for await (const update of (await this.codebaseIndexerPromise).refresh(
|
||||
dirs,
|
||||
for await (const update of (await this.codebaseIndexerPromise).refreshDirs(
|
||||
paths,
|
||||
this.indexingCancellationController.signal,
|
||||
)) {
|
||||
let updateToSend = { ...update };
|
||||
|
|
@ -743,19 +763,41 @@ export class Core {
|
|||
this.indexingState = updateToSend;
|
||||
|
||||
if (update.status === "failed") {
|
||||
console.debug(
|
||||
"Indexing failed with error: ",
|
||||
update.desc,
|
||||
update.debugInfo,
|
||||
);
|
||||
void Telemetry.capture(
|
||||
"indexing_error",
|
||||
{
|
||||
error: update.desc,
|
||||
stack: update.debugInfo,
|
||||
},
|
||||
false,
|
||||
);
|
||||
void this.sendIndexingErrorTelemetry(update);
|
||||
}
|
||||
}
|
||||
|
||||
this.messenger.send("refreshSubmenuItems", undefined);
|
||||
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 console.debug(
|
||||
"Codebase indexing already in progress, skipping indexing of files\n" +
|
||||
files.join("\n"),
|
||||
);
|
||||
}
|
||||
this.indexingCancellationController = new AbortController();
|
||||
for await (const update of (await this.codebaseIndexerPromise).refreshFiles(
|
||||
files,
|
||||
)) {
|
||||
let updateToSend = { ...update };
|
||||
if (update.status === "failed") {
|
||||
updateToSend.status = "done";
|
||||
updateToSend.desc = "Indexing complete";
|
||||
updateToSend.progress = 1.0;
|
||||
}
|
||||
|
||||
void this.messenger.request("indexProgress", updateToSend);
|
||||
this.indexingState = updateToSend;
|
||||
|
||||
if (update.status === "failed") {
|
||||
void this.sendIndexingErrorTelemetry(update);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
26
core/index.d.ts
vendored
26
core/index.d.ts
vendored
|
|
@ -45,12 +45,12 @@ export interface IndexingProgressUpdate {
|
|||
debugInfo?: string;
|
||||
}
|
||||
|
||||
export type PromptTemplate =
|
||||
| string
|
||||
| ((
|
||||
history: ChatMessage[],
|
||||
otherData: Record<string, string>,
|
||||
) => string | ChatMessage[]);
|
||||
export type PromptTemplateFunction = (
|
||||
history: ChatMessage[],
|
||||
otherData: Record<string, string>,
|
||||
) => string | ChatMessage[];
|
||||
|
||||
export type PromptTemplate = string | PromptTemplateFunction;
|
||||
|
||||
export interface ILLM extends LLMOptions {
|
||||
get providerName(): ModelProvider;
|
||||
|
|
@ -200,11 +200,16 @@ export interface IContextProvider {
|
|||
loadSubmenuItems(args: LoadSubmenuItemsArgs): Promise<ContextSubmenuItem[]>;
|
||||
}
|
||||
|
||||
export interface Checkpoint {
|
||||
[filepath: string]: string;
|
||||
}
|
||||
|
||||
export interface PersistedSessionInfo {
|
||||
history: ChatHistory;
|
||||
title: string;
|
||||
workspaceDirectory: string;
|
||||
sessionId: string;
|
||||
checkpoints?: Checkpoint[];
|
||||
}
|
||||
|
||||
export interface SessionInfo {
|
||||
|
|
@ -654,7 +659,8 @@ type ModelProvider =
|
|||
| "askSage"
|
||||
| "vertexai"
|
||||
| "nebius"
|
||||
| "xAI";
|
||||
| "xAI"
|
||||
| "moonshot";
|
||||
|
||||
export type ModelName =
|
||||
| "AUTODETECT"
|
||||
|
|
@ -749,7 +755,11 @@ export type ModelName =
|
|||
| "starcoder-1b"
|
||||
| "starcoder-3b"
|
||||
| "starcoder2-3b"
|
||||
| "stable-code-3b";
|
||||
| "stable-code-3b"
|
||||
// Moonshot
|
||||
| "moonshot-v1-8k"
|
||||
| "moonshot-v1-32k"
|
||||
| "moonshot-v1-128k";
|
||||
|
||||
export interface RequestOptions {
|
||||
timeout?: number;
|
||||
|
|
|
|||
|
|
@ -3,12 +3,17 @@ import Parser from "web-tree-sitter";
|
|||
import { getBasename, getLastNPathParts } from "../util/";
|
||||
import { migrate } from "../util/paths";
|
||||
import {
|
||||
TSQueryType,
|
||||
getFullLanguageName,
|
||||
getParserForFile,
|
||||
getQueryForFile,
|
||||
} from "../util/treeSitter";
|
||||
|
||||
import { DatabaseConnection, SqliteDb, tagToString, truncateSqliteLikePattern } from "./refreshIndex";
|
||||
import {
|
||||
DatabaseConnection,
|
||||
SqliteDb,
|
||||
tagToString,
|
||||
truncateSqliteLikePattern,
|
||||
} from "./refreshIndex";
|
||||
import {
|
||||
IndexResultType,
|
||||
MarkCompleteCallback,
|
||||
|
|
@ -31,7 +36,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
relativeExpectedTime: number = 1;
|
||||
artifactId = "codeSnippets";
|
||||
|
||||
constructor(private readonly ide: IDE) { }
|
||||
constructor(private readonly ide: IDE) {}
|
||||
|
||||
private static async _createTables(db: DatabaseConnection) {
|
||||
await db.exec(`CREATE TABLE IF NOT EXISTS code_snippets (
|
||||
|
|
@ -183,7 +188,12 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
}
|
||||
|
||||
const ast = parser.parse(contents);
|
||||
const query = await getQueryForFile(filepath, TSQueryType.CodeSnippets);
|
||||
|
||||
const language = getFullLanguageName(filepath);
|
||||
const query = await getQueryForFile(
|
||||
filepath,
|
||||
`code-snippet-queries/${language}.scm`,
|
||||
);
|
||||
const matches = query?.matches(ast.rootNode);
|
||||
|
||||
if (!matches) {
|
||||
|
|
@ -386,7 +396,9 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
|
|||
const db = await SqliteDb.get();
|
||||
await CodeSnippetsCodebaseIndex._createTables(db);
|
||||
|
||||
const likePatterns = workspaceDirs.map((dir) => truncateSqliteLikePattern(`${dir}%`));
|
||||
const likePatterns = workspaceDirs.map((dir) =>
|
||||
truncateSqliteLikePattern(`${dir}%`),
|
||||
);
|
||||
const placeholders = likePatterns.map(() => "?").join(" OR path LIKE ");
|
||||
|
||||
const query = `
|
||||
|
|
|
|||
|
|
@ -89,7 +89,7 @@ describe("CodebaseIndexer", () => {
|
|||
const abortSignal = abortController.signal;
|
||||
|
||||
const updates = [];
|
||||
for await (const update of codebaseIndexer.refresh(
|
||||
for await (const update of codebaseIndexer.refreshDirs(
|
||||
[TEST_DIR],
|
||||
abortSignal,
|
||||
)) {
|
||||
|
|
@ -98,6 +98,16 @@ describe("CodebaseIndexer", () => {
|
|||
return updates;
|
||||
}
|
||||
|
||||
async function refreshIndexFiles(files: string[]) {
|
||||
const updates = [];
|
||||
for await (const update of codebaseIndexer.refreshFiles(
|
||||
files,
|
||||
)) {
|
||||
updates.push(update);
|
||||
}
|
||||
return updates;
|
||||
}
|
||||
|
||||
async function getAllIndexedFiles() {
|
||||
const files = await testIndex.getIndexedFilesForTags(
|
||||
await testIde.getTags(testIndex.artifactId),
|
||||
|
|
@ -158,6 +168,15 @@ describe("CodebaseIndexer", () => {
|
|||
expect(indexed.some((file) => file.endsWith("main.py"))).toBe(true);
|
||||
});
|
||||
|
||||
test("should successfuly re-index specific files", async () => {
|
||||
// Could add more specific tests for this but uses similar logic
|
||||
const before = await getAllIndexedFiles();
|
||||
await refreshIndexFiles(before);
|
||||
|
||||
const after = await getAllIndexedFiles();
|
||||
expect(after.length).toBe(before.length);
|
||||
});
|
||||
|
||||
test("should successfully re-index after adding a file", async () => {
|
||||
addToTestDir([["main.rs", TEST_RS]]);
|
||||
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ import {
|
|||
RefreshIndexResults,
|
||||
} from "./types.js";
|
||||
import { walkDirAsync } from "./walkDir.js";
|
||||
import { getBasename } from "../util/index.js";
|
||||
|
||||
export class PauseToken {
|
||||
constructor(private _paused: boolean) {}
|
||||
|
|
@ -144,13 +145,52 @@ export class CodebaseIndexer {
|
|||
}
|
||||
}
|
||||
|
||||
async *refresh(
|
||||
workspaceDirs: string[],
|
||||
async *refreshFiles(
|
||||
files: string[],
|
||||
): AsyncGenerator<IndexingProgressUpdate> {
|
||||
let progress = 0;
|
||||
if (files.length === 0) {
|
||||
yield {
|
||||
progress: 1,
|
||||
desc: "Indexing Complete",
|
||||
status: "done",
|
||||
};
|
||||
}
|
||||
|
||||
const progressPer = 1 / files.length;
|
||||
try {
|
||||
for (const file of files) {
|
||||
yield {
|
||||
progress,
|
||||
desc: `Indexing file ${file}...`,
|
||||
status: "indexing",
|
||||
};
|
||||
await this.refreshFile(file);
|
||||
|
||||
progress += progressPer;
|
||||
|
||||
if (this.pauseToken.paused) {
|
||||
yield* this.yieldUpdateAndPause();
|
||||
}
|
||||
}
|
||||
|
||||
yield {
|
||||
progress: 1,
|
||||
desc: "Indexing Complete",
|
||||
status: "done",
|
||||
};
|
||||
} catch (err) {
|
||||
yield this.handleErrorAndGetProgressUpdate(err);
|
||||
}
|
||||
}
|
||||
|
||||
async *refreshDirs(
|
||||
dirs: string[],
|
||||
abortSignal: AbortSignal,
|
||||
): AsyncGenerator<IndexingProgressUpdate> {
|
||||
let progress = 0;
|
||||
|
||||
if (workspaceDirs.length === 0) {
|
||||
if (dirs.length === 0) {
|
||||
yield {
|
||||
progress,
|
||||
desc: "Nothing to index",
|
||||
|
|
@ -175,11 +215,9 @@ export class CodebaseIndexer {
|
|||
};
|
||||
}
|
||||
|
||||
let completedDirs = 0;
|
||||
|
||||
// Wait until Git Extension has loaded to report progress
|
||||
// so we don't appear stuck at 0% while waiting
|
||||
await this.ide.getRepoName(workspaceDirs[0]);
|
||||
await this.ide.getRepoName(dirs[0]);
|
||||
|
||||
yield {
|
||||
progress,
|
||||
|
|
@ -188,16 +226,16 @@ export class CodebaseIndexer {
|
|||
};
|
||||
const beginTime = Date.now();
|
||||
|
||||
for (const directory of workspaceDirs) {
|
||||
for (const directory of dirs) {
|
||||
const dirBasename = await this.basename(directory);
|
||||
yield {
|
||||
progress,
|
||||
desc: `Discovering files in ${dirBasename}...`,
|
||||
status: "indexing",
|
||||
};
|
||||
const workspaceFiles = [];
|
||||
const directoryFiles = [];
|
||||
for await (const p of walkDirAsync(directory, this.ide)) {
|
||||
workspaceFiles.push(p);
|
||||
directoryFiles.push(p);
|
||||
if (abortSignal.aborted) {
|
||||
yield {
|
||||
progress: 1,
|
||||
|
|
@ -218,7 +256,7 @@ export class CodebaseIndexer {
|
|||
try {
|
||||
for await (const updateDesc of this.indexFiles(
|
||||
directory,
|
||||
workspaceFiles,
|
||||
directoryFiles,
|
||||
branch,
|
||||
repoName,
|
||||
)) {
|
||||
|
|
@ -240,7 +278,7 @@ export class CodebaseIndexer {
|
|||
nextLogThreshold += 0.025;
|
||||
this.logProgress(
|
||||
beginTime,
|
||||
Math.floor(workspaceFiles.length * updateDesc.progress),
|
||||
Math.floor(directoryFiles.length * updateDesc.progress),
|
||||
updateDesc.progress,
|
||||
);
|
||||
}
|
||||
|
|
@ -347,18 +385,18 @@ export class CodebaseIndexer {
|
|||
}
|
||||
|
||||
private async *indexFiles(
|
||||
workspaceDir: string,
|
||||
workspaceFiles: string[],
|
||||
directory: string,
|
||||
files: string[],
|
||||
branch: string,
|
||||
repoName: string | undefined,
|
||||
): AsyncGenerator<IndexingProgressUpdate> {
|
||||
const stats = await this.ide.getLastModified(workspaceFiles);
|
||||
const stats = await this.ide.getLastModified(files);
|
||||
const indexesToBuild = await this.getIndexesToBuild();
|
||||
let completedIndexCount = 0;
|
||||
let progress = 0;
|
||||
for (const codebaseIndex of indexesToBuild) {
|
||||
const tag: IndexTag = {
|
||||
directory: workspaceDir,
|
||||
directory,
|
||||
branch,
|
||||
artifactId: codebaseIndex.artifactId,
|
||||
};
|
||||
|
|
|
|||
|
|
@ -79,7 +79,7 @@ class DocsCrawler {
|
|||
);
|
||||
|
||||
if (didInstall) {
|
||||
await this.ide.showToast(
|
||||
void this.ide.showToast(
|
||||
"info",
|
||||
`Successfully installed Chromium! Retrying crawl of: ${startUrl.toString()}`,
|
||||
);
|
||||
|
|
|
|||
|
|
@ -157,7 +157,7 @@ export default class DocsService {
|
|||
params: {},
|
||||
});
|
||||
|
||||
await this.ide.showToast(
|
||||
void this.ide.showToast(
|
||||
"info",
|
||||
"Successfuly added docs context provider",
|
||||
);
|
||||
|
|
@ -183,7 +183,7 @@ export default class DocsService {
|
|||
while (!(await generator.next()).done) {}
|
||||
}
|
||||
|
||||
await this.ide.showToast("info", "Docs indexing completed");
|
||||
void this.ide.showToast("info", "Docs indexing completed");
|
||||
}
|
||||
|
||||
async list() {
|
||||
|
|
@ -254,6 +254,8 @@ export default class DocsService {
|
|||
if (processedPages === maxKnownPages) {
|
||||
maxKnownPages *= 2;
|
||||
}
|
||||
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
|
||||
void Telemetry.capture("docs_pages_crawled", {
|
||||
|
|
@ -362,11 +364,16 @@ export default class DocsService {
|
|||
isPreIndexedDoc: !!preIndexedDocs[startUrl],
|
||||
});
|
||||
|
||||
const docs: LanceDbDocsRow[] = await table
|
||||
.search(vector)
|
||||
.limit(nRetrieve)
|
||||
.where(`starturl = '${startUrl}'`)
|
||||
.execute();
|
||||
let docs: LanceDbDocsRow[] = [];
|
||||
try {
|
||||
docs = await table
|
||||
.search(vector)
|
||||
.limit(nRetrieve)
|
||||
.where(`starturl = '${startUrl}'`)
|
||||
.execute();
|
||||
} catch (e: any) {
|
||||
console.error("Error retrieving chunks from LanceDB", e);
|
||||
}
|
||||
|
||||
const hasIndexedDoc = await this.hasIndexedDoc(startUrl);
|
||||
|
||||
|
|
@ -553,9 +560,8 @@ export default class DocsService {
|
|||
private async getLanceTableNameFromEmbeddingsProvider(
|
||||
isPreIndexedDoc: boolean,
|
||||
) {
|
||||
const embeddingsProvider = await this.getEmbeddingsProvider(
|
||||
isPreIndexedDoc,
|
||||
);
|
||||
const embeddingsProvider =
|
||||
await this.getEmbeddingsProvider(isPreIndexedDoc);
|
||||
|
||||
const tableName = this.sanitizeLanceTableName(
|
||||
`${DocsService.lanceTableName}${embeddingsProvider.id}`,
|
||||
|
|
@ -737,7 +743,7 @@ export default class DocsService {
|
|||
|
||||
if (isJetBrainsAndPreIndexedDocsProvider) {
|
||||
// A bit noisy for teams users whom have no choice if their admin is the one who didn't setup an embeddingsProvider
|
||||
// this.ide.showToast(
|
||||
// void this.ide.showToast(
|
||||
// "error",
|
||||
// "The 'transformers.js' embeddings provider currently cannot be used to index " +
|
||||
// "documentation in JetBrains. To enable documentation indexing, you can use " +
|
||||
|
|
|
|||
|
|
@ -242,7 +242,7 @@ export class ChromiumInstaller {
|
|||
|
||||
ChromiumCrawler.setUseChromiumForDocsCrawling(false);
|
||||
|
||||
await this.ide.showToast("error", "Failed to install Chromium");
|
||||
void this.ide.showToast("error", "Failed to install Chromium");
|
||||
|
||||
return false;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -325,6 +325,11 @@ const preIndexedDocs: Record<
|
|||
rootUrl: "https://awscli.amazonaws.com/v2/documentation/api/latest/",
|
||||
faviconUrl: "https://docs.aws.amazon.com/favicon.ico",
|
||||
},
|
||||
"https://llama-stack.readthedocs.io/": {
|
||||
title: "Llama Stack",
|
||||
startUrl: "https://llama-stack.readthedocs.io/",
|
||||
rootUrl: "https://llama-stack.readthedocs.io/",
|
||||
},
|
||||
};
|
||||
|
||||
export default preIndexedDocs;
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ const PROVIDER_HANDLES_TEMPLATING: ModelProvider[] = [
|
|||
"mistral",
|
||||
"sambanova",
|
||||
"vertexai",
|
||||
"watsonx"
|
||||
"watsonx",
|
||||
];
|
||||
|
||||
const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
|
||||
|
|
@ -63,7 +63,8 @@ const PROVIDER_SUPPORTS_IMAGES: ModelProvider[] = [
|
|||
"sagemaker",
|
||||
"continue-proxy",
|
||||
"openrouter",
|
||||
"vertexai"
|
||||
"vertexai",
|
||||
"azure",
|
||||
];
|
||||
|
||||
const MODEL_SUPPORTS_IMAGES: string[] = [
|
||||
|
|
@ -116,12 +117,13 @@ const PARALLEL_PROVIDERS: ModelProvider[] = [
|
|||
"huggingface-inference-api",
|
||||
"huggingface-tgi",
|
||||
"mistral",
|
||||
"moonshot",
|
||||
"free-trial",
|
||||
"replicate",
|
||||
"together",
|
||||
"sambanova",
|
||||
"nebius",
|
||||
"vertexai"
|
||||
"vertexai",
|
||||
];
|
||||
|
||||
function llmCanGenerateInParallel(
|
||||
|
|
@ -148,9 +150,10 @@ function autodetectTemplateType(model: string): TemplateType | undefined {
|
|||
lower.includes("chat-bison") ||
|
||||
lower.includes("pplx") ||
|
||||
lower.includes("gemini") ||
|
||||
lower.includes("grok")
|
||||
lower.includes("grok")||
|
||||
lower.includes("moonshot")
|
||||
) {
|
||||
return undefined;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (lower.includes("llama3")) {
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
const DEFAULT_MAX_TOKENS = 2048;
|
||||
const DEFAULT_MAX_TOKENS = 4096;
|
||||
const DEFAULT_CONTEXT_LENGTH = 8096;
|
||||
const DEFAULT_TEMPERATURE = 0.5;
|
||||
|
||||
|
|
@ -7,7 +7,7 @@ const DEFAULT_ARGS = {
|
|||
temperature: DEFAULT_TEMPERATURE,
|
||||
};
|
||||
|
||||
const GPT_4_CTX_LEN = 4096;
|
||||
const GPT_4_CTX_LEN = 128_000;
|
||||
|
||||
const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = {
|
||||
"gpt-3.5-turbo": 4096,
|
||||
|
|
@ -16,9 +16,9 @@ const CONTEXT_LENGTH_FOR_MODEL: { [name: string]: number } = {
|
|||
"gpt-35-turbo-16k": 16_384,
|
||||
"gpt-35-turbo-0613": 4096,
|
||||
"gpt-35-turbo": 4096,
|
||||
"gpt-4": GPT_4_CTX_LEN,
|
||||
"gpt-4-32k": GPT_4_CTX_LEN,
|
||||
"gpt-4-turbo-preview": GPT_4_CTX_LEN,
|
||||
"gpt-4": 4096,
|
||||
"gpt-4-32k": 32_000,
|
||||
"gpt-4-turbo-preview": 32_000,
|
||||
"gpt-4o": GPT_4_CTX_LEN,
|
||||
"gpt-4o-mini": GPT_4_CTX_LEN,
|
||||
"gpt-4-vision": GPT_4_CTX_LEN,
|
||||
|
|
|
|||
|
|
@ -323,6 +323,27 @@ function pruneChatHistory(
|
|||
return chatHistory;
|
||||
}
|
||||
|
||||
function messageIsEmpty(message: ChatMessage): boolean {
|
||||
if (typeof message.content === "string") {
|
||||
return message.content.trim() === "";
|
||||
}
|
||||
if (Array.isArray(message.content)) {
|
||||
return message.content.every(
|
||||
(item) => !item.imageUrl && item.text?.trim() === "",
|
||||
);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function addSpaceToAnyEmptyMessages(messages: ChatMessage[]): ChatMessage[] {
|
||||
return messages.map((message) => {
|
||||
if (messageIsEmpty(message)) {
|
||||
message.content = " ";
|
||||
}
|
||||
return message;
|
||||
});
|
||||
}
|
||||
|
||||
function compileChatMessages(
|
||||
modelName: string,
|
||||
msgs: ChatMessage[] | undefined,
|
||||
|
|
@ -333,12 +354,14 @@ function compileChatMessages(
|
|||
functions: any[] | undefined = undefined,
|
||||
systemMessage: string | undefined = undefined,
|
||||
): ChatMessage[] {
|
||||
const msgsCopy = msgs
|
||||
let msgsCopy = msgs
|
||||
? msgs
|
||||
.map((msg) => ({ ...msg }))
|
||||
.filter((msg) => msg.content !== "" && msg.role !== "system")
|
||||
: [];
|
||||
|
||||
msgsCopy = addSpaceToAnyEmptyMessages(msgsCopy);
|
||||
|
||||
if (prompt) {
|
||||
const promptMsg: ChatMessage = {
|
||||
role: "user",
|
||||
|
|
|
|||
59
core/llm/llms/Moonshot.ts
Normal file
59
core/llm/llms/Moonshot.ts
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
import { CompletionOptions, LLMOptions, ModelProvider } from "../../index.js";
|
||||
import { streamSse } from "../stream.js";
|
||||
import { osModelsEditPrompt } from "../templates/edit.js";
|
||||
|
||||
import OpenAI from "./OpenAI.js";
|
||||
|
||||
class Moonshot extends OpenAI {
|
||||
static providerName: ModelProvider = "moonshot";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
apiBase: "https://api.moonshot.cn/v1/",
|
||||
model: "moonshot-v1-8k",
|
||||
promptTemplates: {
|
||||
edit: osModelsEditPrompt,
|
||||
},
|
||||
useLegacyCompletionsEndpoint: false,
|
||||
};
|
||||
maxStopWords: number | undefined = 16;
|
||||
|
||||
supportsFim(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
async *_streamFim(
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
options: CompletionOptions,
|
||||
): AsyncGenerator<string> {
|
||||
const endpoint = new URL("v1/chat/completions", this.apiBase);
|
||||
const resp = await this.fetch(endpoint, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
model: options.model,
|
||||
messages: [
|
||||
{
|
||||
role: "user",
|
||||
content: prefix + "[fill]" + suffix,
|
||||
},
|
||||
],
|
||||
max_tokens: options.maxTokens,
|
||||
temperature: options.temperature,
|
||||
top_p: options.topP,
|
||||
frequency_penalty: options.frequencyPenalty,
|
||||
presence_penalty: options.presencePenalty,
|
||||
stop: options.stop,
|
||||
stream: true,
|
||||
}),
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
Authorization: `Bearer ${this.apiKey}`,
|
||||
},
|
||||
});
|
||||
for await (const chunk of streamSse(resp)) {
|
||||
yield chunk.choices[0].delta.content;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default Moonshot;
|
||||
|
|
@ -31,6 +31,7 @@ import Llamafile from "./Llamafile";
|
|||
import LMStudio from "./LMStudio";
|
||||
import Mistral from "./Mistral";
|
||||
import Mock from "./Mock";
|
||||
import Moonshot from "./Moonshot";
|
||||
import Msty from "./Msty";
|
||||
import Nebius from "./Nebius";
|
||||
import Nvidia from "./Nvidia";
|
||||
|
|
@ -54,6 +55,7 @@ const LLMs = [
|
|||
FreeTrial,
|
||||
Gemini,
|
||||
Llamafile,
|
||||
Moonshot,
|
||||
Ollama,
|
||||
Replicate,
|
||||
TextGenWebUI,
|
||||
|
|
|
|||
|
|
@ -13,13 +13,14 @@ class ContinueProxy extends OpenAI {
|
|||
static providerName: ModelProvider = "continue-proxy";
|
||||
static defaultOptions: Partial<LLMOptions> = {
|
||||
useLegacyCompletionsEndpoint: false,
|
||||
requestOptions: {
|
||||
headers: {
|
||||
"x-continue-unique-id": Telemetry.uniqueId,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
protected _getHeaders() {
|
||||
const headers: any = super._getHeaders();
|
||||
headers["x-continue-unique-id"] = Telemetry.uniqueId;
|
||||
return headers;
|
||||
}
|
||||
|
||||
supportsCompletions(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
import { ChatMessage, PromptTemplate } from "../../index.js";
|
||||
import { gptEditPrompt } from "./edit/gpt.js";
|
||||
|
||||
const simplifiedEditPrompt = `Consider the following code:
|
||||
\`\`\`{{{language}}}
|
||||
|
|
@ -18,49 +19,6 @@ Here is the edit requested:
|
|||
|
||||
Here is the code after editing:`;
|
||||
|
||||
const gptEditPrompt: PromptTemplate = (_, otherData) => {
|
||||
if (otherData?.codeToEdit?.trim().length === 0) {
|
||||
return `\
|
||||
\`\`\`${otherData.language}
|
||||
${otherData.prefix}[BLANK]${otherData.codeToEdit}${otherData.suffix}
|
||||
\`\`\`
|
||||
|
||||
Above is the file of code that the user is currently editing in. Their cursor is located at the "[BLANK]". They have requested that you fill in the "[BLANK]" with code that satisfies the following request:
|
||||
|
||||
"${otherData.userInput}"
|
||||
|
||||
Please generate this code. Your output will be only the code that should replace the "[BLANK]", without repeating any of the prefix or suffix, without any natural language explanation, and without messing up indentation. Here is the code that will replace the "[BLANK]":`;
|
||||
}
|
||||
|
||||
const paragraphs = [
|
||||
"The user has requested a section of code in a file to be rewritten.",
|
||||
];
|
||||
if (otherData.prefix?.trim().length > 0) {
|
||||
paragraphs.push(`This is the prefix of the file:
|
||||
\`\`\`${otherData.language}
|
||||
${otherData.prefix}
|
||||
\`\`\``);
|
||||
}
|
||||
|
||||
if (otherData.suffix?.trim().length > 0) {
|
||||
paragraphs.push(`This is the suffix of the file:
|
||||
\`\`\`${otherData.language}
|
||||
${otherData.suffix}
|
||||
\`\`\``);
|
||||
}
|
||||
|
||||
paragraphs.push(`This is the code to rewrite:
|
||||
\`\`\`${otherData.language}
|
||||
${otherData.codeToEdit}
|
||||
\`\`\`
|
||||
|
||||
The user's request is: "${otherData.userInput}"
|
||||
|
||||
Here is the rewritten code:`);
|
||||
|
||||
return paragraphs.join("\n\n");
|
||||
};
|
||||
|
||||
const codellamaInfillEditPrompt = "{{filePrefix}}<FILL>{{fileSuffix}}";
|
||||
|
||||
const START_TAG = "<START EDITING HERE>";
|
||||
|
|
@ -76,7 +34,7 @@ const osModelsEditPrompt: PromptTemplate = (history, otherData) => {
|
|||
!firstCharOfFirstLine;
|
||||
const suffixTag = isSuffix ? "<STOP EDITING HERE>" : "";
|
||||
const suffixExplanation = isSuffix
|
||||
? " When you get to \"<STOP EDITING HERE>\", end your response."
|
||||
? ' When you get to "<STOP EDITING HERE>", end your response.'
|
||||
: "";
|
||||
|
||||
// If neither prefilling nor /v1/completions are supported, we have to use a chat prompt without putting words in the model's mouth
|
||||
|
|
|
|||
44
core/llm/templates/edit/claude.ts
Normal file
44
core/llm/templates/edit/claude.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { PromptTemplateFunction } from "../../..";
|
||||
|
||||
export const claudeEditPrompt: PromptTemplateFunction = (_, otherData) => {
|
||||
if (otherData?.codeToEdit?.trim().length === 0) {
|
||||
return `\
|
||||
\`\`\`${otherData.language}
|
||||
${otherData.prefix}[BLANK]${otherData.codeToEdit}${otherData.suffix}
|
||||
\`\`\`
|
||||
|
||||
Above is the file of code that the user is currently editing in. Their cursor is located at the "[BLANK]". They have requested that you fill in the "[BLANK]" with code that satisfies the following request:
|
||||
|
||||
"${otherData.userInput}"
|
||||
|
||||
Please generate this code. Your output will be only the code that should replace the "[BLANK]", without repeating any of the prefix or suffix, without any natural language explanation, and without messing up indentation. Here is the code that will replace the "[BLANK]":`;
|
||||
}
|
||||
|
||||
const paragraphs = [
|
||||
"The user has requested a section of code in a file to be rewritten.",
|
||||
];
|
||||
if (otherData.prefix?.trim().length > 0) {
|
||||
paragraphs.push(`This is the prefix of the file:
|
||||
\`\`\`${otherData.language}
|
||||
${otherData.prefix}
|
||||
\`\`\``);
|
||||
}
|
||||
|
||||
if (otherData.suffix?.trim().length > 0) {
|
||||
paragraphs.push(`This is the suffix of the file:
|
||||
\`\`\`${otherData.language}
|
||||
${otherData.suffix}
|
||||
\`\`\``);
|
||||
}
|
||||
|
||||
paragraphs.push(`This is the code to rewrite:
|
||||
\`\`\`${otherData.language}
|
||||
${otherData.codeToEdit}
|
||||
\`\`\`
|
||||
|
||||
The user's request is: "${otherData.userInput}"
|
||||
|
||||
Here is the rewritten code:`);
|
||||
|
||||
return paragraphs.join("\n\n");
|
||||
};
|
||||
71
core/llm/templates/edit/gpt.ts
Normal file
71
core/llm/templates/edit/gpt.ts
Normal file
|
|
@ -0,0 +1,71 @@
|
|||
import { PromptTemplateFunction } from "../../..";
|
||||
import { dedent } from "../../../util";
|
||||
|
||||
const gptInsertionEditPrompt: PromptTemplateFunction = (_, otherData) => {
|
||||
return dedent`
|
||||
\`\`\`${otherData.language}
|
||||
${otherData.prefix}[BLANK]${otherData.codeToEdit}${otherData.suffix}
|
||||
\`\`\`
|
||||
|
||||
Above is the file of code that the user is currently editing in. Their cursor is located at the "[BLANK]". They have requested that you fill in the "[BLANK]" with code that satisfies the following request:
|
||||
|
||||
"${otherData.userInput}"
|
||||
|
||||
Please generate this code. Your output will be only the code that should replace the "[BLANK]", without repeating any of the prefix or suffix, without any natural language explanation, and without messing up indentation. Here is the code that will replace the "[BLANK]":`;
|
||||
};
|
||||
|
||||
const gptFullFileEditPrompt: PromptTemplateFunction = (_, otherData) => {
|
||||
return dedent`
|
||||
\`\`\`${otherData.language}
|
||||
${otherData.codeToEdit}
|
||||
\`\`\`
|
||||
|
||||
Please rewrite the above file to address the following request:
|
||||
|
||||
${otherData.userInput}
|
||||
|
||||
You should rewrite the entire file without any natural language explanation. DO NOT surround the code in a code block and DO NOT explain yourself.`;
|
||||
};
|
||||
|
||||
export const gptEditPrompt: PromptTemplateFunction = (history, otherData) => {
|
||||
if (otherData?.codeToEdit?.trim().length === 0) {
|
||||
return gptInsertionEditPrompt(history, otherData);
|
||||
} else if (
|
||||
otherData?.prefix?.trim().length === 0 &&
|
||||
otherData?.suffix?.trim().length === 0
|
||||
) {
|
||||
return gptFullFileEditPrompt(history, otherData);
|
||||
}
|
||||
|
||||
const paragraphs = [
|
||||
"The user has requested a section of code in a file to be rewritten.",
|
||||
];
|
||||
|
||||
if (otherData.prefix?.trim().length > 0) {
|
||||
paragraphs.push(dedent`
|
||||
This is the prefix of the file:
|
||||
\`\`\`${otherData.language}
|
||||
${otherData.prefix}
|
||||
\`\`\``);
|
||||
}
|
||||
|
||||
if (otherData.suffix?.trim().length > 0) {
|
||||
paragraphs.push(dedent`
|
||||
This is the suffix of the file:
|
||||
\`\`\`${otherData.language}
|
||||
${otherData.suffix}
|
||||
\`\`\``);
|
||||
}
|
||||
|
||||
paragraphs.push(dedent`
|
||||
This is the code to rewrite:
|
||||
\`\`\`${otherData.language}
|
||||
${otherData.codeToEdit}
|
||||
\`\`\`
|
||||
|
||||
The user's request is: "${otherData.userInput}"
|
||||
|
||||
Here is the rewritten code:`);
|
||||
|
||||
return paragraphs.join("\n\n");
|
||||
};
|
||||
95
core/package-lock.json
generated
95
core/package-lock.json
generated
|
|
@ -101,12 +101,12 @@
|
|||
}
|
||||
},
|
||||
"node_modules/@75lb/deep-merge": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.1.tgz",
|
||||
"integrity": "sha512-xvgv6pkMGBA6GwdyJbNAnDmfAIR/DfWhrj9jgWh3TY7gRm3KO46x/GPjRg6wJ0nOepwqrNxFfojebh0Df4h4Tw==",
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/@75lb/deep-merge/-/deep-merge-1.1.2.tgz",
|
||||
"integrity": "sha512-08K9ou5VNbheZFxM5tDWoqjA3ImC50DiuuJ2tj1yEPRfkp8lLLg6XAaJ4On+a0yAXor/8ay5gHnAIshRM44Kpw==",
|
||||
"peer": true,
|
||||
"dependencies": {
|
||||
"lodash.assignwith": "^4.2.0",
|
||||
"lodash": "^4.17.21",
|
||||
"typical": "^7.1.1"
|
||||
},
|
||||
"engines": {
|
||||
|
|
@ -5832,15 +5832,23 @@
|
|||
"node": "*"
|
||||
}
|
||||
},
|
||||
"node_modules/aws-ssl-profiles": {
|
||||
"version": "1.1.2",
|
||||
"resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",
|
||||
"integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==",
|
||||
"engines": {
|
||||
"node": ">= 6.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/aws4": {
|
||||
"version": "1.13.0",
|
||||
"resolved": "https://registry.npmjs.org/aws4/-/aws4-1.13.0.tgz",
|
||||
"integrity": "sha512-3AungXC4I8kKsS9PuS4JH2nc+0bVY/mjgrephHTIi8fpEeGsTHBUJeosp0Wc1myYMElmD0B3Oc4XL/HVJ4PV2g=="
|
||||
},
|
||||
"node_modules/axios": {
|
||||
"version": "1.7.1",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.1.tgz",
|
||||
"integrity": "sha512-+LV37nQcd1EpFalkXksWNBiA17NZ5m5/WspmHGmZmdx1qBOg/VNq/c4eRJiA9VQQHBOs+N0ZhhdU10h2TyNK7Q==",
|
||||
"version": "1.7.7",
|
||||
"resolved": "https://registry.npmjs.org/axios/-/axios-1.7.7.tgz",
|
||||
"integrity": "sha512-S4kL7XrjgBmvdGut0sN3yJxqYzrDOnivkBiN0OFs6hLiUam3UPvswUo0kqGyhqUZGEOytHyumEdXsAkgCOUf3Q==",
|
||||
"dependencies": {
|
||||
"follow-redirects": "^1.15.6",
|
||||
"form-data": "^4.0.0",
|
||||
|
|
@ -7331,27 +7339,27 @@
|
|||
}
|
||||
},
|
||||
"node_modules/engine.io-client": {
|
||||
"version": "6.5.3",
|
||||
"resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.5.3.tgz",
|
||||
"integrity": "sha512-9Z0qLB0NIisTRt1DZ/8U2k12RJn8yls/nXMZLn+/N8hANT3TcYjKFKcwbw5zFQiN4NTde3TSY9zb79e1ij6j9Q==",
|
||||
"version": "6.5.4",
|
||||
"resolved": "https://registry.npmjs.org/engine.io-client/-/engine.io-client-6.5.4.tgz",
|
||||
"integrity": "sha512-GeZeeRjpD2qf49cZQ0Wvh/8NJNfeXkXXcoGh+F77oEAgo9gUHwT1fCRxSNU+YEEaysOJTnsFHmM5oAcPy4ntvQ==",
|
||||
"dependencies": {
|
||||
"@socket.io/component-emitter": "~3.1.0",
|
||||
"debug": "~4.3.1",
|
||||
"engine.io-parser": "~5.2.1",
|
||||
"ws": "~8.11.0",
|
||||
"ws": "~8.17.1",
|
||||
"xmlhttprequest-ssl": "~2.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/engine.io-client/node_modules/ws": {
|
||||
"version": "8.11.0",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.11.0.tgz",
|
||||
"integrity": "sha512-HPG3wQd9sNQoT9xHyNCXoDUa+Xw/VevmY9FoHyQ+g+rrMn4j6FB4np7Z0OhdTgjx6MgQLK7jwSy1YecU1+4Asg==",
|
||||
"version": "8.17.1",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz",
|
||||
"integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bufferutil": "^4.0.1",
|
||||
"utf-8-validate": "^5.0.2"
|
||||
"utf-8-validate": ">=5.0.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bufferutil": {
|
||||
|
|
@ -10868,12 +10876,6 @@
|
|||
"resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz",
|
||||
"integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg=="
|
||||
},
|
||||
"node_modules/lodash.assignwith": {
|
||||
"version": "4.2.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.assignwith/-/lodash.assignwith-4.2.0.tgz",
|
||||
"integrity": "sha512-ZznplvbvtjK2gMvnQ1BR/zqPFZmS6jbK4p+6Up4xcRYA7yMIwxHCfbTcrYxXKzzqLsQ05eJPVznEW3tuwV7k1g==",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/lodash.camelcase": {
|
||||
"version": "4.3.0",
|
||||
"resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz",
|
||||
|
|
@ -10910,6 +10912,20 @@
|
|||
"node": "20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/lru.min": {
|
||||
"version": "1.1.1",
|
||||
"resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.1.tgz",
|
||||
"integrity": "sha512-FbAj6lXil6t8z4z3j0E5mfRlPzxkySotzUHwRXjlpRh10vc6AI6WN62ehZj82VG7M20rqogJ0GLwar2Xa05a8Q==",
|
||||
"engines": {
|
||||
"bun": ">=1.0.0",
|
||||
"deno": ">=1.30.0",
|
||||
"node": ">=8.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/wellwelwel"
|
||||
}
|
||||
},
|
||||
"node_modules/mac-ca": {
|
||||
"version": "3.1.0",
|
||||
"resolved": "https://registry.npmjs.org/mac-ca/-/mac-ca-3.1.0.tgz",
|
||||
|
|
@ -11068,28 +11084,17 @@
|
|||
}
|
||||
},
|
||||
"node_modules/micromatch": {
|
||||
"version": "4.0.6",
|
||||
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.6.tgz",
|
||||
"integrity": "sha512-Y4Ypn3oujJYxJcMacVgcs92wofTHxp9FzfDpQON4msDefoC0lb3ETvQLOdLcbhSwU1bz8HrL/1sygfBIHudrkQ==",
|
||||
"version": "4.0.8",
|
||||
"resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz",
|
||||
"integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==",
|
||||
"dependencies": {
|
||||
"braces": "^3.0.3",
|
||||
"picomatch": "^4.0.2"
|
||||
"picomatch": "^2.3.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=8.6"
|
||||
}
|
||||
},
|
||||
"node_modules/micromatch/node_modules/picomatch": {
|
||||
"version": "4.0.2",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.2.tgz",
|
||||
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/sponsors/jonschlinkert"
|
||||
}
|
||||
},
|
||||
"node_modules/mime-db": {
|
||||
"version": "1.52.0",
|
||||
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
|
||||
|
|
@ -11293,15 +11298,16 @@
|
|||
}
|
||||
},
|
||||
"node_modules/mysql2": {
|
||||
"version": "3.9.7",
|
||||
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.9.7.tgz",
|
||||
"integrity": "sha512-KnJT8vYRcNAZv73uf9zpXqNbvBG7DJrs+1nACsjZP1HMJ1TgXEy8wnNilXAn/5i57JizXKtrUtwDB7HxT9DDpw==",
|
||||
"version": "3.11.4",
|
||||
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.11.4.tgz",
|
||||
"integrity": "sha512-Z2o3tY4Z8EvSRDwknaC40MdZ3+m0sKbpnXrShQLdxPrAvcNli7jLrD2Zd2IzsRMw4eK9Yle500FDmlkIqp+krg==",
|
||||
"dependencies": {
|
||||
"aws-ssl-profiles": "^1.1.1",
|
||||
"denque": "^2.1.0",
|
||||
"generate-function": "^2.3.1",
|
||||
"iconv-lite": "^0.6.3",
|
||||
"long": "^5.2.1",
|
||||
"lru-cache": "^8.0.0",
|
||||
"lru.min": "^1.0.0",
|
||||
"named-placeholders": "^1.1.3",
|
||||
"seq-queue": "^0.0.5",
|
||||
"sqlstring": "^2.3.2"
|
||||
|
|
@ -11310,14 +11316,6 @@
|
|||
"node": ">= 8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/mysql2/node_modules/lru-cache": {
|
||||
"version": "8.0.5",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-8.0.5.tgz",
|
||||
"integrity": "sha512-MhWWlVnuab1RG5/zMRRcVGXZLCXrZTgfwMikgzCegsPnG62yDQo5JnqKkrK4jO5iKqDAZGItAqN5CtKBCBWRUA==",
|
||||
"engines": {
|
||||
"node": ">=16.14"
|
||||
}
|
||||
},
|
||||
"node_modules/named-placeholders": {
|
||||
"version": "1.1.3",
|
||||
"resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.3.tgz",
|
||||
|
|
@ -12253,7 +12251,6 @@
|
|||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz",
|
||||
"integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==",
|
||||
"dev": true,
|
||||
"engines": {
|
||||
"node": ">=8.6"
|
||||
},
|
||||
|
|
|
|||
|
|
@ -1,46 +1,39 @@
|
|||
import path from "path";
|
||||
|
||||
import { IDE } from "../..";
|
||||
import { GlobalContext } from "../../util/GlobalContext";
|
||||
|
||||
import { DEFAULT_PROMPTS_FOLDER_V2 } from "./getPromptFiles";
|
||||
import { getPathModuleForIde } from "../../util/pathModule";
|
||||
|
||||
const FIRST_TIME_DEFAULT_PROMPT_FILE = `# This is an example ".prompt" file
|
||||
# It is used to define and reuse prompts within Continue
|
||||
# Continue will automatically create a context provider for each prompt in the .prompts folder
|
||||
# Each .prompt file can be accessed by typing "@prompts" in the Chat input
|
||||
|
||||
# A prompt file consists of two parts:
|
||||
# 1. Everything above the "---" is YAML. Here you can set "temperature", "description", and other options
|
||||
# 2. Everything below the "---" is the prompt body
|
||||
|
||||
# If you don't want to set any options, you don't need to include the "---"
|
||||
# If you do not want to set any options, you do not need to include the "---"
|
||||
|
||||
# In the body, you can reference:
|
||||
# 1. Files, using either absolute or relative (based on the workspace root) paths
|
||||
# e.g. @README.md
|
||||
# e.g. @src/test/test.py
|
||||
# e.g. @/Users/me/Desktop/my-project/src/test/test.py
|
||||
# 2. URLs
|
||||
# e.g. https://example.com
|
||||
# 3. Some context providers, like
|
||||
# e.g. @currentFile
|
||||
# e.g. @os
|
||||
# e.g. @repo-map
|
||||
# 1. Files, using either absolute or relative paths (based on the workspace root)
|
||||
# @README.md
|
||||
# @src/test/test.py
|
||||
# @/Users/me/Desktop/my-project/src/test/test.py
|
||||
# 2. URLs, for example
|
||||
# @https://example.com
|
||||
# 3. Context providers, for example
|
||||
# @currentFile
|
||||
# @os
|
||||
# @repo-map
|
||||
|
||||
# To learn more, see the full .prompt file reference: https://docs.continue.dev/features/prompt-files
|
||||
name: Example
|
||||
description: Example prompt file
|
||||
version: 2
|
||||
---
|
||||
@README.md
|
||||
|
||||
Please reference the above README.md file to understand the current project.
|
||||
`;
|
||||
|
||||
const DEFAULT_PROMPT_FILE = `version: 2
|
||||
---
|
||||
|
||||
`;
|
||||
Here is information about the current repo:
|
||||
|
||||
@README.md`;
|
||||
|
||||
const DEFAULT_PROMPT_FILE = "";
|
||||
|
||||
export async function createNewPromptFileV2(
|
||||
ide: IDE,
|
||||
|
|
@ -52,9 +45,11 @@ export async function createNewPromptFileV2(
|
|||
"No workspace directories found. Make sure you've opened a folder in your IDE.",
|
||||
);
|
||||
}
|
||||
const baseDir = path.join(
|
||||
const pathModule = await getPathModuleForIde(ide);
|
||||
|
||||
const baseDir = pathModule.join(
|
||||
workspaceDirs[0],
|
||||
promptPath ?? DEFAULT_PROMPTS_FOLDER_V2,
|
||||
promptPath ?? pathModule.join(".continue", "prompts"),
|
||||
);
|
||||
|
||||
// Find the first available filename
|
||||
|
|
@ -62,15 +57,21 @@ export async function createNewPromptFileV2(
|
|||
let promptFilePath: string;
|
||||
do {
|
||||
const suffix = counter === 0 ? "" : `-${counter}`;
|
||||
promptFilePath = path.join(baseDir, `new-prompt-file${suffix}.prompt`);
|
||||
promptFilePath = pathModule.join(
|
||||
baseDir,
|
||||
`new-prompt-file${suffix}.prompt`,
|
||||
);
|
||||
counter++;
|
||||
} while (await ide.fileExists(promptFilePath));
|
||||
|
||||
const globalContext = new GlobalContext();
|
||||
const PROMPT_FILE =
|
||||
new GlobalContext().get("hasAlreadyCreatedAPromptFile") === true
|
||||
globalContext.get("hasAlreadyCreatedAPromptFile") === true
|
||||
? DEFAULT_PROMPT_FILE
|
||||
: FIRST_TIME_DEFAULT_PROMPT_FILE;
|
||||
|
||||
globalContext.update("hasAlreadyCreatedAPromptFile", true);
|
||||
|
||||
await ide.writeFile(promptFilePath, PROMPT_FILE);
|
||||
await ide.openFile(promptFilePath);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
import path from "path";
|
||||
|
||||
import { IDE } from "../..";
|
||||
import { walkDir } from "../../indexing/walkDir";
|
||||
import { getPathModuleForIde } from "../../util/pathModule";
|
||||
import { readAllGlobalPromptFiles } from "../../util/paths";
|
||||
|
||||
async function getPromptFilesFromDir(
|
||||
|
|
@ -27,20 +26,23 @@ async function getPromptFilesFromDir(
|
|||
}
|
||||
}
|
||||
|
||||
export const DEFAULT_PROMPTS_FOLDER_V2 = ".prompts";
|
||||
|
||||
export async function getAllPromptFilesV2(
|
||||
ide: IDE,
|
||||
overridePromptFolder?: string,
|
||||
): Promise<{ path: string; content: string }[]> {
|
||||
const workspaceDirs = await ide.getWorkspaceDirs();
|
||||
let promptFiles: { path: string; content: string }[] = [];
|
||||
const pathModule = await getPathModuleForIde(ide);
|
||||
|
||||
promptFiles = (
|
||||
await Promise.all(
|
||||
workspaceDirs.map((dir) =>
|
||||
getPromptFilesFromDir(
|
||||
ide,
|
||||
path.join(dir, overridePromptFolder ?? DEFAULT_PROMPTS_FOLDER_V2),
|
||||
pathModule.join(
|
||||
dir,
|
||||
overridePromptFolder ?? pathModule.join(".continue", "prompts"),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
import { ContextItem, ContextProviderExtras } from "../..";
|
||||
import { contextProviderClassFromName } from "../../context/providers";
|
||||
import URLContextProvider from "../../context/providers/URLContextProvider";
|
||||
import { getBasename } from "../../util";
|
||||
|
||||
import { getPreambleAndBody } from "./parse";
|
||||
|
||||
async function resolveAttachment(
|
||||
|
|
@ -15,6 +15,13 @@ async function resolveAttachment(
|
|||
if (contextProvider) {
|
||||
const items = await contextProvider.getContextItems("", extras);
|
||||
return items;
|
||||
} else {
|
||||
// Just instantiate it here
|
||||
const providerClass = contextProviderClassFromName(name) as any;
|
||||
if (providerClass) {
|
||||
const providerInstance = new providerClass({});
|
||||
return providerInstance.getContextItems("", extras);
|
||||
}
|
||||
}
|
||||
|
||||
// Files
|
||||
|
|
|
|||
|
|
@ -147,6 +147,7 @@ export type ToCoreFromIdeOrWebviewProtocol = {
|
|||
undefined | { dirs?: string[]; shouldClearIndexes?: boolean },
|
||||
void,
|
||||
];
|
||||
"index/forceReIndexFiles": [undefined | { files?: string[] }, void];
|
||||
"index/indexingProgressBarInitialized": [undefined, void];
|
||||
completeOnboarding: [
|
||||
{
|
||||
|
|
|
|||
|
|
@ -27,6 +27,7 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
},
|
||||
void,
|
||||
];
|
||||
overwriteFile: [{ filepath: string; prevFileContent: string | null }, void];
|
||||
showTutorial: [undefined, void];
|
||||
showFile: [{ filepath: string }, void];
|
||||
openConfigJson: [undefined, void];
|
||||
|
|
@ -37,10 +38,11 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
insertAtCursor: [{ text: string }, void];
|
||||
copyText: [{ text: string }, void];
|
||||
"jetbrains/editorInsetHeight": [{ height: number }, void];
|
||||
"jetbrains/isOSREnabled": [undefined, void];
|
||||
"vscode/openMoveRightMarkdown": [undefined, void];
|
||||
setGitHubAuthToken: [{ token: string }, void];
|
||||
acceptDiff: [{ filepath: string }, void];
|
||||
rejectDiff: [{ filepath: string }, void];
|
||||
acceptDiff: [{ filepath: string; streamId?: string }, void];
|
||||
rejectDiff: [{ filepath: string; streamId?: string }, void];
|
||||
"edit/sendPrompt": [
|
||||
{ prompt: MessageContent; range: RangeInFileWithContents },
|
||||
void,
|
||||
|
|
@ -56,13 +58,24 @@ export interface EditModeArgs {
|
|||
highlightedCode: RangeInFileWithContents;
|
||||
}
|
||||
|
||||
export type EditStatus = "not-started" | "streaming" | "accepting" | "done";
|
||||
export type EditStatus =
|
||||
| "not-started"
|
||||
| "streaming"
|
||||
| "accepting"
|
||||
| "accepting:full-diff"
|
||||
| "done";
|
||||
|
||||
export type ApplyStateStatus =
|
||||
| "streaming" // Changes are being applied to the file
|
||||
| "done" // All changes have been applied, awaiting user to accept/reject
|
||||
| "closed"; // All changes have been applied. Note that for new files, we immediately set the status to "closed"
|
||||
|
||||
export interface ApplyState {
|
||||
streamId: string;
|
||||
status?: "streaming" | "done" | "closed";
|
||||
status?: ApplyStateStatus;
|
||||
numDiffs?: number;
|
||||
filepath?: string;
|
||||
fileContent?: string;
|
||||
}
|
||||
|
||||
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
||||
|
|
@ -98,6 +111,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
|||
setTheme: [{ theme: any }, void];
|
||||
setColors: [{ [key: string]: string }, void];
|
||||
"jetbrains/editorInsetRefresh": [undefined, void];
|
||||
"jetbrains/isOSREnabled": [boolean, void];
|
||||
addApiKey: [undefined, void];
|
||||
setupLocalConfig: [undefined, void];
|
||||
incrementFtc: [undefined, void];
|
||||
|
|
@ -105,6 +119,6 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
|||
applyCodeFromChat: [undefined, void];
|
||||
updateApplyState: [ApplyState, void];
|
||||
startEditMode: [EditModeArgs, void];
|
||||
setEditStatus: [{ status: EditStatus }, void];
|
||||
setEditStatus: [{ status: EditStatus; fileAfterEdit?: string }, void];
|
||||
exitEditMode: [undefined, void];
|
||||
};
|
||||
|
|
|
|||
|
|
@ -41,6 +41,7 @@ export const WEBVIEW_TO_CORE_PASS_THROUGH: (keyof ToCoreFromWebviewProtocol)[] =
|
|||
"stats/getTokensPerModel",
|
||||
"index/setPaused",
|
||||
"index/forceReIndex",
|
||||
"index/forceReIndexFiles",
|
||||
"index/indexingProgressBarInitialized",
|
||||
"completeOnboarding",
|
||||
"addAutocompleteModel",
|
||||
|
|
@ -60,5 +61,5 @@ export const CORE_TO_WEBVIEW_PASS_THROUGH: (keyof ToWebviewFromCoreProtocol)[] =
|
|||
"isContinueInputFocused",
|
||||
"didChangeAvailableProfiles",
|
||||
"setTTSActive",
|
||||
"getWebviewHistoryLength"
|
||||
"getWebviewHistoryLength",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -135,4 +135,21 @@ World
|
|||
|
||||
expect(result).toBe("Hello\n\nWorld");
|
||||
});
|
||||
|
||||
it("should work with templated strings", () => {
|
||||
const language = "typescript";
|
||||
const code = "console.log('hello');\nconsole.log('world');";
|
||||
|
||||
const result = dedent`
|
||||
This is the prefix of the file:
|
||||
\`\`\`${language}
|
||||
${code}
|
||||
\`\`\``;
|
||||
|
||||
expect(result).toBe(`\
|
||||
This is the prefix of the file:
|
||||
\`\`\`${language}
|
||||
${code}
|
||||
\`\`\``);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -20,7 +20,7 @@ import { GetGhTokenArgs } from "../protocol/ide.js";
|
|||
import { getContinueGlobalPath } from "./paths.js";
|
||||
|
||||
class FileSystemIde implements IDE {
|
||||
constructor(private readonly workspaceDir: string) { }
|
||||
constructor(private readonly workspaceDir: string) {}
|
||||
showToast(
|
||||
type: ToastType,
|
||||
message: string,
|
||||
|
|
@ -36,7 +36,7 @@ class FileSystemIde implements IDE {
|
|||
}
|
||||
|
||||
gotoDefinition(location: Location): Promise<RangeInFile[]> {
|
||||
throw new Error("Method not implemented.");
|
||||
return Promise.resolve([]);
|
||||
}
|
||||
onDidChangeActiveTextEditor(callback: (filepath: string) => void): void {
|
||||
return;
|
||||
|
|
|
|||
|
|
@ -2,19 +2,19 @@ export function removeQuotesAndEscapes(output: string): string {
|
|||
output = output.trim();
|
||||
|
||||
// Replace smart quotes
|
||||
output = output.replace("“", "\"");
|
||||
output = output.replace("”", "\"");
|
||||
output = output.replace("“", '"');
|
||||
output = output.replace("”", '"');
|
||||
output = output.replace("‘", "'");
|
||||
output = output.replace("’", "'");
|
||||
|
||||
// Remove escapes
|
||||
output = output.replace("\\\"", "\"");
|
||||
output = output.replace('\\"', '"');
|
||||
output = output.replace("\\'", "'");
|
||||
output = output.replace("\\n", "\n");
|
||||
output = output.replace("\\t", "\t");
|
||||
output = output.replace("\\\\", "\\");
|
||||
while (
|
||||
(output.startsWith("\"") && output.endsWith("\"")) ||
|
||||
(output.startsWith('"') && output.endsWith('"')) ||
|
||||
(output.startsWith("'") && output.endsWith("'"))
|
||||
) {
|
||||
output = output.slice(1, -1);
|
||||
|
|
@ -276,31 +276,55 @@ export function deduplicateArray<T>(
|
|||
export type TODO = any;
|
||||
|
||||
export function dedent(strings: TemplateStringsArray, ...values: any[]) {
|
||||
let result = strings.reduce(
|
||||
(acc, str, i) => acc + str + (values[i] || ""),
|
||||
"",
|
||||
);
|
||||
result = result.replace(/^\n/, "").replace(/\n\s*$/, "");
|
||||
let raw = "";
|
||||
for (let i = 0; i < strings.length; i++) {
|
||||
raw += strings[i];
|
||||
|
||||
// Handle the value if it exists
|
||||
if (i < values.length) {
|
||||
let value = String(values[i]);
|
||||
// If the value contains newlines, we need to adjust the indentation
|
||||
if (value.includes("\n")) {
|
||||
// Find the indentation level of the last line in strings[i]
|
||||
let lines = strings[i].split("\n");
|
||||
let lastLine = lines[lines.length - 1];
|
||||
let match = lastLine.match(/(^|\n)([^\S\n]*)$/);
|
||||
let indent = match ? match[2] : "";
|
||||
// Add indentation to all lines except the first line of value
|
||||
let valueLines = value.split("\n");
|
||||
valueLines = valueLines.map((line, index) =>
|
||||
index === 0 ? line : indent + line,
|
||||
);
|
||||
value = valueLines.join("\n");
|
||||
}
|
||||
raw += value;
|
||||
}
|
||||
}
|
||||
|
||||
// Now dedent the full string
|
||||
let result = raw.replace(/^\n/, "").replace(/\n\s*$/, "");
|
||||
let lines = result.split("\n");
|
||||
|
||||
// Remove leading white-space-only lines
|
||||
// Remove leading/trailing blank lines
|
||||
while (lines.length > 0 && lines[0].trim() === "") {
|
||||
lines.shift();
|
||||
}
|
||||
|
||||
// Remove trailing white-space-only lines
|
||||
while (lines.length > 0 && lines[lines.length - 1].trim() === "") {
|
||||
lines.pop();
|
||||
}
|
||||
|
||||
const minIndent = lines.reduce((min, line) => {
|
||||
if (line.trim() === "") {
|
||||
// Don't consider empty lines when calculating indentation
|
||||
return min;
|
||||
}
|
||||
const match = line.match(/^\s*/);
|
||||
return Math.min(min, match ? match[0].length : Infinity);
|
||||
}, Infinity);
|
||||
// Calculate minimum indentation (excluding empty lines)
|
||||
let minIndent = lines.reduce((min: any, line: any) => {
|
||||
if (line.trim() === "") return min;
|
||||
let match = line.match(/^(\s*)/);
|
||||
let indent = match ? match[1].length : 0;
|
||||
return min === null ? indent : Math.min(min, indent);
|
||||
}, null);
|
||||
|
||||
return lines.map((line) => line.slice(minIndent)).join("\n");
|
||||
if (minIndent !== null && minIndent > 0) {
|
||||
// Remove the minimum indentation from each line
|
||||
lines = lines.map((line) => line.slice(minIndent));
|
||||
}
|
||||
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
|
|
|||
13
core/util/pathModule.ts
Normal file
13
core/util/pathModule.ts
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
import { PlatformPath, posix, win32 } from "node:path";
|
||||
import { IDE } from "..";
|
||||
|
||||
export type PathSep = "/" | "\\";
|
||||
|
||||
function getPathModuleFromPathSep(pathSep: PathSep): PlatformPath {
|
||||
return pathSep === "/" ? posix : win32;
|
||||
}
|
||||
|
||||
export async function getPathModuleForIde(ide: IDE): Promise<PlatformPath> {
|
||||
const pathSep = await ide.pathSep();
|
||||
return getPathModuleFromPathSep(pathSep as PathSep);
|
||||
}
|
||||
|
|
@ -327,7 +327,7 @@ export function getPromptLogsPath(): string {
|
|||
}
|
||||
|
||||
export function getGlobalPromptsPath(): string {
|
||||
return path.join(getContinueGlobalPath(), ".prompts");
|
||||
return path.join(getContinueGlobalPath(), "prompts");
|
||||
}
|
||||
|
||||
export function readAllGlobalPromptFiles(
|
||||
|
|
|
|||
|
|
@ -3,81 +3,116 @@ import * as path from "node:path";
|
|||
|
||||
import Parser, { Language } from "web-tree-sitter";
|
||||
|
||||
export const supportedLanguages: { [key: string]: string } = {
|
||||
cpp: "cpp",
|
||||
hpp: "cpp",
|
||||
cc: "cpp",
|
||||
cxx: "cpp",
|
||||
hxx: "cpp",
|
||||
cp: "cpp",
|
||||
hh: "cpp",
|
||||
inc: "cpp",
|
||||
// Depended on this PR: https://github.com/tree-sitter/tree-sitter-cpp/pull/173
|
||||
// ccm: "cpp",
|
||||
// c++m: "cpp",
|
||||
// cppm: "cpp",
|
||||
// cxxm: "cpp",
|
||||
cs: "c_sharp",
|
||||
c: "c",
|
||||
h: "c",
|
||||
css: "css",
|
||||
php: "php",
|
||||
phtml: "php",
|
||||
php3: "php",
|
||||
php4: "php",
|
||||
php5: "php",
|
||||
php7: "php",
|
||||
phps: "php",
|
||||
"php-s": "php",
|
||||
bash: "bash",
|
||||
sh: "bash",
|
||||
json: "json",
|
||||
ts: "typescript",
|
||||
mts: "typescript",
|
||||
cts: "typescript",
|
||||
tsx: "tsx",
|
||||
// vue: "vue", // tree-sitter-vue parser is broken
|
||||
// The .wasm file being used is faulty, and yaml is split line-by-line anyway for the most part
|
||||
// yaml: "yaml",
|
||||
// yml: "yaml",
|
||||
elm: "elm",
|
||||
js: "javascript",
|
||||
jsx: "javascript",
|
||||
mjs: "javascript",
|
||||
cjs: "javascript",
|
||||
py: "python",
|
||||
ipynb: "python",
|
||||
pyw: "python",
|
||||
pyi: "python",
|
||||
el: "elisp",
|
||||
emacs: "elisp",
|
||||
ex: "elixir",
|
||||
exs: "elixir",
|
||||
go: "go",
|
||||
eex: "embedded_template",
|
||||
heex: "embedded_template",
|
||||
leex: "embedded_template",
|
||||
html: "html",
|
||||
htm: "html",
|
||||
java: "java",
|
||||
lua: "lua",
|
||||
ocaml: "ocaml",
|
||||
ml: "ocaml",
|
||||
mli: "ocaml",
|
||||
ql: "ql",
|
||||
res: "rescript",
|
||||
resi: "rescript",
|
||||
rb: "ruby",
|
||||
erb: "ruby",
|
||||
rs: "rust",
|
||||
rdl: "systemrdl",
|
||||
toml: "toml",
|
||||
sol: "solidity",
|
||||
export enum LanguageName {
|
||||
CPP = "cpp",
|
||||
C_SHARP = "c_sharp",
|
||||
C = "c",
|
||||
CSS = "css",
|
||||
PHP = "php",
|
||||
BASH = "bash",
|
||||
JSON = "json",
|
||||
TYPESCRIPT = "typescript",
|
||||
TSX = "tsx",
|
||||
ELM = "elm",
|
||||
JAVASCRIPT = "javascript",
|
||||
PYTHON = "python",
|
||||
ELISP = "elisp",
|
||||
ELIXIR = "elixir",
|
||||
GO = "go",
|
||||
EMBEDDED_TEMPLATE = "embedded_template",
|
||||
HTML = "html",
|
||||
JAVA = "java",
|
||||
LUA = "lua",
|
||||
OCAML = "ocaml",
|
||||
QL = "ql",
|
||||
RESCRIPT = "rescript",
|
||||
RUBY = "ruby",
|
||||
RUST = "rust",
|
||||
SYSTEMRDL = "systemrdl",
|
||||
TOML = "toml",
|
||||
SOLIDITY = "solidity",
|
||||
}
|
||||
|
||||
// jl: "julia",
|
||||
// swift: "swift",
|
||||
// kt: "kotlin",
|
||||
// scala: "scala",
|
||||
export const supportedLanguages: { [key: string]: LanguageName } = {
|
||||
cpp: LanguageName.CPP,
|
||||
hpp: LanguageName.CPP,
|
||||
cc: LanguageName.CPP,
|
||||
cxx: LanguageName.CPP,
|
||||
hxx: LanguageName.CPP,
|
||||
cp: LanguageName.CPP,
|
||||
hh: LanguageName.CPP,
|
||||
inc: LanguageName.CPP,
|
||||
// Depended on this PR: https://github.com/tree-sitter/tree-sitter-cpp/pull/173
|
||||
// ccm: LanguageName.CPP,
|
||||
// c++m: LanguageName.CPP,
|
||||
// cppm: LanguageName.CPP,
|
||||
// cxxm: LanguageName.CPP,
|
||||
cs: LanguageName.C_SHARP,
|
||||
c: LanguageName.C,
|
||||
h: LanguageName.C,
|
||||
css: LanguageName.CSS,
|
||||
php: LanguageName.PHP,
|
||||
phtml: LanguageName.PHP,
|
||||
php3: LanguageName.PHP,
|
||||
php4: LanguageName.PHP,
|
||||
php5: LanguageName.PHP,
|
||||
php7: LanguageName.PHP,
|
||||
phps: LanguageName.PHP,
|
||||
"php-s": LanguageName.PHP,
|
||||
bash: LanguageName.BASH,
|
||||
sh: LanguageName.BASH,
|
||||
json: LanguageName.JSON,
|
||||
ts: LanguageName.TYPESCRIPT,
|
||||
mts: LanguageName.TYPESCRIPT,
|
||||
cts: LanguageName.TYPESCRIPT,
|
||||
tsx: LanguageName.TSX,
|
||||
// vue: LanguageName.VUE, // tree-sitter-vue parser is broken
|
||||
// The .wasm file being used is faulty, and yaml is split line-by-line anyway for the most part
|
||||
// yaml: LanguageName.YAML,
|
||||
// yml: LanguageName.YAML,
|
||||
elm: LanguageName.ELM,
|
||||
js: LanguageName.JAVASCRIPT,
|
||||
jsx: LanguageName.JAVASCRIPT,
|
||||
mjs: LanguageName.JAVASCRIPT,
|
||||
cjs: LanguageName.JAVASCRIPT,
|
||||
py: LanguageName.PYTHON,
|
||||
ipynb: LanguageName.PYTHON,
|
||||
pyw: LanguageName.PYTHON,
|
||||
pyi: LanguageName.PYTHON,
|
||||
el: LanguageName.ELISP,
|
||||
emacs: LanguageName.ELISP,
|
||||
ex: LanguageName.ELIXIR,
|
||||
exs: LanguageName.ELIXIR,
|
||||
go: LanguageName.GO,
|
||||
eex: LanguageName.EMBEDDED_TEMPLATE,
|
||||
heex: LanguageName.EMBEDDED_TEMPLATE,
|
||||
leex: LanguageName.EMBEDDED_TEMPLATE,
|
||||
html: LanguageName.HTML,
|
||||
htm: LanguageName.HTML,
|
||||
java: LanguageName.JAVA,
|
||||
lua: LanguageName.LUA,
|
||||
ocaml: LanguageName.OCAML,
|
||||
ml: LanguageName.OCAML,
|
||||
mli: LanguageName.OCAML,
|
||||
ql: LanguageName.QL,
|
||||
res: LanguageName.RESCRIPT,
|
||||
resi: LanguageName.RESCRIPT,
|
||||
rb: LanguageName.RUBY,
|
||||
erb: LanguageName.RUBY,
|
||||
rs: LanguageName.RUST,
|
||||
rdl: LanguageName.SYSTEMRDL,
|
||||
toml: LanguageName.TOML,
|
||||
sol: LanguageName.SOLIDITY,
|
||||
|
||||
// jl: LanguageName.JULIA,
|
||||
// swift: LanguageName.SWIFT,
|
||||
// kt: LanguageName.KOTLIN,
|
||||
// scala: LanguageName.SCALA,
|
||||
};
|
||||
|
||||
export const IGNORE_PATH_PATTERNS: Partial<Record<LanguageName, RegExp[]>> = {
|
||||
[LanguageName.TYPESCRIPT]: [/.*node_modules/],
|
||||
[LanguageName.JAVASCRIPT]: [/.*node_modules/],
|
||||
};
|
||||
|
||||
export async function getParserForFile(filepath: string) {
|
||||
|
|
@ -128,15 +163,9 @@ export async function getLanguageForFile(
|
|||
}
|
||||
}
|
||||
|
||||
export enum TSQueryType {
|
||||
CodeSnippets = "code-snippet-queries",
|
||||
Imports = "import-queries",
|
||||
// Used in RootPathContextService.ts
|
||||
FunctionDeclaration = "root-path-context-queries/function_declaration",
|
||||
MethodDefinition = "root-path-context-queries/method_definition",
|
||||
FunctionDefinition = "root-path-context-queries/function_definition",
|
||||
MethodDeclaration = "root-path-context-queries/method_declaration",
|
||||
}
|
||||
export const getFullLanguageName = (filepath: string) => {
|
||||
return supportedLanguages[filepath.split(".").pop() ?? ""];
|
||||
};
|
||||
|
||||
export async function getQueryForFile(
|
||||
filepath: string,
|
||||
|
|
@ -147,7 +176,6 @@ export async function getQueryForFile(
|
|||
return undefined;
|
||||
}
|
||||
|
||||
const fullLangName = supportedLanguages[filepath.split(".").pop() ?? ""];
|
||||
const sourcePath = path.join(
|
||||
__dirname,
|
||||
"..",
|
||||
|
|
@ -155,7 +183,6 @@ export async function getQueryForFile(
|
|||
? ["extensions", "vscode", "tree-sitter"]
|
||||
: ["tree-sitter"]),
|
||||
queryPath,
|
||||
`${fullLangName}.scm`,
|
||||
);
|
||||
if (!fs.existsSync(sourcePath)) {
|
||||
return undefined;
|
||||
|
|
|
|||
|
|
@ -82,10 +82,10 @@ export class TTS {
|
|||
return;
|
||||
}
|
||||
|
||||
TTS.messenger.request("setTTSActive", true);
|
||||
void TTS.messenger.request("setTTSActive", true);
|
||||
|
||||
TTS.handle?.once("exit", () => {
|
||||
TTS.messenger.request("setTTSActive", false);
|
||||
void TTS.messenger.request("setTTSActive", false);
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -26,26 +26,23 @@ The API keys for Codestral and the general Mistral APIs are different. If you ar
|
|||
|
||||
## Local, offline / self-hosted experience
|
||||
|
||||
For those preferring local execution or self-hosting,`StarCoder2-3b` offers a good balance of performance and quality for most users:
|
||||
For those preferring local execution or self-hosting,`Qwen2.5-Coder 1.5B` offers a good balance of performance and quality for most users:
|
||||
|
||||
```json title="config.json""
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "StarCoder2-3b",
|
||||
"model": "starcoder2:3b",
|
||||
"title": "Qwen2.5-Coder 1.5B",
|
||||
"model": "qwen2.5-coder:1.5b",
|
||||
"provider": "ollama"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Alternative experiences
|
||||
|
||||
- Completions too slow? Try `deepseek-coder:1.3b-base` for quicker completions on less powerful hardware
|
||||
- Have more compute? Use `deepseek-coder:6.7b-base` for potentially higher-quality suggestions
|
||||
Have more compute? Use `qwen2.5-coder:7b` for potentially higher-quality suggestions.
|
||||
|
||||
:::note
|
||||
|
||||
For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., second-state/StarCoder2-3B-GGUF/starcoder2-3b-Q8_0.gguf). Use this path as the `model` value in your configuration.
|
||||
For LM Studio users, navigate to the "My Models" section, find your desired model, and copy the path (e.g., `Qwen/Qwen2.5-Coder-1.5B-Instruct-GGUF/wen2.5-coder-1.5b-instruct-q4_k_m.gguf`). Use this path as the `model` value in your configuration.
|
||||
|
||||
:::
|
||||
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ sidebar_position: 5
|
|||
|
||||
There are a number of different ways to customize Chat
|
||||
|
||||
- You can add a [`.continuerules`](../customize/deep-dives/rules.md) file to the root of your project to customize the system prompt
|
||||
- You can configure [`@Codebase`](../customize/deep-dives/codebase.md)
|
||||
- You can create your own [custom code RAG](../customize/tutorials/custom-code-rag.md)
|
||||
- You can configure [`@Docs`](../customize/deep-dives/docs.md)
|
||||
|
|
|
|||
|
|
@ -23,7 +23,7 @@ If you want to have the best autocomplete experience, we recommend using Codestr
|
|||
If you'd like to run your autocomplete model locally, we recommend using Ollama. To do this, first download the latest version of Ollama from [here](https://ollama.ai). Then, run the following command to download our recommended model:
|
||||
|
||||
```bash
|
||||
ollama run starcoder2:3b
|
||||
ollama run qwen2.5-coder:1.5b
|
||||
```
|
||||
|
||||
Once it has been downloaded, you should begin to see completions in VS Code.
|
||||
|
|
@ -37,7 +37,7 @@ All of the configuration options available for chat models are available to use
|
|||
"tabAutocompleteModel": {
|
||||
"title": "Tab Autocomplete Model",
|
||||
"provider": "ollama",
|
||||
"model": "starcoder2:3b",
|
||||
"model": "qwen2.5-coder:1.5b",
|
||||
"apiBase": "https://<my endpoint>"
|
||||
},
|
||||
...
|
||||
|
|
@ -52,7 +52,7 @@ The following can be configured in `config.json`:
|
|||
|
||||
### `tabAutocompleteModel`
|
||||
|
||||
This is just another object like the ones in the `"models"` array of `config.json`. You can choose and configure any model you would like, but we strongly suggest using a small model made for tab-autocomplete, such as `deepseek-1b`, `starcoder-1b`, or `starcoder2-3b`.
|
||||
This is just another object like the ones in the `"models"` array of `config.json`. You can choose and configure any model you would like, but we strongly suggest using a small model made for tab-autocomplete, such as `deepseek-1b`, `qwen2.5-coder:1.5b`, or `starcoder2-3b`.
|
||||
|
||||
### `tabAutocompleteOptions`
|
||||
|
||||
|
|
@ -78,7 +78,7 @@ This object allows you to customize the behavior of tab-autocomplete. The availa
|
|||
"tabAutocompleteModel": {
|
||||
"title": "Tab Autocomplete Model",
|
||||
"provider": "ollama",
|
||||
"model": "starcoder2:3b",
|
||||
"model": "qwen2.5-coder:1.5b",
|
||||
"apiBase": "https://<my endpoint>"
|
||||
},
|
||||
"tabAutocompleteOptions": {
|
||||
|
|
@ -101,16 +101,12 @@ Follow these steps to ensure that everything is set up correctly:
|
|||
|
||||
1. Make sure you have the "Enable Tab Autocomplete" setting checked (in VS Code, you can toggle by clicking the "Continue" button in the status bar, and in JetBrains by going to Settings -> Tools -> Continue).
|
||||
2. Make sure you have downloaded Ollama.
|
||||
3. Run `ollama run starcoder2:3b` to verify that the model is downloaded.
|
||||
3. Run `ollama run qwen2.5-coder:1.5b` to verify that the model is downloaded.
|
||||
4. Make sure that any other completion providers are disabled (e.g. Copilot), as they may interfere.
|
||||
5. Check the output of the logs to find any potential errors: <kbd>cmd/ctrl</kbd> + <kbd>shift</kbd> + <kbd>P</kbd> -> "Toggle Developer Tools" -> "Console" tab in VS Code, ~/.continue/logs/core.log in JetBrains.
|
||||
6. Check VS Code settings to make sure that `"editor.inlineSuggest.enabled"` is set to `true` (use <kbd>cmd/ctrl</kbd> + <kbd>,</kbd> then search for this and check the box)
|
||||
7. If you are still having issues, please let us know in our [Discord](https://discord.gg/vapESyrFmJ) and we'll help as soon as possible.
|
||||
|
||||
### Completions are slow
|
||||
|
||||
Depending on your hardware, you may want to try a smaller, faster model. If 3b isn't working for you we recommend trying `deepseek-coder:1.3b-base`.
|
||||
|
||||
### Completions are only ever single-line
|
||||
|
||||
To ensure that you receive multi-line completions, you can set `"multilineCompletions": "always"` in `tabAutocompleteOptions`. By default, it is `"auto"`. If you still find that you are only seeing single-line completions, this may be because some models tend to produce shorter completions when starting in the middle of a file. You can try temporarily moving text below your cursor out of your active file, or switching to a larger model.
|
||||
|
|
|
|||
|
|
@ -6,42 +6,30 @@ Prompt files provide a convenient way to standardize common patterns and share a
|
|||
|
||||
## Quick start
|
||||
|
||||
:::tip[Prompt library]
|
||||
<!-- :::tip[Prompt library]
|
||||
To assist you in getting started, [we've curated a small library of `.prompt` files](https://github.com/continuedev/prompt-file-examples). We encourage community contributions to this repository, so please consider opening up a pull request with your own prompts!
|
||||
:::
|
||||
::: -->
|
||||
|
||||
Below is a quick example of setting up a prompt file to write unit tests using Jest.
|
||||
Below is a quick example of setting up a prompt file to de
|
||||
|
||||
1. Create a folder called `.prompts/` at the top level of your workspace.
|
||||
2. Add a file called `test.prompt` to this folder. The name of this file will be the name of the slash command you will use to generate your prompt.
|
||||
3. Write the following contents to `test.prompt` and save.
|
||||
1. Create a folder called `.continue/prompts` at the top level of your workspace (or you can use the button in the UI by typing @, selecting "Prompt Files", and selecting "New Prompt File").
|
||||
2. Add a file called `rails.prompt` to this folder.
|
||||
3. Write the following contents to `rails.prompt` and save.
|
||||
|
||||
```
|
||||
temperature: 0.5
|
||||
maxTokens: 4096
|
||||
name: Rails Project
|
||||
description: Information about this project
|
||||
---
|
||||
<system>
|
||||
You are an expert programmer
|
||||
</system>
|
||||
|
||||
{{{ input }}}
|
||||
|
||||
Write unit tests for the above selected code, following each of these instructions:
|
||||
- Use `jest`
|
||||
- Properly set up and tear down
|
||||
- Include important edge cases
|
||||
- The tests should be complete and sophisticated
|
||||
- Give the tests just as chat output, don't edit any file
|
||||
- Don't explain how to set up `jest`
|
||||
Attached is a summary of the current Ruby on Rails application, including the @Gemfile and database schema in @db/schema.rb
|
||||
```
|
||||
|
||||
Now to use this prompt, you can highlight code and use <kbd>cmd/ctrl</kbd> + <kbd>L</kbd> to select it in the Continue sidebar.
|
||||
|
||||
Then, type "/" to see the list of slash commands and choose the one called "test". Press enter and the LLM will respond given the instructions from your prompt file.
|
||||
Then, type "@", select "Prompt files", and choose the one called "Rails Project". You can now ask any question as usual and the LLM will have the information from your .prompt file.
|
||||
|
||||
## Format
|
||||
|
||||
The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to use context providers and built-in variables using [Handlebars syntax](https://handlebarsjs.com/guide/).
|
||||
The format is inspired by [HumanLoops's .prompt file](https://docs.humanloop.com/docs/prompt-file-format), with additional templating to reference files, URLs, and context providers.
|
||||
|
||||
:::info
|
||||
The current state of this format is experimental and subject to change
|
||||
|
|
@ -51,38 +39,19 @@ The current state of this format is experimental and subject to change
|
|||
|
||||
The "preamble" is everything above the `---` separator, and lets you specify model parameters. It uses YAML syntax and currently supports the following parameters:
|
||||
|
||||
- `name`
|
||||
- `temperature`
|
||||
- `topP`
|
||||
- `topK`
|
||||
- `minP`
|
||||
- `presencePenalty`
|
||||
- `frequencyPenalty`
|
||||
- `mirostat`
|
||||
- `stop`
|
||||
- `maxTokens`
|
||||
- `description`
|
||||
- `name` - The display title
|
||||
- `description` - The description you will see in the dropdown
|
||||
- `version` - Can be either "1" (for legacy prompt files) or "2" (this is the default and does not need to be set)
|
||||
|
||||
If you don't need any of these parameters, you can leave out the preamble and do not need to include the `---` separator.
|
||||
|
||||
### System message
|
||||
### Context
|
||||
|
||||
To add a system message, start the body with `<system></system>` tags like in the example above and place your system message inside.
|
||||
Many [context provider](../context-providers.md) can be referenced by typing "@" followed by the name of the context provider.
|
||||
|
||||
### Built-in variables
|
||||
|
||||
The following built-in variables are currently available:
|
||||
|
||||
- `{{{ input }}}` - The full text from the input box in the sidebar that is sent along with the slash command
|
||||
- `{{{ currentFile }}}` - The currently open file in your IDE
|
||||
- `{{{ ./path/to/file.js }}}` - Any file can be directly referenced
|
||||
|
||||
### Context providers
|
||||
|
||||
Any [context provider](../context-providers.md) that you have added to your config can be referenced using the name of the context provider. Context providers that receive an input are also supported.
|
||||
|
||||
- `{{{ terminal }}}` - The contents of the terminal
|
||||
- `{{{ url "https://github.com/continuedev/continue" }}}` - The contents of a URL
|
||||
- `@terminal` - The contents of the terminal
|
||||
- `@https://github.com/continuedev/continue` - The contents of a URL
|
||||
- `@src/index.ts` - The contents of a file
|
||||
|
||||
## Feedback
|
||||
|
||||
|
|
|
|||
27
docs/docs/customize/deep-dives/rules.md
Normal file
27
docs/docs/customize/deep-dives/rules.md
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
---
|
||||
description: Learn how to customize the system prompt with a `.continuerules` file
|
||||
keywords: [rules, .continuerules, system, prompt, message]
|
||||
---
|
||||
|
||||
# `.continuerules`
|
||||
|
||||
You can create a project-specific system message by adding a `.continuerules` file to the root of your project. This file is raw text and its contents will be inserted into the system message for all LLM requests.
|
||||
|
||||
## Simple Examples
|
||||
|
||||
- If you want concise answers:
|
||||
|
||||
```title=.continuerules
|
||||
Please provide concise answers. Do explain obvious concepts. You can assume that I am knowledgable about most programming topics.
|
||||
```
|
||||
|
||||
- If you want to ensure certain practices are followed, for example in React:
|
||||
|
||||
```title=.continuerules
|
||||
Whenever you are writing React code, make sure to
|
||||
- use functional components instead of class components
|
||||
- use hooks for state management
|
||||
- define an interface for your component props
|
||||
- use Tailwind CSS for styling
|
||||
- modularize components into smaller, reusable pieces
|
||||
```
|
||||
60
docs/docs/customize/model-providers/moonshot.md
Normal file
60
docs/docs/customize/model-providers/moonshot.md
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
# Moonshot
|
||||
|
||||
[Moonshot AI](https://platform.moonshot.cn/) provides high-quality large language model services with competitive pricing and excellent performance.
|
||||
|
||||
## Configuration
|
||||
|
||||
To use Moonshot AI models, you need to:
|
||||
|
||||
1. Get an API key from [Moonshot AI Platform](https://platform.moonshot.cn/)
|
||||
2. Add the following configuration to your `config.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Moonshot",
|
||||
"provider": "moonshot",
|
||||
"model": "moonshot-v1-8k",
|
||||
"apiKey": "YOUR_API_KEY"
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
## Available Models
|
||||
|
||||
Moonshot AI currently provides the following models:
|
||||
|
||||
- `moonshot-v1-8k`: Base model with 8K context window
|
||||
- `moonshot-v1-32k`: Base model with 32K context window
|
||||
- `moonshot-v1-128k`: Base model with 128K context window
|
||||
|
||||
## Configuration Options
|
||||
|
||||
| Option | Description | Default |
|
||||
|--------|-------------|---------|
|
||||
| `apiKey` | Moonshot API key | Required |
|
||||
| `apiBase` | API base URL | `https://api.moonshot.cn/v1/` |
|
||||
| `model` | Model name to use | `moonshot-v1-8k` |
|
||||
|
||||
## Example
|
||||
|
||||
Here's a complete configuration example:
|
||||
|
||||
```json
|
||||
{
|
||||
"models": [
|
||||
{
|
||||
"title": "Moonshot-8K",
|
||||
"provider": "moonshot",
|
||||
"model": "moonshot-v1-8k",
|
||||
"apiKey": "YOUR_API_KEY",
|
||||
"completionOptions": {
|
||||
"temperature": 0.7,
|
||||
"topP": 0.95,
|
||||
"maxTokens": 2048
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
@ -23,14 +23,14 @@ We recommend configuring **Llama3.1 8B** as your chat model.
|
|||
|
||||
## Autocomplete model
|
||||
|
||||
We recommend configuring **StarCoder2 3B** as your autocomplete model.
|
||||
We recommend configuring **Qwen2.5-Coder 1.5B** as your autocomplete model.
|
||||
|
||||
```json title="config.json"
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "StarCoder2 3B",
|
||||
"title": "Qwen2.5-Coder 1.5B",
|
||||
"provider": "ollama",
|
||||
"model": "starcoder2:3b"
|
||||
"model": "qwen2.5-coder:1.5b"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
|
|||
|
|
@ -13,4 +13,4 @@ In Continue, these models are used to display inline [Autocomplete](../../autoco
|
|||
|
||||
If you have the ability to use any model, we recommend `Codestral` with [Mistral](../model-providers/top-level/mistral.md#autocomplete-model) or [Vertex AI](../model-providers/top-level/vertexai.md#autocomplete-model).
|
||||
|
||||
If you want to run a model locally, we recommend `Starcoder2-3B` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model).
|
||||
If you want to run a model locally, we recommend `Qwen2.5-Coder 1.5B` with [Ollama](../model-providers/top-level/ollama.md#autocomplete-model).
|
||||
|
|
|
|||
|
|
@ -15,7 +15,7 @@ keywords:
|
|||
]
|
||||
---
|
||||
|
||||

|
||||

|
||||
|
||||
**Continue is the leading open-source AI code assistant inside of [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains](https://plugins.jetbrains.com/plugin/22707-continue-extension)**
|
||||
|
||||
|
|
|
|||
|
|
@ -31,7 +31,7 @@ const config = {
|
|||
// to replace "en" with "zh-Hans".
|
||||
i18n: {
|
||||
defaultLocale: "en",
|
||||
locales: ["en"],
|
||||
locales: ["en", "zh-CN"],
|
||||
},
|
||||
|
||||
themes: [],
|
||||
|
|
@ -110,6 +110,10 @@ const config = {
|
|||
position: "right",
|
||||
className: "discord-navbar",
|
||||
},
|
||||
{
|
||||
type: "localeDropdown",
|
||||
position: "right",
|
||||
},
|
||||
],
|
||||
},
|
||||
footer: {
|
||||
|
|
|
|||
440
docs/i18n/zh-CN/code.json
Normal file
440
docs/i18n/zh-CN/code.json
Normal file
|
|
@ -0,0 +1,440 @@
|
|||
{
|
||||
"theme.ErrorPageContent.title": {
|
||||
"message": "页面已崩溃。",
|
||||
"description": "The title of the fallback page when the page crashed"
|
||||
},
|
||||
"theme.BackToTopButton.buttonAriaLabel": {
|
||||
"message": "回到顶部",
|
||||
"description": "The ARIA label for the back to top button"
|
||||
},
|
||||
"theme.blog.archive.title": {
|
||||
"message": "历史博文",
|
||||
"description": "The page & hero title of the blog archive page"
|
||||
},
|
||||
"theme.blog.archive.description": {
|
||||
"message": "历史博文",
|
||||
"description": "The page & hero description of the blog archive page"
|
||||
},
|
||||
"theme.blog.paginator.navAriaLabel": {
|
||||
"message": "博文列表分页导航",
|
||||
"description": "The ARIA label for the blog pagination"
|
||||
},
|
||||
"theme.blog.paginator.newerEntries": {
|
||||
"message": "较新的博文",
|
||||
"description": "The label used to navigate to the newer blog posts page (previous page)"
|
||||
},
|
||||
"theme.blog.paginator.olderEntries": {
|
||||
"message": "较旧的博文",
|
||||
"description": "The label used to navigate to the older blog posts page (next page)"
|
||||
},
|
||||
"theme.blog.post.paginator.navAriaLabel": {
|
||||
"message": "博文分页导航",
|
||||
"description": "The ARIA label for the blog posts pagination"
|
||||
},
|
||||
"theme.blog.post.paginator.newerPost": {
|
||||
"message": "较新一篇",
|
||||
"description": "The blog post button label to navigate to the newer/previous post"
|
||||
},
|
||||
"theme.blog.post.paginator.olderPost": {
|
||||
"message": "较旧一篇",
|
||||
"description": "The blog post button label to navigate to the older/next post"
|
||||
},
|
||||
"theme.tags.tagsPageLink": {
|
||||
"message": "查看所有标签",
|
||||
"description": "The label of the link targeting the tag list page"
|
||||
},
|
||||
"theme.colorToggle.ariaLabel": {
|
||||
"message": "切换浅色/暗黑模式(当前为{mode})",
|
||||
"description": "The ARIA label for the navbar color mode toggle"
|
||||
},
|
||||
"theme.colorToggle.ariaLabel.mode.dark": {
|
||||
"message": "暗黑模式",
|
||||
"description": "The name for the dark color mode"
|
||||
},
|
||||
"theme.colorToggle.ariaLabel.mode.light": {
|
||||
"message": "浅色模式",
|
||||
"description": "The name for the light color mode"
|
||||
},
|
||||
"theme.docs.breadcrumbs.navAriaLabel": {
|
||||
"message": "页面路径",
|
||||
"description": "The ARIA label for the breadcrumbs"
|
||||
},
|
||||
"theme.docs.DocCard.categoryDescription.plurals": {
|
||||
"message": "{count} 个项目",
|
||||
"description": "The default description for a category card in the generated index about how many items this category includes"
|
||||
},
|
||||
"theme.docs.paginator.navAriaLabel": {
|
||||
"message": "文件选项卡",
|
||||
"description": "The ARIA label for the docs pagination"
|
||||
},
|
||||
"theme.docs.paginator.previous": {
|
||||
"message": "上一页",
|
||||
"description": "The label used to navigate to the previous doc"
|
||||
},
|
||||
"theme.docs.paginator.next": {
|
||||
"message": "下一页",
|
||||
"description": "The label used to navigate to the next doc"
|
||||
},
|
||||
"theme.docs.tagDocListPageTitle.nDocsTagged": {
|
||||
"message": "{count} 篇文档带有标签",
|
||||
"description": "Pluralized label for \"{count} docs tagged\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)"
|
||||
},
|
||||
"theme.docs.tagDocListPageTitle": {
|
||||
"message": "{nDocsTagged}「{tagName}」",
|
||||
"description": "The title of the page for a docs tag"
|
||||
},
|
||||
"theme.docs.versionBadge.label": {
|
||||
"message": "版本:{versionLabel}"
|
||||
},
|
||||
"theme.docs.versions.unreleasedVersionLabel": {
|
||||
"message": "此为 {siteTitle} {versionLabel} 版尚未发行的文档。",
|
||||
"description": "The label used to tell the user that he's browsing an unreleased doc version"
|
||||
},
|
||||
"theme.docs.versions.unmaintainedVersionLabel": {
|
||||
"message": "此为 {siteTitle} {versionLabel} 版的文档,现已不再积极维护。",
|
||||
"description": "The label used to tell the user that he's browsing an unmaintained doc version"
|
||||
},
|
||||
"theme.docs.versions.latestVersionSuggestionLabel": {
|
||||
"message": "最新的文档请参阅 {latestVersionLink} ({versionLabel})。",
|
||||
"description": "The label used to tell the user to check the latest version"
|
||||
},
|
||||
"theme.docs.versions.latestVersionLinkLabel": {
|
||||
"message": "最新版本",
|
||||
"description": "The label used for the latest version suggestion link label"
|
||||
},
|
||||
"theme.common.editThisPage": {
|
||||
"message": "编辑此页",
|
||||
"description": "The link label to edit the current page"
|
||||
},
|
||||
"theme.common.headingLinkTitle": {
|
||||
"message": "{heading}的直接链接",
|
||||
"description": "Title for link to heading"
|
||||
},
|
||||
"theme.lastUpdated.atDate": {
|
||||
"message": "于 {date} ",
|
||||
"description": "The words used to describe on which date a page has been last updated"
|
||||
},
|
||||
"theme.lastUpdated.byUser": {
|
||||
"message": "由 {user} ",
|
||||
"description": "The words used to describe by who the page has been last updated"
|
||||
},
|
||||
"theme.lastUpdated.lastUpdatedAtBy": {
|
||||
"message": "最后{byUser}{atDate}更新",
|
||||
"description": "The sentence used to display when a page has been last updated, and by who"
|
||||
},
|
||||
"theme.navbar.mobileVersionsDropdown.label": {
|
||||
"message": "选择版本",
|
||||
"description": "The label for the navbar versions dropdown on mobile view"
|
||||
},
|
||||
"theme.NotFound.title": {
|
||||
"message": "找不到页面",
|
||||
"description": "The title of the 404 page"
|
||||
},
|
||||
"theme.tags.tagsListLabel": {
|
||||
"message": "标签:",
|
||||
"description": "The label alongside a tag list"
|
||||
},
|
||||
"theme.AnnouncementBar.closeButtonAriaLabel": {
|
||||
"message": "关闭",
|
||||
"description": "The ARIA label for close button of announcement bar"
|
||||
},
|
||||
"theme.admonition.caution": {
|
||||
"message": "警告",
|
||||
"description": "The default label used for the Caution admonition (:::caution)"
|
||||
},
|
||||
"theme.admonition.danger": {
|
||||
"message": "危险",
|
||||
"description": "The default label used for the Danger admonition (:::danger)"
|
||||
},
|
||||
"theme.admonition.info": {
|
||||
"message": "信息",
|
||||
"description": "The default label used for the Info admonition (:::info)"
|
||||
},
|
||||
"theme.admonition.note": {
|
||||
"message": "备注",
|
||||
"description": "The default label used for the Note admonition (:::note)"
|
||||
},
|
||||
"theme.admonition.tip": {
|
||||
"message": "提示",
|
||||
"description": "The default label used for the Tip admonition (:::tip)"
|
||||
},
|
||||
"theme.admonition.warning": {
|
||||
"message": "注意",
|
||||
"description": "The default label used for the Warning admonition (:::warning)"
|
||||
},
|
||||
"theme.blog.sidebar.navAriaLabel": {
|
||||
"message": "最近博文导航",
|
||||
"description": "The ARIA label for recent posts in the blog sidebar"
|
||||
},
|
||||
"theme.CodeBlock.copied": {
|
||||
"message": "复制成功",
|
||||
"description": "The copied button label on code blocks"
|
||||
},
|
||||
"theme.CodeBlock.copyButtonAriaLabel": {
|
||||
"message": "复制代码到剪贴板",
|
||||
"description": "The ARIA label for copy code blocks button"
|
||||
},
|
||||
"theme.CodeBlock.copy": {
|
||||
"message": "复制",
|
||||
"description": "The copy button label on code blocks"
|
||||
},
|
||||
"theme.CodeBlock.wordWrapToggle": {
|
||||
"message": "切换自动换行",
|
||||
"description": "The title attribute for toggle word wrapping button of code block lines"
|
||||
},
|
||||
"theme.DocSidebarItem.expandCategoryAriaLabel": {
|
||||
"message": "展开侧边栏分类 '{label}'",
|
||||
"description": "The ARIA label to expand the sidebar category"
|
||||
},
|
||||
"theme.DocSidebarItem.collapseCategoryAriaLabel": {
|
||||
"message": "折叠侧边栏分类 '{label}'",
|
||||
"description": "The ARIA label to collapse the sidebar category"
|
||||
},
|
||||
"theme.NavBar.navAriaLabel": {
|
||||
"message": "主导航",
|
||||
"description": "The ARIA label for the main navigation"
|
||||
},
|
||||
"theme.navbar.mobileLanguageDropdown.label": {
|
||||
"message": "选择语言",
|
||||
"description": "The label for the mobile language switcher dropdown"
|
||||
},
|
||||
"theme.NotFound.p1": {
|
||||
"message": "我们找不到您要找的页面。",
|
||||
"description": "The first paragraph of the 404 page"
|
||||
},
|
||||
"theme.NotFound.p2": {
|
||||
"message": "请联系原始链接来源网站的所有者,并告知他们链接已损坏。",
|
||||
"description": "The 2nd paragraph of the 404 page"
|
||||
},
|
||||
"theme.TOCCollapsible.toggleButtonLabel": {
|
||||
"message": "本页总览",
|
||||
"description": "The label used by the button on the collapsible TOC component"
|
||||
},
|
||||
"theme.blog.post.readingTime.plurals": {
|
||||
"message": "阅读需 {readingTime} 分钟",
|
||||
"description": "Pluralized label for \"{readingTime} min read\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)"
|
||||
},
|
||||
"theme.blog.post.readMore": {
|
||||
"message": "阅读更多",
|
||||
"description": "The label used in blog post item excerpts to link to full blog posts"
|
||||
},
|
||||
"theme.blog.post.readMoreLabel": {
|
||||
"message": "阅读 {title} 的全文",
|
||||
"description": "The ARIA label for the link to full blog posts from excerpts"
|
||||
},
|
||||
"theme.docs.sidebar.collapseButtonTitle": {
|
||||
"message": "收起侧边栏",
|
||||
"description": "The title attribute for collapse button of doc sidebar"
|
||||
},
|
||||
"theme.docs.sidebar.collapseButtonAriaLabel": {
|
||||
"message": "收起侧边栏",
|
||||
"description": "The title attribute for collapse button of doc sidebar"
|
||||
},
|
||||
"theme.docs.breadcrumbs.home": {
|
||||
"message": "主页面",
|
||||
"description": "The ARIA label for the home page in the breadcrumbs"
|
||||
},
|
||||
"theme.docs.sidebar.navAriaLabel": {
|
||||
"message": "文档侧边栏",
|
||||
"description": "The ARIA label for the sidebar navigation"
|
||||
},
|
||||
"theme.docs.sidebar.closeSidebarButtonAriaLabel": {
|
||||
"message": "关闭导航栏",
|
||||
"description": "The ARIA label for close button of mobile sidebar"
|
||||
},
|
||||
"theme.navbar.mobileSidebarSecondaryMenu.backButtonLabel": {
|
||||
"message": "← 回到主菜单",
|
||||
"description": "The label of the back button to return to main menu, inside the mobile navbar sidebar secondary menu (notably used to display the docs sidebar)"
|
||||
},
|
||||
"theme.docs.sidebar.toggleSidebarButtonAriaLabel": {
|
||||
"message": "切换导航栏",
|
||||
"description": "The ARIA label for hamburger menu button of mobile navigation"
|
||||
},
|
||||
"theme.docs.sidebar.expandButtonTitle": {
|
||||
"message": "展开侧边栏",
|
||||
"description": "The ARIA label and title attribute for expand button of doc sidebar"
|
||||
},
|
||||
"theme.docs.sidebar.expandButtonAriaLabel": {
|
||||
"message": "展开侧边栏",
|
||||
"description": "The ARIA label and title attribute for expand button of doc sidebar"
|
||||
},
|
||||
"theme.SearchBar.seeAll": {
|
||||
"message": "查看全部 {count} 个结果"
|
||||
},
|
||||
"theme.SearchPage.documentsFound.plurals": {
|
||||
"message": "找到 {count} 份文件",
|
||||
"description": "Pluralized label for \"{count} documents found\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)"
|
||||
},
|
||||
"theme.SearchPage.existingResultsTitle": {
|
||||
"message": "「{query}」的搜索结果",
|
||||
"description": "The search page title for non-empty query"
|
||||
},
|
||||
"theme.SearchPage.emptyResultsTitle": {
|
||||
"message": "在文档中搜索",
|
||||
"description": "The search page title for empty query"
|
||||
},
|
||||
"theme.SearchPage.inputPlaceholder": {
|
||||
"message": "在此输入搜索字词",
|
||||
"description": "The placeholder for search page input"
|
||||
},
|
||||
"theme.SearchPage.inputLabel": {
|
||||
"message": "搜索",
|
||||
"description": "The ARIA label for search page input"
|
||||
},
|
||||
"theme.SearchPage.algoliaLabel": {
|
||||
"message": "通过 Algolia 搜索",
|
||||
"description": "The ARIA label for Algolia mention"
|
||||
},
|
||||
"theme.SearchPage.noResultsText": {
|
||||
"message": "未找到任何结果",
|
||||
"description": "The paragraph for empty search result"
|
||||
},
|
||||
"theme.SearchPage.fetchingNewResults": {
|
||||
"message": "正在获取新的搜索结果...",
|
||||
"description": "The paragraph for fetching new search results"
|
||||
},
|
||||
"theme.SearchBar.label": {
|
||||
"message": "搜索",
|
||||
"description": "The ARIA label and placeholder for search button"
|
||||
},
|
||||
"theme.SearchModal.searchBox.resetButtonTitle": {
|
||||
"message": "清除查询",
|
||||
"description": "The label and ARIA label for search box reset button"
|
||||
},
|
||||
"theme.SearchModal.searchBox.cancelButtonText": {
|
||||
"message": "取消",
|
||||
"description": "The label and ARIA label for search box cancel button"
|
||||
},
|
||||
"theme.SearchModal.startScreen.recentSearchesTitle": {
|
||||
"message": "最近搜索",
|
||||
"description": "The title for recent searches"
|
||||
},
|
||||
"theme.SearchModal.startScreen.noRecentSearchesText": {
|
||||
"message": "没有最近搜索",
|
||||
"description": "The text when no recent searches"
|
||||
},
|
||||
"theme.SearchModal.startScreen.saveRecentSearchButtonTitle": {
|
||||
"message": "保存这个搜索",
|
||||
"description": "The label for save recent search button"
|
||||
},
|
||||
"theme.SearchModal.startScreen.removeRecentSearchButtonTitle": {
|
||||
"message": "从历史记录中删除这个搜索",
|
||||
"description": "The label for remove recent search button"
|
||||
},
|
||||
"theme.SearchModal.startScreen.favoriteSearchesTitle": {
|
||||
"message": "收藏",
|
||||
"description": "The title for favorite searches"
|
||||
},
|
||||
"theme.SearchModal.startScreen.removeFavoriteSearchButtonTitle": {
|
||||
"message": "从收藏列表中删除这个搜索",
|
||||
"description": "The label for remove favorite search button"
|
||||
},
|
||||
"theme.SearchModal.errorScreen.titleText": {
|
||||
"message": "无法获取结果",
|
||||
"description": "The title for error screen of search modal"
|
||||
},
|
||||
"theme.SearchModal.errorScreen.helpText": {
|
||||
"message": "你可能需要检查网络连接。",
|
||||
"description": "The help text for error screen of search modal"
|
||||
},
|
||||
"theme.SearchModal.footer.selectText": {
|
||||
"message": "选中",
|
||||
"description": "The explanatory text of the action for the enter key"
|
||||
},
|
||||
"theme.SearchModal.footer.selectKeyAriaLabel": {
|
||||
"message": "Enter 键",
|
||||
"description": "The ARIA label for the Enter key button that makes the selection"
|
||||
},
|
||||
"theme.SearchModal.footer.navigateText": {
|
||||
"message": "导航",
|
||||
"description": "The explanatory text of the action for the Arrow up and Arrow down key"
|
||||
},
|
||||
"theme.SearchModal.footer.navigateUpKeyAriaLabel": {
|
||||
"message": "向上键",
|
||||
"description": "The ARIA label for the Arrow up key button that makes the navigation"
|
||||
},
|
||||
"theme.SearchModal.footer.navigateDownKeyAriaLabel": {
|
||||
"message": "向下键",
|
||||
"description": "The ARIA label for the Arrow down key button that makes the navigation"
|
||||
},
|
||||
"theme.SearchModal.footer.closeText": {
|
||||
"message": "关闭",
|
||||
"description": "The explanatory text of the action for Escape key"
|
||||
},
|
||||
"theme.SearchModal.footer.closeKeyAriaLabel": {
|
||||
"message": "Esc 键",
|
||||
"description": "The ARIA label for the Escape key button that close the modal"
|
||||
},
|
||||
"theme.SearchModal.footer.searchByText": {
|
||||
"message": "搜索提供",
|
||||
"description": "The text explain that the search is making by Algolia"
|
||||
},
|
||||
"theme.SearchModal.noResultsScreen.noResultsText": {
|
||||
"message": "没有结果:",
|
||||
"description": "The text explains that there are no results for the following search"
|
||||
},
|
||||
"theme.SearchModal.noResultsScreen.suggestedQueryText": {
|
||||
"message": "试试搜索",
|
||||
"description": "The text for the suggested query when no results are found for the following search"
|
||||
},
|
||||
"theme.SearchModal.noResultsScreen.reportMissingResultsText": {
|
||||
"message": "认为这个查询应该有结果?",
|
||||
"description": "The text for the question where the user thinks there are missing results"
|
||||
},
|
||||
"theme.SearchModal.noResultsScreen.reportMissingResultsLinkText": {
|
||||
"message": "请告知我们。",
|
||||
"description": "The text for the link to report missing results"
|
||||
},
|
||||
"theme.SearchModal.placeholder": {
|
||||
"message": "搜索文档",
|
||||
"description": "The placeholder of the input of the DocSearch pop-up modal"
|
||||
},
|
||||
"theme.blog.post.plurals": {
|
||||
"message": "{count} 篇博文",
|
||||
"description": "Pluralized label for \"{count} posts\". Use as much plural forms (separated by \"|\") as your language support (see https://www.unicode.org/cldr/cldr-aux/charts/34/supplemental/language_plural_rules.html)"
|
||||
},
|
||||
"theme.blog.tagTitle": {
|
||||
"message": "{nPosts} 含有标签「{tagName}」",
|
||||
"description": "The title of the page for a blog tag"
|
||||
},
|
||||
"theme.blog.author.pageTitle": {
|
||||
"message": "{authorName} - {nPosts}",
|
||||
"description": "The title of the page for a blog author"
|
||||
},
|
||||
"theme.blog.authorsList.pageTitle": {
|
||||
"message": "Authors",
|
||||
"description": "The title of the authors page"
|
||||
},
|
||||
"theme.blog.authorsList.viewAll": {
|
||||
"message": "View All Authors",
|
||||
"description": "The label of the link targeting the blog authors page"
|
||||
},
|
||||
"theme.contentVisibility.unlistedBanner.title": {
|
||||
"message": "未列出页",
|
||||
"description": "The unlisted content banner title"
|
||||
},
|
||||
"theme.contentVisibility.unlistedBanner.message": {
|
||||
"message": "此页面未列出。搜索引擎不会对其索引,只有拥有直接链接的用户才能访问。",
|
||||
"description": "The unlisted content banner message"
|
||||
},
|
||||
"theme.contentVisibility.draftBanner.title": {
|
||||
"message": "Draft page",
|
||||
"description": "The draft content banner title"
|
||||
},
|
||||
"theme.contentVisibility.draftBanner.message": {
|
||||
"message": "This page is a draft. It will only be visible in dev and be excluded from the production build.",
|
||||
"description": "The draft content banner message"
|
||||
},
|
||||
"theme.ErrorPageContent.tryAgain": {
|
||||
"message": "重试",
|
||||
"description": "The label of the button to try again rendering when the React error boundary captures an error"
|
||||
},
|
||||
"theme.common.skipToMainContent": {
|
||||
"message": "跳到主要内容",
|
||||
"description": "The skip to content label used for accessibility, allowing to rapidly navigate to main content with keyboard tab/enter navigation"
|
||||
},
|
||||
"theme.tags.tagsPageTitle": {
|
||||
"message": "标签",
|
||||
"description": "The title of the tag list page"
|
||||
}
|
||||
}
|
||||
14
docs/i18n/zh-CN/docusaurus-plugin-content-blog/options.json
Normal file
14
docs/i18n/zh-CN/docusaurus-plugin-content-blog/options.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"title": {
|
||||
"message": "Blog",
|
||||
"description": "The title for the blog used in SEO"
|
||||
},
|
||||
"description": {
|
||||
"message": "Blog",
|
||||
"description": "The description for the blog used in SEO"
|
||||
},
|
||||
"sidebar.title": {
|
||||
"message": "Recent posts",
|
||||
"description": "The label for the left sidebar"
|
||||
}
|
||||
}
|
||||
50
docs/i18n/zh-CN/docusaurus-plugin-content-docs/current.json
Normal file
50
docs/i18n/zh-CN/docusaurus-plugin-content-docs/current.json
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
{
|
||||
"version.label": {
|
||||
"message": "Next",
|
||||
"description": "The label for version current"
|
||||
},
|
||||
"sidebar.docsSidebar.category.Getting started": {
|
||||
"message": "开始",
|
||||
"description": "The label for category Getting started in sidebar docsSidebar"
|
||||
},
|
||||
"sidebar.docsSidebar.category.Chat": {
|
||||
"message": "聊天",
|
||||
"description": "The label for category Chat in sidebar docsSidebar"
|
||||
},
|
||||
"sidebar.docsSidebar.category.Autocomplete": {
|
||||
"message": "自动补全",
|
||||
"description": "The label for category Autocomplete in sidebar docsSidebar"
|
||||
},
|
||||
"sidebar.docsSidebar.category.Edit": {
|
||||
"message": "编辑",
|
||||
"description": "The label for category Edit in sidebar docsSidebar"
|
||||
},
|
||||
"sidebar.docsSidebar.category.Actions": {
|
||||
"message": "Actions",
|
||||
"description": "The label for category Actions in sidebar docsSidebar"
|
||||
},
|
||||
"sidebar.docsSidebar.link.Customize": {
|
||||
"message": "定制",
|
||||
"description": "The label for link Customize in sidebar docsSidebar, linking to /customize/overview"
|
||||
},
|
||||
"sidebar.customizingSidebar.category.Model providers": {
|
||||
"message": "模型提供者",
|
||||
"description": "The label for category Model providers in sidebar customizingSidebar"
|
||||
},
|
||||
"sidebar.customizingSidebar.category.More": {
|
||||
"message": "更多",
|
||||
"description": "The label for category More in sidebar customizingSidebar"
|
||||
},
|
||||
"sidebar.customizingSidebar.category.Model types": {
|
||||
"message": "模型类型",
|
||||
"description": "The label for category Model types in sidebar customizingSidebar"
|
||||
},
|
||||
"sidebar.customizingSidebar.category.Deep dives": {
|
||||
"message": "深入理解",
|
||||
"description": "The label for category Deep dives in sidebar customizingSidebar"
|
||||
},
|
||||
"sidebar.customizingSidebar.category.Tutorials": {
|
||||
"message": "教程",
|
||||
"description": "The label for category Tutorials in sidebar customizingSidebar"
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,36 @@
|
|||
---
|
||||
title: 上下文选择
|
||||
description: Actions \-上下文选择
|
||||
keywords: [上下文, 斜杠, 调试, 快速修复, 右击]
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
## 斜杠命令
|
||||
|
||||
斜杠命令可以与更多的指令结合,包括 [上下文提供者](chat/context-selection.md) 或 [高亮代码](chat/context-selection.md) 。
|
||||
|
||||
例如,使用 "/edit" 斜杠命令,你应该描述你想要 LLM 执行的编辑。
|
||||
|
||||
一些斜杠命令不会理会你的输入,例如, "/share" 斜杠命令只是创建一个当前交谈的 markdown 副本,忽略任何你请求它做的。
|
||||
|
||||
## 快速 action
|
||||
|
||||
快速 action 总是显示在一个类和函数上,将会编辑那个类或函数,但是不会对外面的东西有影响。
|
||||
|
||||
## 右击 action
|
||||
|
||||
你选择的高亮代码将会包含在你的提示词中,和一些基于选择的 action 提前写好的指令一起。这是模型想要尝试的仅有的代码块。
|
||||
|
||||
## 调试 action
|
||||
|
||||
调试 action 选择最近运行的终端命令以及它的输出,然后插入以下提示词到聊天窗口中。没有更多的,不可见的信息发送给语言模型。
|
||||
|
||||
```
|
||||
I got the following error, can you please help explain how to fix it?
|
||||
|
||||
[ERROR_MESSAGE]
|
||||
```
|
||||
|
||||
## 快速修复
|
||||
|
||||
类似于调试 action ,快速 action 透明地添加提示词到聊天窗口中。当你选择 "Ask Continue" ,错误的上下 3 行会发送给聊天,跟上问题 "How do I fix the following problem in the above code?: [ERROR_MESSAGE]" 。
|
||||
|
|
@ -0,0 +1,12 @@
|
|||
---
|
||||
title: 它是如何工作的
|
||||
description: actions 是如何工作的
|
||||
keywords: [如何, 斜杠, 命令, 提示词, 右击, 快速修复, 调试, action]
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
很多 action 基于模板提示词,可以使用 .prompt 文件配置,在底层有一些执行更复杂的代码。
|
||||
|
||||
action 生成行内 diff ,比如 "/edit", "/comment" 或右击 action ,使用与 [编辑](edit/how-it-works.md) 相同的提示词和响应处理逻辑。
|
||||
|
||||
要了解其他斜杠命令如何工作的, [在这里](../customize/slash-commands.md) 查看完整参考。
|
||||
|
|
@ -0,0 +1,58 @@
|
|||
---
|
||||
title: 如何定制
|
||||
description: 如何定制 actions
|
||||
keywords: [定制, actions]
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
## 内置的斜杠命令
|
||||
|
||||
Continue 有一个大的内置斜杠命令库,但是当你首次安装时,我们只显示最常用的一些,比如 "/edit", "/comment" 和 "/share" 。为了添加更多的 action ,你可以打开 [config.json](../customize/config.mdx) 并添加它们到 `slashCommands` 列表中。
|
||||
|
||||
## 定制斜杠命令
|
||||
|
||||
有两种方法添加定制斜杠命令:
|
||||
|
||||
1. 使用 `.prompt` 文件 - 这是大多数情况下推荐的。[在这里](../customize/deep-dives/prompt-files.md) 查看完整参考。
|
||||
2. 使用 `config.ts` - 这给你对于 LLM, IDE 和其他重要的入口可编程的访问,通过编写 JavaScript/TypeScript 函数
|
||||
|
||||
### 使用 `config.ts` 定制斜杠命令
|
||||
|
||||
<!-- TODO: We need a config.ts reference -->
|
||||
<!-- :::tip[config.ts]
|
||||
Before adding a custom slash command, we recommend reading the [introduction to `config.ts`](../customize/config.mdx).
|
||||
::: -->
|
||||
|
||||
如果你想比使用自然语言编写定制命令更进一步,你可以编写一个定制函数返回响应。这需要使用 `config.ts` 替代 `config.json` 。
|
||||
|
||||
要做这个,放一个新的 `SlashCommand` 对象到 `slashCommands` 列表中。这个对象包含 "name" ,你输入用来触发斜杠命令的名字, "description", 在下拉菜单中看到的描述,以及 "run" 。 `run` 函数是任何异步生成器,应该生成你希望流式地返回到 UI 的字符串。作为这个函数的一个参数,你可以访问 `ContinueSDK` 对象实用工具,例如访问 IDE 中确定的信息/action ,当前的语言模型,以及一些其他的实用工具。例如,这是一个生成 commit 说明的斜杠命令:
|
||||
|
||||
```typescript title="config.ts"
|
||||
export function modifyConfig(config: Config): Config {
|
||||
config.slashCommands?.push({
|
||||
name: "commit",
|
||||
description: "Write a commit message",
|
||||
run: async function* (sdk) {
|
||||
const diff = await sdk.ide.getDiff();
|
||||
for await (const message of sdk.llm.streamComplete(
|
||||
`${diff}\n\nWrite a commit message for the above changes. Use no more than 20 tokens to give a brief description in the imperative mood (e.g. 'Add feature' not 'Added feature'):`,
|
||||
{
|
||||
maxTokens: 20,
|
||||
},
|
||||
)) {
|
||||
yield message;
|
||||
}
|
||||
},
|
||||
});
|
||||
return config;
|
||||
}
|
||||
```
|
||||
|
||||
<!-- TODO: We need a config.ts reference -->
|
||||
<!-- For full `config.ts` reference, see [here](reference/config-ts.md). -->
|
||||
|
||||
## 其他定制 action
|
||||
|
||||
目前,其他 action 触发器没有开放配置,但是我们计划在未来通过 .prompt 文件来允许。
|
||||
|
||||
<!-- For any actions defined in a .prompt file, you can [configure a specific model](TODO). -->
|
||||
|
|
@ -0,0 +1,85 @@
|
|||
---
|
||||
title: Actions
|
||||
description: 如何使用 Actions
|
||||
sidebar_label: 如何使用它
|
||||
keywords: [如何, 斜杠, 命令, 提示词, 右击, 快速修复, 调试, 操作]
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||

|
||||
|
||||
## 如何使用它
|
||||
|
||||
Actions 是常见用例的快捷方式。例如,你可能想要审查代码,编写测试,或添加一个文档字符串。
|
||||
|
||||
### 斜杠命令
|
||||
|
||||
最常见的调用 action 的方法是使用斜杠命令。通过输入 '/' 并在下拉框中选择,这里有快捷方式会被激活。例如,内置的 '/edit' 斜杠命令,让你可以直接在你的编辑器中流式地编辑。
|
||||
|
||||

|
||||
|
||||
一些最常用的斜杠命令默认是可用的,比如 "/edit", "/comment" 和 "/share" ,但是 Continue 有大量内置的其他选择的库。要启用它们,[在这里](../customize/slash-commands.md) 了解更多。
|
||||
|
||||
### prompt 文件
|
||||
|
||||
通过定义一个 ".prompt 文件" ,也可以编写你自己的斜杠命令。 prompt 文件可以是个简单的文本文件,但是也包含模板,所以你可以引用文件, URL ,高亮代码以及更多。
|
||||
|
||||
完整的 .prompt 文件可以参考 [这里](../customize/deep-dives/prompt-files.md) 。
|
||||
|
||||
:::tip[Prompt 库]
|
||||
为了帮助你开始,[我们精心编写了一个小的 `.prompt` 文件库](https://github.com/continuedev/prompt-file-examples) 。我们鼓励社区贡献到这个仓库,所以请考虑为你的 prompt 创建一个拉取请求!
|
||||
:::
|
||||
|
||||
以下是一个快速示例,设置一个使用 Jest 编写单元测试的 prompt 文件。
|
||||
|
||||
1. 在你的工作区的最高层级,创建一个名为 `.prompts/` 的目录。
|
||||
2. 在这个目录中,添加一个名为 `test.prompt` 的文件。这个文件的名称将是你用来生成提示词的斜杠命令的名称。
|
||||
3. 写入以下内容到 `test.prompt` 并保存。
|
||||
|
||||
```
|
||||
{{{ input }}}
|
||||
|
||||
Write unit tests for the above selected code, following each of these instructions:
|
||||
- Use `jest`
|
||||
- Properly set up and tear down
|
||||
- Include important edge cases
|
||||
- The tests should be complete and sophisticated
|
||||
- Give the tests just as chat output, don't edit any file
|
||||
- Don't explain how to set up `jest`
|
||||
```
|
||||
|
||||
现在要使用这个提示词,你可以高亮代码,并使用 `cmd/ctrl+L` 来选择它到 Continue 侧边栏中。
|
||||
|
||||
然后,输入 "/" 来查看斜杠命令列表,选择名为 "test" 的那个。按下回车, LLM 会响应你的 prompt 文件中给出的指令。
|
||||
|
||||
### action 的其他触发器 (VS Code)
|
||||
|
||||
:::info
|
||||
目前,所有这些只在 VS Code 中有效
|
||||
:::
|
||||
|
||||
为了让常见用例更可用,我们提供了一些其他方法来触发 action 。
|
||||
|
||||
#### 快速 action
|
||||
|
||||
快速 action 在你源码中的顶级类和函数上显示为按钮,让你可以一键触发 action 。它们也可以使用 .prompt 文件定制,来执行定制的 action 。
|
||||
|
||||

|
||||
|
||||
默认情况下,快速 action 是禁用的,但是可以在 VS Code 的设置中通过 "Continue: Enable Quick Actions" 启用。
|
||||
|
||||
#### 右击 action
|
||||
|
||||
右击 action 让你高亮期望的代码区域,右击,然后在下拉菜单中选择一个 action 。
|
||||
|
||||

|
||||
|
||||
#### 调试 action
|
||||
|
||||
调试 action 是 VS Code 扩展中一个特殊的内置键盘快捷方式。使用 `cmd/ctrl+shift+R` 来快速复制当前终端的内容到聊天侧边栏,并获得调试建议。
|
||||
|
||||
#### 快速修复
|
||||
|
||||
无论何时在你的代码中看到红色/黄色下划线表示错误,你可以把光标放到附近, VS Code 会显示一个灯泡图标。无论点击灯泡,或使用 `cmd/ctrl+.` 快捷键,将会显示一个快速修复的下拉菜单。其中之一是 "Ask Continue" action 。无论单击或再次使用 `cmd/ctrl+.` , Continue 将尝试帮助解决问题。
|
||||
|
||||

|
||||
|
|
@ -0,0 +1,8 @@
|
|||
---
|
||||
title: 模型设置
|
||||
description: Actions 模型设置
|
||||
keywords: [模型]
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
默认情况下, action 使用与 [聊天](chat/model-setup.mdx) 相同的模型,所以,对于执行的复杂指令,我们推荐相同的 400B+ 参数模型或者领先的模型之一。
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
---
|
||||
title: 上下文选择
|
||||
description: 自动补全上下文选择
|
||||
keywords: [上下文, 自动补全, lsp, 最近的]
|
||||
sidebar_position: 3
|
||||
---
|
||||
|
||||
自动补全会基于当前的光标位置自动地确定上下文。我们使用以下的技术来确定什么包含在提示词中:
|
||||
|
||||
### 文件前缀/后缀
|
||||
|
||||
我们总是包含你的文件中光标前后的代码。
|
||||
|
||||
### 来自语言服务协议的定义
|
||||
|
||||
类似于你如何在编辑器中使用 `cmd/ctrl + click` ,我们使用相同的工具 (LSP) 来增强 "转到定义" 。例如,如果你输入一个函数调用,我们将包含函数定义。或者,如果你在一个方法中写代码,我们将包含类型定义中的任何参数或返回类型。
|
||||
|
||||
### 导入文件
|
||||
|
||||
因为通常有很多导入,我们不能包含它们所有。相反,我们查找你的光标附近的标识,使用它所匹配的导入作为上下文。
|
||||
|
||||
### 最近的文件
|
||||
|
||||
我们自动考虑最近打开的或编辑的文件,并包含与当前补全相关的片段。
|
||||
|
|
@ -0,0 +1,33 @@
|
|||
---
|
||||
title: 它是如何工作的
|
||||
description: 自动补全是如何工作的
|
||||
keywords: [如何, 自动补全, 上下分]
|
||||
sidebar_position: 4
|
||||
---
|
||||
|
||||
自动补全是一个 [复合人工智能系统](https://bair.berkeley.edu/blog/2024/02/18/compound-ai-systems/),使用检索方法和响应处理技术的结合。系统可以大致理解为三个部分。
|
||||
|
||||
## 时机
|
||||
|
||||
为了快速地显示建议,并且不需要发送太多请求,我们做了下面这些:
|
||||
|
||||
- 去抖动: 如果你快速输入,我们不会为每个按键创建一个请求。相反,我们等待直到你完成输入。
|
||||
- 缓存: 如果你的光标在一个我们已经生成补全的位置,这个补全将会被使用。例如,如果你回退,我们将可以直接显示你之前看到的建议。
|
||||
|
||||
## 上下文
|
||||
|
||||
就像 [上下文选择](context-selection.md) 页面解释的那样, Continue 使用了大量的检索方法,来查找你的代码库中相关的片断,包含在提示词中。
|
||||
|
||||
## 过滤
|
||||
|
||||
语言模型不是完美的,但是可以通过调整它们的输出接近完美。在显示建议之前,我们对响应做了大量的后处理,包括:
|
||||
|
||||
- 过滤出指定的 token
|
||||
- 当重新生成代码时,提前停止
|
||||
- 修复缩进
|
||||
|
||||
如果响应是坏的,我们也会偶尔过滤掉整个响应。这通常是因为过度的重复。
|
||||
|
||||
You can learn more about how it works in the [Autocomplete deep dive](../customize/deep-dives/autocomplete.md).
|
||||
|
||||
你可以在 [深入理解自动补全](../customize/deep-dives/autocomplete.md) 中了解它是如何工作的。
|
||||
|
|
@ -0,0 +1,24 @@
|
|||
---
|
||||
title: 如何定制
|
||||
description: 如何定制自动补全
|
||||
keywords: [定制]
|
||||
sidebar_position: 5
|
||||
---
|
||||
|
||||
Continue 在 [`config.json`](../customize/config.mdx) 提供少量的参数,对于你的特定需求和硬件能力,可以调整找到建议质量和系统性能之间的最佳平衡:
|
||||
|
||||
```json title="config.json"
|
||||
"tabAutocompleteOptions": {
|
||||
"useCopyBuffer": false,
|
||||
"maxPromptTokens": 400,
|
||||
"prefixPercentage": 0.5,
|
||||
"multilineCompletions": "always"
|
||||
}
|
||||
```
|
||||
|
||||
- `useCopyBuffer`: 决定剪贴板的内容是否包含在提示词构建中
|
||||
- `maxPromptTokens`: 设置提示词的最大 token 数,平衡上下文和速度
|
||||
- `prefixPercentage`: 决定提示词使用光标前代码的比例
|
||||
- `multilineCompletions`: 控制建议是否可以跨多行 ("always", "never" 或 "auto")
|
||||
|
||||
对于所有配置选项和它们的影响的综合指南,查看 [深入理解自动补全](../customize/deep-dives/autocomplete.md) 。
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
---
|
||||
title: 自动补全
|
||||
description: 自动补全 \- 如何使用它
|
||||
sidebar_label: 如何使用它
|
||||
keywords: [如何]
|
||||
sidebar_position: 1
|
||||
---
|
||||
|
||||

|
||||
|
||||
## 如何使用它
|
||||
|
||||
自动补全随着你的输入提供行内代码建议。要启用它,只需要简单地点击状态栏中的 "Continue" 按钮,在你的 IDE 右下侧,或者在你的 IDE 设置中勾选 "启用 Tab 自动补全" 选项。
|
||||
|
||||
### 接受整个建议
|
||||
|
||||
按下 `Tab` ,接受整个建议
|
||||
|
||||
### 拒绝整个建议
|
||||
|
||||
按下 `Esc` ,拒绝整个建议
|
||||
|
||||
### 部分接受建议
|
||||
|
||||
对于更细粒度的控制,使用 `cmd/ctrl + →` 来逐字地接受部分建议。
|
||||
|
|
@ -0,0 +1,52 @@
|
|||
---
|
||||
title: 模型设置
|
||||
description: 自动补全 \- 模型设置
|
||||
keywords: [模型, 自动补全]
|
||||
sidebar_position: 2
|
||||
---
|
||||
|
||||
## 最好的总体体验
|
||||
|
||||
为了最好的自动补全体验,我们推荐通过 [Mistral API](https://console.mistral.ai/) 使用 Codestral 。这个模型提供高质量的补全,使用极好的代码上下文理解:
|
||||
|
||||
```json title="config.json""
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "Codestral",
|
||||
"provider": "mistral",
|
||||
"model": "codestral-latest",
|
||||
"apiKey": "YOUR_API_KEY"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
:::tip[Codestral API Key]
|
||||
Codestral 的 API key 和通常的 Mistral API 是不同的。如果你使用 Codestral ,你可能想要一个 Codestral API key ,但是如果你想分享 key 给团队或其他人想要使用 `api.mistral.ai` ,那么确保在你的 `tabAutocompleteModel` 中设置 `"apiBase": "https://api.mistral.ai/v1"` 。
|
||||
:::
|
||||
|
||||
## 本地的,离线的/自托管的体验
|
||||
|
||||
对于倾向于本地执行或自托管的, `StarCoder2-3b` 提供了一个对于大多数用户性能和质量的平衡:
|
||||
|
||||
```json title="config.json""
|
||||
{
|
||||
"tabAutocompleteModel": {
|
||||
"title": "StarCoder2-3b",
|
||||
"model": "starcoder2:3b",
|
||||
"provider": "ollama"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## 可替代的体验
|
||||
|
||||
- 补全太慢?在更弱的机器上,试试 `deepseek-coder:1.3b-base` 更快的补全
|
||||
- 有更多的计算?使用 `deepseek-coder:6.7b-base` 获取可能更高质量的建议
|
||||
|
||||
:::note
|
||||
对于 LM Studio 用户,导航到 "My Models" 章节,找到你想要的模型,复制它的路径 (例如, second-state/StarCoder2-3B-GGUF/starcoder2-3b-Q8_0.gguf) 。使用这个路径作为你的配置中的 `model` 值。
|
||||
:::
|
||||
|
||||
## 其他体验
|
||||
|
||||
有很多更多的模型或提供者可以用来补全。在 [这里](../customize/model-types/autocomplete.md) 查看它们。
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Reference in a new issue