Skip to content

Commit 9cdb8c4

Browse files
committed
refactor(core): use globalState abstraction
1 parent aa58698 commit 9cdb8c4

File tree

13 files changed

+73
-81
lines changed

13 files changed

+73
-81
lines changed

packages/amazonq/test/unit/codewhisperer/commands/onAcceptance.test.ts

Lines changed: 27 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ describe('onAcceptance', function () {
3737
it('Should enqueue an event object to tracker', async function () {
3838
const mockEditor = createMockTextEditor()
3939
const trackerSpy = sinon.spy(CodeWhispererTracker.prototype, 'enqueue')
40-
const extensionContext = await FakeExtensionContext.create()
4140
const fakeReferences = [
4241
{
4342
message: '',
@@ -49,22 +48,19 @@ describe('onAcceptance', function () {
4948
},
5049
},
5150
]
52-
await onAcceptance(
53-
{
54-
editor: mockEditor,
55-
range: new vscode.Range(new vscode.Position(1, 0), new vscode.Position(1, 26)),
56-
effectiveRange: new vscode.Range(new vscode.Position(1, 0), new vscode.Position(1, 26)),
57-
acceptIndex: 0,
58-
recommendation: "print('Hello World!')",
59-
requestId: '',
60-
sessionId: '',
61-
triggerType: 'OnDemand',
62-
completionType: 'Line',
63-
language: 'python',
64-
references: fakeReferences,
65-
},
66-
extensionContext.globalState
67-
)
51+
await onAcceptance({
52+
editor: mockEditor,
53+
range: new vscode.Range(new vscode.Position(1, 0), new vscode.Position(1, 26)),
54+
effectiveRange: new vscode.Range(new vscode.Position(1, 0), new vscode.Position(1, 26)),
55+
acceptIndex: 0,
56+
recommendation: "print('Hello World!')",
57+
requestId: '',
58+
sessionId: '',
59+
triggerType: 'OnDemand',
60+
completionType: 'Line',
61+
language: 'python',
62+
references: fakeReferences,
63+
})
6864
const actualArg = trackerSpy.getCall(0).args[0] as AcceptedSuggestionEntry
6965
assert.ok(trackerSpy.calledOnce)
7066
assert.strictEqual(actualArg.originalString, 'def two_sum(nums, target):')
@@ -79,7 +75,7 @@ describe('onAcceptance', function () {
7975
})
8076

8177
it('Should report telemetry that records this user decision event', async function () {
82-
await globals.context.globalState.update('CODEWHISPERER_USER_GROUP', {
78+
await globals.globalState.update('CODEWHISPERER_USER_GROUP', {
8379
group: UserGroup.Control,
8480
version: extensionVersion,
8581
})
@@ -97,23 +93,19 @@ describe('onAcceptance', function () {
9793
session.triggerType = 'OnDemand'
9894
session.setCompletionType(0, session.recommendations[0])
9995
const assertTelemetry = assertTelemetryCurried('codewhisperer_userDecision')
100-
const extensionContext = await FakeExtensionContext.create()
101-
await onAcceptance(
102-
{
103-
editor: mockEditor,
104-
range: new vscode.Range(new vscode.Position(1, 0), new vscode.Position(1, 21)),
105-
effectiveRange: new vscode.Range(new vscode.Position(1, 0), new vscode.Position(1, 26)),
106-
acceptIndex: 0,
107-
recommendation: "print('Hello World!')",
108-
requestId: '',
109-
sessionId: '',
110-
triggerType: 'OnDemand',
111-
completionType: 'Line',
112-
language: 'python',
113-
references: undefined,
114-
},
115-
extensionContext.globalState
116-
)
96+
await onAcceptance({
97+
editor: mockEditor,
98+
range: new vscode.Range(new vscode.Position(1, 0), new vscode.Position(1, 21)),
99+
effectiveRange: new vscode.Range(new vscode.Position(1, 0), new vscode.Position(1, 26)),
100+
acceptIndex: 0,
101+
recommendation: "print('Hello World!')",
102+
requestId: '',
103+
sessionId: '',
104+
triggerType: 'OnDemand',
105+
completionType: 'Line',
106+
language: 'python',
107+
references: undefined,
108+
})
117109
assertTelemetry({
118110
codewhispererRequestId: 'test',
119111
codewhispererSessionId: 'test',

packages/amazonq/test/unit/codewhisperer/commands/onInlineAcceptance.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ describe('onInlineAcceptance', function () {
5757
})
5858

5959
it('Should report telemetry that records this user decision event', async function () {
60-
await globals.context.globalState.update('CODEWHISPERER_USER_GROUP', {
60+
await globals.globalState.update('CODEWHISPERER_USER_GROUP', {
6161
group: UserGroup.Classifier,
6262
version: extensionVersion,
6363
})

packages/amazonq/test/unit/codewhisperer/service/codewhisperer.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,7 +115,7 @@ describe('codewhisperer', async function () {
115115
ideCategory: 'VSCODE',
116116
operatingSystem: getOperatingSystem(),
117117
product: 'CodeWhisperer',
118-
clientId: getClientId(globals.context.globalState),
118+
clientId: getClientId(globals.globalState),
119119
}
120120

121121
await codeWhispererClient.sendTelemetryEvent({ telemetryEvent: userTriggerDecisionPayload })

packages/amazonq/test/unit/codewhisperer/service/recommendationHandler.test.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ describe('recommendationHandler', function () {
114114
})
115115

116116
it('should call telemetry function that records a CodeWhisperer service invocation', async function () {
117-
await globals.context.globalState.update('CODEWHISPERER_USER_GROUP', {
117+
await globals.globalState.update('CODEWHISPERER_USER_GROUP', {
118118
group: UserGroup.CrossFile,
119119
version: extensionVersion,
120120
})
@@ -166,7 +166,7 @@ describe('recommendationHandler', function () {
166166
})
167167

168168
it('should call telemetry function that records a Empty userDecision event', async function () {
169-
await globals.context.globalState.update('CODEWHISPERER_USER_GROUP', {
169+
await globals.globalState.update('CODEWHISPERER_USER_GROUP', {
170170
group: UserGroup.CrossFile,
171171
version: extensionVersion,
172172
})

packages/amazonq/test/unit/codewhisperer/tracker/codewhispererTracker.test.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -95,7 +95,7 @@ describe('codewhispererTracker', function () {
9595
})
9696

9797
it('Should call recordCodewhispererUserModification with suggestion event', async function () {
98-
await globals.context.globalState.update('CODEWHISPERER_USER_GROUP', {
98+
await globals.globalState.update('CODEWHISPERER_USER_GROUP', {
9999
group: UserGroup.CrossFile,
100100
version: extensionVersion,
101101
})

packages/core/src/amazonq/onboardingPage/walkthrough.ts

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,8 @@ import vscode from 'vscode'
1515
* Show the Amazon Q walkthrough one time forever when the user adds an Amazon Q connection.
1616
* All subsequent calls to this do nothing.
1717
*/
18-
export async function showAmazonQWalkthroughOnce(
19-
state = globals.context.globalState,
20-
showWalkthrough = () => openAmazonQWalkthrough.execute()
21-
) {
22-
const hasShownWalkthroughId = 'aws.amazonq.hasShownWalkthrough'
23-
const hasShownWalkthrough = state.get(hasShownWalkthroughId, false)
18+
export async function showAmazonQWalkthroughOnce(showWalkthrough = () => openAmazonQWalkthrough.execute()) {
19+
const hasShownWalkthrough = globals.globalState.tryGet('aws.amazonq.hasShownWalkthrough', Boolean, false)
2420
if (hasShownWalkthrough) {
2521
return
2622
}
@@ -30,7 +26,7 @@ export async function showAmazonQWalkthroughOnce(
3026
return
3127
}
3228

33-
await state.update(hasShownWalkthroughId, true)
29+
await globals.globalState.update('aws.amazonq.hasShownWalkthrough', true)
3430
await showWalkthrough()
3531
}
3632

packages/core/src/amazonqFeatureDev/client/featureDev.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -337,7 +337,7 @@ export class FeatureDevClient {
337337
ideCategory: 'VSCODE',
338338
operatingSystem: getOperatingSystem(),
339339
product: 'FeatureDev', // Should be the same as in JetBrains
340-
clientId: getClientId(globals.context.globalState),
340+
clientId: getClientId(globals.globalState),
341341
ideVersion: extensionVersion,
342342
},
343343
}

packages/core/src/auth/secondaryAuth.ts

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,12 @@ import { cast, Optional } from '../shared/utilities/typeConstructors'
1111
import { Auth } from './auth'
1212
import { once, onceChanged } from '../shared/utilities/functionUtils'
1313
import { isNonNullable } from '../shared/utilities/tsUtils'
14+
import { ToolIdStateKey } from '../shared/globalState'
1415
import { Connection, SsoConnection, StatefulConnection } from './connection'
1516
import { indent } from '../shared/utilities/textUtilities'
1617

18+
export type ToolId = 'codecatalyst' | 'codewhisperer' | 'testId'
19+
1720
let currentConn: Auth['activeConnection']
1821
const auths = new Map<string, SecondaryAuth>()
1922
const multiConnectionListeners = new WeakMap<Auth, vscode.Disposable>()
@@ -36,7 +39,7 @@ const registerAuthListener = (auth: Auth) => {
3639

3740
export function getSecondaryAuth<T extends Connection>(
3841
auth: Auth,
39-
toolId: string,
42+
toolId: ToolId,
4043
toolLabel: string,
4144
isValid: (conn: Connection) => conn is T
4245
): SecondaryAuth<T> {
@@ -87,16 +90,16 @@ export class SecondaryAuth<T extends Connection = Connection> {
8790
#savedConnection: T | undefined
8891
protected static readonly logIfChanged = onceChanged((s: string) => getLogger().info(s))
8992

90-
private readonly key = `${this.toolId}.savedConnectionId`
93+
private readonly key: ToolIdStateKey = `${this.toolId}.savedConnectionId`
9194
readonly #onDidChangeActiveConnection = new vscode.EventEmitter<T | undefined>()
9295
public readonly onDidChangeActiveConnection = this.#onDidChangeActiveConnection.event
9396

9497
public constructor(
95-
public readonly toolId: string,
98+
public readonly toolId: ToolId,
9699
public readonly toolLabel: string,
97100
public readonly isUsable: (conn: Connection) => conn is T,
98101
private readonly auth: Auth,
99-
private readonly memento = globals.context.globalState
102+
private readonly memento = globals.globalState
100103
) {
101104
const handleConnectionChanged = async (newActiveConn?: Connection) => {
102105
if (newActiveConn === undefined && this.#activeConnection?.id) {

packages/core/src/auth/utils.ts

Lines changed: 8 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -629,15 +629,12 @@ export class ExtensionUse {
629629
/**
630630
* Check if this is the first use/session of the extension.
631631
*/
632-
isFirstUse(
633-
state: vscode.Memento = globals.context.globalState,
634-
hasExistingConnections = () => Auth.instance.hasConnections
635-
): boolean {
632+
isFirstUse(hasExistingConnections = () => Auth.instance.hasConnections): boolean {
636633
if (this.isFirstUseCurrentSession !== undefined) {
637634
return this.isFirstUseCurrentSession
638635
}
639636

640-
this.isFirstUseCurrentSession = state.get(this.isExtensionFirstUseKey)
637+
this.isFirstUseCurrentSession = globals.globalState.get('isExtensionFirstUse')
641638
if (this.isFirstUseCurrentSession === undefined) {
642639
// The variable in the store is not defined yet, fallback to checking if they have existing connections.
643640
this.isFirstUseCurrentSession = !hasExistingConnections()
@@ -650,7 +647,7 @@ export class ExtensionUse {
650647
}
651648

652649
// Update state, so next time it is not first use
653-
this.updateMemento(state, this.isExtensionFirstUseKey, false)
650+
this.updateMemento('isExtensionFirstUse', false)
654651

655652
return this.isFirstUseCurrentSession
656653
}
@@ -663,22 +660,20 @@ export class ExtensionUse {
663660
* Caveat: This may return true even if an update hadn't occurred IF
664661
* this function hasn't been called.
665662
*/
666-
wasUpdated(state: vscode.Memento = globals.context.globalState) {
663+
wasUpdated() {
667664
if (this.wasExtensionUpdated !== undefined) {
668665
return this.wasExtensionUpdated
669666
}
670667
const currentVersion = extensionVersion
671668

672-
this.wasExtensionUpdated = currentVersion !== state.get(this.lastExtensionVersionKey)
673-
this.updateMemento(state, this.lastExtensionVersionKey, currentVersion)
669+
this.wasExtensionUpdated = currentVersion !== globals.globalState.get('lastExtensionVersion')
670+
this.updateMemento(this.lastExtensionVersionKey, currentVersion)
674671

675672
return this.wasExtensionUpdated
676673
}
677674

678-
private updateMemento(memento: vscode.Memento, key: string, val: any) {
679-
memento.update(key, val).then(undefined, (e) => {
680-
getLogger().error('Memento.update failed: %s', (e as Error).message)
681-
})
675+
private updateMemento(key: 'isExtensionFirstUse' | 'lastExtensionVersion', val: any) {
676+
globals.globalState.tryUpdate(key, val)
682677
}
683678

684679
static #instance: ExtensionUse

packages/core/src/codewhisperer/commands/onAcceptance.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import path from 'path'
1919
/**
2020
* This function is called when user accepts a intelliSense suggestion or an inline suggestion
2121
*/
22-
export async function onAcceptance(acceptanceEntry: OnRecommendationAcceptanceEntry, globalStorage: vscode.Memento) {
22+
export async function onAcceptance(acceptanceEntry: OnRecommendationAcceptanceEntry) {
2323
RecommendationHandler.instance.cancelPaginatedRequest()
2424
/**
2525
* Format document

0 commit comments

Comments
 (0)