|
6 | 6 | import * as vscode from 'vscode' |
7 | 7 | import { displaySvgDecoration } from './displayImage' |
8 | 8 | import { SvgGenerationService } from './svgGenerator' |
9 | | -import { getLogger } from 'aws-core-vscode/shared' |
| 9 | +import { getContext, getLogger } from 'aws-core-vscode/shared' |
10 | 10 | import { LanguageClient } from 'vscode-languageclient' |
11 | 11 | import { InlineCompletionItemWithReferences } from '@aws/language-server-runtimes/protocol' |
12 | 12 | import { CodeWhispererSession } from '../sessionManager' |
13 | 13 | import type { AmazonQInlineCompletionItemProvider } from '../completion' |
| 14 | +import { vsCodeState } from 'aws-core-vscode/codewhisperer' |
| 15 | +import { applyPatch, createPatch } from 'diff' |
| 16 | +import { EditSuggestionState } from '../editSuggestionState' |
14 | 17 |
|
15 | | -export async function showEdits( |
16 | | - item: InlineCompletionItemWithReferences, |
17 | | - editor: vscode.TextEditor | undefined, |
18 | | - session: CodeWhispererSession, |
19 | | - languageClient: LanguageClient, |
20 | | - inlineCompletionProvider?: AmazonQInlineCompletionItemProvider |
21 | | -) { |
22 | | - if (!editor) { |
23 | | - return |
| 18 | +function logSuggestionFailure(type: 'DISCARD' | 'REJECT', reason: string, suggestionContent: string) { |
| 19 | + getLogger('nextEditPrediction').debug( |
| 20 | + `Auto ${type} edit suggestion with reason=${reason}, suggetion: ${suggestionContent}` |
| 21 | + ) |
| 22 | +} |
| 23 | + |
| 24 | +const autoRejectEditCursorDistance = 25 |
| 25 | +const maxPrefixRetryCount = 5 |
| 26 | + |
| 27 | +enum RejectReason { |
| 28 | + DocumentChange = 'Invalid patch due to document change', |
| 29 | + NotApplicableToOriginal = 'ApplyPatch fail for original code', |
| 30 | + MaxRetry = 'Already retry 10 times', |
| 31 | +} |
| 32 | + |
| 33 | +export class EditsSuggestionSvg { |
| 34 | + private readonly logger = getLogger('nextEditPrediction') |
| 35 | + private readonly documentChangedListener: vscode.Disposable |
| 36 | + private readonly cursorChangedListener: vscode.Disposable |
| 37 | + private readonly updatedSuggestions: InlineCompletionItemWithReferences[] = [] |
| 38 | + private startLine = 0 |
| 39 | + |
| 40 | + constructor( |
| 41 | + private suggestion: InlineCompletionItemWithReferences, |
| 42 | + private readonly editor: vscode.TextEditor, |
| 43 | + private readonly languageClient: LanguageClient, |
| 44 | + private readonly session: CodeWhispererSession, |
| 45 | + private readonly inlineCompletionProvider?: AmazonQInlineCompletionItemProvider // why nullable? |
| 46 | + ) { |
| 47 | + this.documentChangedListener = vscode.workspace.onDidChangeTextDocument(async (e) => { |
| 48 | + await this.onDocChange(e) |
| 49 | + }) |
| 50 | + |
| 51 | + this.cursorChangedListener = vscode.window.onDidChangeTextEditorSelection((e) => { |
| 52 | + this.onCursorChange(e) |
| 53 | + }) |
24 | 54 | } |
25 | | - try { |
26 | | - const svgGenerationService = new SvgGenerationService() |
27 | | - // Generate your SVG image with the file contents |
28 | | - const currentFile = editor.document.uri.fsPath |
29 | | - const { svgImage, startLine, newCode, originalCodeHighlightRange } = await svgGenerationService.generateDiffSvg( |
30 | | - currentFile, |
31 | | - item.insertText as string |
32 | | - ) |
33 | 55 |
|
34 | | - // TODO: To investigate why it fails and patch [generateDiffSvg] |
35 | | - if (newCode.length === 0) { |
36 | | - getLogger('nextEditPrediction').warn('not able to apply provided edit suggestion, skip rendering') |
| 56 | + async show() { |
| 57 | + if (!this.editor) { |
37 | 58 | return |
38 | 59 | } |
39 | 60 |
|
40 | | - if (svgImage) { |
41 | | - // display the SVG image |
42 | | - await displaySvgDecoration( |
43 | | - editor, |
44 | | - svgImage, |
45 | | - startLine, |
46 | | - newCode, |
47 | | - originalCodeHighlightRange, |
48 | | - session, |
49 | | - languageClient, |
50 | | - item, |
51 | | - inlineCompletionProvider |
| 61 | + const item = |
| 62 | + this.updatedSuggestions.length > 0 |
| 63 | + ? this.updatedSuggestions[this.updatedSuggestions.length - 1] |
| 64 | + : this.suggestion |
| 65 | + |
| 66 | + try { |
| 67 | + const svgGenerationService = new SvgGenerationService() |
| 68 | + // Generate your SVG image with the file contents |
| 69 | + const currentFile = this.editor.document.uri.fsPath |
| 70 | + const { svgImage, startLine, newCode, originalCodeHighlightRange } = |
| 71 | + await svgGenerationService.generateDiffSvg(currentFile, this.suggestion.insertText as string) |
| 72 | + |
| 73 | + // For cursorChangeListener to access |
| 74 | + this.startLine = startLine |
| 75 | + |
| 76 | + // TODO: To investigate why it fails and patch [generateDiffSvg] |
| 77 | + if (newCode.length === 0) { |
| 78 | + this.logger.warn('not able to apply provided edit suggestion, skip rendering') |
| 79 | + return |
| 80 | + } |
| 81 | + |
| 82 | + if (svgImage) { |
| 83 | + // display the SVG image |
| 84 | + await displaySvgDecoration( |
| 85 | + this.editor, |
| 86 | + svgImage, |
| 87 | + startLine, |
| 88 | + newCode, |
| 89 | + originalCodeHighlightRange, |
| 90 | + this.session, |
| 91 | + this.languageClient, |
| 92 | + item, |
| 93 | + [this.documentChangedListener, this.cursorChangedListener], |
| 94 | + this.inlineCompletionProvider |
| 95 | + ) |
| 96 | + } else { |
| 97 | + this.logger.error('SVG image generation returned an empty result.') |
| 98 | + } |
| 99 | + } catch (error) { |
| 100 | + this.logger.error(`Error generating SVG image: ${error}`) |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + private onCursorChange(e: vscode.TextEditorSelectionChangeEvent) { |
| 105 | + if (!EditSuggestionState.isEditSuggestionActive()) { |
| 106 | + return |
| 107 | + } |
| 108 | + if (e.textEditor !== this.editor) { |
| 109 | + return |
| 110 | + } |
| 111 | + const currentPosition = e.selections[0].active |
| 112 | + const distance = Math.abs(currentPosition.line - this.startLine) |
| 113 | + if (distance > autoRejectEditCursorDistance) { |
| 114 | + logSuggestionFailure( |
| 115 | + 'REJECT', |
| 116 | + `cursor position move too far away off ${autoRejectEditCursorDistance} lines`, |
| 117 | + this.suggestion.insertText as string |
52 | 118 | ) |
53 | | - } else { |
54 | | - getLogger('nextEditPrediction').error('SVG image generation returned an empty result.') |
| 119 | + void vscode.commands.executeCommand('aws.amazonq.inline.rejectEdit') |
55 | 120 | } |
56 | | - } catch (error) { |
57 | | - getLogger('nextEditPrediction').error(`Error generating SVG image: ${error}`) |
| 121 | + } |
| 122 | + |
| 123 | + private async onDocChange(e: vscode.TextDocumentChangeEvent) { |
| 124 | + if (e.contentChanges.length <= 0) { |
| 125 | + return |
| 126 | + } |
| 127 | + if (e.document !== this.editor.document) { |
| 128 | + return |
| 129 | + } |
| 130 | + if (vsCodeState.isCodeWhispererEditing) { |
| 131 | + return |
| 132 | + } |
| 133 | + if (getContext('aws.amazonq.editSuggestionActive') === false) { |
| 134 | + return |
| 135 | + } |
| 136 | + |
| 137 | + /** |
| 138 | + * 1. Take the diff returned by the model and apply it to the code we originally sent to the model |
| 139 | + * 2. Do a diff between the above code and what's currently in the editor |
| 140 | + * 3. Show this second diff to the user as the edit suggestion |
| 141 | + */ |
| 142 | + // Users' file content when the request fires (best guess because the actual process happens in language server) |
| 143 | + const originalCode = this.session.fileContent |
| 144 | + const appliedToOriginal = applyPatch(originalCode, this.suggestion.insertText as string) |
| 145 | + try { |
| 146 | + if (appliedToOriginal) { |
| 147 | + const updatedPatch = this.patchSuggestion(appliedToOriginal) |
| 148 | + |
| 149 | + if (this.updatedSuggestions.length > maxPrefixRetryCount) { |
| 150 | + this.autoReject(RejectReason.MaxRetry) |
| 151 | + } else if (applyPatch(this.editor.document.getText(), updatedPatch) === false) { |
| 152 | + this.autoReject(RejectReason.DocumentChange) |
| 153 | + } |
| 154 | + |
| 155 | + await this.show() |
| 156 | + } else { |
| 157 | + this.autoReject(RejectReason.NotApplicableToOriginal) |
| 158 | + } |
| 159 | + } catch (e) { |
| 160 | + // TODO: format |
| 161 | + this.logger.error(`${e}`) |
| 162 | + } |
| 163 | + } |
| 164 | + |
| 165 | + private autoReject(reason: string) { |
| 166 | + logSuggestionFailure('REJECT', reason, this.suggestion.insertText as string) |
| 167 | + void vscode.commands.executeCommand('aws.amazonq.inline.rejectEdit') |
| 168 | + } |
| 169 | + |
| 170 | + private patchSuggestion(appliedToOriginal: string): string { |
| 171 | + const updatedPatch = createPatch( |
| 172 | + this.editor.document.fileName, |
| 173 | + this.editor.document.getText(), |
| 174 | + appliedToOriginal |
| 175 | + ) |
| 176 | + |
| 177 | + this.logger.info(`Update edit suggestion\n ${updatedPatch}`) |
| 178 | + const updated: InlineCompletionItemWithReferences = { ...this.suggestion, insertText: updatedPatch } |
| 179 | + this.updatedSuggestions.push(updated) |
| 180 | + return updatedPatch |
58 | 181 | } |
59 | 182 | } |
0 commit comments