Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 1 addition & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -236,19 +236,7 @@ Custom dimensions and metrics must be registered in the target GA4 property befo

The script `scripts/create_ga4_dimensions.sh` idempotently registers all custom dimensions and custom metrics in GA4 Property `549078235` (or any configured property ID) via the Google Analytics Admin API (`v1beta`).

#### Option A: Authenticate via `gcloud`

```bash
# Log in with the required Google Analytics Edit scope:
gcloud auth application-default login --scopes=https://www.googleapis.com/auth/analytics.edit,https://www.googleapis.com/auth/cloud-platform

# Run the provisioning script:
./scripts/create_ga4_dimensions.sh
```

#### Option B: Authenticate via Google OAuth 2.0 Playground (No `gcloud` Required)

If `gcloud` is not installed or you prefer browser-based authentication:
To authenticate via Google OAuth 2.0 Playground:

1. Open [Google OAuth 2.0 Playground](https://developers.google.com/oauthplayground/).
2. In **Step 1 (Select & authorize APIs)**, input `https://www.googleapis.com/auth/analytics.edit` and click **Authorize APIs**.
Expand Down
35 changes: 10 additions & 25 deletions scripts/create_ga4_dimensions.sh
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,6 @@ echo "Target Property: properties/${PROPERTY_ID}"
# ------------------------------------------------------------------------------
TOKEN="${ACCESS_TOKEN:-}"

if [[ -z "${TOKEN}" ]]; then
if command -v gcloud >/dev/null 2>&1; then
echo "Querying gcloud for access token..."
TOKEN=$(gcloud auth print-access-token 2>/dev/null || true)
if [[ -z "${TOKEN}" ]]; then
TOKEN=$(gcloud auth application-default print-access-token 2>/dev/null || true)
fi
fi
fi

test_token() {
local tok="$1"
local code
Expand All @@ -58,20 +48,12 @@ else
echo ""
echo "No valid OAuth access token found with access to properties/${PROPERTY_ID}."
echo ""
if ! command -v gcloud >/dev/null 2>&1; then
echo "Note: 'gcloud' is not currently installed on this system."
echo "To install google-cloud-cli on gLinux/Debian:"
echo " sudo apt-get update && sudo apt-get install -y google-cloud-cli"
echo ""
fi
echo "To authenticate, run either:"
echo " gcloud auth application-default login --scopes=${REQUIRED_SCOPE}"
echo " or"
echo " gcloud auth login --scopes=${REQUIRED_SCOPE}"
echo ""
echo "Then re-run this script, or export ACCESS_TOKEN:"
echo " export ACCESS_TOKEN=\"\$(gcloud auth print-access-token)\""
echo " $0"
echo "To authenticate via Google OAuth 2.0 Playground:"
echo " 1. Open Google OAuth 2.0 Playground (https://developers.google.com/oauthplayground/)."
echo " 2. In Step 1 (Select & authorize APIs), input ${REQUIRED_SCOPE} and click Authorize APIs."
echo " 3. In Step 2 (Exchange authorization code for tokens), click Exchange authorization code for tokens and copy the Access token."
echo " 4. Run the provisioning script with the access token:"
echo " ACCESS_TOKEN=\"<your_access_token>\" $0"
echo ""
if [[ -t 0 ]]; then
read -r -p "Enter OAuth Access Token (or Ctrl+C to abort): " MANUAL_TOKEN
Expand Down Expand Up @@ -231,7 +213,10 @@ create_dimension "error_category" "Error Category" "Functional error category"
create_dimension "source_tag" "Error Source Tag" "Subsystem emitting error"
create_dimension "invalid_property" "Error Invalid Property" "Schema property failing validation"
create_dimension "error_type" "Error Type" "Functional error type classification"
create_dimension "reason" "Reason" "Categorized failure reason for dialog actions"
Comment thread
jgindin marked this conversation as resolved.
Resolved
create_dimension "open_file_status" "Open File Status" "Status of opening A2UI file"
create_dimension "open_file_reason" "Open File Failure Reason" "Categorized failure reason for failure to open an A2UI file"
create_dimension "create_cl_status" "Create CL Status" "Status of creating a CL"
create_dimension "create_cl_reason" "Create CL Failure Reason" "Categorized failure reason for failure to create a CL"
Comment thread
jgindin marked this conversation as resolved.
Resolved
#### END DIMENSIONS

echo ""
Expand Down
41 changes: 36 additions & 5 deletions scripts/update_ga4_dimensions.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -48,13 +48,40 @@ export const EXCLUDED_PARAMS = new Set([
]);

/**
* Curated descriptions for parameters emitted by downstream usage-tracking subclasses.
* Preserved during standalone syncs when no `--subclass` paths are provided.
* Curated metadata for parameters emitted by downstream usage-tracking subclasses.
*
* Preserved during standalone syncs when no `--subclass` paths are provided. Curated display names
* ensure subclass dimensions that are pruned and later re-discovered keep their intended names
* (e.g. acronym casing such as "CL") rather than the Title Case fallback.
*
* @type {Record<string, {displayName: string, description: string}>}
*/
export const SUBCLASS_DESCRIPTIONS = {
reason: 'Categorized failure reason for dialog actions',
export const SUBCLASS_PARAMS = {
open_file_status: {
displayName: 'Open File Status',
description: 'Status of opening A2UI file',
},
open_file_reason: {
displayName: 'Open File Failure Reason',
description: 'Categorized failure reason for failure to open an A2UI file',
},
create_cl_status: {
displayName: 'Create CL Status',
description: 'Status of creating a CL',
},
create_cl_reason: {
displayName: 'Create CL Failure Reason',
description: 'Categorized failure reason for failure to create a CL',
},
};

/**
* Curated descriptions for subclass parameters, derived from `SUBCLASS_PARAMS`.
*/
export const SUBCLASS_DESCRIPTIONS = Object.fromEntries(
Object.entries(SUBCLASS_PARAMS).map(([param, {description}]) => [param, description]),
);

/**
* Curated descriptions for known parameters discovered during source scans.
*/
Expand Down Expand Up @@ -290,12 +317,16 @@ export function classifyParameter(paramName) {
}

/**
* Converts snake_case parameter name to Title Case display name.
* Resolves a display name for a parameter, using curated definitions or converting the
* snake_case parameter name to a Title Case fallback.
*
* @param {string} paramName
* @returns {string}
*/
export function formatDisplayName(paramName) {
if (Object.hasOwn(SUBCLASS_PARAMS, paramName)) {
return SUBCLASS_PARAMS[paramName].displayName;
}
return paramName
.split('_')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
Expand Down
84 changes: 56 additions & 28 deletions scripts/update_ga4_dimensions.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import {
extractParametersFromSource,
classifyParameter,
formatDescription,
formatDisplayName,
mergeDefinitions,
generateScriptContent,
generateBashScript,
Expand All @@ -39,6 +40,7 @@ import {
METRICS_START,
METRICS_END,
SUBCLASS_DESCRIPTIONS,
SUBCLASS_PARAMS,
} from './update_ga4_dimensions.mjs';

const __filename = fileURLToPath(import.meta.url);
Expand Down Expand Up @@ -357,7 +359,6 @@ describe('update_ga4_dimensions', () => {
'retry_of_prompt_id',
'pipeline_status_at_cancel',
'status',
'reason',
'theme',
'component_key',
'category',
Expand All @@ -372,6 +373,10 @@ describe('update_ga4_dimensions', () => {
'error_type',
'source_tag',
'invalid_property',
'open_file_status',
'open_file_reason',
'create_cl_status',
'create_cl_reason',
];

for (const param of dimensionParams) {
Expand All @@ -387,10 +392,28 @@ describe('update_ga4_dimensions', () => {
}

assert.equal(
formatDescription('reason', 'Reason'),
'Categorized failure reason for dialog actions',
formatDescription('open_file_reason', 'Open File Failure Reason'),
'Categorized failure reason for failure to open an A2UI file',
);
});

it('uses curated display names for known parameters and Title Case for others', () => {
assert.equal(formatDisplayName('open_file_reason'), 'Open File Failure Reason');
assert.equal(formatDisplayName('create_cl_status'), 'Create CL Status');
assert.equal(formatDisplayName('create_cl_reason'), 'Create CL Failure Reason');
assert.equal(formatDisplayName('some_new_param'), 'Some New Param');
});

it('keeps curated subclass display names and descriptions in sync with create_ga4_dimensions.sh', () => {
const existing = parseExistingScript(fs.readFileSync(SCRIPT_PATH, 'utf-8'));
for (const [paramName, {displayName, description}] of Object.entries(SUBCLASS_PARAMS)) {
const def = existing.dimensions.get(paramName);
assert.ok(def, `${paramName} should be defined in create_ga4_dimensions.sh`);
assert.equal(def.displayName, displayName);
assert.equal(def.description, description);
assert.equal(SUBCLASS_DESCRIPTIONS[paramName], description);
}
});
});

describe('d) Idempotent regeneration and --check / --dry-run support', () => {
Expand Down Expand Up @@ -569,15 +592,20 @@ ${METRICS_END}
it('generates bash script with correct scopes, pageSize, failure tracking, and error routing', () => {
const script = generateBashScript();

// Scopes hint
// OAuth 2.0 Playground instructions and scopes hint
assert.ok(
script.includes('https://developers.google.com/oauthplayground/'),
'Must reference Google OAuth 2.0 Playground',
);
assert.ok(
script.includes('gcloud auth login --scopes=${REQUIRED_SCOPE}'),
'Must recommend gcloud auth login with explicit REQUIRED_SCOPE',
script.includes('input ${REQUIRED_SCOPE} and click Authorize APIs'),
'Must instruct authorizing REQUIRED_SCOPE in OAuth 2.0 Playground',
);
assert.ok(
!script.includes('--enable-gdrive-access'),
'Must not contain outdated --enable-gdrive-access flag',
script.includes('ACCESS_TOKEN=\\"<your_access_token>\\" $0'),
'Must show ACCESS_TOKEN usage example',
);
assert.ok(!script.includes('gcloud'), 'Must not contain references to gcloud');

// Page size
assert.ok(
Expand Down Expand Up @@ -814,16 +842,16 @@ ${METRICS_END}
try {
const initialScriptContent = fs
.readFileSync(SCRIPT_PATH, 'utf-8')
.replace(/^create_dimension "reason".*\n/m, '');
.replace(/^create_dimension "open_file_reason".*\n/m, '');
fs.writeFileSync(tempScript, initialScriptContent, 'utf-8');
fs.writeFileSync(
tempSubclass1,
`
export class SubclassOne extends Ga4UsageTrackingService {
trackOpenFile(params: { status: string; reason?: string }): void {
this.dispatchGtagEvent('open_file', {
['status']: params.status,
...(params.status === 'failure' && params.reason ? {['reason']: params.reason} : {}),
['open_file_status']: params.status,
...(params.status === 'failure' && params.reason ? {['open_file_reason']: params.reason} : {}),
});
}
}
Expand Down Expand Up @@ -851,13 +879,13 @@ ${METRICS_END}
});

assert.equal(syncResult.hasChanges, true);
assert.deepEqual(syncResult.newDefinitions.addedDimensions, ['reason']);
assert.deepEqual(syncResult.newDefinitions.addedDimensions, ['open_file_reason']);
assert.deepEqual(syncResult.newDefinitions.addedMetrics, ['subclass_duration_seconds']);
const reasonDim = syncResult.newDefinitions.dimensions.find(d => d.paramName === 'reason');
const reasonDim = syncResult.newDefinitions.dimensions.find(d => d.paramName === 'open_file_reason');
assert.deepEqual(reasonDim, {
paramName: 'reason',
displayName: 'Reason',
description: 'Categorized failure reason for dialog actions',
paramName: 'open_file_reason',
displayName: 'Open File Failure Reason',
description: 'Categorized failure reason for failure to open an A2UI file',
});
const subclassMetric = syncResult.newDefinitions.metrics.find(
m => m.paramName === 'subclass_duration_seconds',
Expand All @@ -872,7 +900,7 @@ ${METRICS_END}
const updatedScriptContent = fs.readFileSync(tempScript, 'utf-8');
assert.ok(
updatedScriptContent.includes(
'create_dimension "reason" "Reason" "Categorized failure reason for dialog actions"',
'create_dimension "open_file_reason" "Open File Failure Reason" "Categorized failure reason for failure to open an A2UI file"',
),
);
assert.ok(
Expand All @@ -895,7 +923,7 @@ ${METRICS_END}
});

it('preserves existing SUBCLASS_DESCRIPTIONS parameters during standalone sync but prunes them when subclassPaths are provided without them', () => {
assert.equal(SUBCLASS_DESCRIPTIONS.reason, 'Categorized failure reason for dialog actions');
assert.equal(SUBCLASS_DESCRIPTIONS.open_file_reason, 'Categorized failure reason for failure to open an A2UI file');
const existing = {
dimensions: new Map([
[
Expand All @@ -907,11 +935,11 @@ ${METRICS_END}
},
],
[
'reason',
'open_file_reason',
{
paramName: 'reason',
displayName: 'Reason',
description: 'Categorized failure reason for dialog actions',
paramName: 'open_file_reason',
displayName: 'Open File Failure Reason',
description: 'Categorized failure reason for failure to open an A2UI file',
},
],
[
Expand All @@ -931,8 +959,8 @@ ${METRICS_END}
preserveSubclassParams: true,
});
assert.ok(
standaloneMerged.dimensions.some(d => d.paramName === 'reason'),
'reason should be preserved when preserveSubclassParams is true',
standaloneMerged.dimensions.some(d => d.paramName === 'open_file_reason'),
'open_file_reason should be preserved when preserveSubclassParams is true',
);
assert.ok(
!standaloneMerged.dimensions.some(d => d.paramName === 'stale_dim'),
Expand All @@ -943,8 +971,8 @@ ${METRICS_END}
preserveSubclassParams: false,
});
assert.ok(
!subclassMerged.dimensions.some(d => d.paramName === 'reason'),
'reason should be pruned when preserveSubclassParams is false and not in extractedParams',
!subclassMerged.dimensions.some(d => d.paramName === 'open_file_reason'),
'open_file_reason should be pruned when preserveSubclassParams is false and not in extractedParams',
);

const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ga4-dims-preserve-'));
Expand All @@ -967,7 +995,7 @@ ${METRICS_END}
});
assert.equal(standaloneSync.isUpToDate, true);
assert.equal(standaloneSync.hasChanges, false);
assert.ok(standaloneSync.newDefinitions.dimensions.some(d => d.paramName === 'reason'));
assert.ok(standaloneSync.newDefinitions.dimensions.some(d => d.paramName === 'open_file_reason'));

const subclassSync = syncDimensions({
scriptPath: tempScript,
Expand All @@ -977,7 +1005,7 @@ ${METRICS_END}
});
assert.equal(subclassSync.isUpToDate, false);
assert.equal(subclassSync.hasChanges, true);
assert.ok(!subclassSync.newDefinitions.dimensions.some(d => d.paramName === 'reason'));
assert.ok(!subclassSync.newDefinitions.dimensions.some(d => d.paramName === 'open_file_reason'));
} finally {
fs.rmSync(tempDir, {recursive: true, force: true});
}
Expand Down
10 changes: 10 additions & 0 deletions shell/src/app/gallery/gallery.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import {
ThemePreference,
} from '../settings/app-config-provider/app-config-provider';
import {ChatState} from '../chat/chat-state/chat-state';
import {StateSync} from '../chat/state-sync/state-sync';
import {UsageTrackingService} from '../usage-tracking/usage-tracking.service';
import {NoopUsageTrackingService} from '../usage-tracking/noop-usage-tracking.service';
import {ErrorLogger} from '../debug/error-logger.service';
Expand Down Expand Up @@ -88,6 +89,14 @@ class MockChatState {
readonly isProgrammaticStreamActive = signal<boolean>(false);
}

/**
* Gallery embeds RenderedFrame, which injects StateSync. Mocking it prevents the real StateSync's
* debounced history sync from calling into MockChatState after a test has finished.
*/
class MockStateSync {
readonly sessionResetNonce = signal(0);
}

describe('Gallery Component', () => {
let fixture: ComponentFixture<Gallery>;
let harness: GalleryHarness;
Expand All @@ -109,6 +118,7 @@ describe('Gallery Component', () => {
{provide: StartupResolution, useClass: MockStartupResolution},
{provide: AppConfigProvider, useValue: {themePreference: signal(ThemePreference.LIGHT)}},
{provide: ChatState, useClass: MockChatState},
{provide: StateSync, useClass: MockStateSync},
{provide: UsageTrackingService, useClass: NoopUsageTrackingService},
{provide: Clipboard, useValue: mockClipboard},
],
Expand Down
Loading
Loading