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(desktop): track the Add Phone card and its entry points

tonye3d91227adec
diff --git a/backend/src/analytics/dailyProductReview.test.ts b/backend/src/analytics/dailyProductReview.test.ts
index 1f2e1c5e9..567a9916a 100644
--- a/backend/src/analytics/dailyProductReview.test.ts
+++ b/backend/src/analytics/dailyProductReview.test.ts
@@ -136,3 +136,16 @@ it("splits the phone onboarding's long waits past a minute and shows what happen
expect(r.flows.find(f => f.channel === 'ui' && f.surface === 'phone' && f.flow === 'session_open')).not.toHaveProperty('over1mBuckets')
expect(r.flows.find(f => f.channel === 'ui' && f.surface === 'desktop' && f.flow === 'computer_wait')).not.toHaveProperty('marks')
})
+
+it('shows every way into Add Phone beside the Desktop\'s Add Phone card', () => {
+ const r = dailyProductReview([
+ row('2026-10-12', 'ui_desktop_phone_offer_started', 3), row('2026-10-12', 'ui_desktop_phone_offer_ok', 1),
+ row('2026-10-12', 'ui_desktop_phone_offer_cancelled', 1),
+ row('2026-10-12', 'ui_desktop_add_phone_offer', 1), row('2026-10-12', 'ui_desktop_add_phone_titlebar', 4),
+ ], new Date('2026-10-13'))
+ // Started minus its outcomes: an app closed with the card still up.
+ expect(r.flows.find(f => f.channel === 'ui' && f.surface === 'desktop' && f.flow === 'phone_offer')).toMatchObject({
+ started: 3, outcomes: { ok: 1, cancelled: 1, unknown: 0 }, unmatchedStarts: 1,
+ addPhoneOpenings: { offer: 1, titlebar: 4, menu: 0, account: 0, machines: 0, command: 0 } })
+ expect(r.flows.find(f => f.channel === 'ui' && f.surface === 'phone' && f.flow === 'phone_offer')).not.toHaveProperty('addPhoneOpenings')
+})
diff --git a/backend/src/analytics/dailyProductReview.ts b/backend/src/analytics/dailyProductReview.ts
index 4074baee1..546597bfa 100644
--- a/backend/src/analytics/dailyProductReview.ts
+++ b/backend/src/analytics/dailyProductReview.ts
@@ -1,4 +1,4 @@
-import { LAUNCH_ERROR_CODES, LAUNCH_ERROR_FAMILIES, PRODUCT_FEEDBACK, PRODUCT_FEEDBACK_REASONS, PRODUCT_FEEDBACK_OUTCOMES, PRODUCT_USAGE_ACTIONS, PRODUCT_USAGE_AUTOMATIC_ACTIONS, PRODUCT_USAGE_FLOWS, PRODUCT_USAGE_LONG_FLOWS, PRODUCT_USAGE_LONG_MEASURES, PRODUCT_USAGE_ONBOARDING_MARKS, PRODUCT_USAGE_SETUP_FLOWS, PRODUCT_USAGE_SURFACES, PRODUCT_USAGE_UI_SURFACES, PRODUCT_USAGE_USER_OPENED_ACTIONS } from '../types/productUsage.js'
+import { LAUNCH_ERROR_CODES, LAUNCH_ERROR_FAMILIES, PRODUCT_FEEDBACK, PRODUCT_FEEDBACK_REASONS, PRODUCT_FEEDBACK_OUTCOMES, PRODUCT_USAGE_ACTIONS, PRODUCT_USAGE_ADD_PHONE_OPENINGS, PRODUCT_USAGE_AUTOMATIC_ACTIONS, PRODUCT_USAGE_FLOWS, PRODUCT_USAGE_LONG_FLOWS, PRODUCT_USAGE_LONG_MEASURES, PRODUCT_USAGE_ONBOARDING_MARKS, PRODUCT_USAGE_SETUP_FLOWS, PRODUCT_USAGE_SURFACES, PRODUCT_USAGE_UI_SURFACES, PRODUCT_USAGE_USER_OPENED_ACTIONS } from '../types/productUsage.js'
import { DAILY_PRODUCT_METRICS } from './dailyProductUsage.js'
type Row = { dayUtc: Date; metric: string; value: number }
@@ -114,6 +114,9 @@ export function dailyProductReview(rows: Row[], now: Date) {
...(channel === 'ui' && surface === 'phone' && (PRODUCT_USAGE_LONG_FLOWS as readonly string[]).includes(flow)
? { over1mBuckets: Object.fromEntries(PRODUCT_USAGE_LONG_MEASURES.map(bucket => [bucket, c[`${prefix}${bucket}`] ?? (started ? 0 : null)])) } : {}),
...(channel === 'ui' ? marksOf(prefix) : {}),
+ // Beside the Desktop's Add Phone card, every way Add Phone was opened: the card's own button is `offer`.
+ ...(channel === 'ui' && surface === 'desktop' && flow === 'phone_offer'
+ ? { addPhoneOpenings: Object.fromEntries(PRODUCT_USAGE_ADD_PHONE_OPENINGS.map(opening => [opening, c[`ui_desktop_add_phone_${opening}`] ?? 0])) } : {}),
interpretation: channel === 'setup'
? 'Optional signed-out app-session counts, untrusted and self-selected. No cross-step linkage, unique people or signup conversion. Web pre-sign-in is not collected.'
: 'Observed app operations, possibly automatic. Missing outcomes include closed apps, offline reports and choice changes; absence is not failure. Viewer opening is not page rendering; update staging is not successful relaunch.',
diff --git a/backend/src/analytics/productHealth.test.ts b/backend/src/analytics/productHealth.test.ts
index d8d217832..c5305529a 100644
--- a/backend/src/analytics/productHealth.test.ts
+++ b/backend/src/analytics/productHealth.test.ts
@@ -1,6 +1,7 @@
import { readFileSync } from 'node:fs'
import { expect, it } from 'vitest'
import { cleanUsageContext, HEALTH_MEASURES, HEALTH_FLOWS } from '../types/productHealthContract.js'
+import { PRODUCT_USAGE_ADD_PHONE_OPENINGS, PRODUCT_USAGE_DESKTOP_FLOWS } from '../types/productUsage.js'
import { dailyProductHealth, healthBreakdowns } from './productHealth.js'
const context = { surface: 'desktop', release: '1.2.73', platform: 'macos', channel: 'production' } as const
@@ -11,6 +12,12 @@ it('keeps the CLI contract identical and every Desktop enum in the server vocabu
const flows = readFileSync('../desktop/lib/measurement/product_measurement.dart', 'utf8')
for (const flow of HEALTH_FLOWS) expect(flows).toContain(`'${flow}'`)
})
+it('names the Desktop\'s Add Phone card and every way into Add Phone as the Desktop does', () => {
+ const dart = readFileSync('../desktop/lib/measurement/product_measurement.dart', 'utf8')
+ for (const flow of PRODUCT_USAGE_DESKTOP_FLOWS) expect(dart).toContain(`'${flow}'`)
+ const openings = dart.split('enum AddPhoneOpening')[1].split('const AddPhoneOpening(')[0]
+ expect([...openings.matchAll(/\w+\('([a-z_]+)'\)/g)].map(match => match[1])).toEqual([...PRODUCT_USAGE_ADD_PHONE_OPENINGS])
+})
it('shows hn\'s session milestones beside the Desktop\'s', () => {
const row = (metric: string, value: number) => ({ dayUtc: new Date('2026-10-01'), metric, value })
const data = dailyProductHealth([row('health_tui_funnel_first_work', 3), row('health_tui_first_work_under_1m', 2),
diff --git a/backend/src/routes/productUsage.test.ts b/backend/src/routes/productUsage.test.ts
index 5efa7145b..bd29c42cc 100644
--- a/backend/src/routes/productUsage.test.ts
+++ b/backend/src/routes/productUsage.test.ts
@@ -152,6 +152,18 @@ it('takes how the phone opened Find or Computers, and the phone\'s own requests,
}
})
+it('takes the Desktop\'s Add Phone card and each way into Add Phone, and no other name like them', async () => {
+ const 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_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)
+ for (const name of ['ui_desktop_add_phone_welcome', 'ui_desktop_add_phone_qr', 'ui_phone_add_phone_offer', 'ui_web_add_phone_command']) {
+ expect((await submit({ ...good, context, counters: { [name]: 1 } })).statusCode).toBe(400)
+ }
+})
+
it('rejects extra context, custom versions and device fingerprints without echoing them', async () => {
const context = { surface: 'desktop', release: '1.2.73', platform: 'macos', channel: 'production' }
for (const c of [{ ...context, path: 'PRIVATE_CANARY' }, { ...context, release: 'PRIVATE_CANARY' },
diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.ts
index f1ec00673..6ecd57ca4 100644
--- a/backend/src/types/productUsage.ts
+++ b/backend/src/types/productUsage.ts
@@ -52,9 +52,19 @@ export const PRODUCT_USAGE_PHONE_SCREENS = ['find', 'computers'] as const
export const PRODUCT_USAGE_SCREEN_OPENINGS = ['swipe', 'button'] as const
export const PRODUCT_USAGE_PHONE_SCREEN_METRICS = PRODUCT_USAGE_PHONE_SCREENS.flatMap(screen =>
PRODUCT_USAGE_SCREEN_OPENINGS.map(opening => `ui_phone_screen_${screen}_${opening}` as const))
+/** 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
+/** 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. */
+export const PRODUCT_USAGE_ADD_PHONE_OPENINGS = ['offer', 'titlebar', 'menu', 'account', 'machines', 'command'] as const
+export const PRODUCT_USAGE_ADD_PHONE_METRICS = PRODUCT_USAGE_ADD_PHONE_OPENINGS.map(opening => `ui_desktop_add_phone_${opening}` as const)
export const PRODUCT_USAGE_FLOWS = [...PRODUCT_USAGE_SETUP_FLOWS,
'workspace_connect', 'computer_link', 'remote_connect', 'viewer_open', 'update_check', 'update_stage',
- ...HEALTH_FLOWS, ...PRODUCT_USAGE_ONBOARDING_FLOWS] as const
+ ...HEALTH_FLOWS, ...PRODUCT_USAGE_ONBOARDING_FLOWS, ...PRODUCT_USAGE_DESKTOP_FLOWS] as const
export const PRODUCT_USAGE_FLOW_MEASURES = ['started', 'ok', 'failed', 'cancelled', 'unknown',
'under_1s', '1s_to_10s', '10s_to_1m', 'over_1m'] as const
export const PRODUCT_USAGE_UI_METRICS = PRODUCT_USAGE_UI_SURFACES.flatMap(surface =>
@@ -150,6 +160,7 @@ export const PRODUCT_USAGE_METRICS = [
...PRODUCT_USAGE_UI_METRICS,
...PRODUCT_USAGE_ONBOARDING_METRICS,
...PRODUCT_USAGE_PHONE_SCREEN_METRICS,
+ ...PRODUCT_USAGE_ADD_PHONE_METRICS,
// Written by the backend itself: a report that named counters this backend does not know yet, which
// it kept without them (routes/productUsage.ts). One per report, never the names.
'health_cli_report_unknown_metric', 'health_desktop_report_unknown_metric', 'health_phone_report_unknown_metric',
diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.ts
index ead6f559a..cbe18fd59 100644
--- a/cli/src/hookServer.spec.ts
+++ b/cli/src/hookServer.spec.ts
@@ -408,7 +408,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('2')
+ expect(kept.headers.get('x-harness-usage-vocabulary')).toBe('3')
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')
@@ -421,7 +421,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('2')
+ expect(response.headers.get('x-harness-usage-vocabulary')).toBe('3')
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.ts
index 9d57d4388..168f74ea5 100644
--- a/cli/src/lib/appProductUsageReport.spec.ts
+++ b/cli/src/lib/appProductUsageReport.spec.ts
@@ -2,7 +2,7 @@ import { readFileSync } from 'node:fs'
import { expect, it } from 'vitest'
import { appProductUsageReport, APP_USAGE_VOCABULARY, isAppProductUsageReport } from './appProductUsageReport.js'
import { HEALTH_MEASURES, CLI_REPORT_FAILURES } from './productHealthContract.js'
-import { PRODUCT_USAGE_UI_METRICS } from './productUsageContract.js'
+import { PRODUCT_USAGE_ADD_PHONE_METRICS, PRODUCT_USAGE_UI_METRICS } from './productUsageContract.js'
const native = JSON.parse(readFileSync(new URL('../../../tests/fixtures/desktop-product-usage-report.json', import.meta.url), 'utf8'))
const { context: _context, ...legacy } = native
@@ -84,9 +84,18 @@ 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 2, the revision whose frame-phase names a Desktop waits for', () => {
- expect(APP_USAGE_VOCABULARY).toBe(2)
+it('announces vocabulary 3, the revision whose frame-phase and Add Phone names a Desktop waits for', () => {
+ expect(APP_USAGE_VOCABULARY).toBe(3)
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_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)
+ expect(PRODUCT_USAGE_ADD_PHONE_METRICS).toEqual(['ui_desktop_add_phone_offer', 'ui_desktop_add_phone_titlebar',
+ 'ui_desktop_add_phone_menu', 'ui_desktop_add_phone_account', 'ui_desktop_add_phone_machines', 'ui_desktop_add_phone_command'])
+ // Only a Desktop report with its context files them: not the legacy UI-only form.
+ expect(appProductUsageReport({ ...old, counters: { ui_desktop_add_phone_menu: 1 } })).toBeUndefined()
})
diff --git a/cli/src/lib/appProductUsageReport.ts b/cli/src/lib/appProductUsageReport.ts
index fc7842454..b454c189a 100644
--- a/cli/src/lib/appProductUsageReport.ts
+++ b/cli/src/lib/appProductUsageReport.ts
@@ -1,17 +1,20 @@
import { cleanUsageContext, HEALTH_MEASURES, CLI_REPORT_FAILURES } from './productHealthContract.js'
-import { PRODUCT_USAGE_METRICS, PRODUCT_USAGE_UI_METRICS, type ProductUsageReport } from './productUsageContract.js'
+import { PRODUCT_USAGE_ADD_PHONE_METRICS, PRODUCT_USAGE_METRICS, PRODUCT_USAGE_UI_METRICS,
+ type ProductUsageReport } from './productUsageContract.js'
/** 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`). The Desktop counts 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`). */
-export const APP_USAGE_VOCABULARY = 2
+ * 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
export 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.
const uiMetrics = new Set<string>(PRODUCT_USAGE_UI_METRICS.filter(metric => !metric.startsWith('ui_tui_')))
const desktopMetrics = new Set<string>([
...PRODUCT_USAGE_UI_METRICS.filter(metric => metric.startsWith('ui_desktop_')),
+ ...PRODUCT_USAGE_ADD_PHONE_METRICS,
...HEALTH_MEASURES.map(measure => `health_desktop_${measure}`),
...CLI_REPORT_FAILURES.map(reason => `health_desktop_report_failure_${reason}`),
])
diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.ts
index f1ec00673..6ecd57ca4 100644
--- a/cli/src/lib/productUsageContract.ts
+++ b/cli/src/lib/productUsageContract.ts
@@ -52,9 +52,19 @@ export const PRODUCT_USAGE_PHONE_SCREENS = ['find', 'computers'] as const
export const PRODUCT_USAGE_SCREEN_OPENINGS = ['swipe', 'button'] as const
export const PRODUCT_USAGE_PHONE_SCREEN_METRICS = PRODUCT_USAGE_PHONE_SCREENS.flatMap(screen =>
PRODUCT_USAGE_SCREEN_OPENINGS.map(opening => `ui_phone_screen_${screen}_${opening}` as const))
+/** 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
+/** 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. */
+export const PRODUCT_USAGE_ADD_PHONE_OPENINGS = ['offer', 'titlebar', 'menu', 'account', 'machines', 'command'] as const
+export const PRODUCT_USAGE_ADD_PHONE_METRICS = PRODUCT_USAGE_ADD_PHONE_OPENINGS.map(opening => `ui_desktop_add_phone_${opening}` as const)
export const PRODUCT_USAGE_FLOWS = [...PRODUCT_USAGE_SETUP_FLOWS,
'workspace_connect', 'computer_link', 'remote_connect', 'viewer_open', 'update_check', 'update_stage',
- ...HEALTH_FLOWS, ...PRODUCT_USAGE_ONBOARDING_FLOWS] as const
+ ...HEALTH_FLOWS, ...PRODUCT_USAGE_ONBOARDING_FLOWS, ...PRODUCT_USAGE_DESKTOP_FLOWS] as const
export const PRODUCT_USAGE_FLOW_MEASURES = ['started', 'ok', 'failed', 'cancelled', 'unknown',
'under_1s', '1s_to_10s', '10s_to_1m', 'over_1m'] as const
export const PRODUCT_USAGE_UI_METRICS = PRODUCT_USAGE_UI_SURFACES.flatMap(surface =>
@@ -150,6 +160,7 @@ export const PRODUCT_USAGE_METRICS = [
...PRODUCT_USAGE_UI_METRICS,
...PRODUCT_USAGE_ONBOARDING_METRICS,
...PRODUCT_USAGE_PHONE_SCREEN_METRICS,
+ ...PRODUCT_USAGE_ADD_PHONE_METRICS,
// Written by the backend itself: a report that named counters this backend does not know yet, which
// it kept without them (routes/productUsage.ts). One per report, never the names.
'health_cli_report_unknown_metric', 'health_desktop_report_unknown_metric', 'health_phone_report_unknown_metric',
diff --git a/desktop/lib/measurement/product_measurement.dart b/desktop/lib/measurement/product_measurement.dart
index 8b24ab323..3d0c656f4 100644
--- a/desktop/lib/measurement/product_measurement.dart
+++ b/desktop/lib/measurement/product_measurement.dart
@@ -28,6 +28,9 @@ enum ProductFlow {
connectUser('connect_user'),
connectAuto('connect_auto'),
resumeRecovery('resume_recovery'),
+ // 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 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'),
@@ -42,10 +45,50 @@ enum ProductFlow {
const ProductFlow(this.wire);
final String wire;
bool get beforeSignIn => index <= ProductFlow.signIn.index;
+
+ /// 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;
+
+ /// 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;
}
enum ProductOutcome { ok, failed, cancelled, unknown }
+/// Where Add Phone was opened from, counted each time it opens
+/// (`ui_desktop_add_phone_<wire>`): which way in, nothing else.
+enum AddPhoneOpening {
+ /// The Add Phone card's own button ([ProductFlow.phoneOffer]).
+ offer('offer'),
+
+ /// The title bar's phone: the native one on macOS, the tab row's elsewhere.
+ titlebar('titlebar'),
+
+ /// Harness ▸ Add Phone… in the macOS app menu, or a key bound to it there.
+ menu('menu'),
+
+ /// The account menu's Add Phone.
+ account('account'),
+
+ /// The Machines picker's Add Phone.
+ machines('machines'),
+
+ /// The `app.add_phone` command: `> add phone` in the palette, a key bound
+ /// to it outside the macOS menu, the start guide's phone row (shown only
+ /// without the New Harness box).
+ command('command');
+
+ const AddPhoneOpening(this.wire);
+ final String wire;
+
+ /// As [ProductFlow.phoneOffer]'s ([ProductFlow.vocabulary]).
+ static const vocabulary = 3;
+}
+
typedef ProductReportRequest = Future<Map<String, dynamic>> Function(
Map<String, dynamic> report,
);
@@ -435,13 +478,37 @@ class ProductMeasurement extends ChangeNotifier {
);
}
- if (healthEnabled) {
+ if (healthEnabled && !flow.unbounded) {
_expires[ticket] = started.add(const Duration(minutes: 15));
_expire[ticket] = finish;
}
return finish;
}
+ /// Add Phone opened, and from where ([AddPhoneOpening]): one fixed name per
+ /// way in, nothing about the dialog or what follows. A signed-in, sharing
+ /// Desktop only; the browser has no such names.
+ void addPhoneOpened(AddPhoneOpening from) {
+ if (!healthEnabled || !sharing || _disposed) return;
+ _coverage();
+ _count(
+ 'ui',
+ _now().toUtc().toIso8601String().substring(0, 10),
+ 'ui_desktop_add_phone_${from.wire}',
+ );
+ }
+
+ /// 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;
+
/// A widget's delayed callback cannot count after sign-out or a choice revision.
VoidCallback observer(ProductHealthMeasure measure) {
final epoch = _accountEpoch;
@@ -604,11 +671,24 @@ class ProductMeasurement extends ChangeNotifier {
final epoch = channel == 'setup' ? _guestEpoch : _accountEpoch;
var report = _pending[channel];
if (report == null) {
- final keys = _days.keys.where((k) => k.startsWith('$channel:')).toList()
- ..sort();
+ // A name newer than the proxy is known to forward waits here for an
+ // answer that says it does, rather than being skipped as a health
+ // measure is: the Add Phone card shows once per computer, often before
+ // the first answer. Each minute's runtime sample sends a report, so
+ // an answer comes; an older CLI's never does, and the day expires.
+ bool ready(String metric) => _vocabularyOf(metric) <= proxyVocabulary;
+ final keys =
+ _days.keys
+ .where(
+ (k) => k.startsWith('$channel:') && _days[k]!.keys.any(ready),
+ )
+ .toList()
+ ..sort();
if (keys.isEmpty) continue;
final key = keys.first, counts = _days[key]!;
- final batch = Map<String, int>.fromEntries(counts.entries.take(32));
+ final batch = Map<String, int>.fromEntries(
+ counts.entries.where((entry) => ready(entry.key)).take(32),
+ );
for (final metric in batch.keys) {
counts.remove(metric);
}
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 1273ea226..1ebf6c6d2 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -119,6 +119,7 @@ import '../widgets/delete_agent_dialog.dart';
import '../widgets/delete_harness_dialog.dart';
import '../widgets/fork_agent_dialog.dart';
import '../widgets/restart_agent_action.dart';
+import '../measurement/product_measurement.dart' show AddPhoneOpening;
import '../measurement/task_feedback.dart';
import '../widgets/new_agent_dialog.dart';
import '../widgets/box_chrome.dart';
@@ -2653,7 +2654,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
case 'settings':
await _settings();
case 'addPhone':
- await _addPhone();
+ await _addPhone(
+ from: args['from'] == 'titlebar'
+ ? AddPhoneOpening.titlebar
+ : AddPhoneOpening.menu,
+ );
case 'customize':
await _customize();
}
@@ -3206,7 +3211,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (!mounted) return;
switch (choice) {
case AccountMenuChoice.addPhone:
- await _addPhone();
+ await _addPhone(from: AddPhoneOpening.account);
case AccountMenuChoice.customize:
await _customize();
case AccountMenuChoice.notifications:
@@ -3234,15 +3239,18 @@ class _SwarmScreenState extends State<SwarmScreen> {
/// Harness ▸ Add Phone… and `> add phone`: the QR a phone scans to sign in
/// and pair with this computer. See `widgets/add_phone_dialog.dart`.
- Future<void> _addPhone() async {
+ /// [from] is the way in it is counted under ([AddPhoneOpening]).
+ Future<void> _addPhone({required AddPhoneOpening from}) async {
// Open, from its card or by hand, it is this computer's offer
// ([_phoneOfferCard]) spent for good — and a sign-in made from inside it
// (its Continue with…) must not bring the card back once it closes, so
// the offer is dropped on the way out too.
- app.dropPhoneOffer();
try {
- await _dialog(
- () => showAddPhoneDialog(
+ await _dialog(() {
+ // Counted, and the offer spent, once it opens: [_dialog] refuses one
+ // while another dialog is up.
+ app.addPhoneOpened(from);
+ return showAddPhoneDialog(
context,
app,
keymap: _keymap,
@@ -3253,8 +3261,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
// picker refused to open — the link did nothing. The request waits
// for the route ([_maybeOpenMachinesRequest]).
onManageDevices: () => app.requestMachines(phones: true),
- ),
- );
+ );
+ });
} finally {
app.dropPhoneOffer();
}
@@ -3422,7 +3430,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
? null
: () {
_closeSearch(restoreFocus: false);
- unawaited(_addPhone());
+ unawaited(_addPhone(from: AddPhoneOpening.machines));
},
);
@@ -7036,8 +7044,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
if (kIsWeb || !app.phoneOfferShowing) return null;
if (app.firstArrival.pending || app.firstArrival.running) return null;
return PhoneOfferCard(
- onAdd: () => unawaited(_addPhone()),
- onDismiss: app.dropPhoneOffer,
+ onAdd: () => unawaited(_addPhone(from: AddPhoneOpening.offer)),
+ onDismiss: app.dismissPhoneOffer,
+ onShown: app.phoneOfferShown,
);
}
@@ -7241,7 +7250,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
!appearancePrefsStore.value.shadeInactivePanes,
),
),
- 'app.add_phone': () => unawaited(_addPhone()),
+ 'app.add_phone': () => unawaited(_addPhone(from: AddPhoneOpening.command)),
'app.product_feedback': () => unawaited(
showTaskFeedback(
context,
@@ -8793,7 +8802,9 @@ class _SwarmScreenState extends State<SwarmScreen> {
key: const ValueKey('swarm-add-phone-button'),
label: 'Add Phone',
tooltip: _addPhoneTooltip,
- onPressed: _shortcutsEnabled ? () => unawaited(_addPhone()) : null,
+ onPressed: _shortcutsEnabled
+ ? () => unawaited(_addPhone(from: AddPhoneOpening.titlebar))
+ : null,
builder: (context, emphasized) => SizedBox(
width: workspaceBarCellSizeOf(context).width * 4,
height: workspaceBarControlHeight(context),
diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dart
index 8a8af57e7..8626ebc4d 100644
--- a/desktop/lib/state/app_state.dart
+++ b/desktop/lib/state/app_state.dart
@@ -1110,6 +1110,8 @@ class AppNotifier extends ChangeNotifier {
int _invalidateAuthWork() {
_closeAttachmentSessions();
+ // A card a sign-out or another sign-in takes away went neither way.
+ _endPhoneOffer(ProductOutcome.unknown);
_phoneOffer = false;
_closeOwnerMemories();
_stopMachineRecovery();
@@ -7028,10 +7030,45 @@ class AppNotifier extends ChangeNotifier {
bool get phoneOfferShowing => _phoneOffer;
bool _phoneOffer = false;
+ /// 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).
+ void Function(ProductOutcome)? _phoneOfferMeasure;
+
+ /// The card is on screen. Its observation starts here, not at [_phoneOffer]: a new computer's
+ /// first agents keep it off the screen while they open (`state/first_arrival.dart`). Once per
+ /// offer, however often the card is built again.
+ void phoneOfferShown() {
+ if (!_phoneOffer || _phoneOfferMeasure != null) return;
+ _phoneOfferMeasure = productMeasurement.begin(ProductFlow.phoneOffer);
+ }
+
+ void _endPhoneOffer(ProductOutcome outcome) {
+ final finish = _phoneOfferMeasure;
+ _phoneOfferMeasure = null;
+ finish?.call(outcome);
+ }
+
+ /// Add Phone is opening, from [from]: counted by its way in, and this computer's offer spent
+ /// ([dropPhoneOffer]) — ok for the card when it was the card's own button.
+ void addPhoneOpened(AddPhoneOpening from) {
+ productMeasurement.addPhoneOpened(from);
+ if (from == AddPhoneOpening.offer) _endPhoneOffer(ProductOutcome.ok);
+ dropPhoneOffer();
+ }
+
+ /// The card's ×: put away for good ([dropPhoneOffer]).
+ void dismissPhoneOffer() {
+ _endPhoneOffer(ProductOutcome.cancelled);
+ dropPhoneOffer();
+ }
+
/// Add Phone was opened — from the card or by hand — or the card was put away: nothing is left to
/// offer, now or on a later launch or sign-in. Also how a sign-in made from inside Add Phone (its
/// "Sign in…") does not bring the card back.
void dropPhoneOffer() {
+ // Not by the card's own buttons ([addPhoneOpened], [dismissPhoneOffer]), which end it first.
+ _endPhoneOffer(ProductOutcome.unknown);
final showing = _phoneOffer;
_phoneOffer = false;
_markPhoneOfferDone();
diff --git a/desktop/lib/widgets/phone_offer_card.dart b/desktop/lib/widgets/phone_offer_card.dart
index 10dd099fe..c77dff58e 100644
--- a/desktop/lib/widgets/phone_offer_card.dart
+++ b/desktop/lib/widgets/phone_offer_card.dart
@@ -22,11 +22,12 @@ import '../theme/app_theme.dart';
/// go"), which a new computer has just shown. The button is named as the phone
/// names it — "Open Add Phone on your computer" (mobile `set_up_computer.dart`)
/// — so somebody the phone sent here finds the thing it told them about.
-class PhoneOfferCard extends StatelessWidget {
+class PhoneOfferCard extends StatefulWidget {
const PhoneOfferCard({
super.key,
required this.onAdd,
required this.onDismiss,
+ this.onShown,
});
/// Add Phone: the code a phone scans — or, for a guest, the sign-in first.
@@ -36,6 +37,23 @@ class PhoneOfferCard extends StatelessWidget {
/// command palette.
final VoidCallback onDismiss;
+ /// After the card's first frame on screen ([AppNotifier.phoneOfferShown]),
+ /// again each time it is built anew; the app counts one per offer.
+ final VoidCallback? onShown;
+
+ @override
+ State<PhoneOfferCard> createState() => _PhoneOfferCardState();
+}
+
+class _PhoneOfferCardState extends State<PhoneOfferCard> {
+ @override
+ void initState() {
+ super.initState();
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) widget.onShown?.call();
+ });
+ }
+
@override
Widget build(BuildContext context) {
grid.AppTheme.watch(context);
@@ -82,7 +100,7 @@ class PhoneOfferCard extends StatelessWidget {
const SizedBox(height: 10),
FilledButton(
key: const Key('phone-offer-add'),
- onPressed: onAdd,
+ onPressed: widget.onAdd,
child: const Text('Add Phone'),
),
],
@@ -95,7 +113,7 @@ class PhoneOfferCard extends StatelessWidget {
splashRadius: 14,
visualDensity: VisualDensity.compact,
tooltip: 'Dismiss',
- onPressed: onDismiss,
+ onPressed: widget.onDismiss,
),
],
),
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 3ee3c6146..6ab40ae16 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -2823,7 +2823,9 @@ private final class SwarmTabStrip: NSView {
if actionsEnabled && searchButton.isEnabled { emit?("sessions", nil) }
}
@objc private func openAddPhone() {
- if actionsEnabled && phoneButton.isEnabled { emit?("addPhone", nil) }
+ // Named, so Add Phone is counted as the title bar's rather than Harness ▸ Add Phone…'s,
+ // which sends the same action with no arguments (`AddPhoneOpening` in product_measurement.dart).
+ if actionsEnabled && phoneButton.isEnabled { emit?("addPhone", ["from": "titlebar"]) }
}
@objc private func openStore() {
if actionsEnabled && storeButton.isEnabled { emit?("store", nil) }
diff --git a/desktop/test/add_phone_dialog_test.dart b/desktop/test/add_phone_dialog_test.dart
index 1971816f9..1f8f1a1fc 100644
--- a/desktop/test/add_phone_dialog_test.dart
+++ b/desktop/test/add_phone_dialog_test.dart
@@ -8,6 +8,7 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:harness/core/models.dart';
import 'package:harness/core/config.dart';
import 'package:harness/core/phone_app_links.dart';
+import 'package:harness/measurement/product_measurement.dart';
import 'package:harness/auth/auth_session.dart';
import 'package:harness/auth/sign_in_provider.dart';
import 'package:harness/viewer/viewer_services.dart';
@@ -19,6 +20,7 @@ import 'package:harness/widgets/add_phone_dialog.dart';
import 'package:harness/widgets/desktop_chrome.dart'
show DesktopChrome, DesktopDialogSurface;
+import 'support/add_phone_measurement.dart';
import 'swarm_interactions_test.dart' show chord;
import 'swarm_screen_test.dart' show mount;
import 'swarm_state_test.dart' show createApp, MemoryStore;
@@ -895,39 +897,65 @@ void main() {
group('the way in', () {
// `createApp` has no profile and no local machine, so the dialog opens
// with nothing to arm — these tests never reach for a real daemon.
- testWidgets('Harness ▸ Add Phone… opens the dialog', (tester) async {
- const channel = MethodChannel('harness/swarm_tabs');
- final messenger = tester.binding.defaultBinaryMessenger;
- messenger.setMockMethodCallHandler(channel, (_) async => true);
- addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
- final app = createApp()..status = AppStatus.authenticated;
- addTearDown(app.dispose);
- await mount(tester, app, nativeTabs: true);
-
- final handled = Completer<void>();
- messenger.handlePlatformMessage(
- channel.name,
- const StandardMethodCodec().encodeMethodCall(
- const MethodCall('addPhone'),
- ),
- (_) => handled.complete(),
- );
- await tester.pump();
- await tester.pump(const Duration(milliseconds: 100));
- expect(find.byType(AddPhoneDialog), findsOneWidget);
- expect(find.text('Add your phone'), findsOneWidget);
-
- await tester.sendKeyEvent(LogicalKeyboardKey.escape);
- await tester.pump();
- await handled.future;
- expect(find.byType(AddPhoneDialog), findsNothing);
- await tester.pumpWidget(const SizedBox());
- });
+ // Each way in is counted as its own (`ui_desktop_add_phone_<way>`).
+ for (final (name, arguments, from) in [
+ ('Harness ▸ Add Phone…', null, AddPhoneOpening.menu),
+ (
+ 'The native title bar\'s phone',
+ {'from': 'titlebar'},
+ AddPhoneOpening.titlebar,
+ ),
+ ]) {
+ testWidgets('$name opens the dialog', (tester) async {
+ const channel = MethodChannel('harness/swarm_tabs');
+ final messenger = tester.binding.defaultBinaryMessenger;
+ messenger.setMockMethodCallHandler(channel, (_) async => true);
+ addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
+ final usage = AddPhoneRecorder();
+ final app = createApp(productMeasurement: usage)
+ ..status = AppStatus.authenticated;
+ addTearDown(app.dispose);
+ await mount(tester, app, nativeTabs: true);
+
+ final handled = Completer<void>();
+ messenger.handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ MethodCall('addPhone', arguments),
+ ),
+ (_) => handled.complete(),
+ );
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 100));
+ expect(find.byType(AddPhoneDialog), findsOneWidget);
+ expect(find.text('Add your phone'), findsOneWidget);
+ expect(usage.openings, [from]);
+
+ // Asked again while it is open: refused, so not counted.
+ messenger.handlePlatformMessage(
+ channel.name,
+ const StandardMethodCodec().encodeMethodCall(
+ MethodCall('addPhone', arguments),
+ ),
+ (_) {},
+ );
+ await tester.pump();
+ expect(usage.openings, [from]);
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ await handled.future;
+ expect(find.byType(AddPhoneDialog), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ });
+ }
testWidgets('> add phone opens the dialog from the command search', (
tester,
) async {
- final app = createApp()..status = AppStatus.authenticated;
+ final usage = AddPhoneRecorder();
+ final app = createApp(productMeasurement: usage)
+ ..status = AppStatus.authenticated;
addTearDown(app.dispose);
await mount(tester, app);
await chord(tester, LogicalKeyboardKey.keyP, shift: true);
@@ -940,6 +968,7 @@ void main() {
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(find.byType(AddPhoneDialog), findsOneWidget);
+ expect(usage.openings, [AddPhoneOpening.command]);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
@@ -948,18 +977,48 @@ void main() {
});
testWidgets('the tab row\'s Add Phone opens the dialog', (tester) async {
- final app = createApp()..status = AppStatus.authenticated;
+ final usage = AddPhoneRecorder();
+ final app = createApp(productMeasurement: usage)
+ ..status = AppStatus.authenticated;
addTearDown(app.dispose);
await mount(tester, app);
await tester.tap(find.byKey(const ValueKey('swarm-add-phone-button')));
await tester.pump();
await tester.pump(const Duration(milliseconds: 100));
expect(find.byType(AddPhoneDialog), findsOneWidget);
+ expect(usage.openings, [AddPhoneOpening.titlebar]);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
expect(find.byType(AddPhoneDialog), findsNothing);
await tester.pumpWidget(const SizedBox());
});
+
+ testWidgets('the account menu\'s Add Phone opens the dialog', (
+ tester,
+ ) async {
+ final usage = AddPhoneRecorder();
+ final app = createApp(productMeasurement: usage)
+ ..currentUser = const CurrentUserProfile(
+ name: 'Dee Example',
+ email: '[email protected]',
+ );
+ addTearDown(app.dispose);
+ await mount(tester, app);
+ await tester.tap(find.byKey(const ValueKey('swarm-account-button')));
+ await tester.pump();
+ await tester.pump();
+ await tester.tap(find.byKey(const ValueKey('account-menu-addPhone')));
+ await tester.pump();
+ await tester.pump(const Duration(milliseconds: 400));
+ expect(find.byType(AddPhoneDialog), findsOneWidget);
+ expect(usage.openings, [AddPhoneOpening.account]);
+
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
+ await tester.pump();
+ expect(find.byType(AddPhoneDialog), findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ await tester.pump(const Duration(seconds: 5));
+ });
});
}
diff --git a/desktop/test/machine_devices_picker_test.dart b/desktop/test/machine_devices_picker_test.dart
index 3bc6b849a..908340984 100644
--- a/desktop/test/machine_devices_picker_test.dart
+++ b/desktop/test/machine_devices_picker_test.dart
@@ -9,6 +9,8 @@ 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'
+ show AddPhoneOpening;
import 'package:harness/screens/swarm_screen.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/shared/widgets/app_select_field.dart';
@@ -35,6 +37,15 @@ class _App extends FakeDevicesApp {
final deletes = <String>[];
String? deleteError;
+ /// Each Add Phone opened, by its way in.
+ final addPhoneOpenings = <AddPhoneOpening>[];
+
+ @override
+ void addPhoneOpened(AddPhoneOpening from) {
+ addPhoneOpenings.add(from);
+ super.addPhoneOpened(from);
+ }
+
@override
Future<String?> deleteMachine(String id) async {
deletes.add(id);
@@ -520,6 +531,7 @@ void main() {
await tester.tap(find.byKey(const Key('machine-picker-add-phone')));
await tester.pumpAndSettle();
expect(find.byType(AddPhoneDialog), findsOneWidget);
+ expect(app.addPhoneOpenings, [AddPhoneOpening.machines]);
expect(resourceScope('@'), findsNothing);
app.ownDaemonMachineIdForTest(_localId);
diff --git a/desktop/test/phone_offer_test.dart b/desktop/test/phone_offer_test.dart
index 38b1df78b..b5027505b 100644
--- a/desktop/test/phone_offer_test.dart
+++ b/desktop/test/phone_offer_test.dart
@@ -3,11 +3,13 @@ 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/measurement/product_measurement.dart';
import 'package:harness/shared/theme/app_theme.dart' as grid;
import 'package:harness/state/app_state.dart';
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_state_test.dart' show createApp, MemoryStore;
@@ -143,6 +145,98 @@ void main() {
});
});
+ group('its measure', () {
+ /// A guest's first launch, with the card offered, measured by [usage].
+ Future<AppNotifier> offered(AddPhoneRecorder usage) async {
+ final app = createApp(store: MemoryStore(), productMeasurement: usage)
+ ..signedIn = false;
+ addTearDown(app.dispose);
+ await app.offerPhoneForTest(atLaunch: true);
+ expect(app.phoneOfferShowing, isTrue);
+ return app;
+ }
+
+ List<String> card(AddPhoneRecorder usage) =>
+ usage.started.where((flow) => flow == 'phoneOffer').toList();
+
+ test(
+ 'begins once it is on screen, once however often it is built',
+ () async {
+ final usage = AddPhoneRecorder();
+ final app = await offered(usage);
+ expect(card(usage), isEmpty);
+ app.phoneOfferShown();
+ app.phoneOfferShown();
+ expect(card(usage), ['phoneOffer']);
+ expect(usage.ended, isEmpty);
+ },
+ );
+
+ test('nothing begins with no card offered', () async {
+ final usage = AddPhoneRecorder();
+ final app = createApp(store: MemoryStore(), productMeasurement: usage);
+ addTearDown(app.dispose);
+ app.phoneOfferShown();
+ expect(card(usage), isEmpty);
+ });
+
+ test('its Add Phone is ok, its × cancelled, once each', () async {
+ final add = AddPhoneRecorder();
+ final app = await offered(add);
+ app.phoneOfferShown();
+ app.addPhoneOpened(AddPhoneOpening.offer);
+ expect(add.ended, ['phoneOffer:ok']);
+ expect(add.openings, [AddPhoneOpening.offer]);
+ expect(app.phoneOfferShowing, isFalse);
+ // The dialog closing drops the spent offer again: nothing more.
+ app.dropPhoneOffer();
+ expect(add.ended, ['phoneOffer:ok']);
+
+ final dismiss = AddPhoneRecorder();
+ final other = await offered(dismiss);
+ other.phoneOfferShown();
+ other.dismissPhoneOffer();
+ other.dismissPhoneOffer();
+ expect(dismiss.ended, ['phoneOffer:cancelled']);
+ expect(dismiss.openings, isEmpty);
+ expect(other.phoneOfferShowing, isFalse);
+ });
+
+ test(
+ 'Add Phone opened another way while it shows is unknown for it',
+ () async {
+ final usage = AddPhoneRecorder();
+ final app = await offered(usage);
+ app.phoneOfferShown();
+ app.addPhoneOpened(AddPhoneOpening.menu);
+ expect(usage.ended, ['phoneOffer:unknown']);
+ expect(usage.openings, [AddPhoneOpening.menu]);
+ expect(app.phoneOfferShowing, isFalse);
+ // Later openings count their way in, with no card left to end.
+ app.addPhoneOpened(AddPhoneOpening.account);
+ expect(usage.ended, ['phoneOffer:unknown']);
+ expect(usage.openings, [AddPhoneOpening.menu, AddPhoneOpening.account]);
+ },
+ );
+
+ test('a card a sign-in takes away is unknown', () async {
+ final usage = AddPhoneRecorder();
+ final app = await offered(usage);
+ app.phoneOfferShown();
+ app.signingIn = true;
+ app.cancelLogin();
+ expect(usage.ended, ['phoneOffer:unknown']);
+ expect(app.phoneOfferShowing, isFalse);
+ });
+
+ test('a card never on screen ends nothing', () async {
+ final usage = AddPhoneRecorder();
+ final app = await offered(usage);
+ app.dismissPhoneOffer();
+ expect(usage.ended, isEmpty);
+ });
+ });
+
group('the card', () {
Future<({List<String> taps})> card(WidgetTester tester) async {
final taps = <String>[];
@@ -155,6 +249,7 @@ void main() {
child: PhoneOfferCard(
onAdd: () => taps.add('add'),
onDismiss: () => taps.add('dismiss'),
+ onShown: () => taps.add('shown'),
),
),
),
@@ -176,14 +271,18 @@ void main() {
expect(find.widgetWithText(FilledButton, 'Add Phone'), findsOneWidget);
await tester.tap(find.byKey(const Key('phone-offer-add')));
await tester.tap(find.byKey(const Key('phone-offer-dismiss')));
- expect(taps, ['add', 'dismiss']);
+ // On screen once its first frame is drawn, before any tap.
+ expect(taps, ['shown', 'add', 'dismiss']);
});
});
group('on the workspace', () {
- Future<(AppNotifier, MemoryStore)> offered(WidgetTester tester) async {
+ Future<(AppNotifier, MemoryStore)> offered(
+ WidgetTester tester, {
+ ProductMeasurement? usage,
+ }) async {
final store = MemoryStore();
- final app = createApp(store: store)
+ final app = createApp(store: store, productMeasurement: usage)
..status = AppStatus.authenticated
..signedIn = false;
await app.offerPhoneForTest(atLaunch: true);
@@ -195,8 +294,10 @@ void main() {
testWidgets(
'the card stands in the top-right, and Add Phone opens from it',
(tester) async {
- final (app, store) = await offered(tester);
+ final usage = AddPhoneRecorder();
+ final (app, store) = await offered(tester, usage: usage);
addTearDown(app.dispose);
+ expect(usage.started.where((f) => f == 'phoneOffer'), ['phoneOffer']);
final card = find.byKey(const Key('phone-offer-card'));
expect(card, findsOneWidget);
// Beside the work, in the agents' banners' corner — not over the middle of the window.
@@ -209,6 +310,8 @@ void main() {
await tester.pump(const Duration(milliseconds: 100));
expect(find.byType(AddPhoneDialog), findsOneWidget);
expect(find.byKey(const Key('phone-offer-card')), findsNothing);
+ expect(usage.ended, ['phoneOffer:ok']);
+ expect(usage.openings, [AddPhoneOpening.offer]);
await tester.pump();
expect(store.values[_done], '1');
@@ -218,12 +321,15 @@ void main() {
);
testWidgets('× puts it away for good', (tester) async {
- final (app, store) = await offered(tester);
+ final usage = AddPhoneRecorder();
+ final (app, store) = await offered(tester, usage: usage);
addTearDown(app.dispose);
await tester.tap(find.byKey(const Key('phone-offer-dismiss')));
await tester.pump();
expect(find.byKey(const Key('phone-offer-card')), findsNothing);
expect(find.byType(AddPhoneDialog), findsNothing);
+ expect(usage.ended, ['phoneOffer:cancelled']);
+ expect(usage.openings, isEmpty);
await tester.pump();
expect(store.values[_done], '1');
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/product_health_test.dart b/desktop/test/product_health_test.dart
index 4db1d146a..640ab23d3 100644
--- a/desktop/test/product_health_test.dart
+++ b/desktop/test/product_health_test.dart
@@ -408,4 +408,160 @@ void main() {
await tester.pump();
},
);
+
+ group('Add Phone', () {
+ Iterable<String> addPhoneNames() => totals().keys.where(
+ (key) =>
+ key.startsWith('ui_desktop_phone_offer_') ||
+ key.startsWith('ui_desktop_add_phone_'),
+ );
+
+ test(
+ 'the card and its openings wait for a CLI that forwards them, then go',
+ () async {
+ await usage.flush();
+ // Counted from the start: the card shows once per computer, often
+ // before the CLI's first answer has said which names it forwards.
+ usage.begin(ProductFlow.phoneOffer)(ProductOutcome.ok);
+ usage.addPhoneOpened(AddPhoneOpening.offer);
+ await usage.flush();
+ // The day's coverage goes; the names wait.
+ expect(totals()['health_desktop_collector_days'], 1);
+ expect(addPhoneNames(), isEmpty);
+ final sent = reports.length;
+ await usage.flush();
+ // Only waiting names are left, and a report of none is not sent.
+ expect(reports, hasLength(sent));
+ for (final vocabulary in [1, 2]) {
+ usage.proxyVocabulary = vocabulary;
+ usage.health(ProductHealthMeasure.asyncError);
+ await usage.flush();
+ expect(totals()['health_desktop_async_error'], vocabulary);
+ expect(addPhoneNames(), isEmpty, reason: 'vocabulary $vocabulary');
+ }
+ usage.proxyVocabulary = 3;
+ await usage.flush();
+ expect(
+ {for (final name in addPhoneNames()) name: totals()[name]},
+ {
+ 'ui_desktop_phone_offer_started': 1,
+ 'ui_desktop_phone_offer_ok': 1,
+ 'ui_desktop_phone_offer_under_1s': 1,
+ 'ui_desktop_add_phone_offer': 1,
+ },
+ );
+ expect(reports.last['context'], isNotNull);
+ },
+ );
+
+ test(
+ 'waiting names do not hold back a later day or other counts',
+ () async {
+ await usage.flush();
+ usage.health(ProductHealthMeasure.asyncError);
+ await usage.flush();
+ // The day's coverage is counted already: the day holds only a
+ // waiting name now.
+ usage.addPhoneOpened(AddPhoneOpening.menu);
+ now = now.add(const Duration(days: 1));
+ usage.health(ProductHealthMeasure.asyncError);
+ await usage.flush();
+ expect(reports.last['day'], '2026-10-15');
+ expect(totals()['health_desktop_async_error'], 2);
+ expect(addPhoneNames(), isEmpty);
+ usage.proxyVocabulary = 3;
+ await usage.flush();
+ expect(reports.last['day'], '2026-10-14');
+ expect(totals()['ui_desktop_add_phone_menu'], 1);
+ },
+ );
+
+ test('the card is not ended by the 15-minute observation bound', () async {
+ await usage.flush();
+ usage.proxyVocabulary = 3;
+ final card = usage.begin(ProductFlow.phoneOffer);
+ // A bounded flow begun beside it is ended unknown, as before.
+ usage.begin(ProductFlow.connectUser);
+ now = now.add(const Duration(minutes: 40));
+ await usage.flush();
+ await usage.flush();
+ expect(totals()['ui_desktop_connect_user_unknown'], 1);
+ expect(totals()['ui_desktop_phone_offer_unknown'], isNull);
+ // Put away 40 minutes later, and counted as that.
+ card(ProductOutcome.cancelled);
+ card(ProductOutcome.ok);
+ await usage.flush();
+ expect(totals()['ui_desktop_phone_offer_started'], 1);
+ expect(totals()['ui_desktop_phone_offer_cancelled'], 1);
+ expect(totals()['ui_desktop_phone_offer_ok'], isNull);
+ });
+
+ test('every way in has its own name, and nothing else is sent', () async {
+ await usage.flush();
+ usage.proxyVocabulary = 3;
+ for (final from in AddPhoneOpening.values) {
+ usage.addPhoneOpened(from);
+ }
+ usage.addPhoneOpened(AddPhoneOpening.titlebar);
+ await usage.flush();
+ expect(
+ {for (final name in addPhoneNames()) name: totals()[name]},
+ {
+ 'ui_desktop_add_phone_offer': 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,
+ },
+ );
+ });
+
+ test(
+ 'nothing is counted without sharing, an account or a Desktop',
+ () async {
+ await usage.flush();
+ usage.proxyVocabulary = 3;
+ usage.savedChoice({'enabled': false, 'revision': 1});
+ usage.begin(ProductFlow.phoneOffer)(ProductOutcome.ok);
+ usage.addPhoneOpened(AddPhoneOpening.offer);
+ choice = {'enabled': true, 'revision': 2};
+ await usage.flush();
+ expect(addPhoneNames(), isEmpty);
+
+ // Signed out: no account to count it under, and no signed-out name.
+ usage.account(null);
+ usage.begin(ProductFlow.phoneOffer)(ProductOutcome.ok);
+ usage.addPhoneOpened(AddPhoneOpening.offer);
+ await usage.flush();
+ expect(addPhoneNames(), isEmpty);
+ expect(jsonEncode(setup), isNot(contains('phone_offer')));
+ expect(jsonEncode(setup), isNot(contains('add_phone')));
+
+ // The browser has no health context, and no names for these.
+ final web = ProductMeasurement(
+ surface: 'web',
+ automatic: false,
+ now: () => now,
+ sendSetup: (report) async => {'accepted': true},
+ );
+ addTearDown(web.dispose);
+ final sentByWeb = <Map<String, dynamic>>[];
+ web.account(
+ 'PRIVATE_ACCOUNT',
+ choice: () async => choice,
+ send: (report) async {
+ sentByWeb.add(report);
+ return {'accepted': true};
+ },
+ );
+ await web.flush();
+ web.proxyVocabulary = 3;
+ web.begin(ProductFlow.phoneOffer)(ProductOutcome.ok);
+ web.addPhoneOpened(AddPhoneOpening.command);
+ await web.flush();
+ expect(sentByWeb, isEmpty);
+ },
+ );
+ });
}
diff --git a/desktop/test/support/add_phone_measurement.dart b/desktop/test/support/add_phone_measurement.dart
new file mode 100644
index 000000000..53bb0d9db
--- /dev/null
+++ b/desktop/test/support/add_phone_measurement.dart
@@ -0,0 +1,24 @@
+import 'package:harness/measurement/product_measurement.dart';
+
+/// Records the Add Phone card's observation and each way Add Phone opened,
+/// instead of reporting them.
+class AddPhoneRecorder extends ProductMeasurement {
+ AddPhoneRecorder()
+ : super(surface: 'desktop', automatic: false, sendSetup: (_) async => {});
+
+ /// Each flow begun, by its enum name.
+ final started = <String>[];
+
+ /// Each flow's end, as `flow:outcome`.
+ final ended = <String>[];
+ final openings = <AddPhoneOpening>[];
+
+ @override
+ void Function(ProductOutcome) begin(ProductFlow flow) {
+ started.add(flow.name);
+ return (outcome) => ended.add('${flow.name}:${outcome.name}');
+ }
+
+ @override
+ void addPhoneOpened(AddPhoneOpening from) => openings.add(from);
+}
diff --git a/desktop/test/swarm_state_test.dart b/desktop/test/swarm_state_test.dart
index 0e251acef..86872278d 100644
--- a/desktop/test/swarm_state_test.dart
+++ b/desktop/test/swarm_state_test.dart
@@ -3,6 +3,7 @@ import 'package:harness/auth/auth_session.dart';
import 'package:harness/core/config.dart';
import 'package:harness/core/local_key_value_store.dart';
import 'package:harness/core/models.dart';
+import 'package:harness/measurement/product_measurement.dart';
import 'package:harness/state/app_state.dart';
import 'package:harness/state/pane_layout_store.dart';
import 'package:harness/state/pane_preset.dart';
@@ -31,12 +32,14 @@ AppNotifier createApp({
MemoryStore? store,
WsConn Function(String)? connectionForTest,
bool connected = false,
+ ProductMeasurement? productMeasurement,
}) {
final app = AppNotifier(
config: AppConfig.dev,
authSession: AuthSession(),
configStore: null,
connectionForTest: connectionForTest,
+ productMeasurement: productMeasurement,
paneLayoutStore: store == null ? null : PaneLayoutStore(storage: store),
)..hasNavigationRail = false;
const machine = Machine(
diff --git a/docs/product-measurement.md b/docs/product-measurement.md
index 6f535d8a9..ecce84a35 100644
--- a/docs/product-measurement.md
+++ b/docs/product-measurement.md
@@ -22,6 +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 | Stage totals per day, not a linked funnel. 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. |
| 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. 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. |
| 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) | 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. |
@@ -168,7 +169,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 Desktop
discards a refused packet. A known name an app may not send, a bad value, or a report with no known
counter 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); a Desktop counts newer names only after reading it.
+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.
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.
@@ -290,7 +291,7 @@ Deploy backend schema and the singleton worker first, including unique indexes a
Use synthetic data to verify duplicate receipts, transaction rollback/retry, off/on revision fencing
and expiry. Then release CLI, desktop and phone together. An older backend refuses a whole report
carrying a counter it does not know (a phone page opening, a `request_phone_*` count, a phone
-`sharing: "default"` setup report, a launch code or a first launch's engine), so the backend always goes first. Check that the switch saves and that reports
+`sharing: "default"` setup report, a launch code, a first launch's engine, Desktop's Add Phone card or opening), so the backend always goes first. Check that the switch saves and that reports
stop when it is off. Old clients stop contributing individual daily histories when the backend changes;
the historical reporting command will no longer be a current-usage source.