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): load Find recaps for visible rows in large lists

tony2442298f3b11
diff --git a/mobile/lib/phone/agent_recap.dart b/mobile/lib/phone/agent_recap.dart
index 81dce5161..a2d79c1e1 100644
--- a/mobile/lib/phone/agent_recap.dart
+++ b/mobile/lib/phone/agent_recap.dart
@@ -48,6 +48,35 @@ PhoneRecap? phoneRecap(SessionPreviewStore previews, SessionPreviewKey? key) {
if (preview == null) return null;
final headline = preview.recap;
final saved = preview.savedText;
+ final body = preview.response;
+ // Find rebuilds on every preview the store publishes — as often as every 80 ms while an agent
+ // streams — and a streamed delta moves none of these three. Same strings, same recap: the
+ // flattening is not run again.
+ final memo = _recaps[preview];
+ if (memo != null &&
+ identical(memo.headline, headline) &&
+ identical(memo.saved, saved) &&
+ identical(memo.body, body)) {
+ return memo.recap;
+ }
+ final recap = _recapOf(headline, saved, body);
+ _recaps[preview] = (
+ headline: headline,
+ saved: saved,
+ body: body,
+ recap: recap,
+ );
+ return recap;
+}
+
+/// The last recap [phoneRecap] made for each preview, with the strings it was made from. Held
+/// beside the preview rather than in it, so it goes when the store lets the preview go.
+final _recaps =
+ Expando<
+ ({String? headline, String? saved, String? body, PhoneRecap? recap})
+ >('phoneRecap');
+
+PhoneRecap? _recapOf(String? headline, String? saved, String? body) {
if (headline != null && saved != null) {
final flat = flattenRecap(headline);
if (flat.isNotEmpty) {
@@ -58,7 +87,6 @@ PhoneRecap? phoneRecap(SessionPreviewStore previews, SessionPreviewKey? key) {
);
}
}
- final body = preview.response;
if (body == null) return null;
final flat = _flattenHead(body);
if (flat.isEmpty) return null;
diff --git a/mobile/lib/phone/phone_search_controller.dart b/mobile/lib/phone/phone_search_controller.dart
index e7325fa64..eb0f6bc09 100644
--- a/mobile/lib/phone/phone_search_controller.dart
+++ b/mobile/lib/phone/phone_search_controller.dart
@@ -325,9 +325,9 @@ class PhoneSearchController extends ChangeNotifier {
/// Announce a change the APP made, one microtask late.
///
/// ⚠️ **Never synchronously, because these two arrive mid-build.**
- /// [PhoneSearchResults] warms the preview store from its `initState`, and the
- /// store publishes to its listeners as it goes — so the controller was told to
- /// re-rank while the very list watching it was still being built, and
+ /// [PhoneSearchResults] once warmed the preview store from its `initState`,
+ /// and the store publishes to its listeners as it goes — so the controller was
+ /// told to re-rank while the very list watching it was still being built, and
/// `markNeedsBuild` threw. A microtask drains after the build phase, which is
/// the earliest moment a rebuild can legally be asked for.
///
diff --git a/mobile/lib/phone/phone_search_results.dart b/mobile/lib/phone/phone_search_results.dart
index 3fd0258c3..ce6093d78 100644
--- a/mobile/lib/phone/phone_search_results.dart
+++ b/mobile/lib/phone/phone_search_results.dart
@@ -7,6 +7,8 @@ import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/notify/agent_notice.dart' show NoticeKind;
import 'package:harness_mobile/state/app_state.dart';
import 'package:harness_mobile/state/external_session.dart';
+import 'package:harness_mobile/state/session_preview.dart'
+ show SessionPreviewKey;
import 'agent_index.dart';
import 'agent_recap.dart';
@@ -151,10 +153,38 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
WidgetsBinding.instance.addPostFrameCallback((_) {
if (mounted) unawaited(notifier.reachAllMachines());
});
- notifier.sessionPreviews.warm([
- for (final entry in recentAgents(agentIndex(notifier)))
- notifier.previewKey(entry.machineId, entry.agent),
- ], prioritize: true);
+ // No warm of the recaps here: each row asks for its own as it is built — see [_want].
+ }
+
+ /// The sessions whose rows this frame built, read once it is over — see [_want].
+ final _wanted = <SessionPreviewKey>{};
+ bool _warmScheduled = false;
+
+ /// Asks for what [key]'s session last said, because its row is on screen or about to be.
+ ///
+ /// ⚠️ **By the rows built, not the agents known.** Warming the first 32 agents by recency, as
+ /// this did on open, read rows in an order Find does not draw them in — needs you, the frozen
+ /// open order, paused last — and never reached a row past the 32nd: a list of a hundred sessions
+ /// held two thirds of its recaps empty however far it was scrolled. The list is lazy, so the rows
+ /// built are the ones in view and the next few below; asked for top first and ahead of anything
+ /// already queued, they fill in in the order they are read.
+ ///
+ /// After the frame, in one batch: warming mid-build would start reads from inside a layout, and a
+ /// row at a time would reorder the store's queue once per row. Asked again on every rebuild —
+ /// the store skips what is in flight or fresh, so that costs a lookup a row, and a row still on
+ /// screen after [SessionPreviewStore.freshFor] is read again.
+ void _want(SessionPreviewKey key) {
+ _wanted.add(key);
+ if (_warmScheduled) return;
+ _warmScheduled = true;
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ _warmScheduled = false;
+ final keys = _wanted.toList();
+ _wanted.clear();
+ if (mounted) {
+ widget.notifier.sessionPreviews.warm(keys, prioritize: true);
+ }
+ });
}
@override
@@ -329,25 +359,33 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
final selectedAt = typed ? ordered.indexWhere(search.canSubmit) : -1;
final newHarness = widget.onNewHarness;
final project = search.projectMatch;
- final children = <Widget>[];
+ // ⚠️ **Built as they scroll in, not all at once.** Each entry makes its widget only when the
+ // list asks for it, so a hundred sessions cost the rows in view: their state words, their lit
+ // matches, their recaps — and the read that fetches each recap ([_want]). An eager list did all
+ // of that for every row on every rebuild, and this screen rebuilds on every preview the store
+ // publishes.
+ final items = <Widget Function()>[];
+ // Where each session's entry is, so a row keeps its own element when the ranking moves it.
+ final rowAt = <String, int>{};
var index = 0;
- // A row, and under it what its session last came to.
- List<Widget> row(PhoneDestination row) => [
- _findRow(row, terms, now, tty, selected: index++ == selectedAt),
- ?_recap(row),
- ];
+ void row(PhoneDestination row) {
+ final selected = index++ == selectedAt;
+ rowAt[row.id] = items.length;
+ items.add(() => _session(row, terms, now, tty, selected: selected));
+ }
+
if (needsYou.isNotEmpty) {
- children.add(FindHeader('needs you', color: tty.yellow));
- children.addAll(needsYou.expand(row));
- children.add(const FindHeader('recent'));
+ items.add(() => FindHeader('needs you', color: tty.yellow));
+ needsYou.forEach(row);
+ items.add(() => const FindHeader('recent'));
}
- children.addAll(rest.expand(row));
- if (current != null) children.addAll(row(current));
+ rest.forEach(row);
+ if (current != null) row(current);
// At the end and without a heading: each one's own word on the right says `paused`.
- children.addAll(pausedRows.expand(row));
+ pausedRows.forEach(row);
if (ordered.isEmpty) {
- children.add(
- Padding(
+ items.add(
+ () => Padding(
padding: const EdgeInsets.fromLTRB(Tty.origin, 20, Tty.origin, 8),
child: TtyText(
switch (tab) {
@@ -367,8 +405,8 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
// The way out of an empty tab, where the eye already is — rather than back up at a chip the
// rail may have scrolled away.
if (tab != null && (!typed || everywhere > 0)) {
- children.add(
- FindRow(
+ items.add(
+ () => FindRow(
title: 'Show all tabs',
detail: typed
? '$everywhere ${everywhere == 1 ? 'match' : 'matches'} in all tabs'
@@ -379,10 +417,10 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
}
}
if (search.commandMatches.isNotEmpty) {
- children.add(const FindHeader('commands'));
+ items.add(() => const FindHeader('commands'));
for (final command in search.commandMatches) {
- children.add(
- FindRow(
+ items.add(
+ () => FindRow(
title: command.title,
terms: terms,
state: command.shortcut,
@@ -393,9 +431,9 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
}
if (newHarness != null && plain) {
final place = project == null ? null : _projectPlace(project);
- children.add(const SizedBox(height: 8));
- children.add(
- FindAddRow(
+ items.add(() => const SizedBox(height: 8));
+ items.add(
+ () => FindAddRow(
label: place == null
? 'New Harness'
: 'New Harness in ${project!.title}',
@@ -404,11 +442,39 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
),
);
}
- children.add(const SizedBox(height: 24));
- return ListView(
+ items.add(() => const SizedBox(height: 24));
+ return ListView.builder(
keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,
padding: EdgeInsets.zero,
- children: children,
+ itemCount: items.length,
+ itemBuilder: (context, i) => items[i](),
+ findChildIndexCallback: (key) =>
+ key is ValueKey<String> ? rowAt[key.value] : null,
+ );
+ }
+
+ /// One session's entry in the list: its row, and under it what the session last came to.
+ ///
+ /// Keyed by the row's id — what [ListView.builder]'s `findChildIndexCallback` looks it up by — so
+ /// a recap somebody is unfolding stays with its session when a match moves it up the list.
+ Widget _session(
+ PhoneDestination row,
+ List<String> terms,
+ DateTime now,
+ Tty tty, {
+ required bool selected,
+ }) {
+ final line = _findRow(row, terms, now, tty, selected: selected);
+ final recap = _recap(row);
+ return KeyedSubtree(
+ key: ValueKey(row.id),
+ child: recap == null
+ ? line
+ : Column(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ mainAxisSize: MainAxisSize.min,
+ children: [line, recap],
+ ),
);
}
@@ -418,6 +484,7 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
if (!row.isAgent) return null;
final previews = widget.notifier.sessionPreviews;
final key = row.previewKey;
+ if (key != null) _want(key);
final recap = phoneRecap(previews, key);
if (recap != null) {
return AgentRecap(
@@ -428,7 +495,7 @@ class PhoneSearchResultsState extends State<PhoneSearchResults> {
}),
);
}
- if (key != null && previews.isReading(key)) {
+ if (key != null && previews.isPending(key)) {
return const AgentRecapPlaceholder();
}
return null;
diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dart
index 889a64b4d..8ccc108de 100644
--- a/mobile/lib/state/app_state.dart
+++ b/mobile/lib/state/app_state.dart
@@ -282,9 +282,14 @@ class AppNotifier extends ChangeNotifier {
/// Read again after [freshFor] at the soonest, not the desktop's minute: a
/// phone pays for the bytes, and the live events already keep a connected
/// machine's agents current.
+ ///
+ /// Four reads out at once, not the desktop's two: Find draws a recap under every row and reads
+ /// them as the rows come into view, and each read is one small relay round trip — two at a time
+ /// left a screenful of rows waiting on the latency rather than on the bytes.
late final sessionPreviews = SessionPreviewStore(
canFetch: _canFetchPreview,
freshFor: const Duration(minutes: 5),
+ maxInFlight: 4,
fetchRecent: (key) => _conn(key.machineId).request(
'agent_recent',
payload: {'agentId': key.agentId, 'n': 3},
diff --git a/mobile/lib/state/session_preview.dart b/mobile/lib/state/session_preview.dart
index 4f910d4dd..d2b141933 100644
--- a/mobile/lib/state/session_preview.dart
+++ b/mobile/lib/state/session_preview.dart
@@ -3,8 +3,9 @@
/// does. Keep the two in step; the additions here are
/// [SessionPreview.searchParts], which the phone's result rows quote from,
/// [SessionPreviewStore.markStale], for turns a sleeping phone never heard, and
-/// [SessionPreview.recap] with [SessionPreviewStore.isReading], for the recap
-/// under each row of the Harnesses list.
+/// [SessionPreview.recap] with [SessionPreviewStore.isPending], for the recap
+/// under each row of the Harnesses list, and
+/// [SessionPreviewStore.maxInFlight], so that list's rows fill in faster.
library;
import 'dart:async';
@@ -114,14 +115,16 @@ class SessionPreview {
}
/// Bounded memory shared across picker openings. Inventory warms small cached
-/// `agent_recent` replies with two requests at a time. Selection reads memory;
-/// a settled cold selection may schedule the same inexpensive background read.
+/// `agent_recent` replies with [maxInFlight] requests at a time. Selection
+/// reads memory; a settled cold selection may schedule the same inexpensive
+/// background read.
class SessionPreviewStore extends ChangeNotifier {
SessionPreviewStore({
required this.fetchRecent,
required this.canFetch,
this.capacity = 256,
this.freshFor = const Duration(minutes: 1),
+ this.maxInFlight = 2,
DateTime Function()? now,
}) : _now = now ?? DateTime.now;
@@ -129,6 +132,9 @@ class SessionPreviewStore extends ChangeNotifier {
final bool Function(SessionPreviewKey) canFetch;
final int capacity;
final Duration freshFor;
+
+ /// How many reads are out at once, across every machine. The desktop's two.
+ final int maxInFlight;
final DateTime Function() _now;
final _records = <SessionPreviewKey, SessionPreview>{};
final _queue = <SessionPreviewKey>{};
@@ -147,14 +153,24 @@ class SessionPreviewStore extends ChangeNotifier {
/// until [freshFor] runs out and something happens to warm it again.
void markStale(SessionPreviewKey key) => _records[key]?._attemptedAt = null;
- /// Whether [key] is being read, or is queued to be — what lets a row hold a
- /// placeholder for content on its way rather than grow when it lands.
+ /// Whether what [key] said is still to come: being read, queued to be, or
+ /// never read at all — what lets a row hold a placeholder for content on its
+ /// way rather than grow when it lands.
+ ///
+ /// ⚠️ **Never read counts.** Find warms the rows it draws one frame after
+ /// drawing them, so a row scrolled into view is not queued yet on its first
+ /// frame — and is about to be. A row that held nothing there and a
+ /// placeholder a frame later would flicker at the edge of every scroll.
///
/// False for a key that can no longer be fetched: a queued read of it is
/// dropped without a word ([_drain]), and a placeholder waiting on it would
- /// wait for ever.
- bool isReading(SessionPreviewKey key) =>
- (_inFlight.contains(key) || _queue.contains(key)) && canFetch(key);
+ /// wait for ever. False, too, once a read has answered, even with nothing or
+ /// an error: that session has nothing to show, not something on its way.
+ bool isPending(SessionPreviewKey key) {
+ if (!canFetch(key)) return false;
+ if (_inFlight.contains(key) || _queue.contains(key)) return true;
+ return !(_records[key]?.fetched ?? false);
+ }
SessionPreview _entry(SessionPreviewKey key) {
final entry = _records.remove(key) ?? SessionPreview();
@@ -193,7 +209,7 @@ class SessionPreviewStore extends ChangeNotifier {
}
void _drain() {
- while (!_disposed && _inFlight.length < 2 && _queue.isNotEmpty) {
+ while (!_disposed && _inFlight.length < maxInFlight && _queue.isNotEmpty) {
final key = _queue.first;
_queue.remove(key);
if (!canFetch(key)) continue;