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): show full skeleton on launch, keep screens in memory only

tonye71d995c06b1
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dart
index 34c1746ec..214b335cf 100644
--- a/mobile/lib/phone/phone_shell.dart
+++ b/mobile/lib/phone/phone_shell.dart
@@ -197,7 +197,8 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
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].
+ // ever reaching `paused` — so the machine cache is written here as well. See
+ // [AppNotifier.handleAppInactive].
widget.notifier.handleAppInactive();
return;
}
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 725749ab7..cc8b2c5c8 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -194,8 +194,6 @@ typedef _PageFacts = ({
TerminalSession? session,
TerminalSessionStatus? status,
bool rendered,
- bool keptScreen,
- bool keptFromEarlierRun,
String? agentName,
String? agentEngine,
AgentProject? agentProject,
@@ -703,10 +701,6 @@ 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,
@@ -970,7 +964,7 @@ class _TerminalPageState extends State<TerminalPage>
}
// 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 when the stream moves (`status` and `rendered` in [_PageFacts]), and this line
// rebuilds with every voice tick besides.
if (_attaching(_facts?.session)) {
return _StatusLine(
@@ -1000,12 +994,12 @@ class _TerminalPageState extends State<TerminalPage>
/// 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]).
+ /// ⚠️ **Said on the line above the mic, because nothing else says it (owner, 2026-10-01).** A
+ /// kept screen puts an agent opened again in this run up at once, before its stream is live, and
+ /// a tap in that wait 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]). A launch shows no kept screen — its skeleton says it.
static bool _attaching(TerminalSession? session) =>
session != null &&
session.showingKeptScreen &&
@@ -2126,19 +2120,6 @@ 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
@@ -2748,86 +2729,6 @@ 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 38cf77b66..d49b2f0bd 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -968,8 +968,8 @@ class AppNotifier extends ChangeNotifier {
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.
+ // On the machine cache's terms, below: a real app keeps screens (in memory), a test only
+ // when it hands over a store of its own.
_keptScreenStore =
keptScreenStore ??
(paneLayoutStore == null ? null : KeptScreenStore()),
@@ -1270,12 +1270,11 @@ 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()));
+ // No screen from the last run: the agent that record names is drawn as the skeleton until its
+ // keyframe lands — see [KeptScreenStore]. What an earlier build kept of it on disk goes. Only in
+ // the app, on the store's terms: a test never reaches the real cache directory.
+ if (_keptScreenStore != null) {
+ unawaited(KeptScreenStore.deleteLegacyFile());
}
// Before the machines, deliberately: the tiles are intent, they render as
// "waiting for that machine" on their own, and each attaches as its machine
@@ -1404,7 +1403,7 @@ class AppNotifier extends ChangeNotifier {
_forgetLaunchHold();
// Signed out from elsewhere: the kept screens go as on a sign-out here (see [logout]).
_keptScreens.clear();
- unawaited(_keptScreenStore?.clear());
+ _keptScreenStore?.clear();
unawaited(_pool?.closeAll());
_pool = null;
_lastError = message;
@@ -1549,8 +1548,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());
+ // The kept screens are this account's terminals — they go with it, as the cache does.
+ _keptScreenStore?.clear();
sessionPreviews.clear();
agentNotices.reset();
expandedMachines.clear();
@@ -2696,8 +2695,7 @@ class AppNotifier extends ChangeNotifier {
/// 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.
+ /// one stream somebody was waiting to type into queued behind it.
///
/// Nothing on screen needs the list first: a launch draws from last run's
/// ([MachineState.agentsFromCache]), which is also what limits this to a launch — a reconnect
@@ -5432,15 +5430,10 @@ class AppNotifier extends ChangeNotifier {
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.
+ // Or its visible screen, kept when this run last left it — see [_keptScreenStore]. Nothing
+ // from an earlier run: a launch's agent is the skeleton until its keyframe lands.
final saved = _keptScreenStore?.read(keptKey);
- if (saved != null) {
- terminal.seedSnapshot(
- saved,
- fromEarlierRun: saved.savedAt.isBefore(_runStartedAt),
- );
- }
+ if (saved != null) terminal.seedSnapshot(saved);
}
terminal.addListener(notifyListeners);
// The launch's held machines go once a terminal is live — see [_launchMachineId].
@@ -5467,8 +5460,8 @@ class AppNotifier extends ChangeNotifier {
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],
- // and [_keptScreenStore] for the next launch.
+ // The screen as the reader left it, for the next time this agent opens in this run — see
+ // [_keptScreens], and [_keptScreenStore] for one opened again after those three have moved on.
final agentId = pane.agentId;
if (keepScreen && agentId != null && terminal.hasRenderedFrame) {
final key = '${pane.machineId}/$agentId';
@@ -5559,18 +5552,11 @@ 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.
+ /// The visible screens of the agents opened most recently in this run, in memory only — see
+ /// [KeptScreenStore]. Where [_keptScreens] has no exact terminal for an agent (it holds three),
+ /// this has the screen it showed. Null in 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;
@@ -5579,20 +5565,6 @@ class AppNotifier extends ChangeNotifier {
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());
- }
-
/// [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
@@ -5628,8 +5600,8 @@ class AppNotifier extends ChangeNotifier {
/// 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.
+ /// the screen ([handleAppPaused], [handleAppInactive]) and by [_saveMachineCacheSoon]. Never
+ /// awaited, and nothing when nothing changed: an idle run writes nothing.
void _keepMachineCache() {
_machineCacheSaveTimer?.cancel();
_machineCacheSaveTimer = null;
@@ -5648,29 +5620,9 @@ class AppNotifier extends ChangeNotifier {
);
}
- /// 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,
- fromEarlierRun: snapshot.savedAt.isBefore(_runStartedAt),
- );
- }
- }
- }
-
Future<void> _closeAllPanes({bool persist = true}) async {
- // 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`).
+ // Everything closing at once is a sign-out or a reset: nothing of it is kept
+ // ([_detachSession]'s `keepScreen`).
_keptScreens.clear();
final open = allPanes.toList();
for (final swarm in swarms) {
@@ -6379,23 +6331,18 @@ class AppNotifier extends ChangeNotifier {
/// of somebody. The sockets are left to the OS, which suspends them anyway —
/// [handleAppResumed] is what puts both back.
///
- /// 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.
+ /// And write the machine cache now ([_keepMachineCache]): this is the last moment the app is sure
+ /// to run, since closing it from the app switcher starts by sending it here.
void handleAppPaused() {
_desk.pause();
- _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 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();
- }
+ /// only the machine cache is written ([_keepMachineCache]), because the switcher is where an app
+ /// is closed, and closing it there need not pass through [handleAppPaused] first.
+ void handleAppInactive() => _keepMachineCache();
/// What the local CLI closing this machine's socket with [code] does to the
/// model — the `WsPool.onLocalFailure` path, without a socket.
@@ -6434,7 +6381,6 @@ 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
index 63437bdf6..860130cca 100644
--- a/mobile/lib/state/kept_screens.dart
+++ b/mobile/lib/state/kept_screens.dart
@@ -1,194 +1,73 @@
-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.
+/// The last screens of the agents opened most recently in this run, so going back to one shows it at
+/// once instead of a skeleton while its 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.
+/// Beside the few exact terminals `AppNotifier` keeps (`_keptScreens`), each a whole emulator,
+/// scrollback and all: this keeps the visible screen alone ([ScreenSnapshot]), a few kilobytes, so it
+/// can hold [capacity] of them — the agents Find, or a return to an earlier harness, opens next.
///
-/// 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.
+/// ⚠️ **In memory, never on the phone's disk (owner, 2026-10-01).** These screens used to be written
+/// to disk so a launch could draw the agent it reopens before its machine answered. That screen
+/// looked live for the two or three seconds it was not — a prompt that took no key, output hours
+/// old — and a launch shows the skeleton instead now (`_Attaching` in `terminal_page.dart`). With
+/// nothing left to read them in the next run, nothing is written: no terminal's contents on the
+/// phone, and no write each time the app leaves the screen. What an earlier build wrote is deleted
+/// at launch ([deleteLegacyFile]).
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.
+ /// How many agents' screens are kept. 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, 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.
- }
- }
+ /// The screen kept for [key], or null.
+ ScreenSnapshot? read(String key) => _screens[key];
/// 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() {
+ /// Forget [key]'s screen — its agent was deleted, or is gone from its machine's list.
+ void remove(String key) => _screens.remove(key);
+
+ /// Forget every kept screen — signing out: they are that account's terminals.
+ void clear() => _screens.clear();
+
+ /// Delete the file an earlier build kept these screens in, if it is still there: a terminal's
+ /// contents left on the phone with nothing to read them. Never throws — a file that will not go is
+ /// in the app's CACHE directory, which the OS empties when space runs low.
+ ///
+ /// Can go once no install still has the file; until then it costs one look at the disk a launch.
+ static Future<void> deleteLegacyFile() async {
try {
- final temporary = Directory.systemTemp.path;
+ // Where that build put it, resolved the way it was — without a plugin, as `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.
+ final temporary = Directory.systemTemp;
final directory = Platform.isIOS
- ? '${Directory.systemTemp.parent.path}/Library/Caches/harness'
- : '$temporary/harness';
- return FileSnapshotStore('kept-screens', directory: Directory(directory));
+ ? '${temporary.parent.path}/Library/Caches/harness'
+ : '${temporary.path}/harness';
+ final store = FileSnapshotStore(
+ 'kept-screens',
+ directory: Directory(directory),
+ );
+ await store.clear();
+ // And a write the app was closed in the middle of ([FileSnapshotStore.write]).
+ final partial = File('${store.file.path}.tmp');
+ if (await partial.exists()) await partial.delete();
} on Object {
- return MemorySnapshotStore();
+ // Left for the OS to clear with the rest of the cache.
}
}
}
diff --git a/mobile/lib/terminal/screen_snapshot.dart b/mobile/lib/terminal/screen_snapshot.dart
index 41c933767..2b50b1f47 100644
--- a/mobile/lib/terminal/screen_snapshot.dart
+++ b/mobile/lib/terminal/screen_snapshot.dart
@@ -3,13 +3,14 @@ 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]).
+/// next time its agent opens in this run, that screen is up at once while the live stream attaches
+/// (`AppNotifier._attachSession`, [TerminalSession.seedSnapshot]). In memory only — see
+/// `KeptScreenStore`.
///
/// ⚠️ **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.
+/// machine's keyframe lands, which then replaces it whole. Scrollback would multiply what is kept —
+/// fifty of these — for nothing that first frame shows.
class ScreenSnapshot {
const ScreenSnapshot({
required this.cols,
@@ -34,34 +35,6 @@ class ScreenSnapshot {
/// 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].
///
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index 7fee84176..a863feed6 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -283,15 +283,8 @@ 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. [fromEarlierRun]: see [keptScreenFromEarlierRun].
+ /// first keyframe lands and replaces it.
///
/// ⚠️ **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
@@ -300,26 +293,25 @@ 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, {bool fromEarlierRun = false}) {
+ void seedScreen(Terminal kept) {
if (hasRenderedFrame || _disposed) return;
_bindTerminal(kept);
terminal = kept;
_showingKeptScreen = true;
- _keptFromEarlierRun = fromEarlierRun;
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.
+ /// [snapshot] — a screen this run kept of this agent ([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, {bool fromEarlierRun = false}) {
+ 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, fromEarlierRun: fromEarlierRun);
+ seedScreen(kept);
}
/// This session's screen as a [ScreenSnapshot] to keep, or null with nothing live to keep — a