From 7105be0bee800d9a67cde3271866eacdac57b1d6 Mon Sep 17 00:00:00 2001 From: Nate Date: Mon, 11 Nov 2024 19:37:24 -0800 Subject: [PATCH 01/18] .instructions file --- .instructions | 1 + core/config/getSystemPromptDotFile.ts | 27 +++++++++++++++++++ core/config/load.ts | 6 +++++ .../continue/IdeProtocolClient.kt | 2 +- extensions/vscode/package-lock.json | 4 +-- .../vscode/src/extension/VsCodeExtension.ts | 12 ++++++--- 6 files changed, 45 insertions(+), 7 deletions(-) create mode 100644 .instructions create mode 100644 core/config/getSystemPromptDotFile.ts diff --git a/.instructions b/.instructions new file mode 100644 index 000000000..bad5d9689 --- /dev/null +++ b/.instructions @@ -0,0 +1 @@ +Give concise responses. diff --git a/core/config/getSystemPromptDotFile.ts b/core/config/getSystemPromptDotFile.ts new file mode 100644 index 000000000..ae6cd41f2 --- /dev/null +++ b/core/config/getSystemPromptDotFile.ts @@ -0,0 +1,27 @@ +import { IDE } from ".."; + +export const SYSTEM_PROMPT_DOT_FILE = ".instructions"; + +export async function getSystemPromptDotFile(ide: IDE): Promise { + 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"); +} diff --git a/core/config/load.ts b/core/config/load.ts index a10948210..226e678f4 100644 --- a/core/config/load.ts +++ b/core/config/load.ts @@ -64,6 +64,7 @@ import { defaultSlashCommandsJetBrains, defaultSlashCommandsVscode, } from "./default"; +import { getSystemPromptDotFile } from "./getSystemPromptDotFile"; import { DEFAULT_PROMPTS_FOLDER, getPromptFiles, @@ -732,6 +733,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); diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt index b773026bd..c2a35a918 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/IdeProtocolClient.kt @@ -105,7 +105,7 @@ class AsyncFileSaveListener(private val ideProtocolClient: IdeProtocolClient) : for (event in events) { if (event.path.endsWith(".continue/config.json") || event.path.endsWith(".continue/config.ts") || event.path.endsWith( ".continue\\config.json" - ) || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json") + ) || event.path.endsWith(".continue\\config.ts") || event.path.endsWith(".continuerc.json") || event.path.endsWith(".continuerc.json") ) { return object : AsyncFileListener.ChangeApplier { override fun afterVfsChange() { diff --git a/extensions/vscode/package-lock.json b/extensions/vscode/package-lock.json index 3f6ace66f..661eca42c 100644 --- a/extensions/vscode/package-lock.json +++ b/extensions/vscode/package-lock.json @@ -1,12 +1,12 @@ { "name": "continue", - "version": "0.9.226", + "version": "0.9.227", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "continue", - "version": "0.9.226", + "version": "0.9.227", "license": "Apache-2.0", "dependencies": { "@electron/rebuild": "^3.2.10", diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index f8bc7c556..06e498c55 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -284,7 +284,8 @@ export class VsCodeExtension { if ( filepath.endsWith(".continuerc.json") || - filepath.endsWith(".prompt") + filepath.endsWith(".prompt") || + filepath.endsWith(".instructions") ) { this.configHandler.reloadConfig(); } else if ( @@ -296,14 +297,16 @@ export class VsCodeExtension { } else { // Reindex the file this.core.invoke("index/forceReIndex", { - dirs: [filepath] + dirs: [filepath], }); } }); vscode.workspace.onDidDeleteFiles(async (event) => { this.core.invoke("index/forceReIndex", { - dirs: event.files.map((file) => file.fsPath.split("/").slice(0, -1).join("/")) + dirs: event.files.map((file) => + file.fsPath.split("/").slice(0, -1).join("/"), + ), }); }); @@ -352,7 +355,8 @@ export class VsCodeExtension { // Register a content provider for the readonly virtual documents const documentContentProvider = new (class - implements vscode.TextDocumentContentProvider { + implements vscode.TextDocumentContentProvider + { // emitter and its event onDidChangeEmitter = new vscode.EventEmitter(); onDidChange = this.onDidChangeEmitter.event; From eadc96ebef6653a996dff32095fd87a86703058d Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 12 Nov 2024 13:31:13 -0800 Subject: [PATCH 02/18] feat: php definitions --- .../RootPathContextService.ts | 23 +++++ .../test/RootPathContextService.test.ts | 90 ++++++++++--------- .../root-path-context/test/files/file1.php | 32 +++++++ .../function_definition/php.scm | 10 +++ 4 files changed, 115 insertions(+), 40 deletions(-) create mode 100644 core/autocomplete/context/root-path-context/test/files/file1.php create mode 100644 extensions/vscode/tree-sitter/root-path-context-queries/function_definition/php.scm diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index accd4f6df..6f163c265 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -9,6 +9,21 @@ 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({ max: 100, @@ -58,12 +73,17 @@ export class RootPathContextService { this.importDefinitionsService.get(filepath); break; default: + console.log(getSyntaxTreeString(node)); + query = await getQueryForFile( filepath, `root-path-context-queries/${node.type}`, ); break; } + const type = node.type; + + debugger; if (!query) { return snippets; @@ -115,6 +135,9 @@ 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 = diff --git a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts index 196a7b643..f0af54a45 100644 --- a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts +++ b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts @@ -1,49 +1,59 @@ import { testRootPathContext } from "./testUtils"; const TEST_CASES = [ - { - nodeType: "function_declaration", - fileName: "file1.ts", - language: "TypeScript", - cursorPosition: { line: 10, character: 24 }, - definitionPositions: [ - { row: 9, column: 34 }, // Person - { row: 9, column: 44 }, // Address - ], - }, - { - nodeType: "method_declaration", - fileName: "file1.ts", - language: "TypeScript", - cursorPosition: { line: 22, character: 30 }, - definitionPositions: [ - { 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: "function_declaration", + // fileName: "file1.ts", + // language: "TypeScript", + // cursorPosition: { line: 10, character: 24 }, + // definitionPositions: [ + // { row: 9, column: 34 }, // Person + // { row: 9, column: 44 }, // Address + // ], + // }, + // { + // nodeType: "method_declaration", + // fileName: "file1.ts", + // language: "TypeScript", + // cursorPosition: { line: 22, character: 30 }, + // definitionPositions: [ + // { 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: "function_definition", + // fileName: "file1.py", + // language: "Python", + // cursorPosition: { line: 4, character: 25 }, + // definitionPositions: [ + // { row: 3, column: 30 }, // Person + // { row: 3, column: 42 }, // Address + // ], + // }, + // { + // nodeType: "function_definition (inside a class)", + // fileName: "file1.py", + // language: "Python", + // cursorPosition: { line: 12, character: 33 }, + // definitionPositions: [ + // { row: 6, column: 21 }, // BaseClass + // { row: 6, column: 33 }, // Collection + // { row: 11, column: 47 }, // Person + // { row: 11, column: 59 }, // Address + // ], + // }, { nodeType: "function_definition", - fileName: "file1.py", - language: "Python", - cursorPosition: { line: 4, character: 25 }, + fileName: "file1.php", + language: "PHP", + cursorPosition: { line: 12, character: 32 }, definitionPositions: [ - { row: 3, column: 30 }, // Person - { row: 3, column: 42 }, // Address - ], - }, - { - nodeType: "function_definition (inside a class)", - fileName: "file1.py", - language: "Python", - cursorPosition: { line: 12, character: 33 }, - definitionPositions: [ - { row: 6, column: 21 }, // BaseClass - { row: 6, column: 33 }, // Collection - { row: 11, column: 47 }, // Person - { row: 11, column: 59 }, // Address + { row: 10, column: 26 }, // Person + { row: 10, column: 44 }, // Address ], }, ]; diff --git a/core/autocomplete/context/root-path-context/test/files/file1.php b/core/autocomplete/context/root-path-context/test/files/file1.php new file mode 100644 index 000000000..a72f805e0 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/files/file1.php @@ -0,0 +1,32 @@ +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); + } +} + +?> \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/function_definition/php.scm b/extensions/vscode/tree-sitter/root-path-context-queries/function_definition/php.scm new file mode 100644 index 000000000..3f9303ae1 --- /dev/null +++ b/extensions/vscode/tree-sitter/root-path-context-queries/function_definition/php.scm @@ -0,0 +1,10 @@ +( + (function_definition + parameters: (formal_parameters + (simple_parameter + type: (named_type) @param_type + )* + ) + return_type: (named_type) @return_type + ) +) \ No newline at end of file From 0c74f936a3d1358f5d7d0a5a10ead73c7ac9d59d Mon Sep 17 00:00:00 2001 From: "Johnny.H" Date: Wed, 13 Nov 2024 19:11:02 +0800 Subject: [PATCH 03/18] Fix: https://github.com/continuedev/continue/issues/2896 --- .../activities/ContinuePluginStartupActivity.kt | 4 +--- .../continueintellijextension/continue/CoreMessenger.kt | 9 ++++++++- .../services/ContinuePluginService.kt | 4 ++++ 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt index 509bc44ce..fa39729fa 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/activities/ContinuePluginStartupActivity.kt @@ -71,7 +71,6 @@ private fun getTutorialFileName(): String { } class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { - private val coroutineScope = CoroutineScope(Dispatchers.IO) override fun runActivity(project: Project) { removeShortcutFromAction(getPlatformSpecificKeyStroke("J")) @@ -110,6 +109,7 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { } private fun initializePlugin(project: Project) { + val coroutineScope = CoroutineScope(Dispatchers.IO) val continuePluginService = ServiceManager.getService( project, ContinuePluginService::class.java @@ -234,7 +234,5 @@ class ContinuePluginStartupActivity : StartupActivity, Disposable, DumbAware { } override fun dispose() { - // Cleanup resources here - coroutineScope.cancel() } } \ No newline at end of file diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt index aaa6ce28d..178ae4059 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/continue/CoreMessenger.kt @@ -19,7 +19,7 @@ class CoreMessenger( private val project: Project, continueCorePath: String, private val ideProtocolClient: IdeProtocolClient, - coroutineScope: CoroutineScope + val coroutineScope: CoroutineScope ) { private var writer: Writer? = null private var reader: BufferedReader? = null @@ -232,4 +232,11 @@ class CoreMessenger( } } } + + fun killSubProcess() { + process?.isAlive?.let { + exitCallbacks.clear() + process?.destroy() + } + } } diff --git a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt index 7318d2731..87b08f829 100644 --- a/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt +++ b/extensions/intellij/src/main/kotlin/com/github/continuedev/continueintellijextension/services/ContinuePluginService.kt @@ -34,6 +34,10 @@ class ContinuePluginService(project: Project) : Disposable, DumbAware { override fun dispose() { coroutineScope.cancel() + coreMessenger?.coroutineScope?.let { + it.cancel() + coreMessenger?.killSubProcess() + } } fun sendToWebview( From af26938a9916ae8057e806221fa6b23f03d8232d Mon Sep 17 00:00:00 2001 From: Test Date: Wed, 13 Nov 2024 10:04:34 -0800 Subject: [PATCH 04/18] bugfix: get codeblocks for pretoolbar --- gui/src/components/markdown/StyledMarkdownPreview.tsx | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/gui/src/components/markdown/StyledMarkdownPreview.tsx b/gui/src/components/markdown/StyledMarkdownPreview.tsx index 77158e96a..a86a295c9 100644 --- a/gui/src/components/markdown/StyledMarkdownPreview.tsx +++ b/gui/src/components/markdown/StyledMarkdownPreview.tsx @@ -136,13 +136,12 @@ function processCodeBlocks(tree: any) { node.lang = node.lang.split(".").slice(-1)[0]; } + node.data = node.data || {}; + node.data.hProperties = node.data.hProperties || {}; + node.data.hProperties.codeBlockContent = node.value; + node.data.hProperties.isGeneratingCodeBlock = lastCodeNode === node; + if (node.meta) { - node.data = node.data || {}; - node.data.hProperties = node.data.hProperties || {}; - - node.data.hProperties.isGeneratingCodeBlock = lastCodeNode === node; - node.data.hProperties.codeBlockContent = node.value; - let meta = node.meta.split(" "); node.data.hProperties.filepath = meta[0]; node.data.hProperties.range = meta[1]; From ce784e19c60a5c3f4b5ba3c0dc991587121790a4 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 13 Nov 2024 10:16:26 -0800 Subject: [PATCH 05/18] recommend qwen2.5-coder:1.5b --- core/autocomplete/README.md | 22 +++++++-------- core/config/onboarding.ts | 4 +-- docs/docs/autocomplete/model-setup.md | 13 ++++----- .../docs/customize/deep-dives/autocomplete.md | 14 ++++------ .../model-providers/top-level/ollama.md | 6 ++-- .../customize/model-types/autocomplete.md | 2 +- extensions/vscode/config_schema.json | 28 ++++++++++++++++--- .../vscode/src/util/loadAutocompleteModel.ts | 2 +- 8 files changed, 51 insertions(+), 40 deletions(-) diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md index c02be2b01..9baf9cd4b 100644 --- a/core/autocomplete/README.md +++ b/core/autocomplete/README.md @@ -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://" }, "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). diff --git a/core/config/onboarding.ts b/core/config/onboarding.ts index fa6d54945..6b05ca59f 100644 --- a/core/config/onboarding.ts +++ b/core/config/onboarding.ts @@ -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, }, diff --git a/docs/docs/autocomplete/model-setup.md b/docs/docs/autocomplete/model-setup.md index 05136e546..8aae88c75 100644 --- a/docs/docs/autocomplete/model-setup.md +++ b/docs/docs/autocomplete/model-setup.md @@ -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. ::: diff --git a/docs/docs/customize/deep-dives/autocomplete.md b/docs/docs/customize/deep-dives/autocomplete.md index 2ae2435d5..9e03aa756 100644 --- a/docs/docs/customize/deep-dives/autocomplete.md +++ b/docs/docs/customize/deep-dives/autocomplete.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://" }, ... @@ -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://" }, "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: cmd/ctrl + shift + P -> "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 cmd/ctrl + , 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. diff --git a/docs/docs/customize/model-providers/top-level/ollama.md b/docs/docs/customize/model-providers/top-level/ollama.md index ae97d30c3..ed96ac385 100644 --- a/docs/docs/customize/model-providers/top-level/ollama.md +++ b/docs/docs/customize/model-providers/top-level/ollama.md @@ -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" } } ``` diff --git a/docs/docs/customize/model-types/autocomplete.md b/docs/docs/customize/model-types/autocomplete.md index 64d39c893..d85920605 100644 --- a/docs/docs/customize/model-types/autocomplete.md +++ b/docs/docs/customize/model-types/autocomplete.md @@ -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). diff --git a/extensions/vscode/config_schema.json b/extensions/vscode/config_schema.json index a0535391f..eb75d1f90 100644 --- a/extensions/vscode/config_schema.json +++ b/extensions/vscode/config_schema.json @@ -772,6 +772,11 @@ "mistral-tiny", "mistral-small", "mistral-medium", + "qwen2.5-coder:1.5b", + "qwen2.5-coder:3b", + "qwen2.5-coder:7b", + "qwen2.5-coder:14b", + "qwen2.5-coder:32b", "AUTODETECT" ] }, @@ -1028,7 +1033,12 @@ "stable-code-3b", "starcoder-1b", "starcoder-3b", - "starcoder2-3b" + "starcoder2-3b", + "qwen2.5-coder:1.5b", + "qwen2.5-coder:3b", + "qwen2.5-coder:7b", + "qwen2.5-coder:14b", + "qwen2.5-coder:32b" ] }, { @@ -1081,6 +1091,11 @@ "starcoder-1b", "starcoder-3b", "starcoder2-3b", + "qwen2.5-coder:1.5b", + "qwen2.5-coder:3b", + "qwen2.5-coder:7b", + "qwen2.5-coder:14b", + "qwen2.5-coder:32b", "AUTODETECT" ] }, @@ -1400,7 +1415,12 @@ "stable-code-3b", "starcoder-1b", "starcoder-3b", - "starcoder2-3b" + "starcoder2-3b", + "qwen2.5-coder:1.5b", + "qwen2.5-coder:3b", + "qwen2.5-coder:7b", + "qwen2.5-coder:14b", + "qwen2.5-coder:32b" ] }, { @@ -2710,8 +2730,8 @@ }, "tabAutocompleteModel": { "title": "Tab Autocomplete Model", - "markdownDescription": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.\n\n*IMPORTANT*:\n\nIf you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", - "x-intellij-html-description": "The model used for tab autocompletion. If undefined, Continue will default to using starcoder2:3b on a local Ollama instance.

IMPORTANT:

If you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", + "markdownDescription": "The model used for tab autocompletion. If undefined, Continue will default to using qwen2.5-coder:1.5b on a local Ollama instance.\n\n*IMPORTANT*:\n\nIf you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", + "x-intellij-html-description": "The model used for tab autocompletion. If undefined, Continue will default to using qwen2.5-coder:1.5b on a local Ollama instance.

IMPORTANT:

If you use a custom model, ensure that it is one trained for fill-in-the-middle completions. An instruct model is typically not well-suited to autocomplete and you may receive unsatisfactory completions.", "default": { "title": "Tab Autocomplete Model", "provider": "ollama", diff --git a/extensions/vscode/src/util/loadAutocompleteModel.ts b/extensions/vscode/src/util/loadAutocompleteModel.ts index f4f4c87b3..b4aa9289b 100644 --- a/extensions/vscode/src/util/loadAutocompleteModel.ts +++ b/extensions/vscode/src/util/loadAutocompleteModel.ts @@ -6,7 +6,7 @@ import type { ILLM } from "core"; export class TabAutocompleteModel { private _llm: ILLM | undefined; - private defaultTag = "starcoder2:3b"; + private defaultTag = "qwen2.5-coder:1.5b"; private globalContext: GlobalContext = new GlobalContext(); constructor(private configHandler: ConfigHandler) {} From 8da703f74525213dc212efa6b763d4be06dee38b Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 13 Nov 2024 10:23:37 -0800 Subject: [PATCH 06/18] feat: php definitions --- .../RootPathContextService.ts | 12 +- .../test/RootPathContextService.test.ts | 103 ++++++++++-------- .../class_declaration/php.scm | 13 +++ .../method_declaration/php.scm | 10 ++ 4 files changed, 87 insertions(+), 51 deletions(-) create mode 100644 extensions/vscode/tree-sitter/root-path-context-queries/class_declaration/php.scm create mode 100644 extensions/vscode/tree-sitter/root-path-context-queries/method_declaration/php.scm diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts index 6f163c265..9c47138cd 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -43,6 +43,7 @@ export class RootPathContextService { "function_declaration", "function_definition", "method_definition", + "method_declaration", "class_declaration", "class_definition", ]); @@ -73,7 +74,9 @@ export class RootPathContextService { this.importDefinitionsService.get(filepath); break; default: - console.log(getSyntaxTreeString(node)); + // const type = node.type; + // debugger; + // console.log(getSyntaxTreeString(node)); query = await getQueryForFile( filepath, @@ -83,8 +86,6 @@ export class RootPathContextService { } const type = node.type; - debugger; - if (!query) { return snippets; } @@ -135,9 +136,8 @@ export class RootPathContextService { RootPathContextService.TYPES_TO_USE.has(node.type), )) { const key = RootPathContextService.keyFromNode(parentKey, astNode); - const type = astNode.type; - - debugger; + // const type = astNode.type; + // debugger; const foundInCache = this.cache.get(key); const newSnippets = diff --git a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts index f0af54a45..4bc099c28 100644 --- a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts +++ b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts @@ -1,51 +1,51 @@ import { testRootPathContext } from "./testUtils"; const TEST_CASES = [ - // { - // nodeType: "function_declaration", - // fileName: "file1.ts", - // language: "TypeScript", - // cursorPosition: { line: 10, character: 24 }, - // definitionPositions: [ - // { row: 9, column: 34 }, // Person - // { row: 9, column: 44 }, // Address - // ], - // }, - // { - // nodeType: "method_declaration", - // fileName: "file1.ts", - // language: "TypeScript", - // cursorPosition: { line: 22, character: 30 }, - // definitionPositions: [ - // { 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: "function_definition", - // fileName: "file1.py", - // language: "Python", - // cursorPosition: { line: 4, character: 25 }, - // definitionPositions: [ - // { row: 3, column: 30 }, // Person - // { row: 3, column: 42 }, // Address - // ], - // }, - // { - // nodeType: "function_definition (inside a class)", - // fileName: "file1.py", - // language: "Python", - // cursorPosition: { line: 12, character: 33 }, - // definitionPositions: [ - // { row: 6, column: 21 }, // BaseClass - // { row: 6, column: 33 }, // Collection - // { row: 11, column: 47 }, // Person - // { row: 11, column: 59 }, // Address - // ], - // }, + { + nodeType: "function_declaration", + fileName: "file1.ts", + language: "TypeScript", + cursorPosition: { line: 10, character: 24 }, + definitionPositions: [ + { row: 9, column: 34 }, // Person + { row: 9, column: 44 }, // Address + ], + }, + { + nodeType: "method_declaration", + fileName: "file1.ts", + language: "TypeScript", + cursorPosition: { line: 22, character: 30 }, + definitionPositions: [ + { 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: "function_definition", + fileName: "file1.py", + language: "Python", + cursorPosition: { line: 4, character: 25 }, + definitionPositions: [ + { row: 3, column: 30 }, // Person + { row: 3, column: 42 }, // Address + ], + }, + { + nodeType: "function_definition (inside a class)", + fileName: "file1.py", + language: "Python", + cursorPosition: { line: 12, character: 33 }, + definitionPositions: [ + { row: 6, column: 21 }, // BaseClass + { row: 6, column: 33 }, // Collection + { row: 11, column: 47 }, // Person + { row: 11, column: 59 }, // Address + ], + }, { nodeType: "function_definition", fileName: "file1.php", @@ -56,6 +56,19 @@ const TEST_CASES = [ { row: 10, column: 44 }, // Address ], }, + { + nodeType: "function_definition (inside a class)", + 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 + ], + }, ]; describe("RootPathContextService", () => { diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/class_declaration/php.scm b/extensions/vscode/tree-sitter/root-path-context-queries/class_declaration/php.scm new file mode 100644 index 000000000..5e9a9c13e --- /dev/null +++ b/extensions/vscode/tree-sitter/root-path-context-queries/class_declaration/php.scm @@ -0,0 +1,13 @@ +( + (class_declaration + (base_clause + (name) @superclass) + ) +) + +( + (class_declaration + (class_interface_clause + (name) @interface) + ) +) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/method_declaration/php.scm b/extensions/vscode/tree-sitter/root-path-context-queries/method_declaration/php.scm new file mode 100644 index 000000000..825324e01 --- /dev/null +++ b/extensions/vscode/tree-sitter/root-path-context-queries/method_declaration/php.scm @@ -0,0 +1,10 @@ +( + (method_declaration + (formal_parameters + (simple_parameter + type: (named_type) @param_type + )* + ) + return_type: (named_type) @return_type + ) +) \ No newline at end of file From e0ae4ceb567d7288021259b2cd39ac68d138863b Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 13 Nov 2024 11:11:47 -0800 Subject: [PATCH 07/18] test: go --- .../context/root-path-context/test/files/file1.go | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 core/autocomplete/context/root-path-context/test/files/file1.go diff --git a/core/autocomplete/context/root-path-context/test/files/file1.go b/core/autocomplete/context/root-path-context/test/files/file1.go new file mode 100644 index 000000000..94eec171c --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/files/file1.go @@ -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 +} \ No newline at end of file From a9e97fef9aab7cb4bf71812250d8340eab183076 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 13 Nov 2024 11:15:46 -0800 Subject: [PATCH 08/18] fix uniqueId --- core/llm/llms/stubs/ContinueProxy.ts | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/core/llm/llms/stubs/ContinueProxy.ts b/core/llm/llms/stubs/ContinueProxy.ts index 0d04f77f5..97dec3a35 100644 --- a/core/llm/llms/stubs/ContinueProxy.ts +++ b/core/llm/llms/stubs/ContinueProxy.ts @@ -13,13 +13,14 @@ class ContinueProxy extends OpenAI { static providerName: ModelProvider = "continue-proxy"; static defaultOptions: Partial = { 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; } From bf65b1ebbdd3b0913d141e9f60a11414088bc78f Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 13 Nov 2024 11:33:09 -0800 Subject: [PATCH 09/18] feat: go definitions --- .../test/RootPathContextService.test.ts | 12 +++++++++++- .../function_declaration/go.scm | 12 ++++++++++++ 2 files changed, 23 insertions(+), 1 deletion(-) create mode 100644 extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/go.scm diff --git a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts index 4bc099c28..58da8982a 100644 --- a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts +++ b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts @@ -57,7 +57,7 @@ const TEST_CASES = [ ], }, { - nodeType: "function_definition (inside a class)", + nodeType: "method_declaration", fileName: "file1.php", language: "PHP", cursorPosition: { line: 26, character: 35 }, @@ -69,6 +69,16 @@ const TEST_CASES = [ { 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", () => { diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/go.scm b/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/go.scm new file mode 100644 index 000000000..482f50841 --- /dev/null +++ b/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/go.scm @@ -0,0 +1,12 @@ +( + (function_declaration + (parameter_list + (parameter_declaration + type: (_) @param_type + )* + ) + ; Optional return type node before the block + ([_] @return_type)? + (block) + ) +) \ No newline at end of file From 28db3b683b34ae6f0ba87914f6bc95793c84adb5 Mon Sep 17 00:00:00 2001 From: Dmitry Sebastyansky Date: Wed, 13 Nov 2024 23:05:25 +0300 Subject: [PATCH 10/18] Fix an edge case when stop token is not filtered out. --- .../streamTransforms/charStream.test.ts | 16 ++++++++++++++++ .../filtering/streamTransforms/charStream.ts | 7 ++++++- 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/core/autocomplete/filtering/streamTransforms/charStream.test.ts b/core/autocomplete/filtering/streamTransforms/charStream.test.ts index 7ab8923fc..b466ae3cd 100644 --- a/core/autocomplete/filtering/streamTransforms/charStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/charStream.test.ts @@ -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!"); + }); }); diff --git a/core/autocomplete/filtering/streamTransforms/charStream.ts b/core/autocomplete/filtering/streamTransforms/charStream.ts index 79fc33a0d..9f37e1f58 100644 --- a/core/autocomplete/filtering/streamTransforms/charStream.ts +++ b/core/autocomplete/filtering/streamTransforms/charStream.ts @@ -70,7 +70,8 @@ export async function* noFirstCharNewline(stream: AsyncGenerator) { * 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, @@ -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) { From c6e827661919110ac67d486577579df48c6aa028 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 13 Nov 2024 16:46:07 -0800 Subject: [PATCH 11/18] move prompts to .continue/prompts --- core/promptFiles/v2/createNewPromptFile.ts | 57 +++++++++++----------- core/promptFiles/v2/getPromptFiles.ts | 12 +++-- core/util/pathModule.ts | 13 +++++ core/util/paths.ts | 2 +- gui/src/components/find/FindWidget.tsx | 8 +-- 5 files changed, 54 insertions(+), 38 deletions(-) create mode 100644 core/util/pathModule.ts diff --git a/core/promptFiles/v2/createNewPromptFile.ts b/core/promptFiles/v2/createNewPromptFile.ts index a8ea87109..21ff3c7c1 100644 --- a/core/promptFiles/v2/createNewPromptFile.ts +++ b/core/promptFiles/v2/createNewPromptFile.ts @@ -1,46 +1,42 @@ -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 + +# For example, here is how you would write a .prompt +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 +48,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,7 +60,10 @@ 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)); diff --git a/core/promptFiles/v2/getPromptFiles.ts b/core/promptFiles/v2/getPromptFiles.ts index c78068899..0353746be 100644 --- a/core/promptFiles/v2/getPromptFiles.ts +++ b/core/promptFiles/v2/getPromptFiles.ts @@ -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"), + ), ), ), ) diff --git a/core/util/pathModule.ts b/core/util/pathModule.ts new file mode 100644 index 000000000..8b06ab56c --- /dev/null +++ b/core/util/pathModule.ts @@ -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 { + const pathSep = await ide.pathSep(); + return getPathModuleFromPathSep(pathSep as PathSep); +} diff --git a/core/util/paths.ts b/core/util/paths.ts index f8b70159f..d606f095d 100644 --- a/core/util/paths.ts +++ b/core/util/paths.ts @@ -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( diff --git a/gui/src/components/find/FindWidget.tsx b/gui/src/components/find/FindWidget.tsx index 266a09cd8..60a9bf2a9 100644 --- a/gui/src/components/find/FindWidget.tsx +++ b/gui/src/components/find/FindWidget.tsx @@ -389,7 +389,7 @@ export const useFindWidget = (searchRef: RefObject) => { e.stopPropagation(); previousMatch(); }} - className="h-4 w-4 focus:ring focus:ring-1" + className="h-4 w-4 focus:ring" disabled={matches.length < 2 || active} > @@ -401,7 +401,7 @@ export const useFindWidget = (searchRef: RefObject) => { e.stopPropagation(); nextMatch(); }} - className="h-4 w-4 focus:ring focus:ring-1" + className="h-4 w-4 focus:ring" disabled={matches.length < 2 || active} > @@ -420,7 +420,7 @@ export const useFindWidget = (searchRef: RefObject) => { e.stopPropagation(); setCaseSensitive((curr) => !curr); }} - className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring focus:ring-1" + className="h-5 w-6 rounded-full border text-xs focus:outline-none focus:ring" > Aa @@ -428,7 +428,7 @@ export const useFindWidget = (searchRef: RefObject) => { setOpen(false)} - className="focus:ring focus:ring-1" + className="focus:ring" > From bb4f9154ccbb5be7b045c376f249783f76342cea Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 13 Nov 2024 16:54:39 -0800 Subject: [PATCH 12/18] don't require context providers to be in config.json for prompt files --- core/promptFiles/v2/renderPromptFile.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/core/promptFiles/v2/renderPromptFile.ts b/core/promptFiles/v2/renderPromptFile.ts index bb70b19a2..89b36b0a8 100644 --- a/core/promptFiles/v2/renderPromptFile.ts +++ b/core/promptFiles/v2/renderPromptFile.ts @@ -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 From 1e98e366fc2abc16b225bc262a93e1ef10c35f36 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 13 Nov 2024 16:56:56 -0800 Subject: [PATCH 13/18] .continuerules --- core/config/getSystemPromptDotFile.ts | 2 +- extensions/vscode/src/extension/VsCodeExtension.ts | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/core/config/getSystemPromptDotFile.ts b/core/config/getSystemPromptDotFile.ts index ae6cd41f2..03690dd47 100644 --- a/core/config/getSystemPromptDotFile.ts +++ b/core/config/getSystemPromptDotFile.ts @@ -1,6 +1,6 @@ import { IDE } from ".."; -export const SYSTEM_PROMPT_DOT_FILE = ".instructions"; +export const SYSTEM_PROMPT_DOT_FILE = ".continuerules"; export async function getSystemPromptDotFile(ide: IDE): Promise { const dirs = await ide.getWorkspaceDirs(); diff --git a/extensions/vscode/src/extension/VsCodeExtension.ts b/extensions/vscode/src/extension/VsCodeExtension.ts index 06e498c55..06263e356 100644 --- a/extensions/vscode/src/extension/VsCodeExtension.ts +++ b/extensions/vscode/src/extension/VsCodeExtension.ts @@ -37,6 +37,7 @@ import { VsCodeIde } from "../VsCodeIde"; import { VsCodeMessenger } from "./VsCodeMessenger"; +import { SYSTEM_PROMPT_DOT_FILE } from "core/config/getSystemPromptDotFile"; import type { VsCodeWebviewProtocol } from "../webviewProtocol"; export class VsCodeExtension { @@ -285,7 +286,7 @@ export class VsCodeExtension { if ( filepath.endsWith(".continuerc.json") || filepath.endsWith(".prompt") || - filepath.endsWith(".instructions") + filepath.endsWith(SYSTEM_PROMPT_DOT_FILE) ) { this.configHandler.reloadConfig(); } else if ( From 1296ed6b3f677ccb090afbc788896f824e3a65de Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 13 Nov 2024 17:00:16 -0800 Subject: [PATCH 14/18] bump package.json, update changelog --- .changes/unreleased/Added-20241113-165958.yaml | 4 ++++ .changes/unreleased/Added-20241113-170006.yaml | 4 ++++ extensions/vscode/CHANGELOG.md | 9 +++++++-- extensions/vscode/package.json | 2 +- 4 files changed, 16 insertions(+), 3 deletions(-) create mode 100644 .changes/unreleased/Added-20241113-165958.yaml create mode 100644 .changes/unreleased/Added-20241113-170006.yaml diff --git a/.changes/unreleased/Added-20241113-165958.yaml b/.changes/unreleased/Added-20241113-165958.yaml new file mode 100644 index 000000000..95aaa7c70 --- /dev/null +++ b/.changes/unreleased/Added-20241113-165958.yaml @@ -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 diff --git a/.changes/unreleased/Added-20241113-170006.yaml b/.changes/unreleased/Added-20241113-170006.yaml new file mode 100644 index 000000000..bc254f8d9 --- /dev/null +++ b/.changes/unreleased/Added-20241113-170006.yaml @@ -0,0 +1,4 @@ +project: extensions/vscode +kind: Added +body: .prompt files v2 +time: 2024-11-13T17:00:06.855468-08:00 diff --git a/extensions/vscode/CHANGELOG.md b/extensions/vscode/CHANGELOG.md index 88925e7f4..8dac5cd8c 100644 --- a/extensions/vscode/CHANGELOG.md +++ b/extensions/vscode/CHANGELOG.md @@ -7,8 +7,6 @@ and is generated by [Changie](https://github.com/miniscruff/changie). Pre-release Changes ### Added -* New Edit mode in sidebar (cmd/ctrl+I) -* Significantly faster and more accurate docs crawler by default * OpenAI predicted outputs support * Improve codebase retrieval with BM25 * Support for Grok from xAI @@ -19,12 +17,19 @@ Pre-release Changes * Improved reference for config.json * New @web context provider * Updates for llama3.2 +* .continuerules file to set system prompt +* .prompt files v2 ### Changed * Improved @docs crawler * Many improvements to make autocomplete more eager ### Fixed * Brought back the Apply button for all code blocks +## 0.8.56 - 2024-11-08 +### Added +* New Edit mode in sidebar (cmd/ctrl+I) +* Significantly faster and more accurate docs crawler by default + ## 0.8.55 - 2024-10-25 ### Added * Web context provider diff --git a/extensions/vscode/package.json b/extensions/vscode/package.json index 30828f300..2ecfb4768 100644 --- a/extensions/vscode/package.json +++ b/extensions/vscode/package.json @@ -2,7 +2,7 @@ "name": "continue", "icon": "media/icon.png", "author": "Continue Dev, Inc", - "version": "0.9.228", + "version": "0.9.229", "repository": { "type": "git", "url": "https://github.com/continuedev/continue" From eb5140fa8b286697d049e8f8b9b6cc824d8439b7 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 13 Nov 2024 17:09:24 -0800 Subject: [PATCH 15/18] auto-assign to everyone --- .github/workflows/auto-assign.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/auto-assign.yaml b/.github/workflows/auto-assign.yaml index 3108307e5..dc5388ef3 100644 --- a/.github/workflows/auto-assign.yaml +++ b/.github/workflows/auto-assign.yaml @@ -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 From 430b74951949c5e3a52cf4b01df3f06a5c9ae497 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 13 Nov 2024 15:26:12 -0800 Subject: [PATCH 16/18] improv: more robust definitions for typescript --- .../test/RootPathContextService.test.ts | 25 +- .../test/files/{file1.ts => class.ts} | 18 +- .../root-path-context/test/files/file2.ts | 260 ++++++++++++++++++ .../root-path-context/test/files/functions.ts | 13 + .../test/testCases/typescript.ts | 71 +++++ .../function_declaration/typescript.scm | 36 ++- .../method_definition/typescript.scm | 40 ++- 7 files changed, 421 insertions(+), 42 deletions(-) rename core/autocomplete/context/root-path-context/test/files/{file1.ts => class.ts} (54%) create mode 100644 core/autocomplete/context/root-path-context/test/files/file2.ts create mode 100644 core/autocomplete/context/root-path-context/test/files/functions.ts create mode 100644 core/autocomplete/context/root-path-context/test/testCases/typescript.ts diff --git a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts index 58da8982a..fe81a0edd 100644 --- a/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts +++ b/core/autocomplete/context/root-path-context/test/RootPathContextService.test.ts @@ -1,29 +1,8 @@ +import { TYPESCRIPT_TEST_CASES } from "./testCases/typescript"; import { testRootPathContext } from "./testUtils"; const TEST_CASES = [ - { - nodeType: "function_declaration", - fileName: "file1.ts", - language: "TypeScript", - cursorPosition: { line: 10, character: 24 }, - definitionPositions: [ - { row: 9, column: 34 }, // Person - { row: 9, column: 44 }, // Address - ], - }, - { - nodeType: "method_declaration", - fileName: "file1.ts", - language: "TypeScript", - cursorPosition: { line: 22, character: 30 }, - definitionPositions: [ - { 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 - ], - }, + ...TYPESCRIPT_TEST_CASES, { nodeType: "function_definition", fileName: "file1.py", diff --git a/core/autocomplete/context/root-path-context/test/files/file1.ts b/core/autocomplete/context/root-path-context/test/files/class.ts similarity index 54% rename from core/autocomplete/context/root-path-context/test/files/file1.ts rename to core/autocomplete/context/root-path-context/test/files/class.ts index ba09c5709..017b592ae 100644 --- a/core/autocomplete/context/root-path-context/test/files/file1.ts +++ b/core/autocomplete/context/root-path-context/test/files/class.ts @@ -7,10 +7,6 @@ import { // @ts-ignore } from "./types"; -function getAddress(person: Person): Address { - return person.address; -} - class Group extends BaseClass implements FirstInterface, SecondInterface { people: Person[]; @@ -20,6 +16,18 @@ class Group extends BaseClass implements FirstInterface, SecondInterface { } getPersonAddress(person: Person): Address { - return getAddress(person); + return person.address; + } + + getHardcodedAddress(): Address { + return { street: "123 Main St", city: "Anytown" }; + } + + addPerson(person: Person) { + this.people = [...this.people, person]; + } + + addPeople(people: Person[]) { + this.people = [...this.people, ...people]; } } diff --git a/core/autocomplete/context/root-path-context/test/files/file2.ts b/core/autocomplete/context/root-path-context/test/files/file2.ts new file mode 100644 index 000000000..124b76bff --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/files/file2.ts @@ -0,0 +1,260 @@ +// @ts-nocheck +import { IProtocol } from "core/protocol/index.js"; +import { IMessenger, type Message } from "core/util/messenger"; +import { ChildProcessWithoutNullStreams } from "node:child_process"; +import * as fs from "node:fs"; +import net from "node:net"; +import { v4 as uuidv4 } from "uuid"; + +class IPCMessengerBase< + ToProtocol extends IProtocol, + FromProtocol extends IProtocol, +> implements IMessenger +{ + _sendMsg(message: Message) { + throw new Error("Not implemented"); + } + + typeListeners = new Map any)[]>(); + idListeners = new Map any>(); + + private _handleLine(line: string) { + try { + const msg: Message = JSON.parse(line); + if (msg.messageType === undefined || msg.messageId === undefined) { + throw new Error("Invalid message sent: " + JSON.stringify(msg)); + } + + // Call handler and respond with return value + const listeners = this.typeListeners.get(msg.messageType as any); + listeners?.forEach(async (handler) => { + try { + const response = await handler(msg); + if ( + response && + typeof response[Symbol.asyncIterator] === "function" + ) { + for await (const update of response) { + this.send(msg.messageType, update, msg.messageId); + } + this.send(msg.messageType, { done: true }, msg.messageId); + } else { + this.send(msg.messageType, response, msg.messageId); + } + } catch (e: any) { + console.warn(`Error running handler for "${msg.messageType}": `, e); + this._onErrorHandlers.forEach((handler) => { + handler(e); + }); + } + }); + + // Call handler which is waiting for the response, nothing to return + this.idListeners.get(msg.messageId)?.(msg); + } catch (e) { + let truncatedLine = line; + if (line.length > 200) { + truncatedLine = + line.substring(0, 100) + "..." + line.substring(line.length - 100); + } + console.error("Error parsing line: ", truncatedLine, e); + return; + } + } + + private _unfinishedLine: string | undefined = undefined; + protected _handleData(data: Buffer) { + const d = data.toString(); + const lines = d.split(/\r\n/).filter((line) => line.trim() !== ""); + if (lines.length === 0) { + return; + } + + if (this._unfinishedLine) { + lines[0] = this._unfinishedLine + lines[0]; + this._unfinishedLine = undefined; + } + if (!d.endsWith("\r\n")) { + this._unfinishedLine = lines.pop(); + } + lines.forEach((line) => this._handleLine(line)); + } + + private _onErrorHandlers: ((error: Error) => void)[] = []; + + onError(handler: (error: Error) => void) { + this._onErrorHandlers.push(handler); + } + + request( + messageType: T, + data: FromProtocol[T][0], + ): Promise { + const messageId = uuidv4(); + return new Promise((resolve) => { + const handler = (msg: Message) => { + resolve(msg.data); + this.idListeners.delete(messageId); + }; + this.idListeners.set(messageId, handler); + this.send(messageType, data, messageId); + }); + } + + mock(data: any) { + const d = JSON.stringify(data); + this._handleData(Buffer.from(d)); + } + + send( + messageType: T, + data: FromProtocol[T][0], + messageId?: string, + ): string { + messageId = messageId ?? uuidv4(); + const msg: Message = { + messageType: messageType as string, + data, + messageId, + }; + this._sendMsg(msg); + return messageId; + } + + invoke( + messageType: T, + data: ToProtocol[T][0], + ): ToProtocol[T][1] { + return this.typeListeners.get(messageType)?.[0]?.({ + messageId: uuidv4(), + messageType: messageType as string, + data, + }); + } + + on( + messageType: T, + handler: ( + message: Message, + ) => Promise | ToProtocol[T][1], + ): void { + if (!this.typeListeners.has(messageType)) { + this.typeListeners.set(messageType, []); + } + this.typeListeners.get(messageType)?.push(handler); + } +} + +export class IpcMessenger< + ToProtocol extends IProtocol, + FromProtocol extends IProtocol, + > + extends IPCMessengerBase + implements IMessenger +{ + constructor() { + super(); + console.log("Setup"); + process.stdin.on("data", (data) => { + // console.log("[info] Received data: ", data.toString()); + this._handleData(data); + }); + process.stdout.on("close", () => { + fs.writeFileSync("./error.log", `${new Date().toISOString()}\n`); + console.log("[info] Exiting Continue core..."); + process.exit(1); + }); + process.stdin.on("close", () => { + fs.writeFileSync("./error.log", `${new Date().toISOString()}\n`); + console.log("[info] Exiting Continue core..."); + process.exit(1); + }); + } + _sendMsg(msg: Message) { + const d = JSON.stringify(msg); + // console.log("[info] Sending message: ", d); + process.stdout?.write(d + "\r\n"); + } +} + +export class CoreBinaryMessenger< + ToProtocol extends IProtocol, + FromProtocol extends IProtocol, + > + extends IPCMessengerBase + implements IMessenger +{ + private errorHandler: (error: Error) => void = () => {}; + private messageHandlers: Map< + keyof ToProtocol, + (message: Message) => Promise | any + > = new Map(); + + constructor(private readonly subprocess: ChildProcessWithoutNullStreams) { + super(); + console.log("Setup"); + this.subprocess.stdout.on("data", (data) => { + console.log("[info] Received data from core:", data.toString() + "\n"); + this._handleData(data); + }); + this.subprocess.stdout.on("close", () => { + console.log("[info] Continue core exited"); + }); + this.subprocess.stdin.on("close", () => { + console.log("[info] Continue core exited"); + }); + } + + _sendMsg(msg: Message) { + console.log("[info] Sending message to core:", msg); + const d = JSON.stringify(msg); + this.subprocess.stdin.write(d + "\r\n"); + } +} + +export class CoreBinaryTcpMessenger< + ToProtocol extends IProtocol, + FromProtocol extends IProtocol, + > + extends IPCMessengerBase + implements IMessenger +{ + private port: number = 3000; + private socket: net.Socket | null = null; + + typeListeners = new Map any)[]>(); + idListeners = new Map any>(); + + constructor() { + super(); + const socket = net.createConnection(this.port, "localhost"); + + this.socket = socket; + socket.on("data", (data: Buffer) => { + // console.log("[info] Received data from core:", data.toString() + "\n"); + this._handleData(data); + }); + + socket.on("end", () => { + console.log("Disconnected from server"); + }); + + socket.on("error", (err: any) => { + console.error("Client error:", err); + }); + } + + close() { + this.socket?.end(); + } + + _sendMsg(msg: Message) { + if (this.socket) { + // console.log("[info] Sending message to core:", msg); + const d = JSON.stringify(msg); + this.socket.write(d + "\r\n"); + } else { + console.error("Socket is not connected"); + } + } +} diff --git a/core/autocomplete/context/root-path-context/test/files/functions.ts b/core/autocomplete/context/root-path-context/test/files/functions.ts new file mode 100644 index 000000000..8ae6944e9 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/files/functions.ts @@ -0,0 +1,13 @@ +import { + Address, + Person, + // @ts-ignore +} from "./types"; + +function getAddress(person: Person): Address { + return person.address; +} + +function getFirstAddress(people: Person[]): Address { + return people[0].address; +} diff --git a/core/autocomplete/context/root-path-context/test/testCases/typescript.ts b/core/autocomplete/context/root-path-context/test/testCases/typescript.ts new file mode 100644 index 000000000..2eb589c90 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/testCases/typescript.ts @@ -0,0 +1,71 @@ +export const TYPESCRIPT_TEST_CASES = [ + { + nodeType: "function_declaration with a param and a return type", + fileName: "functions.ts", + language: "TypeScript", + cursorPosition: { line: 7, character: 24 }, + definitionPositions: [ + { row: 6, column: 34 }, // Person + { row: 6, column: 44 }, // Address + ], + }, + { + nodeType: "function_declaration with array param", + fileName: "functions.ts", + language: "TypeScript", + cursorPosition: { line: 11, character: 27 }, + definitionPositions: [ + { row: 10, column: 39 }, // Person + { row: 10, column: 51 }, // Address + ], + }, + { + nodeType: "method_declaration", + fileName: "class.ts", + language: "TypeScript", + cursorPosition: { line: 18, character: 26 }, + definitionPositions: [ + { row: 9, column: 29 }, // BaseClass + { row: 9, column: 55 }, // FirstInterface + { row: 9, column: 72 }, // SecondInterface + { row: 17, column: 33 }, // Person + { row: 17, column: 43 }, // Address + ], + }, + { + nodeType: "method_declaration without arguments", + fileName: "class.ts", + language: "TypeScript", + cursorPosition: { line: 22, character: 54 }, + definitionPositions: [ + { row: 9, column: 29 }, // BaseClass + { row: 9, column: 55 }, // FirstInterface + { row: 9, column: 72 }, // SecondInterface + { row: 21, column: 32 }, // Address + ], + }, + { + nodeType: "method_declaration without return type", + fileName: "class.ts", + language: "TypeScript", + cursorPosition: { line: 26, character: 43 }, + definitionPositions: [ + { row: 9, column: 29 }, // BaseClass + { row: 9, column: 55 }, // FirstInterface + { row: 9, column: 72 }, // SecondInterface + { row: 25, column: 26 }, // Person + ], + }, + { + nodeType: "method_declaration with array type arguments", + fileName: "class.ts", + language: "TypeScript", + cursorPosition: { line: 30, character: 46 }, + definitionPositions: [ + { row: 9, column: 29 }, // BaseClass + { row: 9, column: 55 }, // FirstInterface + { row: 9, column: 72 }, // SecondInterface + { row: 29, column: 26 }, // Person + ], + }, +]; diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/typescript.scm b/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/typescript.scm index ab10968a3..24dc04e22 100644 --- a/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/typescript.scm +++ b/extensions/vscode/tree-sitter/root-path-context-queries/function_declaration/typescript.scm @@ -1,10 +1,34 @@ +; Pattern for capturing the return type ( - (function_declaration - (formal_parameters - (_ - (type_annotation) @param_type - ) + (function_declaration + (type_annotation) @return_type + ) +) + +; Pattern for parameters with direct type_identifier +( + (function_declaration + (formal_parameters + (_ + (type_annotation + (type_identifier) @param_type ) - (type_annotation) @return_type + ) ) + ) +) + +; Pattern for parameters with one level of nesting +( + (function_declaration + (formal_parameters + (_ + (type_annotation + (_ + (type_identifier) @param_type + ) + ) + ) + ) + ) ) \ No newline at end of file diff --git a/extensions/vscode/tree-sitter/root-path-context-queries/method_definition/typescript.scm b/extensions/vscode/tree-sitter/root-path-context-queries/method_definition/typescript.scm index 727db5090..9f8685385 100644 --- a/extensions/vscode/tree-sitter/root-path-context-queries/method_definition/typescript.scm +++ b/extensions/vscode/tree-sitter/root-path-context-queries/method_definition/typescript.scm @@ -1,10 +1,34 @@ +; Pattern for capturing the return type ( - (method_definition - (formal_parameters - (_ - (type_annotation) @param_type - ) - ) - (type_annotation) @return_type - ) + (method_definition + (type_annotation) @return_type + ) +) + +; Pattern for parameters with direct type_identifier +( + (method_definition + (formal_parameters + (_ + (type_annotation + (type_identifier) @param_type + ) + ) + ) + ) +) + +; Pattern for parameters with one level of nesting +( + (method_definition + (formal_parameters + (_ + (type_annotation + (_ + (type_identifier) @param_type + ) + ) + ) + ) + ) ) From 41ac57fa408eebb09c90781a4cf8b3092a6191ee Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 13 Nov 2024 17:14:13 -0800 Subject: [PATCH 17/18] test: typescript definitions --- .../root-path-context/test/files/functions.ts | 12 ++++++++++++ .../test/testCases/typescript.ts | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/core/autocomplete/context/root-path-context/test/files/functions.ts b/core/autocomplete/context/root-path-context/test/files/functions.ts index 8ae6944e9..2b6125a74 100644 --- a/core/autocomplete/context/root-path-context/test/files/functions.ts +++ b/core/autocomplete/context/root-path-context/test/files/functions.ts @@ -11,3 +11,15 @@ function getAddress(person: Person): Address { function getFirstAddress(people: Person[]): Address { return people[0].address; } + +function logPerson(person: Person) { + console.log(`Name: ${person.name}, Age: ${person.age}`); +} + +function getHardcodedAddress(): Address { + return { street: "123 Main St", city: "Anytown", zipCode: "12345" }; +} + +function getAddresses(people: Person[]): Address[] { + return people[0].address; +} diff --git a/core/autocomplete/context/root-path-context/test/testCases/typescript.ts b/core/autocomplete/context/root-path-context/test/testCases/typescript.ts index 2eb589c90..6913cb8d3 100644 --- a/core/autocomplete/context/root-path-context/test/testCases/typescript.ts +++ b/core/autocomplete/context/root-path-context/test/testCases/typescript.ts @@ -19,6 +19,24 @@ export const TYPESCRIPT_TEST_CASES = [ { row: 10, column: 51 }, // Address ], }, + { + nodeType: "function_declaration without return type", + fileName: "functions.ts", + language: "TypeScript", + cursorPosition: { line: 15, character: 58 }, + definitionPositions: [ + { row: 14, column: 33 }, // Person + ], + }, + { + nodeType: "function_declaration without params", + fileName: "functions.ts", + language: "TypeScript", + cursorPosition: { line: 19, character: 70 }, + definitionPositions: [ + { row: 18, column: 39 }, // Person + ], + }, { nodeType: "method_declaration", fileName: "class.ts", From 0599c52267b68d936ed328e42a99114fcfbf2dde Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 13 Nov 2024 17:22:37 -0800 Subject: [PATCH 18/18] cleanup: remove unused file --- .../root-path-context/test/files/file2.ts | 260 ------------------ 1 file changed, 260 deletions(-) delete mode 100644 core/autocomplete/context/root-path-context/test/files/file2.ts diff --git a/core/autocomplete/context/root-path-context/test/files/file2.ts b/core/autocomplete/context/root-path-context/test/files/file2.ts deleted file mode 100644 index 124b76bff..000000000 --- a/core/autocomplete/context/root-path-context/test/files/file2.ts +++ /dev/null @@ -1,260 +0,0 @@ -// @ts-nocheck -import { IProtocol } from "core/protocol/index.js"; -import { IMessenger, type Message } from "core/util/messenger"; -import { ChildProcessWithoutNullStreams } from "node:child_process"; -import * as fs from "node:fs"; -import net from "node:net"; -import { v4 as uuidv4 } from "uuid"; - -class IPCMessengerBase< - ToProtocol extends IProtocol, - FromProtocol extends IProtocol, -> implements IMessenger -{ - _sendMsg(message: Message) { - throw new Error("Not implemented"); - } - - typeListeners = new Map any)[]>(); - idListeners = new Map any>(); - - private _handleLine(line: string) { - try { - const msg: Message = JSON.parse(line); - if (msg.messageType === undefined || msg.messageId === undefined) { - throw new Error("Invalid message sent: " + JSON.stringify(msg)); - } - - // Call handler and respond with return value - const listeners = this.typeListeners.get(msg.messageType as any); - listeners?.forEach(async (handler) => { - try { - const response = await handler(msg); - if ( - response && - typeof response[Symbol.asyncIterator] === "function" - ) { - for await (const update of response) { - this.send(msg.messageType, update, msg.messageId); - } - this.send(msg.messageType, { done: true }, msg.messageId); - } else { - this.send(msg.messageType, response, msg.messageId); - } - } catch (e: any) { - console.warn(`Error running handler for "${msg.messageType}": `, e); - this._onErrorHandlers.forEach((handler) => { - handler(e); - }); - } - }); - - // Call handler which is waiting for the response, nothing to return - this.idListeners.get(msg.messageId)?.(msg); - } catch (e) { - let truncatedLine = line; - if (line.length > 200) { - truncatedLine = - line.substring(0, 100) + "..." + line.substring(line.length - 100); - } - console.error("Error parsing line: ", truncatedLine, e); - return; - } - } - - private _unfinishedLine: string | undefined = undefined; - protected _handleData(data: Buffer) { - const d = data.toString(); - const lines = d.split(/\r\n/).filter((line) => line.trim() !== ""); - if (lines.length === 0) { - return; - } - - if (this._unfinishedLine) { - lines[0] = this._unfinishedLine + lines[0]; - this._unfinishedLine = undefined; - } - if (!d.endsWith("\r\n")) { - this._unfinishedLine = lines.pop(); - } - lines.forEach((line) => this._handleLine(line)); - } - - private _onErrorHandlers: ((error: Error) => void)[] = []; - - onError(handler: (error: Error) => void) { - this._onErrorHandlers.push(handler); - } - - request( - messageType: T, - data: FromProtocol[T][0], - ): Promise { - const messageId = uuidv4(); - return new Promise((resolve) => { - const handler = (msg: Message) => { - resolve(msg.data); - this.idListeners.delete(messageId); - }; - this.idListeners.set(messageId, handler); - this.send(messageType, data, messageId); - }); - } - - mock(data: any) { - const d = JSON.stringify(data); - this._handleData(Buffer.from(d)); - } - - send( - messageType: T, - data: FromProtocol[T][0], - messageId?: string, - ): string { - messageId = messageId ?? uuidv4(); - const msg: Message = { - messageType: messageType as string, - data, - messageId, - }; - this._sendMsg(msg); - return messageId; - } - - invoke( - messageType: T, - data: ToProtocol[T][0], - ): ToProtocol[T][1] { - return this.typeListeners.get(messageType)?.[0]?.({ - messageId: uuidv4(), - messageType: messageType as string, - data, - }); - } - - on( - messageType: T, - handler: ( - message: Message, - ) => Promise | ToProtocol[T][1], - ): void { - if (!this.typeListeners.has(messageType)) { - this.typeListeners.set(messageType, []); - } - this.typeListeners.get(messageType)?.push(handler); - } -} - -export class IpcMessenger< - ToProtocol extends IProtocol, - FromProtocol extends IProtocol, - > - extends IPCMessengerBase - implements IMessenger -{ - constructor() { - super(); - console.log("Setup"); - process.stdin.on("data", (data) => { - // console.log("[info] Received data: ", data.toString()); - this._handleData(data); - }); - process.stdout.on("close", () => { - fs.writeFileSync("./error.log", `${new Date().toISOString()}\n`); - console.log("[info] Exiting Continue core..."); - process.exit(1); - }); - process.stdin.on("close", () => { - fs.writeFileSync("./error.log", `${new Date().toISOString()}\n`); - console.log("[info] Exiting Continue core..."); - process.exit(1); - }); - } - _sendMsg(msg: Message) { - const d = JSON.stringify(msg); - // console.log("[info] Sending message: ", d); - process.stdout?.write(d + "\r\n"); - } -} - -export class CoreBinaryMessenger< - ToProtocol extends IProtocol, - FromProtocol extends IProtocol, - > - extends IPCMessengerBase - implements IMessenger -{ - private errorHandler: (error: Error) => void = () => {}; - private messageHandlers: Map< - keyof ToProtocol, - (message: Message) => Promise | any - > = new Map(); - - constructor(private readonly subprocess: ChildProcessWithoutNullStreams) { - super(); - console.log("Setup"); - this.subprocess.stdout.on("data", (data) => { - console.log("[info] Received data from core:", data.toString() + "\n"); - this._handleData(data); - }); - this.subprocess.stdout.on("close", () => { - console.log("[info] Continue core exited"); - }); - this.subprocess.stdin.on("close", () => { - console.log("[info] Continue core exited"); - }); - } - - _sendMsg(msg: Message) { - console.log("[info] Sending message to core:", msg); - const d = JSON.stringify(msg); - this.subprocess.stdin.write(d + "\r\n"); - } -} - -export class CoreBinaryTcpMessenger< - ToProtocol extends IProtocol, - FromProtocol extends IProtocol, - > - extends IPCMessengerBase - implements IMessenger -{ - private port: number = 3000; - private socket: net.Socket | null = null; - - typeListeners = new Map any)[]>(); - idListeners = new Map any>(); - - constructor() { - super(); - const socket = net.createConnection(this.port, "localhost"); - - this.socket = socket; - socket.on("data", (data: Buffer) => { - // console.log("[info] Received data from core:", data.toString() + "\n"); - this._handleData(data); - }); - - socket.on("end", () => { - console.log("Disconnected from server"); - }); - - socket.on("error", (err: any) => { - console.error("Client error:", err); - }); - } - - close() { - this.socket?.end(); - } - - _sendMsg(msg: Message) { - if (this.socket) { - // console.log("[info] Sending message to core:", msg); - const d = JSON.stringify(msg); - this.socket.write(d + "\r\n"); - } else { - console.error("Socket is not connected"); - } - } -}