The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
Mobile: Claude Code scroll follows the finger; Desktop: Add Phone for returning accounts (#1721)
tony496s15900c80a2c0
diff --git a/backend/src/analytics/dailyProductReview.test.ts b/backend/src/analytics/dailyProductReview.test.tsindex 567a9916a..201221c09 100644--- a/backend/src/analytics/dailyProductReview.test.ts+++ b/backend/src/analytics/dailyProductReview.test.ts@@ -149,3 +149,57 @@ it('shows every way into Add Phone beside the Desktop\'s Add Phone card', () =>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')})++it('shows new phone pairings and skipped-card reasons only beside the Desktop card', () => {+ const r = dailyProductReview([+ row('2026-10-12', 'ui_desktop_add_phone_paired_offer', 1),+ row('2026-10-12', 'ui_desktop_add_phone_paired_titlebar', 2),+ row('2026-10-12', 'ui_desktop_add_phone_paired_menu', 3),+ row('2026-10-12', 'ui_desktop_add_phone_paired_account', 4),+ row('2026-10-12', 'ui_desktop_add_phone_paired_machines', 5),+ row('2026-10-12', 'ui_desktop_add_phone_paired_command', 6),+ row('2026-10-12', 'ui_desktop_phone_offer_skipped_has_phone', 7),+ row('2026-10-12', 'ui_desktop_phone_offer_skipped_no_device_list', 8),+ row('2026-10-12', 'ui_desktop_phone_offer_skipped_already_shown', 9),+ row('2026-10-12', 'ui_desktop_phone_offer_skipped_stopped', 10),+ row('2026-10-12', 'ui_desktop_phone_offer_skipped_cap_reached', 11),+ row('2026-10-12', 'ui_desktop_phone_offer_skipped_not_signed_in', 12),+ row('2026-10-12', 'ui_desktop_phone_offer_skipped_viewer', 13),+ row('2026-10-12', 'ui_desktop_phone_offer_skipped_card_showing', 14),+ row('2026-10-12', 'ui_desktop_phone_offer_skipped_no_storage', 15),+ row('2026-10-12', 'ui_desktop_phone_offer_skipped_account_changed', 16),+ row('2026-10-12', 'ui_desktop_phone_offer_skipped_read_limit', 17),+ ], new Date('2026-10-13'))+ const card = r.flows.find(f => f.channel === 'ui' && f.surface === 'desktop' && f.flow === 'phone_offer')+ expect(card).toMatchObject({+ addPhonePaired: { offer: 1, titlebar: 2, menu: 3, account: 4, machines: 5, command: 6 },+ phoneOfferSkipped: { has_phone: 7, no_device_list: 8, already_shown: 9, stopped: 10, cap_reached: 11,+ not_signed_in: 12, viewer: 13, card_showing: 14, no_storage: 15, account_changed: 16, read_limit: 17 },+ })+ expect(r.flows.filter(f => 'addPhonePaired' in f)).toEqual([card])+ expect(r.flows.filter(f => 'phoneOfferSkipped' in f)).toEqual([card])+})++it('zero-fills absent pairing and skip counters and uses the existing complete seven-day window', () => {+ const r = dailyProductReview([+ row('2026-10-06', 'ui_desktop_add_phone_paired_command', 2),+ row('2026-10-12', 'ui_desktop_add_phone_paired_command', 3),+ row('2026-10-05', 'ui_desktop_add_phone_paired_offer', 999),+ row('2026-10-13', 'ui_desktop_add_phone_paired_offer', 999),+ row('2026-10-06', 'ui_desktop_phone_offer_skipped_has_phone', 4),+ row('2026-10-12', 'ui_desktop_phone_offer_skipped_has_phone', 5),+ row('2026-10-05', 'ui_desktop_phone_offer_skipped_stopped', 999),+ row('2026-10-13', 'ui_desktop_phone_offer_skipped_stopped', 999),+ ], new Date('2026-10-13'))+ expect(r.flows.find(f => f.channel === 'ui' && f.surface === 'desktop' && f.flow === 'phone_offer')).toMatchObject({+ addPhonePaired: { offer: 0, titlebar: 0, menu: 0, account: 0, machines: 0, command: 5 },+ phoneOfferSkipped: { has_phone: 9, no_device_list: 0, already_shown: 0, stopped: 0, cap_reached: 0,+ not_signed_in: 0, viewer: 0, card_showing: 0, no_storage: 0, account_changed: 0, read_limit: 0 },+ })+ const empty = dailyProductReview([], new Date('2026-10-13'))+ expect(empty.flows.find(f => f.channel === 'ui' && f.surface === 'desktop' && f.flow === 'phone_offer')).toMatchObject({+ addPhonePaired: { offer: 0, titlebar: 0, menu: 0, account: 0, machines: 0, command: 0 },+ phoneOfferSkipped: { has_phone: 0, no_device_list: 0, already_shown: 0, stopped: 0, cap_reached: 0,+ not_signed_in: 0, viewer: 0, card_showing: 0, no_storage: 0, account_changed: 0, read_limit: 0 },+ })+})diff --git a/backend/src/analytics/dailyProductReview.ts b/backend/src/analytics/dailyProductReview.tsindex 546597bfa..4590d206c 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_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 { 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_PHONE_OFFER_SKIP_REASONS, 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,9 +114,11 @@ 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`.+ // Beside the Desktop's card: openings, new phones by opening, and reasons a card did not show....(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])) } : {}),+ ? { addPhoneOpenings: Object.fromEntries(PRODUCT_USAGE_ADD_PHONE_OPENINGS.map(opening => [opening, c[`ui_desktop_add_phone_${opening}`] ?? 0])),+ addPhonePaired: Object.fromEntries(PRODUCT_USAGE_ADD_PHONE_OPENINGS.map(opening => [opening, c[`ui_desktop_add_phone_paired_${opening}`] ?? 0])),+ phoneOfferSkipped: Object.fromEntries(PRODUCT_USAGE_PHONE_OFFER_SKIP_REASONS.map(reason => [reason, c[`ui_desktop_phone_offer_skipped_${reason}`] ?? 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/routes/productUsage.test.ts b/backend/src/routes/productUsage.test.tsindex 4dc403f8e..eeb514bb2 100644--- a/backend/src/routes/productUsage.test.ts+++ b/backend/src/routes/productUsage.test.ts@@ -319,3 +319,18 @@ it('feedback reduces a voluntary fixed choice to one unlinked, retry-safe count'expect((await app.inject(request)).statusCode).toBe(409)expect(methods.ingestProductUsage).not.toHaveBeenCalled()})++it('accepts every returning-offer skip and pairing-source counter', async () => {+ const metrics = [+ ...['started', 'ok', 'cancelled', 'unknown'].map(x => `ui_desktop_phone_offer_returning_${x}`),+ ...['has_phone', 'no_device_list', 'already_shown', 'stopped', 'cap_reached', 'not_signed_in',+ 'viewer', 'card_showing', 'no_storage', 'account_changed', 'read_limit'].map(x => `ui_desktop_phone_offer_skipped_${x}`),+ ...['offer', 'titlebar', 'menu', 'account', 'machines', 'command'].map(x => `ui_desktop_add_phone_paired_${x}`),+ ]+ for (const metric of metrics) {+ const report = { ...good, context: { surface: 'desktop', release: '1.3.0', platform: 'macos', channel: 'production' },+ counters: { [metric]: 1 } }+ expect((await submit(report)).statusCode, metric).toBe(200)+ expect(methods.ingestProductUsage).toHaveBeenLastCalledWith('account', report)+ }+})diff --git a/backend/src/types/productUsage.ts b/backend/src/types/productUsage.tsindex 960252a70..3f47c79f1 100644--- a/backend/src/types/productUsage.ts+++ b/backend/src/types/productUsage.ts@@ -79,13 +79,21 @@ export const PRODUCT_USAGE_PHONE_SCREEN_METRICS = PRODUCT_USAGE_PHONE_SCREENS.fl* opened signed in was marked offered without it), after one of its own harnesses finished a turn; vocabulary 4.* `phone_offer_away_waited` / `_finished`: the card for a person back after five minutes or more away, to a harness* that waited on them or finished meanwhile; vocabulary 4. docs/design/2026-10-20-desktop-phone-conversion.md. */-export const PRODUCT_USAGE_DESKTOP_FLOWS = ['phone_offer', 'phone_offer_after_work', 'phone_offer_away_waited',+export const PRODUCT_USAGE_DESKTOP_FLOWS = ['phone_offer_returning', 'phone_offer', 'phone_offer_after_work', 'phone_offer_away_waited','phone_offer_away_finished', 'share_invite', 'share_accept'] 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 constexport const PRODUCT_USAGE_ADD_PHONE_METRICS = PRODUCT_USAGE_ADD_PHONE_OPENINGS.map(opening => `ui_desktop_add_phone_${opening}` as const)+/** Vocabulary 6. Fixed counters only: no account or device identity. */+export const PRODUCT_USAGE_PHONE_OFFER_SKIP_REASONS = ['has_phone', 'no_device_list', 'already_shown', 'stopped',+ 'cap_reached', 'not_signed_in', 'viewer', 'card_showing', 'no_storage', 'account_changed', 'read_limit'] as const+export const PRODUCT_USAGE_PHONE_OFFER_SKIP_METRICS = PRODUCT_USAGE_PHONE_OFFER_SKIP_REASONS+ .map(reason => `ui_desktop_phone_offer_skipped_${reason}` as const)+export const PRODUCT_USAGE_ADD_PHONE_PAIRED_METRICS = PRODUCT_USAGE_ADD_PHONE_OPENINGS+ .map(opening => `ui_desktop_add_phone_paired_${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, ...PRODUCT_USAGE_DESKTOP_FLOWS] as const@@ -210,6 +218,8 @@ export const PRODUCT_USAGE_METRICS = [...PRODUCT_USAGE_PHONE_LAUNCH_MARKS,...PRODUCT_USAGE_PHONE_SCREEN_METRICS,...PRODUCT_USAGE_ADD_PHONE_METRICS,+ ...PRODUCT_USAGE_PHONE_OFFER_SKIP_METRICS,+ ...PRODUCT_USAGE_ADD_PHONE_PAIRED_METRICS,'ui_phone_first_open',// 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.diff --git a/cli/src/hookServer.spec.ts b/cli/src/hookServer.spec.tsindex 8cda70dd1..3afde9cff 100644--- a/cli/src/hookServer.spec.ts+++ b/cli/src/hookServer.spec.ts@@ -551,7 +551,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('5')+ expect(kept.headers.get('x-harness-usage-vocabulary')).toBe('6')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')@@ -564,7 +564,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('5')+ expect(response.headers.get('x-harness-usage-vocabulary')).toBe('6')expect(await response.text()).not.toContain('PRIVATE_CANARY')}expect(send).toHaveBeenCalledOnce()diff --git a/cli/src/lib/appProductUsageReport.spec.ts b/cli/src/lib/appProductUsageReport.spec.tsindex 5c2aa8c4c..97b969b6c 100644--- a/cli/src/lib/appProductUsageReport.spec.ts+++ b/cli/src/lib/appProductUsageReport.spec.ts@@ -84,8 +84,8 @@ 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 5 including first-arrival, invite and existing Add Phone names', () => {- expect(APP_USAGE_VOCABULARY).toBe(5)+it('announces vocabulary 6 including first-arrival, invite and existing Add Phone names', () => {+ expect(APP_USAGE_VOCABULARY).toBe(6)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()}@@ -101,3 +101,17 @@ it('announces vocabulary 5 including first-arrival, invite and existing Add Phon// 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()})++it('forwards returning offers, every skip reason and every pairing source in vocabulary 6', () => {+ expect(APP_USAGE_VOCABULARY).toBe(6)+ const metrics = [+ ...['started', 'ok', 'cancelled', 'unknown', 'under_1s', 'over_1m'].map(x => `ui_desktop_phone_offer_returning_${x}`),+ ...['has_phone', 'no_device_list', 'already_shown', 'stopped', 'cap_reached', 'not_signed_in',+ 'viewer', 'card_showing', 'no_storage', 'account_changed', 'read_limit'].map(x => `ui_desktop_phone_offer_skipped_${x}`),+ ...['offer', 'titlebar', 'menu', 'account', 'machines', 'command'].map(x => `ui_desktop_add_phone_paired_${x}`),+ ]+ for (const metric of metrics) {+ const report = { ...native, counters: { [metric]: 1 } }+ expect(appProductUsageReport(report), metric).toEqual(report)+ }+})diff --git a/cli/src/lib/appProductUsageReport.ts b/cli/src/lib/appProductUsageReport.tsindex 36893981a..894e8a922 100644--- a/cli/src/lib/appProductUsageReport.ts+++ b/cli/src/lib/appProductUsageReport.ts@@ -1,5 +1,5 @@import { cleanUsageContext, HEALTH_MEASURES, CLI_REPORT_FAILURES } from './productHealthContract.js'-import { PRODUCT_USAGE_ADD_PHONE_METRICS, PRODUCT_USAGE_METRICS, PRODUCT_USAGE_UI_METRICS,+import { PRODUCT_USAGE_ADD_PHONE_METRICS, PRODUCT_USAGE_ADD_PHONE_PAIRED_METRICS, PRODUCT_USAGE_PHONE_OFFER_SKIP_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`.@@ -8,8 +8,9 @@ import { PRODUCT_USAGE_ADD_PHONE_METRICS, PRODUCT_USAGE_METRICS, PRODUCT_USAGE_U* after work or after time away (`ui_desktop_phone_offer_after_work_*`, `ui_desktop_phone_offer_away_*`). The* Desktop sends a name newer than revision 1 only once a proxy has announced it, so an older CLI never sees one.* 5: first-arrival episodes and shared-tab invitation outcomes.+ * 6: returning-account phone offers, offer skip reasons and Add Phone pairing sources.* Raise it with each name the Desktop gates on it (`ProductHealthMeasure.vocabulary`, `ProductFlow.vocabulary`). */-export const APP_USAGE_VOCABULARY = 5+export const APP_USAGE_VOCABULARY = 6export 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.@@ -17,6 +18,8 @@ const uiMetrics = new Set<string>(PRODUCT_USAGE_UI_METRICS.filter(metric => !metconst desktopMetrics = new Set<string>([...PRODUCT_USAGE_UI_METRICS.filter(metric => metric.startsWith('ui_desktop_')),...PRODUCT_USAGE_ADD_PHONE_METRICS,+ ...PRODUCT_USAGE_ADD_PHONE_PAIRED_METRICS,+ ...PRODUCT_USAGE_PHONE_OFFER_SKIP_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.tsindex 960252a70..3f47c79f1 100644--- a/cli/src/lib/productUsageContract.ts+++ b/cli/src/lib/productUsageContract.ts@@ -79,13 +79,21 @@ export const PRODUCT_USAGE_PHONE_SCREEN_METRICS = PRODUCT_USAGE_PHONE_SCREENS.fl* opened signed in was marked offered without it), after one of its own harnesses finished a turn; vocabulary 4.* `phone_offer_away_waited` / `_finished`: the card for a person back after five minutes or more away, to a harness* that waited on them or finished meanwhile; vocabulary 4. docs/design/2026-10-20-desktop-phone-conversion.md. */-export const PRODUCT_USAGE_DESKTOP_FLOWS = ['phone_offer', 'phone_offer_after_work', 'phone_offer_away_waited',+export const PRODUCT_USAGE_DESKTOP_FLOWS = ['phone_offer_returning', 'phone_offer', 'phone_offer_after_work', 'phone_offer_away_waited','phone_offer_away_finished', 'share_invite', 'share_accept'] 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 constexport const PRODUCT_USAGE_ADD_PHONE_METRICS = PRODUCT_USAGE_ADD_PHONE_OPENINGS.map(opening => `ui_desktop_add_phone_${opening}` as const)+/** Vocabulary 6. Fixed counters only: no account or device identity. */+export const PRODUCT_USAGE_PHONE_OFFER_SKIP_REASONS = ['has_phone', 'no_device_list', 'already_shown', 'stopped',+ 'cap_reached', 'not_signed_in', 'viewer', 'card_showing', 'no_storage', 'account_changed', 'read_limit'] as const+export const PRODUCT_USAGE_PHONE_OFFER_SKIP_METRICS = PRODUCT_USAGE_PHONE_OFFER_SKIP_REASONS+ .map(reason => `ui_desktop_phone_offer_skipped_${reason}` as const)+export const PRODUCT_USAGE_ADD_PHONE_PAIRED_METRICS = PRODUCT_USAGE_ADD_PHONE_OPENINGS+ .map(opening => `ui_desktop_add_phone_paired_${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, ...PRODUCT_USAGE_DESKTOP_FLOWS] as const@@ -210,6 +218,8 @@ export const PRODUCT_USAGE_METRICS = [...PRODUCT_USAGE_PHONE_LAUNCH_MARKS,...PRODUCT_USAGE_PHONE_SCREEN_METRICS,...PRODUCT_USAGE_ADD_PHONE_METRICS,+ ...PRODUCT_USAGE_PHONE_OFFER_SKIP_METRICS,+ ...PRODUCT_USAGE_ADD_PHONE_PAIRED_METRICS,'ui_phone_first_open',// 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.diff --git a/desktop/integration_test/phone_offer_away_native_test.dart b/desktop/integration_test/phone_offer_away_native_test.dartindex 4cd67b2a9..aa68a8c31 100644--- a/desktop/integration_test/phone_offer_away_native_test.dart+++ b/desktop/integration_test/phone_offer_away_native_test.dart@@ -177,6 +177,21 @@ void main() {await settle(tester);}+ testWidgets('returning account gets a card, never a dialog', (tester) async {+ final app = working()+ ..currentUser = const CurrentUserProfile(id: 'returning', email: '[email protected]');+ addTearDown(app.dispose);+ await app.offerPhoneForTest(atLaunch: true);+ await mount(tester, app, Brightness.dark);+ expect(find.byKey(const Key('phone-offer-card')), findsOneWidget);+ expect(find.byKey(const Key('add-phone-close')), findsNothing);+ await captureWindow(tester, _shotsDir, '0-returning-card');+ await tester.tap(find.byKey(const Key('phone-offer-dismiss')));+ await settle(tester);+ expect(app.phoneOfferShowing, isFalse);+ await tester.pumpWidget(const SizedBox());+ });+testWidgets('a harness finished while the person was away', (tester) async {final app = working();addTearDown(app.dispose);diff --git a/desktop/lib/measurement/product_measurement.dart b/desktop/lib/measurement/product_measurement.dartindex eff10aeab..538c9d65a 100644--- a/desktop/lib/measurement/product_measurement.dart+++ b/desktop/lib/measurement/product_measurement.dart@@ -31,6 +31,7 @@ enum ProductFlow {// The Add Phone card (widgets/phone_offer_card.dart), offered once per computer: begun when it is on// screen, ok by its Add Phone, cancelled by its ×, unknown when it goes another way.phoneOffer('phone_offer'),+ phoneOfferReturning('phone_offer_returning'),shareInvite('share_invite'),shareAccept('share_accept'),// The same card offered once to a computer that never had it, after one of its own harnesses@@ -60,6 +61,7 @@ enum ProductFlow {/// queue for that answer instead of being skipped ([ProductMeasurement]).int get vocabulary => switch (this) {phoneOffer => 3,+ phoneOfferReturning => 6,shareInvite || shareAccept => 5,phoneOfferAfterWork || phoneOfferAwayWaited || phoneOfferAwayFinished => 4,_ => 1,@@ -70,6 +72,7 @@ enum ProductFlow {/// an Add Phone pressed after 15 minutes would otherwise be lost to unknown.bool get unbounded =>this == phoneOffer ||+ this == phoneOfferReturning ||this == phoneOfferAfterWork ||this == phoneOfferAwayWaited ||this == phoneOfferAwayFinished;@@ -535,6 +538,45 @@ class ProductMeasurement extends ChangeNotifier {);}+ /// A new non-machine key joined while Add Phone was open, by its opening only.+ void addPhonePaired(AddPhoneOpening from) {+ if (!healthEnabled || !sharing || _disposed) return;+ _coverage();+ _count(+ 'ui',+ _now().toUtc().toIso8601String().substring(0, 10),+ 'ui_desktop_add_phone_paired_${from.wire}',+ );+ }++ /// A card path declined an offer. Fixed reasons only; never account or device data.+ void phoneOfferSkipped(String reason) {+ if (!const {+ 'has_phone',+ 'no_device_list',+ 'already_shown',+ 'stopped',+ 'cap_reached',+ 'not_signed_in',+ 'viewer',+ 'card_showing',+ 'no_storage',+ 'account_changed',+ 'read_limit',+ }.contains(reason) ||+ !healthEnabled ||+ !sharing ||+ _disposed) {+ return;+ }+ _coverage();+ _count(+ 'ui',+ _now().toUtc().toIso8601String().substring(0, 10),+ 'ui_desktop_phone_offer_skipped_$reason',+ );+ }+/// One first-arrival episode in this app run. Retries share its denominator;/// routine launches never call this. Targets stay in RAM and are never reported.void firstRunStarted() {@@ -627,6 +669,10 @@ class ProductMeasurement extends ChangeNotifier {/// after work or after time away 4, and first-run/invite counters 5. Other/// health measures use [health] to wait for support before counting.static int _vocabularyOf(String metric) {+ if (metric.startsWith('ui_desktop_phone_offer_skipped_') ||+ metric.startsWith('ui_desktop_add_phone_paired_')) {+ return 6;+ }if (metric.startsWith('health_desktop_first_run_') ||metric.startsWith('health_desktop_shared_invites_')) return 5;for (final flow in _newerFlows) {diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex c7a0abbcc..5ab98d078 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -3488,6 +3488,7 @@ class _SwarmScreenState extends State<SwarmScreen> {context,app,keymap: _keymap,+ from: from,onConnectMachine: () => unawaited(_openMachines()),// "See your phones": Machines, at its phones, once the dialog has// gone. ⚠️ Asked for, not opened here: right after the pop thisdiff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex 293867367..df0b6c0a1 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -7669,14 +7669,57 @@ class AppNotifier extends ChangeNotifier {/// sign-in by hand ([_offerPhoneAfterSignIn]) — never again once Add Phone has been opened here,/// the card put away, or the account found to have a phone ([_phoneOfferDone]).///- /// A computer that opened signed in was marked offered without ever showing the card, so it gets- /// that one showing after work instead ([_offerPhoneAfterWork], [_phoneOfferSeen]).+ /// Returning accounts get one launch card per account on this computer (owner, 2026-10-26),+ /// remembered only once on screen. It also spends the after-work showing and one away-card slot.+ /// The stopped record (a previous × or Add Phone opening) still rules out every later offer.bool get phoneOfferShowing => _phoneOffer;bool _phoneOffer = false;/// Which offer [_phoneOffer] is: the first one's, the one after work ([_offerPhoneAfterWork]) or/// the one after time away ([_offerPhoneAway]), each counted as its own flow.ProductFlow _phoneOfferFlow = ProductFlow.phoneOffer;+ String? _returningPhoneOfferAccount;+ bool _phoneOffersStoppedHere = false;++ int _phoneOfferSkipRevision = -1;+ final _phoneOfferSkips = <(String, String)>{};++ void _skipPhoneOffer(String path, String reason) {+ // Invalidation changes the revision on account transitions. Forget old+ // pairs rather than retaining a long-lived set for every previous account.+ if (_phoneOfferSkipRevision != _authRevision) {+ _phoneOfferSkips.clear();+ _phoneOfferSkipRevision = _authRevision;+ }+ if (_phoneOfferSkips.add((path, reason))) {+ productMeasurement.phoneOfferSkipped(reason);+ }+ }++ String? _phoneOfferBlock() {+ if (kIsWeb || viewer != null) return 'viewer';+ if (_phoneOffersStoppedHere) return 'stopped';+ if (_phoneOffer) return 'card_showing';+ if (!signedIn) return 'not_signed_in';+ if (_accountHasPhone) return 'has_phone';+ return null;+ }++ Future<String?> _phoneOfferStopReason({bool cap = false}) async {+ final storage = _paneLayout?.storage;+ if (storage == null) return 'no_storage';+ try {+ if (await storage.read(_phoneOfferStoppedKey) == '1') return 'stopped';+ if (cap &&+ (int.tryParse(await storage.read(_phoneOfferShowsKey) ?? '') ?? 0) >=+ phoneOfferMaxShows) {+ return 'cap_reached';+ }+ return null;+ } catch (_) {+ return 'no_storage';+ }+ }/// What the card says when it is offered after time away ([_offerPhoneAway]): the harness, whether/// it waited on the person or finished, and how many minutes ago. Null for the card's usual words.@@ -7694,6 +7737,14 @@ class AppNotifier extends ChangeNotifier {/// offer, however often the card is built again.void phoneOfferShown() {if (!_phoneOffer || _phoneOfferMeasure != null) return;+ if (_phoneOfferFlow == ProductFlow.phoneOfferReturning) {+ final account = _returningPhoneOfferAccount;+ if (account != currentUser?.id) return;+ _markPhoneOfferDone();+ _paneLayout?.storage+ .write('phone_offer_returning.$account', '1')+ .catchError((_) {});+ }_markPhoneOfferSeen();_countPhoneOfferShown();_phoneOfferMeasure = productMeasurement.begin(_phoneOfferFlow);@@ -7818,17 +7869,26 @@ class AppNotifier extends ChangeNotifier {/// no phone, with only the title bar's icon to find Add Phone by. Still once per computer: a computer that/// showed the first card, or opened Add Phone, has seen it.Future<void> _offerPhoneAfterWork() async {- if (_phoneOfferAfterWorkAsked ||- _accountHasPhone ||- _phoneOffer ||- viewer != null ||- !signedIn ||- status != AppStatus.authenticated) {- return;+ final blocked = _phoneOfferBlock();+ if (blocked != null) return _skipPhoneOffer('after_work', blocked);+ if (status != AppStatus.authenticated) {+ return _skipPhoneOffer('after_work', 'not_signed_in');+ }+ if (_phoneOfferAfterWorkAsked) {+ return _skipPhoneOffer(+ 'after_work',+ _phoneOfferAfterWorkUnanswered >= _phoneOfferUnansweredReads+ ? 'read_limit'+ : 'already_shown',+ );}_phoneOfferAfterWorkAsked = true;final revision = _authRevision;- if (await _phoneOfferSeen()) return;+ final stopped = await _phoneOfferStopReason();+ if (stopped != null) return _skipPhoneOffer('after_work', stopped);+ if (await _phoneOfferSeen()) {+ return _skipPhoneOffer('after_work', 'already_shown');+ }// No list to judge by: asked again at a later finished turn, a few times a run at most.void unanswered() => _phoneOfferAfterWorkAsked =++_phoneOfferAfterWorkUnanswered >= _phoneOfferUnansweredReads;@@ -7837,20 +7897,24 @@ class AppNotifier extends ChangeNotifier {final devices = await loadDevices();if (devices == null) {unanswered();- return;+ return _skipPhoneOffer('after_work', 'no_device_list');}hasPhone = devices.devices.any((device) => !device.isMachine && !device.self,);} catch (_) {unanswered();- return;+ return _skipPhoneOffer('after_work', 'no_device_list');+ }+ if (!_authWorkCurrent(revision)) {+ return _skipPhoneOffer('after_work', 'account_changed');}- if (!_authWorkCurrent(revision) || !signedIn || _phoneOffer) return;+ final changed = _phoneOfferBlock();+ if (changed != null) return _skipPhoneOffer('after_work', changed);if (hasPhone) {_accountHasPhone = true;_markPhoneOfferSeen();- return;+ return _skipPhoneOffer('after_work', 'has_phone');}_phoneOfferFlow = ProductFlow.phoneOfferAfterWork;_phoneOfferAway = null;@@ -7889,24 +7953,12 @@ class AppNotifier extends ChangeNotifier {({String agent, bool waited, DateTime at})? _missedWhileAway;void _stopPhoneOffers() {+ // A pending device read must not resurrect a card after Add Phone or ×.+ _phoneOffersStoppedHere = true;// Never awaited: a write that fails costs, at most, one more card after time away._paneLayout?.storage.write(_phoneOfferStoppedKey, '1').catchError((_) {});}- /// Whether this computer is done with cards after time away: said no, opened Add Phone, or shown- /// [phoneOfferMaxShows]. Nowhere to remember it is taken as done, as for [_phoneOfferDone].- Future<bool> _phoneOfferAwayDone() async {- final storage = _paneLayout?.storage;- if (storage == null) return true;- try {- if ((await storage.read(_phoneOfferStoppedKey)) == '1') return true;- final shows = int.tryParse(await storage.read(_phoneOfferShowsKey) ?? '');- return (shows ?? 0) >= phoneOfferMaxShows;- } catch (_) {- return true;- }- }-void _countPhoneOfferShown() {final storage = _paneLayout?.storage;if (storage == null) return;@@ -7946,34 +7998,37 @@ class AppNotifier extends ChangeNotifier {/// The card for a person back after [phoneOfferAwayAfter] or more away from the window, to a harness/// that waited on them or finished meanwhile ([missed]): what a phone would have told them where/// they were. On an account with no phone or browser yet, at most [phoneOfferMaxShows] cards a- /// computer, and none once its card was put away or Add Phone opened ([_phoneOfferAwayDone]).+ /// computer, and none once its card was put away or Add Phone opened ([_phoneOfferStopReason]).Future<void> _offerPhoneAway(({String agent, bool waited, DateTime at}) missed,) async {- if (_phoneOffer ||- _accountHasPhone ||- viewer != null ||- !signedIn ||- status != AppStatus.authenticated) {- return;+ final blocked = _phoneOfferBlock();+ if (blocked != null) return _skipPhoneOffer('away', blocked);+ if (status != AppStatus.authenticated) {+ return _skipPhoneOffer('away', 'not_signed_in');}final revision = _authRevision;- if (await _phoneOfferAwayDone()) return;+ final stopped = await _phoneOfferStopReason(cap: true);+ if (stopped != null) return _skipPhoneOffer('away', stopped);bool hasPhone;try {final devices = await loadDevices();// No list to judge by: nothing this time; the next time away asks again.- if (devices == null) return;+ if (devices == null) return _skipPhoneOffer('away', 'no_device_list');hasPhone = devices.devices.any((device) => !device.isMachine && !device.self,);} catch (_) {- return;+ return _skipPhoneOffer('away', 'no_device_list');+ }+ if (!_authWorkCurrent(revision)) {+ return _skipPhoneOffer('away', 'account_changed');}- if (!_authWorkCurrent(revision) || !signedIn || _phoneOffer) return;+ final changed = _phoneOfferBlock();+ if (changed != null) return _skipPhoneOffer('away', changed);if (hasPhone) {_accountHasPhone = true;- return;+ return _skipPhoneOffer('away', 'has_phone');}final minutes = phoneOfferClock().difference(missed.at).inMinutes;_phoneOfferFlow = missed.waited@@ -7993,16 +8048,62 @@ class AppNotifier extends ChangeNotifier {/// ⚠️ **A new install opens as a guest**, on its desk, with no sign-in asked for — so "after the/// first sign-in" alone never came for the newcomer the phone sent here, who was left looking at a/// desk with no code on it. As a guest, Add Phone asks for the sign-in itself and then shows the- /// code. A computer that opens signed in has had its first sign-in already: nothing after a later- /// one.+ /// code. A signed-in launch gets one returning-account card on this computer (owner, 2026-10-26),+ /// unless a phone already exists or the person stopped offers here.Future<void> _offerPhoneAtLaunch(int revision) async {- if (viewer != null || !_authWorkCurrent(revision)) return;+ if (kIsWeb || viewer != null) return _skipPhoneOffer('launch', 'viewer');+ if (!_authWorkCurrent(revision)) {+ return _skipPhoneOffer('launch', 'account_changed');+ }+ if (_phoneOffer) return _skipPhoneOffer('launch', 'card_showing');if (signedIn) {- _markPhoneOfferDone();+ final stopped = await _phoneOfferStopReason();+ if (stopped != null) return _skipPhoneOffer('launch', stopped);+ // Boot loads the profile independently of machine discovery. Wait for that+ // identity here, without delaying the workspace or reading devices again.+ if (currentUser?.id?.isNotEmpty != true) await _loadProfile();+ final blocked = _phoneOfferBlock();+ if (blocked != null) return _skipPhoneOffer('launch', blocked);+ final account = currentUser?.id;+ if (account == null || account.isEmpty) {+ return _skipPhoneOffer('launch', 'not_signed_in');+ }+ try {+ if (await _paneLayout!.storage.read('phone_offer_returning.$account') ==+ '1') {+ return _skipPhoneOffer('launch', 'already_shown');+ }+ if (_accountHasPhone) return _skipPhoneOffer('launch', 'has_phone');+ final devices = await loadDevices();+ if (devices == null) return _skipPhoneOffer('launch', 'no_device_list');+ if (!_authWorkCurrent(revision) || currentUser?.id != account) {+ return _skipPhoneOffer('launch', 'account_changed');+ }+ final changed = _phoneOfferBlock();+ if (changed != null) return _skipPhoneOffer('launch', changed);+ if (devices.devices.any(+ (device) => !device.isMachine && !device.self,+ )) {+ _accountHasPhone = true;+ return _skipPhoneOffer('launch', 'has_phone');+ }+ } catch (_) {+ return _skipPhoneOffer('launch', 'no_device_list');+ }+ _returningPhoneOfferAccount = account;+ _phoneOfferFlow = ProductFlow.phoneOfferReturning;+ _phoneOfferAway = null;+ _phoneOffer = true;+ notifyListeners();return;}- if (!isGuest || await _phoneOfferDone()) return;- if (!_authWorkCurrent(revision) || !isGuest) return;+ if (!isGuest) return _skipPhoneOffer('launch', 'not_signed_in');+ if (await _phoneOfferDone()) {+ return _skipPhoneOffer('launch', 'already_shown');+ }+ if (!_authWorkCurrent(revision) || !isGuest) {+ return _skipPhoneOffer('launch', 'account_changed');+ }_phoneOfferFlow = ProductFlow.phoneOffer;_phoneOfferAway = null;_phoneOffer = true;@@ -8018,7 +8119,13 @@ class AppNotifier extends ChangeNotifier {/// The first sign-in by hand on this computer offers Add Phone — unless the account already has a/// phone or a browser on it, which has its way in.Future<void> _offerPhoneAfterSignIn(int revision) async {- if (viewer != null || await _phoneOfferDone()) return;+ final blocked = _phoneOfferBlock();+ if (blocked != null) return _skipPhoneOffer('sign_in', blocked);+ final stopped = await _phoneOfferStopReason();+ if (stopped != null) return _skipPhoneOffer('sign_in', stopped);+ if (await _phoneOfferDone()) {+ return _skipPhoneOffer('sign_in', 'already_shown');+ }var hasPhone = false;try {final devices = await loadDevices();@@ -8028,10 +8135,14 @@ class AppNotifier extends ChangeNotifier {} catch (_) {// A list that cannot be read offers the card anyway: it costs one × to put away.}- if (!_authWorkCurrent(revision) || !signedIn) return;+ if (!_authWorkCurrent(revision)) {+ return _skipPhoneOffer('sign_in', 'account_changed');+ }+ final changed = _phoneOfferBlock();+ if (changed != null) return _skipPhoneOffer('sign_in', changed);if (hasPhone) {_markPhoneOfferDone();- return;+ return _skipPhoneOffer('sign_in', 'has_phone');}_phoneOfferFlow = ProductFlow.phoneOffer;_phoneOfferAway = null;diff --git a/desktop/lib/widgets/add_phone_dialog.dart b/desktop/lib/widgets/add_phone_dialog.dartindex a924ca3d8..4b2741445 100644--- a/desktop/lib/widgets/add_phone_dialog.dart+++ b/desktop/lib/widgets/add_phone_dialog.dart@@ -16,6 +16,7 @@ import '../shared/theme/app_theme.dart' as grid;import '../shortcuts/app_keymap.dart';import '../state/account_devices.dart' show NewDeviceNotice;import '../state/app_state.dart';+import '../measurement/product_measurement.dart' show AddPhoneOpening;import '../ws/ws_conn.dart' show WsRequestFailure, WsRequestTimeout;import 'desktop_chrome.dart';import 'desktop_prompt_surface.dart';@@ -67,24 +68,72 @@ Future<void> showAddPhoneDialog(BuildContext context,AppNotifier app, {AppKeymap? keymap,+ AddPhoneOpening? from,PhonePairCall? pair,PhoneSignInCodeCall? signInCode,bool Function()? signInUnavailable,VoidCallback? onConnectMachine,VoidCallback? onManageDevices,-}) => showTerminalPrompt<void>(- context,- keymap: keymap,- builder: (_) => AddPhoneDialog(- app: app,- pair: pair,- signInCode: signInCode ?? app.api.phoneSignInCode,- signInUnavailable:- signInUnavailable ?? () => app.api.phoneSignInUnavailable,- onConnectMachine: onConnectMachine,- onManageDevices: onManageDevices,- ),-);+}) {+ // Membership is needed only for attribution. Last-seen data can delay this+ // read, so open the dialog first and hold joins until its snapshot arrives.+ final account = app.currentUser?.id;+ final generation = app.accountGeneration;+ Set<String>? known;+ final pending = <String>{};+ var reading =+ from != null && account != null && !kIsWeb && app.viewer == null;+ void attribute(String pub) {+ if (account != app.currentUser?.id ||+ generation != app.accountGeneration ||+ app.isGuest ||+ app.signingIn) {+ return;+ }+ if (reading) {+ pending.add(pub);+ return;+ }+ final keys = known;+ if (from != null && keys != null && keys.add(pub)) {+ app.productMeasurement.addPhonePaired(from);+ }+ }++ final dialog = showTerminalPrompt<void>(+ context,+ keymap: keymap,+ builder: (_) => AddPhoneDialog(+ app: app,+ pair: pair,+ signInCode: signInCode ?? app.api.phoneSignInCode,+ signInUnavailable:+ signInUnavailable ?? () => app.api.phoneSignInUnavailable,+ onConnectMachine: onConnectMachine,+ onManageDevices: onManageDevices,+ onPhoneJoined: (device) => attribute(device.pub),+ ),+ );+ if (reading) {+ unawaited(() async {+ try {+ final devices = await app.loadDevices();+ if (devices != null) {+ known = {for (final device in devices.devices) device.pub};+ }+ } catch (_) {+ // A missing snapshot leaves attribution unknown; Add Phone still works.+ }+ reading = false;+ // These joins happened while open, even if the dialog has since closed.+ for (final pub in pending) {+ attribute(pub);+ }+ pending.clear();+ }());+ }+ return dialog;+}/// Where the QR points. The phone's `ConnectCode` (mobile/// `lib/phone/welcome/connect_code.dart`) parses exactly this.@@ -268,6 +317,7 @@ class AddPhoneDialog extends StatefulWidget {this.signInUnavailable,this.onConnectMachine,this.onManageDevices,+ this.onPhoneJoined,});final AppNotifier app;@@ -287,6 +337,7 @@ class AddPhoneDialog extends StatefulWidget {/// (owner, 2026-10-12). Not "devices": the tab row's Devices is the Harness/// hardware. The dialog closes; the caller opens Machines after.final VoidCallback? onManageDevices;+ final ValueChanged<NewDeviceNotice>? onPhoneJoined;@overrideState<AddPhoneDialog> createState() => _AddPhoneDialogState();@@ -425,8 +476,9 @@ class _AddPhoneDialogState extends State<AddPhoneDialog> {/// A device joined the account while this was open. A computer is not the/// phone; anything else signed in with this account is.void _deviceJoined(NewDeviceNotice device) {- if (_closed || _ready != null || device.kind == 'machine') return;- if (_signedOut) return;+ if (_closed || device.kind == 'machine' || _signedOut) return;+ widget.onPhoneJoined?.call(device);+ if (_ready != null) return;_phoneIn(device.label);}diff --git a/desktop/test/add_phone_dialog_test.dart b/desktop/test/add_phone_dialog_test.dartindex 995930544..7c820ae50 100644--- a/desktop/test/add_phone_dialog_test.dart+++ b/desktop/test/add_phone_dialog_test.dart@@ -6,6 +6,7 @@ import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness/core/models.dart';+import 'package:harness/api/api_client.dart';import 'package:harness/core/config.dart';import 'package:harness/core/phone_app_links.dart';import 'package:harness/measurement/product_measurement.dart';@@ -39,6 +40,23 @@ AppNotifier _signedInApp() {return app;}+class _DeviceSnapshotApi extends ApiClient {+ _DeviceSnapshotApi({this.fails = false, this.listing, this.pending})+ : super(+ config: AppConfig.dev,+ session: AuthSession(storage: MemoryStore()),+ );+ final bool fails;+ final Map<String, dynamic>? listing;+ final Completer<Map<String, dynamic>?>? pending;+ @override+ Future<Map<String, dynamic>?> daemonDevices() async {+ if (pending != null) return pending!.future;+ if (fails) throw StateError('unreadable');+ return listing ?? {'members': <Object>[]};+ }+}+/// A scripted daemon: answers in order, records every code it was handed.class _FakeDaemon {/// Copied: a fixed-length `List.filled` cannot be answered from, and the@@ -78,6 +96,7 @@ Future<void> _open(WidgetTester tester,AppNotifier app,PhonePairCall pair, {+ AddPhoneOpening? from,PhoneSignInCodeCall? signInCode,bool Function()? signInUnavailable,VoidCallback? onConnectMachine,@@ -102,6 +121,7 @@ Future<void> _open(showAddPhoneDialog(tester.element(find.byType(Scaffold)),app,+ from: from,pair: pair,signInCode: signInCode ?? _FakeSignIn().call,signInUnavailable: signInUnavailable,@@ -668,44 +688,54 @@ void main() {await tester.pump(const Duration(seconds: 10));});- testWidgets('with no sign-in code to be had on this PC, the QR says the phone will ask for an emailed one', (- tester,- ) async {- final app = _signedInApp();- addTearDown(app.dispose);- final daemon = _FakeDaemon(List.filled(10, _failed('NO_INTENT')));- var unavailable = true;- final signIn = _FakeSignIn(available: false);- await _open(- tester,- app,- daemon.call,- signInCode: () => unavailable ? signIn.call() : _FakeSignIn().call(),- signInUnavailable: () => unavailable,- );- await _codeUp(tester);- expect(- Uri.splitQueryString(Uri.parse(_qrData(tester)).fragment).keys,- ['e', 'm', 'c'],- );- expect(- tester.widget<Text>(find.byKey(const ValueKey('add-phone-email-code'))).data,- 'Your phone will ask for a code from your email.',- );- // Still the QR to scan, as with an older CLI.- expect(find.text('Scan with the Harness mobile app.'), findsOneWidget);+ testWidgets(+ 'with no sign-in code to be had on this PC, the QR says the phone will ask for an emailed one',+ (tester) async {+ final app = _signedInApp();+ addTearDown(app.dispose);+ final daemon = _FakeDaemon(List.filled(10, _failed('NO_INTENT')));+ var unavailable = true;+ final signIn = _FakeSignIn(available: false);+ await _open(+ tester,+ app,+ daemon.call,+ signInCode: () => unavailable ? signIn.call() : _FakeSignIn().call(),+ signInUnavailable: () => unavailable,+ );+ await _codeUp(tester);+ expect(Uri.splitQueryString(Uri.parse(_qrData(tester)).fragment).keys, [+ 'e',+ 'm',+ 'c',+ ]);+ expect(+ tester+ .widget<Text>(find.byKey(const ValueKey('add-phone-email-code')))+ .data,+ 'Your phone will ask for a code from your email.',+ );+ // Still the QR to scan, as with an older CLI.+ expect(find.text('Scan with the Harness mobile app.'), findsOneWidget);- // The pipe is back by the next renewal: the code is in the QR, the sentence gone.- unavailable = false;- await tester.pump(const Duration(seconds: 61));- await tester.pump();- expect(Uri.splitQueryString(Uri.parse(_qrData(tester)).fragment)['h'], 'h1');- expect(find.byKey(const ValueKey('add-phone-email-code')), findsNothing);+ // The pipe is back by the next renewal: the code is in the QR, the sentence gone.+ unavailable = false;+ await tester.pump(const Duration(seconds: 61));+ await tester.pump();+ expect(+ Uri.splitQueryString(Uri.parse(_qrData(tester)).fragment)['h'],+ 'h1',+ );+ expect(+ find.byKey(const ValueKey('add-phone-email-code')),+ findsNothing,+ );- await tester.sendKeyEvent(LogicalKeyboardKey.escape);- await tester.pump();- await tester.pump(const Duration(seconds: 10));- });+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ await tester.pump(const Duration(seconds: 10));+ },+ );});group('arming the daemon', () {@@ -937,6 +967,275 @@ void main() {});});+ for (final from in AddPhoneOpening.values) {+ testWidgets(+ 'opens immediately from ${from.name} while the snapshot never completes',+ (tester) async {+ final snapshot = Completer<Map<String, dynamic>?>();+ final app = _signedInApp()+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ )+ ..api = _DeviceSnapshotApi(pending: snapshot);+ addTearDown(app.dispose);+ final daemon = _FakeDaemon(List.filled(3, _failed('NO_INTENT')));+ await _open(tester, app, daemon.call, from: from);+ expect(find.byType(AddPhoneDialog), findsOneWidget);+ expect(find.byKey(const ValueKey('add-phone-close')), findsOneWidget);+ expect(find.byType(PhonePairQr), findsOneWidget);+ expect(snapshot.isCompleted, isFalse);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(find.byType(AddPhoneDialog), findsNothing);+ },+ );+ }++ testWidgets(+ 'joins before a late snapshot are judged once against its known keys',+ (tester) async {+ final snapshot = Completer<Map<String, dynamic>?>();+ final usage = AddPhoneRecorder();+ final app = createApp(productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ )+ ..api = _DeviceSnapshotApi(pending: snapshot);+ addTearDown(app.dispose);+ final daemon = _FakeDaemon(List.filled(3, _failed('NO_INTENT')));+ await _open(tester, app, daemon.call, from: AddPhoneOpening.menu);+ expect(find.byType(AddPhoneDialog), findsOneWidget);+ await _joins(tester, app, pub: 'existing');+ await _joins(tester, app, pub: 'new-phone');+ app.newDevices.clear();+ await _joins(tester, app, pub: 'new-phone');+ app.notifyListeners();+ await tester.pump();+ expect(usage.pairings, isEmpty);+ snapshot.complete({+ 'members': [+ {+ 'pub': 'existing',+ 'label': 'Existing',+ 'kind': 'viewer',+ 'addedAt': 1,+ 'fingerprint': 'fp',+ 'self': false,+ },+ ],+ });+ await tester.pump();+ await tester.pump();+ expect(usage.pairings, [AddPhoneOpening.menu]);+ app.newDevices.clear();+ await _joins(tester, app, pub: 'existing');+ await _joins(tester, app, pub: 'new-phone');+ await tester.pump();+ expect(usage.pairings, [AddPhoneOpening.menu]);+ await tester.pumpWidget(const SizedBox());+ },+ );++ for (final failed in [false, true]) {+ testWidgets(+ 'a ${failed ? 'failed' : 'null'} late snapshot drops buffered attribution and keeps the dialog usable',+ (tester) async {+ final snapshot = Completer<Map<String, dynamic>?>();+ final usage = AddPhoneRecorder();+ final app = createApp(productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ )+ ..api = _DeviceSnapshotApi(pending: snapshot);+ addTearDown(app.dispose);+ final daemon = _FakeDaemon(List.filled(3, _failed('NO_INTENT')));+ await _open(tester, app, daemon.call, from: AddPhoneOpening.offer);+ expect(find.byType(AddPhoneDialog), findsOneWidget);+ await _joins(tester, app);+ await tester.pump();+ expect(find.text('Dee’s iPhone is ready.'), findsOneWidget);+ expect(usage.pairings, isEmpty);+ if (failed) {+ snapshot.completeError(StateError('snapshot unavailable'));+ } else {+ snapshot.complete(null);+ }+ await tester.pump();+ await tester.pump();+ await _joins(tester, app, pub: 'another-phone');+ await tester.pump();+ expect(usage.pairings, isEmpty);+ expect(find.text('Dee’s iPhone is ready.'), findsOneWidget);+ await tester.pumpWidget(const SizedBox());+ },+ );+ }++ testWidgets(+ 'a buffered join can be attributed after closing but a later join cannot',+ (tester) async {+ final snapshot = Completer<Map<String, dynamic>?>();+ final usage = AddPhoneRecorder();+ final app = createApp(productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ )+ ..api = _DeviceSnapshotApi(pending: snapshot);+ addTearDown(app.dispose);+ final daemon = _FakeDaemon(List.filled(3, _failed('NO_INTENT')));+ await _open(tester, app, daemon.call, from: AddPhoneOpening.offer);+ expect(find.byType(AddPhoneDialog), findsOneWidget);+ await _joins(tester, app, pub: 'while-open');+ await tester.pump();+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ await _joins(tester, app, pub: 'after-close');+ snapshot.complete({'members': <Object>[]});+ await tester.pump();+ await tester.pump();+ expect(usage.pairings, [AddPhoneOpening.offer]);+ await tester.pumpWidget(const SizedBox());+ },+ );++ for (final from in AddPhoneOpening.values) {+ testWidgets('new phones count once per device from ${from.name}', (+ tester,+ ) async {+ final usage = AddPhoneRecorder();+ final app = createApp(productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ )+ ..api = _DeviceSnapshotApi(+ listing: {+ 'members': [+ {+ 'pub': 'existing',+ 'label': 'Existing phone',+ 'kind': 'viewer',+ 'addedAt': 1,+ 'fingerprint': 'fp',+ 'self': false,+ },+ ],+ },+ );+ addTearDown(app.dispose);+ // A completed handshake alone can be a phone that was already on the account.+ final daemon = _FakeDaemon([() => const PhonePairAnswer.paired('Phone')]);+ await _open(tester, app, daemon.call, from: from);+ await _codeUp(tester);+ expect(usage.pairings, isEmpty);+ await _joins(tester, app, pub: 'existing');+ await _joins(tester, app, pub: 'computer', kind: 'machine');+ await tester.pump();+ expect(usage.pairings, isEmpty);+ await _joins(tester, app, pub: 'new-one');+ await tester.pump();+ expect(usage.pairings, [from]);+ // Remove the banner so the same real notice is emitted again.+ app.newDevices.clear();+ await _joins(tester, app, pub: 'new-one');+ app.notifyListeners();+ await tester.pump();+ expect(usage.pairings, [from]);+ await _joins(tester, app, pub: 'new-two');+ await tester.pump();+ expect(usage.pairings, [from, from]);+ app.currentUser = const CurrentUserProfile(+ id: 'b',+ email: '[email protected]',+ );+ await _joins(tester, app, pub: 'another-account');+ await tester.pump();+ expect(usage.pairings, [from, from]);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ await _joins(tester, app, pub: 'closed');+ expect(usage.pairings, [from, from]);+ await tester.pumpWidget(const SizedBox());+ });+ }++ testWidgets(+ 'an unreadable opening snapshot leaves pairing attribution unknown',+ (tester) async {+ final usage = AddPhoneRecorder();+ final app = createApp(productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ )+ ..api = _DeviceSnapshotApi(fails: true);+ addTearDown(app.dispose);+ final daemon = _FakeDaemon(List.filled(3, _failed('NO_INTENT')));+ await _open(tester, app, daemon.call, from: AddPhoneOpening.offer);+ await _joins(tester, app);+ await tester.pump();+ expect(find.text('Dee’s iPhone is ready.'), findsOneWidget);+ expect(usage.pairings, isEmpty);+ await tester.pumpWidget(const SizedBox());+ },+ );++ testWidgets('a phone joining an open menu dialog counts its source once', (+ 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+ ..signedIn = true+ ..api = _DeviceSnapshotApi()+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ );+ addTearDown(app.dispose);+ await mount(tester, app, nativeTabs: true);+ messenger.handlePlatformMessage(+ channel.name,+ const StandardMethodCodec().encodeMethodCall(+ const MethodCall('addPhone'),+ ),+ (_) {},+ );+ await tester.pump();+ await tester.pump(const Duration(milliseconds: 100));+ expect(find.byType(AddPhoneDialog), findsOneWidget);+ await _joins(tester, app);+ await tester.pump();+ expect(usage.pairings, [AddPhoneOpening.menu]);+ await _joins(tester, app);+ app.notifyListeners();+ await tester.pump();+ expect(usage.pairings, [AddPhoneOpening.menu]);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ await _joins(tester, app, pub: 'after-close');+ expect(usage.pairings, [AddPhoneOpening.menu]);+ await tester.pumpWidget(const SizedBox());+ });+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.diff --git a/desktop/test/phone_offer_test.dart b/desktop/test/phone_offer_test.dartindex 386cf3123..f14d0f247 100644--- a/desktop/test/phone_offer_test.dart+++ b/desktop/test/phone_offer_test.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:flutter/material.dart';import 'package:flutter/rendering.dart';import 'package:flutter_test/flutter_test.dart';@@ -8,8 +10,11 @@ import 'package:harness/core/models.dart';import 'package:harness/measurement/product_measurement.dart';import 'package:harness/shared/theme/app_theme.dart' as grid;import 'package:harness/state/app_state.dart';+import 'package:harness/state/pane_layout_store.dart';import 'package:harness/widgets/add_phone_dialog.dart';import 'package:harness/widgets/phone_offer_card.dart';+import 'package:harness/viewer/viewer_services.dart';+import 'package:harness/viewer/viewer_key_store.dart';import 'support/add_phone_measurement.dart';import 'swarm_screen_test.dart' show mount, terminal;@@ -34,6 +39,15 @@ class _DevicesApi extends ApiClient {Map<String, dynamic>? listing;bool fails;+ void Function()? onRead;+ Future<Map<String, dynamic>?>? profile;+ int profileReads = 0;++ @override+ Future<Map<String, dynamic>?> me() async {+ profileReads++;+ return profile == null ? null : await profile;+ }/// How many times the list was read.int reads = 0;@@ -41,11 +55,21 @@ class _DevicesApi extends ApiClient {@overrideFuture<Map<String, dynamic>?> daemonDevices() async {reads++;+ onRead?.call();if (fails) throw StateError('The network connection was lost.');return listing;}}+class _OnReadStore extends MemoryStore {+ void Function(String)? onRead;+ @override+ Future<String?> read(String key) async {+ onRead?.call(key);+ return super.read(key);+ }+}+Map<String, Object?> _device(String kind, {bool self = false}) => {'pub': 'pub-$kind${self ? '-self' : ''}','label': kind,@@ -89,20 +113,110 @@ void main() {},);- test('a computer that opens signed in has had its first sign-in', () async {- final store = MemoryStore();- final app = createApp(store: store)- ..signedIn = true- ..api = _DevicesApi(_listing([]));- addTearDown(app.dispose);- await app.offerPhoneForTest(atLaunch: true);- expect(app.phoneOfferShowing, isFalse);- await pumpEventQueue();+ test(+ 'a signed-in returning account sees the card once it is on screen',+ () async {+ final store = MemoryStore();+ AppNotifier launch(String id) => createApp(store: store)+ ..signedIn = true+ ..currentUser = CurrentUserProfile(+ id: id,+ email: '[email protected]',+ )+ ..api = _DevicesApi(_listing([]));+ final app = launch('account-a');+ addTearDown(app.dispose);+ await app.offerPhoneForTest(atLaunch: true);+ expect(app.phoneOfferShowing, isTrue);+ expect(store.values['phone_offer_returning.account-a'], isNull);+ expect(store.values[_done], isNull);+ app.phoneOfferShown();+ app.phoneOfferShown();+ await pumpEventQueue();+ expect(store.values['phone_offer_returning.account-a'], '1');expect(store.values[_done], '1');- // So a later sign-in by hand offers nothing either.- await app.offerPhoneForTest(atLaunch: false);- expect(app.phoneOfferShowing, isFalse);- });+ expect(store.values[_seen], '1');+ expect(store.values[_shows], '1');+ final next = launch('account-a');+ addTearDown(next.dispose);+ await next.offerPhoneForTest(atLaunch: true);+ expect(next.phoneOfferShowing, isFalse);+ await next.offerPhoneAfterWorkForTest();+ expect(next.phoneOfferShowing, isFalse);+ final other = launch('account-b');+ addTearDown(other.dispose);+ await other.offerPhoneForTest(atLaunch: true);+ expect(other.phoneOfferShowing, isTrue);+ },+ );++ test(+ 'returning launch retries an unreadable list on the next launch',+ () async {+ for (final api in [_DevicesApi(null), _DevicesApi(null, fails: true)]) {+ final store = MemoryStore();+ AppNotifier launch() => createApp(store: store)+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ )+ ..api = api;+ final first = launch();+ addTearDown(first.dispose);+ await first.offerPhoneForTest(atLaunch: true);+ expect(first.phoneOfferShowing, isFalse);+ expect(store.values['phone_offer_returning.a'], isNull);+ api.fails = false;+ api.listing = _listing([]);+ final next = launch();+ addTearDown(next.dispose);+ await next.offerPhoneForTest(atLaunch: true);+ expect(next.phoneOfferShowing, isTrue);+ expect(api.reads, 2);+ }+ },+ );++ test(+ 'returning launch respects a phone, prior x and every Add Phone opening',+ () async {+ for (final kind in ['phone', 'browser']) {+ final app = createApp(store: MemoryStore())+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ )+ ..api = _DevicesApi(_listing([_device(kind)]));+ addTearDown(app.dispose);+ await app.offerPhoneForTest(atLaunch: true);+ expect(app.phoneOfferShowing, isFalse);+ }+ for (final opening in [null, ...AddPhoneOpening.values]) {+ final store = MemoryStore();+ final first = createApp(store: store);+ addTearDown(first.dispose);+ if (opening == null) {+ first.dismissPhoneOffer();+ } else {+ first.addPhoneOpened(opening);+ }+ final api = _DevicesApi(_listing([]));+ final next = createApp(store: store)+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ )+ ..api = api;+ addTearDown(next.dispose);+ await next.offerPhoneForTest(atLaunch: true);+ expect(next.phoneOfferShowing, isFalse);+ expect(api.reads, 0);+ }+ },+ );test('with nowhere to remember it, nothing is offered', () async {// No state file — a test, a fixture — would mean an offer at every launch.@@ -160,6 +274,422 @@ void main() {});});+ test('a returning launch waits for the asynchronous account profile', () async {+ final profile = Completer<Map<String, dynamic>?>();+ final api = _DevicesApi(_listing([]))..profile = profile.future;+ final store = MemoryStore();+ final app = createApp(store: store)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..api = api;+ addTearDown(app.dispose);+ final offer = app.offerPhoneForTest(atLaunch: true);+ await pumpEventQueue();+ expect(api.profileReads, 1);+ expect(api.reads, 0);+ expect(app.phoneOfferShowing, isFalse);+ profile.complete({'user': {'id': 'loaded-account', 'email': '[email protected]'}});+ await offer;+ expect(app.phoneOfferShowing, isTrue);+ expect(api.profileReads, 1);+ expect(api.reads, 1);+ expect(store.values['phone_offer_returning.loaded-account'], isNull);+ app.phoneOfferShown();+ await pumpEventQueue();+ expect(store.values['phone_offer_returning.loaded-account'], '1');+ });++ test('signing out while the returning profile loads leaves no record', () async {+ final profile = Completer<Map<String, dynamic>?>();+ final api = _DevicesApi(_listing([]))..profile = profile.future;+ final store = MemoryStore();+ final usage = AddPhoneRecorder();+ final app = createApp(store: store, productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..api = api;+ addTearDown(app.dispose);+ final offer = app.offerPhoneForTest(atLaunch: true);+ await pumpEventQueue();+ expect(api.profileReads, 1);+ app.signedIn = false;+ profile.complete({'user': {'id': 'loaded-account', 'email': '[email protected]'}});+ await offer;+ expect(app.phoneOfferShowing, isFalse);+ expect(api.reads, 0);+ expect(store.values, isEmpty);+ expect(usage.skipped, ['not_signed_in']);+ });++ test('a returning launch without a stable account identity offers nothing', () async {+ for (final id in [null, '']) {+ final usage = AddPhoneRecorder();+ final app = createApp(store: MemoryStore(), productMeasurement: usage)+ ..signedIn = true+ ..currentUser = CurrentUserProfile(id: id, email: '[email protected]')+ ..api = _DevicesApi(_listing([]));+ addTearDown(app.dispose);+ await app.offerPhoneForTest(atLaunch: true);+ expect(app.phoneOfferShowing, isFalse);+ expect(usage.skipped, ['not_signed_in']);+ }+ });++ test('a guest launch cannot show after the account lands during its state read', () async {+ final usage = AddPhoneRecorder();+ final store = _OnReadStore();+ final app = createApp(store: store, productMeasurement: usage)..signedIn = false;+ addTearDown(app.dispose);+ store.onRead = (key) { if (key == _done) { app.signedIn = true; } };+ await app.offerPhoneForTest(atLaunch: true);+ expect(app.phoneOfferShowing, isFalse);+ expect(usage.skipped, ['account_changed']);+ });++ test('each offer refusal counts one fixed skip reason without another device read', () async {+ final usage = AddPhoneRecorder();+ final store = MemoryStore()..values[_stopped] = '1';+ final api = _DevicesApi(_listing([]));+ final app = createApp(store: store, productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(id: 'a', email: '[email protected]')+ ..api = api;+ addTearDown(app.dispose);+ await app.offerPhoneForTest(atLaunch: true);+ expect(usage.skipped, ['stopped']);+ expect(api.reads, 0);+ store.values.remove(_stopped);+ await app.offerPhoneForTest(atLaunch: true);+ app.phoneOfferShown();+ expect(usage.started, ['phoneOfferReturning']);+ await app.offerPhoneForTest(atLaunch: true);+ expect(usage.skipped.last, 'card_showing');+ });++ test(+ 'skip reasons distinguish seen, stop, no list, cached phone and read limit',+ () async {+ for (final (values, api, expected) in [+ ({_seen: '1'}, _DevicesApi(_listing([])), 'already_shown'),+ ({_stopped: '1'}, _DevicesApi(_listing([])), 'stopped'),+ (<String, String>{}, _DevicesApi(null), 'no_device_list'),+ (+ <String, String>{},+ _DevicesApi(_listing([_device('phone')])),+ 'has_phone',+ ),+ ]) {+ final usage = AddPhoneRecorder();+ final store = MemoryStore()..values.addAll(values);+ final app = createApp(store: store, productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..api = api;+ addTearDown(app.dispose);+ await app.offerPhoneAfterWorkForTest();+ expect(usage.skipped, [expected]);+ expect(app.phoneOfferShowing, isFalse);+ if (expected == 'no_device_list') {+ for (var i = 0; i < 5; i++) {+ await app.offerPhoneAfterWorkForTest();+ }+ expect(api.reads, 3);+ expect(usage.skipped, [+ 'no_device_list',+ 'read_limit',+ ]);+ }+ if (expected == 'has_phone') {+ await app.offerPhoneAfterWorkForTest();+ expect(usage.skipped, ['has_phone']);+ expect(api.reads, 1);+ }+ }+ },+ );++ test('50 finished own turns count already_shown once for this run', () async {+ final store = MemoryStore()..values[_seen] = '1';+ final usage = AddPhoneRecorder();+ final api = _DevicesApi(_listing([]));+ final app = createApp(store: store, productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..api = api;+ addTearDown(app.dispose);+ app.adoptSessionForTest(terminal('a0', []));+ for (var i = 0; i < 50; i++) {+ await app.handleMachineEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'a0',+ });+ await pumpEventQueue();+ }+ expect(usage.skipped, ['already_shown']);+ expect(api.reads, 0);+ });++ test('an account invalidation permits each path/reason again without retaining old revisions', () async {+ final store = MemoryStore()..values[_seen] = '1';+ final usage = AddPhoneRecorder();+ final app =+ AppNotifier(+ config: AppConfig.dev,+ configStore: null,+ authSession: AuthSession(storage: MemoryStore()),+ paneLayoutStore: PaneLayoutStore(storage: store),+ productMeasurement: usage,+ localManualFixture: const LocalManualFixture(+ apiBaseUrl: 'http://127.0.0.1:9',+ apiKey: 'fixture',+ machineId: 'fixture',+ machineName: 'Fixture',+ ),+ )+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ );+ addTearDown(app.dispose);+ final generation = app.accountGeneration;+ for (var i = 0; i < 50; i++) {+ await app.offerPhoneAfterWorkForTest();+ }+ expect(usage.skipped, ['already_shown']);+ app.expireSessionForTest('Account changed');+ expect(app.accountGeneration, greaterThan(generation));+ app+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'b',+ email: '[email protected]',+ );+ for (var i = 0; i < 50; i++) {+ await app.offerPhoneAfterWorkForTest();+ }+ expect(usage.skipped, ['already_shown', 'already_shown']);+ });++ test(+ 'the same reason counts separately for launch, sign-in and work paths',+ () async {+ final store = MemoryStore()..values[_stopped] = '1';+ final usage = AddPhoneRecorder();+ final app = createApp(store: store, productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true;+ addTearDown(app.dispose);+ app.dismissPhoneOffer();+ for (var i = 0; i < 50; i++) {+ await app.offerPhoneForTest(atLaunch: true);+ await app.offerPhoneForTest(atLaunch: false);+ await app.offerPhoneAfterWorkForTest();+ }+ expect(usage.skipped, ['stopped', 'stopped', 'stopped']);+ },+ );++ test(+ 'a completed sign-in offer counts already_shown once without a device read',+ () async {+ final store = MemoryStore()..values[_done] = '1';+ final usage = AddPhoneRecorder();+ final api = _DevicesApi(_listing([]));+ final app = createApp(store: store, productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..api = api;+ addTearDown(app.dispose);+ for (var i = 0; i < 50; i++) {+ await app.offerPhoneForTest(atLaunch: false);+ }+ expect(usage.skipped, ['already_shown']);+ expect(api.reads, 0);+ },+ );++ test(+ 'a window closed before its launch decision cannot show a card',+ () async {+ final api = _DevicesApi(_listing([]));+ final app = createApp(store: MemoryStore())..api = api;+ app.dispose();+ await app.offerPhoneForTest(atLaunch: true);+ expect(app.phoneOfferShowing, isFalse);+ expect(api.reads, 0);+ },+ );++ for (final path in ['work', 'sign_in', 'launch']) {+ test(+ 'a window closed during the $path device read cannot show a card',+ () async {+ final api = _DevicesApi(_listing([]));+ final app = createApp(store: MemoryStore())+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ )+ ..api = api;+ var closed = false;+ addTearDown(() {+ if (!closed) {+ app.dispose();+ }+ });+ api.onRead = () {+ closed = true;+ app.dispose();+ };+ if (path == 'work') {+ await app.offerPhoneAfterWorkForTest();+ } else {+ await app.offerPhoneForTest(atLaunch: path == 'launch');+ }+ expect(app.phoneOfferShowing, isFalse);+ expect(api.reads, 1);+ },+ );+ }++ test('returning launch reports already shown and the sign-in path respects a prior stop', () async {+ final usage = AddPhoneRecorder();+ final store = MemoryStore()..values['phone_offer_returning.a'] = '1';+ final api = _DevicesApi(_listing([]));+ final app = createApp(store: store, productMeasurement: usage)+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(id: 'a', email: '[email protected]')+ ..api = api;+ addTearDown(app.dispose);+ await app.offerPhoneForTest(atLaunch: true);+ expect(usage.skipped, ['already_shown']);+ store.values[_stopped] = '1';+ await app.offerPhoneForTest(atLaunch: false);+ expect(usage.skipped, ['already_shown', 'stopped']);+ expect(api.reads, 0);+ });++ test('a viewer never offers cards or reads devices', () async {+ final store = MemoryStore();+ final session = AuthSession(storage: store);+ final usage = AddPhoneRecorder();+ final api = _DevicesApi(_listing([]));+ final app =+ AppNotifier(+ config: AppConfig.dev,+ authSession: session,+ viewer: ViewerServices(+ config: AppConfig.dev,+ session: session,+ keys: ViewerKeyStore(storage: store),+ ),+ productMeasurement: usage,+ )+ ..signedIn = true+ ..status = AppStatus.authenticated+ ..api = api;+ addTearDown(app.dispose);+ await app.offerPhoneForTest(atLaunch: true);+ await app.offerPhoneForTest(atLaunch: false);+ await app.offerPhoneAfterWorkForTest();+ expect(app.phoneOfferShowing, isFalse);+ expect(api.reads, 0);+ expect(usage.skipped, ['viewer', 'viewer', 'viewer']);+ });++ test('signing out during each device read cannot show a card', () async {+ for (final path in ['returning', 'sign_in', 'work']) {+ final usage = AddPhoneRecorder();+ final api = _DevicesApi(_listing([]));+ final app = createApp(store: MemoryStore(), productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ )+ ..api = api;+ addTearDown(app.dispose);+ api.onRead = () => app.signedIn = false;+ if (path == 'work') {+ await app.offerPhoneAfterWorkForTest();+ } else {+ await app.offerPhoneForTest(atLaunch: path == 'returning');+ }+ expect(app.phoneOfferShowing, isFalse, reason: path);+ expect(usage.skipped, ['not_signed_in'], reason: path);+ }+ });++ test('Add Phone opened while a card path reads devices stops the pending card', () async {+ for (final path in ['returning', 'sign_in', 'work']) {+ final usage = AddPhoneRecorder();+ final api = _DevicesApi(_listing([]));+ final app = createApp(store: MemoryStore(), productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(id: 'a', email: '[email protected]')+ ..api = api;+ addTearDown(app.dispose);+ api.onRead = () => app.addPhoneOpened(AddPhoneOpening.menu);+ if (path == 'work') { await app.offerPhoneAfterWorkForTest(); }+ else { await app.offerPhoneForTest(atLaunch: path == 'returning'); }+ expect(app.phoneOfferShowing, isFalse, reason: path);+ expect(usage.skipped, ['stopped'], reason: path);+ }+ });++ test('changing accounts before a returning card is shown writes no offer record', () async {+ final store = MemoryStore();+ final usage = AddPhoneRecorder();+ final app = createApp(store: store, productMeasurement: usage)+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(id: 'a', email: '[email protected]')+ ..api = _DevicesApi(_listing([]));+ addTearDown(app.dispose);+ await app.offerPhoneForTest(atLaunch: true);+ app.currentUser = const CurrentUserProfile(id: 'b', email: '[email protected]');+ app.phoneOfferShown();+ await pumpEventQueue();+ expect(store.values[_done], isNull);+ expect(store.values[_seen], isNull);+ expect(store.values['phone_offer_returning.a'], isNull);+ expect(store.values['phone_offer_returning.b'], isNull);+ expect(usage.started, isEmpty);+ });++ test(+ 'another account arriving during a returning read cannot inherit its offer',+ () async {+ final usage = AddPhoneRecorder();+ final store = MemoryStore();+ final api = _DevicesApi(_listing([]));+ final app = createApp(store: store, productMeasurement: usage)+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ )+ ..api = api;+ addTearDown(app.dispose);+ api.onRead = () => app.currentUser = const CurrentUserProfile(+ id: 'b',+ email: '[email protected]',+ );+ await app.offerPhoneForTest(atLaunch: true);+ expect(app.phoneOfferShowing, isFalse);+ expect(usage.skipped, ['account_changed']);+ expect(store.values['phone_offer_returning.a'], isNull);+ expect(store.values['phone_offer_returning.b'], isNull);+ },+ );+group('after work, on a computer that never showed it', () {/// A computer that opened signed in — marked offered at launch, the card never on its screen —/// on an account answering [api], measured by [usage].@@ -174,9 +704,9 @@ void main() {..signedIn = true..api = api;addTearDown(app.dispose);- await app.offerPhoneForTest(atLaunch: true);+ // The historical signed-in launch marked done without ever showing a card.+ kept.values[_done] = '1';expect(app.phoneOfferShowing, isFalse);- expect(kept.values[_done], '1');return (app, kept);}@@ -353,6 +883,7 @@ void main() {_DevicesApi api, {MemoryStore? store,AddPhoneRecorder? usage,+ bool disposeAtTearDown = true,}) async {now = DateTime.utc(2026, 10, 20, 9);state = AppLifecycleState.resumed;@@ -363,7 +894,7 @@ void main() {..api = api..phoneOfferClock = (() => now)..lifecycle = (() => state);- addTearDown(app.dispose);+ if (disposeAtTearDown) addTearDown(app.dispose);return (app, kept);}@@ -635,6 +1166,121 @@ void main() {expect(api.reads, 0);});+ test(+ 'a returning card uses one away-cap slot and suppresses the work card',+ () async {+ final usage = AddPhoneRecorder();+ final (app, store) = await working(+ _DevicesApi(_listing([])),+ usage: usage,+ );+ app.currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ );+ await app.offerPhoneForTest(atLaunch: true);+ app.phoneOfferShown();+ await pumpEventQueue();+ expect(store.values[_shows], '1');+ app.dropPhoneOffer();+ await app.offerPhoneAfterWorkForTest();+ expect(app.phoneOfferShowing, isFalse);+ for (var i = 0; i < 3; i++) {+ leave(app);+ await finishes(app, id: 'return-$i');+ await back(app, const Duration(minutes: 10));+ expect(app.phoneOfferShowing, i < 2);+ if (i < 2) {+ app.phoneOfferShown();+ await pumpEventQueue();+ app.dropPhoneOffer();+ }+ }+ expect(store.values[_shows], '3');+ expect(usage.skipped.last, 'cap_reached');+ },+ );++ test('signing out during the away read records one skip', () async {+ final usage = AddPhoneRecorder();+ final api = _DevicesApi(_listing([]));+ final (app, _) = await working(api, usage: usage);+ api.onRead = () => app.signedIn = false;+ leave(app);+ await finishes(app);+ await back(app, const Duration(minutes: 10));+ expect(app.phoneOfferShowing, isFalse);+ expect(usage.skipped, ['not_signed_in']);+ });++ test('an account whose workspace is not ready skips the away card', () async {+ final usage = AddPhoneRecorder();+ final (app, _) = await working(_DevicesApi(_listing([])), usage: usage);+ leave(app);+ await finishes(app);+ app.status = AppStatus.unauthenticated;+ await back(app, const Duration(minutes: 10));+ expect(app.phoneOfferShowing, isFalse);+ expect(usage.skipped, ['not_signed_in']);+ });++ for (final reason in [+ 'stopped',+ 'cap_reached',+ 'no_device_list',+ 'has_phone',+ 'card_showing',+ ]) {+ test('50 returns after time away count $reason once', () async {+ final usage = AddPhoneRecorder();+ final store = MemoryStore();+ if (reason == 'stopped') {+ store.values[_stopped] = '1';+ }+ if (reason == 'cap_reached') {+ store.values[_shows] = '3';+ }+ final api = _DevicesApi(+ reason == 'no_device_list'+ ? null+ : _listing(reason == 'has_phone' ? [_device('phone')] : []),+ );+ final (app, _) = await working(api, store: store, usage: usage);+ if (reason == 'card_showing') {+ await app.offerPhoneAfterWorkForTest();+ }+ for (var i = 0; i < 50; i++) {+ leave(app);+ await finishes(app, id: 'dedup-$i');+ await back(app, const Duration(minutes: 10));+ }+ expect(usage.skipped, [reason]);+ });+ }++ test(+ 'a window closed during the away device read cannot show a card',+ () async {+ final api = _DevicesApi(_listing([]));+ final (app, _) = await working(api, disposeAtTearDown: false);+ var closed = false;+ addTearDown(() {+ if (!closed) {+ app.dispose();+ }+ });+ api.onRead = () {+ closed = true;+ app.dispose();+ };+ leave(app);+ await finishes(app);+ await back(app, const Duration(minutes: 10));+ expect(app.phoneOfferShowing, isFalse);+ expect(api.reads, 1);+ },+ );+test('a card already up is left as it is', () async {final (app, _) = await working(_DevicesApi(_listing([])));await app.offerPhoneAfterWorkForTest();@@ -866,7 +1512,8 @@ void main() {onAdd: () {},onDismiss: () {},away: (- agent: 'Refactor auth flow and more'.padRight(length, 'x')+ agent: 'Refactor auth flow and more'+ .padRight(length, 'x').substring(0, length),waited: waited,minutes: 21,@@ -919,6 +1566,40 @@ void main() {return (app, store);}+ testWidgets(+ 'the returning card waits for first arrival before recording its account',+ (tester) async {+ final usage = AddPhoneRecorder();+ final store = MemoryStore()..values['first_arrival_v1'] = 'new';+ final app = createApp(store: store, productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(+ id: 'a',+ email: '[email protected]',+ )+ ..api = _DevicesApi(_listing([]));+ addTearDown(app.dispose);+ await app.firstArrival.restore();+ await app.offerPhoneForTest(atLaunch: true);+ await mount(tester, app);+ expect(app.phoneOfferShowing, isTrue);+ expect(find.byType(PhoneOfferCard), findsNothing);+ expect(find.byType(AddPhoneDialog), findsNothing);+ expect(store.values['phone_offer_returning.a'], isNull);+ expect(usage.started, isEmpty);+ app.firstArrival.dismiss();+ app.notifyListeners();+ await tester.pump();+ await tester.pump();+ expect(find.byType(PhoneOfferCard), findsOneWidget);+ expect(find.byType(AddPhoneDialog), findsNothing);+ expect(store.values['phone_offer_returning.a'], '1');+ expect(usage.started, ['phoneOfferReturning']);+ await tester.pumpWidget(const SizedBox());+ },+ );+testWidgets('the card stands in the top-right, and Add Phone opens from it',(tester) async {diff --git a/desktop/test/product_health_test.dart b/desktop/test/product_health_test.dartindex 08370472a..5a73196d7 100644--- a/desktop/test/product_health_test.dart+++ b/desktop/test/product_health_test.dart@@ -63,36 +63,45 @@ void main() {return all;}- test('a first arrival waits for initial consent without observing earlier work', () async {- usage.firstRunStarted();- usage.firstRunReady('m', 'a');- usage.firstRunWork('m', 'a');- usage.firstRunResponse('m', 'a');- await usage.flush();- usage.proxyVocabulary = 5;- await usage.flush();- expect(totals()['health_desktop_first_run_started'], 1);- expect(totals()['health_desktop_first_run_ready'], 1);- expect(totals()['health_desktop_first_run_response'], isNull);- usage.firstRunWork('m', 'a');- usage.firstRunResponse('m', 'a');- await usage.flush();- expect(totals()['health_desktop_first_run_response'], 1);- });+ test(+ 'a first arrival waits for initial consent without observing earlier work',+ () async {+ usage.firstRunStarted();+ usage.firstRunReady('m', 'a');+ usage.firstRunWork('m', 'a');+ usage.firstRunResponse('m', 'a');+ await usage.flush();+ usage.proxyVocabulary = 5;+ await usage.flush();+ expect(totals()['health_desktop_first_run_started'], 1);+ expect(totals()['health_desktop_first_run_ready'], 1);+ expect(totals()['health_desktop_first_run_response'], isNull);+ usage.firstRunWork('m', 'a');+ usage.firstRunResponse('m', 'a');+ await usage.flush();+ expect(totals()['health_desktop_first_run_response'], 1);+ },+ );- test('an initial opt-out discards pending first-arrival eligibility', () async {- usage.firstRunStarted();- usage.firstRunReady('m', 'a');- choice = {'enabled': false, 'revision': 0};- await usage.flush();- choice = {'enabled': true, 'revision': 1};- await usage.flush();- usage.proxyVocabulary = 5;- usage.firstRunWork('m', 'a');- usage.firstRunResponse('m', 'a');- await usage.flush();- expect(totals().keys.where((name) => name.contains('first_run')), isEmpty);- });+ test(+ 'an initial opt-out discards pending first-arrival eligibility',+ () async {+ usage.firstRunStarted();+ usage.firstRunReady('m', 'a');+ choice = {'enabled': false, 'revision': 0};+ await usage.flush();+ choice = {'enabled': true, 'revision': 1};+ await usage.flush();+ usage.proxyVocabulary = 5;+ usage.firstRunWork('m', 'a');+ usage.firstRunResponse('m', 'a');+ await usage.flush();+ expect(+ totals().keys.where((name) => name.contains('first_run')),+ isEmpty,+ );+ },+ );test('first-run response follows only the opened harness and never counts retries twice', () async {await usage.flush();@@ -559,6 +568,98 @@ void main() {);group('Add Phone', () {+ test(+ 'returning flow, every skip and pairing way wait for vocabulary 6',+ () async {+ await usage.flush();+ usage.proxyVocabulary = 5;+ final flow = ProductFlow.values.singleWhere(+ (f) => f.wire == 'phone_offer_returning',+ );+ expect(flow.vocabulary, 6);+ expect(flow.unbounded, isTrue);+ for (final outcome in [+ ProductOutcome.ok,+ ProductOutcome.cancelled,+ ProductOutcome.unknown,+ ]) {+ usage.begin(flow)(outcome);+ }+ for (final reason in [+ 'has_phone',+ 'no_device_list',+ 'already_shown',+ 'stopped',+ 'cap_reached',+ 'not_signed_in',+ 'viewer',+ 'card_showing',+ 'no_storage',+ 'account_changed',+ 'read_limit',+ ]) {+ usage.phoneOfferSkipped(reason);+ }+ usage.phoneOfferSkipped('PRIVATE_CANARY');+ for (final from in AddPhoneOpening.values) {+ usage.addPhonePaired(from);+ }+ final pending = usage.begin(flow);+ now = now.add(const Duration(minutes: 40));+ await usage.flush();+ expect(+ totals().keys.where(+ (n) =>+ n.contains('returning') ||+ n.contains('skipped') ||+ n.contains('paired'),+ ),+ isEmpty,+ );+ usage.proxyVocabulary = 6;+ pending(ProductOutcome.ok);+ await usage.flush();+ await usage.flush();+ expect(totals()['ui_desktop_phone_offer_returning_started'], 4);+ expect(totals()['ui_desktop_phone_offer_returning_ok'], 2);+ expect(totals()['ui_desktop_phone_offer_returning_cancelled'], 1);+ expect(totals()['ui_desktop_phone_offer_returning_unknown'], 1);+ for (final reason in [+ 'has_phone',+ 'no_device_list',+ 'already_shown',+ 'stopped',+ 'cap_reached',+ 'not_signed_in',+ 'viewer',+ 'card_showing',+ 'no_storage',+ 'account_changed',+ 'read_limit',+ ]) {+ expect(totals()['ui_desktop_phone_offer_skipped_$reason'], 1);+ }+ for (final from in AddPhoneOpening.values) {+ expect(totals()['ui_desktop_add_phone_paired_${from.wire}'], 1);+ }+ expect(reports.toString(), isNot(contains('PRIVATE_CANARY')));+ },+ );++ test('new phone counters respect sharing and disposal', () async {+ await usage.flush();+ usage.proxyVocabulary = 6;+ usage.savedChoice({'enabled': false, 'revision': 1});+ usage.addPhonePaired(AddPhoneOpening.offer);+ usage.phoneOfferSkipped('has_phone');+ await usage.flush();+ expect(totals()['ui_desktop_add_phone_paired_offer'], isNull);+ expect(totals()['ui_desktop_phone_offer_skipped_has_phone'], isNull);+ usage.account(null);+ usage.addPhonePaired(AddPhoneOpening.menu);+ usage.phoneOfferSkipped('has_phone');+ });+Iterable<String> addPhoneNames() => totals().keys.where((key) =>key.startsWith('ui_desktop_phone_offer_') ||@@ -681,18 +782,21 @@ void main() {expect(ProductFlow.phoneOfferAwayFinished.unbounded, isTrue);});- test('the card offered after work is not ended by the 15-minute bound', () async {- await usage.flush();- usage.proxyVocabulary = 4;- final card = usage.begin(ProductFlow.phoneOfferAfterWork);- now = now.add(const Duration(minutes: 40));- await usage.flush();- await usage.flush();- expect(totals()['ui_desktop_phone_offer_after_work_unknown'], isNull);- card(ProductOutcome.cancelled);- await usage.flush();- expect(totals()['ui_desktop_phone_offer_after_work_cancelled'], 1);- });+ test(+ 'the card offered after work is not ended by the 15-minute bound',+ () async {+ await usage.flush();+ usage.proxyVocabulary = 4;+ final card = usage.begin(ProductFlow.phoneOfferAfterWork);+ now = now.add(const Duration(minutes: 40));+ await usage.flush();+ await usage.flush();+ expect(totals()['ui_desktop_phone_offer_after_work_unknown'], isNull);+ card(ProductOutcome.cancelled);+ await usage.flush();+ expect(totals()['ui_desktop_phone_offer_after_work_cancelled'], 1);+ },+ );test('the card is not ended by the 15-minute observation bound', () async {await usage.flush();diff --git a/desktop/test/support/add_phone_measurement.dart b/desktop/test/support/add_phone_measurement.dartindex 53bb0d9db..b695a8646 100644--- a/desktop/test/support/add_phone_measurement.dart+++ b/desktop/test/support/add_phone_measurement.dart@@ -12,6 +12,14 @@ class AddPhoneRecorder extends ProductMeasurement {/// Each flow's end, as `flow:outcome`.final ended = <String>[];final openings = <AddPhoneOpening>[];+ final skipped = <String>[];+ final pairings = <AddPhoneOpening>[];++ @override+ void addPhonePaired(AddPhoneOpening from) => pairings.add(from);++ @override+ void phoneOfferSkipped(String reason) => skipped.add(reason);@overridevoid Function(ProductOutcome) begin(ProductFlow flow) {diff --git a/desktop/test/web/phone_offer_web_test.dart b/desktop/test/web/phone_offer_web_test.dartnew file mode 100644index 000000000..7c45bb55d--- /dev/null+++ b/desktop/test/web/phone_offer_web_test.dart@@ -0,0 +1,26 @@+@TestOn('browser')+library;++import 'package:flutter_test/flutter_test.dart';+import 'package:harness/core/models.dart';+import 'package:harness/state/app_state.dart';+import '../support/add_phone_measurement.dart';+import '../swarm_state_test.dart' show createApp, MemoryStore;++void main() {+ test('the web never offers a launch, sign-in or after-work phone card', () async {+ final usage = AddPhoneRecorder();+ final store = MemoryStore();+ final app = createApp(store: store, productMeasurement: usage)+ ..status = AppStatus.authenticated+ ..signedIn = true+ ..currentUser = const CurrentUserProfile(id: 'a', email: '[email protected]');+ addTearDown(app.dispose);+ await app.offerPhoneForTest(atLaunch: true);+ await app.offerPhoneForTest(atLaunch: false);+ await app.offerPhoneAfterWorkForTest();+ expect(app.phoneOfferShowing, isFalse);+ expect(store.values['phone_offer_returning.a'], isNull);+ expect(usage.skipped, ['viewer', 'viewer', 'viewer']);+ });+}diff --git a/docs/design/2026-10-20-desktop-phone-conversion.md b/docs/design/2026-10-20-desktop-phone-conversion.mdindex 459ca54c9..893913275 100644--- a/docs/design/2026-10-20-desktop-phone-conversion.md+++ b/docs/design/2026-10-20-desktop-phone-conversion.md@@ -33,11 +33,35 @@ first. For those people, the only way to Add Phone was the title bar's icon, the## What is built-The same top-right card (`PhoneOfferCard`) as the first offer, at two new moments. Nothing else in the window+The same top-right card (`PhoneOfferCard`) as the first offer, at the moments below. Nothing else in the windowchanges, and Add Phone opens the same dialog. The card stands below the top-right pane's header(`AgentAlertBanners.footerDrop`), not over it: it stays until it is answered, and at the corner it covered thatpane's model and its ×, often the very pane waiting on the person.+### 0. Once at a returning account's signed-in launch (owner, 2026-10-26)++The October 26 daily report found no accounts with an older computer adding their first phone in four days,+among 307 accounts. The existing paths rarely ran for those people. This owner decision supersedes the+October 9 rule that an already-signed-in launch only marks the offer done for this case.++Offer the existing card once per account on this computer when the launch is already signed in, the account+has no non-machine device other than self in `loadDevices()`, no card has been dismissed with × and Add Phone+has never been opened here (`phone_offer_stopped`), this is neither web nor a viewer window, and no other+phone card is showing. Historical `phone_offer_done` and `phone_offer_seen` do not rule out this returning+account's launch offer. The account needs a stable identity and local state that can be read. The offer waits for the existing+asynchronous profile load, without delaying the workspace; an unavailable identity records no offer.++It is a card, never an automatic dialog, and waits for first arrival just like the existing card.+Write `phone_offer_returning.<account id>` only when `phoneOfferShown` says it is on screen. Closing the app+with it unanswered does not bring that launch card back. Closing before it is on screen leaves it eligible.+An unreadable device list (including an older CLI) shows nothing and writes no returning record, so the next+launch tries again. This path reads devices at most once per launch. It does not add reads to the existing+after-work retry limit.++Showing it writes `phone_offer_seen` to suppress the after-work card and increments `phone_offer_shows`.+The away card remains eligible until that combined count reaches three, or × / Add Phone stops it.+The returning flow is `phone_offer_returning`, with the same outcomes and no observation timeout.+### 1. Once after work, on a computer that never showed the cardA computer that has never shown the card gets it **once**, right after one of the person's own harnesses on it@@ -82,7 +106,7 @@ told them while they were away:- Only on an account with **no phone or browser** yet (`loadDevices`). No list to judge by: no card this time.An account found to have one is not read again in that run: each read reaches the backend through the daemon.-- **At most 3 cards per computer**, every kind together (the first offer, after work, after time away).+- **Away cards stop at 3 combined showings per computer**, including the first offer, returning offer and after-work offer. The returning launch offer is once per account on that computer.- **× or Add Phone opened (from the card or any other way in) stops the cards on this computer for good.**- A card left unanswered stays on screen until the app closes or the person signs out. On a later run, the cardafter time away may come back, until the 3-card cap.@@ -99,7 +123,8 @@ In the Desktop's local state file (`LocalKeyValueStore`, beside the dial's state| Key | Written when | Read by ||---|---|---|-| `phone_offer_done` (existing) | Add Phone opened, card put away, account has a phone, or a signed-in launch | the first offer |+| `phone_offer_returning.<account id>` | returning card on screen, once per account locally | signed-in returning launch |+| `phone_offer_done` (existing) | Add Phone opened, card put away, the first sign-in finds a phone, or the returning card is on screen; older versions wrote it at signed-in launch | the first offer || `phone_offer_seen` | any card on screen, or Add Phone opened | the card after work || `phone_offer_stopped` | the card's ×, or Add Phone opened any way | the card after time away || `phone_offer_shows` | every card on screen, counted | the card after time away (cap 3) |@@ -113,6 +138,7 @@ Each card is its own flow, so the moments compare with each other and with the f| Flow | Card ||---|---|| `phone_offer` | the first offer (existing) |+| `phone_offer_returning` | once at a returning account’s signed-in launch (vocabulary 6) || `phone_offer_after_work` | once after work || `phone_offer_away_waited` | back to a harness that waited || `phone_offer_away_finished` | back to a harness that finished |@@ -169,3 +195,23 @@ A Desktop released first still offers the cards; its counts wait for the CLI.- Away time follows the window (`appLifecycleChanged`), not the person. A window left behind another app for 5minutes while the person sat at the computer counts as away. The card then says what happened, which stays true.- Counts are per computer, not per person: a person with two computers can see up to 3 cards on each.++## October 26 measurement additions++Vocabulary 6 adds the returning flow, `ui_desktop_phone_offer_skipped_<reason>`, and+`ui_desktop_add_phone_paired_<opening>`. The fixed reason list and precise count semantics are in+[product measurement](../product-measurement.md). The CLI forwards the names and announces revision 6;+Desktop queues them until then. Backend and CLI vocabularies remain identical.++The dialog already receives live `deviceJoins` notices. Open the dialog immediately and read one account-device+snapshot alongside it. Hold joins until the snapshot arrives, then count each new non-machine key once per+dialog, excluding keys already in that snapshot. Keep the+snapshot and deduplication set in RAM; report only the opening (`offer`, `titlebar`, `menu`, `account`,+`machines`, `command`). A returning card uses `offer`. Repeated notices, rebuilds, machines, notices after+close and another account's notices do not count. A second new phone does. An unreadable snapshot leaves+attribution unknown and keeps the dialog usable; a successful pairing handshake alone is not proof of a+new account device.++Skip reasons count each path/reason pair once per app run. An auth-revision change clears the counted pairs,+allowing the next account to count again without retaining old revisions. Finished-turn volume and repeated+returns to the window do not inflate these counters. Fixed names and vocabulary 6 remain unchanged.diff --git a/docs/product-measurement.md b/docs/product-measurement.mdindex 4a2ab21e8..6b57b0f14 100644--- a/docs/product-measurement.md+++ b/docs/product-measurement.md@@ -22,7 +22,36 @@ automatically proven improvement. Changes still need review, tests and a deliber| Where does the phone's onboarding stall? | After sign-in: waiting for the first computer, opening its session, the first message, the notification prompt. A sign-in that went through, by button, counted again under the account's sharing. Waits past a minute split into 1–5 min, 5–15 min, 15 min–1 h and over 1 h for the computer and the first message. Once per step per sign-in: `resumed` (reopened in a run that did not sign in), "Not you? Sign out", the address sent from the share sheet, a joining computer that wants its password or is offline, `joined_after_leaving` (the computer turned up after the app left the wait), `new_account` (a sign-in that created the account). Once per install: `first_open` (signed out `setup_phone_first_open`, signed in `ui_phone_first_open`) | Stage totals per day, not a linked funnel. A wait's `ok` is a computer that turned up while its screen was open: add `joined_after_leaving` for the computers that came while the app was away (16–19 October 2026: 5 `ok` in 49 fresh waits, while 91% of the phone's people had a computer on the same account). `new_account` is an account minutes old at sign-in, its first Harness sign-in anywhere. `first_open` is set once per install by a local flag that is never sent: the step between a store's download and a sign-in. Subtract `resumed` from starts for fresh starts; an unmatched start is a closed app or a step still waiting. A resumed step's duration starts at the reopening. Signed-in sign-in counts are successes only; failures and cancels before an account remain the signed-out counts', but a success is marked `retried` (a failed or cancelled try came first in that app run) or `switched` (another button was tried first). Phone reports carry release and iOS/Android, so every phone count also splits by those two margins (above 20 collector days); debug builds are not kept. A chosen sign-out sends what is queued first (up to 2 s), so "Not you? Sign out" reaches the totals. The first message is the first line sent after the hand-over in any session, or a task typed into New Harness; before 2026-10-20 only the session the hand-over opened counted and leaving it cancelled the step (compare releases separately). Each step of a sign-in that created its account is marked `new_account` when counted and `new_account_ok` when it ends ok, so new people's funnel reads apart. The phone sends what it queued as it leaves the screen, since iOS can end a suspended app with its counts still in RAM. || How fast does the phone get back to work? | A launch that came back signed in, to its first computer answering (`app_start`); a dial the person asked for ("Try again", `connect_user`) apart from the app's own (`connect_auto`), beside the unchanged `remote_connect`; a stopped harness resumed from the phone, to its first live turn (`resume_recovery`) | A launch that signs in is the onboarding's and is not counted; one that leaves the screen before a computer answers (the app hidden, at the latest sent to the background) is `unknown`, one whose computers never answer stays started. What a launch waited on is counted beside it, once each, until a computer answers or the app leaves the screen (`ui_phone_app_start_<why>`): `no_computer` and `list_failed` (the account's list had none, or could not be read), `offline` (it said every computer was offline), `locked` (a computer wanted the phone's password), `connect_failed` (a dial to a computer said to be online failed) and `waited_1m` (a minute on screen); a launch can name several. An asked-for dial fails at 12 s, as Desktop Connect does. A phone dial is `failed` only when the phone knows why (locked or offline), `unknown` otherwise; the reasons (`connect_error_*`) are Desktop health counters. The phone's `remote_connect` is one computer's socket dialling, from connecting or reconnecting until it connects (`ok`) or drops (`failed`). `cancelled` is a dial still going when the app went to the background (the pause, not the app switcher or a system sheet): a suspended app never hears the socket's answer, so the dial ends there rather than staying without an outcome, and a dial after the app is back is a new count. The two dials beside it end the same way: a `connect_auto` or `connect_user` dial still going at the pause is `cancelled`, an asked-for dial's 12 s deadline goes with it, and the socket's answer after the pause counts nothing more. From build 72, the release after 1.0.8 (71), a `remote_connect`, `connect_auto` or `connect_user` dial still in progress when the app goes to the background ends `cancelled`; earlier builds, 1.0.8 (71) included, left it without an outcome (79 of the 252 `remote_connect` dials on 2026-10-20): compare releases separately. || 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. A computer that opened signed in was marked offered without ever showing the card; from 2026-10-20 it shows the card once after one of its own harnesses finishes a turn, if the account has no phone or browser, counted apart as `ui_desktop_phone_offer_after_work_*` (vocabulary 4). The same card also shows to a person back after 5 minutes or more away to one of their harnesses that waited on them or finished meanwhile, counted as `ui_desktop_phone_offer_away_waited_*` / `ui_desktop_phone_offer_away_finished_*` (vocabulary 4): at most 3 cards a computer, every kind together, and none once a card's × or Add Phone was used there ([design](design/2026-10-20-desktop-phone-conversion.md)). The browser counts none. Vocabulary 3: counted from the start, but sent only once the local CLI has answered that it forwards them, so a Desktop on an older CLI sends none. |+| Does Desktop's Add Phone card get used, why is it skipped, and which opening leads to a new phone? | Each card has its own flow: `ui_desktop_phone_offer_*`, `phone_offer_returning_*`, `phone_offer_after_work_*`, `phone_offer_away_waited_*`, `phone_offer_away_finished_*` (all have the `ui_desktop_` prefix). `started` is on screen, `ok` its Add Phone, `cancelled` its ×, `unknown` another dismissal. Openings: `ui_desktop_add_phone_<offer\|titlebar\|menu\|account\|machines\|command>`. New phones: `ui_desktop_add_phone_paired_<same opening>`. Skips: `ui_desktop_phone_offer_skipped_<reason>` (below). | From 2026-10-26, a signed-in returning account gets the existing card once per account on this computer, only with no phone or browser and no prior × or Add Phone opening. It waits for first arrival; the local account record is written only on screen, so an unanswered card does not return at launch. An unreadable device list records nothing and retries next launch. Showing it spends the after-work offer and one slot of the away-card cap. All card flows are unbounded. The returning flow, skips and pairing counts wait in RAM for CLI vocabulary 6; older names keep their existing vocabulary. The browser counts none. See the [design](design/2026-10-20-desktop-phone-conversion.md). |++The daily product review shows `addPhonePaired` and `phoneOfferSkipped` beside `addPhoneOpenings` on its+`ui`/`desktop` `phone_offer` flow, with zero for missing opening or reason counters.++Add Phone skip reasons are a fixed list: `has_phone` (including a cached answer), `no_device_list`,+`already_shown` (a stored showing or the completed after-work decision), `stopped` (× or Add Phone opened),+`cap_reached` (the away card's combined show count is three), `not_signed_in` (including a missing account+identity or a workspace not ready), `viewer` (web or viewer window), `card_showing`, `no_storage` (missing or+unreadable local state), `account_changed` (the original account/work is no longer current), and `read_limit`+(after-work's three unanswered reads in this run). Count each path/reason pair at most once per app run.+Account-work invalidation clears the counted pairs, so another account can count again and old revisions do+not accumulate. A counter means a launch where that reason blocked that path, rather than a number of turns+or returns to the window; the same reason can count once for each distinct path. Fixed reason names and+vocabulary 6 are unchanged. No account or device identifiers, names, card text, or error content are reported.+The first sign-in path keeps+its existing fallback of offering a card when its device list cannot be read; that is an offer, not a skip.++A pairing counter uses the existing live account-join signal, only while the Add Phone dialog is open and+signed in. The dialog opens immediately while a known-key snapshot is read alongside it. Joins received+before the snapshot are held until it arrives; keys in that snapshot never count. It excludes computers and counts+each new device key once even if its notice repeats or the dialog rebuilds. A handshake alone may be an+existing phone and does not count. A second new phone can count in the same dialog. Attribution is omitted+when the opening snapshot fails or is null, the account identity is unavailable, or the account changes.+A join received while open can be attributed after closing once its snapshot arrives; notices received after+closing do not count. The snapshot never delays opening the dialog.+The snapshot and deduplication keys stay in RAM, outside the report. Returning cards use the `offer` opening;+their separate flow identifies the card. Openings measure dialogs, pairing counters measure new account keys,+and neither proves that the phone subsequently used a harness.+| Is measurement losing coverage? | Updated collector installation-days, pruned queues, full observation maps, unmatched app starts | Loss signals warrant caution. No signal does not prove complete collection. || How many people use Harness, and do they come back? | People active / working / new per day and per app, and D1/D2/D3/D7 returns (backend rollup of 10-day pseudonymous marks) | Sharing accounts only, staff excluded; an app open across midnight counts on both days, so prefer working returns. Not available before `PRODUCT_USAGE_SUBJECT_KEY` is set. || What do people do on the Hub? | Page views by page and signed-out/signed-in reader, the first page of a tab's visit by where it came from (direct, search, social, internal, other; classified in the browser, the referrer is never sent), clicks and submits (search, sort, like, comment, share, fork, follow, report, sign-in prompt, publish), and how long a harness page stayed visible (under 10 s, 10 s–1 min, over 1 min). A shared link (`/s/:id`, the web app) counts the same way: the page drawn by reader, what it showed (live, owner offline, private, no access, failed), how long a live harness stayed visible, and its clicks (comments, comment posted, sign-in, retry, Download app, product page), plus once when its live viewer draws | Unlinked daily totals of views, entries, clicks and dwell buckets: not people, not a funnel. Public counts that can be fabricated; directional only. Browsers sending Global Privacy Control or Do Not Track, and signed-in readers who turned sharing off, are not counted. The website's server strips cookies and auth before forwarding. |diff --git a/mobile/RELEASE.md b/mobile/RELEASE.mdindex 9764a0635..c1f1fdde3 100644--- a/mobile/RELEASE.md+++ b/mobile/RELEASE.md@@ -140,9 +140,11 @@ may lack symbolicated stacks until the matching symbols are supplied.| `1.0.7 (69)` | 2026-10-19 | TestFlight. Desktop's harness actions on the phone: clone, fork, change agent, delete with its conversation, stop once its task is done; the New form attaches files, starts a Terminal and says what a held creation waits on; find in terminal; any file sent from the key bar; native-style key caps; hardware-keyboard paste; media previews in the app; remote panes recover after their stream dies; Settings ▸ About links the privacy policy. Went up as 1.0.7 straight away, since 1.0.6 had been submitted. Built from `feat/mobile-ios-android` at `1d2466de` || `1.0.7 (70)` | 2026-10-19 | TestFlight, then submitted for App Store review as 1.0.7. The first set-up step reads "Download and install Harness"; terminal menu rows lose their trailing …. Built from `feat/mobile-ios-android` at `1d4ca45c` || `1.0.8 (71)` | 2026-10-20 | TestFlight. A + after Find's tab chips opens a new harness in a tab of its own; a held New Harness stops asking once Cancel is pressed, and a launch back to work says what it waited on; a locked Harness OS computer set up on its hotspot in one stay; a spoken sign-in code for devices with no screen; parked machines rechecked less often and not in the background; counts flushed on background, first open, new accounts and testers measured. 1.0.7 had been approved, so it went up as 1.0.8. Built (by another session) from `feat/mobile-ios-android` at `7849fd00`. Approved and on sale on the App Store: released 2026-10-20 22:09 UTC (App Store Connect: 1.0.8 `READY_FOR_SALE`, build 71) |+| `1.0.9 (72)` | 2026-10-21 | TestFlight, then submitted as 1.0.9. The system banner shows while the app is open, and agent questions and turn tiers reach phones over the relay; faster terminal typing over P2P; Change agent hands over the conversation and can switch a busy Claude harness; a Harness OS computer's Version page, its update's restart and Unlock after one; Set up a device under Add computer; a desk tab renamed or closed by holding its chip in Find. Built from `feat/mobile-ios-android` at `9c329760`, the merge of local `main` with origin's #1499 |+| `1.0.10 (73)` | 2026-10-23 | TestFlight. The phone's first session: task chips, one suggestion with a Send button, the keyboard over its task and a mic that sends the prompt, and Desktop's engine choice; a Harness OS computer signed out, its password changed, SSH turned on; Version lists releases and takes a newer OS release only; a pasted image waits for its transcode before uploading. 1.0.9 had been submitted, so it went up as 1.0.10. Built from `feat/mobile-ios-android` at `3c024672` |-`pubspec.yaml` is now at `1.0.9+72`, the next build number. Build 71 (1.0.8) is the last upload, to both-TestFlight and Play (54 went up outside this record, 53 went to Play only); do not upload any of them again. 1.0.1 to 1.0.8 are approved, so new builds go up as 1.0.9 until it is approved too. Check App Store Connect before uploading if another release has happened meanwhile.+`pubspec.yaml` is now at `1.0.10+74`, the next build number. Build 73 (1.0.10) is the last build, for both+TestFlight and Play (54 went up outside this record, 53 went to Play only); do not upload any of them again. 1.0.1 to 1.0.8 are approved and 1.0.9 is submitted, so new builds go up as 1.0.10 until it is submitted or approved too. Check App Store Connect before uploading if another release has happened meanwhile.### Why the app is iPhone-only@@ -369,3 +371,5 @@ account (Autonomous Inc.) is exempt — check which kind the account is before p| `68` (1.0.6) | 2026-10-16 | Built, same code as iOS 1.0.6 (68); to be uploaded by hand || `70` (1.0.7) | 2026-10-19 | Production, sent for review. Same code as iOS 1.0.7 (70): desktop's harness actions (clone, fork, change agent, delete), files in the New form and from the key bar, find in terminal, hardware-keyboard paste, panes that recover after their stream dies || `71` (1.0.8) | 2026-10-20 | Built by another session, same code as iOS 1.0.8 (71); uploaded by hand to Production (reported by the release owner on 2026-10-21) |+| `72` (1.0.9) | 2026-10-21 | Built, same code as iOS 1.0.9 (72); uploaded by hand, the track it went to is not recorded |+| `73` (1.0.10) | 2026-10-23 | Built, same code as iOS 1.0.10 (73); to be uploaded by hand |diff --git a/mobile/android/app/build.gradle.kts b/mobile/android/app/build.gradle.ktsindex 4c62fafb2..be611dcfd 100644--- a/mobile/android/app/build.gradle.kts+++ b/mobile/android/app/build.gradle.kts@@ -43,6 +43,11 @@ android {// needs to rise with every upload.versionCode = flutter.versionCodeversionName = flutter.versionName+ // A copy that installs beside the Play one, for the on-device benchmarks+ // (mobile/integration_test/README.md): `-P harnessIdSuffix=.bench`. A local build cannot+ // replace a Play install — Play re-signs the app with a key only Google holds — and+ // uninstalling it to make room signs the phone out.+ (project.findProperty("harnessIdSuffix") as String?)?.let { applicationIdSuffix = it }}signingConfigs {diff --git a/mobile/integration_test/README.md b/mobile/integration_test/README.mdindex fdcde06e0..6578b312d 100644--- a/mobile/integration_test/README.md+++ b/mobile/integration_test/README.md@@ -114,6 +114,88 @@ It pools every measured observation and every frame across the runs in thedirectory, then takes percentiles — it never averages percentiles — and printsmarkdown tables, plus each run's timeline rankings.+## Claude Code's fullscreen scroll++`claude_scroll_test.dart` measures one thing against what a native list does:+the rows that scroll move as far as the finger every frame, and stop when it+does. The production `TerminalView`, set up for Claude Code as `TerminalPanel`+sets it up (the `RemoteScrollMirror`, page keys, `RemoteScrollPhysics`), in a+profile build, touched through the device's own dispatch (`perf/gestures.dart`).+Per scenario — the first drag on a freshly opened terminal, slow reading drags,+flicks up after reading, flicks on into rows nobody fetched, flicks back down —+it reports how far the content went against the finger (`rowsBehind`), frame by+frame (`errorRows*`), frames it stood still under a moving finger+(`stalledFrames`), lurches past it (`jumpFrames`), movement after the finger and+its fling stopped (`rowsAfterStop`), when the mirror first drew+(`firstMirrorFrameMs`), and the engine's frame timings.++Behind the terminal is Claude Code 2.1.309's fullscreen renderer faked in the+app (`claude_scroll/program.dart`: wheel acceleration, a dropped wheel after a+turn, Page Up/Down by half the transcript, a pinned prompt and "Jump to bottom"+line, its layout under the transcript), across a link of+`CLAUDE_FAKE_ONE_WAY_MS` each way (30) with a redraw of `CLAUDE_FAKE_DRAW_MS`+(40). The same every run, so two builds compare.++```sh+flutter build ios --profile --target=integration_test/claude_scroll_test.dart++HARNESS_SCROLL_LABEL=after \+flutter drive --profile --no-dds --keep-app-running \+ --use-application-binary=build/ios/iphoneos/Runner.app \+ --driver=test_driver/claude_scroll_driver.dart \+ --target=integration_test/claude_scroll_test.dart \+ -d <device id>+```++Results go to `build/claude_scroll/<label>-<UTC time>.json` with every frame's+sample and the mirror's trace; the driver prints the per-scenario medians.+`CLAUDE_SCROLL_ROUNDS` (3) and `CLAUDE_SCROLL_SCENARIOS` (name prefixes) are+`--dart-define`s on the build line. Like the benchmark above it replaces the+app on the phone: reinstall the development build afterwards.++`claude_scroll_app_test.dart` measures the same in the REAL app, end to+end: it starts the app as a tap on its icon would, with the phone's own+sign-in, opens one of the owner's own Claude Code agents over the real link,+takes its terminal as "Take control" does, puts the keyboard away, and runs+the same scenarios. `CLAUDE_AGENT_NAME` is a comma-separated list of agent+names tried in turn: the first with 300 rows above its screen once it has+fetched ahead is measured, else the one with most. The phone must already be+signed in. Opening an agent takes its pane at the phone's size, as opening it+by hand does, and the scroll sends it wheel events and Page Up/Down — nothing+is typed; pick agents that are idle.++```sh+flutter build ios --profile --target=integration_test/claude_scroll_app_test.dart \+ --dart-define=CLAUDE_AGENT_NAME="T- 300,Testing with Claude Code"+HARNESS_SCROLL_LABEL=app flutter drive --profile --no-dds --keep-app-running \+ --use-application-binary=build/ios/iphoneos/Runner.app \+ --driver=test_driver/claude_scroll_driver.dart \+ --target=integration_test/claude_scroll_app_test.dart -d <device id>+```++With a real program the newest row is not known: frames past it count as+stalled in `flick_down`. The oldest is, once a page up has gone nowhere.++What these measured before and after the mirror's rework, on an iPhone 14 and+a Galaxy S23, over Wi-Fi and 4G: `claude_scroll/RESULTS.md`.++⚠️ **On Android, always `--keep-app-running` and a prebuilt APK.** `flutter+drive` uninstalls the app when it finishes, and on the first build — no APK yet+— it takes the package from the source manifest: it uninstalled a Play-installed+Harness that way (2026-10-24). A local build cannot replace the Play install+(Play re-signs it with Google's key); to run beside it, build with+`--android-project-arg=harnessIdSuffix=.bench` and check the package with+`aapt2 dump badging` before installing. A copy beside the Play one has its own+sign-in.++`CLAUDE_SCROLL_PROGRAM=live` puts the real Claude Code behind it instead: the+phone listens on `CLAUDE_BRIDGE_PORT` (8765) and prints its addresses, and+`claude_scroll/claude_bridge.py` on a Mac connects to it, runs+`claude --resume <session>` in a pseudo terminal at the phone's grid and holds+every byte `CLAUDE_BRIDGE_DELAY_MS` each way. Nothing on the Mac listens, and the+bridge passes only wheel reports and Page Up/Down to Claude Code. Resume a+session no agent is using, in a folder Claude Code already trusts.+## Files- `perf_test.dart` — entry point; one test that runs the suite.@@ -130,3 +212,6 @@ markdown tables, plus each run's timeline rankings.- `../scripts/perf_summarize.py` — the summarizer.- `../test/perf_fixture_test.dart` — the fixture's assumptions, and that anidle terminal page asks for no frames, on every `flutter test`.+- `claude_scroll_test.dart`, `claude_scroll_app_test.dart`, `claude_scroll/`+ and `../test_driver/claude_scroll_driver.dart` — Claude Code's fullscreen+ scroll, above; `claude_scroll/RESULTS.md` — its results.diff --git a/mobile/integration_test/claude_scroll/RESULTS.md b/mobile/integration_test/claude_scroll/RESULTS.mdnew file mode 100644index 000000000..b5d28fd2d--- /dev/null+++ b/mobile/integration_test/claude_scroll/RESULTS.md@@ -0,0 +1,131 @@+# Claude Code scroll: why it changed, and what it measures now++Measured 2026-10-24 on an iPhone 14 (60 Hz) and a Galaxy S23 (120 Hz), profile+builds, touched through the device's own dispatch (`../perf/gestures.dart`).+**Old** is `3c024672b` on `feat/mobile-ios-android`; **new** is the commit that+added this file. How to run each benchmark: `../README.md`, "Claude Code's+fullscreen scroll". Raw results land in `build/claude_scroll/` and are not+committed.++- **Follow** — how far the content moved against the finger; 100% is a native+ list.+- **Drift** — rows the content kept moving after the finger and its fling+ stopped.+- **Stalled** — frames the content stood still under a moving finger.+- Ranges span the 2–3 rounds of one run.++## What was wrong++The phone draws Claude Code's fullscreen scroll from a local mirror of its rows+and asks Claude Code for more with wheel events and Page Up/Down. The old+mirror:++- moved the content 11–78% of the finger on the first drag after an agent+ opened, then drifted up to 6.5 rows. It did not know which rows scroll+ until Claude Code had answered a scroll;+- followed the first flicks at 28–67%. It asked one page per round trip, and+ only once the finger reached the last row it knew;+- stalled 76–287 frames on a flick back down to the newest row.++Frame rendering was not the cause. The Play build, with the old code,+presented 107–116 fps on the S23 while the content moved (SurfaceFlinger+`--latency`). In the benchmark, both builds build 96–99% of frames inside the+8.3 ms budget on slow reading drags.++## What changed++In `third_party/xterm/lib/src/ui/` (`remote_scroll_mirror.dart`,+`scroll_handler.dart`, `render.dart`); entry 21 of+`third_party/xterm/README.autonomous.md`.++| Change | Why |+|---|---|+| The next page is asked when the finger is within 80 ms of the last known row | a fling no longer waits a round trip at each edge |+| Up to 3 Page Up/Down sent in one batch, where they land among rows already known | one round trip instead of three |+| Which rows scroll is read off the prompt box once Claude Code has been quiet 300 ms | the first drag moves 1:1 |+| 400 rows above fetched 500 ms after opening (was 120 rows after 1200 ms) | the first flicks find rows already there |+| The blank row over the prompt box never counts as a scrolling row | it is the same in every frame, so it looked like one |+| "Quiet" waits 1.25× the measured answer time, at most 1 s | a slow link's late answer is not taken for a new frame |+| While the spring catches up, a finger move reaches the screen in the same frame | removes a lag that grew with finger speed |+| A Page Up that moves nothing marks the top of the transcript | flicks at the top stop on the top row |+| Frames placed by row-signature votes (`bestPlacing`) | same answer as trying every placing, less work |+| The mirror exists from the first frame for Claude Code terminals | the first drag is drawn from it too |++## Results++### iPhone 14, fake Claude Code, ~100 ms an answer++| Scenario | Old | New |+|---|---|---|+| First drag | 29–44%, drift ≤ 4 rows | **100%**, drift 0.4 |+| Reading drag | 100% | 100% |+| Flick up | 28–49% | **75–78%** |+| Flick on into unfetched rows | 38–45% | **64–67%** |+| Flick back down | 57–63%, 76–124 stalled | **100–101%**, 0 stalled |++### iPhone 14, fake Claude Code, slow link (~200 ms round trip)++| Scenario | Old | New |+|---|---|---|+| First drag | 27–38% | **100%** |+| Reading drag | 99–100%, 9–12 stalled | 100%, 0 stalled |+| Flick up | 31–35% | **65–67%** |+| Flick on into unfetched rows | 29–30% | 33–38% |+| Flick back down | 101% | 101% |++### iPhone 14, real app, a real agent over the real link++Its transcript was about 200 rows, so flicks reached its top in both builds.++| Scenario | Old | New |+|---|---|---|+| First drag | 11%, drift 6.5 rows | **100%**, drift 0.4 |+| Flick up, before / after the same-frame finger move | 50–51%, error p95 4.8–5.0 rows | **101–102%**, error p95 0 |++### Galaxy S23, fake Claude Code++| Scenario | Old | New |+|---|---|---|+| First drag | 33–40%, drift 3.6–4.2 rows | **100%**, drift 0.3 |+| Reading drag | 100% | 100% |+| Flick up | 45–51% | **72–82%** |+| Flick on into unfetched rows | 42–45% | **57–73%** |+| Flick back down | 54–63%, 197–287 stalled | **97–101%**, 0–22 stalled |++### Galaxy S23, real app, a real agent with 408 rows above, Wi-Fi++First round / second round.++| Scenario | Old | New |+|---|---|---|+| First drag | 78%, drift 3.5 / 92%, drift 1.9 | **100%**, drift 0.3 / 100% |+| Reading drag | 100% / 101% | 100% / 100% |+| Flick up | 67% / 91% | **97%** / 103% |+| Flick on into unfetched rows | 63% / 92% | **99%** / at the top |+| Flick back down | 88%, 26 stalled / 97%, 44 stalled | **101%** / 101% |++### Galaxy S23, real app, same agent, 4G (LTE, ping 51–196 ms, average 123)++First round / second round.++| Scenario | Old | New |+|---|---|---|+| First drag | 77%, drift 3.4 / 92%, drift 2.0 | **100%**, drift 0.3 / 100% |+| Reading drag | 100% / 100% | 100% / 100% |+| Flick up | 52% / 91% | **93%** / 101% |+| Flick on into unfetched rows | 46% / 63% | **72%** / 101% |+| Flick back down | 63%, 207 stalled / 83%, 169 stalled | **95%**, 89 stalled / 101%, 0 stalled |++Not measured: a very weak or lossy link (3G, packet loss), and whether 4G+went peer to peer or through the relay.++## Tests++- `test/remote_scroll_mirror_test.dart`: 14 tests against a fake Claude Code.+ Covers `bestPlacing` against brute force, the fling page lead, reattaching+ from memory, trimming on a long read, prompt-box seeding and prefetch,+ multi-page batches, never blanking a row, getting back to the newest row, a+ slow link, the chase following the finger, and a busy program not being+ seeded. Each fix was reverted once to check its test fails.+- `flutter test` on the 73 test files that touch the terminal: 1269 passed,+ 27 skipped, 0 failed. `flutter analyze` on the changed files: no issues.diff --git a/mobile/integration_test/claude_scroll/bench.dart b/mobile/integration_test/claude_scroll/bench.dartnew file mode 100644index 000000000..431a48414--- /dev/null+++ b/mobile/integration_test/claude_scroll/bench.dart@@ -0,0 +1,729 @@+import 'dart:math' as math;+import 'dart:ui' as ui;++import 'package:flutter/material.dart';+import 'package:flutter/scheduler.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/terminal/remote_scroll_physics.dart';+import 'package:harness_mobile/terminal/terminal_font_store.dart';+import 'package:harness_mobile/terminal/terminal_typography.dart';+import 'package:wakelock_plus/wakelock_plus.dart';+import 'package:xterm/xterm.dart';+// The mirror and the render object are not exported; the benchmark reads where+// the rows are drawn from them.+// ignore: implementation_imports+import 'package:xterm/src/ui/render.dart';+// ignore: implementation_imports+import 'package:xterm/src/utils/input_trace.dart';++import '../perf/frames.dart';+import '../perf/gestures.dart';+import '../perf/perf_binding.dart';+import 'program.dart';++/// What to run, from `--dart-define`s — see `integration_test/README.md`.+class ClaudeScrollOptions {+ const ClaudeScrollOptions({+ required this.program,+ required this.port,+ required this.bridgeDelayMs,+ required this.fakeOneWayMs,+ required this.fakeDrawMs,+ required this.rounds,+ required this.scenarios,+ });++ factory ClaudeScrollOptions.fromEnvironment() {+ const only = String.fromEnvironment('CLAUDE_SCROLL_SCENARIOS');+ return ClaudeScrollOptions(+ program: const String.fromEnvironment(+ 'CLAUDE_SCROLL_PROGRAM',+ defaultValue: 'fake',+ ),+ port: const int.fromEnvironment('CLAUDE_BRIDGE_PORT', defaultValue: 8765),+ bridgeDelayMs: const int.fromEnvironment('CLAUDE_BRIDGE_DELAY_MS'),+ fakeOneWayMs: const int.fromEnvironment(+ 'CLAUDE_FAKE_ONE_WAY_MS',+ defaultValue: 30,+ ),+ fakeDrawMs: const int.fromEnvironment(+ 'CLAUDE_FAKE_DRAW_MS',+ defaultValue: 40,+ ),+ rounds: const int.fromEnvironment(+ 'CLAUDE_SCROLL_ROUNDS',+ defaultValue: 3,+ ),+ scenarios: only.isEmpty+ ? null+ : only.split(',').map((s) => s.trim()).toSet(),+ );+ }++ final String program;+ final int port;+ final int bridgeDelayMs;+ final int fakeOneWayMs;+ final int fakeDrawMs;+ final int rounds;+ final Set<String>? scenarios;++ bool wants(String name) =>+ scenarios == null || scenarios!.any((s) => name.startsWith(s));++ Map<String, Object?> toJson() => {+ 'program': program,+ 'port': program == 'live' ? port : null,+ 'bridgeDelayMs': program == 'live' ? bridgeDelayMs : null,+ 'fakeOneWayMs': program == 'fake' ? fakeOneWayMs : null,+ 'fakeDrawMs': program == 'fake' ? fakeDrawMs : null,+ 'rounds': rounds,+ };+}++/// One frame's look at the scroll: where the finger (or its fling) has the+/// scrollable, and where the rows that scroll are drawn — both in rows.+class _Sample {+ _Sample(+ this.wall,+ this.frame,+ this.pixels,+ this.content,+ this.active, {+ this.bottom,+ this.top,+ this.remote,+ this.generation = 0,+ });++ final int wall;+ final int frame;+ final double pixels;++ /// The document row drawn at the top of the rows that scroll — the mirror's+ /// while it draws them, else the program's own — or null: nothing to say.+ final double? content;+ final bool active;++ /// Where the transcript's newest and oldest rows put the content — the fake+ /// program knows both; for a real one, the oldest once a page up has gone+ /// nowhere.+ final double? bottom;+ final double? top;++ /// The document row at the top of the program's own screen.+ final double? remote;++ /// Which numbering [content] is in: a new mirror, or one whose document+ /// started again, numbers its rows afresh — not the rows moving.+ final int generation;+}++/// Claude Code's fullscreen scroll on the phone, measured against what a native+/// list does: the rows move exactly as far as the finger, every frame, and+/// stop when it does.+class ClaudeScrollBench {+ /// [openInApp], when given, opens a real agent's terminal in the real app+ /// and answers how to read its emulator — which a keyframe replaces — in+ /// place of the benchmark's own view over a program it runs.+ ClaudeScrollBench(+ this.tester,+ this.binding,+ this.options, {+ this.openInApp,+ this.beforeScenario,+ });++ final WidgetTester tester;+ final PerfBinding binding;+ final ClaudeScrollOptions options;+ final Future<Terminal Function()> Function()? openInApp;++ /// Run before each scenario's gestures — in the app, holding the terminal.+ final Future<void> Function()? beforeScenario;++ final results = <String, Object?>{};+ final failures = <String, String>{};+ final _samples = <_Sample>[];+ final _traces = <(int, String)>[];+ late final FrameClock _clock;+ late final Touches _touches;+ ScrollProgram? _program;+ final _terminal = Terminal(maxLines: 1000);++ /// The app's own emulator of the agent, when [openInApp] opened one.+ Terminal Function()? _appTerminal;++ Terminal get _screen => _appTerminal?.call() ?? _terminal;+ final _controller = TerminalController();+ var _memory = RemoteScrollMemory();+ var _viewKey = UniqueKey();+ bool _sampling = false;++ /// What [_sample] reads every frame, found once per measurement: the view+ /// is small, but a tree walk inside the frames being timed is still work.+ ScrollableState? _scrollState;+ RenderTerminal? _renderTerminal;++ /// The mirror last sampled, and how many have been: a new one numbers its+ /// rows afresh.+ Object? _lastMirror;+ int _mirrors = 0;++ Future<void> run() async {+ await WakelockPlus.enable();+ _clock = FrameClock();+ _touches = Touches(binding);+ xtermInputTrace = (message) {+ if (message.startsWith('mirror:')) _traces.add((wallMicros(), message));+ };+ SchedulerBinding.instance.addPersistentFrameCallback(_sample);+ try {+ final open = openInApp;+ if (open != null) {+ _appTerminal = await open();+ } else {+ await _mount();+ final program = _program = _makeProgram();+ _terminal.onOutput = program.input;+ await program.start(_terminal);+ }+ await _waitForPrompt();+ results['grid'] = '${_screen.viewWidth}x${_screen.viewHeight}';+ results['refreshRate'] =+ ui.PlatformDispatcher.instance.views.first.display.refreshRate;+ final rounds = <Map<String, Object?>>[];+ for (var round = 0; round < options.rounds; round++) {+ rounds.add(await _round(round));+ }+ results['rounds'] = rounds;+ results['summary'] = _summarize(rounds);+ results['programAfter'] = _program?.describe() ?? {'program': 'app'};+ } finally {+ xtermInputTrace = null;+ _clock.dispose();+ await WakelockPlus.disable();+ }+ results['options'] = options.toJson();+ results['failures'] = failures;+ results['success'] = failures.isEmpty;+ }++ void dispose() {+ _program?.dispose();+ }++ ScrollProgram _makeProgram() {+ if (options.program == 'live') {+ return LiveClaudeCode(options.port, extraDelayMs: options.bridgeDelayMs);+ }+ return FakeClaudeCode(+ oneWay: Duration(milliseconds: options.fakeOneWayMs),+ draw: Duration(milliseconds: options.fakeDrawMs),+ );+ }++ /// The terminal as the phone shows Claude Code: its own font, no app scaling,+ /// and the alternate screen's scroll as `TerminalPanel` sets it up.+ Future<void> _mount() async {+ final choice = TerminalFontChoice.defaultOn(TerminalFontHost.current);+ final style = TerminalStyle(+ fontSize: terminalFontSize,+ fontFamily: choice.fontFamily,+ fontFamilyFallback: choice.fontFamilyFallback,+ );+ await tester.pumpWidget(+ MaterialApp(+ debugShowCheckedModeBanner: false,+ home: Scaffold(+ backgroundColor: Colors.black,+ body: SafeArea(+ child: TerminalView(+ _terminal,+ key: _viewKey,+ controller: _controller,+ textStyle: style,+ textScaler: TextScaler.noScaling,+ autofocus: false,+ altBufferScrollPhysics: const RemoteScrollPhysics(),+ altBufferScrollPaced: true,+ altBufferScrollAnimated: true,+ altBufferScrollMirror: true,+ altBufferScrollPageKeys: true,+ altBufferScrollMemory: _memory,+ ),+ ),+ ),+ ),+ );+ await _frames(3);+ }++ /// A new view and a new memory: the next scroll is the first this agent's+ /// terminal has seen, as on opening it.+ Future<void> _remount() async {+ _memory = RemoteScrollMemory();+ _viewKey = UniqueKey();+ await _mount();+ }++ Future<void> _frames(int count) async {+ for (var i = 0; i < count; i++) {+ await nextFrame();+ }+ }++ Future<void> _wait(int ms) =>+ Future<void>.delayed(Duration(milliseconds: ms));++ Future<void> _waitForPrompt() async {+ final watch = Stopwatch()..start();+ while (watch.elapsed < const Duration(seconds: 90)) {+ final screen = _screen;+ final lines = screen.buffer.lines;+ final ready =+ screen.isUsingAltBuffer &&+ [+ for (var i = 0; i < screen.viewHeight && i < lines.length; i++)+ lines[i].getText(),+ ].any((text) => text.trimLeft().startsWith('❯')) &&+ _scrollable() != null;+ if (ready) {+ results['readyMs'] = watch.elapsedMilliseconds;+ await _wait(1500);+ return;+ }+ await _wait(100);+ await nextFrame();+ }+ throw StateError('Claude Code never showed its prompt');+ }++ /// The view of the terminal measured — in the app, the one showing the+ /// agent, not a neighbour the pager built ahead.+ Element? _view() => findElement(+ (w) =>+ w is TerminalView &&+ (openInApp == null || identical(w.terminal, _screen)),+ );++ ScrollableState? _scrollable() {+ final view = _view();+ if (view == null) return null;+ ScrollableState? found;+ void visit(Element element) {+ if (found != null) return;+ if (element is StatefulElement && element.state is ScrollableState) {+ found = element.state as ScrollableState;+ return;+ }+ element.visitChildElements(visit);+ }++ view.visitChildElements(visit);+ return found;+ }++ RenderTerminal? _render() {+ final view = _view();+ if (view == null) return null;+ RenderTerminal? found;+ void visit(Element element) {+ if (found != null) return;+ if (element.renderObject is RenderTerminal) {+ found = element.renderObject! as RenderTerminal;+ return;+ }+ element.visitChildElements(visit);+ }++ view.visitChildElements(visit);+ return found;+ }++ void _sample(Duration _) {+ if (!_sampling) return;+ final position = _scrollState?.position;+ final render = _renderTerminal;+ if (position == null || render == null) return;+ final mirror = render.debugRemoteScrollMirror;+ final lineHeight = render.lineHeight;+ double? content;+ double? bottom;+ double? top;+ double? remote;+ var active = false;+ if (mirror != null && lineHeight > 0) {+ active = mirror.isActive;+ final at = mirror.display + mirror.offset / lineHeight;+ remote = at;+ content = active ? mirror.display : at;+ final program = _program;+ if (program is FakeClaudeCode) {+ bottom = at + program.rowsBelow;+ top = at - program.rowsAbove;+ } else {+ final first = mirror.debugTranscriptTop;+ if (first != null) top = (first - mirror.top).toDouble();+ }+ }+ if (!identical(mirror, _lastMirror)) {+ _lastMirror = mirror;+ _mirrors++;+ }+ _samples.add(+ _Sample(+ wallMicros(),+ currentFrameNumber(),+ position.pixels / math.max(1, lineHeight),+ content,+ active,+ bottom: bottom,+ top: top,+ remote: remote,+ generation: _mirrors * 100000 + (mirror?.debugRenumbered ?? 0),+ ),+ );+ }++ Offset _at(double heightShare) {+ final view = _view()!;+ final box = view.renderObject! as RenderBox;+ return box.localToGlobal(+ Offset(box.size.width / 2, box.size.height * heightShare),+ );+ }++ Future<Map<String, Object?>> _round(int round) async {+ final scenarios = <String, Object?>{};+ // Every round from the newest row, as an agent is opened, and the first+ // scroll on a freshly opened terminal: nothing known yet. The app's own+ // terminal is opened once — its first round's first drag is the cold one.+ if (openInApp == null) {+ final program = _program;+ if (program is FakeClaudeCode) program.scrollToBottom();+ await _remount();+ }+ await _wait(2000);+ if (options.wants('first_drag')) {+ scenarios['first_drag'] = await _measure('first_drag', () async {+ await _drag(fromShare: 0.35, dy: 260, steps: 26);+ });+ }+ await _wait(1800);+ if (options.wants('read_drag')) {+ scenarios['read_drag'] = await _measure('read_drag', () async {+ for (var i = 0; i < 5; i++) {+ await _drag(fromShare: 0.3, dy: 300, steps: 30);+ await _wait(200);+ }+ });+ }+ // A screen read before the thumb goes looking further back.+ await _wait(4000);+ if (options.wants('flick_up')) {+ scenarios['flick_up'] = await _measure('flick_up', () async {+ for (var i = 0; i < 8; i++) {+ await _flick(fromShare: 0.3, dy: 340);+ await _wait(260);+ }+ });+ }+ // And on at once, into rows nobody has fetched: as fast as the program+ // brings them, at best.+ await _wait(300);+ if (options.wants('flick_deep')) {+ scenarios['flick_deep'] = await _measure('flick_deep', () async {+ for (var i = 0; i < 6; i++) {+ await _flick(fromShare: 0.3, dy: 340);+ await _wait(260);+ }+ });+ }+ await _wait(1800);+ if (options.wants('flick_down')) {+ scenarios['flick_down'] = await _measure('flick_down', () async {+ for (var i = 0; i < 16; i++) {+ await _flick(fromShare: 0.7, dy: -340);+ await _wait(260);+ }+ });+ }+ await _wait(1200);+ return {'round': round, ...scenarios};+ }++ /// A finger that follows the content: [dy] logical pixels in [steps] moves a+ /// frame apart, then held a moment so it lifts with no fling.+ Future<void> _drag({+ required double fromShare,+ required double dy,+ required int steps,+ }) async {+ // A move each refresh, as a finger is sampled — 120 times a second on a+ // 120 Hz phone — over the time [steps] moves 16 ms apart would take.+ final interval = Duration(microseconds: _budgetMicros);+ final moves = (steps * 16000 / _budgetMicros).round();+ final finger = _touches.down(_at(fromShare));+ await glide(finger, Offset(0, dy), steps: moves, interval: interval);+ await _wait(120);+ finger.up();+ }++ /// A thumb's flick: [dy] in eight moves 8 ms apart, lifted moving.+ Future<void> _flick({required double fromShare, required double dy}) async {+ final finger = _touches.down(_at(fromShare));+ await glide(finger, Offset(0, dy), steps: 8);+ finger.up();+ }++ Future<Map<String, Object?>> _measure(+ String name,+ Future<void> Function() gesture,+ ) async {+ await beforeScenario?.call();+ _samples.clear();+ final tracesFrom = _traces.length;+ _scrollState = _scrollable();+ _renderTerminal = _render();+ _sampling = true;+ final start = wallMicros();+ try {+ await gesture();+ // The fling runs out, the screen settles, the program comes back.+ await _waitUntilStill();+ } catch (error) {+ failures[name] = '$error';+ }+ final end = wallMicros();+ _sampling = false;+ await _clock.settleUntil(end);+ final frames = _clock.between(start, end);+ final first = _samples.isEmpty ? start : _samples.first.wall;+ String? fixed(double? value) => value?.toStringAsFixed(2);+ return {+ 'frames': _frameSummary(frames, end - start),+ 'follow': _follow(List.of(_samples)),+ // Every frame: [ms since the first, finger row, content row, drawn from+ // the mirror, the transcript's newest row there, the program's row].+ 'samples': [+ for (final s in _samples)+ [+ (s.wall - first) ~/ 1000,+ fixed(s.pixels),+ fixed(s.content),+ s.active ? 1 : 0,+ fixed(s.bottom),+ fixed(s.remote),+ ],+ ],+ 'trace': [+ for (final (at, line) in _traces.skip(tracesFrom).take(600))+ '${(at - first) ~/ 1000} $line',+ ],+ 'mirror': [+ for (final (_, line) in _traces.skip(tracesFrom))+ if (line.startsWith('mirror: done') ||+ line.contains('not placed') ||+ line.contains('did not come back') ||+ line.contains('drawing from the document') ||+ line.contains('starting again'))+ line,+ ],+ };+ }++ /// Until nothing has moved for 600 ms, the mirror is drawing live again, or+ /// 6 s have gone by.+ Future<void> _waitUntilStill() async {+ final watch = Stopwatch()..start();+ var stillSince = watch.elapsedMilliseconds;+ double? lastPixels;+ double? lastContent;+ while (watch.elapsedMilliseconds < 6000) {+ await _wait(50);+ await nextFrame();+ final position = _scrollState?.position;+ final mirror = _renderTerminal?.debugRemoteScrollMirror;+ final pixels = position?.pixels;+ final content = mirror?.display;+ if (pixels != lastPixels || content != lastContent) {+ stillSince = watch.elapsedMilliseconds;+ }+ lastPixels = pixels;+ lastContent = content;+ final active = mirror?.isActive ?? false;+ if (!active && watch.elapsedMilliseconds - stillSince > 600) return;+ }+ }++ /// One refresh of this phone's display: 8.3 ms on a 120 Hz Android, 16.7+ /// on the iPhone 14.+ int get _budgetMicros {+ final rate = ui.PlatformDispatcher.instance.views.first.display.refreshRate;+ return rate > 0 ? (1e6 / rate).round() : frameBudgetMicros;+ }++ Map<String, Object?> _frameSummary(List<ui.FrameTiming> frames, int window) {+ final stats = frameStats(+ frames,+ windowMicros: window,+ budgetMicros: _budgetMicros,+ );+ stats.remove('raw');+ stats.remove('rawColumns');+ return stats;+ }++ /// Frame by frame, how far the rows moved against how far the finger did.+ Map<String, Object?> _follow(List<_Sample> samples) {+ final errors = <int>[];+ var fingerRows = 0.0;+ var contentRows = 0.0;+ var stalls = 0;+ var jumps = 0;+ var moving = 0;+ var atEnd = 0;+ var renumbered = 0;+ var activeFrames = 0;+ var afterStopRows = 0.0;+ int? firstActiveMs;+ int? lastFingerMoveIndex;+ for (var i = 1; i < samples.length; i++) {+ final a = samples[i - 1];+ final b = samples[i];+ final finger = b.pixels - a.pixels;+ if (finger.abs() > 0.001) lastFingerMoveIndex = i;+ }+ for (var i = 1; i < samples.length; i++) {+ final a = samples[i - 1];+ final b = samples[i];+ if (b.active) {+ activeFrames++;+ firstActiveMs ??= ((b.wall - samples.first.wall) / 1000).round();+ }+ final ca = a.content;+ final cb = b.content;+ if (ca == null || cb == null) continue;+ if (a.generation != b.generation) {+ renumbered++;+ continue;+ }+ final finger = b.pixels - a.pixels;+ final content = cb - ca;+ final stopped = lastFingerMoveIndex != null && i > lastFingerMoveIndex;+ if (stopped) {+ afterStopRows += content.abs();+ continue;+ }+ if (finger.abs() < 0.001 && content.abs() < 0.001) continue;+ // At an end of the transcript a native list stops too.+ final bottom = b.bottom;+ final top = b.top;+ if (bottom != null && finger > 0 && cb >= bottom - 0.05 ||+ top != null && finger < 0 && cb <= top + 0.05) {+ atEnd++;+ continue;+ }+ moving++;+ fingerRows += finger;+ contentRows += content;+ final error = (content - finger).abs();+ errors.add((error * 1000).round());+ if (finger.abs() >= 0.25 && content.abs() < 0.05) stalls++;+ // Further than the finger by two rows or more, or the other way: a+ // lurch. Short of it is a screen waiting for rows, counted above.+ if (content * finger < 0 && content.abs() >= 1 ||+ content.abs() - finger.abs() >= 2) {+ jumps++;+ }+ }+ errors.sort();+ double at(double q) =>+ errors.isEmpty ? 0 : errors[(errors.length * q).ceil() - 1] / 1000;+ return {+ 'movingFrames': moving,+ 'framesAtAnEnd': atEnd,+ // The document started again (a keyframe, a frame not placed): the+ // screen may have jumped there by an amount this cannot tell.+ 'renumbered': renumbered,+ 'mirrorFrames': activeFrames,+ 'firstMirrorFrameMs': firstActiveMs,+ 'fingerRows': _round2(fingerRows),+ 'contentRows': _round2(contentRows),+ // Rows the finger moved that the content never did — what was let go at+ // the edge of what is known, and the lead of a fling over the screen.+ 'rowsBehind': _round2((fingerRows - contentRows).abs()),+ 'errorRowsP50': at(.5),+ 'errorRowsP95': at(.95),+ 'errorRowsMax': at(1),+ 'stalledFrames': stalls,+ 'jumpFrames': jumps,+ // Moved after the finger and its fling had stopped: the glide to a whole+ // row is under one; more is the screen moving by itself.+ 'rowsAfterStop': _round2(afterStopRows),+ };+ }++ static double _round2(double value) => (value * 100).round() / 100;++ /// Every round's scenarios pooled: their medians, side by side.+ Map<String, Object?> _summarize(List<Map<String, Object?>> rounds) {+ final out = <String, Object?>{};+ final names = <String>{+ for (final round in rounds) ...round.keys.where((k) => k != 'round'),+ };+ for (final name in names) {+ final follows = [+ for (final round in rounds)+ if (round[name] case {'follow': final Map<String, Object?> follow})+ follow,+ ];+ final frames = [+ for (final round in rounds)+ if (round[name] case {'frames': final Map<String, Object?> frames})+ frames,+ ];+ num median(Iterable<num> values) {+ final sorted = values.toList()..sort();+ return sorted.isEmpty ? 0 : sorted[sorted.length ~/ 2];+ }++ num pick(Map<String, Object?> map, String key) => (map[key] as num?) ?? 0;+ out[name] = {+ for (final key in [+ 'fingerRows',+ 'contentRows',+ 'rowsBehind',+ 'errorRowsP50',+ 'errorRowsP95',+ 'errorRowsMax',+ 'stalledFrames',+ 'jumpFrames',+ 'rowsAfterStop',+ 'firstMirrorFrameMs',+ ])+ key: median(follows.map((f) => pick(f, key))),+ 'framesOverBudget': median(+ frames.map(+ (f) => pick(+ f['framesOverBudget']! as Map<String, Object?>,+ 'totalSpan',+ ),+ ),+ ),+ 'buildP95Ms': median(+ frames.map(+ (f) => pick(f['buildMs']! as Map<String, Object?>, 'p95Ms'),+ ),+ ),+ 'rasterP95Ms': median(+ frames.map(+ (f) => pick(f['rasterMs']! as Map<String, Object?>, 'p95Ms'),+ ),+ ),+ };+ }+ return out;+ }+}diff --git a/mobile/integration_test/claude_scroll/claude_bridge.py b/mobile/integration_test/claude_scroll/claude_bridge.pynew file mode 100644index 000000000..b6d580d72--- /dev/null+++ b/mobile/integration_test/claude_scroll/claude_bridge.py@@ -0,0 +1,171 @@+#!/usr/bin/env python3+"""The real Claude Code for integration_test/claude_scroll_test.dart.++The phone's benchmark app listens; this script connects OUT to it (over the USB+tunnel or the LAN), starts `claude --resume SESSION` in CWD in a pseudo+terminal at the grid the phone sends first ("<cols> <rows> <delay ms>\\n"), and+carries the bytes both ways — each held DELAY ms on the way, to stand in for+the relay. The connection closing ends Claude Code.++Nothing on this Mac listens, and only scrolling reaches Claude Code: of what the+phone sends, wheel reports (SGR mouse, buttons 64/65) and Page Up/Down pass;+every other byte — a character, Enter, any other key — is dropped. No prompt+can be typed into it from the phone.++ python3 claude_bridge.py --phone HOST:PORT --cwd DIR --session ID++Run Claude Code once in DIR by hand first, so its folder-trust question is+answered; resume a copy of a session rather than one an agent is still writing.+"""++import argparse+import asyncio+import fcntl+import os+import pty+import re+import signal+import struct+import termios+import time++# What may reach Claude Code: a wheel report or Page Up/Down, nothing else.+SCROLL = re.compile(rb"\x1b\[<6[45];\d+;\d+[Mm]|\x1b\[[56]~")+++class ScrollOnly:+ """Keeps the scroll sequences of what the phone sends, across chunks."""++ def __init__(self):+ self.pending = b""+ self.dropped = 0++ def feed(self, data):+ self.pending += data+ kept = []+ while self.pending:+ match = SCROLL.match(self.pending)+ if match:+ kept.append(match.group(0))+ self.pending = self.pending[match.end():]+ continue+ # The start of a sequence still arriving waits for the rest.+ if self.pending.startswith(b"\x1b") and len(self.pending) < 16 \+ and b"M" not in self.pending and b"m" not in self.pending \+ and b"~" not in self.pending:+ break+ self.pending = self.pending[1:]+ self.dropped += 1+ return b"".join(kept)+++class DelayLine:+ """Hands each chunk on `delay` seconds after it came, in order."""++ def __init__(self, delay, sink):+ self.delay = delay+ self.sink = sink+ self.queue = asyncio.Queue()+ self.task = asyncio.ensure_future(self._run())++ def put(self, data):+ self.queue.put_nowait((time.monotonic() + self.delay, data))++ async def _run(self):+ while True:+ due, data = await self.queue.get()+ wait = due - time.monotonic()+ if wait > 0:+ await asyncio.sleep(wait)+ self.sink(data)++ def close(self):+ self.task.cancel()+++async def connect(host, port, seconds):+ for _ in range(seconds):+ try:+ return await asyncio.open_connection(host, port)+ except OSError:+ await asyncio.sleep(1)+ raise SystemExit(f"[bridge] the phone at {host}:{port} never answered")+++async def run(args):+ host, port = args.phone.rsplit(":", 1)+ host = host.strip("[]")+ reader, writer = await connect(host, int(port), args.wait)+ header = (await reader.readline()).decode().split()+ cols, rows = int(header[0]), int(header[1])+ delay = (int(header[2]) if len(header) > 2 else 0) / 1000+ print(f"[bridge] phone grid {cols}x{rows}, {delay * 1000:.0f} ms each way",+ flush=True)+ pid, fd = pty.fork()+ if pid == 0:+ fcntl.ioctl(0, termios.TIOCSWINSZ, struct.pack("HHHH", rows, cols, 0, 0))+ os.chdir(args.cwd)+ os.environ["TERM"] = "xterm-256color"+ os.environ["COLORTERM"] = "truecolor"+ os.execvp("claude", ["claude", "--resume", args.session])+ loop = asyncio.get_running_loop()+ to_phone = DelayLine(delay, writer.write)+ to_claude = DelayLine(delay, lambda data: os.write(fd, data))+ scroll_only = ScrollOnly()+ done = asyncio.Event()++ def readable():+ try:+ data = os.read(fd, 65536)+ except OSError:+ data = b""+ if not data:+ loop.remove_reader(fd)+ done.set()+ return+ to_phone.put(data)++ loop.add_reader(fd, readable)++ async def from_phone():+ while True:+ data = await reader.read(4096)+ if not data:+ break+ kept = scroll_only.feed(data)+ if kept:+ to_claude.put(kept)+ done.set()++ pump = asyncio.ensure_future(from_phone())+ await done.wait()+ pump.cancel()+ to_phone.close()+ to_claude.close()+ try:+ loop.remove_reader(fd)+ except Exception:+ pass+ for sig in (signal.SIGTERM, signal.SIGKILL):+ try:+ os.kill(pid, sig)+ await asyncio.sleep(0.3)+ except ProcessLookupError:+ break+ writer.close()+ print(f"[bridge] closed; {scroll_only.dropped} non-scroll bytes dropped",+ flush=True)+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("--phone", required=True, help="HOST:PORT the phone listens on")+ parser.add_argument("--cwd", required=True)+ parser.add_argument("--session", required=True)+ parser.add_argument("--wait", type=int, default=180,+ help="seconds to keep trying to reach the phone")+ asyncio.run(run(parser.parse_args()))+++if __name__ == "__main__":+ main()diff --git a/mobile/integration_test/claude_scroll/program.dart b/mobile/integration_test/claude_scroll/program.dartnew file mode 100644index 000000000..51ee901c3--- /dev/null+++ b/mobile/integration_test/claude_scroll/program.dart@@ -0,0 +1,439 @@+import 'dart:async';+import 'dart:convert';+import 'dart:io';+import 'dart:math' as math;++import 'package:xterm/xterm.dart';++/// What runs behind the benchmark's terminal: the phone's input goes in, what+/// it draws comes out — Claude Code's fullscreen renderer, faked in the app or+/// real on a Mac.+abstract class ScrollProgram {+ String get name;++ /// Starts drawing into [terminal], already laid out at the phone's grid.+ Future<void> start(Terminal terminal);++ /// Bytes the phone sent: wheel reports, Page Up/Down, keys.+ void input(String data);++ void dispose();++ Map<String, Object?> describe();+}++/// Claude Code 2.1.309's fullscreen renderer as far as a scroll sees it, in the+/// app: a transcript scrolled by wheel reports and Page Up/Down, redrawn whole+/// in a synchronized update, across a link [oneWay] long each way.+///+/// What it copies, as `RemoteScrollMirror` and the scroll handler record it:+///+/// - a wheel event after a pause of over 40 ms scrolls one row; each one closer+/// than that to the last 0.3 of a row more, up to 6, floored;+/// - the first wheel event after a turn is dropped;+/// - Page Up/Down scroll half the transcript's height at once;+/// - scrolled, the prompt of the rows on screen is pinned to row 0 once it has+/// scrolled off, and a "Jump to bottom" line covers the transcript's last row;+/// - under the transcript a blank row, the prompt box between two rules, a blank+/// row and the mode line (read off a live 2.1.309 pane's layout);+/// - a redraw takes [draw] (50–150 ms for a page in a long session), at most one+/// every 16 ms, and inputs arriving meanwhile join it.+class FakeClaudeCode implements ScrollProgram {+ FakeClaudeCode({+ this.oneWay = const Duration(milliseconds: 30),+ this.draw = const Duration(milliseconds: 40),+ this.transcriptMessages = 400,+ this.seed = 7,+ });++ final Duration oneWay;+ final Duration draw;+ final int transcriptMessages;+ final int seed;++ late Terminal _terminal;+ int _cols = 0;+ int _rows = 0;+ List<String> _transcript = const [];++ /// For each transcript row, the transcript row of the prompt it answers.+ List<int> _promptOf = const [];++ /// Rows scrolled up from the bottom.+ int _offset = 0;+ int _lastDirection = 0;+ double _step = 1;+ final _clock = Stopwatch()..start();+ int _lastWheelMs = -1 << 30;+ int _lastDrawMs = -1 << 30;+ Timer? _drawTimer;+ bool _disposed = false;+ String _pending = '';++ int wheels = 0;+ int pages = 0;+ int redraws = 0;++ @override+ String get name => 'fake';++ /// Rows between the screen last delivered and the transcript's newest row,+ /// and its oldest: where a scroll has to stop, as a native list stops at its+ /// ends. Of the screen the phone has, not of a redraw still on its way.+ int get rowsBelow => _shownOffset;+ int get rowsAbove => _maxOffset - _shownOffset;+ int _shownOffset = 0;++ int get _transcriptRows => _rows - 6;++ int get _maxOffset => math.max(0, _transcript.length - _transcriptRows);++ @override+ Future<void> start(Terminal terminal) async {+ _terminal = terminal;+ _layout(terminal.viewWidth, terminal.viewHeight);+ terminal.onResize = (cols, rows, _, _) {+ _layout(cols, rows);+ _scheduleDraw();+ };+ terminal.write('\x1b[?1049h\x1b[?1000h\x1b[?1006h\x1b[?25l');+ _render();+ }++ void _layout(int cols, int rows) {+ if (cols == _cols && rows == _rows) return;+ _cols = cols;+ _rows = rows;+ final rowsOut = <String>[];+ final promptOf = <int>[];+ final random = math.Random(seed);+ var prompt = 0;+ for (var m = 0; m < transcriptMessages; m++) {+ if (m % 6 == 0) {+ prompt = rowsOut.length;+ for (final row in _wrap('> ${_sentence(random, 8)} (message $m)')) {+ rowsOut.add('\x1b[38;2;153;153;153m$row\x1b[0m');+ promptOf.add(prompt);+ }+ } else if (m % 6 == 3) {+ rowsOut.add('\x1b[38;2;78;186;101m⏺\x1b[0m Update(lib/file_$m.dart)');+ promptOf.add(prompt);+ for (var d = 0; d < 4; d++) {+ final add = d.isEven;+ rowsOut.add(+ '${add ? '\x1b[48;2;34;92;43m' : '\x1b[48;2;122;41;54m'}'+ '${_fit(' ${40 + d} ${add ? '+' : '-'} ${_sentence(random, 5)}')}'+ '\x1b[0m',+ );+ promptOf.add(prompt);+ }+ } else {+ final lines = _wrap(+ '⏺ ${_sentence(random, 12 + random.nextInt(30))}'+ ' (row $m)',+ );+ for (final row in lines) {+ rowsOut.add(row);+ promptOf.add(prompt);+ }+ }+ rowsOut.add('');+ promptOf.add(prompt);+ }+ _transcript = rowsOut;+ _promptOf = promptOf;+ _offset = _offset.clamp(0, _maxOffset);+ }++ static const _words = [+ 'the',+ 'mirror',+ 'scroll',+ 'phone',+ 'row',+ 'frame',+ 'page',+ 'program',+ 'finger',+ 'screen',+ 'redraw',+ 'Claude',+ 'wheel',+ 'transcript',+ 'fling',+ 'native',+ 'smooth',+ 'edge',+ 'document',+ 'placed',+ 'held',+ 'answer',+ ];++ String _sentence(math.Random random, int words) =>+ [for (var w = 0; w < words; w++) _words[random.nextInt(_words.length)]]+ .join(' ');++ String _fit(String text) =>+ text.length > _cols ? text.substring(0, _cols) : text.padRight(_cols);++ List<String> _wrap(String text) {+ final rows = <String>[];+ var line = '';+ for (final word in text.split(' ')) {+ if (line.isEmpty) {+ line = word;+ } else if (line.length + 1 + word.length <= _cols - 2) {+ line = '$line $word';+ } else {+ rows.add(line);+ line = ' $word';+ }+ }+ if (line.isNotEmpty) rows.add(line);+ return rows;+ }++ /// Back to the newest row at once, as a freshly opened agent shows it.+ void scrollToBottom() {+ _offset = 0;+ _render();+ }++ @override+ void input(String data) {+ Timer(oneWay, () {+ if (_disposed) return;+ _receive(data);+ });+ }++ static final _sgrMouse = RegExp(r'\x1b\[<(\d+);(\d+);(\d+)([Mm])');++ void _receive(String data) {+ _pending += data;+ var changed = false;+ while (_pending.isNotEmpty) {+ final mouse = _sgrMouse.matchAsPrefix(_pending);+ if (mouse != null) {+ final button = int.parse(mouse.group(1)!);+ if (button == 64) changed |= _wheel(1);+ if (button == 65) changed |= _wheel(-1);+ _pending = _pending.substring(mouse.end);+ continue;+ }+ if (_pending.startsWith('\x1b[5~')) {+ changed |= _page(1);+ _pending = _pending.substring(4);+ continue;+ }+ if (_pending.startsWith('\x1b[6~')) {+ changed |= _page(-1);+ _pending = _pending.substring(4);+ continue;+ }+ // A sequence still arriving waits for the rest; anything else is a key+ // the benchmark never sends.+ if (_pending.startsWith('\x1b') && _pending.length < 16) break;+ _pending = _pending.substring(1);+ }+ if (changed) _scheduleDraw();+ }++ /// [direction] 1 scrolls up, towards older rows.+ bool _wheel(int direction) {+ wheels++;+ final now = _clock.elapsedMilliseconds;+ if (_lastDirection != 0 && direction != _lastDirection) {+ _lastDirection = direction;+ _lastWheelMs = now;+ _step = 1;+ return false;+ }+ _lastDirection = direction;+ _step = now - _lastWheelMs > 40 ? 1 : math.min(6, _step + 0.3);+ _lastWheelMs = now;+ return _scrollBy(direction * _step.floor());+ }++ bool _page(int direction) {+ pages++;+ return _scrollBy(direction * (_transcriptRows ~/ 2));+ }++ bool _scrollBy(int rows) {+ final next = (_offset + rows).clamp(0, _maxOffset);+ if (next == _offset) return false;+ _offset = next;+ return true;+ }++ void _scheduleDraw() {+ if (_drawTimer != null) return;+ final now = _clock.elapsedMilliseconds;+ final at = math.max(now + draw.inMilliseconds, _lastDrawMs + 16);+ _drawTimer = Timer(Duration(milliseconds: at - now), () {+ _drawTimer = null;+ if (_disposed) return;+ _lastDrawMs = _clock.elapsedMilliseconds;+ final frame = _frame();+ final offset = _offset;+ Timer(oneWay, () {+ if (_disposed) return;+ _terminal.write(frame);+ _shownOffset = offset;+ });+ });+ }++ void _render() {+ _terminal.write(_frame());+ _shownOffset = _offset;+ }++ String _frame() {+ redraws++;+ final rows = _transcriptRows;+ final first = _transcript.length - rows - _offset;+ final out = StringBuffer('\x1b[?2026h');+ for (var i = 0; i < _rows; i++) {+ out.write('\x1b[${i + 1};1H\x1b[0m\x1b[2K');+ if (i < rows) {+ final index = first + i;+ if (_offset > 0 && i == 0) {+ final prompt = _promptOf[math.max(0, index)];+ if (prompt < index) {+ out.write(+ '\x1b[38;2;153;153;153m${_plain(_transcript[prompt])}\x1b[0m',+ );+ continue;+ }+ }+ if (_offset > 0 && i == rows - 1) {+ out.write('\x1b[38;2;177;185;249m ↓ Jump to bottom\x1b[0m');+ continue;+ }+ if (index >= 0) out.write(_transcript[index]);+ } else {+ // A blank row, the prompt box, a blank row and the mode line, as+ // 2.1.309 lays them out under the transcript.+ out.write(switch (i - rows) {+ 1 || 3 => '\x1b[38;2;80;80;80m${'─' * _cols}\x1b[0m',+ 2 => '❯ ',+ 5 => '\x1b[38;2;175;135;255m ⏵⏵ accept edits on\x1b[0m',+ _ => '',+ });+ }+ }+ out.write('\x1b[?2026l');+ return out.toString();+ }++ static String _plain(String styled) =>+ styled.replaceAll(RegExp(r'\x1b\[[0-9;]*m'), '');++ @override+ void dispose() {+ _disposed = true;+ _drawTimer?.cancel();+ }++ @override+ Map<String, Object?> describe() => {+ 'program': name,+ 'oneWayMs': oneWay.inMilliseconds,+ 'drawMs': draw.inMilliseconds,+ 'transcriptRows': _transcript.length,+ 'grid': '${_cols}x$_rows',+ 'wheels': wheels,+ 'pages': pages,+ 'redraws': redraws,+ };+}++/// The real Claude Code, run on a Mac by `claude_bridge.py` in a pseudo+/// terminal at the phone's grid. The phone listens on [port]; the bridge+/// connects to it — nothing on the Mac listens — and holds every byte+/// [extraDelayMs] each way, to stand in for the relay.+class LiveClaudeCode implements ScrollProgram {+ LiveClaudeCode(this.port, {this.extraDelayMs = 0});++ final int port;+ final int extraDelayMs;++ ServerSocket? _server;+ Socket? _socket;+ int bytesIn = 0;+ int bytesOut = 0;+ Duration? connectTook;++ @override+ String get name => 'live';++ @override+ Future<void> start(Terminal terminal) async {+ final watch = Stopwatch()..start();+ final server = await ServerSocket.bind(+ InternetAddress.anyIPv6,+ port,+ v6Only: false,+ );+ _server = server;+ final addresses = [+ for (final interface in await NetworkInterface.list(+ includeLinkLocal: true,+ ))+ for (final address in interface.addresses)+ '${interface.name}=${address.address}',+ ];+ // Read by whoever starts the bridge: where to reach this phone.+ // ignore: avoid_print+ print(+ '[scroll] waiting for claude_bridge.py on port $port · '+ '${addresses.join(' ')}',+ );+ final socket = await server.first.timeout(const Duration(minutes: 4));+ await server.close();+ _server = null;+ socket.setOption(SocketOption.tcpNoDelay, true);+ connectTook = watch.elapsed;+ _socket = socket;+ socket.add(+ utf8.encode(+ '${terminal.viewWidth} ${terminal.viewHeight} $extraDelayMs\n',+ ),+ );+ socket+ .map((chunk) {+ bytesIn += chunk.length;+ return chunk;+ })+ .cast<List<int>>()+ .transform(const Utf8Decoder(allowMalformed: true))+ .listen(terminal.write, onError: (_) {}, cancelOnError: true);+ }++ @override+ void input(String data) {+ final bytes = utf8.encode(data);+ bytesOut += bytes.length;+ _socket?.add(bytes);+ }++ @override+ void dispose() {+ _server?.close();+ _socket?.destroy();+ _socket = null;+ }++ @override+ Map<String, Object?> describe() => {+ 'program': name,+ 'port': port,+ 'extraDelayMsEachWay': extraDelayMs,+ 'connectMs': connectTook?.inMilliseconds,+ 'bytesIn': bytesIn,+ 'bytesOut': bytesOut,+ };+}diff --git a/mobile/integration_test/claude_scroll_app_test.dart b/mobile/integration_test/claude_scroll_app_test.dartnew file mode 100644index 000000000..72f10e530--- /dev/null+++ b/mobile/integration_test/claude_scroll_app_test.dart@@ -0,0 +1,242 @@+// What it is waiting for goes to the console: the run is watched from it.+// ignore_for_file: avoid_print++import 'dart:async';++import 'package:flutter/services.dart';+import 'package:flutter/widgets.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/main.dart' as app;+import 'package:harness_mobile/phone/phone_shell.dart';+import 'package:harness_mobile/phone/phone_shell_scope.dart';+import 'package:harness_mobile/phone/welcome/phone_welcome.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:xterm/xterm.dart' show Terminal, TerminalView;+// The mirror is not exported; what it knows of the rows above is read off it.+// ignore: implementation_imports+import 'package:xterm/src/ui/render.dart' show RenderTerminal;++import 'claude_scroll/bench.dart';+import 'perf/frames.dart';+import 'perf/perf_binding.dart';++/// Claude Code's fullscreen scroll in the REAL app, end to end: this phone's+/// own sign-in, its own computers over the real link, and one of the owner's+/// own Claude Code agents — `CLAUDE_AGENT_NAME`, by its name. The same+/// scenarios and measures as `claude_scroll_test.dart`.+///+/// ⚠️ **It is a real agent on a real computer.** Opening it from the phone takes+/// its pane over at the phone's size, as opening it by hand does, and the+/// scroll sends it wheel events and Page Up/Down — nothing is typed. Pick one+/// that is idle.+///+/// flutter build ios --profile --target=integration_test/claude_scroll_app_test.dart \+/// --dart-define=CLAUDE_AGENT_NAME="Mobile features"+/// flutter drive --profile --no-dds --keep-app-running \+/// --use-application-binary=build/ios/iphoneos/Runner.app \+/// --driver=test_driver/claude_scroll_driver.dart \+/// --target=integration_test/claude_scroll_app_test.dart -d <phone>+///+/// The phone must be signed in already: this never signs in. Like every+/// benchmark here it replaces the app on the phone; reinstall the app after.+void main() {+ final binding = PerfBinding()+ ..framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.benchmarkLive;+ final options = ClaudeScrollOptions.fromEnvironment();+ // Tried in turn: the first with a long enough transcript is measured.+ const agentNames = String.fromEnvironment(+ 'CLAUDE_AGENT_NAME',+ defaultValue: 'Mobile features',+ );++ testWidgets('Claude Code scroll in the real app', (tester) async {+ final bench = ClaudeScrollBench(+ tester,+ binding,+ options,+ openInApp: () => _openAgent(agentNames.split(',')),+ beforeScenario: _holdTerminal,+ );+ try {+ await bench.run();+ } finally {+ bench.dispose();+ binding.reportData = {...bench.results, 'agent': _chosen};+ }+ if (bench.failures.isNotEmpty) {+ fail('Scenarios failed: ${bench.failures}');+ }+ }, timeout: const Timeout(Duration(minutes: 15)));+}++/// The rows above the screen a measured agent must have — known, fetched+/// ahead — for flicks to measure more than the top of its transcript.+const _rowsWanted = 300;++/// The agent measured, and what each one tried had above its screen.+Map<String, Object?> _chosen = {};++/// The app, computer and agent [_openAgent] opened.+(AppNotifier, String, String)? _held;++/// The phone drives the terminal, as a person picking it up does: one another+/// app holds only shows here, and takes nothing typed — a scroll included —+/// until "Take control" (`TerminalPage._takeControl`). Taken again if the+/// computer took it back meanwhile.+Future<void> _holdTerminal() async {+ final (notifier, machineId, agentId) = _held!;+ final session = notifier.paneOfAgent(machineId, agentId)?.session;+ if (session != null && session.acceptsInput) return;+ print(+ '[scroll] not holding the terminal (status ${session?.status.name}, '+ 'watching ${session?.watching}) — taking control',+ );+ await notifier.selectAgent(machineId, agentId);+ await _until('control of the terminal', () {+ final now = notifier.paneOfAgent(machineId, agentId)?.session;+ return now != null && now.acceptsInput ? true : null;+ }, seconds: 30);+ await _wait(1500);+}++Future<void> _wait(int ms) => Future<void>.delayed(Duration(milliseconds: ms));++/// Waits — frames drawn meanwhile — for [found] to answer, up to [seconds].+Future<T> _until<T extends Object>(+ String what,+ T? Function() found, {+ int seconds = 90,+}) async {+ final watch = Stopwatch()..start();+ var said = -1;+ while (watch.elapsed.inSeconds < seconds) {+ final value = found();+ if (value != null) return value;+ if (watch.elapsed.inSeconds ~/ 10 != said) {+ said = watch.elapsed.inSeconds ~/ 10;+ print('[scroll] waiting for $what (${watch.elapsed.inSeconds}s)');+ }+ await _wait(200);+ await nextFrame();+ }+ throw StateError('never got $what in ${seconds}s');+}++/// The app started as on a tap of its icon; each of [agentNames] on this+/// phone's computers opened in turn on the home screen and left to fetch+/// ahead, until one has [_rowsWanted] rows above its screen — else the one+/// with most. Answers how to read the chosen agent's emulator.+Future<Terminal Function()> _openAgent(List<String> agentNames) async {+ unawaited(app.main());+ final shell = await _until('the app signed in', () {+ if (findElement((w) => w is PhoneWelcome) != null) {+ throw StateError('the phone is signed out: sign in by hand first');+ }+ return findElement((w) => w is PhoneShell);+ });+ final notifier = (shell.widget as PhoneShell).notifier;+ final tried = <String, int>{};+ (String, String, String)? chosen;+ var chosenRows = -1;+ for (final name in agentNames.map((n) => n.trim())) {+ final (machineId, agentId) = await _until('agent "$name"', () {+ for (final entry in notifier.machineStates.entries) {+ for (final agent in entry.value.agents) {+ if (agent.name == name && agent.engine == 'claude') {+ return (entry.key, agent.id);+ }+ }+ }+ return null;+ }, seconds: 60);+ final terminal = await _show(notifier, name, machineId, agentId);+ // Time to fetch the rows above, as it does for anyone who opens it.+ await _wait(8000);+ final above = _rowsAbove(terminal());+ tried[name] = above;+ print('[scroll] "$name" · $above rows known above the screen');+ if (above > chosenRows) {+ chosenRows = above;+ chosen = (name, machineId, agentId);+ }+ if (above >= _rowsWanted) break;+ }+ final (name, machineId, agentId) = chosen!;+ _chosen = {'name': name, 'rowsAbove': chosenRows, 'tried': tried};+ final (_, heldMachine, heldAgent) = _held!;+ final terminal = heldMachine == machineId && heldAgent == agentId+ ? () => notifier.paneOfAgent(machineId, agentId)!.session!.terminal+ : await _show(notifier, name, machineId, agentId);+ print('[scroll] measuring "$name" · tried $tried');+ return terminal;+}++/// [agentId] opened on the home screen, as a tap on it does, its terminal+/// taken and the keyboard put away as a reader puts it away.+Future<Terminal Function()> _show(+ AppNotifier notifier,+ String name,+ String machineId,+ String agentId,+) async {+ print('[scroll] opening "$name" ($agentId) on $machineId');+ final scope = await _until(+ 'the shell',+ () => findElement((w) => w is PhoneShellScope),+ );+ Element? below;+ scope.visitChildElements((child) => below ??= child);+ PhoneShellScope.maybeOf(below!)!.onOpenAgent(machineId, agentId);+ await _until(+ 'its terminal',+ () =>+ notifier.paneOfAgent(machineId, agentId)?.session == null ? null : true,+ );+ _held = (notifier, machineId, agentId);+ await _holdTerminal();+ // A reader reads with the keyboard down: the grid is the taller one.+ await _wait(2500);+ FocusManager.instance.primaryFocus?.unfocus();+ await SystemChannels.textInput.invokeMethod<void>('TextInput.hide');+ await _wait(2500);+ Terminal terminal() =>+ notifier.paneOfAgent(machineId, agentId)!.session!.terminal;+ final status = notifier.machineStates[machineId]?.connectionStatus;+ print(+ '[scroll] "$name" open · ${terminal().viewWidth}x${terminal().viewHeight}'+ ' · ${status?.name}',+ );+ return terminal;+}++/// Rows of [terminal]'s agent the mirror knows above the screen.+int _rowsAbove(Terminal terminal) {+ RenderTerminal? render;+ void visit(Element element) {+ if (render != null) return;+ if (element.widget case TerminalView(:final terminal)+ when identical(terminal, terminal)) {}+ final object = element.renderObject;+ if (object is RenderTerminal) {+ render = object;+ return;+ }+ element.visitChildElements(visit);+ }++ final view = findElement(+ (w) => w is TerminalView && identical(w.terminal, terminal),+ );+ view?.visitChildElements(visit);+ final mirror = render?.debugRemoteScrollMirror;+ if (mirror == null) return 0;+ var rows = 0;+ for (+ var row = mirror.display.round() + mirror.top - 1;+ mirror.rowAt(row) != null;+ row--+ ) {+ rows++;+ }+ return rows;+}diff --git a/mobile/integration_test/claude_scroll_test.dart b/mobile/integration_test/claude_scroll_test.dartnew file mode 100644index 000000000..d4e782631--- /dev/null+++ b/mobile/integration_test/claude_scroll_test.dart@@ -0,0 +1,35 @@+import 'package:flutter/widgets.dart';+import 'package:flutter_test/flutter_test.dart';++import 'claude_scroll/bench.dart';+import 'perf/perf_binding.dart';++/// Claude Code's fullscreen scroll on a real phone, against what a native list+/// does — the rows move exactly as far as the finger, every frame, and stop when+/// it does.+///+/// The production `TerminalView`, set up for Claude Code as `TerminalPanel`+/// sets it up, in a profile build, touched through the device's own dispatch.+/// Behind it either Claude Code faked in the app (`CLAUDE_SCROLL_PROGRAM=fake`,+/// the default: the same every run) or the real one on a Mac+/// (`=live`, through `claude_scroll/claude_bridge.py`). See+/// `integration_test/README.md`.+void main() {+ final binding = PerfBinding()+ ..framePolicy = LiveTestWidgetsFlutterBindingFramePolicy.benchmarkLive;+ final options = ClaudeScrollOptions.fromEnvironment();++ testWidgets('Claude Code scroll on the phone', (tester) async {+ final bench = ClaudeScrollBench(tester, binding, options);+ try {+ await bench.run();+ } finally {+ await tester.pumpWidget(const SizedBox.shrink());+ bench.dispose();+ binding.reportData = bench.results;+ }+ if (bench.failures.isNotEmpty) {+ fail('Scenarios failed: ${bench.failures}');+ }+ }, timeout: const Timeout(Duration(minutes: 15)));+}diff --git a/mobile/integration_test/perf/frames.dart b/mobile/integration_test/perf/frames.dartindex 7331095f3..e75270e58 100644--- a/mobile/integration_test/perf/frames.dart+++ b/mobile/integration_test/perf/frames.dart@@ -119,6 +119,7 @@ const int frameBudgetMicros = 16667;Map<String, Object?> frameStats(List<ui.FrameTiming> frames, {required int windowMicros,+ int budgetMicros = frameBudgetMicros,}) {List<int> pick(int Function(ui.FrameTiming) f) => [for (final t in frames) f(t),@@ -127,8 +128,7 @@ Map<String, Object?> frameStats(final raster = pick((t) => t.rasterDuration.inMicroseconds);final vsync = pick((t) => t.vsyncOverhead.inMicroseconds);final total = pick((t) => t.totalSpan.inMicroseconds);- int over(List<int> values) =>- values.where((v) => v > frameBudgetMicros).length;+ int over(List<int> values) => values.where((v) => v > budgetMicros).length;return {'frames': frames.length,'windowMs': windowMicros / 1000,@@ -138,7 +138,7 @@ Map<String, Object?> frameStats('vsyncOverheadMs': distribution(vsync),'totalSpanMs': distribution(total),'framesOverBudget': {- 'budgetMs': frameBudgetMicros / 1000,+ 'budgetMs': budgetMicros / 1000,'build': over(build),'raster': over(raster),'totalSpan': over(total),diff --git a/mobile/pubspec.yaml b/mobile/pubspec.yamlindex bf0d15f99..9a2eae8fb 100644--- a/mobile/pubspec.yaml+++ b/mobile/pubspec.yaml@@ -2,7 +2,7 @@ name: harness_mobiledescription: "Harness viewer for iOS and Android."publish_to: 'none'-version: 1.0.9+72+version: 1.0.10+74environment:sdk: ^3.13.0diff --git a/mobile/test/remote_scroll_mirror_test.dart b/mobile/test/remote_scroll_mirror_test.dartnew file mode 100644index 000000000..396f37784--- /dev/null+++ b/mobile/test/remote_scroll_mirror_test.dart@@ -0,0 +1,801 @@+import 'dart:async';+import 'dart:math' as math;++import 'package:flutter_test/flutter_test.dart';+import 'package:xterm/xterm.dart';+// The mirror is not exported: the phone reaches it through TerminalView, and+// what is tested here lives in it.+// ignore: implementation_imports+import 'package:xterm/src/ui/remote_scroll_mirror.dart';++/// Claude Code's fullscreen renderer as far as [RemoteScrollMirror] sees it: a+/// transcript in the top rows, moved by wheel rows and Page Up/Down (half the+/// transcript's height), with its prompt box and footer pinned below — a blank+/// row between the transcript and the box, as 2.1.309 draws it.+class _FakeClaudeCode {+ _FakeClaudeCode({int transcriptRows = 900})+ : transcript = [+ for (var n = 0; n < transcriptRows; n++)+ 'message $n ${_words[n % _words.length]}',+ ] {+ terminal.resize(columns, rowCount);+ terminal.write('\x1b[?1049h');+ top = transcript.length - scrollingRows;+ draw();+ }++ static const _words = ['alpha', 'bravo', 'charlie', 'delta', 'echo'];++ static const columns = 40;+ static const rowCount = 40;+ static const scrollingRows = 33;+ static const page = scrollingRows ~/ 2;+ static const lineHeight = 10.0;++ final List<String> transcript;+ final terminal = Terminal();++ /// The transcript row shown at screen row 0.+ late int top;++ void scroll(int rows) {+ top = (top + rows).clamp(0, transcript.length - scrollingRows);+ }++ void draw() {+ final out = StringBuffer();+ for (var i = 0; i < rowCount; i++) {+ out.write('\x1b[${i + 1};1H\x1b[2K${_row(i)}');+ }+ terminal.write(out.toString());+ }++ String _row(int i) {+ if (i < scrollingRows) return transcript[top + i];+ return switch (i - scrollingRows) {+ 1 || 3 => '─' * columns,+ 2 => '❯ ',+ 5 => ' ? for shortcuts',+ _ => '',+ };+ }+}++/// The scroll handler's side of the mirror over a link: wheel rows and page+/// keys reach the program [latency] later, and its redraw lands at once. Like+/// the handler it counts a batch answered by any write, or after 120 ms with+/// none (`TerminalScrollGestureHandler`'s `_answerWaitLimit`): on a link+/// slower than that, [idle] says so before the redraw has landed.+class _Link {+ _Link(this.claude, {this.latency = const Duration(milliseconds: 45)});++ /// From a request going out to the program's redraw landing: by default+ /// about a page key's round trip in a long session (42ms p50, measured on a+ /// phone, 2026-10-07).+ final Duration latency;++ final _FakeClaudeCode claude;+ late final RemoteScrollMirror mirror;++ var inFlight = 0;+ var pages = 0;+ var wheelRows = 0;++ /// Set once the test is done: what is still on its way lands nowhere.+ var closed = false;++ /// How many page keys went in each batch, in order.+ final pageBatches = <int>[];++ /// Batches the handler would count unanswered.+ var _unanswered = 0;+ Timer? _answerWait;++ bool get idle => _unanswered == 0;++ void _sent() {+ _unanswered++;+ _answerWait?.cancel();+ _answerWait = Timer(const Duration(milliseconds: 120), () {+ _unanswered = 0;+ });+ }++ void lines(int rows) {+ inFlight++;+ wheelRows += rows.abs();+ _sent();+ Timer(latency, () => _land(rows));+ }++ bool page(int direction, int count) {+ if (_unanswered > 0) return false;+ inFlight++;+ _sent();+ pages += count;+ pageBatches.add(count);+ Timer(latency, () => _land(direction * count * _FakeClaudeCode.page));+ return true;+ }++ void _land(int rows) {+ inFlight--;+ if (_unanswered > 0) _unanswered--;+ if (!closed) redraw(rows);+ }++ /// The program scrolled [rows] — or not at all — and drew its screen.+ void redraw([int rows = 0]) {+ claude.scroll(rows);+ claude.draw();+ mirror.frame(+ claude.terminal.buffer.lines,+ _FakeClaudeCode.rowCount,+ _FakeClaudeCode.lineHeight,+ );+ }+}++/// A mirror over [link]; [fetchAhead] lets it read the screen for itself, as+/// the phone's does, and so fetch rows ahead while nobody scrolls.+RemoteScrollMirror _mirrorOf(+ WidgetTester tester,+ _Link link, {+ RemoteScrollMemory? memory,+ bool fetchAhead = false,+}) {+ final mirror = RemoteScrollMirror(+ onFrame: () {},+ requestLines: link.lines,+ requestsIdle: () => link.idle,+ cancelRequests: () => 0,+ pageKeysEnabled: () => true,+ requestPage: link.page,+ readScreen: fetchAhead+ ? () => (+ lines: link.claude.terminal.buffer.lines,+ rowCount: _FakeClaudeCode.rowCount,+ lineHeight: _FakeClaudeCode.lineHeight,+ )+ : null,+ clock: tester.binding.clock.stopwatch(),+ )..memory = memory;+ link.mirror = mirror;+ return mirror;+}++const _frame = Duration(milliseconds: 16);++/// A finger on the glass at [pixels], moving [rowsPerFrame] rows up every+/// frame for [frames] frames — then left there.+Future<void> _drag(+ WidgetTester tester,+ RemoteScrollMirror mirror,+ _FakeClaudeCode claude, {+ required double pixels,+ required int frames,+ required double rowsPerFrame,+}) async {+ final lines = claude.terminal.buffer.lines;+ const rowCount = _FakeClaudeCode.rowCount;+ const lineHeight = _FakeClaudeCode.lineHeight;+ mirror.begin(pixels, lines, rowCount, lineHeight);+ for (var f = 0; f < frames; f++) {+ await tester.pump(_frame);+ pixels -= rowsPerFrame * lineHeight;+ mirror.scrollTo(pixels, lines, rowCount, lineHeight);+ }+}++/// The finger lifted, and everything the program still has to do done.+Future<void> _lift(WidgetTester tester, RemoteScrollMirror mirror) async {+ mirror.end();+ for (var f = 0; f < 150; f++) {+ await tester.pump(_frame);+ }+}++/// The test over: [mirror] gone, and what [link] still had on its way let+/// land on nothing.+Future<void> _close(+ WidgetTester tester,+ RemoteScrollMirror mirror,+ _Link link,+) async {+ link.closed = true;+ mirror.dispose();+ await tester.pump(link.latency + const Duration(milliseconds: 150));+}++/// A slow scroll a few rows up, come to rest: where the mirror learns which+/// rows scroll, before it draws any of them.+Future<void> _learnScrollingRows(+ WidgetTester tester,+ RemoteScrollMirror mirror,+ _FakeClaudeCode claude,+) async {+ await _drag(tester, mirror, claude, pixels: 0, frames: 4, rowsPerFrame: 1);+ await _lift(tester, mirror);+}++/// Where [bestPlacing] puts [probe] when every placing is tried in turn, as+/// the mirror did before it voted: the reference it must agree with.+({int d, int agree, int share, int runnerUp})? _placingTriedEverywhere(+ List<int> probe,+ List<int> screen,+ Map<int, int> known,+ int origin,+ int lowest,+ int highest, {+ bool Function(int d)? skip,+}) {+ ({int d, int agree, int share})? best;+ var runnerUp = 0;+ for (var d = lowest; d <= highest; d++) {+ if (skip != null && skip(d)) continue;+ var agree = 0;+ var comparable = 0;+ for (final i in probe) {+ final kept = known[origin + i + d];+ if (kept == null) continue;+ comparable++;+ if (kept == screen[i]) agree++;+ }+ if (agree == 0) continue;+ final current = best;+ if (current == null || agree > current.agree) {+ if (current != null) runnerUp = math.max(runnerUp, current.agree);+ best = (d: d, agree: agree, share: comparable);+ } else {+ runnerUp = math.max(runnerUp, agree);+ }+ }+ final found = best;+ if (found == null) return null;+ return (+ d: found.d,+ agree: found.agree,+ share: found.share,+ runnerUp: runnerUp,+ );+}++({int d, int agree, int share, int runnerUp})? _vote(+ List<int> probe,+ List<int> screen,+ Map<int, int> known,+ int origin,+ int lowest,+ int highest, {+ bool Function(int d)? skip,+}) => bestPlacing(+ probe: probe,+ signatureOf: (i) => screen[i],+ bySignature: rowsBySignature(known, (signature) => signature),+ isKnown: known.containsKey,+ origin: origin,+ lowest: lowest,+ highest: highest,+ skip: skip,+);++void main() {+ group('bestPlacing', () {+ test('places a screen exactly where trying every placing does', () {+ final random = math.Random(20261023);+ var placed = 0;+ for (var round = 0; round < 400; round++) {+ // Few distinct texts, so rows repeat and placings tie — as a+ // transcript's rules, blank-ish rows and repeated output do.+ final texts = 1 + random.nextInt(12);+ final from = random.nextInt(400) - 200;+ final count = random.nextInt(400);+ final known = <int, int>{+ for (var row = from; row < from + count; row++)+ if (random.nextInt(6) != 0) row: random.nextInt(texts),+ };+ final screenRows = 5 + random.nextInt(36);+ final origin = random.nextInt(200) - 100;+ final screen = [+ for (var i = 0; i < screenRows; i++) random.nextInt(texts),+ ];+ // Half the time the screen shows rows that are known, here and there+ // drawn over, as a scroll's frame does.+ if (random.nextBool() && count > 0) {+ final at = from + random.nextInt(count) - origin;+ for (var i = 0; i < screenRows; i++) {+ final kept = known[origin + i + at];+ if (kept != null && random.nextInt(8) != 0) screen[i] = kept;+ }+ }+ final probe = [+ for (var i = 0; i < screenRows; i++)+ if (random.nextInt(4) != 0) i,+ ];+ if (probe.isEmpty || known.isEmpty) continue;+ final knownMin = known.keys.reduce(math.min) - origin;+ final knownMax = known.keys.reduce(math.max) - origin;+ final reach = random.nextInt(60);+ final skip = random.nextBool() ? (int d) => d.abs() <= reach : null;+ final lowest = knownMin - probe.last;+ final highest = knownMax - probe.first;+ final expected = _placingTriedEverywhere(+ probe,+ screen,+ known,+ origin,+ lowest,+ highest,+ skip: skip,+ );+ expect(+ _vote(probe, screen, known, origin, lowest, highest, skip: skip),+ expected,+ reason: 'round $round',+ );+ if (expected != null) placed++;+ }+ // The comparison means something only if most rounds placed a screen.+ expect(placed, greaterThan(300));+ });++ test('a tie goes to the lowest placing, the other is the runner-up', () {+ // Rows 0..3 say A B A B: a screen showing A B fits at 0 and at 2.+ final known = {0: 1, 1: 2, 2: 1, 3: 2};+ expect(_vote([0, 1], [1, 2], known, 0, -1, 3), (+ d: 0,+ agree: 2,+ share: 2,+ runnerUp: 2,+ ));+ // Placings left out are neither best nor runner-up.+ expect(_vote([0, 1], [1, 2], known, 0, -1, 3, skip: (d) => d == 0), (+ d: 2,+ agree: 2,+ share: 2,+ runnerUp: 0,+ ));+ });++ test('counts as share the probe rows that land on a known row', () {+ // Row 5 is a hole: the screen's second row lands on it at d=4.+ final known = {4: 7, 6: 9, 7: 3};+ expect(_vote([0, 1, 2], [7, 8, 9], known, 0, 2, 7), (+ d: 4,+ agree: 2,+ share: 2,+ runnerUp: 0,+ ));+ });++ test('is null when no placing agrees, or nothing is probed', () {+ final known = {0: 1, 1: 2};+ expect(_vote([0, 1], [5, 6], known, 0, -1, 1), isNull);+ expect(_vote(const [], const [], known, 0, 0, 1), isNull);+ // The only agreeing placing is outside the range asked about.+ expect(_vote([0], [2], known, 0, 2, 5), isNull);+ // No range at all.+ expect(_vote([0], [1], known, 0, 1, 0), isNull);+ });+ });++ group('RemoteScrollMirror over Claude Code', () {+ testWidgets('a fast fling into rows not yet seen sends the next page before the '+ 'finger reaches their edge', (tester) async {+ final claude = _FakeClaudeCode();+ final link = _Link(claude);+ final mirror = _mirrorOf(tester, link);+ await _learnScrollingRows(tester, mirror, claude);+ expect(mirror.top, 0);+ expect(mirror.bottom, _FakeClaudeCode.scrollingRows - 1);++ // A flick of ~310 rows a second for a second: faster than wheel rows+ // bring rows in, so the screen keeps up only while pages arrive ahead of+ // the finger.+ final pagesBefore = link.pages;+ final startedAt = mirror.display;+ await _drag(+ tester,+ mirror,+ claude,+ pixels: 0,+ frames: 60,+ rowsPerFrame: 5,+ );+ final moved = startedAt - mirror.display;++ // A page goes as the last one lands, not once the finger has caught up+ // with it: 19 pages, the screen 290 rows behind a finger at 300. Sent+ // only at the edge, each page waited for the finger to get there and then+ // held the screen for its round trip: 12 pages, 200 rows.+ expect(link.pages - pagesBefore, greaterThanOrEqualTo(16));+ expect(moved, greaterThanOrEqualTo(260));+ // Every row drawn is the program's own row there.+ for (var s = mirror.top; s <= mirror.bottom; s++) {+ final row = mirror.display.round() + s;+ expect(+ mirror.rowAt(row)?.getText().trimRight(),+ claude.transcript[claude.transcript.length -+ _FakeClaudeCode.scrollingRows ++ row],+ reason: 'document row $row',+ );+ }++ await _lift(tester, mirror);+ await _close(tester, mirror, link);+ });++ testWidgets('a new emulator takes back the rows read before, placed where the '+ 'program has moved to, without asking for them again', (tester) async {+ final claude = _FakeClaudeCode();+ final memory = RemoteScrollMemory();+ final firstLink = _Link(claude);+ final first = _mirrorOf(tester, firstLink, memory: memory);+ await _learnScrollingRows(tester, first, claude);+ // Read 60 rows back, and stay there.+ await _drag(+ tester,+ first,+ claude,+ pixels: 0,+ frames: 30,+ rowsPerFrame: 2,+ );+ await _lift(tester, first);+ // Where the screen came to rest, rows above where it started.+ final rested = -first.display.round();+ firstLink.closed = true;+ first.dispose();++ // The program moved on meanwhile; a keyframe brings a new emulator.+ claude.scroll(5);+ claude.draw();+ final link = _Link(claude);+ final second = _mirrorOf(tester, link, memory: memory);+ second.begin(+ 0,+ claude.terminal.buffer.lines,+ _FakeClaudeCode.rowCount,+ _FakeClaudeCode.lineHeight,+ );++ // Rows above the screen are drawn at once: the program's own rows there.+ var above = 0;+ for (var row = -1; ; row--) {+ final line = second.rowAt(row);+ if (line == null) break;+ expect(+ line.getText().trimRight(),+ claude.transcript[claude.top + row],+ reason: 'row $row above the screen',+ );+ above++;+ }+ // And below it, every row read on the way up: down to the newest, less+ // the 5 the program has moved on since.+ var below = 0;+ for (var row = _FakeClaudeCode.scrollingRows; ; row++) {+ final line = second.rowAt(row);+ if (line == null) break;+ expect(+ line.getText().trimRight(),+ claude.transcript[claude.top + row],+ reason: 'row $row below the screen',+ );+ below++;+ }+ expect(rested, greaterThan(20));+ expect(above, greaterThan(0));+ expect(below, rested - 5);+ expect(link.wheelRows, 0);+ expect(link.pages, 0);++ await _lift(tester, second);+ await _close(tester, second, link);+ });++ testWidgets('an agent nobody has scrolled fetches the rows above while it is '+ 'quiet, its scrolling rows read off the prompt box', (tester) async {+ final claude = _FakeClaudeCode();+ final link = _Link(claude);+ final mirror = _mirrorOf(tester, link, fetchAhead: true);+ final newest = claude.top;+ // The program draws once, then is quiet: no scroll has taught the mirror+ // anything.+ link.redraw();+ for (var f = 0; f < 250; f++) {+ await tester.pump(_frame);+ }++ expect(link.pages, greaterThan(0));+ // The rows read off the prompt box: all above it but the first and the+ // one over the box's rule — widened to every row that moved with them.+ expect(mirror.top, 0);+ expect(mirror.bottom, _FakeClaudeCode.scrollingRows - 1);+ // Hundreds of rows above the screen are known, as the program showed+ // them, and the program is back on the screen's row.+ for (final row in [-1, -100, -350]) {+ expect(+ mirror.rowAt(row)?.getText().trimRight(),+ claude.transcript[newest + row],+ reason: 'document row $row',+ );+ }+ expect(claude.top, newest);+ expect(mirror.isActive, isFalse);++ // The first scroll is drawn from them at once, nothing to learn first.+ mirror.begin(+ 0,+ claude.terminal.buffer.lines,+ _FakeClaudeCode.rowCount,+ _FakeClaudeCode.lineHeight,+ );+ expect(mirror.isActive, isTrue);+ await _lift(tester, mirror);+ await _close(tester, mirror, link);+ });++ testWidgets(+ 'fetching ahead never blanks a row of the screen nobody scrolled',+ (tester) async {+ final claude = _FakeClaudeCode();+ final link = _Link(claude);+ final mirror = _mirrorOf(tester, link, fetchAhead: true);+ final newest = claude.top;+ link.redraw();+ // Every frame while it fetches and comes back: each row that scrolls+ // is drawn — from the document — as the screen showed it.+ var checked = 0;+ for (var f = 0; f < 250; f++) {+ await tester.pump(_frame);+ if (!mirror.isActive) continue;+ expect(mirror.display, 0);+ for (var s = mirror.top; s <= mirror.bottom; s++) {+ expect(+ mirror.rowAt(s)?.getText().trimRight(),+ claude.transcript[newest + s],+ reason: 'screen row $s, ${f * 16} ms in',+ );+ }+ checked++;+ }+ expect(checked, greaterThan(50));+ await _close(tester, mirror, link);+ },+ );++ testWidgets(+ 'rows already known are crossed several pages at a time, every frame '+ 'placed',+ (tester) async {+ final claude = _FakeClaudeCode();+ final link = _Link(claude);+ final mirror = _mirrorOf(tester, link, fetchAhead: true);+ final newest = claude.top;+ link.redraw();+ for (var f = 0; f < 250; f++) {+ await tester.pump(_frame);+ }+ // Coming back from fetching ahead, the program crossed what it fetched.+ expect(link.pageBatches.where((count) => count > 1), isNotEmpty);+ expect(link.pageBatches.every((count) => count <= 3), isTrue);++ // A flick over them: the program follows several pages at a time, and+ // the screen keeps with the finger the whole way.+ final batchesBefore = link.pageBatches.length;+ await _drag(+ tester,+ mirror,+ claude,+ pixels: 0,+ frames: 40,+ rowsPerFrame: 6,+ );+ expect(+ link.pageBatches.skip(batchesBefore).where((count) => count > 1),+ isNotEmpty,+ );+ expect(mirror.display, closeTo(-240, 1));+ for (var s = mirror.top; s <= mirror.bottom; s++) {+ final row = mirror.display.round() + s;+ expect(+ mirror.rowAt(row)?.getText().trimRight(),+ claude.transcript[newest + row],+ reason: 'document row $row',+ );+ }+ await _lift(tester, mirror);+ await _close(tester, mirror, link);+ },+ );++ testWidgets(+ 'scrolled up and back past the newest row, the program is left on it',+ (tester) async {+ final claude = _FakeClaudeCode();+ final link = _Link(claude);+ final mirror = _mirrorOf(tester, link);+ final newest = claude.top;+ // Up a few rows from the newest one, then down past it.+ link.redraw();+ await tester.pump(const Duration(seconds: 1));+ await _drag(+ tester,+ mirror,+ claude,+ pixels: 0,+ frames: 6,+ rowsPerFrame: 1,+ );+ await _lift(tester, mirror);+ expect(claude.top, lessThan(newest));+ await _drag(+ tester,+ mirror,+ claude,+ pixels: 0,+ frames: 12,+ rowsPerFrame: -1,+ );+ await _lift(tester, mirror);+ expect(claude.top, newest);+ expect(mirror.isActive, isFalse);+ await _close(tester, mirror, link);+ },+ );++ testWidgets(+ 'over a slow link the program is left on the row the screen rests on',+ (tester) async {+ final claude = _FakeClaudeCode();+ // A phone on a cellular link: a redraw 250 ms after its request.+ final link = _Link(claude, latency: const Duration(milliseconds: 250));+ final mirror = _mirrorOf(tester, link);+ final newest = claude.top;+ link.redraw();+ await tester.pump(const Duration(seconds: 1));+ for (var drag = 0; drag < 3; drag++) {+ await _drag(+ tester,+ mirror,+ claude,+ pixels: 0,+ frames: 10,+ rowsPerFrame: 1,+ );+ // Held a moment, then lifted with no fling.+ await tester.pump(const Duration(milliseconds: 150));+ await _lift(tester, mirror);+ expect(mirror.isActive, isFalse);+ // Where the screen rests is where the program is: nothing of what it+ // was asked is still to land and move it on.+ expect(+ claude.top - newest,+ mirror.display.round(),+ reason: 'drag $drag',+ );+ await tester.pump(const Duration(seconds: 1));+ expect(+ claude.top - newest,+ mirror.display.round(),+ reason: 'drag $drag',+ );+ }+ await _close(tester, mirror, link);+ },+ );++ testWidgets(+ 'a drag that catches the last scroll still gliding moves the rows as '+ 'far as the finger, frame for frame',+ (tester) async {+ final claude = _FakeClaudeCode();+ final link = _Link(claude);+ final mirror = _mirrorOf(tester, link, fetchAhead: true);+ link.redraw();+ // Rows above fetched ahead, so the drags below cross only rows known.+ for (var f = 0; f < 250; f++) {+ await tester.pump(_frame);+ }+ final lines = claude.terminal.buffer.lines;+ const rowCount = _FakeClaudeCode.rowCount;+ const lineHeight = _FakeClaudeCode.lineHeight;+ // A flick, let go moving: the screen glides on towards its row.+ var pixels = 0.0;+ mirror.begin(pixels, lines, rowCount, lineHeight);+ for (var f = 0; f < 6; f++) {+ await tester.pump(_frame);+ pixels -= 6 * lineHeight;+ mirror.scrollTo(pixels, lines, rowCount, lineHeight);+ }+ mirror.end();+ // Caught mid-glide by the next drag, 4 rows a frame: the rows go with+ // the finger from its first move — what the glide had left is taken in+ // within a few frames, and from then on the screen is where the finger+ // has it, not a spring's v/ω behind.+ mirror.begin(pixels, lines, rowCount, lineHeight);+ final startedAt = mirror.display;+ final behind = <double>[];+ for (var f = 0; f < 20; f++) {+ await tester.pump(_frame);+ pixels -= 4 * lineHeight;+ mirror.scrollTo(pixels, lines, rowCount, lineHeight);+ behind.add((mirror.display - startedAt) - (-4.0 * (f + 1)));+ }+ for (final rows in behind.skip(8)) {+ expect(rows.abs(), lessThan(0.5), reason: 'behind $behind');+ }+ await _lift(tester, mirror);+ await _close(tester, mirror, link);+ },+ );++ testWidgets(+ 'a program still drawing does not have its rows read off the prompt '+ 'box: its first scroll learns them',+ (tester) async {+ final claude = _FakeClaudeCode();+ final link = _Link(claude);+ final mirror = _mirrorOf(tester, link);+ // A frame just now — at work, a spinner over the box would be taken+ // for content.+ link.redraw();+ mirror.begin(+ 0,+ claude.terminal.buffer.lines,+ _FakeClaudeCode.rowCount,+ _FakeClaudeCode.lineHeight,+ );+ expect(mirror.bottom, -1);+ expect(mirror.isActive, isFalse);+ await _lift(tester, mirror);+ await _close(tester, mirror, link);+ },+ );++ testWidgets(+ 'a long read back keeps the rows around the screen and lets go of '+ 'those far behind it',+ (tester) async {+ final claude = _FakeClaudeCode(transcriptRows: 8000);+ final link = _Link(claude);+ final mirror = _mirrorOf(tester, link);+ await _learnScrollingRows(tester, mirror, claude);++ await _drag(+ tester,+ mirror,+ claude,+ pixels: 0,+ frames: 1000,+ rowsPerFrame: 6,+ );+ final shown = mirror.display.round();+ // Further back than the rows kept either side of the screen (2,000)+ // and a screen: the rows read first are gone.+ expect(shown, lessThan(-4100));+ expect(mirror.rowAt(0), isNull);+ expect(mirror.rowAt(mirror.top + 10), isNull);+ // Those on the screen and within reach below it are kept, as read.+ final bottomRow =+ claude.transcript.length - _FakeClaudeCode.scrollingRows;+ for (final row in [+ shown + mirror.top,+ shown + mirror.bottom,+ shown + mirror.bottom + 1500,+ ]) {+ expect(+ mirror.rowAt(row)?.getText().trimRight(),+ claude.transcript[bottomRow + row],+ reason: 'document row $row',+ );+ }++ await _lift(tester, mirror);+ await _close(tester, mirror, link);+ },+ );+ });+}diff --git a/mobile/test_driver/claude_scroll_driver.dart b/mobile/test_driver/claude_scroll_driver.dartnew file mode 100644index 000000000..de1ce9ae0--- /dev/null+++ b/mobile/test_driver/claude_scroll_driver.dart@@ -0,0 +1,45 @@+// A command-line driver; printing is its interface.+// ignore_for_file: avoid_print++import 'dart:convert';+import 'dart:io';++import 'package:integration_test/integration_test_driver.dart';++/// Host side of `integration_test/claude_scroll_test.dart`: writes the phone's+/// results to `HARNESS_SCROLL_OUT` (default `build/claude_scroll/`) as+/// `<HARNESS_SCROLL_LABEL>-<UTC time>.json`, never over an earlier run, and+/// prints the summary.+Future<void> main() => integrationDriver(+ timeout: const Duration(minutes: 20),+ writeResponseOnFailure: true,+ responseDataCallback: (data) async {+ if (data == null) {+ print('[scroll] the phone reported no data');+ return;+ }+ final env = Platform.environment;+ final directory = Directory(+ env['HARNESS_SCROLL_OUT'] ?? 'build/claude_scroll',+ );+ await directory.create(recursive: true);+ final label = env['HARNESS_SCROLL_LABEL'] ?? 'run';+ final stamp = DateTime.now()+ .toUtc()+ .toIso8601String()+ .replaceAll(RegExp(r'[:\-]'), '')+ .split('.')+ .first;+ var file = File('${directory.path}/$label-${stamp}Z.json');+ for (var n = 2; file.existsSync(); n++) {+ file = File('${directory.path}/$label-${stamp}Z-$n.json');+ }+ await file.writeAsString(const JsonEncoder.withIndent(' ').convert(data));+ print('[scroll] wrote ${file.path}');+ print('[scroll] summary ${jsonEncode(data['summary'])}');+ if (data['failures'] case final Map<String, dynamic> failures+ when failures.isNotEmpty) {+ print('[scroll] FAILED $failures');+ }+ },+);diff --git a/mobile/third_party/xterm/README.autonomous.md b/mobile/third_party/xterm/README.autonomous.mdindex a5aaa24a8..50e89951b 100644--- a/mobile/third_party/xterm/README.autonomous.md+++ b/mobile/third_party/xterm/README.autonomous.md@@ -294,3 +294,26 @@ it if one is dropped.visual: emulator, hit-testing and selection see the new screen at once. Achange that is not a recognisable scroll ends any slide on the spot, as thescreen behaved before. False draws each redraw as it lands, as upstream.++21. **A full-screen program's scroll is drawn from rows kept here**+ (`lib/src/ui/remote_scroll_mirror.dart`, `TerminalView.altBufferScrollMirror`).+ The finger moves a document of the program's rows; the program is asked to+ scroll ahead of it — a page at a time once the finger is fast, the next+ page sent before the finger reaches the edge of what is known, several+ pages together where they land among rows already known — and each frame+ it draws is placed in the document. With page keys on (Claude Code), which+ rows scroll is read off its prompt box while it is quiet, so the first+ scroll of an agent is drawn from the document and the 400 rows above are+ fetched ahead before anyone scrolls; the blank row over the box never+ joins the rows that scroll. "Quiet" waits a little over how long the+ program has lately taken to answer, so a slow link does not have it asked+ twice. Catching up — still gliding, or let go of the edge of what is+ known — the screen still moves with the finger, the spring taking in only+ what lies between them, not trailing the finger by its speed. A page up+ that goes nowhere marks the top of the transcript. A frame placed far off,+ and rows set aside to be found again, are+ looked up by row text (`bestPlacing`, `rowsBySignature`) rather than tried+ at every placing. Regressions: `mobile/test/remote_scroll_mirror_test.dart`,+ against a fake Claude Code; measured on a phone by+ `mobile/integration_test/claude_scroll_test.dart`, results in+ `mobile/integration_test/claude_scroll/RESULTS.md`.diff --git a/mobile/third_party/xterm/lib/src/ui/remote_scroll_mirror.dart b/mobile/third_party/xterm/lib/src/ui/remote_scroll_mirror.dartindex ef31078a3..98f569918 100644--- a/mobile/third_party/xterm/lib/src/ui/remote_scroll_mirror.dart+++ b/mobile/third_party/xterm/lib/src/ui/remote_scroll_mirror.dart@@ -1,7 +1,9 @@import 'dart:async';import 'dart:math' as math;+import 'dart:typed_data';import 'package:flutter/scheduler.dart';+import 'package:meta/meta.dart' show visibleForTesting;import 'package:xterm/src/core/buffer/line.dart';import 'package:xterm/src/core/cell.dart';import 'package:xterm/src/utils/circular_buffer.dart';@@ -38,7 +40,9 @@ class RemoteScrollMirror {this.pageKeysEnabled,this.requestPage,this.readScreen,- });+ // A test's own clock, which its fake time moves.+ @visibleForTesting Stopwatch? clock,+ }) : _clock = (clock ?? Stopwatch())..start();/// The program's whole screen now, for [_prefetch] to start from — null/// when it cannot be read whole (a frame still arriving, another screen).@@ -48,9 +52,9 @@ class RemoteScrollMirror {/// Page Down keys at all — see [_pageOrWait].final bool Function()? pageKeysEnabled;- /// Press Page Down ([direction] positive) or Page Up once, alone; false when- /// it was not sent.- final bool Function(int direction)? requestPage;+ /// Press Page Down ([direction] positive) or Page Up [count] times, alone;+ /// false when it was not sent.+ final bool Function(int direction, int count)? requestPage;/// Something drawn from here moved: paint again.final VoidCallback onFrame;@@ -153,17 +157,62 @@ class RemoteScrollMirror {/// A page shorter than this is not worth a key: wheel events do as well.static const _minPage = 6;+ /// The most page keys sent together, where they land among rows already+ /// known — see [_pagesAtOnce].+ static const _maxPagesAtOnce = 3;+/// A finger faster than this, in rows a second, is scrolled after with page/// keys only — see [_pageOrWait]'s `fast`.static const _pageSpeed = 120.0;+ /// About how long a page key takes to come back as a frame placed, in+ /// seconds: what the finger covers meanwhile is how far short of the edge of+ /// what is known the next page goes — see [_pageLeadRows].+ ///+ /// ⚠️ **A page asked for at the edge came too late.** Kept [_leadMax] rows+ /// ahead of the finger, no more than a page, the next page went only once+ /// the finger had reached the edge — and the screen held there for its round+ /// trip (42ms p50, 113ms p90), each flick 78ms (p50) before its first page:+ /// two pages a flick, the program ~150 rows a second against a finger at+ /// ~400 (measured on a phone, 2026-10-07). Sent this far short, a page lands+ /// about as the finger gets there (p75 51ms).+ static const _pageLatency = 0.08;+/// How long the program must have drawn nothing, and the finger been off the/// glass, before the rows above are fetched ahead — see [_prefetch].- static const _prefetchAfter = Duration(milliseconds: 1200);+ ///+ /// ⚠️ **A thumb goes back soon after it reads.** At 1.2 s, with the settle+ /// before it, fetching ahead had barely begun when the next flick came, and+ /// the flick met the edge of what was known at once (an iPhone 14 against+ /// Claude Code faked over a 100 ms round trip, 2026-10-23). It gives way to+ /// the finger the moment it comes ([begin]), with the program already part+ /// of the way up.+ static const _prefetchAfter = Duration(milliseconds: 500);++ /// How many rows above the screen [_prefetch] has the document reach: ten+ /// screens of a phone.+ ///+ /// ⚠️ **What is fetched ahead is all a flick gets at the finger's pace.**+ /// Rows not yet seen come a page a round trip, ~160 a second, against a+ /// flick of 300–400; over rows known the screen keeps up with the finger+ /// (an iPhone 14 against Claude Code faked over a 100 ms round trip,+ /// 2026-10-23: from 120 rows to 400, a flick's screen went 62% of the+ /// finger's way to 71%). The program crosses them again several pages at a+ /// time ([_pagesAtOnce]), so coming back costs a few round trips.+ static const _prefetchRows = 400;++ /// The fewest rows a fetch ahead must add to be worth one.+ ///+ /// ⚠️ **One row short, it went round again.** The rows that scroll widened+ /// by one after a fetch, the rows known above the screen came to one less+ /// than [_prefetchRows], and the program crossed all of them again for that+ /// one row, and back — on and on (a test against a fake of 2.1.309,+ /// 2026-10-24). Every fetch scrolls the agent's screen on its computer.+ static const _prefetchGain = 100;- /// How many rows above the screen [_prefetch] has the document reach: three- /// or four screens of a phone.- static const _prefetchRows = 120;+ /// How long the program must have drawn nothing for its prompt box to say+ /// which rows scroll — see [_seedScrollingRows].+ static const _seedQuiet = Duration(milliseconds: 300);/// About how fast the program scrolls, in rows a second: four wheel events/// every 50ms (`_exactBurst` and `_burstGap` in the scroll handler) move it@@ -207,10 +256,14 @@ class RemoteScrollMirror {static const _stillAfter = Duration(milliseconds: 100);/// How long the program must have stood still before the screen goes back to- /// it — see [_checkSettled].+ /// it — see [_checkSettled] — at the least: over a slower link, longer+ /// ([_quietMs]).static const _settleQuiet = Duration(milliseconds: 100);- final _clock = Stopwatch()..start();+ /// The longest [_quietMs] waits, however slow the program has answered.+ static const _quietMost = Duration(milliseconds: 1000);++ final Stopwatch _clock;// The grid the document is in; any change and it is dropped.int _rowCount = 0;@@ -240,10 +293,21 @@ class RemoteScrollMirror {/// Rows known before the document last had to start again, in their own/// numbering, and the first and last of them — see [_setAside].- Map<int, _DocRow>? _aside;+ Map<int, _DocRow>? get _aside => _asideRows;+ set _aside(Map<int, _DocRow>? rows) {+ _asideRows = rows;+ _asideBySignature = null;+ }++ Map<int, _DocRow>? _asideRows;int _asideMin = 0;int _asideMax = -1;+ /// [_aside] by what its rows say ([rowsBySignature]), made the first time+ /// [_reattach] looks among them and kept until they are taken back or+ /// replaced: it looks again on every frame of a scroll, among the same rows.+ Map<int, List<int>>? _asideBySignature;+/// The screen [_reattach] last looked for among the rows set aside, and when.int? _reattachTried;int _reattachAtMs = -1 << 30;@@ -253,9 +317,13 @@ class RemoteScrollMirror {int _missesInARow = 0;/// Whether the program's last whole screen showed its prompt — when a page- /// key scrolls its transcript ([_promptShown]).+ /// key scrolls its transcript ([_promptRow]).bool _pageKeysSafe = false;+ /// The screen row of the prompt the program's last whole screen showed, for+ /// a program whose page keys scroll it — or -1 — see [_lowestScrollingRow].+ int _promptAt = -1;+/// Whether a page key was refused this scroll: wheel events from then on.bool _pageKeysRefused = false;@@ -263,6 +331,7 @@ class RemoteScrollMirror {/// nothing else was — see [_pageOrWait] and [_pageLanded].bool _pageInFlight = false;int _pageDirection = 0;+ int _pageCount = 1;int _pageSentAtMs = 0;int _pageFromRemote = 0;@@ -315,6 +384,15 @@ class RemoteScrollMirror {/// When a frame last showed the program's rows moved.int _movedAtMs = 0;+ /// About how long the program takes to answer — from a request going out to+ /// the frame that shows it moved: the longest of late, fading — and when the+ /// oldest request not yet answered went out, or null. See [_quietMs].+ double _answerMs = 0;+ int? _askedAtMs;++ /// When the program last drew anything — see [_seedQuiet].+ int _drewAtMs = -1 << 30;+bool _scrolling = false;bool _active = false;bool _settling = false;@@ -357,6 +435,8 @@ class RemoteScrollMirror {int _asksSpared = 0;int _rowsAsked = 0;int _pagesSent = 0;+ int _frameMicros = 0;+ int _frameMicrosMost = 0;int _startedAtMs = 0;int _endedAtMs = 0;@@ -377,6 +457,19 @@ class RemoteScrollMirror {/// Document row [row], as last seen; null when it never has been.BufferLine? rowAt(int row) => _document[row]?.line;+ /// The document row the program's transcript starts at, once a page up has+ /// gone nowhere — for a benchmark to tell the top of the transcript from a+ /// screen waiting for rows.+ @visibleForTesting+ int? get debugTranscriptTop => _topRow;++ /// How many times the document has started again in numbering of its own+ /// ([_forget], [_lost]) — for a benchmark not to read the renumbering as the+ /// rows moving.+ @visibleForTesting+ int get debugRenumbered => _renumbered;+ int _renumbered = 0;+/// The program's own screen row [row] to draw in place of the live one —/// held as it was while rows are fetched ahead ([_prefetch]), so its pinned/// prompt and "jump to bottom" line, which come up as the program scrolls,@@ -412,6 +505,9 @@ class RemoteScrollMirror {_takeGrid(screen, rowCount, lineHeight);_load();}+ if (screenWhole && _nowMs - _drewAtMs >= _seedQuiet.inMilliseconds) {+ _seedScrollingRows(screen, rowCount);+ }// Fetching ahead gives way to the finger: what it asked is still counted._stopPrefetch();_scrolling = true;@@ -429,6 +525,8 @@ class RemoteScrollMirror {_asksSpared = 0;_rowsAsked = 0;_pagesSent = 0;+ _frameMicros = 0;+ _frameMicrosMost = 0;_pageKeysRefused = false;_resyncs = 0;_missesInARow = 0;@@ -493,6 +591,19 @@ class RemoteScrollMirror {_velocityPixels = pixels;_velocityAtMs = now;}+ if (_active && _chasing) {+ // Catching up, the screen still goes with the finger, move for move:+ // the spring takes in only what lies between them ([_onTick]).+ //+ // ⚠️ **A spring after a moving finger trails it by its speed over ω.**+ // Caught still gliding, or let go of the edge of what is known, the screen+ // was handed to the spring — and dragged on, it sat 6–14 rows behind the+ // finger for the rest of the drag, over rows long known (Claude Code on an+ // iPhone 14, 2026-10-24: the content 1–3 rows short every frame of a+ // flick's start). Moved with the finger, what is left between them dies+ // away, and the screen is the finger's again.+ _display = _clamp(_display + (_target - _lastTarget));+ }_follow();_requestRemote();if (_active) onFrame();@@ -601,6 +712,7 @@ class RemoteScrollMirror {int rowCount,double lineHeight,) {+ _drewAtMs = _nowMs;if (!_scrolling && !_active) {// The program drew: fetching ahead waits until it has been quiet._armPrefetch();@@ -620,7 +732,15 @@ class RemoteScrollMirror {if (_prefetching) _endPrefetch();onFrame();}+ // Trace only: what placing the frame took on this thread — the document+ // matched, rows set aside looked for — while the finger waits on it.+ final placing = xtermInputTrace == null ? null : (Stopwatch()..start());_frame(screen, rowCount);+ if (placing != null) {+ final micros = placing.elapsedMicroseconds;+ _frameMicros += micros;+ if (micros > _frameMicrosMost) _frameMicrosMost = micros;+ }_activateIfReady();if (!_active) {// Still learning which rows scroll: the program follows the finger.@@ -767,6 +887,7 @@ class RemoteScrollMirror {}void _forget() {+ _renumbered++;_document.clear();_documentMin = 0;_documentMax = -1;@@ -901,6 +1022,11 @@ class RemoteScrollMirror {);_remote += shift.rows;_movedAtMs = _nowMs;+ final asked = _askedAtMs;+ if (asked != null) {+ _answerMs = math.max((_movedAtMs - asked).toDouble(), _answerMs * 0.8);+ _askedAtMs = null;+ }if (_pageInFlight) _pageLanded();// Gone further than it was asked: Claude Code speeds up wheel events it// reads together — as it does when busy drawing, however far apart they@@ -1044,6 +1170,8 @@ class RemoteScrollMirror {probe,rows,_document,+ // Made again each time: the document changes with every frame written.+ rowsBySignature(_document, _signatureOf),_documentMin - _remote,_documentMax - _remote,skip: (k) => k.abs() <= reach,@@ -1077,50 +1205,35 @@ class RemoteScrollMirror {];}- /// The placing of [probe] rows of [rows] in [known] that most agree: screen- /// row `i` showing `known[_remote + i + d]`, for every `d` that puts a probe- /// row between [knownMin] and [knownMax] — and how many agree with the next- /// best placing. Null when none agrees at all.+ /// The placing of [probe] rows of [rows] in [known] — [bySignature] its rows+ /// by what they say — that most agree: screen row `i` showing+ /// `known[_remote + i + d]`, for every `d` that puts a probe row between+ /// [knownMin] and [knownMax] — and how many agree with the next best+ /// placing. Null when none agrees at all. See [bestPlacing].({int d, int agree, int share, int runnerUp})? _bestPlacing(List<int> probe,List<_Row> rows,Map<int, _DocRow> known,+ Map<int, List<int>> bySignature,int knownMin,int knownMax, {bool Function(int d)? skip,}) {if (probe.isEmpty) return null;- ({int d, int agree, int share})? best;- var runnerUp = 0;- for (var d = knownMin - probe.last; d <= knownMax - probe.first; d++) {- if (skip != null && skip(d)) continue;- var agree = 0;- var comparable = 0;- for (final i in probe) {- final kept = known[_remote + i + d];- if (kept == null) continue;- comparable++;- if (kept.signature == rows[i].signature) agree++;- }- if (agree == 0) continue;- final current = best;- if (current == null || agree > current.agree) {- if (current != null) runnerUp = math.max(runnerUp, current.agree);- best = (d: d, agree: agree, share: comparable);- } else {- runnerUp = math.max(runnerUp, agree);- }- }- final found = best;- if (found == null) return null;- return (- d: found.d,- agree: found.agree,- share: found.share,- runnerUp: runnerUp,+ return bestPlacing(+ probe: probe,+ signatureOf: (i) => rows[i].signature,+ bySignature: bySignature,+ isKnown: known.containsKey,+ origin: _remote,+ lowest: knownMin - probe.last,+ highest: knownMax - probe.first,+ skip: skip,);}+ static int _signatureOf(_DocRow row) => row.signature;+/// Whether a placing found far off ([_bestPlacing]) leaves no doubt:/// [_reattachAgree] rows agreeing — or [_reattachAgreeAll], when every row/// that could agreed — and [_reattachShare] of those that could, with the@@ -1238,6 +1351,7 @@ class RemoteScrollMirror {(fixed(newBottom) || stoodStill(newBottom) && newBottom > shift.last)) {newBottom--;}+ newBottom = math.max(newTop, math.min(newBottom, _lowestScrollingRow));if (newTop != _top || newBottom != _bottom) {inputTrace(() => 'mirror: scrolling rows $newTop..$newBottom');_learned = true;@@ -1307,6 +1421,10 @@ class RemoteScrollMirror {final shown = _active ? _display.round() : _remote;final low = math.min(_remote, shown) - _keepRows;final high = math.max(_remote, shown) + _rowCount + _keepRows;+ // Nothing outside them — what the last trim leaves while the screen stands+ // apart from the program. Gone through anyway, every row was looked at on+ // every frame written, for none to drop.+ if (_documentMin >= low && _documentMax <= high) return;_document.removeWhere((row, _) => row < low || row > high);_documentMin = math.max(_documentMin, low);_documentMax = math.min(_documentMax, high);@@ -1363,6 +1481,7 @@ class RemoteScrollMirror {probe,rows,aside,+ _asideBySignature ??= rowsBySignature(aside, _signatureOf),_asideMin - _remote,_asideMax - _remote,);@@ -1437,9 +1556,11 @@ class RemoteScrollMirror {/// screen — what is known set aside, to be taken back once a later frame/// shows where it stands ([_reattach]).void _lost() {+ _renumbered++;inputTrace(() => 'mirror: frame not placed — starting again from it');// The rows still waiting were counted in books that are gone.cancelRequests();+ _askedAtMs = null;_pageInFlight = false;_stopPrefetch();_setAside();@@ -1573,7 +1694,9 @@ class RemoteScrollMirror {: math.max(0, (timeStamp - last).inMicroseconds) / 1e6;_dropLag();if (_chasing) {- // A critically damped spring towards the goal, solved exactly.+ // A critically damped spring towards the goal, solved exactly — on what+ // lies between the screen and it: the finger's own moves are carried in+ // [scrollTo].final goal = _clamp(_target);final omega = _omegaNow;final x = _display - goal;@@ -1612,23 +1735,57 @@ class RemoteScrollMirror {IndexAwareCircularBuffer<BufferLine> screen,int rowCount,) {- _pageKeysSafe =- (pageKeysEnabled?.call() ?? false) && _promptShown(screen, rowCount);+ _promptAt =+ (pageKeysEnabled?.call() ?? false) ? _promptRow(screen, rowCount) : -1;+ _pageKeysSafe = _promptAt >= 0;}- /// Whether [screen] shows Claude Code's prompt: a row starting `❯` with a- /// rule (`────`) right above it, and another a few rows below — its input- /// box.+ /// The lowest row that may scroll: over Claude Code's prompt box, the row+ /// above the blank one over its rule ([_seedScrollingRows]) — else the last.///- /// ⚠️ **Not a list to choose from.** A question it asks — "Do you want to- /// proceed?" over "❯ 1. Yes" — has its own words above the `❯`, not a rule,- /// and Page Up or Down there would move the choice instead of scrolling. In- /// any doubt, no page keys: wheel events only ever scroll.- static bool _promptShown(+ /// ⚠️ **The blank row over the box was taken for content.** Blank, it never+ /// stands still as far as [_widenScrollingRows] can tell, so a scroll down+ /// widened the rows that scroll over it, and it was written into the+ /// document as a row of the transcript — over rows not yet seen to move,+ /// which were drawn blank from then on (a fake of 2.1.309's layout in+ /// `mobile/test/remote_scroll_mirror_test.dart`, 2026-10-24).+ int get _lowestScrollingRow => _promptAt >= 0 ? _promptAt - 3 : _rowCount - 1;++ /// Which rows scroll, read off Claude Code's screen before any scroll has+ /// shown them: the rows above its prompt box ([_promptRow]) — less the first,+ /// where it pins the prompt of the rows on screen once that has scrolled+ /// off, and the last, just over the box's rule, where a "jump to bottom"+ /// line goes. Only for a program whose page keys scroll it, with nothing+ /// known of this grid, and only while it is quiet: at work its spinner and+ /// todo list stand over the box, and are not content. Scrolls widen them as+ /// they learn ([_widenScrollingRows]), and take back a row that stands still+ /// while the content moves ([_learnFixedRows]).+ ///+ /// ⚠️ **An agent's first scroll waited to learn them.** Until one scroll had+ /// placed two frames, nothing was drawn from the document and nothing was+ /// fetched ahead: the screen moved with the program's redraws for the first+ /// 150–200 ms, a round trip behind the finger, went on 3 rows by itself+ /// after the finger stopped, and the first flick met the edge of one screen+ /// (an iPhone 14 against Claude Code faked over a 100 ms round trip,+ /// 2026-10-23).+ void _seedScrollingRows(IndexAwareCircularBuffer<BufferLine> screen,int rowCount,- ) =>- _promptRow(screen, rowCount) >= 0;+ ) {+ if (_top != null || _bottom != null) return;+ if (!(pageKeysEnabled?.call() ?? false)) return;+ final prompt = _promptRow(screen, rowCount);+ // The prompt, the rule over it, and the row over that, left out.+ final bottom = prompt - 3;+ const top = 1;+ if (prompt < 0 || bottom - top + 1 < 2 * _minPage) return;+ _top = top;+ _bottom = bottom;+ _learned = true;+ inputTrace(+ () => 'mirror: scrolling rows $top..$bottom read off the prompt box',+ );+ }/// The text of the prompt's row ([_promptRow]), or null when none shows.static String? _promptText(@@ -1639,7 +1796,14 @@ class RemoteScrollMirror {return row < 0 ? null : screen[row].getText();}- /// The screen row of Claude Code's prompt — see [_promptShown] — or -1.+ /// The screen row of Claude Code's prompt, or -1: a row starting `❯` with a+ /// rule (`────`) right above it, and another a few rows below — its input+ /// box.+ ///+ /// ⚠️ **Not a list to choose from.** A question it asks — "Do you want to+ /// proceed?" over "❯ 1. Yes" — has its own words above the `❯`, not a rule,+ /// and Page Up or Down there would move the choice instead of scrolling. In+ /// any doubt, no page keys: wheel events only ever scroll.static int _promptRow(IndexAwareCircularBuffer<BufferLine> screen,int rowCount,@@ -1711,24 +1875,75 @@ class RemoteScrollMirror {if (lines.abs() < page) return fast;if (!requestsIdle() || _wheelsGliding) return true;final direction = lines.sign;- if (!send(direction)) {+ final count = _pagesAtOnce(lines, page);+ if (!send(direction, count)) {_pageKeysRefused = true;inputTrace(() => 'mirror: page key refused — wheel events from here');return false;}+ _asked();_pageInFlight = true;_pageNowhere = false;_pageDirection = direction;+ _pageCount = count;_pageSentAtMs = _nowMs;_pageFromRemote = _remote;- _requested += direction * page;+ _requested += direction * page * count;_requestedAtMs = _nowMs;_askedDirection = direction;- _rowsAsked += page;- _pagesSent++;+ _rowsAsked += page * count;+ _pagesSent += count;return true;}+ /// How many page keys go together for [lines] rows, pages of [page] rows:+ /// one — unless the program has rows already known to cross first. Then as+ /// many as [lines] holds, up to [_maxPagesAtOnce], as long as they leave its+ /// screen among the rows known.+ ///+ /// ⚠️ **What has been seen came back at the pace of what has not.** Rows+ /// fetched ahead, or read before, are drawn at once — but the program, one+ /// page a round trip, has to cross them before it brings anything new: in a+ /// flick over 120 rows fetched ahead the finger got to their edge long before+ /// the program did, and the screen held there ~250 ms (an iPhone 14 against+ /// Claude Code faked over a 100 ms round trip, 2026-10-23). Pages that land+ /// among rows known are placed like any frame, however far they went: a+ /// frame shares its rows with the document, not only with the last frame.+ /// Into rows not yet seen a page still goes alone, so that what it brings+ /// overlaps what is known.+ int _pagesAtOnce(int lines, int page) {+ final top = _top;+ final bottom = _bottom;+ if (top == null || bottom == null || _documentMax < _documentMin) return 1;+ // The rows known between the program's screen and their edge, its way.+ final known = lines < 0+ ? _remote + top - _documentMin+ : _documentMax - (_remote + bottom);+ final most = math.min(lines.abs() ~/ page, known ~/ page);+ return most.clamp(1, _maxPagesAtOnce);+ }++ /// How far past where the program was last seen it may be asked to go, its+ /// [direction]: [_maxAhead] — or, while its page keys can take it, to the+ /// edge of the rows known, which it has to cross before it brings anything+ /// new ([_pagesAtOnce]).+ int _reachAhead(int direction) {+ final top = _top;+ final bottom = _bottom;+ if (requestPage == null ||+ !_pageKeysSafe ||+ _pageKeysRefused ||+ top == null ||+ bottom == null ||+ _documentMax < _documentMin) {+ return _maxAhead;+ }+ final known = direction < 0+ ? _remote + top - _documentMin+ : _documentMax - (_remote + bottom);+ return math.max(_maxAhead, known);+ }+/// A frame placed while a page key was on its way: once the program has/// moved its way, the page has landed — and where the frame shows it is/// where it stands. A page jumps (`scrollTo`), with nothing gliding behind@@ -1737,6 +1952,12 @@ class RemoteScrollMirror {void _pageLanded() {final moved = (_remote - _pageFromRemote) * _pageDirection;if (moved <= 0) return;+ // Pages sent together may be drawn one by one: landed once most of the+ // way is gone — the size of a page is only an estimate.+ if (_pageCount > 1 &&+ moved < (_pageCount - 1) * _pageRowsNow + _pageRowsNow ~/ 2) {+ return;+ }_pageInFlight = false;_pageLandedAtMs = _nowMs;_requested = _remote;@@ -1768,6 +1989,12 @@ class RemoteScrollMirror {_pageInFlight = false;_pageNowhere = _remote == _pageFromRemote;if (_pageNowhere && requestsIdle()) _requested = _remote;+ // A page up that went nowhere: the program's first row is where its+ // transcript starts — nothing above it to fetch ahead ([_prefetch]).+ final top = _top;+ if (_pageNowhere && _pageDirection < 0 && top != null) {+ _topRow = _remote + top;+ }}/* Fetching ahead */@@ -1819,6 +2046,8 @@ class RemoteScrollMirror {_takeGrid(screen, rowCount, now.lineHeight);_load();}+ // Quiet since [_prefetchAfter]: what the prompt box says can be read.+ _seedScrollingRows(screen, rowCount);final top = _top;final bottom = _bottom;if (top == null || bottom == null) {@@ -1837,7 +2066,7 @@ class RemoteScrollMirror {final want = _remote + top - _prefetchRows;final topRow = _topRow;final above = _remote + top - _documentMin;- if (_documentMin <= want) {+ if (above > _prefetchRows - _prefetchGain) {return _skipPrefetch('$above rows above the screen known already');}if (topRow != null && _documentMin <= topRow) {@@ -1877,6 +2106,8 @@ class RemoteScrollMirror {_asksSpared = 0;_rowsAsked = 0;_pagesSent = 0;+ _frameMicros = 0;+ _frameMicrosMost = 0;_pageKeysRefused = false;_resyncs = 0;_missesInARow = 0;@@ -1925,7 +2156,8 @@ class RemoteScrollMirror {final top = _top ?? 0;inputTrace(() => 'mirror: fetched ahead in ${_nowMs - _prefetchStartedAtMs}ms'- ' · ${_remote + top - _documentMin} rows above the screen known'+ ' · ${_display.round() + top - _documentMin} rows above the screen'+ ' known'' · $_pagesSent pages',);_settling = true;@@ -1959,6 +2191,18 @@ class RemoteScrollMirror {return math.max(0, math.min(most, wanted));}+ /// How many rows ahead of the finger the program is asked to be while the+ /// finger is fast enough for page keys ([_pageSpeed]): a page, and what the+ /// finger covers while one comes back ([_pageLatency]) — so the next page+ /// goes before the finger gets to the edge of what is known. Zero when no+ /// page key can go.+ int _pageLeadRows() {+ if (requestPage == null || !_pageKeysSafe || _pageKeysRefused) return 0;+ final page = _pageRowsNow;+ if (page < _minPage) return 0;+ return page + (_fingerVelocity.abs() * _pageLatency).round();+ }+/// The program asked to scroll to where the finger is, and a little ahead —/// while it scrolls; once it has ended, [_settleStep].void _requestRemote() {@@ -1971,7 +2215,13 @@ class RemoteScrollMirror {_asksSpared++;return;}- final lead = moving ? (held ? _maxAhead : _leadRows()) * _direction : 0;+ final fast = moving && (held || _fingerVelocity.abs() >= _pageSpeed);+ final ahead = held+ ? _maxAhead+ : fast+ ? math.max(_leadRows(), _pageLeadRows())+ : _leadRows();+ final lead = moving ? ahead * _direction : 0;final wanted = _target.round() + lead;// ⚠️ **Never far past where the program was last seen.** A fling runs// hundreds of rows ahead of a program that scrolls ~80 a second, and all of@@ -1981,7 +2231,8 @@ class RemoteScrollMirror {// rows wrong (measured on a phone, 2026-10-06). Asked [_maxAhead] at most// past the last row seen, the rest is asked for as the program gets there:// each frame asks again.- final goal = wanted.clamp(_remote - _maxAhead, _remote + _maxAhead);+ final goal =+ wanted.clamp(_remote - _reachAhead(-1), _remote + _reachAhead(1));final lines = goal - _requested;if (lines == 0) return;// While the finger moves the program is only asked onwards. Ahead of the@@ -1990,7 +2241,6 @@ class RemoteScrollMirror {// turn, and glides on the old way a few frames first. Coming back to the// row on screen is for when the scroll comes to rest.if (_scrolling && _direction != 0 && lines.sign != _direction) return;- final fast = moving && (held || _fingerVelocity.abs() >= _pageSpeed);if (_pageOrWait(lines, fast: fast)) return;_requested = goal;_requestedAtMs = _nowMs;@@ -1998,6 +2248,7 @@ class RemoteScrollMirror {_rowsAsked += lines.abs();_wheelsAtMs = _nowMs;requestLines(lines);+ _asked();}/// Whether the finger, moving over rows already known, is far enough from@@ -2045,8 +2296,9 @@ class RemoteScrollMirror {final now = _nowMs;// Not moved, rather than not drawn: an agent at work redraws its spinner// every few frames, and a program at an end never moves however it draws.- if (now - _movedAtMs < _resyncAfter.inMilliseconds) return;- if (now - _requestedAtMs < _resyncAfter.inMilliseconds) return;+ final quiet = math.max(_resyncAfter.inMilliseconds, _quietMs);+ if (now - _movedAtMs < quiet) return;+ if (now - _requestedAtMs < quiet) return;if (!requestsIdle()) return;if (_resyncs >= _maxResyncs) return;_resyncs++;@@ -2082,8 +2334,8 @@ class RemoteScrollMirror {// see [_resyncIfStalled].final quiet = !_pageInFlight &&requestsIdle() &&- now - _movedAtMs >= _settleQuiet.inMilliseconds &&- now - _requestedAtMs >= _settleQuiet.inMilliseconds;+ now - _movedAtMs >= _quietMs &&+ now - _requestedAtMs >= _quietMs;// Nothing on its way and standing still: the program is where it is,// whatever was asked of it.if (quiet) _requested = _remote;@@ -2096,7 +2348,8 @@ class RemoteScrollMirror {final far = diff.abs() > _landingRows;if (!quiet && (!far || sign != _askedDirection)) return;final want = far ? row - sign * _landingBurst : row;- final goal = want.clamp(_remote - _maxAhead, _remote + _maxAhead);+ final goal =+ want.clamp(_remote - _reachAhead(-1), _remote + _reachAhead(1));var lines = goal - _requested;// Asked that far already, and on its way.if (lines == 0 || lines.sign != sign) return;@@ -2110,8 +2363,27 @@ class RemoteScrollMirror {_rowsAsked += lines.abs();_wheelsAtMs = _nowMs;requestLines(lines);+ _asked();}+ /// A request went out: when it did, unless an older one is still unanswered.+ void _asked() => _askedAtMs ??= _nowMs;++ /// How long the program must have stood still, and nothing been asked of it,+ /// for it to be where it is going to stay: [_settleQuiet], or a little over+ /// how long it has lately taken to answer, when that is longer.+ ///+ /// ⚠️ **Over a slow link it was asked twice.** A redraw came back 200 ms and+ /// more after its request, and after 100 ms of nothing the program was taken+ /// to have stopped — the scroll handler, too, counts a batch answered after+ /// 120 ms with none: the books were put back to where the program was, the+ /// same rows asked again, and the second answer moved it on after the screen+ /// had gone back to it — the screen jumping rows by itself (an iPhone 14+ /// against Claude Code faked over a 200 ms round trip, 2026-10-24).+ int get _quietMs => math+ .max(_settleQuiet.inMilliseconds, (_answerMs * 1.25).round())+ .clamp(0, _quietMost.inMilliseconds);+/// The program stands at the row on screen: drawn from it again.void _finishSettle() {final now = _nowMs;@@ -2124,7 +2396,9 @@ class RemoteScrollMirror {' · $_settleAsks asks to come back · rows kept from the program\'s'' own $_rowsGuarded, put right $_rowsMended'' · $_rowsAsked rows asked ($_pagesSent pages),'- ' $_asksSpared asks spared over known rows',+ ' $_asksSpared asks spared over known rows'+ ' · frames placed in ${(_frameMicros / 1000).toStringAsFixed(1)}ms,'+ ' the longest ${(_frameMicrosMost / 1000).toStringAsFixed(1)}ms',);_settling = false;_settleTimer?.cancel();@@ -2236,6 +2510,85 @@ class _Shift {int get last => agreeing.isEmpty ? -1 : agreeing.last;}+/// AUTONOMOUS PATCH: [rows]' keys by what they say — for each signature, the+/// rows that show it — for [bestPlacing] to look a screen's rows up in.+@visibleForTesting+Map<int, List<int>> rowsBySignature<T>(+ Map<int, T> rows,+ int Function(T row) signatureOf,+) {+ final index = <int, List<int>>{};+ rows.forEach((row, value) {+ (index[signatureOf(value)] ??= <int>[]).add(row);+ });+ return index;+}++/// AUTONOMOUS PATCH: the placing of the [probe] screen rows among the rows+/// known that most agree — screen row `i` showing row `origin + i + d` — for+/// every `d` from [lowest] to [highest] that [skip] leaves: how many agree,+/// how many could (`share`: a row is known there, [isKnown]), and how many+/// agree with the next best placing. A tie goes to the lowest `d`. Null when+/// none agrees at all. [signatureOf] is what screen row `i` says, and+/// [bySignature] the rows known by what they say ([rowsBySignature]).+///+/// ⚠️ **Counted from where a row was seen, not tried at every placing.** Tried+/// one by one, every placing compared every probe row: with the thousands of+/// rows a long session keeps, one look was over a hundred thousand lookups —+/// 2ms for 4,000 rows on a laptop, several times that on a phone — on this+/// thread, while the finger moved: on every frame not placed nearby, and every+/// look among the rows set aside. Each probe row now votes only for the+/// placings that put it on a row that says the same, which is the same count:+/// 15µs for the same rows, 0.5ms with every row one of four texts (measured+/// 2026-10-23).+@visibleForTesting+({int d, int agree, int share, int runnerUp})? bestPlacing({+ required List<int> probe,+ required int Function(int screenRow) signatureOf,+ required Map<int, List<int>> bySignature,+ required bool Function(int row) isKnown,+ required int origin,+ required int lowest,+ required int highest,+ bool Function(int d)? skip,+}) {+ if (highest < lowest) return null;+ // One count per placing, `d - lowest`: a few thousand at most, as many as+ // the rows known span.+ final votes = Int32List(highest - lowest + 1);+ for (final i in probe) {+ final seen = bySignature[signatureOf(i)];+ if (seen == null) continue;+ for (final row in seen) {+ final d = row - origin - i;+ if (d >= lowest && d <= highest) votes[d - lowest]++;+ }+ }+ int? best;+ var agree = 0;+ var runnerUp = 0;+ for (var at = 0; at < votes.length; at++) {+ final count = votes[at];+ if (count == 0) continue;+ final d = lowest + at;+ if (skip != null && skip(d)) continue;+ if (count > agree) {+ runnerUp = math.max(runnerUp, agree);+ best = d;+ agree = count;+ } else {+ runnerUp = math.max(runnerUp, count);+ }+ }+ final d = best;+ if (d == null) return null;+ var share = 0;+ for (final i in probe) {+ if (isKnown(origin + i + d)) share++;+ }+ return (d: d, agree: agree, share: share, runnerUp: runnerUp);+}+/// AUTONOMOUS PATCH: the program's whole screen, for [RemoteScrollMirror] to/// start fetching ahead from on its own — see [RemoteScrollMirror.readScreen].typedef RemoteScreen = ({@@ -2271,10 +2624,6 @@ class RemoteScrollMemory {/// By grid ([RemoteScrollMirror._gridKey]), least recently kept first.final _grids = <String, _Known>{};- /// Whether which rows scroll is known in any grid — what fetching ahead- /// before the first scroll needs.- bool get knowsScrollingRows => _grids.isNotEmpty;-void _keep(String grid, _Known known) {_grids.remove(grid);_grids[grid] = known;diff --git a/mobile/third_party/xterm/lib/src/ui/render.dart b/mobile/third_party/xterm/lib/src/ui/render.dartindex 5ca060ab2..0f35d952a 100644--- a/mobile/third_party/xterm/lib/src/ui/render.dart+++ b/mobile/third_party/xterm/lib/src/ui/render.dart@@ -323,6 +323,11 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {RemoteScrollMirror? _mirror;+ /// The mirror drawing a full-screen program's scroll, if one was made — for a+ /// benchmark to compare where it draws the rows with where the finger is.+ @visibleForTesting+ RemoteScrollMirror? get debugRemoteScrollMirror => _mirror;+/// The screen for the mirror to fetch ahead from, when it can be read whole.RemoteScreen? _mirrorScreen() {if (!_canMirror || _terminal.synchronizedOutputHeld) return null;@@ -341,9 +346,9 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {requestsIdle: () => _remoteScrollLink?.idle ?? true,cancelRequests: () => _remoteScrollLink?.cancel() ?? 0,pageKeysEnabled: () => _mirrorPageKeys,- requestPage: (direction) =>+ requestPage: (direction, count) =>_mirrorPageKeys &&- (_remoteScrollLink?.sendPage(direction) ?? false),+ (_remoteScrollLink?.sendPage(direction, count: count) ?? false),readScreen: _mirrorScreen,)..memory = _remoteScrollMemory;@@ -409,12 +414,12 @@ class RenderTerminal extends RenderBox with RelayoutWhenSystemFontsChangeMixin {/// The screen was laid out again: a slide starts, carries on or ends here.void _updateRemoteScroll() {- // A program whose scrolling rows are remembered gets its mirror before the- // first scroll: it fetches ahead from the start.+ // A program whose page keys scroll it gets its mirror before the first+ // scroll: it fetches ahead from the start, its scrolling rows remembered+ // or read off its prompt box (`RemoteScrollMirror._seedScrollingRows`).if (_mirror == null &&_mirrorRemoteScroll &&_mirrorPageKeys &&- _remoteScrollMemory?.knowsScrollingRows == true &&_canMirror) {_mirrorNow;}diff --git a/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart b/mobile/third_party/xterm/lib/src/ui/scroll_handler.dartindex 1018858b3..349ba575b 100644--- a/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart+++ b/mobile/third_party/xterm/lib/src/ui/scroll_handler.dart@@ -12,17 +12,19 @@ class RemoteScrollLink {void Function(int lines)? _send;bool Function()? _idle;int Function()? _cancel;- bool Function(int direction)? _page;+ bool Function(int direction, int count)? _page;Object? _owner;/// Scroll the program [lines] rows, positive towards newer ones. Dropped when/// no scroll handler is listening: the program is not on its alternate screen.void send(int lines) => _send?.call(lines);- /// Press Page Down ([direction] positive) or Page Up once — only when nothing- /// else asked is still on its way. False when it was not sent: something is,- /// or nobody is listening, or the program is scrolled another way.- bool sendPage(int direction) => _page?.call(direction) ?? false;+ /// Press Page Down ([direction] positive) or Page Up [count] times, in one+ /// write — only when nothing else asked is still on its way. False when it+ /// was not sent: something is, or nobody is listening, or the program is+ /// scrolled another way.+ bool sendPage(int direction, {int count = 1}) =>+ _page?.call(direction, count) ?? false;/// Whether every row asked for has gone out and been answered.bool get idle => _idle?.call() ?? true;@@ -37,7 +39,7 @@ class RemoteScrollLink {void Function(int) send,bool Function() idle,int Function() cancel,- bool Function(int direction) page,+ bool Function(int direction, int count) page,) {_owner = owner;_send = send;@@ -375,11 +377,14 @@ class _TerminalScrollGestureHandlerState}/// AUTONOMOUS PATCH: [RemoteScrollLink.sendPage] — Page Up or Page Down,- /// alone: nothing waiting and nothing unanswered, so the program draws this- /// page by itself, never two at once. Answered like a batch of wheel events- /// (any write from the program), and paced with them.- bool _sendLinkPage(int direction) {- if (direction == 0 || _unsentLines != 0 || _batchesInFlight > 0) {+ /// [count] of them together, alone: nothing waiting and nothing unanswered,+ /// so the program draws these pages by themselves. Answered like a batch of+ /// wheel events (any write from the program), and paced with them.+ bool _sendLinkPage(int direction, int count) {+ if (direction == 0 ||+ count < 1 ||+ _unsentLines != 0 ||+ _batchesInFlight > 0) {return false;}// A program scrolled by other means than its keys.@@ -387,9 +392,11 @@ class _TerminalScrollGestureHandlerState_batchesInFlight++;_answerWait?.cancel();_answerWait = Timer(_answerWaitLimit, _onAnswerWaitOver);- widget.terminal.keyInput(- direction < 0 ? TerminalKey.pageUp : TerminalKey.pageDown,- );+ for (var i = 0; i < count; i++) {+ widget.terminal.keyInput(+ direction < 0 ? TerminalKey.pageUp : TerminalKey.pageDown,+ );+ }return true;}