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): cut launch latency to the first live terminal

tony21acce29500f
diff --git a/mobile/lib/app_shell.dart b/mobile/lib/app_shell.dart
index 437248283..24a9bf18c 100644
--- a/mobile/lib/app_shell.dart
+++ b/mobile/lib/app_shell.dart
@@ -53,8 +53,15 @@ Future<void> startHarness({
// — 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);
+ // ⚠️ **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
+ // own first build (~170ms on a debug launch) and then queued behind the first frame too.
+ final container = ProviderContainer();
+ StartupTrace.timeSync('app.create', () => container.read(appStateProvider));
runApp(
- ProviderScope(
+ UncontrolledProviderScope(
+ container: container,
child: HarnessApp(
authenticatedScreen: authenticatedScreen,
signedOutScreen: signedOutScreen,
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index d49b2f0bd..4d1f55b5e 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -1192,6 +1192,18 @@ class AppNotifier extends ChangeNotifier {
}
Future<void> bootstrap() async {
+ // ⚠️ **Started before anything is awaited (owner, 2026-10-01).** The launch's dial waits on
+ // these two reads: the last-opened agent names its machine, the cache says that machine was up
+ // ([_warmStartMachines]). Started after the config and the sign-in check, they landed after
+ // the first frame, ~250ms into the dial's wait. Disk only; dropped when nobody is signed in.
+ lastOpenedAgent.prefetch();
+ final cache = _machineCache;
+ if (cache != null) {
+ _launchCacheRead = StartupTrace.time(
+ 'boot.machineCacheRead',
+ cache.readRaw,
+ );
+ }
try {
if (_store != null) {
try {
@@ -1221,9 +1233,16 @@ class AppNotifier extends ChangeNotifier {
currentUser = null;
status = AppStatus.unauthenticated;
notifyListeners();
+ } finally {
+ // Taken by the warm start when signed in; otherwise last run's text has no reader.
+ _launchCacheRead = null;
}
}
+ /// 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;
+
/// 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 {
@@ -1266,9 +1285,11 @@ class AppNotifier extends ChangeNotifier {
_bootStatusMessage = 'Getting your machines…';
notifyListeners();
// Which agent to reopen is the first thing the phone's home screen asks for
- // and the last thing it can draw without, so the read starts here rather
- // than when that screen mounts — several state-file operations later, behind
- // every one of their locks. See [LastOpenedAgent.prefetch].
+ // and the last thing it can draw without, so the read starts no later than
+ // here rather than when that screen mounts — several state-file operations
+ // later, behind every one of their locks. A launch has already started it
+ // (top of [bootstrap]); a sign-in in this run starts it here. See
+ // [LastOpenedAgent.prefetch].
lastOpenedAgent.prefetch();
// No screen from the last run: the agent that record names is drawn as the skeleton until its
// keyframe lands — see [KeptScreenStore]. What an earlier build kept of it on disk goes. Only in
@@ -2715,6 +2736,15 @@ class AppNotifier extends ChangeNotifier {
pane.machineId != machine.machine.machineId) {
return;
}
+ await _untilTerminalLive(terminal, _launchListYield);
+ }
+
+ /// 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 {
// `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() {
@@ -2731,7 +2761,7 @@ class AppNotifier extends ChangeNotifier {
}
// A session closed meanwhile never notifies again; this is what ends the wait then.
- final timer = Timer(_launchListYield, () {
+ final timer = Timer(bound, () {
if (!done.isCompleted) done.complete();
});
terminal.addListener(check);
@@ -2770,10 +2800,15 @@ class AppNotifier extends ChangeNotifier {
final cache = _machineCache;
if (cache == null || _disposed) return;
final revision = _authRevision;
- // Taken before the cache read so the two overlap: the record was prefetched at the top of the
- // bootstrap and is normally on hand by the time the cache is.
+ // Both 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;
- final raw = await StartupTrace.time('boot.machineCacheRead', cache.readRaw);
+ final pendingRaw =
+ _launchCacheRead ??
+ StartupTrace.time('boot.machineCacheRead', cache.readRaw);
+ _launchCacheRead = null;
+ final raw = await pendingRaw;
if (raw == null || _disposed || !_authWorkCurrent(revision)) return;
AgentRef? launchAgent;
if (launchRead != null) {
@@ -4457,8 +4492,20 @@ class AppNotifier extends ChangeNotifier {
final last = _touchedAt[key];
if (last != null && now.difference(last) < _touchEvery) return;
_touchedAt[key] = now;
+ final revision = _authRevision;
unawaited(() async {
try {
+ // ⚠️ **After the agent's own terminal, never ahead of it (owner, 2026-10-01).** The machine
+ // takes a connection's frames one at a time (`enqueueDown` in the CLI's backendSocket.ts),
+ // and this one costs it a whole agent frame (`toProject`, git context and all). At launch
+ // it is queued before the socket is up and flushed first, so the `terminal_open` behind it
+ // waited for that. A recency stamp can wait a second; the screen cannot.
+ await _yieldToTerminalOpen(_conn(machineId), machineId, agentId);
+ if (_disposed ||
+ !_authWorkCurrent(revision) ||
+ machineStates[machineId]?.needsLink != false) {
+ return;
+ }
await _conn(machineId).request(
'agent_update',
payload: {'agentId': agentId, 'opened': true},
@@ -4472,6 +4519,39 @@ class AppNotifier extends ChangeNotifier {
static const _touchEvery = Duration(seconds: 3);
final _touchedAt = <String, DateTime>{};
+ /// The longest [touchAgent] holds its stamp for the socket, and then for the terminal.
+ static const _touchYield = Duration(seconds: 3);
+
+ /// Until [agentId]'s terminal on [machineId] is live — see [touchAgent]. The socket first: a frame
+ /// asked for before it is up is queued, and that queue goes out ahead of the terminal's open
+ /// (`WsConn._flushQueue` runs before the open's wait for readiness ends).
+ Future<void> _yieldToTerminalOpen(
+ WsConn connection,
+ String machineId,
+ String agentId,
+ ) async {
+ // Read as the app shows it too: a machine already `connected` here has nothing to wait for.
+ if (!connection.isReady &&
+ machineStates[machineId]?.connectionStatus !=
+ ConnectionStatus.connected) {
+ try {
+ await connection.waitUntilReady(timeout: _touchYield);
+ } catch (_) {
+ // Not up in time, or closed: the stamp goes the way it always did.
+ }
+ }
+ if (_disposed) return;
+ TerminalSession? terminal;
+ for (final pane in allPanes) {
+ if (pane.machineId == machineId && pane.agentId == agentId) {
+ terminal = pane.session;
+ if (terminal != null) break;
+ }
+ }
+ if (terminal == null) return;
+ await _untilTerminalLive(terminal, _touchYield);
+ }
+
/// Deletes an agent via `agent_delete`. Returns null on success, or an error message to show
/// inline in the caller's dialog.
Future<String?> deleteAgent(String machineId, String agentId) async {
diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dart
index e3926d852..8638832f2 100644
--- a/mobile/lib/ws/ws_conn.dart
+++ b/mobile/lib/ws/ws_conn.dart
@@ -128,6 +128,10 @@ class WsConn {
Timer? _reconnectTimer;
String? _tokenUsed;
+ /// 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;
+
/// How long a dial may take to open before it counts as failed. Without one, a socket dialled
/// into a network that swallows packets waits out the OS's own TCP timeout — over a minute on
/// iOS — with the machine showing "reconnecting" the whole time.
@@ -215,6 +219,7 @@ class WsConn {
// Anything still pending on it was addressed to a channel that is gone, and
// `_flushQueue` re-sends what actually matters once the session is ready.
_outboundTail = Future<void>.value();
+ _helloAhead = false;
WebSocketChannel? dialing;
onStatus(
_attempt == 0
@@ -260,13 +265,46 @@ class WsConn {
}
if (_closing) return;
_tokenUsed = token;
+ final base = Uri.parse('$wsBaseUrl/api/web-ws');
+ final uri = base.replace(
+ queryParameters: {
+ ...base.queryParameters,
+ 'autonomousEnv': autonomousEnv,
+ },
+ );
+ // ⚠️ **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],
+ );
+ void dropChannel() =>
+ unawaited(channel.sink.close().catchError((Object _) {}));
+ // Its outcome captured here, where the future is made: the ways out below leave without
+ // awaiting it, and an unhandled rejection would be reported as a crash.
+ final opening = StartupTrace.time(
+ 'ws.dial',
+ () => channel.ready.timeout(_dialTimeout),
+ ).then<Object?>((_) => null, onError: (Object error) => error);
if (pendingCodec != null) {
final result = await pendingCodec;
- if (_closing) return;
+ if (_closing) {
+ dropChannel();
+ return;
+ }
final failure = result.error;
- if (failure != null) throw failure;
+ if (failure != null) {
+ dropChannel();
+ throw failure;
+ }
final codec = result.codec;
if (codec == null) {
+ dropChannel();
_refusePeer('NO_PEER_LINK');
return;
}
@@ -276,22 +314,9 @@ class WsConn {
final plugins = transportPlugins;
if (plugins != null) _plugin = plugins(_PluginHost(this), machineId);
}
- final base = Uri.parse('$wsBaseUrl/api/web-ws');
- final uri = base.replace(
- queryParameters: {
- ...base.queryParameters,
- 'autonomousEnv': autonomousEnv,
- },
- );
- final channel = dialing = (connectChannel ?? WebSocketChannel.connect)(
- uri,
- protocols: [token],
- );
- _channel = channel;
- await StartupTrace.time(
- 'ws.dial',
- () => channel.ready.timeout(_dialTimeout),
- );
+ _channel = dialing = channel;
+ final dialFailure = await opening;
+ if (dialFailure != null) throw dialFailure;
if (_closing || !identical(_channel, channel)) {
// Logged because this is a silent exit from a dial that otherwise looks
// successful — the trace shows `ws.dial` completing and then nothing at
@@ -330,10 +355,25 @@ class WsConn {
// relay. Cancelled by [_markReady], by [_onDone] and by [close].
_armSelectWatchdog();
appLog.debug('ws', '→ machine_select $machineId');
- await sendFrame({
+ final selected = await _enqueueFrame({
'type': 'machine_select',
'payload': {'machineId': machineId},
});
+ // ⚠️ **The hello goes right behind the select, not on its ack (owner, 2026-10-01).** The
+ // relay takes a socket's frames strictly in order (`backend/src/lib/orderedInbox.ts`), so it
+ // reaches the machine only once the select has bound — waiting for the ack added a whole
+ // phone↔relay round trip in front of every handshake. A select the relay refuses drops it
+ // (no machine bound), which is harmless. The ack still reaches the plugin before the welcome:
+ // the relay sends it before it handles the hello. See the `connected` case in [_onRelayFrame].
+ final codec = _codec;
+ if (selected &&
+ codec != null &&
+ !_closing &&
+ !_ready &&
+ identical(_channel, channel)) {
+ channel.sink.add(jsonEncode(codec.helloFrame()));
+ _helloAhead = true;
+ }
} on WsCredentialRevoked catch (error) {
// ⚠️ Not for a connection somebody already closed. Signing out closes every connection, and
// one still waiting on its credential then learns the session is gone — which is the
@@ -500,6 +540,12 @@ class WsConn {
// The policy rides the ack; the plugin must have it before the welcome
// that decides whether to act on it.
_plugin?.onConnectedAck(payload);
+ // Already sent behind this socket's select — see [connect]. Exactly one hello per
+ // session: a second one would have the machine start the handshake over.
+ if (_helloAhead) {
+ _helloAhead = false;
+ return;
+ }
_channel?.sink.add(jsonEncode(codec.helloFrame()));
}
return;