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.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: implement PhoneSearchOrder to maintain row stability during searches
Dev jacobfd355ac1330d
diff --git a/mobile/lib/phone/phone_search_index.dart b/mobile/lib/phone/phone_search_index.dartindex af804ff34..161deed57 100644--- a/mobile/lib/phone/phone_search_index.dart+++ b/mobile/lib/phone/phone_search_index.dart@@ -94,6 +94,10 @@ class PhoneSearchResult {/// Everything one query can reach, unfiltered: agents most recent first (see/// [recentAgents]).///+/// Recomputed on every rebuild, so the recency in it is live — which is why the+/// screen drawing it pins the order down rather than following it. See+/// `PhoneSearchOrder`.+////// Agents come from [agentIndex], so only machines that are LINKED and answering/// contribute — a row offered here has to be openable, and an offline machine's/// last-seen agent list is not. Machines are not listed: they are reached fromdiff --git a/mobile/lib/phone/phone_search_order.dart b/mobile/lib/phone/phone_search_order.dartnew file mode 100644index 000000000..3fe3ada54--- /dev/null+++ b/mobile/lib/phone/phone_search_order.dart@@ -0,0 +1,49 @@+import 'phone_search_index.dart';++/// The place each row keeps for as long as one search is open.+///+/// ⚠️ **A list somebody is reading must not reorder itself.** [phoneSearchIndex]+/// hands its rows in `recentAgents` order, and recency MOVES: every turn event+/// stamps its agent's `lastActiveAt`, and that row jumps to the top — from under+/// a finger already on its way to the row that was there. On a fleet with+/// several agents working it never settles, and a turn left open by a restarted+/// daemon heartbeats every second for ever, so the list reshuffles roughly as+/// fast as it can be read. What the person gets for it is a tap on the wrong+/// agent.+///+/// So the order is taken ONCE — from the first index this search is built with,+/// which is the ranked one worth offering — and every rebuild after that is+/// arranged back into it. The rows still say what is true right now: `working`+/// replaces an age, a quote appears under a name as its preview lands. Only+/// WHERE they are is held still.+///+/// One search, one order: both ways in mount [PhoneSearchResults] when the+/// search opens and drop it when it closes, so the next one opens freshly+/// ranked rather than on an order frozen minutes ago.+class PhoneSearchOrder {+ /// Row id → its place. Ids are [PhoneSearchResult.id], stable across rebuilds.+ final Map<String, int> _slots = {};++ int _next = 0;++ /// [rows] in the frozen order, rows this search has not seen before last.+ ///+ /// An agent that appears mid-search — one just created, or a machine that has+ /// only now answered — goes to the END rather than into the middle. Dropping+ /// it into recency order would be exactly the shove this class exists to+ /// stop, and a row nobody has looked for yet has not earned the top of a list+ /// somebody is already reading.+ ///+ /// ⚠️ **A slot is never released.** A machine redialling takes its agents out+ /// of `agentIndex` for the length of the redial (`phoneMachineListsAgents`),+ /// which backgrounding the app does every time. Forgetting them there would+ /// send every one of that machine's rows to the bottom of the list and back+ /// on each reconnect — the same jump, arriving by the other door. Kept, they+ /// come back exactly where they were.+ List<PhoneSearchResult> arrange(List<PhoneSearchResult> rows) {+ for (final row in rows) {+ _slots.putIfAbsent(row.id, () => _next++);+ }+ return [...rows]..sort((a, b) => _slots[a.id]!.compareTo(_slots[b.id]!));+ }+}diff --git a/mobile/lib/phone/phone_search_rank.dart b/mobile/lib/phone/phone_search_rank.dartindex 2728a0c00..bd34ae931 100644--- a/mobile/lib/phone/phone_search_rank.dart+++ b/mobile/lib/phone/phone_search_rank.dart@@ -93,10 +93,11 @@ const _contentScore = 256;/// needed the content to match rank after every row that matched on the agent/// itself, as on the desktop.///-/// ⚠️ Ties break on the row's position in the index, never on anything that-/// moves by itself. An agent that starts working sorts upward in [agentIndex],-/// and that is the one reshuffle worth having; a second, unstable tiebreak on-/// top of it would let two idle rows swap places on an unrelated rebuild.+/// ⚠️ Ties break on the row's position in [all], never on anything that moves+/// by itself — and [all] is held still for the length of one search by+/// `PhoneSearchOrder`, so a tie settled on this keystroke is settled the same+/// way on the next one. A second, unstable tiebreak on top of it would let two+/// idle rows swap places on an unrelated rebuild.List<PhoneSearchResult> rankPhoneSearch(List<PhoneSearchResult> all,String query,diff --git a/mobile/lib/phone/phone_search_results.dart b/mobile/lib/phone/phone_search_results.dartindex 12cfcf5b5..ae1976bad 100644--- a/mobile/lib/phone/phone_search_results.dart+++ b/mobile/lib/phone/phone_search_results.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:flutter/material.dart';import 'package:lucide_icons_flutter/lucide_icons.dart';@@ -10,6 +12,7 @@ import 'phone_navigation.dart';import 'phone_search_folder_header.dart';import 'phone_search_groups.dart';import 'phone_search_index.dart';+import 'phone_search_order.dart';import 'phone_search_rank.dart';import 'phone_search_row.dart';import 'phone_section_label.dart';@@ -28,6 +31,11 @@ import 'phone_section_label.dart';/// Keystrokes only ever read it, so typing stays instant and costs no data;/// opening the search just moves the agents offered first to the front of its/// background reads.+///+/// Opening it also re-reaches every machine on the account+/// ([AppNotifier.reachAllMachines]) and pins the rows where they are drawn+/// ([PhoneSearchOrder]) — the list fills out, and never reorders while it is+/// being read.class PhoneSearchResults extends StatefulWidget {const PhoneSearchResults({super.key,@@ -57,10 +65,21 @@ class _PhoneSearchResultsState extends State<PhoneSearchResults> {widget.notifier.sessionPreviews,]);+ /// Holds the rows where they were first drawn — see [PhoneSearchOrder]. Owned+ /// by the State, so it lives exactly as long as one search.+ final _order = PhoneSearchOrder();+@overridevoid initState() {super.initState();final notifier = widget.notifier;+ // ⚠️ **Opening the search is what re-reaches the fleet.** Until here the app+ // has only the machines that happened to answer at launch, and a machine the+ // account reported down was never even dialled — so the one screen that+ // claims to search EVERY agent was the one screen quietly missing whole+ // machines of them. Asked on the way in, not awaited: what is already known+ // draws immediately, and each machine adds its agents as it answers.+ unawaited(notifier.reachAllMachines());notifier.sessionPreviews.warm([for (final entry in recentAgents(agentIndex(notifier)))notifier.previewKey(entry.machineId, entry.agent),@@ -72,7 +91,7 @@ class _PhoneSearchResultsState extends State<PhoneSearchResults> {listenable: _changes,builder: (context, _) {AppTheme.watch(context);- final all = phoneSearchIndex(widget.notifier);+ final all = _order.arrange(phoneSearchIndex(widget.notifier));if (all.isEmpty) {return const EmptyState(icon: LucideIcons.laptopMinimal300,@@ -93,7 +112,9 @@ class _PhoneSearchResultsState extends State<PhoneSearchResults> {},);- /// Every agent in one run, the one that moved last on top.+ /// Every agent in one run, the one that had moved last WHEN THE SEARCH OPENED+ /// on top — and still on top a minute later, whatever has moved since. See+ /// [PhoneSearchOrder].////// No folder headers here. Before a word is typed the question is "which one/// was I just on", and grouping answers a different one: a folder with onediff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex f6f831432..a7d740cfd 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -3290,12 +3290,17 @@ class AppNotifier extends ChangeNotifier {// real launch measured four of those, `10002ms` apiece, while the one// live machine had been ready since 3s.//- // Nothing is lost by skipping them. `_applyNodeStatus` has already put- // each one on the 5-second offline poll (`_startOfflineRetry`), which- // dials the moment it comes back, and a pull-to-refresh still reaches- // every machine through `refreshMachines`. The tiles say "Offline", which- // is both true and immediate, instead of "Connecting…" for ten seconds- // before saying the same thing.+ // The tiles say "Offline", which is both true and immediate, instead of+ // "Connecting…" for ten seconds before saying the same thing.+ //+ // ⚠️ **This is NOT covered by the 5-second offline poll, whatever it+ // looks like.** `_startOfflineRetry` bails for a REMOTE machine unless+ // something is already waiting on one of its agents+ // (`pendingOfflineAgentId`) — and on a phone every machine is remote. So+ // a machine skipped here is not dialled again by anything on a timer: it+ // stays invisible, its agents included, until a pull-to-refresh+ // (`retryMachines`) or the search asks ([reachAllMachines]). That gap is+ // what "it only shows the sessions on one machine" was.//// A null answer means the account did not say — an older backend, or a// status this app does not recognise. That still dials: silence is not@@ -4323,6 +4328,46 @@ class AppNotifier extends ChangeNotifier {await _loadMachineData(machine, force: true);}+ /// Dial and re-ask EVERY machine on the account, whatever the account last+ /// said about any of them.+ ///+ /// For the screen that offers the whole fleet in one list — the search, which+ /// is the one place somebody asks "where is that agent" without knowing which+ /// machine holds it, and so the one place a missing machine is a wrong answer+ /// rather than a shorter list.+ ///+ /// ⚠️ **This deliberately dials machines [_autoConnectAndLoadMachines]+ /// skipped.** Not dialling a machine the account reported down is right at+ /// launch — finding out costs the full inventory budget EACH, and four dead+ /// machines held the screen ten seconds apiece — and wrong here. That status+ /// is a snapshot from before the app was opened; a machine that has come up+ /// since contributes nothing, because [agentIndex] lists only a machine that+ /// is answering. Reported as "it only shows the sessions on one machine".+ ///+ /// ⚠️ Contrast [_canFetchPreview], which must never dial, and still must not.+ /// That one is per AGENT — dozens of reads, each able to wake a relay socket+ /// for one row's subtitle. This is one `agents_list` per machine, and the+ /// list is what the search has nothing to offer without.+ ///+ /// ⚠️ **No `/api/machines` round trip.** It asks the machines the app already+ /// knows, so a phone on two bars still reaches all of them; an account fetch+ /// that failed would otherwise take the dials down with it, which is exactly+ /// what [retryMachines] does when it returns early. A machine ADDED to the+ /// account since launch is therefore not found here — it arrives through the+ /// Machines tab's pull-to-refresh, the screen whose job is listing them.+ ///+ /// Nothing on screen waits for this: each machine publishes as it answers,+ /// and the rows already drawn keep their places (`PhoneSearchOrder`).+ Future<void> reachAllMachines() async {+ // No transport yet — before sign-in, or in a test with no fake connection.+ // The same guard [_canFetchPreview] uses, and for the same reason: `_conn`+ // would build one out of a null pool.+ if (_disposed || (_pool == null && connectionForTest == null)) return;+ await Future.wait([+ for (final machine in machines) reloadMachineData(machine.machineId),+ ]);+ }+/// What every connected REMOTE machine's agent accounts have spent, asked in/// parallel and read there with that machine's own credentials (`usage_read`).///diff --git a/mobile/test/phone_search_test.dart b/mobile/test/phone_search_test.dartindex 0f7f364bb..bc3f2ecff 100644--- a/mobile/test/phone_search_test.dart+++ b/mobile/test/phone_search_test.dart@@ -9,6 +9,7 @@ import 'package:harness_mobile/phone/phone_search_field.dart';import 'package:harness_mobile/phone/phone_search_folder_header.dart';import 'package:harness_mobile/phone/phone_search_groups.dart';import 'package:harness_mobile/phone/phone_search_index.dart';+import 'package:harness_mobile/phone/phone_search_order.dart';import 'package:harness_mobile/phone/phone_search_page.dart';import 'package:harness_mobile/phone/phone_search_rank.dart';import 'package:harness_mobile/phone/terminal_search.dart';@@ -61,12 +62,16 @@ void _markWaiting(MachineState machine, String agentId) =>since: _now,);-AppNotifier _app(List<MachineState> machines, {WsConn? conn}) {+AppNotifier _app(+ List<MachineState> machines, {+ WsConn? conn,+ WsConn Function(String machineId)? connFor,+}) {final app = AppNotifier(config: AppConfig.dev,authSession: AuthSession(),configStore: null,- connectionForTest: conn == null ? null : (_) => conn,+ connectionForTest: connFor ?? (conn == null ? null : (_) => conn),);app.machines = [for (final state in machines) state.machine];for (final state in machines) {@@ -93,19 +98,67 @@ class _RecentConn extends WsConn {final Map<String, List<String>> asks;final asked = <String>[];+ /// Already handshaken. The real wait is on a socket a fake has not got, so+ /// leaving it to time out costs every test the full inventory budget in real+ /// seconds — and leaves a pending timer behind when the tree is torn down.+ @override+ Future<void> waitUntilReady({required Duration timeout}) async {}+@overrideFuture<Map<String, dynamic>> request(String type, {Map<String, dynamic> payload = const {},Duration timeout = const Duration(seconds: 20),}) async {- if (type != 'agent_recent') return {'error': 'UNEXPECTED'};+ // ⚠️ A real [WsConn] completes an error reply as an error (`ws_conn.dart`),+ // never as a map. Returning one here let `agents_list` read `agents: null`+ // as "this machine has no agents" and wipe the list the test had set up.+ if (type != 'agent_recent') throw StateError('unexpected $type');final agentId = payload['agentId'] as String;asked.add(agentId);return {'agentId': agentId, 'events': const [], 'asks': asks[agentId]};}}+/// One machine that answers `agents_list`, and records that it was asked.+///+/// The fleet shares one [asked] list, so a test can say WHICH machines the+/// screen reached rather than only that something was sent.+class _FleetConn extends WsConn {+ _FleetConn(String machineId, this.agents, this.asked)+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: machineId,+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ /// The agent frames this machine hands back, as the daemon would send them.+ final List<Map<String, dynamic>> agents;++ final List<String> asked;++ /// Already handshaken. The real wait is on a socket a fake has not got, so+ /// leaving it to time out costs every test the full inventory budget in real+ /// seconds — and leaves a pending timer behind when the tree is torn down.+ @override+ Future<void> waitUntilReady({required Duration timeout}) async {}++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type != 'agents_list') throw StateError('unexpected $type');+ asked.add(machineId);+ return {'agents': agents};+ }+}+/// Lets every in-flight `agent_recent` reply land.Future<void> _settle() async {for (var i = 0; i < 8; i++) {@@ -407,6 +460,172 @@ void main() {expect(find.byType(PhoneSearchFolderHeader), findsOneWidget);});+ group('the list holds still while it is being read', () {+ test('a row that moves in the index keeps the place it was drawn in', () {+ final machine = _machine('box', [+ _agent('first', minutesAgo: 1),+ _agent('second', minutesAgo: 2),+ _agent('third', minutesAgo: 3),+ ]);+ final app = _app([machine]);+ addTearDown(app.dispose);+ final order = PhoneSearchOrder();+ expect(_agentIds(order.arrange(phoneSearchIndex(app))), [+ 'first',+ 'second',+ 'third',+ ]);++ // What a turn event does: the oldest agent is suddenly the most recent,+ // and `recentAgents` puts it on top.+ machine.agentActivityAt['third'] = DateTime.now();+ expect(_agentIds(phoneSearchIndex(app)), ['third', 'first', 'second']);+ // The list somebody is reading does not follow it.+ expect(_agentIds(order.arrange(phoneSearchIndex(app))), [+ 'first',+ 'second',+ 'third',+ ]);+ });++ test('an agent that starts working stays where it is', () {+ final machine = _machine('box', [+ _agent('idle', minutesAgo: 1),+ _agent('busy', minutesAgo: 90),+ ]);+ final app = _app([machine]);+ addTearDown(app.dispose);+ final order = PhoneSearchOrder();+ expect(_agentIds(order.arrange(phoneSearchIndex(app))), ['idle', 'busy']);++ machine.processingAgentIds.add('busy');+ expect(_agentIds(phoneSearchIndex(app)), ['busy', 'idle']);+ expect(_agentIds(order.arrange(phoneSearchIndex(app))), ['idle', 'busy']);+ });++ test('an agent that arrives mid-search goes last, not into the middle', () {+ final machine = _machine('box', [+ _agent('first', minutesAgo: 10),+ _agent('second', minutesAgo: 20),+ ]);+ final app = _app([machine]);+ addTearDown(app.dispose);+ final order = PhoneSearchOrder();+ order.arrange(phoneSearchIndex(app));++ // The freshest agent on the account — and still it waits at the bottom+ // rather than shoving the two rows somebody is looking at down one.+ machine.agents = [...machine.agents, _agent('joined', minutesAgo: 0)];+ expect(_agentIds(order.arrange(phoneSearchIndex(app))), [+ 'first',+ 'second',+ 'joined',+ ]);+ });++ test('a machine redialling gives its rows back where they were', () {+ final box = _machine('box', [_agent('a', minutesAgo: 5)]);+ final lab = _machine('lab', [_agent('b', minutesAgo: 50)]);+ final app = _app([box, lab]);+ addTearDown(app.dispose);+ final order = PhoneSearchOrder();+ expect(_agentIds(order.arrange(phoneSearchIndex(app))), ['a', 'b']);++ // Backgrounding the app drops every socket; `box` is the one that has not+ // answered yet on the way back.+ box+ ..connectionStatus = ConnectionStatus.connecting+ ..agentLoadStatus = AgentLoadStatus.loading;+ expect(_agentIds(order.arrange(phoneSearchIndex(app))), ['b']);++ box+ ..connectionStatus = ConnectionStatus.connected+ ..agentLoadStatus = AgentLoadStatus.loaded;+ expect(_agentIds(order.arrange(phoneSearchIndex(app))), ['a', 'b']);+ });+ });++ testWidgets('opening search reaches machines that never answered at launch', (+ tester,+ ) async {+ final asked = <String>[];+ final conns = {+ 'box': _FleetConn('box', [+ {'id': 'known', 'name': 'work · known'},+ ], asked),+ // The machine the account reported down at launch, so it was never+ // dialled — and whose agents the search therefore could not offer.+ 'lab': _FleetConn('lab', [+ {'id': 'unseen', 'name': 'work · unseen'},+ ], asked),+ };+ final box = _machine('box', [_agent('known', minutesAgo: 5)]);+ final lab = _machine('lab', [])+ ..nodeOnline = false+ ..connectionStatus = ConnectionStatus.disconnected+ ..agentLoadStatus = AgentLoadStatus.loading;+ final app = _app([box, lab], connFor: (machineId) => conns[machineId]!);+ addTearDown(app.dispose);++ await tester.pumpWidget(MaterialApp(home: PhoneSearchPage(notifier: app)));+ await tester.pump(const Duration(milliseconds: 100));++ // Opening the search asked BOTH — the whole point. Before this it asked+ // only the machines that happened to answer at launch, and `lab` was not+ // even dialled.+ expect(asked, containsAll(<String>['box', 'lab']));+ // Its list is in, but the account's stale word for it still hides it.+ expect(lab.agents.map((agent) => agent.id), ['unseen']);+ expect(find.text('work · known'), findsOneWidget);+ expect(find.text('work · unseen'), findsNothing);++ // What a successful dial does to that stale word: `_onConnectionStatus`+ // routes a connect through `_applyNodeStatus(machine, true)`. There is no+ // pool behind a fake connection to fire it, so the test says it instead.+ lab.nodeOnline = true;+ app.notifyListeners();+ await tester.pump();++ expect(find.text('work · unseen'), findsOneWidget);+ // And it arrives at the END, not on top: the row somebody was already+ // reaching for does not move to make room for it.+ expect(+ tester.getTopLeft(find.text('work · known')).dy,+ lessThan(tester.getTopLeft(find.text('work · unseen')).dy),+ );+ });++ testWidgets('the Recent list does not reshuffle under a finger', (+ tester,+ ) async {+ final machine = _machine('box', [+ _agent('3188', minutesAgo: 4),+ _agent('2312', minutesAgo: 30),+ _agent('9999', minutesAgo: 90),+ ]);+ final app = _app([machine]);+ addTearDown(app.dispose);+ await tester.pumpWidget(MaterialApp(home: PhoneSearchPage(notifier: app)));+ await tester.pump();+ double top(String name) => tester.getTopLeft(find.text(name)).dy;+ final was = top('work · 9999');+ expect(top('work · 3188'), lessThan(top('work · 2312')));++ // The reported case: a heartbeat lands on the bottom row while somebody is+ // reaching for it. Before this, the row jumped to the top and the tap+ // landed on whatever had taken its place.+ machine.agentActivityAt['9999'] = DateTime.now();+ app.notifyListeners();+ await tester.pump();++ expect(top('work · 9999'), was);+ expect(top('work · 3188'), lessThan(top('work · 2312')));+ expect(top('work · 2312'), lessThan(top('work · 9999')));+ // Still live in what it SAYS — only where it sits is pinned.+ expect(find.text('now'), findsOneWidget);+ expect(find.text('90m'), findsNothing);+ });+testWidgets('opening search warms content; the matching line is quoted', (tester,) async {