The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(desktop): give Linux the macOS menu bar
jaylfc6dfbaa7848d0
diff --git a/desktop/lib/app_shell.dart b/desktop/lib/app_shell.dartindex b0241ca34..54c116eda 100644--- a/desktop/lib/app_shell.dart+++ b/desktop/lib/app_shell.dart@@ -1,3 +1,5 @@+import 'core/app_version.dart';+import 'dart:async';import 'dart:ui' show AppExitResponse;@@ -21,6 +23,7 @@ import 'widgets/environment_preflight_screen.dart';import 'widgets/environment_setup_screen.dart';import 'widgets/export_logs_dialog.dart';import 'widgets/flash_firmware_dialog.dart';+import 'widgets/linux_menu_bar.dart';import 'core/startup.dart';import 'logging/app_log.dart';import 'logging/install.dart';@@ -192,8 +195,17 @@ class _RootShellState extends ConsumerState<RootShell>}Future<void> _onAppMenu(MethodCall call) async {+ await runAppMenuAction(call.method);+ }++ /// Runs one app-menu action.+ ///+ /// The macOS native menu reports over `harness/app_menu`; the Linux menu bar+ /// ([LinuxMenuBar]) fires the same strings directly, so one switch serves+ /// both platforms.+ Future<void> runAppMenuAction(String action) async {if (!mounted) return;- switch (call.method) {+ switch (action) {case 'checkForUpdates':final app = ref.read(appStateProvider);await _menuDialog(() => checkForUpdatesAndShowResult(context, app));@@ -210,6 +222,18 @@ class _RootShellState extends ConsumerState<RootShell>await _menuDialog(() => showShortcutsSheet(context));case 'keyboardPractice':await _menuDialog(() => showKeyboardPractice(context));+ case 'showAbout':+ // macOS shows AppKit's standard About panel; the Linux bar's row lands+ // here, with the version the Linux release stamps beside the binary.+ final version = await runningAppVersion();+ if (!mounted) return;+ await _menuDialog(+ () async => showAboutDialog(+ context: context,+ applicationName: 'Harness',+ applicationVersion: version,+ ),+ );case 'increaseTerminalFontSize':await terminalFontStore.increaseSize();case 'decreaseTerminalFontSize':@@ -280,6 +304,9 @@ class _RootShellState extends ConsumerState<RootShell>// must stay reachable.return Column(children: [+ // The app's commands as a menu strip (Linux only; macOS carries+ // them in its native menu bar, and this renders nothing there).+ LinuxMenuBar(onAction: runAppMenuAction),if (app.hasAvailableUpdate &&app.status != AppStatus.bootstrapping &&app.status != AppStatus.checkingEnvironment &&diff --git a/desktop/lib/screens/swarm_menu_bus.dart b/desktop/lib/screens/swarm_menu_bus.dartnew file mode 100644index 000000000..71265dfc9--- /dev/null+++ b/desktop/lib/screens/swarm_menu_bus.dart@@ -0,0 +1,214 @@+import 'dart:io' show Platform;++import 'package:flutter/foundation.dart';+import 'package:flutter/services.dart';++import '../core/test_run.dart';++/// The seam both native menu surfaces talk through.+///+/// On macOS the state the title bar draws crosses to AppKit over the+/// `harness/swarm_tabs` channel and the actions come back over it; the Swift+/// side owns that half. Linux has no native menu bar to hand the payloads to,+/// so this bus is ALSO where the Linux menu bar (`widgets/linux_menu_bar.dart`)+/// reads them from and the path its rows dispatch back through — one contract,+/// two hosts, and Dart keeps a single switch (`_onNative`) for either side.+class SwarmMenuBus {+ /// The platform default: the channel on macOS, the state model on Linux.+ ///+ /// Never the channel under test, whatever the host: the Linux bar's tests+ /// run on macOS machines too, and there the channel has nobody on the other+ /// end, so the bar would draw no state and its rows would reach no handler.+ /// A test that wants the channel asks for [SwarmMenuBus.forChannel].+ SwarmMenuBus() : _channelBacked = Platform.isMacOS && !kUnderTest;++ /// The channel, even on a Linux test host — a screen forced onto the+ /// native-tabs path must keep talking to something a test can mock.+ SwarmMenuBus.forChannel() : _channelBacked = true;++ /// macOS hands the payloads to AppKit; Linux keeps them here for the bar.+ final bool _channelBacked;++ final SwarmMenuState state = SwarmMenuState();++ Future<dynamic> Function(MethodCall call)? _handler;++ /// Dart → native. On macOS this crosses to Swift; on Linux the menu state and+ /// the keymap land in [state] (what the menu bar draws, and the shortcut+ /// hints beside its rows) and the rest have no reader here.+ Future<void> send(String method, [Map<Object?, Object?>? arguments]) async {+ if (_channelBacked) {+ await const MethodChannel('harness/swarm_tabs')+ .invokeMethod<void>(method, arguments);+ return;+ }+ switch (method) {+ case 'update':+ case 'keymapState':+ state.apply(method, arguments ?? const <Object?, Object?>{});+ }+ }++ /// Registers where the native side's actions arrive. On macOS this is the+ /// platform handler; on Linux the menu bar calls [receive] with the same+ /// shape a native menu would have delivered.+ void setHandler(Future<dynamic> Function(MethodCall call)? handler) {+ if (_channelBacked) {+ const MethodChannel('harness/swarm_tabs').setMethodCallHandler(handler);+ return;+ }+ _handler = handler;+ }++ /// Delivers one action to Dart — the Linux menu bar's half of the channel.+ Future<dynamic> receive(MethodCall call) async {+ final handler = _handler;+ if (handler == null) return null;+ return handler(call);+ }+}++/// The menu bar's one shared bus.+final swarmMenuBus = SwarmMenuBus();++/// The state a native menu bar draws, parsed from the same payloads+/// SwarmTitlebar.swift and HarnessKeymap.swift consume. Field-for-field the+/// Swift side's `SwarmHistoryEntry`, with the same tolerance for a short row:+/// a missing key reads as absent, never as a crash.+class SwarmMenuState extends ChangeNotifier {+ bool enabled = false;+ bool canReopen = false;+ bool canFind = false;+ bool canClosePane = false;+ bool canGoBack = false;+ bool canGoForward = false;+ List<SwarmMenuEntry> history = const [];+ List<SwarmMenuEntry> closedHistory = const [];++ /// The per-pane commands the focused pane can take right now: restart,+ /// share, the viewer and the composer. validateMenuItem reads the same map.+ Map<String, bool> paneActions = const {};++ /// Each menu action's (and keymap command's) shortcut, as the Keyboard+ /// Shortcuts sheet writes it.+ /// macOS sets a row's key equivalent from the same binding+ /// (HarnessKeymap.applyMenuKeys), so a rebinding shows up in both.+ Map<String, String> hints = const {};++ void apply(String method, Map<Object?, Object?> args) {+ switch (method) {+ case 'update':+ enabled = args['enabled'] as bool? ?? false;+ canReopen = args['canReopen'] as bool? ?? false;+ canFind = args['canFind'] as bool? ?? false;+ canClosePane = args['canClosePane'] as bool? ?? false;+ canGoBack = args['canGoBack'] as bool? ?? false;+ canGoForward = args['canGoForward'] as bool? ?? false;+ history = _parseEntries(args['history'], closed: false);+ closedHistory = _parseEntries(args['closedHistory'], closed: true);+ paneActions = {+ if (args['paneActions'] case final Map actions)+ for (final MapEntry(:key, :value) in actions.entries)+ if (key is String && value is bool) key: value,+ };+ case 'keymapState':+ hints = _parseHints(args['contexts']);+ default:+ return;+ }+ notifyListeners();+ }++ /// The dispose path pushes empty payloads so a macOS menu stops showing+ /// state; on Linux the same pushes clear the bar.+ void clear() {+ enabled = false;+ canReopen = false;+ canFind = false;+ canClosePane = false;+ canGoBack = false;+ canGoForward = false;+ history = const [];+ closedHistory = const [];+ paneActions = const {};+ notifyListeners();+ }++ /// The first binding per menu action, workspace bindings first: a menu row+ /// shows one chord, and the workspace's is the one that works from anywhere.+ static Map<String, String> _parseHints(Object? contexts) {+ final hints = <String, String>{};+ if (contexts is! Map) return hints;+ final ordered = [+ contexts['workspace'],+ for (final MapEntry(:key, :value) in contexts.entries)+ if (key != 'workspace') value,+ ];+ for (final bindings in ordered) {+ if (bindings is! List) continue;+ for (final binding in bindings) {+ if (binding is! Map) continue;+ final hint = binding['hint'];+ if (hint is! String || hint.isEmpty) continue;+ // By menu action, and by command id for a row that sends the command+ // itself (Help's Quick Start). The two never collide: ids are dotted.+ for (final id in [binding['menuAction'], binding['command']]) {+ if (id is String) hints.putIfAbsent(id, () => hint);+ }+ }+ }+ return hints;+ }++ static List<SwarmMenuEntry> _parseEntries(+ Object? rows, {+ required bool closed,+ }) => [+ if (rows is List)+ for (final row in rows)+ if (row is Map) SwarmMenuEntry.fromMap(row, closed: closed),+ ];+}++/// One row of the History menu — a recently visited tab or a closed one.+class SwarmMenuEntry {+ const SwarmMenuEntry({+ required this.id,+ required this.title,+ required this.machineName,+ required this.detail,+ required this.engine,+ required this.iconAsset,+ required this.agentCount,+ required this.current,+ required this.canReopen,+ required this.closed,+ });++ factory SwarmMenuEntry.fromMap(+ Map<dynamic, dynamic> row, {+ required bool closed,+ }) => SwarmMenuEntry(+ id: row['id'] as String? ?? '',+ title: row['title'] as String? ?? '',+ machineName: row['machineName'] as String? ?? '',+ detail: row['detail'] as String? ?? '',+ engine: row['engine'] as String?,+ iconAsset: row['iconAsset'] as String?,+ agentCount: (row['agentCount'] as num?)?.toInt(),+ current: row['current'] as bool? ?? false,+ canReopen: row['canReopen'] as bool? ?? false,+ closed: closed,+ );++ final String id;+ final String title;+ final String machineName;+ final String detail;+ final String? engine;+ final String? iconAsset;+ final int? agentCount;+ final bool current;+ final bool canReopen;+ final bool closed;+}diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 9cb2414d0..2c1d257ab 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -39,6 +39,7 @@ import '../state/app_state.dart';import '../state/harness_sessions.dart';import '../state/harness_placement.dart';import '../state/new_harness.dart';+import 'swarm_menu_bus.dart';import '../state/pane_arrangement.dart';import '../terminal/terminal_viewport.dart';import '../terminal/terminal_text.dart';@@ -148,13 +149,25 @@ TextStyle get _boxCaption =>grid.AppType.monoLabel(color: kBoxFaint, fontWeight: FontWeight.w400);class _SwarmScreenState extends State<SwarmScreen> {- static const _channel = MethodChannel('harness/swarm_tabs');+ /// The title bar's seam: the `harness/swarm_tabs` channel on macOS — and+ /// in anything forced onto the native-tabs path, so a test can still mock+ /// the channel — and the Linux menu bar's bus here. One set of payloads+ /// out, one switch of actions back.+ late final SwarmMenuBus _menuBus = widget.nativeTabs == true+ ? SwarmMenuBus.forChannel()+ : swarmMenuBus;/// The tab the middle button went down on, so an up that slid onto another/// tab closes nothing. Null between presses.String? _middleDownTab;late final bool _native =widget.nativeTabs ?? (Platform.isMacOS && !kUnderTest);++ /// A menu bar is listening: AppKit's on macOS, the in-window bar on Linux.+ /// Not the same as [_native], which is whether AppKit also draws the tab+ /// strip and the title-bar buttons. On Linux Flutter still draws those, so+ /// the strip stays and only the menu state and actions cross the bus.+ late final bool _menuHost = _native || (Platform.isLinux && !kUnderTest);late final SwarmProjectStore _projects =widget.projectStore ??SwarmProjectStore(storage: kUnderTest ? null : HarnessFileStore.shared);@@ -352,8 +365,8 @@ class _SwarmScreenState extends State<SwarmScreen> {_modelsMenu!.start();});}- if (_native) {- _channel.setMethodCallHandler(_onNative);+ if (_menuHost) {+ _menuBus.setHandler(_onNative);app.addListener(_syncNative);_syncNative();}@@ -386,7 +399,7 @@ class _SwarmScreenState extends State<SwarmScreen> {}});}- if (_native) _syncNative();+ if (_menuHost) _syncNative();}@override@@ -441,13 +454,11 @@ class _SwarmScreenState extends State<SwarmScreen> {if (_hasCommandBar) _commandBar.dispose();unawaited(_spokenTasks?.cancel());app.systemNotifications.onTap = null;- if (_native) {- unawaited(_channel.invokeMethod<void>('machinesState', {'machines': []}));+ if (_menuHost) {+ unawaited(_menuBus.send('machinesState', {'machines': []}));app.removeListener(_syncNative);- _channel.setMethodCallHandler(null);- unawaited(- _channel.invokeMethod<void>('update', {'tabs': [], 'enabled': false}),- );+ _menuBus.setHandler(null);+ unawaited(_menuBus.send('update', {'tabs': [], 'enabled': false}));}if (widget.projectStore == null) _projects.dispose();super.dispose();@@ -456,14 +467,14 @@ class _SwarmScreenState extends State<SwarmScreen> {AppKeymap? _sentKeymap;int? _sentKeymapVersion;void _syncKeymap() {- if (!_native ||+ if (!_menuHost ||(_sentKeymap == _keymap && _sentKeymapVersion == _keymap.version)) {return;}_sentKeymap = _keymap;_sentKeymapVersion = _keymap.version;unawaited(- _channel.invokeMethod<void>(+ _menuBus.send('keymapState',nativeKeymapSnapshot(_keymap,@@ -482,16 +493,14 @@ class _SwarmScreenState extends State<SwarmScreen> {}void _syncKeyContext() {- if (!_native) return;+ if (!_menuHost) return;final focus = FocusManager.instance.primaryFocus?.context;final kind = focus == null? KeymapContext.workspace: KeymapRegion.of(focus)?.contextKind ?? KeymapContext.workspace;if (_nativeKeyContext == kind.name) return;_nativeKeyContext = kind.name;- unawaited(- _channel.invokeMethod<void>('keymapContext', {'context': kind.name}),- );+ unawaited(_menuBus.send('keymapContext', {'context': kind.name}));}bool get _modelsVisible =>@@ -711,7 +720,7 @@ class _SwarmScreenState extends State<SwarmScreen> {_machinesPanel?.rebuild();_modelsOverlay?.markNeedsBuild();_harnessesOverlay?.markNeedsBuild();- if (_native) _syncNative();+ if (_menuHost) _syncNative();setState(() {});}@@ -751,7 +760,7 @@ class _SwarmScreenState extends State<SwarmScreen> {void _toolbarNoticesChanged() {if (!mounted) return;_modelsOverlay?.markNeedsBuild();- if (_native) _syncNative();+ if (_menuHost) _syncNative();setState(() {});}@@ -764,7 +773,7 @@ class _SwarmScreenState extends State<SwarmScreen> {// `_syncNative` — which is subscribed to the APP, not to this notifier. A// mark that only called setState redrew a tab strip the native window does// not use, and the badge a person can actually see never moved.- if (_native) _syncNative();+ if (_menuHost) _syncNative();}void _restoreEmptyFocus() {@@ -795,7 +804,7 @@ class _SwarmScreenState extends State<SwarmScreen> {}void _statusPrefsChanged() {- if (_native) _syncNative();+ if (_menuHost) _syncNative();if (mounted) setState(() {});}@@ -895,7 +904,7 @@ class _SwarmScreenState extends State<SwarmScreen> {_modelsOverlay?.markNeedsBuild();_harnessesOverlay?.markNeedsBuild();_searchOverlay?.markNeedsBuild();- if (_native) _syncNative();+ if (_menuHost) _syncNative();}/// The agents a tab holds, once each: a harness's viewer belongs to the agent beside it, so an@@ -1098,7 +1107,7 @@ class _SwarmScreenState extends State<SwarmScreen> {final encoded = jsonEncode(payload);if (encoded == _nativeState) return;_nativeState = encoded;- unawaited(_channel.invokeMethod<void>('update', payload));+ unawaited(_menuBus.send('update', payload));}void _syncMachines() {@@ -1141,7 +1150,7 @@ class _SwarmScreenState extends State<SwarmScreen> {if (listEquals(presentation, _machinesPresentation)) return;_machinesPresentation = presentation;unawaited(- _channel.invokeMethod<void>('machinesState', {+ _menuBus.send('machinesState', {'machines': [for (final machine in machines){@@ -1563,7 +1572,7 @@ class _SwarmScreenState extends State<SwarmScreen> {// The route must not restore an old terminal while the destination changes// behind a dialog. Return input explicitly when that dialog finishes._canvasFocus.descendantsAreFocusable = false;- if (_native) _syncNative();+ if (_menuHost) _syncNative();try {await action();} finally {@@ -1575,7 +1584,7 @@ class _SwarmScreenState extends State<SwarmScreen> {app.focusedPane?.session?.focusInput() != true) {_shellFocus.requestFocus();}- if (_native) _syncNative();+ if (_menuHost) _syncNative();}}if (restoreEntry) await _ensureEmptyEntry();@@ -1747,13 +1756,13 @@ class _SwarmScreenState extends State<SwarmScreen> {);_machinesPanel = panel;_syncToolbarNotices();- if (_native) _syncNative();+ if (_menuHost) _syncNative();setState(() {});final destination = await panel.closed;if (!mounted || !identical(_machinesPanel, panel)) return;_machinesPanel = null;_syncToolbarNotices();- if (_native) _syncNative();+ if (_menuHost) _syncNative();setState(() {});// Let the removed panel release its focus before opening work.await WidgetsBinding.instance.endOfFrame;@@ -2535,7 +2544,7 @@ class _SwarmScreenState extends State<SwarmScreen> {void _modelManagerChanged() {_syncToolbarNotices();- if (_native && mounted) _syncNative();+ if (_menuHost && mounted) _syncNative();}Future<void> _openModelManager() async {@@ -2631,7 +2640,7 @@ class _SwarmScreenState extends State<SwarmScreen> {_unregisterModels = registerTransientMenu(() => _closeModelsControls(restoreFocus: false),);- if (_native) _syncNative();+ if (_menuHost) _syncNative();setState(() {});}@@ -2645,7 +2654,7 @@ class _SwarmScreenState extends State<SwarmScreen> {_syncToolbarNotices();app.modelManager.setPanelVisible(false);if (!mounted) return;- if (_native) _syncNative();+ if (_menuHost) _syncNative();setState(() {});if (restoreFocus) {_shellFocus.requestFocus();@@ -2821,7 +2830,7 @@ class _SwarmScreenState extends State<SwarmScreen> {_unregisterHarnesses = registerTransientMenu(() => _closeHarnessControls(restoreFocus: false),);- if (_native) _syncNative();+ if (_menuHost) _syncNative();setState(() {});}@@ -2833,7 +2842,7 @@ class _SwarmScreenState extends State<SwarmScreen> {_harnessesOverlay?.dispose();_harnessesOverlay = null;if (!mounted) return;- if (_native) _syncNative();+ if (_menuHost) _syncNative();setState(() {});if (restoreFocus) {_shellFocus.requestFocus();@@ -3049,7 +3058,7 @@ class _SwarmScreenState extends State<SwarmScreen> {if (search.isCommandMode) _learning.commandSearchOpened();_searchOverlay?.markNeedsBuild();_syncToolbarNotices();- if (_native) _syncNative();+ if (_menuHost) _syncNative();}}@@ -3073,7 +3082,7 @@ class _SwarmScreenState extends State<SwarmScreen> {_searchHeaderState = null;_searchText.clear();_syncToolbarNotices();- if (_native && mounted) _syncNative();+ if (_menuHost && mounted) _syncNative();_searchFocus.unfocus();final previous = _searchReturnFocus;_searchReturnFocus = null;@@ -3575,7 +3584,7 @@ class _SwarmScreenState extends State<SwarmScreen> {_closeSearch();_spokenPaletteOpen = true;_closeCommandBar(restoreFocus: false);- if (_native) _syncNative();+ if (_menuHost) _syncNative();try {await revealWindow();if (!mounted) {@@ -3585,7 +3594,7 @@ class _SwarmScreenState extends State<SwarmScreen> {await showTaskPalette(context, app, spoken: spoken);} finally {_spokenPaletteOpen = false;- if (_native && mounted) _syncNative();+ if (_menuHost && mounted) _syncNative();spoken.cancelled();}}diff --git a/desktop/lib/widgets/linux_menu_bar.dart b/desktop/lib/widgets/linux_menu_bar.dartnew file mode 100644index 000000000..93d84b6cf--- /dev/null+++ b/desktop/lib/widgets/linux_menu_bar.dart@@ -0,0 +1,769 @@+import 'dart:io' show Platform;++import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:lucide_icons_flutter/lucide_icons.dart';+import 'package:window_manager/window_manager.dart';++import '../core/test_run.dart';+import '../screens/swarm_menu_bus.dart';+import '../shared/theme/app_theme.dart' as grid;+import '../shared/widgets/app_menu.dart';+import 'engine_identity.dart';++/// Runs one app-menu action — the same strings the macOS application menu+/// reports over `harness/app_menu`, handled once in+/// `_RootShellState.runAppMenuAction`.+typedef AppMenuActionHandler = Future<void> Function(String action);++/// The app's commands as an in-window menu bar.+///+/// On macOS the commands live in the native menu bar: the application menu's+/// own rows and View's font rows are installed in MainFlutterWindow.swift,+/// and File, Edit's Find rows, View's workspace rows and History are built by+/// SwarmTitlebar.swift from the `harness/swarm_tabs` payloads. Linux has no native menu bar to hand any of+/// that to, so this draws the same menus in the window instead: the state+/// comes off [SwarmMenuBus] (what Swift would have received), the rows+/// dispatch back through the same handler the macOS channel delivers to, and+/// the application-menu commands fire the same action strings through+/// [onAction].+///+/// The tab strip and the title-bar buttons are not here: on Linux Flutter+/// draws those itself, as it does anywhere AppKit is not drawing them. Two+/// standard menus are deliberately not mirrored row for row: Edit lacks+/// AppKit's Cut/Copy/Paste roles (the terminal owns those keys; only the rows+/// that reach Dart are drawn), and Window carries the two rows this app can+/// act on itself. Each row shows the shortcut the keymap gives its action,+/// which is where macOS takes its key equivalents from too. Off Linux this renders nothing; [visible] exists so a widget+/// test can force the bar on without caring which OS the host is. Widget+/// tests at large keep the bar off by default: it is window chrome — on macOS+/// it costs the layout nothing at all — and pane-geometry assertions should+/// not depend on whether the Linux build is drawing it.+class LinuxMenuBar extends StatefulWidget {+ const LinuxMenuBar({+ super.key,+ required this.onAction,+ this.state,+ this.visible,+ });++ final AppMenuActionHandler onAction;++ /// The swarm-menu state to draw; defaults to the shared bus's. A test seams+ /// its own in rather than touching the singleton.+ final SwarmMenuState? state;++ /// Force the bar on or off; defaults to following the host platform.+ final bool? visible;++ @override+ State<LinuxMenuBar> createState() => _LinuxMenuBarState();+}++class _LinuxMenuBarState extends State<LinuxMenuBar> {+ final _controllers = <String, MenuController>{};++ MenuController? _openMenu;++ SwarmMenuState get _state => widget.state ?? swarmMenuBus.state;++ @override+ void initState() {+ super.initState();+ _state.addListener(_changed);+ }++ @override+ void dispose() {+ _state.removeListener(_changed);+ super.dispose();+ }++ void _changed() {+ if (mounted) setState(() {});+ }++ /// The bar's panels size to the window, not to [AppControl.menuMaxHeight] —+ /// a History menu a row or two over the token drew a scrollbar for entries+ /// the screen had every room to draw. The panels open downward from a strip+ /// at the top, so the room they have is the window minus the strip itself+ /// and a margin for the screen edge; past that a menu really does scroll.+ MenuStyle get _panelStyle {+ final height = MediaQuery.sizeOf(context).height;+ return grid.AppMenu.style(maxHeight: height - 30 - 24);+ }++ @override+ Widget build(BuildContext context) {+ final visible = widget.visible ?? (Platform.isLinux && !kUnderTest);+ if (!visible) return const SizedBox.shrink();+ grid.AppTheme.watch(context);+ return Container(+ height: 30,+ decoration: BoxDecoration(+ color: grid.AppPalette.panelBg,+ border: Border(bottom: BorderSide(color: grid.AppGlass.hair)),+ ),+ // The full set of menus outgrows a narrow window; a menubar that+ // scrolls beats one that clips its last menus into nothing.+ child: ScrollConfiguration(+ behavior: ScrollConfiguration.of(context).copyWith(scrollbars: false),+ child: SingleChildScrollView(+ scrollDirection: Axis.horizontal,+ padding: const EdgeInsets.symmetric(horizontal: 6),+ child: Row(+ children: [+ _menu('Harness', _buildHarnessMenu()),+ _menu('File', _buildFileMenu()),+ _menu('Edit', _buildEditMenu()),+ _menu('View', _buildViewMenu(), onOpen: _readFullScreen),+ _menu('History', _buildHistoryMenu()),+ _menu('Window', _buildWindowMenu()),+ _menu('Help', _buildHelpMenu()),+ ],+ ),+ ),+ ),+ );+ }++ // ---------------------------------------------------------------------------+ // The menus. Row for row the macOS bar: the application menu's additions+ // (MainFlutterWindow.swift), File and History (SwarmTitlebar.swift), and the+ // stock menus' rows that reach Dart.+ // ---------------------------------------------------------------------------++ List<Widget> _buildHarnessMenu() {+ return [+ _appRow(+ key: 'menu-bar-about',+ icon: LucideIcons.info300,+ label: 'About Harness',+ action: 'showAbout',+ ),+ const AppMenuDivider(),+ _swarmRow(+ key: 'menu-bar-customize',+ icon: LucideIcons.palette300,+ label: 'Customize Harness',+ action: 'customize',+ ),+ _swarmRow(+ key: 'menu-bar-settings',+ icon: LucideIcons.settings300,+ label: 'Settings…',+ action: 'settings',+ ),+ const AppMenuDivider(),+ _appRow(+ key: 'menu-bar-shortcuts',+ icon: LucideIcons.keyboard300,+ label: 'Keyboard Shortcuts…',+ action: 'showShortcuts',+ ),+ _appRow(+ key: 'menu-bar-check-for-updates',+ icon: LucideIcons.refreshCw300,+ label: 'Check for Updates…',+ action: 'checkForUpdates',+ ),+ _appRow(+ key: 'menu-bar-flash-firmware',+ icon: LucideIcons.zap300,+ label: 'Flash Firmware…',+ action: 'flashFirmware',+ ),+ const AppMenuDivider(),+ // The Quit row the Mac's application menu carries. It goes through+ // window_manager so the app's exit lifecycle — the pane-arrangement+ // flush in didRequestAppExit — runs on the way out.+ _plainRow(+ key: 'menu-bar-quit',+ label: 'Quit Harness',+ onTap: () => windowManager.close(),+ ),+ ];+ }++ /// SwarmTitlebar.swift's File menu, in its three groups: the harness, the+ /// tab, the pane. New Terminal stays off it there too; its shortcut is the+ /// way in.+ List<Widget> _buildFileMenu() {+ final state = _state;+ return [+ _swarmRow(+ key: 'menu-bar-new-harness',+ icon: LucideIcons.plus300,+ label: 'New Harness',+ action: 'newAgent',+ ),+ _swarmRow(+ key: 'menu-bar-open-harness',+ icon: LucideIcons.folderOpen300,+ label: 'Open Harness',+ action: 'addAgent',+ ),+ _swarmRow(+ key: 'menu-bar-clone-agent',+ icon: LucideIcons.copyPlus300,+ label: 'Clone Harness',+ action: 'cloneAgent',+ ),+ _swarmRow(+ key: 'menu-bar-restart-agent',+ icon: LucideIcons.rotateCw300,+ label: 'Restart Harness',+ action: 'restartAgent',+ enabled: _paneAction('restartAgent'),+ ),+ _swarmRow(+ key: 'menu-bar-share-agent',+ icon: LucideIcons.share300,+ label: 'Share Harness',+ action: 'shareAgent',+ enabled: _paneAction('shareAgent'),+ ),+ const AppMenuDivider(),+ _swarmRow(+ key: 'menu-bar-new-tab',+ icon: LucideIcons.squarePlus300,+ label: 'New Tab',+ action: 'new',+ ),+ _swarmRow(+ key: 'menu-bar-rename-tab',+ icon: LucideIcons.pencil300,+ label: 'Rename Tab',+ action: 'renameActive',+ ),+ _swarmRow(+ key: 'menu-bar-close-tab',+ icon: LucideIcons.x300,+ label: 'Close Tab',+ action: 'closeActive',+ ),+ const AppMenuDivider(),+ _swarmRow(+ key: 'menu-bar-split-right',+ icon: LucideIcons.panelRight300,+ label: 'Split Right',+ action: 'splitRight',+ enabled: state.enabled && state.canFind,+ ),+ _swarmRow(+ key: 'menu-bar-split-down',+ icon: LucideIcons.panelBottom300,+ label: 'Split Down',+ action: 'splitDown',+ enabled: state.enabled && state.canFind,+ ),+ _swarmRow(+ key: 'menu-bar-zoom-pane',+ icon: LucideIcons.focus300,+ label: 'Zoom Pane',+ action: 'zoomPane',+ enabled: state.enabled && state.canFind,+ ),+ _swarmRow(+ key: 'menu-bar-move-pane',+ icon: LucideIcons.arrowRightLeft300,+ label: 'Move Pane to Tab',+ action: 'movePaneToTab',+ enabled: state.enabled && state.canFind,+ ),+ _swarmRow(+ key: 'menu-bar-close-pane',+ icon: LucideIcons.x300,+ label: 'Close Pane',+ action: 'closePane',+ enabled: state.enabled && state.canClosePane,+ ),+ ];+ }++ /// AppKit's Edit menu carries the text-editing roles a terminal owns, so+ /// only the rows that reach Dart are drawn here: the terminal's Find rows,+ /// then Search Commands, last as on macOS.+ List<Widget> _buildEditMenu() {+ final state = _state;+ return [+ _swarmRow(+ key: 'menu-bar-find-terminal',+ label: 'Find in Terminal…',+ action: 'findTerminal',+ enabled: state.enabled && state.canFind,+ ),+ _swarmRow(+ key: 'menu-bar-find-next',+ label: 'Find Next',+ action: 'findNext',+ enabled: state.enabled && state.canFind,+ ),+ _swarmRow(+ key: 'menu-bar-find-previous',+ label: 'Find Previous',+ action: 'findPrevious',+ enabled: state.enabled && state.canFind,+ ),+ const AppMenuDivider(),+ _swarmRow(+ key: 'menu-bar-commands',+ icon: LucideIcons.command300,+ label: 'Search Commands…',+ action: 'commands',+ ),+ ];+ }++ /// MainFlutterWindow.swift's rows before Full Screen, SwarmTitlebar.swift's+ /// after it.+ List<Widget> _buildViewMenu() {+ return [+ _appRow(+ key: 'menu-bar-layout',+ icon: LucideIcons.layoutGrid300,+ label: 'Layout…',+ action: 'showLayout',+ ),+ const AppMenuDivider(),+ _appRow(+ key: 'menu-bar-reset-font-size',+ icon: LucideIcons.type300,+ label: 'Default Font Size',+ action: 'resetTerminalFontSize',+ ),+ _appRow(+ key: 'menu-bar-bigger-font',+ icon: LucideIcons.aArrowUp300,+ label: 'Bigger',+ action: 'increaseTerminalFontSize',+ ),+ _appRow(+ key: 'menu-bar-smaller-font',+ icon: LucideIcons.aArrowDown300,+ label: 'Smaller',+ action: 'decreaseTerminalFontSize',+ ),+ const AppMenuDivider(),+ // AppKit's stock Full Screen row, reached through window_manager, and+ // named for what it will do the way AppKit names it.+ _plainRow(+ key: 'menu-bar-full-screen',+ label: _fullScreen ? 'Exit Full Screen' : 'Enter Full Screen',+ onTap: () async {+ await windowManager.setFullScreen(+ !await windowManager.isFullScreen(),+ );+ },+ ),+ const AppMenuDivider(),+ _swarmRow(+ key: 'menu-bar-sessions',+ icon: LucideIcons.terminal300,+ label: 'Harnesses',+ action: 'sessions',+ ),+ _swarmRow(+ key: 'menu-bar-notifications',+ icon: LucideIcons.bell300,+ label: 'Harnesses Needing Input…',+ action: 'notifications',+ ),+ _swarmRow(+ key: 'menu-bar-machines',+ icon: LucideIcons.server300,+ label: 'Machines',+ action: 'machineList',+ ),+ _swarmRow(+ key: 'menu-bar-models',+ icon: LucideIcons.cpu300,+ label: 'Models',+ action: 'models',+ ),+ _swarmRow(+ key: 'menu-bar-machine-monitor',+ icon: LucideIcons.activity300,+ label: 'Machine Monitor',+ action: 'manageMachines',+ ),+ const AppMenuDivider(),+ _swarmRow(+ key: 'menu-bar-toggle-viewer',+ label: 'Toggle Viewer',+ action: 'toggleViewer',+ enabled: _paneAction('toggleViewer'),+ ),+ _swarmRow(+ key: 'menu-bar-toggle-composer',+ label: 'Toggle Message Composer',+ action: 'toggleComposer',+ enabled: _paneAction('toggleComposer'),+ ),+ ];+ }++ /// validateMenuItem's rule for the per-pane rows: the app takes actions,+ /// and the focused pane can take this one.+ bool _paneAction(String action) =>+ _state.enabled && _state.paneActions[action] == true;++ bool _fullScreen = false;++ Future<void> _readFullScreen() async {+ if (kUnderTest && widget.visible != null) return;+ final full = await windowManager.isFullScreen();+ if (mounted && full != _fullScreen) setState(() => _fullScreen = full);+ }++ List<Widget> _buildHistoryMenu() {+ final state = _state;+ final closed = state.closedHistory.take(10).toList();+ final visited = state.history.take(15).toList();+ return [+ _swarmRow(+ key: 'menu-bar-history-back',+ label: 'Back',+ action: 'historyBack',+ enabled: state.enabled && state.canGoBack,+ ),+ _swarmRow(+ key: 'menu-bar-history-forward',+ label: 'Forward',+ action: 'historyForward',+ enabled: state.enabled && state.canGoForward,+ ),+ // No default chord here: ⌘⇧T is New Terminal now. The same row, the+ // same missing shortcut, as the native menu.+ _swarmRow(+ key: 'menu-bar-reopen-last',+ label: 'Reopen Closed Tab or Pane',+ action: 'reopen',+ enabled: state.enabled && state.canReopen,+ ),+ const AppMenuDivider(),+ _header('Recently Closed'),+ for (final entry in closed)+ _swarmRow(+ key: 'menu-bar-closed-${entry.id}',+ label: _entryTitle(entry),+ note: entry.machineName.isEmpty ? null : entry.machineName,+ leading: _engineLeading(entry.engine, entry.iconAsset),+ action: 'reopenHistory',+ args: {'id': entry.id},+ enabled: state.enabled && entry.canReopen,+ ),+ if (closed.isEmpty) _label('No Recently Closed Tabs or Panes'),+ const AppMenuDivider(),+ _header('Recently Visited'),+ for (final entry in visited)+ _swarmRow(+ key: 'menu-bar-visited-${entry.id}',+ label: _entryTitle(entry),+ note: entry.machineName.isEmpty ? null : entry.machineName,+ leading: _engineLeading(entry.engine, entry.iconAsset),+ action: 'historyDestination',+ args: {'id': entry.id},+ enabled: state.enabled,+ selected: entry.current,+ ),+ if (visited.isEmpty) _label('No Recent Visits'),+ const AppMenuDivider(),+ _swarmRow(+ key: 'menu-bar-show-history',+ label: 'Show Full History',+ action: 'showHistory',+ ),+ ];+ }++ /// The two window rows this app can act on itself. The Mac's Window menu is+ /// AppKit's own; the same two belong to window_manager here.+ List<Widget> _buildWindowMenu() {+ return [+ _plainRow(+ key: 'menu-bar-minimize',+ label: 'Minimize',+ onTap: () => windowManager.minimize(),+ ),+ _plainRow(+ key: 'menu-bar-zoom',+ label: 'Zoom',+ onTap: () async {+ if (await windowManager.isMaximized()) {+ await windowManager.unmaximize();+ } else {+ await windowManager.maximize();+ }+ },+ ),+ ];+ }++ List<Widget> _buildHelpMenu() {+ return [+ // Quick Start is a keymap command on macOS too: the Help row sends it+ // over the swarm channel as `keymapCommand`.+ _swarmRow(+ key: 'menu-bar-quick-start',+ icon: LucideIcons.rocket300,+ label: 'Quick Start',+ action: 'keymapCommand',+ args: const {'command': 'keyboard.quick_start'},+ hintAction: 'keyboard.quick_start',+ ),+ _appRow(+ key: 'menu-bar-keyboard-practice',+ icon: LucideIcons.keyboard300,+ label: 'Keyboard Practice',+ action: 'keyboardPractice',+ ),+ const AppMenuDivider(),+ _appRow(+ key: 'menu-bar-export-logs',+ icon: LucideIcons.fileDown300,+ label: 'Export Logs…',+ action: 'exportLogs',+ ),+ ];+ }++ // ---------------------------------------------------------------------------+ // Rows and panels.+ // ---------------------------------------------------------------------------++ /// A row that dispatches into the swarm bus — the same contract a native+ /// menu on macOS delivers with. [swarm] false sends an app-menu action to+ /// [LinuxMenuBar.onAction] instead (View's layout row lives on the other+ /// channel, as it does on the Mac).+ Widget _swarmRow({+ required String key,+ required String label,+ required String action,+ Map<String, Object?>? args,+ IconData? icon,+ String? note,+ Widget? leading,+ bool? enabled,+ bool selected = false,+ bool danger = false,+ bool swarm = true,+ String? hintAction,+ }) {+ // Every action row takes `actionsEnabled` from the state, the way the+ // native menu's validateMenuItem does; a row that passes its own flag+ // means BOTH must hold.+ if (!(enabled ?? _state.enabled)) return _label(label, note: note);+ return AppMenuItem(+ key: Key(key),+ icon: icon,+ label: label,+ note: note,+ leading: leading,+ trailing: _hint(hintAction ?? action),+ selected: selected,+ danger: danger,+ onPressed: () {+ _closeAll();+ if (swarm) {+ swarmMenuBus.receive(MethodCall(action, args));+ } else {+ widget.onAction(action);+ }+ },+ );+ }++ /// A row on the app-menu bus — the commands MainFlutterWindow.swift installs+ /// into the application menu on macOS.+ Widget _appRow({+ required String key,+ required String label,+ required String action,+ IconData? icon,+ }) {+ return AppMenuItem(+ key: Key(key),+ icon: icon,+ label: label,+ trailing: _hint(action),+ onPressed: () {+ _closeAll();+ widget.onAction(action);+ },+ );+ }++ Widget _plainRow({+ required String key,+ required String label,+ required VoidCallback onTap,+ }) {+ return AppMenuItem(+ key: Key(key),+ label: label,+ onPressed: () {+ _closeAll();+ onTap();+ },+ );+ }++ Widget _menu(String label, List<Widget> children, {VoidCallback? onOpen}) {+ final controller = _controllers.putIfAbsent(label, MenuController.new);+ final isOpen = identical(_openMenu, controller);+ return MenuAnchor(+ controller: controller,+ style: _panelStyle,+ onOpen: () {+ setState(() => _openMenu = controller);+ onOpen?.call();+ },+ onClose: () {+ if (identical(_openMenu, controller)) {+ setState(() => _openMenu = null);+ }+ },+ menuChildren: children,+ child: TextButton(+ key: Key('menu-bar-${label.toLowerCase()}'),+ onPressed: () {+ // Read at press time, not from the build's capture: the button does+ // not rebuild between a menu closing and the click that reopens it.+ final wasOpen = controller.isOpen;+ _closeAll();+ if (!wasOpen) controller.open();+ },+ style: TextButton.styleFrom(+ foregroundColor: isOpen+ ? grid.AppPalette.textPrimary+ : grid.AppPalette.textSecondary,+ padding: const EdgeInsets.symmetric(horizontal: 10),+ minimumSize: const Size(0, 28),+ shape: const RoundedRectangleBorder(),+ textStyle: const TextStyle(+ fontSize: 12.5,+ fontWeight: FontWeight.w500,+ ),+ ),+ child: Text(label),+ ),+ );+ }++ /// The keymap's chord for [action], set quietly at the row's end where a+ /// native menu draws its key equivalent.+ Widget? _hint(String action) {+ final hint = _state.hints[action];+ if (hint == null) return null;+ return Text(+ hint,+ style: grid.AppType.monoLabel(color: grid.AppPalette.textFaint),+ );+ }++ void _closeAll() {+ for (final controller in _controllers.values) {+ if (controller.isOpen) controller.close();+ }+ }++ Widget? _engineLeading(String? engine, String? iconAsset) {+ final asset =+ iconAsset ?? (engine == null ? null : engineIdentity(engine).asset);+ if (asset == null) return null;+ return Image.asset(+ asset,+ width: 16,+ height: 16,+ errorBuilder: (context, error, stackTrace) => const SizedBox.shrink(),+ );+ }++ /// Swift trims a long tab title to head…tail at 76 characters; the same+ /// shape keeps a wide History menu from pushing the panel wide.+ String _entryTitle(SwarmMenuEntry entry) {+ final title = entry.title;+ if (title.length <= 76) return title;+ return '${title.substring(0, 48)}…${title.substring(title.length - 24)}';+ }++ // A section heading — the small quiet line AppKit's section headers draw.+ Widget _header(String text) =>+ _MenuLabelRow(text, color: grid.AppPalette.textFaint, fontSize: 11.5);++ // A disabled row: an empty state, a provider with no reading behind it, a+ // command the current pane cannot take.+ Widget _label(String text, {String? note, bool faint = false}) =>+ _MenuLabelRow(text, note: note, faint: faint);+}++/// A non-interactive menu row, matched to [AppMenuItem]'s metrics so a+/// disabled row sits where an enabled one would.+class _MenuLabelRow extends StatelessWidget {+ const _MenuLabelRow(+ this.label, {+ this.note,+ this.faint = false,+ this.color,+ this.fontSize,+ });++ final String label;+ final String? note;+ final bool faint;+ final Color? color;+ final double? fontSize;++ @override+ Widget build(BuildContext context) {+ grid.AppTheme.watch(context);+ final metrics = AppMenuRowMetrics.compact;+ final ink = faint+ ? grid.AppPalette.textFaint+ : grid.AppPalette.textSecondary;+ return Padding(+ padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 1),+ child: Padding(+ padding: metrics.padding,+ child: Row(+ children: [+ SizedBox(width: metrics.iconSize + 9),+ Flexible(+ child: Text(+ label,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: color ?? ink,+ fontFamily: grid.AppFont.sans,+ fontFamilyFallback: grid.AppFont.sansFallback,+ fontSize: fontSize ?? metrics.fontSize,+ height: 1.2,+ fontWeight: grid.AppFont.medium,+ ),+ ),+ ),+ if (note != null) ...[+ const SizedBox(width: 8),+ Flexible(+ child: Text(+ note!,+ maxLines: 1,+ overflow: TextOverflow.ellipsis,+ style: TextStyle(+ color: grid.AppPalette.textFaint,+ fontFamily: grid.AppFont.sans,+ fontFamilyFallback: grid.AppFont.sansFallback,+ fontSize: metrics.noteSize,+ height: 1.2,+ ),+ ),+ ),+ ],+ ],+ ),+ ),+ );+ }+}diff --git a/desktop/test/linux_menu_bar_test.dart b/desktop/test/linux_menu_bar_test.dartnew file mode 100644index 000000000..bf7f99bba--- /dev/null+++ b/desktop/test/linux_menu_bar_test.dart@@ -0,0 +1,312 @@+import 'package:flutter/material.dart';+import 'package:flutter/services.dart';+import 'package:flutter_test/flutter_test.dart';++import 'package:harness/screens/swarm_menu_bus.dart';+import 'package:harness/shared/theme/app_theme.dart';+import 'package:harness/widgets/linux_menu_bar.dart';++/// The Linux menu bar's wiring.+///+/// The bar is a mouse-shaped door onto the same surfaces the native menus+/// drive: the app-menu rows report through [LinuxMenuBar.onAction] and the+/// swarm rows dispatch through the bus with the SAME action strings the macOS+/// channel delivers. Those strings are the shared contract with+/// `_RootShellState.runAppMenuAction` and `SwarmScreen._onNative` — a typo in+/// one is a menu item that silently does nothing — so the tests pin strings+/// and arguments, not styling, which the other menus' tests already guard.+void main() {+ TestWidgetsFlutterBinding.ensureInitialized();++ final appActions = <String>[];+ final swarmCalls = <MethodCall>[];++ setUp(() {+ appActions.clear();+ swarmCalls.clear();+ swarmMenuBus.setHandler((call) async => swarmCalls.add(call));+ swarmMenuBus.send('update', {+ 'enabled': true,+ 'canReopen': true,+ 'canFind': true,+ 'canClosePane': true,+ 'canGoBack': true,+ 'canGoForward': true,+ });+ });++ tearDown(() {+ swarmMenuBus.setHandler(null);+ swarmMenuBus.send('update', {'enabled': false});+ swarmMenuBus.send('keymapState', {'contexts': {}});+ });++ Future<void> pumpBar(WidgetTester tester) async {+ tester.view.physicalSize = const Size(900 * 2, 700 * 2);+ tester.view.devicePixelRatio = 2;+ addTearDown(tester.view.reset);++ await tester.pumpWidget(+ MaterialApp(+ theme: buildAppTheme(brightness: Brightness.dark),+ home: Scaffold(+ body: Column(+ children: [+ LinuxMenuBar(+ onAction: (action) async => appActions.add(action),+ visible: true,+ ),+ const Expanded(child: SizedBox.shrink()),+ ],+ ),+ ),+ ),+ );+ }++ /// Taps the first hit-testable widget under [key].+ ///+ /// MenuAnchor keeps a closed menu's rows mounted but unhittable while its+ /// close animation unwinds, and a long menu scrolls its lower rows out of+ /// the panel's max height — so a raw find matches a row the pointer cannot+ /// reach. Scrolling to the row and waiting for a hit-testable match keeps+ /// the sequence deterministic without weakening what it asserts.+ Future<void> tap(WidgetTester tester, String key) async {+ for (var attempt = 0; attempt < 5; attempt++) {+ final candidates = find.byKey(Key(key));+ if (candidates.evaluate().isNotEmpty) {+ await tester.ensureVisible(candidates.first);+ await tester.pumpAndSettle();+ final tappable = candidates.hitTestable();+ if (tappable.evaluate().isNotEmpty) {+ await tester.tap(tappable.first);+ await tester.pumpAndSettle();+ return;+ }+ }+ await tester.pump(const Duration(milliseconds: 50));+ }+ fail('no tappable widget for $key');+ }++ testWidgets('stays off the screen when not visible', (tester) async {+ await tester.pumpWidget(+ MaterialApp(+ home: Scaffold(+ body: LinuxMenuBar(onAction: (_) async {}, visible: false),+ ),+ ),+ );++ expect(find.text('File'), findsNothing);+ expect(find.text('History'), findsNothing);+ expect(find.text('View'), findsNothing);+ });++ testWidgets('the Harness menu carries the app-menu commands', (tester) async {+ await pumpBar(tester);++ await tap(tester, 'menu-bar-harness');+ await tap(tester, 'menu-bar-about');+ expect(appActions.last, 'showAbout');++ await tap(tester, 'menu-bar-harness');+ await tap(tester, 'menu-bar-customize');+ expect(swarmCalls.last.method, 'customize');++ await tap(tester, 'menu-bar-harness');+ await tap(tester, 'menu-bar-shortcuts');+ expect(appActions.last, 'showShortcuts');++ await tap(tester, 'menu-bar-harness');+ await tap(tester, 'menu-bar-check-for-updates');+ expect(appActions.last, 'checkForUpdates');++ await tap(tester, 'menu-bar-harness');+ await tap(tester, 'menu-bar-flash-firmware');+ expect(appActions.last, 'flashFirmware');+ });++ testWidgets('the File menu fires the native action strings', (tester) async {+ await pumpBar(tester);++ await tap(tester, 'menu-bar-file');+ await tap(tester, 'menu-bar-new-harness');+ expect(swarmCalls.last.method, 'newAgent');++ await tap(tester, 'menu-bar-file');+ await tap(tester, 'menu-bar-open-harness');+ expect(swarmCalls.last.method, 'addAgent');++ await tap(tester, 'menu-bar-file');+ await tap(tester, 'menu-bar-clone-agent');+ expect(swarmCalls.last.method, 'cloneAgent');++ // Kept off the File menu, as SwarmTitlebar.swift keeps it off.+ await tap(tester, 'menu-bar-file');+ expect(find.byKey(const Key('menu-bar-new-terminal')), findsNothing);+ await tap(tester, 'menu-bar-move-pane');+ expect(swarmCalls.last.method, 'movePaneToTab');++ await tap(tester, 'menu-bar-file');+ await tap(tester, 'menu-bar-close-tab');+ expect(swarmCalls.last.method, 'closeActive');+ });++ testWidgets('View reaches both channels', (tester) async {+ await pumpBar(tester);++ await tap(tester, 'menu-bar-view');+ await tap(tester, 'menu-bar-notifications');+ expect(swarmCalls.last.method, 'notifications');++ await tap(tester, 'menu-bar-view');+ await tap(tester, 'menu-bar-layout');+ expect(appActions.last, 'showLayout');++ await tap(tester, 'menu-bar-view');+ await tap(tester, 'menu-bar-bigger-font');+ expect(appActions.last, 'increaseTerminalFontSize');++ for (final (key, action) in [+ ('menu-bar-sessions', 'sessions'),+ ('menu-bar-machines', 'machineList'),+ ('menu-bar-models', 'models'),+ ('menu-bar-machine-monitor', 'manageMachines'),+ ]) {+ await tap(tester, 'menu-bar-view');+ await tap(tester, key);+ expect(swarmCalls.last.method, action);+ }+ });++ testWidgets('History navigates and reopens from the state', (tester) async {+ swarmMenuBus.send('update', {+ 'enabled': true,+ 'canGoBack': true,+ 'history': [+ {+ 'id': 'visited-1',+ 'title': 'Codex on workstation',+ 'machineName': 'workstation',+ 'current': true,+ },+ ],+ 'closedHistory': [+ {'id': 'closed-1', 'title': 'Claude on laptop', 'canReopen': true},+ {'id': 'closed-2', 'title': 'Gone for good', 'canReopen': false},+ ],+ });+ await pumpBar(tester);++ await tap(tester, 'menu-bar-history');+ await tap(tester, 'menu-bar-history-back');+ expect(swarmCalls.map((c) => c.method), ['historyBack']);++ await tap(tester, 'menu-bar-history');+ await tap(tester, 'menu-bar-visited-visited-1');+ expect(swarmCalls.last.method, 'historyDestination');+ expect(swarmCalls.last.arguments, {'id': 'visited-1'});++ await tap(tester, 'menu-bar-history');+ await tap(tester, 'menu-bar-closed-closed-1');+ expect(swarmCalls.last.method, 'reopenHistory');+ expect(swarmCalls.last.arguments, {'id': 'closed-1'});++ // A closed tab that cannot reopen draws as a label, not a row.+ await tap(tester, 'menu-bar-history');+ expect(find.byKey(const Key('menu-bar-closed-closed-2')), findsNothing);+ expect(find.text('Gone for good'), findsOneWidget);+ });++ testWidgets('pane rows follow what the focused pane can take', (+ tester,+ ) async {+ swarmMenuBus.send('update', {+ 'enabled': true,+ 'canFind': false,+ 'canClosePane': false,+ 'paneActions': {'restartAgent': true, 'shareAgent': false},+ });+ await pumpBar(tester);++ await tap(tester, 'menu-bar-file');+ await tap(tester, 'menu-bar-restart-agent');+ expect(swarmCalls.last.method, 'restartAgent');++ // No pane to act on: the rows validateMenuItem would disable draw as labels.+ await tap(tester, 'menu-bar-file');+ for (final key in [+ 'menu-bar-share-agent',+ 'menu-bar-split-right',+ 'menu-bar-zoom-pane',+ 'menu-bar-close-pane',+ ]) {+ expect(find.byKey(Key(key)), findsNothing, reason: key);+ }+ expect(find.text('Share Harness'), findsOneWidget);+ await tap(tester, 'menu-bar-file');++ await tap(tester, 'menu-bar-edit');+ expect(find.byKey(const Key('menu-bar-find-terminal')), findsNothing);+ await tap(tester, 'menu-bar-commands');+ expect(swarmCalls.last.method, 'commands');+ });++ testWidgets('rows show the chord the keymap gives their action', (+ tester,+ ) async {+ swarmMenuBus.send('keymapState', {+ 'version': 1,+ 'contexts': {+ 'terminal': [+ {+ 'command': 'agent.new',+ 'hint': 'Ctrl+Alt+N',+ 'menuAction': 'newAgent',+ },+ ],+ 'workspace': [+ {'command': 'agent.new', 'hint': 'Super+N', 'menuAction': 'newAgent'},+ {'command': 'keyboard.quick_start', 'hint': 'Super+K Q'},+ ],+ },+ });+ await pumpBar(tester);++ // The workspace binding wins: it is the one that works from anywhere.+ await tap(tester, 'menu-bar-file');+ expect(find.text('Super+N'), findsOneWidget);+ expect(find.text('Ctrl+Alt+N'), findsNothing);+ await tap(tester, 'menu-bar-file');++ // Quick Start sends the keymap command itself, as the macOS Help row does,+ // and shows that command's chord.+ await tap(tester, 'menu-bar-help');+ expect(find.text('Super+K Q'), findsOneWidget);+ await tap(tester, 'menu-bar-quick-start');+ expect(swarmCalls.last.method, 'keymapCommand');+ expect(swarmCalls.last.arguments, {'command': 'keyboard.quick_start'});++ await tap(tester, 'menu-bar-help');+ await tap(tester, 'menu-bar-keyboard-practice');+ expect(appActions.last, 'keyboardPractice');+ });++ testWidgets('rows go quiet while the app cannot take them', (tester) async {+ swarmMenuBus.send('update', {+ 'enabled': false,+ 'canGoBack': false,+ 'canReopen': false,+ });+ await pumpBar(tester);++ await tap(tester, 'menu-bar-file');+ expect(find.byKey(const Key('menu-bar-clone-agent')), findsNothing);+ expect(find.text('Clone Harness'), findsOneWidget);++ await tap(tester, 'menu-bar-history');+ expect(find.byKey(const Key('menu-bar-history-back')), findsNothing);+ expect(find.text('Back'), findsOneWidget);+ });+}