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
Add notification previews and working overview to macOS menu (#505)
Dee9c0f053a9b46
diff --git a/desktop/README.md b/desktop/README.mdindex e11caff1d..a18f1bb5b 100644--- a/desktop/README.md+++ b/desktop/README.md@@ -189,14 +189,19 @@ upstream package upgrade without preserving the local rendering and IME fixes.On macOS, the Harness portrait symbol follows the system menu bar's appearance andcarries a small circular unread badge at its bottom-right corner,only when notifications are unread (`99+` above 99; the tooltip keeps the exact count). Open it for-sessions with unread results or questions, grouped-by project and marked with blue dots. Read sessions disappear from the list;-an empty inbox says “No unread notifications.” The menu also offers New Harness,-Clear All Notifications, Open Harness, Settings, and Quit. Selecting a-conversation reuses its existing pane and-brings the window forward. Clear All dismisses the displayed notifications-without answering pending questions or clearing newer arrivals. Linux and the-browser keep the in-window notification bell.+one Notifications section, with questions first and the newest results below.+Each row includes the question or completion recap, tab, machine, and arrival+time. The first five appear here; View all opens the full inbox. Read sessions+disappear, and an empty inbox says “No unread notifications.” Working expands+to show active sessions with elapsed time when the app observed their start;+idle sessions and sessions already listed above do not fill this section.+Working never contributes to the unread badge. New Harness and Open Harness+use the normal creation and existing-session pickers. Show Harness brings the+window forward; Quit exits the app. Selecting a conversation reuses its existing+pane before revealing the window. Mark all read acknowledges the opening+snapshot without answering pending questions or clearing newer arrivals.+Linux and the browser keep the in-window notification bell. GitHub merge+notifications are not part of this menu yet.The search icon to the left of Harness Store opens a compact list across yourmachines. Each harness shows its agent and name, followed by its machine, project,diff --git a/desktop/design/desktop-design-system.md b/desktop/design/desktop-design-system.mdindex fbd2535ef..0408df39f 100644--- a/desktop/design/desktop-design-system.md+++ b/desktop/design/desktop-design-system.md@@ -363,6 +363,16 @@ Companion and sharing controls sit after usage without shifting the context.at page scale. Related settings use grouping and whitespace. Existing artwork,terminal previews, native toolbar/footer components and domain-specific visualsretain their meaning. Read-only loading/error views use the same hierarchy.++**macOS notification menu** — one Notifications section with up to five unread+session rows and a route to the full inbox. Use a 13-point semibold session title,+12-point status and tab/machine context, and a 13-point message preview capped+at two lines. Retain the full text in accessibility and tooltips. Questions+precede results; each kind is newest first. Mark all read belongs beside the+heading. Working is a collapsed disclosure with compact title/context rows+and observed elapsed time. The unread count excludes work in progress. Use+native menu selection and system colors; no inner cards or decorative borders.+Settings stays in the application menu; this menu ends with Show Harness and Quit.Pane-resize guidance is app navigation: use the shared popover surface, systemtype and wrapping keyboard hints. It must not look like terminal output.diff --git a/desktop/design/desktop-ui-migration.md b/desktop/design/desktop-ui-migration.mdindex 9c2fb6631..e45c77105 100644--- a/desktop/design/desktop-ui-migration.md+++ b/desktop/design/desktop-ui-migration.md@@ -20,7 +20,7 @@ on 2026-09-30; the unmerged checkpoints below describe earlier review stages.| Sharing | Access/people/options, comments, observer sidebar, and viewer access/error states use desktop surfaces; existing sharing and authentication rules retained || Add Phone | Desktop QR/device layout implemented; pairing lifecycle tests and light/dark enlarged-text renders pass || Machine recovery/linking | Desktop linking/password layouts implemented; bounded selectable errors, fixed actions, and 32-point reveal controls tested/rendered |-| Notifications | Desktop popup, two-line rows, glyphs, and empty/error states implemented; unchanged event rules tested; live empty popup inspected |+| Notifications | macOS menu overview has receipt-bound message previews, tab/machine context, a collapsed Working section, and Mark all read; full desktop inbox remains available. Synthetic native light/dark, expanded, empty, long, selected and unavailable states inspected; live menu interaction still needs review || Branches / pull requests | Desktop lists and shared modal veil implemented; colored icons, readable status words, honest load failures, Page Up/Down tested and rendered || Settings / customization | Desktop status customization, natural-height controls, error contrast, keyboard focus and passive native footer preview implemented; actual status previews preserve the selected renderer || Store | Existing graphical discovery/detail/launch routes retained; ordinary labels, search and counts use system typography; desktop and narrow/enlarged previews inspected |@@ -38,6 +38,30 @@ The standalone MachinesManager, old machine-link dialog, and genericteam-creation presenter have no production caller in this tree. They are notcounted as completed user journeys. Shared controls still serve their tests.+## Notification overview review — 2026-09-30++The menu now presents questions and completed results together, with the actual+question or notified recap beneath the session title. Working expands inline;+its count excludes unread sessions already above it and never changes the badge.+Settings is removed from this menu and its last action is Quit. GitHub merge+events remain a follow-up rather than inferred notifications.++Native captures use synthetic sessions and the production AppKit views:+[light](images/notification-overview-light.png),+[dark](images/notification-overview-dark.png), and+[expanded Working](images/notification-overview-working.png). These are view+renders on neutral surfaces; they do not simulate the window-server blur.+The fixture also covers empty, long/truncated, highlighted, and offline rows.+Reproduce with `tool/check_swarm_titlebar.sh <flutter-sdk> --status-menu-preview`.++Validation: 67 targeted Flutter tests, 44 native menu checks, changed-file static+analysis, icon audit, and a signed Intel Skia debug build. Coverage includes+receipt-bound previews, same-session coalescing, unread/working separation,+known versus unknown elapsed time, stale clicks, snapshot clearing, tab moves,+existing-pane navigation, disclosure key handling, effective shortcut hints,+and sign-out cleanup. Physical pointer/keyboard tracking and VoiceOver in the+user's running app remain manual review items; this fixture is not that evidence.+## AI review panelThe user requested independent AI perspectives. These are design and engineeringdiff --git a/desktop/design/images/notification-overview-dark.png b/desktop/design/images/notification-overview-dark.pngnew file mode 100644index 000000000..99f43d001Binary files /dev/null and b/desktop/design/images/notification-overview-dark.png differdiff --git a/desktop/design/images/notification-overview-light.png b/desktop/design/images/notification-overview-light.pngnew file mode 100644index 000000000..d7be61bb4Binary files /dev/null and b/desktop/design/images/notification-overview-light.png differdiff --git a/desktop/design/images/notification-overview-working.png b/desktop/design/images/notification-overview-working.pngnew file mode 100644index 000000000..5ef791fa1Binary files /dev/null and b/desktop/design/images/notification-overview-working.png differdiff --git a/desktop/design/workspace-status-bar.md b/desktop/design/workspace-status-bar.mdindex 469062fe4..6b8a95d12 100644--- a/desktop/design/workspace-status-bar.md+++ b/desktop/design/workspace-status-bar.md@@ -219,25 +219,38 @@ At zero, only the portrait icon is shown, with no number or badge circle. The basits slightly outside the mark so both remain legible. The combined templateadapts to the menu bar's light, dark, and selected appearances. It keeps a fixed size, showing `99+`above 99 with the exact count in its tooltip and accessibility-value. Its native menu lists only harnesses with unread-notifications, grouped by their open tab's displayed name in tab order. Each-section lists its newest notifications first. Sessions outside open tabs appear-under “Other sessions” at the end. A session in multiple tabs appears once,-preferring the active tab, then the first tab containing it. Machine profiles-do not hide notification groups. Project and machine context stays in row-tooltips. Read sessions disappear; an empty inbox says “No unread-notifications.” Blue dots mark unread rows. Long titles truncate with-their full text and context in tooltips; unavailable rows are disabled. Rows-stay in place while the menu is open. New Harness and Open Harness open the-same creation and existing-session pickers as the workspace commands. Clear All-Notifications, Show Harness, Settings, and Quit follow. Show Harness only brings-the app window forward and stays available when workspace actions are disabled.-The window's titlebar-has search and Store without a duplicate bell.----Clear All acknowledges only the notifications in the displayed snapshot. Newer+value. The native menu has one Notifications section, with questions first,+then failures and completed results, newest first within each kind. Each row+shows a title, status, up to two lines of the actual question or notified recap,+and tab/machine context. Its age is when this app received the notification.+The recap stays bound to that unread receipt; later transcript text cannot+replace it. Show at most five notifications and a View all route to the full+inbox. A session in multiple tabs appears once, preferring the active tab,+then the first containing it. Machine profiles do not hide notifications.+Project context remains in tooltips. Blue dots mark unread rows; unavailable+rows remain visible and disabled. An empty inbox says “No unread notifications.”++Working is a collapsed inline disclosure. It shows active, known sessions that+are not already in Notifications, with elapsed time only when the app observed+their turn start. Exclude idle shells, paused/offline sessions, and waiting+questions. Show five compact rows, with additional sessions in a submenu.+Working never adds to the badge. Both sections keep their snapshot while open;+opening the disclosure must not insert new notifications under the pointer.+Keyboard Left/Right and Return/Space toggle the disclosure. Rows use native+selection, type-select, accessibility, and existing navigation receipts.++Mark all read sits beside the Notifications heading. New Harness and Open+Harness use the existing creation/session pickers and effective shortcut hints.+Show Harness and Quit finish the menu; Settings stays in the application menu.+Show Harness stays available while workspace actions are disabled. The window's+titlebar has Search and Store without a duplicate bell. GitHub merge tracking+is deferred; this first version does not invent merge events from focused PR state.++++++Mark all read acknowledges only the notifications in the opening snapshot. Newerresults and replacement questions stay unread. Opening a conversation restoresits existing pane in the displayed tab before bringing the window forward. Ifthat view moved or closed, navigation resolves the session's current location.diff --git a/desktop/lib/notify/agent_alerts.dart b/desktop/lib/notify/agent_alerts.dartindex 0caaae078..7bea45bc9 100644--- a/desktop/lib/notify/agent_alerts.dart+++ b/desktop/lib/notify/agent_alerts.dart@@ -160,6 +160,8 @@ class AgentUnread extends ChangeNotifier {final _unread = <String, AlertKind>{};final _tokens = <String, String>{};+ final _messages = <String, String>{};+ final _receivedAt = <String, DateTime>{};final _epoch = List.generate(12,(_) => Random.secure().nextInt(256),@@ -170,6 +172,13 @@ class AgentUnread extends ChangeNotifier {String? readTokenFor(String machineId, String agentId) =>_tokens[keyFor(machineId, agentId)];+ /// The message belongs to this unread receipt, never the session's latest+ /// transcript (which may already describe a different turn).+ String? messageFor(String machineId, String agentId) =>+ _messages[keyFor(machineId, agentId)];+ DateTime? receivedAtFor(String machineId, String agentId) =>+ _receivedAt[keyFor(machineId, agentId)];+static String keyFor(String machineId, String agentId) =>'$machineId/$agentId';@@ -208,10 +217,19 @@ class AgentUnread extends ChangeNotifier {String agentId,AlertKind kind, {bool fresh = false,+ String? message,+ DateTime? at,}) {final key = keyFor(machineId, agentId);if (!fresh && _unread[key] == kind) return;_tokens[key] = '$_epoch-${(++_sequence).toRadixString(36)}';+ _receivedAt[key] = at ?? DateTime.now();+ _messages.remove(key);+ if (message != null && message.trim().isNotEmpty) {+ _messages[key] = message.length > 600+ ? message.substring(0, 600)+ : message;+ }// Re-inserted, not updated in place: an agent that moved is the newest// again, which is what makes the first key the oldest for the eviction// below. `notif_push` on the dial does exactly this — it lifts an existing@@ -221,6 +239,8 @@ class AgentUnread extends ChangeNotifier {..[key] = kind;while (_unread.length > capacity) {_tokens.remove(_unread.keys.first);+ _messages.remove(_unread.keys.first);+ _receivedAt.remove(_unread.keys.first);_unread.remove(_unread.keys.first);}notifyListeners();@@ -232,6 +252,8 @@ class AgentUnread extends ChangeNotifier {final key = keyFor(machineId, agentId);if (_unread.remove(key) == null) return;_tokens.remove(key);+ _messages.remove(key);+ _receivedAt.remove(key);notifyListeners();}@@ -243,6 +265,8 @@ class AgentUnread extends ChangeNotifier {if (_unread.isEmpty) return;_unread.clear();_tokens.clear();+ _messages.clear();+ _receivedAt.clear();notifyListeners();}}diff --git a/desktop/lib/screens/swarm_screen.dart b/desktop/lib/screens/swarm_screen.dartindex 530d0204c..76e076193 100644--- a/desktop/lib/screens/swarm_screen.dart+++ b/desktop/lib/screens/swarm_screen.dart@@ -1868,6 +1868,7 @@ class _SwarmScreenState extends State<SwarmScreen> {],'attention': _attention,if (_native) 'statusMenuEntries': statusMenuEntries(app),+ if (_native) 'statusMenuWorkingEntries': statusMenuWorkingEntries(app),// The fallback bell and the macOS menu use the same unread ledger.'unread': _unread,'sessionsOpen': _harnessesVisible,@@ -5690,12 +5691,17 @@ class _SwarmScreenState extends State<SwarmScreen> {if (!statusMenuReceiptIsCurrent(app, receipt)) return;final machineId = receipt['machineId'] as String;final agentId = receipt['agentId'] as String;- final row = statusMenuEntries(app)+ final working = receipt['unread'] == false;+ final candidates = working+ ? statusMenuWorkingEntries(app)+ : statusMenuEntries(app);+ final row = candidates.where((row) => row['machineId'] == machineId && row['agentId'] == agentId,).firstOrNull;if (row == null || row['unavailable'] != null) return;+ if (working && row['sessionId'] != receipt['sessionId']) return;// Keep the tab shown in the menu even if the active tab changed while it// was open. If that view moved or closed, resolve the session's new home.final destination =diff --git a/desktop/lib/state/app_state.dart b/desktop/lib/state/app_state.dartindex cf1e4ba66..653979001 100644--- a/desktop/lib/state/app_state.dart+++ b/desktop/lib/state/app_state.dart@@ -7748,7 +7748,12 @@ class AppNotifier extends ChangeNotifier {}};- void _raiseAlert(MachineState machine, String agentId, AlertKind kind) {+ void _raiseAlert(+ MachineState machine,+ String agentId,+ AlertKind kind, {+ String? message,+ }) {// Nothing at all for the agent on screen in front of you. A sound, a banner// and a count are three ways of saying "look over here", and all three are// noise about the pane you are already in.@@ -7766,7 +7771,13 @@ class AppNotifier extends ChangeNotifier {final agent = machine.agents.where((a) => a.id == agentId).firstOrNull;// Before the banner and outside its switch: the mark is what the window can// still say when somebody has turned the interrupting halves off.- agentUnread.mark(machine.machine.machineId, agentId, kind, fresh: true);+ agentUnread.mark(+ machine.machine.machineId,+ agentId,+ kind,+ fresh: true,+ message: message,+ );alerts.play(kind);final alert = AgentAlert(machineId: machine.machine.machineId,@@ -7888,6 +7899,11 @@ class AppNotifier extends ChangeNotifier {bool agentIsProcessing(String machineId, String agentId) =>machineStates[machineId]?.processingAgentIds.contains(agentId) ?? false;+ /// Unknown after attaching to a turn already under way; do not invent an+ /// elapsed time from the last heartbeat or the last time its pane was opened.+ DateTime? agentWorkingSince(String machineId, String agentId) =>+ harnessStats.turnStartedAt(_turnActivityKey(machineId, agentId));+// ── blocked agents ────────────────────────────────────────────────────────/// The question this agent stopped on, if it is waiting for one.@@ -13391,9 +13407,9 @@ class AppNotifier extends ChangeNotifier {// is a turn already under way, and counting one would report an agent// this app merely reconnected to as work somebody just asked for.if (type == 'turn_started') {- harnessStats.onTurnStarted(- _turnActivityKey(machine.machine.machineId, agentId),- );+ final key = _turnActivityKey(machine.machine.machineId, agentId);+ changed = harnessStats.turnStartedAt(key) == null || changed;+ harnessStats.onTurnStarted(key);}} else {final sessionId = _eventSessionId(event, payload);@@ -13402,7 +13418,8 @@ class AppNotifier extends ChangeNotifier {}}// Renew the watchdog on every heartbeat, but redraw only when the- // agent first becomes busy. Expiry and turn end publish separately.+ // agent becomes busy or its start time becomes known. Expiry and turn+ // end publish separately.if (!changed) return;break;case 'turn_summary':@@ -13417,7 +13434,14 @@ class AppNotifier extends ChangeNotifier {while (_deliveredNotifications.length > 512) {_deliveredNotifications.remove(_deliveredNotifications.first);}- _raiseAlert(machine, agentId, AlertKind.done);+ _raiseAlert(+ machine,+ agentId,+ AlertKind.done,+ message:+ previewText(payload['recap'], limit: 600) ??+ previewText(payload['text'], limit: 600),+ );break;case 'turn_ended':final agentId = _eventAgentId(machine, event, payload);diff --git a/desktop/lib/state/status_menu.dart b/desktop/lib/state/status_menu.dartindex 8dc31f4bb..a7dbb0511 100644--- a/desktop/lib/state/status_menu.dart+++ b/desktop/lib/state/status_menu.dart@@ -1,14 +1,82 @@+import '../notify/alert_sounds.dart';import 'app_state.dart';+import 'harness_activity.dart';+import 'harness_sessions.dart';import 'notification_inbox.dart';+import 'session_preview.dart';import 'swarm.dart';import 'workspace_status.dart';-/// The macOS menu lists unread harnesses in tab order, then Other sessions.+/// One notification section, questions first and newest first within each kind./// Receipts travel with each row so a menu left open cannot clear newer news.List<Map<String, Object?>> statusMenuEntries(AppNotifier app) {final notifications = notificationInbox(app);if (notifications.isEmpty) return [];final names = workspaceTabNames(app);+ final owners = _owners(app);+ final rows = [+ for (final notification in notifications)+ {+ ..._entry(app, notification),+ ..._location(+ app,+ notification.machineId,+ notification.agentId,+ owners,+ names,+ ),+ },+ ];+ final positions = {for (final (index, row) in rows.indexed) row: index};+ rows.sort((a, b) {+ final priority = (a['priority'] as int).compareTo(b['priority'] as int);+ if (priority != 0) return priority;+ final time = (b['receivedAt'] as int? ?? 0).compareTo(+ a['receivedAt'] as int? ?? 0,+ );+ return time != 0 ? time : positions[a]!.compareTo(positions[b]!);+ });+ return rows;+}++/// The same live activity as the tabs. Idle shells and waiting questions are+/// not working. A session with unread news gets its one row above instead.+List<Map<String, Object?>> statusMenuWorkingEntries(AppNotifier app) {+ final names = workspaceTabNames(app);+ final owners = _owners(app);+ final unread = notificationInbox(app).map((row) => row.id).toSet();+ return [+ for (final session in harnessSessions(app))+ if (!unread.contains('${session.machineId}/${session.agent.id}') &&+ harnessActivity(app, session.machineId, session.agent.id) ==+ HarnessActivity.working)+ {+ 'machineId': session.machineId,+ 'agentId': session.agent.id,+ 'sessionId': session.agent.sessionId,+ 'title': session.agent.displayName,+ 'unread': false,+ 'label': 'Working',+ 'startedAt': app+ .agentWorkingSince(session.machineId, session.agent.id)+ ?.millisecondsSinceEpoch,+ 'unavailable': harnessSessionUnavailable(+ session.machine,+ session.agent,+ ),+ ..._location(app, session.machineId, session.agent.id, owners, names),+ 'readToken': app.agentUnread.readTokenFor(+ session.machineId,+ session.agent.id,+ ),+ 'questionId': app+ .questionFor(session.machineId, session.agent.id)+ ?.requestId,+ },+ ];+}++Map<(String, String), Swarm> _owners(AppNotifier app) {final owners = <(String, String), Swarm>{};// A shared session counts once. Prefer its active tab, otherwise the first// tab containing it. Include tabs hidden by the machine profile, too.@@ -21,21 +89,29 @@ List<Map<String, Object?>> statusMenuEntries(AppNotifier app) {}}}- final groups = <String?, List<Map<String, Object?>>>{};- for (final notification in notifications) {- final tab = owners[(notification.machineId, notification.agentId)];- (groups[tab?.id] ??= []).add({- ..._entry(app, notification),- 'tabId': tab?.id,- 'tabName': tab == null ? 'Other sessions' : names[tab.id],- });- }- return [for (final tab in app.swarms) ...?groups[tab.id], ...?groups[null]];+ return owners;+}++Map<String, Object?> _location(+ AppNotifier app,+ String machineId,+ String agentId,+ Map<(String, String), Swarm> owners,+ Map<String, String> names,+) {+ final tab = owners[(machineId, agentId)];+ return {+ 'tabId': tab?.id,+ 'tabName': tab == null ? 'Other sessions' : names[tab.id],+ 'machineName':+ app.stateOf(machineId)?.machine.displayName ?? 'Unavailable machine',+ };}Map<String, Object?> _entry(AppNotifier app, InboxNotification notification) {final machineId = notification.machineId;final agentId = notification.agentId;+ final question = app.questionFor(machineId, agentId);return {'machineId': machineId,'agentId': agentId,@@ -43,12 +119,34 @@ Map<String, Object?> _entry(AppNotifier app, InboxNotification notification) {'detail': notification.detail,'unavailable': notification.unavailable,'unread': true,- 'label': notification.label,+ 'label': notification.kind == AlertKind.done+ ? 'Ready for review'+ : notification.label,+ 'priority': notification.kind == AlertKind.needsYou+ ? 0+ : notification.kind == AlertKind.failed+ ? 1+ : 2,+ 'message': statusMenuMessage(+ question?.prompt ?? app.agentUnread.messageFor(machineId, agentId),+ ),+ 'receivedAt':+ (question?.since ?? app.agentUnread.receivedAtFor(machineId, agentId))+ ?.millisecondsSinceEpoch,'readToken': app.agentUnread.readTokenFor(machineId, agentId),- 'questionId': app.questionFor(machineId, agentId)?.requestId,+ 'questionId': question?.requestId,};}+/// A plain-text excerpt, never rendered markdown or terminal control bytes.+String? statusMenuMessage(Object? value) => previewText(value, limit: 600)+ ?.replaceAllMapped(RegExp(r'\[([^\]]+)\]\([^\)]+\)'), (match) => match[1]!)+ .replaceAll(RegExp(r'(^|\n)\s{0,3}(#{1,6}\s+|[-*]\s+|>\s*)'), ' ')+ .replaceAllMapped(RegExp(r'(\*\*|__)([^\n]+?)\1'), (match) => match[2]!)+ .replaceAll(RegExp(r'`'), '')+ .replaceAll(RegExp(r'\s+'), ' ')+ .trim();+bool statusMenuReceiptIsCurrent(AppNotifier app, Map receipt) {final machineId = receipt['machineId'], agentId = receipt['agentId'];return machineId is String &&@@ -58,7 +156,7 @@ bool statusMenuReceiptIsCurrent(AppNotifier app, Map receipt) {receipt['questionId'] == app.questionFor(machineId, agentId)?.requestId;}-/// Dismiss the exact notifications displayed when Clear All was selected.+/// Dismiss the exact opening snapshot when Mark all read was selected./// A pending question remains pending; a newer notification remains unread.void clearStatusMenuNotifications(AppNotifier app, List receipts) {for (final receipt in receipts.whereType<Map>()) {diff --git a/desktop/lib/stats/harness_stats.dart b/desktop/lib/stats/harness_stats.dartindex 5454a3221..a73aaa581 100644--- a/desktop/lib/stats/harness_stats.dart+++ b/desktop/lib/stats/harness_stats.dart@@ -94,6 +94,8 @@ class HarnessStats extends ChangeNotifier {/// later turn into a multi-day "turn".final Map<String, DateTime> _live = {};+ DateTime? turnStartedAt(String key) => _live[key];+Timer? _writeTimer;bool _disposed = false;diff --git a/desktop/macos/Runner/HarnessStatusMenu.swift b/desktop/macos/Runner/HarnessStatusMenu.swiftindex 80ea6815b..bd506947c 100644--- a/desktop/macos/Runner/HarnessStatusMenu.swift+++ b/desktop/macos/Runner/HarnessStatusMenu.swift@@ -7,6 +7,12 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {let menu = NSMenu(title: "Harness")private(set) var statusItem: NSStatusItem?private var entries: [[String: Any]] = []+ private var working: [[String: Any]] = []+ private var workingExpanded = false+ private var workingItems: [NSMenuItem] = []+ private var keymap: HarnessNativeKeymap?+ private var keyContext = "workspace"+ private var menuKeys: Any?private var enabled = falseprivate var workspaceAvailable = falseprivate var tracking = false@@ -32,6 +38,7 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {}deinit {+ if let menuKeys { NSEvent.removeMonitor(menuKeys) }if let statusItem { NSStatusBar.system.removeStatusItem(statusItem) }}@@ -40,11 +47,15 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {let nextAvailable = state["statusMenuEntries"] != nillet nextEntries = (state["statusMenuEntries"] as? [[String: Any]] ?? []).filter { $0["unread"] as? Bool == true }+ let nextWorking = state["statusMenuWorkingEntries"] as? [[String: Any]] ?? []guard dirty || enabled != nextEnabled || workspaceAvailable != nextAvailable ||- !NSArray(array: entries).isEqual(to: nextEntries) else { return }+ !NSArray(array: entries).isEqual(to: nextEntries) ||+ !NSArray(array: working).isEqual(to: nextWorking) else { return }enabled = nextEnabledworkspaceAvailable = nextAvailableentries = nextEntries+ working = nextAvailable ? nextWorking : []+ if !workspaceAvailable { workingExpanded = false }let count = entries.countstatusItem?.button?.image = Self.badgeImage(logo: NSImage(named: "HarnessStatusIcon"),count: workspaceAvailable ? count : nil)@@ -58,72 +69,125 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {}func menuNeedsUpdate(_ menu: NSMenu) {- if !tracking && dirty { rebuild() }+ if menu === self.menu && !tracking && dirty { rebuild() }}func menuWillOpen(_ menu: NSMenu) {+ guard menu === self.menu else { return }if dirty { rebuild() }+ refreshTimes()tracking = true+ if menuKeys == nil {+ menuKeys = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { [weak self] event in+ guard let self, self.tracking, let item = self.menu.highlightedItem,+ self.handleWorkingKey(event, item: item) else { return event }+ return nil+ }+ }}func menuDidClose(_ menu: NSMenu) {+ guard menu === self.menu else { return }tracking = false+ if let menuKeys { NSEvent.removeMonitor(menuKeys); self.menuKeys = nil }// AppKit dispatches the selected item after closing. Rebuild on next open// or update so its receipt remains the snapshot the person selected.}+ /// AppKit normally closes a menu on Return. This disclosure stays open for+ /// keyboard users too; all other keys keep native menu navigation.+ func handleWorkingKey(_ event: NSEvent, item: NSMenuItem) -> Bool {+ guard item.menu === menu, item.identifier?.rawValue == "toggleWorking", item.isEnabled,+ event.modifierFlags.intersection([.command, .control, .option]).isEmpty,+ let row = item.view as? HarnessStatusMenuRow else { return false }+ switch event.keyCode {+ case 36, 76, 49: return row.accessibilityPerformPress() // Return, keypad Enter, Space+ case 124: // Right opens; Left closes an already expanded section.+ if !workingExpanded { _ = row.accessibilityPerformPress() }+ return true+ case 123 where workingExpanded: return row.accessibilityPerformPress()+ default: return false+ }+ }++ func menu(_ menu: NSMenu, willHighlight item: NSMenuItem?) {+ for row in menu.items {+ (row.view as? HarnessStatusMenuRow)?.highlighted = row === item+ }+ }++ func updateKeymap(_ map: HarnessNativeKeymap, context: String) {+ keymap = map+ keyContext = context+ map.applyMenuKeys(to: menu, context: context)+ }++ private func refreshTimes() {+ for item in menu.items {+ (item.view as? HarnessStatusMenuRow)?.refreshTime()+ for child in item.submenu?.items ?? [] {+ (child.view as? HarnessStatusMenuRow)?.refreshTime()+ }+ }+ }+private func rebuild() {dirty = falsemenu.removeAllItems()+ workingItems.removeAll()+ if working.isEmpty { workingExpanded = false }+ menu.minimumWidth = 360+ let clear = add("Mark all read", "clearStatusNotifications", enabled: enabled && !entries.isEmpty)+ clear.representedObject = entries+ clear.view = HarnessStatusMenuRow(item: clear, heading: "Notifications (\(entries.count))")if entries.isEmpty {let empty = NSMenuItem(title: workspaceAvailable ? "No unread notifications" : "Open Harness to get started",action: nil, keyEquivalent: "")empty.isEnabled = falsemenu.addItem(empty)} else {- // Dart supplies tab order and newest-first rows within each tab. IDs keep- // identically named tabs separate; nil holds sessions outside open tabs.- var groups: [String?] = []- var grouped: [String?: [[String: Any]]] = [:]- for entry in entries {- let group = entry["tabId"] as? String- if grouped[group] == nil { groups.append(group) }- grouped[group, default: []].append(entry)+ for entry in entries.prefix(5) { addSession(entry, to: menu) }+ if entries.count > 5 {+ add("View all \(entries.count) notifications…", "notificationInbox", enabled: enabled)+ }+ }+ if workspaceAvailable {+ menu.addItem(.separator())+ let toggle = add("Working (\(working.count))", "toggleWorking", enabled: !working.isEmpty)+ toggle.view = HarnessStatusMenuRow(item: toggle, expanded: workingExpanded)+ for entry in working.prefix(5) {+ workingItems.append(addSession(entry, to: menu))}- for (index, group) in groups.enumerated() {- if index > 0 { menu.addItem(.separator()) }- let rows = grouped[group]!- let first = rows[0]- let title = first["tabName"] as? String ?? "Other sessions"- let heading = NSMenuItem(title: compact(title), action: nil, keyEquivalent: "")- heading.isEnabled = false- heading.toolTip = title- menu.addItem(heading)- for entry in rows {- let title = entry["title"] as? String ?? "Unavailable harness"- let row = add(compact(title), "openStatusHarness", enabled: enabled && entry["unavailable"] as? String == nil)- row.representedObject = entry- row.indentationLevel = 1- row.state = .on- row.onStateImage = Self.unreadDot- let status = entry["unavailable"] as? String ?? entry["label"] as? String- row.toolTip = [title, entry["detail"] as? String, status].compactMap { $0 }.joined(separator: " · ")- row.setAccessibilityLabel([title, status, "Unread"]- .compactMap { $0 }.joined(separator: ", "))- }+ if working.count > 5 {+ let more = add("More working sessions (\(working.count - 5))", "moreWorking", enabled: enabled)+ let submenu = NSMenu(title: "Working")+ submenu.autoenablesItems = false+ submenu.delegate = self+ for entry in working.dropFirst(5) { addSession(entry, to: submenu) }+ more.submenu = submenu+ workingItems.append(more)}+ for item in workingItems { item.isHidden = !workingExpanded }}menu.addItem(.separator())- add("New Harness…", "newAgent", enabled: enabled)- add("Open Harness…", "addAgent", enabled: enabled)- let clear = add("Clear All Notifications", "clearStatusNotifications",- enabled: enabled && !entries.isEmpty)- clear.representedObject = entries+ add("New Harness…", HarnessKeymapMenu.actionPrefix + "newAgent", enabled: enabled)+ add("Open Harness…", HarnessKeymapMenu.actionPrefix + "addAgent", enabled: enabled)menu.addItem(.separator())add("Show Harness", "openWindow")- add("Settings…", "settings", enabled: enabled)- menu.addItem(.separator())- add("Quit Harness", "quit")+ add("Quit", "quit")+ keymap?.applyMenuKeys(to: menu, context: keyContext)+ }++ @discardableResult private func addSession(_ entry: [String: Any], to destination: NSMenu) -> NSMenuItem {+ let title = entry["title"] as? String ?? "Unavailable harness"+ let item = NSMenuItem(title: compact(title), action: #selector(selected(_:)), keyEquivalent: "")+ item.identifier = NSUserInterfaceItemIdentifier("openStatusHarness")+ item.target = self+ item.isEnabled = enabled && entry["unavailable"] as? String == nil+ item.representedObject = entry+ item.view = HarnessStatusMenuRow(item: item, entry: entry)+ destination.addItem(item)+ return item}@discardableResult private func add(_ title: String, _ action: String, enabled: Bool = true) -> NSMenuItem {@@ -136,13 +200,24 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {}@objc private func selected(_ item: NSMenuItem) {- guard item.isEnabled, let action = item.identifier?.rawValue else { return }+ guard item.isEnabled, let identifier = item.identifier?.rawValue else { return }+ let action = identifier.hasPrefix(HarnessKeymapMenu.actionPrefix)+ ? String(identifier.dropFirst(HarnessKeymapMenu.actionPrefix.count)) : identifierswitch action {case "openWindow": showWindow()case "quit": NSApp.terminate(nil)+ case "toggleWorking":+ workingExpanded.toggle()+ (item.view as? HarnessStatusMenuRow)?.expanded = workingExpanded+ // Expand the already displayed snapshot. New arrivals and their receipts+ // stay deferred until the next opening, just like the notification rows.+ for row in workingItems { row.isHidden = !workingExpanded }+ menu.update()case "openStatusHarness":guard enabled, let receipt = item.representedObject as? [String: Any],- entries.contains(where: { sameReceipt($0, receipt) && $0["unavailable"] as? String == nil }) else { return }+ (receipt["unread"] as? Bool == true ? entries : working).contains(where: {+ sameReceipt($0, receipt) && $0["unavailable"] as? String == nil+ }) else { return }// Dart opens the destination before revealing the window, so activating// the previously selected tab cannot acknowledge the wrong notification.emit(action, receipt)@@ -157,7 +232,7 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {}private func sameReceipt(_ current: [String: Any], _ displayed: [String: Any]) -> Bool {- ["machineId", "agentId", "readToken", "questionId"].allSatisfy {+ ["machineId", "agentId", "sessionId", "readToken", "questionId"].allSatisfy {current[$0] as? String == displayed[$0] as? String}}@@ -209,9 +284,181 @@ final class HarnessStatusMenu: NSObject, NSMenuDelegate {return image}- private static let unreadDot = NSImage(size: NSSize(width: 12, height: 12), flipped: false) { _ in- NSColor.systemBlue.setFill()- NSBezierPath(ovalIn: NSRect(x: 3, y: 3, width: 6, height: 6)).fill()+}++/// Rich rows keep NSMenuItem's native keyboard/type-select actions, just like+/// the History menu. All clicks and VoiceOver presses use the same receipt.+private final class HarnessStatusMenuRow: NSView {+ private weak var item: NSMenuItem?+ private let entry: [String: Any]?+ private let heading: String?+ private var time = ""+ var highlighted = false { didSet { needsDisplay = true } }+ var expanded: Bool? { didSet { updateAccessibility(); needsDisplay = true } }+ override var isFlipped: Bool { true }++ init(item: NSMenuItem, entry: [String: Any]? = nil, heading: String? = nil, expanded: Bool? = nil) {+ self.item = item+ self.entry = entry+ self.heading = heading+ self.expanded = expanded+ let unread = entry?["unread"] as? Bool == true+ let message = entry?["message"] as? String ?? ""+ let measured = (message as NSString).boundingRect(with: NSSize(width: 316, height: 1000),+ options: [.usesLineFragmentOrigin], attributes: [.font: NSFont.systemFont(ofSize: 13)])+ let messageHeight = message.isEmpty ? 0 : min(32, ceil(measured.height)) + 2+ let height: CGFloat = entry == nil ? 32 : unread ? 64 + messageHeight : 44+ super.init(frame: NSRect(x: 0, y: 0, width: 360, height: height))+ autoresizingMask = [.width]+ setAccessibilityElement(true)+ setAccessibilityRole(.menuItem)+ refreshTime()+ }++ required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") }++ override func viewDidMoveToWindow() {+ super.viewDidMoveToWindow()+ highlighted = false+ refreshTime()+ }++ func refreshTime() {+ time = ""+ if let entry {+ let unread = entry["unread"] as? Bool == true+ if let stamp = entry[unread ? "receivedAt" : "startedAt"] as? NSNumber {+ let age = max(0, Int(Date().timeIntervalSince1970 - stamp.doubleValue / 1000))+ if age < 60 { time = unread ? "now" : "\(age)s" }+ else if age < 3600 { time = "\(age / 60)m" }+ else if age < 86400 { time = "\(age / 3600)h" }+ else { time = "\(age / 86400)d" }+ if unread && age >= 60 { time += " ago" }+ }+ }+ updateAccessibility()+ needsDisplay = true+ }++ private var context: String {+ guard let entry else { return "" }+ return [entry["tabName"] as? String, entry["machineName"] as? String,+ entry["unavailable"] as? String].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: " · ")+ }++ private func updateAccessibility() {+ guard let item else { return }+ let text: String+ if let entry {+ text = [entry["title"] as? String, entry["label"] as? String, entry["message"] as? String,+ context, time, entry["unread"] as? Bool == true ? "Unread" : nil]+ .compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: ", ")+ toolTip = [text, entry["detail"] as? String].compactMap { $0 }.joined(separator: " · ")+ } else if let expanded {+ text = "\(item.title), \(expanded ? "expanded" : "collapsed")"+ setAccessibilityExpanded(expanded)+ toolTip = expanded ? "Hide working sessions" : "Show working sessions"+ } else {+ text = "\(heading ?? "Notifications"), Mark all read"+ toolTip = "Mark these notifications as read. Pending questions stay unanswered."+ }+ setAccessibilityLabel(text)+ setAccessibilityEnabled(item.isEnabled)+ item.setAccessibilityLabel(text)+ item.toolTip = toolTip+ }++ private var clearRect: NSRect {+ NSRect(x: bounds.width - 110, y: 2, width: 102, height: bounds.height - 4)+ }++ override func draw(_ dirtyRect: NSRect) {+ guard let item else { return }+ let selected = highlighted && item.isEnabled+ if selected {+ NSColor.selectedContentBackgroundColor.setFill()+ NSBezierPath(roundedRect: heading == nil ? bounds.insetBy(dx: 4, dy: 2) : clearRect,+ xRadius: 5, yRadius: 5).fill()+ }+ let primary: NSColor = !item.isEnabled ? .disabledControlTextColor+ : selected ? .selectedMenuItemTextColor : .labelColor+ let secondary: NSColor = !item.isEnabled ? .disabledControlTextColor+ : selected ? .selectedMenuItemTextColor : .secondaryLabelColor+ if let heading {+ text(heading, x: 16, y: 8, width: clearRect.minX - 20, height: 18,+ size: 12, weight: .medium, color: .secondaryLabelColor)+ text("Mark all read", x: clearRect.minX, y: 8, width: clearRect.width, height: 18,+ size: 12, color: !item.isEnabled ? .disabledControlTextColor+ : selected ? .selectedMenuItemTextColor : .labelColor, alignment: .center)+ return+ }+ if let expanded {+ if item.isEnabled, let icon = HarnessControlSymbols.image(expanded ? "chevron.down" : "chevron.right")?.copy() as? NSImage {+ icon.lockFocus()+ primary.set()+ NSRect(origin: .zero, size: icon.size).fill(using: .sourceAtop)+ icon.unlockFocus()+ let scale = min(16 / icon.size.width, 16 / icon.size.height)+ let size = NSSize(width: icon.size.width * scale, height: icon.size.height * scale)+ icon.draw(in: NSRect(x: 11 + (16 - size.width) / 2, y: 8 + (16 - size.height) / 2,+ width: size.width, height: size.height),+ from: .zero, operation: .sourceOver, fraction: 1, respectFlipped: true, hints: nil)+ }+ text(item.title, x: 34, y: 7, width: bounds.width - 50, height: 20, color: primary)+ return+ }+ guard let entry else { return }+ let unread = entry["unread"] as? Bool == true+ let message = entry["message"] as? String ?? ""+ if unread {+ (selected ? NSColor.selectedMenuItemTextColor : NSColor.systemBlue).setFill()+ NSBezierPath(ovalIn: NSRect(x: 13, y: 13, width: 6, height: 6)).fill()+ }+ text(entry["title"] as? String ?? item.title, x: 28, y: 6,+ width: bounds.width - 111, height: 19, weight: unread ? .semibold : .regular, color: primary)+ text(time, x: bounds.width - 78, y: 8, width: 62, height: 17,+ size: 12, color: secondary, alignment: .right)+ if unread {+ text(entry["label"] as? String ?? "", x: 28, y: 26, width: bounds.width - 44,+ height: 17, size: 12, color: secondary)+ if !message.isEmpty {+ text(message, x: 28, y: 43, width: bounds.width - 44, height: 32, color: primary, multiline: true)+ }+ }+ text(context, x: 28, y: bounds.height - 20, width: bounds.width - 44, height: 17,+ size: 12, color: secondary)+ }++ private func text(_ value: String, x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat,+ size: CGFloat = 13, weight: NSFont.Weight = .regular, color: NSColor,+ alignment: NSTextAlignment = .left, multiline: Bool = false) {+ let paragraph = NSMutableParagraphStyle()+ paragraph.alignment = alignment+ paragraph.lineBreakMode = multiline ? .byWordWrapping : .byTruncatingTail+ let attributes: [NSAttributedString.Key: Any] = [+ .font: NSFont.systemFont(ofSize: size, weight: weight), .foregroundColor: color, .paragraphStyle: paragraph,+ ]+ (value as NSString).draw(with: NSRect(x: x, y: y, width: max(0, width), height: height),+ options: [.usesLineFragmentOrigin, .truncatesLastVisibleLine], attributes: attributes)+ }++ override func resetCursorRects() {+ if item?.isEnabled == true { addCursorRect(heading == nil ? bounds : clearRect, cursor: .pointingHand) }+ }++ override func mouseUp(with event: NSEvent) {+ let point = convert(event.locationInWindow, from: nil)+ guard (heading == nil ? bounds : clearRect).contains(point) else { return }+ activate()+ }++ override func accessibilityPerformPress() -> Bool { activate() }+ @discardableResult private func activate() -> Bool {+ guard let item, item.isEnabled, let menu = item.menu else { return false }+ let index = menu.index(of: item)+ guard index >= 0 else { return false }+ if expanded == nil { menu.cancelTracking() }+ menu.performActionForItem(at: index)return true}}diff --git a/desktop/macos/Runner/SwarmTitlebar.swift b/desktop/macos/Runner/SwarmTitlebar.swiftindex b668cc8aa..b6119fb26 100644--- a/desktop/macos/Runner/SwarmTitlebar.swift+++ b/desktop/macos/Runner/SwarmTitlebar.swift@@ -190,6 +190,7 @@ final class SwarmTitlebar: NSObject, NSMenuItemValidation, NSMenuDelegate {private func syncMenuKeys() {guard let keymap, let main = NSApp.mainMenu else { return }keymap.applyMenuKeys(to: main, context: flutterKeyContext)+ statusMenu?.updateKeymap(keymap, context: flutterKeyContext)}private func configure(palette: [String: Any]? = nil) {diff --git a/desktop/test/agent_unread_test.dart b/desktop/test/agent_unread_test.dartindex 88a045067..498c3ed1d 100644--- a/desktop/test/agent_unread_test.dart+++ b/desktop/test/agent_unread_test.dart@@ -42,6 +42,32 @@ void main() {expect(unread.count, 1);});+ test('preview and time belong to the unread receipt and leave with it', () {+ final first = DateTime(2026, 9, 30, 12);+ unread.mark('m1', 'a1', AlertKind.done, message: 'First result', at: first);+ unread.mark(+ 'm1',+ 'a1',+ AlertKind.done,+ message: 'Duplicate',+ at: first.add(const Duration(minutes: 1)),+ );+ expect(unread.messageFor('m1', 'a1'), 'First result');+ expect(unread.receivedAtFor('m1', 'a1'), first);+ unread.mark('m1', 'a1', AlertKind.done, fresh: true);+ expect(+ unread.messageFor('m1', 'a1'),+ isNull,+ reason: 'Never reuse a previous turn\'s message',+ );+ unread.clear('m1', 'a1');+ expect(unread.receivedAtFor('m1', 'a1'), isNull);+ unread.mark('m1', 'a1', AlertKind.done, message: 'New result');+ unread.clearAll();+ expect(unread.messageFor('m1', 'a1'), isNull);+ expect(unread.receivedAtFor('m1', 'a1'), isNull);+ });+test('the newest kind wins — a finished agent that then asks is waiting', () {// Which is the mark worth showing: one of these is work you can read later, the other is work// that has stopped until somebody answers.@@ -105,12 +131,15 @@ void main() {test('evicts the oldest entry only at the desktop capacity', () {for (var i = 0; i < AgentUnread.capacity + 3; i++) {- unread.mark('m1', 'a$i', AlertKind.done);+ unread.mark('m1', 'a$i', AlertKind.done, message: 'Result $i');}expect(unread.count, AgentUnread.capacity);expect(unread.kindFor('m1', 'a0'), isNull, reason: 'the oldest went');expect(unread.kindFor('m1', 'a2'), isNull);+ expect(unread.messageFor('m1', 'a2'), isNull);+ expect(unread.receivedAtFor('m1', 'a2'), isNull);+ expect(unread.messageFor('m1', 'a3'), 'Result 3');expect(unread.kindFor('m1', 'a3'), isNotNull, reason: 'the rest stayed');});diff --git a/desktop/test/status_menu_test.dart b/desktop/test/status_menu_test.dartindex c4ad93390..4bac6efbc 100644--- a/desktop/test/status_menu_test.dart+++ b/desktop/test/status_menu_test.dart@@ -45,53 +45,61 @@ void main() {);});- test('groups by tab identity across machines, in tab order with Other sessions last', () {- final app = createApp(connected: true);- addTearDown(app.dispose);- const remote = Machine(- machineId: 'remote',- name: 'Remote host',- authMode: MachineAuthMode.remote,- );- app.machineStates['remote'] = MachineState(remote)- ..agents = [Agent(id: 'a0', name: 'Remote result', engine: 'codex')];- final first = app.activeSwarm;- app.renameSwarm(first.id, 'Design');- first.panes.addAll([- TerminalPane(id: 1, machineId: 'm', agentId: 'a0'),- TerminalPane(id: 2, machineId: 'remote', agentId: 'a0'),- ]);- app.newSwarm(name: 'Design');- final second = app.activeSwarm;- second.panes.add(TerminalPane(id: 3, machineId: 'm', agentId: 'a1'));- app.agentUnread.mark('m', 'a0', AlertKind.done);- app.agentUnread.mark('m', 'a1', AlertKind.done);- app.agentUnread.mark('remote', 'a0', AlertKind.done);- app.agentUnread.mark('m', 'a9', AlertKind.done);+ test(+ 'keeps tab destinations as context while sorting notifications across tabs',+ () {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ const remote = Machine(+ machineId: 'remote',+ name: 'Remote host',+ authMode: MachineAuthMode.remote,+ );+ app.machineStates['remote'] = MachineState(remote)+ ..agents = [Agent(id: 'a0', name: 'Remote result', engine: 'codex')];+ final first = app.activeSwarm;+ app.renameSwarm(first.id, 'Design');+ first.panes.addAll([+ TerminalPane(id: 1, machineId: 'm', agentId: 'a0'),+ TerminalPane(id: 2, machineId: 'remote', agentId: 'a0'),+ ]);+ app.newSwarm(name: 'Design');+ final second = app.activeSwarm;+ second.panes.add(TerminalPane(id: 3, machineId: 'm', agentId: 'a1'));+ app.agentUnread.mark('m', 'a0', AlertKind.done);+ app.agentUnread.mark('m', 'a1', AlertKind.done);+ app.agentUnread.mark('remote', 'a0', AlertKind.done);+ app.agentUnread.mark('m', 'a9', AlertKind.done);- final rows = statusMenuEntries(app);- expect(rows.map((r) => (r['machineId'], r['agentId'])), [- ('remote', 'a0'),- ('m', 'a0'),- ('m', 'a1'),- ('m', 'a9'),- ]);- expect(rows.map((r) => r['tabId']), [first.id, first.id, second.id, null]);- expect(rows.map((r) => r['tabName']), [- 'Design',- 'Design',- 'Design',- 'Other sessions',- ]);+ final rows = statusMenuEntries(app);+ expect(rows.map((r) => (r['machineId'], r['agentId'])), [+ ('m', 'a9'),+ ('remote', 'a0'),+ ('m', 'a1'),+ ('m', 'a0'),+ ]);+ expect(rows.map((r) => r['tabId']), [+ null,+ first.id,+ second.id,+ first.id,+ ]);+ expect(rows.map((r) => r['tabName']), [+ 'Other sessions',+ 'Design',+ 'Design',+ 'Design',+ ]);- app.renameSwarm(second.id, 'Review');- expect(statusMenuEntries(app)[2]['tabName'], 'Review');- expect(- statusMenuReceiptIsCurrent(app, rows[2]),- isTrue,- reason: 'renaming a tab does not replace its notification',- );- });+ app.renameSwarm(second.id, 'Review');+ expect(statusMenuEntries(app)[2]['tabName'], 'Review');+ expect(+ statusMenuReceiptIsCurrent(app, rows[2]),+ isTrue,+ reason: 'renaming a tab does not replace its notification',+ );+ },+ );test('a shared session counts once and follows tab membership and display names',@@ -123,7 +131,7 @@ void main() {);test(- 'machine profiles keep unread sessions grouped under their hidden tabs',+ 'machine profiles preserve unread sessions and their hidden tab context',() {final app = createApp(connected: true);addTearDown(app.dispose);@@ -142,6 +150,149 @@ void main() {},);+ test(+ 'previews use the notified recap, with current questions first',+ () async {+ final app = createApp(connected: true)..watchedAgents = () => const [];+ addTearDown(app.dispose);+ final machine = app.stateOf('m')!;+ machine.blockedAgents['a1'] = waitingQuestion(+ 'a1',+ prompt: 'Keep the shell running?',+ );+ app.agentUnread.mark('m', 'a1', AlertKind.needsYou);+ app.agentUnread.mark('m', 'a2', AlertKind.failed);+ await app.handleEventForTest('m', {+ 'type': 'turn_summary',+ 'agentId': 'a0',+ 'payload': {+ 'notification': {'id': 'result-one', 'kind': 'done'},+ 'recap': '**Fixed reconnects** in `api_client.dart`.',+ 'text': 'A much longer explanation.',+ },+ });+ var rows = statusMenuEntries(app);+ expect(rows.map((r) => r['agentId']), ['a1', 'a2', 'a0']);+ expect(rows.first['message'], 'Keep the shell running?');+ expect(+ rows.first['receivedAt'],+ machine.blockedAgents['a1']!.since.millisecondsSinceEpoch,+ );+ final done = rows.last;+ expect(done['message'], 'Fixed reconnects in api_client.dart.');+ expect(done['label'], 'Ready for review');+ expect(done['receivedAt'], isA<int>());+ await app.handleEventForTest('m', {+ 'type': 'turn_started',+ 'agentId': 'a0',+ 'payload': {'userMessage': 'Now fix something else'},+ });+ await app.handleEventForTest('m', {+ 'type': 'text_delta',+ 'agentId': 'a0',+ 'payload': {'content': 'Working on something else'},+ });+ rows = statusMenuEntries(app);+ expect(+ rows.last['message'],+ done['message'],+ reason: 'Live text cannot replace unread news',+ );+ expect(rows.last['readToken'], done['readToken']);+ await app.handleEventForTest('m', {+ 'type': 'turn_summary',+ 'agentId': 'a0',+ 'payload': {+ 'notification': {'id': 'result-two', 'kind': 'done'},+ 'text': 'The second fix is ready.',+ },+ });+ expect(+ statusMenuEntries(app).last['message'],+ 'The second fix is ready.',+ );+ expect(statusMenuReceiptIsCurrent(app, done), isFalse);+ await app.handleEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'a0',+ 'payload': <String, dynamic>{},+ });+ },+ );++ test('working is unique, known, active work, never idle or unread sessions', () async {+ final app = createApp(connected: true);+ addTearDown(app.dispose);+ final machine = app.stateOf('m')!;+ for (var i = 0; i < 7; i++) {+ app.rememberOpenedHarness('m', 'a$i');+ }+ machine.processingAgentIds.addAll([+ 'a0',+ 'a1',+ 'a3',+ 'a4',+ 'a5',+ 'a6',+ 'a7',+ ]);+ machine.blockedAgents['a1'] = waitingQuestion('a1');+ app.agentUnread.mark('m', 'a3', AlertKind.done);+ machine.agents[4] = machine.agents[4].copyWith(status: 'stopped');+ machine.agents[5] = const Agent(+ id: 'a5',+ name: 'Shell',+ engine: 'terminal',+ terminalAvailable: true,+ );+ final pane = TerminalPane(id: 12, machineId: 'm', agentId: 'a0');+ app.activeSwarm.panes.add(pane);+ app.newSwarm(name: 'Build');+ app.activeSwarm.panes.add(pane);+ var working = statusMenuWorkingEntries(app);+ expect(working.map((r) => r['agentId']), ['a0', 'a6']);+ expect(working.first['tabId'], app.activeSwarmId);+ expect(+ working.first['startedAt'],+ isNull,+ reason: 'No invented elapsed time on reconnect',+ );+ expect(working.every((r) => r['unread'] == false), isTrue);+ expect(statusMenuEntries(app).map((r) => r['agentId']), ['a1', 'a3']);+ var changes = 0;+ app.addListener(() => changes++);+ await app.handleEventForTest('m', {+ 'type': 'turn_started',+ 'agentId': 'a0',+ 'payload': <String, dynamic>{},+ });+ working = statusMenuWorkingEntries(app);+ expect(working.first['startedAt'], isA<int>());+ expect(+ changes,+ greaterThan(0),+ reason:+ 'A known start reaches the menu even after an earlier busy heartbeat',+ );+ await app.handleEventForTest('m', {+ 'type': 'turn_heartbeat',+ 'agentId': 'a0',+ 'payload': <String, dynamic>{},+ });+ expect(+ statusMenuWorkingEntries(app).first['startedAt'],+ working.first['startedAt'],+ );+ await app.handleEventForTest('m', {+ 'type': 'turn_ended',+ 'agentId': 'a0',+ 'payload': <String, dynamic>{},+ });+ expect(statusMenuWorkingEntries(app).map((r) => r['agentId']), ['a6']);+ machine.connectionStatus = ConnectionStatus.disconnected;+ expect(statusMenuWorkingEntries(app), isEmpty);+ });+test('clear acknowledges displayed news, never answers or clears newer news',() {@@ -286,6 +437,28 @@ void main() {expect(rows(), isEmpty);expect(updates.last['unread'], 0);+ // The working section uses the same destinations without acknowledging+ // any newer question or completion that arrived after the menu opened.+ app.stateOf('m')!.processingAgentIds.add('a8');+ app.renameSwarm(originalTab, 'Working review');+ await tester.pump();+ final work = (updates.last['statusMenuWorkingEntries'] as List)+ .cast<Map>()+ .single;+ expect(work['agentId'], 'a8');+ expect(work['unread'], isFalse);+ expect(updates.last['unread'], 0);+ await select('openStatusHarness', work);+ expect(app.focusedPane, same(result));+ expect(app.allPanes.where((p) => p.agentId == 'a8'), hasLength(1));+ app.agentUnread.mark('m', 'a8', AlertKind.done, fresh: true);+ await tester.pump();+ await select('openStatusHarness', work);+ expect(app.agentUnread.kindFor('m', 'a8'), AlertKind.done);+ expect(updates.last['statusMenuWorkingEntries'], isEmpty);+ await select('clearStatusNotifications', {'receipts': rows()});+ app.stateOf('m')!.processingAgentIds.remove('a8');+// Open Harness from an empty notification menu still opens the normal// picker, ready for typing, and selecting a session reuses its pane.await select('addAgent', {});@@ -306,6 +479,7 @@ void main() {await tester.pumpWidget(const SizedBox());expect(updates.last['enabled'], isFalse);expect(updates.last['statusMenuEntries'], isNull);+ expect(updates.last['statusMenuWorkingEntries'], isNull);app.dispose();},);diff --git a/desktop/tool/check_swarm_titlebar.sh b/desktop/tool/check_swarm_titlebar.shindex 1d26c5842..7da55e29b 100644--- a/desktop/tool/check_swarm_titlebar.sh+++ b/desktop/tool/check_swarm_titlebar.sh@@ -33,6 +33,9 @@ fiif [[ "${2:-}" == "--status-menu" ]]; thencheck_source="$desktop_dir/tool/status_menu_checks.swift"fi+if [[ "${2:-}" == "--status-menu-preview" ]]; then+ check_source="$desktop_dir/tool/status_menu_preview.swift"+ficat "$desktop_dir/macos/Runner/HarnessKeymap.swift" > "$check_dir/main.swift"# The title bar shares menu ordering with the window. Include that production# helper without booting the Flutter window or its account/runtime services.diff --git a/desktop/tool/status_menu_checks.swift b/desktop/tool/status_menu_checks.swiftindex 69f0dfcb1..ac65e381c 100644--- a/desktop/tool/status_menu_checks.swift+++ b/desktop/tool/status_menu_checks.swift@@ -24,7 +24,9 @@ private func fixture(_ agent: String, project: String = "autonomous-harness",unread: Bool = true, token: String = "first", offline: Bool = false) -> [String: Any] {var row: [String: Any] = ["machineId": machine,"agentId": agent, "title": agent, "tabName": tabId == nil ? "Other sessions" : tabName, "unread": unread,- "detail": "Office Mac · \(project)"]+ "detail": "Office Mac · \(project)", "machineName": "Office Mac",+ "message": "The reconnect fix is ready for you to try.",+ "receivedAt": Date().timeIntervalSince1970 * 1000 - 120_000]row["tabId"] = tabIdif unread { row["readToken"] = token; row["label"] = "Finished" }if offline { row["unavailable"] = "Offline" }@@ -33,7 +35,8 @@ private func fixture(_ agent: String, project: String = "autonomous-harness",private extension HarnessStatusMenu {func item(_ action: String) -> NSMenuItem {- menu.items.first { $0.identifier?.rawValue == action }!+ menu.items.first { $0.identifier?.rawValue == action ||+ $0.identifier?.rawValue == HarnessKeymapMenu.actionPrefix + action }!}func row(_ agent: String) -> NSMenuItem {menu.items.first { ($0.representedObject as? [String: Any])?["agentId"] as? String == agent }!@@ -51,19 +54,25 @@ do {fixture("DeepSeek model", project: "No Project", unread: false),fixture("Math addition inquiry", project: "No Project", tabId: nil, offline: true)]status.update(["enabled": true, "statusMenuEntries": rows])- try check(status.menu.items.filter { $0.state == .on }.count == 2, "Unread rows have dots")- try check(status.row("General chat conversation").onStateImage != nil, "A blue dot replaces the checkmark")- try check(status.menu.items.contains { $0.title == "Build" && !$0.isEnabled } &&- status.menu.items.contains { $0.title == "Other sessions" && !$0.isEnabled }, "Tabs and other sessions use native section headings")+ try check(status.menu.items.filter { $0.identifier?.rawValue == "openStatusHarness" }.count == 2,+ "One row per unread session")+ try check((status.row("General chat conversation").view?.frame.height ?? 0) > 64 &&+ (status.row("General chat conversation").view?.frame.height ?? 0) <= 98 &&+ status.row("General chat conversation").view?.accessibilityLabel()?.contains("reconnect fix") == true,+ "Multiline rows expose the actual message to accessibility")+ try check(status.item("clearStatusNotifications").view?.accessibilityLabel()?.contains("Notifications (2)") == true &&+ !status.menu.items.contains { $0.title == "Build" }, "One notification section replaces tab headings")try check(!status.row("Math addition inquiry").isEnabled, "Offline conversations stay visible but disabled")try check(status.row("Math addition inquiry").toolTip?.contains("Offline") == true, "Unavailable state is explained")try check(!status.menu.items.contains { $0.title == "DeepSeek model" }, "Read conversations are absent from the notification menu")status.click(status.row("General chat conversation"))try check(emitted.last?.0 == "openStatusHarness" && reveals == 0, "Navigation is sent before revealing the window")status.click(status.item("newAgent"))- status.click(status.item("settings"))- try check(emitted.suffix(2).map { $0.0 } == ["newAgent", "settings"] && reveals == 2,- "New Harness and Settings reveal the window and reuse existing actions")+ status.click(status.item("addAgent"))+ try check(emitted.suffix(2).map { $0.0 } == ["newAgent", "addAgent"] && reveals == 2,+ "New and Open Harness reveal the window and reuse existing actions")+ try check(!status.menu.items.contains { $0.identifier?.rawValue == "settings" } &&+ status.item("quit").title == "Quit", "Settings is absent and the exit command is simply Quit")status.menuWillOpen(status.menu)let selected = status.row("General chat conversation")@@ -72,7 +81,7 @@ do {rows.append(fixture("New result", project: "website", tabId: "tab-website", tabName: "Website"))status.update(["enabled": true, "statusMenuEntries": rows])try check(status.row("General chat conversation") === selected &&- !status.menu.items.contains { $0.title == "Website" }, "Arrivals do not move open-menu rows")+ !status.menu.items.contains { $0.title == "New result" }, "Arrivals do not move open-menu rows")status.click(selected)try check(emitted.count == before, "A replaced notification cannot dispatch an old click")status.click(status.item("clearStatusNotifications"))@@ -82,7 +91,7 @@ do {cleared?.first?["readToken"] as? String == "first", "Clear sends only displayed receipts, never new arrivals")status.menuDidClose(status.menu)status.menuNeedsUpdate(status.menu)- try check(status.menu.items.contains { $0.title == "Website" }, "The next opening shows new arrivals")+ try check(status.menu.items.contains { $0.title == "New result" }, "The next opening shows new arrivals")status.menuWillOpen(status.menu)let originalLocation = status.row("General chat conversation")@@ -93,18 +102,20 @@ do {let originalReceipt = emitted.last?.1 as? [String: Any]try check(emitted.last?.0 == "openStatusHarness" && originalReceipt?["tabId"] as? String == "tab-build","A current notification retains its displayed destination when tabs change")- try check(!status.menu.items.contains { $0.title == "Review" }, "Tab changes do not move open-menu rows")+ try check(status.row("General chat conversation").toolTip?.contains("Build") == true,+ "Tab context does not move under the pointer")status.menuDidClose(status.menu)status.menuNeedsUpdate(status.menu)- try check(status.menu.items.contains { $0.title == "Review" }, "The next opening reflects the new tab group")+ try check(status.row("General chat conversation").toolTip?.contains("Review") == true,+ "The next opening reflects the new tab context")status.update(["enabled": false, "statusMenuEntries": rows])- try check(!status.item("newAgent").isEnabled && !status.item("addAgent").isEnabled && !status.item("settings").isEnabled &&+ try check(!status.item("newAgent").isEnabled && !status.item("addAgent").isEnabled &&!status.item("clearStatusNotifications").isEnabled, "A modal disables workspace actions")status.click(status.item("openWindow"))try check(reveals == 3, "Show Harness remains available during a modal")status.update(["enabled": true, "statusMenuEntries": []])- try check(status.menu.items.first?.title == "No unread notifications" &&+ try check(status.menu.items.contains { $0.title == "No unread notifications" } &&!status.item("clearStatusNotifications").isEnabled, "An empty inbox is explicit and cannot be cleared")let open = status.menu.items.first { $0.title == "Open Harness…" }!status.click(open)@@ -128,12 +139,13 @@ do {try check(logo != nil, "The menu bar template loads from the Harness artwork")logo?.setName("HarnessStatusIcon")let indicator = HarnessStatusMenu(showWindow: {}, emit: { _, _ in })- indicator.update(["enabled": true, "statusMenuEntries": rows])+ indicator.update(["enabled": true, "statusMenuEntries": rows,+ "statusMenuWorkingEntries": [fixture("Running", unread: false)]])try check(indicator.statusItem?.button?.title == "" &&indicator.statusItem?.button?.image?.accessibilityDescription == "3 unread" &&indicator.statusItem?.button?.image?.isTemplate == true &&indicator.statusItem?.button?.accessibilityValue() as? String == "3 unread",- "The monochrome Harness template carries the count badge without a separate text label")+ "The badge counts notifications only, never working sessions")let unreadPixels = renderedStatusPixels(indicator.statusItem!.button!.image!)indicator.update(["enabled": true, "statusMenuEntries": []])try check(indicator.statusItem?.button?.image?.accessibilityDescription == "0 unread" &&@@ -162,14 +174,66 @@ do {fixture("Review result", tabId: "tab-two", tabName: "Work"),fixture("Background result", tabId: nil),]])- let headings = status.menu.items.filter { !$0.isEnabled && !$0.isSeparatorItem && $0.representedObject == nil }- try check(headings.map { $0.title } == ["Work", "Work", "Other sessions"],- "Tab IDs keep equal names separate, combine projects and machines, and preserve section order")- try check(status.menu.index(of: status.row("Website result")) < status.menu.index(of: headings[1]) &&- status.menu.index(of: status.row("Review result")) > status.menu.index(of: headings[1]),- "Each row stays inside its tab's section")+ try check(status.menu.items.filter { $0.identifier?.rawValue == "openStatusHarness" }.map { $0.title } ==+ ["API result", "Website result", "Review result", "Background result"],+ "Notifications retain Dart's urgency and time order across tabs")try check(status.row("Website result").toolTip?.contains("website") == true,"Project context remains available in the row tooltip")++ var working = (0..<7).map { fixture("Working \($0)", unread: false) }+ status.update(["enabled": true, "statusMenuEntries": (0..<8).map { fixture("News \($0)") },+ "statusMenuWorkingEntries": working])+ try check(status.menu.items.filter { $0.identifier?.rawValue == "openStatusHarness" && !$0.isHidden }.count == 5 &&+ status.item("notificationInbox").title == "View all 8 notifications…",+ "The glance is bounded, with a route to every unread notification")+ let toggle = status.item("toggleWorking")+ try check(toggle.title == "Working (7)" && status.row("Working 0").isHidden,+ "Working starts collapsed")+ status.menuWillOpen(status.menu)+ try check(toggle.view?.accessibilityPerformPress() == true && !status.row("Working 0").isHidden,+ "Disclosure expands inline through the accessible native control")+ let overflow = status.item("moreWorking")+ try check(overflow.submenu?.items.count == 2, "Additional work stays available without flooding the overview")+ func keyEvent(_ code: UInt16) -> NSEvent {+ NSEvent.keyEvent(with: .keyDown, location: .zero, modifierFlags: [], timestamp: 0,+ windowNumber: 0, context: nil, characters: "", charactersIgnoringModifiers: "", isARepeat: false, keyCode: code)!+ }+ try check(status.handleWorkingKey(keyEvent(123), item: toggle) && status.row("Working 0").isHidden &&+ status.handleWorkingKey(keyEvent(124), item: toggle) && !status.row("Working 0").isHidden,+ "Left and Right collapse and expand the working section")+ try check(!status.handleWorkingKey(keyEvent(125), item: toggle), "Arrow navigation remains AppKit's")+ let workingRow = status.row("Working 0")+ let beforeWorking = emitted.count+ working.removeFirst()+ status.update(["enabled": true, "statusMenuEntries": [fixture("Newer news")], "statusMenuWorkingEntries": working])+ status.click(workingRow)+ try check(emitted.count == beforeWorking, "A session that stopped working cannot dispatch a stale working click")+ _ = toggle.view?.accessibilityPerformPress()+ _ = toggle.view?.accessibilityPerformPress()+ try check(status.menu.items.contains { $0.title == "News 0" } &&+ !status.menu.items.contains { $0.title == "Newer news" },+ "Toggling Working preserves the open notification snapshot")+ let currentWorking = status.row("Working 1")+ try check(currentWorking.view?.accessibilityPerformPress() == true && emitted.last?.0 == "openStatusHarness" &&+ (emitted.last?.1 as? [String: Any])?["unread"] as? Bool == false,+ "Working rows navigate with a distinct non-notification receipt")+ status.menuDidClose(status.menu)+ status.menuNeedsUpdate(status.menu)+ status.update([:])+ try check(!status.menu.items.contains { $0.identifier?.rawValue == "toggleWorking" },+ "Sign-out removes working data as well as unread messages")+ let bindings: [[String: Any]] = [+ ["keys": ["cmd+shift+k"], "command": "agent.open", "hint": "⇧⌘K", "repeatable": false, "menuAction": "addAgent"],+ ]+ let map = HarnessNativeKeymap(["version": 1, "contexts": ["workspace": bindings, "terminal": [], "picker": [], "project": []]])!+ status.updateKeymap(map, context: "workspace")+ status.update(["enabled": true, "statusMenuEntries": []])+ try check(status.item("addAgent").keyEquivalent == "k" &&+ status.item("addAgent").keyEquivalentModifierMask == [.command, .shift] &&+ status.item("newAgent").keyEquivalent.isEmpty,+ "Footer shortcuts follow remapping and unbinding, including after a rebuild")+ status.click(status.item("addAgent"))+ try check(emitted.last?.0 == "addAgent", "Keymap identifiers preserve the existing Open Harness action")print("Harness status menu passed \(checks) checks")} catch {fputs("Harness status menu failed: \(error)\n", stderr)diff --git a/desktop/tool/status_menu_preview.swift b/desktop/tool/status_menu_preview.swiftnew file mode 100644index 000000000..8a434e655--- /dev/null+++ b/desktop/tool/status_menu_preview.swift@@ -0,0 +1,87 @@+// Actual AppKit menu views with synthetic data, independent of account state.+// HARNESS_STATUS_MENU_PREVIEW_DIR=/tmp/harness-menu bash tool/check_swarm_titlebar.sh <flutter> --status-menu-preview+let app = NSApplication.shared+app.setActivationPolicy(.accessory)+app.finishLaunching()+let output = URL(fileURLWithPath: ProcessInfo.processInfo.environment["HARNESS_STATUS_MENU_PREVIEW_DIR"] ?? "/tmp/harness-menu")+try FileManager.default.createDirectory(at: output, withIntermediateDirectories: true)+let timestamp = Date().timeIntervalSince1970 * 1000+func news(_ id: String, _ title: String, _ message: String, tab: String, machine: String, age: Double,+ label: String = "Ready for review") -> [String: Any] {+ ["machineId": machine, "agentId": id, "title": title, "message": message,+ "tabId": tab, "tabName": tab, "machineName": machine, "unread": true,+ "label": label, "readToken": id, "receivedAt": timestamp - age * 1000]+}+let notifications = [+ news("hn", "hn", "Keep the shell running after detach?", tab: "TUI", machine: "M2", age: 10, label: "Needs input"),+ news("reconnect", "Fix session reconnects", "The reconnect fix is ready for you to try.", tab: "Desktop", machine: "office", age: 120),+ news("menu", "Notification menu", "Message previews and the Working section are ready for review.", tab: "Desktop", machine: "office", age: 300),+]+let working: [[String: Any]] = [+ ["machineId": "office", "agentId": "shortcuts", "title": "Refactor shortcuts", "tabName": "Desktop", "machineName": "office", "unread": false, "startedAt": timestamp - 120_000],+ ["machineId": "M2", "agentId": "resize", "title": "Fix Linux resize", "tabName": "Desktop", "machineName": "M2", "unread": false, "startedAt": timestamp - 480_000],+ ["machineId": "office", "agentId": "tests", "title": "Run integration tests", "tabName": "Tests", "machineName": "office", "unread": false, "startedAt": timestamp - 30_000],+]+let bindings: [[String: Any]] = [+ ["keys": ["cmd+n"], "command": "agent.new", "hint": "⌘N", "repeatable": false, "menuAction": "newAgent"],+ ["keys": ["cmd+o"], "command": "agent.open", "hint": "⌘O", "repeatable": false, "menuAction": "addAgent"],+]+let map = HarnessNativeKeymap(["version": 1, "contexts": ["workspace": bindings, "terminal": [], "picker": [], "project": []]])!++func render(_ name: String, dark: Bool, entries: [[String: Any]], work: [[String: Any]], expanded: Bool = false,+ highlight: Bool = false) {+ app.appearance = NSAppearance(named: dark ? .darkAqua : .aqua)+ let status = HarnessStatusMenu(installStatusItem: false, showWindow: {}, emit: { _, _ in })+ status.menu.appearance = app.appearance+ status.updateKeymap(map, context: "workspace")+ status.update(["enabled": true, "statusMenuEntries": entries, "statusMenuWorkingEntries": work])+ if expanded, let toggle = status.menu.items.first(where: { $0.identifier?.rawValue == "toggleWorking" }) {+ _ = toggle.view?.accessibilityPerformPress()+ }+ var captured = false+ let timer = Timer(timeInterval: 0.2, repeats: false) { _ in+ if highlight {+ status.menu(status.menu, willHighlight: status.menu.items.first { $0.identifier?.rawValue == "openStatusHarness" })+ }+ let activeWindow = status.menu.items.compactMap { $0.view?.window }.first+ for window in app.windows where window === activeWindow {+ guard let view = window.contentView, window.frame.height > 100,+ let bitmap = view.bitmapImageRepForCachingDisplay(in: view.bounds) else { continue }+ view.cacheDisplay(in: view.bounds, to: bitmap)+ let composed = NSBitmapImageRep(bitmapDataPlanes: nil,+ pixelsWide: bitmap.pixelsWide, pixelsHigh: bitmap.pixelsHigh,+ bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false,+ colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)!+ composed.size = view.bounds.size+ NSGraphicsContext.saveGraphicsState()+ NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: composed)+ // View caching has no window-server backdrop. Composite on a neutral+ // surface instead of presenting a fake transparency/blur screenshot.+ NSColor(calibratedWhite: dark ? 0.16 : 0.94, alpha: 1).setFill()+ view.bounds.fill()+ let cached = NSImage(size: view.bounds.size)+ cached.addRepresentation(bitmap)+ cached.draw(in: view.bounds, from: .zero, operation: .sourceOver, fraction: 1)+ NSGraphicsContext.restoreGraphicsState()+ try! composed.representation(using: .png, properties: [:])!.write(to: output.appendingPathComponent(name + ".png"))+ print("Rendered \(name): \(view.bounds.size)")+ captured = true+ break+ }+ status.menu.cancelTracking()+ }+ RunLoop.main.add(timer, forMode: .common)+ status.menu.popUp(positioning: nil, at: NSPoint(x: 100, y: 800), in: nil)+ precondition(captured, "The menu must produce an actual native view")+}++render("notification-overview-light", dark: false, entries: notifications, work: working)+render("notification-overview-dark", dark: true, entries: notifications, work: working)+render("notification-overview-working", dark: false, entries: notifications, work: working, expanded: true)+render("notification-overview-empty", dark: false, entries: [], work: [])+let long = news("long", String(repeating: "Long session title ", count: 6),+ String(repeating: "A lengthy question that must wrap and then truncate without covering its tab and machine context. ", count: 8),+ tab: "Desktop with an unusually long tab name", machine: "Office Mac with a long machine name", age: 180, label: "Needs input")+var offline = notifications[1]+offline["unavailable"] = "Offline"+render("notification-overview-long", dark: false, entries: [long, offline], work: working, highlight: true)