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): open the launch terminal before the agent list

tony3973ce5386e4
diff --git a/mobile/lib/core/machine_cache.dart b/mobile/lib/core/machine_cache.dart
index d3f54eba8..d8592bb3c 100644
--- a/mobile/lib/core/machine_cache.dart
+++ b/mobile/lib/core/machine_cache.dart
@@ -202,8 +202,80 @@ class MachineCache {
/// Kept until the next [save] writes it out. Passing an empty list is
/// meaningful and is kept: a machine whose agents were all deleted should come
/// back empty next launch, not with the ones it had before.
- void rememberAgents(String machineId, List<Map<String, dynamic>> agents) =>
- _agents[machineId] = agents;
+ void rememberAgents(String machineId, List<Map<String, dynamic>> agents) {
+ _agents[machineId] = agents;
+ _unsaved = true;
+ }
+
+ /// Whether a list or an agent was remembered since the last [save] — what a
+ /// save made only to keep the file current asks first (`AppNotifier`'s
+ /// background write), so an unchanged run writes nothing.
+ bool get hasUnsaved => _unsaved;
+ bool _unsaved = false;
+
+ /// [agent] — one agent as the daemon sent it, in a push (`agent_synced`,
+ /// `agent_created`) or a reply that carries one — put in place of the agent
+ /// with its id in [machineId]'s list, or added at its end. Whether it was
+ /// added is returned: a list that GREW is the one change the next launch
+ /// cannot do without (see `AppNotifier`'s early save).
+ ///
+ /// ⚠️ **Why the list is amended between lists (owner, 2026-10-01).** It was
+ /// only ever written when a machine answered `agents_list`, which a phone asks
+ /// on connecting — so a harness made during a run was not in the file at the
+ /// end of it, and the next launch, reopening exactly that harness, had no
+ /// agent to draw a terminal for: it waited out the machine's whole list first.
+ /// Measured on 2 of 7 launches, both straight after making a harness.
+ ///
+ /// The same object `agents_list` carries — one shape on the wire, built by
+ /// one function in the CLI (`agentFrame.ts`) — so it is kept as it came. Not
+ /// for a machine this run has neither read from the file nor listed: there is
+ /// no list to amend, and one agent written as the whole of it would read back
+ /// as a machine that has nothing else.
+ bool rememberAgent(String machineId, Map<String, dynamic> agent) {
+ final list = _agents[machineId];
+ final id = agent['id'];
+ if (list == null || id is! String || id.isEmpty) return false;
+ // A fresh list rather than an edit: the one held may be the very list a
+ // caller handed [rememberAgents], and it is not this class's to change.
+ final next = List<Map<String, dynamic>>.of(list);
+ final at = next.indexWhere((item) => item['id'] == id);
+ if (at == -1) {
+ next.add(agent);
+ } else {
+ next[at] = agent;
+ }
+ _agents[machineId] = next;
+ _unsaved = true;
+ return at == -1;
+ }
+
+ /// [agentId]'s name in [machineId]'s list changed — `agent_renamed`, which
+ /// carries the name alone. A copy of its JSON with the new name; nothing for
+ /// an agent the list does not have.
+ void renameAgent(String machineId, String agentId, String name) {
+ final list = _agents[machineId];
+ if (list == null) return;
+ final at = list.indexWhere((item) => item['id'] == agentId);
+ if (at == -1 || list[at]['name'] == name) return;
+ _agents[machineId] = List<Map<String, dynamic>>.of(list)
+ ..[at] = {...list[at], 'name': name};
+ _unsaved = true;
+ }
+
+ /// [agentId] is gone from [machineId] — deleted, or stopped and waiting for
+ /// the next list to bring it back as such. Whether it was there is returned.
+ bool forgetAgent(String machineId, String agentId) {
+ final list = _agents[machineId];
+ if (list == null) return false;
+ final next = [
+ for (final item in list)
+ if (item['id'] != agentId) item,
+ ];
+ if (next.length == list.length) return false;
+ _agents[machineId] = next;
+ _unsaved = true;
+ return true;
+ }
/// Remember a machine's `terminal_capabilities` reply, as the daemon sent it.
///
@@ -254,6 +326,8 @@ class MachineCache {
},
],
});
+ // What was remembered is in [payload] now, whichever write lands last.
+ _unsaved = false;
return _queue(() => _store.write(payload));
}
@@ -262,6 +336,7 @@ class MachineCache {
Future<void> clear() {
_agents.clear();
_capabilities.clear();
+ _unsaved = false;
return _queue(_store.clear);
}
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 2e3eb0438..725749ab7 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -194,6 +194,8 @@ typedef _PageFacts = ({
TerminalSession? session,
TerminalSessionStatus? status,
bool rendered,
+ bool keptScreen,
+ bool keptFromEarlierRun,
String? agentName,
String? agentEngine,
AgentProject? agentProject,
@@ -701,6 +703,10 @@ class _TerminalPageState extends State<TerminalPage>
session: session,
status: session?.status,
rendered: session?.hasRenderedFrame ?? false,
+ // A kept screen can be drawn in after the session exists — the store's read lands a moment
+ // into a launch — and nothing else here moves when it is: see [_attaching].
+ keptScreen: session?.showingKeptScreen ?? false,
+ keptFromEarlierRun: session?.keptScreenFromEarlierRun ?? false,
agentName: agent?.displayName,
agentEngine: agent?.engine,
agentProject: agent?.displayProject,
@@ -962,6 +968,18 @@ class _TerminalPageState extends State<TerminalPage>
if (voiceStatus(widget.voice, tty) case final said?) {
return _StatusLine(text: said.text, color: said.color);
}
+ // Before the question lines: an answer read off a kept screen cannot be given until the stream
+ // it stands in for is up. The facts this page last built from, not a fresh read: the page
+ // rebuilds when the stream moves (`status` and `keptScreen` in [_PageFacts]), and this line
+ // rebuilds with every voice tick besides.
+ if (_attaching(_facts?.session)) {
+ return _StatusLine(
+ text: _keyboardRequested
+ ? 'attaching… · keyboard opens when live'
+ : 'attaching…',
+ color: tty.faint,
+ );
+ }
final view = _questionWatcher?.view;
if (view != null && !_answersTappable(view)) {
return _StatusLine(text: 'answer on screen', color: tty.yellow);
@@ -979,6 +997,21 @@ class _TerminalPageState extends State<TerminalPage>
return null;
}
+ /// Whether [session] is a kept screen standing in while its stream attaches — drawn like the live
+ /// terminal, and taking no key until the stream is up ([TerminalSession.acceptsInput]).
+ ///
+ /// ⚠️ **Said on the line above the mic, because nothing else says it (owner, 2026-10-01).** The
+ /// kept screen puts the agent on screen in the first frames of a launch, 2–4s before its stream
+ /// is live, and a tap in those seconds raised nothing — read as a terminal that would not focus.
+ /// The tap is not lost: the keyboard is asked for at once ([_raiseKeyboard]) and opens the moment
+ /// the pane stops being read-only. Only while the open is on its way: a stream that failed or
+ /// was taken has its own answer to a tap ([_takeControl]).
+ static bool _attaching(TerminalSession? session) =>
+ session != null &&
+ session.showingKeptScreen &&
+ !session.watching &&
+ session.status == TerminalSessionStatus.opening;
+
/// Whether the open question's answers are bands to tap in the terminal right now — not under
/// the keyboard, where a tap on the pane is xterm's.
///
@@ -1480,6 +1513,10 @@ class _TerminalPageState extends State<TerminalPage>
// Typing is not scrolling: the chrome has no reason to be out of the way,
// and the header holds the controls somebody reaches for next.
_chrome.reveal();
+ // Before the stream is live the pane is read-only, so the keyboard asked for below opens only
+ // once it is up — felt now, and said above the mic meanwhile ([_attaching]), so the wait is
+ // not taken for a tap that missed.
+ if (!session.acceptsInput) HapticFeedback.selectionClick();
final heard = await widget.voice.takeTranscript();
if (!mounted) return;
if (heard.isNotEmpty && session.acceptsInput) {
@@ -2089,6 +2126,19 @@ class _TerminalPageState extends State<TerminalPage>
if (session != null && !session.hasScreen)
Positioned.fill(
child: _Attaching(key: _skeletonKey),
+ )
+ // A screen an EARLIER run kept stands in for only part of the
+ // pane: the skeleton takes the rest until the keyframe lands — see
+ // [_KeptScreenCover]. The same skeleton, by key, so one that was
+ // showing before the kept screen was read in keeps its sweep. Not
+ // over [_AgentGone], which owns the body when the agent is gone.
+ else if (!agentGone &&
+ session != null &&
+ session.keptScreenFromEarlierRun)
+ Positioned.fill(
+ child: _KeptScreenCover(
+ skeleton: _Attaching(key: _skeletonKey),
+ ),
),
// The mic and Search, floating in the
// terminal's bottom-right corner — see
@@ -2698,6 +2748,86 @@ class _AgentGone extends StatelessWidget {
);
}
+/// What covers a kept screen from an EARLIER run while its stream attaches: the [skeleton] over the
+/// lower [share] of the pane, the screen above fading into it.
+///
+/// ⚠️ **Part of the screen, not all of it, and on purpose (owner, 2026-10-01).** The whole kept
+/// screen put the agent up in the first frames of a launch looking exactly as if it were live, for
+/// the two or three seconds it was not — a prompt that took no key, output minutes or hours old: a
+/// session made to look ready while it was still loading. The upper half still says which harness
+/// this is and where it had got to; the lower half — the newest output and the prompt, the part
+/// most likely to have moved and the part that cannot be used yet — is the skeleton the session is
+/// coming back into. The keyframe replaces both whole, as it always did.
+///
+/// Only a screen an earlier run kept ([TerminalSession.keptScreenFromEarlierRun]): one this run kept
+/// a moment ago, swiped back to, is fresh enough to stand in whole, and a skeleton flashing over it
+/// for the half second its keyframe takes would be noise.
+///
+/// Taps go through it ([IgnorePointer]): under the skeleton is the kept prompt, and a tap there asks
+/// for the keyboard as it always does, which opens once the stream is live — see `_raiseKeyboard`.
+class _KeptScreenCover extends StatelessWidget {
+ const _KeptScreenCover({required this.skeleton});
+
+ final Widget skeleton;
+
+ /// How much of the pane the skeleton takes, from the bottom up.
+ static const share = 0.5;
+
+ /// The fade above it, in the terminal's own rows: deep enough that a row the edge crosses fades
+ /// out rather than being cut through, shallow enough to leave the half above it readable.
+ static const fadeRows = 2.0;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final style = terminalFontStore.value;
+ final fade = style.fontSize * style.height * fadeRows;
+ // The terminal's own ground, resolved as [TerminalPanel] and [_Attaching] resolve it, so the
+ // fade ends in exactly the colour the skeleton starts with — no seam where the two meet.
+ final ground = terminalScreenThemeFor(
+ AppTheme.palette.value,
+ terminalThemeStore.value,
+ ).background;
+ return IgnorePointer(
+ child: LayoutBuilder(
+ builder: (context, constraints) {
+ final height = constraints.maxHeight;
+ // Laid out in the pane's Stack, which is always bounded; anything else draws nothing
+ // rather than a skeleton of infinite height.
+ if (!height.isFinite) return const SizedBox.shrink();
+ final cover = height * share;
+ // Never taller than the room above the skeleton — a pane squeezed by the keyboard.
+ final edge = fade < height - cover ? fade : height - cover;
+ return Align(
+ alignment: Alignment.bottomCenter,
+ child: SizedBox(
+ height: cover + edge,
+ child: Column(
+ children: [
+ SizedBox(
+ height: edge,
+ width: double.infinity,
+ child: DecoratedBox(
+ decoration: BoxDecoration(
+ gradient: LinearGradient(
+ begin: Alignment.topCenter,
+ end: Alignment.bottomCenter,
+ colors: [ground.withValues(alpha: 0), ground],
+ ),
+ ),
+ ),
+ ),
+ Expanded(child: skeleton),
+ ],
+ ),
+ ),
+ );
+ },
+ ),
+ );
+ }
+}
+
/// The terminal's body while its first keyframe is still crossing the network.
///
/// ⚠️ **A skeleton here, not a spinner, because the shape IS known** — that is
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 1067023f0..15af5ae71 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -1895,10 +1895,26 @@ class AppNotifier extends ChangeNotifier {
if (machine.terminalCapabilityUnanswered) {
unawaited(_loadTerminalCapabilities(machine, connection, revision));
}
- final agents = (response['agents'] as List<dynamic>? ?? [])
+ final rawAgents = response['agents'] as List<dynamic>? ?? const [];
+ final agents = rawAgents
.map((item) => Agent.fromJson(item as Map<String, dynamic>))
.toList();
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
+ // with the app leaving the screen — see [_saveMachineCacheSoon].
+ final cache = _machineCache;
+ if (cache != null) {
+ final had = {for (final agent in machine.agents) agent.id};
+ cache.rememberAgents(machineId, [
+ for (final item in rawAgents)
+ if (item is Map<String, dynamic>) item,
+ ]);
+ if (agents.length != had.length ||
+ !agents.every((agent) => had.contains(agent.id))) {
+ _saveMachineCacheSoon();
+ }
+ }
_replaceAgents(machine, agents);
notifyListeners();
} on WsRequestTimeout {
@@ -2665,6 +2681,63 @@ class AppNotifier extends ChangeNotifier {
terminal.addListener(check);
}
+ /// The longest a launch's agent list waits for the terminal on screen — see
+ /// [_yieldToLaunchTerminal].
+ static const _launchListYield = Duration(milliseconds: 1500);
+
+ /// Let the terminal on screen answer before [machine]'s agent list is asked for — at launch only.
+ ///
+ /// ⚠️ **Why the list waits (owner, 2026-10-01).** The terminal a launch reopens and the machine's
+ /// agent list left on the same connection in the same instant, and the terminal came second: on
+ /// every launch measured (ten of ten) its `terminal_ready` arrived in the same second as the
+ /// list's reply, which took 1.1–3.0s for 134 agents. The machine builds that reply for every
+ /// agent at once, stopped ones included (`agents_list` in the CLI's `backendSocket.ts`), and the
+ /// one stream somebody was waiting to type into queued behind it — while the kept screen made
+ /// the terminal look ready from the first frames of the launch, and a tap on it raised nothing.
+ ///
+ /// Nothing on screen needs the list first: a launch draws from last run's
+ /// ([MachineState.agentsFromCache]), which is also what limits this to a launch — a reconnect
+ /// already has a confirmed list, and asks at once as it always did. Over the moment the terminal
+ /// shows its first live frame or stops opening (failed, taken, gone), and after
+ /// [_launchListYield] whatever happens: the list never waits on a terminal that is not coming.
+ ///
+ /// What it costs: for up to that long, an agent deleted elsewhere since the last run is still
+ /// drawn (`_AgentGone` in `terminal_page.dart` needs the real list), and the list's news — a new
+ /// agent, a rename — arrives that much later.
+ Future<void> _yieldToLaunchTerminal(MachineState machine) async {
+ if (!machine.agentsFromCache) return;
+ final pane = focusedPane;
+ final terminal = pane?.session;
+ if (pane == null ||
+ terminal == null ||
+ pane.machineId != machine.machine.machineId) {
+ return;
+ }
+ // `controlling` without a frame is a `terminal_ready` whose keyframe is on its way: still worth
+ // the wait, the screen is not live until it lands.
+ bool over() {
+ if (terminal.hasRenderedFrame) return true;
+ final status = terminal.status;
+ return status != TerminalSessionStatus.opening &&
+ status != TerminalSessionStatus.controlling;
+ }
+
+ if (over()) return;
+ final done = Completer<void>();
+ void check() {
+ if (!done.isCompleted && over()) done.complete();
+ }
+
+ // A session closed meanwhile never notifies again; this is what ends the wait then.
+ final timer = Timer(_launchListYield, () {
+ if (!done.isCompleted) done.complete();
+ });
+ terminal.addListener(check);
+ await done.future;
+ timer.cancel();
+ terminal.removeListener(check);
+ }
+
/// Start dialling last run's machines without waiting for `/api/machines`.
///
/// ⚠️ **The whole point is the socket, not the list.** A relay dial plus the
@@ -2984,6 +3057,10 @@ class AppNotifier extends ChangeNotifier {
connection,
revision,
);
+ // The launch's own terminal first — see [_yieldToLaunchTerminal]. Outside [remaining]: the
+ // wait is the phone's choice, not the machine being slow to answer.
+ await _yieldToLaunchTerminal(machine);
+ if (!_machineWorkCurrent(machine, revision)) return;
listAskedAt = DateTime.now();
final response = await StartupTrace.time(
'agents.list',
@@ -3369,7 +3446,14 @@ class AppNotifier extends ChangeNotifier {
// No preview reads from here — see [sessionPreviews].
}
- void _upsertAgent(MachineState machine, Agent agent) {
+ /// [json] is [agent] as the daemon sent it, where the caller has it: kept for the next launch
+ /// ([_cacheAgentJson]).
+ void _upsertAgent(
+ MachineState machine,
+ Agent agent, {
+ Map<String, dynamic>? json,
+ }) {
+ if (json != null) _cacheAgentJson(machine, json);
final index = machine.agents.indexWhere((item) => item.id == agent.id);
final previous = index == -1 ? null : machine.agents[index];
agent = retainNewerGitContext(agent, previous);
@@ -3409,6 +3493,8 @@ class AppNotifier extends ChangeNotifier {
final cleanName = name.trim();
machine.agents = [...machine.agents]
..[index] = machine.agents[index].copyWith(name: cleanName);
+ // Written with the rest when the app leaves the screen — see [_keepMachineCache].
+ _machineCache?.renameAgent(machine.machine.machineId, agentId, cleanName);
for (final pane in panesFor(machine.machine.machineId)) {
if (pane.agentId != agentId) continue;
pane.session?.renameAgent(cleanName);
@@ -3419,6 +3505,12 @@ class AppNotifier extends ChangeNotifier {
machine.agents = machine.agents
.where((agent) => agent.id != agentId)
.toList();
+ // Out of the next launch's list too, and soon: reopening a harness that is gone is the one
+ // thing a stale entry would do — see [_saveMachineCacheSoon].
+ if (_machineCache?.forgetAgent(machine.machine.machineId, agentId) ??
+ false) {
+ _saveMachineCacheSoon();
+ }
sessionPreviews.removeAgent(machine.machine.machineId, agentId);
_keptScreens.remove('${machine.machine.machineId}/$agentId');
_keptScreenStore?.remove('${machine.machine.machineId}/$agentId');
@@ -4230,16 +4322,20 @@ class AppNotifier extends ChangeNotifier {
if (raw is! Map || raw['id'] is! String || (raw['id'] as String).isEmpty) {
return unconfirmed;
}
+ final Map<String, dynamic> json;
final Agent agent;
try {
- agent = Agent.fromJson(Map<String, dynamic>.from(raw));
+ json = Map<String, dynamic>.from(raw);
+ agent = Agent.fromJson(json);
} catch (_) {
return unconfirmed;
}
creation._agentId = agent.id;
creation._complete(null);
if (_disposed || machineStates[machineId] != machine) return null;
- _upsertAgent(machine, agent);
+ // Into the next launch's list at once — the harness just made is the one most likely to be
+ // reopened by it. See [_cacheAgentJson].
+ _upsertAgent(machine, agent, json: json);
// ⚠️ Read from the AGENT the machine answered with, not from what was asked for. "New project"
// and a clone send no `cwd` at all — the folder is whatever the machine made — so taking it
// from the request would record nothing for exactly the two sources that produce a folder
@@ -4526,9 +4622,11 @@ class AppNotifier extends ChangeNotifier {
}
final raw = result['agent'];
if (raw is! Map || raw['id'] != stopped.id) return unconfirmed;
+ final Map<String, dynamic> json;
final Agent resumed;
try {
- resumed = Agent.fromJson(Map<String, dynamic>.from(raw));
+ json = Map<String, dynamic>.from(raw);
+ resumed = Agent.fromJson(json);
} catch (_) {
return unconfirmed;
}
@@ -4547,7 +4645,7 @@ class AppNotifier extends ChangeNotifier {
if (_disposed || machineStates[machine.machine.machineId] != machine) {
return const RestartAgentResult();
}
- _upsertAgent(machine, resumed);
+ _upsertAgent(machine, resumed, json: json);
notifyListeners();
return const RestartAgentResult();
}
@@ -4588,7 +4686,8 @@ class AppNotifier extends ChangeNotifier {
final raw = result['agent'];
if (raw is Map) {
try {
- _upsertAgent(machine, Agent.fromJson(Map<String, dynamic>.from(raw)));
+ final json = Map<String, dynamic>.from(raw);
+ _upsertAgent(machine, Agent.fromJson(json), json: json);
notifyListeners();
} catch (_) {
// Malformed reply agent — harmless, the CLI's own agent_synced push still lands.
@@ -5332,7 +5431,12 @@ class AppNotifier extends ChangeNotifier {
// 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);
+ if (saved != null) {
+ terminal.seedSnapshot(
+ saved,
+ fromEarlierRun: saved.savedAt.isBefore(_runStartedAt),
+ );
+ }
}
terminal.addListener(notifyListeners);
// The launch's held machines go once a terminal is live — see [_launchMachineId].
@@ -5457,6 +5561,12 @@ class AppNotifier extends ChangeNotifier {
/// tests that do not hand one over.
final KeptScreenStore? _keptScreenStore;
+ /// When this run began, near enough: the notifier is built at the start of the launch, and this
+ /// run keeps no screen before its first live frame. A kept screen saved before it is an EARLIER
+ /// run's — the one a launch draws, which the page shows only part of
+ /// ([TerminalSession.keptScreenFromEarlierRun]).
+ final DateTime _runStartedAt = DateTime.now();
+
/// [terminal]'s screen into [_keptScreenStore] under [key], when it has a live one to keep.
void _keepScreen(String key, TerminalSession terminal) {
final store = _keptScreenStore;
@@ -5479,6 +5589,61 @@ class AppNotifier extends ChangeNotifier {
unawaited(store.flush());
}
+ /// [json] — one agent as the daemon sent it — into the machine cache's copy of [machine]'s list,
+ /// for the next launch to draw from ([MachineCache.rememberAgent]). A harness NEW to that list is
+ /// written out in a moment ([_saveMachineCacheSoon]); any other change waits for the app to leave
+ /// the screen ([_keepMachineCache]).
+ void _cacheAgentJson(MachineState machine, Map<String, dynamic> json) {
+ final cache = _machineCache;
+ if (cache == null) return;
+ if (cache.rememberAgent(machine.machine.machineId, json)) {
+ _saveMachineCacheSoon();
+ }
+ }
+
+ /// When the machine cache goes out after a harness was added to or removed from it — see
+ /// [_saveMachineCacheSoon].
+ Timer? _machineCacheSaveTimer;
+ static const _machineCacheSaveDelay = Duration(seconds: 3);
+
+ /// Write the machine cache in [_machineCacheSaveDelay], not only when the app leaves the screen.
+ ///
+ /// ⚠️ **For a harness made or deleted — not for every push.** The background write
+ /// ([_keepMachineCache]) is the one that matters, and it is enough for everything else: a status, a
+ /// title, a branch drawn a run late costs nothing, the machine's list replaces it a second in.
+ /// A harness missing from the list costs the launch that reopens it its whole head start (the
+ /// terminal waits for that list — see [MachineCache.rememberAgent]), and an app closed without
+ /// passing through the background — killed from a debugger, or crashed — would lose it. Made
+ /// rarely and by hand, so writing for each is a few writes an hour; the delay lets the pushes
+ /// that follow a creation (its name, its terminal coming up) land in the same write. Not
+ /// re-armed by them: the first change starts the clock.
+ void _saveMachineCacheSoon() {
+ if (_machineCacheSaveTimer != null || _disposed) return;
+ _machineCacheSaveTimer = Timer(_machineCacheSaveDelay, _keepMachineCache);
+ }
+
+ /// The machine cache written out if anything in it changed since it last was — the agents this
+ /// run learned one at a time, between lists ([MachineCache.hasUnsaved]). Called as the app leaves
+ /// the screen, beside [_keepLiveScreens], and by [_saveMachineCacheSoon]. Never awaited, and
+ /// nothing when nothing changed: an idle run writes nothing.
+ void _keepMachineCache() {
+ _machineCacheSaveTimer?.cancel();
+ _machineCacheSaveTimer = null;
+ final cache = _machineCache;
+ if (cache == null || _disposed || !cache.hasUnsaved) 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,
+ ),
+ );
+ }
+
/// 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).
@@ -5490,7 +5655,12 @@ class AppNotifier extends ChangeNotifier {
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);
+ if (snapshot != null) {
+ terminal.seedSnapshot(
+ snapshot,
+ fromEarlierRun: snapshot.savedAt.isBefore(_runStartedAt),
+ );
+ }
}
}
@@ -5881,8 +6051,9 @@ class AppNotifier extends ChangeNotifier {
final raw = payload['agent'];
if (raw is Map) {
try {
- final agent = Agent.fromJson(Map<String, dynamic>.from(raw));
- _upsertAgent(machine, agent);
+ final json = Map<String, dynamic>.from(raw);
+ final agent = Agent.fromJson(json);
+ _upsertAgent(machine, agent, json: json);
if (agent.terminalAvailable) {
// A pane created before this agent's terminal was verified is still sitting on
// "Attaching…" with no session — nothing else re-checks it once agentLoadStatus is
@@ -5912,8 +6083,9 @@ class AppNotifier extends ChangeNotifier {
final raw = payload['agent'];
if (raw is Map && raw['terminal'] is Map) {
try {
- final agent = Agent.fromJson(Map<String, dynamic>.from(raw));
- _upsertAgent(machine, agent);
+ final json = Map<String, dynamic>.from(raw);
+ final agent = Agent.fromJson(json);
+ _upsertAgent(machine, agent, json: json);
// Same reattach as `agent_synced` above — a pane can be waiting on this exact agent
// (e.g. one this window's own New Agent dialog just opened) with no session yet.
// A push about an agent created elsewhere.
@@ -6208,12 +6380,18 @@ class AppNotifier extends ChangeNotifier {
void handleAppPaused() {
_desk.pause();
_keepLiveScreens();
+ // The agents this run learned between lists, for the next launch — see [_keepMachineCache].
+ _keepMachineCache();
}
/// The app lost the foreground for a moment — the app switcher, a system sheet. Nothing stops;
- /// only the 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();
+ /// only the screens and the machine cache are kept ([_keepLiveScreens], [_keepMachineCache]),
+ /// because the switcher is where an app is closed, and closing it there need not pass through
+ /// [handleAppPaused] first.
+ void handleAppInactive() {
+ _keepLiveScreens();
+ _keepMachineCache();
+ }
/// What the local CLI closing this machine's socket with [code] does to the
/// model — the `WsPool.onLocalFailure` path, without a socket.
@@ -6241,6 +6419,8 @@ class AppNotifier extends ChangeNotifier {
_stopAllOfflineRetries();
_stopAllAgentSyncTimers();
_forgetLaunchHold();
+ _machineCacheSaveTimer?.cancel();
+ _machineCacheSaveTimer = null;
_clearAllTurnActivity();
for (final pane in allPanes) {
pane.session?.removeListener(notifyListeners);
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index 3a7a4976a..7fee84176 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -283,8 +283,15 @@ class TerminalSession extends ChangeNotifier {
/// Something to show: this attach's first frame, or a kept screen standing in for it.
bool get hasScreen => hasRenderedFrame || _showingKeptScreen;
+ /// Whether the kept screen on show ([showingKeptScreen]) was kept by an EARLIER run of the app —
+ /// what a launch draws while it reconnects — rather than by this one, a swipe or a moment ago.
+ /// The phone draws only part of such a screen — see `_KeptScreenCover` in `terminal_page.dart`.
+ bool get keptScreenFromEarlierRun =>
+ _showingKeptScreen && _keptFromEarlierRun;
+ bool _keptFromEarlierRun = false;
+
/// Shows [kept] — the screen this agent had when the phone last left it — until the live stream's
- /// first keyframe lands and replaces it.
+ /// first keyframe lands and replaces it. [fromEarlierRun]: see [keptScreenFromEarlierRun].
///
/// ⚠️ **What makes switching back to an agent instant.** An attach waits a network round trip for
/// its keyframe; until then the page showed a skeleton. The kept screen is what the reader last
@@ -293,11 +300,12 @@ class TerminalSession extends ChangeNotifier {
///
/// Rebound to this session: the kept terminal's callbacks still named the session it came from,
/// which is gone.
- void seedScreen(Terminal kept) {
+ void seedScreen(Terminal kept, {bool fromEarlierRun = false}) {
if (hasRenderedFrame || _disposed) return;
_bindTerminal(kept);
terminal = kept;
_showingKeptScreen = true;
+ _keptFromEarlierRun = fromEarlierRun;
notifyListeners();
}
@@ -306,12 +314,12 @@ class TerminalSession extends ChangeNotifier {
///
/// 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) {
+ void seedSnapshot(ScreenSnapshot snapshot, {bool fromEarlierRun = false}) {
if (hasScreen || _disposed) return;
final kept = _newTerminal(bindCallbacks: false)
..resize(_clampCols(snapshot.cols), _clampRows(snapshot.rows))
..write(snapshot.ansi);
- seedScreen(kept);
+ seedScreen(kept, fromEarlierRun: fromEarlierRun);
}
/// This session's screen as a [ScreenSnapshot] to keep, or null with nothing live to keep — a