Skip to content

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

feat(desktop): edit global search directly in the title bar

dee17544eda39af
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index 7fedf6e25..c2afba98f 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -17,6 +17,7 @@ import '../terminal/terminal_viewport.dart';
import '../state/swarm_catalog.dart';
import '../state/swarm_attention.dart';
import '../state/swarm_navigation.dart';
+import '../state/swarm_search.dart';
import '../widgets/layout_palette.dart';
import '../widgets/link_machine_screen.dart';
import '../widgets/new_agent_dialog.dart';
@@ -54,6 +55,15 @@ class _SwarmScreenState extends State<SwarmScreen> {
StreamSubscription<SpokenTaskRequest>? _spokenTasks;
final _shellFocus = FocusNode(debugLabel: 'Swarm shell');
final _navigation = SwarmNavigationHistory();
+ final _searchText = TextEditingController();
+ final _searchFocus = FocusNode(debugLabel: 'Title bar search');
+ final _searchAnchor = LayerLink();
+ SwarmSearchController? _search;
+ OverlayEntry? _searchOverlay;
+ FocusNode? _searchReturnFocus;
+ double _nativeSearchWidth = 600;
+ String? _searchFieldState;
+ bool _nativeQueryChange = false;
bool _spokenPaletteOpen = false;
bool _dialogOpen = false;
bool _routeIsCurrent = true;
@@ -69,6 +79,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
_recordNavigation();
app.addListener(_recordNavigation);
FocusManager.instance.addListener(_restoreEmptyFocus);
+ _searchFocus.addListener(_searchFocusChanged);
unawaited(_projects.load());
_spokenTasks = app.spokenTasks.listen(_openSpokenTask);
if (_native) {
@@ -84,6 +95,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
final current = ModalRoute.isCurrentOf(context) ?? true;
if (_routeIsCurrent == current) return;
_routeIsCurrent = current;
+ if (!current && _search != null) {
+ WidgetsBinding.instance.addPostFrameCallback((_) {
+ if (mounted && !_routeIsCurrent) _closeSearch(restoreFocus: false);
+ });
+ }
if (_native) _syncNative();
}
@@ -91,6 +107,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
void dispose() {
app.removeListener(_recordNavigation);
FocusManager.instance.removeListener(_restoreEmptyFocus);
+ _searchOverlay?.remove();
+ _searchOverlay?.dispose();
+ _search?.dispose();
+ _searchFocus.dispose();
+ _searchText.dispose();
_shellFocus.dispose();
unawaited(_spokenTasks?.cancel());
if (_native) {
@@ -104,7 +125,12 @@ class _SwarmScreenState extends State<SwarmScreen> {
super.dispose();
}
- void _recordNavigation() => _navigation.record(app);
+ void _recordNavigation() {
+ _navigation.record(app);
+ if (_search != null && _search!.targetId != app.activeSwarmId) {
+ _closeSearch(restoreFocus: false);
+ }
+ }
int get _attention =>
app.machineStates.values.fold(0, (n, m) => n + m.blockedAgents.length);
@@ -114,6 +140,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.panes.isNotEmpty ||
_dialogOpen ||
_spokenPaletteOpen ||
+ _search != null ||
ModalRoute.of(context)?.isCurrent == false ||
_shellFocus.hasFocus) {
return;
@@ -189,6 +216,50 @@ class _SwarmScreenState extends State<SwarmScreen> {
return;
}
final args = call.arguments is Map ? call.arguments as Map : const {};
+ if (call.method == 'searchBegin') {
+ _openSearch();
+ _updateSearchGeometry(args);
+ return;
+ }
+ if (call.method == 'searchGeometry') {
+ _updateSearchGeometry(args);
+ return;
+ }
+ if (call.method == 'searchChanged') {
+ // The field editor is authoritative while typing. Echoing an earlier
+ // query back over the channel could replace a newer edit or marked text.
+ _nativeQueryChange = true;
+ try {
+ if (args['query'] is String) _search?.setQuery(args['query']);
+ } finally {
+ _nativeQueryChange = false;
+ }
+ return;
+ }
+ if (call.method == 'searchCommand') {
+ final search = _search;
+ if (search == null) return;
+ switch (args['command']) {
+ case 'next':
+ search.move(1);
+ case 'previous':
+ search.move(-1);
+ case 'back':
+ search.back();
+ case 'submit':
+ final choice = search.submit();
+ if (choice != null) await _chooseSearch(choice);
+ case 'add':
+ final choice = search.addHere();
+ if (choice != null) await _chooseSearch(choice);
+ case 'close':
+ _closeSearch();
+ case 'dismiss':
+ _closeSearch();
+ }
+ return;
+ }
+ if (call.method != 'jump') _closeSearch(restoreFocus: false);
switch (call.method) {
case 'new':
app.newSwarm();
@@ -260,6 +331,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
Future<void> _dialog(Future<void> Function() action) async {
if (_dialogOpen || _spokenPaletteOpen || !mounted) return;
+ _closeSearch();
_dialogOpen = true;
if (_native) _syncNative();
try {
@@ -304,22 +376,28 @@ class _SwarmScreenState extends State<SwarmScreen> {
);
});
Future<void> _jump({bool historyOnly = false}) async {
+ if (!historyOnly) {
+ _openSearch();
+ _focusSearch(selectAll: true);
+ return;
+ }
final target = app.activeSwarmId;
SwarmSearchSelection? selected;
await _dialog(() async {
- selected = await showSwarmSwitcher(
- context,
- app,
- _navigation,
- historyOnly: historyOnly,
- projects: _projects,
- );
+ selected = await showSwarmHistory(context, app, _navigation);
});
if (!mounted || selected == null) return;
+ await _activateSearch(selected!, target);
+ }
+
+ Future<void> _activateSearch(
+ SwarmSearchSelection selected,
+ String target,
+ ) async {
_preparePaneFocus();
final opened = await activateSwarmSearchSelection(
app,
- selected!,
+ selected,
destinationSwarmId: target,
projects: _projects.projects,
);
@@ -332,6 +410,199 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
}
+ void _searchFocusChanged() {
+ if (_searchFocus.hasFocus && _search == null) _openSearch();
+ }
+
+ void _openSearch() {
+ if (_search != null ||
+ !mounted ||
+ _dialogOpen ||
+ _spokenPaletteOpen ||
+ !_routeIsCurrent) {
+ return;
+ }
+ _searchReturnFocus ??= FocusManager.instance.primaryFocus == _searchFocus
+ ? null
+ : FocusManager.instance.primaryFocus;
+ if (_native) _preparePaneFocus();
+ _search = SwarmSearchController(
+ app,
+ _navigation.recent,
+ projects: _projects,
+ );
+ _search!.addListener(_syncSearch);
+ _searchOverlay = OverlayEntry(builder: _buildSearchOverlay);
+ Overlay.of(context).insert(_searchOverlay!);
+ _nativeQueryChange = _native;
+ _syncSearch();
+ _nativeQueryChange = false;
+ setState(() {});
+ // Flutter releases its text client before AppKit takes the caret. This
+ // prevents a terminal's old client from reclaiming the field editor.
+ if (_native) _focusSearch();
+ }
+
+ void _focusSearch({bool selectAll = false}) {
+ if (_search == null) return;
+ if (_native) {
+ unawaited(
+ _channel.invokeMethod<void>('focusSearch', {'selectAll': selectAll}),
+ );
+ } else {
+ _searchFocus.requestFocus();
+ if (selectAll) {
+ _searchText.selection = TextSelection(
+ baseOffset: 0,
+ extentOffset: _searchText.text.length,
+ );
+ }
+ }
+ }
+
+ void _syncSearch() {
+ final search = _search;
+ if (search == null) return;
+ if (_searchText.text != search.query) {
+ _searchText.value = TextEditingValue(
+ text: search.query,
+ selection: TextSelection.collapsed(offset: search.query.length),
+ );
+ }
+ final state = {
+ 'query': search.query,
+ 'hint': search.hint,
+ 'scoped': search.scoped,
+ };
+ final encoded = jsonEncode(state);
+ if (_searchFieldState != encoded) {
+ _searchFieldState = encoded;
+ if (_native) {
+ unawaited(
+ _channel.invokeMethod<void>('searchState', {
+ if (!_nativeQueryChange) 'query': search.query,
+ 'hint': search.hint,
+ 'scoped': search.scoped,
+ }),
+ );
+ }
+ }
+ _searchOverlay?.markNeedsBuild();
+ }
+
+ void _updateSearchGeometry(Map args) {
+ if (args['width'] is num) {
+ _nativeSearchWidth = (args['width'] as num).toDouble();
+ _searchOverlay?.markNeedsBuild();
+ }
+ }
+
+ void _closeSearch({bool restoreFocus = true}) {
+ if (_search == null) return;
+ _searchOverlay?.remove();
+ _searchOverlay?.dispose();
+ _searchOverlay = null;
+ _search!.removeListener(_syncSearch);
+ _search!.dispose();
+ _search = null;
+ _searchFieldState = null;
+ _searchText.clear();
+ _searchFocus.unfocus();
+ if (_native) unawaited(_channel.invokeMethod<void>('closeSearch'));
+ final previous = _searchReturnFocus;
+ _searchReturnFocus = null;
+ if (restoreFocus) {
+ if (previous?.context != null && previous!.canRequestFocus) {
+ previous.requestFocus();
+ } else {
+ _shellFocus.requestFocus();
+ }
+ }
+ if (mounted) setState(() {});
+ }
+
+ Future<void> _chooseSearch(SwarmSearchSelection choice) async {
+ final target = _search?.targetId;
+ if (target == null) return;
+ _closeSearch(restoreFocus: false);
+ await _activateSearch(choice, target);
+ }
+
+ double _searchWidth(double available) =>
+ _search == null ? 192 : (available - 200).clamp(140, 600).toDouble();
+
+ Widget _buildSearchOverlay(BuildContext context) {
+ final search = _search!;
+ return LayoutBuilder(
+ builder: (context, constraints) {
+ final width =
+ (_native ? _nativeSearchWidth : _searchWidth(constraints.maxWidth))
+ .clamp(128.0, constraints.maxWidth - 16);
+ final scale = MediaQuery.textScalerOf(context);
+ final rowHeight = (scale.scale(13) + scale.scale(11) + 32).clamp(
+ 56,
+ double.infinity,
+ );
+ final height =
+ (search.rows.length.clamp(1, 7) * rowHeight +
+ 64 +
+ (search.scoped ? 48 : 0))
+ .clamp(140.0, constraints.maxHeight - (_native ? 12 : 56));
+ final results = SizedBox(
+ width: width,
+ height: height.toDouble(),
+ child: Material(
+ key: const ValueKey('swarm-search-results'),
+ elevation: 12,
+ color: grid.AppPalette.panelBg,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(10),
+ side: const BorderSide(color: Colors.white12),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: Padding(
+ padding: const EdgeInsets.all(8),
+ child: SwarmSearchResults(
+ search: search,
+ onChoose: _chooseSearch,
+ onRefocus: _focusSearch,
+ ),
+ ),
+ ),
+ );
+ return Stack(
+ children: [
+ Positioned(
+ top: _native ? 0 : 44,
+ left: 0,
+ right: 0,
+ bottom: 0,
+ child: GestureDetector(
+ behavior: HitTestBehavior.opaque,
+ onTap: _closeSearch,
+ ),
+ ),
+ if (_native)
+ Positioned(top: 6, right: 8, child: results)
+ else
+ Positioned(
+ left: 0,
+ top: 0,
+ child: CompositedTransformFollower(
+ link: _searchAnchor,
+ showWhenUnlinked: false,
+ targetAnchor: Alignment.bottomRight,
+ followerAnchor: Alignment.topRight,
+ offset: const Offset(0, 6),
+ child: results,
+ ),
+ ),
+ ],
+ );
+ },
+ );
+ }
+
void _stepHistory(int direction) {
if (direction < 0
? !_navigation.canGoBack(app)
@@ -422,6 +693,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
spoken.cancelled();
return;
}
+ _closeSearch();
_spokenPaletteOpen = true;
if (_native) _syncNative();
try {
@@ -444,6 +716,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
!machine.needsLink ||
machine.isLocalMachine ||
_dialogOpen ||
+ _search != null ||
app.isLinkPromptDismissed(machine.machine.machineId) ||
_linkDialogMachineId != null) {
return;
@@ -639,7 +912,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
child: Row(
children: [
const SizedBox(width: 10),
- Flexible(
+ Expanded(
child: ReorderableListView.builder(
scrollDirection: Axis.horizontal,
shrinkWrap: true,
@@ -703,32 +976,67 @@ class _SwarmScreenState extends State<SwarmScreen> {
: null,
icon: const Icon(Icons.add, size: 18),
),
- const Spacer(),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 8),
- child: SizedBox(
- width: 192,
- height: 28,
- child: OutlinedButton(
- onPressed: _jump,
- style: OutlinedButton.styleFrom(
- padding: const EdgeInsets.symmetric(horizontal: 10),
- foregroundColor: grid.AppPalette.swarmAccent,
- backgroundColor: grid.AppPalette.swarmField,
- side: const BorderSide(color: Colors.white10),
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(8),
+ child: CompositedTransformTarget(
+ link: _searchAnchor,
+ child: SizedBox(
+ width: _searchWidth(MediaQuery.sizeOf(context).width),
+ height: 28,
+ child: ListenableBuilder(
+ listenable: _search ?? _searchText,
+ builder: (context, _) => SwarmSearchKeys(
+ search: _search,
+ editing: _searchText,
+ onChoose: _chooseSearch,
+ onClose: _closeSearch,
+ child: Listener(
+ onPointerDown: (_) => _openSearch(),
+ child: TextField(
+ key: const ValueKey('swarm-search-input'),
+ controller: _searchText,
+ focusNode: _searchFocus,
+ onChanged: (query) => _search?.setQuery(query),
+ style: const TextStyle(fontSize: 12),
+ textAlignVertical: TextAlignVertical.center,
+ decoration: InputDecoration(
+ hintText: _search?.hint ?? 'Search…',
+ isDense: true,
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 10,
+ ),
+ prefixIcon: const Icon(Icons.search, size: 14),
+ prefixIconConstraints: const BoxConstraints.tightFor(
+ width: 30,
+ height: 28,
+ ),
+ suffixIcon: _search == null
+ ? const Padding(
+ padding: EdgeInsets.only(right: 10),
+ child: Text(
+ '⌘P',
+ style: TextStyle(fontSize: 11),
+ ),
+ )
+ : null,
+ suffixIconConstraints: const BoxConstraints(
+ minWidth: 24,
+ ),
+ filled: true,
+ fillColor: grid.AppPalette.swarmField,
+ border: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(8),
+ borderSide: const BorderSide(color: Colors.white12),
+ ),
+ enabledBorder: OutlineInputBorder(
+ borderRadius: BorderRadius.circular(8),
+ borderSide: const BorderSide(color: Colors.white12),
+ ),
+ ),
+ ),
+ ),
),
),
- child: const Row(
- children: [
- Icon(Icons.search, size: 14),
- SizedBox(width: 8),
- Text('Search…', style: TextStyle(fontSize: 12)),
- Spacer(),
- Text('⌘P', style: TextStyle(fontSize: 11)),
- ],
- ),
),
),
),
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
new file mode 100644
index 000000000..072d4825c
--- /dev/null
+++ b/desktop/lib/state/swarm_search.dart
@@ -0,0 +1,151 @@
+import 'package:flutter/foundation.dart';
+
+import 'app_state.dart';
+import 'swarm_catalog.dart';
+import 'swarm_navigation.dart';
+
+/// One search session, shared by the native/Flutter input and its results.
+/// Keystrokes only filter the cached catalog; they never query a machine.
+class SwarmSearchController extends ChangeNotifier {
+ SwarmSearchController(this.app, this.recent, {this.projects, this.history})
+ : targetId = app.activeSwarmId,
+ targetName = app.activeSwarm.name {
+ _refresh();
+ app.addListener(_refresh);
+ projects?.addListener(_refresh);
+ }
+
+ final AppNotifier app;
+ final List<String> recent;
+ final SwarmProjectStore? projects;
+ final SwarmNavigationHistory? history;
+ final String targetId, targetName;
+ final _cache = SwarmSearchCatalog();
+ List<SwarmDestination> _catalog = const [];
+ List<SwarmDestination> rows = const [];
+ String query = '', _rootQuery = '';
+ String? _scopeId, _selectedId;
+ int cursor = 0;
+
+ SwarmDestination? get selected => rows.isEmpty ? null : rows[cursor];
+ bool get scoped => _scopeId != null;
+ SwarmDestination? get scope =>
+ _catalog.where((row) => row.id == _scopeId).firstOrNull;
+ String get hint => history != null
+ ? 'Search history…'
+ : scoped
+ ? 'Search agents in ${scope?.title ?? 'this group'}…'
+ : 'Search agents, swarms, machines, projects…';
+
+ void _refresh() {
+ final next = history == null
+ ? _cache.read(app, projects?.projects ?? const [], recent: recent)
+ : [...history!.menuDestinations(app), ...closedSwarmDestinations(app)];
+ if (identical(next, _catalog)) return;
+ _catalog = next;
+ _filter();
+ notifyListeners();
+ }
+
+ void _filter() {
+ final group = scope;
+ rows = rankSwarmDestinations(
+ !scoped
+ ? _catalog
+ : [
+ for (final row in _catalog)
+ if (group?.members.contains(row.id) == true) row,
+ ],
+ query,
+ recent: recent,
+ );
+ final index = rows.indexWhere((row) => row.id == _selectedId);
+ cursor = rows.isEmpty
+ ? 0
+ : index >= 0
+ ? index
+ : cursor.clamp(0, rows.length - 1);
+ _selectedId = selected?.id;
+ }
+
+ void setQuery(String value) {
+ if (query == value) return;
+ query = value;
+ cursor = 0;
+ _selectedId = null;
+ _filter();
+ notifyListeners();
+ }
+
+ void move(int delta) {
+ if (rows.isEmpty) return;
+ cursor = (cursor + delta) % rows.length;
+ _selectedId = selected!.id;
+ notifyListeners();
+ }
+
+ SwarmSearchSelection? submit([SwarmDestination? row]) {
+ final destination = row ?? selected;
+ if (destination == null) return null;
+ if (!destination.isGroup) return SwarmSearchSelection(destination);
+ _rootQuery = query;
+ _scopeId = destination.id;
+ query = '';
+ cursor = 0;
+ _selectedId = null;
+ _filter();
+ notifyListeners();
+ return null;
+ }
+
+ void back() {
+ if (!scoped) return;
+ _selectedId = _scopeId;
+ _scopeId = null;
+ query = _rootQuery;
+ _filter();
+ notifyListeners();
+ }
+
+ bool canAdd(SwarmDestination? row) =>
+ history == null &&
+ row?.agentId != null &&
+ row!.hasView &&
+ app.swarms.any(
+ (swarm) =>
+ swarm.id == targetId &&
+ swarm.panes.length < AppNotifier.maxPanes &&
+ !swarm.panes.any(
+ (pane) =>
+ pane.machineId == row.machineId &&
+ pane.agentId == row.agentId,
+ ),
+ );
+
+ SwarmSearchSelection? addHere() => canAdd(selected)
+ ? SwarmSearchSelection(selected!, SwarmSearchAction.addHere)
+ : null;
+
+ bool get canOpenGroup =>
+ scope != null &&
+ scope!.members.isNotEmpty &&
+ scope!.members.length <= AppNotifier.maxPanes &&
+ app.swarms.length < AppNotifier.maxSwarms;
+
+ static String action(SwarmDestination row) => row.closedId != null
+ ? 'Reopen'
+ : row.isGroup
+ ? 'Browse agents'
+ : row.isSwarm
+ ? 'Switch swarm'
+ : row.hasView
+ ? 'Focus pane'
+ : 'Open here';
+
+ @override
+ void dispose() {
+ app.removeListener(_refresh);
+ projects?.removeListener(_refresh);
+ super.dispose();
+ }
+}
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index 7f9489937..0005cfe22 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -3,125 +3,229 @@ import 'package:flutter/services.dart';
import '../shared/widgets/app_dialog.dart';
import '../state/app_state.dart';
-import '../state/swarm_catalog.dart';
import '../state/swarm_navigation.dart';
+import '../state/swarm_search.dart';
import 'engine_identity.dart';
import 'swarm_welcome.dart';
-Future<SwarmSearchSelection?> showSwarmSwitcher(
+Future<SwarmSearchSelection?> showSwarmHistory(
BuildContext context,
AppNotifier app,
- SwarmNavigationHistory history, {
- bool historyOnly = false,
- SwarmProjectStore? projects,
-}) => showAppDialog<SwarmSearchSelection>(
- context: context,
- transitionDuration: Duration.zero,
- veilBlur: 0,
- veilTint: const Color(0x66000000),
- builder: (_) => _SwarmSwitcher(
- app: app,
- recent: history.recent,
- history: historyOnly ? history : null,
- projects: projects,
- ),
-);
+ SwarmNavigationHistory history,
+) async {
+ final search = SwarmSearchController(app, history.recent, history: history);
+ try {
+ return await showAppDialog<SwarmSearchSelection>(
+ context: context,
+ transitionDuration: Duration.zero,
+ veilBlur: 0,
+ veilTint: const Color(0x66000000),
+ builder: (_) => _SwarmHistory(search: search),
+ );
+ } finally {
+ search.dispose();
+ }
+}
-class _SwarmSwitcher extends StatefulWidget {
- const _SwarmSwitcher({
- required this.app,
- required this.recent,
- this.history,
- this.projects,
- });
- final AppNotifier app;
- final List<String> recent;
- final SwarmNavigationHistory? history;
- final SwarmProjectStore? projects;
+class _SwarmHistory extends StatefulWidget {
+ const _SwarmHistory({required this.search});
+ final SwarmSearchController search;
@override
- State<_SwarmSwitcher> createState() => _SwarmSwitcherState();
+ State<_SwarmHistory> createState() => _SwarmHistoryState();
}
-class _SwarmSwitcherState extends State<_SwarmSwitcher> {
- final _scroll = ScrollController();
+class _SwarmHistoryState extends State<_SwarmHistory> {
final _query = TextEditingController();
- final _searchFocus = FocusNode(debugLabel: 'Unified search query');
- final _searchCatalog = SwarmSearchCatalog();
- List<SwarmDestination> _catalog = const [];
- List<SwarmDestination> _rows = [];
- String? _scopeId, _selectedId;
- String _rootQuery = '';
- int _cursor = 0;
- double _rowHeight = 56;
- bool _revealScheduled = false;
- late final String _targetId, _targetName;
- SwarmDestination? get _selected => _rows.isEmpty ? null : _rows[_cursor];
- SwarmDestination? get _scope =>
- _catalog.where((row) => row.id == _scopeId).firstOrNull;
- bool get _composing =>
- _query.value.composing.isValid && !_query.value.composing.isCollapsed;
-
+ final _focus = FocusNode(debugLabel: 'History search');
+ void _choose(SwarmSearchSelection choice) => Navigator.pop(context, choice);
@override
- void initState() {
- super.initState();
- _targetId = widget.app.activeSwarmId;
- _targetName = widget.app.activeSwarm.name;
- _refreshCatalog();
- widget.app.addListener(_onAppChanged);
- widget.projects?.addListener(_onAppChanged);
+ void dispose() {
+ _query.dispose();
+ _focus.dispose();
+ super.dispose();
}
- void _onAppChanged() {
- final previous = _catalog;
- _refreshCatalog();
- if (!identical(previous, _catalog)) setState(() {});
- }
+ @override
+ Widget build(BuildContext context) => Dialog(
+ alignment: const Alignment(0, -0.5),
+ insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 48),
+ child: SizedBox(
+ width: 680,
+ height: 480,
+ child: Padding(
+ padding: const EdgeInsets.all(16),
+ child: Column(
+ children: [
+ const Row(
+ children: [
+ Text(
+ 'History',
+ style: TextStyle(fontSize: 20, fontWeight: FontWeight.w500),
+ ),
+ Spacer(),
+ Text(
+ 'This session',
+ style: TextStyle(fontSize: 11, color: Colors.white54),
+ ),
+ ],
+ ),
+ const SizedBox(height: 16),
+ SwarmSearchKeys(
+ search: widget.search,
+ editing: _query,
+ onChoose: _choose,
+ onClose: () => Navigator.pop(context),
+ child: SwarmSearchField(
+ controller: _query,
+ focusNode: _focus,
+ autofocus: true,
+ hintText: 'Search history…',
+ onChanged: widget.search.setQuery,
+ ),
+ ),
+ const SizedBox(height: 8),
+ Expanded(
+ child: SwarmSearchResults(
+ search: widget.search,
+ onChoose: _choose,
+ onRefocus: _focus.requestFocus,
+ ),
+ ),
+ ],
+ ),
+ ),
+ ),
+ );
+}
- void _refreshCatalog() {
- final next = widget.history == null
- ? _searchCatalog.read(
- widget.app,
- widget.projects?.projects ?? const [],
- recent: widget.recent,
- )
- : [
- ...widget.history!.menuDestinations(widget.app),
- ...closedSwarmDestinations(widget.app),
- ];
- if (identical(next, _catalog)) return;
- _catalog = next;
- _filter();
- }
+/// The Flutter field and History use the same keys. The native field sends
+/// these commands to the same controller after AppKit has handled composition.
+class SwarmSearchKeys extends StatelessWidget {
+ const SwarmSearchKeys({
+ super.key,
+ required this.search,
+ required this.editing,
+ required this.onChoose,
+ required this.onClose,
+ required this.child,
+ });
+ final SwarmSearchController? search;
+ final TextEditingController editing;
+ final ValueChanged<SwarmSearchSelection> onChoose;
+ final VoidCallback onClose;
+ final Widget child;
- void _filter() {
- final scope = _scope;
- final source = _scopeId == null
- ? _catalog
- : [
- for (final row in _catalog)
- if (scope?.members.contains(row.id) == true) row,
- ];
- _rows = rankSwarmDestinations(source, _query.text, recent: widget.recent);
- final index = _rows.indexWhere((row) => row.id == _selectedId);
- _cursor = _rows.isEmpty
- ? 0
- : index >= 0
- ? index
- : _cursor.clamp(0, _rows.length - 1);
- _selectedId = _selected?.id;
- _revealSelection();
- }
+ @override
+ Widget build(BuildContext context) {
+ final search = this.search;
+ bool composing() =>
+ editing.value.composing.isValid && !editing.value.composing.isCollapsed;
+ void run(VoidCallback action) {
+ if (!composing()) action();
+ }
- void _move(int delta) {
- if (_rows.isEmpty || _composing) return;
- setState(() {
- _cursor = (_cursor + delta) % _rows.length;
- _selectedId = _rows[_cursor].id;
+ void choose(bool add) => run(() {
+ final choice = add ? search?.addHere() : search?.submit();
+ if (choice != null) onChoose(choice);
});
- _scrollToSelection();
+ return CallbackShortcuts(
+ bindings: search == null
+ ? {}
+ : {
+ const SingleActivator(
+ LogicalKeyboardKey.enter,
+ includeRepeats: false,
+ ): () =>
+ choose(false),
+ const SingleActivator(
+ LogicalKeyboardKey.numpadEnter,
+ includeRepeats: false,
+ ): () =>
+ choose(false),
+ const SingleActivator(
+ LogicalKeyboardKey.enter,
+ meta: true,
+ includeRepeats: false,
+ ): () =>
+ choose(true),
+ const SingleActivator(
+ LogicalKeyboardKey.numpadEnter,
+ meta: true,
+ includeRepeats: false,
+ ): () =>
+ choose(true),
+ const SingleActivator(LogicalKeyboardKey.arrowDown): () =>
+ run(() => search.move(1)),
+ const SingleActivator(LogicalKeyboardKey.arrowUp): () =>
+ run(() => search.move(-1)),
+ const SingleActivator(
+ LogicalKeyboardKey.keyN,
+ control: true,
+ ): () =>
+ run(() => search.move(1)),
+ const SingleActivator(
+ LogicalKeyboardKey.keyP,
+ control: true,
+ ): () =>
+ run(() => search.move(-1)),
+ const SingleActivator(
+ LogicalKeyboardKey.keyJ,
+ control: true,
+ ): () =>
+ run(() => search.move(1)),
+ const SingleActivator(
+ LogicalKeyboardKey.keyK,
+ control: true,
+ ): () =>
+ run(() => search.move(-1)),
+ const SingleActivator(LogicalKeyboardKey.escape): () =>
+ run(onClose),
+ const SingleActivator(
+ LogicalKeyboardKey.keyG,
+ control: true,
+ ): () =>
+ run(onClose),
+ if (search.scoped)
+ const SingleActivator(
+ LogicalKeyboardKey.arrowLeft,
+ alt: true,
+ ): () =>
+ run(search.back),
+ },
+ child: child,
+ );
+ }
+}
+
+/// Results only: global search keeps its one editable input in the title bar.
+class SwarmSearchResults extends StatefulWidget {
+ const SwarmSearchResults({
+ super.key,
+ required this.search,
+ required this.onChoose,
+ required this.onRefocus,
+ });
+ final SwarmSearchController search;
+ final ValueChanged<SwarmSearchSelection> onChoose;
+ final VoidCallback onRefocus;
+ @override
+ State<SwarmSearchResults> createState() => _SwarmSearchResultsState();
+}
+
+class _SwarmSearchResultsState extends State<SwarmSearchResults> {
+ final _scroll = ScrollController();
+ double _rowHeight = 56;
+ bool _revealScheduled = false;
+ SwarmSearchController get search => widget.search;
+ @override
+ void initState() {
+ super.initState();
+ search.addListener(_changed);
}
- void _revealSelection() {
+ void _changed() {
+ setState(() {});
+ _scrollToSelection();
if (_revealScheduled) return;
_revealScheduled = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
@@ -131,8 +235,8 @@ class _SwarmSwitcherState extends State<_SwarmSwitcher> {
}
void _scrollToSelection() {
- if (!_scroll.hasClients || _rows.isEmpty) return;
- final top = _cursor * _rowHeight;
+ if (!_scroll.hasClients || search.rows.isEmpty) return;
+ final top = search.cursor * _rowHeight;
final bottom = top + _rowHeight;
final position = _scroll.position;
final offset = top < position.pixels
@@ -145,76 +249,18 @@ class _SwarmSwitcherState extends State<_SwarmSwitcher> {
}
void _submit([SwarmDestination? row]) {
- if (_composing) return;
- final selected = row ?? _selected;
- if (selected == null) return;
- if (selected.isGroup) {
- setState(() {
- _rootQuery = _query.text;
- _scopeId = selected.id;
- _query.clear();
- _cursor = 0;
- _selectedId = null;
- _filter();
- });
- _searchFocus.requestFocus();
+ final choice = search.submit(row);
+ if (choice != null) {
+ widget.onChoose(choice);
} else {
- Navigator.pop(context, SwarmSearchSelection(selected));
+ widget.onRefocus();
}
}
- bool _canAdd(SwarmDestination? row) =>
- widget.history == null &&
- row?.agentId != null &&
- row!.hasView &&
- widget.app.swarms.any(
- (swarm) =>
- swarm.id == _targetId &&
- swarm.panes.length < AppNotifier.maxPanes &&
- !swarm.panes.any(
- (pane) =>
- pane.machineId == row.machineId &&
- pane.agentId == row.agentId,
- ),
- );
-
- void _addHere() {
- if (!_composing && _canAdd(_selected)) {
- Navigator.pop(
- context,
- SwarmSearchSelection(_selected!, SwarmSearchAction.addHere),
- );
- }
- }
-
- void _back() {
- setState(() {
- _selectedId = _scopeId;
- _scopeId = null;
- _query.text = _rootQuery;
- _query.selection = TextSelection.collapsed(offset: _query.text.length);
- _filter();
- });
- _searchFocus.requestFocus();
- }
-
- String _action(SwarmDestination row) => row.closedId != null
- ? 'Reopen'
- : row.isGroup
- ? 'Browse agents'
- : row.isSwarm
- ? 'Switch swarm'
- : row.hasView
- ? 'Focus pane'
- : 'Open here';
-
@override
void dispose() {
- widget.app.removeListener(_onAppChanged);
- widget.projects?.removeListener(_onAppChanged);
+ search.removeListener(_changed);
_scroll.dispose();
- _query.dispose();
- _searchFocus.dispose();
super.dispose();
}
@@ -225,227 +271,152 @@ class _SwarmSwitcherState extends State<_SwarmSwitcher> {
56,
double.infinity,
);
- final selected = _selected;
- final scope = _scope;
- return CallbackShortcuts(
- bindings: {
- const SingleActivator(LogicalKeyboardKey.enter, meta: true): _addHere,
- const SingleActivator(LogicalKeyboardKey.numpadEnter, meta: true):
- _addHere,
- const SingleActivator(LogicalKeyboardKey.keyG, control: true): () {
- if (!_composing) Navigator.pop(context);
- },
- if (_scopeId != null)
- const SingleActivator(LogicalKeyboardKey.arrowLeft, alt: true): _back,
- },
- child: Dialog(
- alignment: const Alignment(0, -0.5),
- insetPadding: const EdgeInsets.symmetric(horizontal: 24, vertical: 48),
- child: SizedBox(
- width: 680,
- height: 480,
- child: Padding(
- padding: const EdgeInsets.all(16),
- child: Column(
+ final scope = search.scope;
+ final selected = search.selected;
+ return Semantics(
+ container: true,
+ label: 'Search results',
+ child: Column(
+ children: [
+ if (search.scoped)
+ Row(
children: [
- if (widget.history != null) ...[
- const Row(
- children: [
- Text(
- 'History',
- style: TextStyle(
- fontSize: 20,
- fontWeight: FontWeight.w500,
+ IconButton(
+ tooltip: 'All results',
+ onPressed: () {
+ search.back();
+ widget.onRefocus();
+ },
+ icon: const Icon(Icons.arrow_back, size: 16),
+ ),
+ Expanded(
+ child: Text(
+ scope?.title ?? 'Group no longer available',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 12),
+ ),
+ ),
+ TextButton(
+ onPressed: !search.canOpenGroup
+ ? null
+ : () => widget.onChoose(
+ SwarmSearchSelection(
+ scope!,
+ SwarmSearchAction.openGroup,
+ ),
),
- ),
- Spacer(),
- Text(
- 'This session',
- style: TextStyle(fontSize: 11, color: Colors.white54),
- ),
- ],
+ child: Text(
+ 'Open ${scope?.members.length ?? 0} agents as swarm',
+ style: const TextStyle(fontSize: 11),
),
- const SizedBox(height: 16),
- ],
- Row(
- children: [
- Expanded(
- child: SwarmSearchField(
- controller: _query,
- focusNode: _searchFocus,
- autofocus: true,
- hintText: widget.history != null
- ? 'Search history…'
- : _scopeId != null
- ? 'Search agents in ${scope?.title ?? 'this group'}…'
- : 'Search agents, swarms, machines, projects…',
- onChanged: (_) => setState(() {
- _cursor = 0;
- _selectedId = null;
- _filter();
- }),
- onMove: _move,
- onSubmitted: _submit,
+ ),
+ ],
+ ),
+ Expanded(
+ child: search.rows.isEmpty
+ ? Center(
+ child: Text(
+ search.scoped && search.query.isEmpty
+ ? 'No available agent views in this group'
+ : 'No matching results',
+ style: const TextStyle(
+ fontSize: 13,
+ color: Colors.white60,
),
),
- const SizedBox(width: 4),
- IconButton(
- tooltip: 'Close search',
- onPressed: () => Navigator.pop(context),
- icon: const Icon(Icons.close, size: 18),
- ),
- ],
- ),
- if (_scopeId != null)
- Padding(
- padding: const EdgeInsets.only(top: 8),
- child: Row(
- children: [
- IconButton(
- tooltip: 'All results',
- onPressed: _back,
- icon: const Icon(Icons.arrow_back, size: 16),
+ )
+ : ListView.builder(
+ controller: _scroll,
+ itemCount: search.rows.length,
+ itemExtent: _rowHeight,
+ itemBuilder: (context, index) {
+ final row = search.rows[index];
+ return ListTile(
+ key: ValueKey(row.id),
+ selected: index == search.cursor,
+ selectedColor: Colors.white,
+ selectedTileColor: Colors.white10,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(8),
),
- Expanded(
- child: Text(
- scope?.title ?? 'Group no longer available',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(fontSize: 12),
- ),
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 12,
+ ),
+ leading: row.agentId != null
+ ? EngineMark(engine: row.engine, size: 20)
+ : Icon(
+ row.isMachine
+ ? Icons.computer_outlined
+ : row.isProject
+ ? Icons.folder_outlined
+ : Icons.tab,
+ size: 19,
+ color: Colors.white60,
+ ),
+ title: Text(
+ row.title,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 13),
),
- TextButton(
- onPressed:
- scope == null ||
- scope.members.isEmpty ||
- scope.members.length > AppNotifier.maxPanes ||
- widget.app.swarms.length >=
- AppNotifier.maxSwarms
- ? null
- : () => Navigator.pop(
- context,
- SwarmSearchSelection(
- scope,
- SwarmSearchAction.openGroup,
- ),
- ),
- child: Text(
- 'Open ${scope?.members.length ?? 0} agents as swarm',
- style: const TextStyle(fontSize: 11),
+ subtitle: Text(
+ row.detail,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(
+ fontSize: 11,
+ color: Colors.white54,
),
),
- ],
- ),
- ),
- const SizedBox(height: 12),
- Expanded(
- child: _rows.isEmpty
- ? Center(
- child: Text(
- _scopeId != null && _query.text.isEmpty
- ? 'No available agent views in this group'
- : 'No matching results',
- style: const TextStyle(
- fontSize: 13,
- color: Colors.white60,
- ),
+ trailing: Text(
+ row.current
+ ? 'Current'
+ : SwarmSearchController.action(row),
+ style: const TextStyle(
+ fontSize: 11,
+ color: Colors.white54,
),
- )
- : ListView.builder(
- controller: _scroll,
- itemCount: _rows.length,
- itemExtent: _rowHeight,
- itemBuilder: (context, index) {
- final row = _rows[index];
- return ListTile(
- key: ValueKey(row.id),
- selected: index == _cursor,
- selectedColor: Colors.white,
- selectedTileColor: Colors.white10,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(8),
- ),
- contentPadding: const EdgeInsets.symmetric(
- horizontal: 12,
- ),
- leading: row.agentId != null
- ? EngineMark(engine: row.engine, size: 20)
- : Icon(
- row.isMachine
- ? Icons.computer_outlined
- : row.isProject
- ? Icons.folder_outlined
- : Icons.tab,
- size: 19,
- color: Colors.white60,
- ),
- title: Text(
- row.title,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(fontSize: 13),
- ),
- subtitle: Text(
- row.detail,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(
- fontSize: 11,
- color: Colors.white54,
- ),
- ),
- trailing: Text(
- row.current ? 'Current' : _action(row),
- style: const TextStyle(
- fontSize: 11,
- color: Colors.white54,
- ),
- ),
- onTap: () => _submit(row),
- );
- },
),
+ onTap: () => _submit(row),
+ );
+ },
+ ),
+ ),
+ const SizedBox(height: 4),
+ Row(
+ children: [
+ Expanded(
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 10),
+ child: Text(
+ selected?.agentId != null && !selected!.hasView
+ ? 'Open view in ${search.targetName}'
+ : '↑↓ choose · Esc close',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(fontSize: 11, color: Colors.white54),
+ ),
),
- const SizedBox(height: 12),
- Row(
- children: [
- Expanded(
- child: Text(
- selected != null &&
- selected.agentId != null &&
- !selected.hasView
- ? 'Open view in $_targetName'
- : '↑↓ choose · Esc close',
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(
- fontSize: 11,
- color: Colors.white54,
- ),
- ),
- ),
- if (_canAdd(selected))
- TextButton(
- onPressed: _addHere,
- child: const Text(
- 'Add to this swarm ⌘↵',
- style: TextStyle(fontSize: 11),
- ),
- ),
- const SizedBox(width: 8),
- FilledButton(
- onPressed: selected == null ? null : _submit,
- child: Text(
- '${selected == null ? 'Open' : _action(selected)} ↵',
- style: const TextStyle(fontSize: 12),
- ),
- ),
- ],
+ ),
+ if (search.canAdd(selected))
+ TextButton(
+ onPressed: () => widget.onChoose(search.addHere()!),
+ child: const Text(
+ 'Add to this swarm ⌘↵',
+ style: TextStyle(fontSize: 11),
+ ),
),
- ],
- ),
+ TextButton(
+ onPressed: selected == null ? null : _submit,
+ child: Text(
+ '${selected == null ? 'Open' : SwarmSearchController.action(selected)} ↵',
+ style: const TextStyle(fontSize: 11),
+ ),
+ ),
+ ],
),
- ),
+ ],
),
);
}
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index 8c6a625a4..efa8c0102 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -44,6 +44,15 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {
self.updateHistory(state["history"] as? [[String: Any]] ?? [], closed: state["closedHistory"] as? [[String: Any]] ?? [])
self.strip.update(state)
result(nil)
+ case "focusSearch":
+ self.strip.focusSearch(selectAll: (call.arguments as? [String: Any])?["selectAll"] as? Bool == true)
+ result(nil)
+ case "searchState":
+ self.strip.setSearchState(call.arguments as? [String: Any] ?? [:])
+ result(nil)
+ case "closeSearch":
+ self.strip.closeSearch()
+ result(nil)
default: result(FlutterMethodNotImplemented)
}
}
@@ -53,6 +62,9 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation {
[weak self] _ in self?.resize()
})
}
+ observers.append(NotificationCenter.default.addObserver(forName: NSWindow.didResignKeyNotification, object: window, queue: .main) {
+ [weak self] _ in self?.strip.dismissSearch()
+ })
}
deinit { observers.forEach(NotificationCenter.default.removeObserver) }
@@ -270,60 +282,90 @@ private let swarmSelectedTabColor = NSColor(srgbRed: 70.0 / 255, green: 55.0 / 2
/// A compact launcher for the shared picker; no second editable field or search
/// state lives in AppKit. Native keyboard focus and button activation still work.
-private final class SwarmSearchButton: NSButton {
- private var hovered = false
- private var tracking: NSTrackingArea?
- private let symbol = NSImage(systemSymbolName: "magnifyingglass", accessibilityDescription: nil)
-
+/// AppKit owns editing, selection, paste and IME. Only result-navigation keys
+/// leave the field editor; ordinary terminal input never passes through here.
+private final class SwarmSearchField: NSSearchField {
+ var begin: (() -> Void)?
+ var command: ((String) -> Void)?
+ var scoped = false
+ var searching = false { didSet { needsDisplay = true } }
override init(frame: NSRect) {
super.init(frame: frame)
- title = ""
- isBordered = false
- setButtonType(.momentaryChange)
+ font = NSFont.systemFont(ofSize: 12)
+ controlSize = .small
+ appearance = NSAppearance(named: .darkAqua)
+ placeholderString = "Search…"
+ sendsSearchStringImmediately = true
+ sendsWholeSearchString = false
+ maximumRecents = 0
+ searchMenuTemplate = nil
+ focusRingType = .exterior
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
override var mouseDownCanMoveWindow: Bool { false }
- override func updateTrackingAreas() {
- if let tracking { removeTrackingArea(tracking) }
- tracking = NSTrackingArea(rect: bounds, options: [.mouseEnteredAndExited, .activeInKeyWindow, .inVisibleRect], owner: self)
- addTrackingArea(tracking!)
- super.updateTrackingAreas()
+ override func becomeFirstResponder() -> Bool {
+ begin?()
+ return super.becomeFirstResponder()
+ }
+ override func mouseDown(with event: NSEvent) {
+ begin?()
+ super.mouseDown(with: event)
+ }
+ override func performKeyEquivalent(with event: NSEvent) -> Bool {
+ if let editor = currentEditor() as? NSTextView,
+ event.modifierFlags.intersection([.command, .option, .control, .shift]) == .command {
+ if event.charactersIgnoringModifiers == "p" && !editor.hasMarkedText() {
+ editor.selectAll(nil)
+ return true
+ }
+ if let action = Self.resultCommand("insertNewline:", event: event, composing: editor.hasMarkedText()),
+ event.charactersIgnoringModifiers == "\r" || event.charactersIgnoringModifiers == "\u{3}" {
+ if !event.isARepeat { command?(action) }
+ return true
+ }
+ }
+ return super.performKeyEquivalent(with: event)
+ }
+ static func resultCommand(_ selector: String, event: NSEvent?, composing: Bool, scoped: Bool = false) -> String? {
+ guard !composing else { return nil }
+ let modifiers = event?.modifierFlags.intersection([.command, .option, .control, .shift]) ?? []
+ if modifiers == .control {
+ switch event?.charactersIgnoringModifiers?.lowercased() {
+ case "n", "j": return "next"
+ case "p", "k": return "previous"
+ case "g": return "close"
+ default: break
+ }
+ }
+ if scoped && modifiers == .option && selector == "moveWordLeft:" { return "back" }
+ switch selector {
+ case "moveDown:": return "next"
+ case "moveUp:": return "previous"
+ case "insertNewline:", "insertNewlineIgnoringFieldEditor:": return modifiers == .command ? "add" : "submit"
+ case "cancelOperation:", "complete:": return "close"
+ default: return nil
+ }
}
- override func mouseEntered(with event: NSEvent) { hovered = true; needsDisplay = true }
- override func mouseExited(with event: NSEvent) { hovered = false; needsDisplay = true }
override func draw(_ dirtyRect: NSRect) {
- let shape = NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), xRadius: 8, yRadius: 8)
- NSColor.white.withAlphaComponent(isHighlighted ? 0.16 : hovered ? 0.11 : 0.06).setFill()
- shape.fill()
- NSColor.white.withAlphaComponent(hovered ? 0.16 : 0.08).setStroke()
- shape.stroke()
- let tint = NSColor(srgbRed: 0.84, green: 0.80, blue: 0.87, alpha: isEnabled ? 1 : 0.4)
- let iconX: CGFloat = bounds.width < 100 ? (bounds.width - 14) / 2 : 10
- symbol?.withSymbolConfiguration(NSImage.SymbolConfiguration(paletteColors: [tint]))?
- .draw(in: NSRect(x: iconX, y: (bounds.height - 14) / 2, width: 14, height: 14))
- if bounds.width >= 100 {
- let attrs: [NSAttributedString.Key: Any] = [.font: NSFont.systemFont(ofSize: 12), .foregroundColor: tint]
- let label = "Search…" as NSString
- label.draw(at: NSPoint(x: 32, y: (bounds.height - label.size(withAttributes: attrs).height) / 2), withAttributes: attrs)
+ super.draw(dirtyRect)
+ if !searching && stringValue.isEmpty && bounds.width >= 140 {
let shortcut = "⌘P" as NSString
- let shortcutAttrs: [NSAttributedString.Key: Any] = [.font: NSFont.systemFont(ofSize: 11), .foregroundColor: tint.withAlphaComponent(isEnabled ? 0.65 : 0.3)]
- let size = shortcut.size(withAttributes: shortcutAttrs)
- shortcut.draw(at: NSPoint(x: bounds.width - size.width - 10, y: (bounds.height - size.height) / 2), withAttributes: shortcutAttrs)
- }
- if window?.firstResponder === self {
- NSColor.keyboardFocusIndicatorColor.setStroke()
- shape.lineWidth = 2
- shape.stroke()
+ let attrs: [NSAttributedString.Key: Any] = [.font: NSFont.systemFont(ofSize: 11),
+ .foregroundColor: NSColor.secondaryLabelColor]
+ let size = shortcut.size(withAttributes: attrs)
+ shortcut.draw(at: NSPoint(x: bounds.width - size.width - 10,
+ y: (bounds.height - size.height) / 2), withAttributes: attrs)
}
}
}
-private final class SwarmTabStrip: NSView {
+private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
var emit: ((String, Any?) -> Void)?
private let scroll = NSScrollView()
private let document = NSView()
private let newButton = NSButton()
- private let searchButton = SwarmSearchButton()
+ private let searchField = SwarmSearchField()
+ private var lastSearchWidth: CGFloat = 0
private var tabs: [SwarmTabButton] = []
private var activeId = ""
private var actionsEnabled = false
@@ -349,11 +391,12 @@ private final class SwarmTabStrip: NSView {
addSubview(button)
}
button(newButton, "plus", "New swarm (⌘T)", #selector(newSwarm))
- searchButton.target = self
- searchButton.action = #selector(showSearch)
- searchButton.toolTip = "Search agents, swarms, machines and projects (⌘P)"
- searchButton.setAccessibilityLabel("Search agents, swarms, machines and projects")
- addSubview(searchButton)
+ searchField.delegate = self
+ searchField.begin = { [weak self] in self?.beginSearch() }
+ searchField.command = { [weak self] action in self?.emit?("searchCommand", ["command": action]) }
+ searchField.toolTip = "Search agents, swarms, machines and projects (⌘P)"
+ searchField.setAccessibilityLabel("Search agents, swarms, machines and projects")
+ addSubview(searchField)
registerForDraggedTypes([swarmPasteboardType])
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
@@ -383,7 +426,8 @@ private final class SwarmTabStrip: NSView {
// Moving frames alone leaves AppKit's child traversal in insertion order.
document.setAccessibilityChildren(tabs)
newButton.isEnabled = actionsEnabled && tabs.count < 24
- searchButton.isEnabled = actionsEnabled
+ searchField.isEnabled = actionsEnabled
+ if !actionsEnabled { closeSearch() }
needsLayout = true
layoutSubtreeIfNeeded()
if ids != previousOrder {
@@ -401,8 +445,10 @@ private final class SwarmTabStrip: NSView {
override func layout() {
super.layout()
- let searchWidth: CGFloat = bounds.width < 480 ? 28 : bounds.width < 720 ? 156 : 200
- let available = max(120, bounds.width - searchWidth - 56)
+ let searchWidth: CGFloat = searchField.searching
+ ? min(600, max(128, bounds.width - 184))
+ : bounds.width < 480 ? 128 : bounds.width < 720 ? 156 : 200
+ let available = max(132, bounds.width - searchWidth - 56)
let width = min(220, max(132, available / CGFloat(max(1, tabs.count))))
let occupied = min(available, CGFloat(tabs.count) * width)
scroll.frame = NSRect(x: 0, y: 0, width: occupied, height: bounds.height)
@@ -413,7 +459,11 @@ private final class SwarmTabStrip: NSView {
}
let buttonY = (bounds.height - 28) / 2
newButton.frame = NSRect(x: occupied + 4, y: buttonY, width: 28, height: 28)
- searchButton.frame = NSRect(x: bounds.width - searchWidth - 8, y: buttonY, width: searchWidth, height: 28)
+ searchField.frame = NSRect(x: bounds.width - searchWidth - 8, y: buttonY, width: searchWidth, height: 28)
+ if searchField.searching && searchWidth != lastSearchWidth {
+ lastSearchWidth = searchWidth
+ emit?("searchGeometry", ["width": searchWidth])
+ }
if let active = tabs.first(where: { $0.swarmId == activeId }) {
document.scrollToVisible(active.frame)
}
@@ -429,7 +479,60 @@ private final class SwarmTabStrip: NSView {
else { window?.performDrag(with: event) }
}
@objc private func newSwarm() { emit?("new", nil) }
- @objc private func showSearch() { emit?("jump", nil) }
+ private func beginSearch() {
+ guard actionsEnabled, !searchField.searching else { return }
+ searchField.searching = true
+ needsLayout = true
+ layoutSubtreeIfNeeded()
+ emit?("searchBegin", ["width": searchField.frame.width])
+ }
+ func focusSearch(selectAll: Bool = false) {
+ guard actionsEnabled else { return }
+ beginSearch()
+ if searchField.currentEditor() == nil { window?.makeFirstResponder(searchField) }
+ if selectAll, let editor = searchField.currentEditor() as? NSTextView, !editor.hasMarkedText() { editor.selectAll(nil) }
+ }
+ func setSearchState(_ state: [String: Any]) {
+ if let query = state["query"] as? String, query != searchField.stringValue {
+ searchField.stringValue = query
+ if let editor = searchField.currentEditor() as? NSTextView {
+ editor.string = query
+ editor.setSelectedRange(NSRange(location: (query as NSString).length, length: 0))
+ }
+ }
+ searchField.placeholderString = state["hint"] as? String ?? "Search…"
+ searchField.scoped = state["scoped"] as? Bool == true
+ }
+ func closeSearch() {
+ guard searchField.searching else { return }
+ searchField.searching = false
+ if searchField.currentEditor() != nil {
+ // Flutter's wrapper NSView does not accept first responder. Its public
+ // view controller does, and routes the next event to Flutter's keyboard.
+ let responder = window?.contentViewController as NSResponder? ?? window?.contentView
+ window?.makeFirstResponder(responder)
+ }
+ searchField.stringValue = ""
+ searchField.placeholderString = "Search…"
+ lastSearchWidth = 0
+ needsLayout = true
+ }
+ func dismissSearch() {
+ if searchField.searching { emit?("searchCommand", ["command": "dismiss"]) }
+ }
+ func controlTextDidChange(_ notification: Notification) {
+ guard searchField.searching else { return }
+ emit?("searchChanged", ["query": searchField.stringValue])
+ }
+ func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool {
+ let event = NSApp.currentEvent
+ guard let action = SwarmSearchField.resultCommand(NSStringFromSelector(selector), event: event,
+ composing: textView.hasMarkedText(), scoped: searchField.scoped) else { return false }
+ if event?.isARepeat != true || !["submit", "add", "close"].contains(action) {
+ emit?("searchCommand", ["command": action])
+ }
+ return true
+ }
override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { actionsEnabled ? .move : [] }
override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { actionsEnabled ? .move : [] }
override func performDragOperation(_ sender: NSDraggingInfo) -> Bool {
diff --git a/desktop/test/swarm_history_test.dart b/desktop/test/swarm_history_test.dart
index 55f3064eb..86e335680 100644
--- a/desktop/test/swarm_history_test.dart
+++ b/desktop/test/swarm_history_test.dart
@@ -112,8 +112,12 @@ void main() {
const channel = MethodChannel('harness/swarm_tabs');
final messenger = tester.binding.defaultBinaryMessenger;
final updates = <Map>[];
+ final fieldUpdates = <Map>[];
messenger.setMockMethodCallHandler(channel, (call) async {
if (call.method == 'update') updates.add(call.arguments as Map);
+ if (call.method == 'searchState') {
+ fieldUpdates.add(call.arguments as Map);
+ }
return true;
});
addTearDown(() => messenger.setMockMethodCallHandler(channel, null));
@@ -194,13 +198,30 @@ void main() {
await tester.pump();
await settings;
- // Native Command-P reaches the same picker even when the terminal owns focus.
+ // Native Command-P focuses the native input; Flutter only paints its results.
final jumping = native('jump');
await tester.pump();
- expect(jumpField, findsOneWidget);
- await tester.enterText(jumpField, 'Agent 1');
+ expect(
+ find.byKey(const ValueKey('swarm-search-results')),
+ findsOneWidget,
+ );
+ expect(find.byType(TextField), findsNothing);
+ await native('searchChanged', {'query': 'A'});
+ await native('searchChanged', {'query': 'Agent 1'});
+ expect(
+ fieldUpdates.every((state) => !state.containsKey('query')),
+ isTrue,
+ reason: 'Native edits must never be echoed back over newer typing',
+ );
+ await native('searchGeometry', {'width': 480});
await tester.pump();
- await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ expect(
+ tester
+ .getSize(find.byKey(const ValueKey('swarm-search-results')))
+ .width,
+ 480,
+ );
+ await native('searchCommand', {'command': 'submit'});
await tester.pump();
await jumping;
expect(app.focusedPaneId, second.id);
diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dart
index 2a8afe2ab..d8bd57fbd 100644
--- a/desktop/test/swarm_screen_test.dart
+++ b/desktop/test/swarm_screen_test.dart
@@ -75,7 +75,7 @@ void main() {
expect(find.text('Agent 0'), findsOneWidget);
expect(find.text('Agent 1'), findsOneWidget);
expect(find.text('Agent 2'), findsNothing);
- await tester.tap(find.byTooltip('Close search'));
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
await tester.tap(find.text('Existing project'));
await tester.pump(const Duration(milliseconds: 100));
@@ -106,13 +106,17 @@ void main() {
await tester.pump();
final zoom = app.zoomedPaneId;
final before = tester.getSize(find.byType(PaneGrid));
- await tester.tap(find.text('Search…'));
+ await tester.tap(find.byKey(const ValueKey('swarm-search-input')));
await tester.pump(const Duration(milliseconds: 300));
- expect(find.byType(Dialog), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('swarm-search-results')),
+ findsOneWidget,
+ );
+ expect(find.byType(Dialog), findsNothing);
expect(app.panes.length, 2);
expect(app.zoomedPaneId, zoom);
expect(tester.getSize(find.byType(PaneGrid)), before);
- await tester.tap(find.byTooltip('Close search'));
+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump(const Duration(milliseconds: 300));
expect(app.zoomedPaneId, zoom);
expect(app.panes.length, 2);
diff --git a/desktop/test/swarm_search_test.dart b/desktop/test/swarm_search_test.dart
index a26384e49..06a586612 100644
--- a/desktop/test/swarm_search_test.dart
+++ b/desktop/test/swarm_search_test.dart
@@ -14,6 +14,43 @@ import 'swarm_state_test.dart' show createApp;
import 'swarm_switcher_test.dart' show jumpField;
void main() {
+ testWidgets(
+ 'clicking the real bar and cancelling restores terminal focus without sending the query',
+ (tester) async {
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final inputs = <TerminalBinaryFrame>[];
+ final session = terminal('a0', inputs);
+ app.adoptSessionForTest(session);
+ await mount(tester, app);
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ final originalController = tester.widget<TextField>(input).controller;
+ await tester.tap(input);
+ await tester.pump();
+ await tester.enterText(input, 'a query only');
+ await tester.pump();
+ expect(
+ tester.widget<TextField>(input).controller,
+ same(originalController),
+ );
+ expect(tester.widget<TextField>(input).focusNode!.hasFocus, isTrue);
+ expect(inputs, isEmpty);
+ await tester.tapAt(const Offset(20, 600));
+ await tester.pump();
+ expect(find.byKey(const ValueKey('swarm-search-results')), findsNothing);
+ expect(originalController!.text, isEmpty);
+ final terminalView = tester.widget<TerminalView>(
+ find.byType(TerminalView),
+ );
+ expect(terminalView.focusNode!.hasFocus, isTrue);
+ await tester.sendKeyEvent(LogicalKeyboardKey.arrowLeft);
+ await tester.pump(const Duration(milliseconds: 10));
+ expect(inputs.single.bytes, [27, 91, 68]);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ },
+ );
+
test('one cached catalog searches all four objects and explicit remote project members', () {
final app = createApp();
addTearDown(app.dispose);
@@ -198,7 +235,7 @@ void main() {
(tester) async {
final app = createApp();
await mount(tester, app);
- await tester.tap(find.text('Search…'));
+ await tester.tap(find.byKey(const ValueKey('swarm-search-input')));
await tester.pump();
await tester.enterText(jumpField, 'Test host');
await tester.pump();
@@ -282,7 +319,11 @@ void main() {
);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
- expect(find.byType(Dialog), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('swarm-search-results')),
+ findsOneWidget,
+ );
+ expect(find.byType(Dialog), findsNothing);
expect(app.panes, isEmpty);
controller.clearComposing();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
diff --git a/desktop/test/swarm_switcher_test.dart b/desktop/test/swarm_switcher_test.dart
index cdd63511d..29963a243 100644
--- a/desktop/test/swarm_switcher_test.dart
+++ b/desktop/test/swarm_switcher_test.dart
@@ -137,6 +137,9 @@ void main() {
app.adoptSessionForTest(terminal('a0', []));
await mount(tester, app);
final membership = [...app.panes];
+ final input = find.byKey(const ValueKey('swarm-search-input'));
+ final controller = tester.widget<TextField>(input).controller;
+ final route = ModalRoute.of(tester.element(input));
await tester.sendKeyDownEvent(LogicalKeyboardKey.meta);
await tester.sendKeyEvent(LogicalKeyboardKey.keyP);
await tester.sendKeyUpEvent(LogicalKeyboardKey.meta);
@@ -144,15 +147,22 @@ void main() {
expect(jumpField, findsOneWidget);
final field = tester.widget<TextField>(jumpField);
expect(field.focusNode!.hasFocus, isTrue);
- expect(
- (ModalRoute.of(
- tester.element(jumpField),
- ) as TransitionRoute).transitionDuration,
- Duration.zero,
+ expect(field.controller, same(controller));
+ expect(ModalRoute.of(tester.element(input)), same(route));
+ final results = tester.getRect(
+ find.byKey(const ValueKey('swarm-search-results')),
);
+ final bar = tester.getRect(input);
+ expect(results.top, inInclusiveRange(bar.bottom, bar.bottom + 12));
+ expect(results.right, closeTo(bar.right, 0.1));
+ expect(find.byType(TextField), findsOneWidget);
expect(find.byType(BackdropFilter), findsNothing);
await chord(tester, LogicalKeyboardKey.keyP);
- expect(find.byType(Dialog), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('swarm-search-results')),
+ findsOneWidget,
+ );
+ expect(find.byType(Dialog), findsNothing);
await tester.enterText(jumpField, 'missing');
await tester.pump();
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
@@ -164,7 +174,7 @@ void main() {
expect(app.panes, membership);
await chord(tester, LogicalKeyboardKey.keyF, shift: true);
expect(find.byType(Dialog), findsNothing);
- await tester.tap(find.text('Search…'));
+ await tester.tap(find.byKey(const ValueKey('swarm-search-input')));
await tester.pump();
expect(jumpField, findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index a78a1eac4..c8baeeb38 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -99,13 +99,40 @@ private extension SwarmTabStrip {
try checkTitlebar(tabs.count == 1 && tabs[0] === original, "Closing tabs retains the surviving control")
try original.checkAccessibility(expectedName: "Renamed tab", active: true)
try checkTitlebar(newButton.isEnabled, "New tab returns below capacity")
- try checkTitlebar(searchButton.accessibilityLabel() == "Search agents, swarms, machines and projects", "Search has a readable accessible label")
- try checkTitlebar(searchButton.toolTip?.contains("⌘P") == true, "Search tooltip advertises its keyboard shortcut")
- try checkTitlebar(subviews.compactMap { $0 as? NSButton }.count == 2, "Titlebar keeps New swarm and Search; Settings belongs to the app menu")
- try checkTitlebar(newButton.frame.maxX + 12 <= searchButton.frame.minX, "New swarm leaves balanced space before Search")
- try checkTitlebar(searchButton.frame.height == 28 && searchButton.frame.maxX == bounds.width - 8, "Search has an aligned 28-point target and eight-point trailing inset")
- searchButton.performClick(nil)
- try checkTitlebar(events == ["jump"], "Search dispatches the shared picker exactly once")
+ try checkTitlebar(searchField.accessibilityLabel() == "Search agents, swarms, machines and projects", "Search has a readable accessible label")
+ try checkTitlebar(searchField.toolTip?.contains("⌘P") == true, "Search tooltip advertises its keyboard shortcut")
+ try checkTitlebar(searchField.isEditable && searchField.maximumRecents == 0, "Search is an editable field without a separate AppKit recents menu")
+ try checkTitlebar(newButton.frame.maxX + 12 <= searchField.frame.minX, "New swarm leaves balanced space before Search")
+ focusSearch()
+ try checkTitlebar(events.filter { $0 == "searchBegin" }.count == 1, "Focusing search opens one attached result list")
+ focusSearch()
+ try checkTitlebar(events.filter { $0 == "searchBegin" }.count == 1, "Refocusing search keeps the same search session")
+ setSearchState(["query": "Workshop", "hint": "Search agents in Workshop…"])
+ try checkTitlebar(searchField.stringValue == "Workshop", "Group navigation updates the original editable input")
+ closeSearch()
+ try checkTitlebar(searchField.stringValue.isEmpty && !searchField.searching, "Closing search clears and collapses its original input")
+ func key(_ characters: String, _ flags: NSEvent.ModifierFlags = []) -> NSEvent {
+ NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags,
+ timestamp: 0, windowNumber: 0, context: nil, characters: characters,
+ charactersIgnoringModifiers: characters, isARepeat: false, keyCode: 0)!
+ }
+ for (selector, event, expected) in [
+ ("moveDown:", key(""), "next"), ("moveUp:", key(""), "previous"),
+ ("insertNewline:", key("j", .control), "next"),
+ ("moveUp:", key("k", .control), "previous"),
+ ("insertNewline:", key("\r"), "submit"),
+ ("insertNewline:", key("\r", .command), "add"),
+ ("cancelOperation:", key("g", .control), "close")
+ ] {
+ try checkTitlebar(SwarmSearchField.resultCommand(selector, event: event, composing: false) == expected,
+ "Native search dispatches result command \(expected)")
+ try checkTitlebar(SwarmSearchField.resultCommand(selector, event: event, composing: true) == nil,
+ "IME keeps \(expected) while marked text is active")
+ }
+ try checkTitlebar(SwarmSearchField.resultCommand("selectAll:", event: key("a", .command), composing: false) == nil,
+ "Native select-all remains text editing")
+ try checkTitlebar(SwarmSearchField.resultCommand("moveLeft:", event: key(""), composing: false) == nil,
+ "Ordinary arrow movement keeps the caret in the query")
events.removeAll()
try original.checkEnabled(true)
original.clickBothActions()
@@ -114,14 +141,30 @@ private extension SwarmTabStrip {
events.removeAll()
update(state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0", enabled: false))
try original.checkEnabled(false)
- try checkTitlebar(!newButton.isEnabled && !searchButton.isEnabled, "Titlebar actions disable with a modal")
+ try checkTitlebar(!newButton.isEnabled && !searchField.isEnabled, "Titlebar actions disable with a modal")
original.clickBothActions()
newButton.performClick(nil)
- searchButton.performClick(nil)
+ focusSearch()
try checkTitlebar(events.isEmpty, "Disabled controls emit no actions")
}
}
+private extension SwarmTabStrip {
+ func checkSearchEditing(_ window: NSWindow) throws {
+ focusSearch()
+ try checkTitlebar(searchField.currentEditor() is NSTextView, "The actual search bar owns a native field editor")
+ setSearchState(["query": "feature/木", "hint": "Search agents…"])
+ try checkTitlebar((searchField.currentEditor() as? NSTextView)?.string == "feature/木",
+ "Unicode query stays in the original native input")
+ focusSearch(selectAll: true)
+ try checkTitlebar((searchField.currentEditor() as? NSTextView)?.selectedRange().length == ("feature/木" as NSString).length,
+ "Command-P selects the current query for replacement")
+ closeSearch()
+ try checkTitlebar(window.firstResponder === window.contentViewController,
+ "Closing native search returns keyboard events to the content controller")
+ }
+}
+
// No engine, account, terminal or transport is involved in native layout.
private final class TitlebarCheckMessenger: NSObject, FlutterBinaryMessenger {
func send(onChannel channel: String, message: Data?) {}
@@ -251,10 +294,15 @@ private extension SwarmTitlebar {
strip.layoutSubtreeIfNeeded()
try strip.checkWindowGeometry(window)
}
+ try strip.checkSearchEditing(window)
try checkTitlebar(!window.isVisible, "Native layout check never displays its window")
}
}
+private final class TitlebarCheckContentController: NSViewController {
+ override var acceptsFirstResponder: Bool { true }
+}
+
let titlebarCheckApp = NSApplication.shared
titlebarCheckApp.setActivationPolicy(.prohibited)
titlebarCheckApp.appearance = NSAppearance(named: .darkAqua)
@@ -266,6 +314,9 @@ do {
let window = NSWindow(contentRect: NSRect(x: 0, y: 0, width: 1280, height: 700),
styleMask: [.titled, .closable, .miniaturizable, .resizable], backing: .buffered, defer: false)
window.isReleasedWhenClosed = false
+ let content = TitlebarCheckContentController()
+ content.view = NSView(frame: NSRect(x: 0, y: 0, width: 1280, height: 700))
+ window.contentViewController = content
let titlebar = SwarmTitlebar(window: window, messenger: TitlebarCheckMessenger())
try titlebar.checkNativeContainer()
window.close()
diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.md
index bada10732..1733e076b 100644
--- a/docs/harness-v2-progress.md
+++ b/docs/harness-v2-progress.md
@@ -1,18 +1,19 @@
# Harness App V2 — development handoff
-Updated 2026-09-13 after unified search, the single-wallpaper decision and the keyboard-system audit. This is a working preview, not a release.
+Updated 2026-09-13 after replacing the search launcher with an editable title-bar input and attached results. This is a working preview, not a release.
-## Current continuation: unified search and keyboard configuration
+## Current continuation: editable title-bar search and keyboard configuration
-- The user approved a compact search control at the top right of the existing tab row. It opens the same immediate Cmd-P picker as New swarm's search control. The catalog includes agents, Swarms, machines and projects, fuzzy matching across names/branches/folders/machines, and saved cross-machine project associations. Normalized results are retained across ordinary output notifications; typing makes no file/network requests.
-- Return focuses an existing pane (switching Swarms if needed) or opens an unviewed agent in the captured current Swarm. **Add to this swarm**, also Cmd-Enter inside the picker, explicitly shares an existing session here. It reuses the exact pane/session and focuses it for the next terminal key. A stale result or closed target cannot redirect the operation to unrelated work.
-- Machine/project results browse their agents inside the picker. Opening the whole reviewed group is an explicit **Open N agents as swarm** action that creates a new Swarm, observes capacity and revalidates member identities. Browsing, filtering and cancellation do not change the current arrangement. New arrivals are not silently added to a reviewed group operation.
+- The top-right search control is now a **real editable input**, using AppKit’s native field editor on macOS and a Flutter TextField in the fallback title bar. Clicking places the caret there; Cmd-P focuses/selects that same input. It expands left while active, and a modeless result list is anchored directly below it. There is no duplicate global-search input, centered dialog, dimming or blur. New swarm’s search launcher focuses the same bar; full History retains its separate session view.
+- `SwarmSearchController` shares catalog/ranking/actions between input and results. The catalog includes agents, Swarms, machines and projects, fuzzy matching across names/branches/folders/machines, and saved cross-machine project associations. Output notifications reuse normalized results; typing makes no file/network requests. Native edits are never echoed back over newer text/IME input, and keyboard result scrolling happens before paint.
+- Return focuses an existing pane (switching Swarms if needed) or opens an unviewed agent in the captured current Swarm. **Add to this swarm**, also Cmd-Enter while searching, explicitly shares an existing session here. It reuses the exact pane/session and focuses it for the next terminal key. A stale result or closed target cannot redirect the operation to unrelated work.
+- Machine/project results browse their agents in the attached list, keeping the caret in the original bar. Opening the whole reviewed group is an explicit **Open N agents as swarm** action that creates a new Swarm, observes capacity and revalidates member identities. Browsing, filtering and cancellation do not change the current arrangement. New arrivals are not silently added to a reviewed group operation.
- Removed the separate Cmd-Shift-F Add picker and its default shortcut, floating pane +, top-right bell, obsolete picker/selection code, and wallpaper rotation/menu/state. Needs Input remains in the native Swarm menu and Cmd-Shift-I. New agent remains in File and Cmd-N. No Cmd-O launcher was added. The selected mountain/lake dusk image is the only wallpaper asset in source and in the built bundle; only an empty New swarm loads it.
-- Live CUA review confirmed the native search control, immediate search typing, the Workshop project and all three cross-machine agents. It exposed lost field focus after clicking a group; the fix explicitly restores query focus on group entry/back, with a regression check. Repeated project/Swarm names in result subtitles are deduplicated. The final Release preview is running; CUA saw the corrected subtitles. The final native group-entry/Escape retest was interrupted by the user's app activity and remains pending. No more UI actions were sent after reading the fresh state; the user had closed the picker and was in Workshop.
-- Verification: **1,074 full Flutter tests passed with one existing skip**, **230 AppKit checks passed including hidden native window layout**, and analyzer reports no errors/warnings (12 existing vendored infos). After the live-review fix, all **20 focused search/history/attention checks passed** and analyzer remained clean apart from the same vendored infos. Both Release builds succeeded and each preview was quit/relaunched normally, one at a time. Logs: `/private/tmp/harness-v2-search-full-tests.log`, `harness-v2-search-titlebar.log`, `harness-v2-search-focus-tests.log`, `harness-v2-unified-search-analyze.log`, `harness-v2-search-focus-build.log`. Native input/display latency measurement remains paused and has no accepted result yet.
+- Live CUA review of the rebuilt Release confirmed an actual accessible native search text field; typing `autonomous-workshop` filters the attached results; clicking its project shows all three local/remote members and returns focus to the same input. Escape closes it. Cmd-P from the terminal focuses the bar; Cmd-P again selects the existing query, and replacement typing stays in that field. The final search was cancelled, leaving the original four Swarms and three-pane Workshop arrangement intact. No test input was sent to any agent, no view was added, and no daemon was restarted.
+- Verification: **1,075 full Flutter tests passed, one existing skip; 252 AppKit checks passed including hidden-window field editing/layout; analyzer has no errors/warnings and 12 existing vendored infos**. Search regressions cover one retained editable field, attachment geometry, one-frame scrolling, group/back focus, IME acceptance guards, query cancellation/next-key delivery to the original synthetic terminal, cross-Swarm focus, Add here, and native query changes without text echo. Native checks exercise the actual field editor, Unicode/select-all, composition command guards and return to the content controller. Release build succeeded. Logs: `/private/tmp/harness-v2-inline-search-full-tests.log`, `harness-v2-inline-search-tests.log`, `harness-v2-inline-search-titlebar.log`, `harness-v2-inline-search-analyze.log`, `harness-v2-inline-search-build.log`. Native end-to-end latency measurement remains paused and has no accepted result yet.
- Remote Workshop branch labels remain unavailable from the old iMac Home daemon. The implemented CLI agent metadata includes Git branch, but production daemons have not been upgraded or restarted. The existing remote file API deliberately excludes dotfiles/Git metadata; do not bypass that boundary or infer a remote branch from a local checkout.
- [Keyboard-system research and the complete shortcut audit](harness-v2-keyboard-system.md) is the next implementation track. File-first JSONC parser/resolver and bounded live-reload core pass 18 isolated tests (including invalid edits, stale reads, atomic saves and symlinked dotfiles). **They are not integrated into runtime dispatch, native menu equivalents or help yet.** Preserve terminal Control/Meta input while finishing that integration; the other proposed default changes are not shipped.
-- The sole final V2 preview was **PID 81588** at the last read-only process check; revalidate before any later restart. Continue on `app-v2`. Do not merge/release, update production daemons, send test input to real agents, restore old layouts or run overlapping V2 previews. The standalone native benchmark remains untracked calibration work; foreground runs are paused while the user is using the app. `docs/prototypes/` is unrelated user work and must be left alone.
+- The sole final V2 preview was **PID 7639** at the last read-only process check; revalidate before any later restart. Continue on `app-v2`. Do not merge/release, update production daemons, send test input to real agents, restore old layouts or run overlapping V2 previews. The standalone native benchmark remains untracked calibration work; foreground runs are paused while the user is using the app. `docs/prototypes/` is unrelated user work and must be left alone.
## Previous continuation