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): one telemetry answer, honoured on the managed server too (CHOO-2890) (#529)
Louis Amaudruz8f68b1c85b3a
diff --git a/console/AGENTS.md b/console/AGENTS.mdindex b32f1051e..52c131bc3 100644--- a/console/AGENTS.md+++ b/console/AGENTS.md@@ -405,6 +405,17 @@ pnpm run lintsettings directly — it does not distinguish "said yes" from "not asked yet" — and do notcache the answer across a send, since the user can revoke it at any time. Consent offmeans **no request is made at all**, not a request whose result is discarded.+- **The answer reaches the managed server too, and never by omission.** "Share usage+ data" is one decision covering this app and a Switch server it runs, so `startStack`+ reads it and writes `TELEMETRY_ENABLED` into the stack's `.env` on every start —+ `false` as explicitly as `true`, because the compose file forwards the key only when+ the `.env` names it, and a stack started under a yes would otherwise keep reporting.+ Adding a variable to that contract needs both edits: `deploy/local/standalone-docker-compose.yml`+ plus `pnpm run sync:compose`, and `env-file.ts`. The server reads the gate once at+ boot, so a running stack can be out of step; that is surfaced on the server's page with+ a restart offered, never applied by restarting the user's server for them. Whether it+ is out of step is read off the running container, not inferred from what we last wrote —+ and a host that cannot be read is reported as unknown, never as agreeing.- **The toggle defaults to off.** The payload carries a random per-install id, which makesit 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,diff --git a/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.ts b/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.tsindex 67c648425..6b086dd1e 100644--- a/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.ts+++ b/console/apps/switch-console-desktop/src/main/core/agents/agent-model-catalogue.ts@@ -48,6 +48,14 @@ export async function getAgentModelCatalogue(params: {dir: string;}): Promise<AgentModelCatalogue> {if (['claude', 'codex', 'cursor', 'antigravity'].includes(params.providerId)) {+ // Listing Antigravity's models means starting a real ACP session, and+ // starting one signs in — which opens a browser when there is no cached+ // token. Opening the agent form is not a request to sign in, so ask the+ // read-only probe first and stop here when the answer is no.+ if (params.providerId === 'antigravity') {+ const probe = await getProviderReadiness(params, false);+ if (probe.status !== 'authenticated') return { kind: 'unavailable', reason: probe.message };+ }const readiness = await getProviderReadiness(params, true);return readiness.models.length? { kind: 'available', models: readiness.models.map((model) => ({ ...model, variants: [] })) }diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/compose.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/compose.tsindex 3d4383c63..380e9460c 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/compose.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/compose.ts@@ -31,7 +31,7 @@ function baseArgs(host: ServerHost, globalFlags: string[], extraFiles: string[]];}-async function runCompose(host: ServerHost, args: string[], timeout: number): Promise<string> {+async function runDocker(host: ServerHost, args: string[], timeout: number): Promise<string> {const full = [host.dockerBin, ...args];try {const { stdout } = await host.ctx.exec(host.dockerBin, args, {@@ -129,7 +129,7 @@ export function dockerRunOneOff(* data volumes (the reset path) — irreversible. */export async function composeDown(host: ServerHost, removeVolumes: boolean): Promise<void> {log.info(`local-switch-server: docker compose down${removeVolumes ? ' -v' : ''} (${host.label})`);- await runCompose(+ await runDocker(host,[...baseArgs(host, []), 'down', ...(removeVolumes ? ['-v'] : [])],5 * 60 * 1000@@ -139,7 +139,7 @@ export async function composeDown(host: ServerHost, removeVolumes: boolean): Pro/** Service names currently in the `running` state for the managed project. */export async function runningServices(host: ServerHost): Promise<string[]> {try {- const stdout = await runCompose(+ const stdout = await runDocker(host,[...baseArgs(host, []), 'ps', '--status', 'running', '--services'],60_000@@ -169,7 +169,7 @@ export async function isStackRunning(host: ServerHost): Promise<boolean> {* "nothing is running" from "could not ask".*/export async function runningImages(host: ServerHost): Promise<Map<string, string>> {- const stdout = await runCompose(+ const stdout = await runDocker(host,[...baseArgs(host, []), 'ps', '--status', 'running', '--format', 'json'],60_000@@ -181,7 +181,50 @@ export async function runningImages(host: ServerHost): Promise<Map<string, strinreturn images;}-type ComposePsEntry = { Service?: string; Image?: string };+/**+ * Environment of the running container for `service`, keyed by variable name.+ *+ * This is what the process is ACTUALLY running with, which the `.env` on disk+ * is not: that file is rewritten at the top of every start, so between a+ * rewrite and a `compose up` that failed it describes an intention rather than+ * a fact. For a setting the user has consented to, the difference is the whole+ * point of asking.+ *+ * Null when the service has no running container. Failures are not swallowed,+ * for the reason {@link runningImages} does not swallow them: "not running" and+ * "could not ask" are different answers.+ */+export async function runningServiceEnv(+ host: ServerHost,+ service: string+): Promise<Map<string, string> | null> {+ const listed = await runDocker(+ host,+ [...baseArgs(host, []), 'ps', '--status', 'running', '--format', 'json'],+ 60_000+ );+ const id = parseComposePs(listed).find((entry) => entry.Service === service)?.ID;+ if (!id) return null;++ const inspected = await runDocker(+ host,+ ['inspect', '--format', '{{json .Config.Env}}', id],+ 60_000+ );+ const parsed: unknown = JSON.parse(inspected.trim());+ if (!Array.isArray(parsed)) {+ throw new Error(`docker inspect ${service}: .Config.Env was not a list`);+ }+ const env = new Map<string, string>();+ for (const entry of parsed) {+ if (typeof entry !== 'string') continue;+ const split = entry.indexOf('=');+ if (split > 0) env.set(entry.slice(0, split), entry.slice(split + 1));+ }+ return env;+}++type ComposePsEntry = { Service?: string; Image?: string; ID?: string };/** Compose emits `ps --format json` as a JSON array on some versions and as* one JSON object per line on others; accept both. */diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/deployed-version.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/deployed-version.tsindex 2b5961756..dee7b0831 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/deployed-version.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/deployed-version.ts@@ -6,6 +6,7 @@ import type {} from '@shared/core/managed-switch-server/managed-switch-server';import { runningImages } from './compose';import { ENV_FILE_NAME } from './constants';+import { readEnvValue } from './env-file';import type { ServerHost } from './host/types';/**@@ -57,7 +58,7 @@ export async function readDeployedVersion(host: ServerHost): Promise<DeployedVer// No `.env` and no running container: nothing was ever deployed here.if (failures.length === 0) return { kind: 'absent' };} else {- const version = envVersion(env);+ const version = readEnvValue(env, 'SWITCH_VERSION');if (version) return { kind: 'deployed', version, source: 'env-file' };failures.push(`${ENV_FILE_NAME}: no SWITCH_VERSION entry`);}@@ -144,20 +145,6 @@ function imageTag(image: string): string | null {return tag.length > 0 ? tag : null;}-/** `SWITCH_VERSION` from a generated `.env`, unquoted, or null when absent. */-function envVersion(env: string): string | null {- for (const raw of env.split('\n')) {- const line = raw.trim();- if (!line.startsWith('SWITCH_VERSION=')) continue;- const value = line- .slice('SWITCH_VERSION='.length)- .trim()- .replace(/^["']|["']$/g, '');- if (value.length > 0) return value;- }- return null;-}-function errorText(error: unknown): string {return error instanceof Error ? error.message : String(error);}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.tsindex 55fff0fce..531a7598f 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.test.ts@@ -30,6 +30,7 @@ describe('buildEnvFile', () => {ports: { gateway: 51000, api: 51001, mattermost: 51002, postgres: 51003 },secrets,sessionDemo: false,+ telemetryEnabled: false,});const vars = Object.fromEntries(env@@ -135,10 +136,36 @@ describe('buildEnvFile', () => {ports: { gateway: 51000, api: 51001, mattermost: 51002, postgres: 51003 },secrets,sessionDemo: true,+ telemetryEnabled: false,});expect(fromCheckout).toContain('SESSION_DEMO_ENABLED=true');});+ it('carries the telemetry answer in both directions, never by omission', () => {+ // The compose file passes this key through only when the `.env` names it,+ // so leaving it out on "no" would let a stack started under a "yes" keep+ // reporting. Off has to be written down (CHOO-2890).+ expect(vars.TELEMETRY_ENABLED).toBe('false');++ const sharing = buildEnvFile({+ version: '1.2.3',+ registry: 'ghcr.io',+ namespace: 'sandbox-quantum',+ ports: { gateway: 51000, api: 51001, mattermost: 51002, postgres: 51003 },+ secrets,+ sessionDemo: false,+ telemetryEnabled: true,+ });+ expect(sharing).toContain('TELEMETRY_ENABLED=true');+ });++ it('is the only thing the compose file needs to forward the gate', () => {+ // A value in the `.env` that the `switch` service does not name never+ // reaches the container, which is the failure mode this pairing exists to+ // rule out — the writer and the contract have to agree.+ expect(composeYaml).toMatch(/^\s+TELEMETRY_ENABLED:\s*$/m);+ });+it('points the deeplink redirect at the API, not the operator UI', () => {// switch-core only rewrites `switchdash://` links into clickable http ones// when this is set, and serves the redirect on the agent-bridge app — sodiff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.tsindex bd0b88115..d9565e687 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/env-file.ts@@ -25,8 +25,18 @@ export type LocalServerEnvParams = {* of it. **Temporary** — goes when the demo does.*/sessionDemo: boolean;+ /**+ * The user's "Share usage data" answer, applied to the server as well as to+ * the app. One consent decision covers both, so this is the toggle's value+ * and nothing else — not a separate server-side preference (CHOO-2890).+ */+ telemetryEnabled: boolean;};+/** The variable the server reads its telemetry gate from. Named here because+ * reading the choice back off a host has to look for the same key. */+export const TELEMETRY_ENABLED_KEY = 'TELEMETRY_ENABLED';+/*** Render the `.env` docker compose interpolates for the local stack. Pure — the* host/user values are fixed by the compose contract, ports are chosen per@@ -34,7 +44,7 @@ export type LocalServerEnvParams = {* app's pin. Kept as a pure function so the exact output is unit-testable.*/export function buildEnvFile(params: LocalServerEnvParams): string {- const { version, registry, namespace, ports, secrets, sessionDemo } = params;+ const { version, registry, namespace, ports, secrets, sessionDemo, telemetryEnabled } = params;return ['# Generated by Switch Console local-server mode — do not edit by hand.','# Secrets originate in the app encrypted store; this file is derived.',@@ -77,6 +87,11 @@ export function buildEnvFile(params: LocalServerEnvParams): string {// reports in the deeplink it is rewriting.`GATEWAY_PUBLIC_URL=${apiUrlFor(ports)}`,...(sessionDemo ? ['SESSION_DEMO_ENABLED=true'] : []),+ // Written on every start, in both directions. Omitting it when the answer+ // is no would leave a stack that was started under a yes still reporting,+ // because the compose file passes this key through only when the `.env`+ // carries it — so "off" has to be said, not left unsaid.+ `${TELEMETRY_ENABLED_KEY}=${telemetryEnabled ? 'true' : 'false'}`,'','MATTERMOST_ADMIN_USER=admin',`MATTERMOST_ADMIN_PASSWORD=${secrets.mattermostAdminPassword}`,@@ -86,3 +101,24 @@ export function buildEnvFile(params: LocalServerEnvParams): string {'',].join('\n');}++/**+ * One variable's value out of a generated `.env`, unquoted, or null when the+ * file does not carry it (or carries it empty, which compose treats as unset).+ *+ * Lives beside the writer so reading a value back off a host cannot drift from+ * the format that wrote it.+ */+export function readEnvValue(env: string, key: string): string | null {+ const prefix = `${key}=`;+ for (const raw of env.split('\n')) {+ const line = raw.trim();+ if (!line.startsWith(prefix)) continue;+ const value = line+ .slice(prefix.length)+ .trim()+ .replace(/^["']|["']$/g, '');+ if (value.length > 0) return value;+ }+ return null;+}diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.tsindex 3cd262442..688349450 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/local-server-service.ts@@ -32,6 +32,7 @@ import { readVersionStatus } from './deployed-version';import { LocalServerHost } from './host/local-host';import type { ServerHost } from './host/types';import { resetStack, startStack, stopStack } from './pipeline';+import { readDeployedTelemetry } from './telemetry-consent';/*** Supervises the managed local Switch stack via the shared {@link startStack}@@ -51,6 +52,7 @@ class LocalServerService {deployedVersion: null,drift: null,checkoutBuild: null,+ deployedTelemetry: null,message: null,error: null,};@@ -128,6 +130,9 @@ class LocalServerService {if (!managed) return;if (await isStackRunning(host)) {this.setStatus({ phase: 'running', serverId: managed.id, message: null, error: null });+ // Only for a running stack: a stopped one sends nothing, so it cannot+ // be out of step with the user's answer.+ this.setStatus({ deployedTelemetry: await readDeployedTelemetry(host) });}const version = await readVersionStatus(host, COMPATIBLE_SWITCH_VERSION);// A checkout build is deliberately not a comparable version, so the pin@@ -191,6 +196,7 @@ class LocalServerService {error: null,deployedVersion: checkoutRoot !== null ? CHECKOUT_IMAGE_TAG : COMPATIBLE_SWITCH_VERSION,drift: null,+ deployedTelemetry: { known: true, enabled: result.telemetryEnabled },});}reportManagedServerStart('local', result);@@ -215,7 +221,7 @@ class LocalServerService {try {this.setStatus({ phase: 'stopping', message: 'Stopping containers…' });await stopStack(host);- this.setStatus({ phase: 'stopped', message: null, error: null });+ this.setStatus({ phase: 'stopped', message: null, error: null, deployedTelemetry: null });reportManagedServerOutcome('stop', 'local', 'success');} catch (error) {this.setStatus({@@ -247,7 +253,7 @@ class LocalServerService {if (server) await deleteAgentsForServer(server.id);this.setStatus({ phase: 'stopping', message: 'Destroying containers and data…' });await resetStack(host);- this.setStatus({ phase: 'stopped', message: null, error: null });+ this.setStatus({ phase: 'stopped', message: null, error: null, deployedTelemetry: null });reportManagedServerOutcome('reset', 'local', 'success');} catch (error) {this.setStatus({diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.tsindex 0560294cc..451b035ad 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline-matrix-migration.test.ts@@ -45,7 +45,15 @@ vi.mock('./ports', () => ({Promise.resolve({ gateway: 3300, api: 8000, mattermost: 8065, postgres: 5432 }),clearPorts: vi.fn(),}));-vi.mock('./env-file', () => ({ buildEnvFile: () => 'SWITCH_VERSION=0.24.0\n' }));+vi.mock('./env-file', () => ({+ buildEnvFile: () => 'SWITCH_VERSION=0.24.0\n',+ readEnvValue: vi.fn(),+ TELEMETRY_ENABLED_KEY: 'TELEMETRY_ENABLED',+}));+vi.mock('./telemetry-consent', () => ({+ telemetryConsent: () => Promise.resolve(false),+ readDeployedTelemetry: vi.fn(),+}));vi.mock('@main/core/switch-servers/servers-store', () => ({ensureManagedServer: () => Promise.resolve({ id: 'srv-1' }),setActiveServerId: vi.fn(),@@ -107,7 +115,11 @@ describe('startStack across the Matrix boundary', () => {return Promise.resolve();});- expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ expect(await startStack(opts)).toEqual({+ kind: 'started',+ serverId: 'srv-1',+ telemetryEnabled: false,+ });// The old stack comes up and is drained before the new compose file lands:// that file is what removes the homeserver being read from.expect(order.slice(0, 3)).toEqual(['compose-up', 'backfill', 'write']);@@ -159,7 +171,11 @@ describe('startStack across the Matrix boundary', () => {});const { opts } = options();- expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ expect(await startStack(opts)).toEqual({+ kind: 'started',+ serverId: 'srv-1',+ telemetryEnabled: false,+ });expect(dockerRunOneOffMock).not.toHaveBeenCalled();});diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.tsindex a2b45de87..6cee618fa 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.test.ts@@ -4,9 +4,10 @@ import type * as DeployedVersion from './deployed-version';import type { ServerHost } from './host/types';/**- * Covers the downgrade guard only (CHOO-1736). The rest of `startStack` is an- * orchestration of already-tested pieces; what matters here is that a stack- * ahead of this build is refused BEFORE anything on the host is touched.+ * Covers the two things `startStack` decides rather than merely sequences: the+ * downgrade guard (CHOO-1736) — a stack ahead of this build is refused BEFORE+ * anything on the host is touched — and the telemetry answer it carries onto+ * the stack (CHOO-2890). The rest is an orchestration of already-tested pieces.*/const readDeployedVersionMock = vi.hoisted(() => vi.fn());@@ -14,6 +15,8 @@ const composeUpMock = vi.hoisted(() => vi.fn(() => Promise.resolve()));const waitForHealthMock = vi.hoisted(() => vi.fn(() => Promise.resolve(true)));const logError = vi.hoisted(() => vi.fn());const logWarn = vi.hoisted(() => vi.fn());+const buildEnvFileMock = vi.hoisted(() => vi.fn((_params: unknown) => 'SWITCH_VERSION=0.11.0\n'));+const telemetryConsentMock = vi.hoisted(() => vi.fn(() => Promise.resolve(false)));// Pin the build's expected version so the guard's arithmetic is not coupled to// whatever the real pin happens to be.@@ -45,7 +48,15 @@ vi.mock('./ports', () => ({Promise.resolve({ gateway: 3300, api: 8000, mattermost: 8065, postgres: 5432 }),clearPorts: vi.fn(),}));-vi.mock('./env-file', () => ({ buildEnvFile: () => 'SWITCH_VERSION=0.11.0\n' }));+vi.mock('./env-file', () => ({+ buildEnvFile: buildEnvFileMock,+ readEnvValue: vi.fn(),+ TELEMETRY_ENABLED_KEY: 'TELEMETRY_ENABLED',+}));+vi.mock('./telemetry-consent', () => ({+ telemetryConsent: telemetryConsentMock,+ readDeployedTelemetry: vi.fn(),+}));vi.mock('@main/core/switch-servers/servers-store', () => ({ensureManagedServer: () => Promise.resolve({ id: 'srv-1' }),setActiveServerId: vi.fn(),@@ -84,6 +95,8 @@ function options() {beforeEach(() => {vi.clearAllMocks();+ telemetryConsentMock.mockResolvedValue(false);+ buildEnvFileMock.mockReturnValue('SWITCH_VERSION=0.11.0\n');});describe('startStack version guard', () => {@@ -116,7 +129,11 @@ describe('startStack version guard', () => {});const { opts, writeFile } = options();- expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ expect(await startStack(opts)).toEqual({+ kind: 'started',+ serverId: 'srv-1',+ telemetryEnabled: false,+ });expect(writeFile).toHaveBeenCalledWith(ENV_FILE_NAME, expect.any(String), 0o600);expect(composeUpMock).toHaveBeenCalledOnce();});@@ -124,7 +141,11 @@ describe('startStack version guard', () => {it('starts a fresh host with nothing deployed', async () => {readDeployedVersionMock.mockResolvedValue({ kind: 'absent' });const { opts } = options();- expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ expect(await startStack(opts)).toEqual({+ kind: 'started',+ serverId: 'srv-1',+ telemetryEnabled: false,+ });});it('starts a matching stack (the plain restart path)', async () => {@@ -134,14 +155,22 @@ describe('startStack version guard', () => {source: 'container',});const { opts } = options();- expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ expect(await startStack(opts)).toEqual({+ kind: 'started',+ serverId: 'srv-1',+ telemetryEnabled: false,+ });});it('proceeds with a warning when the deployed version cannot be read', async () => {readDeployedVersionMock.mockResolvedValue({ kind: 'unreadable', reason: 'daemon down' });const { opts } = options();- expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ expect(await startStack(opts)).toEqual({+ kind: 'started',+ serverId: 'srv-1',+ telemetryEnabled: false,+ });// Degraded, but disclosed — a transient probe failure must not make the app// unstartable.expect(logWarn).toHaveBeenCalledOnce();@@ -154,7 +183,11 @@ describe('startStack version guard', () => {source: 'container',});const { opts } = options();- expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ expect(await startStack(opts)).toEqual({+ kind: 'started',+ serverId: 'srv-1',+ telemetryEnabled: false,+ });});it('says so loudly when it cannot prove the start is not a downgrade', async () => {@@ -207,7 +240,11 @@ describe('startStack checkout build', () => {const { opts, writeFile } = options();opts.checkoutRoot = '/src/switch';- expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ expect(await startStack(opts)).toEqual({+ kind: 'started',+ serverId: 'srv-1',+ telemetryEnabled: false,+ });const override = writeFile.mock.calls.find(([name]) => name === 'standalone-docker-compose.build.yml'@@ -225,10 +262,55 @@ describe('startStack checkout build', () => {const { opts } = options();opts.checkoutRoot = '/src/switch';- expect(await startStack(opts)).toEqual({ kind: 'started', serverId: 'srv-1' });+ expect(await startStack(opts)).toEqual({+ kind: 'started',+ serverId: 'srv-1',+ telemetryEnabled: false,+ });expect(logWarn).toHaveBeenCalled();});+ // CHOO-2890. The toggle is only honoured end to end if a start carries the+ // answer as given — including "no", which must be written rather than left+ // out, and including a start that is really a restart.+ it('applies the current consent answer to the stack it starts', async () => {+ readDeployedVersionMock.mockResolvedValue({ kind: 'absent' });+ telemetryConsentMock.mockResolvedValue(true);+ const { opts } = options();++ expect(await startStack(opts)).toEqual({+ kind: 'started',+ serverId: 'srv-1',+ telemetryEnabled: true,+ });+ expect(buildEnvFileMock).toHaveBeenCalledWith(+ expect.objectContaining({ telemetryEnabled: true })+ );+ });++ it('applies a refusal just as explicitly', async () => {+ readDeployedVersionMock.mockResolvedValue({ kind: 'absent' });+ telemetryConsentMock.mockResolvedValue(false);+ const { opts } = options();++ await startStack(opts);++ expect(buildEnvFileMock).toHaveBeenCalledWith(+ expect.objectContaining({ telemetryEnabled: false })+ );+ });++ // A start that cannot read the answer must not invent one: writing a guess is+ // how a refusal gets quietly overridden.+ it('fails the start rather than guessing at the answer', async () => {+ readDeployedVersionMock.mockResolvedValue({ kind: 'absent' });+ telemetryConsentMock.mockRejectedValue(new Error('settings unreadable'));+ const { opts } = options();++ await expect(startStack(opts)).rejects.toThrow('settings unreadable');+ expect(composeUpMock).not.toHaveBeenCalled();+ });+it('leaves the released path unbuilt and without an override', async () => {readDeployedVersionMock.mockResolvedValue({ kind: 'absent' });const { opts, writeFile } = options();diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.tsindex 7540170ce..161e9d2f5 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/pipeline.ts@@ -26,6 +26,7 @@ import type { ServerHost } from './host/types';import { crossesMatrixBoundary, runBackfill } from './matrix-migration';import { clearPorts, resolvePorts } from './ports';import { clearSecrets, loadOrCreateSecrets } from './secrets';+import { telemetryConsent } from './telemetry-consent';/*** The transport-agnostic lifecycle for a Switch Console-managed Switch stack, run@@ -208,6 +209,9 @@ export async function startStack(opts: StartStackOptions): Promise<StartLocalSerconst ports = await resolvePorts(host);const gatewayUrl = gatewayUrlFor(ports);const apiUrl = apiUrlFor(ports);+ // Read here rather than taken from the caller: a start is the moment the+ // user's answer reaches the server, and no supervisor can forget to carry it.+ const telemetryEnabled = await telemetryConsent();await host.writeFile(ENV_FILE_NAME,buildEnvFile({@@ -217,6 +221,7 @@ export async function startStack(opts: StartStackOptions): Promise<StartLocalSerports,secrets,sessionDemo: checkoutRoot !== null,+ telemetryEnabled,}),0o600);@@ -255,7 +260,7 @@ export async function startStack(opts: StartStackOptions): Promise<StartLocalSer}await resolveAgentServers();- return { kind: 'started', serverId: server.id };+ return { kind: 'started', serverId: server.id, telemetryEnabled };}/** Stop the stack's containers and tear down networking (leaves data + config). */diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.tsindex 9cf414fe8..b8b044026 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.ts+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/remote-server-service.ts@@ -29,6 +29,7 @@ import { readVersionStatus } from './deployed-version';import { createRemoteServerHost, type RemoteServerHost } from './host/remote-host';import { resetStack, startStack, stopStack } from './pipeline';import { readPersistedPorts } from './ports';+import { readDeployedTelemetry } from './telemetry-consent';function initialStatus(sshHost: string): RemoteServerStatus {return {@@ -41,6 +42,7 @@ function initialStatus(sshHost: string): RemoteServerStatus {// A remote host builds nothing: its stack always runs the pinned released// images, so the dev checkout option is not on offer there.checkoutBuild: null,+ deployedTelemetry: null,message: null,error: null,};@@ -137,6 +139,9 @@ class RemoteServerService {this.hosts.set(sshHost, host);adopted = true;this.setStatus(sshHost, { phase: 'running', serverId });+ // Only for a running stack: a stopped one sends nothing, so it+ // cannot be out of step with the user's answer.+ this.setStatus(sshHost, { deployedTelemetry: await readDeployedTelemetry(host) });}// Running but we don't know its ports — leave it stopped; the user can// restart to re-derive them rather than forward to the wrong ports.@@ -213,6 +218,7 @@ class RemoteServerService {error: null,deployedVersion: COMPATIBLE_SWITCH_VERSION,drift: null,+ deployedTelemetry: { known: true, enabled: result.telemetryEnabled },});}reportManagedServerStart('remote', result);@@ -244,7 +250,12 @@ class RemoteServerService {host = this.hosts.get(sshHost) ?? (await createRemoteServerHost(sshHost));this.setStatus(sshHost, { phase: 'stopping', message: 'Stopping containers…' });await stopStack(host);- this.setStatus(sshHost, { phase: 'stopped', message: null, error: null });+ this.setStatus(sshHost, {+ phase: 'stopped',+ message: null,+ error: null,+ deployedTelemetry: null,+ });reportManagedServerOutcome('stop', 'remote', 'success');} catch (error) {this.setStatus(sshHost, {@@ -279,7 +290,12 @@ class RemoteServerService {if (server) await deleteAgentsForServer(server.id);this.setStatus(sshHost, { phase: 'stopping', message: 'Destroying containers and data…' });await resetStack(host);- this.setStatus(sshHost, { phase: 'stopped', message: null, error: null });+ this.setStatus(sshHost, {+ phase: 'stopped',+ message: null,+ error: null,+ deployedTelemetry: null,+ });reportManagedServerOutcome('reset', 'remote', 'success');} catch (error) {this.setStatus(sshHost, {diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.ymlindex 33d05fda0..5af90083f 100644--- a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/resources/standalone-docker-compose.pinned.yml@@ -248,6 +248,14 @@ services:OTLP_HEADERS:OTLP_EXPORT_INTERVAL_SECONDS:OTLP_TIMEOUT_SECONDS:+ # Product usage telemetry, forwarded for the same reason and in the same+ # bare-key form. Switch Console writes TELEMETRY_ENABLED into the `.env`+ # from the user's "Share usage data" choice, so one consent decision+ # governs the app and the server it runs for them (CHOO-2890). On a stack+ # brought up by hand, an operator sets it here the same way.+ TELEMETRY_ENABLED:+ TELEMETRY_ENDPOINT:+ TELEMETRY_SNAPSHOT_INTERVAL_HOURS:depends_on:postgres:condition: service_healthydiff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/telemetry-consent.test.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/telemetry-consent.test.tsnew file mode 100644index 000000000..91de2e5d9--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/telemetry-consent.test.ts@@ -0,0 +1,101 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import type { ServerHost } from './host/types';++/**+ * Reading back what a managed stack is actually doing about usage data+ * (CHOO-2890).+ *+ * The point of reading it at all is that the Console's own record of what it+ * last wrote can be wrong — a start that wrote the `.env` and then failed+ * leaves the two disagreeing. So the container wins over the file, and a host+ * that answers neither says so instead of falling back on either.+ */++const runningServiceEnvMock = vi.hoisted(() => vi.fn());++vi.mock('./compose', () => ({ runningServiceEnv: runningServiceEnvMock }));+vi.mock('@main/core/settings/settings-service', () => ({+ appSettingsService: { get: vi.fn() },+}));++const { readDeployedTelemetry } = await import('./telemetry-consent');++function host(readFile: () => Promise<string | null>): ServerHost {+ return { label: 'this computer', readFile } as unknown as ServerHost;+}++const noEnvFile = () => Promise.resolve(null);++beforeEach(() => {+ vi.clearAllMocks();+});++describe('readDeployedTelemetry', () => {+ it('reads the running container, which is what is actually sending', async () => {+ runningServiceEnvMock.mockResolvedValue(new Map([['TELEMETRY_ENABLED', 'true']]));++ expect(await readDeployedTelemetry(host(noEnvFile))).toEqual({ known: true, enabled: true });+ });++ it('prefers the container over a .env that disagrees with it', async () => {+ // Exactly the state a start that wrote the file and then failed leaves+ // behind. Trusting the file here would report a choice as applied that the+ // running server has never seen.+ runningServiceEnvMock.mockResolvedValue(new Map([['TELEMETRY_ENABLED', 'true']]));++ const result = await readDeployedTelemetry(+ host(() => Promise.resolve('TELEMETRY_ENABLED=false\n'))+ );++ expect(result).toEqual({ known: true, enabled: true });+ });++ it('treats a container without the variable as not sharing', async () => {+ // switch-core's own default is off, so a stack started before this existed+ // is genuinely not reporting — this is a reading, not a fallback.+ runningServiceEnvMock.mockResolvedValue(new Map([['SWITCH_VERSION', '0.11.0']]));++ expect(await readDeployedTelemetry(host(noEnvFile))).toEqual({ known: true, enabled: false });+ });++ it.each(['1', 'TRUE', ' yes ', 'on'])('reads %s as sharing', async (value) => {+ runningServiceEnvMock.mockResolvedValue(new Map([['TELEMETRY_ENABLED', value]]));++ expect(await readDeployedTelemetry(host(noEnvFile))).toEqual({ known: true, enabled: true });+ });++ it('falls back to the .env when no container is up', async () => {+ runningServiceEnvMock.mockResolvedValue(null);++ const result = await readDeployedTelemetry(+ host(() => Promise.resolve('SWITCH_VERSION=0.11.0\nTELEMETRY_ENABLED=true\n'))+ );++ expect(result).toEqual({ known: true, enabled: true });+ });++ it('reports a host it could not read, naming both failures', async () => {+ runningServiceEnvMock.mockRejectedValue(new Error('docker daemon down'));++ const result = await readDeployedTelemetry(+ host(() => Promise.reject(new Error('ssh timed out')))+ );++ expect(result.known).toBe(false);+ expect(result).toMatchObject({+ reason: expect.stringContaining('docker daemon down') as unknown as string,+ });+ expect(result).toMatchObject({+ reason: expect.stringContaining('ssh timed out') as unknown as string,+ });+ });++ it('does not let an unreadable host read as agreement', async () => {+ runningServiceEnvMock.mockRejectedValue(new Error('docker daemon down'));++ expect(await readDeployedTelemetry(host(noEnvFile))).toEqual({+ known: false,+ reason: expect.stringContaining('docker daemon down') as unknown as string,+ });+ });+});diff --git a/console/apps/switch-console-desktop/src/main/core/managed-switch-server/telemetry-consent.ts b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/telemetry-consent.tsnew file mode 100644index 000000000..bb256a445--- /dev/null+++ b/console/apps/switch-console-desktop/src/main/core/managed-switch-server/telemetry-consent.ts@@ -0,0 +1,78 @@+import { appSettingsService } from '@main/core/settings/settings-service';+import type { DeployedTelemetry } from '@shared/core/managed-switch-server/managed-switch-server';+import { runningServiceEnv } from './compose';+import { ENV_FILE_NAME } from './constants';+import { readEnvValue, TELEMETRY_ENABLED_KEY } from './env-file';+import type { ServerHost } from './host/types';++/**+ * The "Share usage data" answer, as the managed server needs it (CHOO-2890).+ *+ * One consent decision covers the Console and the server it runs, so there is+ * no separate server-side preference to merge with — this is the toggle, read+ * fresh. It is deliberately not cached anywhere: a start is the moment the+ * answer is applied, and a copy taken earlier could apply an answer the user+ * has since withdrawn.+ *+ * Reading it is allowed to fail the start it is part of. A server started+ * without knowing the answer would be a server reporting on a guess, and the+ * one guess that cannot be defended is the one in favour.+ */+export async function telemetryConsent(): Promise<boolean> {+ return (await appSettingsService.get('telemetry')).enabled;+}++/** The compose service whose environment carries the server's telemetry gate. */+const CORE_SERVICE = 'switch';++/**+ * How pydantic-settings reads a boolean, narrowed to the forms that can reach+ * this variable.+ *+ * Absent means off, and that is a reading rather than a fallback: switch-core's+ * own default for the gate is off, so a stack started before this existed — or+ * by an operator who never set it — is genuinely not reporting.+ */+function envFlag(value: string | null | undefined): boolean {+ if (value === null || value === undefined) return false;+ return ['1', 'true', 'yes', 'on'].includes(value.trim().toLowerCase());+}++/**+ * Whether the stack on `host` is actually sharing usage data.+ *+ * Prefers the running core container's own environment — the only thing that+ * says what the server is doing right now — and falls back to the `.env`, which+ * is what the last start asked for. The two differ exactly when a start wrote+ * the file and then failed, which is the case this must not paper over.+ *+ * Call it only for a stack that is up. A stopped stack sends nothing, so its+ * answer is not a consent question.+ */+export async function readDeployedTelemetry(host: ServerHost): Promise<DeployedTelemetry> {+ const failures: string[] = [];++ try {+ const env = await runningServiceEnv(host, CORE_SERVICE);+ if (env) return { known: true, enabled: envFlag(env.get(TELEMETRY_ENABLED_KEY)) };+ failures.push(`the ${CORE_SERVICE} service has no running container`);+ } catch (error) {+ failures.push(`container environment: ${errorText(error)}`);+ }++ try {+ const env = await host.readFile(ENV_FILE_NAME);+ if (env !== null) {+ return { known: true, enabled: envFlag(readEnvValue(env, TELEMETRY_ENABLED_KEY)) };+ }+ failures.push(`${ENV_FILE_NAME}: not on the host`);+ } catch (error) {+ failures.push(`${ENV_FILE_NAME}: ${errorText(error)}`);+ }++ return { known: false, reason: failures.join('; ') };+}++function errorText(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}diff --git a/console/apps/switch-console-desktop/src/main/core/switch-setup/controller.test.ts b/console/apps/switch-console-desktop/src/main/core/switch-setup/controller.test.tsindex 6e5680376..023ca26f9 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-setup/controller.test.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-setup/controller.test.ts@@ -22,13 +22,24 @@ it('offers installed remote ACP providers without requiring connector plugins',status: id === 'cursor' ? 'available' : 'missing',}));const statuses = await switchSetupController.listAgentTypeAvailabilityRemote('example-host');- expect(statuses).toContainEqual({ agentId: 'cursor', available: true, blockedReason: null });+ expect(statuses).toContainEqual({+ agentId: 'cursor',+ available: true,+ blockedReason: null,+ blockedKind: null,+ });expect(statuses).toContainEqual({agentId: 'antigravity',available: false,blockedReason: 'Install Antigravity ACP on example-host.',+ blockedKind: 'not-installed',+ });+ expect(statuses).toContainEqual({+ agentId: 'claude',+ available: true,+ blockedReason: null,+ blockedKind: null,});- expect(statuses).toContainEqual({ agentId: 'claude', available: true, blockedReason: null });});it('does not call a failed remote probe an installed CLI', async () => {mocks.probe.mockResolvedValue({ status: 'error' });@@ -36,5 +47,8 @@ it('does not call a failed remote probe an installed CLI', async () => {expect(statuses.find((status) => status.agentId === 'cursor')).toMatchObject({available: false,blockedReason: 'Could not verify this CLI on example-host. Recheck the host setup.',+ // Not 'not-installed': the host never answered, so nothing here says the+ // CLI is missing, and the tile must not send anyone off to install it.+ blockedKind: 'unknown',});});diff --git a/console/apps/switch-console-desktop/src/main/core/switch-setup/controller.ts b/console/apps/switch-console-desktop/src/main/core/switch-setup/controller.tsindex 4fb07d4ed..1d179f3ba 100644--- a/console/apps/switch-console-desktop/src/main/core/switch-setup/controller.ts+++ b/console/apps/switch-console-desktop/src/main/core/switch-setup/controller.ts@@ -42,6 +42,12 @@ export const switchSetupController = createRPCController({: cli.status === 'missing'? `Install ${agentId === 'cursor' ? 'Cursor CLI' : 'Antigravity ACP'} on ${sshHost}.`: `Could not verify this CLI on ${sshHost}. Recheck the host setup.`,+ blockedKind:+ cli.status === 'available'+ ? null+ : cli.status === 'missing'+ ? 'not-installed'+ : 'unknown',};}));@@ -55,14 +61,21 @@ export const switchSetupController = createRPCController({agentId: status.agentId,available: false,blockedReason: `Switch Console cannot manage this agent type on ${sshHost}.`,+ blockedKind: 'unsupported' as const,};}return status.installed- ? { agentId: status.agentId, available: true, blockedReason: null }+ ? {+ agentId: status.agentId,+ available: true,+ blockedReason: null,+ blockedKind: null,+ }: {agentId: status.agentId,available: false,blockedReason: `Its Switch connector is not installed on ${sshHost}.`,+ blockedKind: 'not-installed' as const,};}),];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 a6a275ee0..ef80125ee 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@@ -281,6 +281,7 @@ describe('switchSetupService.listAgentTypeAvailability', () => {blockedReason: installed? null: 'Install Antigravity ACP on this computer to use SDK sessions.',+ blockedKind: installed ? null : 'not-installed',},]);}@@ -300,6 +301,7 @@ describe('switchSetupService.listAgentTypeAvailability', () => {blockedReason: installed? null: 'Install Cursor CLI on this computer to use ACP sessions.',+ blockedKind: installed ? null : 'not-installed',},]);}@@ -311,7 +313,7 @@ describe('switchSetupService.listAgentTypeAvailability', () => {mocks.readFile.mockImplementation(readFileImpl('0.1.0', '0.1.0'));expect(await switchSetupService.listAgentTypeAvailability()).toEqual([- { agentId: 'claude', available: true, blockedReason: null },+ { agentId: 'claude', available: true, blockedReason: null, blockedKind: null },]);});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 1220cd359..16b88b8ad 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@@ -319,6 +319,8 @@ class SwitchSetupService {process.platform === 'win32'? 'SDK sessions require a POSIX SSH execution host.': 'This provider has no SDK session adapter.',+ // Neither is an install away — there is nothing to install.+ blockedKind: 'unsupported',});continue;}@@ -334,17 +336,19 @@ class SwitchSetupService {: cursor? 'Install Cursor CLI on this computer to use ACP sessions.': 'Install Antigravity ACP on this computer to use SDK sessions.',+ blockedKind: installed ? null : 'not-installed',});continue;}const status = await this.getStatus(agentId);availability.push(status.installed- ? { agentId, available: true, blockedReason: null }+ ? { agentId, available: true, blockedReason: null, blockedKind: null }: {agentId,available: false,blockedReason: 'Its Switch connector is not installed on this computer.',+ blockedKind: 'not-installed',});}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsxindex 6ef11e677..48c42e2cb 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/add-agent-modal.tsx@@ -564,11 +564,16 @@ export const AddAgentModal = observer(function AddAgentModal({/>)}+ {/* No `dir`: signing in is a property of the machine, not of the folder+ an agent will run in — which is what the provider tiles above+ already assume. Keying it on `dir` made this a second, separate+ check of the same thing, re-run on every change to the working+ directory. */}{canChooseAgentType && pickState.providerId && (<ProviderConnectionStatusproviderId={pickState.providerId}sshHost={isRemoteRun ? runHost : null}- dir={dir}+ dir=""/>)}diff --git a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsxindex cd4655fa1..f23d70bd0 100644--- a/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/locations/components/add-agent-modal/agent-type-picker.tsx@@ -10,8 +10,21 @@ import { Field, FieldLabel } from '@renderer/lib/ui/field';import { Spinner } from '@renderer/lib/ui/spinner';import { cn } from '@renderer/utils/utils';import type { AgentProviderId } from '@shared/core/providers/agent-provider-registry';+import type { AgentTypeBlockedKind } from '@shared/core/switch-setup/agent-type-availability';import { autoSelectedAgentType } from './agent-type-auto-selection';+/**+ * The tile is three words wide, so it gets the verdict and the full sentence+ * goes to the tooltip. "Not installed" is only said where something really is+ * missing — a provider with no adapter, or a host that could not be reached,+ * would be sent off to install something that would not help.+ */+const BLOCKED_LABEL: Record<AgentTypeBlockedKind, string> = {+ 'not-installed': 'Not installed',+ unsupported: 'Not supported here',+ unknown: "Couldn't check",+};+/*** Picks the agent type for a new Switch agent. Only agent types that are both* Switch-supported and have their connector plugin installed (i.e. actually@@ -124,7 +137,7 @@ export function AgentTypePicker({user has locally can legitimately be absent on the host they picked.*/}<div className="grid grid-cols-3 gap-2">- {options.map(({ agent, available, blockedReason }) => (+ {options.map(({ agent, available, blockedReason, blockedKind }) => (<buttonkey={agent.id}type="button"@@ -137,7 +150,9 @@ export function AgentTypePicker({value === agent.id? 'border-foreground bg-[var(--sel-soft)]': 'border-border hover:bg-[var(--sel-soft)]',- !available && 'cursor-not-allowed bg-background-1 hover:bg-transparent'+ // Dimmed as a whole, icon and name included. Disabling the click+ // without dimming left it looking exactly like a tile that works.+ !available && 'cursor-not-allowed opacity-50 bg-background-1 hover:bg-transparent')}><AgentIcon id={agent.id} size={22} />@@ -150,8 +165,10 @@ export function AgentTypePicker({compact/>) : (- <span className="text-xs text-foreground-warning">- {blockedReason ?? 'Setup required'}+ // Muted, not amber: a tile that is already greyed out does not+ // also need to raise a warning, and the sentence is on hover.+ <span className="text-xs text-foreground-muted">+ {blockedKind ? BLOCKED_LABEL[blockedKind] : 'Not available'}</span>)}</button>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 583175486..8594cf107 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@@ -3,6 +3,7 @@ import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-import {TELEMETRY_DETAILS_LABEL,TELEMETRY_DETAILS_URL,+ TELEMETRY_SCOPE_NOTE,TELEMETRY_SUMMARY,} from '@renderer/features/telemetry/telemetry-copy';import { openExternalUrl } from '@renderer/lib/open-external';@@ -34,6 +35,7 @@ const TelemetrySettingsCard: React.FC = () => {description={<><p>{TELEMETRY_SUMMARY}</p>+ <p className="mt-1">{TELEMETRY_SCOPE_NOTE}</p><buttontype="button"className="mt-1 cursor-pointer text-foreground-muted underline-offset-2 transition-colors hover:text-foreground hover:underline"diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/TelemetryConsentNotice.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/TelemetryConsentNotice.tsxnew file mode 100644index 000000000..696e18bb4--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/TelemetryConsentNotice.tsx@@ -0,0 +1,58 @@+import { RefreshCw, TriangleAlert } from 'lucide-react';+import { Alert, AlertAction, AlertDescription, AlertTitle } from '@renderer/lib/ui/alert';+import { Button } from '@renderer/lib/ui/button';+import type { ManagedTelemetryNotice } from './managed-telemetry-notice';++/**+ * Surfaces a managed server still acting on an older answer to "Share usage+ * data" than the one the user has given (CHOO-2890).+ *+ * The server reads that answer when it starts, and nothing restarts it on the+ * user's behalf: a restart drops live agent sessions, which is not a price to+ * charge for a settings toggle without asking. So the gap is shown and the+ * restart offered, rather than either taken silently or left unsaid — an+ * opt-out that quietly does not reach the server is exactly the failure this+ * exists to prevent.+ */+export function TelemetryConsentNotice({+ notice,+ disabled,+ onRestart,+}: {+ notice: ManagedTelemetryNotice;+ /** True while a lifecycle operation is in flight (or the host is unreachable). */+ disabled: boolean;+ onRestart: () => void;+}) {+ if (notice.kind === 'in-step') return null;++ const { title, body } =+ notice.kind === 'unknown'+ ? {+ title: "Can't tell whether this server shares usage data",+ body: `Reading the setting off the server failed (${notice.reason}). Restarting applies your current choice, and makes it certain.`,+ }+ : notice.consent+ ? {+ title: 'This server is not sharing usage data yet',+ body: 'Your choice to share covers the servers Switch Console runs for you, but this one has been up since before you made it. Restart to apply it.',+ }+ : {+ title: 'This server is still sharing usage data',+ body: 'You turned sharing off. This server has been up since before that and keeps the setting it started with until it restarts. Restart to apply your choice.',+ };++ return (+ <Alert variant="warning">+ <TriangleAlert className="size-4" />+ <AlertTitle>{title}</AlertTitle>+ <AlertDescription>{body}</AlertDescription>+ <AlertAction>+ <Button size="sm" disabled={disabled} onClick={onRestart}>+ <RefreshCw className="size-4" />+ Restart to apply+ </Button>+ </AlertAction>+ </Alert>+ );+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.tsindex 53d622467..1bfc55600 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/local-server-store.ts@@ -4,6 +4,7 @@ import { describeFailure } from '@renderer/lib/errors/describe-failure';import { events, rpc } from '@renderer/lib/ipc';import type {CheckoutBuild,+ DeployedTelemetry,DockerAvailability,LocalServerStatus,SwitchVersionDrift,@@ -82,6 +83,12 @@ export class LocalServerStore {return this.status?.drift ?? null;}+ /** What the running stack is doing about usage data, or null when nothing is+ * up to be doing anything. */+ get deployedTelemetry(): DeployedTelemetry | null {+ return this.status?.deployedTelemetry ?? null;+ }+/** Dev builds launched from a Switch checkout only: the checkout the stack's* images can be built from, and whether that is on. Null everywhere else, and* the controls hide the option when it is. */diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-telemetry-notice.test.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-telemetry-notice.test.tsnew file mode 100644index 000000000..c404a9a74--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-telemetry-notice.test.ts@@ -0,0 +1,64 @@+import { describe, expect, it } from 'vitest';+import { managedTelemetryNotice } from './managed-telemetry-notice';++describe('managedTelemetryNotice', () => {+ it('says nothing while the stack is down', () => {+ expect(+ managedTelemetryNotice({+ running: false,+ deployed: { known: true, enabled: true },+ consent: false,+ })+ ).toEqual({ kind: 'in-step' });+ });++ it('says nothing when nothing has been observed', () => {+ expect(managedTelemetryNotice({ running: true, deployed: null, consent: true })).toEqual({+ kind: 'in-step',+ });+ });++ it('says nothing when the server agrees with the user', () => {+ for (const consent of [true, false]) {+ expect(+ managedTelemetryNotice({+ running: true,+ deployed: { known: true, enabled: consent },+ consent,+ })+ ).toEqual({ kind: 'in-step' });+ }+ });++ it('reports a server that has not picked up an opt-in', () => {+ expect(+ managedTelemetryNotice({+ running: true,+ deployed: { known: true, enabled: false },+ consent: true,+ })+ ).toEqual({ kind: 'stale', consent: true });+ });++ // The direction that matters most: a server still reporting after the user+ // said no must not be reported as merely "out of date".+ it('reports a server still sharing after the user opted out', () => {+ expect(+ managedTelemetryNotice({+ running: true,+ deployed: { known: true, enabled: true },+ consent: false,+ })+ ).toEqual({ kind: 'stale', consent: false });+ });++ it('reports an unreadable server as unknown rather than as agreeing', () => {+ expect(+ managedTelemetryNotice({+ running: true,+ deployed: { known: false, reason: 'ssh timed out' },+ consent: true,+ })+ ).toEqual({ kind: 'unknown', reason: 'ssh timed out' });+ });+});diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-telemetry-notice.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-telemetry-notice.tsnew file mode 100644index 000000000..c6ec067c3--- /dev/null+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/managed-telemetry-notice.ts@@ -0,0 +1,37 @@+import type { DeployedTelemetry } from '@shared/core/managed-switch-server/managed-switch-server';++/**+ * What a managed server's page has to say about usage data (CHOO-2890).+ *+ * "Share usage data" is one decision covering Switch Console and the server it+ * runs, but the server only reads it when it starts. So the answer the user+ * gave and the answer the server is acting on can differ, and this is where+ * that gap is turned into something to show.+ *+ * The three outcomes are deliberately distinct. A server in step says nothing.+ * A server out of step says which way, because "not sharing yet" and "still+ * sharing after you said no" are not the same news. And a server we could not+ * read says so rather than borrowing either answer — the whole point of+ * checking is that assuming was what went wrong.+ */+export type ManagedTelemetryNotice =+ | { kind: 'in-step' }+ | { kind: 'unknown'; reason: string }+ | { kind: 'stale'; consent: boolean };++export function managedTelemetryNotice(args: {+ /** Whether the managed stack is up. A stopped server transmits nothing, so it+ * cannot be violating a choice and has nothing to apply until it starts —+ * which the start itself does. */+ running: boolean;+ /** What the running stack was observed to be doing, or null when nothing has+ * been observed. */+ deployed: DeployedTelemetry | null;+ /** The user's current answer. */+ consent: boolean;+}): ManagedTelemetryNotice {+ const { running, deployed, consent } = args;+ if (!running || deployed === null) return { kind: 'in-step' };+ if (!deployed.known) return { kind: 'unknown', reason: deployed.reason };+ return deployed.enabled === consent ? { kind: 'in-step' } : { kind: 'stale', consent };+}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/remote-server-store.ts b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/remote-server-store.tsindex db0c4608a..39d52c0d3 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/remote-server-store.ts+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/remote-server-store.ts@@ -4,6 +4,7 @@ import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reacimport { describeFailure } from '@renderer/lib/errors/describe-failure';import { events, rpc } from '@renderer/lib/ipc';import type {+ DeployedTelemetry,DockerAvailability,SwitchVersionDrift,} from '@shared/core/managed-switch-server/managed-switch-server';@@ -31,6 +32,7 @@ function defaultStatus(sshHost: string): RemoteServerStatus {// A remote stack always runs the pinned released images — the dev checkout// build is a local-only option.checkoutBuild: null,+ deployedTelemetry: null,message: null,error: null,};@@ -127,6 +129,12 @@ export class RemoteServerStore {return this.statusFor(sshHost).drift;}+ /** What the host's running stack is doing about usage data, or null when+ * nothing is up there to be doing anything. */+ deployedTelemetryFor(sshHost: string): DeployedTelemetry | null {+ return this.statusFor(sshHost).deployedTelemetry;+ }+logsFor(sshHost: string): string[] {return this.logsByHost.get(sshHost) ?? [];}diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-presentation.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-presentation.tsxindex eaac3c619..5964cb3fb 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-presentation.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/server-presentation.tsx@@ -3,7 +3,10 @@ import { observer } from 'mobx-react-lite';import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';import { Tooltip, TooltipContent, TooltipTrigger } from '@renderer/lib/ui/tooltip';import { cn } from '@renderer/utils/utils';-import type { SwitchVersionDrift } from '@shared/core/managed-switch-server/managed-switch-server';+import type {+ DeployedTelemetry,+ SwitchVersionDrift,+} from '@shared/core/managed-switch-server/managed-switch-server';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import { localServerStore } from './local-server-store';import { remoteServerStore } from './remote-server-store';@@ -90,6 +93,19 @@ export function serverDrift(server: SwitchServer): SwitchVersionDrift | null {return localServerStore.drift;}+/**+ * What a managed server's running stack is doing about usage data. Null for a+ * server this app does not run: its operator decides, and the Console's toggle+ * neither reaches it nor claims to.+ */+export function serverDeployedTelemetry(server: SwitchServer): DeployedTelemetry | null {+ if (!server.managed) return null;+ if (server.managementKind === 'remote' && server.sshHost) {+ return remoteServerStore.deployedTelemetryFor(server.sshHost);+ }+ return localServerStore.deployedTelemetry;+}+const AVATAR_SIZE = {sm: 'size-6 text-xs',md: 'size-[26px] text-xs',diff --git a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsxindex 50a6f5a4f..6752580c4 100644--- a/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx+++ b/console/apps/switch-console-desktop/src/renderer/features/switch-servers/view.tsx@@ -15,6 +15,7 @@ import { type GuardResult, type ViewDefinition } from '@renderer/app/view-registimport { agentsStore } from '@renderer/features/locations/stores/agents-store';import { hostReachabilityStore } from '@renderer/features/remote-hosts/host-reachability-store';import { HostUnreachablePanel } from '@renderer/features/remote-hosts/host-unreachable-panel';+import { useAppSettingsKey } from '@renderer/features/settings/use-app-settings-key';import { rpc } from '@renderer/lib/ipc';import { useNavigate, useParams } from '@renderer/lib/layout/navigation-provider';import { useShowModal } from '@renderer/lib/modal/modal-provider';@@ -32,17 +33,24 @@ import { Spinner } from '@renderer/lib/ui/spinner';import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';import { localServerStore } from './local-server-store';import { LocalServerControls } from './LocalServerControls';+import { managedTelemetryNotice } from './managed-telemetry-notice';import { MessagingAppsCard } from './MessagingAppsCard';import { remoteServerStore } from './remote-server-store';import { RemoteServerControls } from './RemoteServerControls';import { serverIcon } from './server-icon';-import { ServerAvatar, serverDrift, serverPlacementLabel } from './server-presentation';+import {+ ServerAvatar,+ serverDeployedTelemetry,+ serverDrift,+ serverPlacementLabel,+} from './server-presentation';import { ServerResetSection } from './server-reset-section';import { ServerSectionTitlebar } from './server-section-titlebar';import { ServerSignInFields, useServerSignIn } from './server-sign-in';import { ServerStatTiles } from './server-stat-tiles';import { switchRoomsStore } from './switch-rooms-store';import { switchServersStore } from './switch-servers-store';+import { TelemetryConsentNotice } from './TelemetryConsentNotice';import { myIdentitiesQueryKey } from './use-my-identities';import { VersionDriftNotice } from './VersionDriftNotice';@@ -90,6 +98,10 @@ const ServerMainPanel = observer(function ServerMainPanel() {const queryClient = useQueryClient();const [refreshingPage, setRefreshingPage] = useState(false);+ // The same answer the Console checks before its own events. Read here rather+ // than pushed with the stack's status so that flipping the toggle in Settings+ // updates this page at once, without waiting for the server to be re-probed.+ const { value: telemetry } = useAppSettingsKey('telemetry');/*** Everything the page is showing, re-read.@@ -277,6 +289,19 @@ const ServerMainPanel = observer(function ServerMainPanel() {onRestart={() => restartStack(server)}/>+ {/* Same placement, and for the same reason: a consent decision that has+ not reached this server is about the server, not about one card on+ its page. */}+ <TelemetryConsentNotice+ notice={managedTelemetryNotice({+ running: server.managed && isManagedRunning(server),+ deployed: serverDeployedTelemetry(server),+ consent: telemetry?.enabled ?? true,+ })}+ disabled={stackTransitioning}+ onRestart={() => restartStack(server)}+ />+{detailsVisible && unreachable && <ServerUnreachableCard serverId={serverId} />}{detailsVisible && !unreachable && (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 40542454b..70e31c8ae 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@@ -9,6 +9,7 @@ import { Switch } from '@renderer/lib/ui/switch';import {TELEMETRY_DETAILS_LABEL,TELEMETRY_DETAILS_URL,+ TELEMETRY_SCOPE_NOTE,TELEMETRY_SUMMARY,} from './telemetry-copy';@@ -69,6 +70,7 @@ export function TelemetryConsentDialog({ onAnswered }: { onAnswered: () => voidHelp improve Switch Console</h2><p className="text-sm text-foreground-muted">{TELEMETRY_SUMMARY}</p>+ <p className="text-sm text-foreground-muted">{TELEMETRY_SCOPE_NOTE}</p></div><DialogContentArea className="gap-4"><div className="flex items-center justify-between gap-4 rounded-lg border border-border bg-background-1 p-3">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 e6f314d5c..b92d2b6e2 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@@ -15,6 +15,18 @@export const TELEMETRY_SUMMARY ='Switch Console shares anonymous usage data to show which features get used and where the app runs into trouble.';+/**+ * How far the answer reaches, stated because the alternative is a toggle that+ * appears to govern more than it does (CHOO-2890).+ *+ * It governs a Switch server this app runs — the setting is written into that+ * server's configuration at every start — and it does not govern a server+ * reached by URL, which is somebody else's deployment with its own answer. Both+ * halves matter: the first is the promise, the second is the limit of it.+ */+export const TELEMETRY_SCOPE_NOTE =+ 'The same answer applies to a Switch server this app runs for you. A server you connect to by URL is not covered — whoever operates it decides.';+export const TELEMETRY_DETAILS_LABEL = 'Read what is collected';export const TELEMETRY_DETAILS_URL =diff --git a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsxindex 0fcd55b83..45fb91b3b 100644--- a/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx+++ b/console/apps/switch-console-desktop/src/renderer/lib/components/provider-connection-status.tsx@@ -26,7 +26,11 @@ export function ProviderConnectionStatus({const query = useQuery({queryKey: ['provider-readiness', providerId, sshHost, dir],queryFn: () => rpc.agents.providerReadiness({ providerId, sshHost, dir }),- staleTime: 30_000,+ // Signing in is not something that changes minute to minute, and this+ // component is rendered once per provider tile and once per agent row —+ // so a short window turned opening a page into a burst of probes, each of+ // which starts a provider process on the execution machine.+ staleTime: 5 * 60_000,retry: false,});const copy = useMutation({diff --git a/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/managed-switch-server.ts b/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/managed-switch-server.tsindex 58220f483..4099d8949 100644--- a/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/managed-switch-server.ts+++ b/console/apps/switch-console-desktop/src/shared/core/managed-switch-server/managed-switch-server.ts@@ -110,6 +110,20 @@ export type CheckoutBuild = {enabled: boolean;};+/**+ * Whether the running managed stack is sharing usage data — read off the host,+ * not assumed from what the Console last wrote (CHOO-2890).+ *+ * The Console's "Share usage data" toggle governs the server it manages as well+ * as itself, but the server reads that choice once, when it starts. So a+ * running stack can be out of step with the current answer, and the only+ * honest way to know is to look. `known: false` carries what stopped us: an+ * unread host must not render as one that agrees.+ */+export type DeployedTelemetry =+ | { known: true; enabled: boolean }+ | { known: false; reason: string };+/** Snapshot of the managed local server, emitted on every transition. */export type LocalServerStatus = {phase: LocalServerPhase;@@ -127,6 +141,10 @@ export type LocalServerStatus = {* Null in a released build, and in a dev build that is not running from a* checkout — there is nothing to offer then. */checkoutBuild: CheckoutBuild | null;+ /** What the running stack is doing about usage data, or null when no stack is+ * up — a stopped server reports nothing, so there is nothing to be out of+ * step with. */+ deployedTelemetry: DeployedTelemetry | null;/** Human-readable current step (e.g. "Pulling images…"), or null. */message: string | null;/** Populated only when `phase === 'error'`. */@@ -168,7 +186,14 @@ export function managedServerStoppedReason(serverName: string, phase: LocalServe* starting Docker, or explain why an older build refuses to take over a stack* that has already migrated forward. */export type StartLocalServerResult =- | { kind: 'started'; serverId: string }+ | {+ kind: 'started';+ serverId: string;+ /** The consent this start applied to the stack, so the supervisor can+ * record what the server is now doing without probing for what it just+ * wrote. */+ telemetryEnabled: boolean;+ }| { kind: 'docker-unavailable'; reason: 'not-installed' | 'daemon-down'; detail: string }| { kind: 'version-downgrade'; deployed: string; expected: string }// The upgrade would have removed the message server before this stack'sdiff --git a/console/apps/switch-console-desktop/src/shared/core/switch-setup/agent-type-availability.ts b/console/apps/switch-console-desktop/src/shared/core/switch-setup/agent-type-availability.tsindex c7d01070f..fd2b77483 100644--- a/console/apps/switch-console-desktop/src/shared/core/switch-setup/agent-type-availability.ts+++ b/console/apps/switch-console-desktop/src/shared/core/switch-setup/agent-type-availability.ts@@ -11,6 +11,22 @@* whole roster, grey out what cannot be chosen, and say what would make it* choosable.*/+/**+ * What kind of obstacle it is, in one word, for the tile that has room for one.+ *+ * - `not-installed` — the software is missing and installing it is the fix.+ * - `unsupported` — it cannot run here at all: no session adapter for this+ * provider, or a platform that cannot host one. Telling someone to install+ * something is wrong here; there is nothing they could install.+ * - `unknown` — the check itself did not come back. Kept apart from the other+ * two on purpose: a host that could not be probed has not said the CLI is+ * missing, and reporting it as missing would invent an answer.+ *+ * The full {@link AgentTypeAvailability.blockedReason} still says which, in+ * full, wherever there is room for a sentence.+ */+export type AgentTypeBlockedKind = 'not-installed' | 'unsupported' | 'unknown';+export type AgentTypeAvailability = {agentId: string;/** True only when this type can be onboarded here right now. */@@ -22,4 +38,7 @@ export type AgentTypeAvailability = {* reason is the silence this type exists to remove.*/blockedReason: string | null;+ /** The same verdict in one word, for a tile too small for the sentence.+ * Null exactly when {@link blockedReason} is. */+ blockedKind: AgentTypeBlockedKind | null;};diff --git a/console/packages/agent-providers/src/antigravity/antigravity-adapter.ts b/console/packages/agent-providers/src/antigravity/antigravity-adapter.tsindex 33c27322d..8e2126fa8 100644--- a/console/packages/agent-providers/src/antigravity/antigravity-adapter.ts+++ b/console/packages/agent-providers/src/antigravity/antigravity-adapter.ts@@ -22,7 +22,7 @@ import {type ProviderLogger,} from '../transport/stdio-json-rpc';import { modelsFromConfig, type ConfigOption } from './protocol';-import { createAntigravityClient, initializeAntigravity } from './runtime';+import { authenticateAntigravity, createAntigravityClient, initializeAntigravity } from './runtime';interface PermissionOption {optionId: string;@@ -154,6 +154,10 @@ export class AntigravityAdapter implements ProviderAdapter {this.emit(state, { type: 'session.state.changed', status: 'starting' });try {const initialized = await initializeAntigravity(client);+ // Signing in belongs here — starting a session is work the user asked+ // for, so a browser opening is an answer to something they did. The+ // readiness probe deliberately stops at the handshake above.+ await authenticateAntigravity(client);const mcpServers = Object.entries(input.mcpServers).map(([name, server]) =>server.transport === 'stdio'? {diff --git a/console/packages/agent-providers/src/antigravity/runtime.ts b/console/packages/agent-providers/src/antigravity/runtime.tsindex 25d66e958..5bda5fcad 100644--- a/console/packages/agent-providers/src/antigravity/runtime.ts+++ b/console/packages/agent-providers/src/antigravity/runtime.ts@@ -52,14 +52,35 @@ export async function createAntigravityClient(input: {});}+/**+ * The ACP handshake, and nothing else.+ *+ * Deliberately does NOT sign in. The response's `authMethods` is the agent+ * saying which sign-ins are still outstanding, so this is the whole of what a+ * caller needs to ANSWER "is this signed in?" — and answering that question+ * must not change it. Signing in is {@link authenticateAntigravity}, called+ * only where the user has asked for work that needs it.+ */export async function initializeAntigravity(client: StdioJsonRpcClient) {- const initialized = await client.request<{+ return await client.request<{agentCapabilities?: { sessionCapabilities?: { resume?: unknown } };+ authMethods?: { id?: string }[];}>('initialize', {protocolVersion: 1,clientInfo: { name: 'switch-console', version: '0.1.0' },clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },});+}++/**+ * Sign in to the ACP server.+ *+ * **This opens a browser** when the profile holds no usable token — the OAuth+ * consent page, launched by the agent itself. `BROWSER=false` in the spawn env+ * asks it not to, and it is not obliged to listen, which is why the call site+ * matters more than the mitigation: only call this for work the user asked+ * for, never to find out whether it would be needed.+ */+export async function authenticateAntigravity(client: StdioJsonRpcClient) {await client.request('authenticate', { methodId: 'oauth-personal' });- return initialized;}diff --git a/console/packages/agent-providers/src/host/provider-readiness.protocol.test.ts b/console/packages/agent-providers/src/host/provider-readiness.protocol.test.tsindex b837ab499..b187dd57f 100644--- a/console/packages/agent-providers/src/host/provider-readiness.protocol.test.ts+++ b/console/packages/agent-providers/src/host/provider-readiness.protocol.test.ts@@ -50,15 +50,38 @@ it('does not classify a transport failure as missing credentials', async () => {expect((await checkProviderReadiness({ ...input, provider: 'codex' })).status).toBe('unknown');expect(mock.dispose).toHaveBeenCalledOnce();});-it('checks Antigravity authentication on ACP without opening a conversation', async () => {- mock.request.mockResolvedValueOnce({}).mockResolvedValueOnce({});+// The probe used to answer "are you signed in?" by calling `authenticate` —+// which does not test the sign-in, it performs it, opening a browser. It then+// reported success whether or not anything had happened. Asking a question must+// not be the thing that changes the answer.+it('answers Antigravity sign-in from the handshake, without signing in', async () => {+ mock.request.mockResolvedValueOnce({ authMethods: [] });const result = await checkProviderReadiness({ ...input, provider: 'antigravity' });expect(result.status).toBe('authenticated');- expect(mock.request.mock.calls.map((call) => call[0])).toEqual(['initialize', 'authenticate']);+ expect(mock.request.mock.calls.map((call) => call[0])).toEqual(['initialize']);expect(mock.dispose).toHaveBeenCalledOnce();});-it('reports Antigravity sign-in failures', async () => {- mock.request.mockResolvedValueOnce({}).mockRejectedValueOnce(new Error('Sign in required'));+it('never calls authenticate, whatever the agent reports', async () => {+ mock.request.mockResolvedValueOnce({ authMethods: [{ id: 'oauth-personal' }] });+ await checkProviderReadiness({ ...input, provider: 'antigravity' });+ expect(mock.request.mock.calls.map((call) => call[0])).not.toContain('authenticate');+});+it('reports an outstanding Antigravity sign-in as unauthenticated', async () => {+ mock.request.mockResolvedValueOnce({ authMethods: [{ id: 'oauth-personal' }] });+ const result = await checkProviderReadiness({ ...input, provider: 'antigravity' });+ expect(result.status).toBe('unauthenticated');+ expect(result.message).toContain('antigravity-acp --login');+ expect(mock.dispose).toHaveBeenCalledOnce();+});+// An agent that says nothing about auth is not an agent asking to be signed in.+it('treats a handshake with no authMethods as nothing outstanding', async () => {+ mock.request.mockResolvedValueOnce({});+ expect((await checkProviderReadiness({ ...input, provider: 'antigravity' })).status).toBe(+ 'authenticated'+ );+});+it('reports Antigravity handshake failures', async () => {+ mock.request.mockRejectedValueOnce(new Error('Sign in required'));expect((await checkProviderReadiness({ ...input, provider: 'antigravity' })).status).toBe('unauthenticated');diff --git a/console/packages/agent-providers/src/host/provider-readiness.ts b/console/packages/agent-providers/src/host/provider-readiness.tsindex 7b8943b2d..48f35c63a 100644--- a/console/packages/agent-providers/src/host/provider-readiness.ts+++ b/console/packages/agent-providers/src/host/provider-readiness.ts@@ -1,7 +1,11 @@import { execFile } from 'node:child_process';import { promisify } from 'node:util';import { z } from 'zod';-import { createAntigravityClient, initializeAntigravity } from '../antigravity/runtime';+import {+ ANTIGRAVITY_SIGN_IN,+ createAntigravityClient,+ initializeAntigravity,+} from '../antigravity/runtime';import { startOpencodeServer, stopOpencodeServer } from '../opencode/server';import { JsonRpcError, noopLogger, StdioJsonRpcClient } from '../transport/stdio-json-rpc';@@ -107,8 +111,15 @@ export async function checkProviderReadiness(input: {}if (input.provider === 'antigravity') {client = await createAntigravityClient({ ...input, logger: noopLogger, onExit: () => {} });- await initializeAntigravity(client);- return result('authenticated', 'Signed in to Antigravity ACP.');+ // Handshake only. This used to call `authenticate`, which does not test+ // the sign-in — it performs it, opening a browser, and then reported+ // "signed in" whether or not anything had happened. `authMethods` is the+ // agent's own answer to the question being asked: the sign-ins it still+ // wants. Empty means none outstanding.+ const initialized = await initializeAntigravity(client);+ return initialized.authMethods?.length+ ? result('unauthenticated', ANTIGRAVITY_SIGN_IN)+ : result('authenticated', 'Signed in to Antigravity ACP.');}if (input.provider !== 'codex')return result('unknown', 'This provider has no authentication check.');diff --git a/console/packages/agent-providers/src/host/shared-watcher.test.ts b/console/packages/agent-providers/src/host/shared-watcher.test.tsindex e3f81fc59..8a7302be4 100644--- a/console/packages/agent-providers/src/host/shared-watcher.test.ts+++ b/console/packages/agent-providers/src/host/shared-watcher.test.ts@@ -208,3 +208,53 @@ it('restarts only the live sessions of this agent left on a superseded build', a]);expect(vi.mocked(ensureSharedProcess).mock.calls[0]![0].restart).toBe(false);});++// The sweep reads every session on the machine and only then asks whether each+// one belongs to this agent, so a directory left by an older build — naming a+// provider that no longer exists — used to abort the call and take auto-start+// down for an agent that had nothing to do with it.+it('steps over a neighbour whose saved config no longer parses', async () => {+ const root = await mkdtemp(join(tmpdir(), 'shared-watch-stale-'));+ roots.push(root);+ paths.root = root;+ supervisors.clear();+ vi.mocked(ensureSharedProcess).mockClear();+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const agentId = randomUUID();++ // A provider this build has never heard of: exactly what `fde4e217` left on+ // disk for anyone who had a gemini/droid/amp agent before it was removed.+ const stale = template(root);+ stale.session = { ...stale.session, sessionId: 'stale-session', agentId: randomUUID() };+ await mkdir(join(root, 'stale'), { recursive: true });+ await writeFile(+ join(root, 'stale', 'config.json'),+ JSON.stringify({ ...stale, start: { ...stale.start, provider: 'gemini' } })+ );+ // And one that is not even JSON, which must not be fatal either.+ await mkdir(join(root, 'corrupt'), { recursive: true });+ await writeFile(join(root, 'corrupt', 'config.json'), '{ truncated');++ const mine = template(root);+ mine.session = { ...mine.session, sessionId: 'my-session', agentId };+ mine.start.input.sessionId = 'my-session';+ await mkdir(join(root, 'mine'), { recursive: true });+ await writeFile(join(root, 'mine', 'config.json'), JSON.stringify(mine));+ supervisors.set(join(root, 'mine'), { build: '/host/shared-host-old.mjs' });++ await expect(+ replaceSupersededSessions(agentId, {+ build: '/host/shared-host-new.mjs',+ start: vi.fn(),+ stop: vi.fn(),+ })+ ).resolves.toBeUndefined();++ // This agent's own session is still picked up, which is the whole point.+ expect(vi.mocked(ensureSharedProcess).mock.calls.map((call) => call[0].root)).toEqual([+ join(root, 'mine'),+ ]);+ // Skipped, but never in silence.+ expect(warn.mock.calls.map(String).join('\n')).toContain('stale');+ warn.mockRestore();+});diff --git a/console/packages/agent-providers/src/host/shared-watcher.ts b/console/packages/agent-providers/src/host/shared-watcher.tsindex da4e61530..0929c8221 100644--- a/console/packages/agent-providers/src/host/shared-watcher.ts+++ b/console/packages/agent-providers/src/host/shared-watcher.ts@@ -91,7 +91,18 @@ export async function replaceSupersededSessions();} catch (error) {if (['ENOENT', 'ENOTDIR'].includes((error as NodeJS.ErrnoException).code ?? '')) continue;- throw error;+ // This is a sweep over every session on the machine, and the filter for+ // "is it even this agent's" is the line below — after the parse. So a+ // directory left by an older build, naming a provider this one no longer+ // has, used to abort the whole call and take auto-sessions down for an+ // agent that had nothing to do with it. One unreadable neighbour is not a+ // reason to stop; it is a reason to say so and carry on.+ console.warn(+ `Skipping session state at ${root}: its config could not be read (${+ error instanceof Error ? error.message : String(error)+ }). It will not be restarted.`+ );+ continue;}if (config.session.agentId !== agentId) continue;const running = await liveSupervisor(root);diff --git a/deploy/local/standalone-docker-compose.yml b/deploy/local/standalone-docker-compose.ymlindex 2f1e9c077..ded42cedd 100644--- a/deploy/local/standalone-docker-compose.yml+++ b/deploy/local/standalone-docker-compose.yml@@ -241,6 +241,14 @@ services:OTLP_HEADERS:OTLP_EXPORT_INTERVAL_SECONDS:OTLP_TIMEOUT_SECONDS:+ # Product usage telemetry, forwarded for the same reason and in the same+ # bare-key form. Switch Console writes TELEMETRY_ENABLED into the `.env`+ # from the user's "Share usage data" choice, so one consent decision+ # governs the app and the server it runs for them (CHOO-2890). On a stack+ # brought up by hand, an operator sets it here the same way.+ TELEMETRY_ENABLED:+ TELEMETRY_ENDPOINT:+ TELEMETRY_SNAPSHOT_INTERVAL_HOURS:depends_on:postgres:condition: service_healthydiff --git a/docs/TELEMETRY.md b/docs/TELEMETRY.mdindex b41d9296e..29a8ee2eb 100644--- a/docs/TELEMETRY.md+++ b/docs/TELEMETRY.md@@ -1,8 +1,10 @@# Switch Console telemetry — what we collect, where it goes, and why it cannot be traced to a person**Audience:** InfoSec.-**Scope:** the Switch Console desktop app. Switch server-side logging is out of-scope and needs its own pass.+**Scope:** the Switch Console desktop app, and the consent decision it carries+to a Switch server it runs for the user (§4.1). What that server itself+collects is documented separately; Switch server-side logging is out of scope+here and needs its own pass.**Claim:** the data we transmit is anonymous. No field identifies a person, andno combination of the fields we transmit can be resolved back to one.@@ -226,6 +228,29 @@ immediately, with no further requests and no queued backlog. Dev builds nevertransmit regardless of the setting. Opting out is itself not reported — the onething we do not measure is someone asking not to be measured.+### 4.1 The same answer governs a server the Console runs++Switch Console can run a Switch server for the user — as containers on their own+machine, or on a host they have given it over SSH. That server has product-usage+telemetry of its own, off unless its configuration turns it on, and the Console's+toggle is what turns it on: the answer is written into the server's configuration+every time the Console starts it, in both directions. "No" is written down+explicitly rather than left out, because a stack started under a "yes" would+otherwise keep the setting it started with.++Two limits are stated in the app rather than left to be discovered.++- **The server reads the setting when it starts.** Changing the answer while it+ is running does not reach it until it restarts, and the Console does not+ restart it silently — a restart ends live agent sessions. Instead the server's+ page says the running server is out of step with the answer and offers the+ restart. The check reads the running container's own environment, so a start+ that wrote the configuration and then failed is reported as out of step rather+ than as applied; a server that cannot be read at all is reported as unknown,+ never as agreeing.+- **A server reached by URL is not covered.** It is somebody else's deployment+ with its own answer, and the toggle neither reaches it nor claims to.+---## 5. The identifierdiff --git a/docs/old/telemetry-events.md b/docs/old/telemetry-events.mdindex 358261678..e6b1da82a 100644--- a/docs/old/telemetry-events.md+++ b/docs/old/telemetry-events.md@@ -504,6 +504,16 @@ having been made, and re-read on every event so revoking takes effectimmediately. **The server takes the same position**: telemetry is off unlessswitched on, it is one setting, and when it is off no request is made at all.+Who sets that one setting depends on who deployed the server. On a stack an+operator brought up themselves, they set `TELEMETRY_ENABLED` — in the `.env` for+the standalone compose file, or in the chart's values. On a stack **Switch+Console runs for a user**, the Console sets it from that user's "Share usage+data" answer at every start, in both directions, so the person running the+server and the person answering are the same person and answer once+(`CHOO-2890`). Because the gate is read at boot, a change to the answer reaches+a running server only when it restarts; the Console says so on the server's page+and offers the restart rather than taking it.+This interacts with the milestone events in a way worth stating: a deploymentthat enables telemetry three months in has already passed most of itsactivation funnel. Milestones are emitted only when they actually occur, never