The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
chore: remove analytics from the desktop and phone apps
bubu-duduac0c8393dc86
diff --git a/desktop/CLAUDE.md b/desktop/CLAUDE.mdindex d797d8110..09603d051 100644--- a/desktop/CLAUDE.md+++ b/desktop/CLAUDE.md@@ -126,7 +126,7 @@ The owner daemon stores comments and enforces link/invitation access on everyrequest. Reuse `ShareHarnessDialog` and `HarnessComments` for both app targets.See [README.md](README.md#web-development) for origin setup, browser storagelifetime, capability limits, and Chrome checks. Browser tests must set-`--dart-define=HARNESS_TEST=true` so no production pollers or analytics run.+`--dart-define=HARNESS_TEST=true` so no production pollers run.### Native desktop talks to the local `harness` CLI@@ -376,8 +376,8 @@ its headless debug timings do not establish native display or network latency.than assuming, because a confident "5h" beside a real percentage reads as measured.`loading` is false **before** `start()` as well as after the first answer — a controller nobodystarted is not waiting for anything, and a skeleton for it would promise an answer never coming.- That is also what keeps `flutter test` honest: `kUnderTest` (`core/test_run.dart`, shared with- `AnalyticsConfig`) stops the poll auto-starting, since a `Timer.periodic` is a `pumpAndSettle` that+ That is also what keeps `flutter test` honest: `kUnderTest` (`core/test_run.dart`) stops the+ poll auto-starting, since a `Timer.periodic` is a `pumpAndSettle` thatnever settles and these sources would otherwise shell out to `security` and open real sockets.- **The token ledger is the OTHER usage feature, and the two must not be merged** (`lib/usage/ledger/`,Settings ▸ Usage in `settings/sections/usage_section.dart` + `usage_panels.dart`). The Models menu's@@ -440,10 +440,10 @@ its headless debug timings do not establish native display or network latency.(`lib/stats/harness_stats.dart`, drawn by `StatsSummaryCards`). Ported from Orca's`src/main/stats/`: agents spawned, time agents worked, and a "Tracking since" line. These are thisapp's own events, so unlike the ledger there is no permission to ask and no switch — an app may- count what it did. `harnessStats` is a singleton like `analytics`, loaded by+ count what it did. `harnessStats` is a singleton like `appLog`, loaded by`loadPersistedSettings` (not for the first frame — because the counters start moving as soon as anagent does, and a load landing after the first `onAgentSpawned` would overwrite it) and flushed by- `AnalyticsLifecycle.didRequestAppExit`, which is the ONLY place a turn still running at quit gets+ `StatsLifecycle.didRequestAppExit` (`stats/stats_lifecycle.dart`), which is the ONLY place a turn still running at quit getsits time counted.Three hooks, all in `AppNotifier`: `createAgent` (**not** the `agent_created` push, which alsofires for agents another client made on the same machine), the `turn_started` case (**not**@@ -491,59 +491,6 @@ its headless debug timings do not establish native display or network latency.`SingleChildScrollView` the incoming width is unbounded, so `CrossAxisAlignment.stretch` asks foran infinite row and the layout throws; `_sessionTableWidth` sums the columns, which is the onlyhonest width it has.-- **Behavioural analytics is a PORT of Grid's, not a second design** (`lib/analytics/`, copied from- `autonomous-grid-app/lib/infrastructure/analytics/`). It reports to **Autonomous Analytics**, the- stream the website and Grid already feed, so one person's path across the three products is one- funnel; `AnalyticsConfig.category` (`harness-desktop`) is what keeps them apart inside it. Not to- be confused with the CLI's `harness analytics`, which is a different product entirely — aggregate- usage metering uploaded to the Harness backend. ⚠️ **It reports under GRID's write key**, not one- of its own: `_defaultWriteKey` is the same constant `autonomous-grid-app` ships, so both apps- append into one analytics project and are separable **only by `category`**, not at the source —- a quota, a retention rule or a rotated key set on that project lands on both at once- (**TODO(BE)**: a Harness Desktop key is a one-constant change here). ⚠️ **With the Grid project- killed (2026-09-11), that shared project is the one to watch**: if it is wound down or its key- rotated, this app's analytics go silent with it. `--dart-define=HARNESS_ANALYTICS_KEY=…`- overrides it for a dev build. It still mutes for three other reasons — `HARNESS_ANALYTICS_DISABLED`,- a test run, and an opt-out (`{"enabled": false}` in `~/.harness/desktop-app/analytics.json`) —- checked in that order so `flutter test` never reads a real Harness home. The sink is a **singleton** (`analytics`), like- `themeModeStore`: the call sites are `main`, `AppNotifier`, a settings pane and a menu inside a- pane header, and most were handed a notifier rather than a `Ref`. Every event name is written down- **once**, in `analytics_events.dart` — two call sites naming one action differently is what makes- a stream unqueryable — and params are product facts only: a short code, an option, a count, an id.- **Never** a prompt, terminal output, an agent or machine name, or a path. One event is- deliberately not where you would look for it: `app_opened` is sent by `AppNotifier` when- bootstrap resolves (a first-frame event would report every launch as signed out). **The agent funnel is- three events, one per step, because the interesting numbers are the DROPS between them**:- `new_agent_opened` is sent by `showNewAgentDialog` itself rather than by its four callers, so a- fifth door cannot forget to report (its `source` is `required`, not defaulted); `agent_created`- is sent by the dialog once Create succeeds, carrying only the engine and the bypass flag;- `app_first_message` rides the CLI's `turn_started` rather than the- composer, so a message typed straight into the terminal counts, and it fires **once per signed-in- session, not per agent** (`_awaitingFirstMessage`) — the question is how long somebody sits- logged in before talking to anything at all, so it carries the wait and `from` (`sign_in` against- `launch`, two populations that must not be averaged together) and deliberately names no agent,- engine or machine. Sign-out clears the clock: a session that ended without a message reports- nothing, and its absence is the finding. `app_closed` hooks only- `didRequestAppExit` — intercepting the window's close button needs `setPreventClose(true)`, and a- bug on that path leaves a window nobody can close.- **Settings ▸ Tracking is where that stream is read back** (`analytics/analytics_log.dart`,- `settings/sections/tracking_*.dart`, ported from Grid's Tracking tab), and it answers the- question analytics always raises and normally cannot: *did that event actually leave, and what- was in it?* — an event never sent, sent with a missing field, or refused by the server looks- exactly like one that landed, because the app is silent either way by design. `QueuedAnalytics`- reports each row's life to an `AnalyticsLog` (`queued → attempted → settled`), so a retry is- **one row with two attempts** rather than two rows, and the dialog shows the payload *as sent*- beside the params the call site passed — the gap between those two is the bug it exists to find.- Gated by `kDebugSurfaceEnabled` like Settings ▸ Debug, which now hides two rail rows rather than- one (`_kDeveloperSections` in `settings_section.dart` names both, once). **The muted case is the- one that matters**: a build can send nothing for four separate reasons, and a Tracking screen that- were blank for any of them would be the exact trap it exists to spring — hence `MutedAnalytics`,- which records every event as `dropped` with the reason, and a header card- that says `Off` and why in a sentence. A release build has no such screen and gets `NoopAnalytics`- and a `NoopAnalyticsLog`, so nothing is retained for a surface that is not there. The buffer is- in memory and never written to disk — a stream that measures the app must not become a second- thing the app writes on every click — which is also why recording is right even for a user who- opted out: their choice is about what we *send*, and this sends nothing.- Settings is a **screen**, not a dialog (`lib/settings/`): `showSettingsScreen` pushes a faded routewhose rail lists `settingsGroups` from `settings_section.dart` and whose pane is one widget per`SettingsSection` (`sections/`). Adding a setting means adding an enum value, a group entry and adiff --git a/desktop/README.md b/desktop/README.mdindex 54c8de2e3..39b3a6961 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -59,7 +59,6 @@ comma-separated `WEB_ORIGINS`, and register that origin's `/auth/callback` withAny `SSO_REDIRECT_URI` override must point to that same hosted callback. Tests use asynthetic authorization service. An alternate backend can be selected with`--dart-define=HARNESS_API_URL=https://your-backend.example` on run/build.-Use `--dart-define=HARNESS_ANALYTICS_DISABLED=true` for isolated previews.### Production releasediff --git a/desktop/lib/analytics/analytics.dart b/desktop/lib/analytics/analytics.dartdeleted file mode 100644index 7ef5a2f09..000000000--- a/desktop/lib/analytics/analytics.dart+++ /dev/null@@ -1,54 +0,0 @@-import 'analytics_config.dart';--export 'analytics_events.dart';-export 'analytics_sink.dart' show analytics, analyticsAccount;--/// The app's behavioural-event sink.-///-/// Ported from Grid (`lib/infrastructure/analytics/`) rather than rewritten, so-/// the two desktop apps report into one stream in one shape — see-/// [AnalyticsConfig] for the destination and why it is shared.-///-/// Not to be confused with the Harness CLI's `harness analytics`. That is a-/// different product: aggregate usage metering (turns per engine per day)-/// uploaded to the Harness backend. This is what a person *did* in this window,-/// and the two never meet.-///-/// Every call site talks to this, never to the transport underneath, so-/// tracking can be muted (opt-out, a test run, a build with no key) by handing-/// out a [NoopAnalytics] instead of by checking a flag at each call site.-///-/// Nothing here throws and nothing here is awaited by the UI: an analytics-/// problem must never be something the user finds out about.-abstract interface class Analytics {- /// Queue one event. [name] must be `snake_case`- /// (`analyticsEventNamePattern`) or it is dropped with a warning in the- /// debug log — the backend would accept it silently and leave the stream- /// unqueryable.- ///- /// [params] is free-form, but it is a *product* record, not a debug dump:- /// never put message text, prompts, terminal output, file contents or- /// absolute paths in it.- void track(String name, {Map<String, Object?> params});-- /// Send whatever is queued now, instead of waiting on the retry timer.- Future<void> flush();-- /// Final, time-boxed drain, then release the connection. Called when the app- /// quits; the instance is spent afterwards.- Future<void> close();-}--/// Does nothing, for a muted app and for tests.-class NoopAnalytics implements Analytics {- const NoopAnalytics();-- @override- void track(String name, {Map<String, Object?> params = const {}}) {}-- @override- Future<void> flush() async {}-- @override- Future<void> close() async {}-}diff --git a/desktop/lib/analytics/analytics_client.dart b/desktop/lib/analytics/analytics_client.dartdeleted file mode 100644index bf549dad3..000000000--- a/desktop/lib/analytics/analytics_client.dart+++ /dev/null@@ -1,92 +0,0 @@-import 'dart:async';--import 'package:dio/dio.dart';--import 'analytics_config.dart';--/// What one send attempt came to.-enum AnalyticsSendResult {- /// The server took it.- sent,-- /// Worth trying again with the same body — a timeout, an offline machine, a- /// 429 or a 5xx. The event stays at the head of the queue.- retry,-- /// The server refused the event itself (a 4xx that isn't 408 or 429). Sending- /// it again would fail identically, so it is dropped and logged: that is our- /// instrumentation being wrong, not the network.- rejected,-}--/// Posts one event to Autonomous Analytics.-///-/// An interface rather than a bare function so the queue can be exercised-/// against a fake, which is how `test/analytics_test.dart` reaches every branch-/// without a socket.-abstract interface class AnalyticsClient {- /// Sends [payload] as `POST …/event_tracking`. Never throws; a transport- /// failure comes back as [AnalyticsSendResult.retry].- Future<AnalyticsSendResult> send(Map<String, Object?> payload);-- /// Releases the underlying connection. Called once, when the app quits.- void dispose();-}--/// Real [AnalyticsClient] using Dio on both native and browser targets.-///-/// Deliberately not the app's Dio [ApiClient]: that one carries the CLI's base-/// URL and unwraps `{success, data|error}` envelopes, neither of which applies-/// to a third-party ingest host. One HTTP client for the life of the app, so a-/// burst of events reuses the connection instead of paying a TLS handshake per-/// click.-class HttpAnalyticsClient implements AnalyticsClient {- HttpAnalyticsClient(this._config);-- final AnalyticsConfig _config;- late final Dio _client = Dio(- BaseOptions(- connectTimeout: AnalyticsLimits.requestTimeout,- receiveTimeout: AnalyticsLimits.requestTimeout,- sendTimeout: AnalyticsLimits.requestTimeout,- validateStatus: (status) => status != null,- headers: {'Authorization': _config.writeKey},- ),- );- bool _disposed = false;-- @override- Future<AnalyticsSendResult> send(Map<String, Object?> payload) async {- if (_disposed) return AnalyticsSendResult.rejected;- try {- final response = await _client.post<dynamic>(- _config.endpoint.toString(),- data: payload,- );- return _resultFor(response.statusCode ?? 0);- } on TimeoutException {- return AnalyticsSendResult.retry;- } on DioException {- return AnalyticsSendResult.retry;- } on Object {- // Anything left (a bad URL, a TLS failure) would fail the same way every- // time, so it is the event that goes, not the queue behind it.- return AnalyticsSendResult.rejected;- }- }-- @override- void dispose() {- _disposed = true;- _client.close(force: true);- }-- /// 408 and 429 are "come back later", not "you are wrong" — they retry with- /// the rest of the transport failures.- static AnalyticsSendResult _resultFor(int status) => switch (status) {- >= 200 && < 300 => AnalyticsSendResult.sent,- 408 || 429 => AnalyticsSendResult.retry,- >= 500 => AnalyticsSendResult.retry,- _ => AnalyticsSendResult.rejected,- };-}diff --git a/desktop/lib/analytics/analytics_config.dart b/desktop/lib/analytics/analytics_config.dartdeleted file mode 100644index ad88585f7..000000000--- a/desktop/lib/analytics/analytics_config.dart+++ /dev/null@@ -1,170 +0,0 @@-import 'package:flutter/foundation.dart';--import '../core/runtime_platform.dart';-import '../core/test_run.dart';--/// Where behavioural events go, whether they go at all, and under what limits.-///-/// The destination is **Autonomous Analytics** — the same event stream the-/// website and the Grid desktop app report into. Sharing the destination is the-/// point: someone who read the site, installed Grid and then installed Harness-/// is one funnel, not three datasets that can never be joined. [category] is-/// what keeps them apart within it.-///-/// ⚠️ **This app reports under GRID's write key, not one of its own.** The-/// constant below is the same one `autonomous-grid-app` ships, so both desktop-/// apps append into the same analytics project. That is a deliberate stopgap —-/// a muted stream measures nothing, and this app has been waiting on a key of-/// its own since the port — but the cost is real and worth stating: the two-/// apps are then separable **only by [category]** (`harness-desktop` against-/// Grid's `grid-app`, stamped on every event), not at the source. Anyone-/// reading the Grid project sees this app's events inside it, and anything set-/// per project — a quota, a retention rule, a rotated or revoked key — lands on-/// both apps at once.-///-/// TODO(BE): swap in a Harness Desktop key from the analytics owner. It is a-/// one-constant change here, and it is the only thing that separates the two-/// streams properly.-///-/// The key is a *write* key rather than a secret. The website ships the same-/// kind of key in its public JS bundle, a desktop binary can be unpacked either-/// way, and it only lets the holder append events.-class AnalyticsConfig {- const AnalyticsConfig({- required this.endpoint,- required this.writeKey,- this.offReason,- });-- /// The full `…/api/v1/event_tracking` URL one event is POSTed to. Autonomous- /// Analytics takes a single event per request — there is no batch route — so- /// the queue sends serially rather than in batches.- final Uri endpoint;-- /// Sent verbatim as `Authorization`, with no `Bearer` prefix — that is what- /// the web client does and what the server reads.- final String writeKey;-- /// Why nothing is being sent, or null when the stream is live. A sentence- /// rather than a bool, because it is the answer to "why is nothing arriving"- /// and a developer can lose an hour to that question.- final String? offReason;-- /// Whether events are queued and sent at all.- bool get enabled => offReason == null;-- /// Stamped on every event, so this app's stream stays separable from Grid's- /// and the website's inside the shared project. Grid sends `grid-app`.- static const String category = kIsWeb ? 'harness-web' : 'harness-desktop-v2';-- /// Env var / `--dart-define` names. The URL and key overrides are dev-only so- /// a shipped build always reports to production; [disableEnvKey] is honoured- /// everywhere, because a user who wants to be left alone has to be able to- /// say so in a release build.- static const String urlEnvKey = 'HARNESS_ANALYTICS_URL';- static const String keyEnvKey = 'HARNESS_ANALYTICS_KEY';- static const String disableEnvKey = 'HARNESS_ANALYTICS_DISABLED';-- // `String.fromEnvironment` needs a const literal, so the names above can't be- // used here — keep the two in step by hand.- static const String _urlDefine = String.fromEnvironment(- 'HARNESS_ANALYTICS_URL',- );- static const String _keyDefine = String.fromEnvironment(- 'HARNESS_ANALYTICS_KEY',- );-- static const String _defaultBaseUrl =- 'https://autonomous-analytics-qffztaoryq-uc.a.run.app/api/v1';- static const String _path = 'event_tracking';-- /// Borrowed from Grid until this app has its own — see the class TODO(BE).- /// Keep it byte-for-byte equal to `autonomous-grid-app`'s- /// `AnalyticsConfig._defaultWriteKey`; a copy that drifts sends this app's- /// events to a project nobody is reading.- static const String _defaultWriteKey = 'tBCs0oLwgFgf1borYn54cjHz4fvWahyV';-- /// The live configuration, from the environment alone.- static AnalyticsConfig resolve() {- final base = (_devOverride(urlEnvKey) ?? _defaultBaseUrl).replaceFirst(- RegExp(r'/+$'),- '',- );- final key = _devOverride(keyEnvKey) ?? _defaultWriteKey;- return AnalyticsConfig(- endpoint: Uri.parse('$base/$_path'),- writeKey: key,- offReason: _offReason(key),- );- }-- static String? _offReason(String key) {- if (key.isEmpty) {- return 'This build carries no analytics key '- '(set $keyEnvKey to turn the stream on).';- }- if (_muted) return '$disableEnvKey is set in this environment.';- if (_underTest) return 'Running under flutter test.';- return null;- }-- /// True when `HARNESS_ANALYTICS_DISABLED` is set to anything truthy.- static bool get _muted {- if (const bool.fromEnvironment('HARNESS_ANALYTICS_DISABLED')) return true;- final value = RuntimePlatform.environment[disableEnvKey]?.toLowerCase().trim();- return value == '1' || value == 'true' || value == 'yes';- }-- /// Tests here build a real `AppNotifier` and drive real controllers, so one- /// that happens to track an event must not open a socket or touch- /// `~/.harness` to do it. See [kUnderTest] for the whole of why.- static bool get _underTest => kUnderTest;-- /// [key]'s override — `--dart-define` first, then the process env — ignored- /// in release so a shipped build can only ever report to production.- static String? _devOverride(String key) {- if (kReleaseMode) return null;- final define = switch (key) {- urlEnvKey => _urlDefine,- keyEnvKey => _keyDefine,- _ => '',- };- if (define.isNotEmpty) return define;- final value = RuntimePlatform.environment[key];- return (value != null && value.isNotEmpty) ? value : null;- }-}--/// The limits the queue and the payload are held to.-///-/// [sessionIdle] matches the website's and Grid's 15 minutes on purpose: a-/// "visit" has to mean the same span everywhere or the streams cannot be-/// compared. The rest are a desktop app's own — one quit offline and reopened-/// on a plane needs a bounded queue and a backoff, which a page that unloads-/// after a few minutes never did.-class AnalyticsLimits {- const AnalyticsLimits._();-- /// Events kept while the server is unreachable. Past this the oldest go —- /// a full queue is a signal, and the newest events describe it best.- static const int queueCap = 500;-- /// Params per event, and the length of any one string value. The backend- /// truncates and drops on its own; doing it here keeps what we send and what- /// lands identical, so a value read back in analysis is the value we meant.- static const int paramsMaxKeys = 40;- static const int paramsMaxStringLength = 500;-- /// How long a visit survives without an event before a new one starts.- static const Duration sessionIdle = Duration(minutes: 15);-- static const Duration requestTimeout = Duration(seconds: 10);-- /// First retry delay, doubled up to [retryDelayMax] while sends keep failing.- static const Duration retryDelay = Duration(seconds: 2);- static const Duration retryDelayMax = Duration(minutes: 2);-- /// How long a quit waits for the queue to drain. A wedged network must never- /// be what keeps the window on screen after the user pressed ⌘Q.- static const Duration closeDeadline = Duration(seconds: 3);-}diff --git a/desktop/lib/analytics/analytics_event.dart b/desktop/lib/analytics/analytics_event.dartdeleted file mode 100644index ad588468a..000000000--- a/desktop/lib/analytics/analytics_event.dart+++ /dev/null@@ -1,200 +0,0 @@-import 'dart:convert';--import 'package:flutter/foundation.dart';--import 'analytics_config.dart';--/// The name rule this app holds itself to: `snake_case`, 3–64 characters.-///-/// Autonomous Analytics accepts anything — the website sends whole sentences-/// (`"Click button add to cart"`) — which is exactly why a rule is worth having-/// here. A stream where the same action is called three things is a stream-/// nobody can query, and the app is the only place that can prevent it.-final RegExp analyticsEventNamePattern = RegExp(r'^[a-z][a-z0-9_]{2,63}$');--/// The machine, the build and the OS an event happened on. Resolved once per-/// launch and attached to every event.-@immutable-class AnalyticsContext {- const AnalyticsContext({- required this.platform,- required this.appVersion,- required this.appBuild,- required this.osVersion,- required this.arch,- required this.locale,- required this.release,- });-- /// `macos`, `windows` or `linux`. The website sends `web` in this field; the- /// app says which desktop it is, because that is the first question asked of- /// a desktop funnel.- final String platform;-- final String appVersion;-- /// The `+N` build behind [appVersion]. Note that this app's `pubspec.yaml`- /// version is a placeholder — the published version comes from the remote GCS- /// manifest — so this field tells builds apart, it does not name a release.- final String appBuild;-- final String osVersion;-- /// `macosArm64`, `macosX64`, … — an Intel Mac and an Apple Silicon one are- /// different products as far as running agents and models locally goes.- final String arch;-- final String locale;-- /// False in a developer build. Sent on every event so analysis can drop the- /// noise our own machines make instead of guessing at it.- final bool release;-- /// Stand-in for a context that could not be read, so an event still goes out- /// with its name and identity rather than being dropped over a version- /// lookup.- static const AnalyticsContext unknown = AnalyticsContext(- platform: '',- appVersion: '',- appBuild: '',- osVersion: '',- arch: '',- locale: '',- release: kReleaseMode,- );-- /// The context as event params. Empty strings are dropped downstream, so a- /// half-resolved context costs the missing fields and nothing else.- Map<String, Object?> asParams() => {- 'app_version': appVersion.isEmpty ? null : appVersion,- 'app_build': appBuild.isEmpty ? null : appBuild,- 'os': platform.isEmpty ? null : platform,- 'os_version': osVersion.isEmpty ? null : osVersion,- 'arch': arch.isEmpty ? null : arch,- 'locale': locale.isEmpty ? null : locale,- 'build': release ? 'release' : 'debug',- };-}--/// Who an event belongs to and which visit it is part of.-@immutable-class AnalyticsIdentity {- const AnalyticsIdentity({- required this.pseudoId,- required this.sessionId,- this.userId,- this.userEmail,- });-- /// The device id — stable for the life of the machine, present whether or not- /// anyone is signed in. See `AnalyticsIdentityStore`.- final String pseudoId;-- /// The visit id, rotated after quiet (`AnalyticsLimits.sessionIdle`).- final String sessionId;-- /// The signed-in account, or null before sign-in. The account id the CLI- /// reports through `api.me()` — stable, and not something a user typed.- final String? userId;-- /// Sent as a param, mirroring the website, so the same person can be found in- /// both streams. Null while signed out.- final String? userEmail;-}--/// One event, as it sits in the queue and goes on the wire.-@immutable-class AnalyticsEvent {- const AnalyticsEvent({- required this.name,- required this.params,- required this.at,- required this.identity,- });-- final String name;- final Map<String, Object?> params;-- /// When the event *happened*, not when it was flushed — a queue that drains- /// after a reconnect must not report an hour of activity as one instant.- final DateTime at;-- final AnalyticsIdentity identity;-}--/// The Autonomous Analytics request body for [event].-///-/// Pure, so the wire format is checked by reading one function rather than by-/// watching a queue. The shape is the web client's: an envelope naming the-/// event and its timestamp, with everything else under `data`, and the params-/// as a `{key, value}` list.-///-/// `user_id` goes in both `data` and the params, as it does on the web — most-/// queries read the params table, and dropping it from there would make the-/// app's events the only ones that cannot be filtered by account.-Map<String, Object?> analyticsPayload(- AnalyticsEvent event,- AnalyticsContext context,-) {- final identity = event.identity;- // Merged as a map, not appended to a list: a later key simply wins, so an- // event that wants to say more about `model` than the context did needs no- // de-duplication pass afterwards (the web has one because it uses a list).- final params = <String, Object?>{- ...context.asParams(),- 'user_id': identity.userId,- 'user_email': identity.userEmail,- ...event.params,- 'category': AnalyticsConfig.category,- };- return {- 'event_name': event.name,- 'event_timestamp': event.at.millisecondsSinceEpoch ~/ 1000,- 'data': {- 'session_id': identity.sessionId,- 'user_pseudo_id': identity.pseudoId,- if (identity.userId != null) 'user_id': identity.userId,- 'platform': context.platform,- 'event_params': analyticsParams(params),- },- };-}--/// [params] as the wire's `{key, value}` list: nulls dropped, nested values-/// JSON-encoded, long strings clipped, and never more than-/// `AnalyticsLimits.paramsMaxKeys` entries.-List<Map<String, Object?>> analyticsParams(Map<String, Object?> params) {- final out = <Map<String, Object?>>[];- for (final entry in params.entries) {- final value = entry.value;- if (value == null) continue;- if (value is String && value.isEmpty) continue;- if (out.length >= AnalyticsLimits.paramsMaxKeys) break;- out.add({'key': entry.key, 'value': analyticsValue(value)});- }- return out;-}--/// One param value the backend can store: a string, a number or a bool.-/// Anything else is JSON-encoded (the website does the same), and anything long-/// is clipped to `AnalyticsLimits.paramsMaxStringLength`.-Object analyticsValue(Object value) {- final encoded = switch (value) {- String() || num() || bool() => value,- _ => _encode(value),- };- if (encoded is! String) return encoded;- return encoded.length > AnalyticsLimits.paramsMaxStringLength- ? encoded.substring(0, AnalyticsLimits.paramsMaxStringLength)- : encoded;-}--/// JSON, or the value's own `toString` when it isn't encodable — a param that-/// cannot be serialised must cost that param, never the event.-String _encode(Object value) {- try {- return jsonEncode(value);- } on Object {- return value.toString();- }-}diff --git a/desktop/lib/analytics/analytics_events.dart b/desktop/lib/analytics/analytics_events.dartdeleted file mode 100644index 4b2e51c33..000000000--- a/desktop/lib/analytics/analytics_events.dart+++ /dev/null@@ -1,124 +0,0 @@-import 'analytics.dart';--/// The events this app sends, one method each.-///-/// An extension rather than a set of loose helpers, so every [Analytics]-/// implementation gets them for free — and so the name and the params of an-/// event are written down **once**. Two call sites that name the same action-/// differently is the failure mode this exists to prevent.-///-/// Adding an event: add a method here, keep the name `snake_case`, and keep the-/// params to product facts — a short code, an option, a count. **Never** a-/// prompt, terminal output, an agent's name, a repository path or a machine-/// hostname. This stream describes what someone did, not what they wrote or-/// what their machines are called; ids are fine, the names people give things-/// are not.-extension AnalyticsEvents on Analytics {- // --- The launch ----------------------------------------------------------- /// The app came up. [signedIn] separates a returning user from someone who- /// is about to meet the login screen.- void appOpened({required bool signedIn}) =>- track('app_opened', params: {'signed_in': signedIn});-- /// The app is quitting, after [open]. Sent on the way out, so it is the last- /// thing the queue drains.- void appClosed({required Duration open}) =>- track('app_closed', params: {'open_seconds': open.inSeconds});-- /// A screen was opened. [screen] is the section's stable name, never its- /// label — labels are rewritten weekly and a renamed label would read as a- /// new screen.- ///- /// [source] is the DOOR that was used, and it is `required` for the reason- /// `new_agent_opened`'s is: a screen with several ways in tells you almost- /// nothing as a bare count.- ///- /// Values: `account_menu` and `shortcut` (a door that OPENED Settings on this- /// pane); `rail` (moved here from another pane, using the settings rail).- void screenView(String screen, {required String source}) =>- track('screen_view', params: {'screen': screen, 'source': source});-- // --- Sign-in -------------------------------------------------------------- /// Sign-in completed.- void signedIn() => track('signed_in');-- /// Sign-in didn't complete. [reason] is a short code — `cancelled`,- /// `failed` — never the error text, which can carry a path or a host name.- void signInFailed(String reason) =>- track('sign_in_failed', params: {'reason': reason});-- /// The user signed out.- void signedOut() => track('signed_out');-- /// First-run provisioning finished. [ready] is false when a required step- /// could not be completed — which says how much of a fresh Mac this app can- /// actually set up on its own, otherwise only visible in a support thread.- void environmentPrepared({required bool ready}) =>- track('environment_prepared', params: {'ready': ready});-- // --- Agents -------------------------------------------------------------- //- // How many people open the New agent dialog, how many of those finish it,- // and how many of THOSE ever send the agent a message. Each step is a- // separate event carrying the same device and user id, so the funnel is- // built by counting distinct people per step.-- /// The New agent dialog was opened. [source] is which door was used —- /// `machine_row` (the `+` on a machine's row), `rail_empty` (the button the- /// empty rail shows), `pane_empty` (the button in the empty centre pane) or- /// `shortcut` (⌘N and the app menu).- ///- /// Sent by `showNewAgentDialog` itself rather than by its callers, so a door- /// added later cannot forget to report itself.- void newAgentOpened({required String source}) =>- track('new_agent_opened', params: {'source': source});-- /// An agent was created from the New agent dialog. [engine] is the engine id- /// and [bypassPermission] whether its own guardrails were switched off, both- /// product facts.- ///- /// The working folder is deliberately absent: it is an absolute path, which- /// this stream never carries.- void agentCreated({- required String engine,- required bool bypassPermission,- String? permissionMode,- }) => track(- 'agent_created',- params: {- 'engine': engine,- 'bypass_permission': bypassPermission,- 'permission_mode': ?permissionMode,- },- );-- /// The first message of a signed-in session — how long it took this person to- /// get from being logged in to actually talking to an agent, whichever agent- /// that turned out to be.- ///- /// **Once per sign-in, not per agent.** Which agent it was is- /// [agentCreated]'s question; this one is about the gap at the top of the- /// funnel, where somebody signs in and then does nothing.- ///- /// [from] says what started the clock, because the two populations behave- /// nothing alike: `sign_in` is a fresh log-in, `launch` is opening the app- /// with a session already on the machine. Averaging them together would hide- /// both.- ///- /// Driven by the CLI's `turn_started`, not by the composer, so a message- /// typed straight into the terminal counts the same as one sent from the box- /// underneath it — which is how most people drive these engines.- ///- /// ⚠️ **No message text, ever**, and no agent, machine or folder either. Who- /// it was and when are already on every event (`user_email`,- /// `event_timestamp`); what this adds is the wait.- void appFirstMessage({- required String from,- required int secondsSinceLogin,- }) => track(- 'app_first_message',- params: {'from': from, 'seconds_since_login': secondsSinceLogin},- );-}diff --git a/desktop/lib/analytics/analytics_identity.dart b/desktop/lib/analytics/analytics_identity.dartdeleted file mode 100644index 9c136c639..000000000--- a/desktop/lib/analytics/analytics_identity.dart+++ /dev/null@@ -1,191 +0,0 @@-import 'dart:convert';-import 'dart:io';-import 'dart:math';--import 'package:flutter/foundation.dart' show kIsWeb;--import '../core/browser_storage.dart';-import '../core/harness_file_store.dart';-import 'analytics_config.dart';--/// The device id and the visit id every event carries, kept in-/// `~/.harness/desktop-app/analytics.json`.-///-/// Two ids, two lifetimes. The **device id** is minted once and never reset —-/// it is what ties a person's first launch to the day they finally ran an-/// agent, across sign-in and sign-out. The **visit id** rotates after-/// `AnalyticsLimits.sessionIdle` of quiet, which is how a session is counted.-///-/// The file also carries the user's own switch: `{"enabled": false}` mutes the-/// app, and is preserved by every write here so turning it off stays off.-///-/// Its own file rather than a key in [HarnessFileStore]'s `state.json`: that-/// store is async, serialised behind a lock and holds credentials, while this-/// is read synchronously on the first event of a launch and is the one piece of-/// app state a user may reasonably want to open and edit by hand.-///-/// Lenient like the other app stores — a missing, corrupt or hand-edited file-/// reads as "no ids yet" rather than throwing, because the alternative is an-/// analytics detail breaking the launch it was meant to measure. Both files are-/// overridable so tests never touch a real Harness home.-class AnalyticsIdentityStore {- AnalyticsIdentityStore({File? file, File? computerIdFile, Random? random})- : _file =- file ??- (kIsWeb- ? null- : File('${HarnessFileStore.defaultDirectoryPath()}/$_name')),- _computerIdFile =- computerIdFile ?? (kIsWeb ? null : File(_defaultComputerIdPath())),- _random = random ?? Random.secure();-- static const String _name = 'analytics.json';-- final File? _file;- final File? _computerIdFile;- final Random _random;-- _StoredIdentity? _state;-- /// How stale the on-disk `last_active_ms` is allowed to get. A write per event- /// would be an fsync per click; the cost of lagging is that a restart after a- /// long quiet spell may start a new visit up to a minute early, which is- /// noise beside a 15-minute window.- static const Duration _persistEvery = Duration(minutes: 1);-- /// `~/.harness/computer-id` — the machine identity this app already shares- /// with the CLI (`LocalCliDiscovery.defaultComputerIdPath`). Resolved the same- /// way rather than imported, so an analytics detail cannot drag the WS layer- /// into every test that builds this store.- static String _defaultComputerIdPath() =>- '${Directory(HarnessFileStore.defaultDirectoryPath()).parent.path}'- '/computer-id';-- /// Whether the user turned tracking off in- /// `~/.harness/desktop-app/analytics.json`.- bool get optedOut => _load().optedOut;-- /// The ids as they stand, without starting a visit or moving the clock.- /// `sessionId` is empty until the first event of a launch has been tracked.- ({String pseudoId, String sessionId}) peek() {- final state = _load();- return (pseudoId: state.pseudoId, sessionId: state.sessionId);- }-- /// The ids for an event happening at [now], rotating the visit after a quiet- /// spell and persisting sparingly (see [_persistEvery]).- ({String pseudoId, String sessionId}) touch(DateTime now) {- final state = _load();- final at = now.millisecondsSinceEpoch;- final expired =- state.sessionId.isEmpty ||- at - state.lastActive > AnalyticsLimits.sessionIdle.inMilliseconds;- final next = _StoredIdentity(- pseudoId: state.pseudoId,- sessionId: expired ? _uuidV4(_random) : state.sessionId,- lastActive: at,- optedOut: state.optedOut,- );- _state = next;- if (expired || at - state.lastActive >= _persistEvery.inMilliseconds) {- _persist(next);- }- return (pseudoId: next.pseudoId, sessionId: next.sessionId);- }-- _StoredIdentity _load() {- final cached = _state;- if (cached != null) return cached;- var json = const <String, Object?>{};- try {- final raw = kIsWeb- ? readBrowserPreference('analytics')- : (_file!.existsSync() ? _file.readAsStringSync() : null);- if (raw != null) {- final decoded = jsonDecode(raw);- if (decoded is Map) json = decoded.cast<String, Object?>();- }- } on Object {- // Corrupt or hand-edited: start over rather than fail the launch.- }- final stored = (json['user_pseudo_id'] as String?)?.trim();- final state = _StoredIdentity(- pseudoId: stored != null && stored.isNotEmpty ? stored : _newPseudoId(),- sessionId: (json['session_id'] as String?) ?? '',- lastActive: (json['last_active_ms'] as num?)?.toInt() ?? 0,- optedOut: json['enabled'] == false,- );- _state = state;- return state;- }-- /// A fresh device id: this computer's Harness id when it has one, else a new- /// UUID.- ///- /// Borrowing `computer-id` rather than minting a second one is what lets an- /// event be lined up with the machine the backend knows about. It is copied- /// here on first use and then never re-read, so a later re-registration that- /// rewrites that file cannot silently turn this machine into a second- /// visitor.- String _newPseudoId() => _computerId() ?? _uuidV4(_random);-- String? _computerId() {- try {- if (_computerIdFile == null || !_computerIdFile.existsSync()) return null;- final id = _computerIdFile.readAsStringSync().trim();- return id.isEmpty ? null : id;- } on Object {- return null;- }- }-- /// Writes the ids back, `enabled` included so a user's opt-out survives.- void _persist(_StoredIdentity state) {- try {- final contents = const JsonEncoder.withIndent(' ').convert({- 'user_pseudo_id': state.pseudoId,- 'session_id': state.sessionId,- 'last_active_ms': state.lastActive,- 'enabled': !state.optedOut,- });- if (kIsWeb) {- writeBrowserPreference('analytics', contents);- } else {- _file!.parent.createSync(recursive: true);- _file.writeAsStringSync(contents, flush: true);- }- } on Object {- // A read-only home or a full disk costs id stability across restarts,- // not the event in hand.- }- }-}--/// What `analytics.json` holds, as one immutable value.-class _StoredIdentity {- const _StoredIdentity({- required this.pseudoId,- required this.sessionId,- required this.lastActive,- required this.optedOut,- });-- final String pseudoId;- final String sessionId;-- /// Epoch ms of the last tracked event.- final int lastActive;- final bool optedOut;-}--/// A random v4 UUID — the id format both this stream and the CLI already use.-/// `Random.secure` so two machines starting in the same millisecond cannot be-/// handed the same device id.-String _uuidV4(Random random) {- final bytes = List<int>.generate(16, (_) => random.nextInt(256));- bytes[6] = (bytes[6] & 0x0f) | 0x40;- bytes[8] = (bytes[8] & 0x3f) | 0x80;- final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();- return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-'- '${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}';-}diff --git a/desktop/lib/analytics/analytics_lifecycle.dart b/desktop/lib/analytics/analytics_lifecycle.dartdeleted file mode 100644index 3a1f6a3f7..000000000--- a/desktop/lib/analytics/analytics_lifecycle.dart+++ /dev/null@@ -1,70 +0,0 @@-import 'dart:ui' show AppExitResponse;--import 'package:flutter/widgets.dart';--import '../stats/harness_stats.dart';-import 'analytics.dart';--/// Closes the launch out: `app_closed`, then a time-boxed drain of whatever is-/// still queued. Renders [child] unchanged.-///-/// Only `didRequestAppExit` is hooked, which covers ⌘Q, the app menu's Quit and-/// an OS log-out. Grid also intercepts the window's close button, but that-/// needs `windowManager.setPreventClose(true)` and a matching `destroy()` call-/// — and a bug on that path leaves a window the user cannot close. A missing-/// `app_closed` is worth less than that risk, so this app takes the exit hook-/// alone; `app_opened` is unaffected either way.-///-/// The matching `app_opened` is NOT here. It is sent by `AppNotifier` when-/// bootstrap resolves, because `signed_in` is not known until the CLI has been-/// asked, and a first-frame event would report every launch as signed out.-class AnalyticsLifecycle extends StatefulWidget {- const AnalyticsLifecycle({super.key, required this.child});-- final Widget child;-- @override- State<AnalyticsLifecycle> createState() => _AnalyticsLifecycleState();-}--class _AnalyticsLifecycleState extends State<AnalyticsLifecycle>- with WidgetsBindingObserver {- /// When this launch started, so the quit event can say how long the app was- /// open.- final DateTime _openedAt = DateTime.now();-- /// Guards against a quit that somehow asks twice.- bool _closed = false;-- @override- void initState() {- super.initState();- WidgetsBinding.instance.addObserver(this);- }-- @override- void dispose() {- WidgetsBinding.instance.removeObserver(this);- super.dispose();- }-- @override- Future<AppExitResponse> didRequestAppExit() async {- if (!_closed) {- _closed = true;- analytics.appClosed(open: DateTime.now().difference(_openedAt));- // Before the drain below, and awaited: this is a local file write that- // finishes in milliseconds, and it is the ONLY place a turn still running- // at quit gets its time counted — the debounce timer is cancelled by the- // process exiting, not fired by it.- await harnessStats.flush();- // Time-boxed inside `close` itself — a wedged network must never be what- // keeps the window on screen after the user pressed ⌘Q.- await analytics.close();- }- return AppExitResponse.exit;- }-- @override- Widget build(BuildContext context) => widget.child;-}diff --git a/desktop/lib/analytics/analytics_log.dart b/desktop/lib/analytics/analytics_log.dartdeleted file mode 100644index 15a3ef6f7..000000000--- a/desktop/lib/analytics/analytics_log.dart+++ /dev/null@@ -1,216 +0,0 @@-import 'dart:async';-import 'dart:collection';-import 'dart:convert';--import 'package:flutter/foundation.dart';--/// Where one tracked event got to.-enum AnalyticsEventStatus {- /// In the queue: never sent, or sent and waiting on a retry.- queued,-- /// The server took it.- sent,-- /// The server refused it (a 4xx that isn't 408/429) — our instrumentation is- /// wrong, not the network.- refused,-- /// Never reached the wire: an invalid name, a full queue, or a build whose- /// stream is muted.- dropped,-}--/// One tracked event as Settings ▸ Tracking shows it: what was tracked, what-/// went over the wire, and how it ended.-///-/// Mutable in place, like [LogEntry] and unlike Grid's immutable-/// `AnalyticsLogEntry`: Grid rebuilds through `copyWith` because Riverpod-/// compares state objects, while this buffer is a [ChangeNotifier] and an event-/// that is still retrying collects its attempts on the entry it already has.-class AnalyticsLogEntry {- AnalyticsLogEntry({- required this.id,- required this.name,- required this.params,- required this.queuedAt,- });-- /// Monotonic within a session — the handle the queue settles a row by.- final int id;-- final String name;-- /// The params as the call site passed them, before the context and the- /// identity are merged in. [payload] is what actually went out.- final Map<String, Object?> params;-- final DateTime queuedAt;-- AnalyticsEventStatus status = AnalyticsEventStatus.queued;-- /// How many times this event has been put on the wire. Two or more means the- /// endpoint failed and the queue retried, which is the thing this screen- /// exists to make visible.- int attempts = 0;-- /// The exact JSON body sent, re-indented, or null before the first attempt.- String? payload;-- /// Why it ended the way it did, when the status alone doesn't say.- String? note;-- DateTime? settledAt;-- /// How long from being tracked to being settled, or null while it waits.- Duration? get took => settledAt?.difference(queuedAt);-}--/// The recorder the analytics queue reports to.-///-/// An interface so the queue stays free of the screen, and so a release build —-/// which has no Tracking screen — pays nothing for it. The same seam-/// `AnalyticsClient` gives the transport.-abstract interface class AnalyticsLog {- /// Records an event entering the queue; returns its id for the calls below.- int queued(String name, Map<String, Object?> params, DateTime at);-- /// Records that [payload] has just gone on the wire for entry [id]. Called- /// once per attempt, so the count reads as retries.- ///- /// Takes the payload as the map the queue already built rather than as a- /// string: encoding it is the recorder's business, and a build with nothing- /// recording must not pay for a `jsonEncode` per event.- void attempted(int id, Map<String, Object?> payload);-- /// Records how entry [id] ended.- void settled(int id, AnalyticsEventStatus status, {String? note});-}--/// Records nothing — what a release build gets, so the queue can run with no-/// screen watching.-class NoopAnalyticsLog implements AnalyticsLog {- const NoopAnalyticsLog();-- @override- int queued(String name, Map<String, Object?> params, DateTime at) => 0;-- @override- void attempted(int id, Map<String, Object?> payload) {}-- @override- void settled(int id, AnalyticsEventStatus status, {String? note}) {}-}--/// The events this session tracked, newest first — a bounded ring, fed by-/// `QueuedAnalytics` and read by Settings ▸ Tracking.-///-/// In memory only, and deliberately: this is a window onto a queue that is-/// itself in memory, and a stream that measures the app must not become a-/// second thing the app writes to disk on every click. It is the one place the-/// question analytics always raises can be answered — *did that event actually-/// leave, and what was in it?* — because an event that was never sent, sent-/// with a missing field, or refused by the server looks exactly like an event-/// that landed: the app is silent either way, by design.-class AnalyticsLogStream extends ChangeNotifier implements AnalyticsLog {- AnalyticsLogStream({this.maxEntries = 200});-- /// How many events the buffer keeps. Smaller than [LogStream]'s 500: one row- /// here is one deliberate product event, not a socket frame, and a session- /// that has tracked two hundred of them has long since answered the question- /// this screen was opened with.- final int maxEntries;-- final List<AnalyticsLogEntry> _entries = [];- int _seq = 0;- bool _notifyScheduled = false;-- /// Newest first — the order the Tracking list reads in.- late final UnmodifiableListView<AnalyticsLogEntry> entries =- UnmodifiableListView(_entries);-- @override- int queued(String name, Map<String, Object?> params, DateTime at) {- final id = ++_seq;- _entries.insert(- 0,- AnalyticsLogEntry(- id: id,- name: name,- // Copied, so a caller that reuses its map cannot rewrite history here.- params: Map<String, Object?>.unmodifiable(params),- queuedAt: at,- ),- );- if (_entries.length > maxEntries) {- _entries.removeRange(maxEntries, _entries.length);- }- _scheduleNotify();- return id;- }-- @override- void attempted(int id, Map<String, Object?> payload) {- final entry = _entryFor(id);- if (entry == null) return;- entry.attempts += 1;- entry.payload = _pretty(payload);- _scheduleNotify();- }-- @override- void settled(int id, AnalyticsEventStatus status, {String? note}) {- final entry = _entryFor(id);- if (entry == null) return;- entry.status = status;- entry.note = note;- entry.settledAt = DateTime.now();- _scheduleNotify();- }-- void clear() {- if (_entries.isEmpty) return;- _entries.clear();- _scheduleNotify();- }-- /// An event settles near where it was queued, and the newest rows are at the- /// front — so this walks a handful of entries, not the buffer. Null once a- /// row has been pushed out by [maxEntries] or dropped by [clear], which the- /// callers treat as "nothing left to update" rather than as an error.- AnalyticsLogEntry? _entryFor(int id) {- for (final entry in _entries) {- if (entry.id == id) return entry;- }- return null;- }-- /// One notification per microtask, however many rows changed in it — the- /// same rhythm [LogStream] keeps, for the same reason: a queue draining after- /// a reconnect settles a run of events in one pass.- void _scheduleNotify() {- if (_notifyScheduled) return;- _notifyScheduled = true;- scheduleMicrotask(() {- _notifyScheduled = false;- notifyListeners();- });- }-- /// The body as it went out, re-indented so the dialog can be read.- ///- /// A payload that will not encode costs its own readability and nothing else- /// — this is a debug view of an event that has *already been sent*, and- /// throwing here would take the row with it.- static String _pretty(Map<String, Object?> payload) {- try {- return const JsonEncoder.withIndent(' ').convert(payload);- } on Object {- return payload.toString();- }- }-}--/// This session's tracked events. Fed only where the Tracking screen exists —-/// see `analyticsRecorder` in `analytics_sink.dart`.-final AnalyticsLogStream analyticsLog = AnalyticsLogStream();diff --git a/desktop/lib/analytics/analytics_service.dart b/desktop/lib/analytics/analytics_service.dartdeleted file mode 100644index 2ad50bd19..000000000--- a/desktop/lib/analytics/analytics_service.dart+++ /dev/null@@ -1,220 +0,0 @@-import 'dart:async';-import 'dart:collection';--import 'package:flutter/foundation.dart';--import 'analytics.dart';-import 'analytics_client.dart';-import 'analytics_config.dart';-import 'analytics_event.dart';-import 'analytics_identity.dart';-import 'analytics_log.dart';--/// Who is signed in, asked fresh at track time — a session that starts signed-/// out and ends signed in must not report the whole visit as anonymous.-typedef AnalyticsUserLookup = ({String? id, String? email}) Function();--/// [Analytics] that queues in memory and sends serially, with retry.-///-/// Autonomous Analytics takes one event per request, so this is a queue with a-/// worker rather than a batcher. The order of the three failure paths is the-/// point: a **transport** failure keeps the event and backs off, a **refusal**-/// drops it (resending changes nothing), and a queue that grows past-/// `AnalyticsLimits.queueCap` drops its oldest — the newest events are the ones-/// that describe what is happening now.-///-/// Not persisted across launches: a machine quit while offline loses what was-/// still queued. That is a deliberate limit, not an oversight — the alternative-/// is a spool file that outlives an uninstall.-///-/// Ported from Grid, [recorder] included: Settings ▸ Tracking is this app's-/// version of Grid's Tracking tab, and it is fed from here rather than from a-/// second stream, so a row on that screen is an event this queue really held.-class QueuedAnalytics implements Analytics {- QueuedAnalytics({- required this.client,- required this.identityStore,- required this.contextFuture,- required this.userLookup,- this.recorder = const NoopAnalyticsLog(),- this.clock = DateTime.now,- });-- /// The collaborators, public because they arrive through the constructor and- /// a test that swaps one has no reason to reach past the door it came in by.- /// Named apart from the locals they produce (`context`, the account) so a- /// method body cannot quietly shadow one of them.- final AnalyticsClient client;- final AnalyticsIdentityStore identityStore;- final Future<AnalyticsContext> contextFuture;- final AnalyticsUserLookup userLookup;-- /// Where the Tracking screen reads this queue from. A [NoopAnalyticsLog] in- /// a release build, so nothing is retained for a screen that is not there.- final AnalyticsLog recorder;-- final DateTime Function() clock;-- /// Each queued event beside the id of its row on the Tracking screen, so the- /// row can be settled without the wire model carrying a debug field.- final Queue<({AnalyticsEvent event, int logId})> _queue =- Queue<({AnalyticsEvent event, int logId})>();-- AnalyticsContext? _resolvedContext;- Future<void>? _draining;- Timer? _retryTimer;- Duration _retryDelay = AnalyticsLimits.retryDelay;- bool _warnedFull = false;- bool _closed = false;-- /// How many events are waiting to go out. Test seam, and the one honest- /// answer to "did that call actually queue anything".- @visibleForTesting- int get pending => _queue.length;-- @override- void track(String name, {Map<String, Object?> params = const {}}) {- if (_closed) return;- final now = clock();- if (!analyticsEventNamePattern.hasMatch(name)) {- const reason = 'names must be snake_case, 3-64 characters';- // Recorded before it is refused, so the Tracking screen shows the mistake- // rather than nothing at all — an event that never lands is exactly what- // somebody would open that screen to explain.- recorder.settled(- recorder.queued(name, params, now),- AnalyticsEventStatus.dropped,- note: reason,- );- debugPrint('analytics: ignored event "$name" — $reason');- return;- }- try {- final ids = identityStore.touch(now);- final account = userLookup();- _queue.add((- event: AnalyticsEvent(- name: name,- params: params,- at: now,- identity: AnalyticsIdentity(- pseudoId: ids.pseudoId,- sessionId: ids.sessionId,- userId: account.id,- userEmail: account.email,- ),- ),- logId: recorder.queued(name, params, now),- ));- _trim();- unawaited(_pump());- } on Object catch (error) {- debugPrint('analytics: dropped event "$name" — $error');- }- }-- @override- Future<void> flush() {- _cancelRetry();- return _pump();- }-- @override- Future<void> close() async {- if (_closed) return;- _cancelRetry();- await _pump().timeout(AnalyticsLimits.closeDeadline, onTimeout: () {});- _closed = true;- client.dispose();- }-- /// Drops the oldest events once the queue is over its cap, warning once per- /// outage so a plane ride doesn't fill the log with the same line.- void _trim() {- if (_queue.length <= AnalyticsLimits.queueCap) return;- while (_queue.length > AnalyticsLimits.queueCap) {- recorder.settled(- _queue.removeFirst().logId,- AnalyticsEventStatus.dropped,- note: 'the queue was full',- );- }- if (_warnedFull) return;- _warnedFull = true;- debugPrint(- 'analytics: event queue full (${AnalyticsLimits.queueCap}) — dropping '- 'the oldest; the endpoint has been unreachable for a while',- );- }-- /// One drain at a time: concurrent callers share the in-flight future rather- /// than starting a second worker on the same queue.- Future<void> _pump() {- if (_closed || _queue.isEmpty) return Future.value();- return _draining ??= _drain().whenComplete(() => _draining = null);- }-- Future<void> _drain() async {- final context = _resolvedContext ??= await contextFuture.catchError(- (Object _) => AnalyticsContext.unknown,- );- while (_queue.isNotEmpty && !_closed) {- final queued = _queue.first;- final event = queued.event;- final AnalyticsSendResult result;- try {- final payload = analyticsPayload(event, context);- recorder.attempted(queued.logId, payload);- result = await client.send(payload);- } on Object catch (error) {- // The client's contract says it never throws; if it ever does, the- // queue must not be left spinning on the same event forever.- _queue.removeFirst();- recorder.settled(- queued.logId,- AnalyticsEventStatus.dropped,- note: '$error',- );- debugPrint('analytics: send failed for "${event.name}" — $error');- continue;- }- switch (result) {- case AnalyticsSendResult.sent:- _queue.removeFirst();- recorder.settled(queued.logId, AnalyticsEventStatus.sent);- _retryDelay = AnalyticsLimits.retryDelay;- _warnedFull = false;- case AnalyticsSendResult.rejected:- _queue.removeFirst();- recorder.settled(- queued.logId,- AnalyticsEventStatus.refused,- note: 'the server refused it',- );- debugPrint(- 'analytics: server refused "${event.name}" — the event was dropped',- );- case AnalyticsSendResult.retry:- _scheduleRetry();- return;- }- }- }-- void _scheduleRetry() {- if (_retryTimer != null || _closed) return;- _retryTimer = Timer(_retryDelay, () {- _retryTimer = null;- unawaited(_pump());- });- final doubled = _retryDelay * 2;- _retryDelay = doubled > AnalyticsLimits.retryDelayMax- ? AnalyticsLimits.retryDelayMax- : doubled;- }-- void _cancelRetry() {- _retryTimer?.cancel();- _retryTimer = null;- }-}diff --git a/desktop/lib/analytics/analytics_sink.dart b/desktop/lib/analytics/analytics_sink.dartdeleted file mode 100644index b9442c040..000000000--- a/desktop/lib/analytics/analytics_sink.dart+++ /dev/null@@ -1,207 +0,0 @@-import 'dart:async';--import 'package:flutter/foundation.dart';-import 'package:package_info_plus/package_info_plus.dart';--import '../core/runtime_architecture.dart';-import '../core/runtime_platform.dart';-import '../logging/debug_surface.dart';-import 'analytics.dart';-import 'analytics_client.dart';-import 'analytics_config.dart';-import 'analytics_event.dart';-import 'analytics_identity.dart';-import 'analytics_log.dart';-import 'analytics_service.dart';--/// The app's one analytics sink.-///-/// A lazily-built singleton rather than a Riverpod provider, for the same-/// reason `terminalFontStore` is: the call sites have no-/// common ancestor short of `MaterialApp` — `main`, `AppNotifier`, a settings-/// pane, a menu item inside a pane header — and most of them are plain widgets-/// that were handed a notifier, not a `Ref`.-///-/// [NoopAnalytics] whenever tracking is off — no key in this build, the-/// environment muted it, the code is under `flutter test`, or the user opted-/// out in `~/.harness/desktop-app/analytics.json` — so a muted app and a test-/// run open no sockets at all rather than queueing into a void.-Analytics get analytics => _analytics ??= _build();--Analytics? _analytics;--/// Replaces the sink, for tests. Returns what was there, so a test can put it-/// back; passing null re-arms the lazy build.-@visibleForTesting-Analytics? setAnalyticsForTest(Analytics? value) {- final previous = _analytics;- _analytics = value;- return previous;-}--Analytics _build() {- // The environment is asked first, and on purpose: under `flutter test` this- // returns before anything reads `~/.harness`, so a widget test that happens- // to track an event touches neither the network nor a real Harness home.- final config = AnalyticsConfig.resolve();- if (config.offReason case final reason?) return _muted(reason);- final identity = AnalyticsIdentityStore();- if (identity.optedOut) return _muted(kAnalyticsOptedOutReason);- return QueuedAnalytics(- client: HttpAnalyticsClient(config),- identityStore: identity,- contextFuture: resolveAnalyticsContext(),- userLookup: () => analyticsAccount.current,- recorder: analyticsRecorder,- );-}--/// A muted sink that still shows its work where there is a screen to show it-/// on, and a plain [NoopAnalytics] where there is not.-///-/// A build can be muted for four reasons — no key, `HARNESS_ANALYTICS_DISABLED`,-/// `flutter test`, or the user's own opt-out (see [AnalyticsConfig]) — and a-/// Tracking screen that were permanently empty for any of them is the exact-/// trap that screen exists to spring. Every event still lands in the list,-/// settled as `dropped` with [reason], which turns "nothing is arriving" into a-/// sentence.-///-/// Nothing recorded here leaves the machine: the buffer is in memory, and a-/// build with no [kDebugSurfaceEnabled] keeps none of it. That is what makes it-/// right to record even for a user who opted out — their choice is about what-/// we *send*, and this sends nothing.-Analytics _muted(String reason) => kDebugSurfaceEnabled- ? MutedAnalytics(analyticsLog, reason)- : const NoopAnalytics();--/// Where the queue reports its rows: this session's buffer where the Tracking-/// screen exists, nothing at all where it does not.-AnalyticsLog get analyticsRecorder =>- kDebugSurfaceEnabled ? analyticsLog : const NoopAnalyticsLog();--/// Why a sink is muted when the user turned it off by hand.-const String kAnalyticsOptedOutReason =- 'Tracking is switched off in ~/.harness/desktop-app/analytics.json.';--/// [Analytics] that records what was tracked and sends none of it.-///-/// Not a subclass of [QueuedAnalytics] with the transport stubbed out: this-/// must not touch [AnalyticsIdentityStore], so a muted build reads no Harness-/// home and mints no ids for a stream that will never carry them.-class MutedAnalytics implements Analytics {- MutedAnalytics(this.recorder, this.reason, {this.clock = DateTime.now});-- final AnalyticsLog recorder;-- /// The sentence the Tracking screen puts on every row, and the one its header- /// card leads with.- final String reason;-- final DateTime Function() clock;-- @override- void track(String name, {Map<String, Object?> params = const {}}) {- // Settled the instant it is queued: there is no wire and no retry, so a row- // that sat at "Waiting" would be describing a queue that does not exist.- recorder.settled(- recorder.queued(name, params, clock()),- AnalyticsEventStatus.dropped,- note: reason,- );- }-- @override- Future<void> flush() async {}-- @override- Future<void> close() async {}-}--/// What the Tracking screen's header card reports: where events go, whether-/// they are going at all, and the two ids they are filed under.-@immutable-class AnalyticsStreamStatus {- const AnalyticsStreamStatus({- required this.endpoint,- required this.offReason,- required this.deviceId,- required this.sessionId,- });-- final Uri endpoint;-- /// Why nothing is being sent, or null when the stream is live.- final String? offReason;-- final String deviceId;-- /// Empty until the first event of a launch has been tracked.- final String sessionId;-- bool get enabled => offReason == null;-}--/// Reads the live configuration and the ids on disk.-///-/// Injected into the Tracking screen the way `probeDebugEnvironment` is into-/// Settings ▸ Debug, and for the same reason: this reads a real `~/.harness`,-/// which a test must not.-///-/// The opt-out is checked here as well as in [_build] — a card that said-/// "Reporting" over a stream the user switched off would be the dishonest-/// label this screen exists to prevent.-AnalyticsStreamStatus probeAnalyticsStatus() {- final config = AnalyticsConfig.resolve();- final store = AnalyticsIdentityStore();- final ids = store.peek();- final optedOut = store.optedOut ? kAnalyticsOptedOutReason : null;- return AnalyticsStreamStatus(- endpoint: config.endpoint,- offReason: config.offReason ?? optedOut,- deviceId: ids.pseudoId,- sessionId: ids.sessionId,- );-}--/// Who events are filed under.-///-/// `AppNotifier` writes it when sign-in resolves and clears it on sign-out; the-/// queue reads it fresh per event, so a visit that begins signed out and ends-/// signed in is not reported as anonymous throughout.-final AnalyticsAccount analyticsAccount = AnalyticsAccount();--/// The signed-in account, as the wire wants it. Mutable and global on purpose —-/// see [analyticsAccount].-class AnalyticsAccount {- ({String? id, String? email}) current = (id: null, email: null);-- void set({String? id, String? email}) => current = (id: id, email: email);-- void clear() => current = (id: null, email: null);-}--/// The machine and build an event happened on, resolved once per launch.-///-/// Never fails: a version lookup that throws costs those fields, not the-/// stream. The queue awaits this once, before its first send, so the first-/// event of a launch already carries the version rather than racing it.-Future<AnalyticsContext> resolveAnalyticsContext() async {- var version = '';- var build = '';- try {- final info = await PackageInfo.fromPlatform();- version = info.version;- build = info.buildNumber;- } on Object {- // A bundle we can't read is worth an anonymous version, not a lost event.- }- return AnalyticsContext(- platform: RuntimePlatform.operatingSystem,- appVersion: version,- appBuild: build,- osVersion: RuntimePlatform.operatingSystemVersion,- arch: runtimeAbi,- locale: RuntimePlatform.localeName,- release: kReleaseMode,- );-}diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dartindex ce22c4e06..b4177fa3f 100644--- a/desktop/lib/app_shell.dart+++ b/desktop/lib/app_shell.dart@@ -10,11 +10,11 @@ import 'package:flutter/services.dart';import 'package:flutter_riverpod/flutter_riverpod.dart';import 'package:flutter_web_plugins/url_strategy.dart';-import 'analytics/analytics_lifecycle.dart';import 'core/crash_log.dart';import 'core/desktop_window.dart';import 'screens/login_screen.dart';import 'state/app_state.dart';+import 'stats/stats_lifecycle.dart';import 'viewer/viewer_services.dart';import 'ws/terminal_transport_plugin.dart';import 'shared/theme/app_theme.dart' as grid;@@ -138,7 +138,7 @@ class HarnessApp extends StatelessWidget {),),),- home: AnalyticsLifecycle(+ home: StatsLifecycle(child: RootShell(authenticatedScreen: authenticatedScreen),),);diff --git a/desktop/lib/logging/app_log.dart b/desktop/lib/logging/app_log.dartindex bf5f5d650..d619003be 100644--- a/desktop/lib/logging/app_log.dart+++ b/desktop/lib/logging/app_log.dart@@ -9,8 +9,7 @@ enum AppLogLevel { debug, info, warn, error }////// Ported from Grid, with one change: Riverpod out, a singleton in. The call/// sites here are `main`, `AppNotifier`, `WsConn` and the CLI runner, and most-/// were never handed a `Ref` — the same reasoning that made `analytics` a-/// singleton (see `analytics/analytics.dart`).+/// were never handed a `Ref`.////// **Distinct from [CrashLog], and both are kept.** `CrashLog` answers "what/// threw", in one file, forever, with a full stack; this answers "what was the@@ -132,7 +131,7 @@ class FileAppLog implements AppLog {}/// No-op [AppLog]. The default, so a `flutter test` run never writes into a real-/// `~/.harness` — the same rule analytics follows, and for the same reason.+/// `~/.harness`.class NoopAppLog implements AppLog {const NoopAppLog();diff --git a/desktop/lib/logging/debug_surface.dart b/desktop/lib/logging/debug_surface.dartindex 08095bb8b..57932905d 100644--- a/desktop/lib/logging/debug_surface.dart+++ b/desktop/lib/logging/debug_surface.dart@@ -1,8 +1,7 @@import 'package:flutter/foundation.dart';-/// Whether this build shows its developer surfaces: Settings ▸ Debug and its-/// ⌘D shortcut, Settings ▸ Tracking, and the two in-memory buffers that feed-/// them (`logStream`, `analyticsLog`).+/// Whether this build shows its developer surfaces: Settings ▸ Debug, its ⌘D+/// shortcut, and the in-memory buffer that feeds it (`logStream`).////// A debug build has it; a release build does not. The log *files* are written/// either way — a shipped app that has no stderr anyone reads is exactly thediff --git a/desktop/lib/logging/install.dart b/desktop/lib/logging/install.dartindex 4724c633d..002a1d7c5 100644--- a/desktop/lib/logging/install.dart+++ b/desktop/lib/logging/install.dart@@ -17,8 +17,7 @@ const String kCliLogBase = 'cli';////// Called once from `main()`. Nothing else calls it, which is what keeps the/// suite honest: both sinks default to their no-op, so `flutter test` cannot-/// write into a real Harness home no matter which code path it exercises — the-/// same rule analytics follows.+/// write into a real Harness home no matter which code path it exercises.////// Deliberately not `async`: the first lines this app writes are the ones about/// starting up, and awaiting a directory probe here would lose them.diff --git a/desktop/lib/logging/log_stream.dart b/desktop/lib/logging/log_stream.dartindex 8b866d91d..2b7c76fc9 100644--- a/desktop/lib/logging/log_stream.dart+++ b/desktop/lib/logging/log_stream.dart@@ -96,7 +96,7 @@ class LogCommand {/// most recent entries, newest first.////// Fed by [StreamAppLog]/[StreamCliLog], read by Settings ▸ Debug. A singleton-/// like `appLog` and `analytics`, and for the same reason: the things that+/// like `appLog`, and for the same reason: the things that/// write to it — the socket, the CLI runners, the HTTP clients — hold no `Ref`/// and no notifier between them.class LogStream extends ChangeNotifier {diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 067b04cfa..afa1121fa 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -14,7 +14,6 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:xterm/xterm.dart' show TerminalTheme;import '../core/runtime_platform.dart';-import '../analytics/analytics.dart';import '../api/api_client.dart';import '../core/desktop_window.dart';import '../core/harness_file_store.dart';@@ -2733,7 +2732,6 @@ class _SwarmScreenState extends State<SwarmScreen> {}if (_search != null) _closeSearch(restoreFocus: false);_closeCommandBar(restoreFocus: false);- analytics.newAgentOpened(source: 'swarm_box');_searchReturnFocus ??= FocusManager.instance.primaryFocus;if (_native) _preparePaneFocus();_canvasFocus.descendantsAreFocusable = false;diff --git a/desktop/lib/settings/sections/tracking_detail_dialog.dart b/desktop/lib/settings/sections/tracking_detail_dialog.dartdeleted file mode 100644index 3caff0639..000000000--- a/desktop/lib/settings/sections/tracking_detail_dialog.dart+++ /dev/null@@ -1,198 +0,0 @@-import 'package:flutter/material.dart';-import 'package:flutter/services.dart';-import 'package:harness/terminal/terminal_text.dart';--import '../../analytics/analytics_log.dart';-import '../../logging/log_file.dart';-import '../../shared/theme/app_theme.dart';-import '../../shared/widgets/app_dialog.dart';-import 'debug_log_tile.dart';-import 'tracking_tile.dart';--/// The exact JSON one tracked event put on the wire, opened by clicking its row.-///-/// The row shows what the *call site* passed; this shows what actually left the-/// app — context, identity and params merged, in the envelope the server reads.-/// That difference is the whole reason this dialog exists: a field the call site-/// set and the payload doesn't carry is a bug you cannot see from the list.-Future<void> showTrackingDetailDialog(- BuildContext context,- AnalyticsLogEntry entry,-) {- return showAppDialog<void>(- context: context,- builder: (context) => _TrackingDetailDialog(entry: entry),- );-}--class _TrackingDetailDialog extends StatelessWidget {- const _TrackingDetailDialog({required this.entry});-- final AnalyticsLogEntry entry;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- return Dialog(- child: ConstrainedBox(- constraints: const BoxConstraints(maxWidth: 720),- // The entry mutates in place as the queue retries and settles it, so a- // panel built once would keep saying "Waiting" long after it landed.- child: ListenableBuilder(- listenable: analyticsLog,- builder: (context, _) => _Body(entry: entry),- ),- ),- );- }-}--class _Body extends StatelessWidget {- const _Body({required this.entry});-- final AnalyticsLogEntry entry;-- @override- Widget build(BuildContext context) {- TerminalFontScope.watch(context);- final payload = entry.payload;- return Column(- mainAxisSize: MainAxisSize.min,- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Padding(- padding: const EdgeInsets.fromLTRB(18, 16, 18, 10),- child: Row(- children: [- TrackingStatusIcon(status: entry.status),- const SizedBox(width: 9),- Expanded(- child: Text(- '${entry.name} · ${trackedOutcome(entry)}',- style: AppType.monoLabel(- fontWeight: AppFont.regular,- color: AppPalette.textSecondary,- ),- ),- ),- ],- ),- ),- Flexible(- child: SingleChildScrollView(- padding: const EdgeInsets.fromLTRB(18, 0, 18, 16),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- _Caption('Outcome'),- _Block(- text: [- trackedStatusLabel(entry.status),- ?entry.note,- ].join(' — '),- danger: entry.status == AnalyticsEventStatus.refused,- ),- const SizedBox(height: 10),- _Caption('Tracked'),- _Block(text: logStamp(entry.queuedAt)),- const SizedBox(height: 10),- // What the call site passed, kept apart from the payload: the- // gap between the two is the bug this dialog is opened to find.- _Caption('Params the call site passed'),- _Block(- text: entry.params.isEmpty- ? 'none'- : trackedParamsSummary(entry.params),- ),- const SizedBox(height: 10),- _Caption(payload == null ? 'Payload' : 'Payload as sent'),- _Block(- text:- payload ??- 'Nothing has gone over the wire for this event yet.',- ),- ],- ),- ),- ),- Container(- width: double.infinity,- padding: const EdgeInsets.fromLTRB(18, 10, 18, 10),- decoration: BoxDecoration(- border: Border(top: BorderSide(color: AppGlass.hair)),- ),- child: Row(- mainAxisAlignment: MainAxisAlignment.end,- children: [- TextButton(- // The payload alone, not the panel: what gets pasted into a- // backend thread is the body the server was handed.- onPressed: payload == null- ? null- : () => Clipboard.setData(ClipboardData(text: payload)),- child: const Text('Copy payload'),- ),- const SizedBox(width: 4),- TextButton(- onPressed: () => Navigator.of(context).pop(),- child: const Text('Close'),- ),- ],- ),- ),- ],- );- }-}--/// A caption over one block of the panel.-class _Caption extends StatelessWidget {- const _Caption(this.text);-- final String text;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- return Padding(- padding: const EdgeInsets.only(bottom: 5),- child: Text(- text,- style: AppType.caption(- fontWeight: AppFont.medium,- color: AppPalette.textFaint,- ),- ),- );- }-}--/// One selectable mono block, recessed against the dialog. The same block-/// `debug_detail_dialog.dart` draws — the two panels are read the same way.-class _Block extends StatelessWidget {- const _Block({required this.text, this.danger = false});-- final String text;- final bool danger;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- return Container(- width: double.infinity,- padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 10),- decoration: BoxDecoration(- color: AppCard.inset,- borderRadius: BorderRadius.circular(AppCard.insetRadius),- ),- child: SelectableText(- text,- style: AppType.monoLabel(- fontWeight: AppFont.regular,- height: 1.45,- color: danger ? debugDangerInk(context) : AppPalette.textPrimary,- ),- ),- );- }-}diff --git a/desktop/lib/settings/sections/tracking_section.dart b/desktop/lib/settings/sections/tracking_section.dartdeleted file mode 100644index 0a141c620..000000000--- a/desktop/lib/settings/sections/tracking_section.dart+++ /dev/null@@ -1,188 +0,0 @@-import 'package:flutter/material.dart';-import 'package:lucide_icons_flutter/lucide_icons.dart';--import '../../analytics/analytics_log.dart';-import '../../analytics/analytics_sink.dart';-import '../../shared/theme/app_theme.dart';-import '../../shared/widgets/empty_state.dart';-import '../../shared/widgets/section_scaffold.dart';-import '../../shared/widgets/toolbar_pill.dart';-import 'debug_filter_bar.dart';-import 'debug_toolbar.dart';-import 'tracking_stream_card.dart';-import 'tracking_tile.dart';--/// The lens the list is filtered to. Waiting and Failed are separate: an event-/// still queued is the network's problem, a refused one is ours.-enum _EventFilter { all, sent, waiting, failed }--extension on _EventFilter {- String get label => switch (this) {- _EventFilter.all => 'All',- _EventFilter.sent => 'Sent',- _EventFilter.waiting => 'Waiting',- _EventFilter.failed => 'Failed',- };-- bool matches(AnalyticsLogEntry entry) => switch (this) {- _EventFilter.all => true,- _EventFilter.sent => entry.status == AnalyticsEventStatus.sent,- _EventFilter.waiting => entry.status == AnalyticsEventStatus.queued,- _EventFilter.failed =>- entry.status == AnalyticsEventStatus.refused ||- entry.status == AnalyticsEventStatus.dropped,- };-}--/// Settings ▸ Tracking — every analytics event this app reports, newest first,-/// with the exact JSON behind each one.-///-/// Ported from Grid's Tracking tab-/// (`features/debug/presentation/tracking_view.dart`). Settings ▸ Debug beside-/// it answers "what did this app ask the CLI and the grid for"; this answers the-/// question analytics always raises and normally cannot: *did that event-/// actually leave, and what was in it?* Without it, an event that was never-/// sent, sent with a missing field, or refused by the server looks exactly like-/// an event that landed — the app is silent either way, by design.-///-/// Only reachable where [kDebugSurfaceEnabled] is — see `settings_section.dart`-/// — and only fed there either, since the buffer behind it is memory a shipped-/// session should not spend.-class TrackingSection extends StatefulWidget {- const TrackingSection({super.key, this.log, this.probe});-- /// The buffer to show. Defaults to the app's own; a test passes its own.- final AnalyticsLogStream? log;-- /// How the header card resolves the stream — injected in tests, which must- /// not read a real `~/.harness`.- final AnalyticsStreamStatus Function()? probe;-- @override- State<TrackingSection> createState() => _TrackingSectionState();-}--class _TrackingSectionState extends State<TrackingSection> {- _EventFilter _filter = _EventFilter.all;-- AnalyticsLogStream get _log => widget.log ?? analyticsLog;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- return SectionScaffold(- title: 'Tracking',- subtitle:- 'Every analytics event this app reports, and where it goes. Held in '- 'memory for this harness only — nothing here is written to disk.',- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- // Outside the builder below: where the stream points has nothing to- // do with what it has carried, and a card that re-read on every event- // would be a second thing on the screen moving.- TrackingStreamCard(probe: widget.probe ?? probeAnalyticsStatus),- const SizedBox(height: 14),- Expanded(- child: ListenableBuilder(- listenable: _log,- builder: (context, _) {- final entries = _log.entries;- final visible = [- for (final entry in entries)- if (_filter.matches(entry)) entry,- ];- return Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- _Toolbar(total: entries.length, onClear: _log.clear),- const SizedBox(height: 10),- DebugFilterBar(- lenses: [- for (final filter in _EventFilter.values)- DebugLens(- label: filter.label,- count: entries.where(filter.matches).length,- selected: filter == _filter,- onTap: () => setState(() => _filter = filter),- danger: filter == _EventFilter.failed,- hideWhenEmpty: filter == _EventFilter.failed,- ),- ],- ),- const SizedBox(height: 12),- Expanded(child: _list(entries.isEmpty, visible)),- ],- );- },- ),- ),- ],- ),- );- }-- Widget _list(bool nothingTracked, List<AnalyticsLogEntry> visible) {- if (visible.isNotEmpty) {- return ListView.separated(- itemCount: visible.length,- separatorBuilder: (_, _) => const SizedBox(height: 6),- itemBuilder: (context, i) => TrackingTile(entry: visible[i]),- );- }- // Nothing tracked yet and "the filter hid it all" are two different- // stories, so the lenses stay above and the user has a way back out.- if (nothingTracked) {- return const EmptyState(- icon: LucideIcons.activity300,- title: 'No events yet',- message:- 'Move around the app — opening a screen or creating a harness '- 'reports an event, and each one shows up here with what it sent.',- );- }- return const EmptyState.noMatches(message: 'No event matches this filter.');- }-}--/// The strip above the list: how much is held, and the one thing you can do-/// with it.-///-/// No "Open logs" beside Clear, unlike [DebugToolbar]: this buffer has no file-/// behind it, and a button pointing at `~/.harness/logs` would promise a-/// durable copy of these events that does not exist.-class _Toolbar extends StatelessWidget {- const _Toolbar({required this.total, required this.onClear});-- /// Everything captured this session, not the filtered view — this is the- /// buffer's fill level, not the list's length.- final int total;-- final VoidCallback onClear;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- return Row(- children: [- Expanded(- child: Text(- '$total ${total == 1 ? 'event' : 'events'}',- style: AppType.body(color: AppPalette.textSecondary),- ),- ),- ToolbarPill(- // Visible and dead when there is nothing to clear, rather than gone:- // a control that disappears takes its own explanation with it.- onTap: total == 0 ? null : onClear,- rimmed: true,- child: DebugPillLabel(- icon: LucideIcons.trash2,- label: 'Clear',- enabled: total != 0,- ),- ),- ],- );- }-}diff --git a/desktop/lib/settings/sections/tracking_stream_card.dart b/desktop/lib/settings/sections/tracking_stream_card.dartdeleted file mode 100644index 289568222..000000000--- a/desktop/lib/settings/sections/tracking_stream_card.dart+++ /dev/null@@ -1,155 +0,0 @@-import 'package:flutter/material.dart';-import 'package:lucide_icons_flutter/lucide_icons.dart';--import '../../analytics/analytics_sink.dart';-import '../../shared/theme/app_theme.dart';--/// Where the events go, whether they are going at all, and the two ids they are-/// filed under.-///-/// First on the Tracking screen because it is the first thing to check when the-/// list looks wrong: a muted stream and a quiet app look identical from the list-/// alone. When it is off, the reason says so in a sentence — "no events" with-/// nothing beside it is the state a developer wastes an hour on, and there are-/// four separate ways to end up in it (see `AnalyticsConfig`).-///-/// Built to [DebugPathsCard]'s shape, the sibling screen's header, rather than-/// to Grid's `GlassCard` — the two cards answer the same kind of question one-/// rail row apart.-class TrackingStreamCard extends StatefulWidget {- const TrackingStreamCard({super.key, this.probe = probeAnalyticsStatus});-- /// How the card reads the config and the ids. Injected in tests, which must- /// not read a real `~/.harness`.- final AnalyticsStreamStatus Function() probe;-- @override- State<TrackingStreamCard> createState() => _TrackingStreamCardState();-}--class _TrackingStreamCardState extends State<TrackingStreamCard> {- /// Read once: the write key is fixed at build time and the visit id only- /// changes when an event is tracked, which is the list's business, not this- /// card's. A card that re-read on every event would be a second thing on the- /// screen moving for the same reason.- late final AnalyticsStreamStatus _status = widget.probe();-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- final status = _status;- return Container(- padding: const EdgeInsets.fromLTRB(14, 11, 14, 12),- decoration: BoxDecoration(- color: AppGlass.surfaceFill,- borderRadius: BorderRadius.circular(14),- boxShadow: AppGlass.cardShadow,- ),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Row(- children: [- Icon(- LucideIcons.radioTower300,- size: 15,- color: AppPalette.textFaint,- ),- const SizedBox(width: 8),- Expanded(- child: Text('Analytics stream', style: AppType.heading()),- ),- _StatePill(enabled: status.enabled),- ],- ),- if (status.offReason case final reason?) ...[- const SizedBox(height: 6),- Text(- reason,- style: AppType.body(height: 1.4, color: AppPalette.textSecondary),- ),- ],- const SizedBox(height: 6),- _Row(label: 'endpoint', value: '${status.endpoint}'),- _Row(label: 'device id', value: status.deviceId),- _Row(- label: 'visit id',- // "Not yet" and "we could not read it" must not print the same.- value: status.sessionId.isEmpty- ? 'starts with the first event'- : status.sessionId,- muted: status.sessionId.isEmpty,- ),- ],- ),- );- }-}--/// Reporting or Off, as one small badge. A word rather than a dot: this is the-/// one fact on the screen a person came for, and a coloured dot would need the-/// sentence beside it anyway.-class _StatePill extends StatelessWidget {- const _StatePill({required this.enabled});-- final bool enabled;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- final ink = enabled ? AppPalette.online : AppPalette.textSecondary;- return Container(- padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 3),- decoration: BoxDecoration(- color: ink.withValues(alpha: 0.12),- borderRadius: BorderRadius.circular(999),- ),- child: Text(- enabled ? 'Reporting' : 'Off',- style: AppType.caption(fontWeight: AppFont.medium, color: ink),- ),- );- }-}--/// One `label: value` line, mono and selectable — an id is copied far more-/// often than it is read.-class _Row extends StatelessWidget {- const _Row({required this.label, required this.value, this.muted = false});-- final String label;- final String value;- final bool muted;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- return Padding(- padding: const EdgeInsets.symmetric(vertical: 2),- child: Row(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- SizedBox(- width: 72,- child: Text(- label,- style: AppType.body(color: AppPalette.textFaint),- ),- ),- Expanded(- child: SelectableText(- value,- style: AppType.monoLabel(- fontWeight: AppFont.regular,- height: 1.4,- color: muted- ? AppPalette.textSecondary- : AppPalette.textPrimary,- ),- ),- ),- ],- ),- );- }-}diff --git a/desktop/lib/settings/sections/tracking_tile.dart b/desktop/lib/settings/sections/tracking_tile.dartdeleted file mode 100644index 84e94f9b1..000000000--- a/desktop/lib/settings/sections/tracking_tile.dart+++ /dev/null@@ -1,203 +0,0 @@-import 'package:flutter/material.dart';-import 'package:lucide_icons_flutter/lucide_icons.dart';--import '../../analytics/analytics_log.dart';-import '../../logging/log_file.dart';-import '../../shared/theme/app_theme.dart';-import 'debug_log_tile.dart';-import 'tracking_detail_dialog.dart';--/// One tracked event in the Tracking list: what was tracked, how it ended, and-/// — on a click — the exact JSON it put on the wire.-///-/// Built to [DebugLogTile]'s shape rather than to Grid's `TrackingTile`: these-/// two lists sit one rail row apart, and a second card style for the second one-/// would read as two apps. Plain text rather than selectable, for the reason-/// that tile gives — a `SelectableText` eats the tap that opens the row, and-/// what it would let you copy is the summary, not the payload.-class TrackingTile extends StatefulWidget {- const TrackingTile({super.key, required this.entry});-- final AnalyticsLogEntry entry;-- @override- State<TrackingTile> createState() => _TrackingTileState();-}--class _TrackingTileState extends State<TrackingTile> {- bool _hovered = false;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context); // a list item — must self-watch to follow flips.- final entry = widget.entry;- final summary = trackedSummaryLine(entry);- final failed = entry.note != null && entry.note!.isNotEmpty;-- return Semantics(- button: true,- child: MouseRegion(- cursor: SystemMouseCursors.click,- onEnter: (_) => setState(() => _hovered = true),- onExit: (_) => setState(() => _hovered = false),- child: GestureDetector(- onTap: () => showTrackingDetailDialog(context, entry),- child: DecoratedBox(- decoration: BoxDecoration(- color: _hovered ? AppPalette.cardBgHover : AppPalette.cardBg,- borderRadius: BorderRadius.circular(AppCard.insetRadius),- ),- child: Padding(- padding: const EdgeInsets.fromLTRB(12, 9, 10, 9),- child: Column(- crossAxisAlignment: CrossAxisAlignment.start,- children: [- Row(- children: [- TrackingStatusIcon(status: entry.status),- const SizedBox(width: 9),- Expanded(- child: Text(- entry.name,- maxLines: 1,- overflow: TextOverflow.ellipsis,- style: AppType.monoLabel(- fontWeight: AppFont.regular,- color: AppPalette.textPrimary,- ),- ),- ),- const SizedBox(width: 10),- _Meta(entry: entry),- // Held open whether or not the cursor is here, so a row- // does not reflow the instant it is pointed at.- SizedBox(- width: 18,- child: _hovered- ? Icon(- LucideIcons.chevronRight,- size: 15,- color: AppPalette.textSecondary,- )- : null,- ),- ],- ),- if (summary.isNotEmpty) ...[- const SizedBox(height: 5),- Padding(- padding: const EdgeInsets.only(left: 24, right: 28),- child: Text(- summary,- maxLines: 2,- overflow: TextOverflow.ellipsis,- style: AppType.monoLabel(- fontWeight: AppFont.regular,- height: 1.35,- color: failed- ? debugDangerInk(context)- : AppPalette.textSecondary,- ),- ),- ),- ],- ],- ),- ),- ),- ),- ),- );- }-}--/// Waiting / sent / refused / dropped, as one glyph. Shared with the detail-/// dialog so a row and the panel it opens cannot disagree.-class TrackingStatusIcon extends StatelessWidget {- const TrackingStatusIcon({super.key, required this.status});-- final AnalyticsEventStatus status;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- return Icon(_glyph, size: 15, color: _ink(context));- }-- IconData get _glyph => switch (status) {- AnalyticsEventStatus.queued => LucideIcons.clock,- AnalyticsEventStatus.sent => LucideIcons.circleCheck,- AnalyticsEventStatus.refused => LucideIcons.circleAlert,- // A slash, not an alert: nothing went wrong on the wire, the event simply- // never reached it — a muted build, a full queue, a name we refused.- AnalyticsEventStatus.dropped => LucideIcons.circleSlash,- };-- Color _ink(BuildContext context) => switch (status) {- AnalyticsEventStatus.queued => AppPalette.textFaint,- AnalyticsEventStatus.sent => AppPalette.online,- AnalyticsEventStatus.refused => debugDangerInk(context),- // Warn, not danger: a dropped event is usually this build's own doing (no- // key) rather than a fault, and red would cry wolf on every row.- AnalyticsEventStatus.dropped => AppPalette.warn,- };-}--/// The clock time and, once it has settled, how long it took.-class _Meta extends StatelessWidget {- const _Meta({required this.entry});-- final AnalyticsLogEntry entry;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- final style = AppType.monoMeta(color: AppPalette.textFaint);- return Column(- crossAxisAlignment: CrossAxisAlignment.end,- children: [- Text(trackedStatusLabel(entry.status), style: style),- const SizedBox(height: 2),- Text(trackedOutcome(entry), style: style),- ],- );- }-}--/// `12:04:33 · 118ms · 2 tries` — the clock, and whatever the entry knows about-/// how it ended. The attempt count appears only past one: a badge that is-/// always there stops being read, and a retry is the thing worth seeing.-String trackedOutcome(AnalyticsLogEntry entry) {- final took = entry.took;- return [- logClock(entry.queuedAt),- if (took != null) debugDuration(took),- if (entry.attempts > 1) '${entry.attempts} tries',- ].join(' · ');-}--/// The word for a status, as both the row and the detail panel say it.-String trackedStatusLabel(AnalyticsEventStatus status) => switch (status) {- AnalyticsEventStatus.queued => 'Waiting',- AnalyticsEventStatus.sent => 'Sent',- AnalyticsEventStatus.refused => 'Refused',- AnalyticsEventStatus.dropped => 'Dropped',-};--/// What the row says under the event name: why it failed if it did, else the-/// params it carried. The failure wins — a dropped event's params are not the-/// thing anyone opened this screen to read.-String trackedSummaryLine(AnalyticsLogEntry entry) {- final note = entry.note;- if (note != null && note.isNotEmpty) return note;- return trackedParamsSummary(entry.params);-}--/// The params a call site passed, on one line:-/// `screen=settings_usage · source=rail`.-///-/// The row can only hold a line, and the line has to say *which* event this was-/// — `screen_view` on its own is thirty identical rows. The whole payload,-/// context and identity included, is a click away in the detail dialog.-String trackedParamsSummary(Map<String, Object?> params) =>- params.entries.map((e) => '${e.key}=${e.value}').join(' · ');diff --git a/desktop/lib/settings/settings_screen.dart b/desktop/lib/settings/settings_screen.dartindex 80972e904..1ff5d93cc 100644--- a/desktop/lib/settings/settings_screen.dart+++ b/desktop/lib/settings/settings_screen.dart@@ -1,7 +1,6 @@import 'package:flutter/material.dart';import 'package:flutter/services.dart';-import '../analytics/analytics.dart';import '../shared/theme/app_theme.dart' as grid;import '../state/app_state.dart';import '../widgets/harness_customize_pane.dart';@@ -13,7 +12,6 @@ import 'sections/debug_section.dart';import 'sections/devices_section.dart';import 'sections/experimental_section.dart';import 'sections/shortcuts_section.dart';-import 'sections/tracking_section.dart';import 'sections/usage_section.dart';import 'settings_nav.dart';import 'settings_section.dart';@@ -35,9 +33,8 @@ Future<void> showSettingsScreen(AppNotifier notifier, {SettingsSection? initialSection,ExperimentalFeaturesStore? experimentalFeatures,- // Which door opened Settings — see [AnalyticsEvents.screenView]. `required`,- // because a pane reachable several ways is close to meaningless as a bare- // count.+ // Which door opened Settings. No longer read since analytics was removed;+ // kept so the callers need not change.required String source,}) async {if (initialSection == SettingsSection.customize) {@@ -81,7 +78,7 @@ class SettingsScreen extends StatefulWidget {final AppNotifier notifier;final ExperimentalFeaturesStore? experimentalFeatures;- /// The door that opened this screen, reported with the first `screen_view`.+ /// The door that opened this screen. Unread since analytics was removed./// Defaulted only for tests that build the screen directly; every app door/// goes through [showSettingsScreen], where it is `required`.final String source;@@ -123,16 +120,6 @@ class _SettingsScreenState extends State<SettingsScreen> {return KeyEventResult.handled;}- @override- void initState() {- super.initState();- // The pane Settings opens on is a screen view like any other — without it- // the section a user lands on is the one section the stream never sees.- // This one carries the door that OPENED Settings; every later view in this- // visit came from the rail.- analytics.screenView(_screenName(_section), source: widget.source);- }-/// Move to another pane, from the settings rail.void _show(SettingsSection target) {if (target == SettingsSection.customize) {@@ -140,17 +127,9 @@ class _SettingsScreenState extends State<SettingsScreen> {return;}if (target == _section) return;- analytics.screenView(_screenName(target), source: 'rail');setState(() => _section = target);}- /// The section's stable name, never its label: labels are rewritten and a- /// renamed label would read as a new screen. `SettingsSection.usage` becomes- /// `settings_usage`, so a settings pane cannot collide with a top-level screen- /// that happens to share a word.- static String _screenName(SettingsSection section) =>- 'settings_${section.name}';-@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);@@ -211,7 +190,6 @@ class _SettingsBody extends StatelessWidget {SettingsSection.devices => const DevicesSection(),SettingsSection.shortcuts => const ShortcutsSection(),SettingsSection.debug => const DebugSection(),- SettingsSection.tracking => const TrackingSection(),SettingsSection.about => AboutSection(notifier: notifier),};return KeyedSubtree(key: ValueKey(section), child: screen);diff --git a/desktop/lib/settings/settings_section.dart b/desktop/lib/settings/settings_section.dartindex 983632eb4..ac87e7bb8 100644--- a/desktop/lib/settings/settings_section.dart+++ b/desktop/lib/settings/settings_section.dart@@ -20,7 +20,6 @@ enum SettingsSection {devices(LucideIcons.zap300, 'Autonomous robots'),shortcuts(LucideIcons.keyboard300, 'Keyboard shortcuts'),debug(LucideIcons.bug300, 'Debug'),- tracking(LucideIcons.activity300, 'Tracking'),about(LucideIcons.info300, 'About');const SettingsSection(this.icon, this.label);@@ -46,9 +45,9 @@ class SettingsGroup {/// What Settings lists, in order.///-/// A getter rather than a `const`, for the rows that are not always there:-/// [SettingsSection.debug] and [SettingsSection.tracking] are developer-/// furniture and ship only where [kDebugSurfaceEnabled] says so. Everything+/// A getter rather than a `const`, for the row that is not always there:+/// [SettingsSection.debug] is developer furniture and ships only where+/// [kDebugSurfaceEnabled] says so. Everything/// that draws or searches the rail reads this, so a hidden section cannot be/// reached by a stale copy of the list — while the enum values themselves/// always exist, so the screens behind them need no gate of their own.@@ -58,7 +57,7 @@ List<SettingsGroup> get settingsGroups =>/// [settingsGroups] with the gate passed in rather than read off the build.////// The flag is a compile-time const, so the shape a SHIPPED build has — no-/// Debug, no Tracking — is otherwise unreachable from a test, which by+/// Debug — is otherwise unreachable from a test, which by/// definition runs with it switched on. This seam is the only way to assert/// the thing the gate exists to do.@visibleForTesting@@ -76,14 +75,13 @@ List<SettingsGroup> settingsGroupsFor({required bool debugSurface}) {];}-/// The two developer sections, named once. Both read the same in-memory-/// buffers, both are worth nothing in a build that cannot open them, and a-/// second list of "which ones are hidden" is how the two would drift apart.-const _kDeveloperSections = {SettingsSection.debug, SettingsSection.tracking};+/// The developer sections, named once: worth nothing in a build that cannot+/// open them, and a second list of "which ones are hidden" would drift.+const _kDeveloperSections = {SettingsSection.debug};const _kSettingsGroups = [- // Usage sits with the preferences rather than with Debug and Tracking, which- // it otherwise resembles: those two are developer furniture a shipped build+ // Usage sits with the preferences rather than with Debug, which it+ // otherwise resembles: that is developer furniture a shipped build// hides, and this is a screen anybody is meant to open. It earns its place in// a run titled "what you change" by carrying the three switches that decide// which logs are read at all — the pane is off until somebody sets it.@@ -100,14 +98,11 @@ const _kSettingsGroups = [SettingsSection.account,SettingsSection.profiles,]),- // Debug and Tracking sit between the two things they are most often reached- // from: the keys that open them, and the version a report has to name. The- // two are adjacent because they answer the same question from opposite ends- // — what this app asked for, and what it reported about being asked.+ // Debug sits between the two things it is most often reached from: the keys+ // that open it, and the version a report has to name.SettingsGroup('Help', [SettingsSection.shortcuts,SettingsSection.debug,- SettingsSection.tracking,SettingsSection.about,]),];diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 3433c08d1..b41b29e7b 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -14,7 +14,6 @@ import 'package:flutter/widgets.dart'show AppLifecycleState, BuildContext, StringCharacters, WidgetsBinding;import 'package:flutter_riverpod/flutter_riverpod.dart';-import '../analytics/analytics.dart';import '../models/model_manager_controller.dart';import '../api/api_client.dart';import '../viewer/sign_in_browser.dart';@@ -728,16 +727,6 @@ class AppNotifier extends ChangeNotifier {machine.agents.map((agent) => previewKey(machine.machine.machineId, agent)),);- /// When this launch became signed in, and by which route — until the first- /// message of that session has been reported, after which it is null.- ///- /// One record for the whole app, not one per agent: the question is how long- /// somebody sits signed in before talking to anything at all, and which agent- /// they finally picked is `agent_created`'s business. A session where nobody- /// ever sends a message simply leaves this set until sign-out or quit, which- /// is exactly the population the event exists to measure the absence of.- ({DateTime at, String from})? _awaitingFirstMessage;-final Map<String, Timer> _offlineRetryTimers = {};// Periodic retry for a machine the relay reported NO_PEER_LINK for — a `harness link connect` run// in a terminal (or another app instance) has no way to notify this one, so this is what makes the@@ -3060,31 +3049,9 @@ class AppNotifier extends ChangeNotifier {_lastError = 'Could not complete sign-in. Please sign in again.';}notifyListeners();- } finally {- // A `finally` rather than a call per exit path: bootstrap resolves four- // ways (environment not ready, signed out, signed in, thrown) and the- // launch happened in all four. `retryEnvironmentSetup` re-enters here,- // which is why the event itself is once-per-launch.- _trackAppOpened();}}- bool _appOpenedTracked = false;-- /// `app_opened`, once, with the answer bootstrap actually reached. Sent from- /// here rather than from the first frame because `signed_in` is not known- /// until the CLI has been asked, and a first-frame event would report every- /// launch as signed out.- void _trackAppOpened() {- if (_appOpenedTracked) return;- _appOpenedTracked = true;- final signedIn = status == AppStatus.authenticated;- analytics.appOpened(signedIn: signedIn);- // A returning user is signed in before the app is even on screen, so their- // wait starts here rather than at a sign-in that never happens.- if (signedIn) _armFirstMessage('launch');- }-/// Runs before we invoke a single Harness subcommand. A fresh mac used to/// fail here with a generic Sign in error because `harness` and its Node/// runtime were absent; provisioning now makes that a visible, recoverable@@ -3158,11 +3125,6 @@ class AppNotifier extends ChangeNotifier {mode: mode,);environmentReadiness = result;- if (!quiet ||- result.isReady ||- result.phase == EnvironmentSetupPhase.failed) {- analytics.environmentPrepared(ready: result.isReady);- }return result;}@@ -3352,7 +3314,6 @@ class AppNotifier extends ChangeNotifier {} finally {_environmentSetupInFlight = false;notifyListeners();- _trackAppOpened();}}@@ -3598,7 +3559,6 @@ class AppNotifier extends ChangeNotifier {_guestDeskRestorePending = true;signedIn = false;currentUser = null;- analyticsAccount.clear();if (banner != null) {_lastError = banner;_lastErrorRetryable = true;@@ -3750,7 +3710,7 @@ class AppNotifier extends ChangeNotifier {/// Who is signed in, from the daemon. Shared by the boot path and by the/// retry path, because a boot that found the daemon still connecting now/// finishes THROUGH the retry path — and a session that never learns its- /// own account has an empty footer and unattributed analytics.+ /// own account has an empty footer.Future<void> _loadProfile() {final pending = _profileInFlight;if (pending != null) return pending;@@ -3770,12 +3730,7 @@ class AppNotifier extends ChangeNotifier {return;}if (me != null) {- final profile = CurrentUserProfile.fromMe(me);- currentUser = profile;- // Every event from here on is filed under the account, including ones- // queued while this call was still in flight — the queue reads the- // account per event, not per launch.- analyticsAccount.set(id: profile.id, email: profile.email);+ currentUser = CurrentUserProfile.fromMe(me);notifyListeners();}} catch (error) {@@ -3955,8 +3910,6 @@ class AppNotifier extends ChangeNotifier {currentUser = null;signingIn = false;pendingAuthorizeUrl = null;- _awaitingFirstMessage = null;- analyticsAccount.clear();final previousMachineId = localMachineState?.machine.machineId;_clearAccountWorkspace();// A VIEWER has nowhere to be but its login screen — no daemon, nothing of@@ -4343,24 +4296,11 @@ class AppNotifier extends ChangeNotifier {return;}_guestDeskRestorePending = false;- analytics.signedIn();- // Restarts the clock even if `_trackAppOpened` already started one: this- // person met the login screen, so their wait begins where the launch's- // did not.- _armFirstMessage('sign_in');} catch (error) {if (!_authWorkCurrent(revision)) return;status = wasGuest ? AppStatus.authenticated : AppStatus.unauthenticated;_lastError = error.toString();_lastErrorRetryable = true;- // A short code, never `error.toString()` — a CLI failure carries paths- // and host names, and this stream is not the place for them. Only the- // two the TYPE can tell apart: a cancelled sign-in and a refused one both- // arrive as a `StateError` differing in message text, and matching on- // English sentences is how a stream starts lying after a copy edit.- analytics.signInFailed(- error is CliNotAvailableException ? 'cli_missing' : 'failed',- );if (wasGuest && _guestDeskRestorePending && !signedIn) {unawaited(_becomeGuest(revision: revision));}@@ -4489,7 +4429,6 @@ class AppNotifier extends ChangeNotifier {final becomesGuest = viewer == null && localManualFixture == null;if (!becomesGuest) status = AppStatus.unauthenticated;currentUser = null;- analyticsAccount.clear();notifyListeners();// Clear saved credentials alongside connection cleanup. A new login must// wait for both, otherwise the old logout can delete its fresh session.@@ -4499,12 +4438,6 @@ class AppNotifier extends ChangeNotifier {: Future<void>.sync(cliLogin.logout).then((_) => true, onError: (Object _) => false);_clearAccountWorkspace();- analytics.signedOut();- // A session that ended without a message reports nothing — its absence IS- // the finding, and a stale clock would attach that wait to whoever signs in- // next.- _awaitingFirstMessage = null;- analyticsAccount.clear();notifyListeners();await _workspaceCleanup;final didClear = await cleared;@@ -7574,40 +7507,6 @@ class AppNotifier extends ChangeNotifier {return session is String && session.isNotEmpty ? session : null;}- /// Starts the clock `app_first_message` measures. [from] is `sign_in` for a- /// fresh log-in and `launch` for an app opened with a session already there.- ///- /// One body, called by both routes and by the test seam below — a second- /// place building this record is a second place to get it wrong.- void _armFirstMessage(String from) =>- _awaitingFirstMessage = (at: DateTime.now(), from: from);-- /// Closes that clock out, once.- ///- /// A one-shot latch rather than a counter: the record is read and cleared in- /// the same breath, so every turn after the first finds nothing and there is- /// never a "which message is this" to get wrong.- ///- /// ⚠️ Called from `turn_started` ONLY, never from the other two routes into- /// [_markAgentProcessing]. A `turn_heartbeat`, and an adopted agent found- /// already mid-turn when this app connected, are both work that was under way- /// before anybody here typed anything — counting either would report a- /// near-zero wait for a returning user who has not said a word.- void _reportFirstMessage() {- if (_awaitingFirstMessage case final login?) {- _awaitingFirstMessage = null;- analytics.appFirstMessage(- from: login.from,- secondsSinceLogin: DateTime.now().difference(login.at).inSeconds,- );- }- }-- /// [_armFirstMessage], for a test: signing in needs a live CLI, and what is- /// worth pinning is what the first turn AFTER it does.- @visibleForTesting- void armFirstMessageForTest(String from) => _armFirstMessage(from);-String _turnActivityKey(String machineId, String agentId) =>'$machineId\u0000$agentId';@@ -13016,10 +12915,6 @@ class AppNotifier extends ChangeNotifier {break;case 'turn_started':case 'turn_heartbeat':- // A turn that STARTS is somebody sending something; a heartbeat is a- // turn already under way, which for an agent this app merely reconnected- // to is work nobody here just asked for.- if (type == 'turn_started') _reportFirstMessage();var changed = false;final agentId = _eventAgentId(machine, event, payload);if (agentId != null) {diff --git a/desktop/lib/state/model_start_watch.dart b/desktop/lib/state/model_start_watch.dartindex 8ca0e0f37..c9c6284cb 100644--- a/desktop/lib/state/model_start_watch.dart+++ b/desktop/lib/state/model_start_watch.dart@@ -37,8 +37,7 @@ enum ModelStartPhase {////// Terminal output is deliberately NOT a signal: the first bytes a pane prints after Enter are the/// engine echoing the prompt and drawing its own spinner, which would end the chip the moment it-/// appeared. Those events are what this app already trusts for the rail's working mark and for-/// `app_first_message`.+/// appeared. Those events are what this app already trusts for the rail's working mark.////// Its own notifier, like [GridPictures], so a pane header listening for its chip is not rebuilt on/// every terminal frame.diff --git a/desktop/lib/state/new_harness.dart b/desktop/lib/state/new_harness.dartindex 947f7817c..997ceb471 100644--- a/desktop/lib/state/new_harness.dart+++ b/desktop/lib/state/new_harness.dart@@ -9,7 +9,6 @@ import 'package:flutter/foundation.dart';import 'package:path/path.dart' as p;import '../core/runtime_platform.dart';-import '../analytics/analytics.dart';import '../core/codex_profiles.dart';import '../core/dsh_catalog.dart';import '../core/harness_catalog.dart';@@ -3281,11 +3280,6 @@ class NewHarnessController extends ChangeNotifier {}return _fail(failure);}- analytics.agentCreated(- engine: choice,- bypassPermission: bypass,- permissionMode: permissionMode,- );unawaited(app.agentPreference.remember(choice, harnessId: _harnessId));busy = false;status = null;diff --git a/desktop/lib/stats/harness_stats.dart b/desktop/lib/stats/harness_stats.dartindex 8b5169ab0..5454a3221 100644--- a/desktop/lib/stats/harness_stats.dart+++ b/desktop/lib/stats/harness_stats.dart@@ -219,7 +219,7 @@ class HarnessStats extends ChangeNotifier {/// The app's own counters.///-/// A singleton like `analytics` and `terminalFontStore`, for the same reason: the+/// A singleton like `appLog` and `terminalFontStore`, for the same reason: the/// call sites are `AppNotifier`'s event dispatcher and one settings pane, and/// threading an instance from one to the other would mean handing a `Ref` to a/// widget that has no other use for one.diff --git a/desktop/lib/stats/stats_lifecycle.dart b/desktop/lib/stats/stats_lifecycle.dartnew file mode 100644index 000000000..366fa10d6--- /dev/null+++ b/desktop/lib/stats/stats_lifecycle.dart@@ -0,0 +1,52 @@+import 'dart:ui' show AppExitResponse;++import 'package:flutter/widgets.dart';++import 'harness_stats.dart';++/// Writes [harnessStats] out when the app quits. Renders [child] unchanged.+///+/// Only `didRequestAppExit` is hooked, which covers ⌘Q, the app menu's Quit and+/// an OS log-out. Intercepting the window's close button needs+/// `windowManager.setPreventClose(true)` and a matching `destroy()` call — and+/// a bug on that path leaves a window the user cannot close.+class StatsLifecycle extends StatefulWidget {+ const StatsLifecycle({super.key, required this.child});++ final Widget child;++ @override+ State<StatsLifecycle> createState() => _StatsLifecycleState();+}++class _StatsLifecycleState extends State<StatsLifecycle>+ with WidgetsBindingObserver {+ bool _closed = false;++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ }++ @override+ void dispose() {+ WidgetsBinding.instance.removeObserver(this);+ super.dispose();+ }++ @override+ Future<AppExitResponse> didRequestAppExit() async {+ if (!_closed) {+ _closed = true;+ // Awaited: a local file write that finishes in milliseconds, and the ONLY+ // place a turn still running at quit gets its time counted — the+ // debounce timer is cancelled by the process exiting, not fired by it.+ await harnessStats.flush();+ }+ return AppExitResponse.exit;+ }++ @override+ Widget build(BuildContext context) => widget.child;+}diff --git a/desktop/lib/store/store_screen.dart b/desktop/lib/store/store_screen.dartindex 02ad930a7..66c40af8b 100644--- a/desktop/lib/store/store_screen.dart+++ b/desktop/lib/store/store_screen.dart@@ -7,7 +7,6 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:url_launcher/url_launcher.dart';import 'package:harness/terminal/terminal_text.dart';-import '../analytics/analytics.dart';import '../core/dsh_catalog.dart';import '../core/harness_catalog.dart';import '../core/models.dart' show ConnectionStatus;@@ -167,7 +166,6 @@ class _StoreTabState extends State<StoreTab> {void initState() {super.initState();_remember();- analytics.screenView('store', source: widget.source);// Deferred a frame: both calls notify listeners at once, and this screen// is built while the shell underneath — which listens to the same// notifier — is mid-build.@@ -379,7 +377,6 @@ class _StoreTabState extends State<StoreTab> {void _show(_Shelf shelf) => _navigate(_StoreVisit(shelf, null, ''));void _openPage(String id) {- analytics.screenView('store_harness', source: 'store');_navigate(_StoreVisit(_shelf, id, _search.text));}diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dartindex 99f9ec796..1856874b6 100644--- a/desktop/lib/widgets/new_agent_dialog.dart+++ b/desktop/lib/widgets/new_agent_dialog.dart@@ -6,7 +6,6 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';-import '../analytics/analytics.dart';import '../state/pane_arrangement.dart';import '../core/desktop_window.dart';import '../core/engine_availability.dart';@@ -95,7 +94,6 @@ Future<NewAgentDialogResult?> showNewAgentDialog(.machineId ??'';}- analytics.newAgentOpened(source: source);// This dialog uses a separate route. Carry the live picker bindings with// it; showGeneralDialog does not capture inherited themes for us.final activeKeymap = keymap ?? KeymapTheme.of(context, listen: false);@@ -766,11 +764,6 @@ class _NewAgentDialogState extends State<_NewAgentDialog> {});return;}- analytics.agentCreated(- engine: choice,- bypassPermission: bypassPermission,- permissionMode: permissionMode,- );// What New Harness lists first next time, before anything is typed.unawaited(widget.notifier.agentPreference.remember(choice, harnessId: _harnessId),diff --git a/desktop/test/agent_events_test.dart b/desktop/test/agent_events_test.dartdeleted file mode 100644index acef45d13..000000000--- a/desktop/test/agent_events_test.dart+++ /dev/null@@ -1,282 +0,0 @@-// The funnel: opening the New agent dialog, finishing it, and — once per-// signed-in session — actually saying something. Separate events on purpose:-// the interesting numbers are the DROPS between them, and one event per step is-// the only way to see a drop at all.-//-// What is pinned here is the part that is easy to get subtly wrong: which door-// a dialog says it was opened by, and that the first message is reported once-// per SESSION rather than per agent, and never with any of what was typed.-import 'package:flutter/material.dart';-import 'package:flutter/services.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:harness/analytics/analytics.dart';-import 'package:harness/analytics/analytics_sink.dart';-import 'package:harness/auth/auth_session.dart';-import 'package:harness/core/config.dart';-import 'package:harness/core/models.dart';-import 'package:harness/state/app_state.dart';-import 'package:harness/state/harness_placement.dart';-import 'package:harness/core/project_folder.dart';-import 'package:harness/state/pane_arrangement.dart';-import 'package:harness/widgets/new_agent_dialog.dart';--/// Keeps every tracked event, so a test can assert on the name AND the params-/// — a stream is only as good as what its params carry.-class RecordingAnalytics implements Analytics {- final List<({String name, Map<String, Object?> params})> events = [];-- Map<String, Object?> paramsOf(String name) =>- events.firstWhere((event) => event.name == name).params;-- int count(String name) => events.where((e) => e.name == name).length;-- @override- void track(String name, {Map<String, Object?> params = const {}}) =>- events.add((name: name, params: params));-- @override- Future<void> flush() async {}-- @override- Future<void> close() async {}-}--/// Stands in for the CLI round trip, so a test can drive a real Create click.-class FakeCreateAgentNotifier extends AppNotifier {- FakeCreateAgentNotifier()- : super(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- );-- @override- Future<Map<String, dynamic>> listRemoteFolder(- String machineId,- String? path,- ) async => {'path': '/tmp/agent-folder', 'entries': <dynamic>[]};-- @override- Future<String?> createAgent(- String machineId, {- required String engine,- required String? folder,- ProjectFolderRequest? projectFolder,- bool bypassPermission = false,- String? permissionMode,- String? codexHome,- String? dsh,- GridModel? model,- String? prompt,- String? name,- String? agent,- String? swarmId,- PaneSplitRequest? split,- AgentCreationAttempt? attempt,- HarnessPlacement? placement,- }) async => null;-}--void main() {- TestWidgetsFlutterBinding.ensureInitialized();-- late RecordingAnalytics tracked;-- setUp(() {- tracked = RecordingAnalytics();- setAnalyticsForTest(tracked);- });-- // Put back, or every later test in the run reports into this list.- tearDown(() => setAnalyticsForTest(null));-- const machine = Machine(- machineId: 'machine-1',- authMode: MachineAuthMode.remote,- name: 'Mac mini M4',- );-- group('new_agent_opened', () {- Future<void> openFrom(WidgetTester tester, String source) async {- final notifier = FakeCreateAgentNotifier();- addTearDown(notifier.dispose);- notifier.machineStates['machine-1'] = MachineState(machine)- ..localOnly = true;- await tester.pumpWidget(- MaterialApp(- home: Builder(- builder: (context) => Scaffold(- body: TextButton(- onPressed: () => showNewAgentDialog(- context,- notifier,- 'machine-1',- source: source,- ),- child: const Text('open'),- ),- ),- ),- ),- );- await tester.tap(find.text('open'));- await tester.pumpAndSettle();- }-- testWidgets('names the door it was opened by', (tester) async {- await openFrom(tester, 'rail_empty');-- expect(tracked.paramsOf('new_agent_opened'), {'source': 'rail_empty'});- });-- testWidgets('every door reports, because the dialog reports for them', (- tester,- ) async {- // The point of tracking inside `showNewAgentDialog` rather than at each- // call site: a door added later cannot forget.- for (final source in ['machine_row', 'pane_empty', 'shortcut']) {- await openFrom(tester, source);- await tester.sendKeyEvent(LogicalKeyboardKey.escape);- await tester.pumpAndSettle();- }-- expect(tracked.count('new_agent_opened'), 3);- expect(tracked.events.map((e) => e.params['source']), [- 'machine_row',- 'pane_empty',- 'shortcut',- ]);- });- });-- group('agent_created', () {- Future<void> create(WidgetTester tester) async {- final notifier = FakeCreateAgentNotifier();- addTearDown(notifier.dispose);- notifier.machineStates['machine-1'] = MachineState(machine);- await tester.pumpWidget(- MaterialApp(- home: Builder(- builder: (context) => Scaffold(- body: TextButton(- onPressed: () => showNewAgentDialog(- context,- notifier,- 'machine-1',- source: 'machine_row',- ),- child: const Text('open'),- ),- ),- ),- ),- );- await tester.tap(find.text('open'));- await tester.pumpAndSettle();- // Browse on a remote machine uses the in-app folder picker.- await tester.ensureVisible(- find.byKey(const Key('new-agent-project-browse')),- );- await tester.tap(find.byKey(const Key('new-agent-project-browse')));- await tester.pumpAndSettle();- await tester.tap(find.widgetWithText(FilledButton, 'Select this folder'));- await tester.pumpAndSettle();- await tester.tap(find.byKey(const ValueKey('create-agent-submit')));- await tester.pumpAndSettle();- }-- testWidgets('carries the engine and the bypass flag', (tester) async {- await create(tester);-- // Auto-approve unless the person picks another mode.- expect(tracked.paramsOf('agent_created'), {- 'engine': 'claude',- 'bypass_permission': true,- 'permission_mode': 'auto',- });- });-- testWidgets('the working folder is never sent', (tester) async {- await create(tester);-- // An absolute path names the person as surely as their email does.- expect(- tracked.paramsOf('agent_created').values.join(' '),- isNot(contains('/tmp/agent-folder')),- );- });- });-- group('app_first_message', () {- AppNotifier notifierWithMachine() {- final notifier = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- );- addTearDown(notifier.dispose);- notifier.machineStates['machine-1'] = MachineState(machine);- return notifier;- }-- Future<void> turn(AppNotifier notifier, String type, String agentId) =>- notifier.handleEventForTest('machine-1', {- 'type': type,- 'agentId': agentId,- });-- Future<void> turnStarted(AppNotifier notifier, String agentId) =>- turn(notifier, 'turn_started', agentId);-- test('reports the wait, and what started the clock', () async {- final notifier = notifierWithMachine();- notifier.armFirstMessageForTest('sign_in');-- await turnStarted(notifier, 'agent-1');-- final params = tracked.paramsOf('app_first_message');- expect(params['from'], 'sign_in');- expect(params['seconds_since_login'], isA<int>());- // Not per agent: nothing here may name the agent, its engine or its- // machine. Which agent it was is `agent_created`'s question.- expect(params.keys, unorderedEquals(['from', 'seconds_since_login']));- });-- test('once per session, however many agents are spoken to', () async {- final notifier = notifierWithMachine();- notifier.armFirstMessageForTest('launch');-- await turnStarted(notifier, 'agent-1');- await turnStarted(notifier, 'agent-1');- await turnStarted(notifier, 'agent-2');-- expect(tracked.count('app_first_message'), 1);- expect(tracked.paramsOf('app_first_message')['from'], 'launch');- });-- test('a heartbeat is not a message', () async {- // The trap this closes: a returning user whose agent was already mid-turn- // when the app reconnected gets heartbeats, not a turn start. Counting- // one would report a near-zero wait for somebody who has not said a word.- final notifier = notifierWithMachine();- notifier.armFirstMessageForTest('launch');-- await turn(notifier, 'turn_heartbeat', 'agent-1');- expect(tracked.count('app_first_message'), 0);-- // And the real first message still lands afterwards.- await turnStarted(notifier, 'agent-1');- expect(tracked.count('app_first_message'), 1);- });-- test('a turn with nobody signed in reports nothing', () async {- // Nothing started the clock, so there is no wait to measure — and an- // event with no login behind it is a number attached to nobody.- final notifier = notifierWithMachine();-- await turnStarted(notifier, 'agent-1');-- expect(tracked.count('app_first_message'), 0);- });- });-}diff --git a/desktop/test/analytics_test.dart b/desktop/test/analytics_test.dartdeleted file mode 100644index 2e4bde54c..000000000--- a/desktop/test/analytics_test.dart+++ /dev/null@@ -1,412 +0,0 @@-import 'dart:convert';-import 'dart:io';-import 'dart:math';--import 'package:flutter_test/flutter_test.dart';-import 'package:harness/analytics/analytics_client.dart';-import 'package:harness/analytics/analytics_config.dart';-import 'package:harness/analytics/analytics_event.dart';-import 'package:harness/analytics/analytics_identity.dart';-import 'package:harness/analytics/analytics_log.dart';-import 'package:harness/analytics/analytics_sink.dart';-import 'package:harness/analytics/analytics_service.dart';--/// Records what it was asked to send and answers with a scripted result, so-/// every branch of the queue is reachable without a socket.-class FakeAnalyticsClient implements AnalyticsClient {- FakeAnalyticsClient([this.answer = AnalyticsSendResult.sent]);-- AnalyticsSendResult answer;- final List<Map<String, Object?>> sent = [];- int disposed = 0;-- @override- Future<AnalyticsSendResult> send(Map<String, Object?> payload) async {- sent.add(payload);- return answer;- }-- @override- void dispose() => disposed++;-}--/// The params list of a captured payload, flattened back to a map.-Map<String, Object?> paramsOf(Map<String, Object?> payload) {- final data = payload['data']! as Map<String, Object?>;- final entries = data['event_params']! as List<Map<String, Object?>>;- return {for (final entry in entries) entry['key']! as String: entry['value']};-}--void main() {- late Directory scratch;-- setUp(() async {- scratch = await Directory.systemTemp.createTemp('harness-analytics-test-');- });-- tearDown(() async {- if (await scratch.exists()) await scratch.delete(recursive: true);- });-- AnalyticsIdentityStore storeIn(Directory dir, {String? computerId}) {- final computerIdFile = File('${dir.path}/computer-id');- if (computerId != null) computerIdFile.writeAsStringSync('$computerId\n');- return AnalyticsIdentityStore(- file: File('${dir.path}/analytics.json'),- computerIdFile: computerIdFile,- random: Random(7),- );- }-- QueuedAnalytics queueOn(- FakeAnalyticsClient client, {- AnalyticsIdentityStore? identity,- ({String? id, String? email}) user = (id: null, email: null),- AnalyticsLog recorder = const NoopAnalyticsLog(),- DateTime Function()? clock,- }) => QueuedAnalytics(- client: client,- identityStore: identity ?? storeIn(scratch),- contextFuture: Future.value(AnalyticsContext.unknown),- userLookup: () => user,- recorder: recorder,- clock: clock ?? DateTime.now,- );-- // --- the wire -------------------------------------------------------------- test('the payload is the web client shape, and says which app sent it', () {- final event = AnalyticsEvent(- name: 'agent_created',- params: const {'engine': 'claude', 'bypass_permission': true},- at: DateTime.fromMillisecondsSinceEpoch(1700000000000, isUtc: true),- identity: const AnalyticsIdentity(- pseudoId: 'device-1',- sessionId: 'visit-1',- userId: 'user-1',- userEmail: '[email protected]',- ),- );-- final payload = analyticsPayload(event, AnalyticsContext.unknown);- final data = payload['data']! as Map<String, Object?>;- final params = paramsOf(payload);-- expect(payload['event_name'], 'agent_created');- // Seconds, not milliseconds — the web client's unit.- expect(payload['event_timestamp'], 1700000000);- expect(data['session_id'], 'visit-1');- expect(data['user_pseudo_id'], 'device-1');- // In BOTH places, as on the web: most queries read the params table.- expect(data['user_id'], 'user-1');- expect(params['user_id'], 'user-1');- expect(params['user_email'], '[email protected]');- expect(params['engine'], 'claude');- expect(params['bypass_permission'], true);- // Without this every stream in the shared project looks like one app.- expect(params['category'], 'harness-desktop-v2');- });-- test('params drop nothing meaningful and carry nothing unbounded', () {- final long = 'x' * (AnalyticsLimits.paramsMaxStringLength + 50);- final params = analyticsParams({- 'kept': 'value',- 'zero': 0,- 'off': false,- 'null_goes': null,- 'empty_goes': '',- 'nested': {'a': 1},- 'long': long,- });- final byKey = {- for (final entry in params) entry['key']! as String: entry['value'],- };-- expect(byKey.containsKey('null_goes'), isFalse);- expect(byKey.containsKey('empty_goes'), isFalse);- // A zero and a false are measurements, not absences.- expect(byKey['zero'], 0);- expect(byKey['off'], false);- expect(byKey['nested'], '{"a":1}');- expect(- (byKey['long']! as String).length,- AnalyticsLimits.paramsMaxStringLength,- );- });-- test('more params than the cap are cut, not sent for the server to drop', () {- final params = analyticsParams({- for (var i = 0; i < AnalyticsLimits.paramsMaxKeys + 10; i++) 'k$i': i,- });-- expect(params, hasLength(AnalyticsLimits.paramsMaxKeys));- });-- // --- the queue ------------------------------------------------------------- test(- 'a name that is not snake_case is refused before it is queued',- () async {- final client = FakeAnalyticsClient();- final analytics = queueOn(client);-- analytics.track('Agent Created');- analytics.track('no');- await analytics.flush();-- expect(client.sent, isEmpty);- expect(analytics.pending, 0);- },- );-- test('a sent event leaves the queue; a refused one is dropped', () async {- final client = FakeAnalyticsClient();- final analytics = queueOn(client);-- analytics.track('agent_created');- await analytics.flush();- expect(client.sent, hasLength(1));- expect(analytics.pending, 0);-- client.answer = AnalyticsSendResult.rejected;- analytics.track('agent_created');- await analytics.flush();- // Sending it again would fail identically, so it goes.- expect(analytics.pending, 0);- });-- test('a transport failure keeps the event for the next attempt', () async {- final client = FakeAnalyticsClient(AnalyticsSendResult.retry);- final analytics = queueOn(client);-- analytics.track('agent_created');- await analytics.flush();-- expect(analytics.pending, 1, reason: 'a 5xx must not lose the event');-- client.answer = AnalyticsSendResult.sent;- await analytics.flush();- expect(analytics.pending, 0);- });-- test('a full queue drops its OLDEST, keeping what describes now', () async {- final client = FakeAnalyticsClient(AnalyticsSendResult.retry);- final analytics = queueOn(client);-- for (var i = 0; i < AnalyticsLimits.queueCap + 5; i++) {- analytics.track('signed_in');- }- await analytics.flush();-- expect(analytics.pending, AnalyticsLimits.queueCap);- });-- test('the account is read per event, not per launch', () async {- final client = FakeAnalyticsClient();- var user = (id: null, email: null) as ({String? id, String? email});- final analytics = QueuedAnalytics(- client: client,- identityStore: storeIn(scratch),- contextFuture: Future.value(AnalyticsContext.unknown),- userLookup: () => user,- );-- analytics.track('app_opened');- user = (id: 'user-9', email: '[email protected]');- analytics.track('signed_in');- await analytics.flush();-- expect(paramsOf(client.sent[0])['user_id'], isNull);- expect(paramsOf(client.sent[1])['user_id'], 'user-9');- });-- test('close drains once, then the sink is spent', () async {- final client = FakeAnalyticsClient();- final analytics = queueOn(client);-- analytics.track('app_closed');- await analytics.close();- analytics.track('app_opened');-- expect(client.sent, hasLength(1));- expect(client.disposed, 1);- });-- // --- identity -------------------------------------------------------------- test('the device id is this machine\'s Harness id when it has one', () {- final store = storeIn(scratch, computerId: 'computer-abc');-- expect(store.peek().pseudoId, 'computer-abc');- });-- test('with no computer-id it mints a v4 UUID and keeps it', () {- final store = storeIn(scratch);- final first = store.touch(DateTime.now()).pseudoId;-- expect(- first,- matches(- r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$',- ),- );- // A second store over the same file reads the id back rather than minting.- expect(storeIn(scratch).peek().pseudoId, first);- });-- test('the visit rotates after quiet and holds through activity', () {- final store = storeIn(scratch, computerId: 'computer-abc');- final start = DateTime.utc(2026, 1, 1, 9);-- final first = store.touch(start).sessionId;- final same = store.touch(start.add(const Duration(minutes: 5))).sessionId;- final after = store- .touch(start.add(AnalyticsLimits.sessionIdle * 2))- .sessionId;-- expect(first, isNotEmpty);- expect(same, first);- expect(after, isNot(first));- });-- test('an opt-out is honoured and survives every write', () {- final file = File('${scratch.path}/analytics.json')- ..writeAsStringSync(jsonEncode({'enabled': false}));- final store = AnalyticsIdentityStore(- file: file,- computerIdFile: File('${scratch.path}/computer-id'),- );-- expect(store.optedOut, isTrue);-- store.touch(DateTime.utc(2026, 1, 1, 9));- final written = jsonDecode(file.readAsStringSync()) as Map<String, Object?>;- expect(- written['enabled'],- false,- reason: 'turning tracking off has to stay off across a write',- );- });-- test('a corrupt file starts over rather than failing the launch', () {- File('${scratch.path}/analytics.json').writeAsStringSync('not json {');- final store = storeIn(scratch, computerId: 'computer-abc');-- expect(store.peek().pseudoId, 'computer-abc');- expect(store.optedOut, isFalse);- });-- // --- the switch ------------------------------------------------------------ test('a test run is muted, and says why', () {- final config = AnalyticsConfig.resolve();-- expect(config.enabled, isFalse);- expect(config.offReason, isNotNull);- // The sink every test gets: no socket, no queue, no Harness home. It is- // MutedAnalytics rather than NoopAnalytics because a test VM has the debug- // surface, so the events still land in the buffer Settings ▸ Tracking- // reads — a screen whose whole job is to explain a stream going nowhere- // cannot be blank in the state that makes it most needed. A release build- // has no such screen and gets the Noop.- expect(analytics, isA<MutedAnalytics>());- expect((analytics as MutedAnalytics).reason, config.offReason);- });-- // --- the Tracking screen's buffer ------------------------------------------ test('a muted sink records the event it did not send', () {- final log = AnalyticsLogStream();- MutedAnalytics(- log,- 'This build carries no analytics key.',- ).track('screen_view', params: const {'screen': 'settings_tracking'});-- final entry = log.entries.single;- expect(entry.name, 'screen_view');- expect(entry.params, const {'screen': 'settings_tracking'});- expect(entry.status, AnalyticsEventStatus.dropped);- expect(entry.note, 'This build carries no analytics key.');- expect(- entry.payload,- isNull,- reason: 'nothing went on the wire, so there is no body to show',- );- });-- test('the queue records an event from queued to sent', () async {- final log = AnalyticsLogStream();- final client = FakeAnalyticsClient();- final analytics = queueOn(client, recorder: log);-- analytics.track('agent_created', params: const {'engine': 'claude'});- expect(log.entries.single.status, AnalyticsEventStatus.queued);-- await analytics.flush();-- final entry = log.entries.single;- expect(entry.status, AnalyticsEventStatus.sent);- expect(entry.attempts, 1);- expect(entry.took, isNotNull);- // The payload, not the params: the gap between what the call site passed- // and what actually left is the bug this screen is opened to find.- expect(entry.payload, contains('"event_name": "agent_created"'));- expect(entry.payload, contains('harness-desktop-v2'));- });-- test('a retry shows as one row with two attempts, not two rows', () async {- final log = AnalyticsLogStream();- final client = FakeAnalyticsClient(AnalyticsSendResult.retry);- final analytics = queueOn(client, recorder: log);-- analytics.track('signed_in');- await analytics.flush();- expect(log.entries.single.status, AnalyticsEventStatus.queued);- expect(log.entries.single.attempts, 1);-- client.answer = AnalyticsSendResult.sent;- await analytics.flush();-- expect(log.entries, hasLength(1));- expect(log.entries.single.status, AnalyticsEventStatus.sent);- expect(- log.entries.single.attempts,- 2,- reason: 'the retry is the thing this screen exists to make visible',- );- });-- test('a refusal and a bad name are told apart on the row', () async {- final log = AnalyticsLogStream();- final analytics = queueOn(- FakeAnalyticsClient(AnalyticsSendResult.rejected),- recorder: log,- );-- analytics.track('Agent Created');- analytics.track('signed_in');- await analytics.flush();-- // Newest first, so the refused one leads.- expect(log.entries.first.name, 'signed_in');- expect(log.entries.first.status, AnalyticsEventStatus.refused);- // Dropped before the queue, so it never reached the wire — and it is on- // the screen at all, which is the point: an event the app itself refused- // is otherwise indistinguishable from one nobody tracked.- expect(log.entries.last.name, 'Agent Created');- expect(log.entries.last.status, AnalyticsEventStatus.dropped);- expect(log.entries.last.payload, isNull);- });-- test('the buffer keeps the newest and drops the rest', () {- final log = AnalyticsLogStream(maxEntries: 3);- for (var i = 0; i < 5; i++) {- log.queued('event_$i', const {}, DateTime.utc(2026, 1, 1, 9, i));- }-- expect(log.entries.map((e) => e.name), ['event_4', 'event_3', 'event_2']);-- log.clear();- expect(log.entries, isEmpty);- });-}diff --git a/desktop/test/navigation_events_test.dart b/desktop/test/navigation_events_test.dartdeleted file mode 100644index 11d6d23ac..000000000--- a/desktop/test/navigation_events_test.dart+++ /dev/null@@ -1,119 +0,0 @@-// Which DOOR opened a Settings pane.-//-// Settings is reachable several ways, and a bare count of a pane answers-// almost nothing: the account menu, the ⌘D shortcut and the settings rail-// itself are different visits.-//-// What is pinned here is the part a refactor breaks silently: that every door-// says which one it is.-import 'package:flutter/material.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:harness/analytics/analytics.dart';-import 'package:harness/analytics/analytics_sink.dart';-import 'package:harness/auth/auth_session.dart';-import 'package:harness/core/config.dart';-import 'package:harness/settings/settings_screen.dart';-import 'package:harness/settings/settings_section.dart';-import 'package:harness/state/app_state.dart';--/// Keeps every tracked event — the same recorder `agent_events_test` uses.-class _Recording implements Analytics {- final List<({String name, Map<String, Object?> params})> events = [];-- List<Map<String, Object?>> allOf(String name) => [- for (final event in events)- if (event.name == name) event.params,- ];-- @override- void track(String name, {Map<String, Object?> params = const {}}) =>- events.add((name: name, params: params));-- @override- Future<void> flush() async {}-- @override- Future<void> close() async {}-}--void main() {- TestWidgetsFlutterBinding.ensureInitialized();-- late _Recording tracked;-- setUp(() {- tracked = _Recording();- setAnalyticsForTest(tracked);- });-- // Put back, or every later test in the run reports into this list.- tearDown(() => setAnalyticsForTest(null));-- group('screen_view carries the door', () {- Future<void> openSettings(- WidgetTester tester, {- required String source,- SettingsSection? initialSection,- }) async {- final notifier = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- );- addTearDown(notifier.dispose);- await tester.pumpWidget(- MaterialApp(- home: Builder(- builder: (context) => Scaffold(- body: TextButton(- onPressed: () => showSettingsScreen(- context,- notifier,- initialSection: initialSection,- source: source,- ),- child: const Text('open'),- ),- ),- ),- ),- );- await tester.tap(find.text('open'));- await tester.pumpAndSettle();- }-- testWidgets('the pane Settings opens on names the door that opened it', (- tester,- ) async {- await openSettings(- tester,- source: 'account_menu',- initialSection: SettingsSection.shortcuts,- );-- expect(tracked.allOf('screen_view'), [- {'screen': 'settings_shortcuts', 'source': 'account_menu'},- ]);- });-- testWidgets('moving between panes reports the rail, not the first door', (- tester,- ) async {- await openSettings(- tester,- source: 'account_menu',- initialSection: SettingsSection.shortcuts,- );- await tester.tap(find.text('Account'));- await tester.pumpAndSettle();-- // Two visits, two sources: the door into Settings, then the rail. A- // second view that inherited `account_menu` would report every pane a- // reader wandered through as having been opened from the account menu.- expect(tracked.allOf('screen_view'), [- {'screen': 'settings_shortcuts', 'source': 'account_menu'},- {'screen': 'settings_account', 'source': 'rail'},- ]);- });- });-}diff --git a/desktop/test/profile_startup_test.dart b/desktop/test/profile_startup_test.dartindex 40b644aa1..45613407f 100644--- a/desktop/test/profile_startup_test.dart+++ b/desktop/test/profile_startup_test.dart@@ -1,7 +1,6 @@import 'dart:async';import 'package:flutter_test/flutter_test.dart';-import 'package:harness/analytics/analytics.dart';import 'package:harness/api/api_client.dart';import 'package:harness/auth/auth_session.dart';import 'package:harness/auth/cli_login.dart';@@ -170,12 +169,8 @@ void main() {api = _Api();connection = _Connection();app = _App(api, connection);- analyticsAccount.clear();- });- tearDown(() {- disposeApp();- analyticsAccount.clear();});+ tearDown(disposeApp);for (final signingIn in [false, true]) {test(@@ -484,7 +479,6 @@ void main() {// what left. What must not survive is the old account's identity.expect(app.signedIn, isFalse);expect(app.currentUser, isNull);- expect(analyticsAccount.current.id, isNull);expect(app.machines, isEmpty);expect(connection.requests, isEmpty);});@@ -524,7 +518,6 @@ void main() {await _tick();expect(profileNotifications, 1);expect(app.currentUser!.id, 'current');- expect(analyticsAccount.current.id, 'current');expect(api.lists, hasLength(1));expect(connection.requests.where((r) => r == 'agents_list'),@@ -581,7 +574,6 @@ void main() {await newLogin;await _tick();expect(app.currentUser!.id, 'new');- expect(analyticsAccount.current.id, 'new');expect(app.signingIn, isFalse);expect(app.machinesLoading, isFalse);},@@ -616,7 +608,6 @@ void main() {await _tick();expect(app.currentUser, isNull);expect(app.machines, isEmpty);- expect(analyticsAccount.current.id, isNull);expect(connection.requests, isEmpty);},);diff --git a/desktop/test/settings_section_test.dart b/desktop/test/settings_section_test.dartindex 822769f35..bd3c4103d 100644--- a/desktop/test/settings_section_test.dart+++ b/desktop/test/settings_section_test.dart@@ -1,4 +1,4 @@-// Debug and Tracking are developer furniture, so a shipped build hides them. The flag behind that+// Debug is developer furniture, so a shipped build hides it. The flag behind that// is a compile-time const and a test run has it ON — which is the whole difficulty, since the// shape worth guarding is the one no test build has. `settingsGroupsFor` takes the gate as an// argument for exactly this.@@ -17,7 +17,7 @@ void main() {expect(kDebugSurfaceEnabled, isTrue, reason: 'tests run in debug mode');expect(sectionsOf(settingsGroups),- containsAll([SettingsSection.debug, SettingsSection.tracking]),+ contains(SettingsSection.debug),);});diff --git a/desktop/test/tracking_section_test.dart b/desktop/test/tracking_section_test.dartdeleted file mode 100644index 34ff7b847..000000000--- a/desktop/test/tracking_section_test.dart+++ /dev/null@@ -1,247 +0,0 @@-// Settings ▸ Tracking. What matters here is the pane's job as a *reader*: the-// newest event first, a way to tell a sent event from a refused one, and a-// header that says why nothing is arriving — a screen that renders "muted" and-// "quiet" the same is the screen that sends somebody looking for a bug in the-// analytics stack.-import 'package:flutter/material.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:harness/analytics/analytics_log.dart';-import 'package:harness/analytics/analytics_sink.dart';-import 'package:harness/settings/sections/debug_filter_bar.dart';-import 'package:harness/settings/sections/tracking_section.dart';-import 'package:harness/settings/sections/tracking_tile.dart';-import 'package:harness/settings/settings_section.dart';-import 'package:harness/shared/theme/app_theme.dart';-import 'package:harness/shared/widgets/empty_state.dart';--/// The probe every test here passes: the real one reads-/// `~/.harness/desktop-app/analytics.json`, which no widget test may do.-AnalyticsStreamStatus _live() => AnalyticsStreamStatus(- endpoint: Uri.parse('https://example.invalid/api/v1/event_tracking'),- offReason: null,- deviceId: 'computer-abc',- sessionId: 'visit-1',-);--AnalyticsStreamStatus _muted() => AnalyticsStreamStatus(- endpoint: Uri.parse('https://example.invalid/api/v1/event_tracking'),- offReason: 'This build carries no analytics key.',- deviceId: 'computer-abc',- sessionId: '',-);--/// One settled row, as the queue would have left it.-AnalyticsLogEntry _record(- AnalyticsLogStream log,- String name, {- Map<String, Object?> params = const {},- required AnalyticsEventStatus status,- Map<String, Object?>? payload,- String? note,-}) {- final id = log.queued(name, params, DateTime.utc(2026, 1, 1, 9));- if (payload != null) log.attempted(id, payload);- log.settled(id, status, note: note);- return log.entries.firstWhere((entry) => entry.id == id);-}--void main() {- Future<void> pumpTracking(- WidgetTester tester,- AnalyticsLogStream log, {- AnalyticsStreamStatus Function() probe = _live,- }) async {- tester.view.physicalSize = const Size(1000 * 2, 760 * 2);- tester.view.devicePixelRatio = 2;- addTearDown(tester.view.reset);- await tester.pumpWidget(- MaterialApp(- theme: buildAppTheme(brightness: Brightness.light),- home: Builder(- builder: (context) {- AppTheme.brightness.value = Brightness.light;- return BrightnessScope(- child: Scaffold(- body: TrackingSection(log: log, probe: probe),- ),- );- },- ),- ),- );- await tester.pumpAndSettle();- }-- testWidgets('lists what was tracked, newest first', (tester) async {- final log = AnalyticsLogStream();- _record(log, 'app_opened', status: AnalyticsEventStatus.sent);- _record(- log,- 'screen_view',- params: const {'screen': 'settings_tracking'},- status: AnalyticsEventStatus.sent,- );- await pumpTracking(tester, log);-- final tiles = tester.widgetList<TrackingTile>(find.byType(TrackingTile));- expect(tiles.map((tile) => tile.entry.name), ['screen_view', 'app_opened']);- expect(find.text('2 events'), findsOneWidget);- // The params are on the row, because thirty `screen_view`s are otherwise- // one row repeated.- expect(find.textContaining('screen=settings_tracking'), findsOneWidget);- });-- testWidgets('the Failed lens keeps the refused and the dropped', (- tester,- ) async {- final log = AnalyticsLogStream();- _record(log, 'app_opened', status: AnalyticsEventStatus.sent);- _record(- log,- 'signed_in',- status: AnalyticsEventStatus.refused,- note: 'the server refused it',- );- _record(- log,- 'agent_created',- status: AnalyticsEventStatus.dropped,- note: 'the queue was full',- );- await pumpTracking(tester, log);-- await tester.tap(- find.descendant(- of: find.byType(DebugFilterBar),- matching: find.text('Failed'),- ),- );- await tester.pumpAndSettle();-- final tiles = tester.widgetList<TrackingTile>(find.byType(TrackingTile));- expect(tiles.map((tile) => tile.entry.name), [- 'agent_created',- 'signed_in',- ]);- });-- testWidgets('Waiting keeps only what has not settled', (tester) async {- final log = AnalyticsLogStream();- log.queued('signed_in', const {}, DateTime.utc(2026, 1, 1, 9));- _record(log, 'app_opened', status: AnalyticsEventStatus.sent);- await pumpTracking(tester, log);-- await tester.tap(- find.descendant(- of: find.byType(DebugFilterBar),- matching: find.text('Waiting'),- ),- );- await tester.pumpAndSettle();-- expect(find.byType(TrackingTile), findsOneWidget);- expect(- tester.widget<TrackingTile>(find.byType(TrackingTile)).entry.name,- 'signed_in',- );- });-- testWidgets('an empty list says nothing was tracked, not "no matches"', (- tester,- ) async {- await pumpTracking(tester, AnalyticsLogStream());-- expect(find.text('No events yet'), findsOneWidget);- expect(find.byType(EmptyState), findsOneWidget);- });-- testWidgets('a filter that hides everything says so instead', (tester) async {- final log = AnalyticsLogStream();- _record(log, 'app_opened', status: AnalyticsEventStatus.sent);- await pumpTracking(tester, log);-- await tester.tap(- find.descendant(- of: find.byType(DebugFilterBar),- matching: find.text('Waiting'),- ),- );- await tester.pumpAndSettle();-- expect(find.text('No matches'), findsOneWidget);- expect(find.text('No events yet'), findsNothing);- });-- testWidgets('Clear empties the list, and is dead while it is empty', (- tester,- ) async {- final log = AnalyticsLogStream();- _record(log, 'app_opened', status: AnalyticsEventStatus.sent);- await pumpTracking(tester, log);-- await tester.tap(find.text('Clear'));- await tester.pumpAndSettle();-- expect(log.entries, isEmpty);- expect(find.byType(TrackingTile), findsNothing);- // Pressing it again is a no-op rather than an error.- await tester.tap(find.text('Clear'));- await tester.pumpAndSettle();- expect(find.text('0 events'), findsOneWidget);- });-- testWidgets('a row opens the payload the line could not hold', (- tester,- ) async {- final log = AnalyticsLogStream();- _record(- log,- 'agent_created',- params: const {'engine': 'claude'},- status: AnalyticsEventStatus.sent,- payload: const {- 'event_name': 'agent_created',- 'data': {'session_id': 'visit-1'},- },- );- await pumpTracking(tester, log);-- await tester.tap(find.byType(TrackingTile));- await tester.pumpAndSettle();-- expect(find.byType(Dialog), findsOneWidget);- // The body as it went out — which is the difference between this dialog- // and the row above it.- expect(find.textContaining('"session_id": "visit-1"'), findsOneWidget);- });-- group('the header card', () {- testWidgets('says the stream is reporting, and under which ids', (- tester,- ) async {- await pumpTracking(tester, AnalyticsLogStream());-- expect(find.text('Reporting'), findsOneWidget);- expect(find.text('computer-abc'), findsOneWidget);- expect(find.text('visit-1'), findsOneWidget);- });-- testWidgets('a muted build says so in a sentence, not by staying empty', (- tester,- ) async {- await pumpTracking(tester, AnalyticsLogStream(), probe: _muted);-- expect(find.text('Off'), findsOneWidget);- expect(find.text('This build carries no analytics key.'), findsOneWidget);- // "Not yet" and "we could not read it" must not print the same.- expect(find.text('starts with the first event'), findsOneWidget);- });- });-- group('the section itself', () {- test('is listed where the debug surface is on, which a test build is', () {- final sections = [for (final group in settingsGroups) ...group.sections];- expect(sections, contains(SettingsSection.tracking));- });- });-}diff --git a/mobile/README.md b/mobile/README.mdindex 235618e70..cb8ff0546 100644--- a/mobile/README.md+++ b/mobile/README.md@@ -35,7 +35,7 @@ The app it runs now lives under `lib/`, in the same folders the desktop app uses| `lib/auth/`, `lib/viewer/` | SSO, device linking, and the viewer's stand-ins for the harness CLI || `lib/e2ee/` | the end-to-end encryption this app terminates itself || `lib/terminal/`, `lib/widgets/` | the xterm session, the terminal panel and its chrome |-| `lib/shared/`, `lib/analytics/`, `lib/logging/` | design system, analytics, file logs |+| `lib/shared/`, `lib/logging/` | design system, file logs || `third_party/xterm/` | the vendored, patched xterm 4.0.0 (see its `README.autonomous.md`) |Two folders are this package's own, and have no counterpart on the desktop:diff --git a/mobile/lib/analytics/analytics.dart b/mobile/lib/analytics/analytics.dartdeleted file mode 100644index 7ef5a2f09..000000000--- a/mobile/lib/analytics/analytics.dart+++ /dev/null@@ -1,54 +0,0 @@-import 'analytics_config.dart';--export 'analytics_events.dart';-export 'analytics_sink.dart' show analytics, analyticsAccount;--/// The app's behavioural-event sink.-///-/// Ported from Grid (`lib/infrastructure/analytics/`) rather than rewritten, so-/// the two desktop apps report into one stream in one shape — see-/// [AnalyticsConfig] for the destination and why it is shared.-///-/// Not to be confused with the Harness CLI's `harness analytics`. That is a-/// different product: aggregate usage metering (turns per engine per day)-/// uploaded to the Harness backend. This is what a person *did* in this window,-/// and the two never meet.-///-/// Every call site talks to this, never to the transport underneath, so-/// tracking can be muted (opt-out, a test run, a build with no key) by handing-/// out a [NoopAnalytics] instead of by checking a flag at each call site.-///-/// Nothing here throws and nothing here is awaited by the UI: an analytics-/// problem must never be something the user finds out about.-abstract interface class Analytics {- /// Queue one event. [name] must be `snake_case`- /// (`analyticsEventNamePattern`) or it is dropped with a warning in the- /// debug log — the backend would accept it silently and leave the stream- /// unqueryable.- ///- /// [params] is free-form, but it is a *product* record, not a debug dump:- /// never put message text, prompts, terminal output, file contents or- /// absolute paths in it.- void track(String name, {Map<String, Object?> params});-- /// Send whatever is queued now, instead of waiting on the retry timer.- Future<void> flush();-- /// Final, time-boxed drain, then release the connection. Called when the app- /// quits; the instance is spent afterwards.- Future<void> close();-}--/// Does nothing, for a muted app and for tests.-class NoopAnalytics implements Analytics {- const NoopAnalytics();-- @override- void track(String name, {Map<String, Object?> params = const {}}) {}-- @override- Future<void> flush() async {}-- @override- Future<void> close() async {}-}diff --git a/mobile/lib/analytics/analytics_client.dart b/mobile/lib/analytics/analytics_client.dartdeleted file mode 100644index b5a2037f9..000000000--- a/mobile/lib/analytics/analytics_client.dart+++ /dev/null@@ -1,99 +0,0 @@-import 'dart:async';-import 'dart:convert';-import 'dart:io';--import 'analytics_config.dart';--/// What one send attempt came to.-enum AnalyticsSendResult {- /// The server took it.- sent,-- /// Worth trying again with the same body — a timeout, an offline machine, a- /// 429 or a 5xx. The event stays at the head of the queue.- retry,-- /// The server refused the event itself (a 4xx that isn't 408 or 429). Sending- /// it again would fail identically, so it is dropped and logged: that is our- /// instrumentation being wrong, not the network.- rejected,-}--/// Posts one event to Autonomous Analytics.-///-/// An interface rather than a bare function so the queue can be exercised-/// against a fake, which is how `test/analytics_test.dart` reaches every branch-/// without a socket.-abstract interface class AnalyticsClient {- /// Sends [payload] as `POST …/event_tracking`. Never throws; a transport- /// failure comes back as [AnalyticsSendResult.retry].- Future<AnalyticsSendResult> send(Map<String, Object?> payload);-- /// Releases the underlying connection. Called once, when the app quits.- void dispose();-}--/// Real [AnalyticsClient] over `dart:io` [HttpClient].-///-/// Deliberately not the app's Dio [ApiClient]: that one carries the CLI's base-/// URL and unwraps `{success, data|error}` envelopes, neither of which applies-/// to a third-party ingest host. One [HttpClient] for the life of the app, so a-/// burst of events reuses the connection instead of paying a TLS handshake per-/// click.-class HttpAnalyticsClient implements AnalyticsClient {- HttpAnalyticsClient(this._config);-- final AnalyticsConfig _config;- HttpClient? _client;- bool _disposed = false;-- @override- Future<AnalyticsSendResult> send(Map<String, Object?> payload) async {- if (_disposed) return AnalyticsSendResult.rejected;- try {- final body = utf8.encode(jsonEncode(payload));- final request = await _http().postUrl(_config.endpoint);- request.headers.set(HttpHeaders.authorizationHeader, _config.writeKey);- request.headers.set(HttpHeaders.contentTypeHeader, 'application/json');- request.contentLength = body.length;- request.add(body);- final response = await request.close().timeout(- AnalyticsLimits.requestTimeout,- );- // Drained rather than read: the response body says nothing the app acts- // on, but an undrained socket is one that never returns to the pool.- await response.drain<void>();- return _resultFor(response.statusCode);- } on TimeoutException {- return AnalyticsSendResult.retry;- } on SocketException {- return AnalyticsSendResult.retry;- } on HttpException {- return AnalyticsSendResult.retry;- } on Object {- // Anything left (a bad URL, a TLS failure) would fail the same way every- // time, so it is the event that goes, not the queue behind it.- return AnalyticsSendResult.rejected;- }- }-- @override- void dispose() {- _disposed = true;- _client?.close(force: true);- _client = null;- }-- HttpClient _http() =>- _client ??= (HttpClient()- ..connectionTimeout = const Duration(seconds: 10));-- /// 408 and 429 are "come back later", not "you are wrong" — they retry with- /// the rest of the transport failures.- static AnalyticsSendResult _resultFor(int status) => switch (status) {- >= 200 && < 300 => AnalyticsSendResult.sent,- 408 || 429 => AnalyticsSendResult.retry,- >= 500 => AnalyticsSendResult.retry,- _ => AnalyticsSendResult.rejected,- };-}diff --git a/mobile/lib/analytics/analytics_config.dart b/mobile/lib/analytics/analytics_config.dartdeleted file mode 100644index 84187c6c9..000000000--- a/mobile/lib/analytics/analytics_config.dart+++ /dev/null@@ -1,170 +0,0 @@-import 'dart:io';--import 'package:flutter/foundation.dart';--import '../core/test_run.dart';--/// Where behavioural events go, whether they go at all, and under what limits.-///-/// The destination is **Autonomous Analytics** — the same event stream the-/// website and the Grid desktop app report into. Sharing the destination is the-/// point: someone who read the site, installed Grid and then installed Harness-/// is one funnel, not three datasets that can never be joined. [category] is-/// what keeps them apart within it.-///-/// ⚠️ **This app reports under GRID's write key, not one of its own.** The-/// constant below is the same one `autonomous-grid-app` ships, so both desktop-/// apps append into the same analytics project. That is a deliberate stopgap —-/// a muted stream measures nothing, and this app has been waiting on a key of-/// its own since the port — but the cost is real and worth stating: the two-/// apps are then separable **only by [category]** (`harness-desktop` against-/// Grid's `grid-app`, stamped on every event), not at the source. Anyone-/// reading the Grid project sees this app's events inside it, and anything set-/// per project — a quota, a retention rule, a rotated or revoked key — lands on-/// both apps at once.-///-/// TODO(BE): swap in a Harness Desktop key from the analytics owner. It is a-/// one-constant change here, and it is the only thing that separates the two-/// streams properly.-///-/// The key is a *write* key rather than a secret. The website ships the same-/// kind of key in its public JS bundle, a desktop binary can be unpacked either-/// way, and it only lets the holder append events.-class AnalyticsConfig {- const AnalyticsConfig({- required this.endpoint,- required this.writeKey,- this.offReason,- });-- /// The full `…/api/v1/event_tracking` URL one event is POSTed to. Autonomous- /// Analytics takes a single event per request — there is no batch route — so- /// the queue sends serially rather than in batches.- final Uri endpoint;-- /// Sent verbatim as `Authorization`, with no `Bearer` prefix — that is what- /// the web client does and what the server reads.- final String writeKey;-- /// Why nothing is being sent, or null when the stream is live. A sentence- /// rather than a bool, because it is the answer to "why is nothing arriving"- /// and a developer can lose an hour to that question.- final String? offReason;-- /// Whether events are queued and sent at all.- bool get enabled => offReason == null;-- /// Stamped on every event, so this app's stream stays separable from Grid's- /// and the website's inside the shared project. Grid sends `grid-app`.- static const String category = 'harness-desktop-v2';-- /// Env var / `--dart-define` names. The URL and key overrides are dev-only so- /// a shipped build always reports to production; [disableEnvKey] is honoured- /// everywhere, because a user who wants to be left alone has to be able to- /// say so in a release build.- static const String urlEnvKey = 'HARNESS_ANALYTICS_URL';- static const String keyEnvKey = 'HARNESS_ANALYTICS_KEY';- static const String disableEnvKey = 'HARNESS_ANALYTICS_DISABLED';-- // `String.fromEnvironment` needs a const literal, so the names above can't be- // used here — keep the two in step by hand.- static const String _urlDefine = String.fromEnvironment(- 'HARNESS_ANALYTICS_URL',- );- static const String _keyDefine = String.fromEnvironment(- 'HARNESS_ANALYTICS_KEY',- );-- static const String _defaultBaseUrl =- 'https://autonomous-analytics-qffztaoryq-uc.a.run.app/api/v1';- static const String _path = 'event_tracking';-- /// Borrowed from Grid until this app has its own — see the class TODO(BE).- /// Keep it byte-for-byte equal to `autonomous-grid-app`'s- /// `AnalyticsConfig._defaultWriteKey`; a copy that drifts sends this app's- /// events to a project nobody is reading.- static const String _defaultWriteKey = 'tBCs0oLwgFgf1borYn54cjHz4fvWahyV';-- /// The live configuration, from the environment alone.- static AnalyticsConfig resolve() {- final base = (_devOverride(urlEnvKey) ?? _defaultBaseUrl).replaceFirst(- RegExp(r'/+$'),- '',- );- final key = _devOverride(keyEnvKey) ?? _defaultWriteKey;- return AnalyticsConfig(- endpoint: Uri.parse('$base/$_path'),- writeKey: key,- offReason: _offReason(key),- );- }-- static String? _offReason(String key) {- if (key.isEmpty) {- return 'This build carries no analytics key '- '(set $keyEnvKey to turn the stream on).';- }- if (_muted) return '$disableEnvKey is set in this environment.';- if (_underTest) return 'Running under flutter test.';- return null;- }-- /// True when `HARNESS_ANALYTICS_DISABLED` is set to anything truthy.- static bool get _muted {- final value = Platform.environment[disableEnvKey]?.toLowerCase().trim();- return value == '1' || value == 'true' || value == 'yes';- }-- /// Tests here build a real `AppNotifier` and drive real controllers, so one- /// that happens to track an event must not open a socket or touch- /// `~/.harness` to do it. See [kUnderTest] for the whole of why.- static bool get _underTest => kUnderTest;-- /// [key]'s override — `--dart-define` first, then the process env — ignored- /// in release so a shipped build can only ever report to production.- static String? _devOverride(String key) {- if (kReleaseMode) return null;- final define = switch (key) {- urlEnvKey => _urlDefine,- keyEnvKey => _keyDefine,- _ => '',- };- if (define.isNotEmpty) return define;- final value = Platform.environment[key];- return (value != null && value.isNotEmpty) ? value : null;- }-}--/// The limits the queue and the payload are held to.-///-/// [sessionIdle] matches the website's and Grid's 15 minutes on purpose: a-/// "visit" has to mean the same span everywhere or the streams cannot be-/// compared. The rest are a desktop app's own — one quit offline and reopened-/// on a plane needs a bounded queue and a backoff, which a page that unloads-/// after a few minutes never did.-class AnalyticsLimits {- const AnalyticsLimits._();-- /// Events kept while the server is unreachable. Past this the oldest go —- /// a full queue is a signal, and the newest events describe it best.- static const int queueCap = 500;-- /// Params per event, and the length of any one string value. The backend- /// truncates and drops on its own; doing it here keeps what we send and what- /// lands identical, so a value read back in analysis is the value we meant.- static const int paramsMaxKeys = 40;- static const int paramsMaxStringLength = 500;-- /// How long a visit survives without an event before a new one starts.- static const Duration sessionIdle = Duration(minutes: 15);-- static const Duration requestTimeout = Duration(seconds: 10);-- /// First retry delay, doubled up to [retryDelayMax] while sends keep failing.- static const Duration retryDelay = Duration(seconds: 2);- static const Duration retryDelayMax = Duration(minutes: 2);-- /// How long a quit waits for the queue to drain. A wedged network must never- /// be what keeps the window on screen after the user pressed ⌘Q.- static const Duration closeDeadline = Duration(seconds: 3);-}diff --git a/mobile/lib/analytics/analytics_event.dart b/mobile/lib/analytics/analytics_event.dartdeleted file mode 100644index ad588468a..000000000--- a/mobile/lib/analytics/analytics_event.dart+++ /dev/null@@ -1,200 +0,0 @@-import 'dart:convert';--import 'package:flutter/foundation.dart';--import 'analytics_config.dart';--/// The name rule this app holds itself to: `snake_case`, 3–64 characters.-///-/// Autonomous Analytics accepts anything — the website sends whole sentences-/// (`"Click button add to cart"`) — which is exactly why a rule is worth having-/// here. A stream where the same action is called three things is a stream-/// nobody can query, and the app is the only place that can prevent it.-final RegExp analyticsEventNamePattern = RegExp(r'^[a-z][a-z0-9_]{2,63}$');--/// The machine, the build and the OS an event happened on. Resolved once per-/// launch and attached to every event.-@immutable-class AnalyticsContext {- const AnalyticsContext({- required this.platform,- required this.appVersion,- required this.appBuild,- required this.osVersion,- required this.arch,- required this.locale,- required this.release,- });-- /// `macos`, `windows` or `linux`. The website sends `web` in this field; the- /// app says which desktop it is, because that is the first question asked of- /// a desktop funnel.- final String platform;-- final String appVersion;-- /// The `+N` build behind [appVersion]. Note that this app's `pubspec.yaml`- /// version is a placeholder — the published version comes from the remote GCS- /// manifest — so this field tells builds apart, it does not name a release.- final String appBuild;-- final String osVersion;-- /// `macosArm64`, `macosX64`, … — an Intel Mac and an Apple Silicon one are- /// different products as far as running agents and models locally goes.- final String arch;-- final String locale;-- /// False in a developer build. Sent on every event so analysis can drop the- /// noise our own machines make instead of guessing at it.- final bool release;-- /// Stand-in for a context that could not be read, so an event still goes out- /// with its name and identity rather than being dropped over a version- /// lookup.- static const AnalyticsContext unknown = AnalyticsContext(- platform: '',- appVersion: '',- appBuild: '',- osVersion: '',- arch: '',- locale: '',- release: kReleaseMode,- );-- /// The context as event params. Empty strings are dropped downstream, so a- /// half-resolved context costs the missing fields and nothing else.- Map<String, Object?> asParams() => {- 'app_version': appVersion.isEmpty ? null : appVersion,- 'app_build': appBuild.isEmpty ? null : appBuild,- 'os': platform.isEmpty ? null : platform,- 'os_version': osVersion.isEmpty ? null : osVersion,- 'arch': arch.isEmpty ? null : arch,- 'locale': locale.isEmpty ? null : locale,- 'build': release ? 'release' : 'debug',- };-}--/// Who an event belongs to and which visit it is part of.-@immutable-class AnalyticsIdentity {- const AnalyticsIdentity({- required this.pseudoId,- required this.sessionId,- this.userId,- this.userEmail,- });-- /// The device id — stable for the life of the machine, present whether or not- /// anyone is signed in. See `AnalyticsIdentityStore`.- final String pseudoId;-- /// The visit id, rotated after quiet (`AnalyticsLimits.sessionIdle`).- final String sessionId;-- /// The signed-in account, or null before sign-in. The account id the CLI- /// reports through `api.me()` — stable, and not something a user typed.- final String? userId;-- /// Sent as a param, mirroring the website, so the same person can be found in- /// both streams. Null while signed out.- final String? userEmail;-}--/// One event, as it sits in the queue and goes on the wire.-@immutable-class AnalyticsEvent {- const AnalyticsEvent({- required this.name,- required this.params,- required this.at,- required this.identity,- });-- final String name;- final Map<String, Object?> params;-- /// When the event *happened*, not when it was flushed — a queue that drains- /// after a reconnect must not report an hour of activity as one instant.- final DateTime at;-- final AnalyticsIdentity identity;-}--/// The Autonomous Analytics request body for [event].-///-/// Pure, so the wire format is checked by reading one function rather than by-/// watching a queue. The shape is the web client's: an envelope naming the-/// event and its timestamp, with everything else under `data`, and the params-/// as a `{key, value}` list.-///-/// `user_id` goes in both `data` and the params, as it does on the web — most-/// queries read the params table, and dropping it from there would make the-/// app's events the only ones that cannot be filtered by account.-Map<String, Object?> analyticsPayload(- AnalyticsEvent event,- AnalyticsContext context,-) {- final identity = event.identity;- // Merged as a map, not appended to a list: a later key simply wins, so an- // event that wants to say more about `model` than the context did needs no- // de-duplication pass afterwards (the web has one because it uses a list).- final params = <String, Object?>{- ...context.asParams(),- 'user_id': identity.userId,- 'user_email': identity.userEmail,- ...event.params,- 'category': AnalyticsConfig.category,- };- return {- 'event_name': event.name,- 'event_timestamp': event.at.millisecondsSinceEpoch ~/ 1000,- 'data': {- 'session_id': identity.sessionId,- 'user_pseudo_id': identity.pseudoId,- if (identity.userId != null) 'user_id': identity.userId,- 'platform': context.platform,- 'event_params': analyticsParams(params),- },- };-}--/// [params] as the wire's `{key, value}` list: nulls dropped, nested values-/// JSON-encoded, long strings clipped, and never more than-/// `AnalyticsLimits.paramsMaxKeys` entries.-List<Map<String, Object?>> analyticsParams(Map<String, Object?> params) {- final out = <Map<String, Object?>>[];- for (final entry in params.entries) {- final value = entry.value;- if (value == null) continue;- if (value is String && value.isEmpty) continue;- if (out.length >= AnalyticsLimits.paramsMaxKeys) break;- out.add({'key': entry.key, 'value': analyticsValue(value)});- }- return out;-}--/// One param value the backend can store: a string, a number or a bool.-/// Anything else is JSON-encoded (the website does the same), and anything long-/// is clipped to `AnalyticsLimits.paramsMaxStringLength`.-Object analyticsValue(Object value) {- final encoded = switch (value) {- String() || num() || bool() => value,- _ => _encode(value),- };- if (encoded is! String) return encoded;- return encoded.length > AnalyticsLimits.paramsMaxStringLength- ? encoded.substring(0, AnalyticsLimits.paramsMaxStringLength)- : encoded;-}--/// JSON, or the value's own `toString` when it isn't encodable — a param that-/// cannot be serialised must cost that param, never the event.-String _encode(Object value) {- try {- return jsonEncode(value);- } on Object {- return value.toString();- }-}diff --git a/mobile/lib/analytics/analytics_events.dart b/mobile/lib/analytics/analytics_events.dartdeleted file mode 100644index e04a81582..000000000--- a/mobile/lib/analytics/analytics_events.dart+++ /dev/null@@ -1,111 +0,0 @@-import 'analytics.dart';--/// The events this app sends, one method each.-///-/// An extension rather than a set of loose helpers, so every [Analytics]-/// implementation gets them for free — and so the name and the params of an-/// event are written down **once**. Two call sites that name the same action-/// differently is the failure mode this exists to prevent.-///-/// Adding an event: add a method here, keep the name `snake_case`, and keep the-/// params to product facts — a short code, an option, a count. **Never** a-/// prompt, terminal output, an agent's name, a repository path or a machine-/// hostname. This stream describes what someone did, not what they wrote or-/// what their machines are called; ids are fine, the names people give things-/// are not.-extension AnalyticsEvents on Analytics {- // --- The launch ----------------------------------------------------------- /// The app came up. [signedIn] separates a returning user from someone who- /// is about to meet the login screen.- void appOpened({required bool signedIn}) =>- track('app_opened', params: {'signed_in': signedIn});-- /// The app is quitting, after [open]. Sent on the way out, so it is the last- /// thing the queue drains.- void appClosed({required Duration open}) =>- track('app_closed', params: {'open_seconds': open.inSeconds});-- /// A screen was opened. [screen] is the section's stable name, never its- /// label — labels are rewritten weekly and a renamed label would read as a- /// new screen.- ///- /// [source] is the DOOR that was used, and it is `required` for the reason- /// `new_agent_opened`'s is: a screen with several ways in tells you almost- /// nothing as a bare count.- ///- /// Values: `account_menu` and `shortcut` (a door that OPENED Settings on this- /// pane); `rail` (moved here from another pane, using the settings rail).- void screenView(String screen, {required String source}) =>- track('screen_view', params: {'screen': screen, 'source': source});-- // --- Sign-in -------------------------------------------------------------- /// Sign-in completed.- void signedIn() => track('signed_in');-- /// Sign-in didn't complete. [reason] is a short code — `cancelled`,- /// `failed` — never the error text, which can carry a path or a host name.- void signInFailed(String reason) =>- track('sign_in_failed', params: {'reason': reason});-- /// The user signed out.- void signedOut() => track('signed_out');-- // --- Agents -------------------------------------------------------------- //- // How many people open the New agent dialog, how many of those finish it,- // and how many of THOSE ever send the agent a message. Each step is a- // separate event carrying the same device and user id, so the funnel is- // built by counting distinct people per step.-- /// The New agent dialog was opened. [source] is which door was used —- /// `machine_row` (the `+` on a machine's row), `rail_empty` (the button the- /// empty rail shows), `pane_empty` (the button in the empty centre pane) or- /// `shortcut` (⌘N and the app menu).- ///- /// Sent by `showNewAgentDialog` itself rather than by its callers, so a door- /// added later cannot forget to report itself.- void newAgentOpened({required String source}) =>- track('new_agent_opened', params: {'source': source});-- /// An agent was created from the New agent dialog. [engine] is the engine id- /// and [bypassPermission] whether its own guardrails were switched off, both- /// product facts.- ///- /// The working folder is deliberately absent: it is an absolute path, which- /// this stream never carries.- void agentCreated({required String engine, required bool bypassPermission}) =>- track(- 'agent_created',- params: {'engine': engine, 'bypass_permission': bypassPermission},- );-- /// The first message of a signed-in session — how long it took this person to- /// get from being logged in to actually talking to an agent, whichever agent- /// that turned out to be.- ///- /// **Once per sign-in, not per agent.** Which agent it was is- /// [agentCreated]'s question; this one is about the gap at the top of the- /// funnel, where somebody signs in and then does nothing.- ///- /// [from] says what started the clock, because the two populations behave- /// nothing alike: `sign_in` is a fresh log-in, `launch` is opening the app- /// with a session already on the machine. Averaging them together would hide- /// both.- ///- /// Driven by the CLI's `turn_started`, not by the composer, so a message- /// typed straight into the terminal counts the same as one sent from the box- /// underneath it — which is how most people drive these engines.- ///- /// ⚠️ **No message text, ever**, and no agent, machine or folder either. Who- /// it was and when are already on every event (`user_email`,- /// `event_timestamp`); what this adds is the wait.- void appFirstMessage({- required String from,- required int secondsSinceLogin,- }) => track(- 'app_first_message',- params: {'from': from, 'seconds_since_login': secondsSinceLogin},- );-}diff --git a/mobile/lib/analytics/analytics_identity.dart b/mobile/lib/analytics/analytics_identity.dartdeleted file mode 100644index 74dbe737e..000000000--- a/mobile/lib/analytics/analytics_identity.dart+++ /dev/null@@ -1,188 +0,0 @@-import 'dart:convert';-import 'dart:io';-import 'dart:math';--import '../core/harness_file_store.dart';-import 'analytics_config.dart';--/// The device id and the visit id every event carries, kept in-/// `~/.harness/desktop-app/analytics.json`.-///-/// Two ids, two lifetimes. The **device id** is minted once and never reset —-/// it is what ties a person's first launch to the day they finally ran an-/// agent, across sign-in and sign-out. The **visit id** rotates after-/// `AnalyticsLimits.sessionIdle` of quiet, which is how a session is counted.-///-/// The file also carries the user's own switch: `{"enabled": false}` mutes the-/// app, and is preserved by every write here so turning it off stays off.-///-/// Its own file rather than a key in [HarnessFileStore]'s `state.json`: that-/// store is async, serialised behind a lock and holds credentials, while this-/// is read synchronously on the first event of a launch and is the one piece of-/// app state a user may reasonably want to open and edit by hand.-///-/// Lenient like the other app stores — a missing, corrupt or hand-edited file-/// reads as "no ids yet" rather than throwing, because the alternative is an-/// analytics detail breaking the launch it was meant to measure. Both files are-/// overridable so tests never touch a real Harness home.-class AnalyticsIdentityStore {- AnalyticsIdentityStore({File? file, File? computerIdFile, Random? random})- : _file = file ?? File('${HarnessFileStore.defaultDirectoryPath()}/$_name'),- _computerIdFile = computerIdFile ?? File(_defaultComputerIdPath()),- _random = random ?? Random.secure();-- static const String _name = 'analytics.json';-- final File _file;- final File _computerIdFile;- final Random _random;-- _StoredIdentity? _state;-- /// `last_active_ms` as the file holds it — what [_persistEvery] is measured- /// from. Not the in-memory clock: that moves on every event, so events closer- /// together than a minute would each find the last one "too recent" and the- /// file would never be brought forward at all.- int _savedActive = 0;-- /// How stale the on-disk `last_active_ms` is allowed to get. A write per event- /// would be an fsync per click; the cost of lagging is that a restart after a- /// long quiet spell may start a new visit up to a minute early, which is- /// noise beside a 15-minute window.- static const Duration _persistEvery = Duration(minutes: 1);-- /// `~/.harness/computer-id` — the machine identity this app already shares- /// with the CLI (the desktop's `LocalCliDiscovery.defaultComputerIdPath`).- /// Resolved the same way rather than imported, so an analytics detail cannot- /// drag the WS layer into every test that builds this store.- static String _defaultComputerIdPath() =>- '${Directory(HarnessFileStore.defaultDirectoryPath()).parent.path}'- '/computer-id';-- /// Whether the user turned tracking off in- /// `~/.harness/desktop-app/analytics.json`.- bool get optedOut => _load().optedOut;-- /// The ids as they stand, without starting a visit or moving the clock.- /// `sessionId` is empty until the first event of a launch has been tracked.- ({String pseudoId, String sessionId}) peek() {- final state = _load();- return (pseudoId: state.pseudoId, sessionId: state.sessionId);- }-- /// The ids for an event happening at [now], rotating the visit after a quiet- /// spell and persisting sparingly (see [_persistEvery]).- ({String pseudoId, String sessionId}) touch(DateTime now) {- final state = _load();- final at = now.millisecondsSinceEpoch;- final expired =- state.sessionId.isEmpty ||- at - state.lastActive > AnalyticsLimits.sessionIdle.inMilliseconds;- final next = _StoredIdentity(- pseudoId: state.pseudoId,- sessionId: expired ? _uuidV4(_random) : state.sessionId,- lastActive: at,- optedOut: state.optedOut,- );- _state = next;- if (expired || at - _savedActive >= _persistEvery.inMilliseconds) {- _persist(next);- }- return (pseudoId: next.pseudoId, sessionId: next.sessionId);- }-- _StoredIdentity _load() {- final cached = _state;- if (cached != null) return cached;- var json = const <String, Object?>{};- try {- if (_file.existsSync()) {- final decoded = jsonDecode(_file.readAsStringSync());- if (decoded is Map) json = decoded.cast<String, Object?>();- }- } on Object {- // Corrupt or hand-edited: start over rather than fail the launch.- }- final stored = (json['user_pseudo_id'] as String?)?.trim();- final state = _StoredIdentity(- pseudoId: stored != null && stored.isNotEmpty ? stored : _newPseudoId(),- sessionId: (json['session_id'] as String?) ?? '',- lastActive: (json['last_active_ms'] as num?)?.toInt() ?? 0,- optedOut: json['enabled'] == false,- );- _state = state;- _savedActive = state.lastActive;- return state;- }-- /// A fresh device id: this computer's Harness id when it has one, else a new- /// UUID.- ///- /// Borrowing `computer-id` rather than minting a second one is what lets an- /// event be lined up with the machine the backend knows about. It is copied- /// here on first use and then never re-read, so a later re-registration that- /// rewrites that file cannot silently turn this machine into a second- /// visitor.- String _newPseudoId() => _computerId() ?? _uuidV4(_random);-- String? _computerId() {- try {- if (!_computerIdFile.existsSync()) return null;- final id = _computerIdFile.readAsStringSync().trim();- return id.isEmpty ? null : id;- } on Object {- return null;- }- }-- /// Writes the ids back, `enabled` included so a user's opt-out survives.- void _persist(_StoredIdentity state) {- // Moved on the attempt, not only on success: a home that cannot be written- // is tried again a minute later, not on every event in between.- _savedActive = state.lastActive;- try {- _file.parent.createSync(recursive: true);- _file.writeAsStringSync(- const JsonEncoder.withIndent(' ').convert({- 'user_pseudo_id': state.pseudoId,- 'session_id': state.sessionId,- 'last_active_ms': state.lastActive,- 'enabled': !state.optedOut,- }),- flush: true,- );- } on Object {- // A read-only home or a full disk costs id stability across restarts,- // not the event in hand.- }- }-}--/// What `analytics.json` holds, as one immutable value.-class _StoredIdentity {- const _StoredIdentity({- required this.pseudoId,- required this.sessionId,- required this.lastActive,- required this.optedOut,- });-- final String pseudoId;- final String sessionId;-- /// Epoch ms of the last tracked event.- final int lastActive;- final bool optedOut;-}--/// A random v4 UUID — the id format both this stream and the CLI already use.-/// `Random.secure` so two machines starting in the same millisecond cannot be-/// handed the same device id.-String _uuidV4(Random random) {- final bytes = List<int>.generate(16, (_) => random.nextInt(256));- bytes[6] = (bytes[6] & 0x0f) | 0x40;- bytes[8] = (bytes[8] & 0x3f) | 0x80;- final hex = bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join();- return '${hex.substring(0, 8)}-${hex.substring(8, 12)}-'- '${hex.substring(12, 16)}-${hex.substring(16, 20)}-${hex.substring(20)}';-}diff --git a/mobile/lib/analytics/analytics_lifecycle.dart b/mobile/lib/analytics/analytics_lifecycle.dartdeleted file mode 100644index 3a1f6a3f7..000000000--- a/mobile/lib/analytics/analytics_lifecycle.dart+++ /dev/null@@ -1,70 +0,0 @@-import 'dart:ui' show AppExitResponse;--import 'package:flutter/widgets.dart';--import '../stats/harness_stats.dart';-import 'analytics.dart';--/// Closes the launch out: `app_closed`, then a time-boxed drain of whatever is-/// still queued. Renders [child] unchanged.-///-/// Only `didRequestAppExit` is hooked, which covers ⌘Q, the app menu's Quit and-/// an OS log-out. Grid also intercepts the window's close button, but that-/// needs `windowManager.setPreventClose(true)` and a matching `destroy()` call-/// — and a bug on that path leaves a window the user cannot close. A missing-/// `app_closed` is worth less than that risk, so this app takes the exit hook-/// alone; `app_opened` is unaffected either way.-///-/// The matching `app_opened` is NOT here. It is sent by `AppNotifier` when-/// bootstrap resolves, because `signed_in` is not known until the CLI has been-/// asked, and a first-frame event would report every launch as signed out.-class AnalyticsLifecycle extends StatefulWidget {- const AnalyticsLifecycle({super.key, required this.child});-- final Widget child;-- @override- State<AnalyticsLifecycle> createState() => _AnalyticsLifecycleState();-}--class _AnalyticsLifecycleState extends State<AnalyticsLifecycle>- with WidgetsBindingObserver {- /// When this launch started, so the quit event can say how long the app was- /// open.- final DateTime _openedAt = DateTime.now();-- /// Guards against a quit that somehow asks twice.- bool _closed = false;-- @override- void initState() {- super.initState();- WidgetsBinding.instance.addObserver(this);- }-- @override- void dispose() {- WidgetsBinding.instance.removeObserver(this);- super.dispose();- }-- @override- Future<AppExitResponse> didRequestAppExit() async {- if (!_closed) {- _closed = true;- analytics.appClosed(open: DateTime.now().difference(_openedAt));- // Before the drain below, and awaited: this is a local file write that- // finishes in milliseconds, and it is the ONLY place a turn still running- // at quit gets its time counted — the debounce timer is cancelled by the- // process exiting, not fired by it.- await harnessStats.flush();- // Time-boxed inside `close` itself — a wedged network must never be what- // keeps the window on screen after the user pressed ⌘Q.- await analytics.close();- }- return AppExitResponse.exit;- }-- @override- Widget build(BuildContext context) => widget.child;-}diff --git a/mobile/lib/analytics/analytics_log.dart b/mobile/lib/analytics/analytics_log.dartdeleted file mode 100644index 15a3ef6f7..000000000--- a/mobile/lib/analytics/analytics_log.dart+++ /dev/null@@ -1,216 +0,0 @@-import 'dart:async';-import 'dart:collection';-import 'dart:convert';--import 'package:flutter/foundation.dart';--/// Where one tracked event got to.-enum AnalyticsEventStatus {- /// In the queue: never sent, or sent and waiting on a retry.- queued,-- /// The server took it.- sent,-- /// The server refused it (a 4xx that isn't 408/429) — our instrumentation is- /// wrong, not the network.- refused,-- /// Never reached the wire: an invalid name, a full queue, or a build whose- /// stream is muted.- dropped,-}--/// One tracked event as Settings ▸ Tracking shows it: what was tracked, what-/// went over the wire, and how it ended.-///-/// Mutable in place, like [LogEntry] and unlike Grid's immutable-/// `AnalyticsLogEntry`: Grid rebuilds through `copyWith` because Riverpod-/// compares state objects, while this buffer is a [ChangeNotifier] and an event-/// that is still retrying collects its attempts on the entry it already has.-class AnalyticsLogEntry {- AnalyticsLogEntry({- required this.id,- required this.name,- required this.params,- required this.queuedAt,- });-- /// Monotonic within a session — the handle the queue settles a row by.- final int id;-- final String name;-- /// The params as the call site passed them, before the context and the- /// identity are merged in. [payload] is what actually went out.- final Map<String, Object?> params;-- final DateTime queuedAt;-- AnalyticsEventStatus status = AnalyticsEventStatus.queued;-- /// How many times this event has been put on the wire. Two or more means the- /// endpoint failed and the queue retried, which is the thing this screen- /// exists to make visible.- int attempts = 0;-- /// The exact JSON body sent, re-indented, or null before the first attempt.- String? payload;-- /// Why it ended the way it did, when the status alone doesn't say.- String? note;-- DateTime? settledAt;-- /// How long from being tracked to being settled, or null while it waits.- Duration? get took => settledAt?.difference(queuedAt);-}--/// The recorder the analytics queue reports to.-///-/// An interface so the queue stays free of the screen, and so a release build —-/// which has no Tracking screen — pays nothing for it. The same seam-/// `AnalyticsClient` gives the transport.-abstract interface class AnalyticsLog {- /// Records an event entering the queue; returns its id for the calls below.- int queued(String name, Map<String, Object?> params, DateTime at);-- /// Records that [payload] has just gone on the wire for entry [id]. Called- /// once per attempt, so the count reads as retries.- ///- /// Takes the payload as the map the queue already built rather than as a- /// string: encoding it is the recorder's business, and a build with nothing- /// recording must not pay for a `jsonEncode` per event.- void attempted(int id, Map<String, Object?> payload);-- /// Records how entry [id] ended.- void settled(int id, AnalyticsEventStatus status, {String? note});-}--/// Records nothing — what a release build gets, so the queue can run with no-/// screen watching.-class NoopAnalyticsLog implements AnalyticsLog {- const NoopAnalyticsLog();-- @override- int queued(String name, Map<String, Object?> params, DateTime at) => 0;-- @override- void attempted(int id, Map<String, Object?> payload) {}-- @override- void settled(int id, AnalyticsEventStatus status, {String? note}) {}-}--/// The events this session tracked, newest first — a bounded ring, fed by-/// `QueuedAnalytics` and read by Settings ▸ Tracking.-///-/// In memory only, and deliberately: this is a window onto a queue that is-/// itself in memory, and a stream that measures the app must not become a-/// second thing the app writes to disk on every click. It is the one place the-/// question analytics always raises can be answered — *did that event actually-/// leave, and what was in it?* — because an event that was never sent, sent-/// with a missing field, or refused by the server looks exactly like an event-/// that landed: the app is silent either way, by design.-class AnalyticsLogStream extends ChangeNotifier implements AnalyticsLog {- AnalyticsLogStream({this.maxEntries = 200});-- /// How many events the buffer keeps. Smaller than [LogStream]'s 500: one row- /// here is one deliberate product event, not a socket frame, and a session- /// that has tracked two hundred of them has long since answered the question- /// this screen was opened with.- final int maxEntries;-- final List<AnalyticsLogEntry> _entries = [];- int _seq = 0;- bool _notifyScheduled = false;-- /// Newest first — the order the Tracking list reads in.- late final UnmodifiableListView<AnalyticsLogEntry> entries =- UnmodifiableListView(_entries);-- @override- int queued(String name, Map<String, Object?> params, DateTime at) {- final id = ++_seq;- _entries.insert(- 0,- AnalyticsLogEntry(- id: id,- name: name,- // Copied, so a caller that reuses its map cannot rewrite history here.- params: Map<String, Object?>.unmodifiable(params),- queuedAt: at,- ),- );- if (_entries.length > maxEntries) {- _entries.removeRange(maxEntries, _entries.length);- }- _scheduleNotify();- return id;- }-- @override- void attempted(int id, Map<String, Object?> payload) {- final entry = _entryFor(id);- if (entry == null) return;- entry.attempts += 1;- entry.payload = _pretty(payload);- _scheduleNotify();- }-- @override- void settled(int id, AnalyticsEventStatus status, {String? note}) {- final entry = _entryFor(id);- if (entry == null) return;- entry.status = status;- entry.note = note;- entry.settledAt = DateTime.now();- _scheduleNotify();- }-- void clear() {- if (_entries.isEmpty) return;- _entries.clear();- _scheduleNotify();- }-- /// An event settles near where it was queued, and the newest rows are at the- /// front — so this walks a handful of entries, not the buffer. Null once a- /// row has been pushed out by [maxEntries] or dropped by [clear], which the- /// callers treat as "nothing left to update" rather than as an error.- AnalyticsLogEntry? _entryFor(int id) {- for (final entry in _entries) {- if (entry.id == id) return entry;- }- return null;- }-- /// One notification per microtask, however many rows changed in it — the- /// same rhythm [LogStream] keeps, for the same reason: a queue draining after- /// a reconnect settles a run of events in one pass.- void _scheduleNotify() {- if (_notifyScheduled) return;- _notifyScheduled = true;- scheduleMicrotask(() {- _notifyScheduled = false;- notifyListeners();- });- }-- /// The body as it went out, re-indented so the dialog can be read.- ///- /// A payload that will not encode costs its own readability and nothing else- /// — this is a debug view of an event that has *already been sent*, and- /// throwing here would take the row with it.- static String _pretty(Map<String, Object?> payload) {- try {- return const JsonEncoder.withIndent(' ').convert(payload);- } on Object {- return payload.toString();- }- }-}--/// This session's tracked events. Fed only where the Tracking screen exists —-/// see `analyticsRecorder` in `analytics_sink.dart`.-final AnalyticsLogStream analyticsLog = AnalyticsLogStream();diff --git a/mobile/lib/analytics/analytics_service.dart b/mobile/lib/analytics/analytics_service.dartdeleted file mode 100644index b5cd69d55..000000000--- a/mobile/lib/analytics/analytics_service.dart+++ /dev/null@@ -1,224 +0,0 @@-import 'dart:async';-import 'dart:collection';--import 'package:flutter/foundation.dart';--import 'analytics.dart';-import 'analytics_client.dart';-import 'analytics_config.dart';-import 'analytics_event.dart';-import 'analytics_identity.dart';-import 'analytics_log.dart';--/// Who is signed in, asked fresh at track time — a session that starts signed-/// out and ends signed in must not report the whole visit as anonymous.-typedef AnalyticsUserLookup = ({String? id, String? email}) Function();--/// [Analytics] that queues in memory and sends serially, with retry.-///-/// Autonomous Analytics takes one event per request, so this is a queue with a-/// worker rather than a batcher. The order of the three failure paths is the-/// point: a **transport** failure keeps the event and backs off, a **refusal**-/// drops it (resending changes nothing), and a queue that grows past-/// `AnalyticsLimits.queueCap` drops its oldest — the newest events are the ones-/// that describe what is happening now.-///-/// Not persisted across launches: a machine quit while offline loses what was-/// still queued. That is a deliberate limit, not an oversight — the alternative-/// is a spool file that outlives an uninstall.-///-/// Ported from Grid, [recorder] included: Settings ▸ Tracking is this app's-/// version of Grid's Tracking tab, and it is fed from here rather than from a-/// second stream, so a row on that screen is an event this queue really held.-class QueuedAnalytics implements Analytics {- QueuedAnalytics({- required this.client,- required this.identityStore,- required this.contextFuture,- required this.userLookup,- this.recorder = const NoopAnalyticsLog(),- this.clock = DateTime.now,- });-- /// The collaborators, public because they arrive through the constructor and- /// a test that swaps one has no reason to reach past the door it came in by.- /// Named apart from the locals they produce (`context`, the account) so a- /// method body cannot quietly shadow one of them.- final AnalyticsClient client;- final AnalyticsIdentityStore identityStore;- final Future<AnalyticsContext> contextFuture;- final AnalyticsUserLookup userLookup;-- /// Where the Tracking screen reads this queue from. A [NoopAnalyticsLog] in- /// a release build, so nothing is retained for a screen that is not there.- final AnalyticsLog recorder;-- final DateTime Function() clock;-- /// Each queued event beside the id of its row on the Tracking screen, so the- /// row can be settled without the wire model carrying a debug field.- final Queue<({AnalyticsEvent event, int logId})> _queue =- Queue<({AnalyticsEvent event, int logId})>();-- AnalyticsContext? _resolvedContext;- Future<void>? _draining;- Timer? _retryTimer;- Duration _retryDelay = AnalyticsLimits.retryDelay;- bool _warnedFull = false;- bool _closed = false;-- /// How many events are waiting to go out. Test seam, and the one honest- /// answer to "did that call actually queue anything".- @visibleForTesting- int get pending => _queue.length;-- @override- void track(String name, {Map<String, Object?> params = const {}}) {- if (_closed) return;- final now = clock();- if (!analyticsEventNamePattern.hasMatch(name)) {- const reason = 'names must be snake_case, 3-64 characters';- // Recorded before it is refused, so the Tracking screen shows the mistake- // rather than nothing at all — an event that never lands is exactly what- // somebody would open that screen to explain.- recorder.settled(- recorder.queued(name, params, now),- AnalyticsEventStatus.dropped,- note: reason,- );- debugPrint('analytics: ignored event "$name" — $reason');- return;- }- try {- final ids = identityStore.touch(now);- final account = userLookup();- _queue.add((- event: AnalyticsEvent(- name: name,- params: params,- at: now,- identity: AnalyticsIdentity(- pseudoId: ids.pseudoId,- sessionId: ids.sessionId,- userId: account.id,- userEmail: account.email,- ),- ),- logId: recorder.queued(name, params, now),- ));- _trim();- unawaited(_pump());- } on Object catch (error) {- debugPrint('analytics: dropped event "$name" — $error');- }- }-- @override- Future<void> flush() {- _cancelRetry();- return _pump();- }-- @override- Future<void> close() async {- if (_closed) return;- _cancelRetry();- await _pump().timeout(AnalyticsLimits.closeDeadline, onTimeout: () {});- _closed = true;- client.dispose();- }-- /// Drops the oldest events once the queue is over its cap, warning once per- /// outage so a plane ride doesn't fill the log with the same line.- void _trim() {- if (_queue.length <= AnalyticsLimits.queueCap) return;- while (_queue.length > AnalyticsLimits.queueCap) {- recorder.settled(- _queue.removeFirst().logId,- AnalyticsEventStatus.dropped,- note: 'the queue was full',- );- }- if (_warnedFull) return;- _warnedFull = true;- debugPrint(- 'analytics: event queue full (${AnalyticsLimits.queueCap}) — dropping '- 'the oldest; the endpoint has been unreachable for a while',- );- }-- /// One drain at a time: concurrent callers share the in-flight future rather- /// than starting a second worker on the same queue.- Future<void> _pump() {- if (_closed || _queue.isEmpty) return Future.value();- return _draining ??= _drain().whenComplete(() => _draining = null);- }-- Future<void> _drain() async {- final context = _resolvedContext ??= await contextFuture.catchError(- (Object _) => AnalyticsContext.unknown,- );- while (_queue.isNotEmpty && !_closed) {- final queued = _queue.first;- final event = queued.event;- final AnalyticsSendResult result;- try {- final payload = analyticsPayload(event, context);- recorder.attempted(queued.logId, payload);- result = await client.send(payload);- } on Object catch (error) {- // The client's contract says it never throws; if it ever does, the- // queue must not be left spinning on the same event forever.- _queue.remove(queued);- recorder.settled(- queued.logId,- AnalyticsEventStatus.dropped,- note: '$error',- );- debugPrint('analytics: send failed for "${event.name}" — $error');- continue;- }- switch (result) {- // ⚠️ `remove(queued)`, never `removeFirst()`: the send above is- // awaited, and a queue that filled up meanwhile has already trimmed- // this event off its head (see [_trim]). Removing whatever is first- // NOW would drop the next event unsent, and without a row saying so.- case AnalyticsSendResult.sent:- _queue.remove(queued);- recorder.settled(queued.logId, AnalyticsEventStatus.sent);- _retryDelay = AnalyticsLimits.retryDelay;- _warnedFull = false;- case AnalyticsSendResult.rejected:- _queue.remove(queued);- recorder.settled(- queued.logId,- AnalyticsEventStatus.refused,- note: 'the server refused it',- );- debugPrint(- 'analytics: server refused "${event.name}" — the event was dropped',- );- case AnalyticsSendResult.retry:- _scheduleRetry();- return;- }- }- }-- void _scheduleRetry() {- if (_retryTimer != null || _closed) return;- _retryTimer = Timer(_retryDelay, () {- _retryTimer = null;- unawaited(_pump());- });- final doubled = _retryDelay * 2;- _retryDelay = doubled > AnalyticsLimits.retryDelayMax- ? AnalyticsLimits.retryDelayMax- : doubled;- }-- void _cancelRetry() {- _retryTimer?.cancel();- _retryTimer = null;- }-}diff --git a/mobile/lib/analytics/analytics_sink.dart b/mobile/lib/analytics/analytics_sink.dartdeleted file mode 100644index 9d386728c..000000000--- a/mobile/lib/analytics/analytics_sink.dart+++ /dev/null@@ -1,161 +0,0 @@-import 'dart:async';-import 'dart:ffi' show Abi;-import 'dart:io';--import 'package:flutter/foundation.dart';-import 'package:package_info_plus/package_info_plus.dart';--import '../logging/debug_surface.dart';-import 'analytics.dart';-import 'analytics_client.dart';-import 'analytics_config.dart';-import 'analytics_event.dart';-import 'analytics_identity.dart';-import 'analytics_log.dart';-import 'analytics_service.dart';--/// The app's one analytics sink.-///-/// A lazily-built singleton rather than a Riverpod provider, for the same-/// reason `terminalFontStore` is: the call sites have no-/// common ancestor short of `MaterialApp` — `main`, `AppNotifier`, a settings-/// pane, a menu item inside a pane header — and most of them are plain widgets-/// that were handed a notifier, not a `Ref`.-///-/// [NoopAnalytics] whenever tracking is off — no key in this build, the-/// environment muted it, the code is under `flutter test`, or the user opted-/// out in `~/.harness/desktop-app/analytics.json` — so a muted app and a test-/// run open no sockets at all rather than queueing into a void.-Analytics get analytics => _analytics ??= _build();--Analytics? _analytics;--/// Replaces the sink, for tests. Returns what was there, so a test can put it-/// back; passing null re-arms the lazy build.-@visibleForTesting-Analytics? setAnalyticsForTest(Analytics? value) {- final previous = _analytics;- _analytics = value;- return previous;-}--Analytics _build() {- // The environment is asked first, and on purpose: under `flutter test` this- // returns before anything reads `~/.harness`, so a widget test that happens- // to track an event touches neither the network nor a real Harness home.- final config = AnalyticsConfig.resolve();- if (config.offReason case final reason?) return _muted(reason);- final identity = AnalyticsIdentityStore();- if (identity.optedOut) return _muted(kAnalyticsOptedOutReason);- return QueuedAnalytics(- client: HttpAnalyticsClient(config),- identityStore: identity,- contextFuture: resolveAnalyticsContext(),- userLookup: () => analyticsAccount.current,- recorder: analyticsRecorder,- );-}--/// A muted sink that still shows its work where there is a screen to show it-/// on, and a plain [NoopAnalytics] where there is not.-///-/// A build can be muted for four reasons — no key, `HARNESS_ANALYTICS_DISABLED`,-/// `flutter test`, or the user's own opt-out (see [AnalyticsConfig]) — and a-/// Tracking screen that were permanently empty for any of them is the exact-/// trap that screen exists to spring. Every event still lands in the list,-/// settled as `dropped` with [reason], which turns "nothing is arriving" into a-/// sentence.-///-/// Nothing recorded here leaves the machine: the buffer is in memory, and a-/// build with no [kDebugSurfaceEnabled] keeps none of it. That is what makes it-/// right to record even for a user who opted out — their choice is about what-/// we *send*, and this sends nothing.-Analytics _muted(String reason) => kDebugSurfaceEnabled- ? MutedAnalytics(analyticsLog, reason)- : const NoopAnalytics();--/// Where the queue reports its rows: this session's buffer where the Tracking-/// screen exists, nothing at all where it does not.-AnalyticsLog get analyticsRecorder =>- kDebugSurfaceEnabled ? analyticsLog : const NoopAnalyticsLog();--/// Why a sink is muted when the user turned it off by hand.-const String kAnalyticsOptedOutReason =- 'Tracking is switched off in ~/.harness/desktop-app/analytics.json.';--/// [Analytics] that records what was tracked and sends none of it.-///-/// Not a subclass of [QueuedAnalytics] with the transport stubbed out: this-/// must not touch [AnalyticsIdentityStore], so a muted build reads no Harness-/// home and mints no ids for a stream that will never carry them.-class MutedAnalytics implements Analytics {- MutedAnalytics(this.recorder, this.reason, {this.clock = DateTime.now});-- final AnalyticsLog recorder;-- /// The sentence the Tracking screen puts on every row, and the one its header- /// card leads with.- final String reason;-- final DateTime Function() clock;-- @override- void track(String name, {Map<String, Object?> params = const {}}) {- // Settled the instant it is queued: there is no wire and no retry, so a row- // that sat at "Waiting" would be describing a queue that does not exist.- recorder.settled(- recorder.queued(name, params, clock()),- AnalyticsEventStatus.dropped,- note: reason,- );- }-- @override- Future<void> flush() async {}-- @override- Future<void> close() async {}-}--/// Who events are filed under.-///-/// `AppNotifier` writes it when sign-in resolves and clears it on sign-out; the-/// queue reads it fresh per event, so a visit that begins signed out and ends-/// signed in is not reported as anonymous throughout.-final AnalyticsAccount analyticsAccount = AnalyticsAccount();--/// The signed-in account, as the wire wants it. Mutable and global on purpose —-/// see [analyticsAccount].-class AnalyticsAccount {- ({String? id, String? email}) current = (id: null, email: null);-- void set({String? id, String? email}) => current = (id: id, email: email);-- void clear() => current = (id: null, email: null);-}--/// The machine and build an event happened on, resolved once per launch.-///-/// Never fails: a version lookup that throws costs those fields, not the-/// stream. The queue awaits this once, before its first send, so the first-/// event of a launch already carries the version rather than racing it.-Future<AnalyticsContext> resolveAnalyticsContext() async {- var version = '';- var build = '';- try {- final info = await PackageInfo.fromPlatform();- version = info.version;- build = info.buildNumber;- } on Object {- // A bundle we can't read is worth an anonymous version, not a lost event.- }- return AnalyticsContext(- platform: Platform.operatingSystem,- appVersion: version,- appBuild: build,- osVersion: Platform.operatingSystemVersion,- arch: Abi.current().toString(),- locale: Platform.localeName,- release: kReleaseMode,- );-}diff --git a/mobile/lib/app_shell.dart b/mobile/lib/app_shell.dartindex 648623a90..437248283 100644--- a/mobile/lib/app_shell.dart+++ b/mobile/lib/app_shell.dart@@ -2,7 +2,7 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_riverpod/flutter_riverpod.dart';-import 'analytics/analytics_lifecycle.dart';+import 'stats/stats_lifecycle.dart';import 'core/crash_log.dart';import 'state/app_state.dart';import 'viewer/viewer_services.dart';@@ -158,7 +158,7 @@ class HarnessApp extends StatelessWidget {maxScaleFactor: scale,child: _GridTokenScope(child: child ?? const SizedBox.shrink()),),- home: AnalyticsLifecycle(+ home: StatsLifecycle(child: RootShell(authenticatedScreen: authenticatedScreen,signedOutScreen: signedOutScreen,diff --git a/mobile/lib/logging/app_log.dart b/mobile/lib/logging/app_log.dartindex bf5f5d650..d619003be 100644--- a/mobile/lib/logging/app_log.dart+++ b/mobile/lib/logging/app_log.dart@@ -9,8 +9,7 @@ enum AppLogLevel { debug, info, warn, error }////// Ported from Grid, with one change: Riverpod out, a singleton in. The call/// sites here are `main`, `AppNotifier`, `WsConn` and the CLI runner, and most-/// were never handed a `Ref` — the same reasoning that made `analytics` a-/// singleton (see `analytics/analytics.dart`).+/// were never handed a `Ref`.////// **Distinct from [CrashLog], and both are kept.** `CrashLog` answers "what/// threw", in one file, forever, with a full stack; this answers "what was the@@ -132,7 +131,7 @@ class FileAppLog implements AppLog {}/// No-op [AppLog]. The default, so a `flutter test` run never writes into a real-/// `~/.harness` — the same rule analytics follows, and for the same reason.+/// `~/.harness`.class NoopAppLog implements AppLog {const NoopAppLog();diff --git a/mobile/lib/logging/debug_surface.dart b/mobile/lib/logging/debug_surface.dartindex 08095bb8b..57932905d 100644--- a/mobile/lib/logging/debug_surface.dart+++ b/mobile/lib/logging/debug_surface.dart@@ -1,8 +1,7 @@import 'package:flutter/foundation.dart';-/// Whether this build shows its developer surfaces: Settings ▸ Debug and its-/// ⌘D shortcut, Settings ▸ Tracking, and the two in-memory buffers that feed-/// them (`logStream`, `analyticsLog`).+/// Whether this build shows its developer surfaces: Settings ▸ Debug, its ⌘D+/// shortcut, and the in-memory buffer that feeds it (`logStream`).////// A debug build has it; a release build does not. The log *files* are written/// either way — a shipped app that has no stderr anyone reads is exactly thediff --git a/mobile/lib/logging/install.dart b/mobile/lib/logging/install.dartindex 3d534cfe7..0b79ef0e4 100644--- a/mobile/lib/logging/install.dart+++ b/mobile/lib/logging/install.dart@@ -12,8 +12,7 @@ const String kAppLogBase = 'app';////// Called once from `main()`. Nothing else calls it, which is what keeps the/// suite honest: the app log defaults to a no-op, so `flutter test` cannot-/// write into a real Harness home no matter which code path it exercises — the-/// same rule analytics follows.+/// write into a real Harness home no matter which code path it exercises.////// Deliberately not `async`: the first lines this app writes are the ones about/// starting up, and awaiting a directory probe here would lose them.diff --git a/mobile/lib/logging/log_stream.dart b/mobile/lib/logging/log_stream.dartindex 3b824ea36..cdee499ce 100644--- a/mobile/lib/logging/log_stream.dart+++ b/mobile/lib/logging/log_stream.dart@@ -96,7 +96,7 @@ class LogCommand {/// most recent entries, newest first.////// Fed by `StreamAppLog`, read by Settings ▸ Debug. A singleton-/// like `appLog` and `analytics`, and for the same reason: the things that+/// like `appLog`, and for the same reason: the things that/// write to it — the socket and the HTTP clients — hold no `Ref`/// and no notifier between them.class LogStream extends ChangeNotifier {diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex 54b618833..c933ab08c 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -6,7 +6,6 @@ import 'package:xterm/xterm.dart' show Terminal;import 'package:flutter/foundation.dart';import 'package:flutter_riverpod/flutter_riverpod.dart';-import '../analytics/analytics.dart';import '../teams/team_controller.dart';import '../api/api_client.dart';import '../viewer/direct_auth_api.dart';@@ -330,16 +329,6 @@ class AppNotifier extends ChangeNotifier {sessionPreviews.markStale(previewKey(machine.machine.machineId, agent));}- /// When this launch became signed in, and by which route — until the first- /// message of that session has been reported, after which it is null.- ///- /// One record for the whole app, not one per agent: the question is how long- /// somebody sits signed in before talking to anything at all, and which agent- /// they finally picked is `agent_created`'s business. A session where nobody- /// ever sends a message simply leaves this set until sign-out or quit, which- /// is exactly the population the event exists to measure the absence of.- ({DateTime at, String from})? _awaitingFirstMessage;-final Map<String, Timer> _offlineRetryTimers = {};// Safety-net reconciliation for a connected machine's agent list, on top of the push events// (agent_synced/agent_created/agent_renamed/agent_deleted) that normally keep it live — catches the@@ -1215,30 +1204,9 @@ class AppNotifier extends ChangeNotifier {currentUser = null;status = AppStatus.unauthenticated;notifyListeners();- } finally {- // A `finally` rather than a call per exit path: bootstrap resolves three- // ways (signed out, signed in, thrown) and the launch happened in all- // three.- _trackAppOpened();}}- bool _appOpenedTracked = false;-- /// `app_opened`, once, with the answer bootstrap actually reached. Sent from- /// here rather than from the first frame because `signed_in` is not known- /// until the session has been read, and a first-frame event would report- /// every launch as signed out.- void _trackAppOpened() {- if (_appOpenedTracked) return;- _appOpenedTracked = true;- final signedIn = status == AppStatus.authenticated;- analytics.appOpened(signedIn: signedIn);- // A returning user is signed in before the app is even on screen, so their- // wait starts here rather than at a sign-in that never happens.- if (signedIn) _armFirstMessage('launch');- }-/// Whether this device is signed in, and everything behind the login screen when it is — what/// `bootstrap()` does once its config is loaded.Future<void> _checkSignIn() async {@@ -1362,7 +1330,7 @@ class AppNotifier extends ChangeNotifier {/// Who is signed in, from the account. Shared by the boot path and by the/// retry path, because a profile the boot could not read is asked for again/// there — and a session that never learns its own account has an empty- /// footer and unattributed analytics.+ /// footer.Future<void> _loadProfile() {final pending = _profileInFlight;if (pending != null) return pending;@@ -1382,12 +1350,7 @@ class AppNotifier extends ChangeNotifier {return;}if (me != null) {- final profile = CurrentUserProfile.fromMe(me);- currentUser = profile;- // Every event from here on is filed under the account, including ones- // queued while this call was still in flight — the queue reads the- // account per event, not per launch.- analyticsAccount.set(id: profile.id, email: profile.email);+ currentUser = CurrentUserProfile.fromMe(me);notifyListeners();}} catch (error) {@@ -1412,10 +1375,8 @@ class AppNotifier extends ChangeNotifier {signingIn = false;// The code was scanned into the session that just ended — see [logout].pendingPairing = null;- _awaitingFirstMessage = null;_desk.reset();zoo.reset();- analyticsAccount.clear();unawaited(_pool?.closeAll());_pool = null;_lastError = message;@@ -1424,18 +1385,10 @@ class AppNotifier extends ChangeNotifier {notifyListeners();}- /// A session was just saved: load everything behind the login screen, and- /// count the sign-in. The one road in for every way of signing in.+ /// A session was just saved: load everything behind the login screen. The+ /// one road in for every way of signing in.Future<void> _enterSignedIn(int revision) async {await _finishBootstrapSignedIn();- if (!_authWorkCurrent(revision) || status != AppStatus.authenticated) {- return;- }- analytics.signedIn();- // Restarts the clock even if `_trackAppOpened` already started one: this- // person met the login screen, so their wait begins where the launch's- // did not.- _armFirstMessage('sign_in');}/// The phone's sign-in, first step: email [email] a one-time code. Throws the@@ -1471,7 +1424,6 @@ class AppNotifier extends ChangeNotifier {} catch (_) {if (_authWorkCurrent(revision)) {status = AppStatus.unauthenticated;- analytics.signInFailed('failed');}rethrow;} finally {@@ -1502,7 +1454,6 @@ class AppNotifier extends ChangeNotifier {} catch (_) {if (_authWorkCurrent(revision)) {status = AppStatus.unauthenticated;- analytics.signInFailed('failed');}rethrow;} finally {@@ -1567,12 +1518,6 @@ class AppNotifier extends ChangeNotifier {expandedMachines.clear();selectedMachineId = null;status = AppStatus.unauthenticated;- analytics.signedOut();- // A session that ended without a message reports nothing — its absence IS- // the finding, and a stale clock would attach that wait to whoever signs in- // next.- _awaitingFirstMessage = null;- analyticsAccount.clear();notifyListeners();}@@ -3136,40 +3081,6 @@ class AppNotifier extends ChangeNotifier {);}- /// Starts the clock `app_first_message` measures. [from] is `sign_in` for a- /// fresh log-in and `launch` for an app opened with a session already there.- ///- /// One body, called by both routes and by the test seam below — a second- /// place building this record is a second place to get it wrong.- void _armFirstMessage(String from) =>- _awaitingFirstMessage = (at: DateTime.now(), from: from);-- /// Closes that clock out, once.- ///- /// A one-shot latch rather than a counter: the record is read and cleared in- /// the same breath, so every turn after the first finds nothing and there is- /// never a "which message is this" to get wrong.- ///- /// ⚠️ Called from `turn_started` ONLY, never from the other two routes into- /// [_markAgentProcessing]. A `turn_heartbeat`, and an adopted agent found- /// already mid-turn when this app connected, are both work that was under way- /// before anybody here typed anything — counting either would report a- /// near-zero wait for a returning user who has not said a word.- void _reportFirstMessage() {- if (_awaitingFirstMessage case final login?) {- _awaitingFirstMessage = null;- analytics.appFirstMessage(- from: login.from,- secondsSinceLogin: DateTime.now().difference(login.at).inSeconds,- );- }- }-- /// [_armFirstMessage], for a test: signing in needs a live CLI, and what is- /// worth pinning is what the first turn AFTER it does.- @visibleForTesting- void armFirstMessageForTest(String from) => _armFirstMessage(from);-String _turnActivityKey(String machineId, String agentId) =>'$machineId\u0000$agentId';@@ -5577,10 +5488,6 @@ class AppNotifier extends ChangeNotifier {break;case 'turn_started':case 'turn_heartbeat':- // A turn that STARTS is somebody sending something; a heartbeat is a- // turn already under way, which for an agent this app merely reconnected- // to is work nobody here just asked for.- if (type == 'turn_started') _reportFirstMessage();var changed = false;final agentId = _eventAgentId(machine, event, payload);if (agentId != null) {diff --git a/mobile/lib/stats/harness_stats.dart b/mobile/lib/stats/harness_stats.dartindex ec397616d..586808f4c 100644--- a/mobile/lib/stats/harness_stats.dart+++ b/mobile/lib/stats/harness_stats.dart@@ -186,7 +186,7 @@ class HarnessStats extends ChangeNotifier {/// The app's own counters.///-/// A singleton like `analytics` and `terminalFontStore`, for the same reason: the+/// A singleton like `appLog` and `terminalFontStore`, for the same reason: the/// call sites are `AppNotifier`'s event dispatcher and one settings pane, and/// threading an instance from one to the other would mean handing a `Ref` to a/// widget that has no other use for one.diff --git a/mobile/lib/stats/stats_lifecycle.dart b/mobile/lib/stats/stats_lifecycle.dartnew file mode 100644index 000000000..366fa10d6--- /dev/null+++ b/mobile/lib/stats/stats_lifecycle.dart@@ -0,0 +1,52 @@+import 'dart:ui' show AppExitResponse;++import 'package:flutter/widgets.dart';++import 'harness_stats.dart';++/// Writes [harnessStats] out when the app quits. Renders [child] unchanged.+///+/// Only `didRequestAppExit` is hooked, which covers ⌘Q, the app menu's Quit and+/// an OS log-out. Intercepting the window's close button needs+/// `windowManager.setPreventClose(true)` and a matching `destroy()` call — and+/// a bug on that path leaves a window the user cannot close.+class StatsLifecycle extends StatefulWidget {+ const StatsLifecycle({super.key, required this.child});++ final Widget child;++ @override+ State<StatsLifecycle> createState() => _StatsLifecycleState();+}++class _StatsLifecycleState extends State<StatsLifecycle>+ with WidgetsBindingObserver {+ bool _closed = false;++ @override+ void initState() {+ super.initState();+ WidgetsBinding.instance.addObserver(this);+ }++ @override+ void dispose() {+ WidgetsBinding.instance.removeObserver(this);+ super.dispose();+ }++ @override+ Future<AppExitResponse> didRequestAppExit() async {+ if (!_closed) {+ _closed = true;+ // Awaited: a local file write that finishes in milliseconds, and the ONLY+ // place a turn still running at quit gets its time counted — the+ // debounce timer is cancelled by the process exiting, not fired by it.+ await harnessStats.flush();+ }+ return AppExitResponse.exit;+ }++ @override+ Widget build(BuildContext context) => widget.child;+}diff --git a/mobile/test/analytics/analytics_client_test.dart b/mobile/test/analytics/analytics_client_test.dartdeleted file mode 100644index fe01ff900..000000000--- a/mobile/test/analytics/analytics_client_test.dart+++ /dev/null@@ -1,196 +0,0 @@-import 'dart:async';-import 'dart:convert';-import 'dart:io';--import 'package:flutter_test/flutter_test.dart';-import 'package:harness_mobile/analytics/analytics_client.dart';-import 'package:harness_mobile/analytics/analytics_config.dart';--/// The real transport, over a `dart:io` client that never opens a socket:-/// [HttpOverrides] hands it [_FakeClient], which answers from [_FakeClient.answer].-///-/// What is pinned is the mapping from what the ingest host did to what the-/// queue does next — send, retry or drop — because a wrong answer there either-/// loses events (a retryable failure dropped) or wedges the queue forever (a-/// refusal retried).-class _FakeClient implements HttpClient {- _FakeClient(this.answer);-- /// A status code, or something to throw from the request.- Object answer;- final requests = <_FakeRequest>[];- bool closed = false;-- @override- Duration? connectionTimeout;-- @override- Future<HttpClientRequest> postUrl(Uri url) async {- final request = _FakeRequest(url, answer);- requests.add(request);- return request;- }-- @override- void close({bool force = false}) => closed = true;-- @override- dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);-}--class _FakeRequest implements HttpClientRequest {- _FakeRequest(this.url, this.answer);-- final Uri url;- final Object answer;- final sentHeaders = <String, Object>{};- final body = <int>[];-- @override- int contentLength = -1;-- @override- HttpHeaders get headers => _FakeHeaders(sentHeaders);-- @override- void add(List<int> data) => body.addAll(data);-- @override- Future<HttpClientResponse> close() async {- final answer = this.answer;- if (answer is int) return _FakeResponse(answer);- throw answer;- }-- @override- dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);-}--class _FakeHeaders implements HttpHeaders {- _FakeHeaders(this.values);-- final Map<String, Object> values;-- @override- void set(String name, Object value, {bool preserveHeaderCase = false}) =>- values[name] = value;-- @override- dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);-}--class _FakeResponse extends Stream<List<int>> implements HttpClientResponse {- _FakeResponse(this.statusCode);-- @override- final int statusCode;-- @override- StreamSubscription<List<int>> listen(- void Function(List<int> event)? onData, {- Function? onError,- void Function()? onDone,- bool? cancelOnError,- }) => Stream<List<int>>.fromIterable([utf8.encode('{"ok":true}')]).listen(- onData,- onError: onError,- onDone: onDone,- cancelOnError: cancelOnError,- );-- @override- dynamic noSuchMethod(Invocation invocation) => super.noSuchMethod(invocation);-}--void main() {- final config = AnalyticsConfig(- endpoint: Uri.parse('https://analytics.invalid/api/v1/event_tracking'),- writeKey: 'write-key',- );-- Future<(AnalyticsSendResult, _FakeClient)> sendWith(Object answer) async {- final fake = _FakeClient(answer);- final result = await HttpOverrides.runZoned(- () => HttpAnalyticsClient(config).send({'event_name': 'app_opened'}),- createHttpClient: (_) => fake,- );- return (result, fake);- }-- test(- 'one POST to the endpoint, keyed the way the web client keys it',- () async {- final (result, fake) = await sendWith(200);-- expect(result, AnalyticsSendResult.sent);- final request = fake.requests.single;- expect(request.url, config.endpoint);- // The key verbatim — no `Bearer` — which is what the server reads.- expect(request.sentHeaders[HttpHeaders.authorizationHeader], 'write-key');- expect(- request.sentHeaders[HttpHeaders.contentTypeHeader],- 'application/json',- );- expect(jsonDecode(utf8.decode(request.body)), {- 'event_name': 'app_opened',- });- expect(request.contentLength, request.body.length);- expect(fake.connectionTimeout, const Duration(seconds: 10));- },- );-- test(- 'a 2xx is sent, "come back later" retries, a refusal is dropped',- () async {- expect((await sendWith(204)).$1, AnalyticsSendResult.sent);- expect((await sendWith(408)).$1, AnalyticsSendResult.retry);- expect((await sendWith(429)).$1, AnalyticsSendResult.retry);- expect((await sendWith(500)).$1, AnalyticsSendResult.retry);- expect((await sendWith(503)).$1, AnalyticsSendResult.retry);- expect((await sendWith(400)).$1, AnalyticsSendResult.rejected);- expect((await sendWith(401)).$1, AnalyticsSendResult.rejected);- expect((await sendWith(302)).$1, AnalyticsSendResult.rejected);- },- );-- test(- 'a phone off the network retries rather than losing the event',- () async {- expect(- (await sendWith(const SocketException('offline'))).$1,- AnalyticsSendResult.retry,- );- expect(- (await sendWith(TimeoutException('slow'))).$1,- AnalyticsSendResult.retry,- );- expect(- (await sendWith(const HttpException('reset'))).$1,- AnalyticsSendResult.retry,- );- // Anything else would fail identically every time: the event goes.- expect(- (await sendWith(const HandshakeException('bad cert'))).$1,- AnalyticsSendResult.rejected,- );- },- );-- test('one connection for the life of the app, released on dispose', () async {- final fake = _FakeClient(200);- await HttpOverrides.runZoned(() async {- final client = HttpAnalyticsClient(config);- await client.send({'event_name': 'app_opened'});- await client.send({'event_name': 'signed_in'});- client.dispose();- expect(fake.requests, hasLength(2));- expect(fake.closed, isTrue);- // Spent: nothing more goes on the wire.- expect(- await client.send({'event_name': 'signed_out'}),- AnalyticsSendResult.rejected,- );- expect(fake.requests, hasLength(2));- }, createHttpClient: (_) => fake);- });-}diff --git a/mobile/test/analytics/analytics_identity_test.dart b/mobile/test/analytics/analytics_identity_test.dartdeleted file mode 100644index 523b47dcd..000000000--- a/mobile/test/analytics/analytics_identity_test.dart+++ /dev/null@@ -1,152 +0,0 @@-import 'dart:convert';-import 'dart:io';-import 'dart:math';--import 'package:flutter_test/flutter_test.dart';-import 'package:harness_mobile/analytics/analytics_config.dart';-import 'package:harness_mobile/analytics/analytics_identity.dart';--/// `analytics.json` on a phone: the device id, the visit, and the user's own-/// switch — in a temporary home, never the real one.-void main() {- late Directory home;- late File file;- late File computerId;-- setUp(() {- home = Directory.systemTemp.createTempSync('analytics_identity_test');- file = File('${home.path}/desktop-app/analytics.json');- computerId = File('${home.path}/computer-id');- });-- tearDown(() => home.deleteSync(recursive: true));-- AnalyticsIdentityStore store({Random? random}) => AnalyticsIdentityStore(- file: file,- computerIdFile: computerId,- random: random,- );-- Map<String, Object?> saved() =>- jsonDecode(file.readAsStringSync()) as Map<String, Object?>;-- final start = DateTime.utc(2026, 9, 27, 9);- final uuid = RegExp(- r'^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$',- );-- test('a fresh phone mints a v4 device id, and no visit until an event', () {- final ids = store().peek();-- expect(ids.pseudoId, matches(uuid));- expect(ids.sessionId, isEmpty);- expect(file.existsSync(), isFalse, reason: 'peeking writes nothing');- });-- test('the machine id is borrowed when there is one', () {- computerId.writeAsStringSync(' computer-42\n');- expect(store().peek().pseudoId, 'computer-42');- });-- test('an empty machine id file is no id at all', () {- computerId.writeAsStringSync(' ');- expect(store().peek().pseudoId, matches(uuid));- });-- test('the first event starts a visit and writes both ids down', () {- final ids = store().touch(start);-- expect(ids.sessionId, matches(uuid));- expect(saved(), {- 'user_pseudo_id': ids.pseudoId,- 'session_id': ids.sessionId,- 'last_active_ms': start.millisecondsSinceEpoch,- 'enabled': true,- });- });-- test('a visit survives quiet shorter than the idle window, not longer', () {- final identity = store();- final first = identity.touch(start);-- final soon = identity.touch(- start.add(AnalyticsLimits.sessionIdle - const Duration(seconds: 1)),- );- expect(soon.sessionId, first.sessionId);-- final later = identity.touch(- start.add(- AnalyticsLimits.sessionIdle * 2 + const Duration(milliseconds: 1),- ),- );- expect(later.sessionId, isNot(first.sessionId));- expect(later.pseudoId, first.pseudoId, reason: 'the device never changes');- });-- test('the clock is written sparingly: not per event, at most per minute', () {- final identity = store();- identity.touch(start);- identity.touch(start.add(const Duration(seconds: 30)));- expect(saved()['last_active_ms'], start.millisecondsSinceEpoch);-- final minute = start.add(const Duration(minutes: 1));- identity.touch(minute);- expect(saved()['last_active_ms'], minute.millisecondsSinceEpoch);- });-- test('a busy visit still keeps the file within a minute of the clock', () {- // An event every 30 seconds for twenty minutes. Measured from the- // in-memory clock, each event found the previous one only 30s old, the- // file kept the visit's FIRST minute forever — and a relaunch 16 minutes- // in read that as a visit gone quiet and started a new one.- final identity = store();- for (var s = 0; s <= 20 * 60; s += 30) {- final now = start.add(Duration(seconds: s));- identity.touch(now);- final lag =- now.millisecondsSinceEpoch - (saved()['last_active_ms']! as int);- expect(lag, lessThan(const Duration(minutes: 1).inMilliseconds));- }- final visit = store().peek().sessionId;- final relaunch = store().touch(start.add(const Duration(minutes: 21)));- expect(relaunch.sessionId, visit);- });-- test('a relaunch picks up the same device and the same visit', () {- final first = store().touch(start);- final again = store().touch(start.add(const Duration(minutes: 2)));-- expect(again, first);- });-- test('the user\'s switch is read, and kept by every write', () {- file.parent.createSync(recursive: true);- file.writeAsStringSync(jsonEncode({'enabled': false}));- final identity = store();-- expect(identity.optedOut, isTrue);- identity.touch(start);- expect(saved()['enabled'], isFalse);- });-- test('a corrupt or hand-edited file reads as no ids yet', () {- file.parent.createSync(recursive: true);- file.writeAsStringSync('{not json');- expect(store().peek().pseudoId, matches(uuid));-- file.writeAsStringSync(jsonEncode(['a', 'list']));- expect(store().optedOut, isFalse);-- file.writeAsStringSync(jsonEncode({'user_pseudo_id': ' '}));- expect(store().peek().pseudoId, matches(uuid));- });-- test('a home that cannot be written costs id stability, never the event', () {- // The parent of the file is a FILE, so creating the directory fails.- File('${home.path}/desktop-app').writeAsStringSync('in the way');- final ids = store().touch(start);-- expect(ids.sessionId, matches(uuid));- expect(file.existsSync(), isFalse);- });-}diff --git a/mobile/test/analytics/analytics_payload_test.dart b/mobile/test/analytics/analytics_payload_test.dartdeleted file mode 100644index 199d57a84..000000000--- a/mobile/test/analytics/analytics_payload_test.dart+++ /dev/null@@ -1,361 +0,0 @@-import 'package:flutter/foundation.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:harness_mobile/analytics/analytics.dart';-import 'package:harness_mobile/analytics/analytics_config.dart';-import 'package:harness_mobile/analytics/analytics_event.dart';-import 'package:harness_mobile/analytics/analytics_log.dart';-import 'package:harness_mobile/analytics/analytics_sink.dart';-import 'package:package_info_plus/package_info_plus.dart';--/// Every call the extension makes, by name and params — the stream as the-/// queue would receive it, with no queue.-class _Recording implements Analytics {- final events = <({String name, Map<String, Object?> params})>[];-- @override- void track(String name, {Map<String, Object?> params = const {}}) =>- events.add((name: name, params: params));-- @override- Future<void> flush() async {}-- @override- Future<void> close() async {}-}--const _context = AnalyticsContext(- platform: 'ios',- appVersion: '1.0.0',- appBuild: '45',- osVersion: 'Version 26.0',- arch: 'iosArm64',- locale: 'vi_VN',- release: true,-);--AnalyticsEvent _event({- String name = 'app_opened',- Map<String, Object?> params = const {},- String? userId,- String? userEmail,-}) => AnalyticsEvent(- name: name,- params: params,- at: DateTime.fromMillisecondsSinceEpoch(1790000000999),- identity: AnalyticsIdentity(- pseudoId: 'device-1',- sessionId: 'visit-1',- userId: userId,- userEmail: userEmail,- ),-);--/// `{key: value}` back out of the wire's `[{key, value}]` list.-Map<String, Object?> _paramsOf(Map<String, Object?> payload) {- final data = payload['data']! as Map<String, Object?>;- return {- for (final entry in data['event_params']! as List<Map<String, Object?>>)- entry['key']! as String: entry['value'],- };-}--void main() {- group('the name rule', () {- test('snake_case, 3 to 64 characters, starting with a letter', () {- expect(analyticsEventNamePattern.hasMatch('app_opened'), isTrue);- expect(analyticsEventNamePattern.hasMatch('a' * 64), isTrue);- // What the website sends, and exactly what this rule exists to refuse.- expect(analyticsEventNamePattern.hasMatch('Click button'), isFalse);- expect(analyticsEventNamePattern.hasMatch('ab'), isFalse);- expect(analyticsEventNamePattern.hasMatch('a' * 65), isFalse);- expect(analyticsEventNamePattern.hasMatch('1st_event'), isFalse);- });- });-- group('the wire payload', () {- test('an envelope naming the event, with everything else under data', () {- final payload = analyticsPayload(- _event(userId: 'user-9', userEmail: '[email protected]'),- _context,- );-- expect(payload['event_name'], 'app_opened');- // Seconds, not milliseconds — and floored, so the 999ms go.- expect(payload['event_timestamp'], 1790000000);- final data = payload['data']! as Map<String, Object?>;- expect(data['session_id'], 'visit-1');- expect(data['user_pseudo_id'], 'device-1');- expect(data['user_id'], 'user-9');- expect(data['platform'], 'ios');- expect(_paramsOf(payload), {- 'app_version': '1.0.0',- 'app_build': '45',- 'os': 'ios',- 'os_version': 'Version 26.0',- 'arch': 'iosArm64',- 'locale': 'vi_VN',- 'build': 'release',- 'user_id': 'user-9',- 'user_email': '[email protected]',- 'category': AnalyticsConfig.category,- });- });-- test('signed out: no user id in data and none in the params', () {- final payload = analyticsPayload(_event(), _context);-- final data = payload['data']! as Map<String, Object?>;- expect(data.containsKey('user_id'), isFalse);- final params = _paramsOf(payload);- expect(params.containsKey('user_id'), isFalse);- expect(params.containsKey('user_email'), isFalse);- });-- test('an event may say more than the context did, but never its category', () {- final payload = analyticsPayload(- _event(params: {'locale': 'en_US', 'category': 'someone-else'}),- _context,- );-- final params = _paramsOf(payload);- expect(params['locale'], 'en_US');- // The one field that keeps this app separable inside the shared project.- expect(params['category'], AnalyticsConfig.category);- });-- test(- 'a context that could not be read costs its fields, not the event',- () {- final payload = analyticsPayload(_event(), AnalyticsContext.unknown);-- final params = _paramsOf(payload);- expect(params.keys, containsAll(['build', 'category']));- expect(params.containsKey('app_version'), isFalse);- expect(params.containsKey('os'), isFalse);- expect(params['build'], kReleaseMode ? 'release' : 'debug');- },- );-- test('a debug build says so on every event', () {- const debug = AnalyticsContext(- platform: 'android',- appVersion: '',- appBuild: '',- osVersion: '',- arch: '',- locale: '',- release: false,- );- expect(debug.asParams()['build'], 'debug');- expect(debug.asParams()['app_version'], isNull);- });- });-- group('params', () {- test('nulls and empty strings are dropped, the rest kept in order', () {- expect(analyticsParams({'a': null, 'b': '', 'c': 'x', 'd': 0}), [- {'key': 'c', 'value': 'x'},- {'key': 'd', 'value': 0},- ]);- });-- test('never more than the cap, however many are passed', () {- final params = {for (var i = 0; i < 60; i++) 'k$i': i};- final out = analyticsParams(params);- expect(out, hasLength(AnalyticsLimits.paramsMaxKeys));- expect(out.last['key'], 'k${AnalyticsLimits.paramsMaxKeys - 1}');- });-- test('numbers and bools go as they are; anything else as JSON', () {- expect(analyticsValue(3), 3);- expect(analyticsValue(2.5), 2.5);- expect(analyticsValue(true), true);- expect(analyticsValue(['a', 1]), '["a",1]');- expect(analyticsValue({'k': 'v'}), '{"k":"v"}');- });-- test('a long string is clipped to what the backend keeps', () {- final long = 'x' * (AnalyticsLimits.paramsMaxStringLength + 20);- expect(- analyticsValue(long),- hasLength(AnalyticsLimits.paramsMaxStringLength),- );- // The clip applies to an encoded value too.- expect(- analyticsValue([long]),- hasLength(AnalyticsLimits.paramsMaxStringLength),- );- });-- test('a value that will not encode costs that value, never the event', () {- final value = _Unencodable();- expect(analyticsValue(value), 'unencodable');- });- });-- group('the config', () {- test('muted under flutter test, and says why', () {- final config = AnalyticsConfig.resolve();-- expect(config.enabled, isFalse);- expect(config.offReason, isNotNull);- expect(config.endpoint.path, endsWith('/event_tracking'));- expect(config.endpoint.path, isNot(contains('//')));- expect(config.writeKey, isNotEmpty);- });-- test('a config with no reason is live', () {- final config = AnalyticsConfig(- endpoint: Uri.parse('https://analytics.invalid/api/v1/event_tracking'),- writeKey: 'k',- );- expect(config.enabled, isTrue);- });- });-- group('the events the phone sends', () {- late _Recording recording;-- setUp(() => recording = _Recording());-- test('each is written once, as a product fact and nothing more', () {- recording- ..appOpened(signedIn: true)- ..signedIn()- ..signInFailed('cli_missing')- ..signedOut()- ..appFirstMessage(from: 'launch', secondsSinceLogin: 42);-- expect(recording.events.map((e) => e.name), [- 'app_opened',- 'signed_in',- 'sign_in_failed',- 'signed_out',- 'app_first_message',- ]);- expect(recording.events[0].params, {'signed_in': true});- expect(recording.events[1].params, isEmpty);- expect(recording.events[2].params, {'reason': 'cli_missing'});- expect(recording.events[4].params, {- 'from': 'launch',- 'seconds_since_login': 42,- });- for (final event in recording.events) {- expect(analyticsEventNamePattern.hasMatch(event.name), isTrue);- }- });- });-- group('the recorder', () {- test('a release build records nothing, and hands out no ids', () {- const log = NoopAnalyticsLog();- expect(log.queued('app_opened', const {}, DateTime(2026)), 0);- log.attempted(0, const {});- log.settled(0, AnalyticsEventStatus.sent);- });-- test(- 'the ring keeps the newest rows; a row pushed out settles nothing',- () {- final log = AnalyticsLogStream(maxEntries: 2);- final first = log.queued('first_event', const {}, DateTime(2026));- log.queued('second_event', const {}, DateTime(2026));- log.queued('third_event', const {}, DateTime(2026));-- expect(log.entries.map((e) => e.name), ['third_event', 'second_event']);- log.attempted(first, const {});- log.settled(first, AnalyticsEventStatus.sent);- expect(log.entries.every((e) => e.attempts == 0), isTrue);- },- );-- test('a body that will not re-indent is shown as it is', () {- final log = AnalyticsLogStream();- final id = log.queued('app_opened', const {}, DateTime(2026));- log.attempted(id, {'value': _Unencodable()});- expect(log.entries.single.payload, '{value: unencodable}');- });- });-- group('the sink', () {- tearDown(() {- setAnalyticsForTest(null);- analyticsAccount.clear();- });-- test('under test it is muted, and shows its work where it can', () {- setAnalyticsForTest(null);- final sink = analytics;-- // A debug run has the debug surface, so the muted sink records rather- // than dropping silently — see `_muted`.- expect(sink, isA<MutedAnalytics>());- expect(identical(analytics, sink), isTrue, reason: 'built once');- final before = analyticsLog.entries.length;- sink.track('app_opened', params: {'signed_in': false});- final row = analyticsLog.entries.first;- expect(analyticsLog.entries.length, before + 1);- expect(row.name, 'app_opened');- expect(row.status, AnalyticsEventStatus.dropped);- expect(row.note, (sink as MutedAnalytics).reason);- expect(analyticsRecorder, same(analyticsLog));- });-- test('a test can swap the sink and put the old one back', () async {- final previous = setAnalyticsForTest(const NoopAnalytics());- expect(analytics, isA<NoopAnalytics>());- await analytics.flush();- await analytics.close();- analytics.track('app_opened');- expect(setAnalyticsForTest(previous), isA<NoopAnalytics>());- });-- test('a muted sink has nothing to flush or close', () async {- final muted = MutedAnalytics(- AnalyticsLogStream(),- 'off',- clock: () => DateTime(2026),- );- await muted.flush();- await muted.close();- muted.track('signed_in');- expect(- (muted.recorder as AnalyticsLogStream).entries.single.queuedAt,- DateTime(2026),- );- });-- test('the account is who events are filed under, until sign-out', () {- analyticsAccount.set(id: 'u1', email: '[email protected]');- expect(analyticsAccount.current, (id: 'u1', email: '[email protected]'));- analyticsAccount.clear();- expect(analyticsAccount.current, (id: null, email: null));- });-- test('the context never fails, with or without a readable bundle', () async {- TestWidgetsFlutterBinding.ensureInitialized();- // No plugin behind the channel: the version lookup throws, and costs the- // version only.- final bare = await resolveAnalyticsContext();- expect(bare.appVersion, isEmpty);- expect(bare.platform, isNotEmpty);- expect(bare.release, kReleaseMode);-- PackageInfo.setMockInitialValues(- appName: 'Harness',- packageName: 'ai.autonomous.harness',- version: '1.0.0',- buildNumber: '45',- buildSignature: '',- );- final read = await resolveAnalyticsContext();- expect(read.appVersion, '1.0.0');- expect(read.appBuild, '45');- });- });-}--class _Unencodable {- @override- String toString() => 'unencodable';-}diff --git a/mobile/test/analytics/analytics_queue_test.dart b/mobile/test/analytics/analytics_queue_test.dartdeleted file mode 100644index e9e1a0da8..000000000--- a/mobile/test/analytics/analytics_queue_test.dart+++ /dev/null@@ -1,328 +0,0 @@-import 'dart:async';-import 'dart:io';--import 'package:fake_async/fake_async.dart';-import 'package:flutter_test/flutter_test.dart';-import 'package:harness_mobile/analytics/analytics_client.dart';-import 'package:harness_mobile/analytics/analytics_config.dart';-import 'package:harness_mobile/analytics/analytics_event.dart';-import 'package:harness_mobile/analytics/analytics_identity.dart';-import 'package:harness_mobile/analytics/analytics_log.dart';-import 'package:harness_mobile/analytics/analytics_service.dart';--/// A transport that answers from a script, one result per send, and remembers-/// every body it was handed. An empty script answers `sent`.-class _Client implements AnalyticsClient {- final results = <Object>[];- final bodies = <Map<String, Object?>>[];-- /// While set, a send waits on it instead of reading the script — an event- /// held on the wire.- Completer<AnalyticsSendResult>? hold;- bool disposed = false;-- List<String> get names => [- for (final body in bodies) '${body['event_name']}',- ];-- @override- Future<AnalyticsSendResult> send(Map<String, Object?> payload) async {- bodies.add(payload);- final held = hold;- if (held != null) return held.future;- if (results.isEmpty) return AnalyticsSendResult.sent;- final next = results.removeAt(0);- if (next is AnalyticsSendResult) return next;- throw next;- }-- @override- void dispose() => disposed = true;-}--const _context = AnalyticsContext(- platform: 'ios',- appVersion: '1.0.0',- appBuild: '45',- osVersion: '26.0',- arch: 'iosArm64',- locale: 'en_US',- release: false,-);--void main() {- late Directory home;- late _Client client;- late AnalyticsLogStream log;- late ({String? id, String? email}) account;-- setUp(() {- home = Directory.systemTemp.createTempSync('analytics_queue_test');- client = _Client();- // Room for every row a full queue produces: the screen's own ring keeps- // 200, and a row pushed out of it can no longer be read back here.- log = AnalyticsLogStream(maxEntries: 2 * AnalyticsLimits.queueCap);- account = (id: null, email: null);- });-- tearDown(() => home.deleteSync(recursive: true));-- QueuedAnalytics queue({- Future<AnalyticsContext>? context,- DateTime Function()? clock,- }) => QueuedAnalytics(- client: client,- identityStore: AnalyticsIdentityStore(- file: File('${home.path}/analytics.json'),- computerIdFile: File('${home.path}/computer-id'),- ),- contextFuture: context ?? Future.value(_context),- userLookup: () => account,- recorder: log,- clock: clock ?? DateTime.now,- );-- AnalyticsLogEntry row(String name) =>- log.entries.firstWhere((entry) => entry.name == name);-- test('sends in order, one at a time, and settles each row', () async {- final analytics = queue();- analytics.track('app_opened', params: {'signed_in': true});- analytics.track('signed_in');- await analytics.flush();-- expect(client.names, ['app_opened', 'signed_in']);- expect(analytics.pending, 0);- expect(row('app_opened').status, AnalyticsEventStatus.sent);- expect(row('app_opened').attempts, 1);- expect(row('app_opened').payload, contains('"event_name": "app_opened"'));- expect(row('app_opened').took, isNotNull);- });-- test('a badly named event is recorded as dropped and never sent', () async {- final analytics = queue();- analytics.track('Opened the app');- await analytics.flush();-- expect(client.bodies, isEmpty);- expect(analytics.pending, 0);- expect(row('Opened the app').status, AnalyticsEventStatus.dropped);- expect(row('Opened the app').note, contains('snake_case'));- });-- test(- 'who is signed in is read when the event happens, not when it is sent',- () async {- final analytics = queue();- analytics.track('app_opened');- account = (id: 'u1', email: '[email protected]');- analytics.track('signed_in');- await analytics.flush();-- final data = [- for (final body in client.bodies) body['data']! as Map<String, Object?>,- ];- expect(data[0].containsKey('user_id'), isFalse);- expect(data[1]['user_id'], 'u1');- // One device, one visit, across the sign-in.- expect(data[0]['user_pseudo_id'], data[1]['user_pseudo_id']);- expect(data[0]['session_id'], data[1]['session_id']);- },- );-- test('a refused event is dropped; the queue behind it carries on', () async {- client.results.add(AnalyticsSendResult.rejected);- final analytics = queue();- analytics.track('app_opened');- analytics.track('signed_in');- await analytics.flush();-- expect(client.names, ['app_opened', 'signed_in']);- expect(row('app_opened').status, AnalyticsEventStatus.refused);- expect(row('signed_in').status, AnalyticsEventStatus.sent);- });-- test('a client that throws costs that event, not the queue', () async {- client.results.add(StateError('broken client'));- final analytics = queue();- analytics.track('app_opened');- analytics.track('signed_in');- await analytics.flush();-- expect(row('app_opened').status, AnalyticsEventStatus.dropped);- expect(row('app_opened').note, contains('broken client'));- expect(row('signed_in').status, AnalyticsEventStatus.sent);- });-- test('a context that fails still lets the event go, anonymously', () async {- final analytics = queue(context: Future.error(StateError('no bundle')));- analytics.track('app_opened');- await analytics.flush();-- final data = client.bodies.single['data']! as Map<String, Object?>;- expect(data['platform'], '');- expect(row('app_opened').status, AnalyticsEventStatus.sent);- });-- test('a user lookup that throws drops the one event and says so', () async {- final analytics = QueuedAnalytics(- client: client,- identityStore: AnalyticsIdentityStore(- file: File('${home.path}/analytics.json'),- computerIdFile: File('${home.path}/computer-id'),- ),- contextFuture: Future.value(_context),- userLookup: () => throw StateError('no account'),- );- analytics.track('app_opened');- await analytics.flush();-- expect(analytics.pending, 0);- expect(client.bodies, isEmpty);- });-- test('a transport failure keeps the event and retries, backing off', () {- fakeAsync((async) {- client.results.addAll([- AnalyticsSendResult.retry,- AnalyticsSendResult.retry,- AnalyticsSendResult.retry,- ]);- final analytics = queue();- analytics.track('app_opened');- async.flushMicrotasks();- expect(client.bodies, hasLength(1));- expect(analytics.pending, 1);- expect(row('app_opened').status, AnalyticsEventStatus.queued);-- // First retry after 2s, the next after 4s, the one after that after 8s.- async.elapse(const Duration(milliseconds: 1999));- expect(client.bodies, hasLength(1));- async.elapse(const Duration(milliseconds: 1));- expect(client.bodies, hasLength(2));- async.elapse(const Duration(seconds: 3));- expect(client.bodies, hasLength(2));- async.elapse(const Duration(seconds: 1));- expect(client.bodies, hasLength(3));- async.elapse(const Duration(seconds: 8));- expect(client.bodies, hasLength(4));- expect(analytics.pending, 0);- expect(row('app_opened').attempts, 4);- expect(row('app_opened').status, AnalyticsEventStatus.sent);- });- });-- test('the backoff stops growing at its cap, and a success resets it', () {- fakeAsync((async) {- client.results.addAll(List.filled(12, AnalyticsSendResult.retry));- final analytics = queue();- analytics.track('app_opened');- // 2+4+…+64 = 126s, then 120s apiece: all twelve failures are spent well- // inside this, and the thirteenth attempt succeeds.- async.elapse(const Duration(minutes: 20));- expect(client.bodies, hasLength(13));- expect(analytics.pending, 0);-- // Back to 2s after the success.- client.results.add(AnalyticsSendResult.retry);- analytics.track('signed_in');- async.flushMicrotasks();- expect(client.bodies, hasLength(14));- async.elapse(const Duration(seconds: 2));- expect(client.bodies, hasLength(15));- });- });-- test('flush sends now instead of waiting out the retry', () {- fakeAsync((async) {- client.results.add(AnalyticsSendResult.retry);- final analytics = queue();- analytics.track('app_opened');- async.flushMicrotasks();- expect(analytics.pending, 1);-- unawaited(analytics.flush());- async.flushMicrotasks();- expect(client.bodies, hasLength(2));- expect(analytics.pending, 0);- });- });-- test('past the cap the oldest go, and the rows say why', () {- fakeAsync((async) {- client.results.add(AnalyticsSendResult.retry);- final analytics = queue();- for (var i = 0; i < AnalyticsLimits.queueCap + 3; i++) {- analytics.track('event_$i');- }- async.flushMicrotasks();-- expect(analytics.pending, AnalyticsLimits.queueCap);- final dropped = log.entries- .where((entry) => entry.status == AnalyticsEventStatus.dropped)- .toList();- expect(dropped, hasLength(3));- expect(dropped.every((e) => e.note == 'the queue was full'), isTrue);- });- });-- test('an event trimmed while it is on the wire does not take the next one with it', () {- fakeAsync((async) {- final analytics = queue();- client.hold = Completer<AnalyticsSendResult>();- analytics.track('first_event');- async.flushMicrotasks();- expect(client.names, ['first_event']);-- // An outage long enough to fill the queue while `first_event` waits on- // the wire: the cap pushes it — the one in flight — out of the queue.- for (var i = 0; i < AnalyticsLimits.queueCap; i++) {- analytics.track('later_$i');- }- expect(analytics.pending, AnalyticsLimits.queueCap);-- final held = client.hold!;- client.hold = null;- held.complete(AnalyticsSendResult.sent);- async.flushMicrotasks();-- // Every one of the later events reached the wire — none was removed in- // place of the event that was already gone.- expect(client.names.skip(1), [- for (var i = 0; i < AnalyticsLimits.queueCap; i++) 'later_$i',- ]);- expect(analytics.pending, 0);- expect(row('later_0').status, AnalyticsEventStatus.sent);- });- });-- test(- 'close drains what it can, releases the client, and ends the queue',- () async {- final analytics = queue();- analytics.track('app_opened');- await analytics.close();-- expect(client.names, ['app_opened']);- expect(client.disposed, isTrue);- analytics.track('signed_in');- await analytics.flush();- expect(client.names, ['app_opened'], reason: 'the instance is spent');- // A second close is nothing.- await analytics.close();- },- );-- test('a wedged network cannot hold a close past its deadline', () {- fakeAsync((async) {- client.hold = Completer<AnalyticsSendResult>();- final analytics = queue();- analytics.track('app_opened');- var closed = false;- analytics.close().then((_) => closed = true);- async.elapse(AnalyticsLimits.closeDeadline);- expect(closed, isTrue);- expect(client.disposed, isTrue);- });- });-}diff --git a/mobile/test/app_state_phone_paths_test.dart b/mobile/test/app_state_phone_paths_test.dartindex 99911365f..b42d688b7 100644--- a/mobile/test/app_state_phone_paths_test.dart+++ b/mobile/test/app_state_phone_paths_test.dart@@ -430,12 +430,11 @@ void main() {);});- test('the first message after sign-in is counted once', () async {+ test('a second turn after the first leaves the agent processing', () async {final rig = await signedInWith({'m': ['a'],});addTearDown(rig.app.dispose);- rig.app.armFirstMessageForTest('sign_in');await push(rig, 'm', 'turn_started', {'agentId': 'a'});await push(rig, 'm', 'turn_ended', {'agentId': 'a'});diff --git a/mobile/test/flutter_test_config.dart b/mobile/test/flutter_test_config.dartindex 66cc5f369..2785e5443 100644--- a/mobile/test/flutter_test_config.dart+++ b/mobile/test/flutter_test_config.dart@@ -7,7 +7,7 @@ import 'package:harness_mobile/core/harness_file_store.dart';/// Runs before every test file under `test/`.////// ⚠️ **Every default path points into a throwaway home.** The app's stores,-/// logs, crash log, analytics id and snapshots all resolve under+/// logs, crash log and snapshots all resolve under/// `~/.harness` through [HarnessFileStore.defaultDirectoryPath], and a test/// that builds the app without handing each one a fake would otherwise read and/// write the developer's real state — sessions and E2EE keys included. See the