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: implement phone search functionality with new UI components

Dev jacob0f8a4893829f
diff --git a/mobile/lib/core/models.dart b/mobile/lib/core/models.dart
index ca0408391..1add13218 100644
--- a/mobile/lib/core/models.dart
+++ b/mobile/lib/core/models.dart
@@ -119,6 +119,17 @@ class Agent {
final String id;
final String? sessionId;
final String name;
+
+ /// What the agent is on, in its own words — the transcript's title as the
+ /// daemon cleaned it, null when it has none or it is the name already. A
+ /// created agent keeps its `work · 3188` name while this moves with the work,
+ /// so it is what tells two such agents apart on a phone.
+ final String? title;
+
+ /// When the conversation was last written — the transcript's mtime, which the
+ /// daemon prefers over its own bookkeeping precisely so a client sorting by
+ /// recency follows the work. Null from a daemon too old to send it.
+ final DateTime? updatedAt;
final String? engine;
final String? engineDisplayName;
final String? engineIconHint;
@@ -136,6 +147,8 @@ class Agent {
required this.id,
this.sessionId,
required this.name,
+ this.title,
+ this.updatedAt,
this.engine,
this.engineDisplayName,
this.engineIconHint,
@@ -178,6 +191,8 @@ class Agent {
id: j['id'] as String,
sessionId: _safeLabel(j['sessionId']),
name: j['name'] as String? ?? 'agent',
+ title: _safeLabel(j['title']),
+ updatedAt: _safeTime(j['updatedAt']),
engine: _safeEngine(j['engine']),
engineDisplayName: _safeLabel(j['engineDisplayName']),
engineIconHint: _safeLabel(j['engineIconHint']),
@@ -202,6 +217,8 @@ class Agent {
id: id,
sessionId: sessionId,
name: name ?? this.name,
+ title: title,
+ updatedAt: updatedAt,
engine: engine,
engineDisplayName: engineDisplayName,
engineIconHint: engineIconHint,
@@ -236,6 +253,9 @@ class Agent {
return raw.length <= 80 ? raw : raw.substring(0, 80);
}
+ static DateTime? _safeTime(Object? raw) =>
+ raw is String && raw.length <= 64 ? DateTime.tryParse(raw) : null;
+
static String? _safeDetail(Object? raw) {
if (raw is! String || raw.isEmpty) return null;
final clean = raw.replaceAll(RegExp(r'[\u0000-\u001f\u007f]'), ' ').trim();
diff --git a/mobile/lib/phone/agent_index.dart b/mobile/lib/phone/agent_index.dart
index d93c6e180..6fb8a5129 100644
--- a/mobile/lib/phone/agent_index.dart
+++ b/mobile/lib/phone/agent_index.dart
@@ -63,26 +63,54 @@ List<AgentEntry> waitingAgents(List<AgentEntry> entries) =>
/// Sorted rather than left in machine order because "working" is the only remaining state that
/// changes on its own — an idle agent will still be idle in a minute, and a row that is moving is
/// the one worth putting where the eye lands.
-List<AgentEntry> otherAgents(List<AgentEntry> entries) {
- final rest = entries.where((entry) => !entry.isWaiting).toList();
- // A stable sort, which `List.sort` is not — see [filterableMachines] for the same technique and
- // the same reason. It matters more here than it does for the chips: the terminal page walks this
- // order to find the next agent along, so an unstable tie would let two idle agents swap places on
- // an unrelated rebuild and send a swipe to a different agent than the list was offering.
- final indexed = [for (final (index, entry) in rest.indexed) (index, entry)]
+List<AgentEntry> otherAgents(List<AgentEntry> entries) =>
+ // A stable sort, which `List.sort` is not. It matters more here than it does for the chips: the
+ // terminal page walks this order to find the next agent along, so an unstable tie would let two
+ // idle agents swap places on an unrelated rebuild and send a swipe to a different agent than the
+ // list was offering.
+ _stableSorted(
+ entries.where((entry) => !entry.isWaiting),
+ (a, b) =>
+ _firstWhere(a.isWorking, b.isWorking) ??
+ // Then agents that can actually be opened, so a row with no terminal never heads the list.
+ _firstWhere(a.agent.terminalAvailable, b.agent.terminalAvailable) ??
+ 0,
+ );
+
+/// Every agent, in the order search offers them before a word is typed: waiting on the person,
+/// then working, then the one whose conversation moved last.
+///
+/// The recency is what the tabs deliberately do NOT sort on — a list somebody browses must not
+/// reshuffle — but a search is opened to reach one agent and closed again, and the agent somebody
+/// reaches for is overwhelmingly the one that just finished. Agents from a daemon too old to send
+/// [Agent.updatedAt] keep their index order after every dated one.
+List<AgentEntry> recentAgents(List<AgentEntry> entries) => _stableSorted(
+ entries,
+ (a, b) =>
+ _firstWhere(a.isWaiting, b.isWaiting) ??
+ _firstWhere(a.isWorking, b.isWorking) ??
+ _firstWhere(a.agent.terminalAvailable, b.agent.terminalAvailable) ??
+ _newestFirst(a.agent.updatedAt, b.agent.updatedAt),
+);
+
+/// -1 when only [a] holds, 1 when only [b] does, null on a tie — so comparators chain with `??`.
+int? _firstWhere(bool a, bool b) => a == b ? null : (a ? -1 : 1);
+
+int _newestFirst(DateTime? a, DateTime? b) {
+ if (a == null || b == null) return _firstWhere(a != null, b != null) ?? 0;
+ return b.compareTo(a);
+}
+
+/// [items] sorted by [compare], ties kept in their incoming order — which `List.sort` does not
+/// promise. Every list here is walked by index by something (a pager, a chip rail), so a tie that
+/// flips on an unrelated rebuild moves a row out from under a finger.
+List<T> _stableSorted<T>(Iterable<T> items, int Function(T a, T b) compare) {
+ final indexed = [...items.indexed]
..sort((a, b) {
- final aEntry = a.$2;
- final bEntry = b.$2;
- if (aEntry.isWorking != bEntry.isWorking) {
- return aEntry.isWorking ? -1 : 1;
- }
- // Then agents that can actually be opened, so a row with no terminal never heads the list.
- final aOpen = aEntry.agent.terminalAvailable;
- final bOpen = bEntry.agent.terminalAvailable;
- if (aOpen != bOpen) return aOpen ? -1 : 1;
- return a.$1.compareTo(b.$1);
+ final order = compare(a.$2, b.$2);
+ return order != 0 ? order : a.$1.compareTo(b.$1);
});
- return [for (final (_, entry) in indexed) entry];
+ return [for (final (_, item) in indexed) item];
}
/// Every agent the list draws, in the order a finger meets them.
@@ -116,14 +144,9 @@ List<MachineState> filterableMachines(AppNotifier notifier) {
for (final machine in notifier.machines)
?notifier.stateOf(machine.machineId),
];
- // A stable sort, which `List.sort` is not — an unstable one would let two ready machines swap
- // places on an unrelated rebuild, moving a chip out from under a finger already reaching for it.
- final indexed = [for (final (index, state) in states.indexed) (index, state)]
- ..sort((a, b) {
- final rank = _chipRank(a.$2).compareTo(_chipRank(b.$2));
- return rank != 0 ? rank : a.$1.compareTo(b.$1);
- });
- return [for (final (_, state) in indexed) state];
+ // Stable, so two ready machines never swap places on an unrelated rebuild and move a chip out
+ // from under a finger already reaching for it.
+ return _stableSorted(states, (a, b) => _chipRank(a).compareTo(_chipRank(b)));
}
/// Where a machine's chip sits: lower sorts first.
diff --git a/mobile/lib/phone/compact_age.dart b/mobile/lib/phone/compact_age.dart
new file mode 100644
index 000000000..0285b75a0
--- /dev/null
+++ b/mobile/lib/phone/compact_age.dart
@@ -0,0 +1,14 @@
+/// How long ago [at] was, in the fewest characters a row's trailing edge can
+/// hold: `now`, `4m`, `2h`, `3d`, `5w`, `1y`.
+///
+/// A time in the future — a machine whose clock runs ahead of the phone's —
+/// reads as `now` rather than as a negative age.
+String compactAge(DateTime at, DateTime now) {
+ final age = now.difference(at);
+ if (age.inMinutes < 1) return 'now';
+ if (age.inHours < 1) return '${age.inMinutes}m';
+ if (age.inDays < 1) return '${age.inHours}h';
+ if (age.inDays < 7) return '${age.inDays}d';
+ if (age.inDays < 365) return '${age.inDays ~/ 7}w';
+ return '${age.inDays ~/ 365}y';
+}
diff --git a/mobile/lib/phone/phone_search_field.dart b/mobile/lib/phone/phone_search_field.dart
new file mode 100644
index 000000000..0713bb45f
--- /dev/null
+++ b/mobile/lib/phone/phone_search_field.dart
@@ -0,0 +1,209 @@
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+
+/// The search page's whole header: one bar, with the way out inside it.
+///
+/// Drawn here rather than through [PhoneHeader]: the page has no title. The
+/// field IS the header, because nothing else on the screen is worth the 32pt
+/// line a large title would take from the results.
+///
+/// The way back is a chevron at the bar's leading edge rather than a "Cancel"
+/// beside it. The word cost the field a fifth of the screen's width to say what
+/// the edge swipe, Android's back button and the chevron every other page wears
+/// already say; the chevron takes the place of the magnifier, which the hint
+/// text made redundant.
+class PhoneSearchField extends StatelessWidget {
+ const PhoneSearchField({
+ super.key,
+ required this.controller,
+ required this.focus,
+ required this.onChanged,
+ required this.onClear,
+ required this.onBack,
+ });
+
+ final TextEditingController controller;
+ final FocusNode focus;
+ final ValueChanged<String> onChanged;
+ final VoidCallback onClear;
+ final VoidCallback onBack;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(16, 8, 16, 8),
+ // The rim lives on the BOX, never on the TextField inside it — see the
+ // decoration below for why the field draws no border of its own. Listening
+ // to the node here is what lets the box carry the focus state instead.
+ child: ListenableBuilder(
+ listenable: focus,
+ builder: (context, child) => AnimatedContainer(
+ duration: AppMotion.hover,
+ curve: AppMotion.curve,
+ height: 44,
+ padding: const EdgeInsets.only(right: 12),
+ decoration: BoxDecoration(
+ color: AppGlass.rowFill,
+ borderRadius: BorderRadius.circular(AppCard.radius),
+ // Focus is said once, by the rim of the box the field fills. The
+ // accent is the same one the caret already uses, so the two read as
+ // one state rather than as two decorations.
+ border: Border.all(
+ color: focus.hasFocus
+ ? AppPalette.accentOnSurface
+ : AppGlass.hair,
+ ),
+ ),
+ child: child,
+ ),
+ child: Row(
+ children: [
+ _BackButton(onTap: onBack),
+ Expanded(
+ child: _QueryInput(
+ controller: controller,
+ focus: focus,
+ onChanged: onChanged,
+ ),
+ ),
+ _ClearButton(controller: controller, onTap: onClear),
+ ],
+ ),
+ ),
+ );
+ }
+}
+
+/// The bar's full height and a thumb's width, not the glyph's: the chevron sits
+/// against the bar's rounded edge, where a miss is the easiest to make.
+class _BackButton extends StatelessWidget {
+ const _BackButton({required this.onTap});
+
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Semantics(
+ button: true,
+ label: 'Back',
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: SizedBox(
+ width: 40,
+ height: 44,
+ child: Icon(
+ LucideIcons.chevronLeft300,
+ size: 22,
+ color: AppPalette.textPrimary,
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+class _QueryInput extends StatelessWidget {
+ const _QueryInput({
+ required this.controller,
+ required this.focus,
+ required this.onChanged,
+ });
+
+ final TextEditingController controller;
+ final FocusNode focus;
+ final ValueChanged<String> onChanged;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return TextField(
+ controller: controller,
+ focusNode: focus,
+ autofocus: true,
+ onChanged: onChanged,
+ // The list is already filtered by the time a key is released; there is
+ // nothing left for the return key to submit, so it stays a plain "done"
+ // that drops the keyboard and leaves the results up.
+ textInputAction: TextInputAction.search,
+ onSubmitted: (_) => focus.unfocus(),
+ autocorrect: false,
+ enableSuggestions: false,
+ // Agent names are ids as often as sentences — `Dijkstra-visualization.html`
+ // — and a capital forced onto the first letter of one is a wrong query.
+ textCapitalization: TextCapitalization.none,
+ // With the decoration's padding zeroed below, the field is exactly one line
+ // tall inside a 44pt box; this is what centres that line on the chevron
+ // beside it instead of letting it sit on the box's top edge.
+ textAlignVertical: TextAlignVertical.center,
+ style: TextStyle(color: AppPalette.textPrimary, fontSize: 16),
+ cursorColor: AppPalette.accentOnSurface,
+ decoration: InputDecoration(
+ isDense: true,
+ // ⚠️ **Every** border state, not just `border`.
+ //
+ // `border` alone is the wrong half of the fix: it is the fallback, and
+ // the app's `inputDecorationTheme` fills the named states in —
+ // `focusedBorder` is a 1.5px accent outline at [AppControl.radius] (8).
+ // This box is [AppCard.radius] (12), so focusing drew a second, tighter
+ // blue rectangle INSIDE the rim. Naming each state is what keeps the
+ // theme from reaching past `border`.
+ border: InputBorder.none,
+ enabledBorder: InputBorder.none,
+ focusedBorder: InputBorder.none,
+ errorBorder: InputBorder.none,
+ focusedErrorBorder: InputBorder.none,
+ disabledBorder: InputBorder.none,
+ // The theme also fills these, and both would draw on top of the box: a
+ // `surfaceContainerHighest` fill over the rim's own, and Material's
+ // phone-sized padding over the 44pt height set above.
+ filled: false,
+ contentPadding: EdgeInsets.zero,
+ constraints: const BoxConstraints(),
+ hintText: 'Search agents and machines',
+ hintStyle: TextStyle(color: AppPalette.textFaint, fontSize: 16),
+ ),
+ );
+ }
+}
+
+/// Only once there is something to clear: a button that does nothing on an
+/// empty field is a button people learn to skip.
+class _ClearButton extends StatelessWidget {
+ const _ClearButton({required this.controller, required this.onTap});
+
+ final TextEditingController controller;
+ final VoidCallback onTap;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return ValueListenableBuilder(
+ valueListenable: controller,
+ builder: (context, value, _) => value.text.isEmpty
+ ? const SizedBox.shrink()
+ : Semantics(
+ button: true,
+ label: 'Clear',
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: onTap,
+ child: Padding(
+ // Padding, not size: the glyph stays small while the target
+ // reaches a thumb.
+ padding: const EdgeInsets.only(left: 8),
+ child: Icon(
+ LucideIcons.circleX300,
+ size: 18,
+ color: AppPalette.textFaint,
+ ),
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/phone_search_folder_header.dart b/mobile/lib/phone/phone_search_folder_header.dart
new file mode 100644
index 000000000..b7bebf032
--- /dev/null
+++ b/mobile/lib/phone/phone_search_folder_header.dart
@@ -0,0 +1,60 @@
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+
+import 'phone_search_groups.dart';
+
+/// The line over one folder's agents: the folder, the machine it is on, and how
+/// many matched.
+///
+/// Carries the two things every row under it used to repeat, so each row's
+/// second line is left for what actually tells its agents apart. A folder glyph
+/// rather than an uppercase label, so it cannot be read as the same kind of
+/// heading as the Machines section below it.
+class PhoneSearchFolderHeader extends StatelessWidget {
+ const PhoneSearchFolderHeader({super.key, required this.group});
+
+ final PhoneSearchGroup group;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final faint = TextStyle(color: AppPalette.textFaint, fontSize: 12);
+ return Padding(
+ padding: const EdgeInsets.fromLTRB(10, 14, 10, 4),
+ child: Row(
+ children: [
+ Icon(LucideIcons.folder300, size: 14, color: AppPalette.textFaint),
+ const SizedBox(width: 6),
+ Flexible(
+ child: Text.rich(
+ TextSpan(
+ children: [
+ TextSpan(
+ text: group.folder.isEmpty ? 'No folder' : group.folder,
+ style: TextStyle(
+ color: AppPalette.textSecondary,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ // The machine ellipses off first: it is the longest part and
+ // the one that is the same for most people's every group.
+ TextSpan(text: ' · ${group.machineName}'),
+ ],
+ ),
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: faint,
+ ),
+ ),
+ const SizedBox(width: 7),
+ Text(
+ '${group.rows.length}',
+ style: faint.copyWith(fontFeatures: AppFont.tabularFigures),
+ ),
+ ],
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/phone_search_groups.dart b/mobile/lib/phone/phone_search_groups.dart
new file mode 100644
index 000000000..3e42c77e2
Binary files /dev/null and b/mobile/lib/phone/phone_search_groups.dart differ
diff --git a/mobile/lib/phone/phone_search_index.dart b/mobile/lib/phone/phone_search_index.dart
index 74fbb79f5..0edfbbf24 100644
--- a/mobile/lib/phone/phone_search_index.dart
+++ b/mobile/lib/phone/phone_search_index.dart
@@ -17,9 +17,9 @@ enum PhoneSearchKind { agent, machine }
/// runs on. This is the flattening that lets one query reach both, built the way
/// [AgentEntry] flattens machine-keyed state for the Agents tab.
///
-/// [fields] is what the query is matched against, title first. The order is the
-/// ranking: a hit on the name outranks a hit on the machine under it, the same
-/// rule the desktop's `swarmFieldMatchScore` applies with its `title` flag.
+/// [fields] is what the query is matched against, title fields first. The order
+/// is the ranking: a hit on the name outranks a hit on the machine under it, the
+/// same rule the desktop's `swarmFieldMatchScore` applies with its `title` flag.
class PhoneSearchResult {
const PhoneSearchResult({
required this.kind,
@@ -29,6 +29,7 @@ class PhoneSearchResult {
required this.fields,
required this.summary,
required this.machineId,
+ this.titleFields = 1,
this.entry,
this.machine,
});
@@ -51,6 +52,11 @@ class PhoneSearchResult {
/// the text it is emphasising.
final List<String> fields;
+ /// How many of [fields], from the front, rank as a name rather than as
+ /// metadata: two for an agent that has a title, which is how people describe
+ /// it, and is ranked that way on the desktop too (its `titleFields`).
+ final int titleFields;
+
final PhoneSummary summary;
/// The machine this row belongs to, for either kind. An agent needs it to
@@ -64,7 +70,8 @@ class PhoneSearchResult {
final MachineState? machine;
}
-/// Everything one query can reach, unfiltered, in the order the two tabs draw.
+/// Everything one query can reach, unfiltered: agents most recent first (see
+/// [recentAgents]), then machines in the order their tab draws them.
///
/// 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
@@ -75,45 +82,8 @@ class PhoneSearchResult {
/// The asymmetry is deliberate and is the same one the tabs already make.
List<PhoneSearchResult> phoneSearchIndex(AppNotifier notifier) {
final results = <PhoneSearchResult>[];
- for (final entry in visibleAgents(agentIndex(notifier))) {
- final agent = entry.agent;
- final engine = agent.engineDisplayName ?? agent.engine ?? '';
- final folder = entry.project?.folder ?? '';
- results.add(
- PhoneSearchResult(
- kind: PhoneSearchKind.agent,
- id: 'agent:${entry.machineId}:${agent.id}',
- title: agent.name,
- // The tabs' rows carry the folder too ([AgentContextLine]); a result row
- // has one line for all of it, so the three land in the same order on it,
- // and the machine — the longest and the least distinguishing — ellipses
- // off the end first.
- subtitle: [
- if (engine.isNotEmpty) engine,
- if (folder.isNotEmpty) folder,
- entry.machineName,
- ].join(' · '),
- fields: [
- agent.name.toLowerCase(),
- entry.machineName.toLowerCase(),
- engine.toLowerCase(),
- // The raw engine id as well as its display name: somebody types
- // "codex", and the display name may well be "Codex CLI".
- (agent.engine ?? '').toLowerCase(),
- folder.toLowerCase(),
- // The project's own name and its branch are not drawn on a result row,
- // but they are how people describe the agent they are hunting for, so
- // both stay searchable. [SearchResultText] checks that a matched field
- // is present in the text it is about to emphasise, so matching here
- // never bolds something unrelated.
- (entry.project?.name ?? '').toLowerCase(),
- (entry.project?.branchLabel ?? '').toLowerCase(),
- ].where((field) => field.isNotEmpty).toList(),
- summary: entry.summary,
- machineId: entry.machineId,
- entry: entry,
- ),
- );
+ for (final entry in recentAgents(agentIndex(notifier))) {
+ results.add(_agentResult(entry));
}
for (final machine in visibleMachines(notifier)) {
final summary = phoneMachineSummary(machine);
@@ -136,6 +106,51 @@ List<PhoneSearchResult> phoneSearchIndex(AppNotifier notifier) {
return results;
}
+PhoneSearchResult _agentResult(AgentEntry entry) {
+ final agent = entry.agent;
+ final engine = agent.engineDisplayName ?? agent.engine ?? '';
+ final title = agent.title ?? '';
+ final branch = entry.project?.branchLabel ?? '';
+ return PhoneSearchResult(
+ kind: PhoneSearchKind.agent,
+ id: 'agent:${entry.machineId}:${agent.id}',
+ title: agent.name,
+ // What tells `work · 3188` from `work · 48e9`: the work itself, then its
+ // branch. The folder and the machine are said once, by the group header
+ // over the row, rather than repeated down every line of it; the engine is
+ // the mark's to show and is only spelled out when nothing else is known.
+ subtitle: [
+ title,
+ branch,
+ ].where((part) => part.isNotEmpty).join(' · ').ifEmpty(engine),
+ fields: [
+ agent.name.toLowerCase(),
+ title.toLowerCase(),
+ entry.machineName.toLowerCase(),
+ engine.toLowerCase(),
+ // The raw engine id as well as its display name: somebody types "codex",
+ // and the display name may well be "Codex CLI".
+ (agent.engine ?? '').toLowerCase(),
+ (entry.project?.folder ?? '').toLowerCase(),
+ // The project's own name is not drawn on a result row, but it is how
+ // people describe the agent they are hunting for, so it stays searchable.
+ // [SearchResultText] checks that a matched field is present in the text
+ // it is about to emphasise, so matching here never bolds something
+ // unrelated.
+ (entry.project?.name ?? '').toLowerCase(),
+ branch.toLowerCase(),
+ ].where((field) => field.isNotEmpty).toList(),
+ titleFields: title.isEmpty ? 1 : 2,
+ summary: entry.summary,
+ machineId: entry.machineId,
+ entry: entry,
+ );
+}
+
+extension on String {
+ String ifEmpty(String fallback) => isEmpty ? fallback : this;
+}
+
/// The query, split into the words that each have to match something.
///
/// Every word must hit — possibly a DIFFERENT field each — so "review mac" finds
@@ -169,11 +184,43 @@ int? phoneFieldMatchScore(String field, String term, {required bool title}) {
: 128 + spread);
}
+/// The field [term] reaches best on [row] — its score and its index in
+/// [PhoneSearchResult.fields] — or null when it reaches none.
+///
+/// Shared by the ranking and by the emphasis, so the field a row is ranked on is
+/// the field that is bolded.
+///
+/// Bounded: a pathologically long field is skipped rather than scanned, so one
+/// agent named with a pasted log cannot make a keystroke cost more than a frame.
+({int score, int index})? phoneBestFieldMatch(
+ PhoneSearchResult row,
+ String term,
+) {
+ ({int score, int index})? best;
+ for (final (index, field) in row.fields.indexed) {
+ if (field.length > 4096) continue;
+ final score = phoneFieldMatchScore(
+ field,
+ term,
+ title: index < row.titleFields,
+ );
+ if (score != null && (best == null || score < best.score)) {
+ best = (score: score, index: index);
+ }
+ // Every field past the title fields is metadata, whose best possible score
+ // is 64. An exact, prefix or substring title match already beats that, so
+ // once the title fields are behind us there is nothing left to find.
+ if (best != null && index >= row.titleFields - 1 && best.score <= 64) {
+ break;
+ }
+ }
+ return best;
+}
+
/// The rows [query] reaches, best first.
///
-/// An empty query keeps index order untouched — the two tabs already sort
-/// themselves by what needs attention, and re-sorting a list nobody has filtered
-/// would only move rows out from under a finger.
+/// An empty query keeps index order untouched: [phoneSearchIndex] already put
+/// the agents in the order worth offering before a word is typed.
///
/// ⚠️ 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],
@@ -190,24 +237,15 @@ List<PhoneSearchResult> rankPhoneSearch(
final ranked = <({PhoneSearchResult row, int score, int index})>[];
for (final (index, row) in all.indexed) {
- // An exact hit on the name wins outright, ahead of every scored row. Typing
- // a name in full is the least ambiguous thing somebody can do.
- if (row.fields.first == needle) {
+ // An exact hit on the name — or the title — wins outright, ahead of every
+ // scored row. Typing one in full is the least ambiguous thing somebody can do.
+ if (row.fields.take(row.titleFields).contains(needle)) {
ranked.add((row: row, score: -1, index: index));
continue;
}
var total = 0;
for (final term in terms) {
- int? best;
- for (final (fieldIndex, field) in row.fields.indexed) {
- final score = phoneFieldMatchScore(field, term, title: fieldIndex == 0);
- if (score == null) continue;
- if (best == null || score < best) best = score;
- // Every field after the first is metadata, whose best possible score is
- // 64. An exact, prefix or substring title match already beats that, so
- // there is nothing left to find.
- if (best <= 64) break;
- }
+ final best = phoneBestFieldMatch(row, term);
// One word matching nothing drops the row: the words narrow, they do not
// accumulate. Without this, "review mac" would return everything either
// word touches.
@@ -215,7 +253,7 @@ List<PhoneSearchResult> rankPhoneSearch(
total = -1;
break;
}
- total += best;
+ total += best.score;
}
if (total >= 0) ranked.add((row: row, score: total, index: index));
}
diff --git a/mobile/lib/phone/phone_search_page.dart b/mobile/lib/phone/phone_search_page.dart
index 022f2b3c5..35226772e 100644
--- a/mobile/lib/phone/phone_search_page.dart
+++ b/mobile/lib/phone/phone_search_page.dart
@@ -6,15 +6,16 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';
import 'package:harness_mobile/shared/theme/app_theme.dart';
import 'package:harness_mobile/shared/widgets/empty_state.dart';
import 'package:harness_mobile/state/app_state.dart';
-import 'package:harness_mobile/widgets/engine_identity.dart';
import 'link_page.dart';
import 'phone_navigation.dart';
+import 'phone_search_field.dart';
+import 'phone_search_folder_header.dart';
+import 'phone_search_groups.dart';
import 'phone_search_index.dart';
+import 'phone_search_row.dart';
import 'phone_sheet.dart';
import 'phone_status.dart';
-import 'search_result_text.dart';
-import 'status_pill.dart';
import 'unlink_machine.dart';
/// One query over everything the account can reach — agents and machines
@@ -76,7 +77,7 @@ class _PhoneSearchPageState extends State<PhoneSearchPage> {
bottom: false,
child: Column(
children: [
- _SearchField(
+ PhoneSearchField(
controller: _controller,
focus: _focus,
onChanged: (value) => setState(() => _query = value),
@@ -87,7 +88,7 @@ class _PhoneSearchPageState extends State<PhoneSearchPage> {
// screen — the caret stays where the next query will go.
_focus.requestFocus();
},
- onCancel: () => Navigator.of(context).maybePop(),
+ onBack: () => Navigator.of(context).maybePop(),
),
Expanded(
child: _Results(
@@ -106,169 +107,6 @@ class _PhoneSearchPageState extends State<PhoneSearchPage> {
);
}
-/// The field, and the way out beside it.
-///
-/// Drawn here rather than through [PhoneHeader]: this page has no title. The
-/// field IS the header, because nothing else on the screen is worth the 32pt
-/// line a large title would take from the results.
-class _SearchField extends StatelessWidget {
- const _SearchField({
- required this.controller,
- required this.focus,
- required this.onChanged,
- required this.onClear,
- required this.onCancel,
- });
-
- final TextEditingController controller;
- final FocusNode focus;
- final ValueChanged<String> onChanged;
- final VoidCallback onClear;
- final VoidCallback onCancel;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return Padding(
- padding: const EdgeInsets.fromLTRB(16, 10, 8, 10),
- child: Row(
- children: [
- Expanded(
- // The rim lives on the BOX, never on the TextField inside it — see
- // the decoration below for why the field draws no border of its own.
- // Listening to the node here is what lets the box carry the focus
- // state instead.
- child: ListenableBuilder(
- listenable: focus,
- builder: (context, child) => AnimatedContainer(
- duration: AppMotion.hover,
- curve: AppMotion.curve,
- height: 44,
- padding: const EdgeInsets.symmetric(horizontal: 13),
- decoration: BoxDecoration(
- color: AppGlass.rowFill,
- borderRadius: BorderRadius.circular(AppCard.radius),
- // Focus is said once, by the rim of the box the field fills.
- // The accent is the same one the caret already uses, so the
- // two read as one state rather than as two decorations.
- border: Border.all(
- color: focus.hasFocus
- ? AppPalette.accentOnSurface
- : AppGlass.hair,
- ),
- ),
- child: child,
- ),
- child: Row(
- children: [
- Icon(
- LucideIcons.search300,
- size: 18,
- color: AppPalette.textFaint,
- ),
- const SizedBox(width: 9),
- Expanded(
- child: TextField(
- controller: controller,
- focusNode: focus,
- autofocus: true,
- onChanged: onChanged,
- // The list is already filtered by the time a key is
- // released; there is nothing left for the return key to
- // submit, so it stays a plain "done" that drops the
- // keyboard and leaves the results up.
- textInputAction: TextInputAction.search,
- onSubmitted: (_) => focus.unfocus(),
- autocorrect: false,
- enableSuggestions: false,
- // Agent names are ids as often as sentences —
- // `Dijkstra-visualization.html` — and a capital forced
- // onto the first letter of one is a wrong query.
- textCapitalization: TextCapitalization.none,
- // With the decoration's padding zeroed below, the field
- // is exactly one line tall inside a 44pt box; this is
- // what centres that line on the glyph beside it instead
- // of letting it sit on the box's top edge.
- textAlignVertical: TextAlignVertical.center,
- style: TextStyle(
- color: AppPalette.textPrimary,
- fontSize: 16,
- ),
- cursorColor: AppPalette.accentOnSurface,
- decoration: InputDecoration(
- isDense: true,
- // ⚠️ **Every** border state, not just `border`.
- //
- // `border` alone is the wrong half of the fix: it is
- // the fallback, and the app's `inputDecorationTheme`
- // fills the named states in — `focusedBorder` is a
- // 1.5px accent outline at [AppControl.radius] (8).
- // This box is [AppCard.radius] (12), so focusing drew
- // a second, tighter blue rectangle INSIDE the rim —
- // the reported bug. Naming each state is what keeps
- // the theme from reaching past `border`.
- border: InputBorder.none,
- enabledBorder: InputBorder.none,
- focusedBorder: InputBorder.none,
- errorBorder: InputBorder.none,
- focusedErrorBorder: InputBorder.none,
- disabledBorder: InputBorder.none,
- // The theme also fills these, and both would draw on
- // top of the box: a `surfaceContainerHighest` fill over
- // the rim's own, and Material's phone-sized padding
- // over the 44pt height set above.
- filled: false,
- contentPadding: EdgeInsets.zero,
- constraints: const BoxConstraints(),
- hintText: 'Search agents and machines',
- hintStyle: TextStyle(
- color: AppPalette.textFaint,
- fontSize: 16,
- ),
- ),
- ),
- ),
- // Only once there is something to clear: a button that does
- // nothing on an empty field is a button people learn to skip.
- ValueListenableBuilder(
- valueListenable: controller,
- builder: (context, value, _) => value.text.isEmpty
- ? const SizedBox(width: 4)
- : GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTap: onClear,
- child: Padding(
- // Padding, not size: the glyph stays small while
- // the target reaches a thumb.
- padding: const EdgeInsets.only(left: 8),
- child: Icon(
- LucideIcons.circleX300,
- size: 18,
- color: AppPalette.textFaint,
- ),
- ),
- ),
- ),
- ],
- ),
- ),
- ),
- TextButton(
- onPressed: onCancel,
- style: TextButton.styleFrom(
- foregroundColor: AppPalette.accentOnSurface,
- padding: const EdgeInsets.symmetric(horizontal: 10),
- minimumSize: const Size(44, 44),
- tapTargetSize: MaterialTapTargetSize.shrinkWrap,
- ),
- child: const Text('Cancel', style: TextStyle(fontSize: 15)),
- ),
- ],
- ),
- );
- }
-}
-
class _Results extends StatelessWidget {
const _Results({
required this.notifier,
@@ -301,8 +139,10 @@ class _Results extends StatelessWidget {
);
}
- final agents = phoneSearchOfKind(rows, PhoneSearchKind.agent);
+ final groups = phoneSearchGroups(rows);
+ final agents = phoneSearchGroupedRows(groups);
final machines = phoneSearchOfKind(rows, PhoneSearchKind.machine);
+ final now = DateTime.now();
return ListView(
// The keyboard is up and the finger is already on the glass; dragging the
// list is how somebody reaches a result without putting it away first.
@@ -314,24 +154,26 @@ class _Results extends StatelessWidget {
MediaQuery.paddingOf(context).bottom + 16,
),
children: [
- // Grouped by kind rather than interleaved by score. The two kinds open
- // different things, and a machine row appearing between two agents is
- // read as another agent until the icon is noticed.
- if (agents.isNotEmpty) ...[
- _GroupLabel('Agents', count: agents.length),
- for (final row in agents)
- _ResultRow(
+ // Agents under their folders, machines in a section of their own. The
+ // two kinds open different things, and a machine row appearing between
+ // two agents is read as another agent until the icon is noticed.
+ for (final group in groups) ...[
+ PhoneSearchFolderHeader(group: group),
+ for (final row in group.rows)
+ PhoneSearchRow(
row: row,
terms: terms,
- onTap: () => _openAgent(context, row),
+ now: now,
+ onTap: () => _openAgent(context, agents, row),
),
],
if (machines.isNotEmpty) ...[
_GroupLabel('Machines', count: machines.length),
for (final row in machines)
- _ResultRow(
+ PhoneSearchRow(
row: row,
terms: terms,
+ now: now,
onTap: () => _openMachine(context, row),
),
],
@@ -345,7 +187,15 @@ class _Results extends StatelessWidget {
/// walks exactly what the query returned, which is the list the person was
/// looking at when they tapped. Handing it the unfiltered index instead would
/// swipe into agents the query had just excluded.
- void _openAgent(BuildContext context, PhoneSearchResult row) {
+ ///
+ /// ⚠️ [agents] is the GROUPED order, the one drawn — not the ranked [rows].
+ /// Grouping pulls a folder's rows together, so the ranked list can hold a
+ /// different agent at any given index than the screen does.
+ void _openAgent(
+ BuildContext context,
+ List<PhoneSearchResult> agents,
+ PhoneSearchResult row,
+ ) {
final entry = row.entry;
if (entry == null || !entry.agent.terminalAvailable) return;
// ⚠️ Built from [phoneSearchAgentEntries] rather than by unwrapping each
@@ -353,7 +203,7 @@ class _Results extends StatelessWidget {
// an agent row ever arrived without its entry, and the pager walks it by
// index — a shorter list than the one on screen sends a swipe to the wrong
// agent, with nothing on screen to explain why.
- openAgentPager(context, notifier, phoneSearchAgentEntries(rows), entry);
+ openAgentPager(context, notifier, phoneSearchAgentEntries(agents), entry);
}
/// A machine that wants its password opens the form for it. One that is
@@ -446,238 +296,3 @@ class _GroupLabel extends StatelessWidget {
);
}
}
-
-/// One result: the mark, the two lines, and what a tap will do.
-///
-/// Shorter than the tabs' 70pt [PhoneCard] and without its fill. A result list
-/// is read top to bottom against a query and abandoned the moment the right row
-/// is seen, so it is built for scanning: more rows in a thumb's reach, and the
-/// emphasis carried by the bolded match rather than by a card edge.
-class _ResultRow extends StatefulWidget {
- const _ResultRow({
- required this.row,
- required this.terms,
- required this.onTap,
- });
-
- final PhoneSearchResult row;
- final List<String> terms;
- final VoidCallback onTap;
-
- @override
- State<_ResultRow> createState() => _ResultRowState();
-}
-
-class _ResultRowState extends State<_ResultRow> {
- bool _pressed = false;
-
- /// An agent whose terminal has gone cannot be opened, the same rule
- /// [AgentRow] applies. A machine opens unless it is offline — a locked one
- /// opens on its password form, which is the thing to do about it, but a
- /// switched-off one has nothing to take a password.
- bool get _openable => switch (widget.row.kind) {
- PhoneSearchKind.agent => widget.row.entry?.agent.terminalAvailable ?? false,
- PhoneSearchKind.machine =>
- widget.row.machine == null ||
- phoneMachineStatusOf(widget.row.machine!) !=
- PhoneMachineStatus.offline,
- };
-
- void _press(bool pressed) {
- if (!_openable || _pressed == pressed) return;
- setState(() => _pressed = pressed);
- }
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final row = widget.row;
- final matches = phoneResultMatches(row, widget.terms);
- final waiting = row.entry?.isWaiting ?? false;
- return GestureDetector(
- behavior: HitTestBehavior.opaque,
- onTapDown: (_) => _press(true),
- onTapUp: (_) => _press(false),
- onTapCancel: () => _press(false),
- onTap: _openable
- ? () {
- // The keyboard goes away with the screen, not a frame after it —
- // dismissing it first keeps the push from animating over a
- // collapsing inset.
- FocusManager.instance.primaryFocus?.unfocus();
- widget.onTap();
- }
- : null,
- child: AnimatedContainer(
- duration: AppMotion.press,
- curve: AppMotion.curve,
- height: 58,
- padding: const EdgeInsets.symmetric(horizontal: 10),
- decoration: BoxDecoration(
- // No resting fill. The tabs' cards earn one because they are the
- // screen's content; a result row is a line of an answer, and forty of
- // them each in their own box is a wall rather than a list.
- color: _pressed ? AppGlass.rowFill : Colors.transparent,
- borderRadius: BorderRadius.circular(AppCard.radius),
- ),
- child: Opacity(
- opacity: _openable ? 1 : 0.55,
- child: Row(
- children: [
- _Mark(row: row, waiting: waiting),
- const SizedBox(width: 12),
- Expanded(
- child: Column(
- mainAxisAlignment: MainAxisAlignment.center,
- crossAxisAlignment: CrossAxisAlignment.start,
- children: [
- SearchResultText(
- row.title,
- matches: matches,
- style: TextStyle(
- color: AppPalette.textPrimary,
- fontSize: 15.5,
- fontWeight: FontWeight.w600,
- ),
- ),
- const SizedBox(height: 3),
- SearchResultText(
- row.subtitle,
- matches: matches,
- style: TextStyle(
- // The subtitle already carries the status in words, and
- // a coloured status pill on every row of a result list
- // turns the colour into wallpaper. The tone is spent on
- // the mark instead, where one row at a time wears it.
- color: AppPalette.textFaint,
- fontSize: 12.5,
- ),
- ),
- ],
- ),
- ),
- // Carries its own leading gap, so an agent row that prints
- // nothing here leaves no gutter behind either.
- _Action(row: row, openable: _openable),
- ],
- ),
- ),
- ),
- );
- }
-}
-
-/// The square mark at the head of a result: an agent's engine, a machine's
-/// screen. Smaller than the tabs' 44pt [PhoneCardGlyph], to match the shorter
-/// row.
-class _Mark extends StatelessWidget {
- const _Mark({required this.row, required this.waiting});
-
- final PhoneSearchResult row;
- final bool waiting;
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- return Container(
- width: 36,
- height: 36,
- decoration: BoxDecoration(
- color: AppSurface.recess,
- borderRadius: BorderRadius.circular(10),
- // The same attention rim the Agents tab puts on a waiting row, so an
- // agent that has stopped to ask something is findable here too.
- border: waiting
- ? Border.all(color: AppPalette.warn.withValues(alpha: 0.42))
- : null,
- ),
- child: Center(
- child: switch (row.kind) {
- PhoneSearchKind.agent => EngineMark(
- engine: row.entry?.agent.engine,
- displayName: row.entry?.agent.engineDisplayName,
- size: 18,
- ),
- PhoneSearchKind.machine => Icon(
- LucideIcons.laptopMinimal300,
- size: 18,
- color: phoneToneColor(row.summary.tone),
- ),
- },
- ),
- );
- }
-}
-
-/// What a tap will do, said in a word.
-///
-/// The desktop's picker labels its rows the same way, and on a list mixing two
-/// kinds the label is what separates "this asks you for a password" from "this
-/// just shows you the machine" before anything is tapped.
-///
-/// ⚠️ Agent rows no longer draw one. Their label only ever said "Open", which is
-/// what tapping any row does — a boxed word repeating that down the whole
-/// Agents section read as a button beside each line rather than a description
-/// of it, and it is the whole row that takes the tap. Machines keep theirs
-/// because theirs distinguishes: Unlock and View are two different destinations.
-///
-/// The exception is an agent whose terminal has gone. Dimming alone leaves the
-/// person tapping a row that cannot answer and reading nothing about why, so
-/// that one keeps its words.
-class _Action extends StatelessWidget {
- const _Action({required this.row, required this.openable});
-
- final PhoneSearchResult row;
- final bool openable;
-
- /// Null where the row says nothing — an agent that opens, which is every
- /// agent row bar the ones with no terminal left.
- ///
- /// A machine always says something, and an offline one says so rather than
- /// "No terminal": it is dimmed for a different reason, and the word is the
- /// only place that reason is given.
- String? get _label {
- final machine = row.machine;
- return switch (row.kind) {
- PhoneSearchKind.agent => openable ? null : 'No terminal',
- PhoneSearchKind.machine => switch (machine == null
- ? null
- : phoneMachineStatusOf(machine)) {
- PhoneMachineStatus.offline => 'Offline',
- PhoneMachineStatus.needsPassword => 'Unlock',
- // Its state, not a verb: the tap brings a sheet of actions, and "View" promised a screen
- // that is no longer there.
- _ => 'Connected',
- },
- };
- }
-
- @override
- Widget build(BuildContext context) {
- AppTheme.watch(context);
- final label = _label;
- // ⚠️ The gutter belongs to the label, not to the row. A bare
- // [SizedBox.shrink] beside a gap the caller kept would leave an 8px column
- // down the right of every agent row, holding space for a word that is no
- // longer printed.
- if (label == null) return const SizedBox.shrink();
- return Padding(
- padding: const EdgeInsets.only(left: 8),
- child: Container(
- padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),
- decoration: BoxDecoration(
- borderRadius: BorderRadius.circular(6),
- border: Border.all(color: AppGlass.hair),
- ),
- child: Text(
- label,
- style: TextStyle(
- color: AppPalette.textFaint,
- fontSize: 11,
- fontWeight: FontWeight.w600,
- ),
- ),
- ),
- );
- }
-}
diff --git a/mobile/lib/phone/phone_search_row.dart b/mobile/lib/phone/phone_search_row.dart
new file mode 100644
index 000000000..a3b207dbd
--- /dev/null
+++ b/mobile/lib/phone/phone_search_row.dart
@@ -0,0 +1,271 @@
+import 'package:flutter/material.dart';
+import 'package:lucide_icons_flutter/lucide_icons.dart';
+
+import 'package:harness_mobile/shared/theme/app_theme.dart';
+import 'package:harness_mobile/widgets/engine_identity.dart';
+
+import 'compact_age.dart';
+import 'phone_search_index.dart';
+import 'phone_status.dart';
+import 'search_result_text.dart';
+import 'status_pill.dart';
+
+/// One result: the mark, the two lines, and what is worth knowing before a tap.
+///
+/// Shorter than the tabs' 70pt [PhoneCard] and without its fill. A result list
+/// is read top to bottom against a query and abandoned the moment the right row
+/// is seen, so it is built for scanning: more rows in a thumb's reach, and the
+/// emphasis carried by the bolded match rather than by a card edge.
+class PhoneSearchRow extends StatefulWidget {
+ const PhoneSearchRow({
+ super.key,
+ required this.row,
+ required this.terms,
+ required this.now,
+ required this.onTap,
+ });
+
+ final PhoneSearchResult row;
+ final List<String> terms;
+
+ /// One clock for the whole list, so two rows built a frame apart cannot
+ /// disagree about what "4m" means.
+ final DateTime now;
+ final VoidCallback onTap;
+
+ @override
+ State<PhoneSearchRow> createState() => _PhoneSearchRowState();
+}
+
+class _PhoneSearchRowState extends State<PhoneSearchRow> {
+ bool _pressed = false;
+
+ /// An agent whose terminal has gone cannot be opened, the same rule
+ /// [AgentRow] applies. A machine opens unless it is offline — a locked one
+ /// opens on its password form, which is the thing to do about it, but a
+ /// switched-off one has nothing to take a password.
+ bool get _openable => switch (widget.row.kind) {
+ PhoneSearchKind.agent => widget.row.entry?.agent.terminalAvailable ?? false,
+ PhoneSearchKind.machine =>
+ widget.row.machine == null ||
+ phoneMachineStatusOf(widget.row.machine!) !=
+ PhoneMachineStatus.offline,
+ };
+
+ void _press(bool pressed) {
+ if (!_openable || _pressed == pressed) return;
+ setState(() => _pressed = pressed);
+ }
+
+ void _open() {
+ // The keyboard goes away with the screen, not a frame after it — dismissing
+ // it first keeps the push from animating over a collapsing inset.
+ FocusManager.instance.primaryFocus?.unfocus();
+ widget.onTap();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final row = widget.row;
+ final matches = phoneResultMatches(row, widget.terms);
+ return GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTapDown: (_) => _press(true),
+ onTapUp: (_) => _press(false),
+ onTapCancel: () => _press(false),
+ onTap: _openable ? _open : null,
+ child: AnimatedContainer(
+ duration: AppMotion.press,
+ curve: AppMotion.curve,
+ height: 58,
+ padding: const EdgeInsets.symmetric(horizontal: 10),
+ decoration: BoxDecoration(
+ // No resting fill. The tabs' cards earn one because they are the
+ // screen's content; a result row is a line of an answer, and forty of
+ // them each in their own box is a wall rather than a list.
+ color: _pressed ? AppGlass.rowFill : Colors.transparent,
+ borderRadius: BorderRadius.circular(AppCard.radius),
+ ),
+ child: Opacity(
+ opacity: _openable ? 1 : 0.55,
+ child: Row(
+ children: [
+ _Mark(row: row),
+ const SizedBox(width: 12),
+ Expanded(
+ child: Column(
+ mainAxisAlignment: MainAxisAlignment.center,
+ crossAxisAlignment: CrossAxisAlignment.start,
+ children: [
+ SearchResultText(
+ row.title,
+ matches: matches,
+ style: TextStyle(
+ color: AppPalette.textPrimary,
+ fontSize: 15.5,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ const SizedBox(height: 3),
+ SearchResultText(
+ row.subtitle,
+ matches: matches,
+ style: TextStyle(
+ color: AppPalette.textFaint,
+ fontSize: 12.5,
+ ),
+ ),
+ ],
+ ),
+ ),
+ _Trailing(row: row, openable: _openable, now: widget.now),
+ ],
+ ),
+ ),
+ ),
+ );
+ }
+}
+
+/// The square mark at the head of a result: an agent's engine, a machine's
+/// screen. Smaller than the tabs' 44pt [PhoneCardGlyph], to match the shorter
+/// row.
+class _Mark extends StatelessWidget {
+ const _Mark({required this.row});
+
+ final PhoneSearchResult row;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Container(
+ width: 36,
+ height: 36,
+ decoration: BoxDecoration(
+ color: AppSurface.recess,
+ borderRadius: BorderRadius.circular(10),
+ // The same attention rim the Agents tab puts on a waiting row, so an
+ // agent that has stopped to ask something is findable here too.
+ border: row.entry?.isWaiting ?? false
+ ? Border.all(color: AppPalette.warn.withValues(alpha: 0.42))
+ : null,
+ ),
+ child: Center(
+ child: switch (row.kind) {
+ PhoneSearchKind.agent => EngineMark(
+ engine: row.entry?.agent.engine,
+ displayName: row.entry?.agent.engineDisplayName,
+ size: 18,
+ ),
+ PhoneSearchKind.machine => Icon(
+ LucideIcons.laptopMinimal300,
+ size: 18,
+ color: phoneToneColor(row.summary.tone),
+ ),
+ },
+ ),
+ );
+ }
+}
+
+/// The row's trailing edge: why it cannot be opened, or else how fresh it is.
+///
+/// An agent that opens says when its conversation last moved — `4m` — or that
+/// it is `working` right now, which is what explains a row sorted above a
+/// fresher one. Unboxed and faint: it is read after the name, never instead.
+///
+/// A boxed word is kept for what a tap would NOT make obvious: a machine's
+/// Unlock or Offline, and an agent whose terminal has gone. Dimming alone leaves
+/// the person tapping a row that cannot answer and reading nothing about why.
+class _Trailing extends StatelessWidget {
+ const _Trailing({
+ required this.row,
+ required this.openable,
+ required this.now,
+ });
+
+ final PhoneSearchResult row;
+ final bool openable;
+ final DateTime now;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final badge = _badge;
+ if (badge != null) return _Badge(badge);
+ final entry = row.entry;
+ if (entry == null) return const SizedBox.shrink();
+ if (entry.isWorking) {
+ return _Recency('working', color: phoneToneColor(PhoneTone.busy));
+ }
+ final at = entry.agent.updatedAt;
+ if (at == null) return const SizedBox.shrink();
+ return _Recency(compactAge(at, now), color: AppPalette.textFaint);
+ }
+
+ String? get _badge {
+ final machine = row.machine;
+ return switch (row.kind) {
+ PhoneSearchKind.agent => openable ? null : 'No terminal',
+ PhoneSearchKind.machine => switch (machine == null
+ ? null
+ : phoneMachineStatusOf(machine)) {
+ PhoneMachineStatus.offline => 'Offline',
+ PhoneMachineStatus.needsPassword => 'Unlock',
+ // Its state, not a verb: the tap brings a sheet of actions, and "View"
+ // promised a screen that is no longer there.
+ _ => 'Connected',
+ },
+ };
+ }
+}
+
+class _Recency extends StatelessWidget {
+ const _Recency(this.text, {required this.color});
+
+ final String text;
+ final Color color;
+
+ @override
+ Widget build(BuildContext context) => Padding(
+ padding: const EdgeInsets.only(left: 8),
+ child: Text(
+ text,
+ style: TextStyle(
+ color: color,
+ fontSize: 12,
+ fontFeatures: AppFont.tabularFigures,
+ ),
+ ),
+ );
+}
+
+class _Badge extends StatelessWidget {
+ const _Badge(this.label);
+
+ final String label;
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ return Padding(
+ padding: const EdgeInsets.only(left: 8),
+ child: Container(
+ padding: const EdgeInsets.symmetric(horizontal: 7, vertical: 3),
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(6),
+ border: Border.all(color: AppGlass.hair),
+ ),
+ child: Text(
+ label,
+ style: TextStyle(
+ color: AppPalette.textFaint,
+ fontSize: 11,
+ fontWeight: FontWeight.w600,
+ ),
+ ),
+ ),
+ );
+ }
+}
diff --git a/mobile/lib/phone/search_result_text.dart b/mobile/lib/phone/search_result_text.dart
index 5cfdbce0f..8d4645eb6 100644
--- a/mobile/lib/phone/search_result_text.dart
+++ b/mobile/lib/phone/search_result_text.dart
@@ -1,6 +1,7 @@
import 'package:flutter/widgets.dart';
import 'package:harness_mobile/core/fuzzy_match.dart';
+
import 'phone_search_index.dart';
/// Which field earned each query term its score, and whether that field is the
@@ -21,24 +22,13 @@ List<PhoneFieldMatch> phoneResultMatches(
// work than drawing the whole list.
for (final term in terms.take(12).toSet()) {
if (term.length > 128) continue;
- int? best;
- var fieldIndex = -1;
- for (final (index, field) in row.fields.indexed) {
- if (field.length > 4096) continue;
- final score = phoneFieldMatchScore(field, term, title: index == 0);
- if (score != null && (best == null || score < best)) {
- best = score;
- fieldIndex = index;
- }
- if (best != null && best <= 64) break;
- }
- if (fieldIndex >= 0) {
- matches.add((
- field: row.fields[fieldIndex],
- term: term,
- title: fieldIndex == 0,
- ));
- }
+ final best = phoneBestFieldMatch(row, term);
+ if (best == null) continue;
+ matches.add((
+ field: row.fields[best.index],
+ term: term,
+ title: best.index < row.titleFields,
+ ));
}
return matches;
}
diff --git a/mobile/test/phone_search_test.dart b/mobile/test/phone_search_test.dart
new file mode 100644
index 000000000..85faf87ef
--- /dev/null
+++ b/mobile/test/phone_search_test.dart
@@ -0,0 +1,231 @@
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/auth/auth_session.dart';
+import 'package:harness_mobile/core/config.dart';
+import 'package:harness_mobile/core/models.dart';
+import 'package:harness_mobile/phone/agent_index.dart';
+import 'package:harness_mobile/phone/compact_age.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_page.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/state/pending_question.dart';
+
+final _now = DateTime.now();
+
+Agent _agent(
+ String id, {
+ String? title,
+ String cwd = '/srv/work',
+ int? minutesAgo,
+ bool terminal = true,
+}) => Agent(
+ id: id,
+ name: 'work · $id',
+ title: title,
+ engine: 'codex',
+ project: AgentProject(name: 'work', cwd: cwd),
+ updatedAt: minutesAgo == null
+ ? null
+ : _now.subtract(Duration(minutes: minutesAgo)),
+ terminalAvailable: terminal,
+);
+
+MachineState _machine(String id, List<Agent> agents) =>
+ MachineState(
+ Machine(machineId: id, authMode: MachineAuthMode.remote, name: id),
+ )
+ ..nodeOnline = true
+ ..connectionStatus = ConnectionStatus.connected
+ ..agentLoadStatus = AgentLoadStatus.loaded
+ ..agents = agents;
+
+void _markWaiting(MachineState machine, String agentId) =>
+ machine.blockedAgents[agentId] = PendingQuestion(
+ machineId: machine.machine.machineId,
+ agentId: agentId,
+ requestId: 'r',
+ answerKey: 'q',
+ prompt: 'q',
+ options: const ['yes'],
+ multi: false,
+ since: _now,
+ );
+
+AppNotifier _app(List<MachineState> machines) {
+ final app = AppNotifier(
+ config: AppConfig.dev,
+ authSession: AuthSession(),
+ configStore: null,
+ );
+ app.machines = [for (final state in machines) state.machine];
+ for (final state in machines) {
+ app.machineStates[state.machine.machineId] = state;
+ }
+ return app;
+}
+
+List<String> _agentIds(List<PhoneSearchResult> rows) => [
+ for (final row in rows)
+ if (row.entry != null) row.entry!.agent.id,
+];
+
+void main() {
+ group('Agent.fromJson', () {
+ test('reads the title and when the conversation last moved', () {
+ final agent = Agent.fromJson({
+ 'id': 'a',
+ 'name': 'work · 3188',
+ 'title': 'Fix login redirect',
+ 'updatedAt': '2026-09-17T07:00:00.000Z',
+ });
+ expect(agent.title, 'Fix login redirect');
+ expect(agent.updatedAt, DateTime.utc(2026, 9, 17, 7));
+ expect(agent.copyWith(name: 'x').updatedAt, agent.updatedAt);
+ });
+
+ test('an older daemon, or garbage, leaves both unknown', () {
+ final agent = Agent.fromJson({
+ 'id': 'a',
+ 'title': null,
+ 'updatedAt': 'yesterday-ish',
+ });
+ expect(agent.title, isNull);
+ expect(agent.updatedAt, isNull);
+ });
+ });
+
+ test('recentAgents: waiting, working, openable, then newest first', () {
+ final machine = _machine('m', [
+ _agent('undated'),
+ _agent('old', minutesAgo: 90),
+ _agent('gone', minutesAgo: 1, terminal: false),
+ _agent('fresh', minutesAgo: 2),
+ _agent('busy', minutesAgo: 60),
+ _agent('asking', minutesAgo: 30),
+ ]);
+ machine.processingAgentIds.add('busy');
+ _markWaiting(machine, 'asking');
+ final entries = [
+ for (final agent in machine.agents)
+ AgentEntry(machine: machine, agent: agent),
+ ];
+ expect(recentAgents(entries).map((entry) => entry.agent.id), [
+ 'asking',
+ 'busy',
+ 'fresh',
+ 'old',
+ 'undated',
+ 'gone',
+ ]);
+ });
+
+ group('search', () {
+ final app = _app([
+ _machine('box', [
+ _agent('3188', minutesAgo: 1),
+ _agent('48e9', title: 'Review payment flow', minutesAgo: 20),
+ _agent('2312', cwd: '/srv/node', minutesAgo: 5),
+ ]),
+ ]);
+ tearDownAll(app.dispose);
+
+ test('a title ranks like a name, ahead of a fresher metadata hit', () {
+ final withFolderHit = _app([
+ _machine('box', [
+ _agent('f00d', cwd: '/srv/reviewer', minutesAgo: 0),
+ ...app.machineStates['box']!.agents,
+ ]),
+ ]);
+ addTearDown(withFolderHit.dispose);
+ final ranked = rankPhoneSearch(phoneSearchIndex(withFolderHit), 'review');
+ expect(_agentIds(ranked), ['48e9', 'f00d']);
+ expect(ranked.first.subtitle, 'Review payment flow');
+ });
+
+ test('groups keep recency: the freshest agent heads the first group', () {
+ final groups = phoneSearchGroups(phoneSearchIndex(app));
+ expect([for (final group in groups) group.folder], ['work', 'node']);
+ expect(_agentIds(phoneSearchGroupedRows(groups)), [
+ '3188',
+ '48e9',
+ '2312',
+ ]);
+ });
+
+ test('the best match is the first row of the first group', () {
+ final ranked = rankPhoneSearch(phoneSearchIndex(app), '2312');
+ final groups = phoneSearchGroups(ranked);
+ expect(groups.first.folder, 'node');
+ expect(_agentIds(groups.first.rows).first, '2312');
+ });
+ });
+
+ test('compactAge', () {
+ final now = DateTime(2026, 9, 17, 12);
+ String ago(Duration age) => compactAge(now.subtract(age), now);
+ expect(ago(const Duration(seconds: 20)), 'now');
+ expect(ago(const Duration(minutes: 4)), '4m');
+ expect(ago(const Duration(hours: 2, minutes: 59)), '2h');
+ expect(ago(const Duration(days: 3)), '3d');
+ expect(ago(const Duration(days: 15)), '2w');
+ expect(ago(const Duration(days: 400)), '1y');
+ expect(compactAge(now.add(const Duration(minutes: 5)), now), 'now');
+ });
+
+ testWidgets('the page draws folders, the work and how fresh it is', (
+ tester,
+ ) async {
+ final app = _app([
+ _machine('box', [
+ _agent('3188', title: 'Fix login redirect', minutesAgo: 4),
+ _agent('2312', cwd: '/srv/node', minutesAgo: 30),
+ ]),
+ ]);
+ addTearDown(app.dispose);
+ await tester.pumpWidget(MaterialApp(home: PhoneSearchPage(notifier: app)));
+ await tester.pump();
+
+ expect(find.byType(PhoneSearchFolderHeader), findsNWidgets(2));
+ expect(find.text('Fix login redirect'), findsOneWidget);
+ expect(find.text('4m'), findsOneWidget);
+ expect(find.text('30m'), findsOneWidget);
+ expect(
+ tester.getTopLeft(find.text('work · 3188')).dy,
+ lessThan(tester.getTopLeft(find.text('work · 2312')).dy),
+ );
+
+ await tester.enterText(find.byType(TextField), 'login');
+ await tester.pump();
+ expect(find.text('work · 2312'), findsNothing);
+ expect(find.byType(PhoneSearchFolderHeader), findsOneWidget);
+ });
+
+ testWidgets('one bar: no Cancel beside it, and its chevron closes search', (
+ tester,
+ ) async {
+ final app = _app([
+ _machine('box', [_agent('3188', minutesAgo: 4)]),
+ ]);
+ addTearDown(app.dispose);
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Builder(
+ builder: (context) => TextButton(
+ onPressed: () => openPhoneSearch(context, app),
+ child: const Text('Open search'),
+ ),
+ ),
+ ),
+ );
+ await tester.tap(find.text('Open search'));
+ await tester.pumpAndSettle();
+ expect(find.byType(PhoneSearchPage), findsOneWidget);
+ expect(find.text('Cancel'), findsNothing);
+
+ await tester.tap(find.bySemanticsLabel('Back'));
+ await tester.pumpAndSettle();
+ expect(find.byType(PhoneSearchPage), findsNothing);
+ });
+}