Elffuss BraidHub

kikocis/continue public

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