Skip to content

Commit 62e9cfb

Browse files
authored
feat(amazonq): add button to view diff in IDE (aws#5338)
Add `Accept Diff` & `View Diff` button to Amazon Q for auto generated code. https://github.com/user-attachments/assets/2bd6cf19-0649-4355-8ac5-7eb87bfe27fb ## License By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.
1 parent 562128a commit 62e9cfb

File tree

29 files changed

+754
-64
lines changed

29 files changed

+754
-64
lines changed
Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
{
2+
"type": "Feature",
3+
"description": "Add buttons to code blocks to view and accept diffs."
4+
}

packages/amazonq/src/extension.ts

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,11 +20,14 @@ import {
2020
import { makeEndpointsProvider, registerGenericCommands } from 'aws-core-vscode'
2121
import { CommonAuthWebview } from 'aws-core-vscode/login'
2222
import {
23+
amazonQDiffScheme,
2324
DefaultAWSClientBuilder,
2425
DefaultAwsContext,
2526
ExtContext,
2627
RegionProvider,
2728
Settings,
29+
VirtualFileSystem,
30+
VirtualMemoryFile,
2831
activateLogger,
2932
activateTelemetry,
3033
env,
@@ -136,6 +139,14 @@ export async function activateAmazonQCommon(context: vscode.ExtensionContext, is
136139
// Handle Amazon Q Extension un-installation.
137140
setupUninstallHandler(VSCODE_EXTENSION_ID.amazonq, context.extension.packageJSON.version, context)
138141

142+
const vfs = new VirtualFileSystem()
143+
144+
// Register an empty file that's used when a to open a diff
145+
vfs.registerProvider(
146+
vscode.Uri.from({ scheme: amazonQDiffScheme, path: 'empty' }),
147+
new VirtualMemoryFile(new Uint8Array())
148+
)
149+
139150
// Hide the Amazon Q tree in toolkit explorer
140151
await setContext('aws.toolkit.amazonq.dismissed', true)
141152

packages/amazonq/test/e2e/amazonq/featureDev.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ describe('Amazon Q Feature Dev', function () {
110110

111111
beforeEach(() => {
112112
registerAuthHook('amazonq-test-account')
113-
framework = new qTestingFramework('featuredev', true)
113+
framework = new qTestingFramework('featuredev', true, [])
114114
tab = framework.createTab()
115115
})
116116

@@ -135,7 +135,7 @@ describe('Amazon Q Feature Dev', function () {
135135
it('Does NOT show /dev when feature dev is NOT enabled', () => {
136136
// The beforeEach registers a framework which accepts requests. If we don't dispose before building a new one we have duplicate messages
137137
framework.dispose()
138-
framework = new qTestingFramework('featuredev', false)
138+
framework = new qTestingFramework('featuredev', false, [])
139139
const tab = framework.createTab()
140140
const command = tab.findCommand('/dev')
141141
if (command.length > 0) {

packages/amazonq/test/e2e/amazonq/framework/framework.ts

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import * as vscode from 'vscode'
1212
import { MynahUI, MynahUIProps } from '@aws/mynah-ui'
1313
import { DefaultAmazonQAppInitContext, TabType, createMynahUI } from 'aws-core-vscode/amazonq'
1414
import { Messenger, MessengerOptions } from './messenger'
15+
import { FeatureContext } from 'aws-core-vscode/shared'
1516

1617
/**
1718
* Abstraction over Amazon Q to make e2e testing easier
@@ -23,7 +24,7 @@ export class qTestingFramework {
2324

2425
lastEventId: string = ''
2526

26-
constructor(featureName: TabType, amazonQEnabled: boolean) {
27+
constructor(featureName: TabType, amazonQEnabled: boolean, featureConfigsSerialized: [string, FeatureContext][]) {
2728
/**
2829
* Instantiate the UI and override the postMessage to publish using the app message
2930
* publishers directly.
@@ -42,7 +43,8 @@ export class qTestingFramework {
4243
appMessagePublisher.publish(message)
4344
},
4445
},
45-
amazonQEnabled
46+
amazonQEnabled,
47+
featureConfigsSerialized
4648
)
4749
this.mynahUI = ui.mynahUI
4850
this.mynahUIProps = (this.mynahUI as any).props

packages/core/src/amazonq/commons/controllers/contentController.ts

Lines changed: 122 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,28 @@
44
*/
55

66
import * as vscode from 'vscode'
7+
import path from 'path'
78
import { Position, TextEditor, window } from 'vscode'
89
import { getLogger } from '../../../shared/logger'
10+
import { amazonQDiffScheme, amazonQTabSuffix } from '../../../shared/constants'
11+
import { disposeOnEditorClose } from '../../../shared/utilities/editorUtilities'
12+
import {
13+
applyChanges,
14+
createTempFileForDiff,
15+
getSelectionFromRange,
16+
} from '../../../shared/utilities/textDocumentUtilities'
17+
import { extractFileAndCodeSelectionFromMessage, fs, getErrorMsg, getIndentedCode, ToolkitError } from '../../../shared'
18+
19+
class ContentProvider implements vscode.TextDocumentContentProvider {
20+
constructor(private uri: vscode.Uri) {}
21+
22+
provideTextDocumentContent(_uri: vscode.Uri) {
23+
return fs.readFileText(this.uri.fsPath)
24+
}
25+
}
26+
27+
const chatDiffCode = 'ChatDiff'
28+
const ChatDiffError = ToolkitError.named(chatDiffCode)
929

1030
export class EditorContentController {
1131
/* *
@@ -52,4 +72,106 @@ export class EditorContentController {
5272
)
5373
}
5474
}
75+
76+
/**
77+
* Accepts and applies a diff to a file, then closes the associated diff view tab.
78+
*
79+
* @param {any} message - The message containing diff information.
80+
* @returns {Promise<void>} A promise that resolves when the diff is applied and the tab is closed.
81+
*
82+
* @description
83+
* This method performs the following steps:
84+
* 1. Extracts file path and selection from the message.
85+
* 2. If valid file path, non-empty code, and selection are present:
86+
* a. Opens the document.
87+
* b. Gets the indented code to update.
88+
* c. Applies the changes to the document.
89+
* d. Attempts to close the diff view tab for the file.
90+
*
91+
* @throws {Error} If there's an issue opening the document or applying changes.
92+
*/
93+
public async acceptDiff(message: any) {
94+
const errorNotification = 'Unable to Apply code changes.'
95+
const { filePath, selection } = extractFileAndCodeSelectionFromMessage(message)
96+
97+
if (filePath && message?.code?.trim().length > 0 && selection) {
98+
try {
99+
const doc = await vscode.workspace.openTextDocument(filePath)
100+
101+
const code = getIndentedCode(message, doc, selection)
102+
const range = getSelectionFromRange(doc, selection)
103+
await applyChanges(doc, range, code)
104+
105+
// Sets the editor selection from the start of the given range, extending it by the number of lines in the code till the end of the last line
106+
const editor = await vscode.window.showTextDocument(doc)
107+
editor.selection = new vscode.Selection(
108+
range.start,
109+
new Position(range.start.line + code.split('\n').length, Number.MAX_SAFE_INTEGER)
110+
)
111+
112+
// If vscode.diff is open for the filePath then close it.
113+
vscode.window.tabGroups.all.flatMap(({ tabs }) =>
114+
tabs.map((tab) => {
115+
if (tab.label === `${path.basename(filePath)} ${amazonQTabSuffix}`) {
116+
const tabClosed = vscode.window.tabGroups.close(tab)
117+
if (!tabClosed) {
118+
getLogger().error(
119+
'%s: Unable to close the diff view tab for %s',
120+
chatDiffCode,
121+
tab.label
122+
)
123+
}
124+
}
125+
})
126+
)
127+
} catch (error) {
128+
void vscode.window.showInformationMessage(errorNotification)
129+
const wrappedError = ChatDiffError.chain(error, `Failed to Accept Diff`, { code: chatDiffCode })
130+
getLogger().error('%s: Failed to open diff view %s', chatDiffCode, getErrorMsg(wrappedError, true))
131+
throw wrappedError
132+
}
133+
}
134+
}
135+
136+
/**
137+
* Displays a diff view comparing proposed changes with the existing file.
138+
*
139+
* How is diff generated:
140+
* 1. Creates a temporary file as a clone of the original file.
141+
* 2. Applies the proposed changes to the temporary file within the selected range.
142+
* 3. Opens a diff view comparing original file to the temporary file.
143+
*
144+
* This approach ensures that the diff view only shows the changes proposed by Amazon Q,
145+
* isolating them from any other modifications in the original file.
146+
*
147+
* @param message the message from Amazon Q chat
148+
*/
149+
public async viewDiff(message: any, scheme: string = amazonQDiffScheme) {
150+
const errorNotification = 'Unable to Open Diff.'
151+
const { filePath, selection } = extractFileAndCodeSelectionFromMessage(message)
152+
153+
try {
154+
if (filePath && message?.code?.trim().length > 0 && selection) {
155+
const originalFileUri = vscode.Uri.file(filePath)
156+
const uri = await createTempFileForDiff(originalFileUri, message, selection, scheme)
157+
158+
// Register content provider and show diff
159+
const contentProvider = new ContentProvider(uri)
160+
const disposable = vscode.workspace.registerTextDocumentContentProvider(scheme, contentProvider)
161+
await vscode.commands.executeCommand(
162+
'vscode.diff',
163+
originalFileUri,
164+
uri,
165+
`${path.basename(filePath)} ${amazonQTabSuffix}`
166+
)
167+
168+
disposeOnEditorClose(uri, disposable)
169+
}
170+
} catch (error) {
171+
void vscode.window.showInformationMessage(errorNotification)
172+
const wrappedError = ChatDiffError.chain(error, `Failed to Open Diff View`, { code: chatDiffCode })
173+
getLogger().error('%s: Failed to open diff view %s', chatDiffCode, getErrorMsg(wrappedError, true))
174+
throw wrappedError
175+
}
176+
}
55177
}

packages/core/src/amazonq/index.ts

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,17 +28,22 @@ export { listCodeWhispererCommandsWalkthrough } from '../codewhisperer/ui/status
2828
export { focusAmazonQPanel, focusAmazonQPanelKeybinding } from '../codewhispererChat/commands/registerCommands'
2929
export { TryChatCodeLensProvider, tryChatCodeLensCommand } from '../codewhispererChat/editor/codelens'
3030
export { createAmazonQUri, openDiff, openDeletedDiff, getOriginalFileUri, getFileDiffUris } from './commons/diff'
31+
import { FeatureContext } from '../shared'
3132

3233
/**
3334
* main from createMynahUI is a purely browser dependency. Due to this
3435
* we need to create a wrapper function that will dynamically execute it
3536
* while only running on browser instances (like the e2e tests). If we
3637
* just export it regularly we will get "ReferenceError: self is not defined"
3738
*/
38-
export function createMynahUI(ideApi: any, amazonQEnabled: boolean) {
39+
export function createMynahUI(
40+
ideApi: any,
41+
amazonQEnabled: boolean,
42+
featureConfigsSerialized: [string, FeatureContext][]
43+
) {
3944
if (typeof window !== 'undefined') {
4045
const mynahUI = require('./webview/ui/main')
41-
return mynahUI.createMynahUI(ideApi, amazonQEnabled)
46+
return mynahUI.createMynahUI(ideApi, amazonQEnabled, featureConfigsSerialized)
4247
}
4348
throw new Error('Not implemented for node')
4449
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/*!
2+
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3+
* SPDX-License-Identifier: Apache-2.0
4+
*/
5+
6+
/**
7+
* Converts an array of key-value pairs into a Map object.
8+
*
9+
* @param {[unknown, unknown][]} arr - An array of tuples, where each tuple represents a key-value pair.
10+
* @returns {Map<unknown, unknown>} A new Map object created from the input array.
11+
* If the conversion fails, an empty Map is returned.
12+
*
13+
* @example
14+
* const array = [['key1', 'value1'], ['key2', 'value2']];
15+
* const map = tryNewMap(array);
16+
* // map is now a Map object with entries: { 'key1' => 'value1', 'key2' => 'value2' }
17+
*/
18+
export function tryNewMap(arr: [unknown, unknown][]) {
19+
try {
20+
return new Map(arr)
21+
} catch (error) {
22+
return new Map()
23+
}
24+
}

packages/core/src/amazonq/webview/generators/webViewContent.ts

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import path from 'path'
77
import { Uri, Webview } from 'vscode'
88
import { AuthUtil } from '../../../codewhisperer/util/authUtil'
9-
import { globals } from '../../../shared'
9+
import { FeatureConfigProvider, FeatureContext, globals } from '../../../shared'
1010

1111
export class WebViewContentGenerator {
1212
public async generate(extensionURI: Uri, webView: Webview): Promise<string> {
@@ -45,14 +45,23 @@ export class WebViewContentGenerator {
4545
Uri.joinPath(globals.context.extensionUri, 'resources', 'css', 'amazonq-webview.css')
4646
)
4747

48+
let featureConfigs = new Map<string, FeatureContext>()
49+
try {
50+
await FeatureConfigProvider.instance.fetchFeatureConfigs()
51+
featureConfigs = FeatureConfigProvider.getFeatureConfigs()
52+
} catch (error) {
53+
// eslint-disable-next-line aws-toolkits/no-console-log
54+
console.error('Error fetching feature configs:', error)
55+
}
56+
4857
return `
4958
<script type="text/javascript" src="${javascriptEntrypoint.toString()}" defer onload="init()"></script>
5059
<link rel="stylesheet" href="${cssEntrypoint.toString()}">
5160
<script type="text/javascript">
5261
const init = () => {
5362
createMynahUI(acquireVsCodeApi(), ${
5463
(await AuthUtil.instance.getChatAuthState()).amazonQ === 'connected'
55-
});
64+
},${JSON.stringify(Array.from(featureConfigs.entries()))});
5665
}
5766
</script>
5867
`

packages/core/src/amazonq/webview/ui/apps/cwChatConnector.ts

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ interface ChatPayload {
1818
export interface ConnectorProps {
1919
sendMessageToExtension: (message: ExtensionMessage) => void
2020
onMessageReceived?: (tabID: string, messageData: any, needToShowAPIDocsTab: boolean) => void
21-
onChatAnswerReceived?: (tabID: string, message: CWCChatItem) => void
21+
onChatAnswerReceived?: (tabID: string, message: CWCChatItem, messageData: any) => void
2222
onCWCContextCommandMessage: (message: CWCChatItem, command?: string) => string | undefined
2323
onError: (tabID: string, message: string, title: string) => void
2424
onWarning: (tabID: string, message: string, title: string) => void
@@ -308,7 +308,7 @@ export class Connector {
308308
content: messageData.relatedSuggestions,
309309
}
310310
}
311-
this.onChatAnswerReceived(messageData.tabID, answer)
311+
this.onChatAnswerReceived(messageData.tabID, answer, messageData)
312312

313313
// Exit the function if we received an answer from AI
314314
if (
@@ -336,7 +336,7 @@ export class Connector {
336336
}
337337
: undefined,
338338
}
339-
this.onChatAnswerReceived(messageData.tabID, answer)
339+
this.onChatAnswerReceived(messageData.tabID, answer, messageData)
340340

341341
return
342342
}
@@ -347,13 +347,17 @@ export class Connector {
347347
return
348348
}
349349

350-
this.onChatAnswerReceived(messageData.tabID, {
351-
type: ChatItemType.ANSWER,
352-
messageId: messageData.triggerID,
353-
body: messageData.message,
354-
followUp: this.followUpGenerator.generateAuthFollowUps('cwc', messageData.authType),
355-
canBeVoted: false,
356-
})
350+
this.onChatAnswerReceived(
351+
messageData.tabID,
352+
{
353+
type: ChatItemType.ANSWER,
354+
messageId: messageData.triggerID,
355+
body: messageData.message,
356+
followUp: this.followUpGenerator.generateAuthFollowUps('cwc', messageData.authType),
357+
canBeVoted: false,
358+
},
359+
messageData
360+
)
357361

358362
return
359363
}

0 commit comments

Comments
 (0)