Elffuss BraidHub

kikocis/continue public

f257cf52b41d · 10.8 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";
8import { IS_NEXT_EDIT_ACTIVE } from "core/nextEdit/constants";
9import { 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 { getDefinitionsFromLsp } from "./lsp";
19import { RecentlyEditedTracker } from "./recentlyEdited";
20import { RecentlyVisitedRangesService } from "./RecentlyVisitedRangesService";
21import {
22 StatusBarStatus,
23 getStatusBarStatus,
24 setupStatusBar,
25 stopStatusBarLoading,
26} from "./statusBar";
27
28interface VsCodeCompletionInput {
29 document: vscode.TextDocument;
30 position: vscode.Position;
31 context: vscode.InlineCompletionContext;
32}
33
34export 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 const input: AutocompleteInput = {
193 pos,
194 manuallyPassFileContents,
195 manuallyPassPrefix,
196 selectedCompletionInfo,
197 injectDetails,
198 isUntitledFile: document.isUntitled,
199 completionId: uuidv4(),
200 filepath: document.uri.toString(),
201 recentlyVisitedRanges: this.recentlyVisitedRanges.getSnippets(),
202 recentlyEditedRanges:
203 await this.recentlyEditedTracker.getRecentlyEditedRanges(),
204 };
205
206 setupStatusBar(undefined, true);
207 const outcome =
208 await this.completionProvider.provideInlineCompletionItems(
209 input,
210 signal,
211 );
212
213 if (!outcome || !outcome.completion) {
214 return null;
215 }
216
217 // NOTE: This is a very rudimentary check to see if we can call the next edit service.
218 // In the future we will have to figure out how to call this more gracefully.
219 if (this.nextEditProvider) {
220 const nextEditOutcome =
221 await this.nextEditProvider?.provideInlineCompletionItems(
222 input,
223 signal,
224 );
225
226 if (nextEditOutcome && nextEditOutcome.completion) {
227 outcome.completion = nextEditOutcome.completion;
228 }
229 }
230
231 // VS Code displays dependent on selectedCompletionInfo (their docstring below)
232 // We should first always make sure we have a valid completion, but if it goes wrong we
233 // want telemetry to be correct
234 /**
235 * Provides information about the currently selected item in the autocomplete widget if it is visible.
236 *
237 * If set, provided inline completions must extend the text of the selected item
238 * and use the same range, otherwise they are not shown as preview.
239 * As an example, if the document text is `console.` and the selected item is `.log` replacing the `.` in the document,
240 * the inline completion must also replace `.` and start with `.log`, for example `.log()`.
241 *
242 * Inline completion providers are requested again whenever the selected item changes.
243 */
244 if (selectedCompletionInfo) {
245 outcome.completion = selectedCompletionInfo.text + outcome.completion;
246 }
247 const willDisplay = this.willDisplay(
248 document,
249 selectedCompletionInfo,
250 signal,
251 outcome,
252 );
253 if (!willDisplay) {
254 return null;
255 }
256
257 // Mark displayed
258 this.completionProvider.markDisplayed(input.completionId, outcome);
259 this._lastShownCompletion = outcome;
260
261 // Construct the range/text to show
262 const startPos = selectedCompletionInfo?.range.start ?? position;
263 let range = new vscode.Range(startPos, startPos);
264 let completionText = outcome.completion;
265 const isSingleLineCompletion = outcome.completion.split("\n").length <= 1;
266
267 if (isSingleLineCompletion) {
268 const lastLineOfCompletionText = completionText.split("\n").pop() || "";
269 const currentText = document
270 .lineAt(startPos)
271 .text.substring(startPos.character);
272
273 const result = processSingleLineCompletion(
274 lastLineOfCompletionText,
275 currentText,
276 startPos.character,
277 );
278
279 if (result === undefined) {
280 return undefined;
281 }
282
283 completionText = result.completionText;
284 if (result.range) {
285 range = new vscode.Range(
286 new vscode.Position(startPos.line, result.range.start),
287 new vscode.Position(startPos.line, result.range.end),
288 );
289 }
290 } else {
291 // Extend the range to the end of the line for multiline completions
292 range = new vscode.Range(startPos, document.lineAt(startPos).range.end);
293 }
294
295 const completionItem = new vscode.InlineCompletionItem(
296 completionText,
297 range,
298 {
299 title: "Log Autocomplete Outcome",
300 command: "continue.logAutocompleteOutcome",
301 arguments: [input.completionId, this.completionProvider],
302 },
303 );
304
305 (completionItem as any).completeBracketPairs = true;
306 return [completionItem];
307 } finally {
308 stopStatusBarLoading();
309 }
310 }
311
312 willDisplay(
313 document: vscode.TextDocument,
314 selectedCompletionInfo: vscode.SelectedCompletionInfo | undefined,
315 abortSignal: AbortSignal,
316 outcome: AutocompleteOutcome,
317 ): boolean {
318 if (selectedCompletionInfo) {
319 const { text, range } = selectedCompletionInfo;
320 if (!outcome.completion.startsWith(text)) {
321 console.log(
322 `Won't display completion because text doesn't match: ${text}, ${outcome.completion}`,
323 range,
324 );
325 return false;
326 }
327 }
328
329 if (abortSignal.aborted) {
330 return false;
331 }
332
333 return true;
334 }
335}