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(desktop): add terminal find and refine native tab hover
deec9e4e487fe4b
diff --git a/desktop/lib/screens/home_screen.dart b/desktop/lib/screens/home_screen.dartindex 94e2c8515..2784bcef7 100644--- a/desktop/lib/screens/home_screen.dart+++ b/desktop/lib/screens/home_screen.dart@@ -5,6 +5,7 @@ import 'package:flutter/material.dart';import '../core/desktop_window.dart';import '../state/app_state.dart';+import '../terminal/terminal_viewport.dart';import '../shared/theme/app_theme.dart' as grid;import '../theme/app_theme.dart';import '../usage/usage_controller.dart';@@ -247,6 +248,12 @@ class _HomeScreenState extends State<HomeScreen> {notifier.movePaneDirection(dx: 0, dy: -1),ShortcutAction.movePaneDown: () =>notifier.movePaneDirection(dx: 0, dy: 1),+ ShortcutAction.findTerminal: () =>+ notifier.focusedPane?.session?.find(TerminalFindAction.open),+ ShortcutAction.findNext: () =>+ notifier.focusedPane?.session?.find(TerminalFindAction.next),+ ShortcutAction.findPrevious: () => notifier.focusedPane?.session+ ?.find(TerminalFindAction.previous),ShortcutAction.lastPane: notifier.focusLastPane,ShortcutAction.zoomPane: notifier.toggleZoomPane,ShortcutAction.switchAgent: () =>diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex fef32d685..d1d6bf5cf 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -13,6 +13,7 @@ import '../settings/settings_section.dart';import '../shared/theme/app_theme.dart' as grid;import '../shortcuts/app_shortcuts.dart';import '../state/app_state.dart';+import '../terminal/terminal_viewport.dart';import '../state/swarm_catalog.dart';import '../state/swarm_attention.dart';import '../state/swarm_navigation.dart';@@ -123,11 +124,27 @@ class _SwarmScreenState extends State<SwarmScreen> {}}+ bool get _canFindTerminal {+ final pane = app.focusedPane;+ if (pane?.session == null) return false;+ final machine = app.stateOf(pane!.machineId);+ final agent = machine?.agents+ .where((a) => a.id == pane.agentId)+ .firstOrNull;+ // Connection/setup placeholders do not currently mount a TerminalPanel.+ return machine != null &&+ agent?.terminalAvailable == true &&+ machine.nodeOnline != false &&+ !(machine.isRemote && !machine.isLocalMachine && machine.needsLink) &&+ (!machine.isLocalMachine || machine.usesLocalTransport);+ }+void _syncNative() {final payload = {'enabled': _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen,'activeId': app.activeSwarmId,'canReopen': app.canReopenClosedSwarm,+ 'canFind': _canFindTerminal,'attention': _attention,'tabs': [for (final swarm in app.swarms)@@ -185,6 +202,12 @@ class _SwarmScreenState extends State<SwarmScreen> {await _addAgent();case 'closePane':if (app.focusedPaneId != null) await app.closePane(app.focusedPaneId!);+ case 'findTerminal':+ app.focusedPane?.session?.find(TerminalFindAction.open);+ case 'findNext':+ app.focusedPane?.session?.find(TerminalFindAction.next);+ case 'findPrevious':+ app.focusedPane?.session?.find(TerminalFindAction.previous);case 'notifications':await _notifications();case 'settings':@@ -407,6 +430,12 @@ class _SwarmScreenState extends State<SwarmScreen> {app.movePaneDirection(dx: 0, dy: 1),ShortcutAction.nextAgent: () => app.focusPaneBy(1),ShortcutAction.previousAgent: () => app.focusPaneBy(-1),+ ShortcutAction.findTerminal: () =>+ app.focusedPane?.session?.find(TerminalFindAction.open),+ ShortcutAction.findNext: () =>+ app.focusedPane?.session?.find(TerminalFindAction.next),+ ShortcutAction.findPrevious: () =>+ app.focusedPane?.session?.find(TerminalFindAction.previous),ShortcutAction.lastPane: app.focusLastPane,ShortcutAction.zoomPane: app.toggleZoomPane,ShortcutAction.switchAgent: _jump,diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dartindex 685a435a4..dc3edb346 100644--- a/desktop/lib/shortcuts/app_shortcuts.dart+++ b/desktop/lib/shortcuts/app_shortcuts.dart@@ -76,6 +76,10 @@ enum ShortcutAction {/// Find a live question and jump to the agent waiting for input.showAttention,+ findTerminal,+ findNext,+ findPrevious,+/// Add a view to the current Swarm, independently of navigation.addAgent,@@ -114,6 +118,28 @@ class AppShortcut {}const List<AppShortcut> kAppShortcuts = [+ AppShortcut(+ action: ShortcutAction.findTerminal,+ activator: SingleActivator(LogicalKeyboardKey.keyF, meta: true),+ label: 'Find in the focused terminal',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.findNext,+ activator: SingleActivator(LogicalKeyboardKey.keyG, meta: true),+ label: 'Next terminal match',+ group: ShortcutGroup.navigate,+ ),+ AppShortcut(+ action: ShortcutAction.findPrevious,+ activator: SingleActivator(+ LogicalKeyboardKey.keyG,+ meta: true,+ shift: true,+ ),+ label: 'Previous terminal match',+ group: ShortcutGroup.navigate,+ ),// --- navigate -------------------------------------------------------------//// ONE MOTION, TWO SPELLINGS. Every direction is bound as both `⌘`+arrow and@@ -135,7 +161,8 @@ const List<AppShortcut> kAppShortcuts = [// the header describes for ⌘C/⌘V/⌘A, and answered the same way: the// keyEquivalent is stripped, the menu item stays and still works when clicked.// ⌘J (Jump to Selection) and ⌘; (Check Document Now) went with it; this app- // has no Find and no spell-checked field. The cost is real and worth saying:+ // uses those keys for pane navigation. Terminal Find owns ⌘F/G separately.+ // The cost is real and worth saying:// Hide is no longer a keystroke in this app.AppShortcut(action: ShortcutAction.focusPaneLeft,diff --git a/desktop/lib/terminal/terminal_search.dart b/desktop/lib/terminal/terminal_search.dartnew file mode 100644index 000000000..d12cd006d--- /dev/null+++ b/desktop/lib/terminal/terminal_search.dart@@ -0,0 +1,448 @@+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/desktop/lib/terminal/terminal_session.dart b/desktop/lib/terminal/terminal_session.dartindex de76f6372..787f3594a 100644--- a/desktop/lib/terminal/terminal_session.dart+++ b/desktop/lib/terminal/terminal_session.dart@@ -995,6 +995,8 @@ class TerminalSession extends ChangeNotifier {_viewport?.scroll(phase, dy, velocity);}+ void find(TerminalFindAction action) => _viewport?.find(action);+/// Coalescing windows for the two things the user drives directly.////// Both are leading + trailing: act on the first event, batch the rest. A flat trailing debounce@@ -1027,6 +1029,9 @@ class TerminalSession extends ChangeNotifier {}Future<void> _flushResize() async {+ // A keyframe can flush the measured viewport before the debounce fires.+ // Cancel that callback before releasing its handle.+ _resizeTimer?.cancel();_resizeTimer = null;if (!acceptsInput || _pendingCols == null || _pendingRows == null) return;final nextCols = _pendingCols!;diff --git a/desktop/lib/terminal/terminal_viewport.dart b/desktop/lib/terminal/terminal_viewport.dartindex 81af84f7b..d883d8578 100644--- a/desktop/lib/terminal/terminal_viewport.dart+++ b/desktop/lib/terminal/terminal_viewport.dart@@ -1,9 +1,14 @@/// Local UI boundary for controls that operate on the rendered terminal but/// do not travel to the remote tmux pane.+enum TerminalFindAction { open, next, previous }+abstract interface class TerminalViewport {/// One report from the hardware dial.////// [phase] is 0 (down), 1 (move), or 2 (up). [dy] is the movement in glass/// pixels and [velocity] is glass pixels per second at release.void scroll(int phase, int dy, int velocity);++ /// Opens or steps through local terminal output without sending a key.+ void find(TerminalFindAction action);}diff --git a/desktop/lib/widgets/terminal_find_bar.dart b/desktop/lib/widgets/terminal_find_bar.dartnew file mode 100644index 000000000..c4a94c799--- /dev/null+++ b/desktop/lib/widgets/terminal_find_bar.dart@@ -0,0 +1,239 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';++import '../terminal/terminal_search.dart';++class TerminalFindBar extends StatefulWidget {+ const TerminalFindBar({+ super.key,+ required this.search,+ required this.onQuery,+ required this.onStep,+ required this.onClose,+ required this.onFocus,+ this.readOnly = false,+ });+ final TerminalSearch search;+ final void Function(String query, bool caseSensitive) onQuery;+ final ValueChanged<int> onStep;+ final VoidCallback onClose;+ final VoidCallback onFocus;+ final bool readOnly;++ @override+ State<TerminalFindBar> createState() => TerminalFindBarState();+}++class TerminalFindBarState extends State<TerminalFindBar> {+ final _focus = FocusNode(debugLabel: 'Find in terminal');+ late final _text = TextEditingController(text: widget.search.query);++ @override+ void initState() {+ super.initState();+ _focus.addListener(_onFocus);+ WidgetsBinding.instance.addPostFrameCallback((_) {+ if (mounted) focusSearch();+ });+ }++ void _onFocus() {+ if (_focus.hasFocus) widget.onFocus();+ }++ void focusSearch({bool selectAll = true}) {+ _focus.requestFocus();+ if (selectAll) {+ _text.selection = TextSelection(+ baseOffset: 0,+ extentOffset: _text.text.length,+ );+ }+ }++ @override+ void dispose() {+ _focus.removeListener(_onFocus);+ _focus.dispose();+ _text.dispose();+ super.dispose();+ }++ @override+ Widget build(BuildContext context) => CallbackShortcuts(+ bindings: {+ const SingleActivator(LogicalKeyboardKey.escape): widget.onClose,+ const SingleActivator(LogicalKeyboardKey.enter): () => widget.onStep(1),+ const SingleActivator(LogicalKeyboardKey.enter, shift: true): () =>+ widget.onStep(-1),+ const SingleActivator(LogicalKeyboardKey.numpadEnter): () =>+ widget.onStep(1),+ const SingleActivator(LogicalKeyboardKey.numpadEnter, shift: true): () =>+ widget.onStep(-1),+ },+ child: Material(+ color: const Color(0xff272727),+ shape: RoundedRectangleBorder(+ borderRadius: BorderRadius.circular(8),+ side: const BorderSide(color: Colors.white24),+ ),+ child: Padding(+ padding: const EdgeInsets.only(left: 10, right: 4, top: 2, bottom: 2),+ child: ListenableBuilder(+ listenable: widget.search,+ builder: (context, _) {+ final search = widget.search;+ final status = search.query.isEmpty+ ? ''+ : search.searching && !search.hasSnapshot+ ? '…'+ : '${search.selected + 1}/${search.count}';+ Widget button(+ String label,+ Widget icon,+ VoidCallback? action, {+ bool selected = false,+ }) => SizedBox(+ width: 28,+ height: 30,+ child: IconButton(+ tooltip: label,+ onPressed: action,+ isSelected: selected,+ constraints: const BoxConstraints.tightFor(+ width: 28,+ height: 30,+ ),+ padding: EdgeInsets.zero,+ visualDensity: VisualDensity.compact,+ iconSize: 17,+ color: selected ? Colors.white : Colors.white60,+ icon: icon,+ ),+ );+ return Row(+ children: [+ if (widget.readOnly) ...[+ const Tooltip(+ message: 'This terminal is read only',+ child: Icon(+ Icons.lock_outline,+ size: 14,+ color: Colors.white54,+ ),+ ),+ const SizedBox(width: 6),+ ],+ Expanded(+ child: TextField(+ controller: _text,+ focusNode: _focus,+ autofocus: true,+ textAlignVertical: TextAlignVertical.center,+ style: const TextStyle(+ fontSize: 13,+ height: 1,+ color: Colors.white,+ ),+ decoration: const InputDecoration(+ hintText: 'Find in terminal…',+ hintStyle: TextStyle(color: Colors.white54),+ isDense: true,+ isCollapsed: true,+ constraints: BoxConstraints(),+ border: InputBorder.none,+ enabledBorder: InputBorder.none,+ focusedBorder: InputBorder.none,+ filled: false,+ contentPadding: EdgeInsets.zero,+ ),+ onChanged: (value) =>+ widget.onQuery(value, search.caseSensitive),+ ),+ ),+ const SizedBox(width: 6),+ Semantics(+ liveRegion: true,+ label: search.searching && !search.hasSnapshot+ ? 'Searching terminal'+ : search.query.isEmpty+ ? 'Find in terminal'+ : search.count == 0+ ? 'No matches'+ : 'Match ${search.selected + 1} of ${search.count}',+ child: ConstrainedBox(+ constraints: const BoxConstraints(maxWidth: 56),+ child: ExcludeSemantics(+ child: Text(+ status,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ fontSize: 11,+ height: 1,+ color:+ search.count == 0 &&+ search.query.isNotEmpty &&+ !search.searching+ ? const Color(0xffffb4a9)+ : Colors.white54,+ ),+ ),+ ),+ ),+ ),+ const SizedBox(width: 4),+ button(+ 'Match case',+ Text(+ 'Aa',+ style: TextStyle(+ fontSize: 12,+ height: 1,+ color: search.caseSensitive+ ? Colors.white+ : Colors.white54,+ fontWeight: search.caseSensitive+ ? FontWeight.w700+ : FontWeight.normal,+ ),+ ),+ () {+ widget.onQuery(_text.text, !search.caseSensitive);+ _focus.requestFocus();+ },+ selected: search.caseSensitive,+ ),+ button(+ 'Previous match (⇧⌘G)',+ const Icon(Icons.keyboard_arrow_up),+ search.count > 0+ ? () {+ widget.onStep(-1);+ _focus.requestFocus();+ }+ : null,+ ),+ button(+ 'Next match (⌘G)',+ const Icon(Icons.keyboard_arrow_down),+ search.count > 0+ ? () {+ widget.onStep(1);+ _focus.requestFocus();+ }+ : null,+ ),+ button(+ 'Close find (Esc)',+ const Icon(Icons.close),+ widget.onClose,+ ),+ ],+ );+ },+ ),+ ),+ ),+ );+}diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dartindex 0f21496a4..c5745d603 100644--- a/desktop/lib/widgets/terminal_panel.dart+++ b/desktop/lib/widgets/terminal_panel.dart@@ -14,6 +14,8 @@ import '../state/app_state.dart';import 'agent_drag.dart';import 'rename_agent_dialog.dart';import 'terminal_composer.dart';+import 'terminal_find_bar.dart';+import '../terminal/terminal_search.dart';import '../terminal/terminal_binary.dart';import '../terminal/terminal_font_store.dart';import '../terminal/terminal_link_opener.dart';@@ -99,6 +101,20 @@ class _TerminalPanelState extends State<TerminalPanel>final ScrollController _scrollController = ScrollController();final FocusNode _focusNode = FocusNode();final FocusNode _composerFocus = FocusNode();+ final _findBarKey = GlobalKey<TerminalFindBarState>();+ TerminalSearch? _find;+ String _lastFindQuery = '';+ bool _lastFindCaseSensitive = false;+ CellAnchor? _lastFindAnchor;+ Buffer? _lastFindBuffer;+ TerminalHighlight? _findHighlight;+ Buffer? _findPaintedBuffer;+ BufferRangeLine? _findPaintedRange;+ Buffer? _findOriginBuffer;+ CellAnchor? _findOriginLine;+ double _findOriginFraction = 0;+ bool _findOriginAtEnd = false;+ bool _findRevealPending = false;late Terminal _viewTerminal;late GlobalKey<TerminalViewState> _terminalViewKey;Timer? _dialInertiaTimer;@@ -174,6 +190,9 @@ class _TerminalPanelState extends State<TerminalPanel>void didUpdateWidget(TerminalPanel oldWidget) {super.didUpdateWidget(oldWidget);if (!identical(oldWidget.session, widget.session)) {+ _closeFind(restore: false, focus: false, rebuild: false);+ _clearLastFind();+ _lastFindQuery = '';_previewCancellation?.cancel();_previewProgress = null;oldWidget.session.setCursorBlinkPhase(true);@@ -217,6 +236,8 @@ class _TerminalPanelState extends State<TerminalPanel>@overridevoid dispose() {+ _closeFind(restore: false, focus: false, rebuild: false);+ _clearLastFind();WidgetsBinding.instance.removeObserver(this);_tickerMode?.removeListener(_syncCursorBlink);_previewCancellation?.cancel();@@ -291,6 +312,9 @@ class _TerminalPanelState extends State<TerminalPanel>void _syncTerminal(Terminal terminal) {if (identical(_viewTerminal, terminal)) return;+ final wasFinding = _find != null;+ _closeFind(restore: false, focus: false, rebuild: false);+ _clearLastFind();// Selection anchors belong to a specific circular buffer. Detach them// before the TerminalView starts laying out the replacement terminal._controller.clearSelection();@@ -305,6 +329,13 @@ class _TerminalPanelState extends State<TerminalPanel>_alternateScrollRemainder = 0;_cursorBlinkVisible = true;widget.session.setCursorBlinkPhase(true);+ if (wasFinding) {+ _findOriginBuffer = terminal.buffer;+ _findOriginAtEnd = true;+ _findRevealPending = true;+ _find = TerminalSearch(terminal)..addListener(_onFindChanged);+ _find!.setQuery(_lastFindQuery, caseSensitive: _lastFindCaseSensitive);+ }_afterTerminalMounted(clearSelection: true);}@@ -329,7 +360,12 @@ class _TerminalPanelState extends State<TerminalPanel>/// focus when needed, or opens the connection immediately when focus stayed/// on this tile. That is essential for ordinary keys and IMEs alike.void _claimFocus(TerminalViewState view) {- if (!mounted || !widget.focused || _composerFocus.hasFocus) return;+ if (!mounted || !widget.focused || !widget.visible) return;+ if (_find != null) {+ _findBarKey.currentState?.focusSearch(selectAll: false);+ return;+ }+ if (_composerFocus.hasFocus) return;// On a remote pane the box gets the caret, not the terminal. Landing in the terminal would// hand the user the per-keystroke path by default — the exact cost the box exists to avoid.if (_showsComposer) {@@ -356,6 +392,13 @@ class _TerminalPanelState extends State<TerminalPanel>/// ticker mode without rebuilding the subtree when a route covers it.void _syncCursorBlink() {final lifecycle = WidgetsBinding.instance.lifecycleState;+ final findEnabled =+ mounted &&+ widget.visible &&+ (_tickerMode?.value.enabled ?? false) &&+ (lifecycle == null || lifecycle == AppLifecycleState.resumed);+ _find?.setEnabled(findEnabled);+ if (!findEnabled) _clearFindHighlight();final enabled =mounted &&widget.visible &&@@ -439,10 +482,162 @@ class _TerminalPanelState extends State<TerminalPanel>// Never over the composer: a rebuild that re-focuses this tile while someone is typing into// the box would pull the caret out from under them mid-sentence._claimFocus(view);+ if (_find != null) _onFindChanged();if (_linkPointerPosition != null) _hoverLink(_linkPointerPosition);});}+ @override+ void find(TerminalFindAction action) {+ if (!mounted || !widget.visible || !widget.focused) return;+ final wasClosed = _find == null;+ if (wasClosed) {+ final view = _laidOutTerminalView();+ if (view == null || !_scrollController.hasClients) return;+ final position = _scrollController.position;+ final height = view.renderTerminal.lineHeight;+ 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;+ var origin = CellOffset(0, row);+ if (action != TerminalFindAction.open &&+ _lastFindAnchor?.attached == true &&+ identical(_lastFindBuffer, _viewTerminal.buffer)) {+ final last = _lastFindAnchor!.offset;+ origin = CellOffset(+ last.x + (action == TerminalFindAction.next ? 1 : 0),+ last.y,+ );+ }+ _find = TerminalSearch(_viewTerminal, origin: origin)+ ..addListener(_onFindChanged);+ _findRevealPending = true;+ _find!.setQuery(_lastFindQuery, caseSensitive: _lastFindCaseSensitive);+ setState(() {});+ } else if (action == TerminalFindAction.open) {+ _findBarKey.currentState?.focusSearch();+ }+ if (action != TerminalFindAction.open &&+ !(wasClosed && action == TerminalFindAction.next)) {+ _stepFind(action == TerminalFindAction.next ? 1 : -1);+ }+ }++ void _queryFind(String query, bool caseSensitive) {+ _lastFindQuery = query;+ _lastFindCaseSensitive = caseSensitive;+ _findRevealPending = true;+ _find?.setQuery(query, caseSensitive: caseSensitive);+ }++ void _stepFind(int delta) {+ _findRevealPending = true;+ _find?.step(delta);+ }++ void _onFindChanged() {+ final search = _find;+ if (!mounted || search == null || !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;+ _findRevealPending = false;+ final position = _scrollController.position;+ final top = range.begin.y * render.lineHeight + 10;+ final bottom = (range.end.y + 1) * render.lineHeight + 10;+ final safeTop = position.pixels + 10;+ final safeBottom = position.pixels + position.viewportDimension - 10;+ final offset = top < safeTop+ ? top - 10+ : 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();+ }++ void _clearLastFind() {+ _lastFindAnchor?.dispose();+ _lastFindAnchor = null;+ _lastFindBuffer = null;+ }++ void _closeFind({+ bool restore = true,+ bool focus = true,+ bool rebuild = true,+ }) {+ final search = _find;+ if (search == null) return;+ final match = search.match;+ if (match != null) {+ _clearLastFind();+ _lastFindAnchor = _viewTerminal.buffer.createAnchorFromOffset(+ match.begin,+ );+ _lastFindBuffer = _viewTerminal.buffer;+ }+ _find = null;+ search.removeListener(_onFindChanged);+ search.dispose();+ _clearFindHighlight();+ if (restore &&+ identical(_findOriginBuffer, _viewTerminal.buffer) &&+ _scrollController.hasClients) {+ final height = _laidOutTerminalView()?.renderTerminal.lineHeight;+ final position = _scrollController.position;+ if (height != null) {+ 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;+ if (rebuild && mounted) setState(() {});+ if (focus) _claimFocusAfterFrame();+ }+@overridevoid scroll(int phase, int dy, int velocity) {if (phase == 0) _cancelDialInertia();@@ -749,7 +944,64 @@ class _TerminalPanelState extends State<TerminalPanel>color: grid.AppPalette.windowBg,child: Column(children: [- _buildHeader(context, remote: remote),+ Stack(+ children: [+ Visibility(+ visible: _find == null,+ maintainSize: true,+ maintainAnimation: true,+ maintainState: true,+ child: _buildHeader(context, remote: remote),+ ),+ if (_find != null)+ Positioned.fill(+ child: LayoutBuilder(+ builder: (context, constraints) => Row(+ children: [+ if (constraints.maxWidth > 520)+ Expanded(+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: _stripPadding,+ ),+ child: Text(+ session.agentName,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: const TextStyle(+ fontSize: 13,+ color: Colors.white70,+ ),+ ),+ ),+ )+ else+ const Spacer(),+ SizedBox(+ width: math.min(constraints.maxWidth, 380),+ child: Padding(+ padding: const EdgeInsets.symmetric(+ horizontal: 6,+ vertical: 4,+ ),+ child: TerminalFindBar(+ key: _findBarKey,+ search: _find!,+ readOnly:+ widget.readOnly || !session.acceptsInput,+ onQuery: _queryFind,+ onStep: _stepFind,+ onClose: _closeFind,+ onFocus: () => widget.onRendererFocus?.call(),+ ),+ ),+ ),+ ],+ ),+ ),+ ),+ ],+ ),Divider(height: 1, color: AppColors.border),Expanded(@@ -822,8 +1074,9 @@ class _TerminalPanelState extends State<TerminalPanel>spinning: true,),),- if (session.status == TerminalSessionStatus.error ||- session.status == TerminalSessionStatus.takenOver)+ if (_find == null &&+ (session.status == TerminalSessionStatus.error ||+ session.status == TerminalSessionStatus.takenOver))Positioned.fill(child: _FrozenOverlay(session: session,diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex e72eb3aba..8b19476c8 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -12,6 +12,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {private var configured = falseprivate var actionsEnabled = falseprivate var canReopen = false+ private var canFind = falseinit(window: NSWindow, messenger: FlutterBinaryMessenger) {self.window = window@@ -28,6 +29,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {let state = call.arguments as? [String: Any] ?? [:]self.actionsEnabled = state["enabled"] as? Bool == trueself.canReopen = state["canReopen"] as? Bool == true+ self.canFind = state["canFind"] as? Bool == trueself.strip.update(state)result(nil)default: result(FlutterMethodNotImplemented)@@ -113,10 +115,33 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {let item = NSMenuItem(title: "Swarm", action: nil, keyEquivalent: "")item.submenu = menumain.insertItem(item, at: min(2, main.numberOfItems))+ installTerminalFindMenu(main)+ }++ private func installTerminalFindMenu(_ main: NSMenu) {+ guard let edit = main.items.first(where: { $0.title == "Edit" })?.submenu,+ let find = edit.items.first(where: { $0.title == "Find" }) else { return }+ let menu = NSMenu(title: "Find")+ for (title, key, action, modifiers) in [+ ("Find in Terminal…", "f", "findTerminal", NSEvent.ModifierFlags.command),+ ("Find Next", "g", "findNext", NSEvent.ModifierFlags.command),+ ("Find Previous", "g", "findPrevious", NSEvent.ModifierFlags([.command, .shift])),+ ] {+ let item = NSMenuItem(title: title, action: #selector(menuAction(_:)), keyEquivalent: key)+ item.keyEquivalentModifierMask = modifiers+ item.target = self+ item.representedObject = action+ menu.addItem(item)+ }+ // The template's find/replace actions target an unused text-editor handler.+ // Terminal output is searchable; replacement belongs to the running tool.+ find.submenu = menu}func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {- actionsEnabled && (menuItem.representedObject as? String != "reopen" || canReopen)+ let action = menuItem.representedObject as? String ?? ""+ return actionsEnabled && (action != "reopen" || canReopen) &&+ (!["findTerminal", "findNext", "findPrevious"].contains(action) || canFind)}@objc private func menuAction(_ sender: NSMenuItem) {@@ -183,13 +208,12 @@ private final class SwarmTabStrip: NSView {tab.actionsEnabled = actionsEnabledtab.attention = (row["attention"] as? Int ?? 0) > 0tab.emit = { [weak self] method, args in self?.emit?(method, args) }+ tab.hoverChanged = { [weak self] in self?.updateDividers() }if tab.superview == nil { document.addSubview(tab) }tab.needsDisplay = truereturn tab}- for (index, tab) in tabs.enumerated() {- tab.showsDivider = !tab.selected && index + 1 < tabs.count && !tabs[index + 1].selected- }+ updateDividers()// Moving frames alone leaves AppKit's child traversal in insertion order.document.setAccessibilityChildren(tabs)newButton.isEnabled = actionsEnabled && tabs.count < 24@@ -208,6 +232,14 @@ private final class SwarmTabStrip: NSView {}}+ private func updateDividers() {+ for (index, tab) in tabs.enumerated() {+ let next = index + 1 < tabs.count ? tabs[index + 1] : nil+ tab.showsDivider = !tab.selected && !tab.isHovered && next != nil &&+ next?.selected == false && next?.isHovered == false+ }+ }+override func layout() {super.layout()let available = max(120, bounds.width - 112)@@ -255,14 +287,17 @@ private final class SwarmTabStrip: NSView {private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidation {let swarmId: String- var name = "New swarm" { didSet { updateAccessibility() } }- var selected = false { didSet { updateAccessibility() } }+ var name = "New swarm" { didSet { if name != oldValue { invalidateLabel(); updateAccessibility() } } }+ var selected = false { didSet { if selected != oldValue { invalidateLabel(); updateAccessibility() } } }var attention = false- var showsDivider = false+ var showsDivider = false { didSet { if showsDivider != oldValue { needsDisplay = true } } }var contentCenterY: CGFloat = 20var emit: ((String, Any?) -> Void)?+ var hoverChanged: (() -> Void)?+ var isHovered: Bool { hovered && actionsEnabled }private let closeButton = NSButton()private let selectButton = SwarmSelectButton()+ private var cachedLabel: NSAttributedString?var actionsEnabled = true {didSet {closeButton.isEnabled = actionsEnabled@@ -287,7 +322,7 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatiselectButton.action = #selector(selectSwarm)addSubview(selectButton)closeButton.image = NSImage(systemSymbolName: "xmark", accessibilityDescription: "Close swarm")- closeButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 9, weight: .semibold)+ closeButton.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 10, weight: .semibold)closeButton.contentTintColor = NSColor(white: 0.78, alpha: 1)closeButton.isBordered = falsecloseButton.target = self@@ -317,8 +352,28 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidatiaddTrackingArea(area)hoverTracking = area}- override func mouseEntered(with event: NSEvent) { hovered = true; needsDisplay = true }- override func mouseExited(with event: NSEvent) { hovered = false; needsDisplay = true }+ override func mouseEntered(with event: NSEvent) { setHovered(true) }+ override func mouseExited(with event: NSEvent) { setHovered(false) }+ private func setHovered(_ value: Bool) {+ guard hovered != value else { return }+ hovered = value+ needsDisplay = true+ hoverChanged?()+ }+ private func invalidateLabel() {+ cachedLabel = nil+ needsDisplay = true+ }+ private var label: NSAttributedString {+ if let cachedLabel { return cachedLabel }+ let paragraph = NSMutableParagraphStyle()+ paragraph.lineBreakMode = .byTruncatingTail+ let label = NSAttributedString(string: name,+ attributes: [.font: NSFont.systemFont(ofSize: 13, weight: selected ? .medium : .regular),+ .foregroundColor: selected ? NSColor.white : NSColor(white: 0.76, alpha: 1), .paragraphStyle: paragraph])+ cachedLabel = label+ return label+ }override func draw(_ dirtyRect: NSRect) {if selected {let w = bounds.width, h = bounds.height@@ -337,20 +392,16 @@ private final class SwarmTabButton: NSView, NSDraggingSource, NSMenuItemValidati} else if hovered && actionsEnabled {NSColor(white: 1, alpha: 0.05).setFill()let hoverRect = NSRect(x: 8, y: contentCenterY - 14, width: bounds.width - 16, height: 28)- NSBezierPath(roundedRect: hoverRect, xRadius: 10, yRadius: 10).fill()+ NSBezierPath(roundedRect: hoverRect, xRadius: 12, yRadius: 12).fill()}if showsDivider && !hovered {NSColor(white: 1, alpha: 0.16).setFill()NSBezierPath(roundedRect: NSRect(x: bounds.width - 0.5, y: contentCenterY - 8, width: 1, height: 16),xRadius: 0.5, yRadius: 0.5).fill()}- let paragraph = NSMutableParagraphStyle()- paragraph.lineBreakMode = .byTruncatingTail- let label = NSAttributedString(string: name,- attributes: [.font: NSFont.systemFont(ofSize: 12, weight: selected ? .medium : .regular),- .foregroundColor: selected ? NSColor.white : NSColor(white: 0.72, alpha: 1), .paragraphStyle: paragraph])+ let label = self.labellet labelHeight = label.size().height- label.draw(in: NSRect(x: 24, y: contentCenterY - labelHeight / 2,+ label.draw(in: NSRect(x: 22, y: contentCenterY - labelHeight / 2,width: bounds.width - 64, height: labelHeight))if attention {NSColor.systemOrange.setFill()diff --git a/desktop/test/benchmarks/terminal_find_benchmark.dart b/desktop/test/benchmarks/terminal_find_benchmark.dartnew file mode 100644index 000000000..07adc0528--- /dev/null+++ b/desktop/test/benchmarks/terminal_find_benchmark.dart@@ -0,0 +1,50 @@+import 'dart:convert';++import 'package:flutter/foundation.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/terminal/terminal_search.dart';+import 'package:xterm/xterm.dart';++import 'swarm_benchmark.dart' show distribution;++/// Explicit, isolated event-loop timing. Includes cooperative yields but no+/// native input, compositor, sockets or real sessions.+void main() {+ test('find across 10000 retained terminal rows', () async {+ final terminal = Terminal(maxLines: 10000)..resize(120, 24);+ terminal.write(+ List.generate(+ 9999,+ (i) =>+ 'Build $i: ${i % 20 == 0 ? 'Error' : 'ready'} · staging project /work/harness 界🙂\r\n',+ ).join(),+ );+ final search = TerminalSearch(terminal, origin: const CellOffset(0, 9800));+ final cold = Stopwatch()..start();+ search.setQuery('error');+ await search.settled;+ cold.stop();+ expect(search.count, 500);+ final queries = <int>[];+ final updates = <int>[];+ final steps = <int>[];+ for (var i = 0; i < 40; i++) {+ final watch = Stopwatch()..start();+ search.setQuery(i.isEven ? 'staging' : 'error');+ await search.settled;+ queries.add(watch.elapsedMicroseconds);+ watch.reset();+ search.step(1);+ steps.add(watch.elapsedMicroseconds);+ watch.reset();+ terminal.write('\r\x1b[2KCurrent error $i');+ await search.settled;+ updates.add(watch.elapsedMicroseconds);+ }+ debugPrint(+ 'TERMINAL_FIND_BENCH ${jsonEncode({'kind': 'headless_debug_event_loop', 'rows': terminal.lines.length, 'coldQueryMs': cold.elapsedMicroseconds / 1000, 'cachedTextQuery': distribution(queries), 'liveRowUpdate': distribution(updates), 'nextMatch': distribution(steps)})}',+ );+ search.dispose();+ expect(terminal.listeners, isEmpty);+ });+}diff --git a/desktop/test/shortcuts_test.dart b/desktop/test/shortcuts_test.dartindex 08c323123..df9875bdd 100644--- a/desktop/test/shortcuts_test.dart+++ b/desktop/test/shortcuts_test.dart@@ -295,6 +295,9 @@ void main() {expect(chordsFor(ShortcutAction.switchAgent), isNot(contains('⇧⌘F')));expect(chordsFor(ShortcutAction.addAgent), ['⇧⌘F']);expect(chordsFor(ShortcutAction.showAttention), ['⇧⌘I']);+ expect(chordsFor(ShortcutAction.findTerminal), ['⌘F']);+ expect(chordsFor(ShortcutAction.findNext), ['⌘G']);+ expect(chordsFor(ShortcutAction.findPrevious), ['⇧⌘G']);});test(diff --git a/desktop/test/swarm_interactions_test.dart b/desktop/test/swarm_interactions_test.dartindex 47e615321..0b671753d 100644--- a/desktop/test/swarm_interactions_test.dart+++ b/desktop/test/swarm_interactions_test.dart@@ -17,6 +17,7 @@ import 'package:harness/widgets/codex_profile_field.dart';import 'package:harness/widgets/new_agent_dialog.dart';import 'package:harness/widgets/swarm_dialogs.dart';import 'package:harness/widgets/terminal_composer.dart';+import 'package:harness/widgets/terminal_find_bar.dart';import 'swarm_screen_test.dart' show mount, terminal;import 'swarm_state_test.dart' show createApp;@@ -263,6 +264,32 @@ void main() {await tester.pump();await attention;expect(updates.last['enabled'], isTrue);+ expect(updates.last['canFind'], isFalse);+ app.machineStates['m']!.nodeOnline = true;+ final session = terminal('a0', []);+ session.terminal.write('marker one\r\nmarker two\r\n');+ app.adoptSessionForTest(session);+ app.dismissError();+ await tester.pump();+ expect(updates.last['canFind'], isTrue);+ await native('findTerminal');+ await tester.pump();+ expect(find.byType(TerminalFindBar), findsOneWidget);+ await tester.enterText(find.byType(TextField), 'marker');+ await tester.pump(const Duration(milliseconds: 10));+ final search = tester+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))+ .search;+ expect(search.count, 2);+ await native('findNext');+ await tester.pump();+ expect(search.selected, 1);+ await native('findPrevious');+ await tester.pump();+ expect(search.selected, 0);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(find.byType(TerminalFindBar), findsNothing);await tester.pumpWidget(const SizedBox());projects.dispose();app.dispose();diff --git a/desktop/test/terminal_find_test.dart b/desktop/test/terminal_find_test.dartnew file mode 100644index 000000000..389dcc58b--- /dev/null+++ b/desktop/test/terminal_find_test.dart@@ -0,0 +1,334 @@+import 'dart:convert';++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/terminal/terminal_binary.dart';+import 'package:harness/terminal/terminal_session.dart';+import 'package:harness/terminal/terminal_search.dart';+import 'package:harness/widgets/terminal_find_bar.dart';+import 'package:xterm/xterm.dart';++import 'swarm_interactions_test.dart' show chord;+import 'swarm_screen_test.dart' show mount, terminal;+import 'swarm_state_test.dart' show createApp;++Finder get findField => find.byWidgetPredicate(+ (widget) =>+ widget is TextField && widget.decoration?.hintText == 'Find in terminal…',+);++Future<void> finishFind(WidgetTester tester) async {+ for (var frame = 0; frame < 200; frame++) {+ await tester.pump(const Duration(milliseconds: 1));+ if (!tester+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))+ .search+ .searching) {+ return;+ }+ }+ fail('Find did not settle');+}++TerminalViewState terminalView(WidgetTester tester, TerminalSession session) =>+ tester.state<TerminalViewState>(+ find.byWidgetPredicate(+ (widget) =>+ widget is TerminalView && widget.terminal == session.terminal,+ ),+ );++Future<void> output(+ TerminalSession session,+ int sequence,+ String text, {+ bool keyframe = false,+}) => session.handleBinary(+ TerminalBinaryFrame(+ kind: keyframe ? TerminalBinaryKind.keyframe : TerminalBinaryKind.output,+ streamId: session.streamId!,+ seq: sequence,+ compressed: false,+ bytes: utf8.encode(text),+ cols: keyframe ? 80 : null,+ rows: keyframe ? 24 : null,+ ),+);++void main() {+ testWidgets(+ 'a narrow find bar supports large text and a large result count',+ (tester) async {+ final terminal = Terminal()..resize(80, 4);+ terminal.write('needle\r\n' * 9998);+ final search = TerminalSearch(terminal);+ await tester.runAsync(() async {+ search.setQuery('needle');+ await search.settled;+ });+ final semantics = tester.ensureSemantics();+ await tester.pumpWidget(+ MaterialApp(+ builder: (context, child) => MediaQuery(+ data: MediaQuery.of(context)+ .copyWith(textScaler: TextScaler.linear(2)),+ child: child!,+ ),+ home: Scaffold(+ body: Center(+ child: SizedBox(+ width: 260,+ height: 38,+ child: TerminalFindBar(+ search: search,+ readOnly: true,+ onQuery: (query, sensitive) =>+ search.setQuery(query, caseSensitive: sensitive),+ onStep: search.step,+ onClose: () {},+ onFocus: () {},+ ),+ ),+ ),+ ),+ ),+ );+ await tester.pump();+ expect(tester.takeException(), isNull);+ expect(tester.getSize(findField).height, lessThanOrEqualTo(38));+ expect(tester.getSize(findField).width, greaterThan(24));+ expect(+ find.bySemanticsLabel(+ 'Match ${search.selected + 1} of ${search.count}',+ ),+ findsOneWidget,+ );+ await tester.tap(find.byTooltip('Match case'));+ await tester.pump();+ expect(tester.widget<TextField>(findField).focusNode!.hasFocus, isTrue);+ await tester.pumpWidget(const SizedBox());+ search.dispose();+ semantics.dispose();+ },+ );++ testWidgets(+ 'find opens in one frame without resizing, preserves selection and returns to prior scroll',+ (tester) async {+ final app = createApp();+ app.machineStates['m']!.nodeOnline = true;+ final input = <TerminalBinaryFrame>[];+ final session = terminal('a0', input);+ session.terminal.write(+ List.generate(+ 180,+ (i) => 'Line $i${i % 50 == 0 ? ' needle' : ''}\r\n',+ ).join(),+ );+ app.adoptSessionForTest(session);+ await mount(tester, app);+ final view = terminalView(tester, session);+ final renderer = view.renderTerminal;+ final size = renderer.size;+ final dimensions = (+ session.terminal.viewWidth,+ session.terminal.viewHeight,+ );+ final scroll = view.widget.scrollController!;+ scroll.jumpTo(renderer.lineHeight * 20.5);+ final previousScroll = scroll.offset;+ final controller = view.widget.controller!;+ controller.setSelection(+ session.terminal.buffer.createAnchor(0, 5),+ session.terminal.buffer.createAnchor(4, 5),+ );+ final previousSelection = controller.selection;+ await tester.pump();+ await tester.sendKeyDownEvent(LogicalKeyboardKey.meta);+ await tester.sendKeyEvent(LogicalKeyboardKey.keyF);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.meta);+ await tester.pump();+ expect(findField, findsOneWidget);+ expect(tester.widget<TextField>(findField).focusNode!.hasFocus, isTrue);+ expect(view.renderTerminal, same(renderer));+ expect(renderer.size, size);+ expect((+ session.terminal.viewWidth,+ session.terminal.viewHeight,+ ), dimensions);+ await tester.enterText(findField, 'needle');+ await finishFind(tester);+ final search = tester+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))+ .search;+ expect(search.count, 4);+ expect(search.selected, 1);+ expect(controller.highlights, hasLength(1));+ expect(+ session.terminal.buffer.getText(controller.highlights.single.range),+ 'needle',+ );+ expect(controller.selection, previousSelection);+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);+ await tester.pump();+ expect(search.selected, 2);+ await chord(tester, LogicalKeyboardKey.keyG);+ expect(search.selected, 3);+ await chord(tester, LogicalKeyboardKey.keyG, shift: true);+ expect(search.selected, 2);+ expect(input, isEmpty);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(findField, findsNothing);+ expect(controller.highlights, isEmpty);+ expect(controller.selection, previousSelection);+ expect(scroll.offset, closeTo(previousScroll, 0.01));+ expect(renderer.size, size);+ await chord(tester, LogicalKeyboardKey.keyG);+ await finishFind(tester);+ expect(+ tester+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))+ .search+ .selected,+ 3,+ );+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(scroll.offset, closeTo(previousScroll, 0.01));+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);+ await tester.pump(const Duration(milliseconds: 10));+ expect(input.single.bytes, [27, 91, 68]);+ for (final key in [LogicalKeyboardKey.keyF, LogicalKeyboardKey.keyG]) {+ await tester.sendKeyDownEvent(LogicalKeyboardKey.control);+ await tester.sendKeyEvent(key);+ await tester.sendKeyUpEvent(LogicalKeyboardKey.control);+ await tester.pump(const Duration(milliseconds: 10));+ }+ expect(input.skip(1).map((frame) => frame.bytes.single), [6, 7]);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );++ testWidgets(+ 'hidden find does no indexing and returns to the same query with current output',+ (tester) async {+ final app = createApp();+ app.machineStates['m']!.nodeOnline = true;+ final a = terminal('a0', []);+ final b = terminal('a1', []);+ await output(a, 0, 'first marker\r\n', keyframe: true);+ app.adoptSessionForTest(a);+ final first = app.activeSwarm;+ await mount(tester, app);+ await chord(tester, LogicalKeyboardKey.keyF);+ await tester.enterText(findField, 'marker');+ await finishFind(tester);+ final search = tester+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))+ .search;+ expect(search.count, 1);+ app.newSwarm();+ app.adoptSessionForTest(b);+ await tester.pump();+ await tester.pump();+ expect(search.count, 0);+ expect(findField, findsNothing);+ await output(a, 1, 'second marker\r\n');+ expect(tester.binding.hasScheduledFrame, isFalse);+ app.selectSwarm(first.id, attachPending: false);+ await tester.pump();+ await finishFind(tester);+ expect(search.count, 2);+ expect(tester.widget<TextField>(findField).controller!.text, 'marker');+ expect(tester.widget<TextField>(findField).focusNode!.hasFocus, isTrue);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );++ testWidgets(+ 'a real keyframe replaces the emulator without sending find text to the agent',+ (tester) async {+ final app = createApp();+ app.machineStates['m']!.nodeOnline = true;+ final input = <TerminalBinaryFrame>[];+ final session = terminal('a0', input);+ await output(session, 0, 'old marker\r\n', keyframe: true);+ app.adoptSessionForTest(session);+ await mount(tester, app);+ await chord(tester, LogicalKeyboardKey.keyF);+ await tester.enterText(findField, 'marker');+ await finishFind(tester);+ final old = session.terminal;+ final text = tester.widget<TextField>(findField).controller!;+ text.selection = const TextSelection.collapsed(offset: 3);+ await output(+ session,+ 10,+ 'new marker\r\nsecond marker\r\n',+ keyframe: true,+ );+ await tester.pump();+ await finishFind(tester);+ expect(session.terminal, isNot(same(old)));+ expect(tester.widget<TextField>(findField).controller, same(text));+ expect(text.selection, const TextSelection.collapsed(offset: 3));+ expect(tester.widget<TextField>(findField).focusNode!.hasFocus, isTrue);+ expect(+ tester+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))+ .search+ .count,+ 2,+ );+ await tester.enterText(findField, 'new');+ await finishFind(tester);+ expect(+ tester+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))+ .search+ .count,+ 1,+ );+ expect(input, isEmpty);+ old.buffer.lines.forEach((line) => expect(line.anchors, isEmpty));+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ },+ );++ testWidgets('taken-over terminals can be searched without retry or input', (+ tester,+ ) async {+ final app = createApp();+ app.machineStates['m']!.nodeOnline = true;+ final input = <TerminalBinaryFrame>[];+ final session = terminal('a0', input);+ session.terminal.write('Retained Error\r\n');+ app.adoptSessionForTest(session);+ session.status = TerminalSessionStatus.takenOver;+ await mount(tester, app);+ await chord(tester, LogicalKeyboardKey.keyF);+ expect(find.text('TERMINAL FROZEN'), findsNothing);+ expect(find.byTooltip('This terminal is read only'), findsOneWidget);+ await tester.enterText(findField, 'error');+ await finishFind(tester);+ final search = tester+ .widget<TerminalFindBar>(find.byType(TerminalFindBar))+ .search;+ expect(search.count, 1);+ await tester.tap(find.byTooltip('Match case'));+ await finishFind(tester);+ expect(search.count, 0);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pump();+ expect(session.status, TerminalSessionStatus.takenOver);+ expect(find.text('TERMINAL FROZEN'), findsOneWidget);+ expect(input, isEmpty);+ await tester.pumpWidget(const SizedBox());+ app.dispose();+ });+}diff --git a/desktop/test/terminal_search_test.dart b/desktop/test/terminal_search_test.dartnew file mode 100644index 000000000..a64587b57--- /dev/null+++ b/desktop/test/terminal_search_test.dart@@ -0,0 +1,169 @@+import 'package:flutter_test/flutter_test.dart';+import 'package:harness/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);+ });+}diff --git a/desktop/third_party/xterm/README.autonomous.md b/desktop/third_party/xterm/README.autonomous.mdindex d485ffa2b..b1aa6df5f 100644--- a/desktop/third_party/xterm/README.autonomous.md+++ b/desktop/third_party/xterm/README.autonomous.md@@ -13,6 +13,13 @@ fix and the regression in `test/terminal_session_test.dart` passes against it.## Local patches+- **On-demand terminal find** (`lib/src/core/buffer/line.dart`,+ `lib/src/terminal.dart`). Text mutations advance a local line version so a+ search can reuse decoded rows; color-only changes keep the version. Optional+ resize listeners run after buffer reflow without replacing the transport's+ `onResize` callback. Search attaches only while visible with a nonempty query.+ Regressions: `test/terminal_search_test.dart`, `test/terminal_find_test.dart`.+- **Host-handled primary clicks** (`lib/src/terminal_view.dart`,`lib/src/ui/gesture/gesture_handler.dart`). `onTapUp` was declared but neverdispatched by the single-click path. It now runs, and a consuming `onTapDown`diff --git a/desktop/third_party/xterm/lib/src/core/buffer/line.dart b/desktop/third_party/xterm/lib/src/core/buffer/line.dartindex a71446c54..7ea477ad4 100644--- a/desktop/third_party/xterm/lib/src/core/buffer/line.dart+++ b/desktop/third_party/xterm/lib/src/core/buffer/line.dart@@ -33,6 +33,11 @@ class BufferLine with IndexedItem {int get length => _length;+ /// Local text caches can reuse an unchanged line without rereading its cells.+ /// Color-only changes do not invalidate text; wrapping is tracked separately.+ int get textVersion => _textVersion;+ int _textVersion = 0;+final _anchors = <CellAnchor>[];List<CellAnchor> get anchors => _anchors;@@ -70,6 +75,7 @@ class BufferLine with IndexedItem {}CellData createCellData(int index) {+ _textVersion++;final cellData = CellData.empty();final offset = index * _cellSize;_data[offset + _cellForeground] = cellData.foreground;@@ -92,6 +98,7 @@ class BufferLine with IndexedItem {}void setContent(int index, int value) {+ _textVersion++;_data[index * _cellSize + _cellContent] = value;}@@ -101,6 +108,7 @@ class BufferLine with IndexedItem {}void setCell(int index, int char, int witdh, CursorStyle style) {+ _textVersion++;final offset = index * _cellSize;_data[offset + _cellForeground] = style.foreground;_data[offset + _cellBackground] = style.background;@@ -109,6 +117,7 @@ class BufferLine with IndexedItem {}void setCellData(int index, CellData cellData) {+ _textVersion++;final offset = index * _cellSize;_data[offset + _cellForeground] = cellData.foreground;_data[offset + _cellBackground] = cellData.background;@@ -117,6 +126,7 @@ class BufferLine with IndexedItem {}void eraseCell(int index, CursorStyle style) {+ _textVersion++;final offset = index * _cellSize;_data[offset + _cellForeground] = style.foreground;_data[offset + _cellBackground] = style.background;@@ -125,6 +135,7 @@ class BufferLine with IndexedItem {}void resetCell(int index) {+ _textVersion++;final offset = index * _cellSize;_data[offset + _cellForeground] = 0;_data[offset + _cellBackground] = 0;@@ -246,6 +257,7 @@ class BufferLine with IndexedItem {}}+ _textVersion++;_length = length;for (var i = 0; i < _anchors.length; i++) {@@ -287,6 +299,7 @@ class BufferLine with IndexedItem {/// Copies [len] cells from [src] starting at [srcCol] to [dstCol] at this/// line.void copyFrom(BufferLine src, int srcCol, int dstCol, int len) {+ _textVersion++;resize(dstCol + len);// data.setRange(diff --git a/desktop/third_party/xterm/lib/src/terminal.dart b/desktop/third_party/xterm/lib/src/terminal.dartindex 461e2084a..0c174438e 100644--- a/desktop/third_party/xterm/lib/src/terminal.dart+++ b/desktop/third_party/xterm/lib/src/terminal.dart@@ -346,9 +346,20 @@ class Terminal with Observable implements TerminalState, EscapeHandler {return false;}- /// Resize the terminal screen. [newWidth] and [newHeight] should be greater- /// than 0. Text reflow is currently not implemented and will be avaliable in- /// the future.+ Set<void Function()>? _resizeListeners;++ /// Observes completed local buffer reflow without replacing the transport's+ /// onResize callback. No observer set is retained when the last user leaves.+ void addResizeListener(void Function() listener) {+ (_resizeListeners ??= {}).add(listener);+ }++ void removeResizeListener(void Function() listener) {+ _resizeListeners?.remove(listener);+ if (_resizeListeners?.isEmpty == true) _resizeListeners = null;+ }++ /// Resize the screen and notify local observers after buffer reflow.@overridevoid resize(int newWidth,@@ -374,6 +385,9 @@ class Terminal with Observable implements TerminalState, EscapeHandler {_altBuffer.resetVerticalMargins();_mainBuffer.resetVerticalMargins();+ for (final listener in _resizeListeners ?? const <void Function()>{}) {+ listener();+ }}@overridediff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex 5d6cd80c8..0bc20cd21 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -67,6 +67,14 @@ private extension SwarmTabStrip {["tabs": rows, "activeId": active, "enabled": enabled, "attention": 2]}update(state(rows, active: "swarm-11"))+ let hover = NSEvent.mouseEvent(with: .mouseMoved, location: .zero, modifierFlags: [],+ timestamp: 0, windowNumber: 0, context: nil, eventNumber: 0, clickCount: 0, pressure: 0)!+ try checkTitlebar(tabs[0].showsDivider && tabs[1].showsDivider, "Idle neighboring tabs have separators")+ tabs[1].mouseEntered(with: hover)+ try checkTitlebar(!tabs[0].showsDivider && !tabs[1].showsDivider, "Hover clears separators on both sides of the tab")+ tabs[1].mouseExited(with: hover)+ try checkTitlebar(tabs[0].showsDivider && tabs[1].showsDivider, "Separators return when the pointer leaves")+ try checkTitlebar(!tabs[10].showsDivider && !tabs[11].showsDivider, "Selected tab remains joined without neighboring separators")try checkTitlebar(tabs.count == 24, "All overflow tabs exist")try checkTitlebar(!newButton.isEnabled, "New tab is disabled at capacity")for (index, tab) in tabs.enumerated() {@@ -122,6 +130,13 @@ private extension SwarmTitlebar {guard let window else { throw TitlebarCheckFailure(message: "Native test window exists") }let main = NSMenu()main.addItem(NSMenuItem(title: "Harness V2", action: nil, keyEquivalent: ""))+ let edit = NSMenuItem(title: "Edit", action: nil, keyEquivalent: "")+ edit.submenu = NSMenu(title: "Edit")+ let find = NSMenuItem(title: "Find", action: nil, keyEquivalent: "")+ find.submenu = NSMenu(title: "Find")+ find.submenu?.addItem(NSMenuItem(title: "Find and Replace…", action: nil, keyEquivalent: "f"))+ edit.submenu?.addItem(find)+ main.addItem(edit)NSApp.mainMenu = mainconfigure()guard let menu = main.items.first(where: { $0.title == "Swarm" })?.submenu,@@ -135,6 +150,20 @@ private extension SwarmTitlebar {try checkTitlebar(!validateMenuItem(attention), "Native attention shortcut is disabled behind a modal")actionsEnabled = truetry checkTitlebar(validateMenuItem(attention), "Native attention shortcut returns when the modal closes")+ let findItems = find.submenu?.items ?? []+ try checkTitlebar(findItems.map(\.title) == ["Find in Terminal…", "Find Next", "Find Previous"], "Find replaces the unused editor actions with terminal commands")+ try checkTitlebar(findItems.map(\.keyEquivalent) == ["f", "g", "g"], "Native find shortcuts match Flutter")+ try checkTitlebar(findItems.last?.keyEquivalentModifierMask == [.command, .shift], "Previous match uses Shift-Command-G")+ for item in findItems {+ canFind = false+ try checkTitlebar(!validateMenuItem(item), "Find is disabled without a focused terminal")+ canFind = true+ try checkTitlebar(validateMenuItem(item), "Find is enabled for a focused terminal")+ actionsEnabled = false+ try checkTitlebar(!validateMenuItem(item), "Find cannot run behind a modal")+ actionsEnabled = true+ try checkTitlebar(item.target === self && item.action == #selector(menuAction(_:)), "Find uses the guarded channel handler")+ }strip.update(["enabled": true, "activeId": "swarm-11","tabs": (0..<12).map { ["id": "swarm-\($0)", "name": "Swarm \($0)"] },diff --git a/docs/harness-v2-developer-tools-research.md b/docs/harness-v2-developer-tools-research.mdindex 3ee8c40be..cacc2952a 100644--- a/docs/harness-v2-developer-tools-research.md+++ b/docs/harness-v2-developer-tools-research.md@@ -50,6 +50,7 @@ The opportunity for Harness is to make movement among real agents across real ma| **Keep and harden** | Shared terminal controllers, saved membership, reconnect and local/remote discovery | This is the foundation. Preserve input ownership, scrollback and chosen arrangements through interruption. Validate remote failures on real linked machines; do not infer that a disconnected agent stopped. || **Implemented; verify in daily use** | `Cmd+P` jumps to agents and Swarms; `Cmd+Shift+F` opens **Add agent** | Fuzzy search covers name/project/branch/folder/machine context, with recent destinations and shared-view reuse. Existing-view navigation preserves focus/layout and terminal ownership without retrying a stream. No dialog fade or backdrop blur. Unopened agents explicitly offer **Open view** in the captured Swarm. || **Implemented; verify in daily use** | **Needs input** replaces the notifications list; `Cmd+Shift+I` opens it | Search live questions and agent/project/machine context; jump without changing ownership or chosen membership. `Cmd+P`, Return goes back to prior work. Resolved/replaced questions cannot trigger stale navigation. Unavailable terminals remain explicit. Opens on request with no fade, blur or polling. |+| **Implemented; verify in daily use** | Terminal Find with `Cmd+F`, `Cmd+G` and `Cmd+Shift+G` | Search retained output and move between literal matches without sending input. Escape restores the previous scroll position and prompt focus. The compact field uses the existing header, then disappears. These familiar bindings are documented by [Apple Terminal](https://support.apple.com/en-euro/guide/terminal/trmlshtcts/mac) and [Chrome](https://support.google.com/chrome/answer/157179?co=GENIE.Platform%3DDesktop&hl=en). Offline panes that show a connection guide still need retained-output support. || **Preserve compatibility** | Real agent terminals and user shell environments | Verify selection, multiline/image paste, scrollback, nested tmux/Vim and escape/control keys. Before promising a full terminal replacement, verify a straightforward ordinary-shell workflow too; the current New agent UI centers on detected agent engines. || **Remove from active work — implemented** | Wallpaper behind populated Swarms | Use `#463746`, matching the selected native tab. Wallpaper fills only an empty New swarm canvas and its decoded cache entry is evicted when that view is disposed. || **Reduce prominence** | “Next wallpaper” button, repeated metadata, permanent Settings gear | Keep appearance choices in a secondary location. Keep machine identity legible where needed to distinguish remote work. Settings already has `Cmd+,` and the app menu; consider reclaiming the extra toolbar control. These are proposals, not removed features. |diff --git a/docs/harness-v2-performance.md b/docs/harness-v2-performance.mdindex 03b8e7e11..fe4b67172 100644--- a/docs/harness-v2-performance.md+++ b/docs/harness-v2-performance.md@@ -141,13 +141,43 @@ Cmd+Shift+I opens the existing bell's **Needs input** surface without the priorKeyboard selection in both pickers now adjusts the scroll offset during the key event, before painting. The earlier post-frame scroll could leave the new selection offscreen for a frame. Tests require the selected row to be visible after a single pump on each arrow movement, including past the bottom edge. Live catalog changes still reveal selection after the new list dimensions exist, with at most one scheduled reveal callback.-Nine new state/widget checks pass, alongside the extended native command guards. They cover immediate search focus, Ctrl-N/P, 2× text at 880×600, stale question/view guards and the cross-Swarm round trip: select a waiting agent, deliver input only there, then Cmd+P / Return and deliver input only to the prior agent. The final full suite passes 1,023 tests with one skip. These are frame-order and correctness checks, not measurements of physical input-to-display latency.+Nine new state/widget checks pass, alongside the extended native command guards. They cover immediate search focus, Ctrl-N/P, 2× text at 880×600, stale question/view guards and the cross-Swarm round trip: select a waiting agent, deliver input only there, then Cmd+P / Return and deliver input only to the prior agent. That continuation passed 1,023 tests with one skip. These are frame-order and correctness checks, not measurements of physical input-to-display latency.++## Terminal Find and tab hover++Cmd+F mounts a small field in the focused pane's existing header. It neither changes the terminal viewport nor covers output. Cmd+G / Cmd+Shift+G and Enter / Shift+Enter select matches; Escape restores the original scroll bookmark and input focus. A real keyframe preserves the text controller, caret, query and focus while replacing the emulator. This test also exposed a resize debounce callback whose handle was dropped by a keyframe's immediate flush; the flush now cancels that pending callback first.++The literal Unicode search joins soft-wrapped lines and keeps hard lines distinct. An optional index reuses decoded text from unchanged line identities and versions, yields after about 1.5 ms of scan work, and stores one offset checkpoint per 64 matches. Only the selected search result owns an anchor; the renderer highlights that result separately from normal terminal selection. Already-valid matches remain navigable while output refreshes. Hidden, covered and inactive searches release the index and listeners, retaining the query and selected location. Closing Find leaves no search listener or timer. Line-version increments remain in the ordinary buffer mutation path.++Sequential isolated benchmarks (`--concurrency=1`, with no other test/build running) use 10,000 retained rows at 120 columns. These are debug event-loop times including cooperative yields, excluding native input, display, transport and file search:++| Operation | Median | p95 |+| --- | --- | --- |+| Cold query, one observation | 42.181 ms | — |+| Changed query over cached text, 40 samples | 7.183 ms | 15.497 ms |+| Live single-row output refresh, 40 samples | 2.809 ms | 7.452 ms |+| Move to next match, 40 samples | 0.004 ms | 0.026 ms |++Background-output comparison before/after line versioning and Find:++| Retained terminals / scope | Before median / p95 | After median / p95 |+| --- | --- | --- |+| 16 / hidden | 0.120 / 0.169 ms | 0.118 / 0.165 ms |+| 16 / all | 0.790 / 1.665 ms | 0.818 / 1.362 ms |+| 48 / hidden | 0.195 / 0.218 ms | 0.205 / 0.246 ms |+| 48 / all | 0.736 / 0.912 ms | 0.774 / 1.048 ms |++All hidden-output samples still reported zero hidden renderers needing layout and no scheduled frame. Several median timings increased by about 4–5%; these shared-workstation observations do not isolate that difference or establish zero overhead. Logs: `/private/tmp/harness-v2-find-benchmark.log` and `/private/tmp/harness-v2-find-output-before.log`. The earlier overlapping benchmark run was replaced by this sequential result.++The final full suite passes 1,035 tests with one skip; the analyzer reports zero errors/warnings and 12 existing vendored infos. Find checks cover literal/wide-character mapping, reflow and buffer changes, 50,000 repeated matches, cancellation/eviction, immediate navigation during output, first-frame opening, no resize or agent input, hidden suspension, keyframe focus preservation, read-only ownership, and a narrow field at 2× text. Offline panes still show a connection guide in place of their retained renderer, so offline search is not yet available.++Native tab hover now hides both adjacent separators, uses a 28-point shape with 12-point corners, and aligns 13-point text with a 10-point close symbol. The title and paragraph layout are cached until the name or selection changes. Before/after native component renders were inspected, alongside an isolated Flutter Find render; neither substitutes for live native interaction or physical-display timing.## Native follow-upThe optimized real-data app builds and runs locally. The native tab/canvas polish was visually reviewed before the navigation and retained-canvas continuations; CUA currently returns `cgWindowNotFound` for the rebuilt Release preview, so those newer interactions still need live native review. The tab strip uses AppKit's compact unified title bar: the old right accessory was clipped to 32 points; the container now supplies 40 points and aligns controls with the system traffic lights.-The native check covers overflow, resizing, accessibility order and disabled actions. `bash tool/check_swarm_titlebar.sh /path/to/flutter --window-layout` adds actual container checks in a hidden window at three widths, for 176 assertions total, including the native attention shortcut and its modal guard. No Flutter engine, account or terminal is accessed.+The native check covers overflow, resizing, accessibility order and disabled actions. `bash tool/check_swarm_titlebar.sh /path/to/flutter --window-layout` adds actual container checks in a hidden window at three widths, for 195 assertions total, including hover separators and native Find/attention shortcuts and modal guards. No Flutter engine, account or terminal is accessed.Wallpaper is built only for the empty New swarm. Populated Swarms paint a flat color matching the selected native tab, and the disposed wallpaper evicts its own decoded cache entry. This removes wallpaper painting/cache retention from the active terminal canvas; no process-memory reduction has been measured yet.diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.mdindex ba20e53d9..0cae484ac 100644--- a/docs/harness-v2-progress.md+++ b/docs/harness-v2-progress.md@@ -1,6 +1,6 @@# Harness App V2 — development handoff-Updated 2026-09-13 after the keyboard attention continuation. This is a working preview, not a release.+Updated 2026-09-13 after the terminal Find and native hover continuation. This is a working preview, not a release.## Resume here@@ -17,8 +17,10 @@ Updated 2026-09-13 after the keyboard attention continuation. This is a working- Cmd+Shift+I now opens **Needs input** from the existing bell or native Swarm menu. It searches live questions and agent/project/machine context, keeps the oldest first when search is blank, and shares focus-only navigation with Cmd+P. Cmd+P, Return takes you back to the prior agent. Both pickers scroll and highlight keyboard selections in the same frame. Nine new state/widget checks pass, including large text and the full terminal-input round trip.- Swarm terminals now keep the same widget ancestry across tabs, zoom and presets, retaining unchanged cells and headers. The paired headless check reduced median tab-switch CPU time from 20.924 to 12.226 ms with 16 terminals and from 14.151 to 8.925 ms with 48; focus changes also improved. Settings route and section fades are removed. These are debug CPU measurements, not native input-to-display timings.- Cursor timers now follow the active, focused terminal, stopping for hidden/covered views and inactive windows. With 48 retained terminals, the isolated five-second observation fell from 480 periodic callbacks to 10 in the foreground and zero when inactive. New swarm retains only its search caret timer. Link-modifier keyboard listeners exist only while hovering a visible link. The idle-work continuation's full suite passed 1,010 tests with one skip.-- Ordinary hidden output now updates the buffer without scheduling a renderer frame. The paired 16/48-terminal debug benchmark reduced hidden-output median CPU cost by 88%/84%; mixed visible/hidden output improved by 32%/51%. Restoring a view reconciles its current buffer, scroll and dimensions once; native caret coordinates coalesce after the frame. That continuation passed 1,014 tests with one skip; the current full suite passes 1,023 with one skip.-- The final Release preview was rebuilt and normally relaunched; PID **84666** was the sole V2 instance at the last check. Revalidate the process before any later restart. CUA still reports `cgWindowNotFound` when selecting that full bundle path after this rebuild, as it did after an earlier CUA reset and normal relaunches. CUA's earlier surface inventory listed the preview as running. An earlier relaunched process did have a 1280×840 onscreen CoreGraphics window. Bundle-ID selection was also ambiguous with the retained backup under `/Users/ab/code/harness-app-v2`; no backup was altered. Do not claim the new jump/Needs input interaction, stable canvas, cursor lifecycle or renderer restoration was reviewed in the live native window. The actual native titlebar/canvas had been reviewed before these continuations; both pickers were visually inspected in isolated Flutter renders with native font files and engine icons loaded. First-frame renderer pixels and native caret messages are now covered by isolated Flutter checks.+- Ordinary hidden output now updates the buffer without scheduling a renderer frame. The paired 16/48-terminal debug benchmark reduced hidden-output median CPU cost by 88%/84%; mixed visible/hidden output improved by 32%/51%. Restoring a view reconciles its current buffer, scroll and dimensions once; native caret coordinates coalesce after the frame. That continuation passed 1,014 tests with one skip; the current full suite passes 1,035 with one skip.+- The final Release preview was rebuilt and normally relaunched; PID **20082** was the sole V2 instance at the last check. Revalidate the process before any later restart. CUA still reports `cgWindowNotFound` when selecting that full bundle path after this rebuild, as it did after an earlier CUA reset and normal relaunches. CUA's inventory after this rebuild still listed the preview as running, alongside an unlaunched backup with the same bundle ID. An earlier relaunched process did have a 1280×840 onscreen CoreGraphics window. Bundle-ID selection was also ambiguous with the retained backup under `/Users/ab/code/harness-app-v2`; no backup was altered. Do not claim the new Find/jump/Needs input interaction, latest hover refinement, stable canvas, cursor lifecycle or renderer restoration was reviewed in the live native window. The actual native titlebar/canvas had been reviewed before these continuations; both pickers were visually inspected in isolated Flutter renders with native font files and engine icons loaded. First-frame renderer pixels and native caret messages are now covered by isolated Flutter checks.+- Cmd+F now searches retained output in the focused terminal; Cmd+G / Cmd+Shift+G and Enter / Shift+Enter move through matches. Escape restores the previous scroll position and input focus. The field occupies the existing header without resizing the terminal. Find pauses and releases its index when hidden or covered. A keyframe keeps the field, caret and query; read-only rendered panes remain searchable without taking control. Offline panes currently replace retained output with a connection guide, so offline search remains a separate follow-up.+- The latest hover pass uses 13-point native titles, 14-point leading space inside the 28-point hover shape, a 12-point corner radius and a 10-point close symbol. Both neighboring separators disappear on hover. The title layout is cached across hover redraws. Native selected shoulders still meet the flat canvas. Isolated native before/after images were inspected; CUA still could not capture the live window after the normal Release relaunch.- Continue implementation here. Do not create another repository or fork for V2.```bash@@ -143,6 +145,7 @@ Approved reference: `/Users/ab/code/harness-new-ui`, React prototype commit `f83| Previous / next swarm | Cmd+Shift+[ / ], Ctrl+Shift+Tab / Ctrl+Tab || Jump to agent or swarm | Cmd+P || Agents needing input | Cmd+Shift+I |+| Find in terminal / next / previous match | Cmd+F / Cmd+G / Cmd+Shift+G || Add agent picker / New agent | Cmd+Shift+F / Cmd+N || Focus neighboring pane | Cmd+H/J/K/L or Cmd+arrow || Move pane | Cmd+Shift+H/J/K/L or Cmd+Shift+arrow |@@ -164,7 +167,7 @@ The reopen binding follows the documented Mac tab-recovery shortcut in [Safari](| --- | --- || macOS debug build | Passed and launched from the monorepo with real saved Swarms and terminals. || macOS optimized local build | Passed and running with the real entry point and saved V2 state. Local ad hoc signing requires the command-line `ENABLE_HARDENED_RUNTIME=NO` override for Flutter's framework; distribution signing settings remain unchanged. The distribution Developer ID certificate is unavailable; nothing was uploaded. Normal asynchronous quit and relaunch were verified. Unlocked native review confirmed the taller tab container, edge-to-edge empty wallpaper, and the flat populated canvas joining the selected tab. The native hover rendering was also inspected in a local image. |-| Full Flutter suite | **1,023 passed, 1 skipped** on the final keyboard attention production code, including terminal, modal, persistence, layout and shortcut regressions. |+| Full Flutter suite | **1,035 passed, 1 skipped** on the final terminal Find and native hover code, including terminal, modal, persistence, layout and shortcut regressions. || Hidden rendering and native caret | Four new checks cover binary output arriving without hidden layout/frame requests; retained selection, manual scroll and follow-tail; first-visible-frame raster pixels; changed emulator dimensions and preserved TUI scroll regions; covered routes; and coalesced/fresh caret coordinates. The focused restoration/IME/key-ownership run passed 22 checks. || Cursor and link activity | Four new checks cover one cursor clock across retained Swarms/focus/zoom, immediate suspension for inactive windows and disabled ticker mode, session replacement and read-only/connection ownership, and stationary link hover across session replacement/modifier release. The earlier focused cursor/session run passed 74 checks. || Retained canvas and header | Five new checks cover stable element ancestry and terminal State across tabs/zoom/presets, first-frame per-Swarm scrolling, tall splits and hidden geometry, font metrics at unchanged point size, and fresh header metadata/callbacks. Layout checks compare legacy and Swarm geometry for all fixed presets and auto layouts at two sizes. |@@ -180,7 +183,7 @@ The reopen binding follows the documented Mac tab-recovery shortcut in [Safari](| Headless performance | The prior five-case catalog/terminal/output benchmark passed. The paired retained-canvas continuation reran both 16/48-terminal cases with new focus measurements: tab medians 12.226 / 8.925 ms and focus medians 5.284 / 4.586 ms. Reproducible commands and limits in `docs/harness-v2-performance.md`. || Idle-work measurement | Both isolated timer scenarios passed: 16/48 retained terminals now share one focused cursor clock, with 10 callbacks in five seconds, and zero terminal cursor callbacks when the window is inactive or an empty Swarm is shown. Empty New swarm keeps its search field's caret timer. These are fake-clock structural counts, not native process CPU/battery measurements. || Background output measurement | Both 16/48-terminal cases passed with hidden-only and mixed output. Hidden dirty renderers fell from 12/44 to zero; hidden-only bursts schedule no frame in this workload. Final CPU medians are 0.110/0.206 ms for hidden output and 0.757/0.766 ms for all-terminal output. See performance notes for scope and paired results. |-| AppKit components and container | **176 assertions passed**: component, attention shortcut/menu/modal checks plus native-container checks at 880, 1280 and 1920 points. These verify height, traffic-light clearance/alignment, direct contact with the content edge and active-tab visibility. The optional container check creates a hidden native window; no window is displayed and no engine, account or terminal is accessed. |+| AppKit components and container | **195 assertions passed**: component, hover separator behavior, terminal Find/attention shortcut/menu/modal checks plus native-container checks at 880, 1280 and 1920 points. These verify height, traffic-light clearance/alignment, direct contact with the content edge and active-tab visibility. The optional container check creates a hidden native window; no window is displayed and no engine, account or terminal is accessed. || Remote terminals / production release | No remote takeover, release, installer, or production CLI update/restart. Cross-platform and end-to-end latency measurements remain. |Tests now exercise the actual V2 welcome/settings/linking flow. Usage pricing again explains a partial estimate as a lower bound. Small offline panes avoid overflowing the full connection guide. No remaining full-suite failures are being dismissed as baseline.@@ -189,9 +192,16 @@ Tests now exercise the actual V2 welcome/settings/linking flow. Usage pricing agEvidence on this Mac under `/private/tmp`:+- `harness-v2-find-full-tests.log`: 1,035 passed, one existing skip.+- `harness-v2-find-focused.log`: 99 focused checks, including one isolated visual fixture; `harness-v2-find-visual-tests.log`: final six-case render/find pass.+- `harness-v2-find-native.log`: 195 AppKit checks, including hidden native window geometry and hover separators.+- `harness-v2-find-analyze.log`: current diagnostics, zero errors/warnings and 12 existing vendored infos.+- `harness-v2-find-benchmark.log`: sequential three-case terminal Find/background-output run; `harness-v2-find-output-before.log`: pre-index versioning background baseline. Timings and limits are in the performance notes.+- `harness-titlebar-before.png`, `harness-titlebar-after.png`, `harness-find-review.png`: inspected isolated native/Flutter renders, not live app captures.+- `harness-v2-background-full-tests.log`: full 1,014-test pass on the final production changes.- `harness-v2-background-caret-tests.log`: 22 restoration/IME/key-ownership checks, including raster and native-caret assertions.-- `harness-v2-background-analyze.log`: latest diagnostics, 0 errors/warnings and 12 existing vendored infos.+- `harness-v2-background-analyze.log`: earlier background-work diagnostics, 0 errors/warnings and 12 existing vendored infos.- `harness-v2-background-before.log`, `harness-v2-background-measured.log`: paired parser/render CPU measurements and hidden layout/frame counts.- `harness-v2-idle-full-tests.log`: full 1,010-test pass on the idle-work changes.- `harness-v2-idle-tests.log`: 74 cursor/session/focus/canvas checks before the hover-listener change.@@ -231,7 +241,8 @@ Earlier logs contain superseded failures. Temporary logs and toolchains are loca3. Measure native terminal input and tab-switch responsiveness before making end-to-end latency claims. Headless CPU benchmarks are now recorded. Preserve the existing immediate first-input flush and shared retained renderers.4. Visually confirm app-menu modal behavior and overflow accessibility in AppKit; route/shortcut behavior is covered by passing Flutter tests.5. Build/review Linux and Windows when their toolchains are available. Remote full project/branch metadata requires daemons running the new wire format; do not upgrade them automatically.-6. Continue the agreed goal and apply the latest steering. The research proposes a focused roadmap and specific subtraction candidates; do not mistake proposals for already-implemented removals.+6. Preserve retained terminal output when an offline pane shows a connection guide, then enable offline Find without reconnecting or taking control. Current Find searches only the buffer rendered by TerminalPanel, not remote files or unretained history.+7. Continue the agreed goal and apply the latest steering. The research proposes a focused roadmap and specific subtraction candidates; do not mistake proposals for already-implemented removals.## Toolchain and workflow