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): count page opens, phone requests; default-on setup sharing

tony05a644628091
diff --git a/backend/src/lib/productUsage.test.ts b/backend/src/lib/productUsage.test.ts
index fe36e5633..37856f32a 100644
--- a/backend/src/lib/productUsage.test.ts
+++ b/backend/src/lib/productUsage.test.ts
@@ -248,10 +248,11 @@ it('setup ingestion never reads an account and expires after yesterday', async (
it('keeps anonymous transport and the phone opt-in unchanged while Desktop evolves independently', () => {
expect(readFileSync(new URL('../../../desktop/lib/measurement/setup_transport.dart', import.meta.url), 'utf8'))
.toBe(readFileSync(new URL('../../../mobile/lib/measurement/setup_transport.dart', import.meta.url), 'utf8'))
- // Desktop now uses its Settings-only default-on preference; the phone retains its own opt-in.
+ // Desktop keeps its Settings-only default-on preference; the phone defaults on too, with its opt-out
+ // kept on the phone and carried to the account at sign-in — and says so on its signed-out line.
const choice = (app: string) => readFileSync(new URL(`../../../${app}/lib/measurement/setup_usage_choice.dart`, import.meta.url), 'utf8')
for (const words of ['Share setup and sign-in counts',
- 'Optional for this app session. Help us find setup problems without sharing account details, prompts, or files.']) {
+ 'On unless you turn it off; off also turns it off for your account when you sign in. Helps us find setup problems without sharing account details, prompts, or files.']) {
expect(choice('mobile')).toContain(`'${words}'`)
}
const mobile = readFileSync(new URL('../../../mobile/lib/measurement/product_measurement.dart', import.meta.url), 'utf8')
diff --git a/backend/src/routes/productUsage.test.ts b/backend/src/routes/productUsage.test.ts
index 6db5de448..860d3dbb5 100644
--- a/backend/src/routes/productUsage.test.ts
+++ b/backend/src/routes/productUsage.test.ts
@@ -102,6 +102,17 @@ it('takes a phone build context: its release and iOS or Android, nothing finer',
expect(model.statusCode).toBe(400)
})
+it('takes how the phone opened Find or Computers, and the phone\'s own requests, and nothing else', async () => {
+ const context = { surface: 'phone', release: '1.0.4', platform: 'ios', channel: 'production' }
+ const counters = { ui_phone_screen_find_swipe: 2, ui_phone_screen_find_button: 1, ui_phone_screen_computers_swipe: 1,
+ ui_phone_screen_computers_button: 1, request_phone_create_started: 1, request_phone_resume_error_other: 1,
+ request_phone_resume_reason_busy: 1 }
+ expect((await submit({ ...good, context, counters })).statusCode).toBe(200)
+ for (const name of ['ui_phone_screen_settings_swipe', 'ui_phone_screen_find_pinch', 'ui_desktop_screen_find_swipe']) {
+ 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' },
@@ -129,16 +140,19 @@ it('keeps legacy explicit setup opt-in without credentials or account lookup', a
}
for (const headers of [{ authorization: 'fixture' }, { cookie: 'PRIVATE_CANARY' }]) expect((await sendSetup(setup, headers)).statusCode).toBe(400)
})
-it('accepts default-on sharing only for Desktop setup without asserting consent', async () => {
+it('accepts default-on sharing only for Desktop or phone setup, one at a time, without asserting consent', async () => {
const { consent: _, ...fields } = setup
const report = { ...fields, sharing: 'default' }
- expect((await sendSetup(report)).statusCode).toBe(200)
- expect(methods.ingestSetupUsage).toHaveBeenCalledWith(report)
+ const phone = { ...report, counters: { setup_phone_sign_in_started: 1, setup_phone_sign_in_google_ok: 1 } }
+ for (const accepted of [report, phone]) {
+ expect((await sendSetup(accepted)).statusCode).toBe(200)
+ expect(methods.ingestSetupUsage).toHaveBeenCalledWith(accepted)
+ }
expect(methods.productUsageChoice).not.toHaveBeenCalled()
expect(methods.ingestProductUsage).not.toHaveBeenCalled()
methods.ingestSetupUsage.mockClear()
for (const payload of [fields, { ...report, consent: true }, { ...report, sharing: 'off' },
- { ...report, counters: { setup_phone_sign_in_started: 1 } },
+ { ...report, counters: { setup_web_sign_in_started: 1 } },
{ ...report, counters: { ...setup.counters, setup_phone_sign_in_started: 1 } },
{ ...report, counters: { ui_desktop_sign_in_started: 1 } },
{ ...report, account: 'PRIVATE_CANARY' }]) {
diff --git a/backend/src/routes/productUsage.ts b/backend/src/routes/productUsage.ts
index fa90d68db..e8f4d89d2 100644
--- a/backend/src/routes/productUsage.ts
+++ b/backend/src/routes/productUsage.ts
@@ -26,12 +26,16 @@ const setupFields = {
counters: z.partialRecord(z.enum(PRODUCT_USAGE_SETUP_METRICS), z.number().int().min(1).max(1000))
.refine(c => Object.keys(c).length > 0 && Object.keys(c).length <= 32),
}
+// The surfaces whose signed-out counts may be on by default, each report wholly one surface's.
+const DEFAULT_SETUP_PREFIXES = ['setup_desktop_', 'setup_phone_']
export const setupUsageSchema = z.union([
- // Older native clients (including the phone) still require explicit opt-in.
+ // Older native clients (earlier phone builds included) still require explicit opt-in.
z.strictObject({ ...setupFields, consent: z.literal(true) }),
- // Desktop defaults on with a persistent Settings opt-out. Do not call that consent.
+ // Desktop and the phone default on, with an opt-out each keeps (Desktop's Settings, the line under
+ // the phone's signed-out screens). Do not call that consent.
z.strictObject({ ...setupFields, sharing: z.literal('default') })
- .refine(report => Object.keys(report.counters).every(key => key.startsWith('setup_desktop_'))),
+ .refine(report => DEFAULT_SETUP_PREFIXES.some(prefix =>
+ Object.keys(report.counters).every(key => key.startsWith(prefix)))),
])
export async function productUsageRoutes(app: FastifyInstance): Promise<void> {
diff --git a/backend/src/types/productHealthContract.ts b/backend/src/types/productHealthContract.ts
index 865626f81..1e53e411f 100644
--- a/backend/src/types/productHealthContract.ts
+++ b/backend/src/types/productHealthContract.ts
@@ -1,5 +1,7 @@
/** Fixed health vocabulary. Keep the CLI/backend copies identical. No arbitrary labels. */
-export const HEALTH_SOURCES = ['app', 'tool', 'automatic', 'unknown'] as const
+// `phone`: the phone app's requests, which it marks itself (`usageSurface`) — over the relay it is a
+// remote app client like the browser, and only it can say which one it is.
+export const HEALTH_SOURCES = ['app', 'tool', 'automatic', 'unknown', 'phone'] as const
export const HEALTH_ACTIONS = ['create', 'resume', 'restart', 'model_change', 'history', 'fork', 'close', 'delete',
'search', 'history_page', 'store_list', 'store_install', 'store_update', 'store_remove',
'model_list', 'model_download', 'model_start', 'model_stop', 'browser_open', 'message'] as const
diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.ts
index fceff8a0f..f8568c358 100644
--- a/backend/src/types/productUsage.ts
+++ b/backend/src/types/productUsage.ts
@@ -44,6 +44,14 @@ export const PRODUCT_USAGE_ONBOARDING_MARKS = ['ui_phone_sign_in_retried', 'ui_p
export const PRODUCT_USAGE_ONBOARDING_METRICS = [...PRODUCT_USAGE_ONBOARDING_MARKS,
...PRODUCT_USAGE_LONG_FLOWS.flatMap(flow => PRODUCT_USAGE_LONG_MEASURES.map(measure => `ui_phone_${flow}_${measure}` as const)),
] as const
+/** The phone's two side pages, counted each time one opens and by how: a sideways swipe on the
+ * terminal (Find from the left, Computers from the right), or a button (Computers' row in Settings,
+ * its link on a long wait at home). Find's key and screen-reader actions are not counted. Which page
+ * and which way, nothing else. */
+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))
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
@@ -86,6 +94,7 @@ export const PRODUCT_USAGE_METRICS = [
.map(measure => `${action}_user_${measure}` as const)),
...PRODUCT_USAGE_UI_METRICS,
...PRODUCT_USAGE_ONBOARDING_METRICS,
+ ...PRODUCT_USAGE_PHONE_SCREEN_METRICS,
] as const
export type ProductUsageMetric = typeof PRODUCT_USAGE_METRICS[number]
export interface ProductUsageReport {
diff --git a/cli/src/backendSocket.spec.ts b/cli/src/backendSocket.spec.ts
index b25adaac8..8b3580f55 100644
--- a/cli/src/backendSocket.spec.ts
+++ b/cli/src/backendSocket.spec.ts
@@ -3781,6 +3781,35 @@ describe('agent_recent replies', () => {
})
})
+describe('request sources', () => {
+ // The counter a request starts with, for a remote `web` client: the phone only by its own word.
+ async function startedFor(payload: Record<string, unknown>) {
+ const socket = relaySocket('token')
+ socket.connect()
+ const ws = wsMock.instances.at(-1)!
+ ws.open()
+ const counted: string[] = []
+ vi.spyOn(gatewayOf(socket), 'usageCounter').mockImplementation((metric) => { counted.push(metric) })
+ vi.spyOn(gatewayOf(socket).e2ee, 'unwrapDown').mockReturnValue({
+ type: 'session_search', payload: { requestId: 'search-1', query: 'llama', ...payload },
+ })
+ vi.spyOn(gatewayOf(socket).e2ee, 'hasSession').mockReturnValue(true)
+ vi.spyOn(gatewayOf(socket).e2ee, 'sessionRole').mockReturnValue('web')
+ ws.message({ t: 'down', connId: 'conn-1', frame: { type: 'session_search', payload: { __e2e: { v: 1, k: 's', n: 1, ct: 'ciphertext' } } } })
+ await vi.waitFor(() => expect(counted).toContain('search_requests'))
+ await socket.stop()
+ vi.restoreAllMocks()
+ return counted
+ }
+
+ it('counts a phone\'s request as the phone\'s, and the browser\'s as an app\'s as before', async () => {
+ const phone = await startedFor({ usageSurface: 'phone' })
+ expect(phone).toContain('request_phone_search_started')
+ expect(phone).not.toContain('request_app_search_started')
+ expect(await startedFor({})).toContain('request_app_search_started')
+ })
+})
+
describe('machines_changed relay', () => {
// Earlier suites in this file leave their sockets in the mock's list; index 0 must be ours.
beforeEach(() => { wsMock.instances.length = 0 })
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.ts
index 4b982769f..35293df3d 100644
--- a/cli/src/backendSocket.ts
+++ b/cli/src/backendSocket.ts
@@ -1,4 +1,4 @@
-import { productObservation, productUsageIntent, productUsageLaunch, productUsageRequest } from './lib/productUsageSignals.js'
+import { productObservation, productUsageIntent, productUsageLaunch, productUsageRequest, productUsageSource } from './lib/productUsageSignals.js'
import { isLocalOnly, withoutUpdate } from './lib/cardUpdate.js'
import type { PurgeAgentService } from './lib/purgeAgentService.js'
import { MESSAGES_REQUESTS, SHARE_REQUESTS, type Asker, type LocalWindows, type WindowSurface, type BackendNotice, type GatewayEvents, type GatewayPort, type ModelsPort, type RemoteClient, type RemoteRole, type RemoteTransport } from './core/api.js'
@@ -834,7 +834,7 @@ export class BackendSocket {
}
const launchMeasured = productUsageLaunch(type, (frame.payload as { creationId?: unknown } | undefined)?.creationId,
signal => this.toGateway('usage', gateway => gateway.usageLaunch?.(signal)))
- const usageSource = local && connId && this.toolClients.has(connId) ? 'tool' : local || role === 'web' ? 'app' : 'unknown'
+ const usageSource = productUsageSource(local, !!connId && this.toolClients.has(connId), role, frame.payload)
const measured = productUsageRequest(type, (metric) => this.toGateway('usage', (gateway) => gateway.usageCounter?.(metric)), Date.now, usageSource,
(frame.payload as { userAction?: unknown } | undefined)?.userAction === true)
productUsageIntent(type, (frame.payload as { usageIntent?: unknown } | undefined)?.usageIntent,
diff --git a/cli/src/lib/productHealthContract.ts b/cli/src/lib/productHealthContract.ts
index 865626f81..1e53e411f 100644
--- a/cli/src/lib/productHealthContract.ts
+++ b/cli/src/lib/productHealthContract.ts
@@ -1,5 +1,7 @@
/** Fixed health vocabulary. Keep the CLI/backend copies identical. No arbitrary labels. */
-export const HEALTH_SOURCES = ['app', 'tool', 'automatic', 'unknown'] as const
+// `phone`: the phone app's requests, which it marks itself (`usageSurface`) — over the relay it is a
+// remote app client like the browser, and only it can say which one it is.
+export const HEALTH_SOURCES = ['app', 'tool', 'automatic', 'unknown', 'phone'] as const
export const HEALTH_ACTIONS = ['create', 'resume', 'restart', 'model_change', 'history', 'fork', 'close', 'delete',
'search', 'history_page', 'store_list', 'store_install', 'store_update', 'store_remove',
'model_list', 'model_download', 'model_start', 'model_stop', 'browser_open', 'message'] as const
diff --git a/cli/src/lib/productUsageContract.ts b/cli/src/lib/productUsageContract.ts
index fceff8a0f..f8568c358 100644
--- a/cli/src/lib/productUsageContract.ts
+++ b/cli/src/lib/productUsageContract.ts
@@ -44,6 +44,14 @@ export const PRODUCT_USAGE_ONBOARDING_MARKS = ['ui_phone_sign_in_retried', 'ui_p
export const PRODUCT_USAGE_ONBOARDING_METRICS = [...PRODUCT_USAGE_ONBOARDING_MARKS,
...PRODUCT_USAGE_LONG_FLOWS.flatMap(flow => PRODUCT_USAGE_LONG_MEASURES.map(measure => `ui_phone_${flow}_${measure}` as const)),
] as const
+/** The phone's two side pages, counted each time one opens and by how: a sideways swipe on the
+ * terminal (Find from the left, Computers from the right), or a button (Computers' row in Settings,
+ * its link on a long wait at home). Find's key and screen-reader actions are not counted. Which page
+ * and which way, nothing else. */
+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))
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
@@ -86,6 +94,7 @@ export const PRODUCT_USAGE_METRICS = [
.map(measure => `${action}_user_${measure}` as const)),
...PRODUCT_USAGE_UI_METRICS,
...PRODUCT_USAGE_ONBOARDING_METRICS,
+ ...PRODUCT_USAGE_PHONE_SCREEN_METRICS,
] as const
export type ProductUsageMetric = typeof PRODUCT_USAGE_METRICS[number]
export interface ProductUsageReport {
diff --git a/cli/src/lib/productUsageSignals.spec.ts b/cli/src/lib/productUsageSignals.spec.ts
index 6f2af2315..13c14501a 100644
--- a/cli/src/lib/productUsageSignals.spec.ts
+++ b/cli/src/lib/productUsageSignals.spec.ts
@@ -1,5 +1,5 @@
import { expect, it, vi } from 'vitest'
-import { productObservation, productUsageIntent, productUsageLaunch, productUsageRequest } from './productUsageSignals.js'
+import { productObservation, productUsageIntent, productUsageLaunch, productUsageRequest, productUsageSource } from './productUsageSignals.js'
import { PRODUCT_USAGE_FLOWS, PRODUCT_USAGE_METRICS, PRODUCT_USAGE_SETUP_METRICS } from './productUsageContract.js'
import { HEALTH_MEASURES } from './productHealthContract.js'
@@ -15,6 +15,32 @@ it('separates automated polling, tool and app RPCs without inspecting error obje
expect(JSON.stringify(emit.mock.calls)).not.toContain('PRIVATE')
expect(emit.mock.calls.flat()).toContain('request_tool_model_list_ok')
})
+it('tells the phone apart from the browser only by its own word, and never a local or device client', () => {
+ expect(productUsageSource(true, true, null, {})).toBe('tool')
+ expect(productUsageSource(true, false, null, { usageSurface: 'phone' })).toBe('app')
+ expect(productUsageSource(false, false, 'web', { usageSurface: 'phone' })).toBe('phone')
+ expect(productUsageSource(false, false, 'web', {})).toBe('app')
+ expect(productUsageSource(false, false, 'web', undefined)).toBe('app')
+ expect(productUsageSource(false, false, 'web', { usageSurface: 'PRIVATE_LABEL' })).toBe('app')
+ expect(productUsageSource(false, false, 'device', { usageSurface: 'phone' })).toBe('unknown')
+ expect(productUsageSource(false, false, null, { usageSurface: 'phone' })).toBe('unknown')
+})
+it('counts what a person on the phone asked for as the phone\'s, and its polls as automatic', () => {
+ const emit = vi.fn()
+ productUsageRequest('agent_create', emit, Date.now, 'phone')(undefined, 'created', true)
+ productUsageRequest('agent_resume', emit, Date.now, 'phone')('AGENT_BUSY', 'failed', false)
+ productUsageRequest('agent_recent', emit, Date.now, 'phone')(undefined, undefined, false)
+ productUsageRequest('models_list', emit, Date.now, 'phone')(undefined, undefined, false)
+ const names = emit.mock.calls.flat()
+ expect(names).toEqual(expect.arrayContaining(['request_phone_create_started', 'request_phone_create_ok',
+ 'request_phone_resume_error_other', 'request_phone_resume_reason_busy',
+ 'request_automatic_history_ok', 'request_automatic_model_list_ok']))
+ expect(names).not.toContain('request_phone_history_ok')
+ for (const name of names) expect(PRODUCT_USAGE_METRICS).toContain(name)
+ const work = vi.fn()
+ productUsageIntent('message', 'interactive', 'agent', 'phone', work)
+ expect(work).toHaveBeenCalledWith({ id: 'agent', phase: 'work_requested', origin: 'interactive' })
+})
it('requires an explicit composer marker for interactive work; raw terminal input is unclassified', () => {
const emit = vi.fn()
productUsageIntent('terminal_input', 'interactive', 'agent', 'app', emit)
diff --git a/cli/src/lib/productUsageSignals.ts b/cli/src/lib/productUsageSignals.ts
index cb194e9c1..7cac2668c 100644
--- a/cli/src/lib/productUsageSignals.ts
+++ b/cli/src/lib/productUsageSignals.ts
@@ -62,6 +62,16 @@ export function productUsageLaunch(type: string, id: unknown, emit: (signal: Pro
}
}
+/** Who sent a request, as the counters name it: a tool on this computer, an app here, or a remote app
+ * client — the browser, or the phone. Over the relay both are the same E2EE `web` role, so the phone says
+ * which it is in the payload (`usageSurface: 'phone'`, as it says `userAction`); a remote frame with no
+ * such word is the browser's or an older phone's, counted as `app` as before. */
+export function productUsageSource(local: boolean, tool: boolean, role: string | null, payload: unknown): HealthSource {
+ if (local) return tool ? 'tool' : 'app'
+ if (role !== 'web') return 'unknown'
+ return (payload as { usageSurface?: unknown } | undefined)?.usageSurface === 'phone' ? 'phone' : 'app'
+}
+
/** Reduce an RPC at its existing boundary. Only fixed counter names leave this helper.
* No request, reply, error message, path, agent name or identifier is handed to the collector.
* A pending durable launch is an acknowledgement, never a successful launch. Status polling is
@@ -75,7 +85,10 @@ export function productUsageRequest(type: string, emit: (metric: ProductUsageMet
if (!action) return unmeasured
const started = now()
let answered = false
- const origin = source === 'app' && ['history', 'history_page', 'store_list', 'model_list'].includes(action) ? 'automatic' : source
+ // A fixed poll is `automatic` whichever app makes it, the phone's included: its own source is for what a
+ // person on it asked for.
+ const origin = (source === 'app' || source === 'phone') && ['history', 'history_page', 'store_list', 'model_list'].includes(action)
+ ? 'automatic' : source
const count = (measure: string) => { if (action && action !== 'message') { try { emit(`${action}_${measure}` as ProductUsageMetric) } catch { /* Optional measurement. */ } } }
const detail = (measure: string) => { if (!source) return; try { emit(`request_${origin}_${action}_${measure}` as ProductUsageMetric) } catch { /* Optional measurement. */ } }
count('requests'); detail('started')
@@ -108,7 +121,8 @@ export function productUsageRequest(type: string, emit: (metric: ProductUsageMet
export function productUsageIntent(type: string, intent: unknown, agent: unknown, source: HealthSource, emit: (signal: ProductUsageLaunchSignal) => void): void {
if (type !== 'message' || typeof agent !== 'string' || !agent || agent.length > 256) return
try {
- if (source === 'app' && intent === 'interactive') emit({ id: agent, phase: 'work_requested', origin: 'interactive' })
+ // A person's composer is interactive work on the phone as in any app.
+ if ((source === 'app' || source === 'phone') && intent === 'interactive') emit({ id: agent, phase: 'work_requested', origin: 'interactive' })
else if (source === 'tool') emit({ id: agent, phase: 'work_requested', origin: 'tool' })
} catch { /* Optional observation cannot block a message. */ }
}
diff --git a/mobile/lib/measurement/product_measurement.dart b/mobile/lib/measurement/product_measurement.dart
index 64bca271a..a970c22a3 100644
--- a/mobile/lib/measurement/product_measurement.dart
+++ b/mobile/lib/measurement/product_measurement.dart
@@ -3,6 +3,8 @@ import 'dart:math';
import 'package:flutter/foundation.dart';
+import '../core/local_key_value_store.dart';
+
/// Mirrors `PRODUCT_USAGE_FLOWS` in backend/src/types/productUsage.ts; a wire name the backend
/// does not list rejects the whole report. Everything up to [signIn] can happen before an account.
enum ProductFlow {
@@ -43,13 +45,22 @@ enum ProductFlow {
enum ProductOutcome { ok, failed, cancelled, unknown }
+/// Mirrors `PRODUCT_USAGE_PHONE_SCREENS` in backend/src/types/productUsage.ts: the phone's two side
+/// pages, Find and Computers.
+enum PhoneScreen { find, computers }
+
+/// Mirrors `PRODUCT_USAGE_SCREEN_OPENINGS`: a sideways swipe on the terminal, or anything the person
+/// pressed instead — a key, a row, a screen reader's action.
+enum ScreenOpening { swipe, button }
+
typedef ProductReportRequest = Future<Map<String, dynamic>> Function(
Map<String, dynamic> report,
);
typedef ProductChoiceRequest = Future<Map<String, dynamic>> Function();
/// Fixed counters only: no event log, identifiers, errors, request/response objects or content.
-/// Nothing is saved. Signed-out sharing is an explicit choice for this app session; a close/crash can lose queued counts.
+/// Counters stay in RAM; a close/crash can lose queued counts. The one thing kept is the signed-out
+/// choice, in [setupStorage]: on by default, as the desktop's is, until it is turned off.
/// Requests and retries are serialized and never awaited by a product action.
class ProductMeasurement extends ChangeNotifier {
ProductMeasurement({
@@ -58,10 +69,11 @@ class ProductMeasurement extends ChangeNotifier {
DateTime Function()? now,
String Function()? receipt,
this.automatic = true,
+ this.setupStorage,
}) : assert(const ['desktop', 'phone', 'web'].contains(surface)),
_now = now ?? DateTime.now,
_receipt = receipt ?? newProductReceipt {
- choiceLoaded = true;
+ setupChoiceReady = _loadSetupChoice();
}
final String surface;
@@ -71,6 +83,34 @@ class ProductMeasurement extends ChangeNotifier {
final String Function() _receipt;
bool signedOutSharing = false, choiceLoaded = false;
+ /// Where the signed-out choice is kept, across launches. With none — a test, the sample — there is
+ /// nowhere to keep an opt-out, so sharing starts off and is only ever an explicit choice.
+ final LocalKeyValueStore? setupStorage;
+ static const setupPreferenceKey = 'product_setup_sharing';
+
+ /// Kept for an opt-out made signed out that the account has not confirmed yet — the desktop's own
+ /// value, so the next sign-in turns the account's sharing off as well.
+ static const pendingSetupOptOut =
+ '{"enabled":false,"accountOptOutPending":true}';
+
+ /// Done once the kept choice is read: until then nothing is counted signed out.
+ late final Future<void> setupChoiceReady;
+
+ /// Done once the latest choice is written.
+ Future<void> get setupChoiceSaved => _setupSave ?? Future<void>.value();
+ Future<void>? _setupSave;
+ String? _persistedSetupChoice;
+ bool _accountOptOutPending = false;
+ int _setupChoiceGeneration = 0;
+
+ /// Turned off signed out, and not yet carried to the account: the next account read asks it to
+ /// turn sharing off (`AppNotifier.productUsageSettings`), and nothing is counted for it until then.
+ bool get accountOptOutPending => _sharingByDefault && _accountOptOutPending;
+
+ /// Signed-out reports say which kind they are: `sharing: 'default'` where sharing starts on (as on
+ /// the desktop — not consent), `consent: true` where it was only ever ticked.
+ bool get _sharingByDefault => setupStorage != null && surface != 'web';
+
/// Which build reports: `{surface, release, platform, channel}`, as backend
/// `ProductUsageContext` takes it. Sent with the account's reports only, so the totals split by
/// release and by platform; a `development` build's reports are not kept. Null: no context.
@@ -91,7 +131,11 @@ class ProductMeasurement extends ChangeNotifier {
final _setup = <ProductFlow, void Function(ProductOutcome)>{};
final _setupFacts = <ProductFlow, String>{};
- bool get sharing => _account != null && _enabled == true;
+ bool get sharing =>
+ _account != null &&
+ _enabled == true &&
+ (!_sharingByDefault || choiceLoaded) &&
+ !accountOptOutPending;
/// Moves with every account or choice change: an observation begun before one never counts after.
int get observationGeneration => _accountEpoch;
@@ -103,16 +147,72 @@ class ProductMeasurement extends ChangeNotifier {
signedOutSharing &&
(_account == null || _enabled == true);
- Future<void> setSignedOutSharing(bool enabled) async {
- _guestEpoch++;
- signedOutSharing = enabled;
+ /// The kept choice: on unless it was turned off. One that cannot be read is an opt-out still to
+ /// carry to the account, as on the desktop — it must never come back on for an unreadable file.
+ Future<void> _loadSetupChoice() async {
+ final storage = setupStorage;
+ if (storage == null) {
+ choiceLoaded = true;
+ return;
+ }
+ final generation = _setupChoiceGeneration;
+ String? value;
+ try {
+ value = await storage.read(setupPreferenceKey);
+ } catch (_) {
+ value = pendingSetupOptOut;
+ }
+ // Ticked or unticked meanwhile, or the account answered: that word stands.
+ if (_disposed || generation != _setupChoiceGeneration) return;
+ _persistedSetupChoice = value;
+ _accountOptOutPending =
+ value != null && value != 'true' && value != 'false';
+ signedOutSharing = surface != 'web' && (value == null || value == 'true');
choiceLoaded = true;
- _clear('setup');
- _setup.clear();
- if (enabled) _observeSetupFacts();
+ if (signedOutSharing) _observeSetupFacts();
notifyListeners();
}
+ /// The signed-out choice. [fromAccount]: the account's own confirmed choice, remembered for the next
+ /// signed-out launch — not an opt-out to carry to it.
+ Future<void> setSignedOutSharing(
+ bool enabled, {
+ bool fromAccount = false,
+ }) async {
+ _setupChoiceGeneration++;
+ _accountOptOutPending = _sharingByDefault && !enabled && !fromAccount;
+ if (accountOptOutPending) {
+ _accountEpoch++;
+ _clear('ui');
+ }
+ if (signedOutSharing != enabled || !choiceLoaded) {
+ _guestEpoch++;
+ signedOutSharing = enabled;
+ choiceLoaded = true;
+ _clear('setup');
+ _setup.clear();
+ if (enabled) _observeSetupFacts();
+ notifyListeners();
+ }
+ final storage = setupStorage;
+ if (storage == null) return;
+ final value = accountOptOutPending
+ ? pendingSetupOptOut
+ : enabled.toString();
+ // One write at a time, so an older one cannot land after a newer off. Best effort: a choice that
+ // is not kept still holds for this run.
+ final previous = _setupSave;
+ final saving = () async {
+ if (previous != null) await previous;
+ try {
+ await storage.write(setupPreferenceKey, value);
+ _persistedSetupChoice = value;
+ } catch (_) {}
+ }();
+ _setupSave = saving;
+ await saving;
+ }
+
/// The scope is RAM-only and never serialized. A sign-out or account change discards its queue.
void account(
Object? scope, {
@@ -131,19 +231,34 @@ class ProductMeasurement extends ChangeNotifier {
_schedule();
}
- /// A saved switch applies immediately in this app, even while a report is in flight.
- void savedChoice(Map<String, dynamic> value) {
+ /// A saved switch applies immediately in this app, even while a report is in flight. [explicit]: the
+ /// person set it just now (Settings ▸ Privacy), which also settles an opt-out still to carry.
+ void savedChoice(Map<String, dynamic> value, {bool explicit = false}) {
final enabled = value['enabled'], revision = value['revision'];
if (enabled is! bool || revision is! int || revision < 0) {
_enabled = null;
return;
}
+ // A default-on answer before this phone's own choice is read waits for it: it may be an opt-out.
+ if (_sharingByDefault && !choiceLoaded && enabled && !explicit) {
+ _enabled = null;
+ return;
+ }
if (revision != _revision || !enabled) {
_accountEpoch++;
_clear('ui');
}
_revision = revision;
_enabled = enabled;
+ if (_sharingByDefault &&
+ (!accountOptOutPending || !enabled || explicit) &&
+ (signedOutSharing != enabled ||
+ !choiceLoaded ||
+ accountOptOutPending ||
+ _persistedSetupChoice != enabled.toString())) {
+ // The account's confirmed choice is the phone's next signed-out one, as on the desktop.
+ unawaited(setSignedOutSharing(enabled, fromAccount: true));
+ }
if (!enabled) {
_guestEpoch++;
signedOutSharing = false;
@@ -248,6 +363,14 @@ class ProductMeasurement extends ChangeNotifier {
_count('ui', day, 'ui_${surface}_${flow.wire}_$measure');
}
+ /// [screen] opened, by [how] — `ui_phone_screen_<screen>_<how>`, which the backend names for the phone
+ /// alone. For an account that shares; which page and which way, nothing more.
+ void screenOpened(PhoneScreen screen, ScreenOpening how) {
+ if (_disposed || !sharing || surface != 'phone') return;
+ final day = _now().toUtc().toIso8601String().substring(0, 10);
+ _count('ui', day, 'ui_${surface}_screen_${screen.name}_${how.name}');
+ }
+
/// One attempt counted under several flows at once — `sign_in` and the button that started it.
void Function(ProductOutcome) beginEach(List<ProductFlow> flows) {
final finishers = [for (final flow in flows) begin(flow)];
@@ -372,7 +495,12 @@ class ProductMeasurement extends ChangeNotifier {
'id': _receipt(),
'day': key.split(':')[1],
'counters': batch,
- if (channel == 'setup') 'consent': true else 'revision': _revision,
+ if (channel == 'setup' && _sharingByDefault)
+ 'sharing': 'default'
+ else if (channel == 'setup')
+ 'consent': true
+ else
+ 'revision': _revision,
if (channel == 'ui' && context != null) 'context': context,
};
_pending[channel] = report;
diff --git a/mobile/lib/measurement/setup_usage_choice.dart b/mobile/lib/measurement/setup_usage_choice.dart
index b08755b5b..72c337b46 100644
--- a/mobile/lib/measurement/setup_usage_choice.dart
+++ b/mobile/lib/measurement/setup_usage_choice.dart
@@ -19,7 +19,7 @@ class SetupUsageChoice extends StatelessWidget {
static const title = 'Share setup and sign-in counts';
static const detail =
- 'Optional for this app session. Help us find setup problems without sharing account details, prompts, or files.';
+ 'On unless you turn it off; off also turns it off for your account when you sign in. Helps us find setup problems without sharing account details, prompts, or files.';
@override
Widget build(BuildContext context) => ListenableBuilder(
diff --git a/mobile/lib/phone/agent_home.dart b/mobile/lib/phone/agent_home.dart
index 5c3897e9f..9a2dfb0b8 100644
--- a/mobile/lib/phone/agent_home.dart
+++ b/mobile/lib/phone/agent_home.dart
@@ -1096,13 +1096,7 @@ class _AgentHomeState extends State<AgentHome>
key: const ValueKey('home-wait-computers'),
label: 'See your computers ›',
size: TtySize.meta,
- onPressed: () => unawaited(
- Navigator.of(context).push(
- phoneRoute(
- (_) => MachinesTab(notifier: notifier, large: false),
- ),
- ),
- ),
+ onPressed: () => _seeComputers(context, notifier),
),
)
: null,
@@ -1635,6 +1629,18 @@ class _AgentHomeLoading extends StatelessWidget {
}
}
+/// "See your computers ›" under a wait: Computers over the wait, counted as asked for by a button.
+void _seeComputers(BuildContext context, AppNotifier notifier) {
+ notifier.productMeasurement.screenOpened(
+ PhoneScreen.computers,
+ ScreenOpening.button,
+ );
+ unawaited(
+ Navigator.of(context)
+ .push(phoneRoute((_) => MachinesTab(notifier: notifier, large: false))),
+ );
+}
+
/// Under a wait that has gone on: what is true, and the computers — each with what it needs, a
/// password form behind a locked one — over the wait rather than in place of it, so back returns
/// to it and a wait that ends meanwhile still lands where it would have.
@@ -1659,13 +1665,7 @@ class _SlowWaitHint extends StatelessWidget {
TtyTextButton(
key: const ValueKey('home-wait-computers'),
label: 'See your computers ›',
- onPressed: () => unawaited(
- Navigator.of(context).push(
- phoneRoute(
- (_) => MachinesTab(notifier: notifier, large: false),
- ),
- ),
- ),
+ onPressed: () => _seeComputers(context, notifier),
),
],
),
diff --git a/mobile/lib/phone/privacy_shared_fields.dart b/mobile/lib/phone/privacy_shared_fields.dart
index e4962161b..05d44b4c7 100644
--- a/mobile/lib/phone/privacy_shared_fields.dart
+++ b/mobile/lib/phone/privacy_shared_fields.dart
@@ -48,6 +48,12 @@ const List<_Field> _sent = [
'answering the notification prompt: outcomes and duration buckets; '
'whether a sign-in that went through came after a failed try or on another button.',
),
+ (
+ label: 'This phone',
+ text:
+ 'How often Find and Computers are opened, by a swipe or a button; '
+ 'request outcomes counted as this phone\'s rather than any app\'s.',
+ ),
(label: 'Feedback', text: 'Only your selected task outcome or reason.'),
(
label: 'Older apps',
diff --git a/mobile/lib/phone/settings_page.dart b/mobile/lib/phone/settings_page.dart
index b41ef20b6..ecdb815fc 100644
--- a/mobile/lib/phone/settings_page.dart
+++ b/mobile/lib/phone/settings_page.dart
@@ -11,6 +11,7 @@ import 'package:harness_mobile/demo/sample_mode.dart'
show SampleMode, SampleSession, openSampleMode;
import 'package:harness_mobile/core/device_name.dart';
import 'package:harness_mobile/notify/system_notices.dart';
+import 'package:harness_mobile/measurement/product_measurement.dart';
import 'package:harness_mobile/shared/widgets/app_dialog.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/theme/appearance_prefs_store.dart';
@@ -172,8 +173,10 @@ class _Body extends StatelessWidget {
if (_sample(context) == null)
SettingsRow(title: 'Privacy', onTap: () => Navigator.of(context).push(
phoneRoute((_) => PrivacyPage(request: ({bool? enabled}) async {
- final value = await notifier.api.productUsageSettings(enabled: enabled);
- notifier.productMeasurement.savedChoice(value);
+ final value = await notifier.productUsageSettings(enabled: enabled);
+ // Set here by the person: it also settles an opt-out made before sign-in.
+ notifier.productMeasurement.savedChoice(value, explicit: enabled != null);
+ await notifier.productMeasurement.setupChoiceSaved;
return value;
}, feedback: notifier.api.productUsageFeedback)),
)),
@@ -183,15 +186,21 @@ class _Body extends StatelessWidget {
// it, take it off the account (`machine_actions.dart`).
SettingsRow(
title: 'Computers',
- onTap: () => Navigator.of(context).push(
- phoneRoute(
- (_) => MachinesTab(
- notifier: notifier,
- large: false,
- fromSettings: true,
+ onTap: () {
+ notifier.productMeasurement.screenOpened(
+ PhoneScreen.computers,
+ ScreenOpening.button,
+ );
+ Navigator.of(context).push(
+ phoneRoute(
+ (_) => MachinesTab(
+ notifier: notifier,
+ large: false,
+ fromSettings: true,
+ ),
),
- ),
- ),
+ );
+ },
),
// Which computer's tabs this phone shows — the desktop's Profiles. Beside Computers: it
// is a choice among them, and changes nothing on any of them. Only once there IS a choice
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index b6f497988..3276f6b98 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -1386,6 +1386,11 @@ class _TerminalPageState extends State<TerminalPage>
_swipingFind = false;
if (velocity >= _swipeFlick ||
(velocity > -_swipeFlick && _searchOpen.value > 0.3)) {
+ // Counted once it stays: a swipe that lets Find go back opened nothing.
+ widget.notifier.productMeasurement.screenOpened(
+ PhoneScreen.find,
+ ScreenOpening.swipe,
+ );
_searchOpen.forward();
} else {
_closeSearch();
@@ -1393,6 +1398,11 @@ class _TerminalPageState extends State<TerminalPage>
return;
}
if (_swipedLeft >= _computersReach || velocity <= -_swipeFlick) {
+ // The swipe alone is counted here: Find's key and a screen reader's actions are not.
+ widget.notifier.productMeasurement.screenOpened(
+ PhoneScreen.computers,
+ ScreenOpening.swipe,
+ );
unawaited(_openComputers());
}
}
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index ba17865ec..324f58e92 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -1135,6 +1135,9 @@ class AppNotifier extends ChangeNotifier {
ProductMeasurement(
surface: kIsWeb ? 'web' : 'phone',
automatic: !kUnderTest,
+ // Signed-out counts start on, as the desktop's do, where an opt-out can be kept: the app's
+ // own store. A test or the sample (`demo/`) has none, and stays off.
+ setupStorage: paneLayoutStore?.storage,
sendSetup: (report) =>
sendSetupMeasurement(this.config.apiBaseUrl, report),
);
@@ -1182,7 +1185,7 @@ class AppNotifier extends ChangeNotifier {
: null;
productMeasurement.account(
scope,
- choice: () => api.productUsageSettings(),
+ choice: () => productUsageSettings(),
send: api.productUsageReport,
);
launchMeasurement?.account(
@@ -1196,6 +1199,17 @@ class AppNotifier extends ChangeNotifier {
}
}
+ /// The account's product-usage choice — or, while an opt-out made before sign-in waits to be
+ /// carried to the account, set off: the desktop's rule. Pending until the server confirms it, so a
+ /// failed request or a default-on answer never quietly restores sharing.
+ Future<Map<String, dynamic>> productUsageSettings({bool? enabled}) async {
+ await productMeasurement.setupChoiceReady;
+ return api.productUsageSettings(
+ enabled:
+ enabled ?? (productMeasurement.accountOptOutPending ? false : null),
+ );
+ }
+
// Connection keys already belong to the app. Only fixed outcomes reach measurement, never the key.
void _measureConnection(
String key,
diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dart
index 1831d2a90..56ff75082 100644
--- a/mobile/lib/ws/ws_conn.dart
+++ b/mobile/lib/ws/ws_conn.dart
@@ -888,6 +888,36 @@ class WsConn {
@visibleForTesting
static bool worthLogging(String type) => !_unlogged.contains(type);
+ /// The requests a machine's daemon counts by who sent them — `actions` and `message` in
+ /// cli/src/lib/productUsageSignals.ts. Over the relay the phone is a remote app client like the
+ /// browser, so these carry `usageSurface: 'phone'` (as a model list a person opened carries
+ /// `userAction`) and are counted as the phone's. Nothing else gets the word: not the E2EE handshake,
+ /// not the relay's own frames. A daemon from before it reads past it.
+ @visibleForTesting
+ static const usageMeasuredRequests = {
+ 'agent_create',
+ 'agent_resume',
+ 'agent_restart',
+ 'agent_retarget',
+ 'agent_recent',
+ 'agent_fork',
+ 'agent_close',
+ 'agent_delete',
+ 'session_search',
+ 'session_tail',
+ 'dsh_list',
+ 'dsh_install',
+ 'dsh_update',
+ 'dsh_remove',
+ 'models_list',
+ 'grid_models_list',
+ 'grid_fleet_model_download',
+ 'grid_fleet_model_start',
+ 'grid_fleet_model_stop',
+ 'browser_open',
+ 'message',
+ };
+
Future<Map<String, dynamic>> request(
String type, {
Map<String, dynamic> payload = const {},
@@ -1061,6 +1091,11 @@ class WsConn {
final type = frame['type'] as String;
var payload = (frame['payload'] as Map<String, dynamic>?) ?? {};
if (onOutgoing != null) payload = await onOutgoing!(type, payload);
+ // Every JSON frame goes out through here — a request, a terminal's `message`, one held in the
+ // queue across a redial — so this is the one place the word is added.
+ if (usageMeasuredRequests.contains(type)) {
+ payload = {...payload, 'usageSurface': 'phone'};
+ }
final channel = _channel;
if (channel == null) throw StateError('WS is not connected');
final out = <String, dynamic>{'type': type, 'payload': payload};
diff --git a/mobile/test/app_state_flow_measurement_test.dart b/mobile/test/app_state_flow_measurement_test.dart
index 831bd5738..1c4e55def 100644
--- a/mobile/test/app_state_flow_measurement_test.dart
+++ b/mobile/test/app_state_flow_measurement_test.dart
@@ -3,6 +3,7 @@ import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/measurement/product_measurement.dart';
import 'viewer_app_fixture.dart';
+import 'voice_fakes.dart' show MemoryKeyValueStore;
/// The flows the phone counts as the desktop does — its dials, a stopped harness resumed — as the
/// app itself reports them, through the account's own sharing.
@@ -169,4 +170,51 @@ void main() {
},
);
});
+
+ group('the signed-out choice, carried to the account as on the desktop', () {
+ String? kept(MemoryKeyValueStore storage) =>
+ storage.values[ProductMeasurement.setupPreferenceKey];
+
+ test(
+ 'an opt-out made signed out turns the account off, asked once',
+ () async {
+ final storage = MemoryKeyValueStore()
+ ..values[ProductMeasurement.setupPreferenceKey] =
+ ProductMeasurement.pendingSetupOptOut;
+ final rig = await signedInWith({'m': []}, storage: storage);
+ addTearDown(rig.app.dispose);
+ final usage = rig.app.productMeasurement;
+
+ await usage.flush();
+ await usage.setupChoiceSaved;
+ expect(rig.api.usageChoiceAsks, [false]);
+ expect(usage.accountOptOutPending, isFalse);
+ expect(usage.sharing, isFalse);
+ expect(kept(storage), 'false');
+
+ await usage.flush();
+ expect(rig.api.usageChoiceAsks, [
+ false,
+ null,
+ ], reason: 'then only read');
+ },
+ );
+
+ test(
+ 'left on, the account keeps its own choice, and the phone remembers it',
+ () async {
+ final storage = MemoryKeyValueStore();
+ final rig = await signedInWith({'m': []}, storage: storage);
+ addTearDown(rig.app.dispose);
+ rig.api.usageChoice = {'enabled': false, 'revision': 2};
+ final usage = rig.app.productMeasurement;
+
+ await usage.flush();
+ await usage.setupChoiceSaved;
+ expect(rig.api.usageChoiceAsks, [null]);
+ expect(usage.signedOutSharing, isFalse);
+ expect(kept(storage), 'false');
+ },
+ );
+ });
}
diff --git a/mobile/test/focus_swipes_test.dart b/mobile/test/focus_swipes_test.dart
index bc302c215..075889edc 100644
--- a/mobile/test/focus_swipes_test.dart
+++ b/mobile/test/focus_swipes_test.dart
@@ -3,6 +3,7 @@ import 'package:flutter/rendering.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/machines_tab.dart';
import 'package:harness_mobile/phone/terminal_page.dart';
import 'package:harness_mobile/phone/terminal_search.dart';
@@ -22,12 +23,15 @@ void main() {
late VoiceInputController voice;
late ValueNotifier<String> language;
late List<Map<String, dynamic>> resizes;
+ late _Openings usage;
setUp(() {
+ usage = _Openings();
notifier = AppNotifier(
config: AppConfig.dev,
authSession: AuthSession(),
configStore: null,
+ productMeasurement: usage,
);
resizes = [];
session = TerminalSession(
@@ -89,6 +93,7 @@ void main() {
await tester.pump(const Duration(milliseconds: 400));
expect(find.byType(TerminalSearchOverlay), findsOneWidget);
+ expect(usage.opened, [(PhoneScreen.find, ScreenOpening.swipe)]);
});
testWidgets('a short swipe right lets Find go back', (tester) async {
@@ -103,6 +108,7 @@ void main() {
await tester.pump(const Duration(milliseconds: 400));
expect(find.byType(TerminalSearchOverlay), findsNothing);
+ expect(usage.opened, isEmpty, reason: 'Find went back: nothing opened');
});
testWidgets('a tap on the agent\'s name opens Find', (tester) async {
@@ -144,6 +150,7 @@ void main() {
await tester.drag(find.byType(TerminalView), const Offset(-200, 0));
expect(pushed, hasLength(1));
+ expect(usage.opened, [(PhoneScreen.computers, ScreenOpening.swipe)]);
expect(find.byType(TerminalSearchOverlay), findsNothing);
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
@@ -184,6 +191,7 @@ void main() {
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
expect(find.byType(TerminalSearchOverlay), findsOneWidget);
+ expect(usage.opened, isEmpty, reason: 'only a swipe is counted');
handle.dispose();
});
@@ -201,6 +209,7 @@ void main() {
),
);
expect(pushed, hasLength(1));
+ expect(usage.opened, isEmpty, reason: 'only a swipe is counted');
await tester.pump();
await tester.pump(const Duration(milliseconds: 400));
expect(find.byType(MachinesTab), findsOneWidget);
@@ -218,3 +227,15 @@ class _Pushes extends NavigatorObserver {
void didPush(Route<dynamic> route, Route<dynamic>? previousRoute) =>
pushed.add(route);
}
+
+/// Which side page opened and how, recorded in place of being counted.
+class _Openings extends ProductMeasurement {
+ _Openings()
+ : super(surface: 'phone', automatic: false, sendSetup: (_) async => {});
+
+ final opened = <(PhoneScreen, ScreenOpening)>[];
+
+ @override
+ void screenOpened(PhoneScreen screen, ScreenOpening how) =>
+ opened.add((screen, how));
+}
diff --git a/mobile/test/phone_edge/edge_fixture.dart b/mobile/test/phone_edge/edge_fixture.dart
index 44938463e..090c034c5 100644
--- a/mobile/test/phone_edge/edge_fixture.dart
+++ b/mobile/test/phone_edge/edge_fixture.dart
@@ -11,6 +11,7 @@ import 'package:harness_mobile/auth/peer_link_client.dart';
import 'package:harness_mobile/core/config.dart';
import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/demo/sample_mode.dart';
+import 'package:harness_mobile/measurement/product_measurement.dart';
import 'package:harness_mobile/phone/voice_input_controller.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart' as grid;
import 'package:harness_mobile/state/app_state.dart';
@@ -229,12 +230,14 @@ AppNotifier edgeApp({
EdgeConn? conn,
bool noMachines = false,
EdgeLinks? links,
+ ProductMeasurement? productMeasurement,
}) {
final session = AuthSession();
final app = AppNotifier(
config: AppConfig.dev,
authSession: session,
configStore: null,
+ productMeasurement: productMeasurement,
connectionForTest: (_) => conn ?? EdgeConn(),
peerLinks: links ?? EdgeLinks(),
viewer: ViewerServices(
@@ -262,6 +265,18 @@ AppNotifier edgeApp({
return app;
}
+/// Which of the phone's side pages opened and how, recorded in place of being counted.
+class RecordedOpenings extends ProductMeasurement {
+ RecordedOpenings()
+ : super(surface: 'phone', automatic: false, sendSetup: (_) async => {});
+
+ final opened = <(PhoneScreen, ScreenOpening)>[];
+
+ @override
+ void screenOpened(PhoneScreen screen, ScreenOpening how) =>
+ opened.add((screen, how));
+}
+
/// The control plane, answered from the app's own list — never the local CLI's HTTP port, which
/// is where a real [ApiClient] outside a viewer build sends everything.
class EdgeApi extends ApiClient {
diff --git a/mobile/test/phone_edge/home_wait_test.dart b/mobile/test/phone_edge/home_wait_test.dart
new file mode 100644
index 000000000..9c703d37e
--- /dev/null
+++ b/mobile/test/phone_edge/home_wait_test.dart
@@ -0,0 +1,50 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/measurement/product_measurement.dart';
+import 'package:harness_mobile/phone/agent_home.dart';
+import 'package:harness_mobile/phone/machines_tab.dart';
+import 'package:harness_mobile/phone/phone_shell_scope.dart';
+import 'package:harness_mobile/state/app_state.dart';
+
+import 'edge_fixture.dart';
+
+/// A launch wait that goes on: the computers are offered, and opening them that way is counted.
+void main() {
+ testWidgets(
+ 'a long wait offers the computers, counted as opened by a button',
+ (tester) async {
+ setPhone(tester, largePhone);
+ final usage = RecordedOpenings();
+ // The computer is up but its sessions never arrive: home waits on them.
+ final app = edgeApp(
+ agents: const [],
+ load: AgentLoadStatus.loading,
+ productMeasurement: usage,
+ );
+ addTearDown(app.dispose);
+ await tester.pumpWidget(
+ phoneApp(
+ PhoneShellScope(
+ onMachineLinked: (_) {},
+ onOpenAgent: (_, _) {},
+ child: AgentHome(notifier: app),
+ ),
+ ),
+ );
+ await frames(tester);
+ expect(find.byKey(const ValueKey('home-wait-computers')), findsNothing);
+
+ await tester.pump(const Duration(seconds: 16));
+ await frames(tester);
+ await tapInView(
+ tester,
+ find.byKey(const ValueKey('home-wait-computers')),
+ );
+ await frames(tester, count: 6);
+
+ expect(find.byType(MachinesTab), findsOneWidget);
+ expect(usage.opened, [(PhoneScreen.computers, ScreenOpening.button)]);
+ await unmount(tester);
+ },
+ );
+}
diff --git a/mobile/test/phone_edge/settings_behavior_test.dart b/mobile/test/phone_edge/settings_behavior_test.dart
index 330660830..a3f6d5831 100644
--- a/mobile/test/phone_edge/settings_behavior_test.dart
+++ b/mobile/test/phone_edge/settings_behavior_test.dart
@@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/demo/sample_mode.dart';
+import 'package:harness_mobile/measurement/product_measurement.dart';
import 'package:harness_mobile/phone/machines_tab.dart';
import 'package:harness_mobile/phone/settings_page.dart';
import 'package:harness_mobile/phone/welcome/how_it_works.dart';
@@ -31,9 +32,10 @@ void main() {
bool large = true,
bool sample = false,
CurrentUserProfile? user,
+ ProductMeasurement? usage,
}) async {
setPhone(tester, largePhone);
- final app = edgeApp();
+ final app = edgeApp(productMeasurement: usage);
app.currentUser =
user ??
const CurrentUserProfile(
@@ -109,10 +111,12 @@ void main() {
testWidgets('Computers and How Harness works open their pages', (
tester,
) async {
- final app = await openSettings(tester, large: false);
+ final usage = RecordedOpenings();
+ final app = await openSettings(tester, large: false, usage: usage);
await tapInView(tester, find.text('Computers'));
await frames(tester, count: 6);
expect(find.byType(MachinesTab), findsOneWidget);
+ expect(usage.opened, [(PhoneScreen.computers, ScreenOpening.button)]);
await tester.binding.handlePopRoute();
await frames(tester, count: 6);
diff --git a/mobile/test/product_measurement_test.dart b/mobile/test/product_measurement_test.dart
index 6e480a004..d728ca3bd 100644
--- a/mobile/test/product_measurement_test.dart
+++ b/mobile/test/product_measurement_test.dart
@@ -1,10 +1,14 @@
import 'dart:async';
import 'dart:convert';
+import 'dart:io';
import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/core/local_key_value_store.dart';
import 'package:harness_mobile/measurement/product_measurement.dart';
+import 'voice_fakes.dart' show MemoryKeyValueStore;
+
void main() {
late ProductMeasurement usage;
late List<Map<String, dynamic>> setup, reports;
@@ -199,4 +203,277 @@ void main() {
expect(setup, isEmpty);
},
);
+
+ group('signed-out sharing kept on this phone, as on the desktop', () {
+ late MemoryKeyValueStore store;
+ final opened = <ProductMeasurement>[];
+ setUp(() => store = MemoryKeyValueStore());
+ tearDown(() {
+ for (final usage in opened) {
+ usage.dispose();
+ }
+ opened.clear();
+ });
+
+ String? kept() => store.values[ProductMeasurement.setupPreferenceKey];
+
+ ProductMeasurement launch({LocalKeyValueStore? keeping}) {
+ final usage = ProductMeasurement(
+ surface: 'phone',
+ automatic: false,
+ now: () => now,
+ setupStorage: keeping,
+ sendSetup: (r) async {
+ setup.add(jsonDecode(jsonEncode(r)));
+ return {'accepted': true};
+ },
+ );
+ opened.add(usage);
+ return usage;
+ }
+
+ /// Signed in, the account answering [answer] to every read.
+ Future<void> signIn(
+ ProductMeasurement usage,
+ Map<String, dynamic> Function() answer,
+ ) async {
+ usage.account(
+ 'PRIVATE_ACCOUNT',
+ choice: () async => answer(),
+ send: (r) async {
+ reports.add(jsonDecode(jsonEncode(r)));
+ return {'accepted': true};
+ },
+ );
+ await usage.flush();
+ await usage.setupChoiceSaved;
+ }
+
+ test('starts on, and says so rather than consent', () async {
+ final phone = launch(keeping: store);
+ expect(
+ phone.choiceLoaded,
+ isFalse,
+ reason: 'nothing counted before it is read',
+ );
+ await phone.setupChoiceReady;
+ expect(phone.signedOutSharing, isTrue);
+ phone.begin(ProductFlow.signIn)(ProductOutcome.ok);
+ await phone.flush();
+ expect(setup.single['sharing'], 'default');
+ expect(setup.single.containsKey('consent'), isFalse);
+ expect(
+ (setup.single['counters'] as Map).keys,
+ everyElement(startsWith('setup_phone_sign_in_')),
+ );
+ });
+
+ test(
+ 'turned off signed out, it is kept as an opt-out to carry to the account',
+ () async {
+ final first = launch(keeping: store);
+ await first.setupChoiceReady;
+ await first.setSignedOutSharing(false);
+ expect(kept(), ProductMeasurement.pendingSetupOptOut);
+ expect(first.accountOptOutPending, isTrue);
+
+ final second = launch(keeping: store);
+ await second.setupChoiceReady;
+ expect(second.signedOutSharing, isFalse);
+ expect(second.accountOptOutPending, isTrue);
+ second.begin(ProductFlow.signIn)(ProductOutcome.ok);
+ await second.flush();
+ expect(setup, isEmpty);
+ },
+ );
+
+ test('until the account confirms it is off, nothing is counted for the account', () async {
+ final phone = launch(keeping: store);
+ await phone.setupChoiceReady;
+ await phone.setSignedOutSharing(false);
+ // An account that still reads on (the request to turn it off has not landed).
+ await signIn(phone, () => {'enabled': true, 'revision': 0});
+ expect(phone.sharing, isFalse);
+ expect(phone.accountOptOutPending, isTrue);
+ phone.begin(ProductFlow.remoteConnect)(ProductOutcome.ok);
+ await phone.flush();
+ expect(reports, isEmpty);
+
+ // The account turned off: the opt-out is settled and kept as an ordinary off.
+ phone.savedChoice({'enabled': false, 'revision': 1});
+ await phone.setupChoiceSaved;
+ expect(phone.accountOptOutPending, isFalse);
+ expect(kept(), 'false');
+ });
+
+ test(
+ 'the account\'s choice is the next signed-out one, on or off',
+ () async {
+ final phone = launch(keeping: store);
+ await phone.setupChoiceReady;
+ await signIn(phone, () => {'enabled': false, 'revision': 3});
+ expect(kept(), 'false');
+ expect(phone.signedOutSharing, isFalse);
+
+ final next = launch(keeping: store);
+ await next.setupChoiceReady;
+ await signIn(next, () => {'enabled': true, 'revision': 4});
+ expect(kept(), 'true');
+ expect(next.signedOutSharing, isTrue);
+ },
+ );
+
+ test(
+ 'turning sharing on in Privacy settles an opt-out still to carry',
+ () async {
+ final phone = launch(keeping: store);
+ await phone.setupChoiceReady;
+ await phone.setSignedOutSharing(false);
+ await signIn(phone, () => {'enabled': true, 'revision': 0});
+ expect(phone.sharing, isFalse);
+
+ phone.savedChoice({'enabled': true, 'revision': 5}, explicit: true);
+ await phone.setupChoiceSaved;
+ expect(phone.accountOptOutPending, isFalse);
+ expect(phone.sharing, isTrue);
+ expect(kept(), 'true');
+ },
+ );
+
+ test(
+ 'an account answer before the phone\'s own choice is read waits for it',
+ () async {
+ final slow = _Slow();
+ final phone = launch(keeping: slow);
+ phone.savedChoice({'enabled': true, 'revision': 0});
+ expect(phone.choiceLoaded, isFalse);
+ slow.answer.complete(ProductMeasurement.pendingSetupOptOut);
+ await phone.setupChoiceReady;
+ expect(phone.accountOptOutPending, isTrue);
+ expect(phone.signedOutSharing, isFalse);
+ },
+ );
+
+ test('a choice that cannot be read is an opt-out still to carry', () async {
+ final phone = launch(keeping: _Unreadable());
+ await phone.setupChoiceReady;
+ expect(phone.choiceLoaded, isTrue);
+ expect(phone.signedOutSharing, isFalse);
+ expect(phone.accountOptOutPending, isTrue);
+ });
+
+ test(
+ 'a box ticked or unticked before the kept choice is read stands',
+ () async {
+ final phone = launch(keeping: store);
+ await phone.setSignedOutSharing(false);
+ await phone.setupChoiceReady;
+ expect(phone.signedOutSharing, isFalse);
+ },
+ );
+
+ test(
+ 'with nowhere to keep an opt-out — a test, the sample — it starts off',
+ () {
+ final phone = launch();
+ expect(phone.choiceLoaded, isTrue);
+ expect(phone.signedOutSharing, isFalse);
+ expect(phone.accountOptOutPending, isFalse);
+ },
+ );
+ });
+
+ group('the phone\'s side pages', () {
+ late ProductMeasurement phone;
+ setUp(() {
+ phone = ProductMeasurement(
+ surface: 'phone',
+ automatic: false,
+ now: () => now,
+ sendSetup: (_) async => {'accepted': true},
+ );
+ });
+ tearDown(() => phone.dispose());
+
+ test(
+ 'each opening is counted by page and by way, for an account that shares',
+ () async {
+ phone.screenOpened(PhoneScreen.find, ScreenOpening.swipe);
+ phone.account(
+ 'PRIVATE_ACCOUNT',
+ choice: () async => choice,
+ send: (r) async {
+ reports.add(jsonDecode(jsonEncode(r)));
+ return {'accepted': true};
+ },
+ );
+ await phone.flush();
+ phone.screenOpened(PhoneScreen.find, ScreenOpening.swipe);
+ phone.screenOpened(PhoneScreen.find, ScreenOpening.swipe);
+ phone.screenOpened(PhoneScreen.computers, ScreenOpening.button);
+ await phone.flush();
+ expect(reports.single['counters'], {
+ 'ui_phone_screen_find_swipe': 2,
+ 'ui_phone_screen_computers_button': 1,
+ });
+ },
+ );
+
+ test(
+ 'a desktop never counts them: the backend names them for the phone alone',
+ () async {
+ await account();
+ usage.screenOpened(PhoneScreen.find, ScreenOpening.button);
+ await usage.flush();
+ expect(reports, isEmpty);
+ },
+ );
+
+ test('every page and way is in the backend vocabulary', () {
+ final vocabulary = File('../backend/src/types/productUsage.ts')
+ .readAsStringSync();
+ List<String> listed(String name) => RegExp("'(\\w+)'")
+ .allMatches(
+ RegExp('export const $name = \\[([^\\]]*)\\]')
+ .firstMatch(vocabulary)!
+ .group(1)!,
+ )
+ .map((match) => match.group(1)!)
+ .toList();
+ expect(
+ listed('PRODUCT_USAGE_PHONE_SCREENS'),
+ PhoneScreen.values.map((screen) => screen.name),
+ );
+ expect(
+ listed('PRODUCT_USAGE_SCREEN_OPENINGS'),
+ ScreenOpening.values.map((how) => how.name),
+ );
+ });
+ });
+}
+
+/// A kept choice that cannot be read: an opt-out must never come back on because of it.
+class _Unreadable implements LocalKeyValueStore {
+ @override
+ Future<String?> read(String key) async => throw StateError('locked');
+
+ @override
+ Future<void> write(String key, String value) async {}
+
+ @override
+ Future<void> delete(String key) async {}
+}
+
+/// A kept choice read only when the test says so.
+class _Slow implements LocalKeyValueStore {
+ final answer = Completer<String?>();
+
+ @override
+ Future<String?> read(String key) => answer.future;
+
+ @override
+ Future<void> write(String key, String value) async {}
+
+ @override
+ Future<void> delete(String key) async {}
}
diff --git a/mobile/test/viewer_app_fixture.dart b/mobile/test/viewer_app_fixture.dart
index fb150d9b0..b95a659e7 100644
--- a/mobile/test/viewer_app_fixture.dart
+++ b/mobile/test/viewer_app_fixture.dart
@@ -157,9 +157,20 @@ class FakeApi extends ApiClient {
Map<String, dynamic> usageChoice = const {'enabled': true, 'revision': 0};
final List<Map<String, dynamic>> usageReports = [];
- @override
- Future<Map<String, dynamic>> productUsageSettings({bool? enabled}) async =>
- Map.of(usageChoice);
+ /// What each read or save of the choice asked: null for a read, the setting for a save.
+ final List<bool?> usageChoiceAsks = [];
+
+ @override
+ Future<Map<String, dynamic>> productUsageSettings({bool? enabled}) async {
+ usageChoiceAsks.add(enabled);
+ if (enabled != null) {
+ usageChoice = {
+ 'enabled': enabled,
+ 'revision': (usageChoice['revision'] as int) + 1,
+ };
+ }
+ return Map.of(usageChoice);
+ }
@override
Future<Map<String, dynamic>> productUsageReport(
diff --git a/mobile/test/ws/ws_conn_relay_test.dart b/mobile/test/ws/ws_conn_relay_test.dart
index 56a665ad0..773cf1bdf 100644
--- a/mobile/test/ws/ws_conn_relay_test.dart
+++ b/mobile/test/ws/ws_conn_relay_test.dart
@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:convert';
+import 'dart:io';
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
@@ -387,6 +388,55 @@ void main() {
},
);
+ test('what a daemon counts says it is the phone\'s, inside the seal; nothing else does', () async {
+ final (conn, link) = await connected();
+ // Never answered here: what matters is what reached the machine.
+ void ask(String type, Map<String, dynamic> payload) => unawaited(
+ conn.request(type, payload: payload).then((_) {}, onError: (_) {}),
+ );
+ ask('agent_create', {'engine': 'claude'});
+ ask('agents_list', {'scope': 'all'});
+ conn.sendRaw('message', {'content': 'hi', 'agentId': 'a'});
+ conn.sendRaw('app_presence', {'focused': true});
+ await eventually(
+ () => [
+ 'agent_create',
+ 'agents_list',
+ 'message',
+ 'app_presence',
+ ].every((type) => link.frames.any((f) => f['type'] == type)),
+ );
+
+ final create = link.frames.firstWhere((f) => f['type'] == 'agent_create');
+ expect((create['payload'] as Map).keys, [
+ '__e2e',
+ ], reason: 'the relay sees no more than before');
+ expect(link.opened('agent_create').single['usageSurface'], 'phone');
+ expect(link.opened('message').single['usageSurface'], 'phone');
+ expect(
+ link.opened('agents_list').single.containsKey('usageSurface'),
+ isFalse,
+ );
+ expect(link.opened('app_presence').single, {'focused': true});
+ final hello = link.frames.firstWhere((f) => f['type'] == 'e2e_hello');
+ expect(jsonEncode(hello), isNot(contains('usageSurface')));
+ });
+
+ test('the phone marks exactly the requests the daemon counts', () {
+ final signals = File('../cli/src/lib/productUsageSignals.ts')
+ .readAsStringSync();
+ final actions = RegExp(r'const actions = \{([^}]*)\}')
+ .firstMatch(signals)!
+ .group(1)!;
+ final counted = {
+ for (final match in RegExp(r'(\w+):').allMatches(actions))
+ match.group(1)!,
+ // Counted by its own name there, not through the table.
+ 'message',
+ };
+ expect(WsConn.usageMeasuredRequests, counted);
+ });
+
test('sendRaw goes out as it is when its type is not sealed', () async {
final (conn, link) = await connected();
conn.sendRaw('app_presence', {'focused': true});