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
refactor(desktop): open Models from the View menu (#303)
Deec44a2b99b419
diff --git a/.github/assets/models-view-menu/README.md b/.github/assets/models-view-menu/README.mdnew file mode 100644index 000000000..731d1299f--- /dev/null+++ b/.github/assets/models-view-menu/README.md@@ -0,0 +1,16 @@+# Models in View++`models-panel.png` shows the shared Models panel opened through **View → Models**+in the isolated `desktop/tool/models_review.dart` app. All accounts, models,+usage values, and workspace content are synthetic fixtures.++The native accessibility tree confirmed this menu structure:++```text+Harness File Edit View History Window Help+ └ Models ⌘I+```++The brain toolbar icon opens the same panel. The menu popover itself was not+available to the screenshot tool; its placement, action, shortcut, remapping,+and disabled state are also checked by `tool/swarm_titlebar_checks.swift`.diff --git a/.github/assets/models-view-menu/models-panel.png b/.github/assets/models-view-menu/models-panel.pngnew file mode 100644index 000000000..4b37368dfBinary files /dev/null and b/.github/assets/models-view-menu/models-panel.png differdiff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 71469c4cb..051e7a432 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -228,7 +228,6 @@ class _SwarmScreenState extends State<SwarmScreen>String? _nativeState;List<Object?>? _machinesPresentation;ModelsMenuController? _modelsMenu;- String? _modelsState;final _defaultKeymap = AppKeymap();AppKeymap? _providedKeymap;AppKeymap get _keymap => _providedKeymap ?? _defaultKeymap;@@ -298,14 +297,9 @@ class _SwarmScreenState extends State<SwarmScreen>});}if (_native) {- _modelsMenu!.addListener(_syncModels);- // Same trigger as the subscription rows: the daemon memoises its answer, so opening the menu- // repeatedly costs nothing after the first.- unawaited(_refreshLocalModels());_channel.setMethodCallHandler(_onNative);app.addListener(_syncNative);_syncNative();- _syncModels();}}@@ -387,12 +381,8 @@ class _SwarmScreenState extends State<SwarmScreen>_commandFocus.dispose();if (_hasCommandBar) _commandBar.dispose();unawaited(_spokenTasks?.cancel());- _modelsMenu?.removeListener(_syncModels);if (widget.modelsMenu == null) _modelsMenu?.dispose();if (_native) {- unawaited(- _channel.invokeMethod<void>('modelsState', {'subscriptions': []}),- );unawaited(_channel.invokeMethod<void>('machinesState', {'machines': []}));app.removeListener(_syncNative);_channel.setMethodCallHandler(null);@@ -759,10 +749,6 @@ class _SwarmScreenState extends State<SwarmScreen>}void _syncNative() {- // ⚠️ Also from here, not only from `initState`. At init the machine list is still empty, so the- // first read returned nothing and the Local section sat on its empty state forever. This fires- // on every app change, throttled, so it lands as soon as a machine appears.- unawaited(_refreshLocalModels());_syncMachines();final payload = {'enabled': _routeIsCurrent && !_dialogOpen && !_spokenPaletteOpen,@@ -959,113 +945,6 @@ class _SwarmScreenState extends State<SwarmScreen>);}- void _syncModels() {- final payload = {- 'subscriptions': _modelsMenu?.rows ?? [],- // Which subscription the menu marks as the one in use. The pane in focus decides, because- // "which account am I spending" is a question about the agent being looked at; a pane that- // has been moved onto a Local model is on no subscription, and then nothing is marked.- 'currentEngine': _currentSubscriptionEngine(),- // Back-compat: the own grid's models, as the native menu understood them before sections.- 'local': [- for (final s in _localSections)- if (s.own)- for (final m in s.models) {'id': m.id, 'node': m.node},- ],- // The picker's sections, own grid first then each shared grid — what the native menu draws.- 'sections': [- for (final s in _localSections)- {- 'name': s.name,- 'own': s.own,- 'models': [- for (final m in s.models) {'id': m.id, 'node': m.node},- ],- },- ],- };- final encoded = jsonEncode(payload);- if (encoded == _modelsState) return;- _modelsState = encoded;- unawaited(_channel.invokeMethod<void>('modelsState', payload));- }-- /// The focused pane's engine while that pane runs on its own login, else null.- String? _currentSubscriptionEngine() {- final pane = app.focusedPane;- if (pane == null) return null;- final agent = app.machineStates[pane.machineId]?.agents- .where((a) => a.id == pane.agentId)- .firstOrNull;- if (agent == null || agent.gridModel != null) return null;- return agent.engine?.trim().toLowerCase();- }-- /// What the picker's sections answer for the native Models menu.- ///- /// Read from a machine this window is connected to — the grid is per ACCOUNT, so any of them- /// answers the same, and the local one is asked first because its daemon is a loopback away.- /// Never throws and never blocks the menu: a machine that cannot answer leaves the list as it was.- List<GridSection> _localSections = const [];-- DateTime? _localModelsAt;-- Future<void> _refreshLocalModels() async {- final machines = app.machines- .where((machine) => !machine.isShared)- .toList();- if (machines.isEmpty) return;- // The daemon memoises its answer, so a repeat is nearly free — but this is called on every app- // change, and an RPC per keystroke-sized notification is not free. One read per window is- // plenty for a list that changes when someone starts or stops serving a model.- final now = DateTime.now();- final last = _localModelsAt;- if (last != null && now.difference(last) < const Duration(seconds: 10)) {- return;- }- _localModelsAt = now;- final preferred = machines.firstWhere(- (m) => app.stateOf(m.machineId)?.isLocalMachine == true,- orElse: () => machines.first,- );- final answer = await app.gridModels(preferred.machineId);- if (!mounted) return;- final sections = _sectionsForModelMenu(answer);- if (_sameSections(sections, _localSections)) return;- _localSections = sections;- _syncModels();- }-- /// The sections the Models menu draws, matching the pane picker's own: the account's own grid- /// first as "Local", then each shared grid that serves something. A shared grid with nothing- /// running is not a menu a person can pick from, so it is not drawn.- List<GridSection> _sectionsForModelMenu(GridModels answer) {- final sections = answer.sections- .where((s) => s.own || s.models.isNotEmpty)- .toList();- if (sections.any((s) => s.own)) return sections;- return [- GridSection(- name: answer.gridName ?? '',- own: true,- models: answer.models,- ),- ...sections,- ];- }-- static bool _sameSections(List<GridSection> a, List<GridSection> b) {- if (a.length != b.length) return false;- for (var i = 0; i < a.length; i++) {- if (a[i].name != b[i].name || a[i].own != b[i].own) return false;- if (a[i].models.length != b[i].models.length) return false;- for (var j = 0; j < a[i].models.length; j++) {- if (a[i].models[j].id != b[i].models[j].id) return false;- }- }- return true;- }-Future<void> _onNative(MethodCall call) async {if (mounted && call.method == 'keymapPending') {final keys = (call.arguments as Map?)?['keys'];@@ -1101,10 +980,6 @@ class _SwarmScreenState extends State<SwarmScreen>await WidgetsBinding.instance.endOfFrame;return;}- if (call.method == 'modelsOpened') {- await _modelsMenu?.refresh();- return;- }final nativeCommand = switch (call.method) {'keymapCommand' =>args['command'] is String ? args['command'] as String : null,diff --git a/desktop/lib/usage/models_menu_controller.dart b/desktop/lib/usage/models_menu_controller.dartindex e39b3484b..3f384fffe 100644--- a/desktop/lib/usage/models_menu_controller.dart+++ b/desktop/lib/usage/models_menu_controller.dart@@ -7,7 +7,7 @@ import 'usage_accounts.dart';import 'usage_controller.dart';import 'usage_window.dart';-/// Subscription readings for the native Models menu. Opening the menu reads+/// Subscription readings for the Models panel. Opening the panel reads/// the cached snapshot immediately and refreshes at most once per minute./// No polling, credential reads or requests run on startup or tab changes.class ModelsMenuController extends ChangeNotifier {diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex 8772b9687..6b4c021d9 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -23,9 +23,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {private var history: [SwarmHistoryEntry] = []private var closedHistory: [SwarmHistoryEntry] = []private let historyIcons = SwarmHistoryIcons()- private let modelsMenu = NSMenu(title: "Models")private var machines: [SwarmMachineEntry] = []- private var subscriptions: [SwarmSubscriptionEntry] = []private var keymap: HarnessNativeKeymap?private var flutterKeyContext = "workspace"private var tabActionGeneration = 0@@ -72,15 +70,6 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {case "sessionMinimized":self.strip.sessionsButton.receiveSession()result(nil)- case "modelsState":- let state = call.arguments as? [String: Any] ?? [:]- self.updateModels(- state["subscriptions"] as? [[String: Any]] ?? [],- current: state["currentEngine"] as? String,- local: state["local"] as? [[String: Any]] ?? [],- sections: state["sections"] as? [[String: Any]] ?? []- )- result(nil)case "playAlert":// A named macOS system sound. Every Mac has these, so no audio asset ships with the app,// nothing has to be decoded, and the alert plays at whatever volume the person has set for@@ -240,7 +229,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {}private func installWorkspaceMenus() {- guard let main = NSApp.mainMenu, main.item(withTitle: "Models") == nil else { return }+ guard let main = NSApp.mainMenu, main.item(withTitle: "History") == nil else { return }// The stock Flutter nib includes a disabled Preferences placeholder. Make// the app-menu command work, and give ⌘, a single native owner.if let appMenu = main.item(at: 0)?.submenu {@@ -320,12 +309,9 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {view.addItem(.separator())add(view, "Harnesses Needing Input…", "i", "notifications", [.command, .shift])add(view, "Machines", "m", "machineList")+ add(view, "Models", "i", "models")add(view, "Machine Monitor", "", "manageMachines")}- modelsMenu.autoenablesItems = false- modelsMenu.delegate = self- rebuildModelsMenu()- install(modelsMenu, at: main.items.firstIndex(where: { $0.title == "Window" }) ?? main.numberOfItems)installTerminalFindMenu(main)}@@ -343,10 +329,6 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {row.needsDisplay = true}}- guard menu === modelsMenu, actionsEnabled else { return }- // The native menu opens from its cache. Network/credential reads happen- // asynchronously in Dart and never hold up AppKit's menu tracking.- channel.invokeMethod("modelsOpened", arguments: nil)}func menuDidClose(_ menu: NSMenu) {@@ -357,144 +339,6 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {let entries = rows.prefix(128).compactMap(SwarmMachineEntry.init)guard entries != machines else { return }machines = entries- // The Models menu's last row lists these too (see `rebuildModelsMenu`), so it is rebuilt on- // the same change rather than waiting for the next models push to catch up.- rebuildModelsMenu()- }-- /// One heading's worth of the picker: the account's own grid ("Local") or a shared grid, with- /// the models it is serving. `own` picks the heading word; `name` names a shared grid under the- /// "Models shared with you" header, or is empty for the account's own grid.- private struct MenuGridSection {- let name: String- let own: Bool- let models: [(String, String)] // (model id, node)- }-- private func updateModels(_ rows: [[String: Any]], current: String?, local: [[String: Any]] = [],- sections: [[String: Any]] = []) {- let entries = rows.prefix(32).compactMap(SwarmSubscriptionEntry.init)- // What the picker is actually serving RIGHT NOW, read off the machines that answer for it.- // Placeholder names lived here before and read as real ones — a menu naming a model nobody is- // serving is worse than a menu admitting it has none.- func paired(_ models: [[String: Any]]) -> [(String, String)] {- models.prefix(32).compactMap {- guard let id = $0["id"] as? String, !id.isEmpty else { return nil }- return (id, $0["node"] as? String ?? "")- }- }- let parsed: [MenuGridSection]- if sections.isEmpty {- // Older Flutter pushes only `local` (the account's own grid). Fall back to one own section.- let own = paired(local)- parsed = own.isEmpty ? [] : [MenuGridSection(name: "", own: true, models: own)]- } else {- parsed = sections.prefix(16).compactMap { dict -> MenuGridSection? in- guard let name = dict["name"] as? String,- let own = dict["own"] as? Bool,- let models = dict["models"] as? [[String: Any]] else { return nil }- return MenuGridSection(name: name, own: own, models: paired(models))- }- }- guard entries != subscriptions || current != currentEngine- || !sectionsEqual(parsed, localSections) else { return }- subscriptions = entries- currentEngine = current- localSections = parsed- rebuildModelsMenu()- }-- private func sectionsEqual(_ a: [MenuGridSection], _ b: [MenuGridSection]) -> Bool {- guard a.count == b.count else { return false }- for (x, y) in zip(a, b) {- guard x.name == y.name, x.own == y.own,- x.models.map({ $0.0 }) == y.models.map({ $0.0 }),- x.models.map({ $0.1 }) == y.models.map({ $0.1 }) else { return false }- }- return true- }-- /// `(model id, node)` for every model the account's grids are serving, grouped by the grid that- /// serves it — the sections the picker draws, the account's own first.- private var localSections: [MenuGridSection] = []-- /// The engine of the pane in focus, when that pane is running on its own subscription — so the- /// menu can mark WHICH account is being spent. Null while the focused pane is on a Local model,- /// which is on no subscription at all.- private var currentEngine: String?-- private func rebuildModelsMenu() {- modelsMenu.removeAllItems()- func label(_ title: String, in menu: NSMenu) {- let item = NSMenuItem(title: title, action: nil, keyEquivalent: "")- item.isEnabled = false- menu.addItem(item)- }- func section(_ title: String) {- if #available(macOS 14.0, *) {- modelsMenu.addItem(NSMenuItem.sectionHeader(title: title))- } else {- label(title, in: modelsMenu)- }- }- section("Subscriptions")- // One width across every section. Measuring them separately let the menu's halves size- // independently, so the trailing column stepped in or out at each section break.- let allModels = localSections.flatMap { $0.models }- let metered = subscriptions.contains { $0.remaining != nil }- let balanceColumn = SwarmSubscriptionView.balanceColumn(subscriptions)- let rowWidth = max(- subscriptions.map { SwarmSubscriptionView.preferredWidth($0, metered: metered) }.max() ?? 352,- allModels.map { SwarmSubscriptionView.preferredWidth(title: $0.0, account: "", status: $0.1) }.max() ?? 352)- for entry in subscriptions {- let item = NSMenuItem(title: entry.accessibilityLabel, action: nil, keyEquivalent: "")- // The tick marks the subscription the pane in focus is running on. A pane that has been moved- // to a Local model is on none of them, and then no row is ticked — which is the truth, not a- // gap: the menu would otherwise claim an account the agent is not spending.- item.view = SwarmSubscriptionView(entry: entry, width: rowWidth,- current: entry.engine != nil && entry.engine == currentEngine,- balanceColumn: balanceColumn)- item.isEnabled = false- modelsMenu.addItem(item)- }- if subscriptions.isEmpty {- label("Anthropic", in: modelsMenu)- label("OpenAI", in: modelsMenu)- }- // No API section. `OpenRouter` and `fal.ai` were placeholders with nothing behind them, and a- // menu naming providers this app cannot reach reads as a list of things you could pick. The- // section returns when there is a real source for it, not before.- modelsMenu.addItem(.separator())- // One section per grid, the account's own first. Its heading names the COMPUTER rather than the- // feature ("On this Mac"), because that is the fact that distinguishes it from the shared grids- // under it; a shared grid folds its name into its own heading rather than hanging it on a- // second line, which read as an entry of the same kind as the models beneath it.- if localSections.isEmpty {- section("On this Mac")- }- for (index, gridSection) in localSections.enumerated() {- if index > 0 { modelsMenu.addItem(.separator()) }- section(gridSection.own ? "On this Mac" : "Shared from \(gridSection.name)")- for (id, node) in gridSection.models {- // The same row view as the subscriptions above, so the menu reads as one list: the model id- // at full strength where a provider's name sits, and the node — which machine answers, the- // detail that makes a grid legible — in the trailing column the figures use. Local rows- // were plain disabled `NSMenuItem`s once, which AppKit greys wholesale, so a served model- // looked unavailable beside the accounts above.- let item = NSMenuItem(title: [id, node].filter { !$0.isEmpty }.joined(separator: ", "),- action: nil, keyEquivalent: "")- item.view = SwarmSubscriptionView(title: id, account: "", status: node,- icon: nil, width: rowWidth, accessibility: item.title)- item.isEnabled = false- modelsMenu.addItem(item)- }- }- modelsMenu.addItem(.separator())- let run = NSMenuItem(title: "Open Models…", action: #selector(menuAction(_:)), keyEquivalent: "")- run.identifier = NSUserInterfaceItemIdentifier(HarnessKeymapMenu.actionPrefix + "models")- run.target = self- run.representedObject = "models"- modelsMenu.addItem(run)}private func updateHistory(_ rows: [[String: Any]], closed: [[String: Any]] = []) {@@ -719,215 +563,6 @@ private struct SwarmMachineAgent: Equatable {}}-private struct SwarmSubscriptionEntry: Equatable {- let title: String- let account: String- let status: String- let details: [String]- let engine: String?- let iconAsset: String?- /// How much of the tightest window is left, 0…100. Absent whenever the status is not a figure —- /// "Usage unavailable", "Checking usage…" — so a meter is never drawn for a reading nobody has.- let remaining: Double?-- init?(_ row: [String: Any]) {- guard let title = row["title"] as? String, !title.isEmpty,- let status = row["status"] as? String else { return nil }- self.title = title- account = row["account"] as? String ?? ""- self.status = status- details = Array((row["details"] as? [String] ?? [status]).prefix(16))- engine = row["engine"] as? String- iconAsset = row["iconAsset"] as? String- remaining = row["remainingPercent"] as? Double- }-- /// Amber once the tightest window is nearly out, so the bar and the words agree.- static let lowWater: Double = 20-- var isLow: Bool { (remaining ?? 100) <= Self.lowWater }-- /// The figure, said the way the menu says it. Falls back to whatever sentence the reading had.- var balance: String { remaining.map { "\(Int($0.rounded(.down)))% left" } ?? status }-- var accessibilityLabel: String {- [title, account, status].filter { !$0.isEmpty }.joined(separator: ", ")- }-}----/// Read-only account information, with aligned trailing balances. There is no-/// action or submenu to suggest another step just to read the remaining usage.-/// The quota meter: a track, and however much of it is left.-///-/// Drawn rather than an `NSProgressIndicator`, which carries a bezel and an animation this row has-/// no use for and cannot recolour. Two rounded rects is the whole of it.-private final class SwarmQuotaBar: NSView {- var fraction: CGFloat = 0 { didSet { needsDisplay = true } }- var tint: NSColor = .controlAccentColor { didSet { needsDisplay = true } }-- override func draw(_ dirtyRect: NSRect) {- let radius = bounds.height / 2- NSColor.tertiaryLabelColor.withAlphaComponent(0.35).setFill()- NSBezierPath(roundedRect: bounds, xRadius: radius, yRadius: radius).fill()- guard fraction > 0 else { return }- // Never thinner than its own height: a sliver narrower than the cap radius draws as a dot- // that reads as nothing left rather than as nearly nothing left.- let width = max(bounds.height, bounds.width * min(1, fraction))- tint.setFill()- NSBezierPath(roundedRect: NSRect(x: 0, y: 0, width: width, height: bounds.height),- xRadius: radius, yRadius: radius).fill()- }-}--private final class SwarmSubscriptionView: NSView {- private static let rowFont = NSFont.menuFont(ofSize: 0)- let identity = NSTextField(labelWithString: "")- let balance = NSTextField(labelWithString: "")- private let icon = NSImageView()- private let meter = SwarmQuotaBar()- private let tick = NSImageView()- /// The meter's own column, when the row has one. Wide enough to read as a quantity at a glance- /// and narrow enough to leave the identity its own room.- private static let meterWidth: CGFloat = 76- /// The tick's column, RESERVED on every row so a row becoming the current one does not shift- /// the figure beside it.- private static let tickWidth: CGFloat = 18-- private static func textWidth(_ text: String) -> CGFloat {- // Include the native text cell's horizontal drawing insets. Measuring only- // glyphs or a label already constrained by its frame can clip the status.- ceil((text as NSString).size(withAttributes: [.font: rowFont]).width) + 8- }-- static func preferredWidth(_ entry: SwarmSubscriptionEntry) -> CGFloat {- preferredWidth(title: entry.title, account: entry.account, status: entry.status)- }-- static func preferredWidth(title: String, account: String, status: String) -> CGFloat {- let identityWidth = textWidth(title + " " + account)- let balanceWidth = textWidth(status)- return min(576, max(352, identityWidth + balanceWidth + 88))- }-- static func preferredWidth(_ entry: SwarmSubscriptionEntry, metered: Bool) -> CGFloat {- let base = preferredWidth(title: entry.title, account: entry.account, status: entry.balance)- return metered ? min(576, base + meterWidth + 12) : base- }-- /// The orange a nearly-spent account is written in, legible in both appearances.- ///- /// `.systemOrange` is tuned to be *seen*, not to be *read*: on the light menu- /// it measures 1.86:1 against the panel, where text wants 4.5:1. It is only- /// right on the dark one, where it reaches 6.44:1. The light side takes the- /// same hue carried down to #A85400 (4.52:1). Measured with tool/contrast.py.- static let lowInk = NSColor(name: "harnessLowInk") { appearance in- appearance.bestMatch(from: [.aqua, .darkAqua]) == .darkAqua- ? .systemOrange- : NSColor(srgbRed: 168 / 255, green: 84 / 255, blue: 0, alpha: 1)- }-- /// What the trailing figures need to share a column — the widest of them.- static func balanceColumn(_ entries: [SwarmSubscriptionEntry]) -> CGFloat {- entries.map { textWidth($0.balance) }.max() ?? 0- }-- convenience init(entry: SwarmSubscriptionEntry, width: CGFloat, current: Bool,- balanceColumn: CGFloat) {- self.init(title: entry.title, account: entry.account.isEmpty ? "" : "···" + entry.account,- status: entry.balance, icon: nil, width: width,- accessibility: entry.accessibilityLabel + (current ? ", current" : ""),- tint: nil, meter: entry.remaining.map { $0 / 100 },- meterTint: entry.isLow ? Self.lowInk : .controlAccentColor,- balanceTint: entry.isLow ? Self.lowInk : .secondaryLabelColor,- showsTick: current, balanceColumn: balanceColumn)- }-- /// Every row in this menu is built here, subscription or local. Sharing the construction is what- /// keeps the two sections reading as one menu: same font, same label/secondary split, same icon- /// column, same right-aligned trailing field. Local rows were plain disabled `NSMenuItem`s before,- /// which AppKit greys wholesale, so a served model looked unavailable beside the accounts above.- init(title primary: String, account: String, status: String, icon: NSImage?, width: CGFloat,- accessibility: String, tint: NSColor? = nil, meter: Double? = nil,- meterTint: NSColor = .controlAccentColor, balanceTint: NSColor = .secondaryLabelColor,- showsTick: Bool = false, balanceColumn: CGFloat = 0) {- super.init(frame: NSRect(x: 0, y: 0, width: width, height: 26))- autoresizingMask = [.width]- self.icon.image = icon- self.icon.imageScaling = .scaleProportionallyDown- // Brand artwork carries its own colour; an SF Symbol arrives as a template and would paint flat- // black without this, which reads as a hole in the row on a dark menu.- self.icon.contentTintColor = tint- let title = NSMutableAttributedString(string: primary,- attributes: [.font: Self.rowFont, .foregroundColor: NSColor.labelColor])- if !account.isEmpty {- title.append(NSAttributedString(string: " " + account,- attributes: [.font: Self.rowFont, .foregroundColor: NSColor.secondaryLabelColor]))- }- identity.attributedStringValue = title- identity.usesSingleLineMode = true- identity.lineBreakMode = .byTruncatingMiddle- balance.stringValue = status- balance.font = Self.rowFont- balance.textColor = balanceTint- balance.alignment = .right- balance.usesSingleLineMode = true- balance.lineBreakMode = .byClipping- self.meter.isHidden = meter == nil- self.meter.fraction = CGFloat(meter ?? 0)- self.meter.tint = meterTint- self.hasMeter = meter != nil- self.balanceColumn = balanceColumn- tick.image = showsTick- ? NSImage(systemSymbolName: "checkmark", accessibilityDescription: nil)- : nil- tick.contentTintColor = .labelColor- tick.imageScaling = .scaleProportionallyDown- for view in [self.icon, identity, balance, self.meter, tick] {- addSubview(view)- view.setAccessibilityElement(false)- }- setAccessibilityElement(true)- setAccessibilityRole(.staticText)- setAccessibilityLabel(accessibility)- layout()- }-- required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }-- private var hasMeter = false-- /// The width every row's trailing figure is laid out in, so the meters beside them start at one- /// x rather than each one floating off the width of its own text.- ///- /// Sizing the figure to itself right-aligns the TEXT correctly — every row shares a right edge —- /// but it moves that column's LEFT edge per row, and the meter hangs off that. `7% left` is- /// narrower than `78% left`, so one bar began further right than the other and the two read as- /// different lengths. Zero means "size to my own text", for rows with no meter to align.- private var balanceColumn: CGFloat = 0-- override func layout() {- super.layout()- icon.frame = NSRect(x: 16, y: (bounds.height - 16) / 2, width: 16, height: 16)- let height = ceil(Self.rowFont.ascender - Self.rowFont.descender + Self.rowFont.leading)- // The tick's column is reserved whether or not this row draws one — see [tickWidth].- tick.frame = NSRect(x: bounds.width - 16 - 13, y: (bounds.height - 13) / 2, width: 13, height: 13)- let balanceWidth = max(balanceColumn, Self.textWidth(balance.stringValue))- balance.frame = NSRect(x: bounds.width - 16 - Self.tickWidth - balanceWidth,- y: (bounds.height - height) / 2, width: balanceWidth, height: height)- if hasMeter {- meter.frame = NSRect(x: balance.frame.minX - 10 - Self.meterWidth,- y: (bounds.height - 5) / 2, width: Self.meterWidth, height: 5)- }- // No icon column: the rows carry no artwork, so the text starts where a menu's text starts.- let identityLeft: CGFloat = icon.image == nil ? 16 : 40- let identityRight = hasMeter ? meter.frame.minX : balance.frame.minX- identity.frame = NSRect(x: identityLeft, y: balance.frame.minY,- width: max(0, identityRight - 16 - identityLeft), height: height)- }-}-/// A History row uses the full menu width; shortcut columns belong to commands./// Native item titles/actions still own type-select, validation and activation.private final class SwarmHistoryMenuRow: NSView {diff --git a/desktop/test/models_menu_test.dart b/desktop/test/models_menu_test.dartindex 70732adee..699e62373 100644--- a/desktop/test/models_menu_test.dart+++ b/desktop/test/models_menu_test.dart@@ -275,7 +275,7 @@ void main() {);testWidgets(- 'native Models opens lazily without changing the swarm or search',+ 'View Models refreshes subscriptions only when the shared panel opens',(tester) async {const channel = MethodChannel('harness/swarm_tabs');final messenger = tester.binding.defaultBinaryMessenger;@@ -308,39 +308,29 @@ void main() {),);expect(source.calls, 0);- final previousUpdates = messages- .where((c) => c.method == 'update')- .length;final reply = Completer<void>();messenger.handlePlatformMessage(channel.name,const StandardMethodCodec().encodeMethodCall(- const MethodCall('modelsOpened'),+ const MethodCall('models'),),(_) => reply.complete(),);- await reply.future;- await tester.pump();+ await tester.pumpAndSettle();+ expect(reply.isCompleted, isTrue);expect(source.calls, 1);expect(app.activeSwarmId, original);- expect(- messages.where((c) => c.method == 'update').length,- previousUpdates,- );- expect(messages.where((c) => c.method == 'closeSearch'), isEmpty);- final snapshot =- messages.lastWhere((c) => c.method == 'modelsState').arguments as Map;- expect((snapshot['subscriptions'] as List).single['title'], 'OpenAI');- expect(- (snapshot['subscriptions'] as List).single['status'],- 'Not signed in',- );+ expect(find.byType(ModelsPanel), findsOneWidget);+ expect(find.text('OpenAI'), findsOneWidget);+ expect(find.text('Not signed in'), findsOneWidget);+ expect(messages.where((c) => c.method == 'modelsState'), isEmpty);+ await tester.sendKeyEvent(LogicalKeyboardKey.escape);+ await tester.pumpAndSettle();+ expect(find.byType(ModelsPanel), findsNothing);+ expect(app.activeSwarmId, original);await tester.pumpWidget(const SizedBox());- expect(- (messages.lastWhere((c) => c.method == 'modelsState').arguments- as Map)['subscriptions'],- isEmpty,- );+ expect(source.calls, 1);+ expect(messages.where((c) => c.method == 'modelsState'), isEmpty);menu.dispose();usage.dispose();app.dispose();@@ -348,7 +338,7 @@ void main() {},);- /// Mount the swarm screen on [app] and send the native Models menu's+ /// Mount the swarm screen on [app] and send the native local-model/// `runLocalModel` command, with or without a machine.Future<void> openGridDoor(WidgetTester tester,diff --git a/desktop/tool/swarm_titlebar_checks.swift b/desktop/tool/swarm_titlebar_checks.swiftindex a84c99db1..c62a20b55 100644--- a/desktop/tool/swarm_titlebar_checks.swift+++ b/desktop/tool/swarm_titlebar_checks.swift@@ -32,12 +32,6 @@ private extension NSButton {}}-private extension SwarmSubscriptionView {- // `icon` is private to the row view; a same-file extension reads it without widening the app API.- var iconImage: NSImage? { icon.image }- var iconTint: NSColor? { icon.contentTintColor }-}-private extension SwarmTabButton {// `label` is private to the tab; a same-file extension reads what it draws.var drawnFont: NSFont? { label.attribute(.font, at: 0, effectiveRange: nil) as? NSFont }@@ -532,6 +526,7 @@ private extension SwarmTitlebar {let agent = original.item(withTitle: "File")!.submenu!let newSwarm = agent.items.first(where: { $0.representedObject as? String == "new" })!let addHarness = agent.items.first(where: { $0.representedObject as? String == "addAgent" })!+ let models = original.item(withTitle: "View")!.submenu!.items.first { $0.representedObject as? String == "models" }!let nativeCopy = NSMenuItem(title: "Copy", action: #selector(NSText.copy(_:)), keyEquivalent: "c")edit.addItem(nativeCopy)setKeymap(defaults)@@ -547,6 +542,14 @@ private extension SwarmTitlebar {try checkTitlebar(split.keyEquivalent == key && split.keyEquivalentModifierMask == [.command],"The exported keymap preserves the native \(action) shortcut")}+ try checkTitlebar(models.keyEquivalent == "i" && models.keyEquivalentModifierMask == [.command],+ "The exported keymap gives View Models the same Command-I shortcut")+ let remappedModels = HarnessNativeKeymap(["version": 1, "contexts": Dictionary(uniqueKeysWithValues:+ HarnessNativeKeymap.contexts.map { ($0, [["keys": ["cmd+u"], "command": "models.list",+ "hint": "⌘U", "repeatable": false, "menuAction": "models"]]) })])!+ setKeymap(remappedModels)+ try checkTitlebar(models.keyEquivalent == "u" && strip.modelsButton.toolTip == "Models ⌘U",+ "Remapping Models updates both the View menu and the brain icon hint")setKeymap(changed)try checkTitlebar(NSApp.mainMenu === main && newSwarm.keyEquivalent == "o","Hot reload updates the existing menu to the remapped key")@@ -563,6 +566,8 @@ private extension SwarmTitlebar {setKeymap(HarnessNativeKeymap(["version": 1, "contexts": ["workspace": [], "terminal": [], "picker": [], "project": []]])!)try checkTitlebar(newSwarm.keyEquivalent.isEmpty && newSwarm.toolTip == nil,"Unbinding clears the old native shortcut and hint")+ try checkTitlebar(models.keyEquivalent.isEmpty,+ "Unbinding Models clears its View menu shortcut")rebuildHistoryMenu()try checkTitlebar(historyMenu.items.allSatisfy { $0.keyEquivalent.isEmpty },"Rebuilt History rows retain effective unbindings")@@ -716,7 +721,7 @@ private extension SwarmTitlebar {try window.checkContentCommand()try checkTitlebar(window.firstResponder === window.contentInput,"Adding toolbar buttons does not take initial keyboard focus from the workspace")- try checkTitlebar(main.items.map(\.title) == ["Harness", "File", "Edit", "View", "History", "Models", "Window", "Help"], "Machines lives in the toolbar and View menu")+ try checkTitlebar(main.items.map(\.title) == ["Harness", "File", "Edit", "View", "History", "Window", "Help"], "Models and Machines live in the toolbar and View menu")let settings = appItem.submenu!.items.first { $0.representedObject as? String == "settings" }!try checkTitlebar(settings.title == "Settings…" && settings.representedObject as? String == "settings", "Settings stays in the application menu")let agent = main.item(withTitle: "File")!.submenu!@@ -944,39 +949,29 @@ private extension SwarmTitlebar {try checkTitlebar(main.items.compactMap(\.submenu).flatMap(\.items).allSatisfy {!["Next Swarm", "Previous Swarm"].contains($0.title)}, "Next and Previous Swarm have no redundant menu rows")- let modelRows: [[String: Any]] = [- ["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"]],- ]- updateModels(modelRows, current: nil)- let models = main.item(withTitle: "Models")!.submenu!- try checkTitlebar(models.items.filter { !$0.isSeparatorItem }.map(\.title) == [- "Subscriptions", "Anthropic, aabbcc, 12% remaining", "OpenAI, Not signed in",- "On this Mac", "Open Models…"- ], "Models carries the two sections with something behind them, ending on the row that starts a model")- try checkTitlebar(models.items.filter(\.isSeparatorItem).count == 2,- "Two native separators: after the subscriptions, and before the row that manages models")- for gone in ["API", "OpenRouter", "fal.ai", "Add Model"] {- try checkTitlebar(models.item(withTitle: gone) == nil,- "\(gone) is gone — it named nothing this app can reach or do")- }- let openModels = models.items.last!- try checkTitlebar(openModels.title == "Open Models…" && openModels.submenu == nil,- "The Models menu opens the shared overview")- try checkTitlebar(openModels.target === self && openModels.action == #selector(menuAction(_:))- && openModels.representedObject as? String == "models",- "The menu dispatches the same Models action as the toolbar")+ try checkTitlebar(main.item(withTitle: "Models") == nil,+ "Models has no duplicate top-level menu")+ let openModels = menu.items.first(where: { $0.representedObject as? String == "models" })!+ try checkTitlebar(openModels.title == "Models" && openModels.submenu == nil,+ "View offers one direct Models command")+ try checkTitlebar(openModels.keyEquivalent == "i" && openModels.keyEquivalentModifierMask == [.command],+ "View Models advertises Command-I")+ try checkTitlebar(openModels.target === self && openModels.action == #selector(menuAction(_:)),+ "View Models dispatches the same action as the toolbar")try checkTitlebar(openModels.identifier?.rawValue == HarnessKeymapMenu.actionPrefix + "models",- "The Models overview is identified for the keymap")+ "View Models retains its keymap identity")+ installWorkspaceMenus()+ try checkTitlebar(menu.items.filter { $0.representedObject as? String == "models" }.count == 1,+ "Repeated setup keeps a single Models command")for rows in [machineRows, [machineRows[0]], []] {_ = try messenger.receive("machinesState", arguments: ["machines": rows])- let item = main.item(withTitle: "Models")!.submenu!.items.last!- try checkTitlebar(item.title == "Open Models…" && item.submenu == nil- && item.representedObject as? String == "models",- "Any number of machines still opens the same Models overview")+ try checkTitlebar(menu.items.first(where: { $0.representedObject as? String == "models" }) === openModels,+ "Machine updates retain the same Models command")}+ let menuCalls = messenger.calls.count+ menuAction(openModels)+ try checkTitlebar(messenger.calls.count == menuCalls + 1 && messenger.calls.last?.method == "models",+ "View Models opens the shared panel exactly once")_ = try messenger.receive("update", arguments: ["enabled": true, "modelsOpen": true])try checkTitlebar(strip.modelsButton.state == .on && strip.modelsButton.isEnabled&& strip.modelsButton.accessibilityValue() as? String == "Expanded",@@ -993,77 +988,6 @@ private extension SwarmTitlebar {"Neither Models entry point dispatches behind a modal")actionsEnabled = true- // The Local section is DATA, not two hardcoded names. A menu naming a model nobody serves is- // worse than one admitting it has none, which is what the empty case above asserts.- updateModels(modelRows, current: nil, local: [- ["id": "Qwen3.6-35B-A3B-UD-Q5_K_XL", "node": "macbook-m1max"],- ["id": "DeepSeek-V4-Flash", "node": ""],- ])- let served = main.item(withTitle: "Models")!.submenu!- try checkTitlebar(served.item(withTitle: "Qwen3.6-35B-A3B-UD-Q5_K_XL, macbook-m1max") != nil,- "a served model names the machine answering it")- try checkTitlebar(served.item(withTitle: "DeepSeek-V4-Flash") != nil,- "a model with no node named is listed on its own")- try checkTitlebar(served.items.last?.title == "Open Models…"- && served.items[served.items.count - 2].isSeparatorItem- && served.items.filter(\.isSeparatorItem).count == 2,- "the manager row sits under its own rule, after the Local data rows")-- // A local row is built by the same view as a subscription row, which is what makes the two- // sections read as one menu. A plain disabled NSMenuItem greys its whole title, so a served- // model looked unavailable beside the accounts above it.- let localRows = served.items.compactMap { $0.view as? SwarmSubscriptionView }.suffix(2)- try checkTitlebar(localRows.count == 2, "Local models render as rows, not as greyed labels")- try checkTitlebar(localRows.first?.identity.stringValue == "Qwen3.6-35B-A3B-UD-Q5_K_XL"- && localRows.first?.balance.stringValue == "macbook-m1max",- "the model id takes the left column and its node the trailing one, as usage does above")- try checkTitlebar(localRows.last?.balance.stringValue.isEmpty == true,- "a model with no node leaves the trailing column empty rather than inventing one")- // The mark went when the Models menu was reworked: a local row now carries the id and its- // node alone, and the icon column stays empty rather than inventing a brand for it.- try checkTitlebar(localRows.allSatisfy { $0.iconImage == nil },- "a local model is named without a brand mark")- let subscriptionWidth = served.items.compactMap { $0.view as? SwarmSubscriptionView }.first!.bounds.width- try checkTitlebar(localRows.allSatisfy { $0.bounds.width == subscriptionWidth },- "both sections share one width, so the trailing column does not step at the section break")- try checkTitlebar(localRows.allSatisfy { $0.identity.frame.minX == served.items.compactMap({ $0.view as? SwarmSubscriptionView }).first!.identity.frame.minX },- "local and subscription titles start in the same column")- updateModels(modelRows, current: nil)- try checkTitlebar(models.item(withTitle: "No models being served") == nil,- "an empty Local says nothing — the run row is the answer, not a sentence")- let subscription = models.items.first(where: { $0.view is SwarmSubscriptionView })!- let row = subscription.view as! SwarmSubscriptionView- try checkTitlebar(subscription.submenu == nil && subscription.action == nil && !subscription.isEnabled,- "Subscription balances have no arrow or fake action")- // The account is elided on the way in — "···aabbcc" — so the row says which account without- // printing an id nobody reads in full.- 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")- // The meter sits between the two columns on a metered row, and the tick keeps its own column- // on the right whether or not this row wears one — so the balance ends short of the rim.- try checkTitlebar(row.identity.frame.maxX + 12 <= row.balance.frame.minX- && row.balance.frame.maxX == row.bounds.width - 34,- "Account and balance have a clear gap, and the balance clears the reserved tick column")- try checkTitlebar(row.identity.frame.midY == row.balance.frame.midY,- "Both columns share a vertical center")- try checkTitlebar(row.accessibilityLabel() == subscription.title,- "VoiceOver can read the provider, account and remaining usage together")- let secondRow = models.items.compactMap { $0.view as? SwarmSubscriptionView }.last!- for view in [row, secondRow] {- let cell = view.balance.cell!- let drawing = cell.drawingRect(forBounds: view.balance.bounds)- let glyphWidth = (view.balance.stringValue as NSString).size(withAttributes: [.font: view.balance.font!]).width- try checkTitlebar(view.bounds.width >= 352 && view.bounds.width < 440 && drawing.width >= glyphWidth,- "Remaining usage and sign-in status have enough actual text-cell width to display in full")- }- try checkTitlebar(secondRow.balance.frame.maxX == row.balance.frame.maxX,- "Different balances align on their right edges")- updateModels(modelRows, current: nil)- try checkTitlebar(models.items.contains(where: { $0 === subscription }),- "Unchanged subscription data reuses native menu items")- updateModels([], current: nil)- try checkTitlebar(models.items.allSatisfy { !$0.title.contains("12%") && $0.submenu == nil },- "Signing out clears cached native account readings")let findItems = find.submenu?.items ?? []try checkTitlebar(findItems.map(\.title) == ["Find in Terminal…", "Find Next", "Find Previous"], "Find replaces the unused editor actions with terminal commands")try checkTitlebar(findItems.map(\.keyEquivalent) == ["f", "g", "g"], "Native find shortcuts match Flutter")