Skip to content

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

Analytics: Connect an AI steps, desktop launch stages, platform on every event, cloud_plan when known (#6568)

Milind Soni62a1236f6969
diff --git a/apps/docs/content/docs/security/analytics.mdx b/apps/docs/content/docs/security/analytics.mdx
index d2b3fb29e7..07fac676d7 100644
--- a/apps/docs/content/docs/security/analytics.mdx
+++ b/apps/docs/content/docs/security/analytics.mdx
@@ -14,8 +14,9 @@ sent.
sent.
- 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`) and `surface`: `local` for the desktop app's own window,
- `server` for a page a server serves (MausBot Cloud, a self-hosted server, or the app in a browser).
+- Every event carries `app_version` (for example `0.1.112`), `surface`: `local` for the desktop app's own window,
+ `server` for a page a server serves (MausBot Cloud, a self-hosted server, or the app in a browser), and `platform`:
+ `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
@@ -24,7 +25,7 @@ sent.
## Turning it off
**Settings → General → Usage analytics.** When it is off, nothing loads and nothing is sent: no events, no daily
-snapshot, and none of the snapshot's requests.
+snapshot, none of the snapshot's requests, and none of the desktop app's launch events.
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
@@ -59,6 +60,7 @@ Properties are counts, `true` or `false`, or words from fixed lists in the app's
| App | The 24 apps Connected apps lists by default: `slack`, `github`, `gmail`, `googlecalendar`, `googlesheets`, `googledocs`, `googledrive`, `notion`, `linear`, `sentry`, `posthog`, `discord`, `twitter`, `reddit`, `zapier`, `hubspot`, `salesforce`, `jira`, `asana`, `trello`, `dropbox`, `airtable`, `figma`, `stripe`. Every other app is `other`. |
| Starting role | `assistant`, `inbox`, `research`, `coder`, `community`, `ops` |
| Cloud plan | `starter`, `personal`, `pro`, `max` |
+| Test failure | `signed_out`, `timeout`, `empty` (it answered with nothing), `credits`, `usage_limit`, `rate_limit`, `overloaded`, `server`, `tool_schema`, `tool_count`, `model_no_route`, `refused`, `other` |
An engine is named by the kind of engine it is, never by the account or endpoint it runs on: two Claude accounts both
report `claude`. A page that may not list the engines (a member's, a Cloud guest's or a paired device's) names the
@@ -115,7 +117,7 @@ use their own Boat key, and how many bots run on cloud computers, without sendin
| `phone_paired` | true/false | Either count above is more than zero |
| `members` | count | People signed in to this server with an email, other than you |
| `cloud_home` | true/false | This server is a MausBot Cloud |
-| `cloud_plan` | `starter`, `personal`, `pro`, `max`, `other`, `none`, `unknown` | The Cloud plan: `none` when free or signed out, `unknown` when the app cannot tell |
+| `cloud_plan` | `starter`, `personal`, `pro`, `max`, `other`, `none`, `unknown` | The Cloud plan: `none` when free or signed out. While the desktop app's sign-in cannot be checked (offline, expired, signing in again), the plan it last checked, else `none`. `unknown` when the app cannot tell; the snapshot waits up to half a minute while the desktop app is still reading its saved sign-in. Left out on a page that has no way to ask: a server that is not your MausBot Cloud, or the desktop app connected to another server |
| `cloud_trial` | true/false | A Cloud trial is running |
| `edition` | `oss`, `enterprise` | The edition |
| `org_managed` | true/false | An organisation manages this desktop |
@@ -132,6 +134,9 @@ use their own Boat key, and how many bots run on cloud computers, without sendin
| `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 |
| `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` |
+| `sign_in_gate` | The desktop app's own page opens on its sign-in page instead of the app | `reason`: `signed_out`, `session_ended`, `team_left`, `service_trust` |
| `onboarding_completed` | The first run ends in the chat | `reason`: `completed`; `at`: the screen it ended on; `replay`: true/false |
| `setup_import_applied` | You bring in the skills and MCP servers found from other AI tools on this computer, in Settings → Import & export | `skills`, `tools`: how many were added. Never their names or where they came from |
| `onboarding_cloud` | You tap Try Cloud under MausBot's first messages, which opens Add a Cloud | `action`: `start_trial` |
@@ -177,3 +182,29 @@ use their own Boat key, and how many bots run on cloud computers, without sendin
ElevenLabs, Fish Audio), and for a model provider key whose test passed right after saving. A key nothing checks before
it is used (OpenCode, OpenAI images, an added OpenAI-compatible server, an xAI key from a chat request) reports
`unverified`.
+
+## The desktop app's launch
+
+The desktop app itself (not its page) sends one `desktop_launch` event for each stage a launch reaches, so launches
+that never get as far as a page are counted too. Its first stage on a computer that never ran the app is the install
+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.
+- Only the packaged app sends, never a development build.
+
+| Stage | When | Properties besides `stage` |
+| --- | --- | --- |
+| `started` | The app starts | `hidden`: true/false, started at login out of sight |
+| `server_spawned` | The app's own server process started | |
+| `server_ready` | That server answers | `reason`: `relay`, the desktop app connected to another server |
+| `server_failed` | The server did not answer on any port | `reason`: `timeout`, `exited`, `foreign-owner` (another program answers on the port), `stuck-child` |
+| `window_shown` | The window replaced the loading screen | `reason`: `painted` (the app drew its first screen), `crashed`, `timeout` (ten seconds passed first), `shown`, `hidden` (the loading screen was put away in the tray, so the window stays out of sight) |
+| `page_load_failed` | The window could not load the app's own page | |
+| `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.
diff --git a/docs/analytics.md b/docs/analytics.md
index 4e9c64921f..9aecd35ae6 100644
--- a/docs/analytics.md
+++ b/docs/analytics.md
@@ -10,8 +10,9 @@ sent.
sent.
- 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`) and `surface`: `local` for the desktop app's own window,
- `server` for a page a server serves (MausBot Cloud, a self-hosted server, or the app in a browser).
+- Every event carries `app_version` (for example `0.1.112`), `surface`: `local` for the desktop app's own window,
+ `server` for a page a server serves (MausBot Cloud, a self-hosted server, or the app in a browser), and `platform`:
+ `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
@@ -20,7 +21,7 @@ sent.
## Turning it off
**Settings → General → Usage analytics.** When it is off, nothing loads and nothing is sent: no events, no daily
-snapshot, and none of the snapshot's requests.
+snapshot, none of the snapshot's requests, and none of the desktop app's launch events.
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
@@ -55,6 +56,7 @@ Properties are counts, `true` or `false`, or words from fixed lists in the app's
| App | The 24 apps Connected apps lists by default: `slack`, `github`, `gmail`, `googlecalendar`, `googlesheets`, `googledocs`, `googledrive`, `notion`, `linear`, `sentry`, `posthog`, `discord`, `twitter`, `reddit`, `zapier`, `hubspot`, `salesforce`, `jira`, `asana`, `trello`, `dropbox`, `airtable`, `figma`, `stripe`. Every other app is `other`. |
| Starting role | `assistant`, `inbox`, `research`, `coder`, `community`, `ops` |
| Cloud plan | `starter`, `personal`, `pro`, `max` |
+| Test failure | `signed_out`, `timeout`, `empty` (it answered with nothing), `credits`, `usage_limit`, `rate_limit`, `overloaded`, `server`, `tool_schema`, `tool_count`, `model_no_route`, `refused`, `other` |
An engine is named by the kind of engine it is, never by the account or endpoint it runs on: two Claude accounts both
report `claude`. A page that may not list the engines (a member's, a Cloud guest's or a paired device's) names the
@@ -111,7 +113,7 @@ use their own Boat key, and how many bots run on cloud computers, without sendin
| `phone_paired` | true/false | Either count above is more than zero |
| `members` | count | People signed in to this server with an email, other than you |
| `cloud_home` | true/false | This server is a MausBot Cloud |
-| `cloud_plan` | `starter`, `personal`, `pro`, `max`, `other`, `none`, `unknown` | The Cloud plan: `none` when free or signed out, `unknown` when the app cannot tell |
+| `cloud_plan` | `starter`, `personal`, `pro`, `max`, `other`, `none`, `unknown` | The Cloud plan: `none` when free or signed out. While the desktop app's sign-in cannot be checked (offline, expired, signing in again), the plan it last checked, else `none`. `unknown` when the app cannot tell; the snapshot waits up to half a minute while the desktop app is still reading its saved sign-in. Left out on a page that has no way to ask: a server that is not your MausBot Cloud, or the desktop app connected to another server |
| `cloud_trial` | true/false | A Cloud trial is running |
| `edition` | `oss`, `enterprise` | The edition |
| `org_managed` | true/false | An organisation manages this desktop |
@@ -128,6 +130,9 @@ use their own Boat key, and how many bots run on cloud computers, without sendin
| `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 |
| `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` |
+| `sign_in_gate` | The desktop app's own page opens on its sign-in page instead of the app | `reason`: `signed_out`, `session_ended`, `team_left`, `service_trust` |
| `onboarding_completed` | The first run ends in the chat | `reason`: `completed`; `at`: the screen it ended on; `replay`: true/false |
| `setup_import_applied` | You bring in the skills and MCP servers found from other AI tools on this computer, in Settings → Import & export | `skills`, `tools`: how many were added. Never their names or where they came from |
| `onboarding_cloud` | You tap Try Cloud under MausBot's first messages, which opens Add a Cloud | `action`: `start_trial` |
@@ -173,3 +178,29 @@ use their own Boat key, and how many bots run on cloud computers, without sendin
ElevenLabs, Fish Audio), and for a model provider key whose test passed right after saving. A key nothing checks before
it is used (OpenCode, OpenAI images, an added OpenAI-compatible server, an xAI key from a chat request) reports
`unverified`.
+
+## The desktop app's launch
+
+The desktop app itself (not its page) sends one `desktop_launch` event for each stage a launch reaches, so launches
+that never get as far as a page are counted too. Its first stage on a computer that never ran the app is the install
+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.
+- Only the packaged app sends, never a development build.
+
+| Stage | When | Properties besides `stage` |
+| --- | --- | --- |
+| `started` | The app starts | `hidden`: true/false, started at login out of sight |
+| `server_spawned` | The app's own server process started | |
+| `server_ready` | That server answers | `reason`: `relay`, the desktop app connected to another server |
+| `server_failed` | The server did not answer on any port | `reason`: `timeout`, `exited`, `foreign-owner` (another program answers on the port), `stuck-child` |
+| `window_shown` | The window replaced the loading screen | `reason`: `painted` (the app drew its first screen), `crashed`, `timeout` (ten seconds passed first), `shown`, `hidden` (the loading screen was put away in the tray, so the window stays out of sight) |
+| `page_load_failed` | The window could not load the app's own page | |
+| `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.
diff --git a/electron/launch-analytics.mjs b/electron/launch-analytics.mjs
new file mode 100644
index 0000000000..e3abb823b8
--- /dev/null
+++ b/electron/launch-analytics.mjs
@@ -0,0 +1,94 @@
+// 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.
+import { randomUUID } from "node:crypto";
+import { readLastRunVersion } from "./startup-cache-eviction.mjs";
+
+// The app's own PostHog project; the phc_ token is a write-only public key, the same one the app's pages send with.
+const TOKEN = "phc_m2hP39w8y2gLPvHgDvSXAu6xcZ3agjf4ruL56rGcMZEe";
+const ENDPOINT = "https://us.i.posthog.com/i/v0/e/";
+const SEND_TIMEOUT_MS = 10_000;
+
+export const LAUNCH_STAGES = Object.freeze([
+ "started", "server_spawned", "server_ready", "server_failed", "window_shown", "page_load_failed", "page_crashed",
+]);
+/** Why the server did not start, how the window came up, and Electron's render-process-gone reasons. */
+export const LAUNCH_REASONS = Object.freeze([
+ "timeout", "exited", "foreign-owner", "stuck-child", "relay",
+ "painted", "crashed", "shown", "hidden",
+ "abnormal-exit", "integrity-failure", "killed", "launch-failed", "oom",
+]);
+const OS = { darwin: "Mac OS X", win32: "Windows", linux: "Linux" };
+
+/** The first version whose page moves an opt-out kept only in its own storage to the desktop's switch on start. */
+const OPT_OUT_KEPT_SINCE = [0, 1, 113];
+
+function atLeast(version, minimum) {
+ const parts = /^(\d+)\.(\d+)\.(\d+)/.exec(typeof version === "string" ? version : "");
+ if (!parts) return false;
+ for (let index = 0; index < 3; index++) {
+ const part = Number(parts[index + 1]);
+ if (part !== minimum[index]) return part > minimum[index];
+ }
+ return true;
+}
+
+/**
+ * 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 (choice === true) return true;
+ if (choice !== null) return false;
+ return firstLaunch || atLeast(lastVersion, OPT_OUT_KEPT_SINCE);
+}
+
+const allowed = (value, list) => (typeof value === "string" && list.includes(value) ? value : "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.
+ */
+export function createLaunchAnalytics({ fetch, choice, 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 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;
+ 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,
+ };
+ 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 {}
+ };
+ return {
+ stage,
+ /** 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. */
+ crashed(event) {
+ if (event?.kind === "renderer" && event.surface === "main-window" && event.reason !== "clean-exit") stage("page_crashed", { reason: event.reason });
+ },
+ };
+}
+
+/** 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")),
+ 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
new file mode 100644
index 0000000000..48298caedb
--- /dev/null
+++ b/electron/launch-analytics.node-test.mjs
@@ -0,0 +1,79 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { 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" } = {}) {
+ 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",
+ });
+ 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", () => {
+ const { analytics, sent, tick } = launch();
+ analytics.stage("started", { hidden: false });
+ tick(1_500);
+ analytics.stage("server_spawned");
+ analytics.stage("server_spawned");
+ tick(2_000);
+ analytics.stage("server_ready");
+ analytics.stage("window_shown", { reason: "painted" });
+ assert.deepEqual(sent.map(({ body }) => body.properties.stage), ["started", "server_spawned", "server_ready", "window_shown"]);
+ 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(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,
+ });
+ assert.equal(ready.properties.ms, 3_500);
+ assert.equal(shown.properties.reason, "painted");
+});
+
+test("a failed server says why in a word from its list, and a main-window crash counts while other pages do not", () => {
+ const { analytics, sent } = launch({ lastVersion: "0.1.169" });
+ analytics.serverFailed("timeout");
+ analytics.stage("server_failed");
+ analytics.crashed({ kind: "renderer", surface: "auxiliary", reason: "crashed" });
+ analytics.crashed({ kind: "renderer", surface: "main-window", reason: "clean-exit" });
+ analytics.crashed({ kind: "child", reason: "oom" });
+ analytics.crashed({ kind: "renderer", surface: "main-window", reason: "/Users/ada/secret" });
+ assert.deepEqual(sent.map(({ body }) => [body.properties.stage, body.properties.reason]), [["server_failed", "timeout"], ["page_crashed", "other"]]);
+ assert.equal(sent[0].body.properties.first_launch, false);
+ assert.equal(sent[0].body.properties.updated, true);
+ analytics.stage("not-a-stage");
+ assert.equal(sent.length, 2);
+});
+
+test("nothing is sent with the switch off, in development, under the smoke tests or in CI", () => {
+ for (const options of [{ choice: false }, { packaged: false }, { env: { OMB_SMOKE_TEST: "1" } }, { env: { CI: "true" } }]) {
+ const { analytics, sent } = launch(options);
+ analytics.stage("started");
+ analytics.stage("server_failed");
+ assert.equal(sent.length, 0, JSON.stringify(options));
+ }
+});
+
+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);
+ assert.equal(launchAnalyticsAllowed({ ...ON, choice: null, firstLaunch: true, lastVersion: null }), true);
+ assert.equal(launchAnalyticsAllowed({ ...ON, choice: null, firstLaunch: false, lastVersion: "0.1.113" }), true);
+ assert.equal(launchAnalyticsAllowed({ ...ON, choice: null, firstLaunch: false, lastVersion: "0.2.0" }), true);
+ assert.equal(launchAnalyticsAllowed({ ...ON, choice: null, firstLaunch: false, lastVersion: "0.1.112" }), false);
+ assert.equal(launchAnalyticsAllowed({ ...ON, choice: null, firstLaunch: false, lastVersion: "garbage" }), false);
+});
+
+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: {} });
+ assert.doesNotThrow(() => analytics.stage("started"));
+ }
+ await new Promise((resolve) => setImmediate(resolve));
+});
diff --git a/electron/main.mjs b/electron/main.mjs
index 17472a8196..42de561661 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 { evictStartupCacheOnce } from "./startup-cache-eviction.mjs"; import { desktopLaunchAnalytics } from "./launch-analytics.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,10 +504,10 @@ 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.
-installDesktopCrashListeners({
+const launchAnalytics = desktopLaunchAnalytics({ app, session, prefs: nativeText.prefs }); installDesktopCrashListeners({
appTarget: app,
processTarget: process,
- record: (event) => appendDesktopCrashRecord(DESKTOP_CRASH_LOG, DESKTOP_CRASH_LOG_MAX_BYTES, formatDesktopCrashRecord(event)),
+ record: (event) => { appendDesktopCrashRecord(DESKTOP_CRASH_LOG, DESKTOP_CRASH_LOG_MAX_BYTES, formatDesktopCrashRecord(event)); launchAnalytics.crashed(event); },
isShuttingDown: () => desktopShutdownStarted,
mainWebContents: () => mainWindow?.webContents ?? null,
});
@@ -1157,7 +1157,7 @@ async function startServerOn(port, dataDir = runningDataDir ?? startupEnvironmen
}
});
proc.once("spawn", () => {
- slog(`spawned pid=${proc.pid}`);
+ slog(`spawned pid=${proc.pid}`); launchAnalytics.stage("server_spawned");
if (!serverSupervisor.isCurrent(proc)) return;
syncDesktopMutationToken(proc); void tailnetShare.attach(proc, port, companionSettings().routes.tailscale);
syncPhoneSecretKey(proc); grantLocalComputer(proc, (child) => serverSupervisor.isCurrent(child));
@@ -1185,7 +1185,7 @@ async function startServerOn(port, dataDir = runningDataDir ?? startupEnvironmen
if (!stopped) {
slog(`child on port ${port} did not exit after termination; refusing to start a sibling server`);
}
- return { proc: null, reason: stopped ? identity.outcome : "stuck-child", abort: !stopped };
+ launchAnalytics.serverFailed(stopped ? identity.outcome : "stuck-child"); return { proc: null, reason: stopped ? identity.outcome : "stuck-child", abort: !stopped };
}
async function startServerPackaged() {
@@ -1197,7 +1197,7 @@ async function startServerPackaged() {
const started = await startServerOn(port);
if (started.proc) {
SERVER_PORT = port;
- if (serverSupervisor.ready(started.proc)) return true;
+ if (serverSupervisor.ready(started.proc)) { launchAnalytics.stage("server_ready"); return true; }
}
if (started.abort) return false;
if (started.reason !== "foreign-owner") everyPortForeignOwned = false;
@@ -2020,7 +2020,7 @@ function createWindow({ deferNavigation = false } = {}) {
}
});
win.webContents.on("did-fail-load", (_event, errorCode, errorDescription, validatedURL, isMainFrame) => {
- if (!isMainFrame || errorCode === -3) return; // -3: aborted by a newer navigation
+ if (!isMainFrame || errorCode === -3 /* aborted by a newer navigation */) return; if (validatedURL.startsWith(`${rendererOrigin()}/`)) launchAnalytics.stage("page_load_failed");
const remote = activeRemote(environmentsState);
if (!remote) return;
let origin = null;
@@ -2802,14 +2802,14 @@ app.whenReady().then(async () => {
slog(`system tray unavailable: ${error?.message ?? error}`);
}
}
- hiddenStart = loginItem.startedHidden() || reopenedOutOfSight();
+ hiddenStart = loginItem.startedHidden() || reopenedOutOfSight(); launchAnalytics.stage("started", { hidden: hiddenStart });
startupScreen = hiddenStart ? null : createStartupScreen({
BrowserWindow, iconPath: APP_ICON, isQuitting: () => desktopShutdownStarted, t: nativeT, lang: nativeText.intlTag(),
onQuit: () => app.quit(),
onHide: desktopTray ? (win) => desktopTray.hide(win) : undefined,
isHidden: () => desktopTray?.isHidden() ?? false,
onShow: (win) => desktopTray?.windowShown(win),
- onFinished: () => { startupScreen = null; },
+ onFinished: () => { startupScreen = null; }, onReveal: via => launchAnalytics.stage("window_shown", { reason: via }),
});
await startupScreen?.ready;
if (desktopShutdownStarted) return;
@@ -2953,13 +2953,13 @@ app.whenReady().then(async () => {
: path.join(app.getAppPath(), "dist"),
});
SERVER_PORT = desktopCompanionRelay.port;
- serverReady = true;
+ serverReady = true; launchAnalytics.stage("server_ready", { reason: "relay" });
} catch (error) {
serverReady = false;
slog(`desktop companion relay failed: ${error?.message ?? error}`);
}
} else if (app.isPackaged) {
- const booted = await startServerPackaged();
+ const booted = await startServerPackaged(); if (!booted && !desktopShutdownStarted) launchAnalytics.stage("server_failed");
if (!booted && !desktopShutdownStarted && bootDataDir !== desktopDataDir()) {
slog(`boot environment ${bootDataDir} did not start; falling back to the default data dir`);
persistEnvironments({ ...environmentsState, activeId: LOCAL_ID });
diff --git a/electron/startup-screen.mjs b/electron/startup-screen.mjs
index c5bccfc82c..90650394e5 100644
--- a/electron/startup-screen.mjs
+++ b/electron/startup-screen.mjs
@@ -21,7 +21,7 @@ export function startupScreenHtml(iconPath, { t = nativeText.englishText.t, lang
export function createStartupScreen({
BrowserWindow, iconPath, platform = process.platform, isQuitting, onQuit,
- onHide, isHidden = () => false, onShow, onFinished, t, lang,
+ onHide, isHidden = () => false, onShow, onFinished, onReveal, t, lang,
}) {
let disposed = false, revealed = false, fallback, resolveReady;
const ready = new Promise(resolve => { resolveReady = resolve; });
@@ -80,9 +80,10 @@ export function createStartupScreen({
void splash.loadURL("data:text/html;charset=utf-8," + encodeURIComponent(startupScreenHtml(iconPath, { t, lang })))
.catch(resolveReady);
const attach = (win, { maximized = false } = {}) => {
- const reveal = () => {
+ const reveal = (via) => {
if (revealed || win.isDestroyed() || isQuitting()) return;
revealed = true;
+ onReveal?.(isHidden() ? "hidden" : via);
const minimized = !splash.isDestroyed() && splash.isMinimized();
if (isHidden()) {
win.setSkipTaskbar(true);
@@ -104,12 +105,12 @@ export function createStartupScreen({
if (root.childElementCount) { observer.disconnect(); resolve(); }
});
observer.observe(root, { childList: true });
- })`).then(reveal).catch(reveal);
+ })`).then(() => reveal("painted"), () => reveal("shown"));
});
- win.webContents.once("render-process-gone", reveal);
- win.once("show", () => { if (!revealed) { revealed = true; dispose(); } });
+ win.webContents.once("render-process-gone", () => reveal("crashed"));
+ win.once("show", () => { if (!revealed) { revealed = true; onReveal?.("shown"); dispose(); } });
win.once("closed", dispose);
- fallback = setTimeout(reveal, 10_000);
+ fallback = setTimeout(() => reveal("timeout"), 10_000);
fallback.unref?.();
};
/** The line under the name, in place of "Opening your workspace…". */
diff --git a/electron/startup-tray.node-test.mjs b/electron/startup-tray.node-test.mjs
index 08cd61c976..4f7af32437 100644
--- a/electron/startup-tray.node-test.mjs
+++ b/electron/startup-tray.node-test.mjs
@@ -216,3 +216,28 @@ test("the loading screen says what the app waits on, before its page has loaded
splash.status("Opening My Cloud…");
assert.equal(ran.length, 2, "nothing after it is gone");
});
+
+test("the startup screen says how the workspace came up, once", async t => {
+ t.mock.timers.enable({ apis: ["setTimeout"] });
+ const ways = [];
+ const painted = fixture({ onReveal: via => ways.push(via) });
+ await painted.splash.ready;
+ painted.win.webContents.executeJavaScript = () => Promise.resolve();
+ painted.splash.attach(painted.win);
+ painted.win.webContents.emit("did-finish-load"); await flush();
+ painted.win.webContents.emit("render-process-gone");
+ const crashed = fixture({ onReveal: via => ways.push(via) });
+ await crashed.splash.ready; crashed.splash.attach(crashed.win);
+ crashed.win.webContents.emit("render-process-gone");
+ const slow = fixture({ onReveal: via => ways.push(via) });
+ await slow.splash.ready; slow.splash.attach(slow.win);
+ t.mock.timers.tick(10_000);
+ assert.deepEqual(ways, ["painted", "crashed", "timeout"]);
+ const hidden = fixture({ onReveal: via => ways.push(via) });
+ await hidden.splash.ready;
+ hidden.splash.window.emit("close", { preventDefault() {} });
+ hidden.win.webContents.executeJavaScript = () => Promise.resolve();
+ hidden.splash.attach(hidden.win);
+ hidden.win.webContents.emit("did-finish-load"); await flush();
+ assert.equal(ways.at(-1), "hidden");
+});
diff --git a/server/engine-check.test.ts b/server/engine-check.test.ts
index 409f109ec3..fc36b34ac4 100644
--- a/server/engine-check.test.ts
+++ b/server/engine-check.test.ts
@@ -14,10 +14,12 @@ describe("checking a just-connected engine with one tiny real message", () => {
it("names the exact fix: sign in again, the provider's own refusal in plain words, or what it said", async () => {
expect(await checkEngine(engine(async () => { throw new Error("Not logged in · Please run /login"); })))
- .toEqual({ ok: false, error: "Claude isn't signed in on this computer anymore. Sign in again, then check again." });
+ .toEqual({ ok: false, reason: "signed_out", error: "Claude isn't signed in on this computer anymore. Sign in again, then check again." });
expect((await checkEngine(engine(async () => { throw new Error("API Error: 402 {\"error\":{\"message\":\"Your credit balance is too low\"}}"); }))))
- .toMatchObject({ ok: false, error: expect.stringContaining("Your Claude account is out of credits") });
- expect(await checkEngine(engine(async () => ""))).toEqual({ ok: false, error: "Claude answered with nothing. Check again in a minute." });
+ .toMatchObject({ ok: false, reason: "credits", error: expect.stringContaining("Your Claude account is out of credits") });
+ expect(await checkEngine(engine(async () => ""))).toEqual({ ok: false, reason: "empty", error: "Claude answered with nothing. Check again in a minute." });
+ expect(await checkEngine(engine(async () => { throw new Error("spawn claude ENOENT at /Users/ada/bin"); }))).toMatchObject({ ok: false, reason: "other" });
+ expect(await checkEngine(engine(async () => { throw new Error("API Error: 429 rate limited"); }))).toMatchObject({ ok: false, reason: "rate_limit" });
expect(engineCheckError("ChatGPT", "spawn codex ENOENT with key sk-proj-abcdefghijklmnopqrstuvwxyz0123456789")).not.toContain("sk-proj-abcdefghijklmnop");
});
@@ -52,7 +54,7 @@ describe("checking a just-connected engine with one tiny real message", () => {
const hanging = { instanceId: "hanging", displayName: "Grok", driverKind: "grokAgent", generateText };
const pending = checkEngine(hanging, { timeoutMs: 5_000 });
await vi.advanceTimersByTimeAsync(5_000);
- expect(await pending).toEqual({ ok: false, error: "Grok didn't answer within 5 seconds.", errorKey: "serverError.engineCheck.timeout", errorParams: { name: "Grok", seconds: "5" } });
+ expect(await pending).toEqual({ ok: false, reason: "timeout", error: "Grok didn't answer within 5 seconds.", errorKey: "serverError.engineCheck.timeout", errorParams: { name: "Grok", seconds: "5" } });
expect(signal?.aborted).toBe(true);
expect(vi.getTimerCount()).toBe(0);
// The engine is free for the next check.
diff --git a/server/engine-check.ts b/server/engine-check.ts
index cfe81dfbcb..a399426c85 100644
--- a/server/engine-check.ts
+++ b/server/engine-check.ts
@@ -1,11 +1,13 @@
// A tiny real message through an engine the person just connected, so setup can say it works or what to fix.
import type { ProviderInstance } from "./contracts.ts";
-import { engineFailureMessage } from "./drivers/engine-errors.ts";
+import { engineFailureKind, engineFailureMessage } from "./drivers/engine-errors.ts";
import { redactSecretsInText } from "./redact.ts";
import { userError } from "./user-errors.ts";
import type { ServerErrorBody } from "../shared/server-text.ts";
+import type { AiTestReason } from "../shared/ai-ranking.ts";
-export type EngineCheck = { ok: true } | ({ ok: false } & ServerErrorBody) | { ok: null };
+/** `reason`: the failure's kind, for the welcome's usage analytics; `error` stays the words people read. */
+export type EngineCheck = { ok: true } | ({ ok: false; reason?: AiTestReason } & ServerErrorBody) | { ok: null };
const PROMPT = "This is a connection check. Reply with the single word OK.";
const TIMEOUT_MS = 90_000;
@@ -20,6 +22,11 @@ export function engineCheckError(name: string, message: string): string {
return said ? `${name} couldn't answer: ${said}` : `${name} didn't answer. Check again in a minute.`;
}
+export function engineCheckReason(message: string): AiTestReason {
+ if (SIGNED_OUT.test(message)) return "signed_out";
+ return engineFailureKind(message) ?? "other";
+}
+
const running = new Map<string, Promise<EngineCheck>>();
export type CheckableEngine = Pick<ProviderInstance, "instanceId" | "displayName" | "driverKind" | "generateText" | "generateMemoryText">;
@@ -38,13 +45,16 @@ export function checkEngine(instance: CheckableEngine, options: { timeoutMs?: nu
const stop = new AbortController();
const timer = setTimeout(() => {
stop.abort();
- resolve({ ok: false, ...userError("serverError.engineCheck.timeout", { name, seconds: String(Math.round(timeoutMs / 1000)) }) });
+ resolve({ ok: false, reason: "timeout", ...userError("serverError.engineCheck.timeout", { name, seconds: String(Math.round(timeoutMs / 1000)) }) });
}, timeoutMs);
timer.unref?.();
// Wrapped so a call that throws synchronously fails the check too.
new Promise<string>((answer) => answer(call.call(instance, PROMPT, { timeoutMs, signal: stop.signal })))
- .then((answer): EngineCheck => answer.trim() ? { ok: true } : { ok: false, error: `${name} answered with nothing. Check again in a minute.` },
- (error): EngineCheck => ({ ok: false, error: engineCheckError(name, error instanceof Error ? error.message : String(error)) }))
+ .then((answer): EngineCheck => answer.trim() ? { ok: true } : { ok: false, reason: "empty", error: `${name} answered with nothing. Check again in a minute.` },
+ (error): EngineCheck => {
+ const message = error instanceof Error ? error.message : String(error);
+ return { ok: false, reason: engineCheckReason(message), error: engineCheckError(name, message) };
+ })
.then((result) => {
clearTimeout(timer);
resolve(result);
diff --git a/server/tested-ai.test.ts b/server/tested-ai.test.ts
index 0e7d8260e3..dda0429e3c 100644
--- a/server/tested-ai.test.ts
+++ b/server/tested-ai.test.ts
@@ -455,7 +455,7 @@ describe("testing an AI with one tiny message before a new bot's default trusts
// Check again: a sign-out the last status read hasn't seen yet still shows, with the reason.
answers.claude = async () => { throw new Error("Not logged in · Please run /login"); };
await expect(tested.check(live)).resolves.toMatchObject({ ok: false });
- expect(tested.info(instances[1]!)).toEqual({ aiTest: "failed", aiTestError: "claude isn't signed in on this computer anymore. Sign in again, then check again." });
+ expect(tested.info(instances[1]!)).toEqual({ aiTest: "failed", aiTestError: "claude isn't signed in on this computer anymore. Sign in again, then check again.", aiTestReason: "signed_out" });
});
it("sends nothing in the background where it is switched off, and still checks on request", async () => {
diff --git a/server/tested-ai.ts b/server/tested-ai.ts
index 2819db11d3..b484552f61 100644
--- a/server/tested-ai.ts
+++ b/server/tested-ai.ts
@@ -14,7 +14,7 @@
import { createHash } from "node:crypto";
import { mkdirSync, readFileSync } from "node:fs";
import { dirname } from "node:path";
-import { aiSignInKey, rankAis, type AiTestState } from "../shared/ai-ranking.ts";
+import { AI_TEST_REASONS, aiSignInKey, rankAis, type AiTestReason, type AiTestState } from "../shared/ai-ranking.ts";
import { writeFileAtomic } from "./atomic.ts";
import type { ModelSelection, ProviderSnapshot } from "./contracts.ts";
import { readyToRun, signedOut, type DefaultSelectionContext, type SelectableInstance } from "./default-model-selection.ts";
@@ -73,7 +73,7 @@ export function configIdentity(entry: { driver?: unknown; config?: unknown; envi
}
type Subject = { instanceId: string; snapshot: ProviderSnapshot };
-type Result = { key: string; state: "passed" | "failed" | "untestable"; misses: number; at: number; error?: string; retryAt?: number };
+type Result = { key: string; state: "passed" | "failed" | "untestable"; misses: number; at: number; error?: string; reason?: AiTestReason; retryAt?: number };
type Follower = { botId: string; selection: ModelSelection };
type Saved = { results: Record<string, Result>; follower?: Follower };
@@ -169,7 +169,7 @@ export function createTestedAi(deps: TestedAiDeps) {
if (check.ok === false) {
const misses = (previous?.state === "failed" ? previous.misses : 0) + 1;
const delay = RETRY_AFTER_MS[misses - 1] ?? SLOW_RETRY_MS;
- saved.results[instanceId] = { key, state: "failed", misses, at: now(), error: check.error, retryAt: now() + delay };
+ saved.results[instanceId] = { key, state: "failed", misses, at: now(), error: check.error, ...(check.reason ? { reason: check.reason } : {}), retryAt: now() + delay };
if (background) arm(instanceId, now() + delay);
} else {
retries.get(instanceId)?.cancel();
@@ -326,10 +326,11 @@ export function createTestedAi(deps: TestedAiDeps) {
answered,
state,
/** The instance info's fields the welcome reads. */
- info(instance: Subject): { aiTest?: AiTestState; aiTestError?: string } {
+ info(instance: Subject): { aiTest?: AiTestState; aiTestError?: string; aiTestReason?: AiTestReason } {
const result = state(instance);
- const error = result === "failed" ? resultOf(instance)?.error : undefined;
- return result ? { aiTest: result, ...(error ? { aiTestError: error } : {}) } : {};
+ const failed = result === "failed" ? resultOf(instance) : undefined;
+ const reason = failed?.reason && AI_TEST_REASONS.includes(failed.reason) ? failed.reason : undefined;
+ return result ? { aiTest: result, ...(failed?.error ? { aiTestError: failed.error } : {}), ...(reason ? { aiTestReason: reason } : {}) } : {};
},
/** POST /api/instances/:id/check: live, as setup's check always was, sharing only a test already under way. */
async check(instance: CheckableEngine & { snapshot(): Promise<ProviderSnapshot> }): Promise<EngineCheck> {
diff --git a/shared/ai-ranking.ts b/shared/ai-ranking.ts
index 7764703ffc..8172466fed 100644
--- a/shared/ai-ranking.ts
+++ b/shared/ai-ranking.ts
@@ -11,6 +11,12 @@ export interface RankableAi {
/** What a test message through an AI showed: `untestable` is an AI with no one-off call to send one, trusted as before. */
export type AiTestState = "testing" | "passed" | "failed" | "untestable";
+/** Why a test message failed, as a word from a fixed list: never the provider's text. */
+export const AI_TEST_REASONS = [
+ "signed_out", "timeout", "empty", "credits", "usage_limit", "rate_limit", "overloaded", "server", "tool_schema", "tool_count",
+ "model_no_route", "refused", "other",
+] as const;
+export type AiTestReason = (typeof AI_TEST_REASONS)[number];
const TIERS: Readonly<Record<string, number>> = {
claudeAgent: 0,
diff --git a/src/App.tsx b/src/App.tsx
index 5f9ca07b27..e0f0f680ce 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -14,6 +14,7 @@ import { GuidedTour } from "@/components/onboarding/GuidedTour";
import { LiveCallHost } from "@/components/LiveCallHost";
import { ThreadRefsProvider } from "@/components/ThreadRefs";
import { initAnalytics } from "@/lib/analytics";
+import { useAppLoadSignal } from "@/lib/app-load";
import { cloudAccountBridge, openCloudOnWeb } from "@/lib/cloud-add-web";
import { parseComputerHelp } from "@/lib/computer-control";
import { viewerClosedRelease } from "@/components/computer-takeover";
@@ -494,6 +495,11 @@ function Shell({ viewer }: { viewer: WelcomeViewer | null }) {
);
}
+function AppLoadSignal() {
+ useAppLoadSignal();
+ return null;
+}
+
function Application() {
useEffect(() => {
initAnalytics();
@@ -502,6 +508,7 @@ function Application() {
return (
<DesktopCapabilitiesProvider>
<StoreProvider>
+ <AppLoadSignal />
<ThreadRefsProvider>
<Shell viewer={viewer} />
</ThreadRefsProvider>
diff --git a/src/components/ClaudeSignIn.tsx b/src/components/ClaudeSignIn.tsx
index 404ca1b084..1c91fdc288 100644
--- a/src/components/ClaudeSignIn.tsx
+++ b/src/components/ClaudeSignIn.tsx
@@ -29,10 +29,12 @@ function ended(phase: "expired" | "failed", message?: string): DeviceSignInStatu
}
/** `autoStart` begins at once and opens Anthropic's page; `onDone` hears the outcome so an account list can close it. */
-export function ClaudeSignIn({ instanceId, autoStart = false, onDone }: {
+export function ClaudeSignIn({ instanceId, autoStart = false, onDone, onStart }: {
instanceId: string;
autoStart?: boolean;
onDone?: (signedIn: boolean) => void;
+ /** A sign-in is starting. */
+ onStart?: () => void;
}) {
const { refreshInstances, refreshModels } = useStore();
const [auth, setAuth] = useState<DeviceSignInStatus | null>(null);
@@ -64,6 +66,7 @@ export function ClaudeSignIn({ instanceId, autoStart = false, onDone }: {
const start = async () => {
setBusy("start");
setError(null);
+ onStart?.();
try {
const { auth: next }: { auth: DeviceSignInStatus } = await api(`${base}/start`, { method: "POST" });
setCode("");
diff --git a/src/components/DeviceSignIn.tsx b/src/components/DeviceSignIn.tsx
index 6d5ca1a3af..124a6a6277 100644
--- a/src/components/DeviceSignIn.tsx
+++ b/src/components/DeviceSignIn.tsx
@@ -151,12 +151,14 @@ export function DeviceSignInProgress({ auth, browserPkce = false, provider = "co
}
/** `autoStart` begins at once; `onDone` hears the outcome so an account list can close the panel. */
-export function DeviceSignIn({ instanceId, browserPkce = false, provider = "codex", autoStart = false, onDone }: {
+export function DeviceSignIn({ instanceId, browserPkce = false, provider = "codex", autoStart = false, onDone, onStart }: {
instanceId: string;
browserPkce?: boolean;
provider?: DeviceSignInProvider;
autoStart?: boolean;
onDone?: (signedIn: boolean) => void;
+ /** A sign-in is starting. */
+ onStart?: () => void;
}) {
const { refreshInstances, refreshModels } = useStore();
const [auth, setAuth] = useState<DeviceSignInStatus | null>(null);
@@ -211,6 +213,7 @@ export function DeviceSignIn({ instanceId, browserPkce = false, provider = "code
const start = async () => {
setBusy(true);
setError(null);
+ onStart?.();
try {
const { auth: next }: { auth: DeviceSignInStatus } = await api(`${base}/start`, { method: "POST" });
setAuth(next);
diff --git a/src/components/EngineBrowserSignIn.tsx b/src/components/EngineBrowserSignIn.tsx
index 29b7083d64..31fd9cfdd3 100644
--- a/src/components/EngineBrowserSignIn.tsx
+++ b/src/components/EngineBrowserSignIn.tsx
@@ -15,10 +15,12 @@ function ended(phase: "failed" | "expired"): DeviceSignInStatus {
}
/** A start button, a spinner while the person finishes in their browser, and the outcome. */
-export function EngineBrowserSignIn({ instanceId, autoStart = false, onDone }: {
+export function EngineBrowserSignIn({ instanceId, autoStart = false, onDone, onStart }: {
instanceId: string;
autoStart?: boolean;
onDone?: (signedIn: boolean) => void;
+ /** A sign-in is starting. */
+ onStart?: () => void;
}) {
const { refreshInstances, refreshModels } = useStore();
const [auth, setAuth] = useState<DeviceSignInStatus | null>(null);
@@ -72,6 +74,7 @@ export function EngineBrowserSignIn({ instanceId, autoStart = false, onDone }: {
const start = async () => {
setBusy(true);
setError(null);
+ onStart?.();
try {
const { auth: next }: { auth: DeviceSignInStatus } = await api(`${base}/start`, { method: "POST" });
setAuth(next);
diff --git a/src/components/EngineLiveCheck.tsx b/src/components/EngineLiveCheck.tsx
index 2d77e600ae..b9e3fdc6da 100644
--- a/src/components/EngineLiveCheck.tsx
+++ b/src/components/EngineLiveCheck.tsx
@@ -6,8 +6,9 @@ import { api, type InstanceInfo } from "@/state/store";
import { serverErrorText } from "@/lib/server-error";
import type { ServerErrorBody } from "../../shared/server-text";
-export type EngineLiveCheck = { state: "checking" } | { state: "working" } | ({ state: "failed" } & ServerErrorBody);
-type Answer = { ok: true } | ({ ok: false } & ServerErrorBody) | { ok: null };
+/** `reason`: why it failed as a word from a fixed list, for usage analytics. */
+export type EngineLiveCheck = { state: "checking" } | { state: "working" } | ({ state: "failed"; reason?: string } & ServerErrorBody);
+type Answer = { ok: true } | ({ ok: false; reason?: string } & ServerErrorBody) | { ok: null };
/** Right after one of these engines is connected here, one tiny real message checks that it answers. An engine already
* connected when this first renders is left alone. */
@@ -19,7 +20,7 @@ export function useEngineLiveCheck(engines: readonly InstanceInfo[]) {
let next: EngineLiveCheck | null;
try {
const answer = await api<Answer>(`/api/instances/${encodeURIComponent(instanceId)}/check`, { method: "POST", body: "{}", timeoutMs: 120_000 });
- next = answer.ok === true ? { state: "working" } : answer.ok === false ? { state: "failed", error: answer.error, errorKey: answer.errorKey, errorParams: answer.errorParams } : null;
+ next = answer.ok === true ? { state: "working" } : answer.ok === false ? { state: "failed", error: answer.error, errorKey: answer.errorKey, errorParams: answer.errorParams, reason: answer.reason ?? "other" } : null;
} catch (error) {
next = { state: "failed", error: error instanceof Error ? error.message : String(error) };
}
diff --git a/src/components/EngineSetup.tsx b/src/components/EngineSetup.tsx
index 4ae5e1cba9..7bb76932fb 100644
--- a/src/components/EngineSetup.tsx
+++ b/src/components/EngineSetup.tsx
@@ -2,6 +2,7 @@ import { useEffect, useState } from "react";
import { AlertTriangle, Check, Copy, Download, ExternalLink, KeyRound, Loader2, LogIn, TerminalSquare, X } from "lucide-react";
import { api, ApiError, type InstanceInfo, useStore } from "@/state/store";
import { cn } from "@/lib/cn";
+import { useSignInStarted } from "@/lib/connect-ai-events";
import { t } from "@/lib/i18n";
import { engineDisplayName } from "@/lib/engine-name";
import { copyText } from "@/lib/copy-text";
@@ -273,6 +274,7 @@ export function EngineWarningNotice({
function ManagedEngineSetup({ instance, signInOnly }: { instance: InstanceInfo; signInOnly: boolean }) {
const { state, refreshInstances, refreshModels } = useStore();
+ const signInStarted = useSignInStarted(instance.instanceId);
const [busy, setBusy] = useState<"install" | "signin" | "complete" | "check" | null>(null);
const [error, setError] = useState<string | null>(null);
const [flow, setFlow] = useState<{ flowId: string; authorizationUrl: string } | null>(null);
@@ -331,6 +333,7 @@ function ManagedEngineSetup({ instance, signInOnly }: { instance: InstanceInfo;
const signIn = () => run("signin", async () => {
if (flow) return openLink(flow.authorizationUrl);
+ signInStarted();
const { auth } = await api(`/api/instances/${encodeURIComponent(instance.instanceId)}/auth/start`, { method: "POST" });
if (auth.phase === "succeeded") {
await refreshInstances();
@@ -564,6 +567,7 @@ export function EngineSetup({
onHost?: boolean;
}) {
const { state } = useStore();
+ const signInStarted = useSignInStarted(instance.instanceId);
const cloudHome = state.config?.cloudHome === true;
const install = instance.install;
const installCommand = installCommandFor(install);
@@ -664,10 +668,10 @@ export function EngineSetup({
))}
{engineBrowserSignIn ? (
- <EngineBrowserSignIn key={instance.instanceId} instanceId={instance.instanceId} />
+ <EngineBrowserSignIn key={instance.instanceId} instanceId={instance.instanceId} onStart={signInStarted} />
) : deviceSignIn || browserSignIn ? (
<>
- <DeviceSignIn key={instance.instanceId} instanceId={instance.instanceId} browserPkce={browserSignIn} provider={provider} />
+ <DeviceSignIn key={instance.instanceId} instanceId={instance.instanceId} browserPkce={browserSignIn} provider={provider} onStart={signInStarted} />
{deviceSignIn && provider !== "codex" && signInCommand && serverTerminal(cloudHome) && (
<details className="mt-2 rounded-lg border border-hairline/50 bg-app px-2.5 py-2 text-[12px] text-ink-secondary">
<summary className="cursor-pointer select-none">{t("engineSetup.preferTerminal")}</summary>
@@ -676,7 +680,7 @@ export function EngineSetup({
)}
</>
) : pasteSignIn ? (
- <ClaudeSignIn key={instance.instanceId} instanceId={instance.instanceId} />
+ <ClaudeSignIn key={instance.instanceId} instanceId={instance.instanceId} onStart={signInStarted} />
) : install.server && !signInOnly ? (
<ServerEngineInstall instance={instance} mode="install" command={installCommand} />
) : install.managed ? (
diff --git a/src/components/HelperSetup.tsx b/src/components/HelperSetup.tsx
index 8b949dcbb2..35822d8a0b 100644
--- a/src/components/HelperSetup.tsx
+++ b/src/components/HelperSetup.tsx
@@ -9,6 +9,7 @@ import type { LocaleKey } from "@/locales";
import { useStore, type Action } from "@/state/store";
import { engineReady } from "./EngineLibrary";
import { ConnectAiDialog } from "./onboarding/ConnectAi";
+import { ConnectAiPlaceContext } from "@/lib/connect-ai-events";
import { useWelcomeAi } from "./onboarding/welcome-ai";
const STEPS: Record<SetupStep, { label: LocaleKey; icon: LucideIcon }> = {
@@ -83,7 +84,9 @@ export function chipAction(chip: Exclude<IntroChip, "ai">): Action {
function IntroConnectAi({ onClose }: { onClose: () => void }) {
const { state } = useStore();
const [chosen, setChosen] = useState<string | null>(null);
- return <ConnectAiDialog tested={useWelcomeAi(state.instances, true, chosen)} onChoose={setChosen} onClose={onClose} />;
+ return <ConnectAiPlaceContext.Provider value="chat">
+ <ConnectAiDialog tested={useWelcomeAi(state.instances, true, chosen, "chat")} onChoose={setChosen} onClose={onClose} />
+ </ConnectAiPlaceContext.Provider>;
}
/** What is still missing, as chips under MausBot's follow-up (Simple mode): at most INTRO_CHIPS, and one that was tapped
diff --git a/src/components/HomeLine.tsx b/src/components/HomeLine.tsx
index 61db059bfe..17bcc5e6bf 100644
--- a/src/components/HomeLine.tsx
+++ b/src/components/HomeLine.tsx
@@ -3,6 +3,7 @@ import { Cloud, Laptop, Users, X } from "lucide-react";
import { freeFallback } from "../../shared/ai-ranking";
import { engineReady } from "@/components/EngineLibrary";
import { ConnectAiDialog } from "@/components/onboarding/ConnectAi";
+import { ConnectAiPlaceContext } from "@/lib/connect-ai-events";
import { t } from "@/lib/i18n";
import { HOME_LINE_NOTICE, homeLineShown, homeLineStage } from "@/lib/notices";
import { hintSeenPatch } from "@/lib/onboarding";
@@ -25,7 +26,7 @@ function ConnectAiLink() {
const [open, setOpen] = useState(false);
return <>
<button type="button" data-home-line-ai className="underline underline-offset-2 hover:text-ink" onClick={() => setOpen(true)}>{t("onboarding.meet.connectAi")}</button>
- {open && <ConnectAiDialog tested={null} onClose={() => setOpen(false)} />}
+ {open && <ConnectAiPlaceContext.Provider value="home_line"><ConnectAiDialog tested={null} onClose={() => setOpen(false)} /></ConnectAiPlaceContext.Provider>}
</>;
}
diff --git a/src/components/PageBoundary.tsx b/src/components/PageBoundary.tsx
index 249221fa31..b5afe14568 100644
--- a/src/components/PageBoundary.tsx
+++ b/src/components/PageBoundary.tsx
@@ -1,5 +1,6 @@
import { Component, type ReactNode } from "react";
+import { initAnalytics, track } from "@/lib/analytics";
import { t } from "@/lib/i18n";
// React unmounts everything below a root that has no error boundary when a render or an effect throws (react.dev,
@@ -11,6 +12,11 @@ export class PageBoundary extends Component<{ children: ReactNode }, { error: Er
return { error: error instanceof Error ? error : new Error(String(error)) };
}
+ componentDidCatch() {
+ void initAnalytics();
+ track("app_load", { stage: "error" });
+ }
+
render() {
if (!this.state.error) return this.props.children;
return (
diff --git a/src/components/cloud-welcome/WelcomeSteps.tsx b/src/components/cloud-welcome/WelcomeSteps.tsx
index 234ec12fb5..371fb32ad3 100644
--- a/src/components/cloud-welcome/WelcomeSteps.tsx
+++ b/src/components/cloud-welcome/WelcomeSteps.tsx
@@ -3,14 +3,15 @@ import { Check, ChevronDown, CircleAlert, FolderOpen, Plug } from "lucide-react"
import { cloudEngineChoices, useCloudEngineChoices } from "@/components/CloudEngineSignIn";
import { useCloudPlanSnapshot } from "@/components/CloudTrialNotice";
import { engineReady } from "@/components/EngineLibrary";
-import { EngineCheckLine } from "@/components/EngineLiveCheck";
+import { EngineCheckLine, type EngineLiveCheck } from "@/components/EngineLiveCheck";
import { EngineSetup } from "@/components/EngineSetup";
import { usd } from "@/lib/cloud-plan";
import { welcomeCredit } from "@/lib/cloud-welcome";
import { cn } from "@/lib/cn";
+import { connectAiStep, ConnectAiPlaceContext, useConnectAiSteps } from "@/lib/connect-ai-events";
import { t } from "@/lib/i18n";
import { firstAis, signInFollows } from "@/lib/onboarding";
-import { useStore, type Bot } from "@/state/store";
+import { useStore, type Bot, type InstanceInfo } from "@/state/store";
import { CARD, CARD_IDLE, CardIcon, Footer, PRIMARY, QUIET, SECONDARY, StepHeading } from "./parts";
/** Connecting an AI: an AI that already works when the step opens (one signed in here, or the plan's credit) is used as
@@ -23,15 +24,18 @@ export function WelcomeEngine({ name, headingRef, onFinish }: { name: string; he
const credit = own ? null : welcomeCredit(engines.instances, plan);
const readyOnOpen = useRef(own || credit?.state === "active");
const [more, setMore] = useState(false);
+ const step = useConnectAiSteps("cloud_welcome");
useEffect(() => {
+ step("opened", { aiReady: readyOnOpen.current });
if (readyOnOpen.current) onFinish();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
+ useCheckSteps(engines.live.checks, engines.instances);
if (readyOnOpen.current) return null;
const first = firstAis(engines.instances, engineReady);
const shown = new Set(first.map(({ instance }) => instance.driverKind));
const others = { ...engines, choices: engines.choices.filter((choice) => !shown.has(choice.driverKind)) };
- return <section aria-labelledby="cloud-welcome-step" data-welcome-step="engine" className="flex flex-col">
+ return <ConnectAiPlaceContext.Provider value="cloud_welcome"><section aria-labelledby="cloud-welcome-step" data-welcome-step="engine" className="flex flex-col">
<StepHeading headingRef={headingRef} title={t("cloudSetup.engine.title")} sub={t("cloudWelcome.engine.sub", { name })} />
{credit?.state === "active" && <p role="status" data-welcome-credit className="mt-5 flex items-start gap-2.5 rounded-xl bg-success/12 px-3.5 py-3 text-[13px] leading-relaxed text-ink">
<Check size={16} strokeWidth={2.5} aria-hidden="true" className="mt-px shrink-0 text-success" />
@@ -44,7 +48,8 @@ export function WelcomeEngine({ name, headingRef, onFinish }: { name: string; he
{first.map(({ kind, instance }, index) => {
const name = kind === "chatgpt" ? t("cloudSignIn.codex") : instance.displayName;
const check = engines.live.checks[instance.instanceId];
- return <div key={kind} data-welcome-recommended={instance.instanceId} className={cn(index ? "mt-3" : "mt-6", "rounded-2xl border border-hairline/50 bg-card px-4 py-4")}>
+ return <div key={kind} data-welcome-recommended={instance.instanceId} className={cn(index ? "mt-3" : "mt-6", "rounded-2xl border border-hairline/50 bg-card px-4 py-4")}
+ onClickCapture={() => step("chosen", { driverKind: instance.driverKind })}>
{engineReady(instance)
? check && <EngineCheckLine name={name} check={check} onRetry={() => void engines.live.run(instance.instanceId)} />
: <EngineSetup instance={instance} unframed description={signInFollows(instance) ? t("onboarding.engines.signInHint", { name }) : undefined} />}
@@ -61,9 +66,30 @@ export function WelcomeEngine({ name, headingRef, onFinish }: { name: string; he
? <button type="button" className={PRIMARY} onClick={onFinish}>{t("onboarding.continue")}</button>
: credit?.state === "active"
? <button type="button" className={PRIMARY} onClick={onFinish}>{t("cloudWelcome.engine.useCredit")}</button>
- : <button type="button" className={QUIET} onClick={onFinish}>{t("cloudIntent.skip")}</button>}
+ : <button type="button" className={QUIET} onClick={() => { step("later"); onFinish(); }}>{t("cloudIntent.skip")}</button>}
</Footer>
- </section>;
+ </section></ConnectAiPlaceContext.Provider>;
+}
+
+/** A test message the step's setups sent (right after a sign-in) ending, once each time. */
+function useCheckSteps(checks: Record<string, EngineLiveCheck>, instances: readonly InstanceInfo[]) {
+ const before = useRef<Record<string, EngineLiveCheck>>({});
+ const started = useRef<Record<string, number>>({});
+ useEffect(() => {
+ for (const [instanceId, check] of Object.entries(checks)) {
+ const was = before.current[instanceId];
+ const driverKind = instances.find((instance) => instance.instanceId === instanceId)?.driverKind ?? "";
+ if (check.state === "checking" && was?.state !== "checking") {
+ started.current[instanceId] = Date.now();
+ connectAiStep("test_started", "cloud_welcome", { driverKind });
+ }
+ if (check.state === "checking" || was?.state !== "checking") continue;
+ const seconds = (Date.now() - (started.current[instanceId] ?? Date.now())) / 1000;
+ connectAiStep(check.state === "working" ? "test_ok" : "test_failed", "cloud_welcome",
+ { driverKind, seconds, ...(check.state === "failed" ? { reason: check.reason ?? "other" } : {}) });
+ }
+ before.current = checks;
+ }, [checks, instances]);
}
/** "folders": in the app on a Cloud of the person's own, this computer is lent to it by itself; from a browser or on a
diff --git a/src/components/onboarding/ConnectAi.tsx b/src/components/onboarding/ConnectAi.tsx
index 810fa9e447..d2bcea0eec 100644
--- a/src/components/onboarding/ConnectAi.tsx
+++ b/src/components/onboarding/ConnectAi.tsx
@@ -5,6 +5,7 @@ import { engineReady } from "@/components/EngineLibrary";
import { InstanceProviderMark } from "@/components/ProviderIcons";
import { ModelgoOption } from "@/components/ModelgoOffer";
import { cn } from "@/lib/cn";
+import { useConnectAiPlace, useConnectAiSteps, useDialogOpened } from "@/lib/connect-ai-events";
import { t } from "@/lib/i18n";
import { engineDisplayName } from "@/lib/engine-name";
import { modelgoOfferable } from "@/lib/modelgo-offer";
@@ -54,6 +55,7 @@ export function ConnectAi({ hosted = false, tested, onChoose }: { hosted?: boole
const [checking, setChecking] = useState(false);
const [open, setOpen] = useState<string | null>(null);
const latestRequest = useRef(0);
+ const step = useConnectAiSteps(useConnectAiPlace());
const refresh = useCallback(async (fresh = true) => {
const request = ++latestRequest.current;
@@ -129,7 +131,7 @@ export function ConnectAi({ hosted = false, tested, onChoose }: { hosted?: boole
<div className="flex w-full flex-col gap-3">
{leading.map((instance) => (
<div key={instance.instanceId} data-ai-recommended={instance.instanceId} className="animate-rise w-full rounded-2xl bg-card p-4 text-left"
- onClickCapture={() => onChoose?.(instance.instanceId)}>
+ onClickCapture={() => { step("chosen", { driverKind: instance.driverKind }); onChoose?.(instance.instanceId); }}>
<EngineSetup instance={instance} {...setupFor(instance)} className="border-0 bg-transparent p-0" />
</div>
))}
@@ -150,12 +152,18 @@ export function ConnectAi({ hosted = false, tested, onChoose }: { hosted?: boole
onConnected={() => void refresh()}
/>
)}
- {showModelgo && <ModelgoOption open={open === "modelgo"} onToggle={() => setOpen(open === "modelgo" ? null : "modelgo")}>
+ {showModelgo && <ModelgoOption open={open === "modelgo"} onToggle={() => {
+ if (open !== "modelgo") step("chosen", { driverKind: "modelgo" });
+ setOpen(open === "modelgo" ? null : "modelgo");
+ }}>
{modelgo && <EngineSetup instance={modelgo} {...setupFor(modelgo)} className="mx-4 mb-3.5 border-0 bg-inset" />}
</ModelgoOption>}
{otherRows.map((instance) => (
<OtherWay key={instance.instanceId} instance={instance} open={open === instance.instanceId}
- onToggle={() => setOpen(open === instance.instanceId ? null : instance.instanceId)} />
+ onToggle={() => {
+ if (open !== instance.instanceId) step("chosen", { driverKind: instance.driverKind });
+ setOpen(open === instance.instanceId ? null : instance.instanceId);
+ }} />
))}
<button
type="button"
@@ -176,6 +184,7 @@ export function ConnectAi({ hosted = false, tested, onChoose }: { hosted?: boole
export function ConnectAiDialog({ hosted = false, tested, onChoose, onClose }: {
hosted?: boolean; tested: WelcomeAiNow | null; onChoose?: (instanceId: string) => void; onClose: () => void;
}) {
+ useDialogOpened(useConnectAiPlace());
return (
<div
className="ui-scrim fixed inset-0 z-[60] flex items-center justify-center p-4"
diff --git a/src/components/onboarding/MeetScreen.tsx b/src/components/onboarding/MeetScreen.tsx
index 0b5e7dd7ab..6b6a1c1832 100644
--- a/src/components/onboarding/MeetScreen.tsx
+++ b/src/components/onboarding/MeetScreen.tsx
@@ -5,6 +5,7 @@ import { engineReady } from "@/components/EngineLibrary";
import { usePrefersReducedMotion } from "@/components/mascot-clock";
import { brand, productName } from "@/lib/brand";
import { cn } from "@/lib/cn";
+import { ConnectAiPlaceContext, useConnectAiSteps } from "@/lib/connect-ai-events";
import { DEFAULT_BOT_NAME, myDefaultBot, useViewerEmail } from "@/lib/default-bot";
import { activeLocale, t } from "@/lib/i18n";
import { aiChoices, aiWorks, firstAis, type FirstAiKind } from "@/lib/onboarding";
@@ -63,13 +64,16 @@ export function MeetScreen({ hosted, onNext }: { hosted: boolean; onNext: () =>
const maus = myDefaultBot(state.bots, useViewerEmail());
// An AI counts once it answered a test message (or cannot be sent one); OpenCode's free model only once picked here.
const [chosen, setChosen] = useState<string | null>(null);
- const tested = useWelcomeAi(state.instances, !hosted, chosen);
+ const tested = useWelcomeAi(state.instances, !hosted, chosen, "meet");
const ready = aiWorks(tested);
const known = state.instances.length > 0;
const [asking, setAsking] = useState(false);
+ const step = useConnectAiSteps("meet");
useEffect(() => {
- if (!hosted && known && !ready && tested?.state !== "testing") setAsking(true);
- }, [hosted, known, ready, tested?.state]);
+ if (hosted || !known || tested?.state === "testing") return;
+ step("opened", { aiReady: ready, ...(tested ? { driverKind: tested.instance.driverKind } : {}), ...(tested?.state === "failed" ? { reason: tested.reason ?? "other" } : {}) });
+ if (!ready) setAsking(true);
+ }, [hosted, known, ready, tested, step]);
const works = (instance: InstanceInfo) => aiRuns(instance) && !freeFallback(instance);
// Picked and installed, still listing its models: its pill waits until its test message.
const settling = (instance: InstanceInfo | undefined) => Boolean(instance && instance.instanceId === chosen && engineReady(instance) && !aiRuns(instance));
@@ -78,9 +82,9 @@ export function MeetScreen({ hosted, onNext }: { hosted: boolean; onNext: () =>
const choice = (kind: FirstAiKind) => first.find((entry) => entry.kind === kind)?.instance;
const lead = first.length ? undefined : recommended;
const pills = {
- claude: useSignInPill(choice("claude") ?? lead),
- chatgpt: useSignInPill(choice("chatgpt")),
- opencode: useSignInPill(choice("opencode")),
+ claude: useSignInPill(choice("claude") ?? lead, "meet"),
+ chatgpt: useSignInPill(choice("chatgpt"), "meet"),
+ opencode: useSignInPill(choice("opencode"), "meet"),
};
const shown = first.length ? first : [{ kind: "claude" as const, instance: lead }];
const [dialog, setDialog] = useState(false);
@@ -94,6 +98,7 @@ export function MeetScreen({ hosted, onNext }: { hosted: boolean; onNext: () =>
?? (tested?.state === "failed" ? tested.error ?? t("onboarding.engines.noAnswer", { name: tested.instance.displayName }) : null);
const signingIn = asking && !ready;
return (
+ <ConnectAiPlaceContext.Provider value="meet">
<div className="relative h-full min-h-[600px] w-full text-center">
<h1 id="welcome-title" className="absolute left-1/2 top-[calc(50%-264px)] w-max max-w-[min(560px,calc(100%-32px))] -translate-x-1/2 text-[28px] font-normal leading-[34px] tracking-[-0.02em] text-ink">
{t("onboarding.meet.title", { app: productName() })}
@@ -139,12 +144,13 @@ export function MeetScreen({ hosted, onNext }: { hosted: boolean; onNext: () =>
<p className="mt-3 text-[13px] leading-[18px] text-ink-secondary">
<button type="button" onClick={() => setDialog(true)} className="rounded transition-colors hover:text-ink">{t("onboarding.meet.otherWays")}</button>
<span aria-hidden="true"> · </span>
- <button type="button" data-welcome-later="" onClick={onNext} className="rounded transition-colors hover:text-ink">{t("onboarding.meet.setupLater")}</button>
+ <button type="button" data-welcome-later="" onClick={() => { step("later"); onNext(); }} className="rounded transition-colors hover:text-ink">{t("onboarding.meet.setupLater")}</button>
</p>
)}
{signingIn && failure && <p role="alert" className="mt-2 text-[13px] leading-[18px] text-danger">{failure}</p>}
</div>
{dialog && <ConnectAiDialog hosted={hosted} tested={tested} onChoose={setChosen} onClose={() => setDialog(false)} />}
</div>
+ </ConnectAiPlaceContext.Provider>
);
}
diff --git a/src/components/onboarding/SignInPill.tsx b/src/components/onboarding/SignInPill.tsx
index 8a4fd9d63f..1d14d483a1 100644
--- a/src/components/onboarding/SignInPill.tsx
+++ b/src/components/onboarding/SignInPill.tsx
@@ -5,6 +5,8 @@ import { chatgptPlanLink, deviceSignInProvider, type DeviceSignInStatus } from "
import { engineReady } from "@/components/EngineLibrary";
import { needsSignIn } from "@/components/EngineSetup";
import { openExternalLink } from "@/lib/app-links";
+import type { ConnectAiPlace } from "@/lib/analytics-allowlist";
+import { connectAiStep, useConnectAiPlace, useConnectAiSteps } from "@/lib/connect-ai-events";
import { useCopyFeedback } from "@/lib/copy-text";
import { t } from "@/lib/i18n";
import { plainSignIn } from "@/lib/onboarding";
@@ -37,8 +39,8 @@ export function pillWay(instance: InstanceInfo | undefined): "install" | "sign-i
/** One AI connected from the first screen's pill: installed (when the app installs it), signed in on the provider's
* page, and the code pasted or shown in the same place. A finished sign-in refreshes the AIs, where the welcome's test
- * message takes over. */
-export function useSignInPill(instance: InstanceInfo | undefined) {
+ * message takes over. `place` names the first-run flow for usage analytics. */
+export function useSignInPill(instance: InstanceInfo | undefined, place: ConnectAiPlace | null = null) {
const { refreshInstances, refreshModels } = useStore();
const [slot, setSlot] = useState<Slot>({ kind: "start" });
const [error, setError] = useState<string | null>(null);
@@ -77,6 +79,7 @@ export function useSignInPill(instance: InstanceInfo | undefined) {
const start = async () => {
setSlot({ kind: "busy" });
setError(null);
+ if (place) connectAiStep("sign_in_started", place, { driverKind: instance?.driverKind ?? "" });
try {
const { auth }: { auth: DeviceSignInStatus } = await api(`${base}/auth/start`, { method: "POST" });
if (auth.phase === "succeeded") return void await done();
@@ -204,6 +207,7 @@ export function SignInPill({ pill, instance, name = instance?.displayName ?? "",
onPick?: () => void;
}) {
const { slot, install, start, submit } = pill;
+ const step = useConnectAiSteps(useConnectAiPlace());
const look = quiet ? QUIET_PILL : PILL;
if (waiting || slot.kind === "busy" || slot.kind === "waiting") {
const link = slot.kind === "waiting" ? slot.link : null;
@@ -224,6 +228,7 @@ export function SignInPill({ pill, instance, name = instance?.displayName ?? "",
return (
<button type="button" data-primary={quiet ? undefined : ""} data-sign-in={way} className={look}
onClick={() => {
+ step("chosen", { driverKind: instance?.driverKind ?? "" });
onPick?.();
if (way === "install") void install();
else if (way === "sign-in") void start();
diff --git a/src/components/onboarding/welcome-ai.ts b/src/components/onboarding/welcome-ai.ts
index a93cca59a2..485bbd98ce 100644
--- a/src/components/onboarding/welcome-ai.ts
+++ b/src/components/onboarding/welcome-ai.ts
@@ -1,11 +1,13 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { aiSignInKey, type AiTestState } from "../../../shared/ai-ranking";
import { engineReady } from "@/components/EngineLibrary";
+import type { ConnectAiPlace } from "@/lib/analytics-allowlist";
+import { connectAiStep } from "@/lib/connect-ai-events";
import { welcomeAi } from "@/lib/onboarding";
import { api, type InstanceInfo } from "@/state/store";
-type Answer = { ok?: boolean | null; error?: string } | undefined;
-type Known = { state: AiTestState; error?: string };
+type Answer = { ok?: boolean | null; error?: string; reason?: string } | undefined;
+type Known = { state: AiTestState; error?: string; reason?: string };
const keyOf = (instance: InstanceInfo) => `${instance.instanceId}\n${aiSignInKey(instance.snapshot)}`;
/** As the new-bot default sees it: an AI that offers no model yet (OpenCode still listing them) can't run a bot. */
@@ -15,6 +17,8 @@ export const aiRuns = (instance: InstanceInfo) =>
export type WelcomeAiNow = NonNullable<ReturnType<typeof welcomeAi<InstanceInfo>>> & {
/** The plain reason its test failed, when it gave one (signed out, a used-up limit…). */
error?: string;
+ /** The same failure as a word from a fixed list, for usage analytics. */
+ reason?: string;
/** Check again: one more test message. */
retry(): void;
};
@@ -22,8 +26,10 @@ export type WelcomeAiNow = NonNullable<ReturnType<typeof welcomeAi<InstanceInfo>
/** The AI the welcome stands on (welcomeAi), after one tiny test message through the server's check when this sign-in
* hasn't had one: the server shares a test already under way, and its result also settles the new-bot default. A check
* that can't be made trusts the AI as before. `enabled` is false for a viewer who can't run checks; `chosen` is the AI the
- * person picked on the welcome, which counts even as OpenCode's free backup. */
-export function useWelcomeAi(instances: readonly InstanceInfo[], enabled = true, chosen: string | null = null): WelcomeAiNow | null {
+ * person picked on the welcome, which counts even as OpenCode's free backup; `place` names the first-run flow for usage
+ * analytics. */
+export function useWelcomeAi(instances: readonly InstanceInfo[], enabled = true, chosen: string | null = null,
+ place: ConnectAiPlace | null = null): WelcomeAiNow | null {
const [answers, setAnswers] = useState<Record<string, Known>>({});
const asked = useRef(new Set<string>());
const live = useRef(true);
@@ -33,35 +39,44 @@ export function useWelcomeAi(instances: readonly InstanceInfo[], enabled = true,
live.current = false;
};
}, []);
- const ask = useCallback((key: string) => {
+ const ask = useCallback((key: string, driverKind: string) => {
if (asked.current.has(key)) return;
asked.current.add(key);
const instanceId = key.slice(0, key.indexOf("\n"));
+ const started = Date.now();
+ if (place) connectAiStep("test_started", place, { driverKind });
void api<Answer>(`/api/instances/${encodeURIComponent(instanceId)}/check`, { method: "POST", body: "{}", timeoutMs: 120_000 })
.then((answer): Known => answer?.ok === true ? { state: "passed" } : answer?.ok === false
- ? { state: "failed", ...(answer.error ? { error: answer.error } : {}) } : { state: "untestable" }, (): Known => ({ state: "untestable" }))
+ ? { state: "failed", ...(answer.error ? { error: answer.error } : {}), reason: answer.reason ?? "other" } : { state: "untestable" },
+ (): Known => ({ state: "untestable" }))
.then((known) => {
+ if (place && known.state !== "untestable") {
+ connectAiStep(known.state === "passed" ? "test_ok" : "test_failed", place, { driverKind, seconds: (Date.now() - started) / 1000, reason: known.reason });
+ }
asked.current.delete(key);
if (live.current) setAnswers((current) => ({ ...current, [key]: known }));
});
- }, []);
+ }, [place]);
const known = (instance: InstanceInfo): Known | undefined => answers[keyOf(instance)]
- ?? (instance.aiTest && instance.aiTest !== "testing" ? { state: instance.aiTest, ...(instance.aiTestError ? { error: instance.aiTestError } : {}) } : undefined);
+ ?? (instance.aiTest && instance.aiTest !== "testing" ? { state: instance.aiTest, ...(instance.aiTestError ? { error: instance.aiTestError } : {}), ...(instance.aiTestReason ? { reason: instance.aiTestReason } : {}) }
+ : undefined);
const found = welcomeAi(instances, aiRuns, (instance) => known(instance)?.state, (instance) => instance.instanceId === chosen);
const asking = enabled && found?.state === "testing" ? keyOf(found.instance) : null;
+ const askingKind = found?.instance.driverKind ?? "";
useEffect(() => {
- if (asking) ask(asking);
- }, [asking, ask]);
+ if (asking) ask(asking, askingKind);
+ }, [asking, askingKind, ask]);
if (!found) return null;
const key = keyOf(found.instance);
- const error = found.state === "failed" ? known(found.instance)?.error : undefined;
+ const failure = found.state === "failed" ? known(found.instance) : undefined;
return {
...found,
- ...(error ? { error } : {}),
+ ...(failure?.error ? { error: failure.error } : {}),
+ ...(failure?.reason ? { reason: failure.reason } : {}),
retry: () => {
if (!enabled) return;
setAnswers((current) => ({ ...current, [key]: { state: "testing" } }));
- ask(key);
+ ask(key, found.instance.driverKind);
},
};
}
diff --git a/src/hooks/use-usage-snapshot.test.ts b/src/hooks/use-usage-snapshot.test.ts
index c855bd9dfc..0e5c195d08 100644
--- a/src/hooks/use-usage-snapshot.test.ts
+++ b/src/hooks/use-usage-snapshot.test.ts
@@ -157,14 +157,16 @@ describe("what the snapshot asks this page's app", () => {
vi.stubGlobal("ogb", { remoteClient: { active: true }, ...bridges });
await draw(ready({ webhookIngress: null }));
expect(asked).toEqual([]);
- expect(sent()[0]![1]).toMatchObject({ cloud_plan: "unknown", remote_client: true });
+ expect(sent()[0]![1]).toMatchObject({ remote_client: true });
+ expect(sent()[0]![1]).not.toHaveProperty("cloud_plan");
expect(sent()[0]![1]).not.toHaveProperty("webhooks");
});
it("asks nothing in a plain browser", async () => {
await draw(ready({ config: { ...ready().config!, cloudHome: true } }));
expect(asked).toEqual([]);
- expect(sent()[0]![1]).toMatchObject({ cloud_plan: "unknown", platform: "browser" });
+ expect(sent()[0]![1]).toMatchObject({ platform: "browser" });
+ expect(sent()[0]![1]).not.toHaveProperty("cloud_plan");
});
it("runs in the app shell, so every app page sends it", () => {
diff --git a/src/lib/analytics-allowlist.ts b/src/lib/analytics-allowlist.ts
index 45e2b364d0..9ba5b84c7e 100644
--- a/src/lib/analytics-allowlist.ts
+++ b/src/lib/analytics-allowlist.ts
@@ -86,3 +86,9 @@ export const TRIAL_CREDIT = ["active", "used_up", "ended", "none"] as const;
export const CLOUD_PLAN = ["starter", "personal", "pro", "max", "other", "none", "unknown"] as const;
export const EDITION = ["oss", "enterprise"] as const;
export const PLATFORM = ["desktop", "browser"] as const;
+export const CONNECT_AI_PLACE = ["meet", "chat", "home_line", "cloud_welcome"] as const;
+export type ConnectAiPlace = (typeof CONNECT_AI_PLACE)[number];
+export const CONNECT_AI_STEP = ["opened", "dialog_opened", "chosen", "sign_in_started", "test_started", "test_ok", "test_failed", "later"] as const;
+export type ConnectAiStep = (typeof CONNECT_AI_STEP)[number];
+export { AI_TEST_REASONS as AI_TEST_REASON } from "../../shared/ai-ranking";
+export const APP_LOAD_WAITING = ["server", "data", "settings"] as const;
diff --git a/src/lib/analytics.test.ts b/src/lib/analytics.test.ts
index f06e39c938..d6f13be893 100644
--- a/src/lib/analytics.test.ts
+++ b/src/lib/analytics.test.ts
@@ -178,7 +178,7 @@ describe("loading the client", () => {
it("says which app sent every event, and from which page, before the first one", async () => {
const fresh = await freshAnalytics();
await fresh.initAnalytics();
- expect(ph.registered).toEqual([{ app_version: appVersion(), surface: "server" }]);
+ expect(ph.registered).toEqual([{ app_version: appVersion(), surface: "server", platform: "browser" }]);
expect(appVersion()).toMatch(/^\d+\.\d+\.\d+/);
expect(ph.calls.indexOf("register")).toBeLessThan(ph.calls.indexOf("capture app_first_open"));
vi.stubGlobal("window", { ogb: { environments: {} } });
@@ -382,7 +382,7 @@ describe("app_active", () => {
await page.load();
expect(ph.calls).toEqual([...OPENED, "capture app_active"]);
expect(active()).toEqual([{ event: "app_active", props: { platform: "browser", mode: "simple" } }]);
- expect(ph.registered).toEqual([{ app_version: appVersion(), surface: "server" }]);
+ expect(ph.registered).toEqual([{ app_version: appVersion(), surface: "server", platform: "browser" }]);
expect(store.get(DAY)).toBe("2026-10-23");
page.fire("focus");
diff --git a/src/lib/analytics.ts b/src/lib/analytics.ts
index e2db6356fd..fac60c679c 100644
--- a/src/lib/analytics.ts
+++ b/src/lib/analytics.ts
@@ -110,8 +110,8 @@ function start(posthog: PostHog) {
// 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 });
client = posthog;
- posthog.register({ app_version: appVersion(), surface: analyticsSurface() });
const platform = pagePlatform();
+ posthog.register({ app_version: appVersion(), surface: analyticsSurface(), platform });
if (!localStorage.getItem("omb-installed")) {
localStorage.setItem("omb-installed", new Date().toISOString());
posthog.capture("app_first_open", { platform });
diff --git a/src/lib/app-load.ts b/src/lib/app-load.ts
new file mode 100644
index 0000000000..415f4bb919
--- /dev/null
+++ b/src/lib/app-load.ts
@@ -0,0 +1,39 @@
+import { useEffect, useRef } from "react";
+import { track } from "@/lib/analytics";
+import { allow, APP_LOAD_WAITING } from "@/lib/analytics-allowlist";
+import { useStore } from "@/state/store";
+
+export const SLOW_LOAD_MS = 30_000;
+
+type LoadState = { connected: boolean; hydrated?: true; config: unknown };
+
+export function loadWaitingFor(state: LoadState): (typeof APP_LOAD_WAITING)[number] | null {
+ if (!state.connected) return "server";
+ if (state.hydrated !== true) return "data";
+ return state.config === null || state.config === undefined ? "settings" : null;
+}
+
+const sincePageStart = () => Math.round(performance.now() / 100) / 10;
+
+/** Once per page: when the app has its server, its data and its settings (`ready`), or that it still waits for one of
+ * them SLOW_LOAD_MS after the page started (`slow`). */
+export function useAppLoadSignal(): void {
+ const { state } = useStore();
+ const waiting = loadWaitingFor(state);
+ const sent = useRef<{ ready?: true; slow?: true }>({});
+ const onboarded = Boolean(state.config?.onboarding?.completedAt);
+ useEffect(() => {
+ if (waiting !== null || sent.current.ready) return;
+ sent.current.ready = true;
+ track("app_load", { stage: "ready", seconds: sincePageStart(), onboarded });
+ }, [waiting, onboarded]);
+ useEffect(() => {
+ if (waiting === null || sent.current.ready || sent.current.slow) return;
+ const timer = setTimeout(() => {
+ if (sent.current.ready || sent.current.slow) return;
+ sent.current.slow = true;
+ track("app_load", { stage: "slow", waiting: allow(waiting, APP_LOAD_WAITING) });
+ }, Math.max(0, SLOW_LOAD_MS - performance.now()));
+ return () => clearTimeout(timer);
+ }, [waiting]);
+}
diff --git a/src/lib/connect-ai-events.test.ts b/src/lib/connect-ai-events.test.ts
new file mode 100644
index 0000000000..48d52183fc
--- /dev/null
+++ b/src/lib/connect-ai-events.test.ts
@@ -0,0 +1,85 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import { connectAiStep } from "./connect-ai-events";
+import { loadWaitingFor } from "./app-load";
+import { signInGateShown } from "./sign-in-gate";
+
+const ph = vi.hoisted(() => ({
+ captured: [] as Array<{ event: string; props: unknown }>,
+ module: () => ({
+ default: {
+ init: () => {},
+ has_opted_out_capturing: () => false,
+ opt_in_capturing: () => {},
+ opt_out_capturing: () => {},
+ register: () => {},
+ unregister: () => {},
+ capture: (event: string, props?: unknown) => void ph.captured.push({ event, props }),
+ identify: () => {},
+ },
+ }),
+}));
+vi.mock("posthog-js", () => ph.module());
+
+const store = new Map<string, string>();
+vi.stubGlobal("localStorage", {
+ getItem: (key: string) => store.get(key) ?? null,
+ setItem: (key: string, value: string) => void store.set(key, value),
+ removeItem: (key: string) => void store.delete(key),
+});
+
+const HOSTILE = "Claude isn't signed in for [email protected] with sk-ant-api03-SECRET0123456789";
+const sent = (event: string) => ph.captured.filter((entry) => entry.event === event).map((entry) => entry.props);
+
+beforeEach(async () => {
+ store.clear();
+ ph.captured = [];
+ const { initAnalytics } = await import("./analytics");
+ await initAnalytics();
+});
+
+describe("Connect an AI steps", () => {
+ it("names the engine by its kind and the failure by a word from its list, never the provider's text", () => {
+ connectAiStep("test_failed", "meet", { driverKind: "claudeAgent", reason: "signed_out", seconds: 12.4 });
+ connectAiStep("test_failed", "chat", { driverKind: "Ada's own engine", reason: HOSTILE });
+ connectAiStep("chosen", "cloud_welcome", { driverKind: "codex", reason: HOSTILE });
+ connectAiStep("opened", "meet", { aiReady: false });
+ expect(sent("connect_ai")).toEqual([
+ { step: "test_failed", place: "meet", engine: "claude", reason: "signed_out", seconds: 12 },
+ { step: "test_failed", place: "chat", engine: "other", reason: "other" },
+ { step: "chosen", place: "cloud_welcome", engine: "codex" },
+ { step: "opened", place: "meet", ai_ready: false },
+ ]);
+ expect(JSON.stringify(ph.captured)).not.toMatch(/ada@|sk-ant|Ada's/);
+ });
+
+ it("sends a step or a place it does not know as other", () => {
+ connectAiStep("sneaky" as never, "settings" as never);
+ expect(sent("connect_ai")).toEqual([{ step: "other", place: "other" }]);
+ });
+});
+
+describe("the app's load", () => {
+ it("says what it still waits for", () => {
+ expect(loadWaitingFor({ connected: false, config: null })).toBe("server");
+ expect(loadWaitingFor({ connected: true, config: null })).toBe("data");
+ expect(loadWaitingFor({ connected: true, hydrated: true, config: null })).toBe("settings");
+ expect(loadWaitingFor({ connected: true, hydrated: true, config: {} })).toBeNull();
+ });
+});
+
+describe("the sign-in gate", () => {
+ it("is counted on the desktop app's own page only", () => {
+ signInGateShown("signed_out");
+ expect(sent("sign_in_gate")).toEqual([]);
+ vi.stubGlobal("window", { ...globalThis.window, ogb: { environments: {} } });
+ try {
+ signInGateShown("service_trust");
+ signInGateShown("/pair?code=SECRET" as never);
+ } finally {
+ vi.unstubAllGlobals();
+ vi.stubGlobal("localStorage", { getItem: (key: string) => store.get(key) ?? null, setItem: (key: string, value: string) => void store.set(key, value), removeItem: (key: string) => void store.delete(key) });
+ }
+ expect(sent("sign_in_gate")).toEqual([{ reason: "service_trust" }, { reason: "other" }]);
+ });
+});
diff --git a/src/lib/connect-ai-events.ts b/src/lib/connect-ai-events.ts
new file mode 100644
index 0000000000..afa5f20dfe
--- /dev/null
+++ b/src/lib/connect-ai-events.ts
@@ -0,0 +1,53 @@
+import { createContext, useCallback, useContext, useEffect, useRef } from "react";
+import { track } from "@/lib/analytics";
+import {
+ AI_TEST_REASON, allow, CONNECT_AI_PLACE, CONNECT_AI_STEP, engineForDriver, type ConnectAiPlace, type ConnectAiStep,
+} from "@/lib/analytics-allowlist";
+import { useStore } from "@/state/store";
+
+/** Which first-run flow a Connect an AI control sits in. Outside one (Settings, the engine library) it is null and nothing
+ * is sent. */
+export const ConnectAiPlaceContext = createContext<ConnectAiPlace | null>(null);
+export const useConnectAiPlace = () => useContext(ConnectAiPlaceContext);
+
+export type ConnectAiFacts = { driverKind?: string; reason?: unknown; seconds?: number; aiReady?: boolean };
+
+export function connectAiStep(step: ConnectAiStep, place: ConnectAiPlace, facts: ConnectAiFacts = {}): void {
+ track("connect_ai", {
+ step: allow(step, CONNECT_AI_STEP),
+ place: allow(place, CONNECT_AI_PLACE),
+ ...(facts.driverKind !== undefined ? { engine: engineForDriver(facts.driverKind) } : {}),
+ ...(step === "test_failed" || (step === "opened" && facts.reason !== undefined) ? { reason: allow(facts.reason, AI_TEST_REASON) } : {}),
+ ...(typeof facts.seconds === "number" && Number.isFinite(facts.seconds) ? { seconds: Math.max(0, Math.round(facts.seconds)) } : {}),
+ ...(typeof facts.aiReady === "boolean" ? { ai_ready: facts.aiReady } : {}),
+ });
+}
+
+/** `connectAiStep` for one mounted control: `opened` once, every other step once for each engine (React's StrictMode
+ * mounts twice in development). */
+export function useConnectAiSteps(place: ConnectAiPlace | null) {
+ const sent = useRef(new Set<string>());
+ return useCallback((step: ConnectAiStep, facts: ConnectAiFacts = {}) => {
+ const key = step === "opened" ? step : `${step}\n${facts.driverKind ?? ""}`;
+ if (!place || sent.current.has(key)) return;
+ sent.current.add(key);
+ connectAiStep(step, place, facts);
+ }, [place]);
+}
+
+/** The Connect an AI dialog's own step, once for each time it opens. */
+export function useDialogOpened(place: ConnectAiPlace | null): void {
+ const sent = useRef(false);
+ useEffect(() => {
+ if (!place || sent.current) return;
+ sent.current = true;
+ connectAiStep("dialog_opened", place);
+ }, [place]);
+}
+
+/** A sign-in to an AI starting inside a first-run flow; elsewhere it sends nothing. */
+export function useSignInStarted(instanceId: string) {
+ const step = useConnectAiSteps(useConnectAiPlace());
+ const instances = useStore().state?.instances;
+ return () => step("sign_in_started", { driverKind: instances?.find((instance) => instance.instanceId === instanceId)?.driverKind ?? "" });
+}
diff --git a/src/lib/connect-ai-steps.test.ts b/src/lib/connect-ai-steps.test.ts
new file mode 100644
index 0000000000..5290a73280
--- /dev/null
+++ b/src/lib/connect-ai-steps.test.ts
@@ -0,0 +1,31 @@
+// @vitest-environment happy-dom
+import { act, createElement, useEffect } from "react";
+import { createRoot } from "react-dom/client";
+import { expect, it, vi } from "vitest";
+
+const sent = vi.hoisted(() => [] as Array<{ event: string; props: unknown }>);
+vi.mock("@/lib/analytics", () => ({ track: (event: string, props: unknown) => void sent.push({ event, props }) }));
+
+const { useConnectAiSteps } = await import("./connect-ai-events");
+
+it("sends opened once per screen, even when an AI connects after it, and other steps once per engine", async () => {
+ (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
+ function Screen({ engine }: { engine?: string }) {
+ const step = useConnectAiSteps("meet");
+ useEffect(() => {
+ step("opened", { aiReady: Boolean(engine), ...(engine ? { driverKind: engine } : {}) });
+ step("chosen", { driverKind: "claudeAgent" });
+ if (engine) step("chosen", { driverKind: engine });
+ });
+ return null;
+ }
+ const root = createRoot(document.createElement("div"));
+ await act(async () => root.render(createElement(Screen)));
+ await act(async () => root.render(createElement(Screen, { engine: "codex" })));
+ await act(async () => root.unmount());
+ expect(sent.map(({ props }) => props)).toEqual([
+ { step: "opened", place: "meet", ai_ready: false },
+ { step: "chosen", place: "meet", engine: "claude" },
+ { step: "chosen", place: "meet", engine: "codex" },
+ ]);
+});
diff --git a/src/lib/sign-in-gate.ts b/src/lib/sign-in-gate.ts
new file mode 100644
index 0000000000..1f52454d38
--- /dev/null
+++ b/src/lib/sign-in-gate.ts
@@ -0,0 +1,12 @@
+import { analyticsSurface, initAnalytics, track } from "@/lib/analytics";
+
+const SIGN_IN_GATE = ["signed_out", "session_ended", "team_left", "service_trust"] as const;
+export type SignInGate = (typeof SIGN_IN_GATE)[number];
+
+/** The desktop app's own page opened on its sign-in page instead of the app, where nothing else is tracked. A server's
+ * page sends nothing here: its sign-in page is where anyone not signed in lands. */
+export function signInGateShown(reason: SignInGate): void {
+ if (analyticsSurface() !== "local") return;
+ void initAnalytics();
+ track("sign_in_gate", { reason: SIGN_IN_GATE.includes(reason) ? reason : "other" });
+}
diff --git a/src/lib/usage-snapshot.test.ts b/src/lib/usage-snapshot.test.ts
index 89d4a8844b..b0cc4f2e1c 100644
--- a/src/lib/usage-snapshot.test.ts
+++ b/src/lib/usage-snapshot.test.ts
@@ -276,6 +276,44 @@ describe("the daily usage snapshot", () => {
expect(sent).toMatchObject({ cloud_plan: "unknown", bots: 9, key_count: 9 });
});
+ it("waits for this computer's saved sign-in to be read before it names the plan", async () => {
+ const { snapshot } = await freshModules();
+ const states = [{ status: "signed-out", message: "restoring" }, { status: "signed-out", message: "restoring" }, { status: "signed-out" }];
+ const waits: number[] = [];
+ await snapshot.sendDailySnapshot(hostileState(), hostileSources({ cloudAccount: { state: async () => states.shift() as never } }), DAY,
+ async (ms) => void waits.push(ms), () => 0);
+ expect(waits).toEqual([5_000, 5_000]);
+ expect(snapshots()[0]).toMatchObject({ cloud_plan: "none" });
+ });
+
+ it("gives up waiting after half a minute and says the plan is unknown", async () => {
+ const { snapshot } = await freshModules();
+ const waits: number[] = [];
+ let clock = 0;
+ await snapshot.sendDailySnapshot(hostileState(), hostileSources({ cloudAccount: { state: async () => ({ status: "signed-out", message: "restoring" }) } }), DAY,
+ async (ms) => { waits.push(ms); clock += ms; }, () => clock);
+ expect(waits).toHaveLength(5);
+ expect(snapshots()[0]).toMatchObject({ cloud_plan: "unknown" });
+ });
+
+ it("counts slow reads of the sign-in toward that half minute", async () => {
+ const { snapshot } = await freshModules();
+ let clock = 0, reads = 0;
+ await snapshot.sendDailySnapshot(hostileState(), hostileSources({
+ cloudAccount: { state: async () => { reads++; clock += 4_000; return { status: "signed-out", message: "restoring" }; } },
+ }), DAY, async (ms) => { clock += ms; }, () => clock);
+ expect(clock).toBeLessThanOrEqual(30_000 + 4_000);
+ expect(reads).toBe(4);
+ expect(snapshots()[0]).toMatchObject({ cloud_plan: "unknown" });
+ });
+
+ it("leaves the plan out on a page with no way to ask it", async () => {
+ const { snapshot } = await freshModules();
+ await snapshot.sendDailySnapshot(hostileState(), hostileSources({ cloudAccount: null, cloudPlan: null }), DAY);
+ expect(snapshots()[0]).not.toHaveProperty("cloud_plan");
+ expect(snapshots()[0]).not.toHaveProperty("cloud_trial");
+ });
+
it("reads the plan from a Cloud page's own bridge, and leaves out what only this computer knows", async () => {
const { snapshot } = await freshModules();
const sources = hostileSources({
@@ -389,6 +427,13 @@ describe("the Cloud plan", () => {
expect(cloudPlanFromAccount({ status: "signed-out" })).toEqual({ plan: "none" });
for (const status of ["connecting", "reauth-required", "unavailable"] as const) expect(cloudPlanFromAccount({ status }), status).toEqual({ plan: "unknown" });
expect(cloudPlanFromAccount(null)).toEqual({ plan: "unknown" });
+ const account = { id: HOSTILE, email: `${HOSTILE}@example.com` };
+ for (const status of ["connecting", "reauth-required", "unavailable"] as const) {
+ expect(cloudPlanFromAccount({ status, account, lastPlan: { tier: "max", active: true } }), status).toEqual({ plan: "max" });
+ expect(cloudPlanFromAccount({ status, account, lastPlan: { tier: "max", active: false } }), status).toEqual({ plan: "none" });
+ expect(cloudPlanFromAccount({ status, account, lastPlan: { active: true } }), status).toEqual({ plan: "pro" });
+ expect(cloudPlanFromAccount({ status, account }), status).toEqual({ plan: "none" });
+ }
const connected = (patch: Record<string, unknown>, extra: Record<string, unknown> = {}) => cloudPlanFromAccount({ status: "connected", entitlement: entitlement(patch), ...extra } as never);
expect(connected({})).toEqual({ plan: "pro", trial: false });
expect(connected({ tier: "personal" }, { trial })).toEqual({ plan: "personal", trial: true });
diff --git a/src/lib/usage-snapshot.ts b/src/lib/usage-snapshot.ts
index 76da6661b8..f8bc4be4a5 100644
--- a/src/lib/usage-snapshot.ts
+++ b/src/lib/usage-snapshot.ts
@@ -32,7 +32,8 @@ export interface UsageInput {
apps: { services: Record<string, ConnectorStatus>; authoritative: boolean } | null;
sessions: { sessions: ReadonlyArray<{ id?: unknown; email?: unknown }>; current: unknown } | null;
companionDevices: number | null;
- cloud: CloudPlanFacts | null;
+ /** null when the plan could not be read; left out where this page has no way to ask. */
+ cloud?: CloudPlanFacts | null;
computers: { cloudComputers: unknown; teamComputers: unknown } | null;
platform: "desktop" | "browser";
remoteClient: boolean;
@@ -147,7 +148,7 @@ export function buildUsageSnapshot(input: UsageInput): EventProps {
live_calls: config.live?.configured === true,
...deviceFacts(input.sessions, input.companionDevices),
cloud_home: config.cloudHome === true,
- cloud_plan: input.cloud?.plan ?? "unknown",
+ cloud_plan: input.cloud === undefined ? undefined : input.cloud?.plan ?? "unknown",
cloud_trial: input.cloud?.trial,
edition: allow(config.edition?.edition ?? "oss", EDITION),
org_managed: Boolean(config.managedPolicy),
@@ -161,11 +162,34 @@ export function buildUsageSnapshot(input: UsageInput): EventProps {
const tierPlan = (tier: string | undefined): CloudPlanFacts["plan"] => tier === undefined ? "pro" : allow(tier, CLOUD_TIER);
+/** A sign-in that is not verified right now (offline, expired, signing in again) reports the plan it last verified; a
+ * sign-in that verified no paid plan is `none`. */
export function cloudPlanFromAccount(account: CloudAccountState | null | undefined): CloudPlanFacts {
+ if (account?.status === "connected") {
+ const paid = account.entitlement?.plan === "pro" && account.entitlement.status === "active";
+ return { plan: paid ? tierPlan(account.entitlement?.tier) : "none", trial: trialRunning(account.trial) };
+ }
+ if (account?.lastPlan) return { plan: account.lastPlan.active ? tierPlan(account.lastPlan.tier) : "none" };
+ if (account?.account) return { plan: "none" };
if (account?.status === "signed-out" && account.message !== "restoring") return { plan: "none" };
- if (account?.status !== "connected") return { plan: "unknown" };
- const paid = account.entitlement?.plan === "pro" && account.entitlement.status === "active";
- return { plan: paid ? tierPlan(account.entitlement?.tier) : "none", trial: trialRunning(account.trial) };
+ return { plan: "unknown" };
+}
+
+/** Main is still reading this computer's saved sign-in: the plan is not known yet, though it will be in a moment. */
+export const accountSettling = (account: CloudAccountState | null | undefined): boolean =>
+ account?.status === "signed-out" && account.message === "restoring";
+
+const ACCOUNT_SETTLE_MS = 5_000;
+const ACCOUNT_SETTLE_LIMIT_MS = 30_000;
+
+async function settledAccount(read: () => Promise<CloudAccountState>, wait: (ms: number) => Promise<void>, now: () => number): Promise<CloudAccountState> {
+ const until = now() + ACCOUNT_SETTLE_LIMIT_MS;
+ let account = await read();
+ while (accountSettling(account) && now() + ACCOUNT_SETTLE_MS < until) {
+ await wait(ACCOUNT_SETTLE_MS);
+ account = await read();
+ }
+ return account;
}
export function cloudPlanFromSnapshot(snapshot: CloudPlanSnapshot | null | undefined): CloudPlanFacts {
@@ -220,7 +244,8 @@ function claimDay(day: string): boolean {
}
/** At most one app_snapshot per app origin per UTC day; an opted-out install makes no request at all. */
-export async function sendDailySnapshot(state: SnapshotState, sources: UsageSources, now = Date.now()): Promise<boolean> {
+export async function sendDailySnapshot(state: SnapshotState, sources: UsageSources, now = Date.now(),
+ wait = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)), clock = Date.now): Promise<boolean> {
if (!analyticsEnabled() || gathering || !state.config) return false;
if (!claimDay(utcDay(now))) return false;
gathering = true;
@@ -231,9 +256,9 @@ export async function sendDailySnapshot(state: SnapshotState, sources: UsageSour
settle(() => sources.connectedApps()),
settle(() => sources.request<{ sessions?: unknown; current?: unknown }>("/api/auth/sessions")),
companion ? settle(() => companion.state()) : null,
- cloudAccount ? settle(() => cloudAccount.state()).then(cloudPlanFromAccount)
- : cloudPlan ? settle(() => cloudPlan.state()).then(cloudPlanFromSnapshot)
- : null,
+ cloudAccount ? settle(() => settledAccount(() => cloudAccount.state(), wait, clock)).then((account) => account ? cloudPlanFromAccount(account) : null)
+ : cloudPlan ? settle(() => cloudPlan.state()).then((snapshot) => snapshot ? cloudPlanFromSnapshot(snapshot) : null)
+ : undefined,
config.box?.configured
? settle(() => sources.request<{ cloudComputers?: unknown; teamComputers?: unknown }>("/api/computers/usage"))
: { cloudComputers: 0, teamComputers: 0 },
diff --git a/src/main.tsx b/src/main.tsx
index cffebf7e82..620b7fa75a 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -18,6 +18,7 @@ import { TEAM_LEFT_REFUSAL } from "../shared/cloud-hints";
import { HomeScreen, SignedOutAtHome } from "./components/HomeScreen";
import { PageBoundary } from "./components/PageBoundary";
import { endedBeforeReload, forgetEndedSession } from "./lib/session-ended";
+import { signInGateShown } from "./lib/sign-in-gate";
import "./styles.css";
// Before first paint; settleInterfaceMode must run before applySkin writes omb-skin.
@@ -54,13 +55,18 @@ async function chooseRoot(): Promise<React.ReactNode> {
const session = await readSessionState();
if (session.kind === "unauthenticated") {
await pageLanguage;
- if (session.error === TEAM_LEFT_REFUSAL) return <TeamLeftPage team={await teamName()} />;
+ if (session.error === TEAM_LEFT_REFUSAL) {
+ signInGateShown("team_left");
+ return <TeamLeftPage team={await teamName()} />;
+ }
+ signInGateShown(endedBeforeReload() ? "session_ended" : "signed_out");
const pair = <PairPage initialCode={null} reason={endedBeforeReload() ? t("pair.sessionEnded") : session.error} />;
return home ? <SignedOutAtHome bridge={home} fallback={pair} /> : pair;
}
forgetEndedSession();
if (session.kind === "session") rememberTeamSignIn(session.teamSignIn);
if (session.kind === "loopback" && session.trust === "service") {
+ signInGateShown("service_trust");
await pageLanguage;
return <PairPage initialCode={null} reason={t("pair.serviceTrust")} />;
}
diff --git a/src/state/store.tsx b/src/state/store.tsx
index 61b6c6a992..6018718807 100644
--- a/src/state/store.tsx
+++ b/src/state/store.tsx
@@ -434,8 +434,8 @@ export interface InstanceInfo extends InstanceEndpointInfo {
};
/** What one tiny test message through this AI showed, for its current sign-in; absent until one is sent. */
aiTest?: import("../../shared/ai-ranking").AiTestState;
- /** Why it didn't answer, in plain words, when it said (signed out, a used-up limit…). */
- aiTestError?: string;
+ /** Why it didn't answer: in plain words when it said (signed out, a used-up limit…), and as a word from a fixed list. */
+ aiTestError?: string; aiTestReason?: import("../../shared/ai-ranking").AiTestReason;
models: { default: string; options: Array<{ id: string; label: string; custom?: boolean; loaded?: boolean; provider?: string; variants?: ModelVariantOption[]; orgBlocked?: true; needsCliUpdate?: string; local?: import("../../shared/local-model").LocalModelFacts }> };
capabilities?: {
computerMcp?: boolean;