Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Merge branch 'main' into feat/mobile-ios-android

tonya33c94bd6c2d
diff --cc mobile/lib/phone/devices_page.dart
index e8c74efa1,22ee78b47..79afa1d52
--- a/mobile/lib/phone/devices_page.dart
+++ b/mobile/lib/phone/devices_page.dart
@@@ -317,157 -316,156 +317,173 @@@ class _DevicesPageState extends State<D
backgroundColor: tty.ground,
body: SafeArea(
bottom: false,
- child: ListView(
- padding: EdgeInsets.fromLTRB(
- Tty.origin,
- 12,
- Tty.origin,
- MediaQuery.paddingOf(context).bottom + 24,
- ),
+ child: Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
- const TtyText(
- 'Your devices',
- size: TtySize.title,
- weight: FontWeight.w600,
- ),
- const SizedBox(height: 8),
- Text(
- 'Every computer and app signed in to your account. Each reaches your machines '
- 'end to end encrypted. Remove one you do not recognise.',
- style: tty.style(color: tty.dim),
- ),
- if (frozen) ...[
- const SizedBox(height: 12),
- SettingsGroup(
- children: [
- SettingsRow(
- title: 'The device list froze',
- detail: listing.frozen != null
- ? 'Harness served a list that does not match what this phone verified. '
- 'No device is added until you review it.'
- : 'Frozen on ${listing.frozenPeers.join(', ')}. Review it on that computer.',
- destructive: true,
- detailLines: null,
- onTap: listing.frozen != null
- ? () => unawaited(_trustAgain())
- : null,
- value: listing.frozen != null ? 'Review' : null,
- ),
- ],
- ),
- ],
- if (listing?.registerError case final code?) ...[
- const SizedBox(height: 12),
- SettingsGroup(
- children: [
- SettingsRow(
- key: const ValueKey('devices-refused'),
- title: 'This device couldn’t join',
- detail: code == 'TOO_MANY'
- ? 'Your account has too many devices. Remove ones you no longer use.'
- : 'Harness refused it a place on your account’s device list ($code).',
- destructive: true,
- detailLines: null,
- ),
- ],
- ),
- ],
- if (listing != null &&
- !listing.baselineSeen &&
- !_baselineHidden) ...[
- if (_baseline(listing) case final baseline
- when baseline.isNotEmpty) ...[
- const SizedBox(height: 12),
- _BaselinePanel(
- key: const Key('account-devices-baseline'),
- rows: baseline,
- onGotIt: () => unawaited(_gotIt()),
+ // Always pushed — from Settings, the new-device banner or its notification — so it
+ // carries the way back as Settings does: above the title, and outside the list, so a
+ // long list scrolled down keeps it.
+ if (canPop)
+ Align(
+ alignment: Alignment.centerLeft,
+ child: TtyBackButton(
+ onPressed: () => Navigator.of(context).maybePop(),
),
- ],
- ],
- if (_error case final error?) ...[
- const SizedBox(height: 12),
- Text(
- error,
- key: const Key('account-devices-error'),
- // Amber when the person has something to act on (another account, a list that moved):
- // the same severity as the desktop. A failure is red.
- style: tty.style(color: _errorWarns ? tty.yellow : tty.red),
),
- ],
- if (listing != null && _unused(listing).isNotEmpty) ...[
- const SizedBox(height: 12),
- SettingsGroup(
+ Expanded(
+ child: ListView(
+ padding: EdgeInsets.fromLTRB(
+ Tty.origin,
+ canPop ? 8 : 12,
+ Tty.origin,
+ MediaQuery.paddingOf(context).bottom + 24,
+ ),
children: [
- SettingsRow(
- key: const Key('account-devices-unused'),
- title:
- '${_unused(listing).length} app${_unused(listing).length == 1 ? '' : 's'} not used in 90 days',
- detail: 'Most likely a browser whose data was cleared.',
- value: _removingUnused ? 'Removing…' : 'Remove',
- destructive: true,
- onTap: _removingUnused
- ? null
- : () => unawaited(_removeUnused(_unused(listing))),
+ const TtyText(
+ 'Your devices',
+ size: TtySize.title,
+ weight: FontWeight.w600,
),
- ],
- ),
- ],
- const SizedBox(height: 12),
- if (listing == null)
- const SizedBox.shrink()
- else ...[
- if (selfRow(listing.members) case final self?) ...[
- SettingsGroup(
- children: [
- _ThisDeviceCard(
- key: const Key('account-device-this'),
- row: self,
+ const SizedBox(height: 8),
+ Text(
+ 'Every computer and app signed in to your account. Each reaches your machines '
+ 'end to end encrypted. Remove one you do not recognise.',
+ style: tty.style(color: tty.dim),
+ ),
+ if (frozen) ...[
+ const SizedBox(height: 12),
+ SettingsGroup(
+ children: [
+ SettingsRow(
+ title: 'The device list froze',
+ detail: listing.frozen != null
+ ? 'Harness served a list that does not match what this phone verified. '
+ 'No device is added until you review it.'
+ : 'Frozen on ${listing.frozenPeers.join(', ')}. Review it on that computer.',
+ destructive: true,
+ detailLines: null,
+ onTap: listing.frozen != null
+ ? () => unawaited(_trustAgain())
+ : null,
+ value: listing.frozen != null ? 'Review' : null,
+ ),
+ ],
),
],
- ),
- const SizedBox(height: 12),
- ],
- SettingsGroup(
- children: [
- for (final row in orderDeviceRows(
- listing.members,
- _seen,
- _newPubs,
- ))
- SettingsRow(
- key: ValueKey('account-device-${row.member.pub}'),
- title: row.member.label.trim().isEmpty
- ? 'Unnamed device'
- : row.member.label,
- detail: deviceDetailLine(
- row,
- _seen[row.member.pub],
- DateTime.now(),
- sameName: sharedNames(listing.members)
- .contains(row.member.label.trim()),
++ if (listing?.registerError case final code?) ...[
++ const SizedBox(height: 12),
++ SettingsGroup(
++ children: [
++ SettingsRow(
++ key: const ValueKey('devices-refused'),
++ title: 'This device couldn’t join',
++ detail: code == 'TOO_MANY'
++ ? 'Your account has too many devices. Remove ones you no longer use.'
++ : 'Harness refused it a place on your account’s device list ($code).',
++ destructive: true,
++ detailLines: null,
++ ),
++ ],
++ ),
++ ],
+ if (listing != null &&
+ !listing.baselineSeen &&
+ !_baselineHidden) ...[
+ if (_baseline(listing) case final baseline
+ when baseline.isNotEmpty) ...[
+ const SizedBox(height: 12),
+ _BaselinePanel(
+ key: const Key('account-devices-baseline'),
+ rows: baseline,
+ onGotIt: () => unawaited(_gotIt()),
),
- value: row.suspended
- ? 'Suspended'
- : _newPubs.contains(row.member.pub)
- ? 'New'
- : null,
- onTap: () => _open(row),
+ ],
+ ],
+ if (_error case final error?) ...[
+ const SizedBox(height: 12),
+ Text(
+ error,
+ key: const Key('account-devices-error'),
+ // Amber when the person has something to act on (another account, a list that moved):
+ // the same severity as the desktop. A failure is red.
+ style: tty.style(color: _errorWarns ? tty.yellow : tty.red),
),
+ ],
+ if (listing != null && _unused(listing).isNotEmpty) ...[
+ const SizedBox(height: 12),
+ SettingsGroup(
+ children: [
+ SettingsRow(
+ key: const Key('account-devices-unused'),
+ title:
+ '${_unused(listing).length} app${_unused(listing).length == 1 ? '' : 's'} not used in 90 days',
+ detail: 'Most likely a browser whose data was cleared.',
+ value: _removingUnused ? 'Removing…' : 'Remove',
+ destructive: true,
+ onTap: _removingUnused
+ ? null
+ : () => unawaited(_removeUnused(_unused(listing))),
+ ),
+ ],
+ ),
+ ],
+ const SizedBox(height: 12),
+ if (listing == null)
+ const SizedBox.shrink()
+ else ...[
+ if (selfRow(listing.members) case final self?) ...[
+ SettingsGroup(
+ children: [
+ _ThisDeviceCard(
+ key: const Key('account-device-this'),
+ row: self,
+ ),
+ ],
+ ),
+ const SizedBox(height: 12),
+ ],
+ SettingsGroup(
+ children: [
+ for (final row in orderDeviceRows(
+ listing.members,
+ _seen,
+ _newPubs,
+ ))
+ SettingsRow(
+ key: ValueKey('account-device-${row.member.pub}'),
+ title: row.member.label.trim().isEmpty
+ ? 'Unnamed device'
+ : row.member.label,
+ detail: deviceDetailLine(
+ row,
+ _seen[row.member.pub],
+ DateTime.now(),
+ sameName: sharedNames(listing.members)
+ .contains(row.member.label.trim()),
+ ),
+ value: row.suspended
+ ? 'Suspended'
+ : _newPubs.contains(row.member.pub)
+ ? 'New'
+ : null,
+ onTap: () => _open(row),
+ ),
+ ],
+ ),
+ const SizedBox(height: 12),
+ SettingsGroup(
+ children: [
+ SettingsRow(
+ key: const Key('account-devices-history'),
+ title: 'History',
+ onTap: _openHistory,
+ ),
+ ],
+ ),
+ ],
],
),
- const SizedBox(height: 12),
- SettingsGroup(
- children: [
- SettingsRow(
- key: const Key('account-devices-history'),
- title: 'History',
- onTap: _openHistory,
- ),
- ],
- ),
- ],
+ ),
],
),
),
diff --cc mobile/lib/phone/welcome/unlock_computer.dart
index fdf073406,6e094feb0..d53d8d462
--- a/mobile/lib/phone/welcome/unlock_computer.dart
+++ b/mobile/lib/phone/welcome/unlock_computer.dart
@@@ -180,19 -170,55 +182,62 @@@ class _UnlockComputerState extends Stat
return ListView(
padding: const EdgeInsets.fromLTRB(Tty.origin, 12, Tty.origin, 24),
children: [
- TtyText('Unlock $name', size: 24, weight: FontWeight.w600),
+ // A Text, not a one-line TtyText: a long computer name wraps instead of being cut off.
+ Text(
+ 'Unlock $name',
+ style: tty.style(size: 24, weight: FontWeight.w600),
+ ),
const SizedBox(height: 12),
Text(
- 'On $name, open Harness ▸ Add Phone…, then scan the QR code.',
+ // Where Add Phone is, not only its name: the Harness menu is the Mac's; on Linux it is
+ // the command palette's, which the scan page's own hint says.
+ 'In Harness on $name, open Add Phone…, then scan the QR code. On a '
+ 'Mac, it’s in the Harness menu.',
style: tty.style(size: TtySize.row, color: tty.faint),
),
+ // This phone's copy of the device list is frozen, so it pins no computer from it — or the
+ // account has too many devices to let this phone in: the list is the other way in, beside the
+ // code and the password.
+ ListenableBuilder(
+ listenable: widget.notifier,
+ builder: (context, _) =>
+ !widget.notifier.deviceListNeedsReview &&
+ !widget.notifier.deviceListTooMany
+ ? const SizedBox.shrink()
+ : Padding(
+ padding: const EdgeInsets.only(top: 12),
+ child: Row(
+ children: [
+ Expanded(
+ child: Text(
+ [
+ if (widget.notifier.deviceListNeedsReview)
+ 'Your device list needs a review.',
+ if (widget.notifier.deviceListTooMany)
+ 'This device couldn’t join: your account has too many devices. '
+ 'Remove ones you no longer use.',
+ ].join('\n'),
+ style: tty.style(
+ size: TtySize.meta,
+ color: tty.yellow,
+ ),
+ ),
+ ),
+ TtyTextButton(
+ key: const ValueKey('device-list-review'),
+ label: 'Your devices',
+ onPressed: () => unawaited(
+ Navigator.of(context).push(
+ phoneRoute(
+ (_) => DevicesPage(notifier: widget.notifier),
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
const SizedBox(height: 18),
TtyPrimaryButton(
key: const ValueKey('unlock-scan'),
diff --cc mobile/lib/state/app_state.dart
index b4480b9a5,4d3179c57..ba1e97759
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@@ -10,9 -10,8 +10,10 @@@ import '../teams/team_controller.dart'
import '../api/api_client.dart';
import '../viewer/direct_auth_api.dart';
import '../viewer/direct_link.dart';
+import '../viewer/direct_login.dart';
import '../viewer/group_sync.dart';
+ import '../e2ee/bytes.dart' show b64e;
+import '../viewer/sign_in_browser.dart';
import '../viewer/viewer_services.dart';
import '../auth/auth_session.dart';
import '../auth/peer_link_client.dart';
@@@ -1593,45 -1395,16 +1601,46 @@@ class AppNotifier extends ChangeNotifie
_invalidateAuthWork();
currentUser = null;
signingIn = false;
+ signInProvider = null;
// The code was scanned into the session that just ended — see [logout].
pendingPairing = null;
+ pendingComputerSignIn = null;
_clearDeviceNotices();
+ _stopAccountTimers();
_desk.reset();
zoo.reset();
+ _forgetLaunchHold();
+ // Signed out from elsewhere: the kept screens go as on a sign-out here (see [logout]).
+ _keptScreens.clear();
+ _forgetScrollMemories();
+ _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
+ // cannot be written to must not surface as an unhandled error on the way out.
+ unawaited(cliLogin.logout().catchError((Object _) {}));
_lastError = message;
_lastErrorRetryable = true;
+ signedOutReason = _signedOutEnded;
status = AppStatus.unauthenticated;
notifyListeners();
}
@@@ -1859,8 -1511,7 +1868,9 @@@
unawaited(cliLogin.logout());
_stopAllOfflineRetries();
_stopAllAgentSyncTimers();
+ _relaySaid.clear();
+ _forgetLaunchHold();
+ _stopAccountTimers();
// Tiles go, the saved layout stays: signing out and back in is the same
// person at the same desk, and the file is only read once machines exist.
await _closeAllPanes(persist: false);
@@@ -1930,9 -1613,6 +1975,9 @@@
// few seconds for a `harness link connect` run elsewhere, which a phone's links never come from.
machine.needsLink = true;
machine.agentLoadStatus = AgentLoadStatus.needsLink;
+ // …unless the log already vouches for it and this phone's key is new to it: then the machine
+ // has only not read that key yet — see [_redialOnceVouched].
- unawaited(_redialOnceVouched(machineId));
++ unawaited(_redialOnceVouched(machine.machine.machineId));
// A 4404 can also arrive MID-SESSION ("peer revoked trust" in the CLI's
// remoteRelay.ts) with terminals open on this machine. The disconnect
// that follows deliberately no longer marks the node offline (see the
@@@ -1947,6 -1627,130 +1992,132 @@@
notifyListeners();
}
+ // -- a refusal for want of trust ([_onLocalFailure]) ---------------------------------------------
+
+ /// How many refusals of each machine were settled since it last connected, and the ones under way —
+ /// each with what ends its wait early (a pin landing: [_redialNewlyTrusted]).
+ final Map<String, int> _trustRounds = {};
+ final Set<String> _trustSettling = {};
+ final Map<String, Completer<void>> _trustWakes = {};
+ static const _trustSettleRounds = 2;
+
+ /// How long one settling round waits for the machine's key to land before dialling again: two
+ /// rounds, about fifteen seconds, before a password is asked for.
+ @visibleForTesting
+ Duration trustSettleRound = const Duration(milliseconds: 7500);
+
+ /// How long a machine that denied this phone's key gets to read the account's log again (its CLI
+ /// does on a hello from a key it does not know) before the first hello is said again.
+ @visibleForTesting
+ Duration trustDeniedWait = const Duration(seconds: 1);
+
+ /// Hears every [_redial], for a test with no pool to dial through.
+ @visibleForTesting
+ void Function(String machineId)? onRedialForTest;
+
++ /// The first eight characters of a machine id — enough to tell an account's machines apart in
++ /// a log line.
+ static String _shortId(String id) => id.length > 8 ? id.substring(0, 8) : id;
+
+ /// One round of settling [machineId]'s refusal ([reason]: `NO_PEER_LINK`, no key here for it, or
+ /// `E2E_DENIED`, the machine does not know this phone's): put this phone into the account's device
+ /// log and read it, then dial again — at once when the machine's key just landed, after a moment for
+ /// a machine that has to read the log itself. A frozen log can settle nothing: the password it is.
+ Future<void> _settleTrust(String machineId, String reason) async {
+ final log = _deviceLog;
+ if (log == null) return;
+ final revision = _authRevision;
+ final round = _trustRounds[machineId] = (_trustRounds[machineId] ?? 0) + 1;
+ final wake = _trustWakes[machineId] = Completer<void>();
+ final short = _shortId(machineId);
+ bool current() =>
+ !_disposed &&
+ _authWorkCurrent(revision) &&
+ identical(_trustWakes[machineId], wake) &&
+ machineStates.containsKey(machineId);
+ final started = Stopwatch()..start();
+ try {
+ final registration = await log.ensureRegistered().timeout(
+ trustSettleRound,
+ onTimeout: () => DeviceLogRegistration.missing,
+ );
+ if (!current()) return;
+ if (registration == DeviceLogRegistration.frozen) {
+ appLog.info('link', '$short refused ($reason): the device list is frozen');
+ // The machine's password form says so (deviceListNeedsReview), from the listing.
+ unawaited(_syncPendingDevices());
+ _trustRounds[machineId] = _trustSettleRounds;
+ _endTrustSettle(machineId);
+ final machine = machineStates[machineId]!
+ ..connectionStatus = ConnectionStatus.disconnected;
+ _markNeedsLink(machine);
+ return;
+ }
+ if (registration == DeviceLogRegistration.registered) {
+ appLog.info('link', '$short refused ($reason): this phone joined the device list');
+ }
+ final pinned = await _holdsMachineKey(machineId);
+ if (!current()) return;
+ if (reason == 'E2E_DENIED' || !pinned) {
+ final rest = trustSettleRound - started.elapsed;
+ final wait = reason == 'E2E_DENIED' && round == 1
+ ? trustDeniedWait
+ : rest.isNegative
+ ? Duration.zero
+ : rest;
+ await Future.any([Future<void>.delayed(wait), wake.future]);
+ if (!current()) return;
+ }
+ final now = pinned || await _holdsMachineKey(machineId);
+ if (!current()) return;
+ appLog.info(
+ 'link',
+ '$short refused ($reason): ${now ? 'pinned' : 'no key yet'}, dialling again (round $round)',
+ );
+ _endTrustSettle(machineId);
+ _redial(machineId);
+ } finally {
+ // However the round ended, a machine no longer being settled can be settled again.
+ if (identical(_trustWakes[machineId], wake)) _endTrustSettle(machineId);
+ }
+ }
+
+ void _endTrustSettle(String machineId) {
+ _trustSettling.remove(machineId);
+ final wake = _trustWakes.remove(machineId);
+ if (wake != null && !wake.isCompleted) wake.complete();
+ }
+
+ /// [machineId] connected, or the account is left: its refusals start counting again.
+ void _forgetTrustSettle(String machineId) {
+ _trustRounds.remove(machineId);
+ _endTrustSettle(machineId);
+ }
+
+ void _forgetAllTrustSettles() {
+ for (final machineId in [..._trustRounds.keys, ..._trustSettling]) {
+ _forgetTrustSettle(machineId);
+ }
+ }
+
+ Future<bool> _holdsMachineKey(String machineId) async {
+ try {
+ return await viewer.keys.peer(machineId) != null;
+ } catch (_) {
+ return false;
+ }
+ }
+
+ /// Dial [machineId] again from scratch: a refused connection is closed for good, so it is closed
+ /// and replaced.
+ void _redial(String machineId) {
+ final machine = machineStates[machineId];
+ if (machine == null) return;
+ onRedialForTest?.call(machineId);
+ unawaited(_pool?.closeMachine(machineId));
+ _connectMachine(machine);
+ }
+
/// The token a viewer's relay socket dials with.
Future<String> _socketToken(bool force, String? failedToken) =>
// Only a session that is gone for good may sign the person out — see
@@@ -1988,8 -1798,7 +2165,9 @@@
if (nextStatus == ConnectionStatus.connected) {
_refreshDeviceLogAfterReconnect();
machine.needsLink = false;
- // Let in: a later refusal is a new story ([_redialOnceVouched]).
++ // Let in: a later refusal is a new story ([_redialOnceVouched], [_settleTrust]).
+ _vouchedRedials.remove(machineId);
+ _forgetTrustSettle(machineId);
// A relay socket reports `connected` only after the machine's welcome
// proved the link (`WsConn._markReady`), so a code held to pair this
// machine has nothing left to do. Kept, it would be spent the next time
@@@ -3308,33 -2786,67 +3529,73 @@@
StartupTrace.mark('skipped offline machine ${machine.machineId}');
continue;
}
+ // Held until the launch's own terminal is up — see [_launchMachineId]. The cached ones were
+ // held by the warm start already; this catches the machines the cache did not know.
+ if (_heldForLaunch(machine.machineId)) {
+ _holdForLaunch(machine.machineId);
+ continue;
+ }
- _connectMachine(state);
- // ⚠️ **Only ask a machine that is already answering.** `_connectMachine`
- // starts a dial; it does not finish one. Asking here regardless meant
- // `waitUntilReady` sat on a handshake that had not happened yet, spending
- // the inventory budget on the connection rather than on the request — and
- // on a first launch it spent ALL of it, which then read as the machine
- // having gone offline and triggered a `forceReconnect()` that threw the
- // working socket away and started over.
- //
- // A machine that is not ready yet loses nothing: `_onConnectionStatus`
- // calls this the moment its handshake completes, with `force: true`, which
- // is the path every reconnect in the app already takes.
- //
- // Read off the POOL rather than through `_conn`, which would build a
- // connection as a side effect of being asked about one — for a machine
- // `_connectMachine` had just declined to dial, that would be this method
- // quietly undoing its own decision.
- if (_connectionReady(machine.machineId)) {
- unawaited(_loadMachineData(state));
+ dial.add(state);
+ }
+ unawaited(_connectAfterDeviceLog(dial, load: true));
+ }
+
+ /// Dial [states]: at once a machine this phone holds a key for, one already asking for its password
+ /// and one a scanned code waits for. A machine with no key here may only be missing from this
+ /// phone's copy of the device log — a computer signed in after the phone was — so the log is read
+ /// first, briefly, rather than dialling a refusal. [load]: ask a machine that already answers for
+ /// its data ([_dialAndLoad]).
+ Future<void> _connectAfterDeviceLog(
+ List<MachineState> states, {
+ required bool load,
+ }) async {
+ final revision = _authRevision;
+ bool current(MachineState state) =>
+ _authWorkCurrent(revision) &&
+ identical(machineStates[state.machine.machineId], state);
+ final waiting = <MachineState>[];
+ for (final state in states) {
+ final machineId = state.machine.machineId;
+ if (state.needsLink ||
+ pendingPairing?.machineId == machineId ||
+ await _holdsMachineKey(machineId)) {
+ if (current(state)) _dialAndLoad(state, load: load);
+ } else {
+ waiting.add(state);
}
}
+ if (waiting.isEmpty) return;
+ await _deviceLog?.refresh().timeout(
+ const Duration(seconds: 5),
+ onTimeout: () {},
+ );
+ for (final state in waiting) {
+ if (current(state)) _dialAndLoad(state, load: load);
+ }
+ }
+
+ void _dialAndLoad(MachineState state, {required bool load}) {
+ _connectMachine(state);
+ if (!load) return;
+ // ⚠️ **Only ask a machine that is already answering.** `_connectMachine`
+ // starts a dial; it does not finish one. Asking here regardless meant
+ // `waitUntilReady` sat on a handshake that had not happened yet, spending
+ // the inventory budget on the connection rather than on the request — and
+ // on a first launch it spent ALL of it, which then read as the machine
+ // having gone offline and triggered a `forceReconnect()` that threw the
+ // working socket away and started over.
+ //
+ // A machine that is not ready yet loses nothing: `_onConnectionStatus`
+ // calls this the moment its handshake completes, with `force: true`, which
+ // is the path every reconnect in the app already takes.
+ //
+ // Read off the POOL rather than through `_conn`, which would build a
+ // connection as a side effect of being asked about one — for a machine
+ // `_connectMachine` had just declined to dial, that would be this method
+ // quietly undoing its own decision.
+ if (_connectionReady(state.machine.machineId)) {
+ unawaited(_loadMachineData(state));
+ }
}
/// A user-triggered reload is in flight.
@@@ -3476,349 -2980,39 +3737,344 @@@
/// Bulk terminal data for a machine, which may now be feeding several tiles.
///
- /// Read the live session identity instead of maintaining a second registry.
- /// Skip unrelated sessions before awaiting: every ignored async call adds a
- /// scheduling turn to the socket's incoming queue. Matching frames enter the
- /// session's ordered renderer queue synchronously, regardless of tab order.
- Future<void> _handleTerminalBinary(String machineId, Uint8List raw) async {
- final targets = panesFor(machineId)
- .map((pane) => pane.session)
- .whereType<TerminalSession>()
- .toList();
- if (targets.isEmpty) return;
- final clear = decodeTerminalLocal(raw);
- if (clear == null) {
- // Undecodable says the transport is wrong, not that one stream is — so
- // it goes to all of them.
- for (final terminal in targets) {
- terminal.transportLost('Binary terminal frame could not be decoded');
- }
+ /// Read the live session identity instead of maintaining a second registry.
+ /// Skip unrelated sessions before awaiting: every ignored async call adds a
+ /// scheduling turn to the socket's incoming queue. Matching frames enter the
+ /// session's ordered renderer queue synchronously, regardless of tab order.
+ Future<void> _handleTerminalBinary(String machineId, Uint8List raw) async {
+ final targets = panesFor(machineId)
+ .map((pane) => pane.session)
+ .whereType<TerminalSession>()
+ .toList();
+ if (targets.isEmpty) return;
+ final clear = decodeTerminalLocal(raw);
+ if (clear == null) {
+ // Undecodable says the transport is wrong, not that one stream is — so
+ // it goes to all of them.
+ for (final terminal in targets) {
+ terminal.transportLost('Binary terminal frame could not be decoded');
+ }
+ return;
+ }
+ for (final terminal in targets) {
+ if (terminal.streamId == clear.streamId) {
+ await terminal.handleBinary(clear);
+ }
+ }
+ }
+
+ Future<bool> _sendTerminalBinary(
+ String machineId,
+ TerminalBinaryFrame frame,
+ ) async {
+ final encoded = encodeTerminalLocal(frame);
+ if (encoded == null) return false;
+ return _conn(machineId).sendTerminalBinary(encoded);
+ }
+
+ /// How long a `terminal_open` waits for its machine's handshake — see [_sendTerminalFrame].
+ /// The dial's own limit and a select's, near enough: past it the socket is not about to be up.
+ static const _openWaitsForHandshake = Duration(seconds: 15);
+
+ /// A terminal frame for [machineId]'s connection — a `terminal_open` held until the handshake
+ /// is done, every other frame sent (or refused) at once, as before.
+ ///
+ /// ⚠️ **Why the open waits (owner, 2026-10-01).** A launch builds its terminal from the cached
+ /// agent and capabilities, so the open is made while the socket is still handshaking, and the
+ /// socket refused it: the session gave up on it ("Could not send terminal_open"), and nothing
+ /// asked again until the machine answered `terminal_capabilities` or its agent list, which reattach
+ /// waiting panes — measured at 0.6–0.75s after the socket was ready, every launch. Held here
+ /// instead, it leaves the moment the handshake lands, with the request it was made with. Bounded:
+ /// a handshake that does not land in [_openWaitsForHandshake] refuses it as before, and the
+ /// usual reattach on connect takes over.
+ Future<bool> _sendTerminalFrame(
+ String machineId,
+ String type,
+ Map<String, dynamic> payload,
+ ) async {
+ final connection = _conn(machineId);
+ if (type == 'terminal_open' && !connection.isReady) {
+ try {
+ await connection.waitUntilReady(timeout: _openWaitsForHandshake);
+ } catch (_) {
+ // Timed out, or the connection was closed meanwhile: the socket refuses the frame below,
+ // which is the answer the session already knows how to take.
+ }
+ }
+ return connection.sendTerminalFrame(type, payload);
+ }
+
+ /// The machine a launch dials ALONE — the one the phone last had an agent open on — while every
+ /// other machine waits in [_heldMachines]; null once they have been let go, and on a launch that
+ /// had nothing to put first.
+ ///
+ /// ⚠️ **Why a launch dials one machine first (owner, 2026-10-01).** Every machine the account
+ /// had was dialled at once: a relay socket, an E2EE handshake, `terminal_capabilities`, a full
+ /// agent list and a P2P negotiation EACH, seven or eight of them on a phone, all in the same
+ /// second as the one terminal the person is waiting to see — which is on one machine. On one
+ /// machine a launch measured 3.3s to a ready socket; the work on the others added nothing anybody
+ /// was looking at. The rest are let go the moment that terminal shows its first frame
+ /// ([_releaseOnFirstFrame]), when Find opens ([reachAllMachines]), or after
+ /// [_heldMachinesRelease] whatever happens; and a machine is dialled the moment one of its own
+ /// agents is opened, held or not ([_conn] dials what it does not hold).
+ ///
+ /// What it costs: for those few seconds the other machines' sessions read from the cache, as
+ /// `connecting`, and anything they announce in that time (a finished turn, a question) arrives
+ /// as soon as they are dialled rather than at once.
+ String? _launchMachineId;
+ final Set<String> _heldMachines = {};
+ Timer? _heldMachinesTimer;
+ static const _heldMachinesRelease = Duration(seconds: 5);
+
+ /// Whether [machineId] is one the launch is holding back — see [_launchMachineId] — or one it has
+ /// let go of that is still waiting for its turn to dial ([_releaseQueue]).
+ bool _heldForLaunch(String machineId) =>
+ (_launchMachineId != null && machineId != _launchMachineId) ||
+ _releaseQueue.contains(machineId);
+
+ /// Hold [machineId] back for the launch — a machine [_heldForLaunch] says is held. Nothing to do
+ /// for one already let go: it is waiting in [_releaseQueue], which dials it in its turn.
+ void _holdForLaunch(String machineId) {
+ if (_launchMachineId != null) _heldMachines.add(machineId);
+ }
+
+ /// The machines the launch let go of that have not dialled yet, in the order they go — see
+ /// [_dialReleasedInTurn].
+ final List<String> _releaseQueue = [];
+
+ /// The let-go machines dialling now, each with the timer that ends its turn if nothing else does
+ /// first ([_endReleaseTurn]).
+ final Map<String, Timer> _releaseTurns = {};
+
+ /// How many let-go machines dial at once, and how long one may hold its turn.
+ static const _releaseTurnsAtOnce = 3;
+ static const _releaseTurnLimit = Duration(seconds: 4);
+
+ /// Since the launch let its held machines go — the offsets in their timeline lines.
+ Stopwatch? _releaseClock;
+
+ /// Let go of every machine the launch held back. Idempotent; [why] goes to the startup timeline.
+ ///
+ /// [atOnce] dials all of them now, and with them any still waiting their turn — for a person
+ /// asking for every machine (Find), and for a launch that turned out to have nothing to put
+ /// first. Otherwise they dial a few at a time ([_dialReleasedInTurn]).
+ void _releaseHeldMachines(String why, {bool atOnce = false}) {
+ if (_launchMachineId != null) {
+ _launchMachineId = null;
+ _heldMachinesTimer?.cancel();
+ _heldMachinesTimer = null;
+ final held = _heldMachines.toList();
+ _heldMachines.clear();
+ if (_disposed) return;
+ StartupTrace.mark(
+ 'launch: letting ${held.length} held machine(s) go '
+ '${atOnce ? 'at once' : '$_releaseTurnsAtOnce at a time'} · $why',
+ );
+ for (final machineId in held) {
+ if (!_releaseQueue.contains(machineId)) _releaseQueue.add(machineId);
+ }
+ _releaseClock = Stopwatch()..start();
+ } else if (!atOnce || _releaseQueue.isEmpty || _disposed) {
+ return;
+ } else {
+ StartupTrace.mark(
+ 'launch: dialling the ${_releaseQueue.length} machine(s) still '
+ 'waiting their turn · $why',
+ );
+ }
+ if (!atOnce) {
+ _dialReleasedInTurn();
+ return;
+ }
+ final waiting = _releaseQueue.toList();
+ _releaseQueue.clear();
+ for (final timer in _releaseTurns.values) {
+ timer.cancel();
+ }
+ _releaseTurns.clear();
+ _releaseClock = null;
+ for (final machineId in waiting) {
+ _dialReleased(machineId);
+ }
+ }
+
+ /// Dial the next let-go machines while fewer than [_releaseTurnsAtOnce] are dialling.
+ ///
+ /// ⚠️ **Why a few at a time (owner, 2026-10-02).** Let go all at once, the six to nine other
+ /// machines of a large account each made a credential, a key mint and a signature, decrypted and
+ /// parsed an agent list, and wrote the machine cache — all on the UI thread, in the same second,
+ /// right after the terminal somebody had just opened came up. That second is the stutter in the
+ /// terminal at the start of every launch. A turn is over when the machine's list has been read
+ /// or its dial failed ([_endReleaseTurn]), or after [_releaseTurnLimit] whatever happens: a slow
+ /// machine never stops the next from dialling.
+ ///
+ /// What it costs: the last of ten machines dials a few seconds later than it did. Anything that
+ /// asks for a machine still waiting dials it on the spot — opening one of its agents ([_conn]),
+ /// Find ([reachAllMachines]), a pull to refresh ([retryMachines]).
+ void _dialReleasedInTurn() {
+ while (!_disposed &&
+ _releaseTurns.length < _releaseTurnsAtOnce &&
+ _releaseQueue.isNotEmpty) {
+ final machineId = _releaseQueue.removeAt(0);
+ if (!_dialReleased(machineId)) continue;
+ StartupTrace.mark(
+ 'launch: dialling ${_shortId(machineId)} · ${_releaseQueue.length} '
+ 'still waiting${_sinceRelease()}',
+ );
+ _releaseTurns[machineId] = Timer(
+ _releaseTurnLimit,
+ () => _endReleaseTurn(machineId, 'turn limit'),
+ );
+ }
+ if (_releaseQueue.isEmpty &&
+ _releaseTurns.isEmpty &&
+ _releaseClock != null) {
+ StartupTrace.mark('launch: every held machine dialled${_sinceRelease()}');
+ _releaseClock = null;
+ }
+ }
+
+ /// [machineId]'s turn is over — its list landed, its dial failed, or its time ran out ([why]) —
+ /// and the next machine may dial. Nothing for a machine that has no turn.
+ void _endReleaseTurn(String machineId, String why) {
+ final turn = _releaseTurns.remove(machineId);
+ if (turn == null) return;
+ turn.cancel();
+ StartupTrace.mark(
+ 'launch: ${_shortId(machineId)} turn over · $why${_sinceRelease()}',
+ );
+ _dialReleasedInTurn();
+ }
+
+ /// Dial one let-go machine. True when that started a dial; false for a machine gone from the
+ /// account, one it reports down, and one something else has dialled already.
+ bool _dialReleased(String machineId) {
+ final state = machineStates[machineId];
+ // Gone from the account since — `_refreshMachines` dropped it.
+ if (state == null) return false;
+ final listed = machines
+ .where((machine) => machine.machineId == machineId)
+ .firstOrNull;
+ // Down as the account last said: the launch skips those too ([_autoConnectAndLoadMachines]).
+ if (listed != null && _nodeOnlineFromStatus(listed.status) == false) {
+ return false;
+ }
+ final dialledAlready = _pool?[machineId] != null;
+ _connectMachine(state);
+ return !dialledAlready && _pool?[machineId] != null;
+ }
+
+ String _sinceRelease() {
+ final clock = _releaseClock;
+ return clock == null ? '' : ' +${clock.elapsedMilliseconds}ms';
+ }
+
- /// The first eight characters of a machine id — enough to tell an account's machines apart in
- /// a log line.
- static String _shortId(String machineId) =>
- machineId.length <= 8 ? machineId : machineId.substring(0, 8);
-
+ /// A state just made for a machine whose socket the app ALREADY holds — dialled before there was
+ /// a state to report to (`_warmStartMachines` dials the launch's machine ahead of the cache parse).
+ /// Whatever that socket said meanwhile went nowhere ([_onConnectionStatus] needs the state), so it
+ /// is said again here: a socket that is up replays its `connected`, which is what starts the agent
+ /// list, the sync timer and the rest; one still dialling is at least shown as dialling.
+ void _adoptConnection(MachineState state) {
+ final machineId = state.machine.machineId;
+ final connection = _pool?[machineId];
+ if (connection == null) return;
+ if (connection.isReady) {
+ _onConnectionStatus(machineId, ConnectionStatus.connected);
+ } else if (state.connectionStatus == ConnectionStatus.disconnected) {
+ state.connectionStatus = ConnectionStatus.connecting;
+ }
+ }
+
+ /// Drop the launch's hold without dialling anything — signing out, or the notifier going away.
+ void _forgetLaunchHold() {
+ _preDialled = null;
+ _launchMachineId = null;
+ _heldMachines.clear();
+ _heldMachinesTimer?.cancel();
+ _heldMachinesTimer = null;
+ _releaseQueue.clear();
+ for (final turn in _releaseTurns.values) {
+ turn.cancel();
+ }
+ _releaseTurns.clear();
+ _releaseClock = null;
+ }
+
+ /// Let the held machines go once [terminal] shows its first frame — the screen a launch is for
+ /// is up, and nothing on it is waiting any more. See [_launchMachineId].
+ void _releaseOnFirstFrame(TerminalSession terminal) {
+ void check() {
+ if (!terminal.hasRenderedFrame) return;
+ terminal.removeListener(check);
+ _releaseHeldMachines('first terminal live');
+ }
+
+ terminal.addListener(check);
+ }
+
+ /// The longest a launch's agent list waits for the terminal on screen — see
+ /// [_yieldToLaunchTerminal].
+ static const _launchListYield = Duration(milliseconds: 1500);
+
+ /// Let the terminal on screen answer before [machine]'s agent list is asked for — at launch only.
+ ///
+ /// ⚠️ **Why the list waits (owner, 2026-10-01).** The terminal a launch reopens and the machine's
+ /// agent list left on the same connection in the same instant, and the terminal came second: on
+ /// every launch measured (ten of ten) its `terminal_ready` arrived in the same second as the
+ /// list's reply, which took 1.1–3.0s for 134 agents. The machine builds that reply for every
+ /// agent at once, stopped ones included (`agents_list` in the CLI's `backendSocket.ts`), and the
+ /// one stream somebody was waiting to type into queued behind it.
+ ///
+ /// Nothing on screen needs the list first: a launch draws from last run's
+ /// ([MachineState.agentsFromCache]), which is also what limits this to a launch — a reconnect
+ /// already has a confirmed list, and asks at once as it always did. Over the moment the terminal
+ /// shows its first live frame or stops opening (failed, taken, gone), and after
+ /// [_launchListYield] whatever happens: the list never waits on a terminal that is not coming.
+ ///
+ /// What it costs: for up to that long, an agent deleted elsewhere since the last run is still
+ /// drawn (`_AgentGone` in `terminal_page.dart` needs the real list), and the list's news — a new
+ /// agent, a rename — arrives that much later.
+ Future<void> _yieldToLaunchTerminal(MachineState machine) async {
+ if (!machine.agentsFromCache) return;
+ final pane = focusedPane;
+ final terminal = pane?.session;
+ if (pane == null ||
+ terminal == null ||
+ pane.machineId != machine.machine.machineId) {
return;
}
- for (final terminal in targets) {
- if (terminal.streamId == clear.streamId) {
- await terminal.handleBinary(clear);
- }
- }
+ await _untilTerminalLive(terminal, _launchListYield);
}
- Future<bool> _sendTerminalBinary(
- String machineId,
- TerminalBinaryFrame frame,
+ /// Until [terminal] shows its first live frame or stops opening (failed, taken, gone) — and never
+ /// longer than [bound], so nothing waits on a terminal that is not coming.
+ Future<void> _untilTerminalLive(
+ TerminalSession terminal,
+ Duration bound,
) async {
- final encoded = encodeTerminalLocal(frame);
- if (encoded == null) return false;
- return _conn(machineId).sendTerminalBinary(encoded);
+ // `controlling` without a frame is a `terminal_ready` whose keyframe is on its way: still worth
+ // the wait, the screen is not live until it lands.
+ bool over() {
+ if (terminal.hasRenderedFrame) return true;
+ final status = terminal.status;
+ return status != TerminalSessionStatus.opening &&
+ status != TerminalSessionStatus.controlling;
+ }
+
+ if (over()) return;
+ final done = Completer<void>();
+ void check() {
+ if (!done.isCompleted && over()) done.complete();
+ }
+
+ // A session closed meanwhile never notifies again; this is what ends the wait then.
+ final timer = Timer(bound, () {
+ if (!done.isCompleted) done.complete();
+ });
+ terminal.addListener(check);
+ await done.future;
+ timer.cancel();
+ terminal.removeListener(check);
}
/// Start dialling last run's machines without waiting for `/api/machines`.
@@@ -4089,29 -3122,14 +4346,34 @@@
// from the cache are already on screen meanwhile. The warm start's job is
// to have the socket ALREADY OPEN when that happens, which is where its
// second and a half comes from; the request itself was never the part
- // worth racing. A machine with no key here reads the device log first
- // ([_connectAfterDeviceLog]).
- warmStates.add(state);
+ // worth racing.
+ //
+ // Except for a machine the launch holds back — see [_launchMachineId]. Its cached
+ // agents are on screen all the same; only the socket waits.
+ if (_heldForLaunch(machine.machineId)) {
+ _holdForLaunch(machine.machineId);
- } else {
++ } else if (machine.machineId == dialledEarly) {
++ // Its socket came up before this state existed — see `dialledEarly` above — and is taken
++ // now, before `dropUnclaimedDial` below closes it: not one to wait on the device log.
+ _connectMachine(state);
- // Its socket may have come up before this state existed — see `dialledEarly` above.
- if (machine.machineId == dialledEarly) _adoptConnection(state);
++ _adoptConnection(state);
++ } else {
++ // A machine with no key here reads the device log first ([_connectAfterDeviceLog]).
++ warmStates.add(state);
+ }
warmMachines.add(machine);
warmed++;
}
+ dropUnclaimedDial();
+ // The record's machine, which a cache from another write may not list: still on screen.
+ if (first != null &&
+ !warmMachines.any(
+ (machine) => machine.machineId == first!.machine.machineId,
+ )) {
+ warmMachines.insert(0, first.machine);
+ }
if (warmed == 0) return;
+ unawaited(_connectAfterDeviceLog(warmStates, load: false));
// ⚠️ Published to `machines` as well, because every screen indexes agents
// through THAT list (`agentIndex`, `filterableMachines`) rather than through
// `machineStates` — without this the warm start would have opened the
@@@ -7915,20 -6344,54 +8190,64 @@@
/// The app went into a pocket: stop the reads that only make sense in front
/// of somebody. The sockets are left to the OS, which suspends them anyway —
/// [handleAppResumed] is what puts both back.
+ ///
+ /// And write the machine cache now ([_keepMachineCache]): this is the last moment the app is sure
+ /// to run, since closing it from the app switcher starts by sending it here.
void handleAppPaused() {
_desk.pause();
+ _stopDeafPoll();
+ // The agents this run learned between lists, for the next launch — see [_keepMachineCache].
+ _keepMachineCache();
}
+ /// The app lost the foreground for a moment — the app switcher, a system sheet. Nothing stops;
+ /// only the machine cache is written ([_keepMachineCache]), because the switcher is where an app
+ /// is closed, and closing it there need not pass through [handleAppPaused] first.
+ void handleAppInactive() => _keepMachineCache();
+
+ /// How often a phone with no machine connected reads the machine list again. Every push
+ /// (`machines_changed`, `device_keys_changed`) reaches the phone over a machine's socket; with none
+ /// connected — the person signed in on the phone first and is now running `harness login` on their
+ /// computer — nothing tells it that computer joined.
+ @visibleForTesting
+ Duration deafMachineListInterval = const Duration(seconds: 20);
+
+ Timer? _deafMachineListTimer;
+ Future<void>? _machineReread;
+
+ void _startDeafPoll() {
+ if (_disposed || status != AppStatus.authenticated) return;
+ _deafMachineListTimer ??= Timer.periodic(
+ deafMachineListInterval,
+ (_) => _rereadMachinesWhileDeaf(),
+ );
+ }
+
+ void _stopDeafPoll() {
+ _deafMachineListTimer?.cancel();
+ _deafMachineListTimer = null;
+ }
+
+ /// A phone that hears nothing reads the machine list again: the computer the person is signing in on
+ /// right now appears, and the dial that follows reads the device log for its key first.
+ void _rereadMachinesWhileDeaf() {
+ if (_disposed || status != AppStatus.authenticated) return;
+ if (machineStates.values.any(
+ (m) => m.connectionStatus == ConnectionStatus.connected,
+ )) {
+ return;
+ }
+ _rereadMachines();
+ }
+
+ /// Read the machine list again because something other than the person asked; reads under way are
+ /// shared, and a failure is left to the next one.
+ void _rereadMachines() {
+ _machineReread ??= refreshMachines()
+ .catchError((Object _) {})
+ .whenComplete(() => _machineReread = null);
+ }
+
/// What the local CLI closing this machine's socket with [code] does to the
/// model — the `WsPool.onLocalFailure` path, without a socket.
@visibleForTesting
@@@ -7951,14 -6414,10 +8270,15 @@@
}
_channelControllers.clear();
_disposed = true;
+ // A sign-in page still up has nobody left to come back to: its listener goes.
+ if (signInProvider != null) viewer.login.cancel();
_closedHistory.clear();
+ _stopAccountTimers();
_stopAllOfflineRetries();
_stopAllAgentSyncTimers();
+ _forgetLaunchHold();
+ _machineCacheSaveTimer?.cancel();
+ _machineCacheSaveTimer = null;
_clearAllTurnActivity();
for (final pane in allPanes) {
pane.session?.removeListener(notifyListeners);
diff --cc mobile/lib/ws/ws_conn.dart
index 95a4753e5,477edb7ac..4bc4f71c1
--- a/mobile/lib/ws/ws_conn.dart
+++ b/mobile/lib/ws/ws_conn.dart
@@@ -310,16 -268,11 +310,18 @@@ class WsConn
queryParameters: {
...base.queryParameters,
'autonomousEnv': autonomousEnv,
+ // Counts this person as on the mobile app today (backend user_daily_client_presence).
+ 'client': 'mobile',
},
);
- final channel = dialing = (connectChannel ?? WebSocketChannel.connect)(
+ // ⚠️ **Dialled BEFORE the codec is awaited (owner, 2026-10-01).** The socket needs only the
+ // credential; the codec is not used until the first frame. Awaited first, its disk read and key
+ // mint (~65ms at launch) stood in front of a TCP + TLS + upgrade that could have been under way.
+ //
+ // ⚠️ But NOT made [_channel] until the codec is in place: a frame sent in between would go
+ // out with no codec to seal it — in the clear. Until then the socket is this method's alone,
+ // and closed here on every way out.
+ final channel = (connectChannel ?? WebSocketChannel.connect)(
uri,
protocols: [token],
);