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
Refactor terminal input tests and implement phone search functionality
Dev jacob9824bcbffd90
diff --git a/cli/src/backendSocket.ts b/cli/src/backendSocket.tsindex a7396d4a5..00d647847 100644--- a/cli/src/backendSocket.ts+++ b/cli/src/backendSocket.ts@@ -39,7 +39,7 @@ import { engineInstallRecipe } from './lib/engineInstall.js'import { parseProjectFolder, prepareProjectFolder, ProjectFolderError } from './lib/projectFolder.js'import { preTrustClaudeProject, preTrustCodexProject } from './lib/claudeTrust.js'import { projectPreview } from './lib/projectPreview.js'-import { agentFrame, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'+import { agentFrame, lastActivityAt, type AgentDshContext, type AgentFrame } from './lib/agentFrame.js'import { installedDsh } from './dsh/installed.js'import { engineLabel } from './lib/agentNames.js'import { DSH_ID_RE } from './dsh/manifest.js'@@ -1327,14 +1327,13 @@ export class BackendSocket {// lands, instead of pinning `currentSessionId` to an id no event will ever carry.if (!s || !s.sessionId) { reply(type, requestId, { sessions: [] }); return }const lines = s.transcriptPath ? await tailFile(s.transcriptPath, Infinity) : []- const st = s.transcriptPath ? await stat(s.transcriptPath).catch(() => null) : nullreply(type, requestId, {sessions: [{id: s.sessionId,title: projectDisplayName(s),timestamp: new Date(s.registeredAt).toISOString(),messageCount: lines.length,- lastActivity: new Date(st?.mtimeMs ?? s.updatedAt).toISOString(),+ lastActivity: new Date(await lastActivityAt(s)).toISOString(),participants: [],}],})diff --git a/cli/src/lib/agentFrame.spec.ts b/cli/src/lib/agentFrame.spec.tsindex 8cea8fddb..5206248d6 100644--- a/cli/src/lib/agentFrame.spec.ts+++ b/cli/src/lib/agentFrame.spec.ts@@ -1,3 +1,6 @@+import { mkdtemp, rm, utimes, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'import { describe, expect, it } from 'vitest'import { agentFrame } from './agentFrame.js'import type { RegisteredSession } from './registry.js'@@ -77,3 +80,34 @@ describe('agentFrame', () => {.toMatchObject({ launch: { state: 'failed', error: 'ENGINE_DID_NOT_START', detail: 'See terminal.' } })})})++describe('agentFrame updatedAt', () => {+ const context = { selectedModel: null, terminalAvailable: true }+ const lastHook = Date.UTC(2026, 8, 17, 7)++ // The regression: discovery rewrites the registry's `updatedAt` on every pass, so an agent with no+ // readable transcript was stamped "now" forever and a phone sorting by recency put it on top.+ it('follows the last hook without a transcript, never the bookkeeping clock', async () => {+ const row = { ...session(null), updatedAt: Date.now(), lastHookAt: lastHook }+ expect((await agentFrame(row, context)).updatedAt).toBe('2026-09-17T07:00:00.000Z')+ })++ it('an unreadable transcript falls back to the last hook too', async () => {+ const row = { ...session(null), transcriptPath: '/nonexistent/agent-frame.jsonl', updatedAt: Date.now(), lastHookAt: lastHook }+ expect((await agentFrame(row, context)).updatedAt).toBe('2026-09-17T07:00:00.000Z')+ })++ it("prefers the transcript's mtime", async () => {+ const dir = await mkdtemp(join(tmpdir(), 'agent-frame-'))+ try {+ const transcriptPath = join(dir, 'session.jsonl')+ await writeFile(transcriptPath, '{}\n')+ const written = new Date('2026-09-18T01:02:03.000Z')+ await utimes(transcriptPath, written, written)+ const row = { ...session(null), transcriptPath, updatedAt: Date.now(), lastHookAt: lastHook }+ expect((await agentFrame(row, context)).updatedAt).toBe(written.toISOString())+ } finally {+ await rm(dir, { recursive: true, force: true })+ }+ })+})diff --git a/cli/src/lib/agentFrame.ts b/cli/src/lib/agentFrame.tsindex b1814a399..11c44e084 100644--- a/cli/src/lib/agentFrame.ts+++ b/cli/src/lib/agentFrame.ts@@ -96,22 +96,31 @@ export interface AgentFrameContext {}/**- * One agent as every client consumes it.+ * When the conversation last moved, in epoch ms: the transcript's mtime, else the last time the engine+ * reported in (a hook, or a session bind — the agent's creation at the latest).*- * `updatedAt` prefers the transcript's mtime over the registry's own bookkeeping so a client sorting- * by recency follows the conversation rather than the daemon's housekeeping; an unreadable or absent- * transcript falls back to the registry, never to "now".+ * ⚠️ Never the registry's `updatedAt`. That is bookkeeping: discovery rewrites it on every pass+ * (`updateRuntimes`), so falling back to it stamped every agent without a readable transcript "now"+ * — and a client sorting by recency put exactly those agents above the ones just used.*/+export async function lastActivityAt(s: RegisteredSession): Promise<number> {+ const st = s.transcriptPath ? await stat(s.transcriptPath).catch(() => null) : null+ return st?.mtimeMs ?? s.lastHookAt+}+function frameTitle(s: RegisteredSession): string | null {const title = sessionDisplayTitle(s)return title && title !== projectDisplayName(s) ? title : null}+/**+ * One agent as every client consumes it. `updatedAt` is {@link lastActivityAt}, so a client sorting by+ * recency follows the conversation rather than the daemon's housekeeping.+ */export async function agentFrame(s: RegisteredSession,{ selectedModel, terminalAvailable, dsh }: AgentFrameContext,): Promise<AgentFrame> {- const st = s.transcriptPath ? await stat(s.transcriptPath).catch(() => null) : nullreturn {id: s.agentId,sessionId: s.sessionId,@@ -121,7 +130,7 @@ export async function agentFrame(status: s.active ? 'active' : 'offline',launch: s.launch ?? { state: 'ready' },createdAt: new Date(s.registeredAt).toISOString(),- updatedAt: new Date(st?.mtimeMs ?? s.updatedAt).toISOString(),+ updatedAt: new Date(await lastActivityAt(s)).toISOString(),tmuxPane: s.tmuxPane || null,terminal: { available: terminalAvailable, primary: s.primaryRuntimeKey, runtimes: s.runtimes },engine: s.engine,diff --git a/mobile/lib/core/models.dart b/mobile/lib/core/models.dartindex 1add13218..89c7e7db5 100644--- a/mobile/lib/core/models.dart+++ b/mobile/lib/core/models.dart@@ -134,6 +134,18 @@ class Agent {final String? engineDisplayName;final String? engineIconHint;final String? codexHome;++ /// The model a grid launch pinned (`qwen3-coder`, a llama.cpp GGUF), null when+ /// the agent is on its engine's own login or the engine chose.+ final String? gridModel;++ /// The runtime profile's model for this session (`gpt-5-codex`, `opus`), null+ /// when the daemon has none to report.+ final String? selectedModel;++ /// A domain-specific harness's display name ("Model manager"), null for a+ /// plain engine.+ final String? dshName;final String? parentAgentId;final AgentProject? project;final String status;@@ -153,6 +165,9 @@ class Agent {this.engineDisplayName,this.engineIconHint,this.codexHome,+ this.gridModel,+ this.selectedModel,+ this.dshName,this.parentAgentId,this.project,this.status = 'active',@@ -187,6 +202,7 @@ class Agent {'failed' => 'failed',_ => 'ready',};+ final grid = j['grid'];return Agent(id: j['id'] as String,sessionId: _safeLabel(j['sessionId']),@@ -197,6 +213,9 @@ class Agent {engineDisplayName: _safeLabel(j['engineDisplayName']),engineIconHint: _safeLabel(j['engineIconHint']),codexHome: j['engine'] == 'codex' ? _safeCodexHome(j['codexHome']) : null,+ gridModel: grid is Map ? _safeLabel(grid['model']) : null,+ selectedModel: _safeLabel(j['selectedModel']),+ dshName: _safeLabel(j['dshName']),parentAgentId: _safeLabel(j['parentAgentId'] ?? j['parentId']),project: AgentProject.fromJson(j['project']),status: (j['status'] as String?) ?? 'active',@@ -223,6 +242,9 @@ class Agent {engineDisplayName: engineDisplayName,engineIconHint: engineIconHint,codexHome: codexHome,+ gridModel: gridModel,+ selectedModel: selectedModel,+ dshName: dshName,parentAgentId: parentAgentId,project: project,status: status,diff --git a/mobile/lib/phone/machines_tab.dart b/mobile/lib/phone/machines_tab.dartindex ba3051cad..566448bfb 100644--- a/mobile/lib/phone/machines_tab.dart+++ b/mobile/lib/phone/machines_tab.dart@@ -14,6 +14,7 @@ import 'phone_card.dart';import 'phone_header.dart';import 'phone_navigation.dart';import 'phone_search_button.dart';+import 'phone_section_label.dart';import 'phone_status.dart';import 'phone_sheet.dart';import 'unlink_machine.dart';@@ -113,12 +114,13 @@ class _Body extends StatelessWidget {padding: phoneListPadding(context),children: [if (working.isNotEmpty) ...[- const _SectionLabel('Linked'),+ const PhoneSectionLabel('Linked'),for (final state in working) _tile(context, state),const SizedBox(height: 6),],if (needsAttention.isNotEmpty) ...[- if (working.isNotEmpty) const _SectionLabel('Needs your attention'),+ if (working.isNotEmpty)+ const PhoneSectionLabel('Needs your attention'),for (final state in needsAttention) _tile(context, state),],],@@ -180,26 +182,3 @@ class _Body extends StatelessWidget {);}}--class _SectionLabel extends StatelessWidget {- const _SectionLabel(this.text);-- final String text;-- @override- Widget build(BuildContext context) {- AppTheme.watch(context);- return Padding(- padding: const EdgeInsets.fromLTRB(4, 8, 4, 8),- child: Text(- text.toUpperCase(),- style: TextStyle(- color: AppPalette.textFaint,- fontSize: 11.5,- fontWeight: FontWeight.w600,- letterSpacing: 0.5,- ),- ),- );- }-}diff --git a/mobile/lib/phone/phone_search_groups.dart b/mobile/lib/phone/phone_search_groups.dartindex 3e42c77e2..185d66530 100644Binary files a/mobile/lib/phone/phone_search_groups.dart and b/mobile/lib/phone/phone_search_groups.dart differdiff --git a/mobile/lib/phone/phone_search_index.dart b/mobile/lib/phone/phone_search_index.dartindex c7f8d6971..0031767cc 100644--- a/mobile/lib/phone/phone_search_index.dart+++ b/mobile/lib/phone/phone_search_index.dart@@ -1,8 +1,7 @@-import 'package:harness_mobile/core/fuzzy_match.dart';+import 'package:harness_mobile/state/agent_recall.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.@@ -26,10 +25,12 @@ class PhoneSearchResult {required this.id,required this.title,required this.subtitle,+ required this.placedSubtitle,required this.fields,required this.summary,required this.machineId,this.titleFields = 1,+ this.recall,this.entry,this.machine,});@@ -43,9 +44,15 @@ class PhoneSearchResult {/// 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.+ /// The line under it, when a folder header over the row already says where+ /// it is: an agent's work and branch, a machine's status.final String subtitle;+ /// The line under it when nothing above the row says where it is — the+ /// Recent list, which is one run rather than folders: the work, then the+ /// folder and the machine.+ final String placedSubtitle;+/// 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@@ -57,6 +64,10 @@ class PhoneSearchResult {/// it, and is ranked that way on the desktop too (its `titleFields`).final int titleFields;+ /// What was last said to this agent and what it answered, when its machine+ /// has told us — the fallback a word that matches no field is looked for in.+ final AgentRecall? recall;+final PhoneSummary summary;/// The machine this row belongs to, for either kind. An agent needs it to@@ -71,30 +82,29 @@ class PhoneSearchResult {}/// Everything one query can reach, unfiltered: agents most recent first (see-/// [recentAgents]), then machines in the order their tab draws them.+/// [recentAgents]).////// 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 recentAgents(agentIndex(notifier))) {- results.add(_agentResult(entry));- }- // Agents only. Machines used to be listed here as well; they are reached from the terminal's `⋯`- // sheet now (`machine_actions.dart`), so search answers the one question it is opened for.- return results;-}+/// last-seen agent list is not. Machines are not listed: they are reached from+/// the terminal's `⋯` sheet (`machine_actions.dart`), so search answers the one+/// question it is opened for.+List<PhoneSearchResult> phoneSearchIndex(AppNotifier notifier) => [+ for (final entry in recentAgents(agentIndex(notifier)))+ _agentResult(+ entry,+ notifier.agentRecall.read(+ notifier.agentRecallKey(entry.machineId, entry.agent),+ ),+ ),+];-PhoneSearchResult _agentResult(AgentEntry entry) {+PhoneSearchResult _agentResult(AgentEntry entry, AgentRecall? recall) {final agent = entry.agent;final engine = agent.engineDisplayName ?? agent.engine ?? '';final title = agent.title ?? '';final branch = entry.project?.branchLabel ?? '';+ final folder = entry.project?.folder ?? '';return PhoneSearchResult(kind: PhoneSearchKind.agent,id: 'agent:${entry.machineId}:${agent.id}',@@ -103,161 +113,46 @@ PhoneSearchResult _agentResult(AgentEntry entry) {// 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),+ subtitle: _joined([title, branch]).ifEmpty(engine),+ placedSubtitle: _joined([title, folder, entry.machineName]).ifEmpty(engine),fields: [- agent.name.toLowerCase(),- title.toLowerCase(),- entry.machineName.toLowerCase(),- engine.toLowerCase(),+ agent.name,+ title,+ entry.machineName,+ engine,// 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(),+ agent.engine ?? '',+ // What it runs on and what it was made as. None of these is drawn, but+ // "the llama one" or "the model manager" is how somebody away from the+ // desk remembers an agent whose name is `harness-3`.+ agent.gridModel ?? '',+ agent.selectedModel ?? '',+ agent.dshName ?? '',+ folder,// 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(),+ entry.project?.name ?? '',+ branch,+ ].map((field) => field.toLowerCase()).where((field) => field.isNotEmpty).toList(),titleFields: title.isEmpty ? 1 : 2,+ recall: recall,summary: entry.summary,machineId: entry.machineId,entry: entry,);}+String _joined(List<String> parts) =>+ parts.where((part) => part.isNotEmpty).join(' · ');+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-/// 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 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: [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],-/// 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 — 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) {- 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.- if (best == null) {- total = -1;- break;- }- total += best.score;- }- 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.///diff --git a/mobile/lib/phone/phone_search_page.dart b/mobile/lib/phone/phone_search_page.dartindex 86cbeddfa..2a223d3e4 100644--- a/mobile/lib/phone/phone_search_page.dart+++ b/mobile/lib/phone/phone_search_page.dart@@ -1,18 +1,12 @@-import 'dart:async';-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 '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_search_rank.dart';+import 'phone_search_results.dart';/// One query over every agent the account can reach. Machines are not searched/// here — they are on the terminal's `⋯` sheet.@@ -24,9 +18,9 @@ import 'phone_search_row.dart';/// 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.+/// ⚠️ Keystrokes never ask a machine anything. They filter what the app already+/// holds — the agent list, and the recall [PhoneSearchResults] fetched once as+/// the search opened — so typing on two bars of signal stays instant.////// Returns when the search closes, so a caller whose own chrome depends on/// being the top route can rebuild — see `terminal_page.dart`, where the header@@ -56,157 +50,40 @@ class _PhoneSearchPageState extends State<PhoneSearchPage> {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: [- PhoneSearchField(- 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();- },- onBack: () => Navigator.of(context).maybePop(),- ),- Expanded(- child: PhoneSearchResults(- notifier: widget.notifier,- rows: rows,- terms: terms,- query: _query,- total: all.length,- ),- ),- ],- ),- ),- );- },- );-}--/// The ranked results, drawn — agents under their folders, then machines.-///-/// ⚠️ Public because two screens draw it: this page, and the terminal's own-/// in-place search (see `terminal_search.dart`), which expands out of the header-/// bar rather than pushing a route. The two must return the same rows in the-/// same order from the same query, or opening a result would walk a different-/// pager depending on where the search was started.-class PhoneSearchResults extends StatelessWidget {- const PhoneSearchResults({- super.key,- required this.notifier,- required this.rows,- required this.terms,- required this.query,- required this.total,- this.onOpen,- });-- final AppNotifier notifier;- final List<PhoneSearchResult> rows;- final List<String> terms;- final String query;- final int total;-- /// Called the moment a row is tapped, before anything opens.- ///- /// ⚠️ For the in-place search, which is not a route and so is not popped by- /// opening something. Its field still holds the keyboard, and the terminal it- /// is covering is about to be replaced underneath it — this is what puts the- /// search away first. Null on [PhoneSearchPage], where the pop does it.- final VoidCallback? onOpen;-@overrideWidget 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 groups = phoneSearchGroups(rows);- final agents = phoneSearchGroupedRows(groups);- 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.- keyboardDismissBehavior: ScrollViewKeyboardDismissBehavior.onDrag,- padding: EdgeInsets.fromLTRB(- 16,- 0,- 16,- MediaQuery.paddingOf(context).bottom + 16,- ),- children: [- // Agents under their folders. Machines are not searched here any more:- // they live in the terminal's `⋯` sheet — see `machine_actions.dart`.- for (final group in groups) ...[- PhoneSearchFolderHeader(group: group),- for (final row in group.rows)- PhoneSearchRow(- row: row,- terms: terms,- now: now,- onTap: () {- onOpen?.call();- _openAgent(context, agents, row);+ 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: [+ PhoneSearchField(+ 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();},+ onBack: () => Navigator.of(context).maybePop(),+ ),+ Expanded(+ child: PhoneSearchResults(+ notifier: widget.notifier,+ query: _query,+ ),),- ],- ],+ ],+ ),+ ),);}-- /// 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.- ///- /// ⚠️ [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- // 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(agents), entry);- }}diff --git a/mobile/lib/phone/phone_search_rank.dart b/mobile/lib/phone/phone_search_rank.dartnew file mode 100644index 000000000..19c7118b2--- /dev/null+++ b/mobile/lib/phone/phone_search_rank.dart@@ -0,0 +1,192 @@+import 'package:harness_mobile/core/fuzzy_match.dart';++import 'phone_search_index.dart';++/// 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 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;+}++/// Whether [term] appears, as written, in what was last said to [row]'s agent.+///+/// Literal only — never the scattered-letter match the fields get. Three turns of+/// prose contain almost every short run of letters somewhere, so a fuzzy hit in+/// them would return every agent on the account.+bool phoneRecallHas(PhoneSearchResult row, String term) =>+ row.recall?.searchText.contains(term) ?? false;++/// What a word found only in the conversation costs: more than any metadata+/// match can, so an agent that IS "llama" stays ahead of one that talked about it.+const _recallScore = 256;++/// The rows [query] reaches, best first.+///+/// An empty query keeps index order untouched: [phoneSearchIndex] already put+/// the agents in the order worth offering before a word is typed.+///+/// A word that matches no field is looked for in the agent's recall — what was+/// last asked of it and what it answered — which is how "llama" finds the agent+/// somebody asked about llama.cpp. Rows that needed the conversation to match+/// rank after every row that matched on the agent itself, as on the desktop.+///+/// ⚠️ Ties break on the row's position in the index, never on anything that+/// moves by itself. An agent that starts working sorts upward in [agentIndex],+/// and that is the one reshuffle worth having; a second, unstable tiebreak on+/// top of it would let two idle rows swap places on an unrelated rebuild.+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, bool recalled, int index})>[];+ for (final (index, row) in all.indexed) {+ // 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, recalled: false, index: index));+ continue;+ }+ final match = _scoreRow(row, terms);+ if (match == null) continue;+ ranked.add((+ row: row,+ score: match.score,+ recalled: match.recalled,+ index: index,+ ));+ }++ int byRecall(bool recalled) => recalled ? 1 : 0;+ ranked.sort((a, b) {+ var order = byRecall(a.recalled).compareTo(byRecall(b.recalled));+ if (order == 0) order = a.score.compareTo(b.score);+ return order != 0 ? order : a.index.compareTo(b.index);+ });+ return [for (final row in ranked) row.row];+}++/// Every term's best score on [row] summed, and whether any needed the recall —+/// or null when one term matches nothing at all.+///+/// One word matching nothing drops the row: the words narrow, they do not+/// accumulate. Without this, "review mac" would return everything either word+/// touches.+({int score, bool recalled})? _scoreRow(+ PhoneSearchResult row,+ List<String> terms,+) {+ var total = 0;+ var recalled = false;+ for (final term in terms) {+ final best = phoneBestFieldMatch(row, term);+ if (best != null) {+ total += best.score;+ continue;+ }+ if (!phoneRecallHas(row, term)) return null;+ recalled = true;+ total += _recallScore;+ }+ return (score: total, recalled: recalled);+}++/// The part of [row]'s recall worth quoting under its name: the line holding the+/// first word that no field matched, from a little before that word.+///+/// Null when every word matched the agent itself — the row's own subtitle then+/// says why it is there, and a quote would only be noise.+String? phoneRecallSnippet(PhoneSearchResult row, List<String> terms) {+ final recall = row.recall;+ if (recall == null) return null;+ for (final term in terms) {+ if (phoneBestFieldMatch(row, term) != null) continue;+ for (final line in recall.lines) {+ final at = line.toLowerCase().indexOf(term);+ if (at >= 0) return _quote(line, at);+ }+ }+ return null;+}++/// How much of the line before the matched word stays in the quote.+const _lead = 16;++/// [line] from a little before [at], so the word lands near the row's start+/// rather than past the ellipsis on a phone's width.+String _quote(String line, int at) {+ // Lowercasing can change a string's length; an index into the folded line is+ // only trusted on the original when the two are the same length.+ final folds = line.toLowerCase().length == line.length;+ var start = folds && at > _lead ? at - _lead : 0;+ // Never start inside a surrogate pair — the quote would open on half an emoji.+ if (start > 0 && _isLowSurrogate(line.codeUnitAt(start))) start--;+ return start == 0 ? line : '…${line.substring(start).trimLeft()}';+}++bool _isLowSurrogate(int unit) => unit >= 0xDC00 && unit <= 0xDFFF;diff --git a/mobile/lib/phone/phone_search_results.dart b/mobile/lib/phone/phone_search_results.dartnew file mode 100644index 000000000..641c52d03--- /dev/null+++ b/mobile/lib/phone/phone_search_results.dart@@ -0,0 +1,189 @@+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 'agent_index.dart';+import 'phone_navigation.dart';+import 'phone_search_folder_header.dart';+import 'phone_search_groups.dart';+import 'phone_search_index.dart';+import 'phone_search_rank.dart';+import 'phone_search_row.dart';+import 'phone_section_label.dart';++/// What [query] reaches, drawn: the Recent list before a word is typed, then+/// matching agents under their folders.+///+/// ⚠️ Public because two screens draw it: [PhoneSearchPage], and the terminal's+/// own in-place search (see `terminal_search.dart`), which expands out of the+/// header bar rather than pushing a route. Both hand it the query and nothing+/// else, so the two cannot return different rows — or walk a different pager —+/// for the same words.+///+/// Opening it asks each connected machine, once, what was last said to the+/// agents offered first (see [AgentRecallStore]); keystrokes only ever read that+/// memory, so typing stays instant and costs no data.+class PhoneSearchResults extends StatefulWidget {+ const PhoneSearchResults({+ super.key,+ required this.notifier,+ required this.query,+ this.onOpen,+ });++ final AppNotifier notifier;+ final String query;++ /// Called the moment a row is tapped, before anything opens.+ ///+ /// ⚠️ For the in-place search, which is not a route and so is not popped by+ /// opening something. Its field still holds the keyboard, and the terminal it+ /// is covering is about to be replaced underneath it — this is what puts the+ /// search away first. Null on [PhoneSearchPage], where the pop does it.+ final VoidCallback? onOpen;++ @override+ State<PhoneSearchResults> createState() => _PhoneSearchResultsState();+}++class _PhoneSearchResultsState extends State<PhoneSearchResults> {+ late final Listenable _changes = Listenable.merge([+ widget.notifier,+ widget.notifier.agentRecall,+ ]);++ @override+ void initState() {+ super.initState();+ final notifier = widget.notifier;+ notifier.agentRecall.warm([+ for (final entry in recentAgents(agentIndex(notifier)))+ notifier.agentRecallKey(entry.machineId, entry.agent),+ ]);+ }++ @override+ Widget build(BuildContext context) => ListenableBuilder(+ listenable: _changes,+ builder: (context, _) {+ AppTheme.watch(context);+ final all = phoneSearchIndex(widget.notifier);+ if (all.isEmpty) {+ return const EmptyState(+ icon: LucideIcons.laptopMinimal300,+ title: 'Nothing to search yet',+ message: 'Link a machine and its agents will be findable from here.',+ );+ }+ final query = widget.query.trim();+ if (query.isEmpty) return _recentList(all);+ final rows = rankPhoneSearch(all, query);+ if (rows.isEmpty) {+ return EmptyState.noMatches(+ compact: false,+ message: 'Nothing matches “$query”.',+ );+ }+ return _groupedList(phoneSearchGroups(rows), phoneSearchTerms(query));+ },+ );++ /// Every agent in one run, the one that moved last on top.+ ///+ /// No folder headers here. Before a word is typed the question is "which one+ /// was I just on", and grouping answers a different one: a folder with one+ /// fresh agent and one stale one drags the stale one up past fresher agents+ /// elsewhere, and a header over every single-agent folder halves how many+ /// rows fit on the screen. Each row names its own folder and machine instead.+ Widget _recentList(List<PhoneSearchResult> rows) {+ final now = DateTime.now();+ return _ResultsList(+ children: [+ const PhoneSectionLabel(+ 'Recent',+ padding: EdgeInsets.fromLTRB(10, 14, 10, 4),+ ),+ for (final row in rows)+ PhoneSearchRow(+ row: row,+ terms: const [],+ now: now,+ placed: true,+ onTap: () => _open(rows, row),+ ),+ ],+ );+ }++ /// Matching agents under their folders, best match first — see+ /// [phoneSearchGroups] for why grouping never buries it.+ Widget _groupedList(List<PhoneSearchGroup> groups, List<String> terms) {+ final drawn = phoneSearchGroupedRows(groups);+ final now = DateTime.now();+ return _ResultsList(+ children: [+ for (final group in groups) ...[+ PhoneSearchFolderHeader(group: group),+ for (final row in group.rows)+ PhoneSearchRow(+ row: row,+ terms: terms,+ now: now,+ onTap: () => _open(drawn, row),+ ),+ ],+ ],+ );+ }++ /// Opens the agent as a pager over the OTHER rows on screen.+ ///+ /// The neighbours are the rows as drawn, not the Agents tab's list: swiping+ /// walks exactly what the query returned, in the order the person was looking+ /// at when they tapped. Handing it the unfiltered index instead would swipe+ /// into agents the query had just excluded.+ ///+ /// ⚠️ [drawn] is the order ON SCREEN — for the grouped list, 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 _open(List<PhoneSearchResult> drawn, PhoneSearchResult row) {+ widget.onOpen?.call();+ 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,+ widget.notifier,+ phoneSearchAgentEntries(drawn),+ entry,+ );+ }+}++/// The scrolling list both layouts share.+class _ResultsList extends StatelessWidget {+ const _ResultsList({required this.children});++ final List<Widget> children;++ @override+ Widget build(BuildContext context) => 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: children,+ );+}diff --git a/mobile/lib/phone/phone_search_row.dart b/mobile/lib/phone/phone_search_row.dartindex a3b207dbd..f86f0ccf0 100644--- a/mobile/lib/phone/phone_search_row.dart+++ b/mobile/lib/phone/phone_search_row.dart@@ -4,8 +4,9 @@ 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_search_rank.dart';+import 'phone_search_row_trailing.dart';import 'phone_status.dart';import 'search_result_text.dart';import 'status_pill.dart';@@ -23,6 +24,7 @@ class PhoneSearchRow extends StatefulWidget {required this.terms,required this.now,required this.onTap,+ this.placed = false,});final PhoneSearchResult row;@@ -33,6 +35,10 @@ class PhoneSearchRow extends StatefulWidget {final DateTime now;final VoidCallback onTap;+ /// Whether the row has to say where it is itself — no folder header over it,+ /// as in the Recent list. See [PhoneSearchResult.placedSubtitle].+ final bool placed;+@overrideState<PhoneSearchRow> createState() => _PhoneSearchRowState();}@@ -69,6 +75,9 @@ class _PhoneSearchRowState extends State<PhoneSearchRow> {AppTheme.watch(context);final row = widget.row;final matches = phoneResultMatches(row, widget.terms);+ // A row that is here for something said in its conversation quotes it in+ // place of its subtitle: nothing else on the row would explain the match.+ final quote = phoneRecallSnippet(row, widget.terms);return GestureDetector(behavior: HitTestBehavior.opaque,onTapDown: (_) => _press(true),@@ -109,8 +118,11 @@ class _PhoneSearchRowState extends State<PhoneSearchRow> {),const SizedBox(height: 3),SearchResultText(- row.subtitle,- matches: matches,+ quote ??+ (widget.placed ? row.placedSubtitle : row.subtitle),+ matches: quote == null+ ? matches+ : phoneRecallMatches(widget.terms),style: TextStyle(color: AppPalette.textFaint,fontSize: 12.5,@@ -119,7 +131,11 @@ class _PhoneSearchRowState extends State<PhoneSearchRow> {],),),- _Trailing(row: row, openable: _openable, now: widget.now),+ PhoneSearchTrailing(+ row: row,+ openable: _openable,+ now: widget.now,+ ),],),),@@ -168,104 +184,3 @@ class _Mark extends StatelessWidget {);}}--/// 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/phone_search_row_trailing.dart b/mobile/lib/phone/phone_search_row_trailing.dartnew file mode 100644index 000000000..466a6e06c--- /dev/null+++ b/mobile/lib/phone/phone_search_row_trailing.dart@@ -0,0 +1,111 @@+import 'package:flutter/material.dart';++import 'package:harness_mobile/shared/theme/app_theme.dart';++import 'compact_age.dart';+import 'phone_search_index.dart';+import 'phone_status.dart';+import 'status_pill.dart';++/// A search 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 PhoneSearchTrailing extends StatelessWidget {+ const PhoneSearchTrailing({+ super.key,+ 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/phone_section_label.dart b/mobile/lib/phone/phone_section_label.dartnew file mode 100644index 000000000..76b6fb02c--- /dev/null+++ b/mobile/lib/phone/phone_section_label.dart@@ -0,0 +1,34 @@+import 'package:flutter/material.dart';++import 'package:harness_mobile/shared/theme/app_theme.dart';++/// The small uppercase line over one run of a phone list — "Linked", "Recent".+class PhoneSectionLabel extends StatelessWidget {+ const PhoneSectionLabel(+ this.text, {+ super.key,+ this.padding = const EdgeInsets.fromLTRB(4, 8, 4, 8),+ });++ final String text;++ /// Lines the label up with the content under it, whose inset differs by list.+ final EdgeInsetsGeometry padding;++ @override+ Widget build(BuildContext context) {+ AppTheme.watch(context);+ return Padding(+ padding: padding,+ child: Text(+ text.toUpperCase(),+ style: TextStyle(+ color: AppPalette.textFaint,+ fontSize: 11.5,+ fontWeight: FontWeight.w600,+ letterSpacing: 0.5,+ ),+ ),+ );+ }+}diff --git a/mobile/lib/phone/search_result_text.dart b/mobile/lib/phone/search_result_text.dartindex 8d4645eb6..8f6bbbe5c 100644--- a/mobile/lib/phone/search_result_text.dart+++ b/mobile/lib/phone/search_result_text.dart@@ -3,11 +3,19 @@ import 'package:flutter/widgets.dart';import 'package:harness_mobile/core/fuzzy_match.dart';import 'phone_search_index.dart';+import 'phone_search_rank.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});+/// [terms] as matches on a recall quote (see [phoneRecallSnippet]): each term is+/// its own field, so the emphasis lands on the word wherever the quote holds it.+List<PhoneFieldMatch> phoneRecallMatches(List<String> terms) => [+ for (final term in terms.take(12).toSet())+ (field: term, term: term, title: false),+];+/// The field each term actually matched, so only that one is emphasised.////// Recomputed per visible row rather than carried through ranking: the work isdiff --git a/mobile/lib/phone/terminal_search.dart b/mobile/lib/phone/terminal_search.dartindex 4360d2098..caf5aba45 100644--- a/mobile/lib/phone/terminal_search.dart+++ b/mobile/lib/phone/terminal_search.dart@@ -5,8 +5,7 @@ import 'package:harness_mobile/shared/theme/app_theme.dart';import 'package:harness_mobile/shared/widgets/touch_target.dart';import 'package:harness_mobile/state/app_state.dart';-import 'phone_search_index.dart';-import 'phone_search_page.dart' show PhoneSearchResults;+import 'phone_search_results.dart';import 'terminal_header.dart';/// Search, opened in place over a terminal rather than pushed as a page.@@ -81,56 +80,45 @@ class _TerminalSearchOverlayState extends State<TerminalSearchOverlay> {onPopInvokedWithResult: (didPop, _) {if (!didPop) _close();},- child: ListenableBuilder(- listenable: widget.notifier,- builder: (context, _) {- final all = phoneSearchIndex(widget.notifier);- final rows = rankPhoneSearch(all, _query);- final terms = phoneSearchTerms(_query);- return Column(- children: [- // ⚠️ **The bar is NOT faded in over the header's own.** The two- // are the same shape in the same place, so cross-fading them- // looked like nothing happening at all — which is exactly what- // this screen was reported as doing. It is opaque from frame one- // and animates its WIDTH instead: Cancel opens out of the right- // edge while `+` and `⋯` collapse behind it, and the field takes- // the space. That is the move the tap promises.- _Bar(- controller: _controller,- focus: _focus,- animation: widget.animation,- onChanged: (value) => setState(() => _query = value),- onCancel: _close,- ),- // ⚠️ Fades AND rises, on the second half of the animation alone.- // Rows arriving while the bar is still opening read as two things- // at once; waiting until the bar is nearly home makes it one move- // — the bar opens, the list comes up into it.- Expanded(- child: _Rise(- animation: widget.animation,- child: ColoredBox(- color: AppPalette.windowBg,- child: PhoneSearchResults(- notifier: widget.notifier,- rows: rows,- terms: terms,- query: _query,- total: all.length,- // ⚠️ Nothing pops this search — opening an agent swaps- // the terminal underneath it instead — so tapping a row- // has to close it by hand. Without this the keyboard- // would still be up over an agent nobody asked to type- // into.- onOpen: _close,- ),- ),+ child: Column(+ children: [+ // ⚠️ **The bar is NOT faded in over the header's own.** The two+ // are the same shape in the same place, so cross-fading them+ // looked like nothing happening at all — which is exactly what+ // this screen was reported as doing. It is opaque from frame one+ // and animates its WIDTH instead: Cancel opens out of the right+ // edge while `+` and `⋯` collapse behind it, and the field takes+ // the space. That is the move the tap promises.+ _Bar(+ controller: _controller,+ focus: _focus,+ animation: widget.animation,+ onChanged: (value) => setState(() => _query = value),+ onCancel: _close,+ ),+ // ⚠️ Fades AND rises, on the second half of the animation alone.+ // Rows arriving while the bar is still opening read as two things+ // at once; waiting until the bar is nearly home makes it one move+ // — the bar opens, the list comes up into it.+ Expanded(+ child: _Rise(+ animation: widget.animation,+ child: ColoredBox(+ color: AppPalette.windowBg,+ child: PhoneSearchResults(+ notifier: widget.notifier,+ query: _query,+ // ⚠️ Nothing pops this search — opening an agent swaps+ // the terminal underneath it instead — so tapping a row+ // has to close it by hand. Without this the keyboard+ // would still be up over an agent nobody asked to type+ // into.+ onOpen: _close,),),- ],- );- },+ ),+ ),+ ],),);}diff --git a/mobile/lib/state/agent_recall.dart b/mobile/lib/state/agent_recall.dartnew file mode 100644index 000000000..94fd08693--- /dev/null+++ b/mobile/lib/state/agent_recall.dart@@ -0,0 +1,181 @@+import 'dart:async';++import 'package:flutter/foundation.dart';++/// Which agent's recent turns. Keyed on the session as well, so a `/clear` that+/// rotates it is a different conversation and is fetched again.+typedef AgentRecallKey = ({+ String machineId,+ String agentId,+ String? sessionId,+});++/// What the machine remembers of one agent's last few turns: the person's own+/// questions, then the recap of each answer.+///+/// This is what lets search find "the one I asked about llama.cpp" when nothing+/// in the agent's name, folder or title says so. The daemon already bounds it+/// (three turns, each clipped); only what a query can match and a row can quote+/// is kept here — the full answer text is dropped on arrival.+@immutable+class AgentRecall {+ AgentRecall(this.lines) : searchText = lines.join('\n').toLowerCase();++ /// Newest first, cleaned, never empty strings.+ final List<String> lines;++ /// [lines], lowercased once, for keystrokes to reuse.+ final String searchText;+}++/// How many turns to ask for, and to keep of each list — the daemon's own cap.+const _turns = 3;++/// A remembered line longer than this is clipped: the daemon's ask limit.+const _lineLimit = 1000;++/// [reply] to `agent_recent`, reduced to its searchable lines.+///+/// Asks first: the person's own words carry the topic ("which llama.cpp build+/// is this?") where a recap tends to carry the outcome.+AgentRecall parseAgentRecall(Map<String, dynamic> reply) {+ final lines = <String>{};+ final asks = reply['asks'];+ if (asks is List) {+ for (final ask in asks.take(_turns)) {+ final line = recallLine(ask);+ if (line != null) lines.add(line);+ }+ }+ final events = reply['events'];+ if (events is List) {+ for (final event in events.take(_turns)) {+ if (event is! Map || event['kind'] != 'summary') continue;+ for (final text in [event['recap'], event['text']]) {+ final line = recallLine(text);+ if (line != null) lines.add(line);+ }+ }+ }+ return AgentRecall(lines.toList());+}++/// [value] as one clean line: terminal escapes and control characters out,+/// whitespace collapsed, clipped to [_lineLimit]. Null when nothing is left.+String? recallLine(Object? value) {+ if (value is! String || value.isEmpty) return null;+ final bounded = value.length > _lineLimit * 2+ ? value.substring(0, _lineLimit * 2)+ : value;+ final text = bounded+ .replaceAll(RegExp(r'\x1b\[[0-?]*[ -/]*[@-~]'), '')+ .replaceAll(RegExp(r'[\x00-\x1f\x7f]+'), ' ')+ .replaceAll(RegExp(r'\s+'), ' ')+ .trim();+ if (text.isEmpty) return null;+ return text.length > _lineLimit ? text.substring(0, _lineLimit) : text;+}++/// A bounded memory of [AgentRecall]s, shared across every time search opens.+///+/// ⚠️ **Warmed when search opens, never per keystroke.** Typing only reads what+/// is already here, so a query on two bars of signal stays instant; the reads+/// happen once, two at a time, for the agents search offers first, and an+/// agent asked about recently is not asked again for [freshFor]. The desktop's+/// Open Agent picker warms the same `agent_recent` replies the same way.+///+/// A machine that cannot answer (an old daemon, a dropped socket) leaves its+/// agents searchable by their metadata alone — never an error on screen.+class AgentRecallStore extends ChangeNotifier {+ AgentRecallStore({+ required this.fetch,+ required this.canFetch,+ this.capacity = 128,+ this.freshFor = const Duration(minutes: 2),+ DateTime Function()? now,+ }) : _now = now ?? DateTime.now;++ final Future<Map<String, dynamic>> Function(AgentRecallKey key) fetch;++ /// Whether [key]'s machine can be asked right now.+ final bool Function(AgentRecallKey key) canFetch;+ final int capacity;+ final Duration freshFor;+ final DateTime Function() _now;++ /// How many agents one warm reaches, from the front of what it is given.+ static const maxWarm = 24;+ static const _parallel = 2;++ final _recalls = <AgentRecallKey, AgentRecall>{};+ final _attemptedAt = <AgentRecallKey, DateTime>{};+ final _queue = <AgentRecallKey>{};+ final _inFlight = <AgentRecallKey>{};+ bool _disposed = false;++ AgentRecall? read(AgentRecallKey key) => _recalls[key];++ /// Queue [keys] — most wanted first — that have not been asked about lately.+ void warm(Iterable<AgentRecallKey> keys) {+ if (_disposed) return;+ for (final key in keys.take(maxWarm)) {+ if (_inFlight.contains(key) || _askedLately(key) || !canFetch(key)) {+ continue;+ }+ _queue.add(key);+ }+ _drain();+ }++ bool _askedLately(AgentRecallKey key) {+ final at = _attemptedAt[key];+ return at != null && _now().difference(at) < freshFor;+ }++ void _drain() {+ while (!_disposed && _inFlight.length < _parallel && _queue.isNotEmpty) {+ final key = _queue.first;+ _queue.remove(key);+ if (_askedLately(key) || !canFetch(key)) continue;+ _bounded(_attemptedAt, key, _now());+ _inFlight.add(key);+ unawaited(_load(key));+ }+ }++ Future<void> _load(AgentRecallKey key) async {+ try {+ final reply = await fetch(key);+ if (_disposed || !_answers(reply, key)) return;+ _bounded(_recalls, key, parseAgentRecall(reply));+ notifyListeners();+ } on Object {+ // Searched by its metadata until the next warm after [freshFor].+ } finally {+ _inFlight.remove(key);+ _drain();+ }+ }++ static bool _answers(Map<String, dynamic> reply, AgentRecallKey key) =>+ reply['error'] == null &&+ (reply['agentId'] == null || reply['agentId'] == key.agentId);++ /// Writes [key] as the newest entry of [map], dropping the oldest past+ /// [capacity].+ void _bounded<V>(Map<AgentRecallKey, V> map, AgentRecallKey key, V value) {+ map+ ..remove(key)+ ..[key] = value;+ while (map.length > capacity) {+ map.remove(map.keys.first);+ }+ }++ @override+ void dispose() {+ _disposed = true;+ _queue.clear();+ super.dispose();+ }+}diff --git a/mobile/lib/state/app_state.dart b/mobile/lib/state/app_state.dartindex e931db02f..aff7df995 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -34,6 +34,7 @@ import '../stats/harness_stats.dart';import '../terminal/terminal_session.dart';import '../terminal/remote_media_download.dart';import '../widgets/engine_identity.dart' show allEngines;+import 'agent_recall.dart';import 'dial_status.dart';import 'pane_layout_store.dart';import 'terminal_pane.dart';@@ -330,6 +331,26 @@ class AppNotifier extends ChangeNotifier {final WsConn Function(String machineId)? connectionForTest;final Map<String, Timer> _turnActivityWatchdogs = {};+ /// Each agent's last few turns, as search matches them — see [AgentRecallStore].+ ///+ /// Asks only a machine this app is already connected to, and never dials one:+ /// warming search must not be what wakes a relay socket.+ late final AgentRecallStore agentRecall = AgentRecallStore(+ fetch: (key) => _conn(key.machineId).request(+ 'agent_recent',+ payload: {'agentId': key.agentId, 'n': 3},+ timeout: const Duration(seconds: 6),+ ),+ canFetch: (key) =>+ !_disposed &&+ (_pool != null || connectionForTest != null) &&+ machineStates[key.machineId]?.connectionStatus ==+ ConnectionStatus.connected,+ );++ AgentRecallKey agentRecallKey(String machineId, Agent agent) =>+ (machineId: machineId, agentId: agent.id, sessionId: agent.sessionId);+/// When this launch became signed in, and by which route — until the first/// message of that session has been reported, after which it is null.///@@ -5792,6 +5813,7 @@ class AppNotifier extends ChangeNotifier {swarm.panes.clear();}unawaited(_spokenTasks.close());+ agentRecall.dispose();super.dispose();}}diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dartindex 5503e65f9..2673eda11 100644--- a/mobile/lib/widgets/terminal_panel.dart+++ b/mobile/lib/widgets/terminal_panel.dart@@ -7,7 +7,6 @@ import 'package:flutter/services.dart';import 'package:xterm/xterm.dart';import '../clipboard/native_clipboard.dart';-import '../core/host_platform.dart';import '../state/app_state.dart';import 'agent_drag.dart';@@ -1399,11 +1398,16 @@ class _TerminalPanelState extends State<TerminalPanel>// iOS answers Backspace over an empty native buffer// with nothing at all (`deleteBackward` in// FlutterTextInputPlugin.mm), so a line the keyboard- // did not type — a voice transcript, a recalled- // command — could not be rubbed out. xterm keeps a- // padding for Backspace to eat instead — see- // test/terminal_ime_input_test.dart.- deleteDetection: isMobileHost,+ // did not type — text typed on the desktop, a voice+ // transcript, a recalled command — could not be+ // rubbed out. xterm keeps a padding for Backspace to+ // eat instead — see test/terminal_ime_input_test.dart.+ //+ // Unconditional: this package builds for iOS and+ // Android only. ⚠️ Lost once already in a merge+ // (cb47ba35 → TestFlight build 11), which is why+ // test/terminal_panel_backspace_test.dart pins it.+ deleteDetection: true,theme: terminalThemeFor(grid.AppTheme.palette.value,terminalThemeStore.value,diff --git a/mobile/test/keyboard_fakes.dart b/mobile/test/keyboard_fakes.dartnew file mode 100644index 000000000..57aa20a20--- /dev/null+++ b/mobile/test/keyboard_fakes.dart@@ -0,0 +1,18 @@+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';++/// What UIKit's `deleteBackward` does to the buffer it holds: one character+/// fewer, and NOTHING at all once the buffer is empty. Android's+/// `deleteSurroundingText` reaches Dart the same way, as an edited buffer.+Future<void> deleteBackward(WidgetTester tester) async {+ final text = tester.testTextInput.editingState!['text'] as String;+ if (text.isEmpty) return;+ final left = text.substring(0, text.length - 1);+ tester.testTextInput.updateEditingValue(+ TextEditingValue(+ text: left,+ selection: TextSelection.collapsed(offset: left.length),+ ),+ );+ await tester.pump();+}diff --git a/mobile/test/phone_search_test.dart b/mobile/test/phone_search_test.dartindex 85faf87ef..ab5b653f6 100644--- a/mobile/test/phone_search_test.dart+++ b/mobile/test/phone_search_test.dart@@ -1,3 +1,5 @@+import 'dart:async';+import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/auth/auth_session.dart';@@ -9,8 +11,11 @@ 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/phone/phone_search_rank.dart';+import 'package:harness_mobile/state/agent_recall.dart';import 'package:harness_mobile/state/app_state.dart';import 'package:harness_mobile/state/pending_question.dart';+import 'package:harness_mobile/ws/ws_conn.dart';final _now = DateTime.now();@@ -20,11 +25,15 @@ Agent _agent(String cwd = '/srv/work',int? minutesAgo,bool terminal = true,+ String? gridModel,+ String? dshName,}) => Agent(id: id,name: 'work · $id',title: title,engine: 'codex',+ gridModel: gridModel,+ dshName: dshName,project: AgentProject(name: 'work', cwd: cwd),updatedAt: minutesAgo == null? null@@ -53,11 +62,12 @@ void _markWaiting(MachineState machine, String agentId) =>since: _now,);-AppNotifier _app(List<MachineState> machines) {+AppNotifier _app(List<MachineState> machines, {WsConn? conn}) {final app = AppNotifier(config: AppConfig.dev,authSession: AuthSession(),configStore: null,+ connectionForTest: conn == null ? null : (_) => conn,);app.machines = [for (final state in machines) state.machine];for (final state in machines) {@@ -66,6 +76,43 @@ AppNotifier _app(List<MachineState> machines) {return app;}+/// A machine that remembers what was asked of each agent, and answers nothing else.+class _RecallConn extends WsConn {+ _RecallConn(this.asks)+ : super(+ wsBaseUrl: 'ws://fixture.invalid',+ autonomousEnv: 'test',+ machineId: 'box',+ accessTokenProvider: (_, _) async => '',+ onAuthFailure: (_) {},+ onEvent: (_) {},+ onStatus: (_) {},+ );++ /// Agent id → the person's recent questions to it, newest first.+ final Map<String, List<String>> asks;+ final asked = <String>[];++ @override+ Future<Map<String, dynamic>> request(+ String type, {+ Map<String, dynamic> payload = const {},+ Duration timeout = const Duration(seconds: 20),+ }) async {+ if (type != 'agent_recent') return {'error': 'UNEXPECTED'};+ final agentId = payload['agentId'] as String;+ asked.add(agentId);+ return {'agentId': agentId, 'events': const [], 'asks': asks[agentId]};+ }+}++/// Lets every in-flight recall reply land.+Future<void> _settle() async {+ for (var i = 0; i < 8; i++) {+ await Future<void>.delayed(Duration.zero);+ }+}+List<String> _agentIds(List<PhoneSearchResult> rows) => [for (final row in rows)if (row.entry != null) row.entry!.agent.id,@@ -85,6 +132,20 @@ void main() {expect(agent.copyWith(name: 'x').updatedAt, agent.updatedAt);});+ test('reads what it runs on and what it was made as', () {+ final agent = Agent.fromJson({+ 'id': 'a',+ 'grid': {'baseUrl': 'http://grid', 'model': 'llama-3.1-8b-q4'},+ 'selectedModel': 'gpt-5-codex',+ 'dshName': 'Model manager',+ });+ expect(agent.gridModel, 'llama-3.1-8b-q4');+ expect(agent.selectedModel, 'gpt-5-codex');+ expect(agent.dshName, 'Model manager');+ expect(agent.copyWith(name: 'x').gridModel, agent.gridModel);+ expect(Agent.fromJson({'id': 'a', 'grid': null}).gridModel, isNull);+ });+test('an older daemon, or garbage, leaves both unknown', () {final agent = Agent.fromJson({'id': 'a',@@ -154,6 +215,20 @@ void main() {]);});+ test('what it runs on finds it: a grid model, a harness name', () {+ final models = _app([+ _machine('box', [+ _agent('1111', minutesAgo: 1),+ _agent('2222', gridModel: 'llama-3.1-8b-q4', minutesAgo: 9),+ _agent('3333', dshName: 'Model manager', minutesAgo: 30),+ ]),+ ]);+ addTearDown(models.dispose);+ final all = phoneSearchIndex(models);+ expect(_agentIds(rankPhoneSearch(all, 'llama')), ['2222']);+ expect(_agentIds(rankPhoneSearch(all, 'model manager')), ['3333']);+ });+test('the best match is the first row of the first group', () {final ranked = rankPhoneSearch(phoneSearchIndex(app), '2312');final groups = phoneSearchGroups(ranked);@@ -162,6 +237,104 @@ void main() {});});+ group('recall', () {+ test('asks first, then each recap; cleaned, deduped, summaries only', () {+ final recall = parseAgentRecall({+ 'asks': ['which \x1b[1mllama.cpp\x1b[0m build\nis this?', ''],+ 'events': [+ {+ 'kind': 'summary',+ 'recap': 'Pinned llama.cpp b4521',+ 'text': 'Pinned llama.cpp b4521',+ },+ {'kind': 'tool', 'text': 'ls -la'},+ 'garbage',+ ],+ });+ expect(recall.lines, [+ 'which llama.cpp build is this?',+ 'Pinned llama.cpp b4521',+ ]);+ expect(recall.searchText, contains('b4521'));+ });++ test(+ 'warms two at a time, never re-asks lately, survives failures',+ () async {+ final pending = <String, Completer<Map<String, dynamic>>>{};+ var now = DateTime(2026, 9, 18, 9);+ final store = AgentRecallStore(+ fetch: (key) => (pending[key.agentId] = Completer()).future,+ canFetch: (key) => key.machineId != 'offline',+ now: () => now,+ );+ addTearDown(store.dispose);+ AgentRecallKey key(String agentId, [String machineId = 'box']) =>+ (machineId: machineId, agentId: agentId, sessionId: null);++ store.warm([key('a'), key('b'), key('c'), key('x', 'offline')]);+ expect(pending.keys, ['a', 'b']);++ pending['a']!.complete({+ 'agentId': 'a',+ 'asks': ['llama?'],+ });+ pending['b']!.completeError(StateError('socket dropped'));+ await _settle();+ expect(pending.keys, ['a', 'b', 'c']);+ expect(store.read(key('a'))!.lines, ['llama?']);+ expect(store.read(key('b')), isNull);+ pending['c']!.complete({'agentId': 'c', 'asks': const []});+ await _settle();++ pending.clear();+ store.warm([key('a'), key('b')]);+ expect(+ pending,+ isEmpty,+ reason: 'both were asked less than freshFor ago',+ );+ now = now.add(const Duration(minutes: 3));+ store.warm([key('a'), key('b')]);+ expect(pending.keys, ['a', 'b']);+ },+ );++ test(+ 'a word only said to an agent finds it, after every field match',+ () async {+ final conn = _RecallConn({+ 'said': ['which llama.cpp build is running?'],+ 'quiet': ['fix the login redirect'],+ });+ final app = _app([+ _machine('box', [+ _agent('said', minutesAgo: 1),+ _agent('quiet', minutesAgo: 2),+ _agent('named', gridModel: 'llama-3.1-8b', minutesAgo: 30),+ ]),+ ], conn: conn);+ addTearDown(app.dispose);+ expect(_agentIds(rankPhoneSearch(phoneSearchIndex(app), 'llama')), [+ 'named',+ ]);++ app.agentRecall.warm([+ for (final agent in app.machineStates['box']!.agents)+ app.agentRecallKey('box', agent),+ ]);+ await _settle();+ final ranked = rankPhoneSearch(phoneSearchIndex(app), 'llama');+ expect(_agentIds(ranked), ['named', 'said']);+ expect(phoneRecallSnippet(ranked.first, ['llama']), isNull);+ expect(+ phoneRecallSnippet(ranked.last, ['llama']),+ 'which llama.cpp build is running?',+ );+ },+ );+ });+test('compactAge', () {final now = DateTime(2026, 9, 17, 12);String ago(Duration age) => compactAge(now.subtract(age), now);@@ -174,34 +347,66 @@ void main() {expect(compactAge(now.add(const Duration(minutes: 5)), now), 'now');});- testWidgets('the page draws folders, the work and how fresh it is', (+ testWidgets('before a word: one Recent run, newest first, each row placed', (tester,) async {final app = _app([_machine('box', [_agent('3188', title: 'Fix login redirect', minutesAgo: 4),_agent('2312', cwd: '/srv/node', minutesAgo: 30),+ _agent('9999', minutesAgo: 90),]),]);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('RECENT'), findsOneWidget);+ expect(find.byType(PhoneSearchFolderHeader), findsNothing);+ expect(find.text('Fix login redirect · work · box'), findsOneWidget);+ expect(find.text('node · box'), 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),- );+ double top(String name) => tester.getTopLeft(find.text(name)).dy;+ // The fresh `work` agent, then `node`, then the stale `work` one: a folder+ // does not pull its old agent up past a fresher one elsewhere.+ expect(top('work · 3188'), lessThan(top('work · 2312')));+ expect(top('work · 2312'), lessThan(top('work · 9999')));await tester.enterText(find.byType(TextField), 'login');await tester.pump();+ expect(find.text('RECENT'), findsNothing);expect(find.text('work · 2312'), findsNothing);expect(find.byType(PhoneSearchFolderHeader), findsOneWidget);});+ testWidgets('opening search asks for recall; the matching line is quoted', (+ tester,+ ) async {+ final conn = _RecallConn({+ '3188': ['which llama.cpp build is running?'],+ });+ final app = _app([+ _machine('box', [+ _agent('3188', minutesAgo: 4),+ _agent('2312', minutesAgo: 30),+ ]),+ ], conn: conn);+ addTearDown(app.dispose);+ await tester.pumpWidget(MaterialApp(home: PhoneSearchPage(notifier: app)));+ await tester.pump();+ expect(conn.asked, ['3188', '2312']);++ await tester.enterText(find.byType(TextField), 'llama');+ await tester.pump();+ expect(find.text('work · 3188'), findsOneWidget);+ expect(find.text('work · 2312'), findsNothing);+ expect(+ find.text('which llama.cpp build is running?', findRichText: true),+ findsOneWidget,+ );+ });+testWidgets('one bar: no Cancel beside it, and its chevron closes search', (tester,) async {diff --git a/mobile/test/terminal_ime_input_test.dart b/mobile/test/terminal_ime_input_test.dartindex a4c67d56e..8aa060211 100644--- a/mobile/test/terminal_ime_input_test.dart+++ b/mobile/test/terminal_ime_input_test.dart@@ -3,6 +3,8 @@ import 'package:flutter/services.dart';import 'package:flutter_test/flutter_test.dart';import 'package:xterm/xterm.dart';+import 'keyboard_fakes.dart';+/// The phone has no composer box under its pane — see `phone/terminal_page.dart`/// — so the terminal's own input connection is the only place a software/// keyboard has to compose in. Whatever this config says, a Vietnamese Telex or@@ -136,21 +138,6 @@ void main() {);group('with delete detection, as a phone runs it', () {- /// What UIKit's `deleteBackward` does to the buffer it holds: one character- /// fewer, and NOTHING at all once the buffer is empty.- Future<void> deleteBackward(WidgetTester tester) async {- final text = tester.testTextInput.editingState!['text'] as String;- if (text.isEmpty) return;- final left = text.substring(0, text.length - 1);- tester.testTextInput.updateEditingValue(- TextEditingValue(- text: left,- selection: TextSelection.collapsed(offset: left.length),- ),- );- await tester.pump();- }-testWidgets('Backspace keeps rubbing out a line the keyboard never typed', (tester,) async {diff --git a/mobile/test/terminal_panel_backspace_test.dart b/mobile/test/terminal_panel_backspace_test.dartnew file mode 100644index 000000000..1e9d6ae7f--- /dev/null+++ b/mobile/test/terminal_panel_backspace_test.dart@@ -0,0 +1,101 @@+import 'package:flutter/gestures.dart';+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/widgets/terminal_panel.dart';+import 'package:xterm/xterm.dart';++import 'keyboard_fakes.dart';+import 'terminal_panel_fixture.dart';++/// Text typed on the desktop sits in the agent's prompt, and this phone's+/// keyboard never typed it: its buffer holds nothing of that line. Backspace on+/// the phone still has to reach the pty, or the line can only be erased from the+/// desktop.+///+/// TestFlight build 11 shipped without that — a merge (cb47ba35) had dropped+/// the panel's `deleteDetection`, and iOS answers Backspace over an empty+/// buffer with nothing at all. `terminal_ime_input_test.dart` covers xterm's+/// side; this pins the panel actually asking for it.+void main() {+ const erased = [0x7f, 0x7f, 0x7f, 0x7f, 0x7f];++ /// Opens a pane over a prompt the desktop typed into and raises the keyboard+ /// on it. Returns the bytes the pane puts on the wire.+ ///+ /// ⚠️ Built here, not in `setUp`: the session's send queue is a Future, and+ /// one made outside the test's fake clock never drains inside it.+ Future<List<int>> raiseKeyboard(WidgetTester tester) async {+ final wire = <int>[];+ final notifier = panelNotifier();+ final session = controllingSession(+ sendBinary: (frame) async {+ wire.addAll(frame.bytes);+ return true;+ },+ );+ addTearDown(notifier.dispose);+ addTearDown(session.dispose);+ // What the desktop typed, as the phone sees it: output, not keystrokes.+ session.terminal.write('> fssss');++ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: SizedBox(+ width: 400,+ height: 320,+ child: TerminalPanel(+ notifier: notifier,+ session: session,+ focused: false,+ showHeader: false,+ ),+ ),+ ),+ ),+ );+ await tester.tap(find.byType(TerminalView));+ // Past the double-tap window, which is what holds a single tap back.+ await tester.pump(kDoubleTapTimeout);+ expect(tester.testTextInput.hasAnyClients, isTrue);+ return wire;+ }++ /// Past the session's input coalescing, so every key is on the wire.+ Future<void> flushInput(WidgetTester tester) =>+ tester.pump(const Duration(milliseconds: 50));++ testWidgets(+ 'Backspace as an edit to the keyboard\'s buffer erases the desktop\'s text',+ (tester) async {+ final wire = await raiseKeyboard(tester);++ for (var press = 0; press < erased.length; press++) {+ await deleteBackward(tester);+ }+ await flushInput(tester);++ expect(wire, erased);+ },+ variant: TargetPlatformVariant({+ TargetPlatform.iOS,+ TargetPlatform.android,+ }),+ );++ testWidgets(+ 'Backspace as a key, the way Gboard sends it, erases the desktop\'s text',+ (tester) async {+ final wire = await raiseKeyboard(tester);++ for (var press = 0; press < erased.length; press++) {+ await tester.sendKeyEvent(LogicalKeyboardKey.backspace);+ }+ await flushInput(tester);++ expect(wire, erased);+ },+ variant: TargetPlatformVariant.only(TargetPlatform.android),+ );+}diff --git a/mobile/test/terminal_panel_fixture.dart b/mobile/test/terminal_panel_fixture.dartnew file mode 100644index 000000000..5de53c208--- /dev/null+++ b/mobile/test/terminal_panel_fixture.dart@@ -0,0 +1,28 @@+import 'package:harness_mobile/auth/auth_session.dart';+import 'package:harness_mobile/core/config.dart';+import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/terminal/terminal_session.dart';++/// The notifier a lone `TerminalPanel` hangs off: no machines, no stored config.+AppNotifier panelNotifier() => AppNotifier(+ config: AppConfig.dev,+ authSession: AuthSession(),+ configStore: null,+);++/// A session already controlling its stream, so the pane takes input. Every+/// frame is accepted unless the test listens for it.+TerminalSession controllingSession({+ TerminalFrameSender? send,+ TerminalBinarySender? sendBinary,+}) =>+ TerminalSession(+ machineId: 'm',+ agentId: 'a',+ agentName: 'Agent',+ engineId: 'claude',+ send: send ?? (_, _) async => true,+ sendBinary: sendBinary ?? (_) async => true,+ )+ ..status = TerminalSessionStatus.controlling+ ..streamId = 's';diff --git a/mobile/test/terminal_panel_input_tap_test.dart b/mobile/test/terminal_panel_input_tap_test.dartindex bf09e2afd..e53741e3d 100644--- a/mobile/test/terminal_panel_input_tap_test.dart+++ b/mobile/test/terminal_panel_input_tap_test.dart@@ -1,13 +1,13 @@import 'package:flutter/gestures.dart';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/state/app_state.dart';import 'package:harness_mobile/terminal/terminal_session.dart';import 'package:harness_mobile/widgets/terminal_panel.dart';import 'package:xterm/xterm.dart';+import 'terminal_panel_fixture.dart';+/// On the phone the page decides what a tap on the terminal does — it types/// what the mic heard into the prompt before it raises the keyboard. The panel/// is where that tap is taken: xterm would otherwise raise the keyboard itself@@ -18,21 +18,8 @@ void main() {late int inputTaps;setUp(() {- notifier = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- );- session = TerminalSession(- machineId: 'm',- agentId: 'a',- agentName: 'Agent',- engineId: 'claude',- send: (_, _) async => true,- sendBinary: (_) async => true,- );- session.status = TerminalSessionStatus.controlling;- session.streamId = 's';+ notifier = panelNotifier();+ session = controllingSession();inputTaps = 0;});diff --git a/mobile/test/terminal_panel_render_test.dart b/mobile/test/terminal_panel_render_test.dartindex 290f9beb4..3de28a851 100644--- a/mobile/test/terminal_panel_render_test.dart+++ b/mobile/test/terminal_panel_render_test.dart@@ -1,12 +1,12 @@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/state/app_state.dart';import 'package:harness_mobile/terminal/terminal_session.dart';import 'package:harness_mobile/widgets/terminal_panel.dart';import 'package:xterm/xterm.dart';+import 'terminal_panel_fixture.dart';+/// What a phone terminal draws while it is not the page being read, or while/// the keyboard is still sliding.///@@ -20,25 +20,14 @@ void main() {late List<Map<String, dynamic>> resizes;setUp(() {- notifier = AppNotifier(- config: AppConfig.dev,- authSession: AuthSession(),- configStore: null,- );+ notifier = panelNotifier();resizes = [];- session = TerminalSession(- machineId: 'm',- agentId: 'a',- agentName: 'Agent',- engineId: 'claude',+ session = controllingSession(send: (type, payload) async {if (type == 'terminal_resize') resizes.add(payload);return true;},- sendBinary: (_) async => true,);- session.status = TerminalSessionStatus.controlling;- session.streamId = 's';for (var line = 0; line < 200; line++) {session.terminal.write('output line $line\r\n');}