Skip to content

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

feat(mobile): speed up launch for large accounts

tony7993ee0a7e47
diff --git a/mobile/lib/app_shell.dart b/mobile/lib/app_shell.dart
index 24a9bf18c..4cee0dc28 100644
--- a/mobile/lib/app_shell.dart
+++ b/mobile/lib/app_shell.dart
@@ -9,9 +9,11 @@ import 'viewer/viewer_services.dart';
import 'ws/terminal_transport_plugin.dart';
import 'shared/theme/app_theme.dart' as grid;
import 'shared/theme/appearance_prefs_store.dart';
+import 'core/machine_cache.dart';
import 'core/startup.dart';
import 'logging/app_log.dart';
import 'logging/install.dart';
+import 'logging/launch_frames.dart';
import 'logging/startup_trace.dart';
/// A screen the app puts up for one of its states — signed in, signed out, starting.
@@ -52,7 +54,13 @@ Future<void> startHarness({
// and its watchers, beside the appearance. Nothing on the phone reads a keymap
// — no key is ever matched against one — so the file a touchscreen could not
// have edited is not read either.
- await StartupTrace.time('settings.load', loadPersistedSettings);
+ // Beside the preferences, the machine the launch reopens — so the app can dial it before the
+ // first frame rather than after it (`MachineCache.preloadLaunchHint`). Here and not in
+ // [loadPersistedSettings], which tests call: this reads the real cache directory.
+ await Future.wait([
+ StartupTrace.time('settings.load', loadPersistedSettings),
+ StartupTrace.time('launchHint.read', MachineCache.preloadLaunchHint),
+ ]);
// ⚠️ **The app's state is made here, before the first frame, not by the first build that reads
// it (owner, 2026-10-01).** Its bootstrap starts the reads the launch's dial waits on
// (`AppNotifier.bootstrap`); made by `RootShell`'s build, they began only after MaterialApp's
@@ -77,6 +85,8 @@ Future<void> startHarness({
WidgetsBinding.instance.addPostFrameCallback(
(_) => StartupTrace.mark('firstFrame'),
);
+ // And the twenty seconds after it, frame by frame — whether the launch stuttered.
+ LaunchFrames.watch();
}
class HarnessApp extends StatelessWidget {
diff --git a/mobile/lib/core/last_opened_agent.dart b/mobile/lib/core/last_opened_agent.dart
index 88a6862d6..87ed9ad18 100644
--- a/mobile/lib/core/last_opened_agent.dart
+++ b/mobile/lib/core/last_opened_agent.dart
@@ -28,6 +28,13 @@ class LastOpenedAgent {
AgentRef? _value;
String? _tab;
+
+ /// The agent this record names right now, as far as this run knows — the last one [remember]ed,
+ /// or what the previous run left once a read has brought it in. Null when neither has happened.
+ /// For the machine cache's launch record (`MachineCache.save`), which is written for the machine
+ /// the NEXT launch reopens.
+ AgentRef? get current => _value ?? _readBack;
+ AgentRef? _readBack;
Future<void> _writes = Future.value();
Future<AgentRef?>? _read;
@@ -75,7 +82,9 @@ class LastOpenedAgent {
final agentId = decoded['agentId'];
if (machineId is! String || machineId.isEmpty) return null;
if (agentId is! String || agentId.isEmpty) return null;
- return (machineId: machineId, agentId: agentId);
+ final read = (machineId: machineId, agentId: agentId);
+ _readBack = read;
+ return read;
} catch (_) {
return null;
}
diff --git a/mobile/lib/core/machine_cache.dart b/mobile/lib/core/machine_cache.dart
index d8592bb3c..c408084de 100644
--- a/mobile/lib/core/machine_cache.dart
+++ b/mobile/lib/core/machine_cache.dart
@@ -1,6 +1,7 @@
import 'dart:convert';
import 'dart:isolate';
+import '../logging/app_log.dart';
import 'models.dart';
import 'snapshot_store.dart';
@@ -57,11 +58,72 @@ class CachedMachine {
}
class MachineCache {
- MachineCache({SnapshotStore? store})
- : _store = store ?? FileSnapshotStore('machines-cache');
+ /// [launchStore] defaults to a file only beside the default [store]: a caller that hands in its
+ /// own store (every test) gets an empty launch record in memory, and so the launch it always had.
+ MachineCache({SnapshotStore? store, SnapshotStore? launchStore})
+ : _store = store ?? FileSnapshotStore('machines-cache'),
+ _launchStore =
+ launchStore ??
+ (store == null
+ ? FileSnapshotStore('machines-launch')
+ : MemorySnapshotStore()),
+ // Only beside the real files: a test's cache has no hint, so its launch reads as before.
+ _hintStore = store == null ? FileSnapshotStore(_hintName) : null;
+
+ /// The launch hint: the launch record's machine id and nothing else — see [preloadLaunchHint].
+ static const _hintName = 'machines-launch-hint';
+ final SnapshotStore? _hintStore;
+
+ static String? _preloadedHint;
+ static bool _hintPreloaded = false;
+
+ /// Read the launch hint before the app's first frame — `startHarness` awaits this beside the
+ /// preferences, so it costs the launch nothing it was not already waiting for.
+ ///
+ /// ⚠️ **Why (owner, 2026-10-02).** The launch's own machine was dialled only once the launch
+ /// record had been read, and that read — like every other — finished only after the first frame,
+ /// because building that frame holds the UI isolate for ~400ms on a debug build: measured, the
+ /// dial went out at ~500ms with the file itself read in a few. The hint is a few dozen bytes,
+ /// read before the frame, and the app dials from it at once (`AppNotifier._preDialFromHint`).
+ /// It is written and cleared with the launch record, so it names the machine the record holds,
+ /// and only ever this account's — signing out clears it first. Never throws.
+ static Future<void> preloadLaunchHint() async {
+ if (_hintPreloaded) return;
+ _hintPreloaded = true;
+ try {
+ final raw = await FileSnapshotStore(_hintName).read();
+ if (raw == null || raw.isEmpty) return;
+ final decoded = jsonDecode(raw);
+ if (decoded is! Map || decoded['version'] != _version) return;
+ final machineId = decoded['machineId'];
+ if (machineId is String && machineId.isNotEmpty) {
+ _preloadedHint = machineId;
+ }
+ } on Object {
+ // No hint is a launch that dials once the record is read, as it did.
+ }
+ }
+
+ /// The machine [preloadLaunchHint] read, once — the launch that asks first takes it.
+ static String? takeLaunchHint() {
+ final hint = _preloadedHint;
+ _preloadedHint = null;
+ return hint;
+ }
final SnapshotStore _store;
+ /// The launch record: the one machine the next launch reopens, in a document of its own — see
+ /// [readLaunchRaw].
+ ///
+ /// ⚠️ **Why a second file (owner, 2026-10-02).** [_store] holds every agent of every machine,
+ /// and the launch could draw nothing until all of it was read and parsed: 382KB for 167 agents,
+ /// read in 0.5s and parsed in 0.76s on a debug Android build, and an account of seven to ten
+ /// machines of fifty sessions each is three times that. The terminal on screen needs ONE
+ /// machine's agents and capabilities. Written beside [_store], in the same write, so the two
+ /// never describe different runs for longer than a crash between them.
+ final SnapshotStore _launchStore;
+
/// The last agent list seen for each machine, as the daemon sent it, awaiting
/// the next [save].
///
@@ -98,9 +160,17 @@ class MachineCache {
/// Its own step so a launch can act on the text before paying for the parse: the machine to dial
/// first is known from the last-opened record, and the text says whether this account still had it
/// (`AppNotifier._warmStartMachines`). Never throws.
- Future<String?> readRaw() async {
+ Future<String?> readRaw() => _readFrom(_store);
+
+ /// The launch record's text, unparsed, or null when there is none — [parseLaunch] reads it.
+ Future<String?> readLaunchRaw() => _readFrom(_launchStore);
+
+ /// [store]'s text once every write already asked for has landed — a read made while a sign-out's
+ /// [clear] is queued would otherwise find the account that just left. Never throws.
+ Future<String?> _readFrom(SnapshotStore store) async {
try {
- final raw = await _store.read();
+ await _writes;
+ final raw = await store.read();
return raw == null || raw.isEmpty ? null : raw;
} on Object {
return null;
@@ -111,6 +181,31 @@ class MachineCache {
/// a small document does to parse.
static const _parseOffThreadFrom = 64 * 1024;
+ /// The machine in the launch record [raw], when it is [machineId] — reachable over the relay, and
+ /// with [agentId] among its agents. Null for anything else, and nothing is kept from it then.
+ ///
+ /// ⚠️ **The agent has to be there, not just the machine.** The home screen opens on that agent,
+ /// and with only this machine's agents to choose from it could not tell "deleted since" from
+ /// "on a machine not read yet" — its fallback would pick from a partial list. Without the agent,
+ /// the launch waits for the whole cache, as it always did. Never throws.
+ Future<CachedMachine?> parseLaunch(
+ String raw, {
+ required String machineId,
+ required String agentId,
+ }) async {
+ final parsed = await _parseOffThreadIfLarge(raw);
+ if (parsed.length != 1) return null;
+ final entry = parsed.single;
+ final cached = entry.cached;
+ if (cached.machine.machineId != machineId ||
+ cached.machine.authMode != MachineAuthMode.remote ||
+ !cached.agents.any((agent) => agent.id == agentId)) {
+ return null;
+ }
+ _keep(parsed);
+ return cached;
+ }
+
/// [raw] as the machines it lists. Never throws.
///
/// ⚠️ **Parsed off the UI isolate once the file is large (owner, 2026-10-01).** Every agent of
@@ -121,27 +216,38 @@ class MachineCache {
/// isolate, the work still takes as long, but nothing on screen waits for it; a small file is
/// parsed in place, as before, since an isolate's start-up would cost more than it saves.
Future<List<CachedMachine>> parse(String raw) async {
- List<_ParsedMachine> parsed;
- if (raw.length < _parseOffThreadFrom) {
- parsed = _parseDocument(raw);
- } else {
- try {
- parsed = await Isolate.run(() => _parseDocument(raw));
- } on Object {
- // An isolate that would not start is a parse done here instead, never a cache lost.
- parsed = _parseDocument(raw);
- }
+ final parsed = await _parseOffThreadIfLarge(raw);
+ _keep(parsed);
+ return [for (final entry in parsed) entry.cached];
+ }
+
+ static Future<List<_ParsedMachine>> _parseOffThreadIfLarge(String raw) async {
+ if (raw.length < _parseOffThreadFrom) return _parseDocument(raw);
+ try {
+ return await Isolate.run(() => _parseDocument(raw));
+ } on Object {
+ // An isolate that would not start is a parse done here instead, never a cache lost.
+ return _parseDocument(raw);
}
- // Kept for the next [save], on this isolate — see [_agents] and [_capabilities].
+ }
+
+ /// [parsed], kept for the next [save], on this isolate — see [_agents] and [_capabilities].
+ ///
+ /// ⚠️ **Only where this run has learned nothing newer.** A parse finishes whenever it finishes,
+ /// and on a large account a machine can answer its list before it does — the launch record lets
+ /// the launch's machine dial ahead of the rest of the cache. Written over, that fresh list would
+ /// go back to last run's, and the next save would write the old one out.
+ void _keep(List<_ParsedMachine> parsed) {
for (final entry in parsed) {
final machineId = entry.cached.machine.machineId;
- _agents[machineId] = entry.rawAgents;
+ _agents.putIfAbsent(machineId, () => entry.rawAgents);
// Carried forward so a launch that reads the cache and is closed
// before any machine answers still writes back what it knew.
final capabilities = entry.cached.capabilities;
- if (capabilities != null) _capabilities[machineId] = capabilities;
+ if (capabilities != null) {
+ _capabilities.putIfAbsent(machineId, () => capabilities);
+ }
}
- return [for (final entry in parsed) entry.cached];
}
/// The document in [raw], parsed — pure, so it can run on any isolate ([parse]). Empty for a
@@ -296,39 +402,139 @@ class MachineCache {
/// Never throws and is never worth awaiting on a path a person is waiting on:
/// a cache that failed to save costs the NEXT launch a few hundred
/// milliseconds and costs this one nothing.
+ ///
+ /// [launchMachineId] is the machine the next launch reopens — what the launch record holds
+ /// ([readLaunchRaw]). Absent, or not among the machines saved, the record is cleared, so it never
+ /// names a machine the cache beside it does not.
Future<void> save(
Iterable<Machine> machines, {
required bool Function(Machine) isOnline,
+ String? launchMachineId,
}) {
- // Encoded now, on the caller's turn, so the document written is the machine
+ // Built now, on the caller's turn, so the document written is the machine
// list as it was when the save was ASKED for rather than whatever the list
- // has become by the time the queue reaches it.
- final payload = jsonEncode({
- 'version': _version,
- 'machines': [
- for (final machine in machines.where(isOnline))
- {
- 'machineId': machine.machineId,
- 'computerId': machine.computerId,
- 'authMode': machine.authMode.name,
- 'engine': machine.engine,
- 'name': machine.name,
- 'hostname': machine.hostname,
- // Written as the status that got it in here. The reader treats
- // every cached machine as a candidate to dial, and the fetch
- // replaces this with the truth within the second.
- 'status': machine.status,
- // The daemon's own agent JSON, verbatim — see the class comment.
- // Absent where this run never listed that machine's agents, which
- // reads back as a machine with no cached agents.
- 'agents': ?_agents[machine.machineId],
- 'capabilities': ?_capabilities[machine.machineId],
- },
- ],
- });
- // What was remembered is in [payload] now, whichever write lands last.
+ // has become by the time the queue reaches it. Only built — the agents in
+ // it are the lists this class holds, which it replaces and never edits
+ // (see [rememberAgent]), so encoding them later writes the same thing.
+ var agentCount = 0;
+ Map<String, Object?>? launchEntry;
+ final entries = <Map<String, Object?>>[];
+ for (final machine in machines.where(isOnline)) {
+ final agents = _agents[machine.machineId];
+ agentCount += agents?.length ?? 0;
+ final entry = <String, Object?>{
+ 'machineId': machine.machineId,
+ 'computerId': machine.computerId,
+ 'authMode': machine.authMode.name,
+ 'engine': machine.engine,
+ 'name': machine.name,
+ 'hostname': machine.hostname,
+ // Written as the status that got it in here. The reader treats
+ // every cached machine as a candidate to dial, and the fetch
+ // replaces this with the truth within the second.
+ 'status': machine.status,
+ // The daemon's own agent JSON, verbatim — see the class comment.
+ // Absent where this run never listed that machine's agents, which
+ // reads back as a machine with no cached agents.
+ 'agents': ?agents,
+ 'capabilities': ?_capabilities[machine.machineId],
+ };
+ entries.add(entry);
+ if (machine.machineId == launchMachineId) launchEntry = entry;
+ }
+ final document = {'version': _version, 'machines': entries};
+ final launchDocument = launchEntry == null
+ ? null
+ : {
+ 'version': _version,
+ 'machines': [launchEntry],
+ };
+ final launchAgents = (launchEntry?['agents'] as List?)?.length ?? 0;
+ // What was remembered is in [document] now, whichever write lands last.
_unsaved = false;
- return _queue(() => _store.write(payload));
+ _launchAskedFor = (launchMachineId,);
+ final generation = ++_generation;
+ return _queue(() async {
+ // ⚠️ **Only the newest save is written (owner, 2026-10-02).** Each machine's list asks for
+ // one as it lands, and on a launch that lets several machines go at once that was a whole
+ // encode of every agent on the account per machine, each bigger than the last. A save asked
+ // for after this one holds everything this one does, and is in the queue behind it.
+ if (generation != _generation) {
+ _superseded++;
+ return;
+ }
+ final clock = Stopwatch()..start();
+ final text = await _encode(document, agentCount);
+ final encodeMs = clock.elapsedMilliseconds;
+ if (generation != _generation) {
+ _superseded++;
+ return;
+ }
+ await _store.write(text);
+ final hint = _hintStore;
+ if (launchDocument == null) {
+ // The hint first: it is what a launch acts on before anything else is read.
+ await hint?.clear();
+ await _launchStore.clear();
+ } else {
+ await _launchStore.write(await _encode(launchDocument, launchAgents));
+ // After the record it names, so a crash between the two leaves an older hint, which the
+ // launch checks against the agent it reopens — never a hint ahead of its record.
+ await hint?.write(
+ jsonEncode({'version': _version, 'machineId': launchMachineId}),
+ );
+ }
+ final skipped = _superseded;
+ _superseded = 0;
+ appLog.info(
+ 'cache',
+ 'machines-cache written · ${entries.length} machine(s), '
+ '$agentCount agent(s), ${(text.length / 1024).round()}KB · '
+ 'encode ${encodeMs}ms '
+ '${agentCount >= _encodeOffThreadFrom ? 'off-thread' : 'inline'} · '
+ 'launch ${launchDocument == null ? 'none' : '$launchAgents agent(s)'}'
+ '${skipped > 0 ? ' · $skipped older save(s) skipped' : ''} · '
+ 'total ${clock.elapsedMilliseconds}ms',
+ );
+ });
+ }
+
+ /// Whether the launch record was last written for some machine other than [launchMachineId] —
+ /// or not written at all this run. What a save made only to keep the file current asks
+ /// (`AppNotifier`'s background write) beside [hasUnsaved]: a person who moved to another
+ /// machine's agent changed nothing in any list, and the next launch would still find the
+ /// record for the machine before.
+ bool launchRecordStale(String? launchMachineId) {
+ final asked = _launchAskedFor;
+ return asked == null
+ ? launchMachineId != null
+ : asked.$1 != launchMachineId;
+ }
+
+ /// The launch machine the last [save] was asked to record, null inside when it was asked for
+ /// none; null when nothing was saved this run.
+ (String?,)? _launchAskedFor;
+
+ /// Bumped by every [save] and [clear]: a queued save that finds it moved on has been replaced.
+ int _generation = 0;
+
+ /// Saves dropped for a newer one since the last write — for its log line.
+ int _superseded = 0;
+
+ /// From this many agents a document is encoded on a background isolate. Below it, spawning one
+ /// costs more than the encode.
+ static const _encodeOffThreadFrom = 40;
+
+ /// [document] as JSON — off the UI isolate when it holds [agentCount] agents or more, since
+ /// the whole account's agents encoded on it were a stall the screen could see.
+ static Future<String> _encode(Object document, int agentCount) async {
+ if (agentCount < _encodeOffThreadFrom) return jsonEncode(document);
+ try {
+ return await Isolate.run(() => jsonEncode(document));
+ } on Object {
+ // An isolate that would not start is an encode done here instead, never a cache lost.
+ return jsonEncode(document);
+ }
}
/// Forget everything — what signing out does, so the next account does not
@@ -337,7 +543,16 @@ class MachineCache {
_agents.clear();
_capabilities.clear();
_unsaved = false;
- return _queue(_store.clear);
+ _launchAskedFor = null;
+ // A save still waiting its turn was the account that is leaving.
+ _generation++;
+ // The hint and the launch record first: they are what a launch acts on before anything else.
+ _preloadedHint = null;
+ return _queue(() async {
+ await _hintStore?.clear();
+ await _launchStore.clear();
+ await _store.clear();
+ });
}
/// Run [write] after every write already asked for, swallowing its failure.
diff --git a/mobile/lib/e2ee/envelope.dart b/mobile/lib/e2ee/envelope.dart
index 4fb9d9213..f620b7301 100644
--- a/mobile/lib/e2ee/envelope.dart
+++ b/mobile/lib/e2ee/envelope.dart
@@ -1,6 +1,8 @@
import 'dart:convert';
+import 'dart:isolate';
import 'dart:typed_data';
+import '../core/test_run.dart';
import 'bytes.dart';
import 'primitives.dart';
@@ -173,6 +175,37 @@ Map<String, dynamic>? unwrapPayload(
return clear == null ? null : jsonObjectOf(clear);
}
+/// From this many characters of `ct` an envelope is opened off the UI isolate ([unwrapPayloadOffThread]).
+/// Below it — every event, every small reply — spawning an isolate costs more than the open.
+const int unwrapOffThreadFrom = 48 * 1024;
+
+/// Whether [env]'s ciphertext is large enough to open off the UI isolate.
+bool opensOffThread(Object? env) {
+ if (kUnderTest || env is! Map) return false;
+ final ct = env['ct'];
+ return ct is String && ct.length >= unwrapOffThreadFrom;
+}
+
+/// [unwrapPayload] on a background isolate: base64, ChaCha20-Poly1305 and the JSON of a large
+/// payload — a machine's whole agent list, a transcript, a file — are pure Dart, and done on the UI
+/// isolate they stalled the screen for as long as they took. A pure function of its arguments, so
+/// the isolate answers exactly what this one would; one that will not start is the work done here.
+Future<Map<String, dynamic>?> unwrapPayloadOffThread(
+ List<int> key,
+ Map<String, dynamic> env,
+ String frameType,
+ String? dbSessionId,
+) async {
+ final keyBytes = Uint8List.fromList(key);
+ try {
+ return await Isolate.run(
+ () => unwrapPayload(keyBytes, env, frameType, dbSessionId),
+ );
+ } on Object {
+ return unwrapPayload(key, env, frameType, dbSessionId);
+ }
+}
+
bool isWrapped(Object? payload) =>
payload is Map && payload.containsKey('__e2e');
diff --git a/mobile/lib/e2ee/keys.dart b/mobile/lib/e2ee/keys.dart
index 63559c859..ef8d23da7 100644
--- a/mobile/lib/e2ee/keys.dart
+++ b/mobile/lib/e2ee/keys.dart
@@ -1,8 +1,10 @@
+import 'dart:isolate';
import 'dart:typed_data';
import 'package:cryptography/cryptography.dart';
import 'package:cryptography/dart.dart';
+import '../core/test_run.dart';
import 'bytes.dart';
import 'primitives.dart';
@@ -79,9 +81,26 @@ String fingerprint(List<int> pub) {
class Ephemeral {
Ephemeral._(this._keyPair, this.pub);
+ /// The key [_privateBytes] and [pub] describe, as [generate] made it on another isolate —
+ /// the same bytes, public key and type in the same [SimpleKeyPairData], so nothing derived from
+ /// it can differ.
+ Ephemeral._fromParts(Uint8List privateBytes, Uint8List pub)
+ : this._(
+ SimpleKeyPairData(
+ privateBytes,
+ publicKey: SimplePublicKey(pub, type: KeyPairType.x25519),
+ type: KeyPairType.x25519,
+ ),
+ pub,
+ );
+
final SimpleKeyPairData _keyPair;
final Uint8List pub;
+ /// The private key as plain bytes — what crosses to a background isolate, where
+ /// [Ephemeral._fromParts] puts it back together.
+ Uint8List get _privateBytes => Uint8List.fromList(_keyPair.bytes);
+
static Future<Ephemeral> generate([Rng rng = secureRandomBytes]) async {
final keyPair =
await _x25519.newKeyPairFromSeed(rng(32)) as SimpleKeyPairData;
@@ -142,3 +161,110 @@ Future<bool> welcomeVerify(
lvCat(['e2e-welcome-v1', machineId, webEphPub, adapterEphPub]),
sig,
);
+
+// ── the handshake, off the UI isolate ─────────────────────────────────────────────────────────────
+//
+// ⚠️ **Why (owner, 2026-10-02).** Ed25519 and X25519 are pure Dart here, and each connection
+// signs a hello and verifies a welcome — measured at 70–740ms and ~390ms on a debug Android build,
+// on the thread drawing the screen. A launch lets six to nine machines dial once the terminal on
+// screen is up, so that was a stutter in it. Each step below runs on a background isolate and
+// hands back plain bytes; only the bytes cross, and the objects are rebuilt from them exactly as
+// they were made. An isolate that will not start is the same work done here, never a failure;
+// under `flutter test`, whose fake clocks never deliver an isolate's answer, it is always here.
+
+/// An ephemeral key for one connection to [machineId], and [identity]'s hello signature over it
+/// ([helloSig]) — minted on a background isolate.
+Future<({Ephemeral eph, Uint8List sig})> mintHello(
+ E2eeIdentity identity,
+ String machineId,
+) async {
+ if (!kUnderTest) {
+ final seed = identity.seed;
+ final pub = identity.pub;
+ try {
+ final minted = await Isolate.run(
+ () => _mintHelloParts(seed, pub, machineId),
+ );
+ return (
+ eph: Ephemeral._fromParts(minted.privateBytes, minted.pub),
+ sig: minted.sig,
+ );
+ } on Object {
+ // Done here instead, below.
+ }
+ }
+ final eph = await Ephemeral.generate();
+ return (eph: eph, sig: await helloSig(identity, machineId, eph.pub));
+}
+
+Future<({Uint8List privateBytes, Uint8List pub, Uint8List sig})>
+_mintHelloParts(Uint8List seed, Uint8List pub, String machineId) async {
+ final eph = await Ephemeral.generate();
+ final sig = await helloSig(E2eeIdentity._(seed, pub), machineId, eph.pub);
+ return (privateBytes: eph._privateBytes, pub: eph.pub, sig: sig);
+}
+
+/// What a machine's `e2e_welcome` gives a session once its signature holds: the pairwise keys
+/// ([sessionKeys]), and its sealed `enc` opened under `s2c` — null when it does not open.
+typedef OpenedWelcome = ({Uint8List c2s, Uint8List s2c, Uint8List? initial});
+
+/// [welcomeVerify], [sessionKeys] and the welcome's `enc` opened — on a background isolate. Null
+/// when the signature does not hold, as [welcomeVerify]'s false. Throws what they throw (a key of
+/// the wrong shape is an [ArgumentError]), for the caller to take as a welcome that is no good.
+Future<OpenedWelcome?> openWelcome({
+ required Ephemeral eph,
+ required List<int> peerPub,
+ required String machineId,
+ required List<int> adapterEphPub,
+ required List<int> sig,
+ required List<int> enc,
+}) async {
+ if (!kUnderTest) {
+ final privateBytes = eph._privateBytes;
+ final ephPub = eph.pub;
+ final peer = Uint8List.fromList(peerPub);
+ final adapter = Uint8List.fromList(adapterEphPub);
+ final signature = Uint8List.fromList(sig);
+ final sealed = Uint8List.fromList(enc);
+ try {
+ return await Isolate.run(
+ () => _openWelcome(
+ Ephemeral._fromParts(privateBytes, ephPub),
+ peer,
+ machineId,
+ adapter,
+ signature,
+ sealed,
+ ),
+ );
+ } on Object {
+ // Done here instead, below — which throws again if the welcome itself was the problem.
+ }
+ }
+ return _openWelcome(eph, peerPub, machineId, adapterEphPub, sig, enc);
+}
+
+Future<OpenedWelcome?> _openWelcome(
+ Ephemeral eph,
+ List<int> peerPub,
+ String machineId,
+ List<int> adapterEphPub,
+ List<int> sig,
+ List<int> enc,
+) async {
+ if (!await welcomeVerify(peerPub, machineId, eph.pub, adapterEphPub, sig)) {
+ return null;
+ }
+ final keys = sessionKeys(
+ eph,
+ adapterEphPub,
+ machineId,
+ eph.pub,
+ adapterEphPub,
+ );
+ return (
+ c2s: keys.c2s,
+ s2c: keys.s2c,
+ initial: aeadOpen(keys.s2c, 0, utf8Bytes('e2e-welcome'), enc),
+ );
+}
diff --git a/mobile/lib/e2ee/relay_session_crypto.dart b/mobile/lib/e2ee/relay_session_crypto.dart
index 2bfeea27d..7cc18d55b 100644
--- a/mobile/lib/e2ee/relay_session_crypto.dart
+++ b/mobile/lib/e2ee/relay_session_crypto.dart
@@ -33,13 +33,23 @@ class RelaySessionCrypto {
required List<int> peerPub,
Ephemeral? ephemeral,
}) async {
- final eph = ephemeral ?? await Ephemeral.generate();
+ if (ephemeral != null) {
+ return RelaySessionCrypto._(
+ machineId,
+ identity,
+ Uint8List.fromList(peerPub),
+ ephemeral,
+ await helloSig(identity, machineId, ephemeral.pub),
+ );
+ }
+ // The key and its signature on a background isolate — see [mintHello].
+ final minted = await mintHello(identity, machineId);
return RelaySessionCrypto._(
machineId,
identity,
Uint8List.fromList(peerPub),
- eph,
- await helloSig(identity, machineId, eph.pub),
+ minted.eph,
+ minted.sig,
);
}
@@ -96,11 +106,19 @@ class RelaySessionCrypto {
final sig = _bytesField(payload, 'sig');
final enc = _bytesField(payload, 'enc');
if (adapterEphPub == null || sig == null || enc == null) return false;
- if (!await welcomeVerify(_peerPub, machineId, _eph.pub, adapterEphPub, sig)) {
- return false;
- }
- final keys = sessionKeys(_eph, adapterEphPub, machineId, _eph.pub, adapterEphPub);
- final opened = aeadOpen(keys.s2c, 0, utf8Bytes('e2e-welcome'), enc);
+ // Verified, keyed and opened on a background isolate — see [openWelcome].
+ final keys = await openWelcome(
+ eph: _eph,
+ peerPub: _peerPub,
+ machineId: machineId,
+ adapterEphPub: adapterEphPub,
+ sig: sig,
+ enc: enc,
+ );
+ if (keys == null) return false;
+ // Still the one welcome: nothing else can have made the session while that was away.
+ if (ready) return false;
+ final opened = keys.initial;
final initial = opened == null ? null : jsonObjectOf(opened);
final groupKey = initial?['groupKey'], epoch = initial?['epoch'];
if (groupKey is! String || groupKey.isEmpty || epoch is! String || epoch.isEmpty) {
@@ -192,6 +210,48 @@ class RelaySessionCrypto {
return {...frame, 'payload': clear};
}
+ /// [unwrapIncoming], with a large envelope opened on a background isolate
+ /// ([unwrapPayloadOffThread]) — a machine's agent list, a transcript. Anything smaller is
+ /// [unwrapIncoming] itself.
+ ///
+ /// ⚠️ **The replay window is checked before and again after.** Before, so a stale or replayed
+ /// frame is not worth an isolate; after, because only an opened frame may be committed. Frames
+ /// reach this one at a time (`WsConn`'s inbound chain awaits each), so nothing else moves the
+ /// window or the epoch in between — the second check is a guard, not a race being won.
+ Future<Map<String, dynamic>?> unwrapIncomingOffThread(
+ Map<String, dynamic> frame,
+ ) async {
+ final payload = frame['payload'];
+ if (payload is! Map || !isWrapped(payload)) return frame;
+ final env = payload['__e2e'], type = frame['type'];
+ if (!opensOffThread(env)) return unwrapIncoming(frame);
+ if (env is! Map<String, dynamic> || type is! String) return null;
+ final n = env['n'];
+ if (n is! int) return null;
+ final dbSessionId = frame['dbSessionId'] as String?;
+ if (env['k'] == 'g') {
+ final groupKey = _groupKey, epoch = env['epoch'];
+ if (groupKey == null || epoch != _epoch) return null;
+ if (n <= (_groupRecv[_epoch] ?? -1)) return null;
+ final clear = await unwrapPayloadOffThread(
+ groupKey,
+ env,
+ type,
+ dbSessionId,
+ );
+ if (clear == null || epoch != _epoch) return null;
+ if (n <= (_groupRecv[_epoch] ?? -1)) return null;
+ _groupRecv[_epoch] = n;
+ return {...frame, 'payload': clear};
+ }
+ final s2c = _s2c;
+ if (s2c == null || !_s2cRecv.allows(n)) return null;
+ final clear = await unwrapPayloadOffThread(s2c, env, type, dbSessionId);
+ if (clear == null || !_s2cRecv.allows(n)) return null;
+ _s2cRecv.commit(n);
+ return {...frame, 'payload': clear};
+ }
+
Uint8List? encryptTerminal(TerminalBinaryFrame frame) {
final key = _terminalC2s;
if (key == null) return null;
diff --git a/mobile/lib/logging/launch_frames.dart b/mobile/lib/logging/launch_frames.dart
new file mode 100644
index 000000000..da10d8710
--- /dev/null
+++ b/mobile/lib/logging/launch_frames.dart
@@ -0,0 +1,91 @@
+import 'dart:async';
+import 'dart:io' show Platform;
+import 'dart:ui' show FramePhase, FrameTiming;
+
+import 'package:flutter/scheduler.dart';
+
+import 'app_log.dart';
+
+/// The launch's frames, timed for its first [_span] and written as one `startup frames` line —
+/// whether the screen held still while the machines behind it were dialling.
+///
+/// ⚠️ **Why (owner, 2026-10-02).** A large account dials six to nine machines once the terminal
+/// on screen is up, each with a key mint, a decrypt, an agent list to parse and a cache to write,
+/// all on the UI thread. Whether that reads as a stutter is a question about frames, and the
+/// startup timeline (`startup_trace.dart`) only says when each step ran. Bucketed by two seconds
+/// from the first frame, so a burst lines up with the `launch: dialling …` marks around it.
+///
+/// ```
+/// startup frames from the first · 0-2s 61 (2 slow, worst build 31ms raster 9ms) · 2-4s 58 (0 slow…)
+/// ```
+///
+/// A frame is drawn only when something changed: a bucket with few frames is a still screen,
+/// not a slow one. Off under `flutter test`, whose widget trees do not outlive the timer.
+abstract final class LaunchFrames {
+ static const _span = Duration(seconds: 20);
+ static const _bucket = Duration(seconds: 2);
+
+ /// A frame slower than this to build or to raster is a dropped one at 60 Hz.
+ static const _frameBudget = Duration(microseconds: 16667);
+
+ static bool _watching = false;
+
+ /// Start timing; once per process.
+ static void watch() {
+ if (_watching || Platform.environment.containsKey('FLUTTER_TEST')) return;
+ _watching = true;
+ final buckets = <int, _Bucket>{};
+ int? firstVsync;
+ void onTimings(List<FrameTiming> timings) {
+ for (final timing in timings) {
+ final vsync = timing.timestampInMicroseconds(FramePhase.vsyncStart);
+ final origin = firstVsync ??= vsync;
+ final at = vsync - origin;
+ if (at > _span.inMicroseconds) continue;
+ buckets
+ .putIfAbsent(at ~/ _bucket.inMicroseconds, _Bucket.new)
+ .add(timing);
+ }
+ }
+
+ SchedulerBinding.instance.addTimingsCallback(onTimings);
+ // The engine reports timings in batches; a little past the span lets the last one in.
+ Timer(_span + const Duration(seconds: 2), () {
+ SchedulerBinding.instance.removeTimingsCallback(onTimings);
+ final seconds = _bucket.inSeconds;
+ final parts = [
+ for (final index in buckets.keys.toList()..sort())
+ '${index * seconds}-${(index + 1) * seconds}s ${buckets[index]}',
+ ];
+ appLog.info(
+ 'startup',
+ 'frames from the first · '
+ '${parts.isEmpty ? 'none' : parts.join(' · ')}',
+ );
+ });
+ }
+}
+
+class _Bucket {
+ int frames = 0;
+ int slow = 0;
+ Duration worstBuild = Duration.zero;
+ Duration worstRaster = Duration.zero;
+
+ void add(FrameTiming timing) {
+ frames++;
+ final build = timing.buildDuration;
+ final raster = timing.rasterDuration;
+ if (build > LaunchFrames._frameBudget ||
+ raster > LaunchFrames._frameBudget) {
+ slow++;
+ }
+ if (build > worstBuild) worstBuild = build;
+ if (raster > worstRaster) worstRaster = raster;
+ }
+
+ @override
+ String toString() =>
+ '$frames ($slow slow, worst build ${worstBuild.inMilliseconds}ms '
+ 'raster ${worstRaster.inMilliseconds}ms)';
+}
diff --git a/mobile/lib/phone/agent_index.dart b/mobile/lib/phone/agent_index.dart
index 982ad6611..0d450d4ab 100644
--- a/mobile/lib/phone/agent_index.dart
+++ b/mobile/lib/phone/agent_index.dart
@@ -1,3 +1,5 @@
+import 'dart:typed_data';
+
import 'package:collection/collection.dart' show compareNatural;
import 'package:harness_mobile/core/models.dart';
import 'package:harness_mobile/state/app_state.dart';
@@ -62,17 +64,79 @@ class AgentEntry {
/// [phoneMachineListsAgents]: an offline machine's agent list is whatever was last seen there, and
/// drawing it beside live ones would offer rows that cannot be opened. Those machines are reachable
/// on the Machines tab instead, which is where the thing to do about them lives.
+///
+/// ⚠️ **The same list comes back while nothing it was built from has changed (owner, 2026-10-02).**
+/// Every screen on a phone reads this in its build, several times over — the terminal on screen
+/// three times — and each of those rebuilds on every change anywhere in the app. On an account of
+/// seven to ten machines with fifty sessions each that was hundreds of entries made, and sorted by
+/// [visibleAgents], per read, per rebuild. What it is built from is checked machine by machine —
+/// the machine, its state, whether it lists, and the list object itself, which the app replaces
+/// rather than edits whenever an agent changes — so the check is as long as the machine list, not
+/// as the agents. An [AgentEntry] reads waiting and working live from its machine's state, so a
+/// kept entry is never stale on those.
+///
+/// Read-only: callers walk it or build from it, and a list shared between them must not be edited.
List<AgentEntry> agentIndex(AppNotifier notifier) {
+ final memo = _indexMemo[notifier];
+ if (memo != null && memo.stillFor(notifier)) return memo.entries;
+ final sources = <_IndexSource>[];
final entries = <AgentEntry>[];
for (final machine in notifier.machines) {
final state = notifier.stateOf(machine.machineId);
- if (state == null) continue;
- if (!phoneMachineListsAgents(state)) continue;
+ final lists = state != null && phoneMachineListsAgents(state);
+ sources.add(_IndexSource(machine, state, lists ? state.agents : null));
+ if (!lists) continue;
for (final agent in state.agents) {
entries.add(AgentEntry(machine: state, agent: agent));
}
}
- return entries;
+ final built = List<AgentEntry>.unmodifiable(entries);
+ _indexMemo[notifier] = _IndexMemo(sources, built);
+ return built;
+}
+
+/// What [agentIndex] last built for a notifier, kept on the notifier itself so it goes with it.
+final _indexMemo = Expando<_IndexMemo>('agentIndex');
+
+/// One machine as [agentIndex] read it: the machine, its state, and the agent list it drew from
+/// that state — null when the machine did not list.
+class _IndexSource {
+ _IndexSource(this.machine, this.state, this.agents)
+ : agentCount = agents?.length ?? 0;
+
+ final Machine machine;
+ final MachineState? state;
+ final List<Agent>? agents;
+
+ /// The list's length when it was read — a list edited in place, which the app does not do,
+ /// would keep its identity and still be caught by the length most of the time.
+ final int agentCount;
+}
+
+class _IndexMemo {
+ _IndexMemo(this.sources, this.entries);
+
+ final List<_IndexSource> sources;
+ final List<AgentEntry> entries;
+
+ /// Whether [notifier] would build exactly [entries] again: the same machines, in the same order,
+ /// each with the same state, listing or not as before, from the same list of agents.
+ bool stillFor(AppNotifier notifier) {
+ final machines = notifier.machines;
+ if (machines.length != sources.length) return false;
+ for (var i = 0; i < sources.length; i++) {
+ final source = sources[i];
+ final machine = machines[i];
+ if (!identical(machine, source.machine)) return false;
+ final state = notifier.stateOf(machine.machineId);
+ if (!identical(state, source.state)) return false;
+ final lists = state != null && phoneMachineListsAgents(state);
+ final agents = lists ? state.agents : null;
+ if (!identical(agents, source.agents)) return false;
+ if ((agents?.length ?? 0) != source.agentCount) return false;
+ }
+ return true;
+ }
}
/// The agents waiting on an answer, across every machine.
@@ -173,10 +237,42 @@ List<T> _stableSorted<T>(Iterable<T> items, int Function(T a, T b) compare) {
/// along it, so it has to be built in ONE place: a page computing "the next agent" from a slightly
/// different order than the list it was opened from would skip an agent, or hand back the one just
/// left, and nothing on screen would explain why.
-List<AgentEntry> visibleAgents(List<AgentEntry> entries) => [
- ...waitingAgents(entries),
- ...otherAgents(entries),
-];
+///
+/// Kept per [entries] list, and handed back again while every entry still waits, works and opens
+/// as it did — the only things the order reads. [agentIndex] returns the same list while nothing
+/// under it changed, so on a rebuild that changed nothing this is one pass over the entries
+/// instead of a sort of them. Read-only, like [agentIndex]'s.
+List<AgentEntry> visibleAgents(List<AgentEntry> entries) {
+ final flags = Uint8List(entries.length);
+ for (var i = 0; i < entries.length; i++) {
+ final entry = entries[i];
+ flags[i] =
+ (entry.isWaiting ? 1 : 0) |
+ (entry.isWorking ? 2 : 0) |
+ (entry.isOpenable ? 4 : 0);
+ }
+ final memo = _visibleMemo[entries];
+ if (memo != null && _sameFlags(memo.flags, flags)) return memo.visible;
+ final visible = List<AgentEntry>.unmodifiable([
+ ...waitingAgents(entries),
+ ...otherAgents(entries),
+ ]);
+ _visibleMemo[entries] = (flags: flags, visible: visible);
+ return visible;
+}
+
+/// What [visibleAgents] last made of an entries list, with the flags it was ordered by.
+final _visibleMemo = Expando<({Uint8List flags, List<AgentEntry> visible})>(
+ 'visibleAgents',
+);
+
+bool _sameFlags(Uint8List a, Uint8List b) {
+ if (a.length != b.length) return false;
+ for (var i = 0; i < a.length; i++) {
+ if (a[i] != b[i]) return false;
+ }
+ return true;
+}
/// The machines the filter chips offer, in the order they are drawn.
///
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 186ca678a..4ffb653d2 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -143,6 +143,11 @@ class MachineState {
/// that moment the list is the machine's own and nothing is provisional.
bool agentsFromCache = false;
+ /// When this machine last answered `agents_list` over the socket it is on now — null before the
+ /// first answer, and again once that socket drops, since the pushes that keep a list current
+ /// went nowhere while it was down. What Find asks before asking again (`_listStillCurrent`).
+ DateTime? agentsListedAt;
+
AgentLoadStatus agentLoadStatus = AgentLoadStatus.idle;
bool agentsRefreshing = false;
String? agentsLoadError;
@@ -1210,10 +1215,17 @@ class AppNotifier extends ChangeNotifier {
lastOpenedAgent.prefetch();
final cache = _machineCache;
if (cache != null) {
+ // Read before the first frame by `startHarness` — see [_preDialFromHint].
+ _launchHint = MachineCache.takeLaunchHint();
_launchCacheRead = StartupTrace.time(
'boot.machineCacheRead',
cache.readRaw,
);
+ // The small one beside it, which the launch's own machine is drawn from first.
+ _launchRecordRead = StartupTrace.time(
+ 'boot.machineLaunchRead',
+ cache.readLaunchRaw,
+ );
}
try {
if (_store != null) {
@@ -1247,13 +1259,48 @@ class AppNotifier extends ChangeNotifier {
} finally {
// Taken by the warm start when signed in; otherwise last run's text has no reader.
_launchCacheRead = null;
+ _launchRecordRead = null;
+ _launchHint = null;
}
}
+ /// The machine the launch hint names ([MachineCache.preloadLaunchHint]), for [_preDialFromHint]
+ /// — during the bootstrap that took it, and only then.
+ String? _launchHint;
+
+ /// The machine [_preDialFromHint] dialled, until the warm start has read which agent the launch
+ /// reopens and either keeps that dial as its own or lets it go ([_warmStartMachines]).
+ String? _preDialled;
+
+ /// Dial the machine the launch hint names, now — before the first frame, before anything else is
+ /// read — when the launch is signed in and nothing is on screen yet.
+ ///
+ /// ⚠️ **A head start, not a decision (owner, 2026-10-02).** Which agent the launch reopens is
+ /// still [lastOpenedAgent]'s to say, and the hold on the other machines is still the warm start's
+ /// to make; this only puts the socket — TCP, TLS, the upgrade — under way ~400ms sooner than the
+ /// warm start could, which had to wait out the first frame to read anything. The warm start takes
+ /// the dial over when the agent it reopens is on this machine, which is what the hint is written
+ /// for; otherwise the socket is closed again, one dial wasted, as a hint behind a crash is.
+ void _preDialFromHint() {
+ final hint = _launchHint;
+ _launchHint = null;
+ if (hint == null || _pool == null || _disposed) return;
+ if (machines.isNotEmpty || machineStates.isNotEmpty) return;
+ _preDialled = hint;
+ StartupTrace.mark(
+ 'launch: dialling ${_shortId(hint)} from the launch hint',
+ );
+ _conn(hint);
+ }
+
/// The machine cache as [bootstrap] began reading it, for the launch's [_warmStartMachines] —
/// once, and only during the bootstrap that started it.
Future<String?>? _launchCacheRead;
+ /// The cache's launch record ([MachineCache.readLaunchRaw]), read beside [_launchCacheRead] and
+ /// on the same terms.
+ Future<String?>? _launchRecordRead;
+
/// Whether this device is signed in, and everything behind the login screen when it is — what
/// `bootstrap()` does once its config is loaded.
Future<void> _checkSignIn() async {
@@ -1338,6 +1385,8 @@ class AppNotifier extends ChangeNotifier {
// that await, where the existing handler words it for the user and offers
// the retry.
_ensurePool();
+ // The launch's machine first of all, from the hint read before the first frame.
+ _preDialFromHint();
final machineRefresh = StartupTrace.time<Object?>(
'boot.refreshMachines',
() async {
@@ -1749,6 +1798,10 @@ class AppNotifier extends ChangeNotifier {
unawaited(_syncGroup(machineId));
} else if (nextStatus == ConnectionStatus.reconnecting ||
nextStatus == ConnectionStatus.disconnected) {
+ // A dial that failed is a turn spent: the next machine need not wait out its limit.
+ _endReleaseTurn(machineId, 'dial failed');
+ // Pushes sent while this socket is down reach nobody: the list is no longer current.
+ machine.agentsListedAt = null;
_stopAgentSyncTimer(machineId);
_clearMachineActivity(machine);
// Same reasoning as above, mirrored: capture pendingOfflineAgentId from the currently-open
@@ -1877,17 +1930,23 @@ class AppNotifier extends ChangeNotifier {
// awaited: it is a hint for a future run and must not add a disk write to
// the one a person is waiting on right now.
final cache = _machineCache;
- if (cache != null) {
- unawaited(
- cache.save(
- machines,
- isOnline: (machine) => _nodeOnlineFromStatus(machine.status) == true,
- ),
- );
- }
+ if (cache != null) _writeMachineCache(cache);
notifyListeners();
}
+ /// [cache] written out with this run's machines, and the launch record for the machine the next
+ /// launch reopens ([MachineCache.save]). Never awaited: it is for a future launch, and must not
+ /// add a disk write to anything a person is waiting on now.
+ void _writeMachineCache(MachineCache cache) {
+ unawaited(
+ cache.save(
+ machines,
+ isOnline: (machine) => _nodeOnlineFromStatus(machine.status) == true,
+ launchMachineId: lastOpenedAgent.current?.machineId,
+ ),
+ );
+ }
+
// The daemon reports `connected` only once its own backend socket is open, but
// `/api/machines` is a separate REST leg (fresh token refresh + fetch) that can still stall
// briefly right after that — a bounded retry absorbs that transient window without falling
@@ -2009,6 +2068,12 @@ class AppNotifier extends ChangeNotifier {
final agents = rawAgents
.map((item) => Agent.fromJson(item as Map<String, dynamic>))
.toList();
+ // Answered over this socket, changed or not: the list is current as of now. Only once the
+ // machine's list has been confirmed — a tick never stands in for that first one.
+ if (machine.agentLoadStatus == AgentLoadStatus.loaded &&
+ !machine.agentsFromCache) {
+ machine.agentsListedAt = DateTime.now();
+ }
if (agentsEqual(machine.agents, agents)) return;
// The machine's own list for the next launch too: what changed reached this phone without a
// push (one sent while the socket was away). A harness added or gone goes out soon, the rest
@@ -2162,12 +2227,15 @@ class AppNotifier extends ChangeNotifier {
newDevices.add(m);
devicesRevision++;
final name = m.label.isEmpty ? 'A device' : m.label;
- unawaited(agentNotices.system.showAccountNotice(
- key: m.pub,
- title: 'New device on your account',
- body: '$name ${m.kind == 'machine' ? 'joined' : 'signed in to'} your account and can reach '
- 'your machines. Not yours? Remove it in Settings ▸ Your devices.',
- ));
+ unawaited(
+ agentNotices.system.showAccountNotice(
+ key: m.pub,
+ title: 'New device on your account',
+ body:
+ '$name ${m.kind == 'machine' ? 'joined' : 'signed in to'} your account and can reach '
+ 'your machines. Not yours? Remove it in Settings ▸ Your devices.',
+ ),
+ );
if (!_disposed) notifyListeners();
},
onSignedOut: () async {
@@ -2574,7 +2642,7 @@ class AppNotifier extends ChangeNotifier {
// 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)) {
- _heldMachines.add(machine.machineId);
+ _holdForLaunch(machine.machineId);
continue;
}
_connectMachine(state);
@@ -2828,35 +2896,154 @@ class AppNotifier extends ChangeNotifier {
Timer? _heldMachinesTimer;
static const _heldMachinesRelease = Duration(seconds: 5);
- /// Whether [machineId] is one the launch is holding back — see [_launchMachineId].
+ /// 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;
+ (_launchMachineId != null && machineId != _launchMachineId) ||
+ _releaseQueue.contains(machineId);
- /// Dial every machine the launch held back. Idempotent; [why] goes to the startup timeline.
- void _releaseHeldMachines(String why) {
- if (_launchMachineId == null) return;
- _launchMachineId = null;
- _heldMachinesTimer?.cancel();
- _heldMachinesTimer = null;
- final held = _heldMachines.toList();
- _heldMachines.clear();
- if (_disposed) return;
- StartupTrace.mark('launch: dialling ${held.length} held machine(s) · $why');
- for (final machineId in held) {
- final state = machineStates[machineId];
- // Gone from the account since — `_refreshMachines` dropped it.
- if (state == null) continue;
- 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) {
- continue;
+ /// 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);
}
- _connectMachine(state);
+ _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
@@ -2875,10 +3062,17 @@ class AppNotifier extends ChangeNotifier {
/// 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
@@ -2988,7 +3182,7 @@ class AppNotifier extends ChangeNotifier {
final cache = _machineCache;
if (cache == null || _disposed) return;
final revision = _authRevision;
- // Both reads were started at the top of [bootstrap] and are normally in hand by now. Taken
+ // The reads were started at the top of [bootstrap] and are normally in hand by now. Taken
// before any await; the cache's once, so a later warm start (a sign-in in this run) reads what
// is on disk then.
final launchRead = lastOpenedAgent.prefetched;
@@ -2996,8 +3190,10 @@ class AppNotifier extends ChangeNotifier {
_launchCacheRead ??
StartupTrace.time('boot.machineCacheRead', cache.readRaw);
_launchCacheRead = null;
- final raw = await pendingRaw;
- if (raw == null || _disposed || !_authWorkCurrent(revision)) return;
+ final pendingRecord =
+ _launchRecordRead ??
+ StartupTrace.time('boot.machineLaunchRead', cache.readLaunchRaw);
+ _launchRecordRead = null;
AgentRef? launchAgent;
if (launchRead != null) {
try {
@@ -3024,26 +3220,25 @@ class AppNotifier extends ChangeNotifier {
// `/api/machines` can land while the cache is still being parsed, and the dial-everything it
// does then ([_autoConnectAndLoadMachines]) has to find the hold already in place.
String? dialledEarly;
- if (launchMachine != null &&
- machines.isEmpty &&
- machineStates.isEmpty &&
- raw.contains('"$launchMachine"')) {
- _launchMachineId = launchMachine;
+ void holdAndDialEarly(String machineId, String source) {
+ _launchMachineId = machineId;
_heldMachinesTimer?.cancel();
_heldMachinesTimer = Timer(
_heldMachinesRelease,
() => _releaseHeldMachines('launch budget spent'),
);
if (_pool != null) {
- dialledEarly = launchMachine;
- StartupTrace.mark('launch: dialling its machine before the cache parse');
- _conn(launchMachine);
+ final already = dialledEarly == machineId;
+ dialledEarly = machineId;
+ StartupTrace.mark(
+ already
+ ? 'launch: its machine is already dialling from the hint · $source'
+ : 'launch: dialling its machine before the cache parse · $source',
+ );
+ _conn(machineId);
}
}
- final cached = await StartupTrace.time(
- 'boot.machineCache',
- () => cache.parse(raw),
- );
+
// A socket dialled above for a machine nothing went on to make a state for — closed, or it
// would redial for the rest of the session with nobody listening.
void dropUnclaimedDial() {
@@ -3053,6 +3248,97 @@ class AppNotifier extends ChangeNotifier {
}
}
+ bool nothingYet() => machines.isEmpty && machineStates.isEmpty;
+
+ // The hint's dial ([_preDialFromHint]): this launch's early dial when the agent it reopens is
+ // on that machine — kept, adopted with its state below, closed by [dropUnclaimedDial] if no
+ // state ever claims it. A hint naming another machine was a guess that missed: let go.
+ final preDialled = _preDialled;
+ _preDialled = null;
+ if (preDialled != null) {
+ if (preDialled == launchMachine) {
+ dialledEarly = preDialled;
+ } else if (!machineStates.containsKey(preDialled)) {
+ StartupTrace.mark(
+ 'launch: the hint dialled ${_shortId(preDialled)}, the agent reopened '
+ 'is elsewhere — closing it',
+ );
+ unawaited(_pool?.closeMachine(preDialled));
+ }
+ }
+
+ // ⚠️ **The launch's own machine first, from the launch record (owner, 2026-10-02).** The
+ // record holds that one machine — its agents and its capabilities — and nothing else, so it is
+ // read and parsed in a fraction of the time the whole cache takes (see
+ // [MachineCache.parseLaunch]). Its terminal is drawn from it, and the rest of the account
+ // follows when the whole cache has been parsed below. Only when the record has the very agent
+ // being reopened: anything less, and the launch waits for the whole cache as it did before.
+ final record = await pendingRecord;
+ if (_disposed || !_authWorkCurrent(revision)) return;
+ CachedMachine? first;
+ List<Machine>? firstMachines;
+ if (launchAgent != null &&
+ record != null &&
+ nothingYet() &&
+ record.contains('"${launchAgent.machineId}"')) {
+ holdAndDialEarly(launchAgent.machineId, 'launch record');
+ first = await StartupTrace.time(
+ 'boot.machineLaunchParse',
+ () => cache.parseLaunch(
+ record,
+ machineId: launchAgent!.machineId,
+ agentId: launchAgent.agentId,
+ ),
+ );
+ if (_disposed || !_authWorkCurrent(revision)) {
+ dropUnclaimedDial();
+ return;
+ }
+ // The fetch landed during the parse: it is the truth, and made the state itself.
+ if (first != null && !nothingYet()) first = null;
+ if (first != null) {
+ final machine = first.machine;
+ final state = machineStates.putIfAbsent(
+ machine.machineId,
+ () => MachineState(machine),
+ );
+ _warmFromCache(state, first);
+ // Not held: it is the machine the hold puts first.
+ _connectMachine(state);
+ if (machine.machineId == dialledEarly) _adoptConnection(state);
+ // Kept to tell, after the parse below, whether the fetch has replaced it since.
+ firstMachines = [machine];
+ machines = firstMachines;
+ StartupTrace.mark(
+ 'warm-started its machine from the launch record, '
+ '${first.agents.length} agent(s)',
+ );
+ notifyListeners();
+ }
+ }
+ final raw = await pendingRaw;
+ if (_disposed || !_authWorkCurrent(revision)) {
+ dropUnclaimedDial();
+ return;
+ }
+ if (raw == null) {
+ // No cache beside the record: whatever the record started is all there is. A hold it put in
+ // place has nothing else to hold — the fetch dials the rest.
+ _releaseHeldMachines('cache unreadable', atOnce: true);
+ dropUnclaimedDial();
+ return;
+ }
+ if (dialledEarly == null &&
+ _launchMachineId == null &&
+ launchMachine != null &&
+ nothingYet() &&
+ raw.contains('"$launchMachine"')) {
+ holdAndDialEarly(launchMachine, 'cache');
+ }
+ final cached = await StartupTrace.time(
+ 'boot.machineCache',
+ () => cache.parse(raw),
+ );
if (_disposed || !_authWorkCurrent(revision)) {
dropUnclaimedDial();
return;
@@ -3060,30 +3346,36 @@ class AppNotifier extends ChangeNotifier {
if (cached.isEmpty) {
// Nothing usable after all: the hold has no machine to put first, so it is let go — the
// fetch dials everything, as a launch with no cache always did.
- _releaseHeldMachines('cache unreadable');
+ _releaseHeldMachines('cache unreadable', atOnce: true);
dropUnclaimedDial();
return;
}
// The fetch got there first — it is the truth, and this has nothing to add. Its own dial
- // honoured the hold; a launch machine the account no longer lists ends it.
- if (machines.isNotEmpty || machineStates.isNotEmpty) {
- final first = _launchMachineId;
- if (first != null && !machineStates.containsKey(first)) {
- _releaseHeldMachines('launch machine not on the account');
+ // honoured the hold; a launch machine the account no longer lists ends it. With the launch
+ // record drawn, `machines` is that record's list until the fetch replaces it.
+ final fetchLanded = firstMachines == null
+ ? !nothingYet()
+ : !identical(machines, firstMachines);
+ if (fetchLanded) {
+ final held = _launchMachineId;
+ if (held != null && !machineStates.containsKey(held)) {
+ _releaseHeldMachines('launch machine not on the account', atOnce: true);
}
dropUnclaimedDial();
return;
}
// The text named the launch machine, but the parse did not list it as one to dial — a match
- // elsewhere in the document. Nothing to put first, then.
- final first = _launchMachineId;
- if (first != null &&
+ // elsewhere in the document. Nothing to put first, then. Not once the record has drawn it:
+ // that machine is real, and dialling.
+ final held = _launchMachineId;
+ if (first == null &&
+ held != null &&
!cached.any(
(entry) =>
- entry.machine.machineId == first &&
+ entry.machine.machineId == held &&
entry.machine.authMode == MachineAuthMode.remote,
)) {
- _releaseHeldMachines('launch machine not cached');
+ _releaseHeldMachines('launch machine not cached', atOnce: true);
}
var warmed = 0;
var warmedAgents = 0;
@@ -3094,48 +3386,19 @@ class AppNotifier extends ChangeNotifier {
// claims to be this computer has no meaning on a phone and no local
// endpoint to dial, so it waits for the fetch like it always did.
if (machine.authMode != MachineAuthMode.remote) continue;
+ // Drawn already, from the launch record, and dialling: kept where the cache lists it.
+ if (first != null && machine.machineId == first.machine.machineId) {
+ warmMachines.add(first.machine);
+ warmed++;
+ warmedAgents += first.agents.length;
+ continue;
+ }
final state = machineStates.putIfAbsent(
machine.machineId,
() => MachineState(machine),
);
- // ⚠️ **The agents go in as PROVISIONAL, and the flag below is what keeps
- // them honest.** With them the phone draws its terminal — the right
- // agent's name on it, from the record it already had — while the real list
- // is still crossing the network, instead of showing a spinner for two
- // seconds and then the same screen.
- //
- // `agentLoadStatus` stays `loading`, not `loaded`: every screen reads that
- // to mean the machine still owes a list, so the refresh indicators, the
- // empty states and `_machineStillComing` all keep behaving as though
- // nothing had arrived — which is the truth. What these give is a name to
- // draw and an id to open, not a claim that the list is settled.
- if (entry.agents.isNotEmpty) {
- state.agents = entry.agents;
- state.agentsFromCache = true;
- warmedAgents += entry.agents.length;
- }
- // ⚠️ **The capability reply is replayed so a terminal can attach without
- // waiting for the negotiation round-trip.** `_canAttachAgent` requires
- // `terminalCapabilityAvailable`, which is otherwise only true once
- // `terminal_capabilities` has crossed the network — the last gate on the
- // launch, and worth about 700ms of it.
- //
- // Safe in the direction that matters. Only a reply that SAID the terminal
- // works is ever cached, the live negotiation runs regardless and
- // overwrites this within the second, and a machine that has genuinely lost
- // its tmux answers `available: false` — at which point
- // `_applyTerminalCapabilities` clears the flag and every screen reverts to
- // what it would have shown anyway. The narrow cost of being wrong is one
- // `terminal_open` that fails and is retried, against a second saved on
- // every launch that is right.
- final capabilities = entry.capabilities;
- if (capabilities != null) {
- _applyTerminalCapabilities(state, capabilities);
- // ⚠️ NOT `terminalCapabilityLoaded`-as-settled: the live negotiation
- // still has to run, and `_loadTerminalCapabilities` keys off its own
- // in-flight future rather than this flag, so replaying here cannot
- // suppress it.
- }
+ _warmFromCache(state, entry);
+ warmedAgents += entry.agents.length;
// ⚠️ **The dial, and ONLY the dial. No `_loadMachineData` here.**
//
// Asking for the agent list at this point was a real bug, and an ugly one
@@ -3162,7 +3425,7 @@ class AppNotifier extends ChangeNotifier {
// 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)) {
- _heldMachines.add(machine.machineId);
+ _holdForLaunch(machine.machineId);
} else {
_connectMachine(state);
// Its socket may have come up before this state existed — see `dialledEarly` above.
@@ -3172,6 +3435,13 @@ class AppNotifier extends ChangeNotifier {
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;
// ⚠️ Published to `machines` as well, because every screen indexes agents
// through THAT list (`agentIndex`, `filterableMachines`) rather than through
@@ -3188,6 +3458,48 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
}
+ /// What last run cached for [state]'s machine — its agents and its capability reply — put in
+ /// place for the launch to draw from ([_warmStartMachines]).
+ void _warmFromCache(MachineState state, CachedMachine entry) {
+ // ⚠️ **The agents go in as PROVISIONAL, and the flag below is what keeps
+ // them honest.** With them the phone draws its terminal — the right
+ // agent's name on it, from the record it already had — while the real list
+ // is still crossing the network, instead of showing a spinner for two
+ // seconds and then the same screen.
+ //
+ // `agentLoadStatus` stays `loading`, not `loaded`: every screen reads that
+ // to mean the machine still owes a list, so the refresh indicators, the
+ // empty states and `_machineStillComing` all keep behaving as though
+ // nothing had arrived — which is the truth. What these give is a name to
+ // draw and an id to open, not a claim that the list is settled.
+ if (entry.agents.isNotEmpty) {
+ state.agents = entry.agents;
+ state.agentsFromCache = true;
+ }
+ // ⚠️ **The capability reply is replayed so a terminal can attach without
+ // waiting for the negotiation round-trip.** `_canAttachAgent` requires
+ // `terminalCapabilityAvailable`, which is otherwise only true once
+ // `terminal_capabilities` has crossed the network — the last gate on the
+ // launch, and worth about 700ms of it.
+ //
+ // Safe in the direction that matters. Only a reply that SAID the terminal
+ // works is ever cached, the live negotiation runs regardless and
+ // overwrites this within the second, and a machine that has genuinely lost
+ // its tmux answers `available: false` — at which point
+ // `_applyTerminalCapabilities` clears the flag and every screen reverts to
+ // what it would have shown anyway. The narrow cost of being wrong is one
+ // `terminal_open` that fails and is retried, against a second saved on
+ // every launch that is right.
+ final capabilities = entry.capabilities;
+ if (capabilities != null) {
+ _applyTerminalCapabilities(state, capabilities);
+ // ⚠️ NOT `terminalCapabilityLoaded`-as-settled: the live negotiation
+ // still has to run, and `_loadTerminalCapabilities` keys off its own
+ // in-flight future rather than this flag, so replaying here cannot
+ // suppress it.
+ }
+ }
+
/// The least time `agents_list` gets, however long the handshake before it
/// took. Short enough that a dead machine is still reported promptly, long
/// enough for one round-trip over a relay on a mobile connection.
@@ -3209,6 +3521,14 @@ class AppNotifier extends ChangeNotifier {
if (identical(machine.agentsLoadInFlight, load)) {
machine.agentsLoadInFlight = null;
}
+ // A machine the launch let go of has had its say: the next one may dial
+ // ([_dialReleasedInTurn]).
+ _endReleaseTurn(
+ machine.machine.machineId,
+ machine.agentLoadStatus == AgentLoadStatus.loaded
+ ? 'listed ${machine.agents.length} agent(s)'
+ : 'list not read',
+ );
});
machine.agentsLoadInFlight = load;
return load;
@@ -3297,9 +3617,13 @@ class AppNotifier extends ChangeNotifier {
);
if (!_machineWorkCurrent(machine, revision)) return;
final rawAgents = response['agents'] as List<dynamic>? ?? [];
- final agents = rawAgents
- .map((item) => Agent.fromJson(item as Map<String, dynamic>))
- .toList();
+ final agents = StartupTrace.timeSync(
+ 'agents.parse ${_shortId(machine.machine.machineId)} '
+ '(${rawAgents.length} agent(s))',
+ () => rawAgents
+ .map((item) => Agent.fromJson(item as Map<String, dynamic>))
+ .toList(),
+ );
// Kept for the next launch, as the daemon sent it — see [MachineCache].
//
// ⚠️ Written out HERE, not left to the next refresh. The machine list is
@@ -3314,15 +3638,13 @@ class AppNotifier extends ChangeNotifier {
for (final item in rawAgents)
if (item is Map<String, dynamic>) item,
]);
- unawaited(
- cache.save(
- machines,
- isOnline: (item) => _nodeOnlineFromStatus(item.status) == true,
- ),
- );
+ // Several machines answering together write once: a save asked for while an older one
+ // still waits replaces it, and the encode is off the UI thread ([MachineCache.save]).
+ _writeMachineCache(cache);
}
_replaceAgents(machine, agents);
machine.agentLoadStatus = AgentLoadStatus.loaded;
+ machine.agentsListedAt = DateTime.now();
machine.agentsRefreshing = false;
machine.agentsLoadError = null;
debugPrint(
@@ -3901,8 +4223,21 @@ class AppNotifier extends ChangeNotifier {
await _loadMachineData(machine, force: true);
}
- /// Dial and re-ask EVERY machine on the account, whatever the account last
- /// said about any of them.
+ /// Dial and re-ask every machine on the account whose list is not already current, whatever the
+ /// account last said about any of them.
+ ///
+ /// ⚠️ **Not the ones already current, nor the ones waiting for a password (owner, 2026-10-02).**
+ /// Every opening of Find asked every machine for its whole agent list again — stopped work
+ /// included, 1.1–1.4s and ~400KB for 167 agents, decrypted and parsed on the phone — though a
+ /// machine on a live socket keeps its list current by itself: `agent_synced`, `agent_created`,
+ /// `agent_deleted` and the turn events land as they happen, and [_syncAgentsIfChanged] re-reads
+ /// it every [agentSyncInterval] to catch what they miss. So a machine that answered over the
+ /// socket it is on now, within that interval and a margin, is left as it is ([_listStillCurrent]);
+ /// everything this method was written for — a machine launch skipped, one not answering, one back
+ /// from a dropped socket — has no such answer, and is asked as before. A machine that refused this
+ /// phone for want of a link is not dialled again: a password, a code or the group dials it the
+ /// moment one lands (`connectWithPassword`, `_afterGroupSync`, `_redialNewlyTrusted`), and until
+ /// then a dial can only be refused again.
///
/// For the screen that offers the whole fleet in one list — the search, which
/// is the one place somebody asks "where is that agent" without knowing which
@@ -3940,12 +4275,48 @@ class AppNotifier extends ChangeNotifier {
if (_disposed || (_pool == null && connectionForTest == null)) return;
// Somebody is looking for a session, on any machine: the launch's hold is over — see
// [_launchMachineId]. Before the reloads below, so the held ones dial with the rest.
- _releaseHeldMachines('search opened');
+ _releaseHeldMachines('search opened', atOnce: true);
+ final now = DateTime.now();
+ final asking = <String>[];
+ var current = 0;
+ var locked = 0;
+ for (final machine in machines) {
+ final state = machineStates[machine.machineId];
+ if (state != null && state.needsLink) {
+ locked++;
+ } else if (state != null && _listStillCurrent(state, now)) {
+ current++;
+ } else {
+ asking.add(machine.machineId);
+ }
+ }
+ appLog.info(
+ 'search',
+ 'Find asks ${asking.length} machine(s) for their lists · '
+ '$current current already, $locked waiting for a password',
+ );
await Future.wait([
- for (final machine in machines) reloadMachineData(machine.machineId),
+ for (final machineId in asking) reloadMachineData(machineId),
]);
}
+ /// Whether [state]'s list was answered over the socket it is on now, recently enough that the
+ /// pushes since have kept it current — see [reachAllMachines].
+ bool _listStillCurrent(MachineState state, DateTime now) {
+ final listedAt = state.agentsListedAt;
+ // Asked first, so a machine with no answer yet never reaches [_connectionReady].
+ if (listedAt == null) return false;
+ return state.agentLoadStatus == AgentLoadStatus.loaded &&
+ !state.agentsFromCache &&
+ state.connectionStatus == ConnectionStatus.connected &&
+ _connectionReady(state.machine.machineId) &&
+ now.difference(listedAt) < agentSyncInterval + _listCurrentMargin;
+ }
+
+ /// How far past one [agentSyncInterval] a list still counts as current: a sync tick lands a little
+ /// late, or a slow machine answers it late, and that is not a list gone stale.
+ static const _listCurrentMargin = Duration(seconds: 30);
+
/// What every connected machine's agent accounts have spent, asked in
/// parallel and read there with that machine's own credentials (`usage_read`).
///
@@ -5143,6 +5514,8 @@ class AppNotifier extends ChangeNotifier {
_startOfflineRetry(machine);
} else {
_stopOfflineRetry(machineId);
+ // A socket waiting for this machine to come back need wait no longer ([_parkUntilOnline]).
+ _pool?[machineId]?.wake('reported online');
if (wasOnline == false) {
for (final pane in panesFor(machineId)) {
pane.session?.transportLost(
@@ -5192,6 +5565,40 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
}
+ /// The relay said [machine] is offline: a socket of the app's that never reached it waits for
+ /// it to come back instead of redialling on its backoff ([WsConn.parkUntilOnline]). It is woken
+ /// by any word that the machine is back — `machines_status` down any socket
+ /// ([_wakeMachinesBackOnline]), its own `node_status`, `/api/machines` ([_applyNodeStatus]) — and
+ /// by a person opening one of its agents ([_redialNow] → [WsConn.reconnectNow] once the parked
+ /// socket is gone, or the parked socket itself answering).
+ ///
+ /// Nothing for a socket that is up: a live session's machine going away is [_applyNodeStatus]'s.
+ void _parkUntilOnline(MachineState machine) {
+ final machineId = machine.machine.machineId;
+ final connection = _pool?[machineId];
+ if (connection == null || connection.isReady) return;
+ connection.parkUntilOnline();
+ // Waiting on a machine that is off is no reason to keep the next one from dialling.
+ if (connection.isParked) _endReleaseTurn(machineId, 'parked: offline');
+ }
+
+ /// `machines_status` — the relay's word on every machine of the account, sent down every socket
+ /// as it changes. Read for one thing: a machine reported online whose socket is parked waiting
+ /// for it ([_parkUntilOnline]) dials now.
+ ///
+ /// ⚠️ **Not applied as each machine's status.** That stays with `/api/machines` and each
+ /// socket's own `node_status`, as it was; this frame was ignored before, and taking it up for
+ /// everything would change what every machine's row says on a feed nothing here was built on.
+ void _wakeMachinesBackOnline(Object? statuses) {
+ if (statuses is! List) return;
+ for (final status in statuses) {
+ if (status is! Map || status['online'] != true) continue;
+ final machineId = status['machineId'];
+ if (machineId is! String || machineId.isEmpty) continue;
+ _pool?[machineId]?.wake('the relay says it is online');
+ }
+ }
+
Future<void> _recoverPendingAgent(
MachineState machine,
String agentId,
@@ -5874,18 +6281,20 @@ class AppNotifier extends ChangeNotifier {
_machineCacheSaveTimer?.cancel();
_machineCacheSaveTimer = null;
final cache = _machineCache;
- if (cache == null || _disposed || !cache.hasUnsaved) return;
+ if (cache == null || _disposed) return;
+ // Nothing learned, and the launch record already names the machine the next launch reopens:
+ // nothing to write. A person who moved to another machine's agent since is a launch record
+ // to rewrite, even with every list unchanged.
+ if (!cache.hasUnsaved &&
+ !cache.launchRecordStale(lastOpenedAgent.current?.machineId)) {
+ return;
+ }
// Signed out, or not yet signed in: the file is the account's, and [logout] clears it.
if (status != AppStatus.authenticated) return;
// A list not there to write would write the cache EMPTY — every machine gone from the next
// launch's warm start. The fetch that fills it saves on landing anyway.
if (machines.isEmpty) return;
- unawaited(
- cache.save(
- machines,
- isOnline: (machine) => _nodeOnlineFromStatus(machine.status) == true,
- ),
- );
+ _writeMachineCache(cache);
}
Future<void> _closeAllPanes({bool persist = true}) async {
@@ -6263,8 +6672,13 @@ class AppNotifier extends ChangeNotifier {
return;
case 'node_status':
final online = payload['online'] == true;
+ if (!online) _parkUntilOnline(machine);
await _applyNodeStatus(machine, online);
break;
+ case 'machines_status':
+ // Read only to wake a parked socket, and nothing else changed here: no redraw.
+ _wakeMachinesBackOnline(payload['statuses']);
+ return;
case 'machine_select_error':
_lastError =
'Machine selection failed: ${payload['error'] ?? 'unknown error'}';
diff --git a/mobile/lib/viewer/e2ee_relay_codec.dart b/mobile/lib/viewer/e2ee_relay_codec.dart
index bf4b432d4..f80079d09 100644
--- a/mobile/lib/viewer/e2ee_relay_codec.dart
+++ b/mobile/lib/viewer/e2ee_relay_codec.dart
@@ -8,7 +8,7 @@ import 'viewer_key_store.dart';
/// [RelaySessionCrypto] as a [RelayCodec]: the conversion the harness CLI's `remoteRelay.ts` does
/// between the relay's HTRM frames and the loopback HTRL ones, done in the app instead.
-class E2eeRelayCodec implements RelayCodec {
+class E2eeRelayCodec implements RelayCodec, OffThreadRelayDecoder {
E2eeRelayCodec(this._session);
final RelaySessionCrypto _session;
@@ -41,6 +41,11 @@ class E2eeRelayCodec implements RelayCodec {
Map<String, dynamic>? decodeFrame(Map<String, dynamic> frame) =>
_session.unwrapIncoming(frame);
+ @override
+ Future<Map<String, dynamic>?> decodeFrameOffThread(
+ Map<String, dynamic> frame,
+ ) => _session.unwrapIncomingOffThread(frame);
+
@override
Uint8List? encodeBinary(Uint8List localFrame) {
final clear = decodeTerminalLocal(localFrame);
diff --git a/mobile/lib/ws/relay_codec.dart b/mobile/lib/ws/relay_codec.dart
index 9dd854449..3bb006cc8 100644
--- a/mobile/lib/ws/relay_codec.dart
+++ b/mobile/lib/ws/relay_codec.dart
@@ -34,6 +34,17 @@ abstract interface class RelayCodec {
Uint8List? decodeBinary(Uint8List wireFrame);
}
+/// A [RelayCodec] that can open a large frame off the UI isolate — what [WsConn] asks of one when
+/// there is one, and [RelayCodec.decodeFrame] otherwise. A separate interface so a codec that has
+/// nothing to gain from it (a test's) need not say so.
+abstract interface class OffThreadRelayDecoder {
+ /// [RelayCodec.decodeFrame], with a large payload opened on a background isolate — same answer,
+ /// same null for a frame to drop.
+ Future<Map<String, dynamic>?> decodeFrameOffThread(
+ Map<String, dynamic> frame,
+ );
+}
+
/// A fresh session for each connection to [machineId]; null when this device has no link to it —
/// the machine could only answer `e2e_denied`, so there is nothing worth dialing.
typedef RelayCodecFactory = Future<RelayCodec?> Function(String machineId);
diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dart
index 8638832f2..9dc4cba2c 100644
--- a/mobile/lib/ws/ws_conn.dart
+++ b/mobile/lib/ws/ws_conn.dart
@@ -1,5 +1,6 @@
import 'dart:async';
import 'dart:convert';
+import 'dart:isolate';
import 'dart:math';
import 'package:flutter/foundation.dart';
@@ -9,6 +10,7 @@ import '../logging/app_log.dart';
import '../logging/redact.dart';
import '../logging/startup_trace.dart';
import '../core/models.dart';
+import '../core/test_run.dart';
import 'relay_codec.dart';
import 'terminal_transport_plugin.dart';
@@ -128,6 +130,15 @@ class WsConn {
Timer? _reconnectTimer;
String? _tokenUsed;
+ /// The relay said this connection's machine is offline, and the connection is waiting for it to
+ /// come back rather than redialling — see [parkUntilOnline].
+ bool _parked = false;
+ bool get isParked => _parked;
+
+ /// How long a parked connection waits before it dials again of its own accord, with nothing having
+ /// said the machine is back — the fallback under [wake], not the way back.
+ static const _parkedRecheck = Duration(seconds: 60);
+
/// This socket's `e2e_hello` went out right behind its `machine_select`, so the select's ack must
/// not send another — see [connect]. Reset on every dial.
bool _helloAhead = false;
@@ -208,6 +219,8 @@ class WsConn {
if (_closing || _connecting) return;
_connecting = true;
_ready = false;
+ // A dial is under way: whatever parked the last one is over ([parkUntilOnline]).
+ _parked = false;
// ⚠️ **The outbound queue starts empty on every dial, and it did not used
// to.** `_outboundTail` is a chain each send appends itself to, so one link
// that never completes stalls every frame queued behind it — for the life of
@@ -259,11 +272,38 @@ class WsConn {
(codec) => (codec: codec, error: null),
onError: (Object error) => (codec: null, error: error),
);
+ // What the codec said while the credential was being fetched, if it has said it yet.
+ ({RelayCodec? codec, Object? error})? codecAnswered;
+ unawaited(pendingCodec?.then((result) => codecAnswered = result));
final token = await pendingToken;
if (token.isEmpty) {
throw StateError('WebSocket credential is missing');
}
if (_closing) return;
+ // The codec's "no link" comes from links held in memory, a handful of microtasks behind its
+ // start — and the credential, also from memory, often lands in the same turn, just ahead of
+ // it: measured, Find dialled three unlinked machines that way. A few microtask hops let an
+ // answer already on its way arrive. Microtasks only, so this never waits on the event loop or
+ // a frame; a codec still reading the disk or minting a key is not waited for.
+ for (
+ var hop = 0;
+ hop < _codecAnswerHops && pendingCodec != null && codecAnswered == null;
+ hop++
+ ) {
+ await Future<void>.value();
+ }
+ if (_closing) return;
+ // ⚠️ **No link, no dial (owner, 2026-10-02).** The codec answers "no link to this machine"
+ // from the links this device holds in memory, usually before the credential is back — and
+ // the dial below went out anyway, a TCP + TLS + upgrade opened only to be dropped by
+ // [_refusePeer] the moment the codec was awaited. Opening Find did that for every machine
+ // this phone never linked, on every opening. Said already, it is said here, with no socket;
+ // not said yet, the dial goes ahead as before and the same refusal follows it.
+ final early = codecAnswered;
+ if (early != null && early.codec == null && early.error == null) {
+ _refusePeer('NO_PEER_LINK');
+ return;
+ }
_tokenUsed = token;
final base = Uri.parse('$wsBaseUrl/api/web-ws');
final uri = base.replace(
@@ -413,6 +453,37 @@ class WsConn {
onAuthFailure(message);
}
+ /// How many microtask hops [connect] gives the codec's answer before dialling — more than the
+ /// in-memory link lookup takes to reach it (~6), and still nothing a person could measure.
+ static const _codecAnswerHops = 12;
+
+ /// From this many characters a relay text frame is decoded off the UI isolate — see [_onRaw].
+ static const _decodeOffThreadFrom = 64 * 1024;
+
+ /// [raw]'s JSON object, decoded on a background isolate; null for anything that is not one. An
+ /// isolate that will not start is the decode done here.
+ static Future<Map<String, dynamic>?> _decodeOffThread(String raw) async {
+ Object? decoded;
+ try {
+ decoded = await Isolate.run(() => jsonDecode(raw));
+ } on FormatException {
+ return null;
+ } on Object {
+ try {
+ decoded = jsonDecode(raw);
+ } on Object {
+ return null;
+ }
+ }
+ return decoded is Map<String, dynamic> ? decoded : null;
+ }
+
+ static String _typeOf(Map<String, dynamic> message) =>
+ message['type'] is String ? message['type'] as String : '?';
+
+ static String _short(String machineId) =>
+ machineId.length <= 8 ? machineId : machineId.substring(0, 8);
+
void _onRaw(dynamic raw) {
final codec = _codec;
if (raw is List<int>) {
@@ -433,6 +504,34 @@ class WsConn {
});
return;
}
+ // ⚠️ **A large frame is decoded off the UI isolate, in its place in the line (owner,
+ // 2026-10-02).** A machine's whole agent list arrives as one frame of hundreds of KB, and its
+ // JSON was decoded right here on the thread drawing the screen — then opened (below), then
+ // decoded again. Done inside the inbound chain rather than before it, so it keeps its place:
+ // the frames behind it wait for it exactly as they waited for the decode done here.
+ if (codec != null &&
+ raw is String &&
+ raw.length >= _decodeOffThreadFrom &&
+ !kUnderTest) {
+ _inboundTail = _inboundTail
+ .then((_) async {
+ final clock = Stopwatch()..start();
+ final message = await _decodeOffThread(raw);
+ if (message == null) return;
+ final decodeMs = clock.elapsedMilliseconds;
+ await _onRelayFrame(codec, message);
+ appLog.info(
+ 'ws',
+ 'large frame · ${(raw.length / 1024).round()}KB '
+ '${_typeOf(message)} · decoded off-thread in ${decodeMs}ms, '
+ 'handled in ${clock.elapsedMilliseconds}ms · ${_short(machineId)}',
+ );
+ })
+ .catchError((_) {
+ // Keep the FIFO alive: a frame that will not open is dropped, never dispatched.
+ });
+ return;
+ }
final Map<String, dynamic> message;
try {
message = jsonDecode(raw as String) as Map<String, dynamic>;
@@ -514,9 +613,66 @@ class WsConn {
});
}
+ /// The relay has just said this connection's machine is offline: stop treating the silence that
+ /// follows as a dial gone wrong, and wait for the machine instead.
+ ///
+ /// ⚠️ **Why (owner, 2026-10-02).** Without this, a machine that is switched off was redialled for
+ /// as long as the app ran: [_armSelectWatchdog] read the welcome that never came as a relay gone
+ /// quiet, and every redial on its 1–30s backoff paid a fresh credential, a key mint and a TLS
+ /// dial — the key mint pure Dart on the UI thread. Opening Find dials every machine on the
+ /// account, so four machines that were off cost about twenty of those in Find's first minute.
+ ///
+ /// The socket is KEPT, not closed. The relay pushes every one of the account's machines'
+ /// status changes down every socket (`machines_status`), so the app hears this machine come back
+ /// through it — or through any other machine's socket, or `/api/machines` — and calls [wake]. A
+ /// welcome that arrives anyway (the relay was wrong) still makes it ready ([_markReady]). With
+ /// nothing heard at all, it dials again after [_parkedRecheck].
+ ///
+ /// Only a connection that never became ready: a live session's machine going away is the
+ /// `node_status` the app already handles, on a socket that is still up.
+ void parkUntilOnline() {
+ if (_closing || _ready || _parked || _channel == null) return;
+ _parked = true;
+ _selectWatchdog?.cancel();
+ _selectWatchdog = null;
+ _reconnectTimer?.cancel();
+ _reconnectTimer = Timer(_parkedRecheck, () => wake('recheck'));
+ appLog.info(
+ 'ws',
+ 'parked $machineId · the relay says it is offline; '
+ 'waiting for it (recheck ${_parkedRecheck.inSeconds}s)',
+ );
+ }
+
+ /// Dial a parked connection now — its machine was reported back ([reason] goes to the log).
+ /// Nothing for a connection that is not parked.
+ void wake(String reason) {
+ if (!_parked) return;
+ _parked = false;
+ _reconnectTimer?.cancel();
+ _reconnectTimer = null;
+ if (_closing || _ready) return;
+ appLog.info('ws', 'woken $machineId · $reason');
+ _abandonDial(_channel);
+ _attempt = 0;
+ // A dial still finishing would turn [connect] away, and nothing would dial after it: the
+ // ordinary backoff picks it up instead.
+ if (_connecting) {
+ _scheduleReconnect();
+ return;
+ }
+ unawaited(connect());
+ }
+
void _markReady() {
_selectWatchdog?.cancel();
_selectWatchdog = null;
+ // The machine answered after all: the recheck a park armed is not wanted.
+ if (_parked) {
+ _parked = false;
+ _reconnectTimer?.cancel();
+ _reconnectTimer = null;
+ }
_ready = true;
_attempt = 0;
onStatus(ConnectionStatus.connected);
@@ -576,7 +732,10 @@ class WsConn {
codec.handleRekey(payload);
return;
}
- final clear = codec.decodeFrame(message);
+ // A large sealed payload is opened off the UI isolate, by a codec that can.
+ final clear = codec is OffThreadRelayDecoder
+ ? await (codec as OffThreadRelayDecoder).decodeFrameOffThread(message)
+ : codec.decodeFrame(message);
if (clear == null) return;
// Only a frame that arrived sealed and opened: the relay's own frames pass through
// [RelayCodec.decodeFrame] in the clear — see [lastHeardFromMachineAt].
@@ -915,6 +1074,8 @@ class WsConn {
if (!identical(_channel, channel)) return;
_channel = null;
_sub = null;
+ // A parked socket that closed is redialled on the backoff below, which replaces the recheck.
+ _parked = false;
_codec = null;
_disposePlugin();
_ready = false;
@@ -1002,6 +1163,12 @@ class WsConn {
/// calls `handleAppResumed` as it mounts, which is a few hundred milliseconds
/// after the warm start has begun dialling.
void reconnectNow() {
+ // Parked, the socket is open but waiting on a machine the relay called offline
+ // ([parkUntilOnline]): somebody arriving is worth asking again, once, as it always was.
+ if (_parked) {
+ wake('asked for');
+ return;
+ }
if (_closing || _connecting || _channel != null) {
return;
}
@@ -1029,6 +1196,7 @@ class WsConn {
Future<void> close() async {
_closing = true;
_ready = false;
+ _parked = false;
_codec = null;
_disposePlugin();
_reconnectTimer?.cancel();