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.

fix(mobile): stop terminal typing lag and lost keystrokes

tony47c0ba7bbed6
diff --git a/mobile/lib/app_shell.dart b/mobile/lib/app_shell.dart
index 4cee0dc28..c8f2b2fb1 100644
--- a/mobile/lib/app_shell.dart
+++ b/mobile/lib/app_shell.dart
@@ -257,7 +257,15 @@ class RootShell extends ConsumerWidget {
final app = ref.watch(appStateProvider);
return ListenableBuilder(
listenable: app,
- builder: (context, _) => switch (app.status) {
+ // ⚠️ **Made here and handed through, never made in the builder.** The notifier ticks for
+ // everything on the account — an agent synced, a turn starting on another machine — and
+ // the signed-in screen rebuilt from the top on each one: the shell, its navigator, every
+ // route on it, down to the terminal being typed into. Everything in that screen that draws
+ // from the notifier listens to it for itself, so the tick has nothing to bring it. Made
+ // here, it is the same widget on every tick and Flutter stops at it; it is made again
+ // only when this shell is (a theme or text-size change), which still rebuilds it whole.
+ child: _SignedInScreen(app: app, screen: authenticatedScreen),
+ builder: (context, signedIn) => switch (app.status) {
// `bootstrapping` covers two unrelated moments: the app starting
// cold, and a sign-in the user just began. The second keeps the
// signed-out screen, which carries the wait as a state of its own
@@ -268,8 +276,20 @@ class RootShell extends ConsumerWidget {
AppStatus.bootstrapping =>
app.signingIn ? signedOutScreen(app) : bootScreen(app),
AppStatus.unauthenticated => signedOutScreen(app),
- AppStatus.authenticated => authenticatedScreen(app),
+ AppStatus.authenticated => signedIn!,
},
);
}
}
+
+/// [screen] for [app] as a widget of its own, so [RootShell] can make it once and hand it through
+/// its [ListenableBuilder] — and so the screen itself is only built when it is shown.
+class _SignedInScreen extends StatelessWidget {
+ const _SignedInScreen({required this.app, required this.screen});
+
+ final AppNotifier app;
+ final AuthenticatedScreenBuilder screen;
+
+ @override
+ Widget build(BuildContext context) => screen(app);
+}
diff --git a/mobile/lib/logging/app_log.dart b/mobile/lib/logging/app_log.dart
index d619003be..932cd3305 100644
--- a/mobile/lib/logging/app_log.dart
+++ b/mobile/lib/logging/app_log.dart
@@ -59,7 +59,8 @@ extension AppLogX on AppLog {
}
/// [AppLog] backed by a per-day file under `~/.harness/logs`. Writes are
-/// synchronous and flushed (see [DailyLogFile]); IO errors are swallowed.
+/// synchronous — flushed per line, or batched when the file is (see
+/// [DailyLogFile.batch]); IO errors are swallowed.
class FileAppLog implements AppLog {
FileAppLog(this._file, {ErrorBurstFilter? burst, DateTime Function()? clock})
: _burst = burst ?? ErrorBurstFilter(),
@@ -103,6 +104,10 @@ class FileAppLog implements AppLog {
if (admitted == null) return;
_file.append('[${logStamp(_clock())}] $admitted');
_appendStack(stackTrace);
+ // On disk now, with every line held for a batch before it: an error is what
+ // the log is opened for, and the lines before it are why it happened — they
+ // must not wait on a timer an app about to go down may never see fire.
+ _file.flush(durable: true);
}
void _appendStack(StackTrace? stackTrace) {
diff --git a/mobile/lib/logging/install.dart b/mobile/lib/logging/install.dart
index 0b79ef0e4..aec08d2c5 100644
--- a/mobile/lib/logging/install.dart
+++ b/mobile/lib/logging/install.dart
@@ -1,3 +1,5 @@
+import 'package:flutter/widgets.dart';
+
import 'app_log.dart';
import 'debug_surface.dart';
import 'log_file.dart';
@@ -7,6 +9,10 @@ import 'log_stream_sinks.dart';
/// Base name of the per-day file under `~/.harness/logs`.
const String kAppLogBase = 'app';
+/// How long a line of the app log may wait to be written with the ones after it — see
+/// [DailyLogFile.batch].
+const Duration kAppLogBatch = Duration(milliseconds: 250);
+
/// Point [appLog] at real files under `~/.harness/logs`, and — in
/// a build that has the Debug screen — at the in-memory [logStream] as well.
///
@@ -18,7 +24,17 @@ const String kAppLogBase = 'app';
/// starting up, and awaiting a directory probe here would lose them.
void installFileLogs() {
final directory = DailyLogFile.defaultDirectory;
- final file = FileAppLog(DailyLogFile(directory, kAppLogBase));
+ final daily = DailyLogFile(directory, kAppLogBase, batch: kAppLogBatch);
+ // The lines held for a batch go out the moment the app leaves the screen: the switcher is where
+ // an app is closed, and a closed app never sees the batch's timer fire. Never disposed — it lives
+ // as long as the log does, held by the binding it registers with.
+ AppLifecycleListener(
+ onInactive: daily.flush,
+ onHide: daily.flush,
+ onPause: daily.flush,
+ onDetach: () => daily.flush(durable: true),
+ );
+ final file = FileAppLog(daily);
if (!kDebugSurfaceEnabled) {
appLog = file;
return;
diff --git a/mobile/lib/logging/log_file.dart b/mobile/lib/logging/log_file.dart
index 453407a14..304fd3fd0 100644
--- a/mobile/lib/logging/log_file.dart
+++ b/mobile/lib/logging/log_file.dart
@@ -1,3 +1,4 @@
+import 'dart:async';
import 'dart:developer' as developer;
import 'dart:io';
@@ -19,11 +20,22 @@ import '../core/harness_file_store.dart';
/// Writes are synchronous and flushed so a line survives even if the app is
/// force-quit mid-write, and every IO error is swallowed — diagnostic logging
/// must never break the flow it only observes.
+///
+/// ⚠️ **Unless [batch] is set, which the app's own log does** (`installFileLogs`).
+/// A write and an fsync PER LINE is milliseconds on a phone's flash, on the UI
+/// isolate, and a machine reconciling its agents is a burst of lines: frames
+/// dropped, under somebody typing. Batched, lines wait up to [batch] and go
+/// out in one write, without the fsync — a write that has reached the kernel
+/// survives the app being killed, which is the loss the fsync was there for;
+/// what it adds is surviving the PHONE going down. [flush] puts them out at
+/// once, durably when asked: an error does, and so does the app on its way to
+/// the background.
class DailyLogFile {
DailyLogFile(
this.directory,
this.base, {
this.retentionDays = 14,
+ this.batch,
DateTime Function() clock = DateTime.now,
// The field is private, so an initialising formal would name the
// PARAMETER `_clock` — which no caller outside this library could pass.
@@ -31,6 +43,16 @@ class DailyLogFile {
// ignore: prefer_initializing_formals
}) : _clock = clock;
+ /// How long a line may wait to go out with the ones after it. Null — the
+ /// default — writes and flushes every line as it comes.
+ final Duration? batch;
+
+ /// The lines waiting for [batch], and the moment the first of them was
+ /// appended — which names the day's file they go to.
+ final StringBuffer _pending = StringBuffer();
+ DateTime? _pendingSince;
+ Timer? _batchTimer;
+
/// The app's own log directory, `~/.harness/logs`.
///
/// Through [HarnessFileStore.defaultDirectoryPath] rather than a second path
@@ -64,18 +86,47 @@ class DailyLogFile {
/// Append [block] followed by a newline to today's file. Creates the directory
/// on demand and prunes stale days on the first write after midnight; any
- /// failure is swallowed.
+ /// failure is swallowed. With [batch] set the line waits for the next [flush].
void append(String block) {
+ final now = _clock();
+ final wait = batch;
+ if (wait == null) {
+ _write(now, '$block\n', durable: true);
+ return;
+ }
+ // A line of a new day: what is waiting belongs to the day before, and its file.
+ final since = _pendingSince;
+ if (since != null && _ymd(since) != _ymd(now)) flush();
+ _pendingSince ??= now;
+ _pending
+ ..write(block)
+ ..write('\n');
+ _batchTimer ??= Timer(wait, flush);
+ }
+
+ /// Writes every line [batch] is holding, now, in one write — and to disk
+ /// before returning when [durable]. Nothing to do without [batch].
+ void flush({bool durable = false}) {
+ _batchTimer?.cancel();
+ _batchTimer = null;
+ final since = _pendingSince;
+ if (since == null) return;
+ final text = _pending.toString();
+ _pending.clear();
+ _pendingSince = null;
+ _write(since, text, durable: durable);
+ }
+
+ void _write(DateTime at, String text, {required bool durable}) {
try {
- final now = _clock();
- final day = _ymd(now);
- final file = _fileFor(now);
+ final day = _ymd(at);
+ final file = _fileFor(at);
file.parent.createSync(recursive: true);
if (day != _activeDay) {
_activeDay = day;
- _pruneOlderThan(now);
+ _pruneOlderThan(at);
}
- file.writeAsStringSync('$block\n', mode: FileMode.append, flush: true);
+ file.writeAsStringSync(text, mode: FileMode.append, flush: durable);
} catch (e) {
// Best-effort: never surface an IO failure into the caller's flow.
_debugLog('DailyLogFile.append failed: $e');
diff --git a/mobile/lib/phone/agent_swipe.dart b/mobile/lib/phone/agent_swipe.dart
index bdd881076..26bf7108f 100644
--- a/mobile/lib/phone/agent_swipe.dart
+++ b/mobile/lib/phone/agent_swipe.dart
@@ -255,6 +255,17 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {
_armPrefetch();
}
+ /// The page of a pager with no neighbours — made once, and handed back unchanged by every [build]
+ /// after.
+ ///
+ /// ⚠️ **The same widget, so a rebuild of this pager stops here.** [AgentHome] holds this pager at
+ /// the root and rebuilds it on every tick of the notifier — an agent synced on any machine, a
+ /// turn starting — and a new [TerminalPage] each time rebuilt the whole page with it: header,
+ /// dock and terminal, under somebody typing. The page listens to the notifier for itself and
+ /// rebuilds only for what it draws ([TerminalPage]'s `_onNotifier`), so nothing is lost by it.
+ /// Made again only if what it was made from changes.
+ TerminalPage? _single;
+
/// Takes in a new neighbour list without leaving the page on screen.
///
/// ⚠️ **In place, and that is the whole point.** The list is retaken whenever the tab's agents
@@ -272,6 +283,11 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {
@override
void didUpdateWidget(AgentSwipeHost oldWidget) {
super.didUpdateWidget(oldWidget);
+ if (!identical(oldWidget.notifier, widget.notifier) ||
+ oldWidget.machineId != widget.machineId ||
+ oldWidget.agentId != widget.agentId) {
+ _single = null;
+ }
final next = widget.neighbours;
final held = _neighbours;
if (next == null || held == null || identical(next, held)) return;
@@ -349,7 +365,7 @@ class _AgentSwipeHostState extends State<AgentSwipeHost> {
final neighbours = _neighbours;
final controller = _controller;
if (neighbours == null || controller == null || neighbours.isEmpty) {
- return TerminalPage(
+ return _single ??= TerminalPage(
notifier: widget.notifier,
machineId: widget.machineId,
agentId: widget.agentId,
diff --git a/mobile/lib/phone/phone_shell.dart b/mobile/lib/phone/phone_shell.dart
index 2e39fdb59..099cbfd30 100644
--- a/mobile/lib/phone/phone_shell.dart
+++ b/mobile/lib/phone/phone_shell.dart
@@ -254,13 +254,37 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
await confirmExitApp(context);
}
+ /// The page stack. A fresh widget each call — what makes the [Navigator] tell every route on it
+ /// that the world may have changed (`Route.changedExternalState`), and so rebuild every page.
+ Widget _pages() => HeroControllerScope(
+ controller: _heroController,
+ child: Navigator(
+ key: _navigator,
+ // ⚠️ The controller goes in the SCOPE ONLY, never also in `observers`.
+ // `NavigatorState._updateEffectiveObservers` appends the scope's controller
+ // to `widget.observers` itself, so listing it here registers it twice and
+ // trips "A HeroController can not be shared by multiple Navigators" — which
+ // reads like a sharing bug and is really a double-subscription by one
+ // navigator.
+ onGenerateRoute: (_) => MaterialPageRoute<void>(
+ builder: (_) => AgentHome(
+ notifier: widget.notifier,
+ openMachineId: _linkedMachineId,
+ openAgent: _openAgentRequest,
+ ),
+ ),
+ ),
+ );
+
@override
- Widget build(BuildContext context) => PhoneShellScope(
- onMachineLinked: _followLinkedMachine,
- onOpenAgent: _openAgentAtHome,
- child: ListenableBuilder(
- listenable: widget.notifier,
- builder: (context, _) => PopScope<Object?>(
+ Widget build(BuildContext context) {
+ // Made once per build of the shell, and handed through the [ListenableBuilder] below — see the
+ // note there.
+ final pages = _pages();
+ return PhoneShellScope(
+ onMachineLinked: _followLinkedMachine,
+ onOpenAgent: _openAgentAtHome,
+ child: PopScope<Object?>(
// False while the stack has somewhere to go back to, so the gesture reaches [_handleBack]
// instead of leaving the app. True at its root: the press then belongs to the system —
// except on Android, where the root asks before the app is left ([confirmExitApp]), so
@@ -275,57 +299,55 @@ class _PhoneShellState extends State<PhoneShell> with WidgetsBindingObserver {
//
// `MaterialApp` installs one controller for the ROOT navigator only; a nested
// `Navigator` inherits nothing, so its routes have no observer to drive a flight.
- body: Column(
- children: [
- // A device this phone had never trusted joined the account (device key log).
- NewDeviceBanner(
- notifier: widget.notifier,
- navigator: _navigator,
- ),
- Expanded(
- // While a band shows it has taken the status-bar inset, so the pages under it must
- // not take it again (a blank gap the height of the notch otherwise).
- //
- // ⚠️ **Read under the Scaffold, through this Builder — never through the shell's
- // own context.** The Scaffold has resized its body for the keyboard, and hands the
- // body a MediaQuery with the keyboard's inset taken out so nothing below takes it
- // again. The shell's context sits ABOVE the Scaffold and still holds that inset:
- // rebuilt from it, every page in this navigator read the keyboard afresh and its
- // own Scaffold shrank for it a second time. The terminal page lost twice the
- // keyboard's height, its key bar left floating halfway up the screen over an
- // empty band. See `TerminalPage.didChangeMetrics`, which relies on the inset
- // being gone here.
- child: Builder(
- builder: (context) => MediaQuery.removePadding(
- context: context,
- removeTop: NewDeviceBanner.showing(widget.notifier),
- child: HeroControllerScope(
- controller: _heroController,
- child: Navigator(
- key: _navigator,
- // ⚠️ The controller goes in the SCOPE ONLY, never also in `observers`.
- // `NavigatorState._updateEffectiveObservers` appends the scope's controller
- // to `widget.observers` itself, so listing it here registers it twice and
- // trips "A HeroController can not be shared by multiple Navigators" — which
- // reads like a sharing bug and is really a double-subscription by one
- // navigator.
- onGenerateRoute: (_) => MaterialPageRoute<void>(
- builder: (_) => AgentHome(
- notifier: widget.notifier,
- openMachineId: _linkedMachineId,
- openAgent: _openAgentRequest,
- ),
- ),
- ),
+ //
+ // ⚠️ **Only the bands and the inset under them are rebuilt by the notifier, and the
+ // page stack is not — while the home screen is all there is.** This used to wrap the
+ // whole shell, so every tick of the notifier (an agent synced on any machine, a turn
+ // starting) handed the [Navigator] a new widget, which rebuilds EVERY route on it:
+ // the home screen down to the terminal being typed into, several times a second in a
+ // burst. The home screen listens to the notifier for itself ([AgentHome]), so at the
+ // root the stack is handed through untouched. A page PUSHED over it may not listen —
+ // it may read the notifier in `build` and count on being rebuilt — so while one is up
+ // the stack is rebuilt on every tick exactly as before.
+ body: ListenableBuilder(
+ listenable: widget.notifier,
+ child: pages,
+ builder: (context, pages) => Column(
+ children: [
+ // A device this phone had never trusted joined the account (device key log).
+ NewDeviceBanner(
+ notifier: widget.notifier,
+ navigator: _navigator,
+ ),
+ Expanded(
+ // While a band shows it has taken the status-bar inset, so the pages under it must
+ // not take it again (a blank gap the height of the notch otherwise).
+ //
+ // ⚠️ **Read under the Scaffold, through this Builder — never through the shell's
+ // own context.** The Scaffold has resized its body for the keyboard, and hands the
+ // body a MediaQuery with the keyboard's inset taken out so nothing below takes it
+ // again. The shell's context sits ABOVE the Scaffold and still holds that inset:
+ // rebuilt from it, every page in this navigator read the keyboard afresh and its
+ // own Scaffold shrank for it a second time. The terminal page lost twice the
+ // keyboard's height, its key bar left floating halfway up the screen over an
+ // empty band. See `TerminalPage.didChangeMetrics`, which relies on the inset
+ // being gone here.
+ child: Builder(
+ builder: (context) => MediaQuery.removePadding(
+ context: context,
+ removeTop: NewDeviceBanner.showing(widget.notifier),
+ child: (_navigator.currentState?.canPop() ?? false)
+ ? _pages()
+ : pages!,
),
),
),
- ),
- ],
+ ],
+ ),
),
),
),
),
- ),
- );
+ );
+ }
}
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index 94da71f72..bad03460d 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -195,6 +195,12 @@ typedef _PageFacts = ({
TerminalSession? session,
TerminalSessionStatus? status,
bool rendered,
+ bool hasScreen,
+ Terminal? terminal,
+ bool watching,
+ bool acceptsInput,
+ String? tabId,
+ String? branch,
String? agentName,
String? agentEngine,
AgentProject? agentProject,
@@ -702,6 +708,17 @@ class _TerminalPageState extends State<TerminalPage>
session: session,
status: session?.status,
rendered: session?.hasRenderedFrame ?? false,
+ // ⚠️ Everything below to `branch` is read by [build] too, and has to be compared here: this
+ // page is no longer rebuilt from above on every tick of the notifier (see
+ // `AgentSwipeHost._single`), so a fact left out is a fact drawn stale. The terminal itself is
+ // replaced by every keyframe — each keyboard raised or lowered ends in one — and the page
+ // anchors and reads the one it is handed.
+ hasScreen: session?.hasScreen ?? false,
+ terminal: session?.terminal,
+ watching: session?.watching ?? false,
+ acceptsInput: session?.acceptsInput ?? false,
+ tabId: notifier.activeSwarmId,
+ branch: agent?.gitContext?.branchLabel,
agentName: agent?.displayName,
agentEngine: agent?.engine,
agentProject: agent?.displayProject,
@@ -3382,6 +3399,10 @@ class _SlideAway extends StatelessWidget {
/// keeps the whole screen, so reading back through the history uses every row: while it is read
/// ([enabled] off) the terminal eases back to where it is drawn. Nothing moves on the alternate
/// screen, where a full-screen program owns its own layout.
+/// What [_AnchoredTerminal] places the terminal by: the buffer's height and its last line with
+/// anything on it.
+typedef _Anchor = ({int height, int last});
+
class _AnchoredTerminal extends StatefulWidget {
const _AnchoredTerminal({
required this.terminal,
@@ -3416,16 +3437,17 @@ class _AnchoredTerminalState extends State<_AnchoredTerminal> {
@override
void initState() {
super.initState();
- widget.terminal?.addListener(_changed);
+ widget.terminal?.addListener(_output);
widget.reading.addListener(_toggled);
+ terminalFontStore.addListener(_changed);
}
@override
void didUpdateWidget(_AnchoredTerminal old) {
super.didUpdateWidget(old);
if (!identical(old.terminal, widget.terminal)) {
- old.terminal?.removeListener(_changed);
- widget.terminal?.addListener(_changed);
+ old.terminal?.removeListener(_output);
+ widget.terminal?.addListener(_output);
}
if (!identical(old.reading, widget.reading)) {
old.reading.removeListener(_toggled);
@@ -3437,8 +3459,9 @@ class _AnchoredTerminalState extends State<_AnchoredTerminal> {
@override
void dispose() {
- widget.terminal?.removeListener(_changed);
+ widget.terminal?.removeListener(_output);
widget.reading.removeListener(_toggled);
+ terminalFontStore.removeListener(_changed);
super.dispose();
}
@@ -3457,6 +3480,21 @@ class _AnchoredTerminalState extends State<_AnchoredTerminal> {
_changed();
}
+ /// What the last layout placed the terminal by — see [_output].
+ _Anchor? _drawnFor;
+
+ /// The terminal changed: output, the cursor's blink, a resize.
+ ///
+ /// ⚠️ **Rebuilt only when that moves where the terminal is drawn.** Every byte of output and every
+ /// blink of the cursor lands here, and each one used to rebuild this widget — and with it ask for
+ /// a fresh layout — even with the keyboard up, when nothing is anchored at all, which is exactly
+ /// while somebody types. What the place is worked out from is a few rows read off the buffer, so
+ /// it is compared first.
+ void _output() {
+ if (!mounted || _anchor() == _drawnFor) return;
+ _changed();
+ }
+
void _changed() {
if (!mounted) return;
// Output can land mid-frame (a resize answered during layout): rebuild after it, then.
@@ -3484,15 +3522,13 @@ class _AnchoredTerminalState extends State<_AnchoredTerminal> {
return height;
}();
- double _shift(double viewport) {
+ /// What [_shift] places the terminal by, read off it now — null while nothing is anchored.
+ _Anchor? _anchor() {
final terminal = widget.terminal;
- if (!_on || terminal == null || terminal.isUsingAltBuffer) {
- return 0;
- }
+ if (!_on || terminal == null || terminal.isUsingAltBuffer) return null;
final buffer = terminal.buffer;
final height = buffer.height;
- if (height == 0) return 0;
- final cell = _cellHeight(terminalFontStore.value);
+ if (height == 0) return null;
// The last line with anything on it — the cursor's, or below it where a TUI parked the
// cursor higher up.
var last = buffer.absoluteCursorY.clamp(0, height - 1);
@@ -3502,6 +3538,14 @@ class _AnchoredTerminalState extends State<_AnchoredTerminal> {
break;
}
}
+ return (height: height, last: last);
+ }
+
+ double _shift(double viewport) {
+ final anchor = _drawnFor = _anchor();
+ if (anchor == null) return 0;
+ final (:height, :last) = anchor;
+ final cell = _cellHeight(terminalFontStore.value);
// Rows are laid from the top until there is history to scroll, and from the foot after.
final bottom = height * cell <= viewport
? (last + 1) * cell
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index ad18b9e99..b80353397 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -1114,7 +1114,16 @@ class AppNotifier extends ChangeNotifier {
String get autonomousEnv => _autonomousEnv;
static const offlineRetryInterval = Duration(seconds: 5);
- static const agentSyncInterval = Duration(seconds: 60);
+
+ /// How often a connected machine's agent list is read again, under the pushes — see
+ /// [_syncAgentsIfChanged].
+ ///
+ /// ⚠️ **Two minutes, not one.** The pushes keep the list live; this catches only what they miss,
+ /// and a relay session gone stale ([agentSyncStaleTicks] of these timing out in a row). And it is
+ /// not cheap where it lands: the machine reads every agent's git state and history to answer —
+ /// one to two seconds for 150 of them — and every keystroke sent to it meanwhile waits behind
+ /// that answer. Once a minute, on each machine, was a stall in somebody's typing every minute.
+ static const agentSyncInterval = Duration(seconds: 120);
MachineState? stateOf(String machineId) => machineStates[machineId];
@@ -1922,7 +1931,7 @@ class AppNotifier extends ChangeNotifier {
}
/// One tick of the agent-list safety net ([_syncAgentsIfChanged]), which the
- /// app itself only reaches through a 60-second timer.
+ /// app itself only reaches through its [agentSyncInterval] timer.
@visibleForTesting
Future<void> syncAgentsForTest(String machineId) async {
final machine = machineStates[machineId];
@@ -2103,18 +2112,61 @@ class AppNotifier extends ChangeNotifier {
void _startAgentSyncTimer(String machineId) {
if (_agentSyncTimers.containsKey(machineId)) return;
- _agentSyncTimers[machineId] = Timer.periodic(agentSyncInterval, (_) {
- final machine = machineStates[machineId];
- if (machine == null) {
- _stopAgentSyncTimer(machineId);
- return;
- }
- unawaited(_syncAgentsIfChanged(machine));
- });
+ _agentSyncTimers[machineId] = Timer.periodic(
+ agentSyncInterval,
+ (_) => _agentSyncTick(machineId, DateTime.now()),
+ );
+ }
+
+ /// How recently a keystroke must have gone to a machine for its agent-list tick to wait.
+ static const _typingQuiet = Duration(seconds: 8);
+
+ /// The longest a tick waits on somebody typing before it goes anyway: a safety net held back
+ /// for as long as somebody keeps typing would never run at all.
+ static const _typingWaitLimit = Duration(seconds: 60);
+
+ /// Per machine, a tick waiting for the typing on it to stop — see [_agentSyncTick].
+ final Map<String, Timer> _agentSyncHolds = {};
+
+ /// Whether somebody is typing into a terminal on [machineId]: a keystroke sent to it in the last
+ /// [_typingQuiet].
+ bool _typingOn(String machineId, DateTime now) =>
+ panesFor(machineId).any((pane) {
+ final at = pane.session?.lastInputAt;
+ return at != null && now.difference(at) < _typingQuiet;
+ });
+
+ /// One tick of the agent-list safety net, first due at [dueSince].
+ ///
+ /// ⚠️ **Held while somebody types on that machine.** The machine answers `agents_list` on the
+ /// same queue it takes keystrokes from, and the answer takes it a second or two (see
+ /// [agentSyncInterval]) — a tick landing mid-sentence froze the echo for that long. So a tick
+ /// that finds a keystroke gone in the last [_typingQuiet] waits that long and looks again, up to
+ /// [_typingWaitLimit] from when it was due; the periodic ticks meanwhile leave it to the one
+ /// waiting.
+ void _agentSyncTick(String machineId, DateTime dueSince) {
+ final machine = machineStates[machineId];
+ if (machine == null) {
+ _stopAgentSyncTimer(machineId);
+ return;
+ }
+ if (_agentSyncHolds.containsKey(machineId)) return;
+ final now = DateTime.now();
+ if (_typingOn(machineId, now) &&
+ now.difference(dueSince) < _typingWaitLimit) {
+ _agentSyncHolds[machineId] = Timer(_typingQuiet, () {
+ _agentSyncHolds.remove(machineId);
+ if (_disposed || !_agentSyncTimers.containsKey(machineId)) return;
+ _agentSyncTick(machineId, dueSince);
+ });
+ return;
+ }
+ unawaited(_syncAgentsIfChanged(machine));
}
void _stopAgentSyncTimer(String machineId) {
_agentSyncTimers.remove(machineId)?.cancel();
+ _agentSyncHolds.remove(machineId)?.cancel();
_agentSyncTimeouts.remove(machineId);
}
@@ -2123,6 +2175,10 @@ class AppNotifier extends ChangeNotifier {
timer.cancel();
}
_agentSyncTimers.clear();
+ for (final hold in _agentSyncHolds.values) {
+ hold.cancel();
+ }
+ _agentSyncHolds.clear();
_agentSyncTimeouts.clear();
}
@@ -2130,8 +2186,8 @@ class AppNotifier extends ChangeNotifier {
/// is treated as gone and redialled ([_recoverStaleSession]).
///
/// Two, not one: a single missed tick is a busy machine or a slow relay, and a
- /// forced redial costs every terminal on it a resync. Two in a row is a minute
- /// of a machine not answering the cheapest request there is, which nothing
+ /// forced redial costs every terminal on it a resync. Two in a row is minutes
+ /// of a machine not answering a request it always answers, which nothing
/// healthy does.
@visibleForTesting
static const agentSyncStaleTicks = 2;
@@ -2237,7 +2293,16 @@ class AppNotifier extends ChangeNotifier {
final byId = {for (final agent in a) agent.id: agent};
for (final agent in b) {
final prev = byId[agent.id];
- if (prev == null ||
+ if (prev == null || !agentEqual(prev, agent)) return false;
+ }
+ return true;
+ }
+
+ /// One agent of [agentsEqual]: the same agent, with nothing the UI reads changed. The same
+ /// hand-kept list, and the same rule — a field added to [Agent] is added here.
+ @visibleForTesting
+ static bool agentEqual(Agent prev, Agent agent) =>
+ !(prev.id != agent.id ||
prev.name != agent.name ||
// What search and the Recent list read: a turn that ends moves
// `updatedAt` and often `title`, and a sync that ignored them left
@@ -2272,12 +2337,7 @@ class AppNotifier extends ChangeNotifier {
prev.tokensUpdatedAt != agent.tokensUpdatedAt ||
prev.outputStats != agent.outputStats ||
// Whether a stopped row can be opened at all ([Agent.canPauseAndResume]).
- prev.resumeMode != agent.resumeMode) {
- return false;
- }
- }
- return true;
- }
+ prev.resumeMode != agent.resumeMode);
/// Public retry hook used by the offline join guide's "Retry now" action.
Future<void> retryOfflineMachine(String machineId) =>
@@ -4041,7 +4101,7 @@ class AppNotifier extends ChangeNotifier {
/// 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.
+ /// next sync tick. 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;
@@ -4315,7 +4375,12 @@ class AppNotifier extends ChangeNotifier {
/// [json] is [agent] as the daemon sent it, where the caller has it: kept for the next launch
/// ([_cacheAgentJson]).
- void _upsertAgent(
+ ///
+ /// False when it changed nothing — the agent is held already, equal in everything a screen reads
+ /// ([agentEqual]), with the machine's list loaded and no turn waiting on its session — and then
+ /// nothing here is touched either. See `agent_synced` in [_handleEvent], the caller that skips
+ /// its redraw for it.
+ bool _upsertAgent(
MachineState machine,
Agent agent, {
Map<String, dynamic>? json,
@@ -4324,6 +4389,16 @@ class AppNotifier extends ChangeNotifier {
final index = machine.agents.indexWhere((item) => item.id == agent.id);
final previous = index == -1 ? null : machine.agents[index];
agent = retainNewerGitContext(agent, previous);
+ final heldSession = agent.sessionId;
+ if (previous != null &&
+ agentEqual(previous, agent) &&
+ machine.agentLoadStatus == AgentLoadStatus.loaded &&
+ machine.agentsLoadError == null &&
+ (heldSession == null ||
+ (machine.sessionAgentIds[heldSession] == agent.id &&
+ !machine.pendingProcessingSessions.contains(heldSession)))) {
+ return false;
+ }
if (index == -1) {
machine.agents = [...machine.agents, agent];
} else {
@@ -4352,6 +4427,7 @@ class AppNotifier extends ChangeNotifier {
// install failed) — reloading the machine list will not install it.
_lastErrorRetryable = false;
}
+ return true;
}
void _renameAgent(MachineState machine, String agentId, String name) {
@@ -7134,13 +7210,18 @@ class AppNotifier extends ChangeNotifier {
try {
final json = Map<String, dynamic>.from(raw);
final agent = Agent.fromJson(json);
- _upsertAgent(machine, agent, json: json);
+ final changed = _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
// already `loaded`, so this push is the only signal that it can attach now.
// A push about an agent synced elsewhere.
_attachPendingPanes(machine, intent: AttachIntent.automatic);
+ // ⚠️ **No redraw for a push that changed nothing**, which is most of them: the
+ // machine re-sends every agent it has every five minutes (its reconcile), and a
+ // fleet of eighty was eighty redraws of every screen in two seconds — under
+ // somebody typing. An attach started above redraws for itself when it lands.
+ if (!changed) return;
} else {
// ⚠️ **Kept, not removed — the desktop's rule.** This is how a STOP arrives
// (`publishStoppedAgent` pushes the agent with `status: 'stopped'`), and also how an
@@ -7148,10 +7229,14 @@ class AppNotifier extends ChangeNotifier {
// stopped work vanish from the phone until the next full reload, so there was no row
// left to resume. `agent_deleted` is what removes an agent; this only lets go of the
// streams, which have no terminal behind them any more.
+ var detached = false;
for (final pane in panesFor(machine.machine.machineId).toList()) {
if (pane.agentId != agent.id) continue;
+ // `_detachSession` redraws nothing itself — the redraw below is this one's.
+ if (pane.session != null) detached = true;
await _detachSession(pane, sendClose: false);
}
+ if (!changed && !detached) return;
}
} catch (_) {
unawaited(_loadMachineData(machine, force: true));
@@ -7195,7 +7280,7 @@ class AppNotifier extends ChangeNotifier {
// stopped harness in the same breath, and says only this; the stopped
// row is in the next `agents_list` (`includeStopped`), never in a push.
// Without the read the harness vanished from the phone until the
- // 60-second sync — the one row somebody opens to resume it.
+ // next sync tick — the one row somebody opens to resume it.
if (agentId == null || payload['retained'] == true) {
unawaited(_loadMachineData(machine, force: true));
}
diff --git a/mobile/lib/terminal/terminal_session.dart b/mobile/lib/terminal/terminal_session.dart
index 95c4ec9ab..5a5544866 100644
--- a/mobile/lib/terminal/terminal_session.dart
+++ b/mobile/lib/terminal/terminal_session.dart
@@ -372,6 +372,11 @@ class TerminalSession extends ChangeNotifier {
Timer? _inputTimer;
Timer? _resizeTimer;
DateTime? _lastInputFlushAt;
+
+ /// When typing into this terminal last went out to the machine — null before it ever has. What
+ /// the app's agent-list check reads to stay out of the way of somebody typing
+ /// (`AppNotifier._typingOn`).
+ DateTime? get lastInputAt => _lastInputFlushAt;
DateTime? _lastResizeFlushAt;
Timer? _resyncTimer;
Timer? _scrollTimer;
diff --git a/mobile/lib/ws/ws_conn.dart b/mobile/lib/ws/ws_conn.dart
index 9dc4cba2c..b87d1546d 100644
--- a/mobile/lib/ws/ws_conn.dart
+++ b/mobile/lib/ws/ws_conn.dart
@@ -801,11 +801,37 @@ class WsConn {
}
final eventType = message['type'];
if (eventType is String && worthLogging(eventType)) {
- appLog.debug('ws', '↓ $eventType ${summariseForLog(payload)}');
+ appLog.debug('ws', '↓ $eventType ${_summaryOf(eventType, payload)}');
}
await onEvent({...message, 'payload': payload});
}
+ /// [payload] for the log line of a [type] frame.
+ ///
+ /// ⚠️ **The two that come in bursts say which agent and what state, not the whole agent.** A
+ /// machine re-sends every agent it has as `agent_synced` each time it reconciles (every five
+ /// minutes), and `agent_activity` beats for every agent mid-turn: rendered in full, each was a
+ /// whole agent — project, git context, model — turned into 1,200 characters on the UI thread,
+ /// four thousand lines a day of it. Which agent, and whether it is up, is what the timeline is
+ /// read for.
+ static String _summaryOf(String type, Map<String, dynamic> payload) {
+ switch (type) {
+ case 'agent_synced':
+ final agent = payload['agent'];
+ if (agent is! Map) break;
+ final launch = agent['launch'];
+ final terminal = agent['terminal'];
+ return '{id: ${agent['id']}, status: ${agent['status']}'
+ '${launch is Map ? ', launch: ${launch['state']}' : ''}'
+ '${terminal is Map ? ', terminal: ${terminal['available']}' : ''}}';
+ case 'agent_activity':
+ final activity = payload['activity'];
+ return '{agentId: ${payload['agentId']}'
+ '${activity is Map ? ', state: ${activity['state']}' : ''}}';
+ }
+ return summariseForLog(payload);
+ }
+
Future<void> _handleE2ee(Map<String, dynamic> frame) async {
final decrypted = await onE2eeFrame!(frame);
if (decrypted != null) await _dispatch(decrypted);
diff --git a/mobile/third_party/xterm/lib/src/ui/custom_text_edit.dart b/mobile/third_party/xterm/lib/src/ui/custom_text_edit.dart
index 40b4419fe..72cfca79d 100644
--- a/mobile/third_party/xterm/lib/src/ui/custom_text_edit.dart
+++ b/mobile/third_party/xterm/lib/src/ui/custom_text_edit.dart
@@ -101,6 +101,9 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
@override
void dispose() {
widget.focusNode.removeListener(_onFocusChange);
+ // Not settled: the terminal it would type into is going with this widget.
+ _rewriteSettle?.cancel();
+ _rewriteSettle = null;
_closeInputConnectionIfNeeded();
super.dispose();
}
@@ -132,6 +135,7 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
}
void setEditingState(TextEditingValue value) {
+ _settleRewrite();
_cancelPendingDeletes();
_currentEditingState = value;
_terminalText = value.text;
@@ -142,6 +146,8 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
/// It intentionally stays intact between ordinary key presses: Vietnamese
/// Telex needs the preceding `u` available to convert it into `ư`.
void resetEditingState() {
+ // What the keyboard was rewriting reaches the terminal before the buffer is emptied under it.
+ _settleRewrite();
_cancelPendingDeletes();
_currentEditingState = _initEditingState.copyWith();
_terminalText = _currentEditingState.text;
@@ -167,6 +173,7 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
}
KeyEventResult _onKeyEvent(FocusNode focusNode, KeyEvent event) {
+ _settleRewrite();
if (_currentEditingState.composing.isCollapsed) {
if (_isBufferBackspace(event)) {
_cancelPendingDeletes();
@@ -347,12 +354,72 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
@override
void updateEditingValue(TextEditingValue value) {
if (_consumeActionEcho(value)) return;
+ if (_holdRewrite(value)) return;
_applyEditingValue(
value,
hasTextMutation: value.text != _currentEditingState.text,
);
}
+ /// Set while the keyboard is rewriting a run of its buffer — see
+ /// [_holdRewrite] — and fires once it has gone quiet ([_settleRewrite]).
+ Timer? _rewriteSettle;
+
+ /// How long the keyboard must go quiet before a rewrite counts as done. Its
+ /// steps arrive a millisecond or two apart; a person's next key is a hundred
+ /// or more behind.
+ static const _rewriteQuiet = Duration(milliseconds: 30);
+
+ /// AUTONOMOUS PATCH: holds back the steps of a word the keyboard is
+ /// rewriting, so only where it ends up reaches the terminal.
+ ///
+ /// ⚠️ **iOS rewrites the whole word on every key typed into it** — with
+ /// autocorrect on, which Telex needs (see [_openInputConnection]). It selects
+ /// the word WITH the space before it (a selection change, the text untouched),
+ /// deletes that, then types the space and the word back a letter or a few at a
+ /// time: " b" + `a` arrived as " b" [1..3] → " " → " " → " ba". Forwarded
+ /// step by step, every key became a run of deletes and retypes on the
+ /// terminal — the word visibly vanishing and coming back — and a word at the
+ /// start of the buffer lost more than that: the space it deleted is one of the
+ /// buffer's padding spaces ([_initEditingState]), which stand for text the
+ /// terminal had BEFORE the buffer, so the step deleted a character the person
+ /// typed earlier; and the step, no longer starting with the padding, reset the
+ /// buffer under the keyboard while it was still mid-rewrite, after which its
+ /// next edit was read against a buffer it no longer had and the word just
+ /// typed was deleted ("ban" came out "n"). Measured on a phone, 2026-10-05.
+ ///
+ /// So the selection change that starts a rewrite starts a hold: every edit
+ /// after it only updates the buffer, until [_rewriteQuiet] passes with none,
+ /// and then the terminal gets one edit — from what it had to where the
+ /// keyboard ended. Typing that is not a rewrite (an ordinary key appended, a
+ /// Backspace, a composition) never waits.
+ bool _holdRewrite(TextEditingValue value) {
+ final holding = _rewriteSettle != null;
+ if (!holding) {
+ final startsRewrite = _composesThroughSoftwareKeyboard &&
+ value.composing.isCollapsed &&
+ !value.selection.isCollapsed &&
+ value.text == _currentEditingState.text &&
+ value.text == _terminalText;
+ if (!startsRewrite) return false;
+ }
+ _currentEditingState = value;
+ _rewriteSettle?.cancel();
+ _rewriteSettle = Timer(_rewriteQuiet, _settleRewrite);
+ return true;
+ }
+
+ /// The rewrite [_holdRewrite] is holding, applied now: the terminal goes from
+ /// what it has to what the buffer ended on, in one edit. Nothing without one.
+ void _settleRewrite() {
+ final timer = _rewriteSettle;
+ if (timer == null) return;
+ timer.cancel();
+ _rewriteSettle = null;
+ final value = _currentEditingState;
+ _applyEditingValue(value, hasTextMutation: value.text != _terminalText);
+ }
+
/// Drops the newline described by [_pendingActionEcho] and puts the native
/// buffer back on the state the action left, so the line the terminal was
/// already sent cannot be typed a second time.
@@ -448,6 +515,8 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
@override
void performAction(TextInputAction action) {
+ // The line goes as the keyboard ended it, before the action acts on it.
+ _settleRewrite();
// Captured before the handler runs: it is what the pty has been sent, and
// what iOS is about to append its newline to. See [_pendingActionEcho].
_pendingActionEcho = _currentEditingState.text;
@@ -456,6 +525,7 @@ class CustomTextEditState extends State<CustomTextEdit> with TextInputClient {
@override
void performSelector(String selectorName) {
+ _settleRewrite();
if (!selectorName.startsWith('deleteBackward')) return;
// A marked string belongs entirely to the IME. It will send a fresh