Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.
Python agent-orchestrationaiai-agentschatopsdiscordlangchainmcpmicrosoft-teamsmulti-agentopen-sourceopenaiself-hostedslack
feat(console): send a small set of product events to Amplitude (CHOO-2177) (#247)
Christian McDermott64f07f2fa5a6
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 293c62044..85e5aa20a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -714,6 +714,17 @@ version of their own to them without also giving them a release of their own.## switch-console### [Unreleased]+#### Added+- Switch Console now sends a small, fixed set of product events — the app+ launching, an agent being created, a session starting and ending, a server+ being added, a connector being installed — so we can see which features get+ used and where the app runs into trouble. Nothing is sent unless you agree to+ it, and the first-run prompt now defaults to **off**, because each event+ carries a random id for your installation.+- Events go to a relay we run, which forwards them on. The analytics services+ therefore never see your network address, and the app itself ships no+ credential — there is nothing in it to leak.+#### Fixed- The OpenCode connector the app writes carries its own copy of theroom-workflow skill, so it picked up the same wrong claim that a Telegram DM@@ -733,6 +744,12 @@ version of their own to them without also giving them a release of their own.Teams or Telegram — rather than the repository's markdown, with themessaging-apps index as the fallback for an unrecognised platform(CHOO-2313, unblocking CHOO-2269).+- The **Share usage data** prompt and its Settings row default to off, and say+ plainly that a random id for the installation is part of what is sent. The+ 0.27.2 entry below describes a payload of anonymous counters carrying no+ identifier of any kind; that was the shape of a feature that sent nothing, and+ this replaces it. Anyone who had already agreed under the old default keeps+ that answer — it is not silently reset to a refusal.### [0.28.0] - 2026-08-21diff --git a/console/AGENTS.md b/console/AGENTS.mdindex 8572cece6..25f87659e 100644--- a/console/AGENTS.md+++ b/console/AGENTS.md@@ -394,27 +394,48 @@ pnpm run lintor generated dependency folders.- Application secrets are stored through encrypted app secret services and Electronsafe storage.-- The app sends no telemetry or analytics today, and nothing may start sending without- going through the consent gate below. Logs are local-only and no code path transmits- them off the machine. Do not add one. `getDiagnosticLogAttachment()` builds a redacted- export and is the only function intended to ever feed such a path; anything that ships- log content must go through it rather than reading the log itself.+- The app sends a small, fixed set of product events to the company's public OTLP relay,+ which forwards them to Amplitude and Datadog, and nothing else. The relay holds both+ vendor keys, so **no credential ships in the app** — do not reintroduce one, and do not+ call a vendor directly. It also means the vendors see the relay's network address rather+ than the user's. Do not turn that into a promise about *them*: it is a property of the+ relay's configuration, which lives in another repository and whose own documentation+ describes the change that would undo it. The consent copy therefore promises only what+ this app does — it sends no address and no location — which stays true either way.+ Logs are local-only and no code path transmits them off the machine. Do not add one.+ `getDiagnosticLogAttachment()` builds a redacted export and is the only function+ intended to ever feed such a path; anything that ships log content must go through it+ rather than reading the log itself, and no log content may enter a telemetry payload.- **Telemetry consent is a gate, not a preference.** Anything that would send usage datamust `await isTelemetryAllowed()` (`src/main/core/telemetry/consent.ts`) at the point ofemission and send nothing when it returns false. Do not read `telemetry.enabled` fromsettings directly — it does not distinguish "said yes" from "not asked yet" — and do not- cache the answer across a send, since the user can revoke it at any time.-- **What telemetry may contain, if it is ever built.** The consent toggle defaults to *on*,- which is only defensible for data that is not personal, so the payload is limited to- anonymous counters: feature-usage counts, error and crash counts, app version, operating- system. It must carry **no identifier of any kind** — no install id, machine id, user id,- or any other value that distinguishes one install from another — and no prompts, code,- file paths, or agent/room/project/server names. Adding an identifier makes the data- pseudonymous personal data under GDPR/nFADP, at which point an opt-out default is no- longer valid and the default has to flip to off. That is a decision for the product- owner, not a code change: if you need per-install numbers, raise it rather than adding- a field. The user-facing wording of this promise lives in- `src/renderer/features/telemetry/telemetry-copy.ts` and must be kept in step.+ cache the answer across a send, since the user can revoke it at any time. Consent off+ means **no request is made at all**, not a request whose result is discarded.+- **The toggle defaults to off.** The payload carries a random per-install id, which makes+ it pseudonymous personal data under GDPR/nFADP; an opt-out default does not cover that.+ Flipping the default back to on is a product decision that requires the id to go first,+ not a code change.+- **What a telemetry payload may contain.** Add an event only by adding it to the closed+ catalogue in `src/main/core/telemetry/events.ts`: its property types are literal unions+ and numbers, and `TELEMETRY_EVENT_PROPERTIES` names the same fields as data, which the+ emitter uses to drop anything else before it builds a payload. The types alone are not+ enough — excess-property checking does not apply through a spread — so the runtime+ filter is what makes "nothing free-text can reach a payload" true rather than intended.+ Permitted: which of the catalogued things happened, agent type, local-vs-remote,+ success-vs-failure, app version, operating system, and the random install id. Never:+ prompts, code, file paths, working directories, error messages or stack traces (use an+ enumerated code), machine or user names, IP or MAC addresses, email or sign-in, and no+ agent, room, project, location or server names or ids. Widening this is a consent+ decision — the user-facing wording lives in+ `src/renderer/features/telemetry/telemetry-copy.ts` and must be kept in step with it.+- **Telemetry never affects the user.** It is fire-and-forget with a short timeout and no+ retry: a send that fails is logged with an `errorCode` and dropped. It must never block,+ delay or fail an operation, and must never surface in the UI. It is off in a dev build,+ which is logged once so a build that is not reporting says why.+- **The sidecar sends nothing.** It runs headless on a user's VM with no consent prompt+ and no access to this setting, so sessions it starts are not counted. Do not "fix" that+ by having it report; the gate is not reachable from there.- **Redaction is split by destination, and both halves must be preserved:**- **Secrets** (tokens, keys, JWTs, PEM blocks, URL credentials) are redacted on thewrite path by `redactSecrets()` and must never reach disk.@@ -618,8 +639,17 @@ pnpm run test`.switchdash.json`.- Optional environment variables:`SWITCHDASH_DB_FILE`, `SWITCHDASH_DISABLE_NATIVE_DB`,- `SWITCHDASH_DISABLE_PTY`, `SWITCHDASH_REGISTER_DEEPLINK`, and- `SWITCHDASH_FAKE_UPDATE`.+ `SWITCHDASH_DISABLE_PTY`, `SWITCHDASH_REGISTER_DEEPLINK`,+ `SWITCHDASH_FAKE_UPDATE`, `SWITCHDASH_TELEMETRY_DEV`, and+ `SWITCHDASH_TELEMETRY_ENDPOINT`.+- Telemetry in dev: a dev build sends nothing, so the emitter cannot be exercised by+ `pnpm run dev` alone. `SWITCHDASH_TELEMETRY_DEV=1` opts a dev run in, and+ `SWITCHDASH_TELEMETRY_ENDPOINT` redirects it at a local listener so what is actually+ sent can be read off the wire rather than off the code. Both are dev-only and cannot+ activate in a packaged build. There is no key to configure: events go to the public+ OTLP relay, which holds the vendor credentials server-side, so every build can report+ and none carries a secret. Example:+ `SWITCHDASH_TELEMETRY_DEV=1 SWITCHDASH_TELEMETRY_ENDPOINT=http://127.0.0.1:9009 pnpm run dev`.- **A hook command is built for the machine the session runs on, not for the onebuilding it.** `writeHooks(fs, hooks, { platform })` takes the targetplatform: `process.platform` locally and in the sidecar, the VM's `uname -s`diff --git a/console/agents/architecture/main-process.md b/console/agents/architecture/main-process.mdindex 46e0d7882..a824d2ee7 100644--- a/console/agents/architecture/main-process.md+++ b/console/agents/architecture/main-process.md@@ -37,6 +37,7 @@ Two names in this list are easy to misread, because one of them changed meaning:- **switch-rooms** — Room connections, the auto-session watcher, prompt injection sinks, Switch credentials, notification polling- **switch-servers** — Switch server records, gateway client, auth, room creation- **switch-setup** — First-run Switch setup, local and remote (`remote-switch-setup.ts`)+- **telemetry** — The consent gate, the closed event catalogue, and `relay-client.ts`, which posts one OTLP log record per event to the company's public relay (which forwards to Amplitude and Datadog, and holds their keys, so the app ships none). The three session/agent events are subscribed in `telemetry-listeners.ts`; the other three (app launched, server added, connector installed) have no hook bus to subscribe to and call `trackEvent` at their own site- **terminal-shell** — Terminal shell availability and detection- **terminals** — Terminal lifecycle with provider pattern (`impl/local-terminal-provider.ts`), lifecycle scripts- **updates** — Auto-update servicediff --git a/console/apps/switch-console-desktop/drizzle/0047_materialise_telemetry_consent.sql b/console/apps/switch-console-desktop/drizzle/0047_materialise_telemetry_consent.sqlnew file mode 100644index 000000000..621652b04--- /dev/null+++ b/console/apps/switch-console-desktop/drizzle/0047_materialise_telemetry_consent.sql@@ -0,0 +1,37 @@+/*+ Write an agreement to share usage data back into the row that records it,+ before the default it was stored against changes meaning.++ App settings are persisted as a delta: `SettingsStore.update()` keeps only the+ fields that differ from the default at the moment of writing, and drops the+ rest. While sharing defaulted to on, someone who saw the first-run prompt and+ left it on therefore stored `{"askedAt": <ts>}` and nothing else — their answer+ was recorded by its own absence.++ The default is now off, because what is sent carries a per-install id. That+ turns those rows inside out: with `enabled` missing, they resolve to the new+ default and read as a refusal, and the prompt never returns to ask again+ because `askedAt` is set. The agreement would be lost with no way to tell it+ from a genuine no.++ A row that is missing `enabled` while carrying an `askedAt` can only have been+ written under the old default, so its absent value is recoverable: it was on.+ Rows that name `enabled` explicitly — including every row written from here on+ — already say what they mean and are left alone.++ `json_valid` guards a value that is not JSON at all. Nothing writes one today,+ since every writer goes through JSON.stringify and every reader tolerates the+ failure — but the JSON functions raise on malformed input, migrations run in+ one transaction, and a failed migration stops the app from starting at all.+ One unreadable settings row should cost its own repair, not the application.++ `json_type` rather than `json_extract` for the same reason it matters here:+ extract cannot tell an absent `enabled` from one explicitly set to null, and+ would overwrite the second.+*/+UPDATE app_settings+SET value = json_set(value, '$.enabled', json('true'))+WHERE key = 'telemetry'+ AND json_valid(value)+ AND json_extract(value, '$.askedAt') IS NOT NULL+ AND json_type(value, '$.enabled') IS NULL;diff --git a/console/apps/switch-console-desktop/drizzle/meta/0047_snapshot.json b/console/apps/switch-console-desktop/drizzle/meta/0047_snapshot.jsonnew file mode 100644index 000000000..848339a15--- /dev/null+++ b/console/apps/switch-console-desktop/drizzle/meta/0047_snapshot.json@@ -0,0 +1,891 @@+{+ "id": "395a411a-8bb8-47cc-bb31-031ab4291c0a",+ "prevId": "2e3bb8e5-5808-4f99-a61d-d2d70ff8e2d9",+ "version": "6",+ "dialect": "sqlite",+ "tables": {+ "agents": {+ "name": "agents",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "location_id": {+ "name": "location_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "provider_id": {+ "name": "provider_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "switch_agent_id": {+ "name": "switch_agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "api_endpoint": {+ "name": "api_endpoint",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "server_id": {+ "name": "server_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "auto_approve": {+ "name": "auto_approve",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "provider_config": {+ "name": "provider_config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_agents_location_id": {+ "name": "idx_agents_location_id",+ "columns": ["location_id"],+ "isUnique": false+ },+ "idx_agents_server_id": {+ "name": "idx_agents_server_id",+ "columns": ["server_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "agents_location_id_locations_id_fk": {+ "name": "agents_location_id_locations_id_fk",+ "tableFrom": "agents",+ "columnsFrom": ["location_id"],+ "tableTo": "locations",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "no action"+ },+ "agents_server_id_switch_servers_id_fk": {+ "name": "agents_server_id_switch_servers_id_fk",+ "tableFrom": "agents",+ "columnsFrom": ["server_id"],+ "tableTo": "switch_servers",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "set null"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "app_secrets": {+ "name": "app_secrets",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "secret": {+ "name": "secret",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_app_secrets_key": {+ "name": "idx_app_secrets_key",+ "columns": ["key"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "app_settings": {+ "name": "app_settings",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_app_settings_key": {+ "name": "idx_app_settings_key",+ "columns": ["key"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "kv": {+ "name": "kv",+ "columns": {+ "key": {+ "name": "key",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "value": {+ "name": "value",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_kv_key": {+ "name": "idx_kv_key",+ "columns": ["key"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "location_settings": {+ "name": "location_settings",+ "columns": {+ "location_id": {+ "name": "location_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "base_settings_json": {+ "name": "base_settings_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "shareable_settings_json": {+ "name": "shareable_settings_json",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'{}'"+ },+ "legacy_config_migrated_at": {+ "name": "legacy_config_migrated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "location_settings_location_id_locations_id_fk": {+ "name": "location_settings_location_id_locations_id_fk",+ "tableFrom": "location_settings",+ "columnsFrom": ["location_id"],+ "tableTo": "locations",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "locations": {+ "name": "locations",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "''"+ },+ "dir": {+ "name": "dir",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_locations_host_dir": {+ "name": "idx_locations_host_dir",+ "columns": ["ssh_host", "dir"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "messages": {+ "name": "messages",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "content": {+ "name": "content",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "sender": {+ "name": "sender",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "timestamp": {+ "name": "timestamp",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "metadata": {+ "name": "metadata",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ }+ },+ "indexes": {+ "idx_messages_session_id": {+ "name": "idx_messages_session_id",+ "columns": ["session_id"],+ "isUnique": false+ },+ "idx_messages_timestamp": {+ "name": "idx_messages_timestamp",+ "columns": ["timestamp"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "messages_session_id_sessions_id_fk": {+ "name": "messages_session_id_sessions_id_fk",+ "tableFrom": "messages",+ "columnsFrom": ["session_id"],+ "tableTo": "sessions",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "remote_host_reachability": {+ "name": "remote_host_reachability",+ "columns": {+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'unknown'"+ },+ "last_error": {+ "name": "last_error",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_checked_at": {+ "name": "last_checked_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_reachable_at": {+ "name": "last_reachable_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "consecutive_failures": {+ "name": "consecutive_failures",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "remote_host_setup_plans": {+ "name": "remote_host_setup_plans",+ "columns": {+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'idle'"+ },+ "steps": {+ "name": "steps",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "current_step_id": {+ "name": "current_step_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "remote_hosts": {+ "name": "remote_hosts",+ "columns": {+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "session_room_connections": {+ "name": "session_room_connections",+ "columns": {+ "session_id": {+ "name": "session_id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "room_id": {+ "name": "room_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "room_name": {+ "name": "room_name",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "switch_agent_id": {+ "name": "switch_agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {},+ "foreignKeys": {+ "session_room_connections_session_id_sessions_id_fk": {+ "name": "session_room_connections_session_id_sessions_id_fk",+ "tableFrom": "session_room_connections",+ "columnsFrom": ["session_id"],+ "tableTo": "sessions",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "sessions": {+ "name": "sessions",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "agent_id": {+ "name": "agent_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "title": {+ "name": "title",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "config": {+ "name": "config",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "shell_id": {+ "name": "shell_id",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "'system'"+ },+ "status": {+ "name": "status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_session_id": {+ "name": "agent_session_id",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_status": {+ "name": "agent_status",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "agent_status_seen": {+ "name": "agent_status_seen",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false,+ "default": 1+ },+ "is_initial_session": {+ "name": "is_initial_session",+ "type": "integer",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "is_pinned": {+ "name": "is_pinned",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": 0+ },+ "archived_at": {+ "name": "archived_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "last_interacted_at": {+ "name": "last_interacted_at",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "status_changed_at": {+ "name": "status_changed_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_sessions_agent_id": {+ "name": "idx_sessions_agent_id",+ "columns": ["agent_id"],+ "isUnique": false+ }+ },+ "foreignKeys": {+ "sessions_agent_id_agents_id_fk": {+ "name": "sessions_agent_id_agents_id_fk",+ "tableFrom": "sessions",+ "columnsFrom": ["agent_id"],+ "tableTo": "agents",+ "columnsTo": ["id"],+ "onUpdate": "no action",+ "onDelete": "cascade"+ }+ },+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ },+ "switch_servers": {+ "name": "switch_servers",+ "columns": {+ "id": {+ "name": "id",+ "type": "text",+ "primaryKey": true,+ "notNull": true,+ "autoincrement": false+ },+ "name": {+ "name": "name",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "gateway_url": {+ "name": "gateway_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "api_url": {+ "name": "api_url",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false+ },+ "managed": {+ "name": "managed",+ "type": "integer",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": false+ },+ "management_kind": {+ "name": "management_kind",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "ssh_host": {+ "name": "ssh_host",+ "type": "text",+ "primaryKey": false,+ "notNull": false,+ "autoincrement": false+ },+ "created_at": {+ "name": "created_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ },+ "updated_at": {+ "name": "updated_at",+ "type": "text",+ "primaryKey": false,+ "notNull": true,+ "autoincrement": false,+ "default": "CURRENT_TIMESTAMP"+ }+ },+ "indexes": {+ "idx_switch_servers_gateway_url": {+ "name": "idx_switch_servers_gateway_url",+ "columns": ["gateway_url"],+ "isUnique": true+ }+ },+ "foreignKeys": {},+ "compositePrimaryKeys": {},+ "uniqueConstraints": {},+ "checkConstraints": {}+ }+ },+ "views": {},+ "enums": {},+ "_meta": {+ "columns": {},+ "schemas": {},+ "tables": {}+ },+ "internal": {+ "indexes": {}+ }+}diff --git a/console/apps/switch-console-desktop/drizzle/meta/_journal.json b/console/apps/switch-console-desktop/drizzle/meta/_journal.jsonindex 37c16d0f5..2b8b7d0f6 100644--- a/console/apps/switch-console-desktop/drizzle/meta/_journal.json+++ b/console/apps/switch-console-desktop/drizzle/meta/_journal.json@@ -330,6 +330,13 @@"when": 1785941913915,"tag": "0046_military_whirlwind","breakpoints": true+ },+ {+ "idx": 47,+ "version": "6",+ "when": 1786983032561,+ "tag": "0047_materialise_telemetry_consent",+ "breakpoints": true}]}diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.tsindex 07ec1c3b0..d21dc8079 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/local-agent-runtime.ts@@ -307,7 +307,10 @@ export class LocalAgentRuntime implements AgentRuntimeProvider {events.emit(agentSessionExitedChannel, { sessionId: this.sessionId });// In-process counterpart for main-process consumers — `events` only// reaches the renderer (see session-hooks).- sessionHooks._emit('session:agent-exited', { sessionId: this.sessionId });+ sessionHooks._emit('session:agent-exited', {+ sessionId: this.sessionId,+ decision: decision.kind,+ });if (this.tmux) {return;diff --git a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.tsindex 13dcd589c..9daf9112b 100644--- a/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts+++ b/console/apps/switch-console-desktop/src/main/core/agent-runtime/impl/ssh-agent-runtime.ts@@ -12,7 +12,10 @@ import { DEEPLINK_SCHEME } from '@main/app/deeplinks';import { agentHookService } from '@main/core/agent-hooks/agent-hook-service';import type { PreparedLaunchProfile } from '@main/core/agent-runtime/agent-launch-profile';import { resolveAgentLaunchProfile } from '@main/core/agent-runtime/agent-launch-profile';-import { AgentRuntimeSupervisor } from '@main/core/agent-runtime/agent-runtime-supervisor';+import {+ AgentRuntimeSupervisor,+ type ExitDecision,+} from '@main/core/agent-runtime/agent-runtime-supervisor';import type { AttachableRuntime } from '@main/core/agent-runtime/attachment/types';import { resolveAgentSessionCommandArgs } from '@main/core/agent-runtime/resolve-agent-session-command';import type { AgentRuntimeProvider } from '@main/core/agent-runtime/types';@@ -863,7 +866,7 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntimethis.pty = null;if (decision.kind === 'stopped') return;- this.emitExited();+ this.emitExited(decision.kind);if (this.tmux) return;@@ -937,9 +940,9 @@ export class SshAgentRuntime implements AgentRuntimeProvider, AttachableRuntime}}- private emitExited(): void {+ private emitExited(decision: ExitDecision['kind']): void {events.emit(agentSessionExitedChannel, { sessionId: this.sessionId });- sessionHooks._emit('session:agent-exited', { sessionId: this.sessionId });+ sessionHooks._emit('session:agent-exited', { sessionId: this.sessionId, decision });}private detachPty(): void {diff --git a/console/apps/switch-console-desktop/src/main/core/sessions/session-hooks.ts b/console/apps/switch-console-desktop/src/main/core/sessions/session-hooks.tsindex 6285c464d..e36424bd8 100644--- a/console/apps/switch-console-desktop/src/main/core/sessions/session-hooks.ts+++ b/console/apps/switch-console-desktop/src/main/core/sessions/session-hooks.ts@@ -1,3 +1,4 @@+import type { ExitDecision } from '@main/core/agent-runtime/agent-runtime-supervisor';import { HookCore, type Hookable } from '@main/lib/hookable';import { log } from '@main/lib/logger';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';@@ -26,8 +27,15 @@ export type SessionHookMap = {/*** The session's agent PTY exited unexpectedly (i.e. not a deliberate stop).* In-process counterpart to the renderer-bound `agentSessionExitedChannel`.+ *+ * `decision` is the supervisor's verdict on the exit, and is what separates a+ * session that is about to be respawned from one that is over: only `failed`+ * means the recovery ladder is exhausted.*/- 'session:agent-exited': (params: { sessionId: string }) => void | Promise<void>;+ 'session:agent-exited': (params: {+ sessionId: string;+ decision: ExitDecision['kind'];+ }) => void | Promise<void>;'session:input-submitted': (params: {sessionId: string;providerId: AgentProviderId;diff --git a/console/apps/switch-console-desktop/src/main/core/settings/settings-registry.ts b/console/apps/switch-console-desktop/src/main/core/settings/settings-registry.tsindex e1755f1d2..4dac2b8cf 100644--- a/console/apps/switch-console-desktop/src/main/core/settings/settings-registry.ts+++ b/console/apps/switch-console-desktop/src/main/core/settings/settings-registry.ts@@ -66,7 +66,7 @@ export const SETTINGS_DEFAULTS = {pr: 'flat' as const,},telemetry: {- enabled: true,+ enabled: false,askedAt: null,},} satisfies SettingsDefaultsMap;diff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.tsindex 57dbc7d47..56353cbb8 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.db.test.ts@@ -29,8 +29,16 @@ vi.mock('@main/core/secrets/encrypted-app-secrets-store', () => ({},}));+const telemetryMocks = vi.hoisted(() => ({+ trackEvent: vi.fn(),+}));+vi.mock('@main/core/telemetry/telemetry-service', () => ({+ trackEvent: telemetryMocks.trackEvent,+}));+// Imported after the mocks so the module binds to the mocked db + secrets store.-const { ensureManagedServer, removeServer, renameServer } = await import('./servers-store');+const { addServer, ensureManagedServer, removeServer, renameServer } =+ await import('./servers-store');describe('servers-store: rename & delete', () => {let fixture: Awaited<ReturnType<typeof openFixture>>;@@ -40,6 +48,7 @@ describe('servers-store: rename & delete', () => {mocks.db = fixture.db;fixture.sqlite.pragma('foreign_keys = OFF');secretMocks.deleteSecret.mockReset();+ telemetryMocks.trackEvent.mockReset();});afterEach(() => {@@ -106,6 +115,73 @@ describe('servers-store: rename & delete', () => {});});+ describe('ensureManagedServer telemetry', () => {+ it('reports a new local managed server once', async () => {+ await ensureManagedServer(+ {+ name: 'Local Switch server',+ gatewayUrl: 'http://localhost:8080',+ apiUrl: 'http://localhost:8081',+ },+ { kind: 'local' }+ );++ expect(telemetryMocks.trackEvent).toHaveBeenCalledTimes(1);+ expect(telemetryMocks.trackEvent).toHaveBeenCalledWith('server_added', {+ server_kind: 'local',+ });+ });++ it('reports a new remote managed server with the remote_managed kind', async () => {+ await ensureManagedServer(+ {+ name: 'Remote Switch server',+ gatewayUrl: 'http://localhost:8080',+ apiUrl: 'http://localhost:8081',+ },+ { kind: 'remote', sshHost: 'host-a' }+ );++ expect(telemetryMocks.trackEvent).toHaveBeenCalledTimes(1);+ expect(telemetryMocks.trackEvent).toHaveBeenCalledWith('server_added', {+ server_kind: 'remote_managed',+ });+ });++ it('reports nothing when a managed server restarts (updates the existing row)', async () => {+ const ref = { kind: 'local' } as const;+ const params = {+ name: 'Local Switch server',+ gatewayUrl: 'http://localhost:8080',+ apiUrl: 'http://localhost:8081',+ };+ await ensureManagedServer(params, ref);+ telemetryMocks.trackEvent.mockClear();++ await ensureManagedServer(+ { ...params, gatewayUrl: 'http://localhost:9090', apiUrl: 'http://localhost:9091' },+ ref+ );++ expect(telemetryMocks.trackEvent).not.toHaveBeenCalled();+ });+ });++ describe('addServer telemetry', () => {+ it('reports an externally-hosted server', async () => {+ await addServer({+ name: 'External server',+ gatewayUrl: 'https://gw.example.com',+ apiUrl: 'https://api.example.com',+ });++ expect(telemetryMocks.trackEvent).toHaveBeenCalledTimes(1);+ expect(telemetryMocks.trackEvent).toHaveBeenCalledWith('server_added', {+ server_kind: 'external',+ });+ });+ });+describe('removeServer', () => {it('unlinks the server’s agents (keeps them), deletes the row, and clears the active pointer', async () => {await fixture.dbdiff --git a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.tsindex 58af19ce7..e50c6a470 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-servers/servers-store.ts@@ -1,6 +1,7 @@import { randomUUID } from 'node:crypto';import { and, desc, eq, isNull, ne, or, sql } from 'drizzle-orm';import { encryptedAppSecretsStore } from '@main/core/secrets/encrypted-app-secrets-store';+import { trackEvent } from '@main/core/telemetry/telemetry-service';import { db } from '@main/db/client';import { agents, kv, type SwitchServerRow, switchServers } from '@main/db/schema';import {@@ -155,6 +156,11 @@ export async function ensureManagedServer(updatedAt: sql`CURRENT_TIMESTAMP`,}).returning();+ // Only the insert: this function also runs on every restart of a stack that+ // already exists, and that is not a server being added.+ trackEvent('server_added', {+ server_kind: ref.kind === 'remote' ? 'remote_managed' : 'local',+ });return mapRow(row);}@@ -178,6 +184,7 @@ export async function addServer(params: AddServerParams): Promise<SwitchServer>updatedAt: sql`CURRENT_TIMESTAMP`,}).returning();+ trackEvent('server_added', { server_kind: 'external' });return mapRow(row);}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-setup/remote-switch-setup.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-setup/remote-switch-setup.test.tsindex 42e958add..a3c26a433 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-setup/remote-switch-setup.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-setup/remote-switch-setup.test.ts@@ -6,8 +6,12 @@ const mocks = vi.hoisted(() => ({getPlugin: vi.fn(),listPlugins: vi.fn(),ensureSshConnected: vi.fn(),+ trackEvent: vi.fn(),}));+// Reaches the settings store, and through it the database, at import time.+vi.mock('@main/core/telemetry/telemetry-service', () => ({ trackEvent: mocks.trackEvent }));+vi.mock('@main/core/execution-context/ssh-execution-context', () => ({SshExecutionContext: class {exec = mocks.exec;@@ -391,6 +395,139 @@ describe('RemoteSwitchSetupService.update', () => {});});+describe('RemoteSwitchSetupService.install', () => {+ it('installs the plugin and reports success', async () => {+ mocks.exec.mockImplementation(codexExecImpl('sandbox-quantum/switch'));++ const service = await getRemoteSwitchSetupService(SSH_HOST);+ const result = await service.install('codex');++ expect(result.success).toBe(true);+ expect(calls()).toContain(`plugin add ${CODEX_REF}`);+ expect(mocks.trackEvent).toHaveBeenCalledWith('connector_installed', {+ agent_type: 'codex',+ target: 'remote',+ outcome: 'success',+ });+ });++ it('reports failure when the install command exits non-zero', async () => {+ mocks.exec.mockImplementation((_bin: string, args: string[] = []) => {+ if (args.join(' ') === `plugin add ${CODEX_REF}`) {+ return Promise.reject(+ Object.assign(new Error('exit 1'), { code: 1, stderr: 'no write access' })+ );+ }+ return codexExecImpl('sandbox-quantum/switch')('codex', args);+ });++ const service = await getRemoteSwitchSetupService(SSH_HOST);+ const result = await service.install('codex');++ expect(result.success).toBe(false);+ expect(result.message).toBe('no write access');+ expect(mocks.trackEvent).toHaveBeenCalledWith('connector_installed', {+ agent_type: 'codex',+ target: 'remote',+ outcome: 'failure',+ });+ });++ it('reports nothing when the agent type has no Switch setup to attempt', async () => {+ mocks.getPlugin.mockReturnValue({+ metadata: { id: 'no-switch-agent' },+ capabilities: {+ switchSetup: { kind: 'none' },+ hostDependency: { binaryNames: ['nosw'] },+ },+ });++ const service = await getRemoteSwitchSetupService(SSH_HOST);+ const result = await service.install('no-switch-agent');++ expect(result).toEqual({+ success: false,+ message: 'Switch setup is not supported for this agent.',+ });+ expect(mocks.trackEvent).not.toHaveBeenCalled();+ });++ /**+ * A connector the app writes rather than installs through a CLI. The local+ * service has the same branch and the same telemetry; these are here because+ * the two are separate implementations of one behaviour, and the remote one+ * had no test of it at all.+ */+ describe('a connector the app writes itself', () => {+ const install = vi.fn();+ const FILES_AGENT = {+ metadata: { id: 'opencode' },+ capabilities: {+ switchSetup: {+ kind: 'files',+ connectorName: 'Switch connector',+ artifact: 'switch-connector-opencode',+ },+ hostDependency: { binaryNames: ['opencode'] },+ },+ behavior: { switchSetup: { files: { install } } },+ };++ beforeEach(() => {+ mocks.getPlugin.mockReturnValue(FILES_AGENT);+ });++ it('reports the install, and writes to the host rather than running a CLI', async () => {+ install.mockResolvedValue(undefined);++ const service = await getRemoteSwitchSetupService(SSH_HOST);+ const result = await service.install('opencode');++ expect(result).toEqual({ success: true });+ expect(calls()).toEqual([]);+ expect(mocks.trackEvent).toHaveBeenCalledWith('connector_installed', {+ agent_type: 'opencode',+ target: 'remote',+ outcome: 'success',+ });+ });++ it('reports its failure', async () => {+ install.mockRejectedValue(new Error('permission denied'));++ const service = await getRemoteSwitchSetupService(SSH_HOST);+ const result = await service.install('opencode');++ expect(result.success).toBe(false);+ expect(mocks.trackEvent).toHaveBeenCalledWith('connector_installed', {+ agent_type: 'opencode',+ target: 'remote',+ outcome: 'failure',+ });+ });++ it('still answers, and still reports, when the connector implements nothing', async () => {+ // A plugin can declare a files connector and supply no behaviour for it.+ // The user asked for an install: they get a failure, not a rejected+ // promise reaching the UI as a stack trace with nothing recorded.+ mocks.getPlugin.mockReturnValue({+ ...FILES_AGENT,+ behavior: { switchSetup: {} },+ });++ const service = await getRemoteSwitchSetupService(SSH_HOST);+ const result = await service.install('opencode');++ expect(result.success).toBe(false);+ expect(mocks.trackEvent).toHaveBeenCalledWith('connector_installed', {+ agent_type: 'opencode',+ target: 'remote',+ outcome: 'failure',+ });+ });+ });+});+describe('RemoteSwitchSetupService.checkForUpdates', () => {it('leaves a marketplace already pointing at the expected source alone', async () => {mocks.exec.mockImplementation(codexExecImpl('sandbox-quantum/switch'));diff --git a/console/apps/switch-console-desktop/src/main/core/switch-setup/remote-switch-setup.ts b/console/apps/switch-console-desktop/src/main/core/switch-setup/remote-switch-setup.tsindex fe2c5f70d..c0eadf970 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-setup/remote-switch-setup.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-setup/remote-switch-setup.ts@@ -5,8 +5,10 @@ import { createRemoteHomePluginFs } from '@main/core/agent-runtime/impl/remote-himport { SshExecutionContext } from '@main/core/execution-context/ssh-execution-context';import { sshConnectionIdForHost } from '@main/core/locations/location-transport';import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';+import { trackEvent } from '@main/core/telemetry/telemetry-service';import { log } from '@main/lib/logger';import { isNewerVersion } from '@main/lib/semver';+import { isValidProviderId } from '@shared/core/providers/agent-provider-registry';import { getPlugin, listPlugins } from '../providers/plugin-registry';import { cliRulesFor, type SwitchSetupCliRules } from './switch-setup-cli-dialect';import type { SwitchSetupResult, SwitchSetupStatus } from './switch-setup-service';@@ -361,23 +363,60 @@ export class RemoteSwitchSetupService {}async install(agentId: string): Promise<SwitchSetupResult> {+ const { result, attempted } = await this.runInstall(agentId);+ // An agent type with no connector to install did not fail to install one.+ if (attempted) {+ trackEvent('connector_installed', {+ agent_type: isValidProviderId(agentId) ? agentId : 'unknown',+ target: 'remote',+ outcome: result.success ? 'success' : 'failure',+ });+ }+ return result;+ }++ private async runInstall(+ agentId: string+ ): Promise<{ result: SwitchSetupResult; attempted: boolean }> {if (getPlugin(agentId).capabilities.switchSetup.kind === 'files') {- const version = connectorVersion(agentId);- return this.runFiles(agentId, (files, fs) => files.install(fs, { version }));+ // `runFiles` resolves the behavior outside its own try, and that throws+ // for a connector that declares files and implements none. An install the+ // user asked for must come back as a failed result either way — a+ // rejection here would skip the report and reach the UI as a stack.+ try {+ const version = connectorVersion(agentId);+ const result = await this.runFiles(agentId, (files, fs) => files.install(fs, { version }));+ return { result, attempted: true };+ } catch (err) {+ return {+ result: { success: false, message: String(err) },+ attempted: true,+ };+ }}const resolved = await this.resolve(agentId);if (!resolved)- return { success: false, message: 'Switch setup is not supported for this agent.' };+ return {+ result: { success: false, message: 'Switch setup is not supported for this agent.' },+ attempted: false,+ };const { descriptor, bin, ref, marketplaceSource, rules } = resolved;try {await this.ensureMarketplace(bin, descriptor.marketplaceName, marketplaceSource, rules);} catch (err) {- return { success: false, message: `Could not add marketplace: ${String(err)}` };+ return {+ result: { success: false, message: `Could not add marketplace: ${String(err)}` },+ attempted: true,+ };}const res = await this.run(bin, rules.installArgs(ref, descriptor.scope));- return res.code === 0- ? { success: true }- : { success: false, message: res.stderr.trim() || 'Install failed.' };+ return {+ result:+ res.code === 0+ ? { success: true }+ : { success: false, message: res.stderr.trim() || 'Install failed.' },+ attempted: true,+ };}/**diff --git a/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.test.tsindex 476e09e4d..57857ffdc 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.test.ts@@ -6,6 +6,7 @@ const mocks = vi.hoisted(() => ({getPlugin: vi.fn(),listPlugins: vi.fn(),readFile: vi.fn(),+ trackEvent: vi.fn(),}));vi.mock('@main/core/execution-context/local-execution-context', () => ({@@ -14,6 +15,9 @@ vi.mock('@main/core/execution-context/local-execution-context', () => ({},}));+// Reaches the settings store, and through it the database, at import time.+vi.mock('@main/core/telemetry/telemetry-service', () => ({ trackEvent: mocks.trackEvent }));+vi.mock('@switch-console/core/deps/runtime', () => ({resolveCommandPath: mocks.resolveCommandPath,}));@@ -399,6 +403,11 @@ describe('switchSetupService mutations', () => {['plugin', 'install', 'switch-connector@switch-plugins', '-s', 'user'],expect.anything());+ expect(mocks.trackEvent).toHaveBeenCalledWith('connector_installed', {+ agent_type: 'claude',+ target: 'local',+ outcome: 'success',+ });});it('uninstall issues the scoped uninstall command', async () => {@@ -439,6 +448,23 @@ describe('switchSetupService mutations', () => {expect(result.success).toBe(false);expect(result.message).toBe('no write access');+ expect(mocks.trackEvent).toHaveBeenCalledWith('connector_installed', {+ agent_type: 'claude',+ target: 'local',+ outcome: 'failure',+ });+ });++ it('reports nothing when the agent type has no Switch setup to attempt', async () => {+ mocks.getPlugin.mockReturnValue(NONE_AGENT);++ const result = await switchSetupService.install('no-switch-agent');++ expect(result).toEqual({+ success: false,+ message: 'Switch setup is not supported for this agent.',+ });+ expect(mocks.trackEvent).not.toHaveBeenCalled();});});@@ -646,6 +672,7 @@ describe('switchSetupService with the codex dialect', () => {describe('file-based connector version', () => {const installedVersion = vi.fn();+ const install = vi.fn();const FILES_AGENT = {metadata: { id: 'opencode' },capabilities: {@@ -656,7 +683,7 @@ describe('file-based connector version', () => {},hostDependency: { binaryNames: ['opencode'] },},- behavior: { switchSetup: { files: { installedVersion } } },+ behavior: { switchSetup: { files: { installedVersion, install } } },};beforeEach(() => {@@ -686,4 +713,48 @@ describe('file-based connector version', () => {expect(status.installed).toBe(true);expect(status.updateAvailable).toBe(false);});++ // The app writes this connector rather than driving a marketplace CLI for it,+ // and it is still a connector being installed.+ it('reports an install the app performs itself', async () => {+ install.mockResolvedValue(undefined);++ const result = await switchSetupService.install('opencode');++ expect(result).toEqual({ success: true });+ expect(mocks.trackEvent).toHaveBeenCalledWith('connector_installed', {+ agent_type: 'opencode',+ target: 'local',+ outcome: 'success',+ });+ });++ it('reports its failure too', async () => {+ install.mockRejectedValue(new Error('permission denied'));++ const result = await switchSetupService.install('opencode');++ expect(result.success).toBe(false);+ expect(mocks.trackEvent).toHaveBeenCalledWith('connector_installed', {+ agent_type: 'opencode',+ target: 'local',+ outcome: 'failure',+ });+ });++ it('still answers, and still reports, when the connector implements nothing', async () => {+ // A plugin can declare a files connector and supply no behaviour for it.+ // The user asked for an install: they get a failure, not a rejected promise+ // reaching the UI as a stack trace with nothing recorded.+ mocks.getPlugin.mockReturnValue({ ...FILES_AGENT, behavior: { switchSetup: {} } });++ const result = await switchSetupService.install('opencode');++ expect(result.success).toBe(false);+ expect(mocks.trackEvent).toHaveBeenCalledWith('connector_installed', {+ agent_type: 'opencode',+ target: 'local',+ outcome: 'failure',+ });+ });});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.ts b/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.tsindex a8a4697c3..f074a207f 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-setup/switch-setup-service.ts@@ -5,8 +5,10 @@ import type { ISwitchSetupFilesBehavior, PluginFs } from '@switch-console/core/aimport { resolveCommandPath } from '@switch-console/core/deps/runtime';import { type ArtifactName, artifactVersion } from '@switch-console/shared';import { LocalExecutionContext } from '@main/core/execution-context/local-execution-context';+import { trackEvent } from '@main/core/telemetry/telemetry-service';import { log } from '@main/lib/logger';import { isNewerVersion } from '@main/lib/semver';+import { isValidProviderId } from '@shared/core/providers/agent-provider-registry';import type { AgentTypeAvailability } from '@shared/core/switch-setup/agent-type-availability';import { createPluginFs } from '../providers/plugin-fs';import { getPlugin, listPlugins } from '../providers/plugin-registry';@@ -382,12 +384,44 @@ class SwitchSetupService {}async install(agentId: string): Promise<SwitchSetupResult> {+ const { result, attempted } = await this.runInstall(agentId);+ // An agent type with no connector to install did not fail to install one.+ if (attempted) {+ trackEvent('connector_installed', {+ agent_type: isValidProviderId(agentId) ? agentId : 'unknown',+ target: 'local',+ outcome: result.success ? 'success' : 'failure',+ });+ }+ return result;+ }++ private async runInstall(+ agentId: string+ ): Promise<{ result: SwitchSetupResult; attempted: boolean }> {if (getPlugin(agentId).capabilities.switchSetup.kind === 'files') {- return this.runFiles(agentId, (files, fs, version) => files.install(fs, { version }));+ // `runFiles` resolves the behavior outside its own try, and that throws+ // for a connector that declares files and implements none. An install the+ // user asked for must come back as a failed result either way — a+ // rejection here would skip the report and reach the UI as a stack.+ try {+ const result = await this.runFiles(agentId, (files, fs, version) =>+ files.install(fs, { version })+ );+ return { result, attempted: true };+ } catch (err) {+ return {+ result: { success: false, message: installFailureMessage(String(err)) },+ attempted: true,+ };+ }}const resolved = await this.resolve(agentId);if (!resolved)- return { success: false, message: 'Switch setup is not supported for this agent.' };+ return {+ result: { success: false, message: 'Switch setup is not supported for this agent.' },+ attempted: false,+ };const { descriptor, bin, ref, rules } = resolved;try {await this.ensureMarketplace(@@ -397,12 +431,19 @@ class SwitchSetupService {rules);} catch (err) {- return { success: false, message: installFailureMessage(String(err)) };+ return {+ result: { success: false, message: installFailureMessage(String(err)) },+ attempted: true,+ };}const res = await this.run(bin, rules.installArgs(ref, descriptor.scope));- return res.code === 0- ? { success: true }- : { success: false, message: installFailureMessage(res.stderr.trim()) };+ return {+ result:+ res.code === 0+ ? { success: true }+ : { success: false, message: installFailureMessage(res.stderr.trim()) },+ attempted: true,+ };}/**diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/config.test.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/config.test.tsnew file mode 100644index 000000000..28f08ac43--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/config.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from 'vitest';+import {+ resolveTelemetryEnvironment,+ TELEMETRY_RELAY_ENDPOINT,+ type TelemetryBuildChannel,+ type TelemetryEnvironment,+} from './config';++function resolve(build: TelemetryBuildChannel, env: TelemetryEnvironment['env'] = {}) {+ return resolveTelemetryEnvironment({ build, env });+}++describe('a dev run', () => {+ it('is off until a developer opts in', () => {+ expect(resolve('dev')).toEqual({ enabled: false, reason: 'dev_build' });+ });++ it('reports to the relay once opted in', () => {+ expect(resolve('dev', { SWITCHDASH_TELEMETRY_DEV: '1' })).toEqual({+ enabled: true,+ config: { endpoint: TELEMETRY_RELAY_ENDPOINT, build: 'dev' },+ });+ });++ it('can be pointed at a local listener, so what it sends can be watched', () => {+ const resolution = resolve('dev', {+ SWITCHDASH_TELEMETRY_DEV: '1',+ SWITCHDASH_TELEMETRY_ENDPOINT: 'http://127.0.0.1:9009',+ });++ expect(resolution.enabled && resolution.config.endpoint).toBe('http://127.0.0.1:9009');+ });++ it('ignores a blank override rather than posting nowhere', () => {+ const resolution = resolve('dev', {+ SWITCHDASH_TELEMETRY_DEV: '1',+ SWITCHDASH_TELEMETRY_ENDPOINT: ' ',+ });++ expect(resolution.enabled && resolution.config.endpoint).toBe(TELEMETRY_RELAY_ENDPOINT);+ });+});++describe.each(['stable', 'canary'] as const)('a %s build', (build) => {+ it('reports to the relay, with nothing to configure', () => {+ // The relay holds the vendor keys, so unlike the direct-to-Amplitude shape+ // this replaced, there is no build that is inert for want of a key.+ expect(resolve(build)).toEqual({+ enabled: true,+ config: { endpoint: TELEMETRY_RELAY_ENDPOINT, build },+ });+ });++ it('cannot be redirected away from the relay', () => {+ // Otherwise anything able to set a variable before launch — a shell+ // profile, a launch script, an MDM policy — could collect a consenting+ // user's events somewhere of its own.+ const resolution = resolve(build, {+ SWITCHDASH_TELEMETRY_ENDPOINT: 'http://somewhere.example',+ });++ expect(resolution.enabled && resolution.config.endpoint).toBe(TELEMETRY_RELAY_ENDPOINT);+ });++ it('ignores the dev opt-in switch', () => {+ const resolution = resolve(build, { SWITCHDASH_TELEMETRY_DEV: '1' });++ expect(resolution.enabled && resolution.config.build).toBe(build);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/config.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/config.tsnew file mode 100644index 000000000..b812640db--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/config.ts@@ -0,0 +1,86 @@+import { IS_CANARY } from '@shared/app-identity';++type ImportMetaWithEnv = ImportMeta & { env?: { DEV?: boolean } };++const viteEnv = (import.meta as ImportMetaWithEnv).env;++/**+ * The company's public OTLP relay, which forwards to Amplitude and Datadog.+ *+ * It holds both vendor keys server-side, which is the whole reason to use it. A+ * desktop app cannot keep a credential — anything compiled into it ships to+ * every user and can be read straight back out — so this way nothing of ours is+ * in the binary at all, and no build needs configuring to report.+ *+ * Unauthenticated by design, and guarded by requiring a client id instead: see+ * `./relay-client`. Public rather than internal — the same endpoint a public+ * GitHub Action posts to from a customer's CI.+ *+ * It is another product's hostname, written down in an open-source repository:+ * anyone reading this learns where the app reports to, which is a thing users+ * are entitled to know but was not ours to decide unilaterally. Adopted with+ * the collaborating dev's agreement, pending the product owner's.+ */+export const TELEMETRY_RELAY_ENDPOINT = 'https://telemetry.flintai.dev/v1/logs';++/** Which build sent an event, so a developer's app cannot pollute real numbers. */+export type TelemetryBuildChannel = 'dev' | 'canary' | 'stable';++export type TelemetryConfig = {+ endpoint: string;+ build: TelemetryBuildChannel;+};++/**+ * Why a build reports nothing. Only one reason now: the relay needs no key, so+ * there is no longer such a thing as a build that was configured wrongly.+ */+export type TelemetryDisabledReason = 'dev_build';++export type TelemetryResolution =+ | { enabled: true; config: TelemetryConfig }+ | { enabled: false; reason: TelemetryDisabledReason };++export function telemetryBuildChannel(): TelemetryBuildChannel {+ if (viteEnv?.DEV === true) return 'dev';+ return IS_CANARY ? 'canary' : 'stable';+}++/** Everything the decision depends on, so that it depends on nothing else. */+export type TelemetryEnvironment = {+ build: TelemetryBuildChannel;+ env: NodeJS.ProcessEnv;+};++/**+ * Whether this build can send at all, before any question of consent.+ *+ * Taken as an argument rather than read from the ambient environment, because+ * `import.meta.env.DEV` is replaced at build time: a test cannot become a+ * packaged build, and the rules that apply only to one are exactly the rules+ * worth proving.+ *+ * A dev run sends nothing unless `SWITCHDASH_TELEMETRY_DEV=1`, mirroring how the+ * updater stays inert outside packaged builds. With it set, a dev run can be+ * pointed elsewhere with `SWITCHDASH_TELEMETRY_ENDPOINT` — at a local listener+ * to read what it sends, or at a relay running locally. Dev-only: a shipped+ * build reports to the relay or not at all, so nothing able to set a variable+ * before launch can redirect a consenting user's events somewhere else.+ */+export function resolveTelemetryEnvironment({+ build,+ env,+}: TelemetryEnvironment): TelemetryResolution {+ const isDev = build === 'dev';+ if (isDev && env.SWITCHDASH_TELEMETRY_DEV !== '1') {+ return { enabled: false, reason: 'dev_build' };+ }++ const override = isDev ? env.SWITCHDASH_TELEMETRY_ENDPOINT?.trim() : undefined;+ return { enabled: true, config: { endpoint: override || TELEMETRY_RELAY_ENDPOINT, build } };+}++/** The same decision for the build that is actually running. */+export function resolveTelemetryConfig(): TelemetryResolution {+ return resolveTelemetryEnvironment({ build: telemetryBuildChannel(), env: process.env });+}diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/consent.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/consent.tsindex 077458e55..ae590c793 100644--- a/console/apps/switch-console-desktop/src/main/core/telemetry/consent.ts+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/consent.ts@@ -13,11 +13,11 @@ import { appSettingsService } from '@main/core/settings/settings-service';* that has not reached the prompt sends nothing, and a settings read that* throws sends nothing either.*- * There is no telemetry in the app today — this is the gate the collection work- * (CHOO-1683) is expected to call once there is something to send. What it may- * send is constrained: see the payload rule in `console/AGENTS.md`. Anonymous- * counters only, and no identifier of any kind, because the toggle defaults to- * on and an opt-out default is only defensible for non-personal data.+ * The toggle defaults to off: what is sent carries a random per-install id, and+ * that makes the data pseudonymous rather than anonymous, which an opt-out+ * default would not cover. What may be sent is constrained beyond that — see+ * the payload rule in `console/AGENTS.md` and the closed event catalogue in+ * `./events`.*/export async function isTelemetryAllowed(): Promise<boolean> {const telemetry = await appSettingsService.get('telemetry');diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/events.tsnew file mode 100644index 000000000..a326f9e3d--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/events.ts@@ -0,0 +1,106 @@+import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';++/**+ * Where the thing being reported ran: this machine, or an SSH host.+ *+ * `unknown` is sent rather than guessed when the record that would say has gone+ * — a wrong answer here would be indistinguishable from a real one.+ */+export type TelemetryLocationKind = 'local' | 'remote' | 'unknown';++/**+ * Which CLI agent this concerns.+ *+ * `unknown` covers a value that is not one of the registered providers. The+ * column it comes from is typed rather than constrained, so this is checked at+ * the emitter rather than trusted — an unrecognised value is reported as+ * unrecognised and never passed through as free text.+ */+export type TelemetryAgentType = AgentProviderId | 'unknown';++/**+ * Every event the app may send, and everything each one may carry.+ *+ * The property types are the enforcement, not documentation: literal unions and+ * numbers only, so a caller cannot reach a payload with a path, a name, an+ * error message or anything else free-text. Adding a `string` here removes that+ * guarantee for the whole catalogue — add a union of the values you mean.+ *+ * The ambient fields every event carries — app version, operating system, build+ * channel, install id — are added by the emitter and are not repeated here.+ *+ * Keep this set small. It exists to answer "is the app used, and where does it+ * break"; a question the current set cannot answer is the bar for adding to it,+ * and it is far easier to add an event than to take one away once dashboards+ * depend on it.+ */+/**+ * An event with no properties of its own. `Record<never, never>` rather than+ * `Record<string, never>`, whose `keyof` is `string` — which claims every+ * property name, including the ambient ones the emitter adds.+ */+type NoProperties = Record<never, never>;++export type TelemetryEventMap = {+ /** The app started. Its interesting fields are the ambient ones. */+ app_launched: NoProperties;+ agent_created: {+ agent_type: TelemetryAgentType;+ location: TelemetryLocationKind;+ };+ session_started: {+ agent_type: TelemetryAgentType;+ location: TelemetryLocationKind;+ };+ /**+ * A session finished. `normal` is a session the user ended (deleted or+ * archived); `failed` is one whose agent process died and could not be+ * recovered. A session still running when the app quits reports neither.+ */+ session_ended: {+ agent_type: TelemetryAgentType;+ location: TelemetryLocationKind;+ outcome: 'normal' | 'failed';+ };+ server_added: {+ /** `external` is a server the user registered by URL: Switch Console does not run it. */+ server_kind: 'local' | 'remote_managed' | 'external';+ };+ connector_installed: {+ agent_type: TelemetryAgentType;+ target: TelemetryLocationKind;+ outcome: 'success' | 'failure';+ };+};++export type TelemetryEventName = keyof TelemetryEventMap;++/**+ * The properties each event may carry, as data rather than as types alone.+ *+ * The types above are the design; this is what the emitter enforces at runtime.+ * A property that is not named here is dropped before the payload is built, so+ * a field that reaches a call site through a spread — where excess-property+ * checking does not apply — cannot ride along into a payload unnoticed.+ */+export const TELEMETRY_EVENT_PROPERTIES = {+ app_launched: [],+ agent_created: ['agent_type', 'location'],+ session_started: ['agent_type', 'location'],+ session_ended: ['agent_type', 'location', 'outcome'],+ server_added: ['server_kind'],+ connector_installed: ['agent_type', 'target', 'outcome'],+} as const satisfies { [K in TelemetryEventName]: readonly (keyof TelemetryEventMap[K])[] };++/** Which events, if any, declare a property the emitter also adds. */+type EventsDeclaringAmbientProperty = {+ [K in TelemetryEventName]: 'build' extends keyof TelemetryEventMap[K] ? K : never;+}[TelemetryEventName];++/**+ * `build` is added to every payload by the emitter, and added last, so an event+ * declaring one of its own would have it silently overwritten. This fails to+ * compile rather than letting that happen quietly.+ */+const _buildIsReserved: [EventsDeclaringAmbientProperty] extends [never] ? true : never = true;+void _buildIsReserved;diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/install-id.test.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/install-id.test.tsnew file mode 100644index 000000000..6219cd2d8--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/install-id.test.ts@@ -0,0 +1,110 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { store } = vi.hoisted(() => ({+ store: { get: vi.fn(), setOrThrow: vi.fn() },+}));++vi.mock('@main/db/kv', () => ({+ KV: class {+ get = store.get;+ setOrThrow = store.setOrThrow;+ },+}));++/** The module memoises, so each case needs its own instance of it. */+async function loadModule() {+ vi.resetModules();+ return import('./install-id');+}++beforeEach(() => {+ vi.clearAllMocks();+ store.get.mockResolvedValue(null);+ store.setOrThrow.mockResolvedValue(undefined);+});++/**+ * The relay's guard, verbatim from its `filter/guard` processor. A payload+ * whose client id does not match is dropped — and answered with a 200, so+ * nothing downstream would ever tell us. This id is that client id.+ */+const CANONICAL_UUID =+ /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;+const NIL_UUID = '00000000-0000-0000-0000-000000000000';++describe('the install id', () => {+ it('is created and stored the first time it is needed', async () => {+ const { getInstallId } = await loadModule();++ const id = await getInstallId();++ expect(id).toMatch(CANONICAL_UUID);+ expect(store.setOrThrow).toHaveBeenCalledWith('installId', id);+ });++ it('is a shape the relay will accept, since it is silent when it will not', async () => {+ const { getInstallId } = await loadModule();++ const id = await getInstallId();++ expect(id).toMatch(CANONICAL_UUID);+ expect(id).not.toBe(NIL_UUID);+ });++ it('is the one already stored, when there is one', async () => {+ store.get.mockResolvedValue('stored-id');+ const { getInstallId } = await loadModule();++ await expect(getInstallId()).resolves.toBe('stored-id');+ expect(store.setOrThrow).not.toHaveBeenCalled();+ });++ it('is not the id the removed telemetry stack left behind', async () => {+ // That value lives under `telemetry:instanceId` in databases predating its+ // removal. Reading the same key would carry an identifier forward out of a+ // system users were told had been taken out.+ const { getInstallId } = await loadModule();++ await getInstallId();++ expect(store.get).toHaveBeenCalledWith('installId');+ expect(store.get).not.toHaveBeenCalledWith('instanceId');+ });++ it('is minted once, however many callers ask at the same moment', async () => {+ const { getInstallId } = await loadModule();++ const ids = await Promise.all([getInstallId(), getInstallId(), getInstallId()]);++ expect(new Set(ids).size).toBe(1);+ expect(store.setOrThrow).toHaveBeenCalledTimes(1);+ });++ it('is read once and reused, not fetched per event', async () => {+ store.get.mockResolvedValue('stored-id');+ const { getInstallId } = await loadModule();++ await getInstallId();+ await getInstallId();++ expect(store.get).toHaveBeenCalledTimes(1);+ });++ it('reports a failed write rather than returning an id nothing remembers', async () => {+ store.setOrThrow.mockRejectedValue(new Error('database is locked'));+ const { getInstallId } = await loadModule();++ await expect(getInstallId()).rejects.toThrow('database is locked');+ });++ it('can still be obtained after a failed write, rather than failing forever', async () => {+ // The memoised promise must not keep a rejection: every later event would+ // fail on a write that has long since stopped failing.+ store.setOrThrow.mockRejectedValueOnce(new Error('database is locked'));+ const { getInstallId } = await loadModule();++ await expect(getInstallId()).rejects.toThrow('database is locked');++ await expect(getInstallId()).resolves.toMatch(CANONICAL_UUID);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/install-id.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/install-id.tsnew file mode 100644index 000000000..a002dadf9--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/install-id.ts@@ -0,0 +1,44 @@+import { randomUUID } from 'node:crypto';+import { KV } from '@main/db/kv';++/**+ * Deliberately not `telemetry:instanceId`, which the telemetry stack removed in+ * CHOO-1370 wrote and no migration ever scrubbed: that row is still in the+ * database of every install predating the removal, and reusing it would carry+ * an identifier forward out of a system users were told had been taken out.+ */+const store = new KV<{ installId: string }>('telemetry');++let pending: Promise<string> | null = null;++/**+ * A random id for this installation, created on first use and kept in the local+ * database.+ *+ * It is what lets two events be recognised as coming from the same copy of the+ * app — which is the whole difference between counting events and counting+ * users. It is random: nothing about it is derived from the machine, the user+ * account, the network, or any Switch identity, and it is never sent anywhere+ * but Amplitude, alongside the events in `./events`.+ *+ * Because it makes the data pseudonymous rather than anonymous, it is the+ * reason consent is opt-in. Deleting the app's data directory produces a new+ * one; there is deliberately no way to correlate the two.+ */+export async function getInstallId(): Promise<string> {+ pending ??= load().catch((error: unknown) => {+ // A failed write must not poison every later send with a rejected promise.+ pending = null;+ throw error;+ });+ return pending;+}++async function load(): Promise<string> {+ const existing = await store.get('installId');+ if (existing) return existing;++ const created = randomUUID();+ await store.setOrThrow('installId', created);+ return created;+}diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/relay-client.test.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/relay-client.test.tsnew file mode 100644index 000000000..844683d05--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/relay-client.test.ts@@ -0,0 +1,278 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import type { TelemetryConfig } from './config';+import {+ buildOtlpPayload,+ postTelemetryEvent,+ TelemetrySendError,+ type TelemetryContext,+} from './relay-client';++const CONTEXT: TelemetryContext = {+ clientId: '11111111-2222-4333-8444-555555555555',+ appVersion: '1.2.3',+ osType: 'darwin',+ osVersion: '24.3.0',+ build: 'stable',+ timeMs: 1_700_000_000_000,+};++const CONFIG: TelemetryConfig = {+ endpoint: 'https://telemetry.example/v1/logs',+ build: 'stable',+};++type Attribute = { key: string; value: { stringValue: string } };++function resourceAttributes(payload: Record<string, unknown>): Record<string, string> {+ const resourceLogs = payload.resourceLogs as [{ resource: { attributes: Attribute[] } }];+ return Object.fromEntries(+ resourceLogs[0].resource.attributes.map((a) => [a.key, a.value.stringValue])+ );+}++function logRecord(payload: Record<string, unknown>): Record<string, unknown> {+ const resourceLogs = payload.resourceLogs as [+ { scopeLogs: [{ logRecords: [Record<string, unknown>] }] },+ ];+ return resourceLogs[0].scopeLogs[0].logRecords[0];+}++function logAttributes(payload: Record<string, unknown>): Record<string, string> {+ const attributes = logRecord(payload).attributes as Attribute[];+ return Object.fromEntries(attributes.map((a) => [a.key, a.value.stringValue]));+}++describe('the record that gets built', () => {+ it('carries the client id the relay requires, as a resource attribute', () => {+ // Without it the relay drops the whole payload — and still answers 200.+ const payload = buildOtlpPayload('app_launched', {}, CONTEXT);++ expect(resourceAttributes(payload)['flint.client_id']).toBe(CONTEXT.clientId);+ });++ it('says which app and version it is, for both destinations', () => {+ const payload = buildOtlpPayload('app_launched', {}, CONTEXT);++ expect(resourceAttributes(payload)).toEqual({+ 'service.name': 'switch-console',+ 'service.version': '1.2.3',+ 'flint.client_id': CONTEXT.clientId,+ 'os.type': 'darwin',+ 'os.version': '24.3.0',+ });+ });++ it('names the event under this product, since one project holds them all', () => {+ const payload = buildOtlpPayload(+ 'session_started',+ { agent_type: 'codex', location: 'local' },+ CONTEXT+ );++ expect(logAttributes(payload)['event.name']).toBe('switch_console.session_started');+ });++ it('names it in the record field too, which is what the relay reads first', () => {+ // The attribute alone gets a record past the relay's "is it named?" filter+ // and then dropped by an exporter that only reads the field — silently, and+ // with a 200 at every step. Both, or nothing arrives and nothing says so.+ const payload = buildOtlpPayload('app_launched', {}, CONTEXT);++ expect(logRecord(payload).eventName).toBe('switch_console.app_launched');+ });++ it('carries the catalogued properties, plus which build sent it', () => {+ const payload = buildOtlpPayload(+ 'session_ended',+ { agent_type: 'codex', location: 'remote', outcome: 'failed' },+ CONTEXT+ );++ expect(logAttributes(payload)).toEqual({+ 'event.name': 'switch_console.session_ended',+ agent_type: 'codex',+ location: 'remote',+ outcome: 'failed',+ build: 'stable',+ });+ });++ it('drops a property the catalogue does not name', () => {+ // Excess-property checking does not apply through a spread, so a field+ // added to some internal shape for an unrelated reason can reach a call+ // site without the compiler objecting. This is where it stops.+ const smuggled = {+ agent_type: 'codex',+ location: 'remote',+ outcome: 'failed',+ working_dir: '/Users/someone/secret-project',+ } as never;++ const payload = buildOtlpPayload('session_ended', smuggled, CONTEXT);++ expect(logAttributes(payload)).not.toHaveProperty('working_dir');+ expect(JSON.stringify(payload)).not.toContain('secret-project');+ });++ it('sends an event with no properties of its own as just its name and build', () => {+ const payload = buildOtlpPayload('app_launched', {}, CONTEXT);++ expect(logAttributes(payload)).toEqual({+ 'event.name': 'switch_console.app_launched',+ build: 'stable',+ });+ });++ it('carries a body, so the event is not a blank line in the log sink', () => {+ // The relay forwards the same record to Datadog, which reads the body as+ // the message. It repeats the name rather than adding anything new.+ const payload = buildOtlpPayload('app_launched', {}, CONTEXT);++ expect(logRecord(payload).body).toEqual({ stringValue: 'switch_console.app_launched' });+ });++ it('refuses to invent a property the catalogue promised', () => {+ // Coercing a missing value would put the string "undefined" into the data+ // as though it were an answer. Better to lose the event and say so.+ const incomplete = { agent_type: 'codex' } as never;++ expect(() => buildOtlpPayload('session_ended', incomplete, CONTEXT)).toThrow(+ /missing the catalogued property/+ );+ });++ it('stamps the time in nanoseconds, which is what OTLP counts in', () => {+ const payload = buildOtlpPayload('app_launched', {}, CONTEXT);++ const record = logRecord(payload);+ expect(record.timeUnixNano).toBe('1700000000000000000');+ expect(record.observedTimeUnixNano).toBe('1700000000000000000');+ });++ it('stays far under the attribute count the relay drops a record for', () => {+ // The guard drops any record with more than 128 attributes.+ const payload = buildOtlpPayload(+ 'connector_installed',+ { agent_type: 'claude', target: 'remote', outcome: 'success' },+ CONTEXT+ );++ expect(Object.keys(logAttributes(payload)).length).toBeLessThan(16);+ });+});++describe('sending it', () => {+ const fetchMock = vi.fn();++ beforeEach(() => {+ vi.stubGlobal('fetch', fetchMock);+ fetchMock.mockReset();+ // What the relay actually answers: a 200 whose body reports nothing+ // rejected. A double without `json` would not be a Response.+ fetchMock.mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({ partialSuccess: {} }),+ } as unknown as Response);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it('posts OTLP JSON to the configured endpoint', async () => {+ await postTelemetryEvent({ resourceLogs: [] }, CONFIG);++ const [url, init] = fetchMock.mock.calls[0] as [+ string,+ { body: string; method: string; headers: Record<string, string> },+ ];+ expect(url).toBe(CONFIG.endpoint);+ expect(init.method).toBe('POST');+ expect(init.headers['Content-Type']).toBe('application/json');+ expect(JSON.parse(init.body)).toEqual({ resourceLogs: [] });+ });++ it('carries no credential, because the relay holds them instead', async () => {+ await postTelemetryEvent({ resourceLogs: [] }, CONFIG);++ const [, init] = fetchMock.mock.calls[0] as [string, { headers: Record<string, string> }];+ expect(Object.keys(init.headers).sort()).toEqual(['Content-Type', 'User-Agent']);+ expect(init.headers['User-Agent']).toBe('switch-console');+ });++ it('reports records the relay says it would not take', async () => {+ // A 200 is the answer to a dropped payload as well as an accepted one, so+ // the only rejection this end can ever see is the one it is told about.+ fetchMock.mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({+ partialSuccess: { rejectedLogRecords: '1', errorMessage: 'nope' },+ }),+ } as unknown as Response);++ await expect(postTelemetryEvent({}, CONFIG)).rejects.toMatchObject({ code: 'rejected' });+ });++ it('treats the ordinary empty partial success as success', async () => {+ fetchMock.mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({ partialSuccess: {} }),+ } as unknown as Response);++ await expect(postTelemetryEvent({}, CONFIG)).resolves.toBeUndefined();+ });++ it('does not fail an accepted send over a body it cannot parse', async () => {+ fetchMock.mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => {+ throw new Error('not json');+ },+ } as unknown as Response);++ await expect(postTelemetryEvent({}, CONFIG)).resolves.toBeUndefined();+ });++ it('gives up rather than retrying when the relay refuses', async () => {+ fetchMock.mockResolvedValue({ ok: false, status: 503 } as Response);++ await expect(postTelemetryEvent({}, CONFIG)).rejects.toMatchObject({ code: 'http_status' });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('tells a network failure apart from a refusal', async () => {+ fetchMock.mockRejectedValue(new Error('getaddrinfo ENOTFOUND'));++ await expect(postTelemetryEvent({}, CONFIG)).rejects.toMatchObject({ code: 'network' });+ });++ it('tells a timeout apart from both', async () => {+ const timeout = new Error('The operation was aborted due to timeout');+ timeout.name = 'TimeoutError';+ fetchMock.mockRejectedValue(timeout);++ await expect(postTelemetryEvent({}, CONFIG)).rejects.toMatchObject({ code: 'timeout' });+ });++ it('is written against what this runtime actually names a timeout', async () => {+ // The test above hands the branch an error it made up. This one checks the+ // name it made up is the one Node really produces — otherwise both agree+ // with each other and neither agrees with production.+ const signal = AbortSignal.timeout(1);+ const aborted = new Promise<Error>((resolve) =>+ signal.addEventListener('abort', () => resolve(signal.reason as Error))+ );++ await expect(aborted).resolves.toMatchObject({ name: 'TimeoutError' });+ });++ it('throws something a caller can classify without parsing a message', async () => {+ fetchMock.mockResolvedValue({ ok: false, status: 400 } as Response);++ await expect(postTelemetryEvent({}, CONFIG)).rejects.toBeInstanceOf(TelemetrySendError);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/relay-client.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/relay-client.tsnew file mode 100644index 000000000..78d7a3b83--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/relay-client.ts@@ -0,0 +1,229 @@+import type { TelemetryConfig } from './config';+import {+ TELEMETRY_EVENT_PROPERTIES,+ type TelemetryEventMap,+ type TelemetryEventName,+} from './events';++const SEND_TIMEOUT_MS = 10_000;++/**+ * Events from every product share one Amplitude project, so a bare+ * `session_started` would sit next to another product's and nobody could tell+ * whose it was.+ */+const EVENT_NAME_PREFIX = 'switch_console';++/** What the app calls itself to the relay, and to Datadog beyond it. */+const SERVICE_NAME = 'switch-console';++/**+ * Sent in place of whatever the HTTP client would otherwise volunteer, so that+ * everything leaving the machine is chosen here — and so the relay's operators+ * can see which client their traffic is coming from.+ */+const USER_AGENT = SERVICE_NAME;++/**+ * The name is sent twice, in both of the places the relay looks.+ *+ * `eventName` is the OTLP log record's own field and the first thing the+ * relay's exporter reads — it is what the reference client sends, and the only+ * form older builds of that exporter understand at all. The attribute is its+ * documented fallback, and is separately what the relay's "drop records with no+ * name" filter tests.+ *+ * Sending one was not enough: a record naming itself only in the attribute+ * survives the filter and reaches the exporter with an empty name field, which+ * an exporter without the fallback discards. Every step of that answers 200, so+ * nothing here would ever have seen it happen.+ */+const EVENT_NAME_ATTRIBUTE = 'event.name';++export type TelemetrySendErrorCode =+ | 'timeout'+ | 'network'+ | 'http_status'+ | 'rejected'+ | 'unexpected';++export class TelemetrySendError extends Error {+ constructor(+ readonly code: TelemetrySendErrorCode,+ message: string+ ) {+ super(message);+ this.name = 'TelemetrySendError';+ }+}++/** The ambient facts every event carries, resolved once per send. */+export type TelemetryContext = {+ /**+ * The relay's guard: a canonical UUID identifying this installation, which it+ * requires on every payload and forwards as Amplitude's device id. A payload+ * without one is dropped in silence.+ */+ clientId: string;+ appVersion: string;+ osType: string;+ osVersion: string;+ build: TelemetryConfig['build'];+ timeMs: number;+};++type OtlpAttribute = { key: string; value: { stringValue: string } };++/** Everything sent is a string; nothing in the catalogue is anything else. */+function attributes(values: Record<string, string>): OtlpAttribute[] {+ return Object.entries(values).map(([key, value]) => ({ key, value: { stringValue: value } }));+}++/**+ * Keep only the properties the catalogue names for this event.+ *+ * The types make an unexpected property a compile error at every call site that+ * passes an object literal — but not through a spread, which is how a field+ * added to some internal shape for an unrelated reason could otherwise arrive+ * in a payload. This is where that stops being a convention.+ */+function allowedProperties<K extends TelemetryEventName>(+ name: K,+ properties: TelemetryEventMap[K]+): Record<string, string> {+ const allowed: Record<string, string> = {};+ for (const key of TELEMETRY_EVENT_PROPERTIES[name]) {+ const value = (properties as Record<string, unknown>)[key];+ // Coercing a missing property would send the string "undefined" as though+ // it were data. Refusing means the event is dropped and the mismatch is+ // logged, which is the lesser of the two.+ if (typeof value !== 'string') {+ throw new TelemetrySendError(+ 'unexpected',+ `Event ${name} is missing the catalogued property ${key}`+ );+ }+ allowed[key] = value;+ }+ return allowed;+}++/**+ * One event, as a single OTLP log record.+ *+ * The relay turns this into an Amplitude event — the name becomes `event_type`,+ * the client id becomes `device_id`, and the log attributes become+ * `event_properties` — and forwards the same record to Datadog. Both+ * destinations see exactly what is built here and nothing else.+ */+export function buildOtlpPayload<K extends TelemetryEventName>(+ name: K,+ properties: TelemetryEventMap[K],+ context: TelemetryContext+): Record<string, unknown> {+ const timeNano = String(BigInt(context.timeMs) * 1_000_000n);+ const eventName = `${EVENT_NAME_PREFIX}.${name}`;++ return {+ resourceLogs: [+ {+ resource: {+ attributes: attributes({+ 'service.name': SERVICE_NAME,+ 'service.version': context.appVersion,+ 'flint.client_id': context.clientId,+ 'os.type': context.osType,+ 'os.version': context.osVersion,+ }),+ },+ scopeLogs: [+ {+ scope: { name: SERVICE_NAME, version: context.appVersion },+ logRecords: [+ {+ timeUnixNano: timeNano,+ observedTimeUnixNano: timeNano,+ eventName,+ severityNumber: 9,+ severityText: 'INFO',+ // The relay forwards the same record to Datadog, which reads+ // the body as the log message. Without one every event is a+ // blank line there. The name is already leaving the machine as+ // an attribute, so repeating it here discloses nothing new.+ body: { stringValue: eventName },+ attributes: attributes({+ [EVENT_NAME_ATTRIBUTE]: eventName,+ ...allowedProperties(name, properties),+ build: context.build,+ }),+ },+ ],+ },+ ],+ },+ ],+ };+}++/**+ * Post one event to the relay.+ *+ * A direct `fetch` of hand-built OTLP rather than the OpenTelemetry SDK,+ * deliberately: what leaves the machine, and when, is the promise being made to+ * the user, and an SDK brings its own batching, retry and identity behaviour.+ * Everything sent is visible in this file. The cost is that the wire format is+ * ours to keep correct, which is what the tests are for.+ *+ * Throws {@link TelemetrySendError} on any failure. There is no retry — an event+ * lost to a flaky network is lost, which is the right trade for something the+ * user never sees and must never wait on.+ *+ * A 200 does not prove the event arrived. The relay drops a payload it cannot+ * name or whose client id fails its guard, and answers 200 either way — so the+ * partial-success body is read for the cases where it does say something.+ */+export async function postTelemetryEvent(+ payload: Record<string, unknown>,+ config: TelemetryConfig+): Promise<void> {+ let response: Response;+ try {+ response = await fetch(config.endpoint, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json', 'User-Agent': USER_AGENT },+ body: JSON.stringify(payload),+ signal: AbortSignal.timeout(SEND_TIMEOUT_MS),+ });+ } catch (error) {+ const timedOut = error instanceof Error && error.name === 'TimeoutError';+ throw new TelemetrySendError(timedOut ? 'timeout' : 'network', String(error));+ }++ if (!response.ok) {+ throw new TelemetrySendError('http_status', `Relay responded ${response.status}`);+ }++ await reportRejection(response);+}++/**+ * OTLP allows a 200 to carry a count of records the receiver would not take.+ *+ * Today's relay drops on a failed guard without reporting one, so this will+ * usually be empty — but it is the only channel through which a rejection can+ * ever become visible from here, and reading it costs one parse of a very small+ * body. A response that is not JSON at all is not worth a second failure.+ */+async function reportRejection(response: Response): Promise<void> {+ const body = (await response.json().catch(() => null)) as {+ partialSuccess?: { rejectedLogRecords?: string | number; errorMessage?: string };+ } | null;++ const rejected = Number(body?.partialSuccess?.rejectedLogRecords ?? 0);+ if (!rejected) return;++ throw new TelemetrySendError(+ 'rejected',+ `Relay rejected ${rejected} record(s): ${body?.partialSuccess?.errorMessage ?? 'no reason given'}`+ );+}diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/telemetry-listeners.test.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/telemetry-listeners.test.tsnew file mode 100644index 000000000..aa195a5d5--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/telemetry-listeners.test.ts@@ -0,0 +1,316 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++/**+ * The two buses are kept apart here on purpose.+ *+ * `sessionService` and `sessionHooks` both carry an event called+ * `session:deleted`, and they fire on different paths — the second is how a+ * session pruned from its remote host is reported. Collapsing them into one map+ * of handlers, as an obvious test double would, makes a subscription to only+ * one of them look identical to a subscription to both.+ */+const { buses } = vi.hoisted(() => {+ type Handler = (...args: never[]) => void | Promise<void>;+ const make = () => {+ const handlers = new Map<string, Handler>();+ return {+ on: (name: string, handler: Handler) => handlers.set(name, handler),+ handlers,+ };+ };+ return { buses: { agents: make(), sessionService: make(), sessionHooks: make() } };+});++vi.mock('@main/core/agents/agent-events', () => ({ agentEvents: { on: buses.agents.on } }));+vi.mock('@main/core/sessions/session-service', () => ({+ sessionService: { on: buses.sessionService.on },+}));+vi.mock('@main/core/sessions/session-hooks', () => ({+ sessionHooks: { on: buses.sessionHooks.on },+}));+vi.mock('@main/core/agents/getAgentById', () => ({ getAgentById: vi.fn() }));+vi.mock('@main/core/locations/store', () => ({ getLocationById: vi.fn() }));+vi.mock('@main/core/sessions/operations/getSession', () => ({ getSession: vi.fn() }));+vi.mock('./telemetry-service', () => ({ trackEvent: vi.fn() }));++import { getAgentById } from '@main/core/agents/getAgentById';+import { getLocationById } from '@main/core/locations/store';+import { getSession } from '@main/core/sessions/operations/getSession';+import { registerTelemetryListeners } from './telemetry-listeners';+import { trackEvent } from './telemetry-service';++type Bus = keyof typeof buses;++async function emit(bus: Bus, name: string, ...args: unknown[]): Promise<void> {+ const handler = buses[bus].handlers.get(name);+ if (!handler) throw new Error(`nothing on the ${bus} bus subscribed to ${name}`);+ await (handler as (...a: unknown[]) => void | Promise<void>)(...args);+}++function onLocation(kind: 'local' | 'remote' | 'missing') {+ vi.mocked(getLocationById).mockResolvedValue(+ kind === 'missing'+ ? undefined+ : ({ id: 'loc', sshHost: kind === 'remote' ? 'host' : null } as never)+ );+}++function startSession(id: string, providerId = 'claude') {+ vi.mocked(getAgentById).mockResolvedValue({ id: 'agent', locationId: 'loc' } as never);+ return emit('sessionService', 'session:created', { id, agentId: 'agent', providerId });+}++registerTelemetryListeners();++beforeEach(() => {+ vi.mocked(trackEvent).mockClear();+});++describe('agent_created', () => {+ it('reports where the agent runs', async () => {+ onLocation('remote');++ await emit('agents', 'agent:created', { providerId: 'codex', locationId: 'loc' });++ expect(trackEvent).toHaveBeenCalledWith('agent_created', {+ agent_type: 'codex',+ location: 'remote',+ });+ });++ it('says unknown rather than guessing when the location has gone', async () => {+ onLocation('missing');++ await emit('agents', 'agent:created', { providerId: 'codex', locationId: 'gone' });++ expect(trackEvent).toHaveBeenCalledWith('agent_created', {+ agent_type: 'codex',+ location: 'unknown',+ });+ });++ it('does not pass through a provider id it does not recognise', async () => {+ // The column it comes from is typed, not constrained, so an unexpected+ // value would otherwise become free text in a payload.+ onLocation('local');++ await emit('agents', 'agent:created', {+ providerId: '/Users/someone/custom-agent',+ locationId: 'loc',+ });++ expect(trackEvent).toHaveBeenCalledWith('agent_created', {+ agent_type: 'unknown',+ location: 'local',+ });+ });+});++describe('a session ending', () => {+ it('reports a deliberate end as normal', async () => {+ onLocation('local');+ await startSession('s-normal');+ expect(trackEvent).toHaveBeenCalledWith('session_started', {+ agent_type: 'claude',+ location: 'local',+ });++ await emit('sessionService', 'session:archived', 's-normal');++ expect(trackEvent).toHaveBeenCalledWith('session_ended', {+ agent_type: 'claude',+ location: 'local',+ outcome: 'normal',+ });+ });++ it('reports an exhausted crash as failed, with what the session was', async () => {+ onLocation('remote');+ await startSession('s-crash');++ await emit('sessionHooks', 'session:agent-exited', {+ sessionId: 's-crash',+ decision: 'failed',+ });++ expect(trackEvent).toHaveBeenCalledWith('session_ended', {+ agent_type: 'claude',+ location: 'remote',+ outcome: 'failed',+ });+ });++ it('counts a crash that is about to be respawned as no ending at all', async () => {+ onLocation('local');+ await startSession('s-respawn');+ vi.mocked(trackEvent).mockClear();++ await emit('sessionHooks', 'session:agent-exited', {+ sessionId: 's-respawn',+ decision: 'respawnResume',+ });++ expect(trackEvent).not.toHaveBeenCalled();+ });++ it('ends a session once, not once per way of ending', async () => {+ onLocation('local');+ await startSession('s-twice');+ await emit('sessionHooks', 'session:agent-exited', {+ sessionId: 's-twice',+ decision: 'failed',+ });+ vi.mocked(trackEvent).mockClear();++ await emit('sessionService', 'session:deleted', 's-twice');++ expect(trackEvent).not.toHaveBeenCalled();+ });++ it('reports one pruned from its remote host, which arrives on the other bus', async () => {+ // The reconciler deletes the row itself when a session has gone from the+ // VM, or was terminated from another client. Subscribing only to the+ // session service leaves those reporting a start and never an end.+ onLocation('remote');+ await startSession('s-pruned');+ vi.mocked(trackEvent).mockClear();++ await emit('sessionHooks', 'session:deleted', 's-pruned');++ expect(trackEvent).toHaveBeenCalledWith('session_ended', {+ agent_type: 'claude',+ location: 'remote',+ outcome: 'normal',+ });+ });+});++describe('a session that outlived a restart', () => {+ it('is recognised when its runtime comes back, without counting as new', async () => {+ onLocation('remote');+ vi.mocked(getSession).mockResolvedValue({ id: 's-restored', providerId: 'codex' } as never);++ await emit('sessionService', 'session:runtime-ready', 's-restored', {+ path: '/somewhere',+ locationId: 'loc',+ });++ expect(trackEvent).not.toHaveBeenCalled();++ await emit('sessionService', 'session:deleted', 's-restored');++ expect(trackEvent).toHaveBeenCalledWith('session_ended', {+ agent_type: 'codex',+ location: 'remote',+ outcome: 'normal',+ });+ });++ it('does not overwrite what a session that started here is known to be', async () => {+ onLocation('local');+ await startSession('s-known');+ vi.mocked(getSession).mockResolvedValue({ id: 's-known', providerId: 'codex' } as never);+ onLocation('remote');++ await emit('sessionService', 'session:runtime-ready', 's-known', {+ path: '/somewhere',+ locationId: 'loc',+ });+ await emit('sessionService', 'session:deleted', 's-known');++ expect(trackEvent).toHaveBeenLastCalledWith('session_ended', {+ agent_type: 'claude',+ location: 'local',+ outcome: 'normal',+ });+ });++ it('is still reported as unknown if its row has gone by the time it ends', async () => {+ vi.mocked(getSession).mockResolvedValue(null);++ await emit('sessionService', 'session:runtime-ready', 's-vanished', {+ path: '/somewhere',+ locationId: 'loc',+ });+ await emit('sessionService', 'session:deleted', 's-vanished');++ expect(trackEvent).toHaveBeenCalledWith('session_ended', {+ agent_type: 'unknown',+ location: 'unknown',+ outcome: 'normal',+ });+ });+});++describe('a session that dies before we know what it was', () => {+ // A session is created with its agent already running, so these handlers can+ // genuinely interleave. `emit` awaits each handler to completion, so the race+ // has to be built deliberately rather than hoped for.+ it('is not reported as starting after it has already ended', async () => {+ let releaseLookup = () => {};+ vi.mocked(getAgentById).mockReturnValue(+ new Promise((resolve) => {+ releaseLookup = () => resolve({ id: 'agent', locationId: 'loc' } as never);+ }) as never+ );+ onLocation('local');++ const created = emit('sessionService', 'session:created', {+ id: 's-fast-crash',+ agentId: 'agent',+ providerId: 'claude',+ });+ await emit('sessionHooks', 'session:agent-exited', {+ sessionId: 's-fast-crash',+ decision: 'failed',+ });+ releaseLookup();+ await created;++ expect(trackEvent).toHaveBeenCalledTimes(1);+ expect(trackEvent).toHaveBeenCalledWith('session_ended', {+ agent_type: 'unknown',+ location: 'unknown',+ outcome: 'failed',+ });+ });++ it('leaves nothing behind when it ends twice', async () => {+ // The second ending reports nothing, but it must still clear the entry —+ // otherwise the map keeps it for the life of the process.+ onLocation('local');+ await startSession('s-double');+ await emit('sessionService', 'session:archived', 's-double');+ vi.mocked(trackEvent).mockClear();++ await emit('sessionHooks', 'session:deleted', 's-double');++ expect(trackEvent).not.toHaveBeenCalled();+ });+});++describe('the memory of what has ended', () => {+ it('does not grow without limit', async () => {+ // A long-running app ends a lot of sessions; the set only exists to+ // recognise a second ending moments after the first.+ for (let i = 0; i < 300; i++) {+ await emit('sessionService', 'session:deleted', `bulk-${i}`);+ }+ vi.mocked(trackEvent).mockClear();++ // The oldest have been forgotten, so this one reports again rather than+ // being suppressed forever.+ await emit('sessionService', 'session:deleted', 'bulk-0');++ expect(trackEvent).toHaveBeenCalledTimes(1);+ });++ it('still suppresses a repeat that arrives while it is remembered', async () => {+ await emit('sessionService', 'session:deleted', 'recent');+ vi.mocked(trackEvent).mockClear();++ await emit('sessionService', 'session:deleted', 'recent');++ expect(trackEvent).not.toHaveBeenCalled();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/telemetry-listeners.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/telemetry-listeners.tsnew file mode 100644index 000000000..bb35da458--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/telemetry-listeners.ts@@ -0,0 +1,155 @@+import { agentEvents } from '@main/core/agents/agent-events';+import { getAgentById } from '@main/core/agents/getAgentById';+import { getLocationById } from '@main/core/locations/store';+import { getSession } from '@main/core/sessions/operations/getSession';+import { sessionHooks } from '@main/core/sessions/session-hooks';+import { sessionService } from '@main/core/sessions/session-service';+import {+ isValidProviderId,+ type AgentProviderId,+} from '@shared/core/providers/agent-provider-registry';+import type { TelemetryEventMap, TelemetryLocationKind } from './events';+import { trackEvent } from './telemetry-service';++type SessionShape = {+ agent_type: AgentProviderId | 'unknown';+ location: TelemetryLocationKind;+};++const UNKNOWN_SESSION: SessionShape = { agent_type: 'unknown', location: 'unknown' };++/**+ * How many ended sessions to remember. Only enough to recognise a second ending+ * for the same session, which follows the first within moments; the set is+ * otherwise an unbounded record of everything that ever ran.+ */+const ENDED_SESSION_MEMORY = 256;++/**+ * What each live session is, remembered when it starts so its end can be+ * reported without a database read on a path that must stay cheap.+ */+const liveSessions = new Map<string, SessionShape>();++/**+ * Sessions that have already reported an end. A session whose agent crashed for+ * good and is deleted afterwards has ended once, not twice — without this the+ * same session counts as both a failure and a normal end.+ */+const endedSessions = new Set<string>();++/** A provider id straight from the database is typed, not validated. */+function agentTypeOf(providerId: string): AgentProviderId | 'unknown' {+ return isValidProviderId(providerId) ? providerId : 'unknown';+}++async function locationKindOf(locationId: string): Promise<TelemetryLocationKind> {+ const location = await getLocationById(locationId);+ if (!location) return 'unknown';+ return location.sshHost ? 'remote' : 'local';+}++function rememberEnded(sessionId: string): void {+ endedSessions.add(sessionId);+ if (endedSessions.size <= ENDED_SESSION_MEMORY) return;++ const oldest = endedSessions.values().next();+ if (!oldest.done) endedSessions.delete(oldest.value);+}++function endSession(sessionId: string, outcome: TelemetryEventMap['session_ended']['outcome']) {+ const shape = liveSessions.get(sessionId) ?? UNKNOWN_SESSION;+ // Forget it either way. A second ending reports nothing, but it must still+ // clear the entry, or a session that ends twice stays in the map for good.+ liveSessions.delete(sessionId);++ if (endedSessions.has(sessionId)) return;+ rememberEnded(sessionId);+ trackEvent('session_ended', { ...shape, outcome });+}++/**+ * Learn what a session is without reporting it as a new one.+ *+ * A session that outlives a restart is provisioned again rather than created,+ * so this run never sees it start. Recording it here is what stops its eventual+ * end being filed under `unknown` — which, since restoring live sessions is+ * routine, would otherwise be most of the ends the app ever reports.+ *+ * Provisioning also happens right after a create, and again on every re-open,+ * so the guard below usually skips the reads. Usually, not always: a create and+ * its provision run concurrently, so this occasionally repeats work the created+ * handler is doing. Two cheap reads on a path that is already opening a+ * terminal, in exchange for not having to care about the ordering.+ */+async function rememberSession(sessionId: string, locationId: string): Promise<void> {+ if (liveSessions.has(sessionId) || endedSessions.has(sessionId)) return;++ const session = await getSession(sessionId);+ if (!session) return;++ const shape: SessionShape = {+ agent_type: agentTypeOf(session.providerId),+ location: await locationKindOf(locationId),+ };++ // Checked again after the reads, for the same reason as in the created+ // handler: the session may have ended while they were in flight.+ if (endedSessions.has(sessionId)) return;+ liveSessions.set(sessionId, shape);+}++/**+ * Subscribe the telemetry emitter to the six product moments it reports.+ *+ * Deliberately one place rather than a `trackEvent` sprinkled through each+ * domain: what the app reports about itself should be readable in a single+ * file, both for review and for anyone checking the promise made to the user.+ * The two moments with no hook bus to subscribe to — a server being added and a+ * connector being installed — call `trackEvent` at their own site.+ */+export function registerTelemetryListeners(): void {+ agentEvents.on('agent:created', async (agent) => {+ trackEvent('agent_created', {+ agent_type: agentTypeOf(agent.providerId),+ location: await locationKindOf(agent.locationId),+ });+ });++ sessionService.on('session:created', async (session) => {+ const agent = await getAgentById(session.agentId);+ const shape: SessionShape = {+ agent_type: agentTypeOf(session.providerId),+ location: agent ? await locationKindOf(agent.locationId) : 'unknown',+ };++ // A session is created with its agent already running, so one that dies+ // immediately can be reported as ended while this handler is still working+ // out what it was. Reporting the start now would place it after its own+ // end, and would put back an entry nothing will ever remove.+ if (endedSessions.has(session.id)) return;++ liveSessions.set(session.id, shape);+ trackEvent('session_started', shape);+ });++ sessionService.on('session:runtime-ready', async (sessionId, result) => {+ await rememberSession(sessionId, result.locationId);+ });++ sessionService.on('session:deleted', (sessionId) => endSession(sessionId, 'normal'));+ sessionService.on('session:archived', (sessionId) => endSession(sessionId, 'normal'));++ // Rows deleted outside the sessionService path — the remote-session+ // reconciler pruning a session that has gone from its VM, or one terminated+ // from another client — arrive on the other bus. Subscribing to only one+ // leaves those sessions reporting a start and never an end.+ sessionHooks.on('session:deleted', (sessionId) => endSession(sessionId, 'normal'));++ // Only a decision of `failed` is an ending: the supervisor's other unexpected+ // exits are followed by a respawn, and the session goes on.+ sessionHooks.on('session:agent-exited', ({ sessionId, decision }) => {+ if (decision !== 'failed') return;+ endSession(sessionId, 'failed');+ });+}diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/telemetry-service.test.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/telemetry-service.test.tsnew file mode 100644index 000000000..a2eb5999d--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/telemetry-service.test.ts@@ -0,0 +1,252 @@+import { release } from 'node:os';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++vi.mock('@main/lib/logger', () => ({+ log: { debug: vi.fn(), info: vi.fn(), warn: vi.fn(), error: vi.fn() },+}));+vi.mock('@main/core/app/utils', () => ({ resolveAppVersion: vi.fn(async () => '1.2.3') }));+vi.mock('./consent', () => ({ isTelemetryAllowed: vi.fn() }));+vi.mock('./install-id', () => ({ getInstallId: vi.fn(async () => 'install-abc') }));++import { log } from '@main/lib/logger';+import { isTelemetryAllowed } from './consent';+import { telemetryService, trackEvent } from './telemetry-service';++const fetchMock = vi.fn();++function sentBody(): Record<string, unknown> {+ const [, init] = fetchMock.mock.calls[0] as [string, { body: string }];+ return JSON.parse(init.body) as Record<string, unknown>;+}++type Attribute = { key: string; value: { stringValue: string } };++function sentRecord(): Record<string, unknown> {+ const resourceLogs = sentBody().resourceLogs as [+ { scopeLogs: [{ logRecords: [Record<string, unknown>] }] },+ ];+ return resourceLogs[0].scopeLogs[0].logRecords[0];+}++function sentResource(): Record<string, string> {+ const resourceLogs = sentBody().resourceLogs as [{ resource: { attributes: Attribute[] } }];+ return Object.fromEntries(+ resourceLogs[0].resource.attributes.map((a) => [a.key, a.value.stringValue])+ );+}++function sentAttributes(): Record<string, string> {+ return Object.fromEntries(+ (sentRecord().attributes as Attribute[]).map((a) => [a.key, a.value.stringValue])+ );+}++beforeEach(() => {+ vi.clearAllMocks();+ vi.stubGlobal('fetch', fetchMock);+ fetchMock.mockResolvedValue({+ ok: true,+ status: 200,+ json: async () => ({ partialSuccess: {} }),+ } as unknown as Response);+ // A test run is a dev build, so telemetry is off unless a dev opts in — the+ // same switch a developer uses to watch the traffic locally.+ process.env.SWITCHDASH_TELEMETRY_DEV = '1';+ delete process.env.SWITCHDASH_TELEMETRY_ENDPOINT;+});++afterEach(() => {+ vi.unstubAllGlobals();+ delete process.env.SWITCHDASH_TELEMETRY_DEV;+});++describe('the consent gate', () => {+ it('makes no request at all when consent is off', async () => {+ vi.mocked(isTelemetryAllowed).mockResolvedValue(false);++ await telemetryService.track('app_launched', {});++ expect(fetchMock).not.toHaveBeenCalled();+ });++ it('asks the gate again for every event, so revoking consent stops the next one', async () => {+ vi.mocked(isTelemetryAllowed).mockResolvedValueOnce(true).mockResolvedValueOnce(false);++ await telemetryService.track('app_launched', {});+ await telemetryService.track('app_launched', {});++ expect(isTelemetryAllowed).toHaveBeenCalledTimes(2);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ });++ it('sends once consent is given', async () => {+ vi.mocked(isTelemetryAllowed).mockResolvedValue(true);++ await telemetryService.track('agent_created', { agent_type: 'codex', location: 'remote' });++ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url] = fetchMock.mock.calls[0] as [string];+ expect(url).toBe('https://telemetry.flintai.dev/v1/logs');+ });+});++describe('a build that cannot send', () => {+ /**+ * A reason is reported once per process, and the service is a module+ * singleton — so each of these takes a fresh one rather than depending on+ * which test ran first. Sharing it made two of these pass only in+ * declaration order, and fail under a shuffled run.+ */+ async function freshService() {+ vi.resetModules();+ const module = await import('./telemetry-service');+ return module.telemetryService;+ }++ it('makes no request from a dev run that has not opted in, and says so', async () => {+ delete process.env.SWITCHDASH_TELEMETRY_DEV;+ vi.mocked(isTelemetryAllowed).mockResolvedValue(true);+ const service = await freshService();++ await service.track('app_launched', {});++ expect(fetchMock).not.toHaveBeenCalled();+ expect(isTelemetryAllowed).not.toHaveBeenCalled();+ expect(log.info).toHaveBeenCalledWith(+ 'telemetry: not sending',+ expect.objectContaining({ reason: 'dev_build' })+ );+ });++ it('says it once, however many events are dropped', async () => {+ delete process.env.SWITCHDASH_TELEMETRY_DEV;+ const service = await freshService();++ await service.track('app_launched', {});+ await service.track('app_launched', {});+ await service.track('app_launched', {});++ expect(log.info).toHaveBeenCalledTimes(1);+ });+});++describe('the payload', () => {+ beforeEach(() => {+ vi.mocked(isTelemetryAllowed).mockResolvedValue(true);+ });++ it('identifies the install, and no user', async () => {+ // The relay reads this as Amplitude's device id. It sets a user id only+ // for a caller that sends one, which this is not.+ await telemetryService.track('session_started', { agent_type: 'claude', location: 'local' });++ expect(sentResource()['flint.client_id']).toBe('install-abc');+ expect(sentResource()).not.toHaveProperty('flint.user_id');+ });++ it('stamps the event when it happened, not after the reads that describe it', async () => {+ // The gate and the install id are both awaited between the two, and on a+ // first send the install id is a write. Taking the time afterwards would+ // date every event by however long its own bookkeeping took.+ const now = vi.spyOn(Date, 'now');+ now.mockReturnValueOnce(1_000).mockReturnValue(9_000);++ await telemetryService.track('app_launched', {});++ expect(sentRecord().timeUnixNano).toBe('1000000000');+ now.mockRestore();+ });++ it('carries the event, the build and the app version', async () => {+ await telemetryService.track('connector_installed', {+ agent_type: 'claude',+ target: 'remote',+ outcome: 'failure',+ });++ expect(sentResource()['service.version']).toBe('1.2.3');+ expect(sentAttributes()).toEqual({+ 'event.name': 'switch_console.connector_installed',+ agent_type: 'claude',+ target: 'remote',+ outcome: 'failure',+ build: 'dev',+ });+ });++ it('names the operating system it is actually running on', async () => {+ const expected = { darwin: 'darwin', win32: 'windows', linux: 'linux' }[+ process.platform as string+ ];++ await telemetryService.track('app_launched', {});++ expect(sentResource()['os.type']).toBe(expected ?? 'other');+ expect(sentResource()['os.version']).toBe(release());+ });++ it('sends nothing beyond the fields this test names', async () => {+ // A substring search for forbidden words would pass whatever the payload+ // contained, since nothing here could produce them. Pinning the whole set+ // of keys is what actually notices a new field arriving.+ await telemetryService.track('session_ended', {+ agent_type: 'codex',+ location: 'remote',+ outcome: 'failed',+ });++ expect(Object.keys(sentResource()).sort()).toEqual([+ 'flint.client_id',+ 'os.type',+ 'os.version',+ 'service.name',+ 'service.version',+ ]);+ expect(Object.keys(sentAttributes()).sort()).toEqual([+ 'agent_type',+ 'build',+ 'event.name',+ 'location',+ 'outcome',+ ]);+ });+});++describe('failure', () => {+ beforeEach(() => {+ vi.mocked(isTelemetryAllowed).mockResolvedValue(true);+ });++ it('never reaches the caller, and is logged with a code', async () => {+ fetchMock.mockResolvedValue({ ok: false, status: 503 } as Response);++ expect(() => trackEvent('app_launched', {})).not.toThrow();+ await vi.waitFor(() =>+ expect(log.warn).toHaveBeenCalledWith(+ 'telemetry: event not sent',+ expect.objectContaining({ errorCode: 'http_status' })+ )+ );+ });++ it('reports a network failure as such rather than as a send', async () => {+ fetchMock.mockRejectedValue(new Error('getaddrinfo ENOTFOUND'));++ trackEvent('app_launched', {});++ await vi.waitFor(() =>+ expect(log.warn).toHaveBeenCalledWith(+ 'telemetry: event not sent',+ expect.objectContaining({ errorCode: 'network' })+ )+ );+ });++ it('does not retry', async () => {+ fetchMock.mockResolvedValue({ ok: false, status: 500 } as Response);++ await telemetryService.track('app_launched', {}).catch(() => {});++ expect(fetchMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/telemetry/telemetry-service.ts b/console/apps/switch-console-desktop/src/main/core/telemetry/telemetry-service.tsnew file mode 100644index 000000000..14d9ef983--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/telemetry/telemetry-service.ts@@ -0,0 +1,96 @@+import { release } from 'node:os';+import { resolveAppVersion } from '@main/core/app/utils';+import { log } from '@main/lib/logger';+import { resolveTelemetryConfig, type TelemetryDisabledReason } from './config';+import { isTelemetryAllowed } from './consent';+import type { TelemetryEventMap, TelemetryEventName } from './events';+import { getInstallId } from './install-id';+import { buildOtlpPayload, postTelemetryEvent, TelemetrySendError } from './relay-client';++/** OpenTelemetry's names for what `process.platform` calls darwin/win32/linux. */+const OS_TYPES: Record<string, string> = {+ darwin: 'darwin',+ win32: 'windows',+ linux: 'linux',+};++class TelemetryService {+ private reportedDisabled = new Set<TelemetryDisabledReason>();+ private appVersion: Promise<string> | null = null;++ /**+ * Send one event, if this build can send and the user has said yes.+ *+ * The consent gate is read here, on every event, and never cached: revoking+ * consent has to stop the next event, not the next launch. Both refusals+ * return before anything is built or opened, so consent off means no request+ * is made at all.+ */+ async track<K extends TelemetryEventName>(+ name: K,+ properties: TelemetryEventMap[K]+ ): Promise<void> {+ const resolution = resolveTelemetryConfig();+ if (!resolution.enabled) {+ this.reportDisabled(resolution.reason);+ return;+ }++ // Before the gate, which reads the database: the event happened now, not+ // whenever the reads that describe it finish.+ const timeMs = Date.now();++ if (!(await isTelemetryAllowed())) return;++ const payload = buildOtlpPayload(name, properties, {+ clientId: await getInstallId(),+ appVersion: await this.resolveVersion(),+ osType: OS_TYPES[process.platform] ?? 'other',+ osVersion: release(),+ build: resolution.config.build,+ timeMs,+ });++ await postTelemetryEvent(payload, resolution.config);+ }++ private resolveVersion(): Promise<string> {+ this.appVersion ??= resolveAppVersion();+ return this.appVersion;+ }++ /**+ * Say once, per reason, that this build reports nothing — a build that is+ * silent should be able to explain itself. `info` rather than `warn`: a dev+ * run not reporting is the expected state, not a degraded one.+ */+ private reportDisabled(reason: TelemetryDisabledReason): void {+ if (this.reportedDisabled.has(reason)) return;+ this.reportedDisabled.add(reason);++ log.info('telemetry: not sending', { event: 'telemetry_disabled', reason });+ }+}++export const telemetryService = new TelemetryService();++/**+ * Record that something happened, and get on with the work.+ *+ * This is what call sites use: it never throws, never rejects, and is never+ * awaited, so no user-facing operation can be delayed or failed by telemetry.+ * A send that does not arrive is logged with a code and dropped.+ */+export function trackEvent<K extends TelemetryEventName>(+ name: K,+ properties: TelemetryEventMap[K]+): void {+ void telemetryService.track(name, properties).catch((error: unknown) => {+ log.warn('telemetry: event not sent', {+ event: 'telemetry_send_failed',+ telemetryEvent: name,+ errorCode: error instanceof TelemetrySendError ? error.code : 'unexpected',+ error: String(error),+ });+ });+}diff --git a/console/apps/switch-console-desktop/src/main/db/tests/migrations/0047-materialise-telemetry-consent.test.ts b/console/apps/switch-console-desktop/src/main/db/tests/migrations/0047-materialise-telemetry-consent.test.tsnew file mode 100644index 000000000..5a8320339--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/db/tests/migrations/0047-materialise-telemetry-consent.test.ts@@ -0,0 +1,151 @@+/**+ * Migration 0047 — preserves an agreement to share usage data across the change+ * of default that would otherwise silently revoke it.+ *+ * Settings rows hold only the fields that differed from the default when they+ * were written, so an agreement given while sharing defaulted to on was stored+ * as an `askedAt` with no `enabled` at all. Once the default is off, that row+ * reads as a refusal — and `askedAt` stops the prompt ever asking again.+ *+ * The test applies the committed SQL to an isolated `app_settings` table and+ * checks each shape of row that can exist: the one that must be repaired, and+ * the ones that already say what they mean and must be left untouched.+ */++import { readFileSync } from 'node:fs';+import path from 'node:path';+import { fileURLToPath } from 'node:url';+import Database from 'better-sqlite3';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++const MIGRATION_SQL = readFileSync(+ path.resolve(+ path.dirname(fileURLToPath(import.meta.url)),+ '../../../../../drizzle/0047_materialise_telemetry_consent.sql'+ ),+ 'utf8'+);++describe('migration 0047: materialise telemetry consent', () => {+ let db: Database.Database;++ beforeEach(() => {+ db = new Database(':memory:');+ db.exec(`+ CREATE TABLE app_settings (+ key TEXT PRIMARY KEY,+ value TEXT NOT NULL,+ updated_at INTEGER NOT NULL DEFAULT 0+ );+ `);+ });++ afterEach(() => {+ db.close();+ });++ function seed(key: string, value: Record<string, unknown>): void {+ db.prepare(`INSERT INTO app_settings (key, value) VALUES (?, ?)`).run(+ key,+ JSON.stringify(value)+ );+ }++ function stored(key: string): Record<string, unknown> {+ const row = db.prepare(`SELECT value FROM app_settings WHERE key = ?`).get(key) as+ | { value: string }+ | undefined;+ if (!row) throw new Error(`no row for ${key}`);+ return JSON.parse(row.value) as Record<string, unknown>;+ }++ function applyMigration(): void {+ for (const stmt of MIGRATION_SQL.split('--> statement-breakpoint')) {+ const trimmed = stmt.trim();+ if (trimmed) db.exec(trimmed);+ }+ }++ it('restores the agreement that the old default left unwritten', () => {+ seed('telemetry', { askedAt: 1_700_000_000_000 });++ applyMigration();++ expect(stored('telemetry')).toEqual({ askedAt: 1_700_000_000_000, enabled: true });+ });++ it('writes a real boolean, not a number sqlite would hand back as 1', () => {+ seed('telemetry', { askedAt: 1_700_000_000_000 });++ applyMigration();++ expect(stored('telemetry').enabled).toBe(true);+ });++ it('leaves a refusal alone', () => {+ seed('telemetry', { enabled: false, askedAt: 1_700_000_000_000 });++ applyMigration();++ expect(stored('telemetry')).toEqual({ enabled: false, askedAt: 1_700_000_000_000 });+ });++ it('leaves an agreement that was already written out alone', () => {+ seed('telemetry', { enabled: true, askedAt: 1_700_000_000_000 });++ applyMigration();++ expect(stored('telemetry')).toEqual({ enabled: true, askedAt: 1_700_000_000_000 });+ });++ it('leaves an explicit null alone rather than reading it as absent', () => {+ // Unreachable through the app's own writes, and worth pinning anyway: the+ // obvious `json_extract(...) IS NULL` test cannot tell this from a missing+ // key, and would answer on the user's behalf.+ db.prepare(`INSERT INTO app_settings (key, value) VALUES (?, ?)`).run(+ 'telemetry',+ '{"enabled": null, "askedAt": 1700000000000}'+ );++ applyMigration();++ expect(stored('telemetry').enabled).toBeNull();+ });++ it('steps over a row that is not JSON instead of failing the whole migration', () => {+ // Migrations run in one transaction and a failure stops the app starting,+ // so an unreadable settings row must cost only its own repair.+ db.prepare(`INSERT INTO app_settings (key, value) VALUES (?, ?)`).run('telemetry', 'not json');++ expect(() => applyMigration()).not.toThrow();+ expect(+ (+ db.prepare(`SELECT value FROM app_settings WHERE key = 'telemetry'`).get() as {+ value: string;+ }+ ).value+ ).toBe('not json');+ });++ it('does not answer for someone who was never asked', () => {+ // No `askedAt` means the prompt is still to come, and the gate refuses+ // until it has been. Inventing an agreement here would skip it entirely.+ seed('telemetry', { enabled: false });++ applyMigration();++ expect(stored('telemetry')).toEqual({ enabled: false });+ });++ it('touches no other setting', () => {+ seed('notifications', { askedAt: 1_700_000_000_000 });++ applyMigration();++ expect(stored('notifications')).toEqual({ askedAt: 1_700_000_000_000 });+ });++ it('is safe to run on a database that has no telemetry row', () => {+ expect(() => applyMigration()).not.toThrow();+ });+});diff --git a/console/apps/switch-console-desktop/src/main/index.ts b/console/apps/switch-console-desktop/src/main/index.tsindex 412befce0..8860ef7d5 100644--- a/console/apps/switch-console-desktop/src/main/index.ts+++ b/console/apps/switch-console-desktop/src/main/index.ts@@ -32,6 +32,8 @@ import { registerSidecarDiagnostics } from './core/sidecar/sidecar-diagnostics';import { sshConnectionManager } from './core/ssh/lifecycle/production-ssh-connection-manager';import { autoSessionWatcher } from './core/switch-rooms/auto-session-watcher';import { restoreSwitchRoomSessions } from './core/switch-rooms/restore-sessions';+import { registerTelemetryListeners } from './core/telemetry/telemetry-listeners';+import { trackEvent } from './core/telemetry/telemetry-service';import { updateService } from './core/updates/update-service';import { viewStateService } from './core/view-state/view-state-service';import { initializeDatabase } from './db/initialize';@@ -137,6 +139,11 @@ void app.whenReady().then(async () => {await appSettingsService.initialize();await promptLibraryService.initialize();+ // After the settings store, which owns the consent gate every event asks+ // before it is sent, and never before the database it is read from.+ registerTelemetryListeners();+ trackEvent('app_launched', {});+try {await resolveAgentServers();} catch (e) {diff --git a/console/apps/switch-console-desktop/src/renderer/features/settings/components/TelemetrySettingsCard.tsx b/console/apps/switch-console-desktop/src/renderer/features/settings/components/TelemetrySettingsCard.tsxindex af02a919d..8607ee62c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/settings/components/TelemetrySettingsCard.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/settings/components/TelemetrySettingsCard.tsx@@ -20,7 +20,7 @@ const TelemetrySettingsCard: React.FC = () => {isSaving: saving,} = useAppSettingsKey('telemetry');- const enabled = telemetry?.enabled ?? true;+ const enabled = telemetry?.enabled ?? false;const toggle = useCallback((next: boolean) => {@@ -33,7 +33,7 @@ const TelemetrySettingsCard: React.FC = () => {return (<SettingRow- title="Share anonymous usage data"+ title="Share usage data"description={<><p>{TELEMETRY_SUMMARY}</p>diff --git a/console/apps/switch-console-desktop/src/renderer/features/telemetry/TelemetryConsentDialog.tsx b/console/apps/switch-console-desktop/src/renderer/features/telemetry/TelemetryConsentDialog.tsxindex f833a4c5b..00ace4696 100644--- a/console/apps/switch-console-desktop/src/renderer/features/telemetry/TelemetryConsentDialog.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/telemetry/TelemetryConsentDialog.tsx@@ -50,13 +50,13 @@ function DisclosureList({** Rendered only when the user has never answered it, and not dismissible: the* answer is recorded by `askedAt`, so closing it without choosing would leave- * the app asking again on every launch. Declining is a first-class option, not- * a hidden one — the toggle starts on, matching the default, and the user can- * turn it off before continuing.+ * the app asking again on every launch. The toggle starts off, matching the+ * default: what is sent carries a random per-install id, so sharing has to be+ * something the user turns on rather than something they failed to turn off.*/export function TelemetryConsentDialog({ onAnswered }: { onAnswered: () => void }) {const { value, updateAsync } = useAppSettingsKey('telemetry');- const [enabled, setEnabled] = useState(value?.enabled ?? true);+ const [enabled, setEnabled] = useState(value?.enabled ?? false);const [saving, setSaving] = useState(false);const confirm = useCallback(() => {@@ -97,7 +97,7 @@ export function TelemetryConsentDialog({ onAnswered }: { onAnswered: () => void/><div className="mt-1 flex items-center justify-between gap-4 rounded-lg border border-border bg-background-1 p-3"><label htmlFor="telemetry-consent-switch" className="text-sm text-foreground">- Share anonymous usage data+ Share usage data</label><Switchid="telemetry-consent-switch"diff --git a/console/apps/switch-console-desktop/src/renderer/features/telemetry/telemetry-copy.ts b/console/apps/switch-console-desktop/src/renderer/features/telemetry/telemetry-copy.tsindex 9504873ff..b0367de1c 100644--- a/console/apps/switch-console-desktop/src/renderer/features/telemetry/telemetry-copy.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/telemetry/telemetry-copy.ts@@ -2,22 +2,36 @@* The disclosure shown to the user, in one place so the first-run prompt and* the Settings row cannot drift into promising different things.*- * These lists are a promise, not a description of a feature that exists: the- * app sends nothing today. Whatever eventually does the sending is held to them- * by the payload rule in `console/AGENTS.md`. Widening them is a consent- * decision, not a copy edit.+ * These lists are a promise, and what is sent is held to them by the payload+ * rule in `console/AGENTS.md` and by the closed event catalogue in+ * `src/main/core/telemetry/events.ts`. Widening them is a consent decision, not+ * a copy edit.*/export const TELEMETRY_SUMMARY =- 'Switch Console can share anonymous usage data to show which features get used and where the app runs into trouble.';+ 'Switch Console can share usage data to show which features get used and where the app runs into trouble.';export const TELEMETRY_SHARED = ['Which features are used, and how often',- 'Errors and crashes the app hits',+ 'Which coding agents you use, and whether they run here or on a remote host',+ 'Whether sessions end normally or fail','App version and operating system',+ 'A random id for this install, so one copy of the app can be told from another',];+// The location line says what this app does — it sends no address and no+// location — rather than what the services at the far end can work out.+//+// Today they can work out nothing: events go to our own relay, which calls the+// analytics services itself, so they see its address and never the user's. That+// is a property of the relay's configuration, in another repository, and its+// own documentation describes the change that would undo it (forwarding the+// original client IP so geography becomes usable again). A promise phrased+// about their end would quietly become false the day that lands, without a line+// changing here. Phrased about ours, it stays true and stays ours to keep.export const TELEMETRY_NEVER_SHARED = [- 'Anything that identifies you or your machine',+ 'Your name, email address, or sign-in',+ 'Your machine or its user account',+ 'Your IP address or location — the app sends neither','Your prompts, code, files, or file paths','Agent, room, project, or server names',];diff --git a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db b/console/apps/switch-console-desktop/tooling/fixtures/baseline.dbindex 6ccd07223..f61bda240 100644Binary files a/console/apps/switch-console-desktop/tooling/fixtures/baseline.db and b/console/apps/switch-console-desktop/tooling/fixtures/baseline.db differdiff --git a/console/apps/switch-console-desktop/tooling/fixtures/empty.db b/console/apps/switch-console-desktop/tooling/fixtures/empty.dbindex fe34e2a96..289640a58 100644Binary files a/console/apps/switch-console-desktop/tooling/fixtures/empty.db and b/console/apps/switch-console-desktop/tooling/fixtures/empty.db differ