Elffuss BraidHub

kikocis/continue public

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