Elffuss BraidHub

kikocis/continue public

main · 15.6 KiBRawPermalink
1/* eslint-disable @typescript-eslint/naming-convention */
2import { IDE, ILLM, RuleWithSource } from "core";
3import { ConfigHandler } from "core/config/ConfigHandler";
4import { DataLogger } from "core/data/log";
5import { Telemetry } from "core/util/posthog";
6import * as vscode from "vscode";
7
8import { VerticalDiffManager } from "../diff/vertical/manager";
9import { FileSearch } from "../util/FileSearch";
10import { VsCodeWebviewProtocol } from "../webviewProtocol";
11
12import { getContextProviderQuickPickVal } from "./ContextProvidersQuickPick";
13import { appendToHistory, getHistoryQuickPickVal } from "./HistoryQuickPick";
14
15// @ts-ignore - error finding typings
16// @ts-ignore
17
18/**
19 * Used to track what action to take after a user interacts
20 * with the initial Quick Pick
21 */
22enum QuickEditInitialItemLabels {
23 History = "History",
24 ContextProviders = "Context providers",
25 Submit = "Submit",
26}
27
28enum UserPromptLabels {
29 AcceptAll = "Accept all (Shift + Cmd + Enter)",
30 RejectAll = "Reject all (Shift + Cmd + Backspace)",
31 CloseDialog = "Close dialog",
32}
33
34export type QuickEditShowParams = {
35 initialPrompt?: string;
36 /**
37 * Used for Quick Actions where the user has not highlighted code.
38 * Instead the range comes from the document symbol.
39 */
40 range?: vscode.Range;
41};
42
43const FILE_SEARCH_CHAR = "@";
44
45/**
46 * The user has to select an item to submit the prompt,
47 * so we add a "Submit" item once the user has begun to
48 * type their prompt that is always displayed
49 */
50const SUBMIT_ITEM: vscode.QuickPickItem = {
51 label: "Submit",
52 alwaysShow: true,
53};
54
55const NO_RESULTS_ITEM: vscode.QuickPickItem = { label: "No results found" };
56
57const REVIEW_CHANGES_ITEMS: vscode.QuickPickItem[] = [
58 {
59 label: UserPromptLabels.AcceptAll,
60 alwaysShow: true,
61 },
62 { label: UserPromptLabels.RejectAll, alwaysShow: true },
63 {
64 label: UserPromptLabels.CloseDialog,
65 alwaysShow: true,
66 },
67];
68
69/**
70 * Quick Edit is a collection of Quick Picks that allow the user to
71 * quickly edit a file.
72 */
73export class QuickEdit {
74 /**
75 * Matches the search char followed by non-space chars, excluding matches ending with a space.
76 * This is used to detect file search queries while allowing subsequent prompt text
77 */
78 private static hasFileSearchQueryRegex = new RegExp(
79 `${FILE_SEARCH_CHAR}[^${FILE_SEARCH_CHAR}\\s]+(?!\\s)$`,
80 );
81
82 private static maxFileSearchResults = 20;
83
84 private range?: vscode.Range;
85 private initialPrompt?: string;
86
87 private previousInput?: string;
88
89 /**
90 * Handles situations where the user navigates to a different editor
91 * while interacting with the Quick Pick
92 */
93 private editorWhenOpened!: vscode.TextEditor;
94
95 /**
96 * Required to store the string content of a context provider
97 * while naviagting beween Quick Picks.
98 */
99 private contextProviderStr?: string;
100
101 constructor(
102 private readonly verticalDiffManager: VerticalDiffManager,
103 private readonly configHandler: ConfigHandler,
104 private readonly webviewProtocol: VsCodeWebviewProtocol,
105 private readonly ide: IDE,
106 private readonly context: vscode.ExtensionContext,
107 private readonly fileSearch: FileSearch,
108 ) {}
109
110 /**
111 * Shows the Quick Edit Quick Pick, allowing the user to select an initial item or enter a prompt.
112 * Displays a quick pick for "History" or "ContextProviders" to set the prompt or context provider string.
113 * Displays a quick pick for "Model" to set the current model title.
114 * Appends the entered prompt to the history and streams the edit with input and context.
115 */
116 async show(params?: QuickEditShowParams) {
117 // Clean up state from previous quick picks, e.g. if a user pressed `esc`
118
119 const editor = vscode.window.activeTextEditor;
120
121 // We only allow users to interact with a quick edit if there is an open editor
122 if (!editor) {
123 return;
124 }
125
126 const hasChanges = !!this.verticalDiffManager.getHandlerForFile(
127 editor.document.uri.toString(),
128 );
129
130 if (hasChanges) {
131 this.openAcceptRejectMenu("", editor.document.uri.toString());
132 } else {
133 await this.initiateNewQuickPick(editor, params);
134 }
135 }
136
137 private async initiateNewQuickPick(
138 editor: vscode.TextEditor,
139 params: QuickEditShowParams | undefined,
140 ) {
141 this.clear();
142 // Set state that is unique to each quick pick instance
143 this.setActiveEditorAndPrevInput(editor);
144
145 if (!this.editorWhenOpened) {
146 return;
147 }
148
149 if (!!params?.initialPrompt) {
150 this.initialPrompt = params.initialPrompt;
151 }
152
153 this.range = !!params?.range
154 ? params.range
155 : this.editorWhenOpened.selection;
156
157 const { label: selectedLabel, value: selectedValue } =
158 await this._getInitialQuickPickVal();
159
160 if (!selectedValue && !selectedLabel) {
161 return;
162 }
163
164 Telemetry.capture("quickEditSelection", {
165 selection: {
166 label: selectedLabel,
167 value: selectedValue,
168 },
169 });
170
171 const prompt = await this.handleSelect({
172 selectedLabel,
173 selectedValue,
174 editor,
175 params,
176 });
177
178 if (prompt) {
179 await this.handleUserPrompt(prompt, editor.document.uri.toString());
180 }
181 }
182
183 private openAcceptRejectMenu(prompt: string, path: string | undefined) {
184 const quickPick = vscode.window.createQuickPick();
185 quickPick.placeholder = "Type your acceptance decision";
186
187 quickPick.title = "Accept changes";
188 quickPick.value = prompt;
189 quickPick.items = REVIEW_CHANGES_ITEMS;
190 quickPick.placeholder =
191 "Accept or reject changes. Start typing to try again with a new prompt.";
192 quickPick.show();
193
194 quickPick.onDidChangeValue(() => {
195 quickPick.items = [prompt, ""].includes(quickPick.value)
196 ? REVIEW_CHANGES_ITEMS
197 : [SUBMIT_ITEM];
198 });
199
200 quickPick.onDidAccept(async () => {
201 const { label } = quickPick.selectedItems[0];
202 switch (label) {
203 case UserPromptLabels.AcceptAll:
204 vscode.commands.executeCommand("continue.acceptDiff", path);
205 break;
206 case UserPromptLabels.RejectAll:
207 vscode.commands.executeCommand("continue.rejectDiff", path);
208 break;
209 case QuickEditInitialItemLabels.Submit:
210 if (quickPick.value) {
211 await vscode.commands.executeCommand("continue.rejectDiff", path);
212 const newPrompt = quickPick.value;
213 appendToHistory(newPrompt, this.context);
214 this.handleUserPrompt(newPrompt, path);
215 }
216 break;
217 default:
218 break;
219 }
220 let model = await this.getCurModel();
221
222 void DataLogger.getInstance().logDevData({
223 name: "quickEdit",
224 data: {
225 prompt,
226 path,
227 label,
228 diffs: this.verticalDiffManager.logDiffs,
229 model: model?.title,
230 },
231 });
232
233 quickPick.dispose();
234 });
235 }
236
237 private handleUserPrompt = async (
238 prompt: string,
239 path: string | undefined,
240 ) => {
241 const modelTitle = await this.getCurModel();
242 if (!modelTitle) {
243 throw new Error("No model selected");
244 }
245
246 const { config } = await this.configHandler.loadConfig();
247 const rules = config?.rules ?? []; // no need to error - getCurModel above will handle
248
249 await this._streamEditWithInputAndContext(prompt, modelTitle, rules);
250 this.openAcceptRejectMenu(prompt, path);
251 };
252
253 private setActiveEditorAndPrevInput(editor: vscode.TextEditor) {
254 const existingHandler = this.verticalDiffManager.getHandlerForFile(
255 editor.document.uri.toString(),
256 );
257
258 this.editorWhenOpened = editor;
259 this.previousInput = existingHandler?.options.input;
260 }
261
262 /**
263 * Gets the model title the user has chosen, or their default model
264 */
265 private async getCurModel(): Promise<ILLM | null> {
266 const { config } = await this.configHandler.loadConfig();
267 if (!config) {
268 return null;
269 }
270
271 return config.selectedModelByRole.edit ?? config.selectedModelByRole.chat;
272 }
273
274 /**
275 * Generates a title for the Quick Pick, including the
276 * file name and selected line(s) if available.
277 *
278 * @example
279 * // "Edit myFile.ts", "Edit myFile.ts:5-10", "Edit myFile.ts:15"
280 */
281 private getQuickPickTitle = () => {
282 const { uri } = this.editorWhenOpened.document;
283
284 const fileName = vscode.workspace.asRelativePath(uri, true);
285
286 if (!this.range) {
287 throw new Error("Range is undefined");
288 }
289
290 const { start, end } = this.range;
291
292 const isSelectionEmpty = start.isEqual(end);
293
294 return isSelectionEmpty
295 ? `Edit ${fileName}`
296 : `Edit ${fileName}:${start.line}${
297 end.line > start.line ? `-${end.line}` : ""
298 }`;
299 };
300
301 private async _streamEditWithInputAndContext(
302 prompt: string,
303 model: ILLM,
304 rules: RuleWithSource[],
305 ) {
306 // Extracts all file references from the prompt string,
307 // which are denoted by an '@' symbol followed by
308 // one or more non-whitespace characters.
309 const fileReferences = prompt.match(/@[^\s]+/g) || [];
310
311 // Replace file references with the content of the file
312 for (const fileRef of fileReferences) {
313 const filePath = fileRef.slice(1); // Remove the '@' symbol
314
315 const fileContent = await this.ide.readFile(filePath);
316
317 prompt = prompt.replace(
318 fileRef,
319 `\`\`\`${filePath}\n${fileContent}\n\`\`\`\n\n`,
320 );
321 }
322
323 if (this.contextProviderStr) {
324 prompt = this.contextProviderStr + prompt;
325 }
326
327 void this.webviewProtocol.request("incrementFtc", undefined);
328
329 await this.verticalDiffManager.streamEdit({
330 input: prompt,
331 llm: model,
332 quickEdit: this.previousInput,
333 range: this.range,
334 rulesToInclude: rules,
335 isApply: false,
336 });
337 }
338
339 private getInitialItems(): vscode.QuickPickItem[] {
340 return [
341 {
342 label: QuickEditInitialItemLabels.History,
343 detail: "$(history) Select previous prompts",
344 },
345 {
346 label: QuickEditInitialItemLabels.ContextProviders,
347 detail: "$(add) Add context to your prompt",
348 },
349 ];
350 }
351
352 async _getInitialQuickPickVal(): Promise<{
353 label: QuickEditInitialItemLabels | undefined;
354 value: string | undefined;
355 }> {
356 const model = await this.getCurModel();
357
358 if (!model) {
359 this.ide.showToast("error", "Please configure a model to use Quick Edit");
360 return { label: undefined, value: undefined };
361 }
362
363 const quickPick = vscode.window.createQuickPick();
364
365 const initialItems = this.getInitialItems();
366 quickPick.items = initialItems;
367 quickPick.placeholder =
368 "Enter a prompt to edit your code (@ to search files, ⏎ to submit)";
369 quickPick.title = this.getQuickPickTitle();
370 quickPick.ignoreFocusOut = true;
371 quickPick.value = this.initialPrompt ?? "";
372
373 quickPick.show();
374
375 quickPick.onDidChangeValue((value) =>
376 this.handleQuickPickChange({ value, quickPick, initialItems }),
377 );
378 /**
379 * Waits for the user to select an item from the quick pick.
380 *
381 * @returns {Promise<string | undefined>} The label of the selected item, or undefined if no item was selected.
382 */
383 const selectedItemLabel = await new Promise<
384 QuickEditInitialItemLabels | undefined
385 >((resolve) =>
386 quickPick.onDidAccept(() => {
387 this.handleQuickPickAccept({
388 quickPick,
389 resolve,
390 });
391 }),
392 );
393
394 return {
395 label: selectedItemLabel,
396 value: quickPick.value,
397 };
398 }
399
400 /**
401 * Programatically modify the Quick Pick items based on the input value.
402 *
403 * Shows the current file for a new file search, performs a file search,
404 * or shows the submit option.
405 *
406 * If the input is empty, shows the initial items.
407 */
408 private handleQuickPickChange = ({
409 value,
410 quickPick,
411 initialItems,
412 }: {
413 value: string;
414 quickPick: vscode.QuickPick<vscode.QuickPickItem>;
415 initialItems: vscode.QuickPickItem[];
416 }) => {
417 const { uri } = this.editorWhenOpened.document;
418
419 if (value !== "") {
420 switch (true) {
421 case value.endsWith(FILE_SEARCH_CHAR):
422 quickPick.items = [
423 {
424 label: vscode.workspace.asRelativePath(uri),
425 description: "Current file",
426 alwaysShow: true,
427 },
428 ];
429 break;
430
431 case QuickEdit.hasFileSearchQueryRegex.test(value):
432 const lastAtIndex = value.lastIndexOf(FILE_SEARCH_CHAR);
433
434 // The search query is the last instance of the
435 // search character to the end of the string
436 const searchQuery = value.substring(lastAtIndex + 1);
437
438 const searchResults = this.fileSearch.search(searchQuery);
439
440 if (searchResults.length > 0) {
441 quickPick.items = searchResults
442 .map(({ relativePath }) => ({
443 label: relativePath,
444 alwaysShow: true,
445 }))
446 .slice(0, QuickEdit.maxFileSearchResults);
447 } else {
448 quickPick.items = [NO_RESULTS_ITEM];
449 }
450
451 break;
452
453 default:
454 // The user does not have a file search in progress,
455 // tso only show the submit option
456 quickPick.items = [SUBMIT_ITEM];
457 break;
458 }
459 } else {
460 quickPick.items = initialItems;
461 }
462 };
463
464 /**
465 * If the selected item is a file, it replaces the file search query
466 * with the selected file path and allows further editing.
467 *
468 * If the selected item is an initial item, it closes the quick pick
469 * and returns the selected item label.
470 */
471 private handleQuickPickAccept = ({
472 quickPick,
473 resolve,
474 }: {
475 quickPick: vscode.QuickPick<vscode.QuickPickItem>;
476 resolve: (value: QuickEditInitialItemLabels | undefined) => void;
477 }) => {
478 const { label } = quickPick.selectedItems[0];
479
480 // If not an initial item, it's a file selection. Allow continued prompt editing.
481 const isFileSelection = !Object.values(QuickEditInitialItemLabels).includes(
482 label as QuickEditInitialItemLabels,
483 );
484
485 if (isFileSelection) {
486 // Replace the file search query with the selected file path
487 const curValue = quickPick.value;
488 const newValue =
489 curValue.substring(0, curValue.lastIndexOf("@") + 1) + label + " ";
490
491 quickPick.value = newValue;
492 quickPick.items = [SUBMIT_ITEM];
493 resolve(undefined);
494 } else {
495 // The user has selected one of the initial items, so we close the Quick Pick
496 resolve(label as QuickEditInitialItemLabels);
497 quickPick.dispose();
498 }
499 };
500
501 private async handleSelect({
502 selectedLabel,
503 selectedValue,
504 editor,
505 params,
506 }: {
507 selectedLabel: QuickEditInitialItemLabels | undefined;
508 selectedValue: string | undefined;
509 editor: vscode.TextEditor;
510 params: QuickEditShowParams | undefined;
511 }) {
512 const { config } = await this.configHandler.loadConfig();
513 if (!config) {
514 throw new Error("Config not loaded");
515 }
516
517 let prompt: string | undefined;
518 switch (selectedLabel) {
519 case QuickEditInitialItemLabels.History:
520 const historyVal = await getHistoryQuickPickVal(this.context);
521 prompt = historyVal ?? "";
522 break;
523
524 case QuickEditInitialItemLabels.ContextProviders:
525 const contextProviderVal = await getContextProviderQuickPickVal(
526 config,
527 this.ide,
528 );
529 this.contextProviderStr = contextProviderVal ?? "";
530
531 // Recurse back to let the user write their prompt
532 this.initiateNewQuickPick(editor, params);
533
534 break;
535
536 case QuickEditInitialItemLabels.Submit:
537 if (selectedValue) {
538 prompt = selectedValue;
539 appendToHistory(selectedValue, this.context);
540 }
541 }
542
543 return prompt;
544 }
545
546 /**
547 * Reset the state of the quick pick
548 */
549 private clear() {
550 this.initialPrompt = undefined;
551 this.range = undefined;
552 }
553}