Elffuss BraidHub

kikocis/continue public

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