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
Collect Desktop setup counts by default; move opt-out to Settings (#1362)
Dee0e3765cfd4c5
diff --git a/backend/src/lib/productUsage.test.ts b/backend/src/lib/productUsage.test.tsindex 40d0ccb60..fe36e5633 100644--- a/backend/src/lib/productUsage.test.ts+++ b/backend/src/lib/productUsage.test.ts@@ -245,14 +245,13 @@ it('setup ingestion never reads an account and expires after yesterday', async (expect(await ingestSetupUsage({ ...setup, day: '2026-10-12' }, now)).toMatchObject({ accepted: true })})-it('keeps anonymous transport and consent unchanged across native apps while Desktop health evolves independently', () => {+it('keeps anonymous transport and the phone opt-in unchanged while Desktop evolves independently', () => {expect(readFileSync(new URL('../../../desktop/lib/measurement/setup_transport.dart', import.meta.url), 'utf8')).toBe(readFileSync(new URL('../../../mobile/lib/measurement/setup_transport.dart', import.meta.url), 'utf8'))- // Each app draws the signed-out choice its own way (the phone's is one line with a tooltip); what it asks must not differ.+ // Desktop now uses its Settings-only default-on preference; the phone retains its own opt-in.const choice = (app: string) => readFileSync(new URL(`../../../${app}/lib/measurement/setup_usage_choice.dart`, import.meta.url), 'utf8')for (const words of ['Share setup and sign-in counts','Optional for this app session. Help us find setup problems without sharing account details, prompts, or files.']) {- expect(choice('desktop')).toContain(`'${words}'`)expect(choice('mobile')).toContain(`'${words}'`)}const mobile = readFileSync(new URL('../../../mobile/lib/measurement/product_measurement.dart', import.meta.url), 'utf8')diff --git a/backend/src/routes/productUsage.test.ts b/backend/src/routes/productUsage.test.tsindex 4bd09127b..6db5de448 100644--- a/backend/src/routes/productUsage.test.ts+++ b/backend/src/routes/productUsage.test.ts@@ -114,7 +114,7 @@ it('rejects extra context, custom versions and device fingerprints without echoiconst setup = { schemaVersion: 1, consent: true, id: good.id, day: good.day, counters: { setup_desktop_sign_in_started: 1 } }const sendSetup = (payload: unknown = setup, headers = {}) => app.inject({ method: 'POST', url: '/api/product-usage/setup', payload: payload as Record<string, unknown>, headers })-it('accepts only explicitly enabled setup counts without credentials or account lookup', async () => {+it('keeps legacy explicit setup opt-in without credentials or account lookup', async () => {expect((await sendSetup()).statusCode).toBe(200)expect(methods.ingestSetupUsage).toHaveBeenCalledWith(setup)expect(methods.productUsageChoice).not.toHaveBeenCalled()@@ -129,6 +129,28 @@ it('accepts only explicitly enabled setup counts without credentials or account}for (const headers of [{ authorization: 'fixture' }, { cookie: 'PRIVATE_CANARY' }]) expect((await sendSetup(setup, headers)).statusCode).toBe(400)})+it('accepts default-on sharing only for Desktop setup without asserting consent', async () => {+ const { consent: _, ...fields } = setup+ const report = { ...fields, sharing: 'default' }+ expect((await sendSetup(report)).statusCode).toBe(200)+ expect(methods.ingestSetupUsage).toHaveBeenCalledWith(report)+ expect(methods.productUsageChoice).not.toHaveBeenCalled()+ expect(methods.ingestProductUsage).not.toHaveBeenCalled()+ methods.ingestSetupUsage.mockClear()+ for (const payload of [fields, { ...report, consent: true }, { ...report, sharing: 'off' },+ { ...report, counters: { setup_phone_sign_in_started: 1 } },+ { ...report, counters: { ...setup.counters, setup_phone_sign_in_started: 1 } },+ { ...report, counters: { ui_desktop_sign_in_started: 1 } },+ { ...report, account: 'PRIVATE_CANARY' }]) {+ const response = await sendSetup(payload)+ expect(response.statusCode).toBe(400)+ expect(response.body).not.toContain('PRIVATE_CANARY')+ }+ for (const headers of [{ authorization: 'fixture' }, { cookie: 'PRIVATE_CANARY' }]) {+ expect((await sendSetup(report, headers)).statusCode).toBe(400)+ }+ expect(methods.ingestSetupUsage).not.toHaveBeenCalled()+})it('bounds untrusted setup writes independently of signed-in reports', async () => {let finish!: (value: unknown) => voidmethods.ingestSetupUsage.mockImplementation(() => new Promise(resolve => { finish = resolve }))diff --git a/backend/src/routes/productUsage.ts b/backend/src/routes/productUsage.tsindex dc520b23b..fa90d68db 100644--- a/backend/src/routes/productUsage.ts+++ b/backend/src/routes/productUsage.ts@@ -20,12 +20,19 @@ export const productUsageReportSchema = z.strictObject({})const feedbackSchema = z.strictObject({ id: z.uuid(), answer: z.enum(PRODUCT_FEEDBACK) })const choiceSchema = z.strictObject({ enabled: z.boolean() })-export const setupUsageSchema = z.strictObject({- schemaVersion: z.literal(1), consent: z.literal(true), id: z.uuid(),+const setupFields = {+ schemaVersion: z.literal(1), id: z.uuid(),day: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),counters: z.partialRecord(z.enum(PRODUCT_USAGE_SETUP_METRICS), z.number().int().min(1).max(1000)).refine(c => Object.keys(c).length > 0 && Object.keys(c).length <= 32),-})+}+export const setupUsageSchema = z.union([+ // Older native clients (including the phone) still require explicit opt-in.+ z.strictObject({ ...setupFields, consent: z.literal(true) }),+ // Desktop defaults on with a persistent Settings opt-out. Do not call that consent.+ z.strictObject({ ...setupFields, sharing: z.literal('default') })+ .refine(report => Object.keys(report.counters).every(key => key.startsWith('setup_desktop_'))),+])export async function productUsageRoutes(app: FastifyInstance): Promise<void> {// A process-wide budget bounds untrusted pre-sign-in counts without collecting IPs or cookies.diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dartindex 298071045..d42e9a68f 100644--- a/desktop/lib/app_shell.dart+++ b/desktop/lib/app_shell.dart@@ -1,5 +1,4 @@import 'core/app_version.dart';-import 'measurement/setup_usage_choice.dart';import 'dart:async';@@ -17,6 +16,8 @@ import 'package:flutter_web_plugins/url_strategy.dart';import 'core/crash_log.dart';import 'core/desktop_window.dart';import 'core/linux_app_image.dart';+import 'settings/settings_screen.dart';+import 'settings/settings_section.dart';import 'screens/login_screen.dart';import 'state/app_state.dart';import 'stats/stats_lifecycle.dart';@@ -269,6 +270,16 @@ class _RootShellState extends ConsumerState<RootShell>Future<void> runAppMenuAction(String action) async {if (!mounted) return;switch (action) {+ case 'settings':+ final app = ref.read(appStateProvider);+ await _menuDialog(+ () => showSettingsScreen(+ context,+ app,+ initialSection: SettingsSection.privacy,+ source: 'setup_menu',+ ),+ );case 'checkForUpdates':final app = ref.read(appStateProvider);await _menuDialog(() => checkForUpdatesAndShowResult(context, app));@@ -420,13 +431,6 @@ class _RootShellState extends ConsumerState<RootShell>if (app.deviceConflict != null && deviceBands)DeviceConflictNoticeBand(notifier: app),Expanded(child: framed),- if (!kIsWeb &&- !home &&- (touring ||- signInStep ||- app.status == AppStatus.preparingEnvironment ||- app.status == AppStatus.unauthenticated))- SetupUsageChoice(measurement: app.productMeasurement),],);},diff --git a/desktop/lib/measurement/product_measurement.dart b/desktop/lib/measurement/product_measurement.dartindex d661ba5cc..8c21d7f8e 100644--- a/desktop/lib/measurement/product_measurement.dart+++ b/desktop/lib/measurement/product_measurement.dart@@ -3,6 +3,7 @@ import 'dart:math';import 'package:flutter/foundation.dart';+import '../core/local_key_value_store.dart';import 'product_health_contract.dart';import 'product_report_failure.dart';export 'product_health_contract.dart';@@ -52,7 +53,8 @@ typedef ProductChoiceRequest = Future<Map<String, dynamic>> Function();/// Fixed counters only: no event log, identifiers, errors, request/response objects or content./// Counters stay in RAM. The separate runtime observer saves only last-run control flags locally.-/// Signed-out sharing is an explicit choice for this app session; a close/crash can lose queued counts.+/// Desktop setup sharing defaults on; only its preference is persisted locally.+/// Counters remain in RAM, so a close/crash can lose queued counts./// Requests and retries are serialized and never awaited by a product action.class ProductMeasurement extends ChangeNotifier {ProductMeasurement({@@ -62,10 +64,14 @@ class ProductMeasurement extends ChangeNotifier {String Function()? receipt,this.automatic = true,this.context,+ LocalKeyValueStore? setupStorage,}) : assert(const ['desktop', 'phone', 'web'].contains(surface)),+ _setupStorage = setupStorage,_now = now ?? DateTime.now,_receipt = receipt ?? newProductReceipt {- choiceLoaded = true;+ signedOutSharing = surface == 'desktop' && setupStorage == null;+ choiceLoaded = setupStorage == null;+ setupChoiceReady = _loadSetupChoice();}final String surface;@@ -83,6 +89,18 @@ class ProductMeasurement extends ChangeNotifier {final DateTime Function() _now;final String Function() _receipt;bool signedOutSharing = false, choiceLoaded = false;+ static const setupPreferenceKey = 'product_setup_sharing';+ static const pendingSetupOptOut =+ '{"enabled":false,"accountOptOutPending":true}';+ final LocalKeyValueStore? _setupStorage;+ late final Future<void> setupChoiceReady;+ Future<void>? _setupSave;+ Future<void> get setupChoiceSaved => _setupSave ?? Future<void>.value();+ String? _persistedSetupChoice;+ bool _accountOptOutPending = false;+ bool get accountOptOutPending =>+ surface == 'desktop' && _accountOptOutPending;+ int _setupChoiceGeneration = 0;bool _disposed = false;Object? _account;bool? _enabled;@@ -98,23 +116,78 @@ class ProductMeasurement extends ChangeNotifier {final _setup = <ProductFlow, void Function(ProductOutcome)>{};final _setupFacts = <ProductFlow, String>{};- bool get sharing => _account != null && _enabled == true;+ bool get sharing =>+ _account != null &&+ _enabled == true &&+ (surface != 'desktop' || choiceLoaded) &&+ !accountOptOutPending;bool get _setupAllowed =>surface != 'web' &&(!healthEnabled || context!.production) &&+ choiceLoaded &&signedOutSharing &&(_account == null || _enabled == true);- Future<void> setSignedOutSharing(bool enabled) async {- _guestEpoch++;- signedOutSharing = enabled;+ Future<void> _loadSetupChoice() async {+ final storage = _setupStorage;+ if (storage == null) return;+ final generation = _setupChoiceGeneration;+ String? value;+ try {+ value = await storage.read(setupPreferenceKey);+ } catch (_) {+ // An unreadable preference must not turn a saved opt-out back on.+ value = pendingSetupOptOut;+ }+ if (_disposed || generation != _setupChoiceGeneration) return;+ _persistedSetupChoice = value;+ _accountOptOutPending =+ value != null && value != 'true' && value != 'false';+ signedOutSharing = value == null ? surface == 'desktop' : value == 'true';choiceLoaded = true;- _clear('setup');- _setup.clear();- if (enabled) _observeSetupFacts();+ _observeSetupFacts();notifyListeners();}+ Future<void> setSignedOutSharing(+ bool enabled, {+ bool fromAccount = false,+ }) async {+ _setupChoiceGeneration++;+ _accountOptOutPending = surface == 'desktop' && !enabled && !fromAccount;+ if (accountOptOutPending) {+ _accountEpoch++;+ _clear('ui');+ }+ if (signedOutSharing != enabled || !choiceLoaded) {+ _guestEpoch++;+ signedOutSharing = enabled;+ choiceLoaded = true;+ _clear('setup');+ _setup.clear();+ if (enabled) _observeSetupFacts();+ notifyListeners();+ }+ final storage = _setupStorage;+ if (storage == null) return;+ final value = accountOptOutPending+ ? pendingSetupOptOut+ : enabled.toString();+ // Serialize rapid changes so an older write cannot restore sharing after off.+ final previous = _setupSave;+ final saving = () async {+ if (previous != null) {+ try {+ await previous;+ } catch (_) {}+ }+ await storage.write(setupPreferenceKey, value);+ _persistedSetupChoice = value;+ }();+ _setupSave = saving;+ await saving;+ }+/// The scope is RAM-only and never serialized. A sign-out or account change discards its queue.void account(Object? scope, {@@ -125,7 +198,7 @@ class ProductMeasurement extends ChangeNotifier {_accountEpoch++;if (_account != null) {_guestEpoch++;- signedOutSharing = false;+ if (surface != 'desktop') signedOutSharing = false;_clear('setup');_setup.clear();}@@ -140,18 +213,38 @@ class ProductMeasurement extends ChangeNotifier {}/// A saved switch applies immediately in this app, even while a report is in flight.- void savedChoice(Map<String, dynamic> value) {+ void savedChoice(Map<String, dynamic> value, {bool explicit = false}) {final enabled = value['enabled'], revision = value['revision'];if (enabled is! bool || revision is! int || revision < 0) {_enabled = null;return;}+ if (surface == 'desktop' && !choiceLoaded && enabled && !explicit) {+ _enabled = null;+ return;+ }if (revision != _revision || !enabled) {_accountEpoch++;_clear('ui');}_revision = revision;_enabled = enabled;+ if (surface == 'desktop' &&+ (!accountOptOutPending || !enabled || explicit) &&+ (signedOutSharing != enabled ||+ !choiceLoaded ||+ accountOptOutPending ||+ (_setupStorage != null &&+ _persistedSetupChoice != enabled.toString()))) {+ // Remember the confirmed account choice for the next signed-out launch.+ // Persistence failure never restores the in-memory sharing it just stopped.+ unawaited(+ setSignedOutSharing(+ enabled,+ fromAccount: true,+ ).catchError((Object _) {}),+ );+ }if (!enabled) {_guestEpoch++;signedOutSharing = false;@@ -216,16 +309,16 @@ class ProductMeasurement extends ChangeNotifier {);}- /// A consented app-session funnel, never a click trail or an account join.+ /// A sharing-enabled app-session funnel, never a click trail or an account join./// Its clock starts at the first permitted observation, not retrospectively at install.void milestone(ProductHealthMeasure measure) {if (!healthEnabled || _disposed || !measure.wire.startsWith('funnel_')) {return;}- final channel = _setupAllowed- ? 'setup'- : sharing+ final channel = sharing? 'ui'+ : _setupAllowed+ ? 'setup': null;if (channel == null) return;final seen = _funnelSeen.putIfAbsent(channel, () => {});@@ -401,6 +494,7 @@ class ProductMeasurement extends ChangeNotifier {});Future<void> _flush() async {+ if (!choiceLoaded) await setupChoiceReady;if (_disposed) return;_lastAttempt = _now();for (final ticket in _expires.keys.toList()) {@@ -443,7 +537,10 @@ class ProductMeasurement extends ChangeNotifier {'id': _receipt(),'day': key.split(':')[1],'counters': batch,- if (channel == 'setup') 'consent': true else 'revision': _revision,+ if (channel == 'setup')+ if (surface == 'desktop') 'sharing': 'default' else 'consent': true+ else+ 'revision': _revision,if (channel == 'ui' && healthEnabled) 'context': context!.toJson(),};_pending[channel] = report;diff --git a/desktop/lib/measurement/setup_preference_store.dart b/desktop/lib/measurement/setup_preference_store.dartnew file mode 100644index 000000000..8157a00f3--- /dev/null+++ b/desktop/lib/measurement/setup_preference_store.dart@@ -0,0 +1,53 @@+import 'dart:io';++import '../core/harness_file_store.dart';+import '../core/local_key_value_store.dart';+import 'product_measurement.dart';++/// One local preference, without identifiers or activity. Unlike a disposable+/// cache, an unreadable file must throw so the collector can keep sharing off.+class SetupPreferenceStore implements LocalKeyValueStore {+ SetupPreferenceStore({Directory? directory})+ : file = File(+ '${(directory ?? Directory(HarnessFileStore.defaultDirectoryPath())).path}/setup-sharing.json',+ );++ final File file;++ @override+ Future<String?> read(String key) async {+ try {+ return (await file.readAsString()).trim();+ } on FileSystemException catch (error) {+ if (error.osError?.errorCode == 2) {+ return null; // Only a missing file is a default.+ }+ rethrow;+ }+ }++ @override+ Future<void> write(String key, String value) async {+ if (value != 'true' &&+ value != 'false' &&+ value != ProductMeasurement.pendingSetupOptOut) {+ throw const FormatException('Invalid setup sharing preference');+ }+ await file.parent.create(recursive: true);+ final temporary = File(+ '${file.path}.${pid}_${DateTime.now().microsecondsSinceEpoch}.tmp',+ );+ try {+ await temporary.writeAsString(value, flush: true);+ await temporary.rename(file.path);+ } finally {+ if (await temporary.exists()) await temporary.delete();+ }+ }++ @override+ Future<void> delete(String key) async {+ // Forgetting a privacy choice must not silently restore default-on sharing.+ await write(key, 'false');+ }+}diff --git a/desktop/lib/measurement/setup_usage_choice.dart b/desktop/lib/measurement/setup_usage_choice.dartindex 064e20cbc..a480fb0d7 100644--- a/desktop/lib/measurement/setup_usage_choice.dart+++ b/desktop/lib/measurement/setup_usage_choice.dart@@ -1,31 +1,71 @@-import 'dart:async';-import 'package:flutter/material.dart';+import '../shared/widgets/setting_row.dart';import 'product_measurement.dart';-/// Visible before any optional signed-out report. It never blocks setup or sign-in.-class SetupUsageChoice extends StatelessWidget {+/// Settings-only control for this computer before an account preference is known.+class SetupUsageChoice extends StatefulWidget {const SetupUsageChoice({super.key, required this.measurement});final ProductMeasurement measurement;+ @override+ State<SetupUsageChoice> createState() => _SetupUsageChoiceState();+}++class _SetupUsageChoiceState extends State<SetupUsageChoice> {+ bool _saving = false;+ String? _error;++ Future<void> _set(bool enabled) async {+ setState(() {+ _saving = true;+ _error = null;+ });+ try {+ await widget.measurement.setSignedOutSharing(enabled);+ } catch (_) {+ if (mounted) {+ setState(+ () => _error =+ 'Couldn’t save this setting for the next launch. Try again.',+ );+ }+ } finally {+ if (mounted) setState(() => _saving = false);+ }+ }+@overrideWidget build(BuildContext context) => ListenableBuilder(- listenable: measurement,- builder: (context, _) => Material(- color: Theme.of(context).colorScheme.surface,- child: CheckboxListTile(- dense: true,- controlAffinity: ListTileControlAffinity.leading,- value: measurement.signedOutSharing,- onChanged: measurement.choiceLoaded- ? (value) =>- unawaited(measurement.setSignedOutSharing(value == true))- : null,- title: const Text('Share setup and sign-in counts'),- subtitle: const Text(- 'Optional for this app session. Help us find setup problems without sharing account details, prompts, or files.',+ listenable: widget.measurement,+ builder: (context, _) => SingleChildScrollView(+ child: SettingRow(+ title: 'Share product usage data',+ detail:+ 'Help improve Harness by sharing setup and sign-in counts and duration statistics. '+ 'Your account details, prompts, code, files, and conversations are never included.',+ controlSemanticLabel: 'Share product usage data',+ control: Switch(+ value: widget.measurement.signedOutSharing,+ onChanged: widget.measurement.choiceLoaded && !_saving ? _set : null,),+ footer: _error == null+ ? const Text(+ 'Applies to this computer before sign-in and is remembered for future launches. '+ 'Turning this off also disables sharing for your account when you sign in.',+ )+ : Column(+ crossAxisAlignment: CrossAxisAlignment.start,+ children: [+ Text(_error!),+ TextButton(+ onPressed: _saving+ ? null+ : () => _set(widget.measurement.signedOutSharing),+ child: const Text('Retry saving'),+ ),+ ],+ ),),),);diff --git a/desktop/lib/settings/sections/privacy_section.dart b/desktop/lib/settings/sections/privacy_section.dartindex 9ecdca7bf..2d4fa34d0 100644--- a/desktop/lib/settings/sections/privacy_section.dart+++ b/desktop/lib/settings/sections/privacy_section.dart@@ -23,7 +23,9 @@ class PrivacySection extends StatelessWidget {builder: (context, _) => SectionScaffold(title: 'Privacy',subtitle: 'Choose what you share to help improve Harness.',- child: notifier.isGuest+ child:+ notifier.isGuest ||+ (!kIsWeb && notifier.status != AppStatus.authenticated)? notifier.productMeasurement.surface == 'web'? const Text('Product usage sharing is available after sign-in.',@@ -32,10 +34,14 @@ class PrivacySection extends StatelessWidget {: ProductUsagePreference(key: ObjectKey(notifier.api),request: ({bool? enabled}) async {- final value = await notifier.api.productUsageSettings(+ final value = await notifier.productUsageSettings(enabled: enabled,);- notifier.productMeasurement.savedChoice(value);+ notifier.productMeasurement.savedChoice(+ value,+ explicit: enabled != null,+ );+ await notifier.productMeasurement.setupChoiceSaved;return value;},feedback: notifier.api.productUsageFeedback,@@ -186,15 +192,16 @@ class _ProductUsagePreferenceState extends State<ProductUsagePreference> {),],if (_enabled == true && widget.feedback != null) ...[- if (!kIsWeb) TextButton(- onPressed: () => showTaskFeedback(- context,- choice: widget.request,- send: widget.feedback!,- measurement: widget.measurement,+ if (!kIsWeb)+ TextButton(+ onPressed: () => showTaskFeedback(+ context,+ choice: widget.request,+ send: widget.feedback!,+ measurement: widget.measurement,+ ),+ child: const Text('Rate task outcome'),),- child: const Text('Rate task outcome'),- ),ProductFeedback(send: widget.feedback!,onShown: widget.measurement?.observer(diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 0c04e4a53..0ce23b7be 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -79,6 +79,7 @@ import '../autonomous_device/autonomous_device_cli.dart';import '../settings/config_store.dart';import '../settings/experimental_features.dart';import '../core/local_key_value_store.dart';+import '../measurement/setup_preference_store.dart';import '../devices/device_hosts.dart';import '../stats/harness_stats.dart';import '../terminal/terminal_session.dart';@@ -3290,6 +3291,9 @@ class AppNotifier extends ChangeNotifier {? 'desktop': 'phone',automatic: !kUnderTest,+ setupStorage: !kIsWeb && this.viewer == null && !kUnderTest+ ? SetupPreferenceStore()+ : null,context: !kIsWeb && this.viewer == null? ProductUsageContext(release: 'unknown',@@ -3361,7 +3365,7 @@ class AppNotifier extends ChangeNotifier {: null;productMeasurement.account(scope,- choice: () => api.productUsageSettings(),+ choice: () => productUsageSettings(),send: api.productUsageReport,);productRuntimeHealth?.account(@@ -3391,6 +3395,17 @@ class AppNotifier extends ChangeNotifier {_measurementGeneration = productMeasurement.observationGeneration;}+ /// A Settings opt-out before sign-in applies to the account once it is known.+ /// Keep it pending locally until the server confirms it; a failed request or+ /// a default-on account response must not silently restore sharing.+ Future<Map<String, dynamic>> productUsageSettings({bool? enabled}) async {+ await productMeasurement.setupChoiceReady;+ return api.productUsageSettings(+ enabled:+ enabled ?? (productMeasurement.accountOptOutPending ? false : null),+ );+ }+// Connection keys already belong to the app. Only fixed outcomes reach measurement, never the key.void _measureConnection(String key,diff --git a/desktop/lib/widgets/linux_menu_bar.dart b/desktop/lib/widgets/linux_menu_bar.dartindex de48c0b5b..41c7975bc 100644--- a/desktop/lib/widgets/linux_menu_bar.dart+++ b/desktop/lib/widgets/linux_menu_bar.dart@@ -248,12 +248,20 @@ class _LinuxMenuBarState extends State<LinuxMenuBar> {label: 'Appearance…',action: 'customize',),- _swarmRow(- key: 'menu-bar-settings',- icon: AppIcons.settings,- label: 'Settings…',- action: 'settings',- ),+ if (_state.enabled)+ _swarmRow(+ key: 'menu-bar-settings',+ icon: AppIcons.settings,+ label: 'Settings…',+ action: 'settings',+ )+ else+ _appRow(+ key: 'menu-bar-settings',+ icon: AppIcons.settings,+ label: 'Settings…',+ action: 'settings',+ ),const AppMenuDivider(),_appRow(key: 'menu-bar-shortcuts',diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex d0cf5b285..d337d891a 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -26,6 +26,7 @@ enum HarnessControlSymbols {final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {private weak var window: NSWindow?private let channel: FlutterMethodChannel+ private let appMenuChannel: FlutterMethodChannelprivate let accessory = NSTitlebarAccessoryViewController()private let strip = SwarmTabStrip(frame: NSRect(x: 0, y: 0, width: 900, height: 40))private var statusMenu: HarnessStatusMenu?@@ -55,6 +56,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {init(window: NSWindow, messenger: FlutterBinaryMessenger, installStatusItem: Bool = true) {self.window = windowchannel = FlutterMethodChannel(name: "harness/swarm_tabs", binaryMessenger: messenger)+ appMenuChannel = FlutterMethodChannel(name: "harness/app_menu", binaryMessenger: messenger)super.init()statusMenu = HarnessStatusMenu(installStatusItem: installStatusItem, showWindow: { [weak window] inNSApp.activate(ignoringOtherApps: true)@@ -519,6 +521,8 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {return machine.agents.contains(where: { $0.id == target["agentId"] && $0.canOpen })}let action = menuItem.representedObject as? String ?? ""+ // Privacy settings must remain reachable before a workspace or account exists.+ if action == "settings" && menuItem.action == #selector(menuAction(_:)) { return true }if ["restartAgent", "shareAgent", "toggleViewer", "toggleComposer"].contains(action) {return actionsEnabled && paneActions[action] == true}@@ -546,6 +550,10 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {@objc private func menuAction(_ sender: NSMenuItem) {guard validateMenuItem(sender), let action = sender.representedObject as? String else { return }+ if action == "settings" && !actionsEnabled {+ appMenuChannel.invokeMethod("settings", arguments: nil)+ return+ }sendTabAction(action, arguments: nil)}diff --git a/desktop/test/linux_menu_bar_test.dart b/desktop/test/linux_menu_bar_test.dartindex 5c6dd1dfa..e96e3ed6c 100644--- a/desktop/test/linux_menu_bar_test.dart+++ b/desktop/test/linux_menu_bar_test.dart@@ -89,6 +89,17 @@ void main() {fail('no tappable widget for $key');}+ testWidgets('Settings remains reachable before the workspace is enabled', (+ tester,+ ) async {+ await swarmMenuBus.send('update', {'enabled': false});+ await pumpBar(tester);+ await tap(tester, 'menu-bar-harness');+ await tap(tester, 'menu-bar-settings');+ expect(appActions, ['settings']);+ expect(swarmCalls, isEmpty);+ });+testWidgets('stays off the screen when not visible', (tester) async {await tester.pumpWidget(MaterialApp(diff --git a/desktop/test/measurement_controls_test.dart b/desktop/test/measurement_controls_test.dartindex 2579b9f85..c02716a99 100644--- a/desktop/test/measurement_controls_test.dart+++ b/desktop/test/measurement_controls_test.dart@@ -24,7 +24,7 @@ void main() {tester.view.physicalSize = const Size(390, 844);addTearDown(tester.view.reset);final usage = ProductMeasurement(- surface: 'phone',+ surface: 'desktop',automatic: false,sendSetup: (_) async => {},);@@ -64,7 +64,7 @@ void main() {);await tester.pumpAndSettle();expect(tester.takeException(), isNull);- expect(usage.signedOutSharing, isFalse);+ expect(usage.signedOutSharing, isTrue);expect(sent, isEmpty);final output = Platform.environment['HARNESS_MEASUREMENT_CAPTURE_DIR'];if (output != null) {@@ -82,9 +82,9 @@ void main() {picture.dispose();});}- await tester.tap(find.byType(Checkbox));+ await tester.tap(find.byType(Switch));await tester.pumpAndSettle();- expect(usage.signedOutSharing, isTrue);+ expect(usage.signedOutSharing, isFalse);await tester.ensureVisible(find.text('Partly completed'));await tester.tap(find.text('Partly completed'));await tester.pumpAndSettle();diff --git a/desktop/test/product_health_test.dart b/desktop/test/product_health_test.dartindex 0b2a0b689..c20de4381 100644--- a/desktop/test/product_health_test.dart+++ b/desktop/test/product_health_test.dart@@ -77,23 +77,38 @@ void main() {connections.dispose();});- test('consented funnel is once per local episode, with coarse waits and no identity', () async {- usage.milestone(ProductHealthMeasure.funnelFirstWork);- expect(totals(), isEmpty);- usage.account(null);- await usage.setSignedOutSharing(true);- usage.milestone(ProductHealthMeasure.funnelSetupSeen);- now = now.add(const Duration(minutes: 2));- usage.milestone(ProductHealthMeasure.funnelFirstWork);- usage.milestone(ProductHealthMeasure.funnelFirstWork);- now = now.add(const Duration(minutes: 4));- usage.milestone(ProductHealthMeasure.funnelFirstResponse);- await usage.flush();- expect(totals()['setup_desktop_funnel_first_work'], 1);- expect(totals()['setup_desktop_first_work_1m_to_5m'], 1);- expect(totals()['setup_desktop_first_response_over_5m'], 1);- expect(jsonEncode(setup), isNot(contains('PRIVATE')));- });+ test(+ 'setup funnel is once per local episode, with coarse waits and no identity',+ () async {+ usage.milestone(ProductHealthMeasure.funnelFirstWork);+ expect(totals(), isEmpty);+ usage.account(null);+ await usage.setSignedOutSharing(true);+ usage.milestone(ProductHealthMeasure.funnelSetupSeen);+ now = now.add(const Duration(minutes: 2));+ usage.milestone(ProductHealthMeasure.funnelFirstWork);+ usage.milestone(ProductHealthMeasure.funnelFirstWork);+ now = now.add(const Duration(minutes: 4));+ usage.milestone(ProductHealthMeasure.funnelFirstResponse);+ await usage.flush();+ expect(totals()['setup_desktop_funnel_first_work'], 1);+ expect(totals()['setup_desktop_first_work_1m_to_5m'], 1);+ expect(totals()['setup_desktop_first_response_over_5m'], 1);+ expect(jsonEncode(setup), isNot(contains('PRIVATE')));+ },+ );++ test(+ 'signed-in milestones remain in account-controlled health totals',+ () async {+ await usage.flush();+ usage.milestone(ProductHealthMeasure.funnelWorkspaceReady);+ usage.milestone(ProductHealthMeasure.funnelFirstWork);+ await usage.flush();+ expect(setup, isEmpty);+ expect(totals()['health_desktop_funnel_first_work'], 1);+ },+ );test('manual connect and automatic retries remain separate; missing outcomes expire as unknown', () async {await usage.flush();@@ -127,17 +142,42 @@ void main() {final connections = ProductConnections(usage);addTearDown(connections.dispose);connections.status('PRIVATE_MACHINE', connecting: true, connected: false);- connections.refused('PRIVATE_MACHINE', ProductHealthMeasure.connectErrorUnlinked);- connections.status('PRIVATE_MACHINE', connecting: true, connected: false, suppressStart: true);+ connections.refused(+ 'PRIVATE_MACHINE',+ ProductHealthMeasure.connectErrorUnlinked,+ );+ connections.status(+ 'PRIVATE_MACHINE',+ connecting: true,+ connected: false,+ suppressStart: true,+ );connections.status('PRIVATE_MACHINE', connecting: false, connected: false);for (var retry = 0; retry < 10; retry++) {- connections.status('PRIVATE_MACHINE', connecting: true, connected: false, suppressStart: true);- connections.refused('PRIVATE_MACHINE', ProductHealthMeasure.connectErrorUnlinked);- connections.status('PRIVATE_MACHINE', connecting: false, connected: false,- failure: ProductHealthMeasure.connectErrorUnlinked);+ connections.status(+ 'PRIVATE_MACHINE',+ connecting: true,+ connected: false,+ suppressStart: true,+ );+ connections.refused(+ 'PRIVATE_MACHINE',+ ProductHealthMeasure.connectErrorUnlinked,+ );+ connections.status(+ 'PRIVATE_MACHINE',+ connecting: false,+ connected: false,+ failure: ProductHealthMeasure.connectErrorUnlinked,+ );}final manual = connections.manual('PRIVATE_MACHINE');- connections.status('PRIVATE_MACHINE', connecting: true, connected: false, suppressStart: true);+ connections.status(+ 'PRIVATE_MACHINE',+ connecting: true,+ connected: false,+ suppressStart: true,+ );connections.status('PRIVATE_MACHINE', connecting: false, connected: true);manual(ProductOutcome.ok);// A later ordinary connection remains measurable.diff --git a/desktop/test/product_measurement_test.dart b/desktop/test/product_measurement_test.dartindex 1418e13d1..0a14b312d 100644--- a/desktop/test/product_measurement_test.dart+++ b/desktop/test/product_measurement_test.dart@@ -4,6 +4,20 @@ import 'dart:convert';import 'package:flutter_test/flutter_test.dart';import 'package:harness/measurement/product_measurement.dart';+import 'package:harness/core/local_key_value_store.dart';++import 'support/memory_key_value_store.dart';++class _DelayedSetupStore extends MemoryKeyValueStore {+ final loaded = Completer<String?>();+ @override+ Future<String?> read(String key) => loaded.future;+}++class _UnreadableSetupStore extends MemoryKeyValueStore {+ @override+ Future<String?> read(String key) async => throw StateError('PRIVATE_CANARY');+}void main() {late ProductMeasurement usage;@@ -42,23 +56,20 @@ void main() {}test(- 'signed-out sharing defaults off and opt-in never replays earlier actions',+ 'Desktop setup sharing defaults on without claiming explicit consent',() async {- usage.begin(ProductFlow.signIn)(ProductOutcome.failed);- await usage.flush();- expect(setup, isEmpty);- await usage.setSignedOutSharing(true);final finish = usage.begin(ProductFlow.signIn);finish(ProductOutcome.ok);finish(ProductOutcome.failed);await usage.flush();expect(setup.single.keys.toSet(), {'schemaVersion',- 'consent',+ 'sharing','id','day','counters',});+ expect(setup.single['sharing'], 'default');expect(setup.single['counters'], {'setup_desktop_sign_in_started': 1,'setup_desktop_sign_in_ok': 1,@@ -66,6 +77,162 @@ void main() {});},);+ ProductMeasurement withStore(LocalKeyValueStore storage) =>+ ProductMeasurement(+ surface: 'desktop',+ automatic: false,+ now: () => now,+ setupStorage: storage,+ sendSetup: (r) async {+ setup.add(jsonDecode(jsonEncode(r)));+ return {'accepted': true};+ },+ );++ test(+ 'a fresh persisted preference defaults on, and opt-out survives relaunch',+ () async {+ final store = MemoryKeyValueStore();+ final first = withStore(store);+ expect(first.choiceLoaded, isFalse);+ first.begin(ProductFlow.signIn)(ProductOutcome.failed);+ await first.setupChoiceReady;+ expect(first.signedOutSharing, isTrue);+ final pending = first.begin(ProductFlow.signIn);+ await first.setSignedOutSharing(false);+ pending(ProductOutcome.ok);+ await first.flush();+ first.dispose();+ expect(setup, isEmpty);+ expect(store.values, {+ ProductMeasurement.setupPreferenceKey:+ ProductMeasurement.pendingSetupOptOut,+ });+ final next = withStore(store);+ await next.setupChoiceReady;+ next.begin(ProductFlow.signIn)(ProductOutcome.ok);+ await next.flush();+ expect(setup, isEmpty);+ await next.setSignedOutSharing(true);+ next.begin(ProductFlow.signIn)(ProductOutcome.ok);+ await next.flush();+ next.dispose();+ expect(+ (setup.single['counters'] as Map)['setup_desktop_sign_in_started'],+ 1,+ );+ },+ );++ test('account opt-out persists through sign-out and relaunch', () async {+ final store = MemoryKeyValueStore();+ final first = withStore(store);+ await first.setupChoiceReady;+ first.account(+ 'PRIVATE_ACCOUNT',+ choice: () async => {'enabled': false, 'revision': 1},+ send: (_) async => {},+ );+ await first.flush();+ await first.setupChoiceSaved;+ first.account(null);+ expect(first.signedOutSharing, isFalse);+ first.dispose();+ final next = withStore(store);+ await next.setupChoiceReady;+ expect(next.signedOutSharing, isFalse);+ next.begin(ProductFlow.signIn)(ProductOutcome.ok);+ await next.flush();+ next.dispose();+ expect(setup, isEmpty);+ expect(store.values, {ProductMeasurement.setupPreferenceKey: 'false'});+ });++ test('a late local read cannot override an explicit opt-out', () async {+ final store = _DelayedSetupStore();+ final local = withStore(store);+ await local.setSignedOutSharing(false);+ store.loaded.complete('true');+ await local.setupChoiceReady;+ expect(local.signedOutSharing, isFalse);+ local.dispose();+ });++ test('default-on account lookup waits for the persisted opt-out', () async {+ final store = _DelayedSetupStore();+ final local = withStore(store);+ var reads = 0;+ local.account(+ 'PRIVATE_ACCOUNT',+ choice: () async {+ reads++;+ return {'enabled': true, 'revision': 0};+ },+ send: (_) async => throw StateError('No account report expected'),+ );+ final flushing = local.flush();+ expect(reads, 0);+ local.savedChoice({'enabled': true, 'revision': 0});+ expect(local.sharing, isFalse);+ store.loaded.complete(ProductMeasurement.pendingSetupOptOut);+ await flushing;+ expect(local.accountOptOutPending, isTrue);+ expect(local.sharing, isFalse);+ expect(local.signedOutSharing, isFalse);+ local.dispose();+ expect(setup, isEmpty);+ });++ test(+ 'local opt-out clears account observations before any re-enable',+ () async {+ await account();+ final finish = usage.begin(ProductFlow.remoteConnect);+ await usage.setSignedOutSharing(false);+ finish(ProductOutcome.ok);+ await usage.setSignedOutSharing(true);+ await usage.flush();+ expect(reports, isEmpty);+ },+ );++ test(+ 'unreadable and malformed local preferences do not enable sharing',+ () async {+ for (final store in [+ _UnreadableSetupStore(),+ MemoryKeyValueStore()+ ..values[ProductMeasurement.setupPreferenceKey] = 'broken',+ ]) {+ final local = withStore(store);+ await local.setupChoiceReady;+ local.begin(ProductFlow.signIn)(ProductOutcome.ok);+ await local.flush();+ expect(local.signedOutSharing, isFalse);+ local.dispose();+ }+ expect(setup, isEmpty);+ },+ );++ test(+ 'rapid preference changes persist in order without storing history',+ () async {+ final store = MemoryKeyValueStore();+ final local = withStore(store);+ await local.setupChoiceReady;+ await Future.wait([+ local.setSignedOutSharing(false),+ local.setSignedOutSharing(true),+ local.setSignedOutSharing(false),+ ]);+ local.dispose();+ expect(store.values, {+ ProductMeasurement.setupPreferenceKey:+ ProductMeasurement.pendingSetupOptOut,+ });+ },+ );test('off and account changes discard queued counts and open observations',() async {@@ -90,6 +257,28 @@ void main() {);},);+ test(+ 'setup opt-out discards retries and re-enabling does not replay them',+ () async {+ var attempts = 0;+ final local = ProductMeasurement(+ surface: 'desktop',+ automatic: false,+ sendSetup: (_) async {+ attempts++;+ throw StateError('PRIVATE_CANARY');+ },+ );+ local.begin(ProductFlow.signIn)(ProductOutcome.failed);+ await local.flush();+ expect(attempts, 1);+ await local.setSignedOutSharing(false);+ await local.setSignedOutSharing(true);+ await local.flush();+ local.dispose();+ expect(attempts, 1);+ },+ );test('retry is immutable, current events wait, and batching is bounded',() async {@@ -138,7 +327,7 @@ void main() {},);test(- 'unknown settings fail closed and account off also clears guest consent',+ 'unknown settings fail closed and account off also clears setup sharing',() async {await usage.setSignedOutSharing(true);usage.begin(ProductFlow.signIn)(ProductOutcome.ok);@@ -150,6 +339,25 @@ void main() {expect(usage.sharing, isFalse);},);+ test('phone setup retains its existing off-by-default choice', () async {+ final phone = ProductMeasurement(+ surface: 'phone',+ automatic: false,+ sendSetup: (r) async {+ setup.add(r);+ return {'accepted': true};+ },+ );+ phone.begin(ProductFlow.signIn)(ProductOutcome.ok);+ await phone.flush();+ expect(setup, isEmpty);+ await phone.setSignedOutSharing(true);+ phone.begin(ProductFlow.signIn)(ProductOutcome.ok);+ await phone.flush();+ phone.dispose();+ expect(setup.single['consent'], isTrue);+ expect(setup.single.containsKey('sharing'), isFalse);+ });test('expired RAM queues are discarded and unmatched setup remains unknown',() async {diff --git a/desktop/test/setup_measurement_transport_test.dart b/desktop/test/setup_measurement_transport_test.dartindex 451bcdd52..27bf14726 100644--- a/desktop/test/setup_measurement_transport_test.dart+++ b/desktop/test/setup_measurement_transport_test.dart@@ -5,8 +5,64 @@ import 'package:flutter_test/flutter_test.dart';import 'package:harness/measurement/setup_transport.dart';import 'package:harness/measurement/product_report_failure.dart';import 'package:harness/measurement/desktop_setup_report.dart';+import 'package:harness/measurement/product_measurement.dart';void main() {+ test(+ 'default Desktop counts cross the anonymous transport and stop on opt-out',+ () async {+ final server = await HttpServer.bind(InternetAddress.loopbackIPv4, 0);+ final reports = <Map<String, dynamic>>[];+ final listener = server.listen((request) async {+ expect(request.headers.value('authorization'), isNull);+ expect(request.headers.value('cookie'), isNull);+ reports.add(+ jsonDecode(await utf8.decoder.bind(request).join())+ as Map<String, dynamic>,+ );+ request.response.headers.contentType = ContentType.json;+ request.response.write(+ jsonEncode({+ 'data': {'accepted': true},+ }),+ );+ await request.response.close();+ });+ final usage = ProductMeasurement(+ surface: 'desktop',+ automatic: false,+ sendSetup: (report) => sendDesktopSetupMeasurement(+ 'http://127.0.0.1:${server.port}',+ report,+ ),+ );+ try {+ usage.begin(ProductFlow.signIn)(ProductOutcome.failed);+ await usage.flush();+ expect(reports.single.keys.toSet(), {+ 'schemaVersion',+ 'sharing',+ 'id',+ 'day',+ 'counters',+ });+ expect(reports.single['sharing'], 'default');+ expect(+ (reports.single['counters'] as Map)['setup_desktop_sign_in_failed'],+ 1,+ );+ final finish = usage.begin(ProductFlow.signIn);+ await usage.setSignedOutSharing(false);+ finish(ProductOutcome.ok);+ await usage.flush();+ expect(reports.length, 1);+ } finally {+ usage.dispose();+ await listener.cancel();+ await server.close(force: true);+ }+ },+ );test('a permanent setup rejection is classified without keeping its body',() async {diff --git a/desktop/test/setup_preference_store_test.dart b/desktop/test/setup_preference_store_test.dartnew file mode 100644index 000000000..e74ef695d--- /dev/null+++ b/desktop/test/setup_preference_store_test.dart@@ -0,0 +1,51 @@+import 'dart:io';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/measurement/product_measurement.dart';+import 'package:harness/measurement/setup_preference_store.dart';++void main() {+ late Directory directory;+ setUp(+ () async =>+ directory = await Directory.systemTemp.createTemp('setup-privacy-'),+ );+ tearDown(() async => directory.delete(recursive: true));++ Future<ProductMeasurement> open() async {+ final usage = ProductMeasurement(+ surface: 'desktop',+ automatic: false,+ setupStorage: SetupPreferenceStore(directory: directory),+ sendSetup: (_) async => {},+ );+ await usage.setupChoiceReady;+ addTearDown(usage.dispose);+ return usage;+ }++ test(+ 'a new installation defaults on and stores only privacy flags',+ () async {+ final first = await open();+ expect(first.signedOutSharing, isTrue);+ expect(await directory.list().toList(), isEmpty);+ await first.setSignedOutSharing(false);+ expect(+ await SetupPreferenceStore(directory: directory).file.readAsString(),+ ProductMeasurement.pendingSetupOptOut,+ );+ expect((await open()).signedOutSharing, isFalse);+ expect(await directory.list().length, 1);+ },+ );++ test('corrupt or unreadable state never becomes a fresh default', () async {+ final file = SetupPreferenceStore(directory: directory).file;+ await file.writeAsString('{broken');+ expect((await open()).signedOutSharing, isFalse);+ await file.delete();+ await Directory(file.path).create();+ expect((await open()).signedOutSharing, isFalse);+ });+}diff --git a/desktop/test/setup_privacy_flow_test.dart b/desktop/test/setup_privacy_flow_test.dartnew file mode 100644index 000000000..20c7dac99--- /dev/null+++ b/desktop/test/setup_privacy_flow_test.dart@@ -0,0 +1,246 @@+import 'dart:async';+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_riverpod/flutter_riverpod.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/app_shell.dart';+import 'package:harness/api/api_client.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/measurement/product_measurement.dart';+import 'package:harness/measurement/setup_usage_choice.dart';+import 'package:harness/settings/settings_screen.dart';+import 'package:harness/state/app_state.dart';+import 'package:package_info_plus/package_info_plus.dart';++import 'support/capture.dart';+import 'support/memory_key_value_store.dart';+import 'support/real_fonts.dart';++class _FailingWriteStore extends MemoryKeyValueStore {+ bool fail = true;+ @override+ Future<void> write(String key, String value) async {+ if (fail) throw StateError('PRIVATE_CANARY');+ await super.write(key, value);+ }+}++class _PreferenceApi extends ApiClient {+ _PreferenceApi()+ : super(+ config: AppConfig.dev,+ session: AuthSession(storage: MemoryKeyValueStore()),+ );+ final writes = <bool?>[];+ bool fail = true, enabled = true;+ @override+ Future<Map<String, dynamic>> productUsageSettings({bool? enabled}) async {+ writes.add(enabled);+ if (fail) throw StateError('PRIVATE_CANARY');+ if (enabled != null) this.enabled = enabled;+ return {'enabled': this.enabled, 'revision': 1};+ }+}++void main() {+ final capture = Platform.environment['HARNESS_SETUP_CHOICE_CAPTURE_DIR'];+ setUpAll(() async {+ await loadRealFonts();+ await loadCaptureFonts(capture);+ });+ PackageInfo.setMockInitialValues(+ appName: 'Harness',+ packageName: 'ai.autonomous.harness',+ version: '1.2.80',+ buildNumber: '80',+ buildSignature: '',+ );++ test('pre-sign-in opt-out survives relaunch and applies to the account before reports', () async {+ final store = MemoryKeyValueStore();+ final first = ProductMeasurement(+ surface: 'desktop',+ automatic: false,+ setupStorage: store,+ sendSetup: (_) async => {},+ );+ await first.setupChoiceReady;+ await first.setSignedOutSharing(false);+ first.dispose();+ final usage = ProductMeasurement(+ surface: 'desktop',+ automatic: false,+ setupStorage: store,+ sendSetup: (_) async => throw StateError('No setup report expected'),+ );+ final api = _PreferenceApi();+ final app = AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(storage: MemoryKeyValueStore()),+ productMeasurement: usage,+ )..api = api;+ addTearDown(app.dispose);+ usage.account(+ 'synthetic-account',+ choice: () => app.productUsageSettings(),+ send: (_) async => throw StateError('No account report expected'),+ );+ await usage.flush();+ expect(api.writes, [false]);+ expect(usage.accountOptOutPending, isTrue);+ expect(usage.sharing, isFalse);+ api.fail = false;+ await usage.flush();+ await usage.setupChoiceSaved;+ expect(api.writes, [false, false]);+ expect(usage.accountOptOutPending, isFalse);+ expect(usage.sharing, isFalse);+ expect(store.values, {ProductMeasurement.setupPreferenceKey: 'false'});+ await usage.flush();+ expect(+ api.writes.last,+ isNull,+ ); // The confirmed opt-out is not posted on every poll.+ });++ test('an account default cannot erase pending opt-out; an explicit Settings opt-in can', () async {+ final store = MemoryKeyValueStore();+ final usage = ProductMeasurement(+ surface: 'desktop',+ automatic: false,+ setupStorage: store,+ sendSetup: (_) async => {},+ );+ addTearDown(usage.dispose);+ await usage.setupChoiceReady;+ await usage.setSignedOutSharing(false);+ usage.account(+ 'synthetic-account',+ choice: () async => {'enabled': true, 'revision': 0},+ send: (_) async => {},+ );+ await usage.flush();+ expect(usage.sharing, isFalse);+ expect(usage.signedOutSharing, isFalse);+ expect(usage.accountOptOutPending, isTrue);+ expect(store.values, {+ ProductMeasurement.setupPreferenceKey:+ ProductMeasurement.pendingSetupOptOut,+ });+ usage.savedChoice({'enabled': true, 'revision': 0}, explicit: true);+ await usage.setupChoiceSaved;+ expect(usage.sharing, isTrue);+ expect(usage.accountOptOutPending, isFalse);+ expect(store.values, {ProductMeasurement.setupPreferenceKey: 'true'});+ });++ for (final status in [+ AppStatus.unauthenticated,+ AppStatus.preparingEnvironment,+ ]) {+ testWidgets(+ 'setup has no checkbox and its menu opens Privacy: ${status.name}',+ (tester) async {+ tester.view.devicePixelRatio = 1;+ tester.view.physicalSize = const Size(1100, 760);+ addTearDown(tester.view.reset);+ final store = MemoryKeyValueStore();+ final usage = ProductMeasurement(+ surface: 'desktop',+ automatic: false,+ setupStorage: store,+ sendSetup: (_) async => {'accepted': true},+ );+ await usage.setupChoiceReady;+ final app =+ AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(storage: MemoryKeyValueStore()),+ productMeasurement: usage,+ )+ ..signedIn = false+ ..status = status;+ await tester.pumpWidget(+ ProviderScope(+ overrides: [appStateProvider.overrideWithValue(app)],+ child: HarnessApp(+ authenticatedScreen: (_) => const SizedBox.shrink(),+ ),+ ),+ );+ await tester.pump(const Duration(milliseconds: 400));+ expect(find.byType(SetupUsageChoice), findsNothing);+ expect(find.text('Share setup and sign-in counts'), findsNothing);+ expect(usage.signedOutSharing, isTrue);+ await captureWindow(tester, capture, 'setup-${status.name}');++ // Deliver the same message as macOS's pre-workspace Settings menu.+ final closed = Completer<void>();+ tester.binding.defaultBinaryMessenger.handlePlatformMessage(+ 'harness/app_menu',+ const StandardMethodCodec().encodeMethodCall(+ const MethodCall('settings'),+ ),+ (_) => closed.complete(),+ );+ await tester.pumpAndSettle();+ expect(find.byType(SettingsScreen), findsOneWidget);+ expect(find.text('Share product usage data'), findsOneWidget);+ expect(tester.widget<Switch>(find.byType(Switch)).value, isTrue);+ await tester.tap(find.byType(Switch));+ await tester.pumpAndSettle();+ expect(usage.signedOutSharing, isFalse);+ expect(store.values, {+ ProductMeasurement.setupPreferenceKey:+ ProductMeasurement.pendingSetupOptOut,+ });+ await captureWindow(tester, capture, 'privacy-${status.name}-off');+ await tester.tap(find.byKey(const Key('settings-back-button')));+ await tester.pump(const Duration(milliseconds: 100));+ await closed.future;+ expect(find.byType(SettingsScreen), findsNothing);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox.shrink());+ app.dispose();+ },+ variant: TargetPlatformVariant.only(TargetPlatform.macOS),+ );+ }++ testWidgets('failed opt-out save stays off and retries that same choice', (+ tester,+ ) async {+ final store = _FailingWriteStore();+ final usage = ProductMeasurement(+ surface: 'desktop',+ automatic: false,+ setupStorage: store,+ sendSetup: (_) async => {},+ );+ await usage.setupChoiceReady;+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(body: SetupUsageChoice(measurement: usage)),+ ),+ );+ await tester.tap(find.byType(Switch));+ await tester.pumpAndSettle();+ expect(usage.signedOutSharing, isFalse);+ expect(find.textContaining('PRIVATE_CANARY'), findsNothing);+ expect(find.text('Retry saving'), findsOneWidget);+ store.fail = false;+ await tester.tap(find.text('Retry saving'));+ await tester.pumpAndSettle();+ expect(usage.signedOutSharing, isFalse);+ expect(store.values, {+ ProductMeasurement.setupPreferenceKey:+ ProductMeasurement.pendingSetupOptOut,+ });+ expect(find.text('Retry saving'), findsNothing);+ await tester.pumpWidget(const SizedBox.shrink());+ usage.dispose();+ });+}diff --git a/docs/product-measurement.md b/docs/product-measurement.mdindex 9af19b3ee..6d70de6ee 100644--- a/docs/product-measurement.md+++ b/docs/product-measurement.md@@ -22,12 +22,20 @@ automatically proven improvement. Changes still need review, tests and a deliber| Is measurement losing coverage? | Updated collector installation-days, pruned queues, full observation maps, unmatched app starts | Loss signals warrant caution. No signal does not prove complete collection. || How many people use Harness, and do they come back? | People active / working / new per day and per app, and D1/D2/D3/D7 returns (backend rollup of 10-day pseudonymous marks) | Sharing accounts only, staff excluded; an app open across midnight counts on both days, so prefer working returns. Not available before `PRODUCT_USAGE_SUBJECT_KEY` is set. |-Native signed-out sessions can explicitly enable **Share setup and sign-in counts**. It starts off-on every app launch, sends no credentials/cookies, and never replays earlier actions. Setup state-already visible when opted in can start an observation; duration then begins at that observation,-not necessarily at installation start. An account's off choice disables it once known. Web pre-sign-in-collection stays disabled because that transport cannot guarantee omitted cookies. These optional,-untrusted, self-selected counts are a separate population from signed-in app/daemon reports. They+Desktop setup and sign-in counts are enabled by default, with no onboarding checkbox. Users can+turn them off in **Settings → Privacy → Share product usage data**, including before sign-in through+the app menu. Local booleans remember the preference and a pending opt-out across launches; reporting waits for+that preference to load and stays off if it cannot be read. The confirmed account preference takes+over after sign-in and is remembered for the next signed-out launch. An explicit Settings opt-out+before sign-in is applied to the account before Desktop sharing can resume; failures keep it pending+and reporting off. An account's default-on response cannot erase that pending choice. Turning sharing off discards+queued counts and open observations. It does not retract a request already sent.+The phone retains its separate, off-by-default **Share setup and sign-in counts** choice for each+app session. Neither native setup transport sends credentials/cookies or replays earlier actions.+Setup state already visible when sharing becomes enabled can start an observation; duration then+begins at that observation, not necessarily at installation start. Web pre-sign-in collection stays+disabled because that transport cannot guarantee omitted cookies. These untrusted setup counts are+a separate population from signed-in app/daemon reports; older clients and opt-outs affect coverage. Theyshow observed friction at each step, **not** unique signup conversion or a linked user funnel.Reproduce those paths with test accounts and synthetic inputs. No screen recordings,click trails, stable analytics identifiers, locations, content or arbitrary properties are added.@@ -73,7 +81,7 @@ it cannot reliably detect an idle freeze. Error hooks pass only framework/asyncDesktop RSS and gateway RSS/CPU sample once per minute; they describe those processes, not thewhole machine or agents. Sampling adds no core timer, process enumeration, or subprocess.-Desktop's only new disk state is the last consented run's version, clean-exit/update flags, choice+Desktop keeps its setup-sharing preference and pending opt-out booleans, plus the last sharing-enabled run's version, clean-exit/update flags, choicerevision and a local-only account-scope hash. One serialized asynchronous write plus one latestpending value bounds disk work. It is cleared on sign-out/off and never enters a report. An uncleanrun can mean a force quit or power loss, and only becomes observable if the app returns. Update@@ -133,7 +141,9 @@ At most 64 observations wait in hn's RAM (a full queue drops the rest and says stheir own. A backend that predates `tui` refuses only those, and the daemon then drops hn's countsuntil the next UTC day or its own restart, without counting a failed delivery.-The signed-out endpoint permits only setup counters and explicit consent, rejects auth/cookie+The signed-out endpoint permits only setup counters. Older native clients send `consent: true`;+default-on Desktop sends `sharing: "default"`, accepted only for Desktop counters and never recorded+as an explicit opt-in. The two request forms are mutually exclusive. The endpoint rejects auth/cookieheaders, limits bodies to 4 KiB and values to 1,000, and admits at most 120 writes/minute and fourconcurrent writes per server process. No IP-based analytics or new rate-limit identity is stored.Exhaustion drops measurement rather than affecting sign-in. Public counts remain susceptible todiff --git a/docs/reviews/2026-10-16-setup-privacy/privacy.png b/docs/reviews/2026-10-16-setup-privacy/privacy.pngnew file mode 100644index 000000000..4cb8c6e12Binary files /dev/null and b/docs/reviews/2026-10-16-setup-privacy/privacy.png differdiff --git a/docs/reviews/2026-10-16-setup-privacy/sign-in.png b/docs/reviews/2026-10-16-setup-privacy/sign-in.pngnew file mode 100644index 000000000..458d1101eBinary files /dev/null and b/docs/reviews/2026-10-16-setup-privacy/sign-in.png differ