The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
feat: Introduce SessionPreview and SessionPreviewStore for managing session content on mobile
Dev jacobcea604fe5d92
diff --git a/mobile/android/app/src/main/AndroidManifest.xml b/mobile/android/app/src/main/AndroidManifest.xmlindex 9257336e7..74b46c7ed 100644--- a/mobile/android/app/src/main/AndroidManifest.xml+++ b/mobile/android/app/src/main/AndroidManifest.xml@@ -24,7 +24,7 @@<uses-permission android:name="android.permission.RECORD_AUDIO" /><uses-feature android:name="android.hardware.microphone" android:required="false" /><application- android:label="harness"+ android:label="OpenHarness"android:name="${applicationName}"android:icon="@mipmap/ic_launcher"><activitydiff --git a/mobile/ios/Runner/Info.plist b/mobile/ios/Runner/Info.plistindex bca31ae23..e9ef9fa81 100644--- a/mobile/ios/Runner/Info.plist+++ b/mobile/ios/Runner/Info.plist@@ -7,7 +7,7 @@<key>CFBundleDevelopmentRegion</key><string>$(DEVELOPMENT_LANGUAGE)</string><key>CFBundleDisplayName</key>- <string>Harness</string>+ <string>OpenHarness</string><key>CFBundleExecutable</key><string>$(EXECUTABLE_NAME)</string><key>CFBundleIdentifier</key>diff --git a/mobile/lib/app_shell.dart b/mobile/lib/app_shell.dartindex b61cdd1ff..7546dc201 100644--- a/mobile/lib/app_shell.dart+++ b/mobile/lib/app_shell.dart@@ -107,7 +107,7 @@ class HarnessApp extends StatelessWidget {codeSize: grid.AppFont.codeSize,);return MaterialApp(- title: 'Harness',+ title: 'OpenHarness',// The corner ribbon stays. A phone carries both builds under one icon and// one name, and telling them apart otherwise means reading `dumpsys` over// a cable — by which point a bug has already been reported against thediff --git a/mobile/lib/bootstrap/environment_provisioner.dart b/mobile/lib/bootstrap/environment_provisioner.dartindex 54855408d..45e937500 100644--- a/mobile/lib/bootstrap/environment_provisioner.dart+++ b/mobile/lib/bootstrap/environment_provisioner.dart@@ -1,4 +1,5 @@import '../core/host_platform.dart';+import 'dart:async';import 'dart:convert';import 'dart:io';@@ -482,7 +483,7 @@ class EnvironmentProvisioner {if (!await _hasWritableHome()) {systemFailure = const EnvironmentFailure(title: 'Home directory is not writable',- detail: 'Harness needs to write ~/.harness and ~/.local/bin.',+ detail: 'OpenHarness needs to write ~/.harness and ~/.local/bin.',);} else {linuxMissingBasePackages = await _missingLinuxBasePackages();@@ -626,7 +627,7 @@ class EnvironmentProvisioner {emit(message: _isLinux && linuxMissingPackages.isNotEmpty? 'Linux host packages required: ${linuxMissingPackages.join(', ')}.'- : 'Review what Harness will install before continuing.',+ : 'Review what OpenHarness will install before continuing.',phase: EnvironmentSetupPhase.review,);return state;@@ -778,7 +779,7 @@ class EnvironmentProvisioner {);}emit(- message: 'Complete the visible Linux package prompts in Terminal. Harness never sees your password.',+ message: 'Complete the visible Linux package prompts in Terminal. OpenHarness never sees your password.',output: backgroundInstall == null? 'Terminal opened to install Linux host dependencies.': 'Background install was incomplete; Terminal opened to finish Linux host dependencies.',@@ -835,7 +836,7 @@ class EnvironmentProvisioner {emit(step: EnvironmentStep.tmux,status: EnvironmentStepStatus.needsTerminal,- message: 'Complete the visible Homebrew prompts in Terminal. Harness never sees your password.',+ message: 'Complete the visible Homebrew prompts in Terminal. OpenHarness never sees your password.',output: 'Background install failed; Terminal opened to retry tmux.',phase: EnvironmentSetupPhase.waitingForTerminal,terminalLogPath: terminal.log.path,@@ -854,7 +855,7 @@ class EnvironmentProvisioner {emit(step: EnvironmentStep.tmux,status: EnvironmentStepStatus.needsTerminal,- message: 'Complete any password or macOS prompts in Terminal. Harness never sees your password.',+ message: 'Complete any password or macOS prompts in Terminal. OpenHarness never sees your password.',output: _isMacOS? 'Terminal opened to install Homebrew and tmux.': 'Terminal opened to install tmux.',@@ -1019,7 +1020,7 @@ class EnvironmentProvisioner {return EnvironmentFailure(title: 'Required system tools are missing',detail: _resultText(base).isEmpty- ? 'Harness needs curl, tar, sed, awk, checksum tools and a POSIX shell.'+ ? 'OpenHarness needs curl, tar, sed, awk, checksum tools and a POSIX shell.': _resultText(base),command: _isMacOS? 'xcode-select --install'@@ -1029,7 +1030,7 @@ class EnvironmentProvisioner {if (!await _hasWritableHome()) {return const EnvironmentFailure(title: 'Home directory is not writable',- detail: 'Harness needs to write ~/.harness and ~/.local/bin.',+ detail: 'OpenHarness needs to write ~/.harness and ~/.local/bin.',);}return null;@@ -1136,7 +1137,7 @@ class EnvironmentProvisioner {if (exitCode == _linuxAptUpdateFailureExitCode) {return const EnvironmentFailure(title: 'Package repository refresh failed',- detail: 'Ubuntu could not refresh its package indexes, so Harness stopped instead of retrying with stale package data.',+ detail: 'Ubuntu could not refresh its package indexes, so OpenHarness stopped instead of retrying with stale package data.',command: 'sudo apt-get update',exitCode: _linuxAptUpdateFailureExitCode,);@@ -1228,7 +1229,7 @@ refresh_package_indexes() {return 0firm -f "\$apt_update_log"- echo 'Package repository refresh failed. Harness will not retry with stale package indexes.' >&2+ echo 'Package repository refresh failed. OpenHarness will not retry with stale package indexes.' >&2return $_linuxAptUpdateFailureExitCode}install_linux_packages() {@@ -1390,7 +1391,7 @@ finish() {printf '%s\\n' "\$status" > "\$RESULT_FILE"if [ "\$status" -ne 0 ]; thenecho- echo 'System setup failed. Review the error above, then return to Harness.'+ echo 'System setup failed. Review the error above, then return to OpenHarness.'read -r '?Press Enter to close this window…' || truefireturn "\$status"@@ -1427,7 +1428,7 @@ eval "\$(/opt/homebrew/bin/brew shellenv 2>/dev/null || /usr/local/bin/brew shelif ! command -v tmux >/dev/null 2>&1; thenbrew install tmuxfi-echo 'tmux is ready. Return to Harness.'+echo 'tmux is ready. Return to OpenHarness.'''', flush: true);await _run('/bin/chmod', ['700', script.path]);return script;diff --git a/mobile/lib/phone/agent_home.dart b/mobile/lib/phone/agent_home.dartindex a0bef83f5..80c1cac73 100644--- a/mobile/lib/phone/agent_home.dart+++ b/mobile/lib/phone/agent_home.dart@@ -820,7 +820,7 @@ class _AgentHomeEmpty extends StatelessWidget {icon: LucideIcons.squareTerminal300,title: 'No agents yet',message:- 'Tap + to start one, or launch an agent from Harness on a '+ 'Tap + to start one, or launch an agent from OpenHarness on a ''machine and it will appear here.',),),diff --git a/mobile/lib/phone/agent_index.dart b/mobile/lib/phone/agent_index.dartindex d5b9691ac..7c1c3d50f 100644--- a/mobile/lib/phone/agent_index.dart+++ b/mobile/lib/phone/agent_index.dart@@ -28,6 +28,16 @@ class AgentEntry {bool get isWorking => machine.processingAgentIds.contains(agent.id);+ /// When its conversation last moved: the machine's own [Agent.updatedAt], or+ /// a turn this app saw since ([MachineState.agentActivityAt]) — whichever is+ /// later. Null when neither is known.+ DateTime? get lastActiveAt {+ final reported = agent.updatedAt;+ final seen = machine.agentActivityAt[agent.id];+ if (reported == null || seen == null) return seen ?? reported;+ return seen.isAfter(reported) ? seen : reported;+ }+PhoneSummary get summary => phoneAgentSummary(machine, agent);}@@ -82,15 +92,15 @@ List<AgentEntry> otherAgents(List<AgentEntry> entries) =>////// The recency is what the tabs deliberately do NOT sort on — a list somebody browses must not/// reshuffle — but a search is opened to reach one agent and closed again, and the agent somebody-/// reaches for is overwhelmingly the one that just finished. Agents from a daemon too old to send-/// [Agent.updatedAt] keep their index order after every dated one.+/// reaches for is overwhelmingly the one that just finished — see [AgentEntry.lastActiveAt]. Agents+/// with no date at all keep their index order after every dated one.List<AgentEntry> recentAgents(List<AgentEntry> entries) => _stableSorted(entries,(a, b) =>_firstWhere(a.isWaiting, b.isWaiting) ??_firstWhere(a.isWorking, b.isWorking) ??_firstWhere(a.agent.terminalAvailable, b.agent.terminalAvailable) ??- _newestFirst(a.agent.updatedAt, b.agent.updatedAt),+ _newestFirst(a.lastActiveAt, b.lastActiveAt),);/// -1 when only [a] holds, 1 when only [b] does, null on a tie — so comparators chain with `??`.diff --git a/mobile/lib/phone/agents_page.dart b/mobile/lib/phone/agents_page.dartindex b8c87d788..849681c1d 100644--- a/mobile/lib/phone/agents_page.dart+++ b/mobile/lib/phone/agents_page.dart@@ -220,9 +220,9 @@ class _AgentsBody extends StatelessWidget {if (status == PhoneMachineStatus.offline) {return EmptyState(icon: LucideIcons.cloudOff300,- title: "Harness isn't running there",+ title: "OpenHarness isn't running there",message:- 'Start Harness on ${machine.machine.displayName} and its agents '+ 'Start OpenHarness on ${machine.machine.displayName} and its agents ''will show up here.',);}@@ -245,7 +245,7 @@ class _AgentsBody extends StatelessWidget {return EmptyState(icon: LucideIcons.squareTerminal300,title: 'No agents yet',- message: 'Start one here, or from Harness on that machine.',+ message: 'Start one here, or from OpenHarness on that machine.',action: FilledButton(onPressed: () => openNewAgent(context, notifier, _machineId),child: const Text('New agent'),diff --git a/mobile/lib/phone/composing_keyboard.dart b/mobile/lib/phone/composing_keyboard.dartnew file mode 100644index 000000000..56d2228fa--- /dev/null+++ b/mobile/lib/phone/composing_keyboard.dart@@ -0,0 +1,21 @@+import 'package:flutter/foundation.dart';++/// The keyboard flags a free-text field on a phone needs for the keyboard's+/// input method to compose — Vietnamese Telex, a CJK candidate window.+///+/// On a phone the software keyboard IS the input method, and the two switches a+/// query field instinctively turns off are what take its pre-edit buffer away:+/// iOS maps `autocorrect: false` onto `UITextAutocorrectionTypeNo`, the same+/// machinery its Telex conversion rides on, and Android maps+/// `enableSuggestions: false` onto `TYPE_TEXT_FLAG_NO_SUGGESTIONS`. With either+/// set, `thoiwf tieets` reached search as raw letters instead of `thời tiết`.+///+/// The same policy the terminal's input keeps (see `custom_text_edit.dart` in+/// `third_party/xterm`). ⚠️ The price is on iOS: it has no finer switch, so+/// autocorrection is on there and may rewrite a word at the space bar — the+/// keyboard offers the original back. Android keeps autocorrect off.+abstract final class ComposingKeyboard {+ static bool get autocorrect => defaultTargetPlatform == TargetPlatform.iOS;++ static const enableSuggestions = true;+}diff --git a/mobile/lib/phone/machines_tab.dart b/mobile/lib/phone/machines_tab.dartindex 58cc7ced1..3986b4d28 100644--- a/mobile/lib/phone/machines_tab.dart+++ b/mobile/lib/phone/machines_tab.dart@@ -102,7 +102,7 @@ class _Body extends StatelessWidget {icon: LucideIcons.laptopMinimal300,title: 'No machines yet',message:- 'Run Harness on a computer signed in to this account and it will '+ 'Run OpenHarness on a computer signed in to this account and it will ''appear here.',);}diff --git a/mobile/lib/phone/new_agent_page.dart b/mobile/lib/phone/new_agent_page.dartindex 3687aa8e7..22a76c6cb 100644--- a/mobile/lib/phone/new_agent_page.dart+++ b/mobile/lib/phone/new_agent_page.dart@@ -190,7 +190,7 @@ class _NewAgentPageState extends State<NewAgentPage> {/// Why the two rows are unavailable, or null while they are not.///- /// Printed rather than left to a disabled row: "Update Harness on that machine" is something the+ /// Printed rather than left to a disabled row: "Update OpenHarness on that machine" is something the/// person can act on, and a row that simply does nothing teaches them nothing.String? get _projectSourceNote {final machine = _machine;@@ -198,7 +198,7 @@ class _NewAgentPageState extends State<NewAgentPage> {// Said only once the machine has actually answered. Before that, silence — a row must not call// a machine out of date on the strength of an answer that has not arrived.if (!machine.terminalCapabilityLoaded) return null;- return 'Update Harness on ${machine.machine.displayName} to create a '+ return 'Update OpenHarness on ${machine.machine.displayName} to create a ''project or clone one there.';}diff --git a/mobile/lib/phone/phone_search_field.dart b/mobile/lib/phone/phone_search_field.dartindex 0f7acf26a..50cf38c05 100644--- a/mobile/lib/phone/phone_search_field.dart+++ b/mobile/lib/phone/phone_search_field.dart@@ -3,6 +3,8 @@ import 'package:lucide_icons_flutter/lucide_icons.dart';import 'package:harness_mobile/shared/theme/app_theme.dart';+import 'composing_keyboard.dart';+/// The search page's whole header: one bar, with the way out inside it.////// Drawn here rather than through [PhoneHeader]: the page has no title. The@@ -131,8 +133,13 @@ class _QueryInput extends StatelessWidget {// that drops the keyboard and leaves the results up.textInputAction: TextInputAction.search,onSubmitted: (_) => focus.unfocus(),- autocorrect: false,- enableSuggestions: false,+ // Composing stays on — or Telex types `thoi tiet` for `thời tiết`. See+ // [ComposingKeyboard]; with autocorrect on, iOS would also start curling+ // quotes and joining dashes, which a query means literally.+ autocorrect: ComposingKeyboard.autocorrect,+ enableSuggestions: ComposingKeyboard.enableSuggestions,+ smartDashesType: SmartDashesType.disabled,+ smartQuotesType: SmartQuotesType.disabled,// 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,diff --git a/mobile/lib/phone/phone_search_index.dart b/mobile/lib/phone/phone_search_index.dartindex 0031767cc..dcad81a9b 100644--- a/mobile/lib/phone/phone_search_index.dart+++ b/mobile/lib/phone/phone_search_index.dart@@ -1,5 +1,5 @@-import 'package:harness_mobile/state/agent_recall.dart';import 'package:harness_mobile/state/app_state.dart';+import 'package:harness_mobile/state/session_preview.dart';import 'agent_index.dart';import 'phone_status.dart';@@ -30,7 +30,7 @@ class PhoneSearchResult {required this.summary,required this.machineId,this.titleFields = 1,- this.recall,+ this.preview,this.entry,this.machine,});@@ -64,9 +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;+ /// What was last asked of this agent and what it answered — cached from its+ /// machine and kept live by its turn events. The fallback a word that matches+ /// no field is looked for in, as on the desktop.+ final SessionPreview? preview;final PhoneSummary summary;@@ -93,13 +94,13 @@ List<PhoneSearchResult> phoneSearchIndex(AppNotifier notifier) => [for (final entry in recentAgents(agentIndex(notifier)))_agentResult(entry,- notifier.agentRecall.read(- notifier.agentRecallKey(entry.machineId, entry.agent),+ notifier.sessionPreviews.read(+ notifier.previewKey(entry.machineId, entry.agent),),),];-PhoneSearchResult _agentResult(AgentEntry entry, AgentRecall? recall) {+PhoneSearchResult _agentResult(AgentEntry entry, SessionPreview? preview) {final agent = entry.agent;final engine = agent.engineDisplayName ?? agent.engine ?? '';final title = agent.title ?? '';@@ -139,7 +140,7 @@ PhoneSearchResult _agentResult(AgentEntry entry, AgentRecall? recall) {branch,].map((field) => field.toLowerCase()).where((field) => field.isNotEmpty).toList(),titleFields: title.isEmpty ? 1 : 2,- recall: recall,+ preview: preview,summary: entry.summary,machineId: entry.machineId,entry: entry,diff --git a/mobile/lib/phone/phone_search_page.dart b/mobile/lib/phone/phone_search_page.dartindex 2a223d3e4..e17bd0d28 100644--- a/mobile/lib/phone/phone_search_page.dart+++ b/mobile/lib/phone/phone_search_page.dart@@ -19,8 +19,8 @@ import 'phone_search_results.dart';/// finds the same agent here.////// ⚠️ 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.+/// holds — the agent list, and the session content [PhoneSearchResults] reads —+/// 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 headerdiff --git a/mobile/lib/phone/phone_search_rank.dart b/mobile/lib/phone/phone_search_rank.dartindex 19c7118b2..2728a0c00 100644--- a/mobile/lib/phone/phone_search_rank.dart+++ b/mobile/lib/phone/phone_search_rank.dart@@ -68,27 +68,30 @@ int? phoneFieldMatchScore(String field, String term, {required bool title}) {return best;}-/// Whether [term] appears, as written, in what was last said to [row]'s agent.+/// Whether [term] appears, as written, in what was last asked of [row]'s agent+/// or what it answered — the desktop's content fallback.///-/// 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;+/// Literal only — never the scattered-letter match the fields get. A few 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 phoneContentHas(PhoneSearchResult row, String term) =>+ row.preview?.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;+/// match can, so an agent that IS "llama" stays ahead of one that talked about+/// it. The desktop's figure.+const _contentScore = 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.+/// A word that matches no field is looked for in the agent's session content —+/// its recent requests, its latest answer, what it is writing right now — which+/// is how "llama" finds the agent somebody asked about llama.cpp. Rows that+/// needed the content to match rank after every row that matched on the agent+/// itself, as on the desktop.////// ⚠️ Ties break on the row's position in the index, never on anything that/// moves by itself. An agent that starts working sorts upward in [agentIndex],@@ -104,12 +107,12 @@ List<PhoneSearchResult> rankPhoneSearch(if (terms.isEmpty) return all;final ranked =- <({PhoneSearchResult row, int score, bool recalled, int index})>[];+ <({PhoneSearchResult row, int score, bool content, 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));+ ranked.add((row: row, score: -1, content: false, index: index));continue;}final match = _scoreRow(row, terms);@@ -117,58 +120,63 @@ List<PhoneSearchResult> rankPhoneSearch(ranked.add((row: row,score: match.score,- recalled: match.recalled,+ content: match.content,index: index,));}- int byRecall(bool recalled) => recalled ? 1 : 0;+ int byContent(bool content) => content ? 1 : 0;ranked.sort((a, b) {- var order = byRecall(a.recalled).compareTo(byRecall(b.recalled));+ var order = byContent(a.content).compareTo(byContent(b.content));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.+/// Every term's best score on [row] summed, and whether any needed the session+/// content — 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(+({int score, bool content})? _scoreRow(PhoneSearchResult row,List<String> terms,) {var total = 0;- var recalled = false;+ var content = 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;+ if (!phoneContentHas(row, term)) return null;+ content = true;+ total += _contentScore;}- return (score: total, recalled: recalled);+ return (score: total, content: content);}-/// 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.+/// The line of [row]'s session content worth quoting under its name: the one+/// holding the first word 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;+String? phoneContentSnippet(PhoneSearchResult row, List<String> terms) {+ final preview = row.preview;+ if (preview == 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);+ // Line by line: a saved answer runs to paragraphs, and a row has one line+ // to quote from.+ for (final part in preview.searchParts) {+ for (final raw in part.split('\n')) {+ final line = raw.trim();+ final at = line.toLowerCase().indexOf(term);+ if (at >= 0) return _quote(line, at);+ }}}return null;diff --git a/mobile/lib/phone/phone_search_results.dart b/mobile/lib/phone/phone_search_results.dartindex 641c52d03..5995ba43e 100644--- a/mobile/lib/phone/phone_search_results.dart+++ b/mobile/lib/phone/phone_search_results.dart@@ -23,9 +23,11 @@ import 'phone_section_label.dart';/// 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.+/// A word that matches no agent is looked for in what the agents were last+/// asked and answered — [AppNotifier.sessionPreviews], the desktop's own store.+/// Keystrokes only ever read it, so typing stays instant and costs no data;+/// opening the search just moves the agents offered first to the front of its+/// background reads.class PhoneSearchResults extends StatefulWidget {const PhoneSearchResults({super.key,@@ -52,17 +54,17 @@ class PhoneSearchResults extends StatefulWidget {class _PhoneSearchResultsState extends State<PhoneSearchResults> {late final Listenable _changes = Listenable.merge([widget.notifier,- widget.notifier.agentRecall,+ widget.notifier.sessionPreviews,]);@overridevoid initState() {super.initState();final notifier = widget.notifier;- notifier.agentRecall.warm([+ notifier.sessionPreviews.warm([for (final entry in recentAgents(agentIndex(notifier)))- notifier.agentRecallKey(entry.machineId, entry.agent),- ]);+ notifier.previewKey(entry.machineId, entry.agent),+ ], prioritize: true);}@overridediff --git a/mobile/lib/phone/phone_search_row.dart b/mobile/lib/phone/phone_search_row.dartindex f86f0ccf0..92f53d8cc 100644--- a/mobile/lib/phone/phone_search_row.dart+++ b/mobile/lib/phone/phone_search_row.dart@@ -77,7 +77,7 @@ class _PhoneSearchRowState extends State<PhoneSearchRow> {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);+ final quote = phoneContentSnippet(row, widget.terms);return GestureDetector(behavior: HitTestBehavior.opaque,onTapDown: (_) => _press(true),@@ -122,7 +122,7 @@ class _PhoneSearchRowState extends State<PhoneSearchRow> {(widget.placed ? row.placedSubtitle : row.subtitle),matches: quote == null? matches- : phoneRecallMatches(widget.terms),+ : phoneContentMatches(widget.terms),style: TextStyle(color: AppPalette.textFaint,fontSize: 12.5,diff --git a/mobile/lib/phone/phone_search_row_trailing.dart b/mobile/lib/phone/phone_search_row_trailing.dartindex 466a6e06c..9576d1ef3 100644--- a/mobile/lib/phone/phone_search_row_trailing.dart+++ b/mobile/lib/phone/phone_search_row_trailing.dart@@ -39,7 +39,7 @@ class PhoneSearchTrailing extends StatelessWidget {if (entry.isWorking) {return _Recency('working', color: phoneToneColor(PhoneTone.busy));}- final at = entry.agent.updatedAt;+ final at = entry.lastActiveAt;if (at == null) return const SizedBox.shrink();return _Recency(compactAge(at, now), color: AppPalette.textFaint);}diff --git a/mobile/lib/phone/search_result_text.dart b/mobile/lib/phone/search_result_text.dartindex 8f6bbbe5c..7a475ec18 100644--- a/mobile/lib/phone/search_result_text.dart+++ b/mobile/lib/phone/search_result_text.dart@@ -9,9 +9,9 @@ import 'phone_search_rank.dart';/// 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) => [+/// [terms] as matches on a content quote (see [phoneContentSnippet]): each term+/// is its own field, so the emphasis lands on the word wherever the quote holds it.+List<PhoneFieldMatch> phoneContentMatches(List<String> terms) => [for (final term in terms.take(12).toSet())(field: term, term: term, title: false),];diff --git a/mobile/lib/phone/settings_page.dart b/mobile/lib/phone/settings_page.dartindex 594280306..be85d689c 100644--- a/mobile/lib/phone/settings_page.dart+++ b/mobile/lib/phone/settings_page.dart@@ -150,7 +150,7 @@ class _Body extends StatelessWidget {const SettingsCaption('Appearance'),SettingsGroup(children: [_PaletteRow(), _TextSizeRow()]),const SettingsNote(- 'Harness is dark-only, so a palette picks the shade rather than the mode.',+ 'OpenHarness is dark-only, so a palette picks the shade rather than the mode.',),const SettingsCaption('About'),SettingsGroup(children: const [_VersionRow(), _BuildRow()]),diff --git a/mobile/lib/phone/terminal_search.dart b/mobile/lib/phone/terminal_search.dartindex caf5aba45..1104ae54d 100644--- a/mobile/lib/phone/terminal_search.dart+++ b/mobile/lib/phone/terminal_search.dart@@ -5,6 +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 'composing_keyboard.dart';import 'phone_search_results.dart';import 'terminal_header.dart';@@ -299,8 +300,13 @@ class _Input extends StatelessWidget {// that drops the keyboard and leaves the results up.textInputAction: TextInputAction.search,onSubmitted: (_) => focus.unfocus(),- autocorrect: false,- enableSuggestions: false,+ // Composing stays on — or Telex types `thoi tiet` for `thời tiết`. See+ // [ComposingKeyboard]; with autocorrect on, iOS would also start curling+ // quotes and joining dashes, which a query means literally.+ autocorrect: ComposingKeyboard.autocorrect,+ enableSuggestions: ComposingKeyboard.enableSuggestions,+ smartDashesType: SmartDashesType.disabled,+ smartQuotesType: SmartQuotesType.disabled,// 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,diff --git a/mobile/lib/phone/voice_notice.dart b/mobile/lib/phone/voice_notice.dartindex cd278fcfe..1830fcec0 100644--- a/mobile/lib/phone/voice_notice.dart+++ b/mobile/lib/phone/voice_notice.dart@@ -1,7 +1,7 @@/// The one line voice input shows when it cannot do what was asked.abstract final class VoiceNotice {static const unavailable =- 'Voice input is off. Allow Harness the microphone in Settings, or use the keyboard.';+ 'Voice input is off. Allow OpenHarness the microphone in Settings, or use the keyboard.';static const couldNotStart ="The microphone couldn't start. Tap the mic to try again.";@@ -12,7 +12,7 @@ abstract final class VoiceNotice {/// simulator the Mac has not given its microphone to. Speaking again will not/// help, so the notice does not suggest it.static const noSound =- 'No sound reached the microphone. Check the input Harness is using.';+ 'No sound reached the microphone. Check the input OpenHarness is using.';static const notTranscribed ="Couldn't turn that into text. Tap the mic to try again.";diff --git a/mobile/lib/shortcuts/shortcuts_list.dart b/mobile/lib/shortcuts/shortcuts_list.dartindex a0598204e..6ca4d2ce4 100644--- a/mobile/lib/shortcuts/shortcuts_list.dart+++ b/mobile/lib/shortcuts/shortcuts_list.dart@@ -264,7 +264,7 @@ class ShortcutsNote extends StatelessWidget {Widget build(BuildContext context) {grid.AppTheme.watch(context);final text = Text(- 'Harness shortcuts control your workspace. Other input goes to the '+ 'OpenHarness shortcuts control your workspace. Other input goes to the ''focused agent, where prompt editing and cancellation follow that ''coding agent’s behavior.',style: TextStyle(diff --git a/mobile/lib/state/agent_recall.dart b/mobile/lib/state/agent_recall.dartdeleted file mode 100644index 94fd08693..000000000--- a/mobile/lib/state/agent_recall.dart+++ /dev/null@@ -1,181 +0,0 @@-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 aff7df995..4b42e2d48 100644--- a/mobile/lib/state/app_state.dart+++ b/mobile/lib/state/app_state.dart@@ -34,9 +34,9 @@ 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 'session_preview.dart';import 'terminal_pane.dart';import 'swarm.dart';import '../terminal/terminal_binary.dart';@@ -206,6 +206,16 @@ class MachineState {String? pendingOfflineAgentId;final Set<String> processingAgentIds = {};+ /// When this app last SAW each agent's conversation move — a turn starting,+ /// beating or ending on this socket — by agentId.+ ///+ /// Newer than [Agent.updatedAt] whenever the machine has not re-sent that+ /// agent since, which is the normal case: the daemon pushes an agent when the+ /// agent changes, not on every turn. Without this, an agent somebody had just+ /// talked to kept the age of its last list fetch and sank below idle ones the+ /// moment its turn ended.+ final Map<String, DateTime> agentActivityAt = {};+/// Agents on this machine that have stopped to ask something, by agentId./// At most one per agent: a pane shows one dialog at a time, and the daemon/// re-announces the same open question rather than queueing a second.@@ -331,26 +341,46 @@ 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].+ /// What each agent was last asked and answered, as search matches it — the+ /// desktop's own store (see `session_preview.dart`), fed the same two ways:+ /// a small `agent_recent` read whenever the agent list arrives, and every+ /// turn event this socket carries, so a reply is findable the moment it lands.///- /// 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(+ /// Read again after [freshFor] at the soonest, not the desktop's minute: a+ /// phone pays for the bytes, and the live events already keep a connected+ /// machine's agents current.+ late final sessionPreviews = SessionPreviewStore(+ canFetch: _canFetchPreview,+ freshFor: const Duration(minutes: 5),+ fetchRecent: (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) =>+ SessionPreviewKey previewKey(String machineId, Agent agent) =>(machineId: machineId, agentId: agent.id, sessionId: agent.sessionId);+ /// Asks only a machine this app is already connected to, and never dials one:+ /// warming search must not be what wakes a relay socket.+ bool _canFetchPreview(SessionPreviewKey key) {+ if (_disposed || (_pool == null && connectionForTest == null)) return false;+ final machine = machineStates[key.machineId];+ return machine != null &&+ machine.nodeOnline != false &&+ !machine.needsLink &&+ machine.connectionStatus == ConnectionStatus.connected &&+ machine.agents.any(+ (agent) =>+ agent.id == key.agentId && agent.sessionId == key.sessionId,+ );+ }++ void _warmPreviews(MachineState machine) => sessionPreviews.warm(+ machine.agents.map((agent) => previewKey(machine.machine.machineId, agent)),+ );+/// 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.///@@ -2346,18 +2376,19 @@ class AppNotifier extends ChangeNotifier {final updater = desktopUpdater ?? DesktopUpdater();final staged = await updater.downloadAndStage(info);if (staged == null) {- updateError = 'Could not download and verify Harness ${info.version}.';+ updateError =+ 'Could not download and verify OpenHarness ${info.version}.';return false;}final applied = await updater.applyStaged(staged, selfPid: pid);if (!applied) {updateError =- 'This copy of Harness cannot install updates automatically.';+ 'This copy of OpenHarness cannot install updates automatically.';return false;}exit(0);} catch (error) {- updateError = 'Could not install Harness ${info.version}: $error';+ updateError = 'Could not install OpenHarness ${info.version}: $error';return false;} finally {isInstallingUpdate = false;@@ -2527,6 +2558,7 @@ class AppNotifier extends ChangeNotifier {currentUser = null;machines = [];machineStates.clear();+ sessionPreviews.clear();expandedMachines.clear();selectedMachineId = null;status = AppStatus.unauthenticated;@@ -3562,6 +3594,18 @@ class AppNotifier extends ChangeNotifier {void _replaceAgents(MachineState machine, List<Agent> agents) {final nextIds = agents.map((agent) => agent.id).toSet();+ for (final old in machine.agents.where(+ (agent) => !nextIds.contains(agent.id),+ )) {+ sessionPreviews.removeAgent(machine.machine.machineId, old.id);+ }+ for (final agent in agents) {+ sessionPreviews.retainAgent(+ machine.machine.machineId,+ agent.id,+ agent.sessionId,+ );+ }for (final agentId in machine.processingAgentIds.difference(nextIds)) {_cancelTurnActivity(machine.machine.machineId, agentId);}@@ -3588,6 +3632,7 @@ class AppNotifier extends ChangeNotifier {machine.pendingProcessingSessions.remove(sessionId);_markAgentProcessing(machine, agentId);}+ _warmPreviews(machine);}void _upsertAgent(MachineState machine, Agent agent) {@@ -3598,6 +3643,12 @@ class AppNotifier extends ChangeNotifier {} else {machine.agents = [...machine.agents]..[index] = agent;}+ sessionPreviews.retainAgent(+ machine.machine.machineId,+ agent.id,+ agent.sessionId,+ );+ sessionPreviews.warm([previewKey(machine.machine.machineId, agent)]);machine.sessionAgentIds.removeWhere((_, id) => id == agent.id);final sessionId = agent.sessionId;if (sessionId != null) {@@ -3632,7 +3683,9 @@ class AppNotifier extends ChangeNotifier {machine.agents = machine.agents.where((agent) => agent.id != agentId).toList();+ sessionPreviews.removeAgent(machine.machine.machineId, agentId);machine.sessionAgentIds.removeWhere((_, id) => id == agentId);+ machine.agentActivityAt.remove(agentId);_cancelTurnActivity(machine.machine.machineId, agentId);if (machine.activeAgentId == agentId) machine.activeAgentId = null;if (machine.pendingOfflineAgentId == agentId) {@@ -3674,6 +3727,34 @@ class AppNotifier extends ChangeNotifier {return session is String && session.isNotEmpty ? session : null;}+ /// One session event into [sessionPreviews], as the desktop feeds its own —+ /// dropped when it belongs to a session the agent has already moved on from,+ /// so a late frame from before a `/clear` cannot write into the new one.+ void _ingestPreview(+ MachineState machine,+ Map<String, dynamic> event,+ String type,+ Map<String, dynamic> payload,+ ) {+ final agentId = _eventAgentId(machine, event, payload);+ final agent = machine.agents+ .where((agent) => agent.id == agentId)+ .firstOrNull;+ if (agent == null) return;+ final sessionId = _eventSessionId(event, payload);+ if (sessionId != null &&+ agent.sessionId != null &&+ sessionId != agent.sessionId) {+ return;+ }+ sessionPreviews.ingest(+ previewKey(machine.machine.machineId, agent),+ type,+ payload,+ streamingText: agent.engine == 'opencode' || agent.engine == 'kilo',+ );+ }+/// Starts the clock `app_first_message` measures. [from] is `sign_in` for a/// fresh log-in and `launch` for an app opened with a session already there.///@@ -5489,6 +5570,12 @@ class AppNotifier extends ChangeNotifier {}return;}+ if (SessionPreviewStore.eventTypes.contains(type)) {+ _ingestPreview(machine, event, type, payload);+ // Content belongs to the preview's notifier. It must not invalidate the+ // whole app for every token or tool event.+ if (type != 'turn_started' && type != 'turn_ended') return;+ }switch (type) {// ── the dial, over the cable, forwarded by the local daemon ──────────────────────────────────// Local-only frames (backend.sendLocal in the harness CLI): they describe a hand at THIS desk, so@@ -5692,6 +5779,7 @@ class AppNotifier extends ChangeNotifier {var changed = false;final agentId = _eventAgentId(machine, event, payload);if (agentId != null) {+ machine.agentActivityAt[agentId] = DateTime.now();changed = _markAgentProcessing(machine, agentId);// Only a START opens a stats turn, for the reason above: a heartbeat// is a turn already under way, and counting one would report an agent@@ -5714,6 +5802,8 @@ class AppNotifier extends ChangeNotifier {case 'turn_ended':final agentId = _eventAgentId(machine, event, payload);if (agentId != null) {+ // The answer just landed — the moment a recency sort should follow.+ machine.agentActivityAt[agentId] = DateTime.now();_cancelTurnActivity(machine.machine.machineId, agentId);} else {final sessionId = _eventSessionId(event, payload);@@ -5813,7 +5903,7 @@ class AppNotifier extends ChangeNotifier {swarm.panes.clear();}unawaited(_spokenTasks.close());- agentRecall.dispose();+ sessionPreviews.dispose();super.dispose();}}diff --git a/mobile/lib/state/session_preview.dart b/mobile/lib/state/session_preview.dartnew file mode 100644index 000000000..830704192--- /dev/null+++ b/mobile/lib/state/session_preview.dart@@ -0,0 +1,355 @@+/// Ported from the desktop's `lib/state/session_preview.dart`, so a phone+/// search reaches the same session content the desktop's Open Agent picker+/// does. Keep the two in step; the one addition here is+/// [SessionPreview.searchParts], which the phone's result rows quote from.+library;++import 'dart:async';++import 'package:flutter/foundation.dart';++typedef SessionPreviewKey = ({+ String machineId,+ String agentId,+ String? sessionId,+});++/// Existing session excerpts only. This store never starts a model, reads a+/// transcript, attaches a terminal, or sends input to an agent.+class SessionPreview {+ final List<String> requests = [];+ final List<String> earlierResponses = [];+ String? currentRequest, liveText, completedText, savedText, activity;+ String _streamText = '';+ String? _searchText;+ bool turnOpen = false,+ interrupted = false,+ fetched = false,+ unavailable = false;+ DateTime? receivedAt;+ DateTime? _attemptedAt;+ int _revision = 0;++ String? get latestRequest => requests.firstOrNull;+ String? get earlierRequest =>+ latestRequest != null &&+ RegExp(+ r'^(ok(ay)?|yes|yeah|sure|continue|go ahead|thanks?|thank you|commit( and| &) push|commit and push)[.! ]*$',+ caseSensitive: false,+ ).hasMatch(latestRequest!)+ ? requests.skip(1).firstOrNull+ : null;+ String? get response => completedText ?? savedText;+ String? get responseExcerpt {+ final text = response;+ if (text == null || completedText != null || contextResponse == text) {+ return text;+ }+ // Cached fullText may include the "I'll commit" preamble before the final+ // receipt. Keep the existing outcome paragraphs, not just the preamble.+ final paragraphs = text.split(RegExp(r'\n\s*\n'));+ return paragraphs+ .skip(paragraphs.length > 2 ? paragraphs.length - 2 : 0)+ .join('\n\n');+ }++ // A commit receipt often follows the actual explanation. Reuse an earlier+ // existing response for compact group context, keeping the receipt available+ // as the latest response in the full preview. This is text selection only.+ String? get contextResponse =>+ response != null &&+ RegExp(+ r"^(?:(?:i['’]ll|i will|i['’]m)\s+)?(?:commit(?:ted|ting)?|push(?:ed|ing)?)\b",+ caseSensitive: false,+ ).hasMatch(response!.trimLeft()) &&+ earlierResponses.isNotEmpty+ ? earlierResponses.first+ : response;+ bool get hasContent =>+ latestRequest != null || liveText != null || response != null;++ /// The bounded excerpts search reaches, as written — what a phone result row+ /// quotes when a word matched only here.+ List<String> get searchParts => {+ currentRequest,+ latestRequest,+ earlierRequest,+ liveText,+ responseExcerpt,+ ...earlierResponses,+ activity,+ }.whereType<String>().toList();++ /// A lazy, normalized field over the same bounded excerpts as the preview.+ /// Keystrokes reuse it; it owns no history or separate search index.+ String get searchText => _searchText ??= searchParts.join('\n').toLowerCase();++ void _rememberRequest(Object? value) {+ final text = previewText(value, limit: 1600);+ if (text == null) return;+ requests.remove(text);+ requests.insert(0, text);+ if (requests.length > 3) requests.removeLast();+ }+}++/// Bounded memory shared across picker openings. Inventory warms small cached+/// `agent_recent` replies with two requests at a time. Selection reads memory;+/// a settled cold selection may schedule the same inexpensive background read.+class SessionPreviewStore extends ChangeNotifier {+ SessionPreviewStore({+ required this.fetchRecent,+ required this.canFetch,+ this.capacity = 256,+ this.freshFor = const Duration(minutes: 1),+ DateTime Function()? now,+ }) : _now = now ?? DateTime.now;++ final Future<Map<String, dynamic>> Function(SessionPreviewKey) fetchRecent;+ final bool Function(SessionPreviewKey) canFetch;+ final int capacity;+ final Duration freshFor;+ final DateTime Function() _now;+ final _records = <SessionPreviewKey, SessionPreview>{};+ final _queue = <SessionPreviewKey>{};+ final _inFlight = <SessionPreviewKey>{};+ Timer? _publish;+ bool _disposed = false;++ SessionPreview? read(SessionPreviewKey key) => _records[key];++ SessionPreview _entry(SessionPreviewKey key) {+ final entry = _records.remove(key) ?? SessionPreview();+ entry._searchText = null;+ _records[key] = entry;+ while (_records.length > capacity) {+ _records.remove(_records.keys.first);+ }+ return entry;+ }++ void warm(Iterable<SessionPreviewKey> keys, {bool prioritize = false}) {+ if (_disposed) return;+ final pending = <SessionPreviewKey>[];+ for (final key in keys.take(32)) {+ if (_inFlight.contains(key) || !canFetch(key)) continue;+ final attempted = read(key)?._attemptedAt;+ if (attempted != null && _now().difference(attempted) < freshFor) {+ continue;+ }+ pending.add(key);+ }+ if (prioritize) {+ final rest = _queue.toList();+ _queue+ ..clear()+ ..addAll(pending)+ ..addAll(rest);+ } else {+ _queue.addAll(pending);+ }+ while (_queue.length > 64) {+ _queue.remove(_queue.last);+ }+ _drain();+ }++ void _drain() {+ while (!_disposed && _inFlight.length < 2 && _queue.isNotEmpty) {+ final key = _queue.first;+ _queue.remove(key);+ if (!canFetch(key)) continue;+ final entry = _entry(key);+ final attempted = entry._attemptedAt;+ if (attempted != null && _now().difference(attempted) < freshFor) {+ continue;+ }+ entry._attemptedAt = _now();+ _inFlight.add(key);+ unawaited(_fetch(key, entry));+ }+ }++ Future<void> _fetch(SessionPreviewKey key, SessionPreview entry) async {+ final revision = entry._revision;+ bool current() =>+ !_disposed && identical(read(key), entry) && canFetch(key);+ try {+ final reply = await fetchRecent(key);+ if (!current()) return;+ if (reply['error'] != null ||+ (reply['agentId'] != null && reply['agentId'] != key.agentId)) {+ entry.unavailable = true;+ } else if (entry._revision == revision) {+ final asks = reply['asks'];+ if (asks is List) {+ for (final ask in asks.take(3).toList().reversed) {+ entry._rememberRequest(ask);+ }+ }+ final events = reply['events'];+ if (events is List) {+ final responses = <String>[];+ for (final event in events.take(3)) {+ if (event is! Map || event['kind'] != 'summary') continue;+ final text =+ previewText(event['fullText'], limit: 6000) ??+ previewText(event['text'], limit: 6000) ??+ previewText(event['recap'], limit: 6000);+ if (text != null && !responses.contains(text)) responses.add(text);+ }+ if (responses.isNotEmpty) {+ entry.savedText = responses.first;+ entry.earlierResponses+ ..clear()+ ..addAll(responses.skip(1));+ }+ }+ // Asks and summaries are independent lists, with no shared turn id.+ // They deliberately remain separate: this is never a paired exchange.+ entry.unavailable = false;+ entry.receivedAt = _now();+ }+ entry.fetched = true;+ entry._searchText = null;+ _changed();+ } catch (_) {+ if (current()) {+ entry.unavailable = true;+ entry.fetched = true;+ _changed();+ }+ } finally {+ _inFlight.remove(key);+ _drain();+ }+ }++ /// The ordinary session stream supplies actual requests, answer text and+ /// tool names. Reasoning, tool output and terminal bytes are not retained.+ void ingest(+ SessionPreviewKey key,+ String type,+ Map<String, dynamic> payload, {+ bool streamingText = false,+ }) {+ if (_disposed || !eventTypes.contains(type)) return;+ final entry = _entry(key);+ entry._revision++;+ entry.receivedAt = _now();+ entry.unavailable = false;+ switch (type) {+ case 'turn_started':+ entry.turnOpen = true;+ entry.interrupted = false;+ entry.currentRequest = previewText(payload['userMessage'], limit: 1600);+ entry._rememberRequest(entry.currentRequest);+ entry.liveText = null;+ entry._streamText = '';+ entry.activity = null;+ case 'user_message':+ entry._rememberRequest(payload['content']);+ if (entry.turnOpen) entry.currentRequest = entry.latestRequest;+ case 'text_delta':+ final raw = payload['content'];+ if (raw is String && raw.isNotEmpty) {+ if (streamingText) {+ final combined = '${entry._streamText}$raw';+ entry._streamText = combined.length > 6500+ ? combined.substring(combined.length - 6500)+ : combined;+ }+ entry.liveText = previewText(+ streamingText ? entry._streamText : raw,+ limit: 6000,+ tail: true,+ );+ entry.activity = null;+ }+ case 'tool_start':+ entry._streamText = '';+ entry.activity = previewText(payload['tool'], limit: 100);+ case 'tool_end':+ if (entry.activity == previewText(payload['tool'], limit: 100)) {+ entry.activity = null;+ }+ case 'turn_ended':+ entry.turnOpen = false;+ entry.interrupted = payload['aborted'] == true;+ if (entry.liveText != null) entry.completedText = entry.liveText;+ entry.liveText = null;+ entry.activity = null;+ }+ _changed();+ }++ static const eventTypes = {+ 'turn_started',+ 'user_message',+ 'text_delta',+ 'tool_start',+ 'tool_end',+ 'turn_ended',+ };++ void retainAgent(String machineId, String agentId, String? sessionId) {+ bool obsolete(SessionPreviewKey key) =>+ key.machineId == machineId &&+ key.agentId == agentId &&+ key.sessionId != sessionId;+ _records.removeWhere((key, _) => obsolete(key));+ _queue.removeWhere(obsolete);+ }++ void removeAgent(String machineId, String agentId) {+ bool matches(SessionPreviewKey key) =>+ key.machineId == machineId && key.agentId == agentId;+ _records.removeWhere((key, _) => matches(key));+ _queue.removeWhere(matches);+ }++ void clear() {+ _records.clear();+ _queue.clear();+ _publish?.cancel();+ _publish = null;+ }++ // Text deltas never notify the whole app or rebuild the search editor.+ // At most one preview repaint per 80 ms, even with several working agents.+ void _changed() {+ _publish ??= Timer(const Duration(milliseconds: 80), () {+ _publish = null;+ if (!_disposed) notifyListeners();+ });+ }++ @override+ void dispose() {+ _disposed = true;+ clear();+ super.dispose();+ }+}++String? previewText(Object? value, {required int limit, bool tail = false}) {+ if (value is! String || value.isEmpty) return null;+ // Bound work before cleanup as well as retained memory. No markdown or escape+ // sequence in session text is executable or rendered as HTML.+ var text = value.length > limit * 2+ ? tail+ ? value.substring(value.length - limit * 2)+ : value.substring(0, limit * 2)+ : value;+ text = text+ .replaceAll(RegExp(r'\x1b\[[0-?]*[ -/]*[@-~]'), '')+ .replaceAll(RegExp(r'[\x00-\x08\x0b-\x1f\x7f]'), '')+ .trim();+ if (text.isEmpty) return null;+ if (text.length > limit) {+ text = tail+ ? '…${text.substring(text.length - limit)}'+ : '${text.substring(0, limit)}…';+ }+ return text;+}diff --git a/mobile/lib/update/desktop_updater.dart b/mobile/lib/update/desktop_updater.dartindex f46fd1938..852d9452e 100644--- a/mobile/lib/update/desktop_updater.dart+++ b/mobile/lib/update/desktop_updater.dart@@ -36,7 +36,7 @@ String _currentArchitecture() => switch (Abi.current()) {Abi.linuxArm64 || Abi.macosArm64 || Abi.windowsArm64 => 'arm64',Abi.linuxX64 || Abi.macosX64 || Abi.windowsX64 => 'x64',_ => throw UnsupportedError(- 'Harness Desktop updates do not support ${Abi.current()}',+ 'OpenHarness updates do not support ${Abi.current()}',),};diff --git a/mobile/lib/viewer/direct_login.dart b/mobile/lib/viewer/direct_login.dartindex ccddf0284..313874b41 100644--- a/mobile/lib/viewer/direct_login.dart+++ b/mobile/lib/viewer/direct_login.dart@@ -82,7 +82,11 @@ class _LoopbackCallback {response..statusCode = signedIn ? HttpStatus.ok : HttpStatus.badRequest..headers.contentType = ContentType.html- ..write(_page(signedIn ? 'Signed in to Harness' : 'Harness sign-in failed'));+ ..write(+ _page(+ signedIn ? 'Signed in to OpenHarness' : 'OpenHarness sign-in failed',+ ),+ );await response.close();if (_completer.isCompleted) return;if (signedIn) {@@ -96,7 +100,9 @@ class _LoopbackCallback {void cancel() {if (_completer.isCompleted) return;- _completer.completeError(const DirectAuthException('Sign-in was cancelled.'));+ _completer.completeError(+ const DirectAuthException('Sign-in was cancelled.'),+ );}}@@ -104,4 +110,4 @@ String _page(String title) =>'<!doctype html><meta charset="utf-8"><title>$title</title>''<body style="font:16px system-ui,sans-serif;text-align:center;padding:4em 1em">''<h1 style="font-weight:600">$title</h1>'- '<p>You can close this window and go back to Harness.</p></body>';+ '<p>You can close this window and go back to OpenHarness.</p></body>';diff --git a/mobile/lib/widgets/bootstrapping_screen.dart b/mobile/lib/widgets/bootstrapping_screen.dartindex 791bdf2b5..012692aad 100644--- a/mobile/lib/widgets/bootstrapping_screen.dart+++ b/mobile/lib/widgets/bootstrapping_screen.dart@@ -15,7 +15,7 @@ class BootstrappingScreen extends StatelessWidget {final String? statusMessage;static const double _cardWidth = 420;- static const String _fallbackStatus = 'Opening Harness…';+ static const String _fallbackStatus = 'Opening OpenHarness…';@overrideWidget build(BuildContext context) {@@ -47,7 +47,7 @@ class BootstrappingScreen extends StatelessWidget {const _BootAppMark(),const SizedBox(height: 20),Text(- 'Getting Harness ready',+ 'Getting OpenHarness ready',textAlign: TextAlign.center,style: Theme.of(context).textTheme.titleLarge,),@@ -62,7 +62,7 @@ class BootstrappingScreen extends StatelessWidget {key: const Key('boot-status'),container: true,liveRegion: true,- label: 'Harness startup status',+ label: 'OpenHarness startup status',value: status,child: ExcludeSemantics(child: Container(diff --git a/mobile/lib/widgets/environment_preflight_screen.dart b/mobile/lib/widgets/environment_preflight_screen.dartindex 8180c9884..1875871d8 100644--- a/mobile/lib/widgets/environment_preflight_screen.dart+++ b/mobile/lib/widgets/environment_preflight_screen.dart@@ -78,7 +78,7 @@ class _CheckingContent extends StatelessWidget {),const SizedBox(height: 8),Text(- 'Verifying the tools Harness needs. This check is read-only and nothing is being installed.',+ 'Verifying the tools OpenHarness needs. This check is read-only and nothing is being installed.',textAlign: TextAlign.center,style: Theme.of(context).textTheme.bodySmall,),diff --git a/mobile/lib/widgets/environment_setup_screen.dart b/mobile/lib/widgets/environment_setup_screen.dartindex d374f4fa5..81e8bf4a3 100644--- a/mobile/lib/widgets/environment_setup_screen.dart+++ b/mobile/lib/widgets/environment_setup_screen.dart@@ -162,7 +162,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {_heading('Getting started','Checking this computer',- 'Checking the tools Harness needs to run your harnesses.',+ 'Checking the tools OpenHarness needs to run your harnesses.',),_checkList(state, checking: true),],@@ -215,7 +215,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {_notice(Icons.terminal,'Admin prompts stay in Terminal',- 'Complete any installation prompts there, then return to Harness.',+ 'Complete any installation prompts there, then return to OpenHarness.',),const SizedBox(height: 16),],@@ -241,8 +241,8 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {if (state.phase == EnvironmentSetupPhase.waitingForTerminal)_notice(Icons.lock_outline,- 'Harness cannot see your password',- 'Finish the prompts in Terminal, then return here. Harness checks progress automatically.',+ 'OpenHarness cannot see your password',+ 'Finish the prompts in Terminal, then return here. OpenHarness checks progress automatically.',),const SizedBox(height: 18),_checkList(state, checking: true),@@ -280,7 +280,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {_heading('Setup complete','This computer is ready',- 'Every required command passed. Continue to Harness sign-in.',+ 'Every required command passed. Continue to OpenHarness sign-in.',),_checkList(state),],@@ -313,7 +313,7 @@ class _EnvironmentSetupScreenState extends State<EnvironmentSetupScreen> {detail: _linuxClipboardDetail,status: state.steps[EnvironmentStep.clipboard],),- const _CheckSectionLabel('Harness components'),+ const _CheckSectionLabel('OpenHarness components'),_CheckRow(label: 'Managed Node 20+ & Harness CLI',detail: '~/.harness/runtime · harness version',diff --git a/mobile/lib/widgets/update_notice.dart b/mobile/lib/widgets/update_notice.dartindex 85f9d49fc..e90b4e726 100644--- a/mobile/lib/widgets/update_notice.dart+++ b/mobile/lib/widgets/update_notice.dart@@ -67,9 +67,9 @@ class UpdateNotice extends StatelessWidget {if (failed) {message = error;} else if (installing) {- message = 'Installing Harness ${update.version}…';+ message = 'Installing OpenHarness ${update.version}…';} else {- message = 'Harness ${update.version} is available';+ message = 'OpenHarness ${update.version} is available';}return Material(@@ -255,7 +255,7 @@ Future<void> showUpdateCheckDialog(icon: LucideIcons.circleCheck300,tone: _DialogTone.ok,title: 'You’re up to date',- body: 'This copy of Harness already has the latest version.',+ body: 'This copy of OpenHarness already has the latest version.',),);}@@ -268,13 +268,13 @@ Future<void> showUpdateCheckDialog(builder: (context, setState) => _UpdateDialog(icon: LucideIcons.arrowDownToLine300,title: installing- ? 'Installing Harness ${update.version}…'- : 'Harness ${update.version} is available',+ ? 'Installing OpenHarness ${update.version}…'+ : 'OpenHarness ${update.version} is available',body: installing- ? 'Don’t quit Harness. It will restart on its own.'+ ? 'Don’t quit OpenHarness. It will restart on its own.': result.isSkipped? 'You skipped this version earlier. You can still install it.'- : 'Download and install it now? Harness will restart when it '+ : 'Download and install it now? OpenHarness will restart when it ''finishes.',busy: installing,update: installing ? null : update,diff --git a/mobile/test/phone_search_test.dart b/mobile/test/phone_search_test.dartindex ab5b653f6..eeab33f0f 100644--- a/mobile/test/phone_search_test.dart+++ b/mobile/test/phone_search_test.dart@@ -1,5 +1,3 @@-import 'dart:async';-import 'package:flutter/material.dart';import 'package:flutter_test/flutter_test.dart';import 'package:harness_mobile/auth/auth_session.dart';@@ -12,7 +10,7 @@ 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/phone/terminal_search.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';@@ -76,9 +74,10 @@ AppNotifier _app(List<MachineState> machines, {WsConn? conn}) {return app;}-/// A machine that remembers what was asked of each agent, and answers nothing else.-class _RecallConn extends WsConn {- _RecallConn(this.asks)+/// A machine answering `agent_recent` with what was asked of each agent, and+/// nothing else.+class _RecentConn extends WsConn {+ _RecentConn(this.asks): super(wsBaseUrl: 'ws://fixture.invalid',autonomousEnv: 'test',@@ -106,7 +105,7 @@ class _RecallConn extends WsConn {}}-/// Lets every in-flight recall reply land.+/// Lets every in-flight `agent_recent` reply land.Future<void> _settle() async {for (var i = 0; i < 8; i++) {await Future<void>.delayed(Duration.zero);@@ -182,6 +181,29 @@ void main() {]);});+ test('a turn seen on the socket puts its agent ahead of idle ones', () async {+ // The reported case: a reply had just landed on one agent, but the machine+ // had not re-sent it, so it kept its 35m age under agents listed as 1m.+ final machine = _machine('m', [+ _agent('idle', minutesAgo: 1),+ _agent('talked', minutesAgo: 35),+ ]);+ final app = _app([machine]);+ addTearDown(app.dispose);+ List<String> order() =>+ recentAgents(agentIndex(app)).map((entry) => entry.agent.id).toList();+ expect(order(), ['idle', 'talked']);++ await app.handleEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'talked',+ 'payload': <String, dynamic>{},+ });+ expect(order(), ['talked', 'idle']);+ final talked = agentIndex(app).firstWhere((e) => e.agent.id == 'talked');+ expect(compactAge(talked.lastActiveAt!, DateTime.now()), 'now');+ });+group('search', () {final app = _app([_machine('box', [@@ -237,73 +259,11 @@ 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']);- },- );-+ group('session content', () {test(- 'a word only said to an agent finds it, after every field match',+ 'a word only in what an agent was asked finds it, after fields',() async {- final conn = _RecallConn({+ final conn = _RecentConn({'said': ['which llama.cpp build is running?'],'quiet': ['fix the login redirect'],});@@ -319,20 +279,47 @@ void main() {'named',]);- app.agentRecall.warm([+ app.sessionPreviews.warm([for (final agent in app.machineStates['box']!.agents)- app.agentRecallKey('box', agent),+ app.previewKey('box', agent),]);await _settle();final ranked = rankPhoneSearch(phoneSearchIndex(app), 'llama');expect(_agentIds(ranked), ['named', 'said']);- expect(phoneRecallSnippet(ranked.first, ['llama']), isNull);+ expect(phoneContentSnippet(ranked.first, ['llama']), isNull);expect(- phoneRecallSnippet(ranked.last, ['llama']),+ phoneContentSnippet(ranked.last, ['llama']),'which llama.cpp build is running?',);},);++ test('an answer streaming in is findable before its turn ends', () async {+ final app = _app([+ _machine('box', [+ _agent('live', minutesAgo: 30),+ _agent('other', minutesAgo: 1),+ ]),+ ]);+ addTearDown(app.dispose);+ Future<void> event(String type, Map<String, dynamic> payload) =>+ app.handleEventForTest('box', {+ 'type': type,+ 'agentId': 'live',+ 'payload': payload,+ });+ await event('turn_started', {+ 'userMessage': 'which llama.cpp build is running?',+ });+ await event('text_delta', {'content': 'It is llama.cpp b4521.'});++ final ranked = rankPhoneSearch(phoneSearchIndex(app), 'b4521');+ expect(_agentIds(ranked), ['live']);+ expect(+ phoneContentSnippet(ranked.single, ['b4521']),+ 'It is llama.cpp b4521.',+ );+ });});test('compactAge', () {@@ -380,10 +367,10 @@ void main() {expect(find.byType(PhoneSearchFolderHeader), findsOneWidget);});- testWidgets('opening search asks for recall; the matching line is quoted', (+ testWidgets('opening search warms content; the matching line is quoted', (tester,) async {- final conn = _RecallConn({+ final conn = _RecentConn({'3188': ['which llama.cpp build is running?'],});final app = _app([@@ -394,7 +381,8 @@ void main() {], conn: conn);addTearDown(app.dispose);await tester.pumpWidget(MaterialApp(home: PhoneSearchPage(notifier: app)));- await tester.pump();+ // The store publishes on an 80 ms beat, as on the desktop.+ await tester.pump(const Duration(milliseconds: 100));expect(conn.asked, ['3188', '2312']);await tester.enterText(find.byType(TextField), 'llama');@@ -407,6 +395,58 @@ void main() {);});+ group('the query field lets the keyboard compose', () {+ final fields = <String, Widget Function(AppNotifier)>{+ 'search page': (app) => PhoneSearchPage(notifier: app),+ 'terminal search': (app) => Scaffold(+ body: TerminalSearchOverlay(+ notifier: app,+ animation: const AlwaysStoppedAnimation(1),+ onClose: () {},+ ),+ ),+ };++ Future<Map<String, dynamic>> attachedConfig(+ WidgetTester tester,+ Widget Function(AppNotifier) field,+ ) async {+ final app = _app([+ _machine('box', [_agent('3188', minutesAgo: 4)]),+ ]);+ addTearDown(app.dispose);+ await tester.pumpWidget(MaterialApp(home: field(app)));+ await tester.pump();+ return tester.testTextInput.setClientArgs!;+ }++ for (final MapEntry(key: name, value: field) in fields.entries) {+ testWidgets(+ '$name: iOS keeps the autocorrection its Telex conversion rides on',+ (tester) async {+ final config = await attachedConfig(tester, field);+ expect(config['autocorrect'], isTrue);+ expect(config['enableSuggestions'], isTrue);+ expect(+ config['smartQuotesType'],+ SmartQuotesType.disabled.index.toString(),+ );+ },+ variant: TargetPlatformVariant.only(TargetPlatform.iOS),+ );++ testWidgets(+ '$name: Android composes with suggestions and corrects nothing',+ (tester) async {+ final config = await attachedConfig(tester, field);+ expect(config['enableSuggestions'], isTrue);+ expect(config['autocorrect'], isFalse);+ },+ variant: TargetPlatformVariant.only(TargetPlatform.android),+ );+ }+ });+testWidgets('one bar: no Cancel beside it, and its chevron closes search', (tester,) async {diff --git a/mobile/test/session_preview_test.dart b/mobile/test/session_preview_test.dartnew file mode 100644index 000000000..a0b45bf5f--- /dev/null+++ b/mobile/test/session_preview_test.dart@@ -0,0 +1,226 @@+import 'dart:async';++import 'package:flutter_test/flutter_test.dart';+import 'package:harness_mobile/state/session_preview.dart';++const a = (machineId: 'm', agentId: 'a', sessionId: 's1');+const b = (machineId: 'm', agentId: 'b', sessionId: 's2');+const c = (machineId: 'remote', agentId: 'c', sessionId: 's3');++void main() {+ test(+ 'cached requests and saved answers remain independent, never generated',+ () async {+ var calls = 0;+ final store = SessionPreviewStore(+ canFetch: (_) => true,+ fetchRecent: (key) async {+ calls++;+ return {+ 'agentId': key.agentId,+ 'asks': [+ 'continue',+ 'Make the picker show useful existing session content.',+ ],+ 'events': [+ {+ 'kind': 'summary',+ 'recap': 'short title',+ 'text': 'short body',+ 'fullText': 'Implemented the earlier task. Tests pass.',+ },+ ],+ };+ },+ );+ addTearDown(store.dispose);+ store.warm([a]);+ await Future<void>.delayed(Duration.zero);+ final record = store.read(a)!;+ expect(record.latestRequest, 'continue');+ expect(record.earlierRequest, contains('picker'));+ expect(record.response, 'Implemented the earlier task. Tests pass.');+ expect(record.currentRequest, isNull);+ for (var i = 0; i < 40; i++) {+ store.warm([a]);+ expect(store.read(a), same(record));+ }+ expect(calls, 1);+ },+ );++ test(+ 'a commit receipt retains the existing explanation for context',+ () async {+ final store = SessionPreviewStore(+ canFetch: (_) => true,+ fetchRecent: (_) async => {+ 'events': [+ {+ 'kind': 'summary',+ 'fullText': 'I’ll commit the prototype.\n\nPushing now.\n\nCommitted and pushed.\n\nThe shared comments are saved.',+ },+ {+ 'kind': 'summary',+ 'fullText':+ 'Highlight any message to add a shared comment thread.',+ },+ {+ 'kind': 'summary',+ 'fullText':+ 'Teammates can reply without sending a prompt to the agent.',+ },+ ],+ },+ );+ addTearDown(store.dispose);+ store.warm([a]);+ await Future<void>.delayed(Duration.zero);+ final preview = store.read(a)!;+ expect(+ preview.response,+ 'I’ll commit the prototype.\n\nPushing now.\n\nCommitted and pushed.\n\nThe shared comments are saved.',+ );+ expect(+ preview.responseExcerpt,+ 'Committed and pushed.\n\nThe shared comments are saved.',+ );+ expect(+ preview.contextResponse,+ 'Highlight any message to add a shared comment thread.',+ );+ expect(preview.earlierResponses, hasLength(2));+ },+ );++ test('background work is bounded and late replies cannot replace another session', () async {+ final pending = <SessionPreviewKey, Completer<Map<String, dynamic>>>{};+ final valid = {a, b, c};+ final store = SessionPreviewStore(+ canFetch: valid.contains,+ fetchRecent: (key) => (pending[key] = Completer()).future,+ );+ addTearDown(store.dispose);+ store.warm([a, b, c]);+ expect(pending.keys, [a, b]);+ store.warm([a]);+ valid.remove(a);+ store.retainAgent('m', 'a', 'new-session');+ pending[a]!.complete({+ 'asks': ['Old session contents'],+ });+ await Future<void>.delayed(Duration.zero);+ expect(store.read(a), isNull);+ expect(pending.keys, [a, b, c]);+ pending[c]!.complete({+ 'agentId': 'wrong',+ 'asks': ['Wrong agent'],+ });+ pending[b]!.complete({+ 'asks': ['Correct agent'],+ });+ await Future<void>.delayed(Duration.zero);+ expect(store.read(b)!.latestRequest, 'Correct agent');+ expect(store.read(c)!.hasContent, isFalse);+ expect(store.read(c)!.unavailable, isTrue);+ });++ test(+ 'a cached reply never overwrites a request observed after its fetch began',+ () async {+ final reply = Completer<Map<String, dynamic>>();+ final store = SessionPreviewStore(+ canFetch: (_) => true,+ fetchRecent: (_) => reply.future,+ );+ addTearDown(store.dispose);+ store.warm([a]);+ store.ingest(a, 'turn_started', {'userMessage': 'Fix the latest crash.'});+ store.ingest(a, 'text_delta', {'content': 'Checking the failing input.'});+ reply.complete({+ 'asks': ['Old task'],+ 'events': [+ {'kind': 'summary', 'text': 'Old result'},+ ],+ });+ await Future<void>.delayed(Duration.zero);+ expect(store.read(a)!.currentRequest, 'Fix the latest crash.');+ expect(store.read(a)!.liveText, 'Checking the failing input.');+ expect(store.read(a)!.response, isNull);+ store.ingest(a, 'text_delta', {+ 'content': 'Fixed the crash. All tests pass.',+ });+ store.ingest(a, 'turn_ended', {});+ expect(store.read(a)!.response, 'Fixed the crash. All tests pass.');+ store.ingest(a, 'turn_started', {'userMessage': 'Now fix the layout.'});+ expect(store.read(a)!.liveText, isNull);+ expect(store.read(a)!.response, 'Fixed the crash. All tests pass.');+ expect(store.read(a)!.currentRequest, 'Now fix the layout.');+ },+ );++ test('live excerpts skip reasoning and tool output and stay bounded', () {+ final store = SessionPreviewStore(+ capacity: 2,+ canFetch: (_) => false,+ fetchRecent: (_) async => {},+ );+ addTearDown(store.dispose);+ store.ingest(a, 'thinking_delta', {'content': 'internal analysis'});+ expect(store.read(a), isNull);+ store.ingest(a, 'turn_started', {'userMessage': 'a' * 100000});+ store.ingest(a, 'tool_start', {+ 'tool': 'Read',+ 'input': {'path': '/a'},+ });+ expect(store.read(a)!.activity, 'Read');+ store.ingest(a, 'tool_end', {'tool': 'Read', 'output': 'b' * 100000});+ expect(store.read(a)!.activity, isNull);+ store.ingest(a, 'text_delta', {'content': 'A small '}, streamingText: true);+ store.ingest(a, 'text_delta', {+ 'content': 'response.',+ }, streamingText: true);+ expect(store.read(a)!.liveText, 'A small response.');+ store.ingest(a, 'text_delta', {'content': 'b' * 100000});+ expect(store.read(a)!.liveText!.length, lessThanOrEqualTo(6001));+ expect(store.read(a)!.currentRequest!.length, lessThanOrEqualTo(1601));+ store.ingest(b, 'user_message', {'content': 'second'});+ store.ingest(c, 'user_message', {'content': 'third'});+ expect(store.read(a), isNull);+ store.clear();+ expect(store.read(b), isNull);+ });++ test('offline and failed refresh retain saved text; retries respect the cache age', () async {+ var now = DateTime(2026, 9, 14);+ var online = true;+ var calls = 0;+ final store = SessionPreviewStore(+ now: () => now,+ canFetch: (_) => online,+ fetchRecent: (_) async {+ if (++calls > 1) throw StateError('offline');+ return {+ 'events': [+ {'kind': 'summary', 'text': 'Saved result'},+ ],+ };+ },+ );+ addTearDown(store.dispose);+ store.warm([a]);+ await Future<void>.delayed(Duration.zero);+ online = false;+ now = now.add(const Duration(minutes: 2));+ store.warm([a]);+ expect(calls, 1);+ online = true;+ store.warm([a]);+ await Future<void>.delayed(Duration.zero);+ expect(store.read(a)!.response, 'Saved result');+ expect(store.read(a)!.unavailable, isTrue);+ expect(calls, 2);+ store.warm([a]);+ expect(calls, 2);+ });+}