Elffuss BraidHub

kikocis/continue public

d1cdc8b8ac2b · 15.5 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 });
336 }
337
338 private getInitialItems(): vscode.QuickPickItem[] {
339 return [
340 {
341 label: QuickEditInitialItemLabels.History,
342 detail: "$(history) Select previous prompts",
343 },
344 {
345 label: QuickEditInitialItemLabels.ContextProviders,
346 detail: "$(add) Add context to your prompt",
347 },
348 ];
349 }
350
351 async _getInitialQuickPickVal(): Promise<{
352 label: QuickEditInitialItemLabels | undefined;
353 value: string | undefined;
354 }> {
355 const model = await this.getCurModel();
356
357 if (!model) {
358 this.ide.showToast("error", "Please configure a model to use Quick Edit");
359 return { label: undefined, value: undefined };
360 }
361
362 const quickPick = vscode.window.createQuickPick();
363
364 const initialItems = this.getInitialItems();
365 quickPick.items = initialItems;
366 quickPick.placeholder =
367 "Enter a prompt to edit your code (@ to search files, ⏎ to submit)";
368 quickPick.title = this.getQuickPickTitle();
369 quickPick.ignoreFocusOut = true;
370 quickPick.value = this.initialPrompt ?? "";
371
372 quickPick.show();
373
374 quickPick.onDidChangeValue((value) =>
375 this.handleQuickPickChange({ value, quickPick, initialItems }),
376 );
377 /**
378 * Waits for the user to select an item from the quick pick.
379 *
380 * @returns {Promise<string | undefined>} The label of the selected item, or undefined if no item was selected.
381 */
382 const selectedItemLabel = await new Promise<
383 QuickEditInitialItemLabels | undefined
384 >((resolve) =>
385 quickPick.onDidAccept(() => {
386 this.handleQuickPickAccept({
387 quickPick,
388 resolve,
389 });
390 }),
391 );
392
393 return {
394 label: selectedItemLabel,
395 value: quickPick.value,
396 };
397 }
398
399 /**
400 * Programatically modify the Quick Pick items based on the input value.
401 *
402 * Shows the current file for a new file search, performs a file search,
403 * or shows the submit option.
404 *
405 * If the input is empty, shows the initial items.
406 */
407 private handleQuickPickChange = ({
408 value,
409 quickPick,
410 initialItems,
411 }: {
412 value: string;
413 quickPick: vscode.QuickPick<vscode.QuickPickItem>;
414 initialItems: vscode.QuickPickItem[];
415 }) => {
416 const { uri } = this.editorWhenOpened.document;
417
418 if (value !== "") {
419 switch (true) {
420 case value.endsWith(FILE_SEARCH_CHAR):
421 quickPick.items = [
422 {
423 label: vscode.workspace.asRelativePath(uri),
424 description: "Current file",
425 alwaysShow: true,
426 },
427 ];
428 break;
429
430 case QuickEdit.hasFileSearchQueryRegex.test(value):
431 const lastAtIndex = value.lastIndexOf(FILE_SEARCH_CHAR);
432
433 // The search query is the last instance of the
434 // search character to the end of the string
435 const searchQuery = value.substring(lastAtIndex + 1);
436
437 const searchResults = this.fileSearch.search(searchQuery);
438
439 if (searchResults.length > 0) {
440 quickPick.items = searchResults
441 .map(({ relativePath }) => ({
442 label: relativePath,
443 alwaysShow: true,
444 }))
445 .slice(0, QuickEdit.maxFileSearchResults);
446 } else {
447 quickPick.items = [NO_RESULTS_ITEM];
448 }
449
450 break;
451
452 default:
453 // The user does not have a file search in progress,
454 // tso only show the submit option
455 quickPick.items = [SUBMIT_ITEM];
456 break;
457 }
458 } else {
459 quickPick.items = initialItems;
460 }
461 };
462
463 /**
464 * If the selected item is a file, it replaces the file search query
465 * with the selected file path and allows further editing.
466 *
467 * If the selected item is an initial item, it closes the quick pick
468 * and returns the selected item label.
469 */
470 private handleQuickPickAccept = ({
471 quickPick,
472 resolve,
473 }: {
474 quickPick: vscode.QuickPick<vscode.QuickPickItem>;
475 resolve: (value: QuickEditInitialItemLabels | undefined) => void;
476 }) => {
477 const { label } = quickPick.selectedItems[0];
478
479 // If not an initial item, it's a file selection. Allow continued prompt editing.
480 const isFileSelection = !Object.values(QuickEditInitialItemLabels).includes(
481 label as QuickEditInitialItemLabels,
482 );
483
484 if (isFileSelection) {
485 // Replace the file search query with the selected file path
486 const curValue = quickPick.value;
487 const newValue =
488 curValue.substring(0, curValue.lastIndexOf("@") + 1) + label + " ";
489
490 quickPick.value = newValue;
491 quickPick.items = [SUBMIT_ITEM];
492 resolve(undefined);
493 } else {
494 // The user has selected one of the initial items, so we close the Quick Pick
495 resolve(label as QuickEditInitialItemLabels);
496 quickPick.dispose();
497 }
498 };
499
500 private async handleSelect({
501 selectedLabel,
502 selectedValue,
503 editor,
504 params,
505 }: {
506 selectedLabel: QuickEditInitialItemLabels | undefined;
507 selectedValue: string | undefined;
508 editor: vscode.TextEditor;
509 params: QuickEditShowParams | undefined;
510 }) {
511 const { config } = await this.configHandler.loadConfig();
512 if (!config) {
513 throw new Error("Config not loaded");
514 }
515
516 let prompt: string | undefined;
517 switch (selectedLabel) {
518 case QuickEditInitialItemLabels.History:
519 const historyVal = await getHistoryQuickPickVal(this.context);
520 prompt = historyVal ?? "";
521 break;
522
523 case QuickEditInitialItemLabels.ContextProviders:
524 const contextProviderVal = await getContextProviderQuickPickVal(
525 config,
526 this.ide,
527 );
528 this.contextProviderStr = contextProviderVal ?? "";
529
530 // Recurse back to let the user write their prompt
531 this.initiateNewQuickPick(editor, params);
532
533 break;
534
535 case QuickEditInitialItemLabels.Submit:
536 if (selectedValue) {
537 prompt = selectedValue;
538 appendToHistory(selectedValue, this.context);
539 }
540 }
541
542 return prompt;
543 }
544
545 /**
546 * Reset the state of the quick pick
547 */
548 private clear() {
549 this.initialPrompt = undefined;
550 this.range = undefined;
551 }
552}