Elffuss BraidHub

kikocis/continue public

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