From b65dbf8825aa6e4ba6442b1bfc23b789c47cc17d Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 00:59:48 -0700 Subject: [PATCH 01/43] move files around --- .../{cache.ts => AutocompleteLruCache.ts} | 0 core/autocomplete/NearbyDefinitionsService.ts | 45 - core/autocomplete/README.md | 164 +- .../shouldCompleteMultiline.test.ts | 0 .../shouldCompleteMultiline.ts | 4 +- core/autocomplete/completionProvider.ts | 144 +- .../AutocompleteLanguageInfo.ts} | 2 +- .../AutocompleteTemplate.ts} | 6 +- core/autocomplete/constants/stopWords.ts | 11 + core/autocomplete/constructPrompt.ts | 12 +- .../ImportDefinitionsService.ts | 0 .../NearbyDefinitionsService.ts | 4 +- .../RootPathContextService.ts | 4 +- .../{ranking.ts => context/ranking/index.ts} | 6 +- .../{ => context/ranking}/slidingWindow.ts | 5 +- core/autocomplete/{ => context}/retrieval.ts | 0 .../BracketMatchingService.ts | 0 core/autocomplete/{ => filtering}/filter.ts | 0 .../streamTransforms}/charStream.test.ts | 0 .../streamTransforms/charStream.ts | 0 .../streamTransforms}/lineStream.test.ts | 0 .../streamTransforms/lineStream.ts | 0 .../test/NEGATIVE_CASES_STARCODER.tsx | 51 + .../filtering/test/filter.test.ts | 30 + core/autocomplete/filtering/test/testCases.ts | 2013 +++++++++++++++++ core/autocomplete/filtering/test/util.ts | 77 + .../GeneratorReuseManager.ts} | 76 +- .../generation/ListenableGenerator.ts | 75 + .../index.ts} | 6 +- core/autocomplete/types.ts | 38 + core/autocomplete/{ => util}/ast.ts | 4 +- core/core.ts | 2 +- core/edit/lazy/deterministic.ts | 2 +- core/protocol/core.ts | 2 +- 34 files changed, 2386 insertions(+), 397 deletions(-) rename core/autocomplete/{cache.ts => AutocompleteLruCache.ts} (100%) delete mode 100644 core/autocomplete/NearbyDefinitionsService.ts rename core/autocomplete/{ => classification}/shouldCompleteMultiline.test.ts (100%) rename core/autocomplete/{ => classification}/shouldCompleteMultiline.ts (93%) rename core/autocomplete/{languages.ts => constants/AutocompleteLanguageInfo.ts} (98%) rename core/autocomplete/{templates.ts => constants/AutocompleteTemplate.ts} (97%) create mode 100644 core/autocomplete/constants/stopWords.ts rename core/autocomplete/{services => context}/ImportDefinitionsService.ts (100%) rename core/autocomplete/{services => context}/NearbyDefinitionsService.ts (89%) rename core/autocomplete/{services => context}/RootPathContextService.ts (97%) rename core/autocomplete/{ranking.ts => context/ranking/index.ts} (97%) rename core/autocomplete/{ => context/ranking}/slidingWindow.ts (94%) rename core/autocomplete/{ => context}/retrieval.ts (100%) rename core/autocomplete/{services => filtering}/BracketMatchingService.ts (100%) rename core/autocomplete/{ => filtering}/filter.ts (100%) rename core/autocomplete/{ => filtering/streamTransforms}/charStream.test.ts (100%) rename core/autocomplete/{ => filtering}/streamTransforms/charStream.ts (100%) rename core/autocomplete/{ => filtering/streamTransforms}/lineStream.test.ts (100%) rename core/autocomplete/{ => filtering}/streamTransforms/lineStream.ts (100%) create mode 100644 core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx create mode 100644 core/autocomplete/filtering/test/filter.test.ts create mode 100644 core/autocomplete/filtering/test/testCases.ts create mode 100644 core/autocomplete/filtering/test/util.ts rename core/autocomplete/{util.ts => generation/GeneratorReuseManager.ts} (52%) create mode 100644 core/autocomplete/generation/ListenableGenerator.ts rename core/autocomplete/{postprocessing.ts => postprocessing/index.ts} (93%) create mode 100644 core/autocomplete/types.ts rename core/autocomplete/{ => util}/ast.ts (94%) diff --git a/core/autocomplete/cache.ts b/core/autocomplete/AutocompleteLruCache.ts similarity index 100% rename from core/autocomplete/cache.ts rename to core/autocomplete/AutocompleteLruCache.ts diff --git a/core/autocomplete/NearbyDefinitionsService.ts b/core/autocomplete/NearbyDefinitionsService.ts deleted file mode 100644 index 53178cba7..000000000 --- a/core/autocomplete/NearbyDefinitionsService.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { IDE, Location } from "../index.js"; -import { LANGUAGES } from "./languages.js"; -import { getSymbolsForSnippet } from "./ranking.js"; - -interface FileInfo { - filepath: string; -} - -export class NearbyDefinitionsService { - static N = 10; - - constructor(private readonly ide: IDE) {} - - async getDefinitionsForLine(filepath: string, line: number) { - const lineContent = await this.ide.readRangeInFile(filepath, { - start: { - line, - character: 0, - }, - end: { - line: line + 1, - character: 0, - }, - }); - - // Remove keywords - const lang = LANGUAGES[filepath.split(".").slice(-1)[0]]; - const symbols = Array.from(getSymbolsForSnippet(lineContent)) - .filter((s) => s.length > 0) - .filter((s) => !(lang && lang?.stopWords?.includes(s))); - - return Promise.all( - symbols.map((s) => { - const character = lineContent.indexOf(s); - const pos: Location = { - filepath, - position: { - line, - character, - }, - }; - }), - ); - } -} diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md index e19509bd8..8b860a3cc 100644 --- a/core/autocomplete/README.md +++ b/core/autocomplete/README.md @@ -1,163 +1,29 @@ -# Tab Autocomplete (beta) +# Autocomplete -Continue now provides support for tab autocomplete in [VS Code](https://marketplace.visualstudio.com/items?itemName=Continue.continue) and [JetBrains IDEs](https://plugins.jetbrains.com/plugin/22707-continue/edit). We will be greatly improving the experience over the next few releases, and it is always helpful to hear feedback. If you have any problems or suggestions, please let us know in our [Discord](https://discord.gg/vapESyrFmJ). +The autocomplete pipeline: -## Setting up with Ollama (default) +## 1. Triggering -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: +### Debouncing -```bash -ollama run starcoder:3b -``` +## 2. Context gathering -Once it has been downloaded, you should begin to see completions in VS Code. +## 3. Prompt construction -## Setting up with LM Studio +This is fairly trivial, we just use the correct template/endpoint for the model. Any templates are defined in [`templates.ts`](./templates.ts). -You can also set up tab-autocomplete with a local LM Studio instance by following these steps: +## 4. Caching -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) -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 -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 +## 4. Generation -Example: +### Reusing previous requests -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Starcoder2 3b", - "model": "second-state/StarCoder2-3B-GGUF/starcoder2-3b-Q8_0.gguf", - "provider": "lmstudio", - }, - ... -} -``` +## 4. Classification -## Setting up a custom model +Is it multi-line or single-line? -All of the configuration options available for chat models are available to use for tab-autocomplete. For example, if you wanted to use a remote vLLM instance you would edit your `config.json` like this (note that it is not inside the models array), filling in the correct model name and vLLM endpoint: +## 4. Filtering -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "openai", - "model": "", - "apiBase": "" - }, - ... -} -``` +## 5. Postprocessing -As another example, say you want to use a different model, `deepseek-coder:6.7b-base`, with Ollama: - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "deepseek-coder:6.7b-base" - }, - ... -} -``` - -If you aren't yet familiar with the available options, you can learn more in our [overview](../setup/overview.md). - -### What model should I use? - -If you are running the model locally, we recommend `starcoder:3b`. - -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`. - -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). - -## Configuration Options - -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`. - -### `tabAutocompleteOptions` - -This object allows you to customize the behavior of tab-autocomplete. The available options are: - -- `useCopyBuffer`: Determines whether the copy buffer will be considered when constructing the prompt. (Boolean) -- `useFileSuffix`: Determines whether to use the file suffix in the prompt. (Boolean) -- `maxPromptTokens`: The maximum number of prompt tokens to use. A smaller number will yield faster completions, but less context. (Number) -- `debounceDelay`: The delay in milliseconds before triggering autocomplete after a keystroke. (Number) -- `maxSuffixPercentage`: The maximum percentage of the prompt that can be dedicated to the suffix. (Number) -- `prefixPercentage`: The percentage of the input that should be dedicated to the prefix. (Number) -- `template`: An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables. (String) -- `multilineCompletions`: Whether to enable multiline completions ("always", "never", or "auto"). Defaults to "auto". - -### Full example - -```json title="config.json" -{ - "tabAutocompleteModel": { - "title": "Tab Autocomplete Model", - "provider": "ollama", - "model": "starcoder:3b", - "apiBase": "https://" - }, - "tabAutocompleteOptions": { - "useCopyBuffer": false, - "maxPromptTokens": 400, - "prefixPercentage": 0.5 - } -} -``` - -## Troubleshooting - -### I want better completions, should I use GPT-4? - -Perhaps surprisingly, the answer is no. The models that we suggest for autocomplete are trained with a highly specific prompt format, which allows them to respond to requests for completing code (see examples of these prompts [here](https://github.com/continuedev/continue/blob/d2bc6359e8ebf647892ec953e418042dc7f8a685/core/autocomplete/templates.ts)). Some of the best commercial models like GPT-4 or Claude are not trained with this prompt format, which means that they won't generate useful completions. Luckily, a huge model is not required for great autocomplete. Most of the state-of-the-art autocomplete models are no more than 10b parameters, and increasing beyond this does not significantly improve performance. - -### I'm not seeing any completions - -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. -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). -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 don't know about my code - -We are working on this! Right now Continue uses the Language Server Protocol to add definitions to the prompt, as well as using similarity search over recently edited files. We will be improving the accuracy of this system greatly over the next few weeks. - -### Completions contain formatting errors - -If you're seeing a common pattern of mistake that might be helpful to report, please share in Discord. We will do our best to fix it as soon as possible. - -## How to turn off autocomplete - -### VS Code - -Click the "Continue" button in the status panel at the bottom right of the screen. The checkmark will become a "cancel" symbol and you will no longer see completions. You can click again to turn it back on. - -Alternatively, open VS Code settings, search for "Continue" and uncheck the box for "Enable Tab Autocomplete". - -### JetBrains - -Open Settings -> Tools -> Continue and uncheck the box for "Enable Tab Autocomplete". - -### Feedback - -If you're turning off autocomplete, we'd love to hear how we can improve! Please let us know in our [Discord](https://discord.gg/vapESyrFmJ) or file an issue on GitHub. +## 6. Telemetry diff --git a/core/autocomplete/shouldCompleteMultiline.test.ts b/core/autocomplete/classification/shouldCompleteMultiline.test.ts similarity index 100% rename from core/autocomplete/shouldCompleteMultiline.test.ts rename to core/autocomplete/classification/shouldCompleteMultiline.test.ts diff --git a/core/autocomplete/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts similarity index 93% rename from core/autocomplete/shouldCompleteMultiline.ts rename to core/autocomplete/classification/shouldCompleteMultiline.ts index ae114151d..9c8172f85 100644 --- a/core/autocomplete/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -1,5 +1,5 @@ -import { AstPath } from "./ast"; -import { AutocompleteLanguageInfo } from "./languages"; +import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { AstPath } from "../util/ast"; const BLOCK_TYPES = ["body", "statement_block"]; diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 216286fcc..8458e1281 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -2,18 +2,10 @@ import ignore from "ignore"; import OpenAI from "openai"; import path from "path"; import { v4 as uuidv4 } from "uuid"; -import { RangeInFileWithContents } from "../commands/util.js"; import { ConfigHandler } from "../config/ConfigHandler.js"; import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { streamLines } from "../diff/util.js"; -import { - IDE, - ILLM, - ModelProvider, - Position, - Range, - TabAutocompleteOptions, -} from "../index.js"; +import { IDE, ILLM, ModelProvider, TabAutocompleteOptions } from "../index.js"; import { logDevData } from "../util/devdata.js"; import { getBasename, getLastNPathParts } from "../util/index.js"; import { @@ -23,17 +15,24 @@ import { import { Telemetry } from "../util/posthog.js"; import { getRangeInString } from "../util/ranges.js"; -import AutocompleteLruCache from "./cache.js"; +import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; +import { getTemplateForModel } from "./constants/AutocompleteTemplate.js"; import { constructAutocompletePrompt, languageForFilepath, } from "./constructPrompt.js"; -import { isOnlyWhitespace } from "./filter.js"; -import { AutocompleteLanguageInfo } from "./languages.js"; -import { postprocessCompletion } from "./postprocessing.js"; -import { AutocompleteSnippet } from "./ranking.js"; -import { RecentlyEditedRange } from "./recentlyEdited.js"; -import { RootPathContextService } from "./services/RootPathContextService.js"; +import { AutocompleteSnippet } from "./context/ranking/index.js"; +import { RootPathContextService } from "./context/RootPathContextService.js"; +import { isOnlyWhitespace } from "./filtering/filter.js"; +import { GeneratorReuseManager } from "./generation/GeneratorReuseManager.js"; +import { postprocessCompletion } from "./postprocessing/index.js"; +// @prettier-ignore +import Handlebars from "handlebars"; +import { getConfigJsonPath } from "../util/paths.js"; +import AutocompleteLruCache from "./AutocompleteLruCache.js"; +import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; +import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; +import { stopAtStopTokens } from "./filtering/streamTransforms/charStream.js"; import { avoidPathLineAndEmptyComments, noTopLevelKeywordsMidline, @@ -42,68 +41,11 @@ import { stopAtRepeatingLines, stopAtSimilarLine, streamWithNewLines, -} from "./streamTransforms/lineStream.js"; -import { getTemplateForModel } from "./templates.js"; -import { GeneratorReuseManager } from "./util.js"; -// @prettier-ignore -import Handlebars from "handlebars"; -import { getConfigJsonPath } from "../util/paths.js"; -import { BracketMatchingService } from "./services/BracketMatchingService.js"; -import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js"; -import { - noFirstCharNewline, - onlyWhitespaceAfterEndOfLine, - stopAtStopTokens, -} from "./streamTransforms/charStream.js"; - -export interface AutocompleteInput { - completionId: string; - filepath: string; - pos: Position; - recentlyEditedFiles: RangeInFileWithContents[]; - recentlyEditedRanges: RecentlyEditedRange[]; - clipboardText: string; - // Used for notebook files - manuallyPassFileContents?: string; - // Used for VS Code git commit input box - manuallyPassPrefix?: string; - selectedCompletionInfo?: { - text: string; - range: Range; - }; - injectDetails?: string; -} - -export interface AutocompleteOutcome extends TabAutocompleteOptions { - accepted?: boolean; - time: number; - prefix: string; - suffix: string; - prompt: string; - completion: string; - modelProvider: string; - modelName: string; - completionOptions: any; - cacheHit: boolean; - filepath: string; - gitRepo?: string; - completionId: string; - uniqueId: string; -} +} from "./filtering/streamTransforms/lineStream.js"; +import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; const autocompleteCache = AutocompleteLruCache.get(); -const DOUBLE_NEWLINE = "\n\n"; -const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n"; -const SRC_DIRECTORY = "/src/"; -// Starcoder2 tends to output artifacts starting with the letter "t" -const STARCODER2_T_ARTIFACTS = ["t.", "\nt", ""]; -const PYTHON_ENCODING = "#- coding: utf-8"; -const CODE_BLOCK_END = "```"; - -const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE]; -const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END]; - // Errors that can be expected on occasion even during normal functioning should not be shown. // Not worth disrupting the user to tell them that a single autocomplete request didn't go through const ERRORS_TO_IGNORE = [ @@ -262,7 +204,8 @@ export class CompletionProvider { for (const workspaceDir of workspaceDirs) { const relativePath = path.relative(workspaceDir, filepath); const relativePathBase = relativePath.split(path.sep).at(0); - const isInWorkspace = !path.isAbsolute(relativePath) && relativePathBase !== ".."; + const isInWorkspace = + !path.isAbsolute(relativePath) && relativePathBase !== ".."; if (isInWorkspace) { filepath = path.relative(workspaceDir, filepath); break; @@ -489,10 +432,11 @@ export class CompletionProvider { if (input.injectDetails) { const lines = fullPrefix.split("\n"); - fullPrefix = `${lines.slice(0, -1).join("\n")}\n${lang.singleLineComment - } ${input.injectDetails - .split("\n") - .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; + fullPrefix = `${lines.slice(0, -1).join("\n")}\n${ + lang.singleLineComment + } ${input.injectDetails + .split("\n") + .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; } const fullSuffix = getRangeInString(fileContents, { @@ -513,17 +457,17 @@ export class CompletionProvider { let extrasSnippets = options.useOtherFiles ? ((await Promise.race([ - this.getDefinitionsFromLsp( - filepath, - fullPrefix + fullSuffix, - fullPrefix.length, - this.ide, - lang, - ), - new Promise((resolve) => { - setTimeout(() => resolve([]), 100); - }), - ])) as AutocompleteSnippet[]) + this.getDefinitionsFromLsp( + filepath, + fullPrefix + fullSuffix, + fullPrefix.length, + this.ide, + lang, + ), + new Promise((resolve) => { + setTimeout(() => resolve([]), 100); + }), + ])) as AutocompleteSnippet[]) : []; const workspaceDirs = await this.ide.getWorkspaceDirs(); @@ -562,8 +506,8 @@ export class CompletionProvider { completionOptions, compilePrefixSuffix = undefined, } = options.template - ? { template: options.template, completionOptions: {} } - : getTemplateForModel(llm.model); + ? { template: options.template, completionOptions: {} } + : getTemplateForModel(llm.model); let prompt: string; const filename = getBasename(filepath); @@ -660,14 +604,14 @@ export class CompletionProvider { () => llm.supportsFim() ? llm.streamFim(prefix, suffix, { - ...completionOptions, - stop, - }) + ...completionOptions, + stop, + }) : llm.streamComplete(prompt, { - ...completionOptions, - raw: true, - stop, - }), + ...completionOptions, + raw: true, + stop, + }), multiline, ); diff --git a/core/autocomplete/languages.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts similarity index 98% rename from core/autocomplete/languages.ts rename to core/autocomplete/constants/AutocompleteLanguageInfo.ts index be414098a..3af6e2e15 100644 --- a/core/autocomplete/languages.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -1,4 +1,4 @@ -import { LineFilter } from "./streamTransforms/lineStream"; +import { LineFilter } from "../filtering/streamTransforms/lineStream"; export interface AutocompleteLanguageInfo { name: string; diff --git a/core/autocomplete/templates.ts b/core/autocomplete/constants/AutocompleteTemplate.ts similarity index 97% rename from core/autocomplete/templates.ts rename to core/autocomplete/constants/AutocompleteTemplate.ts index cda8b8a2d..034426f91 100644 --- a/core/autocomplete/templates.ts +++ b/core/autocomplete/constants/AutocompleteTemplate.ts @@ -1,8 +1,8 @@ // Fill in the middle prompts -import { CompletionOptions } from "../index.js"; -import { getLastNPathParts, shortestRelativePaths } from "../util/index.js"; -import { AutocompleteSnippet } from "./ranking.js"; +import { CompletionOptions } from "../../index.js"; +import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js"; +import { AutocompleteSnippet } from "../context/ranking/index.js"; interface AutocompleteTemplate { compilePrefixSuffix?: ( diff --git a/core/autocomplete/constants/stopWords.ts b/core/autocomplete/constants/stopWords.ts new file mode 100644 index 000000000..94d29cf40 --- /dev/null +++ b/core/autocomplete/constants/stopWords.ts @@ -0,0 +1,11 @@ +const DOUBLE_NEWLINE = "\n\n"; +const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n"; +// TODO: Do we want to stop completions when reaching a `/src/` string? +const SRC_DIRECTORY = "/src/"; +// Starcoder2 tends to output artifacts starting with the letter "t" +const STARCODER2_T_ARTIFACTS = ["t.", "\nt", ""]; +const PYTHON_ENCODING = "#- coding: utf-8"; +const CODE_BLOCK_END = "```"; + +const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE]; +const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END]; diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 17b78fa01..889db0d76 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -6,23 +6,23 @@ import { pruneLinesFromBottom, pruneLinesFromTop, } from "../llm/countTokens.js"; -import { AstPath, getAst, getTreePathAtCursor } from "./ast.js"; +import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; import { AutocompleteLanguageInfo, LANGUAGES, Typescript, -} from "./languages.js"; +} from "./constants/AutocompleteLanguageInfo.js"; +import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { fillPromptWithSnippets, getSymbolsForSnippet, rankSnippets, removeRangeFromSnippets, type AutocompleteSnippet, -} from "./ranking.js"; +} from "./context/ranking/index.js"; +import { RootPathContextService } from "./context/RootPathContextService.js"; import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js"; -import { ImportDefinitionsService } from "./services/ImportDefinitionsService.js"; -import { RootPathContextService } from "./services/RootPathContextService.js"; -import { shouldCompleteMultiline } from "./shouldCompleteMultiline.js"; +import { AstPath, getAst, getTreePathAtCursor } from "./util/ast.js"; export function languageForFilepath( filepath: string, diff --git a/core/autocomplete/services/ImportDefinitionsService.ts b/core/autocomplete/context/ImportDefinitionsService.ts similarity index 100% rename from core/autocomplete/services/ImportDefinitionsService.ts rename to core/autocomplete/context/ImportDefinitionsService.ts diff --git a/core/autocomplete/services/NearbyDefinitionsService.ts b/core/autocomplete/context/NearbyDefinitionsService.ts similarity index 89% rename from core/autocomplete/services/NearbyDefinitionsService.ts rename to core/autocomplete/context/NearbyDefinitionsService.ts index 12d6f7947..6e4cece83 100644 --- a/core/autocomplete/services/NearbyDefinitionsService.ts +++ b/core/autocomplete/context/NearbyDefinitionsService.ts @@ -1,6 +1,6 @@ import { IDE, Location } from "../.."; -import { LANGUAGES } from "../languages"; -import { getSymbolsForSnippet } from "../ranking"; +import { LANGUAGES } from "../constants/AutocompleteLanguageInfo"; +import { getSymbolsForSnippet } from "./ranking"; interface FileInfo { filepath: string; diff --git a/core/autocomplete/services/RootPathContextService.ts b/core/autocomplete/context/RootPathContextService.ts similarity index 97% rename from core/autocomplete/services/RootPathContextService.ts rename to core/autocomplete/context/RootPathContextService.ts index 69426aab8..2b2986b75 100644 --- a/core/autocomplete/services/RootPathContextService.ts +++ b/core/autocomplete/context/RootPathContextService.ts @@ -3,9 +3,9 @@ import { LRUCache } from "lru-cache"; import Parser from "web-tree-sitter"; import { IDE } from "../.."; import { getQueryForFile, TSQueryType } from "../../util/treeSitter"; -import { AstPath } from "../ast"; -import { AutocompleteSnippet } from "../ranking"; +import { AstPath } from "../util/ast"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; +import { AutocompleteSnippet } from "./ranking"; export class RootPathContextService { private cache = new LRUCache({ diff --git a/core/autocomplete/ranking.ts b/core/autocomplete/context/ranking/index.ts similarity index 97% rename from core/autocomplete/ranking.ts rename to core/autocomplete/context/ranking/index.ts index 48e01d5ff..4809901cd 100644 --- a/core/autocomplete/ranking.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -1,6 +1,6 @@ -import { RangeInFileWithContents } from "../commands/util.js"; -import { Range } from "../index.js"; -import { countTokens } from "../llm/countTokens.js"; +import { RangeInFileWithContents } from "../../../commands/util.js"; +import { Range } from "../../../index.js"; +import { countTokens } from "../../../llm/countTokens.js"; export type AutocompleteSnippet = RangeInFileWithContents & { score?: number; diff --git a/core/autocomplete/slidingWindow.ts b/core/autocomplete/context/ranking/slidingWindow.ts similarity index 94% rename from core/autocomplete/slidingWindow.ts rename to core/autocomplete/context/ranking/slidingWindow.ts index 72aa1a5ee..37d1a7d9e 100644 --- a/core/autocomplete/slidingWindow.ts +++ b/core/autocomplete/context/ranking/slidingWindow.ts @@ -1,5 +1,8 @@ import { RangeInFileWithContents } from "../commands/util.js"; -import { AutocompleteSnippet, jaccardSimilarity } from "./ranking.js"; +import { + AutocompleteSnippet, + jaccardSimilarity, +} from "./context/ranking/index.js"; function* slidingWindow( content: string, diff --git a/core/autocomplete/retrieval.ts b/core/autocomplete/context/retrieval.ts similarity index 100% rename from core/autocomplete/retrieval.ts rename to core/autocomplete/context/retrieval.ts diff --git a/core/autocomplete/services/BracketMatchingService.ts b/core/autocomplete/filtering/BracketMatchingService.ts similarity index 100% rename from core/autocomplete/services/BracketMatchingService.ts rename to core/autocomplete/filtering/BracketMatchingService.ts diff --git a/core/autocomplete/filter.ts b/core/autocomplete/filtering/filter.ts similarity index 100% rename from core/autocomplete/filter.ts rename to core/autocomplete/filtering/filter.ts diff --git a/core/autocomplete/charStream.test.ts b/core/autocomplete/filtering/streamTransforms/charStream.test.ts similarity index 100% rename from core/autocomplete/charStream.test.ts rename to core/autocomplete/filtering/streamTransforms/charStream.test.ts diff --git a/core/autocomplete/streamTransforms/charStream.ts b/core/autocomplete/filtering/streamTransforms/charStream.ts similarity index 100% rename from core/autocomplete/streamTransforms/charStream.ts rename to core/autocomplete/filtering/streamTransforms/charStream.ts diff --git a/core/autocomplete/lineStream.test.ts b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts similarity index 100% rename from core/autocomplete/lineStream.test.ts rename to core/autocomplete/filtering/streamTransforms/lineStream.test.ts diff --git a/core/autocomplete/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts similarity index 100% rename from core/autocomplete/streamTransforms/lineStream.ts rename to core/autocomplete/filtering/streamTransforms/lineStream.ts diff --git a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx b/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx new file mode 100644 index 000000000..269d25f0f --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx @@ -0,0 +1,51 @@ +##### Prompt ##### +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + + + + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} +========================================================================== +========================================================================== +Completion: + + this.result /= number; + return this; + } +} + +module.exports = Calculator; \ No newline at end of file diff --git a/core/autocomplete/filtering/test/filter.test.ts b/core/autocomplete/filtering/test/filter.test.ts new file mode 100644 index 000000000..171b1cb44 --- /dev/null +++ b/core/autocomplete/filtering/test/filter.test.ts @@ -0,0 +1,30 @@ +import { + AutocompleteFileringTestInput, + testAutocompleteFiltering, +} from "./util"; +import { TEST_CASES } from "./testCases"; + +const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { + if (tests.some((test) => test.options?.only)) { + return tests.filter((test) => test.options?.only); + } + + return tests; +}; + +describe("llms/Mock", () => { + describe("Autocomplete Filtering Tests", () => { + beforeEach(async () => { + await new Promise((resolve) => setTimeout(resolve, 50)); + }); + + describe("Should return unmodified LLM output", () => { + it.each(filterTestCases(TEST_CASES))("$description", async (testCase) => { + await testAutocompleteFiltering(testCase); + }); + }); + + // TODO: Add test cases where modifying LLM output is desirable + describe.skip("Should return modified LLM output", () => {}); + }); +}); diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts new file mode 100644 index 000000000..c3c19dfea --- /dev/null +++ b/core/autocomplete/filtering/test/testCases.ts @@ -0,0 +1,2013 @@ +import { dedent } from "../../../util"; +import { AutocompleteFileringTestInput } from "./util"; + +export const TEST_CASES: AutocompleteFileringTestInput[] = [ + { + description: "should pass", + filename: "test.js", + input: "console.log('Hello <|fim|>!');", + llmOutput: "World", + expectedCompletion: "World", + }, + { + description: + "Should preserve closing brackets when the opening bracket is not a part of the completion.", + filename: "test.js", + input: dedent` + class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + <|fim|> + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } + } + `, + llmOutput: dedent`if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + }`, + expectedCompletion: dedent`if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + }`, + }, + { + description: "Should multiline-autocomplete CSS blocks", + input: `body { + font-family: Arial, sans-serif; + font-size: 16px; + color: #333333; +} + +h1 { + font-size: 24px; + font-weight: bold; + color: #000000; +} + +h4<|fim|> + +a { + text-decoration: none; + color: #007bff; +} + +.container { + width: 100%; + max-width: 1200px; + margin: 0 auto; + padding: 20px; +} + +.button { + display: inline-block; + padding: 10px 20px; + background-color: #007bff; + color: #ffffff;`, + llmOutput: ` { + font-size: 18px; + font-weight: bold; + color: #000000; +}`, + expectedCompletion: ` { + font-size: 18px; + font-weight: bold; + color: #000000; +}`, + filename: "test.css", + }, + { + description: "Should complete CSS rules inside a nested selector", + filename: "styles.css", + input: ` +.container { + display: flex; + justify-content: center; + align-items: center; + width: 100%; + height: 100vh; + + .inner { + <|fim|> + } +} +`, + llmOutput: `width: 50%; + height: 50%; + background-color: #f0f0f0;`, + expectedCompletion: `width: 50%; + height: 50%; + background-color: #f0f0f0;`, + }, + + { + description: + "Should complete a CSS rule when the property is partially typed", + filename: "styles.css", + input: ` +button { + border: 2px solid #000; + border-radius<|fim|> +}`, + llmOutput: `: 5px;`, + expectedCompletion: `: 5px;`, + }, + + { + description: "Should handle CSS autocomplete with a single bracket present", + filename: "styles.css", + input: ` +.card { + box-shadow: 0 4px 8px rgba(0,0,0,0.2); + transition: 0.3s; + padding: 16px; + border-bottom-left-radius: <|fim|>px; + border-bottom-right-radius: 8px; +} +`, + llmOutput: `8`, + expectedCompletion: `8`, + }, + + { + description: "Should autocomplete CSS pseudoclass", + filename: "pseudoClass.css", + input: ` +input:focus { + outline: none; + border: 2px solid <|fim|>; +} +`, + llmOutput: `#4CAF50;`, + expectedCompletion: `#4CAF50;`, + }, + + { + description: "Should handle CSS variable syntax", + filename: "variables.css", + input: ` +:root { + --primary-color: #3498db; + --padding: 10px; +} + +.section { + background-color: var(<|fim|>); + padding: var(--padding); +} +`, + llmOutput: `--primary-color`, + expectedCompletion: `--primary-color`, + }, + { + description: "Should complete CSS grid template columns", + filename: "grid.css", + input: ` +.grid-container { + display: grid; + grid-template-columns: repeat(<|fim|>); + grid-gap: 10px; +} +`, + llmOutput: `3, 1fr`, + expectedCompletion: `3, 1fr`, + }, + + { + description: "Should complete PHP function inside a class with comments", + input: `name = $name; + $this->email = $email; + } + + public function <|fim|> + + public function setEmail($email) { + $this->email = $email; + } +}`, + llmOutput: `getDetails() { + return "Name: " . $this->name . ", Email: " . $this->email; + }`, + expectedCompletion: `getDetails() { + return "Name: " . $this->name . ", Email: " . $this->email; + }`, + filename: "User.php", + }, + + { + description: "Should autocomplete PHP function with inline logic", + input: ` +} + +echo calculateArea(5, 3);`, + llmOutput: `return $length * $width;`, + expectedCompletion: `return $length * $width;`, + filename: "areaCalculator.php", + }, + + { + description: "Should handle PHP completion in the middle of an array", + input: `); + +echo "First color is: " . $colors[0];`, + llmOutput: `"Blue"`, + expectedCompletion: `"Blue"`, + filename: "colors.php", + }, + { + description: "Should autocomplete React return statements (jsx)", + input: `import React from "react"; + +export const Button = ({ + onClick, + children, +}: { + children: React.ReactNode; + onClick: () => void; +}) => { + return ( +<|fim|> + ); +};`, + llmOutput: ``, + expectedCompletion: ``, + filename: "Button.tsx", + }, + { + description: "Should autocomplete React state initialization", + input: `import React, { useState } from "react"; + +export const Counter = () => { + const [count, setCount] = useState(<|fim|>); + + return ( +
+

You clicked {count} times

+ +
+ ); +};`, + llmOutput: `0`, + expectedCompletion: `0`, + filename: "Counter.tsx", + }, + + { + description: "Should autocomplete React effect hook", + input: `import React, { useState, useEffect } from "react"; + +export const Timer = () => { + const [seconds, setSeconds] = useState(0); + + useEffect(() => { + const interval = setInterval(() => { + setSeconds(seconds + 1); + }, 1000); + + <|fim|>; + + return () => clearInterval(interval); + }, [seconds]); + + return ( +
+

{seconds} seconds have passed.

+
+ ); +};`, + llmOutput: `return () => clearInterval(interval);`, + expectedCompletion: `return () => clearInterval(interval);`, + filename: "Timer.tsx", + }, + + { + description: "Should autocomplete React component methods", + input: `import React from "react"; + +class Form extends React.Component { + constructor(props) { + super(props); + this.state = { name: '' }; + } + + handleChange = (event) => { + <|fim|> + } + + handleSubmit = (event) => { + event.preventDefault(); + alert('A name was submitted: ' + this.state.name); + } + + render() { + return ( +
+ + +
+ ); + } +}`, + llmOutput: `this.setState({ name: event.target.value });`, + expectedCompletion: `this.setState({ name: event.target.value });`, + filename: "Form.tsx", + }, + { + description: "Should autocomplete Python function definition", + filename: "test.py", + input: `def calculate_area(length, width): + area = length * width + return area + +def calculate_perimeter(length, width): + <|fim|> +`, + llmOutput: `perimeter = 2 * (length + width) + return perimeter`, + expectedCompletion: `perimeter = 2 * (length + width) + return perimeter`, + }, + { + description: "Should complete Python class method with self", + filename: "test.py", + input: `class BankAccount: + def __init__(self, owner, balance=0): + self.owner = owner + self.balance = balance + + def deposit(self, amount): + self.balance += amount + return self.balance + + def withdraw(self, amount): + <|fim|> +`, + llmOutput: `if amount > self.balance: + return "Insufficient funds" + self.balance -= amount + return self.balance`, + expectedCompletion: `if amount > self.balance: + return "Insufficient funds" + self.balance -= amount + return self.balance`, + }, + { + description: "Should autocomplete Python list comprehension", + filename: "test.py", + input: `squares = [x**2 for x in range(10)] +even_squares = [x for x in squares if x % 2 == 0] +print(even_squares) + +odd_squares = [<|fim|> +print(odd_squares) +`, + llmOutput: `x for x in squares if x % 2 != 0`, + expectedCompletion: `x for x in squares if x % 2 != 0`, + }, + { + description: "Should handle python multi-line string", + filename: "test.py", + input: `def create_greeting(name): + greeting = """Hello, """ + name + """! +Welcome to our community. We hope you have a great time here. +If you have any questions, feel free to reach out.""" + return greeting + +message = create_greeting("Alice") +print(message) + +multi_line_message = """<|fim|> +print(multi_line_message) +`, + llmOutput: `This is a multi-line message. +It continues across multiple lines, +which allows for easy reading and formatting. +""" +`, + expectedCompletion: `This is a multi-line message. +It continues across multiple lines, +which allows for easy reading and formatting. +""" +`, + }, + { + description: "Should autocomplete a simple Go function declaration", + filename: "simpleFunction.go", + input: `package main + +import ( + "fmt" +) + +func main() { + fmt.Println("Hello, World!") +} + +func calculateArea<|fim|>`, + llmOutput: `(length float64, width float64) float64 { + return length * width +}`, + expectedCompletion: `(length float64, width float64) float64 { + return length * width +}`, + }, + + { + description: + "Should handle autocomplete in the middle of a Go struct definition", + filename: "structDefinition.go", + input: `package main + +type Person struct { + FirstName string + LastName string + Age int + Address Address +} + +type Address struct { + Street string + City <|fim|> +} + +func main() {}`, + llmOutput: `string + State string + ZipCode string +}`, + expectedCompletion: `string + State string + ZipCode string +}`, + }, + + { + description: "Should autocomplete a missing Go function body bracket", + filename: "missingBracket.go", + input: `package main + +func add(a int, b int) int { + return a + b<|fim|> + +func multiply(a int, b int) int { + return a * b +} + +func main() { + result1 := add(2, 3) + result2 := multiply(4, 5) + println(result1, result2) +}`, + llmOutput: ` +}`, + expectedCompletion: ` +}`, + }, + { + description: + "Should autocomplete SQL query with subquery and alias in SELECT clause", + filename: "complex_query.sql", + input: `SELECT u.id, + u.name, + (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count + 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)`, + }, + { + description: + "Should autocomplete SQL query with nested functions and missing bracket", + filename: "_nested_function.sql", + input: `SELECT name, ROUND(AVG(rating), 2) as avg_rating + FROM movies + WHERE release_year > 2000 AND director = 'Christopher Nolan' + GROUP BY name + HAVING avg_rating > <|fim|>`, + llmOutput: `8.5)`, + expectedCompletion: `8.5)`, + }, + { + description: + "Should autocomplete multi-line SQL query with CASE statements", + filename: "case_statement.sql", + input: `SELECT order_id, + order_date, + CASE + WHEN status = 'shipped' THEN 'Completed' + WHEN status = 'pending' THEN 'Pending Approval' + <|fim|> + ELSE 'Unknown' + END as order_status + FROM orders`, + llmOutput: `WHEN status = 'cancelled' THEN 'Cancelled'`, + expectedCompletion: `WHEN status = 'cancelled' THEN 'Cancelled'`, + }, + { + description: "Should autocomplete HTML paragraph content", + input: ` + + Document + + +

<|fim|>

+ +`, + llmOutput: `This is a paragraph with some sample text.`, + expectedCompletion: `This is a paragraph with some sample text.`, + filename: "test.html", + }, + { + description: "Should autocomplete HTML attributes within a tag", + input: `
+ > +
+

Title

+

Description text.

+
+
`, + llmOutput: `alt="Description of image"`, + expectedCompletion: `alt="Description of image"`, + filename: "test.html", + }, + { + description: "Should autocomplete HTML nested tags", + input: `
    +
  • Item 1
  • +
  • Item 2
  • +
  • Item 3
  • +
`, + llmOutput: `>Item 4`, + expectedCompletion: `>Item 4`, + filename: "test.html", + }, + + { + description: "Should complete a class method in Ruby", + input: ` +class Greeter + def initialize(name) + @name = name + end + + def greet + puts "Hello, <|fim|> + end +end + +g = Greeter.new("World") +g.greet +`, + llmOutput: "#{@name}!", + expectedCompletion: "#{@name}!", + filename: "greeter.rb", + }, + { + description: "Should complete Ruby if-else block", + input: ` +number = 10 + +if number > 5 + puts "Number is greater than 5" +<|fim|> +end +`, + llmOutput: `else + puts "Number is 5 or less"`, + expectedCompletion: `else + puts "Number is 5 or less"`, + filename: "conditional.rb", + }, + { + description: "Should complete Ruby array method", + input: ` +numbers = [1, 2, 3, 4, 5] +squared_numbers = numbers.<|fim|> +`, + llmOutput: `map { |n| n ** 2 }`, + expectedCompletion: `map { |n| n ** 2 }`, + filename: "array_methods.rb", + }, + { + description: "Should autocomplete a Java method within a class", + filename: "Calculator.java", + input: ` +public class Calculator { + private double result; + + public Calculator() { + this.result = 0.0; + } + + public void add(double number) { + result += number; +<|fim|>`, + llmOutput: ` + } + + public void subtract(double number) { + result -= number; + } +`, + expectedCompletion: ` + } + + public void subtract(double number) { + result -= number; + } +`, + }, + { + description: "Should autocomplete Java when inside a block", + filename: "Main.java", + input: ` +public class Main { + public static void main(String[] args) { + for (int i = 0; i < 10; i++) { + if (i % 2 == 0) { + System.out.println("Even: " + i); + } else { +<|fim|> + } + } + } +}`, + llmOutput: ` + System.out.println("Odd: " + i); +`, + expectedCompletion: ` + System.out.println("Odd: " + i); +`, + }, + { + description: "Should autocomplete Java within a string", + filename: "App.java", + input: ` +public class App { + public static void main(String[] args) { + String message = "Hello, <|fim|>"; + System.out.println(message); + } +}`, + llmOutput: `World`, + expectedCompletion: `World`, + }, + { + description: + "Should autocomplete a C++ class definition with a constructor", + filename: "test.cpp", + input: "class Vehicle { public: Vehicle(<|fim|>); };", + llmOutput: "int wheels, double weight", + expectedCompletion: "int wheels, double weight", + }, + { + description: "Should complete a C++ method declaration inside a class", + filename: "test.cpp", + input: + "class Calculator { public: int add(int a, int b); int subtract(int a, int b);<|fim|> };", + llmOutput: " int multiply(int a, int b);", + expectedCompletion: " int multiply(int a, int b);", + }, + + { + description: "Should autocomplete C++ for loop syntax", + filename: "test.cpp", + input: ` + int sum = 0; + for (int i = 0; i < 10; <|fim|>) { + sum += i; + } + `, + llmOutput: "i++", + expectedCompletion: "i++", + }, + { + description: "Should autocomplete a Markdown list with nested items", + filename: "test.md", + input: ` +- Item 1 +- Item 2 + - Subitem 1 + <|fim|> +- Item 3 +`, + llmOutput: ` - Subitem 2 + - Subitem 3 +`, + expectedCompletion: ` - Subitem 2 + - Subitem 3 +`, + }, + { + description: + "Should autocomplete a Markdown heading and preserve formatting", + filename: "test.md", + input: `# My Document + +## Introduction +This is a sample document for testing. + +## <|fim|> +### Conclusion +Thank you for reading. +`, + llmOutput: `Features +Here is a list of features: +- Feature 1 +- Feature 2 +`, + expectedCompletion: `Features +Here is a list of features: +- Feature 1 +- Feature 2 +`, + }, + { + description: "Should complete a Markdown code block", + filename: "test.md", + input: ` +Here is a sample JavaScript function: + +\`\`\`javascript +function sayHello() { + console.log("Hello, <|fim|> +} +\`\`\` +`, + llmOutput: `world!"); +`, + expectedCompletion: `world!"); +`, + }, + { + description: "Should autocomplete JSON object inside an array", + filename: "data.json", + input: `{ + "users": [ + { "id": 1, "name": "Alice" }, + { "id": 2, "name": "Bob" } + <|fim|> + ] +}`, + llmOutput: `, { "id": 3, "name": "Charlie" }`, + expectedCompletion: `, { "id": 3, "name": "Charlie" }`, + }, + { + description: "Should autocomplete nested JSON objects", + filename: "config.json", + input: `{ + "server": { + "host": "localhost", + "port": 8080, + "features": { + "enableLogging": true, + "maxConnections": 100 + <|fim|> + } +}`, + llmOutput: `, + "timeout": 5000 + }`, + expectedCompletion: `, + "timeout": 5000 + }`, + }, + { + description: "Should autocomplete JSON object with missing bracket", + filename: "settings.json", + input: `{ + "theme": "dark", + "language": "en"<|fim|> + `, + llmOutput: `, + "notifications": true + }`, + expectedCompletion: `, + "notifications": true + }`, + }, + { + description: "Should autocomplete within a CSV record", + filename: "test.csv", + input: `Name, Age, City +John Doe, 30, New York +Jane Smith<|fim|>`, + llmOutput: `, 25, Los Angeles`, + expectedCompletion: `, 25, Los Angeles`, + }, + { + description: + "Should complete CSV record when starting in the middle of a word", + filename: "test.csv", + input: `Product, Price, Quantity +Laptop, 1200, 5 +Smart<|fim|>`, + llmOutput: `phone, 800, 10`, + expectedCompletion: `phone, 800, 10`, + }, + { + description: "Should complete CSV structure adding closing brackets", + filename: "test.csv", + input: `ID, Name, JoiningDate +1, Alice, 2023-01-10 +2, B<|fim|>`, + llmOutput: `ob, 2023-02-10`, + expectedCompletion: `ob, 2023-02-10`, + }, + { + description: "Should complete YAML list item and preserve structure", + filename: "test.yaml", + input: ` + services: + - name: web + image: nginx + - name: app<|fim|> + volumes: + - volume1 + - volume2 + `, + llmOutput: ` + image: node + `, + expectedCompletion: ` + image: node + `, + }, + { + description: + "Should complete YAML key-value pair inside a nested structure", + filename: "test.yaml", + input: ` + version: '3' + services: + db: + image: postgres + environment: + POSTGRES_USER: user + POSTGRES_PASSWORD: pass + POSTGRES_DB: mydb<|fim|> + `, + llmOutput: ` + PGDATA: /var/lib/postgresql/data/pgdata + `, + expectedCompletion: ` + PGDATA: /var/lib/postgresql/data/pgdata + `, + }, + { + description: "Should complete YAML block within an existing block", + filename: "test.yaml", + input: ` + pipelines: + branches: + master: + - step: + name: Build and Test + script: + - npm install + - npm run test + - step: + name: Deploy<|fim|> + `, + llmOutput: ` + script: + - npm run deploy + `, + expectedCompletion: ` + script: + - npm run deploy + `, + }, + { + description: + "Should autocomplete a Rust function implementation inside a struct", + filename: "main.rs", + input: ` +struct Calculator { + result: f64, +} + +impl Calculator { + fn new() -> Self { + Calculator { result: 0.0 } + } + + fn add(&mut self, number: f64) { + self.result += number; + } + + fn subtract(&mut self, number: f64) { + self.result -= number; + } + + fn multiply(&mut self, number: f64) { + self.result *= number; + } + + fn divide(&mut self, number: f64) { + if number != 0.0 { + self.result /= number; + } else { + println!("Cannot divide by zero."); + } + } + + fn reset(&mut self) { + self.result = 0.0; + } + + fn get_result(&self) -> f64 { + self.result + } + + fn<|fim|> +} +`, + llmOutput: ` divide(&mut self, number: f64) { + if number != 0.0 { + self.result /= number; + } else { + println!("Cannot divide by zero."); + } +}`, + expectedCompletion: ` divide(&mut self, number: f64) { + if number != 0.0 { + self.result /= number; + } else { + println!("Cannot divide by zero."); + } +}`, + }, + { + description: "Should autocomplete Rust match arms", + filename: "main.rs", + input: ` +fn get_status_code_description(code: u16) -> &'static str { + match code { + 200 => "OK", + 404 => "Not Found", + 500 => "Internal Server Error", + <|fim|> + } +} +`, + llmOutput: `403 => "Forbidden", + 401 => "Unauthorized", + _ => "Unknown Status", +`, + expectedCompletion: `403 => "Forbidden", + 401 => "Unauthorized", + _ => "Unknown Status", +`, + }, + { + description: "Should autocomplete Rust struct definition", + filename: "main.rs", + input: ` +struct User { + id: u32, + username: String, + email: String, + is_active: bool, + <|fim|> +} + +impl User { + fn new(id: u32, username: String, email: String) -> Self { + User { + id, + username, + email, + is_active: true, + } + } +} +`, + llmOutput: `created_at: String, + updated_at: String,`, + expectedCompletion: `created_at: String, + updated_at: String,`, + }, + { + description: "Haskell: Nested pattern matching with let bindings", + filename: "NestedPattern.hs", + input: `module NestedPattern where + +data Tree a = Leaf a | Node (Tree a) (Tree a) + +sumTree :: Num a => Tree a -> a +sumTree (Leaf x) = x +sumTree (Node left right) = + let leftSum = <|fim|> + rightSum = sumTree right + in leftSum + rightSum`, + llmOutput: `sumTree left`, + expectedCompletion: `sumTree left`, + }, + { + description: "Haskell: Complex function with where clause and guards", + filename: "QuadraticSolver.hs", + input: `module QuadraticSolver where + +solveQuadratic :: (Ord a, Floating a) => a -> a -> a -> Maybe (a, a) +solveQuadratic a b c + | discriminant < 0 = Nothing + | otherwise = Just (x1, x2) + where + discriminant = b^2 - 4*a*c + sqrtD = sqrt discriminant + x1 = (-b + sqrtD) / (2*a) + <|fim|> = (-b - sqrtD) / (2*a)`, + llmOutput: `x2`, + expectedCompletion: `x2`, + }, + { + description: "Haskell: List comprehension with complex filter", + filename: "PrimeNumbers.hs", + input: `module PrimeNumbers where + +primesUpTo :: Int -> [Int] +primesUpTo n = [x | x <- [2..n], isPrime x] + where isPrime num = <|fim|> && all (\d -> num \`mod\` d /= 0) [2..(floor . sqrt $ fromIntegral num)]`, + llmOutput: `num > 1`, + expectedCompletion: `num > 1`, + }, + { + description: "Should autocomplete Dart class methods", + filename: "calculator.dart", + input: ` +class Calculator { + double result = 0.0; + + void add(double number) { + result += number; + } + + void multiply(double number) { + result *= number; + } + + <|fim|> + + double getResult() { + return result; + } +}`, + llmOutput: `void subtract(double number) { + result -= number; + }`, + expectedCompletion: `void subtract(double number) { + result -= number; + }`, + }, + { + description: "Should handle string interpolation in Dart", + filename: "greetings.dart", + input: ` +void main() { + var name = "World"; + print('Hello, <|fim|>!'); +}`, + llmOutput: `\${name}`, + expectedCompletion: `\${name}`, + }, + { + description: "Should autocomplete within a Dart function body", + filename: "counter.dart", + input: ` +class Counter { + int count = 0; + + void increment() { + count++; + } + + void decrement() { + <|fim|> + + void reset() { + count = 0; + } +}`, + llmOutput: `count--;`, + expectedCompletion: `count--;`, + }, + { + description: + "Should autocomplete Clojure function definition with missing closing parenthesis", + input: `(defn calculate-sum [a b] + (let [sum (+ a b)] + (println "The sum is" sum) + sum<|fim|>`, + llmOutput: `))`, + expectedCompletion: `))`, + filename: "test.clj", + }, + { + description: + "Should autocomplete missing part of a Clojure map within a function", + input: `(defn get-user [] + {:username "johndoe" + :email "johndoe@example.com" + :age 30 + <|fim|> + (println "User information loaded"))`, + llmOutput: `:location "Unknown"}`, + expectedCompletion: `:location "Unknown"}`, + filename: "test.clj", + }, + { + description: + "Should autocomplete inside a Clojure vector within a looping construct", + input: `(defn odd-numbers [] + (loop [nums [1 3 5<|fim|> 9 11]] + (when (seq nums) + (println (first nums)) + (recur (rest nums)))))`, + llmOutput: ` 7,`, + expectedCompletion: ` 7,`, + filename: "test.clj", + }, + { + description: "Should autocomplete R function definition", + filename: "calculate.R", + input: ` +calculate_mean <- function(numbers) { + total <- sum(numbers) + <|fim|> +}`, + llmOutput: `mean_value <- total / length(numbers) + return(mean_value)`, + expectedCompletion: `mean_value <- total / length(numbers) + return(mean_value)`, + }, + { + description: "Should complete R loop and print statement", + filename: "loopPrint.R", + input: ` +numbers <- c(1, 2, 3, 4, 5) +for (number in numbers) { + print(<|fim|>) +}`, + llmOutput: `number)`, + expectedCompletion: `number)`, + }, + { + description: "Should autocomplete R data frame creation", + filename: "dataFrame.R", + input: ` +data <- data.frame( + Name = c("Alice", "Bob", "Charlie"), + Age = c(25, 30, 35), + <|fim|> +)`, + llmOutput: `Height = c(165, 180, 175)`, + expectedCompletion: `Height = c(165, 180, 175)`, + }, + { + description: "Should autocomplete R if-else statement", + filename: "condition.R", + input: ` +grade <- 85 +if (grade >= 90) { + print("A") +} else if (grade >= 80) { + <|fim|> +} else { + print("C") +}`, + llmOutput: `print("B")`, + expectedCompletion: `print("B")`, + }, + { + description: "Should autocomplete R ggplot2 plot structure", + filename: "plot.R", + input: ` +library(ggplot2) + +ggplot(data=mtcars, aes(x=wt, y=mpg)) + + geom_point() + + <|fim|>`, + llmOutput: `geom_smooth(method='lm', se=FALSE)`, + expectedCompletion: `geom_smooth(method='lm', se=FALSE)`, + }, + { + description: "Should autocomplete Scala class with a method", + filename: "Person.scala", + input: `class Person(val name: String, val age: Int) { + def greet(): String = { + <|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."`, + }, + + { + description: "Should handle Scala case class with a missing field", + filename: "Person.scala", + input: `case class Address(city: String, postalCode: String) + case class Person(name: String, age: Int, address: Address) + + val alice = Person("Alice", 30, Address("Wonderland", <|fim|>))`, + llmOutput: `"12345")`, + expectedCompletion: `"12345")`, + }, + + { + description: "Should autocomplete Scala function with missing body bracket", + filename: "Math.scala", + input: `object MathUtils { + def add(a: Int, b: Int): Int = { + a + b<|fim|> + + def multiply(a: Int, b: Int): Int = { + a * b + } + } + + object Main extends App { + println(MathUtils.add(3, 5)) + println(MathUtils.multiply(4, 6)) + }`, + llmOutput: ` + }`, + expectedCompletion: ` + }`, + }, + { + description: "Should autocomplete C function definition", + filename: "math_utils.c", + input: `#include + +int add(int a, int b) { + return a + b; +} + +int multiply(int a, int b) { + return a * b; +} + +int subtract(int a, int b) { + <|fim|> +} + +int main() { + printf("Result: %d", add(2, 3)); + return 0; +}`, + llmOutput: `return a - b;`, + expectedCompletion: `return a - b;`, + }, + + { + description: "Should handle C struct with missing field initialization", + filename: "person.c", + input: `#include + +typedef struct { + char name[50]; + int age; + float height; +} Person; + +int main() { + Person alice = {"Alice", 30, <|fim|>}; + printf("Name: %s, Age: %d, Height: %.2f", alice.name, alice.age, alice.height); + return 0; +}`, + llmOutput: `5.5`, + expectedCompletion: `5.5`, + }, + + { + description: "Should autocomplete C function with missing body bracket", + filename: "area.c", + input: `#include + +double calculateCircleArea(double radius) { + const double pi = 3.14159; + return pi * radius * radius;<|fim|> + +double calculateRectangleArea(double length, double width) { + return length * width; +} + +int main() { + printf("Circle Area: %.2f", calculateCircleArea(5.0)); + printf("Rectangle Area: %.2f", calculateRectangleArea(4.0, 6.0)); + return 0; +}`, + llmOutput: ` +}`, + expectedCompletion: ` +}`, + }, + { + description: "Should autocomplete a simple Kotlin function declaration", + filename: "simpleFunction.kt", + input: ` +fun main() { + println("Hello, World!") +} + +fun calculateArea(length: Double, width: Double): Double <|fim|>`, + llmOutput: `{ + return length * width +}`, + expectedCompletion: `{ + return length * width +}`, + }, + { + description: "Should handle autocomplete inside a Kotlin data class", + filename: "dataClass.kt", + input: ` +data class User( + val id: Int, + val name: String, + val email: String, + <|fim|> +)`, + llmOutput: `val age: Int`, + expectedCompletion: `val age: Int`, + }, + { + description: + "Should complete Kotlin if-else structure with missing brackets", + filename: "controlStructure.kt", + input: ` +fun getMax(a: Int, b: Int): Int { + if (a > b<|fim|> + } else { + return b + } +}`, + llmOutput: `) { + return a`, + expectedCompletion: `) { + return a`, + }, + { + description: "Should autocomplete Solidity function definition", + filename: "SimpleStorage.sol", + input: ` +pragma solidity ^0.8.0; + +contract SimpleStorage { + uint private data; + + function set(uint x) public { + data = x; + } + + function get() public view returns (uint) { + <|fim|> + } +} + `, + llmOutput: `return data;`, + expectedCompletion: `return data;`, + }, + + { + description: "Should autocomplete Solidity event with parameters", + filename: "EventExample.sol", + input: ` +pragma solidity ^0.8.0; + +contract EventExample { + event DataStored(uint indexed id, string content); + + function storeData(uint id, string memory content) public { + emit DataStored(<|fim|>); + } +} + `, + llmOutput: `id, content`, + expectedCompletion: `id, content`, + }, + + { + description: "Should handle Solidity struct definition completion", + filename: "StructDefinition.sol", + input: ` +pragma solidity ^0.8.0; + +contract StructExample { + struct Person { + string name; + uint age; + address wallet; + } + + Person[] private people; + + function addPerson(string memory name, uint age, address wallet) public { + people.push(Person(name, age, wallet)); + } + + function getFirstPerson<|fim|> +} + `, + llmOutput: `() public view returns (string memory, uint, address) { + if (people.length > 0) { + Person storage person = people[0]; + return (person.name, person.age, person.wallet); + } + return ("", 0, address(0)); + }`, + expectedCompletion: `() public view returns (string memory, uint, address) { + if (people.length > 0) { + Person storage person = people[0]; + return (person.name, person.age, person.wallet); + } + return ("", 0, address(0)); + }`, + }, + { + description: "Should autocomplete TypeScript interface properties", + filename: "User.ts", + input: ` +interface User { + id: number; + name: string; + e<|fim|> +} +`, + llmOutput: `mail: string; + age: number; +}`, + expectedCompletion: `mail: string; + age: number; +}`, + }, + + { + description: + "Should autocomplete a TypeScript arrow function inside a variable assignment", + filename: "mathOperations.ts", + input: ` +const addNumbers = (a: number, b: number): number => { + return a + b; +}; + +const multiplyNumbers = (a: number, b: number): number => { + re<|fim|> +} + +console.log(multiplyNumbers(2, 3)); +`, + llmOutput: `turn a * b;`, + expectedCompletion: `turn a * b;`, + }, + + { + description: + "Should handle autocomplete inside a nested TypeScript class method", + filename: "Account.ts", + input: ` +class Account { + private balance: number = 0; + + deposit(amount: number) { + this.balance += amount; + return this.balance; + } + + withdraw(amount: number) { + if (amount > this.balance) { + throw new Error("Insufficient funds"); + } + this.balance -= amount; + return thi<|fim|> + } +} +`, + llmOutput: `s.balance;`, + expectedCompletion: `s.balance;`, + }, + + { + description: "Should autocomplete a TypeScript generic function", + filename: "GenericFunction.ts", + input: ` +function identity(arg: T): T { + return ar<|fim|> +} + +console.log(identity(5)); +`, + llmOutput: `g;`, + expectedCompletion: `g;`, + }, + + { + description: + "Should autocomplete a TypeScript promise within an asynchronous function", + filename: "asyncFunction.ts", + input: ` +async function fetchData(url: string): Promise { + const response = await fetch(url); + <|fim|> + return data; +} + +fetchData('https://api.example.com/data'); +`, + llmOutput: `const data = await response.json();`, + expectedCompletion: `const data = await response.json();`, + }, + + { + description: + "Should autocomplete a C# class with a constructor and property", + filename: "Person.cs", + input: `using System; + +public class Person +{ + public string Name { get; set; } + public int Age { get; set; } + + public Person(string name, int <|fim|> +}`, + llmOutput: `age) + { + Name = name; + Age = age; + }`, + expectedCompletion: `age) + { + Name = name; + Age = age; + }`, + }, + { + description: "Should autocomplete a C# interface method", + filename: "IGreetable.cs", + input: `public interface IGreetable +{ + void <|fim|> +}`, + llmOutput: `Greet();`, + expectedCompletion: `Greet();`, + }, + { + description: "Should autocomplete inside C# method with if condition", + filename: "Calculator.cs", + input: `using System; + +public class Calculator +{ + public int Add(int a, int b) + { + if(<|fim|>) + { + return a + b; + } + return 0; + } +}`, + llmOutput: `a > 0 && b > 0`, + expectedCompletion: `a > 0 && b > 0`, + }, + { + description: "Should complete a simple Julia function", + filename: "simpleFunction.jl", + input: `function calculate_area(length, width) + <|fim|> +end +`, + llmOutput: `return length * width`, + expectedCompletion: `return length * width`, + }, + { + description: "Should autocomplete Julia for loop", + filename: "loop.jl", + input: `numbers = [1, 2, 3, 4, 5] +squared_numbers = [] + +for num in numbers + <|fim|> +end + +println(squared_numbers) +`, + llmOutput: `push!(squared_numbers, num^2)`, + expectedCompletion: `push!(squared_numbers, num^2)`, + }, + { + description: "Should complete a Julia struct definition", + filename: "structDefinition.jl", + input: `struct Person + first_name::String + last_name::String + age::Int + address::Address +end + +struct Address + street::String + city::String + <|fim|> +end +`, + llmOutput: `state::String + zip_code::String`, + expectedCompletion: `state::String + zip_code::String`, + }, + { + description: "Should complete a Julia dictionary access", + filename: "dictionary.jl", + input: `grades = Dict("Alice" => 90, "Bob" => 85, "Eve" => 88) + +function get_grade(student_name) + return grades[<|fim|>] +end + +println(get_grade("Alice")) # Should print 90 +`, + llmOutput: `student_name`, + expectedCompletion: `student_name`, + }, + { + description: "Should complete a Julia module declaration", + filename: "moduleDeclaration.jl", + input: `module MathOperations + +export add, subtract + +function add(a, b) + return a + b +end + +function subtract(a, b) + return a - b +end + +<|fim|> +`, + llmOutput: `end`, + expectedCompletion: `end`, + }, + { + description: "Should complete F# let-binding with function definition", + filename: "mathModule.fs", + input: `module MathModule + +let calculateArea length width = + <|fim|>`, + llmOutput: `length * width`, + expectedCompletion: `length * width`, + }, + + { + description: "Should complete incomplete F# type definition", + filename: "personType.fs", + input: `type Person = { + FirstName: string + LastName: string + Age: int<|fim|> +} + +let john = { FirstName = "John"; LastName = "Doe"; Age = 30 }`, + llmOutput: ` + Address: string +}`, + expectedCompletion: ` + Address: string +}`, + }, + + { + description: "Should complete F# pattern matching expression", + filename: "patternMatching.fs", + input: `let describeNumber number = + match number with + | 0 -> "Zero" + | 1 -> "One" + | <|fim|>`, + llmOutput: `2 -> "Two" + | _ -> "Other"`, + expectedCompletion: `2 -> "Two" + | _ -> "Other"`, + }, + + { + description: "Should complete F# list comprehension expression", + filename: "listComprehension.fs", + input: `let squares = [ for x in 1..10 -> x * x ] +let evenSquares = [ for x in squares do if x % 2 = 0 then yield x ] +let oddSquares = [<|fim|>]`, + llmOutput: ` for x in squares do if x % 2 <> 0 then yield x ]`, + expectedCompletion: ` for x in squares do if x % 2 <> 0 then yield x ]`, + }, + + { + description: "Should complete an F# recursive function", + filename: "recursiveFunctions.fs", + input: `let rec factorial n = + if n <= 1 then 1 + else n <|fim|> factorial (n - 1)`, + llmOutput: ` * `, + expectedCompletion: ` * `, + }, + + { + description: "Should complete F# member method inside a class type", + filename: "bankAccount.fs", + input: `type BankAccount(owner: string, initialBalance: float) = + let mutable balance = initialBalance + + member this.Deposit amount = + balance <- balance + amount + this + <|fim|>`, + llmOutput: ` + member this.Withdraw amount = + if amount > balance then + failwith "Insufficient funds" + balance <- balance - amount + this`, + expectedCompletion: ` + member this.Withdraw amount = + if amount > balance then + failwith "Insufficient funds" + balance <- balance - amount + this`, + }, + + { + description: "Should complete F# async workflow function", + filename: "asyncWorkflow.fs", + input: `let fetchDataAsync url = + async { + use client = new System.Net.Http.HttpClient() + <|fim|> + }`, + llmOutput: `let! response = client.GetStringAsync(url) + return response`, + expectedCompletion: `let! response = client.GetStringAsync(url) + return response`, + }, + { + description: "Should autocomplete SCSS nested class starting inside a rule", + filename: "styles.scss", + input: `nav { + display: flex; + justify-content: space-between; + .logo { + font-size: 1.5rem; + color: #333; + + .brand<|fim|> + } + + ul { + list-style: none; + display: flex; + gap: 1rem; + } +}`, + llmOutput: `-name { + font-weight: bold; + text-transform: uppercase; +}`, + expectedCompletion: `-name { + font-weight: bold; + text-transform: uppercase; +}`, + }, + + { + description: "Should handle SCSS mixin within a class", + filename: "styles.scss", + input: `.card { + border: 1px solid #ccc; + padding: 10px; + + @include<|fim|> + + &:hover { + box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); + } +}`, + llmOutput: ` transition(all 0.3s ease);`, + expectedCompletion: ` transition(all 0.3s ease);`, + }, + + { + description: + "Should autocomplete SCSS variable in the middle of a statement", + filename: "styles.scss", + input: `$primary-color: #007bff; +$secondary-color: #6c757d; + +.button { + background-color: <|fim|> color; + padding: 10px 15px; + border: none; + color: #fff; + border-radius: 4px; +}`, + llmOutput: `$primary-`, + expectedCompletion: `$primary-`, + }, + { + description: "Should autocomplete Vue component method", + filename: "MyComponent.vue", + input: ` + + +`, + llmOutput: `() { + this.count = 0; + }`, + expectedCompletion: `() { + this.count = 0; + }`, + }, + { + description: "Should autocomplete Vue computed property", + filename: "UserComponent.vue", + input: ` + + +`, + llmOutput: `() { + return this.firstName + ' ' + this.lastName; + }`, + expectedCompletion: `() { + return this.firstName + ' ' + this.lastName; + }`, + }, + { + description: "Should autocomplete Vue method using props", + filename: "TodoItem.vue", + input: ` + + +`, + llmOutput: `this.completed`, + expectedCompletion: `this.completed`, + }, + { + description: "Should autocomplete Svelte reactive statement", + filename: "Counter.svelte", + input: ` + + + +`, + llmOutput: `doubledCount = count * 2`, + expectedCompletion: `doubledCount = count * 2`, + }, + + { + description: "Should autocomplete Svelte component inside HTML", + filename: "NestedComponent.svelte", + input: ` + + +
+

Hello Svelte

+ /> +
+`, + llmOutput: `name="World"`, + expectedCompletion: `name="World"`, + }, + + { + description: "Should handle autocomplete in Svelte each block", + filename: "List.svelte", + input: ` + + +
    + {#each items as item} +
  • {item}
  • + {/each<|fim|> +
+`, + llmOutput: `}`, + expectedCompletion: `}`, + }, +]; diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts new file mode 100644 index 000000000..9dbf9b6aa --- /dev/null +++ b/core/autocomplete/filtering/test/util.ts @@ -0,0 +1,77 @@ +import fs from "node:fs"; +import path from "node:path"; +import Mock from "../../../llm/llms/Mock"; +import { testConfigHandler, testIde } from "../../../test/util/fixtures"; +import { + AutocompleteInput, + CompletionProvider, +} from "../../CompletionProvider"; + +const FIM_DELIMITER = "<|fim|>"; + +function parseFimExample(text: string): { prefix: string; suffix: string } { + const [prefix, suffix] = text.split(FIM_DELIMITER); + return { prefix, suffix }; +} + +export interface AutocompleteFileringTestInput { + description: string; + filename: string; + input: string; + llmOutput: string; + expectedCompletion: string | null; + options?: { + only?: boolean; + }; +} + +export async function testAutocompleteFiltering( + test: AutocompleteFileringTestInput, +) { + const { prefix, suffix } = parseFimExample(test.input); + + // Setup necessary objects + const llm = new Mock({ + model: "mock", + }); + llm.completion = test.llmOutput; + const ide = testIde; + const configHandler = testConfigHandler; + + // Create a real file + const [workspaceDir] = await ide.getWorkspaceDirs(); + const filepath = path.join(workspaceDir, test.filename); + fs.writeFileSync(filepath, test.input.replace(FIM_DELIMITER, "")); + + // Prepare completion input and provider + const completionProvider = new CompletionProvider( + configHandler, + ide, + async () => llm, + () => {}, + async () => [], + ); + + const line = prefix.split("\n").length - 1; + const character = prefix.split("\n")[line].length; + const autocompleteInput: AutocompleteInput = { + clipboardText: "", + completionId: "test-completion-id", + filepath, + pos: { + line, + character, + }, + recentlyEditedFiles: [], + recentlyEditedRanges: [], + }; + + // Generate a completion + const result = await completionProvider.provideInlineCompletionItems( + autocompleteInput, + undefined, + ); + + // Ensure that we return the text that is wanted to be displayed + expect(result?.completion).toEqual(test.expectedCompletion); +} diff --git a/core/autocomplete/util.ts b/core/autocomplete/generation/GeneratorReuseManager.ts similarity index 52% rename from core/autocomplete/util.ts rename to core/autocomplete/generation/GeneratorReuseManager.ts index d07658d17..7a67e686f 100644 --- a/core/autocomplete/util.ts +++ b/core/autocomplete/generation/GeneratorReuseManager.ts @@ -1,78 +1,4 @@ -export class ListenableGenerator { - private _source: AsyncGenerator; - private _buffer: T[] = []; - private _listeners: Set<(value: T) => void> = new Set(); - private _isEnded = false; - - constructor( - source: AsyncGenerator, - private readonly onError: (e: any) => void, - ) { - this._source = source; - this._start(); - } - - public cancel() { - this._isEnded = true; - } - - private async _start() { - try { - for await (const value of this._source) { - if (this._isEnded) { - break; - } - this._buffer.push(value); - for (const listener of this._listeners) { - listener(value); - } - } - } catch (e) { - this.onError(e); - } finally { - this._isEnded = true; - for (const listener of this._listeners) { - listener(null as any); - } - } - } - - listen(listener: (value: T) => void) { - this._listeners.add(listener); - for (const value of this._buffer) { - listener(value); - } - if (this._isEnded) { - listener(null as any); - } - } - - async *tee(): AsyncGenerator { - try { - let i = 0; - while (i < this._buffer.length) { - yield this._buffer[i++]; - } - while (!this._isEnded) { - let resolve: (value: any) => void; - const promise = new Promise((res) => { - resolve = res; - this._listeners.add(resolve!); - }); - await promise; - this._listeners.delete(resolve!); - - // Possible timing caused something to slip in between - // timers so we iterate over the buffer - while (i < this._buffer.length) { - yield this._buffer[i++]; - } - } - } finally { - // this._listeners.delete(resolve!); - } - } -} +import { ListenableGenerator } from "./ListenableGenerator"; export class GeneratorReuseManager { currentGenerator: ListenableGenerator | undefined; diff --git a/core/autocomplete/generation/ListenableGenerator.ts b/core/autocomplete/generation/ListenableGenerator.ts new file mode 100644 index 000000000..0cc9f664e --- /dev/null +++ b/core/autocomplete/generation/ListenableGenerator.ts @@ -0,0 +1,75 @@ +export class ListenableGenerator { + private _source: AsyncGenerator; + private _buffer: T[] = []; + private _listeners: Set<(value: T) => void> = new Set(); + private _isEnded = false; + + constructor( + source: AsyncGenerator, + private readonly onError: (e: any) => void, + ) { + this._source = source; + this._start(); + } + + public cancel() { + this._isEnded = true; + } + + private async _start() { + try { + for await (const value of this._source) { + if (this._isEnded) { + break; + } + this._buffer.push(value); + for (const listener of this._listeners) { + listener(value); + } + } + } catch (e) { + this.onError(e); + } finally { + this._isEnded = true; + for (const listener of this._listeners) { + listener(null as any); + } + } + } + + listen(listener: (value: T) => void) { + this._listeners.add(listener); + for (const value of this._buffer) { + listener(value); + } + if (this._isEnded) { + listener(null as any); + } + } + + async *tee(): AsyncGenerator { + try { + let i = 0; + while (i < this._buffer.length) { + yield this._buffer[i++]; + } + while (!this._isEnded) { + let resolve: (value: any) => void; + const promise = new Promise((res) => { + resolve = res; + this._listeners.add(resolve!); + }); + await promise; + this._listeners.delete(resolve!); + + // Possible timing caused something to slip in between + // timers so we iterate over the buffer + while (i < this._buffer.length) { + yield this._buffer[i++]; + } + } + } finally { + // this._listeners.delete(resolve!); + } + } +} diff --git a/core/autocomplete/postprocessing.ts b/core/autocomplete/postprocessing/index.ts similarity index 93% rename from core/autocomplete/postprocessing.ts rename to core/autocomplete/postprocessing/index.ts index cb3ada459..af0c698e0 100644 --- a/core/autocomplete/postprocessing.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -1,6 +1,6 @@ -import type { ILLM } from "../index.js"; -import { longestCommonSubsequence } from "../util/lcs.js"; -import { lineIsRepeated } from "./streamTransforms/lineStream.js"; +import type { ILLM } from "../../index.js"; +import { longestCommonSubsequence } from "../../util/lcs.js"; +import { lineIsRepeated } from "../filtering/streamTransforms/lineStream.js"; function rewritesLineAbove(completion: string, prefix: string): boolean { const lineAbove = prefix diff --git a/core/autocomplete/types.ts b/core/autocomplete/types.ts new file mode 100644 index 000000000..745ea563b --- /dev/null +++ b/core/autocomplete/types.ts @@ -0,0 +1,38 @@ +import { Position, Range, TabAutocompleteOptions } from ".."; +import { RangeInFileWithContents } from "../commands/util"; +import { RecentlyEditedRange } from "./recentlyEdited"; + +export interface AutocompleteInput { + completionId: string; + filepath: string; + pos: Position; + recentlyEditedFiles: RangeInFileWithContents[]; + recentlyEditedRanges: RecentlyEditedRange[]; + clipboardText: string; + // Used for notebook files + manuallyPassFileContents?: string; + // Used for VS Code git commit input box + manuallyPassPrefix?: string; + selectedCompletionInfo?: { + text: string; + range: Range; + }; + injectDetails?: string; +} + +export interface AutocompleteOutcome extends TabAutocompleteOptions { + accepted?: boolean; + time: number; + prefix: string; + suffix: string; + prompt: string; + completion: string; + modelProvider: string; + modelName: string; + completionOptions: any; + cacheHit: boolean; + filepath: string; + gitRepo?: string; + completionId: string; + uniqueId: string; +} diff --git a/core/autocomplete/ast.ts b/core/autocomplete/util/ast.ts similarity index 94% rename from core/autocomplete/ast.ts rename to core/autocomplete/util/ast.ts index 139b22dbf..600b84126 100644 --- a/core/autocomplete/ast.ts +++ b/core/autocomplete/util/ast.ts @@ -1,6 +1,6 @@ import Parser from "web-tree-sitter"; -import { RangeInFileWithContents } from "../commands/util.js"; -import { getParserForFile } from "../util/treeSitter.js"; +import { RangeInFileWithContents } from "../../commands/util.js"; +import { getParserForFile } from "../../util/treeSitter.js"; export type AstPath = Parser.SyntaxNode[]; diff --git a/core/core.ts b/core/core.ts index 8ce7c7a5d..d7bd1846f 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,6 +1,6 @@ import { v4 as uuidv4 } from "uuid"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; -import { CompletionProvider } from "./autocomplete/completionProvider"; +import { CompletionProvider } from "./autocomplete/CompletionProvider"; import { ConfigHandler } from "./config/ConfigHandler"; import { setupBestConfig, diff --git a/core/edit/lazy/deterministic.ts b/core/edit/lazy/deterministic.ts index e9cbdf921..bb938b050 100644 --- a/core/edit/lazy/deterministic.ts +++ b/core/edit/lazy/deterministic.ts @@ -2,7 +2,7 @@ import { distance } from "fastest-levenshtein"; import path from "path"; import Parser from "web-tree-sitter"; import { DiffLine } from "../.."; -import { LANGUAGES } from "../../autocomplete/languages"; +import { LANGUAGES } from "../../autocomplete/constants/AutocompleteLanguageInfo"; import { myersDiff } from "../../diff/myers"; import { getParserForFile } from "../../util/treeSitter"; import { findInAst } from "./findInAst"; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index e2d512950..d82454184 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -15,7 +15,7 @@ import type { SessionInfo, SiteIndexingConfig, } from "../"; -import type { AutocompleteInput } from "../autocomplete/completionProvider"; +import type { AutocompleteInput } from "../autocomplete/CompletionProvider"; import { ProfileDescription } from "../config/ConfigHandler"; export type ProtocolGeneratorType = AsyncGenerator<{ From e6d431d1c5032bba1154824b92e52b001cbc83f3 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 01:00:07 -0700 Subject: [PATCH 02/43] autoformat --- core/autocomplete/context/ranking/slidingWindow.ts | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/core/autocomplete/context/ranking/slidingWindow.ts b/core/autocomplete/context/ranking/slidingWindow.ts index 37d1a7d9e..54ec763f2 100644 --- a/core/autocomplete/context/ranking/slidingWindow.ts +++ b/core/autocomplete/context/ranking/slidingWindow.ts @@ -1,8 +1,5 @@ -import { RangeInFileWithContents } from "../commands/util.js"; -import { - AutocompleteSnippet, - jaccardSimilarity, -} from "./context/ranking/index.js"; +import { RangeInFileWithContents } from "../../../commands/util.js"; +import { AutocompleteSnippet, jaccardSimilarity } from "./index.js"; function* slidingWindow( content: string, From 4e57b761398b555e601ec015a611ec232f272817 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 01:05:51 -0700 Subject: [PATCH 03/43] fix tsc errs --- core/autocomplete/completionProvider.ts | 6 +++++- core/autocomplete/context/retrieval.ts | 4 ++-- .../filtering/streamTransforms/charStream.test.ts | 2 +- .../filtering/streamTransforms/lineStream.test.ts | 2 +- .../filtering/streamTransforms/lineStream.ts | 4 ++-- core/autocomplete/filtering/test/util.ts | 6 ++---- core/commands/slash/edit.ts | 2 +- core/core.ts | 2 +- core/edit/lazy/replace.ts | 2 +- core/edit/lazy/streamLazyApply.ts | 4 ++-- core/edit/streamDiffLines.ts | 9 ++------- core/llm/llms/Mock.ts | 6 +++--- core/protocol/core.ts | 2 +- 13 files changed, 24 insertions(+), 27 deletions(-) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 8458e1281..bc910161a 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -32,7 +32,11 @@ import { getConfigJsonPath } from "../util/paths.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; -import { stopAtStopTokens } from "./filtering/streamTransforms/charStream.js"; +import { + noFirstCharNewline, + onlyWhitespaceAfterEndOfLine, + stopAtStopTokens, +} from "./filtering/streamTransforms/charStream.js"; import { avoidPathLineAndEmptyComments, noTopLevelKeywordsMidline, diff --git a/core/autocomplete/context/retrieval.ts b/core/autocomplete/context/retrieval.ts index 422b377bd..45d6f2b64 100644 --- a/core/autocomplete/context/retrieval.ts +++ b/core/autocomplete/context/retrieval.ts @@ -1,5 +1,5 @@ -import { BranchAndDir, Chunk } from "../index.js"; -import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearchCodebaseIndex.js"; +import { BranchAndDir, Chunk } from "../.."; +import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex"; export async function fullTextRetrieve( prefix: string, diff --git a/core/autocomplete/filtering/streamTransforms/charStream.test.ts b/core/autocomplete/filtering/streamTransforms/charStream.test.ts index b5504ad63..7ab8923fc 100644 --- a/core/autocomplete/filtering/streamTransforms/charStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/charStream.test.ts @@ -1,4 +1,4 @@ -import { stopAtStopTokens } from "./streamTransforms/charStream"; +import { stopAtStopTokens } from "./charStream"; describe("stopAtStopTokens", () => { async function* createMockStream(chunks: string[]): AsyncGenerator { diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts index ace94eaa4..df8cd1263 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts @@ -1,5 +1,5 @@ import { jest } from "@jest/globals"; -import * as lineStream from "./streamTransforms/lineStream"; +import * as lineStream from "./lineStream"; describe("lineStream", () => { let mockFullStop: jest.Mock; diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 5990bbf3c..918acaf26 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -1,6 +1,6 @@ import { distance } from "fastest-levenshtein"; -import { DiffLine } from "../.."; -import { LineStream } from "../../diff/util"; +import { DiffLine } from "../../.."; +import { LineStream } from "../../../diff/util"; export type LineFilter = (args: { lines: LineStream; diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index 9dbf9b6aa..37890e1e8 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -2,10 +2,8 @@ import fs from "node:fs"; import path from "node:path"; import Mock from "../../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../../test/util/fixtures"; -import { - AutocompleteInput, - CompletionProvider, -} from "../../CompletionProvider"; +import { CompletionProvider } from "../../completionProvider"; +import { AutocompleteInput } from "../../types"; const FIM_DELIMITER = "<|fim|>"; diff --git a/core/commands/slash/edit.ts b/core/commands/slash/edit.ts index aafafa67e..fc71838df 100644 --- a/core/commands/slash/edit.ts +++ b/core/commands/slash/edit.ts @@ -6,7 +6,7 @@ import { fixCodeLlamaFirstLineIndentation, stopAtLines, streamWithNewLines, -} from "../../autocomplete/streamTransforms/lineStream"; +} from "../../autocomplete/filtering/streamTransforms/lineStream"; import { streamLines } from "../../diff/util"; import { stripImages } from "../../llm/images"; import { diff --git a/core/core.ts b/core/core.ts index d7bd1846f..8ce7c7a5d 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,6 +1,6 @@ import { v4 as uuidv4 } from "uuid"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; -import { CompletionProvider } from "./autocomplete/CompletionProvider"; +import { CompletionProvider } from "./autocomplete/completionProvider"; import { ConfigHandler } from "./config/ConfigHandler"; import { setupBestConfig, diff --git a/core/edit/lazy/replace.ts b/core/edit/lazy/replace.ts index b4b6164cc..e6c3183f0 100644 --- a/core/edit/lazy/replace.ts +++ b/core/edit/lazy/replace.ts @@ -2,7 +2,7 @@ import { ILLM } from "../.."; import { filterLeadingNewline, stopAtLines, -} from "../../autocomplete/streamTransforms/lineStream"; +} from "../../autocomplete/filtering/streamTransforms/lineStream"; import { streamLines } from "../../diff/util"; import { dedent } from "../../util"; diff --git a/core/edit/lazy/streamLazyApply.ts b/core/edit/lazy/streamLazyApply.ts index dece697ca..f101c6981 100644 --- a/core/edit/lazy/streamLazyApply.ts +++ b/core/edit/lazy/streamLazyApply.ts @@ -2,7 +2,7 @@ import { filterLeadingAndTrailingNewLineInsertion, filterLeadingNewline, stopAtLines, -} from "../../autocomplete/streamTransforms/lineStream"; +} from "../../autocomplete/filtering/streamTransforms/lineStream.js"; import { streamDiff } from "../../diff/streamDiff.js"; import { LineStream, streamLines } from "../../diff/util.js"; import { DiffLine, ILLM } from "../../index.js"; @@ -43,7 +43,7 @@ export async function* streamLazyApply( let lazyCompletionLines = streamLines(lazyCompletion, true); // Process line output // lazyCompletionLines = filterEnglishLinesAtStart(lazyCompletionLines); - lazyCompletionLines = stopAtLines(lazyCompletionLines, () => { }, ["```"]); + lazyCompletionLines = stopAtLines(lazyCompletionLines, () => {}, ["```"]); lazyCompletionLines = filterLeadingNewline(lazyCompletionLines); // Fill in unchanged code diff --git a/core/edit/streamDiffLines.ts b/core/edit/streamDiffLines.ts index dbab5841c..f49f3f911 100644 --- a/core/edit/streamDiffLines.ts +++ b/core/edit/streamDiffLines.ts @@ -5,15 +5,10 @@ import { filterLeadingAndTrailingNewLineInsertion, skipLines, stopAtLines, -} from "../autocomplete/streamTransforms/lineStream.js"; +} from "../autocomplete/filtering/streamTransforms/lineStream.js"; import { streamDiff } from "../diff/streamDiff.js"; import { streamLines } from "../diff/util.js"; -import { - ChatMessage, - DiffLine, - ILLM, - LLMFullCompletionOptions, -} from "../index.js"; +import { ChatMessage, DiffLine, ILLM } from "../index.js"; import { gptEditPrompt } from "../llm/templates/edit.js"; import { Telemetry } from "../util/posthog.js"; diff --git a/core/llm/llms/Mock.ts b/core/llm/llms/Mock.ts index d5e2ef59c..d151ba3b2 100644 --- a/core/llm/llms/Mock.ts +++ b/core/llm/llms/Mock.ts @@ -2,14 +2,14 @@ import { ChatMessage, CompletionOptions, ModelProvider } from "../../index.js"; import { BaseLLM } from "../index.js"; class Mock extends BaseLLM { - static Completion = "Test Completion"; + completion = "Test Completion"; static providerName: ModelProvider = "mock"; protected async *_streamComplete( prompt: string, options: CompletionOptions, ): AsyncGenerator { - yield Mock.Completion; + yield this.completion; } protected async *_streamChat( @@ -18,7 +18,7 @@ class Mock extends BaseLLM { ): AsyncGenerator { yield { role: "assistant", - content: Mock.Completion, + content: this.completion, }; } } diff --git a/core/protocol/core.ts b/core/protocol/core.ts index d82454184..090ee2c5a 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -15,7 +15,7 @@ import type { SessionInfo, SiteIndexingConfig, } from "../"; -import type { AutocompleteInput } from "../autocomplete/CompletionProvider"; +import { AutocompleteInput } from "../autocomplete/types"; import { ProfileDescription } from "../config/ConfigHandler"; export type ProtocolGeneratorType = AsyncGenerator<{ From 911256bad10cab2824f5d3b491b09b30948b12d6 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 19:52:07 -0700 Subject: [PATCH 04/43] refactor debouncing --- core/autocomplete/AutocompleteDebouncer.ts | 32 ++++++ core/autocomplete/completionProvider.ts | 105 ++++++------------ core/autocomplete/context/retrieval.ts | 23 ---- core/autocomplete/filtering/filter.ts | 4 - core/autocomplete/postprocessing/index.ts | 6 +- .../AutocompleteTemplate.ts | 0 core/autocomplete/templating/index.ts | 19 ++++ 7 files changed, 89 insertions(+), 100 deletions(-) create mode 100644 core/autocomplete/AutocompleteDebouncer.ts delete mode 100644 core/autocomplete/context/retrieval.ts delete mode 100644 core/autocomplete/filtering/filter.ts rename core/autocomplete/{constants => templating}/AutocompleteTemplate.ts (100%) create mode 100644 core/autocomplete/templating/index.ts diff --git a/core/autocomplete/AutocompleteDebouncer.ts b/core/autocomplete/AutocompleteDebouncer.ts new file mode 100644 index 000000000..f8bcc474f --- /dev/null +++ b/core/autocomplete/AutocompleteDebouncer.ts @@ -0,0 +1,32 @@ +import { v4 as uuidv4 } from "uuid"; +export class AutocompleteDebouncer { + private debounceTimeout: NodeJS.Timeout | undefined = undefined; + private debouncing = false; + private lastUUID: string | undefined = undefined; + + async delayAndShouldDebounce(debounceDelay: number): Promise { + // Debounce + const uuid = uuidv4(); + this.lastUUID = uuid; + + // Debounce + if (this.debouncing) { + this.debounceTimeout?.refresh(); + const lastUUID = await new Promise((resolve) => + setTimeout(() => { + resolve(this.lastUUID); + }, debounceDelay), + ); + if (uuid !== lastUUID) { + return true; + } + } else { + this.debouncing = true; + this.debounceTimeout = setTimeout(async () => { + this.debouncing = false; + }, debounceDelay); + } + + return false; + } +} diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 012b525ca..4f47579a4 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -1,7 +1,6 @@ import ignore from "ignore"; import OpenAI from "openai"; import path from "path"; -import { v4 as uuidv4 } from "uuid"; import { ConfigHandler } from "../config/ConfigHandler.js"; import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { streamLines } from "../diff/util.js"; @@ -16,19 +15,19 @@ import { Telemetry } from "../util/posthog.js"; import { getRangeInString } from "../util/ranges.js"; import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; -import { getTemplateForModel } from "./constants/AutocompleteTemplate.js"; import { constructAutocompletePrompt, languageForFilepath, } from "./constructPrompt.js"; import { AutocompleteSnippet } from "./context/ranking/index.js"; import { RootPathContextService } from "./context/RootPathContextService.js"; -import { isOnlyWhitespace } from "./filtering/filter.js"; import { GeneratorReuseManager } from "./generation/GeneratorReuseManager.js"; import { postprocessCompletion } from "./postprocessing/index.js"; +import { getTemplateForModel } from "./templating/AutocompleteTemplate.js"; // @prettier-ignore import Handlebars from "handlebars"; import { getConfigJsonPath } from "../util/paths.js"; +import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; @@ -41,6 +40,7 @@ import { stopAtSimilarLine, streamWithNewLines, } from "./filtering/streamTransforms/lineStream.js"; +import { formatExternalSnippet } from "./templating/index.js"; import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -60,23 +60,6 @@ const LOCAL_PROVIDERS: ModelProvider[] = [ "text-gen-webui", ]; -function formatExternalSnippet( - filepath: string, - snippet: string, - language: AutocompleteLanguageInfo, -) { - const comment = language.singleLineComment; - const lines = [ - `${comment} Path: ${getBasename(filepath)}`, - ...snippet - .trim() - .split("\n") - .map((line) => `${comment} ${line}`), - comment, - ]; - return lines.join("\n"); -} - export type GetLspDefinitionsFunction = ( filepath: string, contents: string, @@ -86,9 +69,14 @@ export type GetLspDefinitionsFunction = ( ) => Promise; export class CompletionProvider { - private static debounceTimeout: NodeJS.Timeout | undefined = undefined; - private static debouncing = false; - private static lastUUID: string | undefined = undefined; + private importDefinitionsService: ImportDefinitionsService; + private rootPathContextService: RootPathContextService; + private generatorReuseManager: GeneratorReuseManager; + private autocompleteCache = AutocompleteLruCache.get(); + public errorsShown: Set = new Set(); + private bracketMatchingService = new BracketMatchingService(); + private debouncer = new AutocompleteDebouncer(); + // private nearbyDefinitionsService = new NearbyDefinitionsService(); constructor( private readonly configHandler: ConfigHandler, @@ -107,14 +95,6 @@ export class CompletionProvider { ); } - private importDefinitionsService: ImportDefinitionsService; - private rootPathContextService: RootPathContextService; - private generatorReuseManager: GeneratorReuseManager; - private autocompleteCache = AutocompleteLruCache.get(); - public errorsShown: Set = new Set(); - private bracketMatchingService = new BracketMatchingService(); - // private nearbyDefinitionsService = new NearbyDefinitionsService(); - private onError(e: any) { console.warn("Error generating autocompletion: ", e); if ( @@ -150,19 +130,7 @@ export class CompletionProvider { if (this._outcomes.has(completionId)) { const outcome = this._outcomes.get(completionId)!; - outcome.accepted = true; - logDevData("autocomplete", outcome); - void Telemetry.capture( - "autocomplete", - { - accepted: outcome.accepted, - modelName: outcome.modelName, - modelProvider: outcome.modelProvider, - time: outcome.time, - cacheHit: outcome.cacheHit, - }, - true, - ); + this.logAcceptedCompletion(completionId, outcome); this._outcomes.delete(completionId); this.bracketMatchingService.handleAcceptedCompletion( @@ -172,6 +140,25 @@ export class CompletionProvider { } } + private logAcceptedCompletion( + completionId: string, + outcome: AutocompleteOutcome, + ) { + outcome.accepted = true; + logDevData("autocomplete", outcome); + void Telemetry.capture( + "autocomplete", + { + accepted: outcome.accepted, + modelName: outcome.modelName, + modelProvider: outcome.modelProvider, + time: outcome.time, + cacheHit: outcome.cacheHit, + }, + true, + ); + } + public cancelRejectionTimeout(completionId: string) { if (this._logRejectionTimeouts.has(completionId)) { clearTimeout(this._logRejectionTimeouts.get(completionId)!); @@ -188,10 +175,6 @@ export class CompletionProvider { token: AbortSignal | undefined, ): Promise { try { - // Debounce - const uuid = uuidv4(); - CompletionProvider.lastUUID = uuid; - const config = await this.configHandler.loadConfig(); const options = { ...DEFAULT_AUTOCOMPLETE_OPTS, @@ -244,21 +227,8 @@ export class CompletionProvider { } // Debounce - if (CompletionProvider.debouncing) { - CompletionProvider.debounceTimeout?.refresh(); - const lastUUID = await new Promise((resolve) => - setTimeout(() => { - resolve(CompletionProvider.lastUUID); - }, options.debounceDelay), - ); - if (uuid !== lastUUID) { - return undefined; - } - } else { - CompletionProvider.debouncing = true; - CompletionProvider.debounceTimeout = setTimeout(async () => { - CompletionProvider.debouncing = false; - }, options.debounceDelay); + if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { + return undefined; } // Get completion @@ -292,15 +262,6 @@ export class CompletionProvider { return undefined; } - /** - * This check is most likely not needed because we do trim the LLM output - * elsewhere in the code. That said, I'm not yet confident enough to - * remove this. - */ - if (options.transform && isOnlyWhitespace(outcome.completion)) { - return undefined; - } - // Do some stuff later so as not to block return. Latency matters const completionToCache = outcome.completion; setTimeout(async () => { diff --git a/core/autocomplete/context/retrieval.ts b/core/autocomplete/context/retrieval.ts deleted file mode 100644 index 45d6f2b64..000000000 --- a/core/autocomplete/context/retrieval.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { BranchAndDir, Chunk } from "../.."; -import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex"; - -export async function fullTextRetrieve( - prefix: string, - suffix: string, - indexTag: BranchAndDir, -): Promise { - const index = new FullTextSearchCodebaseIndex(); - const searchStrings = prefix.split("\n").slice(-3); - const results: Chunk[] = []; - searchStrings.forEach(async (searchString) => { - const chunks = await index.retrieve( - [indexTag], - searchString, - 3, - undefined, - undefined, - ); - results.push(...chunks); - }); - return results; -} diff --git a/core/autocomplete/filtering/filter.ts b/core/autocomplete/filtering/filter.ts deleted file mode 100644 index 5b2b66df0..000000000 --- a/core/autocomplete/filtering/filter.ts +++ /dev/null @@ -1,4 +0,0 @@ -export function isOnlyWhitespace(completion: string): boolean { - const whitespaceRegex = /^[\s]+$/; - return whitespaceRegex.test(completion); -} diff --git a/core/autocomplete/postprocessing/index.ts b/core/autocomplete/postprocessing/index.ts index af0c698e0..001642573 100644 --- a/core/autocomplete/postprocessing/index.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -42,6 +42,10 @@ function isExtremeRepetition(completion: string): boolean { } return false; } +export function isOnlyWhitespace(completion: string): boolean { + const whitespaceRegex = /^[\s]+$/; + return whitespaceRegex.test(completion); +} export function postprocessCompletion({ completion, @@ -55,7 +59,7 @@ export function postprocessCompletion({ suffix: string; }): string | undefined { // Don't return empty - if (completion.trim().length <= 0) { + if (isOnlyWhitespace(completion)) { return undefined; } diff --git a/core/autocomplete/constants/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts similarity index 100% rename from core/autocomplete/constants/AutocompleteTemplate.ts rename to core/autocomplete/templating/AutocompleteTemplate.ts diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts new file mode 100644 index 000000000..725c99753 --- /dev/null +++ b/core/autocomplete/templating/index.ts @@ -0,0 +1,19 @@ +import { getBasename } from "../../util"; +import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; + +export function formatExternalSnippet( + filepath: string, + snippet: string, + language: AutocompleteLanguageInfo, +) { + const comment = language.singleLineComment; + const lines = [ + `${comment} Path: ${getBasename(filepath)}`, + ...snippet + .trim() + .split("\n") + .map((line) => `${comment} ${line}`), + comment, + ]; + return lines.join("\n"); +} From 54b27748e3a81a19632a0530853da31c1e1c7a88 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 21:00:42 -0700 Subject: [PATCH 05/43] move multiline classification --- .../classification/shouldCompleteMultiline.ts | 55 ++++++ core/autocomplete/completionProvider.ts | 184 +++++++----------- 2 files changed, 127 insertions(+), 112 deletions(-) diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts index 9ae0d55fa..8bc5e5de4 100644 --- a/core/autocomplete/classification/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -1,4 +1,6 @@ +import { TabAutocompleteOptions } from "@continuedev/config-types"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { AutocompleteInput } from "../types"; import { AstPath } from "../util/ast"; const BLOCK_TYPES = ["body", "statement_block"]; @@ -31,3 +33,56 @@ export async function shouldCompleteMultiline( return true; } + +function shouldCompleteMultilineBasedOnLanguage( + language: AutocompleteLanguageInfo, + prefix: string, + suffix: string, +) { + let langMultilineDecision = language.useMultiline?.({ prefix, suffix }); + return langMultilineDecision; +} + +function shouldCompleteMultilineBasedOnSelectedCompletion( + selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"], + multilineCompletions: TabAutocompleteOptions["multilineCompletions"], + completeMultiline: boolean, +) { + return ( + !selectedCompletionInfo && // Only ever single-line if using intellisense selected value + multilineCompletions !== "never" && + (multilineCompletions === "always" || completeMultiline) + ); +} + +export function decideMultilineEarly({ + language, + prefix, + suffix, + selectedCompletionInfo, + multilineCompletions, + completeMultiline, +}: { + language: AutocompleteLanguageInfo; + prefix: string; + suffix: string; + selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"]; + multilineCompletions: TabAutocompleteOptions["multilineCompletions"]; + completeMultiline: boolean; +}) { + if (shouldCompleteMultilineBasedOnLanguage(language, prefix, suffix)) { + return true; + } + + if ( + shouldCompleteMultilineBasedOnSelectedCompletion( + selectedCompletionInfo, + multilineCompletions, + completeMultiline, + ) + ) { + return true; + } + + return false; +} diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 4f47579a4..8c01dcb53 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -4,7 +4,7 @@ import path from "path"; import { ConfigHandler } from "../config/ConfigHandler.js"; import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { streamLines } from "../diff/util.js"; -import { IDE, ILLM, ModelProvider, TabAutocompleteOptions } from "../index.js"; +import { IDE, ILLM, TabAutocompleteOptions } from "../index.js"; import { logDevData } from "../util/devdata.js"; import { getBasename, getLastNPathParts } from "../util/index.js"; import { @@ -29,6 +29,7 @@ import Handlebars from "handlebars"; import { getConfigJsonPath } from "../util/paths.js"; import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; +import { decideMultilineEarly } from "./classification/shouldCompleteMultiline.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { stopAtStopTokens } from "./filtering/streamTransforms/charStream.js"; @@ -52,14 +53,6 @@ const ERRORS_TO_IGNORE = [ "unexpected server status", ]; -const LOCAL_PROVIDERS: ModelProvider[] = [ - "ollama", - "lmstudio", - "llama.cpp", - "llamafile", - "text-gen-webui", -]; - export type GetLspDefinitionsFunction = ( filepath: string, contents: string, @@ -130,7 +123,7 @@ export class CompletionProvider { if (this._outcomes.has(completionId)) { const outcome = this._outcomes.get(completionId)!; - this.logAcceptedCompletion(completionId, outcome); + this.logAutocompleteOutcome(outcome); this._outcomes.delete(completionId); this.bracketMatchingService.handleAcceptedCompletion( @@ -140,20 +133,26 @@ export class CompletionProvider { } } - private logAcceptedCompletion( - completionId: string, - outcome: AutocompleteOutcome, - ) { + private logAutocompleteOutcome(outcome: AutocompleteOutcome) { outcome.accepted = true; logDevData("autocomplete", outcome); + const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; void Telemetry.capture( "autocomplete", { - accepted: outcome.accepted, - modelName: outcome.modelName, - modelProvider: outcome.modelProvider, - time: outcome.time, - cacheHit: outcome.cacheHit, + accepted: restOfOutcome.accepted, + cacheHit: restOfOutcome.cacheHit, + completionId: restOfOutcome.completionId, + completionOptions: restOfOutcome.completionOptions, + debounceDelay: restOfOutcome.debounceDelay, + fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0], + maxPromptTokens: restOfOutcome.maxPromptTokens, + modelName: restOfOutcome.modelName, + modelProvider: restOfOutcome.modelProvider, + multilineCompletions: restOfOutcome.multilineCompletions, + time: restOfOutcome.time, + useRecentlyEdited: restOfOutcome.useRecentlyEdited, + useRootPathContext: restOfOutcome.useRootPathContext, }, true, ); @@ -170,16 +169,58 @@ export class CompletionProvider { } } + private async _getAutocompleteOptions() { + const config = await this.configHandler.loadConfig(); + const options = { + ...DEFAULT_AUTOCOMPLETE_OPTS, + ...config.tabAutocompleteOptions, + }; + return options; + } + + private async _isDisabledForFile( + currentFilepath: string, + disableInFiles: string[] | undefined, + ) { + if (disableInFiles) { + // Relative path needed for `ignore` + const workspaceDirs = await this.ide.getWorkspaceDirs(); + let filepath = currentFilepath; + for (const workspaceDir of workspaceDirs) { + const relativePath = path.relative(workspaceDir, filepath); + const relativePathBase = relativePath.split(path.sep).at(0); + const isInWorkspace = + !path.isAbsolute(relativePath) && relativePathBase !== ".."; + if (isInWorkspace) { + filepath = path.relative(workspaceDir, filepath); + break; + } + } + + // Worst case we can check filetype glob patterns + if (filepath === currentFilepath) { + filepath = getBasename(filepath); + } + + // @ts-ignore + const pattern = ignore.default().add(options.disableInFiles); + if (pattern.ignores(filepath)) { + return true; + } + } + } + public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, ): Promise { try { - const config = await this.configHandler.loadConfig(); - const options = { - ...DEFAULT_AUTOCOMPLETE_OPTS, - ...config.tabAutocompleteOptions, - }; + const options = await this._getAutocompleteOptions(); + + // Allow disabling autocomplete from config.json + if (options.disable) { + return undefined; + } // Check whether we're in the continue config.json file if (input.filepath === getConfigJsonPath()) { @@ -187,31 +228,10 @@ export class CompletionProvider { } // Check whether autocomplete is disabled for this file - if (options.disableInFiles) { - // Relative path needed for `ignore` - const workspaceDirs = await this.ide.getWorkspaceDirs(); - let filepath = input.filepath; - for (const workspaceDir of workspaceDirs) { - const relativePath = path.relative(workspaceDir, filepath); - const relativePathBase = relativePath.split(path.sep).at(0); - const isInWorkspace = - !path.isAbsolute(relativePath) && relativePathBase !== ".."; - if (isInWorkspace) { - filepath = path.relative(workspaceDir, filepath); - break; - } - } - - // Worst case we can check filetype glob patterns - if (filepath === input.filepath) { - filepath = getBasename(filepath); - } - - // @ts-ignore - const pattern = ignore.default().add(options.disableInFiles); - if (pattern.ignores(filepath)) { - return undefined; - } + if ( + await this._isDisabledForFile(input.filepath, options.disableInFiles) + ) { + return undefined; } // Create abort signal if not given @@ -221,11 +241,6 @@ export class CompletionProvider { this._abortControllers.set(input.completionId, controller); } - // Allow disabling autocomplete from config.json - if (options.disable) { - return undefined; - } - // Debounce if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { return undefined; @@ -233,7 +248,6 @@ export class CompletionProvider { // Get completion const llm = await this.getLlm(); - if (!llm) { return undefined; } @@ -244,18 +258,11 @@ export class CompletionProvider { return undefined; } - // Set temperature (but don't overrride) + // Set temperature (but don't override) if (llm.completionOptions.temperature === undefined) { llm.completionOptions.temperature = 0.01; } - if ( - !config.tabAutocompleteOptions?.maxPromptTokens && - LOCAL_PROVIDERS.includes(llm.providerName) - ) { - options.maxPromptTokens = 500; - } - const outcome = await this.getTabCompletion(token, options, llm, input); if (!outcome?.completion) { @@ -285,27 +292,7 @@ export class CompletionProvider { const logRejectionTimeout = setTimeout(() => { // Wait 10 seconds, then assume it wasn't accepted outcome.accepted = false; - logDevData("autocomplete", outcome); - const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; - void Telemetry.capture( - "autocomplete", - { - accepted: restOfOutcome.accepted, - cacheHit: restOfOutcome.cacheHit, - completionId: restOfOutcome.completionId, - completionOptions: restOfOutcome.completionOptions, - debounceDelay: restOfOutcome.debounceDelay, - fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0], - maxPromptTokens: restOfOutcome.maxPromptTokens, - modelName: restOfOutcome.modelName, - modelProvider: restOfOutcome.modelProvider, - multilineCompletions: restOfOutcome.multilineCompletions, - time: restOfOutcome.time, - useRecentlyEdited: restOfOutcome.useRecentlyEdited, - useRootPathContext: restOfOutcome.useRootPathContext, - }, - true, - ); + this.logAutocompleteOutcome(outcome); this._logRejectionTimeouts.delete(completionId); }, COUNT_COMPLETION_REJECTED_AFTER); this._outcomes.set(completionId, outcome); @@ -340,33 +327,6 @@ export class CompletionProvider { }; } - private isMultiline({ - language, - prefix, - suffix, - selectedCompletionInfo, - multilineCompletions, - completeMultiline, - }: { - language: AutocompleteLanguageInfo; - prefix: string; - suffix: string; - selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"]; - multilineCompletions: TabAutocompleteOptions["multilineCompletions"]; - completeMultiline: boolean; - }) { - let langMultilineDecision = language.useMultiline?.({ prefix, suffix }); - if (langMultilineDecision) { - return langMultilineDecision; - } else { - return ( - !selectedCompletionInfo && // Only ever single-line if using intellisense selected value - multilineCompletions !== "never" && - (multilineCompletions === "always" || completeMultiline) - ); - } - } - async getTabCompletion( token: AbortSignal, options: TabAutocompleteOptions, @@ -579,7 +539,7 @@ export class CompletionProvider { const multiline = !options.transform || - this.isMultiline({ + decideMultilineEarly({ multilineCompletions: options.multilineCompletions, language: lang, selectedCompletionInfo: input.selectedCompletionInfo, From 04003da444618af2d3ce049eee75deabf697fe0e Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 21:10:29 -0700 Subject: [PATCH 06/43] refactor getLlm --- core/autocomplete/completionProvider.ts | 83 +++++++++++++++---------- 1 file changed, 49 insertions(+), 34 deletions(-) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 8c01dcb53..bc554c626 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -74,7 +74,7 @@ export class CompletionProvider { constructor( private readonly configHandler: ConfigHandler, private readonly ide: IDE, - private readonly getLlm: () => Promise, + private readonly _injectedGetLlm: () => Promise, private readonly _onError: (e: any) => void, private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, ) { @@ -88,6 +88,27 @@ export class CompletionProvider { ); } + private async _getLlm(): Promise { + const llm = await this._injectedGetLlm(); + + if (!llm) { + return undefined; + } + + // Ignore empty API keys for Mistral since we currently write + // a template provider without one during onboarding + if (llm.providerName === "mistral" && llm.apiKey === "") { + return undefined; + } + + // Set temperature (but don't override) + if (llm.completionOptions.temperature === undefined) { + llm.completionOptions.temperature = 0.01; + } + + return llm; + } + private onError(e: any) { console.warn("Error generating autocompletion: ", e); if ( @@ -210,6 +231,28 @@ export class CompletionProvider { } } + private async _shouldSkipCompletionForAnyReason( + input: AutocompleteInput, + options: TabAutocompleteOptions, + ): Promise { + // Allow disabling autocomplete from config.json + if (options.disable) { + return true; + } + + // Check whether we're in the continue config.json file + if (input.filepath === getConfigJsonPath()) { + return true; + } + + // Check whether autocomplete is disabled for this file + if (await this._isDisabledForFile(input.filepath, options.disableInFiles)) { + return true; + } + + return false; + } + public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, @@ -217,20 +260,14 @@ export class CompletionProvider { try { const options = await this._getAutocompleteOptions(); - // Allow disabling autocomplete from config.json - if (options.disable) { + // Debounce + if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { return undefined; } - // Check whether we're in the continue config.json file - if (input.filepath === getConfigJsonPath()) { - return undefined; - } - - // Check whether autocomplete is disabled for this file - if ( - await this._isDisabledForFile(input.filepath, options.disableInFiles) - ) { + // Get completion + const llm = await this._getLlm(); + if (!llm) { return undefined; } @@ -241,28 +278,6 @@ export class CompletionProvider { this._abortControllers.set(input.completionId, controller); } - // Debounce - if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { - return undefined; - } - - // Get completion - const llm = await this.getLlm(); - if (!llm) { - return undefined; - } - - // Ignore empty API keys for Mistral since we currently write - // a template provider without one during onboarding - if (llm.providerName === "mistral" && llm.apiKey === "") { - return undefined; - } - - // Set temperature (but don't override) - if (llm.completionOptions.temperature === undefined) { - llm.completionOptions.temperature = 0.01; - } - const outcome = await this.getTabCompletion(token, options, llm, input); if (!outcome?.completion) { From 8aa825940f0fc78777f7f1f1cbdf2cdc32046218 Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 21:26:28 -0700 Subject: [PATCH 07/43] prefiltering --- core/autocomplete/completionProvider.ts | 101 +++++------------------- core/autocomplete/prefiltering/index.ts | 92 +++++++++++++++++++++ 2 files changed, 110 insertions(+), 83 deletions(-) create mode 100644 core/autocomplete/prefiltering/index.ts diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index bc554c626..a590045f5 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -1,8 +1,4 @@ -import ignore from "ignore"; -import OpenAI from "openai"; -import path from "path"; import { ConfigHandler } from "../config/ConfigHandler.js"; -import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import { streamLines } from "../diff/util.js"; import { IDE, ILLM, TabAutocompleteOptions } from "../index.js"; import { logDevData } from "../util/devdata.js"; @@ -26,7 +22,8 @@ import { postprocessCompletion } from "./postprocessing/index.js"; import { getTemplateForModel } from "./templating/AutocompleteTemplate.js"; // @prettier-ignore import Handlebars from "handlebars"; -import { getConfigJsonPath } from "../util/paths.js"; +import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; +import OpenAI from "../llm/llms/OpenAI.js"; import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { decideMultilineEarly } from "./classification/shouldCompleteMultiline.js"; @@ -41,6 +38,7 @@ import { stopAtSimilarLine, streamWithNewLines, } from "./filtering/streamTransforms/lineStream.js"; +import { shouldPrefilter } from "./prefiltering/index.js"; import { formatExternalSnippet } from "./templating/index.js"; import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; @@ -88,7 +86,7 @@ export class CompletionProvider { ); } - private async _getLlm(): Promise { + private async _prepareLlm(): Promise { const llm = await this._injectedGetLlm(); if (!llm) { @@ -106,6 +104,15 @@ export class CompletionProvider { llm.completionOptions.temperature = 0.01; } + if (llm instanceof OpenAI) { + llm.useLegacyCompletionsEndpoint = true; + } else if ( + llm.providerName === "free-trial" && + llm.model !== TRIAL_FIM_MODEL + ) { + llm.model = TRIAL_FIM_MODEL; + } + return llm; } @@ -199,60 +206,6 @@ export class CompletionProvider { return options; } - private async _isDisabledForFile( - currentFilepath: string, - disableInFiles: string[] | undefined, - ) { - if (disableInFiles) { - // Relative path needed for `ignore` - const workspaceDirs = await this.ide.getWorkspaceDirs(); - let filepath = currentFilepath; - for (const workspaceDir of workspaceDirs) { - const relativePath = path.relative(workspaceDir, filepath); - const relativePathBase = relativePath.split(path.sep).at(0); - const isInWorkspace = - !path.isAbsolute(relativePath) && relativePathBase !== ".."; - if (isInWorkspace) { - filepath = path.relative(workspaceDir, filepath); - break; - } - } - - // Worst case we can check filetype glob patterns - if (filepath === currentFilepath) { - filepath = getBasename(filepath); - } - - // @ts-ignore - const pattern = ignore.default().add(options.disableInFiles); - if (pattern.ignores(filepath)) { - return true; - } - } - } - - private async _shouldSkipCompletionForAnyReason( - input: AutocompleteInput, - options: TabAutocompleteOptions, - ): Promise { - // Allow disabling autocomplete from config.json - if (options.disable) { - return true; - } - - // Check whether we're in the continue config.json file - if (input.filepath === getConfigJsonPath()) { - return true; - } - - // Check whether autocomplete is disabled for this file - if (await this._isDisabledForFile(input.filepath, options.disableInFiles)) { - return true; - } - - return false; - } - public async provideInlineCompletionItems( input: AutocompleteInput, token: AbortSignal | undefined, @@ -260,13 +213,17 @@ export class CompletionProvider { try { const options = await this._getAutocompleteOptions(); + if (await shouldPrefilter(input, options, this.ide)) { + return undefined; + } + // Debounce if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { return undefined; } // Get completion - const llm = await this._getLlm(); + const llm = await this._prepareLlm(); if (!llm) { return undefined; } @@ -366,28 +323,6 @@ export class CompletionProvider { // Filter const lang = languageForFilepath(filepath); - if (options.transform) { - const line = fileLines[pos.line] ?? ""; - for (const endOfLine of lang.endOfLine) { - if (line.endsWith(endOfLine) && pos.character >= line.length) { - return undefined; - } - } - } - - // Model - if (!llm) { - return; - } - if (llm instanceof OpenAI) { - llm.useLegacyCompletionsEndpoint = true; - } else if ( - llm.providerName === "free-trial" && - llm.model !== TRIAL_FIM_MODEL - ) { - llm.model = TRIAL_FIM_MODEL; - } - // Prompt let fullPrefix = getRangeInString(fileContents, { diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts new file mode 100644 index 000000000..1d8d089c9 --- /dev/null +++ b/core/autocomplete/prefiltering/index.ts @@ -0,0 +1,92 @@ +import path from "node:path"; +import { IDE, Position, TabAutocompleteOptions } from "../.."; +import { getBasename } from "../../util"; +import { getConfigJsonPath } from "../../util/paths"; +import { languageForFilepath } from "../constructPrompt"; +import { AutocompleteInput } from "../types"; + +async function isDisabledForFile( + currentFilepath: string, + disableInFiles: string[] | undefined, + ide: IDE, +) { + if (disableInFiles) { + // Relative path needed for `ignore` + const workspaceDirs = await ide.getWorkspaceDirs(); + let filepath = currentFilepath; + for (const workspaceDir of workspaceDirs) { + const relativePath = path.relative(workspaceDir, filepath); + const relativePathBase = relativePath.split(path.sep).at(0); + const isInWorkspace = + !path.isAbsolute(relativePath) && relativePathBase !== ".."; + if (isInWorkspace) { + filepath = path.relative(workspaceDir, filepath); + break; + } + } + + // Worst case we can check filetype glob patterns + if (filepath === currentFilepath) { + filepath = getBasename(filepath); + } + + // @ts-ignore + const pattern = ignore.default().add(options.disableInFiles); + if (pattern.ignores(filepath)) { + return true; + } + } +} + +async function shouldLanguageSpecificPrefilter( + manuallyPassFileContents: string | undefined, + filepath: string, + pos: Position, + ide: IDE, +) { + const lang = languageForFilepath(filepath); + const fileContents = + manuallyPassFileContents ?? (await ide.readFile(filepath)); + const fileLines = fileContents.split("\n"); + const line = fileLines[pos.line] ?? ""; + for (const endOfLine of lang.endOfLine) { + if (line.endsWith(endOfLine) && pos.character >= line.length) { + return true; + } + } +} + +export async function shouldPrefilter( + input: AutocompleteInput, + options: TabAutocompleteOptions, + ide: IDE, +): Promise { + // Allow disabling autocomplete from config.json + if (options.disable) { + return true; + } + + // Check whether we're in the continue config.json file + if (input.filepath === getConfigJsonPath()) { + return true; + } + + // Check whether autocomplete is disabled for this file + if (await isDisabledForFile(input.filepath, options.disableInFiles, ide)) { + return true; + } + + if ( + options.transform && + (await shouldLanguageSpecificPrefilter( + input.manuallyPassFileContents, + input.filepath, + input.pos, + ide, + )) + ) { + return true; + } + + return false; +} From 66da91b0a400166132db1d18917b3c53486e43cf Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 21:55:53 -0700 Subject: [PATCH 08/43] more refactoring --- core/autocomplete/completionProvider.ts | 82 ++++-------------- .../StreamTransformPipeline.ts | 84 +++++++++++++++++++ 2 files changed, 100 insertions(+), 66 deletions(-) create mode 100644 core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index a590045f5..77a5ac920 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -1,5 +1,4 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; -import { streamLines } from "../diff/util.js"; import { IDE, ILLM, TabAutocompleteOptions } from "../index.js"; import { logDevData } from "../util/devdata.js"; import { getBasename, getLastNPathParts } from "../util/index.js"; @@ -29,15 +28,7 @@ import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { decideMultilineEarly } from "./classification/shouldCompleteMultiline.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; -import { stopAtStopTokens } from "./filtering/streamTransforms/charStream.js"; -import { - avoidPathLineAndEmptyComments, - skipPrefixes, - stopAtLines, - stopAtRepeatingLines, - stopAtSimilarLine, - streamWithNewLines, -} from "./filtering/streamTransforms/lineStream.js"; +import { StreamTransformPipeline } from "./filtering/streamTransforms/StreamTransformPipeline.js"; import { shouldPrefilter } from "./prefiltering/index.js"; import { formatExternalSnippet } from "./templating/index.js"; import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; @@ -67,6 +58,7 @@ export class CompletionProvider { public errorsShown: Set = new Set(); private bracketMatchingService = new BracketMatchingService(); private debouncer = new AutocompleteDebouncer(); + private streamTransformPipeline = new StreamTransformPipeline(); // private nearbyDefinitionsService = new NearbyDefinitionsService(); constructor( @@ -344,17 +336,6 @@ export class CompletionProvider { end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER }, }); - // First non-whitespace line below the cursor - let lineBelowCursor = ""; - let i = 1; - while ( - lineBelowCursor.trim() === "" && - pos.line + i <= fileLines.length - 1 - ) { - lineBelowCursor = fileLines[Math.min(pos.line + i, fileLines.length - 1)]; - i++; - } - let extrasSnippets = options.useOtherFiles ? ((await Promise.race([ this.getDefinitionsFromLsp( @@ -476,7 +457,7 @@ export class CompletionProvider { cacheHit = true; completion = cachedCompletion; } else { - const stop = [ + const stopTokens = [ ...(completionOptions?.stop || []), // ...multilineStops, ...commonStops, @@ -505,12 +486,12 @@ export class CompletionProvider { llm.supportsFim() ? llm.streamFim(prefix, suffix, { ...completionOptions, - stop, + stop: stopTokens, }) : llm.streamComplete(prompt, { ...completionOptions, raw: true, - stop, + stop: stopTokens, }), multiline, ); @@ -530,53 +511,22 @@ export class CompletionProvider { yield update; } }; - let charGenerator = generatorWithCancellation(); - if (options.transform) { - // charGenerator = noFirstCharNewline(charGenerator); - // charGenerator = onlyWhitespaceAfterEndOfLine( - // charGenerator, - // lang.endOfLine, - // fullStop, - // ); - charGenerator = stopAtStopTokens(charGenerator, stop); - charGenerator = - this.bracketMatchingService.stopOnUnmatchedClosingBracket( - charGenerator, + const initialGenerator = generatorWithCancellation(); + const finalGenerator = options.transform + ? this.streamTransformPipeline.transform( + initialGenerator, prefix, suffix, filepath, multiline, - ); - } - - let lineGenerator = streamLines(charGenerator); - if (options.transform) { - lineGenerator = stopAtLines(lineGenerator, fullStop); - lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); - lineGenerator = avoidPathLineAndEmptyComments( - lineGenerator, - lang.singleLineComment, - ); - lineGenerator = skipPrefixes(lineGenerator); - - // lineGenerator = noTopLevelKeywordsMidline( - // lineGenerator, - // lang.topLevelKeywords, - // fullStop, - // ); - for (const lineFilter of lang.lineFilters ?? []) { - lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); - } - - lineGenerator = stopAtSimilarLine( - lineGenerator, - lineBelowCursor, - fullStop, - ); - } - - const finalGenerator = streamWithNewLines(lineGenerator); + pos, + fileLines, + stopTokens, + lang, + fullStop, + ) + : initialGenerator; try { for await (const update of finalGenerator) { diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts new file mode 100644 index 000000000..edc4f8c40 --- /dev/null +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -0,0 +1,84 @@ +import { Position } from "../../.."; +import { streamLines } from "../../../diff/util"; +import { AutocompleteLanguageInfo } from "../../constants/AutocompleteLanguageInfo"; +import { BracketMatchingService } from "../BracketMatchingService"; +import { stopAtStopTokens } from "./charStream"; +import { + avoidPathLineAndEmptyComments, + skipPrefixes, + stopAtLines, + stopAtRepeatingLines, + stopAtSimilarLine, + streamWithNewLines, +} from "./lineStream"; + +export class StreamTransformPipeline { + private bracketMatchingService = new BracketMatchingService(); + + async *transform( + generator: AsyncGenerator, + prefix: string, + suffix: string, + filepath: string, + multiline: boolean, + pos: Position, + fileLines: string[], + stopTokens: string[], + lang: AutocompleteLanguageInfo, + fullStop: () => void, + ): AsyncGenerator { + let charGenerator = generator; + + // charGenerator = noFirstCharNewline(charGenerator); + // charGenerator = onlyWhitespaceAfterEndOfLine( + // charGenerator, + // lang.endOfLine, + // fullStop, + // ); + charGenerator = stopAtStopTokens(generator, stopTokens); + charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( + charGenerator, + prefix, + suffix, + filepath, + multiline, + ); + + let lineGenerator = streamLines(charGenerator); + + // First non-whitespace line below the cursor + let lineBelowCursor = ""; + let i = 1; + while ( + lineBelowCursor.trim() === "" && + pos.line + i <= fileLines.length - 1 + ) { + lineBelowCursor = fileLines[Math.min(pos.line + i, fileLines.length - 1)]; + i++; + } + + lineGenerator = stopAtLines(lineGenerator, fullStop); + lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); + lineGenerator = avoidPathLineAndEmptyComments( + lineGenerator, + lang.singleLineComment, + ); + lineGenerator = skipPrefixes(lineGenerator); + + // lineGenerator = noTopLevelKeywordsMidline( + // lineGenerator, + // lang.topLevelKeywords, + // fullStop, + // ); + for (const lineFilter of lang.lineFilters ?? []) { + lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); + } + + lineGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor, fullStop); + + const finalGenerator = streamWithNewLines(lineGenerator); + for await (const update of finalGenerator) { + yield update; + } + } +} From c1df46c0c03020ab544ac6b88ae15218e0cb8e1a Mon Sep 17 00:00:00 2001 From: Nate Date: Wed, 30 Oct 2024 22:14:07 -0700 Subject: [PATCH 09/43] refactor more --- core/autocomplete/completionProvider.ts | 111 ++++-------------------- core/autocomplete/templating/index.ts | 107 ++++++++++++++++++++++- 2 files changed, 122 insertions(+), 96 deletions(-) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 77a5ac920..45bf98cd0 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -1,7 +1,6 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; import { IDE, ILLM, TabAutocompleteOptions } from "../index.js"; import { logDevData } from "../util/devdata.js"; -import { getBasename, getLastNPathParts } from "../util/index.js"; import { COUNT_COMPLETION_REJECTED_AFTER, DEFAULT_AUTOCOMPLETE_OPTS, @@ -18,19 +17,16 @@ import { AutocompleteSnippet } from "./context/ranking/index.js"; import { RootPathContextService } from "./context/RootPathContextService.js"; import { GeneratorReuseManager } from "./generation/GeneratorReuseManager.js"; import { postprocessCompletion } from "./postprocessing/index.js"; -import { getTemplateForModel } from "./templating/AutocompleteTemplate.js"; // @prettier-ignore -import Handlebars from "handlebars"; import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; -import { decideMultilineEarly } from "./classification/shouldCompleteMultiline.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { StreamTransformPipeline } from "./filtering/streamTransforms/StreamTransformPipeline.js"; import { shouldPrefilter } from "./prefiltering/index.js"; -import { formatExternalSnippet } from "./templating/index.js"; +import { renderPrompt } from "./templating/index.js"; import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; const autocompleteCache = AutocompleteLruCache.get(); @@ -381,68 +377,19 @@ export class CompletionProvider { suffix = ""; } - // Template prompt - const { - template, - completionOptions, - compilePrefixSuffix = undefined, - } = options.template - ? { template: options.template, completionOptions: {} } - : getTemplateForModel(llm.model); - - let prompt: string; - const filename = getBasename(filepath); - const reponame = getBasename(workspaceDirs[0] ?? "myproject"); - - // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix - // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint - if (compilePrefixSuffix) { - [prefix, suffix] = compilePrefixSuffix( - prefix, - suffix, - filepath, - reponame, - snippets, - ); - } - - if (typeof template === "string") { - const compiledTemplate = Handlebars.compile(template); - - // Format snippets as comments and prepend to prefix - const formattedSnippets = snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), - ) - .join("\n"); - if (formattedSnippets.length > 0) { - prefix = `${formattedSnippets}\n\n${prefix}`; - } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { - // If it's an empty file, include the file name as a comment - prefix = `${lang.singleLineComment} ${getLastNPathParts( - filepath, - 2, - )}\n${prefix}`; - } - - prompt = compiledTemplate({ - prefix, - suffix, - filename, - reponame, - language: lang.name, - }); - } else { - // Let the template function format snippets - prompt = template( - prefix, - suffix, - filepath, - reponame, - lang.name, - snippets, - ); - } + const [prompt, completionOptions, multiline] = renderPrompt( + options, + prefix, + suffix, + filepath, + lang, + snippets, + llm.model, + workspaceDirs, + options.template, + input.selectedCompletionInfo, + completeMultiline, + ); // Completion let completion = ""; @@ -457,41 +404,15 @@ export class CompletionProvider { cacheHit = true; completion = cachedCompletion; } else { - const stopTokens = [ - ...(completionOptions?.stop || []), - // ...multilineStops, - ...commonStops, - ...(llm.model.toLowerCase().includes("starcoder2") - ? STARCODER2_T_ARTIFACTS - : []), - ...(lang.stopWords ?? []), - // ...lang.topLevelKeywords.map((word) => `\n${word}`), - ]; - - const multiline = - !options.transform || - decideMultilineEarly({ - multilineCompletions: options.multilineCompletions, - language: lang, - selectedCompletionInfo: input.selectedCompletionInfo, - prefix, - suffix, - completeMultiline, - }); - // Try to reuse pending requests if what the user typed matches start of completion const generator = this.generatorReuseManager.getGenerator( prefix, () => llm.supportsFim() - ? llm.streamFim(prefix, suffix, { - ...completionOptions, - stop: stopTokens, - }) + ? llm.streamFim(prefix, suffix, completionOptions) : llm.streamComplete(prompt, { ...completionOptions, raw: true, - stop: stopTokens, }), multiline, ); @@ -522,7 +443,7 @@ export class CompletionProvider { multiline, pos, fileLines, - stopTokens, + completionOptions?.stop || [], lang, fullStop, ) diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 725c99753..e0890ca8b 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,5 +1,10 @@ -import { getBasename } from "../../util"; +import { CompletionOptions, TabAutocompleteOptions } from "../.."; +import { getBasename, getLastNPathParts } from "../../util"; +import { decideMultilineEarly } from "../classification/shouldCompleteMultiline"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { AutocompleteSnippet } from "../context/ranking"; +import { AutocompleteInput } from "../types"; +import { getTemplateForModel } from "./AutocompleteTemplate"; export function formatExternalSnippet( filepath: string, @@ -17,3 +22,103 @@ export function formatExternalSnippet( ]; return lines.join("\n"); } + +export function renderPrompt( + options: TabAutocompleteOptions, + prefix: string, + suffix: string, + filepath: string, + lang: AutocompleteLanguageInfo, + snippets: AutocompleteSnippet[], + model: string, + workspaceDirs: string[], + userDefinedTemplate: string | undefined, + selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"], + completeMultiline: boolean, +): [string, Partial | undefined, boolean] { + // Template prompt + let { + template, + completionOptions, + compilePrefixSuffix = undefined, + } = userDefinedTemplate + ? { template: userDefinedTemplate, completionOptions: {} } + : getTemplateForModel(model); + + let prompt: string; + const filename = getBasename(filepath); + const reponame = getBasename(workspaceDirs[0] ?? "myproject"); + + // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix + // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint + if (compilePrefixSuffix) { + [prefix, suffix] = compilePrefixSuffix( + prefix, + suffix, + filepath, + reponame, + snippets, + ); + } + + if (typeof template === "string") { + const compiledTemplate = Handlebars.compile(template); + + // Format snippets as comments and prepend to prefix + const formattedSnippets = snippets + .map((snippet) => + formatExternalSnippet(snippet.filepath, snippet.contents, lang), + ) + .join("\n"); + if (formattedSnippets.length > 0) { + prefix = `${formattedSnippets}\n\n${prefix}`; + } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { + // If it's an empty file, include the file name as a comment + prefix = `${lang.singleLineComment} ${getLastNPathParts( + filepath, + 2, + )}\n${prefix}`; + } + + prompt = compiledTemplate({ + prefix, + suffix, + filename, + reponame, + language: lang.name, + }); + } else { + // Let the template function format snippets + prompt = template(prefix, suffix, filepath, reponame, lang.name, snippets); + } + + // Stop tokens + const stopTokens = [ + ...(completionOptions?.stop || []), + // ...multilineStops, + ...commonStops, + ...(model.toLowerCase().includes("starcoder2") + ? STARCODER2_T_ARTIFACTS + : []), + ...(lang.stopWords ?? []), + // ...lang.topLevelKeywords.map((word) => `\n${word}`), + ]; + + const multiline = + !options.transform || + decideMultilineEarly({ + multilineCompletions: options.multilineCompletions, + language: lang, + selectedCompletionInfo: selectedCompletionInfo, + prefix, + suffix, + completeMultiline, + }); + + completionOptions = { + ...completionOptions, + stop: stopTokens, + }; + + return [prompt, completionOptions, multiline]; +} From 34657c80e2c209195a3443033189670b1aab774c Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 12:36:49 -0700 Subject: [PATCH 10/43] allow completion undefined --- core/autocomplete/completionProvider.ts | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/completionProvider.ts index 45bf98cd0..f11ce14e0 100644 --- a/core/autocomplete/completionProvider.ts +++ b/core/autocomplete/completionProvider.ts @@ -392,7 +392,7 @@ export class CompletionProvider { ); // Completion - let completion = ""; + let completion: string | undefined = ""; const cache = await autocompleteCache; const cachedCompletion = options.useCache @@ -473,13 +473,15 @@ export class CompletionProvider { }) : completion; - if (!processedCompletion) { - return undefined; - } completion = processedCompletion; } const time = Date.now() - startTime; + + if (!completion) { + return undefined; + } + return { time, completion, From a42d32d168d6bef11ef3384c260061065b6c1ead Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 12:38:58 -0700 Subject: [PATCH 11/43] fix tsc errs --- core/autocomplete/test/util.ts | 3 ++- extensions/vscode/continue_rc_schema.json | 2 +- extensions/vscode/src/autocomplete/completionProvider.ts | 6 +++--- extensions/vscode/src/autocomplete/lsp.ts | 6 +++--- extensions/vscode/src/autocomplete/recentlyEdited.ts | 2 +- 5 files changed, 10 insertions(+), 9 deletions(-) diff --git a/core/autocomplete/test/util.ts b/core/autocomplete/test/util.ts index 60e7b3f93..4b008143f 100644 --- a/core/autocomplete/test/util.ts +++ b/core/autocomplete/test/util.ts @@ -2,7 +2,8 @@ import fs from "node:fs"; import path from "node:path"; import Mock from "../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../test/util/fixtures"; -import { AutocompleteInput, CompletionProvider } from "../completionProvider"; +import { CompletionProvider } from "../completionProvider"; +import { AutocompleteInput } from "../types"; const FIM_DELIMITER = "<|fim|>"; diff --git a/extensions/vscode/continue_rc_schema.json b/extensions/vscode/continue_rc_schema.json index 1c1610446..6c664ecb0 100644 --- a/extensions/vscode/continue_rc_schema.json +++ b/extensions/vscode/continue_rc_schema.json @@ -3155,7 +3155,7 @@ "transform": { "type": "boolean", "description": "Whether LLM output should be transformed to correct common model pitfalls." - }, + }, "template": { "type": "string", "description": "An optional template string to be used for autocomplete. It will be rendered with the Mustache templating language, and is passed the 'prefix' and 'suffix' variables." diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index 821f215f1..d9244ebfc 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -1,9 +1,9 @@ import type { IDE } from "core"; +import { CompletionProvider } from "core/autocomplete/completionProvider"; import { - AutocompleteOutcome, - CompletionProvider, type AutocompleteInput, -} from "core/autocomplete/completionProvider"; + type AutocompleteOutcome, +} from "core/autocomplete/types"; import { ConfigHandler } from "core/config/ConfigHandler"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index f24b23bf3..c3382dd99 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -1,8 +1,8 @@ import type { IDE, Range, RangeInFile } from "core"; -import { getAst, getTreePathAtCursor } from "core/autocomplete/ast"; import { GetLspDefinitionsFunction } from "core/autocomplete/completionProvider"; -import { AutocompleteLanguageInfo } from "core/autocomplete/languages"; -import { AutocompleteSnippet } from "core/autocomplete/ranking"; +import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo"; +import { AutocompleteSnippet } from "core/autocomplete/context/ranking"; +import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast"; import { RangeInFileWithContents } from "core/commands/util"; import { FUNCTION_BLOCK_NODE_TYPES, diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index 3c8b4e95f..c32739b1c 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -1,4 +1,4 @@ -import { getSymbolsForSnippet } from "core/autocomplete/ranking"; +import { getSymbolsForSnippet } from "core/autocomplete/context/ranking"; import { RecentlyEditedRange } from "core/autocomplete/recentlyEdited"; import { RangeInFileWithContents } from "core/commands/util"; import * as vscode from "vscode"; From e96bd89ebc614350695c7e48073519e5006c2711 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 12:48:40 -0700 Subject: [PATCH 12/43] refactor stop words --- core/autocomplete/constants/stopWords.ts | 11 ------- core/autocomplete/templating/getStopTokens.ts | 33 +++++++++++++++++++ core/autocomplete/templating/index.ts | 15 ++------- 3 files changed, 36 insertions(+), 23 deletions(-) delete mode 100644 core/autocomplete/constants/stopWords.ts create mode 100644 core/autocomplete/templating/getStopTokens.ts diff --git a/core/autocomplete/constants/stopWords.ts b/core/autocomplete/constants/stopWords.ts deleted file mode 100644 index 94d29cf40..000000000 --- a/core/autocomplete/constants/stopWords.ts +++ /dev/null @@ -1,11 +0,0 @@ -const DOUBLE_NEWLINE = "\n\n"; -const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n"; -// TODO: Do we want to stop completions when reaching a `/src/` string? -const SRC_DIRECTORY = "/src/"; -// Starcoder2 tends to output artifacts starting with the letter "t" -const STARCODER2_T_ARTIFACTS = ["t.", "\nt", ""]; -const PYTHON_ENCODING = "#- coding: utf-8"; -const CODE_BLOCK_END = "```"; - -const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE]; -const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END]; diff --git a/core/autocomplete/templating/getStopTokens.ts b/core/autocomplete/templating/getStopTokens.ts new file mode 100644 index 000000000..fffb5351b --- /dev/null +++ b/core/autocomplete/templating/getStopTokens.ts @@ -0,0 +1,33 @@ +import { CompletionOptions } from "../.."; +import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; + +const DOUBLE_NEWLINE = "\n\n"; +const WINDOWS_DOUBLE_NEWLINE = "\r\n\r\n"; +// TODO: Do we want to stop completions when reaching a `/src/` string? +const SRC_DIRECTORY = "/src/"; +// Starcoder2 tends to output artifacts starting with the letter "t" +const STARCODER2_T_ARTIFACTS = ["t.", "\nt", ""]; +const PYTHON_ENCODING = "#- coding: utf-8"; +const CODE_BLOCK_END = "```"; + +const multilineStops: string[] = [DOUBLE_NEWLINE, WINDOWS_DOUBLE_NEWLINE]; +const commonStops = [SRC_DIRECTORY, PYTHON_ENCODING, CODE_BLOCK_END]; + +export function getStopTokens( + completionOptions: Partial | undefined, + lang: AutocompleteLanguageInfo, + model: string, +): string[] { + const stopTokens = [ + ...(completionOptions?.stop || []), + // ...multilineStops, + ...commonStops, + ...(model.toLowerCase().includes("starcoder2") + ? STARCODER2_T_ARTIFACTS + : []), + ...(lang.stopWords ?? []), + // ...lang.topLevelKeywords.map((word) => `\n${word}`), + ]; + + return stopTokens; +} diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index e0890ca8b..7d81589a0 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -5,6 +5,7 @@ import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo" import { AutocompleteSnippet } from "../context/ranking"; import { AutocompleteInput } from "../types"; import { getTemplateForModel } from "./AutocompleteTemplate"; +import { getStopTokens } from "./getStopTokens"; export function formatExternalSnippet( filepath: string, @@ -92,18 +93,6 @@ export function renderPrompt( prompt = template(prefix, suffix, filepath, reponame, lang.name, snippets); } - // Stop tokens - const stopTokens = [ - ...(completionOptions?.stop || []), - // ...multilineStops, - ...commonStops, - ...(model.toLowerCase().includes("starcoder2") - ? STARCODER2_T_ARTIFACTS - : []), - ...(lang.stopWords ?? []), - // ...lang.topLevelKeywords.map((word) => `\n${word}`), - ]; - const multiline = !options.transform || decideMultilineEarly({ @@ -115,6 +104,8 @@ export function renderPrompt( completeMultiline, }); + const stopTokens = getStopTokens(completionOptions, lang, model); + completionOptions = { ...completionOptions, stop: stopTokens, From ebae6597382bd8676ff65588f56d53953deeccd1 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 12:53:15 -0700 Subject: [PATCH 13/43] rename completionProvider --- ...etionProvider.ts => CompletionProvider.ts} | 0 core/autocomplete/templating/index.ts | 68 ++++++++++++------- 2 files changed, 43 insertions(+), 25 deletions(-) rename core/autocomplete/{completionProvider.ts => CompletionProvider.ts} (100%) diff --git a/core/autocomplete/completionProvider.ts b/core/autocomplete/CompletionProvider.ts similarity index 100% rename from core/autocomplete/completionProvider.ts rename to core/autocomplete/CompletionProvider.ts diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 7d81589a0..46ac9432d 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -23,7 +23,43 @@ export function formatExternalSnippet( ]; return lines.join("\n"); } +function renderStringTemplate( + template: string, + prefix: string, + suffix: string, + snippets: AutocompleteSnippet[], + lang: AutocompleteLanguageInfo, + filepath: string, + reponame: string, +) { + const filename = getBasename(filepath); + const compiledTemplate = Handlebars.compile(template); + // Format snippets as comments and prepend to prefix + const formattedSnippets = snippets + .map((snippet) => + formatExternalSnippet(snippet.filepath, snippet.contents, lang), + ) + .join("\n"); + if (formattedSnippets.length > 0) { + prefix = `${formattedSnippets}\n\n${prefix}`; + } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { + // If it's an empty file, include the file name as a comment + prefix = `${lang.singleLineComment} ${getLastNPathParts( + filepath, + 2, + )}\n${prefix}`; + } + + const prompt = compiledTemplate({ + prefix, + suffix, + filename, + reponame, + language: lang.name, + }); + return prompt; +} export function renderPrompt( options: TabAutocompleteOptions, prefix: string, @@ -37,7 +73,6 @@ export function renderPrompt( selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"], completeMultiline: boolean, ): [string, Partial | undefined, boolean] { - // Template prompt let { template, completionOptions, @@ -47,7 +82,6 @@ export function renderPrompt( : getTemplateForModel(model); let prompt: string; - const filename = getBasename(filepath); const reponame = getBasename(workspaceDirs[0] ?? "myproject"); // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix @@ -62,34 +96,18 @@ export function renderPrompt( ); } + // Templates can be passed as a Handlebars template string or a function if (typeof template === "string") { - const compiledTemplate = Handlebars.compile(template); - - // Format snippets as comments and prepend to prefix - const formattedSnippets = snippets - .map((snippet) => - formatExternalSnippet(snippet.filepath, snippet.contents, lang), - ) - .join("\n"); - if (formattedSnippets.length > 0) { - prefix = `${formattedSnippets}\n\n${prefix}`; - } else if (prefix.trim().length === 0 && suffix.trim().length === 0) { - // If it's an empty file, include the file name as a comment - prefix = `${lang.singleLineComment} ${getLastNPathParts( - filepath, - 2, - )}\n${prefix}`; - } - - prompt = compiledTemplate({ + prompt = renderStringTemplate( + template, prefix, suffix, - filename, + snippets, + lang, + filepath, reponame, - language: lang.name, - }); + ); } else { - // Let the template function format snippets prompt = template(prefix, suffix, filepath, reponame, lang.name, snippets); } From 9a92ab4933edf97135016ced232e2c05a599646f Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 12:55:22 -0700 Subject: [PATCH 14/43] fix casing --- core/autocomplete/filtering/test/util.ts | 2 +- core/autocomplete/test/util.ts | 2 +- core/core.ts | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index 37890e1e8..f8564e258 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -2,7 +2,7 @@ import fs from "node:fs"; import path from "node:path"; import Mock from "../../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../../test/util/fixtures"; -import { CompletionProvider } from "../../completionProvider"; +import { CompletionProvider } from "../../CompletionProvider"; import { AutocompleteInput } from "../../types"; const FIM_DELIMITER = "<|fim|>"; diff --git a/core/autocomplete/test/util.ts b/core/autocomplete/test/util.ts index 4b008143f..85dbc60b3 100644 --- a/core/autocomplete/test/util.ts +++ b/core/autocomplete/test/util.ts @@ -2,7 +2,7 @@ import fs from "node:fs"; import path from "node:path"; import Mock from "../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../test/util/fixtures"; -import { CompletionProvider } from "../completionProvider"; +import { CompletionProvider } from "../CompletionProvider"; import { AutocompleteInput } from "../types"; const FIM_DELIMITER = "<|fim|>"; diff --git a/core/core.ts b/core/core.ts index 8ce7c7a5d..d7bd1846f 100644 --- a/core/core.ts +++ b/core/core.ts @@ -1,6 +1,6 @@ import { v4 as uuidv4 } from "uuid"; import type { ContextItemId, IDE, IndexingProgressUpdate } from "."; -import { CompletionProvider } from "./autocomplete/completionProvider"; +import { CompletionProvider } from "./autocomplete/CompletionProvider"; import { ConfigHandler } from "./config/ConfigHandler"; import { setupBestConfig, From 70eeddcd1744ef5fd1eec85d9771efabaeb53b80 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 13:50:29 -0700 Subject: [PATCH 15/43] HelperVars --- core/autocomplete/CompletionProvider.ts | 154 +++++++----------- core/autocomplete/HelperVars.ts | 61 +++++++ core/autocomplete/constructPrompt.ts | 78 +++++---- core/autocomplete/prefiltering/index.ts | 42 ++--- .../templating/constructPrefixSuffix.ts | 43 +++++ core/autocomplete/templating/index.ts | 46 +++--- 6 files changed, 248 insertions(+), 176 deletions(-) create mode 100644 core/autocomplete/HelperVars.ts create mode 100644 core/autocomplete/templating/constructPrefixSuffix.ts diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index f11ce14e0..5ec075c6d 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -1,18 +1,14 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; -import { IDE, ILLM, TabAutocompleteOptions } from "../index.js"; +import { IDE, ILLM } from "../index.js"; import { logDevData } from "../util/devdata.js"; import { COUNT_COMPLETION_REJECTED_AFTER, DEFAULT_AUTOCOMPLETE_OPTS, } from "../util/parameters.js"; import { Telemetry } from "../util/posthog.js"; -import { getRangeInString } from "../util/ranges.js"; import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; -import { - constructAutocompletePrompt, - languageForFilepath, -} from "./constructPrompt.js"; +import { constructAutocompletePrompt } from "./constructPrompt.js"; import { AutocompleteSnippet } from "./context/ranking/index.js"; import { RootPathContextService } from "./context/RootPathContextService.js"; import { GeneratorReuseManager } from "./generation/GeneratorReuseManager.js"; @@ -25,7 +21,9 @@ import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { StreamTransformPipeline } from "./filtering/streamTransforms/StreamTransformPipeline.js"; +import { HelperVars } from "./HelperVars.js"; import { shouldPrefilter } from "./prefiltering/index.js"; +import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix.js"; import { renderPrompt } from "./templating/index.js"; import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; @@ -199,9 +197,15 @@ export class CompletionProvider { token: AbortSignal | undefined, ): Promise { try { - const options = await this._getAutocompleteOptions(); + const llm = await this._prepareLlm(); + if (!llm) { + return undefined; + } - if (await shouldPrefilter(input, options, this.ide)) { + const options = await this._getAutocompleteOptions(); + const helper = new HelperVars(input, options, llm.model, this.ide); + + if (await shouldPrefilter(helper, this.ide)) { return undefined; } @@ -211,10 +215,6 @@ export class CompletionProvider { } // Get completion - const llm = await this._prepareLlm(); - if (!llm) { - return undefined; - } // Create abort signal if not given if (!token) { @@ -223,7 +223,7 @@ export class CompletionProvider { this._abortControllers.set(input.completionId, controller); } - const outcome = await this.getTabCompletion(token, options, llm, input); + const outcome = await this.getTabCompletion(token, llm, helper); if (!outcome?.completion) { return undefined; @@ -287,59 +287,19 @@ export class CompletionProvider { }; } - async getTabCompletion( - token: AbortSignal, - options: TabAutocompleteOptions, - llm: ILLM, - input: AutocompleteInput, - ): Promise { - const startTime = Date.now(); - - const { - filepath, - pos, - recentlyEditedFiles, - recentlyEditedRanges, - clipboardText, - manuallyPassFileContents, - manuallyPassPrefix, - } = input; - const fileContents = - manuallyPassFileContents ?? (await this.ide.readFile(filepath)); - const fileLines = fileContents.split("\n"); - - // Filter - const lang = languageForFilepath(filepath); - - // Prompt - let fullPrefix = - getRangeInString(fileContents, { - start: { line: 0, character: 0 }, - end: input.selectedCompletionInfo?.range.start ?? pos, - }) + (input.selectedCompletionInfo?.text ?? ""); - - if (input.injectDetails) { - const lines = fullPrefix.split("\n"); - fullPrefix = `${lines.slice(0, -1).join("\n")}\n${ - lang.singleLineComment - } ${input.injectDetails - .split("\n") - .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; - } - - const fullSuffix = getRangeInString(fileContents, { - start: pos, - end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER }, - }); - - let extrasSnippets = options.useOtherFiles + private async _getExtraSnippets( + helper: HelperVars, + fullPrefix: string, + fullSuffix: string, + ): Promise { + let extraSnippets = helper.options.useOtherFiles ? ((await Promise.race([ this.getDefinitionsFromLsp( - filepath, + helper.input.filepath, fullPrefix + fullSuffix, fullPrefix.length, this.ide, - lang, + helper.lang, ), new Promise((resolve) => { setTimeout(() => resolve([]), 100); @@ -348,54 +308,64 @@ export class CompletionProvider { : []; const workspaceDirs = await this.ide.getWorkspaceDirs(); - if (options.onlyMyCode) { - extrasSnippets = extrasSnippets.filter((snippet) => { + if (helper.options.onlyMyCode) { + extraSnippets = extraSnippets.filter((snippet) => { return workspaceDirs.some((dir) => snippet.filepath.startsWith(dir)); }); } + return extraSnippets; + } + + async getTabCompletion( + token: AbortSignal, + llm: ILLM, + helper: HelperVars, + ): Promise { + const startTime = Date.now(); + + // Construct full prefix/suffix (a few edge cases handled in here) + const { prefix: fullPrefix, suffix: fullSuffix } = + await constructInitialPrefixSuffix(helper.input, this.ide); + + // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, + // or they might separately track recently edited ranges) + const extraSnippets = await this._getExtraSnippets( + helper, + fullPrefix, + fullSuffix, + ); + let { prefix, suffix, completeMultiline, snippets } = await constructAutocompletePrompt( - filepath, - pos.line, fullPrefix, fullSuffix, - clipboardText, - lang, - options, - recentlyEditedRanges, - recentlyEditedFiles, - llm.model, - extrasSnippets, + helper, + extraSnippets, this.importDefinitionsService, this.rootPathContextService, ); // If prefix is manually passed - if (manuallyPassPrefix) { - prefix = manuallyPassPrefix; + if (helper.input.manuallyPassPrefix) { + prefix = helper.input.manuallyPassPrefix; suffix = ""; } const [prompt, completionOptions, multiline] = renderPrompt( - options, prefix, suffix, - filepath, - lang, snippets, - llm.model, - workspaceDirs, - options.template, - input.selectedCompletionInfo, + await this.ide.getWorkspaceDirs(), completeMultiline, + helper, ); // Completion let completion: string | undefined = ""; const cache = await autocompleteCache; - const cachedCompletion = options.useCache + const cachedCompletion = helper.options.useCache ? await cache.get(prefix) : undefined; let cacheHit = false; @@ -434,17 +404,17 @@ export class CompletionProvider { }; const initialGenerator = generatorWithCancellation(); - const finalGenerator = options.transform + const finalGenerator = helper.options.transform ? this.streamTransformPipeline.transform( initialGenerator, prefix, suffix, - filepath, + helper.filepath, multiline, - pos, - fileLines, + helper.pos, + helper.fileLines, completionOptions?.stop || [], - lang, + helper.lang, fullStop, ) : initialGenerator; @@ -464,7 +434,7 @@ export class CompletionProvider { return undefined; } - const processedCompletion = options.transform + const processedCompletion = helper.options.transform ? postprocessCompletion({ completion, prefix, @@ -492,11 +462,11 @@ export class CompletionProvider { modelName: llm.model, completionOptions, cacheHit, - filepath: input.filepath, - completionId: input.completionId, - gitRepo: await this.ide.getRepoName(input.filepath), + filepath: helper.filepath, + completionId: helper.input.completionId, + gitRepo: await this.ide.getRepoName(helper.filepath), uniqueId: await this.ide.getUniqueId(), - ...options, + ...helper.options, }; } } diff --git a/core/autocomplete/HelperVars.ts b/core/autocomplete/HelperVars.ts new file mode 100644 index 000000000..124389509 --- /dev/null +++ b/core/autocomplete/HelperVars.ts @@ -0,0 +1,61 @@ +import { IDE, TabAutocompleteOptions } from ".."; +import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo"; +import { languageForFilepath } from "./constructPrompt"; +import { AutocompleteInput } from "./types"; + +/** + * A collection of variables that are often accessed throughout the autocomplete pipeline + * It's noisy to re-calculate all the time or inject them into each function + */ +export class HelperVars { + lang: AutocompleteLanguageInfo; + private _fileContents: string | undefined; + private _fileLines: string[] | undefined; + + constructor( + public readonly input: AutocompleteInput, + public readonly options: TabAutocompleteOptions, + public readonly modelName: string, + private readonly ide: IDE, + ) { + this.lang = languageForFilepath(input.filepath); + } + + async init() { + // Don't do anything if already initialized + if (this._fileContents !== undefined) return; + + this._fileContents = + this.input.manuallyPassFileContents ?? + (await this.ide.readFile(this.filepath)); + + this._fileLines = this._fileContents.split("\n"); + } + + // Fast access + get filepath() { + return this.input.filepath; + } + get pos() { + return this.input.pos; + } + + // Getters for lazy access + get fileContents(): string { + if (this._fileContents === undefined) { + throw new Error( + "HelperVars must be initialized before accessing fileContents", + ); + } + return this._fileContents; + } + + get fileLines(): string[] { + if (this._fileLines === undefined) { + throw new Error( + "HelperVars must be initialized before accessing fileLines", + ); + } + return this._fileLines; + } +} diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 889db0d76..cbef4949b 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,6 +1,3 @@ -import { RangeInFileWithContents } from "../commands/util.js"; -import { TabAutocompleteOptions } from "../index.js"; - import { countTokens, pruneLinesFromBottom, @@ -21,7 +18,8 @@ import { type AutocompleteSnippet, } from "./context/ranking/index.js"; import { RootPathContextService } from "./context/RootPathContextService.js"; -import { RecentlyEditedRange, findMatchingRange } from "./recentlyEdited.js"; +import { HelperVars } from "./HelperVars.js"; +import { findMatchingRange } from "./recentlyEdited.js"; import { AstPath, getAst, getTreePathAtCursor } from "./util/ast.js"; export function languageForFilepath( @@ -31,16 +29,9 @@ export function languageForFilepath( } export async function constructAutocompletePrompt( - filepath: string, - cursorLine: number, fullPrefix: string, fullSuffix: string, - clipboardText: string, - language: AutocompleteLanguageInfo, - options: TabAutocompleteOptions, - recentlyEditedRanges: RecentlyEditedRange[], - recentlyEditedFiles: RangeInFileWithContents[], - modelName: string, + helper: HelperVars, extraSnippets: AutocompleteSnippet[], importDefinitionsService: ImportDefinitionsService, rootPathContextService: RootPathContextService, @@ -52,20 +43,29 @@ export async function constructAutocompletePrompt( snippets: AutocompleteSnippet[]; }> { // Construct basic prefix - const maxPrefixTokens = options.maxPromptTokens * options.prefixPercentage; - const prefix = pruneLinesFromTop(fullPrefix, maxPrefixTokens, modelName); + const maxPrefixTokens = + helper.options.maxPromptTokens * helper.options.prefixPercentage; + const prefix = pruneLinesFromTop( + fullPrefix, + maxPrefixTokens, + helper.modelName, + ); // Construct suffix const maxSuffixTokens = Math.min( - options.maxPromptTokens - countTokens(prefix, modelName), - options.maxSuffixPercentage * options.maxPromptTokens, + helper.options.maxPromptTokens - countTokens(prefix, helper.modelName), + helper.options.maxSuffixPercentage * helper.options.maxPromptTokens, + ); + const suffix = pruneLinesFromBottom( + fullSuffix, + maxSuffixTokens, + helper.modelName, ); - const suffix = pruneLinesFromBottom(fullSuffix, maxSuffixTokens, modelName); // Calculate AST Path let treePath: AstPath | undefined; try { - const ast = await getAst(filepath, fullPrefix + fullSuffix); + const ast = await getAst(helper.filepath, fullPrefix + fullSuffix); if (ast) { treePath = await getTreePathAtCursor(ast, fullPrefix.length); } @@ -76,15 +76,17 @@ export async function constructAutocompletePrompt( // Find external snippets let snippets: AutocompleteSnippet[] = []; - if (options.useOtherFiles) { + if (helper.options.useOtherFiles) { snippets.push(...extraSnippets); const windowAroundCursor = fullPrefix.slice( - -options.slidingWindowSize * options.slidingWindowPrefixPercentage, + -helper.options.slidingWindowSize * + helper.options.slidingWindowPrefixPercentage, ) + fullSuffix.slice( - options.slidingWindowSize * (1 - options.slidingWindowPrefixPercentage), + helper.options.slidingWindowSize * + (1 - helper.options.slidingWindowPrefixPercentage), ); // This was much too slow, and not super useful @@ -103,11 +105,14 @@ export async function constructAutocompletePrompt( // })), // ); - if (options.useRecentlyEdited) { + if (helper.options.useRecentlyEdited) { const currentLinePrefix = prefix.trim().split("\n").slice(-1)[0]; - if (currentLinePrefix?.length > options.recentLinePrefixMatchMinLength) { + if ( + currentLinePrefix?.length > + helper.options.recentLinePrefixMatchMinLength + ) { const matchingRange = findMatchingRange( - recentlyEditedRanges, + helper.input.recentlyEditedRanges, currentLinePrefix, ); if (matchingRange) { @@ -121,9 +126,9 @@ export async function constructAutocompletePrompt( } // Use imports - if (options.useImports) { + if (helper.options.useImports) { const importSnippets = []; - const fileInfo = importDefinitionsService.get(filepath); + const fileInfo = importDefinitionsService.get(helper.filepath); if (fileInfo) { const { imports } = fileInfo; // Look for imports of any symbols around the current range @@ -132,7 +137,7 @@ export async function constructAutocompletePrompt( fullSuffix.split("\n").slice(0, 3).join("\n"); const symbols = Array.from( getSymbolsForSnippet(textAroundCursor), - ).filter((symbol) => !language.topLevelKeywords.includes(symbol)); + ).filter((symbol) => !helper.lang.topLevelKeywords.includes(symbol)); for (const symbol of symbols) { const rifs = imports[symbol]; if (Array.isArray(rifs)) { @@ -143,9 +148,9 @@ export async function constructAutocompletePrompt( snippets.push(...importSnippets); } - if (options.useRootPathContext && treePath) { + if (helper.options.useRootPathContext && treePath) { const ctx = await rootPathContextService.getContextForPath( - filepath, + helper.filepath, treePath, ); snippets.push(...ctx); @@ -165,7 +170,7 @@ export async function constructAutocompletePrompt( // Fill maxSnippetTokens with snippets const maxSnippetTokens = - options.maxPromptTokens * options.maxSnippetPercentage; + helper.options.maxPromptTokens * helper.options.maxSnippetPercentage; // Remove prefix range from snippets const prefixLines = prefix.split("\n").length; @@ -173,28 +178,29 @@ export async function constructAutocompletePrompt( const buffer = 8; const prefixSuffixRangeWithBuffer = { start: { - line: cursorLine - prefixLines - buffer, + line: helper.pos.line - prefixLines - buffer, character: 0, }, end: { - line: cursorLine + suffixLines + buffer, + line: helper.pos.line + suffixLines + buffer, character: 0, }, }; let finalSnippets = removeRangeFromSnippets( scoredSnippets, - filepath.split("://").slice(-1)[0], + helper.filepath.split("://").slice(-1)[0], prefixSuffixRangeWithBuffer, ); // Filter snippets for those with best scores (must be above threshold) finalSnippets = finalSnippets.filter( - (snippet) => snippet.score >= options.recentlyEditedSimilarityThreshold, + (snippet) => + snippet.score >= helper.options.recentlyEditedSimilarityThreshold, ); finalSnippets = fillPromptWithSnippets( scoredSnippets, maxSnippetTokens, - modelName, + helper.modelName, ); snippets = finalSnippets; @@ -208,7 +214,7 @@ export async function constructAutocompletePrompt( treePath, fullPrefix, fullSuffix, - language, + helper.lang, ), snippets, }; diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts index 1d8d089c9..45b521511 100644 --- a/core/autocomplete/prefiltering/index.ts +++ b/core/autocomplete/prefiltering/index.ts @@ -1,9 +1,8 @@ import path from "node:path"; -import { IDE, Position, TabAutocompleteOptions } from "../.."; +import { IDE } from "../.."; import { getBasename } from "../../util"; import { getConfigJsonPath } from "../../util/paths"; -import { languageForFilepath } from "../constructPrompt"; -import { AutocompleteInput } from "../types"; +import { HelperVars } from "../HelperVars"; async function isDisabledForFile( currentFilepath: string, @@ -38,52 +37,39 @@ async function isDisabledForFile( } } -async function shouldLanguageSpecificPrefilter( - manuallyPassFileContents: string | undefined, - filepath: string, - pos: Position, - ide: IDE, -) { - const lang = languageForFilepath(filepath); - const fileContents = - manuallyPassFileContents ?? (await ide.readFile(filepath)); - const fileLines = fileContents.split("\n"); - const line = fileLines[pos.line] ?? ""; - for (const endOfLine of lang.endOfLine) { - if (line.endsWith(endOfLine) && pos.character >= line.length) { +async function shouldLanguageSpecificPrefilter(helper: HelperVars) { + const line = helper.fileLines[helper.pos.line] ?? ""; + for (const endOfLine of helper.lang.endOfLine) { + if (line.endsWith(endOfLine) && helper.pos.character >= line.length) { return true; } } } export async function shouldPrefilter( - input: AutocompleteInput, - options: TabAutocompleteOptions, + helper: HelperVars, ide: IDE, ): Promise { // Allow disabling autocomplete from config.json - if (options.disable) { + if (helper.options.disable) { return true; } // Check whether we're in the continue config.json file - if (input.filepath === getConfigJsonPath()) { + if (helper.filepath === getConfigJsonPath()) { return true; } // Check whether autocomplete is disabled for this file - if (await isDisabledForFile(input.filepath, options.disableInFiles, ide)) { + if ( + await isDisabledForFile(helper.filepath, helper.options.disableInFiles, ide) + ) { return true; } if ( - options.transform && - (await shouldLanguageSpecificPrefilter( - input.manuallyPassFileContents, - input.filepath, - input.pos, - ide, - )) + helper.options.transform && + (await shouldLanguageSpecificPrefilter(helper)) ) { return true; } diff --git a/core/autocomplete/templating/constructPrefixSuffix.ts b/core/autocomplete/templating/constructPrefixSuffix.ts new file mode 100644 index 000000000..cead471c3 --- /dev/null +++ b/core/autocomplete/templating/constructPrefixSuffix.ts @@ -0,0 +1,43 @@ +import { IDE } from "../.."; +import { getRangeInString } from "../../util/ranges"; +import { languageForFilepath } from "../constructPrompt"; +import { AutocompleteInput } from "../types"; + +/** + * We have to handle a few edge cases in getting the entire prefix/suffix for the current file. + * This is entirely prior to finding snippets from other files + */ +export async function constructInitialPrefixSuffix( + input: AutocompleteInput, + ide: IDE, +): Promise<{ + prefix: string; + suffix: string; +}> { + const lang = languageForFilepath(input.filepath); + + const fileContents = + input.manuallyPassFileContents ?? (await ide.readFile(input.filepath)); + const fileLines = fileContents.split("\n"); + let prefix = + getRangeInString(fileContents, { + start: { line: 0, character: 0 }, + end: input.selectedCompletionInfo?.range.start ?? input.pos, + }) + (input.selectedCompletionInfo?.text ?? ""); + + if (input.injectDetails) { + const lines = prefix.split("\n"); + prefix = `${lines.slice(0, -1).join("\n")}\n${ + lang.singleLineComment + } ${input.injectDetails + .split("\n") + .join(`\n${lang.singleLineComment} `)}\n${lines[lines.length - 1]}`; + } + + const suffix = getRangeInString(fileContents, { + start: input.pos, + end: { line: fileLines.length - 1, character: Number.MAX_SAFE_INTEGER }, + }); + + return { prefix, suffix }; +} diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 46ac9432d..ad9dc7391 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,9 +1,9 @@ -import { CompletionOptions, TabAutocompleteOptions } from "../.."; +import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; import { decideMultilineEarly } from "../classification/shouldCompleteMultiline"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { AutocompleteSnippet } from "../context/ranking"; -import { AutocompleteInput } from "../types"; +import { HelperVars } from "../HelperVars"; import { getTemplateForModel } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; @@ -61,25 +61,20 @@ function renderStringTemplate( return prompt; } export function renderPrompt( - options: TabAutocompleteOptions, prefix: string, suffix: string, - filepath: string, - lang: AutocompleteLanguageInfo, snippets: AutocompleteSnippet[], - model: string, workspaceDirs: string[], - userDefinedTemplate: string | undefined, - selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"], completeMultiline: boolean, + helper: HelperVars, ): [string, Partial | undefined, boolean] { let { template, completionOptions, compilePrefixSuffix = undefined, - } = userDefinedTemplate - ? { template: userDefinedTemplate, completionOptions: {} } - : getTemplateForModel(model); + } = helper.options.template + ? { template: helper.options.template, completionOptions: {} } + : getTemplateForModel(helper.modelName); let prompt: string; const reponame = getBasename(workspaceDirs[0] ?? "myproject"); @@ -90,7 +85,7 @@ export function renderPrompt( [prefix, suffix] = compilePrefixSuffix( prefix, suffix, - filepath, + helper.filepath, reponame, snippets, ); @@ -103,26 +98,37 @@ export function renderPrompt( prefix, suffix, snippets, - lang, - filepath, + helper.lang, + helper.filepath, reponame, ); } else { - prompt = template(prefix, suffix, filepath, reponame, lang.name, snippets); + prompt = template( + prefix, + suffix, + helper.filepath, + reponame, + helper.lang.name, + snippets, + ); } const multiline = - !options.transform || + !helper.options.transform || decideMultilineEarly({ - multilineCompletions: options.multilineCompletions, - language: lang, - selectedCompletionInfo: selectedCompletionInfo, + multilineCompletions: helper.options.multilineCompletions, + language: helper.lang, + selectedCompletionInfo: helper.input.selectedCompletionInfo, prefix, suffix, completeMultiline, }); - const stopTokens = getStopTokens(completionOptions, lang, model); + const stopTokens = getStopTokens( + completionOptions, + helper.lang, + helper.modelName, + ); completionOptions = { ...completionOptions, From 4b15d00802fbcc7376a5edf194a09435efac2eac Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 14:15:00 -0700 Subject: [PATCH 16/43] more refactoring --- core/autocomplete/CompletionProvider.ts | 277 +++++++----------- .../generation/CompletionStreamer.ts | 67 +++++ 2 files changed, 178 insertions(+), 166 deletions(-) create mode 100644 core/autocomplete/generation/CompletionStreamer.ts diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 5ec075c6d..665e88513 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -11,7 +11,6 @@ import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.j import { constructAutocompletePrompt } from "./constructPrompt.js"; import { AutocompleteSnippet } from "./context/ranking/index.js"; import { RootPathContextService } from "./context/RootPathContextService.js"; -import { GeneratorReuseManager } from "./generation/GeneratorReuseManager.js"; import { postprocessCompletion } from "./postprocessing/index.js"; // @prettier-ignore import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; @@ -20,7 +19,7 @@ import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; -import { StreamTransformPipeline } from "./filtering/streamTransforms/StreamTransformPipeline.js"; +import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { HelperVars } from "./HelperVars.js"; import { shouldPrefilter } from "./prefiltering/index.js"; import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix.js"; @@ -47,13 +46,11 @@ export type GetLspDefinitionsFunction = ( export class CompletionProvider { private importDefinitionsService: ImportDefinitionsService; private rootPathContextService: RootPathContextService; - private generatorReuseManager: GeneratorReuseManager; private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); private bracketMatchingService = new BracketMatchingService(); private debouncer = new AutocompleteDebouncer(); - private streamTransformPipeline = new StreamTransformPipeline(); - // private nearbyDefinitionsService = new NearbyDefinitionsService(); + private completionStreamer: CompletionStreamer; constructor( private readonly configHandler: ConfigHandler, @@ -62,9 +59,7 @@ export class CompletionProvider { private readonly _onError: (e: any) => void, private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, ) { - this.generatorReuseManager = new GeneratorReuseManager( - this.onError.bind(this), - ); + this.completionStreamer = new CompletionStreamer(this.onError.bind(this)); this.importDefinitionsService = new ImportDefinitionsService(this.ide); this.rootPathContextService = new RootPathContextService( this.importDefinitionsService, @@ -103,7 +98,6 @@ export class CompletionProvider { } private onError(e: any) { - console.warn("Error generating autocompletion: ", e); if ( ERRORS_TO_IGNORE.some((err) => typeof e === "string" ? e.includes(err) : e?.message?.includes(err), @@ -111,6 +105,8 @@ export class CompletionProvider { ) { return; } + + console.warn("Error generating autocompletion: ", e); if (!this.errorsShown.has(e.message)) { this.errorsShown.add(e.message); this._onError(e); @@ -197,6 +193,8 @@ export class CompletionProvider { token: AbortSignal | undefined, ): Promise { try { + const startTime = Date.now(); + const llm = await this._prepareLlm(); if (!llm) { return undefined; @@ -214,8 +212,6 @@ export class CompletionProvider { return undefined; } - // Get completion - // Create abort signal if not given if (!token) { const controller = new AbortController(); @@ -223,12 +219,114 @@ export class CompletionProvider { this._abortControllers.set(input.completionId, controller); } - const outcome = await this.getTabCompletion(token, llm, helper); + ////////// - if (!outcome?.completion) { + // Construct full prefix/suffix (a few edge cases handled in here) + const { prefix: fullPrefix, suffix: fullSuffix } = + await constructInitialPrefixSuffix(helper.input, this.ide); + + // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, + // or they might separately track recently edited ranges) + const extraSnippets = await this._getExtraSnippets( + helper, + fullPrefix, + fullSuffix, + ); + + let { prefix, suffix, completeMultiline, snippets } = + await constructAutocompletePrompt( + fullPrefix, + fullSuffix, + helper, + extraSnippets, + this.importDefinitionsService, + this.rootPathContextService, + ); + + // If prefix is manually passed + if (helper.input.manuallyPassPrefix) { + prefix = helper.input.manuallyPassPrefix; + suffix = ""; + } + + const [prompt, completionOptions, multiline] = renderPrompt( + prefix, + suffix, + snippets, + await this.ide.getWorkspaceDirs(), + completeMultiline, + helper, + ); + + // Completion + let completion: string | undefined = ""; + + const cache = await autocompleteCache; + const cachedCompletion = helper.options.useCache + ? await cache.get(prefix) + : undefined; + let cacheHit = false; + if (cachedCompletion) { + // Cache + cacheHit = true; + completion = cachedCompletion; + } else { + const completionStream = + this.completionStreamer.streamCompletionWithFilters( + token, + llm, + prefix, + suffix, + prompt, + multiline, + completionOptions, + helper, + ); + + for await (const update of completionStream) { + completion += update; + } + + // Don't postprocess if aborted + if (token.aborted) { + return undefined; + } + + const processedCompletion = helper.options.transform + ? postprocessCompletion({ + completion, + prefix, + suffix, + llm, + }) + : completion; + + completion = processedCompletion; + } + + if (!completion) { return undefined; } + const outcome: AutocompleteOutcome = { + time: Date.now() - startTime, + completion, + prefix, + suffix, + prompt, + modelProvider: llm.providerName, + modelName: llm.model, + completionOptions, + cacheHit, + filepath: helper.filepath, + completionId: helper.input.completionId, + gitRepo: await this.ide.getRepoName(helper.filepath), + uniqueId: await this.ide.getUniqueId(), + ...helper.options, + }; + + ////////// + // Do some stuff later so as not to block return. Latency matters const completionToCache = outcome.completion; setTimeout(async () => { @@ -316,157 +414,4 @@ export class CompletionProvider { return extraSnippets; } - - async getTabCompletion( - token: AbortSignal, - llm: ILLM, - helper: HelperVars, - ): Promise { - const startTime = Date.now(); - - // Construct full prefix/suffix (a few edge cases handled in here) - const { prefix: fullPrefix, suffix: fullSuffix } = - await constructInitialPrefixSuffix(helper.input, this.ide); - - // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, - // or they might separately track recently edited ranges) - const extraSnippets = await this._getExtraSnippets( - helper, - fullPrefix, - fullSuffix, - ); - - let { prefix, suffix, completeMultiline, snippets } = - await constructAutocompletePrompt( - fullPrefix, - fullSuffix, - helper, - extraSnippets, - this.importDefinitionsService, - this.rootPathContextService, - ); - - // If prefix is manually passed - if (helper.input.manuallyPassPrefix) { - prefix = helper.input.manuallyPassPrefix; - suffix = ""; - } - - const [prompt, completionOptions, multiline] = renderPrompt( - prefix, - suffix, - snippets, - await this.ide.getWorkspaceDirs(), - completeMultiline, - helper, - ); - - // Completion - let completion: string | undefined = ""; - - const cache = await autocompleteCache; - const cachedCompletion = helper.options.useCache - ? await cache.get(prefix) - : undefined; - let cacheHit = false; - if (cachedCompletion) { - // Cache - cacheHit = true; - completion = cachedCompletion; - } else { - // Try to reuse pending requests if what the user typed matches start of completion - const generator = this.generatorReuseManager.getGenerator( - prefix, - () => - llm.supportsFim() - ? llm.streamFim(prefix, suffix, completionOptions) - : llm.streamComplete(prompt, { - ...completionOptions, - raw: true, - }), - multiline, - ); - - // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion - const fullStop = () => - this.generatorReuseManager.currentGenerator?.cancel(); - - // LLM - let cancelled = false; - const generatorWithCancellation = async function* () { - for await (const update of generator) { - if (token.aborted) { - cancelled = true; - return; - } - yield update; - } - }; - - const initialGenerator = generatorWithCancellation(); - const finalGenerator = helper.options.transform - ? this.streamTransformPipeline.transform( - initialGenerator, - prefix, - suffix, - helper.filepath, - multiline, - helper.pos, - helper.fileLines, - completionOptions?.stop || [], - helper.lang, - fullStop, - ) - : initialGenerator; - - try { - for await (const update of finalGenerator) { - completion += update; - } - } catch (e: any) { - if (ERRORS_TO_IGNORE.some((err) => e.includes(err))) { - return undefined; - } - throw e; - } - - if (cancelled) { - return undefined; - } - - const processedCompletion = helper.options.transform - ? postprocessCompletion({ - completion, - prefix, - suffix, - llm, - }) - : completion; - - completion = processedCompletion; - } - - const time = Date.now() - startTime; - - if (!completion) { - return undefined; - } - - return { - time, - completion, - prefix, - suffix, - prompt, - modelProvider: llm.providerName, - modelName: llm.model, - completionOptions, - cacheHit, - filepath: helper.filepath, - completionId: helper.input.completionId, - gitRepo: await this.ide.getRepoName(helper.filepath), - uniqueId: await this.ide.getUniqueId(), - ...helper.options, - }; - } } diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts new file mode 100644 index 000000000..803420be9 --- /dev/null +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -0,0 +1,67 @@ +import { CompletionOptions, ILLM } from "../.."; +import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTransformPipeline"; +import { HelperVars } from "../HelperVars"; +import { GeneratorReuseManager } from "./GeneratorReuseManager"; + +export class CompletionStreamer { + private streamTransformPipeline = new StreamTransformPipeline(); + private generatorReuseManager: GeneratorReuseManager; + + constructor(private readonly onError: (err: any) => void) { + this.generatorReuseManager = new GeneratorReuseManager(onError); + } + + async *streamCompletionWithFilters( + token: AbortSignal, + llm: ILLM, + prefix: string, + suffix: string, + prompt: string, + multiline: boolean, + completionOptions: Partial | undefined, + helper: HelperVars, + ) { + // Try to reuse pending requests if what the user typed matches start of completion + const generator = this.generatorReuseManager.getGenerator( + prefix, + () => + llm.supportsFim() + ? llm.streamFim(prefix, suffix, completionOptions) + : llm.streamComplete(prompt, { + ...completionOptions, + raw: true, + }), + multiline, + ); + + // Full stop means to stop the LLM's generation, instead of just truncating the displayed completion + const fullStop = () => + this.generatorReuseManager.currentGenerator?.cancel(); + + // LLM + const generatorWithCancellation = async function* () { + for await (const update of generator) { + if (token.aborted) { + return; + } + yield update; + } + }; + + const initialGenerator = generatorWithCancellation(); + const finalGenerator = helper.options.transform + ? this.streamTransformPipeline.transform( + initialGenerator, + prefix, + suffix, + helper.filepath, + multiline, + helper.pos, + helper.fileLines, + completionOptions?.stop || [], + helper.lang, + fullStop, + ) + : initialGenerator; + } +} From c74c92848f1c365184443c9c1f7b088ba16346b8 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 14:25:25 -0700 Subject: [PATCH 17/43] fix bugs --- core/autocomplete/CompletionProvider.ts | 7 ++++++- core/autocomplete/HelperVars.ts | 15 +++++++++++++-- .../autocomplete/generation/CompletionStreamer.ts | 4 ++++ 3 files changed, 23 insertions(+), 3 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 665e88513..17b3c871d 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -201,7 +201,12 @@ export class CompletionProvider { } const options = await this._getAutocompleteOptions(); - const helper = new HelperVars(input, options, llm.model, this.ide); + const helper = await HelperVars.create( + input, + options, + llm.model, + this.ide, + ); if (await shouldPrefilter(helper, this.ide)) { return undefined; diff --git a/core/autocomplete/HelperVars.ts b/core/autocomplete/HelperVars.ts index 124389509..9dd56653d 100644 --- a/core/autocomplete/HelperVars.ts +++ b/core/autocomplete/HelperVars.ts @@ -12,7 +12,7 @@ export class HelperVars { private _fileContents: string | undefined; private _fileLines: string[] | undefined; - constructor( + private constructor( public readonly input: AutocompleteInput, public readonly options: TabAutocompleteOptions, public readonly modelName: string, @@ -21,7 +21,7 @@ export class HelperVars { this.lang = languageForFilepath(input.filepath); } - async init() { + private async init() { // Don't do anything if already initialized if (this._fileContents !== undefined) return; @@ -32,6 +32,17 @@ export class HelperVars { this._fileLines = this._fileContents.split("\n"); } + static async create( + input: AutocompleteInput, + options: TabAutocompleteOptions, + modelName: string, + ide: IDE, + ): Promise { + const instance = new HelperVars(input, options, modelName, ide); + await instance.init(); + return instance; + } + // Fast access get filepath() { return this.input.filepath; diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts index 803420be9..a723a3c1b 100644 --- a/core/autocomplete/generation/CompletionStreamer.ts +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -63,5 +63,9 @@ export class CompletionStreamer { fullStop, ) : initialGenerator; + + for await (const update of finalGenerator) { + yield update; + } } } From 9850834c227aa79802381d388f853b7f7ce8201c Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 14:36:28 -0700 Subject: [PATCH 18/43] refactor logging service --- .../AutocompleteLoggingService.ts | 119 +++++++++++++++++ core/autocomplete/CompletionProvider.ts | 123 +++--------------- 2 files changed, 135 insertions(+), 107 deletions(-) create mode 100644 core/autocomplete/AutocompleteLoggingService.ts diff --git a/core/autocomplete/AutocompleteLoggingService.ts b/core/autocomplete/AutocompleteLoggingService.ts new file mode 100644 index 000000000..6771b1dd6 --- /dev/null +++ b/core/autocomplete/AutocompleteLoggingService.ts @@ -0,0 +1,119 @@ +import { logDevData } from "../util/devdata"; +import { COUNT_COMPLETION_REJECTED_AFTER } from "../util/parameters"; +import { Telemetry } from "../util/posthog"; +import { AutocompleteOutcome } from "./types"; + +export class AutocompleteLoggingService { + // Key is completionId + private _abortControllers = new Map(); + private _logRejectionTimeouts = new Map(); + private _outcomes = new Map(); + _lastDisplayedCompletion: { id: string; displayedAt: number } | undefined = + undefined; + + public createAbortController(completionId: string): AbortController { + const abortController = new AbortController(); + this._abortControllers.set(completionId, abortController); + return abortController; + } + + public deleteAbortController(completionId: string) { + this._abortControllers.delete(completionId); + } + + public cancel() { + this._abortControllers.forEach((abortController, id) => { + abortController.abort(); + }); + this._abortControllers.clear(); + } + + public accept(completionId: string): AutocompleteOutcome | undefined { + if (this._logRejectionTimeouts.has(completionId)) { + clearTimeout(this._logRejectionTimeouts.get(completionId)); + this._logRejectionTimeouts.delete(completionId); + } + + if (this._outcomes.has(completionId)) { + const outcome = this._outcomes.get(completionId)!; + this.logAutocompleteOutcome(outcome); + this._outcomes.delete(completionId); + return outcome; + } + } + + public cancelRejectionTimeout(completionId: string) { + if (this._logRejectionTimeouts.has(completionId)) { + clearTimeout(this._logRejectionTimeouts.get(completionId)!); + this._logRejectionTimeouts.delete(completionId); + } + + if (this._outcomes.has(completionId)) { + this._outcomes.delete(completionId); + } + } + + public markDisplayed(completionId: string, outcome: AutocompleteOutcome) { + const logRejectionTimeout = setTimeout(() => { + // Wait 10 seconds, then assume it wasn't accepted + outcome.accepted = false; + this.logAutocompleteOutcome(outcome); + this._logRejectionTimeouts.delete(completionId); + }, COUNT_COMPLETION_REJECTED_AFTER); + this._outcomes.set(completionId, outcome); + this._logRejectionTimeouts.set(completionId, logRejectionTimeout); + + // If the previously displayed completion is still waiting for rejection, + // and this one is a continuation of that (the outcome.completion is the same modulo prefix) + // then we should cancel the rejection timeout + const previous = this._lastDisplayedCompletion; + const now = Date.now(); + if (previous && this._logRejectionTimeouts.has(previous.id)) { + const previousOutcome = this._outcomes.get(previous.id); + const c1 = previousOutcome?.completion.split("\n")[0] ?? ""; + const c2 = outcome.completion.split("\n")[0]; + if ( + previousOutcome && + (c1.endsWith(c2) || + c2.endsWith(c1) || + c1.startsWith(c2) || + c2.startsWith(c1)) + ) { + this.cancelRejectionTimeout(previous.id); + } else if (now - previous.displayedAt < 500) { + // If a completion isn't shown for more than + this.cancelRejectionTimeout(previous.id); + } + } + + this._lastDisplayedCompletion = { + id: completionId, + displayedAt: now, + }; + } + + private logAutocompleteOutcome(outcome: AutocompleteOutcome) { + outcome.accepted = true; + logDevData("autocomplete", outcome); + const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; + void Telemetry.capture( + "autocomplete", + { + accepted: restOfOutcome.accepted, + cacheHit: restOfOutcome.cacheHit, + completionId: restOfOutcome.completionId, + completionOptions: restOfOutcome.completionOptions, + debounceDelay: restOfOutcome.debounceDelay, + fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0], + maxPromptTokens: restOfOutcome.maxPromptTokens, + modelName: restOfOutcome.modelName, + modelProvider: restOfOutcome.modelProvider, + multilineCompletions: restOfOutcome.multilineCompletions, + time: restOfOutcome.time, + useRecentlyEdited: restOfOutcome.useRecentlyEdited, + useRootPathContext: restOfOutcome.useRootPathContext, + }, + true, + ); + } +} diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 17b3c871d..323f737c5 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -1,11 +1,6 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; import { IDE, ILLM } from "../index.js"; -import { logDevData } from "../util/devdata.js"; -import { - COUNT_COMPLETION_REJECTED_AFTER, - DEFAULT_AUTOCOMPLETE_OPTS, -} from "../util/parameters.js"; -import { Telemetry } from "../util/posthog.js"; +import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; import { constructAutocompletePrompt } from "./constructPrompt.js"; @@ -16,6 +11,7 @@ import { postprocessCompletion } from "./postprocessing/index.js"; import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import OpenAI from "../llm/llms/OpenAI.js"; import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; +import { AutocompleteLoggingService } from "./AutocompleteLoggingService.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; @@ -51,6 +47,7 @@ export class CompletionProvider { private bracketMatchingService = new BracketMatchingService(); private debouncer = new AutocompleteDebouncer(); private completionStreamer: CompletionStreamer; + private loggingService = new AutocompleteLoggingService(); constructor( private readonly configHandler: ConfigHandler, @@ -114,69 +111,22 @@ export class CompletionProvider { } public cancel() { - this._abortControllers.forEach((abortController, id) => { - abortController.abort(); - }); - this._abortControllers.clear(); + this.loggingService.cancel(); } - // Key is completionId - private _abortControllers = new Map(); - private _logRejectionTimeouts = new Map(); - private _outcomes = new Map(); - public accept(completionId: string) { - if (this._logRejectionTimeouts.has(completionId)) { - clearTimeout(this._logRejectionTimeouts.get(completionId)); - this._logRejectionTimeouts.delete(completionId); + const outcome = this.loggingService.accept(completionId); + if (!outcome) { + return; } - - if (this._outcomes.has(completionId)) { - const outcome = this._outcomes.get(completionId)!; - this.logAutocompleteOutcome(outcome); - this._outcomes.delete(completionId); - - this.bracketMatchingService.handleAcceptedCompletion( - outcome.completion, - outcome.filepath, - ); - } - } - - private logAutocompleteOutcome(outcome: AutocompleteOutcome) { - outcome.accepted = true; - logDevData("autocomplete", outcome); - const { prompt, completion, prefix, suffix, ...restOfOutcome } = outcome; - void Telemetry.capture( - "autocomplete", - { - accepted: restOfOutcome.accepted, - cacheHit: restOfOutcome.cacheHit, - completionId: restOfOutcome.completionId, - completionOptions: restOfOutcome.completionOptions, - debounceDelay: restOfOutcome.debounceDelay, - fileExtension: restOfOutcome.filepath.split(".")?.slice(-1)[0], - maxPromptTokens: restOfOutcome.maxPromptTokens, - modelName: restOfOutcome.modelName, - modelProvider: restOfOutcome.modelProvider, - multilineCompletions: restOfOutcome.multilineCompletions, - time: restOfOutcome.time, - useRecentlyEdited: restOfOutcome.useRecentlyEdited, - useRootPathContext: restOfOutcome.useRootPathContext, - }, - true, + this.bracketMatchingService.handleAcceptedCompletion( + outcome.completion, + outcome.filepath, ); } - public cancelRejectionTimeout(completionId: string) { - if (this._logRejectionTimeouts.has(completionId)) { - clearTimeout(this._logRejectionTimeouts.get(completionId)!); - this._logRejectionTimeouts.delete(completionId); - } - - if (this._outcomes.has(completionId)) { - this._outcomes.delete(completionId); - } + public markDisplayed(completionId: string, outcome: AutocompleteOutcome) { + this.loggingService.markDisplayed(completionId, outcome); } private async _getAutocompleteOptions() { @@ -219,9 +169,10 @@ export class CompletionProvider { // Create abort signal if not given if (!token) { - const controller = new AbortController(); + const controller = this.loggingService.createAbortController( + input.completionId, + ); token = controller.signal; - this._abortControllers.set(input.completionId, controller); } ////////// @@ -344,52 +295,10 @@ export class CompletionProvider { } catch (e: any) { this.onError(e); } finally { - this._abortControllers.delete(input.completionId); + this.loggingService.deleteAbortController(input.completionId); } } - _lastDisplayedCompletion: { id: string; displayedAt: number } | undefined = - undefined; - - markDisplayed(completionId: string, outcome: AutocompleteOutcome) { - const logRejectionTimeout = setTimeout(() => { - // Wait 10 seconds, then assume it wasn't accepted - outcome.accepted = false; - this.logAutocompleteOutcome(outcome); - this._logRejectionTimeouts.delete(completionId); - }, COUNT_COMPLETION_REJECTED_AFTER); - this._outcomes.set(completionId, outcome); - this._logRejectionTimeouts.set(completionId, logRejectionTimeout); - - // If the previously displayed completion is still waiting for rejection, - // and this one is a continuation of that (the outcome.completion is the same modulo prefix) - // then we should cancel the rejection timeout - const previous = this._lastDisplayedCompletion; - const now = Date.now(); - if (previous && this._logRejectionTimeouts.has(previous.id)) { - const previousOutcome = this._outcomes.get(previous.id); - const c1 = previousOutcome?.completion.split("\n")[0] ?? ""; - const c2 = outcome.completion.split("\n")[0]; - if ( - previousOutcome && - (c1.endsWith(c2) || - c2.endsWith(c1) || - c1.startsWith(c2) || - c2.startsWith(c1)) - ) { - this.cancelRejectionTimeout(previous.id); - } else if (now - previous.displayedAt < 500) { - // If a completion isn't shown for more than - this.cancelRejectionTimeout(previous.id); - } - } - - this._lastDisplayedCompletion = { - id: completionId, - displayedAt: now, - }; - } - private async _getExtraSnippets( helper: HelperVars, fullPrefix: string, From d6e54c39329d485423b03d8d7cb85d4c142cb77b Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 15:35:19 -0700 Subject: [PATCH 19/43] more refactoring --- core/autocomplete/CompletionProvider.ts | 47 +--- core/autocomplete/HelperVars.ts | 39 +++ .../classification/shouldCompleteMultiline.ts | 13 +- core/autocomplete/constructPrompt.ts | 222 +++++------------- .../context/ContextRetrievalService.ts | 85 +++++++ core/autocomplete/context/ranking/index.ts | 13 +- 6 files changed, 215 insertions(+), 204 deletions(-) create mode 100644 core/autocomplete/context/ContextRetrievalService.ts diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 323f737c5..50629e30e 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -1,11 +1,9 @@ import { ConfigHandler } from "../config/ConfigHandler.js"; import { IDE, ILLM } from "../index.js"; import { DEFAULT_AUTOCOMPLETE_OPTS } from "../util/parameters.js"; - import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo.js"; import { constructAutocompletePrompt } from "./constructPrompt.js"; import { AutocompleteSnippet } from "./context/ranking/index.js"; -import { RootPathContextService } from "./context/RootPathContextService.js"; import { postprocessCompletion } from "./postprocessing/index.js"; // @prettier-ignore import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; @@ -13,12 +11,11 @@ import OpenAI from "../llm/llms/OpenAI.js"; import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; import { AutocompleteLoggingService } from "./AutocompleteLoggingService.js"; import AutocompleteLruCache from "./AutocompleteLruCache.js"; -import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; import { HelperVars } from "./HelperVars.js"; import { shouldPrefilter } from "./prefiltering/index.js"; -import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix.js"; import { renderPrompt } from "./templating/index.js"; import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; @@ -40,14 +37,13 @@ export type GetLspDefinitionsFunction = ( ) => Promise; export class CompletionProvider { - private importDefinitionsService: ImportDefinitionsService; - private rootPathContextService: RootPathContextService; private autocompleteCache = AutocompleteLruCache.get(); public errorsShown: Set = new Set(); private bracketMatchingService = new BracketMatchingService(); private debouncer = new AutocompleteDebouncer(); private completionStreamer: CompletionStreamer; private loggingService = new AutocompleteLoggingService(); + private contextRetrievalService: ContextRetrievalService; constructor( private readonly configHandler: ConfigHandler, @@ -57,11 +53,7 @@ export class CompletionProvider { private readonly getDefinitionsFromLsp: GetLspDefinitionsFunction, ) { this.completionStreamer = new CompletionStreamer(this.onError.bind(this)); - this.importDefinitionsService = new ImportDefinitionsService(this.ide); - this.rootPathContextService = new RootPathContextService( - this.importDefinitionsService, - this.ide, - ); + this.contextRetrievalService = new ContextRetrievalService(this.ide); } private async _prepareLlm(): Promise { @@ -144,13 +136,18 @@ export class CompletionProvider { ): Promise { try { const startTime = Date.now(); + const options = await this._getAutocompleteOptions(); + + // Debounce + if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { + return undefined; + } const llm = await this._prepareLlm(); if (!llm) { return undefined; } - const options = await this._getAutocompleteOptions(); const helper = await HelperVars.create( input, options, @@ -162,11 +159,6 @@ export class CompletionProvider { return undefined; } - // Debounce - if (await this.debouncer.delayAndShouldDebounce(options.debounceDelay)) { - return undefined; - } - // Create abort signal if not given if (!token) { const controller = this.loggingService.createAbortController( @@ -177,26 +169,15 @@ export class CompletionProvider { ////////// - // Construct full prefix/suffix (a few edge cases handled in here) - const { prefix: fullPrefix, suffix: fullSuffix } = - await constructInitialPrefixSuffix(helper.input, this.ide); - // Some IDEs might have special ways of finding snippets (e.g. JetBrains and VS Code have different "LSP-equivalent" systems, // or they might separately track recently edited ranges) - const extraSnippets = await this._getExtraSnippets( - helper, - fullPrefix, - fullSuffix, - ); + const extraSnippets = await this._getExtraSnippets(helper); let { prefix, suffix, completeMultiline, snippets } = await constructAutocompletePrompt( - fullPrefix, - fullSuffix, helper, extraSnippets, - this.importDefinitionsService, - this.rootPathContextService, + this.contextRetrievalService, ); // If prefix is manually passed @@ -301,15 +282,13 @@ export class CompletionProvider { private async _getExtraSnippets( helper: HelperVars, - fullPrefix: string, - fullSuffix: string, ): Promise { let extraSnippets = helper.options.useOtherFiles ? ((await Promise.race([ this.getDefinitionsFromLsp( helper.input.filepath, - fullPrefix + fullSuffix, - fullPrefix.length, + helper.fullPrefix + helper.fullSuffix, + helper.fullPrefix.length, this.ide, helper.lang, ), diff --git a/core/autocomplete/HelperVars.ts b/core/autocomplete/HelperVars.ts index 9dd56653d..2c9f0fe27 100644 --- a/core/autocomplete/HelperVars.ts +++ b/core/autocomplete/HelperVars.ts @@ -1,7 +1,9 @@ import { IDE, TabAutocompleteOptions } from ".."; import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo"; import { languageForFilepath } from "./constructPrompt"; +import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix"; import { AutocompleteInput } from "./types"; +import { AstPath, getAst, getTreePathAtCursor } from "./util/ast"; /** * A collection of variables that are often accessed throughout the autocomplete pipeline @@ -9,8 +11,12 @@ import { AutocompleteInput } from "./types"; */ export class HelperVars { lang: AutocompleteLanguageInfo; + treePath: AstPath | undefined; + private _fileContents: string | undefined; private _fileLines: string[] | undefined; + private _fullPrefix: string | undefined; + private _fullSuffix: string | undefined; private constructor( public readonly input: AutocompleteInput, @@ -30,6 +36,21 @@ export class HelperVars { (await this.ide.readFile(this.filepath)); this._fileLines = this._fileContents.split("\n"); + + // Construct full prefix/suffix (a few edge cases handled in here) + const { prefix: fullPrefix, suffix: fullSuffix } = + await constructInitialPrefixSuffix(this.input, this.ide); + this._fullPrefix = fullPrefix; + this._fullSuffix = fullSuffix; + + try { + const ast = await getAst(this.filepath, fullPrefix + fullSuffix); + if (ast) { + this.treePath = await getTreePathAtCursor(ast, fullPrefix.length); + } + } catch (e) { + console.error("Failed to parse AST", e); + } } static async create( @@ -69,4 +90,22 @@ export class HelperVars { } return this._fileLines; } + + get fullPrefix(): string { + if (this._fullPrefix === undefined) { + throw new Error( + "HelperVars must be initialized before accessing fullPrefix", + ); + } + return this._fullPrefix; + } + + get fullSuffix(): string { + if (this._fullSuffix === undefined) { + throw new Error( + "HelperVars must be initialized before accessing fullSuffix", + ); + } + return this._fullSuffix; + } } diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts index 8bc5e5de4..d8df8aeb0 100644 --- a/core/autocomplete/classification/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -1,7 +1,7 @@ import { TabAutocompleteOptions } from "@continuedev/config-types"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; +import { HelperVars } from "../HelperVars"; import { AutocompleteInput } from "../types"; -import { AstPath } from "../util/ast"; const BLOCK_TYPES = ["body", "statement_block"]; @@ -10,23 +10,20 @@ function isMidlineCompletion(prefix: string, suffix: string): boolean { } export async function shouldCompleteMultiline( - treePath: AstPath | undefined, - fullPrefix: string, - fullSuffix: string, - language: AutocompleteLanguageInfo, + helper: HelperVars, ): Promise { // Don't complete multi-line if you are mid-line - if (isMidlineCompletion(fullPrefix, fullSuffix)) { + if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) { return false; } // Don't complete multi-line for single-line comments if ( - fullPrefix + helper.fullPrefix .split("\n") .slice(-1)[0] ?.trimStart() - .startsWith(language.singleLineComment) + .startsWith(helper.lang.singleLineComment) ) { return false; } diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index cbef4949b..c83e1b107 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -9,18 +9,14 @@ import { LANGUAGES, Typescript, } from "./constants/AutocompleteLanguageInfo.js"; -import { ImportDefinitionsService } from "./context/ImportDefinitionsService.js"; +import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, - getSymbolsForSnippet, rankSnippets, removeRangeFromSnippets, type AutocompleteSnippet, } from "./context/ranking/index.js"; -import { RootPathContextService } from "./context/RootPathContextService.js"; import { HelperVars } from "./HelperVars.js"; -import { findMatchingRange } from "./recentlyEdited.js"; -import { AstPath, getAst, getTreePathAtCursor } from "./util/ast.js"; export function languageForFilepath( filepath: string, @@ -29,12 +25,9 @@ export function languageForFilepath( } export async function constructAutocompletePrompt( - fullPrefix: string, - fullSuffix: string, helper: HelperVars, extraSnippets: AutocompleteSnippet[], - importDefinitionsService: ImportDefinitionsService, - rootPathContextService: RootPathContextService, + contextRetrievalService: ContextRetrievalService, ): Promise<{ prefix: string; suffix: string; @@ -45,177 +38,84 @@ export async function constructAutocompletePrompt( // Construct basic prefix const maxPrefixTokens = helper.options.maxPromptTokens * helper.options.prefixPercentage; - const prefix = pruneLinesFromTop( - fullPrefix, + const prunedPrefix = pruneLinesFromTop( + helper.fullPrefix, maxPrefixTokens, helper.modelName, ); // Construct suffix const maxSuffixTokens = Math.min( - helper.options.maxPromptTokens - countTokens(prefix, helper.modelName), + helper.options.maxPromptTokens - + countTokens(prunedPrefix, helper.modelName), helper.options.maxSuffixPercentage * helper.options.maxPromptTokens, ); - const suffix = pruneLinesFromBottom( - fullSuffix, + const prunedSuffix = pruneLinesFromBottom( + helper.fullSuffix, maxSuffixTokens, helper.modelName, ); - // Calculate AST Path - let treePath: AstPath | undefined; - try { - const ast = await getAst(helper.filepath, fullPrefix + fullSuffix); - if (ast) { - treePath = await getTreePathAtCursor(ast, fullPrefix.length); - } - } catch (e) { - console.error("Failed to parse AST", e); - } + let snippets = await contextRetrievalService.retrieve( + prunedPrefix, + helper, + extraSnippets, + ); - // Find external snippets - let snippets: AutocompleteSnippet[] = []; - - if (helper.options.useOtherFiles) { - snippets.push(...extraSnippets); - - const windowAroundCursor = - fullPrefix.slice( - -helper.options.slidingWindowSize * - helper.options.slidingWindowPrefixPercentage, - ) + - fullSuffix.slice( - helper.options.slidingWindowSize * - (1 - helper.options.slidingWindowPrefixPercentage), - ); - - // This was much too slow, and not super useful - // const slidingWindowMatches = await slidingWindowMatcher( - // recentlyEditedFiles, - // windowAroundCursor, - // 3, - // options.slidingWindowSize, - // ); - // snippets.push(...slidingWindowMatches); - - // snippets.push( - // ...recentlyEditedRanges.map((r) => ({ - // ...r, - // contents: r.lines.join("\n"), - // })), - // ); - - if (helper.options.useRecentlyEdited) { - const currentLinePrefix = prefix.trim().split("\n").slice(-1)[0]; - if ( - currentLinePrefix?.length > - helper.options.recentLinePrefixMatchMinLength - ) { - const matchingRange = findMatchingRange( - helper.input.recentlyEditedRanges, - currentLinePrefix, - ); - if (matchingRange) { - snippets.push({ - ...matchingRange, - contents: matchingRange.lines.join("\n"), - score: 0.8, - }); - } - } - } - - // Use imports - if (helper.options.useImports) { - const importSnippets = []; - const fileInfo = importDefinitionsService.get(helper.filepath); - if (fileInfo) { - const { imports } = fileInfo; - // Look for imports of any symbols around the current range - const textAroundCursor = - fullPrefix.split("\n").slice(-5).join("\n") + - fullSuffix.split("\n").slice(0, 3).join("\n"); - const symbols = Array.from( - getSymbolsForSnippet(textAroundCursor), - ).filter((symbol) => !helper.lang.topLevelKeywords.includes(symbol)); - for (const symbol of symbols) { - const rifs = imports[symbol]; - if (Array.isArray(rifs)) { - importSnippets.push(...rifs); - } - } - } - snippets.push(...importSnippets); - } - - if (helper.options.useRootPathContext && treePath) { - const ctx = await rootPathContextService.getContextForPath( - helper.filepath, - treePath, - ); - snippets.push(...ctx); - } - - // Filter out empty snippets and ones that are already in the prefix/suffix - snippets = snippets - .map((snippet) => ({ ...snippet })) - .filter( - (s) => - s.contents.trim() !== "" && - !(prefix + suffix).includes(s.contents.trim()), - ); - - // Rank / order the snippets - const scoredSnippets = rankSnippets(snippets, windowAroundCursor); - - // Fill maxSnippetTokens with snippets - const maxSnippetTokens = - helper.options.maxPromptTokens * helper.options.maxSnippetPercentage; - - // Remove prefix range from snippets - const prefixLines = prefix.split("\n").length; - const suffixLines = suffix.split("\n").length; - const buffer = 8; - const prefixSuffixRangeWithBuffer = { - start: { - line: helper.pos.line - prefixLines - buffer, - character: 0, - }, - end: { - line: helper.pos.line + suffixLines + buffer, - character: 0, - }, - }; - let finalSnippets = removeRangeFromSnippets( - scoredSnippets, - helper.filepath.split("://").slice(-1)[0], - prefixSuffixRangeWithBuffer, + // Filter out empty snippets and ones that are already in the prefix/suffix + snippets = snippets + .map((snippet) => ({ ...snippet })) + .filter( + (s) => + s.contents.trim() !== "" && + !(prunedPrefix + prunedSuffix).includes(s.contents.trim()), ); - // Filter snippets for those with best scores (must be above threshold) - finalSnippets = finalSnippets.filter( - (snippet) => - snippet.score >= helper.options.recentlyEditedSimilarityThreshold, - ); - finalSnippets = fillPromptWithSnippets( - scoredSnippets, - maxSnippetTokens, - helper.modelName, - ); + // Rank / order the snippets + const scoredSnippets = rankSnippets(snippets, helper); - snippets = finalSnippets; - } + // Fill maxSnippetTokens with snippets + const maxSnippetTokens = + helper.options.maxPromptTokens * helper.options.maxSnippetPercentage; + + // Remove prefix range from snippets + const prefixLines = prunedPrefix.split("\n").length; + const suffixLines = prunedSuffix.split("\n").length; + const buffer = 8; + const prefixSuffixRangeWithBuffer = { + start: { + line: helper.pos.line - prefixLines - buffer, + character: 0, + }, + end: { + line: helper.pos.line + suffixLines + buffer, + character: 0, + }, + }; + let finalSnippets = removeRangeFromSnippets( + scoredSnippets, + helper.filepath.split("://").slice(-1)[0], + prefixSuffixRangeWithBuffer, + ); + + // Filter snippets for those with best scores (must be above threshold) + finalSnippets = finalSnippets.filter( + (snippet) => + snippet.score >= helper.options.recentlyEditedSimilarityThreshold, + ); + finalSnippets = fillPromptWithSnippets( + scoredSnippets, + maxSnippetTokens, + helper.modelName, + ); + + snippets = finalSnippets; return { - prefix, - suffix, + prefix: prunedPrefix, + suffix: prunedSuffix, useFim: true, - completeMultiline: await shouldCompleteMultiline( - treePath, - fullPrefix, - fullSuffix, - helper.lang, - ), + completeMultiline: await shouldCompleteMultiline(helper), snippets, }; } diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts new file mode 100644 index 000000000..cdf5f2bcd --- /dev/null +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -0,0 +1,85 @@ +import { IDE } from "../.."; +import { HelperVars } from "../HelperVars"; +import { findMatchingRange } from "../recentlyEdited"; +import { ImportDefinitionsService } from "./ImportDefinitionsService"; +import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; +import { RootPathContextService } from "./RootPathContextService"; + +export class ContextRetrievalService { + private importDefinitionsService: ImportDefinitionsService; + private rootPathContextService: RootPathContextService; + + constructor(private readonly ide: IDE) { + this.importDefinitionsService = new ImportDefinitionsService(this.ide); + this.rootPathContextService = new RootPathContextService( + this.importDefinitionsService, + this.ide, + ); + } + + public async retrieve( + prunedPrefix: string, + helper: HelperVars, + extraSnippets: AutocompleteSnippet[], + ) { + // Find external snippets + let snippets: AutocompleteSnippet[] = []; + + if (helper.options.useOtherFiles) { + snippets.push(...extraSnippets); + + if (helper.options.useRecentlyEdited) { + const currentLinePrefix = prunedPrefix.trim().split("\n").slice(-1)[0]; + if ( + currentLinePrefix?.length > + helper.options.recentLinePrefixMatchMinLength + ) { + const matchingRange = findMatchingRange( + helper.input.recentlyEditedRanges, + currentLinePrefix, + ); + if (matchingRange) { + snippets.push({ + ...matchingRange, + contents: matchingRange.lines.join("\n"), + score: 0.8, + }); + } + } + } + + // Use imports + if (helper.options.useImports) { + const importSnippets = []; + const fileInfo = this.importDefinitionsService.get(helper.filepath); + if (fileInfo) { + const { imports } = fileInfo; + // Look for imports of any symbols around the current range + const textAroundCursor = + helper.fullPrefix.split("\n").slice(-5).join("\n") + + helper.fullSuffix.split("\n").slice(0, 3).join("\n"); + const symbols = Array.from( + getSymbolsForSnippet(textAroundCursor), + ).filter((symbol) => !helper.lang.topLevelKeywords.includes(symbol)); + for (const symbol of symbols) { + const rifs = imports[symbol]; + if (Array.isArray(rifs)) { + importSnippets.push(...rifs); + } + } + } + snippets.push(...importSnippets); + } + + if (helper.options.useRootPathContext && helper.treePath) { + const ctx = await this.rootPathContextService.getContextForPath( + helper.filepath, + helper.treePath, + ); + snippets.push(...ctx); + } + } + + return snippets; + } +} diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index 4809901cd..119056ca8 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -1,6 +1,7 @@ import { RangeInFileWithContents } from "../../../commands/util.js"; import { Range } from "../../../index.js"; import { countTokens } from "../../../llm/countTokens.js"; +import { HelperVars } from "../../HelperVars.js"; export type AutocompleteSnippet = RangeInFileWithContents & { score?: number; @@ -43,8 +44,18 @@ export function jaccardSimilarity(a: string, b: string): number { */ export function rankSnippets( ranges: AutocompleteSnippet[], - windowAroundCursor: string, + helper: HelperVars, ): Required[] { + const windowAroundCursor = + helper.fullPrefix.slice( + -helper.options.slidingWindowSize * + helper.options.slidingWindowPrefixPercentage, + ) + + helper.fullSuffix.slice( + helper.options.slidingWindowSize * + (1 - helper.options.slidingWindowPrefixPercentage), + ); + const snippets: Required[] = ranges.map((snippet) => ({ score: snippet.score ?? jaccardSimilarity(snippet.contents, windowAroundCursor), From 40dfede087707aefccd5e6333a498e5d0c67ec4f Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 15:54:29 -0700 Subject: [PATCH 20/43] refactor constructPrompt --- core/autocomplete/HelperVars.ts | 9 +- .../constants/AutocompleteLanguageInfo.ts | 6 + core/autocomplete/constructPrompt.ts | 119 ++++++++++-------- core/autocomplete/context/ranking/index.ts | 2 +- .../templating/constructPrefixSuffix.ts | 3 +- core/commands/slash/share.ts | 2 +- core/util/parameters.ts | 2 +- extensions/vscode/src/util/expandSnippet.ts | 2 +- 8 files changed, 85 insertions(+), 60 deletions(-) diff --git a/core/autocomplete/HelperVars.ts b/core/autocomplete/HelperVars.ts index 2c9f0fe27..e5e3af61c 100644 --- a/core/autocomplete/HelperVars.ts +++ b/core/autocomplete/HelperVars.ts @@ -1,6 +1,8 @@ import { IDE, TabAutocompleteOptions } from ".."; -import { AutocompleteLanguageInfo } from "./constants/AutocompleteLanguageInfo"; -import { languageForFilepath } from "./constructPrompt"; +import { + AutocompleteLanguageInfo, + languageForFilepath, +} from "./constants/AutocompleteLanguageInfo"; import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix"; import { AutocompleteInput } from "./types"; import { AstPath, getAst, getTreePathAtCursor } from "./util/ast"; @@ -71,6 +73,9 @@ export class HelperVars { get pos() { return this.input.pos; } + get maxSnippetTokens() { + return this.options.maxPromptTokens * this.options.maxSnippetPercentage; + } // Getters for lazy access get fileContents(): string { diff --git a/core/autocomplete/constants/AutocompleteLanguageInfo.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts index 3af6e2e15..397d32ed6 100644 --- a/core/autocomplete/constants/AutocompleteLanguageInfo.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -346,3 +346,9 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { yml: YAML, md: Markdown, }; + +export function languageForFilepath( + filepath: string, +): AutocompleteLanguageInfo { + return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript; +} diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index c83e1b107..7c7d898e6 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,40 +1,20 @@ +import { Position, Range } from "../index.js"; import { countTokens, pruneLinesFromBottom, pruneLinesFromTop, } from "../llm/countTokens.js"; import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; -import { - AutocompleteLanguageInfo, - LANGUAGES, - Typescript, -} from "./constants/AutocompleteLanguageInfo.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, - rankSnippets, + rankAndOrderSnippets, removeRangeFromSnippets, type AutocompleteSnippet, } from "./context/ranking/index.js"; import { HelperVars } from "./HelperVars.js"; -export function languageForFilepath( - filepath: string, -): AutocompleteLanguageInfo { - return LANGUAGES[filepath.split(".").slice(-1)[0]] || Typescript; -} - -export async function constructAutocompletePrompt( - helper: HelperVars, - extraSnippets: AutocompleteSnippet[], - contextRetrievalService: ContextRetrievalService, -): Promise<{ - prefix: string; - suffix: string; - useFim: boolean; - completeMultiline: boolean; - snippets: AutocompleteSnippet[]; -}> { +function prunePrefixSuffix(helper: HelperVars) { // Construct basic prefix const maxPrefixTokens = helper.options.maxPromptTokens * helper.options.prefixPercentage; @@ -56,46 +36,78 @@ export async function constructAutocompletePrompt( helper.modelName, ); + return { + prunedPrefix, + prunedSuffix, + }; +} + +function filterSnippetsAlreadyInCaretWindow( + snippets: AutocompleteSnippet[], + caretWindow: string, +): AutocompleteSnippet[] { + return snippets + .map((snippet) => ({ ...snippet })) + .filter( + (s) => + s.contents.trim() !== "" && !caretWindow.includes(s.contents.trim()), + ); +} + +function getRangeOfPrefixAndSuffixWithBuffer( + prefix: string, + suffix: string, + caretPos: Position, +): Range { + // Remove prefix range from snippets + const prefixLines = prefix.split("\n").length; + const suffixLines = suffix.split("\n").length; + const buffer = 8; + const prefixSuffixRangeWithBuffer = { + start: { + line: caretPos.line - prefixLines - buffer, + character: 0, + }, + end: { + line: caretPos.line + suffixLines + buffer, + character: 0, + }, + }; + + return prefixSuffixRangeWithBuffer; +} + +export async function constructAutocompletePrompt( + helper: HelperVars, + extraSnippets: AutocompleteSnippet[], + contextRetrievalService: ContextRetrievalService, +): Promise<{ + prefix: string; + suffix: string; + useFim: boolean; + completeMultiline: boolean; + snippets: AutocompleteSnippet[]; +}> { + // Prune prefix/suffix based on token budgets + const { prunedPrefix, prunedSuffix } = prunePrefixSuffix(helper); + let snippets = await contextRetrievalService.retrieve( prunedPrefix, helper, extraSnippets, ); - // Filter out empty snippets and ones that are already in the prefix/suffix - snippets = snippets - .map((snippet) => ({ ...snippet })) - .filter( - (s) => - s.contents.trim() !== "" && - !(prunedPrefix + prunedSuffix).includes(s.contents.trim()), - ); + snippets = filterSnippetsAlreadyInCaretWindow( + snippets, + prunedPrefix + prunedSuffix, + ); - // Rank / order the snippets - const scoredSnippets = rankSnippets(snippets, helper); + const scoredSnippets = rankAndOrderSnippets(snippets, helper); - // Fill maxSnippetTokens with snippets - const maxSnippetTokens = - helper.options.maxPromptTokens * helper.options.maxSnippetPercentage; - - // Remove prefix range from snippets - const prefixLines = prunedPrefix.split("\n").length; - const suffixLines = prunedSuffix.split("\n").length; - const buffer = 8; - const prefixSuffixRangeWithBuffer = { - start: { - line: helper.pos.line - prefixLines - buffer, - character: 0, - }, - end: { - line: helper.pos.line + suffixLines + buffer, - character: 0, - }, - }; let finalSnippets = removeRangeFromSnippets( scoredSnippets, helper.filepath.split("://").slice(-1)[0], - prefixSuffixRangeWithBuffer, + getRangeOfPrefixAndSuffixWithBuffer(prunedPrefix, prunedSuffix, helper.pos), ); // Filter snippets for those with best scores (must be above threshold) @@ -103,9 +115,10 @@ export async function constructAutocompletePrompt( (snippet) => snippet.score >= helper.options.recentlyEditedSimilarityThreshold, ); + finalSnippets = fillPromptWithSnippets( scoredSnippets, - maxSnippetTokens, + helper.maxSnippetTokens, helper.modelName, ); diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index 119056ca8..58e97cc04 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -42,7 +42,7 @@ export function jaccardSimilarity(a: string, b: string): number { /** * Rank code snippets to be used in tab-autocomplete prompt. Returns a sorted version of the snippet array. */ -export function rankSnippets( +export function rankAndOrderSnippets( ranges: AutocompleteSnippet[], helper: HelperVars, ): Required[] { diff --git a/core/autocomplete/templating/constructPrefixSuffix.ts b/core/autocomplete/templating/constructPrefixSuffix.ts index cead471c3..9bbffa181 100644 --- a/core/autocomplete/templating/constructPrefixSuffix.ts +++ b/core/autocomplete/templating/constructPrefixSuffix.ts @@ -1,6 +1,7 @@ import { IDE } from "../.."; import { getRangeInString } from "../../util/ranges"; -import { languageForFilepath } from "../constructPrompt"; +import { languageForFilepath } from "../constants/AutocompleteLanguageInfo"; + import { AutocompleteInput } from "../types"; /** diff --git a/core/commands/slash/share.ts b/core/commands/slash/share.ts index a615ec70d..a43b694da 100644 --- a/core/commands/slash/share.ts +++ b/core/commands/slash/share.ts @@ -1,7 +1,7 @@ import * as fs from "node:fs"; import { homedir } from "node:os"; import path from "path"; -import { languageForFilepath } from "../../autocomplete/constructPrompt.js"; +import { languageForFilepath } from "../../autocomplete/constants/AutocompleteLanguageInfo.js"; import { SlashCommand } from "../../index.js"; import { stripImages } from "../../llm/images.js"; diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 4a99dec8c..7144ba4d6 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -12,7 +12,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { slidingWindowPrefixPercentage: 0.75, slidingWindowSize: 500, maxSnippetPercentage: 0.6, - recentlyEditedSimilarityThreshold: 0.3, + recentlyEditedSimilarityThreshold: 0.0, // Effectively no threshold. useCache: true, onlyMyCode: true, useOtherFiles: true, diff --git a/extensions/vscode/src/util/expandSnippet.ts b/extensions/vscode/src/util/expandSnippet.ts index cd83691f7..10d1cda5b 100644 --- a/extensions/vscode/src/util/expandSnippet.ts +++ b/extensions/vscode/src/util/expandSnippet.ts @@ -1,5 +1,5 @@ import { Chunk, IDE } from "core"; -import { languageForFilepath } from "core/autocomplete/constructPrompt"; +import { languageForFilepath } from "core/autocomplete/constants/AutocompleteLanguageInfo"; import { DEFAULT_IGNORE_DIRS } from "core/indexing/ignore"; import { deduplicateArray } from "core/util"; import { getParserForFile } from "core/util/treeSitter"; From 3e1eca6c885f744c28c5f070512f784ca5f01f2d Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 16:17:25 -0700 Subject: [PATCH 21/43] refactor multi-line decision --- core/autocomplete/CompletionProvider.ts | 12 ++- .../classification/shouldCompleteMultiline.ts | 77 ++++++------------- core/autocomplete/constructPrompt.ts | 8 +- core/autocomplete/context/ranking/index.ts | 3 +- core/autocomplete/templating/index.ts | 12 +-- 5 files changed, 35 insertions(+), 77 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 50629e30e..ab8df6629 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -173,12 +173,11 @@ export class CompletionProvider { // or they might separately track recently edited ranges) const extraSnippets = await this._getExtraSnippets(helper); - let { prefix, suffix, completeMultiline, snippets } = - await constructAutocompletePrompt( - helper, - extraSnippets, - this.contextRetrievalService, - ); + let { prefix, suffix, snippets } = await constructAutocompletePrompt( + helper, + extraSnippets, + this.contextRetrievalService, + ); // If prefix is manually passed if (helper.input.manuallyPassPrefix) { @@ -191,7 +190,6 @@ export class CompletionProvider { suffix, snippets, await this.ide.getWorkspaceDirs(), - completeMultiline, helper, ); diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts index d8df8aeb0..1c999fe01 100644 --- a/core/autocomplete/classification/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -1,17 +1,33 @@ -import { TabAutocompleteOptions } from "@continuedev/config-types"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { HelperVars } from "../HelperVars"; -import { AutocompleteInput } from "../types"; - -const BLOCK_TYPES = ["body", "statement_block"]; function isMidlineCompletion(prefix: string, suffix: string): boolean { return !suffix.startsWith("\n"); } -export async function shouldCompleteMultiline( +function shouldCompleteMultilineBasedOnLanguage( + language: AutocompleteLanguageInfo, + prefix: string, + suffix: string, +) { + let langMultilineDecision = language.useMultiline?.({ prefix, suffix }); + return langMultilineDecision; +} + +export function decideMultilineEarly( helper: HelperVars, -): Promise { + prefix: string, + suffix: string, +) { + switch (helper.options.multilineCompletions) { + case "always": + return true; + case "never": + return false; + default: + break; + } + // Don't complete multi-line if you are mid-line if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) { return false; @@ -28,56 +44,11 @@ export async function shouldCompleteMultiline( return false; } - return true; -} - -function shouldCompleteMultilineBasedOnLanguage( - language: AutocompleteLanguageInfo, - prefix: string, - suffix: string, -) { - let langMultilineDecision = language.useMultiline?.({ prefix, suffix }); - return langMultilineDecision; -} - -function shouldCompleteMultilineBasedOnSelectedCompletion( - selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"], - multilineCompletions: TabAutocompleteOptions["multilineCompletions"], - completeMultiline: boolean, -) { - return ( - !selectedCompletionInfo && // Only ever single-line if using intellisense selected value - multilineCompletions !== "never" && - (multilineCompletions === "always" || completeMultiline) - ); -} - -export function decideMultilineEarly({ - language, - prefix, - suffix, - selectedCompletionInfo, - multilineCompletions, - completeMultiline, -}: { - language: AutocompleteLanguageInfo; - prefix: string; - suffix: string; - selectedCompletionInfo: AutocompleteInput["selectedCompletionInfo"]; - multilineCompletions: TabAutocompleteOptions["multilineCompletions"]; - completeMultiline: boolean; -}) { - if (shouldCompleteMultilineBasedOnLanguage(language, prefix, suffix)) { + if (shouldCompleteMultilineBasedOnLanguage(helper.lang, prefix, suffix)) { return true; } - if ( - shouldCompleteMultilineBasedOnSelectedCompletion( - selectedCompletionInfo, - multilineCompletions, - completeMultiline, - ) - ) { + if (helper.input.selectedCompletionInfo) { return true; } diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 7c7d898e6..62c28543e 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -4,7 +4,6 @@ import { pruneLinesFromBottom, pruneLinesFromTop, } from "../llm/countTokens.js"; -import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, @@ -84,8 +83,6 @@ export async function constructAutocompletePrompt( ): Promise<{ prefix: string; suffix: string; - useFim: boolean; - completeMultiline: boolean; snippets: AutocompleteSnippet[]; }> { // Prune prefix/suffix based on token budgets @@ -104,13 +101,14 @@ export async function constructAutocompletePrompt( const scoredSnippets = rankAndOrderSnippets(snippets, helper); + // This might be redundant with filterSnippetsAlreadyInCaretWindow let finalSnippets = removeRangeFromSnippets( scoredSnippets, helper.filepath.split("://").slice(-1)[0], getRangeOfPrefixAndSuffixWithBuffer(prunedPrefix, prunedSuffix, helper.pos), ); - // Filter snippets for those with best scores (must be above threshold) + // Filter snippets below similarity threshold finalSnippets = finalSnippets.filter( (snippet) => snippet.score >= helper.options.recentlyEditedSimilarityThreshold, @@ -127,8 +125,6 @@ export async function constructAutocompletePrompt( return { prefix: prunedPrefix, suffix: prunedSuffix, - useFim: true, - completeMultiline: await shouldCompleteMultiline(helper), snippets, }; } diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index 58e97cc04..aba29d7aa 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -130,7 +130,8 @@ function mergeOverlappingRangeContents( } /** - * Fill the allowed space with snippets + * Fill the allowed space with snippets. + * It is assumed that the snippets are sorted by score. */ export function fillPromptWithSnippets( snippets: Required[], diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index ad9dc7391..dea0f5885 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,6 +1,6 @@ import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; -import { decideMultilineEarly } from "../classification/shouldCompleteMultiline"; +import { decideMultilineEarly as shouldCompleteMultiline } from "../classification/shouldCompleteMultiline"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { AutocompleteSnippet } from "../context/ranking"; import { HelperVars } from "../HelperVars"; @@ -65,7 +65,6 @@ export function renderPrompt( suffix: string, snippets: AutocompleteSnippet[], workspaceDirs: string[], - completeMultiline: boolean, helper: HelperVars, ): [string, Partial | undefined, boolean] { let { @@ -115,14 +114,7 @@ export function renderPrompt( const multiline = !helper.options.transform || - decideMultilineEarly({ - multilineCompletions: helper.options.multilineCompletions, - language: helper.lang, - selectedCompletionInfo: helper.input.selectedCompletionInfo, - prefix, - suffix, - completeMultiline, - }); + shouldCompleteMultiline(helper, prefix, suffix); const stopTokens = getStopTokens( completionOptions, From 176c50210dbf4ee417fd02d1e42abfbf4b64b781 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 16:26:51 -0700 Subject: [PATCH 22/43] more refactoring --- core/autocomplete/CompletionProvider.ts | 10 ++-- core/autocomplete/README.md | 29 ----------- .../classification/shouldCompleteMultiline.ts | 13 ++--- core/autocomplete/constructPrompt.ts | 2 +- .../context/ContextRetrievalService.ts | 15 +++++- core/autocomplete/context/ranking/index.ts | 2 +- core/autocomplete/filtering/test/util.ts | 2 +- .../generation/CompletionStreamer.ts | 2 +- core/autocomplete/prefiltering/index.ts | 2 +- core/autocomplete/recentlyEdited.ts | 18 ------- .../templating/constructPrefixSuffix.ts | 2 +- core/autocomplete/templating/index.ts | 5 +- .../test/NEGATIVE_CASES_STARCODER.tsx | 51 ------------------- core/autocomplete/test/util.ts | 2 +- .../{ => util}/AutocompleteDebouncer.ts | 0 .../{ => util}/AutocompleteLoggingService.ts | 6 +-- .../{ => util}/AutocompleteLruCache.ts | 9 ++-- core/autocomplete/{ => util}/HelperVars.ts | 8 +-- core/autocomplete/{ => util}/types.ts | 11 ++-- core/protocol/core.ts | 2 +- 20 files changed, 57 insertions(+), 134 deletions(-) delete mode 100644 core/autocomplete/README.md delete mode 100644 core/autocomplete/recentlyEdited.ts delete mode 100644 core/autocomplete/test/NEGATIVE_CASES_STARCODER.tsx rename core/autocomplete/{ => util}/AutocompleteDebouncer.ts (100%) rename core/autocomplete/{ => util}/AutocompleteLoggingService.ts (96%) rename core/autocomplete/{ => util}/AutocompleteLruCache.ts (92%) rename core/autocomplete/{ => util}/HelperVars.ts (92%) rename core/autocomplete/{ => util}/types.ts (76%) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index ab8df6629..31f9d4aa6 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -8,16 +8,16 @@ import { postprocessCompletion } from "./postprocessing/index.js"; // @prettier-ignore import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import OpenAI from "../llm/llms/OpenAI.js"; -import { AutocompleteDebouncer } from "./AutocompleteDebouncer.js"; -import { AutocompleteLoggingService } from "./AutocompleteLoggingService.js"; -import AutocompleteLruCache from "./AutocompleteLruCache.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; -import { HelperVars } from "./HelperVars.js"; import { shouldPrefilter } from "./prefiltering/index.js"; import { renderPrompt } from "./templating/index.js"; -import { AutocompleteInput, AutocompleteOutcome } from "./types.js"; +import { AutocompleteDebouncer } from "./util/AutocompleteDebouncer.js"; +import { AutocompleteLoggingService } from "./util/AutocompleteLoggingService.js"; +import AutocompleteLruCache from "./util/AutocompleteLruCache.js"; +import { HelperVars } from "./util/HelperVars.js"; +import { AutocompleteInput, AutocompleteOutcome } from "./util/types.js"; const autocompleteCache = AutocompleteLruCache.get(); diff --git a/core/autocomplete/README.md b/core/autocomplete/README.md deleted file mode 100644 index 8b860a3cc..000000000 --- a/core/autocomplete/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# Autocomplete - -The autocomplete pipeline: - -## 1. Triggering - -### Debouncing - -## 2. Context gathering - -## 3. Prompt construction - -This is fairly trivial, we just use the correct template/endpoint for the model. Any templates are defined in [`templates.ts`](./templates.ts). - -## 4. Caching - -## 4. Generation - -### Reusing previous requests - -## 4. Classification - -Is it multi-line or single-line? - -## 4. Filtering - -## 5. Postprocessing - -## 6. Telemetry diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts index 1c999fe01..fb47cd467 100644 --- a/core/autocomplete/classification/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -1,5 +1,5 @@ import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; -import { HelperVars } from "../HelperVars"; +import { HelperVars } from "../util/HelperVars"; function isMidlineCompletion(prefix: string, suffix: string): boolean { return !suffix.startsWith("\n"); @@ -14,7 +14,7 @@ function shouldCompleteMultilineBasedOnLanguage( return langMultilineDecision; } -export function decideMultilineEarly( +export function shouldCompleteMultiline( helper: HelperVars, prefix: string, suffix: string, @@ -28,6 +28,11 @@ export function decideMultilineEarly( break; } + // Always single-line if an intellisense option is selected + if (helper.input.selectedCompletionInfo) { + return true; + } + // Don't complete multi-line if you are mid-line if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) { return false; @@ -48,9 +53,5 @@ export function decideMultilineEarly( return true; } - if (helper.input.selectedCompletionInfo) { - return true; - } - return false; } diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 62c28543e..08bde361c 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -11,7 +11,7 @@ import { removeRangeFromSnippets, type AutocompleteSnippet, } from "./context/ranking/index.js"; -import { HelperVars } from "./HelperVars.js"; +import { HelperVars } from "./util/HelperVars.js"; function prunePrefixSuffix(helper: HelperVars) { // Construct basic prefix diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index cdf5f2bcd..21e9eddf4 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -1,10 +1,21 @@ import { IDE } from "../.."; -import { HelperVars } from "../HelperVars"; -import { findMatchingRange } from "../recentlyEdited"; +import { HelperVars } from "../util/HelperVars"; +import { RecentlyEditedRange } from "../util/types"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; import { RootPathContextService } from "./RootPathContextService"; +export function findMatchingRange( + recentlyEditedRanges: RecentlyEditedRange[], + linePrefix: string, +): RecentlyEditedRange | undefined { + return recentlyEditedRanges.find((recentlyEditedRange) => { + return recentlyEditedRange.lines.some((line) => + line.startsWith(linePrefix), + ); + }); +} + export class ContextRetrievalService { private importDefinitionsService: ImportDefinitionsService; private rootPathContextService: RootPathContextService; diff --git a/core/autocomplete/context/ranking/index.ts b/core/autocomplete/context/ranking/index.ts index aba29d7aa..e761d994e 100644 --- a/core/autocomplete/context/ranking/index.ts +++ b/core/autocomplete/context/ranking/index.ts @@ -1,7 +1,7 @@ import { RangeInFileWithContents } from "../../../commands/util.js"; import { Range } from "../../../index.js"; import { countTokens } from "../../../llm/countTokens.js"; -import { HelperVars } from "../../HelperVars.js"; +import { HelperVars } from "../../util/HelperVars.js"; export type AutocompleteSnippet = RangeInFileWithContents & { score?: number; diff --git a/core/autocomplete/filtering/test/util.ts b/core/autocomplete/filtering/test/util.ts index f8564e258..5a9b61a72 100644 --- a/core/autocomplete/filtering/test/util.ts +++ b/core/autocomplete/filtering/test/util.ts @@ -3,7 +3,7 @@ import path from "node:path"; import Mock from "../../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../../test/util/fixtures"; import { CompletionProvider } from "../../CompletionProvider"; -import { AutocompleteInput } from "../../types"; +import { AutocompleteInput } from "../../util/types"; const FIM_DELIMITER = "<|fim|>"; diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts index a723a3c1b..11b0755d8 100644 --- a/core/autocomplete/generation/CompletionStreamer.ts +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -1,6 +1,6 @@ import { CompletionOptions, ILLM } from "../.."; import { StreamTransformPipeline } from "../filtering/streamTransforms/StreamTransformPipeline"; -import { HelperVars } from "../HelperVars"; +import { HelperVars } from "../util/HelperVars"; import { GeneratorReuseManager } from "./GeneratorReuseManager"; export class CompletionStreamer { diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts index 45b521511..c844696ac 100644 --- a/core/autocomplete/prefiltering/index.ts +++ b/core/autocomplete/prefiltering/index.ts @@ -2,7 +2,7 @@ import path from "node:path"; import { IDE } from "../.."; import { getBasename } from "../../util"; import { getConfigJsonPath } from "../../util/paths"; -import { HelperVars } from "../HelperVars"; +import { HelperVars } from "../util/HelperVars"; async function isDisabledForFile( currentFilepath: string, diff --git a/core/autocomplete/recentlyEdited.ts b/core/autocomplete/recentlyEdited.ts deleted file mode 100644 index d0e7817ed..000000000 --- a/core/autocomplete/recentlyEdited.ts +++ /dev/null @@ -1,18 +0,0 @@ -import { RangeInFile } from "../index.js"; - -export type RecentlyEditedRange = RangeInFile & { - timestamp: number; - lines: string[]; - symbols: Set; -}; - -export function findMatchingRange( - recentlyEditedRanges: RecentlyEditedRange[], - linePrefix: string, -): RecentlyEditedRange | undefined { - return recentlyEditedRanges.find((recentlyEditedRange) => { - return recentlyEditedRange.lines.some((line) => - line.startsWith(linePrefix), - ); - }); -} diff --git a/core/autocomplete/templating/constructPrefixSuffix.ts b/core/autocomplete/templating/constructPrefixSuffix.ts index 9bbffa181..d4024bf06 100644 --- a/core/autocomplete/templating/constructPrefixSuffix.ts +++ b/core/autocomplete/templating/constructPrefixSuffix.ts @@ -2,7 +2,7 @@ import { IDE } from "../.."; import { getRangeInString } from "../../util/ranges"; import { languageForFilepath } from "../constants/AutocompleteLanguageInfo"; -import { AutocompleteInput } from "../types"; +import { AutocompleteInput } from "../util/types"; /** * We have to handle a few edge cases in getting the entire prefix/suffix for the current file. diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index dea0f5885..a8723cb6c 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,9 +1,9 @@ import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; -import { decideMultilineEarly as shouldCompleteMultiline } from "../classification/shouldCompleteMultiline"; +import { shouldCompleteMultiline } from "../classification/shouldCompleteMultiline"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { AutocompleteSnippet } from "../context/ranking"; -import { HelperVars } from "../HelperVars"; +import { HelperVars } from "../util/HelperVars"; import { getTemplateForModel } from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; @@ -60,6 +60,7 @@ function renderStringTemplate( }); return prompt; } + export function renderPrompt( prefix: string, suffix: string, diff --git a/core/autocomplete/test/NEGATIVE_CASES_STARCODER.tsx b/core/autocomplete/test/NEGATIVE_CASES_STARCODER.tsx deleted file mode 100644 index 269d25f0f..000000000 --- a/core/autocomplete/test/NEGATIVE_CASES_STARCODER.tsx +++ /dev/null @@ -1,51 +0,0 @@ -##### Prompt ##### -class Calculator { - constructor() { - this.result = 0; - } - - add(number) { - this.result += number; - return this; - } - - subtract(number) { - this.result -= number; - return this; - } - - multiply(number) { - this.result *= number; - return this; - } - - divide(number) { - if (number === 0) { - throw new Error("Cannot divide by zero"); - } - - - - this.result /= number; - return this; - } - - getResult() { - return this.result; - } - - reset() { - this.result = 0; - return this; - } -} -========================================================================== -========================================================================== -Completion: - - this.result /= number; - return this; - } -} - -module.exports = Calculator; \ No newline at end of file diff --git a/core/autocomplete/test/util.ts b/core/autocomplete/test/util.ts index 85dbc60b3..bfcf31885 100644 --- a/core/autocomplete/test/util.ts +++ b/core/autocomplete/test/util.ts @@ -3,7 +3,7 @@ import path from "node:path"; import Mock from "../../llm/llms/Mock"; import { testConfigHandler, testIde } from "../../test/util/fixtures"; import { CompletionProvider } from "../CompletionProvider"; -import { AutocompleteInput } from "../types"; +import { AutocompleteInput } from "../util/types"; const FIM_DELIMITER = "<|fim|>"; diff --git a/core/autocomplete/AutocompleteDebouncer.ts b/core/autocomplete/util/AutocompleteDebouncer.ts similarity index 100% rename from core/autocomplete/AutocompleteDebouncer.ts rename to core/autocomplete/util/AutocompleteDebouncer.ts diff --git a/core/autocomplete/AutocompleteLoggingService.ts b/core/autocomplete/util/AutocompleteLoggingService.ts similarity index 96% rename from core/autocomplete/AutocompleteLoggingService.ts rename to core/autocomplete/util/AutocompleteLoggingService.ts index 6771b1dd6..7fd3d24cb 100644 --- a/core/autocomplete/AutocompleteLoggingService.ts +++ b/core/autocomplete/util/AutocompleteLoggingService.ts @@ -1,6 +1,6 @@ -import { logDevData } from "../util/devdata"; -import { COUNT_COMPLETION_REJECTED_AFTER } from "../util/parameters"; -import { Telemetry } from "../util/posthog"; +import { logDevData } from "../../util/devdata"; +import { COUNT_COMPLETION_REJECTED_AFTER } from "../../util/parameters"; +import { Telemetry } from "../../util/posthog"; import { AutocompleteOutcome } from "./types"; export class AutocompleteLoggingService { diff --git a/core/autocomplete/AutocompleteLruCache.ts b/core/autocomplete/util/AutocompleteLruCache.ts similarity index 92% rename from core/autocomplete/AutocompleteLruCache.ts rename to core/autocomplete/util/AutocompleteLruCache.ts index c04770a4c..ec9478c8a 100644 --- a/core/autocomplete/AutocompleteLruCache.ts +++ b/core/autocomplete/util/AutocompleteLruCache.ts @@ -1,14 +1,17 @@ import { Mutex } from "async-mutex"; import { open } from "sqlite"; import sqlite3 from "sqlite3"; -import { DatabaseConnection, truncateSqliteLikePattern } from "../indexing/refreshIndex.js"; -import { getTabAutocompleteCacheSqlitePath } from "../util/paths.js"; +import { + DatabaseConnection, + truncateSqliteLikePattern, +} from "../../indexing/refreshIndex.js"; +import { getTabAutocompleteCacheSqlitePath } from "../../util/paths.js"; export class AutocompleteLruCache { private static capacity = 1000; private mutex = new Mutex(); - constructor(private db: DatabaseConnection) { } + constructor(private db: DatabaseConnection) {} static async get(): Promise { const db = await open({ diff --git a/core/autocomplete/HelperVars.ts b/core/autocomplete/util/HelperVars.ts similarity index 92% rename from core/autocomplete/HelperVars.ts rename to core/autocomplete/util/HelperVars.ts index e5e3af61c..57a81e668 100644 --- a/core/autocomplete/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -1,11 +1,11 @@ -import { IDE, TabAutocompleteOptions } from ".."; +import { IDE, TabAutocompleteOptions } from "../.."; import { AutocompleteLanguageInfo, languageForFilepath, -} from "./constants/AutocompleteLanguageInfo"; -import { constructInitialPrefixSuffix } from "./templating/constructPrefixSuffix"; +} from "../constants/AutocompleteLanguageInfo"; +import { constructInitialPrefixSuffix } from "../templating/constructPrefixSuffix"; +import { AstPath, getAst, getTreePathAtCursor } from "./ast"; import { AutocompleteInput } from "./types"; -import { AstPath, getAst, getTreePathAtCursor } from "./util/ast"; /** * A collection of variables that are often accessed throughout the autocomplete pipeline diff --git a/core/autocomplete/types.ts b/core/autocomplete/util/types.ts similarity index 76% rename from core/autocomplete/types.ts rename to core/autocomplete/util/types.ts index 745ea563b..44ee9fab1 100644 --- a/core/autocomplete/types.ts +++ b/core/autocomplete/util/types.ts @@ -1,6 +1,11 @@ -import { Position, Range, TabAutocompleteOptions } from ".."; -import { RangeInFileWithContents } from "../commands/util"; -import { RecentlyEditedRange } from "./recentlyEdited"; +import { Position, Range, RangeInFile, TabAutocompleteOptions } from "../.."; +import { RangeInFileWithContents } from "../../commands/util"; + +export type RecentlyEditedRange = RangeInFile & { + timestamp: number; + lines: string[]; + symbols: Set; +}; export interface AutocompleteInput { completionId: string; diff --git a/core/protocol/core.ts b/core/protocol/core.ts index 090ee2c5a..abe6c8fe1 100644 --- a/core/protocol/core.ts +++ b/core/protocol/core.ts @@ -15,7 +15,7 @@ import type { SessionInfo, SiteIndexingConfig, } from "../"; -import { AutocompleteInput } from "../autocomplete/types"; +import { AutocompleteInput } from "../autocomplete/util/types"; import { ProfileDescription } from "../config/ConfigHandler"; export type ProtocolGeneratorType = AsyncGenerator<{ From bf13f2004283603b71b22061b7366cf3fc1a62c1 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 16:27:44 -0700 Subject: [PATCH 23/43] fix type errs --- extensions/vscode/src/autocomplete/completionProvider.ts | 2 +- extensions/vscode/src/autocomplete/recentlyEdited.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index d9244ebfc..b1af40435 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -3,7 +3,7 @@ import { CompletionProvider } from "core/autocomplete/completionProvider"; import { type AutocompleteInput, type AutocompleteOutcome, -} from "core/autocomplete/types"; +} from "core/autocomplete/util/types"; import { ConfigHandler } from "core/config/ConfigHandler"; import { v4 as uuidv4 } from "uuid"; import * as vscode from "vscode"; diff --git a/extensions/vscode/src/autocomplete/recentlyEdited.ts b/extensions/vscode/src/autocomplete/recentlyEdited.ts index c32739b1c..0b206eab2 100644 --- a/extensions/vscode/src/autocomplete/recentlyEdited.ts +++ b/extensions/vscode/src/autocomplete/recentlyEdited.ts @@ -1,5 +1,5 @@ import { getSymbolsForSnippet } from "core/autocomplete/context/ranking"; -import { RecentlyEditedRange } from "core/autocomplete/recentlyEdited"; +import { RecentlyEditedRange } from "core/autocomplete/util/types"; import { RangeInFileWithContents } from "core/commands/util"; import * as vscode from "vscode"; From ef4b32975d052f5e768613c185c8a486e8fc4a75 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 16:41:03 -0700 Subject: [PATCH 24/43] refactor context retrieval service --- core/autocomplete/constructPrompt.ts | 2 +- .../context/ContextRetrievalService.ts | 150 +++++++++++------- 2 files changed, 90 insertions(+), 62 deletions(-) diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index 08bde361c..fdf16abad 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -88,7 +88,7 @@ export async function constructAutocompletePrompt( // Prune prefix/suffix based on token budgets const { prunedPrefix, prunedSuffix } = prunePrefixSuffix(helper); - let snippets = await contextRetrievalService.retrieve( + let snippets = await contextRetrievalService.retrieveCandidateSnippets( prunedPrefix, helper, extraSnippets, diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index 21e9eddf4..b8484421d 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -5,17 +5,6 @@ import { ImportDefinitionsService } from "./ImportDefinitionsService"; import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; import { RootPathContextService } from "./RootPathContextService"; -export function findMatchingRange( - recentlyEditedRanges: RecentlyEditedRange[], - linePrefix: string, -): RecentlyEditedRange | undefined { - return recentlyEditedRanges.find((recentlyEditedRange) => { - return recentlyEditedRange.lines.some((line) => - line.startsWith(linePrefix), - ); - }); -} - export class ContextRetrievalService { private importDefinitionsService: ImportDefinitionsService; private rootPathContextService: RootPathContextService; @@ -28,69 +17,108 @@ export class ContextRetrievalService { ); } - public async retrieve( + private getSnippetsFromRecentlyEditedRanges( + prunedPrefix: string, + helper: HelperVars, + ): AutocompleteSnippet[] { + if (helper.options.useRecentlyEdited === false) { + return []; + } + + const currentLinePrefix = prunedPrefix.trim().split("\n").slice(-1)[0]; + if ( + currentLinePrefix?.length > helper.options.recentLinePrefixMatchMinLength + ) { + const matchingRange = this.findMatchingRange( + helper.input.recentlyEditedRanges, + currentLinePrefix, + ); + + if (matchingRange) { + return [ + { + ...matchingRange, + contents: matchingRange.lines.join("\n"), + score: 0.8, + }, + ]; + } + } + + return []; + } + + private async getSnippetsFromImportDefinitions( + helper: HelperVars, + ): Promise { + if (helper.options.useImports === false) { + return []; + } + + const importSnippets = []; + const fileInfo = this.importDefinitionsService.get(helper.filepath); + if (fileInfo) { + const { imports } = fileInfo; + // Look for imports of any symbols around the current range + const textAroundCursor = + helper.fullPrefix.split("\n").slice(-5).join("\n") + + helper.fullSuffix.split("\n").slice(0, 3).join("\n"); + const symbols = Array.from(getSymbolsForSnippet(textAroundCursor)).filter( + (symbol) => !helper.lang.topLevelKeywords.includes(symbol), + ); + for (const symbol of symbols) { + const rifs = imports[symbol]; + if (Array.isArray(rifs)) { + importSnippets.push(...rifs); + } + } + } + return importSnippets; + } + + public async retrieveCandidateSnippets( prunedPrefix: string, helper: HelperVars, extraSnippets: AutocompleteSnippet[], ) { - // Find external snippets + if (helper.options.useOtherFiles === false) { + return []; + } + let snippets: AutocompleteSnippet[] = []; - if (helper.options.useOtherFiles) { - snippets.push(...extraSnippets); + // Snippets injected by the IDE for IDE-specific reasons + snippets.push(...extraSnippets); - if (helper.options.useRecentlyEdited) { - const currentLinePrefix = prunedPrefix.trim().split("\n").slice(-1)[0]; - if ( - currentLinePrefix?.length > - helper.options.recentLinePrefixMatchMinLength - ) { - const matchingRange = findMatchingRange( - helper.input.recentlyEditedRanges, - currentLinePrefix, - ); - if (matchingRange) { - snippets.push({ - ...matchingRange, - contents: matchingRange.lines.join("\n"), - score: 0.8, - }); - } - } - } + // If a recently edited range has a line that is a perfect match with the start of the current line + snippets.push( + ...this.getSnippetsFromRecentlyEditedRanges(prunedPrefix, helper), + ); - // Use imports - if (helper.options.useImports) { - const importSnippets = []; - const fileInfo = this.importDefinitionsService.get(helper.filepath); - if (fileInfo) { - const { imports } = fileInfo; - // Look for imports of any symbols around the current range - const textAroundCursor = - helper.fullPrefix.split("\n").slice(-5).join("\n") + - helper.fullSuffix.split("\n").slice(0, 3).join("\n"); - const symbols = Array.from( - getSymbolsForSnippet(textAroundCursor), - ).filter((symbol) => !helper.lang.topLevelKeywords.includes(symbol)); - for (const symbol of symbols) { - const rifs = imports[symbol]; - if (Array.isArray(rifs)) { - importSnippets.push(...rifs); - } - } - } - snippets.push(...importSnippets); - } + // Import definitions of any symbols in near range of the caret + snippets.push(...(await this.getSnippetsFromImportDefinitions(helper))); - if (helper.options.useRootPathContext && helper.treePath) { - const ctx = await this.rootPathContextService.getContextForPath( + // Root path context https://blog.continue.dev/root-path-context-the-secret-ingredient-in-continues-autocomplete-prompt/ + if (helper.options.useRootPathContext && helper.treePath) { + snippets.push( + ...(await this.rootPathContextService.getContextForPath( helper.filepath, helper.treePath, - ); - snippets.push(...ctx); - } + )), + ); } return snippets; } + + findMatchingRange( + recentlyEditedRanges: RecentlyEditedRange[], + linePrefix: string, + ): RecentlyEditedRange | undefined { + return recentlyEditedRanges.find((recentlyEditedRange) => { + return recentlyEditedRange.lines.some((line) => + line.startsWith(linePrefix), + ); + }); + } } From 263dbaef8c38c6a480a141923c490384699e8d46 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 18:05:32 -0700 Subject: [PATCH 25/43] more refactoring --- core/autocomplete/CompletionProvider.ts | 39 +++++----- .../classification/shouldCompleteMultiline.ts | 14 ++-- core/autocomplete/constructPrompt.ts | 59 ++------------- .../context/ContextRetrievalService.ts | 73 +++++++++---------- .../templating/AutocompleteTemplate.ts | 2 +- core/autocomplete/templating/index.ts | 50 ++++++++----- core/autocomplete/util/HelperVars.ts | 40 ++++++++++ 7 files changed, 144 insertions(+), 133 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 31f9d4aa6..2c7950288 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -8,6 +8,7 @@ import { postprocessCompletion } from "./postprocessing/index.js"; // @prettier-ignore import { TRIAL_FIM_MODEL } from "../config/onboarding.js"; import OpenAI from "../llm/llms/OpenAI.js"; +import { shouldCompleteMultiline } from "./classification/shouldCompleteMultiline.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { BracketMatchingService } from "./filtering/BracketMatchingService.js"; import { CompletionStreamer } from "./generation/CompletionStreamer.js"; @@ -173,32 +174,25 @@ export class CompletionProvider { // or they might separately track recently edited ranges) const extraSnippets = await this._getExtraSnippets(helper); - let { prefix, suffix, snippets } = await constructAutocompletePrompt( + let snippets = await constructAutocompletePrompt( helper, extraSnippets, this.contextRetrievalService, ); - // If prefix is manually passed - if (helper.input.manuallyPassPrefix) { - prefix = helper.input.manuallyPassPrefix; - suffix = ""; - } - - const [prompt, completionOptions, multiline] = renderPrompt( - prefix, - suffix, - snippets, - await this.ide.getWorkspaceDirs(), - helper, - ); + const { + prompt, + prefix: finalPrefix, + suffix: finalSuffix, + completionOptions, + } = renderPrompt(snippets, await this.ide.getWorkspaceDirs(), helper); // Completion let completion: string | undefined = ""; const cache = await autocompleteCache; const cachedCompletion = helper.options.useCache - ? await cache.get(prefix) + ? await cache.get(helper.prunedPrefix) : undefined; let cacheHit = false; if (cachedCompletion) { @@ -206,12 +200,15 @@ export class CompletionProvider { cacheHit = true; completion = cachedCompletion; } else { + const multiline = + !helper.options.transform || shouldCompleteMultiline(helper); + const completionStream = this.completionStreamer.streamCompletionWithFilters( token, llm, - prefix, - suffix, + finalPrefix, + finalSuffix, prompt, multiline, completionOptions, @@ -230,8 +227,8 @@ export class CompletionProvider { const processedCompletion = helper.options.transform ? postprocessCompletion({ completion, - prefix, - suffix, + prefix: helper.prunedPrefix, + suffix: helper.prunedSuffix, llm, }) : completion; @@ -246,8 +243,8 @@ export class CompletionProvider { const outcome: AutocompleteOutcome = { time: Date.now() - startTime, completion, - prefix, - suffix, + prefix: finalPrefix, + suffix: finalSuffix, prompt, modelProvider: llm.providerName, modelName: llm.model, diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts index fb47cd467..16d2a6c47 100644 --- a/core/autocomplete/classification/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -14,11 +14,7 @@ function shouldCompleteMultilineBasedOnLanguage( return langMultilineDecision; } -export function shouldCompleteMultiline( - helper: HelperVars, - prefix: string, - suffix: string, -) { +export function shouldCompleteMultiline(helper: HelperVars) { switch (helper.options.multilineCompletions) { case "always": return true; @@ -49,7 +45,13 @@ export function shouldCompleteMultiline( return false; } - if (shouldCompleteMultilineBasedOnLanguage(helper.lang, prefix, suffix)) { + if ( + shouldCompleteMultilineBasedOnLanguage( + helper.lang, + helper.prunedPrefix, + helper.prunedSuffix, + ) + ) { return true; } diff --git a/core/autocomplete/constructPrompt.ts b/core/autocomplete/constructPrompt.ts index fdf16abad..2c5d43f42 100644 --- a/core/autocomplete/constructPrompt.ts +++ b/core/autocomplete/constructPrompt.ts @@ -1,9 +1,4 @@ import { Position, Range } from "../index.js"; -import { - countTokens, - pruneLinesFromBottom, - pruneLinesFromTop, -} from "../llm/countTokens.js"; import { ContextRetrievalService } from "./context/ContextRetrievalService.js"; import { fillPromptWithSnippets, @@ -13,34 +8,6 @@ import { } from "./context/ranking/index.js"; import { HelperVars } from "./util/HelperVars.js"; -function prunePrefixSuffix(helper: HelperVars) { - // Construct basic prefix - const maxPrefixTokens = - helper.options.maxPromptTokens * helper.options.prefixPercentage; - const prunedPrefix = pruneLinesFromTop( - helper.fullPrefix, - maxPrefixTokens, - helper.modelName, - ); - - // Construct suffix - const maxSuffixTokens = Math.min( - helper.options.maxPromptTokens - - countTokens(prunedPrefix, helper.modelName), - helper.options.maxSuffixPercentage * helper.options.maxPromptTokens, - ); - const prunedSuffix = pruneLinesFromBottom( - helper.fullSuffix, - maxSuffixTokens, - helper.modelName, - ); - - return { - prunedPrefix, - prunedSuffix, - }; -} - function filterSnippetsAlreadyInCaretWindow( snippets: AutocompleteSnippet[], caretWindow: string, @@ -80,23 +47,15 @@ export async function constructAutocompletePrompt( helper: HelperVars, extraSnippets: AutocompleteSnippet[], contextRetrievalService: ContextRetrievalService, -): Promise<{ - prefix: string; - suffix: string; - snippets: AutocompleteSnippet[]; -}> { - // Prune prefix/suffix based on token budgets - const { prunedPrefix, prunedSuffix } = prunePrefixSuffix(helper); - +): Promise { let snippets = await contextRetrievalService.retrieveCandidateSnippets( - prunedPrefix, helper, extraSnippets, ); snippets = filterSnippetsAlreadyInCaretWindow( snippets, - prunedPrefix + prunedSuffix, + helper.prunedCaretWindow, ); const scoredSnippets = rankAndOrderSnippets(snippets, helper); @@ -105,7 +64,11 @@ export async function constructAutocompletePrompt( let finalSnippets = removeRangeFromSnippets( scoredSnippets, helper.filepath.split("://").slice(-1)[0], - getRangeOfPrefixAndSuffixWithBuffer(prunedPrefix, prunedSuffix, helper.pos), + getRangeOfPrefixAndSuffixWithBuffer( + helper.prunedPrefix, + helper.prunedSuffix, + helper.pos, + ), ); // Filter snippets below similarity threshold @@ -120,11 +83,5 @@ export async function constructAutocompletePrompt( helper.modelName, ); - snippets = finalSnippets; - - return { - prefix: prunedPrefix, - suffix: prunedSuffix, - snippets, - }; + return finalSnippets; } diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index b8484421d..3c6ed3376 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -17,15 +17,49 @@ export class ContextRetrievalService { ); } + public async retrieveCandidateSnippets( + helper: HelperVars, + extraSnippets: AutocompleteSnippet[], + ) { + if (helper.options.useOtherFiles === false) { + return []; + } + + let snippets: AutocompleteSnippet[] = []; + + // Snippets injected by the IDE for IDE-specific reasons + snippets.push(...extraSnippets); + + // If a recently edited range has a line that is a perfect match with the start of the current line + snippets.push(...this.getSnippetsFromRecentlyEditedRanges(helper)); + + // Import definitions of any symbols in near range of the caret + snippets.push(...(await this.getSnippetsFromImportDefinitions(helper))); + + // Root path context https://blog.continue.dev/root-path-context-the-secret-ingredient-in-continues-autocomplete-prompt/ + if (helper.options.useRootPathContext && helper.treePath) { + snippets.push( + ...(await this.rootPathContextService.getContextForPath( + helper.filepath, + helper.treePath, + )), + ); + } + + return snippets; + } + private getSnippetsFromRecentlyEditedRanges( - prunedPrefix: string, helper: HelperVars, ): AutocompleteSnippet[] { if (helper.options.useRecentlyEdited === false) { return []; } - const currentLinePrefix = prunedPrefix.trim().split("\n").slice(-1)[0]; + const currentLinePrefix = helper.prunedPrefix + .trim() + .split("\n") + .slice(-1)[0]; if ( currentLinePrefix?.length > helper.options.recentLinePrefixMatchMinLength ) { @@ -76,41 +110,6 @@ export class ContextRetrievalService { return importSnippets; } - public async retrieveCandidateSnippets( - prunedPrefix: string, - helper: HelperVars, - extraSnippets: AutocompleteSnippet[], - ) { - if (helper.options.useOtherFiles === false) { - return []; - } - - let snippets: AutocompleteSnippet[] = []; - - // Snippets injected by the IDE for IDE-specific reasons - snippets.push(...extraSnippets); - - // If a recently edited range has a line that is a perfect match with the start of the current line - snippets.push( - ...this.getSnippetsFromRecentlyEditedRanges(prunedPrefix, helper), - ); - - // Import definitions of any symbols in near range of the caret - snippets.push(...(await this.getSnippetsFromImportDefinitions(helper))); - - // Root path context https://blog.continue.dev/root-path-context-the-secret-ingredient-in-continues-autocomplete-prompt/ - if (helper.options.useRootPathContext && helper.treePath) { - snippets.push( - ...(await this.rootPathContextService.getContextForPath( - helper.filepath, - helper.treePath, - )), - ); - } - - return snippets; - } - findMatchingRange( recentlyEditedRanges: RecentlyEditedRange[], linePrefix: string, diff --git a/core/autocomplete/templating/AutocompleteTemplate.ts b/core/autocomplete/templating/AutocompleteTemplate.ts index 034426f91..ae8cf1487 100644 --- a/core/autocomplete/templating/AutocompleteTemplate.ts +++ b/core/autocomplete/templating/AutocompleteTemplate.ts @@ -4,7 +4,7 @@ import { CompletionOptions } from "../../index.js"; import { getLastNPathParts, shortestRelativePaths } from "../../util/index.js"; import { AutocompleteSnippet } from "../context/ranking/index.js"; -interface AutocompleteTemplate { +export interface AutocompleteTemplate { compilePrefixSuffix?: ( prefix: string, suffix: string, diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index a8723cb6c..6ee99b862 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,10 +1,12 @@ import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; -import { shouldCompleteMultiline } from "../classification/shouldCompleteMultiline"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; import { AutocompleteSnippet } from "../context/ranking"; import { HelperVars } from "../util/HelperVars"; -import { getTemplateForModel } from "./AutocompleteTemplate"; +import { + AutocompleteTemplate, + getTemplateForModel, +} from "./AutocompleteTemplate"; import { getStopTokens } from "./getStopTokens"; export function formatExternalSnippet( @@ -61,24 +63,42 @@ function renderStringTemplate( return prompt; } +function getTemplate(helper: HelperVars): AutocompleteTemplate { + if (helper.options.template) { + return { + template: helper.options.template, + completionOptions: {}, + compilePrefixSuffix: undefined, + }; + } + return getTemplateForModel(helper.modelName); +} + export function renderPrompt( - prefix: string, - suffix: string, snippets: AutocompleteSnippet[], workspaceDirs: string[], helper: HelperVars, -): [string, Partial | undefined, boolean] { - let { - template, - completionOptions, - compilePrefixSuffix = undefined, - } = helper.options.template - ? { template: helper.options.template, completionOptions: {} } - : getTemplateForModel(helper.modelName); +): { + prompt: string; + prefix: string; + suffix: string; + completionOptions: Partial | undefined; +} { + // If prefix is manually passed + let prefix = helper.prunedPrefix; + let suffix = helper.prunedSuffix; + + if (helper.input.manuallyPassPrefix) { + prefix = helper.input.manuallyPassPrefix; + suffix = ""; + } let prompt: string; const reponame = getBasename(workspaceDirs[0] ?? "myproject"); + let { template, compilePrefixSuffix, completionOptions } = + getTemplate(helper); + // Some models have prompts that need two passes. This lets us pass the compiled prefix/suffix // into either the 2nd template to generate a raw string, or to pass prefix, suffix to a FIM endpoint if (compilePrefixSuffix) { @@ -113,10 +133,6 @@ export function renderPrompt( ); } - const multiline = - !helper.options.transform || - shouldCompleteMultiline(helper, prefix, suffix); - const stopTokens = getStopTokens( completionOptions, helper.lang, @@ -128,5 +144,5 @@ export function renderPrompt( stop: stopTokens, }; - return [prompt, completionOptions, multiline]; + return { prompt, prefix, suffix, completionOptions }; } diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts index 57a81e668..dd8eb717b 100644 --- a/core/autocomplete/util/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -1,4 +1,9 @@ import { IDE, TabAutocompleteOptions } from "../.."; +import { + countTokens, + pruneLinesFromBottom, + pruneLinesFromTop, +} from "../../llm/countTokens"; import { AutocompleteLanguageInfo, languageForFilepath, @@ -14,6 +19,8 @@ import { AutocompleteInput } from "./types"; export class HelperVars { lang: AutocompleteLanguageInfo; treePath: AstPath | undefined; + prunedPrefix: string; + prunedSuffix: string; private _fileContents: string | undefined; private _fileLines: string[] | undefined; @@ -27,6 +34,9 @@ export class HelperVars { private readonly ide: IDE, ) { this.lang = languageForFilepath(input.filepath); + const { prunedPrefix, prunedSuffix } = this.prunePrefixSuffix(); + this.prunedPrefix = prunedPrefix; + this.prunedSuffix = prunedSuffix; } private async init() { @@ -66,6 +76,33 @@ export class HelperVars { return instance; } + prunePrefixSuffix() { + // Construct basic prefix + const maxPrefixTokens = + this.options.maxPromptTokens * this.options.prefixPercentage; + const prunedPrefix = pruneLinesFromTop( + this.fullPrefix, + maxPrefixTokens, + this.modelName, + ); + + // Construct suffix + const maxSuffixTokens = Math.min( + this.options.maxPromptTokens - countTokens(prunedPrefix, this.modelName), + this.options.maxSuffixPercentage * this.options.maxPromptTokens, + ); + const prunedSuffix = pruneLinesFromBottom( + this.fullSuffix, + maxSuffixTokens, + this.modelName, + ); + + return { + prunedPrefix, + prunedSuffix, + }; + } + // Fast access get filepath() { return this.input.filepath; @@ -76,6 +113,9 @@ export class HelperVars { get maxSnippetTokens() { return this.options.maxPromptTokens * this.options.maxSnippetPercentage; } + get prunedCaretWindow() { + return this.prunedPrefix + this.prunedSuffix; + } // Getters for lazy access get fileContents(): string { From 664d84dfa0b3fba885f9fc209e2ac71407bc9958 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 18:21:07 -0700 Subject: [PATCH 26/43] show whatever lines we have at x ms --- .../StreamTransformPipeline.ts | 24 ++++++++++--------- .../filtering/streamTransforms/lineStream.ts | 16 +++++++++++++ .../generation/CompletionStreamer.ts | 11 ++++----- core/index.d.ts | 13 +++++----- core/util/parameters.ts | 1 + .../src/autocomplete/completionProvider.ts | 2 +- 6 files changed, 42 insertions(+), 25 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index edc4f8c40..42ab89829 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -1,10 +1,10 @@ -import { Position } from "../../.."; import { streamLines } from "../../../diff/util"; -import { AutocompleteLanguageInfo } from "../../constants/AutocompleteLanguageInfo"; +import { HelperVars } from "../../util/HelperVars"; import { BracketMatchingService } from "../BracketMatchingService"; import { stopAtStopTokens } from "./charStream"; import { avoidPathLineAndEmptyComments, + showWhateverWeHaveAtXMs, skipPrefixes, stopAtLines, stopAtRepeatingLines, @@ -19,13 +19,10 @@ export class StreamTransformPipeline { generator: AsyncGenerator, prefix: string, suffix: string, - filepath: string, multiline: boolean, - pos: Position, - fileLines: string[], stopTokens: string[], - lang: AutocompleteLanguageInfo, fullStop: () => void, + helper: HelperVars, ): AsyncGenerator { let charGenerator = generator; @@ -40,7 +37,7 @@ export class StreamTransformPipeline { charGenerator, prefix, suffix, - filepath, + helper.filepath, multiline, ); @@ -51,9 +48,12 @@ export class StreamTransformPipeline { let i = 1; while ( lineBelowCursor.trim() === "" && - pos.line + i <= fileLines.length - 1 + helper.pos.line + i <= helper.fileLines.length - 1 ) { - lineBelowCursor = fileLines[Math.min(pos.line + i, fileLines.length - 1)]; + lineBelowCursor = + helper.fileLines[ + Math.min(helper.pos.line + i, helper.fileLines.length - 1) + ]; i++; } @@ -61,7 +61,7 @@ export class StreamTransformPipeline { lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); lineGenerator = avoidPathLineAndEmptyComments( lineGenerator, - lang.singleLineComment, + helper.lang.singleLineComment, ); lineGenerator = skipPrefixes(lineGenerator); @@ -70,12 +70,14 @@ export class StreamTransformPipeline { // lang.topLevelKeywords, // fullStop, // ); - for (const lineFilter of lang.lineFilters ?? []) { + for (const lineFilter of helper.lang.lineFilters ?? []) { lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); } lineGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor, fullStop); + lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, 250); + const finalGenerator = streamWithNewLines(lineGenerator); for await (const update of finalGenerator) { yield update; diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index 918acaf26..cd8363672 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -510,3 +510,19 @@ export async function* logLines( } console.log(`${prefix}:\n${linesToLog.join("\n")}\n\n`); } + +export async function* showWhateverWeHaveAtXMs( + lines: LineStream, + ms: number, +): LineStream { + const startTime = Date.now(); + for await (const line of lines) { + // Always get at least one line + yield line; + + // But after that, soft break at X ms + if (Date.now() - startTime > ms) { + break; + } + } +} diff --git a/core/autocomplete/generation/CompletionStreamer.ts b/core/autocomplete/generation/CompletionStreamer.ts index 11b0755d8..3f46f5033 100644 --- a/core/autocomplete/generation/CompletionStreamer.ts +++ b/core/autocomplete/generation/CompletionStreamer.ts @@ -7,7 +7,7 @@ export class CompletionStreamer { private streamTransformPipeline = new StreamTransformPipeline(); private generatorReuseManager: GeneratorReuseManager; - constructor(private readonly onError: (err: any) => void) { + constructor(onError: (err: any) => void) { this.generatorReuseManager = new GeneratorReuseManager(onError); } @@ -49,22 +49,19 @@ export class CompletionStreamer { }; const initialGenerator = generatorWithCancellation(); - const finalGenerator = helper.options.transform + const transformedGenerator = helper.options.transform ? this.streamTransformPipeline.transform( initialGenerator, prefix, suffix, - helper.filepath, multiline, - helper.pos, - helper.fileLines, completionOptions?.stop || [], - helper.lang, fullStop, + helper, ) : initialGenerator; - for await (const update of finalGenerator) { + for await (const update of transformedGenerator) { yield update; } } diff --git a/core/index.d.ts b/core/index.d.ts index 2cc9dc56a..40bcae662 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -48,9 +48,9 @@ export interface IndexingProgressUpdate { export type PromptTemplate = | string | (( - history: ChatMessage[], - otherData: Record, - ) => string | ChatMessage[]); + history: ChatMessage[], + otherData: Record, + ) => string | ChatMessage[]); export interface ILLM extends LLMOptions { get providerName(): ModelProvider; @@ -904,6 +904,7 @@ export interface TabAutocompleteOptions { disableInFiles?: string[]; useImports?: boolean; useRootPathContext?: boolean; + showWhateverWeHaveAtXMs?: number; } export interface ContinueUIConfig { @@ -1053,9 +1054,9 @@ export interface Config { embeddingsProvider?: EmbeddingsProviderDescription | EmbeddingsProvider; /** The model that Continue will use for tab autocompletions. */ tabAutocompleteModel?: - | CustomLLM - | ModelDescription - | (CustomLLM | ModelDescription)[]; + | CustomLLM + | ModelDescription + | (CustomLLM | ModelDescription)[]; /** Options for tab autocomplete */ tabAutocompleteOptions?: Partial; /** UI styles customization */ diff --git a/core/util/parameters.ts b/core/util/parameters.ts index 7144ba4d6..7a94abc03 100644 --- a/core/util/parameters.ts +++ b/core/util/parameters.ts @@ -22,6 +22,7 @@ export const DEFAULT_AUTOCOMPLETE_OPTS: TabAutocompleteOptions = { useImports: true, useRootPathContext: true, transform: true, + showWhateverWeHaveAtXMs: 300, }; export const COUNT_COMPLETION_REJECTED_AFTER = 10_000; diff --git a/extensions/vscode/src/autocomplete/completionProvider.ts b/extensions/vscode/src/autocomplete/completionProvider.ts index b1af40435..131d61ffa 100644 --- a/extensions/vscode/src/autocomplete/completionProvider.ts +++ b/extensions/vscode/src/autocomplete/completionProvider.ts @@ -1,5 +1,5 @@ import type { IDE } from "core"; -import { CompletionProvider } from "core/autocomplete/completionProvider"; +import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { type AutocompleteInput, type AutocompleteOutcome, From a2c192c778720c21742e863bd17350deab91b4c9 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 20:32:58 -0700 Subject: [PATCH 27/43] fix bug --- core/autocomplete/READEME.md | 3 +++ core/autocomplete/util/HelperVars.ts | 29 +++++++++++++++++++++++----- 2 files changed, 27 insertions(+), 5 deletions(-) create mode 100644 core/autocomplete/READEME.md diff --git a/core/autocomplete/READEME.md b/core/autocomplete/READEME.md new file mode 100644 index 000000000..170e673a5 --- /dev/null +++ b/core/autocomplete/READEME.md @@ -0,0 +1,3 @@ +TODO + +- The generator reuse thing isn't working it seems diff --git a/core/autocomplete/util/HelperVars.ts b/core/autocomplete/util/HelperVars.ts index dd8eb717b..a6ecb21a9 100644 --- a/core/autocomplete/util/HelperVars.ts +++ b/core/autocomplete/util/HelperVars.ts @@ -19,13 +19,13 @@ import { AutocompleteInput } from "./types"; export class HelperVars { lang: AutocompleteLanguageInfo; treePath: AstPath | undefined; - prunedPrefix: string; - prunedSuffix: string; private _fileContents: string | undefined; private _fileLines: string[] | undefined; private _fullPrefix: string | undefined; private _fullSuffix: string | undefined; + private _prunedPrefix: string | undefined; + private _prunedSuffix: string | undefined; private constructor( public readonly input: AutocompleteInput, @@ -34,9 +34,6 @@ export class HelperVars { private readonly ide: IDE, ) { this.lang = languageForFilepath(input.filepath); - const { prunedPrefix, prunedSuffix } = this.prunePrefixSuffix(); - this.prunedPrefix = prunedPrefix; - this.prunedSuffix = prunedSuffix; } private async init() { @@ -55,6 +52,10 @@ export class HelperVars { this._fullPrefix = fullPrefix; this._fullSuffix = fullSuffix; + const { prunedPrefix, prunedSuffix } = this.prunePrefixSuffix(); + this._prunedPrefix = prunedPrefix; + this._prunedSuffix = prunedSuffix; + try { const ast = await getAst(this.filepath, fullPrefix + fullSuffix); if (ast) { @@ -153,4 +154,22 @@ export class HelperVars { } return this._fullSuffix; } + + get prunedPrefix(): string { + if (this._prunedPrefix === undefined) { + throw new Error( + "HelperVars must be initialized before accessing prunedPrefix", + ); + } + return this._prunedPrefix; + } + + get prunedSuffix(): string { + if (this._prunedSuffix === undefined) { + throw new Error( + "HelperVars must be initialized before accessing prunedSuffix", + ); + } + return this._prunedSuffix; + } } From cc7d41e8dc4b7524e917b7b0cdb1ed655e033b4c Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 31 Oct 2024 21:27:10 -0700 Subject: [PATCH 28/43] WIP testing rootpathcontext --- core/autocomplete/READEME.md | 6 ++ .../context/ContextRetrievalService.ts | 2 +- .../RootPathContextService.test.ts | 97 +++++++++++++++++++ .../RootPathContextService.ts | 10 +- .../test/typescript/file1.ts | 13 +++ .../test/typescript/types.ts | 11 +++ 6 files changed, 133 insertions(+), 6 deletions(-) create mode 100644 core/autocomplete/context/root-path-context/RootPathContextService.test.ts rename core/autocomplete/context/{ => root-path-context}/RootPathContextService.ts (92%) create mode 100644 core/autocomplete/context/root-path-context/test/typescript/file1.ts create mode 100644 core/autocomplete/context/root-path-context/test/typescript/types.ts diff --git a/core/autocomplete/READEME.md b/core/autocomplete/READEME.md index 170e673a5..d5e822273 100644 --- a/core/autocomplete/READEME.md +++ b/core/autocomplete/READEME.md @@ -1,3 +1,9 @@ TODO - The generator reuse thing isn't working it seems + +Tests for context: + +- You need a static set of files to test. Ideally you don't have to rewrite the exact same files every time you want to make a new test. +- So put some example files in a few folders. There should be a folder for each language I think. +- You should definitely test each of the services separately diff --git a/core/autocomplete/context/ContextRetrievalService.ts b/core/autocomplete/context/ContextRetrievalService.ts index 3c6ed3376..a12d1962e 100644 --- a/core/autocomplete/context/ContextRetrievalService.ts +++ b/core/autocomplete/context/ContextRetrievalService.ts @@ -3,7 +3,7 @@ import { HelperVars } from "../util/HelperVars"; import { RecentlyEditedRange } from "../util/types"; import { ImportDefinitionsService } from "./ImportDefinitionsService"; import { AutocompleteSnippet, getSymbolsForSnippet } from "./ranking"; -import { RootPathContextService } from "./RootPathContextService"; +import { RootPathContextService } from "./root-path-context/RootPathContextService"; export class ContextRetrievalService { private importDefinitionsService: ImportDefinitionsService; diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/RootPathContextService.test.ts new file mode 100644 index 000000000..87795611b --- /dev/null +++ b/core/autocomplete/context/root-path-context/RootPathContextService.test.ts @@ -0,0 +1,97 @@ +import fs from "fs"; +import path from "path"; +import { Range } 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] { + 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 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)]; +} + +export async function testRootPathContext( + folderName: string, + relativeFilepath: string, + rangeToFill: Range, + expectedSnippets: string[], +) { + const ide = testIde; + const importDefinitionsService = new ImportDefinitionsService(ide); + const service = new RootPathContextService(importDefinitionsService, ide); + + // Copy the folder to the test directory + const folderPath = path.join( + __dirname, + "autocomplete", + "context", + "root-path-context", + "test", + folderName, + ); + const workspaceDir = (await ide.getWorkspaceDirs())[0]; + const testFolderPath = path.join(workspaceDir, folderName); + fs.cpSync(folderPath, testFolderPath, { + recursive: true, + force: true, + }); + + // Get results of root path context + const startPath = path.join(testFolderPath, relativeFilepath); + const [prefix, suffix] = splitTextAtRange( + fs.readFileSync(startPath, "utf8"), + rangeToFill, + ); + const fileContents = prefix + suffix; + const ast = await getAst(startPath, fileContents); + if (!ast) { + throw new Error("AST is undefined"); + } + + const treePath = await getTreePathAtCursor(ast, rangeToFill.start.character); + const snippets = await service.getContextForPath(startPath, treePath); + + expectedSnippets.forEach((expectedSnippet) => { + const found = snippets.find((snippet) => + snippet.contents.includes(expectedSnippet), + ); + expect(found).toBeDefined(); + }); +} + +describe("RootPathContextService", () => { + it("should be true", async () => { + await testRootPathContext( + "typescript", + "file1.ts", + { start: { line: 3, character: 2 }, end: { line: 3, character: 24 } }, + ["export interface Person", "export interface Address"], + ); + }); +}); diff --git a/core/autocomplete/context/RootPathContextService.ts b/core/autocomplete/context/root-path-context/RootPathContextService.ts similarity index 92% rename from core/autocomplete/context/RootPathContextService.ts rename to core/autocomplete/context/root-path-context/RootPathContextService.ts index 2b2986b75..ba99b2e83 100644 --- a/core/autocomplete/context/RootPathContextService.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.ts @@ -1,11 +1,11 @@ import { createHash } from "crypto"; import { LRUCache } from "lru-cache"; import Parser from "web-tree-sitter"; -import { IDE } from "../.."; -import { getQueryForFile, TSQueryType } from "../../util/treeSitter"; -import { AstPath } from "../util/ast"; -import { ImportDefinitionsService } from "./ImportDefinitionsService"; -import { AutocompleteSnippet } from "./ranking"; +import { IDE } from "../../.."; +import { getQueryForFile, TSQueryType } from "../../../util/treeSitter"; +import { AstPath } from "../../util/ast"; +import { ImportDefinitionsService } from "../ImportDefinitionsService"; +import { AutocompleteSnippet } from "../ranking"; export class RootPathContextService { private cache = new LRUCache({ diff --git a/core/autocomplete/context/root-path-context/test/typescript/file1.ts b/core/autocomplete/context/root-path-context/test/typescript/file1.ts new file mode 100644 index 000000000..c67ae91e2 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/typescript/file1.ts @@ -0,0 +1,13 @@ +import { Address, Person } from "./types"; + +function getAddress(person: Person): Address { + return person.address; +} + +class Group { + people: Person[]; + + constructor(people: Person[]) { + this.people = people; + } +} diff --git a/core/autocomplete/context/root-path-context/test/typescript/types.ts b/core/autocomplete/context/root-path-context/test/typescript/types.ts new file mode 100644 index 000000000..272ec27d7 --- /dev/null +++ b/core/autocomplete/context/root-path-context/test/typescript/types.ts @@ -0,0 +1,11 @@ +export interface Person { + firstName: string; + lastName: string; + age: number; + address: Address; +} + +export interface Address { + street: string; + city: string; +} From 400be9b47f0b8ab52b4e32ca77339497c63c8f96 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 4 Nov 2024 14:45:14 +0700 Subject: [PATCH 29/43] fix: add missing import --- core/autocomplete/templating/index.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/core/autocomplete/templating/index.ts b/core/autocomplete/templating/index.ts index 6ee99b862..05a10bbed 100644 --- a/core/autocomplete/templating/index.ts +++ b/core/autocomplete/templating/index.ts @@ -1,3 +1,4 @@ +import Handlebars from "handlebars"; import { CompletionOptions } from "../.."; import { getBasename, getLastNPathParts } from "../../util"; import { AutocompleteLanguageInfo } from "../constants/AutocompleteLanguageInfo"; From deea8f1f44403b6d7d7bb4236ff5acb8d38bca01 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 4 Nov 2024 17:46:12 +0700 Subject: [PATCH 30/43] fix: tests --- .../test/NEGATIVE_CASES_STARCODER.tsx | 51 -------- .../test/NEGATIVE_CASES_STARCODER.txt | 123 ++++++++++++++++++ 2 files changed, 123 insertions(+), 51 deletions(-) delete mode 100644 core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx create mode 100644 core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.txt diff --git a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx b/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx deleted file mode 100644 index 269d25f0f..000000000 --- a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.tsx +++ /dev/null @@ -1,51 +0,0 @@ -##### Prompt ##### -class Calculator { - constructor() { - this.result = 0; - } - - add(number) { - this.result += number; - return this; - } - - subtract(number) { - this.result -= number; - return this; - } - - multiply(number) { - this.result *= number; - return this; - } - - divide(number) { - if (number === 0) { - throw new Error("Cannot divide by zero"); - } - - - - this.result /= number; - return this; - } - - getResult() { - return this.result; - } - - reset() { - this.result = 0; - return this; - } -} -========================================================================== -========================================================================== -Completion: - - this.result /= number; - return this; - } -} - -module.exports = Calculator; \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.txt b/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.txt new file mode 100644 index 000000000..9a286d1de --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.txt @@ -0,0 +1,123 @@ +##### Prompt ##### +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + + + + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} +========================================================================== +========================================================================== +Completion: + + this.result /= number; + return this; + } +} + +module.exports = Calculator; + +------------------------------------------------------------------------ + +##### Prompt ##### +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + this.result /= number; + return this; + } + + + + + + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} +========================================================================== +========================================================================== +Completion: + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} + +// Example usage: +const calculator = new Calculator(); +calculator.add(5).subtract(3).multiply(2).divide(4); +console.log(calculator.getResult()); // Output: 2 + +calculator.reset().add(10).divide(2); +console.log(calculator.getResult()); // Output: 5 + +calculator.reset().add(8).multiply(0); +console.log(calculator.getResult()); // Output: 0 + +calculator.reset().add(6).divide(0); // Throws an error: Cannot divide by zero \ No newline at end of file From fb1a75dcf33fa38863bda4f5b88c1a567aaf0269 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 4 Nov 2024 17:46:35 +0700 Subject: [PATCH 31/43] fix: naming --- ...ASES_STARCODER.txt => NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename core/autocomplete/filtering/test/{NEGATIVE_CASES_STARCODER.txt => NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt} (100%) diff --git a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.txt b/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt similarity index 100% rename from core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER.txt rename to core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt From fe1af0156fc9db0640ef2d460ba5da289192aeb0 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 4 Nov 2024 17:58:59 +0700 Subject: [PATCH 32/43] improv: single responsibility in filter functions --- .../StreamTransformPipeline.ts | 6 ++-- .../streamTransforms/lineStream.test.ts | 27 ++++++++++++----- .../filtering/streamTransforms/lineStream.ts | 29 +++++++++++++++---- 3 files changed, 48 insertions(+), 14 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 42ab89829..543c9b7b8 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -3,7 +3,8 @@ import { HelperVars } from "../../util/HelperVars"; import { BracketMatchingService } from "../BracketMatchingService"; import { stopAtStopTokens } from "./charStream"; import { - avoidPathLineAndEmptyComments, + avoidEmptyComments, + avoidPathLine, showWhateverWeHaveAtXMs, skipPrefixes, stopAtLines, @@ -59,10 +60,11 @@ export class StreamTransformPipeline { lineGenerator = stopAtLines(lineGenerator, fullStop); lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); - lineGenerator = avoidPathLineAndEmptyComments( + lineGenerator = avoidEmptyComments( lineGenerator, helper.lang.singleLineComment, ); + lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment); lineGenerator = skipPrefixes(lineGenerator); // lineGenerator = noTopLevelKeywordsMidline( diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts index df8cd1263..810ab9eec 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.test.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.test.ts @@ -31,21 +31,34 @@ describe("lineStream", () => { }); describe("avoidPathLine", () => { - it("should filter out path lines and empty comments", async () => { + it("should filter out path lines", async () => { const linesGenerator = await getLineGenerator([ "// Path: src/index.ts", "const x = 5;", "//", "console.log(x);", ]); - - const result = lineStream.avoidPathLineAndEmptyComments( - linesGenerator, - "//", - ); + const result = lineStream.avoidPathLine(linesGenerator, "//"); const filteredLines = await getFilteredLines(result); + expect(filteredLines).toEqual(["const x = 5;", "//", "console.log(x);"]); + }); + }); - expect(filteredLines).toEqual(["const x = 5;", "console.log(x);"]); + describe("avoidEmptyComments", () => { + it("should filter out empty comments", async () => { + const linesGenerator = await getLineGenerator([ + "// Path: src/index.ts", + "const x = 5;", + "//", + "console.log(x);", + ]); + const result = lineStream.avoidEmptyComments(linesGenerator, "//"); + const filteredLines = await getFilteredLines(result); + expect(filteredLines).toEqual([ + "// Path: src/index.ts", + "const x = 5;", + "console.log(x);", + ]); }); }); diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index cd8363672..dffca36b9 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -122,21 +122,40 @@ export async function* noTopLevelKeywordsMidline( } /** - * Filters out unwanted lines from a LineStream, specifically those starting with '// Path: ' or empty comments. + * Filters out lines starting with '// Path: ' from a LineStream. * * @param {LineStream} stream - The input stream of lines to filter. * @param {string} comment - The comment syntax to filter (e.g., '//' for JavaScript-style comments). - * @yields {string} The filtered lines, excluding unwanted path lines and empty comments. + * @yields {string} The filtered lines, excluding unwanted path lines. */ -export async function* avoidPathLineAndEmptyComments( +export async function* avoidPathLine( stream: LineStream, comment: string, ): LineStream { // Snippets are inserted as comments with a line at the start '// Path: '. // Sometimes the model with copy this pattern, which is unwanted for await (const line of stream) { - // Also filter lines that are empty comments - if (line.startsWith(`${comment} Path: `) || line.trim() === comment) { + if (line.startsWith(`${comment} Path: `)) { + continue; + } + yield line; + } +} + +/** + * Filters out empty comment lines from a LineStream. + * + * @param {LineStream} stream - The input stream of lines to filter. + * @param {string} comment - The comment syntax to filter (e.g., '//' for JavaScript-style comments). + * @yields {string} The filtered lines, excluding empty comments. + */ +export async function* avoidEmptyComments( + stream: LineStream, + comment: string, +): LineStream { + // Filter lines that are empty comments + for await (const line of stream) { + if (line.trim() === comment) { continue; } yield line; From f82b867adbd1d4ac15113a8961e731ab638d2175 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Mon, 4 Nov 2024 18:08:14 +0700 Subject: [PATCH 33/43] improv: organization --- .../CODESTRAL_TYPESCRIPT.txt} | 53 ------------------- .../STARCODER_TYPESCRIPT.txt | 53 +++++++++++++++++++ 2 files changed, 53 insertions(+), 53 deletions(-) rename core/autocomplete/filtering/test/{NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt => NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt} (58%) create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt diff --git a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt similarity index 58% rename from core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt rename to core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt index 9a286d1de..7ecc7003d 100644 --- a/core/autocomplete/filtering/test/NEGATIVE_CASES_STARCODER_TYPESCRIPT.txt +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt @@ -1,56 +1,3 @@ -##### Prompt ##### -class Calculator { - constructor() { - this.result = 0; - } - - add(number) { - this.result += number; - return this; - } - - subtract(number) { - this.result -= number; - return this; - } - - multiply(number) { - this.result *= number; - return this; - } - - divide(number) { - if (number === 0) { - throw new Error("Cannot divide by zero"); - } - - - - this.result /= number; - return this; - } - - getResult() { - return this.result; - } - - reset() { - this.result = 0; - return this; - } -} -========================================================================== -========================================================================== -Completion: - - this.result /= number; - return this; - } -} - -module.exports = Calculator; - ------------------------------------------------------------------------- ##### Prompt ##### class Calculator { diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt new file mode 100644 index 000000000..b2505a0bb --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt @@ -0,0 +1,53 @@ +##### Prompt ##### +class Calculator { + constructor() { + this.result = 0; + } + + add(number) { + this.result += number; + return this; + } + + subtract(number) { + this.result -= number; + return this; + } + + multiply(number) { + this.result *= number; + return this; + } + + divide(number) { + if (number === 0) { + throw new Error("Cannot divide by zero"); + } + + + + this.result /= number; + return this; + } + + getResult() { + return this.result; + } + + reset() { + this.result = 0; + return this; + } +} +========================================================================== +========================================================================== +Completion: + + this.result /= number; + return this; + } +} + +module.exports = Calculator; + +------------------------------------------------------------------------ From c3800fe13721d02eb338869ce7dfebfbf0dec4fc Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 5 Nov 2024 01:21:54 +0700 Subject: [PATCH 34/43] refactor: clean up code --- .../StreamTransformPipeline.ts | 63 +++++++++---------- 1 file changed, 29 insertions(+), 34 deletions(-) diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 543c9b7b8..037059912 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -27,12 +27,6 @@ export class StreamTransformPipeline { ): AsyncGenerator { let charGenerator = generator; - // charGenerator = noFirstCharNewline(charGenerator); - // charGenerator = onlyWhitespaceAfterEndOfLine( - // charGenerator, - // lang.endOfLine, - // fullStop, - // ); charGenerator = stopAtStopTokens(generator, stopTokens); charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( charGenerator, @@ -44,7 +38,34 @@ export class StreamTransformPipeline { let lineGenerator = streamLines(charGenerator); - // First non-whitespace line below the cursor + lineGenerator = stopAtLines(lineGenerator, fullStop); + lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); + lineGenerator = avoidEmptyComments( + lineGenerator, + helper.lang.singleLineComment, + ); + lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment); + lineGenerator = skipPrefixes(lineGenerator); + + for (const lineFilter of helper.lang.lineFilters ?? []) { + lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); + } + + lineGenerator = stopAtSimilarLine( + lineGenerator, + this.getLineBelowCursor(helper), + fullStop, + ); + + lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, 250); + + const finalGenerator = streamWithNewLines(lineGenerator); + for await (const update of finalGenerator) { + yield update; + } + } + + private getLineBelowCursor(helper: HelperVars): string { let lineBelowCursor = ""; let i = 1; while ( @@ -57,32 +78,6 @@ export class StreamTransformPipeline { ]; i++; } - - lineGenerator = stopAtLines(lineGenerator, fullStop); - lineGenerator = stopAtRepeatingLines(lineGenerator, fullStop); - lineGenerator = avoidEmptyComments( - lineGenerator, - helper.lang.singleLineComment, - ); - lineGenerator = avoidPathLine(lineGenerator, helper.lang.singleLineComment); - lineGenerator = skipPrefixes(lineGenerator); - - // lineGenerator = noTopLevelKeywordsMidline( - // lineGenerator, - // lang.topLevelKeywords, - // fullStop, - // ); - for (const lineFilter of helper.lang.lineFilters ?? []) { - lineGenerator = lineFilter({ lines: lineGenerator, fullStop }); - } - - lineGenerator = stopAtSimilarLine(lineGenerator, lineBelowCursor, fullStop); - - lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, 250); - - const finalGenerator = streamWithNewLines(lineGenerator); - for await (const update of finalGenerator) { - yield update; - } + return lineBelowCursor; } } From 4482ca1ac027430b1db44548b721f809eb147b2d Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 5 Nov 2024 10:45:30 +0700 Subject: [PATCH 35/43] refactor: clean up code --- core/autocomplete/test/filter.test.ts | 30 - core/autocomplete/test/testCases.ts | 2013 ------------------------- core/autocomplete/test/util.ts | 75 - 3 files changed, 2118 deletions(-) delete mode 100644 core/autocomplete/test/filter.test.ts delete mode 100644 core/autocomplete/test/testCases.ts delete mode 100644 core/autocomplete/test/util.ts diff --git a/core/autocomplete/test/filter.test.ts b/core/autocomplete/test/filter.test.ts deleted file mode 100644 index 171b1cb44..000000000 --- a/core/autocomplete/test/filter.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { - AutocompleteFileringTestInput, - testAutocompleteFiltering, -} from "./util"; -import { TEST_CASES } from "./testCases"; - -const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { - if (tests.some((test) => test.options?.only)) { - return tests.filter((test) => test.options?.only); - } - - return tests; -}; - -describe("llms/Mock", () => { - describe("Autocomplete Filtering Tests", () => { - beforeEach(async () => { - await new Promise((resolve) => setTimeout(resolve, 50)); - }); - - describe("Should return unmodified LLM output", () => { - it.each(filterTestCases(TEST_CASES))("$description", async (testCase) => { - await testAutocompleteFiltering(testCase); - }); - }); - - // TODO: Add test cases where modifying LLM output is desirable - describe.skip("Should return modified LLM output", () => {}); - }); -}); diff --git a/core/autocomplete/test/testCases.ts b/core/autocomplete/test/testCases.ts deleted file mode 100644 index 2deeec9de..000000000 --- a/core/autocomplete/test/testCases.ts +++ /dev/null @@ -1,2013 +0,0 @@ -import { dedent } from "../../util"; -import { AutocompleteFileringTestInput } from "./util"; - -export const TEST_CASES: AutocompleteFileringTestInput[] = [ - { - description: "should pass", - filename: "test.js", - input: "console.log('Hello <|fim|>!');", - llmOutput: "World", - expectedCompletion: "World", - }, - { - description: - "Should preserve closing brackets when the opening bracket is not a part of the completion.", - filename: "test.js", - input: dedent` - class Calculator { - constructor() { - this.result = 0; - } - - add(number) { - this.result += number; - return this; - } - - subtract(number) { - this.result -= number; - return this; - } - - multiply(number) { - this.result *= number; - return this; - } - - divide(number) { - <|fim|> - - getResult() { - return this.result; - } - - reset() { - this.result = 0; - return this; - } - } - `, - llmOutput: dedent`if (number === 0) { - throw new Error("Cannot divide by zero"); - } - this.result /= number; - return this; - }`, - expectedCompletion: dedent`if (number === 0) { - throw new Error("Cannot divide by zero"); - } - this.result /= number; - return this; - }`, - }, - { - description: "Should multiline-autocomplete CSS blocks", - input: `body { - font-family: Arial, sans-serif; - font-size: 16px; - color: #333333; -} - -h1 { - font-size: 24px; - font-weight: bold; - color: #000000; -} - -h4<|fim|> - -a { - text-decoration: none; - color: #007bff; -} - -.container { - width: 100%; - max-width: 1200px; - margin: 0 auto; - padding: 20px; -} - -.button { - display: inline-block; - padding: 10px 20px; - background-color: #007bff; - color: #ffffff;`, - llmOutput: ` { - font-size: 18px; - font-weight: bold; - color: #000000; -}`, - expectedCompletion: ` { - font-size: 18px; - font-weight: bold; - color: #000000; -}`, - filename: "test.css", - }, - { - description: "Should complete CSS rules inside a nested selector", - filename: "styles.css", - input: ` -.container { - display: flex; - justify-content: center; - align-items: center; - width: 100%; - height: 100vh; - - .inner { - <|fim|> - } -} -`, - llmOutput: `width: 50%; - height: 50%; - background-color: #f0f0f0;`, - expectedCompletion: `width: 50%; - height: 50%; - background-color: #f0f0f0;`, - }, - - { - description: - "Should complete a CSS rule when the property is partially typed", - filename: "styles.css", - input: ` -button { - border: 2px solid #000; - border-radius<|fim|> -}`, - llmOutput: `: 5px;`, - expectedCompletion: `: 5px;`, - }, - - { - description: "Should handle CSS autocomplete with a single bracket present", - filename: "styles.css", - input: ` -.card { - box-shadow: 0 4px 8px rgba(0,0,0,0.2); - transition: 0.3s; - padding: 16px; - border-bottom-left-radius: <|fim|>px; - border-bottom-right-radius: 8px; -} -`, - llmOutput: `8`, - expectedCompletion: `8`, - }, - - { - description: "Should autocomplete CSS pseudoclass", - filename: "pseudoClass.css", - input: ` -input:focus { - outline: none; - border: 2px solid <|fim|>; -} -`, - llmOutput: `#4CAF50;`, - expectedCompletion: `#4CAF50;`, - }, - - { - description: "Should handle CSS variable syntax", - filename: "variables.css", - input: ` -:root { - --primary-color: #3498db; - --padding: 10px; -} - -.section { - background-color: var(<|fim|>); - padding: var(--padding); -} -`, - llmOutput: `--primary-color`, - expectedCompletion: `--primary-color`, - }, - { - description: "Should complete CSS grid template columns", - filename: "grid.css", - input: ` -.grid-container { - display: grid; - grid-template-columns: repeat(<|fim|>); - grid-gap: 10px; -} -`, - llmOutput: `3, 1fr`, - expectedCompletion: `3, 1fr`, - }, - - { - description: "Should complete PHP function inside a class with comments", - input: `name = $name; - $this->email = $email; - } - - public function <|fim|> - - public function setEmail($email) { - $this->email = $email; - } -}`, - llmOutput: `getDetails() { - return "Name: " . $this->name . ", Email: " . $this->email; - }`, - expectedCompletion: `getDetails() { - return "Name: " . $this->name . ", Email: " . $this->email; - }`, - filename: "User.php", - }, - - { - description: "Should autocomplete PHP function with inline logic", - input: ` -} - -echo calculateArea(5, 3);`, - llmOutput: `return $length * $width;`, - expectedCompletion: `return $length * $width;`, - filename: "areaCalculator.php", - }, - - { - description: "Should handle PHP completion in the middle of an array", - input: `); - -echo "First color is: " . $colors[0];`, - llmOutput: `"Blue"`, - expectedCompletion: `"Blue"`, - filename: "colors.php", - }, - { - description: "Should autocomplete React return statements (jsx)", - input: `import React from "react"; - -export const Button = ({ - onClick, - children, -}: { - children: React.ReactNode; - onClick: () => void; -}) => { - return ( -<|fim|> - ); -};`, - llmOutput: ``, - expectedCompletion: ``, - filename: "Button.tsx", - }, - { - description: "Should autocomplete React state initialization", - input: `import React, { useState } from "react"; - -export const Counter = () => { - const [count, setCount] = useState(<|fim|>); - - return ( -
-

You clicked {count} times

- -
- ); -};`, - llmOutput: `0`, - expectedCompletion: `0`, - filename: "Counter.tsx", - }, - - { - description: "Should autocomplete React effect hook", - input: `import React, { useState, useEffect } from "react"; - -export const Timer = () => { - const [seconds, setSeconds] = useState(0); - - useEffect(() => { - const interval = setInterval(() => { - setSeconds(seconds + 1); - }, 1000); - - <|fim|>; - - return () => clearInterval(interval); - }, [seconds]); - - return ( -
-

{seconds} seconds have passed.

-
- ); -};`, - llmOutput: `return () => clearInterval(interval);`, - expectedCompletion: `return () => clearInterval(interval);`, - filename: "Timer.tsx", - }, - - { - description: "Should autocomplete React component methods", - input: `import React from "react"; - -class Form extends React.Component { - constructor(props) { - super(props); - this.state = { name: '' }; - } - - handleChange = (event) => { - <|fim|> - } - - handleSubmit = (event) => { - event.preventDefault(); - alert('A name was submitted: ' + this.state.name); - } - - render() { - return ( -
- - -
- ); - } -}`, - llmOutput: `this.setState({ name: event.target.value });`, - expectedCompletion: `this.setState({ name: event.target.value });`, - filename: "Form.tsx", - }, - { - description: "Should autocomplete Python function definition", - filename: "test.py", - input: `def calculate_area(length, width): - area = length * width - return area - -def calculate_perimeter(length, width): - <|fim|> -`, - llmOutput: `perimeter = 2 * (length + width) - return perimeter`, - expectedCompletion: `perimeter = 2 * (length + width) - return perimeter`, - }, - { - description: "Should complete Python class method with self", - filename: "test.py", - input: `class BankAccount: - def __init__(self, owner, balance=0): - self.owner = owner - self.balance = balance - - def deposit(self, amount): - self.balance += amount - return self.balance - - def withdraw(self, amount): - <|fim|> -`, - llmOutput: `if amount > self.balance: - return "Insufficient funds" - self.balance -= amount - return self.balance`, - expectedCompletion: `if amount > self.balance: - return "Insufficient funds" - self.balance -= amount - return self.balance`, - }, - { - description: "Should autocomplete Python list comprehension", - filename: "test.py", - input: `squares = [x**2 for x in range(10)] -even_squares = [x for x in squares if x % 2 == 0] -print(even_squares) - -odd_squares = [<|fim|> -print(odd_squares) -`, - llmOutput: `x for x in squares if x % 2 != 0`, - expectedCompletion: `x for x in squares if x % 2 != 0`, - }, - { - description: "Should handle python multi-line string", - filename: "test.py", - input: `def create_greeting(name): - greeting = """Hello, """ + name + """! -Welcome to our community. We hope you have a great time here. -If you have any questions, feel free to reach out.""" - return greeting - -message = create_greeting("Alice") -print(message) - -multi_line_message = """<|fim|> -print(multi_line_message) -`, - llmOutput: `This is a multi-line message. -It continues across multiple lines, -which allows for easy reading and formatting. -""" -`, - expectedCompletion: `This is a multi-line message. -It continues across multiple lines, -which allows for easy reading and formatting. -""" -`, - }, - { - description: "Should autocomplete a simple Go function declaration", - filename: "simpleFunction.go", - input: `package main - -import ( - "fmt" -) - -func main() { - fmt.Println("Hello, World!") -} - -func calculateArea<|fim|>`, - llmOutput: `(length float64, width float64) float64 { - return length * width -}`, - expectedCompletion: `(length float64, width float64) float64 { - return length * width -}`, - }, - - { - description: - "Should handle autocomplete in the middle of a Go struct definition", - filename: "structDefinition.go", - input: `package main - -type Person struct { - FirstName string - LastName string - Age int - Address Address -} - -type Address struct { - Street string - City <|fim|> -} - -func main() {}`, - llmOutput: `string - State string - ZipCode string -}`, - expectedCompletion: `string - State string - ZipCode string -}`, - }, - - { - description: "Should autocomplete a missing Go function body bracket", - filename: "missingBracket.go", - input: `package main - -func add(a int, b int) int { - return a + b<|fim|> - -func multiply(a int, b int) int { - return a * b -} - -func main() { - result1 := add(2, 3) - result2 := multiply(4, 5) - println(result1, result2) -}`, - llmOutput: ` -}`, - expectedCompletion: ` -}`, - }, - { - description: - "Should autocomplete SQL query with subquery and alias in SELECT clause", - filename: "complex_query.sql", - input: `SELECT u.id, - u.name, - (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count - 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)`, - }, - { - description: - "Should autocomplete SQL query with nested functions and missing bracket", - filename: "_nested_function.sql", - input: `SELECT name, ROUND(AVG(rating), 2) as avg_rating - FROM movies - WHERE release_year > 2000 AND director = 'Christopher Nolan' - GROUP BY name - HAVING avg_rating > <|fim|>`, - llmOutput: `8.5)`, - expectedCompletion: `8.5)`, - }, - { - description: - "Should autocomplete multi-line SQL query with CASE statements", - filename: "case_statement.sql", - input: `SELECT order_id, - order_date, - CASE - WHEN status = 'shipped' THEN 'Completed' - WHEN status = 'pending' THEN 'Pending Approval' - <|fim|> - ELSE 'Unknown' - END as order_status - FROM orders`, - llmOutput: `WHEN status = 'cancelled' THEN 'Cancelled'`, - expectedCompletion: `WHEN status = 'cancelled' THEN 'Cancelled'`, - }, - { - description: "Should autocomplete HTML paragraph content", - input: ` - - Document - - -

<|fim|>

- -`, - llmOutput: `This is a paragraph with some sample text.`, - expectedCompletion: `This is a paragraph with some sample text.`, - filename: "test.html", - }, - { - description: "Should autocomplete HTML attributes within a tag", - input: `
- > -
-

Title

-

Description text.

-
-
`, - llmOutput: `alt="Description of image"`, - expectedCompletion: `alt="Description of image"`, - filename: "test.html", - }, - { - description: "Should autocomplete HTML nested tags", - input: `
    -
  • Item 1
  • -
  • Item 2
  • -
  • Item 3
  • -
`, - llmOutput: `>Item 4`, - expectedCompletion: `>Item 4`, - filename: "test.html", - }, - - { - description: "Should complete a class method in Ruby", - input: ` -class Greeter - def initialize(name) - @name = name - end - - def greet - puts "Hello, <|fim|> - end -end - -g = Greeter.new("World") -g.greet -`, - llmOutput: "#{@name}!", - expectedCompletion: "#{@name}!", - filename: "greeter.rb", - }, - { - description: "Should complete Ruby if-else block", - input: ` -number = 10 - -if number > 5 - puts "Number is greater than 5" -<|fim|> -end -`, - llmOutput: `else - puts "Number is 5 or less"`, - expectedCompletion: `else - puts "Number is 5 or less"`, - filename: "conditional.rb", - }, - { - description: "Should complete Ruby array method", - input: ` -numbers = [1, 2, 3, 4, 5] -squared_numbers = numbers.<|fim|> -`, - llmOutput: `map { |n| n ** 2 }`, - expectedCompletion: `map { |n| n ** 2 }`, - filename: "array_methods.rb", - }, - { - description: "Should autocomplete a Java method within a class", - filename: "Calculator.java", - input: ` -public class Calculator { - private double result; - - public Calculator() { - this.result = 0.0; - } - - public void add(double number) { - result += number; -<|fim|>`, - llmOutput: ` - } - - public void subtract(double number) { - result -= number; - } -`, - expectedCompletion: ` - } - - public void subtract(double number) { - result -= number; - } -`, - }, - { - description: "Should autocomplete Java when inside a block", - filename: "Main.java", - input: ` -public class Main { - public static void main(String[] args) { - for (int i = 0; i < 10; i++) { - if (i % 2 == 0) { - System.out.println("Even: " + i); - } else { -<|fim|> - } - } - } -}`, - llmOutput: ` - System.out.println("Odd: " + i); -`, - expectedCompletion: ` - System.out.println("Odd: " + i); -`, - }, - { - description: "Should autocomplete Java within a string", - filename: "App.java", - input: ` -public class App { - public static void main(String[] args) { - String message = "Hello, <|fim|>"; - System.out.println(message); - } -}`, - llmOutput: `World`, - expectedCompletion: `World`, - }, - { - description: - "Should autocomplete a C++ class definition with a constructor", - filename: "test.cpp", - input: "class Vehicle { public: Vehicle(<|fim|>); };", - llmOutput: "int wheels, double weight", - expectedCompletion: "int wheels, double weight", - }, - { - description: "Should complete a C++ method declaration inside a class", - filename: "test.cpp", - input: - "class Calculator { public: int add(int a, int b); int subtract(int a, int b);<|fim|> };", - llmOutput: " int multiply(int a, int b);", - expectedCompletion: " int multiply(int a, int b);", - }, - - { - description: "Should autocomplete C++ for loop syntax", - filename: "test.cpp", - input: ` - int sum = 0; - for (int i = 0; i < 10; <|fim|>) { - sum += i; - } - `, - llmOutput: "i++", - expectedCompletion: "i++", - }, - { - description: "Should autocomplete a Markdown list with nested items", - filename: "test.md", - input: ` -- Item 1 -- Item 2 - - Subitem 1 - <|fim|> -- Item 3 -`, - llmOutput: ` - Subitem 2 - - Subitem 3 -`, - expectedCompletion: ` - Subitem 2 - - Subitem 3 -`, - }, - { - description: - "Should autocomplete a Markdown heading and preserve formatting", - filename: "test.md", - input: `# My Document - -## Introduction -This is a sample document for testing. - -## <|fim|> -### Conclusion -Thank you for reading. -`, - llmOutput: `Features -Here is a list of features: -- Feature 1 -- Feature 2 -`, - expectedCompletion: `Features -Here is a list of features: -- Feature 1 -- Feature 2 -`, - }, - { - description: "Should complete a Markdown code block", - filename: "test.md", - input: ` -Here is a sample JavaScript function: - -\`\`\`javascript -function sayHello() { - console.log("Hello, <|fim|> -} -\`\`\` -`, - llmOutput: `world!"); -`, - expectedCompletion: `world!"); -`, - }, - { - description: "Should autocomplete JSON object inside an array", - filename: "data.json", - input: `{ - "users": [ - { "id": 1, "name": "Alice" }, - { "id": 2, "name": "Bob" } - <|fim|> - ] -}`, - llmOutput: `, { "id": 3, "name": "Charlie" }`, - expectedCompletion: `, { "id": 3, "name": "Charlie" }`, - }, - { - description: "Should autocomplete nested JSON objects", - filename: "config.json", - input: `{ - "server": { - "host": "localhost", - "port": 8080, - "features": { - "enableLogging": true, - "maxConnections": 100 - <|fim|> - } -}`, - llmOutput: `, - "timeout": 5000 - }`, - expectedCompletion: `, - "timeout": 5000 - }`, - }, - { - description: "Should autocomplete JSON object with missing bracket", - filename: "settings.json", - input: `{ - "theme": "dark", - "language": "en"<|fim|> - `, - llmOutput: `, - "notifications": true - }`, - expectedCompletion: `, - "notifications": true - }`, - }, - { - description: "Should autocomplete within a CSV record", - filename: "test.csv", - input: `Name, Age, City -John Doe, 30, New York -Jane Smith<|fim|>`, - llmOutput: `, 25, Los Angeles`, - expectedCompletion: `, 25, Los Angeles`, - }, - { - description: - "Should complete CSV record when starting in the middle of a word", - filename: "test.csv", - input: `Product, Price, Quantity -Laptop, 1200, 5 -Smart<|fim|>`, - llmOutput: `phone, 800, 10`, - expectedCompletion: `phone, 800, 10`, - }, - { - description: "Should complete CSV structure adding closing brackets", - filename: "test.csv", - input: `ID, Name, JoiningDate -1, Alice, 2023-01-10 -2, B<|fim|>`, - llmOutput: `ob, 2023-02-10`, - expectedCompletion: `ob, 2023-02-10`, - }, - { - description: "Should complete YAML list item and preserve structure", - filename: "test.yaml", - input: ` - services: - - name: web - image: nginx - - name: app<|fim|> - volumes: - - volume1 - - volume2 - `, - llmOutput: ` - image: node - `, - expectedCompletion: ` - image: node - `, - }, - { - description: - "Should complete YAML key-value pair inside a nested structure", - filename: "test.yaml", - input: ` - version: '3' - services: - db: - image: postgres - environment: - POSTGRES_USER: user - POSTGRES_PASSWORD: pass - POSTGRES_DB: mydb<|fim|> - `, - llmOutput: ` - PGDATA: /var/lib/postgresql/data/pgdata - `, - expectedCompletion: ` - PGDATA: /var/lib/postgresql/data/pgdata - `, - }, - { - description: "Should complete YAML block within an existing block", - filename: "test.yaml", - input: ` - pipelines: - branches: - master: - - step: - name: Build and Test - script: - - npm install - - npm run test - - step: - name: Deploy<|fim|> - `, - llmOutput: ` - script: - - npm run deploy - `, - expectedCompletion: ` - script: - - npm run deploy - `, - }, - { - description: - "Should autocomplete a Rust function implementation inside a struct", - filename: "main.rs", - input: ` -struct Calculator { - result: f64, -} - -impl Calculator { - fn new() -> Self { - Calculator { result: 0.0 } - } - - fn add(&mut self, number: f64) { - self.result += number; - } - - fn subtract(&mut self, number: f64) { - self.result -= number; - } - - fn multiply(&mut self, number: f64) { - self.result *= number; - } - - fn divide(&mut self, number: f64) { - if number != 0.0 { - self.result /= number; - } else { - println!("Cannot divide by zero."); - } - } - - fn reset(&mut self) { - self.result = 0.0; - } - - fn get_result(&self) -> f64 { - self.result - } - - fn<|fim|> -} -`, - llmOutput: ` divide(&mut self, number: f64) { - if number != 0.0 { - self.result /= number; - } else { - println!("Cannot divide by zero."); - } -}`, - expectedCompletion: ` divide(&mut self, number: f64) { - if number != 0.0 { - self.result /= number; - } else { - println!("Cannot divide by zero."); - } -}`, - }, - { - description: "Should autocomplete Rust match arms", - filename: "main.rs", - input: ` -fn get_status_code_description(code: u16) -> &'static str { - match code { - 200 => "OK", - 404 => "Not Found", - 500 => "Internal Server Error", - <|fim|> - } -} -`, - llmOutput: `403 => "Forbidden", - 401 => "Unauthorized", - _ => "Unknown Status", -`, - expectedCompletion: `403 => "Forbidden", - 401 => "Unauthorized", - _ => "Unknown Status", -`, - }, - { - description: "Should autocomplete Rust struct definition", - filename: "main.rs", - input: ` -struct User { - id: u32, - username: String, - email: String, - is_active: bool, - <|fim|> -} - -impl User { - fn new(id: u32, username: String, email: String) -> Self { - User { - id, - username, - email, - is_active: true, - } - } -} -`, - llmOutput: `created_at: String, - updated_at: String,`, - expectedCompletion: `created_at: String, - updated_at: String,`, - }, - { - description: "Haskell: Nested pattern matching with let bindings", - filename: "NestedPattern.hs", - input: `module NestedPattern where - -data Tree a = Leaf a | Node (Tree a) (Tree a) - -sumTree :: Num a => Tree a -> a -sumTree (Leaf x) = x -sumTree (Node left right) = - let leftSum = <|fim|> - rightSum = sumTree right - in leftSum + rightSum`, - llmOutput: `sumTree left`, - expectedCompletion: `sumTree left`, - }, - { - description: "Haskell: Complex function with where clause and guards", - filename: "QuadraticSolver.hs", - input: `module QuadraticSolver where - -solveQuadratic :: (Ord a, Floating a) => a -> a -> a -> Maybe (a, a) -solveQuadratic a b c - | discriminant < 0 = Nothing - | otherwise = Just (x1, x2) - where - discriminant = b^2 - 4*a*c - sqrtD = sqrt discriminant - x1 = (-b + sqrtD) / (2*a) - <|fim|> = (-b - sqrtD) / (2*a)`, - llmOutput: `x2`, - expectedCompletion: `x2`, - }, - { - description: "Haskell: List comprehension with complex filter", - filename: "PrimeNumbers.hs", - input: `module PrimeNumbers where - -primesUpTo :: Int -> [Int] -primesUpTo n = [x | x <- [2..n], isPrime x] - where isPrime num = <|fim|> && all (\d -> num \`mod\` d /= 0) [2..(floor . sqrt $ fromIntegral num)]`, - llmOutput: `num > 1`, - expectedCompletion: `num > 1`, - }, - { - description: "Should autocomplete Dart class methods", - filename: "calculator.dart", - input: ` -class Calculator { - double result = 0.0; - - void add(double number) { - result += number; - } - - void multiply(double number) { - result *= number; - } - - <|fim|> - - double getResult() { - return result; - } -}`, - llmOutput: `void subtract(double number) { - result -= number; - }`, - expectedCompletion: `void subtract(double number) { - result -= number; - }`, - }, - { - description: "Should handle string interpolation in Dart", - filename: "greetings.dart", - input: ` -void main() { - var name = "World"; - print('Hello, <|fim|>!'); -}`, - llmOutput: `\${name}`, - expectedCompletion: `\${name}`, - }, - { - description: "Should autocomplete within a Dart function body", - filename: "counter.dart", - input: ` -class Counter { - int count = 0; - - void increment() { - count++; - } - - void decrement() { - <|fim|> - - void reset() { - count = 0; - } -}`, - llmOutput: `count--;`, - expectedCompletion: `count--;`, - }, - { - description: - "Should autocomplete Clojure function definition with missing closing parenthesis", - input: `(defn calculate-sum [a b] - (let [sum (+ a b)] - (println "The sum is" sum) - sum<|fim|>`, - llmOutput: `))`, - expectedCompletion: `))`, - filename: "test.clj", - }, - { - description: - "Should autocomplete missing part of a Clojure map within a function", - input: `(defn get-user [] - {:username "johndoe" - :email "johndoe@example.com" - :age 30 - <|fim|> - (println "User information loaded"))`, - llmOutput: `:location "Unknown"}`, - expectedCompletion: `:location "Unknown"}`, - filename: "test.clj", - }, - { - description: - "Should autocomplete inside a Clojure vector within a looping construct", - input: `(defn odd-numbers [] - (loop [nums [1 3 5<|fim|> 9 11]] - (when (seq nums) - (println (first nums)) - (recur (rest nums)))))`, - llmOutput: ` 7,`, - expectedCompletion: ` 7,`, - filename: "test.clj", - }, - { - description: "Should autocomplete R function definition", - filename: "calculate.R", - input: ` -calculate_mean <- function(numbers) { - total <- sum(numbers) - <|fim|> -}`, - llmOutput: `mean_value <- total / length(numbers) - return(mean_value)`, - expectedCompletion: `mean_value <- total / length(numbers) - return(mean_value)`, - }, - { - description: "Should complete R loop and print statement", - filename: "loopPrint.R", - input: ` -numbers <- c(1, 2, 3, 4, 5) -for (number in numbers) { - print(<|fim|>) -}`, - llmOutput: `number)`, - expectedCompletion: `number)`, - }, - { - description: "Should autocomplete R data frame creation", - filename: "dataFrame.R", - input: ` -data <- data.frame( - Name = c("Alice", "Bob", "Charlie"), - Age = c(25, 30, 35), - <|fim|> -)`, - llmOutput: `Height = c(165, 180, 175)`, - expectedCompletion: `Height = c(165, 180, 175)`, - }, - { - description: "Should autocomplete R if-else statement", - filename: "condition.R", - input: ` -grade <- 85 -if (grade >= 90) { - print("A") -} else if (grade >= 80) { - <|fim|> -} else { - print("C") -}`, - llmOutput: `print("B")`, - expectedCompletion: `print("B")`, - }, - { - description: "Should autocomplete R ggplot2 plot structure", - filename: "plot.R", - input: ` -library(ggplot2) - -ggplot(data=mtcars, aes(x=wt, y=mpg)) + - geom_point() + - <|fim|>`, - llmOutput: `geom_smooth(method='lm', se=FALSE)`, - expectedCompletion: `geom_smooth(method='lm', se=FALSE)`, - }, - { - description: "Should autocomplete Scala class with a method", - filename: "Person.scala", - input: `class Person(val name: String, val age: Int) { - def greet(): String = { - <|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."`, - }, - - { - description: "Should handle Scala case class with a missing field", - filename: "Person.scala", - input: `case class Address(city: String, postalCode: String) - case class Person(name: String, age: Int, address: Address) - - val alice = Person("Alice", 30, Address("Wonderland", <|fim|>))`, - llmOutput: `"12345")`, - expectedCompletion: `"12345")`, - }, - - { - description: "Should autocomplete Scala function with missing body bracket", - filename: "Math.scala", - input: `object MathUtils { - def add(a: Int, b: Int): Int = { - a + b<|fim|> - - def multiply(a: Int, b: Int): Int = { - a * b - } - } - - object Main extends App { - println(MathUtils.add(3, 5)) - println(MathUtils.multiply(4, 6)) - }`, - llmOutput: ` - }`, - expectedCompletion: ` - }`, - }, - { - description: "Should autocomplete C function definition", - filename: "math_utils.c", - input: `#include - -int add(int a, int b) { - return a + b; -} - -int multiply(int a, int b) { - return a * b; -} - -int subtract(int a, int b) { - <|fim|> -} - -int main() { - printf("Result: %d", add(2, 3)); - return 0; -}`, - llmOutput: `return a - b;`, - expectedCompletion: `return a - b;`, - }, - - { - description: "Should handle C struct with missing field initialization", - filename: "person.c", - input: `#include - -typedef struct { - char name[50]; - int age; - float height; -} Person; - -int main() { - Person alice = {"Alice", 30, <|fim|>}; - printf("Name: %s, Age: %d, Height: %.2f", alice.name, alice.age, alice.height); - return 0; -}`, - llmOutput: `5.5`, - expectedCompletion: `5.5`, - }, - - { - description: "Should autocomplete C function with missing body bracket", - filename: "area.c", - input: `#include - -double calculateCircleArea(double radius) { - const double pi = 3.14159; - return pi * radius * radius;<|fim|> - -double calculateRectangleArea(double length, double width) { - return length * width; -} - -int main() { - printf("Circle Area: %.2f", calculateCircleArea(5.0)); - printf("Rectangle Area: %.2f", calculateRectangleArea(4.0, 6.0)); - return 0; -}`, - llmOutput: ` -}`, - expectedCompletion: ` -}`, - }, - { - description: "Should autocomplete a simple Kotlin function declaration", - filename: "simpleFunction.kt", - input: ` -fun main() { - println("Hello, World!") -} - -fun calculateArea(length: Double, width: Double): Double <|fim|>`, - llmOutput: `{ - return length * width -}`, - expectedCompletion: `{ - return length * width -}`, - }, - { - description: "Should handle autocomplete inside a Kotlin data class", - filename: "dataClass.kt", - input: ` -data class User( - val id: Int, - val name: String, - val email: String, - <|fim|> -)`, - llmOutput: `val age: Int`, - expectedCompletion: `val age: Int`, - }, - { - description: - "Should complete Kotlin if-else structure with missing brackets", - filename: "controlStructure.kt", - input: ` -fun getMax(a: Int, b: Int): Int { - if (a > b<|fim|> - } else { - return b - } -}`, - llmOutput: `) { - return a`, - expectedCompletion: `) { - return a`, - }, - { - description: "Should autocomplete Solidity function definition", - filename: "SimpleStorage.sol", - input: ` -pragma solidity ^0.8.0; - -contract SimpleStorage { - uint private data; - - function set(uint x) public { - data = x; - } - - function get() public view returns (uint) { - <|fim|> - } -} - `, - llmOutput: `return data;`, - expectedCompletion: `return data;`, - }, - - { - description: "Should autocomplete Solidity event with parameters", - filename: "EventExample.sol", - input: ` -pragma solidity ^0.8.0; - -contract EventExample { - event DataStored(uint indexed id, string content); - - function storeData(uint id, string memory content) public { - emit DataStored(<|fim|>); - } -} - `, - llmOutput: `id, content`, - expectedCompletion: `id, content`, - }, - - { - description: "Should handle Solidity struct definition completion", - filename: "StructDefinition.sol", - input: ` -pragma solidity ^0.8.0; - -contract StructExample { - struct Person { - string name; - uint age; - address wallet; - } - - Person[] private people; - - function addPerson(string memory name, uint age, address wallet) public { - people.push(Person(name, age, wallet)); - } - - function getFirstPerson<|fim|> -} - `, - llmOutput: `() public view returns (string memory, uint, address) { - if (people.length > 0) { - Person storage person = people[0]; - return (person.name, person.age, person.wallet); - } - return ("", 0, address(0)); - }`, - expectedCompletion: `() public view returns (string memory, uint, address) { - if (people.length > 0) { - Person storage person = people[0]; - return (person.name, person.age, person.wallet); - } - return ("", 0, address(0)); - }`, - }, - { - description: "Should autocomplete TypeScript interface properties", - filename: "User.ts", - input: ` -interface User { - id: number; - name: string; - e<|fim|> -} -`, - llmOutput: `mail: string; - age: number; -}`, - expectedCompletion: `mail: string; - age: number; -}`, - }, - - { - description: - "Should autocomplete a TypeScript arrow function inside a variable assignment", - filename: "mathOperations.ts", - input: ` -const addNumbers = (a: number, b: number): number => { - return a + b; -}; - -const multiplyNumbers = (a: number, b: number): number => { - re<|fim|> -} - -console.log(multiplyNumbers(2, 3)); -`, - llmOutput: `turn a * b;`, - expectedCompletion: `turn a * b;`, - }, - - { - description: - "Should handle autocomplete inside a nested TypeScript class method", - filename: "Account.ts", - input: ` -class Account { - private balance: number = 0; - - deposit(amount: number) { - this.balance += amount; - return this.balance; - } - - withdraw(amount: number) { - if (amount > this.balance) { - throw new Error("Insufficient funds"); - } - this.balance -= amount; - return thi<|fim|> - } -} -`, - llmOutput: `s.balance;`, - expectedCompletion: `s.balance;`, - }, - - { - description: "Should autocomplete a TypeScript generic function", - filename: "GenericFunction.ts", - input: ` -function identity(arg: T): T { - return ar<|fim|> -} - -console.log(identity(5)); -`, - llmOutput: `g;`, - expectedCompletion: `g;`, - }, - - { - description: - "Should autocomplete a TypeScript promise within an asynchronous function", - filename: "asyncFunction.ts", - input: ` -async function fetchData(url: string): Promise { - const response = await fetch(url); - <|fim|> - return data; -} - -fetchData('https://api.example.com/data'); -`, - llmOutput: `const data = await response.json();`, - expectedCompletion: `const data = await response.json();`, - }, - - { - description: - "Should autocomplete a C# class with a constructor and property", - filename: "Person.cs", - input: `using System; - -public class Person -{ - public string Name { get; set; } - public int Age { get; set; } - - public Person(string name, int <|fim|> -}`, - llmOutput: `age) - { - Name = name; - Age = age; - }`, - expectedCompletion: `age) - { - Name = name; - Age = age; - }`, - }, - { - description: "Should autocomplete a C# interface method", - filename: "IGreetable.cs", - input: `public interface IGreetable -{ - void <|fim|> -}`, - llmOutput: `Greet();`, - expectedCompletion: `Greet();`, - }, - { - description: "Should autocomplete inside C# method with if condition", - filename: "Calculator.cs", - input: `using System; - -public class Calculator -{ - public int Add(int a, int b) - { - if(<|fim|>) - { - return a + b; - } - return 0; - } -}`, - llmOutput: `a > 0 && b > 0`, - expectedCompletion: `a > 0 && b > 0`, - }, - { - description: "Should complete a simple Julia function", - filename: "simpleFunction.jl", - input: `function calculate_area(length, width) - <|fim|> -end -`, - llmOutput: `return length * width`, - expectedCompletion: `return length * width`, - }, - { - description: "Should autocomplete Julia for loop", - filename: "loop.jl", - input: `numbers = [1, 2, 3, 4, 5] -squared_numbers = [] - -for num in numbers - <|fim|> -end - -println(squared_numbers) -`, - llmOutput: `push!(squared_numbers, num^2)`, - expectedCompletion: `push!(squared_numbers, num^2)`, - }, - { - description: "Should complete a Julia struct definition", - filename: "structDefinition.jl", - input: `struct Person - first_name::String - last_name::String - age::Int - address::Address -end - -struct Address - street::String - city::String - <|fim|> -end -`, - llmOutput: `state::String - zip_code::String`, - expectedCompletion: `state::String - zip_code::String`, - }, - { - description: "Should complete a Julia dictionary access", - filename: "dictionary.jl", - input: `grades = Dict("Alice" => 90, "Bob" => 85, "Eve" => 88) - -function get_grade(student_name) - return grades[<|fim|>] -end - -println(get_grade("Alice")) # Should print 90 -`, - llmOutput: `student_name`, - expectedCompletion: `student_name`, - }, - { - description: "Should complete a Julia module declaration", - filename: "moduleDeclaration.jl", - input: `module MathOperations - -export add, subtract - -function add(a, b) - return a + b -end - -function subtract(a, b) - return a - b -end - -<|fim|> -`, - llmOutput: `end`, - expectedCompletion: `end`, - }, - { - description: "Should complete F# let-binding with function definition", - filename: "mathModule.fs", - input: `module MathModule - -let calculateArea length width = - <|fim|>`, - llmOutput: `length * width`, - expectedCompletion: `length * width`, - }, - - { - description: "Should complete incomplete F# type definition", - filename: "personType.fs", - input: `type Person = { - FirstName: string - LastName: string - Age: int<|fim|> -} - -let john = { FirstName = "John"; LastName = "Doe"; Age = 30 }`, - llmOutput: ` - Address: string -}`, - expectedCompletion: ` - Address: string -}`, - }, - - { - description: "Should complete F# pattern matching expression", - filename: "patternMatching.fs", - input: `let describeNumber number = - match number with - | 0 -> "Zero" - | 1 -> "One" - | <|fim|>`, - llmOutput: `2 -> "Two" - | _ -> "Other"`, - expectedCompletion: `2 -> "Two" - | _ -> "Other"`, - }, - - { - description: "Should complete F# list comprehension expression", - filename: "listComprehension.fs", - input: `let squares = [ for x in 1..10 -> x * x ] -let evenSquares = [ for x in squares do if x % 2 = 0 then yield x ] -let oddSquares = [<|fim|>]`, - llmOutput: ` for x in squares do if x % 2 <> 0 then yield x ]`, - expectedCompletion: ` for x in squares do if x % 2 <> 0 then yield x ]`, - }, - - { - description: "Should complete an F# recursive function", - filename: "recursiveFunctions.fs", - input: `let rec factorial n = - if n <= 1 then 1 - else n <|fim|> factorial (n - 1)`, - llmOutput: ` * `, - expectedCompletion: ` * `, - }, - - { - description: "Should complete F# member method inside a class type", - filename: "bankAccount.fs", - input: `type BankAccount(owner: string, initialBalance: float) = - let mutable balance = initialBalance - - member this.Deposit amount = - balance <- balance + amount - this - <|fim|>`, - llmOutput: ` - member this.Withdraw amount = - if amount > balance then - failwith "Insufficient funds" - balance <- balance - amount - this`, - expectedCompletion: ` - member this.Withdraw amount = - if amount > balance then - failwith "Insufficient funds" - balance <- balance - amount - this`, - }, - - { - description: "Should complete F# async workflow function", - filename: "asyncWorkflow.fs", - input: `let fetchDataAsync url = - async { - use client = new System.Net.Http.HttpClient() - <|fim|> - }`, - llmOutput: `let! response = client.GetStringAsync(url) - return response`, - expectedCompletion: `let! response = client.GetStringAsync(url) - return response`, - }, - { - description: "Should autocomplete SCSS nested class starting inside a rule", - filename: "styles.scss", - input: `nav { - display: flex; - justify-content: space-between; - .logo { - font-size: 1.5rem; - color: #333; - - .brand<|fim|> - } - - ul { - list-style: none; - display: flex; - gap: 1rem; - } -}`, - llmOutput: `-name { - font-weight: bold; - text-transform: uppercase; -}`, - expectedCompletion: `-name { - font-weight: bold; - text-transform: uppercase; -}`, - }, - - { - description: "Should handle SCSS mixin within a class", - filename: "styles.scss", - input: `.card { - border: 1px solid #ccc; - padding: 10px; - - @include<|fim|> - - &:hover { - box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); - } -}`, - llmOutput: ` transition(all 0.3s ease);`, - expectedCompletion: ` transition(all 0.3s ease);`, - }, - - { - description: - "Should autocomplete SCSS variable in the middle of a statement", - filename: "styles.scss", - input: `$primary-color: #007bff; -$secondary-color: #6c757d; - -.button { - background-color: <|fim|> color; - padding: 10px 15px; - border: none; - color: #fff; - border-radius: 4px; -}`, - llmOutput: `$primary-`, - expectedCompletion: `$primary-`, - }, - { - description: "Should autocomplete Vue component method", - filename: "MyComponent.vue", - input: ` - - -`, - llmOutput: `() { - this.count = 0; - }`, - expectedCompletion: `() { - this.count = 0; - }`, - }, - { - description: "Should autocomplete Vue computed property", - filename: "UserComponent.vue", - input: ` - - -`, - llmOutput: `() { - return this.firstName + ' ' + this.lastName; - }`, - expectedCompletion: `() { - return this.firstName + ' ' + this.lastName; - }`, - }, - { - description: "Should autocomplete Vue method using props", - filename: "TodoItem.vue", - input: ` - - -`, - llmOutput: `this.completed`, - expectedCompletion: `this.completed`, - }, - { - description: "Should autocomplete Svelte reactive statement", - filename: "Counter.svelte", - input: ` - - - -`, - llmOutput: `doubledCount = count * 2`, - expectedCompletion: `doubledCount = count * 2`, - }, - - { - description: "Should autocomplete Svelte component inside HTML", - filename: "NestedComponent.svelte", - input: ` - - -
-

Hello Svelte

- /> -
-`, - llmOutput: `name="World"`, - expectedCompletion: `name="World"`, - }, - - { - description: "Should handle autocomplete in Svelte each block", - filename: "List.svelte", - input: ` - - -
    - {#each items as item} -
  • {item}
  • - {/each<|fim|> -
-`, - llmOutput: `}`, - expectedCompletion: `}`, - }, -]; diff --git a/core/autocomplete/test/util.ts b/core/autocomplete/test/util.ts deleted file mode 100644 index bfcf31885..000000000 --- a/core/autocomplete/test/util.ts +++ /dev/null @@ -1,75 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import Mock from "../../llm/llms/Mock"; -import { testConfigHandler, testIde } from "../../test/util/fixtures"; -import { CompletionProvider } from "../CompletionProvider"; -import { AutocompleteInput } from "../util/types"; - -const FIM_DELIMITER = "<|fim|>"; - -function parseFimExample(text: string): { prefix: string; suffix: string } { - const [prefix, suffix] = text.split(FIM_DELIMITER); - return { prefix, suffix }; -} - -export interface AutocompleteFileringTestInput { - description: string; - filename: string; - input: string; - llmOutput: string; - expectedCompletion: string | null; - options?: { - only?: boolean; - }; -} - -export async function testAutocompleteFiltering( - test: AutocompleteFileringTestInput, -) { - const { prefix, suffix } = parseFimExample(test.input); - - // Setup necessary objects - const llm = new Mock({ - model: "mock", - }); - llm.completion = test.llmOutput; - const ide = testIde; - const configHandler = testConfigHandler; - - // Create a real file - const [workspaceDir] = await ide.getWorkspaceDirs(); - const filepath = path.join(workspaceDir, test.filename); - fs.writeFileSync(filepath, test.input.replace(FIM_DELIMITER, "")); - - // Prepare completion input and provider - const completionProvider = new CompletionProvider( - configHandler, - ide, - async () => llm, - () => {}, - async () => [], - ); - - const line = prefix.split("\n").length - 1; - const character = prefix.split("\n")[line].length; - const autocompleteInput: AutocompleteInput = { - clipboardText: "", - completionId: "test-completion-id", - filepath, - pos: { - line, - character, - }, - recentlyEditedFiles: [], - recentlyEditedRanges: [], - }; - - // Generate a completion - const result = await completionProvider.provideInlineCompletionItems( - autocompleteInput, - undefined, - ); - - // Ensure that we return the text that is wanted to be displayed - expect(result?.completion).toEqual(test.expectedCompletion); -} From 9404ba5171b75cf90d3038adb00624da0ebeeab8 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 5 Nov 2024 11:12:21 +0700 Subject: [PATCH 36/43] test: set up and tear down test dir --- core/autocomplete/filtering/test/filter.test.ts | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/core/autocomplete/filtering/test/filter.test.ts b/core/autocomplete/filtering/test/filter.test.ts index 171b1cb44..04b5a193a 100644 --- a/core/autocomplete/filtering/test/filter.test.ts +++ b/core/autocomplete/filtering/test/filter.test.ts @@ -3,6 +3,7 @@ import { testAutocompleteFiltering, } from "./util"; import { TEST_CASES } from "./testCases"; +import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir"; const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { if (tests.some((test) => test.options?.only)) { @@ -13,6 +14,15 @@ const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { }; describe("llms/Mock", () => { + beforeAll(async () => { + tearDownTestDir(); + setUpTestDir(); + }); + + afterAll(async () => { + tearDownTestDir(); + }); + describe("Autocomplete Filtering Tests", () => { beforeEach(async () => { await new Promise((resolve) => setTimeout(resolve, 50)); From dca5927bcfdd22fddd853909bb145cfc5d27ac01 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Tue, 5 Nov 2024 11:27:55 +0700 Subject: [PATCH 37/43] improv: fix failing autocomplete test cases --- core/autocomplete/CompletionProvider.ts | 19 +- .../classification/shouldCompleteMultiline.ts | 28 +- .../constants/AutocompleteLanguageInfo.ts | 23 +- .../StreamTransformPipeline.ts | 14 +- .../filtering/streamTransforms/lineStream.ts | 37 +- .../filtering/test/filter.test.ts | 21 +- core/autocomplete/filtering/test/testCases.ts | 365 +++++++++--------- core/autocomplete/postprocessing/index.ts | 29 +- core/autocomplete/prefiltering/index.ts | 12 +- core/util/ranges.ts | 2 +- 10 files changed, 277 insertions(+), 273 deletions(-) diff --git a/core/autocomplete/CompletionProvider.ts b/core/autocomplete/CompletionProvider.ts index 2c7950288..cb162043a 100644 --- a/core/autocomplete/CompletionProvider.ts +++ b/core/autocomplete/CompletionProvider.ts @@ -180,12 +180,11 @@ export class CompletionProvider { this.contextRetrievalService, ); - const { - prompt, - prefix: finalPrefix, - suffix: finalSuffix, - completionOptions, - } = renderPrompt(snippets, await this.ide.getWorkspaceDirs(), helper); + const { prompt, prefix, suffix, completionOptions } = renderPrompt( + snippets, + await this.ide.getWorkspaceDirs(), + helper, + ); // Completion let completion: string | undefined = ""; @@ -207,8 +206,8 @@ export class CompletionProvider { this.completionStreamer.streamCompletionWithFilters( token, llm, - finalPrefix, - finalSuffix, + prefix, + suffix, prompt, multiline, completionOptions, @@ -243,8 +242,8 @@ export class CompletionProvider { const outcome: AutocompleteOutcome = { time: Date.now() - startTime, completion, - prefix: finalPrefix, - suffix: finalSuffix, + prefix, + suffix, prompt, modelProvider: llm.providerName, modelName: llm.model, diff --git a/core/autocomplete/classification/shouldCompleteMultiline.ts b/core/autocomplete/classification/shouldCompleteMultiline.ts index 16d2a6c47..75cfdcd70 100644 --- a/core/autocomplete/classification/shouldCompleteMultiline.ts +++ b/core/autocomplete/classification/shouldCompleteMultiline.ts @@ -10,8 +10,7 @@ function shouldCompleteMultilineBasedOnLanguage( prefix: string, suffix: string, ) { - let langMultilineDecision = language.useMultiline?.({ prefix, suffix }); - return langMultilineDecision; + return language.useMultiline?.({ prefix, suffix }) ?? true; } export function shouldCompleteMultiline(helper: HelperVars) { @@ -29,13 +28,14 @@ export function shouldCompleteMultiline(helper: HelperVars) { return true; } - // Don't complete multi-line if you are mid-line - if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) { - return false; - } + // // Don't complete multi-line if you are mid-line + // if (isMidlineCompletion(helper.fullPrefix, helper.fullSuffix)) { + // return false; + // } // Don't complete multi-line for single-line comments if ( + helper.lang.singleLineComment && helper.fullPrefix .split("\n") .slice(-1)[0] @@ -45,15 +45,9 @@ export function shouldCompleteMultiline(helper: HelperVars) { return false; } - if ( - shouldCompleteMultilineBasedOnLanguage( - helper.lang, - helper.prunedPrefix, - helper.prunedSuffix, - ) - ) { - return true; - } - - return false; + return shouldCompleteMultilineBasedOnLanguage( + helper.lang, + helper.prunedPrefix, + helper.prunedSuffix, + ); } diff --git a/core/autocomplete/constants/AutocompleteLanguageInfo.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts index 397d32ed6..88ba93aa9 100644 --- a/core/autocomplete/constants/AutocompleteLanguageInfo.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -3,14 +3,11 @@ import { LineFilter } from "../filtering/streamTransforms/lineStream"; export interface AutocompleteLanguageInfo { name: string; topLevelKeywords: string[]; - singleLineComment: string; + singleLineComment?: string; endOfLine: string[]; stopWords?: string[]; lineFilters?: LineFilter[]; - useMultiline?: (args: { - prefix: string; - suffix: string; - }) => boolean | undefined; + useMultiline?: (args: { prefix: string; suffix: string }) => boolean; } // TypeScript @@ -256,10 +253,8 @@ export const YAML: AutocompleteLanguageInfo = { } else { seenListItem = true; } - yield line; - } else { - yield line; } + yield line; } }, // Don't allow consecutive lines of same key @@ -268,12 +263,14 @@ export const YAML: AutocompleteLanguageInfo = { for await (const line of lines) { if (line.includes(":")) { const key = line.split(":")[0]; - if (key !== lastKey) { + if (key === lastKey) { + break; + } else { yield line; lastKey = key; - } else { - break; } + } else { + yield line; } } }, @@ -289,7 +286,7 @@ export const Markdown: AutocompleteLanguageInfo = { const singleLineStarters = ["- ", "* ", /^\d+\. /, "> ", "```", /^#{1,6} /]; let currentLine = prefix.split("\n").pop(); if (!currentLine) { - return undefined; + return true; } currentLine = currentLine.trim(); for (const starter of singleLineStarters) { @@ -301,7 +298,7 @@ export const Markdown: AutocompleteLanguageInfo = { return false; } } - return undefined; + return true; }, }; diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 037059912..6b3262192 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -28,13 +28,13 @@ export class StreamTransformPipeline { let charGenerator = generator; charGenerator = stopAtStopTokens(generator, stopTokens); - charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( - charGenerator, - prefix, - suffix, - helper.filepath, - multiline, - ); + // charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( + // charGenerator, + // prefix, + // suffix, + // helper.filepath, + // multiline, + // ); let lineGenerator = streamLines(charGenerator); diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index dffca36b9..e305062cf 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -14,14 +14,6 @@ function isBracketEnding(line: string): boolean { .some((char) => BRACKET_ENDING_CHARS.includes(char)); } -function commonPrefixLength(a: string, b: string): number { - let i = 0; - while (i < a.length && i < b.length && a[i] === b[i]) { - i++; - } - return i; -} - function isEnglishFirstLine(line: string) { line = line.trim().toLowerCase(); @@ -130,7 +122,7 @@ export async function* noTopLevelKeywordsMidline( */ export async function* avoidPathLine( stream: LineStream, - comment: string, + comment?: string, ): LineStream { // Snippets are inserted as comments with a line at the start '// Path: '. // Sometimes the model with copy this pattern, which is unwanted @@ -151,14 +143,13 @@ export async function* avoidPathLine( */ export async function* avoidEmptyComments( stream: LineStream, - comment: string, + comment?: string, ): LineStream { // Filter lines that are empty comments for await (const line of stream) { - if (line.trim() === comment) { - continue; + if (!comment || line.trim() !== comment) { + yield line; } - yield line; } } @@ -187,9 +178,7 @@ export async function* streamWithNewLines(stream: LineStream): LineStream { * @returns {boolean} True if the lines are considered repeated, false otherwise. * * @description - * This function checks if two lines are repeated or very similar based on two criteria: - * 1. They have a common prefix longer than 12 characters. - * 2. The Levenshtein distance between them is less than 10% of the length of the second line. + * This function checks if the Levenshtein distance between them is less than 10% of the length of the second line. * Lines shorter than 5 characters are never considered repeated. */ export function lineIsRepeated(a: string, b: string): boolean { @@ -199,10 +188,7 @@ export function lineIsRepeated(a: string, b: string): boolean { const aTrim = a.trim(); const bTrim = b.trim(); - return ( - commonPrefixLength(aTrim, bTrim) > 12 || - distance(aTrim, bTrim) / bTrim.length < 0.1 - ); + return distance(aTrim, bTrim) / bTrim.length < 0.05; } /** @@ -229,9 +215,9 @@ export async function* stopAtSimilarLine( const lineIsBracketEnding = isBracketEnding(trimmedLine); for await (const nextLine of stream) { - if (nextLine === line) { - fullStop(); - break; + if (trimmedLine === "") { + yield nextLine; + continue; } if (lineIsBracketEnding && trimmedLine.trim() === nextLine.trim()) { @@ -239,6 +225,11 @@ export async function* stopAtSimilarLine( continue; } + if (nextLine === line) { + fullStop(); + break; + } + if (lineIsRepeated(nextLine, trimmedLine)) { fullStop(); break; diff --git a/core/autocomplete/filtering/test/filter.test.ts b/core/autocomplete/filtering/test/filter.test.ts index 04b5a193a..62ef65512 100644 --- a/core/autocomplete/filtering/test/filter.test.ts +++ b/core/autocomplete/filtering/test/filter.test.ts @@ -2,7 +2,7 @@ import { AutocompleteFileringTestInput, testAutocompleteFiltering, } from "./util"; -import { TEST_CASES } from "./testCases"; +import { TEST_CASES_WITH_DIFF, TEST_CASES_WITHOUT_DIFF } from "./testCases"; import { setUpTestDir, tearDownTestDir } from "../../../test/util/testDir"; const filterTestCases = (tests: AutocompleteFileringTestInput[]) => { @@ -29,12 +29,21 @@ describe("llms/Mock", () => { }); describe("Should return unmodified LLM output", () => { - it.each(filterTestCases(TEST_CASES))("$description", async (testCase) => { - await testAutocompleteFiltering(testCase); - }); + it.each(filterTestCases(TEST_CASES_WITHOUT_DIFF))( + "$description", + async (testCase) => { + await testAutocompleteFiltering(testCase); + }, + ); }); - // TODO: Add test cases where modifying LLM output is desirable - describe.skip("Should return modified LLM output", () => {}); + describe("Should return modified LLM output", () => { + it.each(filterTestCases(TEST_CASES_WITH_DIFF))( + "$description", + async (testCase) => { + await testAutocompleteFiltering(testCase); + }, + ); + }); }); }); diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index c3c19dfea..1f0397363 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -1,7 +1,180 @@ import { dedent } from "../../../util"; import { AutocompleteFileringTestInput } from "./util"; -export const TEST_CASES: AutocompleteFileringTestInput[] = [ +export const TEST_CASES_WITH_DIFF: AutocompleteFileringTestInput[] = [ + { + description: "Should handle python multi-line string", + filename: "test.py", + input: `def create_greeting(name): + greeting = """Hello, """ + name + """! +Welcome to our community. We hope you have a great time here. +If you have any questions, feel free to reach out.""" + return greeting + +message = create_greeting("Alice") +print(message) + +multi_line_message = """<|fim|> +print(multi_line_message) +`, + llmOutput: `This is a multi-line message. +It continues across multiple lines, +which allows for easy reading and formatting. +""" +`, + expectedCompletion: `This is a multi-line message. +It continues across multiple lines, +which allows for easy reading and formatting. +"""`, + }, + { + description: "Should autocomplete Rust match arms", + filename: "main.rs", + input: ` +fn get_status_code_description(code: u16) -> &'static str { + match code { + 200 => "OK", + 404 => "Not Found", + 500 => "Internal Server Error", + <|fim|> + } +} +`, + llmOutput: `403 => "Forbidden", + 401 => "Unauthorized", + _ => "Unknown Status", +`, + expectedCompletion: `403 => "Forbidden", + 401 => "Unauthorized", + _ => "Unknown Status",`, + }, + { + description: "Should complete a Markdown code block", + filename: "test.md", + input: ` +Here is a sample JavaScript function: + +\`\`\`javascript +function sayHello() { + console.log("Hello, <|fim|> +} +\`\`\` +`, + llmOutput: `world!"); +`, + expectedCompletion: `world!");`, + }, + { + description: "Should autocomplete Java when inside a block", + filename: "Main.java", + input: ` +public class Main { + public static void main(String[] args) { + for (int i = 0; i < 10; i++) { + if (i % 2 == 0) { + System.out.println("Even: " + i); + } else { +<|fim|> + } + } + } +}`, + llmOutput: ` + System.out.println("Odd: " + i); +`, + expectedCompletion: ` + System.out.println("Odd: " + i);`, + }, + { + description: + "Should autocomplete a Markdown heading and preserve formatting", + filename: "test.md", + input: `# My Document + +## Introduction +This is a sample document for testing. + +## <|fim|> +### Conclusion +Thank you for reading. +`, + llmOutput: `Features +Here is a list of features: +- Feature 1 +- Feature 2 +`, + expectedCompletion: `Features +Here is a list of features: +- Feature 1 +- Feature 2`, + }, + { + description: "Should autocomplete a Java method within a class", + filename: "Calculator.java", + input: ` +public class Calculator { + private double result; + + public Calculator() { + this.result = 0.0; + } + + public void add(double number) { + result += number; +<|fim|>`, + llmOutput: ` + } + + public void subtract(double number) { + result -= number; + } +`, + expectedCompletion: ` + } + + public void subtract(double number) { + result -= number; + }`, + }, + { + description: "Should filter out consecutive, repeated YAML keys", + filename: "test.yaml", + input: ` + version: '3' + services: + db: + image: postgres + environment: + POSTGRES_USER: user + POSTGRES_PASSWORD: pass<|fim|> + `, + llmOutput: ` + POSTGRES_DB: mydb + POSTGRES_DB: mydb + `, + expectedCompletion: ` + POSTGRES_DB: mydb + `, + }, + { + description: "Should autocomplete a Markdown list with nested items", + filename: "test.md", + input: ` +- Item 1 +- Item 2 + - Subitem 1 + <|fim|> +- Item 3 +`, + llmOutput: ` - Subitem 2 + - Subitem 3 +`, + expectedCompletion: ` - Subitem 2 + - Subitem 3`, + }, +]; + +export const TEST_CASES_WITHOUT_DIFF: AutocompleteFileringTestInput[] = [ { description: "should pass", filename: "test.js", @@ -412,32 +585,6 @@ print(odd_squares) llmOutput: `x for x in squares if x % 2 != 0`, expectedCompletion: `x for x in squares if x % 2 != 0`, }, - { - description: "Should handle python multi-line string", - filename: "test.py", - input: `def create_greeting(name): - greeting = """Hello, """ + name + """! -Welcome to our community. We hope you have a great time here. -If you have any questions, feel free to reach out.""" - return greeting - -message = create_greeting("Alice") -print(message) - -multi_line_message = """<|fim|> -print(multi_line_message) -`, - llmOutput: `This is a multi-line message. -It continues across multiple lines, -which allows for easy reading and formatting. -""" -`, - expectedCompletion: `This is a multi-line message. -It continues across multiple lines, -which allows for easy reading and formatting. -""" -`, - }, { description: "Should autocomplete a simple Go function declaration", filename: "simpleFunction.go", @@ -511,19 +658,6 @@ func main() { expectedCompletion: ` }`, }, - { - description: - "Should autocomplete SQL query with subquery and alias in SELECT clause", - filename: "complex_query.sql", - input: `SELECT u.id, - u.name, - (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count - 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)`, - }, { description: "Should autocomplete SQL query with nested functions and missing bracket", @@ -536,6 +670,19 @@ func main() { llmOutput: `8.5)`, expectedCompletion: `8.5)`, }, + { + description: + "Should autocomplete SQL query with subquery and alias in SELECT clause", + filename: "complex_query.sql", + input: `SELECT u.id, + u.name, + (SELECT COUNT(*) FROM orders o WHERE o.user_id = u.id) AS order_count + 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)`, + }, { description: "Should autocomplete multi-line SQL query with CASE statements", @@ -637,57 +784,6 @@ squared_numbers = numbers.<|fim|> expectedCompletion: `map { |n| n ** 2 }`, filename: "array_methods.rb", }, - { - description: "Should autocomplete a Java method within a class", - filename: "Calculator.java", - input: ` -public class Calculator { - private double result; - - public Calculator() { - this.result = 0.0; - } - - public void add(double number) { - result += number; -<|fim|>`, - llmOutput: ` - } - - public void subtract(double number) { - result -= number; - } -`, - expectedCompletion: ` - } - - public void subtract(double number) { - result -= number; - } -`, - }, - { - description: "Should autocomplete Java when inside a block", - filename: "Main.java", - input: ` -public class Main { - public static void main(String[] args) { - for (int i = 0; i < 10; i++) { - if (i % 2 == 0) { - System.out.println("Even: " + i); - } else { -<|fim|> - } - } - } -}`, - llmOutput: ` - System.out.println("Odd: " + i); -`, - expectedCompletion: ` - System.out.println("Odd: " + i); -`, - }, { description: "Should autocomplete Java within a string", filename: "App.java", @@ -717,7 +813,6 @@ public class App { llmOutput: " int multiply(int a, int b);", expectedCompletion: " int multiply(int a, int b);", }, - { description: "Should autocomplete C++ for loop syntax", filename: "test.cpp", @@ -730,64 +825,6 @@ public class App { llmOutput: "i++", expectedCompletion: "i++", }, - { - description: "Should autocomplete a Markdown list with nested items", - filename: "test.md", - input: ` -- Item 1 -- Item 2 - - Subitem 1 - <|fim|> -- Item 3 -`, - llmOutput: ` - Subitem 2 - - Subitem 3 -`, - expectedCompletion: ` - Subitem 2 - - Subitem 3 -`, - }, - { - description: - "Should autocomplete a Markdown heading and preserve formatting", - filename: "test.md", - input: `# My Document - -## Introduction -This is a sample document for testing. - -## <|fim|> -### Conclusion -Thank you for reading. -`, - llmOutput: `Features -Here is a list of features: -- Feature 1 -- Feature 2 -`, - expectedCompletion: `Features -Here is a list of features: -- Feature 1 -- Feature 2 -`, - }, - { - description: "Should complete a Markdown code block", - filename: "test.md", - input: ` -Here is a sample JavaScript function: - -\`\`\`javascript -function sayHello() { - console.log("Hello, <|fim|> -} -\`\`\` -`, - llmOutput: `world!"); -`, - expectedCompletion: `world!"); -`, - }, { description: "Should autocomplete JSON object inside an array", filename: "data.json", @@ -986,28 +1023,6 @@ impl Calculator { println!("Cannot divide by zero."); } }`, - }, - { - description: "Should autocomplete Rust match arms", - filename: "main.rs", - input: ` -fn get_status_code_description(code: u16) -> &'static str { - match code { - 200 => "OK", - 404 => "Not Found", - 500 => "Internal Server Error", - <|fim|> - } -} -`, - llmOutput: `403 => "Forbidden", - 401 => "Unauthorized", - _ => "Unknown Status", -`, - expectedCompletion: `403 => "Forbidden", - 401 => "Unauthorized", - _ => "Unknown Status", -`, }, { description: "Should autocomplete Rust struct definition", @@ -1753,17 +1768,15 @@ let oddSquares = [<|fim|>]`, llmOutput: ` for x in squares do if x % 2 <> 0 then yield x ]`, expectedCompletion: ` for x in squares do if x % 2 <> 0 then yield x ]`, }, - { description: "Should complete an F# recursive function", filename: "recursiveFunctions.fs", input: `let rec factorial n = if n <= 1 then 1 else n <|fim|> factorial (n - 1)`, - llmOutput: ` * `, - expectedCompletion: ` * `, + llmOutput: `*`, + expectedCompletion: `*`, }, - { description: "Should complete F# member method inside a class type", filename: "bankAccount.fs", diff --git a/core/autocomplete/postprocessing/index.ts b/core/autocomplete/postprocessing/index.ts index 001642573..127874d68 100644 --- a/core/autocomplete/postprocessing/index.ts +++ b/core/autocomplete/postprocessing/index.ts @@ -73,9 +73,6 @@ export function postprocessCompletion({ return undefined; } - // Remove trailing whitespace - completion = completion.trimEnd(); - if (llm.model.includes("codestral")) { // Codestral sometimes starts with an extra space if (completion[0] === " " && completion[1] !== " ") { @@ -85,19 +82,23 @@ export function postprocessCompletion({ } } - // If completion starts with multiple whitespaces, but the cursor is at the end of the line - // then it should probably be on a new line - if ( - (completion.startsWith(" ") || completion.startsWith("\t")) && - !prefix.endsWith("\n") && - (suffix.startsWith("\n") || suffix.trim().length === 0) - ) { - // completion = "\n" + completion; - return undefined; - } + // // If completion starts with multiple whitespaces, but the cursor is at the end of the line + // // then it should probably be on a new line + // if ( + // (completion.startsWith(" ") || completion.startsWith("\t")) && + // !prefix.endsWith("\n") && + // (suffix.startsWith("\n") || suffix.trim().length === 0) + // ) { + // completion = "\n" + completion; + // } // If prefix ends with space and so does completion, then remove the space from completion - if (prefix.endsWith(" ") && completion.startsWith(" ")) { + if ( + prefix.split("\n").pop()?.trim() !== "" && + prefix.endsWith(" ") && + completion.startsWith(" ") + ) { + const test = prefix.split("\n").pop()?.trim() !== ""; completion = completion.slice(1); } diff --git a/core/autocomplete/prefiltering/index.ts b/core/autocomplete/prefiltering/index.ts index c844696ac..a7343817d 100644 --- a/core/autocomplete/prefiltering/index.ts +++ b/core/autocomplete/prefiltering/index.ts @@ -67,12 +67,12 @@ export async function shouldPrefilter( return true; } - if ( - helper.options.transform && - (await shouldLanguageSpecificPrefilter(helper)) - ) { - return true; - } + // if ( + // helper.options.transform && + // (await shouldLanguageSpecificPrefilter(helper)) + // ) { + // return true; + // } return false; } diff --git a/core/util/ranges.ts b/core/util/ranges.ts index 345933f03..3fb5b609e 100644 --- a/core/util/ranges.ts +++ b/core/util/ranges.ts @@ -7,7 +7,7 @@ export function getRangeInString(content: string, range: Range): string { return ( lines[range.start.line]?.substring( range.start.character, - range.end.character + 1, + range.end.character, ) ?? "" ); } From aa6cebe9f0c96d36d208c9653be1ae1ace3acbce Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 6 Nov 2024 13:51:07 +0700 Subject: [PATCH 38/43] improv: transform autocomplete edge cases --- .../constants/AutocompleteLanguageInfo.ts | 27 +++- .../StreamTransformPipeline.ts | 20 +-- .../filtering/streamTransforms/lineStream.ts | 8 ++ .../CODESTRAL_TYPESCRIPT.txt | 70 ---------- .../test/NEGATIVE_TEST_CASES/QWEN_JSON.txt | 60 ++++++++ .../NEGATIVE_TEST_CASES/QWEN_TYPESCRIPT.txt | 128 ++++++++++++++++++ .../NEGATIVE_TEST_CASES/STARCODER_JSON.txt | 20 +++ .../NEGATIVE_TEST_CASES/STARCODER_PYTHON.TXT | 29 ++++ .../NEGATIVE_TEST_CASES/STARCODER_RUBY.TXT | 41 ++++++ .../NEGATIVE_TEST_CASES/STARCODER_RUST.TXT | 73 ++++++++++ .../STARCODER_TYPESCRIPT.txt | 53 -------- core/autocomplete/filtering/test/testCases.ts | 127 ++++++++++++----- manual-testing-sandbox/AdvancedPage.tsx | 64 +++++++++ manual-testing-sandbox/Button.tsx | 15 -- manual-testing-sandbox/data.json | 83 +++++++++++- manual-testing-sandbox/test.html | 5 + 16 files changed, 636 insertions(+), 187 deletions(-) delete mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_JSON.txt create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_TYPESCRIPT.txt create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_JSON.txt create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_PYTHON.TXT create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUBY.TXT create mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUST.TXT delete mode 100644 core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt create mode 100644 manual-testing-sandbox/AdvancedPage.tsx delete mode 100644 manual-testing-sandbox/Button.tsx diff --git a/core/autocomplete/constants/AutocompleteLanguageInfo.ts b/core/autocomplete/constants/AutocompleteLanguageInfo.ts index 88ba93aa9..18bbf2ff9 100644 --- a/core/autocomplete/constants/AutocompleteLanguageInfo.ts +++ b/core/autocomplete/constants/AutocompleteLanguageInfo.ts @@ -1,4 +1,8 @@ -import { LineFilter } from "../filtering/streamTransforms/lineStream"; +import { BracketMatchingService } from "../filtering/BracketMatchingService"; +import { + CharacterFilter, + LineFilter, +} from "../filtering/streamTransforms/lineStream"; export interface AutocompleteLanguageInfo { name: string; @@ -7,6 +11,7 @@ export interface AutocompleteLanguageInfo { endOfLine: string[]; stopWords?: string[]; lineFilters?: LineFilter[]; + charFilters?: CharacterFilter[]; useMultiline?: (args: { prefix: string; suffix: string }) => boolean; } @@ -277,6 +282,25 @@ export const YAML: AutocompleteLanguageInfo = { ], }; +export const Json: AutocompleteLanguageInfo = { + name: "JSON", + topLevelKeywords: [], + singleLineComment: "//", + endOfLine: [",", "}", "]"], + charFilters: [ + function matchBrackets({ chars, prefix, suffix, filepath, multiline }) { + const bracketMatchingService = new BracketMatchingService(); + return bracketMatchingService.stopOnUnmatchedClosingBracket( + chars, + prefix, + suffix, + filepath, + multiline, + ); + }, + ], +}; + export const Markdown: AutocompleteLanguageInfo = { name: "Markdown", topLevelKeywords: [], @@ -306,6 +330,7 @@ export const LANGUAGES: { [extension: string]: AutocompleteLanguageInfo } = { ts: Typescript, js: Typescript, tsx: Typescript, + json: Json, jsx: Typescript, ipynb: Python, py: Python, diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 6b3262192..08a318a59 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -1,6 +1,5 @@ import { streamLines } from "../../../diff/util"; import { HelperVars } from "../../util/HelperVars"; -import { BracketMatchingService } from "../BracketMatchingService"; import { stopAtStopTokens } from "./charStream"; import { avoidEmptyComments, @@ -14,8 +13,6 @@ import { } from "./lineStream"; export class StreamTransformPipeline { - private bracketMatchingService = new BracketMatchingService(); - async *transform( generator: AsyncGenerator, prefix: string, @@ -28,13 +25,16 @@ export class StreamTransformPipeline { let charGenerator = generator; charGenerator = stopAtStopTokens(generator, stopTokens); - // charGenerator = this.bracketMatchingService.stopOnUnmatchedClosingBracket( - // charGenerator, - // prefix, - // suffix, - // helper.filepath, - // multiline, - // ); + for (const charFilter of helper.lang.charFilters ?? []) { + debugger; + charGenerator = charFilter({ + chars: charGenerator, + prefix, + suffix, + filepath: helper.filepath, + multiline, + }); + } let lineGenerator = streamLines(charGenerator); diff --git a/core/autocomplete/filtering/streamTransforms/lineStream.ts b/core/autocomplete/filtering/streamTransforms/lineStream.ts index e305062cf..0f49cea55 100644 --- a/core/autocomplete/filtering/streamTransforms/lineStream.ts +++ b/core/autocomplete/filtering/streamTransforms/lineStream.ts @@ -7,6 +7,14 @@ export type LineFilter = (args: { fullStop: () => void; }) => LineStream; +export type CharacterFilter = (args: { + chars: AsyncGenerator; + prefix: string; + suffix: string; + filepath: string; + multiline: boolean; +}) => AsyncGenerator; + function isBracketEnding(line: string): boolean { return line .trim() diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt deleted file mode 100644 index 7ecc7003d..000000000 --- a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/CODESTRAL_TYPESCRIPT.txt +++ /dev/null @@ -1,70 +0,0 @@ - -##### Prompt ##### -class Calculator { - constructor() { - this.result = 0; - } - - add(number) { - this.result += number; - return this; - } - - subtract(number) { - this.result -= number; - return this; - } - - multiply(number) { - this.result *= number; - return this; - } - - divide(number) { - if (number === 0) { - throw new Error("Cannot divide by zero"); - } - this.result /= number; - return this; - } - - - - - - - getResult() { - return this.result; - } - - reset() { - this.result = 0; - return this; - } -} -========================================================================== -========================================================================== -Completion: - - getResult() { - return this.result; - } - - reset() { - this.result = 0; - return this; - } -} - -// Example usage: -const calculator = new Calculator(); -calculator.add(5).subtract(3).multiply(2).divide(4); -console.log(calculator.getResult()); // Output: 2 - -calculator.reset().add(10).divide(2); -console.log(calculator.getResult()); // Output: 5 - -calculator.reset().add(8).multiply(0); -console.log(calculator.getResult()); // Output: 0 - -calculator.reset().add(6).divide(0); // Throws an error: Cannot divide by zero \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_JSON.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_JSON.txt new file mode 100644 index 000000000..ff0ba3cb3 --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_JSON.txt @@ -0,0 +1,60 @@ +##### Prompt ##### +{ + "active": true, + "department": "Product Development", + "location": { + "country": "USA", + "state": "California", + "city": "San BERNARDINO", + "coordinates": { + + } + }, + "employees": [ + { + "name": "John Doe", + "age": 30, + "position": "Developer", + "skills": ["JavaScript", "React", "Node.js"], + "remote": false, + "salary": { + "currency": "USD", + "amount": 95000 + } + }, + { + "name": "Jane Smith", + "age": 25, + "position": "Designer", + "skills": ["Photoshop", "Illustrator"], + "remote": true, + "salary": { + "currency": "USD", + "amount": 70000 + } + }, + { + "name": "Emily Johnson", + "age": 35, + "position": "Manager", + "teamSize": 8, + "remote": true, + "skills": ["Leadership", "Project Management"],========================================================================== +========================================================================== +Completion: + + "latitude": 34.10834, + "longitude": -117.28977 + } + }, + "employeeCount": 2, + "averageAge": 30, + "remoteFriendly": true, + "salaryRange": { + "min": 70000, + "max": 95000, + "currency": "USD" + }, + "skills": { + "required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"], + "optional": ["Photoshop", "Illustrator"] \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_TYPESCRIPT.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_TYPESCRIPT.txt new file mode 100644 index 000000000..241d141f2 --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/QWEN_TYPESCRIPT.txt @@ -0,0 +1,128 @@ +##### Prompt ##### + }`, + }, + { + description: "Should autocomplete Vue computed property", + filename: "UserComponent.vue", + input: ` + + +`, + llmOutput: `() { + return this.firstName + ' ' + this.lastName; + }`, + expectedCompletion: `() { + return this.firstName + ' ' + this.lastName; + }`, + }, + { + description: "Should autocomplete Vue method using props", + filename: "TodoItem.vue", + input: ` + + +`, + llmOutput: `this.completed`, + expectedCompletion: `this.completed`, + }, + { + description: "Should autocomplete Svelte reactive statement", + filename: "Counter.svelte", + input: ` + + + +`, + llmOutput: `doubledCount = count * 2`, + expectedCompletion: `doubledCount = count * 2`, + }, + + { + description: "Should autocomplete Svelte component inside HTML", + filename: "NestedComponent.svelte", + input: ` + + +
+

Hello Svelte

+ /> +
+`, + llmOutput: `name="World"`, + expectedCompletion: `name="World"`, + }, + + { + description: "Should handle autocomplete in Svelte each block", + filename: "List.svelte", + input: ` + + +
    + {#each items as item} +
  • {item}
  • + {/each<|fim|> +
+`, + llmOutput: `}`, + expectedCompletion: `}`, + }, + +]; +========================================================================== +========================================================================== +Completion: + + + +export default { + components: { + ChildComponent, + }, \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_JSON.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_JSON.txt new file mode 100644 index 000000000..a50bd2fb4 --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_JSON.txt @@ -0,0 +1,20 @@ +##### Prompt ##### +{ + "employees": [ + { "name": "John Doe", "age": 30, "position": "Developer" }, + { "name": "Jane Smith", "age": 25, "position": "Designer" }, + { "name": "Emily Johnson", "age": 35, "position": "Manager" } + ], + "active": true +} +========================================================================== +========================================================================== +Completion: + + +} + +{ + "employees": [ + { "name": "John Doe", "age": 30 }, + { "name": "Jane Smith", "age": 25 } \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_PYTHON.TXT b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_PYTHON.TXT new file mode 100644 index 000000000..c4aaf43ec --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_PYTHON.TXT @@ -0,0 +1,29 @@ +##### Prompt ##### +class Calculator: + def __init__(self): + self.result = 0 + + def add(self, number): + self.result += number + return self + + def divid + + def subtract(self, number): + self.result -= number + return self + + def reset(self): + self.result = 0 + return self + + def get_result(self): + return self.result + + +========================================================================== +========================================================================== +Completion: + +self.result /= number + return self \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUBY.TXT b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUBY.TXT new file mode 100644 index 000000000..df8c2011f --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUBY.TXT @@ -0,0 +1,41 @@ +##### Prompt ##### +class Calculator + attr_accessor :result + + def initialize + @result = 0 + end + + def add(number) + @result += number + self + end + + def subtract(number) + @result -= number + self + end + + def power(ne + + def get_result + @result + end + + def reset + @result = 0 + self + end +end + +calc = Calculator.new +calc.add(5).subtract(3) +puts "Result: #{calc.get_result}" +========================================================================== +========================================================================== +Completion: + + + @result ** number + self + end \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUST.TXT b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUST.TXT new file mode 100644 index 000000000..582ae5f36 --- /dev/null +++ b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_RUST.TXT @@ -0,0 +1,73 @@ +##### Prompt ##### +use std::io; + +fn main() { + println!("Welcome to the Calculator!"); + + loop { + println!("Please enter an operator (+, -, *, /) or 'q' to quit:"); + let operator = read_input(); + + if operator == "q" { + break; + } + + println!("Please enter the first number:"); + let num1 = read_input().parse::().unwrap(); + + println!("Please enter the second number:"); + let num2 = read_input().parse::().unwrap(); + + let result = match operator.as_str() { + "+" => num1 + num2, + "-" => num1 - num2, + "*" => num1 * num2, + "/" => num1 / num2, + + _ => { + println!("Invalid operator. Please try again."); + continue; + } + }; + + println!("Result: {}", result); + } +} + +fn read_input() -> String { + let mut input = String::new(); + io::stdin() + .read_line(&mut input) + .expect("Failed to read input"); + input.trim().to_string() +} +========================================================================== +========================================================================== +Completion: + + => { + println!("Invalid operator. Please try again."); + continue; + } + }; + + println!("Result: {}", result); + } + + println!("Goodbye!"); +} + + +fn main2() { + println!("Welcome to the Calculator!"); + + loop { + println!("Please enter an operator (+, -, *, /) or 'q' to quit:"); + let operator = read_input(); + + if operator == "q" { + break; + } + + match operator.as_str() { + "+" | "-" | "*" | "/" => (), \ No newline at end of file diff --git a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt b/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt deleted file mode 100644 index b2505a0bb..000000000 --- a/core/autocomplete/filtering/test/NEGATIVE_TEST_CASES/STARCODER_TYPESCRIPT.txt +++ /dev/null @@ -1,53 +0,0 @@ -##### Prompt ##### -class Calculator { - constructor() { - this.result = 0; - } - - add(number) { - this.result += number; - return this; - } - - subtract(number) { - this.result -= number; - return this; - } - - multiply(number) { - this.result *= number; - return this; - } - - divide(number) { - if (number === 0) { - throw new Error("Cannot divide by zero"); - } - - - - this.result /= number; - return this; - } - - getResult() { - return this.result; - } - - reset() { - this.result = 0; - return this; - } -} -========================================================================== -========================================================================== -Completion: - - this.result /= number; - return this; - } -} - -module.exports = Calculator; - ------------------------------------------------------------------------- diff --git a/core/autocomplete/filtering/test/testCases.ts b/core/autocomplete/filtering/test/testCases.ts index 1f0397363..683dbc7bc 100644 --- a/core/autocomplete/filtering/test/testCases.ts +++ b/core/autocomplete/filtering/test/testCases.ts @@ -172,6 +172,69 @@ public class Calculator { expectedCompletion: ` - Subitem 2 - Subitem 3`, }, + { + description: "Should enforce bracket matching in JSON files", + filename: "test.json", + input: `{ + "active": true, + "department": "Product Development", + "location": { + "country": "USA", + "state": "California", + "city": "San BERNARDINO", + "coordinates": { + + } + }, + "employees": [ + { + "name": "John Doe", + "age": 30, + "position": "Developer", + "skills": ["JavaScript", "React", "Node.js"], + "remote": false, + "salary": { + "currency": "USD", + "amount": 95000 + } + }, + { + "name": "Jane Smith", + "age": 25, + "position": "Designer", + "skills": ["Photoshop", "Illustrator"], + "remote": true, + "salary": { + "currency": "USD", + "amount": 70000 + } + }, + { + "name": "Emily Johnson", + "age": 35, + "position": "Manager", + "teamSize": 8, + "remote": true, + "skills": ["Leadership", "Project Management"],`, + llmOutput: `"latitude": 34.10834, + "longitude": -117.28977 + } + }, + "employeeCount": 2, + "averageAge": 30, + "remoteFriendly": true, + "salaryRange": { + "min": 70000, + "max": 95000, + "currency": "USD" + }, + "skills": { + "required": ["JavaScript", "React", "Node.js", "Leadership", "Project Management"], + "optional": ["Photoshop", "Illustrator"]`, + expectedCompletion: `"latitude": 34.10834, + "longitude": -117.28977 + `, + }, ]; export const TEST_CASES_WITHOUT_DIFF: AutocompleteFileringTestInput[] = [ @@ -670,6 +733,36 @@ func main() { llmOutput: `8.5)`, expectedCompletion: `8.5)`, }, + { + description: + "Should autocomplete SQL script with employee and product tables", + filename: "database.sql", + input: ` + CREATE TABLE employees ( + id INT AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(100) NOT NULL, + age INT NOT NULL, + position VARCHAR(100) + ); + + CREATE TABLE products ( + id INT AUTO_INCREMENT PRIMARY KEY, + name VARCHAR(100), + price DECIMAL(8,2) NOT NULL '0.00', + quantity INT NOT NULL DEFAULT '0' + ); + + INSERT INTO employees (name, age, position) VALUES ('John Doe', 30, 'Developer'); + INSERT INTO products (name, price, quantity) VALUES ('Apple', '1.99', '47'); + + SELECT * FROM products ORDER BY name DESC LIMIT 3; + SELECT * FROM products WHERE price > '0'; + SELECT * FROM products WHERE quantity > '100'; + SELECT * FROM employees WHERE age > 25; + `, + llmOutput: " DEFAULT", + expectedCompletion: " DEFAULT", + }, { description: "Should autocomplete SQL query with subquery and alias in SELECT clause", @@ -838,40 +931,6 @@ public class App { llmOutput: `, { "id": 3, "name": "Charlie" }`, expectedCompletion: `, { "id": 3, "name": "Charlie" }`, }, - { - description: "Should autocomplete nested JSON objects", - filename: "config.json", - input: `{ - "server": { - "host": "localhost", - "port": 8080, - "features": { - "enableLogging": true, - "maxConnections": 100 - <|fim|> - } -}`, - llmOutput: `, - "timeout": 5000 - }`, - expectedCompletion: `, - "timeout": 5000 - }`, - }, - { - description: "Should autocomplete JSON object with missing bracket", - filename: "settings.json", - input: `{ - "theme": "dark", - "language": "en"<|fim|> - `, - llmOutput: `, - "notifications": true - }`, - expectedCompletion: `, - "notifications": true - }`, - }, { description: "Should autocomplete within a CSV record", filename: "test.csv", diff --git a/manual-testing-sandbox/AdvancedPage.tsx b/manual-testing-sandbox/AdvancedPage.tsx new file mode 100644 index 000000000..6d17ef463 --- /dev/null +++ b/manual-testing-sandbox/AdvancedPage.tsx @@ -0,0 +1,64 @@ +import React, { useState } from "react"; + +const AdvancedPage = () => { + const [isDarkMode, setIsDarkMode] = useState(false); + const [counter, setCounter] = useState(0); + + const toggleDarkMode = () => { + setIsDarkMode((prevMode) => !prevMode); + }; + + return ( +
+
+

Welcome to the Advanced Page

+ +
+ +
+
+

+ Counter: {counter} +

+ +
+ +
+

Some other interactive elements:

+ +
+ +
+
+
+ +
+

+ © 2023 Advanced Page. All rights reserved. +

+
+
+ ); +}; + +export default AdvancedPage; diff --git a/manual-testing-sandbox/Button.tsx b/manual-testing-sandbox/Button.tsx deleted file mode 100644 index 4d6f8f91b..000000000 --- a/manual-testing-sandbox/Button.tsx +++ /dev/null @@ -1,15 +0,0 @@ -import React from "react"; - -export const Button = ({ - onClick, - children, -}: { - children: React.ReactNode; - onClick: () => void; -}) => { - return ( - - ); -}; diff --git a/manual-testing-sandbox/data.json b/manual-testing-sandbox/data.json index 7a187514a..6003f4bc2 100644 --- a/manual-testing-sandbox/data.json +++ b/manual-testing-sandbox/data.json @@ -1,8 +1,83 @@ { + "active": true, + "department": "Product Development", + "location": { + "country": "USA", + "state": "California", + "city": "San Francisco", + "coordinates": { + "latitude": 37.7749, + "longitude": -122.4194 + } + }, "employees": [ - { "name": "John Doe", "age": 30, "position": "Developer" }, - { "name": "Jane Smith", "age": 25, "position": "Designer" }, - { "name": "Emily Johnson", "age": 35, "position": "Manager" } + { + "name": "John Doe", + "age": 30, + "position": "Developer", + "skills": ["JavaScript", "React", "Node.js"], + "remote": false, + "salary": { + "currency": "USD", + "amount": 95000 + } + }, + { + "name": "Jane Smith", + "age": 25, + "position": "Designer", + "skills": ["Photoshop", "Illustrator"], + "remote": true, + "salary": { + "currency": "USD", + "amount": 70000 + } + }, + { + "name": "Emily Johnson", + "age": 35, + "position": "Manager", + "teamSize": 8, + "remote": true, + "skills": ["Leadership", "Project Management"], + "salary": { + "currency": "USD", + "amount": 120000 + }, + "contact": { + "email": "emily.johnson@company.com", + "phone": "+1-202-555-0163" + } + } ], - "active": true + "projects": [ + { + "name": "Project Alpha", + "deadline": "2023-12-31", + "budget": 150000, + "teamMembers": ["John Doe", "Jane Smith"] + }, + { + "name": "Project Beta", + "deadline": "2024-06-30", + "budget": 200000, + "teamMembers": ["Emily Johnson"] + } + ], + "companyStats": { + "founded": 2010, + "annualRevenue": 2500000, + "clients": [ + { + "name": "Client A", + "industry": "Technology", + "engagements": ["Consulting", "Development"] + }, + { + "name": "Client B", + "industry": "Finance", + "engagements": ["Design"] + } + ] + } } diff --git a/manual-testing-sandbox/test.html b/manual-testing-sandbox/test.html index 6c19f414b..8ed2c4792 100644 --- a/manual-testing-sandbox/test.html +++ b/manual-testing-sandbox/test.html @@ -19,6 +19,11 @@

This is a sample paragraph.

+
    +
  1. Item 1
  2. +
  3. Item 2
  4. +
  5. Item 3
  6. +
From f60009c2ea7c1c1a980152e5aa3cda17c3f6e64d Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Wed, 6 Nov 2024 20:34:53 +0700 Subject: [PATCH 39/43] fix: broken imports --- extensions/vscode/src/autocomplete/lsp.ts | 2 +- extensions/vscode/src/commands.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/autocomplete/lsp.ts b/extensions/vscode/src/autocomplete/lsp.ts index c3382dd99..41ae1d973 100644 --- a/extensions/vscode/src/autocomplete/lsp.ts +++ b/extensions/vscode/src/autocomplete/lsp.ts @@ -1,5 +1,5 @@ import type { IDE, Range, RangeInFile } from "core"; -import { GetLspDefinitionsFunction } from "core/autocomplete/completionProvider"; +import { GetLspDefinitionsFunction } from "core/autocomplete/CompletionProvider"; import { AutocompleteLanguageInfo } from "core/autocomplete/constants/AutocompleteLanguageInfo"; import { AutocompleteSnippet } from "core/autocomplete/context/ranking"; import { getAst, getTreePathAtCursor } from "core/autocomplete/util/ast"; diff --git a/extensions/vscode/src/commands.ts b/extensions/vscode/src/commands.ts index bb020c302..06601187e 100644 --- a/extensions/vscode/src/commands.ts +++ b/extensions/vscode/src/commands.ts @@ -1,6 +1,6 @@ /* eslint-disable @typescript-eslint/naming-convention */ import { ContextMenuConfig, IDE } from "core"; -import { CompletionProvider } from "core/autocomplete/completionProvider"; +import { CompletionProvider } from "core/autocomplete/CompletionProvider"; import { RangeInFileWithContents } from "core/commands/util"; import { ConfigHandler } from "core/config/ConfigHandler"; import { getModelByRole } from "core/config/util"; From 6284eeebef984ac1afd3846b606a7745c5dfb49d Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 7 Nov 2024 16:59:23 +0700 Subject: [PATCH 40/43] fix: cursor position --- .../context/root-path-context/RootPathContextService.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/autocomplete/context/root-path-context/RootPathContextService.test.ts b/core/autocomplete/context/root-path-context/RootPathContextService.test.ts index 87795611b..ccce0b6ac 100644 --- a/core/autocomplete/context/root-path-context/RootPathContextService.test.ts +++ b/core/autocomplete/context/root-path-context/RootPathContextService.test.ts @@ -74,7 +74,7 @@ export async function testRootPathContext( throw new Error("AST is undefined"); } - const treePath = await getTreePathAtCursor(ast, rangeToFill.start.character); + const treePath = await getTreePathAtCursor(ast, prefix.length); const snippets = await service.getContextForPath(startPath, treePath); expectedSnippets.forEach((expectedSnippet) => { From 71a151f399d514497ee917eca521863d07b2a270 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Thu, 7 Nov 2024 19:32:26 +0700 Subject: [PATCH 41/43] fix: test env path --- core/util/treeSitter.ts | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/core/util/treeSitter.ts b/core/util/treeSitter.ts index 08cfe64d1..bf6891f23 100644 --- a/core/util/treeSitter.ts +++ b/core/util/treeSitter.ts @@ -115,6 +115,7 @@ export async function getLanguageForFile( return undefined; } let language = nameToLanguage.get(languageName); + if (!language) { language = await loadLanguageForFileExt(extension); nameToLanguage.set(languageName, language); @@ -149,7 +150,9 @@ export async function getQueryForFile( const sourcePath = path.join( __dirname, "..", - "tree-sitter", + ...(process.env.NODE_ENV === "test" + ? ["extensions", "vscode", "tree-sitter"] + : ["tree-sitter"]), queryType, `${fullLangName}.scm`, ); From 3e4c75bf461c36c2200ac2922670bb76a612b292 Mon Sep 17 00:00:00 2001 From: tomasz-io Date: Fri, 8 Nov 2024 16:18:37 +0700 Subject: [PATCH 42/43] fix: remove debugger statement --- .../filtering/streamTransforms/StreamTransformPipeline.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 08a318a59..88ae0c352 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -26,7 +26,6 @@ export class StreamTransformPipeline { charGenerator = stopAtStopTokens(generator, stopTokens); for (const charFilter of helper.lang.charFilters ?? []) { - debugger; charGenerator = charFilter({ chars: charGenerator, prefix, From 1095182f952e4912ecd2f691675ba3ff4144ad84 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 8 Nov 2024 14:49:05 -0800 Subject: [PATCH 43/43] use options showWhateverWeHaveAtXMs --- .../filtering/streamTransforms/StreamTransformPipeline.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts index 88ae0c352..8d7f3e23f 100644 --- a/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts +++ b/core/autocomplete/filtering/streamTransforms/StreamTransformPipeline.ts @@ -1,4 +1,5 @@ import { streamLines } from "../../../diff/util"; +import { DEFAULT_AUTOCOMPLETE_OPTS } from "../../../util/parameters"; import { HelperVars } from "../../util/HelperVars"; import { stopAtStopTokens } from "./charStream"; import { @@ -56,7 +57,11 @@ export class StreamTransformPipeline { fullStop, ); - lineGenerator = showWhateverWeHaveAtXMs(lineGenerator, 250); + lineGenerator = showWhateverWeHaveAtXMs( + lineGenerator, + helper.options.showWhateverWeHaveAtXMs ?? + (DEFAULT_AUTOCOMPLETE_OPTS.showWhateverWeHaveAtXMs as number), + ); const finalGenerator = streamWithNewLines(lineGenerator); for await (const update of finalGenerator) {