Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

feat(spaces): Sentry crash reporting for the desktop app + crash gate in auto rollout (CUA-2343) (#6011)

cua-agents[bot]d991e3b4cc22
diff --git a/.github/actions/sentry-upload/action.yml b/.github/actions/sentry-upload/action.yml
new file mode 100644
index 0000000000..4289ae8fa5
--- /dev/null
+++ b/.github/actions/sentry-upload/action.yml
@@ -0,0 +1,74 @@
+name: "Sentry upload (Cua Spaces desktop)"
+description: >-
+ Uploads debug symbols (dSYMs, native debug files) or JavaScript source maps for
+ one Cua Spaces release to Sentry (CUA-2343), so crash reports are readable.
+ Does nothing, and says so, when the Sentry auth token is empty (a fork, or the
+ secret is not set yet) or config/spaces-crash-reporting.json has no DSN. Never
+ fails a release build: an upload error is a warning. Org and project come from
+ config/spaces-crash-reporting.json; the release is cua-spaces-desktop@<version>.
+
+inputs:
+ token:
+ description: "SENTRY_AUTH_TOKEN (project:releases, project:write, org:read)."
+ default: ""
+ version:
+ description: "App version, as in the update feed (0.7.2 or 0.7.2-beta.1)."
+ required: true
+ kind:
+ description: "`debug-files` (path: a directory or .zip of dSYMs or native binaries) or `sourcemaps` (path: a directory of built .js and .map files)."
+ required: true
+ path:
+ description: "What to upload."
+ required: true
+ url-prefix:
+ description: "Sourcemaps only: URL prefix of the files as the app reports them (for example `app:///dist`)."
+ default: "~/"
+ inject:
+ description: "Sourcemaps only: inject debug IDs into the .js files first. Leave off when the files were already packed into the app (the release and URL prefix match instead)."
+ default: "true"
+ delete-maps:
+ description: "Sourcemaps only: delete the .map files after the upload, so they never ship."
+ default: "false"
+
+runs:
+ using: composite
+ steps:
+ - shell: bash
+ env:
+ SENTRY_AUTH_TOKEN: ${{ inputs.token }}
+ VERSION: ${{ inputs.version }}
+ KIND: ${{ inputs.kind }}
+ UPLOAD_PATH: ${{ inputs.path }}
+ URL_PREFIX: ${{ inputs.url-prefix }}
+ DELETE_MAPS: ${{ inputs.delete-maps }}
+ INJECT: ${{ inputs.inject }}
+ SENTRY_CLI: "@sentry/[email protected]"
+ run: |
+ set -uo pipefail
+ cfg="$GITHUB_WORKSPACE/config/spaces-crash-reporting.json"
+ dsn=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("dsn",""))' "$cfg" 2>/dev/null || true)
+ org=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["org"])' "$cfg")
+ project=$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1]))["project"])' "$cfg")
+ if [ -z "$SENTRY_AUTH_TOKEN" ] || [ -z "$dsn" ]; then
+ echo "::notice::Sentry upload skipped (${SENTRY_AUTH_TOKEN:+token set, }${dsn:+DSN set}: needs the SENTRY_AUTH_TOKEN secret and a DSN in config/spaces-crash-reporting.json)"
+ exit 0
+ fi
+ release="cua-spaces-desktop@$VERSION"
+ export SENTRY_ORG="$org" SENTRY_PROJECT="$project"
+ sentry() { npx --yes "$SENTRY_CLI" "$@"; }
+ sentry releases new "$release" || echo "::warning::sentry releases new failed"
+ # shellcheck disable=SC2086
+ target=$(compgen -G "$UPLOAD_PATH" | head -1 || true)
+ [ -n "$target" ] || { echo "::warning::nothing to upload at $UPLOAD_PATH"; exit 0; }
+ case "$target" in
+ *.zip) d=$(mktemp -d); unzip -q "$target" -d "$d"; target="$d" ;;
+ esac
+ case "$KIND" in
+ debug-files)
+ sentry debug-files upload --include-sources "$target" || echo "::warning::debug files upload failed for $release" ;;
+ sourcemaps)
+ if [ "$INJECT" = true ]; then sentry sourcemaps inject "$target" || echo "::warning::sourcemaps inject failed"; fi
+ sentry sourcemaps upload --release "$release" --url-prefix "$URL_PREFIX" "$target" || echo "::warning::sourcemaps upload failed for $release"
+ [ "$DELETE_MAPS" = true ] && find "$target" -name '*.map' -delete ;;
+ *) echo "::error::unknown kind $KIND"; exit 1 ;;
+ esac
diff --git a/.github/scripts/release_rollout_auto.py b/.github/scripts/release_rollout_auto.py
index 7cc31f95f5..874dbbb0eb 100644
--- a/.github/scripts/release_rollout_auto.py
+++ b/.github/scripts/release_rollout_auto.py
@@ -31,11 +31,17 @@ previous stable (the most active non-prerelease version in the week before the s
(needs --min-update-events)
incident no active incident.io incident with "spaces" in its name (needs
INCIDENT_IO_API_KEY; without it the gate is reported as skipped)
-Sentry is not wired into the Spaces app, so there is no crash-free gate: the app sends
-no crash event. Add one here when it does.
+ crash Sentry release health (org and project from config/spaces-crash-reporting.json,
+ release cua-spaces-desktop@<version>, environment stable): crash-free sessions of
+ the new version since the stage began are at most --max-crash-free-drop points
+ below the previous version's over the same window (needs --min-sessions on the
+ new version). A previous version with fewer than --min-sessions sessions (it
+ shipped before crash reporting) is no baseline: the new version must then be at
+ least --min-crash-free percent. Without SENTRY_AUTH_TOKEN the gate is reported as
+ skipped.
Standard library only. Keys come from the environment: POSTHOG_API_KEY (query read),
-INCIDENT_IO_API_KEY (optional).
+INCIDENT_IO_API_KEY (optional), SENTRY_AUTH_TOKEN (optional, org:read and project:read).
"""
from __future__ import annotations
@@ -46,6 +52,7 @@ import os
import re
import sys
import urllib.error
+import urllib.parse
import urllib.request
import xml.etree.ElementTree as ET
from datetime import datetime, timedelta, timezone
@@ -55,6 +62,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parent))
import release_rollout as rr # noqa: E402
POSTHOG = "https://eu.posthog.com/api/projects/56041/query/"
+SENTRY = "https://sentry.io/api/0"
+SENTRY_CONFIG = Path(__file__).resolve().parents[2] / "config" / "spaces-crash-reporting.json"
NEXT = {"10": "50", "50": "100"}
@@ -215,7 +224,60 @@ def gate_incident(key: str | None, fetch=None) -> dict:
return {"gate": "incident", "status": "pass", "detail": "no active incident naming Spaces"}
-def decide(state: dict, now: datetime, a, q=None, incident=None, hold: str = "") -> dict:
+def sentry_get(path: str, token: str, params: list[tuple[str, str]] | None = None) -> dict:
+ url = SENTRY + path + ("?" + urllib.parse.urlencode(params) if params else "")
+ req = urllib.request.Request(url, headers={"Authorization": "Bearer " + token})
+ with urllib.request.urlopen(req, timeout=60) as r:
+ return json.load(r)
+
+
+def sentry_sessions(token: str, cfg: dict, project_id: str, version: str, since: datetime, now: datetime) -> tuple[int, float | None]:
+ """(sessions, crash-free fraction or None) of one release on the stable environment in a window."""
+ data = sentry_get(
+ "/organizations/%s/sessions/" % cfg["org"], token,
+ [("project", project_id), ("environment", "stable"),
+ ("field", "sum(session)"), ("field", "crash_free_rate(session)"),
+ ("query", 'release:"cua-spaces-desktop@%s"' % version),
+ ("start", since.strftime("%Y-%m-%dT%H:%M:%S")), ("end", now.strftime("%Y-%m-%dT%H:%M:%S")),
+ ("interval", "1d")])
+ total, rate = 0, None
+ for g in data.get("groups", []):
+ t = g.get("totals", {})
+ total += int(t.get("sum(session)") or 0)
+ rate = t.get("crash_free_rate(session)")
+ return total, rate
+
+
+def gate_crash(token: str | None, new: str, prev: str | None, since: datetime, now: datetime, a, cfg: dict | None = None, fetch=None) -> dict:
+ """Crash-free sessions of the new version against the previous one (Sentry release health)."""
+ if not token:
+ return {"gate": "crash", "status": "skip", "detail": "SENTRY_AUTH_TOKEN not set, gate skipped"}
+ try:
+ cfg = cfg or json.loads(SENTRY_CONFIG.read_text())
+ if fetch is None:
+ project_id = str(sentry_get("/projects/%s/%s/" % (cfg["org"], cfg["project"]), token)["id"])
+ fetch = lambda v: sentry_sessions(token, cfg, project_id, v, since, now) # noqa: E731
+ n_new, r_new = fetch(new)
+ n_prev, r_prev = fetch(prev) if prev else (0, None)
+ except (urllib.error.URLError, OSError, ValueError, KeyError) as e:
+ return {"gate": "crash", "status": "wait", "detail": f"Sentry unreachable or misconfigured ({e}); not advancing blind"}
+ if n_new < a.min_sessions or r_new is None:
+ return {"gate": "crash", "status": "wait",
+ "detail": f"{n_new} sessions of {new} reported to Sentry since the stage began (need {a.min_sessions})"}
+ new_pct = 100.0 * r_new
+ if n_prev < a.min_sessions or r_prev is None:
+ ok = new_pct >= a.min_crash_free
+ return {"gate": "crash", "status": "pass" if ok else "fail",
+ "detail": f"crash-free sessions {new_pct:.2f}% on {new} ({n_new} sessions); no baseline ({n_prev} sessions on {prev}), "
+ f"floor {a.min_crash_free}%"}
+ prev_pct = 100.0 * r_prev
+ drop = prev_pct - new_pct
+ return {"gate": "crash", "status": "fail" if drop > a.max_crash_free_drop else "pass",
+ "detail": f"crash-free sessions {new_pct:.2f}% on {new} ({n_new}) vs {prev_pct:.2f}% on {prev} ({n_prev}), "
+ f"drop {drop:+.2f} points (limit {a.max_crash_free_drop})"}
+
+
+def decide(state: dict, now: datetime, a, q=None, incident=None, hold: str = "", crash=None) -> dict:
d: dict = {"version": state["version"], "stage": state["stage"],
"since": state["since"].isoformat() if state["since"] else None,
"action": "none", "next": None, "gates": [], "why": ""}
@@ -235,7 +297,8 @@ def decide(state: dict, now: datetime, a, q=None, incident=None, hold: str = "")
prev = previous_version(q, new, since)
d["previous"] = prev
d["gates"] = [gate_adoption(q, new, since, now, a), gate_space_create(q, new, prev, since, now, a),
- gate_update(q, prev, since, now, a), incident or gate_incident(os.environ.get("INCIDENT_IO_API_KEY"))]
+ gate_update(q, prev, since, now, a), incident or gate_incident(os.environ.get("INCIDENT_IO_API_KEY")),
+ crash or gate_crash(os.environ.get("SENTRY_AUTH_TOKEN"), new, prev, since, now, a)]
failed = [g for g in d["gates"] if g["status"] == "fail"]
waiting = [g for g in d["gates"] if g["status"] == "wait"]
if failed:
@@ -268,6 +331,9 @@ def main(argv: list[str] | None = None) -> int:
ap.add_argument("--max-create-error-delta", type=float, default=10.0)
ap.add_argument("--min-update-events", type=int, default=20)
ap.add_argument("--max-update-failure-delta", type=float, default=15.0)
+ ap.add_argument("--min-sessions", type=int, default=100)
+ ap.add_argument("--max-crash-free-drop", type=float, default=0.5)
+ ap.add_argument("--min-crash-free", type=float, default=99.0)
a = ap.parse_args(argv)
now = datetime.fromisoformat(a.now) if a.now else datetime.now(timezone.utc)
key = os.environ.get("POSTHOG_API_KEY", "")
diff --git a/.github/scripts/tests/test_release_rollout_auto.py b/.github/scripts/tests/test_release_rollout_auto.py
index 2a3bf16fa6..6ce56d7895 100644
--- a/.github/scripts/tests/test_release_rollout_auto.py
+++ b/.github/scripts/tests/test_release_rollout_auto.py
@@ -29,7 +29,8 @@ def feeds(staging, interval, pub=PUB, title="0.16.0"):
def args(**kw):
a = argparse.Namespace(min_age_hours=24, min_installs=15, min_create_events=30, max_create_error_delta=10.0,
- min_update_events=20, max_update_failure_delta=15.0)
+ min_update_events=20, max_update_failure_delta=15.0,
+ min_sessions=100, max_crash_free_drop=0.5, min_crash_free=99.0)
a.__dict__.update(kw)
return a
@@ -52,6 +53,7 @@ def fake(installs=40, new_create=(50, 5), old_create=(100, 10), new_update=(100,
return q
+CR = lambda: {"gate": "crash", "status": "pass", "detail": "ok"} # noqa: E731
OK = lambda: ra.gate_incident("k", lambda: {"incidents": []}) # noqa: E731
@@ -71,10 +73,51 @@ class State(unittest.TestCase):
self.assertTrue(ra.read_state(feeds("10", ra.rr.HOLD_SECONDS, title="0.16.1"))["problem"] is None)
+def sessions(**by_version):
+ """A Sentry stand-in: version -> (sessions, crash-free fraction)."""
+ return lambda v: by_version[v]
+
+
+NOW = PUB + timedelta(hours=25)
+CFG = {"org": "trycua", "project": "cua-spaces-desktop"}
+
+
+def crash(new, prev, token="t", **kw):
+ return ra.gate_crash(token, "0.16.0", "0.15.0", PUB, NOW, args(**kw), cfg=CFG, fetch=sessions(**{"0.16.0": new, "0.15.0": prev}))
+
+
+class CrashGate(unittest.TestCase):
+ def test_within_half_a_point_passes(self):
+ self.assertEqual(crash((500, 0.992), (5000, 0.996))["status"], "pass")
+
+ def test_more_than_half_a_point_below_fails(self):
+ g = crash((500, 0.985), (5000, 0.996))
+ self.assertEqual(g["status"], "fail")
+ self.assertIn("drop +1.10", g["detail"])
+
+ def test_better_than_before_passes(self):
+ self.assertEqual(crash((500, 0.999), (5000, 0.99))["status"], "pass")
+
+ def test_too_few_sessions_waits(self):
+ self.assertEqual(crash((99, 0.5), (5000, 0.996))["status"], "wait")
+
+ def test_no_baseline_uses_the_floor(self):
+ self.assertEqual(crash((500, 0.995), (0, None))["status"], "pass")
+ self.assertEqual(crash((500, 0.97), (3, 1.0))["status"], "fail")
+
+ def test_no_token_skips_and_errors_wait(self):
+ self.assertEqual(crash((500, 1.0), (500, 1.0), token="")["status"], "skip")
+
+ def boom(v):
+ raise OSError("down")
+ g = ra.gate_crash("t", "0.16.0", "0.15.0", PUB, NOW, args(), cfg=CFG, fetch=boom)
+ self.assertEqual(g["status"], "wait")
+
+
class Decide(unittest.TestCase):
- def go(self, hours=25, hold="", q=None, stage="10"):
+ def go(self, hours=25, hold="", q=None, stage="10", crash=None):
s = ra.read_state(feeds("10", ra.rr.HOLD_SECONDS)) if stage == "10" else ra.read_state(feeds(stage, None))
- return ra.decide(s, PUB + timedelta(hours=hours), args(), q=q or fake(), incident=OK(), hold=hold)
+ return ra.decide(s, PUB + timedelta(hours=hours), args(), q=q or fake(), incident=OK(), hold=hold, crash=crash or CR())
def test_advance(self):
d = self.go()
@@ -98,6 +141,11 @@ class Decide(unittest.TestCase):
inc = ra.gate_incident("k", lambda: {"incidents": [{"reference": "INC-9", "name": "Spaces relay down"}]})
self.assertEqual(ra.decide(s, PUB + timedelta(hours=30), args(), q=fake(), incident=inc)["action"], "pause")
+ def test_crash_gate_pauses(self):
+ bad = {"gate": "crash", "status": "fail", "detail": "crash-free sessions dropped"}
+ d = self.go(crash=bad)
+ self.assertEqual(d["action"], "pause")
+
def test_hold_blocks_advance_not_pause(self):
self.assertEqual(self.go(hold="label")["action"], "hold")
self.assertEqual(self.go(hold="label", q=fake(new_create=(50, 25)))["action"], "pause")
diff --git a/.github/workflows/cd-cua-spaces.yml b/.github/workflows/cd-cua-spaces.yml
index bc591e2db8..663a5e20b7 100644
--- a/.github/workflows/cd-cua-spaces.yml
+++ b/.github/workflows/cd-cua-spaces.yml
@@ -522,6 +522,15 @@ jobs:
if-no-files-found: error
retention-days: 90
+ # Crash reports (CUA-2343) are readable only with these symbols in Sentry.
+ - name: Upload the macOS dSYMs to Sentry
+ uses: ./.github/actions/sentry-upload
+ with:
+ token: ${{ secrets.SENTRY_AUTH_TOKEN }}
+ version: ${{ steps.version.outputs.version }}
+ kind: debug-files
+ path: ${{ runner.temp }}/spaces-app/cua-spaces-*-dSYMs.zip
+
- name: Notarize and staple the app
if: steps.signing.outputs.apple == 'true'
env:
@@ -1113,9 +1122,27 @@ jobs:
node-version: 22
- name: Build the web UI
working-directory: apps/cua-spaces-web
+ env:
+ # Hidden source maps next to the bundles, uploaded to Sentry below and
+ # deleted before the artifact, so they never ship in the app.
+ CUA_SOURCEMAPS: "1"
run: |
pnpm install --ignore-workspace --frozen-lockfile
pnpm build
+ - name: Resolve version
+ id: version
+ run: |
+ if [ "${{ github.event_name }}" = "workflow_dispatch" ]; then VERSION="${{ github.event.inputs.version }}"; else VERSION="${GITHUB_REF_NAME#cua-spaces-v}"; fi
+ echo "version=$VERSION" >> "$GITHUB_OUTPUT"
+ - name: Upload the web UI source maps to Sentry
+ uses: ./.github/actions/sentry-upload
+ with:
+ token: ${{ secrets.SENTRY_AUTH_TOKEN }}
+ version: ${{ steps.version.outputs.version }}
+ kind: sourcemaps
+ path: apps/cua-spaces-web/dist
+ url-prefix: "~/"
+ delete-maps: "true"
- uses: actions/upload-artifact@v4
with:
name: spaces-web-dist
@@ -1721,6 +1748,18 @@ jobs:
CUA_SPACES_VERSION: ${{ needs.electron-plan.outputs.version }}
CUA_SPACES_BUILD_NUMBER: ${{ github.run_number }}
run: pnpm dist:linux
+ # The Electron main process's source maps stay out of the app (electron-builder
+ # drops *.map): Sentry gets them here, matched by release and file URL.
+ - name: Upload the Electron main source maps to Sentry
+ if: matrix.arch == 'x64'
+ uses: ./.github/actions/sentry-upload
+ with:
+ token: ${{ secrets.SENTRY_AUTH_TOKEN }}
+ version: ${{ needs.electron-plan.outputs.version }}
+ kind: sourcemaps
+ path: apps/cua-spaces-desktop/dist-electron
+ url-prefix: "app:///dist-electron"
+ inject: "false"
- name: Collect the assets
env:
ARCH: ${{ matrix.arch }}
diff --git a/.github/workflows/release-rollout-auto.yml b/.github/workflows/release-rollout-auto.yml
index 7e34157216..af6e97ff0f 100644
--- a/.github/workflows/release-rollout-auto.yml
+++ b/.github/workflows/release-rollout-auto.yml
@@ -46,13 +46,16 @@ jobs:
TAG: cua-spaces-latest
POSTHOG_API_KEY: ${{ secrets.POSTHOG_API_KEY }}
INCIDENT_IO_API_KEY: ${{ secrets.INCIDENT_IO_API_KEY }}
+ SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
ALERTMANAGER_INTAKE_TOKEN: ${{ secrets.ALERTMANAGER_INTAKE_TOKEN }}
HOLD_VAR: ${{ vars.SPACES_ROLLOUT_HOLD }}
DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run || 'false' }}
steps:
- uses: actions/checkout@v4
with:
- sparse-checkout: .github
+ sparse-checkout: |
+ .github
+ config
persist-credentials: false
- name: Check the scripts
run: |
diff --git a/apps/cua-spaces-desktop/docs/staged-rollout.md b/apps/cua-spaces-desktop/docs/staged-rollout.md
index ae4fc1f807..4061cbc11e 100644
--- a/apps/cua-spaces-desktop/docs/staged-rollout.md
+++ b/apps/cua-spaces-desktop/docs/staged-rollout.md
@@ -44,11 +44,11 @@ previous stable, the most active non-prerelease version the week before the stag
- space create: `cua_space_create` error share at most 10 points above the previous version's, at least 30 events each;
- update: failed share of `cua_app_update` from the previous version (the one installing the new one) at most 15 points above its share the week before, at least 20 attempts;
- incident: no active incident.io incident with "spaces" in its name (needs the `INCIDENT_IO_API_KEY` secret; skipped and said so in the summary until it is set).
+- crash: Sentry release health (org and project in `config/spaces-crash-reporting.json`, release `cua-spaces-desktop@<version>`, environment `stable`). Crash-free sessions of the new version since the stage began must be at most 0.5 points below the previous version's over the same window, with at least 100 sessions on the new version (fewer: wait). A previous version with fewer than 100 sessions (it shipped before crash reporting) is no baseline, so the new version must reach 99% crash-free. Needs the `SENTRY_AUTH_TOKEN` secret (`org:read`, `project:read`); skipped and said so in the summary until it is set. Crash reports and sessions only come from people who left "Share usage data" on, so the numbers are a sample.
-There is no crash-free gate: Spaces has no Sentry and sends no crash event. Add
-one to `.github/scripts/release_rollout_auto.py` when it does. Thresholds are
-flags of that script. Secrets: `POSTHOG_API_KEY` (query read), optional
-`INCIDENT_IO_API_KEY`, and the existing `ALERTMANAGER_INTAKE_TOKEN`.
+Thresholds are flags of that script. Secrets: `POSTHOG_API_KEY` (query read),
+optional `INCIDENT_IO_API_KEY`, `SENTRY_AUTH_TOKEN`, and the existing
+`ALERTMANAGER_INTAKE_TOKEN`.
Dry run: **Actions > Release: auto rollout (Cua Spaces) > Run workflow** (dry run
is on by default for a manual run). It prints the decision and every gate in the
diff --git a/apps/cua-spaces-desktop/electron-builder.config.cjs b/apps/cua-spaces-desktop/electron-builder.config.cjs
index c482243c9c..d3b61a24f7 100644
--- a/apps/cua-spaces-desktop/electron-builder.config.cjs
+++ b/apps/cua-spaces-desktop/electron-builder.config.cjs
@@ -154,7 +154,19 @@ module.exports = {
buildVersion,
asar: true,
compression: "normal",
- files: ["package.json", "dist-electron/**/*", "placeholder/**/*", "!**/*.map"],
+ files: [
+ "package.json",
+ "dist-electron/**/*",
+ "placeholder/**/*",
+ "!**/*.map",
+ // @sentry/electron (crash reporting, src/crash-reporting-main.ts) is a runtime dependency.
+ // Its bundler plugins, with the Sentry CLI and the parser they pull in (~35 MB), run in
+ // builds only: the main process never loads them.
+ "!node_modules/@sentry/bundler-plugins/**",
+ "!node_modules/sentry/**",
+ "!node_modules/oxc-parser/**",
+ "!node_modules/@oxc-parser/**",
+ ],
extraResources: [
// The built web UI sits next to the asar, served by the cua-spaces:// handler.
...(fs.existsSync(path.join(webDist, "index.html"))
diff --git a/apps/cua-spaces-desktop/package.json b/apps/cua-spaces-desktop/package.json
index 96d9351b18..0b426b6550 100644
--- a/apps/cua-spaces-desktop/package.json
+++ b/apps/cua-spaces-desktop/package.json
@@ -29,6 +29,7 @@
"test": "vitest run"
},
"dependencies": {
+ "@sentry/electron": "8.3.0",
"electron-updater": "6.8.9"
},
"devDependencies": {
diff --git a/apps/cua-spaces-desktop/pnpm-lock.yaml b/apps/cua-spaces-desktop/pnpm-lock.yaml
index f90b6b7d95..965109d6bd 100644
--- a/apps/cua-spaces-desktop/pnpm-lock.yaml
+++ b/apps/cua-spaces-desktop/pnpm-lock.yaml
@@ -11,9 +11,12 @@ importers:
.:
dependencies:
+ '@sentry/electron':
+ specifier: 8.3.0
+ version: 8.3.0(@sentry/[email protected])
electron-updater:
specifier: 6.8.9
- version: 6.8.9([email protected])
+ version: 6.8.9([email protected])
devDependencies:
'@electron/fuses':
specifier: 1.8.0
@@ -26,10 +29,10 @@ importers:
version: 0.31.0-3(patch_hash=7a70f4dfe952e3fe3e2dd8065c522d81cc27e2028725ef29105ea0ba79b1afb0)
electron:
specifier: 44.9.1
- version: 44.9.1([email protected])
+ version: 44.9.1([email protected])
electron-builder:
specifier: 26.15.3
sax:
specifier: 1.6.1
version: 1.6.1
@@ -41,7 +44,7 @@ importers:
version: 5.9.3
vitest:
specifier: 5.0.3
packages:
@@ -119,6 +122,132 @@ packages:
resolution: {integrity: sha512-X5XaVWZIBCT7HHZGm5I7ZQXDwLG+bGXuSrMQAW+7Zvl87h1kmc1ZB1VSRJcpUfoUrGQp4Fkoxm5kZ+Ms+aW+eA==}
engines: {node: '>= 20.19.0'}
+ '@opentelemetry/[email protected]':
+ resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==}
+ engines: {node: '>=8.0.0'}
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-393VtirINkae4XHBTkq/yQxhOwEr4V+r0et37P2fp+sYZSdYgZTRDPo5Um8vBh0QjMZ+RmaMy4PP0qwr4cTMwA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm]
+ os: [android]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-iYFcExATJNZ0rZj0o02THbD1Nc9jAW0nVgIQPee6ejbSASpbZXlIMw8jxtpzaG14JQTWwGSZ6U5dEtRJXE6V3Q==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [android]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-fnU+DfUzi5/rFy0LzmipYRz06PAUUkOS8kCJQ3Eg6oqlunC1XZXoffFqxmdL51RmcbYtUG3P8DVG1U5fckoa2A==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [darwin]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-Y3U2okryWTs7hDld6UhjJwLNf8/do+x4g4C+1U5SiGwrTLwbO83WJYJA8+l9iFSilWBgnfpd/+U76tfeNxUHzA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [darwin]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-XkhkRrrPffEw+ZLv/d/5pEni0buxinm/E/N6fLbJCunD1DBbeCTtVP23ESV+4CWCWdSz397asks1ViGslpmWiQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [freebsd]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-MLzsRRbdfmdzo6JEhbC1yKU9ItfvM8tEf18HM32jCiNYZEz6J3bRBRl3cTkKR0vBdrk9ZVlcARXtwHccs+epDA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm]
+ os: [linux]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-HHerTEJz7Iy10Ji6BGsk4gqG6PU0UzFuBu91jIEOX89FnrI5ECWSEr7BLpkYQhp7U0QFtMnBhNfQKI0hYZK78w==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm]
+ os: [linux]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-9Bb8GyzZ2uSLzRDZ27usaKokr07mxiBe2dDF5b6bd2janmaJTT1gL51UfP7AU30yFiXrJvcRyFKREAgKwZYs0w==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [linux]
+ libc: [glibc]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-om7iDMUroI74A/lfRRWY9/Ev3VWrVsrUZ4tyvyh8raBey/sdcfyAD7tYWc+iykAiotnmftyKTpUKFr1QnaBrAQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [linux]
+ libc: [musl]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-Lf1OL2lMTqwDMFC6jnRb30B+WYHKV0XT+bPHcFM6xHtNVwxpobiTzUIvKH6a0LWpvfwyru8Yu6zCGHqqFHH+gg==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [ppc64]
+ os: [linux]
+ libc: [glibc]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-BYWSMQK+YJ9ZILStPcmmiSVq8KEG9Qdq/c4BHPC3rUEq/fEDCVjUIwdj5ZzjgZ9P9is9PKu0tcAXzq1ZXg4urQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [riscv64]
+ os: [linux]
+ libc: [glibc]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-d2LqHNNNqdH185sRK5dPKWZu201JrNu9/CRFuVEuT+ht7n/QaVblEMWT9MALQPrDWYvhG10P+NSKJFquDWZ09w==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [riscv64]
+ os: [linux]
+ libc: [musl]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-8gBeHt5rA/8+pKhHl+zLggfa3L/V/L2at96p7ty6pBE7id6lFO19nFUc15u2PcjC4OYeYK465MKy1fhhbpFIGw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [s390x]
+ os: [linux]
+ libc: [glibc]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-ltgrSF6L+yPTVsIdaAyqKq3zTqzj/1VlNbxWZuxAe8flR3sWdyNsKvdXukoO8/ucJbLickhmieRBge+o/e8Ugw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [linux]
+ libc: [glibc]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-LcMp6BvrBnewSfdkLHoSqidhoAq4syKOTBV5TYHWd+2VnGkfD/nPRRVIzTBt/Lkbt7pfOFDGtkiTntFS0p6sQQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [linux]
+ libc: [musl]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-jbhoMCslVxzRCRNQ8TSHxjYdSKRvk8O6ciLVDkahJvmyHDzBqba/bMQHM6ULKj/rgHNNbSzlIiakdx8SEfkJzA==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [openharmony]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-JZYVlhv36mr/nertnRB7vchJECOBb1Lz6lltalILsB+o9M/is+H6BEDRLQKdqA4JKs6NjJszo46+iM5sfwj6jQ==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [arm64]
+ os: [win32]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-1X9oganvVsunRH0lH10UU05N+H9atpX6WsOybByUjwnfcd3h/0tYwvuv16XuHglrIUOnxV2TodbLVEwwafd64g==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [ia32]
+ os: [win32]
+
+ '@oxc-parser/[email protected]':
+ resolution: {integrity: sha512-sw0M80/dn9rcpu+Rqqph/C+MjvDDce6MlXmFjsNQtPEymha0eJy3ml6+foSUTqFfpDIDyHZZ4eoJ43IoMe8bJw==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+ cpu: [x64]
+ os: [win32]
+
'@oxc-project/[email protected]':
resolution: {integrity: sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==}
@@ -239,6 +368,83 @@ packages:
'@rolldown/[email protected]':
resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-tTqJmnfuJaQy9LyInCWJtJ0L+VnOq+L9+lTMkQH+pptXBAuHfdJyEl2IhGqO4QmsfKyZpHa2GVd3HKpEQsVYeg==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-uBC1k2ESZErHv+RfG6p9siHrtxv+QErDxL/jvEBZnoMV6OcWdZyWTGKcqrW7EjwlBiWkgVve1W7z8tNDDuVQxw==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-rQrbL2lYPyiiO6ngdpbbfPKyEzVVQsz1FG+aE8jUiUYs72gvmDmZmRyl9VDCGLrHZfIEwaQMT1t6WQH5nopu5A==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+ peerDependencies:
+ '@babel/core': ^7.18.5
+ rollup: '>=3.2.0'
+ webpack: '>=5.1.0'
+ peerDependenciesMeta:
+ '@babel/core':
+ optional: true
+ rollup:
+ optional: true
+ webpack:
+ optional: true
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-Mrqd/o7n/z7qWSYfQQA7x4fFTA0IqOG6JNsbBpnC97khPwZk7n6DPtOO7YgaYplSl8R8QLRbBz9Xv2lVhToSAg==}
+ engines: {node: '>=14'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-4MVTthk6C/1oQFjbVIfygHyNkx2YGbwNLml0kJji0vjJXy6ZNls9zdIp0FTBTi4e3189IcSc5OXD4qcJdmEeKA==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-2KGa3G03Y8ECI1r73uYQSW9isC4usqbVSTBAOo4aE0CiwGRLjuBgadL07/sSzuWFZKFd0J+5HKrFAJzEfRuPLg==}
+ peerDependencies:
+ '@sentry/node-native': 11.8.0
+ peerDependenciesMeta:
+ '@sentry/node-native':
+ optional: true
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-t8MSpbPoOcPOkywcv0Hwh97A82jWFZju5NU/a6pHmn2pKFktgCgnHKNHvlYp8QUaDNYijYpLv58NIM5Dg7by7A==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-p1Skk57ERpsLa/cUEFx9ePc/noCIoEXc3PnOy2bnl0r1Xkjla+hLzJKcvkVp+CuUX/4eMZ+/5AA4BJ3EJLrjZg==}
+ engines: {node: '>=18'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-b4ndmttPp7VUBEcst2Ta9geDU8ccPy5IqiQi5aU73qn2rsXwJrkAW1GrjT2PfLgY9xpIU4hA4TIofc6kSuxkhA==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-8vFPfCRYoUYmsno+OYdvtf5akIUUvd7FvcuIGcfrge8S/bSLFRKq58YtFmX25JFcrMNZ2oQD8r0jkgZfm/2iuA==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-wKuG2SbHHiGDT/fgT4X5n2usO4AjVkYfAj41002mZ18JZU3mNLeCq+qw/nnDIYbcsfIMOUm/eMh3ShKCE+DpXQ==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+ peerDependencies:
+ '@opentelemetry/api': ^1.9.0
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-/MiivHLdDv3ot5uJmWcPhIOubec54hPd4U/c2OE5oNyhM3zrd/S6b2FEfwke/V120QGEdZcuzGatwNJ2jNSkgQ==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-0jXMLd9XCBEZ5tu0VJa1uj1HYCpsjuNjbEBhF5pUw4FHyIH5hz01WuI20SH2Ct0pP1mykTzJLPGjZ8sUiAmMnQ==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-4uB4E8+9ni5NcJ463aYK/+n1hTMw/vSt4s+AkQ84CKigRDwv2FNNnD1AWpipWNj/xEQ6eQbUitGl7wg7/Ri8Pg==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-2MRFz1rXxnuDGafl6o/itwKHZeZn5hUZYeXNbQK012uO/a2pXhEc8Zh3FeO5L4tjGrIWHx419saAFnKwbVC2IQ==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
'@sindresorhus/[email protected]':
resolution: {integrity: sha512-t09vSN3MdfsyCHoFcTRCH/iUtG7OJ0CsjzB8cjAmKc/va/kIgeDI/TxsigdncE/4be734m0cvIYwNaV4i2XqAw==}
engines: {node: '>=10'}
@@ -691,6 +897,10 @@ packages:
resolution: {integrity: sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==}
engines: {node: '>=12'}
+ resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==}
+ engines: {node: '>=12'}
+
resolution: {integrity: sha512-1T1f+z+4tl9XD+m+0HBgWoL/nm0bOIffyWaUuUSBlFg/86IWvfx+wjNaO/ybU0AJzG9/Mi5hBUgGV6zCmWEN7Q==}
engines: {node: ^22.18.0 || >=24.0.0}
@@ -873,6 +1083,10 @@ packages:
resolution: {integrity: sha512-X6fBC0pmImC70gvX2zm56go9hx0MyoGVdG0tUCkg/D+Xnh5TJsOZ7iDbOdI3PvmtrDxnu1YdDufpK2QJX1Meqw==}
engines: {node: '>=20.20.0'}
+ resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==}
+ engines: {node: 18 || 20 || >=22}
+
resolution: {integrity: sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==}
deprecated: Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting [email protected]
@@ -1101,6 +1315,10 @@ packages:
resolution: {integrity: sha512-tqNXrS78oMOE73NMxK4EMLQsQowWf8jKooH9g7xPavRT706R6bkQJ6DY2Te7QukaZsulxa30wQ7bk0pm4XiHmA==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-U4N8FgzmWxc8k1VH8Kr6lQg18U7Fjvby6wXHVRX/ZZ7IwWbRMgrRbP0Wrb5q5NVinryp4SQampHKdvtecItxUg==}
+ engines: {node: 20 || >=22}
+
resolution: {integrity: sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==}
engines: {node: '>=10'}
@@ -1175,6 +1393,10 @@ packages:
engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}
hasBin: true
+ resolution: {integrity: sha512-bkb/RkuWCE64eWu1PCh3Fu2pGc9mKRs+kOE+FU2bGHRYlQa86/D321DSATV54AsCQMKz3/xSt9sRgraZTpqdhQ==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-ymk4aIzxdPopw2giv8Fs1Ec6vybGkjmyxUwVqhkI4MCy2tVfXdkOGGWieWVjL0THgH+7a8lRdevyupoYj3Js/Q==}
engines: {node: '>=22.12.0'}
@@ -1214,6 +1436,10 @@ packages:
resolution: {integrity: sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==}
+ resolution: {integrity: sha512-ZztsZgaCWmPeKYMdoTT5e0oV/oxD1NeLWNR3kAtr/G707cUPYaaozRlVDHLCGnszHJRszN9mJwmPNpqgwloC0A==}
+ engines: {node: ^20.19.0 || >=22.12.0}
+
resolution: {integrity: sha512-BZOr3nRQHOntUjTrH8+Lh54smKHoHyur8We1V8DSMVrl5A2malOOwuJRnKRDjSnkoeBh4at6BwEnb5I7Jl31wg==}
engines: {node: '>=8'}
@@ -1230,6 +1456,10 @@ packages:
resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==}
+ engines: {node: 18 || 20 || >=22}
+
resolution: {integrity: sha512-eRWB5LBz7PpDu4PUlwT0PhnQfTQJlDDdPa35urV4Osrm0t0AqQFGn+UIkU3klZvwJ8KPO3VbBFsXquA6p6kqZw==}
engines: {node: '>=12', npm: '>=6'}
@@ -1392,6 +1622,11 @@ packages:
engines: {node: '>=10'}
hasBin: true
+ resolution: {integrity: sha512-kgmEbLlC22lL7uneeUm9Sjz65rp5cvwYOMTxXbZCmBum4sbVre/lLT3zTV3kwXHJ9/BM8ZS0/GhZe9Cl1t6WyA==}
+ engines: {node: '>=20.0'}
+ hasBin: true
+
resolution: {integrity: sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==}
engines: {node: '>=10'}
@@ -1451,6 +1686,10 @@ packages:
resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}
engines: {node: '>=8'}
+ resolution: {integrity: sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==}
+ engines: {node: '>=10'}
+
resolution: {integrity: sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==}
engines: {node: '>=18'}
@@ -1659,6 +1898,9 @@ packages:
jsdom:
optional: true
+ resolution: {integrity: sha512-Dmy+vdO1UPMqXiAtZSNayhl4f794Bxfd94W4HIj2HlYtczEQfEOon969memlcpcHrTuOKLa5baFjX7WbgmOq+A==}
+
resolution: {integrity: sha512-gsXecm82UQNlTBURJGuqOWy1Ww08S3kZUcr3aOJS02Pk0xLtkfeUAVC0u0xhgdonFme80edSJUIJyuvL/7250Q==}
@@ -1741,45 +1983,45 @@ snapshots:
fs-extra: 9.1.0
minimist: 1.2.8
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
env-paths: 2.2.1
fs-extra: 8.1.0
got: 11.8.6
progress: 2.0.3
semver: 6.3.1
- sumchecker: 3.0.1([email protected])
+ sumchecker: 3.0.1([email protected])
optionalDependencies:
global-agent: 3.0.0
transitivePeerDependencies:
- supports-color
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
env-paths: 3.0.0
graceful-fs: 4.2.11
progress: 2.0.3
semver: 7.8.5
- sumchecker: 3.0.1([email protected])
+ sumchecker: 3.0.1([email protected])
optionalDependencies:
undici: 7.30.0
transitivePeerDependencies:
- supports-color
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
fs-extra: 9.1.0
promise-retry: 2.0.1
transitivePeerDependencies:
- supports-color
dependencies:
compare-version: 0.1.2
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
fs-extra: 10.1.0
isbinaryfile: 4.0.10
minimist: 1.2.8
@@ -1787,22 +2029,22 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@malept/cross-spawn-promise': 2.0.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
node-abi: 4.35.0
node-api-version: 0.2.1
node-gyp: 12.4.0
- read-binary-file-arch: 1.0.6([email protected])
+ read-binary-file-arch: 1.0.6([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
'@electron/asar': 3.4.1
'@malept/cross-spawn-promise': 2.0.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
dir-compare: 4.2.0
fs-extra: 11.4.1
minimatch: 9.0.9
@@ -1810,10 +2052,10 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
cross-dirname: 0.1.0
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
fs-extra: 11.4.1
minimist: 1.2.8
postject: 1.0.0-alpha.6
@@ -1838,9 +2080,9 @@ snapshots:
dependencies:
cross-spawn: 7.0.6
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
fs-extra: 9.1.0
lodash: 4.18.1
tmp-promise: 3.0.3
@@ -1851,6 +2093,65 @@ snapshots:
'@noble/[email protected]': {}
+ '@opentelemetry/[email protected]': {}
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
+ '@oxc-parser/[email protected]':
+ optional: true
+
'@oxc-project/[email protected]': {}
'@peculiar/[email protected]':
@@ -1926,6 +2227,113 @@ snapshots:
'@rolldown/[email protected]': {}
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/conventions': 0.27.0
+ '@sentry/core': 11.8.0
+ web-vitals: 6.2.3
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/browser-utils': 11.8.0
+ '@sentry/conventions': 0.27.0
+ '@sentry/core': 11.8.0
+ '@sentry/feedback': 11.8.0
+ '@sentry/replay': 11.8.0
+ '@sentry/replay-canvas': 11.8.0
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/core': 11.8.0
+ dotenv: 17.4.2
+ glob: 13.0.6
+ magic-string: 1.4.2
+ oxc-parser: 0.152.0
+ sentry: 0.45.0
+ supports-color: 8.1.1
+
+ '@sentry/[email protected]': {}
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/conventions': 0.27.0
+
+ dependencies:
+ '@sentry/browser': 11.8.0
+ '@sentry/conventions': 0.27.0
+ '@sentry/core': 11.8.0
+ '@sentry/node': 11.8.0
+ '@sentry/server-utils': 11.8.0
+ optionalDependencies:
+ '@sentry/node-native': 11.8.0
+ transitivePeerDependencies:
+ - '@babel/core'
+ - rollup
+ - webpack
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/core': 11.8.0
+
+ '@sentry/[email protected]':
+ dependencies:
+ detect-libc: 2.1.2
+ node-abi: 3.101.0
+ optional: true
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/core': 11.8.0
+ '@sentry/node': 11.8.0
+ '@sentry/node-native-stacktrace': 0.5.2
+ transitivePeerDependencies:
+ - '@babel/core'
+ - rollup
+ - webpack
+ optional: true
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@opentelemetry/api': 1.10.0
+ '@sentry/bundler-plugins': 11.8.0
+ '@sentry/conventions': 0.27.0
+ '@sentry/core': 11.8.0
+ '@sentry/opentelemetry': 11.8.0(@opentelemetry/[email protected])
+ '@sentry/server-runtime-injection': 11.8.0
+ '@sentry/server-utils': 11.8.0
+ transitivePeerDependencies:
+ - '@babel/core'
+ - rollup
+ - webpack
+
+ '@sentry/[email protected](@opentelemetry/[email protected])':
+ dependencies:
+ '@opentelemetry/api': 1.10.0
+ '@sentry/conventions': 0.27.0
+ '@sentry/core': 11.8.0
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/core': 11.8.0
+ '@sentry/replay': 11.8.0
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/browser-utils': 11.8.0
+ '@sentry/core': 11.8.0
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/core': 11.8.0
+ '@sentry/server-utils': 11.8.0
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@opentelemetry/api': 1.10.0
+ '@sentry/conventions': 0.27.0
+ '@sentry/core': 11.8.0
+
'@sindresorhus/[email protected]': {}
'@szmarczak/[email protected]':
@@ -2078,33 +2486,33 @@ snapshots:
dependencies:
color-convert: 2.0.1
dependencies:
'@electron/asar': 3.4.1
'@electron/fuses': 1.8.0
- '@electron/get': 3.1.0([email protected])
- '@electron/notarize': 2.5.0([email protected])
- '@electron/osx-sign': 1.3.3([email protected])
- '@electron/rebuild': 4.2.0([email protected])
- '@electron/universal': 2.0.3([email protected])
- '@malept/flatpak-bundler': 0.4.0([email protected])
+ '@electron/get': 3.1.0([email protected])
+ '@electron/notarize': 2.5.0([email protected])
+ '@electron/osx-sign': 1.3.3([email protected])
+ '@electron/rebuild': 4.2.0([email protected])
+ '@electron/universal': 2.0.3([email protected])
+ '@malept/flatpak-bundler': 0.4.0([email protected])
'@noble/hashes': 2.4.0
'@peculiar/webcrypto': 1.7.1
'@types/fs-extra': 9.0.13
ajv: 8.20.0
asn1js: 3.0.10
async-exit-hook: 2.0.1
- builder-util: 26.15.3([email protected])
- builder-util-runtime: 9.7.0([email protected])
+ builder-util: 26.15.3([email protected])
+ builder-util-runtime: 9.7.0([email protected])
chromium-pickle-js: 0.2.0
ci-info: 4.3.1
- debug: 4.4.3([email protected])
- dmg-builder: 26.15.3([email protected])([email protected])
+ debug: 4.4.3([email protected])
+ dmg-builder: 26.15.3([email protected])([email protected])
dotenv: 16.6.1
dotenv-expand: 11.0.7
ejs: 3.1.10
- electron-builder-squirrel-windows: 26.15.3([email protected])([email protected])
- electron-publish: 26.15.3([email protected])
+ electron-builder-squirrel-windows: 26.15.3([email protected])([email protected])
+ electron-publish: 26.15.3([email protected])
fs-extra: 10.1.0
hosted-git-info: 4.1.0
isbinaryfile: 5.0.7
@@ -2172,23 +2580,23 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
sax: 1.6.1
transitivePeerDependencies:
- supports-color
dependencies:
'@types/debug': 4.1.13
- builder-util-runtime: 9.7.0([email protected])
+ builder-util-runtime: 9.7.0([email protected])
chalk: 4.1.2
cross-spawn: 7.0.6
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
fs-extra: 10.1.0
- http-proxy-agent: 7.0.2([email protected])
- https-proxy-agent: 7.0.6([email protected])
+ http-proxy-agent: 7.0.2([email protected])
+ https-proxy-agent: 7.0.6([email protected])
js-yaml: 4.3.2
sanitize-filename: 1.6.4
source-map-support: 0.5.21
@@ -2274,11 +2682,11 @@ snapshots:
shebang-command: 2.0.0
which: 2.0.2
dependencies:
ms: 2.1.3
optionalDependencies:
- supports-color: 7.2.0
+ supports-color: 8.1.1
dependencies:
@@ -2314,10 +2722,10 @@ snapshots:
minimatch: 3.1.5
p-limit: 3.1.0
dependencies:
- builder-util: 26.15.3([email protected])
+ builder-util: 26.15.3([email protected])
fs-extra: 10.1.0
js-yaml: 4.3.2
transitivePeerDependencies:
@@ -2330,6 +2738,8 @@ snapshots:
+
@@ -2346,23 +2756,23 @@ snapshots:
dependencies:
jake: 10.9.4
dependencies:
- builder-util: 26.15.3([email protected])
- electron-winstaller: 5.4.0([email protected])
+ builder-util: 26.15.3([email protected])
+ electron-winstaller: 5.4.0([email protected])
transitivePeerDependencies:
- dmg-builder
- supports-color
dependencies:
- builder-util: 26.15.3([email protected])
- builder-util-runtime: 9.7.0([email protected])
+ builder-util: 26.15.3([email protected])
+ builder-util-runtime: 9.7.0([email protected])
chalk: 4.1.2
ci-info: 4.4.0
- dmg-builder: 26.15.3([email protected])([email protected])
+ dmg-builder: 26.15.3([email protected])([email protected])
fs-extra: 10.1.0
lazy-val: 1.0.5
simple-update-notifier: 2.0.0
@@ -2371,12 +2781,12 @@ snapshots:
- electron-builder-squirrel-windows
- supports-color
dependencies:
'@types/fs-extra': 9.0.13
aws4: 1.13.2
- builder-util: 26.15.3([email protected])
- builder-util-runtime: 9.7.0([email protected])
+ builder-util: 26.15.3([email protected])
+ builder-util-runtime: 9.7.0([email protected])
chalk: 4.1.2
form-data: 4.0.6
fs-extra: 10.1.0
@@ -2385,9 +2795,9 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
- builder-util-runtime: 9.7.0([email protected])
+ builder-util-runtime: 9.7.0([email protected])
fs-extra: 10.1.0
js-yaml: 4.3.2
lazy-val: 1.0.5
@@ -2398,22 +2808,22 @@ snapshots:
transitivePeerDependencies:
- supports-color
dependencies:
'@electron/asar': 3.4.1
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
fs-extra: 7.0.1
lodash: 4.18.1
temp: 0.9.4
optionalDependencies:
- '@electron/windows-sign': 1.2.2([email protected])
+ '@electron/windows-sign': 1.2.2([email protected])
transitivePeerDependencies:
- supports-color
dependencies:
'@electron-internal/extract-zip': 1.0.5
- '@electron/get': 5.1.0([email protected])
+ '@electron/get': 5.1.0([email protected])
'@types/node': 24.19.1
transitivePeerDependencies:
- supports-color
@@ -2557,6 +2967,12 @@ snapshots:
dependencies:
resolve-pkg-maps: 1.0.0
+ dependencies:
+ minimatch: 10.2.6
+ minipass: 7.1.3
+ path-scurry: 2.0.2
+
dependencies:
fs.realpath: 1.0.0
@@ -2625,10 +3041,10 @@ snapshots:
dependencies:
agent-base: 7.1.4
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -2637,10 +3053,10 @@ snapshots:
quick-lru: 5.1.1
resolve-alpn: 1.2.1
dependencies:
agent-base: 7.1.4
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -2761,6 +3177,8 @@ snapshots:
+
dependencies:
yallist: 4.0.0
@@ -2820,6 +3238,11 @@ snapshots:
+ dependencies:
+ semver: 7.8.5
+ optional: true
+
dependencies:
semver: 7.8.5
@@ -2860,6 +3283,30 @@ snapshots:
dependencies:
wrappy: 1.0.2
+ dependencies:
+ '@oxc-project/types': 0.152.0
+ optionalDependencies:
+ '@oxc-parser/binding-android-arm-eabi': 0.152.0
+ '@oxc-parser/binding-android-arm64': 0.152.0
+ '@oxc-parser/binding-darwin-arm64': 0.152.0
+ '@oxc-parser/binding-darwin-x64': 0.152.0
+ '@oxc-parser/binding-freebsd-x64': 0.152.0
+ '@oxc-parser/binding-linux-arm-gnueabihf': 0.152.0
+ '@oxc-parser/binding-linux-arm-musleabihf': 0.152.0
+ '@oxc-parser/binding-linux-arm64-gnu': 0.152.0
+ '@oxc-parser/binding-linux-arm64-musl': 0.152.0
+ '@oxc-parser/binding-linux-ppc64-gnu': 0.152.0
+ '@oxc-parser/binding-linux-riscv64-gnu': 0.152.0
+ '@oxc-parser/binding-linux-riscv64-musl': 0.152.0
+ '@oxc-parser/binding-linux-s390x-gnu': 0.152.0
+ '@oxc-parser/binding-linux-x64-gnu': 0.152.0
+ '@oxc-parser/binding-linux-x64-musl': 0.152.0
+ '@oxc-parser/binding-openharmony-arm64': 0.152.0
+ '@oxc-parser/binding-win32-arm64-msvc': 0.152.0
+ '@oxc-parser/binding-win32-ia32-msvc': 0.152.0
+ '@oxc-parser/binding-win32-x64-msvc': 0.152.0
+
@@ -2870,6 +3317,11 @@ snapshots:
+ dependencies:
+ lru-cache: 11.5.3
+ minipass: 7.1.3
+
@@ -2934,9 +3386,9 @@ snapshots:
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -3036,6 +3488,8 @@ snapshots:
+
dependencies:
type-fest: 0.13.1
@@ -3083,9 +3537,9 @@ snapshots:
dependencies:
ansi-regex: 5.0.1
dependencies:
- debug: 4.4.3([email protected])
+ debug: 4.4.3([email protected])
transitivePeerDependencies:
- supports-color
@@ -3093,6 +3547,10 @@ snapshots:
dependencies:
has-flag: 4.0.0
+ dependencies:
+ has-flag: 4.0.0
+
dependencies:
'@isaacs/fs-minipass': 4.0.1
@@ -3212,7 +3670,7 @@ snapshots:
fsevents: 2.3.3
jiti: 2.7.0
dependencies:
'@types/chai': 5.2.3
'@vitest/mocker': 5.0.3([email protected](@types/[email protected])([email protected]))
@@ -3229,10 +3687,13 @@ snapshots:
why-is-node-running: 3.2.1
optionalDependencies:
+ '@opentelemetry/api': 1.10.0
'@types/node': 24.19.1
transitivePeerDependencies:
- msw
+
dependencies:
'@peculiar/asn1-schema': 2.10.0
diff --git a/apps/cua-spaces-desktop/pnpm-workspace.yaml b/apps/cua-spaces-desktop/pnpm-workspace.yaml
index 1f28ce61fd..cda9bfc74e 100644
--- a/apps/cua-spaces-desktop/pnpm-workspace.yaml
+++ b/apps/cua-spaces-desktop/pnpm-workspace.yaml
@@ -6,6 +6,8 @@
allowBuilds:
electron: true
electron-winstaller: false
+ # @sentry/electron's optional ANR add-on; crash reporting does not use it.
+ '@sentry/node-native-stacktrace': false
# Security fix (CUA-1948): Electron 44.9.1 distrusts the compromised eMudhra
# intermediates and is newer than the release-age cooldown.
minimumReleaseAgeExclude:
diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.ts
index d893d4c30a..e0037729a4 100644
--- a/apps/cua-spaces-desktop/src/bridge/methods.ts
+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts
@@ -34,7 +34,7 @@ export const METHODS = [
"devices.revoke", "devices.confirmMachine", "devices.createPairingCode", "devices.pairingCodes",
"devices.revokePairingCode", "teams.list", "storage.get", "storage.run",
"notifications.list", "notifications.markAllRead", "notifications.markRead",
- "telemetry.track", "telemetry.linkNotice", "telemetry.acknowledgeLinkNotice", "spaces.usage", "spaces.windows", "stream.pip",
+ "telemetry.track", "telemetry.linkNotice", "telemetry.acknowledgeLinkNotice", "crashReporting.config", "spaces.usage", "spaces.windows", "stream.pip",
"spaces.thumbnail",
"spaces.chooseFiles", "spaces.droppedFiles", "spaces.sendFiles",
"host.setUp", "host.joinWithCode", "host.action", "host.openSettings",
diff --git a/apps/cua-spaces-desktop/src/bridge/settings.ts b/apps/cua-spaces-desktop/src/bridge/settings.ts
index f93fd87293..d420c2e6a9 100644
--- a/apps/cua-spaces-desktop/src/bridge/settings.ts
+++ b/apps/cua-spaces-desktop/src/bridge/settings.ts
@@ -14,6 +14,7 @@ import type { AppModel } from "../model/app-model";
import { words } from "../model/errors";
import { bounded } from "../model/time";
import { string } from "./args";
+import { consentMayHaveChanged } from "../crash-reporting";
import type { BridgeContext } from "./context";
import { Failure, type Handlers } from "./host";
import { hostParts, type HostParts } from "./host-parts";
@@ -182,6 +183,8 @@ export function settingsMethods(ctx: BridgeContext): Handlers {
return;
case "telemetry":
model.telemetry?.setEnabled(option === "on");
+ // Off also stops crash reports (crash-reporting.ts).
+ consentMayHaveChanged();
// The switch sits beside the usage note (Welcome, Settings): the
// notice was seen.
model.telemetry?.acknowledgeNotice();
diff --git a/apps/cua-spaces-desktop/src/bridge/telemetry.ts b/apps/cua-spaces-desktop/src/bridge/telemetry.ts
index 15147197cf..4d01d34481 100644
--- a/apps/cua-spaces-desktop/src/bridge/telemetry.ts
+++ b/apps/cua-spaces-desktop/src/bridge/telemetry.ts
@@ -7,6 +7,7 @@
// locked off, drops every signal here.
import type { Native } from "../native/load";
import type { AppTelemetrySignal } from "../native/generated/index";
+import { crashReportingAnswer } from "../crash-reporting";
import type { BridgeContext } from "./context";
import { Failure, type Handlers } from "./host";
@@ -153,6 +154,11 @@ export function telemetryMethods({ model }: BridgeContext): Handlers {
},
// The one-time linking notice (CUA-1881): the SDK's words and whether
// it is due. No telemetry (a test host) has none.
+ // The page's own crash reports (apps/cua-spaces-web/src/crash-reporting): allowed only while usage data is on and its notice shown.
+ "crashReporting.config": () => {
+ const status = model.telemetry?.status();
+ return crashReportingAnswer(status?.enabled === true && status.noticeShown !== false);
+ },
"telemetry.linkNotice": () => model.telemetry?.linkNotice() ?? null,
"telemetry.acknowledgeLinkNotice": () => {
model.telemetry?.acknowledgeLinkNotice();
diff --git a/apps/cua-spaces-desktop/src/crash-reporting-main.ts b/apps/cua-spaces-desktop/src/crash-reporting-main.ts
new file mode 100644
index 0000000000..d1d59c4ca9
--- /dev/null
+++ b/apps/cua-spaces-desktop/src/crash-reporting-main.ts
@@ -0,0 +1,110 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// Crash reporting, the Electron half (CUA-2343): Sentry in the main process
+// only. It catches native crashes (Crashpad minidumps), main-process errors
+// and one session per launch for release health. The page reports its own
+// errors (apps/cua-spaces-web/src/crash-reporting), and the Rust core and
+// daemon get the same settings through CUA_CRASH_* in the environment.
+//
+// Sentry must start before the app is ready, and before the native library
+// loads, so the consent rule is read from the files the library reads
+// (crash-reporting.ts). Reports stop when the switch goes off (the SDK is
+// closed, and every event is checked again); a switch turned on takes effect
+// at the next launch.
+import { existsSync, readFileSync } from "node:fs";
+import { homedir } from "node:os";
+import * as Sentry from "@sentry/electron/main";
+import { app } from "electron";
+import {
+ crashConsent,
+ crashEnv,
+ crashTestKind,
+ environmentFor,
+ onConsentMayHaveChanged,
+ parseCrashConfig,
+ releaseFor,
+ scrubEvent,
+ setCrashSettings,
+ type ConsentSource,
+ type ScrubbableEvent,
+} from "./crash-reporting";
+
+/** The DSN, from config/spaces-crash-reporting.json at build time (tsdown.config.mts). Absent in a test run. */
+declare const __CUA_CRASH_CONFIG__: string | undefined;
+
+/** Integrations that would record content or the machine's identity: breadcrumbs, local variables and source lines, screenshots, the renderer hooks. */
+const DROPPED = new Set([
+ "Console",
+ "ElectronBreadcrumbs",
+ "ElectronNet",
+ "NodeFetch",
+ "LocalVariables",
+ "ContextLines",
+ "Screenshots",
+ "PreloadInjection",
+ "RendererEventLoopBlock",
+ "RendererProfiling",
+ "AdditionalContext",
+ "GpuContext",
+]);
+
+function machine(): ConsentSource {
+ return {
+ env: process.env,
+ read: (file) => {
+ try {
+ return readFileSync(file, "utf8");
+ } catch {
+ return null;
+ }
+ },
+ exists: (file) => existsSync(file),
+ home: homedir(),
+ };
+}
+
+/** Starts Sentry when a DSN is configured and the switch allows it; call first thing in the main process. */
+export function initCrashReporting(): void {
+ const { dsn } = parseCrashConfig(typeof __CUA_CRASH_CONFIG__ === "string" ? __CUA_CRASH_CONFIG__ : "");
+ if (!dsn) return;
+ const version = app.getVersion();
+ const release = releaseFor(version);
+ const environment = environmentFor(version, app.isPackaged);
+ const test = crashTestKind(process.env.CUA_CRASH_TEST, environment);
+ if (!crashConsent(machine()).allowed) return;
+
+ Object.assign(process.env, crashEnv({ dsn, release, environment }));
+ setCrashSettings({ dsn, release, environment, uiTest: test === "ui" });
+ const home = homedir();
+ Sentry.init({
+ dsn,
+ release,
+ environment,
+ // Sentry 11 replaced `sendDefaultPii` with `dataCollection`: nothing about the user, cookies, headers, bodies or query strings.
+ dataCollection: { userInfo: false, cookies: false, httpHeaders: false, httpBodies: [], urlQueryParams: false },
+ debug: process.env.CUA_CRASH_DEBUG === "1",
+ maxBreadcrumbs: 0,
+ attachScreenshot: false,
+ enableRendererProfiling: false,
+ // No traces, no profiles, no logs.
+ tracesSampleRate: 0,
+ // No renderer is wired to Sentry: no session of the default window, no protocol route.
+ ipcMode: Sentry.IPCMode.Classic,
+ getSessions: () => [],
+ initialScope: { tags: { shell: "electron", component: "shell" } },
+ integrations: (defaults) => defaults.filter((i) => !DROPPED.has(i.name)),
+ beforeBreadcrumb: () => null,
+ beforeSendTransaction: () => null,
+ beforeSend: (event) => (crashConsent(machine()).allowed ? (scrubEvent(event as unknown as ScrubbableEvent, home) as unknown as typeof event) : null),
+ });
+
+ onConsentMayHaveChanged(() => {
+ if (crashConsent(machine()).allowed) return;
+ setCrashSettings(null);
+ void Sentry.close(0);
+ });
+
+ if (test === "main-js") setTimeout(() => { throw new Error("CUA_CRASH_TEST main-js"); }, 4000);
+ if (test === "main-native") setTimeout(() => process.crash(), 4000);
+}
diff --git a/apps/cua-spaces-desktop/src/crash-reporting.ts b/apps/cua-spaces-desktop/src/crash-reporting.ts
new file mode 100644
index 0000000000..f62f4a41b8
--- /dev/null
+++ b/apps/cua-spaces-desktop/src/crash-reporting.ts
@@ -0,0 +1,337 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+// Crash reporting, the pure half (CUA-2343): the consent rule, the release
+// and environment names, the Rust side's environment and the privacy scrub.
+// No Electron and no Sentry here, so it all runs under test; the SDK is wired
+// in crash-reporting-main.ts.
+//
+// Reports are allowed only when the "Share usage data" switch is on and its
+// first-run notice was shown: the decision `cua-telemetry` makes
+// (libs/cua/crates/cua-telemetry/src/config.rs, notice.rs). The app starts
+// Sentry before the native library loads, so the switch is read here from the
+// same places instead of through `telemetryStatus()`.
+import * as path from "node:path";
+
+/** `config/spaces-crash-reporting.json`, as bundled at build time. */
+export interface CrashConfig {
+ dsn: string;
+}
+
+/** The DSN from the config file's text; empty (reporting off) when it is missing or malformed. */
+export function parseCrashConfig(text: string | null | undefined): CrashConfig {
+ try {
+ const dsn = (JSON.parse(text ?? "") as { dsn?: unknown }).dsn;
+ return { dsn: typeof dsn === "string" ? dsn.trim() : "" };
+ } catch {
+ return { dsn: "" };
+ }
+}
+
+/* ---- Names ------------------------------------------------------------------------ */
+
+/** `cua-spaces-desktop@<version>`, the string the update feed carries. */
+export const releaseFor = (version: string): string => `cua-spaces-desktop@${version}`;
+
+export type CrashEnvironment = "stable" | "beta" | "local";
+
+/** The channel: an unpackaged build is `local`, a version with a `-` suffix `beta`, anything else `stable`. */
+export function environmentFor(version: string, packaged: boolean): CrashEnvironment {
+ if (!packaged) return "local";
+ return version.includes("-") ? "beta" : "stable";
+}
+
+/** What the Rust core and daemon read (`cua-crash`), set before either starts. */
+export function crashEnv(o: { dsn: string; release: string; environment: string }): Record<string, string> {
+ return {
+ CUA_CRASH_DSN: o.dsn,
+ CUA_CRASH_RELEASE: o.release,
+ CUA_CRASH_ENVIRONMENT: o.environment,
+ CUA_CRASH_SHELL: "electron",
+ };
+}
+
+/* ---- Consent ---------------------------------------------------------------------- */
+
+type Env = Readonly<Record<string, string | undefined>>;
+
+/** `0/false/no/off/disable(d)` is false, `1/true/yes/on/enable(d)` true (config.rs `parse_bool`). */
+export function parseBool(value: string): boolean | null {
+ switch (value.trim().toLowerCase()) {
+ case "0": case "false": case "no": case "off": case "disable": case "disabled":
+ return false;
+ case "1": case "true": case "yes": case "on": case "enable": case "enabled":
+ return true;
+ default:
+ return null;
+ }
+}
+
+/**
+ * `[telemetry] enabled` of a config.toml: a boolean, a string such as "off"
+ * or an integer. The file is the one `cua config set telemetry off` and
+ * Settings write; only that key is read, so this is a line scan, not TOML.
+ */
+export function configTelemetryEnabled(toml: string): boolean | null {
+ let table = "";
+ for (const raw of toml.split(/\r?\n/)) {
+ const line = raw.replace(/\s+#.*$/, "").trim();
+ if (!line || line.startsWith("#")) continue;
+ const header = /^\[\s*([^\]]+?)\s*\]$/.exec(line);
+ if (header) {
+ table = header[1] ?? "";
+ continue;
+ }
+ const kv = /^([A-Za-z0-9_.-]+)\s*=\s*(.+)$/.exec(line);
+ if (!kv) continue;
+ const key = table ? `${table}.${kv[1]}` : (kv[1] ?? "");
+ if (key !== "telemetry.enabled") continue;
+ const value = (kv[2] ?? "").trim();
+ if (value === "true") return true;
+ if (value === "false") return false;
+ if (/^-?\d+$/.test(value)) return Number(value) !== 0;
+ const str = /^["'](.*)["']$/.exec(value);
+ return str ? parseBool(str[1] ?? "") : null;
+ }
+ return null;
+}
+
+const CI_VARIABLES = [
+ "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",
+];
+
+/** What the consent check reads from the machine. */
+export interface ConsentSource {
+ env: Env;
+ /** The file's text, or null when it is missing. */
+ read(file: string): string | null;
+ exists(file: string): boolean;
+ /** The user's home directory. */
+ home: string;
+}
+
+export interface Consent {
+ allowed: boolean;
+ /** The first rule that decided, for logs and tests. */
+ reason: "do_not_track" | "env" | "legacy_env" | "config" | "ci" | "default" | "notice_pending";
+}
+
+/** `$CUA_HOME`, else `~/.cua` (config.rs `cua_home`). */
+export function cuaHome(s: Pick<ConsentSource, "env" | "home">): string {
+ const set = s.env.CUA_HOME?.trim();
+ return set ? set : path.join(s.env.HOME?.trim() || s.env.USERPROFILE?.trim() || s.home, ".cua");
+}
+
+/**
+ * Whether crash reports may be sent now: the telemetry decision
+ * (`DO_NOT_TRACK`, `CUA_TELEMETRY`, the legacy switches, config.toml, a CI
+ * environment, on by default) says on, and the first-run notice marker
+ * exists. Cheap enough to run for every event.
+ */
+export function crashConsent(s: ConsentSource): Consent {
+ const { env } = s;
+ const no = (reason: Consent["reason"]): Consent => ({ allowed: false, reason });
+ const dnt = env.DO_NOT_TRACK?.trim();
+ if (dnt && dnt !== "0" && dnt.toLowerCase() !== "false") return no("do_not_track");
+ const forced = env.CUA_TELEMETRY === undefined ? null : parseBool(env.CUA_TELEMETRY);
+ let enabled: boolean;
+ let reason: Consent["reason"];
+ if (forced !== null) {
+ enabled = forced;
+ reason = "env";
+ } else if (parseBool(env.CUA_TELEMETRY_ENABLED ?? "") === false || parseBool(env.CUA_TELEMETRY_DISABLED ?? "") === true) {
+ return no("legacy_env");
+ } else {
+ const home = cuaHome(s);
+ let fromConfig: boolean | null = null;
+ try {
+ const text = s.read(path.join(home, "config.toml"));
+ fromConfig = text === null ? null : configTelemetryEnabled(text);
+ } catch {
+ fromConfig = null;
+ }
+ const ci = CI_VARIABLES.some((v) => {
+ const x = env[v]?.trim();
+ return !!x && x.toLowerCase() !== "false" && x !== "0";
+ });
+ enabled = fromConfig ?? !ci;
+ reason = fromConfig !== null ? "config" : ci ? "ci" : "default";
+ }
+ if (!enabled) return no(reason);
+ let shown = false;
+ try {
+ shown = s.exists(path.join(cuaHome(s), "telemetry", "notice_shown"));
+ } catch {
+ shown = false;
+ }
+ return shown ? { allowed: true, reason } : no("notice_pending");
+}
+
+/* ---- Runtime switch ----------------------------------------------------------------- */
+
+const watchers = new Set<() => void>();
+
+/** `listener` runs whenever the usage-data switch may have changed (the Sentry wiring closes the SDK then). */
+export function onConsentMayHaveChanged(listener: () => void): () => void {
+ watchers.add(listener);
+ return () => watchers.delete(listener);
+}
+
+/** The bridge calls this after the page changes the switch. */
+export function consentMayHaveChanged(): void {
+ for (const w of [...watchers]) {
+ try {
+ w();
+ } catch {
+ // Reporting never breaks Settings.
+ }
+ }
+}
+
+/* ---- Privacy ------------------------------------------------------------------------ */
+
+const EMAIL = /[A-Za-z0-9._%+'-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/g;
+const HOME_UNIX = /(?:\/Users|\/home)\/[^/\\\s"'`:;,)\]}]+/g;
+const HOME_WIN = /[A-Za-z]:[\\/]+Users[\\/]+[^\\/"'`:;,)\]}]+/gi;
+
+const escapeRegExp = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+/** Home folders (`/Users/x`, `/home/x`, `C:\Users\x`, the real $HOME) become `~`, emails `[email]`. */
+export function scrubString(value: string, home?: string): string {
+ let out = value.replace(HOME_WIN, "~");
+ for (const h of new Set([home, home?.replace(/\\/g, "/")])) {
+ if (h && h.length > 1) out = out.replace(new RegExp(escapeRegExp(h.replace(/[\\/]+$/, "")), "gi"), "~");
+ }
+ return out.replace(HOME_UNIX, "~").replace(EMAIL, "[email]");
+}
+
+/** A URL without its query string and fragment. */
+export function stripUrl(url: string): string {
+ return url.replace(/[?#].*$/, "");
+}
+
+/** Strings that name no one: keys and values that are URLs lose their query and fragment. */
+function scrubDeep(value: unknown, home: string | undefined, depth = 0): unknown {
+ if (typeof value === "string") {
+ const s = /^[a-z][a-z0-9+.-]*:\/\//i.test(value) ? stripUrl(value) : value;
+ return scrubString(s, home);
+ }
+ if (depth > 12 || value === null || typeof value !== "object") return value;
+ if (Array.isArray(value)) return value.map((v) => scrubDeep(v, home, depth + 1));
+ const out: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(value)) out[k] = scrubDeep(v, home, depth + 1);
+ return out;
+}
+
+/** The parts of a Sentry event the scrub touches (the SDK's own types are wider). */
+export interface ScrubbableEvent {
+ message?: string;
+ logentry?: unknown;
+ exception?: { values?: { type?: string; value?: string; module?: string; stacktrace?: { frames?: Record<string, unknown>[] } }[] };
+ [key: string]: unknown;
+}
+
+/**
+ * The event as it may leave the machine. Exception values (messages), the
+ * message and log entry are cleared whatever they hold: they can carry Space
+ * names, file names and emails. Type, module and stack frames stay, with
+ * paths scrubbed. Everything else is scrubbed or dropped: user, breadcrumbs,
+ * attachments, request data beyond a query-free URL, server name, device
+ * name, app name. Returns a new object.
+ */
+export function scrubEvent<T extends ScrubbableEvent>(event: T, home?: string): T {
+ const e: ScrubbableEvent = { ...event };
+ delete e.user;
+ delete e.breadcrumbs;
+ delete e.logentry;
+ delete e.message;
+ delete e.server_name;
+ delete e.attachments;
+ delete e.threads;
+ e.server_name = "";
+ if (e.exception?.values) {
+ e.exception = {
+ ...e.exception,
+ values: e.exception.values.map((v) => ({
+ ...v,
+ value: "",
+ ...(v.stacktrace?.frames ? { stacktrace: { ...v.stacktrace, frames: v.stacktrace.frames.map((f) => scrubFrame(f, home)) } } : {}),
+ })),
+ };
+ }
+ if (e.request && typeof e.request === "object") {
+ const url = (e.request as { url?: unknown }).url;
+ e.request = typeof url === "string" ? { url: scrubString(stripUrl(url), home) } : {};
+ }
+ for (const key of ["tags", "extra", "contexts", "debug_meta", "modules", "sdk", "fingerprint", "transaction", "culprit"]) {
+ if (e[key] !== undefined) e[key] = scrubDeep(e[key], home);
+ }
+ const contexts = e.contexts as Record<string, Record<string, unknown>> | undefined;
+ if (contexts) {
+ if (contexts.app) delete contexts.app.app_name;
+ if (contexts.device) {
+ delete contexts.device.name;
+ delete contexts.device.hostname;
+ }
+ delete contexts.culture;
+ delete contexts.cloud_resource;
+ }
+ return e as T;
+}
+
+function scrubFrame(frame: Record<string, unknown>, home: string | undefined): Record<string, unknown> {
+ const out: Record<string, unknown> = { ...frame };
+ for (const k of ["filename", "abs_path"]) {
+ if (typeof out[k] === "string") out[k] = scrubString(stripUrl(out[k] as string), home);
+ }
+ for (const k of ["module", "function"]) {
+ if (typeof out[k] === "string") out[k] = scrubString(out[k] as string, home);
+ }
+ // Source lines and local variables are content, not code location.
+ for (const k of ["context_line", "pre_context", "post_context", "vars"]) delete out[k];
+ return out;
+}
+
+/* ---- What the page is told ------------------------------------------------------------ */
+
+/** The settings this process started crash reporting with (null: not configured or not started). */
+export interface CrashSettings {
+ dsn: string;
+ release: string;
+ environment: CrashEnvironment;
+ /** CUA_CRASH_TEST=ui, honoured on a local build only. */
+ uiTest: boolean;
+}
+
+let settings: CrashSettings | null = null;
+
+export function setCrashSettings(next: CrashSettings | null): void {
+ settings = next;
+}
+
+/** The answer to the page's `crashReporting.config`: `allowed` follows the switch as it is now. */
+export function crashReportingAnswer(switchOn: boolean): {
+ allowed: boolean;
+ dsn: string;
+ release: string;
+ environment: string;
+ shell: "electron";
+ crashTest?: "ui";
+} {
+ if (!settings || !settings.dsn) return { allowed: false, dsn: "", release: "", environment: "", shell: "electron" };
+ return {
+ allowed: switchOn,
+ dsn: settings.dsn,
+ release: settings.release,
+ environment: settings.environment,
+ shell: "electron",
+ ...(settings.uiTest && settings.environment === "local" ? { crashTest: "ui" as const } : {}),
+ };
+}
+
+/** The forced crash a local build runs on request (CUA_CRASH_TEST); anything else, or any other channel, is none. */
+export function crashTestKind(value: string | undefined, environment: string): "main-js" | "main-native" | "ui" | null {
+ if (environment !== "local") return null;
+ return value === "main-js" || value === "main-native" || value === "ui" ? value : null;
+}
diff --git a/apps/cua-spaces-desktop/src/main.ts b/apps/cua-spaces-desktop/src/main.ts
index 9d02dfd56a..fd4e712844 100644
--- a/apps/cua-spaces-desktop/src/main.ts
+++ b/apps/cua-spaces-desktop/src/main.ts
@@ -6,6 +6,7 @@ import { readFileSync } from "node:fs";
import { homedir } from "node:os";
import * as path from "node:path";
import { app, BrowserWindow, dialog, nativeTheme, Notification, screen, shell } from "electron";
+import { initCrashReporting } from "./crash-reporting-main";
import { createBridge } from "./bridge";
import { hasBrowser } from "./browser";
import { appBuild } from "./bundle-version";
@@ -60,6 +61,9 @@ if (process.platform === "linux") {
app.setDesktopName(`${LINUX_ID}.desktop`);
}
if (process.env.CUA_SPACES_USER_DATA) app.setPath("userData", process.env.CUA_SPACES_USER_DATA);
+// Crash reporting as early as the app's name and data folder are settled (Sentry keeps its queue
+// and the Crashpad reports there) and before the native library loads, which reads CUA_CRASH_*.
+initCrashReporting();
// The page decodes Spaces' video with WebCodecs: on the GPU where it can (gpu.ts).
applyVideoDecodeSwitches(app.commandLine, process.platform, process.env);
// macOS: Chromium's cookie key stays out of the keychain, so its prompt can't freeze the app (chromium-keychain.ts).
diff --git a/apps/cua-spaces-desktop/test/crash-reporting.test.ts b/apps/cua-spaces-desktop/test/crash-reporting.test.ts
new file mode 100644
index 0000000000..f671126aad
--- /dev/null
+++ b/apps/cua-spaces-desktop/test/crash-reporting.test.ts
@@ -0,0 +1,234 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import * as path from "node:path";
+import { describe, expect, it, vi } from "vitest";
+import {
+ configTelemetryEnabled,
+ consentMayHaveChanged,
+ crashConsent,
+ crashEnv,
+ crashReportingAnswer,
+ crashTestKind,
+ environmentFor,
+ onConsentMayHaveChanged,
+ parseCrashConfig,
+ releaseFor,
+ scrubEvent,
+ scrubString,
+ setCrashSettings,
+ type ConsentSource,
+} from "../src/crash-reporting";
+
+const HOME = "/Users/jane";
+
+/** A machine with the given files and environment. */
+function machine(files: Record<string, string>, env: Record<string, string> = {}): ConsentSource {
+ const at = (f: string) => path.normalize(f);
+ const fs = new Map(Object.entries(files).map(([k, v]) => [at(k), v]));
+ return { env: { HOME, ...env }, read: (f) => fs.get(at(f)) ?? null, exists: (f) => fs.has(at(f)), home: HOME };
+}
+const NOTICE = { "/Users/jane/.cua/telemetry/notice_shown": "" };
+
+describe("config and names", () => {
+ it("reads the DSN, and an empty or broken file is off", () => {
+ expect(parseCrashConfig('{"org":"trycua","dsn":" https://[email protected]/2 "}').dsn).toBe("https://[email protected]/2");
+ expect(parseCrashConfig('{"dsn":""}').dsn).toBe("");
+ expect(parseCrashConfig("not json").dsn).toBe("");
+ expect(parseCrashConfig(null).dsn).toBe("");
+ expect(parseCrashConfig('{"dsn":5}').dsn).toBe("");
+ });
+
+ it("names the release and the channel", () => {
+ expect(releaseFor("0.7.2")).toBe("[email protected]");
+ expect(environmentFor("0.7.2", true)).toBe("stable");
+ expect(environmentFor("0.7.2-beta.1", true)).toBe("beta");
+ expect(environmentFor("0.7.2", false)).toBe("local");
+ expect(environmentFor("0.7.2-beta.1", false)).toBe("local");
+ });
+
+ it("gives the Rust side its four variables", () => {
+ expect(crashEnv({ dsn: "d", release: "r", environment: "beta" })).toEqual({
+ CUA_CRASH_DSN: "d",
+ CUA_CRASH_RELEASE: "r",
+ CUA_CRASH_ENVIRONMENT: "beta",
+ CUA_CRASH_SHELL: "electron",
+ });
+ });
+});
+
+describe("config.toml", () => {
+ it("reads [telemetry] enabled as the SDK does", () => {
+ expect(configTelemetryEnabled('[telemetry]\nenabled = "off"\n')).toBe(false);
+ expect(configTelemetryEnabled('[telemetry]\nenabled = "on" # comment\n')).toBe(true);
+ expect(configTelemetryEnabled("[telemetry]\nenabled = false")).toBe(false);
+ expect(configTelemetryEnabled("[telemetry]\nenabled = 1")).toBe(true);
+ expect(configTelemetryEnabled("telemetry.enabled = 'no'")).toBe(false);
+ expect(configTelemetryEnabled('[other]\nenabled = "off"\n[telemetry]\nx = 1')).toBeNull();
+ expect(configTelemetryEnabled("")).toBeNull();
+ expect(configTelemetryEnabled('[telemetry]\nenabled = "maybe"')).toBeNull();
+ });
+});
+
+describe("consent", () => {
+ it("is on once the notice was shown and nothing turned usage data off", () => {
+ expect(crashConsent(machine(NOTICE))).toEqual({ allowed: true, reason: "default" });
+ });
+
+ it("waits for the first-run notice", () => {
+ expect(crashConsent(machine({}))).toEqual({ allowed: false, reason: "notice_pending" });
+ expect(crashConsent(machine({}, { CUA_TELEMETRY: "1" })).allowed).toBe(false);
+ });
+
+ it("follows the Settings switch in config.toml", () => {
+ const off = machine({ ...NOTICE, "/Users/jane/.cua/config.toml": '[telemetry]\nenabled = "off"\n' });
+ expect(crashConsent(off)).toEqual({ allowed: false, reason: "config" });
+ const on = machine({ ...NOTICE, "/Users/jane/.cua/config.toml": '[telemetry]\nenabled = "on"\n' });
+ expect(crashConsent(on).allowed).toBe(true);
+ });
+
+ it("honours DO_NOT_TRACK and CUA_TELEMETRY over the file", () => {
+ const on = { ...NOTICE, "/Users/jane/.cua/config.toml": '[telemetry]\nenabled = "on"\n' };
+ expect(crashConsent(machine(on, { DO_NOT_TRACK: "1" }))).toEqual({ allowed: false, reason: "do_not_track" });
+ expect(crashConsent(machine(on, { DO_NOT_TRACK: "0" })).allowed).toBe(true);
+ expect(crashConsent(machine(on, { CUA_TELEMETRY: "off" }))).toEqual({ allowed: false, reason: "env" });
+ const off = { ...NOTICE, "/Users/jane/.cua/config.toml": '[telemetry]\nenabled = "off"\n' };
+ expect(crashConsent(machine(off, { CUA_TELEMETRY: "1" })).allowed).toBe(true);
+ expect(crashConsent(machine(NOTICE, { CUA_TELEMETRY_DISABLED: "1" })).reason).toBe("legacy_env");
+ expect(crashConsent(machine(NOTICE, { CUA_TELEMETRY_ENABLED: "false" })).reason).toBe("legacy_env");
+ });
+
+ it("is off in CI unless the file or CUA_TELEMETRY says on", () => {
+ expect(crashConsent(machine(NOTICE, { GITHUB_ACTIONS: "true" }))).toEqual({ allowed: false, reason: "ci" });
+ expect(crashConsent(machine(NOTICE, { CI: "false" })).allowed).toBe(true);
+ expect(crashConsent(machine(NOTICE, { CI: "1", CUA_TELEMETRY: "1" })).allowed).toBe(true);
+ });
+
+ it("reads $CUA_HOME, and an unreadable file is not consent to turn off", () => {
+ const m = machine({ "/tmp/cua/telemetry/notice_shown": "", "/tmp/cua/config.toml": '[telemetry]\nenabled = "off"' }, { CUA_HOME: "/tmp/cua" });
+ expect(crashConsent(m).allowed).toBe(false);
+ const broken: ConsentSource = { ...machine(NOTICE), read: () => { throw new Error("EACCES"); } };
+ expect(crashConsent(broken).allowed).toBe(true);
+ });
+});
+
+describe("the runtime switch", () => {
+ it("tells the listeners, and one that throws does not stop the rest", () => {
+ const a = vi.fn(() => { throw new Error("x"); });
+ const b = vi.fn();
+ const offA = onConsentMayHaveChanged(a);
+ const offB = onConsentMayHaveChanged(b);
+ consentMayHaveChanged();
+ expect([a.mock.calls.length, b.mock.calls.length]).toEqual([1, 1]);
+ offA();
+ offB();
+ consentMayHaveChanged();
+ expect([a.mock.calls.length, b.mock.calls.length]).toEqual([1, 1]);
+ });
+});
+
+describe("what the page is told", () => {
+ it("is off without settings", () => {
+ setCrashSettings(null);
+ expect(crashReportingAnswer(true)).toMatchObject({ allowed: false, dsn: "" });
+ });
+
+ it("follows the switch, and offers the UI test only on a local build", () => {
+ setCrashSettings({ dsn: "d", release: "[email protected]", environment: "stable", uiTest: true });
+ expect(crashReportingAnswer(true)).toEqual({ allowed: true, dsn: "d", release: "[email protected]", environment: "stable", shell: "electron" });
+ expect(crashReportingAnswer(false).allowed).toBe(false);
+ setCrashSettings({ dsn: "d", release: "r", environment: "local", uiTest: true });
+ expect(crashReportingAnswer(true).crashTest).toBe("ui");
+ setCrashSettings(null);
+ });
+
+ it("runs a forced crash on a local build only", () => {
+ expect(crashTestKind("main-js", "local")).toBe("main-js");
+ expect(crashTestKind("main-native", "local")).toBe("main-native");
+ expect(crashTestKind("ui", "local")).toBe("ui");
+ expect(crashTestKind("main-js", "stable")).toBeNull();
+ expect(crashTestKind("main-js", "beta")).toBeNull();
+ expect(crashTestKind("nope", "local")).toBeNull();
+ expect(crashTestKind(undefined, "local")).toBeNull();
+ });
+});
+
+describe("scrubbing", () => {
+ it("shortens home folders and hides emails", () => {
+ expect(scrubString("/Users/jane/Library/Cua/app.asar/main.cjs")).toBe("~/Library/Cua/app.asar/main.cjs");
+ expect(scrubString("at /home/bob/.cua/x.js:1")).toBe("at ~/.cua/x.js:1");
+ expect(scrubString("C:\\Users\\Jane Doe\\AppData\\x.js")).toBe("~\\AppData\\x.js");
+ expect(scrubString("D:/Users/jane/x")).toBe("~/x");
+ expect(scrubString("mail [email protected] now")).toBe("mail [email] now");
+ expect(scrubString("/opt/jane/x", "/opt/jane")).toBe("~/x");
+ expect(scrubString("/Volumes/data/me/x", "/Volumes/data/me/")).toBe("~/x");
+ });
+
+ const event = () => ({
+ message: "could not open Space 'Jane's Secret'",
+ logentry: { message: "x %s", params: ["[email protected]"] },
+ user: { id: "1", ip_address: "{{auto}}", email: "[email protected]" },
+ server_name: "janes-mbp.local",
+ breadcrumbs: [{ message: "click" }],
+ attachments: [{ filename: "screen.png" }],
+ exception: {
+ values: [
+ {
+ type: "TypeError",
+ value: "ENOENT: /Users/jane/Documents/taxes.pdf for [email protected]",
+ module: "main",
+ stacktrace: {
+ frames: [
+ { filename: "/Users/jane/Cua Spaces.app/Contents/Resources/app.asar/dist-electron/main.cjs", function: "open", lineno: 3, vars: { secret: "x" }, context_line: "const secret = 1" },
+ { abs_path: "file:///C:/Users/Jane/app/main.cjs?x=1#y", function: "Foo#bar" },
+ ],
+ },
+ },
+ ],
+ },
+ request: { url: "https://cua.ai/a?token=abc#frag", headers: { cookie: "c" }, data: "body" },
+ tags: { shell: "electron", where: "/Users/jane/x", who: "[email protected]" },
+ extra: { nested: { path: "/home/bob/y", list: ["/Users/jane/z"] } },
+ contexts: { app: { app_name: "Cua Spaces", app_version: "1" }, device: { name: "janes-mbp", family: "Desktop" }, runtime: { name: "Electron" } },
+ });
+
+ it("clears messages and values, keeps type, module and frames", () => {
+ const out = scrubEvent(event(), HOME);
+ expect(out.message).toBeUndefined();
+ expect(out.logentry).toBeUndefined();
+ const v = out.exception!.values![0]!;
+ expect(v).toMatchObject({ type: "TypeError", value: "", module: "main" });
+ expect(v.stacktrace!.frames![0]).toEqual({ filename: "~/Cua Spaces.app/Contents/Resources/app.asar/dist-electron/main.cjs", function: "open", lineno: 3 });
+ expect(v.stacktrace!.frames![1]).toEqual({ abs_path: "file:///~/app/main.cjs", function: "Foo#bar" });
+ });
+
+ it("drops the user, breadcrumbs, attachments and the host name", () => {
+ const out = scrubEvent(event(), HOME);
+ expect(out.user).toBeUndefined();
+ expect(out.breadcrumbs).toBeUndefined();
+ expect(out.attachments).toBeUndefined();
+ expect(out.server_name).toBe("");
+ expect(out.contexts).toEqual({ app: { app_version: "1" }, device: { family: "Desktop" }, runtime: { name: "Electron" } });
+ });
+
+ it("keeps a URL without its query, and no headers or body", () => {
+ expect(scrubEvent(event(), HOME).request).toEqual({ url: "https://cua.ai/a" });
+ });
+
+ it("scrubs what is left", () => {
+ const out = scrubEvent(event(), HOME);
+ expect(out.tags).toEqual({ shell: "electron", where: "~/x", who: "[email]" });
+ expect(out.extra).toEqual({ nested: { path: "~/y", list: ["~/z"] } });
+ });
+
+ it("leaves nothing identifying anywhere in the result", () => {
+ const text = JSON.stringify(scrubEvent(event(), HOME));
+ for (const needle of ["jane", "Jane", "bob", "@", "janes-mbp", "taxes", "Secret", "token=abc", "frag"]) expect(text).not.toContain(needle);
+ });
+
+ it("does not change the event it was given", () => {
+ const e = event();
+ scrubEvent(e, HOME);
+ expect(e).toEqual(event());
+ });
+});
diff --git a/apps/cua-spaces-desktop/tsdown.config.mts b/apps/cua-spaces-desktop/tsdown.config.mts
index a1cb787c99..e770da3217 100644
--- a/apps/cua-spaces-desktop/tsdown.config.mts
+++ b/apps/cua-spaces-desktop/tsdown.config.mts
@@ -1,5 +1,20 @@
+import { readFileSync } from "node:fs";
import { defineConfig, type UserConfig } from "tsdown";
+// The crash-reporting DSN (a public ingest key) comes from
+// config/spaces-crash-reporting.json, so every shell reads one file. A build
+// can override it with CUA_SPACES_CRASH_DSN; an empty DSN leaves crash
+// reporting off.
+function crashConfig(): string {
+ let dsn = "";
+ try {
+ dsn = String(JSON.parse(readFileSync(new URL("../../config/spaces-crash-reporting.json", import.meta.url), "utf8")).dsn ?? "");
+ } catch {
+ // No file: off.
+ }
+ return JSON.stringify({ dsn: (process.env.CUA_SPACES_CRASH_DSN ?? dsn).trim() });
+}
+
// Everything ships as CommonJS: a sandboxed preload cannot load ESM, and CJS
// lets boot.cjs turn on the compile cache before main.cjs loads.
const shared: UserConfig = {
@@ -10,7 +25,9 @@ const shared: UserConfig = {
sourcemap: true,
dts: false,
fixedExtension: true,
- deps: { neverBundle: ["electron", "electron-updater", "./main.cjs"] },
+ // @sentry/electron stays a runtime dependency, packaged beside electron-updater.
+ deps: { neverBundle: ["electron", "electron-updater", /^@sentry\//, "./main.cjs"] },
+ define: { __CUA_CRASH_CONFIG__: JSON.stringify(crashConfig()) },
};
export default defineConfig([
diff --git a/apps/cua-spaces-macos/Package.resolved b/apps/cua-spaces-macos/Package.resolved
index 479e7d7b3a..90cb79c17a 100644
--- a/apps/cua-spaces-macos/Package.resolved
+++ b/apps/cua-spaces-macos/Package.resolved
@@ -1,5 +1,5 @@
{
- "originHash" : "b52af08eb5059379c96073b62be34e36c80d7a32917ac65823e7870e63a761da",
+ "originHash" : "375f1a9bef85c2a7a5ea7bfa19f2ca07f3ebed0b16ce2e9963709809fb38cda5",
"pins" : [
{
"identity" : "permissionflow",
@@ -10,6 +10,15 @@
"version" : "2.11.4"
}
},
+ {
+ "identity" : "sentry-cocoa",
+ "kind" : "remoteSourceControl",
+ "location" : "https://github.com/getsentry/sentry-cocoa",
+ "state" : {
+ "revision" : "2f64c77f77514acd01780d1aac86ae75b7fccd04",
+ "version" : "9.31.0"
+ }
+ },
{
"identity" : "sparkle",
"kind" : "remoteSourceControl",
diff --git a/apps/cua-spaces-macos/Package.swift b/apps/cua-spaces-macos/Package.swift
index d01d420117..69d91eb705 100644
--- a/apps/cua-spaces-macos/Package.swift
+++ b/apps/cua-spaces-macos/Package.swift
@@ -29,6 +29,12 @@ import PackageDescription
// Its strings ship as a SwiftPM resource bundle, which build-app.sh copies
// into Contents/Resources like ours.
//
+// sentry-cocoa (pinned; Package.resolved) reports crashes (CrashReporting.swift,
+// config/spaces-crash-reporting.json). The `Sentry` product is the static
+// library: it links into the executable, so the bundle gains no framework to
+// embed or sign. (`Sentry-Dynamic` would; do not switch to it without
+// teaching build-app.sh and build-release.sh to embed and sign it like Sparkle.)
+//
// UI tests (XCUITest) live in UITests/ and build through project.yml
// (XcodeGen) on a macOS runner with Xcode.
let package = Package(
@@ -46,6 +52,7 @@ let package = Package(
.package(name: "CuaSpacesNotch", path: "../../libs/spaces-notch-swift"),
.package(url: "https://github.com/sparkle-project/Sparkle", exact: "2.10.0"),
.package(url: "https://github.com/jaywcjlove/PermissionFlow", exact: "2.11.4"),
+ .package(url: "https://github.com/getsentry/sentry-cocoa", exact: "9.31.0"),
],
targets: [
.target(
@@ -59,6 +66,7 @@ let package = Package(
.product(name: "CuaSpacesNotchUI", package: "CuaSpacesNotch"),
.product(name: "Sparkle", package: "Sparkle"),
.product(name: "PermissionFlow", package: "PermissionFlow"),
+ .product(name: "Sentry", package: "sentry-cocoa"),
],
path: "Sources/CuaSpacesMacKit",
resources: [.process("Resources")],
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift
index 8075881c99..ef2875305f 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMac/main.swift
@@ -24,6 +24,11 @@ if CommandLine.arguments.dropFirst().first == "--check-launch-only" {
// build changes nothing here.
TargetEnvironment.pinChannel()
+// Crash reporting, as early as the switch can be read (it lives in the
+// channel's home, settled above) and before the Rust core or the daemon start:
+// it sets the CUA_CRASH_* variables they inherit. Off without a DSN or consent.
+CrashReporting.start()
+
// The host service, run by this same executable so every permission is the
// app's ("Cua Spaces"; ServiceLauncher.swift), before anything else:
// * `--service-helper run`: the service itself (the login item launchd
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
index f303dd110e..d8d8e055ee 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift
@@ -1909,6 +1909,10 @@ public final class AppModel {
// The switch sits beside the usage note (the first run's
// Welcome, Settings): the notice was seen.
telemetry?.acknowledgeNotice()
+ // Crash reports follow the switch: off closes the reporter now.
+ if let input = telemetryInput {
+ CrashReporting.switchChanged(enabled: input.enabled, noticeShown: true)
+ }
} catch {
show(error: LiveSpacesBackend.words(error))
}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/CrashReporting.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/CrashReporting.swift
new file mode 100644
index 0000000000..902326e1a8
--- /dev/null
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/CrashReporting.swift
@@ -0,0 +1,233 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import CuaSDK
+import Foundation
+import Sentry
+
+/// Crash reporting for the app (CUA-2343), through sentry-cocoa.
+///
+/// Off unless the bundle carries a DSN (Info.plist `CuaCrashDSN`, written by
+/// `scripts/build-app.sh` from `config/spaces-crash-reporting.json`; empty =
+/// off) and the person allows it: the "Share usage data" switch is on and the
+/// first-run notice was shown, the same rule usage events follow. It is
+/// checked at start and again for every event. Turning the switch off while
+/// the app runs closes the SDK; turning it on takes effect at the next launch.
+///
+/// What leaves the machine: the crash or error's type, module and stack
+/// frames, the release, the environment, the OS and device model, and the
+/// session (crash-free rate). Never messages, usernames, emails, the host
+/// name, screenshots, the view hierarchy, breadcrumbs, traces or an IP.
+public enum CrashReporting {
+ /// What the app tells the Rust core and the daemon (they inherit it).
+ public struct Settings: Equatable {
+ public var dsn: String
+ public var release: String
+ public var environment: String
+ }
+
+ // MARK: Pure logic (unit-tested)
+
+ /// Reports are allowed only when usage data is shared and the notice was
+ /// shown (`Status.enabled && Status.notice_shown`).
+ static func isAllowed(enabled: Bool, noticeShown: Bool) -> Bool { enabled && noticeShown }
+
+ /// `local` for a Local build, `beta` for a version with a `-` suffix,
+ /// otherwise `stable`.
+ static func environment(channel: String?, version: String) -> String {
+ if (channel ?? "").trimmingCharacters(in: .whitespaces).lowercased() == "local" { return "local" }
+ return version.contains("-") ? "beta" : "stable"
+ }
+
+ static func release(version: String) -> String { "cua-spaces-desktop@\(version)" }
+
+ /// The app's version: `CuaVersion` (a release build stamps the full
+ /// string, suffix included), else `CFBundleShortVersionString`.
+ static func version(info: [String: Any]) -> String {
+ for key in ["CuaVersion", "CFBundleShortVersionString"] {
+ if let v = (info[key] as? String)?.trimmingCharacters(in: .whitespaces), !v.isEmpty { return v }
+ }
+ return "0"
+ }
+
+ /// The settings for a bundle, or nil when crash reporting is off (no DSN).
+ static func settings(info: [String: Any]) -> Settings? {
+ let dsn = ((info["CuaCrashDSN"] as? String) ?? "").trimmingCharacters(in: .whitespacesAndNewlines)
+ guard !dsn.isEmpty else { return nil }
+ let version = version(info: info)
+ return Settings(dsn: dsn, release: release(version: version),
+ environment: environment(channel: info["CuaChannel"] as? String, version: version))
+ }
+
+ /// The variables the Rust core and daemon read (`cua-crash`).
+ static func childEnvironment(_ s: Settings) -> [String: String] {
+ ["CUA_CRASH_DSN": s.dsn, "CUA_CRASH_RELEASE": s.release,
+ "CUA_CRASH_ENVIRONMENT": s.environment, "CUA_CRASH_SHELL": "swift"]
+ }
+
+ /// The forced crash for testing the pipeline: `CUA_CRASH_TEST=swift` (or
+ /// the launch argument `--crash-test=swift`), honoured only in a Local build.
+ static func wantsForcedCrash(env: [String: String], args: [String], environment: String) -> Bool {
+ guard environment == "local" else { return false }
+ return env["CUA_CRASH_TEST"] == "swift" || args.contains("--crash-test=swift")
+ }
+
+ /// The page's `crashReporting.config` answer (`CrashReportingConfig`).
+ /// `allowed` is the consent rule; the DSN, release and environment are the
+ /// build's. `crashTest` is set only in a Local build.
+ static func bridgeConfig(info: [String: Any], allowed: Bool, env: [String: String]) -> [String: Any] {
+ let version = version(info: info)
+ let environment = environment(channel: info["CuaChannel"] as? String, version: version)
+ var out: [String: Any] = [
+ "allowed": allowed,
+ "dsn": ((info["CuaCrashDSN"] as? String) ?? "").trimmingCharacters(in: .whitespacesAndNewlines),
+ "release": release(version: version), "environment": environment, "shell": "swift",
+ ]
+ if environment == "local", env["CUA_CRASH_TEST"] == "ui" { out["crashTest"] = "ui" }
+ return out
+ }
+
+ private static let emailPattern = try! NSRegularExpression(
+ pattern: "[A-Za-z0-9._%+\\-]+@[A-Za-z0-9\\-]+(?:\\.[A-Za-z0-9\\-]+)+")
+ private static let homePatterns: [NSRegularExpression] = [
+ try! NSRegularExpression(pattern: "/Users/[^/\\s\"']+"),
+ try! NSRegularExpression(pattern: "/home/[^/\\s\"']+"),
+ try! NSRegularExpression(pattern: "[A-Za-z]:\\\\Users\\\\[^\\\\\\s\"']+"),
+ ]
+
+ /// Home folders become `~`, emails `[email]`.
+ static func scrub(_ text: String, home: String = NSHomeDirectory()) -> String {
+ var out = text
+ let trimmedHome = home.hasSuffix("/") ? String(home.dropLast()) : home
+ if trimmedHome.count > 1 { out = out.replacingOccurrences(of: trimmedHome, with: "~") }
+ for re in homePatterns {
+ out = re.stringByReplacingMatches(in: out, range: NSRange(out.startIndex..., in: out), withTemplate: "~")
+ }
+ return emailPattern.stringByReplacingMatches(
+ in: out, range: NSRange(out.startIndex..., in: out), withTemplate: "[email]")
+ }
+
+ /// A request URL without its query string and fragment, scrubbed.
+ static func scrubURL(_ url: String, home: String = NSHomeDirectory()) -> String {
+ var s = url
+ if let i = s.firstIndex(where: { $0 == "?" || $0 == "#" }) { s = String(s[..<i]) }
+ return scrub(s, home: home)
+ }
+
+ /// Scrubs any value that can carry text (strings, and containers of them).
+ static func scrubValue(_ value: Any, home: String) -> Any {
+ switch value {
+ case let s as String: return scrub(s, home: home)
+ case let d as [String: Any]: return d.mapValues { scrubValue($0, home: home) }
+ case let a as [Any]: return a.map { scrubValue($0, home: home) }
+ default: return value
+ }
+ }
+
+ private static func scrubFrames(_ stacktrace: SentryStacktrace?, home: String) {
+ for frame in stacktrace?.frames ?? [] {
+ if let f = frame.fileName { frame.fileName = scrub(f, home: home) }
+ if let p = frame.package { frame.package = scrub(p, home: home) }
+ if let m = frame.module { frame.module = scrub(m, home: home) }
+ }
+ }
+
+ /// The contract's privacy rules for one event; nil drops it (not allowed).
+ static func sanitize(_ event: Event, allowed: Bool, home: String = NSHomeDirectory()) -> Event? {
+ guard allowed else { return nil }
+ // Messages can carry Space names, file names and emails: type, module
+ // and frames stay, values go.
+ for exception in event.exceptions ?? [] {
+ exception.value = ""
+ scrubFrames(exception.stacktrace, home: home)
+ }
+ for thread in event.threads ?? [] { scrubFrames(thread.stacktrace, home: home) }
+ event.message = nil
+ event.user = nil
+ event.serverName = nil
+ event.breadcrumbs = nil
+ event.tags = event.tags?.mapValues { scrub($0, home: home) }
+ event.extra = event.extra?.mapValues { scrubValue($0, home: home) }
+ if let request = event.request {
+ if let url = request.url { request.url = scrubURL(url, home: home) }
+ request.queryString = nil
+ request.fragment = nil
+ request.cookies = nil
+ request.headers = nil
+ request.bodySize = 0
+ }
+ if var context = event.context {
+ // The device name is the Mac's host name.
+ if var device = context["device"] {
+ device.removeValue(forKey: "name")
+ context["device"] = device
+ }
+ event.context = context.mapValues { $0.mapValues { scrubValue($0, home: home) } }
+ }
+ return event
+ }
+
+ // MARK: Start and stop
+
+ /// The switch as the app core stores it (`telemetryStatus()`).
+ private static func currentlyAllowed() -> Bool {
+ let s = telemetryStatus()
+ return isAllowed(enabled: s.enabled, noticeShown: s.noticeShown)
+ }
+
+ private nonisolated(unsafe) static var started = false
+
+ /// Call early in `main`, after `TargetEnvironment.pinChannel()` (the
+ /// switch lives in the channel's home) and before anything starts the
+ /// Rust core or the daemon. A no-op without a DSN or without consent.
+ public static func start(bundle: Bundle = .main,
+ environment: [String: String] = ProcessInfo.processInfo.environment,
+ arguments: [String] = CommandLine.arguments) {
+ guard environment["CUA_SPACES_FIXTURES"] != "1",
+ let settings = settings(info: bundle.infoDictionary ?? [:]),
+ currentlyAllowed() else { return }
+ for (key, value) in childEnvironment(settings) { setenv(key, value, 1) }
+ SentrySDK.start { options in
+ options.dsn = settings.dsn
+ options.releaseName = settings.release
+ options.environment = settings.environment
+ options.sendDefaultPii = false
+ options.enableCrashHandler = true
+ options.enableAutoSessionTracking = true
+ options.attachStacktrace = true
+ options.enableAutoBreadcrumbTracking = false
+ options.enableNetworkBreadcrumbs = false
+ options.enableNetworkTracking = false
+ options.enableCaptureFailedRequests = false
+ options.enableAutoPerformanceTracing = false
+ options.enableSwizzling = false
+ options.enableAppHangTracking = false
+ options.enableMetricKit = false
+ options.maxBreadcrumbs = 0
+ options.tracesSampleRate = 0
+ options.beforeSend = { event in sanitize(event, allowed: currentlyAllowed()) }
+ }
+ SentrySDK.configureScope { scope in
+ scope.setTag(value: "swift", key: "shell")
+ scope.setTag(value: "shell", key: "component")
+ scope.setUser(nil)
+ }
+ started = true
+ if wantsForcedCrash(env: environment, args: arguments, environment: settings.environment) {
+ DispatchQueue.main.asyncAfter(deadline: .now() + 3) { forcedCrash() }
+ }
+ }
+
+ /// The Settings switch changed: closes the SDK when reports are no
+ /// longer allowed (it is not restarted until the next launch).
+ public static func switchChanged(enabled: Bool, noticeShown: Bool) {
+ guard started, !isAllowed(enabled: enabled, noticeShown: noticeShown) else { return }
+ SentrySDK.close()
+ started = false
+ }
+
+ @inline(never)
+ private static func forcedCrash() {
+ fatalError("CUA_CRASH_TEST=swift")
+ }
+}
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
index 2cba465ea6..59c31c8bdb 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift
@@ -225,6 +225,13 @@ extension WebUIBridge {
case "telemetry.acknowledgeLinkNotice":
model.telemetrySink?.acknowledgeLinkNotice()
return NSNull()
+ // The page's crash reporter (CUA-2343): its consent and build config.
+ case "crashReporting.config":
+ let status = model.telemetrySink?.status()
+ return CrashReporting.bridgeConfig(
+ info: Bundle.main.infoDictionary ?? [:],
+ allowed: status.map { CrashReporting.isAllowed(enabled: $0.enabled, noticeShown: $0.noticeShown) } ?? false,
+ env: ProcessInfo.processInfo.environment)
// A Space's detail
case "spaces.usage":
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
index 455e648dba..12d0ec504a 100644
--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift
@@ -93,7 +93,7 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {
"devices.revoke", "devices.confirmMachine", "devices.createPairingCode", "devices.pairingCodes",
"devices.revokePairingCode", "teams.list", "storage.get", "storage.run",
"notifications.list", "notifications.markAllRead", "notifications.markRead",
- "telemetry.track", "telemetry.linkNotice", "telemetry.acknowledgeLinkNotice", "spaces.usage", "spaces.windows", "stream.pip",
+ "telemetry.track", "telemetry.linkNotice", "telemetry.acknowledgeLinkNotice", "crashReporting.config", "spaces.usage", "spaces.windows", "stream.pip",
// A Space's thumbnail (WebUIBridge+Thumbnails.swift).
"spaces.thumbnail",
// A Space's drop well: Send file… and dropped files (WebUIBridge+Files.swift).
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
index 2b4dd70dde..05cb5ab430 100644
--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift
@@ -252,7 +252,7 @@ struct BridgeContractTests {
("storage.get", [:]), ("storage.run", ["request": ["kind": "clear-cache"]]),
("notifications.list", [:]), ("notifications.markRead", ["ids": ["n1"]]), ("notifications.markAllRead", [:]),
("telemetry.track", ["signals": [["type": "step", "step": "app_launched", "ok": true]]]),
- ("telemetry.linkNotice", [:]), ("telemetry.acknowledgeLinkNotice", [:]),
+ ("telemetry.linkNotice", [:]), ("telemetry.acknowledgeLinkNotice", [:]), ("crashReporting.config", [:]),
("spaces.usage", ["spaceId": space]), ("spaces.windows", ["spaceId": space]),
("spaces.thumbnail", ["spaceId": space]),
("spaces.droppedFiles", ["names": ["notes.txt"]]), ("spaces.chooseFiles", [:]),
diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/CrashReportingTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/CrashReportingTests.swift
new file mode 100644
index 0000000000..2a9f6b8ca3
--- /dev/null
+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/CrashReportingTests.swift
@@ -0,0 +1,132 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+@testable import CuaSpacesMacKit
+import Foundation
+import Sentry
+import Testing
+
+/// Crash reporting: consent, release and environment, and the privacy rules
+/// every event passes before it leaves the machine.
+@Suite("Crash reporting")
+struct CrashReportingTests {
+ @Test func consentNeedsTheSwitchAndTheNotice() {
+ #expect(CrashReporting.isAllowed(enabled: true, noticeShown: true))
+ #expect(!CrashReporting.isAllowed(enabled: true, noticeShown: false))
+ #expect(!CrashReporting.isAllowed(enabled: false, noticeShown: true))
+ #expect(!CrashReporting.isAllowed(enabled: false, noticeShown: false))
+ }
+
+ @Test func environmentFollowsChannelAndVersion() {
+ #expect(CrashReporting.environment(channel: "local", version: "0.7.2") == "local")
+ #expect(CrashReporting.environment(channel: "Local", version: "0.7.2-beta.1") == "local")
+ #expect(CrashReporting.environment(channel: nil, version: "0.7.2-beta.1") == "beta")
+ #expect(CrashReporting.environment(channel: "stable", version: "0.7.2") == "stable")
+ #expect(CrashReporting.release(version: "0.7.2") == "[email protected]")
+ }
+
+ @Test func noDsnMeansOff() {
+ #expect(CrashReporting.settings(info: [:]) == nil)
+ #expect(CrashReporting.settings(info: ["CuaCrashDSN": " "]) == nil)
+ }
+
+ @Test func settingsReadTheBundle() throws {
+ let s = try #require(CrashReporting.settings(info: [
+ "CuaCrashDSN": "https://[email protected]/2", "CuaVersion": "0.7.2-beta.1",
+ "CFBundleShortVersionString": "0.7.2",
+ ]))
+ #expect(s.release == "[email protected]")
+ #expect(s.environment == "beta")
+ let env = CrashReporting.childEnvironment(s)
+ #expect(env["CUA_CRASH_SHELL"] == "swift")
+ #expect(env["CUA_CRASH_DSN"] == "https://[email protected]/2")
+ #expect(env["CUA_CRASH_RELEASE"] == s.release)
+ #expect(env["CUA_CRASH_ENVIRONMENT"] == "beta")
+ }
+
+ @Test func forcedCrashOnlyInLocalBuilds() {
+ #expect(CrashReporting.wantsForcedCrash(env: ["CUA_CRASH_TEST": "swift"], args: [], environment: "local"))
+ #expect(CrashReporting.wantsForcedCrash(env: [:], args: ["--crash-test=swift"], environment: "local"))
+ #expect(!CrashReporting.wantsForcedCrash(env: ["CUA_CRASH_TEST": "swift"], args: [], environment: "stable"))
+ #expect(!CrashReporting.wantsForcedCrash(env: [:], args: [], environment: "local"))
+ }
+
+ @Test func scrubsHomesAndEmails() {
+ let home = "/Volumes/Data/ada"
+ #expect(CrashReporting.scrub("/Users/ada/Library/x.swift", home: home) == "~/Library/x.swift")
+ #expect(CrashReporting.scrub("/home/bob/a", home: home) == "~/a")
+ #expect(CrashReporting.scrub("C:\\Users\\Cy\\a", home: home) == "~\\a")
+ #expect(CrashReporting.scrub("/Volumes/Data/ada/f", home: home) == "~/f")
+ #expect(CrashReporting.scrub("mail [email protected] now", home: home) == "mail [email] now")
+ #expect(CrashReporting.scrubURL("https://x.test/a?token=1#frag", home: home) == "https://x.test/a")
+ }
+
+ private func event() -> Event {
+ let e = Event(level: .fatal)
+ let frame = Frame()
+ frame.fileName = "/Users/ada/src/App.swift"
+ frame.function = "crash()"
+ let trace = SentryStacktrace(frames: [frame], registers: [:])
+ let ex = Exception(value: "Space '[email protected]' in /Users/ada/x failed", type: "NSInvalidArgumentException")
+ ex.stacktrace = trace
+ e.exceptions = [ex]
+ e.message = SentryMessage(formatted: "boom [email protected]")
+ e.user = User(userId: "42")
+ e.user?.ipAddress = "1.2.3.4"
+ e.serverName = "adas-macbook.local"
+ e.tags = ["path": "/Users/ada/y", "shell": "swift"]
+ e.extra = ["note": "ping [email protected]", "n": 3]
+ e.breadcrumbs = [Breadcrumb(level: .info, category: "ui.click")]
+ let r = SentryRequest()
+ r.url = "https://x.test/[email protected]#f"
+ r.queryString = "[email protected]"
+ r.fragment = "f"
+ e.request = r
+ e.context = ["device": ["name": "Ada's Mac", "model": "Mac15,3"]]
+ return e
+ }
+
+ @Test func dropsEventsWithoutConsent() {
+ #expect(CrashReporting.sanitize(event(), allowed: false, home: "/Users/ada") == nil)
+ }
+
+ @Test func clearsValuesAndPersonalData() throws {
+ let e = try #require(CrashReporting.sanitize(event(), allowed: true, home: "/Users/ada"))
+ let ex = try #require(e.exceptions?.first)
+ #expect(ex.value == "")
+ #expect(ex.type == "NSInvalidArgumentException")
+ #expect(ex.stacktrace?.frames.first?.fileName == "~/src/App.swift")
+ #expect(ex.stacktrace?.frames.first?.function == "crash()")
+ #expect(e.message == nil)
+ #expect(e.user == nil)
+ #expect(e.serverName == nil)
+ #expect(e.breadcrumbs == nil)
+ #expect(e.tags?["path"] == "~/y")
+ #expect(e.tags?["shell"] == "swift")
+ #expect(e.extra?["note"] as? String == "ping [email]")
+ #expect(e.extra?["n"] as? Int == 3)
+ #expect(e.request?.url == "https://x.test/p")
+ #expect(e.request?.queryString == nil)
+ #expect(e.request?.fragment == nil)
+ let device = e.context?["device"]
+ #expect(device?["name"] == nil)
+ #expect(device?["model"] as? String == "Mac15,3")
+ }
+}
+
+@Suite("Crash reporting bridge")
+struct CrashReportingBridgeTests {
+ @Test func configCarriesConsentAndBuild() {
+ let info: [String: Any] = ["CuaCrashDSN": "https://[email protected]/1", "CuaVersion": "0.7.2"]
+ let c = CrashReporting.bridgeConfig(info: info, allowed: true, env: ["CUA_CRASH_TEST": "ui"])
+ #expect(c["allowed"] as? Bool == true)
+ #expect(c["shell"] as? String == "swift")
+ #expect(c["environment"] as? String == "stable")
+ #expect(c["release"] as? String == "[email protected]")
+ #expect(c["crashTest"] == nil)
+ let l = CrashReporting.bridgeConfig(info: info.merging(["CuaChannel": "local"]) { $1 }, allowed: false,
+ env: ["CUA_CRASH_TEST": "ui"])
+ #expect(l["crashTest"] as? String == "ui")
+ #expect(l["allowed"] as? Bool == false)
+ }
+}
diff --git a/apps/cua-spaces-macos/scripts/build-app.sh b/apps/cua-spaces-macos/scripts/build-app.sh
index b4e51f2d70..b37b02c753 100755
--- a/apps/cua-spaces-macos/scripts/build-app.sh
+++ b/apps/cua-spaces-macos/scripts/build-app.sh
@@ -122,6 +122,11 @@ app="$out/$app_name.app"
rm -rf "$app"
mkdir -p "$app/Contents/MacOS" "$app/Contents/Resources" "$app/Contents/Frameworks"
cp "$here/Support/Info.plist" "$app/Contents/Info.plist"
+# Crash reporting (CrashReporting.swift): the public DSN from the shared
+# config. An empty or missing dsn writes an empty key, which turns it off.
+crash_dsn="$(plutil -extract dsn raw -o - "$here/../../config/spaces-crash-reporting.json" 2>/dev/null || true)"
+/usr/libexec/PlistBuddy -c "Delete :CuaCrashDSN" "$app/Contents/Info.plist" 2>/dev/null || true
+/usr/libexec/PlistBuddy -c "Add :CuaCrashDSN string $crash_dsn" "$app/Contents/Info.plist"
if [ "$channel" = local ]; then
# Another identity, no updater, staging, its own home, helper and URL
# scheme. Nothing here may reach an installed Cua Spaces: see
diff --git a/apps/cua-spaces-web/package.json b/apps/cua-spaces-web/package.json
index 712b3b8863..ac97a01438 100644
--- a/apps/cua-spaces-web/package.json
+++ b/apps/cua-spaces-web/package.json
@@ -23,6 +23,7 @@
"dependencies": {
"@base-ui/react": "^1.8.0",
"@legendapp/list": "^3.6.0",
+ "@sentry/browser": "11.8.0",
"@tanstack/react-router": "^1.170.41",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
diff --git a/apps/cua-spaces-web/pnpm-lock.yaml b/apps/cua-spaces-web/pnpm-lock.yaml
index 0b5f552e06..83e49f0f2a 100644
--- a/apps/cua-spaces-web/pnpm-lock.yaml
+++ b/apps/cua-spaces-web/pnpm-lock.yaml
@@ -14,6 +14,9 @@ importers:
'@legendapp/list':
specifier: ^3.6.0
+ '@sentry/browser':
+ specifier: 11.8.0
+ version: 11.8.0
'@tanstack/react-router':
specifier: ^1.170.41
@@ -412,6 +415,34 @@ packages:
'@rolldown/[email protected]':
resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==}
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-tTqJmnfuJaQy9LyInCWJtJ0L+VnOq+L9+lTMkQH+pptXBAuHfdJyEl2IhGqO4QmsfKyZpHa2GVd3HKpEQsVYeg==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-uBC1k2ESZErHv+RfG6p9siHrtxv+QErDxL/jvEBZnoMV6OcWdZyWTGKcqrW7EjwlBiWkgVve1W7z8tNDDuVQxw==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-Mrqd/o7n/z7qWSYfQQA7x4fFTA0IqOG6JNsbBpnC97khPwZk7n6DPtOO7YgaYplSl8R8QLRbBz9Xv2lVhToSAg==}
+ engines: {node: '>=14'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-4MVTthk6C/1oQFjbVIfygHyNkx2YGbwNLml0kJji0vjJXy6ZNls9zdIp0FTBTi4e3189IcSc5OXD4qcJdmEeKA==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-t8MSpbPoOcPOkywcv0Hwh97A82jWFZju5NU/a6pHmn2pKFktgCgnHKNHvlYp8QUaDNYijYpLv58NIM5Dg7by7A==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-/MiivHLdDv3ot5uJmWcPhIOubec54hPd4U/c2OE5oNyhM3zrd/S6b2FEfwke/V120QGEdZcuzGatwNJ2jNSkgQ==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
+ '@sentry/[email protected]':
+ resolution: {integrity: sha512-0jXMLd9XCBEZ5tu0VJa1uj1HYCpsjuNjbEBhF5pUw4FHyIH5hz01WuI20SH2Ct0pP1mykTzJLPGjZ8sUiAmMnQ==}
+ engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'}
+
'@tailwindcss/[email protected]':
resolution: {integrity: sha512-/T8IKEsf9VTU6tLjgC7+sv2mOPtQxzE2jMw7u4Tt40Tx+QSZxpzh95/H6cMKoja9XuW7iMdLJYBB0o9G1CaAgg==}
@@ -1414,6 +1445,9 @@ packages:
resolution: {integrity: sha512-4Nsy8K5Tr6SPDH9jhKJOHf7ChDrc1zufZTVSF7x72hwuEXBqxqk9G6cK+K2NRUtB3iELRJqjXb4JPDMBjMTl2Q==}
engines: {node: ^22.22.2 || ^24.15.0 || >=26.0.0}
+ resolution: {integrity: sha512-Dmy+vdO1UPMqXiAtZSNayhl4f794Bxfd94W4HIj2HlYtczEQfEOon969memlcpcHrTuOKLa5baFjX7WbgmOq+A==}
+
resolution: {integrity: sha512-BMhLD/Sw+GbJC21C/UgyaZX41nPt8bUTg+jWyDeg7e7YN4xOM05YPSIXceACnXVtqyEw/LMClUQMtMZ+PGGpqQ==}
engines: {node: '>=20'}
@@ -1746,6 +1780,41 @@ snapshots:
'@rolldown/[email protected]': {}
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/conventions': 0.27.0
+ '@sentry/core': 11.8.0
+ web-vitals: 6.2.3
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/browser-utils': 11.8.0
+ '@sentry/conventions': 0.27.0
+ '@sentry/core': 11.8.0
+ '@sentry/feedback': 11.8.0
+ '@sentry/replay': 11.8.0
+ '@sentry/replay-canvas': 11.8.0
+
+ '@sentry/[email protected]': {}
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/conventions': 0.27.0
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/core': 11.8.0
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/core': 11.8.0
+ '@sentry/replay': 11.8.0
+
+ '@sentry/[email protected]':
+ dependencies:
+ '@sentry/browser-utils': 11.8.0
+ '@sentry/core': 11.8.0
+
'@tailwindcss/[email protected]':
dependencies:
'@jridgewell/remapping': 2.3.5
@@ -2505,6 +2574,8 @@ snapshots:
dependencies:
xml-name-validator: 5.0.0
+
diff --git a/apps/cua-spaces-web/src/bridge/README.md b/apps/cua-spaces-web/src/bridge/README.md
index d3e634483a..65b473d599 100644
--- a/apps/cua-spaces-web/src/bridge/README.md
+++ b/apps/cua-spaces-web/src/bridge/README.md
@@ -475,6 +475,7 @@ something the native apps already do; nothing is a new mechanism.
| `telemetry.track` | `{ signals }` | `null` | `telemetry_record_signals` | `model.telemetrySink?.record(signals)` (`appTelemetryRecord`), only while `status().enabled`; each signal checked again |
| `telemetry.linkNotice` | `{}` | `{ due, title, body, okLabel, turnOffLabel, detailsLabel, docsUrl } \| null` | `telemetry_link_notice` | `model.telemetrySink?.linkNotice()` (`telemetryLinkNotice`, `telemetryLinkNoticeDue`); the one-time notice that usage data is now linked to the account (CUA-1881). The page shows it only while `due`. The demo host has none |
| `telemetry.acknowledgeLinkNotice` | `{}` | `null` | `telemetry_acknowledge_link_notice` | `model.telemetrySink?.acknowledgeLinkNotice()` (`telemetryAcknowledgeLinkNotice`); either button. "Turn off usage data" first sets `telemetry` off through `updateSetting` |
+| `crashReporting.config` | `{}` | `{ allowed, dsn, release, environment, shell, crashTest? }` | none (unsupported) | the host's crash-reporting settings (CUA-2343): `allowed` only while usage data is on and its notice shown; `dsn` empty when the build has none; `crashTest: "ui"` only on a `local` build with `CUA_CRASH_TEST=ui`. Older hosts (`unimplemented`), the demo host and Tauri read as off. Electron: `src/bridge/telemetry.ts` |
| `spaces.usage` | `{ spaceId }` | `SpaceUsage \| null` | `space_usage` | `backend.usage(id:)` |
| `spaces.windows` | `{ spaceId }` | `{ windows, display, open }` (`open`: the rows whose picture in picture is open) | none (the viewer lists windows over its own stream) | `StreamRowsModel` over `backend.streamProvider(id:)` |
| `stream.pip` | `{ spaceId, command: { type: "open" \| "close", row } }` | open row ids | none (its PiP is a viewer window) | a `StreamPiPSet` per Space, as the detail view keeps |
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
index 2557d1c7db..23da076407 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts
@@ -146,6 +146,7 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {
"telemetry.track": { signals: [{ type: "step", step: "app_launched", ok: true }] },
"telemetry.linkNotice": {},
"telemetry.acknowledgeLinkNotice": {},
+ "crashReporting.config": {},
"spaces.usage": { spaceId: SPACE },
"spaces.windows": { spaceId: SPACE },
"stream.pip": { spaceId: SPACE, command: { type: "open", row: "desktop" } },
diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
index e3464be12c..4325a7470f 100644
--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts
@@ -124,6 +124,7 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {
"telemetry.track": { signals: [{ type: "step", step: "app_launched", ok: true }] },
"telemetry.linkNotice": {},
"telemetry.acknowledgeLinkNotice": {},
+ "crashReporting.config": {},
"spaces.usage": { spaceId: "s1" },
"spaces.windows": { spaceId: "s1" },
"stream.pip": { spaceId: "s1", command: { type: "open", row: "desktop" } },
diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo/telemetry.ts b/apps/cua-spaces-web/src/bridge/adapters/demo/telemetry.ts
index 240a725dd8..995a26bfb9 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/demo/telemetry.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/demo/telemetry.ts
@@ -15,7 +15,7 @@ export interface DemoTelemetryState {
export const demoTelemetryState = (): DemoTelemetryState => ({ telemetry: [] });
-export function demoTelemetryHandlers({ state }: DemoContext): DemoHandlers<"telemetry.track" | "telemetry.linkNotice" | "telemetry.acknowledgeLinkNotice"> {
+export function demoTelemetryHandlers({ state }: DemoContext): DemoHandlers<"telemetry.track" | "telemetry.linkNotice" | "telemetry.acknowledgeLinkNotice" | "crashReporting.config"> {
return {
"telemetry.track": ({ signals }) => {
if (state.settings.telemetry) state.telemetry.push(...signals);
@@ -23,5 +23,7 @@ export function demoTelemetryHandlers({ state }: DemoContext): DemoHandlers<"tel
},
"telemetry.linkNotice": () => null,
"telemetry.acknowledgeLinkNotice": () => null,
+ // The demo host has no app to report for.
+ "crashReporting.config": () => ({ allowed: false, dsn: "", release: "", environment: "", shell: "" }),
};
}
diff --git a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts
index 90776377ca..74fefa7a78 100644
--- a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts
+++ b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts
@@ -106,6 +106,7 @@ export const TAURI_UNSUPPORTED: readonly OpName[] = [
...CHECKLIST_OPERATIONS,
...LINKS_OPERATIONS,
...CLI_OPERATIONS,
+ "crashReporting.config",
...PRESENCE_OPERATIONS,
...RUNTIME_FIX_OPERATIONS,
];
diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
index b2d437305d..8e6251a239 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json
@@ -717,6 +717,38 @@
"warning"
]
},
+ "CrashReportingConfig": {
+ "type": "object",
+ "properties": {
+ "allowed": {
+ "type": "boolean"
+ },
+ "dsn": {
+ "type": "string"
+ },
+ "release": {
+ "type": "string"
+ },
+ "environment": {
+ "type": "string"
+ },
+ "shell": {
+ "type": "string"
+ },
+ "crashTest": {
+ "enum": [
+ "ui"
+ ]
+ }
+ },
+ "required": [
+ "allowed",
+ "dsn",
+ "release",
+ "environment",
+ "shell"
+ ]
+ },
"CreateFix": {
"type": "object",
"properties": {
@@ -5505,6 +5537,9 @@
"checks"
]
},
+ "crashReporting.config": {
+ "$ref": "#/$defs/CrashReportingConfig"
+ },
"devices.approve": {
"type": "null"
},
@@ -7352,6 +7387,9 @@
"checks"
]
},
+ "crashReporting.config": {
+ "$ref": "#/$defs/CrashReportingConfig"
+ },
"devices.approve": {
"type": "null"
},
diff --git a/apps/cua-spaces-web/src/bridge/contracts/host.ts b/apps/cua-spaces-web/src/bridge/contracts/host.ts
index ae7f1ee195..c334287ae4 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/host.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/host.ts
@@ -597,6 +597,27 @@ export interface TelemetryView {
docsUrl: string;
}
+/**
+ * `crashReporting.config`: whether the page may report its own errors, and
+ * the settings to do it with. The host decides: `allowed` is true only while
+ * usage data is on and its first-run notice was shown, and the DSN, release
+ * and channel are the app's (config/spaces-crash-reporting.json). A host
+ * with no answer (`unsupported`, `unimplemented`, an error) means off.
+ */
+export interface CrashReportingConfig {
+ allowed: boolean;
+ /** The public ingest key; empty means crash reporting is not configured in this build. */
+ dsn: string;
+ /** `cua-spaces-desktop@<app version>`. */
+ release: string;
+ /** The channel: `stable`, `beta` or `local`. */
+ environment: string;
+ /** Which app hosts the page: `electron` or `swift`. */
+ shell: string;
+ /** A local build's forced-crash request (CUA_CRASH_TEST=ui): throw once after start. Never set on `stable` or `beta`. */
+ crashTest?: "ui";
+}
+
/* ---- Settings page (app core `settings::page`) --------------------------- */
/** Why a sign-in did not finish (`sign_in::SignInFailure`). */
diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
index 6a3df05e02..362a9e7142 100644
--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts
@@ -35,6 +35,7 @@ import type {
SignInStart,
SpacePowerReport,
TelemetryView,
+ CrashReportingConfig,
} from "./host";
import type { KeyvaultOverview, KvGrant } from "./keyvault";
import type {
@@ -482,6 +483,18 @@ const LinkNoticeShape = ref(
}),
);
+const CrashReportingConfigShape = ref(
+ "CrashReportingConfig",
+ obj<CrashReportingConfig>()({
+ allowed: bool,
+ dsn: str,
+ release: str,
+ environment: str,
+ shell: str,
+ crashTest: opt(oneOf("ui")),
+ }),
+);
+
/* ---- New Space ------------------------------------------------------------- */
const StorageVolumeShape = obj<StorageVolume>()({ availableBytes: num, totalBytes: num, name: str });
@@ -1110,6 +1123,7 @@ export const OP_SHAPES: Record<OpName, Schema> = {
"telemetry.track": nul,
"telemetry.linkNotice": nullable(LinkNoticeShape),
"telemetry.acknowledgeLinkNotice": nul,
+ "crashReporting.config": CrashReportingConfigShape,
"spaces.usage": nullable(
obj<SpaceUsage>()({ memoryUsed: num, memoryTotal: num, memoryLimited: bool, diskUsed: num, diskTotal: num, diskLimited: bool }),
),
@@ -1438,6 +1452,7 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {
"telemetry.track": nul,
"telemetry.linkNotice": nullable(LinkNoticeShape),
"telemetry.acknowledgeLinkNotice": nul,
+ "crashReporting.config": CrashReportingConfigShape,
"spaces.usage": OP_SHAPES["spaces.usage"],
"spaces.windows": OP_SHAPES["spaces.windows"],
"stream.pip": strings,
diff --git a/apps/cua-spaces-web/src/bridge/ops/telemetry.ts b/apps/cua-spaces-web/src/bridge/ops/telemetry.ts
index 285899b19c..2411b0c26d 100644
--- a/apps/cua-spaces-web/src/bridge/ops/telemetry.ts
+++ b/apps/cua-spaces-web/src/bridge/ops/telemetry.ts
@@ -26,7 +26,9 @@
* - Demo: no notice (`null`).
*/
+import { UnsupportedOperationError, type BridgeMode } from "../adapter";
import type { OpCoverage } from "../coverage";
+import type { CrashReportingConfig } from "../contracts/host";
/** One usage event (`telemetry::TelemetrySignal`): fixed words, flags and
* durations, never names, paths, URLs, emails or anything typed. */
@@ -86,12 +88,15 @@ export interface TelemetryOps {
"telemetry.linkNotice": { args: Record<string, never>; result: TelemetryLinkNotice | null };
/** The notice was closed (either button): linking may start at the next launch. */
"telemetry.acknowledgeLinkNotice": { args: Record<string, never>; result: null };
+ /** Whether the page may report its own errors, and the settings to do it with (never null: a host that can't says `allowed: false` or is `unsupported`). */
+ "crashReporting.config": { args: Record<string, never>; result: CrashReportingConfig };
}
export const TELEMETRY_OPERATIONS = [
"telemetry.track",
"telemetry.linkNotice",
"telemetry.acknowledgeLinkNotice",
+ "crashReporting.config",
] as const satisfies readonly (keyof TelemetryOps)[];
const text = (v: unknown): v is string => typeof v === "string" && v.length > 0;
@@ -113,6 +118,28 @@ export function linkNoticeFromHost(raw: unknown): TelemetryLinkNotice | null {
}
+const OFF: CrashReportingConfig = { allowed: false, dsn: "", release: "", environment: "", shell: "", };
+
+/** A host's answer as crash settings; anything malformed, or without a DSN, reads as off. */
+export function crashConfigFromHost(raw: unknown): CrashReportingConfig {
+ const c = raw as Partial<CrashReportingConfig> | null | undefined;
+ if (!c || typeof c !== "object" || c.allowed !== true) return OFF;
+ if (!text(c.dsn) || !text(c.release) || !text(c.environment) || !text(c.shell)) return OFF;
+ return {
+ allowed: true,
+ dsn: c.dsn,
+ release: c.release,
+ environment: c.environment,
+ shell: c.shell,
+ ...(c.crashTest === "ui" && c.environment === "local" ? { crashTest: "ui" as const } : {}),
+ };
+}
+
+/** Tauri and the demo host have no crash reporting. */
+export function unsupportedCrashReportingOps(mode: BridgeMode) {
+ return { "crashReporting.config": (): Promise<never> => Promise.reject(new UnsupportedOperationError(mode, "crashReporting.config")) };
+}
+
/* ---- What may cross the bridge ------------------------------------------------ */
type Field = "word" | "flag" | "maybe-flag" | "ms" | "words" | "variant" | "maybe-attempt" | "maybe-word";
@@ -219,7 +246,7 @@ export function tauriTelemetryOps(invoke: Invoke) {
}
type WebkitRequest = <T>(
- method: "telemetry.linkNotice" | "telemetry.acknowledgeLinkNotice",
+ method: "telemetry.linkNotice" | "telemetry.acknowledgeLinkNotice" | "crashReporting.config",
args?: Record<string, unknown>,
wait?: number | null,
) => Promise<T>;
@@ -233,6 +260,8 @@ export function webkitTelemetryNoticeOps(request: WebkitRequest) {
await request("telemetry.acknowledgeLinkNotice", {});
return null;
},
+ // An older host (`unimplemented`) or any failure reads as off.
+ "crashReporting.config": () => request<unknown>("crashReporting.config", {}, 5_000).then(crashConfigFromHost, () => OFF),
};
}
@@ -249,4 +278,9 @@ export const TELEMETRY_COVERAGE = {
webkit: { methods: ["telemetry.acknowledgeLinkNotice"] },
tauri: ["telemetry_acknowledge_link_notice"],
},
+ "crashReporting.config": {
+ webkit: { methods: ["crashReporting.config"] },
+ tauri: [],
+ unsupported: { tauri: "the Tauri app reports crashes from its own Rust process, not the page" },
+ },
} as const satisfies Record<keyof TelemetryOps, OpCoverage>;
diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
index 9640a13924..59deeb6864 100644
--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts
@@ -134,6 +134,7 @@ export const WEBKIT_METHODS = [
"telemetry.track",
"telemetry.linkNotice",
"telemetry.acknowledgeLinkNotice",
+ "crashReporting.config",
"spaces.usage",
"spaces.windows",
"stream.pip",
diff --git a/apps/cua-spaces-web/src/crash-reporting/__tests__/crash-reporting.test.ts b/apps/cua-spaces-web/src/crash-reporting/__tests__/crash-reporting.test.ts
new file mode 100644
index 0000000000..e14a9a7580
--- /dev/null
+++ b/apps/cua-spaces-web/src/crash-reporting/__tests__/crash-reporting.test.ts
@@ -0,0 +1,207 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+import { describe, expect, it, vi } from "vitest";
+import type { BridgeMode, DataAdapter } from "../../bridge/adapter";
+import type { CrashReportingConfig } from "../../bridge/contracts/host";
+import type { HostEvent } from "../../bridge/protocol";
+import { crashConfigFromHost } from "../../bridge/ops/telemetry";
+import { sentryOptions, startCrashReporting, wantsUiTestCrash, type SentryLike } from "..";
+import { scrubEvent, scrubString, stripUrl } from "../scrub";
+
+const ON: CrashReportingConfig = { allowed: true, dsn: "https://[email protected]/2", release: "[email protected]", environment: "stable", shell: "electron" };
+
+function fakeSentry() {
+ const calls: { init: Record<string, unknown>[]; close: number } = { init: [], close: 0 };
+ const sentry: SentryLike = {
+ init: (o) => void calls.init.push(o),
+ close: () => {
+ calls.close++;
+ return Promise.resolve(true);
+ },
+ globalHandlersIntegration: () => "global",
+ dedupeIntegration: () => "dedupe",
+ linkedErrorsIntegration: () => "linked",
+ functionToStringIntegration: () => "fn",
+ eventFiltersIntegration: () => "filters",
+ };
+ return { sentry, calls };
+}
+
+function fakeAdapter(mode: BridgeMode, answer: () => Promise<CrashReportingConfig>) {
+ const listeners = new Set<(e: HostEvent) => void>();
+ const call = vi.fn(async (op: string) => {
+ if (op !== "crashReporting.config") throw new Error(`unexpected ${op}`);
+ return answer();
+ });
+ const adapter = { mode, call, subscribe: (l: (e: HostEvent) => void) => (listeners.add(l), () => listeners.delete(l)), dispose: vi.fn() } as unknown as DataAdapter;
+ return { adapter, call, emit: (e: HostEvent) => listeners.forEach((l) => l(e)), listeners };
+}
+
+describe("the host's answer", () => {
+ it("reads as off unless it is complete and allowed", () => {
+ expect(crashConfigFromHost(ON)).toEqual(ON);
+ expect(crashConfigFromHost({ ...ON, allowed: false }).allowed).toBe(false);
+ expect(crashConfigFromHost({ ...ON, dsn: "" }).allowed).toBe(false);
+ expect(crashConfigFromHost({ ...ON, release: undefined }).allowed).toBe(false);
+ expect(crashConfigFromHost(null).allowed).toBe(false);
+ expect(crashConfigFromHost("yes").allowed).toBe(false);
+ });
+
+ it("offers the forced crash on a local build only", () => {
+ expect(crashConfigFromHost({ ...ON, environment: "local", crashTest: "ui" }).crashTest).toBe("ui");
+ expect(crashConfigFromHost({ ...ON, environment: "stable", crashTest: "ui" }).crashTest).toBeUndefined();
+ expect(wantsUiTestCrash({ ...ON, environment: "beta", crashTest: "ui" })).toBe(false);
+ expect(wantsUiTestCrash({ ...ON, environment: "local", crashTest: "ui" })).toBe(true);
+ });
+});
+
+describe("the SDK's options", () => {
+ it("records errors only, with no breadcrumbs, tracing or user", () => {
+ const { sentry } = fakeSentry();
+ const o = sentryOptions(sentry, ON, () => true);
+ expect(o).toMatchObject({ dsn: ON.dsn, release: ON.release, environment: "stable", sendDefaultPii: false, defaultIntegrations: false, maxBreadcrumbs: 0 });
+ expect(o.integrations).toEqual(["global", "dedupe", "linked", "fn", "filters"]);
+ expect(o.initialScope).toEqual({ tags: { shell: "electron", component: "ui" } });
+ expect(o.tracesSampleRate).toBeUndefined();
+ expect((o.beforeBreadcrumb as () => unknown)()).toBeNull();
+ expect((o.beforeSendTransaction as () => unknown)()).toBeNull();
+ });
+
+ it("scrubs each event, and drops it once the switch is off", () => {
+ const { sentry } = fakeSentry();
+ let allowed = true;
+ const send = sentryOptions(sentry, ON, () => allowed).beforeSend as (e: unknown) => unknown;
+ const event = { message: "Space 'Jane'", exception: { values: [{ type: "Error", value: "[email protected]" }] } };
+ expect(JSON.stringify(send(event))).not.toMatch(/Jane|jane/);
+ allowed = false;
+ expect(send(event)).toBeNull();
+ });
+});
+
+describe("starting", () => {
+ it("does nothing outside the native shells, and never creates an adapter there", async () => {
+ for (const mode of ["demo", "tauri"] as const) {
+ const load = vi.fn();
+ expect(await startCrashReporting({ mode, load })).toBeNull();
+ expect(load).not.toHaveBeenCalled();
+ }
+ });
+
+ it.each(["electron", "webkit"] as const)("%s: stays off, without loading the SDK, when the host says no", async (mode) => {
+ const load = vi.fn();
+ const { adapter } = fakeAdapter(mode, async () => ({ ...ON, allowed: false }));
+ expect(await startCrashReporting({ adapter, load })).toBeNull();
+ expect(load).not.toHaveBeenCalled();
+ });
+
+ it("stays off when the host fails or has no DSN", async () => {
+ const load = vi.fn();
+ expect(await startCrashReporting({ adapter: fakeAdapter("webkit", () => Promise.reject(new Error("unimplemented"))).adapter, load })).toBeNull();
+ expect(await startCrashReporting({ adapter: fakeAdapter("electron", async () => ({ ...ON, dsn: "" })).adapter, load })).toBeNull();
+ expect(load).not.toHaveBeenCalled();
+ });
+
+ it("stays off when the SDK fails to load", async () => {
+ const { adapter } = fakeAdapter("electron", async () => ON);
+ expect(await startCrashReporting({ adapter, load: () => Promise.reject(new Error("offline")) })).toBeNull();
+ });
+
+ it("starts the SDK when allowed, and closes it when the switch goes off", async () => {
+ const { sentry, calls } = fakeSentry();
+ let answer = ON;
+ const { adapter, emit, listeners } = fakeAdapter("electron", async () => answer);
+ const handle = await startCrashReporting({ adapter, load: async () => sentry });
+ expect(handle).not.toBeNull();
+ expect(calls.init).toHaveLength(1);
+ // Another event changes nothing; the switch off closes it.
+ emit({ type: "session.signedOut" } as HostEvent);
+ await Promise.resolve();
+ expect(calls.close).toBe(0);
+ answer = { ...ON, allowed: false };
+ emit({ type: "settings.changed" });
+ await vi.waitFor(() => expect(calls.close).toBe(1));
+ expect(listeners.size).toBe(0);
+ const send = calls.init[0]!.beforeSend as (e: unknown) => unknown;
+ expect(send({})).toBeNull();
+ });
+
+ it("stop is safe to call twice", async () => {
+ const { sentry, calls } = fakeSentry();
+ const { adapter } = fakeAdapter("webkit", async () => ON);
+ const handle = await startCrashReporting({ adapter, load: async () => sentry });
+ handle!.stop();
+ handle!.stop();
+ expect(calls.close).toBe(1);
+ });
+
+ it("runs the forced crash on a local build that asks for it", async () => {
+ vi.useFakeTimers();
+ try {
+ const crash = vi.fn();
+ const { sentry } = fakeSentry();
+ await startCrashReporting({ adapter: fakeAdapter("electron", async () => ({ ...ON, environment: "local", crashTest: "ui" })).adapter, load: async () => sentry, crash });
+ expect(crash).not.toHaveBeenCalled();
+ vi.advanceTimersByTime(3500);
+ expect(crash).toHaveBeenCalledTimes(1);
+ const other = vi.fn();
+ await startCrashReporting({ adapter: fakeAdapter("electron", async () => ({ ...ON, crashTest: "ui" })).adapter, load: async () => sentry, crash: other });
+ vi.advanceTimersByTime(3500);
+ expect(other).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+});
+
+describe("scrubbing", () => {
+ it("shortens home folders, hides emails and cuts query strings", () => {
+ expect(scrubString("/Users/jane/a.js")).toBe("~/a.js");
+ expect(scrubString("C:\\Users\\Jane Doe\\a.js")).toBe("~\\a.js");
+ expect(scrubString("mail [email protected]")).toBe("mail [email]");
+ expect(stripUrl("app://x/spaces/1?token=a#h")).toBe("app://x/spaces/1");
+ });
+
+ const event = () => ({
+ message: "Open 'Jane's Space'",
+ logentry: { message: "x" },
+ user: { id: "1", ip_address: "{{auto}}" },
+ server_name: "janes-mbp",
+ breadcrumbs: [{ message: "ui.click" }],
+ exception: {
+ values: [
+ {
+ type: "TypeError",
+ value: "bad file /Users/jane/x.txt",
+ module: "ui",
+ stacktrace: { frames: [{ filename: "app://cua/assets/index.js?v=1", abs_path: "app://cua/assets/index.js#x", function: "go", lineno: 4, vars: { a: 1 }, context_line: "secret" }] },
+ },
+ ],
+ },
+ request: { url: "app://cua/spaces/s1?name=Jane#frag", headers: { "User-Agent": "x" }, data: "b" },
+ tags: { shell: "swift", path: "/home/bob/x" },
+ contexts: { device: { name: "janes-mbp", family: "Mac" }, browser: { name: "Safari" } },
+ });
+
+ it("keeps the type, module and frames, and clears everything else that names someone", () => {
+ const out = scrubEvent(event());
+ expect(out.exception!.values![0]).toEqual({
+ type: "TypeError",
+ value: "",
+ module: "ui",
+ stacktrace: { frames: [{ filename: "app://cua/assets/index.js", abs_path: "app://cua/assets/index.js", function: "go", lineno: 4 }] },
+ });
+ expect(out.request).toEqual({ url: "app://cua/spaces/s1" });
+ expect(out.tags).toEqual({ shell: "swift", path: "~/x" });
+ expect(out.contexts).toEqual({ device: { family: "Mac" }, browser: { name: "Safari" } });
+ expect(out).toMatchObject({ server_name: "" });
+ for (const k of ["message", "logentry", "user", "breadcrumbs"]) expect(out).not.toHaveProperty(k);
+ expect(JSON.stringify(out)).not.toMatch(/jane|Jane|bob|frag|token/);
+ });
+
+ it("does not change the event it was given", () => {
+ const e = event();
+ scrubEvent(e);
+ expect(e).toEqual(event());
+ });
+});
diff --git a/apps/cua-spaces-web/src/crash-reporting/index.ts b/apps/cua-spaces-web/src/crash-reporting/index.ts
new file mode 100644
index 0000000000..098c7424be
--- /dev/null
+++ b/apps/cua-spaces-web/src/crash-reporting/index.ts
@@ -0,0 +1,125 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * Crash reporting for the page (CUA-2343): `@sentry/browser`, started only
+ * when the host says reports are allowed, and stopped when it says they
+ * no longer are.
+ *
+ * The page runs in the Electron shell and in the SwiftUI app's WKWebView, so
+ * it asks the host (`crashReporting.config`): `allowed` is the "Share usage
+ * data" switch with its first-run notice, and the DSN, release and channel
+ * are the app's. A host that doesn't answer (Tauri, the demo host, an older
+ * app, an error) means off, and nothing of the SDK is even downloaded.
+ *
+ * The SDK is set up for errors only: no breadcrumbs, no tracing, no replay,
+ * no screenshots, no feedback widget, no user, no request context. Every
+ * event passes `scrubEvent` and a live check of the switch (`beforeSend`).
+ * Native crashes and main-process errors are the shell's, not the page's.
+ */
+
+import type { BridgeMode, DataAdapter } from "../bridge/adapter";
+import { createAdapter } from "../bridge/adapters";
+import { detectMode } from "../bridge/detect";
+import type { CrashReportingConfig } from "../bridge/contracts/host";
+import { scrubEvent, type ScrubbableEvent } from "./scrub";
+
+/** The hosts that can answer `crashReporting.config`: the two native shells. */
+export const reportsFrom = (mode: BridgeMode): boolean => mode === "electron" || mode === "webkit";
+
+/** The page's forced crash (CUA_CRASH_TEST=ui): only a `local` build, only when the host asks. */
+export const wantsUiTestCrash = (c: CrashReportingConfig): boolean => c.crashTest === "ui" && c.environment === "local";
+
+/** The subset of `@sentry/browser` used here (so tests can stand in). */
+export interface SentryLike {
+ init(options: Record<string, unknown>): unknown;
+ close(timeout?: number): Promise<boolean>;
+ globalHandlersIntegration(): unknown;
+ dedupeIntegration(): unknown;
+ linkedErrorsIntegration(): unknown;
+ functionToStringIntegration(): unknown;
+ eventFiltersIntegration(): unknown;
+}
+
+/** The SDK's options for this host's settings: error handlers and de-duplication only, nothing that records what people do. `isAllowed` is read for every event. */
+export function sentryOptions(sentry: SentryLike, config: CrashReportingConfig, isAllowed: () => boolean): Record<string, unknown> {
+ return {
+ dsn: config.dsn,
+ release: config.release,
+ environment: config.environment,
+ sendDefaultPii: false,
+ defaultIntegrations: false,
+ integrations: [sentry.globalHandlersIntegration(), sentry.dedupeIntegration(), sentry.linkedErrorsIntegration(), sentry.functionToStringIntegration(), sentry.eventFiltersIntegration()],
+ maxBreadcrumbs: 0,
+ sendClientReports: false,
+ initialScope: { tags: { shell: config.shell, component: "ui" } },
+ beforeBreadcrumb: () => null,
+ beforeSendTransaction: () => null,
+ beforeSend: (event: ScrubbableEvent) => (isAllowed() ? scrubEvent(event) : null),
+ };
+}
+
+export interface CrashReportingHandle {
+ /** Stops reporting and removes the listener. */
+ stop(): void;
+}
+
+export interface StartOptions {
+ adapter?: DataAdapter;
+ mode?: BridgeMode;
+ /** Loads the SDK; the default is a dynamic import, so a page that reports nothing never fetches it. */
+ load?: () => Promise<SentryLike>;
+ /** Runs the forced crash (a test hook; the default throws from a timer). */
+ crash?: () => void;
+}
+
+/**
+ * Asks the host and, when allowed, starts the SDK. Resolves to a handle, or
+ * null when reporting is off. Never throws: crash reporting must not stop the
+ * page from starting.
+ */
+export async function startCrashReporting(o: StartOptions = {}): Promise<CrashReportingHandle | null> {
+ try {
+ const mode = o.mode ?? o.adapter?.mode ?? detectMode();
+ if (!reportsFrom(mode)) return null;
+ const adapter = o.adapter ?? createAdapter(mode);
+ const own = !o.adapter;
+ const first = await adapter.call("crashReporting.config", {}).catch(() => null);
+ if (!first || !first.allowed || !first.dsn) {
+ if (own) adapter.dispose?.();
+ return null;
+ }
+ let allowed = true;
+ const sentry = await (o.load ?? (() => import("@sentry/browser") as unknown as Promise<SentryLike>))();
+ sentry.init(sentryOptions(sentry, first, () => allowed));
+
+ let stopped = false;
+ const stop = () => {
+ if (stopped) return;
+ stopped = true;
+ allowed = false;
+ unsubscribe();
+ void sentry.close(0).catch(() => {});
+ if (own) adapter.dispose?.();
+ };
+ // The switch may go off while the page is open: the host pushes `settings.changed`.
+ let unsubscribe = () => {};
+ unsubscribe = adapter.subscribe((event) => {
+ if (event.type !== "settings.changed") return;
+ void adapter.call("crashReporting.config", {}).then(
+ (c) => {
+ if (!c.allowed) stop();
+ },
+ () => {},
+ );
+ });
+
+ if (wantsUiTestCrash(first)) {
+ const crash = o.crash ?? (() => { throw new Error("CUA_CRASH_TEST ui"); });
+ setTimeout(crash, 3000);
+ }
+ return { stop };
+ } catch {
+ return null;
+ }
+}
diff --git a/apps/cua-spaces-web/src/crash-reporting/scrub.ts b/apps/cua-spaces-web/src/crash-reporting/scrub.ts
new file mode 100644
index 0000000000..599bc7759c
--- /dev/null
+++ b/apps/cua-spaces-web/src/crash-reporting/scrub.ts
@@ -0,0 +1,87 @@
+// SPDX-License-Identifier: FSL-1.1-MIT
+// Copyright (c) 2026 Cua AI, Inc.
+
+/**
+ * What may leave the page in a crash report (CUA-2343). The same rules as the
+ * Electron shell's (apps/cua-spaces-desktop/src/crash-reporting.ts): messages
+ * are cleared (they can carry Space names, file names and emails), and
+ * anything else is scrubbed of home folders and emails, or dropped. Pure, so
+ * it runs under test; `index.ts` applies it in `beforeSend`.
+ */
+
+const EMAIL = /[A-Za-z0-9._%+'-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)+/g;
+const HOME_UNIX = /(?:\/Users|\/home)\/[^/\\\s"'`:;,)\]}]+/g;
+const HOME_WIN = /[A-Za-z]:[\\/]+Users[\\/]+[^\\/"'`:;,)\]}]+/gi;
+
+/** Home folders (`/Users/x`, `/home/x`, `C:\Users\x`) become `~`, emails `[email]`. */
+export function scrubString(value: string): string {
+ return value.replace(HOME_WIN, "~").replace(HOME_UNIX, "~").replace(EMAIL, "[email]");
+}
+
+/** A URL without its query string and fragment. */
+export function stripUrl(url: string): string {
+ return url.replace(/[?#].*$/, "");
+}
+
+function scrubDeep(value: unknown, depth = 0): unknown {
+ if (typeof value === "string") return scrubString(/^[a-z][a-z0-9+.-]*:\/\//i.test(value) ? stripUrl(value) : value);
+ if (depth > 12 || value === null || typeof value !== "object") return value;
+ if (Array.isArray(value)) return value.map((v) => scrubDeep(v, depth + 1));
+ const out: Record<string, unknown> = {};
+ for (const [k, v] of Object.entries(value)) out[k] = scrubDeep(v, depth + 1);
+ return out;
+}
+
+/** The parts of a Sentry event the scrub touches. */
+export interface ScrubbableEvent {
+ message?: string;
+ logentry?: unknown;
+ exception?: { values?: { type?: string; value?: string; module?: string; stacktrace?: { frames?: Record<string, unknown>[] } }[] };
+ [key: string]: unknown;
+}
+
+function scrubFrame(frame: Record<string, unknown>): Record<string, unknown> {
+ const out: Record<string, unknown> = { ...frame };
+ for (const k of ["filename", "abs_path"]) if (typeof out[k] === "string") out[k] = scrubString(stripUrl(out[k] as string));
+ for (const k of ["module", "function"]) if (typeof out[k] === "string") out[k] = scrubString(out[k] as string);
+ for (const k of ["context_line", "pre_context", "post_context", "vars"]) delete out[k];
+ return out;
+}
+
+/**
+ * The event as it may leave the page: exception values, the message and log
+ * entry cleared; type, module and frames kept with paths scrubbed; user,
+ * breadcrumbs, attachments, request headers and bodies, server and device
+ * names dropped; a request URL without query or fragment. Returns a new object.
+ */
+export function scrubEvent<T extends ScrubbableEvent>(event: T): T {
+ const e: ScrubbableEvent = { ...event };
+ for (const k of ["user", "breadcrumbs", "logentry", "message", "attachments", "threads"]) delete e[k];
+ e.server_name = "";
+ if (e.exception?.values) {
+ e.exception = {
+ ...e.exception,
+ values: e.exception.values.map((v) => ({
+ ...v,
+ value: "",
+ ...(v.stacktrace?.frames ? { stacktrace: { ...v.stacktrace, frames: v.stacktrace.frames.map(scrubFrame) } } : {}),
+ })),
+ };
+ }
+ if (e.request && typeof e.request === "object") {
+ const url = (e.request as { url?: unknown }).url;
+ e.request = typeof url === "string" ? { url: scrubString(stripUrl(url)) } : {};
+ }
+ for (const key of ["tags", "extra", "contexts", "debug_meta", "modules", "sdk", "fingerprint", "transaction", "culprit"]) {
+ if (e[key] !== undefined) e[key] = scrubDeep(e[key]);
+ }
+ const contexts = e.contexts as Record<string, Record<string, unknown>> | undefined;
+ if (contexts) {
+ if (contexts.device) {
+ delete contexts.device.name;
+ delete contexts.device.hostname;
+ }
+ delete contexts.culture;
+ }
+ return e as T;
+}
diff --git a/apps/cua-spaces-web/src/main.tsx b/apps/cua-spaces-web/src/main.tsx
index 21e4a2325f..caba93b73b 100644
--- a/apps/cua-spaces-web/src/main.tsx
+++ b/apps/cua-spaces-web/src/main.tsx
@@ -6,6 +6,7 @@ import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import { BridgeProvider } from "@/bridge";
+import { startCrashReporting } from "@/crash-reporting";
import { ToastProvider } from "@/components/ui/toast";
import { TooltipProvider } from "@/components/ui/tooltip";
import { routeTree } from "./routeTree.gen";
@@ -26,6 +27,9 @@ declare module "@tanstack/react-router" {
}
}
+// Errors from the page, when the host allows reports (src/crash-reporting).
+void startCrashReporting();
+
const root = createRoot(document.getElementById("root")!);
if (pip) {
void import("./components/pip/pip-view").then(({ PipView, pipParams }) =>
diff --git a/apps/cua-spaces-web/vite.config.ts b/apps/cua-spaces-web/vite.config.ts
index b723406562..a21c055903 100644
--- a/apps/cua-spaces-web/vite.config.ts
+++ b/apps/cua-spaces-web/vite.config.ts
@@ -47,7 +47,11 @@ export default defineConfig({
optimizeDeps: { entries: ["index.html", "src/**/*.{ts,tsx}", "!src/**/*.d.ts", "!src/**/__tests__/**", "!src/**/*.test.{ts,tsx}"] },
server: { port: 5174, strictPort: true },
preview: { port: 5174 },
- build: { target: "es2023", sourcemap: true },
+ // Source maps: shown in a plain build (`pnpm dev`, local checks). Release CD
+ // sets CUA_SOURCEMAPS=1 to emit them hidden (no sourceMappingURL comment) in
+ // dist/**/*.map, uploads them to Sentry, then deletes them: the app never
+ // ships them (electron-builder's extraResources filter drops *.map too).
+ build: { target: "es2023", sourcemap: process.env.CUA_SOURCEMAPS === "1" ? "hidden" : false },
test: {
environment: "jsdom",
include: ["src/**/*.test.{ts,tsx}"],
diff --git a/config/spaces-crash-reporting.json b/config/spaces-crash-reporting.json
new file mode 100644
index 0000000000..f7d91e62ef
--- /dev/null
+++ b/config/spaces-crash-reporting.json
@@ -0,0 +1,6 @@
+{
+ "_comment": "Sentry crash reporting for the Cua Spaces desktop app (CUA-2343). The DSN is a public ingest key, not a secret. An empty dsn turns crash reporting off in every build, so this file can merge before the project exists.",
+ "org": "trycua",
+ "project": "cua-spaces-desktop",
+ "dsn": ""
+}
diff --git a/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx b/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx
index f3d40b7c9c..dc87af3d56 100644
--- a/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx
+++ b/docs/content/docs/cua-sdk/concepts/telemetry-events.mdx
@@ -58,3 +58,36 @@ Every event carries: `telemetry_schema_version`, `event_version`, `product`
Teleport caller kinds and how session deliveries are counted:
[How events are counted](/cua-sdk/concepts/telemetry-counting).
+
+## Crash and error reports
+
+The Cua Spaces app (the macOS app, and the Windows and Linux app) reports
+crashes and unexpected errors to Sentry, so a bad release is caught before it
+reaches everyone: the staged rollout stops advancing when the share of
+crash-free launches of a new version falls behind the previous one. The
+switch is the same as for usage data: "Share usage data to help improve Cua"
+(Settings, Privacy), `cua telemetry off`, `CUA_TELEMETRY=0` or `DO_NOT_TRACK=1`.
+Off means nothing is sent, and a report that was waiting to be sent is dropped.
+Nothing is sent before the first-run notice has been shown. A switch turned
+on while the app runs takes effect at the next launch.
+
+| Property | What it is | Why |
+|---|---|---|
+| `release` | `cua-spaces-desktop@` and the app version | Which version crashed. |
+| `environment` | `stable`, `beta` or `local` | Which channel. |
+| `shell`, `component` | `swift` or `electron`; `shell`, `ui`, `core` or `daemon` | Which part of the app failed. |
+| Operating system, CPU type | For example macOS 26, `arm64` | Crashes that depend on the platform. |
+| Call stack | Function names and Cua source file names of the failing code, memory addresses, the list of loaded libraries | Finding the bug. Symbols are matched on our side from files uploaded when the release is built. |
+| Crash dump | On a native crash of the Windows, Linux or Electron app: a snapshot of the crashed process. Sentry removes the stack memory on its servers (a project scrubbing rule), keeping addresses and library names | Finding crashes in native code. |
+| Session | One per app launch: started, ended normally, or crashed. No identifier of you or your machine | The crash-free share per version. |
+
+Before anything leaves the app, it is cleaned:
+
+- Error messages are removed (they can carry Space names, file names or emails). The error type and call stack stay.
+- Folders under your home folder are shown as `~`, email addresses as `[email]`, and the computer's name is dropped.
+- No screenshots, no session replay, no screen or accessibility content, no clicks, typed text or console output, no performance traces.
+- No IP address is stored: IP collection is off and no user is attached to a report.
+
+The Spaces app, its web interface and its Rust core and daemon share one
+Sentry project (`cua-spaces-desktop`). Tests feed paths, emails and host names
+through the cleaning step and check that none survive.
diff --git a/docs/content/docs/cua-sdk/concepts/telemetry.mdx b/docs/content/docs/cua-sdk/concepts/telemetry.mdx
index 41e945d380..fa3ac6a91e 100644
--- a/docs/content/docs/cua-sdk/concepts/telemetry.mdx
+++ b/docs/content/docs/cua-sdk/concepts/telemetry.mdx
@@ -12,7 +12,7 @@ every event before or after it is sent, and turn it off with one switch.
## Turn it off
-Any of these turns usage telemetry off for every Cua program on the machine
+Any of these turns usage telemetry, and the Spaces app's crash reports, off for every Cua program on the machine
(SDK in any language, `cua` CLI, `cua daemon`, the Spaces app, and Cua Driver):
| Switch | Scope |
@@ -88,6 +88,16 @@ the same ID. Those are records of our service, so the switch doesn't change them
A fixed set of events with closed-vocabulary properties. The full list, each
property and why it is collected: [Telemetry events](/cua-sdk/concepts/telemetry-events).
+The Cua Spaces app also sends **crash and error reports**, when it crashes or
+hits an unexpected error. They go to Sentry, not PostHog, and the same switch
+controls them. A report holds the app version and channel, the operating
+system and CPU type, which part of the app failed, and the call stack (names
+of Cua's own functions, never your files). It never holds the error message,
+screen content, screenshots or your Space names. The app also counts one
+anonymous session per launch, so we can tell what share of launches end in a
+crash. What is in a report, how it is cleaned, and what we use it for:
+[Crash and error reports](/cua-sdk/concepts/telemetry-events#crash-and-error-reports).
+
## What we use it for
To answer how many people install Cua Spaces, finish the first run, sign in,
@@ -105,4 +115,6 @@ titles, URLs, clipboard, keystrokes or typed text, screenshots, screen or
accessibility content, prompts, model output, sandbox or Space names, error
messages, and anything stored in the Keyvault (only consent decisions are
counted). Tests enforce this: every event builder is fed paths, emails,
-hostnames and window titles, and none may appear in a payload.
+hostnames and window titles, and none may appear in a payload. The same holds
+for crash reports: the app's crash reporting is also fed paths, emails and
+hostnames in tests, and none may leave it.
diff --git a/libs/cua/Cargo.lock b/libs/cua/Cargo.lock
index 2769e9c887..e2bfb3308e 100644
--- a/libs/cua/Cargo.lock
+++ b/libs/cua/Cargo.lock
@@ -18,6 +18,15 @@ version = "0.1.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618"
+[[package]]
+name = "addr2line"
+version = "0.25.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1b5d307320b3181d6d7954e663bd7c774a838b8220fe0593c86d9fb09f498b4b"
+dependencies = [
+ "gimli",
+]
+
[[package]]
name = "adler2"
version = "2.0.1"
@@ -1229,6 +1238,21 @@ dependencies = [
"zstd-safe",
]
+[[package]]
+name = "backtrace"
+version = "0.3.76"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb531853791a215d7c62a30daf0dde835f381ab5de4589cfe7c649d2cbe92bd6"
+dependencies = [
+ "addr2line",
+ "cfg-if",
+ "libc",
+ "miniz_oxide 0.8.9",
+ "object",
+ "rustc-demangle",
+ "windows-link 0.2.1",
+]
+
[[package]]
name = "base16ct"
version = "0.2.0"
@@ -2444,6 +2468,7 @@ dependencies = [
"cua-cluster",
"cua-compat",
"cua-contrib",
+ "cua-crash",
"cua-daemon",
"cua-disk",
"cua-home",
@@ -2589,6 +2614,15 @@ dependencies = [
"url",
]
+[[package]]
+name = "cua-crash"
+version = "0.9.0"
+dependencies = [
+ "cua-telemetry",
+ "sentry",
+ "serde_json",
+]
+
[[package]]
name = "cua-create-failure"
version = "0.9.0"
@@ -3287,6 +3321,7 @@ version = "0.9.0"
dependencies = [
"base64 0.22.1",
"cua-chromium-storage",
+ "cua-crash",
"cua-daemon",
"cua-home",
"cua-host",
@@ -3723,6 +3758,16 @@ dependencies = [
"system-deps",
]
+[[package]]
+name = "debugid"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bef552e6f588e446098f6ba40d89ac146c8c7b64aade83c051ee00bb5d2bc18d"
+dependencies = [
+ "serde",
+ "uuid",
+]
+
[[package]]
name = "deku"
version = "0.20.3"
@@ -4156,6 +4201,18 @@ version = "0.1.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef25905e51abafe4dcea6c15fec58c57b601cdbd0ee53d22ea1d3016c587d39b"
+[[package]]
+name = "findshlibs"
+version = "0.10.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40b9e59cd0f7e0806cca4be089683ecb6434e602038df21fe6bf6711b2f07f64"
+dependencies = [
+ "cc",
+ "lazy_static",
+ "libc",
+ "winapi",
+]
+
[[package]]
name = "fixedbitset"
version = "0.5.7"
@@ -4496,6 +4553,12 @@ dependencies = [
"polyval",
]
+[[package]]
+name = "gimli"
+version = "0.32.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7"
+
[[package]]
name = "gl_generator"
version = "0.14.0"
@@ -6339,6 +6402,15 @@ dependencies = [
"objc2-metal 0.3.2",
]
+[[package]]
+name = "object"
+version = "0.37.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff76201f031d8863c38aa7f905eca4f53abbfa15f609db4277d44cd8938f33fe"
+dependencies = [
+ "memchr",
+]
+
[[package]]
name = "oci-client"
version = "0.18.0"
@@ -7578,6 +7650,7 @@ checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029"
dependencies = [
"base64 0.23.1",
"bytes",
+ "futures-channel",
"futures-core",
"futures-util",
"http",
@@ -7681,6 +7754,12 @@ dependencies = [
"smallvec",
]
+[[package]]
+name = "rustc-demangle"
+version = "0.1.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb"
+
[[package]]
name = "rustc-hash"
version = "1.1.0"
@@ -8063,6 +8142,98 @@ dependencies = [
"serde_core",
]
+[[package]]
+name = "sentry"
+version = "0.49.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9fa951f4e644464ebfd2347a7ab03b0828c512d2448a76262cad2607b343dff4"
+dependencies = [
+ "cfg_aliases 0.2.2",
+ "httpdate",
+ "reqwest 0.13.5",
+ "rustls",
+ "sentry-backtrace",
+ "sentry-core",
+ "sentry-debug-images",
+ "sentry-panic",
+ "sentry-tracing",
+ "ureq",
+]
+
+[[package]]
+name = "sentry-backtrace"
+version = "0.49.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4f27cf048aa63ccd5bc94c29989133eabb82e9c6bf7441b58e9d4a95837a105"
+dependencies = [
+ "backtrace",
+ "regex",
+ "sentry-core",
+]
+
+[[package]]
+name = "sentry-core"
+version = "0.49.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3ed398494bb8fc412a11a182c1883a10ae147587b8f6314abd222d1d626f31b"
+dependencies = [
+ "rand 0.10.3",
+ "sentry-types",
+ "serde",
+ "serde_json",
+ "url",
+]
+
+[[package]]
+name = "sentry-debug-images"
+version = "0.49.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "55854bb40681e84ffd2a69578ad4ef9bfaf5bf2bf1380a745578b591fa24af22"
+dependencies = [
+ "findshlibs",
+ "sentry-core",
+]
+
+[[package]]
+name = "sentry-panic"
+version = "0.49.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7153e68642b761ed3aa62c022795c11b2facc728b2db7484084492373c944f9"
+dependencies = [
+ "sentry-backtrace",
+ "sentry-core",
+]
+
+[[package]]
+name = "sentry-tracing"
+version = "0.49.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e7e7db1aefdf623f4e48e21ec9e4af535024187aeafb2a4cc7e29d035def5a13"
+dependencies = [
+ "bitflags 2.13.2",
+ "sentry-backtrace",
+ "sentry-core",
+ "tracing-core",
+ "tracing-subscriber",
+]
+
+[[package]]
+name = "sentry-types"
+version = "0.49.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1c18bf7b159bdfc7c8f97816f476b4947a1937fb6bea9d38d3479e58631614ac"
+dependencies = [
+ "debugid",
+ "hex",
+ "rand 0.10.3",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.20",
+ "time",
+ "url",
+ "uuid",
+]
+
[[package]]
name = "serde"
version = "1.0.229"
@@ -9562,6 +9733,7 @@ dependencies = [
"idna",
"percent-encoding",
"serde",
+ "serde_derive",
]
[[package]]
diff --git a/libs/cua/Cargo.toml b/libs/cua/Cargo.toml
index 2f5cbad50a..e92e1b1869 100644
--- a/libs/cua/Cargo.toml
+++ b/libs/cua/Cargo.toml
@@ -71,6 +71,8 @@ members = [
"crates/cua-logging",
# Anonymous product telemetry.
"crates/cua-telemetry",
+ # Opt-in crash reporting (Sentry panic handler, consent and scrubbing).
+ "crates/cua-crash",
# A failed create's cause as a fixed telemetry word (no dependencies).
"crates/cua-create-failure",
"crates/cua-viewer",
@@ -204,6 +206,7 @@ cua-spaces-app-core = { path = "crates/cua-spaces-app-core", version = "0.9.0" }
cua-spaces-ext = { path = "crates/cua-spaces-ext", version = "0.9.0" } # x-release-please-version
cua-byoc = { path = "crates/cua-byoc", version = "0.9.0", default-features = false } # x-release-please-version
cua-telemetry = { path = "crates/cua-telemetry", version = "0.9.0" } # x-release-please-version
+cua-crash = { path = "crates/cua-crash", version = "0.9.0" } # x-release-please-version
cua-create-failure = { path = "crates/cua-create-failure", version = "0.9.0" } # x-release-please-version
cua-spaces = { path = "crates/cua-spaces", version = "0.9.0" } # x-release-please-version
cua-spaces-contract = { path = "crates/cua-spaces-contract", version = "0.9.0" } # x-release-please-version
diff --git a/libs/cua/crates/cua-cli/Cargo.toml b/libs/cua/crates/cua-cli/Cargo.toml
index 2bad18db27..ca19df6cef 100644
--- a/libs/cua/crates/cua-cli/Cargo.toml
+++ b/libs/cua/crates/cua-cli/Cargo.toml
@@ -53,6 +53,7 @@ cua-byoc = { workspace = true, optional = true, features = ["aws"] }
# The `cluster_*` MCP tools: a client of the cluster coordinator's API.
# Anonymous usage telemetry (`cua telemetry`, the first-run notice).
cua-telemetry.workspace = true
+cua-crash.workspace = true
async-trait.workspace = true
cua-proto = { workspace = true, features = ["client", "serde"] }
cua-spaces = { path = "../cua-spaces", default-features = false, features = ["mcp", "spaces-hotspot"] }
diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rs
index 6782428fc7..272863c7cc 100644
--- a/libs/cua/crates/cua-cli/src/lib.rs
+++ b/libs/cua/crates/cua-cli/src/lib.rs
@@ -2818,6 +2818,17 @@ pub fn main() {
telemetry.set_notice_mode(notice_mode(
std::env::var("CUA_DAEMON_STARTED_BY").ok().as_deref(),
));
+ // Crash reports (opt-in, only when the Spaces shell passed a DSN) come
+ // from the daemon process itself, not the `cua daemon start` launcher.
+ let crash_guard = matches!(
+ cli.command,
+ Command::Daemon(DaemonCmd::Start {
+ foreground: true,
+ ..
+ })
+ )
+ .then(|| cua_crash::init_from_env("daemon"))
+ .flatten();
// The first-run notice goes to stderr before anything could be sent
// (not for `cua telemetry` / `cua config`, which are how you answer it).
if record && !matches!(cli.command, Command::Config(_)) {
@@ -2912,6 +2923,8 @@ pub fn main() {
}
});
let _ = std::io::stdout().flush();
+ // `process::exit` skips destructors: flush crash reports explicitly.
+ drop(crash_guard);
// Telemetry never holds the exit up for more than this; what is left
// goes to the offline spool, which the cua daemon (or the next command)
// sends. A round trip to the collector often takes longer than this, and
diff --git a/libs/cua/crates/cua-crash/Cargo.toml b/libs/cua/crates/cua-crash/Cargo.toml
new file mode 100644
index 0000000000..545738092e
--- /dev/null
+++ b/libs/cua/crates/cua-crash/Cargo.toml
@@ -0,0 +1,20 @@
+[package]
+name = "cua-crash"
+description = "Opt-in crash reporting for the Cua Spaces app's Rust core and daemon: the Sentry panic handler with a consent check and privacy scrubbing on every event."
+version.workspace = true
+edition.workspace = true
+rust-version.workspace = true
+authors.workspace = true
+license.workspace = true
+repository.workspace = true
+publish = false
+
+[dependencies]
+cua-telemetry.workspace = true
+# No default features: no reqwest or native-tls transport, no log, metrics or
+# contexts integrations, no release-health sessions. The transport is ureq 3
+# with rustls (ring), the stack cua-telemetry already links.
+sentry = { version = "0.49", default-features = false, features = ["ureq", "rustls", "backtrace", "panic", "debug-images"] }
+serde_json.workspace = true
+
+[dev-dependencies]
diff --git a/libs/cua/crates/cua-crash/src/lib.rs b/libs/cua/crates/cua-crash/src/lib.rs
new file mode 100644
index 0000000000..f36853ec7d
--- /dev/null
+++ b/libs/cua/crates/cua-crash/src/lib.rs
@@ -0,0 +1,234 @@
+//! Crash reporting for the Cua Spaces app's Rust core and daemon.
+//!
+//! The Spaces shells (Electron, SwiftUI) pass a Sentry DSN down through
+//! `CUA_CRASH_*` environment variables. When the DSN is set and the user
+//! allows it, panics in this process go to Sentry as events with a stack
+//! trace and nothing else: no messages, paths, emails, host names, IPs,
+//! breadcrumbs or sessions.
+//!
+//! Consent is the "Share usage data" decision of [`cua_telemetry`]: reports
+//! are allowed only when telemetry is enabled and the first-run notice has
+//! been shown. It is checked at start and again for every event.
+//!
+//! Without `CUA_CRASH_DSN` nothing is initialised, so the `cua` CLI and
+//! every other user of these crates are unaffected.
+
+mod scrub;
+
+pub use scrub::{scrub_event, scrub_text, scrub_text_with_home, scrub_url};
+
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, OnceLock};
+use std::time::Duration;
+
+/// Environment variables the shell sets before the native code starts.
+pub const ENV_DSN: &str = "CUA_CRASH_DSN";
+pub const ENV_RELEASE: &str = "CUA_CRASH_RELEASE";
+pub const ENV_ENVIRONMENT: &str = "CUA_CRASH_ENVIRONMENT";
+pub const ENV_SHELL: &str = "CUA_CRASH_SHELL";
+/// Local builds only: the named component panics once, shortly after init.
+pub const ENV_TEST_PANIC: &str = "CUA_CRASH_TEST_PANIC";
+
+/// How long a panic (and shutdown) waits for the event to leave.
+const FLUSH_TIMEOUT: Duration = Duration::from_secs(2);
+
+/// Everything the SDK needs; [`Config::from_env`] reads it from the shell.
+#[derive(Debug, Clone, Default)]
+pub struct Config {
+ pub dsn: String,
+ pub release: Option<String>,
+ pub environment: String,
+ pub shell: String,
+ pub component: String,
+}
+
+impl Config {
+ /// Reads the `CUA_CRASH_*` variables. `None` when no DSN is set.
+ pub fn from_env(component: &str) -> Option<Self> {
+ Self::from_lookup(component, |k| std::env::var(k).ok())
+ }
+
+ fn from_lookup(component: &str, get: impl Fn(&str) -> Option<String>) -> Option<Self> {
+ let non_empty = |k| {
+ get(k)
+ .map(|v| v.trim().to_string())
+ .filter(|v| !v.is_empty())
+ };
+ Some(Self {
+ dsn: non_empty(ENV_DSN)?,
+ release: non_empty(ENV_RELEASE),
+ environment: non_empty(ENV_ENVIRONMENT).unwrap_or_else(|| "stable".into()),
+ shell: non_empty(ENV_SHELL).unwrap_or_else(|| "unknown".into()),
+ component: component.to_string(),
+ })
+ }
+}
+
+/// Whether reports are allowed right now. Called for every event.
+pub type Consent = Arc<dyn Fn() -> bool + Send + Sync>;
+
+/// The "Share usage data" rule: telemetry enabled and the notice shown.
+pub fn telemetry_consent() -> bool {
+ let s = cua_telemetry::global().status();
+ s.enabled && s.notice_shown
+}
+
+/// Keeps the SDK alive; dropping it flushes what is queued and closes the
+/// client.
+pub struct Guard {
+ _inner: sentry::ClientInitGuard,
+}
+
+impl Guard {
+ /// Whether this guard's client is enabled (a valid DSN was given).
+ pub fn is_enabled(&self) -> bool {
+ self._inner.is_enabled()
+ }
+}
+
+static STARTED: AtomicBool = AtomicBool::new(false);
+static PROCESS_GUARD: OnceLock<Guard> = OnceLock::new();
+
+/// Starts crash reporting for this process from the `CUA_CRASH_*` variables.
+///
+/// Returns `None` when no DSN is set, when the user has not allowed reports
+/// (telemetry off or the notice not yet shown; a switch turned on later
+/// takes effect at the next launch), or when it already started in this
+/// process. Keep the guard for the life of the process.
+pub fn init_from_env(component: &str) -> Option<Guard> {
+ let cfg = Config::from_env(component)?;
+ if !telemetry_consent() {
+ return None;
+ }
+ if STARTED.swap(true, Ordering::SeqCst) {
+ return None;
+ }
+ let guard = init_with(cfg, Arc::new(telemetry_consent));
+ if guard.is_none() {
+ STARTED.store(false, Ordering::SeqCst);
+ }
+ guard
+}
+
+/// [`init_from_env`] for callers with nowhere to keep the guard (the FFI
+/// library): it lives for the process. Returns whether reporting started.
+pub fn start_for_process(component: &str) -> bool {
+ match init_from_env(component) {
+ Some(g) => PROCESS_GUARD.set(g).is_ok(),
+ None => false,
+ }
+}
+
+/// Closes the client when consent was withdrawn while running. Cheap; call
+/// it after the "Share usage data" switch changes.
+pub fn refresh_consent() {
+ if !telemetry_consent()
+ && let Some(client) = sentry::Hub::main().client()
+ {
+ client.close(Some(Duration::from_millis(200)));
+ }
+}
+
+/// Starts the SDK with an explicit config and consent check (the shared
+/// path of [`init_from_env`]; tests use it with a loopback DSN). Not
+/// idempotent on its own.
+pub fn init_with(cfg: Config, consent: Consent) -> Option<Guard> {
+ let dsn: sentry::types::Dsn = cfg.dsn.parse().ok()?;
+ let home = std::env::var("HOME")
+ .or_else(|_| std::env::var("USERPROFILE"))
+ .ok();
+ let before_send = {
+ let consent = consent.clone();
+ move |event: sentry::protocol::Event<'static>| {
+ if !consent() {
+ return None;
+ }
+ Some(scrub_event(event, home.as_deref()))
+ }
+ };
+ // `ClientOptions` is non-exhaustive: start from the default and set.
+ // Traces sampling defaults to off and stays there; sessions need the
+ // `release-health` feature, which is not enabled.
+ let mut options = sentry::ClientOptions::default();
+ options.dsn = Some(dsn);
+ options.release = cfg.release.clone().map(Into::into);
+ options.environment = Some(cfg.environment.clone().into());
+ options.send_default_pii = false;
+ options.attach_stacktrace = true;
+ options.server_name = None;
+ options.max_breadcrumbs = 0;
+ options.shutdown_timeout = FLUSH_TIMEOUT;
+ options.before_send = Some(Arc::new(before_send));
+ options.before_breadcrumb = Some(Arc::new(|_| None));
+ let guard = sentry::init(options);
+ if !guard.is_enabled() {
+ return None;
+ }
+ sentry::configure_scope(|scope| {
+ scope.set_tag("shell", &cfg.shell);
+ scope.set_tag("component", &cfg.component);
+ });
+ if cfg.environment == "local" && std::env::var(ENV_TEST_PANIC).is_ok_and(|c| c == cfg.component)
+ {
+ spawn_test_panic(&cfg.component);
+ }
+ Some(Guard { _inner: guard })
+}
+
+/// Local builds only: panics once, a moment after init, so the pipeline
+/// can be exercised end to end.
+fn spawn_test_panic(component: &str) {
+ static FIRED: AtomicBool = AtomicBool::new(false);
+ let component = component.to_string();
+ let _ = std::thread::Builder::new()
+ .name("cua-crash-test-panic".into())
+ .spawn(move || {
+ std::thread::sleep(Duration::from_millis(1500));
+ if !FIRED.swap(true, Ordering::SeqCst) {
+ panic!("cua-crash test panic ({component})");
+ }
+ });
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn lookup(pairs: &'static [(&'static str, &'static str)]) -> impl Fn(&str) -> Option<String> {
+ move |k| {
+ pairs
+ .iter()
+ .find(|(n, _)| *n == k)
+ .map(|(_, v)| v.to_string())
+ }
+ }
+
+ #[test]
+ fn no_dsn_means_off() {
+ assert!(Config::from_lookup("core", lookup(&[])).is_none());
+ assert!(Config::from_lookup("core", lookup(&[(ENV_DSN, " ")])).is_none());
+ }
+
+ #[test]
+ fn reads_the_contract_variables() {
+ let c = Config::from_lookup(
+ "daemon",
+ lookup(&[
+ (ENV_DSN, "https://[email protected]/2"),
+ (ENV_RELEASE, "[email protected]"),
+ (ENV_ENVIRONMENT, "beta"),
+ (ENV_SHELL, "swift"),
+ ]),
+ )
+ .unwrap();
+ assert_eq!(
+ c.release.as_deref(),
+ );
+ assert_eq!(
+ (c.environment.as_str(), c.shell.as_str()),
+ ("beta", "swift")
+ );
+ assert_eq!(c.component, "daemon");
+ }
+}
diff --git a/libs/cua/crates/cua-crash/src/scrub.rs b/libs/cua/crates/cua-crash/src/scrub.rs
new file mode 100644
index 0000000000..778f701c28
--- /dev/null
+++ b/libs/cua/crates/cua-crash/src/scrub.rs
@@ -0,0 +1,338 @@
+//! Pure scrubbing of events before they leave the machine.
+//!
+//! Hard rules: exception values and messages are cleared (they can carry
+//! Space names, file names, emails); the user, request bodies and headers,
+//! breadcrumbs, contexts and the host name are dropped; every string that
+//! remains loses home folder prefixes (`~`) and emails (`[email]`); URLs
+//! lose query strings and fragments.
+
+use sentry::protocol::{DebugImage, Event, Frame, Stacktrace};
+use serde_json::Value;
+
+/// Marker directories whose next path segment is a user name.
+const HOME_PARENTS: [&str; 3] = ["/Users/", "/home/", "\\Users\\"];
+
+/// [`scrub_text_with_home`] with no extra home folder.
+pub fn scrub_text(s: &str) -> String {
+ scrub_text_with_home(s, None)
+}
+
+/// Replaces home folder prefixes (`/Users/<x>`, `/home/<x>`,
+/// `C:\Users\<x>`, and `home` itself) with `~` and emails with `[email]`.
+pub fn scrub_text_with_home(s: &str, home: Option<&str>) -> String {
+ let mut out = s.to_string();
+ if let Some(h) = home.map(|h| h.trim_end_matches(['/', '\\']))
+ && h.len() > 1
+ && out.contains(h)
+ {
+ out = out.replace(h, "~");
+ }
+ scrub_emails(&scrub_home_dirs(&out))
+}
+
+fn is_sep(c: char) -> bool {
+ matches!(c, '/' | '\\') || c.is_whitespace() || matches!(c, '"' | '\'' | ':' | ',' | ')')
+}
+
+fn scrub_home_dirs(s: &str) -> String {
+ let mut out = String::with_capacity(s.len());
+ let mut rest = s;
+ loop {
+ let hit = HOME_PARENTS
+ .iter()
+ .filter_map(|m| find_ci(rest, m).map(|i| (i, m.len())))
+ .min_by_key(|(i, _)| *i);
+ let Some((i, mlen)) = hit else {
+ out.push_str(rest);
+ return out;
+ };
+ let after = &rest[i + mlen..];
+ let seg_len = after.find(is_sep).unwrap_or(after.len());
+ if seg_len == 0 {
+ out.push_str(&rest[..i + mlen]);
+ rest = after;
+ continue;
+ }
+ let mut head = &rest[..i];
+ // A Windows drive prefix (`C:`) belongs to the home folder.
+ let b = head.as_bytes();
+ if mlen == 7
+ && b.len() >= 2
+ && b[b.len() - 1] == b':'
+ && b[b.len() - 2].is_ascii_alphabetic()
+ {
+ head = &head[..head.len() - 2];
+ }
+ out.push_str(head);
+ out.push('~');
+ rest = &after[seg_len..];
+ }
+}
+
+/// Case-insensitive (ASCII) find of an ASCII `needle`.
+fn find_ci(hay: &str, needle: &str) -> Option<usize> {
+ let (h, n) = (hay.as_bytes(), needle.as_bytes());
+ if n.len() > h.len() {
+ return None;
+ }
+ (0..=h.len() - n.len()).find(|&i| h[i..i + n.len()].eq_ignore_ascii_case(n))
+}
+
+fn scrub_emails(s: &str) -> String {
+ if !s.contains('@') {
+ return s.to_string();
+ }
+ let local_ok = |c: char| c.is_alphanumeric() || "._%+-".contains(c);
+ let domain_ok = |c: char| c.is_alphanumeric() || ".-".contains(c);
+ let mut out = String::with_capacity(s.len());
+ let mut last = 0;
+ for (at, _) in s.match_indices('@') {
+ if at < last {
+ continue;
+ }
+ let start = s[last..at]
+ .char_indices()
+ .rev()
+ .take_while(|(_, c)| local_ok(*c))
+ .last()
+ .map_or(at, |(i, _)| last + i);
+ let tail = &s[at + 1..];
+ let dlen = tail.find(|c: char| !domain_ok(c)).unwrap_or(tail.len());
+ let domain = tail[..dlen].trim_end_matches(['.', '-']);
+ if start < at && domain.contains('.') && !domain.starts_with('.') {
+ out.push_str(&s[last..start]);
+ out.push_str("[email]");
+ last = at + 1 + domain.len();
+ }
+ }
+ out.push_str(&s[last..]);
+ out
+}
+
+/// A URL without credentials, query string or fragment, and with its path
+/// scrubbed. Anything that does not parse is returned as scrubbed text cut
+/// at the first `?` or `#`.
+pub fn scrub_url(url: &str, home: Option<&str>) -> String {
+ let cut = url.split(['?', '#']).next().unwrap_or("");
+ let no_creds = match cut.split_once("://") {
+ Some((scheme, rest)) => {
+ let (authority, path) = rest.split_at(rest.find('/').unwrap_or(rest.len()));
+ let host = authority.rsplit('@').next().unwrap_or(authority);
+ format!("{scheme}://{host}{path}")
+ }
+ None => cut.to_string(),
+ };
+ scrub_text_with_home(&no_creds, home)
+}
+
+fn scrub_opt(s: &mut Option<String>, home: Option<&str>) {
+ if let Some(v) = s {
+ *v = scrub_text_with_home(v, home);
+ }
+}
+
+fn scrub_json(v: &mut Value, home: Option<&str>) {
+ match v {
+ Value::String(s) => *s = scrub_text_with_home(s, home),
+ Value::Array(a) => a.iter_mut().for_each(|x| scrub_json(x, home)),
+ Value::Object(m) => m.values_mut().for_each(|x| scrub_json(x, home)),
+ _ => {}
+ }
+}
+
+fn scrub_frame(f: &mut Frame, home: Option<&str>) {
+ scrub_opt(&mut f.filename, home);
+ scrub_opt(&mut f.abs_path, home);
+ scrub_opt(&mut f.package, home);
+ // Function and module names are code, not user data, but run the same
+ // pass in case a closure name embeds a path.
+ scrub_opt(&mut f.function, home);
+ scrub_opt(&mut f.symbol, home);
+ scrub_opt(&mut f.module, home);
+ f.pre_context.clear();
+ f.post_context.clear();
+ f.context_line = None;
+ f.vars.clear();
+}
+
+fn scrub_stacktrace(st: &mut Option<Stacktrace>, home: Option<&str>) {
+ if let Some(st) = st {
+ st.frames.iter_mut().for_each(|f| scrub_frame(f, home));
+ st.registers.clear();
+ }
+}
+
+/// Applies every privacy rule to `event`. `home` is the actual home folder
+/// of this process, if known.
+pub fn scrub_event(mut event: Event<'static>, home: Option<&str>) -> Event<'static> {
+ event.message = None;
+ event.logentry = None;
+ event.user = None;
+ event.server_name = None;
+ event.breadcrumbs.values.clear();
+ event.contexts.clear();
+ event.modules.clear();
+ event.template = None;
+ event.logger = None;
+ scrub_opt(&mut event.culprit, home);
+ scrub_opt(&mut event.transaction, home);
+
+ for ex in &mut event.exception.values {
+ ex.value = None;
+ scrub_opt(&mut ex.module, home);
+ scrub_stacktrace(&mut ex.stacktrace, home);
+ scrub_stacktrace(&mut ex.raw_stacktrace, home);
+ }
+ scrub_stacktrace(&mut event.stacktrace, home);
+ for t in &mut event.threads.values {
+ scrub_opt(&mut t.name, home);
+ scrub_stacktrace(&mut t.stacktrace, home);
+ scrub_stacktrace(&mut t.raw_stacktrace, home);
+ }
+
+ if let Some(req) = &mut event.request {
+ if let Some(url) = &mut req.url {
+ let clean = scrub_url(url.as_str(), home);
+ if let Ok(u) = clean.parse() {
+ *url = u;
+ } else {
+ req.url = None;
+ }
+ }
+ req.query_string = None;
+ req.cookies = None;
+ req.data = None;
+ req.headers.clear();
+ req.env.clear();
+ }
+
+ for v in event.tags.values_mut() {
+ *v = scrub_text_with_home(v, home);
+ }
+ event.extra.values_mut().for_each(|v| scrub_json(v, home));
+
+ let meta = event.debug_meta.to_mut();
+ meta.sdk_info = None;
+ for img in &mut meta.images {
+ match img {
+ DebugImage::Symbolic(i) => {
+ i.name = scrub_text_with_home(&i.name, home);
+ scrub_opt(&mut i.debug_file, home);
+ }
+ DebugImage::Apple(i) => i.name = scrub_text_with_home(&i.name, home),
+ DebugImage::Wasm(i) => {
+ i.name = scrub_text_with_home(&i.name, home);
+ i.code_file = scrub_text_with_home(&i.code_file, home);
+ scrub_opt(&mut i.debug_file, home);
+ }
+ _ => {}
+ }
+ }
+ event
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use sentry::protocol::{Exception, Request, User, Values};
+
+ #[test]
+ fn home_paths_become_tilde() {
+ assert_eq!(scrub_text("/Users/alice/Library/x.rs"), "~/Library/x.rs");
+ assert_eq!(
+ scrub_text("at /home/bob/.cargo/lib.rs:3"),
+ "at ~/.cargo/lib.rs:3"
+ );
+ assert_eq!(scrub_text(r"C:\Users\Carol\AppData\x"), r"~\AppData\x");
+ assert_eq!(scrub_text("/users/dave/x"), "~/x");
+ assert_eq!(
+ scrub_text_with_home("/opt/me/work/a.rs", Some("/opt/me")),
+ "~/work/a.rs"
+ );
+ assert_eq!(scrub_text("/Users/"), "/Users/");
+ assert_eq!(scrub_text("/usr/lib/libc.dylib"), "/usr/lib/libc.dylib");
+ assert_eq!(scrub_text("/Users/a/x and /Users/b/y"), "~/x and ~/y");
+ }
+
+ #[test]
+ fn emails_are_replaced() {
+ assert_eq!(
+ scrub_text("mail [email protected] now"),
+ "mail [email] now"
+ );
+ assert_eq!(scrub_text("<[email protected]>,[email protected]"), "<[email]>,[email]");
+ assert_eq!(scrub_text("user@host"), "user@host");
+ assert_eq!(scrub_text("@handle and a @ b"), "@handle and a @ b");
+ }
+
+ #[test]
+ fn urls_lose_query_fragment_and_credentials() {
+ assert_eq!(
+ scrub_url("https://u:[email protected]/a/b?token=1&[email protected]#frag", None),
+ "https://spaces.cua.ai/a/b"
+ );
+ assert_eq!(scrub_url("/Users/x/f?y=1", None), "~/f");
+ }
+
+ fn dirty() -> Event<'static> {
+ let mut ev = Event {
+ message: Some("boom in Space acme-secrets".into()),
+ server_name: Some("Francescos-MacBook.local".into()),
+ user: Some(User {
+ ip_address: Some("1.2.3.4".parse().unwrap()),
+ email: Some("[email protected]".into()),
+ ..Default::default()
+ }),
+ request: Some(Request {
+ url: Some("https://x.test/p?q=secret#f".parse().unwrap()),
+ query_string: Some("q=secret".into()),
+ headers: [("Cookie".to_string(), "s=1".to_string())].into(),
+ ..Default::default()
+ }),
+ exception: Values::from(vec![Exception {
+ ty: "panic".into(),
+ value: Some("failed to open /Users/alice/Secret Space.txt".into()),
+ stacktrace: Some(Stacktrace {
+ frames: vec![Frame {
+ filename: Some("/Users/alice/src/lib.rs".into()),
+ abs_path: Some("/Users/alice/src/lib.rs".into()),
+ function: Some("run".into()),
+ context_line: Some("let k = 1;".into()),
+ ..Default::default()
+ }],
+ ..Default::default()
+ }),
+ ..Default::default()
+ }]),
+ ..Default::default()
+ };
+ ev.tags.insert("path".into(), "/home/bob/x [email protected]".into());
+ ev.extra
+ .insert("n".into(), serde_json::json!({"p": ["/Users/zed/q"]}));
+ ev
+ }
+
+ #[test]
+ fn event_is_scrubbed() {
+ let ev = scrub_event(dirty(), None);
+ assert!(ev.message.is_none() && ev.logentry.is_none());
+ assert!(ev.server_name.is_none());
+ assert!(ev.user.is_none());
+ assert_eq!(ev.exception.values[0].value, None);
+ assert_eq!(ev.exception.values[0].ty, "panic");
+ let f = &ev.exception.values[0].stacktrace.as_ref().unwrap().frames[0];
+ assert_eq!(f.filename.as_deref(), Some("~/src/lib.rs"));
+ assert_eq!(f.abs_path.as_deref(), Some("~/src/lib.rs"));
+ assert_eq!(f.function.as_deref(), Some("run"));
+ assert!(f.context_line.is_none());
+ let r = ev.request.clone().unwrap();
+ assert_eq!(r.url.clone().unwrap().as_str(), "https://x.test/p");
+ assert!(r.query_string.is_none() && r.headers.is_empty());
+ assert_eq!(ev.tags["path"], "~/x [email]");
+ assert_eq!(ev.extra["n"]["p"][0], "~/q");
+ let all = format!("{ev:?}");
+ for needle in ["alice", "bob", "zed", "secret", "MacBook", "[email protected]"] {
+ assert!(!all.contains(needle), "{needle} leaked: {all}");
+ }
+ }
+}
diff --git a/libs/cua/crates/cua-crash/tests/mock_ingest.rs b/libs/cua/crates/cua-crash/tests/mock_ingest.rs
new file mode 100644
index 0000000000..5131a48025
--- /dev/null
+++ b/libs/cua/crates/cua-crash/tests/mock_ingest.rs
@@ -0,0 +1,148 @@
+//! A panic goes to a local mock ingest only when consent is on, and what
+//! arrives is scrubbed. One test function: the panic hook and the SDK's main
+//! hub are process-wide.
+
+use std::io::{Read, Write};
+use std::net::{TcpListener, TcpStream};
+use std::sync::atomic::{AtomicBool, Ordering};
+use std::sync::{Arc, Mutex};
+use std::time::Duration;
+
+type Bodies = Arc<Mutex<Vec<String>>>;
+
+fn read_request(mut s: TcpStream) -> Option<String> {
+ s.set_read_timeout(Some(Duration::from_secs(5))).ok()?;
+ let mut buf = Vec::new();
+ let mut chunk = [0u8; 4096];
+ let head_end = loop {
+ let n = s.read(&mut chunk).ok()?;
+ if n == 0 {
+ return None;
+ }
+ buf.extend_from_slice(&chunk[..n]);
+ if let Some(i) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
+ break i + 4;
+ }
+ };
+ let head = String::from_utf8_lossy(&buf[..head_end]).to_lowercase();
+ let len: usize = head
+ .lines()
+ .find_map(|l| l.strip_prefix("content-length:"))
+ .and_then(|v| v.trim().parse().ok())
+ .unwrap_or(0);
+ while buf.len() < head_end + len {
+ let n = s.read(&mut chunk).ok()?;
+ if n == 0 {
+ break;
+ }
+ buf.extend_from_slice(&chunk[..n]);
+ }
+ let _ = s.write_all(
+ b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{}",
+ );
+ Some(String::from_utf8_lossy(&buf[head_end..]).into_owned())
+}
+
+fn mock_ingest() -> (u16, Bodies) {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let port = listener.local_addr().unwrap().port();
+ let bodies: Bodies = Arc::default();
+ let sink = bodies.clone();
+ std::thread::spawn(move || {
+ for s in listener.incoming().flatten() {
+ if let Some(b) = read_request(s) {
+ sink.lock().unwrap().push(b);
+ }
+ }
+ });
+ (port, bodies)
+}
+
+fn config(port: u16) -> cua_crash::Config {
+ cua_crash::Config {
+ dsn: format!("http://[email protected]:{port}/42"),
+ release: Some("[email protected]".into()),
+ environment: "local".into(),
+ shell: "swift".into(),
+ component: "core".into(),
+ }
+}
+
+fn panic_in_thread() {
+ let _ = std::thread::spawn(|| {
+ panic!("opened /Users/alicia/Secret Space.txt for [email protected]");
+ })
+ .join();
+}
+
+#[test]
+fn consent_gates_and_scrubs() {
+ // Consent off: the panic produces no request.
+ let (port, bodies) = mock_ingest();
+ let guard = cua_crash::init_with(config(port), Arc::new(|| false)).expect("init");
+ panic_in_thread();
+ drop(guard);
+ std::thread::sleep(Duration::from_millis(300));
+ assert!(
+ bodies.lock().unwrap().is_empty(),
+ "nothing may be sent with consent off"
+ );
+
+ // Consent on (and revoked later in the same run): the event arrives,
+ // scrubbed.
+ let (port, bodies) = mock_ingest();
+ let on = Arc::new(AtomicBool::new(true));
+ let flag = on.clone();
+ let guard = cua_crash::init_with(config(port), Arc::new(move || flag.load(Ordering::SeqCst)))
+ .expect("init");
+ sentry::configure_scope(|s| {
+ s.set_extra("note", "from /home/bobby/x".into());
+ s.set_user(Some(sentry::User {
+ email: Some("[email protected]".into()),
+ ..Default::default()
+ }));
+ });
+ sentry::add_breadcrumb(sentry::Breadcrumb {
+ message: Some("click on Secret Space".into()),
+ ..Default::default()
+ });
+ panic_in_thread();
+ // The panic path flushes before it returns; no sleep needed.
+ let got = bodies.lock().unwrap().clone();
+ assert_eq!(got.len(), 1, "one envelope expected, got {got:?}");
+ let body = &got[0];
+ for leaked in [
+ "alicia",
+ "bobby",
+ "caroline",
+ "example.com",
+ "Secret",
+ "Space.txt",
+ ] {
+ assert!(!body.contains(leaked), "{leaked} leaked");
+ }
+ for want in [
+ "\"type\":\"panic\"",
+ "\"shell\":\"swift\"",
+ "\"component\":\"core\"",
+ "\"environment\":\"local\"",
+ "~/",
+ ] {
+ assert!(body.contains(want), "{want} missing");
+ }
+ assert!(!body.contains("server_name"), "host name sent");
+ assert!(!body.contains("\"user\""), "user sent");
+ assert!(!body.contains("breadcrumbs"), "breadcrumbs sent");
+
+ // Consent withdrawn mid-run: the next panic is dropped.
+ on.store(false, Ordering::SeqCst);
+ panic_in_thread();
+ drop(guard);
+ std::thread::sleep(Duration::from_millis(300));
+ assert_eq!(
+ bodies.lock().unwrap().len(),
+ 1,
+ "revoked consent still sent"
+ );
+}
diff --git a/libs/cua/crates/cua-spaces-ffi/Cargo.toml b/libs/cua/crates/cua-spaces-ffi/Cargo.toml
index 9ba8789a61..2363f837c0 100644
--- a/libs/cua/crates/cua-spaces-ffi/Cargo.toml
+++ b/libs/cua/crates/cua-spaces-ffi/Cargo.toml
@@ -24,6 +24,7 @@ cua-home.workspace = true
cua-host.workspace = true
cua-spacesd-client.workspace = true
cua-telemetry.workspace = true
+cua-crash.workspace = true
tokio-tungstenite.workspace = true
uniffi.workspace = true
serde.workspace = true
diff --git a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
index 2a045457da..893a0f61ba 100644
--- a/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
+++ b/libs/cua/crates/cua-spaces-ffi/src/app_core.rs
@@ -2619,6 +2619,8 @@ pub fn app_telemetry_start(version: String, onboarding_eligible: Option<bool>) -
cua_sdk::support::spawn(async {
cua_sdk::telemetry_sync_account().await;
});
+ // Crash reports for the core (no-op without CUA_CRASH_DSN or consent).
+ cua_crash::start_for_process("core");
core::telemetry::start_with(t, onboarding_eligible)
}
@@ -2627,7 +2629,11 @@ pub fn app_telemetry_start(version: String, onboarding_eligible: Option<bool>) -
/// were queued.
#[uniffi::export]
pub fn app_telemetry_record(signals: Vec<AppTelemetrySignal>) -> u32 {
- core::telemetry::record(cua_telemetry::global(), &signals) as u32
+ let queued = core::telemetry::record(cua_telemetry::global(), &signals) as u32;
+ // The "Share usage data" switch may have changed: close crash reporting
+ // when consent was withdrawn.
+ cua_crash::refresh_consent();
+ queued
}
/// The app started (`app_launched`).