Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
Add consent-aware telemetry for Cua Driver and Lume (#2211)
Francesco Bonaccicb18c24f3189
diff --git a/.github/scripts/tests/test_cua_driver_release_wiring.py b/.github/scripts/tests/test_cua_driver_release_wiring.pyindex ad1bb9350c..cb281c6d54 100644--- a/.github/scripts/tests/test_cua_driver_release_wiring.py+++ b/.github/scripts/tests/test_cua_driver_release_wiring.py@@ -57,12 +57,95 @@ class TestCuaDriverReleaseWiring(unittest.TestCase):workflow,)+ def test_distro_compat_downloads_release_asset_once_per_run(self) -> None:+ workflow = self.read(".github/workflows/ci-distro-compat-cua-driver.yml")++ self.assertEqual(workflow.count('curl -fsSL "$BINARY_URL"'), 1)+ self.assertIn("actions/upload-artifact@v4", workflow)+ self.assertIn("actions/download-artifact@v4", workflow)+ self.assertIn("cua-driver-release-${{ steps.pick.outputs.version }}", workflow)+ self.assertIn('CUA_DRIVER_RS_TELEMETRY_ENABLED: "false"', workflow)+ self.assertIn('CUA_TELEMETRY_ENABLED: "false"', workflow)+def test_rust_driver_bump_keeps_python_wrapper_version_synced(self) -> None:config = self.read("libs/cua-driver/rust/.bumpversion.cfg")self.assertIn("[bumpversion:file:../python/pyproject.toml]", config)self.assertIn("[bumpversion:file:../python/src/cua_driver/__init__.py]", config)+ def test_installers_preserve_legacy_telemetry_state_before_cleanup(self) -> None:+ for relative_path in (+ "libs/cua-driver/scripts/_install-rust.sh",+ "libs/cua-driver/scripts/_install-local-rust.sh",+ ):+ installer = self.read(relative_path)+ cleanup = installer.index('rm -rf "$LEGACY_HOME_DIR"')+ self.assertLess(+ installer.index("for telemetry_file in .telemetry_id .installation_recorded"),+ cleanup,+ relative_path,+ )+ self.assertLess(+ installer.index('cp -p "$LEGACY_HOME_DIR/$telemetry_file"'),+ cleanup,+ relative_path,+ )++ powershell = self.read("libs/cua-driver/scripts/install.ps1")+ cleanup = powershell.index(+ "Remove-Item -LiteralPath $LegacyHomeDir -Recurse -Force"+ )+ self.assertLess(+ powershell.index("foreach ($telemetryFile in @('.telemetry_id', '.installation_recorded'))"),+ cleanup,+ )+ self.assertLess(+ powershell.index("Copy-Item -LiteralPath $legacyTelemetryPath"),+ cleanup,+ )++ def test_local_macos_signing_uses_an_unambiguous_identity_hash(self) -> None:+ installer = self.read("libs/cua-driver/scripts/_install-local-rust.sh")++ self.assertIn(+ 'security find-identity -v -p codesigning "$kc"',+ installer,+ )+ self.assertIn('SIGN_ID="$(ensure_local_signing_identity)"', installer)+ self.assertIn(+ 'codesign_bounded 20 --force --deep --sign "$SIGN_ID" "$APP_STAGE"',+ installer,+ )+ self.assertNotIn('printf \'%s\' "$CUA_LOCAL_SIGN_CN"; return', installer)++ def test_release_installers_persist_channel_before_binary_swap(self) -> None:+ shell = self.read("libs/cua-driver/scripts/_install-rust.sh")+ hint = shell.index('> "$HOME_DIR/.telemetry_install_channel"')+ self.assertLess(hint, shell.index('ditto "$SRC_APP" "$APP_DEST"'))+ self.assertLess(hint, shell.index('mv -Tf "$TMP_LINK" "$CURRENT_LINK"'))++ powershell = self.read("libs/cua-driver/scripts/install.ps1")+ hint = powershell.index("Set-Content -LiteralPath (Join-Path $HomeDir '.telemetry_install_channel')")+ self.assertLess(hint, powershell.index("Ensure-Junction $CurrentDir $versionedDir"))++ def test_lifecycle_telemetry_runs_outside_foreground_command(self) -> None:+ main = self.read("libs/cua-driver/rust/crates/cua-driver/src/main.rs")+ telemetry = self.read(+ "libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs"+ )++ self.assertNotIn("telemetry::ensure_first_run_registration();", main)+ self.assertGreaterEqual(+ main.count("telemetry::run_lifecycle_worker_if_requested()"), 2+ )+ self.assertGreaterEqual(+ main.count("telemetry::spawn_first_run_registration_worker()"), 3+ )+ self.assertIn("CUA_DRIVER_LIFECYCLE_TELEMETRY_WORKER", telemetry)+ self.assertIn(".stdin(Stdio::null())", telemetry)+ self.assertIn(".stdout(Stdio::null())", telemetry)+ self.assertIn(".stderr(Stdio::null())", telemetry)+if __name__ == "__main__":unittest.main()diff --git a/.github/workflows/ci-distro-compat-cua-driver.yml b/.github/workflows/ci-distro-compat-cua-driver.ymlindex a176113cf2..4d9761d23c 100644--- a/.github/workflows/ci-distro-compat-cua-driver.yml+++ b/.github/workflows/ci-distro-compat-cua-driver.yml@@ -96,8 +96,27 @@ jobs:echo "Binary URL: $BINARY_URL"fi+ # Download the public release asset exactly once for the whole workflow.+ # Matrix jobs consume the Actions artifact below instead of incrementing+ # the GitHub release asset counter once per distro.+ - name: Download released binary once+ if: steps.pick.outputs.version != 'none'+ env:+ BINARY_URL: ${{ steps.pick.outputs.binary_url }}+ run: curl -fsSL "$BINARY_URL" -o cua-driver-release.tar.gz++ - name: Cache released binary for matrix+ if: steps.pick.outputs.version != 'none'+ uses: actions/upload-artifact@v4+ with:+ name: cua-driver-release-${{ steps.pick.outputs.version }}+ path: cua-driver-release.tar.gz+ if-no-files-found: error+ retention-days: 1+# ── Per-distro smoke-test matrix ─────────────────────────────────────────────- # Each job runs in a real distro container, downloads the released binary,+ # Each job runs in a real distro container, restores the one workflow-cached+ # released binary,# and asserts that:# 1. The binary executes at all (catches glibc ABI floor regressions).# 2. `--version` prints a version string.@@ -118,6 +137,12 @@ jobs:# Don't block the PR if no release binary exists yet.continue-on-error: trueruns-on: ubuntu-latest+ env:+ # The released binary's smoke commands must never create client telemetry+ # or installation markers from a CI runner. Set both names during the+ # compatibility window; Rust reads the RS-prefixed variable.+ CUA_DRIVER_RS_TELEMETRY_ENABLED: "false"+ CUA_TELEMETRY_ENABLED: "false"container:image: ${{ matrix.image }}strategy:@@ -174,14 +199,17 @@ jobs:if: needs.resolve-version.outputs.version != 'none'run: ${{ matrix.pkg_install }}- - name: Download released binary+ - name: Restore workflow-cached released binary+ if: needs.resolve-version.outputs.version != 'none'+ uses: actions/download-artifact@v4+ with:+ name: cua-driver-release-${{ needs.resolve-version.outputs.version }}+ path: release-artifact++ - name: Extract released binaryif: needs.resolve-version.outputs.version != 'none'- env:- BINARY_URL: ${{ needs.resolve-version.outputs.binary_url }}run: |- echo "Downloading: $BINARY_URL"- curl -fsSL "$BINARY_URL" -o cua-driver.tar.gz- tar -xzf cua-driver.tar.gz+ tar -xzf release-artifact/cua-driver-release.tar.gzchmod +x cua-driverls -lh cua-driverdiff --git a/docs/content/docs/how-to-guides/driver/install.mdx b/docs/content/docs/how-to-guides/driver/install.mdxindex 720ecc7064..1098c493f0 100644--- a/docs/content/docs/how-to-guides/driver/install.mdx+++ b/docs/content/docs/how-to-guides/driver/install.mdx@@ -8,6 +8,10 @@ import { Callout } from 'fumadocs-ui/components/callout';Cua Driver supports macOS, Windows, and Linux. Use the same **one-line installer** on each platform; the script selects the right install path for the host and *does not require administrator access*.+<Callout type="info">+ Cua Driver sends content-free product telemetry by default. The installer shows this notice before the first event. Run `cua-driver telemetry disable` at any time to stop telemetry; the preference persists across upgrades. See [Telemetry and privacy](/reference/cua-driver/telemetry) for the exact event schema and identity controls.+</Callout>+<Tabs items={['macOS', 'Windows', 'Linux']}><Tab value="macOS">diff --git a/docs/content/docs/reference/cua-driver/cli-reference.mdx b/docs/content/docs/reference/cua-driver/cli-reference.mdxindex 51cc60fc6d..5440b24ab2 100644--- a/docs/content/docs/reference/cua-driver/cli-reference.mdx+++ b/docs/content/docs/reference/cua-driver/cli-reference.mdx@@ -281,6 +281,56 @@ Print a pasteable install-layout and permission-attribution report.## Other commands+### `cua-driver telemetry`++Inspect or change content-free product telemetry.++Telemetry is default-on. Disable retains the pseudonymous installation ID; reset-id erases the ID and event markers while preserving the preference.++#### `cua-driver telemetry enable`++Persistently enable telemetry.++#### `cua-driver telemetry disable`++Persistently disable every telemetry request.++Retains the local installation ID.++#### `cua-driver telemetry status`++Show the effective setting and redacted identity state.++**Flags:**++| Name | Description |+| ---- | ----------- |+| `--json` | Emit JSON. |++#### `cua-driver telemetry reset-id`++Erase the installation ID and event markers.++The persisted enabled/disabled preference is retained.++#### `cua-driver telemetry inspect`++Build a fixed event payload without sending it.++The distinct ID is replaced with a redacted placeholder.++**Arguments:**++| Name | Type | Required | Description |+| ---- | ---- | -------- | ----------- |+| `<event>` | String | Yes | Fixed telemetry event name. |++**Flags:**++| Name | Description |+| ---- | ----------- |+| `--json` | Emit JSON. |+### `cua-driver autostart`Manage platform-native daemon autostart.diff --git a/docs/content/docs/reference/cua-driver/meta.json b/docs/content/docs/reference/cua-driver/meta.jsonindex f90c04713f..ae2d6dd5a4 100644--- a/docs/content/docs/reference/cua-driver/meta.json+++ b/docs/content/docs/reference/cua-driver/meta.json@@ -2,6 +2,7 @@"title": "Cua Driver","pages": ["cli-reference",+ "telemetry","macos-permissions","embedding","mcp-tools",diff --git a/docs/content/docs/reference/cua-driver/telemetry.mdx b/docs/content/docs/reference/cua-driver/telemetry.mdxnew file mode 100644index 0000000000..f79f6a6ce3--- /dev/null+++ b/docs/content/docs/reference/cua-driver/telemetry.mdx@@ -0,0 +1,107 @@+---+title: Telemetry and privacy+description: Exact Cua Driver telemetry controls, event schema, and privacy boundaries.+---++Cua Driver sends content-free product telemetry to the PostHog EU ingest endpoint. Telemetry is enabled by default. The installer prints a notice before it sends the first event, and the preference persists across driver processes and upgrades.++If an installation or release event fails, the driver leaves its success marker unset and waits 15 minutes before retrying. Commands during that interval do not wait for another telemetry request.++## Control telemetry++```bash+cua-driver telemetry status --json+cua-driver telemetry disable+cua-driver telemetry enable+```++An environment override takes precedence over the saved preference:++```bash+CUA_DRIVER_RS_TELEMETRY_ENABLED=false cua-driver mcp+```++Disabling telemetry stops telemetry requests. It does not delete the local installation ID, so enabling telemetry later resumes the same pseudonymous installation identity. A normal uninstall also preserves the ID and saved preference. To create a new identity, run:++```bash+cua-driver telemetry reset-id+```++Use `uninstall --purge` when uninstalling if you also want to remove retained Cua Driver state.++## Inspect events locally++`inspect` builds the event without sending a network request. It replaces the installation ID with a redacted placeholder.++```bash+cua-driver telemetry inspect cua_driver_mcp_session_started --json+cua-driver telemetry inspect cua_driver_mcp_tool_completed --json+```++## Common event properties++Every schema-v2 client event has this fixed envelope:++| Property | Meaning |+| -------------------------- | --------------------------------------------------------- |+| `telemetry_schema_version` | Fixed integer `2` |+| `product_version` | Installed Cua Driver version |+| `os_family` | `macos`, `windows`, `linux`, or `other` |+| `os_major` | Major operating-system version only |+| `arch` | Bounded CPU architecture |+| `is_ci` | Whether a recognized CI environment is present |+| `transport` | `cli`, `mcp_stdio`, `mcp_http`, or `unknown` |+| `process_session_id` | Random ID created once per process and never persisted |+| `id_persisted` | Whether the installation ID came from durable local state |+| `$geoip_disable` | Fixed `true`; PostHog GeoIP enrichment is disabled |++Client events set `$process_person_profile` to `false`. The installation UUID is used only as the PostHog `distinct_id`; it is not duplicated into event properties. This is pseudonymous installation telemetry, not anonymous telemetry.++## Fixed events++| Event | Additional bounded properties |+| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------- |+| `cua_driver_installation_registered` | `install_channel` |+| `cua_driver_release_installed` | `install_channel`, `product_version` |+| `cua_driver_mcp` | None. Transitional process-start event emitted when `cua-driver mcp` starts; `transport` is `mcp_stdio` in the common envelope. |+| `cua_driver_serve` | None. Transitional process-start event emitted when `cua-driver serve` starts; `transport` is `cli` in the common envelope. |+| `cua_driver_cli_completed` | Completed finite CLI outcomes: fixed `command`, `success`, `exit_class`, and `duration_bucket` |+| `cua_driver_mcp_session_started` | normalized MCP client and protocol, capability booleans, optional reported agent context |+| `cua_driver_mcp_tool_completed` | allowlisted tool, success, error class, duration bucket, output type, output-size bucket |++The transitional `cua_driver_mcp` and `cua_driver_serve` events carry the common event properties above and no additional properties. They do not contain MCP initialize data, command arguments, or process output.++The legacy `cua_driver_install` event remains part of lifetime registration dashboards so existing installations are not registered a second time.++## Reported model and agent context++An MCP host can explicitly report agent context in the initialize request:++```json+{+ "params": {+ "_meta": {+ "ai.cua/agent-context": {+ "provider": "anthropic",+ "model": "claude-sonnet-4-5",+ "agent_name": "claude-code",+ "agent_version": "1.x"+ }+ }+ }+}+```++These values are self-reported and normalized through allowlists. Unknown values become `custom` or `unknown`. Cua Driver does not infer a model from the MCP client name, does not use MCP Sampling to identify the parent model, and does not collect the complete initialize payload. This session event currently covers stdio MCP only; HTTP session telemetry remains disabled until Cua Driver implements explicit HTTP session semantics.++## Data that is never collected++Routine telemetry excludes task text, prompts, tool arguments, tool response bodies, typed text, screenshots, accessibility trees, window titles, application names, file paths, URLs, arbitrary MCP metadata, and raw error messages.++Tool-completion events retain only coarse result shape: text, image, mixed, empty, or unknown; a size bucket; a duration bucket; and a fixed error class. The content itself never crosses the telemetry observer boundary.++## Region and deletion controls++Client events are sent to PostHog's EU ingest endpoint with GeoIP enrichment disabled. PostHog does not create person profiles for these events. Network infrastructure may still process request metadata under the [Cua privacy policy](https://cua.ai/privacy-policy), but IP-derived location is not added to the telemetry event.++Retention and server-side deletion are governed by the [Cua privacy policy](https://cua.ai/privacy-policy); the client does not enforce a retention window or submit deletion requests. `telemetry reset-id` and uninstall purge controls remove local identity state only. Do not post the installation UUID in a public issue.diff --git a/docs/content/docs/reference/lume/cli-reference.mdx b/docs/content/docs/reference/lume/cli-reference.mdxindex 917006d04a..f5a527c3e7 100644--- a/docs/content/docs/reference/lume/cli-reference.mdx+++ b/docs/content/docs/reference/lume/cli-reference.mdx@@ -35,7 +35,7 @@ Create a new virtual machine| `--os` | String | macOS | Operating system to install (macOS or linux) || `--cpu` | Int | 4 | Number of CPU cores || `--memory` | String | 8GB | Memory size (e.g., 8GB) |-| `--disk-size` | String | 50GB | Disk size (e.g., 50GB) |+| `--disk-size` | String | 100GB for macOS; 50GB for Linux | Disk size (e.g., 100GB) || `--display` | String | 1024x768 | Display resolution (e.g., 1024x768) || `--ipsw` | String | - | Path to IPSW file or 'latest' for macOS VMs || `--storage` | String | - | VM storage location to use |@@ -384,6 +384,11 @@ Get or set lume configuration- `lume config cache dir` - Get or set cache directory- `lume config cache enable` - Enable image caching- `lume config cache disable` - Disable image caching+- `lume config telemetry` - Manage pseudonymous telemetry settings+ - `lume config telemetry status` - Show current telemetry status+ - `lume config telemetry enable` - Enable pseudonymous telemetry+ - `lume config telemetry disable` - Disable pseudonymous telemetry+ - `lume config telemetry reset-id` - Delete the pseudonymous installation ID and registration markers### lume servediff --git a/libs/cua-driver/python/src/cua_driver/wrapper.py b/libs/cua-driver/python/src/cua_driver/wrapper.pyindex f91a202571..193c513635 100644--- a/libs/cua-driver/python/src/cua_driver/wrapper.py+++ b/libs/cua-driver/python/src/cua_driver/wrapper.py@@ -54,6 +54,14 @@ def run_cua_driver(args: Optional[list[str]] = None) -> int:binary_path = get_binary_path()+ # Let the binary's consent-aware first-run registration distinguish a+ # bundled Python installation from an installer-script installation. Do+ # not overwrite an explicit bounded channel inherited from `update` or a+ # test harness. The Rust binary owns validation, consent, identity, and+ # per-version deduplication.+ child_env = os.environ.copy()+ child_env.setdefault("CUA_DRIVER_INSTALL_CHANNEL", "python_package")+try:# Run with direct stdio inheritance - no buffering, no capturingresult = subprocess.run(@@ -61,6 +69,7 @@ def run_cua_driver(args: Optional[list[str]] = None) -> int:stdin=sys.stdin,stdout=sys.stdout,stderr=sys.stderr,+ env=child_env,)return result.returncodeexcept KeyboardInterrupt:diff --git a/libs/cua-driver/python/tests/test_wrapper.py b/libs/cua-driver/python/tests/test_wrapper.pyindex d0d8b7518b..f40d15d080 100644--- a/libs/cua-driver/python/tests/test_wrapper.py+++ b/libs/cua-driver/python/tests/test_wrapper.py@@ -1,5 +1,6 @@"""Tests for the cua-driver Python wrapper."""+import osimport subprocessimport sysfrom pathlib import Path@@ -69,6 +70,26 @@ def test_subprocess_args(mock_get_binary, mock_run):assert call_args[1]["stdin"] == sys.stdinassert call_args[1]["stdout"] == sys.stdoutassert call_args[1]["stderr"] == sys.stderr+ assert call_args[1]["env"]["CUA_DRIVER_INSTALL_CHANNEL"] == "python_package"+++@patch("cua_driver.wrapper.subprocess.run")+@patch("cua_driver.wrapper.get_binary_path")+def test_subprocess_preserves_explicit_install_channel(+ mock_get_binary, mock_run, monkeypatch+):+ """An update/install caller's bounded channel takes precedence."""+ from cua_driver.wrapper import run_cua_driver++ mock_get_binary.return_value = Path("/fake/path/cua-driver")+ mock_run.return_value = Mock(returncode=0)+ monkeypatch.setenv("CUA_DRIVER_INSTALL_CHANNEL", "update_apply")++ run_cua_driver(["--version"])++ child_env = mock_run.call_args.kwargs["env"]+ assert child_env["CUA_DRIVER_INSTALL_CHANNEL"] == "update_apply"+ assert os.environ["CUA_DRIVER_INSTALL_CHANNEL"] == "update_apply"@patch("cua_driver.wrapper.subprocess.run")diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rsindex ff024628bf..773dbb3677 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/protocol.rs@@ -34,6 +34,148 @@ impl Request {.unwrap_or(Value::Object(Default::default()));Ok(ToolCall { name, args })}++ /// Extract the small, declared subset of MCP initialize metadata that a+ /// transport observer may use. The complete initialize payload is never+ /// retained or forwarded: arbitrary `_meta`, capability payloads, and+ /// client-defined extension values are deliberately ignored.+ pub fn initialize_metadata(&self) -> Option<InitializeMetadata> {+ if self.method != "initialize" {+ return None;+ }++ let params = self.params.as_ref();+ let protocol_version = params+ .and_then(|p| p.get("protocolVersion"))+ .and_then(Value::as_str)+ .and_then(bounded_metadata_value);+ let client_info = params.and_then(|p| p.get("clientInfo"));+ let client_name = client_info+ .and_then(|v| v.get("name"))+ .and_then(Value::as_str)+ .and_then(bounded_metadata_value);+ let client_version = client_info+ .and_then(|v| v.get("version"))+ .and_then(Value::as_str)+ .and_then(bounded_metadata_value);++ let capabilities = params.and_then(|p| p.get("capabilities"));+ let capability_flags = ClientCapabilityFlags {+ tools: capability_declared(capabilities, "tools"),+ roots: capability_declared(capabilities, "roots"),+ sampling: capability_declared(capabilities, "sampling"),+ experimental: capability_declared(capabilities, "experimental"),+ elicitation_form: nested_capability_declared(capabilities, "elicitation", "form"),+ elicitation_url: nested_capability_declared(capabilities, "elicitation", "url"),+ };++ let reported_agent_context = params+ .and_then(|p| p.get("_meta"))+ .and_then(|m| m.get("ai.cua/agent-context"))+ .filter(|v| v.is_object())+ .map(|ctx| ReportedAgentContext {+ provider: ctx+ .get("provider")+ .and_then(Value::as_str)+ .and_then(bounded_metadata_value),+ model: ctx+ .get("model")+ .and_then(Value::as_str)+ .and_then(bounded_metadata_value),+ agent_name: ctx+ .get("agent_name")+ .and_then(Value::as_str)+ .and_then(bounded_metadata_value),+ agent_version: ctx+ .get("agent_version")+ .and_then(Value::as_str)+ .and_then(bounded_metadata_value),+ })+ .filter(ReportedAgentContext::has_any_value);++ Some(InitializeMetadata {+ protocol_version,+ client_name,+ client_version,+ capability_flags,+ reported_agent_context,+ })+ }+}++/// Declared and bounded metadata from one MCP initialize request.+///+/// Values remain self-reported. A product telemetry layer must normalize them+/// through its own allowlists before emission.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct InitializeMetadata {+ pub protocol_version: Option<String>,+ pub client_name: Option<String>,+ pub client_version: Option<String>,+ pub capability_flags: ClientCapabilityFlags,+ pub reported_agent_context: Option<ReportedAgentContext>,+}++/// Presence-only capability flags. Capability values themselves are ignored.+#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]+pub struct ClientCapabilityFlags {+ pub tools: bool,+ pub roots: bool,+ pub sampling: bool,+ pub experimental: bool,+ pub elicitation_form: bool,+ pub elicitation_url: bool,+}++/// Values explicitly reported under+/// `initialize.params._meta["ai.cua/agent-context"]`.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct ReportedAgentContext {+ pub provider: Option<String>,+ pub model: Option<String>,+ pub agent_name: Option<String>,+ pub agent_version: Option<String>,+}++impl ReportedAgentContext {+ fn has_any_value(&self) -> bool {+ self.provider.is_some()+ || self.model.is_some()+ || self.agent_name.is_some()+ || self.agent_version.is_some()+ }+}++const MAX_METADATA_CHARS: usize = 128;++fn bounded_metadata_value(raw: &str) -> Option<String> {+ let trimmed = raw.trim();+ if trimmed.is_empty() {+ return None;+ }+ let value: String = trimmed+ .chars()+ .filter(|c| !c.is_control())+ .take(MAX_METADATA_CHARS)+ .collect();+ (!value.is_empty()).then_some(value)+}++fn capability_declared(capabilities: Option<&Value>, name: &str) -> bool {+ capabilities+ .and_then(|v| v.as_object())+ .is_some_and(|caps| caps.contains_key(name))+}++fn nested_capability_declared(+ capabilities: Option<&Value>,+ parent: &str,+ child: &str,+) -> bool {+ capabilities+ .and_then(|v| v.get(parent))+ .and_then(Value::as_object)+ .is_some_and(|value| value.contains_key(child))}pub struct ToolCall {@@ -240,3 +382,102 @@ mod image_mime_type_tests {assert!(v.get("mimeType").is_none(), "text content must not carry mimeType");}}++#[cfg(test)]+mod initialize_metadata_tests {+ use super::*;++ fn request(params: Value) -> Request {+ serde_json::from_value(serde_json::json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "initialize",+ "params": params,+ }))+ .expect("initialize request")+ }++ #[test]+ fn extracts_only_declared_initialize_fields() {+ let req = request(serde_json::json!({+ "protocolVersion": "2025-06-18",+ "clientInfo": { "name": "Claude Code", "version": "1.2.3", "secret": "ignore" },+ "capabilities": {+ "roots": { "listChanged": true, "arbitrary": "ignored" },+ "sampling": {},+ "elicitation": { "form": {}, "url": { "payload": "ignored" } },+ "experimental": { "anything": "ignored" }+ },+ "_meta": {+ "ai.cua/agent-context": {+ "provider": "anthropic",+ "model": "claude-sonnet-4-5",+ "agent_name": "claude-code",+ "agent_version": "1.x",+ "prompt": "must not be extracted"+ },+ "unrelated": { "task": "must not be extracted" }+ },+ "task": "must not be extracted"+ }));++ let metadata = req.initialize_metadata().expect("initialize metadata");+ assert_eq!(metadata.protocol_version.as_deref(), Some("2025-06-18"));+ assert_eq!(metadata.client_name.as_deref(), Some("Claude Code"));+ assert_eq!(metadata.client_version.as_deref(), Some("1.2.3"));+ assert!(metadata.capability_flags.roots);+ assert!(metadata.capability_flags.sampling);+ assert!(metadata.capability_flags.experimental);+ assert!(metadata.capability_flags.elicitation_form);+ assert!(metadata.capability_flags.elicitation_url);+ assert!(!metadata.capability_flags.tools);++ let agent = metadata+ .reported_agent_context+ .as_ref()+ .expect("reported agent context");+ assert_eq!(agent.provider.as_deref(), Some("anthropic"));+ assert_eq!(agent.model.as_deref(), Some("claude-sonnet-4-5"));+ assert_eq!(agent.agent_name.as_deref(), Some("claude-code"));+ assert_eq!(agent.agent_version.as_deref(), Some("1.x"));++ let debug = format!("{metadata:?}");+ for forbidden in ["secret", "prompt", "task", "arbitrary", "payload"] {+ assert!(!debug.contains(forbidden), "metadata leaked {forbidden}: {debug}");+ }+ }++ #[test]+ fn bounds_reported_strings_and_drops_empty_values() {+ let long_model = "m".repeat(MAX_METADATA_CHARS + 50);+ let req = request(serde_json::json!({+ "clientInfo": { "name": " client\nname ", "version": " " },+ "_meta": { "ai.cua/agent-context": { "model": long_model } }+ }));+ let metadata = req.initialize_metadata().unwrap();+ assert_eq!(metadata.client_name.as_deref(), Some("clientname"));+ assert!(metadata.client_version.is_none());+ assert_eq!(+ metadata+ .reported_agent_context+ .unwrap()+ .model+ .unwrap()+ .chars()+ .count(),+ MAX_METADATA_CHARS+ );+ }++ #[test]+ fn non_initialize_requests_have_no_initialize_metadata() {+ let req: Request = serde_json::from_value(serde_json::json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/list",+ "params": { "clientInfo": { "name": "not-an-initialize" } }+ }))+ .unwrap();+ assert!(req.initialize_metadata().is_none());+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rsindex 97a0be020d..9f19f25bc5 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/server.rs@@ -1,12 +1,194 @@//! Async MCP stdio server loop.-use std::sync::Arc;+use std::sync::{Arc, OnceLock};+use std::time::Instant;use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};use tracing::{debug, error, warn};-use crate::protocol::{initialize_result, Request, Response};+use crate::protocol::{initialize_result, InitializeMetadata, Request, Response, ResponseBody};use crate::tool::ToolRegistry;+/// Receives privacy-bounded observations from the stdio MCP transport.+///+/// The observer never receives tool arguments, text/image content, response+/// bodies, arbitrary MCP metadata, or raw errors. HTTP dispatch deliberately+/// bypasses this seam and remains unobserved until HTTP session semantics are+/// defined.+pub trait StdioObserver: Send + Sync + 'static {+ fn on_session_started(&self, metadata: InitializeMetadata);+ fn on_tool_completed(&self, outcome: ToolCompletionObservation);+}++static STDIO_OBSERVER: OnceLock<Arc<dyn StdioObserver>> = OnceLock::new();++/// Register the process-wide stdio observer. Registration is intentionally+/// one-shot so a second subsystem cannot replace the privacy policy at runtime.+pub fn set_stdio_observer(observer: Arc<dyn StdioObserver>) -> bool {+ STDIO_OBSERVER.set(observer).is_ok()+}++/// Coarse duration buckets used by tool-completion observations.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum DurationBucket {+ Under10Ms,+ Ms10To49,+ Ms50To249,+ Ms250To999,+ Ms1000To4999,+ Ms5000OrMore,+}++impl DurationBucket {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Under10Ms => "lt_10ms",+ Self::Ms10To49 => "10_49ms",+ Self::Ms50To249 => "50_249ms",+ Self::Ms250To999 => "250_999ms",+ Self::Ms1000To4999 => "1000_4999ms",+ Self::Ms5000OrMore => "gte_5000ms",+ }+ }+}++/// Content shape only. No content bytes or strings cross the observer seam.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OutputType {+ Empty,+ Text,+ Image,+ Mixed,+ Unknown,+}++impl OutputType {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Empty => "empty",+ Self::Text => "text",+ Self::Image => "image",+ Self::Mixed => "mixed",+ Self::Unknown => "unknown",+ }+ }+}++/// Coarse serialized-result size buckets. The serialized value is measured in+/// place and immediately discarded; only this enum reaches the observer.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OutputSizeBucket {+ Empty,+ Under1KiB,+ KiB1To9,+ KiB10To99,+ KiB100To1023,+ MiB1OrMore,+}++impl OutputSizeBucket {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::Empty => "0",+ Self::Under1KiB => "lt_1kib",+ Self::KiB1To9 => "1_9kib",+ Self::KiB10To99 => "10_99kib",+ Self::KiB100To1023 => "100_1023kib",+ Self::MiB1OrMore => "gte_1mib",+ }+ }+}++/// Fixed tool failure classes. Arbitrary error messages are never inspected or+/// forwarded.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum ToolErrorClass {+ None,+ InvalidParams,+ UnknownTool,+ PermissionDenied,+ BackgroundUnavailable,+ TransportError,+ InternalError,+}++impl ToolErrorClass {+ pub const fn as_str(self) -> &'static str {+ match self {+ Self::None => "none",+ Self::InvalidParams => "invalid_params",+ Self::UnknownTool => "unknown_tool",+ Self::PermissionDenied => "permission_denied",+ Self::BackgroundUnavailable => "background_unavailable",+ Self::TransportError => "transport_error",+ Self::InternalError => "internal_error",+ }+ }+}++/// Privacy-bounded completion record for a stdio `tools/call` request.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct ToolCompletionObservation {+ /// Still self-reported input at this layer. The telemetry consumer must map+ /// this through the registry allowlist and use an `unknown` fallback.+ pub tool_name: String,+ pub success: bool,+ pub error_class: ToolErrorClass,+ pub duration_bucket: DurationBucket,+ pub output_type: OutputType,+ pub output_size_bucket: OutputSizeBucket,+}++/// Which stdio execution path produced a response. This only affects the+/// classification of JSON-RPC internal errors and is not emitted directly.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum StdioExecutionPath {+ InProcess,+ DaemonProxy,+}++/// Start-state for one tool call. Public so the daemon-proxy transport can use+/// exactly the same privacy and bucketing logic as the in-process transport.+pub struct ToolObservationTimer {+ tool_name: String,+ known_tool: bool,+ valid_params: bool,+ path: StdioExecutionPath,+ started: Instant,+}++impl ToolObservationTimer {+ pub fn start(+ tool_name: String,+ known_tool: bool,+ valid_params: bool,+ path: StdioExecutionPath,+ ) -> Self {+ Self {+ tool_name,+ known_tool,+ valid_params,+ path,+ started: Instant::now(),+ }+ }++ pub fn finish(self, response: &Response) -> ToolCompletionObservation {+ classify_tool_completion(self, response)+ }+}++/// Notify the registered observer about a proxy-path initialize request.+/// Direct stdio calls this internally from [`run`].+pub fn observe_proxy_session_started(metadata: InitializeMetadata) {+ notify_session_started(metadata);+}++/// Notify the registered observer about a proxy-path tool result.+/// Direct stdio calls this internally from [`run`].+pub fn observe_proxy_tool_completed(outcome: ToolCompletionObservation) {+ notify_tool_completed(outcome);+}+/// Run the MCP server, reading JSON-RPC lines from stdin and writing/// responses to stdout. Exits when stdin reaches EOF or a fatal I/O/// error occurs.@@ -16,6 +198,7 @@ pub async fn run(registry: Arc<ToolRegistry>) -> anyhow::Result<()> {let mut reader = BufReader::new(stdin);let mut writer = tokio::io::BufWriter::new(stdout);let mut line = String::new();+ let mut session_observed = false;loop {line.clear();@@ -40,8 +223,27 @@ pub async fn run(registry: Arc<ToolRegistry>) -> anyhow::Result<()> {continue;}Ok(req) => {+ let initialize_metadata = (!session_observed)+ .then(|| req.initialize_metadata())+ .flatten();+ let tool_timer = tool_observation_timer(+ &req,+ |name| name == "type_text_chars" || registry.get_def(name).is_some(),+ StdioExecutionPath::InProcess,+ );let id = req.id.clone().unwrap_or(serde_json::Value::Null);- handle_request(req, id, ®istry).await+ let response = handle_request(req, id, ®istry).await;+ if let Some(metadata) = initialize_metadata {+ // A parsed initialize request always receives the static+ // initialize result from handle_request. Mark it once only+ // after that successful dispatch.+ notify_session_started(metadata);+ session_observed = true;+ }+ if let Some(timer) = tool_timer {+ notify_tool_completed(timer.finish(&response));+ }+ response}};@@ -57,6 +259,203 @@ pub async fn run(registry: Arc<ToolRegistry>) -> anyhow::Result<()> {Ok(())}+/// Build a completion timer from a `tools/call` request while extracting only+/// the declared tool name and validity/allowlist booleans. Tool arguments are+/// neither cloned nor retained.+pub fn tool_observation_timer(+ req: &Request,+ is_known_tool: impl FnOnce(&str) -> bool,+ path: StdioExecutionPath,+) -> Option<ToolObservationTimer> {+ if req.method != "tools/call" {+ return None;+ }+ let parsed = req.tool_call();+ let (tool_name, valid_params) = match parsed {+ Ok(call) => (bounded_tool_name(&call.name), true),+ Err(_) => {+ let name = req+ .params+ .as_ref()+ .and_then(|p| p.get("name"))+ .and_then(serde_json::Value::as_str)+ .map(bounded_tool_name)+ .unwrap_or_else(|| "unknown".to_owned());+ (name, false)+ }+ };+ let known_tool = valid_params && is_known_tool(&tool_name);+ Some(ToolObservationTimer::start(+ tool_name,+ known_tool,+ valid_params,+ path,+ ))+}++fn notify_session_started(metadata: InitializeMetadata) {+ if let Some(observer) = STDIO_OBSERVER.get() {+ observer.on_session_started(metadata);+ }+}++fn notify_tool_completed(outcome: ToolCompletionObservation) {+ if let Some(observer) = STDIO_OBSERVER.get() {+ observer.on_tool_completed(outcome);+ }+}++const MAX_TOOL_NAME_CHARS: usize = 64;++fn bounded_tool_name(name: &str) -> String {+ let value: String = name+ .chars()+ .filter(|c| c.is_ascii_alphanumeric() || *c == '_')+ .take(MAX_TOOL_NAME_CHARS)+ .collect();+ if value.is_empty() {+ "unknown".to_owned()+ } else {+ value+ }+}++fn classify_tool_completion(+ timer: ToolObservationTimer,+ response: &Response,+) -> ToolCompletionObservation {+ let elapsed_ms = timer.started.elapsed().as_millis();+ let duration_bucket = match elapsed_ms {+ 0..=9 => DurationBucket::Under10Ms,+ 10..=49 => DurationBucket::Ms10To49,+ 50..=249 => DurationBucket::Ms50To249,+ 250..=999 => DurationBucket::Ms250To999,+ 1000..=4999 => DurationBucket::Ms1000To4999,+ _ => DurationBucket::Ms5000OrMore,+ };++ let (result, rpc_error_code) = match &response.body {+ ResponseBody::Result { result } => (Some(result), None),+ ResponseBody::Error { error } => (None, Some(error.code)),+ };+ let tool_reported_error = result+ .and_then(|value| value.get("isError"))+ .and_then(serde_json::Value::as_bool)+ .unwrap_or(false);+ let success = timer.valid_params+ && timer.known_tool+ && rpc_error_code.is_none()+ && !tool_reported_error;++ let error_class = if success {+ ToolErrorClass::None+ } else if !timer.valid_params || rpc_error_code == Some(-32602) {+ ToolErrorClass::InvalidParams+ } else if !timer.known_tool {+ ToolErrorClass::UnknownTool+ } else if rpc_error_code == Some(-32603)+ && timer.path == StdioExecutionPath::DaemonProxy+ {+ ToolErrorClass::TransportError+ } else if rpc_error_code.is_some() {+ ToolErrorClass::InternalError+ } else {+ structured_error_class(result)+ };++ let output_type = classify_output_type(result);+ let output_size_bucket = result+ .and_then(serialized_size_without_retaining)+ .map(size_bucket)+ .unwrap_or(OutputSizeBucket::Empty);++ ToolCompletionObservation {+ tool_name: timer.tool_name,+ success,+ error_class,+ duration_bucket,+ output_type,+ output_size_bucket,+ }+}++fn serialized_size_without_retaining(value: &serde_json::Value) -> Option<usize> {+ struct ByteCounter(usize);+ impl std::io::Write for ByteCounter {+ fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {+ self.0 = self.0.saturating_add(bytes.len());+ Ok(bytes.len())+ }++ fn flush(&mut self) -> std::io::Result<()> {+ Ok(())+ }+ }++ let mut counter = ByteCounter(0);+ serde_json::to_writer(&mut counter, value).ok()?;+ Some(counter.0)+}++fn structured_error_class(result: Option<&serde_json::Value>) -> ToolErrorClass {+ let code = result+ .and_then(|value| value.get("structuredContent"))+ .and_then(|value| value.get("code"))+ .and_then(serde_json::Value::as_str);+ match code {+ Some("background_unavailable" | "background_occluded") => {+ ToolErrorClass::BackgroundUnavailable+ }+ Some(+ "permission_denied"+ | "accessibility_permission_denied"+ | "screen_recording_permission_denied"+ | "tcc_permission_denied",+ ) => ToolErrorClass::PermissionDenied,+ _ => ToolErrorClass::InternalError,+ }+}++fn classify_output_type(result: Option<&serde_json::Value>) -> OutputType {+ let Some(content) = result+ .and_then(|value| value.get("content"))+ .and_then(serde_json::Value::as_array)+ else {+ return OutputType::Empty;+ };+ if content.is_empty() {+ return OutputType::Empty;+ }++ let mut has_text = false;+ let mut has_image = false;+ let mut has_unknown = false;+ for item in content {+ match item.get("type").and_then(serde_json::Value::as_str) {+ Some("text") => has_text = true,+ Some("image") => has_image = true,+ _ => has_unknown = true,+ }+ }+ match (has_text, has_image, has_unknown) {+ (true, false, false) => OutputType::Text,+ (false, true, false) => OutputType::Image,+ (true, true, false) => OutputType::Mixed,+ _ => OutputType::Unknown,+ }+}++fn size_bucket(size: usize) -> OutputSizeBucket {+ match size {+ 0 => OutputSizeBucket::Empty,+ 1..=1023 => OutputSizeBucket::Under1KiB,+ 1024..=10_239 => OutputSizeBucket::KiB1To9,+ 10_240..=102_399 => OutputSizeBucket::KiB10To99,+ 102_400..=1_048_575 => OutputSizeBucket::KiB100To1023,+ _ => OutputSizeBucket::MiB1OrMore,+ }+}+/// Dispatch one MCP JSON-RPC request against the registry (initialize //// tools/list / tools/call). Shared by the stdio loop above and the/// daemon's HTTP transport (`cua-driver`'s `mcp_http`) so both speak the@@ -84,3 +483,127 @@ pub async fn handle_request(req: Request, id: serde_json::Value, registry: &Arc<}}}++#[cfg(test)]+mod observation_tests {+ use super::*;++ fn timer(known: bool, valid: bool, path: StdioExecutionPath) -> ToolObservationTimer {+ ToolObservationTimer::start("click".to_owned(), known, valid, path)+ }++ #[test]+ fn successful_mixed_output_is_shape_only() {+ let response = Response::ok(+ serde_json::json!(1),+ serde_json::json!({+ "content": [+ {"type":"text", "text":"private task text"},+ {"type":"image", "data":"private-base64", "mimeType":"image/png"}+ ],+ "isError": false,+ "structuredContent": {"private": "result body"}+ }),+ );+ let observation = timer(true, true, StdioExecutionPath::InProcess).finish(&response);+ assert!(observation.success);+ assert_eq!(observation.error_class, ToolErrorClass::None);+ assert_eq!(observation.output_type, OutputType::Mixed);+ assert_ne!(observation.output_size_bucket, OutputSizeBucket::Empty);++ let debug = format!("{observation:?}");+ for forbidden in ["private task text", "private-base64", "result body"] {+ assert!(!debug.contains(forbidden), "observer leaked content: {debug}");+ }+ }++ #[test]+ fn invalid_params_and_unknown_tool_are_distinct() {+ let invalid = Response::error(serde_json::json!(1), -32602, "private invalid params");+ let invalid_observation =+ timer(false, false, StdioExecutionPath::InProcess).finish(&invalid);+ assert!(!invalid_observation.success);+ assert_eq!(invalid_observation.error_class, ToolErrorClass::InvalidParams);+ assert_eq!(invalid_observation.output_type, OutputType::Empty);++ let unknown = Response::ok(+ serde_json::json!(2),+ serde_json::json!({+ "content": [{"type":"text", "text":"private unknown-tool error"}],+ "isError": true+ }),+ );+ let unknown_observation =+ timer(false, true, StdioExecutionPath::InProcess).finish(&unknown);+ assert_eq!(unknown_observation.error_class, ToolErrorClass::UnknownTool);+ assert!(!format!("{unknown_observation:?}").contains("private unknown-tool error"));+ }++ #[test]+ fn proxy_internal_rpc_error_is_transport_error() {+ let response = Response::error(serde_json::json!(1), -32603, "private daemon failure");+ let proxy = timer(true, true, StdioExecutionPath::DaemonProxy).finish(&response);+ let direct = timer(true, true, StdioExecutionPath::InProcess).finish(&response);+ assert_eq!(proxy.error_class, ToolErrorClass::TransportError);+ assert_eq!(direct.error_class, ToolErrorClass::InternalError);+ assert!(!format!("{proxy:?}").contains("private daemon failure"));+ }++ #[test]+ fn structured_codes_map_without_error_text() {+ for (code, expected) in [+ ("background_unavailable", ToolErrorClass::BackgroundUnavailable),+ ("permission_denied", ToolErrorClass::PermissionDenied),+ ("private_custom_error", ToolErrorClass::InternalError),+ ] {+ let response = Response::ok(+ serde_json::json!(1),+ serde_json::json!({+ "content": [{"type":"text", "text":"private prose"}],+ "isError": true,+ "structuredContent": {"code": code, "detail": "private detail"}+ }),+ );+ let observation =+ timer(true, true, StdioExecutionPath::InProcess).finish(&response);+ assert_eq!(observation.error_class, expected, "code={code}");+ let debug = format!("{observation:?}");+ assert!(!debug.contains("private prose"));+ assert!(!debug.contains("private detail"));+ assert!(!debug.contains("private_custom_error"));+ }+ }++ #[test]+ fn tool_timer_retains_no_arguments() {+ let req: Request = serde_json::from_value(serde_json::json!({+ "jsonrpc": "2.0",+ "id": 1,+ "method": "tools/call",+ "params": {+ "name": "type_text",+ "arguments": {"text":"secret typed text", "path":"/secret/path"}+ }+ }))+ .unwrap();+ let timer = tool_observation_timer(+ &req,+ |name| name == "type_text",+ StdioExecutionPath::InProcess,+ )+ .unwrap();+ assert_eq!(timer.tool_name, "type_text");+ let debug = format!("{}:{}", timer.tool_name, timer.valid_params);+ assert!(!debug.contains("secret typed text"));+ assert!(!debug.contains("/secret/path"));+ }++ #[test]+ fn observer_enum_labels_are_fixed() {+ assert_eq!(DurationBucket::Under10Ms.as_str(), "lt_10ms");+ assert_eq!(DurationBucket::Ms5000OrMore.as_str(), "gte_5000ms");+ assert_eq!(OutputType::Empty.as_str(), "empty");+ assert_eq!(OutputSizeBucket::MiB1OrMore.as_str(), "gte_1mib");+ assert_eq!(ToolErrorClass::TransportError.as_str(), "transport_error");+ }+}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs b/libs/cua-driver/rust/crates/cua-driver/src/cli.rsindex ffc9501013..2f69bdcac2 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/cli.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/cli.rs@@ -93,13 +93,8 @@ pub enum Command {value: Option<String>,socket: Option<String>,},- /// Hidden subcommand used by `scripts/install.sh` to emit the- /// one-shot `cua_driver_install` PostHog event. Bypasses the- /// opt-out flag (the only call site that does so) so we get a- /// usable adoption signal even from users who opt out immediately- /// after install. Subsequent runs see the `.installation_recorded`- /// marker file and become no-ops.- TelemetryInstallEvent,+ /// Content-free telemetry preference, inspection, and installer hooks.+ Telemetry(TelemetryCommand),/// `cua-driver autostart {enable|disable|status|kick}` —/// platform-native auto-start so `cua-driver serve` comes up on/// every logon. Windows: Scheduled Task with LogonType=Interactive@@ -134,6 +129,15 @@ pub enum Command {Skills { subcommand: String, flags: Vec<String> },}+pub enum TelemetryCommand {+ InstallEvent,+ Enable,+ Disable,+ Status { json: bool },+ ResetId,+ Inspect { event: String },+}+/// Flags whose next token is a value (not a subcommand)./// We skip both the flag and its value when scanning for the subcommand.const VALUE_FLAGS: &[&str] = &[@@ -147,6 +151,50 @@ const VALUE_FLAGS: &[&str] = &["--experimental-pip-geometry",];+/// Classify the requested finite command without parsing its arguments. The+/// parent process uses this before `parse_command` so invalid JSON and other+/// parser exits are still observed as completed failures.+pub fn finite_command_name_from_argv() -> Option<&'static str> {+ let args: Vec<String> = std::env::args().skip(1).collect();+ if args.iter().any(|arg| matches!(arg.as_str(), "--help" | "-h" | "--version" | "-V")) {+ return None;+ }+ let mut positionals = Vec::new();+ let mut index = 0;+ while index < args.len() {+ let arg = args[index].as_str();+ if VALUE_FLAGS.contains(&arg) {+ index += 2;+ } else if arg.starts_with('-') {+ index += 1;+ } else {+ positionals.push(arg);+ index += 1;+ }+ }+ match positionals.first().copied() {+ None | Some("mcp" | "serve" | "telemetry") => None,+ Some("list-tools") => Some("list_tools"),+ Some("describe") => Some("describe"),+ Some("mcp-config") => Some("mcp_config"),+ Some("manifest") => Some("manifest"),+ Some("call") => Some("call"),+ Some("stop") => Some("stop"),+ Some("status") => Some("status"),+ Some("recording") => Some("recording"),+ Some("dump-docs") => Some("dump_docs"),+ Some("update") => Some("update"),+ Some("check-update") => Some("check_update"),+ Some("doctor") => Some("doctor"),+ Some("diagnose") => Some("diagnose"),+ Some("permissions") => Some("permissions"),+ Some("autostart") => Some("autostart"),+ Some("skills") => Some("skills"),+ Some("config") => Some("config"),+ Some(_) => Some("call"),+ }+}+/// Parse the first non-flag positional argument from argv to determine which/// subcommand to run. Cursor-overlay flags are consumed by `CursorConfig`/// independently; we only care about the first non-`--` arg here.@@ -162,7 +210,7 @@ pub fn parse_command() -> Command {if args.iter().any(|a| a == "--help" || a == "-h") {println!("cua-driver {} — cross-platform computer-use automation driver", env!("CARGO_PKG_VERSION"));println!("Usage: cua-driver [SUBCOMMAND] [OPTIONS]");- println!("Subcommands: mcp, list-tools, describe, call, serve, stop, status, config, recording, update, check-update, doctor, diagnose, permissions, autostart, skills, manifest");+ println!("Subcommands: mcp, list-tools, describe, call, serve, stop, status, config, telemetry, recording, update, check-update, doctor, diagnose, permissions, autostart, skills, manifest");println!();println!("permissions options (macOS):");println!(" cua-driver permissions status Report Accessibility + Screen Recording status. Read-only (no prompt).");@@ -414,12 +462,24 @@ pub fn parse_command() -> Command {Command::Call { tool, json_args, screenshot_out_file, socket: socket.clone() }}Some("telemetry") => {- // Hidden — used by install.sh. Only supports `install-event`- // today; left extensible (e.g. future `telemetry status`).match pos.next() {- Some("install-event") => Command::TelemetryInstallEvent,+ Some("install-event") => Command::Telemetry(TelemetryCommand::InstallEvent),+ Some("enable") => Command::Telemetry(TelemetryCommand::Enable),+ Some("disable") => Command::Telemetry(TelemetryCommand::Disable),+ Some("status") => Command::Telemetry(TelemetryCommand::Status {+ json: args.iter().any(|arg| arg == "--json"),+ }),+ Some("reset-id") => Command::Telemetry(TelemetryCommand::ResetId),+ Some("inspect") => {+ let event = pos.next().unwrap_or("").to_owned();+ if event.is_empty() {+ eprintln!("Usage: cua-driver telemetry inspect <event> --json");+ process::exit(64);+ }+ Command::Telemetry(TelemetryCommand::Inspect { event })+ }_ => {- eprintln!("Usage: cua-driver telemetry install-event");+ eprintln!("Usage: cua-driver telemetry {{enable|disable|status [--json]|reset-id|inspect <event> --json}}");process::exit(64);}}@@ -954,6 +1014,13 @@ pub fn build_manifest() -> serde_json::Value {{ "name": "value", "type": "positional-string", "description": "Config value (for set)." },{ "name": "--socket", "type": "string", "description": "Override the daemon socket path." }] },+ { "name": "telemetry",+ "description": "Inspect or change content-free telemetry and its pseudonymous installation identity.",+ "args": [+ { "name": "subcommand", "type": "positional-string", "description": "enable | disable | status | reset-id | inspect" },+ { "name": "event", "type": "positional-string", "description": "Fixed event name for inspect." },+ { "name": "--json", "type": "flag", "description": "Emit machine-readable status or inspection output." }+ ] },{ "name": "autostart","description": "Platform-native auto-start so `cua-driver serve` comes up on every logon.","args": [ { "name": "subcommand", "type": "positional-string", "description": "enable | disable | status | kick" } ] },@@ -1340,7 +1407,8 @@ pub fn run_call(if let Some(err) = resp.error {eprintln!("{err}");}- process::exit(resp.exit_code.unwrap_or(1));+ let exit_code = resp.exit_code.unwrap_or(1);+ process::exit(exit_code);}}Err(e) => {@@ -2200,6 +2268,21 @@ fn cli_docs_json() -> serde_json::Value {{"name":"reset","abstract":"Reset config to defaults.","discussion":"","arguments":[],"options":[],"flags":[],"subcommands":[]}]},+ {+ "name": "telemetry",+ "abstract": "Inspect or change content-free product telemetry.",+ "discussion": "Telemetry is default-on. Disable retains the pseudonymous installation ID; reset-id erases the ID and event markers while preserving the preference.",+ "arguments": no_args,+ "options": no_options,+ "flags": no_flags,+ "subcommands": [+ {"name":"enable","abstract":"Persistently enable telemetry.","discussion":"","arguments":[],"options":[],"flags":[],"subcommands":[]},+ {"name":"disable","abstract":"Persistently disable every telemetry request.","discussion":"Retains the local installation ID.","arguments":[],"options":[],"flags":[],"subcommands":[]},+ {"name":"status","abstract":"Show the effective setting and redacted identity state.","discussion":"","arguments":[],"options":[],"flags":[{"name":"json","short_name":null,"help":"Emit JSON.","default_value":false}],"subcommands":[]},+ {"name":"reset-id","abstract":"Erase the installation ID and event markers.","discussion":"The persisted enabled/disabled preference is retained.","arguments":[],"options":[],"flags":[],"subcommands":[]},+ {"name":"inspect","abstract":"Build a fixed event payload without sending it.","discussion":"The distinct ID is replaced with a redacted placeholder.","arguments":[{"name":"event","help":"Fixed telemetry event name.","type":"String","is_optional":false}],"options":[],"flags":[{"name":"json","short_name":null,"help":"Emit JSON.","default_value":true}],"subcommands":[]}+ ]+ },{"name": "check-update","abstract": "Check whether a newer cua-driver release is available.",@@ -2860,62 +2943,6 @@ mod stdin_bom_tests {}}-/// Map a parsed [`Command`] to its canonical telemetry event name.-///-/// Mirrors Swift's `CuaDriverCommand.telemetryEntryEvent(for:)`. Per-tool-/// `call <tool>` invocations report as `cua_driver_api_<tool>` so per-tool-/// usage shows up in aggregate without our ever recording the args.-///-/// Returns `None` for [`Command::TelemetryInstallEvent`] — that path emits-/// the install event directly via [`crate::telemetry::capture_install`]-/// instead of a per-entry event.-pub fn telemetry_entry_event(cmd: &Command) -> Option<String> {- use crate::telemetry::event;- let name = match cmd {- Command::Mcp { .. } => event::MCP.to_owned(),- Command::Serve { .. } => event::SERVE.to_owned(),- Command::Stop { .. } => event::STOP.to_owned(),- Command::Status { .. } => event::STATUS.to_owned(),- Command::ListTools => event::LIST_TOOLS.to_owned(),- Command::Describe(_) => event::DESCRIBE.to_owned(),- // `call <tool>` → per-tool event (no args, just the tool name).- // The tool name flows into the PostHog event name, so we sanitize- // it aggressively (see `sanitize_tool_name`) before concatenation —- // otherwise weird / path-like / non-ASCII tool names would pollute- // dashboards and could even leak user-controlled strings into- // telemetry event names.- Command::Call { tool, .. } => {- if tool.is_empty() {- event::CALL.to_owned()- } else {- format!("{}{}", event::API_PREFIX, sanitize_tool_name(tool))- }- }- Command::McpConfig { .. } => "cua_driver_mcp_config".to_owned(),- Command::Manifest { .. } => "cua_driver_manifest".to_owned(),- Command::Recording { .. } => event::RECORDING.to_owned(),- Command::Config { .. } => event::CONFIG.to_owned(),- Command::DumpDocs { .. } => "cua_driver_dump_docs".to_owned(),- Command::Update { .. } => "cua_driver_update".to_owned(),- Command::CheckUpdate { .. } => "cua_driver_check_update".to_owned(),- Command::Doctor { .. } => "cua_driver_doctor".to_owned(),- Command::Permissions { .. } => "cua_driver_permissions".to_owned(),- Command::Diagnose => "cua_driver_diagnose".to_owned(),- // Per-subcommand event so dashboards can split enable / disable /- // status / kick separately — they have very different meanings- // for adoption. `sanitize_tool_name` already does what we want- // (lowercase ASCII / underscore-only / max 64 chars / fallback).- Command::Autostart { subcommand } => {- format!("cua_driver_autostart_{}", sanitize_tool_name(subcommand))- }- Command::Skills { subcommand, .. } => {- format!("cua_driver_skills_{}", sanitize_tool_name(subcommand))- }- Command::TelemetryInstallEvent => return None,- };- Some(name)-}-/// Normalise a user-provided tool name into a safe PostHog event suffix.////// Tool names are concatenated onto `cua_driver_api_` to build per-tool@@ -2928,6 +2955,7 @@ pub fn telemetry_entry_event(cmd: &Command) -> Option<String> {/// 4. Fall back to `"unknown"` when the result is empty (e.g. all non-ASCII/// input), so we still record *that* a call happened without inventing/// a per-payload event name.+#[cfg(test)]fn sanitize_tool_name(name: &str) -> String {const MAX_LEN: usize = 64;const FALLBACK: &str = "unknown";diff --git a/libs/cua-driver/rust/crates/cua-driver/src/doctor.rs b/libs/cua-driver/rust/crates/cua-driver/src/doctor.rsindex a0f0c58aba..e1ef4e9bfe 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/doctor.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/doctor.rs@@ -212,25 +212,14 @@ fn probe_home_dir() -> Probe {)}-/// Probe: telemetry state — env-var opt-out + install-id file presence.-/// Reports without reading the UUID itself (privacy-preserving — only-/// presence, not value).+/// Probe the same effective persisted/environment state as `telemetry status`.fn probe_telemetry() -> Probe {- let env_disabled = std::env::var("CUA_DRIVER_RS_TELEMETRY_ENABLED")- .ok()- .map(|v| matches!(v.to_ascii_lowercase().as_str(), "0" | "false" | "no" | "off"))- .unwrap_or(false);- let install_id_present = home_dir()- .map(|h| h.join(".cua-driver").join(".telemetry_id").exists())- .unwrap_or(false);- if env_disabled {- Probe::ok(- "telemetry",- "disabled via CUA_DRIVER_RS_TELEMETRY_ENABLED",- )+ let status = crate::telemetry::status();+ if status.enabled {+ let identity = if status.installation_id_present { "install-id present" } else { "install-id not yet generated" };+ Probe::ok("telemetry", format!("enabled via {} ({identity})", status.source))} else {- let id_state = if install_id_present { "install-id present" } else { "install-id not yet generated" };- Probe::ok("telemetry", format!("enabled ({id_state})"))+ Probe::ok("telemetry", format!("disabled via {} (installation ID retained)", status.source))}}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/main.rs b/libs/cua-driver/rust/crates/cua-driver/src/main.rsindex 8c727cd327..564cc54ecd 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/main.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/main.rs@@ -58,20 +58,89 @@ fn init_logging() {.add_directive(tracing::Level::WARN.into()),).init();+ telemetry::register_stdio_observer();}-/// Fire the per-entry-point telemetry event (e.g. `cua_driver_mcp`,-/// `cua_driver_api_click`). Respects the opt-out env var — no-op when-/// telemetry is disabled. Always returns immediately: the actual POST-/// happens on a background thread or tokio task.-///-/// Mirrors Swift's `TelemetryClient.shared.record(event:)` call at the-/// top of `CuaDriverCommand.main()`. The install ping is *not* emitted-/// here — that's the dedicated `telemetry install-event` subcommand-/// fired exactly once by the post-install script.+/// Keep entry events only for long-running process starts. Supported finite+/// command paths emit a bounded event only after their outcome is known.fn emit_entry_telemetry(command: &cli::Command) {- if let Some(event_name) = cli::telemetry_entry_event(command) {- telemetry::capture(&event_name, None);+ match command {+ cli::Command::Mcp { .. } => telemetry::capture_start(+ telemetry::event::MCP_START_LEGACY,+ telemetry::Transport::McpStdio,+ ),+ cli::Command::Serve { .. } => telemetry::capture_start(+ telemetry::event::SERVE_START_LEGACY,+ telemetry::Transport::Cli,+ ),+ _ => {}+ }+}++/// Execute finite commands in a child so the parent can observe every exit,+/// including validation failures and legacy `process::exit` paths. Delivery is+/// delegated to a detached, no-output worker after the child exits, so network+/// latency is never added to the foreground command.+fn maybe_wrap_finite_command() {+ if telemetry::is_wrapped_cli_child() {+ return;+ }+ let Some(command_name) = cli::finite_command_name_from_argv() else { return; };+ telemetry::spawn_first_run_registration_worker();+ let Ok(executable) = std::env::current_exe() else { return; };+ let started_at = std::time::Instant::now();+ let status = std::process::Command::new(executable)+ .args(std::env::args_os().skip(1))+ .env(telemetry::cli_wrapped_child_env(), "1")+ .status();+ let Ok(status) = status else { return; };+ let exit_code = status.code().unwrap_or(1);+ telemetry::spawn_cli_completion_worker(command_name, exit_code, started_at.elapsed());+ std::process::exit(exit_code);+}++fn run_telemetry_command(command: cli::TelemetryCommand) {+ match command {+ cli::TelemetryCommand::InstallEvent => telemetry::capture_install(),+ cli::TelemetryCommand::Enable => match telemetry::set_enabled(true) {+ Ok(()) => println!("Telemetry enabled. The retained installation ID will be reused."),+ Err(error) => {+ eprintln!("cua-driver: failed to enable telemetry: {error}");+ std::process::exit(1);+ }+ },+ cli::TelemetryCommand::Disable => match telemetry::set_enabled(false) {+ Ok(()) => println!("Telemetry disabled. The local installation ID was retained; run `cua-driver telemetry reset-id` to erase it."),+ Err(error) => {+ eprintln!("cua-driver: failed to disable telemetry: {error}");+ std::process::exit(1);+ }+ },+ cli::TelemetryCommand::Status { json } => {+ let status = telemetry::status();+ if json {+ println!("{}", serde_json::to_string_pretty(&status).expect("serialize telemetry status"));+ } else {+ println!("Telemetry: {} (source: {})", if status.enabled { "enabled" } else { "disabled" }, status.source);+ println!("Installation ID: {}", status.installation_id.as_deref().unwrap_or("not created"));+ println!("Registration recorded: {}", status.registration_recorded);+ println!("Current release recorded: {}", status.current_release_recorded);+ }+ }+ cli::TelemetryCommand::ResetId => match telemetry::reset_id() {+ Ok(()) => println!("Telemetry installation ID and event markers erased. The enable/disable preference was retained."),+ Err(error) => {+ eprintln!("cua-driver: failed to reset telemetry ID: {error}");+ std::process::exit(1);+ }+ },+ cli::TelemetryCommand::Inspect { event } => match telemetry::inspect_event(&event) {+ Ok(payload) => println!("{}", serde_json::to_string_pretty(&payload).expect("serialize telemetry payload")),+ Err(error) => {+ eprintln!("cua-driver: {error}");+ std::process::exit(64);+ }+ },}}@@ -167,20 +236,25 @@ fn build_macos_registry_with_compat(compat: bool) -> cua_driver_core::tool::Tool#[cfg(target_os = "macos")]fn main() {init_logging();+ if telemetry::run_cli_completion_worker_if_requested() {+ return;+ }+ if telemetry::run_lifecycle_worker_if_requested() {+ return;+ }+ maybe_wrap_finite_command();// ── CLI subcommand dispatch ──────────────────────────────────────────────// Handled before AppKit init so `list-tools` / `describe` / `call` exit// cleanly without starting the overlay or NSApplication.let command = cli::parse_command();+ if !telemetry::is_wrapped_cli_child() && !matches!(&command, cli::Command::Telemetry(_)) {+ telemetry::spawn_first_run_registration_worker();+ }emit_entry_telemetry(&command);match command {- cli::Command::TelemetryInstallEvent => {- // Synchronous install ping (see `telemetry::capture_install`).- // Blocks on the POST so the `.installation_recorded` marker- // is only written on HTTP success — failed POST means next- // launch retries. Installer script already runs us in the- // background via `&`, so blocking here is fine.- telemetry::capture_install();+ cli::Command::Telemetry(command) => {+ run_telemetry_command(command);return;}cli::Command::ListTools => {@@ -441,8 +515,10 @@ fn main() {if cli::should_use_daemon_proxy(no_daemon_relaunch) {if let Err(e) = cli::run_mcp_via_daemon_proxy(socket, claude_code_compat) {eprintln!("cua-driver-rs: {e}");+ telemetry::flush_pending(std::time::Duration::from_millis(750));std::process::exit(1);}+ telemetry::flush_pending(std::time::Duration::from_millis(750));return;}// Fall through to the in-process MCP server below. The@@ -520,6 +596,7 @@ fn main() {// MCP server exited (stdin closed / client disconnected).// The main thread is blocked in NSApplication.run() and won't// exit on its own — force-exit the process cleanly.+ telemetry::flush_pending(std::time::Duration::from_millis(750));std::process::exit(0);}).expect("spawn mcp thread");@@ -538,21 +615,26 @@ fn main() {#[cfg(not(target_os = "macos"))]fn main() -> anyhow::Result<()> {init_logging();+ if telemetry::run_cli_completion_worker_if_requested() {+ return Ok(());+ }+ if telemetry::run_lifecycle_worker_if_requested() {+ return Ok(());+ }+ maybe_wrap_finite_command();// ── CLI subcommand dispatch ──────────────────────────────────────────────// These commands create their own tokio runtimes internally, so they must// run on a plain OS thread — not inside a #[tokio::main] context which// would cause nested block_on panics.let command = cli::parse_command();+ if !telemetry::is_wrapped_cli_child() && !matches!(&command, cli::Command::Telemetry(_)) {+ telemetry::spawn_first_run_registration_worker();+ }emit_entry_telemetry(&command);match command {- cli::Command::TelemetryInstallEvent => {- // Synchronous install ping (see `telemetry::capture_install`).- // Blocks on the POST so the `.installation_recorded` marker- // is only written on HTTP success — failed POST means next- // launch retries. Installer script already runs us in the- // background via `&`, so blocking here is fine.- telemetry::capture_install();+ cli::Command::Telemetry(command) => {+ run_telemetry_command(command);return Ok(());}cli::Command::ListTools => {@@ -691,8 +773,10 @@ fn main() -> anyhow::Result<()> {if cli::should_use_daemon_proxy(no_daemon_relaunch) {if let Err(e) = cli::run_mcp_via_daemon_proxy(socket, claude_code_compat) {eprintln!("cua-driver-rs: {e}");+ telemetry::flush_pending(std::time::Duration::from_millis(750));std::process::exit(1);}+ telemetry::flush_pending(std::time::Duration::from_millis(750));return Ok(());}// Fall through to the in-process MCP server below. The@@ -743,6 +827,7 @@ async fn async_main() -> anyhow::Result<()> {// CPU after the client is gone (issue #1808). Force a clean process exit so// the overlay thread dies with us the moment the transport closes — mirrors// the macOS `std::process::exit(0)` after `server::run`.+ telemetry::flush_pending(std::time::Duration::from_millis(750));std::process::exit(if result.is_ok() { 0 } else { 1 });}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rsindex 97cc8baf75..313e3c1a32 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/proxy.rs@@ -26,6 +26,10 @@use std::sync::Arc;use cua_driver_core::protocol::{initialize_result, Request, Response};+use cua_driver_core::server::{+ observe_proxy_session_started, observe_proxy_tool_completed, tool_observation_timer,+ StdioExecutionPath,+};use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};use tracing::{debug, error, warn};@@ -101,6 +105,7 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {let mut reader = BufReader::new(stdin);let mut writer = tokio::io::BufWriter::new(stdout);let mut line = String::new();+ let mut session_observed = false;loop {line.clear();@@ -124,8 +129,26 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {continue;}Ok(req) => {+ let initialize_metadata = (!session_observed)+ .then(|| req.initialize_metadata())+ .flatten();+ let tool_timer = tool_observation_timer(+ &req,+ |name| proxy_knows_tool(&cached_tools_list, name),+ StdioExecutionPath::DaemonProxy,+ );let id = req.id.clone().unwrap_or(serde_json::Value::Null);- handle_proxy_request(req, id, &socket_path, &cached_tools_list, &session_id).await+ let response =+ handle_proxy_request(req, id, &socket_path, &cached_tools_list, &session_id)+ .await;+ if let Some(metadata) = initialize_metadata {+ observe_proxy_session_started(metadata);+ session_observed = true;+ }+ if let Some(timer) = tool_timer {+ observe_proxy_tool_completed(timer.finish(&response));+ }+ response}};@@ -152,6 +175,20 @@ pub async fn run_proxy(socket_path: String) -> anyhow::Result<()> {Ok(())}+fn proxy_knows_tool(cached_tools_list: &serde_json::Value, name: &str) -> bool {+ if name == "type_text_chars" {+ return true;+ }+ cached_tools_list+ .get("tools")+ .and_then(serde_json::Value::as_array)+ .is_some_and(|tools| {+ tools.iter().any(|tool| {+ tool.get("name").and_then(serde_json::Value::as_str) == Some(name)+ })+ })+}+/// Own the proxy's single long-lived control connection. Connects directly to/// the daemon socket (its OWN async open — `send_request` is sync, blocking,/// and one-shot, so it cannot be reused here), sends one `session_begin` line@@ -585,4 +622,18 @@ mod tests {assert_eq!(value["result"]["content"][0]["text"], "daemon reported failure");assert_eq!(value["result"]["structuredContent"]["exit_code"], 1);}++ #[test]+ fn cached_proxy_tool_allowlist_is_exact() {+ let cached = serde_json::json!({+ "tools": [+ {"name":"click"},+ {"name":"type_text"}+ ]+ });+ assert!(proxy_knows_tool(&cached, "click"));+ assert!(proxy_knows_tool(&cached, "type_text_chars"), "deprecated alias stays bounded/known");+ assert!(!proxy_knows_tool(&cached, "click/private-user-value"));+ assert!(!proxy_knows_tool(&cached, ""));+ }}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rsindex 1749679390..73deac9a4a 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/telemetry.rs@@ -1,419 +1,1166 @@-//! Anonymous usage-tracking client — a Rust port of the Swift-//! `TelemetryClient` (`libs/cua-driver/Sources/CuaDriverCore/Telemetry/-//! TelemetryClient.swift`).+//! Content-free product telemetry for Cua Driver.//!-//! Same PostHog HTTP-capture pattern, per-install UUID, env-override-//! support, and installation-record-once behavior as the Swift reference.+//! Routine telemetry is enabled by default, with precedence+//! `environment override -> persisted preference -> enabled`. Disabling+//! telemetry stops every request while retaining the local installation ID.+//! Normal uninstall also retains telemetry state; `telemetry reset-id` and+//! `uninstall --purge` are the explicit identity-erasure paths.//!-//! ## Differences from Swift-//!-//! - **Install ID path** is `~/.cua-driver/.telemetry_id` (matches the-//! v0.2.14+ install layout). Swift driver uses the same path. Deliberately-//! who opts out of one binary still gets a fresh distinct_id on the other.-//! - **Opt-out env var** is `CUA_DRIVER_RS_TELEMETRY_ENABLED=false` (Swift-//! uses `CUA_DRIVER_TELEMETRY_ENABLED`). Same reason — opting out of one-//! port must not silence the other.-//! - **`$lib`** is reported as `cua-driver-rs` so dashboards can split-//! Rust vs Swift adoption per-event without inspecting `os`/`arch`.-//! - **No persisted config flag.** Swift falls back to a YAML-//! `telemetryEnabled` setting; Rust honours only the env var (telemetry-//! defaults to enabled, env-var opt-out). Matches Rust's existing-//! config surface — there's no `ConfigStore.loadSync()` analogue yet,-//! and YAGNI suggests waiting until someone actually requests it.-//!-//! ## Privacy posture (identical to Swift)-//!-//! We send: driver version, OS name, OS version, CPU arch, CI-environment-//! flag, and a stable per-install UUID. We do **NOT** send: usernames,-//! file paths, command arguments, tool args, or anything user-typed.--use std::path::PathBuf;-use std::sync::OnceLock;+//! Event builders in this module accept only fixed event names and bounded+//! properties. They never receive prompts, tool arguments/results, typed text,+//! screenshots, accessibility trees, application/window names, URLs, paths,+//! or raw errors.++use serde::Serialize;+use serde_json::{Map, Value};+use std::fs::{File, OpenOptions, TryLockError};+use std::io::Write;+use std::path::{Path, PathBuf};+use std::process::Stdio;+use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};+use std::sync::{Arc, Condvar, Mutex, OnceLock};+use std::time::Duration;-// ── Constants ────────────────────────────────────────────────────────────--/// PostHog ingest endpoint (EU region — matches Swift exactly so dashboards-/// aggregate Rust + Swift events cleanly).const POSTHOG_CAPTURE_URL: &str = "https://eu.i.posthog.com/capture/";--/// Public PostHog project key. Public by design — keys can only ingest-/// events, not read them. Matches Swift `TelemetryClient.Constants.apiKey`.const POSTHOG_API_KEY: &str = "phc_eSkLnbLxsnYFaXksif1ksbrNzYlJShr35miFLDppF14";+const POSTHOG_TIMEOUT_SECS: u64 = 3;+const LIFECYCLE_RETRY_BACKOFF_SECS: u64 = 15 * 60;-/// `~/.cua-driver/` subdirectory. Renamed from `.cua-driver-rs/` in v0.2.16-/// to match the install path rename (PR #1644). The Swift driver uses the-/// same path — telemetry files are namespaced by filename, not directory.-///-/// One-time migration: if `~/.cua-driver-rs/.telemetry_id` exists but the-/// new `~/.cua-driver/.telemetry_id` doesn't, the legacy file is moved to-/// the new location (preserving the per-install UUID so analytics continuity-/// survives the rename). See `migrate_legacy_telemetry_home` below.const HOME_SUBDIRECTORY: &str = ".cua-driver";const LEGACY_HOME_SUBDIRECTORY: &str = ".cua-driver-rs";--/// Filename inside the home subdirectory holding the per-install UUID.+const CONFIG_FILE_NAME: &str = "config.json";+const CONFIG_ENABLED_KEY: &str = "telemetry_enabled";const TELEMETRY_ID_FILE_NAME: &str = ".telemetry_id";--/// Marker file written after the install event has been recorded once.+const TELEMETRY_IDENTITY_LOCK_FILE_NAME: &str = ".telemetry_identity.lock";+const TELEMETRY_LIFECYCLE_LOCK_FILE_NAME: &str = ".telemetry_lifecycle.lock";+const TELEMETRY_RETRY_AFTER_FILE_NAME: &str = ".telemetry_retry_after";+const TELEMETRY_INSTALL_CHANNEL_FILE_NAME: &str = ".telemetry_install_channel";const INSTALLATION_RECORDED_FILE_NAME: &str = ".installation_recorded";+const RELEASE_RECORDED_DIRECTORY: &str = ".release_installed";-/// Env var disabling telemetry. Accepts `0|false|no|off` to disable,-/// `1|true|yes|on` to enable. Default: enabled (matches Swift).-const ENV_TELEMETRY_ENABLED: &str = "CUA_DRIVER_RS_TELEMETRY_ENABLED";--/// Env var enabling debug logging to stderr (mirrors Swift-/// `CUA_DRIVER_TELEMETRY_DEBUG`).+pub const ENV_TELEMETRY_ENABLED: &str = "CUA_DRIVER_RS_TELEMETRY_ENABLED";+const ENV_TELEMETRY_ENABLED_COMPAT: &str = "CUA_TELEMETRY_ENABLED";const ENV_TELEMETRY_DEBUG: &str = "CUA_DRIVER_RS_TELEMETRY_DEBUG";+const ENV_TELEMETRY_HOME: &str = "CUA_DRIVER_TELEMETRY_HOME";+const ENV_CLI_WRAPPED_CHILD: &str = "CUA_DRIVER_CLI_TELEMETRY_CHILD";+const ENV_CLI_COMPLETION_WORKER: &str = "CUA_DRIVER_CLI_TELEMETRY_WORKER";+const ENV_CLI_COMPLETION_COMMAND: &str = "CUA_DRIVER_CLI_TELEMETRY_COMMAND";+const ENV_CLI_COMPLETION_EXIT_CODE: &str = "CUA_DRIVER_CLI_TELEMETRY_EXIT_CODE";+const ENV_CLI_COMPLETION_DURATION_MS: &str = "CUA_DRIVER_CLI_TELEMETRY_DURATION_MS";+const ENV_LIFECYCLE_WORKER: &str = "CUA_DRIVER_LIFECYCLE_TELEMETRY_WORKER";+pub const ENV_INSTALL_CHANNEL: &str = "CUA_DRIVER_INSTALL_CHANNEL";+pub const ENV_RELEASE_VERSION: &str = "CUA_DRIVER_RELEASE_VERSION";-/// Fire-and-forget POST timeout. PostHog ingest must never delay a CLI call.-const POSTHOG_TIMEOUT_SECS: u64 = 3;+pub mod event {+ pub const INSTALLATION_REGISTERED: &str = "cua_driver_installation_registered";+ pub const RELEASE_INSTALLED: &str = "cua_driver_release_installed";+ pub const MCP_START_LEGACY: &str = "cua_driver_mcp";+ pub const SERVE_START_LEGACY: &str = "cua_driver_serve";+ pub const CLI_COMPLETED: &str = "cua_driver_cli_completed";+ pub const MCP_SESSION_STARTED: &str = "cua_driver_mcp_session_started";+ pub const MCP_TOOL_COMPLETED: &str = "cua_driver_mcp_tool_completed";+}-// ── Canonical event names ────────────────────────────────────────────────+const INSPECTABLE_EVENTS: &[&str] = &[+ event::INSTALLATION_REGISTERED,+ event::RELEASE_INSTALLED,+ event::MCP_START_LEGACY,+ event::SERVE_START_LEGACY,+ event::CLI_COMPLETED,+ event::MCP_SESSION_STARTED,+ event::MCP_TOOL_COMPLETED,+];++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+#[allow(dead_code)] // HTTP is intentionally deferred until session semantics are defined.+pub enum Transport {+ Cli,+ McpStdio,+ McpHttp,+ Unknown,+}++impl Transport {+ fn as_str(self) -> &'static str {+ match self {+ Self::Cli => "cli",+ Self::McpStdio => "mcp_stdio",+ Self::McpHttp => "mcp_http",+ Self::Unknown => "unknown",+ }+ }+}++#[derive(Clone, Debug)]+struct InstallationIdentity {+ id: String,+ persisted: bool,+}++#[derive(Clone, Debug, Serialize)]+pub struct TelemetryStatus {+ pub enabled: bool,+ pub source: &'static str,+ pub installation_id_present: bool,+ pub installation_id: Option<String>,+ pub registration_recorded: bool,+ pub current_release_recorded: bool,+}-/// Event names, mirrored 1:1 from Swift `TelemetryEvent`. Keeping the-/// exact strings is load-bearing for dashboards (Rust + Swift aggregate-/// under the same event name).-pub mod event {- /// One-time install ping. Sent regardless of opt-out (see- /// `capture_install`); all other events respect the env flag.- pub const INSTALL: &str = "cua_driver_install";-- // CLI entry points- pub const MCP: &str = "cua_driver_mcp";- pub const SERVE: &str = "cua_driver_serve";- pub const STOP: &str = "cua_driver_stop";- pub const STATUS: &str = "cua_driver_status";- pub const CALL: &str = "cua_driver_call";- pub const LIST_TOOLS: &str = "cua_driver_list_tools";- pub const DESCRIBE: &str = "cua_driver_describe";- pub const RECORDING: &str = "cua_driver_recording";- pub const CONFIG: &str = "cua_driver_config";- /// Bare-launch (no args) event — Swift uses it from- /// `runFirstLaunchGUI`. Rust has no GUI surface yet but ships the- /// constant for future parity.- #[allow(dead_code)]- pub const GUI_LAUNCH: &str = "cua_driver_gui_launch";-- /// Prefix for per-MCP-tool events. `API_PREFIX + tool_name` produces- /// e.g. `cua_driver_api_click`.- pub const API_PREFIX: &str = "cua_driver_api_";-}--// ── Public API ───────────────────────────────────────────────────────────--/// Whether telemetry is enabled in this process. Env var is the only-/// signal in the Rust port (no persisted config flag — see module docs).-///-/// Defaults to **enabled** when the env var is unset (matches Swift, which-/// defaults `telemetryEnabled` to `true` in its config).pub fn is_enabled() -> bool {- parse_env_bool(ENV_TELEMETRY_ENABLED).unwrap_or(true)-}--/// Record a telemetry event. No-op when telemetry is disabled.-///-/// Fire-and-forget: the HTTP POST runs on a `tokio::spawn`-ed background-/// task with a short timeout. The caller never blocks and never sees an-/// error from telemetry — only `tracing::debug!` on failure.-///-/// `properties` is merged on top of the default envelope (version / OS /-/// arch / etc.). Pass `None` for the common case.-pub fn capture(event_name: &str, properties: Option<serde_json::Value>) {- if !is_enabled() {+ effective_enabled().0+}++fn effective_enabled() -> (bool, &'static str) {+ if let Some(value) = parse_env_bool(ENV_TELEMETRY_ENABLED) {+ return (value, "environment");+ }+ if let Some(value) = parse_env_bool(ENV_TELEMETRY_ENABLED_COMPAT) {+ return (value, "environment_compat");+ }+ if let Some(value) = persisted_enabled() {+ return (value, "persisted");+ }+ (true, "default")+}++pub fn status() -> TelemetryStatus {+ let (enabled, source) = effective_enabled();+ let id = read_install_id();+ TelemetryStatus {+ enabled,+ source,+ installation_id_present: id.is_some(),+ installation_id: id.as_deref().map(redact_id),+ registration_recorded: marker_path(INSTALLATION_RECORDED_FILE_NAME)+ .is_some_and(|path| path.exists()),+ current_release_recorded: release_marker_path(current_product_version())+ .is_some_and(|path| path.exists()),+ }+}++pub fn set_enabled(enabled: bool) -> Result<(), String> {+ let path = config_path().ok_or_else(|| "home directory is unavailable".to_owned())?;+ let mut config = read_config();+ let object = config+ .as_object_mut()+ .ok_or_else(|| "telemetry config is not a JSON object".to_owned())?;+ object.insert(CONFIG_ENABLED_KEY.to_owned(), Value::Bool(enabled));+ write_json_atomic(&path, &config)+}++pub fn reset_id() -> Result<(), String> {+ let Some(home) = telemetry_home_dir() else {+ return Ok(());+ };+ let legacy = if std::env::var_os(ENV_TELEMETRY_HOME).is_none() {+ home_root().map(|root| root.join(LEGACY_HOME_SUBDIRECTORY))+ } else {+ None+ };+ reset_id_in_homes(&home, legacy.as_deref())+}++fn reset_id_in_homes(home: &Path, legacy: Option<&Path>) -> Result<(), String> {+ let lifecycle_lock = open_lock_file(&home, TELEMETRY_LIFECYCLE_LOCK_FILE_NAME)?;+ lifecycle_lock+ .lock()+ .map_err(|error| format!("failed to lock telemetry lifecycle: {error}"))?;+ let identity_lock = open_lock_file(&home, TELEMETRY_IDENTITY_LOCK_FILE_NAME)?;+ identity_lock+ .lock()+ .map_err(|error| format!("failed to lock telemetry identity: {error}"))?;+ remove_file_if_exists(&home.join(TELEMETRY_ID_FILE_NAME))?;+ remove_file_if_exists(&home.join(INSTALLATION_RECORDED_FILE_NAME))?;+ remove_file_if_exists(&home.join(TELEMETRY_RETRY_AFTER_FILE_NAME))?;+ remove_file_if_exists(&home.join(TELEMETRY_INSTALL_CHANNEL_FILE_NAME))?;+ let releases = home.join(RELEASE_RECORDED_DIRECTORY);+ if releases.exists() {+ std::fs::remove_dir_all(&releases)+ .map_err(|error| format!("failed to remove {}: {error}", releases.display()))?;+ }+ if let Some(legacy) = legacy {+ remove_file_if_exists(&legacy.join(TELEMETRY_ID_FILE_NAME))?;+ remove_file_if_exists(&legacy.join(INSTALLATION_RECORDED_FILE_NAME))?;+ remove_file_if_exists(&legacy.join(TELEMETRY_RETRY_AFTER_FILE_NAME))?;+ remove_file_if_exists(&legacy.join(TELEMETRY_INSTALL_CHANNEL_FILE_NAME))?;+ let legacy_releases = legacy.join(RELEASE_RECORDED_DIRECTORY);+ if legacy_releases.exists() {+ std::fs::remove_dir_all(&legacy_releases)+ .map_err(|error| format!("failed to remove {}: {error}", legacy_releases.display()))?;+ }+ }+ Ok(())+}++pub fn inspect_event(event_name: &str) -> Result<Value, String> {+ if !INSPECTABLE_EVENTS.contains(&event_name) {+ return Err(format!(+ "unknown telemetry event; expected one of: {}",+ INSPECTABLE_EVENTS.join(", ")+ ));+ }+ let identity = InstallationIdentity {+ id: "redacted-installation-id".to_owned(),+ persisted: read_install_id().is_some(),+ };+ let properties = match event_name {+ event::INSTALLATION_REGISTERED | event::RELEASE_INSTALLED => {+ lifecycle_properties(install_channel())+ }+ event::CLI_COMPLETED => bounded_properties(&[+ ("command", Value::String("other".into())),+ ("success", Value::Bool(true)),+ ("exit_class", Value::String("success".into())),+ ("duration_bucket", Value::String("lt_100ms".into())),+ ]),+ event::MCP_SESSION_STARTED => bounded_properties(&[+ ("mcp_client", Value::String("unknown".into())),+ ("mcp_client_version_major", Value::String("unknown".into())),+ ("protocol_version", Value::String("unknown".into())),+ ("capability_tools", Value::Bool(false)),+ ("capability_roots", Value::Bool(false)),+ ("capability_sampling", Value::Bool(false)),+ ("capability_experimental", Value::Bool(false)),+ ("capability_elicitation_form", Value::Bool(false)),+ ("capability_elicitation_url", Value::Bool(false)),+ ("reported_provider", Value::String("unknown".into())),+ ("reported_model", Value::String("unknown".into())),+ ("reported_agent", Value::String("unknown".into())),+ ("reported_agent_version_major", Value::String("unknown".into())),+ ]),+ event::MCP_TOOL_COMPLETED => bounded_properties(&[+ ("tool_name", Value::String("other".into())),+ ("success", Value::Bool(true)),+ ("error_class", Value::String("none".into())),+ ("duration_bucket", Value::String("lt_10ms".into())),+ ("output_type", Value::String("empty".into())),+ ("output_size_bucket", Value::String("0".into())),+ ]),+ _ => Map::new(),+ };+ let transport = match event_name {+ event::MCP_START_LEGACY | event::MCP_SESSION_STARTED | event::MCP_TOOL_COMPLETED => Transport::McpStdio,+ _ => Transport::Cli,+ };+ Ok(build_payload(event_name, &properties, &identity, transport))+}++/// Transitional fixed start events for long-running processes only.+pub fn capture_start(event_name: &'static str, transport: Transport) {+ if !matches!(event_name, event::MCP_START_LEGACY | event::SERVE_START_LEGACY) {+ return;+ }+ capture_bounded(event_name, Map::new(), transport);+}++pub fn register_stdio_observer() {+ let _ = cua_driver_core::server::set_stdio_observer(Arc::new(TelemetryObserver));+}++struct TelemetryObserver;++impl cua_driver_core::server::StdioObserver for TelemetryObserver {+ fn on_session_started(&self, metadata: cua_driver_core::protocol::InitializeMetadata) {+ static OBSERVED: AtomicBool = AtomicBool::new(false);+ if OBSERVED.swap(true, Ordering::SeqCst) {+ return;+ }+ let context = metadata.reported_agent_context.unwrap_or_default();+ let capabilities = metadata.capability_flags;+ capture_bounded(+ event::MCP_SESSION_STARTED,+ bounded_properties(&[+ ("mcp_client", Value::String(normalize_client(metadata.client_name.as_deref()))),+ ("mcp_client_version_major", Value::String(version_major(metadata.client_version.as_deref()))),+ ("protocol_version", Value::String(normalize_protocol(metadata.protocol_version.as_deref()))),+ ("capability_tools", Value::Bool(capabilities.tools)),+ ("capability_roots", Value::Bool(capabilities.roots)),+ ("capability_sampling", Value::Bool(capabilities.sampling)),+ ("capability_experimental", Value::Bool(capabilities.experimental)),+ ("capability_elicitation_form", Value::Bool(capabilities.elicitation_form)),+ ("capability_elicitation_url", Value::Bool(capabilities.elicitation_url)),+ ("reported_provider", Value::String(normalize_provider(context.provider.as_deref()))),+ ("reported_model", Value::String(normalize_model(context.model.as_deref()))),+ ("reported_agent", Value::String(normalize_client(context.agent_name.as_deref()))),+ ("reported_agent_version_major", Value::String(version_major(context.agent_version.as_deref()))),+ ]),+ Transport::McpStdio,+ );+ }++ fn on_tool_completed(&self, outcome: cua_driver_core::server::ToolCompletionObservation) {+ use cua_driver_core::server::{DurationBucket, OutputSizeBucket, OutputType, ToolErrorClass};+ let tool_name = if matches!(outcome.error_class, ToolErrorClass::UnknownTool | ToolErrorClass::InvalidParams) {+ "other".to_owned()+ } else if outcome.tool_name == "type_text_chars" {+ "type_text".to_owned()+ } else {+ outcome.tool_name+ };+ let error_class = match outcome.error_class {+ ToolErrorClass::None => "none",+ ToolErrorClass::InvalidParams => "invalid_params",+ ToolErrorClass::UnknownTool => "unknown_tool",+ ToolErrorClass::PermissionDenied => "permission_denied",+ ToolErrorClass::BackgroundUnavailable => "background_unavailable",+ ToolErrorClass::TransportError => "transport_error",+ ToolErrorClass::InternalError => "internal_error",+ };+ let duration_bucket = match outcome.duration_bucket {+ DurationBucket::Under10Ms => "lt_10ms",+ DurationBucket::Ms10To49 => "10_49ms",+ DurationBucket::Ms50To249 => "50_249ms",+ DurationBucket::Ms250To999 => "250_999ms",+ DurationBucket::Ms1000To4999 => "1_4s",+ DurationBucket::Ms5000OrMore => "gte_5s",+ };+ let output_type = match outcome.output_type {+ OutputType::Empty => "empty",+ OutputType::Text => "text",+ OutputType::Image => "image",+ OutputType::Mixed => "mixed",+ OutputType::Unknown => "unknown",+ };+ let output_size_bucket = match outcome.output_size_bucket {+ OutputSizeBucket::Empty => "0",+ OutputSizeBucket::Under1KiB => "lt_1kib",+ OutputSizeBucket::KiB1To9 => "1_9kib",+ OutputSizeBucket::KiB10To99 => "10_99kib",+ OutputSizeBucket::KiB100To1023 => "100_1023kib",+ OutputSizeBucket::MiB1OrMore => "gte_1mib",+ };+ capture_bounded(+ event::MCP_TOOL_COMPLETED,+ bounded_properties(&[+ ("tool_name", Value::String(tool_name)),+ ("success", Value::Bool(outcome.success)),+ ("error_class", Value::String(error_class.into())),+ ("duration_bucket", Value::String(duration_bucket.into())),+ ("output_type", Value::String(output_type.into())),+ ("output_size_bucket", Value::String(output_size_bucket.into())),+ ]),+ Transport::McpStdio,+ );+ }+}++fn normalize_client(value: Option<&str>) -> String {+ let normalized = value.unwrap_or("").trim().to_ascii_lowercase();+ for (needle, canonical) in [+ ("claude", "claude_code"), ("codex", "codex"), ("cursor", "cursor"),+ ("windsurf", "windsurf"), ("vscode", "vscode"), ("visual studio code", "vscode"),+ ("zed", "zed"), ("openclaw", "openclaw"), ("opencode", "opencode"),+ ("hermes", "hermes"),+ ] {+ if normalized.contains(needle) { return canonical.into(); }+ }+ if normalized == "pi" || normalized.starts_with("pi/") || normalized.starts_with("pi ") {+ return "pi".into();+ }+ if normalized.is_empty() { "unknown".into() } else { "other".into() }+}++fn normalize_provider(value: Option<&str>) -> String {+ match value.unwrap_or("").trim().to_ascii_lowercase().as_str() {+ "anthropic" => "anthropic".into(),+ "openai" => "openai".into(),+ "google" | "google-ai" | "google_vertex" => "google".into(),+ "xai" | "x.ai" => "xai".into(),+ "amazon" | "aws" | "bedrock" => "amazon".into(),+ "microsoft" | "azure" | "azure-openai" => "microsoft".into(),+ "" => "unknown".into(),+ _ => "custom".into(),+ }+}++fn normalize_model(value: Option<&str>) -> String {+ let raw = value.unwrap_or("").trim().to_ascii_lowercase();+ if raw.is_empty() { return "unknown".into(); }+ let category = if raw.starts_with("claude-") {+ if raw.contains("opus") { "claude_opus" }+ else if raw.contains("sonnet") { "claude_sonnet" }+ else if raw.contains("haiku") { "claude_haiku" }+ else { "claude_other" }+ } else if raw.starts_with("gpt-5") {+ "gpt_5"+ } else if raw.starts_with("gpt-4.1") {+ "gpt_4_1"+ } else if raw.starts_with("gpt-4o") {+ "gpt_4o"+ } else if raw.starts_with("gpt-4") {+ "gpt_4"+ } else if raw == "o1" || raw.starts_with("o1-") {+ "openai_o1"+ } else if raw == "o3" || raw.starts_with("o3-") {+ "openai_o3"+ } else if raw == "o4" || raw.starts_with("o4-") {+ "openai_o4"+ } else if raw.starts_with("gemini-") {+ if raw.contains("flash") { "gemini_flash" }+ else if raw.contains("pro") { "gemini_pro" }+ else { "gemini_other" }+ } else if raw.starts_with("grok-") {+ "grok"+ } else if raw.starts_with("nova-") {+ "amazon_nova"+ } else if raw.starts_with("phi-") {+ "microsoft_phi"+ } else {+ "custom"+ };+ category.into()+}++fn normalize_protocol(value: Option<&str>) -> String {+ match value {+ Some(value @ ("2024-11-05" | "2025-03-26" | "2025-06-18" | "2025-11-25")) => value.to_owned(),+ _ => "unknown".into(),+ }+}++fn version_major(value: Option<&str>) -> String {+ let major = value+ .unwrap_or("")+ .split(|character: char| !character.is_ascii_digit())+ .find(|part| !part.is_empty())+ .unwrap_or("unknown");+ if major.len() <= 4 { major.to_owned() } else { "unknown".into() }+}++pub fn ensure_first_run_registration() {+ if !is_enabled() || lifecycle_is_current() || lifecycle_retry_deferred() {return;}- spawn_capture(event_name.to_owned(), properties, /*bypass_opt_out*/ false);-}--/// Record the one-time `cua_driver_install` event. Guarded by a-/// `.installation_recorded` marker file so it only fires once per install,-/// and **bypasses the opt-out check** — this is the only path that does so.-///-/// Rationale: we count adoption (one ping per install) so the Rust port's-/// install metric is comparable to the Swift port's. Every subsequent-/// event respects the opt-out normally.-///-/// Unlike [`capture`], this path posts **synchronously** so the marker-/// file is only written when the POST actually succeeds. A failed POST-/// (network, PostHog outage, timeout) leaves the marker absent so the-/// next launch retries — without this, a single bad network at install-/// time would silently drop the only adoption signal we have.+ let Some(home) = telemetry_home_dir() else {+ return;+ };+ let Some(_lifecycle_lock) = try_lifecycle_lock(&home) else {+ return;+ };+ if !is_enabled() || lifecycle_retry_deferred() {+ return;+ }+ if lifecycle_is_current() {+ let _ = remove_file_if_exists(&home.join(TELEMETRY_INSTALL_CHANNEL_FILE_NAME));+ return;+ }+ eprintln!(+ "Cua Driver sends content-free product telemetry by default. Run `cua-driver telemetry disable` to stop it; `cua-driver telemetry status` shows the current setting."+ );+ capture_install_locked(&home, &mut post_to_posthog);+}++/// Run lifecycle delivery in a hidden worker before CLI parsing. The normal+/// process only spawns this worker, so a blackholed telemetry endpoint cannot+/// delay MCP initialization, daemon startup, or finite CLI commands.+pub(crate) fn run_lifecycle_worker_if_requested() -> bool {+ if !parse_env_bool(ENV_LIFECYCLE_WORKER).unwrap_or(false) {+ return false;+ }+ ensure_first_run_registration();+ true+}++pub(crate) fn spawn_first_run_registration_worker() {+ if !is_enabled() || lifecycle_is_current() || lifecycle_retry_deferred() {+ return;+ }+ eprintln!(+ "Cua Driver sends content-free product telemetry by default. Run `cua-driver telemetry disable` to stop it; `cua-driver telemetry status` shows the current setting."+ );+ let Ok(executable) = std::env::current_exe() else { return; };+ let _ = std::process::Command::new(executable)+ .env(ENV_LIFECYCLE_WORKER, "1")+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn();+}+pub fn capture_install() {capture_install_with_poster(post_to_posthog);}-/// Internal seam for [`capture_install`] so tests can inject a fake-/// HTTP poster. Returns immediately if the marker already exists or if-/// the HOME directory cannot be resolved.-fn capture_install_with_poster<F>(post: F)+fn capture_install_with_poster<F>(mut post: F)where- F: FnOnce(&serde_json::Value) -> Result<u16, String>,+ F: FnMut(&Value) -> Result<u16, String>,{- let home_dir = match telemetry_home_dir() {- Some(p) => p,- None => return,+ if !is_enabled() || lifecycle_retry_deferred() {+ return;+ }+ let Some(home) = telemetry_home_dir() else {+ return;};- let marker_path = home_dir.join(INSTALLATION_RECORDED_FILE_NAME);- if marker_path.exists() {- // Already recorded — silent no-op (matches Swift).+ let Some(_lifecycle_lock) = try_lifecycle_lock(&home) else {+ return;+ };+ if !is_enabled() || lifecycle_is_current() || lifecycle_retry_deferred() {return;}+ capture_install_locked(&home, &mut post);+}- // Build the payload directly (we still bypass the opt-out check here,- // see module docs + capture_install rationale) and POST synchronously.- let distinct_id = get_or_create_install_id();- let payload = build_payload(event::INSTALL, None, &distinct_id);- let debug = debug_enabled();- if debug {- eprintln!("[telemetry] sending event: {} (sync)", event::INSTALL);- }+fn capture_install_locked<F>(home: &Path, post: &mut F)+where+ F: FnMut(&Value) -> Result<u16, String>,+{+ let Some(identity) = get_or_create_install_id() else {+ return;+ };+ let channel = install_channel();+ let registration_marker = home.join(INSTALLATION_RECORDED_FILE_NAME);- match post(&payload) {- Ok(status) if (200..300).contains(&status) => {- if debug {- eprintln!("[telemetry] {} status: {status}", event::INSTALL);+ if !registration_marker.exists() {+ let payload = build_payload(+ event::INSTALLATION_REGISTERED,+ &lifecycle_properties(channel),+ &identity,+ Transport::Cli,+ );+ if post_success(post, &payload, event::INSTALLATION_REGISTERED) {+ if write_marker(®istration_marker).is_err() {+ defer_lifecycle_retry(home);+ return;}- }- Ok(status) => {- // Non-2xx: treat as failure so the next launch retries. PostHog- // returns 200 on accepted capture; anything else (4xx auth /- // payload error, 5xx outage) is not a success.- debug_log(format_args!(- "{} non-success status {status}; marker not written, will retry",- event::INSTALL- ));- return;- }- Err(e) => {- debug_log(format_args!(- "{} failed: {e}; marker not written, will retry",- event::INSTALL- ));+ } else {+ defer_lifecycle_retry(home);return;}}- // Only reached on HTTP 2xx — persist the marker so subsequent launches- // skip re-sending. IO errors here are non-fatal (next launch retries).- if let Err(e) = std::fs::create_dir_all(&home_dir) {- debug_log(format_args!("failed to create {}: {e}", home_dir.display()));+ let version = release_version();+ let Some(release_marker) = release_marker_path(&version) else {+ return;+ };+ if release_marker.exists() {return;}- if let Err(e) = std::fs::write(&marker_path, "1") {- debug_log(format_args!(- "failed to write install marker {}: {e}",- marker_path.display()- ));+ let payload = build_payload(+ event::RELEASE_INSTALLED,+ &lifecycle_properties(channel),+ &identity,+ Transport::Cli,+ );+ if post_success(post, &payload, event::RELEASE_INSTALLED) {+ if write_marker(&release_marker).is_ok() {+ let _ = remove_file_if_exists(&home.join(TELEMETRY_RETRY_AFTER_FILE_NAME));+ let _ = remove_file_if_exists(&home.join(TELEMETRY_INSTALL_CHANNEL_FILE_NAME));+ } else {+ defer_lifecycle_retry(home);+ }+ } else {+ defer_lifecycle_retry(home);}}-// ── Internals ────────────────────────────────────────────────────────────+fn lifecycle_is_current() -> bool {+ let registered = marker_path(INSTALLATION_RECORDED_FILE_NAME)+ .is_some_and(|path| path.exists());+ let release = release_marker_path(&release_version())+ .is_some_and(|path| path.exists());+ registered && release+}-/// Resolve `~/.cua-driver`. Returns `None` only on the platform-impossible-/// case where neither `HOME` (Unix) nor `USERPROFILE` (Windows) is set.-fn telemetry_home_dir() -> Option<PathBuf> {- let home = std::env::var_os("HOME")- .or_else(|| std::env::var_os("USERPROFILE"))?;- Some(PathBuf::from(home).join(HOME_SUBDIRECTORY))+fn lifecycle_retry_deferred() -> bool {+ let Some(path) = marker_path(TELEMETRY_RETRY_AFTER_FILE_NAME) else { return false; };+ let Some(retry_after) = std::fs::read_to_string(path)+ .ok()+ .and_then(|value| value.trim().parse::<u64>().ok())+ else { return false; };+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|duration| duration.as_secs())+ .unwrap_or(retry_after);+ retry_after > now && retry_after.saturating_sub(now) <= LIFECYCLE_RETRY_BACKOFF_SECS}-/// One-shot migration: when the legacy `~/.cua-driver-rs/` exists, move its-/// telemetry files into the new `~/.cua-driver/` directory and remove the-/// legacy dir. Best-effort — if anything fails (legacy dir not present,-/// permissions, locks), we silently fall through and the daemon proceeds-/// with the new path. Called once per process start from-/// `load_or_create_install_id_uncached`.-fn migrate_legacy_telemetry_home() {- let Some(home_root) = std::env::var_os("HOME")- .or_else(|| std::env::var_os("USERPROFILE"))- else {+fn defer_lifecycle_retry(home: &Path) {+ let retry_after = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|duration| duration.as_secs().saturating_add(LIFECYCLE_RETRY_BACKOFF_SECS));+ if let Ok(retry_after) = retry_after {+ let _ = std::fs::write(home.join(TELEMETRY_RETRY_AFTER_FILE_NAME), retry_after.to_string());+ }+}++fn post_success<F>(post: &mut F, payload: &Value, event_name: &str) -> bool+where+ F: FnMut(&Value) -> Result<u16, String>,+{+ match post(payload) {+ Ok(status) if (200..300).contains(&status) => true,+ Ok(status) => {+ debug_log(format_args!("{event_name} returned {status}; marker not written"));+ false+ }+ Err(error) => {+ debug_log(format_args!("{event_name} failed: {error}; marker not written"));+ false+ }+ }+}++pub(crate) fn capture_bounded(+ event_name: &'static str,+ properties: Map<String, Value>,+ transport: Transport,+) {+ if !is_enabled() {+ return;+ }+ let Some(identity) = get_or_create_install_id() else {return;};- let legacy_dir = PathBuf::from(&home_root).join(LEGACY_HOME_SUBDIRECTORY);- if !legacy_dir.is_dir() {+ let payload = build_payload(event_name, &properties, &identity, transport);+ spawn_payload(event_name, payload);+}++/// Record a finite CLI command only after its outcome is known. This is+/// synchronous with a short timeout because one-shot processes may exit before+/// a detached request is delivered.+pub(crate) fn capture_cli_completed(+ command: &'static str,+ exit_code: i32,+ elapsed: Duration,+) {+ if !is_enabled() {return;}- let new_dir = PathBuf::from(&home_root).join(HOME_SUBDIRECTORY);- let _ = std::fs::create_dir_all(&new_dir);+ let command = match command {+ "list_tools" => "list_tools",+ "describe" => "describe",+ "mcp_config" => "mcp_config",+ "manifest" => "manifest",+ "call" => "call",+ "stop" => "stop",+ "status" => "status",+ "recording" => "recording",+ "dump_docs" => "dump_docs",+ "update" => "update",+ "check_update" => "check_update",+ "doctor" => "doctor",+ "diagnose" => "diagnose",+ "permissions" => "permissions",+ "autostart" => "autostart",+ "skills" => "skills",+ "config" => "config",+ _ => "other",+ };+ let success = exit_code == 0;+ let exit_class = match exit_code {+ 0 => "success",+ 1 => "tool_error",+ 64 => "invalid_input",+ _ => "other",+ };+ let Some(identity) = get_or_create_install_id() else {+ return;+ };+ let payload = build_payload(+ event::CLI_COMPLETED,+ &bounded_properties(&[+ ("command", Value::String(command.into())),+ ("success", Value::Bool(success)),+ ("exit_class", Value::String(exit_class.into())),+ ("duration_bucket", Value::String(duration_bucket(elapsed).into())),+ ]),+ &identity,+ Transport::Cli,+ );+ if let Err(error) = post_to_posthog_with_timeout(&payload, Duration::from_secs(POSTHOG_TIMEOUT_SECS)) {+ debug_log(format_args!("{} failed: {error}", event::CLI_COMPLETED));+ }+}- // Move the two known telemetry markers if they exist + the new- // location doesn't already have them (avoid clobbering newer state).- for name in [TELEMETRY_ID_FILE_NAME, INSTALLATION_RECORDED_FILE_NAME] {- let legacy_path = legacy_dir.join(name);- let new_path = new_dir.join(name);- if legacy_path.exists() && !new_path.exists() {- let _ = std::fs::rename(&legacy_path, &new_path);- }- // Also delete the legacy file if it lingered for any reason — we- // never want to leave the legacy directory inhabited.- let _ = std::fs::remove_file(&legacy_path);- }- // Try to remove the legacy directory. Only succeeds if it's empty,- // which is the only case where removal is safe (we don't want to- // delete user-placed files we don't know about).- let _ = std::fs::remove_dir(&legacy_dir);-}--/// Read the per-install UUID, creating + persisting a fresh one if absent-/// or unreadable. Idempotent across calls in the same process via-/// `INSTALL_ID_CACHE`.-fn get_or_create_install_id() -> String {- static INSTALL_ID_CACHE: OnceLock<String> = OnceLock::new();- INSTALL_ID_CACHE- .get_or_init(load_or_create_install_id_uncached)- .clone()-}--/// Disk-bound path. Read existing UUID if valid; otherwise generate and persist.-/// Separated from the `OnceLock` wrapper so tests can exercise the path logic-/// without contaminating process-global state.-fn load_or_create_install_id_uncached() -> String {- // Migrate legacy telemetry files from `.cua-driver-rs/` → `.cua-driver/`- // before reading the new path. Best-effort; idempotent.- migrate_legacy_telemetry_home();+pub(crate) fn is_wrapped_cli_child() -> bool {+ parse_env_bool(ENV_CLI_WRAPPED_CHILD).unwrap_or(false)+}- let Some(home_dir) = telemetry_home_dir() else {- // No HOME — generate an ephemeral UUID. Telemetry will still send,- // but the distinct_id won't be stable across runs. Acceptable- // fallback for non-interactive containers.- return uuid::Uuid::new_v4().to_string();- };- let id_path = home_dir.join(TELEMETRY_ID_FILE_NAME);+pub(crate) fn cli_wrapped_child_env() -> &'static str {+ ENV_CLI_WRAPPED_CHILD+}- // Try existing UUID first.- if let Ok(existing) = std::fs::read_to_string(&id_path) {- let trimmed = existing.trim();- if !trimmed.is_empty() {- return trimmed.to_owned();- }+/// Run the hidden delivery worker before CLI parsing. The foreground parent+/// never waits on this process, so telemetry delivery cannot add network+/// latency to one-shot commands.+pub(crate) fn run_cli_completion_worker_if_requested() -> bool {+ if !parse_env_bool(ENV_CLI_COMPLETION_WORKER).unwrap_or(false) {+ return false;}+ let command = std::env::var(ENV_CLI_COMPLETION_COMMAND).unwrap_or_default();+ let exit_code = std::env::var(ENV_CLI_COMPLETION_EXIT_CODE)+ .ok()+ .and_then(|value| value.parse::<i32>().ok())+ .unwrap_or(1);+ let elapsed = std::env::var(ENV_CLI_COMPLETION_DURATION_MS)+ .ok()+ .and_then(|value| value.parse::<u64>().ok())+ .map(Duration::from_millis)+ .unwrap_or_default();+ let command = fixed_cli_command(&command);+ capture_cli_completed(command, exit_code, elapsed);+ true+}- // Generate + persist a fresh UUID. Persistence failures are- // non-fatal — we still return the generated id, just without- // cross-run stability.- let new_id = uuid::Uuid::new_v4().to_string();- if let Err(e) = std::fs::create_dir_all(&home_dir) {- debug_log(format_args!("failed to create {}: {e}", home_dir.display()));- return new_id;+pub(crate) fn spawn_cli_completion_worker(+ command: &'static str,+ exit_code: i32,+ elapsed: Duration,+) {+ if !is_enabled() {+ return;}- if let Err(e) = std::fs::write(&id_path, &new_id) {- debug_log(format_args!(- "failed to persist install id {}: {e}",- id_path.display()- ));+ let Ok(executable) = std::env::current_exe() else { return; };+ let _ = std::process::Command::new(executable)+ .env(ENV_CLI_COMPLETION_WORKER, "1")+ .env(ENV_CLI_COMPLETION_COMMAND, fixed_cli_command(command))+ .env(ENV_CLI_COMPLETION_EXIT_CODE, exit_code.to_string())+ .env(ENV_CLI_COMPLETION_DURATION_MS, elapsed.as_millis().to_string())+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ .spawn();+}++fn fixed_cli_command(command: &str) -> &'static str {+ match command {+ "list_tools" => "list_tools",+ "describe" => "describe",+ "mcp_config" => "mcp_config",+ "manifest" => "manifest",+ "call" => "call",+ "stop" => "stop",+ "status" => "status",+ "recording" => "recording",+ "dump_docs" => "dump_docs",+ "update" => "update",+ "check_update" => "check_update",+ "doctor" => "doctor",+ "diagnose" => "diagnose",+ "permissions" => "permissions",+ "autostart" => "autostart",+ "skills" => "skills",+ "config" => "config",+ _ => "other",}- new_id}-/// Build the PostHog event payload. Public-in-crate so unit tests can-/// assert on payload shape without an actual HTTP roundtrip.-pub(crate) fn build_payload(+pub(crate) fn bounded_properties(entries: &[(&str, Value)]) -> Map<String, Value> {+ entries+ .iter()+ .map(|(key, value)| ((*key).to_owned(), value.clone()))+ .collect()+}++fn lifecycle_properties(channel: &'static str) -> Map<String, Value> {+ bounded_properties(&[+ ("install_channel", Value::String(channel.to_owned())),+ ("product_version", Value::String(release_version())),+ ])+}++fn build_payload(event_name: &str,- properties: Option<&serde_json::Value>,- distinct_id: &str,-) -> serde_json::Value {- let version = env!("CARGO_PKG_VERSION");-- let mut event_properties = serde_json::Map::new();- // Caller-provided properties first, so default-envelope keys win on- // collision (matches Swift's `eventProperties[key] = value` order).- if let Some(serde_json::Value::Object(map)) = properties {- for (k, v) in map {- event_properties.insert(k.clone(), v.clone());- }- }- event_properties.insert("cua_driver_version".into(), version.into());- event_properties.insert("os".into(), os_name().into());- event_properties.insert("os_version".into(), os_version().into());- event_properties.insert("arch".into(), arch().into());- event_properties.insert("is_ci".into(), is_ci().into());- event_properties.insert("$lib".into(), "cua-driver-rs".into());- event_properties.insert("$lib_version".into(), version.into());+ properties: &Map<String, Value>,+ identity: &InstallationIdentity,+ transport: Transport,+) -> Value {+ let mut event_properties = properties.clone();+ event_properties.insert("telemetry_schema_version".into(), Value::from(2));+ event_properties+ .entry("product_version")+ .or_insert_with(|| Value::String(current_product_version().into()));+ event_properties.insert("os_family".into(), Value::String(os_family().into()));+ event_properties.insert("os_major".into(), Value::String(os_major()));+ event_properties.insert("arch".into(), Value::String(arch().into()));+ event_properties.insert("is_ci".into(), Value::Bool(is_ci()));+ event_properties.insert("transport".into(), Value::String(transport.as_str().into()));+ event_properties.insert("process_session_id".into(), Value::String(process_session_id()));+ event_properties.insert("id_persisted".into(), Value::Bool(identity.persisted));+ event_properties.insert("$process_person_profile".into(), Value::Bool(false));+ event_properties.insert("$geoip_disable".into(), Value::Bool(true));+ event_properties.insert("$lib".into(), Value::String("cua-driver-rs".into()));+ event_properties.insert("$lib_version".into(), Value::String(current_product_version().into()));serde_json::json!({"api_key": POSTHOG_API_KEY,"event": event_name,- "distinct_id": distinct_id,+ "distinct_id": identity.id,"properties": event_properties,- "timestamp": iso8601_now(),})}-/// Spawn the HTTP POST on a background tokio task. Caller returns immediately.-/// Requires a tokio runtime to be active in the current thread; falls back-/// to `std::thread::spawn` otherwise so CLI subcommands that don't build-/// a runtime (e.g. `list-tools`) still get telemetry coverage.-fn spawn_capture(- event_name: String,- properties: Option<serde_json::Value>,- bypass_opt_out: bool,-) {- if !bypass_opt_out && !is_enabled() {- return;- }- let distinct_id = get_or_create_install_id();- let payload = build_payload(&event_name, properties.as_ref(), &distinct_id);- let debug = debug_enabled();-+fn spawn_payload(event_name: &'static str, payload: Value) {+ PENDING_SENDS.fetch_add(1, Ordering::SeqCst);let task = move || {- if debug {- eprintln!("[telemetry] sending event: {event_name}");- }- match post_to_posthog(&payload) {- Ok(status) => {- if debug {- eprintln!("[telemetry] {event_name} status: {status}");- }- }- Err(e) => {- if debug {- eprintln!("[telemetry] {event_name} failed: {e}");- } else {- tracing::debug!(target: "cua_driver::telemetry",- "POST {event_name} failed: {e}");- }- }+ let _pending = PendingSendGuard;+ if let Err(error) = post_to_posthog(&payload) {+ debug_log(format_args!("{event_name} failed: {error}"));}};-- // Prefer tokio so the POST shares the runtime's reactor; fall back to- // a plain OS thread for sync entry-points (CLI subcommands like- // `list-tools` that don't construct a runtime).if tokio::runtime::Handle::try_current().is_ok() {tokio::task::spawn_blocking(task);} else {- // Best-effort: detach a short-lived OS thread. ureq's POST is- // synchronous and self-contained, so this is safe and simple.- std::thread::Builder::new()- .name("cua-telemetry".into())- .spawn(task)- .ok();+ if std::thread::Builder::new().name("cua-telemetry".into()).spawn(task).is_err() {+ finish_pending_send();+ }+ }+}++static PENDING_SENDS: AtomicUsize = AtomicUsize::new(0);+static PENDING_WAIT: OnceLock<(Mutex<()>, Condvar)> = OnceLock::new();++struct PendingSendGuard;++impl Drop for PendingSendGuard {+ fn drop(&mut self) {+ finish_pending_send();+ }+}++fn finish_pending_send() {+ if let Some((lock, ready)) = PENDING_WAIT.get() {+ let _guard = lock.lock().unwrap_or_else(|poisoned| poisoned.into_inner());+ PENDING_SENDS.fetch_sub(1, Ordering::SeqCst);+ ready.notify_all();+ } else {+ PENDING_SENDS.fetch_sub(1, Ordering::SeqCst);}}-/// Actual ureq POST. Returns the HTTP status code on success. Anything else-/// (network error, 4xx/5xx, timeout) is propagated as `Err`.-fn post_to_posthog(payload: &serde_json::Value) -> Result<u16, String> {+/// Give already-enqueued telemetry a bounded chance to finish when a+/// long-running MCP process is about to force-exit.+pub(crate) fn flush_pending(timeout: Duration) {+ if PENDING_SENDS.load(Ordering::SeqCst) == 0 {+ return;+ }+ let wait = PENDING_WAIT.get_or_init(|| (Mutex::new(()), Condvar::new()));+ let deadline = std::time::Instant::now() + timeout;+ let mut guard = wait.0.lock().unwrap_or_else(|poisoned| poisoned.into_inner());+ while PENDING_SENDS.load(Ordering::SeqCst) > 0 {+ let now = std::time::Instant::now();+ if now >= deadline {+ break;+ }+ let (next, result) = wait.1.wait_timeout(guard, deadline - now)+ .unwrap_or_else(|poisoned| poisoned.into_inner());+ guard = next;+ if result.timed_out() {+ break;+ }+ }+}++fn post_to_posthog(payload: &Value) -> Result<u16, String> {+ post_to_posthog_with_timeout(payload, Duration::from_secs(POSTHOG_TIMEOUT_SECS))+}++fn post_to_posthog_with_timeout(payload: &Value, timeout: Duration) -> Result<u16, String> {let agent = ureq::Agent::config_builder()- .timeout_global(Some(std::time::Duration::from_secs(POSTHOG_TIMEOUT_SECS)))+ .timeout_global(Some(timeout)).build().new_agent();-match agent.post(POSTHOG_CAPTURE_URL).header("Content-Type", "application/json").send_json(payload){Ok(response) => Ok(response.status().as_u16()),- Err(e) => Err(e.to_string()),+ Err(error) => Err(error.to_string()),+ }+}++fn telemetry_home_dir() -> Option<PathBuf> {+ if let Some(path) = std::env::var_os(ENV_TELEMETRY_HOME) {+ return Some(PathBuf::from(path));+ }+ home_root().map(|home| home.join(HOME_SUBDIRECTORY))+}++fn home_root() -> Option<PathBuf> {+ std::env::var_os("HOME")+ .or_else(|| std::env::var_os("USERPROFILE"))+ .map(PathBuf::from)+}++fn config_path() -> Option<PathBuf> {+ telemetry_home_dir().map(|home| home.join(CONFIG_FILE_NAME))+}++fn marker_path(name: &str) -> Option<PathBuf> {+ telemetry_home_dir().map(|home| home.join(name))+}++fn release_marker_path(version: &str) -> Option<PathBuf> {+ let safe: String = version+ .chars()+ .filter(|character| character.is_ascii_alphanumeric() || matches!(character, '.' | '-' | '_'))+ .take(80)+ .collect();+ telemetry_home_dir().map(|home| home.join(RELEASE_RECORDED_DIRECTORY).join(safe))+}++fn read_config() -> Value {+ config_path()+ .and_then(|path| std::fs::read_to_string(path).ok())+ .and_then(|json| serde_json::from_str(&json).ok())+ .filter(Value::is_object)+ .unwrap_or_else(|| Value::Object(Map::new()))+}++fn persisted_enabled() -> Option<bool> {+ read_config().get(CONFIG_ENABLED_KEY).and_then(Value::as_bool)+}++fn write_json_atomic(path: &Path, value: &Value) -> Result<(), String> {+ let parent = path.parent().ok_or_else(|| "invalid config path".to_owned())?;+ std::fs::create_dir_all(parent)+ .map_err(|error| format!("failed to create {}: {error}", parent.display()))?;+ let temporary = path.with_extension(format!("tmp-{}", uuid::Uuid::new_v4()));+ let json = serde_json::to_vec_pretty(value).map_err(|error| error.to_string())?;+ std::fs::write(&temporary, json)+ .map_err(|error| format!("failed to write {}: {error}", temporary.display()))?;+ #[cfg(windows)]+ if path.exists() {+ std::fs::remove_file(path)+ .map_err(|error| format!("failed to replace {}: {error}", path.display()))?;}+ std::fs::rename(&temporary, path)+ .map_err(|error| format!("failed to replace {}: {error}", path.display()))}-// ── Environment helpers ──────────────────────────────────────────────────+fn remove_file_if_exists(path: &Path) -> Result<(), String> {+ match std::fs::remove_file(path) {+ Ok(()) => Ok(()),+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(()),+ Err(error) => Err(format!("failed to remove {}: {error}", path.display())),+ }+}++fn write_marker(path: &Path) -> Result<(), String> {+ if let Some(parent) = path.parent() {+ std::fs::create_dir_all(parent)+ .map_err(|error| format!("failed to create {}: {error}", parent.display()))?;+ }+ std::fs::write(path, "1")+ .map_err(|error| format!("failed to write {}: {error}", path.display()))+}++fn open_lock_file(home: &Path, name: &str) -> Result<File, String> {+ std::fs::create_dir_all(home)+ .map_err(|error| format!("failed to create {}: {error}", home.display()))?;+ OpenOptions::new()+ .read(true)+ .write(true)+ .create(true)+ .open(home.join(name))+ .map_err(|error| format!("failed to open telemetry state lock: {error}"))+}++fn try_lifecycle_lock(home: &Path) -> Option<File> {+ let file = match open_lock_file(home, TELEMETRY_LIFECYCLE_LOCK_FILE_NAME) {+ Ok(file) => file,+ Err(error) => {+ debug_log(format_args!("lifecycle lock unavailable: {error}"));+ return None;+ }+ };+ match file.try_lock() {+ Ok(()) => Some(file),+ Err(TryLockError::WouldBlock) => {+ debug_log(format_args!("lifecycle registration already in progress"));+ None+ }+ Err(TryLockError::Error(error)) => {+ debug_log(format_args!("failed to lock telemetry lifecycle: {error}"));+ None+ }+ }+}++fn migrate_legacy_telemetry_home() {+ if std::env::var_os(ENV_TELEMETRY_HOME).is_some() {+ return;+ }+ let Some(root) = home_root() else { return; };+ let legacy = root.join(LEGACY_HOME_SUBDIRECTORY);+ let current = root.join(HOME_SUBDIRECTORY);+ if !legacy.is_dir() { return; }+ let _ = std::fs::create_dir_all(¤t);+ let Ok(identity_lock) = open_lock_file(¤t, TELEMETRY_IDENTITY_LOCK_FILE_NAME) else { return; };+ if identity_lock.lock().is_err() { return; }+ for name in [TELEMETRY_ID_FILE_NAME, INSTALLATION_RECORDED_FILE_NAME] {+ let source = legacy.join(name);+ let destination = current.join(name);+ if source.exists() && !destination.exists() {+ let _ = std::fs::rename(&source, &destination);+ }+ }+ let _ = std::fs::remove_dir(&legacy);+}++fn read_install_id() -> Option<String> {+ migrate_legacy_telemetry_home();+ let path = marker_path(TELEMETRY_ID_FILE_NAME)?;+ read_install_id_path(&path)+}-fn parse_env_bool(var: &str) -> Option<bool> {- let raw = std::env::var(var).ok()?;- match raw.trim().to_ascii_lowercase().as_str() {+fn read_install_id_path(path: &Path) -> Option<String> {+ let value = std::fs::read_to_string(path).ok()?;+ let trimmed = value.trim();+ if uuid::Uuid::parse_str(trimmed).is_ok() {+ Some(trimmed.to_owned())+ } else {+ None+ }+}++fn get_or_create_install_id() -> Option<InstallationIdentity> {+ load_or_create_install_id_uncached()+}++fn load_or_create_install_id_uncached() -> Option<InstallationIdentity> {+ if let Some(id) = read_install_id() {+ return Some(InstallationIdentity { id, persisted: true });+ }+ let Some(path) = marker_path(TELEMETRY_ID_FILE_NAME) else {+ static EPHEMERAL_ID: OnceLock<String> = OnceLock::new();+ return Some(InstallationIdentity {+ id: EPHEMERAL_ID.get_or_init(|| uuid::Uuid::new_v4().to_string()).clone(),+ persisted: false,+ });+ };+ let candidate = uuid::Uuid::new_v4().to_string();+ match persist_install_id_if_absent(&path, &candidate) {+ Ok(id) => Some(InstallationIdentity { id, persisted: true }),+ Err(error) => {+ debug_log(format_args!("installation identity unavailable: {error}"));+ None+ }+ }+}++fn persist_install_id_if_absent(path: &Path, candidate: &str) -> Result<String, String> {+ let home = path.parent().ok_or_else(|| "invalid telemetry identity path".to_owned())?;+ let identity_lock = open_lock_file(home, TELEMETRY_IDENTITY_LOCK_FILE_NAME)?;+ identity_lock+ .lock()+ .map_err(|error| format!("failed to lock telemetry identity: {error}"))?;++ if let Some(id) = read_install_id_path(path) {+ return Ok(id);+ }++ let temporary = home.join(format!(".telemetry-id-{}.tmp", uuid::Uuid::new_v4()));+ let result = (|| {+ let mut file = File::create(&temporary)+ .map_err(|error| format!("failed to write telemetry identity: {error}"))?;+ file.write_all(candidate.as_bytes())+ .map_err(|error| format!("failed to write telemetry identity: {error}"))?;+ file.sync_data()+ .map_err(|error| format!("failed to sync telemetry identity: {error}"))?;++ #[cfg(windows)]+ if path.exists() {+ std::fs::remove_file(path)+ .map_err(|error| format!("failed to replace telemetry identity: {error}"))?;+ }+ std::fs::rename(&temporary, path)+ .map_err(|error| format!("failed to persist telemetry identity: {error}"))?;+ Ok(candidate.to_owned())+ })();+ if result.is_err() {+ let _ = std::fs::remove_file(&temporary);+ }+ result+}++fn redact_id(id: &str) -> String {+ format!("{}…", id.chars().take(8).collect::<String>())+}++fn current_product_version() -> &'static str {+ env!("CARGO_PKG_VERSION")+}++fn release_version() -> String {+ std::env::var(ENV_RELEASE_VERSION)+ .ok()+ .and_then(|value| strict_release_version(&value))+ .unwrap_or_else(|| current_product_version().to_owned())+}++fn strict_release_version(raw: &str) -> Option<String> {+ let value = raw.trim().strip_prefix('v').unwrap_or(raw.trim());+ if value.is_empty() || value.len() > 64 || value.contains('+') {+ return None;+ }+ let (core, prerelease) = value+ .split_once('-')+ .map_or((value, None), |(core, suffix)| (core, Some(suffix)));+ let components: Vec<&str> = core.split('.').collect();+ if components.len() != 3+ || components.iter().any(|part| {+ part.is_empty() || part.len() > 6 || !part.chars().all(|c| c.is_ascii_digit())+ })+ {+ return None;+ }+ if prerelease.is_some_and(|suffix| {+ suffix.is_empty()+ || suffix.len() > 32+ || suffix.split('.').any(|part| part.is_empty())+ || !suffix+ .chars()+ .all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-'))+ }) {+ return None;+ }+ Some(value.to_owned())+}++fn duration_bucket(elapsed: Duration) -> &'static str {+ match elapsed.as_millis() {+ 0..=99 => "lt_100ms",+ 100..=499 => "100_499ms",+ 500..=1_999 => "500ms_1_999ms",+ 2_000..=9_999 => "2s_9_999ms",+ _ => "gte_10s",+ }+}++fn install_channel() -> &'static str {+ std::env::var(ENV_INSTALL_CHANNEL)+ .ok()+ .and_then(|value| normalize_install_channel(&value))+ .or_else(|| {+ marker_path(TELEMETRY_INSTALL_CHANNEL_FILE_NAME)+ .and_then(|path| std::fs::read_to_string(path).ok())+ .and_then(|value| normalize_install_channel(&value))+ })+ .unwrap_or("first_run")+}++fn normalize_install_channel(value: &str) -> Option<&'static str> {+ match value.trim() {+ "install_script" => Some("install_script"),+ "update_apply" => Some("update_apply"),+ "python_package" => Some("python_package"),+ "manual_binary" => Some("manual_binary"),+ "first_run" => Some("first_run"),+ _ => None,+ }+}++fn process_session_id() -> String {+ static ID: OnceLock<String> = OnceLock::new();+ ID.get_or_init(|| uuid::Uuid::new_v4().to_string()).clone()+}++fn parse_env_bool(name: &str) -> Option<bool> {+ let value = std::env::var(name).ok()?;+ match value.trim().to_ascii_lowercase().as_str() {"0" | "false" | "no" | "off" => Some(false),"1" | "true" | "yes" | "on" => Some(true),_ => None,@@ -432,375 +1179,542 @@ fn debug_log(args: std::fmt::Arguments<'_>) {}}-/// Stringly OS name — `"macos" | "windows" | "linux"` to match Swift's-/// `"macos"` value exactly on darwin.-fn os_name() -> &'static str {- std::env::consts::OS // already "macos"/"windows"/"linux"+fn os_family() -> &'static str {+ match std::env::consts::OS {+ "macos" => "macos",+ "windows" => "windows",+ "linux" => "linux",+ _ => "other",+ }+}++fn os_major() -> String {+ static OS_MAJOR: OnceLock<String> = OnceLock::new();+ OS_MAJOR.get_or_init(|| {+ let raw = os_version();+ let start = raw.find(|character: char| character.is_ascii_digit());+ let Some(start) = start else { return "unknown".into(); };+ raw[start..]+ .split(|character: char| !character.is_ascii_digit())+ .next()+ .filter(|value| !value.is_empty())+ .unwrap_or("unknown")+ .to_owned()+ }).clone()}-/// Reported OS version. Best-effort: returns whatever the OS exposes via-/// the canonical "release" file/registry. Swift uses-/// `ProcessInfo.operatingSystemVersionString` (e.g. "Version 14.5 (Build 23F79)");-/// we approximate with a short string per platform.fn os_version() -> String {#[cfg(target_os = "macos")]- {- std::process::Command::new("sw_vers")- .arg("-productVersion")- .output()- .ok()- .and_then(|o| {- if o.status.success() {- Some(String::from_utf8_lossy(&o.stdout).trim().to_owned())- } else {- None- }- })- .unwrap_or_else(|| "unknown".to_owned())- }- #[cfg(target_os = "linux")]- {- // `/etc/os-release` is the freedesktop standard; fall back to "unknown".- std::fs::read_to_string("/etc/os-release")- .ok()- .and_then(|s| {- s.lines()- .find_map(|l| l.strip_prefix("PRETTY_NAME="))- .map(|v| v.trim_matches('"').to_owned())- })- .unwrap_or_else(|| "unknown".to_owned())- }+ let command = std::process::Command::new("sw_vers").arg("-productVersion").output();#[cfg(target_os = "windows")]+ let command = std::process::Command::new("cmd").args(["/c", "ver"]).output();+ #[cfg(target_os = "linux")]{- // No std API; cmd /c ver is best-effort.- std::process::Command::new("cmd")- .args(["/c", "ver"])- .output()+ return std::fs::read_to_string("/etc/os-release").ok()- .and_then(|o| {- if o.status.success() {- Some(String::from_utf8_lossy(&o.stdout).trim().to_owned())- } else {- None- }- })- .unwrap_or_else(|| "unknown".to_owned())- }- #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]- {- "unknown".to_owned()+ .and_then(|contents| contents.lines().find_map(|line| line.strip_prefix("VERSION_ID=").map(str::to_owned)))+ .map(|value| value.trim_matches('"').to_owned())+ .unwrap_or_else(|| "unknown".into());}+ #[cfg(not(target_os = "linux"))]+ command+ .ok()+ .filter(|output| output.status.success())+ .map(|output| String::from_utf8_lossy(&output.stdout).trim().to_owned())+ .unwrap_or_else(|| "unknown".into())}fn arch() -> &'static str {- // std::env::consts::ARCH returns "aarch64"/"x86_64"/etc.- // Map "aarch64" → "arm64" so the Rust label matches Swift's- // (`#if arch(arm64)` → `"arm64"`) and dashboards group correctly.match std::env::consts::ARCH {"aarch64" => "arm64",- other => other,+ "x86_64" => "x86_64",+ "x86" => "x86",+ _ => "other",}}-/// True when any well-known CI env var is set. List mirrors Swift exactly.fn is_ci() -> bool {- const CI_VARS: &[&str] = &[- "CI",- "CONTINUOUS_INTEGRATION",- "GITHUB_ACTIONS",- "GITLAB_CI",- "JENKINS_URL",- "CIRCLECI",+ const VARIABLES: &[&str] = &[+ "CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI",+ "JENKINS_URL", "CIRCLECI", "BUILDKITE", "TF_BUILD", "TEAMCITY_VERSION",+ "TRAVIS", "APPVEYOR", "BITBUCKET_BUILD_NUMBER", "CODEBUILD_BUILD_ID",+ "DRONE", "HUDSON_URL", "CI_NAME",];- CI_VARS.iter().any(|v| std::env::var_os(v).is_some())-}--/// ISO-8601 timestamp without bringing in a chrono dependency. PostHog-/// accepts `YYYY-MM-DDTHH:MM:SSZ` (UTC) directly.-fn iso8601_now() -> String {- use std::time::{SystemTime, UNIX_EPOCH};- let secs = SystemTime::now()- .duration_since(UNIX_EPOCH)- .map(|d| d.as_secs())- .unwrap_or(0);- // Civil-date conversion: 1970-01-01 + secs. Algorithm cribbed from- // Howard Hinnant's civil_from_days; safe through year 9999.- let (year, month, day, hour, minute, second) = civil_from_unix(secs);- format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")-}--fn civil_from_unix(unix_secs: u64) -> (i32, u32, u32, u32, u32, u32) {- let days = (unix_secs / 86_400) as i64;- let secs_of_day = (unix_secs % 86_400) as u32;- let hour = secs_of_day / 3600;- let minute = (secs_of_day % 3600) / 60;- let second = secs_of_day % 60;-- // Howard Hinnant's civil_from_days, shifted to 0000-03-01 era epoch.- let z = days + 719_468;- let era = z.div_euclid(146_097);- let doe = (z - era * 146_097) as u32; // [0, 146096]- let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]- let y = yoe as i64 + era * 400;- let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]- let mp = (5 * doy + 2) / 153; // [0, 11]- let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]- let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]- let year = (y + if m <= 2 { 1 } else { 0 }) as i32;- (year, m, d, hour, minute, second)-}--// ── Tests ────────────────────────────────────────────────────────────────+ VARIABLES.iter().any(|name| std::env::var_os(name).is_some())+}#[cfg(test)]mod tests {use super::*;+ use std::process::{Child, Command};use std::sync::Mutex;+ use std::time::Instant;- /// All env-mutating tests serialise on this lock — `std::env::set_var`- /// is process-global, parallel tests would race.static ENV_LOCK: Mutex<()> = Mutex::new(());+ const TEST_CHILD_KIND: &str = "CUA_DRIVER_TELEMETRY_TEST_CHILD_KIND";+ const TEST_CHILD_ROOT: &str = "CUA_DRIVER_TELEMETRY_TEST_CHILD_ROOT";+ const TEST_CHILD_INDEX: &str = "CUA_DRIVER_TELEMETRY_TEST_CHILD_INDEX";+ const TEST_CHILD_CANDIDATE: &str = "CUA_DRIVER_TELEMETRY_TEST_CHILD_CANDIDATE";++ fn with_isolated_home<R>(test: impl FnOnce(&Path) -> R) -> R {+ let root = std::env::temp_dir().join(format!("cua-telemetry-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&root).unwrap();+ let telemetry_home = root.join(HOME_SUBDIRECTORY);+ let old_telemetry_home = std::env::var_os(ENV_TELEMETRY_HOME);+ unsafe {+ std::env::set_var(ENV_TELEMETRY_HOME, &telemetry_home);+ std::env::remove_var(ENV_TELEMETRY_ENABLED);+ std::env::remove_var(ENV_TELEMETRY_ENABLED_COMPAT);+ }+ let result = test(&root);+ let _ = std::fs::remove_dir_all(&root);+ unsafe {+ match old_telemetry_home {+ Some(value) => std::env::set_var(ENV_TELEMETRY_HOME, value),+ None => std::env::remove_var(ENV_TELEMETRY_HOME),+ }+ }+ result+ }- #[test]- fn parse_env_bool_recognises_canonical_forms() {- let _g = ENV_LOCK.lock().unwrap();- for (raw, expected) in [- ("0", false),- ("false", false),- ("FALSE", false),- ("no", false),- ("off", false),- ("1", true),- ("true", true),- ("YES", true),- ("on", true),- ] {- unsafe { std::env::set_var("CUA_TELEMETRY_TEST_BOOL", raw); }- assert_eq!(parse_env_bool("CUA_TELEMETRY_TEST_BOOL"), Some(expected),- "raw={raw:?}");+ fn wait_for_path(path: &Path, timeout: Duration) -> bool {+ let deadline = Instant::now() + timeout;+ while Instant::now() < deadline {+ if path.exists() { return true; }+ std::thread::sleep(Duration::from_millis(10));}- unsafe { std::env::set_var("CUA_TELEMETRY_TEST_BOOL", "maybe"); }- assert_eq!(parse_env_bool("CUA_TELEMETRY_TEST_BOOL"), None);- unsafe { std::env::remove_var("CUA_TELEMETRY_TEST_BOOL"); }- assert_eq!(parse_env_bool("CUA_TELEMETRY_TEST_BOOL"), None);+ path.exists()}- #[test]- fn is_enabled_defaults_to_true_and_honors_env_opt_out() {- let _g = ENV_LOCK.lock().unwrap();- unsafe { std::env::remove_var(ENV_TELEMETRY_ENABLED); }- assert!(is_enabled(), "default must be enabled (Swift parity)");+ fn wait_for_children_ready(directory: &Path, count: usize, timeout: Duration) -> bool {+ let deadline = Instant::now() + timeout;+ while Instant::now() < deadline {+ let ready = std::fs::read_dir(directory)+ .ok()+ .into_iter()+ .flatten()+ .filter_map(Result::ok)+ .filter(|entry| entry.file_name().to_string_lossy().starts_with("ready-"))+ .count();+ if ready == count { return true; }+ std::thread::sleep(Duration::from_millis(10));+ }+ false+ }++ fn wait_for_child(child: &mut Child, timeout: Duration) -> Option<std::process::ExitStatus> {+ let deadline = Instant::now() + timeout;+ while Instant::now() < deadline {+ if let Some(status) = child.try_wait().expect("poll test child") {+ return Some(status);+ }+ std::thread::sleep(Duration::from_millis(10));+ }+ child.try_wait().expect("poll test child")+ }- unsafe { std::env::set_var(ENV_TELEMETRY_ENABLED, "false"); }- assert!(!is_enabled(), "explicit false must disable");+ fn spawn_test_child(kind: &str, root: &Path, index: usize) -> Child {+ Command::new(std::env::current_exe().expect("current test executable"))+ .arg(match kind {+ "identity" => "telemetry::tests::identity_process_child",+ "lifecycle-winner" | "lifecycle-contender" => "telemetry::tests::lifecycle_process_child",+ _ => panic!("unknown test child kind"),+ })+ .arg("--exact")+ .arg("--nocapture")+ .env(TEST_CHILD_KIND, kind)+ .env(TEST_CHILD_ROOT, root)+ .env(TEST_CHILD_INDEX, index.to_string())+ .env(TEST_CHILD_CANDIDATE, uuid::Uuid::new_v4().to_string())+ .spawn()+ .expect("spawn telemetry test child")+ }- unsafe { std::env::set_var(ENV_TELEMETRY_ENABLED, "0"); }- assert!(!is_enabled(), "0 must disable");+ #[test]+ fn identity_process_child() {+ if std::env::var(TEST_CHILD_KIND).ok().as_deref() != Some("identity") { return; }+ let root = PathBuf::from(std::env::var_os(TEST_CHILD_ROOT).expect("test child root"));+ let index = std::env::var(TEST_CHILD_INDEX).expect("test child index");+ let candidate = std::env::var(TEST_CHILD_CANDIDATE).expect("test child candidate");+ std::fs::write(root.join(format!("ready-{index}")), "1").expect("signal ready");+ assert!(wait_for_path(&root.join("go"), Duration::from_secs(15)));+ let path = marker_path(TELEMETRY_ID_FILE_NAME).expect("identity path");+ let id = persist_install_id_if_absent(&path, &candidate).expect("persist identity");+ std::fs::write(root.join(format!("result-{index}")), id).expect("write result");+ }- unsafe { std::env::set_var(ENV_TELEMETRY_ENABLED, "true"); }- assert!(is_enabled(), "explicit true must enable");+ #[test]+ fn lifecycle_process_child() {+ let Ok(kind) = std::env::var(TEST_CHILD_KIND) else { return; };+ if !matches!(kind.as_str(), "lifecycle-winner" | "lifecycle-contender") { return; }+ let root = PathBuf::from(std::env::var_os(TEST_CHILD_ROOT).expect("test child root"));+ let index = std::env::var(TEST_CHILD_INDEX).expect("test child index");+ let mut call = 0usize;+ capture_install_with_poster(|payload| {+ call += 1;+ std::fs::write(+ root.join(format!("event-{index}-{call}.json")),+ serde_json::to_vec(payload).expect("serialize captured event"),+ ).expect("write captured event");+ if kind == "lifecycle-winner" && call == 1 {+ std::fs::write(root.join("winner-ready"), "1").expect("signal winner ready");+ if !wait_for_path(&root.join("release-winner"), Duration::from_secs(15)) {+ return Err("parent did not release lifecycle winner".to_owned());+ }+ }+ Ok(200)+ });+ std::fs::write(+ root.join(format!("observed-id-{index}")),+ read_install_id().unwrap_or_default(),+ ).expect("write observed identity");+ }- unsafe { std::env::remove_var(ENV_TELEMETRY_ENABLED); }+ #[test]+ fn installation_identity_creation_is_atomic_across_processes() {+ let _guard = ENV_LOCK.lock().unwrap();+ with_isolated_home(|root| {+ const CHILDREN: usize = 8;+ let mut children: Vec<_> = (0..CHILDREN)+ .map(|index| spawn_test_child("identity", root, index))+ .collect();+ assert!(wait_for_children_ready(root, CHILDREN, Duration::from_secs(15)));+ std::fs::write(root.join("go"), "1").unwrap();+ for child in &mut children {+ let status = wait_for_child(child, Duration::from_secs(15));+ if status.is_none() {+ let _ = child.kill();+ let _ = child.wait();+ }+ assert!(+ status.is_some_and(|status| status.success()),+ "identity child must finish successfully"+ );+ }++ let persisted = read_install_id().expect("persisted identity");+ assert!(uuid::Uuid::parse_str(&persisted).is_ok());+ for index in 0..CHILDREN {+ let observed = std::fs::read_to_string(root.join(format!("result-{index}")))+ .expect("child result");+ assert_eq!(observed, persisted);+ }+ });}#[test]- fn is_ci_detects_known_vars() {- let _g = ENV_LOCK.lock().unwrap();- // Snapshot + clear all CI vars; restore at end.- let saved: Vec<(&str, Option<String>)> = [- "CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS",- "GITLAB_CI", "JENKINS_URL", "CIRCLECI",- ].iter()- .map(|v| (*v, std::env::var(v).ok()))- .collect();- for (v, _) in &saved { unsafe { std::env::remove_var(v); } }-- assert!(!is_ci(), "with no CI vars set, is_ci must be false");-- unsafe { std::env::set_var("GITHUB_ACTIONS", "true"); }- assert!(is_ci(), "GITHUB_ACTIONS must trigger CI detection");- unsafe { std::env::remove_var("GITHUB_ACTIONS"); }-- unsafe { std::env::set_var("CIRCLECI", "1"); }- assert!(is_ci(), "CIRCLECI must trigger CI detection");- unsafe { std::env::remove_var("CIRCLECI"); }-- // Restore.- for (v, val) in saved {- match val {- Some(s) => unsafe { std::env::set_var(v, s); },- None => unsafe { std::env::remove_var(v); },+ fn lifecycle_registration_is_single_writer_and_non_blocking_across_processes() {+ let _guard = ENV_LOCK.lock().unwrap();+ with_isolated_home(|root| {+ let mut winner = spawn_test_child("lifecycle-winner", root, 0);+ assert!(wait_for_path(&root.join("winner-ready"), Duration::from_secs(15)));++ let mut contender = spawn_test_child("lifecycle-contender", root, 1);+ let contender_status = wait_for_child(&mut contender, Duration::from_secs(5));+ if contender_status.is_none() {+ let _ = std::fs::write(root.join("release-winner"), "1");+ let _ = contender.kill();+ let _ = winner.kill();}- }+ assert!(+ contender_status.is_some_and(|status| status.success()),+ "contender must skip a busy lifecycle lock without waiting for network delivery"+ );++ std::fs::write(root.join("release-winner"), "1").unwrap();+ let winner_status = wait_for_child(&mut winner, Duration::from_secs(15));+ if winner_status.is_none() {+ let _ = winner.kill();+ let _ = winner.wait();+ }+ assert!(+ winner_status.is_some_and(|status| status.success()),+ "lifecycle winner must finish successfully"+ );++ let mut events = std::fs::read_dir(root)+ .unwrap()+ .filter_map(Result::ok)+ .filter(|entry| entry.file_name().to_string_lossy().starts_with("event-"))+ .map(|entry| serde_json::from_slice::<Value>(&std::fs::read(entry.path()).unwrap()).unwrap())+ .collect::<Vec<_>>();+ events.sort_by_key(|event| event["event"].as_str().unwrap_or_default().to_owned());+ assert_eq!(events.len(), 2);+ assert_eq!(events.iter().filter(|item| item["event"] == event::INSTALLATION_REGISTERED).count(), 1);+ assert_eq!(events.iter().filter(|item| item["event"] == event::RELEASE_INSTALLED).count(), 1);+ let persisted = read_install_id().expect("persisted identity");+ assert!(events.iter().all(|item| item["distinct_id"] == persisted));+ for index in 0..=1 {+ assert_eq!(+ std::fs::read_to_string(root.join(format!("observed-id-{index}"))).unwrap(),+ persisted+ );+ }+ assert!(root.join(HOME_SUBDIRECTORY).join(INSTALLATION_RECORDED_FILE_NAME).exists());+ assert!(release_marker_path(current_product_version()).unwrap().exists());+ });}#[test]- fn build_payload_contains_required_keys() {- let payload = build_payload(- "cua_driver_test",- Some(&serde_json::json!({"extra_key": "extra_val"})),- "test-distinct-id",- );- // Top-level envelope.- assert_eq!(payload["api_key"], POSTHOG_API_KEY);- assert_eq!(payload["event"], "cua_driver_test");- assert_eq!(payload["distinct_id"], "test-distinct-id");- assert!(payload["timestamp"].is_string());-- // Properties: default envelope + caller-provided.- let props = &payload["properties"];- assert_eq!(props["cua_driver_version"], env!("CARGO_PKG_VERSION"));- assert_eq!(props["$lib"], "cua-driver-rs");- assert_eq!(props["$lib_version"], env!("CARGO_PKG_VERSION"));- assert_eq!(props["os"], std::env::consts::OS);- assert_eq!(props["arch"], arch());- assert!(props["is_ci"].is_boolean());- assert!(props["os_version"].is_string());- // Caller-provided property survives the merge.- assert_eq!(props["extra_key"], "extra_val");-- // Privacy assertions: nothing that looks like a username,- // file path, or args should be in the payload.- let serialized = serde_json::to_string(&payload).unwrap();- for forbidden in &["$user", "username", "home_dir", "cwd", "argv"] {- assert!(!serialized.contains(forbidden),- "payload must not contain {forbidden}: {serialized}");- }+ fn precedence_is_environment_then_persisted_then_default() {+ let _guard = ENV_LOCK.lock().unwrap();+ with_isolated_home(|_| {+ assert_eq!(effective_enabled(), (true, "default"));+ set_enabled(false).unwrap();+ assert_eq!(effective_enabled(), (false, "persisted"));+ unsafe { std::env::set_var(ENV_TELEMETRY_ENABLED, "true"); }+ assert_eq!(effective_enabled(), (true, "environment"));+ unsafe { std::env::remove_var(ENV_TELEMETRY_ENABLED); }+ });}#[test]- fn build_payload_default_envelope_wins_on_key_collision() {- // If a caller tries to override a default-envelope key, the- // default-envelope value must win (mirrors Swift's insertion order).+ fn persisted_install_channel_prevents_first_run_attribution_race() {+ let _guard = ENV_LOCK.lock().unwrap();+ with_isolated_home(|root| {+ let home = root.join(HOME_SUBDIRECTORY);+ std::fs::create_dir_all(&home).unwrap();+ std::fs::write(+ home.join(TELEMETRY_INSTALL_CHANNEL_FILE_NAME),+ "install_script",+ )+ .unwrap();+ assert_eq!(install_channel(), "install_script");++ unsafe { std::env::set_var(ENV_INSTALL_CHANNEL, "update_apply"); }+ assert_eq!(install_channel(), "update_apply");+ unsafe { std::env::remove_var(ENV_INSTALL_CHANNEL); }++ std::fs::write(home.join(TELEMETRY_INSTALL_CHANNEL_FILE_NAME), "invalid").unwrap();+ assert_eq!(install_channel(), "first_run");+ });+ }++ #[test]+ fn disabled_install_makes_no_request_or_marker_and_keeps_existing_id() {+ let _guard = ENV_LOCK.lock().unwrap();+ with_isolated_home(|root| {+ let home = root.join(HOME_SUBDIRECTORY);+ std::fs::create_dir_all(&home).unwrap();+ let id = uuid::Uuid::new_v4().to_string();+ std::fs::write(home.join(TELEMETRY_ID_FILE_NAME), &id).unwrap();+ set_enabled(false).unwrap();+ unsafe { std::env::set_var(ENV_TELEMETRY_ENABLED, "false"); }+ let mut calls = 0;+ capture_install_with_poster(|_| { calls += 1; Ok(200) });+ assert_eq!(calls, 0);+ assert_eq!(read_install_id().as_deref(), Some(id.as_str()));+ assert!(!home.join(INSTALLATION_RECORDED_FILE_NAME).exists());+ assert!(!home.join(TELEMETRY_RETRY_AFTER_FILE_NAME).exists());+ unsafe { std::env::remove_var(ENV_TELEMETRY_ENABLED); }+ });+ }++ #[test]+ fn lifecycle_markers_are_written_only_after_each_2xx() {+ let _guard = ENV_LOCK.lock().unwrap();+ with_isolated_home(|root| {+ let home = root.join(HOME_SUBDIRECTORY);+ let mut calls = 0;+ capture_install_with_poster(|_| {+ calls += 1;+ if calls == 1 { Ok(200) } else { Ok(500) }+ });+ assert!(home.join(INSTALLATION_RECORDED_FILE_NAME).exists());+ assert!(!release_marker_path(current_product_version()).unwrap().exists());++ remove_file_if_exists(&home.join(TELEMETRY_RETRY_AFTER_FILE_NAME)).unwrap();+ capture_install_with_poster(|_| Ok(200));+ assert!(release_marker_path(current_product_version()).unwrap().exists());+ });+ }++ #[test]+ fn failed_lifecycle_delivery_defers_retries_without_marking_success() {+ let _guard = ENV_LOCK.lock().unwrap();+ with_isolated_home(|root| {+ let home = root.join(HOME_SUBDIRECTORY);+ let mut calls = 0;+ capture_install_with_poster(|_| {+ calls += 1;+ Ok(503)+ });+ assert_eq!(calls, 1);+ assert!(lifecycle_retry_deferred());+ assert!(!home.join(INSTALLATION_RECORDED_FILE_NAME).exists());++ capture_install_with_poster(|_| {+ calls += 1;+ Ok(200)+ });+ assert_eq!(calls, 1, "retry backoff must prevent per-command network stalls");+ });+ }++ #[test]+ fn reset_erases_identity_and_markers_but_preserves_preference() {+ let _guard = ENV_LOCK.lock().unwrap();+ with_isolated_home(|root| {+ set_enabled(false).unwrap();+ let home = root.join(HOME_SUBDIRECTORY);+ std::fs::write(home.join(TELEMETRY_ID_FILE_NAME), uuid::Uuid::new_v4().to_string()).unwrap();+ write_marker(&home.join(INSTALLATION_RECORDED_FILE_NAME)).unwrap();+ write_marker(&release_marker_path("1.2.3").unwrap()).unwrap();+ reset_id().unwrap();+ assert_eq!(persisted_enabled(), Some(false));+ assert!(read_install_id().is_none());+ assert!(!home.join(INSTALLATION_RECORDED_FILE_NAME).exists());+ });+ }++ #[test]+ fn reset_erases_legacy_identity_before_migration_can_restore_it() {+ let _guard = ENV_LOCK.lock().unwrap();+ let root = std::env::temp_dir().join(format!("cua-telemetry-reset-{}", uuid::Uuid::new_v4()));+ let current = root.join(HOME_SUBDIRECTORY);+ let legacy = root.join(LEGACY_HOME_SUBDIRECTORY);+ std::fs::create_dir_all(&legacy).unwrap();+ let legacy_id = uuid::Uuid::new_v4().to_string();+ std::fs::write(legacy.join(TELEMETRY_ID_FILE_NAME), &legacy_id).unwrap();+ std::fs::write(legacy.join(INSTALLATION_RECORDED_FILE_NAME), "1").unwrap();++ reset_id_in_homes(¤t, Some(&legacy)).unwrap();+ assert!(!current.join(TELEMETRY_ID_FILE_NAME).exists());+ assert!(!legacy.join(TELEMETRY_ID_FILE_NAME).exists());+ assert!(!legacy.join(INSTALLATION_RECORDED_FILE_NAME).exists());+ let _ = std::fs::remove_dir_all(&root);+ }++ #[test]+ fn v2_payload_has_exact_content_free_envelope_and_no_client_timestamp() {+ let identity = InstallationIdentity { id: "test-id".into(), persisted: true };let payload = build_payload(- "cua_driver_test",- Some(&serde_json::json!({"os": "fake-os", "$lib": "fake-lib"})),- "id",+ event::MCP_TOOL_COMPLETED,+ &bounded_properties(&[+ ("tool_name", Value::String("click".into())),+ ("success", Value::Bool(true)),+ ]),+ &identity,+ Transport::McpStdio,);- assert_eq!(payload["properties"]["os"], std::env::consts::OS);- assert_eq!(payload["properties"]["$lib"], "cua-driver-rs");+ assert!(payload.get("timestamp").is_none());+ let properties = payload["properties"].as_object().unwrap();+ for required in [+ "telemetry_schema_version", "product_version", "os_family", "os_major",+ "arch", "is_ci", "transport", "process_session_id", "id_persisted",+ "$process_person_profile", "$geoip_disable", "$lib", "$lib_version",+ "tool_name", "success",+ ] {+ assert!(properties.contains_key(required), "missing {required}");+ }+ let serialized = serde_json::to_string(&payload).unwrap().to_ascii_lowercase();+ for forbidden in [+ "prompt", "task_text", "arguments", "result_text", "typed_text", "clipboard",+ "screenshot", "accessibility_tree", "window_title", "application_name", "file_path",+ "url", "raw_error", "stack_trace", "initialize_payload",+ ] {+ assert!(!serialized.contains(forbidden), "payload contains {forbidden}: {serialized}");+ }}#[test]- fn install_id_persists_across_reads() {- let _g = ENV_LOCK.lock().unwrap();- // Redirect HOME to a temp dir so we don't touch the real- // `~/.cua-driver-rs`.- let tmp = std::env::temp_dir().join(format!(- "cua-driver-rs-telemetry-test-{}", uuid::Uuid::new_v4()- ));- std::fs::create_dir_all(&tmp).unwrap();- let saved_home = std::env::var_os("HOME");- let saved_userprofile = std::env::var_os("USERPROFILE");- unsafe { std::env::set_var("HOME", &tmp); }- unsafe { std::env::set_var("USERPROFILE", &tmp); }-- let first = load_or_create_install_id_uncached();- assert!(!first.is_empty());- // UUID v4 is 36 chars (8-4-4-4-12). Sanity check.- assert_eq!(first.len(), 36);-- // Second call must read from disk and return the same UUID.- let second = load_or_create_install_id_uncached();- assert_eq!(first, second, "install id must be stable across reads");-- // File must exist on disk and contain the UUID.- let id_file = tmp.join(HOME_SUBDIRECTORY).join(TELEMETRY_ID_FILE_NAME);- let on_disk = std::fs::read_to_string(&id_file).unwrap();- assert_eq!(on_disk.trim(), first);-- // Cleanup.- let _ = std::fs::remove_dir_all(&tmp);- match saved_home {- Some(s) => unsafe { std::env::set_var("HOME", s); },- None => unsafe { std::env::remove_var("HOME"); },- }- match saved_userprofile {- Some(s) => unsafe { std::env::set_var("USERPROFILE", s); },- None => unsafe { std::env::remove_var("USERPROFILE"); },+ fn inspect_events_match_the_emitted_bounded_schema() {+ let session = inspect_event(event::MCP_SESSION_STARTED).unwrap();+ let session_properties = session["properties"].as_object().unwrap();+ for field in [+ "mcp_client", "mcp_client_version_major", "protocol_version",+ "capability_tools", "capability_roots", "capability_sampling",+ "capability_experimental", "capability_elicitation_form",+ "capability_elicitation_url", "reported_provider", "reported_model",+ "reported_agent", "reported_agent_version_major",+ ] {+ assert!(session_properties.contains_key(field), "missing {field}");}++ let tool = inspect_event(event::MCP_TOOL_COMPLETED).unwrap();+ assert_eq!(tool["properties"]["duration_bucket"], "lt_10ms");+ let mcp_start = inspect_event(event::MCP_START_LEGACY).unwrap();+ assert_eq!(mcp_start["properties"]["transport"], "mcp_stdio");+ let serve_start = inspect_event(event::SERVE_START_LEGACY).unwrap();+ assert_eq!(serve_start["properties"]["transport"], "cli");}#[test]- fn iso8601_now_is_well_formed() {- let s = iso8601_now();- // YYYY-MM-DDTHH:MM:SSZ = 20 chars.- assert_eq!(s.len(), 20, "got {s:?}");- assert!(s.ends_with('Z'));- assert_eq!(&s[4..5], "-");- assert_eq!(&s[7..8], "-");- assert_eq!(&s[10..11], "T");- assert_eq!(&s[13..14], ":");- assert_eq!(&s[16..17], ":");+ fn process_session_id_is_stable_and_not_written_to_disk() {+ let _guard = ENV_LOCK.lock().unwrap();+ with_isolated_home(|root| {+ assert_eq!(process_session_id(), process_session_id());+ let on_disk = std::fs::read_dir(root.join(HOME_SUBDIRECTORY))+ .ok()+ .into_iter()+ .flatten()+ .filter_map(Result::ok)+ .any(|entry| entry.file_name().to_string_lossy().contains("session"));+ assert!(!on_disk);+ });}#[test]- fn arch_maps_aarch64_to_arm64() {- // Smoke: just confirm we don't return "aarch64" on aarch64 hosts.- let a = arch();- assert_ne!(a, "aarch64", "arm64 dashboards expect 'arm64' not 'aarch64'");- }-- /// Redirect HOME/USERPROFILE to a fresh temp dir for the duration of- /// the closure, then restore. Used by `capture_install_*` tests so- /// they don't pollute the real `~/.cua-driver-rs`.- fn with_isolated_home<R>(test: impl FnOnce(&std::path::Path) -> R) -> R {- let tmp = std::env::temp_dir().join(format!(- "cua-driver-rs-install-test-{}", uuid::Uuid::new_v4()- ));- std::fs::create_dir_all(&tmp).unwrap();- let saved_home = std::env::var_os("HOME");- let saved_userprofile = std::env::var_os("USERPROFILE");- unsafe { std::env::set_var("HOME", &tmp); }- unsafe { std::env::set_var("USERPROFILE", &tmp); }-- let result = test(&tmp);-- let _ = std::fs::remove_dir_all(&tmp);- match saved_home {- Some(s) => unsafe { std::env::set_var("HOME", s); },- None => unsafe { std::env::remove_var("HOME"); },+ fn release_version_is_bounded_and_safe_for_payloads_and_marker_paths() {+ let _guard = ENV_LOCK.lock().unwrap();+ let previous = std::env::var_os(ENV_RELEASE_VERSION);+ unsafe {+ std::env::set_var(+ ENV_RELEASE_VERSION,+ "v1.2.3/../../private path?token=secret-and-more",+ );}- match saved_userprofile {- Some(s) => unsafe { std::env::set_var("USERPROFILE", s); },- None => unsafe { std::env::remove_var("USERPROFILE"); },+ assert_eq!(release_version(), current_product_version());+ assert!(!release_version().contains("secret"));+ unsafe {+ match previous {+ Some(value) => std::env::set_var(ENV_RELEASE_VERSION, value),+ None => std::env::remove_var(ENV_RELEASE_VERSION),+ }}- result}#[test]- fn capture_install_does_not_write_marker_when_post_fails() {- // The whole point of the sync install path: if the POST fails,- // the marker must NOT be written, so the next launch retries.- let _g = ENV_LOCK.lock().unwrap();- with_isolated_home(|home| {- let marker = home.join(HOME_SUBDIRECTORY).join(INSTALLATION_RECORDED_FILE_NAME);- assert!(!marker.exists(), "precondition: marker must not exist");-- capture_install_with_poster(|_payload| {- Err("simulated network failure".to_owned())- });+ fn cli_duration_buckets_have_fixed_boundaries() {+ assert_eq!(duration_bucket(Duration::from_millis(99)), "lt_100ms");+ assert_eq!(duration_bucket(Duration::from_millis(100)), "100_499ms");+ assert_eq!(duration_bucket(Duration::from_millis(500)), "500ms_1_999ms");+ assert_eq!(duration_bucket(Duration::from_secs(2)), "2s_9_999ms");+ assert_eq!(duration_bucket(Duration::from_secs(10)), "gte_10s");+ }- assert!(!marker.exists(),- "marker must NOT be written when POST returns Err");- });+ #[test]+ fn release_versions_accept_strict_semver_and_drop_leading_v() {+ assert_eq!(strict_release_version("v1.2.3"), Some("1.2.3".into()));+ assert_eq!(strict_release_version("1.2.3-rc.1"), Some("1.2.3-rc.1".into()));+ assert_eq!(strict_release_version("1.2"), None);+ assert_eq!(strict_release_version("1.2.3+private"), None);+ }++ #[test]+ fn reported_models_are_coarse_fixed_categories() {+ assert_eq!(normalize_model(Some("claude-opus-4-1")), "claude_opus");+ assert_eq!(normalize_model(Some("gpt-5.2-codex")), "gpt_5");+ assert_eq!(normalize_model(Some("gpt-private_secret")), "custom");+ assert!(!normalize_model(Some("gpt-private_secret")).contains("secret"));}#[test]- fn capture_install_does_not_write_marker_when_post_returns_non_2xx() {- // PostHog returning e.g. 500 must also be treated as failure.- let _g = ENV_LOCK.lock().unwrap();- with_isolated_home(|home| {- let marker = home.join(HOME_SUBDIRECTORY).join(INSTALLATION_RECORDED_FILE_NAME);-- capture_install_with_poster(|_payload| Ok(500u16));- assert!(!marker.exists(),- "marker must NOT be written on 5xx response");-- capture_install_with_poster(|_payload| Ok(401u16));- assert!(!marker.exists(),- "marker must NOT be written on 4xx response");+ fn pending_send_flush_waits_for_bounded_delivery() {+ let _guard = ENV_LOCK.lock().unwrap();+ assert_eq!(PENDING_SENDS.load(Ordering::SeqCst), 0);+ PENDING_SENDS.fetch_add(1, Ordering::SeqCst);+ std::thread::spawn(|| {+ std::thread::sleep(Duration::from_millis(20));+ finish_pending_send();});+ flush_pending(Duration::from_secs(1));+ assert_eq!(PENDING_SENDS.load(Ordering::SeqCst), 0);}+ #[test]+ fn cli_command_values_are_fixed() {+ assert_eq!(fixed_cli_command("call"), "call");+ assert_eq!(fixed_cli_command("private-customer-command"), "other");+ }}diff --git a/libs/cua-driver/rust/crates/cua-driver/src/updater.rs b/libs/cua-driver/rust/crates/cua-driver/src/updater.rsindex 0626209f59..4e10dd05d3 100644--- a/libs/cua-driver/rust/crates/cua-driver/src/updater.rs+++ b/libs/cua-driver/rust/crates/cua-driver/src/updater.rs@@ -37,6 +37,8 @@ const CANONICAL_INSTALL_PS1: &str =/// bare version like `"0.2.18"` (no `cua-driver-rs-v` prefix). See/// `libs/cua-driver/scripts/_install-rust.sh` + `install.ps1`.const VERSION_PIN_ENV: &str = "CUA_DRIVER_RS_VERSION";+const INSTALL_CHANNEL_ENV: &str = "CUA_DRIVER_INSTALL_CHANNEL";+const RELEASE_VERSION_ENV: &str = "CUA_DRIVER_RELEASE_VERSION";/// Invoke the canonical installer pinned to `version`. Returns the/// installer's exit status so the caller can produce the right@@ -52,6 +54,8 @@ pub fn run_install_script(version: &str) -> std::io::Result<ExitStatus> {let pwsh_cmd = format!("iwr -useb {CANONICAL_INSTALL_PS1} | iex");Command::new("powershell.exe").env(VERSION_PIN_ENV, version)+ .env(INSTALL_CHANNEL_ENV, "update_apply")+ .env(RELEASE_VERSION_ENV, version).args(["-NoProfile","-ExecutionPolicy",@@ -69,6 +73,8 @@ pub fn run_install_script(version: &str) -> std::io::Result<ExitStatus> {let bash_cmd = format!("curl -fsSL {CANONICAL_INSTALL_SH} | bash");Command::new("bash").env(VERSION_PIN_ENV, version)+ .env(INSTALL_CHANNEL_ENV, "update_apply")+ .env(RELEASE_VERSION_ENV, version).args(["-c", &bash_cmd]).status()}diff --git a/libs/cua-driver/rust/crates/cua-driver/tests/installed_app_textedit_macos_test.rs b/libs/cua-driver/rust/crates/cua-driver/tests/installed_app_textedit_macos_test.rsindex a09abbe93e..62efeaefde 100644--- a/libs/cua-driver/rust/crates/cua-driver/tests/installed_app_textedit_macos_test.rs+++ b/libs/cua-driver/rust/crates/cua-driver/tests/installed_app_textedit_macos_test.rs@@ -57,29 +57,40 @@ fn background_type_on_native_cocoa_is_ax_verified() {launch.text());let pid = launch.structured()["pid"].as_i64().expect("TextEdit pid");- let windows = launch.structured()["windows"]+ let mut windows = launch.structured()["windows"].as_array().cloned().unwrap_or_default();- let wid = windows- .first()- .and_then(|window| window["window_id"].as_u64())- .expect("TextEdit opened no window");+ assert!(!windows.is_empty(), "TextEdit opened no window");- // Find the AXTextArea.- let state = driver.call(- "get_window_state",- serde_json::json!({ "pid": pid, "window_id": wid, "capture_mode": "ax" }),- );- let el = state.structured()["elements"]- .as_array()- .and_then(|elements| {- elements- .iter()- .find(|element| element["role"] == "AXTextArea")- .and_then(|element| element["element_index"].as_u64())+ // TextEdit can retain an off-screen restoration window alongside the+ // visible blank document. WindowServer does not guarantee their order,+ // so prefer visible windows and select the one that actually exposes+ // the editor instead of assuming `windows[0]` is the document.+ windows.sort_by_key(|window| !window["is_on_screen"].as_bool().unwrap_or(false));+ let (wid, el) = windows+ .iter()+ .filter_map(|window| window["window_id"].as_u64())+ .find_map(|window_id| {+ let state = driver.call(+ "get_window_state",+ serde_json::json!({+ "pid": pid,+ "window_id": window_id,+ "capture_mode": "ax"+ }),+ );+ state.structured()["elements"]+ .as_array()+ .and_then(|elements| {+ elements+ .iter()+ .find(|element| element["role"] == "AXTextArea")+ .and_then(|element| element["element_index"].as_u64())+ })+ .map(|element_index| (window_id, element_index))})- .expect("TextEdit AXTextArea");+ .expect("TextEdit opened no window containing an AXTextArea");let (typed, mut passed) = run_with_background_oracles(&mut driver,diff --git a/libs/cua-driver/scripts/README.md b/libs/cua-driver/scripts/README.mdindex f995a109b7..41a07800eb 100644--- a/libs/cua-driver/scripts/README.md+++ b/libs/cua-driver/scripts/README.md@@ -12,5 +12,12 @@ Install, uninstall, local-build, and VM sync helpers for cua-driver.| `sync-vm-worktree.sh` | Sync this checkout to verification VMs and pull artifacts back || `post-install-hints.txt` | User-facing hints printed by install scripts |+Released installers show a telemetry notice before asking the installed binary+to record anything. Telemetry is enabled by default and can be persistently+disabled with `cua-driver telemetry disable`. Installation events use the same+consent decision as routine events. A normal uninstall preserves the pseudonymous+installation ID and preference for a future reinstall; use `--purge` on Unix,+or set `CUA_DRIVER_RS_UNINSTALL_PURGE=1` on Windows, to delete them.+Keep source commits host-owned. Verification machines should sync from thischeckout and return artifacts, not push code.diff --git a/libs/cua-driver/scripts/_install-local-rust.sh b/libs/cua-driver/scripts/_install-local-rust.shindex dd6c9d6d3d..cbf6a52483 100755--- a/libs/cua-driver/scripts/_install-local-rust.sh+++ b/libs/cua-driver/scripts/_install-local-rust.sh@@ -144,6 +144,14 @@ CURRENT_LINK="$HOME_DIR/packages/current"# and-braces — keeps the home dir layout single-rooted for the user.LEGACY_HOME_DIR="$HOME/.cua-driver-rs"if [ -d "$LEGACY_HOME_DIR" ] && [ "$HOME_DIR" != "$LEGACY_HOME_DIR" ]; then+ mkdir -p "$HOME_DIR"+ for telemetry_file in .telemetry_id .installation_recorded; do+ if [ -f "$LEGACY_HOME_DIR/$telemetry_file" ] && [ ! -e "$HOME_DIR/$telemetry_file" ]; then+ cp -p "$LEGACY_HOME_DIR/$telemetry_file" "$HOME_DIR/$telemetry_file" 2>/dev/null \+ && echo " Preserved legacy telemetry state $telemetry_file" \+ || echo " Could not preserve legacy telemetry state $telemetry_file"+ fi+ doneecho " Sweeping legacy install dir $LEGACY_HOME_DIR"rm -rf "$LEGACY_HOME_DIR"fi@@ -271,20 +279,24 @@ echo ""# We create a self-signed code-signing cert once (idempotent, in the login# keychain) and reuse it. Local dev only; releases are CI-signed.#-# Echoes the `codesign --sign` argument: the cert CN when available, or "-"-# (ad-hoc) when it can't be created — no codesign/openssl, CI, locked keychain.+# Echoes the `codesign --sign` argument: the valid identity's SHA-1 when+# available, or "-" when it can't be created — no codesign/openssl, CI,+# locked keychain. Use the identity hash rather than the certificate name:+# stale certificate-only duplicates can share the same name and make codesign+# reject an otherwise valid identity as ambiguous.CUA_LOCAL_SIGN_CN="CuaDriver Local Signing (cua-driver-rs)"ensure_local_signing_identity() {{ [ "$OS" = "Darwin" ] && command -v codesign >/dev/null 2>&1; } || { printf -- '-'; return; }- # Reuse if already present (find-certificate finds it regardless of trust;- # `find-identity -v` would miss an untrusted self-signed cert).- if security find-certificate -c "$CUA_LOCAL_SIGN_CN" >/dev/null 2>&1; then- printf '%s' "$CUA_LOCAL_SIGN_CN"; return- fi- command -v openssl >/dev/null 2>&1 || { printf -- '-'; return; }local kc="$HOME/Library/Keychains/login.keychain-db"[ -f "$kc" ] || kc="$HOME/Library/Keychains/login.keychain"[ -f "$kc" ] || { printf -- '-'; return; }+ local identity+ identity="$(security find-identity -v -p codesigning "$kc" 2>/dev/null \+ | awk -v cn="$CUA_LOCAL_SIGN_CN" 'index($0, "\"" cn "\"") { print $2; exit }')"+ if [ -n "$identity" ]; then+ printf '%s' "$identity"; return+ fi+ command -v openssl >/dev/null 2>&1 || { printf -- '-'; return; }local tmp; tmp="$(mktemp -d)" || { printf -- '-'; return; }printf '[req]\ndistinguished_name=dn\nx509_extensions=ext\nprompt=no\n[dn]\nCN=%s\n[ext]\nbasicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature\nextendedKeyUsage=critical,codeSigning\n' \"$CUA_LOCAL_SIGN_CN" > "$tmp/req.cnf"@@ -301,8 +313,13 @@ ensure_local_signing_identity() {|| openssl pkcs12 -export -inkey "$tmp/key.pem" -in "$tmp/cert.pem" \-out "$tmp/id.p12" -passout pass:"$pw" -name "$CUA_LOCAL_SIGN_CN" >/dev/null 2>&1; } \&& security import "$tmp/id.p12" -k "$kc" -P "$pw" -A -T /usr/bin/codesign >/dev/null 2>&1; then+ identity="$(security find-identity -v -p codesigning "$kc" 2>/dev/null \+ | awk -v cn="$CUA_LOCAL_SIGN_CN" 'index($0, "\"" cn "\"") { print $2; exit }')"rm -rf "$tmp"- printf '%s' "$CUA_LOCAL_SIGN_CN"; return+ if [ -n "$identity" ]; then+ printf '%s' "$identity"; return+ fi+ printf -- '-'; returnfirm -rf "$tmp"printf -- '-'diff --git a/libs/cua-driver/scripts/_install-rust.sh b/libs/cua-driver/scripts/_install-rust.shindex cea0b6beb7..97468b37f1 100644--- a/libs/cua-driver/scripts/_install-rust.sh+++ b/libs/cua-driver/scripts/_install-rust.sh@@ -607,6 +607,18 @@ cleanup_prior_local_installmkdir -p "$BIN_DIR"+# Persist the bounded installer channel before the new binary becomes visible.+# If the user invokes Cua Driver before the detached install-event hook wins+# the lifecycle lock, the ordinary first-run path will still use the installer+# attribution. The runtime removes this hint after lifecycle delivery succeeds.+INSTALL_CHANNEL="${CUA_DRIVER_INSTALL_CHANNEL:-install_script}"+case "$INSTALL_CHANNEL" in+ install_script|update_apply|python_package|first_run) ;;+ *) INSTALL_CHANNEL="install_script" ;;+esac+mkdir -p "$HOME_DIR"+printf '%s\n' "$INSTALL_CHANNEL" > "$HOME_DIR/.telemetry_install_channel"+# macOS: install the .app to /Applications first, then symlink the# bin into the bundle so `~/.local/bin/cua-driver` resolves into# `/Applications/CuaDriver.app/Contents/MacOS/cua-driver`. The@@ -752,6 +764,14 @@ fi# skipped when the user pinned CUA_DRIVER_RS_HOME to the legacy path on# purpose. Best-effort + idempotent.if [[ -d "$LEGACY_HOME_DIR" && "$HOME_DIR" != "$LEGACY_HOME_DIR" ]]; then+ mkdir -p "$HOME_DIR"+ for telemetry_file in .telemetry_id .installation_recorded; do+ if [[ -f "$LEGACY_HOME_DIR/$telemetry_file" && ! -e "$HOME_DIR/$telemetry_file" ]]; then+ cp -p "$LEGACY_HOME_DIR/$telemetry_file" "$HOME_DIR/$telemetry_file" 2>/dev/null \+ && log "preserved legacy telemetry state $telemetry_file" \+ || log "note: could not preserve legacy telemetry state $telemetry_file"+ fi+ donerm -rf "$LEGACY_HOME_DIR" 2>/dev/null \&& log "swept legacy package home $LEGACY_HOME_DIR (reconciled onto $HOME_DIR)" \|| log "note: could not fully remove legacy package home $LEGACY_HOME_DIR (best-effort)"@@ -776,21 +796,24 @@ show_cua_driver_daemon_survivors# matching GitHub release. The post-install hint below points at the# verb.-# --- Fire the one-shot install telemetry ping ----------------------------#-# Anonymous adoption signal — sends `cua_driver_install` to PostHog-# exactly once per install (guarded by ~/.cua-driver/.installation_recorded-# on the binary side). The Rust port keeps its install signal independent-# of the Swift `cua-driver` install (separate marker dir + separate env var)-# so users can opt out of one without affecting the other.+# --- Record consent-aware install telemetry -----------------------------#-# Bypasses the CUA_DRIVER_RS_TELEMETRY_ENABLED check by design — see-# `telemetry::capture_install()` for the rationale (count adoption even-# when users opt out immediately after install). Every subsequent event-# from the binary respects the opt-out normally.+# Telemetry is default-on, but the binary applies the same effective consent+# policy to installation events as every other event: environment override,+# then the persisted preference, then the default. It records the pseudonymous+# installation once and the installed release once per version. The channel+# is a fixed enum so an inherited/user-controlled value cannot fragment the+# dashboard.## Background + redirect so a slow / failed POST never blocks the install.-"$BIN_LINK" telemetry install-event >/dev/null 2>&1 &+echo "Telemetry defaults to enabled for new installations; saved preferences and environment overrides are honored."+echo "When enabled, Cua collects a pseudonymous installation ID and bounded, content-free usage metadata."+echo " No prompts, tool arguments, screen contents, or file paths are collected."+echo " Disable persistently at any time: $BIN_LINK telemetry disable"++CUA_DRIVER_INSTALL_CHANNEL="$INSTALL_CHANNEL" \+CUA_DRIVER_RELEASE_VERSION="$VERSION" \+ "$BIN_LINK" telemetry install-event >/dev/null 2>&1 &disown 2>/dev/null || true# Auto-extend PATH for users whose shell doesn't already include BIN_DIR.diff --git a/libs/cua-driver/scripts/install.ps1 b/libs/cua-driver/scripts/install.ps1index d38f2acbce..5ba2df247a 100644--- a/libs/cua-driver/scripts/install.ps1+++ b/libs/cua-driver/scripts/install.ps1@@ -1035,6 +1035,14 @@ function Remove-LegacyInstall {# 4. Remove the legacy package home tree.if (Test-Path -LiteralPath $LegacyHomeDir) {try {+ New-Item -ItemType Directory -Force -Path $HomeDir | Out-Null+ foreach ($telemetryFile in @('.telemetry_id', '.installation_recorded')) {+ $legacyTelemetryPath = Join-Path $LegacyHomeDir $telemetryFile+ $currentTelemetryPath = Join-Path $HomeDir $telemetryFile+ if ((Test-Path -LiteralPath $legacyTelemetryPath) -and -not (Test-Path -LiteralPath $currentTelemetryPath)) {+ Copy-Item -LiteralPath $legacyTelemetryPath -Destination $currentTelemetryPath -Force -ErrorAction Stop+ }+ }Remove-Item -LiteralPath $LegacyHomeDir -Recurse -Force -ErrorAction Stop} catch {Write-Host " (could not remove $LegacyHomeDir : $($_.Exception.Message))" -ForegroundColor Yellow@@ -1106,6 +1114,19 @@ if (-not $skipDownload) {}}+# Persist the bounded installer channel before the new junction target becomes+# visible. If a user command wins the lifecycle lock before the detached hook,+# the runtime reads this hint and preserves installer attribution. It removes+# the hint after lifecycle delivery succeeds.+$allowedChannels = @("install_script", "update_apply", "python_package", "first_run")+$installChannel = $env:CUA_DRIVER_INSTALL_CHANNEL+if (-not $installChannel -or $installChannel -notin $allowedChannels) {+ $installChannel = "install_script"+}+New-Item -ItemType Directory -Force -Path $HomeDir | Out-Null+Set-Content -LiteralPath (Join-Path $HomeDir '.telemetry_install_channel') `+ -Value $installChannel -Encoding Ascii -NoNewline+# Wire up the junction chain. The inner junction (current → releases\<v>)# is what makes the upgrade atomic; the outer junction (bin → current)# is what gives users a stable PATH entry.@@ -1119,16 +1140,42 @@ Ensure-Junction $VisibleBinDir $CurrentDir$keepVersions = Resolve-KeepVersionsInvoke-OldReleasesGc -releasesDir $ReleasesDir -currentDir $CurrentDir -target $target -keep $keepVersions-# ---------- Fire-and-forget install telemetry ping ------------------------+# ---------- Record consent-aware install telemetry ------------------------#-# Same shape as the Linux install.sh path: invoke `cua-driver telemetry-# install-event` once per install. The binary itself guards against-# double-counting via ~\.cua-driver-rs\.installation_recorded.+# Same shape as the Unix installer. The binary applies the normal effective+# consent policy, preserves the v1 registration marker, and records this+# release once per version. Keep the channel bounded before allowing it into+# analytics.$installedBinary = Join-Path $VisibleBinDir $BinaryNameif (Test-Path -LiteralPath $installedBinary) {+ Write-Host "Telemetry defaults to enabled for new installations; saved preferences and environment overrides are honored." -ForegroundColor Cyan+ Write-Host "When enabled, Cua collects a pseudonymous installation ID and bounded, content-free usage metadata." -ForegroundColor Cyan+ Write-Host " No prompts, tool arguments, screen contents, or file paths are collected."+ Write-Host " Disable persistently at any time: $installedBinary telemetry disable"try {- Start-Process -FilePath $installedBinary -ArgumentList "telemetry","install-event" `- -WindowStyle Hidden -ErrorAction SilentlyContinue | Out-Null+ # install.ps1 commonly runs via `irm | iex` in the caller's shell.+ # Restore both variables after Start-Process snapshots the environment+ # so the install does not leak transient attribution into that shell.+ $savedChannel = $env:CUA_DRIVER_INSTALL_CHANNEL+ $savedReleaseVersion = $env:CUA_DRIVER_RELEASE_VERSION+ try {+ $env:CUA_DRIVER_INSTALL_CHANNEL = $installChannel+ $env:CUA_DRIVER_RELEASE_VERSION = $version+ Start-Process -FilePath $installedBinary -ArgumentList "telemetry","install-event" `+ -WindowStyle Hidden -ErrorAction SilentlyContinue | Out-Null+ }+ finally {+ if ($null -eq $savedChannel) {+ Remove-Item Env:CUA_DRIVER_INSTALL_CHANNEL -ErrorAction SilentlyContinue+ } else {+ $env:CUA_DRIVER_INSTALL_CHANNEL = $savedChannel+ }+ if ($null -eq $savedReleaseVersion) {+ Remove-Item Env:CUA_DRIVER_RELEASE_VERSION -ErrorAction SilentlyContinue+ } else {+ $env:CUA_DRIVER_RELEASE_VERSION = $savedReleaseVersion+ }+ }}catch {# Ignore — telemetry must never block install.diff --git a/libs/cua-driver/scripts/uninstall.ps1 b/libs/cua-driver/scripts/uninstall.ps1index eb0af18285..46af92ef69 100644--- a/libs/cua-driver/scripts/uninstall.ps1+++ b/libs/cua-driver/scripts/uninstall.ps1@@ -1,4 +1,4 @@-# cua-driver-rs uninstaller (Windows) — removes everything install.ps1+# cua-driver-rs uninstaller (Windows) — removes the runtime installed by install.ps1# laid down: the Scheduled Task autostart entry, running daemon# processes, the directory junctions wiring the visible bin dir back to# a per-version release dir, the entire package home tree, and any skill@@ -26,11 +26,9 @@# the binary directory open during the delete pass)# - <visibleBinDir> = %LOCALAPPDATA%\Programs\Cua\cua-driver\bin (directory junction)# - <currentDir> = %USERPROFILE%\.cua-driver\packages\current (directory junction)-# - <packageHome> = %USERPROFILE%\.cua-driver\ (entire tree:-# releases, lockfile,-# telemetry id,-# install marker,-# version_check.json)+# - <packageHome>\packages and runtime artifacts. The pseudonymous telemetry+# id, preference, and registration markers are preserved unless purge is+# explicitly requested.# - Skill junctions under:# %USERPROFILE%\.claude\skills\cua-driver-rs# %USERPROFILE%\.agents\skills\cua-driver-rs@@ -61,6 +59,10 @@# working install. Inherited automatically by the elevated# re-exec child (see Elevation below).#+# Env (purge identity + preference):+# $env:CUA_DRIVER_RS_UNINSTALL_PURGE = '1'+# also delete the package home after removing the runtime.+## Elevation:# `install.ps1 -AutoStart` (and `cua-driver autostart enable`) register# the `cua-driver-serve` Scheduled Task at RunLevel=Highest — the@@ -85,6 +87,7 @@ $ProgressPreference = "SilentlyContinue"# Env var also inherits across the self-elevation re-exec automatically,# so we don't need to plumb -Force through -ArgumentList.$Force = [bool]$env:CUA_DRIVER_RS_UNINSTALL_FORCE+$Purge = $env:CUA_DRIVER_RS_UNINSTALL_PURGE -match '^(1|true|yes|on)$'# ---------- Elevation pre-check -------------------------------------------@@ -345,24 +348,41 @@ if (Test-Path -LiteralPath $CurrentDir) {}}-# 5. Entire package home ($HomeDir). Contains releases\, lockfile,-# telemetry id, install marker, version_check.json, and the now--# removed current\ junction.+# 5. Package home. A normal uninstall removes runtime-owned payloads while+# preserving the pseudonymous installation id, persisted preference, and+# install/release markers. Purge is the explicit identity reset.if (Test-Path -LiteralPath $HomeDir) {- if (Confirm-Remove "package home tree $HomeDir (releases, lockfile, telemetry id, install marker)") {- # -Recurse -Force walks into every subdir and clears read-only- # bits. ErrorAction SilentlyContinue tolerates leftover handles- # (rare after step 2's process kill); we log a follow-up if- # anything survived.- Remove-Item -LiteralPath $HomeDir -Force -Recurse -ErrorAction SilentlyContinue- if (Test-Path -LiteralPath $HomeDir) {- Write-WarningStep "$HomeDir was not fully removed — some files may still be locked."- Write-WarningStep " Close any open cua-driver processes / shells with cwd inside the tree and re-run."+ $removalLabel = if ($Purge) {+ "package home tree $HomeDir (including telemetry identity and preference)"+ } else {+ "runtime packages under $HomeDir (preserve telemetry identity and preference)"+ }+ if (Confirm-Remove $removalLabel) {+ if ($Purge) {+ Remove-Item -LiteralPath $HomeDir -Force -Recurse -ErrorAction SilentlyContinue+ if (Test-Path -LiteralPath $HomeDir) {+ Write-WarningStep "$HomeDir was not fully removed — some files may still be locked."+ Write-WarningStep " Close any open cua-driver processes / shells with cwd inside the tree and re-run."+ } else {+ Write-Step "purged $HomeDir (including telemetry identity and preference)"+ }} else {- Write-Step "removed $HomeDir"+ foreach ($runtimePath in @(+ $PackagesDir,+ (Join-Path $HomeDir "skills"),+ (Join-Path $HomeDir ".tcc-signing-identity"),+ (Join-Path $HomeDir "serve.out.log"),+ (Join-Path $HomeDir "serve.err.log")+ )) {+ if (Test-Path -LiteralPath $runtimePath) {+ Remove-Item -LiteralPath $runtimePath -Force -Recurse -ErrorAction SilentlyContinue+ }+ }+ Write-Step "removed runtime payloads from $HomeDir"+ Write-Step "preserved telemetry identity, preference, and registration markers"}} else {- Write-Step "skipped $HomeDir (user declined)"+ Write-Step "skipped package-home cleanup (user declined)"}} else {Write-Step "no package home at $HomeDir (skipping)"@@ -393,13 +413,29 @@ if ((Test-Path -LiteralPath $LegacyVendorDir) -and -not (Get-ChildItem -LiteralPRemove-Item -LiteralPath $LegacyVendorDir -Force -ErrorAction SilentlyContinueWrite-Step "removed empty legacy vendor dir $LegacyVendorDir"}-# Legacy package home+# Legacy package home. Preserve telemetry state on a normal uninstall so a+# future runtime can migrate the same pseudonymous identity to ~/.cua-driver.if (Test-Path -LiteralPath $LegacyHomeDir) {- Remove-Item -LiteralPath $LegacyHomeDir -Force -Recurse -ErrorAction SilentlyContinue- if (Test-Path -LiteralPath $LegacyHomeDir) {- Write-WarningStep "$LegacyHomeDir was not fully removed — some files may still be locked."+ if ($Purge) {+ Remove-Item -LiteralPath $LegacyHomeDir -Force -Recurse -ErrorAction SilentlyContinue+ if (Test-Path -LiteralPath $LegacyHomeDir) {+ Write-WarningStep "$LegacyHomeDir was not fully removed — some files may still be locked."+ } else {+ Write-Step "purged legacy package home $LegacyHomeDir"+ }} else {- Write-Step "removed legacy package home $LegacyHomeDir"+ foreach ($legacyRuntimePath in @(+ (Join-Path $LegacyHomeDir "packages"),+ (Join-Path $LegacyHomeDir "skills"),+ (Join-Path $LegacyHomeDir ".tcc-signing-identity"),+ (Join-Path $LegacyHomeDir "serve.out.log"),+ (Join-Path $LegacyHomeDir "serve.err.log")+ )) {+ if (Test-Path -LiteralPath $legacyRuntimePath) {+ Remove-Item -LiteralPath $legacyRuntimePath -Force -Recurse -ErrorAction SilentlyContinue+ }+ }+ Write-Step "removed legacy runtime payloads and preserved legacy telemetry state"}}@@ -424,6 +460,14 @@ foreach ($skillLink in $SkillJunctions) {Write-Host ""Write-Host "cua-driver-rs uninstalled." -ForegroundColor GreenWrite-Host ""+if (-not $Purge) {+ Write-Host "Telemetry identity and preference were preserved for a future reinstall." -ForegroundColor Cyan+ Write-Host "To delete them too, re-run with:"+ Write-Host ""+ Write-Host " `$env:CUA_DRIVER_RS_UNINSTALL_PURGE = '1'"+ Write-Host " irm https://cua.ai/driver/uninstall.ps1 | iex"+ Write-Host ""+}Write-Host "Claude Code MCP registrations:" -ForegroundColor YellowWrite-Host " We don't auto-edit ~/.claude.json on Windows. If you registered cua-driver-rs"Write-Host " with Claude Code, remove it manually:"diff --git a/libs/cua-driver/scripts/uninstall.sh b/libs/cua-driver/scripts/uninstall.shindex 9c94dcefd4..c0a4d138d0 100755--- a/libs/cua-driver/scripts/uninstall.sh+++ b/libs/cua-driver/scripts/uninstall.sh@@ -23,8 +23,9 @@# Linux:# - ~/.local/bin/cua-driver symlink (only when it resolves to a# cua-driver path — a Swift-driver symlink is left in place)-# - ~/.cua-driver/ (current package home) + legacy ~/.cua-driver-rs/-# (telemetry id, config.json, versioned releases, current symlink)+# - versioned packages/current symlink under ~/.cua-driver/+# - telemetry id, preference, and registration markers are preserved by+# default so a reinstall remains the same pseudonymous installation# - ~/.config/systemd/user/cua-driver-rs.service (if --autostart# was used via install-local.sh — stop + disable + remove)# - Skill symlinks under ~/.claude/skills/cua-driver(-rs), ~/.agents/@@ -33,7 +34,8 @@# - /Applications/CuaDriver.app bundle (+ legacy CuaDriverRs.app)# - ~/.local/bin/cua-driver symlink (only when it resolves into# /Applications/CuaDriver.app)-# - ~/.cua-driver/ (current package home) + legacy ~/.cua-driver-rs/+# - runtime payloads under ~/.cua-driver/ and legacy ~/.cua-driver-rs/;+# telemetry state remains unless --purge is passed# - ~/Library/LaunchAgents/com.trycua.cua-driver-rs.plist (if# --autostart was used via install-local.sh — unload + remove)# - Skill symlinks under ~/.claude/skills/cua-driver(-rs), etc.@@ -42,7 +44,7 @@# symlink use the same bundle id (com.trycua.driver) as the Swift driver,# so they're only removed when an unambiguous Rust marker is on disk# (~/.cua-driver/packages/, legacy ~/.cua-driver-rs/, CuaDriverRs.app,-# or the LaunchAgent/systemd unit).+# the LaunchAgent/systemd unit, or current Rust telemetry state).## Also scrubs Claude MCP registrations in ~/.claude.json that match# the active backend.@@ -53,9 +55,11 @@## Usage:# /bin/bash -c "$(curl -fsSL https://cua.ai/driver/uninstall.sh)"+# /bin/bash -c "$(curl -fsSL https://cua.ai/driver/uninstall.sh)" -- --purge## Env overrides (mirror install side):-# CUA_DRIVER_RS_HOME Rust package home to remove (default ~/.cua-driver-rs)+# CUA_DRIVER_HOME Rust package home to remove (default ~/.cua-driver)+# CUA_DRIVER_RS_HOME Legacy alias for CUA_DRIVER_HOMEset -euo pipefail# ----------------------------------------------------------------------@@ -65,6 +69,7 @@ set -euo pipefail# ----------------------------------------------------------------------USE_RUST_BACKEND=1RESET_TCC=1+PURGE_DATA=0FORWARDED_ARGS=()PASSTHROUGH=0while [[ $# -gt 0 ]]; do@@ -77,6 +82,7 @@ while [[ $# -gt 0 ]]; do--backend=swift) shift ;; # retired Swift (no-op)--reset-tcc) RESET_TCC=1; shift ;; # legacy/explicit default: revoke TCC grants--keep-tcc) RESET_TCC=0; shift ;; # preserve TCC grants across reinstall+ --purge) PURGE_DATA=1; shift ;; # also delete pseudonymous identity + preference--backend=*)printf 'error: unknown backend %q; supported: rust\n' "${1#*=}" >&2exit 2@@ -194,8 +200,10 @@ if [[ "$USE_RUST_BACKEND" == "1" ]]; then# - ~/.cua-driver-rs/ exists (legacy Rust state dir, pre-rename)# - /Applications/CuaDriverRs.app exists (legacy bundle, pre-rename)# - LaunchAgent plist / systemd unit exists (autostart was used)+ # - current telemetry identity/registration marker exists (release+ # installs on macOS live in /Applications and have no packages dir)RUST_INSTALL_PRESENT=0- if [[ -d "$PACKAGES_DIR" || -d "$LEGACY_HOME_DIR" || -d "$LEGACY_APP_BUNDLE" || -f "$LAUNCHAGENT_PLIST" || -f "$SYSTEMD_USER_UNIT" ]]; then+ if [[ -d "$PACKAGES_DIR" || -d "$LEGACY_HOME_DIR" || -d "$LEGACY_APP_BUNDLE" || -f "$LAUNCHAGENT_PLIST" || -f "$SYSTEMD_USER_UNIT" || -f "$HOME_DIR/.telemetry_id" || -f "$HOME_DIR/.installation_recorded" ]]; thenRUST_INSTALL_PRESENT=1fi@@ -301,25 +309,49 @@ if [[ "$USE_RUST_BACKEND" == "1" ]]; thenfi# --- Package home ---- # Everything under $HOME_DIR (default ~/.cua-driver): telemetry id,- # config.json, versioned releases, current symlink, local skill copy,- # version_check.json cache. This is the live runtime home now (post- # v0.2.16 rename), so gate its removal on the Rust marker — don't nuke- # a Swift-only Mac's ~/.cua-driver/config.json on a mistaken run.+ # A normal uninstall deliberately keeps the pseudonymous installation ID,+ # persisted telemetry preference, and install/release markers. This lets a+ # later reinstall be counted as a returning installation without sending+ # any events while disabled. `--purge` is the explicit identity reset.+ # All removal remains gated on the Rust marker so a mistaken invocation+ # cannot damage a Swift-only Mac's shared ~/.cua-driver state.if [[ -d "$HOME_DIR" ]]; then- if [[ "$RUST_INSTALL_PRESENT" == "1" ]]; then- rm -rf "$HOME_DIR"- log "removed $HOME_DIR"+ if [[ "$RUST_INSTALL_PRESENT" == "1" || "$PURGE_DATA" == "1" ]]; then+ if [[ "$PURGE_DATA" == "1" ]]; then+ rm -rf "$HOME_DIR"+ log "purged $HOME_DIR (including telemetry identity and preference)"+ else+ # Remove only installer/runtime-owned payloads. Unknown files+ # and all telemetry state remain untouched.+ rm -rf "$HOME_DIR/packages" "$HOME_DIR/skills"+ rm -f \+ "$HOME_DIR/.tcc-signing-identity" \+ "$HOME_DIR/serve.out.log" \+ "$HOME_DIR/serve.err.log"+ log "removed runtime payloads from $HOME_DIR"+ log "preserved telemetry identity, preference, and registration markers"+ fielselog "$HOME_DIR exists but no Rust marker on disk; leaving it (looks like a Swift-only / shared config dir)"fielselog "no package home at $HOME_DIR (skipping)"fi- # Legacy pre-rename home is unambiguously Rust — always sweep it.+ # Preserve legacy telemetry state during a normal uninstall so the+ # runtime's existing one-shot migration can carry the same identity into+ # ~/.cua-driver on reinstall.if [[ -d "$LEGACY_HOME_DIR" ]]; then- rm -rf "$LEGACY_HOME_DIR"- log "removed legacy package home $LEGACY_HOME_DIR"+ if [[ "$PURGE_DATA" == "1" ]]; then+ rm -rf "$LEGACY_HOME_DIR"+ log "purged legacy package home $LEGACY_HOME_DIR"+ else+ rm -rf "$LEGACY_HOME_DIR/packages" "$LEGACY_HOME_DIR/skills"+ rm -f \+ "$LEGACY_HOME_DIR/.tcc-signing-identity" \+ "$LEGACY_HOME_DIR/serve.out.log" \+ "$LEGACY_HOME_DIR/serve.err.log"+ log "removed legacy runtime payloads and preserved legacy telemetry state"+ fifi# --- Swift-era macOS data dirs (leave nothing behind) ---@@ -511,6 +543,15 @@ PYif [[ "$OS" == "Darwin" ]]; thenecho ""echo "cua-driver uninstalled."+ if [[ "$PURGE_DATA" == "0" ]]; then+ cat << 'TELEMETRYUNMSG'++Telemetry identity and preference were preserved for a future reinstall.+To delete them too, re-run with --purge:++ /bin/bash -c "$(curl -fsSL https://cua.ai/driver/uninstall.sh)" -- --purge+TELEMETRYUNMSG+ fiif [[ "$RESET_TCC" != "1" ]]; thencat << 'FINALUNMSG'@@ -527,6 +568,15 @@ FINALUNMSGcua-driver uninstalled.FINALUNMSG+ if [[ "$PURGE_DATA" == "0" ]]; then+ cat << 'TELEMETRYUNMSG'++Telemetry identity and preference were preserved for a future reinstall.+To delete them too, re-run with --purge:++ /bin/bash -c "$(curl -fsSL https://cua.ai/driver/uninstall.sh)" -- --purge+TELEMETRYUNMSG+ fifiexit 0fidiff --git a/libs/lume/README.md b/libs/lume/README.mdindex 5c56bc3633..544cf708bb 100644--- a/libs/lume/README.md+++ b/libs/lume/README.md@@ -36,3 +36,21 @@ pip3 install vncdotool```Other Lume commands do not require this package.++## Telemetry++Lume telemetry is enabled by default and records pseudonymous installation,+release, command, and API-event metadata. It does not collect prompts,+VM/image names, file paths, command arguments, or VM contents.++```bash+lume config telemetry status+lume config telemetry disable+lume config telemetry enable+lume config telemetry reset-id+```++`LUME_TELEMETRY_ENABLED` overrides the persisted preference for the current+process. A normal uninstall preserves the preference and pseudonymous installation+ID so a reinstall is recognized as returning. `uninstall.sh --purge` deletes+the ID, markers, configuration, cache, and VMs.diff --git a/libs/lume/scripts/install.sh b/libs/lume/scripts/install.shindex ef485f2f63..161d76adac 100755--- a/libs/lume/scripts/install.sh+++ b/libs/lume/scripts/install.sh@@ -394,6 +394,29 @@ cleanup_deprecated_auto_updater() {fi}+# Record consent-aware installation and per-version release events through+# the installed binary so identity, preference precedence, request timeouts,+# and 2xx-only marker semantics stay in one implementation. This happens+# before the LaunchAgent can start Lume and race first-run registration.+record_installation_telemetry() {+ echo ""+ echo "${BLUE}Telemetry defaults to enabled for new installations; saved preferences and environment overrides are honored.${NORMAL}"+ echo "${BLUE}When enabled, Lume collects a pseudonymous installation ID and bounded, content-free usage metadata.${NORMAL}"+ echo " No prompts, VM/image names, file paths, or VM contents are collected."+ echo " Disable persistently at any time: $INSTALL_DIR/lume config telemetry disable"++ INSTALL_CHANNEL="${LUME_INSTALL_CHANNEL:-install_script}"+ case "$INSTALL_CHANNEL" in+ install_script|update_apply|first_run) ;;+ *) INSTALL_CHANNEL="install_script" ;;+ esac++ # `--version` is a side-effect-free command after the registration preflight.+ # Telemetry failure must never turn a successful install into a failure.+ LUME_INSTALL_CHANNEL="$INSTALL_CHANNEL" \+ "$INSTALL_DIR/lume" --version >/dev/null 2>&1 || true+}+# Main installation flowmain() {check_permissions@@ -401,6 +424,7 @@ main() {create_temp_dirdownload_releaseinstall_binary+ record_installation_telemetryecho ""echo "${GREEN}${BOLD}Lume has been successfully installed!${NORMAL}"diff --git a/libs/lume/scripts/uninstall.sh b/libs/lume/scripts/uninstall.shindex 229bdc07f8..5a142b0a59 100755--- a/libs/lume/scripts/uninstall.sh+++ b/libs/lume/scripts/uninstall.sh@@ -31,7 +31,7 @@ while [ "$#" -gt 0 ]; doecho "Usage: $0 [OPTIONS]"echo ""echo "Options:"- echo " --purge Also remove all Lume data (VMs, cache, config)"+ echo " --purge Also remove all Lume data, telemetry identity, and config"echo " --force Skip confirmation prompts"echo " --help Display this help message"echo ""@@ -64,7 +64,7 @@ if [ "$FORCE" = false ]; thenecho "This will uninstall Lume from your system."if [ "$PURGE_DATA" = true ]; thenecho "${YELLOW}WARNING: --purge flag detected. This will also delete:${NORMAL}"- echo " - All VMs in ~/.lume/"+ echo " - All VMs and the pseudonymous telemetry identity in ~/.lume/"echo " - Configuration in ~/.config/lume/"echo " - Cached images"fi@@ -187,7 +187,7 @@ if [ "$PURGE_DATA" = true ]; thenfirm -rf "$HOME/.lume"- echo " ${GREEN}Removed ~/.lume/ (VMs and cache)${NORMAL}"+ echo " ${GREEN}Removed ~/.lume/ (VMs, cache, and telemetry identity)${NORMAL}"elseecho " ~/.lume/ not found (skipped)"fi@@ -205,7 +205,7 @@ echo ""echo "${GREEN}${BOLD}Lume has been successfully uninstalled!${NORMAL}"if [ "$PURGE_DATA" = false ]; thenecho ""- echo "Note: Your VMs and configuration were preserved."+ echo "Note: Your VMs, telemetry identity, and configuration preference were preserved."echo "To also remove all data, run with ${BOLD}--purge${NORMAL}:"echo " /bin/bash -c \"\$(curl -fsSL https://cua.ai/lume/uninstall.sh)\" -- --purge"fidiff --git a/libs/lume/src/Commands/Config.swift b/libs/lume/src/Commands/Config.swiftindex 1a26039ee5..9e4cd47a5d 100644--- a/libs/lume/src/Commands/Config.swift+++ b/libs/lume/src/Commands/Config.swift@@ -231,8 +231,8 @@ struct Config: ParsableCommand {struct Telemetry: ParsableCommand {static let configuration = CommandConfiguration(commandName: "telemetry",- abstract: "Manage anonymous telemetry settings",- subcommands: [Status.self, Enable.self, Disable.self],+ abstract: "Manage pseudonymous telemetry settings",+ subcommands: [Status.self, Enable.self, Disable.self, ResetID.self],defaultSubcommand: Status.self)@@ -243,30 +243,22 @@ struct Config: ParsableCommand {)func run() throws {- let controller = LumeController()- let settings = controller.getSettings()- let envOverride = ProcessInfo.processInfo.environment["LUME_TELEMETRY_ENABLED"]-- print("Telemetry enabled: \(settings.telemetryEnabled)")+ let status = TelemetryClient.shared.status()- if let envValue = envOverride {- let lowercased = envValue.lowercased()- let envEnabled = ["1", "true", "yes", "on"].contains(lowercased)- let envDisabled = ["0", "false", "no", "off"].contains(lowercased)- if envEnabled || envDisabled {- print(" (overridden by LUME_TELEMETRY_ENABLED=\(envValue))")- }- }+ print("Telemetry enabled: \(status.enabled)")+ print("Effective source: \(status.source)")+ print("Persisted preference: \(status.persistedEnabled)")+ print("Installation ID: \(status.installationIdPresent ? "present (redacted)" : "not created")")- print("\nTelemetry collects anonymous usage data to help improve Lume.")- print("No personal information or VM contents are ever collected.")+ print("\nTelemetry collects pseudonymous usage data to help improve Lume.")+ print("No prompts, VM/image names, file paths, or VM contents are collected.")}}struct Enable: ParsableCommand {static let configuration = CommandConfiguration(commandName: "enable",- abstract: "Enable anonymous telemetry"+ abstract: "Enable pseudonymous telemetry")func run() throws {@@ -280,7 +272,7 @@ struct Config: ParsableCommand {struct Disable: ParsableCommand {static let configuration = CommandConfiguration(commandName: "disable",- abstract: "Disable anonymous telemetry"+ abstract: "Disable pseudonymous telemetry")func run() throws {@@ -289,6 +281,19 @@ struct Config: ParsableCommand {print("Telemetry disabled")}}++ struct ResetID: ParsableCommand {+ static let configuration = CommandConfiguration(+ commandName: "reset-id",+ abstract: "Delete the pseudonymous installation ID and registration markers"+ )++ func run() throws {+ try TelemetryClient.shared.resetInstallationId()+ print("Telemetry installation ID reset")+ print("The enabled/disabled preference was preserved.")+ }+ }}// MARK: - Registry Management Subcommandsdiff --git a/libs/lume/src/Main.swift b/libs/lume/src/Main.swiftindex cdd1e0ccc5..c22982d5b4 100644--- a/libs/lume/src/Main.swift+++ b/libs/lume/src/Main.swift@@ -57,8 +57,18 @@ extension Lume {// MARK: - Command Executionextension Lume {public static func main() async {- // Record installation event on first run (sent regardless of telemetry opt-out)- TelemetryClient.shared.recordInstallation()+ // Telemetry management must be able to be the first invocation without+ // creating an ID or making a request. Every other entry point performs+ // consent-aware registration and per-version release recording before+ // routine command telemetry can fire.+ if !isTelemetryManagementInvocation() {+ let rawChannel = ProcessInfo.processInfo.environment["LUME_INSTALL_CHANNEL"]+ let channel = TelemetryClient.normalizedInstallChannel(rawChannel)+ if channel == "first_run" && TelemetryClient.shared.shouldShowFirstRunNotice() {+ writeTelemetryNoticeToStandardError()+ }+ await TelemetryClient.shared.recordInstallation(channel: channel)+ }// Print banner when showing helpif shouldShowBanner() {@@ -67,11 +77,30 @@ extension Lume {do {try await executeCommand()+ await TelemetryClient.shared.flush()} catch {+ await TelemetryClient.shared.flush()exit(withError: error)}}+ private static func isTelemetryManagementInvocation() -> Bool {+ let args = Array(CommandLine.arguments.dropFirst())+ return args.count >= 2 && args[0] == "config" && args[1] == "telemetry"+ }++ private static func writeTelemetryNoticeToStandardError() {+ let notice = """+ Telemetry: enabled by default; Lume collects pseudonymous install and bounded usage metadata only.+ No prompts, VM/image names, file paths, or VM contents are collected.+ Disable persistently at any time: lume config telemetry disable++ """+ if let data = notice.data(using: .utf8) {+ FileHandle.standardError.write(data)+ }+ }+private static func executeCommand() async throws {var command = try parseAsRoot()@@ -81,4 +110,4 @@ extension Lume {try command.run()}}-}\ No newline at end of file+}diff --git a/libs/lume/src/Telemetry/TelemetryClient.swift b/libs/lume/src/Telemetry/TelemetryClient.swiftindex 8bd457ad67..70e074b874 100644--- a/libs/lume/src/Telemetry/TelemetryClient.swift+++ b/libs/lume/src/Telemetry/TelemetryClient.swift@@ -1,257 +1,504 @@import Foundation-/// Singleton telemetry client for anonymous usage tracking-/// Uses PostHog HTTP API directly for CLI compatibility+/// Pseudonymous, content-free product telemetry for Lume.+///+/// Telemetry is enabled by default, can be persistently disabled through+/// `lume config telemetry disable`, and can be overridden for the current+/// process with `LUME_TELEMETRY_ENABLED`. The environment always has highest+/// precedence. Installation and release events obey the same consent decision+/// as routine usage events.final class TelemetryClient: @unchecked Sendable {- // MARK: - Constants-- private enum Constants {- static let apiKey = "phc_eSkLnbLxsnYFaXksif1ksbrNzYlJShr35miFLDppF14"- static let captureURL = "https://eu.i.posthog.com/capture/"- static let telemetryIdFileName = ".telemetry_id"- static let installationRecordedFileName = ".installation_recorded"- static let envTelemetryEnabled = "LUME_TELEMETRY_ENABLED"- static let envTelemetryDebug = "LUME_TELEMETRY_DEBUG"+ private enum Constants {+ static let apiKey = "phc_eSkLnbLxsnYFaXksif1ksbrNzYlJShr35miFLDppF14"+ static let captureURL = "https://eu.i.posthog.com/capture/"+ static let telemetryIdFileName = ".telemetry_id"+ static let installationRecordedFileName = ".installation_recorded"+ static let releaseRecordedDirectoryName = ".telemetry_releases"+ static let lifecycleRetryAfterFileName = ".telemetry_retry_after"+ static let envTelemetryEnabled = "LUME_TELEMETRY_ENABLED"+ static let envTelemetryDebug = "LUME_TELEMETRY_DEBUG"+ static let envInstallChannel = "LUME_INSTALL_CHANNEL"+ static let requestTimeout: TimeInterval = 3+ static let flushTimeout: TimeInterval = 1.5+ static let lifecycleRetryBackoff: TimeInterval = 15 * 60+ static let schemaVersion = 2+ static let processSessionId = UUID().uuidString+ static let allowedInstallChannels: Swift.Set<String> = [+ "install_script", "update_apply", "first_run",+ ]+ }++ struct Status: Sendable {+ let enabled: Bool+ let source: String+ let persistedEnabled: Bool+ let installationIdPresent: Bool+ }++ private struct InstallationIdentity {+ let value: String+ let persisted: Bool+ }++ typealias Poster = @Sendable (URLRequest) async -> Bool++ static let shared = TelemetryClient()++ private var installationIdentity: InstallationIdentity?+ private let urlSession: URLSession+ private let homeDirectory: URL+ private let poster: Poster?+ private let preferenceProvider: @Sendable () -> Bool+ private let identityLock = NSLock()+ private let pendingRequests = DispatchGroup()++ init(+ settingsManager: SettingsManager = .shared,+ urlSession: URLSession? = nil,+ homeDirectory: URL? = nil,+ poster: Poster? = nil,+ preferenceProvider: (@Sendable () -> Bool)? = nil+ ) {+ self.homeDirectory =+ homeDirectory+ ?? FileManager.default.homeDirectoryForCurrentUser.appendingPathComponent(".lume")+ self.poster = poster+ self.preferenceProvider =+ preferenceProvider ?? { settingsManager.getSettings().telemetryEnabled }++ if let urlSession {+ self.urlSession = urlSession+ } else {+ let config = URLSessionConfiguration.ephemeral+ config.timeoutIntervalForRequest = Constants.requestTimeout+ config.timeoutIntervalForResource = Constants.requestTimeout+ self.urlSession = URLSession(configuration: config)}+ }- // MARK: - Singleton+ // MARK: - Public API- static let shared = TelemetryClient()-- // MARK: - Properties+ /// Record a routine event without blocking the command. Only fixed,+ /// typed properties survive `sanitizeProperties`; strings originating+ /// from image names, VM names, paths, prompts, or arguments are dropped.+ func record(event: String, properties: [String: Any] = [:]) {+ guard isEnabled(), let request = makeRequest(event: event, properties: properties) else {+ return+ }- private var installationId: String?- private let settingsManager: SettingsManager- private let urlSession: URLSession+ pendingRequests.enter()+ Task.detached { [self] in+ _ = await send(request: request, event: event)+ pendingRequests.leave()+ }+ }++ /// Record the legacy installation event once and the release event once+ /// per Lume version. Both events honor consent. Each marker is written+ /// only after its corresponding request receives HTTP 2xx.+ func recordInstallation(channel: String? = nil) async {+ guard isEnabled(), !lifecycleRetryDeferred() else { return }++ let installChannel = Self.normalizedInstallChannel(+ channel ?? ProcessInfo.processInfo.environment[Constants.envInstallChannel]+ )+ let installMarker = installationMarkerURL+ let releaseMarker = releaseMarkerURL(version: Lume.Version.current)+ let needsInstall = !FileManager.default.fileExists(atPath: installMarker.path)+ let needsRelease = !FileManager.default.fileExists(atPath: releaseMarker.path)++ guard needsInstall || needsRelease else { return }++ let properties: [String: Any] = [+ "install_channel": installChannel,+ "product_version": Lume.Version.current,+ ]++ if needsInstall && needsRelease,+ let installRequest = makeRequest(event: TelemetryEvent.install, properties: properties),+ let releaseRequest = makeRequest(+ event: TelemetryEvent.releaseInstalled, properties: properties)+ {+ async let installAccepted = send(request: installRequest, event: TelemetryEvent.install)+ async let releaseAccepted = send(+ request: releaseRequest, event: TelemetryEvent.releaseInstalled)+ let (didInstall, didRelease) = await (installAccepted, releaseAccepted)+ let installRecorded = didInstall && writeMarker(installMarker)+ let releaseRecorded = didRelease && writeMarker(releaseMarker)+ finishLifecycleAttempt(succeeded: installRecorded && releaseRecorded)+ return+ }- // MARK: - Initialization+ if needsInstall,+ let request = makeRequest(event: TelemetryEvent.install, properties: properties),+ await send(request: request, event: TelemetryEvent.install)+ {+ if !writeMarker(installMarker) {+ deferLifecycleRetry()+ return+ }+ } else if needsInstall {+ deferLifecycleRetry()+ return+ }- private init(settingsManager: SettingsManager = .shared) {- self.settingsManager = settingsManager+ if needsRelease,+ let request = makeRequest(+ event: TelemetryEvent.releaseInstalled, properties: properties),+ await send(request: request, event: TelemetryEvent.releaseInstalled)+ {+ if !writeMarker(releaseMarker) {+ deferLifecycleRetry()+ return+ }+ } else if needsRelease {+ deferLifecycleRetry()+ return+ }- // Configure URL session with short timeout (don't block CLI)- let config = URLSessionConfiguration.default- config.timeoutIntervalForRequest = 10- config.timeoutIntervalForResource = 10- self.urlSession = URLSession(configuration: config)+ clearLifecycleRetry()+ }++ /// Wait a short, bounded interval for routine events queued by a+ /// short-lived CLI command. Long-running `serve` processes do not reach+ /// this path until shutdown.+ @discardableResult+ func flush(timeout: TimeInterval = Constants.flushTimeout) async -> Bool {+ let group = pendingRequests+ return await Task.detached {+ Self.waitForPendingRequests(group, timeout: timeout)+ }.value+ }++ private static func waitForPendingRequests(+ _ group: DispatchGroup, timeout: TimeInterval+ ) -> Bool {+ group.wait(timeout: .now() + timeout) == .success+ }++ func isEnabled() -> Bool {+ effectiveState().enabled+ }++ func status() -> Status {+ let state = effectiveState()+ return Status(+ enabled: state.enabled,+ source: state.source,+ persistedEnabled: state.persistedEnabled,+ installationIdPresent: FileManager.default.fileExists(atPath: installationIdURL.path)+ )+ }++ /// Delete the pseudonymous identity and its registration/release markers.+ /// The persisted enabled/disabled preference is intentionally retained.+ func resetInstallationId() throws {+ identityLock.lock()+ installationIdentity = nil+ identityLock.unlock()++ for url in [installationIdURL, installationMarkerURL, lifecycleRetryAfterURL] {+ if FileManager.default.fileExists(atPath: url.path) {+ try FileManager.default.removeItem(at: url)+ }}+ if FileManager.default.fileExists(atPath: releaseMarkerDirectoryURL.path) {+ try FileManager.default.removeItem(at: releaseMarkerDirectoryURL)+ }+ }++ /// A direct release-asset/manual first run has no installer in which to+ /// show the default-on notice. Telemetry management commands skip this+ /// path so `disable` can be the first action without any event.+ func shouldShowFirstRunNotice() -> Bool {+ isEnabled() && !FileManager.default.fileExists(atPath: installationMarkerURL.path)+ }++ static func normalizedInstallChannel(_ raw: String?) -> String {+ guard let raw, Constants.allowedInstallChannels.contains(raw) else {+ return "first_run"+ }+ return raw+ }++ // MARK: - Consent and identity- // MARK: - Public Methods+ private func effectiveState() -> (enabled: Bool, source: String, persistedEnabled: Bool) {+ let persisted = preferenceProvider()+ if let raw = ProcessInfo.processInfo.environment[Constants.envTelemetryEnabled],+ let enabled = Self.parseBoolean(raw)+ {+ return (enabled, "environment", persisted)+ }+ return (persisted, "persisted", persisted)+ }++ private static func parseBoolean(_ raw: String) -> Bool? {+ switch raw.trimmingCharacters(in: .whitespacesAndNewlines).lowercased() {+ case "0", "false", "no", "off": false+ case "1", "true", "yes", "on": true+ default: nil+ }+ }- /// Record a telemetry event- /// - Parameters:- /// - event: Event name (e.g., "lume_create", "lume_api_vm_run")- /// - properties: Additional event properties- func record(event: String, properties: [String: Any] = [:]) {- guard isEnabled() else { return }+ private func getOrCreateInstallationIdentity() -> InstallationIdentity {+ identityLock.lock()+ defer { identityLock.unlock() }- // Lazy load installation ID- if installationId == nil {- installationId = getOrCreateInstallationId()- }+ if let installationIdentity { return installationIdentity }- sendEvent(event: event, properties: properties, bypassOptOut: false)+ if let existing = try? String(contentsOf: installationIdURL, encoding: .utf8) {+ let trimmed = existing.trimmingCharacters(in: .whitespacesAndNewlines)+ if let parsed = UUID(uuidString: trimmed) {+ let identity = InstallationIdentity(value: parsed.uuidString, persisted: true)+ installationIdentity = identity+ return identity+ }}- /// Record installation event - sent ONCE on first run, regardless of telemetry opt-out- /// This tracks adoption while respecting user's choice to opt out of ongoing telemetry- func recordInstallation() {- let homeDir = (("~/.lume") as NSString).expandingTildeInPath- let markerPath = "\(homeDir)/\(Constants.installationRecordedFileName)"-- // Check if we've already recorded installation- if FileManager.default.fileExists(atPath: markerPath) {- return- }-- // Get or create installation ID- let installId = getOrCreateInstallationId()- self.installationId = installId-- // Send installation event (bypasses isEnabled check)- sendEvent(event: TelemetryEvent.install, properties: [:], bypassOptOut: true)-- // Mark as recorded- do {- try FileManager.default.createDirectory(atPath: homeDir, withIntermediateDirectories: true)- try "1".write(toFile: markerPath, atomically: true, encoding: .utf8)- } catch {- if isDebugEnabled() {- Logger.info("[Telemetry] Failed to write installation marker: \(error.localizedDescription)")- }- }-- if isDebugEnabled() {- Logger.info("[Telemetry] Installation event recorded for: \(installId)")- }+ let newId = UUID().uuidString+ var persisted = false+ do {+ try FileManager.default.createDirectory(+ at: homeDirectory, withIntermediateDirectories: true)+ try newId.write(to: installationIdURL, atomically: true, encoding: .utf8)+ persisted = true+ } catch {+ debugLog("Failed to persist installation ID: \(error.localizedDescription)")}- /// Check if telemetry is enabled- /// - Returns: true if telemetry should be collected- func isEnabled() -> Bool {- // Check environment variable first (highest priority for CI/CD)- if let envValue = ProcessInfo.processInfo.environment[Constants.envTelemetryEnabled] {- let lowercased = envValue.lowercased()- if ["0", "false", "no", "off"].contains(lowercased) {- return false- }- if ["1", "true", "yes", "on"].contains(lowercased) {- return true- }- }-- // Check settings- return settingsManager.getSettings().telemetryEnabled+ let identity = InstallationIdentity(value: newId, persisted: persisted)+ installationIdentity = identity+ return identity+ }++ // MARK: - Request construction and delivery++ private func makeRequest(event: String, properties: [String: Any]) -> URLRequest? {+ let identity = getOrCreateInstallationIdentity()+ var eventProperties = sanitizeProperties(properties)+ eventProperties["lume_version"] = Lume.Version.current+ eventProperties["product_version"] = Lume.Version.current+ eventProperties["telemetry_schema_version"] = Constants.schemaVersion+ eventProperties["os_family"] = "macos"+ eventProperties["os_major"] = String(ProcessInfo.processInfo.operatingSystemVersion.majorVersion)+ eventProperties["arch"] = architecture()+ eventProperties["is_ci"] = isCI()+ eventProperties["transport"] = transport(event: event, properties: properties)+ eventProperties["process_session_id"] = Constants.processSessionId+ eventProperties["id_persisted"] = identity.persisted+ eventProperties["$lib"] = "lume-swift"+ eventProperties["$lib_version"] = Lume.Version.current+ eventProperties["$process_person_profile"] = false+ eventProperties["$geoip_disable"] = true++ let payload: [String: Any] = [+ "api_key": Constants.apiKey,+ "event": event,+ "distinct_id": identity.value,+ "properties": eventProperties,+ ]++ guard let url = URL(string: Constants.captureURL),+ let jsonData = try? JSONSerialization.data(withJSONObject: payload)+ else {+ debugLog("Failed to serialize event payload")+ return nil}- // MARK: - Private Methods-- private func sendEvent(event: String, properties: [String: Any], bypassOptOut: Bool) {- guard bypassOptOut || isEnabled() else { return }-- let distinctId = installationId ?? getOrCreateInstallationId()-- // Build event properties- var eventProperties = properties- eventProperties["lume_version"] = Lume.Version.current- eventProperties["os"] = "macos"- eventProperties["os_version"] = ProcessInfo.processInfo.operatingSystemVersionString- eventProperties["arch"] = getArchitecture()- eventProperties["is_ci"] = isCI()- eventProperties["$lib"] = "lume-swift"- eventProperties["$lib_version"] = Lume.Version.current-- // Build PostHog capture payload- let payload: [String: Any] = [- "api_key": Constants.apiKey,- "event": event,- "distinct_id": distinctId,- "properties": eventProperties,- "timestamp": ISO8601DateFormatter().string(from: Date())+ var request = URLRequest(url: url, timeoutInterval: Constants.requestTimeout)+ request.httpMethod = "POST"+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")+ request.httpBody = jsonData+ return request+ }++ private func transport(event: String, properties: [String: Any]) -> String {+ if event.hasPrefix("lume_api_") { return "http" }+ if event == TelemetryEvent.serve, let mode = properties["mode"] as? String,+ mode == "mcp" || mode == "http"+ {+ return mode+ }+ return "cli"+ }++ private func sanitizeProperties(_ properties: [String: Any]) -> [String: Any] {+ let allowedKeys: Swift.Set<String> = [+ "cpu", "disk_size", "disk_size_gb", "has_unattended", "headless",+ "install_channel", "memory", "memory_gb", "mode", "os_type",+ "product_version",+ ]+ var sanitized: [String: Any] = [:]+ for (key, value) in properties where allowedKeys.contains(key) {+ switch value {+ case let value as Bool:+ sanitized[key] = value+ case let value as Int:+ sanitized[key] = value+ case let value as Int64:+ sanitized[key] = value+ case let value as Double where value.isFinite:+ sanitized[key] = value+ case let value as String:+ // Only bounded enums are accepted. User-derived strings such+ // as image names and custom preset names never pass through.+ let allowedValues: Swift.Set<String> = [+ "custom", "first_run", "install_script", "linux", "macos",+ "offline", "update_apply", "mcp", "http",]-- guard let url = URL(string: Constants.captureURL),- let jsonData = try? JSONSerialization.data(withJSONObject: payload) else {- if isDebugEnabled() {- Logger.info("[Telemetry] Failed to serialize event payload")- }- return- }-- var request = URLRequest(url: url)- request.httpMethod = "POST"- request.setValue("application/json", forHTTPHeaderField: "Content-Type")- request.httpBody = jsonData-- if isDebugEnabled() {- Logger.info("[Telemetry] Sending event: \(event)", metadata: ["properties": "\(eventProperties)"])- }-- // Fire and forget - don't block CLI execution- let debugEnabled = isDebugEnabled()- Task.detached {- do {- let (_, response) = try await self.urlSession.data(for: request)- if debugEnabled {- let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0- Logger.info("[Telemetry] Event sent: \(event), status: \(statusCode)")- }- } catch {- if debugEnabled {- Logger.info("[Telemetry] Failed to send event \(event): \(error.localizedDescription)")- }- }- }+ sanitized[key] = allowedValues.contains(value) ? value : "unknown"+ default:+ continue+ }}+ return sanitized+ }- private func isDebugEnabled() -> Bool {- if let envValue = ProcessInfo.processInfo.environment[Constants.envTelemetryDebug] {- return ["on", "true", "1", "yes"].contains(envValue.lowercased())- }- return false+ private func send(request: URLRequest, event: String) async -> Bool {+ if let poster {+ return await poster(request)}- private func getOrCreateInstallationId() -> String {- let homeDir = (("~/.lume") as NSString).expandingTildeInPath- let idFilePath = "\(homeDir)/\(Constants.telemetryIdFileName)"-- // Try to read existing ID- if let existingId = try? String(contentsOfFile: idFilePath, encoding: .utf8) {- let trimmedId = existingId.trimmingCharacters(in: .whitespacesAndNewlines)- if !trimmedId.isEmpty {- return trimmedId- }- }-- // Generate new ID- let newId = UUID().uuidString-- // Try to persist it- do {- try FileManager.default.createDirectory(- atPath: homeDir,- withIntermediateDirectories: true- )- try newId.write(toFile: idFilePath, atomically: true, encoding: .utf8)- } catch {- if isDebugEnabled() {- Logger.info("[Telemetry] Failed to persist installation ID: \(error.localizedDescription)")- }- }-- return newId+ do {+ let (_, response) = try await urlSession.data(for: request)+ let statusCode = (response as? HTTPURLResponse)?.statusCode ?? 0+ debugLog("Event sent: \(event), status: \(statusCode)")+ return (200..<300).contains(statusCode)+ } catch {+ debugLog("Failed to send event \(event): \(error.localizedDescription)")+ return false}+ }++ // MARK: - Paths and platform fields++ private var installationIdURL: URL {+ homeDirectory.appendingPathComponent(Constants.telemetryIdFileName)+ }++ private var installationMarkerURL: URL {+ homeDirectory.appendingPathComponent(Constants.installationRecordedFileName)+ }- private func getArchitecture() -> String {- #if arch(arm64)- return "arm64"- #elseif arch(x86_64)- return "x86_64"- #else- return "unknown"- #endif+ private var releaseMarkerDirectoryURL: URL {+ homeDirectory.appendingPathComponent(Constants.releaseRecordedDirectoryName)+ }++ private var lifecycleRetryAfterURL: URL {+ homeDirectory.appendingPathComponent(Constants.lifecycleRetryAfterFileName)+ }++ private func releaseMarkerURL(version: String) -> URL {+ let safeVersion = version.map { character -> Character in+ character.isLetter || character.isNumber || character == "." || character == "-"+ ? character : "_"+ }+ return releaseMarkerDirectoryURL.appendingPathComponent(String(safeVersion))+ }++ @discardableResult+ private func writeMarker(_ url: URL) -> Bool {+ do {+ try FileManager.default.createDirectory(+ at: url.deletingLastPathComponent(), withIntermediateDirectories: true)+ try "1".write(to: url, atomically: true, encoding: .utf8)+ return true+ } catch {+ debugLog("Failed to write marker: \(error.localizedDescription)")+ return false+ }+ }++ private func lifecycleRetryDeferred(now: Date = Date()) -> Bool {+ guard+ let raw = try? String(contentsOf: lifecycleRetryAfterURL, encoding: .utf8),+ let retryAfter = TimeInterval(raw.trimmingCharacters(in: .whitespacesAndNewlines))+ else { return false }+ let remaining = retryAfter - now.timeIntervalSince1970+ return remaining > 0 && remaining <= Constants.lifecycleRetryBackoff+ }++ private func deferLifecycleRetry(now: Date = Date()) {+ let retryAfter = now.timeIntervalSince1970 + Constants.lifecycleRetryBackoff+ do {+ try FileManager.default.createDirectory(at: homeDirectory, withIntermediateDirectories: true)+ try String(retryAfter).write(+ to: lifecycleRetryAfterURL, atomically: true, encoding: .utf8)+ } catch {+ debugLog("Failed to defer lifecycle retry: \(error.localizedDescription)")+ }+ }++ private func clearLifecycleRetry() {+ guard FileManager.default.fileExists(atPath: lifecycleRetryAfterURL.path) else { return }+ do {+ try FileManager.default.removeItem(at: lifecycleRetryAfterURL)+ } catch {+ debugLog("Failed to clear lifecycle retry: \(error.localizedDescription)")}+ }- private func isCI() -> Bool {- let ciEnvVars = ["CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI", "JENKINS_URL", "CIRCLECI"]- for envVar in ciEnvVars {- if ProcessInfo.processInfo.environment[envVar] != nil {- return true- }- }- return false+ private func finishLifecycleAttempt(succeeded: Bool) {+ if succeeded {+ clearLifecycleRetry()+ } else {+ deferLifecycleRetry()}+ }++ private func architecture() -> String {+ #if arch(arm64)+ "arm64"+ #elseif arch(x86_64)+ "x86_64"+ #else+ "unknown"+ #endif+ }++ private func isCI() -> Bool {+ let variables = [+ "CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI",+ "JENKINS_URL", "CIRCLECI", "BUILDKITE", "TF_BUILD", "TEAMCITY_VERSION",+ ]+ return variables.contains { ProcessInfo.processInfo.environment[$0] != nil }+ }++ private func debugLog(_ message: String) {+ guard let value = ProcessInfo.processInfo.environment[Constants.envTelemetryDebug],+ Self.parseBoolean(value) == true+ else { return }+ Logger.info("[Telemetry] \(message)")+ }}// MARK: - Telemetry Events-/// Standard telemetry event namesenum TelemetryEvent {- // Installation (sent once, regardless of opt-out)- static let install = "lume_install"-- // CLI Commands- static let create = "lume_create"- static let run = "lume_run"- static let stop = "lume_stop"- static let delete = "lume_delete"- static let clone = "lume_clone"- static let pull = "lume_pull"- static let push = "lume_push"- static let serve = "lume_serve"- static let setup = "lume_setup"- static let config = "lume_config"-- // API Endpoints- static let apiVMList = "lume_api_vm_list"- static let apiVMGet = "lume_api_vm_get"- static let apiVMCreate = "lume_api_vm_create"- static let apiVMRun = "lume_api_vm_run"- static let apiVMStop = "lume_api_vm_stop"- static let apiVMDelete = "lume_api_vm_delete"- static let apiVMClone = "lume_api_vm_clone"- static let apiVMUpdate = "lume_api_vm_update"- static let apiPull = "lume_api_pull"- static let apiPush = "lume_api_push"- static let apiImages = "lume_api_images"+ static let install = "lume_install"+ static let releaseInstalled = "lume_release_installed"++ static let create = "lume_create"+ static let run = "lume_run"+ static let stop = "lume_stop"+ static let delete = "lume_delete"+ static let clone = "lume_clone"+ static let pull = "lume_pull"+ static let push = "lume_push"+ static let serve = "lume_serve"+ static let setup = "lume_setup"+ static let config = "lume_config"++ static let apiVMList = "lume_api_vm_list"+ static let apiVMGet = "lume_api_vm_get"+ static let apiVMCreate = "lume_api_vm_create"+ static let apiVMRun = "lume_api_vm_run"+ static let apiVMStop = "lume_api_vm_stop"+ static let apiVMDelete = "lume_api_vm_delete"+ static let apiVMClone = "lume_api_vm_clone"+ static let apiVMUpdate = "lume_api_vm_update"+ static let apiPull = "lume_api_pull"+ static let apiPush = "lume_api_push"+ static let apiImages = "lume_api_images"}diff --git a/libs/lume/src/Update/VersionCheck.swift b/libs/lume/src/Update/VersionCheck.swiftindex 2330a90d69..fe5fedb295 100644--- a/libs/lume/src/Update/VersionCheck.swift+++ b/libs/lume/src/Update/VersionCheck.swift@@ -168,6 +168,7 @@ enum LumeVersionCheck {var environment = ProcessInfo.processInfo.environmentenvironment["LUME_VERSION"] = version+ environment["LUME_INSTALL_CHANNEL"] = "update_apply"process.environment = environmenttry process.run()diff --git a/libs/lume/src/Utils/CommandDocExtractor.swift b/libs/lume/src/Utils/CommandDocExtractor.swiftindex 66f4f04fb7..295cb75cba 100644--- a/libs/lume/src/Utils/CommandDocExtractor.swift+++ b/libs/lume/src/Utils/CommandDocExtractor.swift@@ -540,6 +540,20 @@ enum CommandDocExtractor {CommandDoc(name: "disable", abstract: "Disable image caching", discussion: nil, arguments: [], options: [], flags: [], subcommands: []),]),+ CommandDoc(+ name: "telemetry",+ abstract: "Manage pseudonymous telemetry settings",+ discussion: nil,+ arguments: [],+ options: [],+ flags: [],+ subcommands: [+ CommandDoc(name: "status", abstract: "Show current telemetry status", discussion: nil, arguments: [], options: [], flags: [], subcommands: []),+ CommandDoc(name: "enable", abstract: "Enable pseudonymous telemetry", discussion: nil, arguments: [], options: [], flags: [], subcommands: []),+ CommandDoc(name: "disable", abstract: "Disable pseudonymous telemetry", discussion: nil, arguments: [], options: [], flags: [], subcommands: []),+ CommandDoc(name: "reset-id", abstract: "Delete the pseudonymous installation ID and registration markers", discussion: nil, arguments: [], options: [], flags: [], subcommands: []),+ ]+ ),])}diff --git a/libs/lume/tests/TelemetryClientTests.swift b/libs/lume/tests/TelemetryClientTests.swiftnew file mode 100644index 0000000000..b13a0d3158--- /dev/null+++ b/libs/lume/tests/TelemetryClientTests.swift@@ -0,0 +1,209 @@+import Foundation+import Testing++@testable import lume++private actor TelemetryRequestRecorder {+ private(set) var payloads: [[String: Any]] = []+ var accepted = true++ func post(_ request: URLRequest) -> Bool {+ if let data = request.httpBody,+ let payload = try? JSONSerialization.jsonObject(with: data) as? [String: Any]+ {+ payloads.append(payload)+ }+ return accepted+ }++ func count() -> Int { payloads.count }++ func setAccepted(_ value: Bool) { accepted = value }++ func events() -> [String] {+ payloads.compactMap { $0["event"] as? String }+ }++ func hasContentFreePayload(event: String) -> Bool {+ guard+ let payload = payloads.first(where: { $0["event"] as? String == event }),+ let properties = payload["properties"] as? [String: Any]+ else { return false }+ return properties["image_name"] == nil+ && properties["headless"] as? Bool == true+ && properties["$process_person_profile"] as? Bool == false+ && properties["$geoip_disable"] as? Bool == true+ }++ func hasV2Envelope(event: String) -> Bool {+ guard+ let payload = payloads.first(where: { $0["event"] as? String == event }),+ let properties = payload["properties"] as? [String: Any]+ else { return false }+ return properties["telemetry_schema_version"] as? Int == 2+ && properties["os_family"] as? String == "macos"+ && Int(properties["os_major"] as? String ?? "") != nil+ && properties["os"] == nil+ && properties["os_version"] == nil+ && properties["transport"] as? String == "cli"+ && (properties["process_session_id"] as? String).flatMap(UUID.init(uuidString:)) != nil+ }++ func distinctIds() -> [String] {+ payloads.compactMap { $0["distinct_id"] as? String }+ }+}++private func telemetryTempDirectory() throws -> URL {+ let url = FileManager.default.temporaryDirectory.appendingPathComponent(+ "lume-telemetry-tests-\(UUID().uuidString)", isDirectory: true)+ try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true)+ return url+}++@Test("installation and release markers are written only after accepted requests")+func installationMarkersRequireAcceptedRequests() async throws {+ let home = try telemetryTempDirectory()+ defer { try? FileManager.default.removeItem(at: home) }+ let recorder = TelemetryRequestRecorder()+ let client = TelemetryClient(+ homeDirectory: home,+ poster: { request in await recorder.post(request) },+ preferenceProvider: { true }+ )++ await client.recordInstallation(channel: "install_script")++ let events = await recorder.events()+ #expect(+ Swift.Set(events) == Swift.Set([TelemetryEvent.install, TelemetryEvent.releaseInstalled]))+ #expect(+ FileManager.default.fileExists(+ atPath: home.appendingPathComponent(".installation_recorded").path))+ #expect(+ FileManager.default.fileExists(+ atPath: home.appendingPathComponent(".telemetry_releases/\(Lume.Version.current)").path+ ))++ await client.recordInstallation(channel: "install_script")+ #expect(await recorder.count() == 2)+}++@Test("failed installation requests defer retries without writing success markers")+func failedInstallationRequestsDeferRetries() async throws {+ let home = try telemetryTempDirectory()+ defer { try? FileManager.default.removeItem(at: home) }+ let recorder = TelemetryRequestRecorder()+ await recorder.setAccepted(false)+ let client = TelemetryClient(+ homeDirectory: home,+ poster: { request in await recorder.post(request) },+ preferenceProvider: { true }+ )++ await client.recordInstallation(channel: "install_script")++ #expect(await recorder.count() == 2)+ #expect(+ !FileManager.default.fileExists(+ atPath: home.appendingPathComponent(".installation_recorded").path))+ #expect(+ !FileManager.default.fileExists(atPath: home.appendingPathComponent(".telemetry_releases").path)+ )+ #expect(+ FileManager.default.fileExists(+ atPath: home.appendingPathComponent(".telemetry_retry_after").path))++ await recorder.setAccepted(true)+ await client.recordInstallation(channel: "install_script")+ #expect(await recorder.count() == 2)+}++@Test("disabled telemetry creates no ID, request, or marker")+func disabledTelemetryHasNoSideEffects() async throws {+ let home = try telemetryTempDirectory()+ defer { try? FileManager.default.removeItem(at: home) }+ let recorder = TelemetryRequestRecorder()+ let client = TelemetryClient(+ homeDirectory: home,+ poster: { request in await recorder.post(request) },+ preferenceProvider: { false }+ )++ await client.recordInstallation(channel: "install_script")+ client.record(event: TelemetryEvent.run, properties: ["headless": true])+ await client.flush()++ #expect(await recorder.count() == 0)+ #expect(+ !FileManager.default.fileExists(atPath: home.appendingPathComponent(".telemetry_id").path))+}++@Test("reset deletes identity and markers while preserving preference")+func resetIdentityPreservesPreference() async throws {+ let home = try telemetryTempDirectory()+ defer { try? FileManager.default.removeItem(at: home) }+ let recorder = TelemetryRequestRecorder()+ let client = TelemetryClient(+ homeDirectory: home,+ poster: { request in await recorder.post(request) },+ preferenceProvider: { true }+ )+ await client.recordInstallation(channel: "install_script")++ try client.resetInstallationId()++ let status = client.status()+ #expect(status.persistedEnabled)+ #expect(!status.installationIdPresent)+ #expect(+ !FileManager.default.fileExists(+ atPath: home.appendingPathComponent(".installation_recorded").path))+ #expect(+ !FileManager.default.fileExists(atPath: home.appendingPathComponent(".telemetry_releases").path)+ )+}++@Test("routine payload drops user-derived string properties")+func routinePayloadIsContentFree() async throws {+ let home = try telemetryTempDirectory()+ defer { try? FileManager.default.removeItem(at: home) }+ let recorder = TelemetryRequestRecorder()+ let client = TelemetryClient(+ homeDirectory: home,+ poster: { request in await recorder.post(request) },+ preferenceProvider: { true }+ )++ client.record(+ event: TelemetryEvent.pull,+ properties: ["image_name": "private/customer-image", "headless": true])+ #expect(await client.flush())++ #expect(await recorder.hasContentFreePayload(event: TelemetryEvent.pull))++ #expect(await recorder.hasV2Envelope(event: TelemetryEvent.pull))+}++@Test("invalid persisted installation ID is replaced and never emitted")+func invalidPersistedIdentityIsReplaced() async throws {+ let home = try telemetryTempDirectory()+ defer { try? FileManager.default.removeItem(at: home) }+ let secret = "private-customer-secret"+ try secret.write(+ to: home.appendingPathComponent(".telemetry_id"), atomically: true, encoding: .utf8)+ let recorder = TelemetryRequestRecorder()+ let client = TelemetryClient(+ homeDirectory: home,+ poster: { request in await recorder.post(request) },+ preferenceProvider: { true }+ )++ client.record(event: TelemetryEvent.run, properties: ["headless": true])+ #expect(await client.flush())++ let ids = await recorder.distinctIds()+ #expect(ids.count == 1)+ #expect(ids.first != secret)+ #expect(ids.first.flatMap(UUID.init(uuidString:)) != nil)+}diff --git a/scripts/docs-generators/lume.ts b/scripts/docs-generators/lume.tsindex cd56aafc2d..8bd1184477 100644--- a/scripts/docs-generators/lume.ts+++ b/scripts/docs-generators/lume.ts@@ -217,9 +217,14 @@ async function main() {// Step 2: Get CLI documentationconsole.log('\n📖 Extracting CLI documentation...');+ const documentationEnv = {+ ...process.env,+ LUME_TELEMETRY_ENABLED: 'false',+ };const cliDocsJson = execSync('.build/release/lume dump-docs --type cli', {cwd: LUME_DIR,encoding: 'utf-8',+ env: documentationEnv,});const cliDocs: CLIDocumentation = JSON.parse(cliDocsJson);console.log(` Found ${cliDocs.commands.length} commands`);@@ -229,6 +234,7 @@ async function main() {const apiDocsJson = execSync('.build/release/lume dump-docs --type api', {cwd: LUME_DIR,encoding: 'utf-8',+ env: documentationEnv,});const apiDocs: HTTPAPIDocumentation = JSON.parse(apiDocsJson);console.log(` Found ${apiDocs.endpoints.length} endpoints`);