Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

feat(mobile): find in terminal, highlighting matches as desktop's find bar does

tony255c72e75f5a
diff --git a/mobile/lib/phone/terminal_find_bar.dart b/mobile/lib/phone/terminal_find_bar.dart
new file mode 100644
index 000000000..05c5f4a4a
--- /dev/null
+++ b/mobile/lib/phone/terminal_find_bar.dart
@@ -0,0 +1,134 @@
+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/terminal/terminal_find.dart';
+
+import 'tty.dart';
+import 'tty_controls.dart';
+
+/// Find in terminal's bar: the desktop's find bar (`desktop/lib/widgets/terminal_find_bar.dart`) in
+/// the phone's face, where the key bar sits — on the keyboard while one is up, at the foot of the
+/// terminal while not.
+///
+/// `/` and the words, how many matched (`3/12`, red when none), ↑ and ↓, and × to put it away —
+/// the desktop's pieces and its words, nothing added: the terminal stays the screen.
+///
+/// The keyboard's search key puts the keyboard away and leaves the bar, as Safari's find in page
+/// does: half the screen comes back to read the match in, and ↑ ↓ go on stepping.
+class TerminalFindBar extends StatefulWidget {
+ const TerminalFindBar({super.key, required this.find, required this.onClose});
+
+ final TerminalFindController find;
+ final VoidCallback onClose;
+
+ @override
+ State<TerminalFindBar> createState() => _TerminalFindBarState();
+}
+
+class _TerminalFindBarState extends State<TerminalFindBar> {
+ late final _text = TextEditingController(text: widget.find.query);
+ final _focus = FocusNode(debugLabel: 'Find in terminal');
+
+ @override
+ void dispose() {
+ _text.dispose();
+ _focus.dispose();
+ super.dispose();
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ AppTheme.watch(context);
+ final tty = Tty.of(context);
+ return ListenableBuilder(
+ listenable: widget.find,
+ builder: (context, _) {
+ final find = widget.find;
+ final count = find.count;
+ Widget button(
+ String label,
+ IconData icon,
+ VoidCallback? action, {
+ Key? key,
+ }) => IconButton(
+ key: key,
+ tooltip: label,
+ onPressed: action,
+ icon: Icon(icon, size: 20),
+ color: tty.text,
+ disabledColor: tty.faint,
+ visualDensity: VisualDensity.compact,
+ constraints: const BoxConstraints.tightFor(width: 40, height: 40),
+ padding: EdgeInsets.zero,
+ );
+ return Material(
+ key: const ValueKey('terminal-find-bar'),
+ color: tty.ground,
+ child: Padding(
+ padding: const EdgeInsets.fromLTRB(Tty.origin, 6, 4, 6),
+ child: Row(
+ children: [
+ Expanded(
+ child: TtyField(
+ controller: _text,
+ focus: _focus,
+ hint: 'Find in terminal…',
+ autofocus: true,
+ action: TextInputAction.search,
+ leading: ExcludeSemantics(
+ child: TtyText('/', color: tty.faint),
+ ),
+ onChanged: find.setQuery,
+ onSubmitted: _focus.unfocus,
+ trailing: [
+ Semantics(
+ liveRegion: true,
+ label: find.searching && !find.hasSnapshot
+ ? 'Searching terminal'
+ : find.query.isEmpty
+ ? 'Find in terminal'
+ : count == 0
+ ? 'No matches'
+ : 'Match ${find.selected + 1} of $count',
+ child: ExcludeSemantics(
+ child: Padding(
+ padding: const EdgeInsets.only(left: 6),
+ child: TtyText(
+ find.status,
+ key: const ValueKey('terminal-find-status'),
+ color: find.missed ? tty.red : tty.faint,
+ size: TtySize.meta,
+ ),
+ ),
+ ),
+ ),
+ ],
+ ),
+ ),
+ button(
+ 'Previous match',
+ LucideIcons.chevronUp300,
+ count > 0 ? find.previous : null,
+ key: const ValueKey('terminal-find-previous'),
+ ),
+ button(
+ 'Next match',
+ LucideIcons.chevronDown300,
+ count > 0 ? find.next : null,
+ key: const ValueKey('terminal-find-next'),
+ ),
+ button(
+ 'Close find',
+ LucideIcons.x300,
+ widget.onClose,
+ key: const ValueKey('terminal-find-close'),
+ ),
+ ],
+ ),
+ ),
+ );
+ },
+ );
+ }
+}
diff --git a/mobile/lib/phone/terminal_page.dart b/mobile/lib/phone/terminal_page.dart
index a3c73d837..1f516f97e 100644
--- a/mobile/lib/phone/terminal_page.dart
+++ b/mobile/lib/phone/terminal_page.dart
@@ -33,6 +33,7 @@ import 'package:harness_mobile/terminal/elicitation_press.dart';
import 'package:harness_mobile/terminal/key_hints.dart';
import 'package:harness_mobile/terminal/question_pane.dart';
import 'package:harness_mobile/terminal/question_pane_watcher.dart';
+import 'package:harness_mobile/terminal/terminal_find.dart';
import 'package:harness_mobile/terminal/terminal_session.dart';
import 'package:harness_mobile/core/agent_handoff.dart'
show supportsAgentHandoff;
@@ -59,6 +60,7 @@ import 'terminal_chrome_scroll.dart';
import 'terminal_input_dock.dart';
import 'terminal_copy.dart';
import 'terminal_file_send.dart';
+import 'terminal_find_bar.dart';
import 'terminal_paste.dart';
import 'terminal_search.dart';
import 'tty.dart';
@@ -379,6 +381,13 @@ class _TerminalPageState extends State<TerminalPage>
Timer? _searchHoldTimer;
static const _searchHoldLimit = Duration(milliseconds: 800);
+ /// Find in terminal while its bar is up — see [_openFind]. Null while it is not.
+ TerminalFindController? _find;
+
+ /// Whether the terminal had the keyboard when Find opened: closing gives it back, or puts away
+ /// the one Find's field raised — as [_keyboardBeforeSearch] does for search.
+ bool _keyboardBeforeFind = false;
+
/// The header getting out of the way as the terminal is scrolled. See
/// [TerminalChromeScroll].
late final TerminalChromeScroll _chrome = TerminalChromeScroll(vsync: this);
@@ -825,6 +834,8 @@ class _TerminalPageState extends State<TerminalPage>
_keyboardRequested = false;
_cancelSettle();
if (_keyboardSettling) setState(() => _keyboardSettling = false);
+ // Find belongs to the terminal being read: swiped away, it goes, keyboard and all.
+ if (_find != null) _closeFind(giveKeyboardBack: false, rebuild: false);
}
}
@@ -847,6 +858,8 @@ class _TerminalPageState extends State<TerminalPage>
_barMessageTimer?.cancel();
_barMessage.dispose();
_scrollback.dispose();
+ _dropFindBack();
+ _find?.dispose();
widget.notifier.removeListener(_onNotifier);
_daemon?.noteQuestion(
this,
@@ -1552,6 +1565,86 @@ class _TerminalPageState extends State<TerminalPage>
});
}
+ /// Find in terminal: its bar where the key bar is, the terminal searched and its match lit —
+ /// the desktop's ⌘F, from the `⋯` menu.
+ ///
+ /// The terminal is not held still for it, unlike search: the field's keyboard shrinks the page as
+ /// typing into the terminal does, and the panel carries the search across the keyframe that
+ /// follows (`TerminalPanel._syncTerminal`), so the match is read in the space the keyboard
+ /// leaves. What the field must not do is hand the keyboard to the terminal — see [_shouldFocus].
+ void _openFind() {
+ if (_find != null || !mounted) return;
+ _keyboardBeforeFind = _keyboardIsUp;
+ // Let go of the terminal's input before the field mounts and asks for the keyboard — the race
+ // [_openSearch] closes the same way.
+ FocusManager.instance.primaryFocus?.unfocus();
+ _chrome.reveal();
+ final route = ModalRoute.of(context);
+ final back = _FindBack(() => _closeFind());
+ route?.registerPopEntry(back);
+ _findBack = (route: route, entry: back);
+ setState(() {
+ _find = TerminalFindController();
+ _keyboardRequested = false;
+ });
+ }
+
+ /// Back while Find is up closes Find, not the page — registered on the route for as long as the
+ /// bar is up, which is what a [PopScope] would do, without wrapping the page in one.
+ ({ModalRoute<Object?>? route, _FindBack entry})? _findBack;
+
+ void _dropFindBack() {
+ final back = _findBack;
+ _findBack = null;
+ if (back == null) return;
+ back.route?.unregisterPopEntry(back.entry);
+ back.entry.dispose();
+ }
+
+ /// Puts Find away: the panel goes back to where the reader was, and the keyboard goes back to
+ /// whoever had it — the terminal, if it had one when Find opened, else nobody.
+ ///
+ /// ⚠️ **Find's keyboard falls for half a second after the bar has gone**, and the terminal would
+ /// take the falling inset for its own (see [_heldForSearch]). So unless the terminal is getting
+ /// a keyboard back, it is held off the keyboard until that one is gone — search's own close.
+ ///
+ /// [rebuild] false for a page being parked ([didUpdateWidget]): it rebuilds anyway, and a parked
+ /// page claims no keyboard to be held off.
+ void _closeFind({bool giveKeyboardBack = true, bool rebuild = true}) {
+ final find = _find;
+ if (find == null) return;
+ _dropFindBack();
+ final back = giveKeyboardBack && _keyboardBeforeFind && widget.isActive;
+ if (!back) dismissKeyboardForSwipe();
+ void apply() {
+ _find = null;
+ if (!rebuild) return;
+ if (back) {
+ _keyboardRequested = true;
+ _focusRequest++;
+ } else {
+ _heldForSearch = true;
+ _keyboardUpAtSearch = false;
+ }
+ }
+
+ if (rebuild) {
+ setState(apply);
+ if (back) {
+ _armSettle();
+ } else if (_lastInset == 0) {
+ _releaseSearchHold();
+ } else {
+ _searchHoldTimer?.cancel();
+ _searchHoldTimer = Timer(_searchHoldLimit, _releaseSearchHold);
+ }
+ } else {
+ apply();
+ }
+ // After the bar and the panel have let go of it.
+ WidgetsBinding.instance.addPostFrameCallback((_) => find.dispose());
+ }
+
/// Hands the terminal back its own reading of the keyboard.
void _releaseSearchHold() {
_searchHoldTimer?.cancel();
@@ -1686,7 +1779,9 @@ class _TerminalPageState extends State<TerminalPage>
// The search field's keyboard is not this page's to put back, and a
// page with something stacked over it is not the page being returned to.
_keyboardHeldForBackground =
- !_heldForSearch && (_ownsInput || _keyboardRequested);
+ _find == null &&
+ !_heldForSearch &&
+ (_ownsInput || _keyboardRequested);
}
return;
}
@@ -1731,6 +1826,11 @@ class _TerminalPageState extends State<TerminalPage>
/// would be sent to the shell instead.
bool get _shouldFocus =>
widget.isActive &&
+ // ⚠️ Find's field owns the keyboard while its bar is up, for the reason search's does (see
+ // [_heldForSearch]): read as the terminal's, the panel would take the input connection back
+ // on the next keyframe — and the field's own keyboard rising ends in one — so the second
+ // letter of a search would go to the shell.
+ _find == null &&
!_heldForSearch &&
!_heldForCover &&
(_keyboardIsUp || _keyboardRequested);
@@ -2300,6 +2400,8 @@ class _TerminalPageState extends State<TerminalPage>
// up is a separate question, and the pager asks
// it on every swipe — see [_shouldFocus].
focused: _shouldFocus,
+ // What the bar is finding — see [_openFind].
+ find: _find,
// Asks again when `focused` did
// not move — coming back from
// another app. See
@@ -2473,7 +2575,11 @@ class _TerminalPageState extends State<TerminalPage>
// `PhoneShell`'s Scaffold has already resized for it —
// the same resize that empties this page's MediaQuery
// insets (see [didChangeMetrics]).
- if (session != null)
+ // Find in terminal takes the key bar's place: on the keyboard while
+ // its field has one, at the terminal's foot while not.
+ if (session != null && _find != null)
+ TerminalFindBar(find: _find!, onClose: _closeFind)
+ else if (session != null)
TerminalInputDock(
session: session,
keyboardUp: _keyBarUp,
@@ -2571,7 +2677,7 @@ class _TerminalPageState extends State<TerminalPage>
// call (2026-09-27): "we don't need the scrolling indicator". The history
// scrolls like any list; scrolling down is the way back to the stream.
// The line above the mic: what is going on, in a few words — see [_statusLine].
- if (!_ownsInput)
+ if (!_ownsInput && _find == null)
Positioned(
left: 0,
right: 0,
@@ -2589,7 +2695,7 @@ class _TerminalPageState extends State<TerminalPage>
),
),
// How loud the take is: a glow behind the mic that swells with the voice.
- if (!_ownsInput)
+ if (!_ownsInput && _find == null)
ListenableBuilder(
listenable: widget.voice,
builder: (context, _) =>
@@ -2615,7 +2721,7 @@ class _TerminalPageState extends State<TerminalPage>
// way the home screen stays whole under Siri. Laid over the
// whole page so its capsule, rising as it talks, still takes
// taps.
- if (!_ownsInput)
+ if (!_ownsInput && _find == null)
Positioned(
left: 0,
right: 0,
@@ -2777,6 +2883,13 @@ class _TerminalPageState extends State<TerminalPage>
// terminal only being watched too — but only while there is a reply on it to copy.
if (session != null && hasLastReply(session))
_copyReplyAction(session),
+ // The desktop's ⌘F. Only with a terminal on screen to search.
+ if (session != null)
+ PhoneSheetAction(
+ icon: LucideIcons.textSearch300,
+ label: 'Find in terminal',
+ onTap: _openFind,
+ ),
..._agentActions(agent),
],
),
@@ -4446,3 +4559,23 @@ class _SampleEndCard extends StatelessWidget {
);
}
}
+
+/// Find's hold on the back gesture — see `_TerminalPageState._findBack`.
+class _FindBack extends PopEntry<Object?> {
+ _FindBack(this.onBack);
+
+ final VoidCallback onBack;
+
+ @override
+ final ValueNotifier<bool> canPopNotifier = ValueNotifier(false);
+
+ /// ⚠️ **After the route is done asking, not while it asks.** The route walks its entries to tell
+ /// each of them, and closing Find takes this one off the route — taken off mid-walk, the walk
+ /// threw (`ConcurrentModificationError`) and Back did nothing.
+ @override
+ void onPopInvokedWithResult(bool didPop, Object? result) {
+ if (!didPop) scheduleMicrotask(onBack);
+ }
+
+ void dispose() => canPopNotifier.dispose();
+}
diff --git a/mobile/lib/terminal/terminal_find.dart b/mobile/lib/terminal/terminal_find.dart
new file mode 100644
index 000000000..e2a06f190
--- /dev/null
+++ b/mobile/lib/terminal/terminal_find.dart
@@ -0,0 +1,122 @@
+import 'package:flutter/foundation.dart';
+import 'package:flutter/scheduler.dart';
+
+/// The panel searching a terminal, as the bar asking it sees it — see [TerminalFindController].
+abstract interface class TerminalFindTarget {
+ /// Find [query] (empty finds nothing), from where the reader is.
+ void findQuery(String query);
+
+ /// The next match (`1`) or the one before (`-1`), wrapping at either end.
+ void findStep(int delta);
+}
+
+/// Find in terminal: the phone's half of the desktop's ⌘F, between the bar that asks and the panel
+/// that searches.
+///
+/// ⚠️ **Two owners, one object.** The bar sits where the key bar does, at the page's foot over the
+/// keyboard; the terminal it searches, its highlight and its scroll position are the panel's, several
+/// widgets away — and the panel is the one that sees the terminal replaced by every keyframe (each
+/// keyboard raised or lowered ends in one), which is when its search has to be rebuilt. So the bar
+/// writes what to find here, the panel ([TerminalFindTarget]) does the finding with a
+/// `TerminalSearch` and writes back what it found, and neither reaches into the other.
+class TerminalFindController extends ChangeNotifier {
+ String _query = '';
+ int _count = 0;
+ int _selected = -1;
+ bool _searching = false;
+ bool _hasSnapshot = false;
+ TerminalFindTarget? _target;
+ bool _disposed = false;
+
+ /// What the bar is finding, as typed.
+ String get query => _query;
+
+ /// How many matches the panel found — 0 while none, or while nothing is asked.
+ int get count => _count;
+
+ /// The match the terminal shows, from 0, or -1 for none.
+ int get selected => _selected;
+
+ /// A scan still running, and whether its answer is in yet: until it is, the count is a guess.
+ bool get searching => _searching;
+ bool get hasSnapshot => _hasSnapshot;
+
+ /// The desktop bar's count, in its words: empty with nothing asked, `…` while the first answer is
+ /// on its way, then `3/12` — `0/0` for none.
+ String get status => _query.isEmpty
+ ? ''
+ : _searching && !_hasSnapshot
+ ? '…'
+ : '${_selected + 1}/$_count';
+
+ /// Nothing matches what was asked: the bar says so in red, as the desktop's does.
+ bool get missed => _query.isNotEmpty && !_searching && _count == 0;
+
+ /// The bar's words changed.
+ void setQuery(String value) {
+ if (value == _query) return;
+ _query = value;
+ _target?.findQuery(value);
+ _notify();
+ }
+
+ /// ↓ and ↑. Nothing to step through says nothing.
+ void next() => _target?.findStep(1);
+ void previous() => _target?.findStep(-1);
+
+ /// The panel taking the search on — at once with whatever was typed before it attached, so a bar
+ /// opened over a pane that remounted keeps its words.
+ void attach(TerminalFindTarget target) {
+ _target = target;
+ target.findQuery(_query);
+ }
+
+ /// The panel letting go. Only the panel that attached can: a remounted one attaches before the old
+ /// one is disposed, and the old one's goodbye must not take the new one's place.
+ void detach(TerminalFindTarget target) {
+ if (!identical(_target, target)) return;
+ _target = null;
+ report(count: 0, selected: -1, searching: false, hasSnapshot: false);
+ }
+
+ /// What the panel found.
+ void report({
+ required int count,
+ required int selected,
+ required bool searching,
+ required bool hasSnapshot,
+ }) {
+ if (count == _count &&
+ selected == _selected &&
+ searching == _searching &&
+ hasSnapshot == _hasSnapshot) {
+ return;
+ }
+ _count = count;
+ _selected = selected;
+ _searching = searching;
+ _hasSnapshot = hasSnapshot;
+ _notify();
+ }
+
+ /// After the frame when told mid-build: the panel reports from its search's listener, which a
+ /// resize can fire during layout, and the bar rebuilding then would be a build inside a build.
+ void _notify() {
+ if (_disposed) return;
+ if (SchedulerBinding.instance.schedulerPhase ==
+ SchedulerPhase.persistentCallbacks) {
+ SchedulerBinding.instance.addPostFrameCallback((_) {
+ if (!_disposed) notifyListeners();
+ });
+ return;
+ }
+ notifyListeners();
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _target = null;
+ super.dispose();
+ }
+}
diff --git a/mobile/lib/terminal/terminal_search.dart b/mobile/lib/terminal/terminal_search.dart
new file mode 100644
index 000000000..0c50b9395
--- /dev/null
+++ b/mobile/lib/terminal/terminal_search.dart
@@ -0,0 +1,451 @@
+// A copy of the desktop's `lib/terminal/terminal_search.dart`, kept one: the phone's Find in
+// terminal and the desktop's ⌘F search the same buffer the same way, so a phrase found on one is
+// found on the other. Its tests are the desktop's too (`test/terminal_search_test.dart`).
+import 'dart:async';
+import 'dart:collection';
+import 'dart:typed_data';
+
+import 'package:flutter/foundation.dart';
+import 'package:xterm/xterm.dart';
+
+/// An on-demand index of the current terminal buffer. It never reads a file,
+/// queries a daemon, or sends input. Unchanged rows keep their decoded text;
+/// long scans yield to the event loop, and only the selected hit owns an anchor.
+class TerminalSearch extends ChangeNotifier {
+ TerminalSearch(this.terminal, {CellOffset? origin}) {
+ _origin = origin;
+ }
+
+ final Terminal terminal;
+ String _query = '';
+ bool _caseSensitive = false;
+ bool _enabled = true;
+ bool _disposed = false;
+ bool _listening = false;
+ bool _running = false;
+ bool _dirty = false;
+ int _generation = 0;
+ int _indexedGeneration = -1;
+ int _pendingStep = 0;
+ Timer? _timer;
+ Timer? _yieldTimer;
+ Completer<void>? _yieldResume;
+ Completer<void>? _settled;
+ Buffer? _buffer;
+ CellOffset? _origin;
+ CellAnchor? _selectionAnchor;
+ Map<BufferLine, _SearchLine> _lines = HashMap.identity();
+ Map<BufferLine, _SearchGroup> _cache = HashMap.identity();
+ List<_SearchGroup> _groups = [];
+ int _count = 0;
+ int _selected = -1;
+ _SearchGroup? _selectedGroup;
+ int _selectedInGroup = 0;
+
+ String get query => _query;
+ bool get caseSensitive => _caseSensitive;
+ bool get searching => _running || _dirty || _timer != null;
+ bool get hasSnapshot =>
+ _indexedGeneration == _generation && identical(_buffer, terminal.buffer);
+ int get count => _count;
+ int get selected => _selected;
+ Future<void> get settled => _settled?.future ?? Future.value();
+
+ BufferRangeLine? get match =>
+ identical(_buffer, terminal.buffer) && _selectedGroup?.valid == true
+ ? _selectedGroup!.rangeAt(_selectedInGroup)
+ : null;
+
+ void setQuery(String value, {bool? caseSensitive}) {
+ final sensitive = caseSensitive ?? _caseSensitive;
+ if (_query == value && _caseSensitive == sensitive) return;
+ _query = value;
+ _caseSensitive = sensitive;
+ _generation++;
+ _pendingStep = 0;
+ _clearResults();
+ _listen(_enabled && _query.isNotEmpty);
+ if (_query.isEmpty) {
+ _releaseIndex();
+ } else {
+ _request();
+ }
+ notifyListeners();
+ }
+
+ /// Hidden/covered find bars retain only their query and selected location.
+ /// Returning rebuilds from current output instead of indexing hidden traffic.
+ void setEnabled(bool value) {
+ if (_enabled == value || _disposed) return;
+ _enabled = value;
+ _generation++;
+ _listen(value && _query.isNotEmpty);
+ if (value) {
+ _request();
+ } else {
+ _releaseIndex();
+ }
+ }
+
+ void _listen(bool value) {
+ if (_listening == value) return;
+ _listening = value;
+ if (value) {
+ terminal.addListener(_onOutput);
+ terminal.addResizeListener(_onResize);
+ } else {
+ terminal.removeListener(_onOutput);
+ terminal.removeResizeListener(_onResize);
+ }
+ }
+
+ void _onOutput() {
+ _request();
+ // Output can replace the active buffer or overwrite a highlighted row.
+ // Let the view remove an invalid highlight before its next paint.
+ notifyListeners();
+ }
+
+ // Resize runs during renderer layout. Defer UI notifications to the scan's
+ // event-loop turn so reflow never calls setState during layout.
+ void _onResize() => _request();
+
+ void _request() {
+ if (_disposed || !_enabled || _query.isEmpty) return;
+ _dirty = true;
+ _settled ??= Completer<void>();
+ if (!_running) _timer ??= Timer(Duration.zero, () => unawaited(_scan()));
+ }
+
+ Future<void> _scan() async {
+ _timer = null;
+ if (_disposed || !_enabled || _query.isEmpty) return;
+ _running = true;
+ _dirty = false;
+ final generation = _generation;
+ final buffer = terminal.buffer;
+ final query = _query;
+ final sensitive = _caseSensitive;
+ final pattern = RegExp(
+ RegExp.escape(query),
+ caseSensitive: sensitive,
+ unicode: true,
+ );
+ final source = [
+ for (var i = 0; i < buffer.lines.length; i++) buffer.lines[i],
+ ];
+ final lines = HashMap<BufferLine, _SearchLine>.identity();
+ final cache = HashMap<BufferLine, _SearchGroup>.identity();
+ final groups = <_SearchGroup>[];
+ var logical = <_SearchLine>[];
+ final slice = Stopwatch()..start();
+ try {
+ for (var i = 0; i < source.length; i++) {
+ final line = source[i];
+ final cached = _lines[line];
+ final snapshot = cached != null && cached.valid
+ ? cached
+ : _SearchLine(line);
+ lines[line] = snapshot;
+ logical.add(snapshot);
+ if (i + 1 == source.length || !source[i + 1].isWrapped) {
+ final first = logical.first.line;
+ final previous = _cache[first];
+ final _SearchGroup group;
+ if (previous != null && previous.reuses(logical, query, sensitive)) {
+ group = previous;
+ } else {
+ final text = logical.length == 1
+ ? logical.single.text
+ : logical.map((line) => line.text).join();
+ final checkpoints = <int>[];
+ var hits = 0;
+ for (final hit in pattern.allMatches(text)) {
+ if (hits % _SearchGroup.stride == 0) checkpoints.add(hit.start);
+ hits++;
+ if (hits % 128 == 0 && slice.elapsedMicroseconds >= 1500) {
+ await _yieldScan();
+ if (_disposed || generation != _generation || !_enabled) return;
+ slice.reset();
+ }
+ }
+ group = _SearchGroup(
+ logical,
+ query,
+ sensitive,
+ pattern,
+ text,
+ Uint32List.fromList(checkpoints),
+ hits,
+ );
+ }
+ cache[first] = group;
+ if (group.count > 0 && group.valid) groups.add(group);
+ logical = [];
+ }
+ if (slice.elapsedMicroseconds >= 1500) {
+ await _yieldScan();
+ if (_disposed || generation != _generation || !_enabled) return;
+ slice.reset();
+ }
+ }
+ if (_disposed || generation != _generation || !_enabled) return;
+ _lines = lines;
+ _cache = cache;
+ _buffer = buffer;
+ _indexedGeneration = generation;
+ _groups = groups.where((group) => group.valid).toList(growable: false);
+ _count = _groups.fold(0, (count, group) => count + group.count);
+ final origin = _selectionAnchor?.attached == true
+ ? _selectionAnchor!.offset
+ : _origin;
+ var index = 0;
+ var found = false;
+ if (origin != null) {
+ for (final group in _groups) {
+ if (group.lines.last.line.index < origin.y) {
+ index += group.count;
+ continue;
+ }
+ final hit = group.indexAtOrAfter(origin);
+ index += hit;
+ if (hit < group.count) {
+ found = true;
+ break;
+ }
+ }
+ }
+ _select(_count == 0 ? -1 : ((found ? index : 0) + _pendingStep) % _count);
+ _pendingStep = 0;
+ } finally {
+ _running = false;
+ if (!_disposed) {
+ if (_dirty && _enabled && _query.isNotEmpty) {
+ _request();
+ } else {
+ _settled?.complete();
+ _settled = null;
+ }
+ notifyListeners();
+ }
+ }
+ }
+
+ void step(int delta) {
+ if (_query.isEmpty || !_enabled) return;
+ if (searching && !hasSnapshot) {
+ _pendingStep += delta;
+ return;
+ }
+ if (_count == 0) return;
+ final target = (_selected + delta) % _count;
+ var index = target;
+ for (final group in _groups) {
+ if (index < group.count) {
+ if (!group.valid) {
+ _pendingStep += delta;
+ _request();
+ return;
+ }
+ break;
+ }
+ index -= group.count;
+ }
+ _select(target);
+ notifyListeners();
+ }
+
+ void _select(int index) {
+ _selected = index;
+ _selectedGroup = null;
+ if (index < 0) return;
+ for (final group in _groups) {
+ if (index >= group.count) {
+ index -= group.count;
+ continue;
+ }
+ _selectedGroup = group;
+ _selectedInGroup = index;
+ final range = match;
+ if (range != null) {
+ _selectionAnchor?.dispose();
+ _selectionAnchor = terminal.buffer.createAnchorFromOffset(range.begin);
+ _origin = range.begin;
+ }
+ break;
+ }
+ }
+
+ void _clearResults() {
+ _groups = [];
+ _count = 0;
+ _selected = -1;
+ _selectedGroup = null;
+ }
+
+ Future<void> _yieldScan() {
+ final resume = Completer<void>();
+ _yieldResume = resume;
+ _yieldTimer = Timer(Duration.zero, () {
+ _yieldTimer = null;
+ _yieldResume = null;
+ resume.complete();
+ });
+ return resume.future;
+ }
+
+ void _releaseIndex() {
+ _yieldTimer?.cancel();
+ _yieldTimer = null;
+ final resume = _yieldResume;
+ _yieldResume = null;
+ resume?.complete();
+ _timer?.cancel();
+ _timer = null;
+ _dirty = false;
+ _lines.clear();
+ _cache.clear();
+ _clearResults();
+ if (!_running) {
+ _settled?.complete();
+ _settled = null;
+ }
+ }
+
+ @override
+ void dispose() {
+ _disposed = true;
+ _generation++;
+ _listen(false);
+ _releaseIndex();
+ _selectionAnchor?.dispose();
+ _selectionAnchor = null;
+ _settled?.complete();
+ _settled = null;
+ super.dispose();
+ }
+}
+
+class _SearchLine {
+ _SearchLine(this.line)
+ : version = line.textVersion,
+ wrapped = line.isWrapped,
+ text = line.getText();
+ final BufferLine line;
+ final int version;
+ final bool wrapped;
+ final String text;
+ bool get valid =>
+ line.attached && line.textVersion == version && line.isWrapped == wrapped;
+
+ int cellAt(int offset) {
+ if (offset <= 0) return 0;
+ var chars = 0;
+ var end = 0;
+ for (var x = 0; x < line.length; x++) {
+ final code = line.getCodePoint(x);
+ if (code == 0 && x > 0 && line.getWidth(x - 1) == 2) continue;
+ chars += code > 0xffff ? 2 : 1;
+ end = x + (line.getWidth(x) > 1 ? line.getWidth(x) : 1);
+ if (chars >= offset) break;
+ }
+ return end;
+ }
+}
+
+class _SearchGroup {
+ _SearchGroup(
+ this.lines,
+ this.query,
+ this.sensitive,
+ this.pattern,
+ this.text,
+ this.checkpoints,
+ this.count,
+ ) {
+ var offset = 0;
+ starts = [
+ for (final line in lines) (offset += line.text.length) - line.text.length,
+ ];
+ }
+ // One integer per 64 matches, rather than a range/anchor for every character
+ // in a very repetitive log. Selecting a hit examines at most 64 candidates.
+ static const stride = 64;
+ final List<_SearchLine> lines;
+ final String query;
+ final bool sensitive;
+ final RegExp pattern;
+ final String text;
+ final Uint32List checkpoints;
+ final int count;
+ late final List<int> starts;
+ bool get valid {
+ for (var i = 0; i < lines.length; i++) {
+ if (!lines[i].valid ||
+ (i > 0 && lines[i].line.index != lines[i - 1].line.index + 1)) {
+ return false;
+ }
+ }
+ return true;
+ }
+
+ bool reuses(List<_SearchLine> other, String value, bool caseSensitive) =>
+ query == value && sensitive == caseSensitive && listEquals(lines, other);
+
+ int indexAtOrAfter(CellOffset origin) {
+ var row = 0;
+ while (row < lines.length && lines[row].line.index < origin.y) {
+ row++;
+ }
+ if (row == lines.length) return count;
+ final textOffset =
+ starts[row] +
+ (lines[row].line.index == origin.y
+ ? lines[row].line.getText(0, origin.x).length
+ : 0);
+ var low = 0;
+ var high = checkpoints.length - 1;
+ while (low < high) {
+ final middle = (low + high + 1) ~/ 2;
+ if (checkpoints[middle] <= textOffset) {
+ low = middle;
+ } else {
+ high = middle - 1;
+ }
+ }
+ var index = low * stride;
+ for (final hit in pattern.allMatches(text, checkpoints[low])) {
+ if (hit.start >= textOffset) return index;
+ index++;
+ }
+ return count;
+ }
+
+ BufferRangeLine rangeAt(int index) {
+ final hit = pattern
+ .allMatches(text, checkpoints[index ~/ stride])
+ .skip(index % stride)
+ .first;
+ return BufferRangeLine(
+ _cellAt(hit.start, end: false),
+ _cellAt(hit.end, end: true),
+ );
+ }
+
+ CellOffset _cellAt(int offset, {required bool end}) {
+ var low = 0;
+ var high = lines.length - 1;
+ while (low < high) {
+ final middle = (low + high + 1) ~/ 2;
+ if (starts[middle] < offset || (!end && starts[middle] == offset)) {
+ low = middle;
+ } else {
+ high = middle - 1;
+ }
+ }
+ return CellOffset(
+ lines[low].cellAt(offset - starts[low]),
+ lines[low].line.index,
+ );
+ }
+}
diff --git a/mobile/lib/widgets/terminal_panel.dart b/mobile/lib/widgets/terminal_panel.dart
index 2ea43fe43..6b9a93aa7 100644
--- a/mobile/lib/widgets/terminal_panel.dart
+++ b/mobile/lib/widgets/terminal_panel.dart
@@ -14,6 +14,7 @@ import '../state/app_state.dart';
import '../terminal/terminal_snapshot.dart';
import '../terminal/terminal_binary.dart';
+import '../terminal/terminal_find.dart';
import '../terminal/terminal_font_store.dart';
import '../terminal/terminal_link_opener.dart';
import '../terminal/remote_media_download.dart';
@@ -21,6 +22,7 @@ import '../terminal/remote_scroll_physics.dart';
import '../terminal/terminal_links.dart';
import '../terminal/output_blocks.dart';
import '../terminal/terminal_prompt_zone.dart';
+import '../terminal/terminal_search.dart';
import '../phone/media_preview_page.dart';
import '../phone/tty.dart';
import '../terminal/terminal_session.dart';
@@ -131,6 +133,10 @@ class TerminalPanel extends StatefulWidget {
final TerminalLinkOpener? linkOpener;
final RemoteMediaDownloader? mediaDownloader;
+ /// Find in terminal, while the page's bar is up — see [TerminalFindController]. The panel searches
+ /// what it shows, lights the match and scrolls to it; null puts the reader back where they were.
+ final TerminalFindController? find;
+
const TerminalPanel({
super.key,
required this.notifier,
@@ -148,6 +154,7 @@ class TerminalPanel extends StatefulWidget {
this.onPaste,
this.linkOpener,
this.mediaDownloader,
+ this.find,
});
@override
@@ -156,7 +163,7 @@ class TerminalPanel extends StatefulWidget {
class _TerminalPanelState extends State<TerminalPanel>
with WidgetsBindingObserver
- implements TerminalViewport {
+ implements TerminalViewport, TerminalFindTarget {
static const _dialScale = 2.5;
static const _dialStopVelocity = 40.0;
static const _dialDecayPerSecond = 0.002;
@@ -234,6 +241,20 @@ class _TerminalPanelState extends State<TerminalPanel>
bool _openingLink = false;
bool _linkRefreshPending = false;
bool _followTail = true;
+
+ /// Find in terminal — the desktop panel's, field for field ([TerminalPanel.find]). [_find] searches
+ /// the terminal on show; [_findHighlight] lights its match, painted for [_findPaintedRange] in
+ /// [_findPaintedBuffer]; a reveal is owed while [_findRevealPending]. Where the reader was when
+ /// Find opened is kept in [_findOriginLine] and its neighbours, for closing to go back to.
+ TerminalSearch? _find;
+ TerminalHighlight? _findHighlight;
+ Buffer? _findPaintedBuffer;
+ BufferRangeLine? _findPaintedRange;
+ bool _findRevealPending = false;
+ Buffer? _findOriginBuffer;
+ CellAnchor? _findOriginLine;
+ double _findOriginFraction = 0;
+ bool _findOriginAtEnd = true;
TerminalStyle _terminalFont = terminalFontStore.value;
bool _observingLinkModifiers = false;
late final RemoteMediaDownloader _mediaDownloader;
@@ -260,6 +281,12 @@ class _TerminalPanelState extends State<TerminalPanel>
// directly rather than through a builder.
terminalThemeStore.addListener(_onFontChanged);
_afterTerminalMounted();
+ // After the first layout: where the reader is is read off the laid-out view.
+ if (widget.find != null) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _openFind();
+ });
+ }
}
@override
@@ -299,6 +326,21 @@ class _TerminalPanelState extends State<TerminalPanel>
void didUpdateWidget(TerminalPanel oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.jumpToEndRequest != widget.jumpToEndRequest) _jumpToEnd();
+ // Another controller, or none: the search it was running belongs to the bar that went.
+ if (!identical(oldWidget.find, widget.find)) {
+ oldWidget.find?.detach(this);
+ if (widget.find == null) {
+ _closeFind();
+ } else {
+ _closeFind(restore: false);
+ _openFind();
+ }
+ }
+ // A search runs over one terminal; another session is another terminal, searched afresh once
+ // it has laid out.
+ final refind =
+ !identical(oldWidget.session, widget.session) && _find != null;
+ if (refind) _closeFind(restore: false, detach: false);
if (!identical(oldWidget.session, widget.session)) {
_previewCancellation?.cancel();
_previewProgress.value = null;
@@ -331,6 +373,11 @@ class _TerminalPanelState extends State<TerminalPanel>
_cursorBlinkVisible = true;
widget.session.setCursorBlinkPhase(true);
_afterTerminalMounted();
+ if (refind) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted) _openFind();
+ });
+ }
}
if (oldWidget.visible && !widget.visible) {
_promptMenuCell = null;
@@ -363,6 +410,8 @@ class _TerminalPanelState extends State<TerminalPanel>
@override
void dispose() {
+ widget.find?.detach(this);
+ _closeFind(restore: false, detach: false);
WidgetsBinding.instance.removeObserver(this);
_tickerMode?.removeListener(_syncCursorBlink);
_previewCancellation?.cancel();
@@ -487,16 +536,30 @@ class _TerminalPanelState extends State<TerminalPanel>
? position.pixels / lineHeight - viewportRow!
: 0.0;
final atEnd = _followTail || position == null;
+ // Find's place in the old screen, carried to the new one — the desktop's rule. A keyframe
+ // replaces the terminal on every keyboard raised or lowered, and the search field's own
+ // keyboard is one: without this, the first letter typed would end the search it started.
+ final originRow = _findOriginLine?.attached == true
+ ? _findOriginLine!.y
+ : null;
+ final originFraction = _findOriginFraction;
+ final originAtEnd = _findOriginAtEnd;
+ final match = _find?.match?.begin;
final selection = _controller.selection;
final selectedText = selection == null ? null : previous.getText(selection);
final locations = remapTerminalRows(previous, next, [
if (!atEnd) ?viewportRow,
+ ?originRow,
+ ?match?.y,
?selection?.begin.y,
?selection?.end.y,
]);
int row(int old) => locations[old] ?? old.clamp(0, next.lines.length - 1);
CellOffset location(CellOffset old) =>
CellOffset(old.x.clamp(0, terminal.viewWidth - 1), row(old.y));
+ final wasFinding = _find != null;
+ // Rebuilt below over the new terminal; the bar stays attached and keeps its words.
+ _closeFind(restore: false, detach: false);
// Selection anchors belong to a specific circular buffer. Detach them
// before the TerminalView starts laying out the replacement terminal.
_controller.clearSelection();
@@ -535,6 +598,20 @@ class _TerminalPanelState extends State<TerminalPanel>
);
}
}
+ if (wasFinding) {
+ _findOriginBuffer = next;
+ _findOriginAtEnd = originAtEnd;
+ _findOriginFraction = originFraction;
+ if (originRow != null) {
+ _findOriginLine = next.createAnchor(0, row(originRow));
+ }
+ _findRevealPending = true;
+ _find = TerminalSearch(
+ terminal,
+ origin: match == null ? null : location(match),
+ )..addListener(_onFindChanged);
+ _find!.setQuery(widget.find?.query ?? '');
+ }
_followTail = atEnd;
// ⚠️ **The keyboard is claimed only by a view that does not hold the focus.** One that does kept
// its input connection across the swap (`keepsInputAcrossTerminals`), so claiming it again can
@@ -749,10 +826,148 @@ class _TerminalPanelState extends State<TerminalPanel>
}
if (scrollToEnd && _followTail) view.scrollToBottom();
if (claimFocus) _claimFocus(view);
+ if (_find != null) _onFindChanged();
if (_linkPointerPosition != null) _hoverLink(_linkPointerPosition);
});
}
+ /// Starts Find over the terminal on show, from the row at the top of the view — the desktop's
+ /// origin, so the first match is the first one at or below where the reader is looking.
+ void _openFind() {
+ final find = widget.find;
+ if (!mounted || find == null || _find != null) return;
+ CellOffset? origin;
+ final view = _laidOutTerminalView();
+ if (view != null && _scrollController.hasClients) {
+ final position = _scrollController.position;
+ final height = view.renderTerminal.lineHeight;
+ if (height > 0 && position.hasPixels && position.hasContentDimensions) {
+ final row = (position.pixels / height).floor().clamp(
+ 0,
+ _viewTerminal.buffer.lines.length - 1,
+ );
+ _findOriginBuffer = _viewTerminal.buffer;
+ _findOriginLine = _findOriginBuffer!.createAnchor(0, row);
+ _findOriginFraction = position.pixels / height - row;
+ _findOriginAtEnd = position.maxScrollExtent - position.pixels < 1;
+ origin = CellOffset(0, row);
+ }
+ }
+ _find = TerminalSearch(_viewTerminal, origin: origin)
+ ..addListener(_onFindChanged);
+ _findRevealPending = true;
+ find.attach(this);
+ }
+
+ @override
+ void findQuery(String query) {
+ _findRevealPending = true;
+ _find?.setQuery(query);
+ }
+
+ @override
+ void findStep(int delta) {
+ _findRevealPending = true;
+ _find?.step(delta);
+ }
+
+ /// The search moved: say so to the bar, light the match, and bring it into view.
+ ///
+ /// The reveal is the desktop's — scroll only as far as the match needs — with a taller margin at
+ /// the top: the phone's title lies over the terminal's first rows, and a match revealed under it
+ /// would be found and not seen.
+ void _onFindChanged() {
+ final search = _find;
+ if (!mounted || search == null) return;
+ widget.find?.report(
+ count: search.count,
+ selected: search.selected,
+ searching: search.searching,
+ hasSnapshot: search.hasSnapshot,
+ );
+ if (!widget.visible) return;
+ final range = search.match;
+ if (range != _findPaintedRange ||
+ !identical(_findPaintedBuffer, _viewTerminal.buffer)) {
+ _clearFindHighlight();
+ if (range != null) {
+ _findPaintedBuffer = _viewTerminal.buffer;
+ _findPaintedRange = range;
+ _findHighlight = _controller.highlight(
+ p1: _viewTerminal.buffer.createAnchorFromOffset(range.begin),
+ p2: _viewTerminal.buffer.createAnchorFromOffset(range.end),
+ color: const Color(0x99cf8e25),
+ );
+ }
+ }
+ if (_findRevealPending && search.hasSnapshot && range != null) {
+ final render = _laidOutTerminalView()?.renderTerminal;
+ if (render == null || !_scrollController.hasClients) return;
+ final position = _scrollController.position;
+ if (!position.hasPixels || !position.hasContentDimensions) return;
+ _findRevealPending = false;
+ final line = render.lineHeight;
+ final top = range.begin.y * line;
+ final bottom = (range.end.y + 1) * line;
+ final above = line * 3;
+ final safeTop = position.pixels + above;
+ final safeBottom = position.pixels + position.viewportDimension - 10;
+ final offset = top < safeTop
+ ? top - above
+ : bottom > safeBottom
+ ? bottom - position.viewportDimension + 10
+ : position.pixels;
+ final target = offset.clamp(
+ position.minScrollExtent,
+ position.maxScrollExtent,
+ );
+ if (target != position.pixels) position.jumpTo(target);
+ }
+ }
+
+ void _clearFindHighlight() {
+ final highlight = _findHighlight;
+ _findHighlight = null;
+ _findPaintedBuffer = null;
+ _findPaintedRange = null;
+ if (highlight == null) return;
+ highlight.dispose();
+ highlight.p1.dispose();
+ highlight.p2.dispose();
+ }
+
+ /// Ends the search: the highlight goes, and with [restore] the reader goes back to where they
+ /// were when Find opened — the end of the output, if that is where they were. [detach] lets the
+ /// bar go too; a search rebuilt over a new terminal keeps it.
+ void _closeFind({bool restore = true, bool detach = true}) {
+ final search = _find;
+ if (search == null) return;
+ _find = null;
+ search.removeListener(_onFindChanged);
+ search.dispose();
+ _clearFindHighlight();
+ if (detach) widget.find?.detach(this);
+ if (restore &&
+ identical(_findOriginBuffer, _viewTerminal.buffer) &&
+ _scrollController.hasClients) {
+ final height = _laidOutTerminalView()?.renderTerminal.lineHeight;
+ final position = _scrollController.position;
+ if (height != null && position.hasContentDimensions) {
+ final offset = _findOriginAtEnd
+ ? position.maxScrollExtent
+ : _findOriginLine?.attached == true
+ ? (_findOriginLine!.y + _findOriginFraction) * height
+ : 0.0;
+ position.jumpTo(
+ offset.clamp(position.minScrollExtent, position.maxScrollExtent),
+ );
+ }
+ }
+ _findOriginLine?.dispose();
+ _findOriginLine = null;
+ _findOriginBuffer = null;
+ }
+
@override
void scroll(int phase, int dy, int velocity) {
if (phase == 0) _cancelDialInertia();
diff --git a/mobile/test/phone_edge/focus_behavior_test.dart b/mobile/test/phone_edge/focus_behavior_test.dart
index 31557825f..199a9d69c 100644
--- a/mobile/test/phone_edge/focus_behavior_test.dart
+++ b/mobile/test/phone_edge/focus_behavior_test.dart
@@ -13,6 +13,7 @@ import 'package:harness_mobile/phone/phone_search_catalog.dart'
show phoneAgentId;
import 'package:harness_mobile/phone/phone_shell_scope.dart';
import 'package:harness_mobile/phone/terminal_file_send.dart';
+import 'package:harness_mobile/phone/terminal_find_bar.dart';
import 'package:harness_mobile/phone/terminal_page.dart';
import 'package:harness_mobile/phone/terminal_search.dart';
import 'package:harness_mobile/phone/settings_page.dart';
@@ -335,6 +336,161 @@ void main() {
});
});
+ // The desktop's ⌘F: the phone could not search what a harness had said at all — a long build's
+ // one error line was found by scrolling and reading.
+ group('find in terminal', () {
+ Finder bar() => find.byKey(const ValueKey('terminal-find-bar'));
+ Finder field() =>
+ find.descendant(of: bar(), matching: find.byType(TextField));
+ String status(WidgetTester tester) =>
+ (tester.widget<Text>(
+ find.descendant(
+ of: find.byKey(const ValueKey('terminal-find-status')),
+ matching: find.byType(Text),
+ ),
+ ).data ??
+ '')
+ .trim();
+
+ /// The page, its terminal holding [lines], and Find opened from the `⋯` menu.
+ Future<_Focus> openFind(
+ WidgetTester tester, {
+ String lines = 'row 1 marker\r\nrow 2\r\nrow 3 marker\r\n',
+ }) async {
+ final focus = await _Focus.open(tester);
+ focus.session.terminal.write(lines);
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await frames(tester);
+ await tester.tap(find.text('Find in terminal'));
+ await frames(tester);
+ return focus;
+ }
+
+ Future<void> search(WidgetTester tester, String query) async {
+ await tester.enterText(field(), query);
+ await frames(tester);
+ }
+
+ testWidgets('opens from the menu with its field focused, counts and steps, '
+ 'and nothing typed reaches the shell', (tester) async {
+ final focus = await openFind(tester);
+
+ expect(bar(), findsOneWidget);
+ expect(
+ tester.binding.focusManager.primaryFocus?.context
+ ?.findAncestorWidgetOfExactType<TextField>(),
+ isNotNull,
+ reason: 'the field has the keyboard',
+ );
+ await search(tester, 'marker');
+ expect(status(tester), '1/2');
+
+ await tester.tap(find.byKey(const ValueKey('terminal-find-next')));
+ await frames(tester);
+ expect(status(tester), '2/2');
+ await tester.tap(find.byKey(const ValueKey('terminal-find-previous')));
+ await frames(tester);
+ expect(status(tester), '1/2');
+
+ expect(focus.typed, isEmpty, reason: 'the query is the bar’s');
+ await focus.close();
+ });
+
+ testWidgets('nothing found reads 0/0, and ↑ ↓ take no tap', (tester) async {
+ final focus = await openFind(tester);
+ await search(tester, 'needle');
+
+ expect(status(tester), '0/0');
+ final next = tester.widget<IconButton>(
+ find.byKey(const ValueKey('terminal-find-next')),
+ );
+ expect(next.onPressed, isNull);
+ await focus.close();
+ });
+
+ // ⚠️ Every keyboard raised or lowered ends in a keyframe that replaces the terminal — Find's
+ // own field's keyboard among them. Read as the terminal's, that keyboard handed the input
+ // connection back to the panel, and the rest of the query went to the shell.
+ testWidgets('a keyframe while typing keeps the search, and the query out of '
+ 'the shell', (tester) async {
+ final focus = await openFind(tester);
+ await search(tester, 'mar');
+ // The field's keyboard, up — the one the terminal must not take for its own.
+ raiseKeyboard(tester);
+ await frames(tester);
+ // What the machine sends after the resize the field's keyboard caused: a new screen.
+ await focus.session.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: focus.session.streamId!,
+ seq: 1000,
+ bytes: Uint8List.fromList(
+ utf8.encode('one marker\r\nanother marker\r\n'),
+ ),
+ compressed: false,
+ cols: focus.session.terminal.viewWidth,
+ rows: focus.session.terminal.viewHeight,
+ ),
+ );
+ await tester.pump(const Duration(milliseconds: 250));
+ await frames(tester);
+ expect(
+ tester.binding.focusManager.primaryFocus?.context
+ ?.findAncestorWidgetOfExactType<TerminalFindBar>(),
+ isNotNull,
+ reason: 'the keyboard is still the field’s after the terminal was replaced',
+ );
+
+ await search(tester, 'marker');
+ // Both found on the new screen; which one is lit follows the match carried across.
+ expect(status(tester), matches(RegExp(r'^[12]/2$')));
+ expect(focus.typed, isEmpty);
+ await focus.close();
+ });
+
+ testWidgets('× and Back put it away, and the page stays', (tester) async {
+ final focus = await openFind(tester);
+ await tester.tap(find.byKey(const ValueKey('terminal-find-close')));
+ await frames(tester);
+ expect(bar(), findsNothing);
+
+ await tester.tap(find.byKey(const ValueKey('terminal-title')));
+ await frames(tester);
+ await tester.tap(find.text('Find in terminal'));
+ await frames(tester);
+ expect(bar(), findsOneWidget);
+
+ await tester.binding.handlePopRoute();
+ await frames(tester);
+ expect(bar(), findsNothing, reason: 'Back closes Find first');
+ expect(find.byType(TerminalPage), findsOneWidget);
+ await focus.close();
+ });
+
+ // The keyboard-inset rule (`phone_shell.dart`): a bar on the keyboard sits exactly on it, never
+ // a second keyboard's height higher.
+ testWidgets('the bar sits on the keyboard, not two keyboards up', (
+ tester,
+ ) async {
+ final focus = await openFind(tester);
+ raiseKeyboard(tester);
+ await frames(tester);
+
+ final screen = tester.view.physicalSize.height / tester.view.devicePixelRatio;
+ final keyboard = tester.view.viewInsets.bottom / tester.view.devicePixelRatio;
+ expect(tester.getBottomLeft(bar()).dy, moreOrLessEquals(screen - keyboard, epsilon: 1));
+
+ lowerKeyboard(tester);
+ await frames(tester);
+ expect(
+ tester.getBottomLeft(bar()).dy,
+ greaterThan(screen - keyboard),
+ reason: 'back at the foot once the keyboard has gone',
+ );
+ await focus.close();
+ });
+ });
+
group('the menu', () {
Future<_Focus> openMenu(
WidgetTester tester, {
diff --git a/mobile/test/terminal_find_test.dart b/mobile/test/terminal_find_test.dart
new file mode 100644
index 000000000..05d861874
--- /dev/null
+++ b/mobile/test/terminal_find_test.dart
@@ -0,0 +1,281 @@
+import 'dart:convert';
+import 'dart:typed_data';
+
+import 'package:flutter/material.dart';
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/state/app_state.dart';
+import 'package:harness_mobile/terminal/terminal_binary.dart';
+import 'package:harness_mobile/terminal/terminal_find.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 [TerminalFindController] was asked, recorded in place of a panel.
+class _Target implements TerminalFindTarget {
+ final queries = <String>[];
+ final steps = <int>[];
+
+ @override
+ void findQuery(String query) => queries.add(query);
+
+ @override
+ void findStep(int delta) => steps.add(delta);
+}
+
+/// Find in terminal, below the bar: what the bar and the panel say to each other, and what the
+/// panel does with the terminal it shows — the desktop's ⌘F, on the phone.
+void main() {
+ group('the controller between the bar and the panel', () {
+ test('the count, in the desktop bar’s words', () {
+ final find = TerminalFindController();
+ addTearDown(find.dispose);
+ expect(find.status, '', reason: 'nothing asked, nothing said');
+
+ find.setQuery('error');
+ find.report(count: 0, selected: -1, searching: true, hasSnapshot: false);
+ expect(find.status, '…');
+ expect(find.missed, isFalse, reason: 'not known yet');
+
+ find.report(count: 12, selected: 2, searching: false, hasSnapshot: true);
+ expect(find.status, '3/12');
+
+ find.report(count: 0, selected: -1, searching: false, hasSnapshot: true);
+ expect(find.status, '0/0');
+ expect(find.missed, isTrue);
+ });
+
+ test('words typed before the panel attached reach it as it does', () {
+ final find = TerminalFindController();
+ addTearDown(find.dispose);
+ find.setQuery('error');
+
+ final target = _Target();
+ find.attach(target);
+ find.setQuery('errors');
+ find.next();
+ find.previous();
+
+ expect(target.queries, ['error', 'errors']);
+ expect(target.steps, [1, -1]);
+ });
+
+ test('only the panel that attached can let go', () {
+ final find = TerminalFindController();
+ addTearDown(find.dispose);
+ final old = _Target(), current = _Target();
+ find.attach(old);
+ // A remounted panel attaches before the old one is disposed.
+ find.attach(current);
+ find.detach(old);
+ find.next();
+ expect(current.steps, [1]);
+
+ find.report(count: 3, selected: 0, searching: false, hasSnapshot: true);
+ find.detach(current);
+ find.next();
+ expect(current.steps, [1], reason: 'nobody to step once let go');
+ expect(find.count, 0, reason: 'nothing found by nobody');
+ });
+
+ test('says so only when something changed', () {
+ final find = TerminalFindController();
+ addTearDown(find.dispose);
+ var heard = 0;
+ find.addListener(() => heard++);
+ find.report(count: 2, selected: 0, searching: false, hasSnapshot: true);
+ find.report(count: 2, selected: 0, searching: false, hasSnapshot: true);
+ find.setQuery('');
+ expect(heard, 1);
+ });
+ });
+
+ group('the panel', () {
+ late AppNotifier notifier;
+ setUp(() => notifier = panelNotifier());
+ tearDown(() => notifier.dispose());
+
+ TerminalSession session() {
+ final made = controllingSession();
+ addTearDown(made.dispose);
+ return made;
+ }
+
+ Future<void> pumpPanel(
+ WidgetTester tester,
+ TerminalSession session, {
+ TerminalFindController? find,
+ }) async {
+ await tester.pumpWidget(
+ MaterialApp(
+ home: Scaffold(
+ body: Align(
+ alignment: Alignment.topLeft,
+ child: SizedBox(
+ width: 400,
+ height: 320,
+ child: TerminalPanel(
+ key: const ValueKey('pane'),
+ notifier: notifier,
+ session: session,
+ focused: false,
+ find: find,
+ ),
+ ),
+ ),
+ ),
+ ),
+ );
+ await tester.pump();
+ }
+
+ ScrollPosition scroll(WidgetTester tester) => tester
+ .state<ScrollableState>(
+ find.descendant(
+ of: find.byType(TerminalView),
+ matching: find.byType(Scrollable),
+ ),
+ )
+ .position;
+
+ TerminalController controller(WidgetTester tester) =>
+ tester.widget<TerminalView>(find.byType(TerminalView)).controller!;
+
+ double lineHeight(WidgetTester tester) => tester
+ .state<TerminalViewState>(find.byType(TerminalView))
+ .renderTerminal
+ .lineHeight;
+
+ /// Two hundred rows of history, `marker` on rows 3 and 150, read at the end.
+ void history(TerminalSession session) {
+ for (var i = 0; i < 200; i++) {
+ session.terminal.write(
+ i == 3 || i == 150 ? 'row $i marker\r\n' : 'row $i\r\n',
+ );
+ }
+ }
+
+ /// The search's scans, done — they yield to the event loop between slices.
+ Future<void> scanned(WidgetTester tester) async {
+ for (var i = 0; i < 6; i++) {
+ await tester.pump(const Duration(milliseconds: 20));
+ }
+ }
+
+ testWidgets('finds what the terminal shows, lights it, brings it into view '
+ 'and says how many', (tester) async {
+ final pane = session();
+ history(pane);
+ final finding = TerminalFindController();
+ addTearDown(finding.dispose);
+ await pumpPanel(tester, pane);
+ await tester.pump();
+ final atEnd = scroll(tester).pixels;
+ expect(atEnd, scroll(tester).maxScrollExtent);
+
+ await pumpPanel(tester, pane, find: finding);
+ finding.setQuery('marker');
+ await scanned(tester);
+
+ expect(finding.count, 2);
+ expect(finding.status, '1/2');
+ expect(controller(tester).highlights, hasLength(1));
+ // Row 3, three rows clear of the top where the title lies over it.
+ expect(scroll(tester).pixels, 0);
+
+ finding.next();
+ await scanned(tester);
+ expect(finding.status, '2/2');
+ final line = lineHeight(tester);
+ final position = scroll(tester);
+ expect(
+ 150 * line,
+ inInclusiveRange(
+ position.pixels,
+ position.pixels + position.viewportDimension,
+ ),
+ reason: 'row 150 is on screen',
+ );
+ expect(controller(tester).highlights, hasLength(1));
+ });
+
+ testWidgets('nothing found says so and moves nothing', (tester) async {
+ final pane = session();
+ history(pane);
+ final finding = TerminalFindController();
+ addTearDown(finding.dispose);
+ await pumpPanel(tester, pane, find: finding);
+ await tester.pump();
+ final before = scroll(tester).pixels;
+
+ finding.setQuery('needle');
+ await scanned(tester);
+
+ expect(finding.status, '0/0');
+ expect(finding.missed, isTrue);
+ expect(controller(tester).highlights, isEmpty);
+ expect(scroll(tester).pixels, before);
+ });
+
+ testWidgets(
+ 'closed, the light goes and the reader is back where they were',
+ (tester) async {
+ final pane = session();
+ history(pane);
+ final finding = TerminalFindController();
+ addTearDown(finding.dispose);
+ await pumpPanel(tester, pane, find: finding);
+ await tester.pump();
+ finding.setQuery('marker');
+ await scanned(tester);
+ expect(scroll(tester).pixels, 0);
+
+ await pumpPanel(tester, pane);
+ await tester.pump();
+
+ expect(controller(tester).highlights, isEmpty);
+ expect(scroll(tester).pixels, scroll(tester).maxScrollExtent);
+ expect(finding.count, 0, reason: 'the panel let the bar go');
+ },
+ );
+
+ // The keyboard Find's own field raises resizes the pane, and the machine answers every resize
+ // with a keyframe that replaces the terminal: without carrying the search across, the first
+ // letter typed would end the search it started.
+ testWidgets('a keyframe replacing the terminal keeps the search and its '
+ 'words', (tester) async {
+ final pane = session();
+ final finding = TerminalFindController();
+ addTearDown(finding.dispose);
+ await pumpPanel(tester, pane, find: finding);
+ await tester.pump();
+ finding.setQuery('marker');
+ await scanned(tester);
+ expect(finding.count, 0);
+
+ await pane.handleBinary(
+ TerminalBinaryFrame(
+ kind: TerminalBinaryKind.keyframe,
+ streamId: 's',
+ seq: 0,
+ bytes: Uint8List.fromList(
+ utf8.encode('first marker\r\nthen another marker\r\n'),
+ ),
+ compressed: false,
+ cols: 40,
+ rows: 12,
+ ),
+ );
+ await tester.pump();
+ await scanned(tester);
+
+ expect(finding.query, 'marker');
+ expect(finding.count, 2);
+ expect(finding.status, '1/2');
+ expect(controller(tester).highlights, hasLength(1));
+ // The ack and the resize the keyframe asks for, sent before the test ends.
+ await tester.pump(const Duration(seconds: 2));
+ });
+ });
+}
diff --git a/mobile/test/terminal_search_test.dart b/mobile/test/terminal_search_test.dart
new file mode 100644
index 000000000..af0fd5a41
--- /dev/null
+++ b/mobile/test/terminal_search_test.dart
@@ -0,0 +1,170 @@
+// The desktop's `test/terminal_search_test.dart`, against the phone's copy of the search.
+import 'package:flutter_test/flutter_test.dart';
+import 'package:harness_mobile/terminal/terminal_search.dart';
+import 'package:xterm/xterm.dart';
+
+void main() {
+ test(
+ 'next match is immediate while unchanged results refresh with live output',
+ () async {
+ final terminal = Terminal()..resize(30, 5);
+ terminal.write('first marker\r\nsecond marker\r\n');
+ final search = TerminalSearch(terminal);
+ addTearDown(search.dispose);
+ search.setQuery('marker');
+ await search.settled;
+ expect(search.selected, 0);
+ terminal.write('progress continues');
+ expect(search.searching, isTrue);
+ search.step(1);
+ expect(search.selected, 1);
+ expect(search.match!.begin, const CellOffset(7, 1));
+ await search.settled;
+ expect(search.selected, 1);
+ expect(terminal.buffer.getText(search.match), 'marker');
+ },
+ );
+
+ test('literal find spans soft wrapping, respects hard lines, and maps wide Unicode cells', () async {
+ final terminal = Terminal(maxLines: 100)..resize(8, 3);
+ terminal.write('A界🙂 error[1]\r\nnext error[1]\r\n');
+ final search = TerminalSearch(terminal);
+ addTearDown(search.dispose);
+ search.setQuery('error[1]');
+ await search.settled;
+ expect(search.count, 2);
+ expect(terminal.buffer.getText(search.match), 'error[1]');
+ expect(search.match!.begin, const CellOffset(6, 0));
+ search.step(1);
+ expect(terminal.buffer.getText(search.match), 'error[1]');
+ search.step(1);
+ expect(search.selected, 0);
+ search.step(-1);
+ expect(search.selected, 1);
+ search.setQuery('界🙂');
+ await search.settled;
+ expect(search.count, 1);
+ expect(
+ search.match,
+ BufferRangeLine(const CellOffset(1, 0), const CellOffset(5, 0)),
+ );
+ search.setQuery('[1]next');
+ await search.settled;
+ expect(search.count, 0);
+ search.setQuery('ERROR[1]');
+ await search.settled;
+ expect(search.count, 2);
+ search.setQuery('ERROR[1]', caseSensitive: true);
+ await search.settled;
+ expect(search.count, 0);
+ });
+
+ test(
+ 'cursor-created gaps and non-ASCII case folding retain correct cells',
+ () async {
+ final terminal = Terminal()..resize(30, 4);
+ terminal.write('\x1b[1;4HÄpfel\x1b[1;12Hregion');
+ final search = TerminalSearch(terminal);
+ addTearDown(search.dispose);
+ search.setQuery('äPFEL region');
+ await search.settled;
+ expect(search.count, 1);
+ expect(search.match!.begin, const CellOffset(3, 0));
+ expect(search.match!.end, const CellOffset(17, 0));
+ },
+ );
+
+ test('output updates, erasure, buffer switches and reflow refresh without transport input', () async {
+ final sent = <String>[];
+ final terminal = Terminal(maxLines: 100, onOutput: sent.add)..resize(12, 4);
+ terminal.write('one marker\r\ntwo marker\r\n');
+ final search = TerminalSearch(terminal);
+ addTearDown(search.dispose);
+ search.setQuery('marker');
+ await search.settled;
+ search.step(1);
+ final anchor = terminal.buffer.createAnchorFromOffset(search.match!.begin);
+ addTearDown(anchor.dispose);
+ terminal.write('three marker\r\n');
+ await search.settled;
+ expect(search.count, 3);
+ expect(search.match!.begin, anchor.offset);
+ terminal.resize(7, 4);
+ await search.settled;
+ expect(search.count, 3);
+ expect(search.match!.begin, anchor.offset);
+ expect(terminal.buffer.getText(search.match), 'marker');
+ terminal.write('\x1b[?1049hAlternate marker');
+ expect(search.match, isNull);
+ await search.settled;
+ expect(search.count, 1);
+ terminal.write('\x1b[2J');
+ expect(search.match, isNull);
+ await search.settled;
+ expect(search.count, 0);
+ terminal.write('\x1b[?1049l');
+ await search.settled;
+ expect(search.count, 3);
+ expect(sent, isEmpty);
+ });
+
+ test('a long repeating wrapped line counts every match without an anchor per result', () async {
+ final terminal = Terminal(maxLines: 1000)..resize(100, 5);
+ terminal.write('a' * 50000);
+ final search = TerminalSearch(terminal, origin: const CellOffset(70, 490));
+ addTearDown(search.dispose);
+ search.setQuery('a');
+ await search.settled;
+ expect(search.count, 50000);
+ expect(search.selected, 49070);
+ expect(search.match!.begin, const CellOffset(70, 490));
+ search.step(50000 - 49070 - 1);
+ expect(search.selected, 49999);
+ search.step(1);
+ expect(search.selected, 0);
+ var anchors = 0;
+ terminal.buffer.lines.forEach((line) => anchors += line.anchors.length);
+ expect(anchors, 1);
+ });
+
+ test('hidden and disposed searches leave no output listener or retained match anchors', () async {
+ final terminal = Terminal(maxLines: 50)..resize(20, 3);
+ terminal.write('old marker\r\n');
+ final baseline = terminal.listeners.length;
+ final search = TerminalSearch(terminal);
+ expect(terminal.listeners.length, baseline);
+ search.setQuery('marker');
+ await search.settled;
+ expect(terminal.listeners.length, baseline + 1);
+ search.setEnabled(false);
+ expect(terminal.listeners.length, baseline);
+ expect(search.count, 0);
+ terminal.write('new marker\r\n');
+ search.setEnabled(true);
+ await search.settled;
+ expect(search.count, 2);
+ search.dispose();
+ expect(terminal.listeners.length, baseline);
+ terminal.buffer.lines.forEach((line) => expect(line.anchors, isEmpty));
+ });
+
+ test('a new query wins over an in-flight scan and scrollback eviction drops old hits', () async {
+ final terminal = Terminal(maxLines: 500)..resize(80, 4);
+ terminal.write('old marker\r\n' * 450);
+ final search = TerminalSearch(terminal);
+ addTearDown(search.dispose);
+ search.setQuery('old');
+ await Future<void>.delayed(Duration.zero);
+ search.setQuery('new');
+ terminal.write('new marker\r\n' * 510);
+ await search.settled;
+ expect(search.query, 'new');
+ expect(search.count, 499);
+ expect(terminal.buffer.getText(search.match), 'new');
+ search.setQuery('old');
+ await search.settled;
+ expect(search.count, 0);
+ search.setQuery('');
+ expect(terminal.listeners, isEmpty);
+ });
+}