Skip to content

The cross-harness, self-improving memory layer for AI agents. Join our community: https://discord.com/invite/zdNChS2fBu

browser-extension: name the browser on every event; run e2e in Edge

Clauded26d20e36912
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index a613b43d..11ff2e50 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -54,6 +54,16 @@ jobs:
# server. A wedged browser is a plausible failure mode, so bound it rather
# than holding a runner for the six-hour GitHub default.
timeout-minutes: 20
+ # One build serves every Chromium fork; the matrix proves it loads and
+ # captures in each browser Playwright can drive on Linux. Brave, Opera,
+ # Vivaldi and Arc have no Playwright channel and are covered by the manual
+ # checklist in docs/runtimes/browser-extension-chromium.mdx instead.
+ strategy:
+ fail-fast: false
+ matrix:
+ browser: [chromium, msedge]
+ env:
+ BROWSER_CHANNEL: ${{ matrix.browser }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
@@ -109,7 +119,11 @@ jobs:
working-directory: browser-extension
run: echo "version=$(node -p "require('@playwright/test/package.json').version")" >> "$GITHUB_OUTPUT"
+ # Chromium leg only. The msedge leg installs nothing into this directory
+ # but Playwright's .links bookkeeping, and saving that under the shared
+ # key would give the chromium leg a cache hit with no browser in it.
- name: Cache Playwright browsers
+ if: matrix.browser == 'chromium'
id: pw-cache
uses: actions/cache@v4
with:
@@ -125,10 +139,20 @@ jobs:
# The full Chromium build, not the headless shell: e2e/fixtures.ts uses
# channel: 'chromium', which is what supports MV3 extensions in headless.
- name: Install Chromium for Playwright
- if: steps.pw-cache.outputs.cache-hit != 'true'
+ if: matrix.browser == 'chromium' && steps.pw-cache.outputs.cache-hit != 'true'
working-directory: browser-extension
run: npx playwright install chromium
+ # Edge stable installs from Microsoft's apt repository into
+ # /opt/microsoft/msedge, outside the Playwright cache, so it is installed
+ # on every run. Edge still honors --load-extension (checked on Edge 153),
+ # which is what lets the same harness load dist/. Branded Google Chrome
+ # stopped honoring it, which is why `chrome` is not a matrix leg.
+ - name: Install Microsoft Edge for Playwright
+ if: matrix.browser == 'msedge'
+ working-directory: browser-extension
+ run: npx playwright install msedge
+
# `npx playwright test`, not `npm test`: the pretest hook would rebuild
# dist/ and hide a build failure inside the e2e step. GitHub sets CI=true,
# which the config already reads for forbidOnly and retries: 1.
@@ -142,7 +166,7 @@ jobs:
if: failure()
uses: actions/upload-artifact@v4
with:
- name: browser-extension-playwright-report
+ name: browser-extension-playwright-report-${{ matrix.browser }}
path: |
browser-extension/playwright-report/
browser-extension/test-results/
diff --git a/.github/workflows/release-extension.yml b/.github/workflows/release-extension.yml
index ae32e048..1641ce0a 100644
--- a/.github/workflows/release-extension.yml
+++ b/.github/workflows/release-extension.yml
@@ -2,6 +2,13 @@ name: Release Browser Extension
# Publishes the unpacked Chrome MV3 build as a zip on a pushed `ext-v*` tag.
#
+# One zip serves every Chromium browser (Chrome, Edge, Brave, Opera, Vivaldi,
+# Arc). It keeps the `-chrome.zip` name on purpose: `chrome` is the name the
+# WebExtension tooling uses for the whole Chromium target family, it pairs with
+# any future per-engine targets, and renaming it would break every download
+# script and doc that already names the asset. The release notes state the
+# family claim instead (#394).
+#
# Independent of the CLI's `v*` release on purpose: the extension versions on its
# own cadence and shares no assets with the binary. GitHub tag patterns anchor at
# the start, so the `v*` filter in release.yml does not match `ext-v0.1.0` and the
@@ -173,9 +180,9 @@ jobs:
version="$VERSION"
printf '%s\n' \
- "Unpacked Chrome MV3 build of the Agent Beacon browser collector (\`browser-extension/\`)." \
+ "Unpacked Chromium MV3 build of the Agent Beacon browser collector (\`browser-extension/\`). The same archive loads in Chrome, Edge, Brave, Opera, Vivaldi and Arc; CI tests it in Chromium and Edge." \
"" \
- "**Install:** download and unzip, then Chrome -> Extensions -> Developer mode -> Load unpacked -> select the unzipped folder." \
+ "**Install:** download and unzip, then open the browser's extensions page (\`chrome://extensions\`, \`edge://extensions\`, \`brave://extensions\`, ...) -> Developer mode -> Load unpacked -> select the unzipped folder." \
"" \
"Requires a running Beacon endpoint: the extension POSTs OTLP GenAI logs to \`http://127.0.0.1:4318/v1/logs\`." \
"" \
diff --git a/CLAUDE.md b/CLAUDE.md
index 9b18b2b0..5efe0cd5 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -55,7 +55,7 @@ Supported runtime surfaces today:
- OpenClaw Gateway uses a Beacon-managed plugin directory plus OpenClaw's own diagnostics OTLP guidance (`beacon endpoint integrations openclaw`). The plugin's `before_tool_call` hook is fail-closed, so the handler dispatches synchronously and returns without awaiting. Conversation hooks, including `llm_output`, require `plugins.entries.beacon-endpoint.hooks.allowConversationAccess`; without it, token and agent-message coverage is partial. Beacon reads OpenClaw JSON/JSON5 config for advice but does not rewrite it.
- GitHub Copilot CLI uses MDM/customer-managed OTLP HTTP for live spans and approval-like activity, plus `beacon endpoint copilot sync` to backfill local session records from `~/.copilot/session-state`. Poll events carry assistant text, complete tool results, command/file details, and token usage with `harness.collection_method=poll`; approvals still come only from the live OTLP path and are not synthesized from persisted records.
- Runtimes that ride shared hook/OTLP paths without a special contract worth expanding here include Antigravity CLI, Devin CLI, Devin Desktop, Factory Droid, Gemini CLI, Grok Build, Hermes Agent, Qwen Code, and VS Code. Installed hook/endpoint support is governed by `cli/beacon/cmd/endpoint_targets.go` plus the install/status switches in `cli/beacon/cmd/endpoint_hooks.go`; discovery rows live in `cli/beacon/internal/endpoint/harness`.
-- Browser chat telemetry through an optional Chrome MV3 extension (`browser-extension/`) covering claude.ai and chatgpt.com. A main-world interceptor tees the streamed response, a per-site adapter parses it into a normalized turn, and the service worker POSTs OTLP GenAI logs to the local collector on `127.0.0.1:4318`; the extension never writes files and never contacts a remote endpoint. `harness.name` resolves to `claude_web` or `chatgpt_web` (already handled by `NormalizeHarnessName` in `pkg/asymptoteobserve/harness.go`, where the browser cases must stay above the generic `claude` rule) and `harness.collection_method` is `otlp`. Scope is deliberately narrow: only those origins' chat streams, never other tabs or general browsing. Retention defaults to `full`, so prompt and response text is retained by default; this is documented rather than defaulted down, because browser chat telemetry without content has no investigative value. Treat the adapters as experimental, since both sites' stream formats are private and undocumented.
+- Browser chat telemetry through an optional Chrome MV3 extension (`browser-extension/`) covering claude.ai and chatgpt.com. A main-world interceptor tees the streamed response, a per-site adapter parses it into a normalized turn, and the service worker POSTs OTLP GenAI logs to the local collector on `127.0.0.1:4318`; the extension never writes files and never contacts a remote endpoint. `harness.name` resolves to `claude_web` or `chatgpt_web` (already handled by `NormalizeHarnessName` in `pkg/asymptoteobserve/harness.go`, where the browser cases must stay above the generic `claude` rule) and `harness.collection_method` is `otlp`. The one build serves every Chromium browser; each event names the browser it came from in the typed `user_agent.name`/`user_agent.version` fields (OTel semconv, promoted by the exporter so Metadata-only forwarding keeps them), resolved in `browser-extension/src/shared/browser.ts` from UA Client Hints brands. Scope is deliberately narrow: only those origins' chat streams, never other tabs or general browsing. Retention defaults to `full`, so prompt and response text is retained by default; this is documented rather than defaulted down, because browser chat telemetry without content has no investigative value. Treat the adapters as experimental, since both sites' stream formats are private and undocumented.
- `beaconjson` OpenTelemetry Collector exporter that converts OTLP logs, traces, metrics, and resource attributes into Beacon endpoint JSONL.
- Endpoint inventory (`inventory.heartbeat` / `inventory.snapshot` in `inventory_state.jsonl`) is written by a scheduled job, `com.beacon.endpoint.inventory` (`service.InventoryManager`, user LaunchAgent or system LaunchDaemon, `beacon-inventory.timer` on systemd), every six hours and once at load, on by default and reconciled by `lifecycle.ReconcileInventoryJob` on every install, repair and package upgrade (`beacon endpoint inventory install-daemon`). Agent hooks do not trigger inventory any more; the hook binary's `--cli` flag and `inventory-heartbeat` subcommand survive only as no-ops for hook commands written by older versions, and `beacon endpoint inventory heartbeat --trigger hook` is likewise retired. A system-mode run inventories the active console user's home and still writes the liveness heartbeat when nobody is logged in; the scheduled scan has no working directory, so project-scoped config is only in `beacon endpoint inventory`.
- Beacon Managed forwarding, the one Beacon-hosted network channel for endpoint telemetry: user-mode `beacon endpoint connect` authorizes device enrollment with the signed-in CLI account; system mode uses browser PKCE at `/cli/enroll`. Both store only the per-device key in `<BaseDir>/asymptote/vector-secrets.json` (0600, 0700 dir), render the selected privacy mode into `vector.toml`, validate it, and run Vector as `com.beacon.endpoint.asymptote-forwarder` / `beacon-asymptote-forwarder.service` through `service.ForwarderManager` (refused in supervised mode). `enrollment.json` and `config.json`'s `managed_ingest` block carry only non-secret identity and privacy mode; `beacon endpoint status` reports forwarder state and a live credential check (`GET /v1/ingest/health`, 3 s timeout); `disconnect` and `uninstall` remove the forwarder and credentials but never revoke server-side.
@@ -451,7 +451,9 @@ Use these npm trusted publisher values:
The browser extension versions independently of the CLI. A pushed `ext-v*` tag
runs `.github/workflows/release-extension.yml`, which creates its own GitHub
-release carrying the unpacked Chrome build as a zip plus a `.sha256`.
+release carrying the unpacked Chromium-family build as a zip plus a `.sha256`.
+The zip keeps its `-chrome.zip` name: `chrome` names the Chromium extension
+target family, and the same archive loads in Edge, Brave, Opera, Vivaldi and Arc.
`ext-v*` and the CLI's `v*` trigger cannot collide: GitHub tag patterns anchor at
the start, so `v*` does not match `ext-v0.1.0`.
@@ -506,7 +508,7 @@ unpacked through Chrome's developer mode.
- `go-test` (macOS): `bun run check && bun test` in all seven `plugins/*` directories, then `make build-hooks-current`, then `go test ./...` in `cli/beacon`, `go test -race ./internal/endpoint/...`, `go test ./...` in `cli/beacon-hooks`, `collector-builder/exporter/beaconjsonexporter`, and `pkg/asymptoteobserve` (includes threat-rules pack conformance), then CLI help smoke checks that also assert removed commands stay unexposed.
- `linux-test` (ubuntu) and `windows-test` (windows-2025) rerun the Go suites per platform. The Windows job tests a measured package list rather than `./...`; the excluded packages are tracked in #318, and the scope must not be widened back to `./...`.
- `typescript-sdk` (Node 20, 22, 24): `npm test`, `npm run check`, `npm run build`, `npm run pack:dry-run`, `npm run pack:smoke` in `packages/asymptote-sdk-js`.
-- `browser-extension` (Node 22): `npm run check`, `npm run test:unit`, `npm run build`, a check that the build is a loadable MV3 extension, and the Playwright replay e2e running the real extension in headless Chromium against a local HTTPS replay server; the HTML report and traces upload on failure.
+- `browser-extension` (Node 22, matrix over `chromium` and `msedge`): `npm run check`, `npm run test:unit`, `npm run build`, a check that the build is a loadable MV3 extension, and the Playwright replay e2e running the real extension headless in that browser (`BROWSER_CHANNEL`) against a local HTTPS replay server; the HTML report and traces upload on failure. Brave, Opera, Vivaldi and Arc have no Playwright channel; `BROWSER_EXECUTABLE` runs the same e2e against their binaries for the manual checklist in `docs/runtimes/browser-extension-chromium.mdx`.
- `beacon-sandbox` (ubuntu): `go build`, `go vet`, and `go test` for the verification harness. Hermetic — no Modal account, no API key, no paid resources.
- `cross-build` (ubuntu): builds all five release targets and asserts the Linux binaries are statically linked (no `PT_INTERP`).
- `package-smoke` (macOS): `packaging/macos/test-endpoint-scripts.sh`, a `build-pkg.sh` payload check, and `packaging/macos/smoke-endpoint.sh`.
diff --git a/browser-extension/README.md b/browser-extension/README.md
index 2fa73ec5..71cc1897 100644
--- a/browser-extension/README.md
+++ b/browser-extension/README.md
@@ -82,6 +82,8 @@ npm run build:watch # rebuild on change
npm run check # tsc --noEmit
npm run test:unit # pure adapter + normalization tests (vitest, no browser)
npm test # builds dist/, runs the Playwright replay e2e (THE autonomous loop)
+BROWSER_CHANNEL=msedge npm test # same e2e in Microsoft Edge (chromium is the default)
+BROWSER_EXECUTABLE=/path/to/brave npm test # same e2e in any other Chromium-family binary
npm run test:headed # watch it drive a browser
npm run record:fixtures -- --site claude|chatgpt --name <n> # capture a fixture (headed, authed)
npm run report # open the last HTML report
@@ -89,6 +91,13 @@ npm run report # open the last HTML report
## Loading the extension in your own browser
+One build serves every Chromium browser: Chrome, Edge, Brave, Opera, Vivaldi and Arc. The
+release archive is named `-chrome.zip` after the Chromium extension family, not after Google
+Chrome alone. CI runs the replay e2e in Chromium and Edge; the other forks are covered by the
+manual checklist in [docs/runtimes/browser-extension-chromium.mdx](../docs/runtimes/browser-extension-chromium.mdx).
+Every emitted event names the browser that produced it (`user_agent.name`, `user_agent.version`,
+`browser.brands`; see `src/shared/browser.ts`).
+
**Beta, and not on the Chrome Web Store.** It installs unpacked, so Chrome will not
auto-update it: to move to a new version, rebuild or re-download and reload.
diff --git a/browser-extension/e2e/browser-identity.spec.ts b/browser-extension/e2e/browser-identity.spec.ts
new file mode 100644
index 00000000..de92c56e
--- /dev/null
+++ b/browser-extension/e2e/browser-identity.spec.ts
@@ -0,0 +1,58 @@
+import { test, expect, seedSettings, browserTarget } from './fixtures.js';
+import { resourceAttrs } from './helpers/otlp-assertions.js';
+
+// Every emitted turn must say which browser produced it. This runs the real
+// extension in whatever browser the fixture launched (BROWSER_CHANNEL /
+// BROWSER_EXECUTABLE) and checks the resource attributes against what that
+// browser's own service worker reports.
+
+const CONV = '99999999-8888-7777-6666-555555555555';
+
+test('stamps the browser identity on every delivered envelope', async ({
+ context,
+ serviceWorker,
+ replay,
+ mockCollector,
+}) => {
+ mockCollector.reset();
+ replay.setCase({
+ site: 'claude',
+ name: 'simple-turn',
+ conversationId: CONV,
+ prompt: 'Which browser am I?',
+ completionPath: '/api/organizations/org-test/chat_conversations/{conv}/completion',
+ });
+ await seedSettings(serviceWorker, {
+ enabled: true,
+ retention: 'metadata', // identity is metadata: it must survive the leanest mode
+ endpoint: mockCollector.url,
+ sites: { claude_web: true, chatgpt_web: true },
+ });
+
+ const page = await context.newPage();
+ await page.goto('https://claude.ai/chat');
+ await expect(page.locator('[data-testid="assistant-message"]')).toHaveAttribute('data-complete', '1');
+ await expect.poll(() => mockCollector.received.length, { timeout: 10_000 }).toBeGreaterThan(0);
+
+ // Ground truth from the same service worker that built the envelope.
+ const seen = await serviceWorker.evaluate(() => {
+ const uad = (navigator as Navigator & { userAgentData?: { brands: { brand: string; version: string }[] } })
+ .userAgentData;
+ return { brands: uad?.brands.map((b) => `${b.brand} ${b.version}`) ?? [], ua: navigator.userAgent };
+ });
+
+ for (const env of mockCollector.received) {
+ const res = resourceAttrs(env);
+ const name = res['user_agent.name'];
+ expect(typeof name, `user_agent.name missing in ${browserTarget.label}`).toBe('string');
+ expect(res['user_agent.original']).toBe(seen.ua);
+ if (seen.brands.length > 0) expect(res['browser.brands']).toEqual(seen.brands);
+ if (browserTarget.expectedUserAgentNames) {
+ expect(browserTarget.expectedUserAgentNames).toContain(name);
+ }
+ }
+ test.info().annotations.push({
+ type: 'browser',
+ description: `${browserTarget.label}: user_agent.name=${resourceAttrs(mockCollector.received[0])['user_agent.name']}`,
+ });
+});
diff --git a/browser-extension/e2e/browser-target.ts b/browser-extension/e2e/browser-target.ts
new file mode 100644
index 00000000..6c1df3a9
--- /dev/null
+++ b/browser-extension/e2e/browser-target.ts
@@ -0,0 +1,55 @@
+// Resolves which browser the replay e2e launches, from the environment.
+//
+// BROWSER_CHANNEL A Playwright channel: `chromium` (the default), `msedge`,
+// `chrome`, or a pre-release variant such as `msedge-beta`.
+// CI runs `chromium` and `msedge`.
+// BROWSER_EXECUTABLE An absolute path to any other Chromium-family browser
+// binary (Brave, Opera, Vivaldi, Arc). Those forks have no
+// Playwright channel, so this is how the manual checklist in
+// docs/runtimes/browser-extension-chromium.mdx runs the same
+// specs against them. It wins over BROWSER_CHANNEL.
+//
+// Kept apart from fixtures.ts so it can be reasoned about without a browser.
+
+export interface BrowserTarget {
+ /** Human label for logs and assertions: the channel name, or the executable. */
+ label: string;
+ /** Spread into chromium.launchPersistentContext(). */
+ launch: { channel?: string; executablePath?: string };
+ /**
+ * The `user_agent.name` values the extension may report in this browser, when
+ * knowable in advance. Undefined for an arbitrary executable, whose brand is
+ * whatever that binary claims.
+ */
+ expectedUserAgentNames?: readonly string[];
+}
+
+// Playwright's `chromium` channel is a Chrome for Testing build (older
+// Playwright releases shipped a raw Chromium build). Neither is Chrome-branded,
+// so both should report the plain engine brand; "Google Chrome for Testing" is
+// accepted in case a CfT build ever brands itself.
+const EXPECTED_NAMES: Record<string, readonly string[]> = {
+ chromium: ['Chromium', 'Google Chrome for Testing'],
+ chrome: ['Google Chrome'],
+ msedge: ['Microsoft Edge'],
+};
+
+export function resolveBrowserTarget(env: Record<string, string | undefined>): BrowserTarget {
+ const executablePath = env.BROWSER_EXECUTABLE?.trim();
+ if (executablePath) {
+ return { label: executablePath, launch: { executablePath } };
+ }
+ const channel = env.BROWSER_CHANNEL?.trim() || 'chromium';
+ if (!/^(chromium|chrome|msedge)(-(beta|dev|canary))?$/.test(channel)) {
+ throw new Error(
+ `BROWSER_CHANNEL=${channel} is not a Chromium-family Playwright channel. ` +
+ 'Use chromium, chrome, or msedge (optionally -beta, -dev, -canary), ' +
+ 'or set BROWSER_EXECUTABLE to a browser binary.',
+ );
+ }
+ return {
+ label: channel,
+ launch: { channel },
+ expectedUserAgentNames: EXPECTED_NAMES[channel.replace(/-(beta|dev|canary)$/, '')],
+ };
+}
diff --git a/browser-extension/e2e/fixtures.ts b/browser-extension/e2e/fixtures.ts
index d8ae82dd..80c04324 100644
--- a/browser-extension/e2e/fixtures.ts
+++ b/browser-extension/e2e/fixtures.ts
@@ -3,6 +3,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { startMockCollector, type MockCollector } from './helpers/mock-collector.js';
import { startReplayServer, type ReplayServer } from './helpers/sse-replay-server.js';
+import { resolveBrowserTarget } from './browser-target.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
@@ -10,6 +11,10 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
const pathToExtension = process.env.EXTENSION_PATH ?? path.join(__dirname, '..', 'dist');
const headless = process.env.HEADED !== '1';
+// Which browser the replay runs in. The specs are browser-agnostic; only the
+// launch changes. See e2e/browser-target.ts for the accepted values.
+export const browserTarget = resolveBrowserTarget(process.env);
+
interface Fixtures {
mockCollector: MockCollector;
replay: ReplayServer;
@@ -44,7 +49,7 @@ export const test = base.extend<Fixtures>({
].join(', ');
const context = await chromium.launchPersistentContext('', {
- channel: 'chromium',
+ ...browserTarget.launch,
headless,
ignoreHTTPSErrors: true,
args: [
diff --git a/browser-extension/e2e/helpers/otlp-assertions.ts b/browser-extension/e2e/helpers/otlp-assertions.ts
index eb6028b4..d16e3dbe 100644
--- a/browser-extension/e2e/helpers/otlp-assertions.ts
+++ b/browser-extension/e2e/helpers/otlp-assertions.ts
@@ -1,10 +1,10 @@
// Helpers to read OTLP log envelopes captured by the mock collector.
-import type { KeyValue, LogRecord, LogsEnvelope } from '../../src/shared/otlp.js';
+import type { AttrPrimitive, KeyValue, LogRecord, LogsEnvelope } from '../../src/shared/otlp.js';
import { attrValue } from '../../src/shared/otlp.js';
-export function flatAttrs(attrs: KeyValue[]): Record<string, string | number | boolean> {
- const out: Record<string, string | number | boolean> = {};
+export function flatAttrs(attrs: KeyValue[]): Record<string, AttrPrimitive | AttrPrimitive[]> {
+ const out: Record<string, AttrPrimitive | AttrPrimitive[]> = {};
for (const a of attrs) {
const v = attrValue(attrs, a.key);
if (v !== undefined) out[a.key] = v;
@@ -12,7 +12,7 @@ export function flatAttrs(attrs: KeyValue[]): Record<string, string | number | b
return out;
}
-export function resourceAttrs(env: LogsEnvelope): Record<string, string | number | boolean> {
+export function resourceAttrs(env: LogsEnvelope): Record<string, AttrPrimitive | AttrPrimitive[]> {
return flatAttrs(env.resourceLogs[0]?.resource.attributes ?? []);
}
diff --git a/browser-extension/src/background/delivery.ts b/browser-extension/src/background/delivery.ts
index 827d3cb7..ff31207b 100644
--- a/browser-extension/src/background/delivery.ts
+++ b/browser-extension/src/background/delivery.ts
@@ -6,6 +6,7 @@
import type { ChatTurn, Settings } from '../shared/types.js';
import { turnToEnvelope } from '../shared/normalize.js';
import type { LogsEnvelope } from '../shared/otlp.js';
+import type { BrowserIdentity } from '../shared/browser.js';
const QUEUE_KEY = 'delivery_queue';
const ALARM = 'beacon_flush';
@@ -42,8 +43,12 @@ function withQueueLock<T>(fn: () => Promise<T>): Promise<T> {
}
/** Normalize a turn and enqueue it for delivery, then kick a flush. */
-export async function enqueueTurn(turn: ChatTurn, settings: Settings): Promise<void> {
- const envelope = turnToEnvelope(turn, settings.retention);
+export async function enqueueTurn(
+ turn: ChatTurn,
+ settings: Settings,
+ browser?: BrowserIdentity,
+): Promise<void> {
+ const envelope = turnToEnvelope(turn, settings.retention, browser);
const item: QueueItem = {
id: turn.turnId,
endpoint: settings.endpoint,
diff --git a/browser-extension/src/background/sw.ts b/browser-extension/src/background/sw.ts
index 3945ba54..e005efad 100644
--- a/browser-extension/src/background/sw.ts
+++ b/browser-extension/src/background/sw.ts
@@ -7,9 +7,15 @@ import type { ChatTurn, RelayMessage, Settings } from '../shared/types.js';
import { getSettings, saveSettings, siteEnabled } from './settings.js';
import { Assembler } from './assembler.js';
import { enqueueTurn, flush, installFlushAlarm } from './delivery.js';
+import { detectBrowser } from '../shared/browser.js';
const assembler = new Assembler();
+// Which Chromium fork (or other browser) this is. Resolved once: the brand
+// list and UA string are fixed for the life of the worker. Stamped on every
+// emitted turn as user_agent.* / browser.brands.
+const browser = detectBrowser(globalThis.navigator);
+
// Keep the SW awake while any stream is active, so mid-stream suspension is
// rare. Correctness never depends on this — durable state covers the rest.
let keepAliveTimer: ReturnType<typeof setInterval> | undefined;
@@ -51,7 +57,7 @@ async function finalizeTurn(turn: ChatTurn): Promise<void> {
const settings = await getSettings();
// siteEnabled covers both the global toggle and the per-site toggle.
if (!siteEnabled(settings, turn.site)) return;
- await enqueueTurn(turn, settings);
+ await enqueueTurn(turn, settings, browser);
}
// ---- Control messages from popup/options ----
diff --git a/browser-extension/src/shared/browser.ts b/browser-extension/src/shared/browser.ts
new file mode 100644
index 00000000..29550c74
--- /dev/null
+++ b/browser-extension/src/shared/browser.ts
@@ -0,0 +1,118 @@
+// PURE: which browser is this extension running in?
+//
+// Every Chromium fork runs the same MV3 build, so a captured turn says nothing
+// about the browser it came from unless we record it. On a managed fleet that
+// matters: a paste into ChatGPT from the managed Edge profile and one from a
+// personal Brave install are different investigations.
+//
+// Resolution order, from most to least reliable:
+// 1. navigator.userAgentData.brands (UA Client Hints). Edge, Opera and Brave
+// add their own brand here, which the UA string no longer carries reliably.
+// 2. A Brave-only `navigator.brave` object, for Brave builds whose brand list
+// reads like plain Chrome.
+// 3. The UA string's vendor tokens (Edg/, OPR/, Vivaldi/, Firefox/), for
+// engines without UA Client Hints.
+//
+// What this cannot do: Arc and Vivaldi do not add a brand of their own, and
+// copy Chrome's UA string, so from a service worker they are indistinguishable
+// from Google Chrome or plain Chromium. We report what the browser claims and
+// document that limit rather than guessing.
+//
+// No I/O, no chrome.*: sw.ts hands in `navigator`, tests hand in fixtures.
+
+/** One entry of NavigatorUAData.brands. */
+export interface UABrand {
+ brand: string;
+ version: string;
+}
+
+/** The subset of (Worker)Navigator this reads. Every field is optional. */
+export interface NavigatorLike {
+ userAgent?: string;
+ userAgentData?: { brands?: readonly UABrand[] } | null;
+ brave?: unknown;
+}
+
+export interface BrowserIdentity {
+ /** Browser name as the browser itself claims it, e.g. "Microsoft Edge". OTel `user_agent.name`. */
+ name: string;
+ /** Major version of that browser, when known. OTel `user_agent.version`. */
+ version?: string;
+ /** UA Client Hints brands as "<brand> <version>", in reported order. OTel `browser.brands`. */
+ brands: string[];
+ /** The raw UA string, when available. OTel `user_agent.original`. */
+ original?: string;
+}
+
+const CHROME = 'Google Chrome';
+const CHROMIUM = 'Chromium';
+
+// Chromium adds a deliberately malformed "GREASE" brand ("Not_A Brand",
+// "Not)A;Brand", " Not A;Brand", ...) with randomized punctuation so sites
+// cannot match the brand list exactly. It never names a browser.
+const GREASE = /^\s*not.?a.?brand\s*$/i;
+
+/** Resolve the browser identity, or undefined when nothing identifies it. */
+export function detectBrowser(nav: NavigatorLike | undefined): BrowserIdentity | undefined {
+ if (!nav) return undefined;
+ const rawBrands = Array.isArray(nav.userAgentData?.brands) ? nav.userAgentData!.brands! : [];
+ const valid = rawBrands.filter(
+ (b): b is UABrand => typeof b?.brand === 'string' && b.brand.trim() !== '',
+ );
+ const brands = valid.map((b) => `${b.brand} ${b.version ?? ''}`.trim());
+ const original = typeof nav.userAgent === 'string' && nav.userAgent !== '' ? nav.userAgent : undefined;
+ const isBrave = nav.brave != null && typeof nav.brave === 'object';
+
+ let found = fromBrands(valid) ?? (original ? fromUserAgent(original) : undefined);
+ if (!found) return undefined;
+ // Brave's own object is a stronger signal than a brand list that reads like Chrome.
+ if (isBrave && (found.name === CHROME || found.name === CHROMIUM)) found = { name: 'Brave', version: found.version };
+
+ const identity: BrowserIdentity = { name: found.name, brands };
+ if (found.version) identity.version = found.version;
+ if (original) identity.original = original;
+ return identity;
+}
+
+interface Found {
+ name: string;
+ version?: string;
+}
+
+function fromBrands(brands: readonly UABrand[]): Found | undefined {
+ const named = brands.filter((b) => !GREASE.test(b.brand));
+ if (named.length === 0) return undefined;
+ // Any brand other than the engine and Chrome is the vendor naming itself
+ // (Microsoft Edge, Opera, Brave, ...). Chromium shuffles brand order, so when
+ // there is more than one, pick deterministically: the most specific (longest)
+ // name, so "Opera GX" beats "Opera", then alphabetical.
+ const vendor = named
+ .filter((b) => b.brand !== CHROME && b.brand !== CHROMIUM)
+ .sort((a, b) => b.brand.length - a.brand.length || a.brand.localeCompare(b.brand))[0];
+ const pick =
+ vendor ?? named.find((b) => b.brand === CHROME) ?? named.find((b) => b.brand === CHROMIUM);
+ if (!pick) return undefined;
+ return { name: pick.brand.trim(), version: pick.version || undefined };
+}
+
+// Vendor tokens first: every Chromium fork also carries "Chrome/", and Chrome
+// and Edge also carry "Safari/".
+const UA_RULES: Array<[RegExp, string]> = [
+ [/\bEdg(?:e|A|iOS)?\/(\d+)/, 'Microsoft Edge'],
+ [/\bOPR\/(\d+)/, 'Opera'],
+ [/\bVivaldi\/(\d+)/, 'Vivaldi'],
+ [/\bBrave\/(\d+)/, 'Brave'],
+ [/\bFirefox\/(\d+)/, 'Firefox'],
+ // The UA string alone cannot tell Chrome from the forks that copy it, so
+ // claim only the engine.
+ [/\b(?:Headless)?Chrome\/(\d+)/, CHROMIUM],
+ [/\bVersion\/(\d+)[^ ]* (?:Mobile\/\S+ )?Safari\//, 'Safari'],
+];
+
+function fromUserAgent(ua: string): Found | undefined {
+ for (const [re, name] of UA_RULES) {
+ const m = re.exec(ua);
+ if (m) return { name, version: m[1] };
+ }
+ return undefined;
+}
diff --git a/browser-extension/src/shared/normalize.ts b/browser-extension/src/shared/normalize.ts
index 225b7032..c6eee15b 100644
--- a/browser-extension/src/shared/normalize.ts
+++ b/browser-extension/src/shared/normalize.ts
@@ -14,7 +14,9 @@ import {
int,
msToUnixNano,
str,
+ strArray,
} from './otlp.js';
+import type { BrowserIdentity } from './browser.js';
import {
type EventAction,
MAX_FIELD_BYTES,
@@ -73,13 +75,22 @@ function shapeText(text: string, retention: Retention): Shaped | null {
* Normalize a chat turn into 1..N OTLP log records:
* - one response record (agent.response.completed, or agent.response if partial)
* - one tool.invoked record per captured tool call
+ *
+ * `browser` is the identity sw.ts resolved at startup (see browser.ts). It is
+ * a resource attribute, so every record of the turn carries it, and it is
+ * metadata rather than content, so it survives every retention mode.
*/
-export function normalizeTurn(turn: ChatTurn, retention: Retention): NormalizedTurn {
+export function normalizeTurn(
+ turn: ChatTurn,
+ retention: Retention,
+ browser?: BrowserIdentity,
+): NormalizedTurn {
const resourceAttributes: KeyValue[] = [
str('beacon.origin', ORIGIN),
str('beacon.harness.name', turn.site),
str('service.name', SERVICE_NAME),
str('gen_ai.provider.name', providerFor(turn.site)),
+ ...browserAttributes(browser),
];
const tid = turn.turnId || turnId(turn.sessionId, 0);
@@ -209,12 +220,23 @@ function toolRecord(
};
}
+/** OTel semconv browser/user-agent attributes. The collector promotes
+ * user_agent.name/version into the event's typed `user_agent` field. */
+function browserAttributes(browser: BrowserIdentity | undefined): KeyValue[] {
+ if (!browser) return [];
+ const attrs: KeyValue[] = [str('user_agent.name', browser.name)];
+ if (browser.version) attrs.push(str('user_agent.version', browser.version));
+ if (browser.original) attrs.push(str('user_agent.original', browser.original));
+ if (browser.brands.length > 0) attrs.push(strArray('browser.brands', browser.brands));
+ return attrs;
+}
+
function stringify(v: unknown): string {
return typeof v === 'string' ? v : JSON.stringify(v ?? null);
}
/** Convenience: normalize straight into a single OTLP logs envelope. */
-export function turnToEnvelope(turn: ChatTurn, retention: Retention) {
- const { resourceAttributes, logRecords } = normalizeTurn(turn, retention);
+export function turnToEnvelope(turn: ChatTurn, retention: Retention, browser?: BrowserIdentity) {
+ const { resourceAttributes, logRecords } = normalizeTurn(turn, retention, browser);
return buildLogsEnvelope(resourceAttributes, logRecords, SERVICE_NAME);
}
diff --git a/browser-extension/src/shared/otlp.ts b/browser-extension/src/shared/otlp.ts
index 9644ed29..080f1e39 100644
--- a/browser-extension/src/shared/otlp.ts
+++ b/browser-extension/src/shared/otlp.ts
@@ -7,7 +7,8 @@ export type AnyValue =
| { stringValue: string }
| { intValue: string }
| { doubleValue: number }
- | { boolValue: boolean };
+ | { boolValue: boolean }
+ | { arrayValue: { values: AnyValue[] } };
export interface KeyValue {
key: string;
@@ -45,16 +46,34 @@ export function bool(key: string, value: boolean): KeyValue {
return { key, value: { boolValue: value } };
}
+/** string[] attribute (OTLP ArrayValue of stringValues), e.g. browser.brands. */
+export function strArray(key: string, values: readonly string[]): KeyValue {
+ return { key, value: { arrayValue: { values: values.map((v) => ({ stringValue: v })) } } };
+}
+
/** epoch milliseconds → OTLP nanosecond timestamp string. */
export function msToUnixNano(ms: number): string {
return String(Math.trunc(ms)) + '000000';
}
-/** Look up a single attribute's primitive value (used by tests/delivery). */
-export function attrValue(attrs: KeyValue[], key: string): string | number | boolean | undefined {
+export type AttrPrimitive = string | number | boolean;
+
+/** Look up a single attribute's value (used by tests/delivery). Arrays come
+ * back as arrays of their primitive elements. */
+export function attrValue(
+ attrs: KeyValue[],
+ key: string,
+): AttrPrimitive | AttrPrimitive[] | undefined {
const kv = attrs.find((a) => a.key === key);
if (!kv) return undefined;
const v = kv.value;
+ if ('arrayValue' in v) {
+ return v.arrayValue.values.map(primitive).filter((x): x is AttrPrimitive => x !== undefined);
+ }
+ return primitive(v);
+}
+
+function primitive(v: AnyValue): AttrPrimitive | undefined {
if ('stringValue' in v) return v.stringValue;
if ('intValue' in v) return Number(v.intValue);
if ('doubleValue' in v) return v.doubleValue;
diff --git a/browser-extension/test/unit/browser-target.test.ts b/browser-extension/test/unit/browser-target.test.ts
new file mode 100644
index 00000000..fde2d0be
--- /dev/null
+++ b/browser-extension/test/unit/browser-target.test.ts
@@ -0,0 +1,46 @@
+import { describe, it, expect } from 'vitest';
+import { resolveBrowserTarget } from '../../e2e/browser-target.js';
+
+describe('resolveBrowserTarget (e2e browser selection)', () => {
+ it('defaults to the chromium channel when nothing is set', () => {
+ const t = resolveBrowserTarget({});
+ expect(t.launch).toEqual({ channel: 'chromium' });
+ expect(t.expectedUserAgentNames).toContain('Chromium');
+ });
+
+ it('treats an empty or blank BROWSER_CHANNEL as the default', () => {
+ expect(resolveBrowserTarget({ BROWSER_CHANNEL: '' }).launch).toEqual({ channel: 'chromium' });
+ expect(resolveBrowserTarget({ BROWSER_CHANNEL: ' ' }).launch).toEqual({ channel: 'chromium' });
+ });
+
+ it('selects msedge and expects Edge to identify itself', () => {
+ const t = resolveBrowserTarget({ BROWSER_CHANNEL: 'msedge' });
+ expect(t.launch).toEqual({ channel: 'msedge' });
+ expect(t.expectedUserAgentNames).toEqual(['Microsoft Edge']);
+ });
+
+ it('accepts pre-release channels and maps them to the stable expectation', () => {
+ const t = resolveBrowserTarget({ BROWSER_CHANNEL: 'msedge-beta' });
+ expect(t.launch).toEqual({ channel: 'msedge-beta' });
+ expect(t.expectedUserAgentNames).toEqual(['Microsoft Edge']);
+ expect(resolveBrowserTarget({ BROWSER_CHANNEL: 'chrome' }).expectedUserAgentNames).toEqual([
+ 'Google Chrome',
+ ]);
+ });
+
+ it('BROWSER_EXECUTABLE wins over BROWSER_CHANNEL and carries no fixed expectation', () => {
+ const t = resolveBrowserTarget({
+ BROWSER_CHANNEL: 'msedge',
+ BROWSER_EXECUTABLE: '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
+ });
+ expect(t.launch).toEqual({
+ executablePath: '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
+ });
+ expect(t.expectedUserAgentNames).toBeUndefined();
+ });
+
+ it('rejects non-Chromium or misspelled channels with an actionable message', () => {
+ expect(() => resolveBrowserTarget({ BROWSER_CHANNEL: 'firefox' })).toThrow(/BROWSER_EXECUTABLE/);
+ expect(() => resolveBrowserTarget({ BROWSER_CHANNEL: 'edge' })).toThrow(/msedge/);
+ });
+});
diff --git a/browser-extension/test/unit/browser.test.ts b/browser-extension/test/unit/browser.test.ts
new file mode 100644
index 00000000..8f5de763
--- /dev/null
+++ b/browser-extension/test/unit/browser.test.ts
@@ -0,0 +1,180 @@
+import { describe, it, expect } from 'vitest';
+import { detectBrowser, type NavigatorLike, type UABrand } from '../../src/shared/browser.js';
+
+// Brand lists as each browser reports them in navigator.userAgentData.brands.
+// Edge and Chromium were read from a live MV3 service worker (Edge 153, Chromium
+// 141); the others follow each vendor's documented UA Client Hints behavior.
+const b = (brand: string, version: string): UABrand => ({ brand, version });
+
+const CHROME_UA =
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36';
+
+function nav(brands: UABrand[] | undefined, userAgent = CHROME_UA, extra: Partial<NavigatorLike> = {}) {
+ return { userAgent, userAgentData: brands ? { brands } : undefined, ...extra };
+}
+
+describe('detectBrowser — UA Client Hints brands', () => {
+ it('Microsoft Edge (live Edge 153 service worker)', () => {
+ const id = detectBrowser(
+ nav(
+ [b('Microsoft Edge', '153'), b('Not_A Brand', '8'), b('Chromium', '153')],
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/153.0.0.0 Safari/537.36 Edg/153.0.0.0',
+ ),
+ );
+ expect(id).toEqual({
+ name: 'Microsoft Edge',
+ version: '153',
+ brands: ['Microsoft Edge 153', 'Not_A Brand 8', 'Chromium 153'],
+ original:
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/153.0.0.0 Safari/537.36 Edg/153.0.0.0',
+ });
+ });
+
+ it('plain Chromium (live Chromium 141 service worker)', () => {
+ const id = detectBrowser(nav([b('Chromium', '141'), b('Not?A_Brand', '8')]));
+ expect(id?.name).toBe('Chromium');
+ expect(id?.version).toBe('141');
+ });
+
+ it('Google Chrome', () => {
+ const id = detectBrowser(nav([b('Google Chrome', '124'), b('Chromium', '124'), b('Not-A.Brand', '99')]));
+ expect(id?.name).toBe('Google Chrome');
+ expect(id?.version).toBe('124');
+ });
+
+ it('Brave, which adds its own brand', () => {
+ const id = detectBrowser(nav([b('Brave', '124'), b('Chromium', '124'), b('Not-A.Brand', '99')]));
+ expect(id?.name).toBe('Brave');
+ });
+
+ it("Opera, reporting Opera's own version rather than Chromium's", () => {
+ const id = detectBrowser(
+ nav(
+ [b('Chromium', '124'), b('Opera', '110'), b('Not-A.Brand', '99')],
+ CHROME_UA + ' OPR/110.0.0.0',
+ ),
+ );
+ expect(id?.name).toBe('Opera');
+ expect(id?.version).toBe('110');
+ });
+
+ it('Opera GX: the more specific vendor brand wins', () => {
+ const id = detectBrowser(nav([b('Opera', '110'), b('Chromium', '124'), b('Opera GX', '110')]));
+ expect(id?.name).toBe('Opera GX');
+ });
+
+ it('an unknown fork that brands itself is reported verbatim', () => {
+ const id = detectBrowser(nav([b('Chromium', '124'), b('YaBrowser', '24'), b('Not-A.Brand', '99')]));
+ expect(id?.name).toBe('YaBrowser');
+ expect(id?.version).toBe('24');
+ });
+
+ it('Vivaldi adds no brand, so it reports as Chromium (documented limit)', () => {
+ const id = detectBrowser(nav([b('Chromium', '124'), b('Not-A.Brand', '99')]));
+ expect(id?.name).toBe('Chromium');
+ });
+
+ it('Arc copies Chrome\'s brand list, so it reports as Google Chrome (documented limit)', () => {
+ const id = detectBrowser(nav([b('Chromium', '124'), b('Google Chrome', '124'), b('Not-A.Brand', '99')]));
+ expect(id?.name).toBe('Google Chrome');
+ });
+
+ it('is independent of brand order (Chromium shuffles it)', () => {
+ const brands = [b('Microsoft Edge', '153'), b('Not_A Brand', '8'), b('Chromium', '153')];
+ const names = new Set<string | undefined>();
+ for (const order of [[0, 1, 2], [2, 1, 0], [1, 2, 0], [2, 0, 1]]) {
+ names.add(detectBrowser(nav(order.map((i) => brands[i])))?.name);
+ }
+ expect([...names]).toEqual(['Microsoft Edge']);
+ });
+
+ it.each(['Not_A Brand', 'Not)A;Brand', ' Not A;Brand', 'Not-A.Brand', 'Not?A_Brand', 'Not/A)Brand', 'Not A(Brand'])(
+ 'never picks the GREASE brand %j',
+ (grease) => {
+ expect(detectBrowser(nav([b(grease, '99'), b('Chromium', '124')]))?.name).toBe('Chromium');
+ },
+ );
+
+ it('keeps GREASE in browser.brands, exactly as reported (semconv takes brands verbatim)', () => {
+ const id = detectBrowser(nav([b('Not)A;Brand', '99'), b('Chromium', '124')]));
+ expect(id?.brands).toEqual(['Not)A;Brand 99', 'Chromium 124']);
+ });
+});
+
+describe('detectBrowser — Brave without a Brave brand', () => {
+ it('navigator.brave overrides a Chrome-looking brand list', () => {
+ const id = detectBrowser(
+ nav([b('Google Chrome', '124'), b('Chromium', '124')], CHROME_UA, { brave: { isBrave: () => true } }),
+ );
+ expect(id?.name).toBe('Brave');
+ expect(id?.version).toBe('124');
+ });
+
+ it('navigator.brave does not override another vendor brand', () => {
+ const id = detectBrowser(nav([b('Microsoft Edge', '153'), b('Chromium', '153')], CHROME_UA, { brave: {} }));
+ expect(id?.name).toBe('Microsoft Edge');
+ });
+
+ it('a non-object navigator.brave is ignored', () => {
+ const id = detectBrowser(nav([b('Google Chrome', '124')], CHROME_UA, { brave: true }));
+ expect(id?.name).toBe('Google Chrome');
+ });
+});
+
+describe('detectBrowser — UA string fallback (no UA Client Hints)', () => {
+ it.each([
+ ['Edge', CHROME_UA + ' Edg/120.0.0.0', 'Microsoft Edge', '120'],
+ ['Opera', CHROME_UA + ' OPR/106.0.0.0', 'Opera', '106'],
+ ['Vivaldi (older builds that still say so)', CHROME_UA + ' Vivaldi/6.5.3206.48', 'Vivaldi', '6'],
+ ['Chrome-shaped UA: only the engine can be claimed', CHROME_UA, 'Chromium', '124'],
+ [
+ 'Firefox',
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14.4; rv:125.0) Gecko/20100101 Firefox/125.0',
+ 'Firefox',
+ '125',
+ ],
+ [
+ 'Safari',
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 14_4) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15',
+ 'Safari',
+ '17',
+ ],
+ ])('%s', (_label, ua, name, version) => {
+ const id = detectBrowser(nav(undefined, ua));
+ expect(id?.name).toBe(name);
+ expect(id?.version).toBe(version);
+ expect(id?.brands).toEqual([]);
+ expect(id?.original).toBe(ua);
+ });
+
+ it('falls back to the UA string when the brand list is empty', () => {
+ expect(detectBrowser(nav([], CHROME_UA + ' Edg/120.0.0.0'))?.name).toBe('Microsoft Edge');
+ });
+
+ it('falls back to the UA string when the brand list is only GREASE', () => {
+ const id = detectBrowser(nav([b('Not_A Brand', '8')], CHROME_UA + ' OPR/106.0.0.0'));
+ expect(id?.name).toBe('Opera');
+ expect(id?.brands).toEqual(['Not_A Brand 8']);
+ });
+});
+
+describe('detectBrowser — nothing to go on', () => {
+ it('returns undefined without a navigator', () => {
+ expect(detectBrowser(undefined)).toBeUndefined();
+ });
+
+ it('returns undefined for an empty navigator', () => {
+ expect(detectBrowser({})).toBeUndefined();
+ });
+
+ it('returns undefined for an unrecognizable UA and no brands', () => {
+ expect(detectBrowser({ userAgent: 'curl/8.4.0', userAgentData: null })).toBeUndefined();
+ });
+
+ it('tolerates malformed brand entries', () => {
+ const brands = [null, { brand: 42 }, { brand: '' }, b('Chromium', '124')] as unknown as UABrand[];
+ const id = detectBrowser(nav(brands));
+ expect(id?.name).toBe('Chromium');
+ expect(id?.brands).toEqual(['Chromium 124']);
+ });
+});
diff --git a/browser-extension/test/unit/normalize.test.ts b/browser-extension/test/unit/normalize.test.ts
index b729b7fe..0f7de4f8 100644
--- a/browser-extension/test/unit/normalize.test.ts
+++ b/browser-extension/test/unit/normalize.test.ts
@@ -1,6 +1,12 @@
import { describe, it, expect } from 'vitest';
-import { normalizeTurn } from '../../src/shared/normalize.js';
-import { attrValue, type KeyValue, type LogRecord } from '../../src/shared/otlp.js';
+import { normalizeTurn, turnToEnvelope } from '../../src/shared/normalize.js';
+import {
+ attrValue,
+ type AttrPrimitive,
+ type KeyValue,
+ type LogRecord,
+} from '../../src/shared/otlp.js';
+import type { BrowserIdentity } from '../../src/shared/browser.js';
import type { ChatTurn, Retention } from '../../src/shared/types.js';
function baseTurn(over: Partial<ChatTurn> = {}): ChatTurn {
@@ -23,8 +29,8 @@ function baseTurn(over: Partial<ChatTurn> = {}): ChatTurn {
};
}
-function flat(attrs: KeyValue[]): Record<string, string | number | boolean> {
- const out: Record<string, string | number | boolean> = {};
+function flat(attrs: KeyValue[]): Record<string, AttrPrimitive | AttrPrimitive[]> {
+ const out: Record<string, AttrPrimitive | AttrPrimitive[]> = {};
for (const a of attrs) {
const v = attrValue(attrs, a.key);
if (v !== undefined) out[a.key] = v;
@@ -183,3 +189,67 @@ describe('normalizeTurn — size cap', () => {
expect(p['beacon.field_truncated']).toBe(true);
});
});
+
+describe('normalizeTurn — browser identity', () => {
+ const edge: BrowserIdentity = {
+ name: 'Microsoft Edge',
+ version: '153',
+ brands: ['Microsoft Edge 153', 'Not_A Brand 8', 'Chromium 153'],
+ original: 'Mozilla/5.0 (X11; Linux x86_64) Chrome/153.0.0.0 Safari/537.36 Edg/153.0.0.0',
+ };
+
+ it('emits OTel semconv user_agent.* and browser.brands as resource attributes', () => {
+ const { resourceAttributes } = normalizeTurn(baseTurn(), 'full', edge);
+ const res = flat(resourceAttributes);
+ expect(res['user_agent.name']).toBe('Microsoft Edge');
+ expect(res['user_agent.version']).toBe('153');
+ expect(res['user_agent.original']).toBe(edge.original);
+ expect(res['browser.brands']).toEqual(['Microsoft Edge 153', 'Not_A Brand 8', 'Chromium 153']);
+ });
+
+ it('encodes browser.brands as an OTLP arrayValue of strings', () => {
+ const { resourceAttributes } = normalizeTurn(baseTurn(), 'full', edge);
+ const kv = resourceAttributes.find((a) => a.key === 'browser.brands');
+ expect(kv?.value).toEqual({
+ arrayValue: {
+ values: [
+ { stringValue: 'Microsoft Edge 153' },
+ { stringValue: 'Not_A Brand 8' },
+ { stringValue: 'Chromium 153' },
+ ],
+ },
+ });
+ });
+
+ it('puts identity on the resource, so every record of the turn (incl. tools) carries it', () => {
+ const turn = baseTurn({ toolCalls: [{ id: 't1', name: 'web_search', arguments: { q: 'x' } }] });
+ const env = turnToEnvelope(turn, 'full', edge);
+ expect(env.resourceLogs).toHaveLength(1);
+ expect(flat(env.resourceLogs[0].resource.attributes)['user_agent.name']).toBe('Microsoft Edge');
+ expect(env.resourceLogs[0].scopeLogs[0].logRecords).toHaveLength(3);
+ });
+
+ it('survives metadata retention (identity is metadata, not content)', () => {
+ const res = flat(normalizeTurn(baseTurn(), 'metadata', edge).resourceAttributes);
+ expect(res['user_agent.name']).toBe('Microsoft Edge');
+ expect(res['browser.brands']).toBeDefined();
+ });
+
+ it('omits optional fields it does not have (no version, no UA string, no brands)', () => {
+ const res = flat(normalizeTurn(baseTurn(), 'full', { name: 'Chromium', brands: [] }).resourceAttributes);
+ expect(res['user_agent.name']).toBe('Chromium');
+ expect('user_agent.version' in res).toBe(false);
+ expect('user_agent.original' in res).toBe(false);
+ expect('browser.brands' in res).toBe(false);
+ });
+
+ it('emits no browser attributes at all when identity is unknown (no regression)', () => {
+ const without = normalizeTurn(baseTurn(), 'full').resourceAttributes;
+ expect(without.map((a) => a.key)).toEqual([
+ 'beacon.origin',
+ 'beacon.harness.name',
+ 'service.name',
+ 'gen_ai.provider.name',
+ ]);
+ });
+});
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
index 464fb7c7..7af807ef 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter.go
@@ -1120,6 +1120,7 @@ func (c Converter) PopulateCommon(event *Event, attrs map[string]interface{}) {
applyModel(event, FirstString(attrs, "gen_ai.request.model", "gen_ai.response.model", "model", "ai.model"))
event.Repository = FirstString(attrs, "vcs.repository.url", "repository", "repo.path", "workspace.repository")
event.Branch = FirstString(attrs, "vcs.branch.name", "git.branch", "branch")
+ event.UserAgent = UserAgentFromAttrs(attrs)
if id := FirstString(attrs, "gen_ai.conversation.id", "beacon.session.id", "copilot_chat.session_id", "copilot_chat.chat_session_id", "conversation.id", "conversation_id", "session.id"); id != "" || FirstString(attrs, "cwd", "working_directory", "workspace") != "" {
event.Session = &SessionInfo{
ID: id,
@@ -1548,6 +1549,19 @@ func populateRunContext(event *Event, attrs map[string]interface{}) {
event.Run = &run
}
+// UserAgentFromAttrs promotes the OTel semconv `user_agent.name` / `user_agent.version`
+// attributes into the typed user_agent field. The browser extension sets them on its
+// resource so every browser chat event names the browser (Edge, Brave, Chromium, ...)
+// it came from; promoting them matters because metadata-only forwarding drops raw
+// attributes. A version without a name identifies nothing and is left in raw.
+func UserAgentFromAttrs(attrs map[string]interface{}) *UserAgentInfo {
+ name := FirstStringAttr(attrs, "user_agent.name")
+ if name == "" {
+ return nil
+ }
+ return &UserAgentInfo{Name: name, Version: FirstStringAttr(attrs, "user_agent.version")}
+}
+
func (c Converter) RawPayload(attrs map[string]interface{}, extra map[string]interface{}) map[string]interface{} {
raw := map[string]interface{}{}
for k, v := range extra {
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter_test.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter_test.go
index 5beffe6f..deaa6ddf 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter_test.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/converter_test.go
@@ -1478,6 +1478,108 @@ func TestHarnessNameHonorsBrowserExtensionAttr(t *testing.T) {
}
}
+// browserExtensionLogs builds one OTLP log the way browser-extension/src/shared/normalize.ts
+// does: identity on the resource, the event on the record.
+func browserExtensionLogs(withIdentity bool) plog.Logs {
+ logs := plog.NewLogs()
+ resourceLogs := logs.ResourceLogs().AppendEmpty()
+ res := resourceLogs.Resource().Attributes()
+ res.PutStr("beacon.origin", "browser-extension")
+ res.PutStr("beacon.harness.name", "chatgpt_web")
+ res.PutStr("service.name", "agent-beacon-browser-collector")
+ res.PutStr("gen_ai.provider.name", "openai")
+ if withIdentity {
+ res.PutStr("user_agent.name", "Microsoft Edge")
+ res.PutStr("user_agent.version", "153")
+ res.PutStr("user_agent.original", "Mozilla/5.0 (X11; Linux x86_64) Chrome/153.0.0.0 Safari/537.36 Edg/153.0.0.0")
+ brands := res.PutEmptySlice("browser.brands")
+ for _, b := range []string{"Microsoft Edge 153", "Not_A Brand 8", "Chromium 153"} {
+ brands.AppendEmpty().SetStr(b)
+ }
+ }
+ record := resourceLogs.ScopeLogs().AppendEmpty().LogRecords().AppendEmpty()
+ record.Body().SetStr("chatgpt_web agent.response.completed")
+ record.SetTimestamp(pcommon.NewTimestampFromTime(time.Unix(1700000000, 0).UTC()))
+ record.Attributes().PutStr("beacon.event.action", "agent.response.completed")
+ record.Attributes().PutStr("beacon.event.category", "agent")
+ record.Attributes().PutStr("gen_ai.conversation.id", "conv-1")
+ return logs
+}
+
+// A browser chat event must say which browser produced it, in a typed field rather than only
+// in raw.attributes: metadata-only managed forwarding deletes raw, and a rule or an analyst
+// filtering on the managed Edge profile vs a personal Brave install needs it either way.
+func TestEventFromLogPromotesBrowserUserAgent(t *testing.T) {
+ events := NewConverter(Options{}).EventsFromLogs(browserExtensionLogs(true))
+ if len(events) != 1 {
+ t.Fatalf("expected 1 event, got %d", len(events))
+ }
+ event := events[0]
+ if event.UserAgent == nil || event.UserAgent.Name != "Microsoft Edge" || event.UserAgent.Version != "153" {
+ t.Fatalf("user_agent = %#v, want Microsoft Edge 153", event.UserAgent)
+ }
+ if event.Harness.Name != "chatgpt_web" {
+ t.Fatalf("harness.name = %q, want chatgpt_web (identity must not disturb harness naming)", event.Harness.Name)
+ }
+ encoded, err := json.Marshal(event)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(string(encoded), `"user_agent":{"name":"Microsoft Edge","version":"153"}`) {
+ t.Fatalf("encoded event lacks the typed user_agent object: %s", encoded)
+ }
+ // The full brand list and UA string stay available in raw for local investigation.
+ rawAttrs, _ := event.Raw["attributes"].(map[string]interface{})
+ brands, _ := rawAttrs["browser.brands"].([]interface{})
+ if len(brands) != 3 || brands[0] != "Microsoft Edge 153" {
+ t.Fatalf("raw browser.brands = %#v, want the three reported brands", rawAttrs["browser.brands"])
+ }
+ if rawAttrs["user_agent.original"] == nil {
+ t.Fatal("raw user_agent.original missing")
+ }
+}
+
+func TestEventFromLogOmitsUserAgentWithoutIdentity(t *testing.T) {
+ events := NewConverter(Options{}).EventsFromLogs(browserExtensionLogs(false))
+ if len(events) != 1 {
+ t.Fatalf("expected 1 event, got %d", len(events))
+ }
+ if events[0].UserAgent != nil {
+ t.Fatalf("user_agent = %#v, want nil when no user_agent.name is sent", events[0].UserAgent)
+ }
+ encoded, err := json.Marshal(events[0])
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(string(encoded), `"user_agent"`) {
+ t.Fatalf("encoded event carries user_agent without identity: %s", encoded)
+ }
+}
+
+func TestUserAgentFromAttrs(t *testing.T) {
+ cases := []struct {
+ name string
+ attrs map[string]interface{}
+ want *UserAgentInfo
+ }{
+ {"name and version", map[string]interface{}{"user_agent.name": "Brave", "user_agent.version": "124"}, &UserAgentInfo{Name: "Brave", Version: "124"}},
+ {"name only", map[string]interface{}{"user_agent.name": "Chromium"}, &UserAgentInfo{Name: "Chromium"}},
+ {"trimmed", map[string]interface{}{"user_agent.name": " Opera ", "user_agent.version": " 110 "}, &UserAgentInfo{Name: "Opera", Version: "110"}},
+ {"version without a name identifies nothing", map[string]interface{}{"user_agent.version": "124"}, nil},
+ {"blank name", map[string]interface{}{"user_agent.name": " "}, nil},
+ {"non-string name is not coerced", map[string]interface{}{"user_agent.name": []interface{}{"Edge"}}, nil},
+ {"original alone is not promoted", map[string]interface{}{"user_agent.original": "curl/8.4.0"}, nil},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got := UserAgentFromAttrs(tc.attrs)
+ if (got == nil) != (tc.want == nil) || (got != nil && *got != *tc.want) {
+ t.Fatalf("UserAgentFromAttrs(%v) = %#v, want %#v", tc.attrs, got, tc.want)
+ }
+ })
+ }
+}
+
// Claude Code ships a native PowerShell tool that replaces Bash as the default shell on Windows,
// and it reports the command in the same tool_input.command field. Handling only "bash" left the
// event classified as command.executed with an empty e.command.command -- the leaf every
diff --git a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/event.go b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/event.go
index fccafa52..a6ec020f 100644
--- a/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/event.go
+++ b/collector-builder/exporter/beaconjsonexporter/internal/beaconevent/event.go
@@ -64,6 +64,7 @@ type GenAIUsageCacheCreationInfo = asymptoteobserve.GenAIUsageCacheCreationInfo
type GenAIUsageCacheReadInfo = asymptoteobserve.GenAIUsageCacheReadInfo
type GenAIUsageReasoningInfo = asymptoteobserve.GenAIUsageReasoningInfo
type GenAIWorkflowInfo = asymptoteobserve.GenAIWorkflowInfo
+type UserAgentInfo = asymptoteobserve.UserAgentInfo
type Event struct {
ObservedAt time.Time `json:"-"`
@@ -100,6 +101,7 @@ type Event struct {
Content *ContentInfo `json:"content,omitempty"`
Destination *asymptoteobserve.DestinationInfo `json:"destination,omitempty"`
Health *asymptoteobserve.HealthInfo `json:"health,omitempty"`
+ UserAgent *UserAgentInfo `json:"user_agent,omitempty"`
GenAI *GenAIInfo `json:"gen_ai,omitempty"`
Model string `json:"model,omitempty"`
Repository string `json:"repository,omitempty"`
diff --git a/docs/docs.json b/docs/docs.json
index 50f79451..358bf4ff 100644
--- a/docs/docs.json
+++ b/docs/docs.json
@@ -163,6 +163,7 @@
"group": "Browser Chat",
"pages": [
"runtimes/browser-extension",
+ "runtimes/browser-extension-chromium",
"runtimes/claude-web",
"runtimes/chatgpt-web"
]
diff --git a/docs/runtimes/browser-extension-chromium.mdx b/docs/runtimes/browser-extension-chromium.mdx
new file mode 100644
index 00000000..45e8f902
--- /dev/null
+++ b/docs/runtimes/browser-extension-chromium.mdx
@@ -0,0 +1,160 @@
+---
+title: "Chromium Browsers"
+description: "Which Chromium browsers the Beacon browser extension is tested in, how events name the browser, and how to verify and deploy it in Edge, Brave, Opera, Vivaldi, and Arc"
+---
+
+## Overview
+
+Microsoft Edge, Brave, Opera, Vivaldi, and Arc are all built on Chromium and all run Manifest V3 extensions. The [browser extension](/runtimes/browser-extension) ships one build, and that same build loads in each of them. There is no per-browser port and no second artifact.
+
+A browser being Chromium-based does not mean Beacon has tested it there. This page keeps the two claims apart: which browsers run in automated tests on every change, and which rely on the manual checklist below.
+
+## Support levels
+
+| Browser | Status | How it is verified |
+|---------|--------|--------------------|
+| Chromium | Tested | Automated replay e2e in CI on every pull request (`BROWSER_CHANNEL=chromium`) |
+| Microsoft Edge | Tested | Automated replay e2e in CI on every pull request (`BROWSER_CHANNEL=msedge`) |
+| Google Chrome | Expected to work, not in CI | Branded Chrome (137 and later) no longer honors `--load-extension`, which the harness uses to load `dist/`, so it cannot run in the automated e2e. Use the [manual checklist](#manual-verification-checklist) |
+| Brave | Expected to work, not in CI | [Manual checklist](#manual-verification-checklist). There is no Playwright channel for Brave |
+| Opera, Opera GX | Expected to work, not in CI | [Manual checklist](#manual-verification-checklist). There is no Playwright channel for Opera |
+| Vivaldi | Expected to work, not in CI | [Manual checklist](#manual-verification-checklist). There is no Playwright channel for Vivaldi |
+| Arc | Expected to work, not in CI | [Manual checklist](#manual-verification-checklist). There is no Playwright channel for Arc, and Arc does not run on Linux CI runners |
+| Firefox, Safari | Not supported | Different extension platforms. Tracked separately |
+
+The extension needs a browser built on Chromium 111 or newer, because its interceptor is declared as a main-world content script in the manifest.
+
+## Which browser an event came from
+
+Every event the extension sends names the browser that produced it. On a managed fleet that matters: a paste into ChatGPT from the managed Edge profile and one from a personal Brave install are different investigations.
+
+The extension's service worker reads the browser's own UA Client Hints brand list (`navigator.userAgentData.brands`), falling back to the user-agent string, and sends OpenTelemetry semantic-convention attributes on every OTLP log:
+
+| OTLP attribute | Example | Where it lands in the event |
+|----------------|---------|-----------------------------|
+| `user_agent.name` | `Microsoft Edge` | `user_agent.name` |
+| `user_agent.version` | `153` (major version) | `user_agent.version` |
+| `browser.brands` | `["Microsoft Edge 153", "Not_A Brand 8", "Chromium 153"]` | `raw.attributes` |
+| `user_agent.original` | the browser's UA string | `raw.attributes` |
+
+`user_agent.name` and `user_agent.version` are typed event fields. They are metadata rather than content, so they survive every retention mode, including `metadata` retention in the extension and Metadata-only managed forwarding, which drops `raw`. Threat rules can match on `e.user_agent.name`.
+
+To see the browser on recent events:
+
+```bash
+grep '"claude_web"\|"chatgpt_web"' ~/.beacon/endpoint/logs/runtime.jsonl | tail -5 | jq '{harness: .harness.name, browser: .user_agent.name, version: .user_agent.version}'
+```
+
+`user_agent.name` is what the browser claims to be. Some browsers do not name themselves:
+
+| Browser | Reports as | Why |
+|---------|------------|-----|
+| Microsoft Edge | `Microsoft Edge` | Edge adds its own brand |
+| Brave | `Brave` | Brave adds its own brand. Builds that do not are still recognized by Brave's `navigator.brave` object |
+| Opera, Opera GX | `Opera`, `Opera GX` | Opera adds its own brand. `user_agent.version` is Opera's version, not Chromium's |
+| Google Chrome | `Google Chrome` | |
+| Chromium, and Playwright's test build | `Chromium` | No vendor brand |
+| Vivaldi | Usually `Chromium` | Vivaldi adds no brand of its own and copies Chrome's UA string for site compatibility. Older builds that still put `Vivaldi/` in the UA string without brand hints report `Vivaldi` |
+| Arc | Usually `Google Chrome` | Arc copies Chrome's brand list and UA string. An extension's service worker has no other signal, so Arc cannot be told apart from Chrome |
+
+When a browser adds a brand Beacon does not know, that brand is reported as-is. When a browser gives neither brand hints nor a recognizable UA string, the attributes are omitted rather than guessed.
+
+## Install
+
+Every Chromium browser uses the same archive, `agent-beacon-browser-extension-<version>-chrome.zip`, or a local `dist/` build. The `-chrome` suffix names the Chromium extension family, not Google Chrome alone. See [Use a release archive](/runtimes/browser-extension#use-a-release-archive) for download and verification.
+
+Load it unpacked from the browser's extensions page, with developer mode turned on:
+
+| Browser | Extensions page | Developer mode toggle |
+|---------|-----------------|-----------------------|
+| Google Chrome, Chromium | `chrome://extensions` | Top right |
+| Microsoft Edge | `edge://extensions` | Left sidebar |
+| Brave | `brave://extensions` | Top right |
+| Opera, Opera GX | `opera://extensions` | Top right |
+| Vivaldi | `vivaldi://extensions` | Top right |
+| Arc | `chrome://extensions` | Top right |
+
+Then choose **Load unpacked** and select the `dist` folder or the unzipped release folder, as described in [Load it in Chrome](/runtimes/browser-extension#load-it-in-chrome).
+
+The extension is not published in any extension store yet. When it is, Brave, Vivaldi, and Arc install from the Chrome Web Store, Opera needs its own add-ons listing (or the user allows Chrome Web Store installs in Opera), and Edge needs its own Microsoft Edge Add-ons listing through Partner Center. No Edge Add-ons submission exists today.
+
+## Manual verification checklist
+
+Use this for every browser the automated e2e does not cover, and record the result. Two passes: the replay e2e, which needs no login and no network, and a live check against the real sites.
+
+### 1. Replay e2e against the browser binary
+
+The Playwright harness accepts any Chromium-family binary through `BROWSER_EXECUTABLE`. It launches the browser with the built extension and replays recorded chat streams through it, which proves the extension loads, the interceptor fires, and delivery works in that browser.
+
+```bash
+cd browser-extension
+npm ci
+npm run build
+BROWSER_EXECUTABLE="/Applications/Brave Browser.app/Contents/MacOS/Brave Browser" npx playwright test
+```
+
+Typical executable paths:
+
+| Browser | macOS | Linux |
+|---------|-------|-------|
+| Brave | `/Applications/Brave Browser.app/Contents/MacOS/Brave Browser` | `/usr/bin/brave-browser` |
+| Opera | `/Applications/Opera.app/Contents/MacOS/Opera` | `/usr/bin/opera` |
+| Vivaldi | `/Applications/Vivaldi.app/Contents/MacOS/Vivaldi` | `/usr/bin/vivaldi` |
+| Arc | `/Applications/Arc.app/Contents/MacOS/Arc` | Not available |
+
+On Windows, the path is the **Target** of the browser's shortcut (right-click the shortcut, then **Properties**).
+
+`BROWSER_CHANNEL` selects a Playwright channel instead (`chromium`, the default, or `msedge`; pre-release variants such as `msedge-beta` also work). `BROWSER_EXECUTABLE` wins when both are set. A browser that ignores `--load-extension`, as branded Chrome does, fails every test at the first step, which is itself a useful result: skip to the live check.
+
+### 2. Live check against the real sites
+
+With the Beacon endpoint running:
+
+- [ ] Load the extension unpacked from the browser's extensions page. It appears in the list, is enabled, and shows no errors.
+- [ ] The toolbar popup opens and shows capture on and a queue depth of 0.
+- [ ] Send one message on claude.ai. A `claude_web` event arrives in the runtime log.
+- [ ] Send one message on chatgpt.com. A `chatgpt_web` event arrives in the runtime log.
+- [ ] Both events carry `user_agent.name`. Note the value; see [Which browser an event came from](#which-browser-an-event-came-from) for what each browser should report.
+- [ ] No permission prompt about local network access appeared. The service worker console, from the extensions page, shows no delivery errors.
+- [ ] Quit and restart the browser. The extension is still enabled and the next message is still captured.
+- [ ] Browser-specific: in Brave, repeat one message with Shields up for the site; in Opera, confirm the extension is allowed on claude.ai and chatgpt.com; in Arc, check whether capture also works in a Space that uses a different profile, and record the answer.
+
+### 3. Record the result
+
+Add a row to the pull request or release notes that ran it:
+
+| Browser | Version | OS | Date | Replay e2e | Live check | `user_agent.name` seen |
+|---------|---------|----|------|------------|------------|------------------------|
+| _e.g. Brave_ | _1.x (Chromium N)_ | _macOS 15_ | _YYYY-MM-DD_ | _pass/fail_ | _pass/fail_ | _Brave_ |
+
+## Force-install through browser policy
+
+For IT-managed fleets, Chromium browsers can install an extension without user action through the `ExtensionInstallForcelist` policy, or its successor `ExtensionSettings` with `installation_mode: force_installed`. Each browser reads that policy from its own location:
+
+| Browser | Windows registry key | macOS preference domain | Linux policy directory |
+|---------|----------------------|-------------------------|------------------------|
+| Google Chrome | `HKLM\SOFTWARE\Policies\Google\Chrome` | `com.google.Chrome` | `/etc/opt/chrome/policies/managed/` |
+| Microsoft Edge | `HKLM\SOFTWARE\Policies\Microsoft\Edge` (Edge ADMX) | `com.microsoft.Edge` | `/etc/opt/edge/policies/managed/` |
+| Brave | `HKLM\SOFTWARE\Policies\BraveSoftware\Brave` (Brave ADMX) | `com.brave.Browser` | `/etc/brave/policies/managed/` |
+| Chromium | `HKLM\SOFTWARE\Policies\Chromium` | `org.chromium.Chromium` | `/etc/chromium/policies/managed/` |
+| Opera, Vivaldi, Arc | Not verified | Not verified | Not verified |
+
+Beacon has not verified an enterprise policy path for Opera, Vivaldi, or Arc. Check the vendor's current enterprise documentation, and test on one machine, before relying on policy there.
+
+Each `ExtensionInstallForcelist` entry is `<extension id>;<update URL>`. Two things block force-install today:
+
+- **There is no update URL to point at.** The extension is not in the Chrome Web Store or Microsoft Edge Add-ons, and Beacon does not publish a signed `.crx` with an update manifest. Force-install needs one of those.
+- **There is no stable extension ID.** An unpacked extension's ID is derived from the folder it was loaded from, because the manifest carries no `key`. A policy has nothing fixed to name until the extension is packaged with a key or listed in a store.
+
+Until then, distribution is load-unpacked. Managed profiles can also block developer mode, which blocks **Load unpacked**. If your fleet does, allow developer mode for the profiles that should run the extension, or wait for a store listing.
+
+## Related
+
+<Columns cols={2}>
+ <Card title="Browser extension" icon="puzzle-piece" href="/runtimes/browser-extension">
+ Install, configuration, and troubleshooting.
+ </Card>
+ <Card title="Schema fields" icon="table" href="/telemetry-schema/fields">
+ Where `user_agent` sits in the event schema.
+ </Card>
+</Columns>
diff --git a/docs/runtimes/browser-extension.mdx b/docs/runtimes/browser-extension.mdx
index cf825c0c..9c58d87a 100644
--- a/docs/runtimes/browser-extension.mdx
+++ b/docs/runtimes/browser-extension.mdx
@@ -29,7 +29,7 @@ The extension is in beta. It is not published on the Chrome Web Store and instal
Before installing the extension, make sure:
- The Beacon endpoint is [installed](/cli/install) and running. The extension posts to the local collector on `http://127.0.0.1:4318/v1/logs`, which a default endpoint install already listens on, so no collector configuration is needed.
-- You have Chrome, or another Chromium browser that can load an unpacked MV3 extension. Firefox and Safari are not supported.
+- You have Chrome, Edge, or another Chromium browser that can load an unpacked MV3 extension. See [Chromium browsers](/runtimes/browser-extension-chromium) for which ones are tested. Firefox and Safari are not supported.
- You have Node 22 or newer, if you are building from source rather than using a release archive.
- You have reviewed what the extension retains. It captures full prompt and response text by default.
- The people whose browsers it runs in know it is there, since it reads their Claude.ai and ChatGPT conversations.
@@ -48,6 +48,8 @@ The extension never writes files and never contacts a remote endpoint. Delivery
Events collected this way carry `harness.collection_method` of `otlp`, and a harness name of `claude_web` or `chatgpt_web`, so browser activity stays distinguishable from CLI agents in the runtime log and the dashboard.
+Each event also names the browser it came from in `user_agent.name` and `user_agent.version`, such as `Microsoft Edge` or `Brave`. See [Which browser an event came from](/runtimes/browser-extension-chromium#which-browser-an-event-came-from) for how it is detected and where it cannot tell browsers apart.
+
## Discovery and status
Beacon treats the browser extension as a user-installed source. It is not configured by `beacon endpoint install`, has no hook or plugin file on disk, and does not appear in `beacon endpoint status`, which reports on the endpoint service rather than on browser extensions.
@@ -86,6 +88,8 @@ unzip agent-beacon-browser-extension-<version>-chrome.zip -d agent-beacon-extens
The archive is unsigned, so its `.sha256` is the only integrity check it has. The unzipped folder is what you load, in place of `dist`.
+The `-chrome` archive is the build for every Chromium browser, including Edge, Brave, Opera, Vivaldi, and Arc. There is no separate archive per browser.
+
### Load it in Chrome
1. Open `chrome://extensions`.
@@ -94,6 +98,8 @@ The archive is unsigned, so its `.sha256` is the only integrity check it has. Th
4. Confirm the Agent Beacon browser collector now appears in the list and is enabled.
5. Click the extension's toolbar icon to check its status and, if you want, change the retention mode before capturing anything.
+Other Chromium browsers load it the same way from their own extensions page, such as `edge://extensions` or `brave://extensions`. See [Chromium browsers](/runtimes/browser-extension-chromium#install).
+
## Configuration
The extension is configured in its own UI, not by `beacon`. There is no CLI command and no config file on disk. Settings are split across two surfaces:
@@ -165,7 +171,8 @@ Coverage that is the same for both sites:
| Approval telemetry | Not available. Neither site exposes approval decisions to a page script |
| Session lifecycle | Partial. Turns are correlated by conversation id; there is no session start or stop signal |
| Local JSONL and dashboard | Supported after events reach the collector |
-| MDM deployment | Not covered by Beacon's MDM assets. Distribute through browser policy instead |
+| MDM deployment | Not covered by Beacon's MDM assets. Browser force-install policy needs a store listing or signed package, which do not exist yet. See [Force-install through browser policy](/runtimes/browser-extension-chromium#force-install-through-browser-policy) |
+| Browser attribution | Supported. `user_agent.name` and `user_agent.version` name the browser on every event |
Tool telemetry and token usage differ by site. See [Claude.ai](/runtimes/claude-web) and [ChatGPT](/runtimes/chatgpt-web).
diff --git a/docs/telemetry-schema/fields.mdx b/docs/telemetry-schema/fields.mdx
index 0201439b..cbe20dba 100644
--- a/docs/telemetry-schema/fields.mdx
+++ b/docs/telemetry-schema/fields.mdx
@@ -33,6 +33,7 @@ Beacon models each event as an action plus a set of typed entities. The [`event`
| `gen_ai` | OpenTelemetry GenAI semantic convention context | `agent`, `conversation`, `input`, `output`, `provider`, `request`, `response`, `retrieval`, `system_instructions`, `tool`, `usage`, `workflow` |
| `destination` | Output or validation destination state | `type`, `mode`, `status` |
| `health` | Endpoint or component health state | `component`, `status`, `reason` |
+| `user_agent` | Browser that produced a browser chat event, as the browser names itself | `name`, `version` |
Top-level `sequence`, `model`, `repository`, `branch`, `message`, `raw`, and `field_truncated` fields add shared context that can apply across multiple entities. For example, a command event can include both `tool` and `command`; a file edit can include `file`, `session`, `repository`, and `branch`; a CI event can include `origin` and `run`; and a GenAI tool call can include both `tool` and nested `gen_ai.tool` metadata.
@@ -76,6 +77,7 @@ Optional context fields add detail when available:
| `gen_ai` | OpenTelemetry GenAI request, response, usage, message, tool, retrieval, evaluation, provider, and workflow metadata |
| `destination` | Output destination state, such as Wazuh localfile validation |
| `health` | Component health status |
+| `user_agent` | Browser name and major version for browser extension events, such as `Microsoft Edge` or `Brave`. See [Chromium browsers](/runtimes/browser-extension-chromium#which-browser-an-event-came-from) |
| `model`, `repository`, `branch`, `message`, `raw`, `field_truncated` | Additional runtime context and truncation metadata |
## Related
diff --git a/pkg/asymptoteobserve/event.go b/pkg/asymptoteobserve/event.go
index 9320c181..ae536963 100644
--- a/pkg/asymptoteobserve/event.go
+++ b/pkg/asymptoteobserve/event.go
@@ -420,6 +420,16 @@ type DestinationInfo struct {
Status string `json:"status,omitempty"`
}
+// UserAgentInfo identifies the user agent (for browser-sourced events, the browser)
+// that produced an event, in the OpenTelemetry and ECS `user_agent.*` shape. Name is
+// what the agent claims to be, e.g. "Microsoft Edge", "Brave", or "Chromium", and
+// Version is its version as reported (the browser extension sends the major version).
+// It is metadata rather than content, so it survives metadata-only retention.
+type UserAgentInfo struct {
+ Name string `json:"name,omitempty"`
+ Version string `json:"version,omitempty"`
+}
+
type HealthInfo struct {
Component string `json:"component,omitempty"`
Status string `json:"status,omitempty"`
@@ -472,6 +482,7 @@ type Event struct {
Content *ContentInfo `json:"content,omitempty"`
Destination *DestinationInfo `json:"destination,omitempty"`
Health *HealthInfo `json:"health,omitempty"`
+ UserAgent *UserAgentInfo `json:"user_agent,omitempty"`
GenAI *GenAIInfo `json:"gen_ai,omitempty"`
Model string `json:"model,omitempty"`
Repository string `json:"repository,omitempty"`
diff --git a/pkg/asymptoteobserve/threatrules/cel_test.go b/pkg/asymptoteobserve/threatrules/cel_test.go
index 4206c445..a3e11833 100644
--- a/pkg/asymptoteobserve/threatrules/cel_test.go
+++ b/pkg/asymptoteobserve/threatrules/cel_test.go
@@ -105,3 +105,33 @@ func TestEvalMatchPresent(t *testing.T) {
t.Fatalf("expected match")
}
}
+
+// Browser chat events name their browser in e.user_agent, so a rule can scope to (or away
+// from) the managed browser. Events from every other source have no user_agent at all, and a
+// rule on it must quietly not match them rather than error.
+func TestEvalMatchUserAgent(t *testing.T) {
+ prog, err := CompileMatch(`e.harness.name == "chatgpt_web" && e.user_agent.name != "Microsoft Edge"`)
+ if err != nil {
+ t.Fatalf("compile: %v", err)
+ }
+ cases := []struct {
+ name string
+ event asymptoteobserve.Event
+ want bool
+ }{
+ {"personal Brave", asymptoteobserve.Event{Harness: asymptoteobserve.HarnessInfo{Name: "chatgpt_web"}, UserAgent: &asymptoteobserve.UserAgentInfo{Name: "Brave", Version: "124"}}, true},
+ {"managed Edge", asymptoteobserve.Event{Harness: asymptoteobserve.HarnessInfo{Name: "chatgpt_web"}, UserAgent: &asymptoteobserve.UserAgentInfo{Name: "Microsoft Edge", Version: "153"}}, false},
+ {"CLI agent without user_agent", asymptoteobserve.Event{Harness: asymptoteobserve.HarnessInfo{Name: "claude_code"}}, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ got, err := EvalMatch(prog, tc.event)
+ if err != nil {
+ t.Fatalf("eval: %v", err)
+ }
+ if got != tc.want {
+ t.Fatalf("match = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/spec/threat-rules/FIELDS.md b/spec/threat-rules/FIELDS.md
index 562c24d5..e1e9e92b 100644
--- a/spec/threat-rules/FIELDS.md
+++ b/spec/threat-rules/FIELDS.md
@@ -147,4 +147,6 @@ Regenerate with `beacon rules fields --markdown > spec/threat-rules/FIELDS.md`.
| `e.trace.span_id` | string |
| `e.user.name` | string |
| `e.user.uid` | string |
+| `e.user_agent.name` | string |
+| `e.user_agent.version` | string |
| `e.vendor` | string |