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.

Center search and add Swarm and Agent controls

dee2e8d69ddcb54
diff --git a/desktop/lib/core/repository_clone.dart b/desktop/lib/core/repository_clone.dart
index 5424d3b74..de4531138 100644
--- a/desktop/lib/core/repository_clone.dart
+++ b/desktop/lib/core/repository_clone.dart
@@ -24,8 +24,9 @@ class GitHubRepository {
uri.userInfo.isNotEmpty ||
uri.hasPort ||
uri.hasQuery ||
- uri.hasFragment)
+ uri.hasFragment) {
return null;
+ }
path = uri.path.replaceFirst(RegExp(r'^/'), '');
}
path = path
@@ -36,8 +37,9 @@ class GitHubRepository {
!RegExp(r'^[A-Za-z0-9][A-Za-z0-9-]{0,38}$').hasMatch(parts[0]) ||
!RegExp(r'^[A-Za-z0-9_.-]{1,100}$').hasMatch(parts[1]) ||
parts[1] == '.' ||
- parts[1] == '..')
+ parts[1] == '..') {
return null;
+ }
return GitHubRepository._(
ssh ? '[email protected]:$path.git' : 'https://github.com/$path.git',
parts[1],
@@ -121,20 +123,22 @@ class RepositoryClone {
final errors = process.stderr
.transform(const Utf8Decoder(allowMalformed: true))
.forEach((chunk) {
- if (diagnostic.length < 8192)
+ if (diagnostic.length < 8192) {
diagnostic += chunk.substring(
0,
chunk.length.clamp(0, 8192 - diagnostic.length),
);
+ }
});
final code = await process.exitCode;
await output;
await errors;
if (_cancelled) throw const RepositoryCloneException('Clone cancelled.');
- if (timedOut)
+ if (timedOut) {
throw const RepositoryCloneException(
'Cloning took too long. Check the connection and retry.',
);
+ }
if (code != 0) {
if (RegExp(
r'authentication|permission denied|could not read Username|repository not found',
diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dart
index b139fa372..4aefbf521 100644
--- a/desktop/lib/screens/swarm_screen.dart
+++ b/desktop/lib/screens/swarm_screen.dart
@@ -35,6 +35,7 @@ import '../widgets/pane_grid.dart';
import '../widgets/shortcuts_sheet.dart';
import '../widgets/swarm_dialogs.dart';
import '../widgets/swarm_inline_search.dart';
+import '../widgets/swarm_search_input.dart';
import '../widgets/swarm_project_agents.dart';
import '../widgets/swarm_attention.dart';
import '../widgets/swarm_switcher.dart';
@@ -69,14 +70,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
final _shellFocus = FocusNode(debugLabel: 'Swarm shell');
final _navigation = SwarmNavigationHistory();
final _searchText = TextEditingController();
- final _searchFocus = FocusNode(debugLabel: 'Title bar search');
- final _searchAnchor = LayerLink();
+ final _searchFocus = FocusNode(debugLabel: 'Search agents and swarms');
SwarmSearchController? _search;
OverlayEntry? _searchOverlay;
FocusNode? _searchReturnFocus;
- double _nativeSearchWidth = 600;
- ({String query, String hint})? _nativeSearchFieldState;
- bool _nativeQueryChange = false;
bool _spokenPaletteOpen = false;
bool _dialogOpen = false;
bool _routeIsCurrent = true;
@@ -101,7 +98,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
app.addListener(_recordNavigation);
FocusManager.instance.addListener(_restoreEmptyFocus);
FocusManager.instance.addListener(_syncKeyContext);
- _searchFocus.addListener(_searchFocusChanged);
grid.AppTheme.palette.addListener(_paletteChanged);
unawaited(_projects.load());
_spokenTasks = app.spokenTasks.listen(_openSpokenTask);
@@ -339,26 +335,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
await _modelsMenu?.refresh();
return;
}
- 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 == 'keymapCommand' &&
!(args['command'] as String? ?? '').startsWith('picker.')) {
if (args['command'] is String) _runShortcut(args['command']);
@@ -432,13 +408,23 @@ class _SwarmScreenState extends State<SwarmScreen> {
case 'addAgent':
await _addAgent();
case 'newAgent':
- await _newAgent(swarmId: app.activeSwarmId);
+ unawaited(_newAgent(swarmId: app.activeSwarmId));
+ case 'splitRight':
+ unawaited(_splitAgent(PaneResizeAxis.x));
+ case 'splitDown':
+ unawaited(_splitAgent(PaneResizeAxis.y));
+ case 'zoomPane':
+ app.toggleZoomPane();
+ case 'pinPane':
+ if (app.focusedPaneId != null) app.togglePinPane(app.focusedPaneId!);
case 'addProject':
await _addProject();
case 'linkMachine':
await _dialog(() => showSwarmLinkDialog(context, app));
case 'jump':
await _jump();
+ case 'commands':
+ _showSearchCommands();
case 'historyDestination':
final entry = _navigation
.menuDestinations(app)
@@ -461,12 +447,25 @@ class _SwarmScreenState extends State<SwarmScreen> {
case 'findPrevious':
app.focusedPane?.session?.find(TerminalFindAction.previous);
case 'notifications':
- await _notifications();
+ unawaited(_notifications());
case 'settings':
await _settings();
}
if (mounted &&
- const {'select', 'close', 'new', 'rename'}.contains(call.method)) {
+ const {
+ 'select',
+ 'close',
+ 'new',
+ 'rename',
+ 'jump',
+ 'commands',
+ 'notifications',
+ 'newAgent',
+ 'splitRight',
+ 'splitDown',
+ 'zoomPane',
+ 'pinPane',
+ }.contains(call.method)) {
// Native tab controls wait for this reply before releasing keyboard
// ownership. The destination's actual focus tree must be ready first.
await WidgetsBinding.instance.endOfFrame;
@@ -502,11 +501,21 @@ class _SwarmScreenState extends State<SwarmScreen> {
PaneSplitRequest? split,
bool chooseFolderFirst = false,
}) => _dialog(() async {
+ final focused = app.focusedPane;
+ final inherit =
+ machineId == null && !chooseFolderFirst && focused?.agentId != null;
+ final focusedMachine = inherit
+ ? app.machineStates[focused!.machineId]
+ : null;
+ final focusedAgent = focusedMachine?.agents
+ .where((agent) => agent.id == focused?.agentId)
+ .firstOrNull;
final local = app.machineStates.values
.where((m) => m.isLocalMachine)
.firstOrNull;
final id =
machineId ??
+ focusedMachine?.machine.machineId ??
local?.machine.machineId ??
app.machineStates.keys.firstOrNull;
if (id == null) {
@@ -515,7 +524,11 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
final targetId = swarmId ?? app.activeSwarmId;
final machine = app.machineStates[id];
- var selectedFolder = folder;
+ var selectedFolder =
+ folder ??
+ (focusedAgent == null
+ ? null
+ : focusedMachine?.projectOf(focusedAgent)?.cwd);
Future<void>? initialEngineProbe;
if (chooseFolderFirst && machine != null && machine.isLocalMachine) {
// Read availability while the user chooses a folder, so the form can
@@ -614,10 +627,6 @@ class _SwarmScreenState extends State<SwarmScreen> {
}
}
- void _searchFocusChanged() {
- if (_searchFocus.hasFocus && _search == null) _openSearch();
- }
-
void _openSearch() {
if (_search != null ||
!mounted ||
@@ -635,72 +644,45 @@ class _SwarmScreenState extends State<SwarmScreen> {
_navigation.recent,
projects: _projects,
commands: _searchCommands,
+ previewInitiallyEnabled: true,
);
_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();
+ _focusSearch();
}
void _focusSearch({bool selectAll = false}) {
if (_search == null) return;
- if (_native) {
- unawaited(
- _channel.invokeMethod<void>('focusSearch', {'selectAll': selectAll}),
+ _searchFocus.requestFocus();
+ if (selectAll) {
+ _searchText.selection = TextSelection(
+ baseOffset: 0,
+ extentOffset: _searchText.text.length,
);
- } else {
- _searchFocus.requestFocus();
- if (selectAll) {
- _searchText.selection = TextSelection(
- baseOffset: 0,
- extentOffset: _searchText.text.length,
- );
- }
}
}
+ void _showSearchCommands() {
+ _openSearch();
+ _search?.setQuery('> ');
+ _focusSearch();
+ }
+
void _syncSearch() {
final search = _search;
if (search == null) return;
- if (!_native && _searchText.text != search.query) {
+ if (_searchText.text != search.query) {
_searchText.value = TextEditingValue(
text: search.query,
selection: TextSelection.collapsed(offset: search.query.length),
);
}
- if (_native) {
- final state = (query: search.query, hint: search.hint);
- final updateQuery =
- !_nativeQueryChange && state.query != _nativeSearchFieldState?.query;
- final updateHint = state.hint != _nativeSearchFieldState?.hint;
- // Remember native edits even when no message is needed. A later catalog
- // refresh must not echo this query over a newer edit or marked text.
- _nativeSearchFieldState = state;
- if (updateQuery || updateHint) {
- unawaited(
- _channel.invokeMethod<void>('searchState', {
- if (updateQuery) 'query': state.query,
- 'hint': state.hint,
- }),
- );
- }
- }
_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();
@@ -709,10 +691,8 @@ class _SwarmScreenState extends State<SwarmScreen> {
_search!.removeListener(_syncSearch);
_search!.dispose();
_search = null;
- _nativeSearchFieldState = null;
_searchText.clear();
_searchFocus.unfocus();
- if (_native) unawaited(_channel.invokeMethod<void>('closeSearch'));
final previous = _searchReturnFocus;
_searchReturnFocus = null;
if (restoreFocus) {
@@ -732,73 +712,64 @@ class _SwarmScreenState extends State<SwarmScreen> {
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 height = swarmSearchResultsHeight(
- search,
- scale,
- ).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: 8,
- shadowColor: Colors.black54,
- color: grid.AppPalette.swarmSearchSurface,
- shape: const RoundedRectangleBorder(
- borderRadius: BorderRadius.vertical(bottom: Radius.circular(10)),
- ),
- clipBehavior: Clip.antiAlias,
- child: Padding(
- padding: const EdgeInsets.all(8),
- child: SwarmSearchResults(
- search: search,
- onChoose: _chooseSearch,
- onRefocus: _focusSearch,
- ),
- ),
- ),
- );
- return Stack(
+ return KeymapProvider(
+ keymap: _keymap,
+ child: LayoutBuilder(
+ builder: (context, constraints) => Stack(
children: [
- Positioned(
- top: _native ? 0 : 44,
- left: 0,
- right: 0,
- bottom: 0,
+ Positioned.fill(
child: GestureDetector(
behavior: HitTestBehavior.opaque,
onTap: _closeSearch,
+ child: const ColoredBox(color: Color(0x66000000)),
),
),
- if (_native)
- Positioned(top: 0, right: 8, child: results)
- else
- Positioned(
- left: 0,
- top: 0,
- child: CompositedTransformFollower(
- link: _searchAnchor,
- showWhenUnlinked: false,
- targetAnchor: Alignment.bottomRight,
- followerAnchor: Alignment.topRight,
- offset: Offset.zero,
- child: results,
+ Align(
+ alignment: const Alignment(0, -0.12),
+ child: SizedBox(
+ width: (constraints.maxWidth - 64).clamp(280.0, 1040.0),
+ height: (constraints.maxHeight - 96).clamp(220.0, 540.0),
+ child: Material(
+ key: const ValueKey('swarm-search-results'),
+ elevation: 16,
+ shadowColor: Colors.black54,
+ color: grid.AppPalette.swarmSearchSurface,
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(12),
+ side: const BorderSide(color: Colors.white24),
+ ),
+ clipBehavior: Clip.antiAlias,
+ child: Column(
+ children: [
+ SwarmSearchInput(
+ inputKey: const ValueKey('swarm-search-input'),
+ controller: _searchText,
+ focusNode: _searchFocus,
+ search: search,
+ onChoose: _chooseSearch,
+ onClose: _closeSearch,
+ onChanged: search.setQuery,
+ showClose: true,
+ ),
+ const Divider(height: 1, color: Colors.white12),
+ Expanded(
+ child: SwarmSearchResults(
+ search: search,
+ onChoose: _chooseSearch,
+ onRefocus: _focusSearch,
+ onCommands: _showSearchCommands,
+ ),
+ ),
+ ],
+ ),
),
),
+ ),
],
- );
- },
+ ),
+ ),
);
}
@@ -1000,11 +971,7 @@ class _SwarmScreenState extends State<SwarmScreen> {
command.id: _actionHandlers[command.action]!,
for (var i = 1; i <= kAgentDigitCount; i++)
'pane.focus_$i': () => app.focusPaneByIndex(i - 1),
- 'navigation.commands': () {
- _openSearch();
- _search?.setQuery('> ');
- _focusSearch();
- },
+ 'navigation.commands': _showSearchCommands,
'machine.link': () => _dialog(() => showSwarmLinkDialog(context, app)),
'project.add': _addProject,
'keyboard.open_config': () => openKeyboardConfig(context),
@@ -1191,6 +1158,10 @@ class _SwarmScreenState extends State<SwarmScreen> {
child: PaneGrid(
notifier: app,
swarmMode: true,
+ onSplit: (paneId, axis) {
+ app.focusPane(paneId);
+ unawaited(_splitAgent(axis));
+ },
empty: SwarmWelcome(
key: ValueKey(app.activeSwarmId),
notifier: app,
@@ -1332,132 +1303,38 @@ class _SwarmScreenState extends State<SwarmScreen> {
: null,
icon: const Icon(Icons.add, size: 18),
),
- Padding(
- padding: const EdgeInsets.only(left: 8, right: 8, top: 6),
- child: CompositedTransformTarget(
- link: _searchAnchor,
- child: SizedBox(
- width: _searchWidth(MediaQuery.sizeOf(context).width),
- height: 38,
- child: DecoratedBox(
- decoration: BoxDecoration(
- color: _search == null
- ? null
- : grid.AppPalette.swarmSearchSurface,
- borderRadius: const BorderRadius.vertical(
- top: Radius.circular(10),
- ),
- ),
- child: Align(
- alignment: Alignment.topCenter,
- child: SizedBox(
- height: 32,
- 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: 13,
- color: Color(0xffebebeb),
- ),
- textAlignVertical: TextAlignVertical.center,
- decoration: InputDecoration(
- hintText: _search?.hint ?? 'Search…',
- isDense: true,
- contentPadding: const EdgeInsets.symmetric(
- horizontal: 12,
- ),
- prefixIcon: const Icon(
- Icons.search,
- size: 16,
- color: Colors.white60,
- ),
- prefixIconConstraints:
- const BoxConstraints.tightFor(
- width: 36,
- height: 32,
- ),
- suffixIcon:
- _search == null &&
- _keymap.hint('navigation.quick_open') !=
- null
- ? Padding(
- padding: const EdgeInsets.only(right: 12),
- child: ConstrainedBox(
- constraints: const BoxConstraints(
- maxWidth: 80,
- ),
- child: Text(
- _keymap.hint(
- 'navigation.quick_open',
- )!,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(fontSize: 11),
- ),
- ),
- )
- : null,
- suffixIconConstraints: const BoxConstraints(
- minWidth: 24,
- ),
- filled: true,
- fillColor: grid.AppPalette.swarmSearchSurface,
- hintStyle: const TextStyle(color: Colors.white60),
- border: OutlineInputBorder(
- borderRadius: BorderRadius.circular(16),
- borderSide: const BorderSide(
- color: Color(0x29ffffff),
- ),
- ),
- enabledBorder: _search != null
- ? const OutlineInputBorder(
- borderRadius: BorderRadius.vertical(
- top: Radius.circular(10),
- ),
- borderSide: BorderSide.none,
- )
- : OutlineInputBorder(
- borderRadius: BorderRadius.circular(16),
- borderSide: const BorderSide(
- color: Color(0x29ffffff),
- ),
- ),
- focusedBorder: const OutlineInputBorder(
- borderRadius: BorderRadius.vertical(
- top: Radius.circular(10),
- ),
- borderSide: BorderSide.none,
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- ),
- ),
+ IconButton(
+ key: const ValueKey('swarm-search-button'),
+ tooltip: withEffectiveShortcutHint(
+ context,
+ 'Search',
+ ShortcutAction.switchAgent,
+ ),
+ onPressed: _jump,
+ icon: const Icon(Icons.search, size: 20),
+ ),
+ IconButton(
+ key: const ValueKey('swarm-new-agent-button'),
+ tooltip: withEffectiveShortcutHint(
+ context,
+ 'New agent',
+ ShortcutAction.newAgent,
),
+ onPressed: _newAgent,
+ icon: const Icon(Icons.add, size: 20),
),
IconButton(
+ key: const ValueKey('swarm-notifications-button'),
tooltip: withEffectiveShortcutHint(
context,
- 'Settings',
- ShortcutAction.showSettings,
+ 'Agents needing input',
+ ShortcutAction.showAttention,
+ ),
+ onPressed: _notifications,
+ icon: Badge(
+ isLabelVisible: _attention > 0,
+ child: const Icon(Icons.notifications_none, size: 20),
),
- onPressed: _settings,
- icon: const Icon(Icons.settings_outlined, size: 18),
),
const SizedBox(width: 6),
],
diff --git a/desktop/lib/shared/widgets/app_select_field.dart b/desktop/lib/shared/widgets/app_select_field.dart
index 332d685b7..99bfe8905 100644
--- a/desktop/lib/shared/widgets/app_select_field.dart
+++ b/desktop/lib/shared/widgets/app_select_field.dart
@@ -72,6 +72,7 @@ class AppSelectField<T> extends StatefulWidget {
required this.options,
required this.onChanged,
this.width,
+ this.height = AppControl.height,
this.trigger,
});
@@ -82,6 +83,7 @@ class AppSelectField<T> extends StatefulWidget {
/// Fixed width, so a column of these lines up on one right edge. Null lets it
/// take whatever its parent gives.
final double? width;
+ final double height;
/// An alternate compact trigger, such as the agent picker's More button.
/// Selection, keyboard navigation and menu rows remain shared.
@@ -243,7 +245,7 @@ class _AppSelectFieldState<T> extends State<AppSelectField<T>> {
duration: AppMotion.hover,
curve: AppMotion.curve,
width: widget.width,
- height: AppControl.height,
+ height: widget.height,
padding: const EdgeInsets.only(left: 10, right: 8),
decoration: BoxDecoration(
color: _hovered || _focused || controller.isOpen
diff --git a/desktop/lib/shortcuts/app_shortcuts.dart b/desktop/lib/shortcuts/app_shortcuts.dart
index 3532e0496..b6b92f23c 100644
--- a/desktop/lib/shortcuts/app_shortcuts.dart
+++ b/desktop/lib/shortcuts/app_shortcuts.dart
@@ -279,18 +279,6 @@ const List<AppShortcut> kAppShortcuts = [
label: 'Close the focused pane',
group: ShortcutGroup.panes,
),
- AppShortcut(
- action: ShortcutAction.pinPane,
- // ⇧⌘P: plain ⌘P is the switcher now, which is the key people reach for far
- // more often. Same letter, so the pair stays learnable.
- activator: SingleActivator(
- LogicalKeyboardKey.keyP,
- meta: true,
- shift: true,
- ),
- label: 'Hold this pane in its slot',
- group: ShortcutGroup.panes,
- ),
AppShortcut(
action: ShortcutAction.showLayout,
activator: SingleActivator(LogicalKeyboardKey.keyS, meta: true),
diff --git a/desktop/lib/shortcuts/keymap_commands.dart b/desktop/lib/shortcuts/keymap_commands.dart
index c1ce91a5b..1c18302d4 100644
--- a/desktop/lib/shortcuts/keymap_commands.dart
+++ b/desktop/lib/shortcuts/keymap_commands.dart
@@ -58,6 +58,7 @@ final harnessCommands = <HarnessCommand>[
'navigation.commands',
'Search commands',
ShortcutGroup.actions,
+ extraKeys: ['cmd+shift+p'],
nativeAction: 'commands',
),
const HarnessCommand(
@@ -228,6 +229,7 @@ final harnessCommands = <HarnessCommand>[
'Pin or unpin the focused pane',
ShortcutGroup.panes,
action: ShortcutAction.pinPane,
+ nativeAction: 'pinPane',
),
const HarnessCommand(
'pane.layout',
@@ -237,8 +239,18 @@ final harnessCommands = <HarnessCommand>[
nativeAction: 'layout',
),
const HarnessCommand('pane.resize', 'Resize panes', ShortcutGroup.panes),
- const HarnessCommand('pane.split_right', 'Split right…', ShortcutGroup.panes),
- const HarnessCommand('pane.split_down', 'Split down…', ShortcutGroup.panes),
+ const HarnessCommand(
+ 'pane.split_right',
+ 'Split right…',
+ ShortcutGroup.panes,
+ nativeAction: 'splitRight',
+ ),
+ const HarnessCommand(
+ 'pane.split_down',
+ 'Split down…',
+ ShortcutGroup.panes,
+ nativeAction: 'splitDown',
+ ),
const HarnessCommand(
'pane.reset_sizes',
'Reset pane sizes',
diff --git a/desktop/lib/state/swarm_search.dart b/desktop/lib/state/swarm_search.dart
index 7dbe7a93a..a3ddf3b18 100644
--- a/desktop/lib/state/swarm_search.dart
+++ b/desktop/lib/state/swarm_search.dart
@@ -16,7 +16,9 @@ class SwarmSearchController extends ChangeNotifier {
this.projects,
this.history,
this.commands,
- }) : targetId = app.activeSwarmId,
+ bool previewInitiallyEnabled = false,
+ }) : previewEnabled = previewInitiallyEnabled,
+ targetId = app.activeSwarmId,
targetName = app.activeSwarm.name {
_refresh();
app.addListener(_refresh);
@@ -40,12 +42,15 @@ class SwarmSearchController extends ChangeNotifier {
String query = '';
String? _selectedId;
int cursor = 0;
- bool previewEnabled = false;
+ bool previewEnabled;
SearchOutputPreview? preview;
String? _previewId;
bool get canPreview =>
- !isCommandMode && selected?.agentId != null && selected?.closedId == null;
+ !isCommandMode &&
+ history == null &&
+ selected != null &&
+ selected?.closedId == null;
bool get previewVisible => previewEnabled && canPreview;
void togglePreview() {
@@ -56,7 +61,7 @@ class SwarmSearchController extends ChangeNotifier {
}
void _updatePreview() {
- if (!previewVisible) {
+ if (!previewVisible || selected?.agentId == null) {
preview = null;
_previewId = null;
return;
diff --git a/desktop/lib/widgets/agent_picker.dart b/desktop/lib/widgets/agent_picker.dart
index 1df250c20..2d0e84a4c 100644
--- a/desktop/lib/widgets/agent_picker.dart
+++ b/desktop/lib/widgets/agent_picker.dart
@@ -44,7 +44,9 @@ class AgentPicker extends StatelessWidget {
: grid.AppSurface.recess,
minimumSize: const Size(0, 38),
padding: const EdgeInsets.symmetric(horizontal: 8),
- textStyle: const TextStyle(
+ textStyle: TextStyle(
+ fontFamily: grid.AppFont.sans,
+ fontFamilyFallback: grid.AppFont.sansFallback,
fontSize: 13,
fontWeight: FontWeight.w500,
),
@@ -72,6 +74,7 @@ class AgentPicker extends StatelessWidget {
options: options,
onChanged: onChanged,
width: 42,
+ height: 38,
trigger: Icon(
Icons.more_horiz,
size: 20,
diff --git a/desktop/lib/widgets/clone_repository_dialog.dart b/desktop/lib/widgets/clone_repository_dialog.dart
index 4df54957a..b03276af3 100644
--- a/desktop/lib/widgets/clone_repository_dialog.dart
+++ b/desktop/lib/widgets/clone_repository_dialog.dart
@@ -53,14 +53,16 @@ class _CloneRepositoryDialogState extends State<CloneRepositoryDialog> {
: p.dirname(widget.initialFolder!)),
confirmButtonText: 'Choose destination',
);
- if (mounted && folder != null)
+ if (mounted && folder != null) {
setState(() {
_parent = folder;
_error = null;
});
+ }
} catch (_) {
- if (mounted)
+ if (mounted) {
setState(() => _error = 'Could not open the folder picker. Try again.');
+ }
} finally {
if (mounted) setState(() => _picking = false);
}
@@ -80,10 +82,11 @@ class _CloneRepositoryDialogState extends State<CloneRepositoryDialog> {
} on RepositoryCloneException catch (error) {
if (mounted && !_closing) setState(() => _error = error.message);
} catch (_) {
- if (mounted && !_closing)
+ if (mounted && !_closing) {
setState(
() => _error = 'Could not clone the repository. Please retry.',
);
+ }
} finally {
if (mounted) {
setState(() => _clone = null);
diff --git a/desktop/lib/widgets/new_agent_dialog.dart b/desktop/lib/widgets/new_agent_dialog.dart
index aeb937946..37fbd846a 100644
--- a/desktop/lib/widgets/new_agent_dialog.dart
+++ b/desktop/lib/widgets/new_agent_dialog.dart
@@ -89,7 +89,7 @@ class _NewAgentDialog extends StatefulWidget {
}
class _NewAgentDialogState extends State<_NewAgentDialog> {
- final _folderFocus = FocusNode(debugLabel: 'Project folder');
+ final _folderFocus = FocusNode(debugLabel: 'Working folder');
late String _engine = allEngines.first.id;
bool _engineChosenByUser = false;
late String _machineId = widget.machineId;
diff --git a/desktop/lib/widgets/pane_actions_menu.dart b/desktop/lib/widgets/pane_actions_menu.dart
new file mode 100644
index 000000000..f2084db1b
--- /dev/null
+++ b/desktop/lib/widgets/pane_actions_menu.dart
@@ -0,0 +1,85 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../shared/widgets/app_menu.dart';
+
+class PaneActionsMenu extends StatefulWidget {
+ const PaneActionsMenu({
+ super.key,
+ required this.name,
+ this.onSplitRight,
+ this.onSplitDown,
+ this.onTogglePin,
+ this.onToggleComposer,
+ this.onClose,
+ this.pinned = false,
+ this.composerVisible = false,
+ });
+ final String name;
+ final VoidCallback? onSplitRight,
+ onSplitDown,
+ onTogglePin,
+ onToggleComposer,
+ onClose;
+ final bool pinned, composerVisible;
+ @override
+ State<PaneActionsMenu> createState() => _PaneActionsMenuState();
+}
+
+class _PaneActionsMenuState extends State<PaneActionsMenu> {
+ final _menu = MenuController();
+ Widget _action(String label, IconData icon, VoidCallback callback) =>
+ AppMenuItem(
+ label: label,
+ icon: icon,
+ onPressed: () {
+ _menu.close();
+ callback();
+ },
+ );
+
+ @override
+ Widget build(BuildContext context) => MenuAnchor(
+ controller: _menu,
+ style: grid.AppMenu.style(minWidth: 220),
+ menuChildren: [
+ if (widget.onSplitRight != null)
+ _action(
+ 'Split right',
+ Icons.vertical_split_outlined,
+ widget.onSplitRight!,
+ ),
+ if (widget.onSplitDown != null)
+ _action(
+ 'Split down',
+ Icons.horizontal_split_outlined,
+ widget.onSplitDown!,
+ ),
+ if (widget.onSplitRight != null || widget.onSplitDown != null)
+ const AppMenuDivider(),
+ if (widget.onTogglePin != null)
+ _action(
+ widget.pinned ? 'Unpin agent' : 'Pin agent',
+ Icons.push_pin_outlined,
+ widget.onTogglePin!,
+ ),
+ if (widget.onToggleComposer != null)
+ _action(
+ widget.composerVisible
+ ? 'Hide message composer'
+ : 'Show message composer',
+ Icons.edit_note,
+ widget.onToggleComposer!,
+ ),
+ if (widget.onClose != null)
+ _action('Close agent', Icons.close, widget.onClose!),
+ ],
+ builder: (_, menu, _) => IconButton(
+ tooltip: 'Actions for ${widget.name}',
+ onPressed: () => menu.isOpen ? menu.close() : menu.open(),
+ icon: const Icon(Icons.more_horiz, size: 18),
+ constraints: const BoxConstraints.tightFor(width: 28, height: 28),
+ padding: EdgeInsets.zero,
+ ),
+ );
+}
diff --git a/desktop/lib/widgets/pane_grid.dart b/desktop/lib/widgets/pane_grid.dart
index 10905aa13..92697adcb 100644
--- a/desktop/lib/widgets/pane_grid.dart
+++ b/desktop/lib/widgets/pane_grid.dart
@@ -34,11 +34,13 @@ class PaneGrid extends StatelessWidget {
required this.notifier,
this.swarmMode = false,
this.empty,
+ this.onSplit,
});
final AppNotifier notifier;
final bool swarmMode;
final Widget? empty;
+ final void Function(int paneId, PaneResizeAxis axis)? onSplit;
@override
Widget build(BuildContext context) {
@@ -50,6 +52,7 @@ class PaneGrid extends StatelessWidget {
notifier: notifier,
dragging: dragging,
empty: empty,
+ onSplit: onSplit,
);
}
final panes = notifier.panes;
@@ -209,10 +212,12 @@ class _SwarmCanvas extends StatefulWidget {
required this.notifier,
required this.dragging,
this.empty,
+ this.onSplit,
});
final AppNotifier notifier;
final AgentDragRef? dragging;
final Widget? empty;
+ final void Function(int paneId, PaneResizeAxis axis)? onSplit;
@override
State<_SwarmCanvas> createState() => _SwarmCanvasState();
}
@@ -354,6 +359,8 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {
focusRequest: app.isPaneFocused(pane.id) ? app.paneFocusRequest : 0,
single: app.panes.length == 1,
pinned: app.isPanePinned(pane),
+ zoomed: app.zoomedPaneId == pane.id,
+ canSplit: app.canAddPane,
composer: pane.composerVisible,
blocked:
app.questionFor(pane.machineId, pane.agentId ?? session.agentId) !=
@@ -431,6 +438,7 @@ class _SwarmCanvasState extends State<_SwarmCanvas> {
dragging: widget.dragging,
visible: rectangles.containsKey(pane.id),
swarmMode: true,
+ onSplit: widget.onSplit,
),
),
),
@@ -935,6 +943,7 @@ class _PaneCell extends StatelessWidget {
required this.dragging,
this.visible = true,
this.swarmMode = false,
+ this.onSplit,
});
final AppNotifier notifier;
@@ -942,6 +951,7 @@ class _PaneCell extends StatelessWidget {
final AgentDragRef? dragging;
final bool visible;
final bool swarmMode;
+ final void Function(int paneId, PaneResizeAxis axis)? onSplit;
bool get _single => notifier.panes.length == 1;
@@ -1049,6 +1059,7 @@ class _PaneCell extends StatelessWidget {
single: _single,
visible: visible,
swarmMode: swarmMode,
+ onSplit: onSplit,
),
),
),
@@ -1068,6 +1079,7 @@ class _PaneContent extends StatelessWidget {
required this.single,
required this.visible,
required this.swarmMode,
+ this.onSplit,
});
final AppNotifier notifier;
@@ -1075,6 +1087,7 @@ class _PaneContent extends StatelessWidget {
final bool single;
final bool visible;
final bool swarmMode;
+ final void Function(int paneId, PaneResizeAxis axis)? onSplit;
@override
Widget build(BuildContext context) {
@@ -1156,6 +1169,19 @@ class _PaneContent extends StatelessWidget {
onClose: single && !swarmMode ? null : close,
pinned: notifier.isPanePinned(pane),
onTogglePin: single ? null : () => notifier.togglePinPane(pane.id),
+ zoomed: notifier.zoomedPaneId == pane.id,
+ onToggleZoom: swarmMode
+ ? () {
+ notifier.focusPane(pane.id);
+ notifier.toggleZoomPane();
+ }
+ : null,
+ onSplitRight: onSplit == null || !notifier.canAddPane
+ ? null
+ : () => onSplit!(pane.id, PaneResizeAxis.x),
+ onSplitDown: onSplit == null || !notifier.canAddPane
+ ? null
+ : () => onSplit!(pane.id, PaneResizeAxis.y),
onRendererFocus: () => notifier.focusPane(pane.id),
paneDrag: single
? null
diff --git a/desktop/lib/widgets/pane_resize_handle.dart b/desktop/lib/widgets/pane_resize_handle.dart
index d78bdaee3..7e5bdc853 100644
--- a/desktop/lib/widgets/pane_resize_handle.dart
+++ b/desktop/lib/widgets/pane_resize_handle.dart
@@ -3,6 +3,7 @@ import 'package:flutter/gestures.dart';
import 'package:flutter/services.dart';
import '../state/pane_arrangement.dart';
+import '../shared/theme/app_theme.dart' as grid;
/// The existing gap is the hit target. Only hover or keyboard focus reveals
/// its thin grip; pointer movement never changes the focused agent.
@@ -187,19 +188,31 @@ class _PaneResizeHandleState extends State<PaneResizeHandle> {
onVerticalDragUpdate: _horizontal ? null : _drag,
onVerticalDragEnd: _horizontal ? null : _end,
onVerticalDragCancel: _horizontal ? null : _cancel,
- child: Center(
- child: Container(
- width: _horizontal ? 2 : double.infinity,
- height: _horizontal ? double.infinity : 2,
- margin: _horizontal
- ? const EdgeInsets.symmetric(vertical: 12)
- : const EdgeInsets.symmetric(horizontal: 12),
- color: _focused
- ? Colors.white70
- : _hover
- ? Colors.white30
- : Colors.transparent,
- ),
+ child: Stack(
+ alignment: Alignment.center,
+ children: [
+ if (_hover || _focused || _start != null)
+ Center(
+ child: Container(
+ width: _horizontal ? 1 : double.infinity,
+ height: _horizontal ? double.infinity : 1,
+ color: grid.AppPalette.swarmAccent.withValues(alpha: .35),
+ ),
+ ),
+ Center(
+ child: AnimatedContainer(
+ duration: const Duration(milliseconds: 100),
+ width: _horizontal ? 3 : 36,
+ height: _horizontal ? 36 : 3,
+ decoration: BoxDecoration(
+ borderRadius: BorderRadius.circular(2),
+ color: _hover || _focused || _start != null
+ ? grid.AppPalette.swarmAccent
+ : Colors.white24,
+ ),
+ ),
+ ),
+ ],
),
),
),
diff --git a/desktop/lib/widgets/swarm_inline_search.dart b/desktop/lib/widgets/swarm_inline_search.dart
index e7d2da53b..4c342ae97 100644
--- a/desktop/lib/widgets/swarm_inline_search.dart
+++ b/desktop/lib/widgets/swarm_inline_search.dart
@@ -10,6 +10,7 @@ import '../state/swarm_catalog.dart';
import '../state/swarm_navigation.dart';
import '../state/swarm_search.dart';
import 'swarm_switcher.dart';
+import 'swarm_search_input.dart';
/// New swarm owns its input and caret. Only the catalog and result actions are
/// shared with the title bar; typing here never activates the native field.
@@ -72,6 +73,7 @@ class _SwarmInlineSearchState extends State<SwarmInlineSearch> {
widget.recent,
projects: widget.projects,
commands: widget.commands,
+ previewInitiallyEnabled: true,
)..setQuery(_text.text);
_search!.addListener(_changed);
_overlay.show();
@@ -80,6 +82,16 @@ class _SwarmInlineSearchState extends State<SwarmInlineSearch> {
void _changed() => setState(() {});
+ void _showCommands() {
+ _text.value = const TextEditingValue(
+ text: '> ',
+ selection: TextSelection.collapsed(offset: 2),
+ );
+ _begin();
+ _search!.setQuery('> ');
+ _focus.requestFocus();
+ }
+
void _close() {
if (_search == null) return;
_overlay.hide();
@@ -109,14 +121,6 @@ class _SwarmInlineSearchState extends State<SwarmInlineSearch> {
@override
Widget build(BuildContext context) {
- final open = _search != null;
- final border = OutlineInputBorder(
- borderRadius: BorderRadius.vertical(
- top: const Radius.circular(8),
- bottom: Radius.circular(open ? 0 : 8),
- ),
- borderSide: BorderSide(color: open ? Colors.transparent : Colors.white24),
- );
return OverlayPortal.overlayChildLayoutBuilder(
controller: _overlay,
overlayChildBuilder: (context, info) {
@@ -148,15 +152,16 @@ class _SwarmInlineSearchState extends State<SwarmInlineSearch> {
elevation: 8,
shadowColor: Colors.black54,
borderRadius: const BorderRadius.vertical(
- bottom: Radius.circular(8),
+ bottom: Radius.circular(12),
),
clipBehavior: Clip.antiAlias,
child: Padding(
- padding: const EdgeInsets.all(8),
+ padding: EdgeInsets.zero,
child: SwarmSearchResults(
search: search,
onChoose: _choose,
onRefocus: _focus.requestFocus,
+ onCommands: _showCommands,
),
),
),
@@ -164,48 +169,20 @@ class _SwarmInlineSearchState extends State<SwarmInlineSearch> {
),
);
},
- child: SwarmSearchKeys(
+ child: SwarmSearchInput(
+ inputKey: const ValueKey('swarm-welcome-search-input'),
+ controller: _text,
+ focusNode: _focus,
+ groupId: _tapGroup,
search: _search,
- editing: _text,
onChoose: _choose,
onClose: _close,
onOpen: _begin,
- child: TextField(
- key: const ValueKey('swarm-welcome-search-input'),
- groupId: _tapGroup,
- controller: _text,
- focusNode: _focus,
- autofocus: true,
- onTap: _begin,
- onTapAlwaysCalled: true,
- onTapOutside: (_) => _close(),
- onChanged: (value) {
- _begin();
- _search!.setQuery(value);
- },
- style: const TextStyle(fontSize: 13, color: Colors.white),
- decoration: InputDecoration(
- hintText: 'Search agents, swarms, machines, projects…',
- hintStyle: const TextStyle(fontSize: 13, color: Color(0xffc5bece)),
- prefixIcon: const Icon(
- Icons.search,
- size: 18,
- color: Color(0xffc5bece),
- ),
- filled: true,
- fillColor: open
- ? grid.AppPalette.swarmSearchSurface
- : const Color(0xa6111521),
- contentPadding: const EdgeInsets.symmetric(
- horizontal: 14,
- vertical: 14,
- ),
- isDense: true,
- border: border,
- enabledBorder: border,
- focusedBorder: border,
- ),
- ),
+ onTapOutside: _close,
+ onChanged: (value) {
+ _begin();
+ _search!.setQuery(value);
+ },
),
);
}
diff --git a/desktop/lib/widgets/swarm_search_input.dart b/desktop/lib/widgets/swarm_search_input.dart
new file mode 100644
index 000000000..6c642a879
--- /dev/null
+++ b/desktop/lib/widgets/swarm_search_input.dart
@@ -0,0 +1,106 @@
+import 'package:flutter/material.dart';
+
+import '../shared/theme/app_theme.dart' as grid;
+import '../state/swarm_search.dart';
+import '../state/swarm_navigation.dart';
+import 'swarm_switcher.dart';
+
+/// The same editable input in the centered picker and the New swarm page.
+/// Flutter owns both the caret and result navigation; native chrome only opens it.
+class SwarmSearchInput extends StatelessWidget {
+ const SwarmSearchInput({
+ super.key,
+ required this.inputKey,
+ required this.controller,
+ required this.focusNode,
+ required this.search,
+ required this.onChoose,
+ required this.onClose,
+ required this.onChanged,
+ this.onOpen,
+ this.groupId,
+ this.onTapOutside,
+ this.showClose = false,
+ this.autofocus = true,
+ });
+
+ final Key inputKey;
+ final TextEditingController controller;
+ final FocusNode focusNode;
+ final SwarmSearchController? search;
+ final ValueChanged<SwarmSearchSelection> onChoose;
+ final VoidCallback onClose;
+ final ValueChanged<String> onChanged;
+ final VoidCallback? onOpen;
+ final Object? groupId;
+ final VoidCallback? onTapOutside;
+ final bool showClose, autofocus;
+
+ @override
+ Widget build(BuildContext context) {
+ final open = search != null;
+ final border = OutlineInputBorder(
+ borderRadius: BorderRadius.vertical(
+ top: const Radius.circular(12),
+ bottom: Radius.circular(open ? 0 : 12),
+ ),
+ borderSide: BorderSide(color: open ? Colors.transparent : Colors.white24),
+ );
+ return SwarmSearchKeys(
+ search: search,
+ editing: controller,
+ onChoose: onChoose,
+ onClose: onClose,
+ onOpen: onOpen,
+ child: TextField(
+ key: inputKey,
+ groupId: groupId ?? EditableText,
+ controller: controller,
+ focusNode: focusNode,
+ autofocus: autofocus,
+ onTap: onOpen,
+ onTapAlwaysCalled: true,
+ onTapOutside: onTapOutside == null ? null : (_) => onTapOutside!(),
+ onChanged: onChanged,
+ style: const TextStyle(fontSize: 16, color: Colors.white),
+ cursorColor: grid.AppPalette.swarmAccent,
+ textAlignVertical: TextAlignVertical.center,
+ decoration: InputDecoration(
+ hintText:
+ search?.hint ?? 'Search agents, swarms, machines, projects…',
+ hintStyle: const TextStyle(fontSize: 16, color: Colors.white60),
+ prefixIcon: const Icon(Icons.search, size: 20, color: Colors.white60),
+ prefixIconConstraints: const BoxConstraints(
+ minWidth: 52,
+ minHeight: 56,
+ ),
+ suffixIcon: showClose
+ ? Padding(
+ padding: const EdgeInsets.only(right: 12),
+ child: TextButton(
+ onPressed: onClose,
+ style: TextButton.styleFrom(
+ foregroundColor: Colors.white60,
+ minimumSize: const Size(36, 28),
+ ),
+ child: const Text('esc', style: TextStyle(fontSize: 11)),
+ ),
+ )
+ : null,
+ filled: true,
+ fillColor: open
+ ? grid.AppPalette.swarmSearchSurface
+ : const Color(0xa6111521),
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 18,
+ vertical: 18,
+ ),
+ isDense: true,
+ border: border,
+ enabledBorder: border,
+ focusedBorder: border,
+ ),
+ ),
+ );
+ }
+}
diff --git a/desktop/lib/widgets/swarm_switcher.dart b/desktop/lib/widgets/swarm_switcher.dart
index abd8ddeda..5389b34e0 100644
--- a/desktop/lib/widgets/swarm_switcher.dart
+++ b/desktop/lib/widgets/swarm_switcher.dart
@@ -104,8 +104,7 @@ class _SwarmHistoryState extends State<_SwarmHistory> {
);
}
-/// The Flutter field and History use the same keys. The native field sends
-/// these commands to the same controller after AppKit has handled composition.
+/// Centered search, inline search and History share editing and navigation keys.
class SwarmSearchKeys extends StatelessWidget {
const SwarmSearchKeys({
super.key,
@@ -250,17 +249,16 @@ class SwarmSearchKeys extends StatelessWidget {
double swarmSearchRowHeight(TextScaler scale, {required bool commands}) =>
commands
- ? (scale.scale(13) + 20).clamp(40, double.infinity)
- : (scale.scale(13) + scale.scale(11) + 32).clamp(56, double.infinity);
+ ? (scale.scale(14) + 20).clamp(40, double.infinity)
+ : (scale.scale(14) + scale.scale(12) + 30).clamp(56, double.infinity);
double swarmSearchResultsHeight(
SwarmSearchController search,
TextScaler scale,
) =>
- search.rows.length.clamp(1, search.previewVisible ? 4 : 7) *
+ search.rows.length.clamp(4, 7) *
swarmSearchRowHeight(scale, commands: search.isCommandMode) +
- 64 +
- (search.previewVisible ? scale.scale(11) * 10 + 24 : 0);
+ 52;
/// Shared results for the title bar, New swarm field and History.
class SwarmSearchResults extends StatefulWidget {
@@ -269,10 +267,12 @@ class SwarmSearchResults extends StatefulWidget {
required this.search,
required this.onChoose,
required this.onRefocus,
+ this.onCommands,
});
final SwarmSearchController search;
final ValueChanged<SwarmSearchSelection> onChoose;
final VoidCallback onRefocus;
+ final VoidCallback? onCommands;
@override
State<SwarmSearchResults> createState() => _SwarmSearchResultsState();
}
@@ -301,7 +301,7 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
void _scrollToSelection() {
if (!_scroll.hasClients || search.rows.isEmpty) return;
- final top = search.cursor * _rowHeight;
+ final top = 8 + search.cursor * _rowHeight;
final bottom = top + _rowHeight;
final position = _scroll.position;
final offset = top < position.pixels
@@ -332,21 +332,6 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
@override
Widget build(BuildContext context) {
final scale = MediaQuery.textScalerOf(context);
- String? hint(String command) => effectiveCommandHint(
- context,
- command,
- contextKind: KeymapContext.picker,
- );
- final previewHint = hint('picker.preview');
- final movementHints = [
- hint('picker.previous'),
- hint('picker.next'),
- ].whereType<String>().join(' ');
- final cancelHint = hint('picker.cancel');
- final navigationHint = [
- if (movementHints.isNotEmpty) '$movementHints choose',
- if (cancelHint != null) '$cancelHint close',
- ].join(' · ');
_rowHeight = swarmSearchRowHeight(scale, commands: search.isCommandMode);
final selected = search.selected;
final terms = swarmQueryTerms(
@@ -356,182 +341,211 @@ class _SwarmSearchResultsState extends State<SwarmSearchResults> {
);
return LayoutBuilder(
builder: (context, constraints) {
- final previewHeight = (constraints.maxHeight - _rowHeight - 48).clamp(
- 0.0,
- scale.scale(11) * 10 + 24,
- );
+ final showPreview =
+ search.previewVisible && constraints.maxWidth >= 600;
return Semantics(
container: true,
label: 'Search results',
child: Column(
children: [
Expanded(
- child: search.rows.isEmpty
- ? Center(
- child: Text(
- search.isCommandMode
- ? 'No matching commands'
- : 'No matching results',
- style: const TextStyle(
- fontSize: 13,
- color: Colors.white60,
- ),
- ),
- )
- : ListView.builder(
- controller: _scroll,
- itemCount: search.rows.length,
- itemExtent: _rowHeight,
- itemBuilder: (context, index) {
- final row = search.rows[index];
- final matches = searchResultMatches(row, terms);
- return ListTile(
- key: ValueKey(row.id),
- minTileHeight: _rowHeight,
- enabled: search.canSubmit(row),
- selected: index == search.cursor,
- selectedColor: Colors.white,
- selectedTileColor: Colors.white10,
- shape: RoundedRectangleBorder(
- borderRadius: BorderRadius.circular(8),
- ),
- contentPadding: const EdgeInsets.symmetric(
- horizontal: 12,
- ),
- leading: row.isCommand
- ? const Icon(
- Icons.keyboard_command_key,
- size: 19,
- color: Colors.white60,
- )
- : row.agentId != null
- ? EngineMark(
- engine: row.engine,
- size: 20,
- enabled: search.canSubmit(row),
- )
- : row.isSwarm
- ? const SwarmIcon(color: Colors.white60)
- : Icon(
- row.isMachine
- ? Icons.computer_outlined
- : Icons.folder_outlined,
- size: 19,
- color: Colors.white60,
+ child: Row(
+ crossAxisAlignment: CrossAxisAlignment.stretch,
+ children: [
+ Expanded(
+ flex: 6,
+ child: search.rows.isEmpty
+ ? Center(
+ child: Text(
+ search.isCommandMode
+ ? 'No matching commands'
+ : 'No matching results',
+ style: const TextStyle(
+ fontSize: 14,
+ color: Colors.white60,
+ ),
+ ),
+ )
+ : ListView.builder(
+ key: const ValueKey('swarm-search-result-list'),
+ padding: const EdgeInsets.all(8),
+ controller: _scroll,
+ itemCount: search.rows.length,
+ itemExtent: _rowHeight,
+ itemBuilder: (context, index) {
+ final row = search.rows[index];
+ final matches = searchResultMatches(row, terms);
+ return ListTile(
+ key: ValueKey(row.id),
+ minTileHeight: _rowHeight,
+ enabled: search.canSubmit(row),
+ selected: index == search.cursor,
+ selectedColor: Colors.white,
+ selectedTileColor: Colors.white.withValues(
+ alpha: .075,
),
- title: SearchResultText(
- row.title,
- matches: matches.where((match) => match.title),
- style: const TextStyle(fontSize: 13),
- ),
- subtitle: row.isCommand
- ? null
- : SearchResultText(
- row.detail,
- matches: matches.where(
- (match) => !match.title,
- ),
- style: const TextStyle(
- fontSize: 11,
- color: Colors.white70,
- ),
+ shape: RoundedRectangleBorder(
+ borderRadius: BorderRadius.circular(6),
+ ),
+ contentPadding: const EdgeInsets.symmetric(
+ horizontal: 12,
),
- trailing: row.shortcut == null
- ? null
- : Text(
- row.shortcut!,
- style: const TextStyle(
- fontSize: 11,
- color: Colors.white70,
+ leading: row.isCommand
+ ? const Icon(
+ Icons.keyboard_command_key,
+ size: 20,
+ color: Colors.white60,
+ )
+ : row.agentId != null
+ ? EngineMark(
+ engine: row.engine,
+ size: 22,
+ enabled: search.canSubmit(row),
+ )
+ : const SwarmIcon(
+ size: 22,
+ color: Colors.white60,
+ ),
+ title: SearchResultText(
+ row.title,
+ matches: matches.where(
+ (match) => match.title,
),
+ style: const TextStyle(fontSize: 14),
),
- onTap: search.canSubmit(row)
- ? () => _submit(row)
- : null,
- );
- },
+ subtitle: row.isCommand
+ ? null
+ : SearchResultText(
+ row.detail,
+ matches: matches.where(
+ (match) => !match.title,
+ ),
+ style: const TextStyle(
+ fontSize: 12,
+ color: Colors.white60,
+ ),
+ ),
+ trailing: row.shortcut == null
+ ? null
+ : Text(
+ row.shortcut!,
+ style: const TextStyle(
+ fontSize: 12,
+ color: Colors.white60,
+ ),
+ ),
+ onTap: search.canSubmit(row)
+ ? () => _submit(row)
+ : null,
+ );
+ },
+ ),
+ ),
+ if (showPreview) ...[
+ const VerticalDivider(width: 1, color: Colors.white12),
+ Expanded(
+ flex: 4,
+ child: _OutputPreview(
+ row: selected!,
+ text: search.preview?.text ?? '',
+ ),
),
- ),
- if (search.previewVisible && previewHeight >= 64)
- SizedBox(
- height: previewHeight,
- child: _OutputPreview(text: search.preview?.text ?? ''),
+ ],
+ ],
),
- const SizedBox(height: 4),
- Row(
- children: [
- Expanded(
- child: Padding(
- padding: const EdgeInsets.symmetric(horizontal: 10),
- child: Text(
- selected != null && !search.canSubmit(selected)
- ? selected.isGroup &&
- selected.members.length >
- AppNotifier.maxPanes
- ? 'A swarm supports up to ${AppNotifier.maxPanes} agents'
- : 'No room to open this ${selected.isSwarm || selected.isGroup ? 'swarm' : 'agent'}'
- : selected?.closedId != null
- ? search.canSubmit(selected)
- ? 'Reopen ${selected!.isSwarm ? 'swarm' : 'agent'}'
- : 'No room to reopen'
- : selected?.agentId != null && !selected!.hasView
- ? 'Opens in ${search.targetName}'
- : search.query.isEmpty && search.commands != null
- ? 'Type > for commands'
- : navigationHint,
- maxLines: 1,
- overflow: TextOverflow.ellipsis,
- style: const TextStyle(
- fontSize: 11,
- color: Colors.white70,
+ ),
+ const Divider(height: 1, color: Colors.white12),
+ SizedBox(
+ height: 48,
+ child: Padding(
+ padding: const EdgeInsets.symmetric(horizontal: 12),
+ child: Row(
+ children: [
+ if (widget.onCommands != null)
+ TextButton(
+ key: const ValueKey('swarm-search-commands'),
+ onPressed: widget.onCommands,
+ style: TextButton.styleFrom(
+ foregroundColor: Colors.white70,
+ ),
+ child: const Text(
+ '> Commands',
+ style: TextStyle(fontSize: 12),
+ ),
),
- ),
- ),
- ),
- if (search.canPreview ||
- search.previewEnabled && !search.isCommandMode)
- Tooltip(
- message:
- '${search.previewEnabled ? 'Hide preview' : 'Preview recent output'}${previewHint == null ? '' : ' ($previewHint)'}',
- child: IconButton(
- key: const ValueKey('swarm-search-preview-toggle'),
- onPressed: () {
- search.togglePreview();
- widget.onRefocus();
- },
- icon: Icon(
- search.previewEnabled
- ? Icons.visibility
- : Icons.visibility_outlined,
- size: 18,
- color: search.previewEnabled
- ? Colors.white
- : Colors.white70,
+ if (selected != null && !search.canSubmit(selected))
+ Expanded(
+ child: Text(
+ selected.isGroup &&
+ selected.members.length >
+ AppNotifier.maxPanes
+ ? 'A swarm supports up to ${AppNotifier.maxPanes} agents'
+ : 'No room to open this ${selected.isSwarm || selected.isGroup ? 'swarm' : 'agent'}',
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(
+ fontSize: 11,
+ color: Colors.white60,
+ ),
+ ),
+ )
+ else
+ const Spacer(),
+ if (constraints.maxWidth >= 600 &&
+ (search.canPreview ||
+ search.previewEnabled && !search.isCommandMode))
+ IconButton(
+ key: const ValueKey('swarm-search-preview-toggle'),
+ tooltip: [
+ search.previewEnabled
+ ? 'Hide preview'
+ : 'Show preview',
+ if (effectiveCommandHint(
+ context,
+ 'picker.preview',
+ contextKind: KeymapContext.picker,
+ )
+ case final hint?)
+ '($hint)',
+ ].join(' '),
+ onPressed: () {
+ search.togglePreview();
+ widget.onRefocus();
+ },
+ icon: Icon(
+ search.previewEnabled
+ ? Icons.visibility_outlined
+ : Icons.visibility_off_outlined,
+ size: 18,
+ color: Colors.white60,
+ ),
+ visualDensity: VisualDensity.compact,
+ ),
+ if (search.canAdd(selected))
+ TextButton(
+ onPressed: () => widget.onChoose(search.addHere()!),
+ style: TextButton.styleFrom(
+ foregroundColor: Colors.white70,
+ ),
+ child: const _SearchActionLabel(
+ 'Add to this swarm',
+ command: 'picker.add_here',
+ ),
+ ),
+ TextButton(
+ onPressed: search.canSubmit(selected) ? _submit : null,
+ style: TextButton.styleFrom(
+ foregroundColor: Colors.white,
+ ),
+ child: _SearchActionLabel(
+ selected == null
+ ? 'Go to'
+ : SwarmSearchController.action(selected),
),
- visualDensity: VisualDensity.compact,
- ),
- ),
- if (search.canAdd(selected))
- TextButton(
- onPressed: () => widget.onChoose(search.addHere()!),
- style: TextButton.styleFrom(
- foregroundColor: Colors.white70,
- ),
- child: const _SearchActionLabel(
- 'Add to this swarm',
- command: 'picker.add_here',
),
- ),
- TextButton(
- onPressed: search.canSubmit(selected) ? _submit : null,
- style: TextButton.styleFrom(foregroundColor: Colors.white),
- child: _SearchActionLabel(
- selected == null
- ? 'Go to'
- : SwarmSearchController.action(selected),
- ),
+ ],
),
- ],
+ ),
),
],
),
@@ -586,37 +600,69 @@ class _SearchActionLabel extends StatelessWidget {
}
class _OutputPreview extends StatelessWidget {
- const _OutputPreview({required this.text});
+ const _OutputPreview({required this.row, required this.text});
+ final SwarmDestination row;
final String text;
@override
Widget build(BuildContext context) => Container(
key: const ValueKey('swarm-search-preview'),
- width: double.infinity,
- margin: const EdgeInsets.fromLTRB(8, 8, 8, 4),
- padding: const EdgeInsets.all(10),
- decoration: BoxDecoration(
- color: Colors.black.withValues(alpha: 0.16),
- borderRadius: BorderRadius.circular(6),
- ),
+ color: Colors.black.withValues(alpha: 0.10),
+ padding: const EdgeInsets.all(20),
child: Column(
- mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
- const Tooltip(
- message: 'A snapshot of available output. Turn preview off and on to refresh.',
- child: Text(
- 'Output preview',
- style: TextStyle(fontSize: 11, color: Colors.white70),
+ Text(
+ row.agentId == null ? 'SWARM PREVIEW' : 'AGENT PREVIEW',
+ style: const TextStyle(
+ fontSize: 10,
+ letterSpacing: 1.3,
+ color: Colors.white54,
+ ),
+ ),
+ const SizedBox(height: 18),
+ Row(
+ children: [
+ if (row.agentId == null)
+ const SwarmIcon(size: 20, color: Colors.white70)
+ else
+ EngineMark(engine: row.engine, size: 20),
+ const SizedBox(width: 10),
+ Expanded(
+ child: Text(
+ row.title,
+ maxLines: 2,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(
+ fontSize: 15,
+ fontWeight: FontWeight.w500,
+ color: Colors.white,
+ ),
+ ),
+ ),
+ ],
+ ),
+ const SizedBox(height: 8),
+ Text(
+ row.detail,
+ maxLines: 3,
+ overflow: TextOverflow.ellipsis,
+ style: const TextStyle(
+ fontSize: 12,
+ height: 1.5,
+ color: Colors.white60,
),
),
- const SizedBox(height: 6),
- Flexible(
+ const SizedBox(height: 24),
+ Expanded(
child: SingleChildScrollView(
primary: false,
- reverse: true,
child: Text(
- text.isEmpty ? 'No output available for preview.' : text,
+ row.agentId == null
+ ? 'Work with the agents in this swarm side by side.'
+ : text.isEmpty
+ ? 'No recent output available.'
+ : text,
style: TextStyle(
fontFamily: text.isEmpty
? grid.AppFont.sans
@@ -624,9 +670,11 @@ class _OutputPreview extends StatelessWidget {
fontFamilyFallback: text.isEmpty
? grid.AppFont.sansFallback
: grid.AppFont.monoFallback,
- fontSize: 11,
- height: 1.45,
- color: text.isEmpty ? Colors.white70 : Colors.white,
+ fontSize: 12,
+ height: 1.65,
+ color: text.isEmpty
+ ? Colors.white60
+ : Colors.white.withValues(alpha: .85),
),
),
),
diff --git a/desktop/lib/widgets/swarm_welcome.dart b/desktop/lib/widgets/swarm_welcome.dart
index 59b053872..587add8fa 100644
--- a/desktop/lib/widgets/swarm_welcome.dart
+++ b/desktop/lib/widgets/swarm_welcome.dart
@@ -8,6 +8,7 @@ import '../shared/widgets/skeleton.dart';
import '../state/app_state.dart';
import '../state/swarm_catalog.dart';
import 'engine_identity.dart';
+import 'swarm_icon.dart';
class SwarmWelcome extends StatelessWidget {
const SwarmWelcome({
@@ -208,7 +209,6 @@ class SwarmWelcome extends StatelessWidget {
for (final machine
in app.machineStates.values)
_StarterRow(
- icon: Icons.computer_outlined,
name: machine.machine.displayName,
note: machine.needsLink
? 'Link required'
@@ -239,7 +239,6 @@ class SwarmWelcome extends StatelessWidget {
[
for (final group in groups)
_StarterRow(
- icon: Icons.folder_outlined,
name: group.name,
count: group.agents.length,
onTap: () => onProject(group),
@@ -337,11 +336,7 @@ class _FirstAgentGuide extends StatelessWidget {
const SizedBox(height: 16),
for (final (number, title, detail) in const [
('1', 'Choose a folder', 'Use a project you already work on.'),
- (
- '2',
- 'Pick your agent',
- 'Claude Code, Codex, or another coding agent.',
- ),
+ ('2', 'Pick your agent', 'Claude Code, Codex, or another agent.'),
(
'3',
'Start working',
@@ -510,14 +505,12 @@ class _SwarmSearchFieldState extends State<SwarmSearchField> {
class _StarterRow extends StatelessWidget {
const _StarterRow({
- required this.icon,
required this.name,
required this.count,
required this.onTap,
this.note,
this.onManage,
});
- final IconData icon;
final String name;
final int count;
final VoidCallback onTap;
@@ -533,7 +526,7 @@ class _StarterRow extends StatelessWidget {
padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 14),
child: Row(
children: [
- Icon(icon, size: 17, color: Colors.white60),
+ const SwarmIcon(size: 19, color: Colors.white60),
const SizedBox(width: 11),
Expanded(
child: Text(
diff --git a/desktop/lib/widgets/terminal_panel.dart b/desktop/lib/widgets/terminal_panel.dart
index 8708b527c..6a60eff8d 100644
--- a/desktop/lib/widgets/terminal_panel.dart
+++ b/desktop/lib/widgets/terminal_panel.dart
@@ -30,6 +30,7 @@ import '../terminal/terminal_viewport.dart';
import '../shared/theme/app_theme.dart' as grid;
import '../theme/app_theme.dart';
import 'engine_identity.dart';
+import 'pane_actions_menu.dart';
/// The pane header's own horizontal inset.
const double _stripPadding = 14;
@@ -48,6 +49,8 @@ class TerminalPanel extends StatefulWidget {
/// control that changes that. Null where there is no grid to hold a slot in.
final bool pinned;
final VoidCallback? onTogglePin;
+ final VoidCallback? onToggleZoom, onSplitRight, onSplitDown;
+ final bool zoomed;
/// This native terminal took the keyboard, so its grid tile becomes focused.
final VoidCallback? onRendererFocus;
@@ -89,6 +92,10 @@ class TerminalPanel extends StatefulWidget {
this.onClose,
this.pinned = false,
this.onTogglePin,
+ this.onToggleZoom,
+ this.onSplitRight,
+ this.onSplitDown,
+ this.zoomed = false,
this.onRendererFocus,
this.paneDrag,
this.linkOpener,
@@ -1228,6 +1235,10 @@ class _TerminalPanelState extends State<TerminalPanel>
pinned: widget.pinned,
close: widget.onClose != null,
pin: widget.onTogglePin != null,
+ zoomed: widget.zoomed,
+ zoom: widget.onToggleZoom != null,
+ splitRight: widget.onSplitRight != null,
+ splitDown: widget.onSplitDown != null,
composer: canToggleComposer,
composerVisible: widget.composerVisible,
dragId: widget.paneDrag?.ref.paneId,
@@ -1241,6 +1252,10 @@ class _TerminalPanelState extends State<TerminalPanel>
notice: widget.notice,
readOnly: widget.readOnly,
compact: widget.compactHeader,
+ zoomed: widget.zoomed,
+ onToggleZoom: widget.onToggleZoom,
+ onSplitRight: widget.onSplitRight,
+ onSplitDown: widget.onSplitDown,
onClose: widget.onClose == null ? null : () => widget.onClose?.call(),
pinned: widget.pinned,
onTogglePin: widget.onTogglePin == null
@@ -1266,6 +1281,8 @@ class _TerminalHeader extends StatelessWidget {
final bool pinned;
final bool compact;
final VoidCallback? onTogglePin;
+ final VoidCallback? onToggleZoom, onSplitRight, onSplitDown;
+ final bool zoomed;
final VoidCallback? onToggleComposer;
final bool composerVisible;
@@ -1288,6 +1305,10 @@ class _TerminalHeader extends StatelessWidget {
this.pinned = false,
this.compact = false,
this.onTogglePin,
+ this.onToggleZoom,
+ this.onSplitRight,
+ this.onSplitDown,
+ this.zoomed = false,
this.onToggleComposer,
this.composerVisible = false,
this.paneDrag,
@@ -1532,26 +1553,35 @@ class _TerminalHeader extends StatelessWidget {
// memory cannot shift it under their pointer.
if (!compact && onTogglePin != null)
PanePinButton(pinned: pinned, onPressed: onTogglePin!),
- if (compact && onToggleComposer != null)
- IconButton(
- tooltip: composerVisible
- ? 'Hide message composer'
- : 'Show message composer',
- onPressed: onToggleComposer,
- icon: Icon(
- Icons.edit_note,
- size: 18,
- color: composerVisible
- ? AppColors.text
- : AppColors.mutedStrong,
- ),
- constraints: const BoxConstraints.tightFor(
- width: 28,
- height: 28,
+ if (compact) ...[
+ if (onToggleZoom != null)
+ IconButton(
+ tooltip: zoomed
+ ? 'Restore agents'
+ : 'Zoom ${session.agentName}',
+ onPressed: onToggleZoom,
+ icon: Icon(
+ zoomed ? Icons.fullscreen_exit : Icons.fullscreen,
+ size: 18,
+ ),
+ constraints: const BoxConstraints.tightFor(
+ width: 28,
+ height: 28,
+ ),
+ padding: EdgeInsets.zero,
),
- padding: EdgeInsets.zero,
+ PaneActionsMenu(
+ name: session.agentName,
+ onSplitRight: onSplitRight,
+ onSplitDown: onSplitDown,
+ onTogglePin: onTogglePin,
+ pinned: pinned,
+ onToggleComposer: onToggleComposer,
+ composerVisible: composerVisible,
+ onClose: onClose,
),
- if (onClose != null) PaneCloseButton(onPressed: onClose!),
+ ] else if (onClose != null)
+ PaneCloseButton(onPressed: onClose!),
],
),
),
diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swift
index a3759a836..927c4e484 100644
--- a/desktop/macos/Runner/SwarmTitlebar.swift
+++ b/desktop/macos/Runner/SwarmTitlebar.swift
@@ -26,9 +26,6 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
private var subscriptions: [SwarmSubscriptionEntry] = []
private var keymap: HarnessNativeKeymap?
private var flutterKeyContext = "workspace"
- private var searchKeyDispatch: HarnessNativeKeyDispatch?
- private var searchKeyMonitor: Any?
- private var pendingKeyNames: [String] = []
private var tabActionGeneration = 0
init(window: NSWindow, messenger: FlutterBinaryMessenger) {
@@ -39,11 +36,6 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
guard let self else { return }
self.sendTabAction(method, arguments: args)
}
- strip.editingEnded = { [weak self] in
- self?.cancelKeySequence()
- self?.syncMenuKeys()
- }
- strip.editingBegan = { [weak self] in self?.syncMenuKeys() }
channel.setMethodCallHandler { [weak self] call, result in
guard let self else { result(nil); return }
switch call.method {
@@ -54,7 +46,6 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
case "update":
let state = call.arguments as? [String: Any] ?? [:]
self.actionsEnabled = state["enabled"] as? Bool == true
- if !self.actionsEnabled { self.cancelKeySequence() }
self.canReopen = state["canReopen"] as? Bool == true
self.canFind = state["canFind"] as? Bool == true
self.canClosePane = state["canClosePane"] as? Bool == true
@@ -65,17 +56,6 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
self.strip.update(state)
self.window?.backgroundColor = self.strip.palette.tabBar
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.cancelKeySequence()
- self.strip.closeSearch()
- self.syncMenuKeys()
- result(nil)
case "modelsState":
let state = call.arguments as? [String: Any] ?? [:]
self.updateModels(state["subscriptions"] as? [[String: Any]] ?? [])
@@ -104,21 +84,15 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
[weak self] _ in self?.resize()
})
}
- // Keep an in-progress search and its native input owner across app switches.
- // Cancelling on window blur would return the next typed key to an agent.
- observers.append(NotificationCenter.default.addObserver(forName: NSWindow.didResignKeyNotification,
- object: window, queue: .main) { [weak self] _ in self?.cancelKeySequence(suspend: true) })
- observers.append(NotificationCenter.default.addObserver(forName: NSWindow.willCloseNotification,
- object: window, queue: .main) { [weak self] _ in self?.removeKeyMonitor() })
+
}
deinit {
- removeKeyMonitor()
observers.forEach(NotificationCenter.default.removeObserver)
}
private func sendTabAction(_ method: String, arguments: Any?) {
- guard ["select", "close", "new", "rename"].contains(method) else {
+ guard ["select", "close", "new", "rename", "jump", "commands", "notifications", "newAgent", "splitRight", "splitDown", "zoomPane", "pinPane"].contains(method) else {
channel.invokeMethod(method, arguments: arguments)
return
}
@@ -134,79 +108,23 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
}
}
- private func removeKeyMonitor() {
- if let searchKeyMonitor { NSEvent.removeMonitor(searchKeyMonitor) }
- searchKeyMonitor = nil
- cancelKeySequence(suspend: true)
- }
-
- private func cancelKeySequence(suspend: Bool = false) {
- if suspend { searchKeyDispatch?.suspend() }
- else { searchKeyDispatch?.cancel() }
- syncPendingKeys()
- }
-
- private func syncPendingKeys() {
- let names = searchKeyDispatch?.pending.map(\.canonical) ?? []
- guard names != pendingKeyNames else { return }
- pendingKeyNames = names
- channel.invokeMethod("keymapPending", arguments: ["keys": names])
- }
-
private func setKeymap(_ map: HarnessNativeKeymap) {
keymap = map
- if let searchKeyDispatch { searchKeyDispatch.update(map) }
- else { searchKeyDispatch = HarnessNativeKeyDispatch(map) }
- syncPendingKeys()
- strip.searchField.usesKeymap = true
- strip.searchField.shortcutHint = map.hint(for: "navigation.quick_open", context: "workspace")
+ let hint = map.hint(for: "navigation.quick_open", context: "workspace")
+ strip.searchButton.toolTip = hint.map { "Search (\($0))" } ?? "Search"
+ let newHint = map.hint(for: "agent.new", context: "workspace")
+ strip.newAgentButton.toolTip = newHint.map { "New agent (\($0))" } ?? "New agent"
if let main = NSApp.mainMenu, let window {
let menu = main as? HarnessKeymapMenu ?? HarnessKeymapMenu.replacing(main)
if NSApp.mainMenu !== menu { NSApp.mainMenu = menu }
menu.update(map, window: window)
}
syncMenuKeys()
- guard searchKeyMonitor == nil else { return }
- // A local monitor is needed for ordinary letters that follow a custom
- // prefix. NSTextView's command delegate only receives editing commands;
- // it cannot stop a plain sequence suffix before it becomes query text.
- searchKeyMonitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .keyUp, .leftMouseDown, .rightMouseDown]) {
- [weak self] event in
- guard let self else { return event }
- return self.handleSearchKey(event)
- }
- }
-
- private func handleSearchKey(_ event: NSEvent) -> NSEvent? {
- guard let dispatch = searchKeyDispatch else { return event }
- if event.type == .leftMouseDown || event.type == .rightMouseDown {
- cancelKeySequence()
- return event
- }
- guard let window, event.window === window else { return event }
- // Consume the paired release even when a command just moved focus. It
- // must not leak half a keystroke into the newly selected agent.
- if event.type == .keyUp { return dispatch.release(event.keyCode) ? nil : event }
- guard actionsEnabled, strip.searchField.searching,
- let editor = strip.searchField.currentEditor() as? NSTextView,
- window.firstResponder === editor else {
- cancelKeySequence()
- return event
- }
- let result = dispatch.dispatch(HarnessKeyStroke.fromEvent(event), keyCode: event.keyCode,
- repeated: event.isARepeat, composing: editor.hasMarkedText(), context: "picker", owner: editor)
- syncPendingKeys()
- if let command = result.command {
- if command == "navigation.quick_open" { editor.selectAll(nil) }
- else { channel.invokeMethod("keymapCommand", arguments: ["command": command]) }
- }
- return result.handled ? nil : event
}
private func syncMenuKeys() {
guard let keymap, let main = NSApp.mainMenu else { return }
- let context = strip.searchField.currentEditor() == nil ? flutterKeyContext : "picker"
- keymap.applyMenuKeys(to: main, context: context)
+ keymap.applyMenuKeys(to: main, context: flutterKeyContext)
}
private func configure(palette: [String: Any]? = nil) {
@@ -220,7 +138,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
configured = true
NSWindow.allowsAutomaticWindowTabbing = false
window.tabbingMode = .disallowed
- window.title = "Harness V2"
+ window.title = "Harness"
window.titleVisibility = .hidden
window.titlebarAppearsTransparent = true
window.styleMask.remove(.fullSizeContentView)
@@ -240,7 +158,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
resize()
installWorkspaceMenus()
if let keymap { setKeymap(keymap) }
- // An editable accessory must not become the window's initial input owner.
+ // Toolbar controls must not become the window's initial input owner.
window.makeFirstResponder(window.contentViewController)
}
@@ -279,28 +197,36 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
item.submenu = menu
main.insertItem(item, at: index)
}
- let file = NSMenu(title: "File")
- add(file, "New Swarm", "t", "new")
- add(file, "New Agent…", "", "newAgent")
- add(file, "Reopen Last Closed", "t", "reopen", [.command, .shift])
- file.addItem(.separator())
- add(file, "Link Machine…", "", "linkMachine")
- add(file, "Add Project…", "", "addProject")
- file.addItem(.separator())
- add(file, "Rename Swarm…", "r", "renameActive", [.command, .shift])
- add(file, "Remove Agent from Swarm", "w", "closePane", [.command, .shift])
- add(file, "Close Swarm", "w", "closeActive")
- install(file, at: 1)
+ if let file = main.item(withTitle: "File") { main.removeItem(file) }
+ let swarm = NSMenu(title: "Swarm")
+ add(swarm, "New Swarm", "t", "new")
+ add(swarm, "Rename Swarm…", "r", "renameActive", [.command, .shift])
+ add(swarm, "Close Swarm", "w", "closeActive")
+ swarm.addItem(.separator())
+ add(swarm, "Link Machine…", "", "linkMachine")
+ add(swarm, "Add Project…", "", "addProject")
+ install(swarm, at: 1)
+ let agent = NSMenu(title: "Agent")
+ add(agent, "New Agent…", "n", "newAgent")
+ agent.addItem(.separator())
+ add(agent, "Split Right…", "", "splitRight")
+ add(agent, "Split Down…", "", "splitDown")
+ agent.addItem(.separator())
+ add(agent, "Zoom Agent", "", "zoomPane")
+ add(agent, "Pin or Unpin Agent", "", "pinPane")
+ agent.addItem(.separator())
+ add(agent, "Close Agent", "w", "closePane", [.command, .shift])
+ install(agent, at: 2)
rebuildHistoryMenu()
let windowIndex = main.items.firstIndex(where: { $0.title == "Window" }) ?? main.numberOfItems
install(historyMenu, at: windowIndex)
- // Navigation chords remain in Flutter's terminal-safe shortcut table.
- // Search still needs a native owner when the titlebar field has focus.
+ // Native menu hints mirror Flutter; the shared picker owns all editing.
if let edit = main.item(withTitle: "Edit")?.submenu {
edit.addItem(.separator())
- add(edit, "Search Agents, Swarms, Machines and Projects…", "p", "jump")
+ add(edit, "Search Agents and Swarms…", "p", "jump")
+ add(edit, "Search Commands…", "p", "commands", [.command, .shift])
}
if let view = main.item(withTitle: "View")?.submenu {
view.addItem(.separator())
@@ -389,6 +315,12 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
}
command("Back", "[", "historyBack")
command("Forward", "]", "historyForward")
+ let reopen = NSMenuItem(title: "Reopen Last Closed", action: #selector(menuAction(_:)), keyEquivalent: "t")
+ reopen.target = self
+ reopen.representedObject = "reopen"
+ reopen.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "reopen")
+ reopen.keyEquivalentModifierMask = [.command, .shift]
+ historyMenu.addItem(reopen)
historyMenu.addItem(.separator())
appendHistorySection("Recently Closed", entries: Array(closedHistory.prefix(10)), closed: true)
historyMenu.addItem(.separator())
@@ -458,12 +390,12 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {
return actionsEnabled && (action != "reopen" || canReopen) &&
(action != "historyBack" || canGoBack) && (action != "historyForward" || canGoForward) &&
(action != "new" || canCreateSwarm) && (action != "closePane" || canClosePane) &&
- (!["findTerminal", "findNext", "findPrevious"].contains(action) || canFind)
+ (!["findTerminal", "findNext", "findPrevious", "splitRight", "splitDown", "zoomPane", "pinPane"].contains(action) || canFind)
}
@objc private func menuAction(_ sender: NSMenuItem) {
guard validateMenuItem(sender), let action = sender.representedObject as? String else { return }
- channel.invokeMethod(action, arguments: nil)
+ sendTabAction(action, arguments: nil)
}
@objc private func historyAction(_ sender: NSMenuItem) {
@@ -712,152 +644,26 @@ private struct SwarmNativePalette: Equatable {
}
}
-private final class SwarmSearchCell: NSSearchFieldCell {
- override func select(withFrame rect: NSRect, in controlView: NSView, editor: NSText,
- delegate: Any?, start: Int, length: Int) {
- super.select(withFrame: searchTextRect(forBounds: rect), in: controlView,
- editor: editor, delegate: delegate, start: start, length: length)
- }
- override func edit(withFrame rect: NSRect, in controlView: NSView, editor: NSText,
- delegate: Any?, event: NSEvent?) {
- super.edit(withFrame: searchTextRect(forBounds: rect), in: controlView,
- editor: editor, delegate: delegate, event: event)
- }
- override func searchButtonRect(forBounds rect: NSRect) -> NSRect {
- NSRect(x: rect.minX + 12, y: rect.midY - 8, width: 16, height: 16)
- }
- override func cancelButtonRect(forBounds rect: NSRect) -> NSRect {
- NSRect(x: rect.maxX - 28, y: rect.midY - 8, width: 16, height: 16)
- }
- override func searchTextRect(forBounds rect: NSRect) -> NSRect {
- let font = font ?? NSFont.systemFont(ofSize: 13)
- let height = ceil(font.ascender - font.descender + font.leading)
- return NSRect(x: rect.minX + 36, y: rect.midY - height / 2,
- width: max(0, rect.width - 68), height: height)
- }
-}
-
-/// 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 palette = SwarmNativePalette() { didSet { needsDisplay = true } }
- var begin: (() -> Void)?
- var command: ((String) -> Void)?
- var searching = false { didSet { needsDisplay = true } }
- var usesKeymap = false
- var shortcutHint: String? = "⌘P" { didSet { needsDisplay = true } }
- override init(frame: NSRect) {
- super.init(frame: frame)
- cell = SwarmSearchCell(textCell: "")
- font = NSFont.systemFont(ofSize: 13)
- controlSize = .regular
- appearance = NSAppearance(named: .darkAqua)
- isEditable = true
- isSelectable = true
- isBordered = false
- drawsBackground = false
- textColor = NSColor(white: 0.92, alpha: 1)
- placeholderString = "Search…"
- sendsSearchStringImmediately = true
- sendsWholeSearchString = false
- maximumRecents = 0
- searchMenuTemplate = nil
- focusRingType = .none
- if let search = cell as? NSSearchFieldCell {
- search.focusRingType = .none
- search.isScrollable = true
- search.searchButtonCell?.image = NSImage(systemSymbolName: "magnifyingglass", accessibilityDescription: nil)?
- .withSymbolConfiguration(NSImage.SymbolConfiguration(pointSize: 14, weight: .regular))
- }
- }
- required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
- override var mouseDownCanMoveWindow: Bool { false }
- 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 usesKeymap { return super.performKeyEquivalent(with: event) }
- 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 event.charactersIgnoringModifiers == "i" && !editor.hasMarkedText() {
- if !event.isARepeat { command?("preview") }
- 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) -> String? {
- guard !composing else { return nil }
- let modifiers = event?.modifierFlags.intersection([.command, .option, .control, .shift]) ?? []
- if modifiers == .command && event?.charactersIgnoringModifiers == "i" { return "preview" }
- if modifiers == .control {
- switch event?.charactersIgnoringModifiers?.lowercased() {
- case "n", "j": return "next"
- case "p", "k": return "previous"
- case "g": return "close"
- default: break
- }
- }
- 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
- }
- }
+private final class SwarmNotificationButton: NSButton {
+ var hasAttention = false { didSet { needsDisplay = true } }
override func draw(_ dirtyRect: NSRect) {
- let shape = NSBezierPath(roundedRect: bounds, xRadius: searching ? 10 : 16, yRadius: searching ? 10 : 16)
- palette.search.setFill()
- shape.fill()
- if searching {
- // The strip continues the square bottom edge down to the result list.
- NSRect(x: 0, y: isFlipped ? bounds.midY : 0,
- width: bounds.width, height: bounds.height / 2).fill()
- } else {
- NSColor(white: 1, alpha: 0.16).setStroke()
- let rim = NSBezierPath(roundedRect: bounds.insetBy(dx: 0.5, dy: 0.5), xRadius: 16, yRadius: 16)
- rim.lineWidth = 1
- rim.stroke()
- }
super.draw(dirtyRect)
- if !searching && stringValue.isEmpty && bounds.width >= 140, let shortcutHint,
- !shortcutHint.isEmpty {
- let shortcut = shortcutHint as NSString
- let attrs: [NSAttributedString.Key: Any] = [.font: NSFont.systemFont(ofSize: 11),
- .foregroundColor: NSColor.secondaryLabelColor]
- let size = shortcut.size(withAttributes: attrs)
- guard size.width <= bounds.width * 0.4 else { return }
- shortcut.draw(at: NSPoint(x: bounds.width - size.width - 12,
- y: (bounds.height - size.height) / 2), withAttributes: attrs)
+ if hasAttention {
+ NSColor.systemOrange.setFill()
+ NSBezierPath(ovalIn: NSRect(x: bounds.midX + 4, y: bounds.midY + 5, width: 5, height: 5)).fill()
}
}
}
-private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
+private final class SwarmTabStrip: NSView {
private(set) var palette = SwarmNativePalette()
var emit: ((String, Any?) -> Void)?
- var editingEnded: (() -> Void)?
- var editingBegan: (() -> Void)?
private let scroll = NSScrollView()
private let document = NSView()
private let newButton = NSButton()
- fileprivate let searchField = SwarmSearchField()
- private var lastSearchWidth: CGFloat = 0
+ fileprivate let searchButton = NSButton()
+ fileprivate let newAgentButton = NSButton()
+ fileprivate let notificationButton = SwarmNotificationButton()
private var tabs: [SwarmTabButton] = []
private var activeId = ""
private var revealActiveAfterLayout = false
@@ -877,6 +683,8 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
button.image = NSImage(systemSymbolName: symbol, accessibilityDescription: label)
button.symbolConfiguration = NSImage.SymbolConfiguration(pointSize: 13, weight: .regular)
button.isBordered = false
+ button.title = ""
+ button.imagePosition = .imageOnly
button.contentTintColor = palette.accent
button.target = self
button.action = action
@@ -886,13 +694,14 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
}
button(newButton, "plus", "New swarm (⌘T)", #selector(newSwarm))
newButton.isEnabled = false
- searchField.delegate = self
- searchField.isEnabled = false
- 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)
+ button(searchButton, "magnifyingglass", "Search (⌘P)", #selector(openSearch))
+ button(newAgentButton, "plus", "New agent (⌘N)", #selector(newAgent))
+ newAgentButton.imagePosition = .imageOnly
+ newAgentButton.setAccessibilityLabel("New agent")
+ newAgentButton.isEnabled = false
+ button(notificationButton, "bell", "Notifications", #selector(openNotifications))
+ searchButton.isEnabled = false
+ notificationButton.isEnabled = false
registerForDraggedTypes([swarmPasteboardType])
}
required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }
@@ -901,7 +710,9 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
let nextPalette = SwarmNativePalette(values)
guard nextPalette != palette else { return }
palette = nextPalette
- searchField.palette = palette
+ searchButton.contentTintColor = palette.accent
+ newAgentButton.contentTintColor = palette.accent
+ notificationButton.contentTintColor = palette.accent
newButton.contentTintColor = palette.accent
for tab in tabs { tab.palette = palette }
needsDisplay = true
@@ -942,8 +753,13 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
// Moving frames alone leaves AppKit's child traversal in insertion order.
document.setAccessibilityChildren(tabs)
newButton.isEnabled = actionsEnabled && tabs.count < 24
- searchField.isEnabled = actionsEnabled
- if !actionsEnabled { closeSearch() }
+ searchButton.isEnabled = actionsEnabled
+ newAgentButton.isEnabled = actionsEnabled
+ notificationButton.isEnabled = actionsEnabled
+ let attention = state["attention"] as? Int ?? 0
+ notificationButton.hasAttention = attention > 0
+ notificationButton.toolTip = attention > 0 ? "\(attention) agents need input" : "Notifications"
+ notificationButton.setAccessibilityLabel(notificationButton.toolTip)
needsLayout = true
layoutSubtreeIfNeeded()
if ids != previousOrder {
@@ -965,10 +781,7 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
let activeWasVisible = active.map { scroll.documentVisibleRect.intersects($0.frame) } ?? false
let previousScrollSize = scroll.frame.size
let previousDocumentSize = document.frame.size
- 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 available = max(132, bounds.width - 164)
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)
@@ -979,11 +792,9 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
}
let buttonY = (bounds.height - 28) / 2
newButton.frame = NSRect(x: occupied + 4, y: buttonY, width: 28, height: 28)
- searchField.frame = NSRect(x: bounds.width - searchWidth - 8, y: (bounds.height - 32) / 2, width: searchWidth, height: 32)
- if searchField.searching && searchWidth != lastSearchWidth {
- lastSearchWidth = searchWidth
- emit?("searchGeometry", ["width": searchWidth])
- }
+ searchButton.frame = NSRect(x: bounds.width - 120, y: buttonY, width: 28, height: 28)
+ newAgentButton.frame = NSRect(x: bounds.width - 80, y: buttonY, width: 28, height: 28)
+ notificationButton.frame = NSRect(x: bounds.width - 40, y: buttonY, width: 28, height: 28)
let geometryChanged = scroll.frame.size != previousScrollSize || document.frame.size != previousDocumentSize
if let active, revealActiveAfterLayout || (activeWasVisible && (geometryChanged || tabOrderChanged)) {
document.scrollToVisible(active.frame)
@@ -996,11 +807,7 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
// rather than the rounded bottom of a separate pill.
palette.workspace.setFill()
NSRect(x: 0, y: 0, width: bounds.width, height: 1).fill()
- if searchField.searching {
- palette.search.setFill()
- NSRect(x: searchField.frame.minX, y: 0, width: searchField.frame.width,
- height: searchField.frame.minY + 1).fill()
- }
+
}
override func mouseDown(with event: NSEvent) {
if event.clickCount == 2 { window?.performZoom(nil) }
@@ -1009,61 +816,18 @@ private final class SwarmTabStrip: NSView, NSSearchFieldDelegate {
@objc private func newSwarm() {
if actionsEnabled && newButton.isEnabled { emit?("new", nil) }
}
- private func beginSearch() {
- guard actionsEnabled, !searchField.searching else { return }
- searchField.searching = true
- needsDisplay = true
- needsLayout = true
- layoutSubtreeIfNeeded()
- emit?("searchBegin", ["width": searchField.frame.width])
+ @objc private func openSearch() {
+ if actionsEnabled { emit?("jump", nil) }
}
- 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) }
+ @objc private func openNotifications() {
+ if actionsEnabled { emit?("notifications", 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…"
- }
- func closeSearch() {
- guard searchField.searching else { return }
- searchField.searching = false
- needsDisplay = true
- 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 controlTextDidChange(_ notification: Notification) {
- guard searchField.searching else { return }
- emit?("searchChanged", ["query": searchField.stringValue])
- }
- func controlTextDidEndEditing(_ notification: Notification) { editingEnded?() }
- func controlTextDidBeginEditing(_ notification: Notification) { editingBegan?() }
- func control(_ control: NSControl, textView: NSTextView, doCommandBy selector: Selector) -> Bool {
- if searchField.usesKeymap { return false }
- let event = NSApp.currentEvent
- guard let action = SwarmSearchField.resultCommand(NSStringFromSelector(selector), event: event,
- composing: textView.hasMarkedText()) else { return false }
- if event?.isARepeat != true || !["submit", "add", "close", "preview"].contains(action) {
- emit?("searchCommand", ["command": action])
- }
- return true
+
+ @objc private func newAgent() {
+ guard actionsEnabled else { return }
+ emit?("newAgent", nil)
}
+
private func draggedTab(_ sender: NSDraggingInfo) -> SwarmTabButton? {
guard actionsEnabled, sender.draggingSourceOperationMask.contains(.move),
let source = sender.draggingSource as? SwarmTabButton,
diff --git a/desktop/test/app_menu_test.dart b/desktop/test/app_menu_test.dart
index 653050393..27b24d3c8 100644
--- a/desktop/test/app_menu_test.dart
+++ b/desktop/test/app_menu_test.dart
@@ -1,3 +1,5 @@
+import 'swarm_interactions_test.dart' show chord;
+
import 'dart:async';
import 'package:flutter/material.dart';
@@ -100,7 +102,7 @@ void main() {
testWidgets('app menu dialogs do not open over Settings', (tester) async {
final app = createApp();
await _mount(tester, app);
- await tester.tap(find.byTooltip('Settings ⌘,'));
+ await chord(tester, LogicalKeyboardKey.comma);
await tester.pump();
await tester.pump(const Duration(milliseconds: 300));
expect(find.byType(SettingsScreen), findsOneWidget);
diff --git a/desktop/test/boot_flow_widget_test.dart b/desktop/test/boot_flow_widget_test.dart
index 0a66d4da7..e9a8c62b7 100644
--- a/desktop/test/boot_flow_widget_test.dart
+++ b/desktop/test/boot_flow_widget_test.dart
@@ -1,3 +1,7 @@
+import 'swarm_interactions_test.dart' show chord;
+
+import 'package:flutter/services.dart';
+
import 'dart:async';
import 'package:harness/auth/auth_session.dart';
@@ -850,7 +854,7 @@ void main() {
),
);
await tester.pumpAndSettle();
- await tester.tap(find.byTooltip(RegExp(r'^Settings')));
+ await chord(tester, LogicalKeyboardKey.comma);
await tester.pumpAndSettle();
await tester.tap(find.text('Account'));
await tester.pumpAndSettle();
diff --git a/desktop/test/first_workspace_test.dart b/desktop/test/first_workspace_test.dart
index 591daca43..c1413ea99 100644
--- a/desktop/test/first_workspace_test.dart
+++ b/desktop/test/first_workspace_test.dart
@@ -16,6 +16,8 @@ import 'package:xterm/xterm.dart';
import 'swarm_screen_test.dart' show mount, terminal;
import 'swarm_interactions_test.dart' show chord;
+import 'keymap_host_test.dart' show MemoryKeymap;
+import 'keymap_runtime_test.dart' as runtime;
class _FirstUseApp extends AppNotifier {
_FirstUseApp()
@@ -155,6 +157,93 @@ void main() {
},
);
+ for (final native in [false, true]) {
+ testWidgets(
+ 'new agent toolbar ${native ? 'native' : 'Flutter'} action inherits the focused working folder',
+ (tester) async {
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ const MethodChannel('harness/swarm_tabs'),
+ (_) async => null,
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ const MethodChannel('harness/swarm_tabs'),
+ null,
+ ),
+ );
+ final app = _FirstUseApp();
+ final map = MemoryKeymap();
+ app.machineStates['m']!.engines.replace(const [
+ EngineAvailability(engine: 'codex', installed: true),
+ ]);
+ app.machineStates['m']!.agents = const [
+ Agent(
+ id: 'existing',
+ name: 'Existing work',
+ engine: 'codex',
+ terminalAvailable: true,
+ project: AgentProject(name: 'Workspace', cwd: '/work/existing'),
+ ),
+ ];
+ final pane = app.adoptSessionForTest(terminal('existing', app.input));
+ await runtime.mount(tester, app, map, native: native);
+ if (native) {
+ final opening = runtime.native(tester, 'newAgent');
+ await tester.pump();
+ await opening;
+ } else {
+ final search = find.byKey(const ValueKey('swarm-search-button'));
+ final add = find.byKey(const ValueKey('swarm-new-agent-button'));
+ final bell = find.byKey(const ValueKey('swarm-notifications-button'));
+ expect(
+ tester.getRect(search).right,
+ lessThanOrEqualTo(tester.getRect(add).left),
+ );
+ expect(
+ tester.getRect(add).right,
+ lessThanOrEqualTo(tester.getRect(bell).left),
+ );
+ await tester.tap(add);
+ await tester.pump();
+ }
+ expect(find.byType(AlertDialog), findsOneWidget);
+ expect(find.text('/work/existing'), findsOneWidget);
+ expect(
+ tester
+ .widget<AppSelectField<String>>(
+ find.byKey(const Key('new-agent-machine-field')),
+ )
+ .value,
+ 'm',
+ );
+ expect(
+ tester
+ .widget<AppSelectField<String>>(
+ find.byKey(const Key('new-agent-engine-field')),
+ )
+ .value,
+ 'codex',
+ );
+ expect(app.panes, [pane]);
+ expect(app.launches, isEmpty);
+ expect(app.input, isEmpty);
+ await tester.tap(find.text('Cancel'));
+ await tester.pump();
+ expect(find.byType(AlertDialog), findsNothing);
+ expect(
+ tester
+ .widget<TerminalView>(find.byType(TerminalView))
+ .focusNode!
+ .hasFocus,
+ isTrue,
+ );
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ },
+ );
+ }
+
testWidgets(
'new agent is keyboard accessible without hidden focus stops',
(tester) async {
@@ -185,6 +274,13 @@ void main() {
expect(fieldFocused('new-agent-machine-field'), isTrue);
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pump();
+ expect(
+ Focus.of(tester.element(find.text('Clone repository…')))
+ .hasPrimaryFocus,
+ isTrue,
+ );
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
final folder = tester.widget<InkWell>(
find.byKey(const Key('new-agent-folder')),
);
@@ -199,6 +295,21 @@ void main() {
expect(folder.focusNode!.hasPrimaryFocus, isTrue);
expect(find.text('/work/my-project'), findsOneWidget);
+ for (final id in ['codex', 'claude', 'cursor']) {
+ await tester.sendKeyEvent(LogicalKeyboardKey.tab);
+ await tester.pump();
+ expect(
+ Focus.of(
+ tester.element(
+ find.descendant(
+ of: find.byKey(ValueKey('new-agent-quick-$id')),
+ matching: find.byType(Text),
+ ),
+ ),
+ ).hasPrimaryFocus,
+ isTrue,
+ );
+ }
await tester.sendKeyEvent(LogicalKeyboardKey.tab);
await tester.pump();
expect(fieldFocused('new-agent-engine-field'), isTrue);
@@ -280,8 +391,8 @@ void main() {
expect(engine.value, 'codex');
expect(machine.value, 'm');
expect(
- tester.getTopLeft(find.text('Project folder')).dy,
- lessThan(tester.getTopLeft(find.text('Coding agent')).dy),
+ tester.getTopLeft(find.text('Working folder')).dy,
+ lessThan(tester.getTopLeft(find.text('Agent')).dy),
);
expect(picker.opened, 1);
expect(app.probes, 1);
@@ -435,9 +546,9 @@ void main() {
await chord(tester, LogicalKeyboardKey.keyN);
await tester.pump();
if (chooseExplicitly) {
- await tester.tap(find.byKey(const Key('new-agent-engine-field')));
- await tester.pump();
- await tester.tap(find.text('Cursor'));
+ await tester.tap(
+ find.byKey(const ValueKey('new-agent-quick-cursor')),
+ );
await tester.pump();
}
app.machineStates['m']!.engines.replace(const [
diff --git a/desktop/test/keymap_host_test.dart b/desktop/test/keymap_host_test.dart
index a27b41fa9..01d12a934 100644
--- a/desktop/test/keymap_host_test.dart
+++ b/desktop/test/keymap_host_test.dart
@@ -63,7 +63,7 @@ void main() {
('cmd+l', 'pane.focus_right'),
('cmd+left', 'pane.focus_left'),
('cmd+enter', 'pane.zoom'),
- ('cmd+shift+p', 'pane.pin'),
+ ('cmd+shift+p', 'navigation.commands'),
('cmd+s', 'pane.layout'),
('cmd+b', 'task.route'),
('cmd+r', 'machines.refresh'),
diff --git a/desktop/test/keymap_runtime_test.dart b/desktop/test/keymap_runtime_test.dart
index 9682f4bfb..655e3abe3 100644
--- a/desktop/test/keymap_runtime_test.dart
+++ b/desktop/test/keymap_runtime_test.dart
@@ -158,11 +158,11 @@ void main() {
expect(search.cursor, (initial - 1) % search.rows.length);
await tester.enterText(input, 'Agent 0');
await tester.pump();
- expect(find.byTooltip('Preview recent output (⌃I)'), findsOneWidget);
+ expect(find.byTooltip('Hide preview (⌃I)'), findsOneWidget);
await key(tester, LogicalKeyboardKey.keyI, cmd: true);
- expect(search.previewEnabled, isFalse);
- await key(tester, LogicalKeyboardKey.keyI, ctrl: true);
expect(search.previewEnabled, isTrue);
+ await key(tester, LogicalKeyboardKey.keyI, ctrl: true);
+ expect(search.previewEnabled, isFalse);
await key(tester, LogicalKeyboardKey.enter);
expect(find.byType(SwarmSearchResults), findsOneWidget);
expect(frames, isEmpty);
@@ -222,13 +222,7 @@ void main() {
.search;
expect(search.isCommandMode, isTrue);
expect(tester.widget<TextField>(field).controller!.text, '> ');
- expect(
- tester
- .widget<TextField>(find.byKey(const ValueKey('swarm-search-input')))
- .controller!
- .text,
- isEmpty,
- );
+ expect(find.byKey(const ValueKey('swarm-search-input')), findsNothing);
expect(app.panes, isEmpty);
await tester.pumpWidget(const SizedBox());
app.dispose();
@@ -237,7 +231,7 @@ void main() {
);
testWidgets(
- 'native typing sends only changed hints and never echoes a query during refresh',
+ 'native buttons leave all search editing in Flutter during refresh',
(tester) async {
final calls = <MethodCall>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
@@ -261,8 +255,9 @@ void main() {
});
await tester.pump();
calls.clear();
+ final field = find.byKey(const ValueKey('swarm-search-input'));
for (final query in ['w', 'wo', 'wor', 'work', 'work 木']) {
- await native(tester, 'searchChanged', {'query': query});
+ await tester.enterText(field, query);
app.renameSwarm(app.activeSwarmId, 'Background $query');
}
await tester.pump();
@@ -273,7 +268,7 @@ void main() {
'Typing and discovery do not need a reverse-channel field update',
);
for (final query in ['>', '> s', '> se', '> set']) {
- await native(tester, 'searchChanged', {'query': query});
+ await tester.enterText(field, query);
app.renameSwarm(app.activeSwarmId, 'Background $query');
}
map.apply(
@@ -285,11 +280,9 @@ void main() {
.where((c) => c.method == 'searchState')
.map((c) => c.arguments)
.toList(),
- [
- {'hint': 'Search commands…'},
- ],
+ isEmpty,
);
- await native(tester, 'searchChanged', {'query': 'Agent'});
+ await tester.enterText(field, 'Agent');
await tester.pump();
calls.clear();
await native(tester, 'keymapCommand', {'command': 'navigation.commands'});
@@ -299,10 +292,13 @@ void main() {
.where((c) => c.method == 'searchState')
.map((c) => c.arguments)
.toList(),
- [
- {'query': '> ', 'hint': 'Search commands…'},
- ],
- reason: 'Deliberate commands still update the native query and hint',
+ isEmpty,
+ reason: 'Native chrome never mirrors the Flutter query',
+ );
+ expect(tester.widget<TextField>(field).controller!.text, '> ');
+ expect(
+ tester.widget<TextField>(field).decoration!.hintText,
+ 'Search commands…',
);
await native(tester, 'keymapCommand', {'command': 'picker.cancel'});
await tester.pump();
@@ -357,7 +353,7 @@ void main() {
);
testWidgets(
- 'native field commands and snapshots use the same configured workspace actions',
+ 'native commands and snapshots use the same configured workspace actions',
(tester) async {
final calls = <MethodCall>[];
tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
@@ -401,8 +397,14 @@ void main() {
'command': 'navigation.quick_open',
});
await tester.pump();
- await native(tester, 'searchChanged', {'query': 'Agent 0'});
+ await tester.enterText(
+ find.byKey(const ValueKey('swarm-search-input')),
+ 'Agent 0',
+ );
+ await tester.pump();
+ await native(tester, 'keymapCommand', {'command': 'picker.preview'});
await tester.pump();
+ expect(find.byKey(const ValueKey('swarm-search-preview')), findsNothing);
await native(tester, 'keymapCommand', {'command': 'picker.preview'});
await tester.pump();
expect(
diff --git a/desktop/test/search_workspace_test.dart b/desktop/test/search_workspace_test.dart
new file mode 100644
index 000000000..a5649e75a
--- /dev/null
+++ b/desktop/test/search_workspace_test.dart
@@ -0,0 +1,97 @@
+import 'package:flutter/foundation.dart';
+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/widgets/swarm_icon.dart';
+import 'package:harness/widgets/swarm_search_input.dart';
+
+import 'keymap_host_test.dart' show MemoryKeymap, key;
+import 'keymap_runtime_test.dart' show mount;
+import 'swarm_screen_test.dart' show terminal;
+import 'swarm_state_test.dart' show createApp;
+
+void main() {
+ for (final native in [false, true]) {
+ testWidgets(
+ 'shared ${native ? 'native-button' : 'Flutter-button'} picker owns arrows, select-all, delete and command mode',
+ (tester) async {
+ debugDefaultTargetPlatformOverride = TargetPlatform.macOS;
+ addTearDown(() => debugDefaultTargetPlatformOverride = null);
+ tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ const MethodChannel('harness/swarm_tabs'),
+ (_) async => null,
+ );
+ addTearDown(
+ () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler(
+ const MethodChannel('harness/swarm_tabs'),
+ null,
+ ),
+ );
+ final map = MemoryKeymap();
+ final app = createApp();
+ app.machineStates['m']!.nodeOnline = true;
+ final input = <TerminalBinaryFrame>[];
+ final session = terminal('a0', input)
+ ..terminal.write('Reviewing the implementation\r\nAll checks passed');
+ app.adoptSessionForTest(session);
+ await mount(tester, app, map, native: native);
+ final field = find.byKey(const ValueKey('swarm-search-input'));
+ expect(field, findsNothing);
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ await tester.pump();
+ expect(field, findsOneWidget);
+ expect(find.byType(SwarmSearchInput), findsOneWidget);
+ final controller = tester.widget<TextField>(field).controller!;
+ final focus = tester.widget<TextField>(field).focusNode!;
+ expect(focus.hasFocus, isTrue);
+ final selected = find.byWidgetPredicate(
+ (w) => w is ListTile && w.selected,
+ );
+ final first = tester.widget<ListTile>(selected).key;
+ await key(tester, LogicalKeyboardKey.arrowDown);
+ expect(tester.widget<ListTile>(selected).key, isNot(first));
+ await key(tester, LogicalKeyboardKey.arrowUp);
+ expect(tester.widget<ListTile>(selected).key, first);
+ await tester.enterText(field, 'Agent 0');
+ await tester.pump();
+ final results = tester.getRect(
+ find.byKey(const ValueKey('swarm-search-result-list')),
+ );
+ final preview = tester.getRect(
+ find.byKey(const ValueKey('swarm-search-preview')),
+ );
+ expect(preview.left, greaterThanOrEqualTo(results.right));
+ expect(preview.top, results.top);
+ expect(find.textContaining('All checks passed'), findsOneWidget);
+ await key(tester, LogicalKeyboardKey.keyA, cmd: true);
+ expect(controller.selection.textInside(controller.text), 'Agent 0');
+ await key(tester, LogicalKeyboardKey.backspace);
+ expect(controller.text, isEmpty);
+ await tester.enterText(field, 'Agent 1');
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true);
+ expect(controller.selection.textInside(controller.text), 'Agent 1');
+ await key(tester, LogicalKeyboardKey.keyP, cmd: true, shift: true);
+ expect(controller.text, '> ');
+ expect(find.text('Search commands…'), findsOneWidget);
+ expect(
+ find.byKey(const ValueKey('swarm-search-preview')),
+ findsNothing,
+ );
+ expect(app.activeSwarm.pinnedSlots, isEmpty);
+ await key(tester, LogicalKeyboardKey.keyA, cmd: true);
+ await key(tester, LogicalKeyboardKey.backspace);
+ expect(controller.text, isEmpty);
+ expect(find.byType(SwarmIcon), findsWidgets);
+ expect(focus.hasFocus, isTrue);
+ expect(input, isEmpty);
+ await key(tester, LogicalKeyboardKey.escape);
+ expect(field, findsNothing);
+ await tester.pumpWidget(const SizedBox());
+ app.dispose();
+ map.dispose();
+ debugDefaultTargetPlatformOverride = null;
+ },
+ );
+ }
+}
diff --git a/desktop/test/swarm_commands_test.dart b/desktop/test/swarm_commands_test.dart
index 6c6915686..05c5f7d65 100644
--- a/desktop/test/swarm_commands_test.dart
+++ b/desktop/test/swarm_commands_test.dart
@@ -73,7 +73,7 @@ void main() {
await tester.enterText(input, '> pin');
await tester.pump();
expect(find.text('⌘⇧P'), findsNothing);
- expect(find.text('⇧⌘P'), findsOneWidget);
+ expect(find.text('⇧⌘P'), findsNothing);
expect(find.text('Add to this swarm'), findsNothing);
expect(find.byKey(const ValueKey('command:pane.pin')), findsOneWidget);
expect(app.isPanePinned(pane), isFalse);
@@ -90,8 +90,14 @@ void main() {
.hasFocus,
isTrue,
);
- // The existing key still toggles pin; > commands did not steal it.
+ // The approved command shortcut opens command mode and leaves pinning alone.
await chord(tester, LogicalKeyboardKey.keyP, shift: true);
+ expect(app.isPanePinned(pane), isTrue);
+ expect(tester.widget<TextField>(input).controller!.text, '> ');
+ await tester.enterText(input, '> unpin');
+ await tester.pump();
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
+ await tester.pump();
expect(app.isPanePinned(pane), isFalse);
expect(frames, isEmpty);
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/swarm_history_test.dart b/desktop/test/swarm_history_test.dart
index 42eb89341..1652f59ee 100644
--- a/desktop/test/swarm_history_test.dart
+++ b/desktop/test/swarm_history_test.dart
@@ -317,41 +317,33 @@ void main() {
await tester.pump();
await settings;
- // Native Command-P focuses the native input; Flutter only paints its results.
+ // Native search opens the same centered Flutter editor and preview.
final jumping = native('jump');
await tester.pump();
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});
+ final field = find.byKey(const ValueKey('swarm-search-input'));
+ expect(field, findsOneWidget);
+ await tester.enterText(field, 'Agent 1');
await tester.pump();
+ expect(tester.widget<TextField>(field).focusNode!.hasFocus, isTrue);
+ expect(fieldUpdates, isEmpty, reason: 'Queries stay in Flutter');
+ final picker = tester.getRect(
+ find.byKey(const ValueKey('swarm-search-results')),
+ );
+ expect(picker.width, greaterThan(600));
expect(
- tester
- .getSize(find.byKey(const ValueKey('swarm-search-results')))
- .width,
- 480,
+ picker.center.dx,
+ tester.view.physicalSize.width / tester.view.devicePixelRatio / 2,
);
- await native('searchCommand', {'command': 'preview'});
- await tester.pump();
expect(
find.byKey(const ValueKey('swarm-search-preview')),
findsOneWidget,
);
- expect(
- fieldUpdates.every((state) => !state.containsKey('query')),
- isTrue,
- );
expect(otherInput, isEmpty);
- await native('searchCommand', {'command': 'submit'});
+ await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
await jumping;
expect(app.focusedPaneId, second.id);
diff --git a/desktop/test/swarm_inline_search_test.dart b/desktop/test/swarm_inline_search_test.dart
index 934c34509..bef56a0ad 100644
--- a/desktop/test/swarm_inline_search_test.dart
+++ b/desktop/test/swarm_inline_search_test.dart
@@ -152,7 +152,7 @@ void main() {
await tester.enterText(_input, 'Agent 12');
await tester.pump();
expect(tester.widget<TextField>(_input).focusNode!.hasFocus, isTrue);
- expect(tester.widget<TextField>(top).controller!.text, isEmpty);
+ expect(top, findsNothing);
expect(find.byKey(const ValueKey('swarm-search-results')), findsNothing);
expect(find.widgetWithText(ListTile, 'Agent 12'), findsOneWidget);
final results = tester.getRect(_results);
diff --git a/desktop/test/swarm_interactions_test.dart b/desktop/test/swarm_interactions_test.dart
index 2a1ab34eb..00ce804ad 100644
--- a/desktop/test/swarm_interactions_test.dart
+++ b/desktop/test/swarm_interactions_test.dart
@@ -129,10 +129,14 @@ void main() {
app.adoptSessionForTest(terminal('a0', []));
await mount(tester, app);
expect(find.byType(TerminalComposer), findsNothing);
- await tester.tap(find.byTooltip('Show message composer'));
+ await tester.tap(find.byTooltip('Actions for Session a0'));
+ await tester.pump();
+ await tester.tap(find.text('Show message composer'));
await tester.pump();
expect(find.byType(TerminalComposer), findsOneWidget);
- await tester.tap(find.byTooltip('Hide message composer'));
+ await tester.tap(find.byTooltip('Actions for Session a0'));
+ await tester.pump();
+ await tester.tap(find.text('Hide message composer'));
await tester.pump();
expect(find.byType(TerminalComposer), findsNothing);
await tester.pumpWidget(const SizedBox());
diff --git a/desktop/test/swarm_screen_test.dart b/desktop/test/swarm_screen_test.dart
index 843c82fd1..6ec457cfe 100644
--- a/desktop/test/swarm_screen_test.dart
+++ b/desktop/test/swarm_screen_test.dart
@@ -77,8 +77,8 @@ void main() {
'/work/existing',
);
await tester.pump();
- expect(find.text('Agent 0'), findsOneWidget);
- expect(find.text('Agent 1'), findsOneWidget);
+ expect(find.widgetWithText(ListTile, 'Agent 0'), findsOneWidget);
+ expect(find.widgetWithText(ListTile, 'Agent 1'), findsOneWidget);
expect(find.text('Agent 2'), findsNothing);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
await tester.pump();
@@ -109,14 +109,14 @@ void main() {
);
await tester.pump();
expect(find.text('Agent 1').last, findsOneWidget);
- await tester.tap(find.text('Agent 1').last);
+ await tester.tap(find.widgetWithText(ListTile, 'Agent 1'));
await tester.pump();
await app.addAgentToSwarm('m', 'a2');
app.toggleZoomPane();
await tester.pump();
final zoom = app.zoomedPaneId;
final before = tester.getSize(find.byType(PaneGrid));
- await tester.tap(find.byKey(const ValueKey('swarm-search-input')));
+ await tester.tap(find.byKey(const ValueKey('swarm-search-button')));
await tester.pump(const Duration(milliseconds: 300));
expect(
find.byKey(const ValueKey('swarm-search-results')),
diff --git a/desktop/test/swarm_search_preview_test.dart b/desktop/test/swarm_search_preview_test.dart
index 94792935f..213fb64c5 100644
--- a/desktop/test/swarm_search_preview_test.dart
+++ b/desktop/test/swarm_search_preview_test.dart
@@ -94,9 +94,19 @@ void main() {
inline ? 'swarm-welcome-search-input' : 'swarm-search-input',
),
);
+ if (!inline) {
+ await tester.tap(find.byKey(const ValueKey('swarm-search-button')));
+ await tester.pump();
+ }
await tester.tap(input);
await tester.enterText(input, 'Agent 0');
await tester.pump();
+ expect(
+ find.byKey(const ValueKey('swarm-search-preview')),
+ findsOneWidget,
+ );
+ await chord(tester, LogicalKeyboardKey.keyI);
+ await tester.pump();
expect(
find.byKey(const ValueKey('swarm-search-preview')),
findsNothing,
diff --git a/desktop/test/swarm_search_test.dart b/desktop/test/swarm_search_test.dart
index 3470e7393..0df9dc287 100644
--- a/desktop/test/swarm_search_test.dart
+++ b/desktop/test/swarm_search_test.dart
@@ -25,9 +25,10 @@ void main() {
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);
+ expect(input, findsNothing);
+ await tester.tap(find.byKey(const ValueKey('swarm-search-button')));
await tester.pump();
+ final originalController = tester.widget<TextField>(input).controller;
await tester.enterText(input, 'a query only');
await tester.pump();
expect(
@@ -273,7 +274,7 @@ void main() {
.take(3)
.toList();
await mount(tester, app);
- await tester.tap(find.byKey(const ValueKey('swarm-search-input')));
+ await tester.tap(find.byKey(const ValueKey('swarm-search-button')));
await tester.pump();
await tester.enterText(jumpField, 'Test host');
await tester.pump();
diff --git a/desktop/test/swarm_switcher_test.dart b/desktop/test/swarm_switcher_test.dart
index 58e3ff232..7b4b745c8 100644
--- a/desktop/test/swarm_switcher_test.dart
+++ b/desktop/test/swarm_switcher_test.dart
@@ -139,8 +139,7 @@ void main() {
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));
+ expect(input, findsNothing);
await tester.sendKeyDownEvent(LogicalKeyboardKey.meta);
await tester.sendKeyEvent(LogicalKeyboardKey.keyP);
await tester.sendKeyUpEvent(LogicalKeyboardKey.meta);
@@ -148,17 +147,20 @@ void main() {
expect(jumpField, findsOneWidget);
final field = tester.widget<TextField>(jumpField);
expect(field.focusNode!.hasFocus, isTrue);
- expect(field.controller, same(controller));
- expect(ModalRoute.of(tester.element(input)), same(route));
+ final controller = field.controller;
final results = tester.getRect(
- find.byKey(const ValueKey('swarm-search-results')),
+ find.byKey(const ValueKey('swarm-search-result-list')),
);
final bar = tester.getRect(input);
expect(results.top, inInclusiveRange(bar.bottom, bar.bottom + 12));
- expect(results.right, closeTo(bar.right, 0.1));
+ final picker = tester.getRect(
+ find.byKey(const ValueKey('swarm-search-results')),
+ );
+ expect(picker.center.dx, closeTo(1280 / 2, 0.1));
expect(find.byType(TextField), findsOneWidget);
expect(find.byType(BackdropFilter), findsNothing);
await chord(tester, LogicalKeyboardKey.keyP);
+ expect(tester.widget<TextField>(input).controller, same(controller));
expect(
find.byKey(const ValueKey('swarm-search-results')),
findsOneWidget,
@@ -175,7 +177,7 @@ void main() {
expect(app.panes, membership);
await chord(tester, LogicalKeyboardKey.keyF, shift: true);
expect(find.byType(Dialog), findsNothing);
- await tester.tap(find.byKey(const ValueKey('swarm-search-input')));
+ await tester.tap(find.byKey(const ValueKey('swarm-search-button')));
await tester.pump();
expect(jumpField, findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.escape);
@@ -271,7 +273,7 @@ void main() {
await tester.pump();
await tester.pump();
expect(tester.widget<ListTile>(selectedRow).key, ValueKey(selectedId));
- expect(find.textContaining('Opens in'), findsOneWidget);
+ expect(find.text('Go to agent'), findsOneWidget);
await tester.sendKeyEvent(LogicalKeyboardKey.enter);
await tester.pump();
expect(app.panes, hasLength(2));
diff --git a/desktop/test/terminal_panel_presentation_test.dart b/desktop/test/terminal_panel_presentation_test.dart
index a54de682a..91e978da2 100644
--- a/desktop/test/terminal_panel_presentation_test.dart
+++ b/desktop/test/terminal_panel_presentation_test.dart
@@ -35,7 +35,10 @@ void main() {
await tester.pump();
revision.value = 1;
await tester.pump();
- await tester.tap(find.byTooltip('Close pane'));
+ await tester.tap(find.byTooltip('Actions for ${session.agentName}'));
+ await tester.pump();
+ await tester.tap(find.text('Close agent'));
+ await tester.pump();
expect(closed, [1]);
session.agentName = 'Renamed terminal';
app.machineStates['m']!.agents = [
diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swift
index c805dad44..73a533615 100644
--- a/desktop/tool/swarm_titlebar_checks.swift
+++ b/desktop/tool/swarm_titlebar_checks.swift
@@ -37,10 +37,10 @@ private extension SwarmTabButton {
private extension SwarmTabStrip {
func checkStartupPalette(_ expected: SwarmNativePalette) throws {
- try checkTitlebar(palette == expected && searchField.palette == expected &&
+ try checkTitlebar(palette == expected && searchButton.contentTintColor == expected.accent && notificationButton.contentTintColor == expected.accent &&
newButton.contentTintColor == expected.accent,
"Initial search and new-swarm colors use the saved palette")
- try checkTitlebar(tabs.isEmpty && !actionsEnabled && !newButton.isEnabled && !searchField.isEnabled,
+ try checkTitlebar(tabs.isEmpty && !actionsEnabled && !newButton.isEnabled && !newAgentButton.isEnabled && !searchButton.isEnabled && !notificationButton.isEnabled,
"Initial palette setup does not create or enable workspace controls")
}
@@ -123,49 +123,25 @@ 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(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")
+ try checkTitlebar(searchButton.toolTip?.contains("⌘P") == true, "Search advertises its keyboard shortcut")
+ try checkTitlebar(newButton.frame.maxX + 12 <= searchButton.frame.minX, "New swarm leaves space before the search icon")
+ try checkTitlebar(searchButton.frame.maxX < newAgentButton.frame.minX && newAgentButton.frame.maxX < notificationButton.frame.minX, "Search, new agent and bell have separate targets in order")
+ try checkTitlebar(newAgentButton.title.isEmpty && newAgentButton.accessibilityLabel() == "New agent", "New agent uses an icon with an accessible label")
+ try checkTitlebar(!subviews.contains(where: { $0 is NSTextField }), "The titlebar has no competing text editor")
+ events.removeAll()
+ searchButton.performClick(nil)
+ newAgentButton.performClick(nil)
+ notificationButton.performClick(nil)
+ try checkTitlebar(events == ["jump", "newAgent", "notifications"], "Each toolbar icon opens its shared Flutter surface once")
+ try checkTitlebar(notificationButton.hasAttention, "The bell represents pending agent attention")
+ let oldButton = searchButton
var themedState = state([["id": "swarm-0", "name": "Renamed tab"]], active: "swarm-0")
themedState["palette"] = ["workspace": Int64(0xff252d43), "search": Int64(0xff262f46)]
- let oldField = searchField
update(themedState)
- try checkTitlebar(searchField === oldField && searchField.stringValue == "Workshop" && searchField.searching,
- "Palette changes preserve the open native search and typed query")
- try checkTitlebar(tabs[0] === original && tabs[0].palette == palette && searchField.palette == palette,
- "The existing native tab and search controls receive one coordinated palette")
- 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"),
- ("showInfo:", key("i", .command), "preview"),
- ("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")
+ try checkTitlebar(searchButton === oldButton && tabs[0] === original,
+ "Palette changes retain native control identity")
+ try checkTitlebar(searchButton.contentTintColor == palette.accent && notificationButton.contentTintColor == palette.accent,
+ "Both toolbar icons receive the coordinated palette")
events.removeAll()
try original.checkEnabled(true)
original.clickBothActions()
@@ -174,59 +150,18 @@ 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 && !searchField.isEnabled, "Titlebar actions disable with a modal")
+ try checkTitlebar(!newButton.isEnabled && !newAgentButton.isEnabled && !searchButton.isEnabled && !notificationButton.isEnabled, "Titlebar actions disable with a modal")
original.clickBothActions()
newButton.performClick(nil)
- focusSearch()
+ newAgentButton.performClick(nil)
+ searchButton.performClick(nil)
+ notificationButton.performClick(nil)
try checkTitlebar(events.isEmpty, "Disabled controls emit no actions")
try checkDragOperations()
}
}
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")
- let fieldEditor = searchField.currentEditor() as! NSTextView
- fieldEditor.setMarkedText("も", selectedRange: NSRange(location: 1, length: 0),
- replacementRange: NSRange(location: 3, length: 0))
- let draft = fieldEditor.string, marked = fieldEditor.markedRange(), caret = fieldEditor.selectedRange()
- update(["enabled": true, "activeId": activeId,
- "tabs": tabs.map { ["id": $0.swarmId, "name": $0.name, "attention": 1] as [String: Any] },
- "palette": ["workspace": Int64(0xff252d43), "search": Int64(0xff262f46)]])
- setSearchState(["hint": "Search agents…"])
- focusSearch(selectAll: true)
- try checkTitlebar(window.firstResponder === fieldEditor && fieldEditor.string == draft,
- "Background attention and palette changes preserve the current search editor and draft")
- try checkTitlebar(fieldEditor.markedRange() == marked && fieldEditor.selectedRange() == caret,
- "Background updates and refocusing preserve marked text and its caret")
- fieldEditor.unmarkText()
- setSearchState(["query": "feature/木", "hint": "Search agents…"])
- var cancelled = false
- let originalEmit = emit
- emit = { method, args in
- if method == "searchCommand", let command = (args as? [String: Any])?["command"] as? String,
- command == "dismiss" || command == "close" { cancelled = true }
- originalEmit?(method, args)
- }
- defer { emit = originalEmit }
- let editor = window.firstResponder
- NotificationCenter.default.post(name: NSWindow.didResignKeyNotification, object: window)
- NotificationCenter.default.post(name: NSWindow.didBecomeKeyNotification, object: window)
- try checkTitlebar(!cancelled, "Switching applications does not cancel search or restore terminal input")
- try checkTitlebar(searchField.stringValue == "feature/木" && window.firstResponder === editor,
- "Returning to the window retains the native search query and its input owner")
- closeSearch()
- try checkTitlebar(window.firstResponder === window.contentViewController,
- "Closing native search returns keyboard events to the content controller")
- }
-
func checkTabKeyboardFocus(_ window: NSWindow, messenger: TitlebarCheckMessenger) throws {
update(["enabled": true, "activeId": "keyboard-23",
"tabs": (0..<24).map { ["id": "keyboard-\($0)", "name": "Keyboard \($0)"] }])
@@ -271,12 +206,14 @@ private extension SwarmTabStrip {
let current = tabs[0].accessibilityChildren()!.first as! NSButton
window.makeFirstResponder(current)
current.performClick(nil)
- focusSearch()
- let editor = window.firstResponder
+ window.makeFirstResponder(searchButton)
+ searchButton.performClick(nil)
+ messenger.finishNextReply()
+ try checkTitlebar(window.firstResponder === searchButton,
+ "A delayed tab reply cannot steal focus from a newer search action")
messenger.finishNextReply()
- try checkTitlebar(window.firstResponder === editor && editor is NSTextView,
- "A delayed tab reply cannot steal focus from a newer search")
- closeSearch()
+ try checkTitlebar(window.firstResponder === window.contentViewController,
+ "The search button hands the next keystroke to the shared Flutter picker")
window.makeFirstResponder(current)
current.performClick(nil)
current.performClick(nil)
@@ -285,6 +222,18 @@ private extension SwarmTabStrip {
messenger.finishNextReply()
try checkTitlebar(window.firstResponder === window.contentViewController,
"The latest acknowledged tab action restores content focus")
+ for (button, method) in [(newAgentButton, "newAgent"), (notificationButton, "notifications")] {
+ window.makeFirstResponder(button)
+ let before = messenger.calls.count
+ button.performClick(nil)
+ try checkTitlebar(messenger.calls.count == before + 1 && messenger.calls.last?.method == method,
+ "The toolbar action dispatches once")
+ try checkTitlebar(window.firstResponder === button,
+ "The toolbar waits for Flutter's destination focus tree")
+ messenger.finishNextReply()
+ try checkTitlebar(window.firstResponder === window.contentViewController,
+ "New-agent and notification controls return keyboard ownership to Flutter")
+ }
messenger.holdReplies = false
}
}
@@ -337,7 +286,7 @@ private extension SwarmTabStrip {
try checkTitlebar(draggingEntered(info).isEmpty && draggingUpdated(info).isEmpty && !performDragOperation(info), reason)
try checkTitlebar(moves.isEmpty, "Rejected drag emits no reorder")
}
- info.draggingLocation = convert(NSPoint(x: searchField.frame.midX, y: 20), to: nil)
+ info.draggingLocation = convert(NSPoint(x: searchButton.frame.midX, y: 20), to: nil)
try rejected("Search is not a tab drop target")
info.draggingLocation = document.convert(NSPoint(x: tabs[0].frame.midX, y: 20), to: nil)
info.draggingSource = SwarmTabButton(id: "drag-3")
@@ -401,8 +350,8 @@ private extension SwarmTitlebar {
let original = NSApp.mainMenu!
let edit = original.item(withTitle: "Edit")!.submenu!
let jump = edit.items.first(where: { $0.representedObject as? String == "jump" })!
- let file = original.item(withTitle: "File")!.submenu!
- let newSwarm = file.items.first(where: { $0.representedObject as? String == "new" })!
+ let swarm = original.item(withTitle: "Swarm")!.submenu!
+ let newSwarm = swarm.items.first(where: { $0.representedObject as? String == "new" })!
let nativeCopy = NSMenuItem(title: "Copy", action: #selector(NSText.copy(_:)), keyEquivalent: "c")
edit.addItem(nativeCopy)
setKeymap(defaults)
@@ -431,72 +380,31 @@ private extension SwarmTitlebar {
"Rebuilt History rows retain effective unbindings")
setKeymap(changed)
actionsEnabled = true
- strip.focusSearch()
- guard let editor = strip.searchField.currentEditor() as? NSTextView else {
- throw TitlebarCheckFailure(message: "Native search owns an editor for shortcut checks")
- }
- strip.setSearchState(["query": "workshop 木"])
- func event(_ text: String, _ code: UInt16, _ flags: NSEvent.ModifierFlags = [],
- up: Bool = false, repeated: Bool = false) -> NSEvent {
- NSEvent.keyEvent(with: up ? .keyUp : .keyDown, location: .zero, modifierFlags: flags,
+ func event(_ text: String, _ code: UInt16, _ flags: NSEvent.ModifierFlags = []) -> NSEvent {
+ NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: flags,
timestamp: 0, windowNumber: window.windowNumber, context: nil, characters: text,
- charactersIgnoringModifiers: text, isARepeat: repeated, keyCode: code)!
+ charactersIgnoringModifiers: text, isARepeat: false, keyCode: code)!
}
let open = event("o", 31, .command)
let oldOpen = event("p", 35, .command)
try checkTitlebar(main.defersToInput(open) && !main.defersToInput(oldOpen),
- "The menu yields the new key while the unbound old key has no native owner")
- try checkTitlebar(!main.performKeyEquivalent(with: open), "Menu key equivalents defer before dispatch")
- try checkTitlebar(handleSearchKey(oldOpen) === oldOpen, "Unbound search key is not claimed by a fallback")
- try checkTitlebar(handleSearchKey(open) == nil && editor.selectedRange().length == editor.string.utf16.count,
- "Remapped search shortcut selects the existing native query")
- try checkTitlebar(handleSearchKey(event("o", 31, .command, up: true)) == nil,
- "A claimed key-up cannot escape to another input")
- let down = event("\u{f701}", 125)
- try checkTitlebar(handleSearchKey(down) === down &&
- !strip.control(strip.searchField, textView: editor, doCommandBy: #selector(NSResponder.moveDown(_:))),
- "Unbound result navigation is not revived by NSTextView's delegate")
- messenger.calls.removeAll()
- let previous = event("j", 38, .control)
- NSApp.sendEvent(previous)
- try checkTitlebar(messenger.calls.filter { $0.method == "keymapCommand" }.count == 1 &&
- (messenger.calls.last?.arguments as? [String: Any])?["command"] as? String == "picker.previous",
- "The installed local monitor routes one remapped result action")
- try checkTitlebar(editor.string == "workshop 木", "Consumed native shortcuts never become query text")
- _ = handleSearchKey(event("k", 40, .command))
- try checkTitlebar(searchKeyDispatch?.pending.count == 1, "Native field retains a sequence prefix")
- let before = messenger.calls.filter { $0.method == "keymapCommand" }.count
- _ = handleSearchKey(event("n", 45, .command))
- try checkTitlebar(messenger.calls.filter { $0.method == "keymapCommand" }.count == before + 1 &&
- (messenger.calls.last?.arguments as? [String: Any])?["command"] as? String == "swarm.new",
- "The configured sequence dispatches its command once")
- _ = handleSearchKey(event("k", 40, .command))
- editor.setMarkedText("木", selectedRange: NSRange(location: 1, length: 0), replacementRange: NSRange(location: NSNotFound, length: 0))
- let enter = event("\r", 36)
- try checkTitlebar(handleSearchKey(enter) === enter && searchKeyDispatch?.pending.isEmpty == true,
- "IME owns Return and cancels any partial shortcut")
- editor.unmarkText()
- _ = handleSearchKey(event("k", 40, .command))
- NotificationCenter.default.post(name: NSWindow.didResignKeyNotification, object: window)
- try checkTitlebar(searchKeyDispatch?.pending.isEmpty == true && window.firstResponder === editor,
- "Blur cancels a partial shortcut while preserving search input ownership")
- _ = handleSearchKey(event("k", 40, .command))
+ "The menu yields the remapped search shortcut to Flutter")
+ try checkTitlebar(!main.performKeyEquivalent(with: open), "Menu equivalents defer before input dispatch")
setKeymap(defaults)
- try checkTitlebar(searchKeyDispatch?.pending.isEmpty == true && strip.searchField.shortcutHint == "⌘P",
- "Reload cancels a pending sequence and refreshes the native search hint")
- strip.closeSearch()
- let ordinary = event("x", 7)
- try checkTitlebar(handleSearchKey(ordinary) === ordinary,
- "The native monitor does not intercept Flutter or agent input")
- removeKeyMonitor()
- try checkTitlebar(searchKeyMonitor == nil, "The scoped event monitor is removed explicitly")
+ try checkTitlebar(strip.searchButton.toolTip == "Search (⌘P)", "Reload refreshes the search button hint")
+ try checkTitlebar(main.defersToInput(event("p", 35, .command)), "Command-P reaches the shared Flutter picker")
+ try checkTitlebar(main.defersToInput(event("p", 35, [.command, .shift])), "Command-Shift-P reaches command search")
+ flutterKeyContext = "picker"
+ syncMenuKeys()
+ try checkTitlebar(!main.performKeyEquivalent(with: event("\u{f701}", 125)), "Result arrows are owned by the shared picker")
+ try checkTitlebar(!main.defersToInput(event("a", 0, .command)), "Standard select-all retains native text-editing dispatch")
}
func checkNativeContainer(messenger: TitlebarCheckMessenger) throws {
guard let window else { throw TitlebarCheckFailure(message: "Native test window exists") }
let main = NSMenu()
- let appItem = NSMenuItem(title: "Harness V2", action: nil, keyEquivalent: "")
- appItem.submenu = NSMenu(title: "Harness V2")
+ let appItem = NSMenuItem(title: "Harness", action: nil, keyEquivalent: "")
+ appItem.submenu = NSMenu(title: "Harness")
appItem.submenu?.addItem(NSMenuItem(title: "Preferences…", action: nil, keyEquivalent: ","))
main.addItem(appItem)
let edit = NSMenuItem(title: "Edit", action: nil, keyEquivalent: "")
@@ -536,27 +444,29 @@ private extension SwarmTitlebar {
"Leaving the workspace preserves the saved native background")
try strip.checkStartupPalette(startupPalette)
try checkTitlebar(window.firstResponder === window.contentViewController,
- "Adding the search field does not take initial keyboard focus from the workspace")
- try checkTitlebar(main.items.map(\.title) == ["Harness V2", "File", "Edit", "View", "History", "Models", "Window", "Help"], "Models replaces the redundant Swarm menu")
+ "Adding toolbar buttons does not take initial keyboard focus from the workspace")
+ try checkTitlebar(main.items.map(\.title) == ["Harness", "Swarm", "Agent", "Edit", "View", "History", "Models", "Window", "Help"], "Swarm and Agent replace File without duplicate menus")
let settings = appItem.submenu!.items[0]
try checkTitlebar(settings.title == "Settings…" && settings.representedObject as? String == "settings", "Settings stays in the application menu")
- let file = main.item(withTitle: "File")!.submenu!
+ let swarm = main.item(withTitle: "Swarm")!.submenu!
+ let agent = main.item(withTitle: "Agent")!.submenu!
let historyMenu = main.item(withTitle: "History")!.submenu!
- try checkTitlebar(file.items.compactMap { $0.representedObject as? String } == ["new", "newAgent", "reopen", "linkMachine", "addProject", "renameActive", "closePane", "closeActive"], "File exposes creation, connection, renaming and closing actions")
+ try checkTitlebar(swarm.items.compactMap { $0.representedObject as? String } == ["new", "renameActive", "closeActive", "linkMachine", "addProject"], "Swarm groups workspace actions")
+ try checkTitlebar(agent.items.compactMap { $0.representedObject as? String } == ["newAgent", "splitRight", "splitDown", "zoomPane", "pinPane", "closePane"], "Agent groups creation and pane actions")
let jump = edit.submenu!.items.first(where: { $0.representedObject as? String == "jump" })!
try checkTitlebar(jump.keyEquivalent == "p" && jump.keyEquivalentModifierMask == [.command], "Command-P has a native menu owner while a terminal has focus")
- let reopen = file.items.first(where: { $0.representedObject as? String == "reopen" })!
+ let reopen = historyMenu.items.first(where: { $0.representedObject as? String == "reopen" })!
actionsEnabled = true
canReopen = false
try checkTitlebar(!validateMenuItem(reopen), "Closed-Swarm recovery is disabled with an empty history")
canReopen = true
try checkTitlebar(validateMenuItem(reopen), "Closed-Swarm recovery becomes available")
- let closePane = file.items.first(where: { $0.representedObject as? String == "closePane" })!
+ let closePane = agent.items.first(where: { $0.representedObject as? String == "closePane" })!
canClosePane = false
try checkTitlebar(!validateMenuItem(closePane), "Remove Agent is disabled in New swarm")
canClosePane = true
try checkTitlebar(validateMenuItem(closePane), "Remove Agent is enabled for a focused pane")
- let create = file.items.first(where: { $0.representedObject as? String == "new" })!
+ let create = swarm.items.first(where: { $0.representedObject as? String == "new" })!
canCreateSwarm = false
try checkTitlebar(!validateMenuItem(create), "Native New Swarm respects the tab capacity")
canCreateSwarm = true
@@ -598,8 +508,8 @@ private extension SwarmTitlebar {
try checkTitlebar(validateMenuItem(recent), "Recent navigation is available in the shell")
actionsEnabled = false
try checkTitlebar(!validateMenuItem(recent) && !validateMenuItem(jump) && !validateMenuItem(settings), "History, jump and Settings cannot act behind a modal")
- for item in file.items where !item.isSeparatorItem {
- try checkTitlebar(!validateMenuItem(item), "File commands cannot change a covered Swarm")
+ for item in swarm.items + agent.items where !item.isSeparatorItem {
+ try checkTitlebar(!validateMenuItem(item), "Workspace commands cannot act behind a modal")
}
actionsEnabled = true
updateHistory([])
@@ -621,7 +531,7 @@ private extension SwarmTitlebar {
!["Next Swarm", "Previous Swarm"].contains($0.title)
}, "Next and Previous Swarm have no redundant menu rows")
let modelRows: [[String: Any]] = [
- ["title": "Anthropic", "account": "Account aabbcc", "status": "12% remaining", "engine": "claude",
+ ["title": "Anthropic", "account": "aabbcc", "status": "12% remaining", "engine": "claude",
"details": ["Limiting window: Session", "Session — 12% remaining · resets in 2h"]],
["title": "OpenAI", "status": "Not signed in", "engine": "codex",
"details": ["Sign in to Codex to see usage"]],
@@ -629,7 +539,7 @@ private extension SwarmTitlebar {
updateModels(modelRows)
let models = main.item(withTitle: "Models")!.submenu!
try checkTitlebar(models.items.filter { !$0.isSeparatorItem }.map(\.title) == [
- "Subscription", "Anthropic, Account aabbcc, 12% remaining", "OpenAI, Not signed in",
+ "Subscription", "Anthropic, aabbcc, 12% remaining", "OpenAI, Not signed in",
"API", "OpenRouter", "fal.ai", "Local", "DeepSeek V4 Flash", "Qwen3.8-27B", "Add Model"
], "Models has the three requested sections and Add Model last")
try checkTitlebar(models.items.filter(\.isSeparatorItem).count == 3,
@@ -643,7 +553,7 @@ private extension SwarmTitlebar {
let row = subscription.view as! SwarmSubscriptionView
try checkTitlebar(subscription.submenu == nil && subscription.action == nil && !subscription.isEnabled,
"Subscription balances have no arrow or fake action")
- try checkTitlebar(row.identity.stringValue == "Anthropic Account aabbcc" && row.balance.stringValue == "12% remaining",
+ try checkTitlebar(row.identity.stringValue == "Anthropic aabbcc" && row.balance.stringValue == "12% remaining",
"Provider and account are on the left; usage is a separate right column")
try checkTitlebar(row.identity.frame.maxX + 24 <= row.balance.frame.minX && row.balance.frame.maxX == row.bounds.width - 18,
"Account and balance have a clear gap and a consistent trailing inset")
@@ -693,7 +603,6 @@ private extension SwarmTitlebar {
strip.layoutSubtreeIfNeeded()
try strip.checkWindowGeometry(window)
}
- try strip.checkSearchEditing(window)
try strip.checkTabKeyboardFocus(window, messenger: messenger)
try checkTitlebar(!window.isVisible, "Native layout check never displays its window")
}
diff --git a/docs/harness-v2-keyboard-system.md b/docs/harness-v2-keyboard-system.md
index 93efdbc66..2c9f68aec 100644
--- a/docs/harness-v2-keyboard-system.md
+++ b/docs/harness-v2-keyboard-system.md
@@ -1,6 +1,6 @@
# A coherent keyboard system for Harness
-Updated 2026-09-13 after the user's review. **The earlier proposed modifier-heavy defaults are withdrawn.** The user explicitly chose to retain Cmd-H/J/K/L and Cmd-arrows for pane movement, Cmd-S for layout, Cmd-R for refresh, and Cmd-B for Boss mode. Cmd-L stays move right. File remapping is not enabled in the running preview yet.
+Updated 2026-09-13 after the user's review. **The earlier proposed modifier-heavy defaults are withdrawn.** The user explicitly chose to retain Cmd-H/J/K/L and Cmd-arrows for pane movement, Cmd-S for layout, Cmd-R for refresh, and Cmd-B for Boss mode. Cmd-L stays move right. File remapping is available; menus and help reflect the effective bindings.
## Product contract
@@ -22,7 +22,7 @@ Keep ordinary typing and editing predictable inside the actual agent CLI, search
| Machine/project search result | Open its swarm directly; no intermediate Browse agents step. |
| Other existing shortcuts | Preserve until a concrete problem justifies a reviewed change. Do not silently switch Cmd-number navigation, zoom, tab traversal, or closing to the earlier proposed alternatives. |
| File customization | One commented config file with reload; menus, help and dispatch must agree. |
-| Commands in search | Approved: optional `>` mode for existing actions. Preserve existing defaults, including Cmd-Shift-P for pin; no new conflicting command shortcut. |
+| Commands in search | Approved: Cmd-Shift-P opens `>` command mode, following the later user decision. Pin remains available in the Agent menu, pane menu, commands and custom bindings. |
The previous full default-binding audit is preserved in Git history. Its evidence is useful, but its proposed defaults do not override these decisions.
@@ -54,10 +54,10 @@ Parse and resolve when configuration changes, never on each keystroke. A lookup
Production startup loads the optional file before the workspace opens. Settings and the shortcut sheet show the effective bindings for Workspace, Agent input or Search, including unassigned commands. **Edit keyboard config** creates a commented template only when explicitly invoked, lists the stable command IDs, and opens the associated editor. The startup path, watcher and dispatch never rewrite existing user configuration.
-Flutter owns configured workspace/terminal keys before the focused input, with live composition checks. Both search fields use their own picker context. Their Enter/add/preview actions and displayed hints update together; the command result list also refreshes its shortcut labels after a configuration change. Prefixes are temporary and never replay into agent input. The current direct defaults and explicit Cmd-P jump to titlebar search remain unchanged.
+Flutter owns configured workspace/terminal keys before the focused input, with live composition checks. Both search fields use their own picker context. Their Enter/add/preview actions and displayed hints update together; the command result list also refreshes its shortcut labels after a configuration change. Prefixes are temporary and never replay into agent input. Cmd-P opens the centered shared search editor. Cmd-Shift-P opens the same editor in command mode. The other frequent direct defaults remain unchanged.
-Native menu labels come from the same resolved snapshot. The main menu yields configured first strokes to the input owner, rather than independently executing a command before Flutter knows its context. The native search editor uses a scoped local event monitor for ordinary sequence suffixes, with explicit cleanup. This follows Apple's [key-event routing](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/HandlingKeyEvents/HandlingKeyEvents.html) and [local event monitor lifecycle](https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/EventOverview/MonitoringEvents/MonitoringEvents.html). Ordinary Mac editing, font and window commands remain native; custom bindings that use those reserved strokes, including sequence suffixes, are rejected instead of being silently unreliable.
+Native menu labels come from the same resolved snapshot. The main menu yields configured first strokes to Flutter, which owns both search editors, text selection, composition and result navigation. The titlebar contains Search, New agent and Notifications buttons. Button activation waits for the destination's Flutter frame before returning native keyboard focus to the content view. Ordinary Mac editing, font and window commands remain native; custom bindings using reserved strokes are rejected.
-The complete Flutter suite passes **1,155 tests with one existing skip**. The native adapter/dispatcher passes **51 checks** against Dart-exported bindings, followed by **319 AppKit titlebar checks**, including remaps in a hidden actual field editor. Integration fixtures cover precise pane destinations and retained sessions, unbinding that returns an input key to its original agent, failed/completed sequences, both search fields, terminal IME, native channel dispatch and effective help. Final visual checks cover the settings deck, narrow layout and sheet; missing Tab/Return glyphs use icons. No real agents receive test input.
+Current validation includes the shared editor's arrow navigation, select-all/delete, command mode, effective remaps, pane focus and terminal IME. The native adapter passes **51 checks** against Dart-exported bindings, followed by **347 AppKit titlebar checks**, including Swarm/Agent menu ordering, three distinct toolbar targets, disabled controls and delayed focus handoff. These are synthetic checks; no real agents receive test input. Current build and regression results are recorded in the progress log.
See the [progress log](harness-v2-progress.md) for build/artifact status and the [working queue](harness-v2-developer-tools-research.md) for the next product improvements. These fixtures do not establish native input-to-display latency or first-install conversion rates; those remain separate measurements.
diff --git a/docs/harness-v2-progress.md b/docs/harness-v2-progress.md
index e30561f77..faea54992 100644
--- a/docs/harness-v2-progress.md
+++ b/docs/harness-v2-progress.md
@@ -2,6 +2,16 @@
Updated 2026-09-13 with coordinated palettes, Models, combined closed-work History and faster unified search. This is a working preview, not a release.
+## Search, creation and workspace controls checkpoint
+
+- Replaced File with separate **Swarm** and **Agent** menus. The top-right toolbar has exactly three icons: Search, New agent and Notifications. The tab-strip plus still creates a swarm. Native and Flutter New agent actions open the current swarm's creation dialog, inherit the focused agent's machine/working folder and preserve the existing agents and their input.
+- Cmd-P opens a centered search editor. Cmd-Shift-P opens command mode. Inline New swarm search uses the same input/results components, with results on the left and an optional preview on the right. Flutter owns arrows, text selection, deletion and IME in both locations. Native chrome no longer maintains a competing text editor or copies queries across channels.
+- Added header zoom and pane actions for right/down splits, pinning, the optional message composer and closing. Resize dividers show short centered grips. Existing resizing limits, saved proportions, cancellation and retained terminals remain covered. The four-pane SwarmIcon also identifies machine/project entries that open swarms.
+- User-facing names now say **Harness**; the internal bundle identifier stays unchanged. Models uses bare short account IDs. The preceding creation checkpoint (`06ba77c`) adds one-click Codex/Claude Code/Cursor choices, remembered agent choice, organized Advanced settings and a separate GitHub clone dialog on this computer. A saved project name wins over a discovered checkout alias.
+- The macOS Release preview built successfully (`/private/tmp/harness-v2-toolbar-release-build.log`). Synthetic visual review with real fonts verified the New agent dialog, quick choices and expanded Advanced section (`/private/tmp/harness-advanced-review.png`). Analyzer reports zero errors/warnings and the 12 existing vendored infos. Native checks pass: **51 decoder + 347 AppKit**; no windows displayed or real agent input used.
+- Full desktop regression run exercised 1,240 tests plus one existing skip. Eight old UI expectations were updated for the approved controls, command shortcut and visible preview; the affected files are rechecked separately. Logs: `/private/tmp/harness-v2-full-workspace-checks.log`, `/private/tmp/harness-v2-final-regressions.log`, `/private/tmp/harness-v2-pane-menu-checks.log`.
+- Draft PR #31 remains a review checkpoint. Actual first-use clarity, direct native input-to-display latency, real remote reconnect and Linux rollout still need qualification. Do not claim those are verified by widget or hidden AppKit tests. Preserve the separate uncommitted first-agent naming work, collaboration design and native benchmark tooling.
+
## Concurrent machine discovery checkpoint
- Agent inventory and terminal capabilities now start together after the machine handshake. Capability checks are sent first, so the CLI's per-client FIFO can answer that small request before building the agent catalog. Discovered agents publish without waiting for a slower capability response. Restored panes still require both results, attach once and preserve focus.