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 to the first session

tony16c0adce2b54
diff --git a/mobile/lib/core/last_opened_agent.dart b/mobile/lib/core/last_opened_agent.dart
index 04eaa232b..88a6862d6 100644
--- a/mobile/lib/core/last_opened_agent.dart
+++ b/mobile/lib/core/last_opened_agent.dart
@@ -45,6 +45,11 @@ class LastOpenedAgent {
/// the prefetch and the screen share one read rather than racing for the lock.
void prefetch() => _read ??= _load();
+ /// The [prefetch] in flight or landed, WITHOUT taking it — for the launch to learn which machine
+ /// to dial first (`AppNotifier._warmStartMachines`), while [read] stays the home screen's own
+ /// one-shot. Null when nothing was prefetched, or the home screen has already taken it.
+ Future<AgentRef?>? get prefetched => _read;
+
/// What the previous run left, or null. Anything malformed reads as nothing — a missing
/// preference must never hold the app on its launch screen.
///
diff --git a/mobile/lib/core/machine_cache.dart b/mobile/lib/core/machine_cache.dart
index 75da3b0a6..d3f54eba8 100644
--- a/mobile/lib/core/machine_cache.dart
+++ b/mobile/lib/core/machine_cache.dart
@@ -1,8 +1,16 @@
import 'dart:convert';
+import 'dart:isolate';
import 'models.dart';
import 'snapshot_store.dart';
+/// One machine as [MachineCache._parseDocument] reads it: what the launch uses, and its agents as the
+/// daemon sent them, for the next save.
+typedef _ParsedMachine = ({
+ CachedMachine cached,
+ List<Map<String, dynamic>> rawAgents,
+});
+
/// The machines this account had at the end of the last run, so the next launch
/// can start dialling before `/api/machines` answers.
///
@@ -77,19 +85,75 @@ class MachineCache {
/// cache at all, which is always safe — the fetch fills it in.
static const _version = 1;
- /// What the last run saw, or empty when there is nothing usable.
+ /// What the last run saw, or empty when there is nothing usable — [readRaw], then [parse].
///
/// Never throws: a cache that cannot be read is a cache that is not there.
Future<List<CachedMachine>> read() async {
+ final raw = await readRaw();
+ return raw == null ? const [] : parse(raw);
+ }
+
+ /// The cache file's text, unparsed — or null when there is none.
+ ///
+ /// 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 {
try {
final raw = await _store.read();
- if (raw == null || raw.isEmpty) return const [];
+ return raw == null || raw.isEmpty ? null : raw;
+ } on Object {
+ return null;
+ }
+ }
+
+ /// Below this many characters [parse] stays on the calling isolate: spawning one costs more than
+ /// a small document does to parse.
+ static const _parseOffThreadFrom = 64 * 1024;
+
+ /// [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
+ /// every machine is in here, verbatim, and the whole of it was decoded and turned into [Agent]s
+ /// on the thread drawing the launch: measured at 273ms for 103 agents and 629ms for 131, during
+ /// which the first frame and the dial both waited. The account the phone is built for has seven
+ /// or eight machines of ten to twenty sessions each, which is worse again. Parsed in a background
+ /// 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);
+ }
+ }
+ // Kept for the next [save], on this isolate — see [_agents] and [_capabilities].
+ for (final entry in parsed) {
+ final machineId = entry.cached.machine.machineId;
+ _agents[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;
+ }
+ 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
+ /// document that is not this version's, or not one at all.
+ static List<_ParsedMachine> _parseDocument(String raw) {
+ try {
final decoded = jsonDecode(raw);
if (decoded is! Map<String, dynamic>) return const [];
if (decoded['version'] != _version) return const [];
final machines = decoded['machines'];
if (machines is! List) return const [];
- final parsed = <CachedMachine>[];
+ final parsed = <_ParsedMachine>[];
for (final item in machines) {
if (item is! Map<String, dynamic>) continue;
try {
@@ -110,22 +174,17 @@ class MachineCache {
}
final rawCaps = item['capabilities'];
final capabilities = rawCaps is Map<String, dynamic> ? rawCaps : null;
- parsed.add(
- CachedMachine(
+ parsed.add((
+ cached: CachedMachine(
machine: machine,
agents: agents,
capabilities: capabilities,
),
- );
- _agents[machine.machineId] = [
- for (final entry in (rawAgents is List ? rawAgents : const []))
- if (entry is Map<String, dynamic>) entry,
- ];
- // Carried forward so a launch that reads the cache and is closed
- // before any machine answers still writes back what it knew.
- if (capabilities != null) {
- _capabilities[machine.machineId] = capabilities;
- }
+ rawAgents: [
+ for (final entry in (rawAgents is List ? rawAgents : const []))
+ if (entry is Map<String, dynamic>) entry,
+ ],
+ ));
} on Object {
// One malformed entry does not discard the rest; the fetch will
// correct whatever this cache got wrong either way.
diff --git a/mobile/lib/p2p/terminal_p2p_plugin.dart b/mobile/lib/p2p/terminal_p2p_plugin.dart
index 1bbb9a1cf..681175935 100644
--- a/mobile/lib/p2p/terminal_p2p_plugin.dart
+++ b/mobile/lib/p2p/terminal_p2p_plugin.dart
@@ -171,6 +171,14 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
}
}
+ /// Whether this connection may run P2P — the backend sent a policy and the peer speaks this
+ /// build's version — settled as its session comes up ([onSessionReady]).
+ bool _p2pEligible = false;
+
+ /// Whether the first negotiation has been started — by the first terminal to open
+ /// ([prepareOpen]). Every later one is [_scheduleRetry]'s, budget and all.
+ bool _p2pStarted = false;
+
@override
void onSessionReady() {
if (_disposed) return;
@@ -186,7 +194,14 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
' v$terminalP2pProtocolVersion — no data channel is possible, ws relay only',
);
} else {
- _startP2p();
+ // ⚠️ **Not started here any more — on the first terminal instead (owner, 2026-10-01).**
+ // Every machine the phone reached used to negotiate the moment its session came up: ICE
+ // gathering, STUN and TURN, and the offer and answer over the relay, for each of seven or
+ // eight machines at once at launch, when one terminal on one of them is all anybody is
+ // waiting for. A data channel only carries terminals, so a machine with none open has no
+ // use for one; the first open on it starts it ([prepareOpen]), rides the relay meanwhile as
+ // every open made before the channel is up does, and moves over once it is.
+ _p2pEligible = true;
}
}
@@ -540,10 +555,16 @@ class TerminalP2pPlugin implements TerminalTransportPlugin {
/// out, and the channel's own outcome is still reported when it lands or gives up.
@override
Future<bool> prepareOpen(String requestId) async {
- final link = _link;
- if (link == null || _policy == null || _disposed || !link.isReady) {
- return false;
+ if (_disposed) return false;
+ // The connection's first terminal is what starts its channel — see [onSessionReady]. Once
+ // only: a channel that failed or was demoted since is [_scheduleRetry]'s to bring back.
+ if (_p2pEligible && !_p2pStarted) {
+ _p2pStarted = true;
+ _log('starting · first terminal on this machine');
+ _startP2p();
}
+ final link = _link;
+ if (link == null || _policy == null || !link.isReady) return false;
_pendingOpens.add(requestId);
return true;
}
diff --git a/mobile/lib/phone/agents_list_page.dart b/mobile/lib/phone/agents_list_page.dart
index 14ad092e7..bcefaace5 100644
--- a/mobile/lib/phone/agents_list_page.dart
+++ b/mobile/lib/phone/agents_list_page.dart
@@ -62,10 +62,11 @@ class _AgentsListPageState extends State<AgentsListPage> {
@override
void initState() {
super.initState();
- // Same warm [PhoneSearchResults] does on open, and for the same reason: the previews are what
- // fill each row's second line, and reading them only as rows scroll into view would fill the
- // list in visibly, line by line. Prioritised — this screen is on top, so its agents are the
- // ones worth the next reads.
+ // ⚠️ **The one screen that reads previews, and only once it is opened (owner, 2026-10-01).**
+ // Nothing reads them in the background any more — see `AppNotifier.sessionPreviews` — so a
+ // person who comes here has asked for them, and gets them for the recent agents at once
+ // rather than line by line as rows scroll in. Prioritised — this screen is on top, so its
+ // agents are the ones worth the next reads.
final notifier = widget.notifier;
notifier.sessionPreviews.warm([
for (final entry in recentAgents(agentIndex(notifier)))
diff --git a/mobile/lib/phone/phone_search_results.dart b/mobile/lib/phone/phone_search_results.dart
index 7e372b764..5ce98b191 100644
--- a/mobile/lib/phone/phone_search_results.dart
+++ b/mobile/lib/phone/phone_search_results.dart
@@ -7,8 +7,6 @@ import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/notify/agent_notice.dart' show NoticeKind;
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/state/external_session.dart';
-import 'package:harness_mobile/state/session_preview.dart'
- show SessionPreviewKey;
import 'agent_index.dart';
import 'desk_groups.dart';
@@ -148,40 +146,12 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) unawaited(notifier.reachAllMachines());
});
- // No warm of the previews here: each row asks for its own as it is built — see [_want].
- }
-
- /// The sessions whose rows this frame built, read once it is over — see [_want].
- final _wanted = <SessionPreviewKey>{};
- bool _warmScheduled = false;
-
- /// Asks for what [key]'s session last said, because its row is on screen or about to be — what
- /// the search matches a session's words against (`phone_search_rank.dart`), no longer drawn under
- /// the row: the recap that was, is gone (owner, 2026-09-30).
- ///
- /// ⚠️ **By the rows built, not the agents known.** Warming the first 32 agents by recency, as
- /// this did on open, read rows in an order Find does not draw them in — needs you, the frozen
- /// open order, paused last — and never reached a row past the 32nd: a list of a hundred sessions
- /// held two thirds of its previews empty however far it was scrolled. The list is lazy, so the rows
- /// built are the ones in view and the next few below; asked for top first and ahead of anything
- /// already queued, they fill in in the order they are read.
- ///
- /// After the frame, in one batch: warming mid-build would start reads from inside a layout, and a
- /// row at a time would reorder the store's queue once per row. Asked again on every rebuild —
- /// the store skips what is in flight or fresh, so that costs a lookup a row, and a row still on
- /// screen after [SessionPreviewStore.freshFor] is read again.
- void _want(SessionPreviewKey key) {
- _wanted.add(key);
- if (_warmScheduled) return;
- _warmScheduled = true;
- WidgetsBinding.instance.addPostFrameCallback((_) {
- _warmScheduled = false;
- final keys = _wanted.toList();
- _wanted.clear();
- if (mounted) {
- widget.notifier.sessionPreviews.warm(keys, prioritize: true);
- }
- });
+ // ⚠️ **No `agent_recent` reads from Find, not on open and not per row (owner, 2026-10-01).**
+ // Each row used to ask for its session's last words as it was built, so opening Find — or
+ // the app, which opens on it — put a read per visible session on the relay beside the
+ // terminal being attached. What a session said is found by the machines' own index
+ // (`session_search`, [PhoneSearchController.contentHitFor]); the store still answers from
+ // the live events and from whatever the agents list read. See `AppNotifier.sessionPreviews`.
}
@override
@@ -357,10 +327,9 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
final newHarness = widget.onNewHarness;
final project = search.projectMatch;
// ⚠️ **Built as they scroll in, not all at once.** Each entry makes its widget only when the
- // list asks for it, so a hundred sessions cost the rows in view: their state words, their lit
- // matches — and the read that fetches each one's preview ([_want]). An eager list did all
- // of that for every row on every rebuild, and this screen rebuilds on every preview the store
- // publishes.
+ // list asks for it, so a hundred sessions cost the rows in view: their state words and their
+ // lit matches. An eager list did that for every row on every rebuild, and this screen rebuilds
+ // on every preview the store publishes.
final items = <Widget Function()>[];
// Where each session's entry is, so a row keeps its own element when the ranking moves it.
final rowAt = <String, int>{};
@@ -450,12 +419,10 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
);
}
- /// One session's entry in the list: its row, and a read of what the session last said for the
- /// search to match against ([_want]).
+ /// One session's entry in the list: its row.
///
- /// ⚠️ **No recap under it any more (owner, 2026-09-30).** The row used to carry a chevron that
- /// unfolded the session's last reply beneath it; it was removed, and with it the room kept at the
- /// end of every first line for that chevron. The read stays — the search still needs the words.
+ /// ⚠️ **No recap under it any more (owner, 2026-09-30),** and no read of what the session last
+ /// said either (2026-10-01) — see the note at the end of [initState].
///
/// Keyed by the row's id — what [ListView.builder]'s `findChildIndexCallback` looks it up by — so
/// the row keeps its element when a match moves it up the list.
@@ -466,9 +433,6 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
Tty tty, {
required bool selected,
}) {
- if (row.isAgent) {
- if (row.previewKey case final key?) _want(key);
- }
return KeyedSubtree(
key: ValueKey(row.id),
child: _findRow(row, terms, now, tty, selected: selected),
@@ -756,10 +720,20 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
// walks exactly what the query returned, in the order the person was
// looking at when they tapped.
final search = widget.controller;
+ final tab = _tab(_tabs(search));
+ // ⚠️ **The tab picked here is the tab Home opens in (owner, 2026-10-01).** The chips narrowed
+ // this list to one tab, and the session tapped is that tab's — but Home chose its tab on its
+ // own, from the tab the phone was last in ([activeDeskGroup]), so a session that sits in two
+ // tabs opened in the other one, and the swipe then walked that tab's panes rather than the ones
+ // just looked at. Selected before the open, so the pager is built in it. Only for a session the
+ // tab holds, and never on All: there the phone's own last tab still decides.
+ if (tab != null && tab.holds(entry)) {
+ widget.notifier.selectDeskTab(tab.id);
+ }
openAgentPager(
context,
widget.notifier,
- phoneSearchAgentEntries(_narrowed(search.rows, _tab(_tabs(search)))),
+ phoneSearchAgentEntries(_narrowed(search.rows, tab)),
entry,
);
}
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dart
index 25096d5b5..0d63a43a7 100644
--- a/mobile/lib/phone/phone_shell.dart
+++ b/mobile/lib/phone/phone_shell.dart
@@ -133,6 +133,12 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
/// who was looking straight at it, with a network that would have answered at once.
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
+ if (state == AppLifecycleState.inactive) {
+ // The app switcher coming up is `inactive`, and a swipe there can end the app without it
+ // ever reaching `paused` — so the screens are kept here as well. See [AppNotifier.handleAppInactive].
+ widget.notifier.handleAppInactive();
+ return;
+ }
if (state == AppLifecycleState.paused) {
// The other half of the resume below: work that only makes sense in
// front of somebody stops here. The sockets are not touched — the OS
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 5a422962a..3510dcf52 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -40,6 +40,7 @@ import '../terminal/terminal_session.dart';
import '../terminal/remote_media_download.dart';
import '../widgets/engine_identity.dart' show allEngines, engineIdentity;
import 'dial_status.dart';
+import 'kept_screens.dart';
import 'retarget_refusal.dart';
import 'pane_layout_store.dart';
import 'session_preview.dart';
@@ -274,17 +275,23 @@ class AppNotifier extends ChangeNotifier {
final Map<String, Timer> _turnActivityWatchdogs = {};
/// What each agent was last asked and answered, as search matches it — the
- /// desktop's own store (see `session_preview.dart`), fed the same two ways:
- /// a small `agent_recent` read whenever the agent list arrives, and every
- /// turn event this socket carries, so a reply is findable the moment it lands.
+ /// desktop's own store (see `session_preview.dart`), fed by every turn event
+ /// this socket carries, so a reply is findable the moment it lands, and by an
+ /// `agent_recent` read ONLY where a screen asks for one (`agents_list_page.dart`).
+ ///
+ /// ⚠️ **No reads in the background, on purpose (owner, 2026-10-01).** It used
+ /// to be read for every agent whenever an agent list arrived (32 a machine, again
+ /// after every reconnect), for every agent a push updated, and for every row
+ /// Find drew — a hundred-odd reads at launch on one machine, and several hundred
+ /// on eight, all on the same relay socket as the terminal somebody was waiting
+ /// for. A launch measured with them showed that socket going silent for 4–7s
+ /// with the terminal's open queued behind them. What they fed is gone (the recap
+ /// under Find's rows) or answered by the machines themselves (`session_search`
+ /// finds what a session said), so the reads went and the store stayed.
///
/// Read again after [freshFor] at the soonest, not the desktop's minute: a
/// phone pays for the bytes, and the live events already keep a connected
/// machine's agents current.
- ///
- /// Four reads out at once, not the desktop's two: Find reads them as its rows come into view, so
- /// its search can match what each session said, and each read is one small relay round trip —
- /// two at a time left a screenful of rows waiting on the latency rather than on the bytes.
late final sessionPreviews = SessionPreviewStore(
canFetch: _canFetchPreview,
freshFor: const Duration(minutes: 5),
@@ -318,10 +325,6 @@ class AppNotifier extends ChangeNotifier {
);
}
- void _warmPreviews(MachineState machine) => sessionPreviews.warm(
- machine.agents.map((agent) => previewKey(machine.machine.machineId, agent)),
- );
-
/// Has the next warm re-read [agent]'s content when its machine says the
/// conversation moved since [before] — a turn this phone may have slept
/// through. Compared on the machine's own clock, so a phone whose clock
@@ -959,9 +962,15 @@ class AppNotifier extends ChangeNotifier {
PaneLayoutStore? paneLayoutStore,
SystemNotices? systemNotices,
MachineCache? machineCache,
+ KeptScreenStore? keptScreenStore,
GroupSync? groupSync,
this.turnActivityTimeout = const Duration(seconds: 12),
}) : _paneLayout = paneLayoutStore,
+ // On the machine cache's terms, below: a real app keeps screens on disk, a test only when
+ // it hands over a store of its own.
+ _keptScreenStore =
+ keptScreenStore ??
+ (paneLayoutStore == null ? null : KeptScreenStore()),
// On the same terms as the stores below: no layout store means a test,
// which must never reach the OS notification centre.
agentNotices = AgentAnnouncer(
@@ -1258,6 +1267,13 @@ class AppNotifier extends ChangeNotifier {
// than when that screen mounts — several state-file operations later, behind
// every one of their locks. See [LastOpenedAgent.prefetch].
lastOpenedAgent.prefetch();
+ // The screens kept from the last run, read beside it: the agent that record names is drawn
+ // from them the moment its tile exists. A tile attached before the read lands is drawn when
+ // it does ([_seedWaitingTiles]).
+ final keptScreens = _keptScreenStore;
+ if (keptScreens != null) {
+ unawaited(keptScreens.load().then((_) => _seedWaitingTiles()));
+ }
// Before the machines, deliberately: the tiles are intent, they render as
// "waiting for that machine" on their own, and each attaches as its machine
// answers. Waiting for the machine list first would leave the window empty
@@ -1382,6 +1398,10 @@ class AppNotifier extends ChangeNotifier {
pendingPairing = null;
_desk.reset();
zoo.reset();
+ _forgetLaunchHold();
+ // Signed out from elsewhere: the kept screens go as on a sign-out here (see [logout]).
+ _keptScreens.clear();
+ unawaited(_keptScreenStore?.clear());
unawaited(_pool?.closeAll());
_pool = null;
_lastError = message;
@@ -1485,6 +1505,7 @@ class AppNotifier extends ChangeNotifier {
unawaited(cliLogin.logout());
_stopAllOfflineRetries();
_stopAllAgentSyncTimers();
+ _forgetLaunchHold();
// Tiles go, the saved layout stays: signing out and back in is the same
// person at the same desk, and the file is only read once machines exist.
await _closeAllPanes(persist: false);
@@ -1518,6 +1539,8 @@ class AppNotifier extends ChangeNotifier {
// Not awaited: sign-out must not wait on a disk write, and the cache is only
// ever read after a sign-in that this clears the way for.
unawaited(_machineCache?.clear());
+ // The screens kept on disk are this account's terminals — they go with it, as the cache does.
+ unawaited(_keptScreenStore?.clear());
sessionPreviews.clear();
agentNotices.reset();
expandedMachines.clear();
@@ -1704,6 +1727,7 @@ class AppNotifier extends ChangeNotifier {
}
machineStates.removeWhere((id, _) => !visible.contains(id));
for (final machine in machines) {
+ final isNew = !machineStates.containsKey(machine.machineId);
final state = machineStates.update(
machine.machineId,
(state) => state..machine = machine,
@@ -1714,6 +1738,9 @@ class AppNotifier extends ChangeNotifier {
(state.nodeOnline == null || state.nodeOnline != reportedOnline)) {
unawaited(_applyNodeStatus(state, reportedOnline));
}
+ // The launch's machine may already be dialled with no state to report to — when this fetch
+ // beats the cache parse it was dialled ahead of. See [_adoptConnection].
+ if (isNew) _adoptConnection(state);
}
_autoConnectAndLoadMachines();
// The list that just landed is what the NEXT launch starts from. Never
@@ -2198,6 +2225,12 @@ class AppNotifier extends ChangeNotifier {
StartupTrace.mark('skipped offline machine ${machine.machineId}');
continue;
}
+ // Held until the launch's own terminal is up — see [_launchMachineId]. The cached ones were
+ // held by the warm start already; this catches the machines the cache did not know.
+ if (_heldForLaunch(machine.machineId)) {
+ _heldMachines.add(machine.machineId);
+ continue;
+ }
_connectMachine(state);
// ⚠️ **Only ask a machine that is already answering.** `_connectMachine`
// starts a dial; it does not finish one. Asking here regardless meant
@@ -2342,6 +2375,14 @@ class AppNotifier extends ChangeNotifier {
return _pool?[machineId]?.isReady == true;
}
+ /// [machineId]'s connection as the app already HOLDS it, or null — never one built for the
+ /// asking, for the same reason as [_connectionReady].
+ WsConn? _heldConnection(String machineId) {
+ final testConnection = connectionForTest;
+ if (testConnection != null) return testConnection(machineId);
+ return _pool?[machineId];
+ }
+
// Every machine hands over the same loopback (HTRL) frames: the relay codec has opened the E2EE
// envelope before a frame gets here (see `ws/relay_codec.dart`), so there is no per-machine
// branching left here at all.
@@ -2387,6 +2428,125 @@ class AppNotifier extends ChangeNotifier {
return _conn(machineId).sendTerminalBinary(encoded);
}
+ /// How long a `terminal_open` waits for its machine's handshake — see [_sendTerminalFrame].
+ /// The dial's own limit and a select's, near enough: past it the socket is not about to be up.
+ static const _openWaitsForHandshake = Duration(seconds: 15);
+
+ /// A terminal frame for [machineId]'s connection — a `terminal_open` held until the handshake
+ /// is done, every other frame sent (or refused) at once, as before.
+ ///
+ /// ⚠️ **Why the open waits (owner, 2026-10-01).** A launch builds its terminal from the cached
+ /// agent and capabilities, so the open is made while the socket is still handshaking, and the
+ /// socket refused it: the session gave up on it ("Could not send terminal_open"), and nothing
+ /// asked again until the machine answered `terminal_capabilities` or its agent list, which reattach
+ /// waiting panes — measured at 0.6–0.75s after the socket was ready, every launch. Held here
+ /// instead, it leaves the moment the handshake lands, with the request it was made with. Bounded:
+ /// a handshake that does not land in [_openWaitsForHandshake] refuses it as before, and the
+ /// usual reattach on connect takes over.
+ Future<bool> _sendTerminalFrame(
+ String machineId,
+ String type,
+ Map<String, dynamic> payload,
+ ) async {
+ final connection = _conn(machineId);
+ if (type == 'terminal_open' && !connection.isReady) {
+ try {
+ await connection.waitUntilReady(timeout: _openWaitsForHandshake);
+ } catch (_) {
+ // Timed out, or the connection was closed meanwhile: the socket refuses the frame below,
+ // which is the answer the session already knows how to take.
+ }
+ }
+ return connection.sendTerminalFrame(type, payload);
+ }
+
+ /// The machine a launch dials ALONE — the one the phone last had an agent open on — while every
+ /// other machine waits in [_heldMachines]; null once they have been let go, and on a launch that
+ /// had nothing to put first.
+ ///
+ /// ⚠️ **Why a launch dials one machine first (owner, 2026-10-01).** Every machine the account
+ /// had was dialled at once: a relay socket, an E2EE handshake, `terminal_capabilities`, a full
+ /// agent list and a P2P negotiation EACH, seven or eight of them on a phone, all in the same
+ /// second as the one terminal the person is waiting to see — which is on one machine. On one
+ /// machine a launch measured 3.3s to a ready socket; the work on the others added nothing anybody
+ /// was looking at. The rest are let go the moment that terminal shows its first frame
+ /// ([_releaseOnFirstFrame]), when Find opens ([reachAllMachines]), or after
+ /// [_heldMachinesRelease] whatever happens; and a machine is dialled the moment one of its own
+ /// agents is opened, held or not ([_conn] dials what it does not hold).
+ ///
+ /// What it costs: for those few seconds the other machines' sessions read from the cache, as
+ /// `connecting`, and anything they announce in that time (a finished turn, a question) arrives
+ /// as soon as they are dialled rather than at once.
+ String? _launchMachineId;
+ final Set<String> _heldMachines = {};
+ Timer? _heldMachinesTimer;
+ static const _heldMachinesRelease = Duration(seconds: 5);
+
+ /// Whether [machineId] is one the launch is holding back — see [_launchMachineId].
+ bool _heldForLaunch(String machineId) =>
+ _launchMachineId != null && machineId != _launchMachineId;
+
+ /// 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;
+ }
+ _connectMachine(state);
+ }
+ }
+
+ /// A state just made for a machine whose socket the app ALREADY holds — dialled before there was
+ /// a state to report to (`_warmStartMachines` dials the launch's machine ahead of the cache parse).
+ /// Whatever that socket said meanwhile went nowhere ([_onConnectionStatus] needs the state), so it
+ /// is said again here: a socket that is up replays its `connected`, which is what starts the agent
+ /// list, the sync timer and the rest; one still dialling is at least shown as dialling.
+ void _adoptConnection(MachineState state) {
+ final machineId = state.machine.machineId;
+ final connection = _pool?[machineId];
+ if (connection == null) return;
+ if (connection.isReady) {
+ _onConnectionStatus(machineId, ConnectionStatus.connected);
+ } else if (state.connectionStatus == ConnectionStatus.disconnected) {
+ state.connectionStatus = ConnectionStatus.connecting;
+ }
+ }
+
+ /// Drop the launch's hold without dialling anything — signing out, or the notifier going away.
+ void _forgetLaunchHold() {
+ _launchMachineId = null;
+ _heldMachines.clear();
+ _heldMachinesTimer?.cancel();
+ _heldMachinesTimer = null;
+ }
+
+ /// Let the held machines go once [terminal] shows its first frame — the screen a launch is for
+ /// is up, and nothing on it is waiting any more. See [_launchMachineId].
+ void _releaseOnFirstFrame(TerminalSession terminal) {
+ void check() {
+ if (!terminal.hasRenderedFrame) return;
+ terminal.removeListener(check);
+ _releaseHeldMachines('first terminal live');
+ }
+
+ terminal.addListener(check);
+ }
+
/// Start dialling last run's machines without waiting for `/api/machines`.
///
/// ⚠️ **The whole point is the socket, not the list.** A relay dial plus the
@@ -2417,10 +2577,98 @@ class AppNotifier extends ChangeNotifier {
final cache = _machineCache;
if (cache == null || _disposed) return;
final revision = _authRevision;
- final cached = await StartupTrace.time('boot.machineCache', cache.read);
- if (cached.isEmpty || _disposed || !_authWorkCurrent(revision)) return;
- // The fetch got there first — it is the truth, and this has nothing to add.
- if (machines.isNotEmpty || machineStates.isNotEmpty) return;
+ // 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.
+ final launchRead = lastOpenedAgent.prefetched;
+ final raw = await StartupTrace.time('boot.machineCacheRead', cache.readRaw);
+ if (raw == null || _disposed || !_authWorkCurrent(revision)) return;
+ AgentRef? launchAgent;
+ if (launchRead != null) {
+ try {
+ // Bounded: a record slower than the cache is not worth holding the dial for, and a launch
+ // without it simply dials everything, as it always did.
+ launchAgent = await launchRead.timeout(
+ const Duration(milliseconds: 300),
+ onTimeout: () => null,
+ );
+ } catch (_) {
+ launchAgent = null;
+ }
+ }
+ if (_disposed || !_authWorkCurrent(revision)) return;
+ final launchMachine = launchAgent?.machineId;
+ // ⚠️ **The launch's machine is dialled before the cache is parsed (owner, 2026-10-01).** A dial
+ // needs nothing but the id, and the parse of every agent of every machine is the longest step
+ // before it (273–629ms measured, more on a bigger account). Only when the text names that
+ // machine, which means this account had it, up, at the end of the last run — the cache keeps
+ // nothing else. The state for it is made below, from the parse, and adopts the socket
+ // ([_adoptConnection]); a parse that turns out not to list it closes the socket again.
+ //
+ // The hold on the other machines ([_launchMachineId]) starts here too, not after the parse:
+ // `/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;
+ _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 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() {
+ final machineId = dialledEarly;
+ if (machineId != null && !machineStates.containsKey(machineId)) {
+ unawaited(_pool?.closeMachine(machineId));
+ }
+ }
+
+ if (_disposed || !_authWorkCurrent(revision)) {
+ dropUnclaimedDial();
+ return;
+ }
+ 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');
+ 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');
+ }
+ 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 &&
+ !cached.any(
+ (entry) =>
+ entry.machine.machineId == first &&
+ entry.machine.authMode == MachineAuthMode.remote,
+ )) {
+ _releaseHeldMachines('launch machine not cached');
+ }
var warmed = 0;
var warmedAgents = 0;
final warmMachines = <Machine>[];
@@ -2494,10 +2742,20 @@ class AppNotifier extends ChangeNotifier {
// to have the socket ALREADY OPEN when that happens, which is where its
// second and a half comes from; the request itself was never the part
// worth racing.
- _connectMachine(state);
+ //
+ // 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);
+ } else {
+ _connectMachine(state);
+ // Its socket may have come up before this state existed — see `dialledEarly` above.
+ if (machine.machineId == dialledEarly) _adoptConnection(state);
+ }
warmMachines.add(machine);
warmed++;
}
+ dropUnclaimedDial();
if (warmed == 0) return;
// ⚠️ Published to `machines` as well, because every screen indexes agents
// through THAT list (`agentIndex`, `filterableMachines`) rather than through
@@ -2554,6 +2812,9 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
final connection = _conn(machine.machine.machineId);
final deadline = Stopwatch()..start();
+ // When the list was asked for — what a timeout is measured against, to tell a machine that
+ // went quiet from one that is answering everything else first (see the catch below).
+ DateTime? listAskedAt;
debugPrint('agents_list start: ${machine.machine.machineId}');
try {
const inventoryTimeout = Duration(seconds: 10);
@@ -2605,6 +2866,7 @@ class AppNotifier extends ChangeNotifier {
connection,
revision,
);
+ listAskedAt = DateTime.now();
final response = await StartupTrace.time(
'agents.list',
() => connection.request(
@@ -2660,7 +2922,20 @@ class AppNotifier extends ChangeNotifier {
} catch (error) {
if (!_machineWorkCurrent(machine, revision)) return;
machine.agentsRefreshing = false;
- if (error is WsRequestTimeout) {
+ final heard = connection.lastHeardFromMachineAt;
+ if (error is WsRequestTimeout &&
+ listAskedAt != null &&
+ heard != null &&
+ heard.isAfter(listAskedAt)) {
+ // ⚠️ **Slow, not gone (owner, 2026-10-01).** The machine sealed frames to this connection
+ // after the list was asked for, so its session is alive and the list is only behind the
+ // rest of its traffic. Read as offline, this took the machine down — its agents off every
+ // screen, the one on Home included — and redialled, which started the whole launch over
+ // on a relay already behind. Nothing is reported; the list is asked again shortly, while
+ // the cached one, if any, keeps standing in.
+ machine.agentsLoadError = null;
+ if (!hadAgents) _askSlowMachineAgain(machine, revision);
+ } else if (error is WsRequestTimeout) {
machine.agentsLoadError =
'Harness is offline — run harness start on that machine';
_recoverStaleSession(machine, connection);
@@ -2702,6 +2977,17 @@ class AppNotifier extends ChangeNotifier {
notifyListeners();
}
+ /// A machine whose list timed out while it was plainly alive — see the catch in
+ /// [_performMachineDataLoad] — is asked again after a short pause, rather than left to the
+ /// minute-long sync. Only a list never confirmed: a confirmed one stands until that sync.
+ void _askSlowMachineAgain(MachineState machine, int revision) {
+ Timer(const Duration(seconds: 2), () {
+ if (_disposed || !_machineWorkCurrent(machine, revision)) return;
+ if (machine.agentLoadStatus == AgentLoadStatus.loaded) return;
+ unawaited(_loadMachineData(machine, force: true));
+ });
+ }
+
/// An RPC timed out on a machine whose transport still calls itself connected:
/// take the machine down and dial it again.
///
@@ -2925,6 +3211,8 @@ class AppNotifier extends ChangeNotifier {
(agent) => !nextIds.contains(agent.id),
)) {
sessionPreviews.removeAgent(machine.machine.machineId, old.id);
+ // Gone from its machine's list: its kept screen is a terminal nobody can open again.
+ _keptScreenStore?.remove('${machine.machine.machineId}/${old.id}');
}
for (final agent in agents) {
sessionPreviews.retainAgent(
@@ -2960,7 +3248,7 @@ class AppNotifier extends ChangeNotifier {
machine.pendingProcessingSessions.remove(sessionId);
_markAgentProcessing(machine, agentId);
}
- _warmPreviews(machine);
+ // No preview reads from here — see [sessionPreviews].
}
void _upsertAgent(MachineState machine, Agent agent) {
@@ -2977,8 +3265,8 @@ class AppNotifier extends ChangeNotifier {
agent.id,
agent.sessionId,
);
+ // Marked, not read: the next screen that asks reads it again — see [sessionPreviews].
_staleIfMoved(machine, previous, agent);
- sessionPreviews.warm([previewKey(machine.machine.machineId, agent)]);
machine.sessionAgentIds.removeWhere((_, id) => id == agent.id);
final sessionId = agent.sessionId;
if (sessionId != null) {
@@ -3014,6 +3302,8 @@ class AppNotifier extends ChangeNotifier {
.where((agent) => agent.id != agentId)
.toList();
sessionPreviews.removeAgent(machine.machine.machineId, agentId);
+ _keptScreens.remove('${machine.machine.machineId}/$agentId');
+ _keptScreenStore?.remove('${machine.machine.machineId}/$agentId');
agentNotices.forgetAgent((
machineId: machine.machine.machineId,
agentId: agentId,
@@ -3032,7 +3322,8 @@ class AppNotifier extends ChangeNotifier {
final machineId = machine.machine.machineId;
for (final pane in allPanes.toList()) {
if (pane.machineId != machineId || pane.agentId != agentId) continue;
- await _detachSession(pane, sendClose: false);
+ // Not kept: the agent is deleted, and its screen was just forgotten above.
+ await _detachSession(pane, sendClose: false, keepScreen: false);
for (final swarm in swarms) {
swarm.remove(pane);
}
@@ -3212,6 +3503,9 @@ class AppNotifier extends ChangeNotifier {
// The same guard [_canFetchPreview] uses, and for the same reason: `_conn`
// would build one out of a null pool.
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');
await Future.wait([
for (final machine in machines) reloadMachineData(machine.machineId),
]);
@@ -4876,8 +5170,13 @@ class AppNotifier extends ChangeNotifier {
engineId: agent.engine,
client: phoneClientDescriptor(),
send: (type, payload) =>
- _conn(pane.machineId).sendTerminalFrame(type, payload),
+ _sendTerminalFrame(pane.machineId, type, payload),
sendBinary: (frame) => _sendTerminalBinary(pane.machineId, frame),
+ // What tells the open watchdog a SLOW machine from a gone one — see
+ // [TerminalSession.lastHeardFromMachine]. Read off the connection the pane
+ // already has, never one built for the asking.
+ lastHeardFromMachine: () =>
+ _heldConnection(pane.machineId)?.lastHeardFromMachineAt,
// ⚠️ **A socket that has not finished its handshake is not a stalled one,
// and forcing a reconnect on it destroys the dial that was about to
// succeed.** `terminal_open` can now be sent very early — the agent and
@@ -4907,9 +5206,19 @@ class AppNotifier extends ChangeNotifier {
);
pane.session = terminal;
// Back to an agent read a moment ago: its last screen, at once, until the stream's arrives.
- final kept = _keptScreens.remove('${pane.machineId}/${agent.id}');
- if (kept != null) terminal.seedScreen(kept);
+ final keptKey = '${pane.machineId}/${agent.id}';
+ final kept = _keptScreens.remove(keptKey);
+ if (kept != null) {
+ terminal.seedScreen(kept);
+ } else {
+ // Or the screen kept on disk — from a moment ago, or from the last run. See
+ // [_keptScreenStore]: this is what puts a launch's agent on screen before its machine answers.
+ final saved = _keptScreenStore?.read(keptKey);
+ if (saved != null) terminal.seedSnapshot(saved);
+ }
terminal.addListener(notifyListeners);
+ // The launch's held machines go once a terminal is live — see [_launchMachineId].
+ if (_launchMachineId != null) _releaseOnFirstFrame(terminal);
notifyListeners();
// Wait for the pane's actual measured viewport before asking the daemon to open anything.
// Sending the 80x24 fallback here used to make the daemon spawn the remote TTY (and render its
@@ -4924,20 +5233,25 @@ class AppNotifier extends ChangeNotifier {
Future<void> _detachSession(
TerminalPane pane, {
required bool sendClose,
+
+ /// False where the screen must not outlive the stream: a sign-out, a reset, a deleted agent.
+ bool keepScreen = true,
}) async {
final terminal = pane.session;
pane.session = null;
if (terminal == null) return;
terminal.removeListener(notifyListeners);
- // The screen as the reader left it, for the next time this agent opens — see [_keptScreens].
+ // The screen as the reader left it, for the next time this agent opens — see [_keptScreens],
+ // and [_keptScreenStore] for the next launch.
final agentId = pane.agentId;
- if (agentId != null && terminal.hasRenderedFrame) {
+ if (keepScreen && agentId != null && terminal.hasRenderedFrame) {
final key = '${pane.machineId}/$agentId';
_keptScreens.remove(key);
_keptScreens[key] = terminal.terminal;
while (_keptScreens.length > _keptScreenLimit) {
_keptScreens.remove(_keptScreens.keys.first);
}
+ _keepScreen(key, terminal);
}
if (sendClose) await terminal.close();
terminal.dispose();
@@ -5019,8 +5333,52 @@ class AppNotifier extends ChangeNotifier {
final _keptScreens = <String, Terminal>{};
static const _keptScreenLimit = 3;
+ /// The visible screens of the agents opened most recently, kept on disk for the NEXT launch as
+ /// well as this run — see [KeptScreenStore]. Where [_keptScreens] has no exact terminal for an
+ /// agent (it holds three, and nothing past a relaunch), this has the screen it showed. Null in
+ /// tests that do not hand one over.
+ final KeptScreenStore? _keptScreenStore;
+
+ /// [terminal]'s screen into [_keptScreenStore] under [key], when it has a live one to keep.
+ void _keepScreen(String key, TerminalSession terminal) {
+ final store = _keptScreenStore;
+ if (store == null) return;
+ final snapshot = terminal.snapshotForKeeping();
+ if (snapshot != null) store.put(key, snapshot);
+ }
+
+ /// Every tile's live screen into [_keptScreenStore], written now — the app is going to the
+ /// background, and a closed app keeps nothing it had not written.
+ void _keepLiveScreens() {
+ final store = _keptScreenStore;
+ if (store == null) return;
+ for (final pane in allPanes) {
+ final agentId = pane.agentId;
+ final terminal = pane.session;
+ if (agentId == null || terminal == null) continue;
+ _keepScreen('${pane.machineId}/$agentId', terminal);
+ }
+ unawaited(store.flush());
+ }
+
+ /// Draw a kept screen behind every tile that has nothing to show yet — the store's read lands a
+ /// moment into a launch, possibly after the launch's own tile was attached ([_attachSession] seeds
+ /// the ones attached after it).
+ void _seedWaitingTiles() {
+ final store = _keptScreenStore;
+ if (store == null || _disposed) return;
+ for (final pane in allPanes) {
+ final agentId = pane.agentId;
+ final terminal = pane.session;
+ if (agentId == null || terminal == null || terminal.hasScreen) continue;
+ final snapshot = store.read('${pane.machineId}/$agentId');
+ if (snapshot != null) terminal.seedSnapshot(snapshot);
+ }
+ }
+
Future<void> _closeAllPanes({bool persist = true}) async {
- // Everything closing at once is a sign-out or a reset: nothing of it is kept.
+ // Everything closing at once is a sign-out or a reset: nothing of it is kept — not in memory,
+ // and not on disk ([_detachSession]'s `keepScreen`).
_keptScreens.clear();
final open = allPanes.toList();
for (final swarm in swarms) {
@@ -5029,7 +5387,7 @@ class AppNotifier extends ChangeNotifier {
swarm.zoomedPaneId = null;
}
for (final pane in open) {
- await _detachSession(pane, sendClose: true);
+ await _detachSession(pane, sendClose: true, keepScreen: false);
}
if (persist) _persistLayout();
}
@@ -5719,7 +6077,18 @@ class AppNotifier extends ChangeNotifier {
/// The app went into a pocket: stop the reads that only make sense in front
/// of somebody. The sockets are left to the OS, which suspends them anyway —
/// [handleAppResumed] is what puts both back.
- void handleAppPaused() => _desk.pause();
+ ///
+ /// And keep every tile's screen on disk now ([_keepLiveScreens]): this is the last moment the app
+ /// is sure to run, since closing it from the app switcher starts by sending it here.
+ void handleAppPaused() {
+ _desk.pause();
+ _keepLiveScreens();
+ }
+
+ /// The app lost the foreground for a moment — the app switcher, a system sheet. Nothing stops;
+ /// only the screens are kept ([_keepLiveScreens]), because the switcher is where an app is
+ /// closed, and closing it there need not pass through [handleAppPaused] first.
+ void handleAppInactive() => _keepLiveScreens();
/// What the local CLI closing this machine's socket with [code] does to the
/// model — the `WsPool.onLocalFailure` path, without a socket.
@@ -5746,6 +6115,7 @@ class AppNotifier extends ChangeNotifier {
_closedHistory.clear();
_stopAllOfflineRetries();
_stopAllAgentSyncTimers();
+ _forgetLaunchHold();
_clearAllTurnActivity();
for (final pane in allPanes) {
pane.session?.removeListener(notifyListeners);
@@ -5755,6 +6125,7 @@ class AppNotifier extends ChangeNotifier {
swarm.panes.clear();
}
sessionPreviews.dispose();
+ _keptScreenStore?.dispose();
agentNotices.dispose();
_desk.dispose();
daemonHabits.dispose();
diff --git a/mobile/lib/state/kept_screens.dart b/mobile/lib/state/kept_screens.dart
new file mode 100644
index 000000000..63437bdf6
--- /dev/null
+++ b/mobile/lib/state/kept_screens.dart
@@ -0,0 +1,194 @@
+import 'dart:async';
+import 'dart:convert';
+import 'dart:io';
+
+import '../core/snapshot_store.dart';
+import '../terminal/screen_snapshot.dart';
+
+/// The last screens of the agents opened most recently, kept on the phone so the next open — in
+/// this run or the next — shows one at once instead of a skeleton while the stream attaches.
+///
+/// ⚠️ **Why the phone keeps terminal screens at all (owner, 2026-10-01).** A launch spends 2–3s
+/// reaching the machine before the first keyframe of the agent it reopens can arrive, and that
+/// floor is the network's: the relay dial, the E2EE handshake, the machine's answer. What the person
+/// sees in those seconds is the only part of it the phone decides. With the screen they left on
+/// disk, the agent is on screen in the first frames of the launch — stale by however long the app
+/// was closed, which the page's "Attaching…" says — and the live keyframe replaces it whole.
+///
+/// What it costs, and how it is bounded:
+/// - **A terminal's contents on the phone's disk.** Only the visible screen ([ScreenSnapshot]),
+/// only the last [capacity] agents and none older than [maxAge], in the app's CACHE directory —
+/// which iOS leaves out of iCloud backups and Android out of Auto Backup, and either may empty
+/// when space runs low, which costs nothing but a skeleton — and forgotten on sign-out ([clear]).
+/// - **Disk writes.** Batched ([_saveDelay]) and only when something changed; [flush] writes at
+/// once when the app goes to the background, where a closed app would otherwise lose them.
+class KeptScreenStore {
+ KeptScreenStore({SnapshotStore? store, DateTime Function()? now})
+ : _store = store ?? _defaultStore(),
+ _now = now ?? DateTime.now;
+
+ final SnapshotStore _store;
+ final DateTime Function() _now;
+
+ /// How many agents' screens are kept: the ones a launch, a swipe or Find is likely to open next.
+ /// The least recently kept goes first once there are more (owner, 2026-10-01: fifty — an account
+ /// of seven or eight machines at ten to twenty sessions each opens well past the first two dozen).
+ /// At a few kilobytes a screen, typically well under a megabyte in all.
+ static const capacity = 50;
+
+ /// How old a kept screen may be and still be shown (owner, 2026-10-01). Past it the screen says
+ /// too little about the agent now to stand in for it, and is dropped — on read and on load —
+ /// rather than kept on the phone for nothing.
+ static const maxAge = Duration(days: 7);
+
+ static const _version = 1;
+ static const _saveDelay = Duration(seconds: 2);
+
+ /// By key (`machineId/agentId`), least recently kept first — see [put].
+ final _screens = <String, ScreenSnapshot>{};
+
+ Future<void>? _loading;
+ bool _dirty = false;
+ bool _cleared = false;
+ Timer? _saveTimer;
+
+ /// Writes run one at a time, in the order asked for — a save and a [clear] racing otherwise
+ /// leave whichever finished last, and the clear must win.
+ Future<void> _writes = Future.value();
+
+ /// The screen kept for [key], or null — null too for one past [maxAge], which is dropped here.
+ ScreenSnapshot? read(String key) {
+ final snapshot = _screens[key];
+ if (snapshot == null) return null;
+ if (_isStale(snapshot)) {
+ remove(key);
+ return null;
+ }
+ return snapshot;
+ }
+
+ /// Whether [snapshot] is older than [maxAge]. Measured on this phone's clock, which also took it.
+ bool _isStale(ScreenSnapshot snapshot) =>
+ _now().difference(snapshot.savedAt) > maxAge;
+
+ /// Read the kept screens from disk, once. Screens [put] before it lands are newer and win.
+ Future<void> load() => _loading ??= _load();
+
+ Future<void> _load() async {
+ final raw = await _store.read();
+ if (raw == null || raw.isEmpty || _cleared) return;
+ try {
+ final decoded = jsonDecode(raw);
+ if (decoded is! Map || decoded['version'] != _version) return;
+ final screens = decoded['screens'];
+ if (screens is! List) return;
+ final loaded = <String, ScreenSnapshot>{};
+ var dropped = false;
+ for (final item in screens) {
+ if (item is! Map) continue;
+ final key = item['key'];
+ final snapshot = ScreenSnapshot.fromJson(item['screen']);
+ if (key is! String || key.isEmpty || snapshot == null) continue;
+ // Past [maxAge]: left out, and the file rewritten without it below.
+ if (_isStale(snapshot)) {
+ dropped = true;
+ continue;
+ }
+ loaded.remove(key);
+ loaded[key] = snapshot;
+ }
+ // What was put meanwhile is newer than anything on disk, so it goes after — taken out of
+ // [loaded] first, since a key already there would keep its old place in the order.
+ final newer = Map.of(_screens);
+ loaded.removeWhere((key, _) => newer.containsKey(key));
+ _screens
+ ..clear()
+ ..addAll(loaded)
+ ..addAll(newer);
+ if (_trim()) dropped = true;
+ if (dropped) _changed();
+ } on Object {
+ // An unreadable file is no kept screens: the next save replaces it.
+ }
+ }
+
+ /// Keep [snapshot] as [key]'s screen, as the most recent.
+ void put(String key, ScreenSnapshot snapshot) {
+ _cleared = false;
+ _screens.remove(key);
+ _screens[key] = snapshot;
+ _trim();
+ _changed();
+ }
+
+ /// Forget [key]'s screen — its agent was deleted, or its screen is past [maxAge].
+ void remove(String key) {
+ if (_screens.remove(key) == null) return;
+ _changed();
+ }
+
+ /// Something to write: soon, batched with whatever else changes meanwhile ([_saveDelay]).
+ void _changed() {
+ _dirty = true;
+ _saveTimer ??= Timer(_saveDelay, () {
+ _saveTimer = null;
+ unawaited(flush());
+ });
+ }
+
+ /// Write what changed, now.
+ Future<void> flush() {
+ _saveTimer?.cancel();
+ _saveTimer = null;
+ if (!_dirty) return _writes;
+ _dirty = false;
+ final contents = jsonEncode({
+ 'version': _version,
+ 'screens': [
+ for (final entry in _screens.entries)
+ {'key': entry.key, 'screen': entry.value.toJson()},
+ ],
+ });
+ return _writes = _writes.then((_) => _store.write(contents));
+ }
+
+ /// Forget every kept screen, in memory and on disk — signing out.
+ Future<void> clear() {
+ _cleared = true;
+ _saveTimer?.cancel();
+ _saveTimer = null;
+ _dirty = false;
+ _screens.clear();
+ return _writes = _writes.then((_) => _store.clear());
+ }
+
+ void dispose() {
+ _saveTimer?.cancel();
+ _saveTimer = null;
+ }
+
+ /// Down to [capacity], least recently kept first. Whether anything went.
+ bool _trim() {
+ var trimmed = false;
+ while (_screens.length > capacity) {
+ _screens.remove(_screens.keys.first);
+ trimmed = true;
+ }
+ return trimmed;
+ }
+
+ /// The real store, in the app's cache directory — see the class note. Resolved without a plugin,
+ /// the way `containerHome` is (`core/host_platform.dart`): iOS names `<container>/tmp`, whose
+ /// sibling `Library/Caches` is the cache; Android's temporary directory IS its cache directory.
+ static SnapshotStore _defaultStore() {
+ try {
+ final temporary = Directory.systemTemp.path;
+ final directory = Platform.isIOS
+ ? '${Directory.systemTemp.parent.path}/Library/Caches/harness'
+ : '$temporary/harness';
+ return FileSnapshotStore('kept-screens', directory: Directory(directory));
+ } on Object {
+ return MemorySnapshotStore();
+ }
+ }
+}
diff --git a/mobile/lib/terminal/screen_snapshot.dart b/mobile/lib/terminal/screen_snapshot.dart
new file mode 100644
index 000000000..41c933767
--- /dev/null
+++ b/mobile/lib/terminal/screen_snapshot.dart
@@ -0,0 +1,190 @@
+import 'dart:math' as math;
+
+import 'package:xterm/xterm.dart';
+
+/// What a terminal showed — its visible screen as the escape sequences that redraw it — kept so the
+/// next time its agent opens, even in the next run of the app, that screen is up at once while the
+/// live stream attaches (`AppNotifier._attachSession`, [TerminalSession.seedSnapshot]).
+///
+/// ⚠️ **The visible screen only, never the scrollback.** What it is for is the first frame of an
+/// open: a page that shows the reader's last view of the agent instead of a skeleton until the
+/// machine's keyframe lands, which then replaces it whole. Scrollback would multiply what is kept on
+/// the phone — a terminal's contents, written to its disk — for nothing that first frame shows.
+class ScreenSnapshot {
+ const ScreenSnapshot({
+ required this.cols,
+ required this.rows,
+ required this.ansi,
+ required this.savedAt,
+ });
+
+ final int cols;
+ final int rows;
+
+ /// The screen, as cursor moves, SGR runs and text — what a fresh terminal of [cols]×[rows] draws
+ /// back into the same screen.
+ final String ansi;
+ final DateTime savedAt;
+
+ /// The largest screen worth keeping. A terminal past this is not one a phone drew.
+ static const maxCols = 512;
+ static const maxRows = 256;
+
+ /// A screen whose redraw runs past this is dropped rather than kept: dense colour on a large
+ /// screen, and the store is meant to be small.
+ static const maxAnsiChars = 96 * 1024;
+
+ Map<String, dynamic> toJson() => {
+ 'cols': cols,
+ 'rows': rows,
+ 'ansi': ansi,
+ 'savedAt': savedAt.millisecondsSinceEpoch,
+ };
+
+ /// The stored shape, or null for anything else. Never throws.
+ static ScreenSnapshot? fromJson(Object? raw) {
+ if (raw is! Map) return null;
+ final cols = raw['cols'];
+ final rows = raw['rows'];
+ final ansi = raw['ansi'];
+ final savedAt = raw['savedAt'];
+ if (cols is! int || cols < 1 || cols > maxCols) return null;
+ if (rows is! int || rows < 1 || rows > maxRows) return null;
+ if (ansi is! String || ansi.isEmpty || ansi.length > maxAnsiChars) {
+ return null;
+ }
+ if (savedAt is! int) return null;
+ return ScreenSnapshot(
+ cols: cols,
+ rows: rows,
+ ansi: ansi,
+ savedAt: DateTime.fromMillisecondsSinceEpoch(savedAt),
+ );
+ }
+
+ /// [terminal]'s visible screen, or null when there is nothing worth keeping — an empty screen, an
+ /// impossible size, or a redraw past [maxAnsiChars].
+ ///
+ /// Row by row, each placed with its own cursor move rather than joined by newlines, so a full
+ /// row never wraps into the next and a blank one costs nothing. Trailing blank cells are left
+ /// out; every change of colour or attribute is a full SGR reset-and-set, which is longer than a
+ /// diff but cannot carry an attribute over by mistake.
+ static ScreenSnapshot? capture(Terminal terminal, {DateTime? now}) {
+ final cols = terminal.viewWidth;
+ final rows = terminal.viewHeight;
+ if (cols < 1 || rows < 1 || cols > maxCols || rows > maxRows) return null;
+ final buffer = terminal.buffer;
+ final top = math.max(0, buffer.height - rows);
+ final out = StringBuffer();
+ var drewAnything = false;
+ for (var row = 0; row < rows; row++) {
+ final index = top + row;
+ if (index >= buffer.height) break;
+ final line = buffer.lines[index];
+ var end = math.min(line.length, cols);
+ while (end > 0 && _isBlank(line, end - 1)) {
+ end--;
+ }
+ if (end == 0) continue;
+ drewAnything = true;
+ out.write('\x1b[${row + 1};1H');
+ int? foreground;
+ int? background;
+ int? attributes;
+ var afterWide = false;
+ for (var col = 0; col < end; col++) {
+ final codePoint = line.getCodePoint(col);
+ // The cell a wide character's second half occupies: the redraw writes that character and
+ // the terminal fills this cell itself.
+ if (afterWide && codePoint == 0) {
+ afterWide = false;
+ continue;
+ }
+ afterWide = line.getWidth(col) == 2;
+ final cellForeground = line.getForeground(col);
+ final cellBackground = line.getBackground(col);
+ final cellAttributes = line.getAttributes(col);
+ if (cellForeground != foreground ||
+ cellBackground != background ||
+ cellAttributes != attributes) {
+ out.write(_sgr(cellForeground, cellBackground, cellAttributes));
+ foreground = cellForeground;
+ background = cellBackground;
+ attributes = cellAttributes;
+ }
+ out.writeCharCode(codePoint == 0 ? 0x20 : codePoint);
+ }
+ out.write('\x1b[0m');
+ if (out.length > maxAnsiChars) return null;
+ }
+ if (!drewAnything) return null;
+ final cursorRow = (buffer.cursorY + 1).clamp(1, rows);
+ final cursorCol = (buffer.cursorX + 1).clamp(1, cols);
+ out.write('\x1b[$cursorRow;${cursorCol}H');
+ if (out.length > maxAnsiChars) return null;
+ return ScreenSnapshot(
+ cols: cols,
+ rows: rows,
+ ansi: out.toString(),
+ savedAt: now ?? DateTime.now(),
+ );
+ }
+
+ /// Whether the cell at [index] draws nothing: no character, the default background, and no
+ /// attribute that marks an empty cell (an inverse block, an underline).
+ static bool _isBlank(BufferLine line, int index) {
+ final codePoint = line.getCodePoint(index);
+ if (codePoint != 0 && codePoint != 0x20) return false;
+ if (line.getBackground(index) & CellColor.typeMask != CellColor.normal) {
+ return false;
+ }
+ const visibleWhenEmpty =
+ CellAttr.inverse | CellAttr.underline | CellAttr.strikethrough;
+ return line.getAttributes(index) & visibleWhenEmpty == 0;
+ }
+
+ /// A full reset followed by [attributes], [foreground] and [background] — see [capture].
+ static String _sgr(int foreground, int background, int attributes) {
+ final codes = <Object>[0];
+ if (attributes & CellAttr.bold != 0) codes.add(1);
+ if (attributes & CellAttr.faint != 0) codes.add(2);
+ if (attributes & CellAttr.italic != 0) codes.add(3);
+ if (attributes & CellAttr.underline != 0) codes.add(4);
+ if (attributes & CellAttr.blink != 0) codes.add(5);
+ if (attributes & CellAttr.inverse != 0) codes.add(7);
+ if (attributes & CellAttr.invisible != 0) codes.add(8);
+ if (attributes & CellAttr.strikethrough != 0) codes.add(9);
+ _color(codes, foreground, base: 30, bright: 90, extended: 38);
+ _color(codes, background, base: 40, bright: 100, extended: 48);
+ return '\x1b[${codes.join(';')}m';
+ }
+
+ /// [color] as SGR parameters — a named colour as 30–37/90–97 (or 40–47/100–107), a palette
+ /// index as `38;5;n`, a true colour as `38;2;r;g;b`, and the default as nothing (the reset before
+ /// it already put it back).
+ static void _color(
+ List<Object> codes,
+ int color, {
+ required int base,
+ required int bright,
+ required int extended,
+ }) {
+ final value = color & CellColor.valueMask;
+ switch (color & CellColor.typeMask) {
+ case CellColor.named:
+ codes.add(value < 8 ? base + value : bright + (value - 8));
+ case CellColor.palette:
+ codes.addAll([extended, 5, value]);
+ case CellColor.rgb:
+ codes.addAll([
+ extended,
+ 2,
+ (value >> 16) & 0xff,
+ (value >> 8) & 0xff,
+ value & 0xff,
+ ]);
+ default:
+ break;
+ }
+ }
+}
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index 13826c34f..3a7a4976a 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -8,6 +8,7 @@ import 'package:xterm/xterm.dart';
import '../core/crash_log.dart';
import 'control_chord.dart';
+import 'screen_snapshot.dart';
import 'terminal_binary.dart';
import 'terminal_input.dart';
import 'terminal_viewport.dart';
@@ -161,6 +162,11 @@ class TerminalSession extends ChangeNotifier {
/// spending it on a no-op.
final Future<bool> Function()? onOpenStalled;
+ /// When the transport last heard from this session's MACHINE — a frame it sealed, not the
+ /// relay's own (`WsConn.lastHeardFromMachineAt`). Null hook: the open watchdog keeps its old,
+ /// impatient rule (see [_openPatience]).
+ final DateTime? Function()? lastHeardFromMachine;
+
/// This client's own introduction, sent with every `terminal_open`; null
/// for a viewer that never takes control and so is never anyone's taker.
final TerminalClientDescriptor? client;
@@ -174,6 +180,7 @@ class TerminalSession extends ChangeNotifier {
required this.sendBinary,
this.client,
this.onOpenStalled,
+ this.lastHeardFromMachine,
this.resyncTimeout = const Duration(seconds: 4),
this.takeover = true,
}) {
@@ -294,6 +301,27 @@ class TerminalSession extends ChangeNotifier {
notifyListeners();
}
+ /// [snapshot] — a screen kept on the phone, from this run or an earlier one ([ScreenSnapshot]) —
+ /// drawn into a terminal built like this session's own, and shown as [seedScreen] shows one.
+ ///
+ /// Never over something better: a screen already on show (a live frame, or the exact terminal
+ /// kept from a moment ago) stays.
+ void seedSnapshot(ScreenSnapshot snapshot) {
+ if (hasScreen || _disposed) return;
+ final kept = _newTerminal(bindCallbacks: false)
+ ..resize(_clampCols(snapshot.cols), _clampRows(snapshot.rows))
+ ..write(snapshot.ansi);
+ seedScreen(kept);
+ }
+
+ /// This session's screen as a [ScreenSnapshot] to keep, or null with nothing live to keep — a
+ /// screen still standing in from a kept one is not news, and keeping it again would only
+ /// refresh its date.
+ ScreenSnapshot? snapshotForKeeping() {
+ if (_disposed || !hasRenderedFrame) return null;
+ return ScreenSnapshot.capture(terminal);
+ }
+
int _lastRenderedSeq = -1;
int _framesSinceAck = 0;
int _renderedSinceAckBytes = 0;
@@ -309,6 +337,21 @@ class TerminalSession extends ChangeNotifier {
int _resyncAttempts = 0;
int _autoReopenAttempts = 0;
bool _openStallRecovered = false;
+
+ /// When the open now in flight first left — kept through its resends, so its patience
+ /// ([_openPatience]) counts from the first ask rather than starting over at each one.
+ DateTime? _openSentAt;
+
+ /// How long an unanswered open waits while its machine is SILENT before [_handleOpenTimeout]
+ /// redials — and while the machine is answering other things, the longer [_openSlowPatience].
+ static const _openSilentPatience = Duration(seconds: 10);
+ static const _openSlowPatience = Duration(seconds: 20);
+
+ /// When this session last reopened itself after an open of this same device took its stream —
+ /// see [_takenBySelf]. Spaced by [_ownTakeoverCooldown].
+ DateTime? _ownTakeoverReopenedAt;
+ static const _ownTakeoverCooldown = Duration(seconds: 30);
+
bool _disposed = false;
int _generation = 0;
bool _remoteCursorVisible = true;
@@ -438,6 +481,7 @@ class TerminalSession extends ChangeNotifier {
_cursorBlinkPhaseVisible = true;
_resyncRequested = false;
_resyncAttempts = 0;
+ _openSentAt = null;
if (resetRecovery) {
_autoReopenAttempts = 0;
_openStallRecovered = false;
@@ -511,6 +555,7 @@ class TerminalSession extends ChangeNotifier {
transportLost('Could not send terminal_open');
return;
}
+ _openSentAt ??= DateTime.now();
// An immediate ready/keyframe can arrive before send() resolves. Its
// watchdog or live stream must not be replaced by an open timeout.
if (status != TerminalSessionStatus.opening || streamId != null) return;
@@ -527,6 +572,8 @@ class TerminalSession extends ChangeNotifier {
/// itself succeeded — the relay session was silently stale (ciphertext for a dead E2EE session gets
/// dropped, not rejected). Force a fresh dial and resend the SAME open request (same `requestId`, so
/// a late reply for the original still matches) before giving up.
+ ///
+ /// Unless the machine is only SLOW — see [_openPatience], which this waits out first.
Future<void> _handleOpenTimeout(
Map<String, dynamic> openPayload,
int generation,
@@ -536,6 +583,15 @@ class TerminalSession extends ChangeNotifier {
streamId != null) {
return;
}
+ final patience = _openPatience();
+ if (patience != null) {
+ _resyncTimer?.cancel();
+ _resyncTimer = Timer(
+ patience,
+ () => unawaited(_handleOpenTimeout(openPayload, generation)),
+ );
+ return;
+ }
final sent = await _recoverAndResend(openPayload, generation);
if (!_isCurrent(generation) ||
status != TerminalSessionStatus.opening ||
@@ -558,6 +614,37 @@ class TerminalSession extends ChangeNotifier {
);
}
+ /// How much longer the open in flight may go unanswered before [_handleOpenTimeout] treats its
+ /// session as stale and redials — null once it has waited long enough, or when there is no way to
+ /// tell ([lastHeardFromMachine] absent, or the open not sent yet): the old rule, no patience.
+ ///
+ /// ⚠️ **Why the watchdog waits now (owner, 2026-10-01).** It redialled four seconds after any
+ /// unanswered open, on the theory that only a session that went stale behind a live relay stays
+ /// that quiet. A launch measured on a busy machine said otherwise: the relay was slow — 5 to 7
+ /// seconds each way while it carried the launch's other traffic — and the redial made it worse
+ /// every time. It threw away every request in flight, started a fresh handshake and agent list
+ /// on top of what was queued, and resent the open, which then reached the machine TWICE (the
+ /// first copy had been on its way all along); the later copy took the terminal off the earlier
+ /// one and the screen sat taken over by its own phone. The terminal that answered in about 8
+ /// seconds was shown at 22, or not at all.
+ ///
+ /// So the redial waits for evidence: a machine that has sealed ANY frame to this connection since
+ /// the open left is alive and only behind, and gets [_openSlowPatience]; one that has said
+ /// nothing at all gets [_openSilentPatience] — still the stale session's cure, ten seconds in
+ /// rather than four. Counted from the open's first send, so a resend does not start the clock
+ /// again, and in steps no longer than [resyncTimeout].
+ Duration? _openPatience() {
+ final sentAt = _openSentAt;
+ final heard = lastHeardFromMachine;
+ if (sentAt == null || heard == null) return null;
+ final lastHeard = heard();
+ final answering = lastHeard != null && lastHeard.isAfter(sentAt);
+ final limit = answering ? _openSlowPatience : _openSilentPatience;
+ final left = limit - DateTime.now().difference(sentAt);
+ if (left <= Duration.zero) return null;
+ return left < resyncTimeout ? left : resyncTimeout;
+ }
+
/// Shared recovery for both open-failure paths (`send()` itself failing, and `terminal_ready` never
/// arriving): force a fresh transport dial (see `WsConn.forceReconnect`), then poll-resend — a forced
/// relay redial is a REAL network round trip (fresh E2EE handshake for a relayed machine), and
@@ -602,12 +689,28 @@ class TerminalSession extends ChangeNotifier {
if (_disposed) return false;
switch (type) {
case 'terminal_ready':
- if (status != TerminalSessionStatus.opening ||
+ // ⚠️ **A reply to the open this session gave up waiting for is still taken (owner,
+ // 2026-10-01).** [_handleOpenTimeout] ends an open nobody answered in `error`, and the reply
+ // used to be dropped when it came after all — on a slow relay it does, seconds later — so
+ // the stream the machine had just opened was left running for nobody while this session
+ // asked for another. Only for THAT open ([_openRequestId] is the last one sent) and only
+ // while nothing has replaced it: a reopen since has a new request id, and the reply to the
+ // old one is then rightly ignored.
+ final lateReply =
+ status == TerminalSessionStatus.error &&
+ errorCode == 'TERMINAL_RESYNC_TIMEOUT' &&
+ streamId == null;
+ if ((status != TerminalSessionStatus.opening && !lateReply) ||
payload['requestId'] != _openRequestId ||
payload['agentId'] != agentId ||
payload['protocolVersion'] != protocolVersion) {
return true;
}
+ if (lateReply) {
+ status = TerminalSessionStatus.opening;
+ errorCode = null;
+ errorMessage = null;
+ }
streamId = payload['streamId'] as String?;
if (streamId == null || streamId!.isEmpty) {
_fail('TERMINAL_READY_INVALID', 'Harness returned no stream id');
@@ -717,6 +820,7 @@ class TerminalSession extends ChangeNotifier {
linkMode = null;
_abortActiveUpload();
notifyListeners();
+ if (takenOver && _takenBySelf(takenOverBy)) _reopenAfterOwnTakeover();
return true;
case 'terminal_error':
final errorStream = payload['streamId'];
@@ -1688,6 +1792,41 @@ class TerminalSession extends ChangeNotifier {
notifyListeners();
}
+ /// Whether [by] — who took this stream — is this very device: the introduction it sends with
+ /// every open ([client]), by kind and name, and by machine where both name one.
+ bool _takenBySelf(TerminalClientDescriptor? by) {
+ final me = client;
+ if (me == null || by == null) return false;
+ if (by.kind != me.kind || by.name != me.name) return false;
+ final mine = me.machineId;
+ final theirs = by.machineId;
+ return mine == null || theirs == null || mine == theirs;
+ }
+
+ /// Taken over by an open of this same device: open again, politely, once.
+ ///
+ /// ⚠️ **A takeover is a person's to answer — except one this phone did to itself (owner,
+ /// 2026-10-01).** [takenOver] is a dead end on purpose (see `_paneNeedsAttach`): reopening it
+ /// automatically would have two apps trading one terminal back and forth. But an open of THIS
+ /// device can reach the machine after the one now showing — a copy of a resent open, delivered
+ /// late from a connection the phone had already dropped. It takes the terminal, its own
+ /// connection is gone a moment later, and the screen sat on "iPhone 16 Pro connected to this
+ /// terminal", taken by itself, with nobody holding the terminal at all. Measured at launch on a
+ /// slow relay, where it left the first screen on its skeleton until it was tapped.
+ ///
+ /// Polite ([takeover] false), so it never takes the terminal from anybody: free, it opens as
+ /// usual; held, it watches, with the band offering it back. And at most once per
+ /// [_ownTakeoverCooldown], because two phones can share a name, and against a daemon that
+ /// ignores the polite flag the two would otherwise take the terminal from each other for ever.
+ void _reopenAfterOwnTakeover() {
+ final now = DateTime.now();
+ final last = _ownTakeoverReopenedAt;
+ if (last != null && now.difference(last) < _ownTakeoverCooldown) return;
+ _ownTakeoverReopenedAt = now;
+ takeover = false;
+ unawaited(reopen());
+ }
+
/// A polite open was refused — see [takeover]. The same dead end as a stream that was taken
/// over, for the same reason: reopening is a person's call, never this session's.
void _heldElsewhere(String code) {
diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dart
index 170f34789..e3926d852 100644
--- a/mobile/lib/ws/ws_conn.dart
+++ b/mobile/lib/ws/ws_conn.dart
@@ -141,6 +141,19 @@ class WsConn {
bool get isReady => _ready && _channel != null;
+ /// When this connection last opened a frame its MACHINE sealed — proof the end-to-end session
+ /// with the machine is alive, as against the relay merely being up. Null until the first.
+ ///
+ /// ⚠️ **Sealed frames only, never the relay's own.** `node_status`, `machines_status` and the
+ /// handshake come from the backend, and keep coming while the session behind them is dead (the
+ /// machine's Harness restarted and dropped it); counted, they would make a stale session look
+ /// like a slow one. Read by a terminal's open watchdog (`TerminalSession.lastHeardFromMachine`)
+ /// and by the agent-list timeout, to tell a machine that is slow from one that is gone.
+ DateTime? get lastHeardFromMachineAt => _lastHeardFromMachineAt;
+ DateTime? _lastHeardFromMachineAt;
+
+ void _heardFromMachine() => _lastHeardFromMachineAt = DateTime.now();
+
/// Wait for this machine's handshake without queuing a request or changing
/// its timeout. Callers can then start independent RPCs with their own budgets.
Future<void> waitUntilReady({required Duration timeout}) {
@@ -370,6 +383,8 @@ class WsConn {
.then((_) async {
final local = codec == null ? bytes : codec.decodeBinary(bytes);
if (local == null) return;
+ // Every relay binary frame is sealed by the machine — see [lastHeardFromMachineAt].
+ if (codec != null) _heardFromMachine();
await _plugin?.observeWsBinary(local);
await onBinaryFrame?.call(local);
})
@@ -517,6 +532,9 @@ class WsConn {
}
final clear = 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].
+ if (payload['__e2e'] is Map) _heardFromMachine();
final plain = <String, dynamic>{
...clear,
'payload': (clear['payload'] as Map<String, dynamic>?) ?? {},
@@ -1075,6 +1093,8 @@ class _PluginHost implements TerminalTransportHost {
@override
Future<void> deliverBinary(Uint8List localFrame) async {
+ // Opened from the data channel with this session's keys: the machine's own, as on the relay.
+ _conn._heardFromMachine();
await _conn.onBinaryFrame?.call(localFrame);
}
}