Skip to content

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.

feat(mobile): flush counts on background, mark new accounts, retry stop

tony84625abff40f
diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.ts
index d27d5ad02..726724746 100644
--- a/backend/src/types/productUsage.ts
+++ b/backend/src/types/productUsage.ts
@@ -43,6 +43,11 @@ export const PRODUCT_USAGE_LONG_MEASURES = ['1m_to_5m', '5m_to_15m', '15m_to_1h'
* while 91% of the phone's people had a computer on the same account those days). */
export const PRODUCT_USAGE_ONBOARDING_MARKS = ['ui_phone_sign_in_retried', 'ui_phone_sign_in_switched',
'ui_phone_sign_in_new_account',
+ // The steps after a sign-in that made its account: started (counted) and ended `ok` there, so the new
+ // people's funnel reads apart from everyone signing in again (mobile/lib/measurement/onboarding_measurement.dart).
+ 'ui_phone_computer_wait_new_account', 'ui_phone_computer_wait_new_account_ok',
+ 'ui_phone_session_open_new_account', 'ui_phone_session_open_new_account_ok',
+ 'ui_phone_first_message_new_account', 'ui_phone_first_message_new_account_ok',
'ui_phone_computer_wait_resumed', 'ui_phone_computer_wait_not_you',
'ui_phone_computer_wait_link_shared', 'ui_phone_computer_wait_joined_after_leaving',
'ui_phone_session_open_resumed', 'ui_phone_session_open_blocked_password',
@@ -134,6 +139,9 @@ export const LAUNCH_ERROR_CODES = [
'restart_failed', 'restart_unsupported_backend', 'retarget_unsupported_backend', 'fork_on_grid_unsupported',
'no_active_process', 'opencode_sqlite_missing', 'unavailable', 'missing_name', 'missing_update',
'invalid_close_request', 'invalid_delete_request', 'close_failed', 'delete_failed',
+ // A Stop (`agent_delete`) the machine could not confirm, or whose harness changed while it saved
+ // (lib/stopAgentService.ts): 3 of the phone's 4 stops on 2026-10-19 were refused as `other`, the kind it falls under.
+ 'stop_unconfirmed',
// A guest on a machine shared with it (core/guestPolicy.ts, core/agents/guestCreate.ts, services/guestLaunches.ts).
'guest_not_allowed', 'guest_unsupported', 'guest_harness', 'guest_unavailable', 'guest_helper_required',
'guest_engine_unsupported', 'guest_relay_failed', 'guest_folder_unavailable', 'guest_invalid', 'guest_helper_missing',
diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.ts
index d27d5ad02..726724746 100644
--- a/cli/src/lib/productUsageContract.ts
+++ b/cli/src/lib/productUsageContract.ts
@@ -43,6 +43,11 @@ export const PRODUCT_USAGE_LONG_MEASURES = ['1m_to_5m', '5m_to_15m', '15m_to_1h'
* while 91% of the phone's people had a computer on the same account those days). */
export const PRODUCT_USAGE_ONBOARDING_MARKS = ['ui_phone_sign_in_retried', 'ui_phone_sign_in_switched',
'ui_phone_sign_in_new_account',
+ // The steps after a sign-in that made its account: started (counted) and ended `ok` there, so the new
+ // people's funnel reads apart from everyone signing in again (mobile/lib/measurement/onboarding_measurement.dart).
+ 'ui_phone_computer_wait_new_account', 'ui_phone_computer_wait_new_account_ok',
+ 'ui_phone_session_open_new_account', 'ui_phone_session_open_new_account_ok',
+ 'ui_phone_first_message_new_account', 'ui_phone_first_message_new_account_ok',
'ui_phone_computer_wait_resumed', 'ui_phone_computer_wait_not_you',
'ui_phone_computer_wait_link_shared', 'ui_phone_computer_wait_joined_after_leaving',
'ui_phone_session_open_resumed', 'ui_phone_session_open_blocked_password',
@@ -134,6 +139,9 @@ export const LAUNCH_ERROR_CODES = [
'restart_failed', 'restart_unsupported_backend', 'retarget_unsupported_backend', 'fork_on_grid_unsupported',
'no_active_process', 'opencode_sqlite_missing', 'unavailable', 'missing_name', 'missing_update',
'invalid_close_request', 'invalid_delete_request', 'close_failed', 'delete_failed',
+ // A Stop (`agent_delete`) the machine could not confirm, or whose harness changed while it saved
+ // (lib/stopAgentService.ts): 3 of the phone's 4 stops on 2026-10-19 were refused as `other`, the kind it falls under.
+ 'stop_unconfirmed',
// A guest on a machine shared with it (core/guestPolicy.ts, core/agents/guestCreate.ts, services/guestLaunches.ts).
'guest_not_allowed', 'guest_unsupported', 'guest_harness', 'guest_unavailable', 'guest_helper_required',
'guest_engine_unsupported', 'guest_relay_failed', 'guest_folder_unavailable', 'guest_invalid', 'guest_helper_missing',
diff --git a/cli/src/lib/productUsageSignals.spec.ts b/cli/src/lib/productUsageSignals.spec.ts
index a7a32e16f..a2cb2cba9 100644
--- a/cli/src/lib/productUsageSignals.spec.ts
+++ b/cli/src/lib/productUsageSignals.spec.ts
@@ -155,6 +155,17 @@ it('measures a person\'s message by what became of it, under its source, once',
}
})
+it('names a stop the machine could not confirm, rather than unlisted', () => {
+ // lib/stopAgentService.ts: `agent_delete` is Stop, and STOP_UNCONFIRMED is its own refusal.
+ const emit = vi.fn()
+ productUsageRequest('agent_delete', emit, () => 0, 'phone')('STOP_UNCONFIRMED', undefined, false)
+ const names: string[] = emit.mock.calls.flat()
+ expect(names).toContain('delete_error_code_stop_unconfirmed')
+ expect(names).toContain('phone_delete_error_code_stop_unconfirmed')
+ expect(names.filter(name => name.endsWith('_unlisted'))).toEqual([])
+ for (const name of names.filter(name => name.includes('error_code_'))) expect(PRODUCT_USAGE_METRICS).toContain(name)
+})
+
it('counts every delete or restart refusal by its code, whatever its kind, so each family adds up to `_failed`', () => {
const emit = vi.fn()
productUsageRequest('agent_delete', emit, () => 0, 'phone')('DELETE_FAILED', undefined, false)
diff --git a/docs/product-measurement.md b/docs/product-measurement.md
index 7f876a265..81923d6e9 100644
--- a/docs/product-measurement.md
+++ b/docs/product-measurement.md
@@ -19,7 +19,7 @@ automatically proven improvement. Changes still need review, tests and a deliber
| Which features get tried and used again? | First measured installations and daily first/repeat feature reach | Locally deduplicated installation-days, not unique accounts. Reads the apps make on their own (history, history paging, Store list, model list; `PRODUCT_USAGE_AUTOMATIC_ACTIONS`) count reliability only. The Store and model lists get reach only from the request an app marks `userAction` when a person opens them (`<action>_user_*`, `PRODUCT_USAGE_USER_OPENED_ACTIONS`); history has none. |
| Where do app flows break? | Setup, Harness/tmux/clipboard steps, sign-in, workspace/remote connections, computer linking, viewer-pane opening and manual update checking/staging; a setup step whose tool was missing at a check (`setup_desktop_setup_<step>_missing`); the agents a new computer downloads beside setup (`setup_desktop_agent_download_<opencode\|codex\|claude>_started`, `_ok`, `_failed`, with under 1 min, 1–5 min and over 5 min) | Fixed started/ok/failed/cancelled/unknown counts and coarse duration buckets. Opening a viewer pane is not rendering its content; staging an update is not a successful relaunch. A setup step stays open from the first check until its tool is in place, so a tool that was missing and then installed is one ok step and one `_missing` mark; only a setup that ends failed fails its step. Earlier Desktop releases counted every check that found a tool missing as a failed step (on 2026-10-16 the Harness step read 72 failed of 221 while 0 setups failed): compare releases separately. `_missing` is any tool a check found absent or out of date (a Harness CLI older than this Desktop needs, on a computer already in use, counts too), not only new computers. A step left waiting (the review, a Linux Terminal handoff, manual mode, someone who walks away) now ends `unknown` at the 15-minute observation bound instead of `failed`, so expect `setup_*_unknown` to rise, mostly on Linux. `_missing` and the download counts are anonymous setup counts only. A download whose prerequisite (curl, Harness's Node) never arrived counts as started and failed; `ok` means the agent's program is in place, judged per engine. |
-| 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. |
+| 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. |
diff --git a/docs/research/2026-10-14-mobile-app-tracking/index.html b/docs/research/2026-10-14-mobile-app-tracking/index.html
index fa7534cbf..323ec370a 100644
--- a/docs/research/2026-10-14-mobile-app-tracking/index.html
+++ b/docs/research/2026-10-14-mobile-app-tracking/index.html
@@ -313,7 +313,7 @@
<tr><td>1 · Sign in</td><td><code>sign_in</code> + <code>sign_in_scan|google|apple|email</code></td><td>Google or Apple pressed, an email code entered, a QR code read</td><td>Signed in</td><td>The service refused, or the page could not open</td><td>Google/Apple page closed, or another attempt replaced it</td></tr>
<tr><td>2 · Your computer</td><td><code>computer_wait</code></td><td>"On your computer, go to" shows</td><td>A computer joins the account</td><td>—</td><td>Signed out ("Not you? Sign out"), see the note</td></tr>
<tr><td>3 · Ready</td><td><code>session_open</code></td><td>"… is ready." starts</td><td>A session opens (its own, or one picked meanwhile)</td><td>No session after 90 s</td><td>Signed out, see the note</td></tr>
- <tr><td>4 · Session</td><td><code>first_message</code></td><td>That session opens</td><td>First line sent from it (mic, composer or Return)</td><td>—</td><td>Left the session first</td></tr>
+ <tr><td>4 · Session</td><td><code>first_message</code></td><td>That session opens</td><td>First line sent in any session after it (mic, composer or Return), or a task typed into New Harness</td><td>—</td><td>Signed out first</td></tr>
<tr><td>5 · Notifications</td><td><code>notify_permission</code></td><td>The system prompt shows</td><td>Allow</td><td>—</td><td>Don't Allow (<code>unknown</code> when the OS gives no answer)</td></tr>
</table></div>
<div class="note">Each flow runs at most once per sign-in and app launch. These are counts of attempts, not of people: the daily totals have no identity to deduplicate them.
@@ -381,8 +381,8 @@
<div class="scroll"><table>
<tr><th>Counter</th><th>When</th></tr>
<tr><td>first_message_started</td><td>The hand-over opens the session with its one line by the mic</td></tr>
- <tr><td>first_message_ok</td><td>The first line sent from that page: a take from the mic, the composer, or a Return</td></tr>
- <tr><td>first_message_cancelled</td><td>Left the page before sending</td></tr>
+ <tr><td>first_message_ok</td><td>The first line sent after the hand-over in any session (a take from the mic, the composer, or a Return), or a task typed into New Harness. Before 2026-10-20 only a line sent from the session the hand-over opened counted: compare releases separately</td></tr>
+ <tr><td>first_message_cancelled</td><td>Signed out before sending. Leaving the session no longer ends it: a line sent in another one still answers it</td></tr>
</table></div>
<p>The old AA <code>app_first_message</code> timed from sign-in. This times from the session opening, so steps 2 and 3 are not counted twice. Sign-in to first message is the sum of the steps.</p>
<div class="note">The message itself, the agent, the computer and the starter task are never part of it.</div></figcaption></figure>
diff --git a/mobile/lib/measurement/onboarding_measurement.dart b/mobile/lib/measurement/onboarding_measurement.dart
index 63027271e..7bcdcca9d 100644
--- a/mobile/lib/measurement/onboarding_measurement.dart
+++ b/mobile/lib/measurement/onboarding_measurement.dart
@@ -12,8 +12,22 @@ enum OnboardingMark {
/// A sign-in went through on another button than the first one tried in this app run.
switched('switched', {ProductFlow.signIn}),
- /// The sign-in created the account: minutes old, its first Harness sign-in anywhere.
- newAccount('new_account', {ProductFlow.signIn}),
+ /// The sign-in created the account: minutes old, its first Harness sign-in anywhere. Under the steps
+ /// after it as well, each counted once in such a sign-in, so the new people's funnel reads apart
+ /// from everyone who signs in again ([newAccountOk] for how it ended).
+ newAccount('new_account', {
+ ProductFlow.signIn,
+ ProductFlow.computerWait,
+ ProductFlow.sessionOpen,
+ ProductFlow.firstMessage,
+ }),
+
+ /// The step ended `ok` in a sign-in that created the account ([newAccount]).
+ newAccountOk('new_account_ok', {
+ ProductFlow.computerWait,
+ ProductFlow.sessionOpen,
+ ProductFlow.firstMessage,
+ }),
/// The step started in an app run that did not sign in: reopened mid-step, not a new start.
resumed('resumed', {
@@ -83,6 +97,14 @@ class OnboardingMeasurement {
ProductFlow? _firstMethod;
bool _troubled = false;
+ /// This sign-in created the account ([accountCreated]).
+ bool _newAccount = false;
+
+ /// The steps of this sign-in that were counted, and those of them that ended `ok`: the profile can
+ /// be read after either, and a step never counted (it ended before sharing was known) marks nothing.
+ final _begun = <ProductFlow>{};
+ final _ok = <ProductFlow>{};
+
/// A sign-in attempt by [method] ended with [outcome]. Kept in RAM for this app run only: before
/// an account there is nobody's choice to ask, so it is counted — as [OnboardingMark.retried] or
/// [OnboardingMark.switched] — only with a sign-in that goes through ([signedIn]).
@@ -128,7 +150,12 @@ class OnboardingMeasurement {
_rememberWaiting(false);
}
_waiting.remove(flow);
- _running.remove(flow)?.call(outcome);
+ final running = _running.remove(flow);
+ running?.call(outcome);
+ if (running != null && outcome == ProductOutcome.ok) {
+ _ok.add(flow);
+ if (_newAccount) _markNew(flow, OnboardingMark.newAccountOk);
+ }
}
/// The account's profile, read after a sign-in in this run: one created by it ([newAccountWithin])
@@ -140,9 +167,24 @@ class OnboardingMeasurement {
if (age > newAccountWithin || age < -newAccountWithin) return;
if (!_marked.add((ProductFlow.signIn, OnboardingMark.newAccount))) return;
_marks.add((ProductFlow.signIn, OnboardingMark.newAccount));
+ _newAccount = true;
+ // Steps counted — or ended `ok` — before the profile was read are the new account's too.
+ for (final flow in _begun) {
+ _markNew(flow, OnboardingMark.newAccount);
+ }
+ for (final flow in _ok) {
+ _markNew(flow, OnboardingMark.newAccountOk);
+ }
_admit();
}
+ /// [what] of [flow], once per sign-in, for a step of a new account ([OnboardingMark.newAccount],
+ /// [OnboardingMark.newAccountOk]); [_admit] counts it.
+ void _markNew(ProductFlow flow, OnboardingMark what) {
+ if (!what.flows.contains(flow) || !_marked.add((flow, what))) return;
+ _marks.add((flow, what));
+ }
+
/// The account's computers have been read and it has at least one. A wait for a computer that a
/// launch before this one left open ([waitingKey]) ended there: counted once as
/// [OnboardingMark.joinedAfterLeaving]. Nothing once this sign-in has a wait of its own, open or
@@ -211,6 +253,9 @@ class OnboardingMeasurement {
_clearWaiting();
_seen.clear();
_marked.clear();
+ _begun.clear();
+ _ok.clear();
+ _newAccount = false;
_signedInThisRun = false;
_firstMethod = null;
_troubled = false;
@@ -228,7 +273,9 @@ class OnboardingMeasurement {
for (final MapEntry(key: flow, value: step) in [..._waiting.entries]) {
_waiting.remove(flow);
_running[flow] = _usage.begin(flow, elapsed: step.watch.elapsed);
+ _begun.add(flow);
if (step.resumed) _usage.mark(flow, OnboardingMark.resumed.wire);
+ if (_newAccount) _markNew(flow, OnboardingMark.newAccount);
}
for (final MapEntry(key: flow, value: took) in [..._signedIn.entries]) {
_signedIn.remove(flow);
diff --git a/mobile/lib/measurement/product_measurement.dart b/mobile/lib/measurement/product_measurement.dart
index 4a7ab015a..fa912e018 100644
--- a/mobile/lib/measurement/product_measurement.dart
+++ b/mobile/lib/measurement/product_measurement.dart
@@ -346,6 +346,39 @@ class ProductMeasurement extends ChangeNotifier {
}
}
+ /// Sends what is queued on either channel, at most [within]: the app is leaving the screen, where iOS
+ /// suspends it within seconds and may end it unannounced, and every count still in RAM goes with it.
+ /// On 2026-10-19 the phone's signed-out screen counted 17 sign-ins that went through and the
+ /// accounts counted 9; counts lost this way are the likely gap, since a sign-in is often followed
+ /// by leaving for the computer to install Harness, before the minute's report. An account whose
+ /// sharing choice is still unread is asked first, which also counts what waits on that answer
+ /// (`OnboardingMeasurement`).
+ Future<void> sendBeforeBackground({
+ Duration within = const Duration(seconds: 2),
+ }) async {
+ final watch = Stopwatch()..start();
+ for (var round = 0; round < 3; round++) {
+ final unread =
+ round == 0 &&
+ _account != null &&
+ _readChoice != null &&
+ _enabled == null;
+ final queued =
+ (sharing && _queued('ui')) || (_setupAllowed && _queued('setup'));
+ if (_disposed || !(unread || queued) || watch.elapsed >= within) return;
+ try {
+ await flush().timeout(within - watch.elapsed);
+ } on TimeoutException {
+ return;
+ }
+ // A report a flush leaves pending was refused or lost: it waits for the next timer, which
+ // keeps retries to one a minute, rather than going again at once.
+ if (_pending.isNotEmpty) {
+ return;
+ }
+ }
+ }
+
bool _queued(String channel) =>
_pending.containsKey(channel) ||
_days.keys.any((key) => key.startsWith('$channel:'));
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 8d6c62f5f..fca65f398 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -848,13 +848,10 @@ class _TerminalPageState extends State<TerminalPage>
?.session;
if (session?.voiceDeliver == _deliverVoice) session?.voiceDeliver = null;
if (session?.onLineSent == _onLineSent) session?.onLineSent = null;
- // Said once: leaving the session spends the onboarding's line too.
- if (_spendFirstSessionLine()) {
- widget.notifier.onboardingMeasurement.end(
- ProductFlow.firstMessage,
- ProductOutcome.cancelled,
- );
- }
+ // Said once: leaving the session spends the onboarding's line too. Not the onboarding's first
+ // message: a line sent in any other session still answers it ([_onLineSent]), and a sign-out
+ // ends it cancelled.
+ _spendFirstSessionLine();
_barMessageTimer?.cancel();
_barMessage.dispose();
_scrollback.dispose();
@@ -1144,8 +1141,11 @@ class _TerminalPageState extends State<TerminalPage>
),
),
);
- if (!_spendFirstSessionLine()) return;
+ // The onboarding's first message is the first line sent after the hand-over in ANY session, not
+ // only the one it opened: a person signing in again may go straight to a session of their own,
+ // which read as no first message (1 in 3 on 2026-10-19). Nothing once it has ended.
onboarding.end(ProductFlow.firstMessage, ProductOutcome.ok);
+ if (!_spendFirstSessionLine()) return;
setState(() {});
}
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 9d83438fc..2b58a57e0 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -6338,7 +6338,7 @@ class AppNotifier extends ChangeNotifier {
'gridModel': ?model?.id,
'gridName': ?model?.grid,
};
- return _create(
+ final created = _create(
machineId,
choices,
swarmId: swarmId,
@@ -6346,6 +6346,15 @@ class AppNotifier extends ChangeNotifier {
newDeskTab: newDeskTab,
attempt: creation,
);
+ if (task == null || task.isEmpty) return created;
+ // A task typed into New Harness is a message sent to a session too: the onboarding's first
+ // message, if it is still waiting for one (`terminal_page.dart` counts every other send).
+ return created.then((error) {
+ if (error == null) {
+ onboardingMeasurement.end(ProductFlow.firstMessage, ProductOutcome.ok);
+ }
+ return error;
+ });
}
/// Clones on their way or still to be confirmed, by machine and source agent — see [cloneAgent].
@@ -7407,15 +7416,32 @@ class AppNotifier extends ChangeNotifier {
/// Deletes an agent via `agent_delete`. Returns null on success, or an error message to show
/// inline in the caller's dialog.
+ ///
+ /// A refusal the machine says is worth asking again (`retryable`: `IDENTITY_UNAVAILABLE`, its
+ /// conversation file changing under the lookup) is asked again after [stopRetryDelays], before it
+ /// is shown. On 2026-10-19, 3 of the phone's 4 stops were refused as `other`, the kind this code
+ /// falls under. Any other refusal is shown at once — `STOP_UNCONFIRMED` asks for a look at the
+ /// harness first, not another stop.
Future<String?> deleteAgent(String machineId, String agentId) async {
final machine = machineStates[machineId];
if (machine == null) return 'Machine not found';
Map<String, dynamic> result;
- try {
- result = await _conn(machineId)
- .request('agent_delete', payload: {'agentId': agentId});
- } catch (error) {
- return 'Delete failed: $error';
+ for (var attempt = 0; ; attempt++) {
+ try {
+ result = await _conn(machineId)
+ .request('agent_delete', payload: {'agentId': agentId});
+ } catch (error) {
+ return 'Delete failed: $error';
+ }
+ if (result['error'] is! String ||
+ result['retryable'] != true ||
+ attempt >= stopRetryDelays.length) {
+ break;
+ }
+ await Future<void>.delayed(stopRetryDelays[attempt]);
+ if (_disposed || machineStates[machineId] == null) {
+ return 'Machine not found';
+ }
}
final error = result['error'];
if (error is String) return 'Delete failed: $error';
@@ -7427,6 +7453,14 @@ class AppNotifier extends ChangeNotifier {
return null;
}
+ /// How long [deleteAgent] waits before asking again after a refusal the machine marks `retryable`,
+ /// one entry per retry.
+ @visibleForTesting
+ List<Duration> stopRetryDelays = const [
+ Duration(seconds: 1),
+ Duration(seconds: 2),
+ ];
+
/// Deletes on their way, by machine and agent — what a second press joins rather than reviewing
/// the same harness twice.
final Map<(String, String), Future<String?>> _agentPurges = {};
@@ -10543,6 +10577,7 @@ class AppNotifier extends ChangeNotifier {
}
// The agents this run learned between lists, for the next launch — see [_keepMachineCache].
_keepMachineCache();
+ _sendMeasurementBeforeBackground();
}
/// When the app last went into the background ([handleAppPaused]); null while it is in front.
@@ -10600,8 +10635,25 @@ class AppNotifier extends ChangeNotifier {
/// The app lost the foreground for a moment — the app switcher, a system sheet. Nothing stops;
/// only the machine cache is written ([_keepMachineCache]), because the switcher is where an app
- /// is closed, and closing it there need not pass through [handleAppPaused] first.
- void handleAppInactive() => _keepMachineCache();
+ /// is closed, and closing it there need not pass through [handleAppPaused] first. The queued
+ /// counts go now too, for the same reason ([_sendMeasurementBeforeBackground]).
+ void handleAppInactive() {
+ _keepMachineCache();
+ _sendMeasurementBeforeBackground();
+ }
+
+ /// Whether leaving the screen sends the queued product counts ([ProductMeasurement
+ /// .sendBeforeBackground]). Off under test, where a report would go to the network; a test that
+ /// passes its own measurement turns it on.
+ @visibleForTesting
+ bool sendMeasurementBeforeBackground = !kUnderTest;
+
+ /// Counts kept in RAM are lost when iOS ends a suspended app; the minute's report may never come.
+ /// Never awaited: leaving the screen waits for nothing.
+ void _sendMeasurementBeforeBackground() {
+ if (!sendMeasurementBeforeBackground) return;
+ unawaited(productMeasurement.sendBeforeBackground());
+ }
/// How often a phone with no machine connected reads the machine list again. Every push
/// (`machines_changed`, `device_keys_changed`) reaches the phone over a machine's socket; with none
diff --git a/mobile/test/app_state_agent_rpcs_test.dart b/mobile/test/app_state_agent_rpcs_test.dart
index 693f973b9..7adc5ac7b 100644
--- a/mobile/test/app_state_agent_rpcs_test.dart
+++ b/mobile/test/app_state_agent_rpcs_test.dart
@@ -1078,6 +1078,59 @@ void main() {
expect(rig.app.stateOf('m')!.agents.single.id, 'a');
});
+ test('a stop the machine says to ask again is asked again, then goes', () async {
+ // IDENTITY_UNAVAILABLE: the conversation file changed under the machine's lookup.
+ final rig = await signedInWith({
+ 'm': ['a', 'b'],
+ });
+ addTearDown(rig.app.dispose);
+ rig.app.stopRetryDelays = const [Duration.zero, Duration.zero];
+ var asked = 0;
+ rig.conn('m').answers['agent_delete'] = (_) => ++asked == 1
+ ? {'error': 'IDENTITY_UNAVAILABLE', 'held': true, 'retryable': true}
+ : {'deleted': true};
+
+ expect(await rig.app.deleteAgent('m', 'a'), isNull);
+
+ expect(rig.conn('m').payloadsOf('agent_delete'), hasLength(2));
+ expect(rig.app.stateOf('m')!.agents.map((a) => a.id), ['b']);
+ });
+
+ test('asks again at most twice, then says why', () async {
+ final rig = await signedInWith({
+ 'm': ['a'],
+ });
+ addTearDown(rig.app.dispose);
+ rig.app.stopRetryDelays = const [Duration.zero, Duration.zero];
+ rig.conn('m').answers['agent_delete'] = (_) =>
+ {'error': 'IDENTITY_UNAVAILABLE', 'retryable': true};
+
+ expect(
+ await rig.app.deleteAgent('m', 'a'),
+ 'Delete failed: IDENTITY_UNAVAILABLE',
+ );
+
+ expect(rig.conn('m').payloadsOf('agent_delete'), hasLength(3));
+ expect(rig.app.stateOf('m')!.agents.single.id, 'a');
+ });
+
+ test('a stop it could not confirm is not asked again', () async {
+ // STOP_UNCONFIRMED asks for a look at the harness first, not another stop.
+ final rig = await signedInWith({
+ 'm': ['a'],
+ });
+ addTearDown(rig.app.dispose);
+ rig.app.stopRetryDelays = const [Duration.zero, Duration.zero];
+ rig.conn('m').answers['agent_delete'] = (_) => {'error': 'STOP_UNCONFIRMED'};
+
+ expect(
+ await rig.app.deleteAgent('m', 'a'),
+ 'Delete failed: STOP_UNCONFIRMED',
+ );
+
+ expect(rig.conn('m').payloadsOf('agent_delete'), hasLength(1));
+ });
+
test('a rename is trimmed, sent, and shown', () async {
final rig = await signedInWith({
'm': ['a'],
diff --git a/mobile/test/app_state_flow_measurement_test.dart b/mobile/test/app_state_flow_measurement_test.dart
index 16a6f3238..a37150501 100644
--- a/mobile/test/app_state_flow_measurement_test.dart
+++ b/mobile/test/app_state_flow_measurement_test.dart
@@ -53,6 +53,52 @@ void main() {
return total;
}
+ group('leaving the screen', () {
+ // iOS suspends an app within seconds and may end it unannounced; counts still in RAM go with
+ // it. The once-a-minute report is not waited for.
+
+ /// A sharing phone that counted a dial and has not reported it yet; [send] as given.
+ Future<(ViewerRig, int)> dialled({required bool send}) async {
+ final rig = await sharing({'m': []});
+ final before = rig.api.usageReports.length;
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connecting);
+ rig.app.connectionStatusForTest('m', ConnectionStatus.connected);
+ rig.app.sendMeasurementBeforeBackground = send;
+ return (rig, before);
+ }
+
+ Iterable<Object?> sentSince(ViewerRig rig, int before) => rig
+ .api
+ .usageReports
+ .skip(before)
+ .expand((report) => (report['counters'] as Map).keys);
+
+ test(
+ 'sends the queued counts when the app goes to the background',
+ () async {
+ final (rig, before) = await dialled(send: true);
+ rig.app.handleAppPaused();
+ await pumpEventQueue();
+ expect(sentSince(rig, before), contains('ui_phone_remote_connect_ok'));
+ },
+ );
+
+ test('and when it loses the foreground (the app switcher)', () async {
+ final (rig, before) = await dialled(send: true);
+ rig.app.handleAppInactive();
+ await pumpEventQueue();
+ expect(sentSince(rig, before), contains('ui_phone_remote_connect_ok'));
+ });
+
+ test('sends nothing when that is switched off', () async {
+ final (rig, before) = await dialled(send: false);
+ rig.app.handleAppPaused();
+ rig.app.handleAppInactive();
+ await pumpEventQueue();
+ expect(sentSince(rig, before), isEmpty);
+ });
+ });
+
group('dials', () {
test('a socket coming back by itself is the app\'s own', () async {
final rig = await sharing({'m': []});
diff --git a/mobile/test/first_message_any_session_test.dart b/mobile/test/first_message_any_session_test.dart
new file mode 100644
index 000000000..ae34882ea
--- /dev/null
+++ b/mobile/test/first_message_any_session_test.dart
@@ -0,0 +1,229 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/measurement/product_measurement.dart';
+import 'package:harness_mobile/phone/terminal_page.dart';
+import 'package:harness_mobile/phone/voice_input_controller.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/terminal/terminal_session.dart';
+
+import 'viewer_app_fixture.dart';
+import 'voice_fakes.dart';
+
+/// Records the flows begun and how each ended, for an account that shares.
+class _Recorder extends ProductMeasurement {
+ _Recorder()
+ : super(surface: 'phone', automatic: false, sendSetup: (_) async => {});
+
+ final ended = <String>[];
+
+ @override
+ bool get sharing => true;
+
+ @override
+ bool get declined => false;
+
+ @override
+ void Function(ProductOutcome) begin(
+ ProductFlow flow, {
+ Duration elapsed = Duration.zero,
+ }) =>
+ (outcome) => ended.add('${flow.name}:${outcome.name}');
+
+ /// How the onboarding's first message ended, if it has.
+ List<String> get firstMessage =>
+ ended.where((e) => e.startsWith('firstMessage:')).toList();
+}
+
+/// The onboarding's first message is the first line sent after the hand-over in ANY session, or a
+/// task typed into New Harness: on 2026-10-19 only the session the hand-over opened counted, and a
+/// person signing in again who went to a session of their own read as no first message.
+void main() {
+ group('a line sent', () {
+ late _Recorder usage;
+ late AppNotifier notifier;
+ late TerminalSession session;
+ late VoiceInputController voice;
+ late ValueNotifier<String> language;
+
+ setUp(() {
+ usage = _Recorder();
+ notifier = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ productMeasurement: usage,
+ );
+ session = TerminalSession(
+ machineId: 'm',
+ agentId: 'a',
+ agentName: 'Agent',
+ engineId: 'claude',
+ send: (type, payload) async => true,
+ sendBinary: (_) async => true,
+ );
+ session.status = TerminalSessionStatus.controlling;
+ session.streamId = 's';
+ notifier.adoptSessionForTest(session);
+ language = ValueNotifier('en');
+ voice = VoiceInputController(
+ transcriber: FakeTranscriber().call,
+ recorder: FakeVoiceRecorder(),
+ language: language,
+ );
+ });
+
+ tearDown(() {
+ voice.dispose();
+ language.dispose();
+ notifier.dispose();
+ });
+
+ Future<void> pumpSession(WidgetTester tester) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: TerminalPage(
+ notifier: notifier,
+ machineId: 'm',
+ agentId: 'a',
+ voice: voice,
+ ),
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 100));
+ }
+
+ testWidgets('in another session than the hand-over opened answers it', (
+ tester,
+ ) async {
+ // The hand-over opened `b`; the person went to `a` and wrote there.
+ notifier.firstSessionLine = (machineId: 'm', agentId: 'b', text: 'Say');
+ notifier.onboardingMeasurement.start(ProductFlow.firstMessage);
+ await pumpSession(tester);
+
+ expect(await session.sendComposerText('fix the build'), isTrue);
+ await tester.pump();
+
+ expect(usage.firstMessage, ['firstMessage:ok']);
+ // `b`'s line by the mic is `b`'s page's to spend.
+ expect(notifier.firstSessionLine?.agentId, 'b');
+ // Once: a second line answers nothing more.
+ await session.sendComposerText('and run it');
+ await tester.pump();
+ expect(usage.firstMessage, ['firstMessage:ok']);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('in the session the hand-over opened answers it, as before', (
+ tester,
+ ) async {
+ notifier.firstSessionLine = (machineId: 'm', agentId: 'a', text: 'Say');
+ notifier.onboardingMeasurement.start(ProductFlow.firstMessage);
+ await pumpSession(tester);
+
+ await session.sendComposerText('fix the build');
+ await tester.pump();
+
+ expect(usage.firstMessage, ['firstMessage:ok']);
+ expect(notifier.firstSessionLine, isNull);
+ await tester.pumpWidget(const SizedBox());
+ });
+
+ testWidgets('leaving the session the hand-over opened does not end it', (
+ tester,
+ ) async {
+ notifier.firstSessionLine = (machineId: 'm', agentId: 'a', text: 'Say');
+ notifier.onboardingMeasurement.start(ProductFlow.firstMessage);
+ await pumpSession(tester);
+
+ await tester.pumpWidget(const SizedBox());
+
+ expect(usage.firstMessage, isEmpty);
+ // The page's line by the mic is still spent on the way out.
+ expect(notifier.firstSessionLine, isNull);
+ // A sign-out is what ends it unanswered.
+ notifier.onboardingMeasurement.reset();
+ expect(usage.firstMessage, ['firstMessage:cancelled']);
+ });
+
+ testWidgets('before the hand-over answers nothing', (tester) async {
+ await pumpSession(tester);
+
+ await session.sendComposerText('fix the build');
+ await tester.pump();
+
+ expect(usage.firstMessage, isEmpty);
+ await tester.pumpWidget(const SizedBox());
+ });
+ });
+
+ group('a task typed into New Harness', () {
+ Map<String, dynamic> created(Map<String, dynamic> payload, String id) => {
+ 'creationId': payload['creationId'],
+ 'state': 'created',
+ 'agent': agentJson(id),
+ };
+
+ /// [pending] finishing, with the terminal it opens measured the way its panel would measure it.
+ Future<T> measured<T>(ViewerRig rig, Future<T> pending) async {
+ await settle();
+ for (final pane in rig.app.panesFor('m')) {
+ pane.session?.reportViewport(80, 24);
+ }
+ return pending;
+ }
+
+ Future<(ViewerRig, _Recorder)> waiting() async {
+ final usage = _Recorder();
+ final rig = await signedInWith({'m': []}, productMeasurement: usage);
+ addTearDown(rig.app.dispose);
+ rig.app.onboardingMeasurement.start(ProductFlow.firstMessage);
+ return (rig, usage);
+ }
+
+ test('answers the first message once the harness is made', () async {
+ final (rig, usage) = await waiting();
+ rig.conn('m').answers['agent_create'] = (p) => created(p, 'new');
+
+ final error = await measured(
+ rig,
+ rig.app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '/work',
+ prompt: 'fix the build',
+ ),
+ );
+
+ expect(error, isNull);
+ expect(usage.firstMessage, ['firstMessage:ok']);
+ });
+
+ test('without a task, or refused, answers nothing', () async {
+ final (rig, usage) = await waiting();
+ rig.conn('m').answers['agent_create'] = (p) => created(p, 'new');
+ await measured(
+ rig,
+ rig.app.createAgent('m', engine: 'claude', folder: '/work'),
+ );
+ await measured(
+ rig,
+ rig.app.createAgent('m', engine: 'claude', folder: '/a', prompt: ' '),
+ );
+ rig.conn('m').answers['agent_create'] = (_) => {'error': 'INVALID_CWD'};
+ final refused = await measured(
+ rig,
+ rig.app.createAgent(
+ 'm',
+ engine: 'claude',
+ folder: '/missing',
+ prompt: 'fix the build',
+ ),
+ );
+
+ expect(refused, isNotNull);
+ expect(usage.firstMessage, isEmpty);
+ });
+ });
+}
diff --git a/mobile/test/onboarding_measurement_test.dart b/mobile/test/onboarding_measurement_test.dart
index 8918cd907..347aa5b29 100644
--- a/mobile/test/onboarding_measurement_test.dart
+++ b/mobile/test/onboarding_measurement_test.dart
@@ -476,6 +476,102 @@ void main() {
await usage.flush();
expect(counters('ui_phone_sign_in_new_account'), isEmpty);
});
+
+ /// The marks under the steps after the sign-in, by name.
+ Map<String, dynamic> newAccountSteps() => {
+ for (final MapEntry(:key, :value) in counters().entries)
+ if (key.contains('new_account') && !key.startsWith('ui_phone_sign_in_'))
+ key: value,
+ };
+
+ test('marks each step of the new account, and how it ended', () async {
+ await signIn();
+ signedInHere();
+ onboarding.accountCreated(
+ now.subtract(const Duration(minutes: 1)),
+ now: now,
+ );
+ onboarding.start(ProductFlow.computerWait);
+ onboarding.end(ProductFlow.computerWait, ProductOutcome.ok);
+ onboarding.start(ProductFlow.sessionOpen);
+ onboarding.end(ProductFlow.sessionOpen, ProductOutcome.ok);
+ onboarding.start(ProductFlow.firstMessage);
+ onboarding.end(ProductFlow.firstMessage, ProductOutcome.cancelled);
+ await onboarding.askNotifications(() async => true);
+ // A step asked for again in the same sign-in is the same step.
+ onboarding.start(ProductFlow.computerWait);
+ await usage.flush();
+ expect(newAccountSteps(), {
+ 'ui_phone_computer_wait_new_account': 1,
+ 'ui_phone_computer_wait_new_account_ok': 1,
+ 'ui_phone_session_open_new_account': 1,
+ 'ui_phone_session_open_new_account_ok': 1,
+ 'ui_phone_first_message_new_account': 1,
+ });
+ });
+
+ test('marks the steps counted before the profile was read', () async {
+ await signIn();
+ signedInHere();
+ onboarding.start(ProductFlow.computerWait);
+ onboarding.end(ProductFlow.computerWait, ProductOutcome.ok);
+ onboarding.start(ProductFlow.sessionOpen);
+ onboarding.accountCreated(
+ now.subtract(const Duration(minutes: 1)),
+ now: now,
+ );
+ onboarding.end(ProductFlow.sessionOpen, ProductOutcome.failed);
+ await usage.flush();
+ expect(newAccountSteps(), {
+ 'ui_phone_computer_wait_new_account': 1,
+ 'ui_phone_computer_wait_new_account_ok': 1,
+ 'ui_phone_session_open_new_account': 1,
+ });
+ });
+
+ test('marks nothing for an account signing in again', () async {
+ await signIn();
+ signedInHere();
+ onboarding.accountCreated(
+ now.subtract(const Duration(days: 3)),
+ now: now,
+ );
+ onboarding.start(ProductFlow.sessionOpen);
+ onboarding.end(ProductFlow.sessionOpen, ProductOutcome.ok);
+ await usage.flush();
+ expect(counters('ui_phone_session_open_ok'), hasLength(1));
+ expect(newAccountSteps(), isEmpty);
+ });
+
+ test('marks nothing for a step that was never counted', () async {
+ // Sharing not known yet: a step that ends before then is not counted, nor marked.
+ signedInHere();
+ onboarding.accountCreated(
+ now.subtract(const Duration(minutes: 1)),
+ now: now,
+ );
+ onboarding.start(ProductFlow.computerWait);
+ onboarding.end(ProductFlow.computerWait, ProductOutcome.ok);
+ await signIn();
+ await usage.flush();
+ expect(counters('ui_phone_computer_wait'), isEmpty);
+ expect(counters('ui_phone_sign_in_new_account'), hasLength(1));
+ });
+
+ test('a sign-out starts the next sign-in afresh', () async {
+ await signIn();
+ signedInHere();
+ onboarding.accountCreated(
+ now.subtract(const Duration(minutes: 1)),
+ now: now,
+ );
+ onboarding.reset();
+ signedInHere();
+ onboarding.start(ProductFlow.sessionOpen);
+ onboarding.end(ProductFlow.sessionOpen, ProductOutcome.ok);
+ await usage.flush();
+ expect(newAccountSteps(), isEmpty);
+ });
});
test('every mark is in the backend vocabulary under each step it names', () {
diff --git a/mobile/test/product_measurement_test.dart b/mobile/test/product_measurement_test.dart
index 1c1051341..46478b08c 100644
--- a/mobile/test/product_measurement_test.dart
+++ b/mobile/test/product_measurement_test.dart
@@ -553,6 +553,118 @@ void main() {
);
});
});
+
+ group('leaving the screen', () {
+ // iOS suspends an app within seconds of leaving the screen and may end it unannounced: a count
+ // still in RAM then is gone. On 2026-10-19 the signed-out screen counted 17 sign-ins and the
+ // accounts 9.
+ test('sends what both channels queued, now', () async {
+ // Signed out: a sign-in's count waits on the setup channel.
+ await usage.setSignedOutSharing(true);
+ usage.begin(ProductFlow.signIn)(ProductOutcome.ok);
+ await usage.sendBeforeBackground();
+ expect(
+ setup.single['counters'],
+ containsPair('setup_desktop_sign_in_ok', 1),
+ );
+ // Signed in: the account's counts.
+ await account();
+ reports.clear();
+ usage.begin(ProductFlow.remoteConnect)(ProductOutcome.ok);
+ usage.begin(ProductFlow.appStart)(ProductOutcome.ok);
+ await usage.sendBeforeBackground();
+ expect(
+ reports.expand((r) => (r['counters'] as Map).keys),
+ containsAll([
+ 'ui_desktop_remote_connect_ok',
+ 'ui_desktop_app_start_ok',
+ ]),
+ );
+ });
+
+ test(
+ 'asks an account whose choice is unread, so what waits on it is counted',
+ () async {
+ final waited = <String>[];
+ usage.addListener(() {
+ if (usage.sharing && waited.isEmpty) {
+ waited.add('admitted');
+ usage.begin(ProductFlow.appStart)(ProductOutcome.ok);
+ }
+ });
+ usage.account(
+ 'PRIVATE_ACCOUNT',
+ choice: () async => choice,
+ send: (r) async {
+ reports.add(jsonDecode(jsonEncode(r)));
+ return {'accepted': true};
+ },
+ );
+ expect(usage.sharing, isFalse);
+ await usage.sendBeforeBackground();
+ expect(waited, ['admitted']);
+ expect(
+ reports.expand((r) => (r['counters'] as Map).keys),
+ contains('ui_desktop_app_start_ok'),
+ );
+ },
+ );
+
+ test('sends nothing when nothing is queued', () async {
+ await account();
+ reports.clear();
+ var reads = 0;
+ usage.account(
+ 'PRIVATE_OTHER',
+ choice: () async {
+ reads++;
+ return choice;
+ },
+ send: (r) async {
+ reports.add(r);
+ return {'accepted': true};
+ },
+ );
+ await usage.flush();
+ reads = 0;
+ await usage.sendBeforeBackground();
+ expect(reports, isEmpty);
+ expect(reads, 0);
+ });
+
+ test(
+ 'a refused report waits for the next minute, not another try at once',
+ () async {
+ await account();
+ fail = true;
+ reports.clear();
+ usage.begin(ProductFlow.remoteConnect)(ProductOutcome.ok);
+ await usage.sendBeforeBackground();
+ expect(reports, hasLength(1));
+ fail = false;
+ await usage.flush();
+ expect(reports, hasLength(2));
+ expect(reports.last['id'], reports.first['id']);
+ },
+ );
+
+ test('a slow report stops the wait at its bound', () async {
+ final answer = Completer<Map<String, dynamic>>();
+ usage.account(
+ 'PRIVATE_ACCOUNT',
+ choice: () async => choice,
+ send: (r) => answer.future,
+ );
+ await Future<void>.delayed(Duration.zero);
+ usage.begin(ProductFlow.remoteConnect)(ProductOutcome.ok);
+ final watch = Stopwatch()..start();
+ await usage.sendBeforeBackground(
+ within: const Duration(milliseconds: 50),
+ );
+ expect(watch.elapsed, lessThan(const Duration(seconds: 2)));
+ answer.complete({'accepted': true});
+ });
+ });
}
/// A kept choice that cannot be read: an opt-out must never come back on because of it.