A desktop coding agent with free access to frontier models.
TypeScript
feat: desktop analytics on our own project
ogsamratc6d177461ed7
diff --git a/.github/workflows/build-electron-desktop.yml b/.github/workflows/build-electron-desktop.ymlindex 69bbb358..fcc0dd53 100644--- a/.github/workflows/build-electron-desktop.yml+++ b/.github/workflows/build-electron-desktop.yml@@ -26,6 +26,12 @@ on:permissions:contents: read+# Product analytics of packaged builds (PostHog project "OmniRush Desktop").+# A public client key, compiled into the app; a repository variable overrides it.+env:+ VITE_OMNIRUSH_POSTHOG_KEY: ${{ vars.OMNIRUSH_POSTHOG_KEY || 'phc_uKRzMW7rNe68NKBxCjAwBvqzpxiRj77dGDY7WN3uGoMX' }}+ VITE_OMNIRUSH_POSTHOG_HOST: ${{ vars.OMNIRUSH_POSTHOG_HOST || 'https://us.i.posthog.com' }}+jobs:build-electron:if: ${{ !inputs.updater_e2e_only }}diff --git a/.github/workflows/release-desktop.yml b/.github/workflows/release-desktop.ymlindex 2770110e..77230b8d 100644--- a/.github/workflows/release-desktop.yml+++ b/.github/workflows/release-desktop.yml@@ -18,6 +18,12 @@ concurrency:group: desktop-release-${{ github.ref_name }}-${{ inputs.tag }}cancel-in-progress: false+# Product analytics of packaged builds (PostHog project "OmniRush Desktop").+# A public client key, compiled into the app; a repository variable overrides it.+env:+ VITE_OMNIRUSH_POSTHOG_KEY: ${{ vars.OMNIRUSH_POSTHOG_KEY || 'phc_uKRzMW7rNe68NKBxCjAwBvqzpxiRj77dGDY7WN3uGoMX' }}+ VITE_OMNIRUSH_POSTHOG_HOST: ${{ vars.OMNIRUSH_POSTHOG_HOST || 'https://us.i.posthog.com' }}+jobs:prepare:name: Prepare releasediff --git a/apps/app/src/app/lib/analytics.ts b/apps/app/src/app/lib/analytics.tsindex 6fd8b826..05b0a0a1 100644--- a/apps/app/src/app/lib/analytics.ts+++ b/apps/app/src/app/lib/analytics.ts@@ -2,14 +2,16 @@* Product analytics for the omnirush.ai desktop app (PostHog, zero-dependency).** Principles (mirrors `den-telemetry.ts`):- * - Never send message content, file paths, code, or prompts. Only event- * names, counts, lengths, durations, and coarse context (workspace type,- * provider/model id). Sole exception: answers the user types directly- * into an explicit survey field (e.g. the onboarding attribution survey).+ * - Never send message content, file paths, code, prompts, e-mail addresses+ * or names. Only event names, counts, lengths, durations, and coarse+ * context (app version, OS, workspace type, provider/model id, sandbox+ * mode). Survey answers are fixed choices only, never free text.+ * - Not anonymous: once signed in, events carry the opaque OmniRush account+ * id (the `id` from /device/me) as the PostHog distinct id; signing out+ * resets to a fresh random device id. Before sign-in, that random id.+ * - Always on when the build sets a PostHog key (VITE_OMNIRUSH_POSTHOG_KEY);+ * there is no in-app opt-out. Without a key nothing is sent.* - Fire-and-forget: analytics must never break or slow the app.- * - Respect the user: a single `analyticsEnabled` preference (Settings ->- * Preferences) turns everything off; without a build-time PostHog key- * nothing is sent over the network.* - Every capture is mirrored into the local app inspector* (`window.__omnirush.record("analytics.<event>")`) so coded evals can* assert instrumentation without any analytics backend.@@ -26,18 +28,24 @@ const DEFAULT_POSTHOG_HOST = "https://us.i.posthog.com";// No built-in key: nothing is sent unless the build sets// VITE_OMNIRUSH_POSTHOG_KEY. The inspector mirror still records events// locally either way.-const POSTHOG_KEY = resolvePosthogKey(import.meta.env.VITE_OMNIRUSH_POSTHOG_KEY);-const POSTHOG_HOST = (ENV_POSTHOG_HOST || DEFAULT_POSTHOG_HOST).replace(/\/+$/, "");+let posthogKey = resolvePosthogKey(import.meta.env.VITE_OMNIRUSH_POSTHOG_KEY);+let posthogHost = (ENV_POSTHOG_HOST || DEFAULT_POSTHOG_HOST).replace(/\/+$/, "");+let appVersion = ENV_APP_VERSION;const PREFS_STORAGE_KEY = "omnirush.preferences";const DISTINCT_ID_STORAGE_KEY = "omnirush.analytics.distinctId";+const ACCOUNT_ID_STORAGE_KEY = "omnirush.analytics.accountId";+const FIRST_RUN_STORAGE_KEY = "omnirush.analytics.firstRun";const FLUSH_INTERVAL_MS = 10_000;const MAX_BATCH = 50;+const ACCOUNT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+export type AnalyticsProperties = Record<string, string | number | boolean | null>;type QueuedEvent = {event: string;+ distinctId: string;properties: AnalyticsProperties;timestamp: string;};@@ -46,44 +54,97 @@ let queue: QueuedEvent[] = [];let flushTimer: ReturnType<typeof setInterval> | null = null;let initialized = false;-export function isAnalyticsEnabled(): boolean {- if (typeof window === "undefined") return false;+// Whether this profile had saved preferences before this process started:+// read at import, before any provider writes its defaults. A first launch+// has none.+const hadPreferencesAtStart = (() => {try {- const raw = window.localStorage.getItem(PREFS_STORAGE_KEY);- if (!raw) return true;- const parsed: unknown = JSON.parse(raw);- if (parsed && typeof parsed === "object" && "analyticsEnabled" in parsed) {- return (parsed as { analyticsEnabled?: unknown }).analyticsEnabled !== false;- }- return true;+ return typeof window !== "undefined" && window.localStorage.getItem(PREFS_STORAGE_KEY) !== null;} catch {return true;}+})();++/** Tests only: set the key, host and version a build would. */+export function configureAnalyticsForTests(config: { key?: string; host?: string; appVersion?: string }) {+ if (config.key !== undefined) posthogKey = resolvePosthogKey(config.key);+ if (config.host !== undefined) posthogHost = config.host.replace(/\/+$/, "");+ if (config.appVersion !== undefined) appVersion = config.appVersion;+}++/** Whether events leave this computer (a key is set). */+export function isAnalyticsActive(): boolean {+ return Boolean(posthogKey);+}++function storage(): Storage | null {+ try {+ return typeof window === "undefined" ? null : window.localStorage;+ } catch {+ return null;+ }}+/** The random device id used before sign-in (and after sign-out). */export function getAnalyticsDistinctId(): string {- if (typeof window === "undefined") return "server";+ const store = storage();+ if (!store) return "server";try {- const existing = window.localStorage.getItem(DISTINCT_ID_STORAGE_KEY)?.trim();+ const existing = store.getItem(DISTINCT_ID_STORAGE_KEY)?.trim();if (existing) return existing;const next = crypto.randomUUID();- window.localStorage.setItem(DISTINCT_ID_STORAGE_KEY, next);+ store.setItem(DISTINCT_ID_STORAGE_KEY, next);return next;} catch {return "unknown";}}+/** The signed-in OmniRush account id events are linked to, or null. */+export function getAnalyticsAccountId(): string | null {+ try {+ const value = storage()?.getItem(ACCOUNT_ID_STORAGE_KEY)?.trim() ?? "";+ return ACCOUNT_ID.test(value) ? value : null;+ } catch {+ return null;+ }+}++function currentDistinctId(): string {+ return getAnalyticsAccountId() ?? getAnalyticsDistinctId();+}++/** "macos" | "windows" | "linux" | "other": the OS family, nothing finer. */+export function analyticsOs(platform: string | null | undefined): string {+ const value = (platform ?? "").toLowerCase();+ if (value.startsWith("mac") || value === "darwin") return "macos";+ if (value.startsWith("win")) return "windows";+ if (value.includes("linux") || value.includes("x11")) return "linux";+ return "other";+}+function baseProperties(): AnalyticsProperties {+ const platform = typeof navigator === "undefined" ? null : navigator.platform || null;return {- app_version: ENV_APP_VERSION || null,- platform: typeof navigator === "undefined" ? null : navigator.platform || null,+ app_version: appVersion || null,+ platform,+ os: analyticsOs(platform),};}+function enqueue(event: string, distinctId: string, properties: AnalyticsProperties) {+ queue.push({+ event,+ distinctId,+ properties: { ...baseProperties(), ...properties },+ timestamp: new Date().toISOString(),+ });+ if (queue.length >= MAX_BATCH) void flushAnalytics();+}+/**- * Queue an analytics event. Always mirrored to the local inspector;- * only sent over the network when enabled and a key is configured.+ * Queue an analytics event. Always mirrored to the local inspector; only+ * sent over the network when a key is configured.*/export function captureAnalyticsEvent(event: string, properties: AnalyticsProperties = {}) {try {@@ -91,54 +152,80 @@ export function captureAnalyticsEvent(event: string, properties: AnalyticsProper} catch {// Inspector unavailable (non-browser context).}+ if (!posthogKey) return;+ enqueue(event, currentDistinctId(), properties);+}- if (!POSTHOG_KEY || !isAnalyticsEnabled()) return;+/**+ * Link this device to the signed-in OmniRush account (its opaque UUID, never+ * an e-mail or name). Sends `$identify` once per account; later events use+ * the account id as their distinct id.+ */+export function identifyAnalyticsAccount(accountId: string | null | undefined): boolean {+ const id = accountId?.trim() ?? "";+ if (!ACCOUNT_ID.test(id)) return false;+ if (getAnalyticsAccountId() === id) return false;+ const anonymous = getAnalyticsDistinctId();+ try {+ storage()?.setItem(ACCOUNT_ID_STORAGE_KEY, id);+ } catch {+ // Storage unavailable: the identify below still links this run.+ }+ try {+ recordInspectorEvent("analytics.$identify", {});+ } catch {+ // Inspector unavailable.+ }+ if (posthogKey) enqueue("$identify", id, { $anon_distinct_id: anonymous });+ return true;+}- queue.push({- event,- properties: { ...baseProperties(), ...properties },- timestamp: new Date().toISOString(),- });- if (queue.length >= MAX_BATCH) {- void flushAnalytics();+/** Sign-out: forget the account and start over with a new random device id. */+export function resetAnalyticsAccount(): boolean {+ const store = storage();+ const had = getAnalyticsAccountId() !== null;+ try {+ store?.removeItem(ACCOUNT_ID_STORAGE_KEY);+ store?.setItem(DISTINCT_ID_STORAGE_KEY, crypto.randomUUID());+ } catch {+ // Storage unavailable.+ }+ if (had) {+ try {+ recordInspectorEvent("analytics.$reset", {});+ } catch {+ // Inspector unavailable.+ }}+ return had;}/**- * Link the anonymous distinct id to the signed-in Den user so DAU and- * retention survive sign-in. Sends only the user id — no email or name.+ * Follow the account status (/device/me): identify when signed in with an+ * account id, reset when the app is signed out.*/-function identify(denUserId: string) {- if (!POSTHOG_KEY || !isAnalyticsEnabled()) return;- queue.push({- event: "$identify",- properties: {- ...baseProperties(),- distinct_id: denUserId,- $anon_distinct_id: getAnalyticsDistinctId(),- },- timestamp: new Date().toISOString(),- });+export function syncAnalyticsAccount(status: { connected: boolean; accountId?: string | null } | null | undefined) {+ if (!status) return;+ if (status.connected) {+ if (status.accountId) identifyAnalyticsAccount(status.accountId);+ return;+ }+ if (getAnalyticsAccountId() !== null) resetAnalyticsAccount();}export async function flushAnalytics(): Promise<void> {- if (queue.length === 0 || !POSTHOG_KEY) return;+ if (queue.length === 0 || !posthogKey) return;const batch = queue.splice(0, MAX_BATCH);- const distinctId = getAnalyticsDistinctId();-try {- await fetch(`${POSTHOG_HOST}/batch/`, {+ await fetch(`${posthogHost}/batch/`, {method: "POST",keepalive: true,headers: { "Content-Type": "application/json" },body: JSON.stringify({- api_key: POSTHOG_KEY,+ api_key: posthogKey,batch: batch.map((entry) => ({event: entry.event,- distinct_id:- typeof entry.properties.distinct_id === "string"- ? entry.properties.distinct_id- : distinctId,+ distinct_id: entry.distinctId,timestamp: entry.timestamp,properties: entry.properties,})),@@ -149,6 +236,11 @@ export async function flushAnalytics(): Promise<void> {}}+/** The onboarding survey's event: the chosen source and the answer's length, never the free text. */+export function attributionSurveyProperties(source: string, aiPrompt?: string | null): AnalyticsProperties {+ return { source, ai_prompt_length: aiPrompt?.trim().slice(0, 500).length ?? 0 };+}+// Task run duration tracking: sendDraft marks the start, the session.idle// sync event takes it. Also acts as a dedupe guard so idle events that do// not correspond to an instrumented run (or arrive from a second workspace@@ -167,8 +259,26 @@ export function takeTaskRunStart(sessionId: string): number | null {}/**- * One-time setup: flush loop, unload flush, and cloud sign-in listener.- * Mounted from AppRoot.+ * `first_run` once per profile: a profile that had no saved preferences when+ * the app started. Profiles from earlier versions are marked without an event.+ */+export function captureFirstRunOnce(hadPreferences = hadPreferencesAtStart): boolean {+ const store = storage();+ if (!store) return false;+ try {+ if (store.getItem(FIRST_RUN_STORAGE_KEY)) return false;+ store.setItem(FIRST_RUN_STORAGE_KEY, new Date().toISOString());+ } catch {+ return false;+ }+ if (hadPreferences) return false;+ captureAnalyticsEvent("first_run", {});+ return true;+}++/**+ * One-time setup: flush loop, unload flush, first run, and the Den cloud+ * sign-in listener. Mounted from AppRoot.*/export function initAnalytics() {if (initialized || typeof window === "undefined") return;@@ -180,10 +290,12 @@ export function initAnalytics() {if (document.visibilityState === "hidden") void flushAnalytics();});+ captureFirstRunOnce();++ // A Den (organization cloud) sign-in: counted, but the distinct id stays+ // the OmniRush account id (identifyAnalyticsAccount), never a Den user id.window.addEventListener(denSessionUpdatedEvent, ((event: CustomEvent<DenSessionUpdatedDetail>) => {if (event.detail?.status !== "success") return;- const userId = event.detail.user?.id?.trim() ?? "";- if (userId) identify(userId);captureAnalyticsEvent("cloud_signed_in", {});}) as EventListener);}diff --git a/apps/app/src/app/lib/error-monitoring.ts b/apps/app/src/app/lib/error-monitoring.tsindex 94a4190a..419d861c 100644--- a/apps/app/src/app/lib/error-monitoring.ts+++ b/apps/app/src/app/lib/error-monitoring.ts@@ -11,13 +11,11 @@* (`VITE_OMNIRUSH_DEPLOYMENT=web`), `VITE_OMNIRUSH_SENTRY_DSN` is set, and* the page is not running inside Electron (the desktop app keeps its own* consent-gated telemetry in `apps/desktop/electron/sentry.mjs`).- * - Respects the same `analyticsEnabled` preference as product analytics.** The pre-boot half lives as an inline script in `index.html` so a bundle* that never loads is still reported; once this module starts it takes over* via `window.__omnirushWebErrorMonitorActive`.*/-import { isAnalyticsEnabled } from "./analytics";import { getOmniRushDeployment } from "./omnirush-deployment";import { isElectronRuntime } from "./runtime-env";@@ -124,7 +122,6 @@ const seenErrors = new Set<string>();function deliver(target: SentryDsnTarget, input: WebErrorInput) {if (sentCount >= MAX_EVENTS_PER_SESSION) return;- if (!isAnalyticsEnabled()) return;const dedupeKey = `${input.type}:${input.message}`;if (seenErrors.has(dedupeKey)) return;seenErrors.add(dedupeKey);diff --git a/apps/app/src/app/lib/gateway-refusal.ts b/apps/app/src/app/lib/gateway-refusal.tsnew file mode 100644index 00000000..6b1bdf13--- /dev/null+++ b/apps/app/src/app/lib/gateway-refusal.ts@@ -0,0 +1,28 @@+import type { AnalyticsProperties } from "./analytics";++/**+ * Which omnirush.ai refusal an error card shows, for product analytics:+ * a spent allowance or cap (`limit_shown`) or the request policy+ * (`policy_refusal_shown`). Reads only the error's title and technical+ * details, and returns coarse labels, never the text.+ */+export type GatewayRefusalEvent = { event: "limit_shown" | "policy_refusal_shown"; properties: AnalyticsProperties };++const POLICY = /request_policy_refused|OmniRush can[’']t help with this request/i;+const GRANT_DAY = /today[’']s tokens are used up|used today[’']s model allowance/i;+const GRANT_WEEK = /this week[’']s cap is reached/i;+const GRANT_EMPTY = /you have no tokens left/i;+const GRANT = /daily_grant_exhausted/i;+const SESSION_CAP = /session_quality_cap/i;++export function gatewayRefusalEvent(error: { title?: string | null; technicalDetails?: string | null } | null | undefined): GatewayRefusalEvent | null {+ if (!error) return null;+ const text = `${error.title ?? ""}\n${error.technicalDetails ?? ""}`;+ if (POLICY.test(text)) return { event: "policy_refusal_shown", properties: { reason: "request_policy" } };+ if (GRANT_DAY.test(text)) return { event: "limit_shown", properties: { limit_type: "tokens", scope: "day" } };+ if (GRANT_WEEK.test(text)) return { event: "limit_shown", properties: { limit_type: "tokens", scope: "week" } };+ if (GRANT_EMPTY.test(text)) return { event: "limit_shown", properties: { limit_type: "tokens", scope: "empty" } };+ if (GRANT.test(text)) return { event: "limit_shown", properties: { limit_type: "tokens", scope: "unknown" } };+ if (SESSION_CAP.test(text)) return { event: "limit_shown", properties: { limit_type: "session_cap", scope: "session" } };+ return null;+}diff --git a/apps/app/src/app/lib/quality.ts b/apps/app/src/app/lib/quality.tsindex 615e41a6..a04c017b 100644--- a/apps/app/src/app/lib/quality.ts+++ b/apps/app/src/app/lib/quality.ts@@ -5,6 +5,7 @@// the app only animates the wheel to `segmentIndex` and renders its flags.import { create } from "zustand";+import { syncAnalyticsAccount } from "./analytics";import type {OmniRushAccountQuality,@@ -295,6 +296,8 @@ export function refreshAccountStatus(inFlight ??= read(openSessionId ? { sessionId: openSessionId } : undefined).then((status) => {useAccountStatusStore.getState().set(status);+ // Signed in: analytics carry the account id; signed out: reset.+ syncAnalyticsAccount(status);return status;}).catch(() => {diff --git a/apps/app/src/i18n/locales/en.ts b/apps/app/src/i18n/locales/en.tsindex 8d54ad1f..045e6549 100644--- a/apps/app/src/i18n/locales/en.ts+++ b/apps/app/src/i18n/locales/en.ts@@ -1417,12 +1417,8 @@ export default {"settings.api_keys_info": "API keys are stored locally by omnirush.ai. Environment-backed providers must be changed in the worker environment and then reloaded.","settings.appearance_hint": "Match the system or force light/dark mode.","settings.appearance_title": "Appearance",- "settings.analytics_toggle": "Share anonymous usage data",- "settings.analytics_toggle_desc": "Helps us understand which features matter. Never includes your messages, prompts, code, or file contents.","settings.audit_log_title": "Audit log","settings.auto_compact": "Auto context compaction",- "settings.privacy_section_desc": "Control what omnirush.ai shares to improve the product.",- "settings.privacy_title": "Privacy","settings.auto_compact_desc": "Controls omnirush.ai compaction.auto for this workspace. Reload the engine after changing it.","settings.auto_compact_unavailable": "Auto context compaction is not yet available.","settings.auto_update_desc": "Download new versions in the background and install when you quit. You can also restart when you’re ready.",diff --git a/apps/app/src/react-app/domains/session/sync/session-sync.ts b/apps/app/src/react-app/domains/session/sync/session-sync.tsindex 72ab1f91..5b914729 100644--- a/apps/app/src/react-app/domains/session/sync/session-sync.ts+++ b/apps/app/src/react-app/domains/session/sync/session-sync.ts@@ -5,6 +5,7 @@ import type { FilePart, Part, PermissionRequest, PermissionV2Request, QuestionReimport { getReactQueryClient } from "../../../infra/query-client";import { closeSessionBrowserTabs } from "@/app/lib/desktop";import { captureAnalyticsEvent, takeTaskRunStart } from "@/app/lib/analytics";+import { gatewayRefusalEvent } from "@/app/lib/gateway-refusal";import { trackTaskCompleted, trackTaskFailed } from "@/app/lib/den-telemetry";import { observeModelsTaskEvent } from "@/app/lib/models-task-analytics";import { createClient, unwrap } from "@/app/lib/opencode";@@ -946,6 +947,11 @@ function applyEvent(entry: SyncEntry, workspaceId: string, event: OpencodeEvent)const errorPresentation = presentOpencodeSessionError(sessionError);const errorText = describeOpencodeSessionError(sessionError);const runStartedAt = takeTaskRunStart(sessionId);+ // Once per shown error: the run this app started, or a session it follows.+ const refusal = gatewayRefusalEvent(errorPresentation);+ if (refusal && (runStartedAt !== null || isTrackedSession(entry, sessionId))) {+ captureAnalyticsEvent(refusal.event, refusal.properties);+ }if (runStartedAt !== null) {captureAnalyticsEvent("task_run_errored", {duration_ms: Date.now() - runStartedAt,diff --git a/apps/app/src/react-app/domains/settings/linux-sandbox.ts b/apps/app/src/react-app/domains/settings/linux-sandbox.tsindex 24ee9c93..84064f04 100644--- a/apps/app/src/react-app/domains/settings/linux-sandbox.ts+++ b/apps/app/src/react-app/domains/settings/linux-sandbox.ts@@ -1,5 +1,6 @@import { useCallback, useEffect, useRef, useState } from "react";+import { captureAnalyticsEvent, type AnalyticsProperties } from "@/app/lib/analytics";import type { OmniRushServerClient, OmniRushWorkspaceBox, OmniRushWorkspaceBoxProgress } from "@/app/lib/omnirush-server";export type LinuxSandboxClient = Pick<OmniRushServerClient, "getWorkspaceBox" | "setWorkspaceBox" | "setWorkspaceBoxBackend" | "resetWorkspaceBox" | "retryWorkspaceBox">;@@ -162,6 +163,39 @@ export function linuxSandboxMoving(box: OmniRushWorkspaceBox | null): boolean {return Boolean(box?.on && MOVING.has(box.state));}+/**+ * Why commands of a project with the sandbox on run on this computer instead+ * (the sandbox fell back to the host), for the `sandbox_fallback` event:+ * coarse labels only (the backend id, never paths or errors). Null while the+ * sandbox runs, moves, or is off by choice.+ */+export function sandboxFallbackProperties(box: OmniRushWorkspaceBox | null): AnalyticsProperties | null {+ if (!box?.on) return null;+ let reason: string | null = null;+ if (box.state === "failed") reason = "start_failed";+ else if (box.state === "unavailable" && box.backendSetting.value !== "native") reason = box.runtime?.ok ? "not_running" : "no_backend";+ if (!reason) return null;+ return {+ reason,+ sandbox_mode: box.mode ?? "default",+ backend: box.backend?.id ?? null,+ backend_setting: box.backendSetting.value === "auto" ? "auto" : "fixed",+ };+}++const fallbackReported = new Set<string>();++/** One `sandbox_fallback` per project and reason while the app runs. */+export function reportSandboxFallback(workspaceId: string | null, box: OmniRushWorkspaceBox | null): boolean {+ const properties = sandboxFallbackProperties(box);+ if (!workspaceId || !properties) return false;+ const key = `${workspaceId}:${properties.reason}`;+ if (fallbackReported.has(key)) return false;+ fallbackReported.add(key);+ captureAnalyticsEvent("sandbox_fallback", properties);+ return true;+}+export type LinuxSandboxProblem = { message: string; retry: (() => void) | null };/**@@ -176,6 +210,8 @@ export function useLinuxSandbox(client: LinuxSandboxClient | null, workspaceId:const [notice, setNotice] = useState("");const sequence = useRef(0);const movingSince = useRef<number | null>(null);+ // The project the shown status was read for (the fallback event names only that one).+ const boxFor = useRef<string | null>(null);const load = useCallback(async (fresh = false) => {if (!client || !workspaceId) return;@@ -183,6 +219,7 @@ export function useLinuxSandbox(client: LinuxSandboxClient | null, workspaceId:const value = await client.getWorkspaceBox(workspaceId, { fresh }).catch(() => null);if (sequence.current !== startedAt) return;if (value) {+ boxFor.current = workspaceId;setBox(value);setProblem((current) => (current?.message === LOAD_FAILED ? null : current));} else {@@ -205,6 +242,10 @@ export function useLinuxSandbox(client: LinuxSandboxClient | null, workspaceId:void load(freshOnOpen);}, [load, freshOnOpen, workspaceId]);+ useEffect(() => {+ if (boxFor.current === workspaceId) reportSandboxFallback(workspaceId, box);+ }, [box, workspaceId]);+// While it moves: every second for a minute, then every 3 s.const moving = linuxSandboxMoving(box);useEffect(() => {@@ -239,7 +280,10 @@ export function useLinuxSandbox(client: LinuxSandboxClient | null, workspaceId:try {const result = await act();if (sequence.current !== startedAt) return;- if (result) setBox(result);+ if (result) {+ boxFor.current = workspaceId;+ setBox(result);+ }} catch {if (sequence.current !== startedAt) return;setProblem({ message: failure, retry: again });diff --git a/apps/app/src/react-app/domains/settings/pages/general-view.tsx b/apps/app/src/react-app/domains/settings/pages/general-view.tsxindex f9c05cd3..84ad59df 100644--- a/apps/app/src/react-app/domains/settings/pages/general-view.tsx+++ b/apps/app/src/react-app/domains/settings/pages/general-view.tsx@@ -28,6 +28,7 @@ import {omnirushAccountStatus,} from "../../../../app/lib/desktop";import type { OmniRushRuntimeApprovals } from "../../../../app/lib/omnirush-server";+import { captureAnalyticsEvent, resetAnalyticsAccount, syncAnalyticsAccount } from "../../../../app/lib/analytics";import { omnirushUsageSummary } from "../../../../app/lib/omnirush-usage";import { isElectronRuntime } from "../../../../app/utils";import {@@ -296,7 +297,10 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {useEffect(() => {if (!isElectronRuntime()) return;- void omnirushAccountStatus().then(setAccount).catch(() => setAccount({ connected: false, gatewayConfigured: false }));+ void omnirushAccountStatus().then((next) => {+ setAccount(next);+ syncAnalyticsAccount(next);+ }).catch(() => setAccount({ connected: false, gatewayConfigured: false }));}, []);async function connectAccount() {@@ -304,7 +308,14 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {setAccountMessage("Approve the device link in your browser…");try {await omnirushAccountConnect();- setAccount(await omnirushAccountStatus());+ captureAnalyticsEvent("device_approved", { method: "device_link" });+ const next = await omnirushAccountStatus();+ setAccount(next);+ if (next.connected) {+ // Identify first so the sign-in itself is linked to the account.+ syncAnalyticsAccount(next);+ captureAnalyticsEvent("sign_in_completed", { method: "device_link" });+ }setAccountMessage("Account connected. omnirush.ai models are ready.");} catch (error) {setAccountMessage(error instanceof Error ? error.message : "The account could not be connected.");@@ -320,6 +331,7 @@ export function GeneralSettingsView(props: GeneralSettingsViewProps) {const server = account?.gatewayHost ?? null;try {const result = await omnirushAccountSignOut();+ resetAnalyticsAccount();const next = await omnirushAccountStatus().catch(() => null);setAccount(next ?? { connected: false, gatewayConfigured: account?.gatewayConfigured ?? false });setAccountMessage(accountSignOutMessage(result, server));diff --git a/apps/app/src/react-app/domains/settings/pages/preferences-view.tsx b/apps/app/src/react-app/domains/settings/pages/preferences-view.tsxindex 731fc0b3..50c4a7d0 100644--- a/apps/app/src/react-app/domains/settings/pages/preferences-view.tsx+++ b/apps/app/src/react-app/domains/settings/pages/preferences-view.tsx@@ -38,8 +38,6 @@ export type PreferencesViewProps = {autoCompactContext: boolean;autoCompactContextBusy: boolean;onToggleAutoCompactContext: () => void;- analyticsEnabled: boolean;- onToggleAnalytics: () => void;desktopNotifications: DesktopNotificationPreference;onDesktopNotificationsChange: (value: DesktopNotificationPreference) => void;/** The server whose sub-agent model setting the Model section shows; hidden without one. */@@ -150,27 +148,6 @@ export function PreferencesView(props: PreferencesViewProps) {<DesktopIntegrationSection />- <LayoutSection>- <LayoutSectionHeader>- <LayoutSectionTitle>{t("settings.privacy_title")}</LayoutSectionTitle>- <LayoutSectionDescription>{t("settings.privacy_section_desc")}</LayoutSectionDescription>- </LayoutSectionHeader>-- <LayoutSectionItem>- <LayoutSectionItemHeader>- <LayoutSectionItemTitle>{t("settings.analytics_toggle")}</LayoutSectionItemTitle>- <LayoutSectionItemDescription>{t("settings.analytics_toggle_desc")}</LayoutSectionItemDescription>- <LayoutSectionItemHeaderActions>- <Switch- aria-label={t("settings.analytics_toggle")}- checked={props.analyticsEnabled}- disabled={props.busy}- onCheckedChange={props.onToggleAnalytics}- />- </LayoutSectionItemHeaderActions>- </LayoutSectionItemHeader>- </LayoutSectionItem>- </LayoutSection></LayoutStack>);diff --git a/apps/app/src/react-app/kernel/local-provider.tsx b/apps/app/src/react-app/kernel/local-provider.tsxindex 94eda9b7..40915a1b 100644--- a/apps/app/src/react-app/kernel/local-provider.tsx+++ b/apps/app/src/react-app/kernel/local-provider.tsx@@ -11,8 +11,6 @@ import {} from "react";import { MODEL_PREF_KEY, THINKING_PREF_KEY } from "../../app/constants";-import { desktopBridge } from "../../app/lib/desktop";-import { isElectronRuntime } from "../../app/lib/runtime-env";import { coerceReleaseChannel } from "../../app/lib/release-channels";import type { ModelRef, ReleaseChannel, SettingsTab, View } from "../../app/types";import {@@ -58,11 +56,6 @@ export type LocalPreferences = {* workspace list is empty, the app redirects to /welcome.*/hasCompletedOnboarding: boolean;- /**- * Anonymous product analytics (PostHog). Only sent when the build sets a- * PostHog key; opt-out in Settings -> Preferences. Never includes message content.- */- analyticsEnabled: boolean;/*** Native OS notifications from the desktop app. Off by default so upgrading* users are not surprised by system popups.@@ -92,7 +85,6 @@ const INITIAL_PREFS: LocalPreferences = {releaseChannel: "stable",featureFlags: { microsandboxCreateSandbox: true, workspaceRunMode: false },hasCompletedOnboarding: false,- analyticsEnabled: true,desktopNotifications: DEFAULT_DESKTOP_NOTIFICATION_PREFERENCE,};@@ -171,13 +163,6 @@ export function LocalProvider({ children }: LocalProviderProps) {writePersisted(LOCAL_PREFERENCES_KEY, prefs);}, [prefs]);- // Desktop error reports (apps/desktop/electron/sentry.mjs) follow the same- // "Share anonymous usage" setting as product analytics.- useEffect(() => {- if (!isElectronRuntime()) return;- void desktopBridge.desktopSentrySetConsent(prefs.analyticsEnabled).catch(() => undefined);- }, [prefs.analyticsEnabled]);-useEffect(() => {const updateDefaultModel = () => {const model = readStoredDefaultModel();diff --git a/apps/app/src/react-app/shell/settings-route.tsx b/apps/app/src/react-app/shell/settings-route.tsxindex 36f25a0e..e2f537da 100644--- a/apps/app/src/react-app/shell/settings-route.tsx+++ b/apps/app/src/react-app/shell/settings-route.tsx@@ -2362,10 +2362,6 @@ function SettingsRouteContent(props: SettingsSurfaceProps = {}) {autoCompactContext={autoCompactContext}autoCompactContextBusy={autoCompactContextBusy}onToggleAutoCompactContext={toggleAutoCompactContext}- analyticsEnabled={local.prefs.analyticsEnabled}- onToggleAnalytics={() => {- local.setPrefs((previous) => ({ ...previous, analyticsEnabled: !previous.analyticsEnabled }));- }}desktopNotifications={local.prefs.desktopNotifications}onDesktopNotificationsChange={(desktopNotifications) => {local.setPrefs((previous) => ({ ...previous, desktopNotifications }));diff --git a/apps/app/src/react-app/shell/welcome-route.tsx b/apps/app/src/react-app/shell/welcome-route.tsxindex dcc200c6..3fd2f1c9 100644--- a/apps/app/src/react-app/shell/welcome-route.tsx+++ b/apps/app/src/react-app/shell/welcome-route.tsx@@ -26,7 +26,7 @@ import { useDenAuth } from "../domains/cloud/den-auth-provider";import { useDenControlPlaneConfigured } from "../domains/cloud/use-den-control-plane-configured";import { JoinOrganizationDialog } from "../domains/cloud/join-organization-dialog";import { resolveOmniRushConnection } from "./omnirush-connection";-import { captureAnalyticsEvent } from "../../app/lib/analytics";+import { attributionSurveyProperties, captureAnalyticsEvent } from "../../app/lib/analytics";import { noteNewBuildathonProject } from "../../app/lib/buildathon";import { buildOmniRushWorkspaceBaseUrl, createOmniRushServerClient } from "../../app/lib/omnirush-server";import { buildDenAuthUrl, DEFAULT_DEN_BASE_URL, readDenSettings } from "../../app/lib/den";@@ -373,13 +373,8 @@ export function WelcomeRoute() {const handleAttributionSubmit = useCallback((source: AttributionSource, aiPrompt?: string) => {- const prompt = aiPrompt?.trim().slice(0, 500) ?? "";- captureAnalyticsEvent("attribution_survey_submitted", {- source,- // User-volunteered survey answer (not session content); see survey UI.- ai_prompt: prompt || null,- ai_prompt_length: prompt.length,- });+ // The fixed choice and how long the optional answer was; never its text.+ captureAnalyticsEvent("attribution_survey_submitted", attributionSurveyProperties(source, aiPrompt));finishOnboarding();},[finishOnboarding],diff --git a/apps/app/tests/analytics.test.ts b/apps/app/tests/analytics.test.tsnew file mode 100644index 00000000..6f019125--- /dev/null+++ b/apps/app/tests/analytics.test.ts@@ -0,0 +1,230 @@+import { afterEach, beforeEach, describe, expect, test } from "bun:test";+import { readFileSync } from "node:fs";+import path from "node:path";++class MemoryStorage {+ private values = new Map<string, string>();+ getItem(key: string) { return this.values.has(key) ? this.values.get(key)! : null; }+ setItem(key: string, value: string) { this.values.set(key, String(value)); }+ removeItem(key: string) { this.values.delete(key); }+ clear() { this.values.clear(); }+}++const storage = new MemoryStorage();+const recorded: Array<{ name: string; data: unknown }> = [];+Object.defineProperty(globalThis, "window", {+ configurable: true,+ value: {+ localStorage: storage,+ addEventListener: () => undefined,+ __omnirush: { record: (name: string, data: unknown) => recorded.push({ name, data }) },+ },+});++const analytics = await import("../src/app/lib/analytics");+const { gatewayRefusalEvent } = await import("../src/app/lib/gateway-refusal");+const { reportSandboxFallback, sandboxFallbackProperties } = await import("../src/react-app/domains/settings/linux-sandbox");++const ACCOUNT = "3f2504e0-4f89-11d3-9a0c-0305e82c3301";+const OTHER = "9b2c1d1e-0000-4000-8000-000000000001";+const NEW_KEY = "phc_uKRzMW7rNe68NKBxCjAwBvqzpxiRj77dGDY7WN3uGoMX";++type Sent = { url: string; body: { api_key: string; batch: Array<{ event: string; distinct_id: string; properties: Record<string, unknown> }> } };+let sent: Sent[] = [];+const realFetch = globalThis.fetch;++beforeEach(() => {+ storage.clear();+ recorded.length = 0;+ sent = [];+ analytics.disposeAnalytics();+ analytics.configureAnalyticsForTests({ key: NEW_KEY, host: "http://127.0.0.1:9/", appVersion: "3.5.8" });+ globalThis.fetch = (async (url: string, init?: RequestInit) => {+ sent.push({ url: String(url), body: JSON.parse(String(init?.body)) });+ return new Response("{}");+ }) as unknown as typeof fetch;+});++afterEach(() => {+ globalThis.fetch = realFetch;+});++async function flushed() {+ await analytics.flushAnalytics();+ return sent.flatMap((request) => request.body.batch);+}++describe("analytics identity", () => {+ test("events before sign-in use the random device id", async () => {+ analytics.captureAnalyticsEvent("app_opened", {});+ const [event] = await flushed();+ expect(event.distinct_id).toBe(analytics.getAnalyticsDistinctId());+ expect(event.properties).toMatchObject({ app_version: "3.5.8" });+ expect(Object.keys(event.properties)).toEqual(expect.arrayContaining(["app_version", "platform", "os"]));+ expect(sent[0].url).toBe("http://127.0.0.1:9/batch/");+ expect(sent[0].body.api_key).toBe(NEW_KEY);+ });++ test("identify sends $identify once with the account id and links later events", async () => {+ const anonymous = analytics.getAnalyticsDistinctId();+ expect(analytics.identifyAnalyticsAccount(ACCOUNT)).toBe(true);+ expect(analytics.identifyAnalyticsAccount(ACCOUNT)).toBe(false);+ analytics.captureAnalyticsEvent("sign_in_completed", { method: "device_link" });+ const batch = await flushed();+ expect(batch.map((event) => event.event)).toEqual(["$identify", "sign_in_completed"]);+ expect(batch[0].distinct_id).toBe(ACCOUNT);+ expect(batch[0].properties.$anon_distinct_id).toBe(anonymous);+ expect(batch[1].distinct_id).toBe(ACCOUNT);+ expect(JSON.stringify(batch)).not.toContain("@");+ });++ test("identify refuses anything but a UUID (never an e-mail or name)", () => {+ expect(analytics.identifyAnalyticsAccount("[email protected]")).toBe(false);+ expect(analytics.identifyAnalyticsAccount("Person")).toBe(false);+ expect(analytics.identifyAnalyticsAccount(null)).toBe(false);+ expect(analytics.getAnalyticsAccountId()).toBeNull();+ });++ test("reset on sign-out forgets the account and starts a new device id", async () => {+ analytics.identifyAnalyticsAccount(ACCOUNT);+ const before = analytics.getAnalyticsDistinctId();+ expect(analytics.resetAnalyticsAccount()).toBe(true);+ expect(analytics.getAnalyticsAccountId()).toBeNull();+ expect(analytics.getAnalyticsDistinctId()).not.toBe(before);+ analytics.captureAnalyticsEvent("app_opened", {});+ const batch = await flushed();+ expect(batch.at(-1)!.distinct_id).toBe(analytics.getAnalyticsDistinctId());+ expect(recorded.some((entry) => entry.name === "analytics.$reset")).toBe(true);+ });++ test("syncAnalyticsAccount follows the account status", () => {+ analytics.syncAnalyticsAccount({ connected: true, accountId: ACCOUNT });+ expect(analytics.getAnalyticsAccountId()).toBe(ACCOUNT);+ analytics.syncAnalyticsAccount({ connected: true, accountId: null });+ expect(analytics.getAnalyticsAccountId()).toBe(ACCOUNT);+ analytics.syncAnalyticsAccount({ connected: true, accountId: OTHER });+ expect(analytics.getAnalyticsAccountId()).toBe(OTHER);+ analytics.syncAnalyticsAccount({ connected: false });+ expect(analytics.getAnalyticsAccountId()).toBeNull();+ });++ test("a blank key sends nothing, but the inspector still records", async () => {+ analytics.configureAnalyticsForTests({ key: " " });+ analytics.captureAnalyticsEvent("app_opened", {});+ analytics.identifyAnalyticsAccount(ACCOUNT);+ await analytics.flushAnalytics();+ expect(sent).toEqual([]);+ expect(analytics.isAnalyticsActive()).toBe(false);+ expect(recorded.map((entry) => entry.name)).toContain("analytics.app_opened");+ });++ test("always on when a key is set: the old preference no longer turns it off", async () => {+ storage.setItem("omnirush.preferences", JSON.stringify({ analyticsEnabled: false }));+ analytics.captureAnalyticsEvent("app_opened", {});+ expect((await flushed()).map((event) => event.event)).toEqual(["app_opened"]);+ });+});++describe("first run", () => {+ test("once for a new profile", async () => {+ expect(analytics.captureFirstRunOnce(false)).toBe(true);+ expect(analytics.captureFirstRunOnce(false)).toBe(false);+ expect((await flushed()).map((event) => event.event)).toEqual(["first_run"]);+ });++ test("an upgraded profile is marked without an event", async () => {+ expect(analytics.captureFirstRunOnce(true)).toBe(false);+ expect(analytics.captureFirstRunOnce(false)).toBe(false);+ expect(await flushed()).toEqual([]);+ });+});++describe("onboarding survey", () => {+ test("never sends the free-text answer", () => {+ const properties = analytics.attributionSurveyProperties("ai_assistant", " best open source agent app ");+ expect(properties).toEqual({ source: "ai_assistant", ai_prompt_length: 26 });+ expect(JSON.stringify(properties)).not.toContain("open source");+ expect(analytics.attributionSurveyProperties("search")).toEqual({ source: "search", ai_prompt_length: 0 });+ });+});++describe("refusals shown", () => {+ test("request policy", () => {+ expect(gatewayRefusalEvent({ title: "OmniRush can't help with this request. Free model access isn't for attacking systems.", technicalDetails: "" }))+ .toEqual({ event: "policy_refusal_shown", properties: { reason: "request_policy" } });+ expect(gatewayRefusalEvent({ title: "x", technicalDetails: "Code: request_policy_refused" })?.event).toBe("policy_refusal_shown");+ });++ test("limits", () => {+ expect(gatewayRefusalEvent({ title: "omnirush.ai: today's tokens are used up. They refill at 5:30 AM (in 3 h).", technicalDetails: "" })?.properties)+ .toEqual({ limit_type: "tokens", scope: "day" });+ expect(gatewayRefusalEvent({ title: "omnirush.ai: this week's cap is reached. It resets Monday.", technicalDetails: "" })?.properties.scope).toBe("week");+ expect(gatewayRefusalEvent({ title: "omnirush.ai: you have no tokens left.", technicalDetails: "" })?.properties.scope).toBe("empty");+ expect(gatewayRefusalEvent({ title: "x", technicalDetails: "Code: daily_grant_exhausted" })?.properties.scope).toBe("unknown");+ expect(gatewayRefusalEvent({ title: "x", technicalDetails: "session_quality_cap" })?.properties.limit_type).toBe("session_cap");+ });++ test("other errors are not refusals", () => {+ expect(gatewayRefusalEvent({ title: "Provider did not respond in time", technicalDetails: "Status: 504" })).toBeNull();+ expect(gatewayRefusalEvent(null)).toBeNull();+ });+});++describe("sandbox fallback", () => {+ const box = (overrides: Record<string, unknown>) => ({+ mode: "on", on: true, state: "ready", runtime: { ok: true, name: "docker", flavor: null, version: "27", reason: null },+ backend: { id: "docker", label: "Docker", version: "27", flavor: null, why: null, alternatives: [], allowed: null },+ backendSetting: { value: "auto", source: "auto", choices: [] }, notice: null, error: "/home/someone/secret path",+ ...overrides,+ }) as never;++ test("reasons, coarse properties only", () => {+ expect(sandboxFallbackProperties(box({ state: "failed" }))).toEqual({ reason: "start_failed", sandbox_mode: "on", backend: "docker", backend_setting: "auto" });+ expect(sandboxFallbackProperties(box({ state: "unavailable" }))?.reason).toBe("not_running");+ expect(sandboxFallbackProperties(box({ state: "unavailable", runtime: { ok: false }, backend: null }))?.reason).toBe("no_backend");+ expect(sandboxFallbackProperties(box({ state: "ready" }))).toBeNull();+ expect(sandboxFallbackProperties(box({ state: "starting" }))).toBeNull();+ expect(sandboxFallbackProperties(box({ on: false, state: "off" }))).toBeNull();+ expect(sandboxFallbackProperties(box({ state: "unavailable", backendSetting: { value: "native", source: "setting", choices: [] } }))).toBeNull();+ expect(JSON.stringify(sandboxFallbackProperties(box({ state: "failed" })))).not.toContain("/home");+ });++ test("once per project and reason", async () => {+ expect(reportSandboxFallback("ws-1", box({ state: "failed" }))).toBe(true);+ expect(reportSandboxFallback("ws-1", box({ state: "failed" }))).toBe(false);+ expect(reportSandboxFallback("ws-2", box({ state: "failed" }))).toBe(true);+ expect(reportSandboxFallback(null, box({ state: "failed" }))).toBe(false);+ expect((await flushed()).map((event) => event.event)).toEqual(["sandbox_fallback", "sandbox_fallback"]);+ });+});++describe("call sites", () => {+ const src = (file: string) => readFileSync(path.join(import.meta.dir, "../src", file), "utf8");++ test("sign-in, device approval, sign-out", () => {+ const view = src("react-app/domains/settings/pages/general-view.tsx");+ expect(view).toContain('captureAnalyticsEvent("device_approved"');+ expect(view).toContain('captureAnalyticsEvent("sign_in_completed"');+ expect(view).toMatch(/omnirushAccountSignOut\(\);\n\s+resetAnalyticsAccount\(\);/);+ expect(src("app/lib/quality.ts")).toContain("syncAnalyticsAccount(status)");+ });++ test("refusals on session errors, sandbox fallback on status reads", () => {+ expect(src("react-app/domains/session/sync/session-sync.ts")).toContain("gatewayRefusalEvent(errorPresentation)");+ expect(src("react-app/domains/settings/linux-sandbox.ts")).toContain("reportSandboxFallback(workspaceId, box)");+ });++ test("the opt-out toggle and preference are gone", () => {+ expect(src("react-app/domains/settings/pages/preferences-view.tsx")).not.toMatch(/analytics_toggle|analyticsEnabled/);+ expect(src("react-app/kernel/local-provider.tsx")).not.toContain("analyticsEnabled");+ expect(src("react-app/shell/settings-route.tsx")).not.toContain("analyticsEnabled");+ expect(src("app/lib/analytics.ts")).not.toContain("isAnalyticsEnabled");+ expect(src("i18n/locales/en.ts")).not.toContain("Share anonymous usage data");+ });++ test("the survey event has no free text", () => {+ const welcome = src("react-app/shell/welcome-route.tsx");+ expect(welcome).not.toMatch(/ai_prompt:/);+ expect(welcome).toContain("attributionSurveyProperties(source, aiPrompt)");+ });+});diff --git a/apps/desktop/electron/omnirush-account.mjs b/apps/desktop/electron/omnirush-account.mjsindex 59ddb62d..b25b148f 100644--- a/apps/desktop/electron/omnirush-account.mjs+++ b/apps/desktop/electron/omnirush-account.mjs@@ -233,12 +233,19 @@ function accountUsage(usage) {};}+/** The account's opaque id (a UUID) from /device/me, or null. */+function accountUuid(value) {+ const id = typeof value === "string" ? value.trim().toLowerCase() : "";+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(id) ? id : null;+}+function accountProfile(value) {if (!value || typeof value !== "object") return null;const email = normalizeCredential(value.email);if (!email) return null;const usage = accountUsage(value.usage);return {+ accountId: accountUuid(value.id),email,displayName: normalizeCredential(value.display_name) ?? displayNameFromEmail(email),status: normalizeCredential(value.status),@@ -1105,6 +1112,7 @@ export function createDesktopOmniRushAccountStore({gatewayConfigured,...server,...storage,+ accountId: profile?.accountId ?? null,email: profile?.email ?? null,displayName: profile?.displayName ?? null,accountStatus: profile?.status ?? null,diff --git a/apps/desktop/electron/omnirush-account.test.mjs b/apps/desktop/electron/omnirush-account.test.mjsindex eddb714e..1a78c9d0 100644--- a/apps/desktop/electron/omnirush-account.test.mjs+++ b/apps/desktop/electron/omnirush-account.test.mjs@@ -93,6 +93,27 @@ test("device authorization polls, encrypts, and restores the account", async ()]);});+test("status carries the account's opaque id (for analytics), never derived from the e-mail", async () => {+ const id = "3F2504E0-4F89-11D3-9A0C-0305E82C3301";+ let body = { id, email: "[email protected]", status: "active" };+ const options = await storeOptions({+ fetchImpl: async (url) => {+ if (String(url).endsWith("/device/me")) return Response.json(body);+ if (String(url).endsWith("/device/authorize")) {+ return Response.json({ device_code: "d", user_code: "U", verification_uri_complete: "http://localhost:5175/console?code=U", interval: 0, expires_in: 60 });+ }+ return Response.json({ gateway_url: "http://localhost:8090/omnirush/v1", access_token: "access-token", refresh_token: "refresh-token" });+ },+ });+ const store = createDesktopOmniRushAccountStore(options);+ await store.authorize({ gatewayUrl: undefined, deviceName: "Test", openVerification: async () => undefined });+ assert.equal((await store.status()).accountId, id.toLowerCase());+ body = { id: "[email protected]", email: "[email protected]", status: "active" };+ assert.equal((await store.status()).accountId, null);+ body = { email: "[email protected]", status: "active" };+ assert.equal((await store.status()).accountId, null);+});+async function authorizeOrigin(env) {const requested = [];const options = await storeOptions({diff --git a/apps/desktop/electron/sentry.mjs b/apps/desktop/electron/sentry.mjsindex c207a75b..3f5c6e77 100644--- a/apps/desktop/electron/sentry.mjs+++ b/apps/desktop/electron/sentry.mjs@@ -5,8 +5,8 @@ import { fileURLToPath } from "node:url";let sentry = null;let initialized = false;-// Reports leave only while signed in to a Den (session) and while the user's-// "Share anonymous usage" setting is on (consent, reported by the renderer).+// Reports leave only while signed in to a Den (session) and after consent+// (desktopSentrySetConsent); the app grants none, so none leave.let sessionActive = false;let consentGranted = false;let telemetryActive = false;@@ -217,7 +217,7 @@ export function setOmniRushSentrySession(input) {}/**- * The renderer's "Share anonymous usage" setting (analyticsEnabled).+ * Consent for desktop error reports (the app no longer grants it).* @param {boolean} enabled*/export function setOmniRushSentryConsent(enabled) {diff --git a/docs/enterprise/outbound-access.json b/docs/enterprise/outbound-access.jsonindex afc910f4..e7ce4bcc 100644--- a/docs/enterprise/outbound-access.json+++ b/docs/enterprise/outbound-access.json@@ -274,10 +274,10 @@"host": "us.i.posthog.com","kind": "fetched","components": ["renderer"],- "purpose": "Optional product analytics endpoint, used only when a build sets VITE_OMNIRUSH_POSTHOG_KEY and analytics are enabled. Release builds set no key.",+ "purpose": "Product analytics endpoint (PostHog project of the OmniRush desktop app). Release builds set VITE_OMNIRUSH_POSTHOG_KEY; a build without a key sends nothing.","requirement": "optional","blockedEffect": "Analytics events are dropped silently; user-facing app behavior is unaffected.",- "override": "VITE_OMNIRUSH_POSTHOG_HOST; users can disable analytics with the analyticsEnabled preference"+ "override": "VITE_OMNIRUSH_POSTHOG_HOST; build without VITE_OMNIRUSH_POSTHOG_KEY to send nothing"},{"host": "www.google.com",diff --git a/packages/docs/start-here/outbound-network-access.mdx b/packages/docs/start-here/outbound-network-access.mdxindex 31a1c514..4de5419a 100644--- a/packages/docs/start-here/outbound-network-access.mdx+++ b/packages/docs/start-here/outbound-network-access.mdx@@ -38,7 +38,7 @@ Common misses:| Your model catalog mirror, if configured | Optional | Model catalog passed to the engine as `OPENCODE_MODELS_URL`. There is no default catalog. | The engine keeps the model list bundled with it. || `cdn.simpleicons.org` | Optional | Provider icons when no local icon exists. | Some icons are missing. || `www.google.com` | Optional | Favicon image service and embedded browser new-tab page. | Favicons or the browser panel new tab may not load. |-| `us.i.posthog.com` | Optional | Product analytics, only when a build sets `VITE_OMNIRUSH_POSTHOG_KEY` (release builds set none). | Analytics are dropped silently. |+| `us.i.posthog.com` | Optional | Product analytics of the desktop app (release builds set `VITE_OMNIRUSH_POSTHOG_KEY`; a build without it sends nothing). | Analytics are dropped silently. || `discord.gg`, `ollama.com`, `opencode.ai`, `linear.app`, `mail.google.com` | Optional or link-only | Docs, feedback, community, provider help, local model links, sample links, and generated Gmail links. | Links do not open; core app behavior is unaffected. |`code.claude.com` and `schemas.agentskills.io` appear in source or schema metadata. They are findable in the manifest, but OmniRush.ai does not fetch them for normal runtime behavior.diff --git a/packages/types/src/desktop-ipc.ts b/packages/types/src/desktop-ipc.tsindex 429bc436..bb8bcba3 100644--- a/packages/types/src/desktop-ipc.ts+++ b/packages/types/src/desktop-ipc.ts@@ -511,6 +511,8 @@ export type OmniRushAccountStatus = {connected: boolean;gatewayConfigured: boolean;reauthorizationRequired?: boolean;+ /** The account's opaque id (UUID) from /device/me; product analytics are linked to it. */+ accountId?: string | null;email?: string | null;displayName?: string | null;accountStatus?: string | null;@@ -899,7 +901,7 @@ export type DesktopCommandMap = {result: { enabled: boolean };};desktopSentryClearSession: { args: []; result: { enabled: boolean } };- /** The "Share anonymous usage" setting; desktop error reports follow it. */+ /** Consent for desktop error reports; the app no longer grants it. */desktopSentrySetConsent: { args: [enabled: boolean]; result: { enabled: boolean } };desktopIntegrationStatus: { args: []; result: DesktopIntegrationStatus };desktopIntegrationInstall: {