Skip to content

Commit 50e5af7

Browse files
Improve user_id detection for analytics
1 parent 1b1a0f4 commit 50e5af7

2 files changed

Lines changed: 13 additions & 10 deletions

File tree

packages/cli-kit/src/private/node/session.test.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -327,7 +327,8 @@ describe('when existing session is valid', () => {
327327
expect(exchangeAccessForApplicationTokens).not.toBeCalled()
328328
expect(refreshAccessToken).not.toBeCalled()
329329
expect(got).toEqual(expected)
330-
await expect(getLastSeenUserIdAfterAuth()).resolves.toBe('1234-5678')
330+
// Env automation token takes precedence for getLastSeenUserIdAfterAuth (analytics identity).
331+
await expect(getLastSeenUserIdAfterAuth()).resolves.toBe(nonRandomUUID('custom_cli_token'))
331332
await expect(getLastSeenAuthMethod()).resolves.toEqual('partners_token')
332333
expect(fetchSessions).toHaveBeenCalledOnce()
333334
})

packages/cli-kit/src/private/node/session.ts

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -120,25 +120,27 @@ let userId: undefined | string
120120
let authMethod: AuthMethod = 'none'
121121

122122
/**
123-
* Retrieves the user ID from the current session or returns 'unknown' if not found.
123+
* Retrieves a stable user identifier for analytics, or `'unknown'` if none applies.
124124
*
125-
* This function performs the following steps:
126-
* 1. Checks for a cached user ID in memory (obtained in the current run).
127-
* 2. Attempts to fetch it from the local storage (from a previous auth session).
128-
* 3. Checks if a custom token was used (either as a theme password or partners token).
129-
* 4. If a custom token is present in the environment, generates a UUID and uses it as userId.
130-
* 5. If after all this we don't have a userId, then reports as 'unknown'.
125+
* Evaluation order:
126+
* 1. If an app automation token or theme token is used, returns a deterministic UUID
127+
* derived from that secret.
128+
* 2. Otherwise, if `setLastSeenUserIdAfterAuth` was called (e.g. after OAuth), returns that value.
129+
* 3. Otherwise, if a persisted CLI session id is available, returns it.
130+
* 4. Otherwise returns `'unknown'`.
131131
*
132132
* @returns A Promise that resolves to the user ID as a string.
133133
*/
134134
export async function getLastSeenUserIdAfterAuth(): Promise<string> {
135+
const customToken = getAppAutomationToken() ?? themeToken()
136+
if (customToken) return nonRandomUUID(customToken)
137+
135138
if (userId) return userId
136139

137140
const currentSessionId = getCurrentSessionId()
138141
if (currentSessionId) return currentSessionId
139142

140-
const customToken = getAppAutomationToken() ?? themeToken()
141-
return customToken ? nonRandomUUID(customToken) : 'unknown'
143+
return 'unknown'
142144
}
143145

144146
export function setLastSeenUserIdAfterAuth(id: string) {

0 commit comments

Comments
 (0)