fix: clearcut logging (retry #3744) (#3751)

This commit is contained in:
Gaurav 2025-07-11 10:57:35 -07:00 committed by GitHub
parent 93284281de
commit 8f12e8a114
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
9 changed files with 444 additions and 184 deletions

View File

@ -5,7 +5,8 @@
*/
import { describe, it, expect, vi, beforeEach, afterEach, Mock } from 'vitest';
import { getOauthClient, getCachedGoogleAccountId } from './oauth2.js';
import { getOauthClient } from './oauth2.js';
import { getCachedGoogleAccount } from '../utils/user_account.js';
import { OAuth2Client, Compute } from 'google-auth-library';
import * as fs from 'fs';
import * as path from 'path';
@ -66,30 +67,11 @@ describe('oauth2', () => {
const mockGetAccessToken = vi
.fn()
.mockResolvedValue({ token: 'mock-access-token' });
const mockRefreshAccessToken = vi.fn().mockImplementation((callback) => {
// Mock the callback-style refreshAccessToken method
const mockTokensWithIdToken = {
access_token: 'test-access-token',
refresh_token: 'test-refresh-token',
id_token:
'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0LWdvb2dsZS1hY2NvdW50LWlkLTEyMyJ9.signature', // Mock JWT with sub: test-google-account-id-123
};
callback(null, mockTokensWithIdToken);
});
const mockVerifyIdToken = vi.fn().mockResolvedValue({
getPayload: () => ({
sub: 'test-google-account-id-123',
aud: 'test-audience',
iss: 'https://accounts.google.com',
}),
});
const mockOAuth2Client = {
generateAuthUrl: mockGenerateAuthUrl,
getToken: mockGetToken,
setCredentials: mockSetCredentials,
getAccessToken: mockGetAccessToken,
refreshAccessToken: mockRefreshAccessToken,
verifyIdToken: mockVerifyIdToken,
credentials: mockTokens,
on: vi.fn(),
} as unknown as OAuth2Client;
@ -103,7 +85,9 @@ describe('oauth2', () => {
// Mock the UserInfo API response
(global.fetch as Mock).mockResolvedValue({
ok: true,
json: vi.fn().mockResolvedValue({ id: 'test-google-account-id-123' }),
json: vi
.fn()
.mockResolvedValue({ email: 'test-google-account@gmail.com' }),
} as unknown as Response);
let requestCallback!: http.RequestListener<
@ -169,18 +153,21 @@ describe('oauth2', () => {
});
expect(mockSetCredentials).toHaveBeenCalledWith(mockTokens);
// Verify Google Account ID was cached
const googleAccountIdPath = path.join(
// Verify Google Account was cached
const googleAccountPath = path.join(
tempHomeDir,
'.gemini',
'google_account_id',
'google_accounts.json',
);
expect(fs.existsSync(googleAccountIdPath)).toBe(true);
const cachedGoogleAccountId = fs.readFileSync(googleAccountIdPath, 'utf-8');
expect(cachedGoogleAccountId).toBe('test-google-account-id-123');
expect(fs.existsSync(googleAccountPath)).toBe(true);
const cachedGoogleAccount = fs.readFileSync(googleAccountPath, 'utf-8');
expect(JSON.parse(cachedGoogleAccount)).toEqual({
active: 'test-google-account@gmail.com',
old: [],
});
// Verify the getCachedGoogleAccountId function works
expect(getCachedGoogleAccountId()).toBe('test-google-account-id-123');
// Verify the getCachedGoogleAccount function works
expect(getCachedGoogleAccount()).toBe('test-google-account@gmail.com');
});
describe('in Cloud Shell', () => {

View File

@ -16,10 +16,15 @@ import crypto from 'crypto';
import * as net from 'net';
import open from 'open';
import path from 'node:path';
import { promises as fs, existsSync, readFileSync } from 'node:fs';
import { promises as fs } from 'node:fs';
import * as os from 'os';
import { Config } from '../config/config.js';
import { getErrorMessage } from '../utils/errors.js';
import {
cacheGoogleAccount,
getCachedGoogleAccount,
clearCachedGoogleAccount,
} from '../utils/user_account.js';
import { AuthType } from '../core/contentGenerator.js';
import readline from 'node:readline';
@ -50,7 +55,6 @@ const SIGN_IN_FAILURE_URL =
const GEMINI_DIR = '.gemini';
const CREDENTIAL_FILENAME = 'oauth_creds.json';
const GOOGLE_ACCOUNT_ID_FILENAME = 'google_account_id';
/**
* An Authentication URL for updating the credentials of a Oauth2Client
@ -78,13 +82,10 @@ export async function getOauthClient(
// If there are cached creds on disk, they always take precedence
if (await loadCachedCredentials(client)) {
// Found valid cached credentials.
// Check if we need to retrieve Google Account ID
if (!getCachedGoogleAccountId()) {
// Check if we need to retrieve Google Account ID or Email
if (!getCachedGoogleAccount()) {
try {
const googleAccountId = await getRawGoogleAccountId(client);
if (googleAccountId) {
await cacheGoogleAccountId(googleAccountId);
}
await fetchAndCacheUserInfo(client);
} catch {
// Non-fatal, continue with existing auth.
}
@ -237,10 +238,7 @@ async function authWithWeb(client: OAuth2Client): Promise<OauthWebLogin> {
client.setCredentials(tokens);
// Retrieve and cache Google Account ID during authentication
try {
const googleAccountId = await getRawGoogleAccountId(client);
if (googleAccountId) {
await cacheGoogleAccountId(googleAccountId);
}
await fetchAndCacheUserInfo(client);
} catch (error) {
console.error(
'Failed to retrieve Google Account ID during authentication:',
@ -326,80 +324,46 @@ function getCachedCredentialPath(): string {
return path.join(os.homedir(), GEMINI_DIR, CREDENTIAL_FILENAME);
}
function getGoogleAccountIdCachePath(): string {
return path.join(os.homedir(), GEMINI_DIR, GOOGLE_ACCOUNT_ID_FILENAME);
}
async function cacheGoogleAccountId(googleAccountId: string): Promise<void> {
const filePath = getGoogleAccountIdCachePath();
await fs.mkdir(path.dirname(filePath), { recursive: true });
await fs.writeFile(filePath, googleAccountId, 'utf-8');
}
export function getCachedGoogleAccountId(): string | null {
try {
const filePath = getGoogleAccountIdCachePath();
if (existsSync(filePath)) {
return readFileSync(filePath, 'utf-8').trim() || null;
}
return null;
} catch (error) {
console.debug('Error reading cached Google Account ID:', error);
return null;
}
}
export async function clearCachedCredentialFile() {
try {
await fs.rm(getCachedCredentialPath(), { force: true });
// Clear the Google Account ID cache when credentials are cleared
await fs.rm(getGoogleAccountIdCachePath(), { force: true });
await clearCachedGoogleAccount();
} catch (_) {
/* empty */
}
}
/**
* Retrieves the authenticated user's Google Account ID from Google's UserInfo API.
* @param client - The authenticated OAuth2Client
* @returns The user's Google Account ID or null if not available
*/
export async function getRawGoogleAccountId(
client: OAuth2Client,
): Promise<string | null> {
async function fetchAndCacheUserInfo(client: OAuth2Client): Promise<void> {
try {
// 1. Get a new Access Token including the id_token
const refreshedTokens = await new Promise<Credentials | null>(
(resolve, reject) => {
client.refreshAccessToken((err, tokens) => {
if (err) {
return reject(err);
}
resolve(tokens ?? null);
});
const { token } = await client.getAccessToken();
if (!token) {
return;
}
const response = await fetch(
'https://www.googleapis.com/oauth2/v2/userinfo',
{
headers: {
Authorization: `Bearer ${token}`,
},
},
);
if (!refreshedTokens?.id_token) {
console.warn('No id_token obtained after refreshing tokens.');
return null;
if (!response.ok) {
console.error(
'Failed to fetch user info:',
response.status,
response.statusText,
);
return;
}
// 2. Verify the ID token to securely get the user's Google Account ID.
const ticket = await client.verifyIdToken({
idToken: refreshedTokens.id_token,
audience: OAUTH_CLIENT_ID,
});
const payload = ticket.getPayload();
if (!payload?.sub) {
console.warn('Could not extract sub claim from verified ID token.');
return null;
const userInfo = await response.json();
if (userInfo.email) {
await cacheGoogleAccount(userInfo.email);
}
return payload.sub;
} catch (error) {
console.error('Error retrieving or verifying Google Account ID:', error);
return null;
console.error('Error retrieving user info:', error);
}
}

View File

@ -18,7 +18,10 @@ import {
import { EventMetadataKey } from './event-metadata-key.js';
import { Config } from '../../config/config.js';
import { getInstallationId } from '../../utils/user_id.js';
import { getGoogleAccountId } from '../../utils/user_id.js';
import {
getCachedGoogleAccount,
getLifetimeGoogleAccounts,
} from '../../utils/user_account.js';
const start_session_event_name = 'start_session';
const new_prompt_event_name = 'new_prompt';
@ -65,14 +68,30 @@ export class ClearcutLogger {
]);
}
createLogEvent(name: string, data: object): object {
return {
createLogEvent(name: string, data: object[]): object {
const email = getCachedGoogleAccount();
const totalAccounts = getLifetimeGoogleAccounts();
data.push({
gemini_cli_key: EventMetadataKey.GEMINI_CLI_GOOGLE_ACCOUNTS_COUNT,
value: totalAccounts.toString(),
});
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const logEvent: any = {
console_type: 'GEMINI_CLI',
application: 102,
event_name: name,
client_install_id: getInstallationId(),
event_metadata: [data] as object[],
};
// Should log either email or install ID, not both. See go/cloudmill-1p-oss-instrumentation#define-sessionable-id
if (email) {
logEvent.client_email = email;
} else {
logEvent.client_install_id = getInstallationId();
}
return logEvent;
}
flushIfNeeded(): void {
@ -80,30 +99,24 @@ export class ClearcutLogger {
return;
}
// Fire and forget - don't await
this.flushToClearcut().catch((error) => {
console.debug('Error flushing to Clearcut:', error);
});
}
async flushToClearcut(): Promise<LogResponse> {
flushToClearcut(): Promise<LogResponse> {
if (this.config?.getDebugMode()) {
console.log('Flushing log events to Clearcut.');
}
const eventsToSend = [...this.events];
this.events.length = 0;
const googleAccountId = await getGoogleAccountId();
return new Promise<Buffer>((resolve, reject) => {
const request = [
{
log_source_name: 'CONCORD',
request_time_ms: Date.now(),
log_event: eventsToSend,
// Add UserInfo with the raw Gaia ID
user_info: googleAccountId
? {
UserID: googleAccountId,
}
: undefined,
},
];
const body = JSON.stringify(request);
@ -249,10 +262,10 @@ export class ClearcutLogger {
value: event.telemetry_log_user_prompts_enabled.toString(),
},
];
this.enqueueLogEvent(this.createLogEvent(start_session_event_name, data));
// Flush start event immediately
this.enqueueLogEvent(this.createLogEvent(start_session_event_name, data));
this.flushToClearcut().catch((error) => {
console.debug('Error flushing start session event to Clearcut:', error);
console.debug('Error flushing to Clearcut:', error);
});
}
@ -273,9 +286,7 @@ export class ClearcutLogger {
];
this.enqueueLogEvent(this.createLogEvent(new_prompt_event_name, data));
this.flushToClearcut().catch((error) => {
console.debug('Error flushing to Clearcut:', error);
});
this.flushIfNeeded();
}
logToolCallEvent(event: ToolCallEvent): void {
@ -310,10 +321,9 @@ export class ClearcutLogger {
},
];
this.enqueueLogEvent(this.createLogEvent(tool_call_event_name, data));
this.flushToClearcut().catch((error) => {
console.debug('Error flushing to Clearcut:', error);
});
const logEvent = this.createLogEvent(tool_call_event_name, data);
this.enqueueLogEvent(logEvent);
this.flushIfNeeded();
}
logApiRequestEvent(event: ApiRequestEvent): void {
@ -329,9 +339,7 @@ export class ClearcutLogger {
];
this.enqueueLogEvent(this.createLogEvent(api_request_event_name, data));
this.flushToClearcut().catch((error) => {
console.debug('Error flushing to Clearcut:', error);
});
this.flushIfNeeded();
}
logApiResponseEvent(event: ApiResponseEvent): void {
@ -388,9 +396,7 @@ export class ClearcutLogger {
];
this.enqueueLogEvent(this.createLogEvent(api_response_event_name, data));
this.flushToClearcut().catch((error) => {
console.debug('Error flushing to Clearcut:', error);
});
this.flushIfNeeded();
}
logApiErrorEvent(event: ApiErrorEvent): void {
@ -422,9 +428,7 @@ export class ClearcutLogger {
];
this.enqueueLogEvent(this.createLogEvent(api_error_event_name, data));
this.flushToClearcut().catch((error) => {
console.debug('Error flushing to Clearcut:', error);
});
this.flushIfNeeded();
}
logEndSessionEvent(event: EndSessionEvent): void {
@ -435,8 +439,8 @@ export class ClearcutLogger {
},
];
this.enqueueLogEvent(this.createLogEvent(end_session_event_name, data));
// Flush immediately on session end.
this.enqueueLogEvent(this.createLogEvent(end_session_event_name, data));
this.flushToClearcut().catch((error) => {
console.debug('Error flushing to Clearcut:', error);
});

View File

@ -147,6 +147,9 @@ export enum EventMetadataKey {
// Logs the Auth type for the prompt, api responses and errors.
GEMINI_CLI_AUTH_TYPE = 36,
// Logs the total number of Google accounts ever used.
GEMINI_CLI_GOOGLE_ACCOUNTS_COUNT = 37,
}
export function getEventMetadataKey(

View File

@ -9,6 +9,7 @@ import os from 'os';
import * as crypto from 'crypto';
export const GEMINI_DIR = '.gemini';
export const GOOGLE_ACCOUNTS_FILENAME = 'google_accounts.json';
const TMP_DIR_NAME = 'tmp';
/**

View File

@ -0,0 +1,237 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import { vi, describe, it, expect, beforeEach, afterEach, Mock } from 'vitest';
import {
cacheGoogleAccount,
getCachedGoogleAccount,
clearCachedGoogleAccount,
getLifetimeGoogleAccounts,
} from './user_account.js';
import * as fs from 'node:fs';
import * as os from 'node:os';
import path from 'node:path';
vi.mock('os', async (importOriginal) => {
const os = await importOriginal<typeof import('os')>();
return {
...os,
homedir: vi.fn(),
};
});
describe('user_account', () => {
let tempHomeDir: string;
const accountsFile = () =>
path.join(tempHomeDir, '.gemini', 'google_accounts.json');
beforeEach(() => {
tempHomeDir = fs.mkdtempSync(
path.join(os.tmpdir(), 'gemini-cli-test-home-'),
);
(os.homedir as Mock).mockReturnValue(tempHomeDir);
});
afterEach(() => {
fs.rmSync(tempHomeDir, { recursive: true, force: true });
vi.clearAllMocks();
});
describe('cacheGoogleAccount', () => {
it('should create directory and write initial account file', async () => {
await cacheGoogleAccount('test1@google.com');
// Verify Google Account ID was cached
expect(fs.existsSync(accountsFile())).toBe(true);
expect(fs.readFileSync(accountsFile(), 'utf-8')).toBe(
JSON.stringify({ active: 'test1@google.com', old: [] }, null, 2),
);
});
it('should update active account and move previous to old', async () => {
fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
fs.writeFileSync(
accountsFile(),
JSON.stringify(
{ active: 'test2@google.com', old: ['test1@google.com'] },
null,
2,
),
);
await cacheGoogleAccount('test3@google.com');
expect(fs.readFileSync(accountsFile(), 'utf-8')).toBe(
JSON.stringify(
{
active: 'test3@google.com',
old: ['test1@google.com', 'test2@google.com'],
},
null,
2,
),
);
});
it('should not add a duplicate to the old list', async () => {
fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
fs.writeFileSync(
accountsFile(),
JSON.stringify(
{ active: 'test1@google.com', old: ['test2@google.com'] },
null,
2,
),
);
await cacheGoogleAccount('test2@google.com');
await cacheGoogleAccount('test1@google.com');
expect(fs.readFileSync(accountsFile(), 'utf-8')).toBe(
JSON.stringify(
{ active: 'test1@google.com', old: ['test2@google.com'] },
null,
2,
),
);
});
it('should handle corrupted JSON by starting fresh', async () => {
fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
fs.writeFileSync(accountsFile(), 'not valid json');
const consoleDebugSpy = vi
.spyOn(console, 'debug')
.mockImplementation(() => {});
await cacheGoogleAccount('test1@google.com');
expect(consoleDebugSpy).toHaveBeenCalled();
expect(JSON.parse(fs.readFileSync(accountsFile(), 'utf-8'))).toEqual({
active: 'test1@google.com',
old: [],
});
});
});
describe('getCachedGoogleAccount', () => {
it('should return the active account if file exists and is valid', () => {
fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
fs.writeFileSync(
accountsFile(),
JSON.stringify({ active: 'active@google.com', old: [] }, null, 2),
);
const account = getCachedGoogleAccount();
expect(account).toBe('active@google.com');
});
it('should return null if file does not exist', () => {
const account = getCachedGoogleAccount();
expect(account).toBeNull();
});
it('should return null if file is empty', () => {
fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
fs.writeFileSync(accountsFile(), '');
const account = getCachedGoogleAccount();
expect(account).toBeNull();
});
it('should return null and log if file is corrupted', () => {
fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
fs.writeFileSync(accountsFile(), '{ "active": "test@google.com"'); // Invalid JSON
const consoleDebugSpy = vi
.spyOn(console, 'debug')
.mockImplementation(() => {});
const account = getCachedGoogleAccount();
expect(account).toBeNull();
expect(consoleDebugSpy).toHaveBeenCalled();
});
});
describe('clearCachedGoogleAccount', () => {
it('should set active to null and move it to old', async () => {
fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
fs.writeFileSync(
accountsFile(),
JSON.stringify(
{ active: 'active@google.com', old: ['old1@google.com'] },
null,
2,
),
);
await clearCachedGoogleAccount();
const stored = JSON.parse(fs.readFileSync(accountsFile(), 'utf-8'));
expect(stored.active).toBeNull();
expect(stored.old).toEqual(['old1@google.com', 'active@google.com']);
});
it('should handle empty file gracefully', async () => {
fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
fs.writeFileSync(accountsFile(), '');
await clearCachedGoogleAccount();
const stored = JSON.parse(fs.readFileSync(accountsFile(), 'utf-8'));
expect(stored.active).toBeNull();
expect(stored.old).toEqual([]);
});
});
describe('getLifetimeGoogleAccounts', () => {
it('should return 0 if the file does not exist', () => {
expect(getLifetimeGoogleAccounts()).toBe(0);
});
it('should return 0 if the file is empty', () => {
fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
fs.writeFileSync(accountsFile(), '');
expect(getLifetimeGoogleAccounts()).toBe(0);
});
it('should return 0 if the file is corrupted', () => {
fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
fs.writeFileSync(accountsFile(), 'invalid json');
const consoleDebugSpy = vi
.spyOn(console, 'debug')
.mockImplementation(() => {});
expect(getLifetimeGoogleAccounts()).toBe(0);
expect(consoleDebugSpy).toHaveBeenCalled();
});
it('should return 1 if there is only an active account', () => {
fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
fs.writeFileSync(
accountsFile(),
JSON.stringify({ active: 'test1@google.com', old: [] }),
);
expect(getLifetimeGoogleAccounts()).toBe(1);
});
it('should correctly count old accounts when active is null', () => {
fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
fs.writeFileSync(
accountsFile(),
JSON.stringify({
active: null,
old: ['test1@google.com', 'test2@google.com'],
}),
);
expect(getLifetimeGoogleAccounts()).toBe(2);
});
it('should correctly count both active and old accounts', () => {
fs.mkdirSync(path.dirname(accountsFile()), { recursive: true });
fs.writeFileSync(
accountsFile(),
JSON.stringify({
active: 'test3@google.com',
old: ['test1@google.com', 'test2@google.com'],
}),
);
expect(getLifetimeGoogleAccounts()).toBe(3);
});
});
});

View File

@ -0,0 +1,115 @@
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import path from 'node:path';
import { promises as fsp, existsSync, readFileSync } from 'node:fs';
import * as os from 'os';
import { GEMINI_DIR, GOOGLE_ACCOUNTS_FILENAME } from './paths.js';
interface UserAccounts {
active: string | null;
old: string[];
}
function getGoogleAccountsCachePath(): string {
return path.join(os.homedir(), GEMINI_DIR, GOOGLE_ACCOUNTS_FILENAME);
}
async function readAccounts(filePath: string): Promise<UserAccounts> {
try {
const content = await fsp.readFile(filePath, 'utf-8');
if (!content.trim()) {
return { active: null, old: [] };
}
return JSON.parse(content) as UserAccounts;
} catch (error) {
if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
// File doesn't exist, which is fine.
return { active: null, old: [] };
}
// File is corrupted or not valid JSON, start with a fresh object.
console.debug('Could not parse accounts file, starting fresh.', error);
return { active: null, old: [] };
}
}
export async function cacheGoogleAccount(email: string): Promise<void> {
const filePath = getGoogleAccountsCachePath();
await fsp.mkdir(path.dirname(filePath), { recursive: true });
const accounts = await readAccounts(filePath);
if (accounts.active && accounts.active !== email) {
if (!accounts.old.includes(accounts.active)) {
accounts.old.push(accounts.active);
}
}
// If the new email was in the old list, remove it
accounts.old = accounts.old.filter((oldEmail) => oldEmail !== email);
accounts.active = email;
await fsp.writeFile(filePath, JSON.stringify(accounts, null, 2), 'utf-8');
}
export function getCachedGoogleAccount(): string | null {
try {
const filePath = getGoogleAccountsCachePath();
if (existsSync(filePath)) {
const content = readFileSync(filePath, 'utf-8').trim();
if (!content) {
return null;
}
const accounts: UserAccounts = JSON.parse(content);
return accounts.active;
}
return null;
} catch (error) {
console.debug('Error reading cached Google Account:', error);
return null;
}
}
export function getLifetimeGoogleAccounts(): number {
try {
const filePath = getGoogleAccountsCachePath();
if (!existsSync(filePath)) {
return 0;
}
const content = readFileSync(filePath, 'utf-8').trim();
if (!content) {
return 0;
}
const accounts: UserAccounts = JSON.parse(content);
let count = accounts.old.length;
if (accounts.active) {
count++;
}
return count;
} catch (error) {
console.debug('Error reading lifetime Google Accounts:', error);
return 0;
}
}
export async function clearCachedGoogleAccount(): Promise<void> {
const filePath = getGoogleAccountsCachePath();
if (!existsSync(filePath)) {
return;
}
const accounts = await readAccounts(filePath);
if (accounts.active) {
if (!accounts.old.includes(accounts.active)) {
accounts.old.push(accounts.active);
}
accounts.active = null;
}
await fsp.writeFile(filePath, JSON.stringify(accounts, null, 2), 'utf-8');
}

View File

@ -5,7 +5,7 @@
*/
import { describe, it, expect } from 'vitest';
import { getInstallationId, getGoogleAccountId } from './user_id.js';
import { getInstallationId } from './user_id.js';
describe('user_id', () => {
describe('getInstallationId', () => {
@ -21,31 +21,4 @@ describe('user_id', () => {
expect(secondCall).toBe(installationId);
});
});
describe('getGoogleAccountId', () => {
it('should return a non-empty string', async () => {
const result = await getGoogleAccountId();
expect(result).toBeDefined();
expect(typeof result).toBe('string');
// Should be consistent on subsequent calls
const secondCall = await getGoogleAccountId();
expect(secondCall).toBe(result);
});
it('should return empty string when no Google Account ID is cached, or a valid ID when cached', async () => {
// The function can return either an empty string (if no cached ID) or a valid Google Account ID (if cached)
const googleAccountIdResult = await getGoogleAccountId();
expect(googleAccountIdResult).toBeDefined();
expect(typeof googleAccountIdResult).toBe('string');
// Should be either empty string or a numeric string (Google Account ID)
if (googleAccountIdResult !== '') {
// If we have a cached ID, it should be a numeric string
expect(googleAccountIdResult).toMatch(/^\d+$/);
}
});
});
});

View File

@ -56,27 +56,3 @@ export function getInstallationId(): string {
return '123456789';
}
}
/**
* Retrieves the obfuscated Google Account ID for the currently authenticated user.
* When OAuth is available, returns the user's cached Google Account ID. Otherwise, returns the installation ID.
* @returns A string ID for the user (Google Account ID if available, otherwise installation ID).
*/
export async function getGoogleAccountId(): Promise<string> {
// Try to get cached Google Account ID first
try {
// Dynamic import to avoid circular dependencies
const { getCachedGoogleAccountId } = await import(
'../code_assist/oauth2.js'
);
const googleAccountId = getCachedGoogleAccountId();
if (googleAccountId) {
return googleAccountId;
}
} catch (error) {
// If there's any error accessing Google Account ID, just return empty string
console.debug('Could not get cached Google Account ID:', error);
}
return '';
}