Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Analytics: the desktop app's pages never sent an event; one id per install and a daily app_active from the app itself (#8049)

Milind Soni3ed8c1b0c18e
diff --git a/apps/docs/content/docs/security/analytics.mdx b/apps/docs/content/docs/security/analytics.mdx
index acac39f5bc..3e41b936b7 100644
--- a/apps/docs/content/docs/security/analytics.mdx
+++ b/apps/docs/content/docs/security/analytics.mdx
@@ -12,6 +12,8 @@ sent.
- `posthog-js` loads only while the switch is on. With the switch off, the library is never downloaded and nothing is
sent.
+- A development build of the desktop app, and the app under its own automated tests, send nothing, from the app or from
+ any page its window shows.
- Autocapture, pageviews, surveys and feature flags are off. Events come only from the calls listed on this page, and
switching analytics back on sends no event of its own.
- Every event carries `app_version` (for example `0.1.112`), `surface`: `local` for the desktop app's own window,
@@ -19,13 +21,17 @@ sent.
`desktop` for a page the desktop app shows, `browser` for a page a browser shows.
- PostHog adds its standard device facts to every event: operating system, browser and its version, device type,
screen and window size, language and time zone. Like any server, PostHog sees the IP address a request comes from.
-- Events are tied to a random id that PostHog keeps in the page's storage. Nothing ties them to you: the app never sends
- your email or your name with them.
+- Events are tied to a random id. A page in a browser, and a server's page the desktop app shows, keep one that PostHog
+ makes in that page's storage. The desktop app makes one for the install and keeps it in its own settings file: the
+ app's own events and this computer's page send under it, and no server's page is ever told it. It is made from nothing
+ of your computer or of you. Nothing ties any of these ids to you: the app never sends your email or your name with
+ them.
## Turning it off
**Settings → General → Usage analytics.** When it is off, nothing loads and nothing is sent: no events, no daily
-snapshot, none of the snapshot's requests, and none of the desktop app's launch events.
+snapshot, none of the snapshot's requests, and none of the desktop app's own events. Turning it off in the desktop app
+also deletes the install's id; turning it on again makes a new one.
The desktop app keeps the switch for this computer's page itself, so it holds whichever port the app serves that page on
(it moves to another when its usual one is taken). It is read before anything loads, and before any email is tied to
@@ -132,7 +138,7 @@ use their own Boat key, and how many bots run on cloud computers, without sendin
| --- | --- | --- |
| `app_first_open` | The first time this app page starts with analytics on | `platform`: `desktop`, `browser` |
| `app_opened` | Each time this app page starts with analytics on | `platform`: `desktop`, `browser` |
-| `app_active` | Once a day you use the app: when this app page starts, comes into view or is focused, or when a check every ten minutes finds a new day while the page is in view and focused. At most once per day by your computer's date for each app page, and never while the page is hidden | `platform`: `desktop`, `browser`; `mode`: `simple`, `advanced`, the look this app page is in when it counts the day |
+| `app_active` | Once a day you use the app: when this app page starts, comes into view or is focused, or when a check every ten minutes finds a new day while the page is in view and focused. At most once per day by your computer's date for each app page, and never while the page is hidden. The desktop app itself sends it too, at most once per day for the install and only while one of its windows is in view (never from a start at login out of sight, or while it waits in the tray), under the same id as this computer's page, so the install counts once | `platform`: `desktop`, `browser`; `mode`: `simple`, `advanced`, the look this app page is in when it counts the day. From the desktop app itself: `platform`: `desktop`, `surface`: `main`, `app_version` and the operating system, nothing else |
| `onboarding_step` | A first-run screen is shown | `step`: `meet`, `chief`; `replay`: true/false |
| `connect_ai` | Connecting an AI takes a step in a first-run flow: the first screen, its Connect an AI dialog, the one MausBot's chat opens, the one on the clean workspace's line, or a new Cloud's welcome. Never from Settings | `step`: `opened` (the flow asked for an AI, or found one already working), `dialog_opened` (the Connect an AI dialog opened), `chosen` (you picked an AI: its button, its setup or its row), `sign_in_started` (a sign-in to it began), `test_started`, `test_ok`, `test_failed` (the tiny test message through it), `later` (Set up later on the first screen, Skip on a Cloud's welcome); `place`: `meet`, `chat`, `home_line`, `cloud_welcome`; `engine`: engine, when one is named; `ai_ready`: true/false, with `opened`; `reason`: why the test failed, a test failure word, with `test_failed`, and with `opened` when the AI found had failed its last test; `seconds`: how long the test took, with `test_ok` and `test_failed` |
| `app_load` | This app page has its server, its data and its settings, or still waits for one of them half a minute after it started, or shows its error screen. Once per page start | `stage`: `ready`, `slow`, `error`; `seconds`: since the page started, with `ready`; `onboarded`: true/false, the first-run tour was finished, with `ready`; `waiting`: `server`, `data`, `settings`, with `slow` |
@@ -192,8 +198,9 @@ count.
- It follows the same switch. With the switch off, it sends nothing. While no choice has been made, it sends on the
computer's first launch, and on a later launch only when the launch before ran a version whose page keeps a switch
turned off in the page's own storage (0.1.113 or later), so that switch holds here too.
-- Each launch makes a random id that is kept nowhere and used for nothing else: it ties one launch's stages together,
- never two launches, never a page's events, never you. PostHog keeps no person for it.
+- Every stage is sent under the install's id (see What it is) and marked `telemetry`: `launch`, so a launch is never
+ counted as someone using the app. `launch_id`, a random id made for the launch and kept nowhere, ties one launch's
+ stages together. PostHog keeps no person for either.
- Only the packaged app sends, never a development build.
| Stage | When | Properties besides `stage` |
@@ -207,4 +214,5 @@ count.
| `page_crashed` | The window's page crashed | `reason`: `crashed`, `oom`, `killed`, `abnormal-exit`, `launch-failed`, `integrity-failure` |
Every stage also carries `ms` (milliseconds since the app started), `first_launch` (true/false), `updated` (true/false,
-the first launch of a new version), `app_version`, `platform`: `desktop`, `surface`: `main`, and the operating system.
+the first launch of a new version), `telemetry`: `launch`, `launch_id`, `app_version`, `platform`: `desktop`,
+`surface`: `main`, and the operating system.
diff --git a/docs/analytics.md b/docs/analytics.md
index 2170f29cff..8d623b2630 100644
--- a/docs/analytics.md
+++ b/docs/analytics.md
@@ -8,6 +8,8 @@ sent.
- `posthog-js` loads only while the switch is on. With the switch off, the library is never downloaded and nothing is
sent.
+- A development build of the desktop app, and the app under its own automated tests, send nothing, from the app or from
+ any page its window shows.
- Autocapture, pageviews, surveys and feature flags are off. Events come only from the calls listed on this page, and
switching analytics back on sends no event of its own.
- Every event carries `app_version` (for example `0.1.112`), `surface`: `local` for the desktop app's own window,
@@ -15,13 +17,17 @@ sent.
`desktop` for a page the desktop app shows, `browser` for a page a browser shows.
- PostHog adds its standard device facts to every event: operating system, browser and its version, device type,
screen and window size, language and time zone. Like any server, PostHog sees the IP address a request comes from.
-- Events are tied to a random id that PostHog keeps in the page's storage. Nothing ties them to you: the app never sends
- your email or your name with them.
+- Events are tied to a random id. A page in a browser, and a server's page the desktop app shows, keep one that PostHog
+ makes in that page's storage. The desktop app makes one for the install and keeps it in its own settings file: the
+ app's own events and this computer's page send under it, and no server's page is ever told it. It is made from nothing
+ of your computer or of you. Nothing ties any of these ids to you: the app never sends your email or your name with
+ them.
## Turning it off
**Settings → General → Usage analytics.** When it is off, nothing loads and nothing is sent: no events, no daily
-snapshot, none of the snapshot's requests, and none of the desktop app's launch events.
+snapshot, none of the snapshot's requests, and none of the desktop app's own events. Turning it off in the desktop app
+also deletes the install's id; turning it on again makes a new one.
The desktop app keeps the switch for this computer's page itself, so it holds whichever port the app serves that page on
(it moves to another when its usual one is taken). It is read before anything loads, and before any email is tied to
@@ -128,7 +134,7 @@ use their own Boat key, and how many bots run on cloud computers, without sendin
| --- | --- | --- |
| `app_first_open` | The first time this app page starts with analytics on | `platform`: `desktop`, `browser` |
| `app_opened` | Each time this app page starts with analytics on | `platform`: `desktop`, `browser` |
-| `app_active` | Once a day you use the app: when this app page starts, comes into view or is focused, or when a check every ten minutes finds a new day while the page is in view and focused. At most once per day by your computer's date for each app page, and never while the page is hidden | `platform`: `desktop`, `browser`; `mode`: `simple`, `advanced`, the look this app page is in when it counts the day |
+| `app_active` | Once a day you use the app: when this app page starts, comes into view or is focused, or when a check every ten minutes finds a new day while the page is in view and focused. At most once per day by your computer's date for each app page, and never while the page is hidden. The desktop app itself sends it too, at most once per day for the install and only while one of its windows is in view (never from a start at login out of sight, or while it waits in the tray), under the same id as this computer's page, so the install counts once | `platform`: `desktop`, `browser`; `mode`: `simple`, `advanced`, the look this app page is in when it counts the day. From the desktop app itself: `platform`: `desktop`, `surface`: `main`, `app_version` and the operating system, nothing else |
| `onboarding_step` | A first-run screen is shown | `step`: `meet`, `chief`; `replay`: true/false |
| `connect_ai` | Connecting an AI takes a step in a first-run flow: the first screen, its Connect an AI dialog, the one MausBot's chat opens, the one on the clean workspace's line, or a new Cloud's welcome. Never from Settings | `step`: `opened` (the flow asked for an AI, or found one already working), `dialog_opened` (the Connect an AI dialog opened), `chosen` (you picked an AI: its button, its setup or its row), `sign_in_started` (a sign-in to it began), `test_started`, `test_ok`, `test_failed` (the tiny test message through it), `later` (Set up later on the first screen, Skip on a Cloud's welcome); `place`: `meet`, `chat`, `home_line`, `cloud_welcome`; `engine`: engine, when one is named; `ai_ready`: true/false, with `opened`; `reason`: why the test failed, a test failure word, with `test_failed`, and with `opened` when the AI found had failed its last test; `seconds`: how long the test took, with `test_ok` and `test_failed` |
| `app_load` | This app page has its server, its data and its settings, or still waits for one of them half a minute after it started, or shows its error screen. Once per page start | `stage`: `ready`, `slow`, `error`; `seconds`: since the page started, with `ready`; `onboarded`: true/false, the first-run tour was finished, with `ready`; `waiting`: `server`, `data`, `settings`, with `slow` |
@@ -188,8 +194,9 @@ count.
- It follows the same switch. With the switch off, it sends nothing. While no choice has been made, it sends on the
computer's first launch, and on a later launch only when the launch before ran a version whose page keeps a switch
turned off in the page's own storage (0.1.113 or later), so that switch holds here too.
-- Each launch makes a random id that is kept nowhere and used for nothing else: it ties one launch's stages together,
- never two launches, never a page's events, never you. PostHog keeps no person for it.
+- Every stage is sent under the install's id (see What it is) and marked `telemetry`: `launch`, so a launch is never
+ counted as someone using the app. `launch_id`, a random id made for the launch and kept nowhere, ties one launch's
+ stages together. PostHog keeps no person for either.
- Only the packaged app sends, never a development build.
| Stage | When | Properties besides `stage` |
@@ -203,4 +210,5 @@ count.
| `page_crashed` | The window's page crashed | `reason`: `crashed`, `oom`, `killed`, `abnormal-exit`, `launch-failed`, `integrity-failure` |
Every stage also carries `ms` (milliseconds since the app started), `first_launch` (true/false), `updated` (true/false,
-the first launch of a new version), `app_version`, `platform`: `desktop`, `surface`: `main`, and the operating system.
+the first launch of a new version), `telemetry`: `launch`, `launch_id`, `app_version`, `platform`: `desktop`,
+`surface`: `main`, and the operating system.
diff --git a/electron/bridge-contract.json b/electron/bridge-contract.json
index 639cd1f3b9..475b6ed5b0 100644
--- a/electron/bridge-contract.json
+++ b/electron/bridge-contract.json
@@ -120,6 +120,7 @@
"copyText",
"desktopAnalytics",
"desktopAnalytics.enabled",
+ "desktopAnalytics.id",
"desktopAnalytics.set",
"desktopLanguage",
"desktopLanguage.choice",
diff --git a/electron/desktop-active.mjs b/electron/desktop-active.mjs
new file mode 100644
index 0000000000..a067da729b
--- /dev/null
+++ b/electron/desktop-active.mjs
@@ -0,0 +1,58 @@
+// The desktop app's own count of a day it was used: one `app_active` event per install per local day, sent by main, so
+// the count holds whatever its pages do. It is the same event, under the same id, that this computer's page sends, so a
+// chart counts one install once a day whichever of the two reached it. It honours the same Usage analytics switch.
+import { desktopOs, sendDesktopEvent } from "./launch-analytics.mjs";
+
+const CHECK_MS = 10 * 60_000;
+
+/** The computer's own calendar day, as the app's pages write it. */
+export function localDay(date) {
+ const pad = part => String(part).padStart(2, "0");
+ return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
+}
+
+/**
+ * `check()` sends the day's event when a window of the app is in view (`visible()`), this install may send
+ * (`installId()` is its id, null with the switch off or in a run that sends nothing) and the day kept in `day` is not
+ * today. The day is kept once the event was taken, so a send that failed is tried again at the next check, and a
+ * restart on the same day sends nothing more. Security: nothing is read, made or sent while no window is in view.
+ */
+export function createDesktopActive({ fetch, installId, day, visible, version, platform, now = Date.now, today = () => localDay(new Date(now())) }) {
+ let sending = null;
+ return {
+ check() {
+ if (!visible()) return;
+ const id = installId();
+ if (!id) return;
+ const date = today();
+ if (sending === date || day.read() === date) return;
+ sending = date;
+ const properties = { app_version: version, platform: "desktop", surface: "main", $os: desktopOs(platform) };
+ void sendDesktopEvent(fetch, { event: "app_active", id, at: now(), properties }).then(taken => {
+ // Security: a switch turned off while the event was on its way keeps no day.
+ if (taken && installId()) day.write(date);
+ if (sending === date) sending = null;
+ });
+ },
+ };
+}
+
+/** A window the person can see: shown, not minimized, not put away in the tray. */
+export const inView = windows => windows.some(win => !win.isDestroyed() && win.isVisible() && !win.isMinimized());
+
+/**
+ * This app's count: checked when a window is shown, restored or focused, and every ten minutes, which is how a day that
+ * changes while the app stays open is counted. A start at login out of sight shows no window, so it counts nothing.
+ * `windows()`: the app's own windows. `launch`: this launch's analytics, which say whether this install may send.
+ */
+export function installDesktopActive({ app, session, prefs, windows, launch, setInterval = globalThis.setInterval }) {
+ const active = createDesktopActive({
+ fetch: (...args) => session.defaultSession.fetch(...args), installId: () => launch.installId(), visible: () => inView(windows()),
+ day: { read: () => prefs.activeDay(), write: date => prefs.setActiveDay(date) }, version: app.getVersion(), platform: process.platform,
+ });
+ const check = () => { try { active.check(); } catch {} };
+ app.on("browser-window-focus", check);
+ app.on("browser-window-created", (_event, win) => { for (const shown of ["show", "restore", "ready-to-show"]) win.on(shown, check); });
+ setInterval(check, CHECK_MS).unref?.();
+ return active;
+}
diff --git a/electron/desktop-active.node-test.mjs b/electron/desktop-active.node-test.mjs
new file mode 100644
index 0000000000..42a6b69e60
--- /dev/null
+++ b/electron/desktop-active.node-test.mjs
@@ -0,0 +1,117 @@
+import assert from "node:assert/strict";
+import { EventEmitter } from "node:events";
+import test from "node:test";
+import { createDesktopActive, inView, installDesktopActive, localDay } from "./desktop-active.mjs";
+import { createDesktopPrefs } from "./desktop-prefs.mjs";
+import { createLaunchAnalytics } from "./launch-analytics.mjs";
+
+/** One computer: its prefs file, what left it, and a calendar the test turns. Each `start()` is a launch of the app. */
+function computer({ record = null, packaged = true, env = {}, answer = () => ({ ok: true }) } = {}) {
+ let saved = record, date = "2026-11-29", shown = false;
+ const sent = [];
+ const start = () => {
+ const prefs = createDesktopPrefs({ read: () => saved, write: value => { saved = structuredClone(value); } });
+ const fetch = async (url, init) => { sent.push({ url, body: JSON.parse(init.body) }); return answer(); };
+ const launch = createLaunchAnalytics({ fetch: async () => ({ ok: true }), choice: () => prefs.analytics(), installId: () => prefs.analyticsId(), lastVersion: null, version: "0.1.190", platform: "win32", packaged, env });
+ const active = createDesktopActive({ fetch, installId: () => launch.installId(), visible: () => shown, day: { read: () => prefs.activeDay(), write: day => prefs.setActiveDay(day) },
+ version: "0.1.190", platform: "win32", now: () => Date.UTC(2026, 10, 29, 12), today: () => date });
+ return { prefs, check: async () => { active.check(); await new Promise(resolve => setImmediate(resolve)); } };
+ };
+ return { start, sent, saved: () => saved, show: (on = true) => { shown = on; }, day: next => { date = next; } };
+}
+
+test("a window in view sends one app_active under the install's id, with the version, the platform and the system only", async () => {
+ const pc = computer();
+ const app = pc.start();
+ pc.show();
+ await app.check();
+ assert.equal(pc.sent.length, 1);
+ const [{ url, body }] = pc.sent;
+ assert.equal(url, "https://us.i.posthog.com/i/v0/e/");
+ assert.equal(body.event, "app_active");
+ assert.equal(body.distinct_id, app.prefs.analyticsId());
+ assert.deepEqual(body.properties, { app_version: "0.1.190", platform: "desktop", surface: "main", $os: "Windows", $process_person_profile: false });
+ assert.equal(body.timestamp, "2026-11-29T12:00:00.000Z");
+});
+
+test("one event per local day, however often it is checked and across restarts; a day that changes while the app runs sends the next day's", async () => {
+ const pc = computer();
+ pc.show();
+ const first = pc.start();
+ await first.check(); await first.check();
+ const again = pc.start();
+ await again.check();
+ assert.equal(pc.sent.length, 1, "a restart on the same day sends nothing more");
+ pc.day("2026-11-30");
+ await again.check(); await again.check();
+ assert.deepEqual(pc.sent.map(({ body }) => body.distinct_id), Array(2).fill(first.prefs.analyticsId()), "the same install both days");
+ assert.equal(pc.saved().activeDay, "2026-11-30");
+ await pc.start().check();
+ assert.equal(pc.sent.length, 2);
+});
+
+test("a start at login out of sight sends nothing and makes no id until a window is shown", async () => {
+ const pc = computer();
+ const app = pc.start();
+ await app.check();
+ pc.day("2026-11-30");
+ await app.check();
+ assert.deepEqual([pc.sent.length, pc.saved()], [0, null]);
+ pc.show();
+ await app.check();
+ assert.equal(pc.sent.length, 1);
+ pc.show(false); pc.day("2026-12-01");
+ await app.check();
+ assert.equal(pc.sent.length, 1, "left running in the tray overnight is not a day of use");
+});
+
+test("with usage analytics off, in a development build or in CI nothing is sent and no id or day is stored", async () => {
+ for (const options of [{ record: { analytics: false } }, { packaged: false }, { env: { CI: "true" } }, { env: { OMB_SMOKE_TEST: "1" } }]) {
+ const pc = computer(options);
+ pc.show();
+ await pc.start().check();
+ assert.equal(pc.sent.length, 0, JSON.stringify(options));
+ assert.deepEqual(pc.saved(), options.record ?? null, JSON.stringify(options));
+ }
+ const pc = computer();
+ pc.show();
+ const app = pc.start();
+ await app.check();
+ app.prefs.setAnalytics(false);
+ pc.day("2026-11-30");
+ await app.check();
+ assert.equal(pc.sent.length, 1, "switched off while running: nothing more");
+ assert.deepEqual(pc.saved(), { seen: [], analytics: false });
+});
+
+test("a send that was not taken is tried again at the next check; one on its way is not sent twice", async () => {
+ let ok = false;
+ const pc = computer({ answer: () => { if (!ok) throw new Error("offline"); return { ok: true }; } });
+ pc.show();
+ const app = pc.start();
+ await app.check();
+ assert.equal(pc.saved().activeDay, undefined);
+ ok = true;
+ await app.check(); await app.check();
+ assert.deepEqual([pc.sent.length, pc.saved().activeDay], [2, "2026-11-29"]);
+});
+
+test("the day is the computer's own calendar day; a window counts when shown and not minimized", () => {
+ assert.equal(localDay(new Date(2026, 0, 5, 23, 59)), "2026-01-05");
+ const win = (visible, minimized = false, destroyed = false) => ({ isVisible: () => visible, isMinimized: () => minimized, isDestroyed: () => destroyed });
+ assert.equal(inView([]), false);
+ assert.equal(inView([win(false), win(true, true), win(true, false, true)]), false);
+ assert.equal(inView([win(false), win(true)]), true);
+});
+
+test("it is checked when a window is shown, restored or focused, and every ten minutes", () => {
+ const app = Object.assign(new EventEmitter(), { getVersion: () => "0.1.190" });
+ let checks = 0, every = 0, tick = null;
+ const prefs = { activeDay: () => null, setActiveDay() {} };
+ installDesktopActive({ app, session: { defaultSession: { fetch: async () => ({ ok: true }) } }, prefs, windows: () => { checks++; return []; },
+ launch: { installId: () => "install-id" }, setInterval: (run, ms) => { tick = run; every = ms; return { unref() {} }; } });
+ const win = new EventEmitter();
+ app.emit("browser-window-created", {}, win);
+ win.emit("show"); win.emit("restore"); app.emit("browser-window-focus"); tick();
+ assert.deepEqual([checks, every], [4, 600_000]);
+});
diff --git a/electron/desktop-prefs.d.mts b/electron/desktop-prefs.d.mts
index c8013b7d94..9f2e3dbc3d 100644
--- a/electron/desktop-prefs.d.mts
+++ b/electron/desktop-prefs.d.mts
@@ -16,6 +16,8 @@ export interface DesktopNoticesBridge {
export interface DesktopAnalyticsBridge {
/** null until a choice is saved; a server's page is told only false, when this desktop turned analytics off. */
enabled(): boolean | null;
+ /** This computer's page only: the id the app itself sends its usage events under; null with analytics off. */
+ id?(): string | null;
/** This computer's page only. */
set?(enabled: boolean): Promise<void>;
}
@@ -37,6 +39,10 @@ export interface DesktopPrefs {
markSeen(id: string): void;
analytics(): boolean | null;
setAnalytics(enabled: boolean): void;
+ /** Random, made on first use; null with analytics off, and none is made then. */
+ analyticsId(): string | null;
+ activeDay(): string | null;
+ setActiveDay(day: string): void;
language(): string | null;
/** False for anything that is not a locale code or "". */
setLanguage(language: unknown): boolean;
@@ -104,6 +110,8 @@ export declare function registerDesktopPrefs(options: {
frame?: { made(): boolean | null; restarts: boolean; changed(): void } | null;
/** The MausBot Cloud sign-in client: with it, the product-updates question is asked and its answer kept here. */
cloudAccount?(): import("./updates-consent.mjs").UpdatesConsentClient | null;
+ /** This run sends no analytics whatever the switch says: every page reads the switch as off. */
+ silenced?(): boolean;
now?: () => number;
systemName?(): Promise<string | null>;
}): import("./updates-consent.mjs").UpdatesConsent | null;
diff --git a/electron/desktop-prefs.mjs b/electron/desktop-prefs.mjs
index 5b57fd7511..12507bf3c2 100644
--- a/electron/desktop-prefs.mjs
+++ b/electron/desktop-prefs.mjs
@@ -33,6 +33,7 @@ const LANGUAGE = /^(?:[a-z]{2,3}(?:-[a-z0-9]{2,8}){0,2})?$/i;
const isLanguage = value => typeof value === "string" && value.length <= 24 && LANGUAGE.test(value);
const CHAT_ID = /^[\w-]{1,128}$/;
const INSTALL_ID = /^[A-Za-z0-9_-]{22,64}$/;
+const LOCAL_DAY = /^\d{4}-\d{2}-\d{2}$/;
/** Security: a write that fails (a full disk, a kill mid-write) leaves the last whole record, analytics opt-out included.
* A file another tool saved with a byte-order mark (Notepad on Windows) still reads. */
@@ -62,7 +63,11 @@ function parse(raw) {
const quickAsks = record.quickAsks && typeof record.quickAsks === "object" && !Array.isArray(record.quickAsks)
? Object.fromEntries(Object.entries(record.quickAsks).flatMap(([server, chat]) => { const parsed = parseChat(chat); return parsed ? [[server, parsed]] : []; }))
: {};
+ // Security: with usage analytics off, its id and its last active day are not kept, whatever the file says.
+ const analyticsOn = record.analytics !== false;
return { seen, ...(typeof record.analytics === "boolean" ? { analytics: record.analytics } : {}),
+ ...(analyticsOn && typeof record.analyticsId === "string" && INSTALL_ID.test(record.analyticsId) ? { analyticsId: record.analyticsId } : {}),
+ ...(analyticsOn && typeof record.activeDay === "string" && LOCAL_DAY.test(record.activeDay) ? { activeDay: record.activeDay } : {}),
...(isLanguage(record.language) ? { language: record.language } : {}),
...(typeof record.installId === "string" && INSTALL_ID.test(record.installId) ? { installId: record.installId } : {}),
...(updatesConsent ? { updatesConsent } : {}),
@@ -109,7 +114,30 @@ export function createDesktopPrefs({ read, write }) {
},
/** null until a choice is saved. */
analytics: () => current().analytics ?? null,
- setAnalytics(enabled) { save({ ...current(), analytics: enabled === true }); },
+ /** Security: turning the switch off deletes the analytics id and the day; turning it on again starts a new id. */
+ setAnalytics(enabled) {
+ const { analyticsId: _id, activeDay: _day, ...rest } = current();
+ save(enabled === true ? { ...current(), analytics: true } : { ...rest, analytics: false });
+ },
+ /**
+ * The one name usage analytics know this install by, from the app itself and from this computer's own page: random,
+ * made on first use, from nothing of the computer or the person, and nothing else's name (never `installId`).
+ * Security: null with the switch off, and none is made then.
+ */
+ analyticsId() {
+ const saved = current();
+ if (saved.analytics === false) return null;
+ if (saved.analyticsId) return saved.analyticsId;
+ const analyticsId = randomBytes(24).toString("base64url");
+ save({ ...saved, analyticsId });
+ return analyticsId;
+ },
+ /** The last local day (YYYY-MM-DD) the app itself reported use; null before any, and with the switch off. */
+ activeDay: () => (current().analytics === false ? null : current().activeDay ?? null),
+ setActiveDay(day) {
+ const saved = current();
+ if (saved.analytics !== false && typeof day === "string" && LOCAL_DAY.test(day) && saved.activeDay !== day) save({ ...saved, activeDay: day });
+ },
/** null until a language is picked; "" is a pick too: follow the system. */
language: () => current().language ?? null,
setLanguage(language) {
@@ -172,8 +200,9 @@ export function createDesktopPrefs({ read, write }) {
* `languageChanged(language, sender)`: tells this desktop's other pages the language picked on one of them;
* `onLanguage(language)`: tells main, which draws its menus, tray and dialogs in it. `onShown(language, sender)`: the
* language a page of the window shows, which main's words follow while nothing is picked. `prefs`: the record main reads too.
+ * `silenced()`: this run sends no analytics whatever the switch says (launch-analytics.mjs analyticsSilenced).
*/
-export function registerDesktopPrefs({ prefs: given, ipcMain, read, write, page, cloudOffered, cloudAccount, localConfig = () => null, languageChanged = () => {}, onLanguage = () => {}, onShown = () => {}, frame = null, now = Date.now, systemName = accountFullName }) {
+export function registerDesktopPrefs({ prefs: given, ipcMain, read, write, page, cloudOffered, cloudAccount, localConfig = () => null, languageChanged = () => {}, onLanguage = () => {}, onShown = () => {}, frame = null, silenced = () => false, now = Date.now, systemName = accountFullName }) {
let prefs = given ?? null;
const store = () => prefs ??= createDesktopPrefs({ read, write });
const from = (channel, pages, handler) => (event, ...args) => {
@@ -194,13 +223,19 @@ export function registerDesktopPrefs({ prefs: given, ipcMain, read, write, page,
ipcMain.handle("desktop-notices:seen", from("desktop-notices:seen", ANY, (_, id) => store().markSeen(id)));
// A first run's default name for the profile: this computer's own page only, never a server's.
ipcMain.handle("desktop-profile:system-name", from("desktop-profile:system-name", ["local"], () => systemName()));
- // Security: a server's page learns only that this desktop turned analytics off, never that it is on.
+ // Security: a server's page learns only that this desktop turned analytics off, never that it is on. A silenced run
+ // reads as off on every page, so a development build or a test run sends no page event either.
ipcMain.on("desktop-analytics:read", event => {
try {
- const asking = page(event), saved = store().analytics();
+ const asking = page(event), saved = silenced() ? false : store().analytics();
event.returnValue = asking === "local" ? saved : asking && saved === false ? false : null;
} catch { event.returnValue = null; }
});
+ // Security: only this computer's own page learns the id, so its events and the app's are one install's; a server's
+ // page, My Cloud's included, never does. None is made or told with the switch off or in a silenced run.
+ ipcMain.on("desktop-analytics:id", event => {
+ try { event.returnValue = page(event) === "local" && !silenced() ? store().analyticsId() : null; } catch { event.returnValue = null; }
+ });
ipcMain.handle("desktop-analytics:set", from("desktop-analytics:set", ["local"], (_, enabled) => { store().setAnalytics(enabled === true); }));
ipcMain.on("desktop-language:read", event => {
try { event.returnValue = page(event) ? store().language() : null; } catch { event.returnValue = null; }
diff --git a/electron/desktop-prefs.node-test.mjs b/electron/desktop-prefs.node-test.mjs
index edd75a100e..82137fc743 100644
--- a/electron/desktop-prefs.node-test.mjs
+++ b/electron/desktop-prefs.node-test.mjs
@@ -106,7 +106,7 @@ test("a write that fails leaves the last whole record on disk, analytics opt-out
});
const WELCOMED = { onboarding: { completedAt: "2026-10-01T09:00:00.000Z", version: WELCOME_VERSION, hintsSeen: [] } };
-function desktopMain({ offered = true, page = event => event.page, config = () => WELCOMED, record = null } = {}) {
+function desktopMain({ offered = true, page = event => event.page, config = () => WELCOMED, record = null, silenced } = {}) {
const handlers = new Map(), listeners = new Map(), calls = [], told = [], languages = [];
let saved = record, now = NOON;
registerDesktopPrefs({
@@ -118,10 +118,11 @@ function desktopMain({ offered = true, page = event => event.page, config = () =
onLanguage: language => languages.push(language),
now: () => now,
systemName: async () => "Ada Lovelace",
+ ...(silenced ? { silenced } : {}),
});
const ask = (channel, page, ...args) => handlers.get(channel)({ page, sender: `${page}-page` }, ...args);
const answer = channel => page => { const event = { page }; listeners.get(channel)(event); return event.returnValue; };
- return { ask, read: answer("desktop-analytics:read"), language: answer("desktop-language:read"), told, languages, calls, channels: [...handlers.keys()], saved: () => saved, later: ms => { now += ms; } };
+ return { ask, read: answer("desktop-analytics:read"), id: answer("desktop-analytics:id"), language: answer("desktop-language:read"), told, languages, calls, channels: [...handlers.keys()], saved: () => saved, later: ms => { now += ms; } };
}
test("every page of this desktop's window reads and records the same notices; nothing else is answered", async () => {
@@ -181,6 +182,64 @@ test("the analytics switch is This computer's page's to set; a server's page in
assert.equal(broken.read("local"), null);
});
+test("the analytics id is made once, kept across restarts, and deleted with its day when the switch goes off", () => {
+ let saved = null;
+ const open = () => createDesktopPrefs({ read: () => saved, write: value => { saved = structuredClone(value); } });
+ const first = open();
+ assert.equal(saved, null, "nothing is made until something is to be sent");
+ const id = first.analyticsId();
+ assert.match(id, /^[A-Za-z0-9_-]{32}$/);
+ assert.equal(first.analyticsId(), id);
+ assert.notEqual(id, first.installId(), "never the id the product-updates question knows this computer by");
+ first.setActiveDay("2026-11-29"); first.setActiveDay("not a day");
+ assert.equal(open().analyticsId(), id, "the same after a restart");
+ assert.equal(open().activeDay(), "2026-11-29");
+ first.setAnalytics(true);
+ assert.equal(open().analyticsId(), id, "turning it on keeps the id");
+
+ first.setAnalytics(false);
+ assert.deepEqual([saved.analytics, "analyticsId" in saved, "activeDay" in saved], [false, false, false], "deleted from the file");
+ assert.equal(typeof saved.installId, "string", "nothing else is touched");
+ for (const prefs of [first, open()]) {
+ assert.equal(prefs.analyticsId(), null); assert.equal(prefs.activeDay(), null);
+ prefs.setActiveDay("2026-11-30");
+ }
+ assert.deepEqual(["analyticsId" in saved, "activeDay" in saved], [false, false], "none is made while it is off");
+ saved = { analytics: false, analyticsId: id, activeDay: "2026-11-29" };
+ assert.deepEqual([open().analyticsId(), open().activeDay()], [null, null], "a file that still names one is not believed");
+
+ saved = { analytics: false };
+ const again = open();
+ again.setAnalytics(true);
+ assert.notEqual(again.analyticsId(), id, "on again is a new id");
+});
+
+test("only this computer's own page is told the analytics id; none is made for another page, with the switch off or in a silenced run", async () => {
+ const main = desktopMain();
+ for (const page of ["cloud", "server", null]) assert.equal(main.id(page), null, String(page));
+ assert.equal(main.saved(), null, "asking from another page makes no id");
+ const id = main.id("local");
+ assert.match(id, /^[A-Za-z0-9_-]{32}$/);
+ assert.equal(main.id("local"), id);
+ for (const page of ["cloud", "server", null]) assert.equal(main.id(page), null, String(page));
+ await main.ask("desktop-analytics:set", "local", false);
+ assert.equal(main.id("local"), null);
+ assert.equal("analyticsId" in main.saved(), false);
+ const silent = desktopMain({ silenced: () => true });
+ assert.equal(silent.id("local"), null);
+ assert.equal(silent.saved(), null);
+});
+
+test("a run that sends no analytics reads as switched off on every page of the window, whatever choice is kept", async () => {
+ for (const record of [null, { analytics: true }]) {
+ const main = desktopMain({ record, silenced: () => true });
+ for (const page of ["local", "cloud", "server"]) assert.equal(main.read(page), false, `${JSON.stringify(record)} ${page}`);
+ assert.equal(main.read(null), null, "a page outside this desktop's window is told nothing");
+ assert.deepEqual(main.saved(), record, "nothing is written: the kept choice holds for a run that does send");
+ }
+ assert.equal(desktopMain({ record: { analytics: true }, silenced: () => false }).read("local"), true);
+});
+
test("the app language picked on any page of the window is the one every page reads, and it outlives a restart", async () => {
const main = desktopMain();
for (const page of ["local", "cloud", "server", null]) assert.equal(main.language(page), null, `System until a pick: ${page}`);
@@ -278,6 +337,7 @@ test("the preload gives every page of the window the notices and the switch's st
assert.equal(page.bridge.desktopAnalytics.enabled(), false, "turned off on this desktop");
assert.deepEqual(asked(), ["desktop-analytics:read"]);
assert.equal(page.bridge.desktopAnalytics.set, undefined, "a server's page cannot change the desktop's switch");
+ assert.equal(page.bridge.desktopAnalytics.id, undefined, "a server's page cannot ask for the desktop's analytics id");
await page.bridge.desktopNotices.state(); await page.bridge.desktopNotices.seen({ toString: () => POPUP });
assert.deepEqual(page.invoked, [["desktop-notices:state"], ["desktop-notices:seen", POPUP]]);
assert.deepEqual(Object.keys(page.bridge.desktopNotices), ["state", "seen", "shown"], "no page moves the window to this computer");
@@ -291,6 +351,8 @@ test("the preload gives every page of the window the notices and the switch's st
await local.bridge.desktopAnalytics.set(true);
assert.equal(local.bridge.desktopAnalytics.enabled(), true);
assert.deepEqual(local.invoked, [["desktop-analytics:set", true]]);
+ assert.equal(local.bridge.desktopAnalytics.id(), null, "main told no id");
+ assert.equal(local.synced.at(-1), "desktop-analytics:id", "asked of main each time, never kept by the page's bridge");
const unsaved = preload(LOCAL);
for (let i = 0; i < 3; i++) assert.equal(unsaved.bridge.desktopAnalytics.enabled(), null);
assert.deepEqual(unsaved.synced, ["desktop-analytics:read"], "no choice saved yet is asked once too");
diff --git a/electron/launch-analytics.mjs b/electron/launch-analytics.mjs
index e3abb823b8..448b76f548 100644
--- a/electron/launch-analytics.mjs
+++ b/electron/launch-analytics.mjs
@@ -1,5 +1,6 @@
// The desktop app's launch, stage by stage, for usage analytics: the app's pages can count only launches that got as
// far as a page, so main says how far each launch got. It honours the same Usage analytics switch as the pages.
+// Every event goes under this install's analytics id (desktop-prefs.mjs), the one this computer's own page sends under.
import { randomUUID } from "node:crypto";
import { readLastRunVersion } from "./startup-cache-eviction.mjs";
@@ -32,13 +33,19 @@ function atLeast(version, minimum) {
return true;
}
+/** A run that sends no analytics whatever its switch says: a development build, the smoke tests, CI. Main keeps to it
+ * here, and the pages this desktop shows are told the switch is off (desktop-prefs.mjs). */
+export function analyticsSilenced({ packaged, env }) {
+ return !packaged || env.OMB_SMOKE_TEST === "1" || Boolean(env.CI);
+}
+
/**
* Security: main sends only where the pages would. The switch says so (`true`), or no choice was kept (`null`) and either
* this is the computer's first launch or its last launch ran a version whose page had already moved any opt-out kept
* only in the page's storage into the switch. Packaged builds only, never under the smoke tests or CI.
*/
export function launchAnalyticsAllowed({ choice, firstLaunch, lastVersion, packaged, env }) {
- if (!packaged || env.OMB_SMOKE_TEST === "1" || env.CI) return false;
+ if (analyticsSilenced({ packaged, env })) return false;
if (choice === true) return true;
if (choice !== null) return false;
return firstLaunch || atLeast(lastVersion, OPT_OUT_KEPT_SINCE);
@@ -46,36 +53,48 @@ export function launchAnalyticsAllowed({ choice, firstLaunch, lastVersion, packa
const allowed = (value, list) => (typeof value === "string" && list.includes(value) ? value : "other");
+/** One event to the app's analytics; resolves true once it was taken. Security: no address, no URL, no person. */
+export function sendDesktopEvent(fetch, { event, id, at, properties }) {
+ try {
+ return Promise.resolve(fetch(ENDPOINT, {
+ method: "POST", headers: { "content-type": "application/json" }, credentials: "omit", cache: "no-store",
+ body: JSON.stringify({ api_key: TOKEN, event, distinct_id: id, timestamp: new Date(at).toISOString(), properties: { ...properties, $process_person_profile: false } }),
+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
+ })).then(response => response?.ok === true, () => false);
+ } catch { return Promise.resolve(false); }
+}
+export const desktopOs = platform => OS[platform] ?? "other";
+
/**
- * One `desktop_launch` event per stage reached, under a random id made for this launch alone and kept nowhere: it ties
- * the stages of one launch together, never one launch to another, to a page's id or to a person.
+ * One `desktop_launch` event per stage reached, under the install's analytics id (`installId()`, null while there is
+ * none to send under) and marked `telemetry: "launch"`, so a launch is never counted as a person using the app.
+ * `launch_id`, random and kept nowhere, ties the stages of one launch together.
*/
-export function createLaunchAnalytics({ fetch, choice, lastVersion, version, platform, packaged, env, now = Date.now, id = randomUUID() }) {
+export function createLaunchAnalytics({ fetch, choice, installId, lastVersion, version, platform, packaged, env, now = Date.now, id = randomUUID() }) {
const startedAt = now();
const firstLaunch = lastVersion === null;
const updated = !firstLaunch && lastVersion !== version;
const reached = new Set();
let serverFailure = null;
+ const mayRun = () => launchAnalyticsAllowed({ choice: choice(), firstLaunch, lastVersion, packaged, env });
const stage = (name, { reason, hidden } = {}) => {
if (!LAUNCH_STAGES.includes(name) || reached.has(name)) return;
reached.add(name);
- if (!launchAnalyticsAllowed({ choice: choice(), firstLaunch, lastVersion, packaged, env })) return;
+ if (!mayRun()) return;
+ const install = installId();
+ if (!install) return;
const why = reason ?? (name === "server_failed" ? serverFailure : undefined);
const properties = {
stage: name, ms: Math.max(0, Math.round(now() - startedAt)), first_launch: firstLaunch, updated,
...(typeof hidden === "boolean" ? { hidden } : {}), ...(why === undefined || why === null ? {} : { reason: allowed(why, LAUNCH_REASONS) }),
- app_version: version, platform: "desktop", surface: "main", $os: OS[platform] ?? "other", $process_person_profile: false,
+ telemetry: "launch", launch_id: id, app_version: version, platform: "desktop", surface: "main", $os: desktopOs(platform),
};
- try {
- void Promise.resolve(fetch(ENDPOINT, {
- method: "POST", headers: { "content-type": "application/json" }, credentials: "omit", cache: "no-store",
- body: JSON.stringify({ api_key: TOKEN, event: "desktop_launch", distinct_id: id, timestamp: new Date(now()).toISOString(), properties }),
- signal: AbortSignal.timeout(SEND_TIMEOUT_MS),
- })).catch(() => {});
- } catch {}
+ void sendDesktopEvent(fetch, { event: "desktop_launch", id: install, at: now(), properties });
};
return {
stage,
+ /** Whether this launch may send at all: the id to send under, or null. Security: none is made while it may not. */
+ installId: () => (mayRun() ? installId() : null),
/** The latest reason a server child did not come up; sent with `server_failed`. */
serverFailed(outcome) { serverFailure = outcome; },
/** A recorded crash: only the main window's page counts. */
@@ -88,7 +107,7 @@ export function createLaunchAnalytics({ fetch, choice, lastVersion, version, pla
/** This app's launch: Electron's own `app` and `session`, and the desktop's kept choices. */
export function desktopLaunchAnalytics({ app, session, prefs, env = process.env }) {
return createLaunchAnalytics({
- fetch: (...args) => session.defaultSession.fetch(...args), choice: () => prefs.analytics(), lastVersion: readLastRunVersion(app.getPath("userData")),
+ fetch: (...args) => session.defaultSession.fetch(...args), choice: () => prefs.analytics(), installId: () => prefs.analyticsId(), lastVersion: readLastRunVersion(app.getPath("userData")),
version: app.getVersion(), platform: process.platform, packaged: app.isPackaged, env,
});
}
diff --git a/electron/launch-analytics.node-test.mjs b/electron/launch-analytics.node-test.mjs
index 48298caedb..48f73d1d7f 100644
--- a/electron/launch-analytics.node-test.mjs
+++ b/electron/launch-analytics.node-test.mjs
@@ -1,20 +1,20 @@
import assert from "node:assert/strict";
import test from "node:test";
-import { createLaunchAnalytics, launchAnalyticsAllowed } from "./launch-analytics.mjs";
+import { analyticsSilenced, createLaunchAnalytics, launchAnalyticsAllowed } from "./launch-analytics.mjs";
const ON = { packaged: true, env: {} };
-function launch({ choice = null, lastVersion = null, version = "0.1.170", packaged = true, env = {}, platform = "darwin" } = {}) {
+function launch({ choice = null, lastVersion = null, version = "0.1.170", packaged = true, env = {}, platform = "darwin", install = () => "install-id" } = {}) {
const sent = [];
let clock = 1_000;
const analytics = createLaunchAnalytics({
fetch: async (url, init) => { sent.push({ url, init, body: JSON.parse(init.body) }); return { ok: true }; },
- choice: () => choice, lastVersion, version, platform, packaged, env, now: () => clock, id: "launch-id",
+ choice: () => choice, installId: install, lastVersion, version, platform, packaged, env, now: () => clock, id: "launch-id",
});
return { analytics, sent, tick: (ms) => { clock += ms; } };
}
-test("each stage of one launch is sent once, under that launch's own id, with no person profile", () => {
+test("each stage of one launch is sent once, under the install's id, marked as launch telemetry, with no person profile", () => {
const { analytics, sent, tick } = launch();
analytics.stage("started", { hidden: false });
tick(1_500);
@@ -27,10 +27,10 @@ test("each stage of one launch is sent once, under that launch's own id, with no
assert.equal(sent[0].url, "https://us.i.posthog.com/i/v0/e/");
const [first, , ready, shown] = sent.map(({ body }) => body);
assert.equal(first.event, "desktop_launch");
- assert.equal(first.distinct_id, "launch-id");
+ assert.deepEqual(sent.map(({ body }) => body.distinct_id), Array(4).fill("install-id"), "a launch is no user of its own");
assert.deepEqual(first.properties, {
- stage: "started", ms: 0, first_launch: true, updated: false, hidden: false, app_version: "0.1.170", platform: "desktop", surface: "main",
- $os: "Mac OS X", $process_person_profile: false,
+ stage: "started", ms: 0, first_launch: true, updated: false, hidden: false, telemetry: "launch", launch_id: "launch-id",
+ app_version: "0.1.170", platform: "desktop", surface: "main", $os: "Mac OS X", $process_person_profile: false,
});
assert.equal(ready.properties.ms, 3_500);
assert.equal(shown.properties.reason, "painted");
@@ -60,6 +60,27 @@ test("nothing is sent with the switch off, in development, under the smoke tests
}
});
+test("a launch that may not send asks for no install id, so none is made; and with none to send under, nothing is sent", () => {
+ for (const options of [{ choice: false }, { packaged: false }, { env: { CI: "true" } }, { lastVersion: "0.1.112" }]) {
+ let asked = 0;
+ const { analytics, sent } = launch({ ...options, install: () => { asked++; return "install-id"; } });
+ analytics.stage("started");
+ assert.equal(analytics.installId(), null, JSON.stringify(options));
+ assert.deepEqual([asked, sent.length], [0, 0], JSON.stringify(options));
+ }
+ const none = launch({ install: () => null });
+ none.analytics.stage("started");
+ assert.equal(none.sent.length, 0);
+ assert.equal(launch().analytics.installId(), "install-id");
+});
+
+test("a development build, a smoke test and CI are silenced; the packaged app on a person's computer is not", () => {
+ assert.equal(analyticsSilenced({ packaged: true, env: {} }), false);
+ assert.equal(analyticsSilenced({ packaged: false, env: {} }), true);
+ assert.equal(analyticsSilenced({ packaged: true, env: { OMB_SMOKE_TEST: "1" } }), true);
+ assert.equal(analyticsSilenced({ packaged: true, env: { CI: "true" } }), true);
+});
+
test("with no choice kept, only a first launch or one after a version that kept page opt-outs sends", () => {
assert.equal(launchAnalyticsAllowed({ ...ON, choice: true, firstLaunch: false, lastVersion: "0.1.1" }), true);
assert.equal(launchAnalyticsAllowed({ ...ON, choice: false, firstLaunch: true, lastVersion: null }), false);
@@ -72,7 +93,7 @@ test("with no choice kept, only a first launch or one after a version that kept
test("a send that throws or rejects never reaches the launch", async () => {
for (const fetch of [() => { throw new Error("offline"); }, async () => { throw new Error("offline"); }]) {
- const analytics = createLaunchAnalytics({ fetch, choice: () => true, lastVersion: null, version: "1.0.0", platform: "win32", packaged: true, env: {} });
+ const analytics = createLaunchAnalytics({ fetch, choice: () => true, installId: () => "install-id", lastVersion: null, version: "1.0.0", platform: "win32", packaged: true, env: {} });
assert.doesNotThrow(() => analytics.stage("started"));
}
await new Promise((resolve) => setImmediate(resolve));
diff --git a/electron/main.mjs b/electron/main.mjs
index e125c4bc02..7acc498f23 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -23,7 +23,7 @@ import {
readSafeLogTail,
} from "./diagnostics.mjs";
import { migrateWorkspaceConfigFile, workspaceCredentialEnv } from "./workspace-credentials.mjs";
-import { evictStartupCacheOnce } from "./startup-cache-eviction.mjs"; import { desktopLaunchAnalytics } from "./launch-analytics.mjs";
+import { evictStartupCacheOnce } from "./startup-cache-eviction.mjs"; import { analyticsSilenced, desktopLaunchAnalytics } from "./launch-analytics.mjs"; import { installDesktopActive } from "./desktop-active.mjs";
import { activateExistingWindow, releaseSingleInstanceLock } from "./single-instance.mjs";
import { bootFailureMessage, listeningSignal, pollServerIdentity, SERVER_BOOT_TIMEOUT_MS, SERVER_LISTENING_GRACE_MS } from "./server-boot-probe.mjs";
import { createServerSupervisor } from "./server-supervisor.mjs";
@@ -504,7 +504,7 @@ function slog(line) {
// Synchronous: a fatal exception can end Electron before an async write flushes.
// uncaughtExceptionMonitor observes Node's fatal path without handling it, so the process still exits.
-const launchAnalytics = desktopLaunchAnalytics({ app, session, prefs: nativeText.prefs }); installDesktopCrashListeners({
+const launchAnalytics = desktopLaunchAnalytics({ app, session, prefs: nativeText.prefs }); installDesktopActive({ app, session, prefs: nativeText.prefs, windows: appWindows, launch: launchAnalytics }); installDesktopCrashListeners({
appTarget: app,
processTarget: process,
record: (event) => { appendDesktopCrashRecord(DESKTOP_CRASH_LOG, DESKTOP_CRASH_LOG_MAX_BYTES, formatDesktopCrashRecord(event)); launchAnalytics.crashed(event); },
@@ -2927,7 +2927,7 @@ app.whenReady().then(async () => { launchRecord.mark("ready");
registerUpdaterIpc({ pageAllowed: updaterPageAllowed, serverPage: event => activePageOrigin(event), confirmRestart: async (version, server) => Boolean(mainWindow && !mainWindow.isDestroyed()) && (await dialog.showMessageBox(mainWindow, { type: "question", message: nativeT("native.update.forServer", { version, server }), detail: nativeT("native.update.forServerDetail"), buttons: [nativeT("native.update.restartNow"), nativeT("native.update.notNow")], defaultId: 0, cancelId: 1, noLink: true })).response === 0 });
desktopPrefs = nativeText.prefs;
updatesConsent = registerDesktopPrefs({ ipcMain, cloudAccount: () => cloudAccount, prefs: desktopPrefs, localConfig: jsonFile(path.join(desktopDataDir(), "config.json")).read, cloudOffered: () => cloudAccountRestored().then(cloudOffersReady),
- frame: { made: () => windowFrameMade, restarts: process.platform === "win32", changed: () => void broadcastDesktopCapabilities() },
+ frame: { made: () => windowFrameMade, restarts: process.platform === "win32", changed: () => void broadcastDesktopCapabilities() }, silenced: () => analyticsSilenced({ packaged: app.isPackaged, env: process.env }),
languageChanged: (language, sender) => {
for (const win of appWindows()) if (!win.isDestroyed() && win.webContents !== sender) win.webContents.send("desktop-language:changed", language);
chromeRail.send("desktop-language:changed", language);
diff --git a/electron/preload.cjs b/electron/preload.cjs
index 44062d222a..7261a18958 100644
--- a/electron/preload.cjs
+++ b/electron/preload.cjs
@@ -845,7 +845,8 @@ const bridge = {
if (analyticsChoice === undefined) analyticsChoice = savedAnalyticsChoice();
return analyticsChoice;
},
- ...(isLocalPage ? { set: enabled => { analyticsChoice = enabled === true; return ipcRenderer.invoke("desktop-analytics:set", analyticsChoice); } } : {}),
+ ...(isLocalPage ? { set: enabled => { analyticsChoice = enabled === true; return ipcRenderer.invoke("desktop-analytics:set", analyticsChoice); },
+ id: () => { try { const id = ipcRenderer.sendSync("desktop-analytics:id"); return typeof id === "string" ? id : null; } catch { return null; } } } : {}),
},
desktopLanguage: {
choice: () => {
diff --git a/src/lib/analytics.desktop-wire.test.ts b/src/lib/analytics.desktop-wire.test.ts
new file mode 100644
index 0000000000..01c9d22fa7
--- /dev/null
+++ b/src/lib/analytics.desktop-wire.test.ts
@@ -0,0 +1,133 @@
+// @vitest-environment happy-dom
+// @vitest-environment-options {"url":"http://127.0.0.1:5174/","settings":{"disableJavaScriptFileLoading":true,"disableJavaScriptEvaluation":true,"disableCSSFileLoading":true,"disableIframePageLoading":true}}
+// The real posthog-js on a page the desktop app shows, behind a recording network stub. The app's user agent names the
+// app, and posthog-js sends nothing from a user agent with a crawler's mark ("bot/" is one) unless told the page is no
+// crawler. One flow: posthog-js is a single instance per process.
+import { gunzipSync } from "node:zlib";
+import { expect, it, vi } from "vitest";
+
+/** What Electron makes of the packaged app's name and version, the same on every platform but for the system part. */
+const DESKTOP_USER_AGENT = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) OpenMausBot/0.1.186 Chrome/150.0.7871.250 Electron/43.8.13 Safari/537.36";
+const TOKEN = "phc_m2hP39w8y2gLPvHgDvSXAu6xcZ3agjf4ruL56rGcMZEe";
+
+const sent: Array<{ url: string; body: unknown }> = [];
+class RecordingXhr {
+ readyState = 0;
+ status = 0;
+ responseText = "";
+ withCredentials = false;
+ onreadystatechange: (() => void) | null = null;
+ private url = "";
+ open(_method: string, url: string) { this.url = url; }
+ setRequestHeader() {}
+ send(body?: unknown) {
+ sent.push({ url: this.url, body });
+ this.readyState = 4;
+ this.status = 200;
+ this.responseText = "{}";
+ queueMicrotask(() => this.onreadystatechange?.());
+ }
+ abort() {}
+}
+function memoryStorage() {
+ const map = new Map<string, string>();
+ return {
+ get length() { return map.size; },
+ key: (index: number) => [...map.keys()][index] ?? null,
+ getItem: (key: string) => map.get(key) ?? null,
+ setItem: (key: string, value: string) => void map.set(key, String(value)),
+ removeItem: (key: string) => void map.delete(key),
+ clear: () => map.clear(),
+ };
+}
+
+// posthog-js reads these when its module loads, so they are in place before analytics.ts imports it.
+vi.stubGlobal("fetch", async (input: unknown, init?: { body?: unknown }) => {
+ sent.push({ url: String((input as { url?: string })?.url ?? input), body: init?.body });
+ const json = { status: 1 };
+ return { status: 200, ok: true, headers: new Headers(), text: async () => JSON.stringify(json), json: async () => json };
+});
+vi.stubGlobal("XMLHttpRequest", RecordingXhr);
+Object.defineProperty(navigator, "sendBeacon", { configurable: true, value: (url: string, body: unknown) => (sent.push({ url, body }), true) });
+Object.defineProperty(navigator, "webdriver", { configurable: true, get: () => false });
+Object.defineProperty(navigator, "userAgent", { configurable: true, get: () => DESKTOP_USER_AGENT });
+vi.stubGlobal("sessionStorage", memoryStorage());
+vi.stubGlobal("localStorage", memoryStorage());
+// The desktop app's bridge on this computer's own page, with no analytics choice kept yet. Main deletes its analytics
+// id when the switch goes off and makes a new one when it comes back on.
+const INSTALL_IDS = ["install-AAAAAAAAAAAAAAAAAAAAAAAAAAAA", "install-BBBBBBBBBBBBBBBBBBBBBBBBBBBB"];
+let installId: string | null = INSTALL_IDS[0]!;
+Object.assign(window, { ogb: { environments: {}, desktopAnalytics: {
+ enabled: () => null, id: () => installId,
+ set: async (enabled: boolean) => { installId = enabled ? INSTALL_IDS[1]! : null; },
+} } });
+// PostHog's CDN config for this project, as posthog-js would have loaded it.
+(window as unknown as Record<string, unknown>)._POSTHOG_REMOTE_CONFIG = {
+ [TOKEN]: {
+ config: {
+ analytics: { endpoint: "/i/v0/e/" }, hasFeatureFlags: false, sessionRecording: false, surveys: false, heatmaps: false,
+ productTours: false, conversations: false, captureDeadClicks: false, autocaptureExceptions: false, siteApps: [],
+ supportedCompression: ["gzip", "gzip-js"],
+ },
+ },
+};
+
+async function bodyText(body: unknown): Promise<string> {
+ if (body === undefined || body === null) return "";
+ if (typeof body === "string") return body.startsWith("data=") ? Buffer.from(decodeURIComponent(body.slice(5)), "base64").toString("utf8") : body;
+ const bytes = Buffer.from(body instanceof Blob ? await body.arrayBuffer() : body as ArrayBuffer);
+ return (bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipSync(bytes) : bytes).toString("utf8");
+}
+
+type Sent = { event: string; properties: Record<string, unknown> & { distinct_id?: string } };
+async function events(): Promise<Sent[]> {
+ const bodies = await Promise.all(sent.map(({ body }) => bodyText(body)));
+ return bodies.filter(Boolean).flatMap((body) => { const parsed = JSON.parse(body) as Sent | { batch: Sent[] }; return "batch" in parsed ? parsed.batch : [parsed]; });
+}
+
+it("sends the desktop app's page events although the app's user agent carries a crawler's mark", async () => {
+ expect(navigator.userAgent.toLowerCase()).toContain("bot/");
+ vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout", "setInterval", "clearInterval"] });
+ try {
+ const analytics = await import("./analytics");
+ await analytics.initAnalytics();
+ analytics.track("app_snapshot", { bots: 3 });
+ for (let elapsed = 0; elapsed < 60; elapsed += 10) {
+ await vi.advanceTimersByTimeAsync(10_000);
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ // posthog-js gzips each batch with the platform's CompressionStream, which finishes on the real clock.
+ await vi.waitFor(async () => {
+ expect((await events()).map(({ event }) => event)).toEqual(expect.arrayContaining(["app_first_open", "app_opened", "app_active", "app_snapshot"]));
+ }, { timeout: 30_000, interval: 20 });
+
+ expect(sent.map(({ url }) => { const { origin, pathname } = new URL(url); return `${origin}${pathname}`; }).filter((url) => url !== "https://us.i.posthog.com/i/v0/e/")).toEqual([]);
+ const all = await events();
+ for (const { properties } of all) {
+ expect(properties).toMatchObject({ platform: "desktop", surface: "local" });
+ // posthog-js's own guess from the user agent would call every desktop page a bot.
+ expect(properties).not.toHaveProperty("$browser_type");
+ }
+ expect(JSON.stringify(all)).not.toContain("127.0.0.1");
+ // One install is one id: the app's own, whichever port's storage this page has.
+ expect([...new Set(all.map(({ properties }) => properties.distinct_id))]).toEqual([INSTALL_IDS[0]]);
+
+ const before = sent.length;
+ analytics.setAnalyticsEnabled(false);
+ analytics.track("after_off");
+ for (let elapsed = 0; elapsed < 600; elapsed += 10) await vi.advanceTimersByTimeAsync(10_000);
+ expect(sent.slice(before).map(({ url }) => url)).toEqual([]);
+
+ analytics.setAnalyticsEnabled(true);
+ await vi.advanceTimersByTimeAsync(0);
+ analytics.track("after_on");
+ for (let elapsed = 0; elapsed < 60; elapsed += 10) {
+ await vi.advanceTimersByTimeAsync(10_000);
+ await new Promise((resolve) => setImmediate(resolve));
+ }
+ await vi.waitFor(async () => expect((await events()).map(({ event }) => event)).toContain("after_on"), { timeout: 30_000, interval: 20 });
+ expect((await events()).filter(({ event }) => event === "after_on").map(({ properties }) => properties.distinct_id)).toEqual([INSTALL_IDS[1]]);
+ } finally {
+ vi.useRealTimers();
+ }
+});
diff --git a/src/lib/analytics.ts b/src/lib/analytics.ts
index fac60c679c..8f5a742b10 100644
--- a/src/lib/analytics.ts
+++ b/src/lib/analytics.ts
@@ -10,6 +10,8 @@ const TOKEN = "phc_m2hP39w8y2gLPvHgDvSXAu6xcZ3agjf4ruL56rGcMZEe";
const OPT_OUT_KEY = "omb-analytics-opt-out";
// The desktop app's own page is served on whichever of its ports was free, and each port has its own storage.
const desktopSwitch = () => globalThis.window?.ogb?.desktopAnalytics;
+/** A page the desktop app shows: the app's bridge says so, in its own window and on a server's page alike. */
+const desktopPage = () => Boolean(globalThis.window?.ogb);
let client: PostHog | undefined;
let loading: Promise<void> | undefined;
@@ -37,7 +39,8 @@ export function optAction(enabled: boolean, running: boolean): OptAction {
export function setAnalyticsEnabled(enabled: boolean) {
choice = enabled;
- void desktopSwitch()?.set?.(enabled).catch(() => {});
+ // The desktop app deletes its analytics id with the switch off and makes a new one once it is on again.
+ void desktopSwitch()?.set?.(enabled).then(() => { if (enabled && client) useDesktopId(client); }, () => {});
try {
localStorage.setItem(OPT_OUT_KEY, enabled ? "0" : "1");
} catch {
@@ -99,7 +102,10 @@ function start(posthog: PostHog) {
save_referrer: false,
save_campaign_params: false,
disable_capture_url_hashes: true,
- before_send: withoutLocation,
+ before_send: beforeSend,
+ // posthog-js 1.415 sends nothing from a browser whose user agent has a crawler's mark, "bot/" among them, and the
+ // desktop app's user agent names the app: every event from every page the app showed was dropped unsent.
+ opt_out_useragent_filter: desktopPage(),
// Security: posthog-js 1.415 posts /flags on load and every 5 minutes, even after opt_out_capturing(), with the stored
// person properties (the first page's URL and referrer), and before_send never sees it. The app reads no flags.
advanced_disable_flags: true,
@@ -109,6 +115,7 @@ function start(posthog: PostHog) {
for (const key of ["$initial_person_info", "$initial_referrer_info", "$initial_campaign_params"]) posthog.unregister(key);
// opt_out_capturing() persists in PostHog's own storage, so a later opt-in would boot opted out.
if (posthog.has_opted_out_capturing()) posthog.opt_in_capturing({ captureEventName: false });
+ useDesktopId(posthog);
client = posthog;
const platform = pagePlatform();
posthog.register({ app_version: appVersion(), surface: analyticsSurface(), platform });
@@ -121,8 +128,18 @@ function start(posthog: PostHog) {
for (const call of pending.splice(0)) call(posthog);
}
+/**
+ * This computer's own page in the desktop app sends under the app's analytics id, not one kept in the page's storage:
+ * the app serves that page on whichever of its ports is free, each with its own storage, and the app's own events
+ * (electron/desktop-active.mjs) are the same install's. A server's page is given no id and keeps its own.
+ */
+function useDesktopId(posthog: PostHog) {
+ const id = desktopSwitch()?.id?.();
+ if (id && posthog.get_distinct_id() !== id) posthog.register({ distinct_id: id, $device_id: id });
+}
+
function pagePlatform() {
- return navigator.userAgent.includes("Electron") ? "desktop" : "browser";
+ return desktopPage() ? "desktop" : "browser";
}
const ACTIVE_DAY_KEY = "omb-analytics-active-day";
@@ -187,6 +204,12 @@ export function withoutLocation(event: CaptureResult | null): CaptureResult | nu
return event;
}
+/** `$browser_type` is posthog-js's own guess from the user agent, sent only with its filter off: "bot" for the app. */
+function beforeSend(event: CaptureResult | null): CaptureResult | null {
+ if (event?.properties) delete event.properties.$browser_type;
+ return withoutLocation(event);
+}
+
export function analyticsSurface(): "local" | "server" {
return globalThis.window?.ogb?.environments ? "local" : "server";
}