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
feat(desktop): offer Add Phone after work and after time away
tonydc1bdc4ed06b
diff --git a/backend/src/routes/productUsage.test.ts b/backend/src/routes/productUsage.test.tsindex aeee261df..4dc403f8e 100644--- a/backend/src/routes/productUsage.test.ts+++ b/backend/src/routes/productUsage.test.ts@@ -161,6 +161,8 @@ it('takes the Desktop\'s Add Phone card and each way into Add Phone, and no otheconst context = { surface: 'desktop', release: '1.2.73', platform: 'macos', channel: 'production' }const counters = { ui_desktop_phone_offer_started: 2, ui_desktop_phone_offer_ok: 1, ui_desktop_phone_offer_cancelled: 1,ui_desktop_phone_offer_unknown: 1, ui_desktop_phone_offer_over_1m: 1, ui_desktop_add_phone_offer: 1,+ ui_desktop_phone_offer_after_work_started: 1, ui_desktop_phone_offer_after_work_ok: 1,+ ui_desktop_phone_offer_away_waited_started: 1, ui_desktop_phone_offer_away_finished_cancelled: 1,ui_desktop_add_phone_titlebar: 2, ui_desktop_add_phone_menu: 1, ui_desktop_add_phone_account: 1,ui_desktop_add_phone_machines: 1, ui_desktop_add_phone_command: 1 }expect((await submit({ ...good, context, counters })).statusCode).toBe(200)diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.tsindex 726724746..02867c28c 100644--- a/backend/src/types/productUsage.ts+++ b/backend/src/types/productUsage.ts@@ -74,8 +74,13 @@ export const PRODUCT_USAGE_PHONE_SCREEN_METRICS = PRODUCT_USAGE_PHONE_SCREENS.fl/** Desktop's Add Phone card (desktop/lib/widgets/phone_offer_card.dart), offered once per computer: started* when it is on screen, ok for its Add Phone, cancelled for its ×, unknown when it goes another way (Add Phone* opened from elsewhere, a sign-out). It waits beside the work, so it has no 15-minute observation bound.- * Vocabulary 3 (`x-harness-usage-vocabulary`, cli/src/lib/appProductUsageReport.ts), like the openings below. */-export const PRODUCT_USAGE_DESKTOP_FLOWS = ['phone_offer'] as const+ * Vocabulary 3 (`x-harness-usage-vocabulary`, cli/src/lib/appProductUsageReport.ts), like the openings below.+ * `phone_offer_after_work` is the same card offered once to a computer that never showed it (a computer that+ * opened signed in was marked offered without it), after one of its own harnesses finished a turn; vocabulary 4.+ * `phone_offer_away_waited` / `_finished`: the card for a person back after five minutes or more away, to a harness+ * that waited on them or finished meanwhile; vocabulary 4. docs/design/2026-10-20-desktop-phone-conversion.md. */+export const PRODUCT_USAGE_DESKTOP_FLOWS = ['phone_offer', 'phone_offer_after_work', 'phone_offer_away_waited',+ 'phone_offer_away_finished'] as const/** Each time Add Phone opens on a computer, by its way in: that card (`offer`), the title bar's phone, Harness ▸* Add Phone… (`menu`, or a key bound to it on macOS), the account menu, the Machines picker, or the command* (`> add phone`, a key bound to it elsewhere). Which way in, nothing else. */diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex cca153d13..1b043ff99 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -450,7 +450,7 @@ describe('account Experimental settings proxy', () => {const newer = { ...body, counters: { ...body.counters, health_desktop_frame_slow_wait: 2, health_desktop_PRIVATE_CANARY: 1 } }const kept = await post(newer)expect(kept.status).toBe(200)- expect(kept.headers.get('x-harness-usage-vocabulary')).toBe('3')+ expect(kept.headers.get('x-harness-usage-vocabulary')).toBe('4')expect(send).toHaveBeenCalledExactlyOnceWith({ ...body,counters: { ...body.counters, health_desktop_frame_slow_wait: 2, health_desktop_report_unknown_metric: 1 } })expect(JSON.stringify(send.mock.calls)).not.toContain('PRIVATE_CANARY')@@ -463,7 +463,7 @@ describe('account Experimental settings proxy', () => {] as const) {const response = await post(refused, h)expect(response.status).toBe('x-adapter-local' in h ? 400 : 403)- expect(response.headers.get('x-harness-usage-vocabulary')).toBe('3')+ expect(response.headers.get('x-harness-usage-vocabulary')).toBe('4')expect(await response.text()).not.toContain('PRIVATE_CANARY')}expect(send).toHaveBeenCalledOnce()diff --git a/cli/src/lib/appProductUsageReport.spec.ts b/cli/src/lib/appProductUsageReport.spec.tsindex 168f74ea5..be28b55cd 100644--- a/cli/src/lib/appProductUsageReport.spec.ts+++ b/cli/src/lib/appProductUsageReport.spec.ts@@ -84,13 +84,15 @@ it('drops names this contract does not know yet, says so once, and refuses every]) expect(appProductUsageReport(refused), JSON.stringify(refused)).toBeUndefined()})-it('announces vocabulary 3, the revision whose frame-phase and Add Phone names a Desktop waits for', () => {- expect(APP_USAGE_VOCABULARY).toBe(3)+it('announces vocabulary 4, the revision whose frame-phase and Add Phone names a Desktop waits for', () => {+ expect(APP_USAGE_VOCABULARY).toBe(4)for (const measure of ['frame_slow_wait', 'frame_slow_build', 'frame_slow_raster', 'frame_long_collector']) {expect(appProductUsageReport({ ...native, counters: { [`health_desktop_${measure}`]: 1 } })).toBeDefined()}// The Add Phone card's flow and each way into Add Phone, from a Desktop, forwarded as they are.const addPhone = { ...native, counters: { ui_desktop_phone_offer_started: 1, ui_desktop_phone_offer_ok: 1,+ ui_desktop_phone_offer_after_work_started: 1, ui_desktop_phone_offer_after_work_cancelled: 1,+ ui_desktop_phone_offer_away_waited_ok: 1, ui_desktop_phone_offer_away_finished_unknown: 1,ui_desktop_phone_offer_cancelled: 1, ui_desktop_phone_offer_over_1m: 1,...Object.fromEntries(PRODUCT_USAGE_ADD_PHONE_METRICS.map(metric => [metric, 1])) } }expect(appProductUsageReport(addPhone)).toBe(addPhone)diff --git a/cli/src/lib/appProductUsageReport.ts b/cli/src/lib/appProductUsageReport.tsindex b454c189a..b232a576a 100644--- a/cli/src/lib/appProductUsageReport.ts+++ b/cli/src/lib/appProductUsageReport.ts@@ -4,10 +4,11 @@ import { PRODUCT_USAGE_ADD_PHONE_METRICS, PRODUCT_USAGE_METRICS, PRODUCT_USAGE_U/** The contract revision this proxy forwards, sent on each of its answers as `x-harness-usage-vocabulary`.* 2: the Desktop's frame-phase counters (`frame_slow_*`, `frame_long_collector`). 3: its Add Phone card- * (`ui_desktop_phone_offer_*`) and the ways Add Phone opened (`ui_desktop_add_phone_*`). The Desktop sends a- * name newer than revision 1 only once a proxy has announced it, so an older CLI never sees one. Raise it with- * each name the Desktop gates on it (`ProductHealthMeasure.vocabulary`, `ProductFlow.vocabulary`). */-export const APP_USAGE_VOCABULARY = 3+ * (`ui_desktop_phone_offer_*`) and the ways Add Phone opened (`ui_desktop_add_phone_*`). 4: the card offered+ * after work or after time away (`ui_desktop_phone_offer_after_work_*`, `ui_desktop_phone_offer_away_*`). The+ * Desktop sends a name newer than revision 1 only once a proxy has announced it, so an older CLI never sees one.+ * Raise it with each name the Desktop gates on it (`ProductHealthMeasure.vocabulary`, `ProductFlow.vocabulary`). */+export const APP_USAGE_VOCABULARY = 4export const APP_USAGE_VOCABULARY_HEADER = 'x-harness-usage-vocabulary'// hn's counts reach the daemon's own queue only through hn's `product_observe`; no app can file them.diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.tsindex 726724746..02867c28c 100644--- a/cli/src/lib/productUsageContract.ts+++ b/cli/src/lib/productUsageContract.ts@@ -74,8 +74,13 @@ export const PRODUCT_USAGE_PHONE_SCREEN_METRICS = PRODUCT_USAGE_PHONE_SCREENS.fl/** Desktop's Add Phone card (desktop/lib/widgets/phone_offer_card.dart), offered once per computer: started* when it is on screen, ok for its Add Phone, cancelled for its ×, unknown when it goes another way (Add Phone* opened from elsewhere, a sign-out). It waits beside the work, so it has no 15-minute observation bound.- * Vocabulary 3 (`x-harness-usage-vocabulary`, cli/src/lib/appProductUsageReport.ts), like the openings below. */-export const PRODUCT_USAGE_DESKTOP_FLOWS = ['phone_offer'] as const+ * Vocabulary 3 (`x-harness-usage-vocabulary`, cli/src/lib/appProductUsageReport.ts), like the openings below.+ * `phone_offer_after_work` is the same card offered once to a computer that never showed it (a computer that+ * opened signed in was marked offered without it), after one of its own harnesses finished a turn; vocabulary 4.+ * `phone_offer_away_waited` / `_finished`: the card for a person back after five minutes or more away, to a harness+ * that waited on them or finished meanwhile; vocabulary 4. docs/design/2026-10-20-desktop-phone-conversion.md. */+export const PRODUCT_USAGE_DESKTOP_FLOWS = ['phone_offer', 'phone_offer_after_work', 'phone_offer_away_waited',+ 'phone_offer_away_finished'] as const/** Each time Add Phone opens on a computer, by its way in: that card (`offer`), the title bar's phone, Harness ▸* Add Phone… (`menu`, or a key bound to it on macOS), the account menu, the Machines picker, or the command* (`> add phone`, a key bound to it elsewhere). Which way in, nothing else. */diff --git a/desktop/integration_test/phone_offer_away_native_test.dart b/desktop/integration_test/phone_offer_away_native_test.dartnew file mode 100644index 000000000..4cd67b2a9--- /dev/null+++ b/desktop/integration_test/phone_offer_away_native_test.dart@@ -0,0 +1,278 @@+import 'dart:io';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:integration_test/integration_test.dart';+import 'package:window_manager/window_manager.dart';++import 'package:harness/api/api_client.dart';+import 'package:harness/auth/auth_session.dart';+import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';+import 'package:harness/core/test_run.dart';+import 'package:harness/notify/alert_sounds.dart';+import 'package:harness/notify/system_notifications.dart';+import 'package:harness/screens/swarm_screen.dart';+import 'package:harness/shared/theme/app_theme.dart' as grid;+import 'package:harness/shared/theme/color_palette.dart';+import 'package:harness/state/app_state.dart';+import 'package:harness/state/pane_layout_store.dart';+import 'package:harness/state/swarm_catalog.dart';+import 'package:harness/terminal/terminal_session.dart';++import '../test/support/capture.dart';+import '../test/swarm_state_test.dart' show MemoryStore;++/// The Add Phone card after time away, in the real macOS window: a person leaves the window, one of+/// their harnesses finishes (or waits on them), and they come back 5 minutes or more later+/// (docs/design/2026-10-20-desktop-phone-conversion.md).+///+/// Run with FLUTTER_TEST=1. The account, its devices and the harnesses are fixtures: nothing reaches+/// the daemon or the backend (both point at a closed port), no notification is posted and no sound+/// plays. `HARNESS_PHONE_OFFER_SHOTS_DIR` is where the window's pictures go; AppKit's title bar is not+/// in them, as everything else Flutter draws is.+final _shotsDir = Platform.environment['HARNESS_PHONE_OFFER_SHOTS_DIR'];++/// Nothing listens there: a request this fixture did not answer itself is refused at once.+const _nowhere = AppConfig(+ apiBaseUrl: 'http://127.0.0.1:9',+ autonomousEnv: 'test',+ localCliBaseUrl: 'http://127.0.0.1:9',+);++/// An account with this computer on it and no phone or browser.+class _NoPhoneApi extends ApiClient {+ _NoPhoneApi() : super(config: _nowhere, session: AuthSession());++ @override+ Future<Map<String, dynamic>?> daemonDevices() async => {+ 'members': [+ {+ 'pub': 'pub-this-mac',+ 'label': 'This Mac',+ 'kind': 'machine',+ 'addedAt': 1,+ 'fingerprint': 'fp',+ 'self': true,+ },+ ],+ };+}++void main() {+ if (!kUnderTest) throw StateError('Use FLUTTER_TEST=1 with this fixture.');+ IntegrationTestWidgetsFlutterBinding.ensureInitialized().framePolicy =+ LiveTestWidgetsFlutterBindingFramePolicy.onlyPumps;+ setUpAll(() async {+ await windowManager.ensureInitialized();+ await windowManager.setSize(const Size(1280, 800));+ await windowManager.show();+ await windowManager.focus();+ });++ late DateTime now;+ late AppLifecycleState state;++ /// A signed-in computer at work: two harnesses open side by side, the window in front.+ AppNotifier working() {+ now = DateTime.utc(2026, 10, 20, 9);+ state = AppLifecycleState.resumed;+ final app =+ AppNotifier(+ config: _nowhere,+ authSession: AuthSession(),+ configStore: null,+ paneLayoutStore: PaneLayoutStore(storage: MemoryStore()),+ systemNotifications: SystemNotifications(+ notifier: const NoSystemNotifier(),+ ),+ alerts: AlertSounds(+ store: alertSoundStore,+ channel: const MethodChannel('phone-offer-fixture/quiet'),+ ),+ )+ ..hasNavigationRail = false+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..api = _NoPhoneApi()+ ..phoneOfferClock = (() => now)+ ..lifecycle = (() => state);+ const machine = Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: 'MacBook Pro',+ );+ app.machines = [machine];+ app.machineStates['m'] = MachineState(machine)+ ..nodeOnline = true+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded+ ..agents = [+ Agent(+ id: 'a0',+ name: 'Refactor auth flow',+ engine: 'codex',+ terminalAvailable: true,+ ),+ Agent(+ id: 'a1',+ name: 'Write release notes',+ engine: 'claude',+ terminalAvailable: true,+ ),+ ];+ for (final agent in app.machineStates['m']!.agents) {+ app.adoptSessionForTest(+ TerminalSession(+ machineId: 'm',+ agentId: agent.id,+ agentName: agent.name,+ engineId: agent.engine,+ send: (_, _) async => true,+ sendBinary: (_) async => true,+ )+ ..status = TerminalSessionStatus.controlling+ ..streamId = 'stream-${agent.id}',+ );+ }+ return app;+ }++ Future<void> mount(+ WidgetTester tester,+ AppNotifier app,+ Brightness brightness,+ ) async {+ grid.AppTheme.palette.value = brightness == Brightness.light+ ? HarnessPalette.paper+ : HarnessPalette.graphite;+ grid.AppTheme.brightness.value = brightness;+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ theme: grid.buildAppTheme(brightness: brightness),+ builder: (_, child) => grid.BrightnessScope(child: child!),+ home: SwarmScreen(notifier: app, projectStore: SwarmProjectStore()),+ ),+ );+ await settle(tester);+ }++ /// The window leaves the front, as the workspace's lifecycle listener reports it.+ void leave(AppNotifier app) {+ state = AppLifecycleState.inactive;+ app.appLifecycleChanged(AppLifecycleState.inactive);+ }++ /// Back in front, [after] it left.+ Future<void> back(+ WidgetTester tester,+ AppNotifier app,+ Duration after,+ ) async {+ now = now.add(after);+ state = AppLifecycleState.resumed;+ app.appLifecycleChanged(AppLifecycleState.resumed);+ await settle(tester);+ }++ testWidgets('a harness finished while the person was away', (tester) async {+ final app = working();+ addTearDown(app.dispose);+ await mount(tester, app, Brightness.dark);+ expect(find.byKey(const Key('phone-offer-card')), findsNothing);+ await captureWindow(tester, _shotsDir, '1-working-no-card');++ leave(app);+ now = now.add(const Duration(minutes: 2));+ await app.handleMachineEventForTest('m', {+ 'type': 'turn_summary',+ 'agentId': 'a0',+ 'payload': {+ 'agentId': 'a0',+ 'notification': {'id': 'n1', 'kind': 'done'},+ },+ });+ // Back 23 minutes after leaving: 21 minutes after the harness finished.+ await back(tester, app, const Duration(minutes: 21));+ expect(find.byKey(const Key('phone-offer-card')), findsOneWidget);+ expect(+ find.text('Refactor auth flow finished 21\u00A0min ago.'),+ findsOneWidget,+ );+ expect(+ find.text('Know the moment it’s done, on your phone.'),+ findsOneWidget,+ );+ await captureWindow(tester, _shotsDir, '2-back-finished-dark');++ await tester.tap(find.byKey(const Key('phone-offer-dismiss')));+ await settle(tester);+ expect(find.byKey(const Key('phone-offer-card')), findsNothing);+ await captureWindow(tester, _shotsDir, '3-after-dismiss');++ // Put away for good: the next time away offers nothing.+ leave(app);+ await app.handleMachineEventForTest('m', {+ 'type': 'turn_summary',+ 'agentId': 'a0',+ 'payload': {+ 'agentId': 'a0',+ 'notification': {'id': 'n2', 'kind': 'done'},+ },+ });+ await back(tester, app, const Duration(minutes: 30));+ expect(find.byKey(const Key('phone-offer-card')), findsNothing);+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 1));+ });++ testWidgets('a harness waited on the person while they were away', (+ tester,+ ) async {+ for (final brightness in [Brightness.dark, Brightness.light]) {+ final app = working();+ await mount(tester, app, brightness);+ leave(app);+ now = now.add(const Duration(minutes: 3));+ await app.handleMachineEventForTest('m', {+ 'type': 'commander_question',+ 'agentId': 'a1',+ 'payload': {+ 'requestId': 'q1',+ 'questions': [+ {+ 'key': 'Ship it?',+ 'q': 'Ship it?',+ 'options': ['Yes', 'No'],+ },+ ],+ },+ });+ await back(tester, app, const Duration(minutes: 18));+ expect(+ find.text('Write release notes waited 18\u00A0min for you.'),+ findsOneWidget,+ );+ expect(find.text('Answer from your phone next time.'), findsOneWidget);+ await captureWindow(+ tester,+ _shotsDir,+ '4-back-waited-${brightness.name}',+ );+ expect(tester.takeException(), isNull);+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 1));+ app.dispose();+ }+ });+}++/// Frames for what just changed, and the async work behind it (the device list read).+Future<void> settle(WidgetTester tester) async {+ for (var i = 0; i < 6; i++) {+ await tester.pump(const Duration(milliseconds: 100));+ }+}diff --git a/desktop/lib/measurement/product_measurement.dart b/desktop/lib/measurement/product_measurement.dartindex 3d0c656f4..1124b9499 100644--- a/desktop/lib/measurement/product_measurement.dart+++ b/desktop/lib/measurement/product_measurement.dart@@ -31,6 +31,13 @@ enum ProductFlow {// The Add Phone card (widgets/phone_offer_card.dart), offered once per computer: begun when it is on// screen, ok by its Add Phone, cancelled by its ×, unknown when it goes another way.phoneOffer('phone_offer'),+ // The same card offered once to a computer that never had it, after one of its own harnesses+ // finished a turn (`AppNotifier._offerPhoneAfterWork`): counted apart, so the two offers read apart.+ phoneOfferAfterWork('phone_offer_after_work'),+ // The same card offered when the person comes back after five minutes or more away to a harness+ // that waited on them, or one that finished (`AppNotifier._offerPhoneAway`), each counted apart.+ phoneOfferAwayWaited('phone_offer_away_waited'),+ phoneOfferAwayFinished('phone_offer_away_finished'),// The phone's own flows, listed so this enum names every flow the phone's copy does; the desktop// never begins them.signInScan('sign_in_scan'),@@ -49,12 +56,20 @@ enum ProductFlow {/// The revision of the local CLI's report proxy that knows this flow's/// names, as [ProductHealthMeasure.vocabulary] — but its counts wait in the/// queue for that answer instead of being skipped ([ProductMeasurement]).- int get vocabulary => this == phoneOffer ? 3 : 1;+ int get vocabulary => switch (this) {+ phoneOffer => 3,+ phoneOfferAfterWork || phoneOfferAwayWaited || phoneOfferAwayFinished => 4,+ _ => 1,+ };/// Ended only by what the person does, never by the 15-minute observation/// bound: the card waits beside the work until it is used or put away, and/// an Add Phone pressed after 15 minutes would otherwise be lost to unknown.- bool get unbounded => this == phoneOffer;+ bool get unbounded =>+ this == phoneOffer ||+ this == phoneOfferAfterWork ||+ this == phoneOfferAwayWaited ||+ this == phoneOfferAwayFinished;}enum ProductOutcome { ok, failed, cancelled, unknown }@@ -499,15 +514,24 @@ class ProductMeasurement extends ChangeNotifier {}/// The proxy revision ([proxyVocabulary]) that forwards [metric]: the Add- /// Phone card's flow and the ways Add Phone opened are 3, everything else- /// this queue holds is 1 (a health measure newer than 1 is never queued- /// before the proxy has named it, [health]).- static int _vocabularyOf(String metric) =>- metric.startsWith('ui_desktop_${ProductFlow.phoneOffer.wire}_')- ? ProductFlow.phoneOffer.vocabulary- : metric.startsWith('ui_desktop_add_phone_')- ? AddPhoneOpening.vocabulary- : 1;+ /// Phone card's flow and the ways Add Phone opened are 3, the card offered+ /// after work or after time away 4, everything else this queue holds is 1 (a+ /// health measure newer than 1 is never queued before the proxy has named+ /// it, [health]).+ static int _vocabularyOf(String metric) {+ for (final flow in _newerFlows) {+ if (metric.startsWith('ui_desktop_${flow.wire}_')) return flow.vocabulary;+ }+ return metric.startsWith('ui_desktop_add_phone_')+ ? AddPhoneOpening.vocabulary+ : 1;+ }++ /// The flows newer than revision 1, longest name first: `phone_offer_after_work_` starts with+ /// `phone_offer_`, and must be read as itself.+ static final _newerFlows =+ ProductFlow.values.where((flow) => flow.vocabulary > 1).toList()+ ..sort((a, b) => b.wire.length.compareTo(a.wire.length));/// A widget's delayed callback cannot count after sign-out or a choice revision.VoidCallback observer(ProductHealthMeasure measure) {diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 0c986eb6c..c6cfd5b2e 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -7270,6 +7270,7 @@ class _SwarmScreenState extends State<SwarmScreen> {onAdd: () => unawaited(_addPhone(from: AddPhoneOpening.offer)),onDismiss: app.dismissPhoneOffer,onShown: app.phoneOfferShown,+ away: app.phoneOfferAway,);}diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 232d0be05..095f932c6 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -934,8 +934,20 @@ class AppNotifier extends ChangeNotifier {if (_disposed) return;final wasForeground = foreground.value;foreground.value = state == null || state == AppLifecycleState.resumed;+ if (wasForeground && !foreground.value) {+ _awaySince = phoneOfferClock();+ _missedWhileAway = null;+ }// Back in front: a viewer reads the device log again, and joins it if the boot never got in.if (foreground.value && !wasForeground) {+ final away = _awaySince, missed = _missedWhileAway;+ _awaySince = null;+ _missedWhileAway = null;+ if (away != null &&+ missed != null &&+ phoneOfferClock().difference(away) >= phoneOfferAwayAfter) {+ unawaited(_offerPhoneAway(missed));+ }if (_notificationOfferDue) {_notificationOfferDue = false;unawaited(notificationOfferStoreForTest.set(true));@@ -1116,6 +1128,9 @@ class AppNotifier extends ChangeNotifier {// A card a sign-out or another sign-in takes away went neither way._endPhoneOffer(ProductOutcome.unknown);_phoneOffer = false;+ _phoneOfferAway = null;+ _missedWhileAway = null;+ _phoneOfferAfterWorkAsked = false;_closeOwnerMemories();_stopMachineRecovery();api.resetAccountCache();@@ -7166,9 +7181,22 @@ class AppNotifier extends ChangeNotifier {/// launch, which a new install makes as a guest ([_offerPhoneAtLaunch]), or else after the first/// sign-in by hand ([_offerPhoneAfterSignIn]) — never again once Add Phone has been opened here,/// the card put away, or the account found to have a phone ([_phoneOfferDone]).+ ///+ /// A computer that opened signed in was marked offered without ever showing the card, so it gets+ /// that one showing after work instead ([_offerPhoneAfterWork], [_phoneOfferSeen]).bool get phoneOfferShowing => _phoneOffer;bool _phoneOffer = false;+ /// Which offer [_phoneOffer] is: the first one's, the one after work ([_offerPhoneAfterWork]) or+ /// the one after time away ([_offerPhoneAway]), each counted as its own flow.+ ProductFlow _phoneOfferFlow = ProductFlow.phoneOffer;++ /// What the card says when it is offered after time away ([_offerPhoneAway]): the harness, whether+ /// it waited on the person or finished, and how many minutes ago. Null for the card's usual words.+ ({String agent, bool waited, int minutes})? get phoneOfferAway =>+ _phoneOffer ? _phoneOfferAway : null;+ ({String agent, bool waited, int minutes})? _phoneOfferAway;+/// The card's observation ([ProductFlow.phoneOffer]): begun once it is on screen/// ([phoneOfferShown]), ended once — ok by its Add Phone, cancelled by its ×, unknown when the/// card goes another way (Add Phone opened from elsewhere, a sign-out).@@ -7179,7 +7207,9 @@ class AppNotifier extends ChangeNotifier {/// offer, however often the card is built again.void phoneOfferShown() {if (!_phoneOffer || _phoneOfferMeasure != null) return;- _phoneOfferMeasure = productMeasurement.begin(ProductFlow.phoneOffer);+ _markPhoneOfferSeen();+ _countPhoneOfferShown();+ _phoneOfferMeasure = productMeasurement.begin(_phoneOfferFlow);}void _endPhoneOffer(ProductOutcome outcome) {@@ -7193,12 +7223,14 @@ class AppNotifier extends ChangeNotifier {void addPhoneOpened(AddPhoneOpening from) {productMeasurement.addPhoneOpened(from);if (from == AddPhoneOpening.offer) _endPhoneOffer(ProductOutcome.ok);+ _stopPhoneOffers();dropPhoneOffer();}- /// The card's ×: put away for good ([dropPhoneOffer]).+ /// The card's ×: put away for good ([dropPhoneOffer]), and no card after time away either.void dismissPhoneOffer() {_endPhoneOffer(ProductOutcome.cancelled);+ _stopPhoneOffers();dropPhoneOffer();}@@ -7210,7 +7242,9 @@ class AppNotifier extends ChangeNotifier {_endPhoneOffer(ProductOutcome.unknown);final showing = _phoneOffer;_phoneOffer = false;+ _phoneOfferAway = null;_markPhoneOfferDone();+ _markPhoneOfferSeen();if (showing) notifyListeners();}@@ -7245,6 +7279,210 @@ class AppNotifier extends ChangeNotifier {_paneLayout?.storage.write(_phoneOfferDoneKey, '1').catchError((_) {});}+ /// This computer's record that the card has been on its screen, or Add Phone opened here: unlike+ /// [_phoneOfferDoneKey], never written by a launch that only skipped the offer. What+ /// [_offerPhoneAfterWork] reads, so a computer sees the card once, whichever way it came.+ static const _phoneOfferSeenKey = 'phone_offer_seen';++ /// [_phoneOfferSeenKey], once read or written.+ bool? _phoneOfferSeenHere;++ /// Whether the card has had its one showing on this computer. Nowhere to remember it is taken as+ /// seen, as for [_phoneOfferDone].+ Future<bool> _phoneOfferSeen() async {+ if (_phoneOfferSeenHere case final seen?) return seen;+ final storage = _paneLayout?.storage;+ if (storage == null) return true;+ try {+ return _phoneOfferSeenHere =+ (await storage.read(_phoneOfferSeenKey)) == '1';+ } catch (_) {+ return true;+ }+ }++ void _markPhoneOfferSeen() {+ if (_phoneOfferSeenHere == true) return;+ _phoneOfferSeenHere = true;+ // Never awaited: a write that fails costs one more card on a later run.+ _paneLayout?.storage.write(_phoneOfferSeenKey, '1').catchError((_) {});+ }++ /// [_offerPhoneAfterWork] has been asked in this run, for this account: one devices read a run.+ bool _phoneOfferAfterWorkAsked = false;++ /// The card for a computer that has never shown it ([_phoneOfferSeen]), on an account with no phone+ /// or browser yet: once, after one of the person's own harnesses here finished a turn — beside work+ /// that just went well, not over a launch.+ ///+ /// ⚠️ **Every computer that opened signed in was marked offered at launch and never saw the card**+ /// ([_offerPhoneAtLaunch]): in the week to 2026-10-19, 59 of the 103 people working on Desktop used+ /// no phone, with only the title bar's icon to find Add Phone by. Still once per computer: a computer that+ /// showed the first card, or opened Add Phone, has seen it.+ Future<void> _offerPhoneAfterWork() async {+ if (_phoneOfferAfterWorkAsked ||+ _phoneOffer ||+ viewer != null ||+ !signedIn ||+ status != AppStatus.authenticated) {+ return;+ }+ _phoneOfferAfterWorkAsked = true;+ final revision = _authRevision;+ if (await _phoneOfferSeen()) return;+ bool hasPhone;+ try {+ final devices = await loadDevices();+ if (devices == null) {+ // No list to judge by: asked again at the next finished turn.+ _phoneOfferAfterWorkAsked = false;+ return;+ }+ hasPhone = devices.devices.any(+ (device) => !device.isMachine && !device.self,+ );+ } catch (_) {+ _phoneOfferAfterWorkAsked = false;+ return;+ }+ if (!_authWorkCurrent(revision) || !signedIn || _phoneOffer) return;+ if (hasPhone) {+ _markPhoneOfferSeen();+ return;+ }+ _phoneOfferFlow = ProductFlow.phoneOfferAfterWork;+ _phoneOfferAway = null;+ _phoneOffer = true;+ notifyListeners();+ }++ /// [_offerPhoneAfterWork], as a finished turn runs it.+ @visibleForTesting+ Future<void> offerPhoneAfterWorkForTest() => _offerPhoneAfterWork();++ /// This computer's record that the person said no to the card (its ×) or opened Add Phone: no card+ /// after time away from then on ([_offerPhoneAway]).+ static const _phoneOfferStoppedKey = 'phone_offer_stopped';++ /// How many times a card has been on this computer's screen, every kind together ([phoneOfferShown]).+ static const _phoneOfferShowsKey = 'phone_offer_shows';++ /// The most cards a computer is shown, every kind together: a card left unanswered may come back+ /// after time away, but not forever.+ static const phoneOfferMaxShows = 3;++ /// How long the window must have been away for a harness's news to offer Add Phone: long enough to+ /// have left the computer, not only to have looked at another window.+ static const phoneOfferAwayAfter = Duration(minutes: 5);++ /// The clock time away is measured by. Injected so a test can move it.+ @visibleForTesting+ DateTime Function() phoneOfferClock = DateTime.now;++ /// When the window last left the front ([appLifecycleChanged]); null while it is in front.+ DateTime? _awaySince;++ /// The news a person away from the window missed that says best what a phone is for: a harness+ /// waiting on them first, else the first to finish, with when it happened ([_noteMissedWhileAway]).+ ({String agent, bool waited, DateTime at})? _missedWhileAway;++ void _stopPhoneOffers() {+ // Never awaited: a write that fails costs, at most, one more card after time away.+ _paneLayout?.storage.write(_phoneOfferStoppedKey, '1').catchError((_) {});+ }++ /// Whether this computer is done with cards after time away: said no, opened Add Phone, or shown+ /// [phoneOfferMaxShows]. Nowhere to remember it is taken as done, as for [_phoneOfferDone].+ Future<bool> _phoneOfferAwayDone() async {+ final storage = _paneLayout?.storage;+ if (storage == null) return true;+ try {+ if ((await storage.read(_phoneOfferStoppedKey)) == '1') return true;+ final shows = int.tryParse(await storage.read(_phoneOfferShowsKey) ?? '');+ return (shows ?? 0) >= phoneOfferMaxShows;+ } catch (_) {+ return true;+ }+ }++ void _countPhoneOfferShown() {+ final storage = _paneLayout?.storage;+ if (storage == null) return;+ // Never awaited, and best effort: a count that is not kept costs one more card at most.+ unawaited(() async {+ try {+ final shows =+ int.tryParse(await storage.read(_phoneOfferShowsKey) ?? '') ?? 0;+ await storage.write(_phoneOfferShowsKey, '${shows + 1}');+ } catch (_) {}+ }());+ }++ /// [kind] of the harness [agent], called [title], told while the window was not in front: kept for+ /// the card when the person is back ([_offerPhoneAway]). Only one of the person's own harnesses here+ /// — not a shared computer's, not a plain terminal.+ void _noteMissedWhileAway(+ MachineState machine,+ Agent? agent,+ AlertKind kind,+ String title,+ ) {+ if (kind != AlertKind.done && kind != AlertKind.needsYou) return;+ if (agent == null ||+ machine.machine.isShared ||+ isTerminalEngine(agent.engine)) {+ return;+ }+ final waited = kind == AlertKind.needsYou;+ final missed = _missedWhileAway;+ // The longest wait or the earliest finish is the truest "while you were away"; a wait outranks+ // a finish, since that harness could not go on without the person.+ if (missed != null && (missed.waited || !waited)) return;+ _missedWhileAway = (agent: title, waited: waited, at: phoneOfferClock());+ }++ /// The card for a person back after [phoneOfferAwayAfter] or more away from the window, to a harness+ /// that waited on them or finished meanwhile ([missed]): what a phone would have told them where+ /// they were. On an account with no phone or browser yet, at most [phoneOfferMaxShows] cards a+ /// computer, and none once its card was put away or Add Phone opened ([_phoneOfferAwayDone]).+ Future<void> _offerPhoneAway(+ ({String agent, bool waited, DateTime at}) missed,+ ) async {+ if (_phoneOffer ||+ viewer != null ||+ !signedIn ||+ status != AppStatus.authenticated) {+ return;+ }+ final revision = _authRevision;+ if (await _phoneOfferAwayDone()) return;+ bool hasPhone;+ try {+ final devices = await loadDevices();+ // No list to judge by: nothing this time; the next time away asks again.+ if (devices == null) return;+ hasPhone = devices.devices.any(+ (device) => !device.isMachine && !device.self,+ );+ } catch (_) {+ return;+ }+ if (!_authWorkCurrent(revision) || !signedIn || _phoneOffer || hasPhone) {+ return;+ }+ final minutes = phoneOfferClock().difference(missed.at).inMinutes;+ _phoneOfferFlow = missed.waited+ ? ProductFlow.phoneOfferAwayWaited+ : ProductFlow.phoneOfferAwayFinished;+ _phoneOfferAway = (+ agent: missed.agent,+ waited: missed.waited,+ minutes: minutes < 1 ? 1 : minutes,+ );+ _phoneOffer = true;+ notifyListeners();+ }+/// The launch's half of the offer.////// ⚠️ **A new install opens as a guest**, on its desk, with no sign-in asked for — so "after the@@ -7260,6 +7498,8 @@ class AppNotifier extends ChangeNotifier {}if (!isGuest || await _phoneOfferDone()) return;if (!_authWorkCurrent(revision) || !isGuest) return;+ _phoneOfferFlow = ProductFlow.phoneOffer;+ _phoneOfferAway = null;_phoneOffer = true;notifyListeners();}@@ -7288,6 +7528,8 @@ class AppNotifier extends ChangeNotifier {_markPhoneOfferDone();return;}+ _phoneOfferFlow = ProductFlow.phoneOffer;+ _phoneOfferAway = null;_phoneOffer = true;notifyListeners();}@@ -12322,6 +12564,7 @@ class AppNotifier extends ChangeNotifier {if (lifecycle() != AppLifecycleState.resumed) {systemNotifications.post(alert);_noteNotificationOffer(kind);+ _noteMissedWhileAway(machine, agent, kind, alert.title);}}@@ -20039,6 +20282,7 @@ class AppNotifier extends ChangeNotifier {model: agent.gridModel,));machine.completedHarnessTurns++;+ unawaited(_offerPhoneAfterWork());} else if (ownWork) {machine.failedHarnessTurns++;}diff --git a/desktop/lib/widgets/agent_alert_banners.dart b/desktop/lib/widgets/agent_alert_banners.dartindex a610ea7d7..2172e7c99 100644--- a/desktop/lib/widgets/agent_alert_banners.dart+++ b/desktop/lib/widgets/agent_alert_banners.dart@@ -36,6 +36,15 @@ class AgentAlertBanners extends StatelessWidget {/// (`phone_offer_card.dart`).final Widget? footer;+ /// How far below the corner the [footer] starts when no banner is above it:+ /// past the top-right pane's header. A banner goes when it is read, but the+ /// card stays until it is answered, and at the corner it covered that pane's+ /// model and its × — the very pane waiting on the person, in the card after+ /// time away (owner, 2026-10-21). Measured: a 38 px header under the+ /// workspace inset ends 36.5 px below the banners' top edge; this leaves a+ /// gap past it.+ static const footerDrop = 48.0;+@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);@@ -56,7 +65,13 @@ class AgentAlertBanners extends StatelessWidget {padding: const EdgeInsets.only(bottom: 8),child: _Banner(alert: alert, notifier: notifier),),- ?footer,+ if (footer case final footer?)+ Padding(+ padding: EdgeInsets.only(+ top: alerts.isEmpty ? footerDrop : 0,+ ),+ child: footer,+ ),],);},diff --git a/desktop/lib/widgets/phone_offer_card.dart b/desktop/lib/widgets/phone_offer_card.dartindex c77dff58e..ca1028cae 100644--- a/desktop/lib/widgets/phone_offer_card.dart+++ b/desktop/lib/widgets/phone_offer_card.dart@@ -28,8 +28,39 @@ class PhoneOfferCard extends StatefulWidget {required this.onAdd,required this.onDismiss,this.onShown,+ this.away,});+ /// The card's words after time away ([AppNotifier.phoneOfferAway]): what a harness did while the+ /// person was gone, then what a phone would have done about it.+ ///+ /// ```+ /// ┌──────────────────────────────────────┐+ /// │ ▯ Codex waited 18 min for you. × │+ /// │ Answer from your phone next time. │+ /// │ ( Add Phone ) │+ /// └──────────────────────────────────────┘+ /// ```+ ///+ /// The minutes and "min" are held together by a no-break space: wrapped apart, the title read+ /// "finished 21" on one line and "min ago." on the next (owner, 2026-10-21).+ static ({String title, String detail}) awayWords({+ required String agent,+ required bool waited,+ required int minutes,+ }) => waited+ ? (+ title: '$agent waited $minutes\u00A0min for you.',+ detail: 'Answer from your phone next time.',+ )+ : (+ title: '$agent finished $minutes\u00A0min ago.',+ detail: 'Know the moment it’s done, on your phone.',+ );++ /// Offered after time away, the harness and what it did ([awayWords]); null for the usual words.+ final ({String agent, bool waited, int minutes})? away;+/// Add Phone: the code a phone scans — or, for a guest, the sign-in first.final VoidCallback onAdd;@@ -57,6 +88,17 @@ class _PhoneOfferCardState extends State<PhoneOfferCard> {@overrideWidget build(BuildContext context) {grid.AppTheme.watch(context);+ final away = widget.away;+ final words = away == null+ ? (+ title: 'Your agents in your pocket.',+ detail: 'When an agent needs you, answer from anywhere.',+ )+ : PhoneOfferCard.awayWords(+ agent: away.agent,+ waited: away.waited,+ minutes: away.minutes,+ );return Container(key: const Key('phone-offer-card'),width: 288,@@ -87,13 +129,17 @@ class _PhoneOfferCardState extends State<PhoneOfferCard> {mainAxisSize: MainAxisSize.min,children: [Text(- 'Your agents in your pocket.',+ words.title,+ key: const Key('phone-offer-title'),+ // A harness with a long name keeps the card its size.+ maxLines: 2,+ overflow: TextOverflow.ellipsis,style: AppType.body(color: AppColors.text).copyWith(fontWeight: FontWeight.w600, fontSize: 13),),const SizedBox(height: 1),Text(- 'When an agent needs you, answer from anywhere.',+ words.detail,style: AppType.body(color: AppColors.mutedStrong).copyWith(fontSize: 12),),diff --git a/desktop/test/agent_alert_banner_widget_test.dart b/desktop/test/agent_alert_banner_widget_test.dartindex 41c1eb204..946c9c999 100644--- a/desktop/test/agent_alert_banner_widget_test.dart+++ b/desktop/test/agent_alert_banner_widget_test.dart@@ -142,10 +142,10 @@ void main() {),);await tester.pump();- // No news: the footer alone, in the top-right.+ // No news: the footer alone, in the top-right, below the top-right pane's header.final alone = tester.getRect(find.byKey(const Key('banner-footer')));expect(alone.right, 1200 - 12);- expect(alone.top, 12);+ expect(alone.top, 12 + AgentAlertBanners.footerDrop);app.agentAlerts.post(AgentAlert(@@ -162,7 +162,8 @@ void main() {find.byKey(const Key('agent-alert-banner')),);final under = tester.getRect(find.byKey(const Key('banner-footer')));- expect(under.top, greaterThan(banner.bottom));+ // Already below the header: no drop on top of the banners' own gap.+ expect(under.top, banner.bottom + 8);expect(under.right, banner.right);await tester.tap(find.byKey(const Key('agent-alert-dismiss')));await tester.pumpAndSettle();diff --git a/desktop/test/phone_offer_test.dart b/desktop/test/phone_offer_test.dartindex b5027505b..c1ab37e77 100644--- a/desktop/test/phone_offer_test.dart+++ b/desktop/test/phone_offer_test.dart@@ -1,8 +1,10 @@import 'package:flutter/material.dart';+import 'package:flutter/rendering.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/api/api_client.dart';import 'package:harness/auth/auth_session.dart';import 'package:harness/core/config.dart';+import 'package:harness/core/models.dart';import 'package:harness/measurement/product_measurement.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/state/app_state.dart';@@ -10,22 +12,35 @@ import 'package:harness/widgets/add_phone_dialog.dart';import 'package:harness/widgets/phone_offer_card.dart';import 'support/add_phone_measurement.dart';-import 'swarm_screen_test.dart' show mount;+import 'swarm_screen_test.dart' show mount, terminal;import 'swarm_state_test.dart' show createApp, MemoryStore;/// This computer's record that Add Phone has had its offer.const _done = 'phone_offer_done';+/// This computer's record that the card has been on its screen, or Add Phone opened here.+const _seen = 'phone_offer_seen';++/// This computer's record that the card was put away or Add Phone opened: no card after time away.+const _stopped = 'phone_offer_stopped';++/// How many cards this computer has shown, every kind together.+const _shows = 'phone_offer_shows';+/// The daemon's device list, answered in memory: [listing], or a read that fails.class _DevicesApi extends ApiClient {_DevicesApi(this.listing, {this.fails = false}): super(config: AppConfig.dev, session: AuthSession());- final Map<String, dynamic>? listing;- final bool fails;+ Map<String, dynamic>? listing;+ bool fails;++ /// How many times the list was read.+ int reads = 0;@overrideFuture<Map<String, dynamic>?> daemonDevices() async {+ reads++;if (fails) throw StateError('The network connection was lost.');return listing;}@@ -145,6 +160,439 @@ void main() {});});+ group('after work, on a computer that never showed it', () {+ /// A computer that opened signed in — marked offered at launch, the card never on its screen —+ /// on an account answering [api], measured by [usage].+ Future<(AppNotifier, MemoryStore)> returning(+ _DevicesApi api, {+ MemoryStore? store,+ AddPhoneRecorder? usage,+ }) async {+ final kept = store ?? MemoryStore();+ final app = createApp(store: kept, productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..api = api;+ addTearDown(app.dispose);+ await app.offerPhoneForTest(atLaunch: true);+ expect(app.phoneOfferShowing, isFalse);+ expect(kept.values[_done], '1');+ return (app, kept);+ }++ /// One of the person's own harnesses here finishing a turn.+ Future<void> turnEnds(AppNotifier app, {bool failed = false}) async {+ app.adoptSessionForTest(terminal('a0', []));+ await app.handleMachineEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'a0',+ if (failed) 'error': 'ENGINE_FAILED',+ });+ await pumpEventQueue();+ }++ test('shows the card once a turn of its own finishes', () async {+ final (app, store) = await returning(_DevicesApi(_listing([])));+ await turnEnds(app);+ expect(app.phoneOfferShowing, isTrue);+ expect(store.values[_seen], isNull, reason: 'seen once on screen');+ app.phoneOfferShown();+ await pumpEventQueue();+ expect(store.values[_seen], '1');+ });++ test('is counted as its own flow, apart from the first offer', () async {+ final usage = AddPhoneRecorder();+ final (app, _) = await returning(_DevicesApi(_listing([])), usage: usage);+ await turnEnds(app);+ app.phoneOfferShown();+ app.addPhoneOpened(AddPhoneOpening.offer);+ expect(usage.started, ['phoneOfferAfterWork']);+ expect(usage.ended, ['phoneOfferAfterWork:ok']);+ });++ test(+ 'once per computer: not after it was put away, nor on a later run',+ () async {+ final api = _DevicesApi(_listing([]));+ final (app, store) = await returning(api);+ await turnEnds(app);+ app.phoneOfferShown();+ app.dismissPhoneOffer();+ await turnEnds(app);+ expect(app.phoneOfferShowing, isFalse);++ final (next, _) = await returning(api, store: store);+ await turnEnds(next);+ expect(next.phoneOfferShowing, isFalse);+ },+ );++ test('not on a computer that showed the first card', () async {+ final store = MemoryStore();+ final first = createApp(store: store)..signedIn = false;+ addTearDown(first.dispose);+ await first.offerPhoneForTest(atLaunch: true);+ first.phoneOfferShown();+ await pumpEventQueue();+ expect(store.values[_seen], '1');++ final (app, _) = await returning(_DevicesApi(_listing([])), store: store);+ await turnEnds(app);+ expect(app.phoneOfferShowing, isFalse);+ });++ test('not on a computer where Add Phone was opened by hand', () async {+ final (app, store) = await returning(_DevicesApi(_listing([])));+ app.addPhoneOpened(AddPhoneOpening.menu);+ await pumpEventQueue();+ expect(store.values[_seen], '1');+ await turnEnds(app);+ expect(app.phoneOfferShowing, isFalse);+ });++ test(+ 'an account with a phone or a browser is not offered it, ever again here',+ () async {+ for (final kind in ['phone', 'browser']) {+ final (app, store) = await returning(+ _DevicesApi(_listing([_device(kind)])),+ );+ await turnEnds(app);+ expect(app.phoneOfferShowing, isFalse, reason: kind);+ expect(store.values[_seen], '1', reason: kind);+ }+ },+ );++ test('a list it cannot read offers nothing yet, and is asked again at the next turn', () async {+ final api = _DevicesApi(_listing([]), fails: true);+ final (app, store) = await returning(api);+ await turnEnds(app);+ expect(app.phoneOfferShowing, isFalse);+ expect(store.values[_seen], isNull);+ api.fails = false;+ await turnEnds(app);+ expect(app.phoneOfferShowing, isTrue);++ // No list at all (an older daemon): the same, asked again at the next turn.+ final none = _DevicesApi(null);+ final (other, _) = await returning(none);+ await turnEnds(other);+ expect(other.phoneOfferShowing, isFalse);+ none.listing = _listing([]);+ await turnEnds(other);+ expect(other.phoneOfferShowing, isTrue);+ expect(none.reads, 2);+ });++ test(+ 'a failed turn offers nothing, and a run reads the list once',+ () async {+ final api = _DevicesApi(_listing([_device('phone')]));+ final (app, _) = await returning(api);+ await turnEnds(app, failed: true);+ expect(api.reads, 0);+ await turnEnds(app);+ await turnEnds(app);+ await turnEnds(app);+ expect(api.reads, 1);+ expect(app.phoneOfferShowing, isFalse);+ },+ );++ test('with nowhere to remember it, nothing is offered', () async {+ final api = _DevicesApi(_listing([]));+ final app = createApp()+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..api = api;+ addTearDown(app.dispose);+ await turnEnds(app);+ expect(app.phoneOfferShowing, isFalse);+ expect(api.reads, 0);+ });++ test('not while signed out', () async {+ final api = _DevicesApi(_listing([]));+ final app = createApp(store: MemoryStore())+ ..status = AppStatus.authenticated+ ..signedIn = false+ ..api = api;+ addTearDown(app.dispose);+ await app.offerPhoneAfterWorkForTest();+ expect(app.phoneOfferShowing, isFalse);+ expect(api.reads, 0);+ });+ });++ group('after time away', () {+ late DateTime now;+ late AppLifecycleState? state;++ /// A signed-in computer whose window is in front, on an account answering [api].+ Future<(AppNotifier, MemoryStore)> working(+ _DevicesApi api, {+ MemoryStore? store,+ AddPhoneRecorder? usage,+ }) async {+ now = DateTime.utc(2026, 10, 20, 9);+ state = AppLifecycleState.resumed;+ final kept = store ?? MemoryStore();+ final app = createApp(store: kept, productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..api = api+ ..phoneOfferClock = (() => now)+ ..lifecycle = (() => state);+ addTearDown(app.dispose);+ return (app, kept);+ }++ /// The window leaves the front.+ void leave(AppNotifier app) {+ state = AppLifecycleState.inactive;+ app.appLifecycleChanged(AppLifecycleState.inactive);+ }++ /// The window is back in front, [after] it left.+ Future<void> back(AppNotifier app, Duration after) async {+ now = now.add(after);+ state = AppLifecycleState.resumed;+ app.appLifecycleChanged(AppLifecycleState.resumed);+ await pumpEventQueue();+ }++ /// Harness `a0` ("Agent 0") finished a turn, with its notification.+ Future<void> finishes(AppNotifier app, {String id = 'n1'}) =>+ app.handleMachineEventForTest('m', {+ 'type': 'turn_summary',+ 'agentId': 'a0',+ 'payload': {+ 'agentId': 'a0',+ 'notification': {'id': id, 'kind': 'done'},+ },+ });++ /// Harness `a1` ("Agent 1") asks the person a question.+ Future<void> asks(AppNotifier app) => app.handleMachineEventForTest('m', {+ 'type': 'commander_question',+ 'agentId': 'a1',+ 'payload': {+ 'requestId': 'q1',+ 'questions': [+ {+ 'key': 'Which?',+ 'q': 'Which?',+ 'options': ['A', 'B'],+ },+ ],+ },+ });++ test(+ 'a harness that finished while the person was away 5 min or more',+ () async {+ final usage = AddPhoneRecorder();+ final (app, store) = await working(+ _DevicesApi(_listing([])),+ usage: usage,+ );+ leave(app);+ now = now.add(const Duration(minutes: 2));+ await finishes(app);+ await back(app, const Duration(minutes: 23));+ expect(app.phoneOfferShowing, isTrue);+ expect(app.phoneOfferAway, (+ agent: 'Agent 0',+ waited: false,+ minutes: 23,+ ));+ app.phoneOfferShown();+ await pumpEventQueue();+ expect(usage.started, ['phoneOfferAwayFinished']);+ expect(store.values[_shows], '1');+ },+ );++ test(+ 'a harness that waited on the person outranks one that finished',+ () async {+ final usage = AddPhoneRecorder();+ final (app, _) = await working(_DevicesApi(_listing([])), usage: usage);+ leave(app);+ await finishes(app);+ now = now.add(const Duration(minutes: 4));+ await asks(app);+ await back(app, const Duration(minutes: 18));+ expect(app.phoneOfferAway, (+ agent: 'Agent 1',+ waited: true,+ minutes: 18,+ ));+ app.phoneOfferShown();+ app.addPhoneOpened(AddPhoneOpening.offer);+ expect(usage.started, ['phoneOfferAwayWaited']);+ expect(usage.ended, ['phoneOfferAwayWaited:ok']);+ },+ );++ test('not after a shorter time away, nor with nothing missed', () async {+ final (app, _) = await working(_DevicesApi(_listing([])));+ leave(app);+ await finishes(app);+ await back(app, const Duration(minutes: 4, seconds: 59));+ expect(app.phoneOfferShowing, isFalse);++ leave(app);+ await back(app, const Duration(minutes: 30));+ expect(app.phoneOfferShowing, isFalse);+ });++ test('news from before the window left is not news from away', () async {+ final (app, _) = await working(_DevicesApi(_listing([])));+ // In front: a finish says nothing to the system and keeps nothing.+ await finishes(app);+ leave(app);+ await back(app, const Duration(minutes: 30));+ expect(app.phoneOfferShowing, isFalse);++ // Heard while the platform already said "not in front" but the window had not yet reported+ // leaving: that belongs to no time away, so leaving afterwards starts clean.+ state = AppLifecycleState.hidden;+ await finishes(app, id: 'n2');+ leave(app);+ await back(app, const Duration(minutes: 30));+ expect(app.phoneOfferShowing, isFalse);+ });++ test('its × stops it on this computer, for good', () async {+ final store = MemoryStore();+ final (app, _) = await working(_DevicesApi(_listing([])), store: store);+ leave(app);+ await finishes(app);+ await back(app, const Duration(minutes: 10));+ app.phoneOfferShown();+ app.dismissPhoneOffer();+ await pumpEventQueue();+ expect(store.values[_stopped], '1');++ final (next, _) = await working(_DevicesApi(_listing([])), store: store);+ leave(next);+ await finishes(next, id: 'n2');+ await back(next, const Duration(minutes: 10));+ expect(next.phoneOfferShowing, isFalse);+ });++ test('Add Phone opened any way stops it too', () async {+ final store = MemoryStore();+ final (app, _) = await working(_DevicesApi(_listing([])), store: store);+ app.addPhoneOpened(AddPhoneOpening.titlebar);+ await pumpEventQueue();+ expect(store.values[_stopped], '1');+ leave(app);+ await finishes(app);+ await back(app, const Duration(minutes: 10));+ expect(app.phoneOfferShowing, isFalse);+ });++ test(+ 'left unanswered, it comes back on a later run, three cards at most',+ () async {+ final store = MemoryStore();+ for (var run = 1; run <= 4; run++) {+ final (app, _) = await working(+ _DevicesApi(_listing([])),+ store: store,+ );+ leave(app);+ await finishes(app, id: 'n$run');+ await back(app, const Duration(minutes: 10));+ expect(app.phoneOfferShowing, run <= 3, reason: 'run $run');+ if (app.phoneOfferShowing) app.phoneOfferShown();+ await pumpEventQueue();+ }+ expect(store.values[_shows], '3');+ },+ );++ test('the other cards count toward the three', () async {+ final store = MemoryStore()..values[_shows] = '3';+ final (app, _) = await working(_DevicesApi(_listing([])), store: store);+ leave(app);+ await finishes(app);+ await back(app, const Duration(minutes: 10));+ expect(app.phoneOfferShowing, isFalse);+ });++ test(+ 'not on an account with a phone or a browser, nor with no list',+ () async {+ for (final api in [+ _DevicesApi(_listing([_device('phone')])),+ _DevicesApi(_listing([_device('browser')])),+ _DevicesApi(null),+ _DevicesApi(_listing([]), fails: true),+ ]) {+ final (app, _) = await working(api);+ leave(app);+ await finishes(app);+ await back(app, const Duration(minutes: 10));+ expect(app.phoneOfferShowing, isFalse);+ expect(api.reads, 1);+ }+ },+ );++ test('not for a shared computer\'s harness, nor while signed out, nor with nowhere to remember', () async {+ final (shared, _) = await working(_DevicesApi(_listing([])));+ const sharedMachine = Machine(+ machineId: 'm',+ authMode: MachineAuthMode.remote,+ name: 'Test host',+ isShared: true,+ );+ shared.machines = [sharedMachine];+ shared.machineStates['m'] = MachineState(sharedMachine)+ ..agents = shared.machineStates['m']!.agents;+ leave(shared);+ await finishes(shared);+ await back(shared, const Duration(minutes: 10));+ expect(shared.phoneOfferShowing, isFalse);++ final (out, _) = await working(_DevicesApi(_listing([])));+ out.signedIn = false;+ leave(out);+ await finishes(out);+ await back(out, const Duration(minutes: 10));+ expect(out.phoneOfferShowing, isFalse);++ final api = _DevicesApi(_listing([]));+ final nowhere = createApp()+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..api = api+ ..phoneOfferClock = (() => now)+ ..lifecycle = (() => state);+ addTearDown(nowhere.dispose);+ leave(nowhere);+ await finishes(nowhere);+ await back(nowhere, const Duration(minutes: 10));+ expect(nowhere.phoneOfferShowing, isFalse);+ expect(api.reads, 0);+ });++ test('a card already up is left as it is', () async {+ final (app, _) = await working(_DevicesApi(_listing([])));+ await app.offerPhoneAfterWorkForTest();+ expect(app.phoneOfferShowing, isTrue);+ leave(app);+ await finishes(app);+ await back(app, const Duration(minutes: 10));+ expect(app.phoneOfferAway, isNull);+ });+ });+group('its measure', () {/// A guest's first launch, with the card offered, measured by [usage].Future<AppNotifier> offered(AddPhoneRecorder usage) async {@@ -276,6 +724,133 @@ void main() {});});+ group('the card after time away', () {+ testWidgets(+ 'says what the harness did, then what a phone would have done',+ (tester) async {+ for (final (away, title, detail) in [+ (+ (agent: 'Codex', waited: true, minutes: 18),+ 'Codex waited 18\u00A0min for you.',+ 'Answer from your phone next time.',+ ),+ (+ (agent: 'Codex', waited: false, minutes: 25),+ 'Codex finished 25\u00A0min ago.',+ 'Know the moment it’s done, on your phone.',+ ),+ ]) {+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: Align(+ alignment: Alignment.topRight,+ child: PhoneOfferCard(+ onAdd: () {},+ onDismiss: () {},+ away: away,+ ),+ ),+ ),+ ),+ );+ expect(find.text(title), findsOneWidget);+ expect(find.text(detail), findsOneWidget);+ expect(+ find.widgetWithText(FilledButton, 'Add Phone'),+ findsOneWidget,+ );+ expect(find.text('Your agents in your pocket.'), findsNothing);+ }+ },+ );++ testWidgets('a long harness name keeps the card its size', (tester) async {+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: Align(+ alignment: Alignment.topRight,+ child: PhoneOfferCard(+ onAdd: () {},+ onDismiss: () {},+ away: (+ agent:+ 'Fix the login flow across every payment provider '+ 'and the account settings page too',+ waited: true,+ minutes: 7,+ ),+ ),+ ),+ ),+ ),+ );+ expect(tester.takeException(), isNull);+ final title = tester.widget<Text>(+ find.byKey(const Key('phone-offer-title')),+ );+ expect(title.maxLines, 2);+ expect(+ tester.getSize(find.byKey(const Key('phone-offer-card'))).width,+ 288,+ );+ });++ testWidgets('the minutes never wrap apart from "min"', (tester) async {+ // Every name length puts the line break somewhere else in the title.+ for (var length = 1; length <= 40; length++) {+ for (final waited in [true, false]) {+ await tester.pumpWidget(+ MaterialApp(+ theme: grid.buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: Align(+ alignment: Alignment.topRight,+ child: PhoneOfferCard(+ onAdd: () {},+ onDismiss: () {},+ away: (+ agent: 'Refactor auth flow and more'.padRight(length, 'x')+ .substring(0, length),+ waited: waited,+ minutes: 21,+ ),+ ),+ ),+ ),+ ),+ );+ final title = tester.renderObject<RenderParagraph>(+ find.descendant(+ of: find.byKey(const Key('phone-offer-title')),+ matching: find.byType(RichText),+ ),+ );+ final text = title.text.toPlainText();+ final digits = text.indexOf('21');+ final unit = text.indexOf('min', digits);+ // The title's own text, laid out at the title's own width.+ final painter = TextPainter(+ text: title.text,+ textDirection: title.textDirection,+ textScaler: title.textScaler,+ )..layout(maxWidth: title.size.width);+ addTearDown(painter.dispose);+ TextRange line(int offset) =>+ painter.getLineBoundary(TextPosition(offset: offset));+ expect(+ line(unit + 2),+ line(digits),+ reason: '"$text" wraps between the minutes and "min"',+ );+ }+ }+ });+ });+group('on the workspace', () {Future<(AppNotifier, MemoryStore)> offered(WidgetTester tester, {@@ -320,6 +895,41 @@ void main() {},);+ testWidgets('it leaves the top-right pane\'s header clear', (tester) async {+ final store = MemoryStore();+ final app = createApp(store: store)+ ..status = AppStatus.authenticated+ ..signedIn = false;+ addTearDown(app.dispose);+ app.adoptSessionForTest(terminal('a0', []));+ app.adoptSessionForTest(terminal('a1', []));+ await app.offerPhoneForTest(atLaunch: true);+ await mount(tester, app);+ final card = find.byKey(const Key('phone-offer-card'));+ final box = tester.getRect(card);+ final titles = find.byKey(const ValueKey('terminal-pane-title'));+ final right = tester+ .widgetList(titles)+ .map((title) => tester.getRect(find.byWidget(title)))+ .reduce((a, b) => a.left > b.left ? a : b);+ // The pane's header row — its name, its model, its × — is not under the card anywhere the+ // card spans, so the waiting pane can still be closed or switched.+ final cardObject = tester.renderObject(card);+ for (final y in [right.top, right.center.dy, right.bottom + 8]) {+ for (final x in [box.left + 8, box.center.dx, box.right - 8]) {+ final hits = tester.hitTestOnBinding(Offset(x, y)).path;+ expect(+ hits.any((entry) => identical(entry.target, cardObject)),+ isFalse,+ reason: 'the card covers the pane header at ($x, $y)',+ );+ }+ }+ expect(box.top, greaterThan(right.bottom));+ await tester.pumpWidget(const SizedBox());+ await tester.pump(const Duration(seconds: 5));+ });+testWidgets('× puts it away for good', (tester) async {final usage = AddPhoneRecorder();final (app, store) = await offered(tester, usage: usage);diff --git a/desktop/test/product_health_test.dart b/desktop/test/product_health_test.dartindex 640ab23d3..c4029f341 100644--- a/desktop/test/product_health_test.dart+++ b/desktop/test/product_health_test.dart@@ -476,6 +476,75 @@ void main() {},);+ test(+ 'the card offered after work waits for a CLI that forwards it, at 4',+ () async {+ await usage.flush();+ usage.begin(ProductFlow.phoneOfferAfterWork)(ProductOutcome.ok);+ usage.begin(ProductFlow.phoneOffer)(ProductOutcome.cancelled);+ // A CLI at 3 forwards the first card's names, not this one's.+ usage.proxyVocabulary = 3;+ await usage.flush();+ expect(addPhoneNames(), {+ 'ui_desktop_phone_offer_started',+ 'ui_desktop_phone_offer_cancelled',+ 'ui_desktop_phone_offer_under_1s',+ });+ usage.proxyVocabulary = 4;+ await usage.flush();+ expect(+ {+ for (final name in addPhoneNames())+ if (name.contains('after_work')) name: totals()[name],+ },+ {+ 'ui_desktop_phone_offer_after_work_started': 1,+ 'ui_desktop_phone_offer_after_work_ok': 1,+ 'ui_desktop_phone_offer_after_work_under_1s': 1,+ },+ );+ },+ );++ test('the cards after time away wait for 4, each read as itself', () async {+ await usage.flush();+ usage.begin(ProductFlow.phoneOfferAwayWaited)(ProductOutcome.ok);+ usage.begin(ProductFlow.phoneOfferAwayFinished)(ProductOutcome.unknown);+ usage.proxyVocabulary = 3;+ await usage.flush();+ expect(addPhoneNames().where((name) => name.contains('away')), isEmpty);+ usage.proxyVocabulary = 4;+ await usage.flush();+ expect(+ {+ for (final name in addPhoneNames())+ if (name.contains('away') && !name.contains('under_1s'))+ name: totals()[name],+ },+ {+ 'ui_desktop_phone_offer_away_waited_started': 1,+ 'ui_desktop_phone_offer_away_waited_ok': 1,+ 'ui_desktop_phone_offer_away_finished_started': 1,+ 'ui_desktop_phone_offer_away_finished_unknown': 1,+ },+ );+ expect(ProductFlow.phoneOfferAwayWaited.unbounded, isTrue);+ expect(ProductFlow.phoneOfferAwayFinished.unbounded, isTrue);+ });++ test('the card offered after work is not ended by the 15-minute bound', () async {+ await usage.flush();+ usage.proxyVocabulary = 4;+ final card = usage.begin(ProductFlow.phoneOfferAfterWork);+ now = now.add(const Duration(minutes: 40));+ await usage.flush();+ await usage.flush();+ expect(totals()['ui_desktop_phone_offer_after_work_unknown'], isNull);+ card(ProductOutcome.cancelled);+ await usage.flush();+ expect(totals()['ui_desktop_phone_offer_after_work_cancelled'], 1);+ });+test('the card is not ended by the 15-minute observation bound', () async {await usage.flush();usage.proxyVocabulary = 3;diff --git a/docs/design/2026-10-20-desktop-phone-conversion.md b/docs/design/2026-10-20-desktop-phone-conversion.mdnew file mode 100644index 000000000..d7eecb3b1--- /dev/null+++ b/docs/design/2026-10-20-desktop-phone-conversion.md@@ -0,0 +1,168 @@+# Desktop to phone: offering Add Phone to people already at work++October 20, 2026. Built in `desktop/lib/state/app_state.dart` and `desktop/lib/widgets/phone_offer_card.dart`.++## Goal++Get more people who already work in the Harness desktop app to add Harness on their phone. Harness on the phone is+what lets a harness that finished, or that waits on a question, reach the person when they are not at the+computer. Desktop users without it miss that, and find out about it only from a phone icon in the title bar.++**Success:** in a week, a higher share of the people working on Desktop also use Harness on their phone. Each+card's own flow (below) shows whether it is the card that brought them there.++**Not in scope:** the notification offer (`notificationOffer`), the Add Phone dialog itself, mobile onboarding.++## What the data showed (October 13–19)++| | People |+|---|---|+| Opened Desktop | 180 |+| ...with a harness at work on it | 103 |+| ...of those, did not use Harness on a phone that week | 59 (57%): 17 working 3 or more days, 42 now and then |+| ...of those, also used it on a phone | 44 (43%) |++Counted per account, staff accounts excluded. The 43% is the baseline to compare against. The card itself asks a+narrower question, "is there a phone or browser on the account?", because that is what the window can check.++The reason most of the 59 never saw an offer is in the code, not the data: the Add Phone card was offered once per+computer, at the first launch as a guest or after the first sign-in by hand (`_offerPhoneAtLaunch`,+`_offerPhoneAfterSignIn`). **A computer that opened already signed in was marked offered (`phone_offer_done`)+without the card ever showing.** That is every computer updated from an older Desktop, and every launch after the+first. For those people, the only way to Add Phone was the title bar's icon, the menu, or the command.++## What is built++The same top-right card (`PhoneOfferCard`) as the first offer, at two new moments. Nothing else in the window+changes, and Add Phone opens the same dialog. The card stands below the top-right pane's header+(`AgentAlertBanners.footerDrop`), not over it: it stays until it is answered, and at the corner it covered that+pane's model and its ×, often the very pane waiting on the person.++### 1. Once after work, on a computer that never showed the card++A computer that has never shown the card gets it **once**, right after one of the person's own harnesses on it+finishes a turn without an error. It shows beside work that just went well, not over a launch. Same words as the+first offer.++- "Own harness" is the same test the window uses for its own work counters: not a shared computer, not a plain+ terminal, open in a pane of this window, not a subagent.+- Asked once per run. If the account's device list cannot be read, it asks again at the next finished turn.+- A computer that already showed the card, or opened Add Phone, has seen it (`phone_offer_seen`).+- An account that already has a phone or browser marks the computer seen and shows nothing.++### 2. When the person comes back to news they missed++When the window has been away from the front for **5 minutes or more** (long enough to have left the computer, not+just looked at another window), and while it was away one of the person's own harnesses **waited on them** (a+question or a permission) or **finished**, the card shows when they come back. It says what a phone would have+told them while they were away:++| What happened | Title | Detail |+|---|---|---|+| A harness waited on them | `{Harness} waited {N} min for you.` | `Answer from your phone next time.` |+| A harness finished | `{Harness} finished {N} min ago.` | `Know the moment it’s done, on your phone.` |++- `{Harness}` is the harness's name as the window shows it; `{N}` is minutes since that news, at least 1.+- **A wait outranks a finish**: a waiting harness could not go on without the person. Between two of the same+ kind, the first one counts (the longest wait, the earliest finish).+- Only news that arrived while the window was away counts. News from before it left, from a shared computer, or+ from a plain terminal does not.+- The news is the one the system notification already reports (`_raiseAlert`, when the window is not in front).+ No new signal from the daemon.+- `{N}` and `min` are joined by a no-break space, so the title never wraps between them.++++++++### Rules shared by every card++- Only on an account with **no phone or browser** yet (`loadDevices`). No list to judge by: no card this time.+- **At most 3 cards per computer**, every kind together (the first offer, after work, after time away).+- **× or Add Phone opened (from the card or any other way in) stops the cards on this computer for good.**+- A card left unanswered stays on screen until the app closes or the person signs out. On a later run, the card+ after time away may come back, until the 3-card cap.+- Not in a viewer window, not signed out, not while another card is on screen.++### Why not ask about notifications here++The window already offers system notifications on its own (`notificationOffer`), and that offer is left as it is.+This card's job is one thing only: Add Phone. Mixing the two in one card would make neither clear.++## Where it is recorded on the computer++In the Desktop's local state file (`LocalKeyValueStore`, beside the dial's state):++| Key | Written when | Read by |+|---|---|---|+| `phone_offer_done` (existing) | Add Phone opened, card put away, account has a phone, or a signed-in launch | the first offer |+| `phone_offer_seen` | any card on screen, or Add Phone opened | the card after work |+| `phone_offer_stopped` | the card's ×, or Add Phone opened any way | the card after time away |+| `phone_offer_shows` | every card on screen, counted | the card after time away (cap 3) |++A state file that cannot be read is taken as "already done": no card, rather than a card at every launch.++## Measuring it++Each card is its own flow, so the moments compare with each other and with the first offer:++| Flow | Card |+|---|---|+| `phone_offer` | the first offer (existing) |+| `phone_offer_after_work` | once after work |+| `phone_offer_away_waited` | back to a harness that waited |+| `phone_offer_away_finished` | back to a harness that finished |++Metric names are `ui_desktop_<flow>_<measure>`. `started` counts cards on screen, `ok` its Add Phone, `cancelled`+its ×, and `unknown` a card that went another way (Add Phone from elsewhere, a sign-out). The flows have no+15-minute bound, because a card waits beside the work. `started` minus the outcomes is cards still up when the+app closed. Every Add Phone opening keeps its own count by way in (`ui_desktop_add_phone_<opening>`).++The card's `ok` is a dialog opened, not a phone added. The final measure stays the weekly share of people working+on Desktop who also use Harness on a phone, against the 43% baseline above.++The new flows are **vocabulary 4** (`x-harness-usage-vocabulary`): the Desktop keeps them queued until the local+CLI says it forwards vocabulary 4, so a Desktop on an older CLI loses none and sends none early. The names live in+`PRODUCT_USAGE_DESKTOP_FLOWS` (`backend/src/types/productUsage.ts`, copied to `cli/src/lib/productUsageContract.ts`).++## Rollout order++1. **Backend**: accepts the new names.+2. **CLI**: forwards them and announces vocabulary 4.+3. **Desktop**: offers the cards and counts them.++A Desktop released first still offers the cards; its counts wait for the CLI.++## Tests++- `desktop/test/phone_offer_test.dart`: the after-work card (once, own harness only, account with a phone, list+ unreadable then asked again) and the away card (5 minutes, wait outranks finish, shared and terminal news+ ignored, news from before leaving ignored, × and Add Phone stop it, 3-card cap, the words on the card, the+ minutes never wrapped apart from `min`, the top-right pane's header left clear).+- `desktop/test/agent_alert_banner_widget_test.dart`: the card stands below the pane header alone, and right+ under the banners when there are some.+- `desktop/test/product_health_test.dart`: the new flows' vocabulary and that they have no 15-minute bound.+- `desktop/integration_test/phone_offer_away_native_test.dart`: the whole story in the real macOS window (leave,+ a harness finishes or waits, back 18–21 minutes later, ×), and the pictures above. Fixtures only: nothing+ reaches the daemon or the backend, no notification is posted, no sound plays. Not run by CI; to run it and+ write the pictures:++ ```bash+ cd desktop+ FLUTTER_TEST=1 HARNESS_PHONE_OFFER_SHOTS_DIR=/tmp/phone-offer-shots \+ flutter test -d macos --no-pub integration_test/phone_offer_away_native_test.dart+ ```++ The pictures are what Flutter draws: AppKit's title bar is not in them, and the tab row is Flutter's own.+- `backend/src/routes/productUsage.test.ts`, `cli/src/lib/appProductUsageReport.spec.ts`,+ `cli/src/hookServer.spec.ts`: the names are accepted and vocabulary 4 is announced.++## Known limits++- A computer that put the first card away before this release has only `phone_offer_done`, which cannot tell a ×+ from a signed-in launch. It may see the card once more; its × then stops it for good.+- Away time follows the window (`appLifecycleChanged`), not the person. A window left behind another app for 5+ minutes while the person sat at the computer counts as away. The card then says what happened, which stays true.+- Counts are per computer, not per person: a person with two computers can see up to 3 cards on each.diff --git a/docs/design/images/phone-offer-away-finished.png b/docs/design/images/phone-offer-away-finished.pngnew file mode 100644index 000000000..0fd04e9c9Binary files /dev/null and b/docs/design/images/phone-offer-away-finished.png differdiff --git a/docs/design/images/phone-offer-away-waited-light.png b/docs/design/images/phone-offer-away-waited-light.pngnew file mode 100644index 000000000..dd55e3b48Binary files /dev/null and b/docs/design/images/phone-offer-away-waited-light.png differdiff --git a/docs/design/images/phone-offer-away-waited.png b/docs/design/images/phone-offer-away-waited.pngnew file mode 100644index 000000000..83f651ce8Binary files /dev/null and b/docs/design/images/phone-offer-away-waited.png differdiff --git a/docs/product-measurement.md b/docs/product-measurement.mdindex 6ec6a0541..4397e8439 100644--- a/docs/product-measurement.md+++ b/docs/product-measurement.md@@ -22,7 +22,7 @@ automatically proven improvement. Changes still need review, tests and a deliber| Where does the phone's onboarding stall? | After sign-in: waiting for the first computer, opening its session, the first message, the notification prompt. A sign-in that went through, by button, counted again under the account's sharing. Waits past a minute split into 1–5 min, 5–15 min, 15 min–1 h and over 1 h for the computer and the first message. Once per step per sign-in: `resumed` (reopened in a run that did not sign in), "Not you? Sign out", the address sent from the share sheet, a joining computer that wants its password or is offline, `joined_after_leaving` (the computer turned up after the app left the wait), `new_account` (a sign-in that created the account). Once per install: `first_open` (signed out `setup_phone_first_open`, signed in `ui_phone_first_open`) | Stage totals per day, not a linked funnel. A wait's `ok` is a computer that turned up while its screen was open: add `joined_after_leaving` for the computers that came while the app was away (16–19 October 2026: 5 `ok` in 49 fresh waits, while 91% of the phone's people had a computer on the same account). `new_account` is an account minutes old at sign-in, its first Harness sign-in anywhere. `first_open` is set once per install by a local flag that is never sent: the step between a store's download and a sign-in. Subtract `resumed` from starts for fresh starts; an unmatched start is a closed app or a step still waiting. A resumed step's duration starts at the reopening. Signed-in sign-in counts are successes only; failures and cancels before an account remain the signed-out counts', but a success is marked `retried` (a failed or cancelled try came first in that app run) or `switched` (another button was tried first). Phone reports carry release and iOS/Android, so every phone count also splits by those two margins (above 20 collector days); debug builds are not kept. A chosen sign-out sends what is queued first (up to 2 s), so "Not you? Sign out" reaches the totals. The first message is the first line sent after the hand-over in any session, or a task typed into New Harness; before 2026-10-20 only the session the hand-over opened counted and leaving it cancelled the step (compare releases separately). Each step of a sign-in that created its account is marked `new_account` when counted and `new_account_ok` when it ends ok, so new people's funnel reads apart. The phone sends what it queued as it leaves the screen, since iOS can end a suspended app with its counts still in RAM. || How fast does the phone get back to work? | A launch that came back signed in, to its first computer answering (`app_start`); a dial the person asked for ("Try again", `connect_user`) apart from the app's own (`connect_auto`), beside the unchanged `remote_connect`; a stopped harness resumed from the phone, to its first live turn (`resume_recovery`) | A launch that signs in is the onboarding's and is not counted; one that leaves the screen before a computer answers is `unknown`, one whose computers never answer stays started. What a launch waited on is counted beside it, once each, until a computer answers or the app leaves the screen (`ui_phone_app_start_<why>`): `no_computer` and `list_failed` (the account's list had none, or could not be read), `offline` (it said every computer was offline), `locked` (a computer wanted the phone's password), `connect_failed` (a dial to a computer said to be online failed) and `waited_1m` (a minute on screen); a launch can name several. An asked-for dial fails at 12 s, as Desktop Connect does. A phone dial is `failed` only when the phone knows why (locked or offline), `unknown` otherwise; the reasons (`connect_error_*`) are Desktop health counters. || Are the phone's side pages used? | Find and Computers opens, by a sideways swipe on the terminal or by a button (Computers' row in Settings, its link on a long wait at home) | Which page and which way, nothing more. Find's key and screen-reader actions are not counted; a swipe that lets Find go back opened nothing. |-| Does Desktop's Add Phone card get used, and where else is Add Phone opened? | The card's flow (`ui_desktop_phone_offer_*`): started once it is on screen, `ok` by its Add Phone, `cancelled` by its ×, `unknown` when it went another way (Add Phone opened from elsewhere, a sign-out); every Add Phone opening by its way in (`ui_desktop_add_phone_<offer\|titlebar\|menu\|account\|machines\|command>`) | The card is offered once per computer, so its starts are computers, not people, and it has no 15-minute bound: started minus outcomes is an app closed with the card still up. An opening is the dialog shown, not a phone paired. `menu` includes a key bound to Harness ▸ Add Phone… on macOS; `command` is `> add phone` or a key bound to it elsewhere. The browser counts none. Vocabulary 3: counted from the start, but sent only once the local CLI has answered that it forwards them, so a Desktop on an older CLI sends none. |+| Does Desktop's Add Phone card get used, and where else is Add Phone opened? | The card's flow (`ui_desktop_phone_offer_*`): started once it is on screen, `ok` by its Add Phone, `cancelled` by its ×, `unknown` when it went another way (Add Phone opened from elsewhere, a sign-out); every Add Phone opening by its way in (`ui_desktop_add_phone_<offer\|titlebar\|menu\|account\|machines\|command>`) | The card is offered once per computer, so its starts are computers, not people, and it has no 15-minute bound: started minus outcomes is an app closed with the card still up. An opening is the dialog shown, not a phone paired. `menu` includes a key bound to Harness ▸ Add Phone… on macOS; `command` is `> add phone` or a key bound to it elsewhere. A computer that opened signed in was marked offered without ever showing the card; from 2026-10-20 it shows the card once after one of its own harnesses finishes a turn, if the account has no phone or browser, counted apart as `ui_desktop_phone_offer_after_work_*` (vocabulary 4). The same card also shows to a person back after 5 minutes or more away to one of their harnesses that waited on them or finished meanwhile, counted as `ui_desktop_phone_offer_away_waited_*` / `ui_desktop_phone_offer_away_finished_*` (vocabulary 4): at most 3 cards a computer, every kind together, and none once a card's × or Add Phone was used there ([design](design/2026-10-20-desktop-phone-conversion.md)). The browser counts none. Vocabulary 3: counted from the start, but sent only once the local CLI has answered that it forwards them, so a Desktop on an older CLI sends none. || 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. || What do people do on the Hub? | Page views by page and signed-out/signed-in reader, the first page of a tab's visit by where it came from (direct, search, social, internal, other; classified in the browser, the referrer is never sent), clicks and submits (search, sort, like, comment, share, fork, follow, report, sign-in prompt, publish), and how long a harness page stayed visible (under 10 s, 10 s–1 min, over 1 min). A shared link (`/s/:id`, the web app) counts the same way: the page drawn by reader, what it showed (live, owner offline, private, no access, failed), how long a live harness stayed visible, and its clicks (comments, comment posted, sign-in, retry, Download app, product page), plus once when its live viewer draws | Unlinked daily totals of views, entries, clicks and dwell buckets: not people, not a funnel. Public counts that can be fabricated; directional only. Browsers sending Global Privacy Control or Do Not Track, and signed-in readers who turned sharing off, are not counted. The website's server strips cookies and auth before forwarding. |@@ -207,7 +207,7 @@ the name is dropped, never forwarded or logged, and a Desktop report counts`health_desktop_report_unknown_metric` once. Earlier CLIs refused the whole report, and the Desktopdiscards a refused packet. A known name an app may not send, a bad value, or a report with no knowncounter left is still refused. Every answer of that route carries `x-harness-usage-vocabulary`, the-revision of the names it forwards (2: the frame phases; 3: the Add Phone card and openings); a Desktop sends newer names only after reading it. The frame phases are not counted until then; the Add Phone counts wait in the queue for it, because the card shows once per computer, often before the first answer.+revision of the names it forwards (2: the frame phases; 3: the Add Phone card and openings; 4: the card offered after work and after time away); a Desktop sends newer names only after reading it. The frame phases are not counted until then; the Add Phone counts wait in the queue for it, because the card shows once per computer, often before the first answer.Desktop and phone collectors keep only fixed counters in RAM, at most 64 in-flight observations,with at most 32 counters per report, one pending report per channel and one flush at a time.