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
Find agents and machines with one query
tony5501970dd2f9
diff --git a/mobile/lib/core/fuzzy_match.dart b/mobile/lib/core/fuzzy_match.dartnew file mode 100644index 000000000..1570f5e29--- /dev/null+++ b/mobile/lib/core/fuzzy_match.dart@@ -0,0 +1,25 @@+/// The spread of a subsequence match, or null when the query does not match.+/// Both arguments should already be normalized for case.+///+/// Ported from the desktop's `core/fuzzy_match.dart` unchanged, so a query that+/// finds an agent there finds the same agent here. The two apps rank the same+/// rows off this one primitive; letting them drift would mean "mbp" reaching a+/// machine on the laptop and nothing on the phone.+int? subsequenceSpread(+ String text,+ String query, {+ void Function(int start, int end)? onMatch,+}) {+ if (query.isEmpty) return 0;+ var at = -1;+ var first = -1;+ for (final rune in query.runes) {+ final character = String.fromCharCode(rune);+ final found = text.indexOf(character, at + 1);+ if (found < 0) return null;+ if (first < 0) first = found;+ at = found;+ onMatch?.call(found, found + character.length);+ }+ return at - first;+}diff --git a/mobile/lib/phone/agents_tab.dart b/mobile/lib/phone/agents_tab.dartindex 1194e415d..184010b4d 100644--- a/mobile/lib/phone/agents_tab.dart+++ b/mobile/lib/phone/agents_tab.dart@@ -12,6 +12,7 @@ import 'machine_filter_bar.dart';import 'phone_card.dart';import 'phone_fab.dart';import 'phone_header.dart';+import 'phone_search_button.dart';import 'phone_sheet.dart';import 'phone_navigation.dart';import 'phone_status.dart';@@ -83,7 +84,20 @@ class _AgentsTabState extends State<AgentsTab> {// No account avatar here. Settings ▸ Account carries the address// and the sign-out, and a second copy in the corner of the home// screen bought nothing but a place for them to disagree.- const PhoneHeader(large: true, title: 'Agents'),+ //+ // The one control the title line does carry is search, because+ // what it searches is not this list: it spans agents AND machines,+ // which is the half of the question this tab cannot answer. It+ // appears only once there is something to find — a glyph that+ // opens an empty screen is worse than no glyph.+ PhoneHeader(+ large: true,+ title: 'Agents',+ trailing: [+ if (machines.isNotEmpty)+ PhoneSearchButton(notifier: widget.notifier),+ ],+ ),if (error != null)_ErrorStrip(message: error, notifier: widget.notifier),if (machines.isNotEmpty)diff --git a/mobile/lib/phone/machines_tab.dart b/mobile/lib/phone/machines_tab.dartindex 497a99179..cf2fb59de 100644--- a/mobile/lib/phone/machines_tab.dart+++ b/mobile/lib/phone/machines_tab.dart@@ -9,6 +9,7 @@ import 'machine_tile.dart';import 'phone_card.dart';import 'phone_header.dart';import 'phone_navigation.dart';+import 'phone_search_button.dart';/// The machines on the account, grouped by what they need.///@@ -34,7 +35,18 @@ class MachinesTab extends StatelessWidget {bottom: false,child: Column(children: [- const PhoneHeader(large: true, title: 'Machines'),+ // The same search the Agents tab offers, reached the same way.+ // It spans both kinds, so which tab it was opened from changes+ // nothing about what it finds — a machine hunted for from here+ // and an agent hunted for from there are one query.+ PhoneHeader(+ large: true,+ title: 'Machines',+ trailing: [+ if (notifier.machines.isNotEmpty)+ PhoneSearchButton(notifier: notifier),+ ],+ ),Expanded(child: _Body(notifier: notifier)),],),diff --git a/mobile/lib/phone/phone_search_button.dart b/mobile/lib/phone/phone_search_button.dartnew file mode 100644index 000000000..1744ec8ce--- /dev/null+++ b/mobile/lib/phone/phone_search_button.dart@@ -0,0 +1,37 @@+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/shared/widgets/app_icon_button.dart';+import 'package:harness_mobile/state/app_state.dart';++import 'phone_search_page.dart';++/// The way into [PhoneSearchPage], drawn in a tab header's `trailing`.+///+/// One widget for both tabs rather than the same four lines written twice: the+/// search it opens spans agents AND machines, so the two tabs must offer it+/// identically. A glyph that sat at a different size or opened a differently+/// configured page on one of them would read as two different features.+class PhoneSearchButton extends StatelessWidget {+ const PhoneSearchButton({super.key, required this.notifier});++ final AppNotifier notifier;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Padding(+ // Clear of the header's own right padding, so the glyph sits on the same+ // vertical as the large title beside it rather than jammed to the edge.+ padding: const EdgeInsets.only(right: 2),+ child: AppIconButton(+ icon: LucideIcons.search300,+ size: 22,+ tooltip: 'Search',+ color: AppPalette.textSecondary,+ onPressed: () => openPhoneSearch(context, notifier),+ ),+ );+ }+}diff --git a/mobile/lib/phone/phone_search_index.dart b/mobile/lib/phone/phone_search_index.dartnew file mode 100644index 000000000..619999ace--- /dev/null+++ b/mobile/lib/phone/phone_search_index.dart@@ -0,0 +1,250 @@+import 'package:harness_mobile/core/fuzzy_match.dart';+import 'package:harness_mobile/state/app_state.dart';++import 'agent_index.dart';+import 'machine_index.dart';+import 'phone_status.dart';++/// What a search result opens.+enum PhoneSearchKind { agent, machine }++/// One row the search offers, whichever of the two lists it came from.+///+/// The phone's two tabs answer two different questions — every agent on the+/// account, every machine on the account — and until now there was nowhere to+/// ask both at once. Somebody who remembers only "that review thing" should not+/// have to know first whether it is the name of an agent or of the machine it+/// 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.+class PhoneSearchResult {+ const PhoneSearchResult({+ required this.kind,+ required this.id,+ required this.title,+ required this.subtitle,+ required this.fields,+ required this.summary,+ required this.machineId,+ this.entry,+ this.machine,+ });++ final PhoneSearchKind kind;++ /// Unique across both kinds — an agent and a machine can share a name, and+ /// two machines can each hold an agent with the same id.+ final String id;++ /// The name, as the row draws it and as the query matches it first.+ final String title;++ /// The line under it: an agent's engine and machine, a machine's status.+ final String subtitle;++ /// Every searchable string, lowercased, title first. Not everything in here is+ /// drawn — an agent's engine id is matched but never shown as itself — which is+ /// why [SearchResultText] re-checks that a matched field is actually present in+ /// the text it is emphasising.+ final List<String> fields;++ final PhoneSummary summary;++ /// The machine this row belongs to, for either kind. An agent needs it to+ /// open; a machine IS it.+ final String machineId;++ /// Set for [PhoneSearchKind.agent] — what a tap opens.+ final AgentEntry? entry;++ /// Set for [PhoneSearchKind.machine].+ final MachineState? machine;+}++/// Everything one query can reach, unfiltered, in the order the two tabs draw.+///+/// 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 come from [visibleMachines], which keeps+/// every one INCLUDING the locked and the offline: a machine wanting its password+/// is exactly what somebody searching for it came to fix.+///+/// 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 ?? '';+ results.add(+ PhoneSearchResult(+ kind: PhoneSearchKind.agent,+ id: 'agent:${entry.machineId}:${agent.id}',+ title: agent.name,+ subtitle: engine.isEmpty+ ? entry.machineName+ : '$engine · ${entry.machineName}',+ 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(),+ // Neither the project nor its branch is drawn on a phone row — there+ // is no third line for either — 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.+ (agent.project?.name ?? '').toLowerCase(),+ (agent.project?.branch ?? '').toLowerCase(),+ ].where((field) => field.isNotEmpty).toList(),+ summary: entry.summary,+ machineId: entry.machineId,+ entry: entry,+ ),+ );+ }+ for (final machine in visibleMachines(notifier)) {+ final summary = phoneMachineSummary(machine);+ results.add(+ PhoneSearchResult(+ kind: PhoneSearchKind.machine,+ id: 'machine:${machine.machine.machineId}',+ title: machine.machine.displayName,+ subtitle: summary.label,+ fields: [+ machine.machine.displayName.toLowerCase(),+ summary.label.toLowerCase(),+ ].where((field) => field.isNotEmpty).toList(),+ summary: summary,+ machineId: machine.machine.machineId,+ machine: machine,+ ),+ );+ }+ return results;+}++/// 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+/// the review agent on the MacBook without either word having to match the whole+/// row. The desktop splits the same way, and the freedom to match different+/// fields is what makes word order not matter.+List<String> phoneSearchTerms(String query) => query+ .toLowerCase()+ .split(RegExp(r'\s+'))+ .where((term) => term.isNotEmpty)+ .toList();++/// How well [term] matches [field]: LOWER is better, null does not match.+///+/// Ported from the desktop's `swarmFieldMatchScore` so both apps rank alike.+/// The bands, cheapest first: an exact field, a prefix, a substring anywhere,+/// and last a scattered-letter subsequence whose cost grows with how far apart+/// the letters landed. A non-title field takes a flat 64 penalty, which is what+/// keeps a name match ahead of every piece of metadata under it.+int? phoneFieldMatchScore(String field, String term, {required bool title}) {+ final offset = field.indexOf(term);+ final spread = offset >= 0 ? 0 : subsequenceSpread(field, term);+ if (spread == null) return null;+ return (title ? 0 : 64) ++ (field == term+ ? 0+ : offset == 0+ ? 8+ : offset > 0+ ? 16+ : 128 + spread);+}++/// 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.+///+/// ⚠️ 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.+List<PhoneSearchResult> rankPhoneSearch(+ List<PhoneSearchResult> all,+ String query,+) {+ final needle = query.trim().toLowerCase();+ if (needle.isEmpty) return all;+ final terms = phoneSearchTerms(needle);+ if (terms.isEmpty) return all;++ 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) {+ 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;+ }+ // One word matching nothing drops the row: the words narrow, they do not+ // accumulate. Without this, "review mac" would return everything either+ // word touches.+ if (best == null) {+ total = -1;+ break;+ }+ total += best;+ }+ if (total >= 0) ranked.add((row: row, score: total, index: index));+ }++ ranked.sort((a, b) {+ final byScore = a.score.compareTo(b.score);+ return byScore != 0 ? byScore : a.index.compareTo(b.index);+ });+ return [for (final row in ranked) row.row];+}++/// The matching rows of one kind, keeping rank order.+List<PhoneSearchResult> phoneSearchOfKind(+ List<PhoneSearchResult> rows,+ PhoneSearchKind kind,+) => [+ for (final row in rows)+ if (row.kind == kind) row,+];++/// The agent rows' entries, in rank order — what a pager opened from a result+/// swipes along.+///+/// ⚠️ **One entry out, one agent row in.** [PhoneSearchResult.entry] is nullable+/// because a machine row has none, so unwrapping it at the call site invites a+/// null-collapse that quietly drops a row. The pager walks this list BY INDEX+/// against the rows drawn on screen: a list one shorter than the list somebody+/// tapped sends the next swipe to a different agent than the one beside it.+///+/// Building it here keeps that invariant next to the code that establishes it —+/// [phoneSearchIndex] sets `entry` on every agent row it makes — rather than+/// leaving each caller to rediscover it.+List<AgentEntry> phoneSearchAgentEntries(List<PhoneSearchResult> rows) => [+ for (final row in rows)+ if (row.kind == PhoneSearchKind.agent && row.entry != null) row.entry!,+];diff --git a/mobile/lib/phone/phone_search_page.dart b/mobile/lib/phone/phone_search_page.dartnew file mode 100644index 000000000..22a06c65e--- /dev/null+++ b/mobile/lib/phone/phone_search_page.dart@@ -0,0 +1,553 @@+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/shared/widgets/empty_state.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/widgets/engine_identity.dart';++import 'phone_navigation.dart';+import 'phone_search_index.dart';+import 'search_result_text.dart';+import 'status_pill.dart';++/// One query over everything the account can reach — agents and machines+/// together.+///+/// A screen of its own rather than a field above either list, and that is the+/// whole point: the two tabs each answer half the question, and somebody who+/// remembers "that review thing" does not know which half holds it. This is the+/// phone's version of the desktop's Open Agent picker, down to the ranking — the+/// two share [phoneFieldMatchScore] so a query that finds an agent on the laptop+/// finds the same agent here.+///+/// ⚠️ It never asks a machine anything. Keystrokes filter the cached index and+/// nothing else, so typing on a phone with two bars of signal stays instant and+/// costs no data.+void openPhoneSearch(BuildContext context, AppNotifier notifier) =>+ Navigator.of(context).push(+ phoneRoute((_) => PhoneSearchPage(notifier: notifier)),+ );++class PhoneSearchPage extends StatefulWidget {+ const PhoneSearchPage({super.key, required this.notifier});++ final AppNotifier notifier;++ @override+ State<PhoneSearchPage> createState() => _PhoneSearchPageState();+}++class _PhoneSearchPageState extends State<PhoneSearchPage> {+ final _controller = TextEditingController();+ final _focus = FocusNode(debugLabel: 'Phone search');+ String _query = '';++ @override+ void dispose() {+ _controller.dispose();+ _focus.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: widget.notifier,+ builder: (context, _) {+ AppTheme.watch(context);+ final all = phoneSearchIndex(widget.notifier);+ final rows = rankPhoneSearch(all, _query);+ final terms = phoneSearchTerms(_query);+ return Scaffold(+ backgroundColor: AppPalette.windowBg,+ // The keyboard is up for this page's whole life, so the body must shrink+ // rather than let the list run underneath it.+ resizeToAvoidBottomInset: true,+ body: SafeArea(+ bottom: false,+ child: Column(+ children: [+ _SearchField(+ controller: _controller,+ focus: _focus,+ onChanged: (value) => setState(() => _query = value),+ onClear: () {+ _controller.clear();+ setState(() => _query = '');+ // Clearing is a step back into browsing, not out of the+ // screen — the caret stays where the next query will go.+ _focus.requestFocus();+ },+ onCancel: () => Navigator.of(context).maybePop(),+ ),+ Expanded(+ child: _Results(+ notifier: widget.notifier,+ rows: rows,+ terms: terms,+ query: _query,+ total: all.length,+ ),+ ),+ ],+ ),+ ),+ );+ },+ );+}++/// 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(+ child: Container(+ height: 44,+ padding: const EdgeInsets.symmetric(horizontal: 13),+ decoration: BoxDecoration(+ color: AppGlass.rowFill,+ borderRadius: BorderRadius.circular(AppCard.radius),+ border: Border.all(color: AppGlass.hair),+ ),+ 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,+ style: TextStyle(+ color: AppPalette.textPrimary,+ fontSize: 16,+ ),+ cursorColor: AppPalette.accentOnSurface,+ decoration: InputDecoration(+ isDense: true,+ border: InputBorder.none,+ 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,+ required this.rows,+ required this.terms,+ required this.query,+ required this.total,+ });++ final AppNotifier notifier;+ final List<PhoneSearchResult> rows;+ final List<String> terms;+ final String query;+ final int total;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ if (total == 0) {+ return const EmptyState(+ icon: LucideIcons.laptopMinimal300,+ title: 'Nothing to search yet',+ message:+ 'Link a machine and its agents will be findable from here.',+ );+ }+ if (rows.isEmpty) {+ return EmptyState.noMatches(+ compact: false,+ message: 'Nothing matches “${query.trim()}”.',+ );+ }++ final agents = phoneSearchOfKind(rows, PhoneSearchKind.agent);+ final machines = phoneSearchOfKind(rows, PhoneSearchKind.machine);+ 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.+ keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,+ padding: EdgeInsets.fromLTRB(+ 16,+ 0,+ 16,+ 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(+ row: row,+ terms: terms,+ onTap: () => _openAgent(context, row),+ ),+ ],+ if (machines.isNotEmpty) ...[+ _GroupLabel('Machines', count: machines.length),+ for (final row in machines)+ _ResultRow(+ row: row,+ terms: terms,+ onTap: () => _openMachine(context, row),+ ),+ ],+ ],+ );+ }++ /// Opens the agent as a pager over the OTHER matching agents.+ ///+ /// The neighbours are the search results, not the Agents tab's list: swiping+ /// 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) {+ final entry = row.entry;+ if (entry == null || !entry.agent.terminalAvailable) return;+ // ⚠️ Built from [phoneSearchAgentEntries] rather than by unwrapping each+ // row here. A `?result.entry` collapse would silently SHORTEN this list if+ // 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);+ }++ /// Opens the machine, on whichever of its two screens it needs — its password+ /// form or its agent list. [openMachine] decides that from the machine's own+ /// state, so a machine that gets linked while this page is open opens on the+ /// right one.+ ///+ /// No pager here. The machines a query returns are a scattering of the+ /// Machines tab's order, and swiping along a set somebody assembled by typing+ /// a word is not a list — it is three unrelated computers.+ void _openMachine(BuildContext context, PhoneSearchResult row) =>+ openMachine(context, notifier, row.machineId);+}++class _GroupLabel extends StatelessWidget {+ const _GroupLabel(this.text, {required this.count});++ final String text;+ final int count;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Padding(+ padding: const EdgeInsets.fromLTRB(4, 12, 4, 6),+ child: Row(+ children: [+ Text(+ text.toUpperCase(),+ style: TextStyle(+ color: AppPalette.textFaint,+ fontSize: 11.5,+ fontWeight: FontWeight.w600,+ letterSpacing: 0.5,+ ),+ ),+ const SizedBox(width: 7),+ Text(+ '$count',+ style: TextStyle(+ color: AppPalette.textFaint,+ fontSize: 11.5,+ fontWeight: FontWeight.w600,+ fontFeatures: AppFont.tabularFigures,+ ),+ ),+ ],+ ),+ );+ }+}++/// 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 can always be opened — a locked one opens on+ /// its password form, which is the thing to do about it.+ bool get _openable => switch (widget.row.kind) {+ PhoneSearchKind.agent => widget.row.entry?.agent.terminalAvailable ?? false,+ PhoneSearchKind.machine => true,+ };++ 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,+ ),+ ),+ ],+ ),+ ),+ const SizedBox(width: 8),+ _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 opens a terminal" from "this asks you+/// for a password" before anything is tapped.+class _Action extends StatelessWidget {+ const _Action({required this.row, required this.openable});++ final PhoneSearchResult row;+ final bool openable;++ String get _label {+ if (!openable) return 'No terminal';+ return switch (row.kind) {+ PhoneSearchKind.agent => 'Open',+ PhoneSearchKind.machine =>+ row.machine?.needsLink ?? false ? 'Unlock' : 'View',+ };+ }++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return 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.dartnew file mode 100644index 000000000..5cfdbce0f--- /dev/null+++ b/mobile/lib/phone/search_result_text.dart@@ -0,0 +1,176 @@+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+/// row's title.+typedef PhoneFieldMatch = ({String field, String term, bool title});++/// The field each term actually matched, so only that one is emphasised.+///+/// Recomputed per visible row rather than carried through ranking: the work is+/// bounded by what is on screen, and keeping it out of the ranking path means+/// scrolling never pays for emphasis it has already drawn.+List<PhoneFieldMatch> phoneResultMatches(+ PhoneSearchResult row,+ List<String> terms,+) {+ final matches = <PhoneFieldMatch>[];+ // Bounded: a pathological query must not turn one row's emphasis into more+ // 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,+ ));+ }+ }+ return matches;+}++/// A stretch of text, and whether the query reached it.+typedef PhoneTextRun = ({String text, bool matched});++/// [text] split into matched and unmatched runs.+///+/// Walks GRAPHEME clusters, not code units, because case folding can change a+/// string's length and a query can land in the middle of an emoji or a combining+/// sequence — an agent named "🇻🇳 deploy" must not be cut through its flag.+/// Long labels are left plain: emphasis is worth a bounded amount of layout work+/// on a one-line row and no more.+List<PhoneTextRun> phoneTextRuns(+ String text,+ Iterable<PhoneFieldMatch> matches,+) {+ if (matches.isEmpty || text.isEmpty || text.length > 1024) {+ return [(text: text, matched: false)];+ }+ final clusters = <({int start, int end, int foldedStart, int foldedEnd})>[];+ final folded = StringBuffer();+ var offset = 0;+ var foldedOffset = 0;+ for (final cluster in text.characters) {+ final lower = cluster.toLowerCase();+ clusters.add((+ start: offset,+ end: offset + cluster.length,+ foldedStart: foldedOffset,+ foldedEnd: foldedOffset + lower.length,+ ));+ offset += cluster.length;+ foldedOffset += lower.length;+ folded.write(lower);+ }+ final normalized = folded.toString();++ final positions = <({int start, int end})>[];+ for (final match in matches) {+ // A row can match on a field it never draws — an engine id, a project path.+ // Emphasising something in unrelated text because of it would be a lie about+ // why the row is there.+ final fieldAt = normalized.indexOf(match.field);+ if (fieldAt < 0) continue;+ final exact = match.field.indexOf(match.term);+ if (exact >= 0) {+ positions.add((+ start: fieldAt + exact,+ end: fieldAt + exact + match.term.length,+ ));+ continue;+ }+ final fuzzy = <({int start, int end})>[];+ final spread = subsequenceSpread(+ match.field,+ match.term,+ onMatch: (start, end) =>+ fuzzy.add((start: fieldAt + start, end: fieldAt + end)),+ );+ if (spread != null) positions.addAll(fuzzy);+ }+ if (positions.isEmpty) return [(text: text, matched: false)];+ positions.sort((a, b) => a.start.compareTo(b.start));++ final runs = <PhoneTextRun>[];+ var start = 0;+ var positionIndex = 0;+ bool? active;+ for (final cluster in clusters) {+ while (positionIndex < positions.length &&+ positions[positionIndex].end <= cluster.foldedStart) {+ positionIndex++;+ }+ final matched =+ positionIndex < positions.length &&+ positions[positionIndex].start < cluster.foldedEnd;+ if (active != null && active != matched) {+ runs.add((text: text.substring(start, cluster.start), matched: active));+ start = cluster.start;+ }+ active = matched;+ }+ runs.add((text: text.substring(start), matched: active ?? false));+ return runs;+}++/// One line of a search result, with the part the query reached set in bold.+///+/// Weight alone carries the emphasis — no colour, no highlight fill. A result+/// list is already dense with tone (a status dot, an attention rim), and a+/// second colour meaning "you typed this" would compete with the one meaning+/// "this needs you".+class SearchResultText extends StatelessWidget {+ const SearchResultText(+ this.text, {+ super.key,+ required this.matches,+ required this.style,+ });++ final String text;+ final Iterable<PhoneFieldMatch> matches;+ final TextStyle style;++ @override+ Widget build(BuildContext context) {+ final runs = phoneTextRuns(text, matches);+ if (!runs.any((run) => run.matched)) {+ return Text(+ text,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: style,+ );+ }+ return Text.rich(+ TextSpan(+ children: [+ for (final run in runs)+ TextSpan(+ text: run.text,+ style: run.matched+ ? const TextStyle(fontWeight: FontWeight.w700)+ : null,+ ),+ ],+ ),+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: style,+ );+ }+}