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
fix(mobile): harden onboarding pairing and waits
tonye73009639c0e
diff --git a/mobile/lib/phone/agent_home.dart b/mobile/lib/phone/agent_home.dartindex 98b81ab5f..f364651f4 100644--- a/mobile/lib/phone/agent_home.dart+++ b/mobile/lib/phone/agent_home.dart@@ -17,6 +17,8 @@ import 'daemon_chip.dart';import 'desk_groups.dart';import 'link_page.dart';import 'machines_tab.dart';+import 'phone_navigation.dart' show phoneRoute;+import 'settings_page.dart' show PhoneSettingsButton;import 'tty_controls.dart';import 'tty.dart';import 'welcome/connect_computer.dart';@@ -145,16 +147,54 @@ class _AgentHomeState extends State<AgentHome> {bool _gaveUpWaiting = false;Timer? _loadingDeadline;- /// The launch's wait is over — the screen has something other than a loading message to show —- /// so [_loadingTimeout] has nothing left to guard, and must not fire into a screen that has- /// stopped waiting: it would hold back every loading message after it.+ /// How long the loading screen waits on its own before it says so and offers a way off it —+ /// Settings, and the computers list ([_loadingSlow]). Past a slow-but-fine launch, short of+ /// [_loadingTimeout].+ static const _slowAfter = Duration(seconds: 15);+ Timer? _slowTimer;++ /// The loading screen has been up for [_slowAfter] without a break.+ bool _loadingSlow = false;++ void _giveUpWaiting() {+ if (!mounted || _gaveUpWaiting) return;+ setState(() => _gaveUpWaiting = true);+ }++ /// The loading screen is what [build] draws: its [_loadingTimeout] and [_slowAfter] run, each+ /// from the moment this wait began.+ ///+ /// ⚠️ **Every wait, not the launch's alone.** The deadline used to be armed once, in+ /// [initState], and ended for good by the first screen that was not a loading one — which on a+ /// first sign-in is "Waiting for your computer…". The computer turning up then brought+ /// "Connecting to your computer…" back with no deadline at all, over a machine whose agent list+ /// can stall (see [_loadingTimeout]): a spinner with no end and nothing on screen to leave it by.+ ///+ /// Called from [build]: it starts timers and never sets state itself.+ void _holdLaunchWait() {+ if (!_gaveUpWaiting) {+ _loadingDeadline ??= Timer(_loadingTimeout, _giveUpWaiting);+ }+ if (!_loadingSlow) {+ _slowTimer ??= Timer(_slowAfter, () {+ if (!mounted) return;+ setState(() => _loadingSlow = true);+ });+ }+ }++ /// The wait is over — the screen has something other than a loading message to show — so+ /// [_loadingTimeout] has nothing left to guard, and must not fire into a screen that has stopped+ /// waiting: it would hold back every loading message after it. A later wait starts its own+ /// ([_holdLaunchWait]).///- /// Called from [build], on each way out of the loading screen; only the first does anything.+ /// Called from [build], on each way out of the loading screen.void _endLaunchWait() {- final deadline = _loadingDeadline;- if (deadline == null) return;+ _loadingDeadline?.cancel();_loadingDeadline = null;- deadline.cancel();+ _slowTimer?.cancel();+ _slowTimer = null;+ _loadingSlow = false;}@override@@ -166,10 +206,7 @@ class _AgentHomeState extends State<AgentHome> {widget.openMachineId?.addListener(_onLinkedMachineChanged);_requestedAgent = widget.openAgent?.value;widget.openAgent?.addListener(_onAgentRequested);- _loadingDeadline = Timer(_loadingTimeout, () {- if (!mounted || _gaveUpWaiting) return;- setState(() => _gaveUpWaiting = true);- });+ _loadingDeadline = Timer(_loadingTimeout, _giveUpWaiting);_readLast();}@@ -178,6 +215,7 @@ class _AgentHomeState extends State<AgentHome> {widget.openMachineId?.removeListener(_onLinkedMachineChanged);widget.openAgent?.removeListener(_onAgentRequested);_loadingDeadline?.cancel();+ _slowTimer?.cancel();_restoreDeadline?.cancel();_terminalWait?.cancel();super.dispose();@@ -284,6 +322,17 @@ class _AgentHomeState extends State<AgentHome> {Timer? _restoreDeadline;bool _restoreGaveUp = false;+ /// The account's machine list could not be read: not answered in this sign-in, not being asked+ /// for, and a failure on record ([AppNotifier.lastError], which every sign-in clears). Not an+ /// empty account — nothing says what the account has until a Try again answers.+ bool get _machinesUnreadable {+ final notifier = widget.notifier;+ return notifier.machines.isEmpty &&+ !notifier.machinesLoading &&+ !notifier.machinesAnswered &&+ notifier.lastError != null;+ }+/// Whether [machineId] is on its way — connecting, or connected with its agent list still owed —/// rather than answered, offline, or wanting a password.///@@ -304,8 +353,13 @@ class _AgentHomeState extends State<AgentHome> {// removed, or one of another account's (it is never cleared). Read as "not answered yet", it// held an account with no computer on "Connecting to your computer…" for the whole// [_restoreTimeout] before its set-up page came up.+ //+ // Nor while a list that FAILED waits on a Try again: nothing is on its way until then, and+ // the wait held "Connecting to your computer…" over the error for the whole timeout.return notifier.machinesLoading ||- (notifier.machines.isEmpty && !notifier.machinesAnswered);+ (notifier.machines.isEmpty &&+ !notifier.machinesAnswered &&+ !_machinesUnreadable);}return switch (phoneMachineStatusOf(machine)) {PhoneMachineStatus.needsPassword => false,@@ -710,7 +764,11 @@ class _AgentHomeState extends State<AgentHome> {// the QR's code — no password. See `welcome/connect_code.dart`.if (widget.notifier.pendingPairing case final pending?) {final machine = widget.notifier.machineStates[pending.machineId];- if (machine != null && machine.needsLink) {+ // ⚠️ Kept up once its pairing has begun ([AppNotifier.pendingPairingTried]), not only while+ // the machine reads locked: a redial that unlocks it for a moment took the page down+ // mid-pairing, and built it again to spend the one-time code a second time.+ if (machine != null &&+ (machine.needsLink || widget.notifier.pendingPairingTried)) {_endLaunchWait();return PairingWithCode(key: ValueKey('pairing-${pending.machineId}'),@@ -739,7 +797,14 @@ class _AgentHomeState extends State<AgentHome> {// two are built to read as one sequence.final loading = _loadingMessage() ?? _restoreMessage();_traceLoading(loading);- if (loading != null) return _AgentHomeLoading(message: loading);+ if (loading != null) {+ _holdLaunchWait();+ return _AgentHomeLoading(+ message: loading,+ notifier: widget.notifier,+ slow: _loadingSlow,+ );+ }_endLaunchWait();// ⚠️ **No machine is open → this is a MACHINE problem, so the machine screen is what the// person gets.** An "Agents" header over "No machines are open yet" named the thing that is@@ -755,6 +820,15 @@ class _AgentHomeState extends State<AgentHome> {// but locked or asleep: the machines list, with its password form.if (widget.notifier.machines.isEmpty &&!widget.notifier.machinesLoading) {+ // ⚠️ **A list that could not be read is not an empty account.** A first fetch that+ // failed leaves the list empty and not loading, exactly as an account with no computer+ // does, and this drew "Get Harness for your computer" — with "Not you? Sign out" — for+ // somebody who has computers, over a reason ("Could not load machines…") said nowhere.+ // The machines screen says it, with its Try again. A list neither answered nor failed+ // still gets the set-up page, whose watch asks again every few seconds.+ if (_machinesUnreadable) {+ return MachinesTab(notifier: widget.notifier);+ }return ConnectComputerPage(notifier: widget.notifier,onTrySample: openSampleMode,@@ -1088,48 +1162,133 @@ class _AgentHomeState extends State<AgentHome> {/// screen is one centred line saying what is happening, which is also what [_Attaching] in/// `terminal_page.dart` looks like — same spinner, same size, same type — so the two read as one/// sequence rather than two unrelated waits.+///+/// ⚠️ **Until the wait is [slow].** Then it says so, and offers the two ways off it: the computers,+/// with what each one needs, and Settings — Sign out among it — at the top right, where every+/// screen before the first harness has it. Without them a wait that stalled ("Connecting to your+/// computer…" over an agent list that never came) was a spinner with nothing on screen to leave+/// it by.class _AgentHomeLoading extends StatelessWidget {- const _AgentHomeLoading({required this.message});+ const _AgentHomeLoading({+ required this.message,+ required this.notifier,+ this.slow = false,+ });/// The step in progress, in the person's words — see [_AgentHomeState._loadingMessage].final String message;+ final AppNotifier notifier;++ /// Up for [_AgentHomeState._slowAfter] without a break.+ final bool slow;+@overrideWidget build(BuildContext context) {AppTheme.watch(context);return Scaffold(backgroundColor: AppPalette.windowBg,body: SafeArea(- child: Center(- child: Column(- mainAxisSize: MainAxisSize.min,- children: [- SizedBox.square(- dimension: 22,- child: CircularProgressIndicator(- strokeWidth: 2,- color: AppPalette.accent,+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // The row Settings stands in on the screens before the first harness — empty until the+ // wait is slow, so a launch that is merely loading stays one centred line.+ SizedBox(+ height: 44,+ child: slow+ ? Align(+ alignment: Alignment.centerRight,+ child: PhoneSettingsButton(notifier: notifier),+ )+ : null,+ ),+ Expanded(+ child: Center(+ child: Padding(+ padding: const EdgeInsets.symmetric(horizontal: 32),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ SizedBox.square(+ dimension: 22,+ child: CircularProgressIndicator(+ strokeWidth: 2,+ color: AppPalette.accent,+ ),+ ),+ const SizedBox(height: 14),+ // ⚠️ Keyed by the text so a change between steps CROSS-FADES rather than+ // snapping. These lines replace each other while somebody is reading them,+ // and a hard swap at that moment reads as a glitch instead of as progress.+ AnimatedSwitcher(+ duration: const Duration(milliseconds: 220),+ child: Text(+ message,+ key: ValueKey(message),+ textAlign: TextAlign.center,+ style: TextStyle(+ color: AppPalette.textSecondary,+ fontSize: 14,+ ),+ ),+ ),+ AnimatedSwitcher(+ duration: const Duration(milliseconds: 220),+ child: slow+ ? _SlowWaitHint(+ key: const ValueKey('home-wait-slow'),+ notifier: notifier,+ )+ : const SizedBox.shrink(),+ ),+ ],+ ),),),- const SizedBox(height: 14),- // ⚠️ Keyed by the text so a change between steps CROSS-FADES rather than snapping.- // These lines replace each other while somebody is reading them, and a hard swap at- // that moment reads as a glitch instead of as progress.- AnimatedSwitcher(- duration: const Duration(milliseconds: 220),- child: Text(- message,- key: ValueKey(message),- textAlign: TextAlign.center,- style: TextStyle(- color: AppPalette.textSecondary,- fontSize: 14,- ),+ ),+ // The top row's height again, so the line stays where it was: the screen's middle.+ const SizedBox(height: 44),+ ],+ ),+ ),+ );+ }+}++/// Under a wait that has gone on: what is true, and the computers — each with what it needs, a+/// password form behind a locked one — over the wait rather than in place of it, so back returns+/// to it and a wait that ends meanwhile still lands where it would have.+class _SlowWaitHint extends StatelessWidget {+ const _SlowWaitHint({super.key, required this.notifier});++ final AppNotifier notifier;++ @override+ Widget build(BuildContext context) {+ return Padding(+ padding: const EdgeInsets.only(top: 18),+ child: Column(+ mainAxisSize: MainAxisSize.min,+ children: [+ Text(+ 'This is taking longer than usual.',+ textAlign: TextAlign.center,+ style: TextStyle(color: AppPalette.textSecondary, fontSize: 13),+ ),+ const SizedBox(height: 4),+ TtyTextButton(+ key: const ValueKey('home-wait-computers'),+ label: 'See your computers ›',+ onPressed: () => unawaited(+ Navigator.of(context).push(+ phoneRoute(+ (_) => MachinesTab(notifier: notifier, large: false),),),- ],+ ),),- ),+ ],),);}@@ -1167,15 +1326,19 @@ class _AgentHomeEmpty extends StatelessWidget {return Scaffold(backgroundColor: tty.ground,body: SafeArea(- child: Padding(- padding: const EdgeInsets.fromLTRB(Tty.origin, 16, Tty.origin, 16),- child: Column(- crossAxisAlignment: CrossAxisAlignment.stretch,- children: [- // The machine, and the paired daemon at the line's right end —- // where a terminal's title carries it. See `daemon_chip.dart`.- Row(+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ // The machine, and the paired daemon at the line's right end — where a terminal's title+ // carries it (see `daemon_chip.dart`) — then Settings, at the top right as on every+ // screen before the first harness. ⚠️ This is the first screen a new account stands on+ // once its computer is open, and nothing else on it leads to Settings — or Sign out:+ // Find and a terminal's menu, the other ways there, both need a harness.+ SizedBox(+ height: 44,+ child: Row(children: [+ const SizedBox(width: Tty.origin),Expanded(child: TtyText(machine.displayName,@@ -1184,29 +1347,47 @@ class _AgentHomeEmpty extends StatelessWidget {),),const DaemonChip(margin: EdgeInsets.only(left: 12)),+ PhoneSettingsButton(notifier: notifier),],),- const Spacer(),- TtyText(- 'Nothing running yet.',- size: 24,- weight: FontWeight.w600,- ),- const SizedBox(height: 12),- Text(- 'Start a harness — an agent on a project on your computer — and '- 'watch it work from here. Swipe right any time to find one '- 'started elsewhere.',- style: tty.style(size: TtySize.row, color: tty.faint),- ),- const Spacer(),- TtyPrimaryButton(- label: 'Start a harness',- onPressed: () =>- openNewAgent(context, notifier, machine.machineId),+ ),+ Expanded(+ child: Padding(+ padding: const EdgeInsets.fromLTRB(+ Tty.origin,+ 0,+ Tty.origin,+ 16,+ ),+ child: Column(+ crossAxisAlignment: CrossAxisAlignment.stretch,+ children: [+ const Spacer(),+ TtyText(+ 'Nothing running yet.',+ size: 24,+ weight: FontWeight.w600,+ ),+ const SizedBox(height: 12),+ // ⚠️ No "Swipe right any time to find one started elsewhere": the swipe is the+ // terminal's (`terminal_page.dart`), it does nothing here, and with no harness on+ // any open computer there is nothing elsewhere to find.+ Text(+ 'Start a harness — an agent on a project on your computer — and '+ 'watch it work from here.',+ style: tty.style(size: TtySize.row, color: tty.faint),+ ),+ const Spacer(),+ TtyPrimaryButton(+ label: 'Start a harness',+ onPressed: () =>+ openNewAgent(context, notifier, machine.machineId),+ ),+ ],+ ),),- ],- ),+ ),+ ],),),);diff --git a/mobile/lib/phone/approve_sign_in.dart b/mobile/lib/phone/approve_sign_in.dartindex f3ff275e0..7808a890c 100644--- a/mobile/lib/phone/approve_sign_in.dart+++ b/mobile/lib/phone/approve_sign_in.dart@@ -1,10 +1,13 @@import 'dart:async';+import 'package:dio/dio.dart' show DioException, DioExceptionType;import 'package:flutter/gestures.dart';import 'package:flutter/material.dart';import 'package:flutter/services.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:harness_mobile/api/api_client.dart'+ show ApiException, describeApiError;import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/shared/widgets/app_dialog.dart'show appDialogButtonStyle, kDialogControlRadius, showAppDialog;@@ -43,7 +46,8 @@ Future<void> approveComputerSignIn(asking = await notifier.api.signInLookup(code.code);} catch (error) {if (context.mounted) {- await _tell(context, "Couldn't read that code", scanAgain == null ? '$error' : '$error $scanAgain');+ final reason = _reason(error);+ await _tell(context, "Couldn't read that code", scanAgain == null ? reason : '$reason $scanAgain');}return;}@@ -82,10 +86,43 @@ Future<void> approveComputerSignIn(await notifier.api.denySignIn(code.code);}} catch (error) {- if (context.mounted) await _tell(context, "Couldn't answer", '$error');+ if (context.mounted) await _tell(context, "Couldn't answer", _reason(error));}}+/// Why a request failed, as a sentence for the person.+///+/// ⚠️ **Never the exception's own text.** `'$error'` put "DioException [connection error]: The+/// connection errored: Failed host lookup: …" in the snackbar for a phone that was merely offline.+/// The backend's own message ([ApiException]) is said as it is — "That code has expired" — and a+/// failure to reach it in [describeApiError]'s words; anything else, in plain ones.+String _reason(Object error) {+ if (error is ApiException) return _sentence(error.message);+ if (error is DioException) {+ return switch (error.type) {+ DioExceptionType.connectionError ||+ DioExceptionType.connectionTimeout ||+ DioExceptionType.sendTimeout ||+ DioExceptionType.receiveTimeout ||+ DioExceptionType.badResponse => _sentence(describeApiError(error)),+ DioExceptionType.badCertificate ||+ DioExceptionType.cancel ||+ DioExceptionType.transformTimeout ||+ DioExceptionType.unknown =>+ 'Couldn’t reach Harness. Check your connection and try again.',+ };+ }+ return 'Something went wrong. Try again.';+}++/// [describeApiError] words its reasons to follow a colon ("could not reach Harness. …"); here+/// they start a sentence.+String _sentence(String text) {+ final trimmed = text.trim();+ if (trimmed.isEmpty) return 'Something went wrong. Try again.';+ return '${trimmed[0].toUpperCase()}${trimmed.substring(1)}';+}+/// One line of news where the person is: the answer went through, or why it did not.Future<void> _tell(BuildContext context, String title, String message) async {ScaffoldMessenger.maybeOf(context)?.showSnackBar(diff --git a/mobile/lib/phone/welcome/connect_computer.dart b/mobile/lib/phone/welcome/connect_computer.dartindex c17b83730..3d5ad95bf 100644--- a/mobile/lib/phone/welcome/connect_computer.dart+++ b/mobile/lib/phone/welcome/connect_computer.dart@@ -100,23 +100,41 @@ class _ConnectComputerPageState extends State<ConnectComputerPage> {_scanFailed = failed;});- /// The code the new computer's Add Phone shows: the phone pairs with it there and then. The- /// computer is asked for first — it may have joined the account a moment ago, too recently for- /// the list the phone holds.- ///- /// ⚠️ **A code is never dropped because this page went.** At home this page is there only while- /// the account has no computer, so the computer this code is for turning up — in the 5-second- /// watch while the camera was open, or in the refresh below — takes the page away, and the code- /// went with it: the person had just scanned, and was shown "Scan its code" again. Gone, the page- /// hands the code to the home screen instead ([AppNotifier.holdPendingPairing]), which pairs with- /// it the way it pairs a code scanned at sign-in.+ /// A scan under way, from the camera to its answer: a second press of "Scan to connect" while+ /// one is still being looked up or paired is not a second pairing by the same one-time code.+ bool _scanning = false;++ /// How long the account gets to say whether it has the scanned computer before the page says it+ /// is still looking — and goes on looking ([_lookUp]).+ static const _lookUpPatience = Duration(seconds: 5);+Future<void> _scanToPair() async {- // Read before the camera: once this page is gone, its widget is not to be reached through.- final notifier = widget.notifier;- void holdIfGone(String machineId, String pairCode) {- if (!mounted) notifier.holdPendingPairing(machineId, pairCode);+ if (_scanning) return;+ _scanning = true;+ try {+ await _scanAndPair();+ } finally {+ _scanning = false;}+ }+ /// The code the new computer's Add Phone shows: the phone pairs with it. The computer is asked+ /// for first — it may have joined the account a moment ago, too recently for the list the phone+ /// holds.+ ///+ /// ⚠️ **At home, the home screen pairs, not this page.** Here this page is up only while the+ /// account has no computer, so the computer the code is for turning up — in the 5-second watch+ /// while the camera was open, or in the look-up below, which is what most often brings it —+ /// takes the page away. A page still pairing then lost its answer: a code that failed showed+ /// nothing, and "Scan its code" on the screen that replaced it started a second pairing while the+ /// first ran (PAIRING_BUSY). So the code goes to the home screen ([AppNotifier.holdPendingPairing])+ /// the moment the computer is known, and its pairing page pairs by it and says how it went —+ /// the way a code scanned at sign-in is paired. Pushed from Computers, which nothing takes away,+ /// the page pairs itself, and goes back on success. Gone either way, it hands the code over.+ Future<void> _scanAndPair() async {+ // Read before the camera: once this page is gone, its widget is not to be reached through.+ final notifier = widget.notifier;+ final atHome = widget.onBack == null;final code = await scanForCode(context,fallbackLabel: 'Not now',@@ -127,13 +145,8 @@ class _ConnectComputerPageState extends State<ConnectComputerPage> {);if (code == null) return;final machineId = code.machineId, pairCode = code.pairCode;- if (!mounted) {- if (machineId != null && pairCode != null) {- holdIfGone(machineId, pairCode);- }- return;- }if (machineId == null || pairCode == null) {+ if (!mounted) return;_say('That isn’t an Add Phone code. Open Add Phone… on the computer and ''scan its code.',@@ -141,44 +154,32 @@ class _ConnectComputerPageState extends State<ConnectComputerPage> {);return;}- _say('Pairing…');- if (!widget.notifier.machineStates.containsKey(machineId)) {- // Bounded: a slow network is a reason to say so, not to leave "Pairing…" up for good.- try {- await widget.notifier.refreshMachines().timeout(- const Duration(seconds: 5),- onTimeout: () {},- );- } catch (_) {- // ⚠️ A list that could not be read says nothing about whether the computer is on the- // account, so it is not "isn't on your account" — and thrown on from here, it left- // "Pairing…" up for good.- if (!mounted) {- holdIfGone(machineId, pairCode);- return;- }- _say(- "Couldn't reach your account. Check your connection and scan again.",- failed: true,- );- return;- }- }- // The refresh is what most often brings the computer in — and with it, at home, the page that- // replaces this one.- if (!mounted) {- holdIfGone(machineId, pairCode);+ if (mounted) _say('Pairing…');+ final lookup = await _lookUp(notifier, machineId);+ if (lookup == _Lookup.missing) {+ // The account answered, and the computer is not on it: no code to hold for it.+ if (!mounted) return;+ _say(+ "That computer isn't on your account. Sign in to Harness on it "+ 'with ${notifier.currentUser?.email ?? 'this account'}.',+ failed: true,+ );return;}- if (!widget.notifier.machineStates.containsKey(machineId)) {+ if (lookup == _Lookup.unreachable && mounted) {_say(- "That computer isn't on your account. Sign in to Harness on it "- 'with ${widget.notifier.currentUser?.email ?? 'this account'}.',+ "Couldn't reach your account. Check your connection and scan again.",failed: true,);return;}- final error = await widget.notifier.connectWithCode(machineId, pairCode);+ // Known — or, with this page gone, not known either way: a list that answers without the+ // computer lets a held code go by itself (`AppNotifier._refreshMachines`).+ if (atHome || !mounted) {+ notifier.holdPendingPairing(machineId, pairCode);+ return;+ }+ final error = await notifier.connectWithCode(machineId, pairCode);if (!mounted) return;if (error == null) {HapticFeedback.mediumImpact();@@ -192,6 +193,37 @@ class _ConnectComputerPageState extends State<ConnectComputerPage> {}}+ /// Whether the account has [machineId], asked of the account when the list held here does not+ /// have it yet.+ ///+ /// ⚠️ **Slow is not "no".** The look used to be cut at 5 seconds and the list read as it stood:+ /// a slow `/api/machines` came back as "That computer isn't on your account" — right under "Not+ /// you? Sign out", about a computer that was on it — and the answer landing a moment later took+ /// the page away with the scanned code. Past [_lookUpPatience] the page says it is still looking,+ /// and waits for the account's actual answer.+ Future<_Lookup> _lookUp(AppNotifier notifier, String machineId) async {+ if (notifier.machineStates.containsKey(machineId)) return _Lookup.found;+ final refresh = notifier.refreshMachines();+ try {+ final answered = await refresh+ .then((_) => true)+ .timeout(_lookUpPatience, onTimeout: () => false);+ if (!answered) {+ if (mounted) _say('Still looking for that computer on your account…');+ await refresh;+ }+ } catch (_) {+ // A list that could not be read says nothing about whether the computer is on the account —+ // unless it already has it.+ return notifier.machineStates.containsKey(machineId)+ ? _Lookup.found+ : _Lookup.unreachable;+ }+ return notifier.machineStates.containsKey(machineId)+ ? _Lookup.found+ : _Lookup.missing;+ }+@overrideWidget build(BuildContext context) {AppTheme.watch(context);@@ -320,3 +352,15 @@ class _WatchingState extends State<_Watching> {);}}++/// What the account said of a scanned computer ([_ConnectComputerPageState._lookUp]).+enum _Lookup {+ /// On the account.+ found,++ /// The account answered without it.+ missing,++ /// The account could not be asked.+ unreachable,+}diff --git a/mobile/lib/phone/welcome/pairing_with_code.dart b/mobile/lib/phone/welcome/pairing_with_code.dartindex 23621d49a..c94598c13 100644--- a/mobile/lib/phone/welcome/pairing_with_code.dart+++ b/mobile/lib/phone/welcome/pairing_with_code.dart@@ -51,12 +51,13 @@ class _PairingWithCodeState extends State<PairingWithCode> {unawaited(_pair(widget.code));}+ /// Through [AppNotifier.pairPendingCode], which joins a pairing by this code already under way+ /// rather than spending the one-time code twice, and lets the code go on success itself.Future<void> _pair(String code) async {- final error = await widget.notifier.connectWithCode(widget.machineId, code);+ final error = await widget.notifier.pairPendingCode(widget.machineId, code);if (!mounted) return;if (error == null) {HapticFeedback.mediumImpact();- widget.notifier.pendingPairing = null;return;}setState(() => _error = error);diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex e963a103b..410997158 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -1607,6 +1607,23 @@ class AppNotifier extends ChangeNotifier {_keptScreenStore?.clear();unawaited(_pool?.closeAll());_pool = null;+ // ⚠️ **The account's machines go with it, as on a sign-out by hand ([_endSession]).** Kept,+ // the next sign-in — perhaps another account's — started on this account's list: it was not+ // empty, so no "Looking for your computers…", and this account's computers were drawn as the+ // next one's until its own fetch landed. The warm-start cache on disk went on naming them too,+ // and the next launch dialled them with the new session.+ _stopAllOfflineRetries();+ _stopAllAgentSyncTimers();+ _relaySaid.clear();+ // Reads [machineStates], so before it is emptied.+ _clearAllTurnActivity();+ machines = [];+ machineStates.clear();+ unawaited(_machineCache?.clear());+ sessionPreviews.clear();+ agentNotices.reset();+ expandedMachines.clear();+ selectedMachineId = null;// ⚠️ The saved session goes too. The socket that said so (a refresh refused, 4403) is the only// judge of it, and a session left on disk signed the NEXT launch straight back in — only to be// refused again, with the person never told why. Best effort, as [logout]'s own: a store that@@ -2953,6 +2970,72 @@ class AppNotifier extends ChangeNotifier {notifyListeners();}+ /// The pairing [pendingPairing]'s code is being spent on, while it runs — see [pairPendingCode].+ ({String machineId, String code, Future<String?> result})? _pairingRun;++ /// The code [pendingPairing] held when the home screen began pairing by it — see+ /// [pendingPairingTried].+ ({String machineId, String code})? _pairingTried;++ /// Whether the home screen has begun pairing by the code [pendingPairing] holds now.+ ///+ /// From then on its pairing page (`phone/welcome/pairing_with_code.dart`) stays up until the code+ /// is spent or dropped, and not only while the machine reads locked: a redial that clears+ /// [MachineState.needsLink] for a moment — the vouched redials of a fresh sign-in+ /// ([_redialOnceVouched]) — took the page down mid-pairing, hid an error it then had, and built+ /// it again a second later to pair a second time by the same one-time code.+ bool get pendingPairingTried {+ final pending = pendingPairing, tried = _pairingTried;+ return pending != null &&+ tried != null &&+ pending.machineId == tried.machineId &&+ pending.code == tried.code;+ }++ /// Pairs with [machineId] by [code], the code [pendingPairing] holds — once per code at a time.+ ///+ /// ⚠️ **A second call for the same code while the first runs joins it.** The code is one-time: a+ /// pairing page built again while one is still pairing (see [pendingPairingTried]) spent it a+ /// second time, and the computer, mid-pairing, answered PAIRING_BUSY or CODE_MISMATCH while the+ /// first went through. A call after one that has FINISHED pairs again: "Scan again" after a+ /// timeout reads the same code back off Add Phone, and it is good again.+ ///+ /// Success lets the code go here, not on the page: the page can be gone by then.+ Future<String?> pairPendingCode(String machineId, String code) {+ final running = _pairingRun;+ if (running != null &&+ running.machineId == machineId &&+ running.code == code) {+ return running.result;+ }+ _pairingTried = (machineId: machineId, code: code);+ late final Future<String?> result;+ result = () async {+ String? error;+ try {+ error = await connectWithCode(machineId, code);+ } catch (e) {+ // [connectWithCode] answers with a result, not an exception; one that slips through must+ // not leave "Connecting to…" up with nothing behind it.+ appLog.warn('pair', 'pairing by code with $machineId threw: $e');+ error = 'Couldn’t connect. Scan again.';+ } finally {+ if (identical(_pairingRun?.result, result)) _pairingRun = null;+ }+ final pending = pendingPairing;+ if (error == null &&+ pending != null &&+ pending.machineId == machineId &&+ pending.code == code) {+ pendingPairing = null;+ notifyListeners();+ }+ return error;+ }();+ _pairingRun = (machineId: machineId, code: code, result: result);+ return result;+ }+/// Pairs with [machineId] by the one-time code its desktop app showed, then reconnects it — the/// QR's way in, where [connectWithPassword] is the password's. Null on success, or what to show.Future<String?> connectWithCode(String machineId, String code) async {diff --git a/mobile/lib/viewer/direct_link.dart b/mobile/lib/viewer/direct_link.dartindex aaa722cf0..afc14a0e0 100644--- a/mobile/lib/viewer/direct_link.dart+++ b/mobile/lib/viewer/direct_link.dart@@ -3,6 +3,7 @@ import '../auth/link_errors.dart';import '../auth/peer_link_client.dart';import '../core/config.dart';import '../e2ee/keys.dart';+import '../logging/app_log.dart';import 'direct_auth.dart';import 'direct_auth_api.dart';import 'code_link.dart';@@ -92,16 +93,7 @@ class DirectLink implements PeerLinkClient {final name = displayName == null || displayName.isEmpty? 'the computer': displayName;- return CliLinkConnectResult(- error: switch (code) {- 'CODE_MISMATCH' =>- 'That code didn’t match. Scan the new one on $name.',- 'TIMEOUT' => 'Keep “Add Phone” open on $name, then scan again.',- 'PAIRING_BUSY' =>- '$name is pairing with something else. Try again.',- _ => 'Couldn’t connect to $name ($code).',- },- );+ return CliLinkConnectResult(error: _codePairingError(code, name));}}@@ -207,3 +199,36 @@ String _asCliPrints(DateTime at) {String two(int n) => n.toString().padLeft(2, '0');return '${at.year}-${two(at.month)}-${two(at.day)} ${two(at.hour)}:${two(at.minute)}';}++/// A failed pairing by an Add Phone code ([linkWithCode]) as the sentence the pairing screen shows,+/// [name] the computer's.+///+/// ⚠️ **Never the bare code.** The fallback used to be "Couldn’t connect to $name ($code)." — and+/// most failures took it: every socket error (CONNECTION_ERROR), a socket closed mid-pairing, a+/// computer the relay could not reach, the computer's own refusal, and whatever string a computer+/// sends back. Each now says what to do instead, and the code goes to the log.+String _codePairingError(String code, String name) {+ appLog.warn('pair', 'pairing by code failed: $code');+ // Where the name starts the sentence: "the computer", for one with no name, would not.+ final subject = name.isEmpty+ ? name+ : '${name[0].toUpperCase()}${name.substring(1)}';+ if (code.startsWith('CONNECTION_CLOSED')) {+ return 'The connection to $name dropped before pairing finished. Scan again.';+ }+ return switch (code) {+ 'CODE_MISMATCH' => 'That code didn’t match. Scan the new one on $name.',+ 'TIMEOUT' => 'Keep “Add Phone” open on $name, then scan again.',+ 'PAIRING_BUSY' => '$subject is pairing with something else. Try again.',+ 'CONNECTION_ERROR' =>+ 'Couldn’t reach $name. Check your connection, then scan again.',+ 'SELECT_FAILED' =>+ 'Couldn’t find $name, or it’s offline. Make sure Harness is open there, then scan again.',+ 'PAIR_REFUSED' || 'PAIR_FAILED' =>+ '$subject didn’t finish pairing. Open Add Phone… on it again and scan the new code.',+ 'PROTOCOL_ERROR' =>+ 'Pairing with $name went wrong. Make sure Harness is up to date there, then scan again.',+ _ =>+ 'Couldn’t pair with $name. Open Add Phone… on it again and scan the new code.',+ };+}