Skip to content

Commit 8c7ec00

Browse files
committed
refactor(codewhisperer): use globalState abstraction
1 parent 9891c8c commit 8c7ec00

File tree

14 files changed

+98
-121
lines changed

14 files changed

+98
-121
lines changed

packages/core/src/amazonq/util/viewBadgeHandler.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,8 +71,7 @@ async function showInitialViewBadge() {
7171
* @returns True if the badge should be shown, false otherwise
7272
*/
7373
export async function shouldShowBadge(): Promise<boolean> {
74-
const memento = globals.context.globalState
75-
const hasAlreadyShown = memento.get('hasAlreadyOpenedAmazonQ')
74+
const hasAlreadyShown = globals.globalState.get('hasAlreadyOpenedAmazonQ')
7675
if (!hasAlreadyShown) {
7776
const state = await AuthUtil.instance.getChatAuthState()
7877
if (state.codewhispererCore === 'connected' && state.codewhispererChat !== 'connected') {

packages/core/src/auth/auth.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ export class Auth implements AuthService, ConnectionManager {
302302

303303
// Remove the split session logout prompt, if it exists.
304304
if (!isAmazonQ()) {
305-
await globals.context.globalState.update(SessionSeparationPrompt.instance.dismissKey, true)
305+
await globals.globalState.update('aws.toolkit.separationPromptDismissed', true)
306306
}
307307

308308
try {
@@ -1029,9 +1029,6 @@ type LoginCommand = 'aws.toolkit.auth.manageConnections' | 'aws.codecatalyst.man
10291029
* TODO: Remove after some time.
10301030
*/
10311031
export class SessionSeparationPrompt {
1032-
public readonly dismissKey = 'aws.toolkit.separationPromptDismissed'
1033-
private readonly loginCmdKey = 'aws.toolkit.separationPromptCommand'
1034-
10351032
// Local variable handles per session displays, e.g. we forgot a CodeCatalyst connection AND
10361033
// an Explorer only connection. We only want to display once in this case.
10371034
// However, we don't want to set this at the global state level until a user interacts with the
@@ -1043,7 +1040,7 @@ export class SessionSeparationPrompt {
10431040
* which is useful to redisplay the prompt after reloads in case a user misses it.
10441041
*/
10451042
public async showAnyPreviousPrompt() {
1046-
const cmd = globals.context.globalState.get<string>(this.loginCmdKey)
1043+
const cmd = globals.globalState.tryGet('aws.toolkit.separationPromptCommand', String)
10471044
return cmd ? await this.showForCommand(cmd as LoginCommand) : undefined
10481045
}
10491046

@@ -1053,11 +1050,14 @@ export class SessionSeparationPrompt {
10531050
* (e.g. codecatalyst sign in vs explorer)
10541051
*/
10551052
public async showForCommand(cmd: LoginCommand) {
1056-
if (this.#separationPromptDisplayed || globals.context.globalState.get<boolean>(this.dismissKey)) {
1053+
if (
1054+
this.#separationPromptDisplayed ||
1055+
globals.globalState.get<boolean>('aws.toolkit.separationPromptDismissed')
1056+
) {
10571057
return
10581058
}
10591059

1060-
await globals.context.globalState.update(this.loginCmdKey, cmd)
1060+
await globals.globalState.update('aws.toolkit.separationPromptCommand', cmd)
10611061

10621062
await telemetry.toolkit_showNotification.run(async () => {
10631063
telemetry.record({ id: 'sessionSeparation' })
@@ -1077,7 +1077,7 @@ export class SessionSeparationPrompt {
10771077
telemetry.record({ action: 'dismiss' })
10781078
}
10791079

1080-
await globals.context.globalState.update(this.dismissKey, true)
1080+
await globals.globalState.update('aws.toolkit.separationPromptDismissed', true)
10811081
})
10821082
})
10831083
})

packages/core/src/awsService/s3/commands/uploadFile.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -437,7 +437,7 @@ export async function promptUserForBucket(
437437
}
438438
})
439439

440-
const lastTouchedFolder = globals.context.globalState.get<SavedFolder | undefined>('aws.lastTouchedS3Folder')
440+
const lastTouchedFolder = globals.globalState.tryGet<SavedFolder>('aws.lastTouchedS3Folder', Object)
441441
let lastFolderItem: BucketQuickPickItem | undefined = undefined
442442
if (lastTouchedFolder) {
443443
lastFolderItem = {
@@ -448,7 +448,7 @@ export async function promptUserForBucket(
448448
}
449449
}
450450

451-
const lastUploadedToFolder = globals.context.globalState.get<SavedFolder | undefined>('aws.lastUploadedToS3Folder')
451+
const lastUploadedToFolder = globals.globalState.tryGet<SavedFolder>('aws.lastUploadedToS3Folder', Object)
452452
let lastUploadedFolderItem: BucketQuickPickItem | undefined = undefined
453453
if (lastUploadedToFolder) {
454454
lastUploadedFolderItem = {

packages/core/src/codewhisperer/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ export {
3737
} from './service/transformByQ/transformationResultsViewProvider'
3838
export { parseVersionsListFromPomFile } from './service/transformByQ/transformFileHandler'
3939
export { SecurityPanelViewProvider } from './views/securityPanelViewProvider'
40-
export { get, set, isInlineCompletionEnabled } from './util/commonUtil'
40+
export { isInlineCompletionEnabled } from './util/commonUtil'
4141
export { validateOpenProjects, getOpenProjects } from './service/transformByQ/transformProjectValidationHandler'
4242
export {
4343
DefaultCodeWhispererClient,

packages/core/src/codewhisperer/models/constants.ts

Lines changed: 0 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -134,16 +134,8 @@ export const unsupportedLanguagesCacheTTL = 10 * 60 * 60 * 1000
134134

135135
export const unsupportedLanguagesKey = 'CODEWHISPERER_UNSUPPORTED_LANGUAGES_KEY'
136136

137-
export const autoTriggerEnabledKey = 'CODEWHISPERER_AUTO_TRIGGER_ENABLED'
138-
139-
export const autoScansEnabledKey = 'CODEWHISPERER_AUTO_SCANS_ENABLED'
140-
141137
export const serviceActiveKey = 'CODEWHISPERER_SERVICE_ACTIVE'
142138

143-
export const persistedCustomizationsKey = 'CODEWHISPERER_PERSISTED_CUSTOMIZATIONS'
144-
145-
export const selectedCustomizationKey = 'CODEWHISPERER_SELECTED_CUSTOMIZATION'
146-
147139
export const inlinehintKey = 'CODEWHISPERER_HINT_DISPLAYED'
148140

149141
export type AnnotationChangeSource = 'codewhisperer' | 'selection' | 'editor' | 'content'
@@ -329,8 +321,6 @@ export const updateInlineLockKey = 'CODEWHISPERER_INLINE_UPDATE_LOCK_KEY'
329321

330322
export const newCustomizationMessage = 'You have access to new Amazon Q customizations.'
331323

332-
export const newCustomizationsAvailableKey = 'aws.amazonq.codewhisperer.newCustomizations'
333-
334324
// Start of QCT Strings
335325
export const uploadZipSizeLimitInBytes = 2000000000 // 2GB
336326

packages/core/src/codewhisperer/models/model.ts

Lines changed: 6 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,6 @@ import {
1515
} from '../../shared/telemetry/telemetry'
1616
import { References } from '../client/codewhisperer'
1717
import globals from '../../shared/extensionGlobals'
18-
import { autoScansEnabledKey, autoTriggerEnabledKey } from './constants'
19-
import { get, set } from '../util/commonUtil'
2018
import { ChatControllerEventEmitters } from '../../amazonqGumby/chat/controller/controller'
2119
import { TransformationSteps } from '../client/codewhispereruserclient'
2220

@@ -76,7 +74,6 @@ export interface GetRecommendationsResponse {
7674

7775
/** Manages the state of CodeWhisperer code suggestions */
7876
export class CodeSuggestionsState {
79-
#context: vscode.Memento
8077
/** The initial state if suggestion state was not defined */
8178
#fallback: boolean
8279
#onDidChangeState = new vscode.EventEmitter<boolean>()
@@ -88,15 +85,14 @@ export class CodeSuggestionsState {
8885
return (this.#instance ??= new this())
8986
}
9087

91-
protected constructor(context: vscode.Memento = globals.context.globalState, fallback: boolean = true) {
92-
this.#context = context
88+
protected constructor(fallback: boolean = true) {
9389
this.#fallback = fallback
9490
}
9591

9692
async toggleSuggestions() {
9793
const autoTriggerEnabled = this.isSuggestionsEnabled()
9894
const toSet: boolean = !autoTriggerEnabled
99-
await set(autoTriggerEnabledKey, toSet, this.#context)
95+
await globals.globalState.tryUpdate('CODEWHISPERER_AUTO_TRIGGER_ENABLED', toSet)
10096
this.#onDidChangeState.fire(toSet)
10197
return toSet
10298
}
@@ -108,13 +104,12 @@ export class CodeSuggestionsState {
108104
}
109105

110106
isSuggestionsEnabled(): boolean {
111-
const isEnabled = get(autoTriggerEnabledKey, this.#context)
107+
const isEnabled = globals.globalState.tryGet('CODEWHISPERER_AUTO_TRIGGER_ENABLED', Boolean)
112108
return isEnabled !== undefined ? isEnabled : this.#fallback
113109
}
114110
}
115111

116112
export class CodeScansState {
117-
#context: vscode.Memento
118113
/** The initial state if scan state was not defined */
119114
#fallback: boolean
120115
#onDidChangeState = new vscode.EventEmitter<boolean>()
@@ -129,15 +124,14 @@ export class CodeScansState {
129124
return (this.#instance ??= new this())
130125
}
131126

132-
protected constructor(context: vscode.Memento = globals.context.globalState, fallback: boolean = true) {
133-
this.#context = context
127+
protected constructor(fallback: boolean = true) {
134128
this.#fallback = fallback
135129
}
136130

137131
async toggleScans() {
138132
const autoScansEnabled = this.isScansEnabled()
139133
const toSet: boolean = !autoScansEnabled
140-
await set(autoScansEnabledKey, toSet, this.#context)
134+
await globals.globalState.tryUpdate('CODEWHISPERER_AUTO_SCANS_ENABLED', toSet)
141135
this.#onDidChangeState.fire(toSet)
142136
return toSet
143137
}
@@ -149,7 +143,7 @@ export class CodeScansState {
149143
}
150144

151145
isScansEnabled(): boolean {
152-
const isEnabled = get(autoScansEnabledKey, this.#context)
146+
const isEnabled = globals.globalState.tryGet('CODEWHISPERER_AUTO_SCANS_ENABLED', Boolean)
153147
return isEnabled !== undefined ? isEnabled : this.#fallback
154148
}
155149

packages/core/src/codewhisperer/ui/codeWhispererNodes.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -29,21 +29,21 @@ import { submitFeedback } from '../../feedback/vue/submitFeedback'
2929
import { focusAmazonQPanel } from '../../codewhispererChat/commands/registerCommands'
3030
import { isWeb } from '../../shared/extensionGlobals'
3131

32-
export function createAutoSuggestions(pause: boolean): DataQuickPickItem<'autoSuggestions'> {
32+
export function createAutoSuggestions(running: boolean): DataQuickPickItem<'autoSuggestions'> {
3333
const labelResume = localize('AWS.codewhisperer.resumeCodeWhispererNode.label', 'Resume Auto-Suggestions')
3434
const iconResume = getIcon('vscode-debug-start')
3535
const labelPause = localize('AWS.codewhisperer.pauseCodeWhispererNode.label', 'Pause Auto-Suggestions')
3636
const iconPause = getIcon('vscode-debug-pause')
3737

3838
return {
3939
data: 'autoSuggestions',
40-
label: pause ? codicon`${iconPause} ${labelPause}` : codicon`${iconResume} ${labelResume}`,
41-
description: pause ? 'Currently RUNNING' : 'Currently PAUSED',
40+
label: running ? codicon`${iconPause} ${labelPause}` : codicon`${iconResume} ${labelResume}`,
41+
description: running ? 'Currently RUNNING' : 'Currently PAUSED',
4242
onClick: () => toggleCodeSuggestions.execute(placeholder, cwQuickPickSource),
4343
} as DataQuickPickItem<'autoSuggestions'>
4444
}
4545

46-
export function createAutoScans(pause: boolean): DataQuickPickItem<'autoScans'> {
46+
export function createAutoScans(running: boolean): DataQuickPickItem<'autoScans'> {
4747
const labelResume = localize('AWS.codewhisperer.resumeCodeWhispererNode.label', 'Resume Auto-Scans')
4848
const iconResume = getIcon('vscode-debug-alt')
4949
const labelPause = localize('AWS.codewhisperer.pauseCodeWhispererNode.label', 'Pause Auto-Scans')
@@ -52,8 +52,8 @@ export function createAutoScans(pause: boolean): DataQuickPickItem<'autoScans'>
5252

5353
return {
5454
data: 'autoScans',
55-
label: pause ? codicon`${iconPause} ${labelPause}` : codicon`${iconResume} ${labelResume}`,
56-
description: monthlyQuotaExceeded ? 'Monthly quota exceeded' : pause ? 'RUNNING' : 'PAUSED',
55+
label: running ? codicon`${iconPause} ${labelPause}` : codicon`${iconResume} ${labelResume}`,
56+
description: monthlyQuotaExceeded ? 'Monthly quota exceeded' : running ? 'RUNNING' : 'PAUSED',
5757
onClick: () => toggleCodeScans.execute(placeholder, cwQuickPickSource),
5858
} as DataQuickPickItem<'autoScans'>
5959
}

packages/core/src/codewhisperer/util/commonUtil.ts

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import * as vscode from 'vscode'
77
import * as semver from 'semver'
88
import { isCloud9 } from '../../shared/extensionUtilities'
99
import { getInlineSuggestEnabled } from '../../shared/utilities/editorUtilities'
10-
import { getLogger } from '../../shared/logger'
1110
import { AWSTemplateCaseInsensitiveKeyWords, AWSTemplateKeyWords } from '../models/constants'
1211

1312
export function getLocalDatetime() {
@@ -62,19 +61,6 @@ export function getPrefixSuffixOverlap(firstString: string, secondString: string
6261
return secondString.slice(0, i)
6362
}
6463

65-
export function get(key: string, context: vscode.Memento): any {
66-
return context.get(key)
67-
}
68-
69-
export async function set(key: string, value: any, context: vscode.Memento): Promise<void> {
70-
await context.update(key, value).then(
71-
() => {},
72-
(error) => {
73-
getLogger().verbose(`Failed to update global state: ${error}`)
74-
}
75-
)
76-
}
77-
7864
export function checkLeftContextKeywordsForJsonAndYaml(leftFileContent: string, language: string): boolean {
7965
if (
8066
(language === 'json' || language === 'yaml') &&

packages/core/src/codewhisperer/util/customizationUtil.ts

Lines changed: 25 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,9 @@
44
*/
55

66
import globals from '../../shared/extensionGlobals'
7-
import {
8-
customLearnMoreUri,
9-
newCustomizationsAvailableKey,
10-
newCustomizationMessage,
11-
persistedCustomizationsKey,
12-
selectedCustomizationKey,
13-
} from '../models/constants'
7+
import { customLearnMoreUri, newCustomizationMessage } from '../models/constants'
148
import { localize, openUrl } from '../../shared/utilities/vsCodeUtils'
159
import { AuthUtil } from './authUtil'
16-
import { set } from './commonUtil'
1710
import * as vscode from 'vscode'
1811
import { createCommonButtons } from '../../shared/ui/buttons'
1912
import { DataQuickPickItem, showQuickPick } from '../../shared/ui/pickerPrompter'
@@ -107,8 +100,11 @@ export const getSelectedCustomization = (): Customization => {
107100
return baseCustomization
108101
}
109102

110-
const selectedCustomizationArr =
111-
globals.context.globalState.get<{ [label: string]: Customization }>(selectedCustomizationKey) || {}
103+
const selectedCustomizationArr = globals.globalState.tryGet<{ [label: string]: Customization }>(
104+
'CODEWHISPERER_SELECTED_CUSTOMIZATION',
105+
Object,
106+
{}
107+
)
112108
const result = selectedCustomizationArr[AuthUtil.instance.conn.label] || baseCustomization
113109

114110
// A/B case
@@ -130,12 +126,15 @@ export const setSelectedCustomization = async (customization: Customization) =>
130126
if (!AuthUtil.instance.isValidEnterpriseSsoInUse() || !AuthUtil.instance.conn) {
131127
return
132128
}
133-
const selectedCustomizationObj =
134-
globals.context.globalState.get<{ [label: string]: Customization }>(selectedCustomizationKey) || {}
129+
const selectedCustomizationObj = globals.globalState.tryGet<{ [label: string]: Customization }>(
130+
'CODEWHISPERER_SELECTED_CUSTOMIZATION',
131+
Object,
132+
{}
133+
)
135134
selectedCustomizationObj[AuthUtil.instance.conn.label] = customization
136135
getLogger().debug(`Selected customization ${customization.name} for ${AuthUtil.instance.conn.label}`)
137136

138-
await set(selectedCustomizationKey, selectedCustomizationObj, globals.context.globalState)
137+
await globals.globalState.tryUpdate('CODEWHISPERER_SELECTED_CUSTOMIZATION', selectedCustomizationObj)
139138
vsCodeState.isFreeTierLimitReached = false
140139
await Commands.tryExecute('aws.amazonq.refreshStatusBar')
141140
}
@@ -144,27 +143,33 @@ export const getPersistedCustomizations = (): Customization[] => {
144143
if (!AuthUtil.instance.isValidEnterpriseSsoInUse() || !AuthUtil.instance.conn) {
145144
return []
146145
}
147-
const persistedCustomizationsObj =
148-
globals.context.globalState.get<{ [label: string]: Customization[] }>(persistedCustomizationsKey) || {}
146+
const persistedCustomizationsObj = globals.globalState.tryGet<{ [label: string]: Customization[] }>(
147+
'CODEWHISPERER_PERSISTED_CUSTOMIZATIONS',
148+
Object,
149+
{}
150+
)
149151
return persistedCustomizationsObj[AuthUtil.instance.conn.label] || []
150152
}
151153

152154
export const setPersistedCustomizations = async (customizations: Customization[]) => {
153155
if (!AuthUtil.instance.isValidEnterpriseSsoInUse() || !AuthUtil.instance.conn) {
154156
return
155157
}
156-
const persistedCustomizationsObj =
157-
globals.context.globalState.get<{ [label: string]: Customization[] }>(persistedCustomizationsKey) || {}
158+
const persistedCustomizationsObj = globals.globalState.tryGet<{ [label: string]: Customization[] }>(
159+
'CODEWHISPERER_PERSISTED_CUSTOMIZATIONS',
160+
Object,
161+
{}
162+
)
158163
persistedCustomizationsObj[AuthUtil.instance.conn.label] = customizations
159-
await set(persistedCustomizationsKey, persistedCustomizationsObj, globals.context.globalState)
164+
await globals.globalState.tryUpdate('CODEWHISPERER_PERSISTED_CUSTOMIZATIONS', persistedCustomizationsObj)
160165
}
161166

162167
export const getNewCustomizationsAvailable = () => {
163-
return globals.context.globalState.get<number>(newCustomizationsAvailableKey) ?? 0
168+
return globals.globalState.tryGet('aws.amazonq.codewhisperer.newCustomizations', Number, 0)
164169
}
165170

166171
export const setNewCustomizationsAvailable = async (num: number) => {
167-
await set(newCustomizationsAvailableKey, num, globals.context.globalState)
172+
await globals.globalState.tryUpdate('aws.amazonq.codewhisperer.newCustomizations', num)
168173
vsCodeState.isFreeTierLimitReached = false
169174
}
170175

0 commit comments

Comments
 (0)