| 1 | import { CompletionProvider } from "core/autocomplete/CompletionProvider"; |
| 2 | import { processSingleLineCompletion } from "core/autocomplete/util/processSingleLineCompletion"; |
| 3 | import { |
| 4 | type AutocompleteInput, |
| 5 | type AutocompleteOutcome, |
| 6 | } from "core/autocomplete/util/types"; |
| 7 | import { ConfigHandler } from "core/config/ConfigHandler"; |
| 8 | import { IS_NEXT_EDIT_ACTIVE } from "core/nextEdit/constants"; |
| 9 | import { NextEditProvider } from "core/nextEdit/NextEditProvider"; |
| 10 | import * as URI from "uri-js"; |
| 11 | import { v4 as uuidv4 } from "uuid"; |
| 12 | import * as vscode from "vscode"; |
| 13 | |
| 14 | import { handleLLMError } from "../util/errorHandling"; |
| 15 | import { VsCodeIde } from "../VsCodeIde"; |
| 16 | import { VsCodeWebviewProtocol } from "../webviewProtocol"; |
| 17 | |
| 18 | import { getDefinitionsFromLsp } from "./lsp"; |
| 19 | import { RecentlyEditedTracker } from "./recentlyEdited"; |
| 20 | import { RecentlyVisitedRangesService } from "./RecentlyVisitedRangesService"; |
| 21 | import { |
| 22 | StatusBarStatus, |
| 23 | getStatusBarStatus, |
| 24 | setupStatusBar, |
| 25 | stopStatusBarLoading, |
| 26 | } from "./statusBar"; |
| 27 | |
| 28 | interface VsCodeCompletionInput { |
| 29 | document: vscode.TextDocument; |
| 30 | position: vscode.Position; |
| 31 | context: vscode.InlineCompletionContext; |
| 32 | } |
| 33 | |
| 34 | export class ContinueCompletionProvider |
| 35 | implements vscode.InlineCompletionItemProvider |
| 36 | { |
| 37 | private async onError(e: unknown) { |
| 38 | if (await handleLLMError(e)) { |
| 39 | return; |
| 40 | } |
| 41 | let message = "Continue Autocomplete Error"; |
| 42 | if (e instanceof Error) { |
| 43 | message += `: ${e.message}`; |
| 44 | } |
| 45 | vscode.window.showErrorMessage(message, "Documentation").then((val) => { |
| 46 | if (val === "Documentation") { |
| 47 | vscode.env.openExternal( |
| 48 | vscode.Uri.parse( |
| 49 | "https://docs.continue.dev/features/tab-autocomplete", |
| 50 | ), |
| 51 | ); |
| 52 | } |
| 53 | }); |
| 54 | } |
| 55 | |
| 56 | private completionProvider: CompletionProvider; |
| 57 | private nextEditProvider: NextEditProvider | undefined; |
| 58 | private recentlyVisitedRanges: RecentlyVisitedRangesService; |
| 59 | private recentlyEditedTracker: RecentlyEditedTracker; |
| 60 | |
| 61 | constructor( |
| 62 | private readonly configHandler: ConfigHandler, |
| 63 | private readonly ide: VsCodeIde, |
| 64 | private readonly webviewProtocol: VsCodeWebviewProtocol, |
| 65 | ) { |
| 66 | this.recentlyEditedTracker = new RecentlyEditedTracker(ide.ideUtils); |
| 67 | |
| 68 | async function getAutocompleteModel() { |
| 69 | const { config } = await configHandler.loadConfig(); |
| 70 | if (!config) { |
| 71 | return; |
| 72 | } |
| 73 | return config.selectedModelByRole.autocomplete ?? undefined; |
| 74 | } |
| 75 | this.completionProvider = new CompletionProvider( |
| 76 | this.configHandler, |
| 77 | this.ide, |
| 78 | getAutocompleteModel, |
| 79 | this.onError.bind(this), |
| 80 | getDefinitionsFromLsp, |
| 81 | ); |
| 82 | // NOTE: Only turn it on locally when testing (for review purposes). |
| 83 | if (IS_NEXT_EDIT_ACTIVE) { |
| 84 | this.nextEditProvider = new NextEditProvider( |
| 85 | this.configHandler, |
| 86 | this.ide, |
| 87 | getAutocompleteModel, |
| 88 | this.onError.bind(this), |
| 89 | getDefinitionsFromLsp, |
| 90 | ); |
| 91 | } |
| 92 | this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide); |
| 93 | } |
| 94 | |
| 95 | _lastShownCompletion: AutocompleteOutcome | undefined; |
| 96 | |
| 97 | public async provideInlineCompletionItems( |
| 98 | document: vscode.TextDocument, |
| 99 | position: vscode.Position, |
| 100 | context: vscode.InlineCompletionContext, |
| 101 | token: vscode.CancellationToken, |
| 102 | //@ts-ignore |
| 103 | ): ProviderResult<InlineCompletionItem[] | InlineCompletionList> { |
| 104 | const enableTabAutocomplete = |
| 105 | getStatusBarStatus() === StatusBarStatus.Enabled; |
| 106 | if (token.isCancellationRequested || !enableTabAutocomplete) { |
| 107 | return null; |
| 108 | } |
| 109 | |
| 110 | if (document.uri.scheme === "vscode-scm") { |
| 111 | return null; |
| 112 | } |
| 113 | |
| 114 | // Don't autocomplete with multi-cursor |
| 115 | const editor = vscode.window.activeTextEditor; |
| 116 | if (editor && editor.selections.length > 1) { |
| 117 | return null; |
| 118 | } |
| 119 | |
| 120 | const selectedCompletionInfo = context.selectedCompletionInfo; |
| 121 | |
| 122 | // This code checks if there is a selected completion suggestion in the given context and ensures that it is valid |
| 123 | // To improve the accuracy of suggestions it checks if the user has typed at least 4 characters |
| 124 | // This helps refine and filter out irrelevant autocomplete options |
| 125 | if (selectedCompletionInfo) { |
| 126 | const { text, range } = selectedCompletionInfo; |
| 127 | const typedText = document.getText(range); |
| 128 | |
| 129 | const typedLength = range.end.character - range.start.character; |
| 130 | |
| 131 | if (typedLength < 4) { |
| 132 | return null; |
| 133 | } |
| 134 | |
| 135 | if (!text.startsWith(typedText)) { |
| 136 | return null; |
| 137 | } |
| 138 | } |
| 139 | let injectDetails: string | undefined = undefined; |
| 140 | |
| 141 | try { |
| 142 | const abortController = new AbortController(); |
| 143 | const signal = abortController.signal; |
| 144 | token.onCancellationRequested(() => abortController.abort()); |
| 145 | |
| 146 | // Handle notebook cells |
| 147 | const pos = { |
| 148 | line: position.line, |
| 149 | character: position.character, |
| 150 | }; |
| 151 | let manuallyPassFileContents: string | undefined = undefined; |
| 152 | if (document.uri.scheme === "vscode-notebook-cell") { |
| 153 | const notebook = vscode.workspace.notebookDocuments.find((notebook) => |
| 154 | notebook |
| 155 | .getCells() |
| 156 | .some((cell) => |
| 157 | URI.equal(cell.document.uri.toString(), document.uri.toString()), |
| 158 | ), |
| 159 | ); |
| 160 | if (notebook) { |
| 161 | const cells = notebook.getCells(); |
| 162 | manuallyPassFileContents = cells |
| 163 | .map((cell) => { |
| 164 | const text = cell.document.getText(); |
| 165 | if (cell.kind === vscode.NotebookCellKind.Markup) { |
| 166 | return `"""${text}"""`; |
| 167 | } else { |
| 168 | return text; |
| 169 | } |
| 170 | }) |
| 171 | .join("\n\n"); |
| 172 | for (const cell of cells) { |
| 173 | if ( |
| 174 | URI.equal(cell.document.uri.toString(), document.uri.toString()) |
| 175 | ) { |
| 176 | break; |
| 177 | } else { |
| 178 | pos.line += cell.document.getText().split("\n").length + 1; |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | |
| 184 | // Manually pass file contents for unsaved, untitled files |
| 185 | if (document.isUntitled) { |
| 186 | manuallyPassFileContents = document.getText(); |
| 187 | } |
| 188 | |
| 189 | // Handle commit message input box |
| 190 | let manuallyPassPrefix: string | undefined = undefined; |
| 191 | |
| 192 | // handle manual autocompletion trigger |
| 193 | const wasManuallyTriggered = |
| 194 | context.triggerKind === vscode.InlineCompletionTriggerKind.Invoke; |
| 195 | |
| 196 | const input: AutocompleteInput = { |
| 197 | pos, |
| 198 | manuallyPassFileContents, |
| 199 | manuallyPassPrefix, |
| 200 | selectedCompletionInfo, |
| 201 | injectDetails, |
| 202 | isUntitledFile: document.isUntitled, |
| 203 | completionId: uuidv4(), |
| 204 | filepath: document.uri.toString(), |
| 205 | recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(), |
| 206 | recentlyEditedRanges: |
| 207 | await this.recentlyEditedTracker.getRecentlyEditedRanges(), |
| 208 | }; |
| 209 | |
| 210 | setupStatusBar(undefined, true); |
| 211 | const outcome = |
| 212 | await this.completionProvider.provideInlineCompletionItems( |
| 213 | input, |
| 214 | signal, |
| 215 | wasManuallyTriggered, |
| 216 | ); |
| 217 | |
| 218 | if (!outcome || !outcome.completion) { |
| 219 | return null; |
| 220 | } |
| 221 | |
| 222 | // NOTE: This is a very rudimentary check to see if we can call the next edit service. |
| 223 | // In the future we will have to figure out how to call this more gracefully. |
| 224 | if (this.nextEditProvider) { |
| 225 | const nextEditOutcome = |
| 226 | await this.nextEditProvider?.provideInlineCompletionItems( |
| 227 | input, |
| 228 | signal, |
| 229 | ); |
| 230 | |
| 231 | if (nextEditOutcome && nextEditOutcome.completion) { |
| 232 | outcome.completion = nextEditOutcome.completion; |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | // VS Code displays dependent on selectedCompletionInfo (their docstring below) |
| 237 | // We should first always make sure we have a valid completion, but if it goes wrong we |
| 238 | // want telemetry to be correct |
| 239 | /** |
| 240 | * Provides information about the currently selected item in the autocomplete widget if it is visible. |
| 241 | * |
| 242 | * If set, provided inline completions must extend the text of the selected item |
| 243 | * and use the same range, otherwise they are not shown as preview. |
| 244 | * As an example, if the document text is `console.` and the selected item is `.log` replacing the `.` in the document, |
| 245 | * the inline completion must also replace `.` and start with `.log`, for example `.log()`. |
| 246 | * |
| 247 | * Inline completion providers are requested again whenever the selected item changes. |
| 248 | */ |
| 249 | if (selectedCompletionInfo) { |
| 250 | outcome.completion = selectedCompletionInfo.text + outcome.completion; |
| 251 | } |
| 252 | const willDisplay = this.willDisplay( |
| 253 | document, |
| 254 | selectedCompletionInfo, |
| 255 | signal, |
| 256 | outcome, |
| 257 | ); |
| 258 | if (!willDisplay) { |
| 259 | return null; |
| 260 | } |
| 261 | |
| 262 | // Mark displayed |
| 263 | this.completionProvider.markDisplayed(input.completionId, outcome); |
| 264 | this._lastShownCompletion = outcome; |
| 265 | |
| 266 | // Construct the range/text to show |
| 267 | const startPos = selectedCompletionInfo?.range.start ?? position; |
| 268 | let range = new vscode.Range(startPos, startPos); |
| 269 | let completionText = outcome.completion; |
| 270 | const isSingleLineCompletion = outcome.completion.split("\n").length <= 1; |
| 271 | |
| 272 | if (isSingleLineCompletion) { |
| 273 | const lastLineOfCompletionText = completionText.split("\n").pop() || ""; |
| 274 | const currentText = document |
| 275 | .lineAt(startPos) |
| 276 | .text.substring(startPos.character); |
| 277 | |
| 278 | const result = processSingleLineCompletion( |
| 279 | lastLineOfCompletionText, |
| 280 | currentText, |
| 281 | startPos.character, |
| 282 | ); |
| 283 | |
| 284 | if (result === undefined) { |
| 285 | return undefined; |
| 286 | } |
| 287 | |
| 288 | completionText = result.completionText; |
| 289 | if (result.range) { |
| 290 | range = new vscode.Range( |
| 291 | new vscode.Position(startPos.line, result.range.start), |
| 292 | new vscode.Position(startPos.line, result.range.end), |
| 293 | ); |
| 294 | } |
| 295 | } else { |
| 296 | // Extend the range to the end of the line for multiline completions |
| 297 | range = new vscode.Range(startPos, document.lineAt(startPos).range.end); |
| 298 | } |
| 299 | |
| 300 | const completionItem = new vscode.InlineCompletionItem( |
| 301 | completionText, |
| 302 | range, |
| 303 | { |
| 304 | title: "Log Autocomplete Outcome", |
| 305 | command: "continue.logAutocompleteOutcome", |
| 306 | arguments: [input.completionId, this.completionProvider], |
| 307 | }, |
| 308 | ); |
| 309 | |
| 310 | (completionItem as any).completeBracketPairs = true; |
| 311 | return [completionItem]; |
| 312 | } finally { |
| 313 | stopStatusBarLoading(); |
| 314 | } |
| 315 | } |
| 316 | |
| 317 | willDisplay( |
| 318 | document: vscode.TextDocument, |
| 319 | selectedCompletionInfo: vscode.SelectedCompletionInfo | undefined, |
| 320 | abortSignal: AbortSignal, |
| 321 | outcome: AutocompleteOutcome, |
| 322 | ): boolean { |
| 323 | if (selectedCompletionInfo) { |
| 324 | const { text, range } = selectedCompletionInfo; |
| 325 | if (!outcome.completion.startsWith(text)) { |
| 326 | console.log( |
| 327 | `Won't display completion because text doesn't match: ${text}, ${outcome.completion}`, |
| 328 | range, |
| 329 | ); |
| 330 | return false; |
| 331 | } |
| 332 | } |
| 333 | |
| 334 | if (abortSignal.aborted) { |
| 335 | return false; |
| 336 | } |
| 337 | |
| 338 | return true; |
| 339 | } |
| 340 | } |